instance_id
stringlengths 30
32
| text
stringlengths 7.7k
116k
| repo
stringclasses 1
value | base_commit
stringlengths 40
40
| problem_statement
stringlengths 127
5.13k
| hints_text
stringclasses 20
values | created_at
timestamp[us] | patch
stringlengths 767
94.8k
| test_patch
stringlengths 527
58.5k
| version
stringclasses 1
value | FAIL_TO_PASS
stringclasses 1
value | PASS_TO_PASS
stringclasses 1
value | environment_setup_commit
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|---|
corona-warn-app__cwa-server-277 | You will be provided with a partial code base and an issue statement explaining a problem to resolve.
<issue>
Switch application*.properties files to Yaml
Let's switch over to YAML for better readability.
Affected files:
common/persistence/src/test/resources/application.properties
services/submission/src/main/resources/application.properties
services/submission/src/test/resources/application.properties
services/distribution/src/main/resources/application.properties
services/distribution/src/test/resources/application.properties
services/submission/src/main/resources/application-dev.properties
services/distribution/src/main/resources/application-dev.properties
services/submission/src/main/resources/application-cloud.properties
services/distribution/src/main/resources/application-cloud.properties
services/distribution/src/main/resources/application-testdata.properties
</issue>
<code>
[start of README.md]
1 <h1 align="center">
2 Corona-Warn-App Server
3 </h1>
4
5 <p align="center">
6 <a href="https://github.com/corona-warn-app/cwa-server/commits/" title="Last Commit"><img src="https://img.shields.io/github/last-commit/corona-warn-app/cwa-server?style=flat"></a>
7 <a href="https://github.com/corona-warn-app/cwa-server/issues" title="Open Issues"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat"></a>
8 <a href="https://circleci.com/gh/corona-warn-app/cwa-server" title="Build Status"><img src="https://circleci.com/gh/corona-warn-app/cwa-server.svg?style=shield&circle-token=4ab059989d10709df19eb4b98ab7c121a25e981a"></a>
9 <a href="https://sonarcloud.io/dashboard?id=corona-warn-app_cwa-server" title="Quality Gate"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=alert_status"></a>
10 <a href="https://sonarcloud.io/component_measures?id=corona-warn-app_cwa-server&metric=Coverage&view=list" title="Coverage"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=coverage"></a>
11 <a href="https://github.com/corona-warn-app/cwa-server/blob/master/LICENSE" title="License"><img src="https://img.shields.io/badge/License-Apache%202.0-green.svg?style=flat"></a>
12 </p>
13
14 <p align="center">
15 <a href="#development">Development</a> •
16 <a href="#service-apis">Service APIs</a> •
17 <a href="#documentation">Documentation</a> •
18 <a href="#support-and-feedback">Support</a> •
19 <a href="#how-to-contribute">Contribute</a> •
20 <a href="#contributors">Contributors</a> •
21 <a href="#repositories">Repositories</a> •
22 <a href="#licensing">Licensing</a>
23 </p>
24
25 The goal of this project is to develop the official Corona-Warn-App for Germany based on the exposure notification API from [Apple](https://www.apple.com/covid19/contacttracing/) and [Google](https://www.google.com/covid19/exposurenotifications/). The apps (for both iOS and Android) use Bluetooth technology to exchange anonymous encrypted data with other mobile phones (on which the app is also installed) in the vicinity of an app user's phone. The data is stored locally on each user's device, preventing authorities or other parties from accessing or controlling the data. This repository contains the **implementation of the server for encryption keys** for the Corona-Warn-App. This implementation is still a **work in progress**, and the code it contains is currently alpha-quality code.
26
27 In this documentation, Corona-Warn-App services are also referred to as CWA services.
28
29 ## Architecture Overview
30
31 You can find the architecture overview [here](/docs/architecture-overview.md), which will give you
32 a good starting point in how the backend services interact with other services, and what purpose
33 they serve.
34
35 ## Development
36
37 After you've checked out this repository, you can run the application in one of the following ways:
38
39 * As a [Docker](https://www.docker.com/)-based deployment on your local machine. You can run either:
40 * Single components using the respective Dockerfile or
41 * The full backend using the Docker Compose (which is considered the most convenient way)
42 * As a [Maven](https://maven.apache.org)-based build on your local machine.
43 If you want to develop something in a single component, this approach is preferable.
44
45 ### Docker-Based Deployment
46
47 If you want to use Docker-based deployment, you need to install Docker on your local machine. For more information about downloading and installing Docker, see the [official Docker documentation](https://docs.docker.com/get-docker/).
48
49 #### Running the Full CWA Backend Using Docker Compose
50
51 For your convenience, a full setup including the generation of test data has been prepared using [Docker Compose](https://docs.docker.com/compose/reference/overview/). To build the backend services, run ```docker-compose build``` in the repository's root directory. A default configuration file can be found under ```.env```in the root folder of the repository. The default values for the local Postgres and Zenko Cloudserver should be changed in this file before docker-compose is run.
52
53 Once the services are built, you can start the whole backend using ```docker-compose up```.
54 The distribution service runs once and then finishes. If you want to trigger additional distribution runs, run ```docker-compose run distribution```.
55
56 The docker-compose contains the following services:
57
58 Service | Description | Endpoint and Default Credentials
59 --------------|-------------|-----------
60 submission | The Corona-Warn-App submission service | http://localhost:8000
61 distribution | The Corona-Warn-App distribution service | NO ENDPOINT
62 postgres | A [postgres] database installation | postgres:8001 <br> Username: postgres <br> Password: postgres
63 pgadmin | A [pgadmin](https://www.pgadmin.org/) installation for the postgres database | http://localhost:8002 <br> Username: [email protected] <br> Password: password
64 cloudserver | [Zenko CloudServer] is a S3-compliant object store | http://localhost:8003/ <br> Access key: accessKey1 <br> Secret key: verySecretKey1
65
66 ##### Known Limitation
67
68 The docker-compose runs into a timing issue in some cases when the create-bucket target runs before the objectstore is available. The mitigation is easy: after running ```docker-compose up``` wait until all components are initialized and running. Afterwards, trigger the ```create-bucket``` service manually by running ```docker-compose run create-bucket```. If you want to trigger distribution runs, run ```docker-compose run distribution```. The timing issue will be fixed in a future release.
69
70 #### Running Single CWA Services Using Docker
71
72 If you would like to build and run a single CWA service, it's considered easiest to run them in a Docker environment. You can do this using the script provided in the respective CWA service directory. The Docker script first builds the CWA service and then creates an image for the runtime, which means that there are no additional dependencies for you to install.
73
74 To build and run the distribution service, run the following command:
75
76 ```bash
77 ./services/distribution/build_and_run.sh
78 ```
79
80 To build and run the submission service, run the following command:
81
82 ```bash
83 ./services/submission/build_and_run.sh
84 ```
85
86 The submission service is available on [localhost:8080](http://localhost:8080 ).
87
88 ### Maven-Based Build
89
90 If you want to actively develop in one of the CWA services, the Maven-based runtime is most suitable.
91 To prepare your machine to run the CWA project locally, we recommend that you first ensure that you've installed the following:
92
93 * Minimum JDK Version 11: [OpenJDK](https://openjdk.java.net/) / [SapMachine](https://sap.github.io/SapMachine/)
94 * [Maven 3.6](https://maven.apache.org/)
95 * [Postgres]
96 * [Zenko CloudServer]
97
98 #### Configure
99
100 After you made sure that the specified dependencies are running, configure them in the respective configuration files.
101
102 * Configure the Postgres connection in the [submission config](./services/submission/src/main/resources/application.properties) and in the [distribution config](./services/distribution/src/main/resources/application.properties)
103 * Configure the S3 compatible object storage in the [distribution config](./services/distribution/src/main/resources/application.properties)
104 * Configure the certificate and private key for the distribution service, the paths need to be prefixed with `file:`
105 * `VAULT_FILESIGNING_SECRET` should be the path to the private key, example available in `<repo-root>/docker-compose-test-secrets/private.pem`
106 * `VAULT_FILESIGNING_CERT` should be the path to the certificate, example available in `<repo-root>/docker-compose-test-secrets/certificate.cert`
107
108 #### Build
109
110 After you've checked out the repository, to build the project, run ```mvn install``` in your base directory.
111
112 #### Run
113
114 Navigate to the service you want to start and run the spring-boot:run target. The configured Postgres and the configured S3 compliant object storage are used as default. When you start the submission service, the endpoint is available on your local port 8080.
115
116 If you want to start the submission service, for example, you start it as follows:
117
118 ```bash
119 cd services/submission/
120 mvn spring-boot:run
121 ```
122
123 #### Debugging
124
125 To enable the `DEBUG` log level, you can run the application using the Spring `dev` profile.
126
127 ```bash
128 mvn spring-boot:run -Dspring-boot.run.profiles=dev
129 ```
130
131 To be able to set breakpoints (e.g. in IntelliJ), it may be necessary to use the ```-Dspring-boot.run.fork=false``` parameter.
132
133 ## Service APIs
134
135 The API that is being exposed by the backend services is documented in an [OpenAPI](https://www.openapis.org/) specification. The specification files are available at the following locations:
136
137 Service | OpenAPI Specification
138 -------------|-------------
139 Submission Service | https://github.com/corona-warn-app/cwa-server/raw/master/services/submission/api_v1.json
140 Distribution Service | https://github.com/corona-warn-app/cwa-server/raw/master/services/distribution/api_v1.json
141
142 ## Documentation
143
144 The full documentation for the Corona-Warn-App can be found in the [cwa-documentation](https://github.com/corona-warn-app/cwa-documentation) repository. The documentation repository contains technical documents, architecture information, and whitepapers related to this implementation.
145
146 ## Support and Feedback
147
148 The following channels are available for discussions, feedback, and support requests:
149
150 | Type | Channel |
151 | ------------------------ | ------------------------------------------------------ |
152 | **General Discussion** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="General Discussion"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/question.svg?style=flat-square"></a> </a> |
153 | **Concept Feedback** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="Open Concept Feedback"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/architecture.svg?style=flat-square"></a> |
154 | **Backend Issue** | <a href="https://github.com/corona-warn-app/cwa-server/issues/new/choose" title="Open Backend Issue"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat-square"></a> |
155 | **Other Requests** | <a href="mailto:[email protected]" title="Email CWA Team"><img src="https://img.shields.io/badge/email-CWA%20team-green?logo=mail.ru&style=flat-square&logoColor=white"></a> |
156
157 ## How to Contribute
158
159 Contribution and feedback are 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.
160
161 ## Contributors
162
163 The German government has asked SAP and Deutsche Telekom to develop the Corona-Warn-App for Germany as open source software. Deutsche Telekom is providing the network and mobile technology and will operate and run the backend for the app in a safe, scalable and stable manner. SAP is responsible for the app development, its framework and the underlying platform. Therefore, development teams of SAP and Deutsche Telekom are contributing to this project. At the same time 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.
164
165 ## Repositories
166
167 The following public repositories are currently available for the Corona-Warn-App:
168
169 | Repository | Description |
170 | ------------------- | --------------------------------------------------------------------- |
171 | [cwa-documentation] | Project overview, general documentation, and white papers |
172 | [cwa-server] | Backend implementation for the Apple/Google exposure notification API|
173
174 [cwa-documentation]: https://github.com/corona-warn-app/cwa-documentation
175 [cwa-server]: https://github.com/corona-warn-app/cwa-server
176 [Postgres]: https://www.postgresql.org/
177 [HSQLDB]: http://hsqldb.org/
178 [Zenko CloudServer]: https://github.com/scality/cloudserver
179
180 ## Licensing
181
182 Copyright (c) 2020 SAP SE or an SAP affiliate company.
183
184 Licensed under the **Apache License, Version 2.0** (the "License"); you may not use this file except in compliance with the License.
185
186 You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0.
187
188 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.
189
[end of README.md]
[start of /dev/null]
1
[end of /dev/null]
[start of README.md]
1 <h1 align="center">
2 Corona-Warn-App Server
3 </h1>
4
5 <p align="center">
6 <a href="https://github.com/corona-warn-app/cwa-server/commits/" title="Last Commit"><img src="https://img.shields.io/github/last-commit/corona-warn-app/cwa-server?style=flat"></a>
7 <a href="https://github.com/corona-warn-app/cwa-server/issues" title="Open Issues"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat"></a>
8 <a href="https://circleci.com/gh/corona-warn-app/cwa-server" title="Build Status"><img src="https://circleci.com/gh/corona-warn-app/cwa-server.svg?style=shield&circle-token=4ab059989d10709df19eb4b98ab7c121a25e981a"></a>
9 <a href="https://sonarcloud.io/dashboard?id=corona-warn-app_cwa-server" title="Quality Gate"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=alert_status"></a>
10 <a href="https://sonarcloud.io/component_measures?id=corona-warn-app_cwa-server&metric=Coverage&view=list" title="Coverage"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=coverage"></a>
11 <a href="https://github.com/corona-warn-app/cwa-server/blob/master/LICENSE" title="License"><img src="https://img.shields.io/badge/License-Apache%202.0-green.svg?style=flat"></a>
12 </p>
13
14 <p align="center">
15 <a href="#development">Development</a> •
16 <a href="#service-apis">Service APIs</a> •
17 <a href="#documentation">Documentation</a> •
18 <a href="#support-and-feedback">Support</a> •
19 <a href="#how-to-contribute">Contribute</a> •
20 <a href="#contributors">Contributors</a> •
21 <a href="#repositories">Repositories</a> •
22 <a href="#licensing">Licensing</a>
23 </p>
24
25 The goal of this project is to develop the official Corona-Warn-App for Germany based on the exposure notification API from [Apple](https://www.apple.com/covid19/contacttracing/) and [Google](https://www.google.com/covid19/exposurenotifications/). The apps (for both iOS and Android) use Bluetooth technology to exchange anonymous encrypted data with other mobile phones (on which the app is also installed) in the vicinity of an app user's phone. The data is stored locally on each user's device, preventing authorities or other parties from accessing or controlling the data. This repository contains the **implementation of the server for encryption keys** for the Corona-Warn-App. This implementation is still a **work in progress**, and the code it contains is currently alpha-quality code.
26
27 In this documentation, Corona-Warn-App services are also referred to as CWA services.
28
29 ## Architecture Overview
30
31 You can find the architecture overview [here](/docs/architecture-overview.md), which will give you
32 a good starting point in how the backend services interact with other services, and what purpose
33 they serve.
34
35 ## Development
36
37 After you've checked out this repository, you can run the application in one of the following ways:
38
39 * As a [Docker](https://www.docker.com/)-based deployment on your local machine. You can run either:
40 * Single components using the respective Dockerfile or
41 * The full backend using the Docker Compose (which is considered the most convenient way)
42 * As a [Maven](https://maven.apache.org)-based build on your local machine.
43 If you want to develop something in a single component, this approach is preferable.
44
45 ### Docker-Based Deployment
46
47 If you want to use Docker-based deployment, you need to install Docker on your local machine. For more information about downloading and installing Docker, see the [official Docker documentation](https://docs.docker.com/get-docker/).
48
49 #### Running the Full CWA Backend Using Docker Compose
50
51 For your convenience, a full setup including the generation of test data has been prepared using [Docker Compose](https://docs.docker.com/compose/reference/overview/). To build the backend services, run ```docker-compose build``` in the repository's root directory. A default configuration file can be found under ```.env```in the root folder of the repository. The default values for the local Postgres and Zenko Cloudserver should be changed in this file before docker-compose is run.
52
53 Once the services are built, you can start the whole backend using ```docker-compose up```.
54 The distribution service runs once and then finishes. If you want to trigger additional distribution runs, run ```docker-compose run distribution```.
55
56 The docker-compose contains the following services:
57
58 Service | Description | Endpoint and Default Credentials
59 --------------|-------------|-----------
60 submission | The Corona-Warn-App submission service | http://localhost:8000
61 distribution | The Corona-Warn-App distribution service | NO ENDPOINT
62 postgres | A [postgres] database installation | postgres:8001 <br> Username: postgres <br> Password: postgres
63 pgadmin | A [pgadmin](https://www.pgadmin.org/) installation for the postgres database | http://localhost:8002 <br> Username: [email protected] <br> Password: password
64 cloudserver | [Zenko CloudServer] is a S3-compliant object store | http://localhost:8003/ <br> Access key: accessKey1 <br> Secret key: verySecretKey1
65
66 ##### Known Limitation
67
68 The docker-compose runs into a timing issue in some cases when the create-bucket target runs before the objectstore is available. The mitigation is easy: after running ```docker-compose up``` wait until all components are initialized and running. Afterwards, trigger the ```create-bucket``` service manually by running ```docker-compose run create-bucket```. If you want to trigger distribution runs, run ```docker-compose run distribution```. The timing issue will be fixed in a future release.
69
70 #### Running Single CWA Services Using Docker
71
72 If you would like to build and run a single CWA service, it's considered easiest to run them in a Docker environment. You can do this using the script provided in the respective CWA service directory. The Docker script first builds the CWA service and then creates an image for the runtime, which means that there are no additional dependencies for you to install.
73
74 To build and run the distribution service, run the following command:
75
76 ```bash
77 ./services/distribution/build_and_run.sh
78 ```
79
80 To build and run the submission service, run the following command:
81
82 ```bash
83 ./services/submission/build_and_run.sh
84 ```
85
86 The submission service is available on [localhost:8080](http://localhost:8080 ).
87
88 ### Maven-Based Build
89
90 If you want to actively develop in one of the CWA services, the Maven-based runtime is most suitable.
91 To prepare your machine to run the CWA project locally, we recommend that you first ensure that you've installed the following:
92
93 * Minimum JDK Version 11: [OpenJDK](https://openjdk.java.net/) / [SapMachine](https://sap.github.io/SapMachine/)
94 * [Maven 3.6](https://maven.apache.org/)
95 * [Postgres]
96 * [Zenko CloudServer]
97
98 #### Configure
99
100 After you made sure that the specified dependencies are running, configure them in the respective configuration files.
101
102 * Configure the Postgres connection in the [submission config](./services/submission/src/main/resources/application.properties) and in the [distribution config](./services/distribution/src/main/resources/application.properties)
103 * Configure the S3 compatible object storage in the [distribution config](./services/distribution/src/main/resources/application.properties)
104 * Configure the certificate and private key for the distribution service, the paths need to be prefixed with `file:`
105 * `VAULT_FILESIGNING_SECRET` should be the path to the private key, example available in `<repo-root>/docker-compose-test-secrets/private.pem`
106 * `VAULT_FILESIGNING_CERT` should be the path to the certificate, example available in `<repo-root>/docker-compose-test-secrets/certificate.cert`
107
108 #### Build
109
110 After you've checked out the repository, to build the project, run ```mvn install``` in your base directory.
111
112 #### Run
113
114 Navigate to the service you want to start and run the spring-boot:run target. The configured Postgres and the configured S3 compliant object storage are used as default. When you start the submission service, the endpoint is available on your local port 8080.
115
116 If you want to start the submission service, for example, you start it as follows:
117
118 ```bash
119 cd services/submission/
120 mvn spring-boot:run
121 ```
122
123 #### Debugging
124
125 To enable the `DEBUG` log level, you can run the application using the Spring `dev` profile.
126
127 ```bash
128 mvn spring-boot:run -Dspring-boot.run.profiles=dev
129 ```
130
131 To be able to set breakpoints (e.g. in IntelliJ), it may be necessary to use the ```-Dspring-boot.run.fork=false``` parameter.
132
133 ## Service APIs
134
135 The API that is being exposed by the backend services is documented in an [OpenAPI](https://www.openapis.org/) specification. The specification files are available at the following locations:
136
137 Service | OpenAPI Specification
138 -------------|-------------
139 Submission Service | https://github.com/corona-warn-app/cwa-server/raw/master/services/submission/api_v1.json
140 Distribution Service | https://github.com/corona-warn-app/cwa-server/raw/master/services/distribution/api_v1.json
141
142 ## Documentation
143
144 The full documentation for the Corona-Warn-App can be found in the [cwa-documentation](https://github.com/corona-warn-app/cwa-documentation) repository. The documentation repository contains technical documents, architecture information, and whitepapers related to this implementation.
145
146 ## Support and Feedback
147
148 The following channels are available for discussions, feedback, and support requests:
149
150 | Type | Channel |
151 | ------------------------ | ------------------------------------------------------ |
152 | **General Discussion** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="General Discussion"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/question.svg?style=flat-square"></a> </a> |
153 | **Concept Feedback** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="Open Concept Feedback"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/architecture.svg?style=flat-square"></a> |
154 | **Backend Issue** | <a href="https://github.com/corona-warn-app/cwa-server/issues/new/choose" title="Open Backend Issue"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat-square"></a> |
155 | **Other Requests** | <a href="mailto:[email protected]" title="Email CWA Team"><img src="https://img.shields.io/badge/email-CWA%20team-green?logo=mail.ru&style=flat-square&logoColor=white"></a> |
156
157 ## How to Contribute
158
159 Contribution and feedback are 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.
160
161 ## Contributors
162
163 The German government has asked SAP and Deutsche Telekom to develop the Corona-Warn-App for Germany as open source software. Deutsche Telekom is providing the network and mobile technology and will operate and run the backend for the app in a safe, scalable and stable manner. SAP is responsible for the app development, its framework and the underlying platform. Therefore, development teams of SAP and Deutsche Telekom are contributing to this project. At the same time 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.
164
165 ## Repositories
166
167 The following public repositories are currently available for the Corona-Warn-App:
168
169 | Repository | Description |
170 | ------------------- | --------------------------------------------------------------------- |
171 | [cwa-documentation] | Project overview, general documentation, and white papers |
172 | [cwa-server] | Backend implementation for the Apple/Google exposure notification API|
173
174 [cwa-documentation]: https://github.com/corona-warn-app/cwa-documentation
175 [cwa-server]: https://github.com/corona-warn-app/cwa-server
176 [Postgres]: https://www.postgresql.org/
177 [HSQLDB]: http://hsqldb.org/
178 [Zenko CloudServer]: https://github.com/scality/cloudserver
179
180 ## Licensing
181
182 Copyright (c) 2020 SAP SE or an SAP affiliate company.
183
184 Licensed under the **Apache License, Version 2.0** (the "License"); you may not use this file except in compliance with the License.
185
186 You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0.
187
188 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.
189
[end of README.md]
[start of services/distribution/src/main/resources/application-cloud.properties]
1 spring.flyway.enabled=true
2 spring.flyway.locations=classpath:db/migration/postgres
3
4 spring.datasource.driver-class-name=org.postgresql.Driver
5 spring.datasource.url=jdbc:postgresql://${POSTGRESQL_SERVICE_HOST}:${POSTGRESQL_SERVICE_PORT}/${POSTGRESQL_DATABASE}
6 spring.datasource.username=${POSTGRESQL_USER}
7 spring.datasource.password=${POSTGRESQL_PASSWORD}
8
9 services.distribution.paths.output=/tmp/distribution
[end of services/distribution/src/main/resources/application-cloud.properties]
[start of services/distribution/src/main/resources/application-dev.properties]
1 logging.level.org.springframework.web=DEBUG
2 logging.level.app.coronawarn=DEBUG
[end of services/distribution/src/main/resources/application-dev.properties]
[start of services/distribution/src/main/resources/application-testdata.properties]
1 services.distribution.testdata.seed=123456
2 services.distribution.testdata.exposures-per-hour=1000
[end of services/distribution/src/main/resources/application-testdata.properties]
[start of services/distribution/src/main/resources/application.properties]
1 logging.level.org.springframework.web=INFO
2 logging.level.app.coronawarn=INFO
3 spring.main.web-application-type=NONE
4
5 services.distribution.retention-days=14
6 services.distribution.output-file-name=index
7 services.distribution.tek-export.file-name=export.bin
8 services.distribution.tek-export.file-header=EK Export v1
9 services.distribution.tek-export.file-header-width=16
10
11 services.distribution.paths.output=out
12 services.distribution.paths.privatekey=${VAULT_FILESIGNING_SECRET}
13 services.distribution.paths.certificate=${VAULT_FILESIGNING_CERT}
14
15 services.distribution.api.version-path=version
16 services.distribution.api.version-v1=v1
17 services.distribution.api.country-path=country
18 services.distribution.api.country-germany=DE
19 services.distribution.api.date-path=date
20 services.distribution.api.hour-path=hour
21 services.distribution.api.diagnosis-keys-path=diagnosis-keys
22 services.distribution.api.parameters-path=configuration
23 services.distribution.api.parameters-exposure-configuration-file-name=exposure_configuration
24 services.distribution.api.parameters-risk-score-classification-file-name=risk_score_classification
25
26 services.distribution.signature.app-bundle-id=de.rki.coronawarnapp
27 services.distribution.signature.android-package=de.rki.coronawarnapp
28 services.distribution.signature.verification-key-id=
29 services.distribution.signature.verification-key-version=
30 services.distribution.signature.algorithm-oid=1.2.840.10045.4.3.2
31 services.distribution.signature.algorithm-name=SHA256withECDSA
32 services.distribution.signature.file-name=export.sig
33 services.distribution.signature.security-provider=BC
34
35 # Configuration for the S3 compatible object storage hosted by Telekom in Germany
36 services.distribution.objectstore.access-key=${CWA_OBJECTSTORE_ACCESSKEY:accessKey1}
37 services.distribution.objectstore.secret-key=${CWA_OBJECTSTORE_SECRETKEY:verySecretKey1}
38 services.distribution.objectstore.endpoint=${CWA_OBJECTSTORE_ENDPOINT:http\://localhost\:8003}
39 services.distribution.objectstore.bucket=${CWA_OBJECTSTORE_BUCKET:cwa}
40 services.distribution.objectstore.port=${CWA_OBJECTSTORE_PORT:8003}
41 services.distribution.objectstore.set-public-read-acl-on-put-object=true
42
43 # Postgres configuration
44 spring.jpa.hibernate.ddl-auto=validate
45
46 spring.flyway.enabled=true
47 spring.flyway.locations=classpath:db/migration/postgres
48
49 spring.datasource.driver-class-name=org.postgresql.Driver
50 spring.datasource.url=jdbc:postgresql://${POSTGRESQL_SERVICE_HOST:localhost}:${POSTGRESQL_SERVICE_PORT:5432}/${POSTGRESQL_DATABASE:cwa}
51 spring.datasource.username=${POSTGRESQL_USER:postgres}
52 spring.datasource.password=${POSTGRESQL_PASSWORD:postgres}
53
[end of services/distribution/src/main/resources/application.properties]
[start of services/submission/src/main/resources/application-cloud.properties]
1 spring.flyway.locations=classpath:db/migration/postgres
2
3 spring.datasource.driver-class-name=org.postgresql.Driver
4 spring.datasource.url=jdbc:postgresql://${POSTGRESQL_SERVICE_HOST}:${POSTGRESQL_SERVICE_PORT}/${POSTGRESQL_DATABASE}
5 spring.datasource.username=${POSTGRESQL_USER}
6 spring.datasource.password=${POSTGRESQL_PASSWORD}
[end of services/submission/src/main/resources/application-cloud.properties]
[start of services/submission/src/main/resources/application-config-test.properties]
1 services.submission.initial_fake_delay_milliseconds=100.0
2 services.submission.fake_delay_moving_average_samples=1.0
3 services.submission.retention-days=10
4 services.submission.payload.max-number-of-keys=1000
[end of services/submission/src/main/resources/application-config-test.properties]
[start of services/submission/src/main/resources/application-dev.properties]
1 logging.level.org.springframework.web=DEBUG
2
[end of services/submission/src/main/resources/application-dev.properties]
[start of services/submission/src/main/resources/application.properties]
1 logging.level.org.springframework.web=INFO
2
3 # The initial value of the moving average for fake request delays.
4 services.submission.initial_fake_delay_milliseconds=10
5 # The number of samples for the calculation of the moving average for fake request delays.
6 services.submission.fake_delay_moving_average_samples=10
7
8 services.submission.retention-days=14
9 services.submission.payload.max-number-of-keys=14
10
11 spring.jpa.hibernate.ddl-auto=validate
12 spring.flyway.enabled=true
13
14 spring.flyway.locations=classpath:db/migration/postgres
15
16 # Postgres configuration
17 spring.datasource.driver-class-name=org.postgresql.Driver
18 spring.datasource.url=jdbc:postgresql://${POSTGRESQL_SERVICE_HOST:localhost}:${POSTGRESQL_SERVICE_PORT:5432}/${POSTGRESQL_DATABASE:cwa}
19 spring.datasource.username=${POSTGRESQL_USER:postgres}
20 spring.datasource.password=${POSTGRESQL_PASSWORD:postgres}
21
[end of services/submission/src/main/resources/application.properties]
</code>
Here is an example of a patch file. It consists of changes to the code base. It specifies the file names, the line numbers of each change, and the removed and added lines. A single patch file can contain changes to multiple files.
<patch>
--- a/file.py
+++ b/file.py
@@ -1,27 +1,35 @@
def euclidean(a, b):
- while b:
- a, b = b, a % b
- return a
+ if b == 0:
+ return a
+ return euclidean(b, a % b)
def bresenham(x0, y0, x1, y1):
points = []
dx = abs(x1 - x0)
dy = abs(y1 - y0)
- sx = 1 if x0 < x1 else -1
- sy = 1 if y0 < y1 else -1
- err = dx - dy
+ x, y = x0, y0
+ sx = -1 if x0 > x1 else 1
+ sy = -1 if y0 > y1 else 1
- while True:
- points.append((x0, y0))
- if x0 == x1 and y0 == y1:
- break
- e2 = 2 * err
- if e2 > -dy:
+ if dx > dy:
+ err = dx / 2.0
+ while x != x1:
+ points.append((x, y))
err -= dy
- x0 += sx
- if e2 < dx:
- err += dx
- y0 += sy
+ if err < 0:
+ y += sy
+ err += dx
+ x += sx
+ else:
+ err = dy / 2.0
+ while y != y1:
+ points.append((x, y))
+ err -= dx
+ if err < 0:
+ x += sx
+ err += dy
+ y += sy
+ points.append((x, y))
return points
</patch>
I need you to solve the provded issue by generating a single patch file that I can apply directly to this repository using git apply. Please respond with a single patch file in the format shown above.
Respond below:
| corona-warn-app/cwa-server | 576fd8b20079374458ffb650fe63ca6002e84a39 | Switch application*.properties files to Yaml
Let's switch over to YAML for better readability.
Affected files:
common/persistence/src/test/resources/application.properties
services/submission/src/main/resources/application.properties
services/submission/src/test/resources/application.properties
services/distribution/src/main/resources/application.properties
services/distribution/src/test/resources/application.properties
services/submission/src/main/resources/application-dev.properties
services/distribution/src/main/resources/application-dev.properties
services/submission/src/main/resources/application-cloud.properties
services/distribution/src/main/resources/application-cloud.properties
services/distribution/src/main/resources/application-testdata.properties
| 2020-05-23T21:07:14 | <patch>
diff --git a/README.md b/README.md
--- a/README.md
+++ b/README.md
@@ -6,7 +6,7 @@
<a href="https://github.com/corona-warn-app/cwa-server/commits/" title="Last Commit"><img src="https://img.shields.io/github/last-commit/corona-warn-app/cwa-server?style=flat"></a>
<a href="https://github.com/corona-warn-app/cwa-server/issues" title="Open Issues"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat"></a>
<a href="https://circleci.com/gh/corona-warn-app/cwa-server" title="Build Status"><img src="https://circleci.com/gh/corona-warn-app/cwa-server.svg?style=shield&circle-token=4ab059989d10709df19eb4b98ab7c121a25e981a"></a>
- <a href="https://sonarcloud.io/dashboard?id=corona-warn-app_cwa-server" title="Quality Gate"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=alert_status"></a>
+ <a href="https://sonarcloud.io/dashboard?id=corona-warn-app_cwa-server" title="Quality Gate"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=alert_status"></a>
<a href="https://sonarcloud.io/component_measures?id=corona-warn-app_cwa-server&metric=Coverage&view=list" title="Coverage"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=coverage"></a>
<a href="https://github.com/corona-warn-app/cwa-server/blob/master/LICENSE" title="License"><img src="https://img.shields.io/badge/License-Apache%202.0-green.svg?style=flat"></a>
</p>
@@ -57,7 +57,7 @@ The docker-compose contains the following services:
Service | Description | Endpoint and Default Credentials
--------------|-------------|-----------
-submission | The Corona-Warn-App submission service | http://localhost:8000
+submission | The Corona-Warn-App submission service | http://localhost:8000
distribution | The Corona-Warn-App distribution service | NO ENDPOINT
postgres | A [postgres] database installation | postgres:8001 <br> Username: postgres <br> Password: postgres
pgadmin | A [pgadmin](https://www.pgadmin.org/) installation for the postgres database | http://localhost:8002 <br> Username: [email protected] <br> Password: password
@@ -99,8 +99,8 @@ To prepare your machine to run the CWA project locally, we recommend that you fi
After you made sure that the specified dependencies are running, configure them in the respective configuration files.
-* Configure the Postgres connection in the [submission config](./services/submission/src/main/resources/application.properties) and in the [distribution config](./services/distribution/src/main/resources/application.properties)
-* Configure the S3 compatible object storage in the [distribution config](./services/distribution/src/main/resources/application.properties)
+* Configure the Postgres connection in the [submission config](./services/submission/src/main/resources/application.yaml) and in the [distribution config](./services/distribution/src/main/resources/application.yaml)
+* Configure the S3 compatible object storage in the [distribution config](./services/distribution/src/main/resources/application.yaml)
* Configure the certificate and private key for the distribution service, the paths need to be prefixed with `file:`
* `VAULT_FILESIGNING_SECRET` should be the path to the private key, example available in `<repo-root>/docker-compose-test-secrets/private.pem`
* `VAULT_FILESIGNING_CERT` should be the path to the certificate, example available in `<repo-root>/docker-compose-test-secrets/certificate.cert`
@@ -181,7 +181,7 @@ The following public repositories are currently available for the Corona-Warn-Ap
Copyright (c) 2020 SAP SE or an SAP affiliate company.
-Licensed under the **Apache License, Version 2.0** (the "License"); you may not use this file except in compliance with the License.
+Licensed under the **Apache License, Version 2.0** (the "License"); you may not use this file except in compliance with the License.
You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0.
diff --git a/services/distribution/src/main/resources/application-cloud.properties b/services/distribution/src/main/resources/application-cloud.properties
deleted file mode 100644
--- a/services/distribution/src/main/resources/application-cloud.properties
+++ /dev/null
@@ -1,9 +0,0 @@
-spring.flyway.enabled=true
-spring.flyway.locations=classpath:db/migration/postgres
-
-spring.datasource.driver-class-name=org.postgresql.Driver
-spring.datasource.url=jdbc:postgresql://${POSTGRESQL_SERVICE_HOST}:${POSTGRESQL_SERVICE_PORT}/${POSTGRESQL_DATABASE}
-spring.datasource.username=${POSTGRESQL_USER}
-spring.datasource.password=${POSTGRESQL_PASSWORD}
-
-services.distribution.paths.output=/tmp/distribution
\ No newline at end of file
diff --git a/services/distribution/src/main/resources/application-cloud.yaml b/services/distribution/src/main/resources/application-cloud.yaml
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/main/resources/application-cloud.yaml
@@ -0,0 +1,22 @@
+---
+spring:
+ flyway:
+ enabled: true
+ locations: classpath:db/migration/postgres
+ datasource:
+ driver-class-name: org.postgresql.Driver
+ url: jdbc:postgresql://${POSTGRESQL_SERVICE_HOST}:${POSTGRESQL_SERVICE_PORT}/${POSTGRESQL_DATABASE}
+ username: ${POSTGRESQL_USER}
+ password: ${POSTGRESQL_PASSWORD}
+
+services:
+ distribution:
+ paths:
+ output: /tmp/distribution
+ objectstore:
+ access-key: ${CWA_OBJECTSTORE_ACCESSKEY}
+ secret-key: ${CWA_OBJECTSTORE_SECRETKEY}
+ endpoint: ${CWA_OBJECTSTORE_ENDPOINT}
+ bucket: ${CWA_OBJECTSTORE_BUCKET}
+ port: ${CWA_OBJECTSTORE_PORT}
+ set-public-read-acl-on-put-object: false
diff --git a/services/distribution/src/main/resources/application-dev.properties b/services/distribution/src/main/resources/application-dev.properties
deleted file mode 100644
--- a/services/distribution/src/main/resources/application-dev.properties
+++ /dev/null
@@ -1,2 +0,0 @@
-logging.level.org.springframework.web=DEBUG
-logging.level.app.coronawarn=DEBUG
\ No newline at end of file
diff --git a/services/distribution/src/main/resources/application-dev.yaml b/services/distribution/src/main/resources/application-dev.yaml
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/main/resources/application-dev.yaml
@@ -0,0 +1,8 @@
+---
+logging:
+ level:
+ org:
+ springframework:
+ web: DEBUG
+ app:
+ coronawarn: DEBUG
diff --git a/services/distribution/src/main/resources/application-testdata.properties b/services/distribution/src/main/resources/application-testdata.properties
deleted file mode 100644
--- a/services/distribution/src/main/resources/application-testdata.properties
+++ /dev/null
@@ -1,2 +0,0 @@
-services.distribution.testdata.seed=123456
-services.distribution.testdata.exposures-per-hour=1000
\ No newline at end of file
diff --git a/services/distribution/src/main/resources/application-testdata.yaml b/services/distribution/src/main/resources/application-testdata.yaml
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/main/resources/application-testdata.yaml
@@ -0,0 +1,6 @@
+---
+services:
+ distribution:
+ testdata:
+ seed: 123456
+ exposures-per-hour: 1000
diff --git a/services/distribution/src/main/resources/application.properties b/services/distribution/src/main/resources/application.properties
deleted file mode 100644
--- a/services/distribution/src/main/resources/application.properties
+++ /dev/null
@@ -1,52 +0,0 @@
-logging.level.org.springframework.web=INFO
-logging.level.app.coronawarn=INFO
-spring.main.web-application-type=NONE
-
-services.distribution.retention-days=14
-services.distribution.output-file-name=index
-services.distribution.tek-export.file-name=export.bin
-services.distribution.tek-export.file-header=EK Export v1
-services.distribution.tek-export.file-header-width=16
-
-services.distribution.paths.output=out
-services.distribution.paths.privatekey=${VAULT_FILESIGNING_SECRET}
-services.distribution.paths.certificate=${VAULT_FILESIGNING_CERT}
-
-services.distribution.api.version-path=version
-services.distribution.api.version-v1=v1
-services.distribution.api.country-path=country
-services.distribution.api.country-germany=DE
-services.distribution.api.date-path=date
-services.distribution.api.hour-path=hour
-services.distribution.api.diagnosis-keys-path=diagnosis-keys
-services.distribution.api.parameters-path=configuration
-services.distribution.api.parameters-exposure-configuration-file-name=exposure_configuration
-services.distribution.api.parameters-risk-score-classification-file-name=risk_score_classification
-
-services.distribution.signature.app-bundle-id=de.rki.coronawarnapp
-services.distribution.signature.android-package=de.rki.coronawarnapp
-services.distribution.signature.verification-key-id=
-services.distribution.signature.verification-key-version=
-services.distribution.signature.algorithm-oid=1.2.840.10045.4.3.2
-services.distribution.signature.algorithm-name=SHA256withECDSA
-services.distribution.signature.file-name=export.sig
-services.distribution.signature.security-provider=BC
-
-# Configuration for the S3 compatible object storage hosted by Telekom in Germany
-services.distribution.objectstore.access-key=${CWA_OBJECTSTORE_ACCESSKEY:accessKey1}
-services.distribution.objectstore.secret-key=${CWA_OBJECTSTORE_SECRETKEY:verySecretKey1}
-services.distribution.objectstore.endpoint=${CWA_OBJECTSTORE_ENDPOINT:http\://localhost\:8003}
-services.distribution.objectstore.bucket=${CWA_OBJECTSTORE_BUCKET:cwa}
-services.distribution.objectstore.port=${CWA_OBJECTSTORE_PORT:8003}
-services.distribution.objectstore.set-public-read-acl-on-put-object=true
-
-# Postgres configuration
-spring.jpa.hibernate.ddl-auto=validate
-
-spring.flyway.enabled=true
-spring.flyway.locations=classpath:db/migration/postgres
-
-spring.datasource.driver-class-name=org.postgresql.Driver
-spring.datasource.url=jdbc:postgresql://${POSTGRESQL_SERVICE_HOST:localhost}:${POSTGRESQL_SERVICE_PORT:5432}/${POSTGRESQL_DATABASE:cwa}
-spring.datasource.username=${POSTGRESQL_USER:postgres}
-spring.datasource.password=${POSTGRESQL_PASSWORD:postgres}
diff --git a/services/distribution/src/main/resources/application.yaml b/services/distribution/src/main/resources/application.yaml
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/main/resources/application.yaml
@@ -0,0 +1,66 @@
+---
+logging:
+ level:
+ org:
+ springframework:
+ web: INFO
+ app:
+ coronawarn: INFO
+
+services:
+ distribution:
+ output-file-name: index
+ retention-days: 14
+ paths:
+ output: out
+ privatekey: ${VAULT_FILESIGNING_SECRET}
+ certificate: ${VAULT_FILESIGNING_CERT}
+ tek-export:
+ file-name: export.bin
+ file-header: EK Export v1
+ file-header-width: 16
+ api:
+ version-path: version
+ version-v1: v1
+ country-path: country
+ country-germany: DE
+ date-path: date
+ hour-path: hour
+ diagnosis-keys-path: diagnosis-keys
+ parameters-path: configuration
+ parameters-exposure-configuration-file-name: exposure_configuration
+ parameters-risk-score-classification-file-name: risk_score_classification
+ signature:
+ app-bundle-id: de.rki.coronawarnapp
+ android-package: de.rki.coronawarnapp
+ verification-key-id:
+ verification-key-version:
+ algorithm-oid: 1.2.840.10045.4.3.2
+ algorithm-name: SHA256withECDSA
+ file-name: export.sig
+ security-provider: BC
+ # Configuration for the S3 compatible object storage hosted by Telekom in Germany
+ objectstore:
+ access-key: ${CWA_OBJECTSTORE_ACCESSKEY:accessKey1}
+ secret-key: ${CWA_OBJECTSTORE_SECRETKEY:verySecretKey1}
+ endpoint: ${CWA_OBJECTSTORE_ENDPOINT:http\://localhost\:8003}
+ bucket: ${CWA_OBJECTSTORE_BUCKET:cwa}
+ port: ${CWA_OBJECTSTORE_PORT:8003}
+ set-public-read-acl-on-put-object: true
+
+spring:
+ main:
+ web-application-type: NONE
+# Postgres configuration
+ jpa:
+ hibernate:
+ ddl-auto: validate
+ flyway:
+ enabled: true
+ locations: classpath:db/migration/postgres
+
+ datasource:
+ driver-class-name: org.postgresql.Driver
+ url: jdbc:postgresql://${POSTGRESQL_SERVICE_HOST:localhost}:${POSTGRESQL_SERVICE_PORT:5432}/${POSTGRESQL_DATABASE:cwa}
+ username: ${POSTGRESQL_USER:postgres}
+ password: ${POSTGRESQL_PASSWORD:postgres}
diff --git a/services/submission/src/main/resources/application-cloud.properties b/services/submission/src/main/resources/application-cloud.properties
deleted file mode 100644
--- a/services/submission/src/main/resources/application-cloud.properties
+++ /dev/null
@@ -1,6 +0,0 @@
-spring.flyway.locations=classpath:db/migration/postgres
-
-spring.datasource.driver-class-name=org.postgresql.Driver
-spring.datasource.url=jdbc:postgresql://${POSTGRESQL_SERVICE_HOST}:${POSTGRESQL_SERVICE_PORT}/${POSTGRESQL_DATABASE}
-spring.datasource.username=${POSTGRESQL_USER}
-spring.datasource.password=${POSTGRESQL_PASSWORD}
\ No newline at end of file
diff --git a/services/submission/src/main/resources/application-cloud.yaml b/services/submission/src/main/resources/application-cloud.yaml
new file mode 100644
--- /dev/null
+++ b/services/submission/src/main/resources/application-cloud.yaml
@@ -0,0 +1,9 @@
+---
+spring:
+ flyway:
+ locations: classpath:db/migration/postgres
+ datasource:
+ driver-class-name: org.postgresql.Driver
+ url: jdbc:postgresql://${POSTGRESQL_SERVICE_HOST}:${POSTGRESQL_SERVICE_PORT}/${POSTGRESQL_DATABASE}
+ username: ${POSTGRESQL_USER}
+ password: ${POSTGRESQL_PASSWORD}
diff --git a/services/submission/src/main/resources/application-config-test.properties b/services/submission/src/main/resources/application-config-test.properties
deleted file mode 100644
--- a/services/submission/src/main/resources/application-config-test.properties
+++ /dev/null
@@ -1,4 +0,0 @@
-services.submission.initial_fake_delay_milliseconds=100.0
-services.submission.fake_delay_moving_average_samples=1.0
-services.submission.retention-days=10
-services.submission.payload.max-number-of-keys=1000
\ No newline at end of file
diff --git a/services/submission/src/main/resources/application-dev.properties b/services/submission/src/main/resources/application-dev.properties
deleted file mode 100644
--- a/services/submission/src/main/resources/application-dev.properties
+++ /dev/null
@@ -1 +0,0 @@
-logging.level.org.springframework.web=DEBUG
diff --git a/services/submission/src/main/resources/application-dev.yaml b/services/submission/src/main/resources/application-dev.yaml
new file mode 100644
--- /dev/null
+++ b/services/submission/src/main/resources/application-dev.yaml
@@ -0,0 +1,6 @@
+---
+logging:
+ level:
+ org:
+ springframework:
+ web: DEBUG
diff --git a/services/submission/src/main/resources/application.properties b/services/submission/src/main/resources/application.properties
deleted file mode 100644
--- a/services/submission/src/main/resources/application.properties
+++ /dev/null
@@ -1,20 +0,0 @@
-logging.level.org.springframework.web=INFO
-
-# The initial value of the moving average for fake request delays.
-services.submission.initial_fake_delay_milliseconds=10
-# The number of samples for the calculation of the moving average for fake request delays.
-services.submission.fake_delay_moving_average_samples=10
-
-services.submission.retention-days=14
-services.submission.payload.max-number-of-keys=14
-
-spring.jpa.hibernate.ddl-auto=validate
-spring.flyway.enabled=true
-
-spring.flyway.locations=classpath:db/migration/postgres
-
-# Postgres configuration
-spring.datasource.driver-class-name=org.postgresql.Driver
-spring.datasource.url=jdbc:postgresql://${POSTGRESQL_SERVICE_HOST:localhost}:${POSTGRESQL_SERVICE_PORT:5432}/${POSTGRESQL_DATABASE:cwa}
-spring.datasource.username=${POSTGRESQL_USER:postgres}
-spring.datasource.password=${POSTGRESQL_PASSWORD:postgres}
diff --git a/services/submission/src/main/resources/application.yaml b/services/submission/src/main/resources/application.yaml
new file mode 100644
--- /dev/null
+++ b/services/submission/src/main/resources/application.yaml
@@ -0,0 +1,30 @@
+---
+logging:
+ level:
+ org:
+ springframework:
+ web: INFO
+
+# The initial value of the moving average for fake request delays.
+services:
+ submission:
+ initial-fake-delay-milliseconds: 10
+ # The number of samples for the calculation of the moving average for fake request delays.
+ fake-delay-moving-average-samples: 10
+ retention-days: 14
+ payload:
+ max-number-of-keys: 14
+
+spring:
+ jpa:
+ hibernate:
+ ddl-auto: validate
+ flyway:
+ enabled: true
+ locations: classpath:db/migration/postgres
+# Postgres configuration
+ datasource:
+ driver-class-name: org.postgresql.Driver
+ url: jdbc:postgresql://${POSTGRESQL_SERVICE_HOST:localhost}:${POSTGRESQL_SERVICE_PORT:5432}/${POSTGRESQL_DATABASE:cwa}
+ username: ${POSTGRESQL_USER:postgres}
+ password: ${POSTGRESQL_PASSWORD:postgres}
</patch> | diff --git a/common/persistence/src/test/resources/application.properties b/common/persistence/src/test/resources/application.properties
deleted file mode 100644
--- a/common/persistence/src/test/resources/application.properties
+++ /dev/null
@@ -1,6 +0,0 @@
-spring.flyway.enabled=false
-spring.jpa.hibernate.ddl-auto=create
-spring.jpa.properties.hibernate.show_sql=false
-spring.main.banner-mode=off
-logging.level.org.springframework=off
-logging.level.root=off
\ No newline at end of file
diff --git a/common/persistence/src/test/resources/application.yaml b/common/persistence/src/test/resources/application.yaml
new file mode 100644
--- /dev/null
+++ b/common/persistence/src/test/resources/application.yaml
@@ -0,0 +1,17 @@
+---
+spring:
+ flyway:
+ enabled: false
+ jpa:
+ hibernate:
+ ddl-auto: create
+ properties:
+ hibernate:
+ show-sql: false
+ main:
+ banner-mode: off
+logging:
+ level:
+ org:
+ springframework: off
+ root: off
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/component/CryptoProviderTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/component/CryptoProviderTest.java
--- a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/component/CryptoProviderTest.java
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/component/CryptoProviderTest.java
@@ -28,7 +28,6 @@
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.test.context.ConfigFileApplicationContextInitializer;
import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit.jupiter.SpringExtension;
@EnableConfigurationProperties(value = DistributionServiceConfig.class)
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysDirectoryTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysDirectoryTest.java
--- a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysDirectoryTest.java
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysDirectoryTest.java
@@ -50,7 +50,6 @@
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.test.context.ConfigFileApplicationContextInitializer;
import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit.jupiter.SpringExtension;
@EnableConfigurationProperties(value = DistributionServiceConfig.class)
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/config/DistributionServiceConfigTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/config/DistributionServiceConfigTest.java
deleted file mode 100644
--- a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/config/DistributionServiceConfigTest.java
+++ /dev/null
@@ -1,91 +0,0 @@
-package app.coronawarn.server.services.distribution.config;
-
-import static org.springframework.test.util.AssertionErrors.assertNotNull;
-import static org.springframework.test.util.AssertionErrors.assertNull;
-
-import static org.assertj.core.api.Assertions.assertThat;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Properties;
-import org.junit.jupiter.api.AfterEach;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.extension.ExtendWith;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.boot.context.properties.EnableConfigurationProperties;
-import org.springframework.test.context.TestPropertySource;
-import org.springframework.test.context.junit.jupiter.SpringExtension;
-
-@ExtendWith(SpringExtension.class)
-@EnableConfigurationProperties(value = DistributionServiceConfig.class)
-@TestPropertySource("classpath:application.properties")
-public class DistributionServiceConfigTest {
-
- @Autowired
- private DistributionServiceConfig dsc;
-
- private final Properties properties = new Properties();
-
- @BeforeEach
- public void setup() throws IOException {
- InputStream is = getClass().getClassLoader().getResourceAsStream("application.properties");
- properties.load(is);
- }
-
- @AfterEach
- public void tearDown() {
- properties.clear();
- }
-
- @Test
- void whenDistributionConfigBeanCreatedThenPropertiesLoadedCorrectly() {
-
- assertNotNull("Configuration should not be null", dsc);
- assertNotNull("Paths should not be null", dsc.getPaths());
- assertNull("TestData should be null", dsc.getTestData());
- assertNotNull("Signature should not be null", dsc.getSignature());
- assertNotNull("API should not be null", dsc.getApi());
-
- Map<String, String> cp = new HashMap<>();
- cp.put("services.distribution.retention-days", dsc.getRetentionDays().toString());
- cp.put("services.distribution.output-file-name", dsc.getOutputFileName());
- cp.put("services.distribution.tek-export.file-name", dsc.getTekExport().getFileName());
- cp.put("services.distribution.tek-export.file-header", dsc.getTekExport().getFileHeader());
- cp.put("services.distribution.tek-export.file-header-width", dsc.getTekExport().getFileHeaderWidth().toString());
- cp.put("services.distribution.paths.privatekey", dsc.getPaths().getPrivateKey());
- cp.put("services.distribution.paths.certificate", dsc.getPaths().getCertificate());
- cp.put("services.distribution.paths.output", dsc.getPaths().getOutput());
- cp.put("services.distribution.signature.app-bundle-id", dsc.getSignature().getAppBundleId());
- cp.put("services.distribution.signature.android-package", dsc.getSignature().getAndroidPackage());
- cp.put("services.distribution.signature.verification-key-id", dsc.getSignature().getVerificationKeyId());
- cp.put("services.distribution.signature.verification-key-version", dsc.getSignature().getVerificationKeyVersion());
- cp.put("services.distribution.signature.algorithm-oid", dsc.getSignature().getAlgorithmOid());
- cp.put("services.distribution.signature.algorithm-name", dsc.getSignature().getAlgorithmName());
- cp.put("services.distribution.signature.file-name", dsc.getSignature().getFileName());
- cp.put("services.distribution.signature.security-provider", dsc.getSignature().getSecurityProvider());
- cp.put("services.distribution.api.version-path", dsc.getApi().getVersionPath());
- cp.put("services.distribution.api.version-v1", dsc.getApi().getVersionV1());
- cp.put("services.distribution.api.country-path", dsc.getApi().getCountryPath());
- cp.put("services.distribution.api.country-germany", dsc.getApi().getCountryGermany());
- cp.put("services.distribution.api.date-path", dsc.getApi().getDatePath());
- cp.put("services.distribution.api.hour-path", dsc.getApi().getHourPath());
- cp.put("services.distribution.api.diagnosis-keys-path", dsc.getApi().getDiagnosisKeysPath());
- cp.put("services.distribution.api.parameters-path", dsc.getApi().getParametersPath());
- cp.put("services.distribution.api.parameters-exposure-configuration-file-name",
- dsc.getApi().getParametersExposureConfigurationFileName());
- cp.put("services.distribution.api.parameters-risk-score-classification-file-name",
- dsc.getApi().getParametersRiskScoreClassificationFileName());
- cp.put("services.distribution.objectstore.access-key", dsc.getObjectStore().getAccessKey());
- cp.put("services.distribution.objectstore.secret-key", dsc.getObjectStore().getSecretKey());
- cp.put("services.distribution.objectstore.endpoint", dsc.getObjectStore().getEndpoint());
- cp.put("services.distribution.objectstore.bucket", dsc.getObjectStore().getBucket());
- cp.put("services.distribution.objectstore.port", dsc.getObjectStore().getPort().toString());
- cp.put("services.distribution.objectstore.set-public-read-acl-on-put-object",
- dsc.getObjectStore().isSetPublicReadAclOnPutObject().toString());
-
- cp.forEach((key, value) -> assertThat(properties.getProperty(key)).isEqualTo(value));
- }
-
-}
diff --git a/services/distribution/src/test/resources/application.properties b/services/distribution/src/test/resources/application.properties
deleted file mode 100644
--- a/services/distribution/src/test/resources/application.properties
+++ /dev/null
@@ -1,47 +0,0 @@
-logging.level.org.springframework=off
-logging.level.root=info
-spring.main.banner-mode=off
-
-services.distribution.retention-days=14
-services.distribution.output-file-name=index
-services.distribution.tek-export.file-name=export.bin
-services.distribution.tek-export.file-header=EK Export v1
-services.distribution.tek-export.file-header-width=16
-
-services.distribution.paths.output=out
-services.distribution.paths.privatekey=classpath:certificates/client/private.pem
-services.distribution.paths.certificate=classpath:certificates/chain/certificate.crt
-
-services.distribution.api.version-path=version
-services.distribution.api.version-v1=v1
-services.distribution.api.country-path=country
-services.distribution.api.country-germany=DE
-services.distribution.api.date-path=date
-services.distribution.api.hour-path=hour
-services.distribution.api.diagnosis-keys-path=diagnosis-keys
-services.distribution.api.parameters-path=configuration
-services.distribution.api.parameters-exposure-configuration-file-name=exposure_configuration
-services.distribution.api.parameters-risk-score-classification-file-name=risk_score_classification
-
-services.distribution.signature.app-bundle-id=de.rki.coronawarnapp
-services.distribution.signature.android-package=de.rki.coronawarnapp
-services.distribution.signature.verification-key-id=
-services.distribution.signature.verification-key-version=
-services.distribution.signature.algorithm-oid=1.2.840.10045.4.3.2
-services.distribution.signature.algorithm-name=SHA256withECDSA
-services.distribution.signature.file-name=export.sig
-services.distribution.signature.security-provider=BC
-
-spring.flyway.enabled=true
-# default case is H2 - value will be overwritten by profile cloud or postgres
-spring.flyway.locations=classpath:db/migration/h2
-
-spring.jpa.hibernate.ddl-auto=validate
-
-# S3 object store configuration
-services.distribution.objectstore.access-key=accessKey1
-services.distribution.objectstore.secret-key=verySecretKey1
-services.distribution.objectstore.endpoint=http\://localhost\:8003
-services.distribution.objectstore.bucket=cwa
-services.distribution.objectstore.port=8003
-services.distribution.objectstore.set-public-read-acl-on-put-object=true
diff --git a/services/distribution/src/test/resources/application.yaml b/services/distribution/src/test/resources/application.yaml
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/test/resources/application.yaml
@@ -0,0 +1,57 @@
+---
+logging:
+ level:
+ org:
+ springframework: off
+ root: info
+
+services:
+ distribution:
+ output-file-name: index
+ retention-days: 14
+ paths:
+ output: out
+ privatekey: classpath:certificates/client/private.pem
+ certificate: classpath:certificates/chain/certificate.crt
+ tek-export:
+ file-name: export.bin
+ file-header: EK Export v1
+ file-header-width: 16
+ api:
+ version-path: version
+ version-v1: v1
+ country-path: country
+ country-germany: DE
+ date-path: date
+ hour-path: hour
+ diagnosis-keys-path: diagnosis-keys
+ parameters-path: configuration
+ parameters-exposure-configuration-file-name: exposure_configuration
+ parameters-risk-score-classification-file-name: risk_score_classification
+ signature:
+ app-bundle-id: de.rki.coronawarnapp
+ android-package: de.rki.coronawarnapp
+ verification-key-id:
+ verification-key-version:
+ algorithm-oid: 1.2.840.10045.4.3.2
+ algorithm-name: SHA256withECDSA
+ file-name: export.sig
+ security-provider: BC
+ # S3 object store configuration
+ objectstore:
+ access-key: ${CWA_OBJECTSTORE_ACCESSKEY:accessKey1}
+ secret-key: ${CWA_OBJECTSTORE_SECRETKEY:verySecretKey1}
+ endpoint: ${WA_OBJECTSTORE_ENDPOINT:http\://localhost\:8003}
+ bucket: ${CWA_OBJECTSTORE_BUCKET:cwa}
+ port: ${CWA_OBJECTSTORE_PORT:8003}
+ set-public-read-acl-on-put-object: true
+spring:
+ main:
+ banner-mode: off
+ flyway:
+ enabled: true
+# default case is H2 - value will be overwritten by profile cloud or postgres
+ locations: classpath:db/migration/h2
+ jpa:
+ hibernate:
+ ddl-auto: validate
diff --git a/services/submission/src/test/java/app/coronawarn/server/services/submission/config/SubmissionServiceConfigTest.java b/services/submission/src/test/java/app/coronawarn/server/services/submission/config/SubmissionServiceConfigTest.java
deleted file mode 100644
--- a/services/submission/src/test/java/app/coronawarn/server/services/submission/config/SubmissionServiceConfigTest.java
+++ /dev/null
@@ -1,59 +0,0 @@
-package app.coronawarn.server.services.submission.config;
-
-import static org.springframework.test.util.AssertionErrors.assertEquals;
-import static org.springframework.test.util.AssertionErrors.assertNotNull;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.Properties;
-import org.junit.jupiter.api.AfterEach;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.extension.ExtendWith;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.boot.context.properties.EnableConfigurationProperties;
-import org.springframework.test.context.TestPropertySource;
-import org.springframework.test.context.junit.jupiter.SpringExtension;
-
-@ExtendWith(SpringExtension.class)
-@EnableConfigurationProperties(value = SubmissionServiceConfig.class)
-@TestPropertySource("classpath:application-config-test.properties")
-public class SubmissionServiceConfigTest {
-
- @Autowired
- private SubmissionServiceConfig config;
-
- private final Properties properties = new Properties();
-
- @BeforeEach
- public void setup() throws IOException {
- InputStream is = getClass().getClassLoader()
- .getResourceAsStream("application-config-test.properties");
- properties.load(is);
- }
-
- @AfterEach
- public void tearDown() {
- properties.clear();
- }
-
- @Test
- void whenDistributionConfigBeanCreatedThenPropertiesLoadedCorrectly() {
-
- assertNotNull("Configuration should not be null", config);
-
- assertEquals("Fake Delay value should be loaded correctly.",
- properties.getProperty("services.submission.initial_fake_delay_milliseconds"),
- String.valueOf(config.getInitialFakeDelayMilliseconds()));
- assertEquals("Fake Delay Moving Average value should be loaded correctly.",
- properties.getProperty("services.submission.fake_delay_moving_average_samples"),
- String.valueOf(config.getFakeDelayMovingAverageSamples()));
- assertEquals("Retention Days should be loaded correctly.",
- properties.getProperty("services.submission.retention-days"),
- String.valueOf(config.getRetentionDays()));
- assertEquals("Max Number of Days value should be loaded correctly.",
- properties.getProperty("services.submission.payload.max-number-of-keys"),
- String.valueOf(config.getMaxNumberOfKeys()));
-
- }
-}
\ No newline at end of file
diff --git a/services/submission/src/test/resources/application.properties b/services/submission/src/test/resources/application.properties
deleted file mode 100644
--- a/services/submission/src/test/resources/application.properties
+++ /dev/null
@@ -1,15 +0,0 @@
-logging.level.org.springframework=off
-logging.level.root=off
-spring.main.banner-mode=off
-
-services.submission.initial_fake_delay_milliseconds=1
-services.submission.fake_delay_moving_average_samples=1
-
-spring.flyway.enabled=true
-# default case is H2 - value will be overwritten by profile cloud or postgres
-spring.flyway.locations=classpath:db/migration/h2
-
-spring.jpa.hibernate.ddl-auto=validate
-
-services.submission.retention-days=14
-services.submission.payload.max-number-of-keys=14
diff --git a/services/submission/src/test/resources/application.yaml b/services/submission/src/test/resources/application.yaml
new file mode 100644
--- /dev/null
+++ b/services/submission/src/test/resources/application.yaml
@@ -0,0 +1,25 @@
+---
+logging:
+ level:
+ org:
+ springframework: off
+ root: off
+spring:
+ main:
+ banner-mode: off
+ flyway:
+ enabled: true
+ # default case is H2 - value will be overwritten by profile cloud or postgres
+ locations: classpath:db/migration/h2
+
+ jpa:
+ hibernate:
+ ddl-auto: validate
+
+services:
+ submission:
+ initial-fake-delay-milliseconds: 1
+ fake-delay-moving-average-samples: 1
+ retention-days: 14
+ payload:
+ max-number-of-keys: 14
| |||||
corona-warn-app__cwa-server-1965 | You will be provided with a partial code base and an issue statement explaining a problem to resolve.
<issue>
min-android 1.5.1 differs from production 1.0.4 value
## Describe the bug
The `min-android` value served on
https://svc90.main.px.t-online.de/version/v1/configuration/country/DE/app_config is
`1.0.4`
which differs from the value
`1.5.1`
stored in https://github.com/corona-warn-app/cwa-server/blob/main/services/distribution/src/main/resources/application.yaml#L144
If CWA Android 1.4.0 is started, there is no prompt shown to the user that the app should be updated.
## Expected behaviour
The `min-android` value served on
https://svc90.main.px.t-online.de/version/v1/configuration/country/DE/app_config should be the same as the value stored in https://github.com/corona-warn-app/cwa-server/blob/main/services/distribution/src/main/resources/application.yaml#L144 which is currently `1.5.1`.
If `min-android` with the value of `1.5.1` were in production then starting CWA Android 1.4.0 should produce a prompt to update the app.
## Steps to reproduce the issue
1. In Android Studio check out CWA Android app release/1.4.x
2. Run CWA on Pixel 3a API 33 Android device emulator in Debug mode
3. Open Logcat in Android Studio and enter search term "UpdateChecker"
The log shows the following:
```
UpdateChecker de.rki.coronawarnapp.dev E minVersionStringFromServer:1.0.4
UpdateChecker de.rki.coronawarnapp.dev E Current app version:1.4.0
UpdateChecker de.rki.coronawarnapp.dev E needs update:false
```
Alternatively install old released versions from https://www.apkmirror.com/apk/robert-koch-institut/corona-warn-app/. As soon as a version < 1.0.4 is started, e.g. 1.0.0 or 1.0.2, a message "Update available" is output.
![Update available](https://user-images.githubusercontent.com/66998419/202911146-6b74b2e4-7a8d-462d-8f19-6e10762719e2.jpg)
If version 1.0.4 is installed and started, no update message is output. This is consistent with min-Android being set to `1.0.4` in production.
## Technical details
- Android Studio Dolphin | 2021.3.1 Patch 1
- Pixel 3a API 33 Android device emulator
- CWA Android 1.4.0 (note that this version was not released. Version 1.5 followed version 1.3)
## Possible Fix
Clarify what the minimum enforced version of CWA Android in production is supposed to be and ensure alignment of https://github.com/corona-warn-app/cwa-server/blob/main/services/distribution/src/main/resources/application.yaml with the values used in production.
</issue>
<code>
[start of README.md]
1 <!-- markdownlint-disable MD041 -->
2 <h1 align="center">
3 Corona-Warn-App Server
4 </h1>
5
6 <p align="center">
7 <a href="https://github.com/corona-warn-app/cwa-server/commits/" title="Last Commit"><img src="https://img.shields.io/github/last-commit/corona-warn-app/cwa-server?style=flat"></a>
8 <a href="https://github.com/corona-warn-app/cwa-server/issues" title="Open Issues"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat"></a>
9 <a href="https://circleci.com/gh/corona-warn-app/cwa-server" title="Build Status"><img src="https://circleci.com/gh/corona-warn-app/cwa-server.svg?style=shield&circle-token=4ab059989d10709df19eb4b98ab7c121a25e981a"></a>
10 <a href="https://sonarcloud.io/dashboard?id=corona-warn-app_cwa-server" title="Quality Gate"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=alert_status"></a>
11 <a href="https://sonarcloud.io/component_measures?id=corona-warn-app_cwa-server&metric=Coverage&view=list" title="Coverage"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=coverage"></a>
12 <a href="https://github.com/corona-warn-app/cwa-server/blob/HEAD/LICENSE" title="License"><img src="https://img.shields.io/badge/License-Apache%202.0-green.svg?style=flat"></a>
13 <a href="https://api.reuse.software/info/github.com/corona-warn-app/cwa-server" title="REUSE Status"><img src="https://api.reuse.software/badge/github.com/corona-warn-app/cwa-server"></a>
14 </p>
15
16 <p align="center">
17 <a href="#development">Development</a> •
18 <a href="#service-apis">Service APIs</a> •
19 <a href="#documentation">Documentation</a> •
20 <a href="#support-and-feedback">Support</a> •
21 <a href="#how-to-contribute">Contribute</a> •
22 <a href="#contributors">Contributors</a> •
23 <a href="#repositories">Repositories</a> •
24 <a href="#licensing">Licensing</a>
25 </p>
26
27 The goal of this project is to develop the official Corona-Warn-App for Germany based on the exposure notification API from [Apple](https://www.apple.com/covid19/contacttracing/) and [Google](https://www.google.com/covid19/exposurenotifications/). The apps (for both iOS and Android) use Bluetooth technology to exchange anonymous encrypted data with other mobile phones (on which the app is also installed) in the vicinity of an app user's phone. The data is stored locally on each user's device, preventing authorities or other parties from accessing or controlling the data. This repository contains the **implementation of the server for encryption keys** for the Corona-Warn-App.
28
29 In this documentation, Corona-Warn-App services are also referred to as CWA services.
30
31 ## Architecture Overview
32
33 You can find the architecture overview [here](/docs/ARCHITECTURE.md), which will give you
34 a good starting point in how the backend services interact with other services, and what purpose
35 they serve.
36
37 ## Development
38
39 After you've checked out this repository, you can run the application in one of the following ways:
40
41 * As a [Docker](https://www.docker.com/)-based deployment on your local machine. You can run either:
42 * Single components using the respective Dockerfile or
43 * The full backend using the Docker Compose (which is considered the most convenient way)
44 * As a [Maven](https://maven.apache.org)-based build on your local machine.
45 If you want to develop something in a single component, this approach is preferable.
46
47 ### Docker-Based Deployment
48
49 If you want to use Docker-based deployment, you need to install Docker on your local machine. For more information about downloading and installing Docker, see the [official Docker documentation](https://docs.docker.com/get-docker/).
50
51 #### Running the Full CWA Backend Using Docker Compose
52
53 For your convenience, a full setup for local development and testing purposes, including the generation of test data has been prepared using [Docker Compose](https://docs.docker.com/compose/reference/overview/). To build the backend services, run ```docker-compose build``` in the repository's root directory. A default configuration file can be found under ```.env``` in the root folder of the repository. If the endpoints are to be exposed to the network the default values in this file should be changed before docker-compose is run.
54
55 Once the services are built, you can start the whole backend using ```docker-compose up```.
56 The distribution service runs once and then finishes. If you want to trigger additional distribution runs, run ```docker-compose run distribution```.
57
58 The docker-compose contains the following services:
59
60 Service | Description | Endpoint and Default Credentials
61 ------------------|-------------|-----------
62 submission | The Corona-Warn-App submission service | `http://localhost:8000` <br> `http://localhost:8006` (for actuator endpoint)
63 distribution | The Corona-Warn-App distribution service | NO ENDPOINT
64 postgres | A [postgres] database installation | `localhost:8001` <br> `postgres:5432` (from containerized pgadmin) <br> Username: postgres <br> Password: postgres
65 pgadmin | A [pgadmin](https://www.pgadmin.org/) installation for the postgres database | `http://localhost:8002` <br> Username: [email protected] <br> Password: password
66 cloudserver | [Zenko CloudServer] is a S3-compliant object store | `http://localhost:8003/` <br> Access key: accessKey1 <br> Secret key: verySecretKey1
67 verification-fake | A very simple fake implementation for the tan verification. | `http://localhost:8004/version/v1/tan/verify` <br> The only valid tan is `edc07f08-a1aa-11ea-bb37-0242ac130002`.
68
69 ##### Known Limitation
70
71 In rare cases the docker-compose runs into a timing issue if the distribution service starts before the bucket of the objectstore was created. This is not a big issue as you can simply run ```docker-compose run distribution``` to trigger additional distribution runs after the objectstore was initialized.
72
73 #### Running Single CWA Services Using Docker
74
75 If you would like to build and run a single CWA service, it's considered easiest to run them in a Docker environment. You can do this using the script provided in the respective CWA service directory. The Docker script first builds the CWA service and then creates an image for the runtime, which means that there are no additional dependencies for you to install.
76
77 To build and run the distribution service, run the following command:
78
79 ```bash
80 ./services/distribution/build_and_run.sh
81 ```
82
83 To build and run the submission service, run the following command:
84
85 ```bash
86 ./services/submission/build_and_run.sh
87 ```
88
89 The submission service is available on [localhost:8080](http://localhost:8080 ).
90
91 ### Maven-Based Build
92
93 If you want to actively develop in one of the CWA services, the Maven-based runtime is most suitable.
94 To prepare your machine to run the CWA project locally, we recommend that you first ensure that you've installed the following:
95
96 * Minimum JDK Version 11: [OpenJDK](https://openjdk.java.net/) / [SapMachine](https://sap.github.io/SapMachine/)
97 * [Maven 3.6](https://maven.apache.org/)
98 * [Postgres]
99 * [Zenko CloudServer]
100
101 If you are already running a local Postgres, you need to create a database `cwa` and run the following setup scripts:
102
103 * Create the different CWA roles first by executing [create-roles.sql](./setup/setup-roles.sql).
104 * Create local database users for the specific roles by running [create-users.sql](./local-setup/create-users.sql).
105 * It is recommended to also run [enable-test-data-docker-compose.sql](./local-setup/enable-test-data-docker-compose.sql)
106 , which enables the test data generation profile. If you already had CWA running before and an existing `diagnosis-key`
107 table on your database, you need to run [enable-test-data.sql](./local-setup/enable-test-data.sql) instead.
108
109 You can also use `docker-compose` to start Postgres and Zenko. If you do that, you have to
110 set the following environment-variables when running the Spring project:
111
112 For the distribution module:
113
114 ```bash
115 POSTGRESQL_SERVICE_PORT=8001
116 VAULT_FILESIGNING_SECRET=</path/to/your/private_key>
117 SPRING_PROFILES_ACTIVE=signature-dev,disable-ssl-client-postgres
118 ```
119
120 For the submission module:
121
122 ```bash
123 POSTGRESQL_SERVICE_PORT=8001
124 SPRING_PROFILES_ACTIVE=disable-ssl-client-postgres
125 ```
126
127 #### Configure
128
129 After you made sure that the specified dependencies are running, configure them in the respective configuration files.
130
131 * Configure the Postgres connection in the [submission config](./services/submission/src/main/resources/application.yaml) and in the [distribution config](./services/distribution/src/main/resources/application.yaml)
132 * Configure the S3 compatible object storage in the [distribution config](./services/distribution/src/main/resources/application.yaml)
133 * Configure the private key for the distribution service, the path need to be prefixed with `file:`
134 * `VAULT_FILESIGNING_SECRET` should be the path to the private key, example available in `<repo-root>/docker-compose-test-secrets/private.pem`
135
136 #### Build
137
138 After you've checked out the repository, to build the project, run ```mvn install``` in your base directory.
139
140 #### Run
141
142 Navigate to the service you want to start and run the spring-boot:run target. The configured Postgres and the configured S3 compliant object storage are used as default. When you start the submission service, the endpoint is available on your local port 8080.
143
144 If you want to start the submission service, for example, you start it as follows:
145
146 ```bash
147 cd services/submission/
148 mvn spring-boot:run
149 ```
150
151 #### Debugging
152
153 To enable the `DEBUG` log level, you can run the application using the Spring `debug` profile.
154
155 ```bash
156 mvn spring-boot:run -Dspring.profiles.active=debug
157 ```
158
159 To be able to set breakpoints (e.g. in IntelliJ), it may be necessary to use the ```-Dspring-boot.run.fork=false``` parameter.
160
161 ## Service APIs
162
163 The API that is being exposed by the backend services is documented in an [OpenAPI](https://www.openapis.org/) specification. The specification files are available at the following locations:
164
165 Service | OpenAPI Specification
166 --------------------------|-------------
167 Submission Service | [services/submission/api_v1.json](https://github.com/corona-warn-app/cwa-server/raw/HEAD/services/submission/api_v1.json)
168 Distribution Service | [services/distribution/api_v1.json](https://github.com/corona-warn-app/cwa-server/raw/HEAD/services/distribution/api_v1.json)
169
170 ## Spring Profiles
171
172 ### Distribution
173
174 See [Distribution Service - Spring Profiles](/docs/DISTRIBUTION.md#spring-profiles).
175
176 ### Submission
177
178 See [Submission Service - Spring Profiles](/docs/SUBMISSION.md#spring-profiles).
179
180 ## Documentation
181
182 The full documentation for the Corona-Warn-App can be found in the [cwa-documentation](https://github.com/corona-warn-app/cwa-documentation) repository. The documentation repository contains technical documents, architecture information, and whitepapers related to this implementation.
183
184 The documentation for cwa-server can be found under the [/docs](./docs) folder.
185
186 The JavaDoc documentation for cwa-server is hosted by Github Pages at [https://corona-warn-app.github.io/cwa-server](https://corona-warn-app.github.io/cwa-server).
187
188 ## Support and Feedback
189
190 The following channels are available for discussions, feedback, and support requests:
191
192 | Type | Channel |
193 | ------------------------ | ------------------------------------------------------ |
194 | **General Discussion** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="General Discussion"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/question.svg?style=flat-square"></a> </a> |
195 | **Concept Feedback** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="Open Concept Feedback"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/architecture.svg?style=flat-square"></a> |
196 | **Backend Issue** | <a href="https://github.com/corona-warn-app/cwa-server/issues/new/choose" title="Open Backend Issue"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat-square"></a> |
197 | **Other Requests** | <a href="mailto:[email protected]" title="Email CWA Team"><img src="https://img.shields.io/badge/email-CWA%20team-green?logo=mail.ru&style=flat-square&logoColor=white"></a> |
198
199 ## How to Contribute
200
201 Contribution and feedback are 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.
202
203 ## Contributors
204
205 The German government has asked SAP and Deutsche Telekom to develop the Corona-Warn-App for Germany as open source software. Deutsche Telekom is providing the network and mobile technology and will operate and run the backend for the app in a safe, scalable and stable manner. SAP is responsible for the app development, its framework and the underlying platform. Therefore, development teams of SAP and Deutsche Telekom are contributing to this project. At the same time 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.
206
207 ## Repositories
208
209 A list of all public repositories from the Corona-Warn-App can be found [here](https://github.com/corona-warn-app/cwa-documentation/blob/master/README.md#repositories).
210
211 ## Licensing
212
213 Copyright (c) 2020-2022 SAP SE or an SAP affiliate company and Corona-Warn-App contributors.
214
215 Licensed under the **Apache License, Version 2.0** (the "License"); you may not use this file except in compliance with the License.
216
217 You may obtain a copy of the License from [here](./LICENSE).
218
219 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.
220
221 Please see the [detailed licensing information](https://api.reuse.software/info/github.com/corona-warn-app/cwa-ppa-server) via the [REUSE Tool](https://reuse.software/) for more details.
222
223 [Postgres]: https://www.postgresql.org/
224
225 [Zenko CloudServer]: https://www.zenko.io/cloudserver/
226
[end of README.md]
[start of services/distribution/src/main/resources/application.yaml]
1 ---
2 logging:
3 level:
4 org:
5 springframework:
6 web: INFO
7 app:
8 coronawarn: INFO
9 com:
10 netflix:
11 config:
12 sources:
13 URLConfigurationSource: ERROR
14
15 services:
16 distribution:
17 # Infection threshold in percentage.
18 infection-threshold: ${INFECTION_THRESHOLD:1}
19 # The name of the distribution output file.
20 output-file-name: index
21 # The name of the distribution output file v2.
22 output-file-name-v2: index-v2
23 # The number of days to retain diagnosis keys and trace time warnings for both database persistency layer and files stored on the object store.
24 retention-days: 14
25 # The number of days for diagnosis keys (based upon submission timestamp) to publish on CDN.
26 days-to-publish: ${DAYS_TO_PUBLISH:10}
27 # The number of minutes that diagnosis keys must have been expired for (since the end of the rolling interval window) before they can be distributed.
28 expiry-policy-minutes: 120
29 # The minimum number of diagnosis keys per bundle.
30 shifting-policy-threshold: 140
31 # The maximum number of keys per bundle.
32 maximum-number-of-keys-per-bundle: 600000
33 # Indicates whether the current incomplete day will be included in the distribution (used for testing purposes).
34 include-incomplete-days: false
35 # Indicates whether the current incomplete hour will be included in the distribution (used for testing purposes).
36 include-incomplete-hours: false
37 # The naming of the eu package that provides all keys in a single package.
38 eu-package-name: EUR
39 # Indicates whether the shifting and expiry policies are applied to all supported countries during distribution.
40 apply-policies-for-all-countries: false
41 card-id-sequence: ${STATS_CARD_ID_SEQUENCE:[12,999,10,2,8,9,1,3,4,5,6,11,7]}
42 # Local paths, that are used during the export creation.
43 connection-pool-size: 200
44 default-archive-name: export.bin
45 # Minimum value allowed for the diagnosis keys TRLs.
46 minimum-trl-value-allowed: ${MINIMUM_TRL_VALUE_ALLOWED:3}
47 paths:
48 # The output path.
49 output: out
50 # The location of the private key.
51 privatekey: ${VAULT_FILESIGNING_SECRET}
52 # Configuration for the exported archive, that is saved on the S3-compatible storage.
53 tek-export:
54 # The TEK file name included in the zip archive, containing the list of diagnosis keys.
55 file-name: export.bin
56 # The TEK file header.
57 file-header: EK Export v1
58 # The fixed (ensured by right whitespace padding) TEK file header width.
59 file-header-width: 16
60 # Configuration for the API which is used by the mobile app to query diagnosis keys.
61 api:
62 version-path: version
63 version-v1: v1
64 version-v2: v2
65 country-path: country
66 origin-country: ${ORIGIN_COUNTRY:DE}
67 date-path: date
68 hour-path: hour
69 diagnosis-keys-path: diagnosis-keys
70 trace-warnings-path: twp
71 parameters-path: configuration
72 app-config-file-name: app_config
73 app-config-v2-android-file-name: app_config_android
74 app-config-v2-ios-file-name: app_config_ios
75 statistics-file-name: stats
76 local-statistics-file-name: local_stats
77 # Signature configuration, used for signing the exports.
78 signature:
79 # The alias with which to identify public key to be used for verification.
80 verification-key-id: 262
81 # The key version for rollovers.
82 verification-key-version: v1
83 # The ASN.1 OID for algorithm identifier.
84 algorithm-oid: 1.2.840.10045.4.3.2
85 # The algorithm name.
86 algorithm-name: SHA256withECDSA
87 # The signature file name included in the zip archive.
88 file-name: export.sig
89 # The security provider.
90 security-provider: BC
91 # Configuration for the S3 compatible object storage hosted by Telekom in Germany.
92 objectstore:
93 access-key: ${CWA_OBJECTSTORE_ACCESSKEY:accessKey1}
94 secret-key: ${CWA_OBJECTSTORE_SECRETKEY:verySecretKey1}
95 endpoint: ${CWA_OBJECTSTORE_ENDPOINT:http://localhost}
96 bucket: ${CWA_OBJECTSTORE_BUCKET:cwa}
97 port: ${CWA_OBJECTSTORE_PORT:8003}
98 # Indicates whether the S3 Access Control List (ACL) header should be set to 'public-read' on put object.
99 set-public-read-acl-on-put-object: true
100 # The number of maximum retry attempts used for configuring Spring @Retryable annotation.
101 retry-attempts: 3
102 # The backoff period in milliseconds used for configuring Spring @Retryable annotation.
103 retry-backoff: 2000
104 # The maximum number of failed operations before giving up.
105 max-number-of-failed-operations: 5
106 # The ThreadPoolTaskExecutor's maximum thread pool size.
107 max-number-of-s3-threads: 4
108 # Allows distribution to overwrite files which are published on the object store
109 force-update-keyfiles: ${FORCE_UPDATE_KEYFILES:false}
110 # The number of days to retain hourly diagnosis keys file in S3. Database entries are still managed by the standard retention policy.
111 hour-file-retention-days: 2
112 # Configuration for the publishing of app statistics
113 statistics:
114 statistic-path: ${STATISTICS_FILE_NAME:json/v1/cwa_reporting_public_data.json}
115 local-statistic-path: ${LOCAL_STATISTICS_FILE_NAME:json/v1/cwa_reporting_public_data_region.json}
116 access-key: ${STATISTICS_FILE_ACCESS_KEY_ID:}
117 secret-key: ${STATISTICS_FILE_SECRET_ACCESS_KEY:}
118 endpoint: ${STATISTICS_FILE_S3_ENDPOINT:}
119 bucket: ${STATISTICS_FILE_S3_BUCKET:obs-cwa-public-dev}
120 pandemic-radar-url: ${STATISTICS_PANDEMIC_RADAR_URL:https://www.rki.de/DE/Content/InfAZ/N/Neuartiges_Coronavirus/Situationsberichte/COVID-19-Trends/COVID-19-Trends.html?__blob=publicationFile#/home}
121
122 app-features:
123 - label: unencrypted-checkins-enabled
124 value: ${EVREG_UNENCRYPTED_CHECKINS_ENABLED:0}
125 - label: validation-service-android-min-version-code
126 value: ${VALIDATION_SERVICE_ANDROID_MIN_VERSION_CODE:0}
127 - label: validation-service-ios-min-version-major
128 value: ${VALIDATION_SERVICE_IOS_MIN_VERSION_MAJOR:0}
129 - label: validation-service-ios-min-version-minor
130 value: ${VALIDATION_SERVICE_IOS_MIN_VERSION_MINOR:0}
131 - label: validation-service-ios-min-version-patch
132 value: ${VALIDATION_SERVICE_IOS_MIN_VERSION_PATCH:0}
133 - label: dcc-person-count-max
134 value: ${DCC_PERSON_COUNT_MAX:20}
135 - label: dcc-person-warn-threshold
136 value: ${DCC_PERSON_WARN_THRESHOLD:4}
137 - label: dcc-admission-check-scenarios-enabled
138 value: ${DCC_ADMISSION_CHECK_SCENARIOS_ENABLED:0}
139 supported-countries: ${SUPPORTED_COUNTRIES}
140 app-versions:
141 latest-ios: ${IOS_LATEST_VERSION:1.5.3}
142 min-ios: ${IOS_MIN_VERSION:1.5.3}
143 latest-android: ${ANDROID_LATEST_VERSION:1.5.1}
144 min-android: ${ANDROID_MIN_VERSION:1.5.1}
145 # With ENF v2 Android apps are versioned by Version Code and not by Semantic Versioning
146 min-android-version-code: ${ANDROID_MIN_VERSION_CODE:48}
147 latest-android-version-code: ${ANDROID_LATEST_VERSION_CODE:48}
148 app-config-parameters:
149 dgcParameters:
150 testCertificateParameters:
151 # validation rule for waitAfterPublicKeyRegistrationInSeconds:
152 # * must be a number
153 # * >= 0
154 # * <= 60
155 waitAfterPublicKeyRegistrationInSeconds: ${DGC_TC_WAIT_AFTER_PUBLIC_KEY_REGISTRATION_IN_SECONDS:10}
156 # validation rule for waitForRetryInSeconds:
157 # * must be a number
158 # * >= 0
159 # * <= 60
160 waitForRetryInSeconds: ${DGC_TC_WAIT_FOR_RETRY_IN_SECONDS:10}
161 expiration-threshold-in-days: ${DGC_EXPIRATION_THRESHOLD_IN_DAYS:27}
162 block-list-parameters:
163 # the value shall be parsed as a JSON string to
164 # generate the individual items, e.g.
165 # '[{"indices":[0],"hash":"9B09CAFEC0A6808411C348880C9C2D920646DFB980B5C959DC6EBF8A19B98120","validFrom":1636040446},{"indices":[0,2],"hash":"7D5D5B336E903086D64D1207EC6E957A4B1301026699011026F84A5156317C2B","validFrom":1638369640}]'
166 # note that `hash` shall be parsed from a hex string to a byte sequence
167 blocked-uvci-chunks: ${DGC_BLOCKED_UVCI_CHUNKS:[]}
168 ios-dgc-reissue-service-public-key-digest: ${IOS_DGC_REISSUE_SERVICE_PUBLIC_KEY_DIGEST:}
169 android-dgc-reissue-service-public-key-digest: ${ANDROID_DGC_REISSUE_SERVICE_PUBLIC_KEY_DIGEST:}
170 ios-key-download-parameters:
171 revoked-day-packages: ${KEY_DOWNLOAD_REVOKED_DAY_PACKAGES:[]}
172 revoked-hour-packages: ${KEY_DOWNLOAD_REVOKED_HOUR_PACKAGES:[]}
173 android-key-download-parameters:
174 revoked-day-packages: ${KEY_DOWNLOAD_REVOKED_DAY_PACKAGES:[]}
175 revoked-hour-packages: ${KEY_DOWNLOAD_REVOKED_HOUR_PACKAGES:[]}
176 download-timeout-in-seconds: ${ANDROID_KEY_DOWNLOAD_DOWNLOAD_TIMEOUT_IN_SECONDS:60}
177 overall-timeout-in-seconds: ${ANDROID_KEY_DOWNLOAD_OVERALL_TIMEOUT_IN_SECONDS:480}
178 ios-exposure-detection-parameters:
179 max-exposure-detections-per-interval: ${IOS_EXPOSURE_DETECTION_MAX_ED_PER_INTERVAL:6}
180 android-exposure-detection-parameters:
181 max-exposure-detections-per-interval: ${ANDROID_EXPOSURE_DETECTION_MAX_ED_PER_INTERVAL:6}
182 overall-timeout-in-seconds: ${ANDROID_EXPOSURE_DETECTION_OVERALL_TIMEOUT_IN_SECONDS:900}
183 ios-event-driven-user-survey-parameters:
184 otp-query-parameter-name: ${EDUS_OTP_QUERY_PARAMETER_NAME:otp}
185 survey-on-high-risk-enabled: ${EDUS_SURVEY_ON_HIGH_RISK_ENABLED:true}
186 survey-on-high-risk-url: ${EDUS_SURVEY_ON_HIGH_RISK_URL:https://befragungen.rki.de/CWABasisbefragung}
187 android-event-driven-user-survey-parameters:
188 otp-query-parameter-name: ${EDUS_OTP_QUERY_PARAMETER_NAME:otp}
189 survey-on-high-risk-enabled: ${EDUS_SURVEY_ON_HIGH_RISK_ENABLED:false}
190 survey-on-high-risk-url: ${EDUS_SURVEY_ON_HIGH_RISK_URL:https://befragungen.rki.de/CWABasisbefragung}
191 require-basic-integrity: ${EDUS_PPAC_REQUIRE_BASIC_INTEGRITY:true}
192 require-cts-profile-match: ${EDUS_PPAC_REQUIRE_CTS_PROFILE_MATCH:true}
193 require-evaluation-type-basic: ${EDUS_PPAC_REQUIRE_EVALUATION_TYPE_BASIC:false}
194 require-evaluation-type-hardware-backed: ${EDUS_PPAC_REQUIRE_EVALUATION_TYPE_HARDWARE_BACKED:true}
195 ios-privacy-preserving-analytics-parameters:
196 probability-to-submit: ${PPA_PROBABILITY_TO_SUBMT:1}
197 probability-to-submit-exposure-windows: ${PPA_PROBABILOITY_TO_SUBMIT_EXPOSURE_WINDOWS:1}
198 hours-since-test-registration-to-submit-test-result-metadata: ${PPA_HOURS_SINCE_TEST_RESULT_TO_SUBMIT_KEY_RESULT_METADATA:165}
199 hours-since-test-to-submit-key-submission-metadata: ${PPA_HOURS_SINCE_TEST_RESULT_TO_SUBMIT_KEY_SUBMISSION_METADATA:36}
200 android-privacy-preserving-analytics-parameters:
201 probability-to-submit: ${PPA_PROBABILITY_TO_SUBMT:1}
202 probability-to-submit-exposure-windows: ${PPA_PROBABILOITY_TO_SUBMIT_EXPOSURE_WINDOWS:1}
203 hours-since-test-registration-to-submit-test-result-metadata: ${PPA_HOURS_SINCE_TEST_RESULT_TO_SUBMIT_KEY_RESULT_METADATA:165}
204 hours-since-test-to-submit-key-submission-metadata: ${PPA_HOURS_SINCE_TEST_RESULT_TO_SUBMIT_KEY_SUBMISSION_METADATA:36}
205 require-basic-integrity: ${PPA_PPAC_REQUIRE_BASIC_INTEGRITY:false}
206 require-cts-profile-match: ${PPA_PPAC_REQUIRE_CTS_PROFILE_MATCH:false}
207 require-evaluation-type-basic: ${PPA_PPAC_REQUIRE_EVALUATION_TYPE_BASIC:false}
208 require-evaluation-type-hardware-backed: ${PPA_PPAC_REQUIRE_EVALUATION_TYPE_HARDWARE_BACKED:false}
209 ios-qr-code-poster-template:
210 published-archive-name: qr_code_poster_template_ios
211 template: ${EVREG_QR_CODE_POSTER_TEMPLATE_IOS_FILE:}
212 offsetX: ${EVREG_QR_CODE_POSTER_TEMPLATE_IOS_OFFSET_X:97}
213 offsetY: ${EVREG_QR_CODE_POSTER_TEMPLATE_IOS_OFFSET_Y:82}
214 qr-code-side-length: ${EVREG_QR_CODE_POSTER_TEMPLATE_IOS_QR_CODE_SIDE_LENGTH:400}
215 description-text-box:
216 offsetX: ${EVREG_QR_CODE_POSTER_TEMPLATE_IOS_DESCRIPTION_OFFSET_X:80}
217 offsetY: ${EVREG_QR_CODE_POSTER_TEMPLATE_IOS_DESCRIPTION_OFFSET_Y:510}
218 width: ${EVREG_QR_CODE_POSTER_TEMPLATE_IOS_DESCRIPTION_WIDTH:420}
219 height: ${EVREG_QR_CODE_POSTER_TEMPLATE_IOS_DESCRIPTION_HEIGHT:15}
220 fontSize: ${EVREG_QR_CODE_POSTER_TEMPLATE_IOS_DESCRIPTION_FONT_SIZE:10}
221 fontColor: ${EVREG_QR_CODE_POSTER_TEMPLATE_IOS_DESCRIPTION_FONT_COLOR:#000000}
222 address-text-box:
223 offsetX: ${EVREG_QR_CODE_POSTER_TEMPLATE_IOS_ADDRESS_OFFSET_X:80}
224 offsetY: ${EVREG_QR_CODE_POSTER_TEMPLATE_IOS_ADDRESS_OFFSET_Y:525}
225 width: ${EVREG_QR_CODE_POSTER_TEMPLATE_IOS_ADDRESS_WIDTH:420}
226 height: ${EVREG_QR_CODE_POSTER_TEMPLATE_IOS_ADDRESS_HEIGHT:15}
227 fontSize: ${EVREG_QR_CODE_POSTER_TEMPLATE_IOS_ADDRESS_FONT_SIZE:10}
228 fontColor: ${EVREG_QR_CODE_POSTER_TEMPLATE_IOS_ADDRESS_FONT_COLOR:#000000}
229 android-qr-code-poster-template:
230 published-archive-name: qr_code_poster_template_android
231 template: ${EVREG_QR_CODE_POSTER_TEMPLATE_ANDROID_FILE:}
232 offsetX: ${EVREG_QR_CODE_POSTER_TEMPLATE_ANDROID_OFFSET_X:0.16}
233 offsetY: ${EVREG_QR_CODE_POSTER_TEMPLATE_ANDROID_OFFSET_Y:0.095}
234 qr-code-side-length: ${EVREG_QR_CODE_POSTER_TEMPLATE_ANDROID_QR_CODE_SIDE_LENGTH:1000}
235 description-text-box:
236 offsetX: ${EVREG_QR_CODE_POSTER_TEMPLATE_ANDROID_DESCRIPTION_OFFSET_X:0.132}
237 offsetY: ${EVREG_QR_CODE_POSTER_TEMPLATE_ANDROID_DESCRIPTION_OFFSET_Y:0.61}
238 width: ${EVREG_QR_CODE_POSTER_TEMPLATE_ANDROID_DESCRIPTION_WIDTH:100}
239 height: ${EVREG_QR_CODE_POSTER_TEMPLATE_ANDROID_DESCRIPTION_HEIGHT:20}
240 font-size: ${EVREG_QR_CODE_POSTER_TEMPLATE_ANDROID_DESCRIPTION_FONT_SIZE:10}
241 font-color: ${EVREG_QR_CODE_POSTER_TEMPLATE_ANDROID_DESCRIPTION_FONT_COLOR:#000000}
242 presence-tracing-parameters:
243 qr-code-error-correction-level: ${EVREG_QR_CODE_ERROR_CORRECTION_LEVEL:0}
244 plausible-deniability-parameters:
245 probability-to-fake-check-ins-if-no-check-ins: ${EVREG_PROBABILITY_TO_FAKE_CHECK_INS_IF_NO_CHECK_INS:0}
246 probability-to-fake-check-ins-if-some-check-ins: ${EVREG_PROBABILITY_TO_FAKE_CHECK_INS_IF_SOME_CHECK_INS:0.005}
247 digital-green-certificate:
248 mah-json-path: ${DIGITAL_GREEN_CERTIFICATE_MAH_JSON_PATH:}
249 prophylaxis-json-path: ${DIGITAL_GREEN_CERTIFICATE_PROPHYLAXIS_JSON_PATH:}
250 medicinal-products-json-path: ${DIGITAL_GREEN_CERTIFICATE_MEDICINAL_PRODUCTS_JSON_PATH:}
251 disease-agent-targeted-path: ${DIGITAL_GREEN_CERTIFICATE_DISEASE_AGENT_TARGETED_JSON_PATH:}
252 test-manf-path: ${DIGITAL_GREEN_CERTIFICATE_TEST_MANF_JSON_PATH:}
253 test-result-path: ${DIGITAL_GREEN_CERTIFICATE_TEST_RESULT_JSON_PATH:}
254 test-type-path: ${DIGITAL_GREEN_CERTIFICATE_TEST_TYPE_JSON_PATH:}
255 dgc-directory: ${DIGITAL_GREEN_CERTIFICATE_DIRECTORY:ehn-dgc}
256 valuesets-file-name: ${DIGITAL_GREEN_CERTIFICATE_VALUESETS_FILE_NAME:value-sets}
257 supported-languages: ${DIGITAL_GREEN_CERTIFICATE_SUPPORTED_LANGUAGES:de, en, bg, pl, ro, tr, uk}
258 booster-notification: ${BOOSTER_NOTIFICATION_DIRECTORY:booster-notification-rules}
259 export-archive-name: ${DIGITAL_GREEN_CERTIFICATE_ARCHIVE_NAME:export.bin}
260 allow-list: ${DCC_VALIDATION_SERVICE_ALLOWLIST}
261 allow-list-signature: ${DCC_VALIDATION_SERVICE_ALLOWLIST_SIGNATURE}
262 allow-list-certificate: ${DCC_VALIDATION_SERVICE_ALLOWLIST_CERTIFICATE}
263 ccl-directory: ${COMMON_COVID_LOGIC:ccl}
264 ccl-allow-list: ${CCL_ALLOW_LIST:CCL-DE-0001}
265 dsc-client:
266 public-key: ${DSC_PUBLIC_KEY:MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEIxHvrv8jQx9OEzTZbsx1prQVQn/3ex0gMYf6GyaNBW0QKLMjrSDeN6HwSPM0QzhvhmyQUixl6l88A7Zpu5OWSw==}
267 base-url: ${DSC_BASE_PATH:https://de.dscg.ubirch.com}
268 dsc-list-path: ${DSC_LIST_PATH:/trustList/DSC/}
269 ssl:
270 trust-store: ${DSC_TRUST_STORE:../../docker-compose-test-secrets/dsc_truststore}
271 trust-store-password: ${DSC_TRUST_STORE_PASSWORD:123456}
272 client:
273 public-key: ${DCC_PUBLIC_KEY:MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEnQmn1s+sTWqFPuRhqFRide7HD52SrsD01ZdX4cxN1r0pnZ0Zh7JNwZxmXlOQW5NDVlPdHq2QcD06gmP/10QizA==}
274 retry-period: 2
275 max-retry-period: 5
276 max-retry-attempts: 2
277 base-url: ${BUSSINESS_RULES_BASE_PATH:https://distribution.dcc-rules.de/}
278 country-list-path: ${BUSSINESS_RULES_COUNTRY_LIST_PATH:/countrylist}
279 value-sets-path: ${BUSSINESS_RULES_VALUE_SETS_PATH:/valuesets}
280 rules-path: ${BUSSINESS_RULES_RULES_PATH:/rules}
281 bn-rules-path: ${BUSSINESS_RULES_BN_RULES_PATH:/bnrules}
282 ccl-rules-path: ${COMMON_COVID_LOGIC:/cclrules}
283 ssl:
284 trust-store: ${DCC_TRUST_STORE:../../docker-compose-test-secrets/dcc_truststore}
285 trust-store-password: ${DCC_TRUST_STORE_PASSWORD:123456}
286 dcc-revocation:
287 client:
288 public-key: ${DCC_REVOCATION_LIST_PUBLIC_KEY:MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE6Ft4aTjScTpsvY0tg2Lx0AK0Ih3Z2VKXnyBvoZxngB9cXmNtTg+Va3fY3QJduf+OXaWsE34xvMTIHxw+MpOLkw==}
289 base-url: ${DCC_REV_BASE_PATH:https://de.crl.dscg.ubirch.com}
290 ssl:
291 trust-store: ${DCC_REV_TRUST_STORE:../../docker-compose-test-secrets/dcc_rev_truststore}
292 trust-store-password: ${DCC_REV_TRUST_STORE_PASSWORD:testtest}
293 retry-period: 2
294 max-retry-period: 5
295 max-retry-attempts: 2
296 dcc-list-path: /chunk.lst
297 dcc-revocation-directory: dcc-rl
298 certificate: ${DCC_REVOCATION_LIST_CERTIFICATE}
299 spring:
300 main:
301 web-application-type: NONE
302 # Postgres configuration
303 flyway:
304 enabled: true
305 locations: classpath:/db/migration, classpath:/db/specific/{vendor}
306 password: ${POSTGRESQL_PASSWORD_FLYWAY:local_setup_flyway}
307 user: ${POSTGRESQL_USER_FLYWAY:local_setup_flyway}
308
309 datasource:
310 driver-class-name: org.postgresql.Driver
311 url: jdbc:postgresql://${POSTGRESQL_SERVICE_HOST}:${POSTGRESQL_SERVICE_PORT}/${POSTGRESQL_DATABASE}?ssl=true&sslmode=verify-full&sslrootcert=${SSL_POSTGRES_CERTIFICATE_PATH}&sslcert=${SSL_DISTRIBUTION_CERTIFICATE_PATH}&sslkey=${SSL_DISTRIBUTION_PRIVATE_KEY_PATH}
312 username: ${POSTGRESQL_USER_DISTRIBUTION:local_setup_distribution}
313 password: ${POSTGRESQL_PASSWORD_DISTRIBUTION:local_setup_distribution}
314
[end of services/distribution/src/main/resources/application.yaml]
</code>
Here is an example of a patch file. It consists of changes to the code base. It specifies the file names, the line numbers of each change, and the removed and added lines. A single patch file can contain changes to multiple files.
<patch>
--- a/file.py
+++ b/file.py
@@ -1,27 +1,35 @@
def euclidean(a, b):
- while b:
- a, b = b, a % b
- return a
+ if b == 0:
+ return a
+ return euclidean(b, a % b)
def bresenham(x0, y0, x1, y1):
points = []
dx = abs(x1 - x0)
dy = abs(y1 - y0)
- sx = 1 if x0 < x1 else -1
- sy = 1 if y0 < y1 else -1
- err = dx - dy
+ x, y = x0, y0
+ sx = -1 if x0 > x1 else 1
+ sy = -1 if y0 > y1 else 1
- while True:
- points.append((x0, y0))
- if x0 == x1 and y0 == y1:
- break
- e2 = 2 * err
- if e2 > -dy:
+ if dx > dy:
+ err = dx / 2.0
+ while x != x1:
+ points.append((x, y))
err -= dy
- x0 += sx
- if e2 < dx:
- err += dx
- y0 += sy
+ if err < 0:
+ y += sy
+ err += dx
+ x += sx
+ else:
+ err = dy / 2.0
+ while y != y1:
+ points.append((x, y))
+ err -= dx
+ if err < 0:
+ x += sx
+ err += dy
+ y += sy
+ points.append((x, y))
return points
</patch>
I need you to solve the provded issue by generating a single patch file that I can apply directly to this repository using git apply. Please respond with a single patch file in the format shown above.
Respond below:
| corona-warn-app/cwa-server | f20af0764008b8ef07ba67c3b26693115035c43f | min-android 1.5.1 differs from production 1.0.4 value
## Describe the bug
The `min-android` value served on
https://svc90.main.px.t-online.de/version/v1/configuration/country/DE/app_config is
`1.0.4`
which differs from the value
`1.5.1`
stored in https://github.com/corona-warn-app/cwa-server/blob/main/services/distribution/src/main/resources/application.yaml#L144
If CWA Android 1.4.0 is started, there is no prompt shown to the user that the app should be updated.
## Expected behaviour
The `min-android` value served on
https://svc90.main.px.t-online.de/version/v1/configuration/country/DE/app_config should be the same as the value stored in https://github.com/corona-warn-app/cwa-server/blob/main/services/distribution/src/main/resources/application.yaml#L144 which is currently `1.5.1`.
If `min-android` with the value of `1.5.1` were in production then starting CWA Android 1.4.0 should produce a prompt to update the app.
## Steps to reproduce the issue
1. In Android Studio check out CWA Android app release/1.4.x
2. Run CWA on Pixel 3a API 33 Android device emulator in Debug mode
3. Open Logcat in Android Studio and enter search term "UpdateChecker"
The log shows the following:
```
UpdateChecker de.rki.coronawarnapp.dev E minVersionStringFromServer:1.0.4
UpdateChecker de.rki.coronawarnapp.dev E Current app version:1.4.0
UpdateChecker de.rki.coronawarnapp.dev E needs update:false
```
Alternatively install old released versions from https://www.apkmirror.com/apk/robert-koch-institut/corona-warn-app/. As soon as a version < 1.0.4 is started, e.g. 1.0.0 or 1.0.2, a message "Update available" is output.
![Update available](https://user-images.githubusercontent.com/66998419/202911146-6b74b2e4-7a8d-462d-8f19-6e10762719e2.jpg)
If version 1.0.4 is installed and started, no update message is output. This is consistent with min-Android being set to `1.0.4` in production.
## Technical details
- Android Studio Dolphin | 2021.3.1 Patch 1
- Pixel 3a API 33 Android device emulator
- CWA Android 1.4.0 (note that this version was not released. Version 1.5 followed version 1.3)
## Possible Fix
Clarify what the minimum enforced version of CWA Android in production is supposed to be and ensure alignment of https://github.com/corona-warn-app/cwa-server/blob/main/services/distribution/src/main/resources/application.yaml with the values used in production.
| - FYI: I opened https://github.com/corona-warn-app/cwa-server/issues/1963 asking the team to check for other differences between this repositories `main` branch & the production environment.
Also I would expect `min-android-version-code` / `minVersionCode=48` and not `31` to be served. | 2022-11-21T14:08:50 | <patch>
diff --git a/services/distribution/src/main/resources/application.yaml b/services/distribution/src/main/resources/application.yaml
--- a/services/distribution/src/main/resources/application.yaml
+++ b/services/distribution/src/main/resources/application.yaml
@@ -140,11 +140,11 @@ services:
app-versions:
latest-ios: ${IOS_LATEST_VERSION:1.5.3}
min-ios: ${IOS_MIN_VERSION:1.5.3}
- latest-android: ${ANDROID_LATEST_VERSION:1.5.1}
- min-android: ${ANDROID_MIN_VERSION:1.5.1}
+ latest-android: ${ANDROID_LATEST_VERSION:1.0.4}
+ min-android: ${ANDROID_MIN_VERSION:1.0.4}
# With ENF v2 Android apps are versioned by Version Code and not by Semantic Versioning
- min-android-version-code: ${ANDROID_MIN_VERSION_CODE:48}
- latest-android-version-code: ${ANDROID_LATEST_VERSION_CODE:48}
+ min-android-version-code: ${ANDROID_MIN_VERSION_CODE:31}
+ latest-android-version-code: ${ANDROID_LATEST_VERSION_CODE:31}
app-config-parameters:
dgcParameters:
testCertificateParameters:
</patch> | diff --git a/services/distribution/src/test/resources/application-allow-list-invalid.yaml b/services/distribution/src/test/resources/application-allow-list-invalid.yaml
--- a/services/distribution/src/test/resources/application-allow-list-invalid.yaml
+++ b/services/distribution/src/test/resources/application-allow-list-invalid.yaml
@@ -83,10 +83,10 @@ services:
app-versions:
latest-ios: ${IOS_LATEST_VERSION:1.5.3}
min-ios: ${IOS_MIN_VERSION:1.5.3}
- latest-android: ${ANDROID_LATEST_VERSION:1.5.1}
- min-android: ${ANDROID_MIN_VERSION:1.5.1}
- min-android-version-code: ${ANDROID_MIN_VERSION_CODE:48}
- latest-android-version-code: ${ANDROID_LATEST_VERSION_CODE:48}
+ latest-android: ${ANDROID_LATEST_VERSION:1.0.4}
+ min-android: ${ANDROID_MIN_VERSION:1.0.4}
+ min-android-version-code: ${ANDROID_MIN_VERSION_CODE:31}
+ latest-android-version-code: ${ANDROID_LATEST_VERSION_CODE:31}
app-config-parameters:
dgcParameters:
testCertificateParameters:
diff --git a/services/distribution/src/test/resources/application.yaml b/services/distribution/src/test/resources/application.yaml
--- a/services/distribution/src/test/resources/application.yaml
+++ b/services/distribution/src/test/resources/application.yaml
@@ -98,10 +98,10 @@ services:
app-versions:
latest-ios: ${IOS_LATEST_VERSION:1.5.3}
min-ios: ${IOS_MIN_VERSION:1.5.3}
- latest-android: ${ANDROID_LATEST_VERSION:1.5.1}
- min-android: ${ANDROID_MIN_VERSION:1.5.1}
- min-android-version-code: ${ANDROID_MIN_VERSION_CODE:48}
- latest-android-version-code: ${ANDROID_LATEST_VERSION_CODE:48}
+ latest-android: ${ANDROID_LATEST_VERSION:1.0.4}
+ min-android: ${ANDROID_MIN_VERSION:1.0.4}
+ min-android-version-code: ${ANDROID_MIN_VERSION_CODE:31}
+ latest-android-version-code: ${ANDROID_LATEST_VERSION_CODE:31}
app-config-parameters:
dgcParameters:
testCertificateParameters:
| ||||
corona-warn-app__cwa-server-406 | You will be provided with a partial code base and an issue statement explaining a problem to resolve.
<issue>
Aggregate File Creation: Skip packages if payload too small
Change the aggregate file creation logic in a way, in which packages are skipped in case the payload (amount of keys) is too small. The threshold should be configurable, and defaulted to 50 for now.
</issue>
<code>
[start of README.md]
1 <!-- markdownlint-disable MD041 -->
2 <h1 align="center">
3 Corona-Warn-App Server
4 </h1>
5
6 <p align="center">
7 <a href="https://github.com/corona-warn-app/cwa-server/commits/" title="Last Commit"><img src="https://img.shields.io/github/last-commit/corona-warn-app/cwa-server?style=flat"></a>
8 <a href="https://github.com/corona-warn-app/cwa-server/issues" title="Open Issues"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat"></a>
9 <a href="https://circleci.com/gh/corona-warn-app/cwa-server" title="Build Status"><img src="https://circleci.com/gh/corona-warn-app/cwa-server.svg?style=shield&circle-token=4ab059989d10709df19eb4b98ab7c121a25e981a"></a>
10 <a href="https://sonarcloud.io/dashboard?id=corona-warn-app_cwa-server" title="Quality Gate"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=alert_status"></a>
11 <a href="https://sonarcloud.io/component_measures?id=corona-warn-app_cwa-server&metric=Coverage&view=list" title="Coverage"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=coverage"></a>
12 <a href="https://github.com/corona-warn-app/cwa-server/blob/master/LICENSE" title="License"><img src="https://img.shields.io/badge/License-Apache%202.0-green.svg?style=flat"></a>
13 </p>
14
15 <p align="center">
16 <a href="#development">Development</a> •
17 <a href="#service-apis">Service APIs</a> •
18 <a href="#documentation">Documentation</a> •
19 <a href="#support-and-feedback">Support</a> •
20 <a href="#how-to-contribute">Contribute</a> •
21 <a href="#contributors">Contributors</a> •
22 <a href="#repositories">Repositories</a> •
23 <a href="#licensing">Licensing</a>
24 </p>
25
26 The goal of this project is to develop the official Corona-Warn-App for Germany based on the exposure notification API from [Apple](https://www.apple.com/covid19/contacttracing/) and [Google](https://www.google.com/covid19/exposurenotifications/). The apps (for both iOS and Android) use Bluetooth technology to exchange anonymous encrypted data with other mobile phones (on which the app is also installed) in the vicinity of an app user's phone. The data is stored locally on each user's device, preventing authorities or other parties from accessing or controlling the data. This repository contains the **implementation of the server for encryption keys** for the Corona-Warn-App. This implementation is still a **work in progress**, and the code it contains is currently alpha-quality code.
27
28 In this documentation, Corona-Warn-App services are also referred to as CWA services.
29
30 ## Architecture Overview
31
32 You can find the architecture overview [here](/docs/architecture-overview.md), which will give you
33 a good starting point in how the backend services interact with other services, and what purpose
34 they serve.
35
36 ## Development
37
38 After you've checked out this repository, you can run the application in one of the following ways:
39
40 * As a [Docker](https://www.docker.com/)-based deployment on your local machine. You can run either:
41 * Single components using the respective Dockerfile or
42 * The full backend using the Docker Compose (which is considered the most convenient way)
43 * As a [Maven](https://maven.apache.org)-based build on your local machine.
44 If you want to develop something in a single component, this approach is preferable.
45
46 ### Docker-Based Deployment
47
48 If you want to use Docker-based deployment, you need to install Docker on your local machine. For more information about downloading and installing Docker, see the [official Docker documentation](https://docs.docker.com/get-docker/).
49
50 #### Running the Full CWA Backend Using Docker Compose
51
52 For your convenience, a full setup including the generation of test data has been prepared using [Docker Compose](https://docs.docker.com/compose/reference/overview/). To build the backend services, run ```docker-compose build``` in the repository's root directory. A default configuration file can be found under ```.env```in the root folder of the repository. The default values for the local Postgres and Zenko Cloudserver should be changed in this file before docker-compose is run.
53
54 Once the services are built, you can start the whole backend using ```docker-compose up```.
55 The distribution service runs once and then finishes. If you want to trigger additional distribution runs, run ```docker-compose run distribution```.
56
57 The docker-compose contains the following services:
58
59 Service | Description | Endpoint and Default Credentials
60 ------------------|-------------|-----------
61 submission | The Corona-Warn-App submission service | `http://localhost:8000` <br> `http://localhost:8006` (for actuator endpoint)
62 distribution | The Corona-Warn-App distribution service | NO ENDPOINT
63 postgres | A [postgres] database installation | `postgres:8001` <br> Username: postgres <br> Password: postgres
64 pgadmin | A [pgadmin](https://www.pgadmin.org/) installation for the postgres database | `http://localhost:8002` <br> Username: [email protected] <br> Password: password
65 cloudserver | [Zenko CloudServer] is a S3-compliant object store | `http://localhost:8003/` <br> Access key: accessKey1 <br> Secret key: verySecretKey1
66 verification-fake | A very simple fake implementation for the tan verification. | `http://localhost:8004/version/v1/tan/verify` <br> The only valid tan is "edc07f08-a1aa-11ea-bb37-0242ac130002"
67
68 ##### Known Limitation
69
70 In rare cases the docker-compose runs into a timing issue if the distribution service starts before the bucket of the objectstore was created. This is not a big issue as you can simply run ```docker-compose run distribution``` to trigger additional distribution runs after the objectstore was initialized.
71
72 #### Running Single CWA Services Using Docker
73
74 If you would like to build and run a single CWA service, it's considered easiest to run them in a Docker environment. You can do this using the script provided in the respective CWA service directory. The Docker script first builds the CWA service and then creates an image for the runtime, which means that there are no additional dependencies for you to install.
75
76 To build and run the distribution service, run the following command:
77
78 ```bash
79 ./services/distribution/build_and_run.sh
80 ```
81
82 To build and run the submission service, run the following command:
83
84 ```bash
85 ./services/submission/build_and_run.sh
86 ```
87
88 The submission service is available on [localhost:8080](http://localhost:8080 ).
89
90 ### Maven-Based Build
91
92 If you want to actively develop in one of the CWA services, the Maven-based runtime is most suitable.
93 To prepare your machine to run the CWA project locally, we recommend that you first ensure that you've installed the following:
94
95 * Minimum JDK Version 11: [OpenJDK](https://openjdk.java.net/) / [SapMachine](https://sap.github.io/SapMachine/)
96 * [Maven 3.6](https://maven.apache.org/)
97 * [Postgres]
98 * [Zenko CloudServer]
99
100 #### Configure
101
102 After you made sure that the specified dependencies are running, configure them in the respective configuration files.
103
104 * Configure the Postgres connection in the [submission config](./services/submission/src/main/resources/application.yaml) and in the [distribution config](./services/distribution/src/main/resources/application.yaml)
105 * Configure the S3 compatible object storage in the [distribution config](./services/distribution/src/main/resources/application.yaml)
106 * Configure the private key for the distribution service, the path need to be prefixed with `file:`
107 * `VAULT_FILESIGNING_SECRET` should be the path to the private key, example available in `<repo-root>/docker-compose-test-secrets/private.pem`
108
109 #### Build
110
111 After you've checked out the repository, to build the project, run ```mvn install``` in your base directory.
112
113 #### Run
114
115 Navigate to the service you want to start and run the spring-boot:run target. The configured Postgres and the configured S3 compliant object storage are used as default. When you start the submission service, the endpoint is available on your local port 8080.
116
117 If you want to start the submission service, for example, you start it as follows:
118
119 ```bash
120 cd services/submission/
121 mvn spring-boot:run
122 ```
123
124 #### Debugging
125
126 To enable the `DEBUG` log level, you can run the application using the Spring `dev` profile.
127
128 ```bash
129 mvn spring-boot:run -Dspring-boot.run.profiles=dev
130 ```
131
132 To be able to set breakpoints (e.g. in IntelliJ), it may be necessary to use the ```-Dspring-boot.run.fork=false``` parameter.
133
134 ## Service APIs
135
136 The API that is being exposed by the backend services is documented in an [OpenAPI](https://www.openapis.org/) specification. The specification files are available at the following locations:
137
138 Service | OpenAPI Specification
139 -------------|-------------
140 Submission Service | [services/submission/api_v1.json](https://github.com/corona-warn-app/cwa-server/raw/master/services/submission/api_v1.json)
141 Distribution Service | [services/distribution/api_v1.json](https://github.com/corona-warn-app/cwa-server/raw/master/services/distribution/api_v1.json)
142
143 ## Spring Profiles
144
145 ### Distribution
146
147 Profile | Effect
148 -----------------|-------------
149 `dev` | Turns the log level to `DEBUG`.
150 `cloud` | Removes default values for the `datasource` and `objectstore` configurations.
151 `demo` | Includes incomplete days and hours into the distribution run, thus creating aggregates for the current day and the current hour (and including both in the respective indices). When running multiple distributions in one hour with this profile, the date aggregate for today and the hours aggregate for the current hour will be updated and overwritten.
152 `testdata` | Causes test data to be inserted into the database before each distribution run. By default, around 1000 random diagnosis keys will be generated per hour. If there are no diagnosis keys in the database yet, random keys will be generated for every hour from the beginning of the retention period (14 days ago at 00:00 UTC) until one hour before the present hour. If there are already keys in the database, the random keys will be generated for every hour from the latest diagnosis key in the database (by submission timestamp) until one hour before the present hour (or none at all, if the latest diagnosis key in the database was submitted one hour ago or later).
153 `signature-dev` | Sets the app package ID in the export packages' signature info to `de.rki.coronawarnapp-dev` so that test certificates (instead of production certificates) will be used for client-side validation.
154 `signature-prod` | Provides production app package IDs for the signature info
155
156 ### Submission
157
158 Profile | Effect
159 -------------|-------------
160 `dev` | Turns the log level to `DEBUG`.
161 `cloud` | Removes default values for the `datasource` configuration.
162
163 ## Documentation
164
165 The full documentation for the Corona-Warn-App can be found in the [cwa-documentation](https://github.com/corona-warn-app/cwa-documentation) repository. The documentation repository contains technical documents, architecture information, and whitepapers related to this implementation.
166
167 ## Support and Feedback
168
169 The following channels are available for discussions, feedback, and support requests:
170
171 | Type | Channel |
172 | ------------------------ | ------------------------------------------------------ |
173 | **General Discussion** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="General Discussion"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/question.svg?style=flat-square"></a> </a> |
174 | **Concept Feedback** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="Open Concept Feedback"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/architecture.svg?style=flat-square"></a> |
175 | **Backend Issue** | <a href="https://github.com/corona-warn-app/cwa-server/issues/new/choose" title="Open Backend Issue"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat-square"></a> |
176 | **Other Requests** | <a href="mailto:[email protected]" title="Email CWA Team"><img src="https://img.shields.io/badge/email-CWA%20team-green?logo=mail.ru&style=flat-square&logoColor=white"></a> |
177
178 ## How to Contribute
179
180 Contribution and feedback are 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.
181
182 ## Contributors
183
184 The German government has asked SAP and Deutsche Telekom to develop the Corona-Warn-App for Germany as open source software. Deutsche Telekom is providing the network and mobile technology and will operate and run the backend for the app in a safe, scalable and stable manner. SAP is responsible for the app development, its framework and the underlying platform. Therefore, development teams of SAP and Deutsche Telekom are contributing to this project. At the same time 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.
185
186 ## Repositories
187
188 The following public repositories are currently available for the Corona-Warn-App:
189
190 | Repository | Description |
191 | ------------------- | --------------------------------------------------------------------- |
192 | [cwa-documentation] | Project overview, general documentation, and white papers |
193 | [cwa-server] | Backend implementation for the Apple/Google exposure notification API|
194 | [cwa-verification-server] | Backend implementation of the verification process|
195
196 [cwa-documentation]: https://github.com/corona-warn-app/cwa-documentation
197 [cwa-server]: https://github.com/corona-warn-app/cwa-server
198 [cwa-verification-server]: https://github.com/corona-warn-app/cwa-verification-server
199 [Postgres]: https://www.postgresql.org/
200 [HSQLDB]: http://hsqldb.org/
201 [Zenko CloudServer]: https://github.com/scality/cloudserver
202
203 ## Licensing
204
205 Copyright (c) 2020 SAP SE or an SAP affiliate company.
206
207 Licensed under the **Apache License, Version 2.0** (the "License"); you may not use this file except in compliance with the License.
208
209 You may obtain a copy of the License at <https://www.apache.org/licenses/LICENSE-2.0>.
210
211 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.
212
[end of README.md]
[start of /dev/null]
1
[end of /dev/null]
[start of README.md]
1 <!-- markdownlint-disable MD041 -->
2 <h1 align="center">
3 Corona-Warn-App Server
4 </h1>
5
6 <p align="center">
7 <a href="https://github.com/corona-warn-app/cwa-server/commits/" title="Last Commit"><img src="https://img.shields.io/github/last-commit/corona-warn-app/cwa-server?style=flat"></a>
8 <a href="https://github.com/corona-warn-app/cwa-server/issues" title="Open Issues"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat"></a>
9 <a href="https://circleci.com/gh/corona-warn-app/cwa-server" title="Build Status"><img src="https://circleci.com/gh/corona-warn-app/cwa-server.svg?style=shield&circle-token=4ab059989d10709df19eb4b98ab7c121a25e981a"></a>
10 <a href="https://sonarcloud.io/dashboard?id=corona-warn-app_cwa-server" title="Quality Gate"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=alert_status"></a>
11 <a href="https://sonarcloud.io/component_measures?id=corona-warn-app_cwa-server&metric=Coverage&view=list" title="Coverage"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=coverage"></a>
12 <a href="https://github.com/corona-warn-app/cwa-server/blob/master/LICENSE" title="License"><img src="https://img.shields.io/badge/License-Apache%202.0-green.svg?style=flat"></a>
13 </p>
14
15 <p align="center">
16 <a href="#development">Development</a> •
17 <a href="#service-apis">Service APIs</a> •
18 <a href="#documentation">Documentation</a> •
19 <a href="#support-and-feedback">Support</a> •
20 <a href="#how-to-contribute">Contribute</a> •
21 <a href="#contributors">Contributors</a> •
22 <a href="#repositories">Repositories</a> •
23 <a href="#licensing">Licensing</a>
24 </p>
25
26 The goal of this project is to develop the official Corona-Warn-App for Germany based on the exposure notification API from [Apple](https://www.apple.com/covid19/contacttracing/) and [Google](https://www.google.com/covid19/exposurenotifications/). The apps (for both iOS and Android) use Bluetooth technology to exchange anonymous encrypted data with other mobile phones (on which the app is also installed) in the vicinity of an app user's phone. The data is stored locally on each user's device, preventing authorities or other parties from accessing or controlling the data. This repository contains the **implementation of the server for encryption keys** for the Corona-Warn-App. This implementation is still a **work in progress**, and the code it contains is currently alpha-quality code.
27
28 In this documentation, Corona-Warn-App services are also referred to as CWA services.
29
30 ## Architecture Overview
31
32 You can find the architecture overview [here](/docs/architecture-overview.md), which will give you
33 a good starting point in how the backend services interact with other services, and what purpose
34 they serve.
35
36 ## Development
37
38 After you've checked out this repository, you can run the application in one of the following ways:
39
40 * As a [Docker](https://www.docker.com/)-based deployment on your local machine. You can run either:
41 * Single components using the respective Dockerfile or
42 * The full backend using the Docker Compose (which is considered the most convenient way)
43 * As a [Maven](https://maven.apache.org)-based build on your local machine.
44 If you want to develop something in a single component, this approach is preferable.
45
46 ### Docker-Based Deployment
47
48 If you want to use Docker-based deployment, you need to install Docker on your local machine. For more information about downloading and installing Docker, see the [official Docker documentation](https://docs.docker.com/get-docker/).
49
50 #### Running the Full CWA Backend Using Docker Compose
51
52 For your convenience, a full setup including the generation of test data has been prepared using [Docker Compose](https://docs.docker.com/compose/reference/overview/). To build the backend services, run ```docker-compose build``` in the repository's root directory. A default configuration file can be found under ```.env```in the root folder of the repository. The default values for the local Postgres and Zenko Cloudserver should be changed in this file before docker-compose is run.
53
54 Once the services are built, you can start the whole backend using ```docker-compose up```.
55 The distribution service runs once and then finishes. If you want to trigger additional distribution runs, run ```docker-compose run distribution```.
56
57 The docker-compose contains the following services:
58
59 Service | Description | Endpoint and Default Credentials
60 ------------------|-------------|-----------
61 submission | The Corona-Warn-App submission service | `http://localhost:8000` <br> `http://localhost:8006` (for actuator endpoint)
62 distribution | The Corona-Warn-App distribution service | NO ENDPOINT
63 postgres | A [postgres] database installation | `postgres:8001` <br> Username: postgres <br> Password: postgres
64 pgadmin | A [pgadmin](https://www.pgadmin.org/) installation for the postgres database | `http://localhost:8002` <br> Username: [email protected] <br> Password: password
65 cloudserver | [Zenko CloudServer] is a S3-compliant object store | `http://localhost:8003/` <br> Access key: accessKey1 <br> Secret key: verySecretKey1
66 verification-fake | A very simple fake implementation for the tan verification. | `http://localhost:8004/version/v1/tan/verify` <br> The only valid tan is "edc07f08-a1aa-11ea-bb37-0242ac130002"
67
68 ##### Known Limitation
69
70 In rare cases the docker-compose runs into a timing issue if the distribution service starts before the bucket of the objectstore was created. This is not a big issue as you can simply run ```docker-compose run distribution``` to trigger additional distribution runs after the objectstore was initialized.
71
72 #### Running Single CWA Services Using Docker
73
74 If you would like to build and run a single CWA service, it's considered easiest to run them in a Docker environment. You can do this using the script provided in the respective CWA service directory. The Docker script first builds the CWA service and then creates an image for the runtime, which means that there are no additional dependencies for you to install.
75
76 To build and run the distribution service, run the following command:
77
78 ```bash
79 ./services/distribution/build_and_run.sh
80 ```
81
82 To build and run the submission service, run the following command:
83
84 ```bash
85 ./services/submission/build_and_run.sh
86 ```
87
88 The submission service is available on [localhost:8080](http://localhost:8080 ).
89
90 ### Maven-Based Build
91
92 If you want to actively develop in one of the CWA services, the Maven-based runtime is most suitable.
93 To prepare your machine to run the CWA project locally, we recommend that you first ensure that you've installed the following:
94
95 * Minimum JDK Version 11: [OpenJDK](https://openjdk.java.net/) / [SapMachine](https://sap.github.io/SapMachine/)
96 * [Maven 3.6](https://maven.apache.org/)
97 * [Postgres]
98 * [Zenko CloudServer]
99
100 #### Configure
101
102 After you made sure that the specified dependencies are running, configure them in the respective configuration files.
103
104 * Configure the Postgres connection in the [submission config](./services/submission/src/main/resources/application.yaml) and in the [distribution config](./services/distribution/src/main/resources/application.yaml)
105 * Configure the S3 compatible object storage in the [distribution config](./services/distribution/src/main/resources/application.yaml)
106 * Configure the private key for the distribution service, the path need to be prefixed with `file:`
107 * `VAULT_FILESIGNING_SECRET` should be the path to the private key, example available in `<repo-root>/docker-compose-test-secrets/private.pem`
108
109 #### Build
110
111 After you've checked out the repository, to build the project, run ```mvn install``` in your base directory.
112
113 #### Run
114
115 Navigate to the service you want to start and run the spring-boot:run target. The configured Postgres and the configured S3 compliant object storage are used as default. When you start the submission service, the endpoint is available on your local port 8080.
116
117 If you want to start the submission service, for example, you start it as follows:
118
119 ```bash
120 cd services/submission/
121 mvn spring-boot:run
122 ```
123
124 #### Debugging
125
126 To enable the `DEBUG` log level, you can run the application using the Spring `dev` profile.
127
128 ```bash
129 mvn spring-boot:run -Dspring-boot.run.profiles=dev
130 ```
131
132 To be able to set breakpoints (e.g. in IntelliJ), it may be necessary to use the ```-Dspring-boot.run.fork=false``` parameter.
133
134 ## Service APIs
135
136 The API that is being exposed by the backend services is documented in an [OpenAPI](https://www.openapis.org/) specification. The specification files are available at the following locations:
137
138 Service | OpenAPI Specification
139 -------------|-------------
140 Submission Service | [services/submission/api_v1.json](https://github.com/corona-warn-app/cwa-server/raw/master/services/submission/api_v1.json)
141 Distribution Service | [services/distribution/api_v1.json](https://github.com/corona-warn-app/cwa-server/raw/master/services/distribution/api_v1.json)
142
143 ## Spring Profiles
144
145 ### Distribution
146
147 Profile | Effect
148 -----------------|-------------
149 `dev` | Turns the log level to `DEBUG`.
150 `cloud` | Removes default values for the `datasource` and `objectstore` configurations.
151 `demo` | Includes incomplete days and hours into the distribution run, thus creating aggregates for the current day and the current hour (and including both in the respective indices). When running multiple distributions in one hour with this profile, the date aggregate for today and the hours aggregate for the current hour will be updated and overwritten.
152 `testdata` | Causes test data to be inserted into the database before each distribution run. By default, around 1000 random diagnosis keys will be generated per hour. If there are no diagnosis keys in the database yet, random keys will be generated for every hour from the beginning of the retention period (14 days ago at 00:00 UTC) until one hour before the present hour. If there are already keys in the database, the random keys will be generated for every hour from the latest diagnosis key in the database (by submission timestamp) until one hour before the present hour (or none at all, if the latest diagnosis key in the database was submitted one hour ago or later).
153 `signature-dev` | Sets the app package ID in the export packages' signature info to `de.rki.coronawarnapp-dev` so that test certificates (instead of production certificates) will be used for client-side validation.
154 `signature-prod` | Provides production app package IDs for the signature info
155
156 ### Submission
157
158 Profile | Effect
159 -------------|-------------
160 `dev` | Turns the log level to `DEBUG`.
161 `cloud` | Removes default values for the `datasource` configuration.
162
163 ## Documentation
164
165 The full documentation for the Corona-Warn-App can be found in the [cwa-documentation](https://github.com/corona-warn-app/cwa-documentation) repository. The documentation repository contains technical documents, architecture information, and whitepapers related to this implementation.
166
167 ## Support and Feedback
168
169 The following channels are available for discussions, feedback, and support requests:
170
171 | Type | Channel |
172 | ------------------------ | ------------------------------------------------------ |
173 | **General Discussion** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="General Discussion"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/question.svg?style=flat-square"></a> </a> |
174 | **Concept Feedback** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="Open Concept Feedback"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/architecture.svg?style=flat-square"></a> |
175 | **Backend Issue** | <a href="https://github.com/corona-warn-app/cwa-server/issues/new/choose" title="Open Backend Issue"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat-square"></a> |
176 | **Other Requests** | <a href="mailto:[email protected]" title="Email CWA Team"><img src="https://img.shields.io/badge/email-CWA%20team-green?logo=mail.ru&style=flat-square&logoColor=white"></a> |
177
178 ## How to Contribute
179
180 Contribution and feedback are 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.
181
182 ## Contributors
183
184 The German government has asked SAP and Deutsche Telekom to develop the Corona-Warn-App for Germany as open source software. Deutsche Telekom is providing the network and mobile technology and will operate and run the backend for the app in a safe, scalable and stable manner. SAP is responsible for the app development, its framework and the underlying platform. Therefore, development teams of SAP and Deutsche Telekom are contributing to this project. At the same time 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.
185
186 ## Repositories
187
188 The following public repositories are currently available for the Corona-Warn-App:
189
190 | Repository | Description |
191 | ------------------- | --------------------------------------------------------------------- |
192 | [cwa-documentation] | Project overview, general documentation, and white papers |
193 | [cwa-server] | Backend implementation for the Apple/Google exposure notification API|
194 | [cwa-verification-server] | Backend implementation of the verification process|
195
196 [cwa-documentation]: https://github.com/corona-warn-app/cwa-documentation
197 [cwa-server]: https://github.com/corona-warn-app/cwa-server
198 [cwa-verification-server]: https://github.com/corona-warn-app/cwa-verification-server
199 [Postgres]: https://www.postgresql.org/
200 [HSQLDB]: http://hsqldb.org/
201 [Zenko CloudServer]: https://github.com/scality/cloudserver
202
203 ## Licensing
204
205 Copyright (c) 2020 SAP SE or an SAP affiliate company.
206
207 Licensed under the **Apache License, Version 2.0** (the "License"); you may not use this file except in compliance with the License.
208
209 You may obtain a copy of the License at <https://www.apache.org/licenses/LICENSE-2.0>.
210
211 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.
212
[end of README.md]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/component/DiagnosisKeysStructureProvider.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.distribution.assembly.component;
22
23 import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
24 import app.coronawarn.server.common.persistence.service.DiagnosisKeyService;
25 import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.directory.DiagnosisKeysDirectory;
26 import app.coronawarn.server.services.distribution.assembly.structure.WritableOnDisk;
27 import app.coronawarn.server.services.distribution.assembly.structure.directory.Directory;
28 import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
29 import java.util.Collection;
30 import org.slf4j.Logger;
31 import org.slf4j.LoggerFactory;
32 import org.springframework.stereotype.Component;
33
34 /**
35 * Retrieves stored diagnosis keys and builds a {@link DiagnosisKeysDirectory} with them.
36 */
37 @Component
38 public class DiagnosisKeysStructureProvider {
39
40 private static final Logger logger = LoggerFactory
41 .getLogger(DiagnosisKeysStructureProvider.class);
42
43 private final DiagnosisKeyService diagnosisKeyService;
44 private final CryptoProvider cryptoProvider;
45 private final DistributionServiceConfig distributionServiceConfig;
46
47 /**
48 * Creates a new DiagnosisKeysStructureProvider.
49 */
50 DiagnosisKeysStructureProvider(DiagnosisKeyService diagnosisKeyService, CryptoProvider cryptoProvider,
51 DistributionServiceConfig distributionServiceConfig) {
52 this.diagnosisKeyService = diagnosisKeyService;
53 this.cryptoProvider = cryptoProvider;
54 this.distributionServiceConfig = distributionServiceConfig;
55 }
56
57 /**
58 * Get directory for diagnosis keys from database.
59 * @return the directory
60 */
61 public Directory<WritableOnDisk> getDiagnosisKeys() {
62 logger.debug("Querying diagnosis keys from the database...");
63 Collection<DiagnosisKey> diagnosisKeys = diagnosisKeyService.getDiagnosisKeys();
64 return new DiagnosisKeysDirectory(diagnosisKeys, cryptoProvider, distributionServiceConfig);
65 }
66 }
67
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/component/DiagnosisKeysStructureProvider.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysCountryDirectory.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.directory;
22
23 import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
24 import app.coronawarn.server.services.distribution.assembly.component.CryptoProvider;
25 import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.directory.decorator.DateAggregatingDecorator;
26 import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.directory.decorator.DateIndexingDecorator;
27 import app.coronawarn.server.services.distribution.assembly.structure.WritableOnDisk;
28 import app.coronawarn.server.services.distribution.assembly.structure.directory.IndexDirectory;
29 import app.coronawarn.server.services.distribution.assembly.structure.directory.IndexDirectoryOnDisk;
30 import app.coronawarn.server.services.distribution.assembly.structure.util.ImmutableStack;
31 import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
32 import java.time.LocalDate;
33 import java.util.Collection;
34 import java.util.Set;
35
36 public class DiagnosisKeysCountryDirectory extends IndexDirectoryOnDisk<String> {
37
38 private final Collection<DiagnosisKey> diagnosisKeys;
39 private final CryptoProvider cryptoProvider;
40 private final DistributionServiceConfig distributionServiceConfig;
41
42 /**
43 * Constructs a {@link DiagnosisKeysCountryDirectory} instance that represents the {@code .../country/:country/...}
44 * portion of the diagnosis key directory structure.
45 *
46 * @param diagnosisKeys The diagnosis keys processed in the contained sub directories.
47 * @param cryptoProvider The {@link CryptoProvider} used for payload signing.
48 */
49 public DiagnosisKeysCountryDirectory(Collection<DiagnosisKey> diagnosisKeys,
50 CryptoProvider cryptoProvider, DistributionServiceConfig distributionServiceConfig) {
51 super(distributionServiceConfig.getApi().getCountryPath(), __ ->
52 Set.of(distributionServiceConfig.getApi().getCountryGermany()), Object::toString);
53 this.diagnosisKeys = diagnosisKeys;
54 this.cryptoProvider = cryptoProvider;
55 this.distributionServiceConfig = distributionServiceConfig;
56 }
57
58 @Override
59 public void prepare(ImmutableStack<Object> indices) {
60 this.addWritableToAll(__ -> {
61 DiagnosisKeysDateDirectory dateDirectory = new DiagnosisKeysDateDirectory(diagnosisKeys, cryptoProvider,
62 distributionServiceConfig);
63 return decorateDateDirectory(dateDirectory);
64 });
65 super.prepare(indices);
66 }
67
68 private IndexDirectory<LocalDate, WritableOnDisk> decorateDateDirectory(DiagnosisKeysDateDirectory dateDirectory) {
69 return new DateAggregatingDecorator(new DateIndexingDecorator(dateDirectory, distributionServiceConfig),
70 cryptoProvider, distributionServiceConfig);
71 }
72 }
73
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysCountryDirectory.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysDateDirectory.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.directory;
22
23 import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
24 import app.coronawarn.server.services.distribution.assembly.component.CryptoProvider;
25 import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.directory.decorator.HourIndexingDecorator;
26 import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.util.DateTime;
27 import app.coronawarn.server.services.distribution.assembly.structure.WritableOnDisk;
28 import app.coronawarn.server.services.distribution.assembly.structure.directory.Directory;
29 import app.coronawarn.server.services.distribution.assembly.structure.directory.IndexDirectoryOnDisk;
30 import app.coronawarn.server.services.distribution.assembly.structure.util.ImmutableStack;
31 import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
32 import java.time.LocalDate;
33 import java.time.format.DateTimeFormatter;
34 import java.util.Collection;
35
36 public class DiagnosisKeysDateDirectory extends IndexDirectoryOnDisk<LocalDate> {
37
38 private static final DateTimeFormatter ISO8601 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
39
40 private final Collection<DiagnosisKey> diagnosisKeys;
41 private final CryptoProvider cryptoProvider;
42 private final DistributionServiceConfig distributionServiceConfig;
43
44 /**
45 * Constructs a {@link DiagnosisKeysDateDirectory} instance associated with the specified {@link DiagnosisKey}
46 * collection. Payload signing is be performed according to the specified {@link CryptoProvider}.
47 *
48 * @param diagnosisKeys The diagnosis keys processed in the contained directories.
49 * @param cryptoProvider The {@link CryptoProvider} used for payload signing.
50 */
51 public DiagnosisKeysDateDirectory(Collection<DiagnosisKey> diagnosisKeys,
52 CryptoProvider cryptoProvider, DistributionServiceConfig distributionServiceConfig) {
53 super(distributionServiceConfig.getApi().getDatePath(), __ -> DateTime.getDates(diagnosisKeys), ISO8601::format);
54 this.cryptoProvider = cryptoProvider;
55 this.diagnosisKeys = diagnosisKeys;
56 this.distributionServiceConfig = distributionServiceConfig;
57 }
58
59 @Override
60 public void prepare(ImmutableStack<Object> indices) {
61 this.addWritableToAll(__ -> {
62 DiagnosisKeysHourDirectory hourDirectory =
63 new DiagnosisKeysHourDirectory(diagnosisKeys, cryptoProvider, distributionServiceConfig);
64 return decorateHourDirectory(hourDirectory);
65 });
66 super.prepare(indices);
67 }
68
69 private Directory<WritableOnDisk> decorateHourDirectory(DiagnosisKeysHourDirectory hourDirectory) {
70 return new HourIndexingDecorator(hourDirectory, distributionServiceConfig);
71 }
72 }
73
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysDateDirectory.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysDirectory.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.directory;
22
23 import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
24 import app.coronawarn.server.services.distribution.assembly.component.CryptoProvider;
25 import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.directory.decorator.CountryIndexingDecorator;
26 import app.coronawarn.server.services.distribution.assembly.structure.WritableOnDisk;
27 import app.coronawarn.server.services.distribution.assembly.structure.directory.Directory;
28 import app.coronawarn.server.services.distribution.assembly.structure.directory.DirectoryOnDisk;
29 import app.coronawarn.server.services.distribution.assembly.structure.directory.IndexDirectory;
30 import app.coronawarn.server.services.distribution.assembly.structure.directory.IndexDirectoryOnDisk;
31 import app.coronawarn.server.services.distribution.assembly.structure.directory.decorator.indexing.IndexingDecoratorOnDisk;
32 import app.coronawarn.server.services.distribution.assembly.structure.util.ImmutableStack;
33 import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
34 import java.util.Collection;
35
36 /**
37 * A {@link Directory} containing the file and directory structure that mirrors the API defined in the OpenAPI
38 * definition {@code /services/distribution/api_v1.json}. Available countries (endpoint {@code
39 * /version/v1/diagnosis-keys/country}) are statically set to only {@code "DE"}. The dates and respective hours
40 * (endpoint {@code /version/v1/diagnosis-keys/country/DE/date}) will be created based on the actual {@link DiagnosisKey
41 * DiagnosisKeys} given to the {@link DiagnosisKeysDirectory#DiagnosisKeysDirectory constructor}.
42 */
43 public class DiagnosisKeysDirectory extends DirectoryOnDisk {
44
45 private final Collection<DiagnosisKey> diagnosisKeys;
46 private final CryptoProvider cryptoProvider;
47 private final DistributionServiceConfig distributionServiceConfig;
48
49 /**
50 * Constructs a {@link DiagnosisKeysDirectory} based on the specified {@link DiagnosisKey} collection. Cryptographic
51 * signing is performed using the specified {@link CryptoProvider}.
52 *
53 * @param diagnosisKeys The diagnosis keys processed in the contained sub directories.
54 * @param cryptoProvider The {@link CryptoProvider} used for payload signing.
55 */
56 public DiagnosisKeysDirectory(Collection<DiagnosisKey> diagnosisKeys, CryptoProvider cryptoProvider,
57 DistributionServiceConfig distributionServiceConfig) {
58 super(distributionServiceConfig.getApi().getDiagnosisKeysPath());
59 this.diagnosisKeys = diagnosisKeys;
60 this.cryptoProvider = cryptoProvider;
61 this.distributionServiceConfig = distributionServiceConfig;
62 }
63
64 @Override
65 public void prepare(ImmutableStack<Object> indices) {
66 this.addWritable(decorateCountryDirectory(
67 new DiagnosisKeysCountryDirectory(diagnosisKeys, cryptoProvider, distributionServiceConfig)));
68 super.prepare(indices);
69 }
70
71 private IndexDirectory<String, WritableOnDisk> decorateCountryDirectory(
72 IndexDirectoryOnDisk<String> countryDirectory) {
73 return new CountryIndexingDecorator<>(
74 new IndexingDecoratorOnDisk<>(countryDirectory, distributionServiceConfig.getOutputFileName()),
75 distributionServiceConfig);
76 }
77 }
78
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysDirectory.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysHourDirectory.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.directory;
22
23 import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
24 import app.coronawarn.server.services.distribution.assembly.component.CryptoProvider;
25 import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.archive.decorator.singing.DiagnosisKeySigningDecorator;
26 import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.file.TemporaryExposureKeyExportFile;
27 import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.util.DateTime;
28 import app.coronawarn.server.services.distribution.assembly.structure.WritableOnDisk;
29 import app.coronawarn.server.services.distribution.assembly.structure.archive.Archive;
30 import app.coronawarn.server.services.distribution.assembly.structure.archive.ArchiveOnDisk;
31 import app.coronawarn.server.services.distribution.assembly.structure.directory.Directory;
32 import app.coronawarn.server.services.distribution.assembly.structure.directory.IndexDirectoryOnDisk;
33 import app.coronawarn.server.services.distribution.assembly.structure.file.File;
34 import app.coronawarn.server.services.distribution.assembly.structure.util.ImmutableStack;
35 import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
36 import java.time.LocalDate;
37 import java.time.LocalDateTime;
38 import java.time.ZoneOffset;
39 import java.util.Collection;
40 import java.util.Set;
41 import java.util.stream.Collectors;
42
43 public class DiagnosisKeysHourDirectory extends IndexDirectoryOnDisk<LocalDateTime> {
44
45 private final Collection<DiagnosisKey> diagnosisKeys;
46 private final CryptoProvider cryptoProvider;
47 private final DistributionServiceConfig distributionServiceConfig;
48
49 /**
50 * Constructs a {@link DiagnosisKeysHourDirectory} instance for the specified date.
51 *
52 * @param diagnosisKeys A collection of diagnosis keys. These will be filtered according to the specified current
53 * date.
54 * @param cryptoProvider The {@link CryptoProvider} used for cryptographic signing.
55 */
56 public DiagnosisKeysHourDirectory(Collection<DiagnosisKey> diagnosisKeys, CryptoProvider cryptoProvider,
57 DistributionServiceConfig distributionServiceConfig) {
58 super(distributionServiceConfig.getApi().getHourPath(),
59 indices -> DateTime.getHours(((LocalDate) indices.peek()), diagnosisKeys), LocalDateTime::getHour);
60 this.diagnosisKeys = diagnosisKeys;
61 this.cryptoProvider = cryptoProvider;
62 this.distributionServiceConfig = distributionServiceConfig;
63 }
64
65 @Override
66 public void prepare(ImmutableStack<Object> indices) {
67 this.addWritableToAll(currentIndices -> {
68 LocalDateTime currentHour = (LocalDateTime) currentIndices.peek();
69 // The LocalDateTime currentHour already contains both the date and the hour information, so
70 // we can throw away the LocalDate that's the second item on the stack from the "/date"
71 // IndexDirectory.
72 String region = (String) currentIndices.pop().pop().peek();
73
74 Set<DiagnosisKey> diagnosisKeysForCurrentHour = getDiagnosisKeysForHour(currentHour);
75
76 long startTimestamp = currentHour.toEpochSecond(ZoneOffset.UTC);
77 long endTimestamp = currentHour.plusHours(1).toEpochSecond(ZoneOffset.UTC);
78 File<WritableOnDisk> temporaryExposureKeyExportFile = TemporaryExposureKeyExportFile.fromDiagnosisKeys(
79 diagnosisKeysForCurrentHour, region, startTimestamp, endTimestamp, distributionServiceConfig);
80
81 Archive<WritableOnDisk> hourArchive = new ArchiveOnDisk(distributionServiceConfig.getOutputFileName());
82 hourArchive.addWritable(temporaryExposureKeyExportFile);
83
84 return decorateDiagnosisKeyArchive(hourArchive);
85 });
86 super.prepare(indices);
87 }
88
89 private Set<DiagnosisKey> getDiagnosisKeysForHour(LocalDateTime hour) {
90 return this.diagnosisKeys.stream()
91 .filter(diagnosisKey -> DistributionDateTimeCalculator.getDistributionDateTime(diagnosisKey).equals(hour))
92 .collect(Collectors.toSet());
93 }
94
95 private Directory<WritableOnDisk> decorateDiagnosisKeyArchive(Archive<WritableOnDisk> archive) {
96 return new DiagnosisKeySigningDecorator(archive, cryptoProvider, distributionServiceConfig);
97 }
98 }
99
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysHourDirectory.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DistributionDateTimeCalculator.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.directory;
22
23 import static app.coronawarn.server.services.distribution.assembly.diagnosiskeys.util.DateTime.ONE_HOUR_INTERVAL_SECONDS;
24 import static app.coronawarn.server.services.distribution.assembly.diagnosiskeys.util.DateTime.TEN_MINUTES_INTERVAL_SECONDS;
25 import static java.time.ZoneOffset.UTC;
26
27 import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
28 import java.time.Duration;
29 import java.time.LocalDateTime;
30 import java.time.temporal.ChronoUnit;
31
32 public class DistributionDateTimeCalculator {
33
34 /**
35 * Minimum time in minutes after key expiration after which it can be distributed.
36 */
37 public static final long DISTRIBUTION_PADDING = 120L;
38
39 private DistributionDateTimeCalculator() {
40 }
41
42 /**
43 * Calculates the earliest point in time at which the specified {@link DiagnosisKey} can be distributed. Before keys
44 * are allowed to be distributed, they must be expired for a configured amount of time.
45 *
46 * @return {@link LocalDateTime} at which the specified {@link DiagnosisKey} can be distributed.
47 */
48 public static LocalDateTime getDistributionDateTime(DiagnosisKey diagnosisKey) {
49 LocalDateTime submissionDateTime = LocalDateTime
50 .ofEpochSecond(diagnosisKey.getSubmissionTimestamp() * ONE_HOUR_INTERVAL_SECONDS, 0, UTC);
51 LocalDateTime keyExpiryDateTime = LocalDateTime
52 .ofEpochSecond(diagnosisKey.getRollingStartIntervalNumber() * TEN_MINUTES_INTERVAL_SECONDS, 0, UTC)
53 .plusMinutes(diagnosisKey.getRollingPeriod() * 10L);
54
55 if (Duration.between(keyExpiryDateTime, submissionDateTime).toMinutes() <= DISTRIBUTION_PADDING) {
56 // truncatedTo floors the value, so we need to add an hour to the DISTRIBUTION_PADDING to compensate that.
57 return keyExpiryDateTime.plusMinutes(DISTRIBUTION_PADDING + 60).truncatedTo(ChronoUnit.HOURS);
58 }
59
60 return submissionDateTime;
61 }
62 }
63
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DistributionDateTimeCalculator.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/config/DistributionServiceConfig.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.distribution.config;
22
23 import app.coronawarn.server.common.protocols.external.exposurenotification.SignatureInfo;
24 import org.springframework.boot.context.properties.ConfigurationProperties;
25 import org.springframework.stereotype.Component;
26
27 @Component
28 @ConfigurationProperties(prefix = "services.distribution")
29 public class DistributionServiceConfig {
30
31 private Paths paths;
32 private TestData testData;
33 private Integer retentionDays;
34 private String outputFileName;
35 private Boolean includeIncompleteDays;
36 private Boolean includeIncompleteHours;
37 private TekExport tekExport;
38 private Signature signature;
39 private Api api;
40 private ObjectStore objectStore;
41
42 public Paths getPaths() {
43 return paths;
44 }
45
46 public void setPaths(Paths paths) {
47 this.paths = paths;
48 }
49
50 public TestData getTestData() {
51 return testData;
52 }
53
54 public void setTestData(TestData testData) {
55 this.testData = testData;
56 }
57
58 public Integer getRetentionDays() {
59 return retentionDays;
60 }
61
62 public void setRetentionDays(Integer retentionDays) {
63 this.retentionDays = retentionDays;
64 }
65
66 public String getOutputFileName() {
67 return outputFileName;
68 }
69
70 public void setOutputFileName(String outputFileName) {
71 this.outputFileName = outputFileName;
72 }
73
74 public Boolean getIncludeIncompleteDays() {
75 return includeIncompleteDays;
76 }
77
78 public void setIncludeIncompleteDays(Boolean includeIncompleteDays) {
79 this.includeIncompleteDays = includeIncompleteDays;
80 }
81
82 public Boolean getIncludeIncompleteHours() {
83 return includeIncompleteHours;
84 }
85
86 public void setIncludeIncompleteHours(Boolean includeIncompleteHours) {
87 this.includeIncompleteHours = includeIncompleteHours;
88 }
89
90 public TekExport getTekExport() {
91 return tekExport;
92 }
93
94 public void setTekExport(TekExport tekExport) {
95 this.tekExport = tekExport;
96 }
97
98 public Signature getSignature() {
99 return signature;
100 }
101
102 public void setSignature(Signature signature) {
103 this.signature = signature;
104 }
105
106 public Api getApi() {
107 return api;
108 }
109
110 public void setApi(Api api) {
111 this.api = api;
112 }
113
114 public ObjectStore getObjectStore() {
115 return objectStore;
116 }
117
118 public void setObjectStore(
119 ObjectStore objectStore) {
120 this.objectStore = objectStore;
121 }
122
123 public static class TekExport {
124
125 private String fileName;
126 private String fileHeader;
127 private Integer fileHeaderWidth;
128
129 public String getFileName() {
130 return fileName;
131 }
132
133 public void setFileName(String fileName) {
134 this.fileName = fileName;
135 }
136
137 public String getFileHeader() {
138 return fileHeader;
139 }
140
141 public void setFileHeader(String fileHeader) {
142 this.fileHeader = fileHeader;
143 }
144
145 public Integer getFileHeaderWidth() {
146 return fileHeaderWidth;
147 }
148
149 public void setFileHeaderWidth(Integer fileHeaderWidth) {
150 this.fileHeaderWidth = fileHeaderWidth;
151 }
152 }
153
154 public static class TestData {
155
156 private Integer seed;
157 private Integer exposuresPerHour;
158
159 public Integer getSeed() {
160 return seed;
161 }
162
163 public void setSeed(Integer seed) {
164 this.seed = seed;
165 }
166
167 public Integer getExposuresPerHour() {
168 return exposuresPerHour;
169 }
170
171 public void setExposuresPerHour(Integer exposuresPerHour) {
172 this.exposuresPerHour = exposuresPerHour;
173 }
174 }
175
176 public static class Paths {
177
178 private String privateKey;
179 private String output;
180
181 public String getPrivateKey() {
182 return privateKey;
183 }
184
185 public void setPrivateKey(String privateKey) {
186 this.privateKey = privateKey;
187 }
188
189 public String getOutput() {
190 return output;
191 }
192
193 public void setOutput(String output) {
194 this.output = output;
195 }
196 }
197
198 public static class Api {
199
200 private String versionPath;
201 private String versionV1;
202 private String countryPath;
203 private String countryGermany;
204 private String datePath;
205 private String hourPath;
206 private String diagnosisKeysPath;
207 private String parametersPath;
208 private String appConfigFileName;
209
210 public String getVersionPath() {
211 return versionPath;
212 }
213
214 public void setVersionPath(String versionPath) {
215 this.versionPath = versionPath;
216 }
217
218 public String getVersionV1() {
219 return versionV1;
220 }
221
222 public void setVersionV1(String versionV1) {
223 this.versionV1 = versionV1;
224 }
225
226 public String getCountryPath() {
227 return countryPath;
228 }
229
230 public void setCountryPath(String countryPath) {
231 this.countryPath = countryPath;
232 }
233
234 public String getCountryGermany() {
235 return countryGermany;
236 }
237
238 public void setCountryGermany(String countryGermany) {
239 this.countryGermany = countryGermany;
240 }
241
242 public String getDatePath() {
243 return datePath;
244 }
245
246 public void setDatePath(String datePath) {
247 this.datePath = datePath;
248 }
249
250 public String getHourPath() {
251 return hourPath;
252 }
253
254 public void setHourPath(String hourPath) {
255 this.hourPath = hourPath;
256 }
257
258 public String getDiagnosisKeysPath() {
259 return diagnosisKeysPath;
260 }
261
262 public void setDiagnosisKeysPath(String diagnosisKeysPath) {
263 this.diagnosisKeysPath = diagnosisKeysPath;
264 }
265
266 public String getParametersPath() {
267 return parametersPath;
268 }
269
270 public void setParametersPath(String parametersPath) {
271 this.parametersPath = parametersPath;
272 }
273
274 public String getAppConfigFileName() {
275 return appConfigFileName;
276 }
277
278 public void setAppConfigFileName(String appConfigFileName) {
279 this.appConfigFileName = appConfigFileName;
280 }
281 }
282
283 public static class Signature {
284
285 private String appBundleId;
286 private String androidPackage;
287 private String verificationKeyId;
288 private String verificationKeyVersion;
289 private String algorithmOid;
290 private String algorithmName;
291 private String fileName;
292 private String securityProvider;
293
294 public String getAppBundleId() {
295 return appBundleId;
296 }
297
298 public void setAppBundleId(String appBundleId) {
299 this.appBundleId = appBundleId;
300 }
301
302 public String getAndroidPackage() {
303 return androidPackage;
304 }
305
306 public void setAndroidPackage(String androidPackage) {
307 this.androidPackage = androidPackage;
308 }
309
310 public String getVerificationKeyId() {
311 return verificationKeyId;
312 }
313
314 public void setVerificationKeyId(String verificationKeyId) {
315 this.verificationKeyId = verificationKeyId;
316 }
317
318 public String getVerificationKeyVersion() {
319 return verificationKeyVersion;
320 }
321
322 public void setVerificationKeyVersion(String verificationKeyVersion) {
323 this.verificationKeyVersion = verificationKeyVersion;
324 }
325
326 public String getAlgorithmOid() {
327 return algorithmOid;
328 }
329
330 public void setAlgorithmOid(String algorithmOid) {
331 this.algorithmOid = algorithmOid;
332 }
333
334 public String getAlgorithmName() {
335 return algorithmName;
336 }
337
338 public void setAlgorithmName(String algorithmName) {
339 this.algorithmName = algorithmName;
340 }
341
342 public String getFileName() {
343 return fileName;
344 }
345
346 public void setFileName(String fileName) {
347 this.fileName = fileName;
348 }
349
350 public String getSecurityProvider() {
351 return securityProvider;
352 }
353
354 public void setSecurityProvider(String securityProvider) {
355 this.securityProvider = securityProvider;
356 }
357
358 /**
359 * Returns the static {@link SignatureInfo} configured in the application properties.
360 */
361 public SignatureInfo getSignatureInfo() {
362 return SignatureInfo.newBuilder()
363 .setAppBundleId(this.getAppBundleId())
364 .setAndroidPackage(this.getAndroidPackage())
365 .setVerificationKeyVersion(this.getVerificationKeyVersion())
366 .setVerificationKeyId(this.getVerificationKeyId())
367 .setSignatureAlgorithm(this.getAlgorithmOid())
368 .build();
369 }
370 }
371
372 public static class ObjectStore {
373
374 private String accessKey;
375 private String secretKey;
376 private String endpoint;
377 private Integer port;
378 private String bucket;
379 private Boolean setPublicReadAclOnPutObject;
380
381 public String getAccessKey() {
382 return accessKey;
383 }
384
385 public void setAccessKey(String accessKey) {
386 this.accessKey = accessKey;
387 }
388
389 public String getSecretKey() {
390 return secretKey;
391 }
392
393 public void setSecretKey(String secretKey) {
394 this.secretKey = secretKey;
395 }
396
397 public String getEndpoint() {
398 return endpoint;
399 }
400
401 public void setEndpoint(String endpoint) {
402 this.endpoint = endpoint;
403 }
404
405 public Integer getPort() {
406 return port;
407 }
408
409 public void setPort(Integer port) {
410 this.port = port;
411 }
412
413 public String getBucket() {
414 return bucket;
415 }
416
417 public void setBucket(String bucket) {
418 this.bucket = bucket;
419 }
420
421 public Boolean isSetPublicReadAclOnPutObject() {
422 return setPublicReadAclOnPutObject;
423 }
424
425 public void setSetPublicReadAclOnPutObject(Boolean setPublicReadAclOnPutObject) {
426 this.setPublicReadAclOnPutObject = setPublicReadAclOnPutObject;
427 }
428 }
429 }
430
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/config/DistributionServiceConfig.java]
[start of services/distribution/src/main/resources/application.yaml]
1 ---
2 logging:
3 level:
4 org:
5 springframework:
6 web: INFO
7 app:
8 coronawarn: INFO
9
10 services:
11 distribution:
12 output-file-name: index
13 retention-days: 14
14 include-incomplete-days: false
15 include-incomplete-hours: false
16 paths:
17 output: out
18 privatekey: ${VAULT_FILESIGNING_SECRET}
19 tek-export:
20 file-name: export.bin
21 file-header: EK Export v1
22 file-header-width: 16
23 api:
24 version-path: version
25 version-v1: v1
26 country-path: country
27 country-germany: DE
28 date-path: date
29 hour-path: hour
30 diagnosis-keys-path: diagnosis-keys
31 parameters-path: configuration
32 app-config-file-name: app_config
33 signature:
34 verification-key-id: 262
35 verification-key-version: v1
36 algorithm-oid: 1.2.840.10045.4.3.2
37 algorithm-name: SHA256withECDSA
38 file-name: export.sig
39 security-provider: BC
40 # Configuration for the S3 compatible object storage hosted by Telekom in Germany
41 objectstore:
42 access-key: ${CWA_OBJECTSTORE_ACCESSKEY:accessKey1}
43 secret-key: ${CWA_OBJECTSTORE_SECRETKEY:verySecretKey1}
44 endpoint: ${CWA_OBJECTSTORE_ENDPOINT:http://localhost}
45 bucket: ${CWA_OBJECTSTORE_BUCKET:cwa}
46 port: ${CWA_OBJECTSTORE_PORT:8003}
47 set-public-read-acl-on-put-object: true
48
49 spring:
50 main:
51 web-application-type: NONE
52 # Postgres configuration
53 jpa:
54 hibernate:
55 ddl-auto: validate
56 flyway:
57 enabled: true
58 locations: classpath:db/migration/postgres
59
60 datasource:
61 driver-class-name: org.postgresql.Driver
62 url: jdbc:postgresql://${POSTGRESQL_SERVICE_HOST:localhost}:${POSTGRESQL_SERVICE_PORT:5432}/${POSTGRESQL_DATABASE:cwa}
63 username: ${POSTGRESQL_USER:postgres}
64 password: ${POSTGRESQL_PASSWORD:postgres}
65
[end of services/distribution/src/main/resources/application.yaml]
</code>
Here is an example of a patch file. It consists of changes to the code base. It specifies the file names, the line numbers of each change, and the removed and added lines. A single patch file can contain changes to multiple files.
<patch>
--- a/file.py
+++ b/file.py
@@ -1,27 +1,35 @@
def euclidean(a, b):
- while b:
- a, b = b, a % b
- return a
+ if b == 0:
+ return a
+ return euclidean(b, a % b)
def bresenham(x0, y0, x1, y1):
points = []
dx = abs(x1 - x0)
dy = abs(y1 - y0)
- sx = 1 if x0 < x1 else -1
- sy = 1 if y0 < y1 else -1
- err = dx - dy
+ x, y = x0, y0
+ sx = -1 if x0 > x1 else 1
+ sy = -1 if y0 > y1 else 1
- while True:
- points.append((x0, y0))
- if x0 == x1 and y0 == y1:
- break
- e2 = 2 * err
- if e2 > -dy:
+ if dx > dy:
+ err = dx / 2.0
+ while x != x1:
+ points.append((x, y))
err -= dy
- x0 += sx
- if e2 < dx:
- err += dx
- y0 += sy
+ if err < 0:
+ y += sy
+ err += dx
+ x += sx
+ else:
+ err = dy / 2.0
+ while y != y1:
+ points.append((x, y))
+ err -= dx
+ if err < 0:
+ x += sx
+ err += dy
+ y += sy
+ points.append((x, y))
return points
</patch>
I need you to solve the provded issue by generating a single patch file that I can apply directly to this repository using git apply. Please respond with a single patch file in the format shown above.
Respond below:
| corona-warn-app/cwa-server | fd114fd04e36c36c8081e0286e3f3fd27170777e | Aggregate File Creation: Skip packages if payload too small
Change the aggregate file creation logic in a way, in which packages are skipped in case the payload (amount of keys) is too small. The threshold should be configurable, and defaulted to 50 for now.
| Maybe combine with #140
**Alternative suggestion: Pad packages with random dummy keys if too small**
Thinking a bit further into the hoped for future, when new infections are becoming rare, this might lead to unnecessary (possibly quite long) delays in notifications being sent. Could one instead use random dummy keys to pad every package that is too small to maybe 50 or 100 keys (or possibly padding to a randomised amount so an outsider can't even determine whether there any dummies are in the set).
This would impact required data volumes marginally - in the worst case, if 75 dummy keys are added every hour, this would represent only 50 kiB per day (or 3% of your bandwidth example in the architecture document) if I did not miscalculate. Since this would only occur in a low load situation anyway, this should be acceptable.
Threhold is now: 140
I like the padding idea - @MKusber do you think we can do this from a DPP/security perspective?
Hey @MikeJayDee, after some investigation, @michael-burwig and me decided that we will go for the "shifting" approach instead of the "padding" approach for this release. For clarification:
**"Shifting" approach:**
- If a package is too small (number of keys submitted in a timeframe is below a configurable threshold), then it will not be distributed (there will be zero keys in that package)
- The keys that would have been distributed in that run are "shifted" to the next distribution run
- Rinse and repeat until a package can be assembled that contains enough keys (above the configurable threshold)
**"Padding" approach:**
- If a package is too small, then it will be padded with random / fake keys until the threshold is matched (or exceeded)
As you have rightly pointed out, the main disadvantage of the "shifting" approach is that it introduces an artificial delay in the distribution of keys. This means that people will not be warned about a potential COVID exposure as quickly as possible, but that the CWA server will wait with the distribution until enough submissions have been made. Especially as the number of submissions decreases, this delay will become significant.
This disadvantage, of course, doesn't exist with the "padding" approach. However, the purpose of this whole "threshold" feature is to preserve peoples anonymity and to not allow anyone to create movement profiles. In order to achieve that, it must be impossible to match a specific temporary exposure key (TEK) to any particular person. In the "shifting" approach, this is achieved by ensuring that a single person's TEKs are always mashed together with enough other people's real TEKs to get lost in the shuffle. In the "padding" approach, this is achieved by mashing a single person's TEKs together with artificially/randomly generated TEKs. In order to make the "padding" approach equally as secure and privacy preserving, we would need to make real TEKs and artificially/randomly generated TEKs absolutely indistinguishable from one another. We decided for the "shifting" approach for this release because we are not 100% certain that we can achieve that - for the following reasons:
There are 4 fields in a TEK:
- Key data
- Transmission risk level
- Rolling start interval number
- Rolling period
"Key data" is random by nature and can easily be generated - no problem there. "Rolling period" is always 144 - no problem here either. However, in the real world, "transmission risk levels" and "rolling start interval numbers" each follow some statistical distribution. In order to make real and fake TEKs indistinguishable to any reasonably certainty, we would need to make sure, that the fake TEKs follow the same distribution as the real ones. The problem is, that we are not sure what the exact properties of that distribution are (and how they change over time). We can thus not confidently guarantee that one wouldn't be able to distinguish random and real TEKs through statistical analysis.
Since data privacy and protection are the foundation of this whole project, we decided to not take this risk and go with the safer but less accurate solution.
Now, it might be entirely possible that there is a solution to this problem that we just don't see. But since time is of the essence right now (and we can not wait for a scientifically substantiated analysis of the "padding" approach), we decided to go for the "shifting" approach for the initial release.
Anyways. Thank you very much for sharing your idea, @MikeJayDee. We forwarded your idea and the open questions outlined above to our scientific partners and will keep you posted on any updates 👍 | 2020-06-01T17:31:01 | <patch>
diff --git a/README.md b/README.md
--- a/README.md
+++ b/README.md
@@ -148,7 +148,7 @@ Profile | Effect
-----------------|-------------
`dev` | Turns the log level to `DEBUG`.
`cloud` | Removes default values for the `datasource` and `objectstore` configurations.
-`demo` | Includes incomplete days and hours into the distribution run, thus creating aggregates for the current day and the current hour (and including both in the respective indices). When running multiple distributions in one hour with this profile, the date aggregate for today and the hours aggregate for the current hour will be updated and overwritten.
+`demo` | Includes incomplete days and hours into the distribution run, thus creating aggregates for the current day and the current hour (and including both in the respective indices). When running multiple distributions in one hour with this profile, the date aggregate for today and the hours aggregate for the current hour will be updated and overwritten. This profile also turns off the expiry policy (Keys must be expired for at least 2 hours before distribution) and the shifting policy (there must be at least 140 keys in a distribution).
`testdata` | Causes test data to be inserted into the database before each distribution run. By default, around 1000 random diagnosis keys will be generated per hour. If there are no diagnosis keys in the database yet, random keys will be generated for every hour from the beginning of the retention period (14 days ago at 00:00 UTC) until one hour before the present hour. If there are already keys in the database, the random keys will be generated for every hour from the latest diagnosis key in the database (by submission timestamp) until one hour before the present hour (or none at all, if the latest diagnosis key in the database was submitted one hour ago or later).
`signature-dev` | Sets the app package ID in the export packages' signature info to `de.rki.coronawarnapp-dev` so that test certificates (instead of production certificates) will be used for client-side validation.
`signature-prod` | Provides production app package IDs for the signature info
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/component/DiagnosisKeysStructureProvider.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/component/DiagnosisKeysStructureProvider.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/component/DiagnosisKeysStructureProvider.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/component/DiagnosisKeysStructureProvider.java
@@ -22,6 +22,7 @@
import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
import app.coronawarn.server.common.persistence.service.DiagnosisKeyService;
+import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.DiagnosisKeyBundler;
import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.directory.DiagnosisKeysDirectory;
import app.coronawarn.server.services.distribution.assembly.structure.WritableOnDisk;
import app.coronawarn.server.services.distribution.assembly.structure.directory.Directory;
@@ -29,6 +30,7 @@
import java.util.Collection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
@@ -40,6 +42,8 @@ public class DiagnosisKeysStructureProvider {
private static final Logger logger = LoggerFactory
.getLogger(DiagnosisKeysStructureProvider.class);
+ @Autowired
+ private DiagnosisKeyBundler diagnosisKeyBundler;
private final DiagnosisKeyService diagnosisKeyService;
private final CryptoProvider cryptoProvider;
private final DistributionServiceConfig distributionServiceConfig;
@@ -56,11 +60,13 @@ public class DiagnosisKeysStructureProvider {
/**
* Get directory for diagnosis keys from database.
+ *
* @return the directory
*/
public Directory<WritableOnDisk> getDiagnosisKeys() {
logger.debug("Querying diagnosis keys from the database...");
Collection<DiagnosisKey> diagnosisKeys = diagnosisKeyService.getDiagnosisKeys();
- return new DiagnosisKeysDirectory(diagnosisKeys, cryptoProvider, distributionServiceConfig);
+ diagnosisKeyBundler.setDiagnosisKeys(diagnosisKeys);
+ return new DiagnosisKeysDirectory(diagnosisKeyBundler, cryptoProvider, distributionServiceConfig);
}
}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/DemoDiagnosisKeyBundler.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/DemoDiagnosisKeyBundler.java
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/DemoDiagnosisKeyBundler.java
@@ -0,0 +1,61 @@
+/*-
+ * ---license-start
+ * Corona-Warn-App
+ * ---
+ * Copyright (C) 2020 SAP SE and all other contributors
+ * ---
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://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 for the specific language governing permissions and
+ * limitations under the License.
+ * ---license-end
+ */
+
+package app.coronawarn.server.services.distribution.assembly.diagnosiskeys;
+
+import static java.util.stream.Collectors.groupingBy;
+
+import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
+import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
+import java.time.LocalDateTime;
+import java.util.Collection;
+import java.util.List;
+import org.springframework.context.annotation.Profile;
+
+/**
+ * An instance of this class contains a collection of {@link DiagnosisKey DiagnosisKeys}, that will be distributed
+ * in the same hour they have been submitted.
+ */
+@Profile("demo")
+public class DemoDiagnosisKeyBundler extends DiagnosisKeyBundler {
+
+ public DemoDiagnosisKeyBundler(DistributionServiceConfig distributionServiceConfig) {
+ super(distributionServiceConfig);
+ }
+
+ /**
+ * Initializes the internal {@code distributableDiagnosisKeys} map, grouping the diagnosis keys by the submission
+ * timestamp, thus ignoring the expiry policy.
+ */
+ @Override
+ protected void createDiagnosisKeyDistributionMap(Collection<DiagnosisKey> diagnosisKeys) {
+ this.distributableDiagnosisKeys.clear();
+ this.distributableDiagnosisKeys.putAll(diagnosisKeys.stream().collect(groupingBy(this::getSubmissionDateTime)));
+ }
+
+ /**
+ * Returns all diagnosis keys that should be distributed in a specific hour, without respecting the shifting and
+ * expiry policies.
+ */
+ @Override
+ public List<DiagnosisKey> getDiagnosisKeysDistributableAt(LocalDateTime hour) {
+ return this.getDiagnosisKeysForHour(hour);
+ }
+}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/DiagnosisKeyBundler.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/DiagnosisKeyBundler.java
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/DiagnosisKeyBundler.java
@@ -0,0 +1,98 @@
+/*-
+ * ---license-start
+ * Corona-Warn-App
+ * ---
+ * Copyright (C) 2020 SAP SE and all other contributors
+ * ---
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://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 for the specific language governing permissions and
+ * limitations under the License.
+ * ---license-end
+ */
+
+package app.coronawarn.server.services.distribution.assembly.diagnosiskeys;
+
+import static app.coronawarn.server.services.distribution.assembly.diagnosiskeys.util.DateTime.ONE_HOUR_INTERVAL_SECONDS;
+import static java.time.ZoneOffset.UTC;
+import static java.util.Collections.emptyList;
+
+import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
+import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
+import java.time.LocalDateTime;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.stream.Collectors;
+import org.springframework.stereotype.Component;
+
+/**
+ * An instance of this class contains a collection of {@link DiagnosisKey DiagnosisKeys}.
+ */
+@Component
+public abstract class DiagnosisKeyBundler {
+
+ protected final int minNumberOfKeysPerBundle;
+ protected final long expiryPolicyMinutes;
+
+ // A map containing diagnosis keys, grouped by the LocalDateTime on which they may be distributed
+ protected final Map<LocalDateTime, List<DiagnosisKey>> distributableDiagnosisKeys = new HashMap<>();
+
+ public DiagnosisKeyBundler(DistributionServiceConfig distributionServiceConfig) {
+ this.minNumberOfKeysPerBundle = distributionServiceConfig.getShiftingPolicyThreshold();
+ this.expiryPolicyMinutes = distributionServiceConfig.getExpiryPolicyMinutes();
+ }
+
+ /**
+ * Sets the {@link DiagnosisKey DiagnosisKeys} contained by this {@link DiagnosisKeyBundler} and calls {@link
+ * DiagnosisKeyBundler#createDiagnosisKeyDistributionMap}.
+ */
+ public void setDiagnosisKeys(Collection<DiagnosisKey> diagnosisKeys) {
+ createDiagnosisKeyDistributionMap(diagnosisKeys);
+ }
+
+ /**
+ * Returns all {@link DiagnosisKey DiagnosisKeys} contained by this {@link DiagnosisKeyBundler}.
+ */
+ public List<DiagnosisKey> getAllDiagnosisKeys() {
+ return this.distributableDiagnosisKeys.values().stream()
+ .flatMap(List::stream)
+ .collect(Collectors.toList());
+ }
+
+ /**
+ * Initializes the internal {@code distributableDiagnosisKeys} map, which should contain all diagnosis keys, grouped
+ * by the LocalDateTime on which they may be distributed.
+ */
+ protected abstract void createDiagnosisKeyDistributionMap(Collection<DiagnosisKey> diagnosisKeys);
+
+ /**
+ * Returns all diagnosis keys that should be distributed in a specific hour.
+ */
+ public abstract List<DiagnosisKey> getDiagnosisKeysDistributableAt(LocalDateTime hour);
+
+ /**
+ * Returns the submission timestamp of a {@link DiagnosisKey} as a {@link LocalDateTime}.
+ */
+ protected LocalDateTime getSubmissionDateTime(DiagnosisKey diagnosisKey) {
+ return LocalDateTime.ofEpochSecond(diagnosisKey.getSubmissionTimestamp() * ONE_HOUR_INTERVAL_SECONDS, 0, UTC);
+ }
+
+ /**
+ * Returns all diagnosis keys that should be distributed in a specific hour.
+ */
+ protected List<DiagnosisKey> getDiagnosisKeysForHour(LocalDateTime hour) {
+ return Optional
+ .ofNullable(this.distributableDiagnosisKeys.get(hour))
+ .orElse(emptyList());
+ }
+}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/ProdDiagnosisKeyBundler.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/ProdDiagnosisKeyBundler.java
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/ProdDiagnosisKeyBundler.java
@@ -0,0 +1,135 @@
+/*-
+ * ---license-start
+ * Corona-Warn-App
+ * ---
+ * Copyright (C) 2020 SAP SE and all other contributors
+ * ---
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://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 for the specific language governing permissions and
+ * limitations under the License.
+ * ---license-end
+ */
+
+package app.coronawarn.server.services.distribution.assembly.diagnosiskeys;
+
+import static app.coronawarn.server.services.distribution.assembly.diagnosiskeys.util.DateTime.TEN_MINUTES_INTERVAL_SECONDS;
+import static java.time.ZoneOffset.UTC;
+import static java.util.Collections.emptyList;
+import static java.util.stream.Collectors.groupingBy;
+
+import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
+import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
+import java.time.Duration;
+import java.time.LocalDateTime;
+import java.time.temporal.ChronoUnit;
+import java.util.Collection;
+import java.util.List;
+import java.util.Optional;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+import org.springframework.context.annotation.Profile;
+
+/**
+ * An instance of this class contains a collection of {@link DiagnosisKey DiagnosisKeys}, that will be distributed while
+ * respecting expiry policy (keys must be expired for a configurable amount of time before distribution) and shifting
+ * policy (there must be at least a configurable number of keys in a distribution). The policies are configurable
+ * through the properties {@code expiry-policy-minutes} and {@code shifting-policy-threshold}.
+ */
+@Profile("!demo")
+public class ProdDiagnosisKeyBundler extends DiagnosisKeyBundler {
+
+ /**
+ * Creates a new {@link ProdDiagnosisKeyBundler}.
+ */
+ public ProdDiagnosisKeyBundler(DistributionServiceConfig distributionServiceConfig) {
+ super(distributionServiceConfig);
+ }
+
+ /**
+ * Initializes the internal {@code distributableDiagnosisKeys} map, grouping the diagnosis keys by the date on which
+ * they may be distributed, while respecting the expiry policy.
+ */
+ @Override
+ protected void createDiagnosisKeyDistributionMap(Collection<DiagnosisKey> diagnosisKeys) {
+ this.distributableDiagnosisKeys.clear();
+ this.distributableDiagnosisKeys.putAll(diagnosisKeys.stream().collect(groupingBy(this::getDistributionDateTime)));
+ }
+
+ /**
+ * Returns all diagnosis keys that should be distributed in a specific hour, while respecting the shifting and expiry
+ * policies.
+ */
+ @Override
+ public List<DiagnosisKey> getDiagnosisKeysDistributableAt(LocalDateTime hour) {
+ List<DiagnosisKey> keysSinceLastDistribution = getKeysSinceLastDistribution(hour);
+ if (keysSinceLastDistribution.size() >= minNumberOfKeysPerBundle) {
+ return keysSinceLastDistribution;
+ } else {
+ return emptyList();
+ }
+ }
+
+ /**
+ * Returns a all distributable keys between a specific hour and the last distribution (bundle that was above the
+ * shifting threshold) or the earliest distributable key.
+ */
+ private List<DiagnosisKey> getKeysSinceLastDistribution(LocalDateTime hour) {
+ Optional<LocalDateTime> earliestDistributableTimestamp = getEarliestDistributableTimestamp();
+ if (earliestDistributableTimestamp.isEmpty() || hour.isBefore(earliestDistributableTimestamp.get())) {
+ return emptyList();
+ }
+ List<DiagnosisKey> distributableInCurrentHour = getDiagnosisKeysForHour(hour);
+ if (distributableInCurrentHour.size() >= minNumberOfKeysPerBundle) {
+ return distributableInCurrentHour;
+ }
+ LocalDateTime previousHour = hour.minusHours(1);
+ Collection<DiagnosisKey> distributableInPreviousHour = getDiagnosisKeysDistributableAt(previousHour);
+ if (distributableInPreviousHour.size() >= minNumberOfKeysPerBundle) {
+ // Last hour was distributed, so we can not combine the current hour with the last hour
+ return distributableInCurrentHour;
+ } else {
+ // Last hour was not distributed, so we can combine the current hour with the last hour
+ return Stream.concat(distributableInCurrentHour.stream(), getKeysSinceLastDistribution(previousHour).stream())
+ .collect(Collectors.toList());
+ }
+ }
+
+ private Optional<LocalDateTime> getEarliestDistributableTimestamp() {
+ return this.distributableDiagnosisKeys.keySet().stream().min(LocalDateTime::compareTo);
+ }
+
+ /**
+ * Returns the end of the rolling time window that a {@link DiagnosisKey} was active for as a {@link LocalDateTime}.
+ */
+ private LocalDateTime getExpiryDateTime(DiagnosisKey diagnosisKey) {
+ return LocalDateTime
+ .ofEpochSecond(diagnosisKey.getRollingStartIntervalNumber() * TEN_MINUTES_INTERVAL_SECONDS, 0, UTC)
+ .plusMinutes(diagnosisKey.getRollingPeriod() * 10L);
+ }
+
+ /**
+ * Calculates the earliest point in time at which the specified {@link DiagnosisKey} can be distributed. Before keys
+ * are allowed to be distributed, they must be expired for a configured amount of time.
+ *
+ * @return {@link LocalDateTime} at which the specified {@link DiagnosisKey} can be distributed.
+ */
+ private LocalDateTime getDistributionDateTime(DiagnosisKey diagnosisKey) {
+ LocalDateTime submissionDateTime = getSubmissionDateTime(diagnosisKey);
+ LocalDateTime expiryDateTime = getExpiryDateTime(diagnosisKey);
+ long minutesBetweenExpiryAndSubmission = Duration.between(expiryDateTime, submissionDateTime).toMinutes();
+ if (minutesBetweenExpiryAndSubmission <= expiryPolicyMinutes) {
+ // truncatedTo floors the value, so we need to add an hour to the DISTRIBUTION_PADDING to compensate that.
+ return expiryDateTime.plusMinutes(expiryPolicyMinutes + 60).truncatedTo(ChronoUnit.HOURS);
+ } else {
+ return submissionDateTime;
+ }
+ }
+}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysCountryDirectory.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysCountryDirectory.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysCountryDirectory.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysCountryDirectory.java
@@ -22,6 +22,7 @@
import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
import app.coronawarn.server.services.distribution.assembly.component.CryptoProvider;
+import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.DiagnosisKeyBundler;
import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.directory.decorator.DateAggregatingDecorator;
import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.directory.decorator.DateIndexingDecorator;
import app.coronawarn.server.services.distribution.assembly.structure.WritableOnDisk;
@@ -30,12 +31,11 @@
import app.coronawarn.server.services.distribution.assembly.structure.util.ImmutableStack;
import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
import java.time.LocalDate;
-import java.util.Collection;
import java.util.Set;
public class DiagnosisKeysCountryDirectory extends IndexDirectoryOnDisk<String> {
- private final Collection<DiagnosisKey> diagnosisKeys;
+ private final DiagnosisKeyBundler diagnosisKeyBundler;
private final CryptoProvider cryptoProvider;
private final DistributionServiceConfig distributionServiceConfig;
@@ -43,14 +43,14 @@ public class DiagnosisKeysCountryDirectory extends IndexDirectoryOnDisk<String>
* Constructs a {@link DiagnosisKeysCountryDirectory} instance that represents the {@code .../country/:country/...}
* portion of the diagnosis key directory structure.
*
- * @param diagnosisKeys The diagnosis keys processed in the contained sub directories.
- * @param cryptoProvider The {@link CryptoProvider} used for payload signing.
+ * @param diagnosisKeyBundler A {@link DiagnosisKeyBundler} containing the {@link DiagnosisKey DiagnosisKeys}.
+ * @param cryptoProvider The {@link CryptoProvider} used for payload signing.
*/
- public DiagnosisKeysCountryDirectory(Collection<DiagnosisKey> diagnosisKeys,
+ public DiagnosisKeysCountryDirectory(DiagnosisKeyBundler diagnosisKeyBundler,
CryptoProvider cryptoProvider, DistributionServiceConfig distributionServiceConfig) {
super(distributionServiceConfig.getApi().getCountryPath(), __ ->
Set.of(distributionServiceConfig.getApi().getCountryGermany()), Object::toString);
- this.diagnosisKeys = diagnosisKeys;
+ this.diagnosisKeyBundler = diagnosisKeyBundler;
this.cryptoProvider = cryptoProvider;
this.distributionServiceConfig = distributionServiceConfig;
}
@@ -58,7 +58,7 @@ public DiagnosisKeysCountryDirectory(Collection<DiagnosisKey> diagnosisKeys,
@Override
public void prepare(ImmutableStack<Object> indices) {
this.addWritableToAll(__ -> {
- DiagnosisKeysDateDirectory dateDirectory = new DiagnosisKeysDateDirectory(diagnosisKeys, cryptoProvider,
+ DiagnosisKeysDateDirectory dateDirectory = new DiagnosisKeysDateDirectory(diagnosisKeyBundler, cryptoProvider,
distributionServiceConfig);
return decorateDateDirectory(dateDirectory);
});
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysDateDirectory.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysDateDirectory.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysDateDirectory.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysDateDirectory.java
@@ -22,6 +22,7 @@
import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
import app.coronawarn.server.services.distribution.assembly.component.CryptoProvider;
+import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.DiagnosisKeyBundler;
import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.directory.decorator.HourIndexingDecorator;
import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.util.DateTime;
import app.coronawarn.server.services.distribution.assembly.structure.WritableOnDisk;
@@ -31,13 +32,12 @@
import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
-import java.util.Collection;
public class DiagnosisKeysDateDirectory extends IndexDirectoryOnDisk<LocalDate> {
private static final DateTimeFormatter ISO8601 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
- private final Collection<DiagnosisKey> diagnosisKeys;
+ private final DiagnosisKeyBundler diagnosisKeyBundler;
private final CryptoProvider cryptoProvider;
private final DistributionServiceConfig distributionServiceConfig;
@@ -45,14 +45,15 @@ public class DiagnosisKeysDateDirectory extends IndexDirectoryOnDisk<LocalDate>
* Constructs a {@link DiagnosisKeysDateDirectory} instance associated with the specified {@link DiagnosisKey}
* collection. Payload signing is be performed according to the specified {@link CryptoProvider}.
*
- * @param diagnosisKeys The diagnosis keys processed in the contained directories.
+ * @param diagnosisKeyBundler A {@link DiagnosisKeyBundler} containing the {@link DiagnosisKey DiagnosisKeys}.
* @param cryptoProvider The {@link CryptoProvider} used for payload signing.
*/
- public DiagnosisKeysDateDirectory(Collection<DiagnosisKey> diagnosisKeys,
+ public DiagnosisKeysDateDirectory(DiagnosisKeyBundler diagnosisKeyBundler,
CryptoProvider cryptoProvider, DistributionServiceConfig distributionServiceConfig) {
- super(distributionServiceConfig.getApi().getDatePath(), __ -> DateTime.getDates(diagnosisKeys), ISO8601::format);
+ super(distributionServiceConfig.getApi().getDatePath(),
+ __ -> DateTime.getDates(diagnosisKeyBundler.getAllDiagnosisKeys()), ISO8601::format);
this.cryptoProvider = cryptoProvider;
- this.diagnosisKeys = diagnosisKeys;
+ this.diagnosisKeyBundler = diagnosisKeyBundler;
this.distributionServiceConfig = distributionServiceConfig;
}
@@ -60,7 +61,7 @@ public DiagnosisKeysDateDirectory(Collection<DiagnosisKey> diagnosisKeys,
public void prepare(ImmutableStack<Object> indices) {
this.addWritableToAll(__ -> {
DiagnosisKeysHourDirectory hourDirectory =
- new DiagnosisKeysHourDirectory(diagnosisKeys, cryptoProvider, distributionServiceConfig);
+ new DiagnosisKeysHourDirectory(diagnosisKeyBundler, cryptoProvider, distributionServiceConfig);
return decorateHourDirectory(hourDirectory);
});
super.prepare(indices);
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysDirectory.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysDirectory.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysDirectory.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysDirectory.java
@@ -22,6 +22,7 @@
import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
import app.coronawarn.server.services.distribution.assembly.component.CryptoProvider;
+import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.DiagnosisKeyBundler;
import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.directory.decorator.CountryIndexingDecorator;
import app.coronawarn.server.services.distribution.assembly.structure.WritableOnDisk;
import app.coronawarn.server.services.distribution.assembly.structure.directory.Directory;
@@ -31,7 +32,6 @@
import app.coronawarn.server.services.distribution.assembly.structure.directory.decorator.indexing.IndexingDecoratorOnDisk;
import app.coronawarn.server.services.distribution.assembly.structure.util.ImmutableStack;
import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
-import java.util.Collection;
/**
* A {@link Directory} containing the file and directory structure that mirrors the API defined in the OpenAPI
@@ -42,7 +42,7 @@
*/
public class DiagnosisKeysDirectory extends DirectoryOnDisk {
- private final Collection<DiagnosisKey> diagnosisKeys;
+ private final DiagnosisKeyBundler diagnosisKeyBundler;
private final CryptoProvider cryptoProvider;
private final DistributionServiceConfig distributionServiceConfig;
@@ -50,13 +50,13 @@ public class DiagnosisKeysDirectory extends DirectoryOnDisk {
* Constructs a {@link DiagnosisKeysDirectory} based on the specified {@link DiagnosisKey} collection. Cryptographic
* signing is performed using the specified {@link CryptoProvider}.
*
- * @param diagnosisKeys The diagnosis keys processed in the contained sub directories.
- * @param cryptoProvider The {@link CryptoProvider} used for payload signing.
+ * @param diagnosisKeyBundler A {@link DiagnosisKeyBundler} containing the {@link DiagnosisKey DiagnosisKeys}.
+ * @param cryptoProvider The {@link CryptoProvider} used for payload signing.
*/
- public DiagnosisKeysDirectory(Collection<DiagnosisKey> diagnosisKeys, CryptoProvider cryptoProvider,
+ public DiagnosisKeysDirectory(DiagnosisKeyBundler diagnosisKeyBundler, CryptoProvider cryptoProvider,
DistributionServiceConfig distributionServiceConfig) {
super(distributionServiceConfig.getApi().getDiagnosisKeysPath());
- this.diagnosisKeys = diagnosisKeys;
+ this.diagnosisKeyBundler = diagnosisKeyBundler;
this.cryptoProvider = cryptoProvider;
this.distributionServiceConfig = distributionServiceConfig;
}
@@ -64,7 +64,7 @@ public DiagnosisKeysDirectory(Collection<DiagnosisKey> diagnosisKeys, CryptoProv
@Override
public void prepare(ImmutableStack<Object> indices) {
this.addWritable(decorateCountryDirectory(
- new DiagnosisKeysCountryDirectory(diagnosisKeys, cryptoProvider, distributionServiceConfig)));
+ new DiagnosisKeysCountryDirectory(diagnosisKeyBundler, cryptoProvider, distributionServiceConfig)));
super.prepare(indices);
}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysHourDirectory.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysHourDirectory.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysHourDirectory.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysHourDirectory.java
@@ -22,6 +22,7 @@
import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
import app.coronawarn.server.services.distribution.assembly.component.CryptoProvider;
+import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.DiagnosisKeyBundler;
import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.archive.decorator.singing.DiagnosisKeySigningDecorator;
import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.file.TemporaryExposureKeyExportFile;
import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.util.DateTime;
@@ -36,28 +37,25 @@
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
-import java.util.Collection;
-import java.util.Set;
-import java.util.stream.Collectors;
+import java.util.List;
public class DiagnosisKeysHourDirectory extends IndexDirectoryOnDisk<LocalDateTime> {
- private final Collection<DiagnosisKey> diagnosisKeys;
+ private final DiagnosisKeyBundler diagnosisKeyBundler;
private final CryptoProvider cryptoProvider;
private final DistributionServiceConfig distributionServiceConfig;
/**
* Constructs a {@link DiagnosisKeysHourDirectory} instance for the specified date.
*
- * @param diagnosisKeys A collection of diagnosis keys. These will be filtered according to the specified current
- * date.
- * @param cryptoProvider The {@link CryptoProvider} used for cryptographic signing.
+ * @param diagnosisKeyBundler A {@link DiagnosisKeyBundler} containing the {@link DiagnosisKey DiagnosisKeys}.
+ * @param cryptoProvider The {@link CryptoProvider} used for cryptographic signing.
*/
- public DiagnosisKeysHourDirectory(Collection<DiagnosisKey> diagnosisKeys, CryptoProvider cryptoProvider,
+ public DiagnosisKeysHourDirectory(DiagnosisKeyBundler diagnosisKeyBundler, CryptoProvider cryptoProvider,
DistributionServiceConfig distributionServiceConfig) {
- super(distributionServiceConfig.getApi().getHourPath(),
- indices -> DateTime.getHours(((LocalDate) indices.peek()), diagnosisKeys), LocalDateTime::getHour);
- this.diagnosisKeys = diagnosisKeys;
+ super(distributionServiceConfig.getApi().getHourPath(), indices -> DateTime.getHours(((LocalDate) indices.peek()),
+ diagnosisKeyBundler.getAllDiagnosisKeys()), LocalDateTime::getHour);
+ this.diagnosisKeyBundler = diagnosisKeyBundler;
this.cryptoProvider = cryptoProvider;
this.distributionServiceConfig = distributionServiceConfig;
}
@@ -71,7 +69,8 @@ public void prepare(ImmutableStack<Object> indices) {
// IndexDirectory.
String region = (String) currentIndices.pop().pop().peek();
- Set<DiagnosisKey> diagnosisKeysForCurrentHour = getDiagnosisKeysForHour(currentHour);
+ List<DiagnosisKey> diagnosisKeysForCurrentHour =
+ this.diagnosisKeyBundler.getDiagnosisKeysDistributableAt(currentHour);
long startTimestamp = currentHour.toEpochSecond(ZoneOffset.UTC);
long endTimestamp = currentHour.plusHours(1).toEpochSecond(ZoneOffset.UTC);
@@ -86,12 +85,6 @@ public void prepare(ImmutableStack<Object> indices) {
super.prepare(indices);
}
- private Set<DiagnosisKey> getDiagnosisKeysForHour(LocalDateTime hour) {
- return this.diagnosisKeys.stream()
- .filter(diagnosisKey -> DistributionDateTimeCalculator.getDistributionDateTime(diagnosisKey).equals(hour))
- .collect(Collectors.toSet());
- }
-
private Directory<WritableOnDisk> decorateDiagnosisKeyArchive(Archive<WritableOnDisk> archive) {
return new DiagnosisKeySigningDecorator(archive, cryptoProvider, distributionServiceConfig);
}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DistributionDateTimeCalculator.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DistributionDateTimeCalculator.java
deleted file mode 100644
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DistributionDateTimeCalculator.java
+++ /dev/null
@@ -1,62 +0,0 @@
-/*-
- * ---license-start
- * Corona-Warn-App
- * ---
- * Copyright (C) 2020 SAP SE and all other contributors
- * ---
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://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 for the specific language governing permissions and
- * limitations under the License.
- * ---license-end
- */
-
-package app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.directory;
-
-import static app.coronawarn.server.services.distribution.assembly.diagnosiskeys.util.DateTime.ONE_HOUR_INTERVAL_SECONDS;
-import static app.coronawarn.server.services.distribution.assembly.diagnosiskeys.util.DateTime.TEN_MINUTES_INTERVAL_SECONDS;
-import static java.time.ZoneOffset.UTC;
-
-import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
-import java.time.Duration;
-import java.time.LocalDateTime;
-import java.time.temporal.ChronoUnit;
-
-public class DistributionDateTimeCalculator {
-
- /**
- * Minimum time in minutes after key expiration after which it can be distributed.
- */
- public static final long DISTRIBUTION_PADDING = 120L;
-
- private DistributionDateTimeCalculator() {
- }
-
- /**
- * Calculates the earliest point in time at which the specified {@link DiagnosisKey} can be distributed. Before keys
- * are allowed to be distributed, they must be expired for a configured amount of time.
- *
- * @return {@link LocalDateTime} at which the specified {@link DiagnosisKey} can be distributed.
- */
- public static LocalDateTime getDistributionDateTime(DiagnosisKey diagnosisKey) {
- LocalDateTime submissionDateTime = LocalDateTime
- .ofEpochSecond(diagnosisKey.getSubmissionTimestamp() * ONE_HOUR_INTERVAL_SECONDS, 0, UTC);
- LocalDateTime keyExpiryDateTime = LocalDateTime
- .ofEpochSecond(diagnosisKey.getRollingStartIntervalNumber() * TEN_MINUTES_INTERVAL_SECONDS, 0, UTC)
- .plusMinutes(diagnosisKey.getRollingPeriod() * 10L);
-
- if (Duration.between(keyExpiryDateTime, submissionDateTime).toMinutes() <= DISTRIBUTION_PADDING) {
- // truncatedTo floors the value, so we need to add an hour to the DISTRIBUTION_PADDING to compensate that.
- return keyExpiryDateTime.plusMinutes(DISTRIBUTION_PADDING + 60).truncatedTo(ChronoUnit.HOURS);
- }
-
- return submissionDateTime;
- }
-}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/config/DistributionServiceConfig.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/config/DistributionServiceConfig.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/config/DistributionServiceConfig.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/config/DistributionServiceConfig.java
@@ -31,6 +31,8 @@ public class DistributionServiceConfig {
private Paths paths;
private TestData testData;
private Integer retentionDays;
+ private Integer expiryPolicyMinutes;
+ private Integer shiftingPolicyThreshold;
private String outputFileName;
private Boolean includeIncompleteDays;
private Boolean includeIncompleteHours;
@@ -63,6 +65,22 @@ public void setRetentionDays(Integer retentionDays) {
this.retentionDays = retentionDays;
}
+ public Integer getExpiryPolicyMinutes() {
+ return expiryPolicyMinutes;
+ }
+
+ public void setExpiryPolicyMinutes(Integer expiryPolicyMinutes) {
+ this.expiryPolicyMinutes = expiryPolicyMinutes;
+ }
+
+ public Integer getShiftingPolicyThreshold() {
+ return shiftingPolicyThreshold;
+ }
+
+ public void setShiftingPolicyThreshold(Integer shiftingPolicyThreshold) {
+ this.shiftingPolicyThreshold = shiftingPolicyThreshold;
+ }
+
public String getOutputFileName() {
return outputFileName;
}
diff --git a/services/distribution/src/main/resources/application.yaml b/services/distribution/src/main/resources/application.yaml
--- a/services/distribution/src/main/resources/application.yaml
+++ b/services/distribution/src/main/resources/application.yaml
@@ -11,6 +11,8 @@ services:
distribution:
output-file-name: index
retention-days: 14
+ expiry-policy-minutes: 120
+ shifting-policy-threshold: 140
include-incomplete-days: false
include-incomplete-hours: false
paths:
</patch> | diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/ProdDiagnosisKeyBundlerTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/ProdDiagnosisKeyBundlerTest.java
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/ProdDiagnosisKeyBundlerTest.java
@@ -0,0 +1,190 @@
+/*-
+ * ---license-start
+ * Corona-Warn-App
+ * ---
+ * Copyright (C) 2020 SAP SE and all other contributors
+ * ---
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://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 for the specific language governing permissions and
+ * limitations under the License.
+ * ---license-end
+ */
+
+package app.coronawarn.server.services.distribution.assembly.diagnosiskeys;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
+import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
+import java.time.LocalDateTime;
+import java.util.List;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+import java.util.stream.Stream;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Nested;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.context.properties.EnableConfigurationProperties;
+import org.springframework.boot.test.context.ConfigFileApplicationContextInitializer;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit.jupiter.SpringExtension;
+
+@EnableConfigurationProperties(value = DistributionServiceConfig.class)
+@ExtendWith(SpringExtension.class)
+@ContextConfiguration(classes = {DistributionServiceConfig.class, ProdDiagnosisKeyBundler.class},
+ initializers = ConfigFileApplicationContextInitializer.class)
+class ProdDiagnosisKeyBundlerTest {
+
+ @Autowired
+ DistributionServiceConfig distributionServiceConfig;
+
+ @Autowired
+ DiagnosisKeyBundler bundler;
+
+ @Test
+ void testEmptyListWhenNoDiagnosisKeys() {
+ bundler.setDiagnosisKeys(List.of());
+ assertThat(bundler.getDiagnosisKeysDistributableAt(LocalDateTime.of(1970, 1, 1, 0, 0, 0))).hasSize(0);
+ }
+
+ @Test
+ void testEmptyListWhenGettingDistributableKeysBeforeEarliestDiagnosisKey() {
+ List<DiagnosisKey> diagnosisKeys = buildDiagnosisKeys(6, 50L, 5);
+ bundler.setDiagnosisKeys(diagnosisKeys);
+ assertThat(bundler.getDiagnosisKeysDistributableAt(LocalDateTime.of(1970, 1, 1, 0, 0, 0))).hasSize(0);
+ }
+
+ @Nested
+ @DisplayName("Expiry policy")
+ class ProdDiagnosisKeyBundlerExpiryPolicyTest {
+
+ @ParameterizedTest
+ @ValueSource(longs = {0L, 24L, 24L + 2L})
+ void testLastPeriodOfHourAndSubmissionLessThanDistributionDateTime(long submissionTimestamp) {
+ List<DiagnosisKey> diagnosisKeys = buildDiagnosisKeys(5, submissionTimestamp, 10);
+ bundler.setDiagnosisKeys(diagnosisKeys);
+ assertThat(bundler.getDiagnosisKeysDistributableAt(LocalDateTime.of(1970, 1, 2, 3, 0, 0))).hasSize(10);
+ }
+
+ @Test
+ void testLastPeriodOfHourAndSubmissionEqualsDistributionDateTime() {
+ List<DiagnosisKey> diagnosisKeys = buildDiagnosisKeys(5, 24L + 3L, 10);
+ bundler.setDiagnosisKeys(diagnosisKeys);
+ assertThat(bundler.getDiagnosisKeysDistributableAt(LocalDateTime.of(1970, 1, 2, 3, 0, 0))).hasSize(10);
+ }
+
+ @ParameterizedTest
+ @ValueSource(longs = {0L, 24L, 24L + 2L, 24L + 3L})
+ void testFirstPeriodOfHourAndSubmissionLessThanDistributionDateTime(long submissionTimestamp) {
+ List<DiagnosisKey> diagnosisKeys = buildDiagnosisKeys(6, submissionTimestamp, 10);
+ bundler.setDiagnosisKeys(diagnosisKeys);
+ assertThat(bundler.getDiagnosisKeysDistributableAt(LocalDateTime.of(1970, 1, 2, 4, 0, 0))).hasSize(10);
+ }
+
+ @Test
+ void testFirstPeriodOfHourAndSubmissionEqualsDistributionDateTime() {
+ List<DiagnosisKey> diagnosisKeys = buildDiagnosisKeys(6, 24L + 4L, 10);
+ bundler.setDiagnosisKeys(diagnosisKeys);
+ assertThat(bundler.getDiagnosisKeysDistributableAt(LocalDateTime.of(1970, 1, 2, 4, 0, 0))).hasSize(10);
+ }
+
+ @Test
+ void testLastPeriodOfHourAndSubmissionGreaterDistributionDateTime() {
+ List<DiagnosisKey> diagnosisKeys = buildDiagnosisKeys(5, 24L + 4L, 10);
+ bundler.setDiagnosisKeys(diagnosisKeys);
+ assertThat(bundler.getDiagnosisKeysDistributableAt(LocalDateTime.of(1970, 1, 2, 4, 0, 0))).hasSize(10);
+ }
+ }
+
+ @Nested
+ @DisplayName("Shifting policy")
+ class ProdDiagnosisKeyBundlerShiftingPolicyTest {
+
+ @Test
+ void testDoesNotShiftIfPackageSizeGreaterThanThreshold() {
+ List<DiagnosisKey> diagnosisKeys = buildDiagnosisKeys(6, 50L, 6);
+ bundler.setDiagnosisKeys(diagnosisKeys);
+ assertThat(bundler.getDiagnosisKeysDistributableAt(LocalDateTime.of(1970, 1, 3, 2, 0, 0))).hasSize(6);
+ }
+
+ @Test
+ void testDoesNotShiftIfPackageSizeEqualsThreshold() {
+ List<DiagnosisKey> diagnosisKeys = buildDiagnosisKeys(6, 50L, 5);
+ bundler.setDiagnosisKeys(diagnosisKeys);
+ assertThat(bundler.getDiagnosisKeysDistributableAt(LocalDateTime.of(1970, 1, 3, 2, 0, 0))).hasSize(5);
+ }
+
+ @Test
+ void testShiftsIfPackageSizeLessThanThreshold() {
+ List<DiagnosisKey> diagnosisKeys = Stream
+ .concat(buildDiagnosisKeys(6, 50L, 4).stream(), buildDiagnosisKeys(6, 51L, 1).stream())
+ .collect(Collectors.toList());
+ bundler.setDiagnosisKeys(diagnosisKeys);
+ assertThat(bundler.getDiagnosisKeysDistributableAt(LocalDateTime.of(1970, 1, 3, 2, 0, 0))).hasSize(0);
+ assertThat(bundler.getDiagnosisKeysDistributableAt(LocalDateTime.of(1970, 1, 3, 3, 0, 0))).hasSize(5);
+ }
+
+ @Test
+ void testShiftsSinceLastDistribution() {
+ List<DiagnosisKey> diagnosisKeys = Stream
+ .of(buildDiagnosisKeys(6, 50L, 5), buildDiagnosisKeys(6, 51L, 2), buildDiagnosisKeys(6, 52L, 4))
+ .flatMap(List::stream)
+ .collect(Collectors.toList());
+ bundler.setDiagnosisKeys(diagnosisKeys);
+ assertThat(bundler.getDiagnosisKeysDistributableAt(LocalDateTime.of(1970, 1, 3, 2, 0, 0))).hasSize(5);
+ assertThat(bundler.getDiagnosisKeysDistributableAt(LocalDateTime.of(1970, 1, 3, 3, 0, 0))).hasSize(0);
+ assertThat(bundler.getDiagnosisKeysDistributableAt(LocalDateTime.of(1970, 1, 3, 4, 0, 0))).hasSize(6);
+ assertThat(bundler.getDiagnosisKeysDistributableAt(LocalDateTime.of(1970, 1, 3, 5, 0, 0))).hasSize(0);
+ }
+
+ @Test
+ void testShiftIncludesPreviouslyUndistributedKeys() {
+ List<DiagnosisKey> diagnosisKeys = Stream
+ .concat(buildDiagnosisKeys(6, 50L, 1).stream(), buildDiagnosisKeys(6, 51L, 5).stream())
+ .collect(Collectors.toList());
+ bundler.setDiagnosisKeys(diagnosisKeys);
+ assertThat(bundler.getDiagnosisKeysDistributableAt(LocalDateTime.of(1970, 1, 3, 2, 0, 0))).hasSize(0);
+ assertThat(bundler.getDiagnosisKeysDistributableAt(LocalDateTime.of(1970, 1, 3, 3, 0, 0))).hasSize(5);
+ }
+
+ @Test
+ void testShiftsSparseDistributions() {
+ List<DiagnosisKey> diagnosisKeys = Stream
+ .of(buildDiagnosisKeys(6, 50L, 1), buildDiagnosisKeys(6, 51L, 1), buildDiagnosisKeys(6, 52L, 1),
+ buildDiagnosisKeys(6, 53L, 0), buildDiagnosisKeys(6, 54L, 0), buildDiagnosisKeys(6, 55L, 1),
+ buildDiagnosisKeys(6, 56L, 1))
+ .flatMap(List::stream)
+ .collect(Collectors.toList());
+ bundler.setDiagnosisKeys(diagnosisKeys);
+ assertThat(bundler.getDiagnosisKeysDistributableAt(LocalDateTime.of(1970, 1, 3, 2, 0, 0))).hasSize(0);
+ assertThat(bundler.getDiagnosisKeysDistributableAt(LocalDateTime.of(1970, 1, 3, 3, 0, 0))).hasSize(0);
+ assertThat(bundler.getDiagnosisKeysDistributableAt(LocalDateTime.of(1970, 1, 3, 4, 0, 0))).hasSize(0);
+ assertThat(bundler.getDiagnosisKeysDistributableAt(LocalDateTime.of(1970, 1, 3, 5, 0, 0))).hasSize(0);
+ assertThat(bundler.getDiagnosisKeysDistributableAt(LocalDateTime.of(1970, 1, 3, 6, 0, 0))).hasSize(0);
+ assertThat(bundler.getDiagnosisKeysDistributableAt(LocalDateTime.of(1970, 1, 3, 7, 0, 0))).hasSize(0);
+ assertThat(bundler.getDiagnosisKeysDistributableAt(LocalDateTime.of(1970, 1, 3, 8, 0, 0))).hasSize(5);
+ }
+ }
+
+ public static List<DiagnosisKey> buildDiagnosisKeys(int startIntervalNumber, long submissionTimestamp, int number) {
+ return IntStream.range(0, number)
+ .mapToObj(__ -> DiagnosisKey.builder()
+ .withKeyData(new byte[16])
+ .withRollingStartIntervalNumber(startIntervalNumber)
+ .withTransmissionRiskLevel(2)
+ .withSubmissionTimestamp(submissionTimestamp).build())
+ .collect(Collectors.toList());
+ }
+}
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysDirectoryTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysDirectoryTest.java
--- a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysDirectoryTest.java
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysDirectoryTest.java
@@ -26,6 +26,8 @@
import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
import app.coronawarn.server.services.distribution.assembly.component.CryptoProvider;
+import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.DemoDiagnosisKeyBundler;
+import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.DiagnosisKeyBundler;
import app.coronawarn.server.services.distribution.assembly.structure.WritableOnDisk;
import app.coronawarn.server.services.distribution.assembly.structure.directory.Directory;
import app.coronawarn.server.services.distribution.assembly.structure.directory.DirectoryOnDisk;
@@ -33,7 +35,6 @@
import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
import java.io.File;
import java.io.IOException;
-import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
@@ -90,8 +91,8 @@ void setupAll() throws IOException {
@Test
void checkBuildsTheCorrectDirectoryStructureWhenNoKeys() {
- diagnosisKeys = new ArrayList<>();
- Directory<WritableOnDisk> directory = new DiagnosisKeysDirectory(diagnosisKeys, cryptoProvider,
+ DiagnosisKeyBundler bundler = new DemoDiagnosisKeyBundler(distributionServiceConfig);
+ Directory<WritableOnDisk> directory = new DiagnosisKeysDirectory(bundler, cryptoProvider,
distributionServiceConfig);
parentDirectory.addWritable(directory);
directory.prepare(new ImmutableStack<>());
@@ -111,7 +112,9 @@ void checkBuildsTheCorrectDirectoryStructureWhenNoKeys() {
@Test
void checkBuildsTheCorrectDirectoryStructure() {
- Directory<WritableOnDisk> directory = new DiagnosisKeysDirectory(diagnosisKeys, cryptoProvider,
+ DiagnosisKeyBundler bundler = new DemoDiagnosisKeyBundler(distributionServiceConfig);
+ bundler.setDiagnosisKeys(diagnosisKeys);
+ Directory<WritableOnDisk> directory = new DiagnosisKeysDirectory(bundler, cryptoProvider,
distributionServiceConfig);
parentDirectory.addWritable(directory);
directory.prepare(new ImmutableStack<>());
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/structure/directory/DistributionDateTimeCalculatorTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/structure/directory/DistributionDateTimeCalculatorTest.java
deleted file mode 100644
--- a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/structure/directory/DistributionDateTimeCalculatorTest.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/*-
- * ---license-start
- * Corona-Warn-App
- * ---
- * Copyright (C) 2020 SAP SE and all other contributors
- * ---
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://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 for the specific language governing permissions and
- * limitations under the License.
- * ---license-end
- */
-
-package app.coronawarn.server.services.distribution.assembly.structure.directory;
-
-import static app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.directory.DistributionDateTimeCalculator.getDistributionDateTime;
-import static org.assertj.core.api.Assertions.assertThat;
-
-import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.params.ParameterizedTest;
-import org.junit.jupiter.params.provider.ValueSource;
-
-class DistributionDateTimeCalculatorTest {
-
- @ParameterizedTest
- @ValueSource(longs = {0L, 24L, 24L + 2L})
- void testLastPeriodOfHourAndSubmissionLessThanDistributionDateTime(long submissionTimestamp) {
- var diagnosisKey = buildDiagnosisKey(5, submissionTimestamp);
- assertThat(getDistributionDateTime(diagnosisKey)).isEqualTo("1970-01-02T03:00");
- }
-
- @Test
- void testLastPeriodOfHourAndSubmissionEqualsDistributionDateTime() {
- var diagnosisKey = buildDiagnosisKey(5, 24L + 3L);
- assertThat(getDistributionDateTime(diagnosisKey)).isEqualTo("1970-01-02T03:00");
- }
-
- @ParameterizedTest
- @ValueSource(longs = {0L, 24L, 24L + 2L, 24L + 3L})
- void testFirstPeriodOfHourAndSubmissionLessThanDistributionDateTime(long submissionTimestamp) {
- var diagnosisKey = buildDiagnosisKey(6, submissionTimestamp);
- assertThat(getDistributionDateTime(diagnosisKey)).isEqualTo("1970-01-02T04:00");
- }
-
- @Test
- void testFirstPeriodOfHourAndSubmissionEqualsDistributionDateTime() {
- var diagnosisKey = buildDiagnosisKey(6, 24L + 4L);
- assertThat(getDistributionDateTime(diagnosisKey)).isEqualTo("1970-01-02T04:00");
- }
-
- @Test
- void testLastPeriodOfHourAndSubmissionGreaterDistributionDateTime() {
- var diagnosisKey = buildDiagnosisKey(5, 24L + 4L);
- assertThat(getDistributionDateTime(diagnosisKey)).isEqualTo("1970-01-02T04:00");
- }
-
- private DiagnosisKey buildDiagnosisKey(int startIntervalNumber, long submissionTimestamp) {
- return DiagnosisKey.builder()
- .withKeyData(new byte[16])
- .withRollingStartIntervalNumber(startIntervalNumber)
- .withTransmissionRiskLevel(2)
- .withSubmissionTimestamp(submissionTimestamp).build();
- }
-}
diff --git a/services/distribution/src/test/resources/application.yaml b/services/distribution/src/test/resources/application.yaml
--- a/services/distribution/src/test/resources/application.yaml
+++ b/services/distribution/src/test/resources/application.yaml
@@ -9,6 +9,8 @@ services:
distribution:
output-file-name: index
retention-days: 14
+ expiry-policy-minutes: 120
+ shifting-policy-threshold: 5
include-incomplete-days: false
include-incomplete-hours: false
paths:
| ||||
corona-warn-app__cwa-server-232 | You will be provided with a partial code base and an issue statement explaining a problem to resolve.
<issue>
Open MinIO read access
## Current Implementation
Receiving files from local MinIO requires access key and secret key.
## Suggested Enhancement
Add a security policy to the MinIO configuration to only protect write access, but have open read access.
## Expected Benefits
Mobile colleagues can use local setup for end-to-end testing.
</issue>
<code>
[start of README.md]
1 <h1 align="center">
2 Corona-Warn-App Server
3 </h1>
4
5 <p align="center">
6 <a href="https://github.com/corona-warn-app/cwa-server/commits/" title="Last Commit"><img src="https://img.shields.io/github/last-commit/corona-warn-app/cwa-server?style=flat"></a>
7 <a href="https://github.com/corona-warn-app/cwa-server/issues" title="Open Issues"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat"></a>
8 <a href="https://circleci.com/gh/corona-warn-app/cwa-server" title="Build Status"><img src="https://circleci.com/gh/corona-warn-app/cwa-server.svg?style=shield&circle-token=4ab059989d10709df19eb4b98ab7c121a25e981a"></a>
9 <a href="https://sonarcloud.io/dashboard?id=corona-warn-app_cwa-server" title="Quality Gate"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=alert_status"></a>
10 <a href="https://sonarcloud.io/component_measures?id=corona-warn-app_cwa-server&metric=Coverage&view=list" title="Coverage"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=coverage"></a>
11 <a href="https://github.com/corona-warn-app/cwa-server/blob/master/LICENSE" title="License"><img src="https://img.shields.io/badge/License-Apache%202.0-green.svg?style=flat"></a>
12 </p>
13
14 <p align="center">
15 <a href="#development">Development</a> •
16 <a href="#service-apis">Service APIs</a> •
17 <a href="#documentation">Documentation</a> •
18 <a href="#support-and-feedback">Support</a> •
19 <a href="#how-to-contribute">Contribute</a> •
20 <a href="#contributors">Contributors</a> •
21 <a href="#repositories">Repositories</a> •
22 <a href="#licensing">Licensing</a>
23 </p>
24
25 The goal of this project is to develop the official Corona-Warn-App for Germany based on the exposure notification API from [Apple](https://www.apple.com/covid19/contacttracing/) and [Google](https://www.google.com/covid19/exposurenotifications/). The apps (for both iOS and Android) use Bluetooth technology to exchange anonymous encrypted data with other mobile phones (on which the app is also installed) in the vicinity of an app user's phone. The data is stored locally on each user's device, preventing authorities or other parties from accessing or controlling the data. This repository contains the **implementation of the server for encryption keys** for the Corona-Warn-App. This implementation is still a **work in progress**, and the code it contains is currently alpha-quality code.
26
27 In this documentation, Corona-Warn-App services are also referred to as CWA services.
28
29 ## Architecture Overview
30
31 You can find the architecture overview [here](/docs/architecture-overview.md), which will give you
32 a good starting point in how the backend services interact with other services, and what purpose
33 they serve.
34
35 ## Development
36
37 After you've checked out this repository, you can run the application in one of the following ways:
38
39 * As a [Docker](https://www.docker.com/)-based deployment on your local machine. You can run either:
40 * Single components using the respective Dockerfile or
41 * The full backend using the Docker Compose (which is considered the most convenient way)
42 * As a [Maven](https://maven.apache.org)-based build on your local machine.
43 If you want to develop something in a single component, this approach is preferable.
44
45 ### Docker-Based Deployment
46
47 If you want to use Docker-based deployment, you need to install Docker on your local machine. For more information about downloading and installing Docker, see the [official Docker documentation](https://docs.docker.com/get-docker/).
48
49 #### Running the Full CWA Backend Using Docker Compose
50
51 For your convenience, a full setup including the generation of test data has been prepared using [Docker Compose](https://docs.docker.com/compose/reference/overview/). To build the backend services, run ```docker-compose build``` in the repository's root directory. A default configuration file can be found under ```.env```in the root folder of the repository. The default values for the local Postgres and MinIO-build should be changed in this file before docker-compose is run.
52
53 Once the services are built, you can start the whole backend using ```docker-compose up```.
54 The distribution service runs once and then finishes. If you want to trigger additional distribution runs, run ```docker-compose start distribution```.
55
56 The docker-compose contains the following services:
57
58 Service | Description | Endpoint and Default Credentials
59 --------------|-------------|-----------
60 submission | The Corona-Warn-App submission service | http://localhost:8080
61 distribution | The Corona-Warn-App distribution service | NO ENDPOINT
62 postgres | A [postgres] database installation | postgres:5432 <br> Username: postgres <br> Password: postgres
63 pgadmin | A [pgadmin](https://www.pgadmin.org/) installation for the postgres database | http://localhost:8081 <br> Username: [email protected] <br> Password: password
64 minio | [MinIO] is an S3-compliant object store | http://localhost:8082/ <br> Access key: minioadmin <br> Secret key: minioadmin
65
66 #### Running Single CWA Services Using Docker
67
68 If you would like to build and run a single CWA service, it's considered easiest to run them in a Docker environment. You can do this using the script provided in the respective CWA service directory. The Docker script first builds the CWA service and then creates an image for the runtime, which means that there are no additional dependencies for you to install.
69
70 To build and run the distribution service, run the following command:
71
72 ```bash
73 ./services/distribution/build_and_run.sh
74 ```
75
76 To build and run the submission service, run the following command:
77
78 ```bash
79 ./services/submission/build_and_run.sh
80 ```
81
82 The submission service is available on [localhost:8080](http://localhost:8080 ).
83
84 ### Maven-Based Build
85
86 If you want to actively develop in one of the CWA services, the Maven-based runtime is most suitable.
87 To prepare your machine to run the CWA project locally, we recommend that you first ensure that you've installed the following:
88
89 * Minimum JDK Version 11: [OpenJDK](https://openjdk.java.net/) / [SapMachine](https://sap.github.io/SapMachine/)
90 * [Maven 3.6](https://maven.apache.org/)
91 * [Postgres]
92 * [MinIO]
93
94 #### Configure
95
96 After you made sure that the specified dependencies are running, configure them in the respective configuration files.
97
98 * Configure the Postgres connection in the [submission config](./services/submission/src/main/resources/application.properties) and in the [distribution config](./services/distribution/src/main/resources/application.properties)
99 * Configure the S3 compatible object storage in the [distribution config](./services/distribution/src/main/resources/application.properties)
100
101 #### Build
102
103 After you've checked out the repository, to build the project, run ```mvn install``` in your base directory.
104
105 #### Run
106
107 Navigate to the service you want to start and run the spring-boot:run target. The configured Postgres and the configured S3 compliant object storage are used as default. When you start the submission service, the endpoint is available on your local port 8080.
108
109 If you want to start the submission service, for example, you start it as follows:
110
111 ```bash
112 cd services/submission/
113 mvn spring-boot:run
114 ```
115
116 #### Debugging
117
118 To enable the `DEBUG` log level, you can run the application using the Spring `dev` profile.
119
120 ```bash
121 mvn spring-boot:run -Dspring-boot.run.profiles=dev
122 ```
123
124 To be able to set breakpoints (e.g. in IntelliJ), it may be necessary to use the ```-Dspring-boot.run.fork=false``` parameter.
125
126 ## Service APIs
127
128 The API that is being exposed by the backend services is documented in an [OpenAPI](https://www.openapis.org/) specification. The specification files are available at the following locations:
129
130 Service | OpenAPI Specification
131 -------------|-------------
132 Submission Service | https://github.com/corona-warn-app/cwa-server/raw/master/services/submission/api_v1.json
133 Distribution Service | https://github.com/corona-warn-app/cwa-server/raw/master/services/distribution/api_v1.json
134
135 ## Documentation
136
137 The full documentation for the Corona-Warn-App can be found in the [cwa-documentation](https://github.com/corona-warn-app/cwa-documentation) repository. The documentation repository contains technical documents, architecture information, and whitepapers related to this implementation.
138
139 ## Support and Feedback
140
141 The following channels are available for discussions, feedback, and support requests:
142
143 | Type | Channel |
144 | ------------------------ | ------------------------------------------------------ |
145 | **General Discussion** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="General Discussion"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/question.svg?style=flat-square"></a> </a> |
146 | **Concept Feedback** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="Open Concept Feedback"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/architecture.svg?style=flat-square"></a> |
147 | **Backend Issue** | <a href="https://github.com/corona-warn-app/cwa-server/issues/new/choose" title="Open Backend Issue"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat-square"></a> |
148 | **Other Requests** | <a href="mailto:[email protected]" title="Email CWD Team"><img src="https://img.shields.io/badge/email-CWD%20team-green?logo=mail.ru&style=flat-square&logoColor=white"></a> |
149
150 ## How to Contribute
151
152 Contribution and feedback are 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.
153
154 ## Contributors
155
156 The German government has asked SAP and Deutsche Telekom to develop the Corona-Warn-App for Germany as open source software. Deutsche Telekom is providing the network and mobile technology and will operate and run the backend for the app in a safe, scalable and stable manner. SAP is responsible for the app development, its framework and the underlying platform. Therefore, development teams of SAP and Deutsche Telekom are contributing to this project. At the same time 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.
157
158 ## Repositories
159
160 The following public repositories are currently available for the Corona-Warn-App:
161
162 | Repository | Description |
163 | ------------------- | --------------------------------------------------------------------- |
164 | [cwa-documentation] | Project overview, general documentation, and white papers |
165 | [cwa-server] | Backend implementation for the Apple/Google exposure notification API|
166
167 [cwa-documentation]: https://github.com/corona-warn-app/cwa-documentation
168 [cwa-server]: https://github.com/corona-warn-app/cwa-server
169 [Postgres]: https://www.postgresql.org/
170 [MinIO]: https://min.io/
171 [HSQLDB]: http://hsqldb.org/
172
173 ## Licensing
174
175 Copyright (c) 2020 SAP SE or an SAP affiliate company.
176
177 Licensed under the **Apache License, Version 2.0** (the "License"); you may not use this file except in compliance with the License.
178
179 You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0.
180
181 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.
182
[end of README.md]
[start of .env]
1 # This file contains simple default values for the deployment through Docker Compose
2 # Please change these default values before running docker-compose
3
4 # Docker Compose Postgres settings
5 POSTGRES_DB=cwa
6 POSTGRES_USER=postgres
7 POSTGRES_PASSWORD=postgres
8
9 # Docker Compose PgAdmin settings
10 [email protected]
11 PGADMIN_DEFAULT_PASSWORD=password
12
13 # Docker Compose MinIO settings
14 MINIO_ACCESS_KEY=minioadmin
15 MINIO_SECRET_KEY=minioadmin
16
17 # Docker Compose Secrets settings
18 SECRET_PRIVATE=file:/secrets/private.pem
19 SECRET_CERTIFICATE=file:/secrets/certificate.crt
20
[end of .env]
[start of /dev/null]
1
[end of /dev/null]
[start of README.md]
1 <h1 align="center">
2 Corona-Warn-App Server
3 </h1>
4
5 <p align="center">
6 <a href="https://github.com/corona-warn-app/cwa-server/commits/" title="Last Commit"><img src="https://img.shields.io/github/last-commit/corona-warn-app/cwa-server?style=flat"></a>
7 <a href="https://github.com/corona-warn-app/cwa-server/issues" title="Open Issues"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat"></a>
8 <a href="https://circleci.com/gh/corona-warn-app/cwa-server" title="Build Status"><img src="https://circleci.com/gh/corona-warn-app/cwa-server.svg?style=shield&circle-token=4ab059989d10709df19eb4b98ab7c121a25e981a"></a>
9 <a href="https://sonarcloud.io/dashboard?id=corona-warn-app_cwa-server" title="Quality Gate"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=alert_status"></a>
10 <a href="https://sonarcloud.io/component_measures?id=corona-warn-app_cwa-server&metric=Coverage&view=list" title="Coverage"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=coverage"></a>
11 <a href="https://github.com/corona-warn-app/cwa-server/blob/master/LICENSE" title="License"><img src="https://img.shields.io/badge/License-Apache%202.0-green.svg?style=flat"></a>
12 </p>
13
14 <p align="center">
15 <a href="#development">Development</a> •
16 <a href="#service-apis">Service APIs</a> •
17 <a href="#documentation">Documentation</a> •
18 <a href="#support-and-feedback">Support</a> •
19 <a href="#how-to-contribute">Contribute</a> •
20 <a href="#contributors">Contributors</a> •
21 <a href="#repositories">Repositories</a> •
22 <a href="#licensing">Licensing</a>
23 </p>
24
25 The goal of this project is to develop the official Corona-Warn-App for Germany based on the exposure notification API from [Apple](https://www.apple.com/covid19/contacttracing/) and [Google](https://www.google.com/covid19/exposurenotifications/). The apps (for both iOS and Android) use Bluetooth technology to exchange anonymous encrypted data with other mobile phones (on which the app is also installed) in the vicinity of an app user's phone. The data is stored locally on each user's device, preventing authorities or other parties from accessing or controlling the data. This repository contains the **implementation of the server for encryption keys** for the Corona-Warn-App. This implementation is still a **work in progress**, and the code it contains is currently alpha-quality code.
26
27 In this documentation, Corona-Warn-App services are also referred to as CWA services.
28
29 ## Architecture Overview
30
31 You can find the architecture overview [here](/docs/architecture-overview.md), which will give you
32 a good starting point in how the backend services interact with other services, and what purpose
33 they serve.
34
35 ## Development
36
37 After you've checked out this repository, you can run the application in one of the following ways:
38
39 * As a [Docker](https://www.docker.com/)-based deployment on your local machine. You can run either:
40 * Single components using the respective Dockerfile or
41 * The full backend using the Docker Compose (which is considered the most convenient way)
42 * As a [Maven](https://maven.apache.org)-based build on your local machine.
43 If you want to develop something in a single component, this approach is preferable.
44
45 ### Docker-Based Deployment
46
47 If you want to use Docker-based deployment, you need to install Docker on your local machine. For more information about downloading and installing Docker, see the [official Docker documentation](https://docs.docker.com/get-docker/).
48
49 #### Running the Full CWA Backend Using Docker Compose
50
51 For your convenience, a full setup including the generation of test data has been prepared using [Docker Compose](https://docs.docker.com/compose/reference/overview/). To build the backend services, run ```docker-compose build``` in the repository's root directory. A default configuration file can be found under ```.env```in the root folder of the repository. The default values for the local Postgres and MinIO-build should be changed in this file before docker-compose is run.
52
53 Once the services are built, you can start the whole backend using ```docker-compose up```.
54 The distribution service runs once and then finishes. If you want to trigger additional distribution runs, run ```docker-compose start distribution```.
55
56 The docker-compose contains the following services:
57
58 Service | Description | Endpoint and Default Credentials
59 --------------|-------------|-----------
60 submission | The Corona-Warn-App submission service | http://localhost:8080
61 distribution | The Corona-Warn-App distribution service | NO ENDPOINT
62 postgres | A [postgres] database installation | postgres:5432 <br> Username: postgres <br> Password: postgres
63 pgadmin | A [pgadmin](https://www.pgadmin.org/) installation for the postgres database | http://localhost:8081 <br> Username: [email protected] <br> Password: password
64 minio | [MinIO] is an S3-compliant object store | http://localhost:8082/ <br> Access key: minioadmin <br> Secret key: minioadmin
65
66 #### Running Single CWA Services Using Docker
67
68 If you would like to build and run a single CWA service, it's considered easiest to run them in a Docker environment. You can do this using the script provided in the respective CWA service directory. The Docker script first builds the CWA service and then creates an image for the runtime, which means that there are no additional dependencies for you to install.
69
70 To build and run the distribution service, run the following command:
71
72 ```bash
73 ./services/distribution/build_and_run.sh
74 ```
75
76 To build and run the submission service, run the following command:
77
78 ```bash
79 ./services/submission/build_and_run.sh
80 ```
81
82 The submission service is available on [localhost:8080](http://localhost:8080 ).
83
84 ### Maven-Based Build
85
86 If you want to actively develop in one of the CWA services, the Maven-based runtime is most suitable.
87 To prepare your machine to run the CWA project locally, we recommend that you first ensure that you've installed the following:
88
89 * Minimum JDK Version 11: [OpenJDK](https://openjdk.java.net/) / [SapMachine](https://sap.github.io/SapMachine/)
90 * [Maven 3.6](https://maven.apache.org/)
91 * [Postgres]
92 * [MinIO]
93
94 #### Configure
95
96 After you made sure that the specified dependencies are running, configure them in the respective configuration files.
97
98 * Configure the Postgres connection in the [submission config](./services/submission/src/main/resources/application.properties) and in the [distribution config](./services/distribution/src/main/resources/application.properties)
99 * Configure the S3 compatible object storage in the [distribution config](./services/distribution/src/main/resources/application.properties)
100
101 #### Build
102
103 After you've checked out the repository, to build the project, run ```mvn install``` in your base directory.
104
105 #### Run
106
107 Navigate to the service you want to start and run the spring-boot:run target. The configured Postgres and the configured S3 compliant object storage are used as default. When you start the submission service, the endpoint is available on your local port 8080.
108
109 If you want to start the submission service, for example, you start it as follows:
110
111 ```bash
112 cd services/submission/
113 mvn spring-boot:run
114 ```
115
116 #### Debugging
117
118 To enable the `DEBUG` log level, you can run the application using the Spring `dev` profile.
119
120 ```bash
121 mvn spring-boot:run -Dspring-boot.run.profiles=dev
122 ```
123
124 To be able to set breakpoints (e.g. in IntelliJ), it may be necessary to use the ```-Dspring-boot.run.fork=false``` parameter.
125
126 ## Service APIs
127
128 The API that is being exposed by the backend services is documented in an [OpenAPI](https://www.openapis.org/) specification. The specification files are available at the following locations:
129
130 Service | OpenAPI Specification
131 -------------|-------------
132 Submission Service | https://github.com/corona-warn-app/cwa-server/raw/master/services/submission/api_v1.json
133 Distribution Service | https://github.com/corona-warn-app/cwa-server/raw/master/services/distribution/api_v1.json
134
135 ## Documentation
136
137 The full documentation for the Corona-Warn-App can be found in the [cwa-documentation](https://github.com/corona-warn-app/cwa-documentation) repository. The documentation repository contains technical documents, architecture information, and whitepapers related to this implementation.
138
139 ## Support and Feedback
140
141 The following channels are available for discussions, feedback, and support requests:
142
143 | Type | Channel |
144 | ------------------------ | ------------------------------------------------------ |
145 | **General Discussion** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="General Discussion"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/question.svg?style=flat-square"></a> </a> |
146 | **Concept Feedback** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="Open Concept Feedback"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/architecture.svg?style=flat-square"></a> |
147 | **Backend Issue** | <a href="https://github.com/corona-warn-app/cwa-server/issues/new/choose" title="Open Backend Issue"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat-square"></a> |
148 | **Other Requests** | <a href="mailto:[email protected]" title="Email CWD Team"><img src="https://img.shields.io/badge/email-CWD%20team-green?logo=mail.ru&style=flat-square&logoColor=white"></a> |
149
150 ## How to Contribute
151
152 Contribution and feedback are 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.
153
154 ## Contributors
155
156 The German government has asked SAP and Deutsche Telekom to develop the Corona-Warn-App for Germany as open source software. Deutsche Telekom is providing the network and mobile technology and will operate and run the backend for the app in a safe, scalable and stable manner. SAP is responsible for the app development, its framework and the underlying platform. Therefore, development teams of SAP and Deutsche Telekom are contributing to this project. At the same time 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.
157
158 ## Repositories
159
160 The following public repositories are currently available for the Corona-Warn-App:
161
162 | Repository | Description |
163 | ------------------- | --------------------------------------------------------------------- |
164 | [cwa-documentation] | Project overview, general documentation, and white papers |
165 | [cwa-server] | Backend implementation for the Apple/Google exposure notification API|
166
167 [cwa-documentation]: https://github.com/corona-warn-app/cwa-documentation
168 [cwa-server]: https://github.com/corona-warn-app/cwa-server
169 [Postgres]: https://www.postgresql.org/
170 [MinIO]: https://min.io/
171 [HSQLDB]: http://hsqldb.org/
172
173 ## Licensing
174
175 Copyright (c) 2020 SAP SE or an SAP affiliate company.
176
177 Licensed under the **Apache License, Version 2.0** (the "License"); you may not use this file except in compliance with the License.
178
179 You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0.
180
181 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.
182
[end of README.md]
[start of THIRD-PARTY-NOTICES]
1 ThirdPartyNotices
2 -----------------
3 corona-warn-app/cwa-server uses third-party software or other resources that
4 may be distributed under licenses different from corona-warn-app/cwa-server
5 software.
6 In the event that we overlooked to list a required notice, please bring this
7 to our attention by contacting us via this email:
8 [email protected]
9
10
11 Components:
12 -----------
13 Component: Bouncy Castle
14 Licensor: Legion of the Bouncy Castle Inc.
15 Website: https://www.bouncycastle.org/
16 License: MIT License
17
18 Component: Commons IO
19 Licensor: Apache Software Foundation
20 Website: https://commons.apache.org/proper/commons-io/
21 License: Apache License 2.0
22
23 Component: Commons Math 3
24 Licensor: Apache Software Foundation
25 Website: https://commons.apache.org/proper/commons-math/
26 License: Apache License 2.0
27
28 Component: dom4j
29 Licensor: dom4j
30 Website: https://dom4j.github.io/
31 License: BSD License
32
33 Component: flyway
34 Licensor: flyway
35 Website: https://github.com/flyway/flyway
36 License: Apache License 2.0
37
38 Component: H2Database
39 Licensor: H2
40 Website: http://www.h2database.com/
41 License: Mozilla Public License 2.0
42
43 Component: JSON-Simple
44 Licensor: Yidong Fang
45 Website: https://github.com/fangyidong/json-simple
46 License: Apache License 2.0
47
48 Component: Maven
49 Licensor: Apache Software Foundation
50 Website: https://maven.apache.org/
51 License: Apache License 2.0
52
53 Component: MinIO Object Storage
54 Licensor: MinIO Inc.
55 Website: https://min.io/
56 License: Apache License 2.0
57
58 Component: PostgreSQL
59 Licensor: PostgreSQL
60 Website: https://www.postgresql.org/
61 License: PostgreSQL License
62
63 Component: Protocol Buffers
64 Licensor: Google Inc.
65 Website: https://developers.google.com/protocol-buffers/
66 License: 3-Clause BSD License
67
68 Component: snakeyaml
69 Licensor: snakeyaml
70 Website: https://bitbucket.org/asomov/snakeyaml/
71 License: Apache License 2.0
72
73 Component: Spring Boot
74 Licensor: VMWare Inc.
75 Website: https://spring.io/
76 License: Apache License 2.0
77 --------------------------------------------------------------------------------
78 Apache License 2.0 (Commons IO, Commons Math 3, flyway, JSON-Simple,
79 Maven, MinIO Object Storage, snakeyaml, Spring Boot)
80
81 Apache License
82 Version 2.0, January 2004
83 https://www.apache.org/licenses/
84
85 TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
86
87 1. Definitions.
88
89 "License" shall mean the terms and conditions for use, reproduction,
90 and distribution as defined by Sections 1 through 9 of this document.
91
92 "Licensor" shall mean the copyright owner or entity authorized by
93 the copyright owner that is granting the License.
94
95 "Legal Entity" shall mean the union of the acting entity and all
96 other entities that control, are controlled by, or are under common
97 control with that entity. For the purposes of this definition,
98 "control" means (i) the power, direct or indirect, to cause the
99 direction or management of such entity, whether by contract or
100 otherwise, or (ii) ownership of fifty percent (50%) or more of the
101 outstanding shares, or (iii) beneficial ownership of such entity.
102
103 "You" (or "Your") shall mean an individual or Legal Entity
104 exercising permissions granted by this License.
105
106 "Source" form shall mean the preferred form for making modifications,
107 including but not limited to software source code, documentation
108 source, and configuration files.
109
110 "Object" form shall mean any form resulting from mechanical
111 transformation or translation of a Source form, including but
112 not limited to compiled object code, generated documentation,
113 and conversions to other media types.
114
115 "Work" shall mean the work of authorship, whether in Source or
116 Object form, made available under the License, as indicated by a
117 copyright notice that is included in or attached to the work
118 (an example is provided in the Appendix below).
119
120 "Derivative Works" shall mean any work, whether in Source or Object
121 form, that is based on (or derived from) the Work and for which the
122 editorial revisions, annotations, elaborations, or other modifications
123 represent, as a whole, an original work of authorship. For the purposes
124 of this License, Derivative Works shall not include works that remain
125 separable from, or merely link (or bind by name) to the interfaces of,
126 the Work and Derivative Works thereof.
127
128 "Contribution" shall mean any work of authorship, including
129 the original version of the Work and any modifications or additions
130 to that Work or Derivative Works thereof, that is intentionally
131 submitted to Licensor for inclusion in the Work by the copyright owner
132 or by an individual or Legal Entity authorized to submit on behalf of
133 the copyright owner. For the purposes of this definition, "submitted"
134 means any form of electronic, verbal, or written communication sent
135 to the Licensor or its representatives, including but not limited to
136 communication on electronic mailing lists, source code control systems,
137 and issue tracking systems that are managed by, or on behalf of, the
138 Licensor for the purpose of discussing and improving the Work, but
139 excluding communication that is conspicuously marked or otherwise
140 designated in writing by the copyright owner as "Not a Contribution."
141
142 "Contributor" shall mean Licensor and any individual or Legal Entity
143 on behalf of whom a Contribution has been received by Licensor and
144 subsequently incorporated within the Work.
145
146 2. Grant of Copyright License. Subject to the terms and conditions of
147 this License, each Contributor hereby grants to You a perpetual,
148 worldwide, non-exclusive, no-charge, royalty-free, irrevocable
149 copyright license to reproduce, prepare Derivative Works of,
150 publicly display, publicly perform, sublicense, and distribute the
151 Work and such Derivative Works in Source or Object form.
152
153 3. Grant of Patent License. Subject to the terms and conditions of
154 this License, each Contributor hereby grants to You a perpetual,
155 worldwide, non-exclusive, no-charge, royalty-free, irrevocable
156 (except as stated in this section) patent license to make, have made,
157 use, offer to sell, sell, import, and otherwise transfer the Work,
158 where such license applies only to those patent claims licensable
159 by such Contributor that are necessarily infringed by their
160 Contribution(s) alone or by combination of their Contribution(s)
161 with the Work to which such Contribution(s) was submitted. If You
162 institute patent litigation against any entity (including a
163 cross-claim or counterclaim in a lawsuit) alleging that the Work
164 or a Contribution incorporated within the Work constitutes direct
165 or contributory patent infringement, then any patent licenses
166 granted to You under this License for that Work shall terminate
167 as of the date such litigation is filed.
168
169 4. Redistribution. You may reproduce and distribute copies of the
170 Work or Derivative Works thereof in any medium, with or without
171 modifications, and in Source or Object form, provided that You
172 meet the following conditions:
173
174 (a) You must give any other recipients of the Work or
175 Derivative Works a copy of this License; and
176
177 (b) You must cause any modified files to carry prominent notices
178 stating that You changed the files; and
179
180 (c) You must retain, in the Source form of any Derivative Works
181 that You distribute, all copyright, patent, trademark, and
182 attribution notices from the Source form of the Work,
183 excluding those notices that do not pertain to any part of
184 the Derivative Works; and
185
186 (d) If the Work includes a "NOTICE" text file as part of its
187 distribution, then any Derivative Works that You distribute must
188 include a readable copy of the attribution notices contained
189 within such NOTICE file, excluding those notices that do not
190 pertain to any part of the Derivative Works, in at least one
191 of the following places: within a NOTICE text file distributed
192 as part of the Derivative Works; within the Source form or
193 documentation, if provided along with the Derivative Works; or,
194 within a display generated by the Derivative Works, if and
195 wherever such third-party notices normally appear. The contents
196 of the NOTICE file are for informational purposes only and
197 do not modify the License. You may add Your own attribution
198 notices within Derivative Works that You distribute, alongside
199 or as an addendum to the NOTICE text from the Work, provided
200 that such additional attribution notices cannot be construed
201 as modifying the License.
202
203 You may add Your own copyright statement to Your modifications and
204 may provide additional or different license terms and conditions
205 for use, reproduction, or distribution of Your modifications, or
206 for any such Derivative Works as a whole, provided Your use,
207 reproduction, and distribution of the Work otherwise complies with
208 the conditions stated in this License.
209
210 5. Submission of Contributions. Unless You explicitly state otherwise,
211 any Contribution intentionally submitted for inclusion in the Work
212 by You to the Licensor shall be under the terms and conditions of
213 this License, without any additional terms or conditions.
214 Notwithstanding the above, nothing herein shall supersede or modify
215 the terms of any separate license agreement you may have executed
216 with Licensor regarding such Contributions.
217
218 6. Trademarks. This License does not grant permission to use the trade
219 names, trademarks, service marks, or product names of the Licensor,
220 except as required for reasonable and customary use in describing the
221 origin of the Work and reproducing the content of the NOTICE file.
222
223 7. Disclaimer of Warranty. Unless required by applicable law or
224 agreed to in writing, Licensor provides the Work (and each
225 Contributor provides its Contributions) on an "AS IS" BASIS,
226 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
227 implied, including, without limitation, any warranties or conditions
228 of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
229 PARTICULAR PURPOSE. You are solely responsible for determining the
230 appropriateness of using or redistributing the Work and assume any
231 risks associated with Your exercise of permissions under this License.
232
233 8. Limitation of Liability. In no event and under no legal theory,
234 whether in tort (including negligence), contract, or otherwise,
235 unless required by applicable law (such as deliberate and grossly
236 negligent acts) or agreed to in writing, shall any Contributor be
237 liable to You for damages, including any direct, indirect, special,
238 incidental, or consequential damages of any character arising as a
239 result of this License or out of the use or inability to use the
240 Work (including but not limited to damages for loss of goodwill,
241 work stoppage, computer failure or malfunction, or any and all
242 other commercial damages or losses), even if such Contributor
243 has been advised of the possibility of such damages.
244
245 9. Accepting Warranty or Additional Liability. While redistributing
246 the Work or Derivative Works thereof, You may choose to offer,
247 and charge a fee for, acceptance of support, warranty, indemnity,
248 or other liability obligations and/or rights consistent with this
249 License. However, in accepting such obligations, You may act only
250 on Your own behalf and on Your sole responsibility, not on behalf
251 of any other Contributor, and only if You agree to indemnify,
252 defend, and hold each Contributor harmless for any liability
253 incurred by, or claims asserted against, such Contributor by reason
254 of your accepting any such warranty or additional liability.
255
256 END OF TERMS AND CONDITIONS
257 --------------------------------------------------------------------------------
258 BSD License (dom4j)
259
260 Copyright 2001-2016 (C) MetaStuff, Ltd. and DOM4J contributors. All Rights Reserved.
261
262 Redistribution and use of this software and associated documentation
263 ("Software"), with or without modification, are permitted provided
264 that the following conditions are met:
265
266 1. Redistributions of source code must retain copyright
267 statements and notices. Redistributions must also contain a
268 copy of this document.
269
270 2. Redistributions in binary form must reproduce the
271 above copyright notice, this list of conditions and the
272 following disclaimer in the documentation and/or other
273 materials provided with the distribution.
274
275 3. The name "DOM4J" must not be used to endorse or promote
276 products derived from this Software without prior written
277 permission of MetaStuff, Ltd. For written permission,
278 please contact [email protected].
279
280 4. Products derived from this Software may not be called "DOM4J"
281 nor may "DOM4J" appear in their names without prior written
282 permission of MetaStuff, Ltd. DOM4J is a registered
283 trademark of MetaStuff, Ltd.
284
285 5. Due credit should be given to the DOM4J Project - https://dom4j.github.io/
286
287 THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS
288 ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT
289 NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
290 FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
291 METASTUFF, LTD. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
292 INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
293 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
294 SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
295 HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
296 STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
297 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
298 OF THE POSSIBILITY OF SUCH DAMAGE.
299 --------------------------------------------------------------------------------
300 3-Clause BSD License (Protocol Buffers)
301
302 Copyright 2008 Google Inc. All rights reserved.
303
304 Redistribution and use in source and binary forms, with or without
305 modification, are permitted provided that the following conditions are
306 met:
307
308 * Redistributions of source code must retain the above copyright
309 notice, this list of conditions and the following disclaimer.
310 * Redistributions in binary form must reproduce the above
311 copyright notice, this list of conditions and the following disclaimer
312 in the documentation and/or other materials provided with the
313 distribution.
314 * Neither the name of Google Inc. nor the names of its
315 contributors may be used to endorse or promote products derived from
316 this software without specific prior written permission.
317
318 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
319 "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
320 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
321 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
322 OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
323 SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
324 LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
325 DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
326 THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
327 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
328 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
329
330 Code generated by the Protocol Buffer compiler is owned by the owner
331 of the input file used when generating it. This code is not
332 standalone and requires a support library to be linked with it. This
333 support library is itself covered by the above license.
334 --------------------------------------------------------------------------------
335 PostgreSQL License (PostgreSQL)
336
337 PostgreSQL Database Management System
338 (formerly known as Postgres, then as Postgres95)
339
340 Portions Copyright © 1996-2020, The PostgreSQL Global Development Group
341
342 Portions Copyright © 1994, The Regents of the University of California
343
344 Permission to use, copy, modify, and distribute this software and its
345 documentation for any purpose, without fee, and without a written agreement is
346 hereby granted, provided that the above copyright notice and this paragraph and
347 the following two paragraphs appear in all copies.
348
349 IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
350 DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST
351 PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF
352 THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
353
354 THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
355 BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
356 PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND
357 THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,
358 UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
359 --------------------------------------------------------------------------------
360 Mozilla Public License 2.0 (H2Database)
361
362 Mozilla Public License
363 Version 2.0
364 1. Definitions
365 1.1. “Contributor”
366 means each individual or legal entity that creates, contributes to the creation
367 of, or owns Covered Software.
368
369 1.2. “Contributor Version”
370 means the combination of the Contributions of others (if any) used by a
371 Contributor and that particular Contributor’s Contribution.
372
373 1.3. “Contribution”
374 means Covered Software of a particular Contributor.
375
376 1.4. “Covered Software”
377 means Source Code Form to which the initial Contributor has attached the notice
378 in Exhibit A, the Executable Form of such Source Code Form, and Modifications
379 of such Source Code Form, in each case including portions thereof.
380
381 1.5. “Incompatible With Secondary Licenses”
382 means
383
384 that the initial Contributor has attached the notice described in Exhibit B to
385 the Covered Software; or
386
387 that the Covered Software was made available under the terms of version 1.1 or
388 earlier of the License, but not also under the terms of a Secondary License.
389
390 1.6. “Executable Form”
391 means any form of the work other than Source Code Form.
392
393 1.7. “Larger Work”
394 means a work that combines Covered Software with other material, in a separate
395 file or files, that is not Covered Software.
396
397 1.8. “License”
398 means this document.
399
400 1.9. “Licensable”
401 means having the right to grant, to the maximum extent possible, whether at the
402 time of the initial grant or subsequently, any and all of the rights conveyed
403 by this License.
404
405 1.10. “Modifications”
406 means any of the following:
407
408 any file in Source Code Form that results from an addition to, deletion from,
409 or modification of the contents of Covered Software; or
410
411 any new file in Source Code Form that contains any Covered Software.
412
413 1.11. “Patent Claims” of a Contributor
414 means any patent claim(s), including without limitation, method, process, and
415 apparatus claims, in any patent Licensable by such Contributor that would be
416 infringed, but for the grant of the License, by the making, using, selling,
417 offering for sale, having made, import, or transfer of either its Contributions
418 or its Contributor Version.
419
420 1.12. “Secondary License”
421 means either the GNU General Public License, Version 2.0, the GNU Lesser
422 General Public License, Version 2.1, the GNU Affero General Public License,
423 Version 3.0, or any later versions of those licenses.
424
425 1.13. “Source Code Form”
426 means the form of the work preferred for making modifications.
427
428 1.14. “You” (or “Your”)
429 means an individual or a legal entity exercising rights under this License. For
430 legal entities, “You” includes any entity that controls, is controlled by, or
431 is under common control with You. For purposes of this definition, “control”
432 means (a) the power, direct or indirect, to cause the direction or management
433 of such entity, whether by contract or otherwise, or (b) ownership of more than
434 fifty percent (50%) of the outstanding shares or beneficial ownership of such
435 entity.
436
437 2. License Grants and Conditions
438 2.1. Grants
439 Each Contributor hereby grants You a world-wide, royalty-free, non-exclusive
440 license:
441
442 under intellectual property rights (other than patent or trademark) Licensable
443 by such Contributor to use, reproduce, make available, modify, display,
444 perform, distribute, and otherwise exploit its Contributions, either on an
445 unmodified basis, with Modifications, or as part of a Larger Work; and
446
447 under Patent Claims of such Contributor to make, use, sell, offer for sale,
448 have made, import, and otherwise transfer either its Contributions or its
449 Contributor Version.
450
451 2.2. Effective Date
452 The licenses granted in Section 2.1 with respect to any Contribution become
453 effective for each Contribution on the date the Contributor first distributes
454 such Contribution.
455
456 2.3. Limitations on Grant Scope
457 The licenses granted in this Section 2 are the only rights granted under this
458 License. No additional rights or licenses will be implied from the distribution
459 or licensing of Covered Software under this License. Notwithstanding Section
460 2.1(b) above, no patent license is granted by a Contributor:
461
462 for any code that a Contributor has removed from Covered Software; or
463
464 for infringements caused by: (i) Your and any other third party’s modifications
465 of Covered Software, or (ii) the combination of its Contributions with other
466 software (except as part of its Contributor Version); or
467
468 under Patent Claims infringed by Covered Software in the absence of its
469 Contributions.
470
471 This License does not grant any rights in the trademarks, service marks, or
472 logos of any Contributor (except as may be necessary to comply with the notice
473 requirements in Section 3.4).
474
475 2.4. Subsequent Licenses
476 No Contributor makes additional grants as a result of Your choice to distribute
477 the Covered Software under a subsequent version of this License (see Section
478 10.2) or under the terms of a Secondary License (if permitted under the terms
479 of Section 3.3).
480
481 2.5. Representation
482 Each Contributor represents that the Contributor believes its Contributions are
483 its original creation(s) or it has sufficient rights to grant the rights to its
484 Contributions conveyed by this License.
485
486 2.6. Fair Use
487 This License is not intended to limit any rights You have under applicable
488 copyright doctrines of fair use, fair dealing, or other equivalents.
489
490 2.7. Conditions
491 Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in
492 Section 2.1.
493
494 3. Responsibilities
495 3.1. Distribution of Source Form
496 All distribution of Covered Software in Source Code Form, including any
497 Modifications that You create or to which You contribute, must be under the
498 terms of this License. You must inform recipients that the Source Code Form of
499 the Covered Software is governed by the terms of this License, and how they can
500 obtain a copy of this License. You may not attempt to alter or restrict the
501 recipients’ rights in the Source Code Form.
502
503 3.2. Distribution of Executable Form
504 If You distribute Covered Software in Executable Form then:
505
506 such Covered Software must also be made available in Source Code Form, as
507 described in Section 3.1, and You must inform recipients of the Executable Form
508 how they can obtain a copy of such Source Code Form by reasonable means in a
509 timely manner, at a charge no more than the cost of distribution to the
510 recipient; and
511
512 You may distribute such Executable Form under the terms of this License, or
513 sublicense it under different terms, provided that the license for the
514 Executable Form does not attempt to limit or alter the recipients’ rights in
515 the Source Code Form under this License.
516
517 3.3. Distribution of a Larger Work
518 You may create and distribute a Larger Work under terms of Your choice,
519 provided that You also comply with the requirements of this License for the
520 Covered Software. If the Larger Work is a combination of Covered Software with
521 a work governed by one or more Secondary Licenses, and the Covered Software is
522 not Incompatible With Secondary Licenses, this License permits You to
523 additionally distribute such Covered Software under the terms of such Secondary
524 License(s), so that the recipient of the Larger Work may, at their option,
525 further distribute the Covered Software under the terms of either this License
526 or such Secondary License(s).
527
528 3.4. Notices
529 You may not remove or alter the substance of any license notices (including
530 copyright notices, patent notices, disclaimers of warranty, or limitations of
531 liability) contained within the Source Code Form of the Covered Software,
532 except that You may alter any license notices to the extent required to remedy
533 known factual inaccuracies.
534
535 3.5. Application of Additional Terms
536 You may choose to offer, and to charge a fee for, warranty, support, indemnity
537 or liability obligations to one or more recipients of Covered Software.
538 However, You may do so only on Your own behalf, and not on behalf of any
539 Contributor. You must make it absolutely clear that any such warranty, support,
540 indemnity, or liability obligation is offered by You alone, and You hereby
541 agree to indemnify every Contributor for any liability incurred by such
542 Contributor as a result of warranty, support, indemnity or liability terms You
543 offer. You may include additional disclaimers of warranty and limitations of
544 liability specific to any jurisdiction.
545
546 4. Inability to Comply Due to Statute or Regulation
547 If it is impossible for You to comply with any of the terms of this License
548 with respect to some or all of the Covered Software due to statute, judicial
549 order, or regulation then You must: (a) comply with the terms of this License
550 to the maximum extent possible; and (b) describe the limitations and the code
551 they affect. Such description must be placed in a text file included with all
552 distributions of the Covered Software under this License. Except to the extent
553 prohibited by statute or regulation, such description must be sufficiently
554 detailed for a recipient of ordinary skill to be able to understand it.
555
556 5. Termination
557 5.1. The rights granted under this License will terminate automatically if You
558 fail to comply with any of its terms. However, if You become compliant, then
559 the rights granted under this License from a particular Contributor are
560 reinstated (a) provisionally, unless and until such Contributor explicitly and
561 finally terminates Your grants, and (b) on an ongoing basis, if such
562 Contributor fails to notify You of the non-compliance by some reasonable means
563 prior to 60 days after You have come back into compliance. Moreover, Your
564 grants from a particular Contributor are reinstated on an ongoing basis if such
565 Contributor notifies You of the non-compliance by some reasonable means, this
566 is the first time You have received notice of non-compliance with this License
567 from such Contributor, and You become compliant prior to 30 days after Your
568 receipt of the notice.
569
570 5.2. If You initiate litigation against any entity by asserting a patent
571 infringement claim (excluding declaratory judgment actions, counter-claims, and
572 cross-claims) alleging that a Contributor Version directly or indirectly
573 infringes any patent, then the rights granted to You by any and all
574 Contributors for the Covered Software under Section 2.1 of this License shall
575 terminate.
576
577 5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user
578 license agreements (excluding distributors and resellers) which have been
579 validly granted by You or Your distributors under this License prior to
580 termination shall survive termination.
581
582 6. Disclaimer of Warranty
583 Covered Software is provided under this License on an “as is” basis, without
584 warranty of any kind, either expressed, implied, or statutory, including,
585 without limitation, warranties that the Covered Software is free of defects,
586 merchantable, fit for a particular purpose or non-infringing. The entire risk
587 as to the quality and performance of the Covered Software is with You. Should
588 any Covered Software prove defective in any respect, You (not any Contributor)
589 assume the cost of any necessary servicing, repair, or correction. This
590 disclaimer of warranty constitutes an essential part of this License. No use of
591 any Covered Software is authorized under this License except under this
592 disclaimer.
593
594 7. Limitation of Liability
595 Under no circumstances and under no legal theory, whether tort (including
596 negligence), contract, or otherwise, shall any Contributor, or anyone who
597 distributes Covered Software as permitted above, be liable to You for any
598 direct, indirect, special, incidental, or consequential damages of any
599 character including, without limitation, damages for lost profits, loss of
600 goodwill, work stoppage, computer failure or malfunction, or any and all other
601 commercial damages or losses, even if such party shall have been informed of
602 the possibility of such damages. This limitation of liability shall not apply
603 to liability for death or personal injury resulting from such party’s
604 negligence to the extent applicable law prohibits such limitation. Some
605 jurisdictions do not allow the exclusion or limitation of incidental or
606 consequential damages, so this exclusion and limitation may not apply to You.
607
608 8. Litigation
609 Any litigation relating to this License may be brought only in the courts of a
610 jurisdiction where the defendant maintains its principal place of business and
611 such litigation shall be governed by laws of that jurisdiction, without
612 reference to its conflict-of-law provisions. Nothing in this Section shall
613 prevent a party’s ability to bring cross-claims or counter-claims.
614
615 9. Miscellaneous
616 This License represents the complete agreement concerning the subject matter
617 hereof. If any provision of this License is held to be unenforceable, such
618 provision shall be reformed only to the extent necessary to make it
619 enforceable. Any law or regulation which provides that the language of a
620 contract shall be construed against the drafter shall not be used to construe
621 this License against a Contributor.
622
623 10. Versions of the License
624 10.1. New Versions
625 Mozilla Foundation is the license steward. Except as provided in Section 10.3,
626 no one other than the license steward has the right to modify or publish new
627 versions of this License. Each version will be given a distinguishing version
628 number.
629
630 10.2. Effect of New Versions
631 You may distribute the Covered Software under the terms of the version of the
632 License under which You originally received the Covered Software, or under the
633 terms of any subsequent version published by the license steward.
634
635 10.3. Modified Versions
636 If you create software not governed by this License, and you want to create a
637 new license for such software, you may create and use a modified version of
638 this License if you rename the license and remove any references to the name of
639 the license steward (except to note that such modified license differs from
640 this License).
641
642 10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses
643 If You choose to distribute Source Code Form that is Incompatible With
644 Secondary Licenses under the terms of this version of the License, the notice
645 described in Exhibit B of this License must be attached.
646
647 Exhibit A - Source Code Form License Notice
648 This Source Code Form is subject to the terms of the Mozilla Public License, v.
649 2.0. If a copy of the MPL was not distributed with this file, You can obtain
650 one at https://mozilla.org/MPL/2.0/.
651
652 If it is not possible or desirable to put the notice in a particular file, then
653 You may include the notice in a location (such as a LICENSE file in a relevant
654 directory) where a recipient would be likely to look for such a notice.
655
656 You may add additional accurate notices of copyright ownership.
657
658 Exhibit B - “Incompatible With Secondary Licenses” Notice
659 This Source Code Form is “Incompatible With Secondary Licenses”, as defined by
660 the Mozilla Public License, v. 2.0.
661 --------------------------------------------------------------------------------
662 MIT License (BouncyCastle)
663
664 Copyright (c) 2000 - 2020 The Legion of the Bouncy Castle Inc.
665 (https://www.bouncycastle.org)
666
667 Permission is hereby granted, free of charge, to any person obtaining a copy of
668 this software and associated documentation files (the "Software"), to deal in
669 the Software without restriction, including without limitation the rights to
670 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
671 of the Software, and to permit persons to whom the Software is furnished to do
672 so, subject to the following conditions:
673
674 The above copyright notice and this permission notice shall be included in all
675 copies or substantial portions of the Software.
676
677 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
678 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
679 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
680 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
681 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
682 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
683 SOFTWARE.
[end of THIRD-PARTY-NOTICES]
[start of docker-compose.yml]
1 version: '3'
2 services:
3 submission:
4 build:
5 context: ./
6 dockerfile: ./services/submission/Dockerfile
7 depends_on:
8 - postgres
9 ports:
10 - "8080:8080"
11 environment:
12 SPRING_PROFILES_ACTIVE: cloud,dev
13 POSTGRESQL_SERVICE_PORT: '5432'
14 POSTGRESQL_SERVICE_HOST: postgres
15 POSTGRESQL_DATABASE: ${POSTGRES_DB}
16 POSTGRESQL_PASSWORD: ${POSTGRES_PASSWORD}
17 POSTGRESQL_USER: ${POSTGRES_USER}
18 networks:
19 - cwa
20 distribution:
21 build:
22 context: ./
23 dockerfile: ./services/distribution/Dockerfile
24 depends_on:
25 - postgres
26 - minio
27 environment:
28 SPRING_PROFILES_ACTIVE: cloud,dev,testdata
29 POSTGRESQL_SERVICE_PORT: '5432'
30 POSTGRESQL_SERVICE_HOST: postgres
31 POSTGRESQL_DATABASE: ${POSTGRES_DB}
32 POSTGRESQL_PASSWORD: ${POSTGRES_PASSWORD}
33 POSTGRESQL_USER: ${POSTGRES_USER}
34 # Settings for the S3 compatible MinIO object storage
35 CWA_OBJECTSTORE_ACCESSKEY: ${MINIO_ACCESS_KEY}
36 CWA_OBJECTSTORE_SECRETKEY: ${MINIO_SECRET_KEY}
37 CWA_OBJECTSTORE_ENDPOINT: http://minio
38 CWA_OBJECTSTORE_BUCKET: cwa
39 CWA_OBJECTSTORE_PORT: 9000
40 services.distribution.paths.output: /tmp/distribution
41 # Settings for cryptographic artefacts
42 VAULT_FILESIGNING_SECRET: ${SECRET_PRIVATE}
43 VAULT_FILESIGNING_CERT: ${SECRET_CERTIFICATE}
44 volumes:
45 - ./docker-compose-test-secrets:/secrets
46 networks:
47 - cwa
48 postgres:
49 image: postgres:9.6
50 restart: always
51 ports:
52 - "5432:5432"
53 environment:
54 PGDATA: /data/postgres
55 POSTGRES_DB: ${POSTGRES_DB}
56 POSTGRES_USER: ${POSTGRES_USER}
57 POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
58 volumes:
59 - postgres_volume:/data/postgres
60 networks:
61 - cwa
62 pgadmin:
63 container_name: pgadmin_container
64 image: dpage/pgadmin4
65 volumes:
66 - pgadmin_volume:/root/.pgadmin
67 ports:
68 - "8081:80"
69 restart: unless-stopped
70 networks:
71 - cwa
72 depends_on:
73 - postgres
74 environment:
75 PGADMIN_DEFAULT_EMAIL: ${PGADMIN_DEFAULT_EMAIL}
76 PGADMIN_DEFAULT_PASSWORD: ${PGADMIN_DEFAULT_PASSWORD}
77 minio:
78 image: "minio/minio"
79 volumes:
80 - minio_volume:/data
81 ports:
82 - "8082:9000"
83 environment:
84 MINIO_ACCESS_KEY: ${MINIO_ACCESS_KEY}
85 MINIO_SECRET_KEY: ${MINIO_SECRET_KEY}
86 entrypoint: sh
87 command: -c 'mkdir -p /data/cwa && minio server /data'
88 networks:
89 - cwa
90 volumes:
91 logvolume01: {}
92 minio_volume:
93 postgres_volume:
94 pgadmin_volume:
95 networks:
96 cwa:
97 driver: bridge
[end of docker-compose.yml]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/ObjectStoreAccess.java]
1 /*
2 * Corona-Warn-App
3 *
4 * SAP SE and all other contributors /
5 * copyright owners license this file to you under the Apache
6 * License, Version 2.0 (the "License"); you may not use this
7 * file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20 package app.coronawarn.server.services.distribution.objectstore;
21
22 import app.coronawarn.server.services.distribution.objectstore.publish.LocalFile;
23 import io.minio.MinioClient;
24 import io.minio.PutObjectOptions;
25 import io.minio.Result;
26 import io.minio.errors.InvalidEndpointException;
27 import io.minio.errors.InvalidPortException;
28 import io.minio.errors.MinioException;
29 import io.minio.messages.DeleteError;
30 import io.minio.messages.Item;
31 import java.io.IOException;
32 import java.security.GeneralSecurityException;
33 import java.util.ArrayList;
34 import java.util.List;
35 import java.util.Map;
36 import java.util.stream.Collectors;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39 import org.springframework.beans.factory.annotation.Autowired;
40 import org.springframework.stereotype.Component;
41
42 /**
43 * <p>Grants access to the S3 compatible object storage hosted by Telekom in Germany, enabling
44 * basic functionality for working with files.</p>
45 * <br>
46 * Make sure the following properties are available on the env:
47 * <ul>
48 * <li>cwa.objectstore.endpoint</li>
49 * <li>cwa.objectstore.bucket</li>
50 * <li>cwa.objectstore.accessKey</li>
51 * <li>cwa.objectstore.secretKey</li>
52 * <li>cwa.objectstore.port</li>
53 * </ul>
54 */
55 @Component
56 public class ObjectStoreAccess {
57
58 private static final Logger logger = LoggerFactory.getLogger(ObjectStoreAccess.class);
59
60 private static final String DEFAULT_REGION = "eu-west-1";
61
62 private final String bucket;
63
64 private MinioClient client;
65
66
67 /**
68 * Constructs an {@link ObjectStoreAccess} instance for communication with the specified object
69 * store endpoint and bucket.
70 *
71 * @param configurationProperties The config properties
72 * @throws IOException When there were problems creating the S3 client
73 * @throws GeneralSecurityException When there were problems creating the S3 client
74 * @throws MinioException When there were problems creating the S3 client
75 */
76 @Autowired
77 public ObjectStoreAccess(ObjectStoreConfigurationProperties configurationProperties)
78 throws IOException, GeneralSecurityException, MinioException {
79 this.client = createClient(configurationProperties);
80
81 this.bucket = configurationProperties.getBucket();
82
83 if (!this.client.bucketExists(this.bucket)) {
84 throw new IllegalArgumentException("Supplied bucket does not exist " + bucket);
85 }
86 }
87
88 private MinioClient createClient(ObjectStoreConfigurationProperties configurationProperties)
89 throws InvalidPortException, InvalidEndpointException {
90 if (isSsl(configurationProperties)) {
91 return new MinioClient(
92 configurationProperties.getEndpoint(),
93 configurationProperties.getPort(),
94 configurationProperties.getAccessKey(), configurationProperties.getSecretKey(),
95 DEFAULT_REGION,
96 true
97 );
98 } else {
99 return new MinioClient(
100 configurationProperties.getEndpoint(),
101 configurationProperties.getPort(),
102 configurationProperties.getAccessKey(), configurationProperties.getSecretKey()
103 );
104 }
105 }
106
107 private boolean isSsl(ObjectStoreConfigurationProperties configurationProperties) {
108 return configurationProperties.getEndpoint().startsWith("https://");
109 }
110
111 /**
112 * Stores the target file on the S3.
113 *
114 * @param localFile the file to be published
115 */
116 public void putObject(LocalFile localFile)
117 throws IOException, GeneralSecurityException, MinioException {
118 String s3Key = localFile.getS3Key();
119
120
121 var options = new PutObjectOptions(localFile.getFile().toFile().length(), -1);
122 options.setHeaders(createMetadataFor(localFile));
123
124 logger.info("... uploading " + s3Key);
125 this.client.putObject(bucket, s3Key, localFile.getFile().toString(), options);
126 }
127
128 /**
129 * Deletes objects in the object store, based on the given prefix (folder structure).
130 *
131 * @param prefix the prefix, e.g. my/folder/
132 */
133 public List<DeleteError> deleteObjectsWithPrefix(String prefix)
134 throws MinioException, GeneralSecurityException, IOException {
135 List<String> toDelete = getObjectsWithPrefix(prefix)
136 .stream()
137 .map(S3Object::getObjectName)
138 .collect(Collectors.toList());
139
140 logger.info("Deleting " + toDelete.size() + " entries with prefix " + prefix);
141 var deletionResponse = this.client.removeObjects(bucket, toDelete);
142
143 List<DeleteError> errors = new ArrayList<>();
144 for (Result<DeleteError> deleteErrorResult : deletionResponse) {
145 errors.add(deleteErrorResult.get());
146 }
147
148 logger.info("Deletion result: " + errors.size());
149
150 return errors;
151 }
152
153 /**
154 * Fetches the list of objects in the store with the given prefix.
155 *
156 * @param prefix the prefix, e.g. my/folder/
157 * @return the list of objects
158 */
159 public List<S3Object> getObjectsWithPrefix(String prefix)
160 throws IOException, GeneralSecurityException, MinioException {
161 var objects = this.client.listObjects(bucket, prefix, true, true, false);
162
163 var list = new ArrayList<S3Object>();
164 for (Result<Item> item : objects) {
165 list.add(S3Object.of(item.get()));
166 }
167
168 return list;
169 }
170
171 private Map<String, String> createMetadataFor(LocalFile file) {
172 return Map.of("cwa.hash", file.getHash());
173 }
174 }
175
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/ObjectStoreAccess.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/ObjectStoreConfigurationProperties.java]
1 /*
2 * Corona-Warn-App
3 *
4 * SAP SE and all other contributors /
5 * copyright owners license this file to you under the Apache
6 * License, Version 2.0 (the "License"); you may not use this
7 * file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20 package app.coronawarn.server.services.distribution.objectstore;
21
22 import org.springframework.boot.context.properties.ConfigurationProperties;
23
24 @ConfigurationProperties(prefix = "cwa.objectstore")
25 public class ObjectStoreConfigurationProperties {
26
27 private String accessKey;
28
29 private String secretKey;
30
31 private String endpoint;
32
33 private int port;
34
35 private String bucket;
36
37 public int getPort() {
38 return port;
39 }
40
41 public void setPort(int port) {
42 this.port = port;
43 }
44
45 public String getSecretKey() {
46 return secretKey;
47 }
48
49 public void setSecretKey(String secretKey) {
50 this.secretKey = secretKey;
51 }
52
53 public String getEndpoint() {
54 return endpoint;
55 }
56
57 public void setEndpoint(String endpoint) {
58 this.endpoint = endpoint;
59 }
60
61 public String getBucket() {
62 return bucket;
63 }
64
65 public void setBucket(String bucket) {
66 this.bucket = bucket;
67 }
68
69 public String getAccessKey() {
70 return accessKey;
71 }
72
73 public void setAccessKey(String accessKey) {
74 this.accessKey = accessKey;
75 }
76 }
77
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/ObjectStoreConfigurationProperties.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/S3Object.java]
1 /*
2 * Corona-Warn-App
3 *
4 * SAP SE and all other contributors /
5 * copyright owners license this file to you under the Apache
6 * License, Version 2.0 (the "License"); you may not use this
7 * file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20 package app.coronawarn.server.services.distribution.objectstore;
21
22 import io.minio.messages.Item;
23 import java.util.HashMap;
24 import java.util.Map;
25
26 /**
27 * Represents an object as discovered on S3.
28 */
29 public class S3Object {
30
31 /**
32 * the name of the object.
33 */
34 private final String objectName;
35
36 /**
37 * the available meta information.
38 */
39 private Map<String, String> metadata = new HashMap<>();
40
41 /**
42 * Constructs a new S3Object for the given object name.
43 *
44 * @param objectName the target object name
45 */
46 public S3Object(String objectName) {
47 this.objectName = objectName;
48 }
49
50 public String getObjectName() {
51 return objectName;
52 }
53
54 public Map<String, String> getMetadata() {
55 return metadata;
56 }
57
58 /**
59 * Returns a new instance of an S3Object based on the given item.
60 *
61 * @param item the item (as provided by MinIO)
62 * @return the S3Object representation
63 */
64 public static S3Object of(Item item) {
65 S3Object s3Object = new S3Object(item.objectName());
66
67 if (item.userMetadata() != null) {
68 s3Object.metadata = item.userMetadata();
69 }
70
71 return s3Object;
72 }
73 }
74
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/S3Object.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/publish/LocalFile.java]
1 /*
2 * Corona-Warn-App
3 *
4 * SAP SE and all other contributors /
5 * copyright owners license this file to you under the Apache
6 * License, Version 2.0 (the "License"); you may not use this
7 * file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20 package app.coronawarn.server.services.distribution.objectstore.publish;
21
22 import java.io.IOException;
23 import java.nio.file.Files;
24 import java.nio.file.Path;
25 import java.security.MessageDigest;
26 import java.security.NoSuchAlgorithmException;
27 import java.util.Base64;
28
29 /**
30 * Represents a file, which is subject for publishing to S3.
31 */
32 public abstract class LocalFile {
33
34 /** the path to the file to be represented. */
35 private final Path file;
36
37 /** the assigned S3 key. */
38 private final String s3Key;
39
40 /** the hash of this file. */
41 private final String hash;
42
43 /**
44 * Constructs a new file representing a file on the disk.
45 *
46 * @param file the path to the file to be represented
47 * @param basePath the base path
48 */
49 public LocalFile(Path file, Path basePath) {
50 this.file = file;
51 this.hash = hash();
52 this.s3Key = createS3Key(file, basePath);
53 }
54
55 public String getS3Key() {
56 return s3Key;
57 }
58
59 public String getHash() {
60 return hash;
61 }
62
63 public Path getFile() {
64 return file;
65 }
66
67 private String hash() {
68 try {
69 MessageDigest digester = MessageDigest.getInstance("SHA-256");
70 digester.update(Files.readAllBytes(file));
71
72 return Base64.getEncoder().encodeToString(digester.digest());
73 } catch (IOException | NoSuchAlgorithmException e) {
74 throw new RuntimeException("Unable to compute hashes due to ", e);
75 }
76 }
77
78 protected String createS3Key(Path file, Path rootFolder) {
79 Path relativePath = rootFolder.relativize(file);
80 return relativePath.toString().replaceAll("\\\\", "/");
81 }
82 }
83
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/publish/LocalFile.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/publish/LocalIndexFile.java]
1 /*
2 * Corona-Warn-App
3 *
4 * SAP SE and all other contributors /
5 * copyright owners license this file to you under the Apache
6 * License, Version 2.0 (the "License"); you may not use this
7 * file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20 package app.coronawarn.server.services.distribution.objectstore.publish;
21
22 import java.nio.file.Path;
23
24 /**
25 * Represents a file of a specific category: Index files.
26 * <br>
27 * Index files contain information about the available packages on the S3, which makes discovery of
28 * those files easier for the consumers. Index files are assembled with the name "index", but should
29 * be published on S3 w/o the index part, to makee.g.:
30 * <br>
31 * /diagnosis-keys/date/2020-12-12/index -> /diagnosis-keys/date/2020-12-12
32 */
33 public class LocalIndexFile extends LocalFile {
34
35 /**
36 * the suffix for index files.
37 */
38 private static final String INDEX_FILE_SUFFIX = "/index";
39
40 /**
41 * Constructs a new file, which is treated as an index file.
42 *
43 * @param file the file on the disk
44 * @param basePath the base path, from where the file was loaded. This will be used in order to
45 * determine the S3 key
46 */
47 public LocalIndexFile(Path file, Path basePath) {
48 super(file, basePath);
49 }
50
51 @Override
52 protected String createS3Key(Path file, Path rootFolder) {
53 String s3Key = super.createS3Key(file, rootFolder);
54
55 // Deactivate index mapping for now
56 // return s3Key.substring(0, s3Key.length() - INDEX_FILE_SUFFIX.length());
57 return s3Key;
58 }
59 }
60
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/publish/LocalIndexFile.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/publish/PublishedFileSet.java]
1 /*
2 * Corona-Warn-App
3 *
4 * SAP SE and all other contributors /
5 * copyright owners license this file to you under the Apache
6 * License, Version 2.0 (the "License"); you may not use this
7 * file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20 package app.coronawarn.server.services.distribution.objectstore.publish;
21
22 import app.coronawarn.server.services.distribution.objectstore.S3Object;
23 import java.util.List;
24 import java.util.Map;
25 import java.util.stream.Collectors;
26
27 /**
28 * Provides an overview about which files are currently available on S3.
29 */
30 public class PublishedFileSet {
31
32 /** ta map of S3 objects with the S3 object name as the key component of the map. */
33 private Map<String, S3Object> s3Objects;
34
35 /**
36 * Creates a new PublishedFileSet for the given S3 objects with the help of the metadata provider.
37 * The metadata provider helps to determine whether files have been changed, and are requiring
38 * re-upload.
39 *
40 * @param s3Objects the list of s3 objects.
41 */
42 public PublishedFileSet(List<S3Object> s3Objects) {
43 this.s3Objects = s3Objects.stream()
44 .collect(Collectors.toMap(S3Object::getObjectName, s3object -> s3object));
45 }
46
47 /**
48 * Checks whether the given file, which is subject for publishing, is already available on the S3.
49 * Will return true, when:
50 * <ul>
51 * <li>The S3 object key exists on S3</li>
52 * <li>The checksum of the existing S3 object matches the hash of the given file</li>
53 * </ul>
54 *
55 * @param file the to-be-published file which should be checked
56 * @return true, if it exists & is identical
57 */
58 public boolean isNotYetPublished(LocalFile file) {
59 S3Object published = s3Objects.get(file.getS3Key());
60
61 if (published == null) {
62 return true;
63 }
64
65 return !hasSameHashAsPublishedFile(file);
66 }
67
68 private boolean hasSameHashAsPublishedFile(LocalFile file) {
69 var metaData = s3Objects.get(file.getS3Key()).getMetadata();
70
71 String s3FileHash = metaData.get("X-Amz-Meta-Cwa.hash");
72
73 return file.getHash().equals(s3FileHash);
74 }
75
76 }
77
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/publish/PublishedFileSet.java]
[start of services/distribution/src/main/resources/application-cloud.properties]
1 spring.flyway.enabled=true
2 spring.flyway.locations=classpath:db/migration/postgres
3
4 spring.datasource.driver-class-name=org.postgresql.Driver
5 spring.datasource.url=jdbc:postgresql://${POSTGRESQL_SERVICE_HOST}:${POSTGRESQL_SERVICE_PORT}/${POSTGRESQL_DATABASE}
6 spring.datasource.username=${POSTGRESQL_USER}
7 spring.datasource.password=${POSTGRESQL_PASSWORD}
8
9 services.distribution.paths.output=/tmp/distribution
10
11 cwa.objectstore.accessKey=${CWA_OBJECTSTORE_ACCESSKEY}
12 cwa.objectstore.secretKey=${CWA_OBJECTSTORE_SECRETKEY}
13 cwa.objectstore.endpoint=${CWA_OBJECTSTORE_ENDPOINT}
14 cwa.objectstore.bucket=${CWA_OBJECTSTORE_BUCKET}
15 cwa.objectstore.port=${CWA_OBJECTSTORE_PORT}
16
[end of services/distribution/src/main/resources/application-cloud.properties]
[start of services/distribution/src/main/resources/application.properties]
1 logging.level.org.springframework.web=INFO
2 logging.level.app.coronawarn=INFO
3 spring.main.web-application-type=NONE
4
5 services.distribution.retention-days=14
6 services.distribution.paths.output=out
7 services.distribution.paths.privatekey=${VAULT_FILESIGNING_SECRET}
8 services.distribution.paths.certificate=${VAULT_FILESIGNING_CERT}
9
10 # Configuration for the S3 compatible object storage hosted by Telekom in Germany
11 cwa.objectstore.accessKey=${CWA_OBJECTSTORE_ACCESSKEY:minioadmin}
12 cwa.objectstore.secretKey=${CWA_OBJECTSTORE_SECRETKEY:minioadmin}
13 cwa.objectstore.endpoint=${CWA_OBJECTSTORE_ENDPOINT:http\://localhost\:9000}
14 cwa.objectstore.bucket=${CWA_OBJECTSTORE_BUCKET:cwa}
15 cwa.objectstore.port=${CWA_OBJECTSTORE_PORT:9000}
16
17 # Postgres configuration
18 spring.jpa.hibernate.ddl-auto=validate
19
20 spring.flyway.enabled=true
21 spring.flyway.locations=classpath:db/migration/postgres
22
23 spring.datasource.driver-class-name=org.postgresql.Driver
24 spring.datasource.url=jdbc:postgresql://${POSTGRESQL_SERVICE_HOST:localhost}:${POSTGRESQL_SERVICE_PORT:5432}/${POSTGRESQL_DATABASE:cwa}
25 spring.datasource.username=${POSTGRESQL_USER:postgres}
26 spring.datasource.password=${POSTGRESQL_PASSWORD:postgres}
27
[end of services/distribution/src/main/resources/application.properties]
</code>
Here is an example of a patch file. It consists of changes to the code base. It specifies the file names, the line numbers of each change, and the removed and added lines. A single patch file can contain changes to multiple files.
<patch>
--- a/file.py
+++ b/file.py
@@ -1,27 +1,35 @@
def euclidean(a, b):
- while b:
- a, b = b, a % b
- return a
+ if b == 0:
+ return a
+ return euclidean(b, a % b)
def bresenham(x0, y0, x1, y1):
points = []
dx = abs(x1 - x0)
dy = abs(y1 - y0)
- sx = 1 if x0 < x1 else -1
- sy = 1 if y0 < y1 else -1
- err = dx - dy
+ x, y = x0, y0
+ sx = -1 if x0 > x1 else 1
+ sy = -1 if y0 > y1 else 1
- while True:
- points.append((x0, y0))
- if x0 == x1 and y0 == y1:
- break
- e2 = 2 * err
- if e2 > -dy:
+ if dx > dy:
+ err = dx / 2.0
+ while x != x1:
+ points.append((x, y))
err -= dy
- x0 += sx
- if e2 < dx:
- err += dx
- y0 += sy
+ if err < 0:
+ y += sy
+ err += dx
+ x += sx
+ else:
+ err = dy / 2.0
+ while y != y1:
+ points.append((x, y))
+ err -= dx
+ if err < 0:
+ x += sx
+ err += dy
+ y += sy
+ points.append((x, y))
return points
</patch>
I need you to solve the provded issue by generating a single patch file that I can apply directly to this repository using git apply. Please respond with a single patch file in the format shown above.
Respond below:
| corona-warn-app/cwa-server | 9a5ae8bbf8872b63578dcca32b3258c012a63866 | Open MinIO read access
## Current Implementation
Receiving files from local MinIO requires access key and secret key.
## Suggested Enhancement
Add a security policy to the MinIO configuration to only protect write access, but have open read access.
## Expected Benefits
Mobile colleagues can use local setup for end-to-end testing.
| 2020-05-21T13:53:01 | <patch>
diff --git a/.env b/.env
--- a/.env
+++ b/.env
@@ -10,9 +10,9 @@ POSTGRES_PASSWORD=postgres
[email protected]
PGADMIN_DEFAULT_PASSWORD=password
-# Docker Compose MinIO settings
-MINIO_ACCESS_KEY=minioadmin
-MINIO_SECRET_KEY=minioadmin
+# Docker Compose objectstore settings
+OBJECTSTORE_ACCESSKEY=accessKey1
+OBJECTSTORE_SECRETKEY=verySecretKey1
# Docker Compose Secrets settings
SECRET_PRIVATE=file:/secrets/private.pem
diff --git a/README.md b/README.md
--- a/README.md
+++ b/README.md
@@ -48,7 +48,7 @@ If you want to use Docker-based deployment, you need to install Docker on your l
#### Running the Full CWA Backend Using Docker Compose
-For your convenience, a full setup including the generation of test data has been prepared using [Docker Compose](https://docs.docker.com/compose/reference/overview/). To build the backend services, run ```docker-compose build``` in the repository's root directory. A default configuration file can be found under ```.env```in the root folder of the repository. The default values for the local Postgres and MinIO-build should be changed in this file before docker-compose is run.
+For your convenience, a full setup including the generation of test data has been prepared using [Docker Compose](https://docs.docker.com/compose/reference/overview/). To build the backend services, run ```docker-compose build``` in the repository's root directory. A default configuration file can be found under ```.env```in the root folder of the repository. The default values for the local Postgres and Zenko Cloudserver should be changed in this file before docker-compose is run.
Once the services are built, you can start the whole backend using ```docker-compose up```.
The distribution service runs once and then finishes. If you want to trigger additional distribution runs, run ```docker-compose start distribution```.
@@ -57,11 +57,11 @@ The docker-compose contains the following services:
Service | Description | Endpoint and Default Credentials
--------------|-------------|-----------
-submission | The Corona-Warn-App submission service | http://localhost:8080
-distribution | The Corona-Warn-App distribution service | NO ENDPOINT
-postgres | A [postgres] database installation | postgres:5432 <br> Username: postgres <br> Password: postgres
-pgadmin | A [pgadmin](https://www.pgadmin.org/) installation for the postgres database | http://localhost:8081 <br> Username: [email protected] <br> Password: password
-minio | [MinIO] is an S3-compliant object store | http://localhost:8082/ <br> Access key: minioadmin <br> Secret key: minioadmin
+submission | The Corona-Warn-App submission service | http://localhost:8000
+distribution | The Corona-Warn-App distribution service | NO ENDPOINT
+postgres | A [postgres] database installation | postgres:8001 <br> Username: postgres <br> Password: postgres
+pgadmin | A [pgadmin](https://www.pgadmin.org/) installation for the postgres database | http://localhost:8002 <br> Username: [email protected] <br> Password: password
+cloudserver | [Zenko CloudServer] is a S3-compliant object store | http://localhost:8003/ <br> Access key: accessKey1 <br> Secret key: verySecretKey1
#### Running Single CWA Services Using Docker
@@ -89,7 +89,7 @@ To prepare your machine to run the CWA project locally, we recommend that you fi
* Minimum JDK Version 11: [OpenJDK](https://openjdk.java.net/) / [SapMachine](https://sap.github.io/SapMachine/)
* [Maven 3.6](https://maven.apache.org/)
* [Postgres]
-* [MinIO]
+* [Zenko CloudServer]
#### Configure
@@ -167,8 +167,8 @@ The following public repositories are currently available for the Corona-Warn-Ap
[cwa-documentation]: https://github.com/corona-warn-app/cwa-documentation
[cwa-server]: https://github.com/corona-warn-app/cwa-server
[Postgres]: https://www.postgresql.org/
-[MinIO]: https://min.io/
[HSQLDB]: http://hsqldb.org/
+[Zenko CloudServer]: https://github.com/scality/cloudserver
## Licensing
diff --git a/THIRD-PARTY-NOTICES b/THIRD-PARTY-NOTICES
--- a/THIRD-PARTY-NOTICES
+++ b/THIRD-PARTY-NOTICES
@@ -74,9 +74,15 @@ Component: Spring Boot
Licensor: VMWare Inc.
Website: https://spring.io/
License: Apache License 2.0
+
+Component: Zenko CloudServer
+Licensor: Zenko
+Website: https://github.com/scality/cloudserver
+License: Apache License 2.0
+
--------------------------------------------------------------------------------
Apache License 2.0 (Commons IO, Commons Math 3, flyway, JSON-Simple,
-Maven, MinIO Object Storage, snakeyaml, Spring Boot)
+Maven, MinIO Object Storage, snakeyaml, Spring Boot, Zenko CloudServer)
Apache License
Version 2.0, January 2004
diff --git a/create-bucket.sh b/create-bucket.sh
new file mode 100755
--- /dev/null
+++ b/create-bucket.sh
@@ -0,0 +1,6 @@
+# Prerequisite - install aws cli
+
+export AWS_ACCESS_KEY_ID=accessKey1
+export AWS_SECRET_ACCESS_KEY=verySecretKey1
+
+aws s3api create-bucket --bucket cwa --endpoint-url http://localhost:8000 --acl public-read
diff --git a/docker-compose.yml b/docker-compose.yml
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -7,49 +7,46 @@ services:
depends_on:
- postgres
ports:
- - "8080:8080"
+ - "8000:8080"
environment:
- SPRING_PROFILES_ACTIVE: cloud,dev
+ SPRING_PROFILES_ACTIVE: dev
POSTGRESQL_SERVICE_PORT: '5432'
POSTGRESQL_SERVICE_HOST: postgres
POSTGRESQL_DATABASE: ${POSTGRES_DB}
POSTGRESQL_PASSWORD: ${POSTGRES_PASSWORD}
POSTGRESQL_USER: ${POSTGRES_USER}
- networks:
- - cwa
distribution:
build:
context: ./
dockerfile: ./services/distribution/Dockerfile
depends_on:
- postgres
- - minio
+ - objectstore
+ - create-bucket
environment:
- SPRING_PROFILES_ACTIVE: cloud,dev,testdata
+ SPRING_PROFILES_ACTIVE: dev,testdata
POSTGRESQL_SERVICE_PORT: '5432'
POSTGRESQL_SERVICE_HOST: postgres
POSTGRESQL_DATABASE: ${POSTGRES_DB}
POSTGRESQL_PASSWORD: ${POSTGRES_PASSWORD}
POSTGRESQL_USER: ${POSTGRES_USER}
- # Settings for the S3 compatible MinIO object storage
- CWA_OBJECTSTORE_ACCESSKEY: ${MINIO_ACCESS_KEY}
- CWA_OBJECTSTORE_SECRETKEY: ${MINIO_SECRET_KEY}
- CWA_OBJECTSTORE_ENDPOINT: http://minio
+ # Settings for the S3 compatible objectstore
+ CWA_OBJECTSTORE_ACCESSKEY: ${OBJECTSTORE_ACCESSKEY}
+ CWA_OBJECTSTORE_SECRETKEY: ${OBJECTSTORE_SECRETKEY}
+ CWA_OBJECTSTORE_ENDPOINT: http://objectstore
CWA_OBJECTSTORE_BUCKET: cwa
- CWA_OBJECTSTORE_PORT: 9000
+ CWA_OBJECTSTORE_PORT: 8000
services.distribution.paths.output: /tmp/distribution
# Settings for cryptographic artefacts
VAULT_FILESIGNING_SECRET: ${SECRET_PRIVATE}
VAULT_FILESIGNING_CERT: ${SECRET_CERTIFICATE}
volumes:
- ./docker-compose-test-secrets:/secrets
- networks:
- - cwa
postgres:
image: postgres:9.6
restart: always
ports:
- - "5432:5432"
+ - "8001:5432"
environment:
PGDATA: /data/postgres
POSTGRES_DB: ${POSTGRES_DB}
@@ -57,41 +54,39 @@ services:
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
volumes:
- postgres_volume:/data/postgres
- networks:
- - cwa
pgadmin:
container_name: pgadmin_container
image: dpage/pgadmin4
volumes:
- pgadmin_volume:/root/.pgadmin
ports:
- - "8081:80"
+ - "8002:80"
restart: unless-stopped
- networks:
- - cwa
depends_on:
- postgres
environment:
PGADMIN_DEFAULT_EMAIL: ${PGADMIN_DEFAULT_EMAIL}
PGADMIN_DEFAULT_PASSWORD: ${PGADMIN_DEFAULT_PASSWORD}
- minio:
- image: "minio/minio"
+ objectstore:
+ image: "zenko/cloudserver"
volumes:
- - minio_volume:/data
+ - objectstore_volume:/data
ports:
- - "8082:9000"
+ - "8003:8000"
environment:
- MINIO_ACCESS_KEY: ${MINIO_ACCESS_KEY}
- MINIO_SECRET_KEY: ${MINIO_SECRET_KEY}
- entrypoint: sh
- command: -c 'mkdir -p /data/cwa && minio server /data'
- networks:
- - cwa
+ ENDPOINT: objectstore
+ REMOTE_MANAGEMENT_DISABLE: 1
+ SCALITY_ACCESS_KEY_ID: ${OBJECTSTORE_ACCESSKEY}
+ SCALITY_SECRET_ACCESS_KEY: ${OBJECTSTORE_SECRETKEY}
+ create-bucket:
+ image: amazon/aws-cli
+ environment:
+ - AWS_ACCESS_KEY_ID=${OBJECTSTORE_ACCESSKEY}
+ - AWS_SECRET_ACCESS_KEY=${OBJECTSTORE_SECRETKEY}
+ command: s3api create-bucket --bucket cwa --endpoint-url http://objectstore:8000 --acl public-read
+ depends_on:
+ - objectstore
volumes:
- logvolume01: {}
- minio_volume:
postgres_volume:
pgadmin_volume:
-networks:
- cwa:
- driver: bridge
\ No newline at end of file
+ objectstore_volume:
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/ObjectStoreAccess.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/ObjectStoreAccess.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/ObjectStoreAccess.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/ObjectStoreAccess.java
@@ -59,10 +59,11 @@ public class ObjectStoreAccess {
private static final String DEFAULT_REGION = "eu-west-1";
- private final String bucket;
+ private final boolean isSetPublicReadAclOnPutObject;
- private MinioClient client;
+ private final String bucket;
+ private final MinioClient client;
/**
* Constructs an {@link ObjectStoreAccess} instance for communication with the specified object
@@ -79,6 +80,7 @@ public ObjectStoreAccess(ObjectStoreConfigurationProperties configurationPropert
this.client = createClient(configurationProperties);
this.bucket = configurationProperties.getBucket();
+ this.isSetPublicReadAclOnPutObject = configurationProperties.isSetPublicReadAclOnPutObject();
if (!this.client.bucketExists(this.bucket)) {
throw new IllegalArgumentException("Supplied bucket does not exist " + bucket);
@@ -116,10 +118,7 @@ private boolean isSsl(ObjectStoreConfigurationProperties configurationProperties
public void putObject(LocalFile localFile)
throws IOException, GeneralSecurityException, MinioException {
String s3Key = localFile.getS3Key();
-
-
- var options = new PutObjectOptions(localFile.getFile().toFile().length(), -1);
- options.setHeaders(createMetadataFor(localFile));
+ PutObjectOptions options = createOptionsFor(localFile);
logger.info("... uploading " + s3Key);
this.client.putObject(bucket, s3Key, localFile.getFile().toString(), options);
@@ -158,7 +157,7 @@ public List<DeleteError> deleteObjectsWithPrefix(String prefix)
*/
public List<S3Object> getObjectsWithPrefix(String prefix)
throws IOException, GeneralSecurityException, MinioException {
- var objects = this.client.listObjects(bucket, prefix, true, true, false);
+ var objects = this.client.listObjects(bucket, prefix, true);
var list = new ArrayList<S3Object>();
for (Result<Item> item : objects) {
@@ -168,7 +167,14 @@ public List<S3Object> getObjectsWithPrefix(String prefix)
return list;
}
- private Map<String, String> createMetadataFor(LocalFile file) {
- return Map.of("cwa.hash", file.getHash());
+ private PutObjectOptions createOptionsFor(LocalFile file) {
+ var options = new PutObjectOptions(file.getFile().toFile().length(), -1);
+
+ if (this.isSetPublicReadAclOnPutObject) {
+ options.setHeaders(Map.of("x-amz-acl", "public-read"));
+ }
+
+ return options;
}
+
}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/ObjectStoreConfigurationProperties.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/ObjectStoreConfigurationProperties.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/ObjectStoreConfigurationProperties.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/ObjectStoreConfigurationProperties.java
@@ -34,6 +34,16 @@ public class ObjectStoreConfigurationProperties {
private String bucket;
+ private boolean setPublicReadAclOnPutObject;
+
+ public boolean isSetPublicReadAclOnPutObject() {
+ return setPublicReadAclOnPutObject;
+ }
+
+ public void setSetPublicReadAclOnPutObject(boolean setPublicReadAclOnPutObject) {
+ this.setPublicReadAclOnPutObject = setPublicReadAclOnPutObject;
+ }
+
public int getPort() {
return port;
}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/S3Object.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/S3Object.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/S3Object.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/S3Object.java
@@ -38,6 +38,9 @@ public class S3Object {
*/
private Map<String, String> metadata = new HashMap<>();
+ /** The e-Tag of this S3 Object. */
+ private String etag;
+
/**
* Constructs a new S3Object for the given object name.
*
@@ -55,6 +58,10 @@ public Map<String, String> getMetadata() {
return metadata;
}
+ public String getEtag() {
+ return etag;
+ }
+
/**
* Returns a new instance of an S3Object based on the given item.
*
@@ -68,6 +75,8 @@ public static S3Object of(Item item) {
s3Object.metadata = item.userMetadata();
}
+ s3Object.etag = item.etag().replaceAll("\"","");
+
return s3Object;
}
}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/publish/LocalFile.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/publish/LocalFile.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/publish/LocalFile.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/publish/LocalFile.java
@@ -19,26 +19,35 @@
package app.coronawarn.server.services.distribution.objectstore.publish;
+import com.google.common.io.BaseEncoding;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
-import java.util.Base64;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.util.DigestUtils;
/**
* Represents a file, which is subject for publishing to S3.
*/
public abstract class LocalFile {
- /** the path to the file to be represented. */
+ private static final Logger logger = LoggerFactory.getLogger(LocalFile.class);
+
+ /**
+ * the path to the file to be represented.
+ */
private final Path file;
- /** the assigned S3 key. */
+ /**
+ * the assigned S3 key.
+ */
private final String s3Key;
- /** the hash of this file. */
- private final String hash;
+ /**
+ * the etag of this file.
+ */
+ private final String etag;
/**
* Constructs a new file representing a file on the disk.
@@ -48,7 +57,7 @@ public abstract class LocalFile {
*/
public LocalFile(Path file, Path basePath) {
this.file = file;
- this.hash = hash();
+ this.etag = computeS3ETag();
this.s3Key = createS3Key(file, basePath);
}
@@ -56,23 +65,25 @@ public String getS3Key() {
return s3Key;
}
- public String getHash() {
- return hash;
+ public String getEtag() {
+ return etag;
}
public Path getFile() {
return file;
}
- private String hash() {
+ private String computeS3ETag() {
try {
- MessageDigest digester = MessageDigest.getInstance("SHA-256");
- digester.update(Files.readAllBytes(file));
+ String md5 = DigestUtils.md5DigestAsHex(Files.readAllBytes(file));
+ byte[] raw = BaseEncoding.base16().decode(md5.toUpperCase());
- return Base64.getEncoder().encodeToString(digester.digest());
- } catch (IOException | NoSuchAlgorithmException e) {
- throw new RuntimeException("Unable to compute hashes due to ", e);
+ return DigestUtils.md5DigestAsHex(raw) + "-1";
+ } catch (IOException e) {
+ logger.warn("Unable to compute E-Tag", e);
}
+
+ return "";
}
protected String createS3Key(Path file, Path rootFolder) {
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/publish/LocalIndexFile.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/publish/LocalIndexFile.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/publish/LocalIndexFile.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/publish/LocalIndexFile.java
@@ -51,9 +51,7 @@ public LocalIndexFile(Path file, Path basePath) {
@Override
protected String createS3Key(Path file, Path rootFolder) {
String s3Key = super.createS3Key(file, rootFolder);
-
- // Deactivate index mapping for now
- // return s3Key.substring(0, s3Key.length() - INDEX_FILE_SUFFIX.length());
- return s3Key;
+
+ return s3Key.substring(0, s3Key.length() - INDEX_FILE_SUFFIX.length());
}
}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/publish/PublishedFileSet.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/publish/PublishedFileSet.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/publish/PublishedFileSet.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/publish/PublishedFileSet.java
@@ -62,15 +62,7 @@ public boolean isNotYetPublished(LocalFile file) {
return true;
}
- return !hasSameHashAsPublishedFile(file);
- }
-
- private boolean hasSameHashAsPublishedFile(LocalFile file) {
- var metaData = s3Objects.get(file.getS3Key()).getMetadata();
-
- String s3FileHash = metaData.get("X-Amz-Meta-Cwa.hash");
-
- return file.getHash().equals(s3FileHash);
+ return !file.getEtag().equals(published.getEtag());
}
}
diff --git a/services/distribution/src/main/java/io/minio/messages/Item.java b/services/distribution/src/main/java/io/minio/messages/Item.java
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/main/java/io/minio/messages/Item.java
@@ -0,0 +1,132 @@
+/*
+ * MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2015 MinIO, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://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 for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package io.minio.messages;
+
+import java.time.ZonedDateTime;
+import java.util.Map;
+import org.simpleframework.xml.Element;
+import org.simpleframework.xml.Root;
+
+/* ----------------------------------------------------------------
+ * Copied from MinIO due to patch not yet available.
+ * https://github.com/minio/minio-java/pull/921
+ * Waiting for new release version: 7.0.3
+ * ----------------------------------------------------------------
+ */
+
+/**
+ * Helper class to denote Object information in {@link ListBucketResult} and {@link
+ * ListBucketResultV1}.
+ */
+@Root(name = "Contents", strict = false)
+public class Item {
+
+ @Element(name = "Key")
+ private String objectName;
+
+ @Element(name = "LastModified")
+ private ResponseDate lastModified;
+
+ @Element(name = "ETag")
+ private String etag;
+
+ @Element(name = "Size")
+ private long size;
+
+ @Element(name = "StorageClass")
+ private String storageClass;
+
+ @Element(name = "Owner", required = false) /* Monkeypatch: Owner should be optional */
+ private Owner owner;
+
+ @Element(name = "UserMetadata", required = false)
+ private Metadata userMetadata;
+
+ private boolean isDir = false;
+
+ public Item() {
+
+ }
+
+ /**
+ * Constructs a new Item for prefix i.e. directory.
+ */
+ public Item(String prefix) {
+ this.objectName = prefix;
+ this.isDir = true;
+ }
+
+ /**
+ * Returns object name.
+ */
+ public String objectName() {
+ return objectName;
+ }
+
+ /**
+ * Returns last modified time of the object.
+ */
+ public ZonedDateTime lastModified() {
+ return lastModified.zonedDateTime();
+ }
+
+ /**
+ * Returns ETag of the object.
+ */
+ public String etag() {
+ return etag;
+ }
+
+ /**
+ * Returns object size.
+ */
+ public long size() {
+ return size;
+ }
+
+ /**
+ * Returns storage class of the object.
+ */
+ public String storageClass() {
+ return storageClass;
+ }
+
+ /**
+ * Returns owner object of given the object.
+ */
+ public Owner owner() {
+ return owner;
+ }
+
+ /**
+ * Returns user metadata. This is MinIO specific extension to ListObjectsV2.
+ */
+ public Map<String, String> userMetadata() {
+ if (userMetadata == null) {
+ return null;
+ }
+
+ return userMetadata.get();
+ }
+
+ /**
+ * Returns whether the object is a directory or not.
+ */
+ public boolean isDir() {
+ return isDir;
+ }
+}
diff --git a/services/distribution/src/main/resources/application-cloud.properties b/services/distribution/src/main/resources/application-cloud.properties
--- a/services/distribution/src/main/resources/application-cloud.properties
+++ b/services/distribution/src/main/resources/application-cloud.properties
@@ -13,3 +13,4 @@ cwa.objectstore.secretKey=${CWA_OBJECTSTORE_SECRETKEY}
cwa.objectstore.endpoint=${CWA_OBJECTSTORE_ENDPOINT}
cwa.objectstore.bucket=${CWA_OBJECTSTORE_BUCKET}
cwa.objectstore.port=${CWA_OBJECTSTORE_PORT}
+cwa.objectstore.set-public-read-acl-on-put-object=false
diff --git a/services/distribution/src/main/resources/application.properties b/services/distribution/src/main/resources/application.properties
--- a/services/distribution/src/main/resources/application.properties
+++ b/services/distribution/src/main/resources/application.properties
@@ -8,11 +8,12 @@ services.distribution.paths.privatekey=${VAULT_FILESIGNING_SECRET}
services.distribution.paths.certificate=${VAULT_FILESIGNING_CERT}
# Configuration for the S3 compatible object storage hosted by Telekom in Germany
-cwa.objectstore.accessKey=${CWA_OBJECTSTORE_ACCESSKEY:minioadmin}
-cwa.objectstore.secretKey=${CWA_OBJECTSTORE_SECRETKEY:minioadmin}
-cwa.objectstore.endpoint=${CWA_OBJECTSTORE_ENDPOINT:http\://localhost\:9000}
+cwa.objectstore.access-key=${CWA_OBJECTSTORE_ACCESSKEY:accessKey1}
+cwa.objectstore.secret-key=${CWA_OBJECTSTORE_SECRETKEY:verySecretKey1}
+cwa.objectstore.endpoint=${CWA_OBJECTSTORE_ENDPOINT:http\://localhost\:8003}
cwa.objectstore.bucket=${CWA_OBJECTSTORE_BUCKET:cwa}
-cwa.objectstore.port=${CWA_OBJECTSTORE_PORT:9000}
+cwa.objectstore.port=${CWA_OBJECTSTORE_PORT:8003}
+cwa.objectstore.set-public-read-acl-on-put-object=true
# Postgres configuration
spring.jpa.hibernate.ddl-auto=validate
</patch> | diff --git a/services/distribution/src/test/resources/application.properties b/services/distribution/src/test/resources/application.properties
--- a/services/distribution/src/test/resources/application.properties
+++ b/services/distribution/src/test/resources/application.properties
@@ -14,9 +14,9 @@ spring.flyway.locations=classpath:db/migration/h2
spring.jpa.hibernate.ddl-auto=validate
# S3 object store configuration
-cwa.objectstore.accessKey=${CWA_OBJECTSTORE_ACCESSKEY:minioadmin}
-cwa.objectstore.secretKey=${CWA_OBJECTSTORE_SECRETKEY:minioadmin}
-cwa.objectstore.endpoint=${CWA_OBJECTSTORE_ENDPOINT:http\://localhost\:9000}
+cwa.objectstore.access-key=${CWA_OBJECTSTORE_ACCESSKEY:accessKey1}
+cwa.objectstore.secret-key=${CWA_OBJECTSTORE_SECRETKEY:verySecretKey1}
+cwa.objectstore.endpoint=${CWA_OBJECTSTORE_ENDPOINT:http\://localhost\:8003}
cwa.objectstore.bucket=${CWA_OBJECTSTORE_BUCKET:cwa}
-cwa.objectstore.port=${CWA_OBJECTSTORE_PORT:9000}
-
+cwa.objectstore.port=${CWA_OBJECTSTORE_PORT:8003}
+cwa.objectstore.set-public-read-acl-on-put-object=true
diff --git a/services/distribution/src/test/resources/objectstore/publisher/version/v1/indexfile b/services/distribution/src/test/resources/objectstore/publisher/version/v1/index
similarity index 100%
rename from services/distribution/src/test/resources/objectstore/publisher/version/v1/indexfile
rename to services/distribution/src/test/resources/objectstore/publisher/version/v1/index
| |||||
corona-warn-app__cwa-server-783 | You will be provided with a partial code base and an issue statement explaining a problem to resolve.
<issue>
Improve logging of the submission validation process
<!--
Thanks for proposing an enhancement 🙌 ❤️
Before opening a new issue, please make sure that we do not have any duplicates already open. You can ensure this by searching the issue list for this repository. If there is a duplicate, please close your issue and add a comment to the existing issue instead.
-->
The enhancement suggested by @Tho-Mat, and based on the discussion in https://github.com/corona-warn-app/cwa-server/issues/723
## Current Implementation
Issue https://github.com/corona-warn-app/cwa-server/issues/723, demonstrated that currently implemented logging is not sufficient for effective troubleshooting of the submission validation process.
## Suggested Enhancement
If the kay can not be saved in a DB (e.g. because it is already in database / Date to high / Date to low / unknown), we log this fact, date of the issue and the reason in the application logs.
## Expected Benefits
This would have the great advantage of better analyzing certain constellations that can lead to errors.
</issue>
<code>
[start of README.md]
1 <!-- markdownlint-disable MD041 -->
2 <h1 align="center">
3 Corona-Warn-App Server
4 </h1>
5
6 <p align="center">
7 <a href="https://github.com/corona-warn-app/cwa-server/commits/" title="Last Commit"><img src="https://img.shields.io/github/last-commit/corona-warn-app/cwa-server?style=flat"></a>
8 <a href="https://github.com/corona-warn-app/cwa-server/issues" title="Open Issues"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat"></a>
9 <a href="https://circleci.com/gh/corona-warn-app/cwa-server" title="Build Status"><img src="https://circleci.com/gh/corona-warn-app/cwa-server.svg?style=shield&circle-token=4ab059989d10709df19eb4b98ab7c121a25e981a"></a>
10 <a href="https://sonarcloud.io/dashboard?id=corona-warn-app_cwa-server" title="Quality Gate"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=alert_status"></a>
11 <a href="https://sonarcloud.io/component_measures?id=corona-warn-app_cwa-server&metric=Coverage&view=list" title="Coverage"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=coverage"></a>
12 <a href="https://github.com/corona-warn-app/cwa-server/blob/master/LICENSE" title="License"><img src="https://img.shields.io/badge/License-Apache%202.0-green.svg?style=flat"></a>
13 </p>
14
15 <p align="center">
16 <a href="#development">Development</a> •
17 <a href="#service-apis">Service APIs</a> •
18 <a href="#documentation">Documentation</a> •
19 <a href="#support-and-feedback">Support</a> •
20 <a href="#how-to-contribute">Contribute</a> •
21 <a href="#contributors">Contributors</a> •
22 <a href="#repositories">Repositories</a> •
23 <a href="#licensing">Licensing</a>
24 </p>
25
26 The goal of this project is to develop the official Corona-Warn-App for Germany based on the exposure notification API from [Apple](https://www.apple.com/covid19/contacttracing/) and [Google](https://www.google.com/covid19/exposurenotifications/). The apps (for both iOS and Android) use Bluetooth technology to exchange anonymous encrypted data with other mobile phones (on which the app is also installed) in the vicinity of an app user's phone. The data is stored locally on each user's device, preventing authorities or other parties from accessing or controlling the data. This repository contains the **implementation of the server for encryption keys** for the Corona-Warn-App.
27
28 In this documentation, Corona-Warn-App services are also referred to as CWA services.
29
30 ## Architecture Overview
31
32 You can find the architecture overview [here](/docs/ARCHITECTURE.md), which will give you
33 a good starting point in how the backend services interact with other services, and what purpose
34 they serve.
35
36 ## Development
37
38 After you've checked out this repository, you can run the application in one of the following ways:
39
40 * As a [Docker](https://www.docker.com/)-based deployment on your local machine. You can run either:
41 * Single components using the respective Dockerfile or
42 * The full backend using the Docker Compose (which is considered the most convenient way)
43 * As a [Maven](https://maven.apache.org)-based build on your local machine.
44 If you want to develop something in a single component, this approach is preferable.
45
46 ### Docker-Based Deployment
47
48 If you want to use Docker-based deployment, you need to install Docker on your local machine. For more information about downloading and installing Docker, see the [official Docker documentation](https://docs.docker.com/get-docker/).
49
50 #### Running the Full CWA Backend Using Docker Compose
51
52 For your convenience, a full setup for local development and testing purposes, including the generation of test data has been prepared using [Docker Compose](https://docs.docker.com/compose/reference/overview/). To build the backend services, run ```docker-compose build``` in the repository's root directory. A default configuration file can be found under ```.env``` in the root folder of the repository. If the endpoints are to be exposed to the network the default values in this file should be changed before docker-compose is run.
53
54 Once the services are built, you can start the whole backend using ```docker-compose up```.
55 The distribution service runs once and then finishes. If you want to trigger additional distribution runs, run ```docker-compose run distribution```.
56
57 The docker-compose contains the following services:
58
59 Service | Description | Endpoint and Default Credentials
60 ------------------|-------------|-----------
61 submission | The Corona-Warn-App submission service | `http://localhost:8000` <br> `http://localhost:8006` (for actuator endpoint)
62 distribution | The Corona-Warn-App distribution service | NO ENDPOINT
63 postgres | A [postgres] database installation | `localhost:8001` <br> `postgres:5432` (from containerized pgadmin) <br> Username: postgres <br> Password: postgres
64 pgadmin | A [pgadmin](https://www.pgadmin.org/) installation for the postgres database | `http://localhost:8002` <br> Username: [email protected] <br> Password: password
65 cloudserver | [Zenko CloudServer] is a S3-compliant object store | `http://localhost:8003/` <br> Access key: accessKey1 <br> Secret key: verySecretKey1
66 verification-fake | A very simple fake implementation for the tan verification. | `http://localhost:8004/version/v1/tan/verify` <br> The only valid tan is `edc07f08-a1aa-11ea-bb37-0242ac130002`.
67
68 ##### Known Limitation
69
70 In rare cases the docker-compose runs into a timing issue if the distribution service starts before the bucket of the objectstore was created. This is not a big issue as you can simply run ```docker-compose run distribution``` to trigger additional distribution runs after the objectstore was initialized.
71
72 #### Running Single CWA Services Using Docker
73
74 If you would like to build and run a single CWA service, it's considered easiest to run them in a Docker environment. You can do this using the script provided in the respective CWA service directory. The Docker script first builds the CWA service and then creates an image for the runtime, which means that there are no additional dependencies for you to install.
75
76 To build and run the distribution service, run the following command:
77
78 ```bash
79 ./services/distribution/build_and_run.sh
80 ```
81
82 To build and run the submission service, run the following command:
83
84 ```bash
85 ./services/submission/build_and_run.sh
86 ```
87
88 The submission service is available on [localhost:8080](http://localhost:8080 ).
89
90 ### Maven-Based Build
91
92 If you want to actively develop in one of the CWA services, the Maven-based runtime is most suitable.
93 To prepare your machine to run the CWA project locally, we recommend that you first ensure that you've installed the following:
94
95 * Minimum JDK Version 11: [OpenJDK](https://openjdk.java.net/) / [SapMachine](https://sap.github.io/SapMachine/)
96 * [Maven 3.6](https://maven.apache.org/)
97 * [Postgres]
98 * [Zenko CloudServer]
99
100 If you are already running a local Postgres, you need to create a database `cwa` and run the following setup scripts:
101
102 * Create the different CWA roles first by executing [create-roles.sql](setup/create-roles.sql).
103 * Create local database users for the specific roles by running [create-users.sql](./local-setup/create-users.sql).
104 * It is recommended to also run [enable-test-data-docker-compose.sql](./local-setup/enable-test-data-docker-compose.sql)
105 , which enables the test data generation profile. If you already had CWA running before and an existing `diagnosis-key`
106 table on your database, you need to run [enable-test-data.sql](./local-setup/enable-test-data.sql) instead.
107
108 You can also use `docker-compose` to start Postgres and Zenko. If you do that, you have to
109 set the following environment-variables when running the Spring project:
110
111 For the distribution module:
112
113 ```bash
114 POSTGRESQL_SERVICE_PORT=8001
115 VAULT_FILESIGNING_SECRET=</path/to/your/private_key>
116 SPRING_PROFILES_ACTIVE=signature-dev,disable-ssl-client-postgres
117 ```
118
119 For the submission module:
120
121 ```bash
122 POSTGRESQL_SERVICE_PORT=8001
123 SPRING_PROFILES_ACTIVE=disable-ssl-server,disable-ssl-client-postgres,disable-ssl-client-verification,disable-ssl-client-verification-verify-hostname
124 ```
125
126 #### Configure
127
128 After you made sure that the specified dependencies are running, configure them in the respective configuration files.
129
130 * Configure the Postgres connection in the [submission config](./services/submission/src/main/resources/application.yaml) and in the [distribution config](./services/distribution/src/main/resources/application.yaml)
131 * Configure the S3 compatible object storage in the [distribution config](./services/distribution/src/main/resources/application.yaml)
132 * Configure the private key for the distribution service, the path need to be prefixed with `file:`
133 * `VAULT_FILESIGNING_SECRET` should be the path to the private key, example available in `<repo-root>/docker-compose-test-secrets/private.pem`
134
135 #### Build
136
137 After you've checked out the repository, to build the project, run ```mvn install``` in your base directory.
138
139 #### Run
140
141 Navigate to the service you want to start and run the spring-boot:run target. The configured Postgres and the configured S3 compliant object storage are used as default. When you start the submission service, the endpoint is available on your local port 8080.
142
143 If you want to start the submission service, for example, you start it as follows:
144
145 ```bash
146 cd services/submission/
147 mvn spring-boot:run
148 ```
149
150 #### Debugging
151
152 To enable the `DEBUG` log level, you can run the application using the Spring `dev` profile.
153
154 ```bash
155 mvn spring-boot:run -Dspring.profiles.active=dev
156 ```
157
158 To be able to set breakpoints (e.g. in IntelliJ), it may be necessary to use the ```-Dspring-boot.run.fork=false``` parameter.
159
160 ## Service APIs
161
162 The API that is being exposed by the backend services is documented in an [OpenAPI](https://www.openapis.org/) specification. The specification files are available at the following locations:
163
164 Service | OpenAPI Specification
165 --------------------------|-------------
166 Submission Service | [services/submission/api_v1.json](https://github.com/corona-warn-app/cwa-server/raw/master/services/submission/api_v1.json)
167 Distribution Service | [services/distribution/api_v1.json](https://github.com/corona-warn-app/cwa-server/raw/master/services/distribution/api_v1.json)
168
169 ## Spring Profiles
170
171 ### Distribution
172
173 See [Distribution Service - Spring Profiles](/docs/DISTRIBUTION.md#spring-profiles).
174
175 ### Submission
176
177 See [Submission Service - Spring Profiles](/docs/SUBMISSION.md#spring-profiles).
178
179 ## Documentation
180
181 The full documentation for the Corona-Warn-App can be found in the [cwa-documentation](https://github.com/corona-warn-app/cwa-documentation) repository. The documentation repository contains technical documents, architecture information, and whitepapers related to this implementation.
182
183 The documentation for cwa-server can be found under the [/docs](./docs) folder.
184
185 The JavaDoc documentation for cwa-server is hosted by Github Pages at [https://corona-warn-app.github.io/cwa-server](https://corona-warn-app.github.io/cwa-server).
186
187 ## Support and Feedback
188
189 The following channels are available for discussions, feedback, and support requests:
190
191 | Type | Channel |
192 | ------------------------ | ------------------------------------------------------ |
193 | **General Discussion** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="General Discussion"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/question.svg?style=flat-square"></a> </a> |
194 | **Concept Feedback** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="Open Concept Feedback"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/architecture.svg?style=flat-square"></a> |
195 | **Backend Issue** | <a href="https://github.com/corona-warn-app/cwa-server/issues/new/choose" title="Open Backend Issue"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat-square"></a> |
196 | **Other Requests** | <a href="mailto:[email protected]" title="Email CWA Team"><img src="https://img.shields.io/badge/email-CWA%20team-green?logo=mail.ru&style=flat-square&logoColor=white"></a> |
197
198 ## How to Contribute
199
200 Contribution and feedback are 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.
201
202 ## Contributors
203
204 The German government has asked SAP and Deutsche Telekom to develop the Corona-Warn-App for Germany as open source software. Deutsche Telekom is providing the network and mobile technology and will operate and run the backend for the app in a safe, scalable and stable manner. SAP is responsible for the app development, its framework and the underlying platform. Therefore, development teams of SAP and Deutsche Telekom are contributing to this project. At the same time 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.
205
206 ## Repositories
207
208 The following public repositories are currently available for the Corona-Warn-App:
209
210 | Repository | Description |
211 | ------------------- | --------------------------------------------------------------------- |
212 | [cwa-documentation] | Project overview, general documentation, and white papers |
213 | [cwa-server] | Backend implementation for the Apple/Google exposure notification API|
214 | [cwa-verification-server] | Backend implementation of the verification process|
215
216 [cwa-documentation]: https://github.com/corona-warn-app/cwa-documentation
217 [cwa-server]: https://github.com/corona-warn-app/cwa-server
218 [cwa-verification-server]: https://github.com/corona-warn-app/cwa-verification-server
219 [Postgres]: https://www.postgresql.org/
220 [HSQLDB]: http://hsqldb.org/
221 [Zenko CloudServer]: https://github.com/scality/cloudserver
222
223 ## Licensing
224
225 Copyright (c) 2020 SAP SE or an SAP affiliate company.
226
227 Licensed under the **Apache License, Version 2.0** (the "License"); you may not use this file except in compliance with the License.
228
229 You may obtain a copy of the License at <https://www.apache.org/licenses/LICENSE-2.0>.
230
231 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.
232
[end of README.md]
[start of common/persistence/src/main/java/app/coronawarn/server/common/persistence/domain/DiagnosisKey.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.common.persistence.domain;
22
23 import static java.time.ZoneOffset.UTC;
24
25 import app.coronawarn.server.common.persistence.domain.DiagnosisKeyBuilders.Builder;
26 import app.coronawarn.server.common.persistence.domain.validation.ValidCountries;
27 import app.coronawarn.server.common.persistence.domain.validation.ValidRollingStartIntervalNumber;
28 import app.coronawarn.server.common.persistence.domain.validation.ValidSubmissionTimestamp;
29 import app.coronawarn.server.common.protocols.external.exposurenotification.ReportType;
30 import java.time.Instant;
31 import java.time.LocalDateTime;
32 import java.util.Arrays;
33 import java.util.Collections;
34 import java.util.List;
35 import java.util.Objects;
36 import java.util.Set;
37 import javax.validation.ConstraintViolation;
38 import javax.validation.Validation;
39 import javax.validation.Validator;
40 import javax.validation.constraints.Size;
41 import org.hibernate.validator.constraints.Range;
42 import org.springframework.data.annotation.Id;
43
44 /**
45 * A key generated for advertising over a window of time.
46 */
47 public class DiagnosisKey {
48
49 public static final long ROLLING_PERIOD_MINUTES_INTERVAL = 10;
50
51 /**
52 * According to "Setting Up an Exposure Notification Server" by Apple, exposure notification servers are expected to
53 * reject any diagnosis keys that do not have a rolling period of a certain fixed value. See
54 * https://developer.apple.com/documentation/exposurenotification/setting_up_an_exposure_notification_server
55 */
56 public static final int MIN_ROLLING_PERIOD = 0;
57 public static final int MAX_ROLLING_PERIOD = 144;
58
59 private static final Validator VALIDATOR = Validation.buildDefaultValidatorFactory().getValidator();
60
61 @Id
62 @Size(min = 16, max = 16, message = "Key data must be a byte array of length 16.")
63 private final byte[] keyData;
64
65 @ValidRollingStartIntervalNumber
66 private final int rollingStartIntervalNumber;
67
68 @Range(min = MIN_ROLLING_PERIOD, max = MAX_ROLLING_PERIOD,
69 message = "Rolling period must be between " + MIN_ROLLING_PERIOD + " and " + MAX_ROLLING_PERIOD + ".")
70 private final int rollingPeriod;
71
72 @Range(min = 0, max = 8, message = "Risk level must be between 0 and 8.")
73 private final int transmissionRiskLevel;
74
75 @ValidSubmissionTimestamp
76 private final long submissionTimestamp;
77
78 private final boolean consentToFederation;
79
80 @Size(max = 2)
81 private final String originCountry;
82
83 @ValidCountries
84 private final List<String> visitedCountries;
85
86 private final ReportType reportType;
87
88 private final int daysSinceOnsetOfSymptoms;
89
90 /**
91 * Should be called by builders.
92 */
93 DiagnosisKey(byte[] keyData, int rollingStartIntervalNumber, int rollingPeriod,
94 int transmissionRiskLevel, long submissionTimestamp,
95 boolean consentToFederation, @Size String originCountry, List<String> visitedCountries,
96 ReportType reportType, int daysSinceOnsetOfSymptoms) {
97 this.keyData = keyData;
98 this.rollingStartIntervalNumber = rollingStartIntervalNumber;
99 this.rollingPeriod = rollingPeriod;
100 this.transmissionRiskLevel = transmissionRiskLevel;
101 this.submissionTimestamp = submissionTimestamp;
102 this.consentToFederation = consentToFederation;
103 this.originCountry = originCountry;
104 this.visitedCountries = visitedCountries == null ? Collections.emptyList() : visitedCountries;
105 this.reportType = reportType;
106 this.daysSinceOnsetOfSymptoms = daysSinceOnsetOfSymptoms;
107 }
108
109 /**
110 * Returns a DiagnosisKeyBuilder instance. A {@link DiagnosisKey} can then be build by either providing the required
111 * member values or by passing the respective protocol buffer object.
112 *
113 * @return DiagnosisKeyBuilder instance.
114 */
115 public static Builder builder() {
116 return new DiagnosisKeyBuilder();
117 }
118
119 /**
120 * Returns the diagnosis key.
121 */
122 public byte[] getKeyData() {
123 return keyData;
124 }
125
126 /**
127 * Returns a number describing when a key starts. It is equal to startTimeOfKeySinceEpochInSecs / (60 * 10).
128 */
129 public int getRollingStartIntervalNumber() {
130 return rollingStartIntervalNumber;
131 }
132
133 /**
134 * Returns a number describing how long a key is valid. It is expressed in increments of 10 minutes (e.g. 144 for 24
135 * hours).
136 */
137 public int getRollingPeriod() {
138 return rollingPeriod;
139 }
140
141 /**
142 * Returns the risk of transmission associated with the person this key came from.
143 */
144 public int getTransmissionRiskLevel() {
145 return transmissionRiskLevel;
146 }
147
148 /**
149 * Returns the timestamp associated with the submission of this {@link DiagnosisKey} as hours since epoch.
150 */
151 public long getSubmissionTimestamp() {
152 return submissionTimestamp;
153 }
154
155 public boolean isConsentToFederation() {
156 return consentToFederation;
157 }
158
159 public String getOriginCountry() {
160 return originCountry;
161 }
162
163 public List<String> getVisitedCountries() {
164 return visitedCountries;
165 }
166
167 public ReportType getReportType() {
168 return reportType;
169 }
170
171 public int getDaysSinceOnsetOfSymptoms() {
172 return daysSinceOnsetOfSymptoms;
173 }
174
175 /**
176 * Checks if this diagnosis key falls into the period between now, and the retention threshold.
177 *
178 * @param daysToRetain the number of days before a key is outdated
179 * @return true, if the rolling start interval number is within the time between now, and the given days to retain
180 * @throws IllegalArgumentException if {@code daysToRetain} is negative.
181 */
182 public boolean isYoungerThanRetentionThreshold(int daysToRetain) {
183 if (daysToRetain < 0) {
184 throw new IllegalArgumentException("Retention threshold must be greater or equal to 0.");
185 }
186 long threshold = LocalDateTime
187 .ofInstant(Instant.now(), UTC)
188 .minusDays(daysToRetain)
189 .toEpochSecond(UTC) / (60 * 10);
190
191 return this.rollingStartIntervalNumber >= threshold;
192 }
193
194 /**
195 * Gets any constraint violations that this key might incorporate.
196 *
197 * <p><ul>
198 * <li>Risk level must be between 0 and 8
199 * <li>Rolling start interval number must be greater than 0
200 * <li>Rolling start number cannot be in the future
201 * <li>Rolling period must be positive number
202 * <li>Key data must be byte array of length 16
203 * </ul>
204 *
205 * @return A set of constraint violations of this key.
206 */
207 public Set<ConstraintViolation<DiagnosisKey>> validate() {
208 return VALIDATOR.validate(this);
209 }
210
211 @Override
212 public boolean equals(Object o) {
213 if (this == o) {
214 return true;
215 }
216 if (o == null || getClass() != o.getClass()) {
217 return false;
218 }
219 DiagnosisKey that = (DiagnosisKey) o;
220 return rollingStartIntervalNumber == that.rollingStartIntervalNumber
221 && rollingPeriod == that.rollingPeriod
222 && transmissionRiskLevel == that.transmissionRiskLevel
223 && submissionTimestamp == that.submissionTimestamp
224 && Arrays.equals(keyData, that.keyData)
225 && Objects.equals(originCountry, that.originCountry)
226 && Objects.equals(visitedCountries, that.visitedCountries)
227 && reportType == that.reportType
228 && daysSinceOnsetOfSymptoms == that.daysSinceOnsetOfSymptoms;
229 }
230
231 @Override
232 public int hashCode() {
233 int result = Objects
234 .hash(rollingStartIntervalNumber, rollingPeriod, transmissionRiskLevel, submissionTimestamp, originCountry,
235 visitedCountries, reportType, daysSinceOnsetOfSymptoms);
236 result = 31 * result + Arrays.hashCode(keyData);
237 return result;
238 }
239 }
240
[end of common/persistence/src/main/java/app/coronawarn/server/common/persistence/domain/DiagnosisKey.java]
[start of common/persistence/src/main/java/app/coronawarn/server/common/persistence/repository/DiagnosisKeyRepository.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.common.persistence.repository;
22
23 import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
24 import org.springframework.data.jdbc.repository.query.Modifying;
25 import org.springframework.data.jdbc.repository.query.Query;
26 import org.springframework.data.repository.PagingAndSortingRepository;
27 import org.springframework.data.repository.query.Param;
28 import org.springframework.stereotype.Repository;
29
30 @Repository
31 public interface DiagnosisKeyRepository extends PagingAndSortingRepository<DiagnosisKey, Long> {
32
33 /**
34 * Counts all entries that have a submission timestamp less or equal than the specified one
35 * and match the given country_code.
36 *
37 * @param submissionTimestamp The submission timestamp up to which entries will be expired.
38 * @return The number of expired keys.
39 */
40 @Query("SELECT COUNT(*) FROM diagnosis_key WHERE submission_timestamp<:threshold")
41 int countOlderThan(@Param("threshold") long submissionTimestamp);
42
43 /**
44 * Deletes all entries that have a submission timestamp less or equal than the specified one
45 * and match the origin country_code.
46 *
47 * @param submissionTimestamp The submission timestamp up to which entries will be deleted.
48 */
49 @Modifying
50 @Query("DELETE FROM diagnosis_key WHERE submission_timestamp<:threshold")
51 void deleteOlderThan(@Param("threshold") long submissionTimestamp);
52
53 /**
54 * Attempts to write the specified diagnosis key information into the database. If a row with the specified key data
55 * already exists, no data is inserted.
56 *
57 * @param keyData The key data of the diagnosis key.
58 * @param rollingStartIntervalNumber The rolling start interval number of the diagnosis key.
59 * @param rollingPeriod The rolling period of the diagnosis key.
60 * @param submissionTimestamp The submission timestamp of the diagnosis key.
61 * @param transmissionRisk The transmission risk level of the diagnosis key.
62 * @param originCountry The origin country from the app.
63 * @param visitedCountries The list of countries this transmissions is relevant for.
64 * @param reportType The report type of the diagnosis key.
65 */
66 @Modifying
67 @Query("INSERT INTO diagnosis_key "
68 + "(key_data, rolling_start_interval_number, rolling_period, submission_timestamp, transmission_risk_level, "
69 + "origin_country, visited_countries, report_type, days_since_onset_of_symptoms, consent_to_federation) "
70 + "VALUES (:keyData, :rollingStartIntervalNumber, :rollingPeriod, :submissionTimestamp, :transmissionRisk, "
71 + ":origin_country, :visited_countries, :report_type, :days_since_onset_of_symptoms, :consent_to_federation) "
72 + "ON CONFLICT DO NOTHING")
73 void saveDoNothingOnConflict(
74 @Param("keyData") byte[] keyData,
75 @Param("rollingStartIntervalNumber") int rollingStartIntervalNumber,
76 @Param("rollingPeriod") int rollingPeriod,
77 @Param("submissionTimestamp") long submissionTimestamp,
78 @Param("transmissionRisk") int transmissionRisk,
79 @Param("origin_country") String originCountry,
80 @Param("visited_countries") String[] visitedCountries,
81 @Param("report_type") String reportType,
82 @Param("days_since_onset_of_symptoms") int daysSinceOnsetOfSymptoms,
83 @Param("consent_to_federation") boolean consentToFederation);
84 }
85
[end of common/persistence/src/main/java/app/coronawarn/server/common/persistence/repository/DiagnosisKeyRepository.java]
[start of common/persistence/src/main/java/app/coronawarn/server/common/persistence/service/DiagnosisKeyService.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.common.persistence.service;
22
23 import static app.coronawarn.server.common.persistence.domain.validation.ValidSubmissionTimestampValidator.SECONDS_PER_HOUR;
24 import static java.time.ZoneOffset.UTC;
25 import static org.springframework.data.util.StreamUtils.createStreamFromIterator;
26
27 import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
28 import app.coronawarn.server.common.persistence.repository.DiagnosisKeyRepository;
29 import app.coronawarn.server.common.persistence.service.common.ValidDiagnosisKeyFilter;
30 import io.micrometer.core.annotation.Timed;
31 import java.time.Instant;
32 import java.time.LocalDateTime;
33 import java.util.Collection;
34 import java.util.List;
35 import java.util.stream.Collectors;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38 import org.springframework.data.domain.Sort;
39 import org.springframework.data.domain.Sort.Direction;
40 import org.springframework.stereotype.Component;
41 import org.springframework.transaction.annotation.Transactional;
42
43 @Component
44 public class DiagnosisKeyService {
45
46 private static final Logger logger = LoggerFactory.getLogger(DiagnosisKeyService.class);
47 private final DiagnosisKeyRepository keyRepository;
48 private final ValidDiagnosisKeyFilter validationFilter;
49
50 public DiagnosisKeyService(DiagnosisKeyRepository keyRepository, ValidDiagnosisKeyFilter filter) {
51 this.keyRepository = keyRepository;
52 this.validationFilter = filter;
53 }
54
55 /**
56 * Persists the specified collection of {@link DiagnosisKey} instances. If the key data of a particular diagnosis key
57 * already exists in the database, this diagnosis key is not persisted.
58 *
59 * @param diagnosisKeys must not contain {@literal null}.
60 * @throws IllegalArgumentException in case the given collection contains {@literal null}.
61 */
62 @Timed
63 @Transactional
64 public void saveDiagnosisKeys(Collection<DiagnosisKey> diagnosisKeys) {
65 for (DiagnosisKey diagnosisKey : diagnosisKeys) {
66 keyRepository.saveDoNothingOnConflict(
67 diagnosisKey.getKeyData(), diagnosisKey.getRollingStartIntervalNumber(), diagnosisKey.getRollingPeriod(),
68 diagnosisKey.getSubmissionTimestamp(), diagnosisKey.getTransmissionRiskLevel(),
69 diagnosisKey.getOriginCountry(), diagnosisKey.getVisitedCountries().toArray(new String[0]),
70 diagnosisKey.getReportType().name(), diagnosisKey.getDaysSinceOnsetOfSymptoms(),
71 diagnosisKey.isConsentToFederation());
72 }
73 }
74
75 /**
76 * Returns all valid persisted diagnosis keys, sorted by their submission timestamp.
77 */
78 public List<DiagnosisKey> getDiagnosisKeys() {
79 List<DiagnosisKey> diagnosisKeys = createStreamFromIterator(
80 keyRepository.findAll(Sort.by(Direction.ASC, "submissionTimestamp")).iterator()).collect(Collectors.toList());
81 return validationFilter.filter(diagnosisKeys);
82 }
83
84 /**
85 * Deletes all diagnosis key entries which have a submission timestamp that is older than the specified number of
86 * days.
87 *
88 * @param daysToRetain the number of days until which diagnosis keys will be retained.
89 * @throws IllegalArgumentException if {@code daysToRetain} is negative.
90 */
91 @Transactional
92 public void applyRetentionPolicy(int daysToRetain) {
93 if (daysToRetain < 0) {
94 throw new IllegalArgumentException("Number of days to retain must be greater or equal to 0.");
95 }
96
97 long threshold = LocalDateTime
98 .ofInstant(Instant.now(), UTC)
99 .minusDays(daysToRetain)
100 .toEpochSecond(UTC) / SECONDS_PER_HOUR;
101 int numberOfDeletions = keyRepository.countOlderThan(threshold);
102 logger.info("Deleting {} diagnosis key(s) with a submission timestamp older than {} day(s) ago.",
103 numberOfDeletions, daysToRetain);
104 keyRepository.deleteOlderThan(threshold);
105 }
106 }
107
[end of common/persistence/src/main/java/app/coronawarn/server/common/persistence/service/DiagnosisKeyService.java]
[start of services/submission/src/main/java/app/coronawarn/server/services/submission/controller/SubmissionController.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.submission.controller;
22
23 import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
24 import app.coronawarn.server.common.persistence.service.DiagnosisKeyService;
25 import app.coronawarn.server.common.protocols.external.exposurenotification.TemporaryExposureKey;
26 import app.coronawarn.server.common.protocols.internal.SubmissionPayload;
27 import app.coronawarn.server.services.submission.config.SubmissionServiceConfig;
28 import app.coronawarn.server.services.submission.monitoring.SubmissionMonitor;
29 import app.coronawarn.server.services.submission.validation.ValidSubmissionPayload;
30 import app.coronawarn.server.services.submission.verification.TanVerifier;
31 import io.micrometer.core.annotation.Timed;
32 import java.security.SecureRandom;
33 import java.util.ArrayList;
34 import java.util.List;
35 import java.util.stream.IntStream;
36 import org.apache.commons.lang3.StringUtils;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39 import org.springframework.http.HttpStatus;
40 import org.springframework.http.ResponseEntity;
41 import org.springframework.util.StopWatch;
42 import org.springframework.validation.annotation.Validated;
43 import org.springframework.web.bind.annotation.PostMapping;
44 import org.springframework.web.bind.annotation.RequestBody;
45 import org.springframework.web.bind.annotation.RequestHeader;
46 import org.springframework.web.bind.annotation.RequestMapping;
47 import org.springframework.web.bind.annotation.RestController;
48 import org.springframework.web.context.request.async.DeferredResult;
49
50 @RestController
51 @RequestMapping("/version/v1")
52 @Validated
53 public class SubmissionController {
54
55 /**
56 * The route to the submission endpoint (version agnostic).
57 */
58 public static final String SUBMISSION_ROUTE = "/diagnosis-keys";
59 private static final Logger logger = LoggerFactory.getLogger(SubmissionController.class);
60 private final SubmissionMonitor submissionMonitor;
61 private final DiagnosisKeyService diagnosisKeyService;
62 private final TanVerifier tanVerifier;
63 private final Integer retentionDays;
64 private final Integer randomKeyPaddingMultiplier;
65 private final FakeDelayManager fakeDelayManager;
66 private final SubmissionServiceConfig submissionServiceConfig;
67
68 SubmissionController(
69 DiagnosisKeyService diagnosisKeyService, TanVerifier tanVerifier, FakeDelayManager fakeDelayManager,
70 SubmissionServiceConfig submissionServiceConfig, SubmissionMonitor submissionMonitor) {
71 this.diagnosisKeyService = diagnosisKeyService;
72 this.tanVerifier = tanVerifier;
73 this.submissionMonitor = submissionMonitor;
74 this.fakeDelayManager = fakeDelayManager;
75 this.submissionServiceConfig = submissionServiceConfig;
76 retentionDays = submissionServiceConfig.getRetentionDays();
77 randomKeyPaddingMultiplier = submissionServiceConfig.getRandomKeyPaddingMultiplier();
78 }
79
80 /**
81 * Handles diagnosis key submission requests.
82 *
83 * @param exposureKeys The unmarshalled protocol buffers submission payload.
84 * @param tan A tan for diagnosis verification.
85 * @return An empty response body.
86 */
87 @PostMapping(value = SUBMISSION_ROUTE, headers = {"cwa-fake=0"})
88 @Timed(description = "Time spent handling submission.")
89 public DeferredResult<ResponseEntity<Void>> submitDiagnosisKey(
90 @ValidSubmissionPayload @RequestBody SubmissionPayload exposureKeys,
91 @RequestHeader("cwa-authorization") String tan) {
92 submissionMonitor.incrementRequestCounter();
93 submissionMonitor.incrementRealRequestCounter();
94 return buildRealDeferredResult(exposureKeys, tan);
95 }
96
97 private DeferredResult<ResponseEntity<Void>> buildRealDeferredResult(SubmissionPayload submissionPayload,
98 String tan) {
99 DeferredResult<ResponseEntity<Void>> deferredResult = new DeferredResult<>();
100
101 StopWatch stopWatch = new StopWatch();
102 stopWatch.start();
103 try {
104 if (!this.tanVerifier.verifyTan(tan)) {
105 submissionMonitor.incrementInvalidTanRequestCounter();
106 deferredResult.setResult(ResponseEntity.status(HttpStatus.FORBIDDEN).build());
107 } else {
108 List<DiagnosisKey> diagnosisKeys = extractValidDiagnosisKeysFromPayload(submissionPayload);
109 diagnosisKeyService.saveDiagnosisKeys(padDiagnosisKeys(diagnosisKeys));
110
111 deferredResult.setResult(ResponseEntity.ok().build());
112 }
113 } catch (Exception e) {
114 deferredResult.setErrorResult(e);
115 } finally {
116 stopWatch.stop();
117 fakeDelayManager.updateFakeRequestDelay(stopWatch.getTotalTimeMillis());
118 }
119
120 return deferredResult;
121 }
122
123 private List<DiagnosisKey> extractValidDiagnosisKeysFromPayload(SubmissionPayload submissionPayload) {
124 List<TemporaryExposureKey> protoBufferKeys = submissionPayload.getKeysList();
125 List<DiagnosisKey> diagnosisKeys = new ArrayList<>();
126
127 for (TemporaryExposureKey protoBufferKey : protoBufferKeys) {
128 String originCountry = StringUtils.defaultIfBlank(submissionPayload.getOrigin(),
129 submissionServiceConfig.getDefaultOriginCountry());
130
131 DiagnosisKey diagnosisKey = DiagnosisKey.builder()
132 .fromTemporaryExposureKey(protoBufferKey)
133 .withVisitedCountries(submissionPayload.getVisitedCountriesList())
134 .withCountryCode(originCountry)
135 .withConsentToFederation(submissionPayload.getConsentToFederation())
136 .build();
137
138 if (diagnosisKey.isYoungerThanRetentionThreshold(retentionDays)) {
139 diagnosisKeys.add(diagnosisKey);
140 } else {
141 logger.info("Not persisting a diagnosis key, as it is outdated beyond retention threshold.");
142 }
143 }
144
145 return diagnosisKeys;
146 }
147
148 private List<DiagnosisKey> padDiagnosisKeys(List<DiagnosisKey> diagnosisKeys) {
149 List<DiagnosisKey> paddedDiagnosisKeys = new ArrayList<>();
150 diagnosisKeys.forEach(diagnosisKey -> {
151 paddedDiagnosisKeys.add(diagnosisKey);
152 IntStream.range(1, randomKeyPaddingMultiplier)
153 .mapToObj(index -> DiagnosisKey.builder()
154 .withKeyData(generateRandomKeyData())
155 .withRollingStartIntervalNumber(diagnosisKey.getRollingStartIntervalNumber())
156 .withTransmissionRiskLevel(diagnosisKey.getTransmissionRiskLevel())
157 .withRollingPeriod(diagnosisKey.getRollingPeriod())
158 .withVisitedCountries(diagnosisKey.getVisitedCountries())
159 .withCountryCode(diagnosisKey.getOriginCountry())
160 .withReportType(diagnosisKey.getReportType())
161 .withConsentToFederation(diagnosisKey.isConsentToFederation())
162 .withDaysSinceOnsetOfSymptoms(diagnosisKey.getDaysSinceOnsetOfSymptoms())
163 .build())
164 .forEach(paddedDiagnosisKeys::add);
165 });
166 return paddedDiagnosisKeys;
167 }
168
169 private static byte[] generateRandomKeyData() {
170 byte[] randomKeyData = new byte[16];
171 new SecureRandom().nextBytes(randomKeyData);
172 return randomKeyData;
173 }
174 }
175
[end of services/submission/src/main/java/app/coronawarn/server/services/submission/controller/SubmissionController.java]
</code>
Here is an example of a patch file. It consists of changes to the code base. It specifies the file names, the line numbers of each change, and the removed and added lines. A single patch file can contain changes to multiple files.
<patch>
--- a/file.py
+++ b/file.py
@@ -1,27 +1,35 @@
def euclidean(a, b):
- while b:
- a, b = b, a % b
- return a
+ if b == 0:
+ return a
+ return euclidean(b, a % b)
def bresenham(x0, y0, x1, y1):
points = []
dx = abs(x1 - x0)
dy = abs(y1 - y0)
- sx = 1 if x0 < x1 else -1
- sy = 1 if y0 < y1 else -1
- err = dx - dy
+ x, y = x0, y0
+ sx = -1 if x0 > x1 else 1
+ sy = -1 if y0 > y1 else 1
- while True:
- points.append((x0, y0))
- if x0 == x1 and y0 == y1:
- break
- e2 = 2 * err
- if e2 > -dy:
+ if dx > dy:
+ err = dx / 2.0
+ while x != x1:
+ points.append((x, y))
err -= dy
- x0 += sx
- if e2 < dx:
- err += dx
- y0 += sy
+ if err < 0:
+ y += sy
+ err += dx
+ x += sx
+ else:
+ err = dy / 2.0
+ while y != y1:
+ points.append((x, y))
+ err -= dx
+ if err < 0:
+ x += sx
+ err += dy
+ y += sy
+ points.append((x, y))
return points
</patch>
I need you to solve the provded issue by generating a single patch file that I can apply directly to this repository using git apply. Please respond with a single patch file in the format shown above.
Respond below:
| corona-warn-app/cwa-server | 3b67b75657b26418691e024e049af7f3494c787b | Improve logging of the submission validation process
<!--
Thanks for proposing an enhancement 🙌 ❤️
Before opening a new issue, please make sure that we do not have any duplicates already open. You can ensure this by searching the issue list for this repository. If there is a duplicate, please close your issue and add a comment to the existing issue instead.
-->
The enhancement suggested by @Tho-Mat, and based on the discussion in https://github.com/corona-warn-app/cwa-server/issues/723
## Current Implementation
Issue https://github.com/corona-warn-app/cwa-server/issues/723, demonstrated that currently implemented logging is not sufficient for effective troubleshooting of the submission validation process.
## Suggested Enhancement
If the kay can not be saved in a DB (e.g. because it is already in database / Date to high / Date to low / unknown), we log this fact, date of the issue and the reason in the application logs.
## Expected Benefits
This would have the great advantage of better analyzing certain constellations that can lead to errors.
| 2020-09-16T09:58:13 | <patch>
diff --git a/common/persistence/src/main/java/app/coronawarn/server/common/persistence/domain/DiagnosisKey.java b/common/persistence/src/main/java/app/coronawarn/server/common/persistence/domain/DiagnosisKey.java
--- a/common/persistence/src/main/java/app/coronawarn/server/common/persistence/domain/DiagnosisKey.java
+++ b/common/persistence/src/main/java/app/coronawarn/server/common/persistence/domain/DiagnosisKey.java
@@ -77,7 +77,7 @@ public class DiagnosisKey {
private final boolean consentToFederation;
- @Size(max = 2)
+ @Size(max = 2, message = "Origin country code must have length of 2.")
private final String originCountry;
@ValidCountries
diff --git a/common/persistence/src/main/java/app/coronawarn/server/common/persistence/repository/DiagnosisKeyRepository.java b/common/persistence/src/main/java/app/coronawarn/server/common/persistence/repository/DiagnosisKeyRepository.java
--- a/common/persistence/src/main/java/app/coronawarn/server/common/persistence/repository/DiagnosisKeyRepository.java
+++ b/common/persistence/src/main/java/app/coronawarn/server/common/persistence/repository/DiagnosisKeyRepository.java
@@ -62,6 +62,7 @@ public interface DiagnosisKeyRepository extends PagingAndSortingRepository<Diagn
* @param originCountry The origin country from the app.
* @param visitedCountries The list of countries this transmissions is relevant for.
* @param reportType The report type of the diagnosis key.
+ * @return {@literal true} if the diagnosis key was inserted successfully, {@literal false} otherwise.
*/
@Modifying
@Query("INSERT INTO diagnosis_key "
@@ -70,7 +71,7 @@ public interface DiagnosisKeyRepository extends PagingAndSortingRepository<Diagn
+ "VALUES (:keyData, :rollingStartIntervalNumber, :rollingPeriod, :submissionTimestamp, :transmissionRisk, "
+ ":origin_country, :visited_countries, :report_type, :days_since_onset_of_symptoms, :consent_to_federation) "
+ "ON CONFLICT DO NOTHING")
- void saveDoNothingOnConflict(
+ boolean saveDoNothingOnConflict(
@Param("keyData") byte[] keyData,
@Param("rollingStartIntervalNumber") int rollingStartIntervalNumber,
@Param("rollingPeriod") int rollingPeriod,
diff --git a/common/persistence/src/main/java/app/coronawarn/server/common/persistence/service/DiagnosisKeyService.java b/common/persistence/src/main/java/app/coronawarn/server/common/persistence/service/DiagnosisKeyService.java
--- a/common/persistence/src/main/java/app/coronawarn/server/common/persistence/service/DiagnosisKeyService.java
+++ b/common/persistence/src/main/java/app/coronawarn/server/common/persistence/service/DiagnosisKeyService.java
@@ -53,23 +53,39 @@ public DiagnosisKeyService(DiagnosisKeyRepository keyRepository, ValidDiagnosisK
}
/**
- * Persists the specified collection of {@link DiagnosisKey} instances. If the key data of a particular diagnosis key
- * already exists in the database, this diagnosis key is not persisted.
+ * Persists the specified collection of {@link DiagnosisKey} instances and returns the number of inserted diagnosis
+ * keys. If the key data of a particular diagnosis key already exists in the database, this diagnosis key is not
+ * persisted.
*
* @param diagnosisKeys must not contain {@literal null}.
+ * @return Number of successfully inserted diagnosis keys.
* @throws IllegalArgumentException in case the given collection contains {@literal null}.
*/
@Timed
@Transactional
- public void saveDiagnosisKeys(Collection<DiagnosisKey> diagnosisKeys) {
+ public int saveDiagnosisKeys(Collection<DiagnosisKey> diagnosisKeys) {
+ int numberOfInsertedKeys = 0;
+
for (DiagnosisKey diagnosisKey : diagnosisKeys) {
- keyRepository.saveDoNothingOnConflict(
+ boolean keyInsertedSuccessfully = keyRepository.saveDoNothingOnConflict(
diagnosisKey.getKeyData(), diagnosisKey.getRollingStartIntervalNumber(), diagnosisKey.getRollingPeriod(),
diagnosisKey.getSubmissionTimestamp(), diagnosisKey.getTransmissionRiskLevel(),
diagnosisKey.getOriginCountry(), diagnosisKey.getVisitedCountries().toArray(new String[0]),
diagnosisKey.getReportType().name(), diagnosisKey.getDaysSinceOnsetOfSymptoms(),
diagnosisKey.isConsentToFederation());
+
+ if (keyInsertedSuccessfully) {
+ numberOfInsertedKeys++;
+ }
}
+
+ int conflictingKeys = diagnosisKeys.size() - numberOfInsertedKeys;
+ if (conflictingKeys > 0) {
+ logger.warn("{} out of {} diagnosis keys conflicted with existing database entries and were ignored.",
+ conflictingKeys, diagnosisKeys.size());
+ }
+
+ return numberOfInsertedKeys;
}
/**
diff --git a/services/submission/src/main/java/app/coronawarn/server/services/submission/controller/SubmissionController.java b/services/submission/src/main/java/app/coronawarn/server/services/submission/controller/SubmissionController.java
--- a/services/submission/src/main/java/app/coronawarn/server/services/submission/controller/SubmissionController.java
+++ b/services/submission/src/main/java/app/coronawarn/server/services/submission/controller/SubmissionController.java
@@ -138,7 +138,7 @@ private List<DiagnosisKey> extractValidDiagnosisKeysFromPayload(SubmissionPayloa
if (diagnosisKey.isYoungerThanRetentionThreshold(retentionDays)) {
diagnosisKeys.add(diagnosisKey);
} else {
- logger.info("Not persisting a diagnosis key, as it is outdated beyond retention threshold.");
+ logger.warn("Not persisting a diagnosis key, as it is outdated beyond retention threshold.");
}
}
</patch> | diff --git a/common/persistence/src/test/java/app/coronawarn/server/common/persistence/service/DiagnosisKeyServiceTest.java b/common/persistence/src/test/java/app/coronawarn/server/common/persistence/service/DiagnosisKeyServiceTest.java
--- a/common/persistence/src/test/java/app/coronawarn/server/common/persistence/service/DiagnosisKeyServiceTest.java
+++ b/common/persistence/src/test/java/app/coronawarn/server/common/persistence/service/DiagnosisKeyServiceTest.java
@@ -155,10 +155,22 @@ void shouldNotUpdateExistingKey() {
.withReportType(ReportType.CONFIRMED_CLINICAL_DIAGNOSIS)
.build());
- diagnosisKeyService.saveDiagnosisKeys(keys);
+ int actNumberOfInsertedRows = diagnosisKeyService.saveDiagnosisKeys(keys);
var actKeys = diagnosisKeyService.getDiagnosisKeys();
+ assertThat(actNumberOfInsertedRows).isEqualTo(1);
assertThat(actKeys).hasSize(1);
assertThat(actKeys.iterator().next().getTransmissionRiskLevel()).isEqualTo(2);
}
+
+ @Test
+ void testReturnedNumberOfInsertedKeysForNoConflict() {
+ var keys = list(
+ buildDiagnosisKeyForSubmissionTimestamp(1L),
+ buildDiagnosisKeyForSubmissionTimestamp(0L));
+
+ int actNumberOfInsertedRows = diagnosisKeyService.saveDiagnosisKeys(keys);
+
+ assertThat(actNumberOfInsertedRows).isEqualTo(2);
+ }
}
| |||||
corona-warn-app__cwa-server-387 | You will be provided with a partial code base and an issue statement explaining a problem to resolve.
<issue>
Use typed client and entities for tan verification
## Current Implementation
The current tan verification look like this:
https://github.com/corona-warn-app/cwa-server/blob/3b98beb268bac511c00f8e13bcbb4978a8cdb4fd/services/submission/src/main/java/app/coronawarn/server/services/submission/verification/TanVerifier.java#L102-L115
There are a couple of issues I would see here:
1. The tan entity is build from a string which can cause bugs, encoding issues an more.
2. When the interface of the verification server changes (and this a repo owned by the same organization) this has to be modified as well and can cause runtime bugs without proper system testing
## Suggested Enhancement
I would suggest two things
1. Create a DTO (Pojo) for the tan payload and pass that to the rest template to let Jackson handle serialization
2. If a dependency between cwa projects is "allowed" (which I would think is perfectly fine) I would actually move that entity to the verification server project in a separate maven module. I would add [Spring Feign client ](https://cloud.spring.io/spring-cloud-netflix/multi/multi_spring-cloud-feign.html) and use that in the CWA server. Feign is like the reverse version of `@RestController` and supports the same annotations. It will create the client implementation from the given interface at runtime.
The client would look like this:
```
@FeignClient(name = "verification-server", url = "${services.submission.verification.baseUrl}")
public interface StoreClient {
@RequestMapping(method = RequestMethod.POST, value = "${services.submission.verification.path}", consumes = "application/json")
ValidationResult validateTan(Tan tan); // both classes should be Pojos
}
```
The usage would look like this (I did not actually implemented that!):
```
private boolean verifyWithVerificationService(String tanString) {
Tan tan = Tan.from(tanString); // This should also do the UUID verification!
ValidationResult result = verificationServer.validateTan(tan);
return result != null;
}
```
## Expected Benefits
- Compilation breaks when interface changes
- Less risk of bugs
</issue>
<code>
[start of README.md]
1 <!-- markdownlint-disable MD041 -->
2 <h1 align="center">
3 Corona-Warn-App Server
4 </h1>
5
6 <p align="center">
7 <a href="https://github.com/corona-warn-app/cwa-server/commits/" title="Last Commit"><img src="https://img.shields.io/github/last-commit/corona-warn-app/cwa-server?style=flat"></a>
8 <a href="https://github.com/corona-warn-app/cwa-server/issues" title="Open Issues"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat"></a>
9 <a href="https://circleci.com/gh/corona-warn-app/cwa-server" title="Build Status"><img src="https://circleci.com/gh/corona-warn-app/cwa-server.svg?style=shield&circle-token=4ab059989d10709df19eb4b98ab7c121a25e981a"></a>
10 <a href="https://sonarcloud.io/dashboard?id=corona-warn-app_cwa-server" title="Quality Gate"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=alert_status"></a>
11 <a href="https://sonarcloud.io/component_measures?id=corona-warn-app_cwa-server&metric=Coverage&view=list" title="Coverage"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=coverage"></a>
12 <a href="https://github.com/corona-warn-app/cwa-server/blob/master/LICENSE" title="License"><img src="https://img.shields.io/badge/License-Apache%202.0-green.svg?style=flat"></a>
13 </p>
14
15 <p align="center">
16 <a href="#development">Development</a> •
17 <a href="#service-apis">Service APIs</a> •
18 <a href="#documentation">Documentation</a> •
19 <a href="#support-and-feedback">Support</a> •
20 <a href="#how-to-contribute">Contribute</a> •
21 <a href="#contributors">Contributors</a> •
22 <a href="#repositories">Repositories</a> •
23 <a href="#licensing">Licensing</a>
24 </p>
25
26 The goal of this project is to develop the official Corona-Warn-App for Germany based on the exposure notification API from [Apple](https://www.apple.com/covid19/contacttracing/) and [Google](https://www.google.com/covid19/exposurenotifications/). The apps (for both iOS and Android) use Bluetooth technology to exchange anonymous encrypted data with other mobile phones (on which the app is also installed) in the vicinity of an app user's phone. The data is stored locally on each user's device, preventing authorities or other parties from accessing or controlling the data. This repository contains the **implementation of the server for encryption keys** for the Corona-Warn-App. This implementation is still a **work in progress**, and the code it contains is currently alpha-quality code.
27
28 In this documentation, Corona-Warn-App services are also referred to as CWA services.
29
30 ## Architecture Overview
31
32 You can find the architecture overview [here](/docs/architecture-overview.md), which will give you
33 a good starting point in how the backend services interact with other services, and what purpose
34 they serve.
35
36 ## Development
37
38 After you've checked out this repository, you can run the application in one of the following ways:
39
40 * As a [Docker](https://www.docker.com/)-based deployment on your local machine. You can run either:
41 * Single components using the respective Dockerfile or
42 * The full backend using the Docker Compose (which is considered the most convenient way)
43 * As a [Maven](https://maven.apache.org)-based build on your local machine.
44 If you want to develop something in a single component, this approach is preferable.
45
46 ### Docker-Based Deployment
47
48 If you want to use Docker-based deployment, you need to install Docker on your local machine. For more information about downloading and installing Docker, see the [official Docker documentation](https://docs.docker.com/get-docker/).
49
50 #### Running the Full CWA Backend Using Docker Compose
51
52 For your convenience, a full setup including the generation of test data has been prepared using [Docker Compose](https://docs.docker.com/compose/reference/overview/). To build the backend services, run ```docker-compose build``` in the repository's root directory. A default configuration file can be found under ```.env```in the root folder of the repository. The default values for the local Postgres and Zenko Cloudserver should be changed in this file before docker-compose is run.
53
54 Once the services are built, you can start the whole backend using ```docker-compose up```.
55 The distribution service runs once and then finishes. If you want to trigger additional distribution runs, run ```docker-compose run distribution```.
56
57 The docker-compose contains the following services:
58
59 Service | Description | Endpoint and Default Credentials
60 ------------------|-------------|-----------
61 submission | The Corona-Warn-App submission service | `http://localhost:8000` <br> `http://localhost:8006` (for actuator endpoint)
62 distribution | The Corona-Warn-App distribution service | NO ENDPOINT
63 postgres | A [postgres] database installation | `postgres:8001` <br> Username: postgres <br> Password: postgres
64 pgadmin | A [pgadmin](https://www.pgadmin.org/) installation for the postgres database | `http://localhost:8002` <br> Username: [email protected] <br> Password: password
65 cloudserver | [Zenko CloudServer] is a S3-compliant object store | `http://localhost:8003/` <br> Access key: accessKey1 <br> Secret key: verySecretKey1
66 verification-fake | A very simple fake implementation for the tan verification. | `http://localhost:8004/version/v1/tan/verify` <br> The only valid tan is "edc07f08-a1aa-11ea-bb37-0242ac130002"
67
68 ##### Known Limitation
69
70 In rare cases the docker-compose runs into a timing issue if the distribution service starts before the bucket of the objectstore was created. This is not a big issue as you can simply run ```docker-compose run distribution``` to trigger additional distribution runs after the objectstore was initialized.
71
72 #### Running Single CWA Services Using Docker
73
74 If you would like to build and run a single CWA service, it's considered easiest to run them in a Docker environment. You can do this using the script provided in the respective CWA service directory. The Docker script first builds the CWA service and then creates an image for the runtime, which means that there are no additional dependencies for you to install.
75
76 To build and run the distribution service, run the following command:
77
78 ```bash
79 ./services/distribution/build_and_run.sh
80 ```
81
82 To build and run the submission service, run the following command:
83
84 ```bash
85 ./services/submission/build_and_run.sh
86 ```
87
88 The submission service is available on [localhost:8080](http://localhost:8080 ).
89
90 ### Maven-Based Build
91
92 If you want to actively develop in one of the CWA services, the Maven-based runtime is most suitable.
93 To prepare your machine to run the CWA project locally, we recommend that you first ensure that you've installed the following:
94
95 * Minimum JDK Version 11: [OpenJDK](https://openjdk.java.net/) / [SapMachine](https://sap.github.io/SapMachine/)
96 * [Maven 3.6](https://maven.apache.org/)
97 * [Postgres]
98 * [Zenko CloudServer]
99
100 #### Configure
101
102 After you made sure that the specified dependencies are running, configure them in the respective configuration files.
103
104 * Configure the Postgres connection in the [submission config](./services/submission/src/main/resources/application.yaml) and in the [distribution config](./services/distribution/src/main/resources/application.yaml)
105 * Configure the S3 compatible object storage in the [distribution config](./services/distribution/src/main/resources/application.yaml)
106 * Configure the private key for the distribution service, the path need to be prefixed with `file:`
107 * `VAULT_FILESIGNING_SECRET` should be the path to the private key, example available in `<repo-root>/docker-compose-test-secrets/private.pem`
108
109 #### Build
110
111 After you've checked out the repository, to build the project, run ```mvn install``` in your base directory.
112
113 #### Run
114
115 Navigate to the service you want to start and run the spring-boot:run target. The configured Postgres and the configured S3 compliant object storage are used as default. When you start the submission service, the endpoint is available on your local port 8080.
116
117 If you want to start the submission service, for example, you start it as follows:
118
119 ```bash
120 cd services/submission/
121 mvn spring-boot:run
122 ```
123
124 #### Debugging
125
126 To enable the `DEBUG` log level, you can run the application using the Spring `dev` profile.
127
128 ```bash
129 mvn spring-boot:run -Dspring-boot.run.profiles=dev
130 ```
131
132 To be able to set breakpoints (e.g. in IntelliJ), it may be necessary to use the ```-Dspring-boot.run.fork=false``` parameter.
133
134 ## Service APIs
135
136 The API that is being exposed by the backend services is documented in an [OpenAPI](https://www.openapis.org/) specification. The specification files are available at the following locations:
137
138 Service | OpenAPI Specification
139 -------------|-------------
140 Submission Service | [services/submission/api_v1.json](https://github.com/corona-warn-app/cwa-server/raw/master/services/submission/api_v1.json)
141 Distribution Service | [services/distribution/api_v1.json](https://github.com/corona-warn-app/cwa-server/raw/master/services/distribution/api_v1.json)
142
143 ## Spring Profiles
144
145 ### Distribution
146
147 Profile | Effect
148 -----------------|-------------
149 `dev` | Turns the log level to `DEBUG`.
150 `cloud` | Removes default values for the `datasource` and `objectstore` configurations.
151 `demo` | Includes incomplete days and hours into the distribution run, thus creating aggregates for the current day and the current hour (and including both in the respective indices). When running multiple distributions in one hour with this profile, the date aggregate for today and the hours aggregate for the current hour will be updated and overwritten.
152 `testdata` | Causes test data to be inserted into the database before each distribution run. By default, around 1000 random diagnosis keys will be generated per hour. If there are no diagnosis keys in the database yet, random keys will be generated for every hour from the beginning of the retention period (14 days ago at 00:00 UTC) until one hour before the present hour. If there are already keys in the database, the random keys will be generated for every hour from the latest diagnosis key in the database (by submission timestamp) until one hour before the present hour (or none at all, if the latest diagnosis key in the database was submitted one hour ago or later).
153 `signature-dev` | Sets the app package ID in the export packages' signature info to `de.rki.coronawarnapp-dev` so that test certificates (instead of production certificates) will be used for client-side validation.
154 `signature-prod` | Provides production app package IDs for the signature info
155
156 ### Submission
157
158 Profile | Effect
159 -------------|-------------
160 `dev` | Turns the log level to `DEBUG`.
161 `cloud` | Removes default values for the `datasource` configuration.
162
163 ## Documentation
164
165 The full documentation for the Corona-Warn-App can be found in the [cwa-documentation](https://github.com/corona-warn-app/cwa-documentation) repository. The documentation repository contains technical documents, architecture information, and whitepapers related to this implementation.
166
167 ## Support and Feedback
168
169 The following channels are available for discussions, feedback, and support requests:
170
171 | Type | Channel |
172 | ------------------------ | ------------------------------------------------------ |
173 | **General Discussion** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="General Discussion"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/question.svg?style=flat-square"></a> </a> |
174 | **Concept Feedback** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="Open Concept Feedback"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/architecture.svg?style=flat-square"></a> |
175 | **Backend Issue** | <a href="https://github.com/corona-warn-app/cwa-server/issues/new/choose" title="Open Backend Issue"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat-square"></a> |
176 | **Other Requests** | <a href="mailto:[email protected]" title="Email CWA Team"><img src="https://img.shields.io/badge/email-CWA%20team-green?logo=mail.ru&style=flat-square&logoColor=white"></a> |
177
178 ## How to Contribute
179
180 Contribution and feedback are 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.
181
182 ## Contributors
183
184 The German government has asked SAP and Deutsche Telekom to develop the Corona-Warn-App for Germany as open source software. Deutsche Telekom is providing the network and mobile technology and will operate and run the backend for the app in a safe, scalable and stable manner. SAP is responsible for the app development, its framework and the underlying platform. Therefore, development teams of SAP and Deutsche Telekom are contributing to this project. At the same time 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.
185
186 ## Repositories
187
188 The following public repositories are currently available for the Corona-Warn-App:
189
190 | Repository | Description |
191 | ------------------- | --------------------------------------------------------------------- |
192 | [cwa-documentation] | Project overview, general documentation, and white papers |
193 | [cwa-server] | Backend implementation for the Apple/Google exposure notification API|
194 | [cwa-verification-server] | Backend implementation of the verification process|
195
196 [cwa-documentation]: https://github.com/corona-warn-app/cwa-documentation
197 [cwa-server]: https://github.com/corona-warn-app/cwa-server
198 [cwa-verification-server]: https://github.com/corona-warn-app/cwa-verification-server
199 [Postgres]: https://www.postgresql.org/
200 [HSQLDB]: http://hsqldb.org/
201 [Zenko CloudServer]: https://github.com/scality/cloudserver
202
203 ## Licensing
204
205 Copyright (c) 2020 SAP SE or an SAP affiliate company.
206
207 Licensed under the **Apache License, Version 2.0** (the "License"); you may not use this file except in compliance with the License.
208
209 You may obtain a copy of the License at <https://www.apache.org/licenses/LICENSE-2.0>.
210
211 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.
212
[end of README.md]
[start of /dev/null]
1
[end of /dev/null]
[start of THIRD-PARTY-NOTICES]
1 ThirdPartyNotices
2 -----------------
3 corona-warn-app/cwa-server uses third-party software or other resources that
4 may be distributed under licenses different from corona-warn-app/cwa-server
5 software.
6 In the event that we overlooked to list a required notice, please bring this
7 to our attention by contacting us via this email:
8 [email protected]
9
10
11 Components:
12 -----------
13 Component: Bouncy Castle
14 Licensor: Legion of the Bouncy Castle Inc.
15 Website: https://www.bouncycastle.org/
16 License: MIT License
17
18 Component: Commons IO
19 Licensor: Apache Software Foundation
20 Website: https://commons.apache.org/proper/commons-io/
21 License: Apache License 2.0
22
23 Component: Commons Math 3
24 Licensor: Apache Software Foundation
25 Website: https://commons.apache.org/proper/commons-math/
26 License: Apache License 2.0
27
28 Component: dom4j
29 Licensor: dom4j
30 Website: https://dom4j.github.io/
31 License: BSD License
32
33 Component: flyway
34 Licensor: flyway
35 Website: https://github.com/flyway/flyway
36 License: Apache License 2.0
37
38 Component: H2Database
39 Licensor: H2
40 Website: http://www.h2database.com/
41 License: Mozilla Public License 2.0
42
43 Component: JSON-Simple
44 Licensor: Yidong Fang
45 Website: https://github.com/fangyidong/json-simple
46 License: Apache License 2.0
47
48 Component: Maven
49 Licensor: Apache Software Foundation
50 Website: https://maven.apache.org/
51 License: Apache License 2.0
52
53 Component: MinIO Object Storage
54 Licensor: MinIO Inc.
55 Website: https://min.io/
56 License: Apache License 2.0
57
58 Component: MojoHaus Flatten Maven Plugin
59 Licensor: MojoHaus
60 Website: https://www.mojohaus.org/flatten-maven-plugin/
61 License: Apache License 2.0
62
63 Component: PostgreSQL
64 Licensor: PostgreSQL
65 Website: https://www.postgresql.org/
66 License: PostgreSQL License
67
68 Component: Protocol Buffers
69 Licensor: Google Inc.
70 Website: https://developers.google.com/protocol-buffers/
71 License: 3-Clause BSD License
72
73 Component: snakeyaml
74 Licensor: snakeyaml
75 Website: https://bitbucket.org/asomov/snakeyaml/
76 License: Apache License 2.0
77
78 Component: Spring Boot
79 Licensor: VMWare Inc.
80 Website: https://spring.io/
81 License: Apache License 2.0
82
83 Component: wait-for-it
84 Licensor: Giles Hall
85 Website: https://github.com/vishnubob/wait-for-it
86 License: MIT License
87
88 Component: Zenko CloudServer
89 Licensor: Zenko
90 Website: https://github.com/scality/cloudserver
91 License: Apache License 2.0
92
93 --------------------------------------------------------------------------------
94 Apache License 2.0 (Commons IO, Commons Math 3, flyway, JSON-Simple,
95 Maven, MinIO Object Storage, MojoHaus Flatten Maven Plugin, snakeyaml, Spring Boot, Zenko CloudServer)
96
97 Apache License
98 Version 2.0, January 2004
99 https://www.apache.org/licenses/
100
101 TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
102
103 1. Definitions.
104
105 "License" shall mean the terms and conditions for use, reproduction,
106 and distribution as defined by Sections 1 through 9 of this document.
107
108 "Licensor" shall mean the copyright owner or entity authorized by
109 the copyright owner that is granting the License.
110
111 "Legal Entity" shall mean the union of the acting entity and all
112 other entities that control, are controlled by, or are under common
113 control with that entity. For the purposes of this definition,
114 "control" means (i) the power, direct or indirect, to cause the
115 direction or management of such entity, whether by contract or
116 otherwise, or (ii) ownership of fifty percent (50%) or more of the
117 outstanding shares, or (iii) beneficial ownership of such entity.
118
119 "You" (or "Your") shall mean an individual or Legal Entity
120 exercising permissions granted by this License.
121
122 "Source" form shall mean the preferred form for making modifications,
123 including but not limited to software source code, documentation
124 source, and configuration files.
125
126 "Object" form shall mean any form resulting from mechanical
127 transformation or translation of a Source form, including but
128 not limited to compiled object code, generated documentation,
129 and conversions to other media types.
130
131 "Work" shall mean the work of authorship, whether in Source or
132 Object form, made available under the License, as indicated by a
133 copyright notice that is included in or attached to the work
134 (an example is provided in the Appendix below).
135
136 "Derivative Works" shall mean any work, whether in Source or Object
137 form, that is based on (or derived from) the Work and for which the
138 editorial revisions, annotations, elaborations, or other modifications
139 represent, as a whole, an original work of authorship. For the purposes
140 of this License, Derivative Works shall not include works that remain
141 separable from, or merely link (or bind by name) to the interfaces of,
142 the Work and Derivative Works thereof.
143
144 "Contribution" shall mean any work of authorship, including
145 the original version of the Work and any modifications or additions
146 to that Work or Derivative Works thereof, that is intentionally
147 submitted to Licensor for inclusion in the Work by the copyright owner
148 or by an individual or Legal Entity authorized to submit on behalf of
149 the copyright owner. For the purposes of this definition, "submitted"
150 means any form of electronic, verbal, or written communication sent
151 to the Licensor or its representatives, including but not limited to
152 communication on electronic mailing lists, source code control systems,
153 and issue tracking systems that are managed by, or on behalf of, the
154 Licensor for the purpose of discussing and improving the Work, but
155 excluding communication that is conspicuously marked or otherwise
156 designated in writing by the copyright owner as "Not a Contribution."
157
158 "Contributor" shall mean Licensor and any individual or Legal Entity
159 on behalf of whom a Contribution has been received by Licensor and
160 subsequently incorporated within the Work.
161
162 2. Grant of Copyright License. Subject to the terms and conditions of
163 this License, each Contributor hereby grants to You a perpetual,
164 worldwide, non-exclusive, no-charge, royalty-free, irrevocable
165 copyright license to reproduce, prepare Derivative Works of,
166 publicly display, publicly perform, sublicense, and distribute the
167 Work and such Derivative Works in Source or Object form.
168
169 3. Grant of Patent License. Subject to the terms and conditions of
170 this License, each Contributor hereby grants to You a perpetual,
171 worldwide, non-exclusive, no-charge, royalty-free, irrevocable
172 (except as stated in this section) patent license to make, have made,
173 use, offer to sell, sell, import, and otherwise transfer the Work,
174 where such license applies only to those patent claims licensable
175 by such Contributor that are necessarily infringed by their
176 Contribution(s) alone or by combination of their Contribution(s)
177 with the Work to which such Contribution(s) was submitted. If You
178 institute patent litigation against any entity (including a
179 cross-claim or counterclaim in a lawsuit) alleging that the Work
180 or a Contribution incorporated within the Work constitutes direct
181 or contributory patent infringement, then any patent licenses
182 granted to You under this License for that Work shall terminate
183 as of the date such litigation is filed.
184
185 4. Redistribution. You may reproduce and distribute copies of the
186 Work or Derivative Works thereof in any medium, with or without
187 modifications, and in Source or Object form, provided that You
188 meet the following conditions:
189
190 (a) You must give any other recipients of the Work or
191 Derivative Works a copy of this License; and
192
193 (b) You must cause any modified files to carry prominent notices
194 stating that You changed the files; and
195
196 (c) You must retain, in the Source form of any Derivative Works
197 that You distribute, all copyright, patent, trademark, and
198 attribution notices from the Source form of the Work,
199 excluding those notices that do not pertain to any part of
200 the Derivative Works; and
201
202 (d) If the Work includes a "NOTICE" text file as part of its
203 distribution, then any Derivative Works that You distribute must
204 include a readable copy of the attribution notices contained
205 within such NOTICE file, excluding those notices that do not
206 pertain to any part of the Derivative Works, in at least one
207 of the following places: within a NOTICE text file distributed
208 as part of the Derivative Works; within the Source form or
209 documentation, if provided along with the Derivative Works; or,
210 within a display generated by the Derivative Works, if and
211 wherever such third-party notices normally appear. The contents
212 of the NOTICE file are for informational purposes only and
213 do not modify the License. You may add Your own attribution
214 notices within Derivative Works that You distribute, alongside
215 or as an addendum to the NOTICE text from the Work, provided
216 that such additional attribution notices cannot be construed
217 as modifying the License.
218
219 You may add Your own copyright statement to Your modifications and
220 may provide additional or different license terms and conditions
221 for use, reproduction, or distribution of Your modifications, or
222 for any such Derivative Works as a whole, provided Your use,
223 reproduction, and distribution of the Work otherwise complies with
224 the conditions stated in this License.
225
226 5. Submission of Contributions. Unless You explicitly state otherwise,
227 any Contribution intentionally submitted for inclusion in the Work
228 by You to the Licensor shall be under the terms and conditions of
229 this License, without any additional terms or conditions.
230 Notwithstanding the above, nothing herein shall supersede or modify
231 the terms of any separate license agreement you may have executed
232 with Licensor regarding such Contributions.
233
234 6. Trademarks. This License does not grant permission to use the trade
235 names, trademarks, service marks, or product names of the Licensor,
236 except as required for reasonable and customary use in describing the
237 origin of the Work and reproducing the content of the NOTICE file.
238
239 7. Disclaimer of Warranty. Unless required by applicable law or
240 agreed to in writing, Licensor provides the Work (and each
241 Contributor provides its Contributions) on an "AS IS" BASIS,
242 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
243 implied, including, without limitation, any warranties or conditions
244 of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
245 PARTICULAR PURPOSE. You are solely responsible for determining the
246 appropriateness of using or redistributing the Work and assume any
247 risks associated with Your exercise of permissions under this License.
248
249 8. Limitation of Liability. In no event and under no legal theory,
250 whether in tort (including negligence), contract, or otherwise,
251 unless required by applicable law (such as deliberate and grossly
252 negligent acts) or agreed to in writing, shall any Contributor be
253 liable to You for damages, including any direct, indirect, special,
254 incidental, or consequential damages of any character arising as a
255 result of this License or out of the use or inability to use the
256 Work (including but not limited to damages for loss of goodwill,
257 work stoppage, computer failure or malfunction, or any and all
258 other commercial damages or losses), even if such Contributor
259 has been advised of the possibility of such damages.
260
261 9. Accepting Warranty or Additional Liability. While redistributing
262 the Work or Derivative Works thereof, You may choose to offer,
263 and charge a fee for, acceptance of support, warranty, indemnity,
264 or other liability obligations and/or rights consistent with this
265 License. However, in accepting such obligations, You may act only
266 on Your own behalf and on Your sole responsibility, not on behalf
267 of any other Contributor, and only if You agree to indemnify,
268 defend, and hold each Contributor harmless for any liability
269 incurred by, or claims asserted against, such Contributor by reason
270 of your accepting any such warranty or additional liability.
271
272 END OF TERMS AND CONDITIONS
273 --------------------------------------------------------------------------------
274 BSD License (dom4j)
275
276 Copyright 2001-2016 (C) MetaStuff, Ltd. and DOM4J contributors. All Rights Reserved.
277
278 Redistribution and use of this software and associated documentation
279 ("Software"), with or without modification, are permitted provided
280 that the following conditions are met:
281
282 1. Redistributions of source code must retain copyright
283 statements and notices. Redistributions must also contain a
284 copy of this document.
285
286 2. Redistributions in binary form must reproduce the
287 above copyright notice, this list of conditions and the
288 following disclaimer in the documentation and/or other
289 materials provided with the distribution.
290
291 3. The name "DOM4J" must not be used to endorse or promote
292 products derived from this Software without prior written
293 permission of MetaStuff, Ltd. For written permission,
294 please contact [email protected].
295
296 4. Products derived from this Software may not be called "DOM4J"
297 nor may "DOM4J" appear in their names without prior written
298 permission of MetaStuff, Ltd. DOM4J is a registered
299 trademark of MetaStuff, Ltd.
300
301 5. Due credit should be given to the DOM4J Project - https://dom4j.github.io/
302
303 THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS
304 ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT
305 NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
306 FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
307 METASTUFF, LTD. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
308 INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
309 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
310 SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
311 HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
312 STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
313 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
314 OF THE POSSIBILITY OF SUCH DAMAGE.
315 --------------------------------------------------------------------------------
316 3-Clause BSD License (Protocol Buffers)
317
318 Copyright 2008 Google Inc. All rights reserved.
319
320 Redistribution and use in source and binary forms, with or without
321 modification, are permitted provided that the following conditions are
322 met:
323
324 * Redistributions of source code must retain the above copyright
325 notice, this list of conditions and the following disclaimer.
326 * Redistributions in binary form must reproduce the above
327 copyright notice, this list of conditions and the following disclaimer
328 in the documentation and/or other materials provided with the
329 distribution.
330 * Neither the name of Google Inc. nor the names of its
331 contributors may be used to endorse or promote products derived from
332 this software without specific prior written permission.
333
334 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
335 "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
336 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
337 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
338 OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
339 SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
340 LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
341 DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
342 THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
343 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
344 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
345
346 Code generated by the Protocol Buffer compiler is owned by the owner
347 of the input file used when generating it. This code is not
348 standalone and requires a support library to be linked with it. This
349 support library is itself covered by the above license.
350 --------------------------------------------------------------------------------
351 PostgreSQL License (PostgreSQL)
352
353 PostgreSQL Database Management System
354 (formerly known as Postgres, then as Postgres95)
355
356 Portions Copyright © 1996-2020, The PostgreSQL Global Development Group
357
358 Portions Copyright © 1994, The Regents of the University of California
359
360 Permission to use, copy, modify, and distribute this software and its
361 documentation for any purpose, without fee, and without a written agreement is
362 hereby granted, provided that the above copyright notice and this paragraph and
363 the following two paragraphs appear in all copies.
364
365 IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
366 DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST
367 PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF
368 THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
369
370 THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
371 BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
372 PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND
373 THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,
374 UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
375 --------------------------------------------------------------------------------
376 Mozilla Public License 2.0 (H2Database)
377
378 Mozilla Public License
379 Version 2.0
380 1. Definitions
381 1.1. “Contributor”
382 means each individual or legal entity that creates, contributes to the creation
383 of, or owns Covered Software.
384
385 1.2. “Contributor Version”
386 means the combination of the Contributions of others (if any) used by a
387 Contributor and that particular Contributor’s Contribution.
388
389 1.3. “Contribution”
390 means Covered Software of a particular Contributor.
391
392 1.4. “Covered Software”
393 means Source Code Form to which the initial Contributor has attached the notice
394 in Exhibit A, the Executable Form of such Source Code Form, and Modifications
395 of such Source Code Form, in each case including portions thereof.
396
397 1.5. “Incompatible With Secondary Licenses”
398 means
399
400 that the initial Contributor has attached the notice described in Exhibit B to
401 the Covered Software; or
402
403 that the Covered Software was made available under the terms of version 1.1 or
404 earlier of the License, but not also under the terms of a Secondary License.
405
406 1.6. “Executable Form”
407 means any form of the work other than Source Code Form.
408
409 1.7. “Larger Work”
410 means a work that combines Covered Software with other material, in a separate
411 file or files, that is not Covered Software.
412
413 1.8. “License”
414 means this document.
415
416 1.9. “Licensable”
417 means having the right to grant, to the maximum extent possible, whether at the
418 time of the initial grant or subsequently, any and all of the rights conveyed
419 by this License.
420
421 1.10. “Modifications”
422 means any of the following:
423
424 any file in Source Code Form that results from an addition to, deletion from,
425 or modification of the contents of Covered Software; or
426
427 any new file in Source Code Form that contains any Covered Software.
428
429 1.11. “Patent Claims” of a Contributor
430 means any patent claim(s), including without limitation, method, process, and
431 apparatus claims, in any patent Licensable by such Contributor that would be
432 infringed, but for the grant of the License, by the making, using, selling,
433 offering for sale, having made, import, or transfer of either its Contributions
434 or its Contributor Version.
435
436 1.12. “Secondary License”
437 means either the GNU General Public License, Version 2.0, the GNU Lesser
438 General Public License, Version 2.1, the GNU Affero General Public License,
439 Version 3.0, or any later versions of those licenses.
440
441 1.13. “Source Code Form”
442 means the form of the work preferred for making modifications.
443
444 1.14. “You” (or “Your”)
445 means an individual or a legal entity exercising rights under this License. For
446 legal entities, “You” includes any entity that controls, is controlled by, or
447 is under common control with You. For purposes of this definition, “control”
448 means (a) the power, direct or indirect, to cause the direction or management
449 of such entity, whether by contract or otherwise, or (b) ownership of more than
450 fifty percent (50%) of the outstanding shares or beneficial ownership of such
451 entity.
452
453 2. License Grants and Conditions
454 2.1. Grants
455 Each Contributor hereby grants You a world-wide, royalty-free, non-exclusive
456 license:
457
458 under intellectual property rights (other than patent or trademark) Licensable
459 by such Contributor to use, reproduce, make available, modify, display,
460 perform, distribute, and otherwise exploit its Contributions, either on an
461 unmodified basis, with Modifications, or as part of a Larger Work; and
462
463 under Patent Claims of such Contributor to make, use, sell, offer for sale,
464 have made, import, and otherwise transfer either its Contributions or its
465 Contributor Version.
466
467 2.2. Effective Date
468 The licenses granted in Section 2.1 with respect to any Contribution become
469 effective for each Contribution on the date the Contributor first distributes
470 such Contribution.
471
472 2.3. Limitations on Grant Scope
473 The licenses granted in this Section 2 are the only rights granted under this
474 License. No additional rights or licenses will be implied from the distribution
475 or licensing of Covered Software under this License. Notwithstanding Section
476 2.1(b) above, no patent license is granted by a Contributor:
477
478 for any code that a Contributor has removed from Covered Software; or
479
480 for infringements caused by: (i) Your and any other third party’s modifications
481 of Covered Software, or (ii) the combination of its Contributions with other
482 software (except as part of its Contributor Version); or
483
484 under Patent Claims infringed by Covered Software in the absence of its
485 Contributions.
486
487 This License does not grant any rights in the trademarks, service marks, or
488 logos of any Contributor (except as may be necessary to comply with the notice
489 requirements in Section 3.4).
490
491 2.4. Subsequent Licenses
492 No Contributor makes additional grants as a result of Your choice to distribute
493 the Covered Software under a subsequent version of this License (see Section
494 10.2) or under the terms of a Secondary License (if permitted under the terms
495 of Section 3.3).
496
497 2.5. Representation
498 Each Contributor represents that the Contributor believes its Contributions are
499 its original creation(s) or it has sufficient rights to grant the rights to its
500 Contributions conveyed by this License.
501
502 2.6. Fair Use
503 This License is not intended to limit any rights You have under applicable
504 copyright doctrines of fair use, fair dealing, or other equivalents.
505
506 2.7. Conditions
507 Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in
508 Section 2.1.
509
510 3. Responsibilities
511 3.1. Distribution of Source Form
512 All distribution of Covered Software in Source Code Form, including any
513 Modifications that You create or to which You contribute, must be under the
514 terms of this License. You must inform recipients that the Source Code Form of
515 the Covered Software is governed by the terms of this License, and how they can
516 obtain a copy of this License. You may not attempt to alter or restrict the
517 recipients’ rights in the Source Code Form.
518
519 3.2. Distribution of Executable Form
520 If You distribute Covered Software in Executable Form then:
521
522 such Covered Software must also be made available in Source Code Form, as
523 described in Section 3.1, and You must inform recipients of the Executable Form
524 how they can obtain a copy of such Source Code Form by reasonable means in a
525 timely manner, at a charge no more than the cost of distribution to the
526 recipient; and
527
528 You may distribute such Executable Form under the terms of this License, or
529 sublicense it under different terms, provided that the license for the
530 Executable Form does not attempt to limit or alter the recipients’ rights in
531 the Source Code Form under this License.
532
533 3.3. Distribution of a Larger Work
534 You may create and distribute a Larger Work under terms of Your choice,
535 provided that You also comply with the requirements of this License for the
536 Covered Software. If the Larger Work is a combination of Covered Software with
537 a work governed by one or more Secondary Licenses, and the Covered Software is
538 not Incompatible With Secondary Licenses, this License permits You to
539 additionally distribute such Covered Software under the terms of such Secondary
540 License(s), so that the recipient of the Larger Work may, at their option,
541 further distribute the Covered Software under the terms of either this License
542 or such Secondary License(s).
543
544 3.4. Notices
545 You may not remove or alter the substance of any license notices (including
546 copyright notices, patent notices, disclaimers of warranty, or limitations of
547 liability) contained within the Source Code Form of the Covered Software,
548 except that You may alter any license notices to the extent required to remedy
549 known factual inaccuracies.
550
551 3.5. Application of Additional Terms
552 You may choose to offer, and to charge a fee for, warranty, support, indemnity
553 or liability obligations to one or more recipients of Covered Software.
554 However, You may do so only on Your own behalf, and not on behalf of any
555 Contributor. You must make it absolutely clear that any such warranty, support,
556 indemnity, or liability obligation is offered by You alone, and You hereby
557 agree to indemnify every Contributor for any liability incurred by such
558 Contributor as a result of warranty, support, indemnity or liability terms You
559 offer. You may include additional disclaimers of warranty and limitations of
560 liability specific to any jurisdiction.
561
562 4. Inability to Comply Due to Statute or Regulation
563 If it is impossible for You to comply with any of the terms of this License
564 with respect to some or all of the Covered Software due to statute, judicial
565 order, or regulation then You must: (a) comply with the terms of this License
566 to the maximum extent possible; and (b) describe the limitations and the code
567 they affect. Such description must be placed in a text file included with all
568 distributions of the Covered Software under this License. Except to the extent
569 prohibited by statute or regulation, such description must be sufficiently
570 detailed for a recipient of ordinary skill to be able to understand it.
571
572 5. Termination
573 5.1. The rights granted under this License will terminate automatically if You
574 fail to comply with any of its terms. However, if You become compliant, then
575 the rights granted under this License from a particular Contributor are
576 reinstated (a) provisionally, unless and until such Contributor explicitly and
577 finally terminates Your grants, and (b) on an ongoing basis, if such
578 Contributor fails to notify You of the non-compliance by some reasonable means
579 prior to 60 days after You have come back into compliance. Moreover, Your
580 grants from a particular Contributor are reinstated on an ongoing basis if such
581 Contributor notifies You of the non-compliance by some reasonable means, this
582 is the first time You have received notice of non-compliance with this License
583 from such Contributor, and You become compliant prior to 30 days after Your
584 receipt of the notice.
585
586 5.2. If You initiate litigation against any entity by asserting a patent
587 infringement claim (excluding declaratory judgment actions, counter-claims, and
588 cross-claims) alleging that a Contributor Version directly or indirectly
589 infringes any patent, then the rights granted to You by any and all
590 Contributors for the Covered Software under Section 2.1 of this License shall
591 terminate.
592
593 5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user
594 license agreements (excluding distributors and resellers) which have been
595 validly granted by You or Your distributors under this License prior to
596 termination shall survive termination.
597
598 6. Disclaimer of Warranty
599 Covered Software is provided under this License on an “as is” basis, without
600 warranty of any kind, either expressed, implied, or statutory, including,
601 without limitation, warranties that the Covered Software is free of defects,
602 merchantable, fit for a particular purpose or non-infringing. The entire risk
603 as to the quality and performance of the Covered Software is with You. Should
604 any Covered Software prove defective in any respect, You (not any Contributor)
605 assume the cost of any necessary servicing, repair, or correction. This
606 disclaimer of warranty constitutes an essential part of this License. No use of
607 any Covered Software is authorized under this License except under this
608 disclaimer.
609
610 7. Limitation of Liability
611 Under no circumstances and under no legal theory, whether tort (including
612 negligence), contract, or otherwise, shall any Contributor, or anyone who
613 distributes Covered Software as permitted above, be liable to You for any
614 direct, indirect, special, incidental, or consequential damages of any
615 character including, without limitation, damages for lost profits, loss of
616 goodwill, work stoppage, computer failure or malfunction, or any and all other
617 commercial damages or losses, even if such party shall have been informed of
618 the possibility of such damages. This limitation of liability shall not apply
619 to liability for death or personal injury resulting from such party’s
620 negligence to the extent applicable law prohibits such limitation. Some
621 jurisdictions do not allow the exclusion or limitation of incidental or
622 consequential damages, so this exclusion and limitation may not apply to You.
623
624 8. Litigation
625 Any litigation relating to this License may be brought only in the courts of a
626 jurisdiction where the defendant maintains its principal place of business and
627 such litigation shall be governed by laws of that jurisdiction, without
628 reference to its conflict-of-law provisions. Nothing in this Section shall
629 prevent a party’s ability to bring cross-claims or counter-claims.
630
631 9. Miscellaneous
632 This License represents the complete agreement concerning the subject matter
633 hereof. If any provision of this License is held to be unenforceable, such
634 provision shall be reformed only to the extent necessary to make it
635 enforceable. Any law or regulation which provides that the language of a
636 contract shall be construed against the drafter shall not be used to construe
637 this License against a Contributor.
638
639 10. Versions of the License
640 10.1. New Versions
641 Mozilla Foundation is the license steward. Except as provided in Section 10.3,
642 no one other than the license steward has the right to modify or publish new
643 versions of this License. Each version will be given a distinguishing version
644 number.
645
646 10.2. Effect of New Versions
647 You may distribute the Covered Software under the terms of the version of the
648 License under which You originally received the Covered Software, or under the
649 terms of any subsequent version published by the license steward.
650
651 10.3. Modified Versions
652 If you create software not governed by this License, and you want to create a
653 new license for such software, you may create and use a modified version of
654 this License if you rename the license and remove any references to the name of
655 the license steward (except to note that such modified license differs from
656 this License).
657
658 10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses
659 If You choose to distribute Source Code Form that is Incompatible With
660 Secondary Licenses under the terms of this version of the License, the notice
661 described in Exhibit B of this License must be attached.
662
663 Exhibit A - Source Code Form License Notice
664 This Source Code Form is subject to the terms of the Mozilla Public License, v.
665 2.0. If a copy of the MPL was not distributed with this file, You can obtain
666 one at https://mozilla.org/MPL/2.0/.
667
668 If it is not possible or desirable to put the notice in a particular file, then
669 You may include the notice in a location (such as a LICENSE file in a relevant
670 directory) where a recipient would be likely to look for such a notice.
671
672 You may add additional accurate notices of copyright ownership.
673
674 Exhibit B - “Incompatible With Secondary Licenses” Notice
675 This Source Code Form is “Incompatible With Secondary Licenses”, as defined by
676 the Mozilla Public License, v. 2.0.
677 --------------------------------------------------------------------------------
678 MIT License (BouncyCastle)
679
680 Copyright (c) 2000 - 2020 The Legion of the Bouncy Castle Inc.
681 (https://www.bouncycastle.org)
682
683 Permission is hereby granted, free of charge, to any person obtaining a copy of
684 this software and associated documentation files (the "Software"), to deal in
685 the Software without restriction, including without limitation the rights to
686 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
687 of the Software, and to permit persons to whom the Software is furnished to do
688 so, subject to the following conditions:
689
690 The above copyright notice and this permission notice shall be included in all
691 copies or substantial portions of the Software.
692
693 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
694 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
695 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
696 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
697 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
698 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
699 SOFTWARE.
700 --------------------------------------------------------------------------------
701 MIT License (wait-for-it)
702
703 Copyright (c) 2016 Giles Hall
704 (https://github.com/vishnubob/wait-for-it)
705
706 Permission is hereby granted, free of charge, to any person obtaining a copy of
707 this software and associated documentation files (the "Software"), to deal in
708 the Software without restriction, including without limitation the rights to
709 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
710 of the Software, and to permit persons to whom the Software is furnished to do
711 so, subject to the following conditions:
712
713 The above copyright notice and this permission notice shall be included in all
714 copies or substantial portions of the Software.
715
716 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
717 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
718 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
719 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
720 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
721 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
722 SOFTWARE.
723 --------------------------------------------------------------------------------
724
[end of THIRD-PARTY-NOTICES]
[start of services/submission/pom.xml]
1 <?xml version="1.0" encoding="UTF-8"?>
2 <project xmlns="http://maven.apache.org/POM/4.0.0"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
5 <parent>
6 <artifactId>services</artifactId>
7 <groupId>org.opencwa</groupId>
8 <version>${revision}</version>
9 <relativePath>../pom.xml</relativePath>
10 </parent>
11 <modelVersion>4.0.0</modelVersion>
12
13 <artifactId>submission</artifactId>
14
15 <properties>
16 <sonar.projectKey>corona-warn-app_cwa-server_services_submission</sonar.projectKey>
17 </properties>
18
19 <dependencies>
20 <dependency>
21 <groupId>org.springframework.boot</groupId>
22 <artifactId>spring-boot-starter-web</artifactId>
23 </dependency>
24 <dependency>
25 <groupId>org.springframework.boot</groupId>
26 <artifactId>spring-boot-starter-security</artifactId>
27 </dependency>
28 <dependency>
29 <groupId>org.springframework.security</groupId>
30 <artifactId>spring-security-test</artifactId>
31 <scope>test</scope>
32 </dependency>
33 <dependency>
34 <groupId>org.apache.commons</groupId>
35 <artifactId>commons-math3</artifactId>
36 <version>3.2</version>
37 <scope>compile</scope>
38 </dependency>
39 <dependency>
40 <groupId>org.springframework.boot</groupId>
41 <artifactId>spring-boot-starter-actuator</artifactId>
42 </dependency>
43 <dependency>
44 <groupId>io.micrometer</groupId>
45 <artifactId>micrometer-core</artifactId>
46 </dependency>
47 <dependency>
48 <groupId>io.micrometer</groupId>
49 <artifactId>micrometer-registry-prometheus</artifactId>
50 </dependency>
51 </dependencies>
52
53 <build>
54 <plugins>
55 <plugin>
56 <groupId>org.jacoco</groupId>
57 <artifactId>jacoco-maven-plugin</artifactId>
58 <version>0.8.5</version>
59 <executions>
60 <execution>
61 <goals>
62 <goal>prepare-agent</goal>
63 </goals>
64 </execution>
65 <execution>
66 <id>report</id>
67 <goals>
68 <goal>report</goal>
69 </goals>
70 <phase>verify</phase>
71 </execution>
72 </executions>
73 </plugin>
74 </plugins>
75 </build>
76
77 </project>
78
[end of services/submission/pom.xml]
[start of services/submission/src/main/java/app/coronawarn/server/services/submission/ServerApplication.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.submission;
22
23 import org.springframework.boot.SpringApplication;
24 import org.springframework.boot.autoconfigure.SpringBootApplication;
25 import org.springframework.boot.autoconfigure.domain.EntityScan;
26 import org.springframework.boot.context.properties.EnableConfigurationProperties;
27 import org.springframework.boot.web.servlet.ServletComponentScan;
28 import org.springframework.context.annotation.Bean;
29 import org.springframework.context.annotation.ComponentScan;
30 import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
31 import org.springframework.http.converter.protobuf.ProtobufHttpMessageConverter;
32
33 @SpringBootApplication
34 @ServletComponentScan
35 @EnableJpaRepositories(basePackages = "app.coronawarn.server.common.persistence")
36 @EntityScan(basePackages = "app.coronawarn.server.common.persistence")
37 @ComponentScan({"app.coronawarn.server.common.persistence",
38 "app.coronawarn.server.services.submission"})
39 @EnableConfigurationProperties
40 public class ServerApplication {
41
42 @Bean
43 ProtobufHttpMessageConverter protobufHttpMessageConverter() {
44 return new ProtobufHttpMessageConverter();
45 }
46
47 public static void main(String[] args) {
48 SpringApplication.run(ServerApplication.class, args);
49 }
50 }
51
[end of services/submission/src/main/java/app/coronawarn/server/services/submission/ServerApplication.java]
[start of services/submission/src/main/java/app/coronawarn/server/services/submission/verification/TanVerifier.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.submission.verification;
22
23 import app.coronawarn.server.services.submission.config.SubmissionServiceConfig;
24 import java.util.UUID;
25 import org.slf4j.Logger;
26 import org.slf4j.LoggerFactory;
27 import org.springframework.beans.factory.annotation.Autowired;
28 import org.springframework.boot.web.client.RestTemplateBuilder;
29 import org.springframework.http.HttpEntity;
30 import org.springframework.http.HttpHeaders;
31 import org.springframework.http.MediaType;
32 import org.springframework.http.ResponseEntity;
33 import org.springframework.stereotype.Service;
34 import org.springframework.web.client.HttpClientErrorException;
35 import org.springframework.web.client.RestClientException;
36 import org.springframework.web.client.RestTemplate;
37
38 /**
39 * The TanVerifier performs the verification of submission TANs.
40 */
41 @Service
42 public class TanVerifier {
43
44 private static final Logger logger = LoggerFactory.getLogger(TanVerifier.class);
45 private final String verificationServiceUrl;
46 private final RestTemplate restTemplate;
47 private final HttpHeaders requestHeader = new HttpHeaders();
48
49 /**
50 * This class can be used to verify a TAN against a configured verification service.
51 *
52 * @param submissionServiceConfig A submission service configuration
53 * @param restTemplateBuilder A rest template builder
54 */
55 @Autowired
56 public TanVerifier(SubmissionServiceConfig submissionServiceConfig, RestTemplateBuilder restTemplateBuilder) {
57 this.verificationServiceUrl = submissionServiceConfig.getVerificationBaseUrl()
58 + submissionServiceConfig.getVerificationPath();
59 this.restTemplate = restTemplateBuilder.build();
60 this.requestHeader.setContentType(MediaType.APPLICATION_JSON);
61 }
62
63 /**
64 * Verifies the specified TAN. Returns {@literal true} if the specified TAN is valid, {@literal false} otherwise.
65 *
66 * @param tan Submission Authorization TAN
67 * @return {@literal true} if the specified TAN is valid, {@literal false} otherwise.
68 * @throws RestClientException if status code is neither 2xx nor 4xx
69 */
70 public boolean verifyTan(String tan) {
71 String trimmedTan = tan.trim();
72
73 if (!checkTanSyntax(trimmedTan)) {
74 logger.debug("TAN Syntax check failed for TAN: {}", trimmedTan);
75 return false;
76 }
77
78 return verifyWithVerificationService(trimmedTan);
79 }
80
81 /**
82 * Verifies if the provided TAN can be parsed as a UUID.
83 *
84 * @param tan Submission Authorization TAN
85 * @return {@literal true} if tan can be parsed as a UUID, {@literal false} otherwise
86 */
87 private boolean checkTanSyntax(String tan) {
88 try {
89 UUID.fromString(tan);
90 return true;
91 } catch (IllegalArgumentException e) {
92 logger.debug("UUID creation failed for value: {}", tan, e);
93 return false;
94 }
95 }
96
97 /**
98 * Queries the configured verification service to validate the provided TAN.
99 *
100 * @param tan Submission Authorization TAN
101 * @return {@literal true} if verification service is able to verify the provided TAN, {@literal false} otherwise
102 * @throws RestClientException if http status code is neither 2xx nor 404
103 */
104 private boolean verifyWithVerificationService(String tan) {
105 String json = "{ \"tan\": \"" + tan + "\" }";
106 HttpEntity<String> entity = new HttpEntity<>(json, requestHeader);
107
108 try {
109 ResponseEntity<String> response = restTemplate.postForEntity(verificationServiceUrl, entity, String.class);
110 return response.getStatusCode().is2xxSuccessful();
111 } catch (HttpClientErrorException.NotFound e) {
112 // The verification service returns http status 404 if the TAN is invalid
113 logger.debug("TAN verification failed");
114 return false;
115 }
116 }
117 }
118
[end of services/submission/src/main/java/app/coronawarn/server/services/submission/verification/TanVerifier.java]
</code>
Here is an example of a patch file. It consists of changes to the code base. It specifies the file names, the line numbers of each change, and the removed and added lines. A single patch file can contain changes to multiple files.
<patch>
--- a/file.py
+++ b/file.py
@@ -1,27 +1,35 @@
def euclidean(a, b):
- while b:
- a, b = b, a % b
- return a
+ if b == 0:
+ return a
+ return euclidean(b, a % b)
def bresenham(x0, y0, x1, y1):
points = []
dx = abs(x1 - x0)
dy = abs(y1 - y0)
- sx = 1 if x0 < x1 else -1
- sy = 1 if y0 < y1 else -1
- err = dx - dy
+ x, y = x0, y0
+ sx = -1 if x0 > x1 else 1
+ sy = -1 if y0 > y1 else 1
- while True:
- points.append((x0, y0))
- if x0 == x1 and y0 == y1:
- break
- e2 = 2 * err
- if e2 > -dy:
+ if dx > dy:
+ err = dx / 2.0
+ while x != x1:
+ points.append((x, y))
err -= dy
- x0 += sx
- if e2 < dx:
- err += dx
- y0 += sy
+ if err < 0:
+ y += sy
+ err += dx
+ x += sx
+ else:
+ err = dy / 2.0
+ while y != y1:
+ points.append((x, y))
+ err -= dx
+ if err < 0:
+ x += sx
+ err += dy
+ y += sy
+ points.append((x, y))
return points
</patch>
I need you to solve the provded issue by generating a single patch file that I can apply directly to this repository using git apply. Please respond with a single patch file in the format shown above.
Respond below:
| corona-warn-app/cwa-server | db3d5faa1fe2702ef32ee0e3a965d0097c394df7 | Use typed client and entities for tan verification
## Current Implementation
The current tan verification look like this:
https://github.com/corona-warn-app/cwa-server/blob/3b98beb268bac511c00f8e13bcbb4978a8cdb4fd/services/submission/src/main/java/app/coronawarn/server/services/submission/verification/TanVerifier.java#L102-L115
There are a couple of issues I would see here:
1. The tan entity is build from a string which can cause bugs, encoding issues an more.
2. When the interface of the verification server changes (and this a repo owned by the same organization) this has to be modified as well and can cause runtime bugs without proper system testing
## Suggested Enhancement
I would suggest two things
1. Create a DTO (Pojo) for the tan payload and pass that to the rest template to let Jackson handle serialization
2. If a dependency between cwa projects is "allowed" (which I would think is perfectly fine) I would actually move that entity to the verification server project in a separate maven module. I would add [Spring Feign client ](https://cloud.spring.io/spring-cloud-netflix/multi/multi_spring-cloud-feign.html) and use that in the CWA server. Feign is like the reverse version of `@RestController` and supports the same annotations. It will create the client implementation from the given interface at runtime.
The client would look like this:
```
@FeignClient(name = "verification-server", url = "${services.submission.verification.baseUrl}")
public interface StoreClient {
@RequestMapping(method = RequestMethod.POST, value = "${services.submission.verification.path}", consumes = "application/json")
ValidationResult validateTan(Tan tan); // both classes should be Pojos
}
```
The usage would look like this (I did not actually implemented that!):
```
private boolean verifyWithVerificationService(String tanString) {
Tan tan = Tan.from(tanString); // This should also do the UUID verification!
ValidationResult result = verificationServer.validateTan(tan);
return result != null;
}
```
## Expected Benefits
- Compilation breaks when interface changes
- Less risk of bugs
| I like those suggestions. The introduction of a value object for a TAN is something I thought about suggesting as well. Would bind the verification logic into a value and make the using code more expressive and safe.
Although I am more of a hypermedia guy and thus not a big fan of hard coding URIs in clients, I think Feign would be fine here, although I think that – unless also used in other places – the benefit of using that over `RestTemplate`/`WebClient` is not that significant.
What I do think needs improvement is the setup of whatever client API is ended up being used. Remote calls definitely need a timeout as otherwise the system is stuck in case the downstream service is not answering at all for whatever reasons.
Also, from a security perspective this implementation shall be changed. When building the json string this way, a malicious tan can inject arbitrary fields to the json object. Even if the tan is previously checked for the correct syntax in another method, this implementation is error-prone. The syntax check for the tan can be called directly before creating the json string or the tan can be filtered with an whitelist approach.
I assume the previously mentioned changes will also tackle the injection issue.
I haven't really looked at the verification server but calling as POST to verify a TAN seems to me a bit unRESTy to be honest. But this is probably worth another issue...
> I haven't really looked at the verification server but calling as POST to verify a TAN seems to me a bit unRESTy to be honest. But this is probably worth another issue...
It actually explained in the documentation:
> The HTTP method POST is used instead of GET for added security, so data (e.g. the registration token or the TAN) can be transferred in the body.
However, I would still doubt that it's necessary.
Correct me if I'm wrong, but when doing backend-to-backend http call, the whole request - both URL params and and body - are within the same TCP packet. So as long as either:
- Both backends are within a secure environment or
- The use TLS
I don't think moving the tan to the body helps to improve security in any way.
This is probably only important when doing a frontend-to-backend call which is not the case here.
We have discussed and would like to proceed with the FeignClient, however, with the approach of keeping the java class entity on cwa-server, simply having one attribute 'tan'
> > I haven't really looked at the verification server but calling as POST to verify a TAN seems to me a bit unRESTy to be honest. But this is probably worth another issue...
>
> It actually explained in the documentation:
>
> > The HTTP method POST is used instead of GET for added security, so data (e.g. the registration token or the TAN) can be transferred in the body.
>
> However, I would still doubt that it's necessary.
>
> Correct me if I'm wrong, but when doing backend-to-backend http call, the whole request - both URL params and and body - are within the same TCP packet. So as long as either:
>
> * Both backends are within a secure environment or
> * The use TLS
> I don't think moving the tan to the body helps to improve security in any way.
>
> This is probably only important when doing a frontend-to-backend call which is not the case here.
The main reason to go with POST here (which transports the secret in the http body) is due to the sensitive nature of the TAN. We don't want the TAN to come up in any of our infrastructure / http access logs by chance.
This does not only apply to TANs but to all other sensitive data we are processing.
I'm working on a PR. | 2020-05-30T17:08:20 | <patch>
diff --git a/THIRD-PARTY-NOTICES b/THIRD-PARTY-NOTICES
--- a/THIRD-PARTY-NOTICES
+++ b/THIRD-PARTY-NOTICES
@@ -80,6 +80,11 @@ Licensor: VMWare Inc.
Website: https://spring.io/
License: Apache License 2.0
+Component: Spring Cloud
+Licensor: VMWare Inc.
+Website: https://spring.io/
+License: Apache License 2.0
+
Component: wait-for-it
Licensor: Giles Hall
Website: https://github.com/vishnubob/wait-for-it
@@ -90,9 +95,14 @@ Licensor: Zenko
Website: https://github.com/scality/cloudserver
License: Apache License 2.0
+Component: Wiremock
+Licensor: Tom Akehurst
+Website: http://wiremock.org/
+License: Apache License 2.0
+
--------------------------------------------------------------------------------
Apache License 2.0 (Commons IO, Commons Math 3, flyway, JSON-Simple,
-Maven, MinIO Object Storage, MojoHaus Flatten Maven Plugin, snakeyaml, Spring Boot, Zenko CloudServer)
+Maven, MinIO Object Storage, MojoHaus Flatten Maven Plugin, snakeyaml, Spring Boot, Spring Cloud, Zenko CloudServer, Wiremock)
Apache License
Version 2.0, January 2004
diff --git a/services/submission/pom.xml b/services/submission/pom.xml
--- a/services/submission/pom.xml
+++ b/services/submission/pom.xml
@@ -26,9 +26,9 @@
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
- <groupId>org.springframework.security</groupId>
- <artifactId>spring-security-test</artifactId>
- <scope>test</scope>
+ <groupId>org.springframework.cloud</groupId>
+ <artifactId>spring-cloud-starter-openfeign</artifactId>
+ <version>2.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
@@ -48,6 +48,18 @@
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
</dependency>
+ <dependency>
+ <groupId>org.springframework.security</groupId>
+ <artifactId>spring-security-test</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>com.github.tomakehurst</groupId>
+ <artifactId>wiremock-jre8</artifactId>
+ <version>2.26.3</version>
+ <scope>test</scope>
+ </dependency>
+
</dependencies>
<build>
diff --git a/services/submission/src/main/java/app/coronawarn/server/services/submission/ServerApplication.java b/services/submission/src/main/java/app/coronawarn/server/services/submission/ServerApplication.java
--- a/services/submission/src/main/java/app/coronawarn/server/services/submission/ServerApplication.java
+++ b/services/submission/src/main/java/app/coronawarn/server/services/submission/ServerApplication.java
@@ -25,6 +25,7 @@
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.ServletComponentScan;
+import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@@ -37,6 +38,7 @@
@ComponentScan({"app.coronawarn.server.common.persistence",
"app.coronawarn.server.services.submission"})
@EnableConfigurationProperties
+@EnableFeignClients
public class ServerApplication {
@Bean
diff --git a/services/submission/src/main/java/app/coronawarn/server/services/submission/verification/Tan.java b/services/submission/src/main/java/app/coronawarn/server/services/submission/verification/Tan.java
new file mode 100644
--- /dev/null
+++ b/services/submission/src/main/java/app/coronawarn/server/services/submission/verification/Tan.java
@@ -0,0 +1,82 @@
+/*-
+ * ---license-start
+ * Corona-Warn-App
+ * ---
+ * Copyright (C) 2020 SAP SE and all other contributors
+ * ---
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://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 for the specific language governing permissions and
+ * limitations under the License.
+ * ---license-end
+ */
+
+package app.coronawarn.server.services.submission.verification;
+
+import java.util.Objects;
+import java.util.UUID;
+
+/**
+ * A representation of a tan.
+ */
+class Tan {
+ private final UUID tan;
+
+ private Tan(UUID tan) {
+ this.tan = tan;
+ }
+
+ /**
+ * Creates a new {@link #Tan} instance for the given tan string.
+ *
+ * @param tanString A valid UUID string representation.
+ * @return The Tan instance
+ * @throws IllegalArgumentException when the given tan string is not a valid UUID.
+ */
+ public static Tan of(String tanString) {
+ UUID tan = UUID.fromString(tanString.trim());
+ return new Tan(tan);
+ }
+
+ /**
+ * Returns the tan entity as UUID.
+ * @return the tan.
+ */
+ public UUID getTan() {
+ return tan;
+ }
+
+ /**
+ * Returns the TAN in it's string representation.
+ *
+ * @return the tan UUID as a string.
+ */
+ @Override
+ public String toString() {
+ return tan.toString();
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ Tan tan1 = (Tan) o;
+ return tan.equals(tan1.tan);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(tan);
+ }
+}
diff --git a/services/submission/src/main/java/app/coronawarn/server/services/submission/verification/TanVerifier.java b/services/submission/src/main/java/app/coronawarn/server/services/submission/verification/TanVerifier.java
--- a/services/submission/src/main/java/app/coronawarn/server/services/submission/verification/TanVerifier.java
+++ b/services/submission/src/main/java/app/coronawarn/server/services/submission/verification/TanVerifier.java
@@ -20,20 +20,12 @@
package app.coronawarn.server.services.submission.verification;
-import app.coronawarn.server.services.submission.config.SubmissionServiceConfig;
-import java.util.UUID;
+import feign.FeignException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.boot.web.client.RestTemplateBuilder;
-import org.springframework.http.HttpEntity;
-import org.springframework.http.HttpHeaders;
-import org.springframework.http.MediaType;
-import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
-import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestClientException;
-import org.springframework.web.client.RestTemplate;
/**
* The TanVerifier performs the verification of submission TANs.
@@ -42,54 +34,32 @@
public class TanVerifier {
private static final Logger logger = LoggerFactory.getLogger(TanVerifier.class);
- private final String verificationServiceUrl;
- private final RestTemplate restTemplate;
- private final HttpHeaders requestHeader = new HttpHeaders();
+ private final VerificationServerClient verificationServerClient;
/**
* This class can be used to verify a TAN against a configured verification service.
*
- * @param submissionServiceConfig A submission service configuration
- * @param restTemplateBuilder A rest template builder
+ * @param verificationServerClient The REST client to communicate with the verification server
*/
@Autowired
- public TanVerifier(SubmissionServiceConfig submissionServiceConfig, RestTemplateBuilder restTemplateBuilder) {
- this.verificationServiceUrl = submissionServiceConfig.getVerificationBaseUrl()
- + submissionServiceConfig.getVerificationPath();
- this.restTemplate = restTemplateBuilder.build();
- this.requestHeader.setContentType(MediaType.APPLICATION_JSON);
+ public TanVerifier(VerificationServerClient verificationServerClient) {
+ this.verificationServerClient = verificationServerClient;
}
/**
* Verifies the specified TAN. Returns {@literal true} if the specified TAN is valid, {@literal false} otherwise.
*
- * @param tan Submission Authorization TAN
+ * @param tanString Submission Authorization TAN
* @return {@literal true} if the specified TAN is valid, {@literal false} otherwise.
* @throws RestClientException if status code is neither 2xx nor 4xx
*/
- public boolean verifyTan(String tan) {
- String trimmedTan = tan.trim();
-
- if (!checkTanSyntax(trimmedTan)) {
- logger.debug("TAN Syntax check failed for TAN: {}", trimmedTan);
- return false;
- }
-
- return verifyWithVerificationService(trimmedTan);
- }
-
- /**
- * Verifies if the provided TAN can be parsed as a UUID.
- *
- * @param tan Submission Authorization TAN
- * @return {@literal true} if tan can be parsed as a UUID, {@literal false} otherwise
- */
- private boolean checkTanSyntax(String tan) {
+ public boolean verifyTan(String tanString) {
try {
- UUID.fromString(tan);
- return true;
+ Tan tan = Tan.of(tanString);
+
+ return verifyWithVerificationService(tan);
} catch (IllegalArgumentException e) {
- logger.debug("UUID creation failed for value: {}", tan, e);
+ logger.debug("TAN Syntax check failed for TAN: {}", tanString.trim());
return false;
}
}
@@ -101,16 +71,11 @@ private boolean checkTanSyntax(String tan) {
* @return {@literal true} if verification service is able to verify the provided TAN, {@literal false} otherwise
* @throws RestClientException if http status code is neither 2xx nor 404
*/
- private boolean verifyWithVerificationService(String tan) {
- String json = "{ \"tan\": \"" + tan + "\" }";
- HttpEntity<String> entity = new HttpEntity<>(json, requestHeader);
-
+ private boolean verifyWithVerificationService(Tan tan) {
try {
- ResponseEntity<String> response = restTemplate.postForEntity(verificationServiceUrl, entity, String.class);
- return response.getStatusCode().is2xxSuccessful();
- } catch (HttpClientErrorException.NotFound e) {
- // The verification service returns http status 404 if the TAN is invalid
- logger.debug("TAN verification failed");
+ verificationServerClient.verifyTan(tan);
+ return true;
+ } catch (FeignException.NotFound e) {
return false;
}
}
diff --git a/services/submission/src/main/java/app/coronawarn/server/services/submission/verification/VerificationServerClient.java b/services/submission/src/main/java/app/coronawarn/server/services/submission/verification/VerificationServerClient.java
new file mode 100644
--- /dev/null
+++ b/services/submission/src/main/java/app/coronawarn/server/services/submission/verification/VerificationServerClient.java
@@ -0,0 +1,42 @@
+/*-
+ * ---license-start
+ * Corona-Warn-App
+ * ---
+ * Copyright (C) 2020 SAP SE and all other contributors
+ * ---
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://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 for the specific language governing permissions and
+ * limitations under the License.
+ * ---license-end
+ */
+
+package app.coronawarn.server.services.submission.verification;
+
+import org.springframework.cloud.openfeign.FeignClient;
+import org.springframework.http.MediaType;
+import org.springframework.web.bind.annotation.PostMapping;
+
+/**
+ * This is a Spring Cloud Feign based HTTP client that allows type-safe HTTP calls
+ * and abstract the implementation away.
+ */
+@FeignClient(name = "verification-server", url = "${services.submission.verification.base-url}")
+public interface VerificationServerClient {
+
+ /**
+ * This methods calls the verification service with the given
+ * {#link tan}.
+ * @param tan the tan to verify.
+ * @return 404 when the tan is not valid.
+ */
+ @PostMapping(value = "${services.submission.verification.path}", consumes = MediaType.APPLICATION_JSON_VALUE)
+ String verifyTan(Tan tan);
+}
</patch> | diff --git a/services/submission/src/test/java/app/coronawarn/server/services/submission/verification/FeignTestConfiguration.java b/services/submission/src/test/java/app/coronawarn/server/services/submission/verification/FeignTestConfiguration.java
new file mode 100644
--- /dev/null
+++ b/services/submission/src/test/java/app/coronawarn/server/services/submission/verification/FeignTestConfiguration.java
@@ -0,0 +1,35 @@
+/*-
+ * ---license-start
+ * Corona-Warn-App
+ * ---
+ * Copyright (C) 2020 SAP SE and all other contributors
+ * ---
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://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 for the specific language governing permissions and
+ * limitations under the License.
+ * ---license-end
+ */
+
+package app.coronawarn.server.services.submission.verification;
+
+import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
+import org.springframework.boot.test.context.TestConfiguration;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Profile;
+
+@TestConfiguration
+@Profile("feign")
+public class FeignTestConfiguration {
+ @Bean
+ public HttpMessageConverters httpMessageConverters() {
+ return new HttpMessageConverters();
+ }
+}
diff --git a/services/submission/src/test/java/app/coronawarn/server/services/submission/verification/TanTest.java b/services/submission/src/test/java/app/coronawarn/server/services/submission/verification/TanTest.java
new file mode 100644
--- /dev/null
+++ b/services/submission/src/test/java/app/coronawarn/server/services/submission/verification/TanTest.java
@@ -0,0 +1,49 @@
+/*-
+ * ---license-start
+ * Corona-Warn-App
+ * ---
+ * Copyright (C) 2020 SAP SE and all other contributors
+ * ---
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://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 for the specific language governing permissions and
+ * limitations under the License.
+ * ---license-end
+ */
+
+package app.coronawarn.server.services.submission.verification;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import java.util.UUID;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+class TanTest {
+ @ParameterizedTest
+ @ValueSource(strings = {
+ "ANY SYNTAX", "123456", "ABCD23X", "ZZZZZZZ", "Bearer 3123fe", "", "&%$§&%&$%/%&",
+ "LOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOONG"
+ })
+ void invalidTanShouldThrowException(String invalidSyntaxTan) {
+ assertThatThrownBy(() -> Tan.of(invalidSyntaxTan)).isInstanceOf(IllegalArgumentException.class);
+ }
+
+ @Test
+ void validTanShouldReturnTanInstance() {
+ String tanString = UUID.randomUUID().toString();
+ Tan tan = Tan.of(tanString);
+
+ assertThat(tan).isNotNull();
+ assertThat(tan.toString()).isEqualTo(tanString);
+ }
+}
diff --git a/services/submission/src/test/java/app/coronawarn/server/services/submission/verification/TanVerifierTest.java b/services/submission/src/test/java/app/coronawarn/server/services/submission/verification/TanVerifierTest.java
--- a/services/submission/src/test/java/app/coronawarn/server/services/submission/verification/TanVerifierTest.java
+++ b/services/submission/src/test/java/app/coronawarn/server/services/submission/verification/TanVerifierTest.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://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.
@@ -21,87 +21,99 @@
package app.coronawarn.server.services.submission.verification;
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
-import static org.springframework.test.web.client.match.MockRestRequestMatchers.method;
-import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
-import static org.springframework.test.web.client.response.MockRestResponseCreators.withStatus;
-
import app.coronawarn.server.services.submission.config.SubmissionServiceConfig;
-import java.util.UUID;
+import com.github.tomakehurst.wiremock.WireMockServer;
+import feign.FeignException;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
-import org.junit.jupiter.params.ParameterizedTest;
-import org.junit.jupiter.params.provider.ValueSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
-import org.springframework.boot.test.autoconfigure.web.client.RestClientTest;
-import org.springframework.boot.test.context.ConfigFileApplicationContextInitializer;
-import org.springframework.http.HttpMethod;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.cloud.openfeign.EnableFeignClients;
+import org.springframework.cloud.openfeign.FeignAutoConfiguration;
+import org.springframework.context.annotation.Import;
import org.springframework.http.HttpStatus;
-import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.web.client.ExpectedCount;
-import org.springframework.test.web.client.MockRestServiceServer;
-import org.springframework.web.client.HttpServerErrorException;
+import org.springframework.http.MediaType;
+import org.springframework.test.context.ActiveProfiles;
-@EnableConfigurationProperties(value = SubmissionServiceConfig.class)
-@ContextConfiguration(classes = {TanVerifier.class},
- initializers = ConfigFileApplicationContextInitializer.class)
-@RestClientTest
-class TanVerifierTest {
+import java.util.UUID;
- @Autowired
- private MockRestServiceServer server;
+import static com.github.tomakehurst.wiremock.client.WireMock.*;
+import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
+import static org.springframework.http.HttpHeaders.CONTENT_TYPE;
+@SpringBootTest(
+ classes = {FeignAutoConfiguration.class, TanVerifier.class})
+@EnableConfigurationProperties(value = SubmissionServiceConfig.class)
+@EnableFeignClients
+@Import(FeignTestConfiguration.class)
+@ActiveProfiles("feign")
+class TanVerifierTest {
@Autowired
private TanVerifier tanVerifier;
@Autowired
private SubmissionServiceConfig submissionServiceConfig;
- private String verificationUrl;
+ private String verificationPath;
private String randomUUID;
+ private static WireMockServer server;
+
+ @BeforeAll
+ static void setupWireMock() {
+ server = new WireMockServer(options().port(1234));
+ server.start();
+ }
@BeforeEach
void setup() {
- this.verificationUrl = submissionServiceConfig.getVerificationBaseUrl()
- + submissionServiceConfig.getVerificationPath();
+ this.verificationPath = submissionServiceConfig.getVerificationPath();
this.randomUUID = UUID.randomUUID().toString();
+ server.resetAll();
}
- @ParameterizedTest
- @ValueSource(strings = {
- "ANY SYNTAX", "123456", "ABCD23X", "ZZZZZZZ", "Bearer 3123fe", "", "&%$§&%&$%/%&",
- "LOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOONG"
- })
- void checkWrongTanSyntax(String invalidSyntaxTan) {
- assertThat(tanVerifier.verifyTan(invalidSyntaxTan)).isFalse();
+ @AfterAll
+ static void tearDown() {
+ server.stop();
}
@Test
void checkValidTan() {
- this.server
- .expect(ExpectedCount.once(), requestTo(verificationUrl))
- .andExpect(method(HttpMethod.POST))
- .andRespond(withStatus(HttpStatus.OK));
- assertThat(tanVerifier.verifyTan(randomUUID)).isTrue();
+ server.stubFor(
+ post(urlEqualTo(verificationPath))
+ .withRequestBody(matchingJsonPath("tan", equalTo(randomUUID)))
+ .withHeader(CONTENT_TYPE, equalTo(MediaType.APPLICATION_JSON.toString()))
+ .willReturn(aResponse().withStatus(HttpStatus.OK.value())));
+
+ boolean tanVerificationResponse = tanVerifier.verifyTan(randomUUID);
+
+ assertThat(tanVerificationResponse).isTrue();
}
@Test
void checkInvalidTan() {
- this.server
- .expect(ExpectedCount.once(), requestTo(verificationUrl))
- .andExpect(method(HttpMethod.POST))
- .andRespond(withStatus(HttpStatus.NOT_FOUND));
- assertThat(tanVerifier.verifyTan(randomUUID)).isFalse();
+ server.stubFor(
+ post(urlEqualTo(verificationPath))
+ .withHeader(CONTENT_TYPE, equalTo(MediaType.APPLICATION_JSON.toString()))
+ .willReturn(aResponse().withStatus(HttpStatus.NOT_FOUND.value())));
+
+ boolean tanVerificationResponse = tanVerifier.verifyTan(randomUUID);
+
+ assertThat(tanVerificationResponse).isFalse();
}
@Test
void checkInternalServerError() {
- this.server
- .expect(ExpectedCount.once(), requestTo(verificationUrl))
- .andExpect(method(HttpMethod.POST))
- .andRespond(withStatus(HttpStatus.INTERNAL_SERVER_ERROR));
- assertThatExceptionOfType(HttpServerErrorException.class).isThrownBy(() -> tanVerifier.verifyTan(randomUUID));
+ server.stubFor(
+ post(urlEqualTo(verificationPath))
+ .withHeader(CONTENT_TYPE, equalTo(MediaType.APPLICATION_JSON.toString()))
+ .willReturn(aResponse().withStatus(HttpStatus.INTERNAL_SERVER_ERROR.value())));
+
+ assertThatExceptionOfType(FeignException.class).isThrownBy(() -> tanVerifier.verifyTan(randomUUID));
}
+
}
diff --git a/services/submission/src/test/resources/application.yaml b/services/submission/src/test/resources/application.yaml
--- a/services/submission/src/test/resources/application.yaml
+++ b/services/submission/src/test/resources/application.yaml
@@ -30,5 +30,5 @@ services:
payload:
max-number-of-keys: 14
verification:
- base-url: http://verificationService:1234
+ base-url: http://localhost:1234
path: /version/v1/tan/verify
| ||||
corona-warn-app__cwa-server-260 | You will be provided with a partial code base and an issue statement explaining a problem to resolve.
<issue>
Exposure configuration parameters not validated
The exposure configuration parameters are currently not validated after being read from the respective yml file. The validation code in ``ExposureConfigurationValidator`` is currently used in tests only.
However, the expected behavior shall be the following:
- The ``RiskScoreParameters`` object is constructed based on yml file. (✅)
- ``ExposureConfigurationValidator`` performs validation of the parameters.
- In case of a failed validation, **do not** publish the exposure configuration parameters, **but do** generate and publish the diagnosis key bundles.
- Clarify whether to keep any previously present (valid) configuration parameters on the object store if a validation error occurs.
- Any validation errors shall be logged appropriately.
</issue>
<code>
[start of README.md]
1 <h1 align="center">
2 Corona-Warn-App Server
3 </h1>
4
5 <p align="center">
6 <a href="https://github.com/corona-warn-app/cwa-server/commits/" title="Last Commit"><img src="https://img.shields.io/github/last-commit/corona-warn-app/cwa-server?style=flat"></a>
7 <a href="https://github.com/corona-warn-app/cwa-server/issues" title="Open Issues"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat"></a>
8 <a href="https://circleci.com/gh/corona-warn-app/cwa-server" title="Build Status"><img src="https://circleci.com/gh/corona-warn-app/cwa-server.svg?style=shield&circle-token=4ab059989d10709df19eb4b98ab7c121a25e981a"></a>
9 <a href="https://sonarcloud.io/dashboard?id=corona-warn-app_cwa-server" title="Quality Gate"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=alert_status"></a>
10 <a href="https://sonarcloud.io/component_measures?id=corona-warn-app_cwa-server&metric=Coverage&view=list" title="Coverage"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=coverage"></a>
11 <a href="https://github.com/corona-warn-app/cwa-server/blob/master/LICENSE" title="License"><img src="https://img.shields.io/badge/License-Apache%202.0-green.svg?style=flat"></a>
12 </p>
13
14 <p align="center">
15 <a href="#development">Development</a> •
16 <a href="#service-apis">Service APIs</a> •
17 <a href="#documentation">Documentation</a> •
18 <a href="#support-and-feedback">Support</a> •
19 <a href="#how-to-contribute">Contribute</a> •
20 <a href="#contributors">Contributors</a> •
21 <a href="#repositories">Repositories</a> •
22 <a href="#licensing">Licensing</a>
23 </p>
24
25 The goal of this project is to develop the official Corona-Warn-App for Germany based on the exposure notification API from [Apple](https://www.apple.com/covid19/contacttracing/) and [Google](https://www.google.com/covid19/exposurenotifications/). The apps (for both iOS and Android) use Bluetooth technology to exchange anonymous encrypted data with other mobile phones (on which the app is also installed) in the vicinity of an app user's phone. The data is stored locally on each user's device, preventing authorities or other parties from accessing or controlling the data. This repository contains the **implementation of the server for encryption keys** for the Corona-Warn-App. This implementation is still a **work in progress**, and the code it contains is currently alpha-quality code.
26
27 In this documentation, Corona-Warn-App services are also referred to as CWA services.
28
29 ## Architecture Overview
30
31 You can find the architecture overview [here](/docs/architecture-overview.md), which will give you
32 a good starting point in how the backend services interact with other services, and what purpose
33 they serve.
34
35 ## Development
36
37 After you've checked out this repository, you can run the application in one of the following ways:
38
39 * As a [Docker](https://www.docker.com/)-based deployment on your local machine. You can run either:
40 * Single components using the respective Dockerfile or
41 * The full backend using the Docker Compose (which is considered the most convenient way)
42 * As a [Maven](https://maven.apache.org)-based build on your local machine.
43 If you want to develop something in a single component, this approach is preferable.
44
45 ### Docker-Based Deployment
46
47 If you want to use Docker-based deployment, you need to install Docker on your local machine. For more information about downloading and installing Docker, see the [official Docker documentation](https://docs.docker.com/get-docker/).
48
49 #### Running the Full CWA Backend Using Docker Compose
50
51 For your convenience, a full setup including the generation of test data has been prepared using [Docker Compose](https://docs.docker.com/compose/reference/overview/). To build the backend services, run ```docker-compose build``` in the repository's root directory. A default configuration file can be found under ```.env```in the root folder of the repository. The default values for the local Postgres and Zenko Cloudserver should be changed in this file before docker-compose is run.
52
53 Once the services are built, you can start the whole backend using ```docker-compose up```.
54 The distribution service runs once and then finishes. If you want to trigger additional distribution runs, run ```docker-compose run distribution```.
55
56 The docker-compose contains the following services:
57
58 Service | Description | Endpoint and Default Credentials
59 --------------|-------------|-----------
60 submission | The Corona-Warn-App submission service | http://localhost:8000
61 distribution | The Corona-Warn-App distribution service | NO ENDPOINT
62 postgres | A [postgres] database installation | postgres:8001 <br> Username: postgres <br> Password: postgres
63 pgadmin | A [pgadmin](https://www.pgadmin.org/) installation for the postgres database | http://localhost:8002 <br> Username: [email protected] <br> Password: password
64 cloudserver | [Zenko CloudServer] is a S3-compliant object store | http://localhost:8003/ <br> Access key: accessKey1 <br> Secret key: verySecretKey1
65
66 ##### Known Limitation
67
68 The docker-compose runs into a timing issue in some cases when the create-bucket target runs before the objectstore is available. The mitigation is easy: after running ```docker-compose up``` wait until all components are initialized and running. Afterwards, trigger the ```create-bucket``` service manually by running ```docker-compose run create-bucket```. If you want to trigger distribution runs, run ```docker-compose run distribution```. The timing issue will be fixed in a future release.
69
70 #### Running Single CWA Services Using Docker
71
72 If you would like to build and run a single CWA service, it's considered easiest to run them in a Docker environment. You can do this using the script provided in the respective CWA service directory. The Docker script first builds the CWA service and then creates an image for the runtime, which means that there are no additional dependencies for you to install.
73
74 To build and run the distribution service, run the following command:
75
76 ```bash
77 ./services/distribution/build_and_run.sh
78 ```
79
80 To build and run the submission service, run the following command:
81
82 ```bash
83 ./services/submission/build_and_run.sh
84 ```
85
86 The submission service is available on [localhost:8080](http://localhost:8080 ).
87
88 ### Maven-Based Build
89
90 If you want to actively develop in one of the CWA services, the Maven-based runtime is most suitable.
91 To prepare your machine to run the CWA project locally, we recommend that you first ensure that you've installed the following:
92
93 * Minimum JDK Version 11: [OpenJDK](https://openjdk.java.net/) / [SapMachine](https://sap.github.io/SapMachine/)
94 * [Maven 3.6](https://maven.apache.org/)
95 * [Postgres]
96 * [Zenko CloudServer]
97
98 #### Configure
99
100 After you made sure that the specified dependencies are running, configure them in the respective configuration files.
101
102 * Configure the Postgres connection in the [submission config](./services/submission/src/main/resources/application.properties) and in the [distribution config](./services/distribution/src/main/resources/application.properties)
103 * Configure the S3 compatible object storage in the [distribution config](./services/distribution/src/main/resources/application.properties)
104 * Configure the certificate and private key for the distribution service, the paths need to be prefixed with `file:`
105 * `VAULT_FILESIGNING_SECRET` should be the path to the private key, example available in `<repo-root>/docker-compose-test-secrets/private.pem`
106 * `VAULT_FILESIGNING_CERT` should be the path to the certificate, example available in `<repo-root>/docker-compose-test-secrets/certificate.cert`
107
108 #### Build
109
110 After you've checked out the repository, to build the project, run ```mvn install``` in your base directory.
111
112 #### Run
113
114 Navigate to the service you want to start and run the spring-boot:run target. The configured Postgres and the configured S3 compliant object storage are used as default. When you start the submission service, the endpoint is available on your local port 8080.
115
116 If you want to start the submission service, for example, you start it as follows:
117
118 ```bash
119 cd services/submission/
120 mvn spring-boot:run
121 ```
122
123 #### Debugging
124
125 To enable the `DEBUG` log level, you can run the application using the Spring `dev` profile.
126
127 ```bash
128 mvn spring-boot:run -Dspring-boot.run.profiles=dev
129 ```
130
131 To be able to set breakpoints (e.g. in IntelliJ), it may be necessary to use the ```-Dspring-boot.run.fork=false``` parameter.
132
133 ## Service APIs
134
135 The API that is being exposed by the backend services is documented in an [OpenAPI](https://www.openapis.org/) specification. The specification files are available at the following locations:
136
137 Service | OpenAPI Specification
138 -------------|-------------
139 Submission Service | https://github.com/corona-warn-app/cwa-server/raw/master/services/submission/api_v1.json
140 Distribution Service | https://github.com/corona-warn-app/cwa-server/raw/master/services/distribution/api_v1.json
141
142 ## Documentation
143
144 The full documentation for the Corona-Warn-App can be found in the [cwa-documentation](https://github.com/corona-warn-app/cwa-documentation) repository. The documentation repository contains technical documents, architecture information, and whitepapers related to this implementation.
145
146 ## Support and Feedback
147
148 The following channels are available for discussions, feedback, and support requests:
149
150 | Type | Channel |
151 | ------------------------ | ------------------------------------------------------ |
152 | **General Discussion** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="General Discussion"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/question.svg?style=flat-square"></a> </a> |
153 | **Concept Feedback** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="Open Concept Feedback"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/architecture.svg?style=flat-square"></a> |
154 | **Backend Issue** | <a href="https://github.com/corona-warn-app/cwa-server/issues/new/choose" title="Open Backend Issue"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat-square"></a> |
155 | **Other Requests** | <a href="mailto:[email protected]" title="Email CWA Team"><img src="https://img.shields.io/badge/email-CWA%20team-green?logo=mail.ru&style=flat-square&logoColor=white"></a> |
156
157 ## How to Contribute
158
159 Contribution and feedback are 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.
160
161 ## Contributors
162
163 The German government has asked SAP and Deutsche Telekom to develop the Corona-Warn-App for Germany as open source software. Deutsche Telekom is providing the network and mobile technology and will operate and run the backend for the app in a safe, scalable and stable manner. SAP is responsible for the app development, its framework and the underlying platform. Therefore, development teams of SAP and Deutsche Telekom are contributing to this project. At the same time 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.
164
165 ## Repositories
166
167 The following public repositories are currently available for the Corona-Warn-App:
168
169 | Repository | Description |
170 | ------------------- | --------------------------------------------------------------------- |
171 | [cwa-documentation] | Project overview, general documentation, and white papers |
172 | [cwa-server] | Backend implementation for the Apple/Google exposure notification API|
173
174 [cwa-documentation]: https://github.com/corona-warn-app/cwa-documentation
175 [cwa-server]: https://github.com/corona-warn-app/cwa-server
176 [Postgres]: https://www.postgresql.org/
177 [HSQLDB]: http://hsqldb.org/
178 [Zenko CloudServer]: https://github.com/scality/cloudserver
179
180 ## Licensing
181
182 Copyright (c) 2020 SAP SE or an SAP affiliate company.
183
184 Licensed under the **Apache License, Version 2.0** (the "License"); you may not use this file except in compliance with the License.
185
186 You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0.
187
188 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.
189
[end of README.md]
[start of /dev/null]
1
[end of /dev/null]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/component/CwaApiStructureProvider.java]
1 /*
2 * Corona-Warn-App
3 *
4 * SAP SE and all other contributors /
5 * copyright owners license this file to you under the Apache
6 * License, Version 2.0 (the "License"); you may not use this
7 * file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20 package app.coronawarn.server.services.distribution.assembly.component;
21
22 import app.coronawarn.server.services.distribution.assembly.structure.WritableOnDisk;
23 import app.coronawarn.server.services.distribution.assembly.structure.directory.Directory;
24 import app.coronawarn.server.services.distribution.assembly.structure.directory.IndexDirectoryOnDisk;
25 import app.coronawarn.server.services.distribution.assembly.structure.directory.decorator.indexing.IndexingDecoratorOnDisk;
26 import java.util.Set;
27 import org.springframework.beans.factory.annotation.Autowired;
28 import org.springframework.stereotype.Component;
29
30 /**
31 * Assembles the content underneath the {@code /version} path of the CWA API.
32 */
33 @Component
34 public class CwaApiStructureProvider {
35
36 public static final String VERSION_DIRECTORY = "version";
37 public static final String VERSION_V1 = "v1";
38
39 private final ExposureConfigurationStructureProvider exposureConfigurationStructureProvider;
40
41 private final DiagnosisKeysStructureProvider diagnosisKeysStructureProvider;
42
43 @Autowired
44 public CwaApiStructureProvider(
45 ExposureConfigurationStructureProvider exposureConfigurationStructureProvider,
46 DiagnosisKeysStructureProvider diagnosisKeysStructureProvider) {
47 this.exposureConfigurationStructureProvider = exposureConfigurationStructureProvider;
48 this.diagnosisKeysStructureProvider = diagnosisKeysStructureProvider;
49 }
50
51 /**
52 * Returns the base directory.
53 */
54 public Directory<WritableOnDisk> getDirectory() {
55 IndexDirectoryOnDisk<String> versionDirectory =
56 new IndexDirectoryOnDisk<>(VERSION_DIRECTORY, __ -> Set.of(VERSION_V1), Object::toString);
57
58 versionDirectory
59 .addWritableToAll(__ -> exposureConfigurationStructureProvider.getExposureConfiguration());
60 versionDirectory.addWritableToAll(__ -> diagnosisKeysStructureProvider.getDiagnosisKeys());
61
62 return new IndexingDecoratorOnDisk<>(versionDirectory);
63 }
64 }
65
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/component/CwaApiStructureProvider.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/component/ExposureConfigurationStructureProvider.java]
1 /*
2 * Corona-Warn-App
3 *
4 * SAP SE and all other contributors /
5 * copyright owners license this file to you under the Apache
6 * License, Version 2.0 (the "License"); you may not use this
7 * file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20 package app.coronawarn.server.services.distribution.assembly.component;
21
22 import app.coronawarn.server.common.protocols.internal.RiskScoreParameters;
23 import app.coronawarn.server.services.distribution.assembly.exposureconfig.ExposureConfigurationProvider;
24 import app.coronawarn.server.services.distribution.assembly.exposureconfig.UnableToLoadFileException;
25 import app.coronawarn.server.services.distribution.assembly.exposureconfig.structure.directory.ExposureConfigurationDirectory;
26 import app.coronawarn.server.services.distribution.assembly.structure.WritableOnDisk;
27 import app.coronawarn.server.services.distribution.assembly.structure.directory.Directory;
28 import org.slf4j.Logger;
29 import org.slf4j.LoggerFactory;
30 import org.springframework.beans.factory.annotation.Autowired;
31 import org.springframework.stereotype.Component;
32
33 /**
34 * Reads the exposure configuration parameters from the respective file in the class path and builds a {@link
35 * ExposureConfigurationDirectory} with them.
36 */
37 @Component
38 public class ExposureConfigurationStructureProvider {
39
40 private static final Logger logger = LoggerFactory
41 .getLogger(ExposureConfigurationStructureProvider.class);
42
43 private final CryptoProvider cryptoProvider;
44
45 @Autowired
46 public ExposureConfigurationStructureProvider(CryptoProvider cryptoProvider) {
47 this.cryptoProvider = cryptoProvider;
48 }
49
50 public Directory<WritableOnDisk> getExposureConfiguration() {
51 var riskScoreParameters = readExposureConfiguration();
52 return new ExposureConfigurationDirectory(riskScoreParameters, cryptoProvider);
53 }
54
55 private RiskScoreParameters readExposureConfiguration() {
56 logger.debug("Reading exposure configuration...");
57 try {
58 return ExposureConfigurationProvider.readMasterFile();
59 } catch (UnableToLoadFileException e) {
60 logger.error("Could not load exposure configuration parameters", e);
61 throw new RuntimeException(e);
62 }
63 }
64 }
65
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/component/ExposureConfigurationStructureProvider.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/ExposureConfigurationProvider.java]
1 /*
2 * Corona-Warn-App
3 *
4 * SAP SE and all other contributors /
5 * copyright owners license this file to you under the Apache
6 * License, Version 2.0 (the "License"); you may not use this
7 * file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20 package app.coronawarn.server.services.distribution.assembly.exposureconfig;
21
22 import app.coronawarn.server.common.protocols.internal.RiskScoreParameters;
23 import app.coronawarn.server.common.protocols.internal.RiskScoreParameters.Builder;
24 import app.coronawarn.server.services.distribution.assembly.exposureconfig.parsing.YamlConstructorForProtoBuf;
25 import java.io.IOException;
26 import java.io.InputStream;
27 import org.springframework.core.io.ClassPathResource;
28 import org.springframework.core.io.Resource;
29 import org.yaml.snakeyaml.Yaml;
30 import org.yaml.snakeyaml.error.YAMLException;
31 import org.yaml.snakeyaml.introspector.BeanAccess;
32
33 /**
34 * Provides the Exposure Configuration based on a file in the file system.<br> The existing file must be a valid YAML
35 * file, and must match the specification of the proto file risk_score_parameters.proto.
36 */
37 public class ExposureConfigurationProvider {
38
39 private ExposureConfigurationProvider() {
40 }
41
42 /**
43 * The location of the exposure configuration master file.
44 */
45 public static final String MASTER_FILE = "exposure-config/master.yaml";
46
47 /**
48 * Fetches the master configuration as a RiskScoreParameters instance.
49 *
50 * @return the exposure configuration as RiskScoreParameters
51 * @throws UnableToLoadFileException when the file/transformation did not succeed
52 */
53 public static RiskScoreParameters readMasterFile() throws UnableToLoadFileException {
54 return readFile(MASTER_FILE);
55 }
56
57 /**
58 * Fetches an exposure configuration file based on the given path. The path must be available in the classloader.
59 *
60 * @param path the path, e.g. folder/my-exposure-configuration.yaml
61 * @return the RiskScoreParameters
62 * @throws UnableToLoadFileException when the file/transformation did not succeed
63 */
64 public static RiskScoreParameters readFile(String path) throws UnableToLoadFileException {
65 Yaml yaml = new Yaml(new YamlConstructorForProtoBuf());
66 yaml.setBeanAccess(BeanAccess.FIELD); /* no setters on RiskScoreParameters available */
67
68 Resource riskScoreParametersResource = new ClassPathResource(path);
69 try (InputStream inputStream = riskScoreParametersResource.getInputStream()) {
70 Builder loaded = yaml.loadAs(inputStream, RiskScoreParameters.newBuilder().getClass());
71 if (loaded == null) {
72 throw new UnableToLoadFileException(path);
73 }
74
75 return loaded.build();
76 } catch (YAMLException e) {
77 throw new UnableToLoadFileException("Parsing failed", e);
78 } catch (IOException e) {
79 throw new UnableToLoadFileException("Failed to load file " + path, e);
80 }
81 }
82 }
83
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/ExposureConfigurationProvider.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/UnableToLoadFileException.java]
1 /*
2 * Corona-Warn-App
3 *
4 * SAP SE and all other contributors /
5 * copyright owners license this file to you under the Apache
6 * License, Version 2.0 (the "License"); you may not use this
7 * file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20 package app.coronawarn.server.services.distribution.assembly.exposureconfig;
21
22 /**
23 * The file could not be loaded/parsed correctly.
24 */
25 public class UnableToLoadFileException extends Exception {
26
27 public UnableToLoadFileException(String message) {
28 super(message);
29 }
30
31 public UnableToLoadFileException(String message, Throwable cause) {
32 super(message, cause);
33 }
34 }
35
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/UnableToLoadFileException.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/parsing/YamlConstructorForProtoBuf.java]
1 /*
2 * Corona-Warn-App
3 *
4 * SAP SE and all other contributors /
5 * copyright owners license this file to you under the Apache
6 * License, Version 2.0 (the "License"); you may not use this
7 * file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20 package app.coronawarn.server.services.distribution.assembly.exposureconfig.parsing;
21
22 import java.util.Arrays;
23 import org.yaml.snakeyaml.constructor.Constructor;
24 import org.yaml.snakeyaml.introspector.BeanAccess;
25 import org.yaml.snakeyaml.introspector.Property;
26 import org.yaml.snakeyaml.introspector.PropertyUtils;
27
28 /**
29 * This Constructor implementation grants SnakeYaml compliance with the generated proto Java classes. SnakeYaml expects
30 * the Java properties to have the same name as the yaml properties. But the generated Java classes' properties have an
31 * added suffix of '_'. In addition, this implementation also allows snake case in the YAML (for better readability), as
32 * the Java properties are transformed to camel case.
33 */
34 public class YamlConstructorForProtoBuf extends Constructor {
35
36 public YamlConstructorForProtoBuf() {
37 setPropertyUtils(new ProtoBufPropertyUtils());
38 }
39
40 private static class ProtoBufPropertyUtils extends PropertyUtils {
41
42 public Property getProperty(Class<?> type, String name, BeanAccess beanAccess) {
43 return super.getProperty(type, transformToProtoNaming(name), beanAccess);
44 }
45
46 private String transformToProtoNaming(String yamlPropertyName) {
47 return snakeToCamelCase(yamlPropertyName) + "_";
48 }
49
50 private String snakeToCamelCase(String snakeCase) {
51 String camelCase = Arrays.stream(snakeCase.split("_"))
52 .map(word -> Character.toUpperCase(word.charAt(0)) + word.substring(1))
53 .reduce("", String::concat);
54
55 return Character.toLowerCase(camelCase.charAt(0)) + camelCase.substring(1);
56 }
57 }
58
59 }
60
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/parsing/YamlConstructorForProtoBuf.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/structure/directory/ExposureConfigurationDirectory.java]
1 /*
2 * Corona-Warn-App
3 *
4 * SAP SE and all other contributors /
5 * copyright owners license this file to you under the Apache
6 * License, Version 2.0 (the "License"); you may not use this
7 * file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20 package app.coronawarn.server.services.distribution.assembly.exposureconfig.structure.directory;
21
22 import app.coronawarn.server.common.protocols.internal.RiskScoreParameters;
23 import app.coronawarn.server.services.distribution.assembly.component.CryptoProvider;
24 import app.coronawarn.server.services.distribution.assembly.exposureconfig.structure.directory.decorator.ExposureConfigSigningDecorator;
25 import app.coronawarn.server.services.distribution.assembly.structure.archive.ArchiveOnDisk;
26 import app.coronawarn.server.services.distribution.assembly.structure.directory.DirectoryOnDisk;
27 import app.coronawarn.server.services.distribution.assembly.structure.directory.IndexDirectoryOnDisk;
28 import app.coronawarn.server.services.distribution.assembly.structure.directory.decorator.indexing.IndexingDecoratorOnDisk;
29 import app.coronawarn.server.services.distribution.assembly.structure.file.FileOnDisk;
30 import java.util.Set;
31
32 /**
33 * Creates the directory structure {@code /parameters/country/:country} and writes a file called {@code index}
34 * containing {@link RiskScoreParameters} wrapped in a signed zip archive.
35 */
36 public class ExposureConfigurationDirectory extends DirectoryOnDisk {
37
38 private static final String PARAMETERS_DIRECTORY = "parameters";
39 private static final String COUNTRY_DIRECTORY = "country";
40 private static final String COUNTRY = "DE";
41 private static final String INDEX_FILE_NAME = "index";
42
43 /**
44 * Constructor.
45 *
46 * @param exposureConfig The {@link RiskScoreParameters} to sign and write.
47 * @param cryptoProvider The {@link CryptoProvider} whose artifacts to use for creating the signature.
48 */
49 public ExposureConfigurationDirectory(RiskScoreParameters exposureConfig,
50 CryptoProvider cryptoProvider) {
51 super(PARAMETERS_DIRECTORY);
52
53 ArchiveOnDisk archive = new ArchiveOnDisk(INDEX_FILE_NAME);
54 archive.addWritable(new FileOnDisk("export.bin", exposureConfig.toByteArray()));
55
56 IndexDirectoryOnDisk<String> country =
57 new IndexDirectoryOnDisk<>(COUNTRY_DIRECTORY, __ -> Set.of(COUNTRY), Object::toString);
58 country.addWritableToAll(__ ->
59 new ExposureConfigSigningDecorator(archive, cryptoProvider));
60
61 this.addWritable(new IndexingDecoratorOnDisk<>(country));
62 }
63 }
64
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/structure/directory/ExposureConfigurationDirectory.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/structure/directory/decorator/ExposureConfigSigningDecorator.java]
1 package app.coronawarn.server.services.distribution.assembly.exposureconfig.structure.directory.decorator;
2
3 import app.coronawarn.server.services.distribution.assembly.component.CryptoProvider;
4 import app.coronawarn.server.services.distribution.assembly.structure.Writable;
5 import app.coronawarn.server.services.distribution.assembly.structure.WritableOnDisk;
6 import app.coronawarn.server.services.distribution.assembly.structure.archive.Archive;
7 import app.coronawarn.server.services.distribution.assembly.structure.archive.decorator.signing.SigningDecoratorOnDisk;
8 import app.coronawarn.server.services.distribution.assembly.structure.file.FileOnDisk;
9
10 public class ExposureConfigSigningDecorator extends SigningDecoratorOnDisk {
11
12 public ExposureConfigSigningDecorator(Archive<WritableOnDisk> archive, CryptoProvider cryptoProvider) {
13 super(archive, cryptoProvider);
14 }
15
16 @Override
17 public byte[] getBytesToSign() {
18 Writable<?> archiveContent = this.getWritables().stream().findFirst().orElseThrow(
19 () -> new RuntimeException("Archive must contain exactly one file for signing"));
20 FileOnDisk fileToSign = (FileOnDisk) archiveContent;
21 return fileToSign.getBytes();
22 }
23
24 @Override
25 public int getBatchNum() {
26 return 1;
27 }
28
29 @Override
30 public int getBatchSize() {
31 return 1;
32 }
33 }
34
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/structure/directory/decorator/ExposureConfigSigningDecorator.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/validation/ExposureConfigurationValidator.java]
1 /*
2 * Corona-Warn-App
3 *
4 * SAP SE and all other contributors /
5 * copyright owners license this file to you under the Apache
6 * License, Version 2.0 (the "License"); you may not use this
7 * file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20 package app.coronawarn.server.services.distribution.assembly.exposureconfig.validation;
21
22 import app.coronawarn.server.common.protocols.internal.RiskLevel;
23 import app.coronawarn.server.common.protocols.internal.RiskScoreParameters;
24 import app.coronawarn.server.services.distribution.assembly.exposureconfig.validation.WeightValidationError.ErrorType;
25 import java.beans.BeanInfo;
26 import java.beans.IntrospectionException;
27 import java.beans.Introspector;
28 import java.beans.PropertyDescriptor;
29 import java.lang.reflect.InvocationTargetException;
30 import java.math.BigDecimal;
31 import java.util.Arrays;
32
33 /**
34 * The Exposure Configuration Validator checks the values of a given RiskScoreParameters instance. Validation is
35 * performed according to the Apple/Google spec.<br>
36 * <br>
37 * Weights must be in the range of 0.001 to 100.<br> Scores must be in the range of 1 to 8.<br>
38 */
39 public class ExposureConfigurationValidator {
40
41 private final RiskScoreParameters config;
42
43 private ValidationResult errors;
44
45 public ExposureConfigurationValidator(RiskScoreParameters config) {
46 this.config = config;
47 }
48
49 /**
50 * Triggers the validation of the configuration.
51 *
52 * @return the ValidationResult instance, containing information about possible errors.
53 * @throws ValidationExecutionException in case the validation could not be performed
54 */
55 public ValidationResult validate() {
56 this.errors = new ValidationResult();
57
58 validateWeights();
59
60 try {
61 validateParameterRiskLevels("duration", config.getDuration());
62 validateParameterRiskLevels("transmission", config.getTransmission());
63 validateParameterRiskLevels("daysSinceLastExposure", config.getDaysSinceLastExposure());
64 validateParameterRiskLevels("attenuation", config.getAttenuation());
65 } catch (IntrospectionException e) {
66 throw new ValidationExecutionException("Unable to check risk levels", e);
67 }
68
69 return errors;
70 }
71
72 private void validateParameterRiskLevels(String name, Object object)
73 throws IntrospectionException {
74 BeanInfo bean = Introspector.getBeanInfo(object.getClass());
75
76 Arrays.stream(bean.getPropertyDescriptors())
77 .filter(propertyDescriptor -> propertyDescriptor.getPropertyType() == RiskLevel.class)
78 .forEach(propertyDescriptor -> validateScore(propertyDescriptor, object, name));
79 }
80
81 private void validateScore(
82 PropertyDescriptor propertyDescriptor, Object object, String parameter) {
83 try {
84 RiskLevel level = (RiskLevel) propertyDescriptor.getReadMethod().invoke(object);
85
86 if (level == RiskLevel.UNRECOGNIZED || level == RiskLevel.RISK_LEVEL_UNSPECIFIED) {
87 this.errors.add(new RiskLevelValidationError(parameter, propertyDescriptor.getName()));
88 }
89 } catch (IllegalAccessException | InvocationTargetException e) {
90 throw new ValidationExecutionException(
91 "Unable to read property " + propertyDescriptor.getName(), e);
92 }
93 }
94
95 private void validateWeights() {
96 validateWeight(config.getTransmissionWeight(), "transmission");
97 validateWeight(config.getDurationWeight(), "duration");
98 validateWeight(config.getAttenuationWeight(), "attenuation");
99 }
100
101 private void validateWeight(double weight, String name) {
102 if (isOutOfRange(ParameterSpec.WEIGHT_MIN, ParameterSpec.WEIGHT_MAX, weight)) {
103 this.errors.add(new WeightValidationError(name, weight, ErrorType.OUT_OF_RANGE));
104 }
105
106 if (!respectsMaximumDecimalPlaces(weight)) {
107 this.errors.add(new WeightValidationError(name, weight, ErrorType.TOO_MANY_DECIMAL_PLACES));
108 }
109 }
110
111 private boolean respectsMaximumDecimalPlaces(double weight) {
112 BigDecimal bd = new BigDecimal(String.valueOf(weight));
113
114 return bd.scale() <= ParameterSpec.WEIGHT_MAX_DECIMALS;
115 }
116
117
118 private boolean isOutOfRange(double min, double max, double x) {
119 return x < min || x > max;
120 }
121 }
122
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/validation/ExposureConfigurationValidator.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/validation/ParameterSpec.java]
1 /*
2 * Corona-Warn-App
3 *
4 * SAP SE and all other contributors /
5 * copyright owners license this file to you under the Apache
6 * License, Version 2.0 (the "License"); you may not use this
7 * file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20 package app.coronawarn.server.services.distribution.assembly.exposureconfig.validation;
21
22 /**
23 * Definition of the spec according to Apple/Google:
24 * https://developer.apple.com/documentation/exposurenotification/enexposureconfiguration
25 */
26 public class ParameterSpec {
27
28 private ParameterSpec() {
29 }
30
31 /**
32 * The minimum weight value for mobile API.
33 */
34 public static final double WEIGHT_MIN = 0.001;
35
36 /**
37 * The maximum weight value for mobile API.
38 */
39 public static final int WEIGHT_MAX = 100;
40
41 /**
42 * Maximum number of allowed decimals.
43 */
44 public static final int WEIGHT_MAX_DECIMALS = 3;
45
46 }
47
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/validation/ParameterSpec.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/validation/RiskLevelValidationError.java]
1 /*
2 * Corona-Warn-App
3 *
4 * SAP SE and all other contributors /
5 * copyright owners license this file to you under the Apache
6 * License, Version 2.0 (the "License"); you may not use this
7 * file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20 package app.coronawarn.server.services.distribution.assembly.exposureconfig.validation;
21
22 import java.util.Objects;
23
24 /**
25 * Defines a validation errors for risk levels, used by the parameter scores.
26 */
27 public class RiskLevelValidationError implements ValidationError {
28
29 private final String parameter;
30
31 private final String riskLevel;
32
33 public RiskLevelValidationError(String parameter, String riskLevel) {
34 this.parameter = parameter;
35 this.riskLevel = riskLevel;
36 }
37
38 public String getParameter() {
39 return parameter;
40 }
41
42 public String getRiskLevel() {
43 return riskLevel;
44 }
45
46 @Override
47 public boolean equals(Object o) {
48 if (this == o) {
49 return true;
50 }
51 if (o == null || getClass() != o.getClass()) {
52 return false;
53 }
54 RiskLevelValidationError that = (RiskLevelValidationError) o;
55 return Objects.equals(getParameter(), that.getParameter())
56 && Objects.equals(getRiskLevel(), that.getRiskLevel());
57 }
58
59 @Override
60 public int hashCode() {
61 return Objects.hash(getParameter(), getRiskLevel());
62 }
63
64 @Override
65 public String toString() {
66 return "RiskLevelValidationError{"
67 + "parameter='" + parameter + '\''
68 + ", riskLevel='" + riskLevel + '\''
69 + '}';
70 }
71 }
72
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/validation/RiskLevelValidationError.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/validation/ValidationError.java]
1 /*
2 * Corona-Warn-App
3 *
4 * SAP SE and all other contributors /
5 * copyright owners license this file to you under the Apache
6 * License, Version 2.0 (the "License"); you may not use this
7 * file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20 package app.coronawarn.server.services.distribution.assembly.exposureconfig.validation;
21
22 /**
23 * A validation error, found during the process of validating the Exposure Configuration. Can either be score or weight
24 * related.
25 */
26 public interface ValidationError {
27
28 }
29
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/validation/ValidationError.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/validation/ValidationExecutionException.java]
1 /*
2 * Corona-Warn-App
3 *
4 * SAP SE and all other contributors /
5 * copyright owners license this file to you under the Apache
6 * License, Version 2.0 (the "License"); you may not use this
7 * file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20 package app.coronawarn.server.services.distribution.assembly.exposureconfig.validation;
21
22 /**
23 * The validation could not be executed. Find more information about the root cause in the cause element, and in the
24 * message property.
25 */
26 public class ValidationExecutionException extends RuntimeException {
27
28 public ValidationExecutionException(String message, Throwable cause) {
29 super(message, cause);
30 }
31 }
32
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/validation/ValidationExecutionException.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/validation/ValidationResult.java]
1 /*
2 * Corona-Warn-App
3 *
4 * SAP SE and all other contributors /
5 * copyright owners license this file to you under the Apache
6 * License, Version 2.0 (the "License"); you may not use this
7 * file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20 package app.coronawarn.server.services.distribution.assembly.exposureconfig.validation;
21
22 import java.util.HashSet;
23 import java.util.Objects;
24 import java.util.Set;
25
26 /**
27 * The result of a validation run for Exposure Configurations. Find details about possible errors in this collection.
28 */
29 public class ValidationResult {
30
31 private Set<ValidationError> errors = new HashSet<>();
32
33 /**
34 * Adds a {@link ValidationError} to this {@link ValidationResult}.
35 *
36 * @param error The {@link ValidationError} that shall be added.
37 * @return true if this {@link ValidationResult} did not already contain the specified {@link ValidationError}.
38 */
39 public boolean add(ValidationError error) {
40 return this.errors.add(error);
41 }
42
43 @Override
44 public String toString() {
45 return errors.toString();
46 }
47
48 /**
49 * Checks whether this validation result instance has at least one error.
50 *
51 * @return true if yes, false otherwise
52 */
53 public boolean hasErrors() {
54 return !this.errors.isEmpty();
55 }
56
57 /**
58 * Checks whether this validation result instance has no errors.
59 *
60 * @return true if yes, false otherwise
61 */
62 public boolean isSuccessful() {
63 return !hasErrors();
64 }
65
66 @Override
67 public boolean equals(Object o) {
68 if (this == o) {
69 return true;
70 }
71 if (o == null || getClass() != o.getClass()) {
72 return false;
73 }
74 ValidationResult that = (ValidationResult) o;
75 return Objects.equals(errors, that.errors);
76 }
77
78 @Override
79 public int hashCode() {
80 return Objects.hash(errors);
81 }
82 }
83
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/validation/ValidationResult.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/validation/WeightValidationError.java]
1 /*
2 * Corona-Warn-App
3 *
4 * SAP SE and all other contributors /
5 * copyright owners license this file to you under the Apache
6 * License, Version 2.0 (the "License"); you may not use this
7 * file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20 package app.coronawarn.server.services.distribution.assembly.exposureconfig.validation;
21
22 import java.util.Objects;
23
24 public class WeightValidationError implements ValidationError {
25
26 private final ErrorType errorType;
27
28 private final String parameter;
29
30 private final double givenValue;
31
32 /**
33 * Constructs a {@link WeightValidationError} for a specific error occurrence.
34 *
35 * @param parameter The name of the exposure configuration parameter.
36 * @param givenValue The value of the exposure configuration parameter.
37 * @param errorType An error specifier.
38 */
39 public WeightValidationError(String parameter, double givenValue, ErrorType errorType) {
40 this.parameter = parameter;
41 this.givenValue = givenValue;
42 this.errorType = errorType;
43 }
44
45 public String getParameter() {
46 return parameter;
47 }
48
49 public double getGivenValue() {
50 return givenValue;
51 }
52
53 public ErrorType getErrorType() {
54 return errorType;
55 }
56
57 @Override
58 public boolean equals(Object o) {
59 if (this == o) {
60 return true;
61 }
62 if (o == null || getClass() != o.getClass()) {
63 return false;
64 }
65 WeightValidationError that = (WeightValidationError) o;
66 return Double.compare(that.getGivenValue(), getGivenValue()) == 0
67 && getErrorType() == that.getErrorType()
68 && Objects.equals(getParameter(), that.getParameter());
69 }
70
71 @Override
72 public int hashCode() {
73 return Objects.hash(getErrorType(), getParameter(), getGivenValue());
74 }
75
76 @Override
77 public String toString() {
78 return "WeightValidationError{"
79 + "errorType=" + errorType
80 + ", parameter='" + parameter + '\''
81 + ", givenValue=" + givenValue
82 + '}';
83 }
84
85 public enum ErrorType {
86 OUT_OF_RANGE,
87 TOO_MANY_DECIMAL_PLACES
88 }
89 }
90
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/validation/WeightValidationError.java]
</code>
Here is an example of a patch file. It consists of changes to the code base. It specifies the file names, the line numbers of each change, and the removed and added lines. A single patch file can contain changes to multiple files.
<patch>
--- a/file.py
+++ b/file.py
@@ -1,27 +1,35 @@
def euclidean(a, b):
- while b:
- a, b = b, a % b
- return a
+ if b == 0:
+ return a
+ return euclidean(b, a % b)
def bresenham(x0, y0, x1, y1):
points = []
dx = abs(x1 - x0)
dy = abs(y1 - y0)
- sx = 1 if x0 < x1 else -1
- sy = 1 if y0 < y1 else -1
- err = dx - dy
+ x, y = x0, y0
+ sx = -1 if x0 > x1 else 1
+ sy = -1 if y0 > y1 else 1
- while True:
- points.append((x0, y0))
- if x0 == x1 and y0 == y1:
- break
- e2 = 2 * err
- if e2 > -dy:
+ if dx > dy:
+ err = dx / 2.0
+ while x != x1:
+ points.append((x, y))
err -= dy
- x0 += sx
- if e2 < dx:
- err += dx
- y0 += sy
+ if err < 0:
+ y += sy
+ err += dx
+ x += sx
+ else:
+ err = dy / 2.0
+ while y != y1:
+ points.append((x, y))
+ err -= dx
+ if err < 0:
+ x += sx
+ err += dy
+ y += sy
+ points.append((x, y))
return points
</patch>
I need you to solve the provded issue by generating a single patch file that I can apply directly to this repository using git apply. Please respond with a single patch file in the format shown above.
Respond below:
| corona-warn-app/cwa-server | 218e0c75d3890fd6c1166fc63ce287f3b9d51fa7 | Exposure configuration parameters not validated
The exposure configuration parameters are currently not validated after being read from the respective yml file. The validation code in ``ExposureConfigurationValidator`` is currently used in tests only.
However, the expected behavior shall be the following:
- The ``RiskScoreParameters`` object is constructed based on yml file. (✅)
- ``ExposureConfigurationValidator`` performs validation of the parameters.
- In case of a failed validation, **do not** publish the exposure configuration parameters, **but do** generate and publish the diagnosis key bundles.
- Clarify whether to keep any previously present (valid) configuration parameters on the object store if a validation error occurs.
- Any validation errors shall be logged appropriately.
| 2020-05-22T19:20:31 | <patch>
diff --git a/common/protocols/src/main/proto/app/coronawarn/server/common/protocols/internal/risk_score_classification.proto b/common/protocols/src/main/proto/app/coronawarn/server/common/protocols/internal/risk_score_classification.proto
new file mode 100644
--- /dev/null
+++ b/common/protocols/src/main/proto/app/coronawarn/server/common/protocols/internal/risk_score_classification.proto
@@ -0,0 +1,15 @@
+syntax = "proto3";
+package app.coronawarn.server.common.protocols.internal;
+option java_package = "app.coronawarn.server.common.protocols.internal";
+option java_multiple_files = true;
+
+message RiskScoreClassification {
+ repeated RiskScoreClass risk_classes = 1;
+}
+
+message RiskScoreClass {
+ string label = 1;
+ int32 min = 2;
+ int32 max = 3;
+ string url = 4;
+}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/ExposureConfigurationProvider.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/ExposureConfigurationProvider.java
similarity index 60%
rename from services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/ExposureConfigurationProvider.java
rename to services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/ExposureConfigurationProvider.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/ExposureConfigurationProvider.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/ExposureConfigurationProvider.java
@@ -17,18 +17,9 @@
* under the License.
*/
-package app.coronawarn.server.services.distribution.assembly.exposureconfig;
+package app.coronawarn.server.services.distribution.assembly.appconfig;
import app.coronawarn.server.common.protocols.internal.RiskScoreParameters;
-import app.coronawarn.server.common.protocols.internal.RiskScoreParameters.Builder;
-import app.coronawarn.server.services.distribution.assembly.exposureconfig.parsing.YamlConstructorForProtoBuf;
-import java.io.IOException;
-import java.io.InputStream;
-import org.springframework.core.io.ClassPathResource;
-import org.springframework.core.io.Resource;
-import org.yaml.snakeyaml.Yaml;
-import org.yaml.snakeyaml.error.YAMLException;
-import org.yaml.snakeyaml.introspector.BeanAccess;
/**
* Provides the Exposure Configuration based on a file in the file system.<br> The existing file must be a valid YAML
@@ -62,21 +53,6 @@ public static RiskScoreParameters readMasterFile() throws UnableToLoadFileExcept
* @throws UnableToLoadFileException when the file/transformation did not succeed
*/
public static RiskScoreParameters readFile(String path) throws UnableToLoadFileException {
- Yaml yaml = new Yaml(new YamlConstructorForProtoBuf());
- yaml.setBeanAccess(BeanAccess.FIELD); /* no setters on RiskScoreParameters available */
-
- Resource riskScoreParametersResource = new ClassPathResource(path);
- try (InputStream inputStream = riskScoreParametersResource.getInputStream()) {
- Builder loaded = yaml.loadAs(inputStream, RiskScoreParameters.newBuilder().getClass());
- if (loaded == null) {
- throw new UnableToLoadFileException(path);
- }
-
- return loaded.build();
- } catch (YAMLException e) {
- throw new UnableToLoadFileException("Parsing failed", e);
- } catch (IOException e) {
- throw new UnableToLoadFileException("Failed to load file " + path, e);
- }
+ return YamlLoader.loadYamlIntoProtobufBuilder(path, RiskScoreParameters.Builder.class).build();
}
}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/RiskScoreClassificationProvider.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/RiskScoreClassificationProvider.java
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/RiskScoreClassificationProvider.java
@@ -0,0 +1,58 @@
+/*
+ * Corona-Warn-App
+ *
+ * SAP SE and all other contributors /
+ * copyright owners license this file to you under the Apache
+ * License, Version 2.0 (the "License"); you may not use this
+ * file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://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 for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package app.coronawarn.server.services.distribution.assembly.appconfig;
+
+import app.coronawarn.server.common.protocols.internal.RiskScoreClassification;
+
+/**
+ * Provides the risk score classification based on a file on the file system. The existing file must be a valid YAML
+ * file, and must match the specification of the proto file risk_score_classification.proto.
+ */
+public class RiskScoreClassificationProvider {
+
+ private RiskScoreClassificationProvider() {
+ }
+
+ /**
+ * The location of the risk score classification master file.
+ */
+ public static final String MASTER_FILE = "risk-score-classification/master.yaml";
+
+ /**
+ * Fetches the master configuration as a {@link RiskScoreClassification} instance.
+ *
+ * @return the risk score classification as {@link RiskScoreClassification}
+ * @throws UnableToLoadFileException when the file/transformation did not succeed
+ */
+ public static RiskScoreClassification readMasterFile() throws UnableToLoadFileException {
+ return readFile(MASTER_FILE);
+ }
+
+ /**
+ * Fetches a risk score classification file based on the given path. The path must be available in the classloader.
+ *
+ * @param path The path, e.g. folder/my-risk-score-classification.yaml
+ * @return the RiskScoreClassification
+ * @throws UnableToLoadFileException when the file access/transformation did not succeed
+ */
+ public static RiskScoreClassification readFile(String path) throws UnableToLoadFileException {
+ return YamlLoader.loadYamlIntoProtobufBuilder(path, RiskScoreClassification.Builder.class).build();
+ }
+}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/UnableToLoadFileException.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/UnableToLoadFileException.java
similarity index 92%
rename from services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/UnableToLoadFileException.java
rename to services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/UnableToLoadFileException.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/UnableToLoadFileException.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/UnableToLoadFileException.java
@@ -17,7 +17,7 @@
* under the License.
*/
-package app.coronawarn.server.services.distribution.assembly.exposureconfig;
+package app.coronawarn.server.services.distribution.assembly.appconfig;
/**
* The file could not be loaded/parsed correctly.
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/YamlLoader.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/YamlLoader.java
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/YamlLoader.java
@@ -0,0 +1,66 @@
+/*
+ * Corona-Warn-App
+ *
+ * SAP SE and all other contributors /
+ * copyright owners license this file to you under the Apache
+ * License, Version 2.0 (the "License"); you may not use this
+ * file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://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 for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package app.coronawarn.server.services.distribution.assembly.appconfig;
+
+import app.coronawarn.server.services.distribution.assembly.appconfig.parsing.YamlConstructorForProtoBuf;
+import com.google.protobuf.Message;
+import java.io.IOException;
+import java.io.InputStream;
+import org.springframework.core.io.ClassPathResource;
+import org.springframework.core.io.Resource;
+import org.yaml.snakeyaml.Yaml;
+import org.yaml.snakeyaml.error.YAMLException;
+import org.yaml.snakeyaml.introspector.BeanAccess;
+
+public class YamlLoader {
+
+ private YamlLoader() {
+ }
+
+ /**
+ * Returns a protobuf {@link Message.Builder message builder} of the specified type, whose fields have been set to the
+ * corresponding values from the yaml file at the specified path.
+ *
+ * @param path The absolute path of the yaml file within the class path.
+ * @param builderType The specific {@link com.google.protobuf.Message.Builder} implementation that will be returned.
+ * @return A prepared protobuf {@link Message.Builder message builder} of the specified type.
+ * @throws UnableToLoadFileException if either the file access or subsequent yaml parsing fails.
+ */
+ public static <T extends Message.Builder> T loadYamlIntoProtobufBuilder(String path, Class<T> builderType)
+ throws UnableToLoadFileException {
+ Yaml yaml = new Yaml(new YamlConstructorForProtoBuf());
+ // no setters for generated message classes available
+ yaml.setBeanAccess(BeanAccess.FIELD);
+
+ Resource riskScoreParametersResource = new ClassPathResource(path);
+ try (InputStream inputStream = riskScoreParametersResource.getInputStream()) {
+ T loaded = yaml.loadAs(inputStream, builderType);
+ if (loaded == null) {
+ throw new UnableToLoadFileException(path);
+ }
+
+ return loaded;
+ } catch (YAMLException e) {
+ throw new UnableToLoadFileException("Parsing failed", e);
+ } catch (IOException e) {
+ throw new UnableToLoadFileException("Failed to load file " + path, e);
+ }
+ }
+}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/parsing/YamlConstructorForProtoBuf.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/parsing/YamlConstructorForProtoBuf.java
similarity index 95%
rename from services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/parsing/YamlConstructorForProtoBuf.java
rename to services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/parsing/YamlConstructorForProtoBuf.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/parsing/YamlConstructorForProtoBuf.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/parsing/YamlConstructorForProtoBuf.java
@@ -17,7 +17,7 @@
* under the License.
*/
-package app.coronawarn.server.services.distribution.assembly.exposureconfig.parsing;
+package app.coronawarn.server.services.distribution.assembly.appconfig.parsing;
import java.util.Arrays;
import org.yaml.snakeyaml.constructor.Constructor;
@@ -39,6 +39,7 @@ public YamlConstructorForProtoBuf() {
private static class ProtoBufPropertyUtils extends PropertyUtils {
+ @Override
public Property getProperty(Class<?> type, String name, BeanAccess beanAccess) {
return super.getProperty(type, transformToProtoNaming(name), beanAccess);
}
@@ -55,5 +56,4 @@ private String snakeToCamelCase(String snakeCase) {
return Character.toLowerCase(camelCase.charAt(0)) + camelCase.substring(1);
}
}
-
}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/structure/directory/AppConfigurationDirectory.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/structure/directory/AppConfigurationDirectory.java
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/structure/directory/AppConfigurationDirectory.java
@@ -0,0 +1,113 @@
+/*
+ * Corona-Warn-App
+ *
+ * SAP SE and all other contributors /
+ * copyright owners license this file to you under the Apache
+ * License, Version 2.0 (the "License"); you may not use this
+ * file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://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 for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package app.coronawarn.server.services.distribution.assembly.appconfig.structure.directory;
+
+import app.coronawarn.server.common.protocols.internal.RiskScoreClassification;
+import app.coronawarn.server.common.protocols.internal.RiskScoreParameters;
+import app.coronawarn.server.services.distribution.assembly.appconfig.ExposureConfigurationProvider;
+import app.coronawarn.server.services.distribution.assembly.appconfig.RiskScoreClassificationProvider;
+import app.coronawarn.server.services.distribution.assembly.appconfig.UnableToLoadFileException;
+import app.coronawarn.server.services.distribution.assembly.appconfig.structure.directory.decorator.AppConfigurationSigningDecorator;
+import app.coronawarn.server.services.distribution.assembly.appconfig.validation.AppConfigurationValidator;
+import app.coronawarn.server.services.distribution.assembly.appconfig.validation.ExposureConfigurationValidator;
+import app.coronawarn.server.services.distribution.assembly.appconfig.validation.RiskScoreClassificationValidator;
+import app.coronawarn.server.services.distribution.assembly.appconfig.validation.ValidationResult;
+import app.coronawarn.server.services.distribution.assembly.component.CryptoProvider;
+import app.coronawarn.server.services.distribution.assembly.structure.archive.ArchiveOnDisk;
+import app.coronawarn.server.services.distribution.assembly.structure.directory.DirectoryOnDisk;
+import app.coronawarn.server.services.distribution.assembly.structure.directory.IndexDirectoryOnDisk;
+import app.coronawarn.server.services.distribution.assembly.structure.directory.decorator.indexing.IndexingDecoratorOnDisk;
+import app.coronawarn.server.services.distribution.assembly.structure.file.FileOnDisk;
+import com.google.protobuf.Message;
+import java.util.Set;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Creates the directory structure {@code /parameters/country/:country} and writes two files. One containing {@link
+ * RiskScoreParameters} and the another containing the {@link RiskScoreClassification}, wrapped in a signed zip
+ * archive.
+ */
+public class AppConfigurationDirectory extends DirectoryOnDisk {
+
+ private static final Logger logger = LoggerFactory.getLogger(AppConfigurationDirectory.class);
+ private static final String PARAMETERS_DIRECTORY = "configuration";
+ private static final String COUNTRY_DIRECTORY = "country";
+ private static final String COUNTRY = "DE";
+ private static final String EXPOSURE_CONFIGURATION_FILE_NAME = "exposure_configuration";
+ private static final String RISK_SCORE_CLASSIFICATION_FILE_NAME = "risk_score_classification";
+
+ private final IndexDirectoryOnDisk<String> countryDirectory =
+ new IndexDirectoryOnDisk<>(COUNTRY_DIRECTORY, __ -> Set.of(COUNTRY), Object::toString);
+
+ private final CryptoProvider cryptoProvider;
+
+ /**
+ * Creates an {@link AppConfigurationDirectory} for the exposure configuration and risk score classification.
+ *
+ * @param cryptoProvider The {@link CryptoProvider} whose artifacts to use for creating the signature.
+ */
+ public AppConfigurationDirectory(CryptoProvider cryptoProvider) {
+ super(PARAMETERS_DIRECTORY);
+
+ this.cryptoProvider = cryptoProvider;
+ addExposureConfigurationIfValid();
+ addRiskScoreClassificationIfValid();
+
+ this.addWritable(new IndexingDecoratorOnDisk<>(countryDirectory));
+ }
+
+ private void addExposureConfigurationIfValid() {
+ try {
+ RiskScoreParameters exposureConfig = ExposureConfigurationProvider.readMasterFile();
+ AppConfigurationValidator validator = new ExposureConfigurationValidator(exposureConfig);
+ addArchiveIfMessageValid(EXPOSURE_CONFIGURATION_FILE_NAME, exposureConfig, validator);
+ } catch (UnableToLoadFileException e) {
+ logger.error("Exposure configuration will not be published! Unable to read configuration file from disk.");
+ }
+ }
+
+ private void addRiskScoreClassificationIfValid() {
+ try {
+ RiskScoreClassification riskScoreClassification = RiskScoreClassificationProvider.readMasterFile();
+ AppConfigurationValidator validator = new RiskScoreClassificationValidator(riskScoreClassification);
+ addArchiveIfMessageValid(RISK_SCORE_CLASSIFICATION_FILE_NAME, riskScoreClassification, validator);
+ } catch (UnableToLoadFileException e) {
+ logger.error("Risk score classification will not be published! Unable to read configuration file from disk.");
+ }
+ }
+
+ /**
+ * If validation of the {@link Message} succeeds, it is written into a file, put into an archive with the specified
+ * name and added to the specified parent directory.
+ */
+ private void addArchiveIfMessageValid(String archiveName, Message message, AppConfigurationValidator validator) {
+ ValidationResult validationResult = validator.validate();
+
+ if (validationResult.hasErrors()) {
+ logger.error("App configuration file creation failed. Validation failed for {}./n{}",
+ archiveName, validationResult);
+ }
+
+ ArchiveOnDisk appConfigurationFile = new ArchiveOnDisk(archiveName);
+ appConfigurationFile.addWritable(new FileOnDisk("export.bin", message.toByteArray()));
+ countryDirectory.addWritableToAll(__ -> new AppConfigurationSigningDecorator(appConfigurationFile, cryptoProvider));
+ }
+}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/structure/directory/decorator/ExposureConfigSigningDecorator.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/structure/directory/decorator/AppConfigurationSigningDecorator.java
similarity index 78%
rename from services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/structure/directory/decorator/ExposureConfigSigningDecorator.java
rename to services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/structure/directory/decorator/AppConfigurationSigningDecorator.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/structure/directory/decorator/ExposureConfigSigningDecorator.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/structure/directory/decorator/AppConfigurationSigningDecorator.java
@@ -1,4 +1,4 @@
-package app.coronawarn.server.services.distribution.assembly.exposureconfig.structure.directory.decorator;
+package app.coronawarn.server.services.distribution.assembly.appconfig.structure.directory.decorator;
import app.coronawarn.server.services.distribution.assembly.component.CryptoProvider;
import app.coronawarn.server.services.distribution.assembly.structure.Writable;
@@ -7,9 +7,9 @@
import app.coronawarn.server.services.distribution.assembly.structure.archive.decorator.signing.SigningDecoratorOnDisk;
import app.coronawarn.server.services.distribution.assembly.structure.file.FileOnDisk;
-public class ExposureConfigSigningDecorator extends SigningDecoratorOnDisk {
+public class AppConfigurationSigningDecorator extends SigningDecoratorOnDisk {
- public ExposureConfigSigningDecorator(Archive<WritableOnDisk> archive, CryptoProvider cryptoProvider) {
+ public AppConfigurationSigningDecorator(Archive<WritableOnDisk> archive, CryptoProvider cryptoProvider) {
super(archive, cryptoProvider);
}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/AppConfigurationValidator.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/AppConfigurationValidator.java
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/AppConfigurationValidator.java
@@ -0,0 +1,37 @@
+/*
+ * Corona-Warn-App
+ *
+ * SAP SE and all other contributors /
+ * copyright owners license this file to you under the Apache
+ * License, Version 2.0 (the "License"); you may not use this
+ * file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://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 for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package app.coronawarn.server.services.distribution.assembly.appconfig.validation;
+
+/**
+ * Classes that extend {@link AppConfigurationValidator} validate the values of an associated {@link
+ * com.google.protobuf.Message} instance.
+ */
+public abstract class AppConfigurationValidator {
+
+ protected ValidationResult errors;
+
+ /**
+ * Performs a validation of the associated {@link com.google.protobuf.Message} instance and returns information about
+ * validation failures.
+ *
+ * @return The ValidationResult instance, containing information about possible errors.
+ */
+ public abstract ValidationResult validate();
+}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/validation/ExposureConfigurationValidator.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ExposureConfigurationValidator.java
similarity index 93%
rename from services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/validation/ExposureConfigurationValidator.java
rename to services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ExposureConfigurationValidator.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/validation/ExposureConfigurationValidator.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ExposureConfigurationValidator.java
@@ -17,11 +17,11 @@
* under the License.
*/
-package app.coronawarn.server.services.distribution.assembly.exposureconfig.validation;
+package app.coronawarn.server.services.distribution.assembly.appconfig.validation;
import app.coronawarn.server.common.protocols.internal.RiskLevel;
import app.coronawarn.server.common.protocols.internal.RiskScoreParameters;
-import app.coronawarn.server.services.distribution.assembly.exposureconfig.validation.WeightValidationError.ErrorType;
+import app.coronawarn.server.services.distribution.assembly.appconfig.validation.WeightValidationError.ErrorType;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
@@ -36,12 +36,10 @@
* <br>
* Weights must be in the range of 0.001 to 100.<br> Scores must be in the range of 1 to 8.<br>
*/
-public class ExposureConfigurationValidator {
+public class ExposureConfigurationValidator extends AppConfigurationValidator {
private final RiskScoreParameters config;
- private ValidationResult errors;
-
public ExposureConfigurationValidator(RiskScoreParameters config) {
this.config = config;
}
@@ -52,6 +50,7 @@ public ExposureConfigurationValidator(RiskScoreParameters config) {
* @return the ValidationResult instance, containing information about possible errors.
* @throws ValidationExecutionException in case the validation could not be performed
*/
+ @Override
public ValidationResult validate() {
this.errors = new ValidationResult();
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/validation/ParameterSpec.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ParameterSpec.java
similarity index 93%
rename from services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/validation/ParameterSpec.java
rename to services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ParameterSpec.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/validation/ParameterSpec.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ParameterSpec.java
@@ -17,7 +17,7 @@
* under the License.
*/
-package app.coronawarn.server.services.distribution.assembly.exposureconfig.validation;
+package app.coronawarn.server.services.distribution.assembly.appconfig.validation;
/**
* Definition of the spec according to Apple/Google:
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/validation/RiskLevelValidationError.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/RiskLevelValidationError.java
similarity index 95%
rename from services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/validation/RiskLevelValidationError.java
rename to services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/RiskLevelValidationError.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/validation/RiskLevelValidationError.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/RiskLevelValidationError.java
@@ -17,7 +17,7 @@
* under the License.
*/
-package app.coronawarn.server.services.distribution.assembly.exposureconfig.validation;
+package app.coronawarn.server.services.distribution.assembly.appconfig.validation;
import java.util.Objects;
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/RiskScoreClassificationValidationError.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/RiskScoreClassificationValidationError.java
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/RiskScoreClassificationValidationError.java
@@ -0,0 +1,81 @@
+/*
+ * Corona-Warn-App
+ *
+ * SAP SE and all other contributors /
+ * copyright owners license this file to you under the Apache
+ * License, Version 2.0 (the "License"); you may not use this
+ * file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://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 for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package app.coronawarn.server.services.distribution.assembly.appconfig.validation;
+
+import java.util.Objects;
+
+public class RiskScoreClassificationValidationError implements ValidationError {
+
+ private final String errorSource;
+
+ private final Object value;
+
+ private final ErrorType reason;
+
+ /**
+ * Creates a {@link RiskScoreClassificationValidationError} that stores the specified validation error source,
+ * erroneous value and a reason for the error to occur.
+ *
+ * @param errorSource A label that describes the property associated with this validation error.
+ * @param value The value that caused the validation error.
+ * @param reason A validation error specifier.
+ */
+ public RiskScoreClassificationValidationError(String errorSource, Object value, ErrorType reason) {
+ this.errorSource = errorSource;
+ this.value = value;
+ this.reason = reason;
+ }
+
+ @Override
+ public String toString() {
+ return "RiskScoreClassificationValidationError{"
+ + "errorType=" + reason
+ + ", parameter='" + errorSource + '\''
+ + ", givenValue=" + value
+ + '}';
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ RiskScoreClassificationValidationError that = (RiskScoreClassificationValidationError) o;
+ return Objects.equals(errorSource, that.errorSource)
+ && Objects.equals(value, that.value)
+ && Objects.equals(reason, that.reason);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(errorSource, value, reason);
+ }
+
+ public enum ErrorType {
+ BLANK_LABEL,
+ MIN_GREATER_THAN_MAX,
+ VALUE_OUT_OF_BOUNDS,
+ INVALID_URL,
+ INVALID_PARTITIONING
+ }
+}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/RiskScoreClassificationValidator.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/RiskScoreClassificationValidator.java
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/RiskScoreClassificationValidator.java
@@ -0,0 +1,113 @@
+/*
+ * Corona-Warn-App
+ *
+ * SAP SE and all other contributors /
+ * copyright owners license this file to you under the Apache
+ * License, Version 2.0 (the "License"); you may not use this
+ * file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://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 for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package app.coronawarn.server.services.distribution.assembly.appconfig.validation;
+
+import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.RiskScoreClassificationValidationError.ErrorType.BLANK_LABEL;
+import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.RiskScoreClassificationValidationError.ErrorType.INVALID_PARTITIONING;
+import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.RiskScoreClassificationValidationError.ErrorType.INVALID_URL;
+import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.RiskScoreClassificationValidationError.ErrorType.MIN_GREATER_THAN_MAX;
+import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.RiskScoreClassificationValidationError.ErrorType.VALUE_OUT_OF_BOUNDS;
+
+import app.coronawarn.server.common.protocols.internal.RiskScoreClass;
+import app.coronawarn.server.common.protocols.internal.RiskScoreClassification;
+import java.net.MalformedURLException;
+import java.net.URL;
+
+/**
+ * The RiskScoreClassificationValidator validates the values of an associated {@link RiskScoreClassification} instance.
+ */
+public class RiskScoreClassificationValidator extends AppConfigurationValidator {
+
+ /**
+ * This defines the number of possible values (0 ... RISK_SCORE_VALUE_RANGE - 1) for the total risk score.
+ */
+ public static final int RISK_SCORE_VALUE_RANGE = 256;
+
+ private final RiskScoreClassification riskScoreClassification;
+
+ public RiskScoreClassificationValidator(RiskScoreClassification riskScoreClassification) {
+ this.riskScoreClassification = riskScoreClassification;
+ }
+
+ /**
+ * Performs a validation of the associated {@link RiskScoreClassification} instance and returns information about
+ * validation failures.
+ *
+ * @return The ValidationResult instance, containing information about possible errors.
+ */
+ @Override
+ public ValidationResult validate() {
+ errors = new ValidationResult();
+
+ validateValues();
+ validateValueRangeCoverage();
+
+ return errors;
+ }
+
+ private void validateValues() {
+ for (RiskScoreClass riskScoreClass : riskScoreClassification.getRiskClassesList()) {
+ int minRiskLevel = riskScoreClass.getMin();
+ int maxRiskLevel = riskScoreClass.getMax();
+
+ validateLabel(riskScoreClass.getLabel());
+ validateRiskScoreValueBounds(minRiskLevel);
+ validateRiskScoreValueBounds(maxRiskLevel);
+ validateUrl(riskScoreClass.getUrl());
+
+ if (minRiskLevel > maxRiskLevel) {
+ errors.add(new RiskScoreClassificationValidationError(
+ "minRiskLevel, maxRiskLevel", minRiskLevel + ", " + maxRiskLevel, MIN_GREATER_THAN_MAX));
+ }
+ }
+ }
+
+ private void validateLabel(String label) {
+ if (label.isBlank()) {
+ errors.add(new RiskScoreClassificationValidationError("label", label, BLANK_LABEL));
+ }
+ }
+
+ private void validateRiskScoreValueBounds(int value) {
+ if (value < 0 || value > RISK_SCORE_VALUE_RANGE - 1) {
+ errors.add(new RiskScoreClassificationValidationError("minRiskLevel/maxRiskLevel", value, VALUE_OUT_OF_BOUNDS));
+ }
+ }
+
+ private void validateUrl(String url) {
+ if (!url.isBlank()) {
+ try {
+ new URL(url);
+ } catch (MalformedURLException e) {
+ errors.add(new RiskScoreClassificationValidationError("url", url, INVALID_URL));
+ }
+ }
+ }
+
+ private void validateValueRangeCoverage() {
+ int partitionSum = riskScoreClassification.getRiskClassesList().stream()
+ .mapToInt(riskScoreClass -> (riskScoreClass.getMax() - riskScoreClass.getMin() + 1))
+ .sum();
+
+ if (partitionSum != RISK_SCORE_VALUE_RANGE) {
+ errors.add(new RiskScoreClassificationValidationError("covered value range", partitionSum, INVALID_PARTITIONING));
+ }
+ }
+}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/validation/ValidationError.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ValidationError.java
similarity index 76%
rename from services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/validation/ValidationError.java
rename to services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ValidationError.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/validation/ValidationError.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ValidationError.java
@@ -17,11 +17,10 @@
* under the License.
*/
-package app.coronawarn.server.services.distribution.assembly.exposureconfig.validation;
+package app.coronawarn.server.services.distribution.assembly.appconfig.validation;
/**
- * A validation error, found during the process of validating the Exposure Configuration. Can either be score or weight
- * related.
+ * A validation error, found during validation of a generated protocol buffers message class instance.
*/
public interface ValidationError {
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/validation/ValidationExecutionException.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ValidationExecutionException.java
similarity index 91%
rename from services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/validation/ValidationExecutionException.java
rename to services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ValidationExecutionException.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/validation/ValidationExecutionException.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ValidationExecutionException.java
@@ -17,7 +17,7 @@
* under the License.
*/
-package app.coronawarn.server.services.distribution.assembly.exposureconfig.validation;
+package app.coronawarn.server.services.distribution.assembly.appconfig.validation;
/**
* The validation could not be executed. Find more information about the root cause in the cause element, and in the
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/validation/ValidationResult.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ValidationResult.java
similarity index 87%
rename from services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/validation/ValidationResult.java
rename to services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ValidationResult.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/validation/ValidationResult.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ValidationResult.java
@@ -17,7 +17,7 @@
* under the License.
*/
-package app.coronawarn.server.services.distribution.assembly.exposureconfig.validation;
+package app.coronawarn.server.services.distribution.assembly.appconfig.validation;
import java.util.HashSet;
import java.util.Objects;
@@ -40,11 +40,6 @@ public boolean add(ValidationError error) {
return this.errors.add(error);
}
- @Override
- public String toString() {
- return errors.toString();
- }
-
/**
* Checks whether this validation result instance has at least one error.
*
@@ -54,13 +49,9 @@ public boolean hasErrors() {
return !this.errors.isEmpty();
}
- /**
- * Checks whether this validation result instance has no errors.
- *
- * @return true if yes, false otherwise
- */
- public boolean isSuccessful() {
- return !hasErrors();
+ @Override
+ public String toString() {
+ return errors.toString();
}
@Override
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/validation/WeightValidationError.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/WeightValidationError.java
similarity index 96%
rename from services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/validation/WeightValidationError.java
rename to services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/WeightValidationError.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/validation/WeightValidationError.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/WeightValidationError.java
@@ -17,7 +17,7 @@
* under the License.
*/
-package app.coronawarn.server.services.distribution.assembly.exposureconfig.validation;
+package app.coronawarn.server.services.distribution.assembly.appconfig.validation;
import java.util.Objects;
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/component/AppConfigurationStructureProvider.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/component/AppConfigurationStructureProvider.java
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/component/AppConfigurationStructureProvider.java
@@ -0,0 +1,45 @@
+/*
+ * Corona-Warn-App
+ *
+ * SAP SE and all other contributors /
+ * copyright owners license this file to you under the Apache
+ * License, Version 2.0 (the "License"); you may not use this
+ * file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://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 for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package app.coronawarn.server.services.distribution.assembly.component;
+
+import app.coronawarn.server.services.distribution.assembly.appconfig.structure.directory.AppConfigurationDirectory;
+import app.coronawarn.server.services.distribution.assembly.structure.WritableOnDisk;
+import app.coronawarn.server.services.distribution.assembly.structure.directory.Directory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+/**
+ * Reads configuration parameters from the respective files in the class path and builds a {@link
+ * AppConfigurationDirectory} with them.
+ */
+@Component
+public class AppConfigurationStructureProvider {
+
+ private final CryptoProvider cryptoProvider;
+
+ @Autowired
+ public AppConfigurationStructureProvider(CryptoProvider cryptoProvider) {
+ this.cryptoProvider = cryptoProvider;
+ }
+
+ public Directory<WritableOnDisk> getAppConfiguration() {
+ return new AppConfigurationDirectory(cryptoProvider);
+ }
+}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/component/CwaApiStructureProvider.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/component/CwaApiStructureProvider.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/component/CwaApiStructureProvider.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/component/CwaApiStructureProvider.java
@@ -36,15 +36,15 @@ public class CwaApiStructureProvider {
public static final String VERSION_DIRECTORY = "version";
public static final String VERSION_V1 = "v1";
- private final ExposureConfigurationStructureProvider exposureConfigurationStructureProvider;
+ private final AppConfigurationStructureProvider appConfigurationStructureProvider;
private final DiagnosisKeysStructureProvider diagnosisKeysStructureProvider;
@Autowired
public CwaApiStructureProvider(
- ExposureConfigurationStructureProvider exposureConfigurationStructureProvider,
+ AppConfigurationStructureProvider appConfigurationStructureProvider,
DiagnosisKeysStructureProvider diagnosisKeysStructureProvider) {
- this.exposureConfigurationStructureProvider = exposureConfigurationStructureProvider;
+ this.appConfigurationStructureProvider = appConfigurationStructureProvider;
this.diagnosisKeysStructureProvider = diagnosisKeysStructureProvider;
}
@@ -56,7 +56,7 @@ public Directory<WritableOnDisk> getDirectory() {
new IndexDirectoryOnDisk<>(VERSION_DIRECTORY, __ -> Set.of(VERSION_V1), Object::toString);
versionDirectory
- .addWritableToAll(__ -> exposureConfigurationStructureProvider.getExposureConfiguration());
+ .addWritableToAll(__ -> appConfigurationStructureProvider.getAppConfiguration());
versionDirectory.addWritableToAll(__ -> diagnosisKeysStructureProvider.getDiagnosisKeys());
return new IndexingDecoratorOnDisk<>(versionDirectory);
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/component/ExposureConfigurationStructureProvider.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/component/ExposureConfigurationStructureProvider.java
deleted file mode 100644
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/component/ExposureConfigurationStructureProvider.java
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * Corona-Warn-App
- *
- * SAP SE and all other contributors /
- * copyright owners license this file to you under the Apache
- * License, Version 2.0 (the "License"); you may not use this
- * file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://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 for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package app.coronawarn.server.services.distribution.assembly.component;
-
-import app.coronawarn.server.common.protocols.internal.RiskScoreParameters;
-import app.coronawarn.server.services.distribution.assembly.exposureconfig.ExposureConfigurationProvider;
-import app.coronawarn.server.services.distribution.assembly.exposureconfig.UnableToLoadFileException;
-import app.coronawarn.server.services.distribution.assembly.exposureconfig.structure.directory.ExposureConfigurationDirectory;
-import app.coronawarn.server.services.distribution.assembly.structure.WritableOnDisk;
-import app.coronawarn.server.services.distribution.assembly.structure.directory.Directory;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Component;
-
-/**
- * Reads the exposure configuration parameters from the respective file in the class path and builds a {@link
- * ExposureConfigurationDirectory} with them.
- */
-@Component
-public class ExposureConfigurationStructureProvider {
-
- private static final Logger logger = LoggerFactory
- .getLogger(ExposureConfigurationStructureProvider.class);
-
- private final CryptoProvider cryptoProvider;
-
- @Autowired
- public ExposureConfigurationStructureProvider(CryptoProvider cryptoProvider) {
- this.cryptoProvider = cryptoProvider;
- }
-
- public Directory<WritableOnDisk> getExposureConfiguration() {
- var riskScoreParameters = readExposureConfiguration();
- return new ExposureConfigurationDirectory(riskScoreParameters, cryptoProvider);
- }
-
- private RiskScoreParameters readExposureConfiguration() {
- logger.debug("Reading exposure configuration...");
- try {
- return ExposureConfigurationProvider.readMasterFile();
- } catch (UnableToLoadFileException e) {
- logger.error("Could not load exposure configuration parameters", e);
- throw new RuntimeException(e);
- }
- }
-}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/structure/directory/ExposureConfigurationDirectory.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/structure/directory/ExposureConfigurationDirectory.java
deleted file mode 100644
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/structure/directory/ExposureConfigurationDirectory.java
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * Corona-Warn-App
- *
- * SAP SE and all other contributors /
- * copyright owners license this file to you under the Apache
- * License, Version 2.0 (the "License"); you may not use this
- * file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://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 for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package app.coronawarn.server.services.distribution.assembly.exposureconfig.structure.directory;
-
-import app.coronawarn.server.common.protocols.internal.RiskScoreParameters;
-import app.coronawarn.server.services.distribution.assembly.component.CryptoProvider;
-import app.coronawarn.server.services.distribution.assembly.exposureconfig.structure.directory.decorator.ExposureConfigSigningDecorator;
-import app.coronawarn.server.services.distribution.assembly.structure.archive.ArchiveOnDisk;
-import app.coronawarn.server.services.distribution.assembly.structure.directory.DirectoryOnDisk;
-import app.coronawarn.server.services.distribution.assembly.structure.directory.IndexDirectoryOnDisk;
-import app.coronawarn.server.services.distribution.assembly.structure.directory.decorator.indexing.IndexingDecoratorOnDisk;
-import app.coronawarn.server.services.distribution.assembly.structure.file.FileOnDisk;
-import java.util.Set;
-
-/**
- * Creates the directory structure {@code /parameters/country/:country} and writes a file called {@code index}
- * containing {@link RiskScoreParameters} wrapped in a signed zip archive.
- */
-public class ExposureConfigurationDirectory extends DirectoryOnDisk {
-
- private static final String PARAMETERS_DIRECTORY = "parameters";
- private static final String COUNTRY_DIRECTORY = "country";
- private static final String COUNTRY = "DE";
- private static final String INDEX_FILE_NAME = "index";
-
- /**
- * Constructor.
- *
- * @param exposureConfig The {@link RiskScoreParameters} to sign and write.
- * @param cryptoProvider The {@link CryptoProvider} whose artifacts to use for creating the signature.
- */
- public ExposureConfigurationDirectory(RiskScoreParameters exposureConfig,
- CryptoProvider cryptoProvider) {
- super(PARAMETERS_DIRECTORY);
-
- ArchiveOnDisk archive = new ArchiveOnDisk(INDEX_FILE_NAME);
- archive.addWritable(new FileOnDisk("export.bin", exposureConfig.toByteArray()));
-
- IndexDirectoryOnDisk<String> country =
- new IndexDirectoryOnDisk<>(COUNTRY_DIRECTORY, __ -> Set.of(COUNTRY), Object::toString);
- country.addWritableToAll(__ ->
- new ExposureConfigSigningDecorator(archive, cryptoProvider));
-
- this.addWritable(new IndexingDecoratorOnDisk<>(country));
- }
-}
diff --git a/services/distribution/src/main/resources/risk-score-classification/master.yaml b/services/distribution/src/main/resources/risk-score-classification/master.yaml
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/main/resources/risk-score-classification/master.yaml
@@ -0,0 +1,27 @@
+# This is the Risk Score Classification master file which partitions the risk
+# score value range (0-255) into distinct risk classes that will be used to by
+# the app in order to present the correct risk classification in a user
+# friendly manner, based on the underlying total risk score, to the user.
+#
+# The risk classes must not overlap and
+# cover the full risk score value range (0-255).
+#
+# Change this file with caution!
+
+risk_classes:
+ -
+ label: "LOW"
+ min: 0
+ max: 100
+ url: "https://www..."
+ -
+ label: "MID"
+ min: 101
+ max: 200
+ url: "https://www..."
+ -
+ label: "HIGH"
+ min: 201
+ max: 255
+ url: "https://www..."
+
\ No newline at end of file
</patch> | diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/ExposureConfigurationProviderMasterFileTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/ExposureConfigurationProviderMasterFileTest.java
similarity index 82%
rename from services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/ExposureConfigurationProviderMasterFileTest.java
rename to services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/ExposureConfigurationProviderMasterFileTest.java
--- a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/ExposureConfigurationProviderMasterFileTest.java
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/ExposureConfigurationProviderMasterFileTest.java
@@ -17,12 +17,12 @@
* under the License.
*/
-package app.coronawarn.server.services.distribution.assembly.exposureconfig;
+package app.coronawarn.server.services.distribution.assembly.appconfig;
import static org.assertj.core.api.Assertions.assertThat;
-import app.coronawarn.server.services.distribution.assembly.exposureconfig.validation.ExposureConfigurationValidator;
-import app.coronawarn.server.services.distribution.assembly.exposureconfig.validation.ValidationResult;
+import app.coronawarn.server.services.distribution.assembly.appconfig.validation.ExposureConfigurationValidator;
+import app.coronawarn.server.services.distribution.assembly.appconfig.validation.ValidationResult;
import org.junit.jupiter.api.Test;
/**
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/ExposureConfigurationProviderTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/ExposureConfigurationProviderTest.java
similarity index 95%
rename from services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/ExposureConfigurationProviderTest.java
rename to services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/ExposureConfigurationProviderTest.java
--- a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/ExposureConfigurationProviderTest.java
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/ExposureConfigurationProviderTest.java
@@ -17,7 +17,7 @@
* under the License.
*/
-package app.coronawarn.server.services.distribution.assembly.exposureconfig;
+package app.coronawarn.server.services.distribution.assembly.appconfig;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/RiskScoreClassificationProviderMasterFileTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/RiskScoreClassificationProviderMasterFileTest.java
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/RiskScoreClassificationProviderMasterFileTest.java
@@ -0,0 +1,46 @@
+/*
+ * Corona-Warn-App
+ *
+ * SAP SE and all other contributors /
+ * copyright owners license this file to you under the Apache
+ * License, Version 2.0 (the "License"); you may not use this
+ * file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://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 for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package app.coronawarn.server.services.distribution.assembly.appconfig;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import app.coronawarn.server.services.distribution.assembly.appconfig.validation.ExposureConfigurationValidator;
+import app.coronawarn.server.services.distribution.assembly.appconfig.validation.RiskScoreClassificationValidator;
+import app.coronawarn.server.services.distribution.assembly.appconfig.validation.ValidationResult;
+import org.junit.jupiter.api.Test;
+
+/**
+ * This test will verify that the provided risk score classification master file is syntactically correct and according
+ * to spec.
+ * There should never be any deployment when this test is failing.
+ */
+public class RiskScoreClassificationProviderMasterFileTest {
+
+ private static final ValidationResult SUCCESS = new ValidationResult();
+
+ @Test
+ public void testMasterFile() throws UnableToLoadFileException {
+ var config = RiskScoreClassificationProvider.readMasterFile();
+
+ var validator = new RiskScoreClassificationValidator(config);
+
+ assertThat(validator.validate()).isEqualTo(SUCCESS);
+ }
+}
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/validation/ExposureConfigurationValidatorTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ExposureConfigurationValidatorTest.java
similarity index 91%
rename from services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/validation/ExposureConfigurationValidatorTest.java
rename to services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ExposureConfigurationValidatorTest.java
--- a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/validation/ExposureConfigurationValidatorTest.java
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ExposureConfigurationValidatorTest.java
@@ -17,14 +17,14 @@
* under the License.
*/
-package app.coronawarn.server.services.distribution.assembly.exposureconfig.validation;
+package app.coronawarn.server.services.distribution.assembly.appconfig.validation;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
-import app.coronawarn.server.services.distribution.assembly.exposureconfig.ExposureConfigurationProvider;
-import app.coronawarn.server.services.distribution.assembly.exposureconfig.UnableToLoadFileException;
-import app.coronawarn.server.services.distribution.assembly.exposureconfig.validation.WeightValidationError.ErrorType;
+import app.coronawarn.server.services.distribution.assembly.appconfig.ExposureConfigurationProvider;
+import app.coronawarn.server.services.distribution.assembly.appconfig.UnableToLoadFileException;
+import app.coronawarn.server.services.distribution.assembly.appconfig.validation.WeightValidationError.ErrorType;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/RiskScoreClassificationValidatorTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/RiskScoreClassificationValidatorTest.java
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/RiskScoreClassificationValidatorTest.java
@@ -0,0 +1,173 @@
+/*
+ * Corona-Warn-App
+ *
+ * SAP SE and all other contributors /
+ * copyright owners license this file to you under the Apache
+ * License, Version 2.0 (the "License"); you may not use this
+ * file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://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 for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package app.coronawarn.server.services.distribution.assembly.appconfig.validation;
+
+import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.RiskScoreClassificationValidator.RISK_SCORE_VALUE_RANGE;
+import static java.util.Arrays.asList;
+import static org.assertj.core.api.Assertions.assertThat;
+import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.RiskScoreClassificationValidationError.ErrorType.*;
+
+import app.coronawarn.server.common.protocols.internal.RiskScoreClass;
+import app.coronawarn.server.common.protocols.internal.RiskScoreClassification;
+import app.coronawarn.server.services.distribution.assembly.appconfig.validation.RiskScoreClassificationValidationError.ErrorType;
+import java.util.Arrays;
+import java.util.stream.Stream;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.junit.jupiter.params.provider.ValueSource;
+
+public class RiskScoreClassificationValidatorTest {
+
+ private final static int MAX_SCORE = RISK_SCORE_VALUE_RANGE - 1;
+ private final static String VALID_LABEL = "myLabel";
+ private final static String VALID_URL = "";
+
+ @ParameterizedTest
+ @ValueSource(strings = {"", " "})
+ void failsForBlankLabels(String invalidLabel) {
+ var validator = buildValidator(buildRiskClass(invalidLabel, 0, MAX_SCORE, ""));
+ var expectedResult = buildExpectedResult(buildError("label", invalidLabel, ErrorType.BLANK_LABEL));
+
+ assertThat(validator.validate()).isEqualTo(expectedResult);
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"invalid.Url", "invalid-url", "$$$://invalid.url"})
+ void failsForInvalidUrl(String invalidUrl) {
+ var validator = buildValidator(buildRiskClass(VALID_LABEL, 0, MAX_SCORE, invalidUrl));
+ var expectedResult = buildExpectedResult(buildError("url", invalidUrl, ErrorType.INVALID_URL));
+
+ assertThat(validator.validate()).isEqualTo(expectedResult);
+ }
+
+ @Test
+ void failsForNegativeRiskValues() {
+ // must cover value range of equal size in order to avoid INVALID_PARTITIONING error
+ int negativeMin = -MAX_SCORE - 1;
+ int negativeMax = -1;
+ var validator = buildValidator(buildRiskClass(VALID_LABEL, negativeMin, negativeMax, VALID_URL));
+ var expectedResult = buildExpectedResult(
+ buildError("minRiskLevel/maxRiskLevel", negativeMin, ErrorType.VALUE_OUT_OF_BOUNDS),
+ buildError("minRiskLevel/maxRiskLevel", negativeMax, ErrorType.VALUE_OUT_OF_BOUNDS));
+
+ assertThat(validator.validate()).isEqualTo(expectedResult);
+ }
+
+ @Test
+ void failsForTooLargeRiskValues() {
+ // must cover value range of equal size in order to avoid INVALID_PARTITIONING error
+ int tooLargeMin = MAX_SCORE + 1;
+ int tooLargeMax = 2 * MAX_SCORE + 1;
+ var validator = buildValidator(buildRiskClass(VALID_LABEL, tooLargeMin, tooLargeMax, VALID_URL));
+ var expectedResult = buildExpectedResult(
+ buildError("minRiskLevel/maxRiskLevel", tooLargeMin, ErrorType.VALUE_OUT_OF_BOUNDS),
+ buildError("minRiskLevel/maxRiskLevel", tooLargeMax, ErrorType.VALUE_OUT_OF_BOUNDS));
+
+ assertThat(validator.validate()).isEqualTo(expectedResult);
+ }
+
+ @Test
+ void failsIfMinGreaterThanMax() {
+ int min = 1;
+ int max = 0;
+ // Note: additional classes have to be added in order to reach the expected value range size
+ var validator = buildValidator(buildRiskClass(VALID_LABEL, min, max, VALID_URL),
+ buildRiskClass(VALID_LABEL, 0, MAX_SCORE, VALID_URL));
+ var expectedResult = buildExpectedResult(
+ buildError("minRiskLevel, maxRiskLevel", (min + ", " + max), MIN_GREATER_THAN_MAX));
+
+ assertThat(validator.validate()).isEqualTo(expectedResult);
+ }
+
+ @ParameterizedTest
+ @MethodSource("createInvalidPartitionings")
+ void failsIfPartitioningInvalid(RiskScoreClassification invalidClassification) {
+ var validator = new RiskScoreClassificationValidator(invalidClassification);
+ int coveredRange = invalidClassification.getRiskClassesList().stream()
+ .mapToInt(riskScoreClass -> (riskScoreClass.getMax() - riskScoreClass.getMin() + 1))
+ .sum();
+ var expectedResult = buildExpectedResult(
+ buildError("covered value range", coveredRange, INVALID_PARTITIONING));
+
+ assertThat(validator.validate()).isEqualTo(expectedResult);
+ }
+
+ private static Stream<Arguments> createInvalidPartitionings() {
+ return Stream.of(
+ buildClassification(buildRiskClass(VALID_LABEL, 0, 0, VALID_URL)),
+ buildClassification(
+ buildRiskClass(VALID_LABEL, 0, MAX_SCORE / 2, VALID_URL),
+ buildRiskClass(VALID_LABEL, MAX_SCORE / 2 + 1, MAX_SCORE, VALID_URL),
+ buildRiskClass(VALID_LABEL, 0, MAX_SCORE, VALID_URL)),
+ buildClassification(
+ buildRiskClass(VALID_LABEL, 0, MAX_SCORE, VALID_URL),
+ buildRiskClass(VALID_LABEL, 0, MAX_SCORE, VALID_URL))
+ ).map(Arguments::of);
+ }
+
+ @ParameterizedTest
+ @MethodSource("createValidClassifications")
+ void doesNotFailForValidClassification(RiskScoreClassification validClassification) {
+ var validator = new RiskScoreClassificationValidator(validClassification);
+ assertThat(validator.validate()).isEqualTo(new ValidationResult());
+ }
+
+ private static Stream<Arguments> createValidClassifications() {
+ return Stream.of(
+ // blank url
+ buildClassification(buildRiskClass(VALID_LABEL, 0, MAX_SCORE, "")),
+ // legit url
+ buildClassification(buildRiskClass(VALID_LABEL, 0, MAX_SCORE, "http://www.sap.com")),
+ // [0:MAX_SCORE/2][MAX_SCORE/2:MAX_SCORE]
+ buildClassification(
+ buildRiskClass(VALID_LABEL, 0, MAX_SCORE / 2, VALID_URL),
+ buildRiskClass(VALID_LABEL, MAX_SCORE / 2 + 1, MAX_SCORE, VALID_URL)),
+ // [0:MAX_SCORE-10][MAX_SCORE-9][MAX_SCORE-8:MAX_SCORE]
+ buildClassification(
+ buildRiskClass(VALID_LABEL, 0, MAX_SCORE - 10, VALID_URL),
+ buildRiskClass(VALID_LABEL, MAX_SCORE - 9, MAX_SCORE - 9, VALID_URL),
+ buildRiskClass(VALID_LABEL, MAX_SCORE - 8, MAX_SCORE, VALID_URL))
+ ).map(Arguments::of);
+ }
+
+ private static RiskScoreClassificationValidationError buildError(String parameter, Object value, ErrorType reason) {
+ return new RiskScoreClassificationValidationError(parameter, value, reason);
+ }
+
+ private static RiskScoreClassificationValidator buildValidator(RiskScoreClass... riskScoreClasses) {
+ return new RiskScoreClassificationValidator(buildClassification(riskScoreClasses));
+ }
+
+ private static RiskScoreClassification buildClassification(RiskScoreClass... riskScoreClasses) {
+ return RiskScoreClassification.newBuilder().addAllRiskClasses(asList(riskScoreClasses)).build();
+ }
+
+ private static RiskScoreClass buildRiskClass(String label, int min, int max, String url) {
+ return RiskScoreClass.newBuilder().setLabel(label).setMin(min).setMax(max).setUrl(url).build();
+ }
+
+ private static ValidationResult buildExpectedResult(RiskScoreClassificationValidationError... errors) {
+ var validationResult = new ValidationResult();
+ Arrays.stream(errors).forEach(validationResult::add);
+ return validationResult;
+ }
+}
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/validation/TestWithExpectedResult.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/TestWithExpectedResult.java
similarity index 92%
rename from services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/validation/TestWithExpectedResult.java
rename to services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/TestWithExpectedResult.java
--- a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/validation/TestWithExpectedResult.java
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/TestWithExpectedResult.java
@@ -17,7 +17,7 @@
* under the License.
*/
-package app.coronawarn.server.services.distribution.assembly.exposureconfig.validation;
+package app.coronawarn.server.services.distribution.assembly.appconfig.validation;
public class TestWithExpectedResult {
| |||||
corona-warn-app__cwa-server-441 | You will be provided with a partial code base and an issue statement explaining a problem to resolve.
<issue>
Application Configuration: Attenuation Duration Enhancements
We need two additional configuration variables for the attenuation duration, namely defaultBucketOffset and riskScoreNormalizationDivisor.
The target config should look like this:
```yaml
default-bucket-offset: 0 # discussed as W4
risk-score-normalization-divisor: 25 # discussed as W5
thresholds:
lower: 50
upper: 70
weights:
low: 1.0
mid: 0.5
high: 0.0
```
Value range for bucket offset: 0 or 1 (int)
risk score normalization divisor: 1...1000 (int)
</issue>
<code>
[start of README.md]
1 <!-- markdownlint-disable MD041 -->
2 <h1 align="center">
3 Corona-Warn-App Server
4 </h1>
5
6 <p align="center">
7 <a href="https://github.com/corona-warn-app/cwa-server/commits/" title="Last Commit"><img src="https://img.shields.io/github/last-commit/corona-warn-app/cwa-server?style=flat"></a>
8 <a href="https://github.com/corona-warn-app/cwa-server/issues" title="Open Issues"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat"></a>
9 <a href="https://circleci.com/gh/corona-warn-app/cwa-server" title="Build Status"><img src="https://circleci.com/gh/corona-warn-app/cwa-server.svg?style=shield&circle-token=4ab059989d10709df19eb4b98ab7c121a25e981a"></a>
10 <a href="https://sonarcloud.io/dashboard?id=corona-warn-app_cwa-server" title="Quality Gate"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=alert_status"></a>
11 <a href="https://sonarcloud.io/component_measures?id=corona-warn-app_cwa-server&metric=Coverage&view=list" title="Coverage"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=coverage"></a>
12 <a href="https://github.com/corona-warn-app/cwa-server/blob/master/LICENSE" title="License"><img src="https://img.shields.io/badge/License-Apache%202.0-green.svg?style=flat"></a>
13 </p>
14
15 <p align="center">
16 <a href="#development">Development</a> •
17 <a href="#service-apis">Service APIs</a> •
18 <a href="#documentation">Documentation</a> •
19 <a href="#support-and-feedback">Support</a> •
20 <a href="#how-to-contribute">Contribute</a> •
21 <a href="#contributors">Contributors</a> •
22 <a href="#repositories">Repositories</a> •
23 <a href="#licensing">Licensing</a>
24 </p>
25
26 The goal of this project is to develop the official Corona-Warn-App for Germany based on the exposure notification API from [Apple](https://www.apple.com/covid19/contacttracing/) and [Google](https://www.google.com/covid19/exposurenotifications/). The apps (for both iOS and Android) use Bluetooth technology to exchange anonymous encrypted data with other mobile phones (on which the app is also installed) in the vicinity of an app user's phone. The data is stored locally on each user's device, preventing authorities or other parties from accessing or controlling the data. This repository contains the **implementation of the server for encryption keys** for the Corona-Warn-App. This implementation is still a **work in progress**, and the code it contains is currently alpha-quality code.
27
28 In this documentation, Corona-Warn-App services are also referred to as CWA services.
29
30 ## Architecture Overview
31
32 You can find the architecture overview [here](/docs/architecture-overview.md), which will give you
33 a good starting point in how the backend services interact with other services, and what purpose
34 they serve.
35
36 ## Development
37
38 After you've checked out this repository, you can run the application in one of the following ways:
39
40 * As a [Docker](https://www.docker.com/)-based deployment on your local machine. You can run either:
41 * Single components using the respective Dockerfile or
42 * The full backend using the Docker Compose (which is considered the most convenient way)
43 * As a [Maven](https://maven.apache.org)-based build on your local machine.
44 If you want to develop something in a single component, this approach is preferable.
45
46 ### Docker-Based Deployment
47
48 If you want to use Docker-based deployment, you need to install Docker on your local machine. For more information about downloading and installing Docker, see the [official Docker documentation](https://docs.docker.com/get-docker/).
49
50 #### Running the Full CWA Backend Using Docker Compose
51
52 For your convenience, a full setup including the generation of test data has been prepared using [Docker Compose](https://docs.docker.com/compose/reference/overview/). To build the backend services, run ```docker-compose build``` in the repository's root directory. A default configuration file can be found under ```.env```in the root folder of the repository. The default values for the local Postgres and Zenko Cloudserver should be changed in this file before docker-compose is run.
53
54 Once the services are built, you can start the whole backend using ```docker-compose up```.
55 The distribution service runs once and then finishes. If you want to trigger additional distribution runs, run ```docker-compose run distribution```.
56
57 The docker-compose contains the following services:
58
59 Service | Description | Endpoint and Default Credentials
60 ------------------|-------------|-----------
61 submission | The Corona-Warn-App submission service | `http://localhost:8000` <br> `http://localhost:8006` (for actuator endpoint)
62 distribution | The Corona-Warn-App distribution service | NO ENDPOINT
63 postgres | A [postgres] database installation | `postgres:8001` <br> Username: postgres <br> Password: postgres
64 pgadmin | A [pgadmin](https://www.pgadmin.org/) installation for the postgres database | `http://localhost:8002` <br> Username: [email protected] <br> Password: password
65 cloudserver | [Zenko CloudServer] is a S3-compliant object store | `http://localhost:8003/` <br> Access key: accessKey1 <br> Secret key: verySecretKey1
66 verification-fake | A very simple fake implementation for the tan verification. | `http://localhost:8004/version/v1/tan/verify` <br> The only valid tan is "edc07f08-a1aa-11ea-bb37-0242ac130002"
67
68 ##### Known Limitation
69
70 In rare cases the docker-compose runs into a timing issue if the distribution service starts before the bucket of the objectstore was created. This is not a big issue as you can simply run ```docker-compose run distribution``` to trigger additional distribution runs after the objectstore was initialized.
71
72 #### Running Single CWA Services Using Docker
73
74 If you would like to build and run a single CWA service, it's considered easiest to run them in a Docker environment. You can do this using the script provided in the respective CWA service directory. The Docker script first builds the CWA service and then creates an image for the runtime, which means that there are no additional dependencies for you to install.
75
76 To build and run the distribution service, run the following command:
77
78 ```bash
79 ./services/distribution/build_and_run.sh
80 ```
81
82 To build and run the submission service, run the following command:
83
84 ```bash
85 ./services/submission/build_and_run.sh
86 ```
87
88 The submission service is available on [localhost:8080](http://localhost:8080 ).
89
90 ### Maven-Based Build
91
92 If you want to actively develop in one of the CWA services, the Maven-based runtime is most suitable.
93 To prepare your machine to run the CWA project locally, we recommend that you first ensure that you've installed the following:
94
95 * Minimum JDK Version 11: [OpenJDK](https://openjdk.java.net/) / [SapMachine](https://sap.github.io/SapMachine/)
96 * [Maven 3.6](https://maven.apache.org/)
97 * [Postgres]
98 * [Zenko CloudServer]
99
100 #### Configure
101
102 After you made sure that the specified dependencies are running, configure them in the respective configuration files.
103
104 * Configure the Postgres connection in the [submission config](./services/submission/src/main/resources/application.yaml) and in the [distribution config](./services/distribution/src/main/resources/application.yaml)
105 * Configure the S3 compatible object storage in the [distribution config](./services/distribution/src/main/resources/application.yaml)
106 * Configure the private key for the distribution service, the path need to be prefixed with `file:`
107 * `VAULT_FILESIGNING_SECRET` should be the path to the private key, example available in `<repo-root>/docker-compose-test-secrets/private.pem`
108
109 #### Build
110
111 After you've checked out the repository, to build the project, run ```mvn install``` in your base directory.
112
113 #### Run
114
115 Navigate to the service you want to start and run the spring-boot:run target. The configured Postgres and the configured S3 compliant object storage are used as default. When you start the submission service, the endpoint is available on your local port 8080.
116
117 If you want to start the submission service, for example, you start it as follows:
118
119 ```bash
120 cd services/submission/
121 mvn spring-boot:run
122 ```
123
124 #### Debugging
125
126 To enable the `DEBUG` log level, you can run the application using the Spring `dev` profile.
127
128 ```bash
129 mvn spring-boot:run -Dspring-boot.run.profiles=dev
130 ```
131
132 To be able to set breakpoints (e.g. in IntelliJ), it may be necessary to use the ```-Dspring-boot.run.fork=false``` parameter.
133
134 ## Service APIs
135
136 The API that is being exposed by the backend services is documented in an [OpenAPI](https://www.openapis.org/) specification. The specification files are available at the following locations:
137
138 Service | OpenAPI Specification
139 -------------|-------------
140 Submission Service | [services/submission/api_v1.json](https://github.com/corona-warn-app/cwa-server/raw/master/services/submission/api_v1.json)
141 Distribution Service | [services/distribution/api_v1.json](https://github.com/corona-warn-app/cwa-server/raw/master/services/distribution/api_v1.json)
142
143 ## Spring Profiles
144
145 ### Distribution
146
147 Profile | Effect
148 -----------------|-------------
149 `dev` | Turns the log level to `DEBUG`.
150 `cloud` | Removes default values for the `datasource` and `objectstore` configurations.
151 `demo` | Includes incomplete days and hours into the distribution run, thus creating aggregates for the current day and the current hour (and including both in the respective indices). When running multiple distributions in one hour with this profile, the date aggregate for today and the hours aggregate for the current hour will be updated and overwritten. This profile also turns off the expiry policy (Keys must be expired for at least 2 hours before distribution) and the shifting policy (there must be at least 140 keys in a distribution).
152 `testdata` | Causes test data to be inserted into the database before each distribution run. By default, around 1000 random diagnosis keys will be generated per hour. If there are no diagnosis keys in the database yet, random keys will be generated for every hour from the beginning of the retention period (14 days ago at 00:00 UTC) until one hour before the present hour. If there are already keys in the database, the random keys will be generated for every hour from the latest diagnosis key in the database (by submission timestamp) until one hour before the present hour (or none at all, if the latest diagnosis key in the database was submitted one hour ago or later).
153 `signature-dev` | Sets the app package ID in the export packages' signature info to `de.rki.coronawarnapp-dev` so that test certificates (instead of production certificates) will be used for client-side validation.
154 `signature-prod` | Provides production app package IDs for the signature info
155
156 ### Submission
157
158 Profile | Effect
159 -------------|-------------
160 `dev` | Turns the log level to `DEBUG`.
161 `cloud` | Removes default values for the `datasource` configuration.
162
163 ## Documentation
164
165 The full documentation for the Corona-Warn-App can be found in the [cwa-documentation](https://github.com/corona-warn-app/cwa-documentation) repository. The documentation repository contains technical documents, architecture information, and whitepapers related to this implementation.
166
167 ## Support and Feedback
168
169 The following channels are available for discussions, feedback, and support requests:
170
171 | Type | Channel |
172 | ------------------------ | ------------------------------------------------------ |
173 | **General Discussion** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="General Discussion"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/question.svg?style=flat-square"></a> </a> |
174 | **Concept Feedback** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="Open Concept Feedback"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/architecture.svg?style=flat-square"></a> |
175 | **Backend Issue** | <a href="https://github.com/corona-warn-app/cwa-server/issues/new/choose" title="Open Backend Issue"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat-square"></a> |
176 | **Other Requests** | <a href="mailto:[email protected]" title="Email CWA Team"><img src="https://img.shields.io/badge/email-CWA%20team-green?logo=mail.ru&style=flat-square&logoColor=white"></a> |
177
178 ## How to Contribute
179
180 Contribution and feedback are 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.
181
182 ## Contributors
183
184 The German government has asked SAP and Deutsche Telekom to develop the Corona-Warn-App for Germany as open source software. Deutsche Telekom is providing the network and mobile technology and will operate and run the backend for the app in a safe, scalable and stable manner. SAP is responsible for the app development, its framework and the underlying platform. Therefore, development teams of SAP and Deutsche Telekom are contributing to this project. At the same time 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.
185
186 ## Repositories
187
188 The following public repositories are currently available for the Corona-Warn-App:
189
190 | Repository | Description |
191 | ------------------- | --------------------------------------------------------------------- |
192 | [cwa-documentation] | Project overview, general documentation, and white papers |
193 | [cwa-server] | Backend implementation for the Apple/Google exposure notification API|
194 | [cwa-verification-server] | Backend implementation of the verification process|
195
196 [cwa-documentation]: https://github.com/corona-warn-app/cwa-documentation
197 [cwa-server]: https://github.com/corona-warn-app/cwa-server
198 [cwa-verification-server]: https://github.com/corona-warn-app/cwa-verification-server
199 [Postgres]: https://www.postgresql.org/
200 [HSQLDB]: http://hsqldb.org/
201 [Zenko CloudServer]: https://github.com/scality/cloudserver
202
203 ## Licensing
204
205 Copyright (c) 2020 SAP SE or an SAP affiliate company.
206
207 Licensed under the **Apache License, Version 2.0** (the "License"); you may not use this file except in compliance with the License.
208
209 You may obtain a copy of the License at <https://www.apache.org/licenses/LICENSE-2.0>.
210
211 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.
212
[end of README.md]
[start of common/protocols/src/main/proto/app/coronawarn/server/common/protocols/internal/attenuation_duration.proto]
1 syntax = "proto3";
2 package app.coronawarn.server.common.protocols.internal;
3 option java_package = "app.coronawarn.server.common.protocols.internal";
4 option java_multiple_files = true;
5
6 message AttenuationDuration {
7 Thresholds thresholds = 1;
8 Weights weights = 2;
9 }
10
11 message Thresholds {
12 int32 lower = 1;
13 int32 upper = 2;
14 }
15
16 message Weights {
17 double low = 1;
18 double mid = 2;
19 double high = 3;
20 }
21
[end of common/protocols/src/main/proto/app/coronawarn/server/common/protocols/internal/attenuation_duration.proto]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/AttenuationDurationValidator.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.distribution.assembly.appconfig.validation;
22
23 import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.GeneralValidationError.ErrorType.MIN_GREATER_THAN_MAX;
24 import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.GeneralValidationError.ErrorType.VALUE_OUT_OF_BOUNDS;
25 import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.ParameterSpec.ATTENUATION_DURATION_THRESHOLD_MAX;
26 import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.ParameterSpec.ATTENUATION_DURATION_THRESHOLD_MIN;
27 import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.ParameterSpec.ATTENUATION_DURATION_WEIGHT_MAX;
28 import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.ParameterSpec.ATTENUATION_DURATION_WEIGHT_MIN;
29 import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.WeightValidationError.ErrorType.OUT_OF_RANGE;
30 import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.WeightValidationError.ErrorType.TOO_MANY_DECIMAL_PLACES;
31
32 import app.coronawarn.server.common.protocols.internal.AttenuationDuration;
33 import java.math.BigDecimal;
34
35 /**
36 * The AttenuationDurationValidator validates the values of an associated {@link AttenuationDuration} instance.
37 */
38 public class AttenuationDurationValidator extends ConfigurationValidator {
39
40 private final AttenuationDuration attenuationDuration;
41
42 public AttenuationDurationValidator(AttenuationDuration attenuationDuration) {
43 this.attenuationDuration = attenuationDuration;
44 }
45
46 @Override
47 public ValidationResult validate() {
48 errors = new ValidationResult();
49
50 validateThresholds();
51 validateWeights();
52
53 return errors;
54 }
55
56 private void validateThresholds() {
57 int lower = attenuationDuration.getThresholds().getLower();
58 int upper = attenuationDuration.getThresholds().getUpper();
59
60 checkThresholdBound("lower", lower);
61 checkThresholdBound("upper", upper);
62
63 if (lower > upper) {
64 String parameters = "attenuation-duration.thresholds.lower, attenuation-duration.thresholds.upper";
65 String values = lower + ", " + upper;
66 this.errors.add(new GeneralValidationError(parameters, values, MIN_GREATER_THAN_MAX));
67 }
68 }
69
70 private void checkThresholdBound(String thresholdLabel, int thresholdValue) {
71 if (thresholdValue < ATTENUATION_DURATION_THRESHOLD_MIN || thresholdValue > ATTENUATION_DURATION_THRESHOLD_MAX) {
72 this.errors.add(new GeneralValidationError(
73 "attenuation-duration.thresholds." + thresholdLabel, thresholdValue, VALUE_OUT_OF_BOUNDS));
74 }
75 }
76
77 private void validateWeights() {
78 checkWeight("low", attenuationDuration.getWeights().getLow());
79 checkWeight("mid", attenuationDuration.getWeights().getMid());
80 checkWeight("high", attenuationDuration.getWeights().getHigh());
81 }
82
83 private void checkWeight(String weightLabel, double weightValue) {
84 if (weightValue < ATTENUATION_DURATION_WEIGHT_MIN || weightValue > ATTENUATION_DURATION_WEIGHT_MAX) {
85 this.errors.add(new WeightValidationError(
86 "attenuation-duration.weights." + weightLabel, weightValue, OUT_OF_RANGE));
87 }
88
89 if (BigDecimal.valueOf(weightValue).scale() > ParameterSpec.ATTENUATION_DURATION_WEIGHT_MAX_DECIMALS) {
90 this.errors.add(new WeightValidationError(
91 "attenuation-duration.weights." + weightLabel, weightValue, TOO_MANY_DECIMAL_PLACES));
92 }
93 }
94 }
95
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/AttenuationDurationValidator.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ParameterSpec.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.distribution.assembly.appconfig.validation;
22
23 /**
24 * Definition of the spec according to Apple/Google:
25 * https://developer.apple.com/documentation/exposurenotification/enexposureconfiguration
26 */
27 public class ParameterSpec {
28
29 private ParameterSpec() {
30 }
31
32 /**
33 * The minimum weight value for mobile API.
34 */
35 public static final double WEIGHT_MIN = 0.001;
36
37 /**
38 * The maximum weight value for mobile API.
39 */
40 public static final int WEIGHT_MAX = 100;
41
42 /**
43 * Maximum number of allowed decimals.
44 */
45 public static final int WEIGHT_MAX_DECIMALS = 3;
46
47 /**
48 * The allowed minimum value for risk score.
49 */
50 public static final int RISK_SCORE_MIN = 0;
51
52 /**
53 * The allowed maximum value for a risk score.
54 */
55 public static final int RISK_SCORE_MAX = 4096;
56
57 /**
58 * The allowed minimum value for an attenuation threshold.
59 */
60 public static final int ATTENUATION_DURATION_THRESHOLD_MIN = 0;
61
62 /**
63 * The allowed maximum value for an attenuation threshold.
64 */
65 public static final int ATTENUATION_DURATION_THRESHOLD_MAX = 100;
66
67 /**
68 * The allowed minimum value for an attenuation weight.
69 */
70 public static final double ATTENUATION_DURATION_WEIGHT_MIN = .0;
71
72 /**
73 * The allowed maximum value for an attenuation weight.
74 */
75 public static final double ATTENUATION_DURATION_WEIGHT_MAX = 1.;
76
77 /**
78 * Maximum number of allowed decimals for an attenuation weight.
79 */
80 public static final int ATTENUATION_DURATION_WEIGHT_MAX_DECIMALS = 3;
81 }
82
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ParameterSpec.java]
[start of services/distribution/src/main/resources/master-config/attenuation-duration.yaml]
1 # This is the attenuation and duration parameter thresholds. The lower and
2 # upper threshold partitions the value range into 3 subsets: low, mid, high
3 #
4 # Each of the aforementioned partitions has a weight in the range of [0, 1]
5 # assigned to it. The number of decimal places is restricted to 3.
6 #
7 # Change this file with caution!
8
9 thresholds:
10 lower: 50
11 upper: 70
12 weights:
13 low: 1.0
14 mid: 0.5
15 high: 0.0
16
[end of services/distribution/src/main/resources/master-config/attenuation-duration.yaml]
</code>
Here is an example of a patch file. It consists of changes to the code base. It specifies the file names, the line numbers of each change, and the removed and added lines. A single patch file can contain changes to multiple files.
<patch>
--- a/file.py
+++ b/file.py
@@ -1,27 +1,35 @@
def euclidean(a, b):
- while b:
- a, b = b, a % b
- return a
+ if b == 0:
+ return a
+ return euclidean(b, a % b)
def bresenham(x0, y0, x1, y1):
points = []
dx = abs(x1 - x0)
dy = abs(y1 - y0)
- sx = 1 if x0 < x1 else -1
- sy = 1 if y0 < y1 else -1
- err = dx - dy
+ x, y = x0, y0
+ sx = -1 if x0 > x1 else 1
+ sy = -1 if y0 > y1 else 1
- while True:
- points.append((x0, y0))
- if x0 == x1 and y0 == y1:
- break
- e2 = 2 * err
- if e2 > -dy:
+ if dx > dy:
+ err = dx / 2.0
+ while x != x1:
+ points.append((x, y))
err -= dy
- x0 += sx
- if e2 < dx:
- err += dx
- y0 += sy
+ if err < 0:
+ y += sy
+ err += dx
+ x += sx
+ else:
+ err = dy / 2.0
+ while y != y1:
+ points.append((x, y))
+ err -= dx
+ if err < 0:
+ x += sx
+ err += dy
+ y += sy
+ points.append((x, y))
return points
</patch>
I need you to solve the provded issue by generating a single patch file that I can apply directly to this repository using git apply. Please respond with a single patch file in the format shown above.
Respond below:
| corona-warn-app/cwa-server | 2165f162938409e6401c926d8643835a114ab887 | Application Configuration: Attenuation Duration Enhancements
We need two additional configuration variables for the attenuation duration, namely defaultBucketOffset and riskScoreNormalizationDivisor.
The target config should look like this:
```yaml
default-bucket-offset: 0 # discussed as W4
risk-score-normalization-divisor: 25 # discussed as W5
thresholds:
lower: 50
upper: 70
weights:
low: 1.0
mid: 0.5
high: 0.0
```
Value range for bucket offset: 0 or 1 (int)
risk score normalization divisor: 1...1000 (int)
| @michael-burwig
Proposed .proto file:
```
syntax = "proto3";
package app.coronawarn.server.common.protocols.internal;
option java_package = "app.coronawarn.server.common.protocols.internal";
option java_multiple_files = true;
message AttenuationDuration {
Thresholds thresholds = 1;
Weights weights = 2;
int32 defaultBucketOffset = 3;
int32 riskScoreNormalizationDivisor = 4;
}
message Thresholds {
int32 lower = 1;
int32 upper = 2;
}
message Weights {
double low = 1;
double mid = 2;
double high = 3;
}
``` | 2020-06-03T19:38:59 | <patch>
diff --git a/common/protocols/src/main/proto/app/coronawarn/server/common/protocols/internal/attenuation_duration.proto b/common/protocols/src/main/proto/app/coronawarn/server/common/protocols/internal/attenuation_duration.proto
--- a/common/protocols/src/main/proto/app/coronawarn/server/common/protocols/internal/attenuation_duration.proto
+++ b/common/protocols/src/main/proto/app/coronawarn/server/common/protocols/internal/attenuation_duration.proto
@@ -6,6 +6,8 @@ option java_multiple_files = true;
message AttenuationDuration {
Thresholds thresholds = 1;
Weights weights = 2;
+ int32 defaultBucketOffset = 3;
+ int32 riskScoreNormalizationDivisor = 4;
}
message Thresholds {
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/AttenuationDurationValidator.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/AttenuationDurationValidator.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/AttenuationDurationValidator.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/AttenuationDurationValidator.java
@@ -26,6 +26,10 @@
import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.ParameterSpec.ATTENUATION_DURATION_THRESHOLD_MIN;
import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.ParameterSpec.ATTENUATION_DURATION_WEIGHT_MAX;
import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.ParameterSpec.ATTENUATION_DURATION_WEIGHT_MIN;
+import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.ParameterSpec.DEFAULT_BUCKET_OFFSET_MAX;
+import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.ParameterSpec.DEFAULT_BUCKET_OFFSET_MIN;
+import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.ParameterSpec.RISK_SCORE_NORMALIZATION_DIVISOR_MAX;
+import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.ParameterSpec.RISK_SCORE_NORMALIZATION_DIVISOR_MIN;
import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.WeightValidationError.ErrorType.OUT_OF_RANGE;
import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.WeightValidationError.ErrorType.TOO_MANY_DECIMAL_PLACES;
@@ -49,6 +53,8 @@ public ValidationResult validate() {
validateThresholds();
validateWeights();
+ validateDefaultBucketOffset();
+ validateRiskScoreNormalizationDivisor();
return errors;
}
@@ -57,8 +63,8 @@ private void validateThresholds() {
int lower = attenuationDuration.getThresholds().getLower();
int upper = attenuationDuration.getThresholds().getUpper();
- checkThresholdBound("lower", lower);
- checkThresholdBound("upper", upper);
+ checkValueRange("thresholds.lower", lower, ATTENUATION_DURATION_THRESHOLD_MIN, ATTENUATION_DURATION_THRESHOLD_MAX);
+ checkValueRange("thresholds.upper", upper, ATTENUATION_DURATION_THRESHOLD_MIN, ATTENUATION_DURATION_THRESHOLD_MAX);
if (lower > upper) {
String parameters = "attenuation-duration.thresholds.lower, attenuation-duration.thresholds.upper";
@@ -67,10 +73,10 @@ private void validateThresholds() {
}
}
- private void checkThresholdBound(String thresholdLabel, int thresholdValue) {
- if (thresholdValue < ATTENUATION_DURATION_THRESHOLD_MIN || thresholdValue > ATTENUATION_DURATION_THRESHOLD_MAX) {
+ private void checkValueRange(String parameterLabel, int value, int min, int max) {
+ if (value < min || value > max) {
this.errors.add(new GeneralValidationError(
- "attenuation-duration.thresholds." + thresholdLabel, thresholdValue, VALUE_OUT_OF_BOUNDS));
+ "attenuation-duration." + parameterLabel, value, VALUE_OUT_OF_BOUNDS));
}
}
@@ -91,4 +97,15 @@ private void checkWeight(String weightLabel, double weightValue) {
"attenuation-duration.weights." + weightLabel, weightValue, TOO_MANY_DECIMAL_PLACES));
}
}
+
+ private void validateDefaultBucketOffset() {
+ int bucketOffset = attenuationDuration.getDefaultBucketOffset();
+ checkValueRange("default-bucket-offset", bucketOffset, DEFAULT_BUCKET_OFFSET_MIN, DEFAULT_BUCKET_OFFSET_MAX);
+ }
+
+ private void validateRiskScoreNormalizationDivisor() {
+ int riskScoreNormalizationDivisor = attenuationDuration.getRiskScoreNormalizationDivisor();
+ checkValueRange("risk-score-normalization-divisor", riskScoreNormalizationDivisor,
+ RISK_SCORE_NORMALIZATION_DIVISOR_MIN, RISK_SCORE_NORMALIZATION_DIVISOR_MAX);
+ }
}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ParameterSpec.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ParameterSpec.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ParameterSpec.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ParameterSpec.java
@@ -78,4 +78,25 @@ private ParameterSpec() {
* Maximum number of allowed decimals for an attenuation weight.
*/
public static final int ATTENUATION_DURATION_WEIGHT_MAX_DECIMALS = 3;
+
+
+ /**
+ * The allowed minimum value for a default bucket offset.
+ */
+ public static final int DEFAULT_BUCKET_OFFSET_MIN = 0;
+
+ /**
+ * The allowed maximum value for a default bucket offset.
+ */
+ public static final int DEFAULT_BUCKET_OFFSET_MAX = 1;
+
+ /**
+ * The allowed minimum value for a risk score normalization divisor.
+ */
+ public static final int RISK_SCORE_NORMALIZATION_DIVISOR_MIN = 0;
+
+ /**
+ * The allowed maximum value for a risk score normalization divisor.
+ */
+ public static final int RISK_SCORE_NORMALIZATION_DIVISOR_MAX = 1000;
}
diff --git a/services/distribution/src/main/resources/master-config/attenuation-duration.yaml b/services/distribution/src/main/resources/master-config/attenuation-duration.yaml
--- a/services/distribution/src/main/resources/master-config/attenuation-duration.yaml
+++ b/services/distribution/src/main/resources/master-config/attenuation-duration.yaml
@@ -4,6 +4,9 @@
# Each of the aforementioned partitions has a weight in the range of [0, 1]
# assigned to it. The number of decimal places is restricted to 3.
#
+# default-bucket-offset value range: {0, 1}
+# risk-score-normalization-divisor value range: [1, 1000]
+#
# Change this file with caution!
thresholds:
@@ -13,3 +16,5 @@ weights:
low: 1.0
mid: 0.5
high: 0.0
+default-bucket-offset: 0
+risk-score-normalization-divisor: 25
</patch> | diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/AttenuationDurationValidatorTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/AttenuationDurationValidatorTest.java
--- a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/AttenuationDurationValidatorTest.java
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/AttenuationDurationValidatorTest.java
@@ -26,6 +26,10 @@
import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.ParameterSpec.ATTENUATION_DURATION_THRESHOLD_MIN;
import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.ParameterSpec.ATTENUATION_DURATION_WEIGHT_MAX;
import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.ParameterSpec.ATTENUATION_DURATION_WEIGHT_MIN;
+import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.ParameterSpec.DEFAULT_BUCKET_OFFSET_MAX;
+import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.ParameterSpec.DEFAULT_BUCKET_OFFSET_MIN;
+import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.ParameterSpec.RISK_SCORE_NORMALIZATION_DIVISOR_MAX;
+import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.ParameterSpec.RISK_SCORE_NORMALIZATION_DIVISOR_MIN;
import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.RiskScoreClassificationValidatorTest.buildError;
import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.RiskScoreClassificationValidatorTest.buildExpectedResult;
import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.WeightValidationError.ErrorType.OUT_OF_RANGE;
@@ -44,12 +48,14 @@ public class AttenuationDurationValidatorTest {
buildThresholds(ATTENUATION_DURATION_THRESHOLD_MIN, ATTENUATION_DURATION_THRESHOLD_MAX);
private static final Weights VALID_WEIGHTS =
buildWeights(ATTENUATION_DURATION_WEIGHT_MAX, ATTENUATION_DURATION_WEIGHT_MAX, ATTENUATION_DURATION_WEIGHT_MAX);
+ private static final int VALID_BUCKET_OFFSET = DEFAULT_BUCKET_OFFSET_MAX;
+ private static final int VALID_NORMALIZATION_DIVISOR = RISK_SCORE_NORMALIZATION_DIVISOR_MIN;
@ParameterizedTest
@ValueSource(ints = {ATTENUATION_DURATION_THRESHOLD_MIN - 1, ATTENUATION_DURATION_THRESHOLD_MAX + 1})
void failsIfAttenuationDurationThresholdOutOfBounds(int invalidThresholdValue) {
AttenuationDurationValidator validator = buildValidator(
- buildThresholds(invalidThresholdValue, invalidThresholdValue), VALID_WEIGHTS);
+ buildThresholds(invalidThresholdValue, invalidThresholdValue));
ValidationResult expectedResult = buildExpectedResult(
buildError("attenuation-duration.thresholds.lower", invalidThresholdValue, VALUE_OUT_OF_BOUNDS),
@@ -58,10 +64,35 @@ void failsIfAttenuationDurationThresholdOutOfBounds(int invalidThresholdValue) {
assertThat(validator.validate()).isEqualTo(expectedResult);
}
+ @ParameterizedTest
+ @ValueSource(ints = {DEFAULT_BUCKET_OFFSET_MIN - 1, DEFAULT_BUCKET_OFFSET_MAX + 1})
+ void failsIfBucketOffsetOutOfBounds(int invalidDefaultBucketOffsetValue) {
+ AttenuationDurationValidator validator = buildValidator(VALID_THRESHOLDS, VALID_WEIGHTS,
+ invalidDefaultBucketOffsetValue, VALID_NORMALIZATION_DIVISOR);
+
+ ValidationResult expectedResult = buildExpectedResult(
+ buildError("attenuation-duration.default-bucket-offset", invalidDefaultBucketOffsetValue, VALUE_OUT_OF_BOUNDS));
+
+ assertThat(validator.validate()).isEqualTo(expectedResult);
+ }
+
+ @ParameterizedTest
+ @ValueSource(ints = {RISK_SCORE_NORMALIZATION_DIVISOR_MIN - 1, RISK_SCORE_NORMALIZATION_DIVISOR_MAX + 1})
+ void failsIfRiskScoreNormalizationDivisorOutOfBounds(int invalidRiskScoreNormalizationDivisorValue) {
+ AttenuationDurationValidator validator = buildValidator(VALID_THRESHOLDS, VALID_WEIGHTS, VALID_BUCKET_OFFSET,
+ invalidRiskScoreNormalizationDivisorValue);
+
+ ValidationResult expectedResult = buildExpectedResult(
+ buildError("attenuation-duration.risk-score-normalization-divisor", invalidRiskScoreNormalizationDivisorValue,
+ VALUE_OUT_OF_BOUNDS));
+
+ assertThat(validator.validate()).isEqualTo(expectedResult);
+ }
+
@Test
void failsIfUpperAttenuationDurationThresholdLesserThanLower() {
AttenuationDurationValidator validator = buildValidator(
- buildThresholds(ATTENUATION_DURATION_THRESHOLD_MAX, ATTENUATION_DURATION_THRESHOLD_MIN), VALID_WEIGHTS);
+ buildThresholds(ATTENUATION_DURATION_THRESHOLD_MAX, ATTENUATION_DURATION_THRESHOLD_MIN));
ValidationResult expectedResult = buildExpectedResult(
new GeneralValidationError("attenuation-duration.thresholds.lower, attenuation-duration.thresholds.upper",
@@ -73,7 +104,7 @@ void failsIfUpperAttenuationDurationThresholdLesserThanLower() {
@ParameterizedTest
@ValueSource(doubles = {ATTENUATION_DURATION_WEIGHT_MIN - .1, ATTENUATION_DURATION_WEIGHT_MAX + .1})
void failsIfWeightsOutOfBounds(double invalidWeightValue) {
- AttenuationDurationValidator validator = buildValidator(VALID_THRESHOLDS,
+ AttenuationDurationValidator validator = buildValidator(
buildWeights(invalidWeightValue, invalidWeightValue, invalidWeightValue));
ValidationResult expectedResult = buildExpectedResult(
@@ -87,7 +118,7 @@ void failsIfWeightsOutOfBounds(double invalidWeightValue) {
@Test
void failsIfWeightsHaveTooManyDecimalPlaces() {
double invalidWeightValue = ATTENUATION_DURATION_WEIGHT_MAX - 0.0000001;
- AttenuationDurationValidator validator = buildValidator(VALID_THRESHOLDS,
+ AttenuationDurationValidator validator = buildValidator(
buildWeights(invalidWeightValue, invalidWeightValue, invalidWeightValue));
ValidationResult expectedResult = buildExpectedResult(
@@ -98,10 +129,22 @@ void failsIfWeightsHaveTooManyDecimalPlaces() {
assertThat(validator.validate()).isEqualTo(expectedResult);
}
- private static AttenuationDurationValidator buildValidator(Thresholds thresholds, Weights weights) {
+ private static AttenuationDurationValidator buildValidator(Thresholds thresholds) {
+ return buildValidator(thresholds, VALID_WEIGHTS, VALID_BUCKET_OFFSET, VALID_NORMALIZATION_DIVISOR);
+ }
+
+ private static AttenuationDurationValidator buildValidator(Weights weights) {
+ return buildValidator(VALID_THRESHOLDS, weights, VALID_BUCKET_OFFSET, VALID_NORMALIZATION_DIVISOR);
+ }
+
+ private static AttenuationDurationValidator buildValidator(
+ Thresholds thresholds, Weights weights, int defaultBucketOffset, int riskScoreNormalizationDivisor) {
return new AttenuationDurationValidator(AttenuationDuration.newBuilder()
.setThresholds(thresholds)
- .setWeights(weights).build());
+ .setWeights(weights)
+ .setDefaultBucketOffset(defaultBucketOffset)
+ .setRiskScoreNormalizationDivisor(riskScoreNormalizationDivisor)
+ .build());
}
private static Thresholds buildThresholds(int lower, int upper) {
diff --git a/services/distribution/src/test/resources/configtests/attenuation-duration.yaml b/services/distribution/src/test/resources/configtests/attenuation-duration.yaml
--- a/services/distribution/src/test/resources/configtests/attenuation-duration.yaml
+++ b/services/distribution/src/test/resources/configtests/attenuation-duration.yaml
@@ -5,3 +5,5 @@ weights:
low: 1.0
mid: 0.5
high: 0.0
+default-bucket-offset: 0
+risk-score-normalization-divisor: 25
| ||||
corona-warn-app__cwa-server-541 | You will be provided with a partial code base and an issue statement explaining a problem to resolve.
<issue>
SSL: Set a profile to willingly decrease security
Currently, we have the profiles `ssl-server`, `ssl-client-verification` and `ssl-client-postgres` which will enable `ssl` for certain situations.
In context of secure-by-default, we should have it in the opposite way - you can set a profile to willingly decrease security.
</issue>
<code>
[start of README.md]
1 <!-- markdownlint-disable MD041 -->
2 <h1 align="center">
3 Corona-Warn-App Server
4 </h1>
5
6 <p align="center">
7 <a href="https://github.com/corona-warn-app/cwa-server/commits/" title="Last Commit"><img src="https://img.shields.io/github/last-commit/corona-warn-app/cwa-server?style=flat"></a>
8 <a href="https://github.com/corona-warn-app/cwa-server/issues" title="Open Issues"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat"></a>
9 <a href="https://circleci.com/gh/corona-warn-app/cwa-server" title="Build Status"><img src="https://circleci.com/gh/corona-warn-app/cwa-server.svg?style=shield&circle-token=4ab059989d10709df19eb4b98ab7c121a25e981a"></a>
10 <a href="https://sonarcloud.io/dashboard?id=corona-warn-app_cwa-server" title="Quality Gate"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=alert_status"></a>
11 <a href="https://sonarcloud.io/component_measures?id=corona-warn-app_cwa-server&metric=Coverage&view=list" title="Coverage"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=coverage"></a>
12 <a href="https://github.com/corona-warn-app/cwa-server/blob/master/LICENSE" title="License"><img src="https://img.shields.io/badge/License-Apache%202.0-green.svg?style=flat"></a>
13 </p>
14
15 <p align="center">
16 <a href="#development">Development</a> •
17 <a href="#service-apis">Service APIs</a> •
18 <a href="#documentation">Documentation</a> •
19 <a href="#support-and-feedback">Support</a> •
20 <a href="#how-to-contribute">Contribute</a> •
21 <a href="#contributors">Contributors</a> •
22 <a href="#repositories">Repositories</a> •
23 <a href="#licensing">Licensing</a>
24 </p>
25
26 The goal of this project is to develop the official Corona-Warn-App for Germany based on the exposure notification API from [Apple](https://www.apple.com/covid19/contacttracing/) and [Google](https://www.google.com/covid19/exposurenotifications/). The apps (for both iOS and Android) use Bluetooth technology to exchange anonymous encrypted data with other mobile phones (on which the app is also installed) in the vicinity of an app user's phone. The data is stored locally on each user's device, preventing authorities or other parties from accessing or controlling the data. This repository contains the **implementation of the server for encryption keys** for the Corona-Warn-App.
27
28 In this documentation, Corona-Warn-App services are also referred to as CWA services.
29
30 ## Architecture Overview
31
32 You can find the architecture overview [here](/docs/ARCHITECTURE.md), which will give you
33 a good starting point in how the backend services interact with other services, and what purpose
34 they serve.
35
36 ## Development
37
38 After you've checked out this repository, you can run the application in one of the following ways:
39
40 * As a [Docker](https://www.docker.com/)-based deployment on your local machine. You can run either:
41 * Single components using the respective Dockerfile or
42 * The full backend using the Docker Compose (which is considered the most convenient way)
43 * As a [Maven](https://maven.apache.org)-based build on your local machine.
44 If you want to develop something in a single component, this approach is preferable.
45
46 ### Docker-Based Deployment
47
48 If you want to use Docker-based deployment, you need to install Docker on your local machine. For more information about downloading and installing Docker, see the [official Docker documentation](https://docs.docker.com/get-docker/).
49
50 #### Running the Full CWA Backend Using Docker Compose
51
52 For your convenience, a full setup including the generation of test data has been prepared using [Docker Compose](https://docs.docker.com/compose/reference/overview/). To build the backend services, run ```docker-compose build``` in the repository's root directory. A default configuration file can be found under ```.env``` in the root folder of the repository. The default values for the local Postgres and Zenko Cloudserver should be changed in this file before docker-compose is run.
53
54 Once the services are built, you can start the whole backend using ```docker-compose up```.
55 The distribution service runs once and then finishes. If you want to trigger additional distribution runs, run ```docker-compose run distribution```.
56
57 The docker-compose contains the following services:
58
59 Service | Description | Endpoint and Default Credentials
60 ------------------|-------------|-----------
61 submission | The Corona-Warn-App submission service | `http://localhost:8000` <br> `http://localhost:8006` (for actuator endpoint)
62 distribution | The Corona-Warn-App distribution service | NO ENDPOINT
63 postgres | A [postgres] database installation | `localhost:8001` <br> `postgres:5432` (from containerized pgadmin) <br> Username: postgres <br> Password: postgres
64 pgadmin | A [pgadmin](https://www.pgadmin.org/) installation for the postgres database | `http://localhost:8002` <br> Username: [email protected] <br> Password: password
65 cloudserver | [Zenko CloudServer] is a S3-compliant object store | `http://localhost:8003/` <br> Access key: accessKey1 <br> Secret key: verySecretKey1
66 verification-fake | A very simple fake implementation for the tan verification. | `http://localhost:8004/version/v1/tan/verify` <br> The only valid tan is `edc07f08-a1aa-11ea-bb37-0242ac130002`.
67
68 ##### Known Limitation
69
70 In rare cases the docker-compose runs into a timing issue if the distribution service starts before the bucket of the objectstore was created. This is not a big issue as you can simply run ```docker-compose run distribution``` to trigger additional distribution runs after the objectstore was initialized.
71
72 #### Running Single CWA Services Using Docker
73
74 If you would like to build and run a single CWA service, it's considered easiest to run them in a Docker environment. You can do this using the script provided in the respective CWA service directory. The Docker script first builds the CWA service and then creates an image for the runtime, which means that there are no additional dependencies for you to install.
75
76 To build and run the distribution service, run the following command:
77
78 ```bash
79 ./services/distribution/build_and_run.sh
80 ```
81
82 To build and run the submission service, run the following command:
83
84 ```bash
85 ./services/submission/build_and_run.sh
86 ```
87
88 The submission service is available on [localhost:8080](http://localhost:8080 ).
89
90 ### Maven-Based Build
91
92 If you want to actively develop in one of the CWA services, the Maven-based runtime is most suitable.
93 To prepare your machine to run the CWA project locally, we recommend that you first ensure that you've installed the following:
94
95 * Minimum JDK Version 11: [OpenJDK](https://openjdk.java.net/) / [SapMachine](https://sap.github.io/SapMachine/)
96 * [Maven 3.6](https://maven.apache.org/)
97 * [Postgres]
98 * [Zenko CloudServer]
99
100 If you are already running a local Postgres, you need to create a database `cwa` and run the following setup scripts:
101
102 * Create the different CWA roles first by executing [create-roles.sql](setup/create-roles.sql).
103 * Create local database users for the specific roles by running [create-users.sql](./local-setup/create-users.sql).
104 * It is recommended to also run [enable-test-data-docker-compose.sql](./local-setup/enable-test-data-docker-compose.sql)
105 , which enables the test data generation profile. If you already had CWA running before and an existing `diagnosis-key`
106 table on your database, you need to run [enable-test-data.sql](./local-setup/enable-test-data.sql) instead.
107
108 You can also use `docker-compose` to start Postgres and Zenko. If you do that, you have to
109 set the following environment-variables when running the Spring project:
110
111 For the distribution module:
112
113 ```bash
114 POSTGRESQL_SERVICE_PORT=8001
115 VAULT_FILESIGNING_SECRET=</path/to/your/private_key>
116 ```
117
118 For the submission module:
119
120 ```bash
121 POSTGRESQL_SERVICE_PORT=8001
122 ```
123
124 #### Configure
125
126 After you made sure that the specified dependencies are running, configure them in the respective configuration files.
127
128 * Configure the Postgres connection in the [submission config](./services/submission/src/main/resources/application.yaml) and in the [distribution config](./services/distribution/src/main/resources/application.yaml)
129 * Configure the S3 compatible object storage in the [distribution config](./services/distribution/src/main/resources/application.yaml)
130 * Configure the private key for the distribution service, the path need to be prefixed with `file:`
131 * `VAULT_FILESIGNING_SECRET` should be the path to the private key, example available in `<repo-root>/docker-compose-test-secrets/private.pem`
132
133 #### Build
134
135 After you've checked out the repository, to build the project, run ```mvn install``` in your base directory.
136
137 #### Run
138
139 Navigate to the service you want to start and run the spring-boot:run target. The configured Postgres and the configured S3 compliant object storage are used as default. When you start the submission service, the endpoint is available on your local port 8080.
140
141 If you want to start the submission service, for example, you start it as follows:
142
143 ```bash
144 cd services/submission/
145 mvn spring-boot:run
146 ```
147
148 #### Debugging
149
150 To enable the `DEBUG` log level, you can run the application using the Spring `dev` profile.
151
152 ```bash
153 mvn spring-boot:run -Dspring.profiles.active=dev
154 ```
155
156 To be able to set breakpoints (e.g. in IntelliJ), it may be necessary to use the ```-Dspring-boot.run.fork=false``` parameter.
157
158 ## Service APIs
159
160 The API that is being exposed by the backend services is documented in an [OpenAPI](https://www.openapis.org/) specification. The specification files are available at the following locations:
161
162 Service | OpenAPI Specification
163 -------------|-------------
164 Submission Service | [services/submission/api_v1.json](https://github.com/corona-warn-app/cwa-server/raw/master/services/submission/api_v1.json)
165 Distribution Service | [services/distribution/api_v1.json](https://github.com/corona-warn-app/cwa-server/raw/master/services/distribution/api_v1.json)
166
167 ## Spring Profiles
168
169 ### Distribution
170
171 Profile | Effect
172 ----------------------|-------------
173 `dev` | Turns the log level to `DEBUG`.
174 `cloud` | Removes default values for the `datasource` and `objectstore` configurations.
175 `demo` | Includes incomplete days and hours into the distribution run, thus creating aggregates for the current day and the current hour (and including both in the respective indices). When running multiple distributions in one hour with this profile, the date aggregate for today and the hours aggregate for the current hour will be updated and overwritten. This profile also turns off the expiry policy (Keys must be expired for at least 2 hours before distribution) and the shifting policy (there must be at least 140 keys in a distribution).
176 `testdata` | Causes test data to be inserted into the database before each distribution run. By default, around 1000 random diagnosis keys will be generated per hour. If there are no diagnosis keys in the database yet, random keys will be generated for every hour from the beginning of the retention period (14 days ago at 00:00 UTC) until one hour before the present hour. If there are already keys in the database, the random keys will be generated for every hour from the latest diagnosis key in the database (by submission timestamp) until one hour before the present hour (or none at all, if the latest diagnosis key in the database was submitted one hour ago or later).
177 `signature-dev` | Sets the app package ID in the export packages' signature info to `de.rki.coronawarnapp-dev` so that the non-productive/test public key will be used for client-side validation.
178 `signature-prod` | Sets the app package ID in the export packages' signature info to `de.rki.coronawarnapp` so that the productive public key will be used for client-side validation.
179 `ssl-client-postgres` | Enforces SSL with a pinned certificate for the connection to the postgres (see [here](https://github.com/corona-warn-app/cwa-server/blob/master/services/distribution/src/main/resources/application-ssl-client-postgres.yaml)).
180
181 ### Submission
182
183 Profile | Effect
184 --------------------------|-------------
185 `dev` | Turns the log level to `DEBUG`.
186 `cloud` | Removes default values for the `datasource` configuration.
187 `ssl-server` | Enables SSL for the submission endpoint (see [here](https://github.com/corona-warn-app/cwa-server/blob/master/services/submission/src/main/resources/application-ssl-server.yaml)).
188 `ssl-client-postgres` | Enforces SSL with a pinned certificate for the connection to the postgres (see [here](https://github.com/corona-warn-app/cwa-server/blob/master/services/submission/src/main/resources/application-ssl-client-postgres.yaml)).
189 `ssl-client-verification` | Enforces SSL with a pinned certificate for the connection to the verification server (see [here](https://github.com/corona-warn-app/cwa-server/blob/master/services/submission/src/main/resources/application-ssl-client-verification.yaml)).
190
191 ## Documentation
192
193 The full documentation for the Corona-Warn-App can be found in the [cwa-documentation](https://github.com/corona-warn-app/cwa-documentation) repository. The documentation repository contains technical documents, architecture information, and whitepapers related to this implementation.
194
195 ## Support and Feedback
196
197 The following channels are available for discussions, feedback, and support requests:
198
199 | Type | Channel |
200 | ------------------------ | ------------------------------------------------------ |
201 | **General Discussion** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="General Discussion"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/question.svg?style=flat-square"></a> </a> |
202 | **Concept Feedback** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="Open Concept Feedback"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/architecture.svg?style=flat-square"></a> |
203 | **Backend Issue** | <a href="https://github.com/corona-warn-app/cwa-server/issues/new/choose" title="Open Backend Issue"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat-square"></a> |
204 | **Other Requests** | <a href="mailto:[email protected]" title="Email CWA Team"><img src="https://img.shields.io/badge/email-CWA%20team-green?logo=mail.ru&style=flat-square&logoColor=white"></a> |
205
206 ## How to Contribute
207
208 Contribution and feedback are 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.
209
210 ## Contributors
211
212 The German government has asked SAP and Deutsche Telekom to develop the Corona-Warn-App for Germany as open source software. Deutsche Telekom is providing the network and mobile technology and will operate and run the backend for the app in a safe, scalable and stable manner. SAP is responsible for the app development, its framework and the underlying platform. Therefore, development teams of SAP and Deutsche Telekom are contributing to this project. At the same time 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.
213
214 ## Repositories
215
216 The following public repositories are currently available for the Corona-Warn-App:
217
218 | Repository | Description |
219 | ------------------- | --------------------------------------------------------------------- |
220 | [cwa-documentation] | Project overview, general documentation, and white papers |
221 | [cwa-server] | Backend implementation for the Apple/Google exposure notification API|
222 | [cwa-verification-server] | Backend implementation of the verification process|
223
224 [cwa-documentation]: https://github.com/corona-warn-app/cwa-documentation
225 [cwa-server]: https://github.com/corona-warn-app/cwa-server
226 [cwa-verification-server]: https://github.com/corona-warn-app/cwa-verification-server
227 [Postgres]: https://www.postgresql.org/
228 [HSQLDB]: http://hsqldb.org/
229 [Zenko CloudServer]: https://github.com/scality/cloudserver
230
231 ## Licensing
232
233 Copyright (c) 2020 SAP SE or an SAP affiliate company.
234
235 Licensed under the **Apache License, Version 2.0** (the "License"); you may not use this file except in compliance with the License.
236
237 You may obtain a copy of the License at <https://www.apache.org/licenses/LICENSE-2.0>.
238
239 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.
240
[end of README.md]
[start of /dev/null]
1
[end of /dev/null]
[start of README.md]
1 <!-- markdownlint-disable MD041 -->
2 <h1 align="center">
3 Corona-Warn-App Server
4 </h1>
5
6 <p align="center">
7 <a href="https://github.com/corona-warn-app/cwa-server/commits/" title="Last Commit"><img src="https://img.shields.io/github/last-commit/corona-warn-app/cwa-server?style=flat"></a>
8 <a href="https://github.com/corona-warn-app/cwa-server/issues" title="Open Issues"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat"></a>
9 <a href="https://circleci.com/gh/corona-warn-app/cwa-server" title="Build Status"><img src="https://circleci.com/gh/corona-warn-app/cwa-server.svg?style=shield&circle-token=4ab059989d10709df19eb4b98ab7c121a25e981a"></a>
10 <a href="https://sonarcloud.io/dashboard?id=corona-warn-app_cwa-server" title="Quality Gate"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=alert_status"></a>
11 <a href="https://sonarcloud.io/component_measures?id=corona-warn-app_cwa-server&metric=Coverage&view=list" title="Coverage"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=coverage"></a>
12 <a href="https://github.com/corona-warn-app/cwa-server/blob/master/LICENSE" title="License"><img src="https://img.shields.io/badge/License-Apache%202.0-green.svg?style=flat"></a>
13 </p>
14
15 <p align="center">
16 <a href="#development">Development</a> •
17 <a href="#service-apis">Service APIs</a> •
18 <a href="#documentation">Documentation</a> •
19 <a href="#support-and-feedback">Support</a> •
20 <a href="#how-to-contribute">Contribute</a> •
21 <a href="#contributors">Contributors</a> •
22 <a href="#repositories">Repositories</a> •
23 <a href="#licensing">Licensing</a>
24 </p>
25
26 The goal of this project is to develop the official Corona-Warn-App for Germany based on the exposure notification API from [Apple](https://www.apple.com/covid19/contacttracing/) and [Google](https://www.google.com/covid19/exposurenotifications/). The apps (for both iOS and Android) use Bluetooth technology to exchange anonymous encrypted data with other mobile phones (on which the app is also installed) in the vicinity of an app user's phone. The data is stored locally on each user's device, preventing authorities or other parties from accessing or controlling the data. This repository contains the **implementation of the server for encryption keys** for the Corona-Warn-App.
27
28 In this documentation, Corona-Warn-App services are also referred to as CWA services.
29
30 ## Architecture Overview
31
32 You can find the architecture overview [here](/docs/ARCHITECTURE.md), which will give you
33 a good starting point in how the backend services interact with other services, and what purpose
34 they serve.
35
36 ## Development
37
38 After you've checked out this repository, you can run the application in one of the following ways:
39
40 * As a [Docker](https://www.docker.com/)-based deployment on your local machine. You can run either:
41 * Single components using the respective Dockerfile or
42 * The full backend using the Docker Compose (which is considered the most convenient way)
43 * As a [Maven](https://maven.apache.org)-based build on your local machine.
44 If you want to develop something in a single component, this approach is preferable.
45
46 ### Docker-Based Deployment
47
48 If you want to use Docker-based deployment, you need to install Docker on your local machine. For more information about downloading and installing Docker, see the [official Docker documentation](https://docs.docker.com/get-docker/).
49
50 #### Running the Full CWA Backend Using Docker Compose
51
52 For your convenience, a full setup including the generation of test data has been prepared using [Docker Compose](https://docs.docker.com/compose/reference/overview/). To build the backend services, run ```docker-compose build``` in the repository's root directory. A default configuration file can be found under ```.env``` in the root folder of the repository. The default values for the local Postgres and Zenko Cloudserver should be changed in this file before docker-compose is run.
53
54 Once the services are built, you can start the whole backend using ```docker-compose up```.
55 The distribution service runs once and then finishes. If you want to trigger additional distribution runs, run ```docker-compose run distribution```.
56
57 The docker-compose contains the following services:
58
59 Service | Description | Endpoint and Default Credentials
60 ------------------|-------------|-----------
61 submission | The Corona-Warn-App submission service | `http://localhost:8000` <br> `http://localhost:8006` (for actuator endpoint)
62 distribution | The Corona-Warn-App distribution service | NO ENDPOINT
63 postgres | A [postgres] database installation | `localhost:8001` <br> `postgres:5432` (from containerized pgadmin) <br> Username: postgres <br> Password: postgres
64 pgadmin | A [pgadmin](https://www.pgadmin.org/) installation for the postgres database | `http://localhost:8002` <br> Username: [email protected] <br> Password: password
65 cloudserver | [Zenko CloudServer] is a S3-compliant object store | `http://localhost:8003/` <br> Access key: accessKey1 <br> Secret key: verySecretKey1
66 verification-fake | A very simple fake implementation for the tan verification. | `http://localhost:8004/version/v1/tan/verify` <br> The only valid tan is `edc07f08-a1aa-11ea-bb37-0242ac130002`.
67
68 ##### Known Limitation
69
70 In rare cases the docker-compose runs into a timing issue if the distribution service starts before the bucket of the objectstore was created. This is not a big issue as you can simply run ```docker-compose run distribution``` to trigger additional distribution runs after the objectstore was initialized.
71
72 #### Running Single CWA Services Using Docker
73
74 If you would like to build and run a single CWA service, it's considered easiest to run them in a Docker environment. You can do this using the script provided in the respective CWA service directory. The Docker script first builds the CWA service and then creates an image for the runtime, which means that there are no additional dependencies for you to install.
75
76 To build and run the distribution service, run the following command:
77
78 ```bash
79 ./services/distribution/build_and_run.sh
80 ```
81
82 To build and run the submission service, run the following command:
83
84 ```bash
85 ./services/submission/build_and_run.sh
86 ```
87
88 The submission service is available on [localhost:8080](http://localhost:8080 ).
89
90 ### Maven-Based Build
91
92 If you want to actively develop in one of the CWA services, the Maven-based runtime is most suitable.
93 To prepare your machine to run the CWA project locally, we recommend that you first ensure that you've installed the following:
94
95 * Minimum JDK Version 11: [OpenJDK](https://openjdk.java.net/) / [SapMachine](https://sap.github.io/SapMachine/)
96 * [Maven 3.6](https://maven.apache.org/)
97 * [Postgres]
98 * [Zenko CloudServer]
99
100 If you are already running a local Postgres, you need to create a database `cwa` and run the following setup scripts:
101
102 * Create the different CWA roles first by executing [create-roles.sql](setup/create-roles.sql).
103 * Create local database users for the specific roles by running [create-users.sql](./local-setup/create-users.sql).
104 * It is recommended to also run [enable-test-data-docker-compose.sql](./local-setup/enable-test-data-docker-compose.sql)
105 , which enables the test data generation profile. If you already had CWA running before and an existing `diagnosis-key`
106 table on your database, you need to run [enable-test-data.sql](./local-setup/enable-test-data.sql) instead.
107
108 You can also use `docker-compose` to start Postgres and Zenko. If you do that, you have to
109 set the following environment-variables when running the Spring project:
110
111 For the distribution module:
112
113 ```bash
114 POSTGRESQL_SERVICE_PORT=8001
115 VAULT_FILESIGNING_SECRET=</path/to/your/private_key>
116 ```
117
118 For the submission module:
119
120 ```bash
121 POSTGRESQL_SERVICE_PORT=8001
122 ```
123
124 #### Configure
125
126 After you made sure that the specified dependencies are running, configure them in the respective configuration files.
127
128 * Configure the Postgres connection in the [submission config](./services/submission/src/main/resources/application.yaml) and in the [distribution config](./services/distribution/src/main/resources/application.yaml)
129 * Configure the S3 compatible object storage in the [distribution config](./services/distribution/src/main/resources/application.yaml)
130 * Configure the private key for the distribution service, the path need to be prefixed with `file:`
131 * `VAULT_FILESIGNING_SECRET` should be the path to the private key, example available in `<repo-root>/docker-compose-test-secrets/private.pem`
132
133 #### Build
134
135 After you've checked out the repository, to build the project, run ```mvn install``` in your base directory.
136
137 #### Run
138
139 Navigate to the service you want to start and run the spring-boot:run target. The configured Postgres and the configured S3 compliant object storage are used as default. When you start the submission service, the endpoint is available on your local port 8080.
140
141 If you want to start the submission service, for example, you start it as follows:
142
143 ```bash
144 cd services/submission/
145 mvn spring-boot:run
146 ```
147
148 #### Debugging
149
150 To enable the `DEBUG` log level, you can run the application using the Spring `dev` profile.
151
152 ```bash
153 mvn spring-boot:run -Dspring.profiles.active=dev
154 ```
155
156 To be able to set breakpoints (e.g. in IntelliJ), it may be necessary to use the ```-Dspring-boot.run.fork=false``` parameter.
157
158 ## Service APIs
159
160 The API that is being exposed by the backend services is documented in an [OpenAPI](https://www.openapis.org/) specification. The specification files are available at the following locations:
161
162 Service | OpenAPI Specification
163 -------------|-------------
164 Submission Service | [services/submission/api_v1.json](https://github.com/corona-warn-app/cwa-server/raw/master/services/submission/api_v1.json)
165 Distribution Service | [services/distribution/api_v1.json](https://github.com/corona-warn-app/cwa-server/raw/master/services/distribution/api_v1.json)
166
167 ## Spring Profiles
168
169 ### Distribution
170
171 Profile | Effect
172 ----------------------|-------------
173 `dev` | Turns the log level to `DEBUG`.
174 `cloud` | Removes default values for the `datasource` and `objectstore` configurations.
175 `demo` | Includes incomplete days and hours into the distribution run, thus creating aggregates for the current day and the current hour (and including both in the respective indices). When running multiple distributions in one hour with this profile, the date aggregate for today and the hours aggregate for the current hour will be updated and overwritten. This profile also turns off the expiry policy (Keys must be expired for at least 2 hours before distribution) and the shifting policy (there must be at least 140 keys in a distribution).
176 `testdata` | Causes test data to be inserted into the database before each distribution run. By default, around 1000 random diagnosis keys will be generated per hour. If there are no diagnosis keys in the database yet, random keys will be generated for every hour from the beginning of the retention period (14 days ago at 00:00 UTC) until one hour before the present hour. If there are already keys in the database, the random keys will be generated for every hour from the latest diagnosis key in the database (by submission timestamp) until one hour before the present hour (or none at all, if the latest diagnosis key in the database was submitted one hour ago or later).
177 `signature-dev` | Sets the app package ID in the export packages' signature info to `de.rki.coronawarnapp-dev` so that the non-productive/test public key will be used for client-side validation.
178 `signature-prod` | Sets the app package ID in the export packages' signature info to `de.rki.coronawarnapp` so that the productive public key will be used for client-side validation.
179 `ssl-client-postgres` | Enforces SSL with a pinned certificate for the connection to the postgres (see [here](https://github.com/corona-warn-app/cwa-server/blob/master/services/distribution/src/main/resources/application-ssl-client-postgres.yaml)).
180
181 ### Submission
182
183 Profile | Effect
184 --------------------------|-------------
185 `dev` | Turns the log level to `DEBUG`.
186 `cloud` | Removes default values for the `datasource` configuration.
187 `ssl-server` | Enables SSL for the submission endpoint (see [here](https://github.com/corona-warn-app/cwa-server/blob/master/services/submission/src/main/resources/application-ssl-server.yaml)).
188 `ssl-client-postgres` | Enforces SSL with a pinned certificate for the connection to the postgres (see [here](https://github.com/corona-warn-app/cwa-server/blob/master/services/submission/src/main/resources/application-ssl-client-postgres.yaml)).
189 `ssl-client-verification` | Enforces SSL with a pinned certificate for the connection to the verification server (see [here](https://github.com/corona-warn-app/cwa-server/blob/master/services/submission/src/main/resources/application-ssl-client-verification.yaml)).
190
191 ## Documentation
192
193 The full documentation for the Corona-Warn-App can be found in the [cwa-documentation](https://github.com/corona-warn-app/cwa-documentation) repository. The documentation repository contains technical documents, architecture information, and whitepapers related to this implementation.
194
195 ## Support and Feedback
196
197 The following channels are available for discussions, feedback, and support requests:
198
199 | Type | Channel |
200 | ------------------------ | ------------------------------------------------------ |
201 | **General Discussion** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="General Discussion"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/question.svg?style=flat-square"></a> </a> |
202 | **Concept Feedback** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="Open Concept Feedback"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/architecture.svg?style=flat-square"></a> |
203 | **Backend Issue** | <a href="https://github.com/corona-warn-app/cwa-server/issues/new/choose" title="Open Backend Issue"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat-square"></a> |
204 | **Other Requests** | <a href="mailto:[email protected]" title="Email CWA Team"><img src="https://img.shields.io/badge/email-CWA%20team-green?logo=mail.ru&style=flat-square&logoColor=white"></a> |
205
206 ## How to Contribute
207
208 Contribution and feedback are 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.
209
210 ## Contributors
211
212 The German government has asked SAP and Deutsche Telekom to develop the Corona-Warn-App for Germany as open source software. Deutsche Telekom is providing the network and mobile technology and will operate and run the backend for the app in a safe, scalable and stable manner. SAP is responsible for the app development, its framework and the underlying platform. Therefore, development teams of SAP and Deutsche Telekom are contributing to this project. At the same time 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.
213
214 ## Repositories
215
216 The following public repositories are currently available for the Corona-Warn-App:
217
218 | Repository | Description |
219 | ------------------- | --------------------------------------------------------------------- |
220 | [cwa-documentation] | Project overview, general documentation, and white papers |
221 | [cwa-server] | Backend implementation for the Apple/Google exposure notification API|
222 | [cwa-verification-server] | Backend implementation of the verification process|
223
224 [cwa-documentation]: https://github.com/corona-warn-app/cwa-documentation
225 [cwa-server]: https://github.com/corona-warn-app/cwa-server
226 [cwa-verification-server]: https://github.com/corona-warn-app/cwa-verification-server
227 [Postgres]: https://www.postgresql.org/
228 [HSQLDB]: http://hsqldb.org/
229 [Zenko CloudServer]: https://github.com/scality/cloudserver
230
231 ## Licensing
232
233 Copyright (c) 2020 SAP SE or an SAP affiliate company.
234
235 Licensed under the **Apache License, Version 2.0** (the "License"); you may not use this file except in compliance with the License.
236
237 You may obtain a copy of the License at <https://www.apache.org/licenses/LICENSE-2.0>.
238
239 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.
240
[end of README.md]
[start of docker-compose.yml]
1 version: '3'
2 services:
3 submission:
4 build:
5 context: ./
6 dockerfile: ./services/submission/Dockerfile
7 depends_on:
8 - postgres
9 - verification-fake
10 ports:
11 - "8000:8080"
12 - "8006:8081"
13 environment:
14 SPRING_PROFILES_ACTIVE: dev
15 POSTGRESQL_SERVICE_PORT: '5432'
16 POSTGRESQL_SERVICE_HOST: postgres
17 POSTGRESQL_DATABASE: ${POSTGRES_DB}
18 POSTGRESQL_PASSWORD_SUBMISION: ${POSTGRES_SUBMISSION_PASSWORD}
19 POSTGRESQL_USER_SUBMISION: ${POSTGRES_SUBMISSION_USER}
20 POSTGRESQL_PASSWORD_FLYWAY: ${POSTGRES_FLYWAY_PASSWORD}
21 POSTGRESQL_USER_FLYWAY: ${POSTGRES_FLYWAY_USER}
22 VERIFICATION_BASE_URL: http://verification-fake:8004
23 distribution:
24 build:
25 context: ./
26 dockerfile: ./services/distribution/Dockerfile
27 depends_on:
28 - postgres
29 - objectstore
30 - create-bucket
31 environment:
32 SPRING_PROFILES_ACTIVE: dev,signature-dev,testdata
33 POSTGRESQL_SERVICE_PORT: '5432'
34 POSTGRESQL_SERVICE_HOST: postgres
35 POSTGRESQL_DATABASE: ${POSTGRES_DB}
36 POSTGRESQL_PASSWORD_DISTRIBUTION: ${POSTGRES_DISTRIBUTION_PASSWORD}
37 POSTGRESQL_USER_DISTRIBUTION: ${POSTGRES_DISTRIBUTION_USER}
38 POSTGRESQL_PASSWORD_FLYWAY: ${POSTGRES_FLYWAY_PASSWORD}
39 POSTGRESQL_USER_FLYWAY: ${POSTGRES_FLYWAY_USER}
40 # Settings for the S3 compatible objectstore
41 CWA_OBJECTSTORE_ACCESSKEY: ${OBJECTSTORE_ACCESSKEY}
42 CWA_OBJECTSTORE_SECRETKEY: ${OBJECTSTORE_SECRETKEY}
43 CWA_OBJECTSTORE_ENDPOINT: http://objectstore
44 CWA_OBJECTSTORE_BUCKET: cwa
45 CWA_OBJECTSTORE_PORT: 8000
46 services.distribution.paths.output: /tmp/distribution
47 # Settings for cryptographic artifacts
48 VAULT_FILESIGNING_SECRET: ${SECRET_PRIVATE}
49 volumes:
50 - ./docker-compose-test-secrets:/secrets
51 postgres:
52 image: postgres:11.8
53 restart: always
54 ports:
55 - "8001:5432"
56 environment:
57 PGDATA: /data/postgres
58 POSTGRES_DB: ${POSTGRES_DB}
59 POSTGRES_USER: ${POSTGRES_USER}
60 POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
61 volumes:
62 - postgres_volume:/data/postgres
63 - ./setup/setup-roles.sql:/docker-entrypoint-initdb.d/1-roles.sql
64 - ./local-setup/create-users.sql:/docker-entrypoint-initdb.d/2-users.sql
65 - ./local-setup/enable-test-data-docker-compose.sql:/docker-entrypoint-initdb.d/3-enable-testdata.sql
66 pgadmin:
67 container_name: pgadmin_container
68 image: dpage/pgadmin4
69 volumes:
70 - pgadmin_volume:/root/.pgadmin
71 ports:
72 - "8002:80"
73 restart: unless-stopped
74 depends_on:
75 - postgres
76 environment:
77 PGADMIN_DEFAULT_EMAIL: ${PGADMIN_DEFAULT_EMAIL}
78 PGADMIN_DEFAULT_PASSWORD: ${PGADMIN_DEFAULT_PASSWORD}
79 objectstore:
80 image: "zenko/cloudserver"
81 volumes:
82 - objectstore_volume:/data
83 ports:
84 - "8003:8000"
85 environment:
86 ENDPOINT: objectstore
87 REMOTE_MANAGEMENT_DISABLE: 1
88 SCALITY_ACCESS_KEY_ID: ${OBJECTSTORE_ACCESSKEY}
89 SCALITY_SECRET_ACCESS_KEY: ${OBJECTSTORE_SECRETKEY}
90 create-bucket:
91 image: amazon/aws-cli
92 environment:
93 - AWS_ACCESS_KEY_ID=${OBJECTSTORE_ACCESSKEY}
94 - AWS_SECRET_ACCESS_KEY=${OBJECTSTORE_SECRETKEY}
95 entrypoint: ["/root/scripts/wait-for-it/wait-for-it.sh", "objectstore:8000", "-t", "30", "--"]
96 volumes:
97 - ./scripts/wait-for-it:/root/scripts/wait-for-it
98 command: aws s3api create-bucket --bucket cwa --endpoint-url http://objectstore:8000 --acl public-read
99 depends_on:
100 - objectstore
101 verification-fake:
102 image: lilienthal/cwa-verification-fake:0.0.3
103 restart: always
104 ports:
105 - "8004:8004"
106 volumes:
107 postgres_volume:
108 pgadmin_volume:
109 objectstore_volume:
110
[end of docker-compose.yml]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/Application.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.distribution;
22
23 import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
24 import org.slf4j.Logger;
25 import org.slf4j.LoggerFactory;
26 import org.springframework.boot.SpringApplication;
27 import org.springframework.boot.autoconfigure.SpringBootApplication;
28 import org.springframework.boot.autoconfigure.domain.EntityScan;
29 import org.springframework.boot.context.properties.EnableConfigurationProperties;
30 import org.springframework.context.ApplicationContext;
31 import org.springframework.context.annotation.ComponentScan;
32 import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
33
34 /**
35 * The retrieval, assembly and distribution of configuration and diagnosis key data is handled by a chain of {@link
36 * org.springframework.boot.ApplicationRunner} instances. An unrecoverable failure in either one of them is terminating
37 * the chain execution.
38 */
39 @SpringBootApplication
40 @EnableJpaRepositories(basePackages = "app.coronawarn.server.common.persistence")
41 @EntityScan(basePackages = "app.coronawarn.server.common.persistence")
42 @ComponentScan({"app.coronawarn.server.common.persistence",
43 "app.coronawarn.server.services.distribution"})
44 @EnableConfigurationProperties({DistributionServiceConfig.class})
45 public class Application {
46
47 private static final Logger logger = LoggerFactory.getLogger(Application.class);
48
49 public static void main(String[] args) {
50 SpringApplication.run(Application.class);
51 }
52
53 /**
54 * Terminates this application with exit code 1 (general error).
55 */
56 public static void killApplication(ApplicationContext appContext) {
57 SpringApplication.exit(appContext);
58 logger.error("Application terminated abnormally.");
59 System.exit(1);
60 }
61 }
62
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/Application.java]
[start of services/distribution/src/main/resources/application-cloud.yaml]
1 ---
2 spring:
3 flyway:
4 password: ${POSTGRESQL_PASSWORD_FLYWAY}
5 user: ${POSTGRESQL_USER_FLYWAY}
6 datasource:
7 driver-class-name: org.postgresql.Driver
8 url: jdbc:postgresql://${POSTGRESQL_SERVICE_HOST}:${POSTGRESQL_SERVICE_PORT}/${POSTGRESQL_DATABASE}
9 username: ${POSTGRESQL_USER_DISTRIBUTION}
10 password: ${POSTGRESQL_PASSWORD_DISTRIBUTION}
11
12 services:
13 distribution:
14 paths:
15 output: /tmp/distribution
16 objectstore:
17 access-key: ${CWA_OBJECTSTORE_ACCESSKEY}
18 secret-key: ${CWA_OBJECTSTORE_SECRETKEY}
19 endpoint: ${CWA_OBJECTSTORE_ENDPOINT}
20 bucket: ${CWA_OBJECTSTORE_BUCKET}
21 port: ${CWA_OBJECTSTORE_PORT}
22 set-public-read-acl-on-put-object: false
23
[end of services/distribution/src/main/resources/application-cloud.yaml]
[start of services/distribution/src/main/resources/application-ssl-client-postgres.yaml]
1 ---
2 spring:
3 datasource:
4 url: jdbc:postgresql://${POSTGRESQL_SERVICE_HOST}:${POSTGRESQL_SERVICE_PORT}/${POSTGRESQL_DATABASE}?ssl=true&sslmode=verify-full&sslrootcert=${SSL_POSTGRES_CERTIFICATE_PATH}&sslcert=${SSL_SUBMISSION_CERTIFICATE_PATH}&sslkey=${SSL_SUBMISSION_PRIVATE_KEY_PATH}
5
[end of services/distribution/src/main/resources/application-ssl-client-postgres.yaml]
[start of services/distribution/src/main/resources/application.yaml]
1 ---
2 logging:
3 level:
4 org:
5 springframework:
6 web: INFO
7 app:
8 coronawarn: INFO
9
10 services:
11 distribution:
12 output-file-name: index
13 retention-days: 14
14 expiry-policy-minutes: 120
15 shifting-policy-threshold: 140
16 maximum-number-of-keys-per-bundle: 600000
17 include-incomplete-days: false
18 include-incomplete-hours: false
19 paths:
20 output: out
21 privatekey: ${VAULT_FILESIGNING_SECRET}
22 tek-export:
23 file-name: export.bin
24 file-header: EK Export v1
25 file-header-width: 16
26 api:
27 version-path: version
28 version-v1: v1
29 country-path: country
30 country-germany: DE
31 date-path: date
32 hour-path: hour
33 diagnosis-keys-path: diagnosis-keys
34 parameters-path: configuration
35 app-config-file-name: app_config
36 signature:
37 verification-key-id: 262
38 verification-key-version: v1
39 algorithm-oid: 1.2.840.10045.4.3.2
40 algorithm-name: SHA256withECDSA
41 file-name: export.sig
42 security-provider: BC
43 # Configuration for the S3 compatible object storage hosted by Telekom in Germany
44 objectstore:
45 access-key: ${CWA_OBJECTSTORE_ACCESSKEY:accessKey1}
46 secret-key: ${CWA_OBJECTSTORE_SECRETKEY:verySecretKey1}
47 endpoint: ${CWA_OBJECTSTORE_ENDPOINT:http://localhost}
48 bucket: ${CWA_OBJECTSTORE_BUCKET:cwa}
49 port: ${CWA_OBJECTSTORE_PORT:8003}
50 set-public-read-acl-on-put-object: true
51 retry-attempts: 3
52 retry-backoff: 2000
53 max-number-of-failed-operations: 5
54 max-number-of-s3-threads: 4
55
56 spring:
57 main:
58 web-application-type: NONE
59 # Postgres configuration
60 jpa:
61 hibernate:
62 ddl-auto: validate
63 flyway:
64 enabled: true
65 locations: classpath:/db/migration, classpath:/db/specific/{vendor}
66 password: ${POSTGRESQL_PASSWORD_FLYWAY:local_setup_flyway}
67 user: ${POSTGRESQL_USER_FLYWAY:local_setup_flyway}
68
69 datasource:
70 driver-class-name: org.postgresql.Driver
71 url: jdbc:postgresql://${POSTGRESQL_SERVICE_HOST:localhost}:${POSTGRESQL_SERVICE_PORT:5432}/${POSTGRESQL_DATABASE:cwa}
72 username: ${POSTGRESQL_USER_DISTRIBUTION:local_setup_distribution}
73 password: ${POSTGRESQL_PASSWORD_DISTRIBUTION:local_setup_distribution}
74
[end of services/distribution/src/main/resources/application.yaml]
[start of services/submission/src/main/java/app/coronawarn/server/services/submission/ServerApplication.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.submission;
22
23 import io.micrometer.core.aop.TimedAspect;
24 import io.micrometer.core.instrument.MeterRegistry;
25 import org.springframework.boot.SpringApplication;
26 import org.springframework.boot.autoconfigure.SpringBootApplication;
27 import org.springframework.boot.autoconfigure.domain.EntityScan;
28 import org.springframework.boot.context.properties.EnableConfigurationProperties;
29 import org.springframework.cloud.openfeign.EnableFeignClients;
30 import org.springframework.context.annotation.Bean;
31 import org.springframework.context.annotation.ComponentScan;
32 import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
33 import org.springframework.http.converter.protobuf.ProtobufHttpMessageConverter;
34
35 @SpringBootApplication
36 @EnableJpaRepositories(basePackages = "app.coronawarn.server.common.persistence")
37 @EntityScan(basePackages = "app.coronawarn.server.common.persistence")
38 @ComponentScan({"app.coronawarn.server.common.persistence",
39 "app.coronawarn.server.services.submission"})
40 @EnableConfigurationProperties
41 @EnableFeignClients
42 public class ServerApplication {
43
44 @Bean
45 TimedAspect timedAspect(MeterRegistry registry) {
46 return new TimedAspect(registry);
47 }
48
49 @Bean
50 ProtobufHttpMessageConverter protobufHttpMessageConverter() {
51 return new ProtobufHttpMessageConverter();
52 }
53
54 public static void main(String[] args) {
55 SpringApplication.run(ServerApplication.class);
56 }
57 }
58
[end of services/submission/src/main/java/app/coronawarn/server/services/submission/ServerApplication.java]
[start of services/submission/src/main/java/app/coronawarn/server/services/submission/config/SubmissionServiceConfig.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.submission.config;
22
23 import org.springframework.boot.context.properties.ConfigurationProperties;
24 import org.springframework.stereotype.Component;
25
26 @Component
27 @ConfigurationProperties(prefix = "services.submission")
28 public class SubmissionServiceConfig {
29
30 // Exponential moving average of the last N real request durations (in ms), where
31 // N = fakeDelayMovingAverageSamples.
32 private Double initialFakeDelayMilliseconds;
33 private Double fakeDelayMovingAverageSamples;
34 private Integer retentionDays;
35 private Payload payload;
36 private Verification verification;
37 private Monitoring monitoring;
38
39 public Double getInitialFakeDelayMilliseconds() {
40 return initialFakeDelayMilliseconds;
41 }
42
43 public void setInitialFakeDelayMilliseconds(Double initialFakeDelayMilliseconds) {
44 this.initialFakeDelayMilliseconds = initialFakeDelayMilliseconds;
45 }
46
47 public Double getFakeDelayMovingAverageSamples() {
48 return fakeDelayMovingAverageSamples;
49 }
50
51 public void setFakeDelayMovingAverageSamples(Double fakeDelayMovingAverageSamples) {
52 this.fakeDelayMovingAverageSamples = fakeDelayMovingAverageSamples;
53 }
54
55 public Integer getRetentionDays() {
56 return retentionDays;
57 }
58
59 public void setRetentionDays(Integer retentionDays) {
60 this.retentionDays = retentionDays;
61 }
62
63 public Integer getMaxNumberOfKeys() {
64 return payload.getMaxNumberOfKeys();
65 }
66
67 public void setPayload(Payload payload) {
68 this.payload = payload;
69 }
70
71 private static class Payload {
72
73 private Integer maxNumberOfKeys;
74
75 public Integer getMaxNumberOfKeys() {
76 return maxNumberOfKeys;
77 }
78
79 public void setMaxNumberOfKeys(Integer maxNumberOfKeys) {
80 this.maxNumberOfKeys = maxNumberOfKeys;
81 }
82 }
83
84 public String getVerificationBaseUrl() {
85 return verification.getBaseUrl();
86 }
87
88 public void setVerification(Verification verification) {
89 this.verification = verification;
90 }
91
92 public String getVerificationPath() {
93 return verification.getPath();
94 }
95
96 private static class Verification {
97 private String baseUrl;
98
99 private String path;
100
101 public String getBaseUrl() {
102 return baseUrl;
103 }
104
105 public String getPath() {
106 return path;
107 }
108
109 public void setBaseUrl(String baseUrl) {
110 this.baseUrl = baseUrl;
111 }
112
113 public void setPath(String path) {
114 this.path = path;
115 }
116 }
117
118 private static class Monitoring {
119 private Long batchSize;
120
121 public Long getBatchSize() {
122 return batchSize;
123 }
124
125 public void setBatchSize(Long batchSize) {
126 this.batchSize = batchSize;
127 }
128 }
129
130 public Monitoring getMonitoring() {
131 return monitoring;
132 }
133
134 public void setMonitoring(Monitoring monitoring) {
135 this.monitoring = monitoring;
136 }
137
138 public Long getMonitoringBatchSize() {
139 return this.monitoring.getBatchSize();
140 }
141
142 public void setMonitoringBatchSize(Long batchSize) {
143 this.monitoring.setBatchSize(batchSize);
144 }
145 }
146
[end of services/submission/src/main/java/app/coronawarn/server/services/submission/config/SubmissionServiceConfig.java]
[start of services/submission/src/main/java/app/coronawarn/server/services/submission/verification/CloudFeignClientProvider.java]
1 /*
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.submission.verification;
22
23 import feign.Client;
24 import feign.httpclient.ApacheHttpClient;
25 import java.io.IOException;
26 import java.security.GeneralSecurityException;
27 import javax.net.ssl.SSLContext;
28 import org.apache.http.impl.client.HttpClientBuilder;
29 import org.apache.http.ssl.SSLContextBuilder;
30 import org.springframework.cloud.commons.httpclient.ApacheHttpClientConnectionManagerFactory;
31 import org.springframework.cloud.commons.httpclient.ApacheHttpClientFactory;
32 import org.springframework.cloud.commons.httpclient.DefaultApacheHttpClientConnectionManagerFactory;
33 import org.springframework.cloud.commons.httpclient.DefaultApacheHttpClientFactory;
34 import org.springframework.context.annotation.Bean;
35 import org.springframework.context.annotation.Profile;
36 import org.springframework.core.env.Environment;
37 import org.springframework.stereotype.Component;
38 import org.springframework.util.ResourceUtils;
39
40 @Component
41 @Profile("ssl-client-verification")
42 public class CloudFeignClientProvider implements FeignClientProvider {
43
44 private final Environment environment;
45 private final HostnameVerifierProvider hostnameVerifierProvider;
46
47 public CloudFeignClientProvider(Environment environment, HostnameVerifierProvider hostnameVerifierProvider) {
48 this.environment = environment;
49 this.hostnameVerifierProvider = hostnameVerifierProvider;
50 }
51
52 @Override
53 public Client createFeignClient() {
54 return new ApacheHttpClient(createHttpClientFactory().createBuilder().build());
55 }
56
57 private SSLContext getSslContext() {
58 try {
59 String keyStorePath = environment.getProperty("client.ssl.key-store");
60 String keyStorePassword = environment.getProperty("client.ssl.key-store-password");
61 String keyPassword = environment.getProperty("client.ssl.key-password");
62
63 String trustStorePath = environment.getProperty("client.ssl.verification.trust-store");
64 String trustStorePassword = environment.getProperty("client.ssl.verification.trust-store-password");
65
66 return SSLContextBuilder
67 .create()
68 .loadKeyMaterial(ResourceUtils.getFile(keyStorePath), keyStorePassword.toCharArray(),
69 keyPassword.toCharArray())
70 .loadTrustMaterial(ResourceUtils.getFile(trustStorePath), trustStorePassword.toCharArray())
71 .build();
72 } catch (IOException | GeneralSecurityException e) {
73 throw new RuntimeException(e);
74 }
75 }
76
77 /**
78 * Creates an {@link ApacheHttpClientFactory} that validates SSL certificates and host names.
79 */
80 @Bean
81 public ApacheHttpClientFactory createHttpClientFactory() {
82 return new DefaultApacheHttpClientFactory(HttpClientBuilder.create()
83 .setSSLContext(getSslContext())
84 .setSSLHostnameVerifier(this.hostnameVerifierProvider.createHostnameVerifier()));
85 }
86
87 @Bean
88 public ApacheHttpClientConnectionManagerFactory createConnectionManager() {
89 return new DefaultApacheHttpClientConnectionManagerFactory();
90 }
91 }
92
[end of services/submission/src/main/java/app/coronawarn/server/services/submission/verification/CloudFeignClientProvider.java]
[start of services/submission/src/main/java/app/coronawarn/server/services/submission/verification/DefaultHostnameVerifierProvider.java]
1 /*
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.submission.verification;
22
23 import javax.net.ssl.HostnameVerifier;
24 import org.apache.http.conn.ssl.DefaultHostnameVerifier;
25 import org.springframework.context.annotation.Profile;
26 import org.springframework.stereotype.Component;
27
28 @Component
29 @Profile("ssl-client-verification-verify-hostname")
30 public class DefaultHostnameVerifierProvider implements HostnameVerifierProvider {
31
32 @Override
33 public HostnameVerifier createHostnameVerifier() {
34 return new DefaultHostnameVerifier();
35 }
36 }
37
[end of services/submission/src/main/java/app/coronawarn/server/services/submission/verification/DefaultHostnameVerifierProvider.java]
[start of services/submission/src/main/java/app/coronawarn/server/services/submission/verification/DevelopmentFeignClientProvider.java]
1 /*
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.submission.verification;
22
23 import feign.Client;
24 import feign.httpclient.ApacheHttpClient;
25 import org.apache.http.impl.client.HttpClientBuilder;
26 import org.springframework.cloud.commons.httpclient.ApacheHttpClientConnectionManagerFactory;
27 import org.springframework.cloud.commons.httpclient.ApacheHttpClientFactory;
28 import org.springframework.cloud.commons.httpclient.DefaultApacheHttpClientConnectionManagerFactory;
29 import org.springframework.cloud.commons.httpclient.DefaultApacheHttpClientFactory;
30 import org.springframework.context.annotation.Bean;
31 import org.springframework.context.annotation.Profile;
32 import org.springframework.stereotype.Component;
33
34 @Component
35 @Profile("!ssl-client-verification")
36 public class DevelopmentFeignClientProvider implements FeignClientProvider {
37
38 @Override
39 public Client createFeignClient() {
40 return new ApacheHttpClient(createHttpClientFactory().createBuilder().build());
41 }
42
43 /**
44 * Creates an {@link ApacheHttpClientFactory} that neither validates SSL certificates nor host names.
45 */
46 @Bean
47 public ApacheHttpClientFactory createHttpClientFactory() {
48 return new DefaultApacheHttpClientFactory(HttpClientBuilder.create());
49 }
50
51 @Bean
52 public ApacheHttpClientConnectionManagerFactory createConnectionManager() {
53 return new DefaultApacheHttpClientConnectionManagerFactory();
54 }
55 }
56
[end of services/submission/src/main/java/app/coronawarn/server/services/submission/verification/DevelopmentFeignClientProvider.java]
[start of services/submission/src/main/java/app/coronawarn/server/services/submission/verification/NoopHostnameVerifierProvider.java]
1 /*
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.submission.verification;
22
23 import javax.net.ssl.HostnameVerifier;
24 import org.apache.http.conn.ssl.NoopHostnameVerifier;
25 import org.springframework.context.annotation.Profile;
26 import org.springframework.stereotype.Component;
27
28 @Component
29 @Profile("!ssl-client-verification-verify-hostname")
30 public class NoopHostnameVerifierProvider implements HostnameVerifierProvider {
31
32 @Override
33 public HostnameVerifier createHostnameVerifier() {
34 return new NoopHostnameVerifier();
35 }
36 }
37
[end of services/submission/src/main/java/app/coronawarn/server/services/submission/verification/NoopHostnameVerifierProvider.java]
[start of services/submission/src/main/resources/application-cloud.yaml]
1 ---
2 spring:
3 flyway:
4 password: ${POSTGRESQL_PASSWORD_FLYWAY}
5 user: ${POSTGRESQL_USER_FLYWAY}
6 datasource:
7 driver-class-name: org.postgresql.Driver
8 url: jdbc:postgresql://${POSTGRESQL_SERVICE_HOST}:${POSTGRESQL_SERVICE_PORT}/${POSTGRESQL_DATABASE}
9 username: ${POSTGRESQL_USER_SUBMISSION}
10 password: ${POSTGRESQL_PASSWORD_SUBMISSION}
11
12 services:
13 submission:
14 verification:
15 base-url: ${VERIFICATION_BASE_URL}
16
[end of services/submission/src/main/resources/application-cloud.yaml]
[start of services/submission/src/main/resources/application-ssl-client-postgres.yaml]
1 ---
2 spring:
3 datasource:
4 url: jdbc:postgresql://${POSTGRESQL_SERVICE_HOST}:${POSTGRESQL_SERVICE_PORT}/${POSTGRESQL_DATABASE}?ssl=true&sslmode=verify-full&sslrootcert=${SSL_POSTGRES_CERTIFICATE_PATH}&sslcert=${SSL_SUBMISSION_CERTIFICATE_PATH}&sslkey=${SSL_SUBMISSION_PRIVATE_KEY_PATH}
5
[end of services/submission/src/main/resources/application-ssl-client-postgres.yaml]
[start of services/submission/src/main/resources/application-ssl-client-verification.yaml]
1 ---
2 client:
3 ssl:
4 key-password: ${SSL_SUBMISSION_KEYSTORE_PASSWORD}
5 key-store: ${SSL_SUBMISSION_KEYSTORE_PATH}
6 key-store-password: ${SSL_SUBMISSION_KEYSTORE_PASSWORD}
7 verification:
8 trust-store: ${SSL_VERIFICATION_TRUSTSTORE_PATH}
9 trust-store-password: ${SSL_VERIFICATION_TRUSTSTORE_PASSWORD}
10
[end of services/submission/src/main/resources/application-ssl-client-verification.yaml]
[start of services/submission/src/main/resources/application-ssl-server.yaml]
1 ---
2 server:
3 ssl:
4 enabled: true
5 enabled-protocols: TLSv1.2,TLSv1.3
6 protocol: TLS
7 ciphers: >-
8 TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
9 TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384
10 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
11 TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384
12 TLS_DHE_DSS_WITH_AES_128_GCM_SHA256
13 TLS_DHE_DSS_WITH_AES_256_GCM_SHA384
14 TLS_DHE_RSA_WITH_AES_128_GCM_SHA256
15 TLS_DHE_RSA_WITH_AES_256_GCM_SHA384
16 TLS_AES_128_GCM_SHA256
17 TLS_AES_256_GCM_SHA384
18 TLS_AES_128_CCM_SHA256
19 key-password: ${SSL_SUBMISSION_KEYSTORE_PASSWORD}
20 key-store: ${SSL_SUBMISSION_KEYSTORE_PATH}
21 key-store-password: ${SSL_SUBMISSION_KEYSTORE_PASSWORD}
22 key-store-provider: SUN
23 key-store-type: JKS
24
[end of services/submission/src/main/resources/application-ssl-server.yaml]
[start of services/submission/src/main/resources/application.yaml]
1 ---
2 logging:
3 level:
4 org:
5 springframework:
6 web: INFO
7
8 services:
9 submission:
10 # The initial value of the moving average for fake request delays.
11 initial-fake-delay-milliseconds: 10
12 # The number of samples for the calculation of the moving average for fake request delays.
13 fake-delay-moving-average-samples: 10
14 retention-days: 14
15 payload:
16 max-number-of-keys: 14
17 verification:
18 base-url: ${VERIFICATION_BASE_URL:http://localhost:8004}
19 path: /version/v1/tan/verify
20 monitoring:
21 batch-size: 5
22
23 spring:
24 jpa:
25 hibernate:
26 ddl-auto: validate
27 flyway:
28 enabled: true
29 locations: classpath:/db/migration, classpath:/db/specific/{vendor}
30 password: ${POSTGRESQL_PASSWORD_FLYWAY:local_setup_flyway}
31 user: ${POSTGRESQL_USER_FLYWAY:local_setup_flyway}
32 # Postgres configuration
33 datasource:
34 driver-class-name: org.postgresql.Driver
35 url: jdbc:postgresql://${POSTGRESQL_SERVICE_HOST:localhost}:${POSTGRESQL_SERVICE_PORT:5432}/${POSTGRESQL_DATABASE:cwa}
36 username: ${POSTGRESQL_USER_SUBMISSION:local_setup_submission}
37 password: ${POSTGRESQL_PASSWORD_SUBMISSION:local_setup_submission}
38
39 management:
40 server:
41 port: 8081
42 endpoint:
43 metrics:
44 enabled: true
45 prometheus:
46 enabled: true
47 health:
48 group:
49 readiness:
50 include: db, verificationService
51 show-details: always
52 endpoints:
53 web:
54 exposure:
55 include: 'health, prometheus'
56 metrics:
57 export:
58 prometheus:
59 enabled: true
60 health:
61 probes:
62 enabled: true
63
64 feign:
65 httpclient:
66 maxConnections: 200
67 maxConnectionsPerRoute: 200
68
[end of services/submission/src/main/resources/application.yaml]
</code>
Here is an example of a patch file. It consists of changes to the code base. It specifies the file names, the line numbers of each change, and the removed and added lines. A single patch file can contain changes to multiple files.
<patch>
--- a/file.py
+++ b/file.py
@@ -1,27 +1,35 @@
def euclidean(a, b):
- while b:
- a, b = b, a % b
- return a
+ if b == 0:
+ return a
+ return euclidean(b, a % b)
def bresenham(x0, y0, x1, y1):
points = []
dx = abs(x1 - x0)
dy = abs(y1 - y0)
- sx = 1 if x0 < x1 else -1
- sy = 1 if y0 < y1 else -1
- err = dx - dy
+ x, y = x0, y0
+ sx = -1 if x0 > x1 else 1
+ sy = -1 if y0 > y1 else 1
- while True:
- points.append((x0, y0))
- if x0 == x1 and y0 == y1:
- break
- e2 = 2 * err
- if e2 > -dy:
+ if dx > dy:
+ err = dx / 2.0
+ while x != x1:
+ points.append((x, y))
err -= dy
- x0 += sx
- if e2 < dx:
- err += dx
- y0 += sy
+ if err < 0:
+ y += sy
+ err += dx
+ x += sx
+ else:
+ err = dy / 2.0
+ while y != y1:
+ points.append((x, y))
+ err -= dx
+ if err < 0:
+ x += sx
+ err += dy
+ y += sy
+ points.append((x, y))
return points
</patch>
I need you to solve the provded issue by generating a single patch file that I can apply directly to this repository using git apply. Please respond with a single patch file in the format shown above.
Respond below:
| corona-warn-app/cwa-server | 27ba812e04d6f842e15999adfbe388137b0c316b | SSL: Set a profile to willingly decrease security
Currently, we have the profiles `ssl-server`, `ssl-client-verification` and `ssl-client-postgres` which will enable `ssl` for certain situations.
In context of secure-by-default, we should have it in the opposite way - you can set a profile to willingly decrease security.
| 2020-06-11T13:35:23 | <patch>
diff --git a/README.md b/README.md
--- a/README.md
+++ b/README.md
@@ -113,12 +113,14 @@ For the distribution module:
```bash
POSTGRESQL_SERVICE_PORT=8001
VAULT_FILESIGNING_SECRET=</path/to/your/private_key>
+SPRING_PROFILES_ACTIVE=signature-dev,disable-ssl-client-postgres
```
For the submission module:
```bash
POSTGRESQL_SERVICE_PORT=8001
+SPRING_PROFILES_ACTIVE=disable-ssl-server,disable-ssl-client-postgres,disable-ssl-client-verification,disable-ssl-client-verification-verify-hostname
```
#### Configure
@@ -159,8 +161,8 @@ To be able to set breakpoints (e.g. in IntelliJ), it may be necessary to use the
The API that is being exposed by the backend services is documented in an [OpenAPI](https://www.openapis.org/) specification. The specification files are available at the following locations:
-Service | OpenAPI Specification
--------------|-------------
+Service | OpenAPI Specification
+--------------------------|-------------
Submission Service | [services/submission/api_v1.json](https://github.com/corona-warn-app/cwa-server/raw/master/services/submission/api_v1.json)
Distribution Service | [services/distribution/api_v1.json](https://github.com/corona-warn-app/cwa-server/raw/master/services/distribution/api_v1.json)
@@ -168,25 +170,26 @@ Distribution Service | [services/distribution/api_v1.json](https://github.c
### Distribution
-Profile | Effect
-----------------------|-------------
-`dev` | Turns the log level to `DEBUG`.
-`cloud` | Removes default values for the `datasource` and `objectstore` configurations.
-`demo` | Includes incomplete days and hours into the distribution run, thus creating aggregates for the current day and the current hour (and including both in the respective indices). When running multiple distributions in one hour with this profile, the date aggregate for today and the hours aggregate for the current hour will be updated and overwritten. This profile also turns off the expiry policy (Keys must be expired for at least 2 hours before distribution) and the shifting policy (there must be at least 140 keys in a distribution).
-`testdata` | Causes test data to be inserted into the database before each distribution run. By default, around 1000 random diagnosis keys will be generated per hour. If there are no diagnosis keys in the database yet, random keys will be generated for every hour from the beginning of the retention period (14 days ago at 00:00 UTC) until one hour before the present hour. If there are already keys in the database, the random keys will be generated for every hour from the latest diagnosis key in the database (by submission timestamp) until one hour before the present hour (or none at all, if the latest diagnosis key in the database was submitted one hour ago or later).
-`signature-dev` | Sets the app package ID in the export packages' signature info to `de.rki.coronawarnapp-dev` so that the non-productive/test public key will be used for client-side validation.
-`signature-prod` | Sets the app package ID in the export packages' signature info to `de.rki.coronawarnapp` so that the productive public key will be used for client-side validation.
-`ssl-client-postgres` | Enforces SSL with a pinned certificate for the connection to the postgres (see [here](https://github.com/corona-warn-app/cwa-server/blob/master/services/distribution/src/main/resources/application-ssl-client-postgres.yaml)).
+Profile | Effect
+------------------------------|-------------
+`dev` | Turns the log level to `DEBUG`.
+`cloud` | Removes default values for the `datasource` and `objectstore` configurations.
+`demo` | Includes incomplete days and hours into the distribution run, thus creating aggregates for the current day and the current hour (and including both in the respective indices). When running multiple distributions in one hour with this profile, the date aggregate for today and the hours aggregate for the current hour will be updated and overwritten. This profile also turns off the expiry policy (Keys must be expired for at least 2 hours before distribution) and the shifting policy (there must be at least 140 keys in a distribution).
+`testdata` | Causes test data to be inserted into the database before each distribution run. By default, around 1000 random diagnosis keys will be generated per hour. If there are no diagnosis keys in the database yet, random keys will be generated for every hour from the beginning of the retention period (14 days ago at 00:00 UTC) until one hour before the present hour. If there are already keys in the database, the random keys will be generated for every hour from the latest diagnosis key in the database (by submission timestamp) until one hour before the present hour (or none at all, if the latest diagnosis key in the database was submitted one hour ago or later).
+`signature-dev` | Sets the app package ID in the export packages' signature info to `de.rki.coronawarnapp-dev` so that the non-productive/test public key will be used for client-side validation.
+`signature-prod` | Sets the app package ID in the export packages' signature info to `de.rki.coronawarnapp` so that the productive public key will be used for client-side validation.
+`disable-ssl-client-postgres` | Disables SSL for the connection to the postgres database.
### Submission
-Profile | Effect
---------------------------|-------------
-`dev` | Turns the log level to `DEBUG`.
-`cloud` | Removes default values for the `datasource` configuration.
-`ssl-server` | Enables SSL for the submission endpoint (see [here](https://github.com/corona-warn-app/cwa-server/blob/master/services/submission/src/main/resources/application-ssl-server.yaml)).
-`ssl-client-postgres` | Enforces SSL with a pinned certificate for the connection to the postgres (see [here](https://github.com/corona-warn-app/cwa-server/blob/master/services/submission/src/main/resources/application-ssl-client-postgres.yaml)).
-`ssl-client-verification` | Enforces SSL with a pinned certificate for the connection to the verification server (see [here](https://github.com/corona-warn-app/cwa-server/blob/master/services/submission/src/main/resources/application-ssl-client-verification.yaml)).
+Profile | Effect
+--------------------------------------------------|-------------
+`dev` | Turns the log level to `DEBUG`.
+`cloud` | Removes default values for the `datasource` configuration.
+`disable-ssl-server` | Disables SSL for the submission endpoint.
+`disable-ssl-client-postgres` | Disables SSL with a pinned certificate for the connection to the postgres database.
+`disable-ssl-client-verification` | Disables SSL with a pinned certificate for the connection to the verification server.
+`disable-ssl-client-verification-verify-hostname` | Disables the verification of the SSL hostname for the connection to the verification server.
## Documentation
diff --git a/docker-compose.yml b/docker-compose.yml
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -11,7 +11,7 @@ services:
- "8000:8080"
- "8006:8081"
environment:
- SPRING_PROFILES_ACTIVE: dev
+ SPRING_PROFILES_ACTIVE: dev,disable-ssl-server,disable-ssl-client-postgres,disable-ssl-client-verification,disable-ssl-client-verification-verify-hostname
POSTGRESQL_SERVICE_PORT: '5432'
POSTGRESQL_SERVICE_HOST: postgres
POSTGRESQL_DATABASE: ${POSTGRES_DB}
@@ -29,7 +29,7 @@ services:
- objectstore
- create-bucket
environment:
- SPRING_PROFILES_ACTIVE: dev,signature-dev,testdata
+ SPRING_PROFILES_ACTIVE: dev,signature-dev,testdata,disable-ssl-client-postgres
POSTGRESQL_SERVICE_PORT: '5432'
POSTGRESQL_SERVICE_HOST: postgres
POSTGRESQL_DATABASE: ${POSTGRES_DB}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/Application.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/Application.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/Application.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/Application.java
@@ -21,6 +21,8 @@
package app.coronawarn.server.services.distribution;
import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
+import java.util.Arrays;
+import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
@@ -28,7 +30,9 @@
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
+import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.ComponentScan;
+import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
/**
@@ -42,7 +46,7 @@
@ComponentScan({"app.coronawarn.server.common.persistence",
"app.coronawarn.server.services.distribution"})
@EnableConfigurationProperties({DistributionServiceConfig.class})
-public class Application {
+public class Application implements EnvironmentAware {
private static final Logger logger = LoggerFactory.getLogger(Application.class);
@@ -58,4 +62,13 @@ public static void killApplication(ApplicationContext appContext) {
logger.error("Application terminated abnormally.");
System.exit(1);
}
+
+ @Override
+ public void setEnvironment(Environment environment) {
+ List<String> profiles = Arrays.asList(environment.getActiveProfiles());
+ if (profiles.contains("disable-ssl-client-postgres")) {
+ logger.warn("The distribution runner is started with postgres connection TLS disabled. "
+ + "This should never be used in PRODUCTION!");
+ }
+ }
}
diff --git a/services/distribution/src/main/resources/application-cloud.yaml b/services/distribution/src/main/resources/application-cloud.yaml
--- a/services/distribution/src/main/resources/application-cloud.yaml
+++ b/services/distribution/src/main/resources/application-cloud.yaml
@@ -5,7 +5,6 @@ spring:
user: ${POSTGRESQL_USER_FLYWAY}
datasource:
driver-class-name: org.postgresql.Driver
- url: jdbc:postgresql://${POSTGRESQL_SERVICE_HOST}:${POSTGRESQL_SERVICE_PORT}/${POSTGRESQL_DATABASE}
username: ${POSTGRESQL_USER_DISTRIBUTION}
password: ${POSTGRESQL_PASSWORD_DISTRIBUTION}
diff --git a/services/distribution/src/main/resources/application-disable-ssl-client-postgres.yaml b/services/distribution/src/main/resources/application-disable-ssl-client-postgres.yaml
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/main/resources/application-disable-ssl-client-postgres.yaml
@@ -0,0 +1,4 @@
+---
+spring:
+ datasource:
+ url: jdbc:postgresql://${POSTGRESQL_SERVICE_HOST:localhost}:${POSTGRESQL_SERVICE_PORT:5432}/${POSTGRESQL_DATABASE:cwa}
diff --git a/services/distribution/src/main/resources/application-ssl-client-postgres.yaml b/services/distribution/src/main/resources/application-ssl-client-postgres.yaml
deleted file mode 100644
--- a/services/distribution/src/main/resources/application-ssl-client-postgres.yaml
+++ /dev/null
@@ -1,4 +0,0 @@
----
-spring:
- datasource:
- url: jdbc:postgresql://${POSTGRESQL_SERVICE_HOST}:${POSTGRESQL_SERVICE_PORT}/${POSTGRESQL_DATABASE}?ssl=true&sslmode=verify-full&sslrootcert=${SSL_POSTGRES_CERTIFICATE_PATH}&sslcert=${SSL_SUBMISSION_CERTIFICATE_PATH}&sslkey=${SSL_SUBMISSION_PRIVATE_KEY_PATH}
diff --git a/services/distribution/src/main/resources/application.yaml b/services/distribution/src/main/resources/application.yaml
--- a/services/distribution/src/main/resources/application.yaml
+++ b/services/distribution/src/main/resources/application.yaml
@@ -68,6 +68,6 @@ spring:
datasource:
driver-class-name: org.postgresql.Driver
- url: jdbc:postgresql://${POSTGRESQL_SERVICE_HOST:localhost}:${POSTGRESQL_SERVICE_PORT:5432}/${POSTGRESQL_DATABASE:cwa}
+ url: jdbc:postgresql://${POSTGRESQL_SERVICE_HOST}:${POSTGRESQL_SERVICE_PORT}/${POSTGRESQL_DATABASE}?ssl=true&sslmode=verify-full&sslrootcert=${SSL_POSTGRES_CERTIFICATE_PATH}&sslcert=${SSL_DISTRIBUTION_CERTIFICATE_PATH}&sslkey=${SSL_DISTRIBUTION_PRIVATE_KEY_PATH}
username: ${POSTGRESQL_USER_DISTRIBUTION:local_setup_distribution}
password: ${POSTGRESQL_PASSWORD_DISTRIBUTION:local_setup_distribution}
diff --git a/services/submission/src/main/java/app/coronawarn/server/services/submission/ServerApplication.java b/services/submission/src/main/java/app/coronawarn/server/services/submission/ServerApplication.java
--- a/services/submission/src/main/java/app/coronawarn/server/services/submission/ServerApplication.java
+++ b/services/submission/src/main/java/app/coronawarn/server/services/submission/ServerApplication.java
@@ -22,13 +22,19 @@
import io.micrometer.core.aop.TimedAspect;
import io.micrometer.core.instrument.MeterRegistry;
+import java.util.Arrays;
+import java.util.List;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.openfeign.EnableFeignClients;
+import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
+import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.http.converter.protobuf.ProtobufHttpMessageConverter;
@@ -39,7 +45,13 @@
"app.coronawarn.server.services.submission"})
@EnableConfigurationProperties
@EnableFeignClients
-public class ServerApplication {
+public class ServerApplication implements EnvironmentAware {
+
+ private static final Logger logger = LoggerFactory.getLogger(ServerApplication.class);
+
+ public static void main(String[] args) {
+ SpringApplication.run(ServerApplication.class);
+ }
@Bean
TimedAspect timedAspect(MeterRegistry registry) {
@@ -51,7 +63,27 @@ ProtobufHttpMessageConverter protobufHttpMessageConverter() {
return new ProtobufHttpMessageConverter();
}
- public static void main(String[] args) {
- SpringApplication.run(ServerApplication.class);
+ @Override
+ public void setEnvironment(Environment environment) {
+ List<String> profiles = Arrays.asList(environment.getActiveProfiles());
+ if (profiles.contains("disable-ssl-server")) {
+ logger.warn(
+ "The submission service is started with endpoint TLS disabled. This should never be used in PRODUCTION!");
+ }
+ if (profiles.contains("disable-ssl-client-postgres")) {
+ logger.warn(
+ "The submission service is started with postgres connection TLS disabled. This should never be used in"
+ + "PRODUCTION!");
+ }
+ if (profiles.contains("disable-ssl-client-verification")) {
+ logger.warn(
+ "The submission service is started with verification service connection TLS disabled. This should never be"
+ + "used in PRODUCTION!");
+ }
+ if (profiles.contains("disable-ssl-client-verification-verify-hostname")) {
+ logger.warn(
+ "The submission service is started with verification service TLS hostname validation disabled. This should"
+ + "never be used in PRODUCTION!");
+ }
}
}
diff --git a/services/submission/src/main/java/app/coronawarn/server/services/submission/config/SubmissionServiceConfig.java b/services/submission/src/main/java/app/coronawarn/server/services/submission/config/SubmissionServiceConfig.java
--- a/services/submission/src/main/java/app/coronawarn/server/services/submission/config/SubmissionServiceConfig.java
+++ b/services/submission/src/main/java/app/coronawarn/server/services/submission/config/SubmissionServiceConfig.java
@@ -20,6 +20,7 @@
package app.coronawarn.server.services.submission.config;
+import java.io.File;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@@ -35,6 +36,7 @@ public class SubmissionServiceConfig {
private Payload payload;
private Verification verification;
private Monitoring monitoring;
+ private Client client;
public Double getInitialFakeDelayMilliseconds() {
return initialFakeDelayMilliseconds;
@@ -142,4 +144,74 @@ public Long getMonitoringBatchSize() {
public void setMonitoringBatchSize(Long batchSize) {
this.monitoring.setBatchSize(batchSize);
}
+
+ public Client getClient() {
+ return client;
+ }
+
+ public void setClient(Client client) {
+ this.client = client;
+ }
+
+ public static class Client {
+
+ private Ssl ssl;
+
+ public Ssl getSsl() {
+ return ssl;
+ }
+
+ public void setSsl(Ssl ssl) {
+ this.ssl = ssl;
+ }
+
+ public static class Ssl {
+
+ private File keyStore;
+ private String keyStorePassword;
+ private String keyPassword;
+ private File trustStore;
+ private String trustStorePassword;
+
+ public File getKeyStore() {
+ return keyStore;
+ }
+
+ public void setKeyStore(File keyStore) {
+ this.keyStore = keyStore;
+ }
+
+ public String getKeyStorePassword() {
+ return keyStorePassword;
+ }
+
+ public void setKeyStorePassword(String keyStorePassword) {
+ this.keyStorePassword = keyStorePassword;
+ }
+
+ public String getKeyPassword() {
+ return keyPassword;
+ }
+
+ public void setKeyPassword(String keyPassword) {
+ this.keyPassword = keyPassword;
+ }
+
+ public File getTrustStore() {
+ return trustStore;
+ }
+
+ public void setTrustStore(File trustStore) {
+ this.trustStore = trustStore;
+ }
+
+ public String getTrustStorePassword() {
+ return trustStorePassword;
+ }
+
+ public void setTrustStorePassword(String trustStorePassword) {
+ this.trustStorePassword = trustStorePassword;
+ }
+ }
+ }
}
diff --git a/services/submission/src/main/java/app/coronawarn/server/services/submission/verification/CloudFeignClientProvider.java b/services/submission/src/main/java/app/coronawarn/server/services/submission/verification/CloudFeignClientProvider.java
--- a/services/submission/src/main/java/app/coronawarn/server/services/submission/verification/CloudFeignClientProvider.java
+++ b/services/submission/src/main/java/app/coronawarn/server/services/submission/verification/CloudFeignClientProvider.java
@@ -20,8 +20,11 @@
package app.coronawarn.server.services.submission.verification;
+import app.coronawarn.server.services.submission.config.SubmissionServiceConfig;
+import app.coronawarn.server.services.submission.config.SubmissionServiceConfig.Client.Ssl;
import feign.Client;
import feign.httpclient.ApacheHttpClient;
+import java.io.File;
import java.io.IOException;
import java.security.GeneralSecurityException;
import javax.net.ssl.SSLContext;
@@ -33,19 +36,29 @@
import org.springframework.cloud.commons.httpclient.DefaultApacheHttpClientFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Profile;
-import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
-import org.springframework.util.ResourceUtils;
@Component
-@Profile("ssl-client-verification")
+@Profile("!disable-ssl-client-verification")
public class CloudFeignClientProvider implements FeignClientProvider {
- private final Environment environment;
private final HostnameVerifierProvider hostnameVerifierProvider;
+ private final File keyStore;
+ private final String keyStorePassword;
+ private final String keyPassword;
+ private final File trustStore;
+ private final String trustStorePassword;
- public CloudFeignClientProvider(Environment environment, HostnameVerifierProvider hostnameVerifierProvider) {
- this.environment = environment;
+ /**
+ * Creates a {@link CloudFeignClientProvider} that provides feign clients with fixed key and trust material.
+ */
+ public CloudFeignClientProvider(SubmissionServiceConfig config, HostnameVerifierProvider hostnameVerifierProvider) {
+ Ssl sslConfig = config.getClient().getSsl();
+ this.keyStore = sslConfig.getKeyStore();
+ this.keyStorePassword = sslConfig.getKeyStorePassword();
+ this.keyPassword = sslConfig.getKeyPassword();
+ this.trustStore = sslConfig.getTrustStore();
+ this.trustStorePassword = sslConfig.getTrustStorePassword();
this.hostnameVerifierProvider = hostnameVerifierProvider;
}
@@ -56,18 +69,10 @@ public Client createFeignClient() {
private SSLContext getSslContext() {
try {
- String keyStorePath = environment.getProperty("client.ssl.key-store");
- String keyStorePassword = environment.getProperty("client.ssl.key-store-password");
- String keyPassword = environment.getProperty("client.ssl.key-password");
-
- String trustStorePath = environment.getProperty("client.ssl.verification.trust-store");
- String trustStorePassword = environment.getProperty("client.ssl.verification.trust-store-password");
-
return SSLContextBuilder
.create()
- .loadKeyMaterial(ResourceUtils.getFile(keyStorePath), keyStorePassword.toCharArray(),
- keyPassword.toCharArray())
- .loadTrustMaterial(ResourceUtils.getFile(trustStorePath), trustStorePassword.toCharArray())
+ .loadKeyMaterial(this.keyStore, this.keyStorePassword.toCharArray(), this.keyPassword.toCharArray())
+ .loadTrustMaterial(this.trustStore, this.trustStorePassword.toCharArray())
.build();
} catch (IOException | GeneralSecurityException e) {
throw new RuntimeException(e);
diff --git a/services/submission/src/main/java/app/coronawarn/server/services/submission/verification/DefaultHostnameVerifierProvider.java b/services/submission/src/main/java/app/coronawarn/server/services/submission/verification/DefaultHostnameVerifierProvider.java
--- a/services/submission/src/main/java/app/coronawarn/server/services/submission/verification/DefaultHostnameVerifierProvider.java
+++ b/services/submission/src/main/java/app/coronawarn/server/services/submission/verification/DefaultHostnameVerifierProvider.java
@@ -26,7 +26,7 @@
import org.springframework.stereotype.Component;
@Component
-@Profile("ssl-client-verification-verify-hostname")
+@Profile("!disable-ssl-client-verification-verify-hostname")
public class DefaultHostnameVerifierProvider implements HostnameVerifierProvider {
@Override
diff --git a/services/submission/src/main/java/app/coronawarn/server/services/submission/verification/DevelopmentFeignClientProvider.java b/services/submission/src/main/java/app/coronawarn/server/services/submission/verification/DevelopmentFeignClientProvider.java
--- a/services/submission/src/main/java/app/coronawarn/server/services/submission/verification/DevelopmentFeignClientProvider.java
+++ b/services/submission/src/main/java/app/coronawarn/server/services/submission/verification/DevelopmentFeignClientProvider.java
@@ -32,9 +32,15 @@
import org.springframework.stereotype.Component;
@Component
-@Profile("!ssl-client-verification")
+@Profile("disable-ssl-client-verification")
public class DevelopmentFeignClientProvider implements FeignClientProvider {
+ private final HostnameVerifierProvider hostnameVerifierProvider;
+
+ public DevelopmentFeignClientProvider(HostnameVerifierProvider hostnameVerifierProvider) {
+ this.hostnameVerifierProvider = hostnameVerifierProvider;
+ }
+
@Override
public Client createFeignClient() {
return new ApacheHttpClient(createHttpClientFactory().createBuilder().build());
@@ -45,7 +51,8 @@ public Client createFeignClient() {
*/
@Bean
public ApacheHttpClientFactory createHttpClientFactory() {
- return new DefaultApacheHttpClientFactory(HttpClientBuilder.create());
+ return new DefaultApacheHttpClientFactory(HttpClientBuilder.create()
+ .setSSLHostnameVerifier(this.hostnameVerifierProvider.createHostnameVerifier()));
}
@Bean
diff --git a/services/submission/src/main/java/app/coronawarn/server/services/submission/verification/NoopHostnameVerifierProvider.java b/services/submission/src/main/java/app/coronawarn/server/services/submission/verification/NoopHostnameVerifierProvider.java
--- a/services/submission/src/main/java/app/coronawarn/server/services/submission/verification/NoopHostnameVerifierProvider.java
+++ b/services/submission/src/main/java/app/coronawarn/server/services/submission/verification/NoopHostnameVerifierProvider.java
@@ -26,7 +26,7 @@
import org.springframework.stereotype.Component;
@Component
-@Profile("!ssl-client-verification-verify-hostname")
+@Profile("disable-ssl-client-verification-verify-hostname")
public class NoopHostnameVerifierProvider implements HostnameVerifierProvider {
@Override
diff --git a/services/submission/src/main/resources/application-cloud.yaml b/services/submission/src/main/resources/application-cloud.yaml
--- a/services/submission/src/main/resources/application-cloud.yaml
+++ b/services/submission/src/main/resources/application-cloud.yaml
@@ -5,7 +5,6 @@ spring:
user: ${POSTGRESQL_USER_FLYWAY}
datasource:
driver-class-name: org.postgresql.Driver
- url: jdbc:postgresql://${POSTGRESQL_SERVICE_HOST}:${POSTGRESQL_SERVICE_PORT}/${POSTGRESQL_DATABASE}
username: ${POSTGRESQL_USER_SUBMISSION}
password: ${POSTGRESQL_PASSWORD_SUBMISSION}
diff --git a/services/submission/src/main/resources/application-disable-ssl-client-postgres.yaml b/services/submission/src/main/resources/application-disable-ssl-client-postgres.yaml
new file mode 100644
--- /dev/null
+++ b/services/submission/src/main/resources/application-disable-ssl-client-postgres.yaml
@@ -0,0 +1,4 @@
+---
+spring:
+ datasource:
+ url: jdbc:postgresql://${POSTGRESQL_SERVICE_HOST:localhost}:${POSTGRESQL_SERVICE_PORT:5432}/${POSTGRESQL_DATABASE:cwa}
diff --git a/services/submission/src/main/resources/application-disable-ssl-server.yaml b/services/submission/src/main/resources/application-disable-ssl-server.yaml
new file mode 100644
--- /dev/null
+++ b/services/submission/src/main/resources/application-disable-ssl-server.yaml
@@ -0,0 +1,4 @@
+---
+server:
+ ssl:
+ enabled: false
diff --git a/services/submission/src/main/resources/application-ssl-client-postgres.yaml b/services/submission/src/main/resources/application-ssl-client-postgres.yaml
deleted file mode 100644
--- a/services/submission/src/main/resources/application-ssl-client-postgres.yaml
+++ /dev/null
@@ -1,4 +0,0 @@
----
-spring:
- datasource:
- url: jdbc:postgresql://${POSTGRESQL_SERVICE_HOST}:${POSTGRESQL_SERVICE_PORT}/${POSTGRESQL_DATABASE}?ssl=true&sslmode=verify-full&sslrootcert=${SSL_POSTGRES_CERTIFICATE_PATH}&sslcert=${SSL_SUBMISSION_CERTIFICATE_PATH}&sslkey=${SSL_SUBMISSION_PRIVATE_KEY_PATH}
diff --git a/services/submission/src/main/resources/application-ssl-client-verification.yaml b/services/submission/src/main/resources/application-ssl-client-verification.yaml
deleted file mode 100644
--- a/services/submission/src/main/resources/application-ssl-client-verification.yaml
+++ /dev/null
@@ -1,9 +0,0 @@
----
-client:
- ssl:
- key-password: ${SSL_SUBMISSION_KEYSTORE_PASSWORD}
- key-store: ${SSL_SUBMISSION_KEYSTORE_PATH}
- key-store-password: ${SSL_SUBMISSION_KEYSTORE_PASSWORD}
- verification:
- trust-store: ${SSL_VERIFICATION_TRUSTSTORE_PATH}
- trust-store-password: ${SSL_VERIFICATION_TRUSTSTORE_PASSWORD}
diff --git a/services/submission/src/main/resources/application-ssl-server.yaml b/services/submission/src/main/resources/application-ssl-server.yaml
deleted file mode 100644
--- a/services/submission/src/main/resources/application-ssl-server.yaml
+++ /dev/null
@@ -1,23 +0,0 @@
----
-server:
- ssl:
- enabled: true
- enabled-protocols: TLSv1.2,TLSv1.3
- protocol: TLS
- ciphers: >-
- TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
- TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384
- TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
- TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384
- TLS_DHE_DSS_WITH_AES_128_GCM_SHA256
- TLS_DHE_DSS_WITH_AES_256_GCM_SHA384
- TLS_DHE_RSA_WITH_AES_128_GCM_SHA256
- TLS_DHE_RSA_WITH_AES_256_GCM_SHA384
- TLS_AES_128_GCM_SHA256
- TLS_AES_256_GCM_SHA384
- TLS_AES_128_CCM_SHA256
- key-password: ${SSL_SUBMISSION_KEYSTORE_PASSWORD}
- key-store: ${SSL_SUBMISSION_KEYSTORE_PATH}
- key-store-password: ${SSL_SUBMISSION_KEYSTORE_PASSWORD}
- key-store-provider: SUN
- key-store-type: JKS
diff --git a/services/submission/src/main/resources/application.yaml b/services/submission/src/main/resources/application.yaml
--- a/services/submission/src/main/resources/application.yaml
+++ b/services/submission/src/main/resources/application.yaml
@@ -32,7 +32,7 @@ spring:
# Postgres configuration
datasource:
driver-class-name: org.postgresql.Driver
- url: jdbc:postgresql://${POSTGRESQL_SERVICE_HOST:localhost}:${POSTGRESQL_SERVICE_PORT:5432}/${POSTGRESQL_DATABASE:cwa}
+ url: jdbc:postgresql://${POSTGRESQL_SERVICE_HOST}:${POSTGRESQL_SERVICE_PORT}/${POSTGRESQL_DATABASE}?ssl=true&sslmode=verify-full&sslrootcert=${SSL_POSTGRES_CERTIFICATE_PATH}&sslcert=${SSL_SUBMISSION_CERTIFICATE_PATH}&sslkey=${SSL_SUBMISSION_PRIVATE_KEY_PATH}
username: ${POSTGRESQL_USER_SUBMISSION:local_setup_submission}
password: ${POSTGRESQL_PASSWORD_SUBMISSION:local_setup_submission}
@@ -64,4 +64,4 @@ management:
feign:
httpclient:
maxConnections: 200
- maxConnectionsPerRoute: 200
+ maxConnectionsPerRoute: 200
\ No newline at end of file
</patch> | diff --git a/services/submission/src/test/java/app/coronawarn/server/services/submission/ServerApplicationTests.java b/services/submission/src/test/java/app/coronawarn/server/services/submission/ServerApplicationTests.java
--- a/services/submission/src/test/java/app/coronawarn/server/services/submission/ServerApplicationTests.java
+++ b/services/submission/src/test/java/app/coronawarn/server/services/submission/ServerApplicationTests.java
@@ -28,8 +28,10 @@
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.boot.test.web.client.TestRestTemplate;
+import org.springframework.test.context.ActiveProfiles;
@SpringBootTest
+@ActiveProfiles({ "disable-ssl-client-verification", "disable-ssl-client-verification-verify-hostname" })
class ServerApplicationTests {
@Autowired
diff --git a/services/submission/src/test/java/app/coronawarn/server/services/submission/controller/PayloadValidationTest.java b/services/submission/src/test/java/app/coronawarn/server/services/submission/controller/PayloadValidationTest.java
--- a/services/submission/src/test/java/app/coronawarn/server/services/submission/controller/PayloadValidationTest.java
+++ b/services/submission/src/test/java/app/coronawarn/server/services/submission/controller/PayloadValidationTest.java
@@ -44,8 +44,10 @@
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.ResponseEntity;
+import org.springframework.test.context.ActiveProfiles;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
+@ActiveProfiles({"disable-ssl-client-verification", "disable-ssl-client-verification-verify-hostname"})
class PayloadValidationTest {
@MockBean
diff --git a/services/submission/src/test/java/app/coronawarn/server/services/submission/controller/SubmissionControllerTest.java b/services/submission/src/test/java/app/coronawarn/server/services/submission/controller/SubmissionControllerTest.java
--- a/services/submission/src/test/java/app/coronawarn/server/services/submission/controller/SubmissionControllerTest.java
+++ b/services/submission/src/test/java/app/coronawarn/server/services/submission/controller/SubmissionControllerTest.java
@@ -73,8 +73,10 @@
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
+import org.springframework.test.context.ActiveProfiles;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
+@ActiveProfiles({ "disable-ssl-client-verification", "disable-ssl-client-verification-verify-hostname" })
class SubmissionControllerTest {
private static final URI SUBMISSION_URL = URI.create("/version/v1/diagnosis-keys");
diff --git a/services/submission/src/test/java/app/coronawarn/server/services/submission/monitoring/VerificationServiceHealthIndicatorTest.java b/services/submission/src/test/java/app/coronawarn/server/services/submission/monitoring/VerificationServiceHealthIndicatorTest.java
--- a/services/submission/src/test/java/app/coronawarn/server/services/submission/monitoring/VerificationServiceHealthIndicatorTest.java
+++ b/services/submission/src/test/java/app/coronawarn/server/services/submission/monitoring/VerificationServiceHealthIndicatorTest.java
@@ -32,14 +32,15 @@
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
+import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
-
@TestPropertySource(properties = {"management.port="})
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
+@ActiveProfiles({ "disable-ssl-client-verification", "disable-ssl-client-verification-verify-hostname" })
class VerificationServiceHealthIndicatorTest {
@MockBean
diff --git a/services/submission/src/test/java/app/coronawarn/server/services/submission/verification/TanVerifierTest.java b/services/submission/src/test/java/app/coronawarn/server/services/submission/verification/TanVerifierTest.java
--- a/services/submission/src/test/java/app/coronawarn/server/services/submission/verification/TanVerifierTest.java
+++ b/services/submission/src/test/java/app/coronawarn/server/services/submission/verification/TanVerifierTest.java
@@ -20,7 +20,6 @@
package app.coronawarn.server.services.submission.verification;
-
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;
import static com.github.tomakehurst.wiremock.client.WireMock.matchingJsonPath;
@@ -49,11 +48,11 @@
import org.springframework.http.MediaType;
import org.springframework.test.context.ActiveProfiles;
-@SpringBootTest(classes = {TanVerifier.class, DevelopmentFeignClientProvider.class})
+@SpringBootTest(classes = {TanVerifier.class, DevelopmentFeignClientProvider.class, NoopHostnameVerifierProvider.class})
@ImportAutoConfiguration({FeignAutoConfiguration.class, FeignTestConfiguration.class})
@EnableConfigurationProperties(value = SubmissionServiceConfig.class)
@EnableFeignClients
-@ActiveProfiles("feign")
+@ActiveProfiles({ "feign", "disable-ssl-client-verification", "disable-ssl-client-verification-verify-hostname" })
class TanVerifierTest {
@Autowired
| |||||
corona-warn-app__cwa-server-424 | You will be provided with a partial code base and an issue statement explaining a problem to resolve.
<issue>
Application Configuration: Add version update support
We would like to keep the mobile application informed about new releases/current release of the app. This information can then be presented to the user, in order to ask for applying updates.
We would like to add new fields to the application config (example values):
```yaml
app-version:
ios:
latest: 1.5.2
min: 1.2.2
android:
latest: 1.3.2
min: 1.1.2
```
After downloading the config, the app checks whether the signature can be verified. If that is the case, it will get the current & min values from the config based on the target platform.
This information can now be used to prompt users for updating the app. The values for the versions must follow semantic versioning.
</issue>
<code>
[start of README.md]
1 <!-- markdownlint-disable MD041 -->
2 <h1 align="center">
3 Corona-Warn-App Server
4 </h1>
5
6 <p align="center">
7 <a href="https://github.com/corona-warn-app/cwa-server/commits/" title="Last Commit"><img src="https://img.shields.io/github/last-commit/corona-warn-app/cwa-server?style=flat"></a>
8 <a href="https://github.com/corona-warn-app/cwa-server/issues" title="Open Issues"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat"></a>
9 <a href="https://circleci.com/gh/corona-warn-app/cwa-server" title="Build Status"><img src="https://circleci.com/gh/corona-warn-app/cwa-server.svg?style=shield&circle-token=4ab059989d10709df19eb4b98ab7c121a25e981a"></a>
10 <a href="https://sonarcloud.io/dashboard?id=corona-warn-app_cwa-server" title="Quality Gate"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=alert_status"></a>
11 <a href="https://sonarcloud.io/component_measures?id=corona-warn-app_cwa-server&metric=Coverage&view=list" title="Coverage"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=coverage"></a>
12 <a href="https://github.com/corona-warn-app/cwa-server/blob/master/LICENSE" title="License"><img src="https://img.shields.io/badge/License-Apache%202.0-green.svg?style=flat"></a>
13 </p>
14
15 <p align="center">
16 <a href="#development">Development</a> •
17 <a href="#service-apis">Service APIs</a> •
18 <a href="#documentation">Documentation</a> •
19 <a href="#support-and-feedback">Support</a> •
20 <a href="#how-to-contribute">Contribute</a> •
21 <a href="#contributors">Contributors</a> •
22 <a href="#repositories">Repositories</a> •
23 <a href="#licensing">Licensing</a>
24 </p>
25
26 The goal of this project is to develop the official Corona-Warn-App for Germany based on the exposure notification API from [Apple](https://www.apple.com/covid19/contacttracing/) and [Google](https://www.google.com/covid19/exposurenotifications/). The apps (for both iOS and Android) use Bluetooth technology to exchange anonymous encrypted data with other mobile phones (on which the app is also installed) in the vicinity of an app user's phone. The data is stored locally on each user's device, preventing authorities or other parties from accessing or controlling the data. This repository contains the **implementation of the server for encryption keys** for the Corona-Warn-App. This implementation is still a **work in progress**, and the code it contains is currently alpha-quality code.
27
28 In this documentation, Corona-Warn-App services are also referred to as CWA services.
29
30 ## Architecture Overview
31
32 You can find the architecture overview [here](/docs/architecture-overview.md), which will give you
33 a good starting point in how the backend services interact with other services, and what purpose
34 they serve.
35
36 ## Development
37
38 After you've checked out this repository, you can run the application in one of the following ways:
39
40 * As a [Docker](https://www.docker.com/)-based deployment on your local machine. You can run either:
41 * Single components using the respective Dockerfile or
42 * The full backend using the Docker Compose (which is considered the most convenient way)
43 * As a [Maven](https://maven.apache.org)-based build on your local machine.
44 If you want to develop something in a single component, this approach is preferable.
45
46 ### Docker-Based Deployment
47
48 If you want to use Docker-based deployment, you need to install Docker on your local machine. For more information about downloading and installing Docker, see the [official Docker documentation](https://docs.docker.com/get-docker/).
49
50 #### Running the Full CWA Backend Using Docker Compose
51
52 For your convenience, a full setup including the generation of test data has been prepared using [Docker Compose](https://docs.docker.com/compose/reference/overview/). To build the backend services, run ```docker-compose build``` in the repository's root directory. A default configuration file can be found under ```.env```in the root folder of the repository. The default values for the local Postgres and Zenko Cloudserver should be changed in this file before docker-compose is run.
53
54 Once the services are built, you can start the whole backend using ```docker-compose up```.
55 The distribution service runs once and then finishes. If you want to trigger additional distribution runs, run ```docker-compose run distribution```.
56
57 The docker-compose contains the following services:
58
59 Service | Description | Endpoint and Default Credentials
60 ------------------|-------------|-----------
61 submission | The Corona-Warn-App submission service | `http://localhost:8000` <br> `http://localhost:8006` (for actuator endpoint)
62 distribution | The Corona-Warn-App distribution service | NO ENDPOINT
63 postgres | A [postgres] database installation | `postgres:8001` <br> Username: postgres <br> Password: postgres
64 pgadmin | A [pgadmin](https://www.pgadmin.org/) installation for the postgres database | `http://localhost:8002` <br> Username: [email protected] <br> Password: password
65 cloudserver | [Zenko CloudServer] is a S3-compliant object store | `http://localhost:8003/` <br> Access key: accessKey1 <br> Secret key: verySecretKey1
66 verification-fake | A very simple fake implementation for the tan verification. | `http://localhost:8004/version/v1/tan/verify` <br> The only valid tan is "edc07f08-a1aa-11ea-bb37-0242ac130002"
67
68 ##### Known Limitation
69
70 In rare cases the docker-compose runs into a timing issue if the distribution service starts before the bucket of the objectstore was created. This is not a big issue as you can simply run ```docker-compose run distribution``` to trigger additional distribution runs after the objectstore was initialized.
71
72 #### Running Single CWA Services Using Docker
73
74 If you would like to build and run a single CWA service, it's considered easiest to run them in a Docker environment. You can do this using the script provided in the respective CWA service directory. The Docker script first builds the CWA service and then creates an image for the runtime, which means that there are no additional dependencies for you to install.
75
76 To build and run the distribution service, run the following command:
77
78 ```bash
79 ./services/distribution/build_and_run.sh
80 ```
81
82 To build and run the submission service, run the following command:
83
84 ```bash
85 ./services/submission/build_and_run.sh
86 ```
87
88 The submission service is available on [localhost:8080](http://localhost:8080 ).
89
90 ### Maven-Based Build
91
92 If you want to actively develop in one of the CWA services, the Maven-based runtime is most suitable.
93 To prepare your machine to run the CWA project locally, we recommend that you first ensure that you've installed the following:
94
95 * Minimum JDK Version 11: [OpenJDK](https://openjdk.java.net/) / [SapMachine](https://sap.github.io/SapMachine/)
96 * [Maven 3.6](https://maven.apache.org/)
97 * [Postgres]
98 * [Zenko CloudServer]
99
100 #### Configure
101
102 After you made sure that the specified dependencies are running, configure them in the respective configuration files.
103
104 * Configure the Postgres connection in the [submission config](./services/submission/src/main/resources/application.yaml) and in the [distribution config](./services/distribution/src/main/resources/application.yaml)
105 * Configure the S3 compatible object storage in the [distribution config](./services/distribution/src/main/resources/application.yaml)
106 * Configure the private key for the distribution service, the path need to be prefixed with `file:`
107 * `VAULT_FILESIGNING_SECRET` should be the path to the private key, example available in `<repo-root>/docker-compose-test-secrets/private.pem`
108
109 #### Build
110
111 After you've checked out the repository, to build the project, run ```mvn install``` in your base directory.
112
113 #### Run
114
115 Navigate to the service you want to start and run the spring-boot:run target. The configured Postgres and the configured S3 compliant object storage are used as default. When you start the submission service, the endpoint is available on your local port 8080.
116
117 If you want to start the submission service, for example, you start it as follows:
118
119 ```bash
120 cd services/submission/
121 mvn spring-boot:run
122 ```
123
124 #### Debugging
125
126 To enable the `DEBUG` log level, you can run the application using the Spring `dev` profile.
127
128 ```bash
129 mvn spring-boot:run -Dspring-boot.run.profiles=dev
130 ```
131
132 To be able to set breakpoints (e.g. in IntelliJ), it may be necessary to use the ```-Dspring-boot.run.fork=false``` parameter.
133
134 ## Service APIs
135
136 The API that is being exposed by the backend services is documented in an [OpenAPI](https://www.openapis.org/) specification. The specification files are available at the following locations:
137
138 Service | OpenAPI Specification
139 -------------|-------------
140 Submission Service | [services/submission/api_v1.json](https://github.com/corona-warn-app/cwa-server/raw/master/services/submission/api_v1.json)
141 Distribution Service | [services/distribution/api_v1.json](https://github.com/corona-warn-app/cwa-server/raw/master/services/distribution/api_v1.json)
142
143 ## Spring Profiles
144
145 ### Distribution
146
147 Profile | Effect
148 -----------------|-------------
149 `dev` | Turns the log level to `DEBUG`.
150 `cloud` | Removes default values for the `datasource` and `objectstore` configurations.
151 `demo` | Includes incomplete days and hours into the distribution run, thus creating aggregates for the current day and the current hour (and including both in the respective indices). When running multiple distributions in one hour with this profile, the date aggregate for today and the hours aggregate for the current hour will be updated and overwritten. This profile also turns off the expiry policy (Keys must be expired for at least 2 hours before distribution) and the shifting policy (there must be at least 140 keys in a distribution).
152 `testdata` | Causes test data to be inserted into the database before each distribution run. By default, around 1000 random diagnosis keys will be generated per hour. If there are no diagnosis keys in the database yet, random keys will be generated for every hour from the beginning of the retention period (14 days ago at 00:00 UTC) until one hour before the present hour. If there are already keys in the database, the random keys will be generated for every hour from the latest diagnosis key in the database (by submission timestamp) until one hour before the present hour (or none at all, if the latest diagnosis key in the database was submitted one hour ago or later).
153 `signature-dev` | Sets the app package ID in the export packages' signature info to `de.rki.coronawarnapp-dev` so that test certificates (instead of production certificates) will be used for client-side validation.
154 `signature-prod` | Provides production app package IDs for the signature info
155
156 ### Submission
157
158 Profile | Effect
159 -------------|-------------
160 `dev` | Turns the log level to `DEBUG`.
161 `cloud` | Removes default values for the `datasource` configuration.
162
163 ## Documentation
164
165 The full documentation for the Corona-Warn-App can be found in the [cwa-documentation](https://github.com/corona-warn-app/cwa-documentation) repository. The documentation repository contains technical documents, architecture information, and whitepapers related to this implementation.
166
167 ## Support and Feedback
168
169 The following channels are available for discussions, feedback, and support requests:
170
171 | Type | Channel |
172 | ------------------------ | ------------------------------------------------------ |
173 | **General Discussion** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="General Discussion"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/question.svg?style=flat-square"></a> </a> |
174 | **Concept Feedback** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="Open Concept Feedback"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/architecture.svg?style=flat-square"></a> |
175 | **Backend Issue** | <a href="https://github.com/corona-warn-app/cwa-server/issues/new/choose" title="Open Backend Issue"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat-square"></a> |
176 | **Other Requests** | <a href="mailto:[email protected]" title="Email CWA Team"><img src="https://img.shields.io/badge/email-CWA%20team-green?logo=mail.ru&style=flat-square&logoColor=white"></a> |
177
178 ## How to Contribute
179
180 Contribution and feedback are 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.
181
182 ## Contributors
183
184 The German government has asked SAP and Deutsche Telekom to develop the Corona-Warn-App for Germany as open source software. Deutsche Telekom is providing the network and mobile technology and will operate and run the backend for the app in a safe, scalable and stable manner. SAP is responsible for the app development, its framework and the underlying platform. Therefore, development teams of SAP and Deutsche Telekom are contributing to this project. At the same time 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.
185
186 ## Repositories
187
188 The following public repositories are currently available for the Corona-Warn-App:
189
190 | Repository | Description |
191 | ------------------- | --------------------------------------------------------------------- |
192 | [cwa-documentation] | Project overview, general documentation, and white papers |
193 | [cwa-server] | Backend implementation for the Apple/Google exposure notification API|
194 | [cwa-verification-server] | Backend implementation of the verification process|
195
196 [cwa-documentation]: https://github.com/corona-warn-app/cwa-documentation
197 [cwa-server]: https://github.com/corona-warn-app/cwa-server
198 [cwa-verification-server]: https://github.com/corona-warn-app/cwa-verification-server
199 [Postgres]: https://www.postgresql.org/
200 [HSQLDB]: http://hsqldb.org/
201 [Zenko CloudServer]: https://github.com/scality/cloudserver
202
203 ## Licensing
204
205 Copyright (c) 2020 SAP SE or an SAP affiliate company.
206
207 Licensed under the **Apache License, Version 2.0** (the "License"); you may not use this file except in compliance with the License.
208
209 You may obtain a copy of the License at <https://www.apache.org/licenses/LICENSE-2.0>.
210
211 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.
212
[end of README.md]
[start of /dev/null]
1
[end of /dev/null]
[start of common/protocols/src/main/proto/app/coronawarn/server/common/protocols/internal/app_config.proto]
1 syntax = "proto3";
2 package app.coronawarn.server.common.protocols.internal;
3 option java_package = "app.coronawarn.server.common.protocols.internal";
4 option java_multiple_files = true;
5 import "app/coronawarn/server/common/protocols/internal/risk_score_classification.proto";
6 import "app/coronawarn/server/common/protocols/internal/risk_score_parameters.proto";
7
8 message ApplicationConfiguration {
9
10 int32 minRiskScore = 1;
11
12 app.coronawarn.server.common.protocols.internal.RiskScoreClassification riskScoreClasses = 2;
13
14 app.coronawarn.server.common.protocols.internal.RiskScoreParameters exposureConfig = 3;
15
16 AttenuationDurationThresholds attenuationDurationThresholds = 4;
17 }
18
19 message AttenuationDurationThresholds {
20 int32 lower = 1;
21 int32 upper = 2;
22 }
[end of common/protocols/src/main/proto/app/coronawarn/server/common/protocols/internal/app_config.proto]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/YamlLoader.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.distribution.assembly.appconfig;
22
23 import app.coronawarn.server.services.distribution.assembly.appconfig.parsing.YamlConstructorForProtoBuf;
24 import com.google.protobuf.Message;
25 import java.io.IOException;
26 import java.io.InputStream;
27 import org.springframework.core.io.ClassPathResource;
28 import org.springframework.core.io.Resource;
29 import org.yaml.snakeyaml.Yaml;
30 import org.yaml.snakeyaml.error.YAMLException;
31 import org.yaml.snakeyaml.introspector.BeanAccess;
32
33 public class YamlLoader {
34
35 private YamlLoader() {
36 }
37
38 /**
39 * Returns a protobuf {@link Message.Builder message builder} of the specified type, whose fields have been set to the
40 * corresponding values from the yaml file at the specified path.
41 *
42 * @param path The absolute path of the yaml file within the class path.
43 * @param builderType The specific {@link com.google.protobuf.Message.Builder} implementation that will be returned.
44 * @return A prepared protobuf {@link Message.Builder message builder} of the specified type.
45 * @throws UnableToLoadFileException if either the file access or subsequent yaml parsing fails.
46 */
47 public static <T extends Message.Builder> T loadYamlIntoProtobufBuilder(String path, Class<T> builderType)
48 throws UnableToLoadFileException {
49 Yaml yaml = new Yaml(new YamlConstructorForProtoBuf(path));
50 // no setters for generated message classes available
51 yaml.setBeanAccess(BeanAccess.FIELD);
52
53 Resource riskScoreParametersResource = new ClassPathResource(path);
54 try (InputStream inputStream = riskScoreParametersResource.getInputStream()) {
55 T loaded = yaml.loadAs(inputStream, builderType);
56 if (loaded == null) {
57 throw new UnableToLoadFileException(path);
58 }
59
60 return loaded;
61 } catch (YAMLException e) {
62 throw new UnableToLoadFileException("Parsing failed", e);
63 } catch (IOException e) {
64 throw new UnableToLoadFileException("Failed to load file " + path, e);
65 }
66 }
67 }
68
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/YamlLoader.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/GeneralValidationError.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.distribution.assembly.appconfig.validation;
22
23 import java.util.Objects;
24
25 public class GeneralValidationError implements ValidationError {
26
27 private final String errorSource;
28 private final Object value;
29 private final ErrorType reason;
30
31 /**
32 * Creates a {@link GeneralValidationError} that stores the specified validation error source,
33 * erroneous value and a reason for the error to occur.
34 *
35 * @param errorSource A label that describes the property associated with this validation error.
36 * @param value The value that caused the validation error.
37 * @param reason A validation error specifier.
38 */
39 public GeneralValidationError(String errorSource, Object value, ErrorType reason) {
40 this.errorSource = errorSource;
41 this.value = value;
42 this.reason = reason;
43 }
44
45 @Override
46 public String toString() {
47 return "GeneralValidationError{"
48 + "errorType=" + reason
49 + ", parameter='" + errorSource + '\''
50 + ", givenValue=" + value
51 + '}';
52 }
53
54 @Override
55 public boolean equals(Object o) {
56 if (this == o) {
57 return true;
58 }
59 if (o == null || getClass() != o.getClass()) {
60 return false;
61 }
62 GeneralValidationError that = (GeneralValidationError) o;
63 return Objects.equals(errorSource, that.errorSource)
64 && Objects.equals(value, that.value)
65 && Objects.equals(reason, that.reason);
66 }
67
68 @Override
69 public int hashCode() {
70 return Objects.hash(errorSource, value, reason);
71 }
72
73 public enum ErrorType {
74 BLANK_LABEL,
75 MIN_GREATER_THAN_MAX,
76 VALUE_OUT_OF_BOUNDS,
77 INVALID_URL,
78 INVALID_PARTITIONING
79 }
80 }
81
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/GeneralValidationError.java]
[start of services/distribution/src/main/resources/master-config/app-config.yaml]
1 #----------------------------------------------------------------------
2 # This is the Corona Warn App master configuration file.
3 # ----------------------------------------------------------------------
4 #
5 # This configuration file will be fetched by the mobile app in order to function.
6 #
7 # It currently provides settings for minimum risk score, score classes and exposure configuration.
8 #
9 # Change this file with caution!
10
11 min-risk-score: 90
12 attenuationDurationThresholds:
13 lower: 50
14 upper: 70
15 risk-score-classes: !include risk-score-classification.yaml
16 exposure-config: !include exposure-config.yaml
[end of services/distribution/src/main/resources/master-config/app-config.yaml]
</code>
Here is an example of a patch file. It consists of changes to the code base. It specifies the file names, the line numbers of each change, and the removed and added lines. A single patch file can contain changes to multiple files.
<patch>
--- a/file.py
+++ b/file.py
@@ -1,27 +1,35 @@
def euclidean(a, b):
- while b:
- a, b = b, a % b
- return a
+ if b == 0:
+ return a
+ return euclidean(b, a % b)
def bresenham(x0, y0, x1, y1):
points = []
dx = abs(x1 - x0)
dy = abs(y1 - y0)
- sx = 1 if x0 < x1 else -1
- sy = 1 if y0 < y1 else -1
- err = dx - dy
+ x, y = x0, y0
+ sx = -1 if x0 > x1 else 1
+ sy = -1 if y0 > y1 else 1
- while True:
- points.append((x0, y0))
- if x0 == x1 and y0 == y1:
- break
- e2 = 2 * err
- if e2 > -dy:
+ if dx > dy:
+ err = dx / 2.0
+ while x != x1:
+ points.append((x, y))
err -= dy
- x0 += sx
- if e2 < dx:
- err += dx
- y0 += sy
+ if err < 0:
+ y += sy
+ err += dx
+ x += sx
+ else:
+ err = dy / 2.0
+ while y != y1:
+ points.append((x, y))
+ err -= dx
+ if err < 0:
+ x += sx
+ err += dy
+ y += sy
+ points.append((x, y))
return points
</patch>
I need you to solve the provded issue by generating a single patch file that I can apply directly to this repository using git apply. Please respond with a single patch file in the format shown above.
Respond below:
| corona-warn-app/cwa-server | 2be284e0518658dcb7ef8d1df5515fd5f962e242 | Application Configuration: Add version update support
We would like to keep the mobile application informed about new releases/current release of the app. This information can then be presented to the user, in order to ask for applying updates.
We would like to add new fields to the application config (example values):
```yaml
app-version:
ios:
latest: 1.5.2
min: 1.2.2
android:
latest: 1.3.2
min: 1.1.2
```
After downloading the config, the app checks whether the signature can be verified. If that is the case, it will get the current & min values from the config based on the target platform.
This information can now be used to prompt users for updating the app. The values for the versions must follow semantic versioning.
| 2020-06-02T19:03:56 | <patch>
diff --git a/common/protocols/src/main/proto/app/coronawarn/server/common/protocols/internal/app_config.proto b/common/protocols/src/main/proto/app/coronawarn/server/common/protocols/internal/app_config.proto
--- a/common/protocols/src/main/proto/app/coronawarn/server/common/protocols/internal/app_config.proto
+++ b/common/protocols/src/main/proto/app/coronawarn/server/common/protocols/internal/app_config.proto
@@ -4,6 +4,7 @@ option java_package = "app.coronawarn.server.common.protocols.internal";
option java_multiple_files = true;
import "app/coronawarn/server/common/protocols/internal/risk_score_classification.proto";
import "app/coronawarn/server/common/protocols/internal/risk_score_parameters.proto";
+import "app/coronawarn/server/common/protocols/internal/app_version_config.proto";
message ApplicationConfiguration {
@@ -14,6 +15,8 @@ message ApplicationConfiguration {
app.coronawarn.server.common.protocols.internal.RiskScoreParameters exposureConfig = 3;
AttenuationDurationThresholds attenuationDurationThresholds = 4;
+
+ app.coronawarn.server.common.protocols.internal.ApplicationVersionConfiguration appVersion = 5;
}
message AttenuationDurationThresholds {
diff --git a/common/protocols/src/main/proto/app/coronawarn/server/common/protocols/internal/app_version_config.proto b/common/protocols/src/main/proto/app/coronawarn/server/common/protocols/internal/app_version_config.proto
new file mode 100644
--- /dev/null
+++ b/common/protocols/src/main/proto/app/coronawarn/server/common/protocols/internal/app_version_config.proto
@@ -0,0 +1,20 @@
+syntax = "proto3";
+package app.coronawarn.server.common.protocols.internal;
+option java_package = "app.coronawarn.server.common.protocols.internal";
+option java_multiple_files = true;
+
+message ApplicationVersionConfiguration {
+ ApplicationVersionInfo ios = 1;
+ ApplicationVersionInfo android = 2;
+}
+
+message ApplicationVersionInfo {
+ SemanticVersion latest = 1;
+ SemanticVersion min = 2;
+}
+
+message SemanticVersion {
+ uint32 major = 1;
+ uint32 minor = 2;
+ uint32 patch = 3;
+}
\ No newline at end of file
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/ApplicationVersionConfigurationProvider.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/ApplicationVersionConfigurationProvider.java
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/ApplicationVersionConfigurationProvider.java
@@ -0,0 +1,56 @@
+/*
+ * ---license-start
+ * Corona-Warn-App
+ * ---
+ * Copyright (C) 2020 SAP SE and all other contributors
+ * ---
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://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 for the specific language governing permissions and
+ * limitations under the License.
+ * ---license-end
+ */
+
+package app.coronawarn.server.services.distribution.assembly.appconfig;
+
+import app.coronawarn.server.common.protocols.internal.ApplicationVersionConfiguration;
+
+/**
+ * Provides the mobile app version configuration based on a file in the file system.<br> The existing file must be a
+ * valid YAML file, and must match the specification of the proto file app_version_config.proto.
+ */
+public class ApplicationVersionConfigurationProvider {
+
+ /**
+ * The location of the app version config master file.
+ */
+ public static final String MASTER_FILE = "master-config/app-version-config.yaml";
+
+ /**
+ * Fetches the master configuration as an ApplicationVersionConfig instance.
+ *
+ * @return the mobile app version configuration as ApplicationVersionConfig
+ * @throws UnableToLoadFileException when the file/transformation did not succeed
+ */
+ public static ApplicationVersionConfiguration readMasterFile() throws UnableToLoadFileException {
+ return readFile(MASTER_FILE);
+ }
+
+ /**
+ * Fetches an app version configuration file based on the given path. The path must be available in the classloader.
+ *
+ * @param path the path, e.g. folder/my-app-version-config.yaml
+ * @return the ApplicationVersionConfig
+ * @throws UnableToLoadFileException when the file/transformation did not succeed
+ */
+ public static ApplicationVersionConfiguration readFile(String path) throws UnableToLoadFileException {
+ return YamlLoader.loadYamlIntoProtobufBuilder(path, ApplicationVersionConfiguration.Builder.class).build();
+ }
+}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/YamlLoader.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/YamlLoader.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/YamlLoader.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/YamlLoader.java
@@ -50,8 +50,8 @@ public static <T extends Message.Builder> T loadYamlIntoProtobufBuilder(String p
// no setters for generated message classes available
yaml.setBeanAccess(BeanAccess.FIELD);
- Resource riskScoreParametersResource = new ClassPathResource(path);
- try (InputStream inputStream = riskScoreParametersResource.getInputStream()) {
+ Resource configurationResource = new ClassPathResource(path);
+ try (InputStream inputStream = configurationResource.getInputStream()) {
T loaded = yaml.loadAs(inputStream, builderType);
if (loaded == null) {
throw new UnableToLoadFileException(path);
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ApplicationVersionConfigurationValidator.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ApplicationVersionConfigurationValidator.java
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ApplicationVersionConfigurationValidator.java
@@ -0,0 +1,81 @@
+/*
+ * ---license-start
+ * Corona-Warn-App
+ * ---
+ * Copyright (C) 2020 SAP SE and all other contributors
+ * ---
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://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 for the specific language governing permissions and
+ * limitations under the License.
+ * ---license-end
+ */
+
+package app.coronawarn.server.services.distribution.assembly.appconfig.validation;
+
+import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.GeneralValidationError.ErrorType.MIN_GREATER_THAN_MAX;
+
+import app.coronawarn.server.common.protocols.internal.ApplicationVersionConfiguration;
+import app.coronawarn.server.common.protocols.internal.ApplicationVersionInfo;
+import app.coronawarn.server.common.protocols.internal.SemanticVersion;
+
+public class ApplicationVersionConfigurationValidator extends ConfigurationValidator {
+
+ private final ApplicationVersionConfiguration config;
+
+ public ApplicationVersionConfigurationValidator(ApplicationVersionConfiguration config) {
+ this.config = config;
+ }
+
+ @Override
+ public ValidationResult validate() {
+ this.errors = new ValidationResult();
+ validateApplicationVersionInfo("ios", config.getIos());
+ validateApplicationVersionInfo("android", config.getAndroid());
+ return this.errors;
+ }
+
+ private void validateApplicationVersionInfo(String name, ApplicationVersionInfo appVersionInfo) {
+ SemanticVersion minVersion = appVersionInfo.getMin();
+ ComparisonResult comparisonResult = compare(appVersionInfo.getLatest(), minVersion);
+ if (ComparisonResult.LOWER.equals(comparisonResult)) {
+ this.errors.add(new GeneralValidationError(name + ": latest/min",
+ minVersion.getMajor() + "." + minVersion.getMinor() + "." + minVersion.getPatch(), MIN_GREATER_THAN_MAX));
+ }
+ }
+
+ private ComparisonResult compare(SemanticVersion left, SemanticVersion right) {
+ if (left.getMajor() < right.getMajor()) {
+ return ComparisonResult.LOWER;
+ }
+ if (left.getMajor() > right.getMajor()) {
+ return ComparisonResult.HIGHER;
+ }
+ if (left.getMinor() < right.getMinor()) {
+ return ComparisonResult.LOWER;
+ }
+ if (left.getMinor() > right.getMinor()) {
+ return ComparisonResult.HIGHER;
+ }
+ if (left.getPatch() < right.getPatch()) {
+ return ComparisonResult.LOWER;
+ }
+ if (left.getPatch() > right.getPatch()) {
+ return ComparisonResult.HIGHER;
+ }
+ return ComparisonResult.EQUAL;
+ }
+
+ private enum ComparisonResult {
+ LOWER,
+ EQUAL,
+ HIGHER
+ }
+}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/GeneralValidationError.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/GeneralValidationError.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/GeneralValidationError.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/GeneralValidationError.java
@@ -44,7 +44,7 @@ public GeneralValidationError(String errorSource, Object value, ErrorType reason
@Override
public String toString() {
- return "GeneralValidationError{"
+ return "RiskScoreClassificationValidationError{"
+ "errorType=" + reason
+ ", parameter='" + errorSource + '\''
+ ", givenValue=" + value
diff --git a/services/distribution/src/main/resources/master-config/app-config.yaml b/services/distribution/src/main/resources/master-config/app-config.yaml
--- a/services/distribution/src/main/resources/master-config/app-config.yaml
+++ b/services/distribution/src/main/resources/master-config/app-config.yaml
@@ -13,4 +13,5 @@ attenuationDurationThresholds:
lower: 50
upper: 70
risk-score-classes: !include risk-score-classification.yaml
-exposure-config: !include exposure-config.yaml
\ No newline at end of file
+exposure-config: !include exposure-config.yaml
+app-version: !include app-version-config.yaml
\ No newline at end of file
diff --git a/services/distribution/src/main/resources/master-config/app-version-config.yaml b/services/distribution/src/main/resources/master-config/app-version-config.yaml
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/main/resources/master-config/app-version-config.yaml
@@ -0,0 +1,25 @@
+# This is the Application Version Configuration master file which contains information for clients
+# about the latest and minimum supported mobile app versions on Android and iOS.
+#
+# The latest version must not be lower than the min version.
+#
+# Change this file with caution!
+
+ios:
+ latest:
+ major: 1
+ minor: 5
+ patch: 2
+ min:
+ major: 1
+ minor: 2
+ patch: 2
+android:
+ latest:
+ major: 1
+ minor: 3
+ patch: 2
+ min:
+ major: 1
+ minor: 1
+ patch: 2
\ No newline at end of file
</patch> | diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/ApplicationVersionConfigurationProviderMasterFileTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/ApplicationVersionConfigurationProviderMasterFileTest.java
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/ApplicationVersionConfigurationProviderMasterFileTest.java
@@ -0,0 +1,49 @@
+/*-
+ * ---license-start
+ * Corona-Warn-App
+ * ---
+ * Copyright (C) 2020 SAP SE and all other contributors
+ * ---
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://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 for the specific language governing permissions and
+ * limitations under the License.
+ * ---license-end
+ */
+
+package app.coronawarn.server.services.distribution.assembly.appconfig;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import app.coronawarn.server.services.distribution.assembly.appconfig.validation.ApplicationVersionConfigurationValidator;
+import app.coronawarn.server.services.distribution.assembly.appconfig.validation.ExposureConfigurationValidator;
+import app.coronawarn.server.services.distribution.assembly.appconfig.validation.ValidationResult;
+import org.junit.jupiter.api.Test;
+
+/**
+ * This test will verify that the provided Exposure Configuration master file is syntactically
+ * correct and according to spec.
+ * <p>
+ * There should never be any deployment when this test is failing.
+ */
+class ApplicationVersionConfigurationProviderMasterFileTest {
+
+ private static final ValidationResult SUCCESS = new ValidationResult();
+
+ @Test
+ void testMasterFile() throws UnableToLoadFileException {
+ var config = ApplicationVersionConfigurationProvider.readMasterFile();
+
+ var validator = new ApplicationVersionConfigurationValidator(config);
+ ValidationResult result = validator.validate();
+
+ assertThat(result).isEqualTo(SUCCESS);
+ }
+}
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/ApplicationVersionConfigurationProviderTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/ApplicationVersionConfigurationProviderTest.java
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/ApplicationVersionConfigurationProviderTest.java
@@ -0,0 +1,59 @@
+/*
+ * ---license-start
+ * Corona-Warn-App
+ * ---
+ * Copyright (C) 2020 SAP SE and all other contributors
+ * ---
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://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 for the specific language governing permissions and
+ * limitations under the License.
+ * ---license-end
+ */
+
+package app.coronawarn.server.services.distribution.assembly.appconfig;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.catchThrowable;
+
+import app.coronawarn.server.common.protocols.internal.ApplicationVersionConfiguration;
+import org.junit.jupiter.api.Test;
+
+public class ApplicationVersionConfigurationProviderTest {
+
+ @Test
+ void okFile() throws UnableToLoadFileException {
+ ApplicationVersionConfiguration result =
+ ApplicationVersionConfigurationProvider.readFile("app-version/all_ok.yaml");
+
+ assertThat(result).withFailMessage("File is null, indicating loading failed").isNotNull();
+ }
+
+ @Test
+ void wrongFile() {
+ assertUnableToLoadFile("app-version/wrong_file.yaml");
+ }
+
+ @Test
+ void brokenSyntax() {
+ assertUnableToLoadFile("app-version/broken_syntax.yaml");
+ }
+
+ @Test
+ void doesNotExist() {
+ assertUnableToLoadFile("file_does_not_exist_anywhere.yaml");
+ }
+
+ public static void assertUnableToLoadFile(String s) {
+ assertThat(catchThrowable(() ->
+ ApplicationVersionConfigurationProvider.readFile(s)))
+ .isInstanceOf(UnableToLoadFileException.class);
+ }
+}
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ApplicationVersionConfigurationValidatorTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ApplicationVersionConfigurationValidatorTest.java
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ApplicationVersionConfigurationValidatorTest.java
@@ -0,0 +1,61 @@
+/*
+ * ---license-start
+ * Corona-Warn-App
+ * ---
+ * Copyright (C) 2020 SAP SE and all other contributors
+ * ---
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://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 for the specific language governing permissions and
+ * limitations under the License.
+ * ---license-end
+ */
+
+package app.coronawarn.server.services.distribution.assembly.appconfig.validation;
+
+import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.RiskScoreClassificationValidatorTest.buildError;
+import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.RiskScoreClassificationValidatorTest.buildExpectedResult;
+import static org.assertj.core.api.Assertions.assertThat;
+
+import app.coronawarn.server.common.protocols.internal.ApplicationVersionConfiguration;
+import app.coronawarn.server.services.distribution.assembly.appconfig.ApplicationVersionConfigurationProvider;
+import app.coronawarn.server.services.distribution.assembly.appconfig.UnableToLoadFileException;
+import app.coronawarn.server.services.distribution.assembly.appconfig.validation.GeneralValidationError.ErrorType;
+import org.junit.jupiter.api.Test;
+
+public class ApplicationVersionConfigurationValidatorTest {
+
+ private static final ValidationResult SUCCESS = new ValidationResult();
+
+ @Test
+ void succeedsIfLatestEqualsMin() throws UnableToLoadFileException {
+ ApplicationVersionConfiguration config = ApplicationVersionConfigurationProvider
+ .readFile("app-version/latest-equals-min.yaml");
+ var validator = new ApplicationVersionConfigurationValidator(config);
+ assertThat(validator.validate()).isEqualTo(SUCCESS);
+ }
+
+ @Test
+ void succeedsIfLatestHigherThanMin() throws UnableToLoadFileException {
+ ApplicationVersionConfiguration config = ApplicationVersionConfigurationProvider
+ .readFile("app-version/latest-higher-than-min.yaml");
+ var validator = new ApplicationVersionConfigurationValidator(config);
+ assertThat(validator.validate()).isEqualTo(SUCCESS);
+ }
+
+ @Test
+ void failsIfLatestLowerThanMin() throws UnableToLoadFileException {
+ ApplicationVersionConfiguration config = ApplicationVersionConfigurationProvider
+ .readFile("app-version/latest-lower-than-min.yaml");
+ var validator = new ApplicationVersionConfigurationValidator(config);
+ assertThat(validator.validate())
+ .isEqualTo(buildExpectedResult(buildError("ios: latest/min", "1.2.2", ErrorType.MIN_GREATER_THAN_MAX)));
+ }
+}
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/RiskScoreClassificationValidatorTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/RiskScoreClassificationValidatorTest.java
--- a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/RiskScoreClassificationValidatorTest.java
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/RiskScoreClassificationValidatorTest.java
@@ -150,7 +150,7 @@ private static Stream<Arguments> createValidClassifications() {
).map(Arguments::of);
}
- private static GeneralValidationError buildError(String parameter, Object value, ErrorType reason) {
+ public static GeneralValidationError buildError(String parameter, Object value, ErrorType reason) {
return new GeneralValidationError(parameter, value, reason);
}
diff --git a/services/distribution/src/test/resources/app-version/all_ok.yaml b/services/distribution/src/test/resources/app-version/all_ok.yaml
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/test/resources/app-version/all_ok.yaml
@@ -0,0 +1,18 @@
+ios:
+ latest:
+ major: 1
+ minor: 5
+ patch: 2
+ min:
+ major: 1
+ minor: 2
+ patch: 2
+android:
+ latest:
+ major: 1
+ minor: 3
+ patch: 2
+ min:
+ major: 1
+ minor: 1
+ patch: 2
diff --git a/services/distribution/src/test/resources/app-version/broken_syntax.yaml b/services/distribution/src/test/resources/app-version/broken_syntax.yaml
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/test/resources/app-version/broken_syntax.yaml
@@ -0,0 +1,18 @@
+ios:
+ latest:
+ major: 1 # wrong syntax, indent too high
+ minor: 5
+ patch: 2
+ min:
+ major: 1
+ minor: 2
+ patch: 2
+android:
+ latest:
+ major: 1
+ minor: 3
+ patch: 2
+ min:
+ major: 1
+ minor: 1
+ patch: 2
diff --git a/services/distribution/src/test/resources/app-version/empty.yaml b/services/distribution/src/test/resources/app-version/empty.yaml
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/test/resources/app-version/empty.yaml
@@ -0,0 +1 @@
+# empty file
\ No newline at end of file
diff --git a/services/distribution/src/test/resources/app-version/latest-equals-min.yaml b/services/distribution/src/test/resources/app-version/latest-equals-min.yaml
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/test/resources/app-version/latest-equals-min.yaml
@@ -0,0 +1,18 @@
+ios:
+ latest:
+ major: 1
+ minor: 2
+ patch: 2
+ min:
+ major: 1
+ minor: 2
+ patch: 2
+android:
+ latest:
+ major: 1
+ minor: 3
+ patch: 2
+ min:
+ major: 1
+ minor: 3
+ patch: 2
diff --git a/services/distribution/src/test/resources/app-version/latest-higher-than-min.yaml b/services/distribution/src/test/resources/app-version/latest-higher-than-min.yaml
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/test/resources/app-version/latest-higher-than-min.yaml
@@ -0,0 +1,18 @@
+ios:
+ latest:
+ major: 1
+ minor: 2
+ patch: 3
+ min:
+ major: 1
+ minor: 2
+ patch: 2
+android:
+ latest:
+ major: 1
+ minor: 3
+ patch: 2
+ min:
+ major: 1
+ minor: 3
+ patch: 2
diff --git a/services/distribution/src/test/resources/app-version/latest-lower-than-min.yaml b/services/distribution/src/test/resources/app-version/latest-lower-than-min.yaml
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/test/resources/app-version/latest-lower-than-min.yaml
@@ -0,0 +1,18 @@
+ios:
+ latest:
+ major: 1
+ minor: 2
+ patch: 1
+ min:
+ major: 1
+ minor: 2
+ patch: 2
+android:
+ latest:
+ major: 1
+ minor: 3
+ patch: 2
+ min:
+ major: 1
+ minor: 3
+ patch: 2
diff --git a/services/distribution/src/test/resources/app-version/wrong_file.yaml b/services/distribution/src/test/resources/app-version/wrong_file.yaml
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/test/resources/app-version/wrong_file.yaml
@@ -0,0 +1,20 @@
+ID: com.acme.mta.sample
+version: 1.0.1
+modules:
+ - name: pricing-ui
+ type: nodejs
+ path: ./ui
+ requires:
+ - name: thedatabase
+
+ - name: pricing-backend
+ type: java
+ path: ./backend
+ provides:
+ - name: price_opt
+ properties:
+ protocol: http
+ uri: myhost.mydomain
+resources:
+ - name: thedatabase
+ type: com.sap.xs.hdi-container
\ No newline at end of file
diff --git a/services/distribution/src/test/resources/configtests/app-config_ok.yaml b/services/distribution/src/test/resources/configtests/app-config_ok.yaml
--- a/services/distribution/src/test/resources/configtests/app-config_ok.yaml
+++ b/services/distribution/src/test/resources/configtests/app-config_ok.yaml
@@ -3,4 +3,5 @@ attenuationDurationThresholds:
lower: 50
upper: 70
risk-score-classes: !include risk-score-class_ok.yaml
-exposure-config: !include exposure-config_ok.yaml
\ No newline at end of file
+exposure-config: !include exposure-config_ok.yaml
+app-version: !include app-version-config_ok.yaml
\ No newline at end of file
diff --git a/services/distribution/src/test/resources/configtests/app-version-config_ok.yaml b/services/distribution/src/test/resources/configtests/app-version-config_ok.yaml
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/test/resources/configtests/app-version-config_ok.yaml
@@ -0,0 +1,18 @@
+ios:
+ latest:
+ major: 1
+ minor: 5
+ patch: 2
+ min:
+ major: 1
+ minor: 2
+ patch: 2
+android:
+ latest:
+ major: 1
+ minor: 3
+ patch: 2
+ min:
+ major: 1
+ minor: 1
+ patch: 2
| |||||
corona-warn-app__cwa-server-422 | You will be provided with a partial code base and an issue statement explaining a problem to resolve.
<issue>
Application Config: Add new Parameter attenuationDurationThresholds
Add a new parameter to the application configuration, called "attenuationDurationTresholds". With the help of this parameter, we will be able to calculate the overall risk factor much better.
Default values are: X=50, Y=70. There will be call with the RKI today night in which the values might be adjusted.
```yaml
attenuation-duration-thresholds:
lower: 50
upper: 70
```
</issue>
<code>
[start of README.md]
1 <!-- markdownlint-disable MD041 -->
2 <h1 align="center">
3 Corona-Warn-App Server
4 </h1>
5
6 <p align="center">
7 <a href="https://github.com/corona-warn-app/cwa-server/commits/" title="Last Commit"><img src="https://img.shields.io/github/last-commit/corona-warn-app/cwa-server?style=flat"></a>
8 <a href="https://github.com/corona-warn-app/cwa-server/issues" title="Open Issues"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat"></a>
9 <a href="https://circleci.com/gh/corona-warn-app/cwa-server" title="Build Status"><img src="https://circleci.com/gh/corona-warn-app/cwa-server.svg?style=shield&circle-token=4ab059989d10709df19eb4b98ab7c121a25e981a"></a>
10 <a href="https://sonarcloud.io/dashboard?id=corona-warn-app_cwa-server" title="Quality Gate"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=alert_status"></a>
11 <a href="https://sonarcloud.io/component_measures?id=corona-warn-app_cwa-server&metric=Coverage&view=list" title="Coverage"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=coverage"></a>
12 <a href="https://github.com/corona-warn-app/cwa-server/blob/master/LICENSE" title="License"><img src="https://img.shields.io/badge/License-Apache%202.0-green.svg?style=flat"></a>
13 </p>
14
15 <p align="center">
16 <a href="#development">Development</a> •
17 <a href="#service-apis">Service APIs</a> •
18 <a href="#documentation">Documentation</a> •
19 <a href="#support-and-feedback">Support</a> •
20 <a href="#how-to-contribute">Contribute</a> •
21 <a href="#contributors">Contributors</a> •
22 <a href="#repositories">Repositories</a> •
23 <a href="#licensing">Licensing</a>
24 </p>
25
26 The goal of this project is to develop the official Corona-Warn-App for Germany based on the exposure notification API from [Apple](https://www.apple.com/covid19/contacttracing/) and [Google](https://www.google.com/covid19/exposurenotifications/). The apps (for both iOS and Android) use Bluetooth technology to exchange anonymous encrypted data with other mobile phones (on which the app is also installed) in the vicinity of an app user's phone. The data is stored locally on each user's device, preventing authorities or other parties from accessing or controlling the data. This repository contains the **implementation of the server for encryption keys** for the Corona-Warn-App. This implementation is still a **work in progress**, and the code it contains is currently alpha-quality code.
27
28 In this documentation, Corona-Warn-App services are also referred to as CWA services.
29
30 ## Architecture Overview
31
32 You can find the architecture overview [here](/docs/architecture-overview.md), which will give you
33 a good starting point in how the backend services interact with other services, and what purpose
34 they serve.
35
36 ## Development
37
38 After you've checked out this repository, you can run the application in one of the following ways:
39
40 * As a [Docker](https://www.docker.com/)-based deployment on your local machine. You can run either:
41 * Single components using the respective Dockerfile or
42 * The full backend using the Docker Compose (which is considered the most convenient way)
43 * As a [Maven](https://maven.apache.org)-based build on your local machine.
44 If you want to develop something in a single component, this approach is preferable.
45
46 ### Docker-Based Deployment
47
48 If you want to use Docker-based deployment, you need to install Docker on your local machine. For more information about downloading and installing Docker, see the [official Docker documentation](https://docs.docker.com/get-docker/).
49
50 #### Running the Full CWA Backend Using Docker Compose
51
52 For your convenience, a full setup including the generation of test data has been prepared using [Docker Compose](https://docs.docker.com/compose/reference/overview/). To build the backend services, run ```docker-compose build``` in the repository's root directory. A default configuration file can be found under ```.env```in the root folder of the repository. The default values for the local Postgres and Zenko Cloudserver should be changed in this file before docker-compose is run.
53
54 Once the services are built, you can start the whole backend using ```docker-compose up```.
55 The distribution service runs once and then finishes. If you want to trigger additional distribution runs, run ```docker-compose run distribution```.
56
57 The docker-compose contains the following services:
58
59 Service | Description | Endpoint and Default Credentials
60 ------------------|-------------|-----------
61 submission | The Corona-Warn-App submission service | `http://localhost:8000` <br> `http://localhost:8006` (for actuator endpoint)
62 distribution | The Corona-Warn-App distribution service | NO ENDPOINT
63 postgres | A [postgres] database installation | `postgres:8001` <br> Username: postgres <br> Password: postgres
64 pgadmin | A [pgadmin](https://www.pgadmin.org/) installation for the postgres database | `http://localhost:8002` <br> Username: [email protected] <br> Password: password
65 cloudserver | [Zenko CloudServer] is a S3-compliant object store | `http://localhost:8003/` <br> Access key: accessKey1 <br> Secret key: verySecretKey1
66 verification-fake | A very simple fake implementation for the tan verification. | `http://localhost:8004/version/v1/tan/verify` <br> The only valid tan is "edc07f08-a1aa-11ea-bb37-0242ac130002"
67
68 ##### Known Limitation
69
70 In rare cases the docker-compose runs into a timing issue if the distribution service starts before the bucket of the objectstore was created. This is not a big issue as you can simply run ```docker-compose run distribution``` to trigger additional distribution runs after the objectstore was initialized.
71
72 #### Running Single CWA Services Using Docker
73
74 If you would like to build and run a single CWA service, it's considered easiest to run them in a Docker environment. You can do this using the script provided in the respective CWA service directory. The Docker script first builds the CWA service and then creates an image for the runtime, which means that there are no additional dependencies for you to install.
75
76 To build and run the distribution service, run the following command:
77
78 ```bash
79 ./services/distribution/build_and_run.sh
80 ```
81
82 To build and run the submission service, run the following command:
83
84 ```bash
85 ./services/submission/build_and_run.sh
86 ```
87
88 The submission service is available on [localhost:8080](http://localhost:8080 ).
89
90 ### Maven-Based Build
91
92 If you want to actively develop in one of the CWA services, the Maven-based runtime is most suitable.
93 To prepare your machine to run the CWA project locally, we recommend that you first ensure that you've installed the following:
94
95 * Minimum JDK Version 11: [OpenJDK](https://openjdk.java.net/) / [SapMachine](https://sap.github.io/SapMachine/)
96 * [Maven 3.6](https://maven.apache.org/)
97 * [Postgres]
98 * [Zenko CloudServer]
99
100 #### Configure
101
102 After you made sure that the specified dependencies are running, configure them in the respective configuration files.
103
104 * Configure the Postgres connection in the [submission config](./services/submission/src/main/resources/application.yaml) and in the [distribution config](./services/distribution/src/main/resources/application.yaml)
105 * Configure the S3 compatible object storage in the [distribution config](./services/distribution/src/main/resources/application.yaml)
106 * Configure the private key for the distribution service, the path need to be prefixed with `file:`
107 * `VAULT_FILESIGNING_SECRET` should be the path to the private key, example available in `<repo-root>/docker-compose-test-secrets/private.pem`
108
109 #### Build
110
111 After you've checked out the repository, to build the project, run ```mvn install``` in your base directory.
112
113 #### Run
114
115 Navigate to the service you want to start and run the spring-boot:run target. The configured Postgres and the configured S3 compliant object storage are used as default. When you start the submission service, the endpoint is available on your local port 8080.
116
117 If you want to start the submission service, for example, you start it as follows:
118
119 ```bash
120 cd services/submission/
121 mvn spring-boot:run
122 ```
123
124 #### Debugging
125
126 To enable the `DEBUG` log level, you can run the application using the Spring `dev` profile.
127
128 ```bash
129 mvn spring-boot:run -Dspring-boot.run.profiles=dev
130 ```
131
132 To be able to set breakpoints (e.g. in IntelliJ), it may be necessary to use the ```-Dspring-boot.run.fork=false``` parameter.
133
134 ## Service APIs
135
136 The API that is being exposed by the backend services is documented in an [OpenAPI](https://www.openapis.org/) specification. The specification files are available at the following locations:
137
138 Service | OpenAPI Specification
139 -------------|-------------
140 Submission Service | [services/submission/api_v1.json](https://github.com/corona-warn-app/cwa-server/raw/master/services/submission/api_v1.json)
141 Distribution Service | [services/distribution/api_v1.json](https://github.com/corona-warn-app/cwa-server/raw/master/services/distribution/api_v1.json)
142
143 ## Spring Profiles
144
145 ### Distribution
146
147 Profile | Effect
148 -----------------|-------------
149 `dev` | Turns the log level to `DEBUG`.
150 `cloud` | Removes default values for the `datasource` and `objectstore` configurations.
151 `demo` | Includes incomplete days and hours into the distribution run, thus creating aggregates for the current day and the current hour (and including both in the respective indices). When running multiple distributions in one hour with this profile, the date aggregate for today and the hours aggregate for the current hour will be updated and overwritten. This profile also turns off the expiry policy (Keys must be expired for at least 2 hours before distribution) and the shifting policy (there must be at least 140 keys in a distribution).
152 `testdata` | Causes test data to be inserted into the database before each distribution run. By default, around 1000 random diagnosis keys will be generated per hour. If there are no diagnosis keys in the database yet, random keys will be generated for every hour from the beginning of the retention period (14 days ago at 00:00 UTC) until one hour before the present hour. If there are already keys in the database, the random keys will be generated for every hour from the latest diagnosis key in the database (by submission timestamp) until one hour before the present hour (or none at all, if the latest diagnosis key in the database was submitted one hour ago or later).
153 `signature-dev` | Sets the app package ID in the export packages' signature info to `de.rki.coronawarnapp-dev` so that test certificates (instead of production certificates) will be used for client-side validation.
154 `signature-prod` | Provides production app package IDs for the signature info
155
156 ### Submission
157
158 Profile | Effect
159 -------------|-------------
160 `dev` | Turns the log level to `DEBUG`.
161 `cloud` | Removes default values for the `datasource` configuration.
162
163 ## Documentation
164
165 The full documentation for the Corona-Warn-App can be found in the [cwa-documentation](https://github.com/corona-warn-app/cwa-documentation) repository. The documentation repository contains technical documents, architecture information, and whitepapers related to this implementation.
166
167 ## Support and Feedback
168
169 The following channels are available for discussions, feedback, and support requests:
170
171 | Type | Channel |
172 | ------------------------ | ------------------------------------------------------ |
173 | **General Discussion** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="General Discussion"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/question.svg?style=flat-square"></a> </a> |
174 | **Concept Feedback** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="Open Concept Feedback"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/architecture.svg?style=flat-square"></a> |
175 | **Backend Issue** | <a href="https://github.com/corona-warn-app/cwa-server/issues/new/choose" title="Open Backend Issue"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat-square"></a> |
176 | **Other Requests** | <a href="mailto:[email protected]" title="Email CWA Team"><img src="https://img.shields.io/badge/email-CWA%20team-green?logo=mail.ru&style=flat-square&logoColor=white"></a> |
177
178 ## How to Contribute
179
180 Contribution and feedback are 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.
181
182 ## Contributors
183
184 The German government has asked SAP and Deutsche Telekom to develop the Corona-Warn-App for Germany as open source software. Deutsche Telekom is providing the network and mobile technology and will operate and run the backend for the app in a safe, scalable and stable manner. SAP is responsible for the app development, its framework and the underlying platform. Therefore, development teams of SAP and Deutsche Telekom are contributing to this project. At the same time 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.
185
186 ## Repositories
187
188 The following public repositories are currently available for the Corona-Warn-App:
189
190 | Repository | Description |
191 | ------------------- | --------------------------------------------------------------------- |
192 | [cwa-documentation] | Project overview, general documentation, and white papers |
193 | [cwa-server] | Backend implementation for the Apple/Google exposure notification API|
194 | [cwa-verification-server] | Backend implementation of the verification process|
195
196 [cwa-documentation]: https://github.com/corona-warn-app/cwa-documentation
197 [cwa-server]: https://github.com/corona-warn-app/cwa-server
198 [cwa-verification-server]: https://github.com/corona-warn-app/cwa-verification-server
199 [Postgres]: https://www.postgresql.org/
200 [HSQLDB]: http://hsqldb.org/
201 [Zenko CloudServer]: https://github.com/scality/cloudserver
202
203 ## Licensing
204
205 Copyright (c) 2020 SAP SE or an SAP affiliate company.
206
207 Licensed under the **Apache License, Version 2.0** (the "License"); you may not use this file except in compliance with the License.
208
209 You may obtain a copy of the License at <https://www.apache.org/licenses/LICENSE-2.0>.
210
211 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.
212
[end of README.md]
[start of common/protocols/src/main/proto/app/coronawarn/server/common/protocols/internal/app_config.proto]
1 syntax = "proto3";
2 package app.coronawarn.server.common.protocols.internal;
3 option java_package = "app.coronawarn.server.common.protocols.internal";
4 option java_multiple_files = true;
5 import "app/coronawarn/server/common/protocols/internal/risk_score_classification.proto";
6 import "app/coronawarn/server/common/protocols/internal/risk_score_parameters.proto";
7
8 message ApplicationConfiguration {
9
10 int32 minRiskScore = 1;
11
12 app.coronawarn.server.common.protocols.internal.RiskScoreClassification riskScoreClasses = 2;
13
14 app.coronawarn.server.common.protocols.internal.RiskScoreParameters exposureConfig = 3;
15 }
[end of common/protocols/src/main/proto/app/coronawarn/server/common/protocols/internal/app_config.proto]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ApplicationConfigurationValidator.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.distribution.assembly.appconfig.validation;
22
23 import app.coronawarn.server.common.protocols.internal.ApplicationConfiguration;
24 import app.coronawarn.server.common.protocols.internal.RiskScoreClassification;
25 import app.coronawarn.server.common.protocols.internal.RiskScoreParameters;
26
27 /**
28 * This validator validates a {@link ApplicationConfiguration}. It will re-use the {@link ConfigurationValidator} from
29 * the sub-configurations of {@link RiskScoreParameters} and {@link RiskScoreClassification}.
30 */
31 public class ApplicationConfigurationValidator extends ConfigurationValidator {
32
33 private final ApplicationConfiguration config;
34
35 /**
36 * Creates a new instance for the given {@link ApplicationConfiguration}.
37 *
38 * @param config the Application Configuration to validate.
39 */
40 public ApplicationConfigurationValidator(ApplicationConfiguration config) {
41 this.config = config;
42 }
43
44 @Override
45 public ValidationResult validate() {
46 this.errors = new ValidationResult();
47
48 validateMinRisk();
49
50 ValidationResult exposureResult = new ExposureConfigurationValidator(config.getExposureConfig()).validate();
51 ValidationResult riskScoreResult = new RiskScoreClassificationValidator(config.getRiskScoreClasses()).validate();
52
53 return errors.with(exposureResult).with(riskScoreResult);
54 }
55
56 private void validateMinRisk() {
57 int minLevel = this.config.getMinRiskScore();
58
59 if (!RiskScoreValidator.isInBounds(minLevel)) {
60 this.errors.add(new MinimumRiskLevelValidationError(minLevel));
61 }
62 }
63 }
64
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ApplicationConfigurationValidator.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ParameterSpec.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.distribution.assembly.appconfig.validation;
22
23 /**
24 * Definition of the spec according to Apple/Google:
25 * https://developer.apple.com/documentation/exposurenotification/enexposureconfiguration
26 */
27 public class ParameterSpec {
28
29 private ParameterSpec() {
30 }
31
32 /**
33 * The minimum weight value for mobile API.
34 */
35 public static final double WEIGHT_MIN = 0.001;
36
37 /**
38 * The maximum weight value for mobile API.
39 */
40 public static final int WEIGHT_MAX = 100;
41
42 /**
43 * Maximum number of allowed decimals.
44 */
45 public static final int WEIGHT_MAX_DECIMALS = 3;
46
47 /**
48 * The allowed minimum value for risk score.
49 */
50 public static final int RISK_SCORE_MIN = 0;
51
52 /**
53 * The allowed maximum value for a risk score.
54 */
55 public static final int RISK_SCORE_MAX = 4096;
56 }
57
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ParameterSpec.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/RiskScoreClassificationValidationError.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.distribution.assembly.appconfig.validation;
22
23 import java.util.Objects;
24
25 public class RiskScoreClassificationValidationError implements ValidationError {
26
27 private final String errorSource;
28
29 private final Object value;
30
31 private final ErrorType reason;
32
33 /**
34 * Creates a {@link RiskScoreClassificationValidationError} that stores the specified validation error source,
35 * erroneous value and a reason for the error to occur.
36 *
37 * @param errorSource A label that describes the property associated with this validation error.
38 * @param value The value that caused the validation error.
39 * @param reason A validation error specifier.
40 */
41 public RiskScoreClassificationValidationError(String errorSource, Object value, ErrorType reason) {
42 this.errorSource = errorSource;
43 this.value = value;
44 this.reason = reason;
45 }
46
47 @Override
48 public String toString() {
49 return "RiskScoreClassificationValidationError{"
50 + "errorType=" + reason
51 + ", parameter='" + errorSource + '\''
52 + ", givenValue=" + value
53 + '}';
54 }
55
56 @Override
57 public boolean equals(Object o) {
58 if (this == o) {
59 return true;
60 }
61 if (o == null || getClass() != o.getClass()) {
62 return false;
63 }
64 RiskScoreClassificationValidationError that = (RiskScoreClassificationValidationError) o;
65 return Objects.equals(errorSource, that.errorSource)
66 && Objects.equals(value, that.value)
67 && Objects.equals(reason, that.reason);
68 }
69
70 @Override
71 public int hashCode() {
72 return Objects.hash(errorSource, value, reason);
73 }
74
75 public enum ErrorType {
76 BLANK_LABEL,
77 MIN_GREATER_THAN_MAX,
78 VALUE_OUT_OF_BOUNDS,
79 INVALID_URL,
80 INVALID_PARTITIONING
81 }
82 }
83
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/RiskScoreClassificationValidationError.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/RiskScoreClassificationValidator.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.distribution.assembly.appconfig.validation;
22
23 import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.RiskScoreClassificationValidationError.ErrorType.BLANK_LABEL;
24 import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.RiskScoreClassificationValidationError.ErrorType.INVALID_PARTITIONING;
25 import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.RiskScoreClassificationValidationError.ErrorType.INVALID_URL;
26 import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.RiskScoreClassificationValidationError.ErrorType.MIN_GREATER_THAN_MAX;
27 import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.RiskScoreClassificationValidationError.ErrorType.VALUE_OUT_OF_BOUNDS;
28
29 import app.coronawarn.server.common.protocols.internal.RiskScoreClass;
30 import app.coronawarn.server.common.protocols.internal.RiskScoreClassification;
31 import java.net.MalformedURLException;
32 import java.net.URL;
33
34 /**
35 * The RiskScoreClassificationValidator validates the values of an associated {@link RiskScoreClassification} instance.
36 */
37 public class RiskScoreClassificationValidator extends ConfigurationValidator {
38
39 private final RiskScoreClassification riskScoreClassification;
40
41 public RiskScoreClassificationValidator(RiskScoreClassification riskScoreClassification) {
42 this.riskScoreClassification = riskScoreClassification;
43 }
44
45 /**
46 * Performs a validation of the associated {@link RiskScoreClassification} instance and returns information about
47 * validation failures.
48 *
49 * @return The ValidationResult instance, containing information about possible errors.
50 */
51 @Override
52 public ValidationResult validate() {
53 errors = new ValidationResult();
54
55 validateValues();
56 validateValueRangeCoverage();
57
58 return errors;
59 }
60
61 private void validateValues() {
62 for (RiskScoreClass riskScoreClass : riskScoreClassification.getRiskClassesList()) {
63 int minRiskLevel = riskScoreClass.getMin();
64 int maxRiskLevel = riskScoreClass.getMax();
65
66 validateLabel(riskScoreClass.getLabel());
67 validateRiskScoreValueBounds(minRiskLevel);
68 validateRiskScoreValueBounds(maxRiskLevel);
69 validateUrl(riskScoreClass.getUrl());
70
71 if (minRiskLevel > maxRiskLevel) {
72 errors.add(new RiskScoreClassificationValidationError(
73 "minRiskLevel, maxRiskLevel", minRiskLevel + ", " + maxRiskLevel, MIN_GREATER_THAN_MAX));
74 }
75 }
76 }
77
78 private void validateLabel(String label) {
79 if (label.isBlank()) {
80 errors.add(new RiskScoreClassificationValidationError("label", label, BLANK_LABEL));
81 }
82 }
83
84 private void validateRiskScoreValueBounds(int value) {
85 if (!RiskScoreValidator.isInBounds(value)) {
86 errors.add(new RiskScoreClassificationValidationError("minRiskLevel/maxRiskLevel", value, VALUE_OUT_OF_BOUNDS));
87 }
88 }
89
90 private void validateUrl(String url) {
91 try {
92 new URL(url.trim());
93 } catch (MalformedURLException e) {
94 errors.add(new RiskScoreClassificationValidationError("url", url, INVALID_URL));
95 }
96 }
97
98 private void validateValueRangeCoverage() {
99 int partitionSum = riskScoreClassification.getRiskClassesList().stream()
100 .mapToInt(riskScoreClass -> (riskScoreClass.getMax() - riskScoreClass.getMin() + 1))
101 .sum();
102
103 if (partitionSum != ParameterSpec.RISK_SCORE_MAX + 1) {
104 errors.add(new RiskScoreClassificationValidationError("covered value range", partitionSum, INVALID_PARTITIONING));
105 }
106 }
107 }
108
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/RiskScoreClassificationValidator.java]
[start of services/distribution/src/main/resources/master-config/app-config.yaml]
1 #----------------------------------------------------------------------
2 # This is the Corona Warn App master configuration file.
3 # ----------------------------------------------------------------------
4 #
5 # This configuration file will be fetched by the mobile app in order to function.
6 #
7 # It currently provides settings for minimum risk score, score classes and exposure configuration.
8 #
9 # Change this file with caution!
10
11 min-risk-score: 90
12 risk-score-classes: !include risk-score-classification.yaml
13 exposure-config: !include exposure-config.yaml
[end of services/distribution/src/main/resources/master-config/app-config.yaml]
</code>
Here is an example of a patch file. It consists of changes to the code base. It specifies the file names, the line numbers of each change, and the removed and added lines. A single patch file can contain changes to multiple files.
<patch>
--- a/file.py
+++ b/file.py
@@ -1,27 +1,35 @@
def euclidean(a, b):
- while b:
- a, b = b, a % b
- return a
+ if b == 0:
+ return a
+ return euclidean(b, a % b)
def bresenham(x0, y0, x1, y1):
points = []
dx = abs(x1 - x0)
dy = abs(y1 - y0)
- sx = 1 if x0 < x1 else -1
- sy = 1 if y0 < y1 else -1
- err = dx - dy
+ x, y = x0, y0
+ sx = -1 if x0 > x1 else 1
+ sy = -1 if y0 > y1 else 1
- while True:
- points.append((x0, y0))
- if x0 == x1 and y0 == y1:
- break
- e2 = 2 * err
- if e2 > -dy:
+ if dx > dy:
+ err = dx / 2.0
+ while x != x1:
+ points.append((x, y))
err -= dy
- x0 += sx
- if e2 < dx:
- err += dx
- y0 += sy
+ if err < 0:
+ y += sy
+ err += dx
+ x += sx
+ else:
+ err = dy / 2.0
+ while y != y1:
+ points.append((x, y))
+ err -= dx
+ if err < 0:
+ x += sx
+ err += dy
+ y += sy
+ points.append((x, y))
return points
</patch>
I need you to solve the provded issue by generating a single patch file that I can apply directly to this repository using git apply. Please respond with a single patch file in the format shown above.
Respond below:
| corona-warn-app/cwa-server | 1032f0e5950d2d6fa064da7026825e3c25260c79 | Application Config: Add new Parameter attenuationDurationThresholds
Add a new parameter to the application configuration, called "attenuationDurationTresholds". With the help of this parameter, we will be able to calculate the overall risk factor much better.
Default values are: X=50, Y=70. There will be call with the RKI today night in which the values might be adjusted.
```yaml
attenuation-duration-thresholds:
lower: 50
upper: 70
```
| Are there any known constraints that define the validity of X/Y values?
Should be:
- type: integer
- 0 to 100 (upper bound might change though, but use 100 for now)
- x must by lower than y -> so would also be nice to make that more explicit, by calling them lower and upper. (edited description of ticket) | 2020-06-02T17:41:10 | <patch>
diff --git a/common/protocols/src/main/proto/app/coronawarn/server/common/protocols/internal/app_config.proto b/common/protocols/src/main/proto/app/coronawarn/server/common/protocols/internal/app_config.proto
--- a/common/protocols/src/main/proto/app/coronawarn/server/common/protocols/internal/app_config.proto
+++ b/common/protocols/src/main/proto/app/coronawarn/server/common/protocols/internal/app_config.proto
@@ -12,4 +12,11 @@ message ApplicationConfiguration {
app.coronawarn.server.common.protocols.internal.RiskScoreClassification riskScoreClasses = 2;
app.coronawarn.server.common.protocols.internal.RiskScoreParameters exposureConfig = 3;
+
+ AttenuationDurationThresholds attenuationDurationThresholds = 4;
+}
+
+message AttenuationDurationThresholds {
+ int32 lower = 1;
+ int32 upper = 2;
}
\ No newline at end of file
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ApplicationConfigurationValidator.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ApplicationConfigurationValidator.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ApplicationConfigurationValidator.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ApplicationConfigurationValidator.java
@@ -20,6 +20,11 @@
package app.coronawarn.server.services.distribution.assembly.appconfig.validation;
+import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.GeneralValidationError.ErrorType.MIN_GREATER_THAN_MAX;
+import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.GeneralValidationError.ErrorType.VALUE_OUT_OF_BOUNDS;
+import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.ParameterSpec.ATTENUATION_DURATION_THRESHOLD_MAX;
+import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.ParameterSpec.ATTENUATION_DURATION_THRESHOLD_MIN;
+
import app.coronawarn.server.common.protocols.internal.ApplicationConfiguration;
import app.coronawarn.server.common.protocols.internal.RiskScoreClassification;
import app.coronawarn.server.common.protocols.internal.RiskScoreParameters;
@@ -46,6 +51,7 @@ public ValidationResult validate() {
this.errors = new ValidationResult();
validateMinRisk();
+ validateAttenuationDurationThresholds();
ValidationResult exposureResult = new ExposureConfigurationValidator(config.getExposureConfig()).validate();
ValidationResult riskScoreResult = new RiskScoreClassificationValidator(config.getRiskScoreClasses()).validate();
@@ -60,4 +66,25 @@ private void validateMinRisk() {
this.errors.add(new MinimumRiskLevelValidationError(minLevel));
}
}
+
+ private void validateAttenuationDurationThresholds() {
+ int lower = config.getAttenuationDurationThresholds().getLower();
+ int upper = config.getAttenuationDurationThresholds().getUpper();
+
+ checkThresholdBound("lower", lower);
+ checkThresholdBound("upper", upper);
+
+ if (lower > upper) {
+ String parameters = "attenuationDurationThreshold.lower, attenuationDurationThreshold.upper";
+ String values = lower + ", " + upper;
+ this.errors.add(new GeneralValidationError(parameters, values, MIN_GREATER_THAN_MAX));
+ }
+ }
+
+ private void checkThresholdBound(String boundLabel, int boundValue) {
+ if (boundValue < ATTENUATION_DURATION_THRESHOLD_MIN || boundValue > ATTENUATION_DURATION_THRESHOLD_MAX) {
+ this.errors.add(
+ new GeneralValidationError("attenuationDurationThreshold." + boundLabel, boundValue, VALUE_OUT_OF_BOUNDS));
+ }
+ }
}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/RiskScoreClassificationValidationError.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/GeneralValidationError.java
similarity index 82%
rename from services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/RiskScoreClassificationValidationError.java
rename to services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/GeneralValidationError.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/RiskScoreClassificationValidationError.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/GeneralValidationError.java
@@ -22,23 +22,21 @@
import java.util.Objects;
-public class RiskScoreClassificationValidationError implements ValidationError {
+public class GeneralValidationError implements ValidationError {
private final String errorSource;
-
private final Object value;
-
private final ErrorType reason;
/**
- * Creates a {@link RiskScoreClassificationValidationError} that stores the specified validation error source,
+ * Creates a {@link GeneralValidationError} that stores the specified validation error source,
* erroneous value and a reason for the error to occur.
*
* @param errorSource A label that describes the property associated with this validation error.
* @param value The value that caused the validation error.
* @param reason A validation error specifier.
*/
- public RiskScoreClassificationValidationError(String errorSource, Object value, ErrorType reason) {
+ public GeneralValidationError(String errorSource, Object value, ErrorType reason) {
this.errorSource = errorSource;
this.value = value;
this.reason = reason;
@@ -46,7 +44,7 @@ public RiskScoreClassificationValidationError(String errorSource, Object value,
@Override
public String toString() {
- return "RiskScoreClassificationValidationError{"
+ return "GeneralValidationError{"
+ "errorType=" + reason
+ ", parameter='" + errorSource + '\''
+ ", givenValue=" + value
@@ -61,7 +59,7 @@ public boolean equals(Object o) {
if (o == null || getClass() != o.getClass()) {
return false;
}
- RiskScoreClassificationValidationError that = (RiskScoreClassificationValidationError) o;
+ GeneralValidationError that = (GeneralValidationError) o;
return Objects.equals(errorSource, that.errorSource)
&& Objects.equals(value, that.value)
&& Objects.equals(reason, that.reason);
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ParameterSpec.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ParameterSpec.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ParameterSpec.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ParameterSpec.java
@@ -53,4 +53,14 @@ private ParameterSpec() {
* The allowed maximum value for a risk score.
*/
public static final int RISK_SCORE_MAX = 4096;
+
+ /**
+ * The allowed minimum value for an attenuation threshold.
+ */
+ public static final int ATTENUATION_DURATION_THRESHOLD_MIN = 0;
+
+ /**
+ * The allowed maximum value for an attenuation threshold.
+ */
+ public static final int ATTENUATION_DURATION_THRESHOLD_MAX = 100;
}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/RiskScoreClassificationValidator.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/RiskScoreClassificationValidator.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/RiskScoreClassificationValidator.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/RiskScoreClassificationValidator.java
@@ -20,11 +20,11 @@
package app.coronawarn.server.services.distribution.assembly.appconfig.validation;
-import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.RiskScoreClassificationValidationError.ErrorType.BLANK_LABEL;
-import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.RiskScoreClassificationValidationError.ErrorType.INVALID_PARTITIONING;
-import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.RiskScoreClassificationValidationError.ErrorType.INVALID_URL;
-import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.RiskScoreClassificationValidationError.ErrorType.MIN_GREATER_THAN_MAX;
-import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.RiskScoreClassificationValidationError.ErrorType.VALUE_OUT_OF_BOUNDS;
+import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.GeneralValidationError.ErrorType.BLANK_LABEL;
+import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.GeneralValidationError.ErrorType.INVALID_PARTITIONING;
+import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.GeneralValidationError.ErrorType.INVALID_URL;
+import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.GeneralValidationError.ErrorType.MIN_GREATER_THAN_MAX;
+import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.GeneralValidationError.ErrorType.VALUE_OUT_OF_BOUNDS;
import app.coronawarn.server.common.protocols.internal.RiskScoreClass;
import app.coronawarn.server.common.protocols.internal.RiskScoreClassification;
@@ -69,7 +69,7 @@ private void validateValues() {
validateUrl(riskScoreClass.getUrl());
if (minRiskLevel > maxRiskLevel) {
- errors.add(new RiskScoreClassificationValidationError(
+ errors.add(new GeneralValidationError(
"minRiskLevel, maxRiskLevel", minRiskLevel + ", " + maxRiskLevel, MIN_GREATER_THAN_MAX));
}
}
@@ -77,13 +77,13 @@ private void validateValues() {
private void validateLabel(String label) {
if (label.isBlank()) {
- errors.add(new RiskScoreClassificationValidationError("label", label, BLANK_LABEL));
+ errors.add(new GeneralValidationError("label", label, BLANK_LABEL));
}
}
private void validateRiskScoreValueBounds(int value) {
if (!RiskScoreValidator.isInBounds(value)) {
- errors.add(new RiskScoreClassificationValidationError("minRiskLevel/maxRiskLevel", value, VALUE_OUT_OF_BOUNDS));
+ errors.add(new GeneralValidationError("minRiskLevel/maxRiskLevel", value, VALUE_OUT_OF_BOUNDS));
}
}
@@ -91,7 +91,7 @@ private void validateUrl(String url) {
try {
new URL(url.trim());
} catch (MalformedURLException e) {
- errors.add(new RiskScoreClassificationValidationError("url", url, INVALID_URL));
+ errors.add(new GeneralValidationError("url", url, INVALID_URL));
}
}
@@ -101,7 +101,7 @@ private void validateValueRangeCoverage() {
.sum();
if (partitionSum != ParameterSpec.RISK_SCORE_MAX + 1) {
- errors.add(new RiskScoreClassificationValidationError("covered value range", partitionSum, INVALID_PARTITIONING));
+ errors.add(new GeneralValidationError("covered value range", partitionSum, INVALID_PARTITIONING));
}
}
}
diff --git a/services/distribution/src/main/resources/master-config/app-config.yaml b/services/distribution/src/main/resources/master-config/app-config.yaml
--- a/services/distribution/src/main/resources/master-config/app-config.yaml
+++ b/services/distribution/src/main/resources/master-config/app-config.yaml
@@ -9,5 +9,8 @@
# Change this file with caution!
min-risk-score: 90
+attenuationDurationThresholds:
+ lower: 50
+ upper: 70
risk-score-classes: !include risk-score-classification.yaml
exposure-config: !include exposure-config.yaml
\ No newline at end of file
</patch> | diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ApplicationConfigurationValidatorTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ApplicationConfigurationValidatorTest.java
--- a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ApplicationConfigurationValidatorTest.java
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ApplicationConfigurationValidatorTest.java
@@ -20,16 +20,26 @@
package app.coronawarn.server.services.distribution.assembly.appconfig.validation;
+import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.GeneralValidationError.ErrorType.MIN_GREATER_THAN_MAX;
+import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.GeneralValidationError.ErrorType.VALUE_OUT_OF_BOUNDS;
+import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.ParameterSpec.ATTENUATION_DURATION_THRESHOLD_MAX;
+import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.ParameterSpec.ATTENUATION_DURATION_THRESHOLD_MIN;
+import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.RiskScoreClassificationValidatorTest.MINIMAL_RISK_SCORE_CLASSIFICATION;
+import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.RiskScoreClassificationValidatorTest.buildExpectedResult;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import app.coronawarn.server.common.protocols.internal.ApplicationConfiguration;
+import app.coronawarn.server.common.protocols.internal.AttenuationDurationThresholds;
import app.coronawarn.server.services.distribution.assembly.appconfig.ApplicationConfigurationProvider;
+import app.coronawarn.server.services.distribution.assembly.appconfig.ExposureConfigurationProvider;
import app.coronawarn.server.services.distribution.assembly.appconfig.UnableToLoadFileException;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
+import org.junit.jupiter.params.provider.ValueSource;
class ApplicationConfigurationValidatorTest {
@@ -49,6 +59,43 @@ void negative(TestWithExpectedResult test) throws UnableToLoadFileException {
assertThat(getResultForTest(test)).isEqualTo(test.result);
}
+ @ParameterizedTest
+ @ValueSource(ints = {ATTENUATION_DURATION_THRESHOLD_MIN - 1, ATTENUATION_DURATION_THRESHOLD_MAX + 1})
+ void negativeForAttenuationDurationThresholdOutOfBounds(int invalidThresholdValue) throws Exception {
+ ApplicationConfigurationValidator validator = getValidatorForAttenuationDurationThreshold(
+ invalidThresholdValue, invalidThresholdValue);
+
+ ValidationResult expectedResult = buildExpectedResult(
+ new GeneralValidationError("attenuationDurationThreshold.upper", invalidThresholdValue, VALUE_OUT_OF_BOUNDS),
+ new GeneralValidationError("attenuationDurationThreshold.lower", invalidThresholdValue, VALUE_OUT_OF_BOUNDS));
+
+ assertThat(validator.validate()).isEqualTo(expectedResult);
+ }
+
+ @Test
+ void negativeForUpperAttenuationDurationThresholdLesserThanLower() throws Exception {
+ ApplicationConfigurationValidator validator = getValidatorForAttenuationDurationThreshold(
+ ATTENUATION_DURATION_THRESHOLD_MAX, ATTENUATION_DURATION_THRESHOLD_MIN);
+
+ ValidationResult expectedResult = buildExpectedResult(
+ new GeneralValidationError("attenuationDurationThreshold.lower, attenuationDurationThreshold.upper",
+ (ATTENUATION_DURATION_THRESHOLD_MAX + ", " + ATTENUATION_DURATION_THRESHOLD_MIN), MIN_GREATER_THAN_MAX));
+
+ assertThat(validator.validate()).isEqualTo(expectedResult);
+ }
+
+ private ApplicationConfigurationValidator getValidatorForAttenuationDurationThreshold(int lower, int upper)
+ throws Exception {
+ ApplicationConfiguration appConfig = ApplicationConfiguration.newBuilder()
+ .setMinRiskScore(100)
+ .setRiskScoreClasses(MINIMAL_RISK_SCORE_CLASSIFICATION)
+ .setExposureConfig(ExposureConfigurationProvider.readFile("configtests/exposure-config_ok.yaml"))
+ .setAttenuationDurationThresholds(AttenuationDurationThresholds.newBuilder()
+ .setLower(lower)
+ .setUpper(upper)).build();
+ return new ApplicationConfigurationValidator(appConfig);
+ }
+
@Test
void circular() {
assertThatThrownBy(() -> {
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/RiskScoreClassificationValidatorTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/RiskScoreClassificationValidatorTest.java
--- a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/RiskScoreClassificationValidatorTest.java
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/RiskScoreClassificationValidatorTest.java
@@ -20,14 +20,14 @@
package app.coronawarn.server.services.distribution.assembly.appconfig.validation;
-import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.RiskScoreClassificationValidationError.ErrorType.INVALID_PARTITIONING;
-import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.RiskScoreClassificationValidationError.ErrorType.MIN_GREATER_THAN_MAX;
+import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.GeneralValidationError.ErrorType.INVALID_PARTITIONING;
+import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.GeneralValidationError.ErrorType.MIN_GREATER_THAN_MAX;
import static java.util.Arrays.asList;
import static org.assertj.core.api.Assertions.assertThat;
import app.coronawarn.server.common.protocols.internal.RiskScoreClass;
import app.coronawarn.server.common.protocols.internal.RiskScoreClassification;
-import app.coronawarn.server.services.distribution.assembly.appconfig.validation.RiskScoreClassificationValidationError.ErrorType;
+import app.coronawarn.server.services.distribution.assembly.appconfig.validation.GeneralValidationError.ErrorType;
import java.util.Arrays;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
@@ -42,6 +42,9 @@ class RiskScoreClassificationValidatorTest {
private final static String VALID_LABEL = "myLabel";
private final static String VALID_URL = "https://www.my.url";
+ public final static RiskScoreClassification MINIMAL_RISK_SCORE_CLASSIFICATION =
+ buildClassification(buildRiskClass(VALID_LABEL, 0, MAX_SCORE, VALID_URL));
+
@ParameterizedTest
@ValueSource(strings = {"", " "})
void failsForBlankLabels(String invalidLabel) {
@@ -134,8 +137,7 @@ void doesNotFailForValidClassification(RiskScoreClassification validClassificati
private static Stream<Arguments> createValidClassifications() {
return Stream.of(
- // valid url
- buildClassification(buildRiskClass(VALID_LABEL, 0, MAX_SCORE, VALID_URL)),
+ MINIMAL_RISK_SCORE_CLASSIFICATION,
// [0:MAX_SCORE/2][MAX_SCORE/2:MAX_SCORE]
buildClassification(
buildRiskClass(VALID_LABEL, 0, MAX_SCORE / 2, VALID_URL),
@@ -148,8 +150,8 @@ private static Stream<Arguments> createValidClassifications() {
).map(Arguments::of);
}
- private static RiskScoreClassificationValidationError buildError(String parameter, Object value, ErrorType reason) {
- return new RiskScoreClassificationValidationError(parameter, value, reason);
+ private static GeneralValidationError buildError(String parameter, Object value, ErrorType reason) {
+ return new GeneralValidationError(parameter, value, reason);
}
private static RiskScoreClassificationValidator buildValidator(RiskScoreClass... riskScoreClasses) {
@@ -164,7 +166,7 @@ private static RiskScoreClass buildRiskClass(String label, int min, int max, Str
return RiskScoreClass.newBuilder().setLabel(label).setMin(min).setMax(max).setUrl(url).build();
}
- private static ValidationResult buildExpectedResult(RiskScoreClassificationValidationError... errors) {
+ public static ValidationResult buildExpectedResult(GeneralValidationError... errors) {
var validationResult = new ValidationResult();
Arrays.stream(errors).forEach(validationResult::add);
return validationResult;
diff --git a/services/distribution/src/test/resources/configtests/app-config_ok.yaml b/services/distribution/src/test/resources/configtests/app-config_ok.yaml
--- a/services/distribution/src/test/resources/configtests/app-config_ok.yaml
+++ b/services/distribution/src/test/resources/configtests/app-config_ok.yaml
@@ -1,3 +1,6 @@
min-risk-score: 100
+attenuationDurationThresholds:
+ lower: 50
+ upper: 70
risk-score-classes: !include risk-score-class_ok.yaml
exposure-config: !include exposure-config_ok.yaml
\ No newline at end of file
| ||||
corona-warn-app__cwa-server-652 | You will be provided with a partial code base and an issue statement explaining a problem to resolve.
<issue>
Validate that no attributes are missing in .yaml
validate that no attributes are missing in .yaml when accordingly re-enable the ``ScoreNegative`` test case in:
https://github.com/corona-warn-app/cwa-server/blob/master/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ExposureConfigurationValidatorTest.java
Note: the validation probably should be done on the loading the values from yaml into a proto object, since validating directly on the resulting proto object is too late as the default value for an unloaded attribute in proto is 0 which we consider as a valid value (or risk score in the allowed range of 0-8)
See PR which disabled the test: https://github.com/corona-warn-app/cwa-server/pull/299
</issue>
<code>
[start of README.md]
1 <!-- markdownlint-disable MD041 -->
2 <h1 align="center">
3 Corona-Warn-App Server
4 </h1>
5
6 <p align="center">
7 <a href="https://github.com/corona-warn-app/cwa-server/commits/" title="Last Commit"><img src="https://img.shields.io/github/last-commit/corona-warn-app/cwa-server?style=flat"></a>
8 <a href="https://github.com/corona-warn-app/cwa-server/issues" title="Open Issues"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat"></a>
9 <a href="https://circleci.com/gh/corona-warn-app/cwa-server" title="Build Status"><img src="https://circleci.com/gh/corona-warn-app/cwa-server.svg?style=shield&circle-token=4ab059989d10709df19eb4b98ab7c121a25e981a"></a>
10 <a href="https://sonarcloud.io/dashboard?id=corona-warn-app_cwa-server" title="Quality Gate"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=alert_status"></a>
11 <a href="https://sonarcloud.io/component_measures?id=corona-warn-app_cwa-server&metric=Coverage&view=list" title="Coverage"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=coverage"></a>
12 <a href="https://github.com/corona-warn-app/cwa-server/blob/master/LICENSE" title="License"><img src="https://img.shields.io/badge/License-Apache%202.0-green.svg?style=flat"></a>
13 </p>
14
15 <p align="center">
16 <a href="#development">Development</a> •
17 <a href="#service-apis">Service APIs</a> •
18 <a href="#documentation">Documentation</a> •
19 <a href="#support-and-feedback">Support</a> •
20 <a href="#how-to-contribute">Contribute</a> •
21 <a href="#contributors">Contributors</a> •
22 <a href="#repositories">Repositories</a> •
23 <a href="#licensing">Licensing</a>
24 </p>
25
26 The goal of this project is to develop the official Corona-Warn-App for Germany based on the exposure notification API from [Apple](https://www.apple.com/covid19/contacttracing/) and [Google](https://www.google.com/covid19/exposurenotifications/). The apps (for both iOS and Android) use Bluetooth technology to exchange anonymous encrypted data with other mobile phones (on which the app is also installed) in the vicinity of an app user's phone. The data is stored locally on each user's device, preventing authorities or other parties from accessing or controlling the data. This repository contains the **implementation of the server for encryption keys** for the Corona-Warn-App.
27
28 In this documentation, Corona-Warn-App services are also referred to as CWA services.
29
30 ## Architecture Overview
31
32 You can find the architecture overview [here](/docs/ARCHITECTURE.md), which will give you
33 a good starting point in how the backend services interact with other services, and what purpose
34 they serve.
35
36 ## Development
37
38 After you've checked out this repository, you can run the application in one of the following ways:
39
40 * As a [Docker](https://www.docker.com/)-based deployment on your local machine. You can run either:
41 * Single components using the respective Dockerfile or
42 * The full backend using the Docker Compose (which is considered the most convenient way)
43 * As a [Maven](https://maven.apache.org)-based build on your local machine.
44 If you want to develop something in a single component, this approach is preferable.
45
46 ### Docker-Based Deployment
47
48 If you want to use Docker-based deployment, you need to install Docker on your local machine. For more information about downloading and installing Docker, see the [official Docker documentation](https://docs.docker.com/get-docker/).
49
50 #### Running the Full CWA Backend Using Docker Compose
51
52 For your convenience, a full setup including the generation of test data has been prepared using [Docker Compose](https://docs.docker.com/compose/reference/overview/). To build the backend services, run ```docker-compose build``` in the repository's root directory. A default configuration file can be found under ```.env``` in the root folder of the repository. The default values for the local Postgres and Zenko Cloudserver should be changed in this file before docker-compose is run.
53
54 Once the services are built, you can start the whole backend using ```docker-compose up```.
55 The distribution service runs once and then finishes. If you want to trigger additional distribution runs, run ```docker-compose run distribution```.
56
57 The docker-compose contains the following services:
58
59 Service | Description | Endpoint and Default Credentials
60 ------------------|-------------|-----------
61 submission | The Corona-Warn-App submission service | `http://localhost:8000` <br> `http://localhost:8006` (for actuator endpoint)
62 distribution | The Corona-Warn-App distribution service | NO ENDPOINT
63 postgres | A [postgres] database installation | `localhost:8001` <br> `postgres:5432` (from containerized pgadmin) <br> Username: postgres <br> Password: postgres
64 pgadmin | A [pgadmin](https://www.pgadmin.org/) installation for the postgres database | `http://localhost:8002` <br> Username: [email protected] <br> Password: password
65 cloudserver | [Zenko CloudServer] is a S3-compliant object store | `http://localhost:8003/` <br> Access key: accessKey1 <br> Secret key: verySecretKey1
66 verification-fake | A very simple fake implementation for the tan verification. | `http://localhost:8004/version/v1/tan/verify` <br> The only valid tan is `edc07f08-a1aa-11ea-bb37-0242ac130002`.
67
68 ##### Known Limitation
69
70 In rare cases the docker-compose runs into a timing issue if the distribution service starts before the bucket of the objectstore was created. This is not a big issue as you can simply run ```docker-compose run distribution``` to trigger additional distribution runs after the objectstore was initialized.
71
72 #### Running Single CWA Services Using Docker
73
74 If you would like to build and run a single CWA service, it's considered easiest to run them in a Docker environment. You can do this using the script provided in the respective CWA service directory. The Docker script first builds the CWA service and then creates an image for the runtime, which means that there are no additional dependencies for you to install.
75
76 To build and run the distribution service, run the following command:
77
78 ```bash
79 ./services/distribution/build_and_run.sh
80 ```
81
82 To build and run the submission service, run the following command:
83
84 ```bash
85 ./services/submission/build_and_run.sh
86 ```
87
88 The submission service is available on [localhost:8080](http://localhost:8080 ).
89
90 ### Maven-Based Build
91
92 If you want to actively develop in one of the CWA services, the Maven-based runtime is most suitable.
93 To prepare your machine to run the CWA project locally, we recommend that you first ensure that you've installed the following:
94
95 * Minimum JDK Version 11: [OpenJDK](https://openjdk.java.net/) / [SapMachine](https://sap.github.io/SapMachine/)
96 * [Maven 3.6](https://maven.apache.org/)
97 * [Postgres]
98 * [Zenko CloudServer]
99
100 If you are already running a local Postgres, you need to create a database `cwa` and run the following setup scripts:
101
102 * Create the different CWA roles first by executing [create-roles.sql](setup/create-roles.sql).
103 * Create local database users for the specific roles by running [create-users.sql](./local-setup/create-users.sql).
104 * It is recommended to also run [enable-test-data-docker-compose.sql](./local-setup/enable-test-data-docker-compose.sql)
105 , which enables the test data generation profile. If you already had CWA running before and an existing `diagnosis-key`
106 table on your database, you need to run [enable-test-data.sql](./local-setup/enable-test-data.sql) instead.
107
108 You can also use `docker-compose` to start Postgres and Zenko. If you do that, you have to
109 set the following environment-variables when running the Spring project:
110
111 For the distribution module:
112
113 ```bash
114 POSTGRESQL_SERVICE_PORT=8001
115 VAULT_FILESIGNING_SECRET=</path/to/your/private_key>
116 SPRING_PROFILES_ACTIVE=signature-dev,disable-ssl-client-postgres
117 ```
118
119 For the submission module:
120
121 ```bash
122 POSTGRESQL_SERVICE_PORT=8001
123 SPRING_PROFILES_ACTIVE=disable-ssl-server,disable-ssl-client-postgres,disable-ssl-client-verification,disable-ssl-client-verification-verify-hostname
124 ```
125
126 #### Configure
127
128 After you made sure that the specified dependencies are running, configure them in the respective configuration files.
129
130 * Configure the Postgres connection in the [submission config](./services/submission/src/main/resources/application.yaml) and in the [distribution config](./services/distribution/src/main/resources/application.yaml)
131 * Configure the S3 compatible object storage in the [distribution config](./services/distribution/src/main/resources/application.yaml)
132 * Configure the private key for the distribution service, the path need to be prefixed with `file:`
133 * `VAULT_FILESIGNING_SECRET` should be the path to the private key, example available in `<repo-root>/docker-compose-test-secrets/private.pem`
134
135 #### Build
136
137 After you've checked out the repository, to build the project, run ```mvn install``` in your base directory.
138
139 #### Run
140
141 Navigate to the service you want to start and run the spring-boot:run target. The configured Postgres and the configured S3 compliant object storage are used as default. When you start the submission service, the endpoint is available on your local port 8080.
142
143 If you want to start the submission service, for example, you start it as follows:
144
145 ```bash
146 cd services/submission/
147 mvn spring-boot:run
148 ```
149
150 #### Debugging
151
152 To enable the `DEBUG` log level, you can run the application using the Spring `dev` profile.
153
154 ```bash
155 mvn spring-boot:run -Dspring.profiles.active=dev
156 ```
157
158 To be able to set breakpoints (e.g. in IntelliJ), it may be necessary to use the ```-Dspring-boot.run.fork=false``` parameter.
159
160 ## Service APIs
161
162 The API that is being exposed by the backend services is documented in an [OpenAPI](https://www.openapis.org/) specification. The specification files are available at the following locations:
163
164 Service | OpenAPI Specification
165 --------------------------|-------------
166 Submission Service | [services/submission/api_v1.json](https://github.com/corona-warn-app/cwa-server/raw/master/services/submission/api_v1.json)
167 Distribution Service | [services/distribution/api_v1.json](https://github.com/corona-warn-app/cwa-server/raw/master/services/distribution/api_v1.json)
168
169 ## Spring Profiles
170
171 ### Distribution
172
173 See [Distribution Service - Spring Profiles](/docs/DISTRIBUTION.md#spring-profiles).
174
175 ### Submission
176
177 See [Submission Service - Spring Profiles](/docs/SUBMISSION.md#spring-profiles).
178
179 ## Documentation
180
181 The full documentation for the Corona-Warn-App can be found in the [cwa-documentation](https://github.com/corona-warn-app/cwa-documentation) repository. The documentation repository contains technical documents, architecture information, and whitepapers related to this implementation.
182
183 ## Support and Feedback
184
185 The following channels are available for discussions, feedback, and support requests:
186
187 | Type | Channel |
188 | ------------------------ | ------------------------------------------------------ |
189 | **General Discussion** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="General Discussion"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/question.svg?style=flat-square"></a> </a> |
190 | **Concept Feedback** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="Open Concept Feedback"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/architecture.svg?style=flat-square"></a> |
191 | **Backend Issue** | <a href="https://github.com/corona-warn-app/cwa-server/issues/new/choose" title="Open Backend Issue"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat-square"></a> |
192 | **Other Requests** | <a href="mailto:[email protected]" title="Email CWA Team"><img src="https://img.shields.io/badge/email-CWA%20team-green?logo=mail.ru&style=flat-square&logoColor=white"></a> |
193
194 ## How to Contribute
195
196 Contribution and feedback are 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.
197
198 ## Contributors
199
200 The German government has asked SAP and Deutsche Telekom to develop the Corona-Warn-App for Germany as open source software. Deutsche Telekom is providing the network and mobile technology and will operate and run the backend for the app in a safe, scalable and stable manner. SAP is responsible for the app development, its framework and the underlying platform. Therefore, development teams of SAP and Deutsche Telekom are contributing to this project. At the same time 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.
201
202 ## Repositories
203
204 The following public repositories are currently available for the Corona-Warn-App:
205
206 | Repository | Description |
207 | ------------------- | --------------------------------------------------------------------- |
208 | [cwa-documentation] | Project overview, general documentation, and white papers |
209 | [cwa-server] | Backend implementation for the Apple/Google exposure notification API|
210 | [cwa-verification-server] | Backend implementation of the verification process|
211
212 [cwa-documentation]: https://github.com/corona-warn-app/cwa-documentation
213 [cwa-server]: https://github.com/corona-warn-app/cwa-server
214 [cwa-verification-server]: https://github.com/corona-warn-app/cwa-verification-server
215 [Postgres]: https://www.postgresql.org/
216 [HSQLDB]: http://hsqldb.org/
217 [Zenko CloudServer]: https://github.com/scality/cloudserver
218
219 ## Licensing
220
221 Copyright (c) 2020 SAP SE or an SAP affiliate company.
222
223 Licensed under the **Apache License, Version 2.0** (the "License"); you may not use this file except in compliance with the License.
224
225 You may obtain a copy of the License at <https://www.apache.org/licenses/LICENSE-2.0>.
226
227 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.
228
[end of README.md]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ValidationError.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.distribution.assembly.appconfig.validation;
22
23 import java.util.Objects;
24
25 /**
26 * {@link ValidationError} instances hold information about errors that occurred during app configuration validation.
27 */
28 public class ValidationError {
29
30 private final String errorSource;
31 private final Object value;
32 private final ErrorType reason;
33
34 /**
35 * Creates a {@link ValidationError} that stores the specified validation error source, erroneous value and a reason
36 * for the error to occur.
37 *
38 * @param errorSource A label that describes the property associated with this validation error.
39 * @param value The value that caused the validation error.
40 * @param reason A validation error specifier.
41 */
42 public ValidationError(String errorSource, Object value, ErrorType reason) {
43 this.errorSource = errorSource;
44 this.value = value;
45 this.reason = reason;
46 }
47
48 @Override
49 public String toString() {
50 return "ValidationError{"
51 + "errorType=" + reason
52 + ", errorSource='" + errorSource + '\''
53 + ", givenValue=" + value
54 + '}';
55 }
56
57 @Override
58 public boolean equals(Object o) {
59 if (this == o) {
60 return true;
61 }
62 if (o == null || getClass() != o.getClass()) {
63 return false;
64 }
65 ValidationError that = (ValidationError) o;
66 return Objects.equals(errorSource, that.errorSource)
67 && Objects.equals(value, that.value)
68 && Objects.equals(reason, that.reason);
69 }
70
71 @Override
72 public int hashCode() {
73 return Objects.hash(errorSource, value, reason);
74 }
75
76 public enum ErrorType {
77 BLANK_LABEL,
78 MIN_GREATER_THAN_MAX,
79 VALUE_OUT_OF_BOUNDS,
80 INVALID_URL,
81 INVALID_PARTITIONING,
82 TOO_MANY_DECIMAL_PLACES,
83 MISSING_ENTRY
84 }
85 }
86
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ValidationError.java]
</code>
Here is an example of a patch file. It consists of changes to the code base. It specifies the file names, the line numbers of each change, and the removed and added lines. A single patch file can contain changes to multiple files.
<patch>
--- a/file.py
+++ b/file.py
@@ -1,27 +1,35 @@
def euclidean(a, b):
- while b:
- a, b = b, a % b
- return a
+ if b == 0:
+ return a
+ return euclidean(b, a % b)
def bresenham(x0, y0, x1, y1):
points = []
dx = abs(x1 - x0)
dy = abs(y1 - y0)
- sx = 1 if x0 < x1 else -1
- sy = 1 if y0 < y1 else -1
- err = dx - dy
+ x, y = x0, y0
+ sx = -1 if x0 > x1 else 1
+ sy = -1 if y0 > y1 else 1
- while True:
- points.append((x0, y0))
- if x0 == x1 and y0 == y1:
- break
- e2 = 2 * err
- if e2 > -dy:
+ if dx > dy:
+ err = dx / 2.0
+ while x != x1:
+ points.append((x, y))
err -= dy
- x0 += sx
- if e2 < dx:
- err += dx
- y0 += sy
+ if err < 0:
+ y += sy
+ err += dx
+ x += sx
+ else:
+ err = dy / 2.0
+ while y != y1:
+ points.append((x, y))
+ err -= dx
+ if err < 0:
+ x += sx
+ err += dy
+ y += sy
+ points.append((x, y))
return points
</patch>
I need you to solve the provded issue by generating a single patch file that I can apply directly to this repository using git apply. Please respond with a single patch file in the format shown above.
Respond below:
| corona-warn-app/cwa-server | ac86a35d9c4a40d55315ce50052ea0e4a64f036e | Validate that no attributes are missing in .yaml
validate that no attributes are missing in .yaml when accordingly re-enable the ``ScoreNegative`` test case in:
https://github.com/corona-warn-app/cwa-server/blob/master/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ExposureConfigurationValidatorTest.java
Note: the validation probably should be done on the loading the values from yaml into a proto object, since validating directly on the resulting proto object is too late as the default value for an unloaded attribute in proto is 0 which we consider as a valid value (or risk score in the allowed range of 0-8)
See PR which disabled the test: https://github.com/corona-warn-app/cwa-server/pull/299
| 2020-07-06T08:16:37 | <patch>
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ValidationError.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ValidationError.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ValidationError.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ValidationError.java
@@ -79,7 +79,6 @@ public enum ErrorType {
VALUE_OUT_OF_BOUNDS,
INVALID_URL,
INVALID_PARTITIONING,
- TOO_MANY_DECIMAL_PLACES,
- MISSING_ENTRY
+ TOO_MANY_DECIMAL_PLACES
}
}
</patch> | diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ExposureConfigurationValidatorTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ExposureConfigurationValidatorTest.java
--- a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ExposureConfigurationValidatorTest.java
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ExposureConfigurationValidatorTest.java
@@ -22,7 +22,6 @@
import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.ExposureConfigurationValidator.CONFIG_PREFIX;
import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.RiskScoreClassificationValidatorTest.buildError;
-import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.ValidationError.ErrorType.MISSING_ENTRY;
import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.ValidationError.ErrorType.TOO_MANY_DECIMAL_PLACES;
import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.ValidationError.ErrorType.VALUE_OUT_OF_BOUNDS;
import static org.assertj.core.api.Assertions.assertThat;
@@ -69,8 +68,6 @@ private static Stream<Arguments> createOkTests() {
private static Stream<Arguments> createFailedTests() {
return Stream.of(
ScoreTooHigh(),
- // TODO cwa-server/#320 Validate that no attributes are missing in .yaml
- // ScoreNegative(),
WeightNegative(),
WeightTooHigh()
).map(Arguments::of);
@@ -103,12 +100,6 @@ public static TestWithExpectedResult WeightTooHigh() {
.with(buildError(CONFIG_PREFIX + "transmission", 101d, VALUE_OUT_OF_BOUNDS));
}
- public static TestWithExpectedResult ScoreNegative() {
- return new TestWithExpectedResult("score_negative.yaml")
- .with(buildError(CONFIG_PREFIX + "transmission.appDefined1", RiskLevel.UNRECOGNIZED, VALUE_OUT_OF_BOUNDS))
- .with(buildError(CONFIG_PREFIX + "transmission.appDefined3", null, MISSING_ENTRY));
- }
-
public static TestWithExpectedResult ScoreTooHigh() {
return new TestWithExpectedResult("score_too_high.yaml")
.with(buildError(CONFIG_PREFIX + "transmission.appDefined1", RiskLevel.UNRECOGNIZED, VALUE_OUT_OF_BOUNDS))
diff --git a/services/distribution/src/test/resources/parameters/score_negative.yaml b/services/distribution/src/test/resources/parameters/score_negative.yaml
deleted file mode 100644
--- a/services/distribution/src/test/resources/parameters/score_negative.yaml
+++ /dev/null
@@ -1,44 +0,0 @@
-transmission_weight: 100
-duration_weight: 50
-attenuation_weight: 80
-
-
-transmission:
- app_defined_1: -2 # not ok, negative
- app_defined_2: 0
- #app_defined_3: 3 # not ok (missing -> unspecified)
- app_defined_4: 5
- app_defined_5: 5
- app_defined_6: 6
- app_defined_7: 7
- app_defined_8: 8
-
-duration:
- eq_0_min: 1
- gt_0_le_5_min: 2
- gt_5_le_10_min: 3
- gt_10_le_15_min: 4
- gt_15_le_20_min: 5
- gt_20_le_25_min: 6
- gt_25_le_30_min: 7
- gt_30_min: 8
-
-days_since_last_exposure:
- ge_14_days: 1
- ge_12_lt_14_days: 2
- ge_10_lt_12_days: 3
- ge_8_lt_10_days: 4
- ge_6_lt_8_days: 5
- ge_4_lt_6_days: 6
- ge_2_lt_4_days: 7
- ge_0_lt_2_days: 8
-
-attenuation:
- gt_73_dbm: 1
- gt_63_le_73_dbm: 2
- gt_51_le_63_dbm: 3
- gt_33_le_51_dbm: 4
- gt_27_le_33_dbm: 5
- gt_15_le_27_dbm: 6
- gt_10_le_15_dbm: 7
- lt_10_dbm: 8
| |||||
corona-warn-app__cwa-server-436 | You will be provided with a partial code base and an issue statement explaining a problem to resolve.
<issue>
Remove "empty" dates/hours from index files
## Current Implementation
All dates/hours between the first submission and now (last full hour) are included in the index files, even if there were no submissions.
## Suggested Enhancement
Only list dates/hours for which there were submissions in the index files. The "empty" date/hour files should, however, still be generated, even if they are not in the index.
## Expected Benefits
Mobile clients need to do fewer requests (they can simply skip empty dates/hours).
</issue>
<code>
[start of README.md]
1 <!-- markdownlint-disable MD041 -->
2 <h1 align="center">
3 Corona-Warn-App Server
4 </h1>
5
6 <p align="center">
7 <a href="https://github.com/corona-warn-app/cwa-server/commits/" title="Last Commit"><img src="https://img.shields.io/github/last-commit/corona-warn-app/cwa-server?style=flat"></a>
8 <a href="https://github.com/corona-warn-app/cwa-server/issues" title="Open Issues"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat"></a>
9 <a href="https://circleci.com/gh/corona-warn-app/cwa-server" title="Build Status"><img src="https://circleci.com/gh/corona-warn-app/cwa-server.svg?style=shield&circle-token=4ab059989d10709df19eb4b98ab7c121a25e981a"></a>
10 <a href="https://sonarcloud.io/dashboard?id=corona-warn-app_cwa-server" title="Quality Gate"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=alert_status"></a>
11 <a href="https://sonarcloud.io/component_measures?id=corona-warn-app_cwa-server&metric=Coverage&view=list" title="Coverage"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=coverage"></a>
12 <a href="https://github.com/corona-warn-app/cwa-server/blob/master/LICENSE" title="License"><img src="https://img.shields.io/badge/License-Apache%202.0-green.svg?style=flat"></a>
13 </p>
14
15 <p align="center">
16 <a href="#development">Development</a> •
17 <a href="#service-apis">Service APIs</a> •
18 <a href="#documentation">Documentation</a> •
19 <a href="#support-and-feedback">Support</a> •
20 <a href="#how-to-contribute">Contribute</a> •
21 <a href="#contributors">Contributors</a> •
22 <a href="#repositories">Repositories</a> •
23 <a href="#licensing">Licensing</a>
24 </p>
25
26 The goal of this project is to develop the official Corona-Warn-App for Germany based on the exposure notification API from [Apple](https://www.apple.com/covid19/contacttracing/) and [Google](https://www.google.com/covid19/exposurenotifications/). The apps (for both iOS and Android) use Bluetooth technology to exchange anonymous encrypted data with other mobile phones (on which the app is also installed) in the vicinity of an app user's phone. The data is stored locally on each user's device, preventing authorities or other parties from accessing or controlling the data. This repository contains the **implementation of the server for encryption keys** for the Corona-Warn-App. This implementation is still a **work in progress**, and the code it contains is currently alpha-quality code.
27
28 In this documentation, Corona-Warn-App services are also referred to as CWA services.
29
30 ## Architecture Overview
31
32 You can find the architecture overview [here](/docs/architecture-overview.md), which will give you
33 a good starting point in how the backend services interact with other services, and what purpose
34 they serve.
35
36 ## Development
37
38 After you've checked out this repository, you can run the application in one of the following ways:
39
40 * As a [Docker](https://www.docker.com/)-based deployment on your local machine. You can run either:
41 * Single components using the respective Dockerfile or
42 * The full backend using the Docker Compose (which is considered the most convenient way)
43 * As a [Maven](https://maven.apache.org)-based build on your local machine.
44 If you want to develop something in a single component, this approach is preferable.
45
46 ### Docker-Based Deployment
47
48 If you want to use Docker-based deployment, you need to install Docker on your local machine. For more information about downloading and installing Docker, see the [official Docker documentation](https://docs.docker.com/get-docker/).
49
50 #### Running the Full CWA Backend Using Docker Compose
51
52 For your convenience, a full setup including the generation of test data has been prepared using [Docker Compose](https://docs.docker.com/compose/reference/overview/). To build the backend services, run ```docker-compose build``` in the repository's root directory. A default configuration file can be found under ```.env```in the root folder of the repository. The default values for the local Postgres and Zenko Cloudserver should be changed in this file before docker-compose is run.
53
54 Once the services are built, you can start the whole backend using ```docker-compose up```.
55 The distribution service runs once and then finishes. If you want to trigger additional distribution runs, run ```docker-compose run distribution```.
56
57 The docker-compose contains the following services:
58
59 Service | Description | Endpoint and Default Credentials
60 ------------------|-------------|-----------
61 submission | The Corona-Warn-App submission service | `http://localhost:8000` <br> `http://localhost:8006` (for actuator endpoint)
62 distribution | The Corona-Warn-App distribution service | NO ENDPOINT
63 postgres | A [postgres] database installation | `postgres:8001` <br> Username: postgres <br> Password: postgres
64 pgadmin | A [pgadmin](https://www.pgadmin.org/) installation for the postgres database | `http://localhost:8002` <br> Username: [email protected] <br> Password: password
65 cloudserver | [Zenko CloudServer] is a S3-compliant object store | `http://localhost:8003/` <br> Access key: accessKey1 <br> Secret key: verySecretKey1
66 verification-fake | A very simple fake implementation for the tan verification. | `http://localhost:8004/version/v1/tan/verify` <br> The only valid tan is "edc07f08-a1aa-11ea-bb37-0242ac130002"
67
68 ##### Known Limitation
69
70 In rare cases the docker-compose runs into a timing issue if the distribution service starts before the bucket of the objectstore was created. This is not a big issue as you can simply run ```docker-compose run distribution``` to trigger additional distribution runs after the objectstore was initialized.
71
72 #### Running Single CWA Services Using Docker
73
74 If you would like to build and run a single CWA service, it's considered easiest to run them in a Docker environment. You can do this using the script provided in the respective CWA service directory. The Docker script first builds the CWA service and then creates an image for the runtime, which means that there are no additional dependencies for you to install.
75
76 To build and run the distribution service, run the following command:
77
78 ```bash
79 ./services/distribution/build_and_run.sh
80 ```
81
82 To build and run the submission service, run the following command:
83
84 ```bash
85 ./services/submission/build_and_run.sh
86 ```
87
88 The submission service is available on [localhost:8080](http://localhost:8080 ).
89
90 ### Maven-Based Build
91
92 If you want to actively develop in one of the CWA services, the Maven-based runtime is most suitable.
93 To prepare your machine to run the CWA project locally, we recommend that you first ensure that you've installed the following:
94
95 * Minimum JDK Version 11: [OpenJDK](https://openjdk.java.net/) / [SapMachine](https://sap.github.io/SapMachine/)
96 * [Maven 3.6](https://maven.apache.org/)
97 * [Postgres]
98 * [Zenko CloudServer]
99
100 #### Configure
101
102 After you made sure that the specified dependencies are running, configure them in the respective configuration files.
103
104 * Configure the Postgres connection in the [submission config](./services/submission/src/main/resources/application.yaml) and in the [distribution config](./services/distribution/src/main/resources/application.yaml)
105 * Configure the S3 compatible object storage in the [distribution config](./services/distribution/src/main/resources/application.yaml)
106 * Configure the private key for the distribution service, the path need to be prefixed with `file:`
107 * `VAULT_FILESIGNING_SECRET` should be the path to the private key, example available in `<repo-root>/docker-compose-test-secrets/private.pem`
108
109 #### Build
110
111 After you've checked out the repository, to build the project, run ```mvn install``` in your base directory.
112
113 #### Run
114
115 Navigate to the service you want to start and run the spring-boot:run target. The configured Postgres and the configured S3 compliant object storage are used as default. When you start the submission service, the endpoint is available on your local port 8080.
116
117 If you want to start the submission service, for example, you start it as follows:
118
119 ```bash
120 cd services/submission/
121 mvn spring-boot:run
122 ```
123
124 #### Debugging
125
126 To enable the `DEBUG` log level, you can run the application using the Spring `dev` profile.
127
128 ```bash
129 mvn spring-boot:run -Dspring-boot.run.profiles=dev
130 ```
131
132 To be able to set breakpoints (e.g. in IntelliJ), it may be necessary to use the ```-Dspring-boot.run.fork=false``` parameter.
133
134 ## Service APIs
135
136 The API that is being exposed by the backend services is documented in an [OpenAPI](https://www.openapis.org/) specification. The specification files are available at the following locations:
137
138 Service | OpenAPI Specification
139 -------------|-------------
140 Submission Service | [services/submission/api_v1.json](https://github.com/corona-warn-app/cwa-server/raw/master/services/submission/api_v1.json)
141 Distribution Service | [services/distribution/api_v1.json](https://github.com/corona-warn-app/cwa-server/raw/master/services/distribution/api_v1.json)
142
143 ## Spring Profiles
144
145 ### Distribution
146
147 Profile | Effect
148 -----------------|-------------
149 `dev` | Turns the log level to `DEBUG`.
150 `cloud` | Removes default values for the `datasource` and `objectstore` configurations.
151 `demo` | Includes incomplete days and hours into the distribution run, thus creating aggregates for the current day and the current hour (and including both in the respective indices). When running multiple distributions in one hour with this profile, the date aggregate for today and the hours aggregate for the current hour will be updated and overwritten. This profile also turns off the expiry policy (Keys must be expired for at least 2 hours before distribution) and the shifting policy (there must be at least 140 keys in a distribution).
152 `testdata` | Causes test data to be inserted into the database before each distribution run. By default, around 1000 random diagnosis keys will be generated per hour. If there are no diagnosis keys in the database yet, random keys will be generated for every hour from the beginning of the retention period (14 days ago at 00:00 UTC) until one hour before the present hour. If there are already keys in the database, the random keys will be generated for every hour from the latest diagnosis key in the database (by submission timestamp) until one hour before the present hour (or none at all, if the latest diagnosis key in the database was submitted one hour ago or later).
153 `signature-dev` | Sets the app package ID in the export packages' signature info to `de.rki.coronawarnapp-dev` so that test certificates (instead of production certificates) will be used for client-side validation.
154 `signature-prod` | Provides production app package IDs for the signature info
155
156 ### Submission
157
158 Profile | Effect
159 -------------|-------------
160 `dev` | Turns the log level to `DEBUG`.
161 `cloud` | Removes default values for the `datasource` configuration.
162
163 ## Documentation
164
165 The full documentation for the Corona-Warn-App can be found in the [cwa-documentation](https://github.com/corona-warn-app/cwa-documentation) repository. The documentation repository contains technical documents, architecture information, and whitepapers related to this implementation.
166
167 ## Support and Feedback
168
169 The following channels are available for discussions, feedback, and support requests:
170
171 | Type | Channel |
172 | ------------------------ | ------------------------------------------------------ |
173 | **General Discussion** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="General Discussion"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/question.svg?style=flat-square"></a> </a> |
174 | **Concept Feedback** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="Open Concept Feedback"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/architecture.svg?style=flat-square"></a> |
175 | **Backend Issue** | <a href="https://github.com/corona-warn-app/cwa-server/issues/new/choose" title="Open Backend Issue"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat-square"></a> |
176 | **Other Requests** | <a href="mailto:[email protected]" title="Email CWA Team"><img src="https://img.shields.io/badge/email-CWA%20team-green?logo=mail.ru&style=flat-square&logoColor=white"></a> |
177
178 ## How to Contribute
179
180 Contribution and feedback are 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.
181
182 ## Contributors
183
184 The German government has asked SAP and Deutsche Telekom to develop the Corona-Warn-App for Germany as open source software. Deutsche Telekom is providing the network and mobile technology and will operate and run the backend for the app in a safe, scalable and stable manner. SAP is responsible for the app development, its framework and the underlying platform. Therefore, development teams of SAP and Deutsche Telekom are contributing to this project. At the same time 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.
185
186 ## Repositories
187
188 The following public repositories are currently available for the Corona-Warn-App:
189
190 | Repository | Description |
191 | ------------------- | --------------------------------------------------------------------- |
192 | [cwa-documentation] | Project overview, general documentation, and white papers |
193 | [cwa-server] | Backend implementation for the Apple/Google exposure notification API|
194 | [cwa-verification-server] | Backend implementation of the verification process|
195
196 [cwa-documentation]: https://github.com/corona-warn-app/cwa-documentation
197 [cwa-server]: https://github.com/corona-warn-app/cwa-server
198 [cwa-verification-server]: https://github.com/corona-warn-app/cwa-verification-server
199 [Postgres]: https://www.postgresql.org/
200 [HSQLDB]: http://hsqldb.org/
201 [Zenko CloudServer]: https://github.com/scality/cloudserver
202
203 ## Licensing
204
205 Copyright (c) 2020 SAP SE or an SAP affiliate company.
206
207 Licensed under the **Apache License, Version 2.0** (the "License"); you may not use this file except in compliance with the License.
208
209 You may obtain a copy of the License at <https://www.apache.org/licenses/LICENSE-2.0>.
210
211 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.
212
[end of README.md]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/component/DiagnosisKeysStructureProvider.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.distribution.assembly.component;
22
23 import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
24 import app.coronawarn.server.common.persistence.service.DiagnosisKeyService;
25 import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.DiagnosisKeyBundler;
26 import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.directory.DiagnosisKeysDirectory;
27 import app.coronawarn.server.services.distribution.assembly.structure.WritableOnDisk;
28 import app.coronawarn.server.services.distribution.assembly.structure.directory.Directory;
29 import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
30 import java.util.Collection;
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
33 import org.springframework.stereotype.Component;
34
35 /**
36 * Retrieves stored diagnosis keys and builds a {@link DiagnosisKeysDirectory} with them.
37 */
38 @Component
39 public class DiagnosisKeysStructureProvider {
40
41 private static final Logger logger = LoggerFactory
42 .getLogger(DiagnosisKeysStructureProvider.class);
43
44 private final DiagnosisKeyBundler diagnosisKeyBundler;
45 private final DiagnosisKeyService diagnosisKeyService;
46 private final CryptoProvider cryptoProvider;
47 private final DistributionServiceConfig distributionServiceConfig;
48
49 /**
50 * Creates a new DiagnosisKeysStructureProvider.
51 */
52 DiagnosisKeysStructureProvider(DiagnosisKeyService diagnosisKeyService, CryptoProvider cryptoProvider,
53 DistributionServiceConfig distributionServiceConfig, DiagnosisKeyBundler diagnosisKeyBundler) {
54 this.diagnosisKeyService = diagnosisKeyService;
55 this.cryptoProvider = cryptoProvider;
56 this.distributionServiceConfig = distributionServiceConfig;
57 this.diagnosisKeyBundler = diagnosisKeyBundler;
58 }
59
60 /**
61 * Get directory for diagnosis keys from database.
62 *
63 * @return the directory
64 */
65 public Directory<WritableOnDisk> getDiagnosisKeys() {
66 logger.debug("Querying diagnosis keys from the database...");
67 Collection<DiagnosisKey> diagnosisKeys = diagnosisKeyService.getDiagnosisKeys();
68 diagnosisKeyBundler.setDiagnosisKeys(diagnosisKeys);
69 return new DiagnosisKeysDirectory(diagnosisKeyBundler, cryptoProvider, distributionServiceConfig);
70 }
71 }
72
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/component/DiagnosisKeysStructureProvider.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/DemoDiagnosisKeyBundler.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.distribution.assembly.diagnosiskeys;
22
23 import static java.util.stream.Collectors.groupingBy;
24
25 import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
26 import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
27 import java.time.LocalDateTime;
28 import java.util.Collection;
29 import java.util.List;
30 import org.springframework.context.annotation.Profile;
31 import org.springframework.stereotype.Component;
32
33 /**
34 * An instance of this class contains a collection of {@link DiagnosisKey DiagnosisKeys}, that will be distributed
35 * in the same hour they have been submitted.
36 */
37 @Profile("demo")
38 @Component
39 public class DemoDiagnosisKeyBundler extends DiagnosisKeyBundler {
40
41 public DemoDiagnosisKeyBundler(DistributionServiceConfig distributionServiceConfig) {
42 super(distributionServiceConfig);
43 }
44
45 /**
46 * Initializes the internal {@code distributableDiagnosisKeys} map, grouping the diagnosis keys by the submission
47 * timestamp, thus ignoring the expiry policy.
48 */
49 @Override
50 protected void createDiagnosisKeyDistributionMap(Collection<DiagnosisKey> diagnosisKeys) {
51 this.distributableDiagnosisKeys.clear();
52 this.distributableDiagnosisKeys.putAll(diagnosisKeys.stream().collect(groupingBy(this::getSubmissionDateTime)));
53 }
54
55 /**
56 * Returns all diagnosis keys that should be distributed in a specific hour, without respecting the shifting and
57 * expiry policies.
58 */
59 @Override
60 public List<DiagnosisKey> getDiagnosisKeysDistributableAt(LocalDateTime hour) {
61 return this.getDiagnosisKeysForHour(hour);
62 }
63 }
64
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/DemoDiagnosisKeyBundler.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/DiagnosisKeyBundler.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.distribution.assembly.diagnosiskeys;
22
23 import static app.coronawarn.server.services.distribution.assembly.diagnosiskeys.util.DateTime.ONE_HOUR_INTERVAL_SECONDS;
24 import static java.time.ZoneOffset.UTC;
25 import static java.util.Collections.emptyList;
26
27 import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
28 import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
29 import java.time.LocalDateTime;
30 import java.util.Collection;
31 import java.util.HashMap;
32 import java.util.List;
33 import java.util.Map;
34 import java.util.Optional;
35 import java.util.stream.Collectors;
36
37 /**
38 * An instance of this class contains a collection of {@link DiagnosisKey DiagnosisKeys}.
39 */
40 public abstract class DiagnosisKeyBundler {
41
42 protected final int minNumberOfKeysPerBundle;
43 protected final long expiryPolicyMinutes;
44
45 // A map containing diagnosis keys, grouped by the LocalDateTime on which they may be distributed
46 protected final Map<LocalDateTime, List<DiagnosisKey>> distributableDiagnosisKeys = new HashMap<>();
47
48 public DiagnosisKeyBundler(DistributionServiceConfig distributionServiceConfig) {
49 this.minNumberOfKeysPerBundle = distributionServiceConfig.getShiftingPolicyThreshold();
50 this.expiryPolicyMinutes = distributionServiceConfig.getExpiryPolicyMinutes();
51 }
52
53 /**
54 * Sets the {@link DiagnosisKey DiagnosisKeys} contained by this {@link DiagnosisKeyBundler} and calls {@link
55 * DiagnosisKeyBundler#createDiagnosisKeyDistributionMap}.
56 */
57 public void setDiagnosisKeys(Collection<DiagnosisKey> diagnosisKeys) {
58 createDiagnosisKeyDistributionMap(diagnosisKeys);
59 }
60
61 /**
62 * Returns all {@link DiagnosisKey DiagnosisKeys} contained by this {@link DiagnosisKeyBundler}.
63 */
64 public List<DiagnosisKey> getAllDiagnosisKeys() {
65 return this.distributableDiagnosisKeys.values().stream()
66 .flatMap(List::stream)
67 .collect(Collectors.toList());
68 }
69
70 /**
71 * Initializes the internal {@code distributableDiagnosisKeys} map, which should contain all diagnosis keys, grouped
72 * by the LocalDateTime on which they may be distributed.
73 */
74 protected abstract void createDiagnosisKeyDistributionMap(Collection<DiagnosisKey> diagnosisKeys);
75
76 /**
77 * Returns all diagnosis keys that should be distributed in a specific hour.
78 */
79 public abstract List<DiagnosisKey> getDiagnosisKeysDistributableAt(LocalDateTime hour);
80
81 /**
82 * Returns the submission timestamp of a {@link DiagnosisKey} as a {@link LocalDateTime}.
83 */
84 protected LocalDateTime getSubmissionDateTime(DiagnosisKey diagnosisKey) {
85 return LocalDateTime.ofEpochSecond(diagnosisKey.getSubmissionTimestamp() * ONE_HOUR_INTERVAL_SECONDS, 0, UTC);
86 }
87
88 /**
89 * Returns all diagnosis keys that should be distributed in a specific hour.
90 */
91 protected List<DiagnosisKey> getDiagnosisKeysForHour(LocalDateTime hour) {
92 return Optional
93 .ofNullable(this.distributableDiagnosisKeys.get(hour))
94 .orElse(emptyList());
95 }
96 }
97
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/DiagnosisKeyBundler.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/ProdDiagnosisKeyBundler.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.distribution.assembly.diagnosiskeys;
22
23 import static app.coronawarn.server.services.distribution.assembly.diagnosiskeys.util.DateTime.TEN_MINUTES_INTERVAL_SECONDS;
24 import static java.time.ZoneOffset.UTC;
25 import static java.util.Collections.emptyList;
26 import static java.util.stream.Collectors.groupingBy;
27
28 import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
29 import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
30 import java.time.Duration;
31 import java.time.LocalDateTime;
32 import java.time.temporal.ChronoUnit;
33 import java.util.Collection;
34 import java.util.List;
35 import java.util.Optional;
36 import java.util.stream.Collectors;
37 import java.util.stream.Stream;
38 import org.springframework.context.annotation.Profile;
39 import org.springframework.stereotype.Component;
40
41 /**
42 * An instance of this class contains a collection of {@link DiagnosisKey DiagnosisKeys}, that will be distributed while
43 * respecting expiry policy (keys must be expired for a configurable amount of time before distribution) and shifting
44 * policy (there must be at least a configurable number of keys in a distribution). The policies are configurable
45 * through the properties {@code expiry-policy-minutes} and {@code shifting-policy-threshold}.
46 */
47 @Profile("!demo")
48 @Component
49 public class ProdDiagnosisKeyBundler extends DiagnosisKeyBundler {
50
51 /**
52 * Creates a new {@link ProdDiagnosisKeyBundler}.
53 */
54 public ProdDiagnosisKeyBundler(DistributionServiceConfig distributionServiceConfig) {
55 super(distributionServiceConfig);
56 }
57
58 /**
59 * Initializes the internal {@code distributableDiagnosisKeys} map, grouping the diagnosis keys by the date on which
60 * they may be distributed, while respecting the expiry policy.
61 */
62 @Override
63 protected void createDiagnosisKeyDistributionMap(Collection<DiagnosisKey> diagnosisKeys) {
64 this.distributableDiagnosisKeys.clear();
65 this.distributableDiagnosisKeys.putAll(diagnosisKeys.stream().collect(groupingBy(this::getDistributionDateTime)));
66 }
67
68 /**
69 * Returns all diagnosis keys that should be distributed in a specific hour, while respecting the shifting and expiry
70 * policies.
71 */
72 @Override
73 public List<DiagnosisKey> getDiagnosisKeysDistributableAt(LocalDateTime hour) {
74 List<DiagnosisKey> keysSinceLastDistribution = getKeysSinceLastDistribution(hour);
75 if (keysSinceLastDistribution.size() >= minNumberOfKeysPerBundle) {
76 return keysSinceLastDistribution;
77 } else {
78 return emptyList();
79 }
80 }
81
82 /**
83 * Returns a all distributable keys between a specific hour and the last distribution (bundle that was above the
84 * shifting threshold) or the earliest distributable key.
85 */
86 private List<DiagnosisKey> getKeysSinceLastDistribution(LocalDateTime hour) {
87 Optional<LocalDateTime> earliestDistributableTimestamp = getEarliestDistributableTimestamp();
88 if (earliestDistributableTimestamp.isEmpty() || hour.isBefore(earliestDistributableTimestamp.get())) {
89 return emptyList();
90 }
91 List<DiagnosisKey> distributableInCurrentHour = getDiagnosisKeysForHour(hour);
92 if (distributableInCurrentHour.size() >= minNumberOfKeysPerBundle) {
93 return distributableInCurrentHour;
94 }
95 LocalDateTime previousHour = hour.minusHours(1);
96 Collection<DiagnosisKey> distributableInPreviousHour = getDiagnosisKeysDistributableAt(previousHour);
97 if (distributableInPreviousHour.size() >= minNumberOfKeysPerBundle) {
98 // Last hour was distributed, so we can not combine the current hour with the last hour
99 return distributableInCurrentHour;
100 } else {
101 // Last hour was not distributed, so we can combine the current hour with the last hour
102 return Stream.concat(distributableInCurrentHour.stream(), getKeysSinceLastDistribution(previousHour).stream())
103 .collect(Collectors.toList());
104 }
105 }
106
107 private Optional<LocalDateTime> getEarliestDistributableTimestamp() {
108 return this.distributableDiagnosisKeys.keySet().stream().min(LocalDateTime::compareTo);
109 }
110
111 /**
112 * Returns the end of the rolling time window that a {@link DiagnosisKey} was active for as a {@link LocalDateTime}.
113 */
114 private LocalDateTime getExpiryDateTime(DiagnosisKey diagnosisKey) {
115 return LocalDateTime
116 .ofEpochSecond(diagnosisKey.getRollingStartIntervalNumber() * TEN_MINUTES_INTERVAL_SECONDS, 0, UTC)
117 .plusMinutes(diagnosisKey.getRollingPeriod() * 10L);
118 }
119
120 /**
121 * Calculates the earliest point in time at which the specified {@link DiagnosisKey} can be distributed. Before keys
122 * are allowed to be distributed, they must be expired for a configured amount of time.
123 *
124 * @return {@link LocalDateTime} at which the specified {@link DiagnosisKey} can be distributed.
125 */
126 private LocalDateTime getDistributionDateTime(DiagnosisKey diagnosisKey) {
127 LocalDateTime submissionDateTime = getSubmissionDateTime(diagnosisKey);
128 LocalDateTime expiryDateTime = getExpiryDateTime(diagnosisKey);
129 long minutesBetweenExpiryAndSubmission = Duration.between(expiryDateTime, submissionDateTime).toMinutes();
130 if (minutesBetweenExpiryAndSubmission <= expiryPolicyMinutes) {
131 // truncatedTo floors the value, so we need to add an hour to the DISTRIBUTION_PADDING to compensate that.
132 return expiryDateTime.plusMinutes(expiryPolicyMinutes + 60).truncatedTo(ChronoUnit.HOURS);
133 } else {
134 return submissionDateTime;
135 }
136 }
137 }
138
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/ProdDiagnosisKeyBundler.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysDateDirectory.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.directory;
22
23 import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
24 import app.coronawarn.server.services.distribution.assembly.component.CryptoProvider;
25 import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.DiagnosisKeyBundler;
26 import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.directory.decorator.HourIndexingDecorator;
27 import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.util.DateTime;
28 import app.coronawarn.server.services.distribution.assembly.structure.WritableOnDisk;
29 import app.coronawarn.server.services.distribution.assembly.structure.directory.Directory;
30 import app.coronawarn.server.services.distribution.assembly.structure.directory.IndexDirectoryOnDisk;
31 import app.coronawarn.server.services.distribution.assembly.structure.util.ImmutableStack;
32 import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
33 import java.time.LocalDate;
34 import java.time.format.DateTimeFormatter;
35
36 public class DiagnosisKeysDateDirectory extends IndexDirectoryOnDisk<LocalDate> {
37
38 private static final DateTimeFormatter ISO8601 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
39
40 private final DiagnosisKeyBundler diagnosisKeyBundler;
41 private final CryptoProvider cryptoProvider;
42 private final DistributionServiceConfig distributionServiceConfig;
43
44 /**
45 * Constructs a {@link DiagnosisKeysDateDirectory} instance associated with the specified {@link DiagnosisKey}
46 * collection. Payload signing is be performed according to the specified {@link CryptoProvider}.
47 *
48 * @param diagnosisKeyBundler A {@link DiagnosisKeyBundler} containing the {@link DiagnosisKey DiagnosisKeys}.
49 * @param cryptoProvider The {@link CryptoProvider} used for payload signing.
50 */
51 public DiagnosisKeysDateDirectory(DiagnosisKeyBundler diagnosisKeyBundler,
52 CryptoProvider cryptoProvider, DistributionServiceConfig distributionServiceConfig) {
53 super(distributionServiceConfig.getApi().getDatePath(),
54 __ -> DateTime.getDates(diagnosisKeyBundler.getAllDiagnosisKeys()), ISO8601::format);
55 this.cryptoProvider = cryptoProvider;
56 this.diagnosisKeyBundler = diagnosisKeyBundler;
57 this.distributionServiceConfig = distributionServiceConfig;
58 }
59
60 @Override
61 public void prepare(ImmutableStack<Object> indices) {
62 this.addWritableToAll(__ -> {
63 DiagnosisKeysHourDirectory hourDirectory =
64 new DiagnosisKeysHourDirectory(diagnosisKeyBundler, cryptoProvider, distributionServiceConfig);
65 return decorateHourDirectory(hourDirectory);
66 });
67 super.prepare(indices);
68 }
69
70 private Directory<WritableOnDisk> decorateHourDirectory(DiagnosisKeysHourDirectory hourDirectory) {
71 return new HourIndexingDecorator(hourDirectory, distributionServiceConfig);
72 }
73 }
74
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysDateDirectory.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysDirectory.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.directory;
22
23 import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
24 import app.coronawarn.server.services.distribution.assembly.component.CryptoProvider;
25 import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.DiagnosisKeyBundler;
26 import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.directory.decorator.CountryIndexingDecorator;
27 import app.coronawarn.server.services.distribution.assembly.structure.WritableOnDisk;
28 import app.coronawarn.server.services.distribution.assembly.structure.directory.Directory;
29 import app.coronawarn.server.services.distribution.assembly.structure.directory.DirectoryOnDisk;
30 import app.coronawarn.server.services.distribution.assembly.structure.directory.IndexDirectory;
31 import app.coronawarn.server.services.distribution.assembly.structure.directory.IndexDirectoryOnDisk;
32 import app.coronawarn.server.services.distribution.assembly.structure.directory.decorator.indexing.IndexingDecoratorOnDisk;
33 import app.coronawarn.server.services.distribution.assembly.structure.util.ImmutableStack;
34 import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
35
36 /**
37 * A {@link Directory} containing the file and directory structure that mirrors the API defined in the OpenAPI
38 * definition {@code /services/distribution/api_v1.json}. Available countries (endpoint {@code
39 * /version/v1/diagnosis-keys/country}) are statically set to only {@code "DE"}. The dates and respective hours
40 * (endpoint {@code /version/v1/diagnosis-keys/country/DE/date}) will be created based on the actual {@link DiagnosisKey
41 * DiagnosisKeys} given to the {@link DiagnosisKeysDirectory#DiagnosisKeysDirectory constructor}.
42 */
43 public class DiagnosisKeysDirectory extends DirectoryOnDisk {
44
45 private final DiagnosisKeyBundler diagnosisKeyBundler;
46 private final CryptoProvider cryptoProvider;
47 private final DistributionServiceConfig distributionServiceConfig;
48
49 /**
50 * Constructs a {@link DiagnosisKeysDirectory} based on the specified {@link DiagnosisKey} collection. Cryptographic
51 * signing is performed using the specified {@link CryptoProvider}.
52 *
53 * @param diagnosisKeyBundler A {@link DiagnosisKeyBundler} containing the {@link DiagnosisKey DiagnosisKeys}.
54 * @param cryptoProvider The {@link CryptoProvider} used for payload signing.
55 */
56 public DiagnosisKeysDirectory(DiagnosisKeyBundler diagnosisKeyBundler, CryptoProvider cryptoProvider,
57 DistributionServiceConfig distributionServiceConfig) {
58 super(distributionServiceConfig.getApi().getDiagnosisKeysPath());
59 this.diagnosisKeyBundler = diagnosisKeyBundler;
60 this.cryptoProvider = cryptoProvider;
61 this.distributionServiceConfig = distributionServiceConfig;
62 }
63
64 @Override
65 public void prepare(ImmutableStack<Object> indices) {
66 this.addWritable(decorateCountryDirectory(
67 new DiagnosisKeysCountryDirectory(diagnosisKeyBundler, cryptoProvider, distributionServiceConfig)));
68 super.prepare(indices);
69 }
70
71 private IndexDirectory<String, WritableOnDisk> decorateCountryDirectory(
72 IndexDirectoryOnDisk<String> countryDirectory) {
73 return new CountryIndexingDecorator<>(
74 new IndexingDecoratorOnDisk<>(countryDirectory, distributionServiceConfig.getOutputFileName()),
75 distributionServiceConfig);
76 }
77 }
78
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysDirectory.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysHourDirectory.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.directory;
22
23 import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
24 import app.coronawarn.server.services.distribution.assembly.component.CryptoProvider;
25 import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.DiagnosisKeyBundler;
26 import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.archive.decorator.singing.DiagnosisKeySigningDecorator;
27 import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.file.TemporaryExposureKeyExportFile;
28 import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.util.DateTime;
29 import app.coronawarn.server.services.distribution.assembly.structure.WritableOnDisk;
30 import app.coronawarn.server.services.distribution.assembly.structure.archive.Archive;
31 import app.coronawarn.server.services.distribution.assembly.structure.archive.ArchiveOnDisk;
32 import app.coronawarn.server.services.distribution.assembly.structure.directory.Directory;
33 import app.coronawarn.server.services.distribution.assembly.structure.directory.IndexDirectoryOnDisk;
34 import app.coronawarn.server.services.distribution.assembly.structure.file.File;
35 import app.coronawarn.server.services.distribution.assembly.structure.util.ImmutableStack;
36 import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
37 import java.time.LocalDate;
38 import java.time.LocalDateTime;
39 import java.time.ZoneOffset;
40 import java.util.List;
41
42 public class DiagnosisKeysHourDirectory extends IndexDirectoryOnDisk<LocalDateTime> {
43
44 private final DiagnosisKeyBundler diagnosisKeyBundler;
45 private final CryptoProvider cryptoProvider;
46 private final DistributionServiceConfig distributionServiceConfig;
47
48 /**
49 * Constructs a {@link DiagnosisKeysHourDirectory} instance for the specified date.
50 *
51 * @param diagnosisKeyBundler A {@link DiagnosisKeyBundler} containing the {@link DiagnosisKey DiagnosisKeys}.
52 * @param cryptoProvider The {@link CryptoProvider} used for cryptographic signing.
53 */
54 public DiagnosisKeysHourDirectory(DiagnosisKeyBundler diagnosisKeyBundler, CryptoProvider cryptoProvider,
55 DistributionServiceConfig distributionServiceConfig) {
56 super(distributionServiceConfig.getApi().getHourPath(), indices -> DateTime.getHours(((LocalDate) indices.peek()),
57 diagnosisKeyBundler.getAllDiagnosisKeys()), LocalDateTime::getHour);
58 this.diagnosisKeyBundler = diagnosisKeyBundler;
59 this.cryptoProvider = cryptoProvider;
60 this.distributionServiceConfig = distributionServiceConfig;
61 }
62
63 @Override
64 public void prepare(ImmutableStack<Object> indices) {
65 this.addWritableToAll(currentIndices -> {
66 LocalDateTime currentHour = (LocalDateTime) currentIndices.peek();
67 // The LocalDateTime currentHour already contains both the date and the hour information, so
68 // we can throw away the LocalDate that's the second item on the stack from the "/date"
69 // IndexDirectory.
70 String region = (String) currentIndices.pop().pop().peek();
71
72 List<DiagnosisKey> diagnosisKeysForCurrentHour =
73 this.diagnosisKeyBundler.getDiagnosisKeysDistributableAt(currentHour);
74
75 long startTimestamp = currentHour.toEpochSecond(ZoneOffset.UTC);
76 long endTimestamp = currentHour.plusHours(1).toEpochSecond(ZoneOffset.UTC);
77 File<WritableOnDisk> temporaryExposureKeyExportFile = TemporaryExposureKeyExportFile.fromDiagnosisKeys(
78 diagnosisKeysForCurrentHour, region, startTimestamp, endTimestamp, distributionServiceConfig);
79
80 Archive<WritableOnDisk> hourArchive = new ArchiveOnDisk(distributionServiceConfig.getOutputFileName());
81 hourArchive.addWritable(temporaryExposureKeyExportFile);
82
83 return decorateDiagnosisKeyArchive(hourArchive);
84 });
85 super.prepare(indices);
86 }
87
88 private Directory<WritableOnDisk> decorateDiagnosisKeyArchive(Archive<WritableOnDisk> archive) {
89 return new DiagnosisKeySigningDecorator(archive, cryptoProvider, distributionServiceConfig);
90 }
91 }
92
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysHourDirectory.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/decorator/CountryIndexingDecorator.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.directory.decorator;
22
23 import app.coronawarn.server.services.distribution.assembly.structure.Writable;
24 import app.coronawarn.server.services.distribution.assembly.structure.WritableOnDisk;
25 import app.coronawarn.server.services.distribution.assembly.structure.archive.Archive;
26 import app.coronawarn.server.services.distribution.assembly.structure.directory.Directory;
27 import app.coronawarn.server.services.distribution.assembly.structure.directory.DirectoryOnDisk;
28 import app.coronawarn.server.services.distribution.assembly.structure.directory.IndexDirectory;
29 import app.coronawarn.server.services.distribution.assembly.structure.directory.decorator.IndexDirectoryDecorator;
30 import app.coronawarn.server.services.distribution.assembly.structure.file.FileOnDisk;
31 import app.coronawarn.server.services.distribution.assembly.structure.util.ImmutableStack;
32 import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
33 import java.nio.charset.StandardCharsets;
34 import java.util.Collection;
35 import java.util.Set;
36 import java.util.stream.Collectors;
37
38 /**
39 * This decorator creates the central index file for a country, e.g. DE.
40 */
41 public class CountryIndexingDecorator<T> extends IndexDirectoryDecorator<T, WritableOnDisk> {
42
43 /**
44 * Separate each entry in the index file with new line.
45 */
46 private static final String NEW_LINE_SEPARATOR = "\r\n";
47
48 /**
49 * the name of this index file.
50 */
51 private final String fileName;
52
53 /**
54 * Creates a new decorator instance for the given directory.
55 *
56 * @param directory The target country directory.
57 * @param distributionServiceConfig The config.
58 */
59 public CountryIndexingDecorator(IndexDirectory<T, WritableOnDisk> directory,
60 DistributionServiceConfig distributionServiceConfig) {
61 super(directory);
62 this.fileName = distributionServiceConfig.getOutputFileName();
63 }
64
65 @Override
66 public void prepare(ImmutableStack<Object> indices) {
67 super.prepare(indices);
68
69 Collection<DirectoryOnDisk> countryDirectories = this.getWritables().stream()
70 .filter(Writable::isDirectory)
71 .map(directory -> (DirectoryOnDisk) directory)
72 .collect(Collectors.toSet());
73
74 countryDirectories.forEach(this::writeIndexFileForCountry);
75 }
76
77 private void writeIndexFileForCountry(Directory<WritableOnDisk> directory) {
78 var dateDirectory = (Directory<WritableOnDisk>) directory.getWritables()
79 .stream()
80 .filter(Writable::isDirectory)
81 .findFirst()
82 .orElseThrow();
83
84 String resourcePaths = CountryIndexingDecorator.getExposureKeyExportPaths(dateDirectory)
85 .stream()
86 .sorted()
87 .collect(Collectors.joining(NEW_LINE_SEPARATOR));
88
89 directory.addWritable(new FileOnDisk(fileName, resourcePaths.getBytes(StandardCharsets.UTF_8)));
90 }
91
92 private static Set<String> getExposureKeyExportPaths(Directory<WritableOnDisk> rootDirectory) {
93 Collection<Directory<WritableOnDisk>> directories = rootDirectory.getWritables()
94 .stream()
95 .filter(Writable::isDirectory)
96 .filter(directory -> !(directory instanceof Archive))
97 .map(directory -> (Directory<WritableOnDisk>) directory)
98 .collect(Collectors.toSet());
99
100 if (directories.isEmpty()) {
101 return Set.of(rootDirectory.getName());
102 } else {
103 return directories.stream()
104 .map(CountryIndexingDecorator::getExposureKeyExportPaths)
105 .flatMap(Set::stream)
106 .map(childName -> rootDirectory.getName() + "/" + childName)
107 .collect(Collectors.toSet());
108 }
109 }
110 }
111
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/decorator/CountryIndexingDecorator.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/util/DateTime.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.distribution.assembly.diagnosiskeys.util;
22
23 import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
24 import java.time.LocalDate;
25 import java.time.LocalDateTime;
26 import java.time.ZoneOffset;
27 import java.util.Collection;
28 import java.util.Set;
29 import java.util.concurrent.TimeUnit;
30 import java.util.stream.Collectors;
31
32 /**
33 * Methods for conversions of time/date data.
34 */
35 public class DateTime {
36
37 /**
38 * The submission timestamp is counted in 1 hour intervals since epoch.
39 */
40 public static final long ONE_HOUR_INTERVAL_SECONDS = TimeUnit.HOURS.toSeconds(1);
41
42 /**
43 * The rolling start interval number is counted in 10 minute intervals since epoch.
44 */
45 public static final long TEN_MINUTES_INTERVAL_SECONDS = TimeUnit.MINUTES.toSeconds(10);
46
47 private DateTime() {
48 }
49
50 /**
51 * Returns a set of all {@link LocalDate dates} that are associated with the submission timestamps of the specified
52 * {@link DiagnosisKey diagnosis keys}.
53 */
54 public static Set<LocalDate> getDates(Collection<DiagnosisKey> diagnosisKeys) {
55 return diagnosisKeys.stream()
56 .map(DiagnosisKey::getSubmissionTimestamp)
57 .map(timestamp -> LocalDate.ofEpochDay(timestamp / 24))
58 .collect(Collectors.toSet());
59 }
60
61 /**
62 * Returns a set of all {@link LocalDateTime hours} that are associated with the submission timestamps of the
63 * specified {@link DiagnosisKey diagnosis keys} and the specified {@link LocalDate date}.
64 */
65 public static Set<LocalDateTime> getHours(LocalDate currentDate, Collection<DiagnosisKey> diagnosisKeys) {
66 return diagnosisKeys.stream()
67 .map(DiagnosisKey::getSubmissionTimestamp)
68 .map(DateTime::getLocalDateTimeFromHoursSinceEpoch)
69 .filter(currentDateTime -> currentDateTime.toLocalDate().equals(currentDate))
70 .collect(Collectors.toSet());
71 }
72
73 /**
74 * Creates a {@link LocalDateTime} based on the specified epoch timestamp.
75 */
76 public static LocalDateTime getLocalDateTimeFromHoursSinceEpoch(long timestamp) {
77 return LocalDateTime.ofEpochSecond(TimeUnit.HOURS.toSeconds(timestamp), 0, ZoneOffset.UTC);
78 }
79 }
80
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/util/DateTime.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/TestDataGeneration.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.distribution.runner;
22
23 import static app.coronawarn.server.services.distribution.assembly.diagnosiskeys.util.DateTime.ONE_HOUR_INTERVAL_SECONDS;
24 import static app.coronawarn.server.services.distribution.assembly.diagnosiskeys.util.DateTime.TEN_MINUTES_INTERVAL_SECONDS;
25
26 import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
27 import app.coronawarn.server.common.persistence.service.DiagnosisKeyService;
28 import app.coronawarn.server.common.protocols.internal.RiskLevel;
29 import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
30 import app.coronawarn.server.services.distribution.config.DistributionServiceConfig.TestData;
31 import java.time.LocalDate;
32 import java.time.LocalDateTime;
33 import java.time.ZoneOffset;
34 import java.util.List;
35 import java.util.concurrent.TimeUnit;
36 import java.util.stream.Collectors;
37 import java.util.stream.IntStream;
38 import java.util.stream.LongStream;
39 import org.apache.commons.math3.distribution.PoissonDistribution;
40 import org.apache.commons.math3.random.JDKRandomGenerator;
41 import org.apache.commons.math3.random.RandomGenerator;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44 import org.springframework.boot.ApplicationArguments;
45 import org.springframework.boot.ApplicationRunner;
46 import org.springframework.context.annotation.Profile;
47 import org.springframework.core.annotation.Order;
48 import org.springframework.stereotype.Component;
49
50 /**
51 * Generates random diagnosis keys for the time frame between the last diagnosis key in the database and now (last full
52 * hour) and writes them to the database. If there are no diagnosis keys in the database yet, then random diagnosis keys
53 * for the time frame between the last full hour and the beginning of the retention period (14 days ago) will be
54 * generated. The average number of exposure keys to be generated per hour is configurable in the application properties
55 * (profile = {@code testdata}).
56 */
57 @Component
58 @Order(-1)
59 @Profile("testdata")
60 public class TestDataGeneration implements ApplicationRunner {
61
62 private final Logger logger = LoggerFactory.getLogger(TestDataGeneration.class);
63
64 private final Integer retentionDays;
65
66 private final TestData config;
67
68 private final DiagnosisKeyService diagnosisKeyService;
69
70 private final RandomGenerator random = new JDKRandomGenerator();
71
72 private static final int POISSON_MAX_ITERATIONS = 10_000_000;
73 private static final double POISSON_EPSILON = 1e-12;
74
75 /**
76 * Creates a new TestDataGeneration runner.
77 */
78 TestDataGeneration(DiagnosisKeyService diagnosisKeyService,
79 DistributionServiceConfig distributionServiceConfig) {
80 this.diagnosisKeyService = diagnosisKeyService;
81 this.retentionDays = distributionServiceConfig.getRetentionDays();
82 this.config = distributionServiceConfig.getTestData();
83 }
84
85 /**
86 * See {@link TestDataGeneration} class documentation.
87 */
88 @Override
89 public void run(ApplicationArguments args) {
90 writeTestData();
91 }
92
93 /**
94 * See {@link TestDataGeneration} class documentation.
95 */
96 private void writeTestData() {
97 logger.debug("Querying diagnosis keys from the database...");
98 List<DiagnosisKey> existingDiagnosisKeys = diagnosisKeyService.getDiagnosisKeys();
99
100 // Timestamps in hours since epoch. Test data generation starts one hour after the latest diagnosis key in the
101 // database and ends one hour before the current one.
102 long startTimestamp = getGeneratorStartTimestamp(existingDiagnosisKeys) + 1; // Inclusive
103 long endTimestamp = getGeneratorEndTimestamp(); // Exclusive
104
105 // Add the startTimestamp to the seed. Otherwise we would generate the same data every hour.
106 random.setSeed(this.config.getSeed() + startTimestamp);
107 PoissonDistribution poisson =
108 new PoissonDistribution(random, this.config.getExposuresPerHour(), POISSON_EPSILON, POISSON_MAX_ITERATIONS);
109
110 if (startTimestamp == endTimestamp) {
111 logger.debug("Skipping test data generation, latest diagnosis keys are still up-to-date.");
112 return;
113 }
114 logger.debug("Generating diagnosis keys between {} and {}...", startTimestamp, endTimestamp);
115 List<DiagnosisKey> newDiagnosisKeys = LongStream.range(startTimestamp, endTimestamp)
116 .mapToObj(submissionTimestamp -> IntStream.range(0, poisson.sample())
117 .mapToObj(__ -> generateDiagnosisKey(submissionTimestamp))
118 .collect(Collectors.toList()))
119 .flatMap(List::stream)
120 .collect(Collectors.toList());
121
122 logger.debug("Writing {} new diagnosis keys to the database...", newDiagnosisKeys.size());
123 diagnosisKeyService.saveDiagnosisKeys(newDiagnosisKeys);
124
125 logger.debug("Test data generation finished successfully.");
126 }
127
128 /**
129 * Returns the submission timestamp (in 1 hour intervals since epoch) of the last diagnosis key in the database (or
130 * the result of {@link TestDataGeneration#getRetentionStartTimestamp} if there are no diagnosis keys in the database
131 * yet.
132 */
133 private long getGeneratorStartTimestamp(List<DiagnosisKey> diagnosisKeys) {
134 if (diagnosisKeys.isEmpty()) {
135 return getRetentionStartTimestamp();
136 } else {
137 DiagnosisKey latestDiagnosisKey = diagnosisKeys.get(diagnosisKeys.size() - 1);
138 return latestDiagnosisKey.getSubmissionTimestamp();
139 }
140 }
141
142 /**
143 * Returns the timestamp (in 1 hour intervals since epoch) of the last full hour. Example: If called at 15:38 UTC,
144 * this function would return the timestamp for today 14:00 UTC.
145 */
146 private long getGeneratorEndTimestamp() {
147 return (LocalDateTime.now().toEpochSecond(ZoneOffset.UTC) / ONE_HOUR_INTERVAL_SECONDS) - 1;
148 }
149
150 /**
151 * Returns the timestamp (in 1 hour intervals since epoch) at which the retention period starts. Example: If the
152 * retention period in the application properties is set to 14 days, then this function would return the timestamp for
153 * 14 days ago (from now) at 00:00 UTC.
154 */
155 private long getRetentionStartTimestamp() {
156 return LocalDate.now().minusDays(retentionDays).atStartOfDay()
157 .toEpochSecond(ZoneOffset.UTC) / ONE_HOUR_INTERVAL_SECONDS;
158 }
159
160 /**
161 * Returns a random diagnosis key with a specific submission timestamp.
162 */
163 private DiagnosisKey generateDiagnosisKey(long submissionTimestamp) {
164 return DiagnosisKey.builder()
165 .withKeyData(generateDiagnosisKeyBytes())
166 .withRollingStartIntervalNumber(generateRollingStartIntervalNumber(submissionTimestamp))
167 .withTransmissionRiskLevel(generateTransmissionRiskLevel())
168 .withSubmissionTimestamp(submissionTimestamp)
169 .build();
170 }
171
172 /**
173 * Returns 16 random bytes.
174 */
175 private byte[] generateDiagnosisKeyBytes() {
176 byte[] exposureKey = new byte[16];
177 random.nextBytes(exposureKey);
178 return exposureKey;
179 }
180
181 /**
182 * Returns a random rolling start interval number (timestamp since when a key was active, represented by a 10 minute
183 * interval counter) between a specific submission timestamp and the beginning of the retention period.
184 */
185 private int generateRollingStartIntervalNumber(long submissionTimestamp) {
186 long maxRollingStartIntervalNumber =
187 submissionTimestamp * ONE_HOUR_INTERVAL_SECONDS / TEN_MINUTES_INTERVAL_SECONDS;
188 long minRollingStartIntervalNumber =
189 maxRollingStartIntervalNumber
190 - TimeUnit.DAYS.toSeconds(retentionDays) / TEN_MINUTES_INTERVAL_SECONDS;
191 return Math.toIntExact(getRandomBetween(minRollingStartIntervalNumber, maxRollingStartIntervalNumber));
192 }
193
194 /**
195 * Returns a random number between {@link RiskLevel#RISK_LEVEL_LOWEST_VALUE} and {@link
196 * RiskLevel#RISK_LEVEL_HIGHEST_VALUE}.
197 */
198 private int generateTransmissionRiskLevel() {
199 return Math.toIntExact(
200 getRandomBetween(RiskLevel.RISK_LEVEL_LOWEST_VALUE, RiskLevel.RISK_LEVEL_HIGHEST_VALUE));
201 }
202
203 /**
204 * Returns a random number between {@code minIncluding} and {@code maxIncluding}.
205 */
206 private long getRandomBetween(long minIncluding, long maxIncluding) {
207 return minIncluding + (long) (random.nextDouble() * (maxIncluding - minIncluding));
208 }
209 }
210
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/TestDataGeneration.java]
</code>
Here is an example of a patch file. It consists of changes to the code base. It specifies the file names, the line numbers of each change, and the removed and added lines. A single patch file can contain changes to multiple files.
<patch>
--- a/file.py
+++ b/file.py
@@ -1,27 +1,35 @@
def euclidean(a, b):
- while b:
- a, b = b, a % b
- return a
+ if b == 0:
+ return a
+ return euclidean(b, a % b)
def bresenham(x0, y0, x1, y1):
points = []
dx = abs(x1 - x0)
dy = abs(y1 - y0)
- sx = 1 if x0 < x1 else -1
- sy = 1 if y0 < y1 else -1
- err = dx - dy
+ x, y = x0, y0
+ sx = -1 if x0 > x1 else 1
+ sy = -1 if y0 > y1 else 1
- while True:
- points.append((x0, y0))
- if x0 == x1 and y0 == y1:
- break
- e2 = 2 * err
- if e2 > -dy:
+ if dx > dy:
+ err = dx / 2.0
+ while x != x1:
+ points.append((x, y))
err -= dy
- x0 += sx
- if e2 < dx:
- err += dx
- y0 += sy
+ if err < 0:
+ y += sy
+ err += dx
+ x += sx
+ else:
+ err = dy / 2.0
+ while y != y1:
+ points.append((x, y))
+ err -= dx
+ if err < 0:
+ x += sx
+ err += dy
+ y += sy
+ points.append((x, y))
return points
</patch>
I need you to solve the provded issue by generating a single patch file that I can apply directly to this repository using git apply. Please respond with a single patch file in the format shown above.
Respond below:
| corona-warn-app/cwa-server | ebb112166c8b6bf21ba18232db773be9a03b93e8 | Remove "empty" dates/hours from index files
## Current Implementation
All dates/hours between the first submission and now (last full hour) are included in the index files, even if there were no submissions.
## Suggested Enhancement
Only list dates/hours for which there were submissions in the index files. The "empty" date/hour files should, however, still be generated, even if they are not in the index.
## Expected Benefits
Mobile clients need to do fewer requests (they can simply skip empty dates/hours).
| Why should the empty files still be generated?
Basically to attest that there were really no submissions in that time window (and that the distribution run didn't just fail). Since we are not (yet) signing index files, I guess the best we can do is to just create and sign the empty exports. | 2020-06-03T16:28:18 | <patch>
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/component/DiagnosisKeysStructureProvider.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/component/DiagnosisKeysStructureProvider.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/component/DiagnosisKeysStructureProvider.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/component/DiagnosisKeysStructureProvider.java
@@ -27,6 +27,8 @@
import app.coronawarn.server.services.distribution.assembly.structure.WritableOnDisk;
import app.coronawarn.server.services.distribution.assembly.structure.directory.Directory;
import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
+import java.time.LocalDateTime;
+import java.time.temporal.ChronoUnit;
import java.util.Collection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -65,7 +67,7 @@ public class DiagnosisKeysStructureProvider {
public Directory<WritableOnDisk> getDiagnosisKeys() {
logger.debug("Querying diagnosis keys from the database...");
Collection<DiagnosisKey> diagnosisKeys = diagnosisKeyService.getDiagnosisKeys();
- diagnosisKeyBundler.setDiagnosisKeys(diagnosisKeys);
+ diagnosisKeyBundler.setDiagnosisKeys(diagnosisKeys, LocalDateTime.now().truncatedTo(ChronoUnit.HOURS));
return new DiagnosisKeysDirectory(diagnosisKeyBundler, cryptoProvider, distributionServiceConfig);
}
}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/DemoDiagnosisKeyBundler.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/DemoDiagnosisKeyBundler.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/DemoDiagnosisKeyBundler.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/DemoDiagnosisKeyBundler.java
@@ -24,15 +24,13 @@
import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
-import java.time.LocalDateTime;
import java.util.Collection;
-import java.util.List;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
/**
- * An instance of this class contains a collection of {@link DiagnosisKey DiagnosisKeys}, that will be distributed
- * in the same hour they have been submitted.
+ * An instance of this class contains a collection of {@link DiagnosisKey DiagnosisKeys}, that will be distributed in
+ * the same hour they have been submitted.
*/
@Profile("demo")
@Component
@@ -44,20 +42,11 @@ public DemoDiagnosisKeyBundler(DistributionServiceConfig distributionServiceConf
/**
* Initializes the internal {@code distributableDiagnosisKeys} map, grouping the diagnosis keys by the submission
- * timestamp, thus ignoring the expiry policy.
+ * timestamp, thus ignoring the expiry and shifting policies.
*/
@Override
protected void createDiagnosisKeyDistributionMap(Collection<DiagnosisKey> diagnosisKeys) {
this.distributableDiagnosisKeys.clear();
this.distributableDiagnosisKeys.putAll(diagnosisKeys.stream().collect(groupingBy(this::getSubmissionDateTime)));
}
-
- /**
- * Returns all diagnosis keys that should be distributed in a specific hour, without respecting the shifting and
- * expiry policies.
- */
- @Override
- public List<DiagnosisKey> getDiagnosisKeysDistributableAt(LocalDateTime hour) {
- return this.getDiagnosisKeysForHour(hour);
- }
}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/DiagnosisKeyBundler.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/DiagnosisKeyBundler.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/DiagnosisKeyBundler.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/DiagnosisKeyBundler.java
@@ -20,18 +20,20 @@
package app.coronawarn.server.services.distribution.assembly.diagnosiskeys;
-import static app.coronawarn.server.services.distribution.assembly.diagnosiskeys.util.DateTime.ONE_HOUR_INTERVAL_SECONDS;
import static java.time.ZoneOffset.UTC;
import static java.util.Collections.emptyList;
import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
+import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
/**
@@ -39,9 +41,23 @@
*/
public abstract class DiagnosisKeyBundler {
+ /**
+ * The submission timestamp is counted in 1 hour intervals since epoch.
+ */
+ public static final long ONE_HOUR_INTERVAL_SECONDS = TimeUnit.HOURS.toSeconds(1);
+
+ /**
+ * The rolling start interval number is counted in 10 minute intervals since epoch.
+ */
+ public static final long TEN_MINUTES_INTERVAL_SECONDS = TimeUnit.MINUTES.toSeconds(10);
+
protected final int minNumberOfKeysPerBundle;
protected final long expiryPolicyMinutes;
+ // The hour at which the distribution runs. This field is needed to prevent the run from distributing any keys that
+ // have already been submitted but may only be distributed in the future (e.g. because they are not expired yet).
+ protected LocalDateTime distributionTime;
+
// A map containing diagnosis keys, grouped by the LocalDateTime on which they may be distributed
protected final Map<LocalDateTime, List<DiagnosisKey>> distributableDiagnosisKeys = new HashMap<>();
@@ -51,11 +67,22 @@ public DiagnosisKeyBundler(DistributionServiceConfig distributionServiceConfig)
}
/**
- * Sets the {@link DiagnosisKey DiagnosisKeys} contained by this {@link DiagnosisKeyBundler} and calls {@link
- * DiagnosisKeyBundler#createDiagnosisKeyDistributionMap}.
+ * Creates a {@link LocalDateTime} based on the specified epoch timestamp.
+ */
+ public static LocalDateTime getLocalDateTimeFromHoursSinceEpoch(long timestamp) {
+ return LocalDateTime.ofEpochSecond(TimeUnit.HOURS.toSeconds(timestamp), 0, UTC);
+ }
+
+ /**
+ * Sets the {@link DiagnosisKey DiagnosisKeys} contained by this {@link DiagnosisKeyBundler} and the time at which the
+ * distribution runs and calls {@link DiagnosisKeyBundler#createDiagnosisKeyDistributionMap}.
+ *
+ * @param diagnosisKeys The {@link DiagnosisKey DiagnosisKeys} contained by this {@link DiagnosisKeyBundler}.
+ * @param distributionTime The {@link LocalDateTime} at which the distribution runs.
*/
- public void setDiagnosisKeys(Collection<DiagnosisKey> diagnosisKeys) {
- createDiagnosisKeyDistributionMap(diagnosisKeys);
+ public void setDiagnosisKeys(Collection<DiagnosisKey> diagnosisKeys, LocalDateTime distributionTime) {
+ this.distributionTime = distributionTime;
+ this.createDiagnosisKeyDistributionMap(diagnosisKeys);
}
/**
@@ -74,9 +101,23 @@ public List<DiagnosisKey> getAllDiagnosisKeys() {
protected abstract void createDiagnosisKeyDistributionMap(Collection<DiagnosisKey> diagnosisKeys);
/**
- * Returns all diagnosis keys that should be distributed in a specific hour.
+ * Returns a set of all {@link LocalDate dates} on which {@link DiagnosisKey diagnosis keys} shall be distributed.
*/
- public abstract List<DiagnosisKey> getDiagnosisKeysDistributableAt(LocalDateTime hour);
+ public Set<LocalDate> getDatesWithDistributableDiagnosisKeys() {
+ return this.distributableDiagnosisKeys.keySet().stream()
+ .map(LocalDateTime::toLocalDate)
+ .collect(Collectors.toSet());
+ }
+
+ /**
+ * Returns a set of all {@link LocalDateTime hours} of a specified {@link LocalDate date} during which {@link
+ * DiagnosisKey diagnosis keys} shall be distributed.
+ */
+ public Set<LocalDateTime> getHoursWithDistributableDiagnosisKeys(LocalDate currentDate) {
+ return this.distributableDiagnosisKeys.keySet().stream()
+ .filter(dateTime -> dateTime.toLocalDate().equals(currentDate))
+ .collect(Collectors.toSet());
+ }
/**
* Returns the submission timestamp of a {@link DiagnosisKey} as a {@link LocalDateTime}.
@@ -85,10 +126,21 @@ protected LocalDateTime getSubmissionDateTime(DiagnosisKey diagnosisKey) {
return LocalDateTime.ofEpochSecond(diagnosisKey.getSubmissionTimestamp() * ONE_HOUR_INTERVAL_SECONDS, 0, UTC);
}
+ /**
+ * Returns all diagnosis keys that should be distributed on a specific date.
+ */
+ public List<DiagnosisKey> getDiagnosisKeysForDate(LocalDate date) {
+ return this.distributableDiagnosisKeys.keySet().stream()
+ .filter(dateTime -> dateTime.toLocalDate().equals(date))
+ .map(this::getDiagnosisKeysForHour)
+ .flatMap(List::stream)
+ .collect(Collectors.toList());
+ }
+
/**
* Returns all diagnosis keys that should be distributed in a specific hour.
*/
- protected List<DiagnosisKey> getDiagnosisKeysForHour(LocalDateTime hour) {
+ public List<DiagnosisKey> getDiagnosisKeysForHour(LocalDateTime hour) {
return Optional
.ofNullable(this.distributableDiagnosisKeys.get(hour))
.orElse(emptyList());
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/ProdDiagnosisKeyBundler.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/ProdDiagnosisKeyBundler.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/ProdDiagnosisKeyBundler.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/ProdDiagnosisKeyBundler.java
@@ -20,7 +20,6 @@
package app.coronawarn.server.services.distribution.assembly.diagnosiskeys;
-import static app.coronawarn.server.services.distribution.assembly.diagnosiskeys.util.DateTime.TEN_MINUTES_INTERVAL_SECONDS;
import static java.time.ZoneOffset.UTC;
import static java.util.Collections.emptyList;
import static java.util.stream.Collectors.groupingBy;
@@ -30,11 +29,13 @@
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
+import java.util.ArrayList;
import java.util.Collection;
+import java.util.HashMap;
import java.util.List;
+import java.util.Map;
import java.util.Optional;
-import java.util.stream.Collectors;
-import java.util.stream.Stream;
+import java.util.stream.LongStream;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
@@ -57,55 +58,38 @@ public ProdDiagnosisKeyBundler(DistributionServiceConfig distributionServiceConf
/**
* Initializes the internal {@code distributableDiagnosisKeys} map, grouping the diagnosis keys by the date on which
- * they may be distributed, while respecting the expiry policy.
+ * they may be distributed, while respecting the expiry and shifting policies.
*/
@Override
protected void createDiagnosisKeyDistributionMap(Collection<DiagnosisKey> diagnosisKeys) {
this.distributableDiagnosisKeys.clear();
- this.distributableDiagnosisKeys.putAll(diagnosisKeys.stream().collect(groupingBy(this::getDistributionDateTime)));
- }
-
- /**
- * Returns all diagnosis keys that should be distributed in a specific hour, while respecting the shifting and expiry
- * policies.
- */
- @Override
- public List<DiagnosisKey> getDiagnosisKeysDistributableAt(LocalDateTime hour) {
- List<DiagnosisKey> keysSinceLastDistribution = getKeysSinceLastDistribution(hour);
- if (keysSinceLastDistribution.size() >= minNumberOfKeysPerBundle) {
- return keysSinceLastDistribution;
- } else {
- return emptyList();
+ if (diagnosisKeys.isEmpty()) {
+ return;
}
- }
+ Map<LocalDateTime, List<DiagnosisKey>> distributableDiagnosisKeysGroupedByExpiryPolicy = new HashMap<>(
+ diagnosisKeys.stream().collect(groupingBy(this::getDistributionDateTimeByExpiryPolicy)));
+ LocalDateTime earliestDistributableTimestamp =
+ getEarliestDistributableTimestamp(distributableDiagnosisKeysGroupedByExpiryPolicy).orElseThrow();
+ LocalDateTime latestDistributableTimestamp = this.distributionTime;
- /**
- * Returns a all distributable keys between a specific hour and the last distribution (bundle that was above the
- * shifting threshold) or the earliest distributable key.
- */
- private List<DiagnosisKey> getKeysSinceLastDistribution(LocalDateTime hour) {
- Optional<LocalDateTime> earliestDistributableTimestamp = getEarliestDistributableTimestamp();
- if (earliestDistributableTimestamp.isEmpty() || hour.isBefore(earliestDistributableTimestamp.get())) {
- return emptyList();
- }
- List<DiagnosisKey> distributableInCurrentHour = getDiagnosisKeysForHour(hour);
- if (distributableInCurrentHour.size() >= minNumberOfKeysPerBundle) {
- return distributableInCurrentHour;
- }
- LocalDateTime previousHour = hour.minusHours(1);
- Collection<DiagnosisKey> distributableInPreviousHour = getDiagnosisKeysDistributableAt(previousHour);
- if (distributableInPreviousHour.size() >= minNumberOfKeysPerBundle) {
- // Last hour was distributed, so we can not combine the current hour with the last hour
- return distributableInCurrentHour;
- } else {
- // Last hour was not distributed, so we can combine the current hour with the last hour
- return Stream.concat(distributableInCurrentHour.stream(), getKeysSinceLastDistribution(previousHour).stream())
- .collect(Collectors.toList());
- }
+ List<DiagnosisKey> diagnosisKeyAccumulator = new ArrayList<>();
+ LongStream.range(0, earliestDistributableTimestamp.until(latestDistributableTimestamp, ChronoUnit.HOURS))
+ .forEach(hourCounter -> {
+ LocalDateTime currentHour = earliestDistributableTimestamp.plusHours(hourCounter);
+ Collection<DiagnosisKey> currentHourDiagnosisKeys = Optional
+ .ofNullable(distributableDiagnosisKeysGroupedByExpiryPolicy.get(currentHour))
+ .orElse(emptyList());
+ diagnosisKeyAccumulator.addAll(currentHourDiagnosisKeys);
+ if (diagnosisKeyAccumulator.size() >= minNumberOfKeysPerBundle) {
+ this.distributableDiagnosisKeys.put(currentHour, new ArrayList<>(diagnosisKeyAccumulator));
+ diagnosisKeyAccumulator.clear();
+ }
+ });
}
- private Optional<LocalDateTime> getEarliestDistributableTimestamp() {
- return this.distributableDiagnosisKeys.keySet().stream().min(LocalDateTime::compareTo);
+ private static Optional<LocalDateTime> getEarliestDistributableTimestamp(
+ Map<LocalDateTime, List<DiagnosisKey>> distributableDiagnosisKeys) {
+ return distributableDiagnosisKeys.keySet().stream().min(LocalDateTime::compareTo);
}
/**
@@ -118,12 +102,13 @@ private LocalDateTime getExpiryDateTime(DiagnosisKey diagnosisKey) {
}
/**
- * Calculates the earliest point in time at which the specified {@link DiagnosisKey} can be distributed. Before keys
- * are allowed to be distributed, they must be expired for a configured amount of time.
+ * Calculates the earliest point in time at which the specified {@link DiagnosisKey} can be distributed, while
+ * respecting the expiry policy and the submission timestamp. Before keys are allowed to be distributed, they must be
+ * expired for a configured amount of time.
*
* @return {@link LocalDateTime} at which the specified {@link DiagnosisKey} can be distributed.
*/
- private LocalDateTime getDistributionDateTime(DiagnosisKey diagnosisKey) {
+ private LocalDateTime getDistributionDateTimeByExpiryPolicy(DiagnosisKey diagnosisKey) {
LocalDateTime submissionDateTime = getSubmissionDateTime(diagnosisKey);
LocalDateTime expiryDateTime = getExpiryDateTime(diagnosisKey);
long minutesBetweenExpiryAndSubmission = Duration.between(expiryDateTime, submissionDateTime).toMinutes();
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysDateDirectory.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysDateDirectory.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysDateDirectory.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysDateDirectory.java
@@ -24,7 +24,6 @@
import app.coronawarn.server.services.distribution.assembly.component.CryptoProvider;
import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.DiagnosisKeyBundler;
import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.directory.decorator.HourIndexingDecorator;
-import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.util.DateTime;
import app.coronawarn.server.services.distribution.assembly.structure.WritableOnDisk;
import app.coronawarn.server.services.distribution.assembly.structure.directory.Directory;
import app.coronawarn.server.services.distribution.assembly.structure.directory.IndexDirectoryOnDisk;
@@ -46,12 +45,12 @@ public class DiagnosisKeysDateDirectory extends IndexDirectoryOnDisk<LocalDate>
* collection. Payload signing is be performed according to the specified {@link CryptoProvider}.
*
* @param diagnosisKeyBundler A {@link DiagnosisKeyBundler} containing the {@link DiagnosisKey DiagnosisKeys}.
- * @param cryptoProvider The {@link CryptoProvider} used for payload signing.
+ * @param cryptoProvider The {@link CryptoProvider} used for payload signing.
*/
public DiagnosisKeysDateDirectory(DiagnosisKeyBundler diagnosisKeyBundler,
CryptoProvider cryptoProvider, DistributionServiceConfig distributionServiceConfig) {
super(distributionServiceConfig.getApi().getDatePath(),
- __ -> DateTime.getDates(diagnosisKeyBundler.getAllDiagnosisKeys()), ISO8601::format);
+ __ -> diagnosisKeyBundler.getDatesWithDistributableDiagnosisKeys(), ISO8601::format);
this.cryptoProvider = cryptoProvider;
this.diagnosisKeyBundler = diagnosisKeyBundler;
this.distributionServiceConfig = distributionServiceConfig;
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysDirectory.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysDirectory.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysDirectory.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysDirectory.java
@@ -23,7 +23,6 @@
import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
import app.coronawarn.server.services.distribution.assembly.component.CryptoProvider;
import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.DiagnosisKeyBundler;
-import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.directory.decorator.CountryIndexingDecorator;
import app.coronawarn.server.services.distribution.assembly.structure.WritableOnDisk;
import app.coronawarn.server.services.distribution.assembly.structure.directory.Directory;
import app.coronawarn.server.services.distribution.assembly.structure.directory.DirectoryOnDisk;
@@ -70,8 +69,6 @@ public void prepare(ImmutableStack<Object> indices) {
private IndexDirectory<String, WritableOnDisk> decorateCountryDirectory(
IndexDirectoryOnDisk<String> countryDirectory) {
- return new CountryIndexingDecorator<>(
- new IndexingDecoratorOnDisk<>(countryDirectory, distributionServiceConfig.getOutputFileName()),
- distributionServiceConfig);
+ return new IndexingDecoratorOnDisk<>(countryDirectory, distributionServiceConfig.getOutputFileName());
}
}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysHourDirectory.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysHourDirectory.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysHourDirectory.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysHourDirectory.java
@@ -25,7 +25,6 @@
import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.DiagnosisKeyBundler;
import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.archive.decorator.singing.DiagnosisKeySigningDecorator;
import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.file.TemporaryExposureKeyExportFile;
-import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.util.DateTime;
import app.coronawarn.server.services.distribution.assembly.structure.WritableOnDisk;
import app.coronawarn.server.services.distribution.assembly.structure.archive.Archive;
import app.coronawarn.server.services.distribution.assembly.structure.archive.ArchiveOnDisk;
@@ -53,8 +52,9 @@ public class DiagnosisKeysHourDirectory extends IndexDirectoryOnDisk<LocalDateTi
*/
public DiagnosisKeysHourDirectory(DiagnosisKeyBundler diagnosisKeyBundler, CryptoProvider cryptoProvider,
DistributionServiceConfig distributionServiceConfig) {
- super(distributionServiceConfig.getApi().getHourPath(), indices -> DateTime.getHours(((LocalDate) indices.peek()),
- diagnosisKeyBundler.getAllDiagnosisKeys()), LocalDateTime::getHour);
+ super(distributionServiceConfig.getApi().getHourPath(),
+ indices -> diagnosisKeyBundler.getHoursWithDistributableDiagnosisKeys(((LocalDate) indices.peek())),
+ LocalDateTime::getHour);
this.diagnosisKeyBundler = diagnosisKeyBundler;
this.cryptoProvider = cryptoProvider;
this.distributionServiceConfig = distributionServiceConfig;
@@ -70,7 +70,7 @@ public void prepare(ImmutableStack<Object> indices) {
String region = (String) currentIndices.pop().pop().peek();
List<DiagnosisKey> diagnosisKeysForCurrentHour =
- this.diagnosisKeyBundler.getDiagnosisKeysDistributableAt(currentHour);
+ this.diagnosisKeyBundler.getDiagnosisKeysForHour(currentHour);
long startTimestamp = currentHour.toEpochSecond(ZoneOffset.UTC);
long endTimestamp = currentHour.plusHours(1).toEpochSecond(ZoneOffset.UTC);
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/decorator/CountryIndexingDecorator.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/decorator/CountryIndexingDecorator.java
deleted file mode 100644
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/decorator/CountryIndexingDecorator.java
+++ /dev/null
@@ -1,110 +0,0 @@
-/*-
- * ---license-start
- * Corona-Warn-App
- * ---
- * Copyright (C) 2020 SAP SE and all other contributors
- * ---
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://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 for the specific language governing permissions and
- * limitations under the License.
- * ---license-end
- */
-
-package app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.directory.decorator;
-
-import app.coronawarn.server.services.distribution.assembly.structure.Writable;
-import app.coronawarn.server.services.distribution.assembly.structure.WritableOnDisk;
-import app.coronawarn.server.services.distribution.assembly.structure.archive.Archive;
-import app.coronawarn.server.services.distribution.assembly.structure.directory.Directory;
-import app.coronawarn.server.services.distribution.assembly.structure.directory.DirectoryOnDisk;
-import app.coronawarn.server.services.distribution.assembly.structure.directory.IndexDirectory;
-import app.coronawarn.server.services.distribution.assembly.structure.directory.decorator.IndexDirectoryDecorator;
-import app.coronawarn.server.services.distribution.assembly.structure.file.FileOnDisk;
-import app.coronawarn.server.services.distribution.assembly.structure.util.ImmutableStack;
-import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
-import java.nio.charset.StandardCharsets;
-import java.util.Collection;
-import java.util.Set;
-import java.util.stream.Collectors;
-
-/**
- * This decorator creates the central index file for a country, e.g. DE.
- */
-public class CountryIndexingDecorator<T> extends IndexDirectoryDecorator<T, WritableOnDisk> {
-
- /**
- * Separate each entry in the index file with new line.
- */
- private static final String NEW_LINE_SEPARATOR = "\r\n";
-
- /**
- * the name of this index file.
- */
- private final String fileName;
-
- /**
- * Creates a new decorator instance for the given directory.
- *
- * @param directory The target country directory.
- * @param distributionServiceConfig The config.
- */
- public CountryIndexingDecorator(IndexDirectory<T, WritableOnDisk> directory,
- DistributionServiceConfig distributionServiceConfig) {
- super(directory);
- this.fileName = distributionServiceConfig.getOutputFileName();
- }
-
- @Override
- public void prepare(ImmutableStack<Object> indices) {
- super.prepare(indices);
-
- Collection<DirectoryOnDisk> countryDirectories = this.getWritables().stream()
- .filter(Writable::isDirectory)
- .map(directory -> (DirectoryOnDisk) directory)
- .collect(Collectors.toSet());
-
- countryDirectories.forEach(this::writeIndexFileForCountry);
- }
-
- private void writeIndexFileForCountry(Directory<WritableOnDisk> directory) {
- var dateDirectory = (Directory<WritableOnDisk>) directory.getWritables()
- .stream()
- .filter(Writable::isDirectory)
- .findFirst()
- .orElseThrow();
-
- String resourcePaths = CountryIndexingDecorator.getExposureKeyExportPaths(dateDirectory)
- .stream()
- .sorted()
- .collect(Collectors.joining(NEW_LINE_SEPARATOR));
-
- directory.addWritable(new FileOnDisk(fileName, resourcePaths.getBytes(StandardCharsets.UTF_8)));
- }
-
- private static Set<String> getExposureKeyExportPaths(Directory<WritableOnDisk> rootDirectory) {
- Collection<Directory<WritableOnDisk>> directories = rootDirectory.getWritables()
- .stream()
- .filter(Writable::isDirectory)
- .filter(directory -> !(directory instanceof Archive))
- .map(directory -> (Directory<WritableOnDisk>) directory)
- .collect(Collectors.toSet());
-
- if (directories.isEmpty()) {
- return Set.of(rootDirectory.getName());
- } else {
- return directories.stream()
- .map(CountryIndexingDecorator::getExposureKeyExportPaths)
- .flatMap(Set::stream)
- .map(childName -> rootDirectory.getName() + "/" + childName)
- .collect(Collectors.toSet());
- }
- }
-}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/util/DateTime.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/util/DateTime.java
deleted file mode 100644
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/util/DateTime.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/*-
- * ---license-start
- * Corona-Warn-App
- * ---
- * Copyright (C) 2020 SAP SE and all other contributors
- * ---
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://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 for the specific language governing permissions and
- * limitations under the License.
- * ---license-end
- */
-
-package app.coronawarn.server.services.distribution.assembly.diagnosiskeys.util;
-
-import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
-import java.time.LocalDate;
-import java.time.LocalDateTime;
-import java.time.ZoneOffset;
-import java.util.Collection;
-import java.util.Set;
-import java.util.concurrent.TimeUnit;
-import java.util.stream.Collectors;
-
-/**
- * Methods for conversions of time/date data.
- */
-public class DateTime {
-
- /**
- * The submission timestamp is counted in 1 hour intervals since epoch.
- */
- public static final long ONE_HOUR_INTERVAL_SECONDS = TimeUnit.HOURS.toSeconds(1);
-
- /**
- * The rolling start interval number is counted in 10 minute intervals since epoch.
- */
- public static final long TEN_MINUTES_INTERVAL_SECONDS = TimeUnit.MINUTES.toSeconds(10);
-
- private DateTime() {
- }
-
- /**
- * Returns a set of all {@link LocalDate dates} that are associated with the submission timestamps of the specified
- * {@link DiagnosisKey diagnosis keys}.
- */
- public static Set<LocalDate> getDates(Collection<DiagnosisKey> diagnosisKeys) {
- return diagnosisKeys.stream()
- .map(DiagnosisKey::getSubmissionTimestamp)
- .map(timestamp -> LocalDate.ofEpochDay(timestamp / 24))
- .collect(Collectors.toSet());
- }
-
- /**
- * Returns a set of all {@link LocalDateTime hours} that are associated with the submission timestamps of the
- * specified {@link DiagnosisKey diagnosis keys} and the specified {@link LocalDate date}.
- */
- public static Set<LocalDateTime> getHours(LocalDate currentDate, Collection<DiagnosisKey> diagnosisKeys) {
- return diagnosisKeys.stream()
- .map(DiagnosisKey::getSubmissionTimestamp)
- .map(DateTime::getLocalDateTimeFromHoursSinceEpoch)
- .filter(currentDateTime -> currentDateTime.toLocalDate().equals(currentDate))
- .collect(Collectors.toSet());
- }
-
- /**
- * Creates a {@link LocalDateTime} based on the specified epoch timestamp.
- */
- public static LocalDateTime getLocalDateTimeFromHoursSinceEpoch(long timestamp) {
- return LocalDateTime.ofEpochSecond(TimeUnit.HOURS.toSeconds(timestamp), 0, ZoneOffset.UTC);
- }
-}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/TestDataGeneration.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/TestDataGeneration.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/TestDataGeneration.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/TestDataGeneration.java
@@ -20,8 +20,8 @@
package app.coronawarn.server.services.distribution.runner;
-import static app.coronawarn.server.services.distribution.assembly.diagnosiskeys.util.DateTime.ONE_HOUR_INTERVAL_SECONDS;
-import static app.coronawarn.server.services.distribution.assembly.diagnosiskeys.util.DateTime.TEN_MINUTES_INTERVAL_SECONDS;
+import static app.coronawarn.server.services.distribution.assembly.diagnosiskeys.DiagnosisKeyBundler.ONE_HOUR_INTERVAL_SECONDS;
+import static app.coronawarn.server.services.distribution.assembly.diagnosiskeys.DiagnosisKeyBundler.TEN_MINUTES_INTERVAL_SECONDS;
import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
import app.coronawarn.server.common.persistence.service.DiagnosisKeyService;
</patch> | diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/ProdDiagnosisKeyBundlerExpiryPolicyTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/ProdDiagnosisKeyBundlerExpiryPolicyTest.java
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/ProdDiagnosisKeyBundlerExpiryPolicyTest.java
@@ -0,0 +1,88 @@
+/*-
+ * ---license-start
+ * Corona-Warn-App
+ * ---
+ * Copyright (C) 2020 SAP SE and all other contributors
+ * ---
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://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 for the specific language governing permissions and
+ * limitations under the License.
+ * ---license-end
+ */
+
+package app.coronawarn.server.services.distribution.assembly.diagnosiskeys;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
+import app.coronawarn.server.services.distribution.common.Helpers;
+import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
+import java.time.LocalDateTime;
+import java.util.List;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.context.properties.EnableConfigurationProperties;
+import org.springframework.boot.test.context.ConfigFileApplicationContextInitializer;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit.jupiter.SpringExtension;
+
+@EnableConfigurationProperties(value = DistributionServiceConfig.class)
+@ExtendWith(SpringExtension.class)
+@ContextConfiguration(classes = {DistributionServiceConfig.class, ProdDiagnosisKeyBundler.class},
+ initializers = ConfigFileApplicationContextInitializer.class)
+class ProdDiagnosisKeyBundlerExpiryPolicyTest {
+
+ @Autowired
+ DistributionServiceConfig distributionServiceConfig;
+
+ @Autowired
+ DiagnosisKeyBundler bundler;
+
+ @ParameterizedTest
+ @ValueSource(longs = {0L, 24L, 24L + 2L})
+ void testLastPeriodOfHourAndSubmissionLessThanDistributionDateTime(long submissionTimestamp) {
+ List<DiagnosisKey> diagnosisKeys = Helpers.buildDiagnosisKeys(5, submissionTimestamp, 10);
+ bundler.setDiagnosisKeys(diagnosisKeys, LocalDateTime.of(1970, 1, 5, 0, 0));
+ assertThat(bundler.getDiagnosisKeysForHour(LocalDateTime.of(1970, 1, 2, 3, 0, 0))).hasSize(10);
+ }
+
+ @Test
+ void testLastPeriodOfHourAndSubmissionEqualsDistributionDateTime() {
+ List<DiagnosisKey> diagnosisKeys = Helpers.buildDiagnosisKeys(5, 24L + 3L, 10);
+ bundler.setDiagnosisKeys(diagnosisKeys, LocalDateTime.of(1970, 1, 5, 0, 0));
+ assertThat(bundler.getDiagnosisKeysForHour(LocalDateTime.of(1970, 1, 2, 3, 0, 0))).hasSize(10);
+ }
+
+ @ParameterizedTest
+ @ValueSource(longs = {0L, 24L, 24L + 2L, 24L + 3L})
+ void testFirstPeriodOfHourAndSubmissionLessThanDistributionDateTime(long submissionTimestamp) {
+ List<DiagnosisKey> diagnosisKeys = Helpers.buildDiagnosisKeys(6, submissionTimestamp, 10);
+ bundler.setDiagnosisKeys(diagnosisKeys, LocalDateTime.of(1970, 1, 5, 0, 0));
+ assertThat(bundler.getDiagnosisKeysForHour(LocalDateTime.of(1970, 1, 2, 4, 0, 0))).hasSize(10);
+ }
+
+ @Test
+ void testFirstPeriodOfHourAndSubmissionEqualsDistributionDateTime() {
+ List<DiagnosisKey> diagnosisKeys = Helpers.buildDiagnosisKeys(6, 24L + 4L, 10);
+ bundler.setDiagnosisKeys(diagnosisKeys, LocalDateTime.of(1970, 1, 5, 0, 0));
+ assertThat(bundler.getDiagnosisKeysForHour(LocalDateTime.of(1970, 1, 2, 4, 0, 0))).hasSize(10);
+ }
+
+ @Test
+ void testLastPeriodOfHourAndSubmissionGreaterDistributionDateTime() {
+ List<DiagnosisKey> diagnosisKeys = Helpers.buildDiagnosisKeys(5, 24L + 4L, 10);
+ bundler.setDiagnosisKeys(diagnosisKeys, LocalDateTime.of(1970, 1, 5, 0, 0));
+ assertThat(bundler.getDiagnosisKeysForHour(LocalDateTime.of(1970, 1, 2, 4, 0, 0))).hasSize(10);
+ }
+}
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/ProdDiagnosisKeyBundlerKeyRetrievalTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/ProdDiagnosisKeyBundlerKeyRetrievalTest.java
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/ProdDiagnosisKeyBundlerKeyRetrievalTest.java
@@ -0,0 +1,185 @@
+/*-
+ * ---license-start
+ * Corona-Warn-App
+ * ---
+ * Copyright (C) 2020 SAP SE and all other contributors
+ * ---
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://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 for the specific language governing permissions and
+ * limitations under the License.
+ * ---license-end
+ */
+
+package app.coronawarn.server.services.distribution.assembly.diagnosiskeys;
+
+import static app.coronawarn.server.services.distribution.common.Helpers.buildDiagnosisKeys;
+import static java.util.Collections.emptySet;
+import static org.assertj.core.api.Assertions.assertThat;
+
+import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
+import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
+import java.time.LocalDate;
+import java.time.LocalDateTime;
+import java.util.Collection;
+import java.util.List;
+import java.util.Set;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Nested;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.context.properties.EnableConfigurationProperties;
+import org.springframework.boot.test.context.ConfigFileApplicationContextInitializer;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit.jupiter.SpringExtension;
+
+@EnableConfigurationProperties(value = DistributionServiceConfig.class)
+@ExtendWith(SpringExtension.class)
+@ContextConfiguration(classes = {DistributionServiceConfig.class, ProdDiagnosisKeyBundler.class},
+ initializers = ConfigFileApplicationContextInitializer.class)
+class ProdDiagnosisKeyBundlerKeyRetrievalTest {
+
+ @Autowired
+ DistributionServiceConfig distributionServiceConfig;
+
+ @Autowired
+ DiagnosisKeyBundler bundler;
+
+ @Test
+ void testGetsAllDiagnosisKeys() {
+ List<DiagnosisKey> diagnosisKeys = Stream
+ .of(buildDiagnosisKeys(6, 50L, 5), buildDiagnosisKeys(6, 51L, 5), buildDiagnosisKeys(6, 52L, 5))
+ .flatMap(List::stream)
+ .collect(Collectors.toList());
+ bundler.setDiagnosisKeys(diagnosisKeys, LocalDateTime.of(1970, 1, 5, 0, 0));
+ assertThat(bundler.getAllDiagnosisKeys()).hasSize(15);
+ }
+
+ @Test
+ void testGetDatesForEmptyList() {
+ bundler.setDiagnosisKeys(emptySet(), LocalDateTime.of(1970, 1, 5, 0, 0));
+ assertThat(bundler.getDatesWithDistributableDiagnosisKeys()).isEmpty();
+ }
+
+ @Test
+ void testGetsDatesWithDistributableDiagnosisKeys() {
+ List<DiagnosisKey> diagnosisKeys = Stream
+ .of(buildDiagnosisKeys(6, 26L, 5), buildDiagnosisKeys(6, 50L, 1), buildDiagnosisKeys(6, 74L, 5))
+ .flatMap(List::stream)
+ .collect(Collectors.toList());
+ bundler.setDiagnosisKeys(diagnosisKeys, LocalDateTime.of(1970, 1, 5, 0, 0));
+ assertThat(bundler.getDatesWithDistributableDiagnosisKeys()).containsAll(List.of(
+ LocalDate.of(1970, 1, 2),
+ LocalDate.of(1970, 1, 4)
+ ));
+ }
+
+ @ParameterizedTest
+ @MethodSource("createDiagnosisKeysForEpochDay0")
+ void testGetDatesForEpochDay0(Collection<DiagnosisKey> diagnosisKeys) {
+ bundler.setDiagnosisKeys(diagnosisKeys, LocalDateTime.of(1970, 1, 5, 0, 0));
+ var expDates = Set.of(LocalDate.ofEpochDay(2L));
+ var actDates = bundler.getDatesWithDistributableDiagnosisKeys();
+ assertThat(actDates).isEqualTo(expDates);
+ }
+
+ private static Stream<Arguments> createDiagnosisKeysForEpochDay0() {
+ return Stream.of(
+ buildDiagnosisKeys(6, LocalDateTime.of(1970, 1, 3, 0, 0), 5),
+ buildDiagnosisKeys(6, LocalDateTime.of(1970, 1, 3, 1, 0), 5),
+ buildDiagnosisKeys(6, LocalDateTime.of(1970, 1, 3, 23, 59, 59), 5)
+ ).map(Arguments::of);
+ }
+
+ @Test
+ void testGetDatesFor2Days() {
+ List<DiagnosisKey> diagnosisKeys = Stream
+ .of(buildDiagnosisKeys(6, LocalDateTime.of(1970, 1, 3, 1, 0), 5),
+ buildDiagnosisKeys(6, LocalDateTime.of(1970, 1, 4, 1, 0), 5))
+ .flatMap(List::stream)
+ .collect(Collectors.toList());
+ bundler.setDiagnosisKeys(diagnosisKeys, LocalDateTime.of(1970, 1, 5, 0, 0));
+ var expDates = Set.of(LocalDate.ofEpochDay(2L), LocalDate.ofEpochDay(3L));
+ assertThat(bundler.getDatesWithDistributableDiagnosisKeys()).isEqualTo(expDates);
+ }
+
+ @Test
+ void testGetHoursForEmptyList() {
+ bundler.setDiagnosisKeys(emptySet(), LocalDateTime.of(1970, 1, 5, 0, 0));
+ assertThat(bundler.getHoursWithDistributableDiagnosisKeys(LocalDate.of(1970, 1, 3))).isEmpty();
+ }
+
+ @Test
+ void testGetsHoursWithDistributableDiagnosisKeys() {
+ List<DiagnosisKey> diagnosisKeys = Stream
+ .of(buildDiagnosisKeys(6, LocalDateTime.of(1970, 1, 2, 4, 0), 5),
+ buildDiagnosisKeys(6, LocalDateTime.of(1970, 1, 2, 5, 0), 1),
+ buildDiagnosisKeys(6, LocalDateTime.of(1970, 1, 2, 6, 0), 5))
+ .flatMap(List::stream)
+ .collect(Collectors.toList());
+ bundler.setDiagnosisKeys(diagnosisKeys, LocalDateTime.of(1970, 1, 5, 0, 0));
+ assertThat(bundler.getHoursWithDistributableDiagnosisKeys(LocalDate.of(1970, 1, 2))).containsAll(List.of(
+ LocalDateTime.of(1970, 1, 2, 4, 0, 0),
+ LocalDateTime.of(1970, 1, 2, 6, 0, 0)
+ ));
+ }
+
+ @Test
+ void testGetsDiagnosisKeysForDate() {
+ List<DiagnosisKey> diagnosisKeys = Stream
+ .of(buildDiagnosisKeys(6, LocalDateTime.of(1970, 1, 2, 2, 0), 5),
+ buildDiagnosisKeys(6, LocalDateTime.of(1970, 1, 3, 2, 0), 1),
+ buildDiagnosisKeys(6, LocalDateTime.of(1970, 1, 4, 2, 0), 5))
+ .flatMap(List::stream)
+ .collect(Collectors.toList());
+ bundler.setDiagnosisKeys(diagnosisKeys, LocalDateTime.of(1970, 1, 5, 20, 0));
+ assertThat(bundler.getDiagnosisKeysForDate(LocalDate.of(1970, 1, 1))).hasSize(0);
+ assertThat(bundler.getDiagnosisKeysForDate(LocalDate.of(1970, 1, 2))).hasSize(5);
+ assertThat(bundler.getDiagnosisKeysForDate(LocalDate.of(1970, 1, 3))).hasSize(0);
+ assertThat(bundler.getDiagnosisKeysForDate(LocalDate.of(1970, 1, 4))).hasSize(6);
+ assertThat(bundler.getDiagnosisKeysForDate(LocalDate.of(1970, 1, 5))).hasSize(0);
+ }
+
+ @Test
+ void testEmptyListWhenGettingDiagnosisKeysForDateBeforeEarliestDiagnosisKey() {
+ List<DiagnosisKey> diagnosisKeys = buildDiagnosisKeys(6, LocalDateTime.of(1970, 1, 2, 4, 0), 5);
+ bundler.setDiagnosisKeys(diagnosisKeys, LocalDateTime.of(1970, 1, 5, 0, 0));
+ assertThat(bundler.getDiagnosisKeysForDate(LocalDate.of(1970, 1, 1))).hasSize(0);
+ }
+
+ @Test
+ void testGetsDiagnosisKeysForHour() {
+ List<DiagnosisKey> diagnosisKeys = Stream
+ .of(buildDiagnosisKeys(6, LocalDateTime.of(1970, 1, 2, 4, 0), 5),
+ buildDiagnosisKeys(6, LocalDateTime.of(1970, 1, 2, 5, 0), 1),
+ buildDiagnosisKeys(6, LocalDateTime.of(1970, 1, 2, 6, 0), 5))
+ .flatMap(List::stream)
+ .collect(Collectors.toList());
+ bundler.setDiagnosisKeys(diagnosisKeys, LocalDateTime.of(1970, 1, 5, 0, 0));
+ assertThat(bundler.getDiagnosisKeysForHour(LocalDateTime.of(1970, 1, 2, 3, 0))).hasSize(0);
+ assertThat(bundler.getDiagnosisKeysForHour(LocalDateTime.of(1970, 1, 2, 4, 0))).hasSize(5);
+ assertThat(bundler.getDiagnosisKeysForHour(LocalDateTime.of(1970, 1, 2, 5, 0))).hasSize(0);
+ assertThat(bundler.getDiagnosisKeysForHour(LocalDateTime.of(1970, 1, 2, 6, 0))).hasSize(6);
+ assertThat(bundler.getDiagnosisKeysForHour(LocalDateTime.of(1970, 1, 2, 7, 0))).hasSize(0);
+ }
+
+ @Test
+ void testEmptyListWhenGettingDiagnosisKeysForHourBeforeEarliestDiagnosisKey() {
+ List<DiagnosisKey> diagnosisKeys = buildDiagnosisKeys(6, LocalDateTime.of(1970, 1, 2, 4, 0), 5);
+ bundler.setDiagnosisKeys(diagnosisKeys, LocalDateTime.of(1970, 1, 5, 0, 0));
+ assertThat(bundler.getDiagnosisKeysForHour(LocalDateTime.of(1970, 1, 1, 0, 0, 0))).hasSize(0);
+ }
+}
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/ProdDiagnosisKeyBundlerShiftingPolicyTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/ProdDiagnosisKeyBundlerShiftingPolicyTest.java
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/ProdDiagnosisKeyBundlerShiftingPolicyTest.java
@@ -0,0 +1,121 @@
+/*-
+ * ---license-start
+ * Corona-Warn-App
+ * ---
+ * Copyright (C) 2020 SAP SE and all other contributors
+ * ---
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://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 for the specific language governing permissions and
+ * limitations under the License.
+ * ---license-end
+ */
+
+package app.coronawarn.server.services.distribution.assembly.diagnosiskeys;
+
+import static app.coronawarn.server.services.distribution.common.Helpers.buildDiagnosisKeys;
+import static org.assertj.core.api.Assertions.assertThat;
+
+import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
+import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
+import java.time.LocalDateTime;
+import java.util.List;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+import java.util.stream.Stream;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Nested;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.context.properties.EnableConfigurationProperties;
+import org.springframework.boot.test.context.ConfigFileApplicationContextInitializer;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit.jupiter.SpringExtension;
+
+@EnableConfigurationProperties(value = DistributionServiceConfig.class)
+@ExtendWith(SpringExtension.class)
+@ContextConfiguration(classes = {DistributionServiceConfig.class, ProdDiagnosisKeyBundler.class},
+ initializers = ConfigFileApplicationContextInitializer.class)
+class ProdDiagnosisKeyBundlerShiftingPolicyTest {
+
+ @Autowired
+ DistributionServiceConfig distributionServiceConfig;
+
+ @Autowired
+ DiagnosisKeyBundler bundler;
+
+ @Test
+ void testDoesNotShiftIfPackageSizeGreaterThanThreshold() {
+ List<DiagnosisKey> diagnosisKeys = buildDiagnosisKeys(6, 50L, 6);
+ bundler.setDiagnosisKeys(diagnosisKeys, LocalDateTime.of(1970, 1, 5, 0, 0));
+ assertThat(bundler.getDiagnosisKeysForHour(LocalDateTime.of(1970, 1, 3, 2, 0, 0))).hasSize(6);
+ }
+
+ @Test
+ void testDoesNotShiftIfPackageSizeEqualsThreshold() {
+ List<DiagnosisKey> diagnosisKeys = buildDiagnosisKeys(6, 50L, 5);
+ bundler.setDiagnosisKeys(diagnosisKeys, LocalDateTime.of(1970, 1, 5, 0, 0));
+ assertThat(bundler.getDiagnosisKeysForHour(LocalDateTime.of(1970, 1, 3, 2, 0, 0))).hasSize(5);
+ }
+
+ @Test
+ void testShiftsIfPackageSizeLessThanThreshold() {
+ List<DiagnosisKey> diagnosisKeys = Stream
+ .concat(buildDiagnosisKeys(6, 50L, 4).stream(), buildDiagnosisKeys(6, 51L, 1).stream())
+ .collect(Collectors.toList());
+ bundler.setDiagnosisKeys(diagnosisKeys, LocalDateTime.of(1970, 1, 5, 0, 0));
+ assertThat(bundler.getDiagnosisKeysForHour(LocalDateTime.of(1970, 1, 3, 2, 0, 0))).hasSize(0);
+ assertThat(bundler.getDiagnosisKeysForHour(LocalDateTime.of(1970, 1, 3, 3, 0, 0))).hasSize(5);
+ }
+
+ @Test
+ void testShiftsSinceLastDistribution() {
+ List<DiagnosisKey> diagnosisKeys = Stream
+ .of(buildDiagnosisKeys(6, 50L, 5), buildDiagnosisKeys(6, 51L, 2), buildDiagnosisKeys(6, 52L, 4))
+ .flatMap(List::stream)
+ .collect(Collectors.toList());
+ bundler.setDiagnosisKeys(diagnosisKeys, LocalDateTime.of(1970, 1, 5, 0, 0));
+ assertThat(bundler.getDiagnosisKeysForHour(LocalDateTime.of(1970, 1, 3, 2, 0, 0))).hasSize(5);
+ assertThat(bundler.getDiagnosisKeysForHour(LocalDateTime.of(1970, 1, 3, 3, 0, 0))).hasSize(0);
+ assertThat(bundler.getDiagnosisKeysForHour(LocalDateTime.of(1970, 1, 3, 4, 0, 0))).hasSize(6);
+ assertThat(bundler.getDiagnosisKeysForHour(LocalDateTime.of(1970, 1, 3, 5, 0, 0))).hasSize(0);
+ }
+
+ @Test
+ void testShiftIncludesPreviouslyUndistributedKeys() {
+ List<DiagnosisKey> diagnosisKeys = Stream
+ .concat(buildDiagnosisKeys(6, 50L, 1).stream(), buildDiagnosisKeys(6, 51L, 5).stream())
+ .collect(Collectors.toList());
+ bundler.setDiagnosisKeys(diagnosisKeys, LocalDateTime.of(1970, 1, 5, 0, 0));
+ assertThat(bundler.getDiagnosisKeysForHour(LocalDateTime.of(1970, 1, 3, 2, 0, 0))).hasSize(0);
+ assertThat(bundler.getDiagnosisKeysForHour(LocalDateTime.of(1970, 1, 3, 3, 0, 0))).hasSize(6);
+ }
+
+ @Test
+ void testShiftsSparseDistributions() {
+ List<DiagnosisKey> diagnosisKeys = Stream
+ .of(buildDiagnosisKeys(6, 50L, 1), buildDiagnosisKeys(6, 51L, 1), buildDiagnosisKeys(6, 52L, 1),
+ buildDiagnosisKeys(6, 53L, 0), buildDiagnosisKeys(6, 54L, 0), buildDiagnosisKeys(6, 55L, 1),
+ buildDiagnosisKeys(6, 56L, 1))
+ .flatMap(List::stream)
+ .collect(Collectors.toList());
+ bundler.setDiagnosisKeys(diagnosisKeys, LocalDateTime.of(1970, 1, 5, 0, 0));
+ assertThat(bundler.getDiagnosisKeysForHour(LocalDateTime.of(1970, 1, 3, 2, 0, 0))).hasSize(0);
+ assertThat(bundler.getDiagnosisKeysForHour(LocalDateTime.of(1970, 1, 3, 3, 0, 0))).hasSize(0);
+ assertThat(bundler.getDiagnosisKeysForHour(LocalDateTime.of(1970, 1, 3, 4, 0, 0))).hasSize(0);
+ assertThat(bundler.getDiagnosisKeysForHour(LocalDateTime.of(1970, 1, 3, 5, 0, 0))).hasSize(0);
+ assertThat(bundler.getDiagnosisKeysForHour(LocalDateTime.of(1970, 1, 3, 6, 0, 0))).hasSize(0);
+ assertThat(bundler.getDiagnosisKeysForHour(LocalDateTime.of(1970, 1, 3, 7, 0, 0))).hasSize(0);
+ assertThat(bundler.getDiagnosisKeysForHour(LocalDateTime.of(1970, 1, 3, 8, 0, 0))).hasSize(5);
+ }
+}
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/ProdDiagnosisKeyBundlerTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/ProdDiagnosisKeyBundlerTest.java
deleted file mode 100644
--- a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/ProdDiagnosisKeyBundlerTest.java
+++ /dev/null
@@ -1,190 +0,0 @@
-/*-
- * ---license-start
- * Corona-Warn-App
- * ---
- * Copyright (C) 2020 SAP SE and all other contributors
- * ---
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://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 for the specific language governing permissions and
- * limitations under the License.
- * ---license-end
- */
-
-package app.coronawarn.server.services.distribution.assembly.diagnosiskeys;
-
-import static org.assertj.core.api.Assertions.assertThat;
-
-import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
-import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
-import java.time.LocalDateTime;
-import java.util.List;
-import java.util.stream.Collectors;
-import java.util.stream.IntStream;
-import java.util.stream.Stream;
-import org.junit.jupiter.api.DisplayName;
-import org.junit.jupiter.api.Nested;
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.extension.ExtendWith;
-import org.junit.jupiter.params.ParameterizedTest;
-import org.junit.jupiter.params.provider.ValueSource;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.boot.context.properties.EnableConfigurationProperties;
-import org.springframework.boot.test.context.ConfigFileApplicationContextInitializer;
-import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit.jupiter.SpringExtension;
-
-@EnableConfigurationProperties(value = DistributionServiceConfig.class)
-@ExtendWith(SpringExtension.class)
-@ContextConfiguration(classes = {DistributionServiceConfig.class, ProdDiagnosisKeyBundler.class},
- initializers = ConfigFileApplicationContextInitializer.class)
-class ProdDiagnosisKeyBundlerTest {
-
- @Autowired
- DistributionServiceConfig distributionServiceConfig;
-
- @Autowired
- DiagnosisKeyBundler bundler;
-
- @Test
- void testEmptyListWhenNoDiagnosisKeys() {
- bundler.setDiagnosisKeys(List.of());
- assertThat(bundler.getDiagnosisKeysDistributableAt(LocalDateTime.of(1970, 1, 1, 0, 0, 0))).hasSize(0);
- }
-
- @Test
- void testEmptyListWhenGettingDistributableKeysBeforeEarliestDiagnosisKey() {
- List<DiagnosisKey> diagnosisKeys = buildDiagnosisKeys(6, 50L, 5);
- bundler.setDiagnosisKeys(diagnosisKeys);
- assertThat(bundler.getDiagnosisKeysDistributableAt(LocalDateTime.of(1970, 1, 1, 0, 0, 0))).hasSize(0);
- }
-
- @Nested
- @DisplayName("Expiry policy")
- class ProdDiagnosisKeyBundlerExpiryPolicyTest {
-
- @ParameterizedTest
- @ValueSource(longs = {0L, 24L, 24L + 2L})
- void testLastPeriodOfHourAndSubmissionLessThanDistributionDateTime(long submissionTimestamp) {
- List<DiagnosisKey> diagnosisKeys = buildDiagnosisKeys(5, submissionTimestamp, 10);
- bundler.setDiagnosisKeys(diagnosisKeys);
- assertThat(bundler.getDiagnosisKeysDistributableAt(LocalDateTime.of(1970, 1, 2, 3, 0, 0))).hasSize(10);
- }
-
- @Test
- void testLastPeriodOfHourAndSubmissionEqualsDistributionDateTime() {
- List<DiagnosisKey> diagnosisKeys = buildDiagnosisKeys(5, 24L + 3L, 10);
- bundler.setDiagnosisKeys(diagnosisKeys);
- assertThat(bundler.getDiagnosisKeysDistributableAt(LocalDateTime.of(1970, 1, 2, 3, 0, 0))).hasSize(10);
- }
-
- @ParameterizedTest
- @ValueSource(longs = {0L, 24L, 24L + 2L, 24L + 3L})
- void testFirstPeriodOfHourAndSubmissionLessThanDistributionDateTime(long submissionTimestamp) {
- List<DiagnosisKey> diagnosisKeys = buildDiagnosisKeys(6, submissionTimestamp, 10);
- bundler.setDiagnosisKeys(diagnosisKeys);
- assertThat(bundler.getDiagnosisKeysDistributableAt(LocalDateTime.of(1970, 1, 2, 4, 0, 0))).hasSize(10);
- }
-
- @Test
- void testFirstPeriodOfHourAndSubmissionEqualsDistributionDateTime() {
- List<DiagnosisKey> diagnosisKeys = buildDiagnosisKeys(6, 24L + 4L, 10);
- bundler.setDiagnosisKeys(diagnosisKeys);
- assertThat(bundler.getDiagnosisKeysDistributableAt(LocalDateTime.of(1970, 1, 2, 4, 0, 0))).hasSize(10);
- }
-
- @Test
- void testLastPeriodOfHourAndSubmissionGreaterDistributionDateTime() {
- List<DiagnosisKey> diagnosisKeys = buildDiagnosisKeys(5, 24L + 4L, 10);
- bundler.setDiagnosisKeys(diagnosisKeys);
- assertThat(bundler.getDiagnosisKeysDistributableAt(LocalDateTime.of(1970, 1, 2, 4, 0, 0))).hasSize(10);
- }
- }
-
- @Nested
- @DisplayName("Shifting policy")
- class ProdDiagnosisKeyBundlerShiftingPolicyTest {
-
- @Test
- void testDoesNotShiftIfPackageSizeGreaterThanThreshold() {
- List<DiagnosisKey> diagnosisKeys = buildDiagnosisKeys(6, 50L, 6);
- bundler.setDiagnosisKeys(diagnosisKeys);
- assertThat(bundler.getDiagnosisKeysDistributableAt(LocalDateTime.of(1970, 1, 3, 2, 0, 0))).hasSize(6);
- }
-
- @Test
- void testDoesNotShiftIfPackageSizeEqualsThreshold() {
- List<DiagnosisKey> diagnosisKeys = buildDiagnosisKeys(6, 50L, 5);
- bundler.setDiagnosisKeys(diagnosisKeys);
- assertThat(bundler.getDiagnosisKeysDistributableAt(LocalDateTime.of(1970, 1, 3, 2, 0, 0))).hasSize(5);
- }
-
- @Test
- void testShiftsIfPackageSizeLessThanThreshold() {
- List<DiagnosisKey> diagnosisKeys = Stream
- .concat(buildDiagnosisKeys(6, 50L, 4).stream(), buildDiagnosisKeys(6, 51L, 1).stream())
- .collect(Collectors.toList());
- bundler.setDiagnosisKeys(diagnosisKeys);
- assertThat(bundler.getDiagnosisKeysDistributableAt(LocalDateTime.of(1970, 1, 3, 2, 0, 0))).hasSize(0);
- assertThat(bundler.getDiagnosisKeysDistributableAt(LocalDateTime.of(1970, 1, 3, 3, 0, 0))).hasSize(5);
- }
-
- @Test
- void testShiftsSinceLastDistribution() {
- List<DiagnosisKey> diagnosisKeys = Stream
- .of(buildDiagnosisKeys(6, 50L, 5), buildDiagnosisKeys(6, 51L, 2), buildDiagnosisKeys(6, 52L, 4))
- .flatMap(List::stream)
- .collect(Collectors.toList());
- bundler.setDiagnosisKeys(diagnosisKeys);
- assertThat(bundler.getDiagnosisKeysDistributableAt(LocalDateTime.of(1970, 1, 3, 2, 0, 0))).hasSize(5);
- assertThat(bundler.getDiagnosisKeysDistributableAt(LocalDateTime.of(1970, 1, 3, 3, 0, 0))).hasSize(0);
- assertThat(bundler.getDiagnosisKeysDistributableAt(LocalDateTime.of(1970, 1, 3, 4, 0, 0))).hasSize(6);
- assertThat(bundler.getDiagnosisKeysDistributableAt(LocalDateTime.of(1970, 1, 3, 5, 0, 0))).hasSize(0);
- }
-
- @Test
- void testShiftIncludesPreviouslyUndistributedKeys() {
- List<DiagnosisKey> diagnosisKeys = Stream
- .concat(buildDiagnosisKeys(6, 50L, 1).stream(), buildDiagnosisKeys(6, 51L, 5).stream())
- .collect(Collectors.toList());
- bundler.setDiagnosisKeys(diagnosisKeys);
- assertThat(bundler.getDiagnosisKeysDistributableAt(LocalDateTime.of(1970, 1, 3, 2, 0, 0))).hasSize(0);
- assertThat(bundler.getDiagnosisKeysDistributableAt(LocalDateTime.of(1970, 1, 3, 3, 0, 0))).hasSize(5);
- }
-
- @Test
- void testShiftsSparseDistributions() {
- List<DiagnosisKey> diagnosisKeys = Stream
- .of(buildDiagnosisKeys(6, 50L, 1), buildDiagnosisKeys(6, 51L, 1), buildDiagnosisKeys(6, 52L, 1),
- buildDiagnosisKeys(6, 53L, 0), buildDiagnosisKeys(6, 54L, 0), buildDiagnosisKeys(6, 55L, 1),
- buildDiagnosisKeys(6, 56L, 1))
- .flatMap(List::stream)
- .collect(Collectors.toList());
- bundler.setDiagnosisKeys(diagnosisKeys);
- assertThat(bundler.getDiagnosisKeysDistributableAt(LocalDateTime.of(1970, 1, 3, 2, 0, 0))).hasSize(0);
- assertThat(bundler.getDiagnosisKeysDistributableAt(LocalDateTime.of(1970, 1, 3, 3, 0, 0))).hasSize(0);
- assertThat(bundler.getDiagnosisKeysDistributableAt(LocalDateTime.of(1970, 1, 3, 4, 0, 0))).hasSize(0);
- assertThat(bundler.getDiagnosisKeysDistributableAt(LocalDateTime.of(1970, 1, 3, 5, 0, 0))).hasSize(0);
- assertThat(bundler.getDiagnosisKeysDistributableAt(LocalDateTime.of(1970, 1, 3, 6, 0, 0))).hasSize(0);
- assertThat(bundler.getDiagnosisKeysDistributableAt(LocalDateTime.of(1970, 1, 3, 7, 0, 0))).hasSize(0);
- assertThat(bundler.getDiagnosisKeysDistributableAt(LocalDateTime.of(1970, 1, 3, 8, 0, 0))).hasSize(5);
- }
- }
-
- public static List<DiagnosisKey> buildDiagnosisKeys(int startIntervalNumber, long submissionTimestamp, int number) {
- return IntStream.range(0, number)
- .mapToObj(__ -> DiagnosisKey.builder()
- .withKeyData(new byte[16])
- .withRollingStartIntervalNumber(startIntervalNumber)
- .withTransmissionRiskLevel(2)
- .withSubmissionTimestamp(submissionTimestamp).build())
- .collect(Collectors.toList());
- }
-}
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysDirectoryTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysDirectoryTest.java
--- a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysDirectoryTest.java
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysDirectoryTest.java
@@ -21,6 +21,7 @@
package app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.directory;
import static app.coronawarn.server.services.distribution.common.Helpers.buildDiagnosisKeyForSubmissionTimestamp;
+import static app.coronawarn.server.services.distribution.common.Helpers.buildDiagnosisKeys;
import static java.lang.String.join;
import static org.assertj.core.api.Assertions.assertThat;
@@ -28,6 +29,7 @@
import app.coronawarn.server.services.distribution.assembly.component.CryptoProvider;
import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.DemoDiagnosisKeyBundler;
import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.DiagnosisKeyBundler;
+import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.ProdDiagnosisKeyBundler;
import app.coronawarn.server.services.distribution.assembly.structure.WritableOnDisk;
import app.coronawarn.server.services.distribution.assembly.structure.directory.Directory;
import app.coronawarn.server.services.distribution.assembly.structure.directory.DirectoryOnDisk;
@@ -35,6 +37,7 @@
import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
import java.io.File;
import java.io.IOException;
+import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
@@ -81,17 +84,18 @@ void setupAll() throws IOException {
// 01.01.1970 - 00:00 UTC
long startTimestamp = 0;
- // Generate diagnosis keys covering 30 hours of submission timestamps
- // Until 02.01.1970 - 06:00 UTC -> 1 full day + 6 hours
+ // Generate diagnosis keys covering 29 hours of submission timestamps (one gap)
+ // Until 04.01.1970 - 06:00 UTC -> 1 full day + 5 hours
diagnosisKeys = IntStream.range(0, 30)
- .mapToObj(
- currentHour -> buildDiagnosisKeyForSubmissionTimestamp(startTimestamp + currentHour))
+ .filter(currentHour -> currentHour != 20)
+ .mapToObj(currentHour -> buildDiagnosisKeys(6, LocalDateTime.of(1970, 1, 3, 0, 0).plusHours(currentHour), 5))
+ .flatMap(List::stream)
.collect(Collectors.toList());
}
@Test
void checkBuildsTheCorrectDirectoryStructureWhenNoKeys() {
- DiagnosisKeyBundler bundler = new DemoDiagnosisKeyBundler(distributionServiceConfig);
+ DiagnosisKeyBundler bundler = new ProdDiagnosisKeyBundler(distributionServiceConfig);
Directory<WritableOnDisk> directory = new DiagnosisKeysDirectory(bundler, cryptoProvider,
distributionServiceConfig);
parentDirectory.addWritable(directory);
@@ -101,7 +105,6 @@ void checkBuildsTheCorrectDirectoryStructureWhenNoKeys() {
String s = File.separator;
Set<String> expectedFiles = Set.of(
join(s, "diagnosis-keys", "country", "index"),
- join(s, "diagnosis-keys", "country", "DE", "index"),
join(s, "diagnosis-keys", "country", "DE", "date", "index")
);
@@ -112,8 +115,8 @@ void checkBuildsTheCorrectDirectoryStructureWhenNoKeys() {
@Test
void checkBuildsTheCorrectDirectoryStructure() {
- DiagnosisKeyBundler bundler = new DemoDiagnosisKeyBundler(distributionServiceConfig);
- bundler.setDiagnosisKeys(diagnosisKeys);
+ DiagnosisKeyBundler bundler = new ProdDiagnosisKeyBundler(distributionServiceConfig);
+ bundler.setDiagnosisKeys(diagnosisKeys, LocalDateTime.of(1970, 1, 5, 0, 0));
Directory<WritableOnDisk> directory = new DiagnosisKeysDirectory(bundler, cryptoProvider,
distributionServiceConfig);
parentDirectory.addWritable(directory);
@@ -123,42 +126,41 @@ void checkBuildsTheCorrectDirectoryStructure() {
String s = File.separator;
Set<String> expectedFiles = Set.of(
join(s, "diagnosis-keys", "country", "index"),
- join(s, "diagnosis-keys", "country", "DE", "index"),
join(s, "diagnosis-keys", "country", "DE", "date", "index"),
- join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-01", "index"),
- join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-01", "hour", "index"),
- join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-01", "hour", "0", "index"),
- join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-01", "hour", "1", "index"),
- join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-01", "hour", "2", "index"),
- join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-01", "hour", "3", "index"),
- join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-01", "hour", "4", "index"),
- join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-01", "hour", "5", "index"),
- join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-01", "hour", "6", "index"),
- join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-01", "hour", "7", "index"),
- join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-01", "hour", "8", "index"),
- join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-01", "hour", "9", "index"),
- join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-01", "hour", "10", "index"),
- join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-01", "hour", "11", "index"),
- join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-01", "hour", "12", "index"),
- join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-01", "hour", "13", "index"),
- join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-01", "hour", "14", "index"),
- join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-01", "hour", "15", "index"),
- join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-01", "hour", "16", "index"),
- join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-01", "hour", "17", "index"),
- join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-01", "hour", "18", "index"),
- join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-01", "hour", "19", "index"),
- join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-01", "hour", "20", "index"),
- join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-01", "hour", "21", "index"),
- join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-01", "hour", "22", "index"),
- join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-01", "hour", "23", "index"),
- join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-02", "index"),
- join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-02", "hour", "index"),
- join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-02", "hour", "0", "index"),
- join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-02", "hour", "1", "index"),
- join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-02", "hour", "2", "index"),
- join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-02", "hour", "3", "index"),
- join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-02", "hour", "4", "index"),
- join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-02", "hour", "5", "index")
+ join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-03", "index"),
+ join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-03", "hour", "index"),
+ join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-03", "hour", "0", "index"),
+ join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-03", "hour", "1", "index"),
+ join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-03", "hour", "2", "index"),
+ join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-03", "hour", "3", "index"),
+ join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-03", "hour", "4", "index"),
+ join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-03", "hour", "5", "index"),
+ join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-03", "hour", "6", "index"),
+ join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-03", "hour", "7", "index"),
+ join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-03", "hour", "8", "index"),
+ join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-03", "hour", "9", "index"),
+ join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-03", "hour", "10", "index"),
+ join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-03", "hour", "11", "index"),
+ join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-03", "hour", "12", "index"),
+ join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-03", "hour", "13", "index"),
+ join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-03", "hour", "14", "index"),
+ join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-03", "hour", "15", "index"),
+ join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-03", "hour", "16", "index"),
+ join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-03", "hour", "17", "index"),
+ join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-03", "hour", "18", "index"),
+ join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-03", "hour", "19", "index"),
+ // One missing
+ join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-03", "hour", "21", "index"),
+ join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-03", "hour", "22", "index"),
+ join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-03", "hour", "23", "index"),
+ join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-04", "index"),
+ join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-04", "hour", "index"),
+ join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-04", "hour", "0", "index"),
+ join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-04", "hour", "1", "index"),
+ join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-04", "hour", "2", "index"),
+ join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-04", "hour", "3", "index"),
+ join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-04", "hour", "4", "index"),
+ join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-04", "hour", "5", "index")
);
Set<String> actualFiles = getActualFiles(outputFile);
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/decorator/DateIndexingDecoratorTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/decorator/DateIndexingDecoratorTest.java
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/decorator/DateIndexingDecoratorTest.java
@@ -0,0 +1,106 @@
+/*
+ * ---license-start
+ * Corona-Warn-App
+ * ---
+ * Copyright (C) 2020 SAP SE and all other contributors
+ * ---
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://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 for the specific language governing permissions and
+ * limitations under the License.
+ * ---license-end
+ */
+
+package app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.directory.decorator;
+
+import static app.coronawarn.server.services.distribution.common.Helpers.buildDiagnosisKeys;
+import static org.assertj.core.api.Assertions.assertThat;
+
+import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
+import app.coronawarn.server.services.distribution.assembly.component.CryptoProvider;
+import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.DiagnosisKeyBundler;
+import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.ProdDiagnosisKeyBundler;
+import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.directory.DiagnosisKeysDateDirectory;
+import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.directory.DiagnosisKeysHourDirectory;
+import app.coronawarn.server.services.distribution.assembly.structure.util.ImmutableStack;
+import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
+import java.time.LocalDate;
+import java.time.LocalDateTime;
+import java.util.List;
+import java.util.Set;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.context.properties.EnableConfigurationProperties;
+import org.springframework.boot.test.context.ConfigFileApplicationContextInitializer;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit.jupiter.SpringExtension;
+
+@EnableConfigurationProperties(value = DistributionServiceConfig.class)
+@ExtendWith(SpringExtension.class)
+@ContextConfiguration(classes = {CryptoProvider.class, DistributionServiceConfig.class},
+ initializers = ConfigFileApplicationContextInitializer.class)
+class DateIndexingDecoratorTest {
+
+ @Autowired
+ DistributionServiceConfig distributionServiceConfig;
+
+ @Autowired
+ CryptoProvider cryptoProvider;
+
+ private DiagnosisKeyBundler diagnosisKeyBundler;
+
+ @BeforeEach
+ void setup() {
+ diagnosisKeyBundler = new ProdDiagnosisKeyBundler(distributionServiceConfig);
+ }
+
+ @Test
+ void excludesEmptyDatesFromIndex() {
+ List<DiagnosisKey> diagnosisKeys = Stream
+ .of(buildDiagnosisKeys(6, LocalDateTime.of(1970, 1, 3, 0, 0), 5),
+ buildDiagnosisKeys(6, LocalDateTime.of(1970, 1, 4, 0, 0), 0),
+ buildDiagnosisKeys(6, LocalDateTime.of(1970, 1, 5, 0, 0), 5))
+ .flatMap(List::stream)
+ .collect(Collectors.toList());
+ diagnosisKeyBundler.setDiagnosisKeys(diagnosisKeys, LocalDateTime.of(1970, 1, 6, 0, 0));
+ DateIndexingDecorator decorator = makeDecoratedDateDirectory(diagnosisKeyBundler);
+ decorator.prepare(new ImmutableStack<>().push("DE"));
+
+ Set<LocalDate> index = decorator.getIndex(new ImmutableStack<>());
+
+ assertThat(index).contains(LocalDate.of(1970, 1, 3));
+ assertThat(index).doesNotContain(LocalDate.of(1970, 1, 4));
+ assertThat(index).contains(LocalDate.of(1970, 1, 5));
+ }
+
+ @Test
+ void excludesCurrentDateFromIndex() {
+ List<DiagnosisKey> diagnosisKeys = buildDiagnosisKeys(6, LocalDateTime.of(1970, 1, 4, 0, 0), 5);
+ diagnosisKeyBundler.setDiagnosisKeys(diagnosisKeys, LocalDateTime.of(1970, 1, 5, 0, 0));
+ DateIndexingDecorator decorator = makeDecoratedDateDirectory(diagnosisKeyBundler);
+ decorator.prepare(new ImmutableStack<>().push("DE"));
+
+ Set<LocalDate> index = decorator.getIndex(new ImmutableStack<>());
+
+ assertThat(index).contains(LocalDate.of(1970, 1, 4));
+ assertThat(index).doesNotContain(LocalDate.of(1970, 1, 5));
+ }
+
+ private DateIndexingDecorator makeDecoratedDateDirectory(DiagnosisKeyBundler diagnosisKeyBundler) {
+ return new DateIndexingDecorator(
+ new DiagnosisKeysDateDirectory(diagnosisKeyBundler, cryptoProvider, distributionServiceConfig),
+ distributionServiceConfig
+ );
+ }
+}
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/decorator/HourIndexingDecoratorTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/decorator/HourIndexingDecoratorTest.java
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/decorator/HourIndexingDecoratorTest.java
@@ -0,0 +1,105 @@
+/*
+ * ---license-start
+ * Corona-Warn-App
+ * ---
+ * Copyright (C) 2020 SAP SE and all other contributors
+ * ---
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://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 for the specific language governing permissions and
+ * limitations under the License.
+ * ---license-end
+ */
+
+package app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.directory.decorator;
+
+import static app.coronawarn.server.services.distribution.common.Helpers.buildDiagnosisKeys;
+import static org.assertj.core.api.Assertions.assertThat;
+
+import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
+import app.coronawarn.server.services.distribution.assembly.component.CryptoProvider;
+import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.DiagnosisKeyBundler;
+import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.ProdDiagnosisKeyBundler;
+import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.directory.DiagnosisKeysHourDirectory;
+import app.coronawarn.server.services.distribution.assembly.structure.util.ImmutableStack;
+import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
+import java.time.LocalDate;
+import java.time.LocalDateTime;
+import java.util.List;
+import java.util.Set;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.context.properties.EnableConfigurationProperties;
+import org.springframework.boot.test.context.ConfigFileApplicationContextInitializer;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit.jupiter.SpringExtension;
+
+@EnableConfigurationProperties(value = DistributionServiceConfig.class)
+@ExtendWith(SpringExtension.class)
+@ContextConfiguration(classes = {CryptoProvider.class, DistributionServiceConfig.class},
+ initializers = ConfigFileApplicationContextInitializer.class)
+class HourIndexingDecoratorTest {
+
+ @Autowired
+ DistributionServiceConfig distributionServiceConfig;
+
+ @Autowired
+ CryptoProvider cryptoProvider;
+
+ private DiagnosisKeyBundler diagnosisKeyBundler;
+
+ @BeforeEach
+ void setup() {
+ diagnosisKeyBundler = new ProdDiagnosisKeyBundler(distributionServiceConfig);
+ }
+
+ @Test
+ void excludesEmptyHoursFromIndex() {
+ List<DiagnosisKey> diagnosisKeys = Stream
+ .of(buildDiagnosisKeys(6, LocalDateTime.of(1970, 1, 3, 4, 0), 5),
+ buildDiagnosisKeys(6, LocalDateTime.of(1970, 1, 3, 5, 0), 0),
+ buildDiagnosisKeys(6, LocalDateTime.of(1970, 1, 3, 6, 0), 5))
+ .flatMap(List::stream)
+ .collect(Collectors.toList());
+ diagnosisKeyBundler.setDiagnosisKeys(diagnosisKeys, LocalDateTime.of(1970, 1, 5, 0, 0));
+ HourIndexingDecorator decorator = makeDecoratedHourDirectory(diagnosisKeyBundler);
+ decorator.prepare(new ImmutableStack<>().push("DE").push(LocalDate.of(1970, 1, 3)));
+
+ Set<LocalDateTime> index = decorator.getIndex(new ImmutableStack<>().push(LocalDate.of(1970, 1, 3)));
+
+ assertThat(index).contains(LocalDateTime.of(1970, 1, 3, 4, 0));
+ assertThat(index).doesNotContain(LocalDateTime.of(1970, 1, 3, 5, 0));
+ assertThat(index).contains(LocalDateTime.of(1970, 1, 3, 6, 0));
+ }
+
+ @Test
+ void excludesCurrentHourFromIndex() {
+ List<DiagnosisKey> diagnosisKeys = buildDiagnosisKeys(6, LocalDateTime.of(1970, 1, 5, 0, 0), 5);
+ diagnosisKeyBundler.setDiagnosisKeys(diagnosisKeys, LocalDateTime.of(1970, 1, 5, 1, 0));
+ HourIndexingDecorator decorator = makeDecoratedHourDirectory(diagnosisKeyBundler);
+ decorator.prepare(new ImmutableStack<>().push("DE").push(LocalDate.of(1970, 1, 5)));
+
+ Set<LocalDateTime> index = decorator.getIndex(new ImmutableStack<>().push(LocalDate.of(1970, 1, 5)));
+
+ assertThat(index).contains(LocalDateTime.of(1970, 1, 5, 0, 0));
+ assertThat(index).doesNotContain(LocalDateTime.of(1970, 1, 5, 1, 0));
+ }
+
+ private HourIndexingDecorator makeDecoratedHourDirectory(DiagnosisKeyBundler diagnosisKeyBundler) {
+ return new HourIndexingDecorator(
+ new DiagnosisKeysHourDirectory(diagnosisKeyBundler, cryptoProvider, distributionServiceConfig),
+ distributionServiceConfig
+ );
+ }
+}
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/util/DateTimeTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/util/DateTimeTest.java
deleted file mode 100644
--- a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/util/DateTimeTest.java
+++ /dev/null
@@ -1,103 +0,0 @@
-/*-
- * ---license-start
- * Corona-Warn-App
- * ---
- * Copyright (C) 2020 SAP SE and all other contributors
- * ---
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://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 for the specific language governing permissions and
- * limitations under the License.
- * ---license-end
- */
-
-package app.coronawarn.server.services.distribution.assembly.diagnosiskeys.util;
-
-import static app.coronawarn.server.services.distribution.common.Helpers.buildDiagnosisKeyForDateTime;
-import static java.util.Collections.emptyList;
-import static java.util.Collections.emptySet;
-import static org.assertj.core.api.Assertions.assertThat;
-
-import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
-import app.coronawarn.server.services.distribution.common.Helpers;
-import java.time.LocalDate;
-import java.time.LocalDateTime;
-import java.util.HashSet;
-import java.util.Set;
-import java.util.stream.Collectors;
-import java.util.stream.Stream;
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.params.ParameterizedTest;
-import org.junit.jupiter.params.provider.Arguments;
-import org.junit.jupiter.params.provider.MethodSource;
-
-class DateTimeTest {
-
- @Test
- void testGetDatesForEmptyList() {
- assertThat(DateTime.getDates(emptyList())).isEmpty();
- }
-
- @ParameterizedTest
- @MethodSource("createDiagnosisKeysForEpochDay0")
- void testGetDatesForEpochDay0(DiagnosisKey diagnosisKey) {
- var expDates = Set.of(LocalDate.ofEpochDay(0L));
- var actDates = DateTime.getDates(Set.of(diagnosisKey));
-
- assertThat(actDates)
- .withFailMessage(
- "Failed for submission timestamp: " + diagnosisKey.getSubmissionTimestamp())
- .isEqualTo(expDates);
- }
-
- private static Stream<Arguments> createDiagnosisKeysForEpochDay0() {
- return Stream.of(
- buildDiagnosisKeyForDateTime(LocalDateTime.of(1970, 1, 1, 0, 0)),
- buildDiagnosisKeyForDateTime(LocalDateTime.of(1970, 1, 1, 1, 0)),
- buildDiagnosisKeyForDateTime(LocalDateTime.of(1970, 1, 1, 23, 59, 59))
- ).map(Arguments::of);
- }
-
- @Test
- void testGetDatesFor2Days() {
- var diagnosisKeys = Set.of(
- buildDiagnosisKeyForDateTime(LocalDateTime.of(1970, 1, 1, 1, 0)),
- buildDiagnosisKeyForDateTime(LocalDateTime.of(1970, 1, 2, 1, 0)));
- var expDates = Set.of(LocalDate.ofEpochDay(0L), LocalDate.ofEpochDay(1L));
-
- assertThat(DateTime.getDates(diagnosisKeys)).isEqualTo(expDates);
- }
-
- @ParameterizedTest
- @MethodSource("createDiagnosisKeysForEpochDay1And3")
- void testGetHoursReturnsHoursOnlyForSpecifiedDate(Set<DiagnosisKey> diagnosisKeys) {
- var expHours = Set.of(
- LocalDateTime.of(1970, 1, 2, 0, 0),
- LocalDateTime.of(1970, 1, 2, 5, 0));
-
- var diagnosisKeysIncludingExpHours = new HashSet<>(diagnosisKeys);
- diagnosisKeysIncludingExpHours.addAll(expHours.stream()
- .map(Helpers::buildDiagnosisKeyForDateTime).collect(Collectors.toSet()));
-
- var actHours = DateTime.getHours(LocalDate.ofEpochDay(1L), diagnosisKeysIncludingExpHours);
-
- assertThat(actHours).isEqualTo(expHours);
- }
-
- private static Stream<Arguments> createDiagnosisKeysForEpochDay1And3() {
- return Stream.of(
- emptySet(),
- Set.of(buildDiagnosisKeyForDateTime(LocalDateTime.of(1970, 1, 1, 23, 59))),
- Set.of(
- buildDiagnosisKeyForDateTime(LocalDateTime.of(1970, 1, 1, 23, 59, 59)),
- buildDiagnosisKeyForDateTime(LocalDateTime.of(1970, 1, 3, 0, 0)))
- ).map(Arguments::of);
- }
-}
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/common/Helpers.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/common/Helpers.java
--- a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/common/Helpers.java
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/common/Helpers.java
@@ -25,6 +25,9 @@
import app.coronawarn.server.services.distribution.assembly.structure.util.ImmutableStack;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
+import java.util.List;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
public class Helpers {
@@ -36,7 +39,7 @@ public static void prepareAndWrite(Directory directory) {
public static DiagnosisKey buildDiagnosisKeyForSubmissionTimestamp(long submissionTimeStamp) {
return DiagnosisKey.builder()
.withKeyData(new byte[16])
- .withRollingStartIntervalNumber(600)
+ .withRollingStartIntervalNumber(1)
.withTransmissionRiskLevel(2)
.withSubmissionTimestamp(submissionTimeStamp).build();
}
@@ -44,4 +47,19 @@ public static DiagnosisKey buildDiagnosisKeyForSubmissionTimestamp(long submissi
public static DiagnosisKey buildDiagnosisKeyForDateTime(LocalDateTime dateTime) {
return buildDiagnosisKeyForSubmissionTimestamp(dateTime.toEpochSecond(ZoneOffset.UTC) / 3600);
}
+
+ public static List<DiagnosisKey> buildDiagnosisKeys(int startIntervalNumber, LocalDateTime submissionTimestamp, int number) {
+ long timestamp = submissionTimestamp.toEpochSecond(ZoneOffset.UTC) / 3600;
+ return buildDiagnosisKeys(startIntervalNumber, timestamp, number);
+ }
+
+ public static List<DiagnosisKey> buildDiagnosisKeys(int startIntervalNumber, long submissionTimestamp, int number) {
+ return IntStream.range(0, number)
+ .mapToObj(__ -> DiagnosisKey.builder()
+ .withKeyData(new byte[16])
+ .withRollingStartIntervalNumber(startIntervalNumber)
+ .withTransmissionRiskLevel(2)
+ .withSubmissionTimestamp(submissionTimestamp).build())
+ .collect(Collectors.toList());
+ }
}
| ||||
corona-warn-app__cwa-server-346 | You will be provided with a partial code base and an issue statement explaining a problem to resolve.
<issue>
Retention: Enforce period on Object Store
Currently, the retention period is only enforced for keys on the database, but it should be enforced on the S3 as well.
Therefore, we need to delete the items on the S3, when the retention policy is reached.
When the retention mechanism is kicked off, and then delete the following keys with the prefix:
`version/v1/diagnosis-keys/country/DE/date/<RETENTIONDATE>`
Where RETENTIONDATE is `current date - retention period`.
Ideally, we should also try to delete older items as well, in case the retention run did not succeed or did not run at all.
</issue>
<code>
[start of README.md]
1 <!-- markdownlint-disable MD041 -->
2 <h1 align="center">
3 Corona-Warn-App Server
4 </h1>
5
6 <p align="center">
7 <a href="https://github.com/corona-warn-app/cwa-server/commits/" title="Last Commit"><img src="https://img.shields.io/github/last-commit/corona-warn-app/cwa-server?style=flat"></a>
8 <a href="https://github.com/corona-warn-app/cwa-server/issues" title="Open Issues"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat"></a>
9 <a href="https://circleci.com/gh/corona-warn-app/cwa-server" title="Build Status"><img src="https://circleci.com/gh/corona-warn-app/cwa-server.svg?style=shield&circle-token=4ab059989d10709df19eb4b98ab7c121a25e981a"></a>
10 <a href="https://sonarcloud.io/dashboard?id=corona-warn-app_cwa-server" title="Quality Gate"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=alert_status"></a>
11 <a href="https://sonarcloud.io/component_measures?id=corona-warn-app_cwa-server&metric=Coverage&view=list" title="Coverage"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=coverage"></a>
12 <a href="https://github.com/corona-warn-app/cwa-server/blob/master/LICENSE" title="License"><img src="https://img.shields.io/badge/License-Apache%202.0-green.svg?style=flat"></a>
13 </p>
14
15 <p align="center">
16 <a href="#development">Development</a> •
17 <a href="#service-apis">Service APIs</a> •
18 <a href="#documentation">Documentation</a> •
19 <a href="#support-and-feedback">Support</a> •
20 <a href="#how-to-contribute">Contribute</a> •
21 <a href="#contributors">Contributors</a> •
22 <a href="#repositories">Repositories</a> •
23 <a href="#licensing">Licensing</a>
24 </p>
25
26 The goal of this project is to develop the official Corona-Warn-App for Germany based on the exposure notification API from [Apple](https://www.apple.com/covid19/contacttracing/) and [Google](https://www.google.com/covid19/exposurenotifications/). The apps (for both iOS and Android) use Bluetooth technology to exchange anonymous encrypted data with other mobile phones (on which the app is also installed) in the vicinity of an app user's phone. The data is stored locally on each user's device, preventing authorities or other parties from accessing or controlling the data. This repository contains the **implementation of the server for encryption keys** for the Corona-Warn-App. This implementation is still a **work in progress**, and the code it contains is currently alpha-quality code.
27
28 In this documentation, Corona-Warn-App services are also referred to as CWA services.
29
30 ## Architecture Overview
31
32 You can find the architecture overview [here](/docs/architecture-overview.md), which will give you
33 a good starting point in how the backend services interact with other services, and what purpose
34 they serve.
35
36 ## Development
37
38 After you've checked out this repository, you can run the application in one of the following ways:
39
40 * As a [Docker](https://www.docker.com/)-based deployment on your local machine. You can run either:
41 * Single components using the respective Dockerfile or
42 * The full backend using the Docker Compose (which is considered the most convenient way)
43 * As a [Maven](https://maven.apache.org)-based build on your local machine.
44 If you want to develop something in a single component, this approach is preferable.
45
46 ### Docker-Based Deployment
47
48 If you want to use Docker-based deployment, you need to install Docker on your local machine. For more information about downloading and installing Docker, see the [official Docker documentation](https://docs.docker.com/get-docker/).
49
50 #### Running the Full CWA Backend Using Docker Compose
51
52 For your convenience, a full setup including the generation of test data has been prepared using [Docker Compose](https://docs.docker.com/compose/reference/overview/). To build the backend services, run ```docker-compose build``` in the repository's root directory. A default configuration file can be found under ```.env```in the root folder of the repository. The default values for the local Postgres and Zenko Cloudserver should be changed in this file before docker-compose is run.
53
54 Once the services are built, you can start the whole backend using ```docker-compose up```.
55 The distribution service runs once and then finishes. If you want to trigger additional distribution runs, run ```docker-compose run distribution```.
56
57 The docker-compose contains the following services:
58
59 Service | Description | Endpoint and Default Credentials
60 ------------------|-------------|-----------
61 submission | The Corona-Warn-App submission service | `http://localhost:8000` <br> `http://localhost:8006` (for actuator endpoint)
62 distribution | The Corona-Warn-App distribution service | NO ENDPOINT
63 postgres | A [postgres] database installation | `postgres:8001` <br> Username: postgres <br> Password: postgres
64 pgadmin | A [pgadmin](https://www.pgadmin.org/) installation for the postgres database | `http://localhost:8002` <br> Username: [email protected] <br> Password: password
65 cloudserver | [Zenko CloudServer] is a S3-compliant object store | `http://localhost:8003/` <br> Access key: accessKey1 <br> Secret key: verySecretKey1
66 verification-fake | A very simple fake implementation for the tan verification. | `http://localhost:8004/version/v1/tan/verify` <br> The only valid tan is "b69ab69f-9823-4549-8961-c41sa74b2f36"
67
68 ##### Known Limitation
69
70 In rare cases the docker-compose runs into a timing issue if the distribution service starts before the bucket of the objectstore was created. This is not a big issue as you can simply run ```docker-compose run distribution``` to trigger additional distribution runs after the objectstore was initialized.
71
72 #### Running Single CWA Services Using Docker
73
74 If you would like to build and run a single CWA service, it's considered easiest to run them in a Docker environment. You can do this using the script provided in the respective CWA service directory. The Docker script first builds the CWA service and then creates an image for the runtime, which means that there are no additional dependencies for you to install.
75
76 To build and run the distribution service, run the following command:
77
78 ```bash
79 ./services/distribution/build_and_run.sh
80 ```
81
82 To build and run the submission service, run the following command:
83
84 ```bash
85 ./services/submission/build_and_run.sh
86 ```
87
88 The submission service is available on [localhost:8080](http://localhost:8080 ).
89
90 ### Maven-Based Build
91
92 If you want to actively develop in one of the CWA services, the Maven-based runtime is most suitable.
93 To prepare your machine to run the CWA project locally, we recommend that you first ensure that you've installed the following:
94
95 * Minimum JDK Version 11: [OpenJDK](https://openjdk.java.net/) / [SapMachine](https://sap.github.io/SapMachine/)
96 * [Maven 3.6](https://maven.apache.org/)
97 * [Postgres]
98 * [Zenko CloudServer]
99
100 #### Configure
101
102 After you made sure that the specified dependencies are running, configure them in the respective configuration files.
103
104 * Configure the Postgres connection in the [submission config](./services/submission/src/main/resources/application.yaml) and in the [distribution config](./services/distribution/src/main/resources/application.yaml)
105 * Configure the S3 compatible object storage in the [distribution config](./services/distribution/src/main/resources/application.yaml)
106 * Configure the private key for the distribution service, the path need to be prefixed with `file:`
107 * `VAULT_FILESIGNING_SECRET` should be the path to the private key, example available in `<repo-root>/docker-compose-test-secrets/private.pem`
108
109 #### Build
110
111 After you've checked out the repository, to build the project, run ```mvn install``` in your base directory.
112
113 #### Run
114
115 Navigate to the service you want to start and run the spring-boot:run target. The configured Postgres and the configured S3 compliant object storage are used as default. When you start the submission service, the endpoint is available on your local port 8080.
116
117 If you want to start the submission service, for example, you start it as follows:
118
119 ```bash
120 cd services/submission/
121 mvn spring-boot:run
122 ```
123
124 #### Debugging
125
126 To enable the `DEBUG` log level, you can run the application using the Spring `dev` profile.
127
128 ```bash
129 mvn spring-boot:run -Dspring-boot.run.profiles=dev
130 ```
131
132 To be able to set breakpoints (e.g. in IntelliJ), it may be necessary to use the ```-Dspring-boot.run.fork=false``` parameter.
133
134 ## Service APIs
135
136 The API that is being exposed by the backend services is documented in an [OpenAPI](https://www.openapis.org/) specification. The specification files are available at the following locations:
137
138 Service | OpenAPI Specification
139 -------------|-------------
140 Submission Service | [services/submission/api_v1.json](https://github.com/corona-warn-app/cwa-server/raw/master/services/submission/api_v1.json)
141 Distribution Service | [services/distribution/api_v1.json)](https://github.com/corona-warn-app/cwa-server/raw/master/services/distribution/api_v1.json)
142
143 ## Spring Profiles
144
145 ### Distribution
146
147 Profile | Effect
148 -------------|-------------
149 `dev` | Turns the log level to `DEBUG` and sets the app package ID in the export packages' signature info to `de.rki.coronawarnapp-dev` so that test certificates (instead of production certificates) will be used for client-side validation.
150 `cloud` | Removes default values for the `datasource` and `objectstore` configurations.
151 `demo` | Includes incomplete days and hours into the distribution run, thus creating aggregates for the current day and the current hour (and including both in the respective indices). When running multiple distributions in one hour with this profile, the date aggregate for today and the hours aggregate for the current hour will be updated and overwritten.
152 `testdata` | Causes test data to be inserted into the database before each distribution run. By default, around 1000 random diagnosis keys will be generated per hour. If there are no diagnosis keys in the database yet, random keys will be generated for every hour from the beginning of the retention period (14 days ago at 00:00 UTC) until one hour before the present hour. If there are already keys in the database, the random keys will be generated for every hour from the latest diagnosis key in the database (by submission timestamp) until one hour before the present hour (or none at all, if the latest diagnosis key in the database was submitted one hour ago or later).
153
154 ### Submission
155
156 Profile | Effect
157 -------------|-------------
158 `dev` | Turns the log level to `DEBUG`.
159 `cloud` | Removes default values for the `datasource` configuration.
160
161 ## Documentation
162
163 The full documentation for the Corona-Warn-App can be found in the [cwa-documentation](https://github.com/corona-warn-app/cwa-documentation) repository. The documentation repository contains technical documents, architecture information, and whitepapers related to this implementation.
164
165 ## Support and Feedback
166
167 The following channels are available for discussions, feedback, and support requests:
168
169 | Type | Channel |
170 | ------------------------ | ------------------------------------------------------ |
171 | **General Discussion** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="General Discussion"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/question.svg?style=flat-square"></a> </a> |
172 | **Concept Feedback** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="Open Concept Feedback"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/architecture.svg?style=flat-square"></a> |
173 | **Backend Issue** | <a href="https://github.com/corona-warn-app/cwa-server/issues/new/choose" title="Open Backend Issue"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat-square"></a> |
174 | **Other Requests** | <a href="mailto:[email protected]" title="Email CWA Team"><img src="https://img.shields.io/badge/email-CWA%20team-green?logo=mail.ru&style=flat-square&logoColor=white"></a> |
175
176 ## How to Contribute
177
178 Contribution and feedback are 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.
179
180 ## Contributors
181
182 The German government has asked SAP and Deutsche Telekom to develop the Corona-Warn-App for Germany as open source software. Deutsche Telekom is providing the network and mobile technology and will operate and run the backend for the app in a safe, scalable and stable manner. SAP is responsible for the app development, its framework and the underlying platform. Therefore, development teams of SAP and Deutsche Telekom are contributing to this project. At the same time 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.
183
184 ## Repositories
185
186 The following public repositories are currently available for the Corona-Warn-App:
187
188 | Repository | Description |
189 | ------------------- | --------------------------------------------------------------------- |
190 | [cwa-documentation] | Project overview, general documentation, and white papers |
191 | [cwa-server] | Backend implementation for the Apple/Google exposure notification API|
192 | [cwa-verification-server] | Backend implementation of the verification process|
193
194 [cwa-documentation]: https://github.com/corona-warn-app/cwa-documentation
195 [cwa-server]: https://github.com/corona-warn-app/cwa-server
196 [cwa-verification-server]: https://github.com/corona-warn-app/cwa-verification-server
197 [Postgres]: https://www.postgresql.org/
198 [HSQLDB]: http://hsqldb.org/
199 [Zenko CloudServer]: https://github.com/scality/cloudserver
200
201 ## Licensing
202
203 Copyright (c) 2020 SAP SE or an SAP affiliate company.
204
205 Licensed under the **Apache License, Version 2.0** (the "License"); you may not use this file except in compliance with the License.
206
207 You may obtain a copy of the License at <https://www.apache.org/licenses/LICENSE-2.0>.
208
209 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.
210
[end of README.md]
[start of /dev/null]
1
[end of /dev/null]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/ObjectStoreAccess.java]
1 /*
2 * Corona-Warn-App
3 *
4 * SAP SE and all other contributors /
5 * copyright owners license this file to you under the Apache
6 * License, Version 2.0 (the "License"); you may not use this
7 * file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20 package app.coronawarn.server.services.distribution.objectstore;
21
22 import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
23 import app.coronawarn.server.services.distribution.config.DistributionServiceConfig.ObjectStore;
24 import app.coronawarn.server.services.distribution.objectstore.publish.LocalFile;
25 import io.minio.MinioClient;
26 import io.minio.PutObjectOptions;
27 import io.minio.Result;
28 import io.minio.errors.InvalidEndpointException;
29 import io.minio.errors.InvalidPortException;
30 import io.minio.errors.MinioException;
31 import io.minio.messages.DeleteError;
32 import io.minio.messages.Item;
33 import java.io.IOException;
34 import java.security.GeneralSecurityException;
35 import java.util.ArrayList;
36 import java.util.List;
37 import java.util.Map;
38 import java.util.stream.Collectors;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41 import org.springframework.stereotype.Component;
42
43 /**
44 * <p>Grants access to the S3 compatible object storage hosted by Telekom in Germany, enabling
45 * basic functionality for working with files.</p>
46 * <br>
47 * Make sure the following properties are available on the env:
48 * <ul>
49 * <li>services.distribution.objectstore.endpoint</li>
50 * <li>services.distribution.objectstore.bucket</li>
51 * <li>services.distribution.objectstore.accessKey</li>
52 * <li>services.distribution.objectstore.secretKey</li>
53 * <li>services.distribution.objectstore.port</li>
54 * </ul>
55 */
56 @Component
57 public class ObjectStoreAccess {
58
59 private static final Logger logger = LoggerFactory.getLogger(ObjectStoreAccess.class);
60
61 private static final String DEFAULT_REGION = "eu-west-1";
62
63 private final boolean isSetPublicReadAclOnPutObject;
64
65 private final String bucket;
66
67 private final MinioClient client;
68
69 /**
70 * Constructs an {@link ObjectStoreAccess} instance for communication with the specified object store endpoint and
71 * bucket.
72 *
73 * @param distributionServiceConfig The config properties
74 * @throws IOException When there were problems creating the S3 client
75 * @throws GeneralSecurityException When there were problems creating the S3 client
76 * @throws MinioException When there were problems creating the S3 client
77 */
78 ObjectStoreAccess(DistributionServiceConfig distributionServiceConfig)
79 throws IOException, GeneralSecurityException, MinioException {
80 this.client = createClient(distributionServiceConfig.getObjectStore());
81
82 this.bucket = distributionServiceConfig.getObjectStore().getBucket();
83 this.isSetPublicReadAclOnPutObject = distributionServiceConfig.getObjectStore().isSetPublicReadAclOnPutObject();
84
85 if (!this.client.bucketExists(this.bucket)) {
86 throw new IllegalArgumentException("Supplied bucket does not exist " + bucket);
87 }
88 }
89
90 private MinioClient createClient(ObjectStore objectStore)
91 throws InvalidPortException, InvalidEndpointException {
92 if (isSsl(objectStore)) {
93 return new MinioClient(
94 objectStore.getEndpoint(),
95 objectStore.getPort(),
96 objectStore.getAccessKey(), objectStore.getSecretKey(),
97 DEFAULT_REGION,
98 true
99 );
100 } else {
101 return new MinioClient(
102 objectStore.getEndpoint(),
103 objectStore.getPort(),
104 objectStore.getAccessKey(), objectStore.getSecretKey()
105 );
106 }
107 }
108
109 private boolean isSsl(ObjectStore objectStore) {
110 return objectStore.getEndpoint().startsWith("https://");
111 }
112
113 /**
114 * Stores the target file on the S3.
115 *
116 * @param localFile the file to be published
117 */
118 public void putObject(LocalFile localFile)
119 throws IOException, GeneralSecurityException, MinioException {
120 String s3Key = localFile.getS3Key();
121 PutObjectOptions options = createOptionsFor(localFile);
122
123 logger.info("... uploading {}", s3Key);
124 this.client.putObject(bucket, s3Key, localFile.getFile().toString(), options);
125 }
126
127 /**
128 * Deletes objects in the object store, based on the given prefix (folder structure).
129 *
130 * @param prefix the prefix, e.g. my/folder/
131 */
132 public List<DeleteError> deleteObjectsWithPrefix(String prefix)
133 throws MinioException, GeneralSecurityException, IOException {
134 List<String> toDelete = getObjectsWithPrefix(prefix)
135 .stream()
136 .map(S3Object::getObjectName)
137 .collect(Collectors.toList());
138
139 logger.info("Deleting {} entries with prefix {}", toDelete.size(), prefix);
140 var deletionResponse = this.client.removeObjects(bucket, toDelete);
141
142 List<DeleteError> errors = new ArrayList<>();
143 for (Result<DeleteError> deleteErrorResult : deletionResponse) {
144 errors.add(deleteErrorResult.get());
145 }
146
147 logger.info("Deletion result: {}", errors.size());
148
149 return errors;
150 }
151
152 /**
153 * Fetches the list of objects in the store with the given prefix.
154 *
155 * @param prefix the prefix, e.g. my/folder/
156 * @return the list of objects
157 */
158 public List<S3Object> getObjectsWithPrefix(String prefix)
159 throws IOException, GeneralSecurityException, MinioException {
160 var objects = this.client.listObjects(bucket, prefix, true);
161
162 var list = new ArrayList<S3Object>();
163 for (Result<Item> item : objects) {
164 list.add(S3Object.of(item.get()));
165 }
166
167 return list;
168 }
169
170 private PutObjectOptions createOptionsFor(LocalFile file) {
171 var options = new PutObjectOptions(file.getFile().toFile().length(), -1);
172
173 if (this.isSetPublicReadAclOnPutObject) {
174 options.setHeaders(Map.of("x-amz-acl", "public-read"));
175 }
176
177 return options;
178 }
179
180 }
181
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/ObjectStoreAccess.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/RetentionPolicy.java]
1 /*
2 * Corona-Warn-App
3 *
4 * SAP SE and all other contributors /
5 * copyright owners license this file to you under the Apache
6 * License, Version 2.0 (the "License"); you may not use this
7 * file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20 package app.coronawarn.server.services.distribution.runner;
21
22 import app.coronawarn.server.common.persistence.service.DiagnosisKeyService;
23 import app.coronawarn.server.services.distribution.Application;
24 import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
25 import org.slf4j.Logger;
26 import org.slf4j.LoggerFactory;
27 import org.springframework.boot.ApplicationArguments;
28 import org.springframework.boot.ApplicationRunner;
29 import org.springframework.context.ApplicationContext;
30 import org.springframework.core.annotation.Order;
31 import org.springframework.stereotype.Component;
32
33 /**
34 * This runner removes any diagnosis keys from the database that were submitted before a configured threshold of days.
35 */
36 @Component
37 @Order(1)
38 public class RetentionPolicy implements ApplicationRunner {
39
40 private static final Logger logger = LoggerFactory
41 .getLogger(RetentionPolicy.class);
42
43 private final DiagnosisKeyService diagnosisKeyService;
44
45 private final ApplicationContext applicationContext;
46
47 private final Integer retentionDays;
48
49 /**
50 * Creates a new RetentionPolicy.
51 */
52 RetentionPolicy(DiagnosisKeyService diagnosisKeyService,
53 ApplicationContext applicationContext,
54 DistributionServiceConfig distributionServiceConfig) {
55 this.diagnosisKeyService = diagnosisKeyService;
56 this.applicationContext = applicationContext;
57 this.retentionDays = distributionServiceConfig.getRetentionDays();
58 }
59
60 @Override
61 public void run(ApplicationArguments args) {
62 try {
63 diagnosisKeyService.applyRetentionPolicy(retentionDays);
64 } catch (Exception e) {
65 logger.error("Application of retention policy failed.", e);
66 Application.killApplication(applicationContext);
67 }
68
69 logger.debug("Retention policy applied successfully. Deleted all entries older that {} days.",
70 retentionDays);
71 }
72 }
73
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/RetentionPolicy.java]
</code>
Here is an example of a patch file. It consists of changes to the code base. It specifies the file names, the line numbers of each change, and the removed and added lines. A single patch file can contain changes to multiple files.
<patch>
--- a/file.py
+++ b/file.py
@@ -1,27 +1,35 @@
def euclidean(a, b):
- while b:
- a, b = b, a % b
- return a
+ if b == 0:
+ return a
+ return euclidean(b, a % b)
def bresenham(x0, y0, x1, y1):
points = []
dx = abs(x1 - x0)
dy = abs(y1 - y0)
- sx = 1 if x0 < x1 else -1
- sy = 1 if y0 < y1 else -1
- err = dx - dy
+ x, y = x0, y0
+ sx = -1 if x0 > x1 else 1
+ sy = -1 if y0 > y1 else 1
- while True:
- points.append((x0, y0))
- if x0 == x1 and y0 == y1:
- break
- e2 = 2 * err
- if e2 > -dy:
+ if dx > dy:
+ err = dx / 2.0
+ while x != x1:
+ points.append((x, y))
err -= dy
- x0 += sx
- if e2 < dx:
- err += dx
- y0 += sy
+ if err < 0:
+ y += sy
+ err += dx
+ x += sx
+ else:
+ err = dy / 2.0
+ while y != y1:
+ points.append((x, y))
+ err -= dx
+ if err < 0:
+ x += sx
+ err += dy
+ y += sy
+ points.append((x, y))
return points
</patch>
I need you to solve the provded issue by generating a single patch file that I can apply directly to this repository using git apply. Please respond with a single patch file in the format shown above.
Respond below:
| corona-warn-app/cwa-server | 92f3c9bd98420cd26c4216cace3e481874be6140 | Retention: Enforce period on Object Store
Currently, the retention period is only enforced for keys on the database, but it should be enforced on the S3 as well.
Therefore, we need to delete the items on the S3, when the retention policy is reached.
When the retention mechanism is kicked off, and then delete the following keys with the prefix:
`version/v1/diagnosis-keys/country/DE/date/<RETENTIONDATE>`
Where RETENTIONDATE is `current date - retention period`.
Ideally, we should also try to delete older items as well, in case the retention run did not succeed or did not run at all.
| I propose to just remove the "delta upload" feature from the S3Publisher (see [here](https://github.com/corona-warn-app/cwa-server/blob/master/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/S3Publisher.java#L75)) and instead just wipe the whole bucket on every distribution run and to upload everything anew. This way, the only place where retention policies need to be applied is the DB as a single source of truth (which is already done) and we remove some moving parts and complexity that could potentially cause problems. Also see review comment [here](https://github.com/corona-warn-app/cwa-server/pull/147#discussion_r426311639). | 2020-05-27T15:03:01 | <patch>
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/ObjectStoreAccess.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/ObjectStoreAccess.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/ObjectStoreAccess.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/ObjectStoreAccess.java
@@ -129,7 +129,7 @@ public void putObject(LocalFile localFile)
*
* @param prefix the prefix, e.g. my/folder/
*/
- public List<DeleteError> deleteObjectsWithPrefix(String prefix)
+ public void deleteObjectsWithPrefix(String prefix)
throws MinioException, GeneralSecurityException, IOException {
List<String> toDelete = getObjectsWithPrefix(prefix)
.stream()
@@ -144,9 +144,9 @@ public List<DeleteError> deleteObjectsWithPrefix(String prefix)
errors.add(deleteErrorResult.get());
}
- logger.info("Deletion result: {}", errors.size());
-
- return errors;
+ if (!errors.isEmpty()) {
+ throw new MinioException("Can't delete files, number of errors: " + errors.size());
+ }
}
/**
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/S3RetentionPolicy.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/S3RetentionPolicy.java
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/S3RetentionPolicy.java
@@ -0,0 +1,90 @@
+/*
+ * Corona-Warn-App
+ *
+ * SAP SE and all other contributors /
+ * copyright owners license this file to you under the Apache
+ * License, Version 2.0 (the "License"); you may not use this
+ * file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://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 for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package app.coronawarn.server.services.distribution.objectstore;
+
+import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
+import app.coronawarn.server.services.distribution.config.DistributionServiceConfig.Api;
+import io.minio.errors.MinioException;
+import java.io.IOException;
+import java.io.UncheckedIOException;
+import java.security.GeneralSecurityException;
+import java.time.LocalDate;
+import java.time.ZoneOffset;
+import java.time.format.DateTimeFormatter;
+import java.util.List;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+/**
+ * Creates an S3RetentionPolicy object, which applies the retention policy to the S3 compatible storage.
+ */
+@Component
+public class S3RetentionPolicy {
+
+ private final ObjectStoreAccess objectStoreAccess;
+ private final Api api;
+
+ @Autowired
+ public S3RetentionPolicy(ObjectStoreAccess objectStoreAccess, DistributionServiceConfig distributionServiceConfig) {
+ this.objectStoreAccess = objectStoreAccess;
+ this.api = distributionServiceConfig.getApi();
+ }
+
+ /**
+ * Deletes all diagnosis-key files from S3 that are older than retentionDays.
+ *
+ * @param retentionDays the number of days, that files should be retained on S3.
+ */
+ public void applyRetentionPolicy(int retentionDays) throws MinioException, GeneralSecurityException, IOException {
+ List<S3Object> diagnosisKeysObjects = objectStoreAccess.getObjectsWithPrefix("version/v1/"
+ + api.getDiagnosisKeysPath() + "/"
+ + api.getCountryPath() + "/"
+ + api.getCountryGermany() + "/"
+ + api.getDatePath() + "/");
+ final String regex = ".*([0-9]{4}-[0-9]{2}-[0-9]{2}).*";
+ final Pattern pattern = Pattern.compile(regex);
+
+ final LocalDate cutOffDate = LocalDate.now(ZoneOffset.UTC).minusDays(retentionDays);
+
+ diagnosisKeysObjects.stream()
+ .filter(diagnosisKeysObject -> {
+ Matcher matcher = pattern.matcher(diagnosisKeysObject.getObjectName());
+ return matcher.matches() && LocalDate.parse(matcher.group(1), DateTimeFormatter.ISO_LOCAL_DATE)
+ .isBefore(cutOffDate);
+ })
+ .forEach(this::deleteDiagnosisKey);
+ }
+
+ /**
+ * Java stream do not support checked exceptions within streams. This helper method rethrows them as unchecked
+ * expressions, so they can be passed up to the Retention Policy.
+ *
+ * @param diagnosisKey the diagnosis key, that should be deleted.
+ */
+ public void deleteDiagnosisKey(S3Object diagnosisKey) {
+ try {
+ objectStoreAccess.deleteObjectsWithPrefix(diagnosisKey.getObjectName());
+ } catch (Exception e) {
+ throw new UncheckedIOException(new IOException(e));
+ }
+ }
+}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/RetentionPolicy.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/RetentionPolicy.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/RetentionPolicy.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/RetentionPolicy.java
@@ -22,6 +22,7 @@
import app.coronawarn.server.common.persistence.service.DiagnosisKeyService;
import app.coronawarn.server.services.distribution.Application;
import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
+import app.coronawarn.server.services.distribution.objectstore.S3RetentionPolicy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.ApplicationArguments;
@@ -46,27 +47,32 @@ public class RetentionPolicy implements ApplicationRunner {
private final Integer retentionDays;
+ private final S3RetentionPolicy s3RetentionPolicy;
+
/**
* Creates a new RetentionPolicy.
*/
RetentionPolicy(DiagnosisKeyService diagnosisKeyService,
ApplicationContext applicationContext,
- DistributionServiceConfig distributionServiceConfig) {
+ DistributionServiceConfig distributionServiceConfig,
+ S3RetentionPolicy s3RetentionPolicy) {
this.diagnosisKeyService = diagnosisKeyService;
this.applicationContext = applicationContext;
this.retentionDays = distributionServiceConfig.getRetentionDays();
+ this.s3RetentionPolicy = s3RetentionPolicy;
}
@Override
public void run(ApplicationArguments args) {
try {
diagnosisKeyService.applyRetentionPolicy(retentionDays);
+ s3RetentionPolicy.applyRetentionPolicy(retentionDays);
} catch (Exception e) {
logger.error("Application of retention policy failed.", e);
Application.killApplication(applicationContext);
}
- logger.debug("Retention policy applied successfully. Deleted all entries older that {} days.",
+ logger.debug("Retention policy applied successfully. Deleted all entries older than {} days.",
retentionDays);
}
}
</patch> | diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/S3RetentionPolicyTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/S3RetentionPolicyTest.java
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/S3RetentionPolicyTest.java
@@ -0,0 +1,92 @@
+/*
+ * Corona-Warn-App
+ *
+ * SAP SE and all other contributors /
+ * copyright owners license this file to you under the Apache
+ * License, Version 2.0 (the "License"); you may not use this
+ * file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://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 for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package app.coronawarn.server.services.distribution.objectstore;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.atLeastOnce;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
+import app.coronawarn.server.services.distribution.config.DistributionServiceConfig.ObjectStore;
+import io.minio.errors.MinioException;
+import java.io.IOException;
+import java.security.GeneralSecurityException;
+import java.time.LocalDate;
+import java.util.List;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.context.properties.EnableConfigurationProperties;
+import org.springframework.boot.test.context.ConfigFileApplicationContextInitializer;
+import org.springframework.boot.test.mock.mockito.MockBean;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit.jupiter.SpringExtension;
+
+@EnableConfigurationProperties(value = DistributionServiceConfig.class)
+@ExtendWith(SpringExtension.class)
+@ContextConfiguration(classes = {S3RetentionPolicy.class, ObjectStore.class},
+ initializers = ConfigFileApplicationContextInitializer.class)
+class S3RetentionPolicyTest {
+
+ @MockBean
+ private ObjectStoreAccess objectStoreAccess;
+
+ @Autowired
+ private S3RetentionPolicy s3RetentionPolicy;
+
+ @Autowired DistributionServiceConfig distributionServiceConfig;
+
+ @Test
+ void shouldDeleteOldFiles() throws IOException, GeneralSecurityException, MinioException {
+ String expectedFileToBeDeleted = generateFileName(LocalDate.now().minusDays(2));
+
+ when(objectStoreAccess.getObjectsWithPrefix(any())).thenReturn(List.of(
+ new S3Object(expectedFileToBeDeleted),
+ new S3Object(generateFileName(LocalDate.now())),
+ new S3Object("version/v1/configuration/country/DE/app_config")));
+
+ s3RetentionPolicy.applyRetentionPolicy(1);
+
+ verify(objectStoreAccess, atLeastOnce()).deleteObjectsWithPrefix(eq(expectedFileToBeDeleted));
+ }
+
+ @Test
+ void shouldNotDeleteFilesIfAllAreValid() throws IOException, GeneralSecurityException, MinioException {
+ when(objectStoreAccess.getObjectsWithPrefix(any())).thenReturn(List.of(
+ new S3Object(generateFileName(LocalDate.now().minusDays(1))),
+ new S3Object(generateFileName(LocalDate.now().plusDays(1))),
+ new S3Object(generateFileName(LocalDate.now())),
+ new S3Object("version/v1/configuration/country/DE/app_config")));
+
+ s3RetentionPolicy.applyRetentionPolicy(1);
+
+ verify(objectStoreAccess, never()).deleteObjectsWithPrefix(any());
+ }
+
+ private String generateFileName(LocalDate date) {
+ var api = distributionServiceConfig.getApi();
+
+ return "version/v1/" + api.getDiagnosisKeysPath() + "/" + api.getCountryPath() + "/"
+ + api.getCountryGermany() + "/" + api.getDatePath() + "/" + date.toString() + "/hour/0";
+ }
+}
| ||||
corona-warn-app__cwa-server-466 | You will be provided with a partial code base and an issue statement explaining a problem to resolve.
<issue>
S3Publisher: Increase performance
The S3Publisher is currently running in only one thread, making it quite slow for uploads/requests for metadata.
Enhance the S3Publisher/ObjectStoreAccess, so that multiple threads are being used for interacting with S3.
</issue>
<code>
[start of README.md]
1 <!-- markdownlint-disable MD041 -->
2 <h1 align="center">
3 Corona-Warn-App Server
4 </h1>
5
6 <p align="center">
7 <a href="https://github.com/corona-warn-app/cwa-server/commits/" title="Last Commit"><img src="https://img.shields.io/github/last-commit/corona-warn-app/cwa-server?style=flat"></a>
8 <a href="https://github.com/corona-warn-app/cwa-server/issues" title="Open Issues"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat"></a>
9 <a href="https://circleci.com/gh/corona-warn-app/cwa-server" title="Build Status"><img src="https://circleci.com/gh/corona-warn-app/cwa-server.svg?style=shield&circle-token=4ab059989d10709df19eb4b98ab7c121a25e981a"></a>
10 <a href="https://sonarcloud.io/dashboard?id=corona-warn-app_cwa-server" title="Quality Gate"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=alert_status"></a>
11 <a href="https://sonarcloud.io/component_measures?id=corona-warn-app_cwa-server&metric=Coverage&view=list" title="Coverage"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=coverage"></a>
12 <a href="https://github.com/corona-warn-app/cwa-server/blob/master/LICENSE" title="License"><img src="https://img.shields.io/badge/License-Apache%202.0-green.svg?style=flat"></a>
13 </p>
14
15 <p align="center">
16 <a href="#development">Development</a> •
17 <a href="#service-apis">Service APIs</a> •
18 <a href="#documentation">Documentation</a> •
19 <a href="#support-and-feedback">Support</a> •
20 <a href="#how-to-contribute">Contribute</a> •
21 <a href="#contributors">Contributors</a> •
22 <a href="#repositories">Repositories</a> •
23 <a href="#licensing">Licensing</a>
24 </p>
25
26 The goal of this project is to develop the official Corona-Warn-App for Germany based on the exposure notification API from [Apple](https://www.apple.com/covid19/contacttracing/) and [Google](https://www.google.com/covid19/exposurenotifications/). The apps (for both iOS and Android) use Bluetooth technology to exchange anonymous encrypted data with other mobile phones (on which the app is also installed) in the vicinity of an app user's phone. The data is stored locally on each user's device, preventing authorities or other parties from accessing or controlling the data. This repository contains the **implementation of the server for encryption keys** for the Corona-Warn-App. This implementation is still a **work in progress**, and the code it contains is currently alpha-quality code.
27
28 In this documentation, Corona-Warn-App services are also referred to as CWA services.
29
30 ## Architecture Overview
31
32 You can find the architecture overview [here](/docs/architecture-overview.md), which will give you
33 a good starting point in how the backend services interact with other services, and what purpose
34 they serve.
35
36 ## Development
37
38 After you've checked out this repository, you can run the application in one of the following ways:
39
40 * As a [Docker](https://www.docker.com/)-based deployment on your local machine. You can run either:
41 * Single components using the respective Dockerfile or
42 * The full backend using the Docker Compose (which is considered the most convenient way)
43 * As a [Maven](https://maven.apache.org)-based build on your local machine.
44 If you want to develop something in a single component, this approach is preferable.
45
46 ### Docker-Based Deployment
47
48 If you want to use Docker-based deployment, you need to install Docker on your local machine. For more information about downloading and installing Docker, see the [official Docker documentation](https://docs.docker.com/get-docker/).
49
50 #### Running the Full CWA Backend Using Docker Compose
51
52 For your convenience, a full setup including the generation of test data has been prepared using [Docker Compose](https://docs.docker.com/compose/reference/overview/). To build the backend services, run ```docker-compose build``` in the repository's root directory. A default configuration file can be found under ```.env``` in the root folder of the repository. The default values for the local Postgres and Zenko Cloudserver should be changed in this file before docker-compose is run.
53
54 Once the services are built, you can start the whole backend using ```docker-compose up```.
55 The distribution service runs once and then finishes. If you want to trigger additional distribution runs, run ```docker-compose run distribution```.
56
57 The docker-compose contains the following services:
58
59 Service | Description | Endpoint and Default Credentials
60 ------------------|-------------|-----------
61 submission | The Corona-Warn-App submission service | `http://localhost:8000` <br> `http://localhost:8006` (for actuator endpoint)
62 distribution | The Corona-Warn-App distribution service | NO ENDPOINT
63 postgres | A [postgres] database installation | `localhost:8001` <br> `postgres:5432` (from containerized pgadmin) <br> Username: postgres <br> Password: postgres
64 pgadmin | A [pgadmin](https://www.pgadmin.org/) installation for the postgres database | `http://localhost:8002` <br> Username: [email protected] <br> Password: password
65 cloudserver | [Zenko CloudServer] is a S3-compliant object store | `http://localhost:8003/` <br> Access key: accessKey1 <br> Secret key: verySecretKey1
66 verification-fake | A very simple fake implementation for the tan verification. | `http://localhost:8004/version/v1/tan/verify` <br> The only valid tan is `edc07f08-a1aa-11ea-bb37-0242ac130002`.
67
68 ##### Known Limitation
69
70 In rare cases the docker-compose runs into a timing issue if the distribution service starts before the bucket of the objectstore was created. This is not a big issue as you can simply run ```docker-compose run distribution``` to trigger additional distribution runs after the objectstore was initialized.
71
72 #### Running Single CWA Services Using Docker
73
74 If you would like to build and run a single CWA service, it's considered easiest to run them in a Docker environment. You can do this using the script provided in the respective CWA service directory. The Docker script first builds the CWA service and then creates an image for the runtime, which means that there are no additional dependencies for you to install.
75
76 To build and run the distribution service, run the following command:
77
78 ```bash
79 ./services/distribution/build_and_run.sh
80 ```
81
82 To build and run the submission service, run the following command:
83
84 ```bash
85 ./services/submission/build_and_run.sh
86 ```
87
88 The submission service is available on [localhost:8080](http://localhost:8080 ).
89
90 ### Maven-Based Build
91
92 If you want to actively develop in one of the CWA services, the Maven-based runtime is most suitable.
93 To prepare your machine to run the CWA project locally, we recommend that you first ensure that you've installed the following:
94
95 * Minimum JDK Version 11: [OpenJDK](https://openjdk.java.net/) / [SapMachine](https://sap.github.io/SapMachine/)
96 * [Maven 3.6](https://maven.apache.org/)
97 * [Postgres]
98 * [Zenko CloudServer]
99
100 #### Configure
101
102 After you made sure that the specified dependencies are running, configure them in the respective configuration files.
103
104 * Configure the Postgres connection in the [submission config](./services/submission/src/main/resources/application.yaml) and in the [distribution config](./services/distribution/src/main/resources/application.yaml)
105 * Configure the S3 compatible object storage in the [distribution config](./services/distribution/src/main/resources/application.yaml)
106 * Configure the private key for the distribution service, the path need to be prefixed with `file:`
107 * `VAULT_FILESIGNING_SECRET` should be the path to the private key, example available in `<repo-root>/docker-compose-test-secrets/private.pem`
108
109 #### Build
110
111 After you've checked out the repository, to build the project, run ```mvn install``` in your base directory.
112
113 #### Run
114
115 Navigate to the service you want to start and run the spring-boot:run target. The configured Postgres and the configured S3 compliant object storage are used as default. When you start the submission service, the endpoint is available on your local port 8080.
116
117 If you want to start the submission service, for example, you start it as follows:
118
119 ```bash
120 cd services/submission/
121 mvn spring-boot:run
122 ```
123
124 #### Debugging
125
126 To enable the `DEBUG` log level, you can run the application using the Spring `dev` profile.
127
128 ```bash
129 mvn spring-boot:run -Dspring-boot.run.profiles=dev
130 ```
131
132 To be able to set breakpoints (e.g. in IntelliJ), it may be necessary to use the ```-Dspring-boot.run.fork=false``` parameter.
133
134 ## Service APIs
135
136 The API that is being exposed by the backend services is documented in an [OpenAPI](https://www.openapis.org/) specification. The specification files are available at the following locations:
137
138 Service | OpenAPI Specification
139 -------------|-------------
140 Submission Service | [services/submission/api_v1.json](https://github.com/corona-warn-app/cwa-server/raw/master/services/submission/api_v1.json)
141 Distribution Service | [services/distribution/api_v1.json](https://github.com/corona-warn-app/cwa-server/raw/master/services/distribution/api_v1.json)
142
143 ## Spring Profiles
144
145 ### Distribution
146
147 Profile | Effect
148 ----------------------|-------------
149 `dev` | Turns the log level to `DEBUG`.
150 `cloud` | Removes default values for the `datasource` and `objectstore` configurations.
151 `demo` | Includes incomplete days and hours into the distribution run, thus creating aggregates for the current day and the current hour (and including both in the respective indices). When running multiple distributions in one hour with this profile, the date aggregate for today and the hours aggregate for the current hour will be updated and overwritten. This profile also turns off the expiry policy (Keys must be expired for at least 2 hours before distribution) and the shifting policy (there must be at least 140 keys in a distribution).
152 `testdata` | Causes test data to be inserted into the database before each distribution run. By default, around 1000 random diagnosis keys will be generated per hour. If there are no diagnosis keys in the database yet, random keys will be generated for every hour from the beginning of the retention period (14 days ago at 00:00 UTC) until one hour before the present hour. If there are already keys in the database, the random keys will be generated for every hour from the latest diagnosis key in the database (by submission timestamp) until one hour before the present hour (or none at all, if the latest diagnosis key in the database was submitted one hour ago or later).
153 `signature-dev` | Sets the app package ID in the export packages' signature info to `de.rki.coronawarnapp-dev` so that the non-productive/test public key will be used for client-side validation.
154 `signature-prod` | Sets the app package ID in the export packages' signature info to `de.rki.coronawarnapp` so that the productive public key will be used for client-side validation.
155 `ssl-client-postgres` | Enforces SSL with a pinned certificate for the connection to the postgres (see [here](https://github.com/corona-warn-app/cwa-server/blob/master/services/distribution/src/main/resources/application-ssl-client-postgres.yaml)).
156
157 ### Submission
158
159 Profile | Effect
160 --------------------------|-------------
161 `dev` | Turns the log level to `DEBUG`.
162 `cloud` | Removes default values for the `datasource` configuration.
163 `ssl-server` | Enables SSL for the submission endpoint (see [here](https://github.com/corona-warn-app/cwa-server/blob/master/services/submission/src/main/resources/application-ssl-server.yaml)).
164 `ssl-client-postgres` | Enforces SSL with a pinned certificate for the connection to the postgres (see [here](https://github.com/corona-warn-app/cwa-server/blob/master/services/submission/src/main/resources/application-ssl-client-postgres.yaml)).
165 `ssl-client-verification` | Enforces SSL with a pinned certificate for the connection to the verification server (see [here](https://github.com/corona-warn-app/cwa-server/blob/master/services/submission/src/main/resources/application-ssl-client-verification.yaml)).
166
167 ## Documentation
168
169 The full documentation for the Corona-Warn-App can be found in the [cwa-documentation](https://github.com/corona-warn-app/cwa-documentation) repository. The documentation repository contains technical documents, architecture information, and whitepapers related to this implementation.
170
171 ## Support and Feedback
172
173 The following channels are available for discussions, feedback, and support requests:
174
175 | Type | Channel |
176 | ------------------------ | ------------------------------------------------------ |
177 | **General Discussion** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="General Discussion"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/question.svg?style=flat-square"></a> </a> |
178 | **Concept Feedback** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="Open Concept Feedback"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/architecture.svg?style=flat-square"></a> |
179 | **Backend Issue** | <a href="https://github.com/corona-warn-app/cwa-server/issues/new/choose" title="Open Backend Issue"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat-square"></a> |
180 | **Other Requests** | <a href="mailto:[email protected]" title="Email CWA Team"><img src="https://img.shields.io/badge/email-CWA%20team-green?logo=mail.ru&style=flat-square&logoColor=white"></a> |
181
182 ## How to Contribute
183
184 Contribution and feedback are 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.
185
186 ## Contributors
187
188 The German government has asked SAP and Deutsche Telekom to develop the Corona-Warn-App for Germany as open source software. Deutsche Telekom is providing the network and mobile technology and will operate and run the backend for the app in a safe, scalable and stable manner. SAP is responsible for the app development, its framework and the underlying platform. Therefore, development teams of SAP and Deutsche Telekom are contributing to this project. At the same time 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.
189
190 ## Repositories
191
192 The following public repositories are currently available for the Corona-Warn-App:
193
194 | Repository | Description |
195 | ------------------- | --------------------------------------------------------------------- |
196 | [cwa-documentation] | Project overview, general documentation, and white papers |
197 | [cwa-server] | Backend implementation for the Apple/Google exposure notification API|
198 | [cwa-verification-server] | Backend implementation of the verification process|
199
200 [cwa-documentation]: https://github.com/corona-warn-app/cwa-documentation
201 [cwa-server]: https://github.com/corona-warn-app/cwa-server
202 [cwa-verification-server]: https://github.com/corona-warn-app/cwa-verification-server
203 [Postgres]: https://www.postgresql.org/
204 [HSQLDB]: http://hsqldb.org/
205 [Zenko CloudServer]: https://github.com/scality/cloudserver
206
207 ## Licensing
208
209 Copyright (c) 2020 SAP SE or an SAP affiliate company.
210
211 Licensed under the **Apache License, Version 2.0** (the "License"); you may not use this file except in compliance with the License.
212
213 You may obtain a copy of the License at <https://www.apache.org/licenses/LICENSE-2.0>.
214
215 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.
216
[end of README.md]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/config/DistributionServiceConfig.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.distribution.config;
22
23 import app.coronawarn.server.common.protocols.external.exposurenotification.SignatureInfo;
24 import org.springframework.boot.context.properties.ConfigurationProperties;
25 import org.springframework.stereotype.Component;
26
27 @Component
28 @ConfigurationProperties(prefix = "services.distribution")
29 public class DistributionServiceConfig {
30
31 private Paths paths;
32 private TestData testData;
33 private Integer retentionDays;
34 private Integer expiryPolicyMinutes;
35 private Integer shiftingPolicyThreshold;
36 private Integer maximumNumberOfKeysPerBundle;
37 private String outputFileName;
38 private Boolean includeIncompleteDays;
39 private Boolean includeIncompleteHours;
40 private TekExport tekExport;
41 private Signature signature;
42 private Api api;
43 private ObjectStore objectStore;
44
45 public Paths getPaths() {
46 return paths;
47 }
48
49 public void setPaths(Paths paths) {
50 this.paths = paths;
51 }
52
53 public TestData getTestData() {
54 return testData;
55 }
56
57 public void setTestData(TestData testData) {
58 this.testData = testData;
59 }
60
61 public Integer getRetentionDays() {
62 return retentionDays;
63 }
64
65 public void setRetentionDays(Integer retentionDays) {
66 this.retentionDays = retentionDays;
67 }
68
69 public Integer getExpiryPolicyMinutes() {
70 return expiryPolicyMinutes;
71 }
72
73 public void setExpiryPolicyMinutes(Integer expiryPolicyMinutes) {
74 this.expiryPolicyMinutes = expiryPolicyMinutes;
75 }
76
77 public Integer getShiftingPolicyThreshold() {
78 return shiftingPolicyThreshold;
79 }
80
81 public void setShiftingPolicyThreshold(Integer shiftingPolicyThreshold) {
82 this.shiftingPolicyThreshold = shiftingPolicyThreshold;
83 }
84
85 public Integer getMaximumNumberOfKeysPerBundle() {
86 return this.maximumNumberOfKeysPerBundle;
87 }
88
89 public void setMaximumNumberOfKeysPerBundle(Integer maximumNumberOfKeysPerBundle) {
90 this.maximumNumberOfKeysPerBundle = maximumNumberOfKeysPerBundle;
91 }
92
93 public String getOutputFileName() {
94 return outputFileName;
95 }
96
97 public void setOutputFileName(String outputFileName) {
98 this.outputFileName = outputFileName;
99 }
100
101 public Boolean getIncludeIncompleteDays() {
102 return includeIncompleteDays;
103 }
104
105 public void setIncludeIncompleteDays(Boolean includeIncompleteDays) {
106 this.includeIncompleteDays = includeIncompleteDays;
107 }
108
109 public Boolean getIncludeIncompleteHours() {
110 return includeIncompleteHours;
111 }
112
113 public void setIncludeIncompleteHours(Boolean includeIncompleteHours) {
114 this.includeIncompleteHours = includeIncompleteHours;
115 }
116
117 public TekExport getTekExport() {
118 return tekExport;
119 }
120
121 public void setTekExport(TekExport tekExport) {
122 this.tekExport = tekExport;
123 }
124
125 public Signature getSignature() {
126 return signature;
127 }
128
129 public void setSignature(Signature signature) {
130 this.signature = signature;
131 }
132
133 public Api getApi() {
134 return api;
135 }
136
137 public void setApi(Api api) {
138 this.api = api;
139 }
140
141 public ObjectStore getObjectStore() {
142 return objectStore;
143 }
144
145 public void setObjectStore(
146 ObjectStore objectStore) {
147 this.objectStore = objectStore;
148 }
149
150 public static class TekExport {
151
152 private String fileName;
153 private String fileHeader;
154 private Integer fileHeaderWidth;
155
156 public String getFileName() {
157 return fileName;
158 }
159
160 public void setFileName(String fileName) {
161 this.fileName = fileName;
162 }
163
164 public String getFileHeader() {
165 return fileHeader;
166 }
167
168 public void setFileHeader(String fileHeader) {
169 this.fileHeader = fileHeader;
170 }
171
172 public Integer getFileHeaderWidth() {
173 return fileHeaderWidth;
174 }
175
176 public void setFileHeaderWidth(Integer fileHeaderWidth) {
177 this.fileHeaderWidth = fileHeaderWidth;
178 }
179 }
180
181 public static class TestData {
182
183 private Integer seed;
184 private Integer exposuresPerHour;
185
186 public Integer getSeed() {
187 return seed;
188 }
189
190 public void setSeed(Integer seed) {
191 this.seed = seed;
192 }
193
194 public Integer getExposuresPerHour() {
195 return exposuresPerHour;
196 }
197
198 public void setExposuresPerHour(Integer exposuresPerHour) {
199 this.exposuresPerHour = exposuresPerHour;
200 }
201 }
202
203 public static class Paths {
204
205 private String privateKey;
206 private String output;
207
208 public String getPrivateKey() {
209 return privateKey;
210 }
211
212 public void setPrivateKey(String privateKey) {
213 this.privateKey = privateKey;
214 }
215
216 public String getOutput() {
217 return output;
218 }
219
220 public void setOutput(String output) {
221 this.output = output;
222 }
223 }
224
225 public static class Api {
226
227 private String versionPath;
228 private String versionV1;
229 private String countryPath;
230 private String countryGermany;
231 private String datePath;
232 private String hourPath;
233 private String diagnosisKeysPath;
234 private String parametersPath;
235 private String appConfigFileName;
236
237 public String getVersionPath() {
238 return versionPath;
239 }
240
241 public void setVersionPath(String versionPath) {
242 this.versionPath = versionPath;
243 }
244
245 public String getVersionV1() {
246 return versionV1;
247 }
248
249 public void setVersionV1(String versionV1) {
250 this.versionV1 = versionV1;
251 }
252
253 public String getCountryPath() {
254 return countryPath;
255 }
256
257 public void setCountryPath(String countryPath) {
258 this.countryPath = countryPath;
259 }
260
261 public String getCountryGermany() {
262 return countryGermany;
263 }
264
265 public void setCountryGermany(String countryGermany) {
266 this.countryGermany = countryGermany;
267 }
268
269 public String getDatePath() {
270 return datePath;
271 }
272
273 public void setDatePath(String datePath) {
274 this.datePath = datePath;
275 }
276
277 public String getHourPath() {
278 return hourPath;
279 }
280
281 public void setHourPath(String hourPath) {
282 this.hourPath = hourPath;
283 }
284
285 public String getDiagnosisKeysPath() {
286 return diagnosisKeysPath;
287 }
288
289 public void setDiagnosisKeysPath(String diagnosisKeysPath) {
290 this.diagnosisKeysPath = diagnosisKeysPath;
291 }
292
293 public String getParametersPath() {
294 return parametersPath;
295 }
296
297 public void setParametersPath(String parametersPath) {
298 this.parametersPath = parametersPath;
299 }
300
301 public String getAppConfigFileName() {
302 return appConfigFileName;
303 }
304
305 public void setAppConfigFileName(String appConfigFileName) {
306 this.appConfigFileName = appConfigFileName;
307 }
308 }
309
310 public static class Signature {
311
312 private String appBundleId;
313 private String androidPackage;
314 private String verificationKeyId;
315 private String verificationKeyVersion;
316 private String algorithmOid;
317 private String algorithmName;
318 private String fileName;
319 private String securityProvider;
320
321 public String getAppBundleId() {
322 return appBundleId;
323 }
324
325 public void setAppBundleId(String appBundleId) {
326 this.appBundleId = appBundleId;
327 }
328
329 public String getAndroidPackage() {
330 return androidPackage;
331 }
332
333 public void setAndroidPackage(String androidPackage) {
334 this.androidPackage = androidPackage;
335 }
336
337 public String getVerificationKeyId() {
338 return verificationKeyId;
339 }
340
341 public void setVerificationKeyId(String verificationKeyId) {
342 this.verificationKeyId = verificationKeyId;
343 }
344
345 public String getVerificationKeyVersion() {
346 return verificationKeyVersion;
347 }
348
349 public void setVerificationKeyVersion(String verificationKeyVersion) {
350 this.verificationKeyVersion = verificationKeyVersion;
351 }
352
353 public String getAlgorithmOid() {
354 return algorithmOid;
355 }
356
357 public void setAlgorithmOid(String algorithmOid) {
358 this.algorithmOid = algorithmOid;
359 }
360
361 public String getAlgorithmName() {
362 return algorithmName;
363 }
364
365 public void setAlgorithmName(String algorithmName) {
366 this.algorithmName = algorithmName;
367 }
368
369 public String getFileName() {
370 return fileName;
371 }
372
373 public void setFileName(String fileName) {
374 this.fileName = fileName;
375 }
376
377 public String getSecurityProvider() {
378 return securityProvider;
379 }
380
381 public void setSecurityProvider(String securityProvider) {
382 this.securityProvider = securityProvider;
383 }
384
385 /**
386 * Returns the static {@link SignatureInfo} configured in the application properties.
387 */
388 public SignatureInfo getSignatureInfo() {
389 return SignatureInfo.newBuilder()
390 .setAppBundleId(this.getAppBundleId())
391 .setVerificationKeyVersion(this.getVerificationKeyVersion())
392 .setVerificationKeyId(this.getVerificationKeyId())
393 .setSignatureAlgorithm(this.getAlgorithmOid())
394 .build();
395 }
396 }
397
398 public static class ObjectStore {
399
400 private String accessKey;
401 private String secretKey;
402 private String endpoint;
403 private Integer port;
404 private String bucket;
405 private Boolean setPublicReadAclOnPutObject;
406 private Integer maxNumberOfFailedOperations;
407
408 public String getAccessKey() {
409 return accessKey;
410 }
411
412 public void setAccessKey(String accessKey) {
413 this.accessKey = accessKey;
414 }
415
416 public String getSecretKey() {
417 return secretKey;
418 }
419
420 public void setSecretKey(String secretKey) {
421 this.secretKey = secretKey;
422 }
423
424 public String getEndpoint() {
425 return endpoint;
426 }
427
428 public void setEndpoint(String endpoint) {
429 this.endpoint = endpoint;
430 }
431
432 public Integer getPort() {
433 return port;
434 }
435
436 public void setPort(Integer port) {
437 this.port = port;
438 }
439
440 public String getBucket() {
441 return bucket;
442 }
443
444 public void setBucket(String bucket) {
445 this.bucket = bucket;
446 }
447
448 public Boolean isSetPublicReadAclOnPutObject() {
449 return setPublicReadAclOnPutObject;
450 }
451
452 public void setSetPublicReadAclOnPutObject(Boolean setPublicReadAclOnPutObject) {
453 this.setPublicReadAclOnPutObject = setPublicReadAclOnPutObject;
454 }
455
456 public Integer getMaxNumberOfFailedOperations() {
457 return maxNumberOfFailedOperations;
458 }
459
460 public void setMaxNumberOfFailedOperations(Integer maxNumberOfFailedOperations) {
461 this.maxNumberOfFailedOperations = maxNumberOfFailedOperations;
462 }
463 }
464 }
465
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/config/DistributionServiceConfig.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/S3Publisher.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.distribution.objectstore;
22
23 import app.coronawarn.server.services.distribution.assembly.component.CwaApiStructureProvider;
24 import app.coronawarn.server.services.distribution.objectstore.client.ObjectStoreOperationFailedException;
25 import app.coronawarn.server.services.distribution.objectstore.publish.LocalFile;
26 import app.coronawarn.server.services.distribution.objectstore.publish.PublishFileSet;
27 import app.coronawarn.server.services.distribution.objectstore.publish.PublishedFileSet;
28 import java.io.IOException;
29 import java.nio.file.Path;
30 import java.util.List;
31 import java.util.stream.Collectors;
32 import org.slf4j.Logger;
33 import org.slf4j.LoggerFactory;
34
35 /**
36 * Publishes a folder on the disk to S3 while keeping the folder and file structure.<br>
37 * Moreover, does the following:
38 * <br>
39 * <ul>
40 * <li>Publishes index files on a different route, removing the trailing "/index" part.</li>
41 * <li>Adds meta information to the uploaded files, e.g. the sha256 hash value.</li>
42 * <li>Only performs the upload for files, which do not yet exist on the object store, and
43 * checks whether the existing files hash differ from the to-be-uploaded files hash. Only if the
44 * hash differs, the file will ultimately be uploaded</li>
45 * <li>Currently not implemented: Set cache control headers</li>
46 * <li>Currently not implemented: Supports multi threaded upload of files.</li>
47 * </ul>
48 */
49 public class S3Publisher {
50
51 private static final Logger logger = LoggerFactory.getLogger(S3Publisher.class);
52
53 /**
54 * The default CWA root folder, which contains all CWA related files.
55 */
56 private static final String CWA_S3_ROOT = CwaApiStructureProvider.VERSION_DIRECTORY;
57
58 private final Path root;
59 private final ObjectStoreAccess objectStoreAccess;
60 private final FailedObjectStoreOperationsCounter failedOperationsCounter;
61
62 /**
63 * Creates an {@link S3Publisher} instance that attempts to publish the files at the specified location to an object
64 * store. Object store operations are performed through the specified {@link ObjectStoreAccess} instance.
65 *
66 * @param root The path of the directory that shall be published.
67 * @param objectStoreAccess The {@link ObjectStoreAccess} used to communicate with the object store.
68 * @param failedOperationsCounter The {@link FailedObjectStoreOperationsCounter} that is used to monitor the number of
69 * failed operations.
70 */
71 public S3Publisher(Path root, ObjectStoreAccess objectStoreAccess,
72 FailedObjectStoreOperationsCounter failedOperationsCounter) {
73 this.root = root;
74 this.objectStoreAccess = objectStoreAccess;
75 this.failedOperationsCounter = failedOperationsCounter;
76 }
77
78 /**
79 * Synchronizes the files to S3.
80 *
81 * @throws IOException in case there were problems reading files from the disk.
82 */
83 public void publish() throws IOException {
84 PublishedFileSet published;
85 List<LocalFile> toPublish = new PublishFileSet(root).getFiles();
86 List<LocalFile> diff;
87
88 try {
89 published = new PublishedFileSet(objectStoreAccess.getObjectsWithPrefix(CWA_S3_ROOT));
90 diff = toPublish
91 .stream()
92 .filter(published::isNotYetPublished)
93 .collect(Collectors.toList());
94 } catch (ObjectStoreOperationFailedException e) {
95 failedOperationsCounter.incrementAndCheckThreshold(e);
96 // failed to retrieve existing files; publish everything
97 diff = toPublish;
98 }
99
100 logger.info("Beginning upload... ");
101 for (LocalFile file : diff) {
102 try {
103 this.objectStoreAccess.putObject(file);
104 } catch (ObjectStoreOperationFailedException e) {
105 failedOperationsCounter.incrementAndCheckThreshold(e);
106 }
107 }
108 logger.info("Upload completed.");
109 }
110 }
111
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/S3Publisher.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/client/ObjectStoreClientConfig.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.distribution.objectstore.client;
22
23 import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
24 import app.coronawarn.server.services.distribution.config.DistributionServiceConfig.ObjectStore;
25 import java.net.URI;
26 import org.springframework.context.annotation.Bean;
27 import org.springframework.context.annotation.Configuration;
28 import org.springframework.retry.annotation.EnableRetry;
29 import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
30 import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
31 import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
32 import software.amazon.awssdk.regions.Region;
33 import software.amazon.awssdk.services.s3.S3Client;
34
35 /**
36 * Manages the instantiation of the {@link ObjectStoreClient} bean.
37 */
38 @Configuration
39 @EnableRetry
40 public class ObjectStoreClientConfig {
41
42 private static final Region DEFAULT_REGION = Region.EU_CENTRAL_1;
43
44 @Bean
45 public ObjectStoreClient createObjectStoreClient(DistributionServiceConfig distributionServiceConfig) {
46 return createClient(distributionServiceConfig.getObjectStore());
47 }
48
49 private ObjectStoreClient createClient(ObjectStore objectStore) {
50 AwsCredentialsProvider credentialsProvider = StaticCredentialsProvider.create(
51 AwsBasicCredentials.create(objectStore.getAccessKey(), objectStore.getSecretKey()));
52 String endpoint = removeTrailingSlash(objectStore.getEndpoint()) + ":" + objectStore.getPort();
53
54 return new S3ClientWrapper(S3Client.builder()
55 .region(DEFAULT_REGION)
56 .endpointOverride(URI.create(endpoint))
57 .credentialsProvider(credentialsProvider)
58 .build());
59 }
60
61 private String removeTrailingSlash(String string) {
62 return string.endsWith("/") ? string.substring(0, string.length() - 1) : string;
63 }
64 }
65
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/client/ObjectStoreClientConfig.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/S3Distribution.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.distribution.runner;
22
23 import app.coronawarn.server.services.distribution.assembly.component.OutputDirectoryProvider;
24 import app.coronawarn.server.services.distribution.objectstore.FailedObjectStoreOperationsCounter;
25 import app.coronawarn.server.services.distribution.objectstore.ObjectStoreAccess;
26 import app.coronawarn.server.services.distribution.objectstore.S3Publisher;
27 import app.coronawarn.server.services.distribution.objectstore.client.ObjectStoreOperationFailedException;
28 import java.io.IOException;
29 import java.nio.file.Path;
30 import org.slf4j.Logger;
31 import org.slf4j.LoggerFactory;
32 import org.springframework.boot.ApplicationArguments;
33 import org.springframework.boot.ApplicationRunner;
34 import org.springframework.core.annotation.Order;
35 import org.springframework.stereotype.Component;
36
37 /**
38 * This runner will sync the base working directory to the S3.
39 */
40 @Component
41 @Order(3)
42 public class S3Distribution implements ApplicationRunner {
43
44 private static final Logger logger = LoggerFactory.getLogger(S3Distribution.class);
45
46 private final OutputDirectoryProvider outputDirectoryProvider;
47 private final ObjectStoreAccess objectStoreAccess;
48 private final FailedObjectStoreOperationsCounter failedOperationsCounter;
49
50 S3Distribution(OutputDirectoryProvider outputDirectoryProvider, ObjectStoreAccess objectStoreAccess,
51 FailedObjectStoreOperationsCounter failedOperationsCounter) {
52 this.outputDirectoryProvider = outputDirectoryProvider;
53 this.objectStoreAccess = objectStoreAccess;
54 this.failedOperationsCounter = failedOperationsCounter;
55 }
56
57 @Override
58 public void run(ApplicationArguments args) {
59 try {
60 Path pathToDistribute = outputDirectoryProvider.getFileOnDisk().toPath().toAbsolutePath();
61 S3Publisher s3Publisher = new S3Publisher(pathToDistribute, objectStoreAccess, failedOperationsCounter);
62
63 s3Publisher.publish();
64 logger.info("Data pushed to Object Store successfully.");
65 } catch (UnsupportedOperationException | ObjectStoreOperationFailedException | IOException e) {
66 logger.error("Distribution failed.", e);
67 }
68 }
69 }
70
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/S3Distribution.java]
[start of services/distribution/src/main/resources/application.yaml]
1 ---
2 logging:
3 level:
4 org:
5 springframework:
6 web: INFO
7 app:
8 coronawarn: INFO
9
10 services:
11 distribution:
12 output-file-name: index
13 retention-days: 14
14 expiry-policy-minutes: 120
15 shifting-policy-threshold: 140
16 maximum-number-of-keys-per-bundle: 600000
17 include-incomplete-days: false
18 include-incomplete-hours: false
19 paths:
20 output: out
21 privatekey: ${VAULT_FILESIGNING_SECRET}
22 tek-export:
23 file-name: export.bin
24 file-header: EK Export v1
25 file-header-width: 16
26 api:
27 version-path: version
28 version-v1: v1
29 country-path: country
30 country-germany: DE
31 date-path: date
32 hour-path: hour
33 diagnosis-keys-path: diagnosis-keys
34 parameters-path: configuration
35 app-config-file-name: app_config
36 signature:
37 verification-key-id: 262
38 verification-key-version: v1
39 algorithm-oid: 1.2.840.10045.4.3.2
40 algorithm-name: SHA256withECDSA
41 file-name: export.sig
42 security-provider: BC
43 # Configuration for the S3 compatible object storage hosted by Telekom in Germany
44 objectstore:
45 access-key: ${CWA_OBJECTSTORE_ACCESSKEY:accessKey1}
46 secret-key: ${CWA_OBJECTSTORE_SECRETKEY:verySecretKey1}
47 endpoint: ${CWA_OBJECTSTORE_ENDPOINT:http://localhost}
48 bucket: ${CWA_OBJECTSTORE_BUCKET:cwa}
49 port: ${CWA_OBJECTSTORE_PORT:8003}
50 set-public-read-acl-on-put-object: true
51 retry-attempts: 3
52 retry-backoff: 2000
53 max-number-of-failed-operations: 5
54
55 spring:
56 main:
57 web-application-type: NONE
58 # Postgres configuration
59 jpa:
60 hibernate:
61 ddl-auto: validate
62 flyway:
63 enabled: true
64 locations: classpath:db/migration/postgres
65 password: ${POSTGRESQL_PASSWORD_FLYWAY:postgres}
66 user: ${POSTGRESQL_USER_FLYWAY:postgres}
67
68 datasource:
69 driver-class-name: org.postgresql.Driver
70 url: jdbc:postgresql://${POSTGRESQL_SERVICE_HOST:localhost}:${POSTGRESQL_SERVICE_PORT:5432}/${POSTGRESQL_DATABASE:cwa}
71 username: ${POSTGRESQL_USER_DISTRIBUTION:postgres}
72 password: ${POSTGRESQL_PASSWORD_DISTRIBUTION:postgres}
73
[end of services/distribution/src/main/resources/application.yaml]
</code>
Here is an example of a patch file. It consists of changes to the code base. It specifies the file names, the line numbers of each change, and the removed and added lines. A single patch file can contain changes to multiple files.
<patch>
--- a/file.py
+++ b/file.py
@@ -1,27 +1,35 @@
def euclidean(a, b):
- while b:
- a, b = b, a % b
- return a
+ if b == 0:
+ return a
+ return euclidean(b, a % b)
def bresenham(x0, y0, x1, y1):
points = []
dx = abs(x1 - x0)
dy = abs(y1 - y0)
- sx = 1 if x0 < x1 else -1
- sy = 1 if y0 < y1 else -1
- err = dx - dy
+ x, y = x0, y0
+ sx = -1 if x0 > x1 else 1
+ sy = -1 if y0 > y1 else 1
- while True:
- points.append((x0, y0))
- if x0 == x1 and y0 == y1:
- break
- e2 = 2 * err
- if e2 > -dy:
+ if dx > dy:
+ err = dx / 2.0
+ while x != x1:
+ points.append((x, y))
err -= dy
- x0 += sx
- if e2 < dx:
- err += dx
- y0 += sy
+ if err < 0:
+ y += sy
+ err += dx
+ x += sx
+ else:
+ err = dy / 2.0
+ while y != y1:
+ points.append((x, y))
+ err -= dx
+ if err < 0:
+ x += sx
+ err += dy
+ y += sy
+ points.append((x, y))
return points
</patch>
I need you to solve the provded issue by generating a single patch file that I can apply directly to this repository using git apply. Please respond with a single patch file in the format shown above.
Respond below:
| corona-warn-app/cwa-server | b148f9eae02d75e509e9b0cc1ae0cdd3fbbad77e | S3Publisher: Increase performance
The S3Publisher is currently running in only one thread, making it quite slow for uploads/requests for metadata.
Enhance the S3Publisher/ObjectStoreAccess, so that multiple threads are being used for interacting with S3.
| 2020-06-06T12:41:36 | <patch>
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/config/DistributionServiceConfig.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/config/DistributionServiceConfig.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/config/DistributionServiceConfig.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/config/DistributionServiceConfig.java
@@ -404,6 +404,7 @@ public static class ObjectStore {
private String bucket;
private Boolean setPublicReadAclOnPutObject;
private Integer maxNumberOfFailedOperations;
+ private Integer maxNumberOfS3Threads;
public String getAccessKey() {
return accessKey;
@@ -460,5 +461,13 @@ public Integer getMaxNumberOfFailedOperations() {
public void setMaxNumberOfFailedOperations(Integer maxNumberOfFailedOperations) {
this.maxNumberOfFailedOperations = maxNumberOfFailedOperations;
}
+
+ public Integer getMaxNumberOfS3Threads() {
+ return maxNumberOfS3Threads;
+ }
+
+ public void setMaxNumberOfS3Threads(Integer maxNumberOfS3Threads) {
+ this.maxNumberOfS3Threads = maxNumberOfS3Threads;
+ }
}
}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/S3Publisher.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/S3Publisher.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/S3Publisher.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/S3Publisher.java
@@ -28,9 +28,13 @@
import java.io.IOException;
import java.nio.file.Path;
import java.util.List;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Future;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
+import org.springframework.stereotype.Component;
/**
* Publishes a folder on the disk to S3 while keeping the folder and file structure.<br>
@@ -46,6 +50,7 @@
* <li>Currently not implemented: Supports multi threaded upload of files.</li>
* </ul>
*/
+@Component
public class S3Publisher {
private static final Logger logger = LoggerFactory.getLogger(S3Publisher.class);
@@ -55,32 +60,33 @@ public class S3Publisher {
*/
private static final String CWA_S3_ROOT = CwaApiStructureProvider.VERSION_DIRECTORY;
- private final Path root;
private final ObjectStoreAccess objectStoreAccess;
private final FailedObjectStoreOperationsCounter failedOperationsCounter;
+ private final ThreadPoolTaskExecutor executor;
/**
* Creates an {@link S3Publisher} instance that attempts to publish the files at the specified location to an object
* store. Object store operations are performed through the specified {@link ObjectStoreAccess} instance.
*
- * @param root The path of the directory that shall be published.
* @param objectStoreAccess The {@link ObjectStoreAccess} used to communicate with the object store.
* @param failedOperationsCounter The {@link FailedObjectStoreOperationsCounter} that is used to monitor the number of
* failed operations.
+ * @param executor The executor that manages the upload task submission.
*/
- public S3Publisher(Path root, ObjectStoreAccess objectStoreAccess,
- FailedObjectStoreOperationsCounter failedOperationsCounter) {
- this.root = root;
+ public S3Publisher(ObjectStoreAccess objectStoreAccess, FailedObjectStoreOperationsCounter failedOperationsCounter,
+ ThreadPoolTaskExecutor executor) {
this.objectStoreAccess = objectStoreAccess;
this.failedOperationsCounter = failedOperationsCounter;
+ this.executor = executor;
}
/**
* Synchronizes the files to S3.
*
+ * @param root The path of the directory that shall be published.
* @throws IOException in case there were problems reading files from the disk.
*/
- public void publish() throws IOException {
+ public void publish(Path root) throws IOException {
PublishedFileSet published;
List<LocalFile> toPublish = new PublishFileSet(root).getFiles();
List<LocalFile> diff;
@@ -97,14 +103,25 @@ public void publish() throws IOException {
diff = toPublish;
}
- logger.info("Beginning upload... ");
- for (LocalFile file : diff) {
- try {
- this.objectStoreAccess.putObject(file);
- } catch (ObjectStoreOperationFailedException e) {
- failedOperationsCounter.incrementAndCheckThreshold(e);
- }
+ logger.info("Beginning upload of {} files... ", diff.size());
+ try {
+ diff.stream()
+ .map(file -> executor.submit(() -> objectStoreAccess.putObject(file)))
+ .forEach(this::awaitThread);
+ } finally {
+ executor.shutdown();
}
logger.info("Upload completed.");
}
+
+ private void awaitThread(Future<?> result) {
+ try {
+ result.get();
+ } catch (ExecutionException e) {
+ failedOperationsCounter.incrementAndCheckThreshold(new ObjectStoreOperationFailedException(e.getMessage(), e));
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new ObjectStoreOperationFailedException(e.getMessage(), e);
+ }
+ }
}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/client/ObjectStoreClientConfig.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/client/ObjectStorePublishingConfig.java
similarity index 77%
rename from services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/client/ObjectStoreClientConfig.java
rename to services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/client/ObjectStorePublishingConfig.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/client/ObjectStoreClientConfig.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/client/ObjectStorePublishingConfig.java
@@ -26,6 +26,7 @@
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.retry.annotation.EnableRetry;
+import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
@@ -37,7 +38,7 @@
*/
@Configuration
@EnableRetry
-public class ObjectStoreClientConfig {
+public class ObjectStorePublishingConfig {
private static final Region DEFAULT_REGION = Region.EU_CENTRAL_1;
@@ -61,4 +62,17 @@ private ObjectStoreClient createClient(ObjectStore objectStore) {
private String removeTrailingSlash(String string) {
return string.endsWith("/") ? string.substring(0, string.length() - 1) : string;
}
+
+ /**
+ * Creates a {@link ThreadPoolTaskExecutor}, which is used to submit object store upload tasks.
+ */
+ @Bean
+ public ThreadPoolTaskExecutor createExecutor(DistributionServiceConfig distributionServiceConfig) {
+ ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
+ executor.setCorePoolSize(distributionServiceConfig.getObjectStore().getMaxNumberOfS3Threads());
+ executor.setMaxPoolSize(distributionServiceConfig.getObjectStore().getMaxNumberOfS3Threads());
+ executor.setThreadNamePrefix("object-store-operation-worker-");
+ executor.initialize();
+ return executor;
+ }
}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/S3Distribution.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/S3Distribution.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/S3Distribution.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/S3Distribution.java
@@ -21,8 +21,6 @@
package app.coronawarn.server.services.distribution.runner;
import app.coronawarn.server.services.distribution.assembly.component.OutputDirectoryProvider;
-import app.coronawarn.server.services.distribution.objectstore.FailedObjectStoreOperationsCounter;
-import app.coronawarn.server.services.distribution.objectstore.ObjectStoreAccess;
import app.coronawarn.server.services.distribution.objectstore.S3Publisher;
import app.coronawarn.server.services.distribution.objectstore.client.ObjectStoreOperationFailedException;
import java.io.IOException;
@@ -44,23 +42,19 @@ public class S3Distribution implements ApplicationRunner {
private static final Logger logger = LoggerFactory.getLogger(S3Distribution.class);
private final OutputDirectoryProvider outputDirectoryProvider;
- private final ObjectStoreAccess objectStoreAccess;
- private final FailedObjectStoreOperationsCounter failedOperationsCounter;
+ private final S3Publisher s3Publisher;
- S3Distribution(OutputDirectoryProvider outputDirectoryProvider, ObjectStoreAccess objectStoreAccess,
- FailedObjectStoreOperationsCounter failedOperationsCounter) {
+ S3Distribution(OutputDirectoryProvider outputDirectoryProvider, S3Publisher s3Publisher) {
this.outputDirectoryProvider = outputDirectoryProvider;
- this.objectStoreAccess = objectStoreAccess;
- this.failedOperationsCounter = failedOperationsCounter;
+ this.s3Publisher = s3Publisher;
}
@Override
public void run(ApplicationArguments args) {
try {
Path pathToDistribute = outputDirectoryProvider.getFileOnDisk().toPath().toAbsolutePath();
- S3Publisher s3Publisher = new S3Publisher(pathToDistribute, objectStoreAccess, failedOperationsCounter);
- s3Publisher.publish();
+ s3Publisher.publish(pathToDistribute);
logger.info("Data pushed to Object Store successfully.");
} catch (UnsupportedOperationException | ObjectStoreOperationFailedException | IOException e) {
logger.error("Distribution failed.", e);
diff --git a/services/distribution/src/main/resources/application.yaml b/services/distribution/src/main/resources/application.yaml
--- a/services/distribution/src/main/resources/application.yaml
+++ b/services/distribution/src/main/resources/application.yaml
@@ -51,6 +51,7 @@ services:
retry-attempts: 3
retry-backoff: 2000
max-number-of-failed-operations: 5
+ max-number-of-s3-threads: 4
spring:
main:
</patch> | diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/ObjectStoreAccessTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/ObjectStoreAccessTest.java
--- a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/ObjectStoreAccessTest.java
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/ObjectStoreAccessTest.java
@@ -25,7 +25,7 @@
import static org.mockito.Mockito.when;
import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
-import app.coronawarn.server.services.distribution.objectstore.client.ObjectStoreClientConfig;
+import app.coronawarn.server.services.distribution.objectstore.client.ObjectStorePublishingConfig;
import app.coronawarn.server.services.distribution.objectstore.publish.LocalFile;
import app.coronawarn.server.services.distribution.objectstore.publish.LocalGenericFile;
import java.io.IOException;
@@ -43,7 +43,7 @@
import org.springframework.test.context.junit.jupiter.SpringExtension;
@ExtendWith(SpringExtension.class)
-@SpringBootTest(classes = {ObjectStoreAccess.class, ObjectStoreClientConfig.class})
+@SpringBootTest(classes = {ObjectStoreAccess.class, ObjectStorePublishingConfig.class})
@EnableConfigurationProperties(value = DistributionServiceConfig.class)
@Tag("s3-integration")
class ObjectStoreAccessTest {
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/ObjectStorePublishingConfigTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/ObjectStorePublishingConfigTest.java
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/ObjectStorePublishingConfigTest.java
@@ -0,0 +1,64 @@
+/*-
+ * ---license-start
+ * Corona-Warn-App
+ * ---
+ * Copyright (C) 2020 SAP SE and all other contributors
+ * ---
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://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 for the specific language governing permissions and
+ * limitations under the License.
+ * ---license-end
+ */
+
+package app.coronawarn.server.services.distribution.objectstore;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
+import app.coronawarn.server.services.distribution.objectstore.client.ObjectStoreClient;
+import app.coronawarn.server.services.distribution.objectstore.client.ObjectStorePublishingConfig;
+import app.coronawarn.server.services.distribution.objectstore.client.S3ClientWrapper;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.context.properties.EnableConfigurationProperties;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.test.mock.mockito.MockBean;
+import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
+import org.springframework.test.context.junit.jupiter.SpringExtension;
+
+@ExtendWith({SpringExtension.class})
+@SpringBootTest(classes = {ObjectStorePublishingConfig.class})
+@EnableConfigurationProperties(value = DistributionServiceConfig.class)
+class ObjectStorePublishingConfigTest {
+
+ @MockBean
+ private ObjectStoreClient objectStoreClient;
+
+ @Autowired
+ private ThreadPoolTaskExecutor executor;
+
+ @Autowired
+ private DistributionServiceConfig distributionServiceConfig;
+
+ @Test
+ void testS3ClientWrapperInstantiation() {
+ ObjectStorePublishingConfig config = new ObjectStorePublishingConfig();
+ assertThat(config.createObjectStoreClient(distributionServiceConfig)).isInstanceOf(S3ClientWrapper.class);
+ }
+
+ @Test
+ void testThreadPoolExecutorPoolSize() {
+ int expNumberOfThreads = distributionServiceConfig.getObjectStore().getMaxNumberOfS3Threads();
+ assertThat(executor.getCorePoolSize()).isEqualTo(expNumberOfThreads);
+ assertThat(executor.getMaxPoolSize()).isEqualTo(expNumberOfThreads);
+ }
+}
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/S3PublisherIntegrationTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/S3PublisherIntegrationTest.java
--- a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/S3PublisherIntegrationTest.java
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/S3PublisherIntegrationTest.java
@@ -21,10 +21,9 @@
package app.coronawarn.server.services.distribution.objectstore;
import static org.assertj.core.api.Assertions.assertThat;
-import static org.mockito.Mockito.mock;
import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
-import app.coronawarn.server.services.distribution.objectstore.client.ObjectStoreClientConfig;
+import app.coronawarn.server.services.distribution.objectstore.client.ObjectStorePublishingConfig;
import app.coronawarn.server.services.distribution.objectstore.client.S3Object;
import java.io.IOException;
import java.nio.file.Path;
@@ -37,11 +36,12 @@
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.core.io.ResourceLoader;
import org.springframework.test.context.junit.jupiter.SpringExtension;
@ExtendWith(SpringExtension.class)
-@SpringBootTest(classes = {ObjectStoreAccess.class, ObjectStoreClientConfig.class})
+@SpringBootTest(classes = {ObjectStoreAccess.class, ObjectStorePublishingConfig.class, S3Publisher.class})
@EnableConfigurationProperties(value = DistributionServiceConfig.class)
@Tag("s3-integration")
class S3PublisherIntegrationTest {
@@ -54,12 +54,15 @@ class S3PublisherIntegrationTest {
@Autowired
private ResourceLoader resourceLoader;
+ @MockBean
+ private FailedObjectStoreOperationsCounter failedObjectStoreOperationsCounter;
+
+ @Autowired
+ private S3Publisher s3Publisher;
+
@Test
void publishTestFolderOk() throws IOException {
- S3Publisher publisher = new S3Publisher(
- getFolderAsPath(rootTestFolder), objectStoreAccess, mock(FailedObjectStoreOperationsCounter.class));
-
- publisher.publish();
+ s3Publisher.publish(getFolderAsPath(rootTestFolder));
List<S3Object> s3Objects = objectStoreAccess.getObjectsWithPrefix("version");
assertThat(s3Objects).hasSize(5);
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/S3PublisherTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/S3PublisherTest.java
--- a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/S3PublisherTest.java
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/S3PublisherTest.java
@@ -20,26 +20,37 @@
package app.coronawarn.server.services.distribution.objectstore;
+import static org.assertj.core.util.Lists.emptyList;
import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
+import app.coronawarn.server.services.distribution.objectstore.client.ObjectStoreOperationFailedException;
import app.coronawarn.server.services.distribution.objectstore.client.S3Object;
import java.io.IOException;
+import java.nio.file.Path;
import java.util.List;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Future;
+import org.assertj.core.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.core.io.ResourceLoader;
+import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.test.context.junit.jupiter.SpringExtension;
@ExtendWith(SpringExtension.class)
class S3PublisherTest {
- private static final String PUBLISHING_PATH = "testsetups/s3publishertest/topublish";
private static final S3Object FILE_1 = new S3Object("file1.txt", "cf7fb1ca5c32adc0941c35a6f7fc5eba");
private static final S3Object FILE_2 = new S3Object("file2.txt", "d882afb9fa9c26f7e9d0965b8faa79b8");
private static final S3Object FILE_3 = new S3Object("file3.txt", "0385524c9fdc83634467a11667c851ac");
@@ -47,14 +58,32 @@ class S3PublisherTest {
@MockBean
private ObjectStoreAccess objectStoreAccess;
+ @MockBean
+ private FailedObjectStoreOperationsCounter failedObjectStoreOperationsCounter;
+
@Autowired
private ResourceLoader resourceLoader;
+ private ThreadPoolTaskExecutor executor;
+ private Path publishingPath;
+ private S3Publisher s3Publisher;
+
+ @BeforeEach
+ void setup() throws IOException {
+ publishingPath = resourceLoader.getResource("testsetups/s3publishertest/topublish").getFile().toPath();
+ executor = new ThreadPoolTaskExecutor();
+ executor.setMaxPoolSize(1);
+ executor.setCorePoolSize(1);
+ executor.initialize();
+ executor = spy(executor);
+ s3Publisher = new S3Publisher(objectStoreAccess, failedObjectStoreOperationsCounter, executor);
+ }
+
@Test
void allNewNoExisting() throws IOException {
- when(objectStoreAccess.getObjectsWithPrefix("version")).thenReturn(noneExisting());
+ when(objectStoreAccess.getObjectsWithPrefix("version")).thenReturn(emptyList());
- createTestPublisher().publish();
+ s3Publisher.publish(publishingPath);
verify(objectStoreAccess, times(3)).putObject(any());
}
@@ -63,7 +92,7 @@ void allNewNoExisting() throws IOException {
void noUploadsDueToAlreadyExist() throws IOException {
when(objectStoreAccess.getObjectsWithPrefix("version")).thenReturn(allExistAllSame());
- createTestPublisher().publish();
+ s3Publisher.publish(publishingPath);
verify(objectStoreAccess, times(0)).putObject(any());
}
@@ -72,7 +101,7 @@ void noUploadsDueToAlreadyExist() throws IOException {
void uploadAllOtherFilesDifferentNames() throws IOException {
when(objectStoreAccess.getObjectsWithPrefix("version")).thenReturn(otherExisting());
- createTestPublisher().publish();
+ s3Publisher.publish(publishingPath);
verify(objectStoreAccess, times(3)).putObject(any());
}
@@ -81,28 +110,75 @@ void uploadAllOtherFilesDifferentNames() throws IOException {
void uploadOneDueToOneChanged() throws IOException {
when(objectStoreAccess.getObjectsWithPrefix("version")).thenReturn(twoIdenticalOneOtherOneChange());
- createTestPublisher().publish();
+ s3Publisher.publish(publishingPath);
verify(objectStoreAccess, times(1)).putObject(any());
}
- private List<S3Object> noneExisting() {
- return List.of();
+ @Test
+ void executorGetsShutDown() throws IOException {
+ when(objectStoreAccess.getObjectsWithPrefix("version")).thenReturn(emptyList());
+
+ s3Publisher.publish(publishingPath);
+
+ verify(executor, times(1)).shutdown();
+ }
+
+ @Test
+ void taskExecutionHaltsWhenMaximumFailedOperationsReached() {
+ when(objectStoreAccess.getObjectsWithPrefix("version")).thenReturn(emptyList());
+ setUpFailureThresholdExceededOnSecondUpload();
+
+ Assertions.assertThatExceptionOfType(ObjectStoreOperationFailedException.class)
+ .isThrownBy(() -> s3Publisher.publish(publishingPath));
+
+ // third invocation does not happen
+ verify(objectStoreAccess, times(2)).putObject(any());
+ }
+
+ @Test
+ void threadPoolShutDownWhenMaximumFailedOperationsReached() {
+ when(objectStoreAccess.getObjectsWithPrefix("version")).thenReturn(emptyList());
+ setUpFailureThresholdExceededOnSecondUpload();
+
+ Assertions.assertThatExceptionOfType(ObjectStoreOperationFailedException.class)
+ .isThrownBy(() -> s3Publisher.publish(publishingPath));
+
+ verify(executor, times(1)).shutdown();
+ }
+
+ private void setUpFailureThresholdExceededOnSecondUpload() {
+ doThrow(ObjectStoreOperationFailedException.class).when(objectStoreAccess).putObject(any());
+ doAnswer(__ -> null)
+ .doThrow(ObjectStoreOperationFailedException.class)
+ .when(failedObjectStoreOperationsCounter)
+ .incrementAndCheckThreshold(any(ObjectStoreOperationFailedException.class));
+ }
+
+ @Test
+ void interruptedExceptionHandling() throws ExecutionException, InterruptedException {
+ var result = mock(Future.class);
+ when(result.get()).thenThrow(new InterruptedException());
+ doReturn(result).when(executor).submit(any(Runnable.class));
+ when(objectStoreAccess.getObjectsWithPrefix("version")).thenReturn(emptyList());
+
+ Assertions.assertThatExceptionOfType(ObjectStoreOperationFailedException.class)
+ .isThrownBy(() -> s3Publisher.publish(publishingPath));
+
+ verify(executor, times(1)).shutdown();
}
private List<S3Object> otherExisting() {
return List.of(
new S3Object("some_old_file.txt", "1fb772815c837b6294d9f163db89e962"),
- new S3Object("other_old_file.txt", "2fb772815c837b6294d9f163db89e962")
- );
+ new S3Object("other_old_file.txt", "2fb772815c837b6294d9f163db89e962"));
}
private List<S3Object> allExistAllSame() {
return List.of(
FILE_1,
FILE_2,
- FILE_3
- );
+ FILE_3);
}
private List<S3Object> twoIdenticalOneOtherOneChange() {
@@ -110,12 +186,6 @@ private List<S3Object> twoIdenticalOneOtherOneChange() {
new S3Object("newfile.txt", "1fb772815c837b6294d9f163db89e962"), // new
FILE_1,
FILE_2,
- new S3Object("file3.txt", "111772815c837b6294d9f163db89e962") // changed
- );
- }
-
- private S3Publisher createTestPublisher() throws IOException {
- var publishPath = resourceLoader.getResource(PUBLISHING_PATH).getFile().toPath();
- return new S3Publisher(publishPath, objectStoreAccess, mock(FailedObjectStoreOperationsCounter.class));
+ new S3Object("file3.txt", "111772815c837b6294d9f163db89e962")); // changed
}
}
diff --git a/services/distribution/src/test/resources/application.yaml b/services/distribution/src/test/resources/application.yaml
--- a/services/distribution/src/test/resources/application.yaml
+++ b/services/distribution/src/test/resources/application.yaml
@@ -50,6 +50,7 @@ services:
retry-attempts: 3
retry-backoff: 1
max-number-of-failed-operations: 5
+ max-number-of-s3-threads: 2
spring:
main:
banner-mode: off
| |||||
corona-warn-app__cwa-server-573 | You will be provided with a partial code base and an issue statement explaining a problem to resolve.
<issue>
Add JPA range validator for submissionTimestamp of DiagnosisKey
DiagnosisKey uses a submissionTimestamp field of type long
https://github.com/corona-warn-app/cwa-server/blob/7059232b48d2507d142fe683fbebdda371a98652/common/persistence/src/main/java/app/coronawarn/server/common/persistence/domain/DiagnosisKey.java#L73
the value is actually the *hours* since epoch but there are no sanity checks on the value.
Just from reading the code you could e.g. easily think it's seconds since epoch and use it the wrong way without noticing at runtime.
Proposal:
* Add a JPA ConstraintValidator similar to ValidRollingStartIntervalNumberValidator which checks the value range to be greater or equal zero and not in the future (current hour since epoch rounded up)
* Add field javadoc to submissionTimestamp: "hours since epoch"
Expected Benefits:
* discard invalid data
* less potential for programming errors
</issue>
<code>
[start of README.md]
1 <!-- markdownlint-disable MD041 -->
2 <h1 align="center">
3 Corona-Warn-App Server
4 </h1>
5
6 <p align="center">
7 <a href="https://github.com/corona-warn-app/cwa-server/commits/" title="Last Commit"><img src="https://img.shields.io/github/last-commit/corona-warn-app/cwa-server?style=flat"></a>
8 <a href="https://github.com/corona-warn-app/cwa-server/issues" title="Open Issues"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat"></a>
9 <a href="https://circleci.com/gh/corona-warn-app/cwa-server" title="Build Status"><img src="https://circleci.com/gh/corona-warn-app/cwa-server.svg?style=shield&circle-token=4ab059989d10709df19eb4b98ab7c121a25e981a"></a>
10 <a href="https://sonarcloud.io/dashboard?id=corona-warn-app_cwa-server" title="Quality Gate"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=alert_status"></a>
11 <a href="https://sonarcloud.io/component_measures?id=corona-warn-app_cwa-server&metric=Coverage&view=list" title="Coverage"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=coverage"></a>
12 <a href="https://github.com/corona-warn-app/cwa-server/blob/master/LICENSE" title="License"><img src="https://img.shields.io/badge/License-Apache%202.0-green.svg?style=flat"></a>
13 </p>
14
15 <p align="center">
16 <a href="#development">Development</a> •
17 <a href="#service-apis">Service APIs</a> •
18 <a href="#documentation">Documentation</a> •
19 <a href="#support-and-feedback">Support</a> •
20 <a href="#how-to-contribute">Contribute</a> •
21 <a href="#contributors">Contributors</a> •
22 <a href="#repositories">Repositories</a> •
23 <a href="#licensing">Licensing</a>
24 </p>
25
26 The goal of this project is to develop the official Corona-Warn-App for Germany based on the exposure notification API from [Apple](https://www.apple.com/covid19/contacttracing/) and [Google](https://www.google.com/covid19/exposurenotifications/). The apps (for both iOS and Android) use Bluetooth technology to exchange anonymous encrypted data with other mobile phones (on which the app is also installed) in the vicinity of an app user's phone. The data is stored locally on each user's device, preventing authorities or other parties from accessing or controlling the data. This repository contains the **implementation of the server for encryption keys** for the Corona-Warn-App.
27
28 In this documentation, Corona-Warn-App services are also referred to as CWA services.
29
30 ## Architecture Overview
31
32 You can find the architecture overview [here](/docs/ARCHITECTURE.md), which will give you
33 a good starting point in how the backend services interact with other services, and what purpose
34 they serve.
35
36 ## Development
37
38 After you've checked out this repository, you can run the application in one of the following ways:
39
40 * As a [Docker](https://www.docker.com/)-based deployment on your local machine. You can run either:
41 * Single components using the respective Dockerfile or
42 * The full backend using the Docker Compose (which is considered the most convenient way)
43 * As a [Maven](https://maven.apache.org)-based build on your local machine.
44 If you want to develop something in a single component, this approach is preferable.
45
46 ### Docker-Based Deployment
47
48 If you want to use Docker-based deployment, you need to install Docker on your local machine. For more information about downloading and installing Docker, see the [official Docker documentation](https://docs.docker.com/get-docker/).
49
50 #### Running the Full CWA Backend Using Docker Compose
51
52 For your convenience, a full setup including the generation of test data has been prepared using [Docker Compose](https://docs.docker.com/compose/reference/overview/). To build the backend services, run ```docker-compose build``` in the repository's root directory. A default configuration file can be found under ```.env``` in the root folder of the repository. The default values for the local Postgres and Zenko Cloudserver should be changed in this file before docker-compose is run.
53
54 Once the services are built, you can start the whole backend using ```docker-compose up```.
55 The distribution service runs once and then finishes. If you want to trigger additional distribution runs, run ```docker-compose run distribution```.
56
57 The docker-compose contains the following services:
58
59 Service | Description | Endpoint and Default Credentials
60 ------------------|-------------|-----------
61 submission | The Corona-Warn-App submission service | `http://localhost:8000` <br> `http://localhost:8006` (for actuator endpoint)
62 distribution | The Corona-Warn-App distribution service | NO ENDPOINT
63 postgres | A [postgres] database installation | `localhost:8001` <br> `postgres:5432` (from containerized pgadmin) <br> Username: postgres <br> Password: postgres
64 pgadmin | A [pgadmin](https://www.pgadmin.org/) installation for the postgres database | `http://localhost:8002` <br> Username: [email protected] <br> Password: password
65 cloudserver | [Zenko CloudServer] is a S3-compliant object store | `http://localhost:8003/` <br> Access key: accessKey1 <br> Secret key: verySecretKey1
66 verification-fake | A very simple fake implementation for the tan verification. | `http://localhost:8004/version/v1/tan/verify` <br> The only valid tan is `edc07f08-a1aa-11ea-bb37-0242ac130002`.
67
68 ##### Known Limitation
69
70 In rare cases the docker-compose runs into a timing issue if the distribution service starts before the bucket of the objectstore was created. This is not a big issue as you can simply run ```docker-compose run distribution``` to trigger additional distribution runs after the objectstore was initialized.
71
72 #### Running Single CWA Services Using Docker
73
74 If you would like to build and run a single CWA service, it's considered easiest to run them in a Docker environment. You can do this using the script provided in the respective CWA service directory. The Docker script first builds the CWA service and then creates an image for the runtime, which means that there are no additional dependencies for you to install.
75
76 To build and run the distribution service, run the following command:
77
78 ```bash
79 ./services/distribution/build_and_run.sh
80 ```
81
82 To build and run the submission service, run the following command:
83
84 ```bash
85 ./services/submission/build_and_run.sh
86 ```
87
88 The submission service is available on [localhost:8080](http://localhost:8080 ).
89
90 ### Maven-Based Build
91
92 If you want to actively develop in one of the CWA services, the Maven-based runtime is most suitable.
93 To prepare your machine to run the CWA project locally, we recommend that you first ensure that you've installed the following:
94
95 * Minimum JDK Version 11: [OpenJDK](https://openjdk.java.net/) / [SapMachine](https://sap.github.io/SapMachine/)
96 * [Maven 3.6](https://maven.apache.org/)
97 * [Postgres]
98 * [Zenko CloudServer]
99
100 If you are already running a local Postgres, you need to create a database `cwa` and run the following setup scripts:
101
102 * Create the different CWA roles first by executing [create-roles.sql](setup/create-roles.sql).
103 * Create local database users for the specific roles by running [create-users.sql](./local-setup/create-users.sql).
104 * It is recommended to also run [enable-test-data-docker-compose.sql](./local-setup/enable-test-data-docker-compose.sql)
105 , which enables the test data generation profile. If you already had CWA running before and an existing `diagnosis-key`
106 table on your database, you need to run [enable-test-data.sql](./local-setup/enable-test-data.sql) instead.
107
108 You can also use `docker-compose` to start Postgres and Zenko. If you do that, you have to
109 set the following environment-variables when running the Spring project:
110
111 For the distribution module:
112
113 ```bash
114 POSTGRESQL_SERVICE_PORT=8001
115 VAULT_FILESIGNING_SECRET=</path/to/your/private_key>
116 SPRING_PROFILES_ACTIVE=signature-dev,disable-ssl-client-postgres
117 ```
118
119 For the submission module:
120
121 ```bash
122 POSTGRESQL_SERVICE_PORT=8001
123 SPRING_PROFILES_ACTIVE=disable-ssl-server,disable-ssl-client-postgres,disable-ssl-client-verification,disable-ssl-client-verification-verify-hostname
124 ```
125
126 #### Configure
127
128 After you made sure that the specified dependencies are running, configure them in the respective configuration files.
129
130 * Configure the Postgres connection in the [submission config](./services/submission/src/main/resources/application.yaml) and in the [distribution config](./services/distribution/src/main/resources/application.yaml)
131 * Configure the S3 compatible object storage in the [distribution config](./services/distribution/src/main/resources/application.yaml)
132 * Configure the private key for the distribution service, the path need to be prefixed with `file:`
133 * `VAULT_FILESIGNING_SECRET` should be the path to the private key, example available in `<repo-root>/docker-compose-test-secrets/private.pem`
134
135 #### Build
136
137 After you've checked out the repository, to build the project, run ```mvn install``` in your base directory.
138
139 #### Run
140
141 Navigate to the service you want to start and run the spring-boot:run target. The configured Postgres and the configured S3 compliant object storage are used as default. When you start the submission service, the endpoint is available on your local port 8080.
142
143 If you want to start the submission service, for example, you start it as follows:
144
145 ```bash
146 cd services/submission/
147 mvn spring-boot:run
148 ```
149
150 #### Debugging
151
152 To enable the `DEBUG` log level, you can run the application using the Spring `dev` profile.
153
154 ```bash
155 mvn spring-boot:run -Dspring.profiles.active=dev
156 ```
157
158 To be able to set breakpoints (e.g. in IntelliJ), it may be necessary to use the ```-Dspring-boot.run.fork=false``` parameter.
159
160 ## Service APIs
161
162 The API that is being exposed by the backend services is documented in an [OpenAPI](https://www.openapis.org/) specification. The specification files are available at the following locations:
163
164 Service | OpenAPI Specification
165 --------------------------|-------------
166 Submission Service | [services/submission/api_v1.json](https://github.com/corona-warn-app/cwa-server/raw/master/services/submission/api_v1.json)
167 Distribution Service | [services/distribution/api_v1.json](https://github.com/corona-warn-app/cwa-server/raw/master/services/distribution/api_v1.json)
168
169 ## Spring Profiles
170
171 ### Distribution
172
173 Profile | Effect
174 ------------------------------|-------------
175 `dev` | Turns the log level to `DEBUG`.
176 `cloud` | Removes default values for the `datasource` and `objectstore` configurations.
177 `demo` | Includes incomplete days and hours into the distribution run, thus creating aggregates for the current day and the current hour (and including both in the respective indices). When running multiple distributions in one hour with this profile, the date aggregate for today and the hours aggregate for the current hour will be updated and overwritten. This profile also turns off the expiry policy (Keys must be expired for at least 2 hours before distribution) and the shifting policy (there must be at least 140 keys in a distribution).
178 `testdata` | Causes test data to be inserted into the database before each distribution run. By default, around 1000 random diagnosis keys will be generated per hour. If there are no diagnosis keys in the database yet, random keys will be generated for every hour from the beginning of the retention period (14 days ago at 00:00 UTC) until one hour before the present hour. If there are already keys in the database, the random keys will be generated for every hour from the latest diagnosis key in the database (by submission timestamp) until one hour before the present hour (or none at all, if the latest diagnosis key in the database was submitted one hour ago or later).
179 `signature-dev` | Sets the app package ID in the export packages' signature info to `de.rki.coronawarnapp-dev` so that the non-productive/test public key will be used for client-side validation.
180 `signature-prod` | Sets the app package ID in the export packages' signature info to `de.rki.coronawarnapp` so that the productive public key will be used for client-side validation.
181 `disable-ssl-client-postgres` | Disables SSL for the connection to the postgres database.
182
183 ### Submission
184
185 Profile | Effect
186 --------------------------------------------------|-------------
187 `dev` | Turns the log level to `DEBUG`.
188 `cloud` | Removes default values for the `datasource` configuration.
189 `disable-ssl-server` | Disables SSL for the submission endpoint.
190 `disable-ssl-client-postgres` | Disables SSL with a pinned certificate for the connection to the postgres database.
191 `disable-ssl-client-verification` | Disables SSL with a pinned certificate for the connection to the verification server.
192 `disable-ssl-client-verification-verify-hostname` | Disables the verification of the SSL hostname for the connection to the verification server.
193
194 ## Documentation
195
196 The full documentation for the Corona-Warn-App can be found in the [cwa-documentation](https://github.com/corona-warn-app/cwa-documentation) repository. The documentation repository contains technical documents, architecture information, and whitepapers related to this implementation.
197
198 ## Support and Feedback
199
200 The following channels are available for discussions, feedback, and support requests:
201
202 | Type | Channel |
203 | ------------------------ | ------------------------------------------------------ |
204 | **General Discussion** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="General Discussion"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/question.svg?style=flat-square"></a> </a> |
205 | **Concept Feedback** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="Open Concept Feedback"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/architecture.svg?style=flat-square"></a> |
206 | **Backend Issue** | <a href="https://github.com/corona-warn-app/cwa-server/issues/new/choose" title="Open Backend Issue"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat-square"></a> |
207 | **Other Requests** | <a href="mailto:[email protected]" title="Email CWA Team"><img src="https://img.shields.io/badge/email-CWA%20team-green?logo=mail.ru&style=flat-square&logoColor=white"></a> |
208
209 ## How to Contribute
210
211 Contribution and feedback are 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.
212
213 ## Contributors
214
215 The German government has asked SAP and Deutsche Telekom to develop the Corona-Warn-App for Germany as open source software. Deutsche Telekom is providing the network and mobile technology and will operate and run the backend for the app in a safe, scalable and stable manner. SAP is responsible for the app development, its framework and the underlying platform. Therefore, development teams of SAP and Deutsche Telekom are contributing to this project. At the same time 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.
216
217 ## Repositories
218
219 The following public repositories are currently available for the Corona-Warn-App:
220
221 | Repository | Description |
222 | ------------------- | --------------------------------------------------------------------- |
223 | [cwa-documentation] | Project overview, general documentation, and white papers |
224 | [cwa-server] | Backend implementation for the Apple/Google exposure notification API|
225 | [cwa-verification-server] | Backend implementation of the verification process|
226
227 [cwa-documentation]: https://github.com/corona-warn-app/cwa-documentation
228 [cwa-server]: https://github.com/corona-warn-app/cwa-server
229 [cwa-verification-server]: https://github.com/corona-warn-app/cwa-verification-server
230 [Postgres]: https://www.postgresql.org/
231 [HSQLDB]: http://hsqldb.org/
232 [Zenko CloudServer]: https://github.com/scality/cloudserver
233
234 ## Licensing
235
236 Copyright (c) 2020 SAP SE or an SAP affiliate company.
237
238 Licensed under the **Apache License, Version 2.0** (the "License"); you may not use this file except in compliance with the License.
239
240 You may obtain a copy of the License at <https://www.apache.org/licenses/LICENSE-2.0>.
241
242 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.
243
[end of README.md]
[start of /dev/null]
1
[end of /dev/null]
[start of common/persistence/src/main/java/app/coronawarn/server/common/persistence/domain/DiagnosisKey.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.common.persistence.domain;
22
23 import static java.time.ZoneOffset.UTC;
24
25 import app.coronawarn.server.common.persistence.domain.DiagnosisKeyBuilders.Builder;
26 import app.coronawarn.server.common.persistence.domain.validation.ValidRollingStartIntervalNumber;
27 import java.time.Instant;
28 import java.time.LocalDateTime;
29 import java.util.Arrays;
30 import java.util.Objects;
31 import java.util.Set;
32 import javax.persistence.Column;
33 import javax.persistence.Entity;
34 import javax.persistence.Id;
35 import javax.persistence.Table;
36 import javax.validation.ConstraintViolation;
37 import javax.validation.Validation;
38 import javax.validation.Validator;
39 import javax.validation.constraints.Size;
40 import org.hibernate.validator.constraints.Range;
41
42 /**
43 * A key generated for advertising over a window of time.
44 */
45 @Entity
46 @Table(name = "diagnosis_key")
47 public class DiagnosisKey {
48
49 /**
50 * According to "Setting Up an Exposure Notification Server" by Apple, exposure notification servers are expected to
51 * reject any diagnosis keys that do not have a rolling period of a certain fixed value. See
52 * https://developer.apple.com/documentation/exposurenotification/setting_up_an_exposure_notification_server
53 */
54 public static final int EXPECTED_ROLLING_PERIOD = 144;
55
56 private static final Validator VALIDATOR = Validation.buildDefaultValidatorFactory().getValidator();
57
58 @Id
59 @Size(min = 16, max = 16, message = "Key data must be a byte array of length 16.")
60 @Column(unique = true)
61 private byte[] keyData;
62
63 @ValidRollingStartIntervalNumber
64 private int rollingStartIntervalNumber;
65
66 @Range(min = EXPECTED_ROLLING_PERIOD, max = EXPECTED_ROLLING_PERIOD,
67 message = "Rolling period must be " + EXPECTED_ROLLING_PERIOD + ".")
68 private int rollingPeriod;
69
70 @Range(min = 0, max = 8, message = "Risk level must be between 0 and 8.")
71 private int transmissionRiskLevel;
72
73 private long submissionTimestamp;
74
75 protected DiagnosisKey() {
76 }
77
78 /**
79 * Should be called by builders.
80 */
81 DiagnosisKey(byte[] keyData, int rollingStartIntervalNumber, int rollingPeriod,
82 int transmissionRiskLevel, long submissionTimestamp) {
83 this.keyData = keyData;
84 this.rollingStartIntervalNumber = rollingStartIntervalNumber;
85 this.rollingPeriod = rollingPeriod;
86 this.transmissionRiskLevel = transmissionRiskLevel;
87 this.submissionTimestamp = submissionTimestamp;
88 }
89
90 /**
91 * Returns a DiagnosisKeyBuilder instance. A {@link DiagnosisKey} can then be build by either providing the required
92 * member values or by passing the respective protocol buffer object.
93 *
94 * @return DiagnosisKeyBuilder instance.
95 */
96 public static Builder builder() {
97 return new DiagnosisKeyBuilder();
98 }
99
100 /**
101 * Returns the diagnosis key.
102 */
103 public byte[] getKeyData() {
104 return keyData;
105 }
106
107 /**
108 * Returns a number describing when a key starts. It is equal to startTimeOfKeySinceEpochInSecs / (60 * 10).
109 */
110 public int getRollingStartIntervalNumber() {
111 return rollingStartIntervalNumber;
112 }
113
114 /**
115 * Returns a number describing how long a key is valid. It is expressed in increments of 10 minutes (e.g. 144 for 24
116 * hours).
117 */
118 public int getRollingPeriod() {
119 return rollingPeriod;
120 }
121
122 /**
123 * Returns the risk of transmission associated with the person this key came from.
124 */
125 public int getTransmissionRiskLevel() {
126 return transmissionRiskLevel;
127 }
128
129 /**
130 * Returns the timestamp associated with the submission of this {@link DiagnosisKey} as hours since epoch.
131 */
132 public long getSubmissionTimestamp() {
133 return submissionTimestamp;
134 }
135
136 /**
137 * Checks if this diagnosis key falls into the period between now, and the retention threshold.
138 *
139 * @param daysToRetain the number of days before a key is outdated
140 * @return true, if the rolling start interval number is within the time between now, and the given days to retain
141 * @throws IllegalArgumentException if {@code daysToRetain} is negative.
142 */
143 public boolean isYoungerThanRetentionThreshold(int daysToRetain) {
144 if (daysToRetain < 0) {
145 throw new IllegalArgumentException("Retention threshold must be greater or equal to 0.");
146 }
147 long threshold = LocalDateTime
148 .ofInstant(Instant.now(), UTC)
149 .minusDays(daysToRetain)
150 .toEpochSecond(UTC) / (60 * 10);
151
152 return this.rollingStartIntervalNumber >= threshold;
153 }
154
155 /**
156 * Gets any constraint violations that this key might incorporate.
157 *
158 * <p><ul>
159 * <li>Risk level must be between 0 and 8
160 * <li>Rolling start interval number must be greater than 0
161 * <li>Rolling start number cannot be in the future
162 * <li>Rolling period must be positive number
163 * <li>Key data must be byte array of length 16
164 * </ul>
165 *
166 * @return A set of constraint violations of this key.
167 */
168 public Set<ConstraintViolation<DiagnosisKey>> validate() {
169 return VALIDATOR.validate(this);
170 }
171
172 @Override
173 public boolean equals(Object o) {
174 if (this == o) {
175 return true;
176 }
177 if (o == null || getClass() != o.getClass()) {
178 return false;
179 }
180 DiagnosisKey that = (DiagnosisKey) o;
181 return rollingStartIntervalNumber == that.rollingStartIntervalNumber
182 && rollingPeriod == that.rollingPeriod
183 && transmissionRiskLevel == that.transmissionRiskLevel
184 && submissionTimestamp == that.submissionTimestamp
185 && Arrays.equals(keyData, that.keyData);
186 }
187
188 @Override
189 public int hashCode() {
190 int result = Objects
191 .hash(rollingStartIntervalNumber, rollingPeriod, transmissionRiskLevel, submissionTimestamp);
192 result = 31 * result + Arrays.hashCode(keyData);
193 return result;
194 }
195 }
196
[end of common/persistence/src/main/java/app/coronawarn/server/common/persistence/domain/DiagnosisKey.java]
[start of common/persistence/src/main/java/app/coronawarn/server/common/persistence/domain/DiagnosisKeyBuilder.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.common.persistence.domain;
22
23 import static app.coronawarn.server.common.persistence.domain.DiagnosisKeyBuilders.Builder;
24 import static app.coronawarn.server.common.persistence.domain.DiagnosisKeyBuilders.FinalBuilder;
25 import static app.coronawarn.server.common.persistence.domain.DiagnosisKeyBuilders.RollingStartIntervalNumberBuilder;
26 import static app.coronawarn.server.common.persistence.domain.DiagnosisKeyBuilders.TransmissionRiskLevelBuilder;
27
28 import app.coronawarn.server.common.persistence.exception.InvalidDiagnosisKeyException;
29 import app.coronawarn.server.common.protocols.external.exposurenotification.TemporaryExposureKey;
30 import java.time.Instant;
31 import java.util.Set;
32 import java.util.stream.Collectors;
33 import javax.validation.ConstraintViolation;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36
37 /**
38 * An instance of this builder can be retrieved by calling {@link DiagnosisKey#builder()}. A {@link DiagnosisKey} can
39 * then be build by either providing the required member values or by passing the respective protocol buffer object.
40 */
41 public class DiagnosisKeyBuilder implements
42 Builder, RollingStartIntervalNumberBuilder, TransmissionRiskLevelBuilder, FinalBuilder {
43
44 private static final Logger logger = LoggerFactory.getLogger(DiagnosisKeyBuilder.class);
45
46 private byte[] keyData;
47 private int rollingStartIntervalNumber;
48 private int rollingPeriod = DiagnosisKey.EXPECTED_ROLLING_PERIOD;
49 private int transmissionRiskLevel;
50 private long submissionTimestamp = -1L;
51
52 DiagnosisKeyBuilder() {
53 }
54
55 @Override
56 public RollingStartIntervalNumberBuilder withKeyData(byte[] keyData) {
57 this.keyData = keyData;
58 return this;
59 }
60
61 @Override
62 public TransmissionRiskLevelBuilder withRollingStartIntervalNumber(int rollingStartIntervalNumber) {
63 this.rollingStartIntervalNumber = rollingStartIntervalNumber;
64 return this;
65 }
66
67 @Override
68 public FinalBuilder withTransmissionRiskLevel(int transmissionRiskLevel) {
69 this.transmissionRiskLevel = transmissionRiskLevel;
70 return this;
71 }
72
73 @Override
74 public FinalBuilder fromProtoBuf(TemporaryExposureKey protoBufObject) {
75 return this
76 .withKeyData(protoBufObject.getKeyData().toByteArray())
77 .withRollingStartIntervalNumber(protoBufObject.getRollingStartIntervalNumber())
78 .withTransmissionRiskLevel(protoBufObject.getTransmissionRiskLevel())
79 .withRollingPeriod(protoBufObject.getRollingPeriod());
80 }
81
82 @Override
83 public FinalBuilder withSubmissionTimestamp(long submissionTimestamp) {
84 this.submissionTimestamp = submissionTimestamp;
85 return this;
86 }
87
88 @Override
89 public FinalBuilder withRollingPeriod(int rollingPeriod) {
90 this.rollingPeriod = rollingPeriod;
91 return this;
92 }
93
94 @Override
95 public DiagnosisKey build() {
96 if (submissionTimestamp < 0) {
97 // hours since epoch
98 submissionTimestamp = Instant.now().getEpochSecond() / 3600L;
99 }
100
101 var diagnosisKey = new DiagnosisKey(
102 keyData, rollingStartIntervalNumber, rollingPeriod, transmissionRiskLevel, submissionTimestamp);
103 return throwIfValidationFails(diagnosisKey);
104 }
105
106 private DiagnosisKey throwIfValidationFails(DiagnosisKey diagnosisKey) {
107 Set<ConstraintViolation<DiagnosisKey>> violations = diagnosisKey.validate();
108
109 if (!violations.isEmpty()) {
110 String violationsMessage = violations.stream()
111 .map(violation -> String.format("%s Invalid Value: %s", violation.getMessage(), violation.getInvalidValue()))
112 .collect(Collectors.toList()).toString();
113 logger.debug(violationsMessage);
114 throw new InvalidDiagnosisKeyException(violationsMessage);
115 }
116
117 return diagnosisKey;
118 }
119 }
120
[end of common/persistence/src/main/java/app/coronawarn/server/common/persistence/domain/DiagnosisKeyBuilder.java]
[start of common/persistence/src/main/java/app/coronawarn/server/common/persistence/service/DiagnosisKeyService.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.common.persistence.service;
22
23 import static java.time.ZoneOffset.UTC;
24
25 import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
26 import app.coronawarn.server.common.persistence.repository.DiagnosisKeyRepository;
27 import io.micrometer.core.annotation.Timed;
28 import java.time.Instant;
29 import java.time.LocalDateTime;
30 import java.util.Collection;
31 import java.util.List;
32 import java.util.stream.Collectors;
33 import javax.validation.ConstraintViolation;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36 import org.springframework.data.domain.Sort;
37 import org.springframework.data.domain.Sort.Direction;
38 import org.springframework.stereotype.Component;
39 import org.springframework.transaction.annotation.Transactional;
40
41 @Component
42 public class DiagnosisKeyService {
43
44 private static final Logger logger = LoggerFactory.getLogger(DiagnosisKeyService.class);
45 private final DiagnosisKeyRepository keyRepository;
46
47 public DiagnosisKeyService(DiagnosisKeyRepository keyRepository) {
48 this.keyRepository = keyRepository;
49 }
50
51 /**
52 * Persists the specified collection of {@link DiagnosisKey} instances. If the key data of a particular diagnosis key
53 * already exists in the database, this diagnosis key is not persisted.
54 *
55 * @param diagnosisKeys must not contain {@literal null}.
56 * @throws IllegalArgumentException in case the given collection contains {@literal null}.
57 */
58 @Timed
59 @Transactional
60 public void saveDiagnosisKeys(Collection<DiagnosisKey> diagnosisKeys) {
61 for (DiagnosisKey diagnosisKey : diagnosisKeys) {
62 keyRepository.saveDoNothingOnConflict(
63 diagnosisKey.getKeyData(), diagnosisKey.getRollingStartIntervalNumber(), diagnosisKey.getRollingPeriod(),
64 diagnosisKey.getSubmissionTimestamp(), diagnosisKey.getTransmissionRiskLevel());
65 }
66 }
67
68 /**
69 * Returns all valid persisted diagnosis keys, sorted by their submission timestamp.
70 */
71 public List<DiagnosisKey> getDiagnosisKeys() {
72 List<DiagnosisKey> diagnosisKeys = keyRepository.findAll(Sort.by(Direction.ASC, "submissionTimestamp"));
73 List<DiagnosisKey> validDiagnosisKeys =
74 diagnosisKeys.stream().filter(DiagnosisKeyService::isDiagnosisKeyValid).collect(Collectors.toList());
75
76 int numberOfDiscardedKeys = diagnosisKeys.size() - validDiagnosisKeys.size();
77 logger.info("Retrieved {} diagnosis key(s). Discarded {} diagnosis key(s) from the result as invalid.",
78 diagnosisKeys.size(), numberOfDiscardedKeys);
79
80 return validDiagnosisKeys;
81 }
82
83 private static boolean isDiagnosisKeyValid(DiagnosisKey diagnosisKey) {
84 Collection<ConstraintViolation<DiagnosisKey>> violations = diagnosisKey.validate();
85 boolean isValid = violations.isEmpty();
86
87 if (!isValid) {
88 List<String> violationMessages =
89 violations.stream().map(ConstraintViolation::getMessage).collect(Collectors.toList());
90 logger.warn("Validation failed for diagnosis key from database. Violations: {}", violationMessages);
91 }
92
93 return isValid;
94 }
95
96 /**
97 * Deletes all diagnosis key entries which have a submission timestamp that is older than the specified number of
98 * days.
99 *
100 * @param daysToRetain the number of days until which diagnosis keys will be retained.
101 * @throws IllegalArgumentException if {@code daysToRetain} is negative.
102 */
103 @Transactional
104 public void applyRetentionPolicy(int daysToRetain) {
105 if (daysToRetain < 0) {
106 throw new IllegalArgumentException("Number of days to retain must be greater or equal to 0.");
107 }
108
109 long threshold = LocalDateTime
110 .ofInstant(Instant.now(), UTC)
111 .minusDays(daysToRetain)
112 .toEpochSecond(UTC) / 3600L;
113 int numberOfDeletions = keyRepository.deleteBySubmissionTimestampIsLessThanEqual(threshold);
114 logger.info("Deleted {} diagnosis key(s) with a submission timestamp older than {} day(s) ago.",
115 numberOfDeletions, daysToRetain);
116 }
117 }
118
[end of common/persistence/src/main/java/app/coronawarn/server/common/persistence/service/DiagnosisKeyService.java]
</code>
Here is an example of a patch file. It consists of changes to the code base. It specifies the file names, the line numbers of each change, and the removed and added lines. A single patch file can contain changes to multiple files.
<patch>
--- a/file.py
+++ b/file.py
@@ -1,27 +1,35 @@
def euclidean(a, b):
- while b:
- a, b = b, a % b
- return a
+ if b == 0:
+ return a
+ return euclidean(b, a % b)
def bresenham(x0, y0, x1, y1):
points = []
dx = abs(x1 - x0)
dy = abs(y1 - y0)
- sx = 1 if x0 < x1 else -1
- sy = 1 if y0 < y1 else -1
- err = dx - dy
+ x, y = x0, y0
+ sx = -1 if x0 > x1 else 1
+ sy = -1 if y0 > y1 else 1
- while True:
- points.append((x0, y0))
- if x0 == x1 and y0 == y1:
- break
- e2 = 2 * err
- if e2 > -dy:
+ if dx > dy:
+ err = dx / 2.0
+ while x != x1:
+ points.append((x, y))
err -= dy
- x0 += sx
- if e2 < dx:
- err += dx
- y0 += sy
+ if err < 0:
+ y += sy
+ err += dx
+ x += sx
+ else:
+ err = dy / 2.0
+ while y != y1:
+ points.append((x, y))
+ err -= dx
+ if err < 0:
+ x += sx
+ err += dy
+ y += sy
+ points.append((x, y))
return points
</patch>
I need you to solve the provded issue by generating a single patch file that I can apply directly to this repository using git apply. Please respond with a single patch file in the format shown above.
Respond below:
| corona-warn-app/cwa-server | 670560bd755a94fe8cf7dfea5bba13c9b64858ed | Add JPA range validator for submissionTimestamp of DiagnosisKey
DiagnosisKey uses a submissionTimestamp field of type long
https://github.com/corona-warn-app/cwa-server/blob/7059232b48d2507d142fe683fbebdda371a98652/common/persistence/src/main/java/app/coronawarn/server/common/persistence/domain/DiagnosisKey.java#L73
the value is actually the *hours* since epoch but there are no sanity checks on the value.
Just from reading the code you could e.g. easily think it's seconds since epoch and use it the wrong way without noticing at runtime.
Proposal:
* Add a JPA ConstraintValidator similar to ValidRollingStartIntervalNumberValidator which checks the value range to be greater or equal zero and not in the future (current hour since epoch rounded up)
* Add field javadoc to submissionTimestamp: "hours since epoch"
Expected Benefits:
* discard invalid data
* less potential for programming errors
| I could open a PR wit the proposal if you think it makes sense
the getter and Builder already do have javadoc "hours since epoch"
https://github.com/corona-warn-app/cwa-server/blob/master/common/persistence/src/main/java/app/coronawarn/server/common/persistence/domain/DiagnosisKeyBuilders.java#L80
so it's actually documented. Would still be nice to validate it though.
@jsievers makes sense. Please go ahead with a proposal PR. | 2020-06-13T22:50:51 | <patch>
diff --git a/common/persistence/src/main/java/app/coronawarn/server/common/persistence/domain/DiagnosisKey.java b/common/persistence/src/main/java/app/coronawarn/server/common/persistence/domain/DiagnosisKey.java
--- a/common/persistence/src/main/java/app/coronawarn/server/common/persistence/domain/DiagnosisKey.java
+++ b/common/persistence/src/main/java/app/coronawarn/server/common/persistence/domain/DiagnosisKey.java
@@ -24,6 +24,7 @@
import app.coronawarn.server.common.persistence.domain.DiagnosisKeyBuilders.Builder;
import app.coronawarn.server.common.persistence.domain.validation.ValidRollingStartIntervalNumber;
+import app.coronawarn.server.common.persistence.domain.validation.ValidSubmissionTimestamp;
import java.time.Instant;
import java.time.LocalDateTime;
import java.util.Arrays;
@@ -70,6 +71,7 @@ public class DiagnosisKey {
@Range(min = 0, max = 8, message = "Risk level must be between 0 and 8.")
private int transmissionRiskLevel;
+ @ValidSubmissionTimestamp
private long submissionTimestamp;
protected DiagnosisKey() {
diff --git a/common/persistence/src/main/java/app/coronawarn/server/common/persistence/domain/DiagnosisKeyBuilder.java b/common/persistence/src/main/java/app/coronawarn/server/common/persistence/domain/DiagnosisKeyBuilder.java
--- a/common/persistence/src/main/java/app/coronawarn/server/common/persistence/domain/DiagnosisKeyBuilder.java
+++ b/common/persistence/src/main/java/app/coronawarn/server/common/persistence/domain/DiagnosisKeyBuilder.java
@@ -24,6 +24,7 @@
import static app.coronawarn.server.common.persistence.domain.DiagnosisKeyBuilders.FinalBuilder;
import static app.coronawarn.server.common.persistence.domain.DiagnosisKeyBuilders.RollingStartIntervalNumberBuilder;
import static app.coronawarn.server.common.persistence.domain.DiagnosisKeyBuilders.TransmissionRiskLevelBuilder;
+import static app.coronawarn.server.common.persistence.domain.validation.ValidSubmissionTimestampValidator.SECONDS_PER_HOUR;
import app.coronawarn.server.common.persistence.exception.InvalidDiagnosisKeyException;
import app.coronawarn.server.common.protocols.external.exposurenotification.TemporaryExposureKey;
@@ -47,7 +48,7 @@ public class DiagnosisKeyBuilder implements
private int rollingStartIntervalNumber;
private int rollingPeriod = DiagnosisKey.EXPECTED_ROLLING_PERIOD;
private int transmissionRiskLevel;
- private long submissionTimestamp = -1L;
+ private Long submissionTimestamp = null;
DiagnosisKeyBuilder() {
}
@@ -93,9 +94,9 @@ public FinalBuilder withRollingPeriod(int rollingPeriod) {
@Override
public DiagnosisKey build() {
- if (submissionTimestamp < 0) {
+ if (submissionTimestamp == null) {
// hours since epoch
- submissionTimestamp = Instant.now().getEpochSecond() / 3600L;
+ submissionTimestamp = Instant.now().getEpochSecond() / SECONDS_PER_HOUR;
}
var diagnosisKey = new DiagnosisKey(
diff --git a/common/persistence/src/main/java/app/coronawarn/server/common/persistence/domain/validation/ValidSubmissionTimestamp.java b/common/persistence/src/main/java/app/coronawarn/server/common/persistence/domain/validation/ValidSubmissionTimestamp.java
new file mode 100644
--- /dev/null
+++ b/common/persistence/src/main/java/app/coronawarn/server/common/persistence/domain/validation/ValidSubmissionTimestamp.java
@@ -0,0 +1,58 @@
+/*-
+ * ---license-start
+ * Corona-Warn-App
+ * ---
+ * Copyright (C) 2020 SAP SE and all other contributors
+ * ---
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://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 for the specific language governing permissions and
+ * limitations under the License.
+ * ---license-end
+ */
+
+package app.coronawarn.server.common.persistence.domain.validation;
+
+import java.lang.annotation.Documented;
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+import javax.validation.Constraint;
+import javax.validation.Payload;
+
+@Constraint(validatedBy = ValidSubmissionTimestampValidator.class)
+@Target({ElementType.FIELD})
+@Retention(RetentionPolicy.RUNTIME)
+@Documented
+public @interface ValidSubmissionTimestamp {
+
+ /**
+ * Error message.
+ *
+ * @return the error message
+ */
+ String message() default "Submission timestamp (hours since epoch)"
+ + " must be greater or equal 0 and cannot be in the future.";
+
+ /**
+ * Groups.
+ *
+ * @return
+ */
+ Class<?>[] groups() default {};
+
+ /**
+ * Payload.
+ *
+ * @return
+ */
+ Class<? extends Payload>[] payload() default {};
+}
diff --git a/common/persistence/src/main/java/app/coronawarn/server/common/persistence/domain/validation/ValidSubmissionTimestampValidator.java b/common/persistence/src/main/java/app/coronawarn/server/common/persistence/domain/validation/ValidSubmissionTimestampValidator.java
new file mode 100644
--- /dev/null
+++ b/common/persistence/src/main/java/app/coronawarn/server/common/persistence/domain/validation/ValidSubmissionTimestampValidator.java
@@ -0,0 +1,38 @@
+/*-
+ * ---license-start
+ * Corona-Warn-App
+ * ---
+ * Copyright (C) 2020 SAP SE and all other contributors
+ * ---
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://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 for the specific language governing permissions and
+ * limitations under the License.
+ * ---license-end
+ */
+
+package app.coronawarn.server.common.persistence.domain.validation;
+
+import java.time.Instant;
+import java.util.concurrent.TimeUnit;
+import javax.validation.ConstraintValidator;
+import javax.validation.ConstraintValidatorContext;
+
+public class ValidSubmissionTimestampValidator
+ implements ConstraintValidator<ValidSubmissionTimestamp, Long> {
+
+ public static final long SECONDS_PER_HOUR = TimeUnit.HOURS.toSeconds(1);
+
+ @Override
+ public boolean isValid(Long submissionTimestamp, ConstraintValidatorContext constraintValidatorContext) {
+ long currentHoursSinceEpoch = Instant.now().getEpochSecond() / SECONDS_PER_HOUR;
+ return submissionTimestamp >= 0L && submissionTimestamp <= currentHoursSinceEpoch;
+ }
+}
diff --git a/common/persistence/src/main/java/app/coronawarn/server/common/persistence/service/DiagnosisKeyService.java b/common/persistence/src/main/java/app/coronawarn/server/common/persistence/service/DiagnosisKeyService.java
--- a/common/persistence/src/main/java/app/coronawarn/server/common/persistence/service/DiagnosisKeyService.java
+++ b/common/persistence/src/main/java/app/coronawarn/server/common/persistence/service/DiagnosisKeyService.java
@@ -20,6 +20,7 @@
package app.coronawarn.server.common.persistence.service;
+import static app.coronawarn.server.common.persistence.domain.validation.ValidSubmissionTimestampValidator.SECONDS_PER_HOUR;
import static java.time.ZoneOffset.UTC;
import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
@@ -109,7 +110,7 @@ public void applyRetentionPolicy(int daysToRetain) {
long threshold = LocalDateTime
.ofInstant(Instant.now(), UTC)
.minusDays(daysToRetain)
- .toEpochSecond(UTC) / 3600L;
+ .toEpochSecond(UTC) / SECONDS_PER_HOUR;
int numberOfDeletions = keyRepository.deleteBySubmissionTimestampIsLessThanEqual(threshold);
logger.info("Deleted {} diagnosis key(s) with a submission timestamp older than {} day(s) ago.",
numberOfDeletions, daysToRetain);
</patch> | diff --git a/common/persistence/src/test/java/app/coronawarn/server/common/persistence/domain/DiagnosisKeyBuilderTest.java b/common/persistence/src/test/java/app/coronawarn/server/common/persistence/domain/DiagnosisKeyBuilderTest.java
--- a/common/persistence/src/test/java/app/coronawarn/server/common/persistence/domain/DiagnosisKeyBuilderTest.java
+++ b/common/persistence/src/test/java/app/coronawarn/server/common/persistence/domain/DiagnosisKeyBuilderTest.java
@@ -20,6 +20,8 @@
package app.coronawarn.server.common.persistence.domain;
+import static app.coronawarn.server.common.persistence.domain.validation.ValidSubmissionTimestampValidator.SECONDS_PER_HOUR;
+import static app.coronawarn.server.common.persistence.service.DiagnosisKeyServiceTestHelper.buildDiagnosisKeyForSubmissionTimestamp;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.catchThrowable;
@@ -28,6 +30,7 @@
import app.coronawarn.server.common.protocols.external.exposurenotification.TemporaryExposureKey;
import com.google.protobuf.ByteString;
import java.nio.charset.StandardCharsets;
+import java.time.Duration;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneOffset;
@@ -189,6 +192,33 @@ void keyDataDoesNotThrowOnValid() {
.doesNotThrowAnyException();
}
+ @ParameterizedTest
+ @ValueSource(longs = {-1L, Long.MAX_VALUE})
+ void submissionTimestampMustBeValid(long submissionTimestamp) {
+ assertThat(
+ catchThrowable(() -> buildDiagnosisKeyForSubmissionTimestamp(submissionTimestamp)))
+ .isInstanceOf(InvalidDiagnosisKeyException.class);
+ }
+
+ @Test
+ void submissionTimestampMustNotBeInTheFuture() {
+ assertThat(catchThrowable(
+ () -> buildDiagnosisKeyForSubmissionTimestamp(getCurrentHoursSinceEpoch() + 1)))
+ .isInstanceOf(InvalidDiagnosisKeyException.class);
+ assertThat(catchThrowable(() -> buildDiagnosisKeyForSubmissionTimestamp(
+ Instant.now().getEpochSecond() /* accidentally forgot to divide by SECONDS_PER_HOUR */)))
+ .isInstanceOf(InvalidDiagnosisKeyException.class);
+ }
+
+ @Test
+ void submissionTimestampDoesNotThrowOnValid() {
+ assertThatCode(() -> buildDiagnosisKeyForSubmissionTimestamp(0L)).doesNotThrowAnyException();
+ assertThatCode(() -> buildDiagnosisKeyForSubmissionTimestamp(getCurrentHoursSinceEpoch())).doesNotThrowAnyException();
+ assertThatCode(
+ () -> buildDiagnosisKeyForSubmissionTimestamp(Instant.now().minus(Duration.ofHours(2)).getEpochSecond() / SECONDS_PER_HOUR))
+ .doesNotThrowAnyException();
+ }
+
private DiagnosisKey keyWithKeyData(byte[] expKeyData) {
return DiagnosisKey.builder()
.withKeyData(expKeyData)
@@ -223,7 +253,7 @@ private void assertDiagnosisKeyEquals(DiagnosisKey actDiagnosisKey) {
}
private long getCurrentHoursSinceEpoch() {
- return Instant.now().getEpochSecond() / 3600L;
+ return Instant.now().getEpochSecond() / SECONDS_PER_HOUR;
}
private void assertDiagnosisKeyEquals(DiagnosisKey actDiagnosisKey, long expSubmissionTimestamp) {
diff --git a/common/persistence/src/test/java/app/coronawarn/server/common/persistence/service/DiagnosisKeyServiceTest.java b/common/persistence/src/test/java/app/coronawarn/server/common/persistence/service/DiagnosisKeyServiceTest.java
--- a/common/persistence/src/test/java/app/coronawarn/server/common/persistence/service/DiagnosisKeyServiceTest.java
+++ b/common/persistence/src/test/java/app/coronawarn/server/common/persistence/service/DiagnosisKeyServiceTest.java
@@ -21,6 +21,8 @@
package app.coronawarn.server.common.persistence.service;
import static app.coronawarn.server.common.persistence.service.DiagnosisKeyServiceTestHelper.assertDiagnosisKeysEqual;
+import static app.coronawarn.server.common.persistence.service.DiagnosisKeyServiceTestHelper.buildDiagnosisKeyForDateTime;
+import static app.coronawarn.server.common.persistence.service.DiagnosisKeyServiceTestHelper.buildDiagnosisKeyForSubmissionTimestamp;
import static java.time.ZoneOffset.UTC;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
@@ -33,7 +35,6 @@
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
-import java.util.Random;
import org.assertj.core.util.Lists;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.DisplayName;
@@ -171,19 +172,4 @@ void shouldNotUpdateExistingKey() {
assertThat(actKeys.size()).isEqualTo(1);
assertThat(actKeys.iterator().next().getTransmissionRiskLevel()).isEqualTo(2);
}
-
- public static DiagnosisKey buildDiagnosisKeyForSubmissionTimestamp(long submissionTimeStamp) {
- byte[] randomBytes = new byte[16];
- Random random = new Random(submissionTimeStamp);
- random.nextBytes(randomBytes);
- return DiagnosisKey.builder()
- .withKeyData(randomBytes)
- .withRollingStartIntervalNumber(600)
- .withTransmissionRiskLevel(2)
- .withSubmissionTimestamp(submissionTimeStamp).build();
- }
-
- public static DiagnosisKey buildDiagnosisKeyForDateTime(OffsetDateTime dateTime) {
- return buildDiagnosisKeyForSubmissionTimestamp(dateTime.toEpochSecond() / 3600);
- }
}
diff --git a/common/persistence/src/test/java/app/coronawarn/server/common/persistence/service/DiagnosisKeyServiceTestHelper.java b/common/persistence/src/test/java/app/coronawarn/server/common/persistence/service/DiagnosisKeyServiceTestHelper.java
--- a/common/persistence/src/test/java/app/coronawarn/server/common/persistence/service/DiagnosisKeyServiceTestHelper.java
+++ b/common/persistence/src/test/java/app/coronawarn/server/common/persistence/service/DiagnosisKeyServiceTestHelper.java
@@ -23,7 +23,9 @@
import static org.assertj.core.api.Assertions.assertThat;
import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
+import java.time.OffsetDateTime;
import java.util.List;
+import java.util.Random;
public class DiagnosisKeyServiceTestHelper {
@@ -48,4 +50,19 @@ public static void assertDiagnosisKeysEqual(List<DiagnosisKey> expKeys,
.isEqualTo(expKey.getSubmissionTimestamp());
}
}
+
+ public static DiagnosisKey buildDiagnosisKeyForSubmissionTimestamp(long submissionTimeStamp) {
+ byte[] randomBytes = new byte[16];
+ Random random = new Random(submissionTimeStamp);
+ random.nextBytes(randomBytes);
+ return DiagnosisKey.builder()
+ .withKeyData(randomBytes)
+ .withRollingStartIntervalNumber(600)
+ .withTransmissionRiskLevel(2)
+ .withSubmissionTimestamp(submissionTimeStamp).build();
+ }
+
+ public static DiagnosisKey buildDiagnosisKeyForDateTime(OffsetDateTime dateTime) {
+ return buildDiagnosisKeyForSubmissionTimestamp(dateTime.toEpochSecond() / 3600);
+ }
}
| ||||
corona-warn-app__cwa-server-572 | You will be provided with a partial code base and an issue statement explaining a problem to resolve.
<issue>
S3ClientWrapper getObjects: Not all objects could be received
<!--
Thanks for reporting a bug 🙌 ❤️
Before opening a new issue, please make sure that we do not have any duplicates already open. You can ensure this by searching the issue list for this repository. If there is a duplicate, please close your issue and add a comment to the existing issue instead.
Also, be sure to check our documentation first: <URL>
-->
## Describe the bug
https://github.com/corona-warn-app/cwa-server/blob/a953c054f8b4dc97d6a40525c5c3d5aa4d867394/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/client/S3ClientWrapper.java#L83
It is possible that not all objects are received, because the **listObjectsV2(ListObjectsV2Request listObjectsV2Request)** method limits them up to 1000.
Javadoc [listObjectsV2](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/s3/S3Client.html#listObjectsV2-software.amazon.awssdk.services.s3.model.ListObjectsV2Request-)
> Returns some or all (up to 1,000) of the objects in a bucket.
## Possible Fix
1. Checking the response for more data with the **isTruncated** method.
JavaDoc [isTruncated](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/s3/model/ListObjectsV2Response.html#isTruncated--)
> Set to false if all of the results were returned. Set to true if more keys are available to return. If the number of results exceeds that specified by MaxKeys, all of the results might not be returned.
2. When the response is truncated, calling the **nextContinuationToken** method for the next token.
JavaDoc [nextContinuationToken](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/s3/model/ListObjectsV2Response.html#nextContinuationToken--)
> NextContinuationToken is sent when isTruncated is true, which means there are more keys in the bucket that can be listed. The next list requests to Amazon S3 can be continued with this NextContinuationToken.
3. Build a new ListObjectsV2Request with the **continuationToken** and call **listObjectsV2** again
JavaDoc [continuationToken](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/s3/model/ListObjectsV2Request.Builder.html#continuationToken-java.lang.String-)
> ContinuationToken indicates Amazon S3 that the list is being continued on this bucket with a token. ContinuationToken is obfuscated and is not a real key.
4. Repeat everything until isTruncate is false.
Here is a pretty good example from AWS. They use a different S3Client, but it is very similar to the one you use. ([source](https://docs.aws.amazon.com/AmazonS3/latest/dev/ListingObjectKeysUsingJava.html))
```java
import com.amazonaws.AmazonServiceException;
import com.amazonaws.SdkClientException;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.ListObjectsV2Request;
import com.amazonaws.services.s3.model.ListObjectsV2Result;
import com.amazonaws.services.s3.model.S3ObjectSummary;
import java.io.IOException;
public class ListKeys {
public static void main(String[] args) throws IOException {
Regions clientRegion = Regions.DEFAULT_REGION;
String bucketName = "*** Bucket name ***";
try {
AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
.withCredentials(new ProfileCredentialsProvider())
.withRegion(clientRegion)
.build();
System.out.println("Listing objects");
// maxKeys is set to 2 to demonstrate the use of
// ListObjectsV2Result.getNextContinuationToken()
ListObjectsV2Request req = new ListObjectsV2Request().withBucketName(bucketName).withMaxKeys(2);
ListObjectsV2Result result;
do {
result = s3Client.listObjectsV2(req);
for (S3ObjectSummary objectSummary : result.getObjectSummaries()) {
System.out.printf(" - %s (size: %d)\n", objectSummary.getKey(), objectSummary.getSize());
}
// If there are more than maxKeys keys in the bucket, get a continuation token
// and list the next objects.
String token = result.getNextContinuationToken();
System.out.println("Next Continuation Token: " + token);
req.setContinuationToken(token);
} while (result.isTruncated());
} catch (AmazonServiceException e) {
// The call was transmitted successfully, but Amazon S3 couldn't process
// it, so it returned an error response.
e.printStackTrace();
} catch (SdkClientException e) {
// Amazon S3 couldn't be contacted for a response, or the client
// couldn't parse the response from Amazon S3.
e.printStackTrace();
}
}
}
``
</issue>
<code>
[start of README.md]
1 <!-- markdownlint-disable MD041 -->
2 <h1 align="center">
3 Corona-Warn-App Server
4 </h1>
5
6 <p align="center">
7 <a href="https://github.com/corona-warn-app/cwa-server/commits/" title="Last Commit"><img src="https://img.shields.io/github/last-commit/corona-warn-app/cwa-server?style=flat"></a>
8 <a href="https://github.com/corona-warn-app/cwa-server/issues" title="Open Issues"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat"></a>
9 <a href="https://circleci.com/gh/corona-warn-app/cwa-server" title="Build Status"><img src="https://circleci.com/gh/corona-warn-app/cwa-server.svg?style=shield&circle-token=4ab059989d10709df19eb4b98ab7c121a25e981a"></a>
10 <a href="https://sonarcloud.io/dashboard?id=corona-warn-app_cwa-server" title="Quality Gate"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=alert_status"></a>
11 <a href="https://sonarcloud.io/component_measures?id=corona-warn-app_cwa-server&metric=Coverage&view=list" title="Coverage"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=coverage"></a>
12 <a href="https://github.com/corona-warn-app/cwa-server/blob/master/LICENSE" title="License"><img src="https://img.shields.io/badge/License-Apache%202.0-green.svg?style=flat"></a>
13 </p>
14
15 <p align="center">
16 <a href="#development">Development</a> •
17 <a href="#service-apis">Service APIs</a> •
18 <a href="#documentation">Documentation</a> •
19 <a href="#support-and-feedback">Support</a> •
20 <a href="#how-to-contribute">Contribute</a> •
21 <a href="#contributors">Contributors</a> •
22 <a href="#repositories">Repositories</a> •
23 <a href="#licensing">Licensing</a>
24 </p>
25
26 The goal of this project is to develop the official Corona-Warn-App for Germany based on the exposure notification API from [Apple](https://www.apple.com/covid19/contacttracing/) and [Google](https://www.google.com/covid19/exposurenotifications/). The apps (for both iOS and Android) use Bluetooth technology to exchange anonymous encrypted data with other mobile phones (on which the app is also installed) in the vicinity of an app user's phone. The data is stored locally on each user's device, preventing authorities or other parties from accessing or controlling the data. This repository contains the **implementation of the server for encryption keys** for the Corona-Warn-App.
27
28 In this documentation, Corona-Warn-App services are also referred to as CWA services.
29
30 ## Architecture Overview
31
32 You can find the architecture overview [here](/docs/ARCHITECTURE.md), which will give you
33 a good starting point in how the backend services interact with other services, and what purpose
34 they serve.
35
36 ## Development
37
38 After you've checked out this repository, you can run the application in one of the following ways:
39
40 * As a [Docker](https://www.docker.com/)-based deployment on your local machine. You can run either:
41 * Single components using the respective Dockerfile or
42 * The full backend using the Docker Compose (which is considered the most convenient way)
43 * As a [Maven](https://maven.apache.org)-based build on your local machine.
44 If you want to develop something in a single component, this approach is preferable.
45
46 ### Docker-Based Deployment
47
48 If you want to use Docker-based deployment, you need to install Docker on your local machine. For more information about downloading and installing Docker, see the [official Docker documentation](https://docs.docker.com/get-docker/).
49
50 #### Running the Full CWA Backend Using Docker Compose
51
52 For your convenience, a full setup including the generation of test data has been prepared using [Docker Compose](https://docs.docker.com/compose/reference/overview/). To build the backend services, run ```docker-compose build``` in the repository's root directory. A default configuration file can be found under ```.env``` in the root folder of the repository. The default values for the local Postgres and Zenko Cloudserver should be changed in this file before docker-compose is run.
53
54 Once the services are built, you can start the whole backend using ```docker-compose up```.
55 The distribution service runs once and then finishes. If you want to trigger additional distribution runs, run ```docker-compose run distribution```.
56
57 The docker-compose contains the following services:
58
59 Service | Description | Endpoint and Default Credentials
60 ------------------|-------------|-----------
61 submission | The Corona-Warn-App submission service | `http://localhost:8000` <br> `http://localhost:8006` (for actuator endpoint)
62 distribution | The Corona-Warn-App distribution service | NO ENDPOINT
63 postgres | A [postgres] database installation | `localhost:8001` <br> `postgres:5432` (from containerized pgadmin) <br> Username: postgres <br> Password: postgres
64 pgadmin | A [pgadmin](https://www.pgadmin.org/) installation for the postgres database | `http://localhost:8002` <br> Username: [email protected] <br> Password: password
65 cloudserver | [Zenko CloudServer] is a S3-compliant object store | `http://localhost:8003/` <br> Access key: accessKey1 <br> Secret key: verySecretKey1
66 verification-fake | A very simple fake implementation for the tan verification. | `http://localhost:8004/version/v1/tan/verify` <br> The only valid tan is `edc07f08-a1aa-11ea-bb37-0242ac130002`.
67
68 ##### Known Limitation
69
70 In rare cases the docker-compose runs into a timing issue if the distribution service starts before the bucket of the objectstore was created. This is not a big issue as you can simply run ```docker-compose run distribution``` to trigger additional distribution runs after the objectstore was initialized.
71
72 #### Running Single CWA Services Using Docker
73
74 If you would like to build and run a single CWA service, it's considered easiest to run them in a Docker environment. You can do this using the script provided in the respective CWA service directory. The Docker script first builds the CWA service and then creates an image for the runtime, which means that there are no additional dependencies for you to install.
75
76 To build and run the distribution service, run the following command:
77
78 ```bash
79 ./services/distribution/build_and_run.sh
80 ```
81
82 To build and run the submission service, run the following command:
83
84 ```bash
85 ./services/submission/build_and_run.sh
86 ```
87
88 The submission service is available on [localhost:8080](http://localhost:8080 ).
89
90 ### Maven-Based Build
91
92 If you want to actively develop in one of the CWA services, the Maven-based runtime is most suitable.
93 To prepare your machine to run the CWA project locally, we recommend that you first ensure that you've installed the following:
94
95 * Minimum JDK Version 11: [OpenJDK](https://openjdk.java.net/) / [SapMachine](https://sap.github.io/SapMachine/)
96 * [Maven 3.6](https://maven.apache.org/)
97 * [Postgres]
98 * [Zenko CloudServer]
99
100 If you are already running a local Postgres, you need to create a database `cwa` and run the following setup scripts:
101
102 * Create the different CWA roles first by executing [create-roles.sql](setup/create-roles.sql).
103 * Create local database users for the specific roles by running [create-users.sql](./local-setup/create-users.sql).
104 * It is recommended to also run [enable-test-data-docker-compose.sql](./local-setup/enable-test-data-docker-compose.sql)
105 , which enables the test data generation profile. If you already had CWA running before and an existing `diagnosis-key`
106 table on your database, you need to run [enable-test-data.sql](./local-setup/enable-test-data.sql) instead.
107
108 You can also use `docker-compose` to start Postgres and Zenko. If you do that, you have to
109 set the following environment-variables when running the Spring project:
110
111 For the distribution module:
112
113 ```bash
114 POSTGRESQL_SERVICE_PORT=8001
115 VAULT_FILESIGNING_SECRET=</path/to/your/private_key>
116 SPRING_PROFILES_ACTIVE=signature-dev,disable-ssl-client-postgres
117 ```
118
119 For the submission module:
120
121 ```bash
122 POSTGRESQL_SERVICE_PORT=8001
123 SPRING_PROFILES_ACTIVE=disable-ssl-server,disable-ssl-client-postgres,disable-ssl-client-verification,disable-ssl-client-verification-verify-hostname
124 ```
125
126 #### Configure
127
128 After you made sure that the specified dependencies are running, configure them in the respective configuration files.
129
130 * Configure the Postgres connection in the [submission config](./services/submission/src/main/resources/application.yaml) and in the [distribution config](./services/distribution/src/main/resources/application.yaml)
131 * Configure the S3 compatible object storage in the [distribution config](./services/distribution/src/main/resources/application.yaml)
132 * Configure the private key for the distribution service, the path need to be prefixed with `file:`
133 * `VAULT_FILESIGNING_SECRET` should be the path to the private key, example available in `<repo-root>/docker-compose-test-secrets/private.pem`
134
135 #### Build
136
137 After you've checked out the repository, to build the project, run ```mvn install``` in your base directory.
138
139 #### Run
140
141 Navigate to the service you want to start and run the spring-boot:run target. The configured Postgres and the configured S3 compliant object storage are used as default. When you start the submission service, the endpoint is available on your local port 8080.
142
143 If you want to start the submission service, for example, you start it as follows:
144
145 ```bash
146 cd services/submission/
147 mvn spring-boot:run
148 ```
149
150 #### Debugging
151
152 To enable the `DEBUG` log level, you can run the application using the Spring `dev` profile.
153
154 ```bash
155 mvn spring-boot:run -Dspring.profiles.active=dev
156 ```
157
158 To be able to set breakpoints (e.g. in IntelliJ), it may be necessary to use the ```-Dspring-boot.run.fork=false``` parameter.
159
160 ## Service APIs
161
162 The API that is being exposed by the backend services is documented in an [OpenAPI](https://www.openapis.org/) specification. The specification files are available at the following locations:
163
164 Service | OpenAPI Specification
165 --------------------------|-------------
166 Submission Service | [services/submission/api_v1.json](https://github.com/corona-warn-app/cwa-server/raw/master/services/submission/api_v1.json)
167 Distribution Service | [services/distribution/api_v1.json](https://github.com/corona-warn-app/cwa-server/raw/master/services/distribution/api_v1.json)
168
169 ## Spring Profiles
170
171 ### Distribution
172
173 Profile | Effect
174 ------------------------------|-------------
175 `dev` | Turns the log level to `DEBUG`.
176 `cloud` | Removes default values for the `datasource` and `objectstore` configurations.
177 `demo` | Includes incomplete days and hours into the distribution run, thus creating aggregates for the current day and the current hour (and including both in the respective indices). When running multiple distributions in one hour with this profile, the date aggregate for today and the hours aggregate for the current hour will be updated and overwritten. This profile also turns off the expiry policy (Keys must be expired for at least 2 hours before distribution) and the shifting policy (there must be at least 140 keys in a distribution).
178 `testdata` | Causes test data to be inserted into the database before each distribution run. By default, around 1000 random diagnosis keys will be generated per hour. If there are no diagnosis keys in the database yet, random keys will be generated for every hour from the beginning of the retention period (14 days ago at 00:00 UTC) until one hour before the present hour. If there are already keys in the database, the random keys will be generated for every hour from the latest diagnosis key in the database (by submission timestamp) until one hour before the present hour (or none at all, if the latest diagnosis key in the database was submitted one hour ago or later).
179 `signature-dev` | Sets the app package ID in the export packages' signature info to `de.rki.coronawarnapp-dev` so that the non-productive/test public key will be used for client-side validation.
180 `signature-prod` | Sets the app package ID in the export packages' signature info to `de.rki.coronawarnapp` so that the productive public key will be used for client-side validation.
181 `disable-ssl-client-postgres` | Disables SSL for the connection to the postgres database.
182
183 ### Submission
184
185 Profile | Effect
186 --------------------------------------------------|-------------
187 `dev` | Turns the log level to `DEBUG`.
188 `cloud` | Removes default values for the `datasource` configuration.
189 `disable-ssl-server` | Disables SSL for the submission endpoint.
190 `disable-ssl-client-postgres` | Disables SSL with a pinned certificate for the connection to the postgres database.
191 `disable-ssl-client-verification` | Disables SSL with a pinned certificate for the connection to the verification server.
192 `disable-ssl-client-verification-verify-hostname` | Disables the verification of the SSL hostname for the connection to the verification server.
193
194 ## Documentation
195
196 The full documentation for the Corona-Warn-App can be found in the [cwa-documentation](https://github.com/corona-warn-app/cwa-documentation) repository. The documentation repository contains technical documents, architecture information, and whitepapers related to this implementation.
197
198 ## Support and Feedback
199
200 The following channels are available for discussions, feedback, and support requests:
201
202 | Type | Channel |
203 | ------------------------ | ------------------------------------------------------ |
204 | **General Discussion** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="General Discussion"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/question.svg?style=flat-square"></a> </a> |
205 | **Concept Feedback** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="Open Concept Feedback"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/architecture.svg?style=flat-square"></a> |
206 | **Backend Issue** | <a href="https://github.com/corona-warn-app/cwa-server/issues/new/choose" title="Open Backend Issue"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat-square"></a> |
207 | **Other Requests** | <a href="mailto:[email protected]" title="Email CWA Team"><img src="https://img.shields.io/badge/email-CWA%20team-green?logo=mail.ru&style=flat-square&logoColor=white"></a> |
208
209 ## How to Contribute
210
211 Contribution and feedback are 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.
212
213 ## Contributors
214
215 The German government has asked SAP and Deutsche Telekom to develop the Corona-Warn-App for Germany as open source software. Deutsche Telekom is providing the network and mobile technology and will operate and run the backend for the app in a safe, scalable and stable manner. SAP is responsible for the app development, its framework and the underlying platform. Therefore, development teams of SAP and Deutsche Telekom are contributing to this project. At the same time 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.
216
217 ## Repositories
218
219 The following public repositories are currently available for the Corona-Warn-App:
220
221 | Repository | Description |
222 | ------------------- | --------------------------------------------------------------------- |
223 | [cwa-documentation] | Project overview, general documentation, and white papers |
224 | [cwa-server] | Backend implementation for the Apple/Google exposure notification API|
225 | [cwa-verification-server] | Backend implementation of the verification process|
226
227 [cwa-documentation]: https://github.com/corona-warn-app/cwa-documentation
228 [cwa-server]: https://github.com/corona-warn-app/cwa-server
229 [cwa-verification-server]: https://github.com/corona-warn-app/cwa-verification-server
230 [Postgres]: https://www.postgresql.org/
231 [HSQLDB]: http://hsqldb.org/
232 [Zenko CloudServer]: https://github.com/scality/cloudserver
233
234 ## Licensing
235
236 Copyright (c) 2020 SAP SE or an SAP affiliate company.
237
238 Licensed under the **Apache License, Version 2.0** (the "License"); you may not use this file except in compliance with the License.
239
240 You may obtain a copy of the License at <https://www.apache.org/licenses/LICENSE-2.0>.
241
242 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.
243
[end of README.md]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/client/S3ClientWrapper.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.distribution.objectstore.client;
22
23 import static java.util.stream.Collectors.toList;
24
25 import java.nio.file.Path;
26 import java.util.Collection;
27 import java.util.List;
28 import java.util.Map;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
31 import org.springframework.retry.annotation.Backoff;
32 import org.springframework.retry.annotation.Recover;
33 import org.springframework.retry.annotation.Retryable;
34 import org.springframework.retry.support.RetrySynchronizationManager;
35 import software.amazon.awssdk.core.exception.SdkException;
36 import software.amazon.awssdk.core.sync.RequestBody;
37 import software.amazon.awssdk.services.s3.S3Client;
38 import software.amazon.awssdk.services.s3.model.Delete;
39 import software.amazon.awssdk.services.s3.model.DeleteObjectsRequest;
40 import software.amazon.awssdk.services.s3.model.DeleteObjectsResponse;
41 import software.amazon.awssdk.services.s3.model.HeadObjectRequest;
42 import software.amazon.awssdk.services.s3.model.ListObjectsV2Request;
43 import software.amazon.awssdk.services.s3.model.ListObjectsV2Response;
44 import software.amazon.awssdk.services.s3.model.NoSuchBucketException;
45 import software.amazon.awssdk.services.s3.model.ObjectIdentifier;
46 import software.amazon.awssdk.services.s3.model.PutObjectRequest;
47
48 /**
49 * Implementation of {@link ObjectStoreClient} that encapsulates an {@link S3Client}.
50 */
51 public class S3ClientWrapper implements ObjectStoreClient {
52
53 private static final Logger logger = LoggerFactory.getLogger(S3ClientWrapper.class);
54
55 private final S3Client s3Client;
56
57 public S3ClientWrapper(S3Client s3Client) {
58 this.s3Client = s3Client;
59 }
60
61 @Override
62 public boolean bucketExists(String bucketName) {
63 try {
64 // using S3Client.listObjectsV2 instead of S3Client.listBuckets/headBucket in order to limit required permissions
65 s3Client.listObjectsV2(ListObjectsV2Request.builder().bucket(bucketName).maxKeys(1).build());
66 return true;
67 } catch (NoSuchBucketException e) {
68 return false;
69 } catch (SdkException e) {
70 throw new ObjectStoreOperationFailedException("Failed to determine if bucket exists.", e);
71 }
72 }
73
74 @Override
75 @Retryable(
76 value = SdkException.class,
77 maxAttemptsExpression = "${services.distribution.objectstore.retry-attempts}",
78 backoff = @Backoff(delayExpression = "${services.distribution.objectstore.retry-backoff}"))
79 public List<S3Object> getObjects(String bucket, String prefix) {
80 logRetryStatus("object download");
81
82 ListObjectsV2Response response =
83 s3Client.listObjectsV2(ListObjectsV2Request.builder().prefix(prefix).bucket(bucket).build());
84
85 return response.contents().stream()
86 .map(s3Object -> buildS3Object(s3Object, bucket))
87 .collect(toList());
88 }
89
90 @Recover
91 public List<S3Object> skipReadOperation(Throwable cause) {
92 throw new ObjectStoreOperationFailedException("Failed to get objects from object store", cause);
93 }
94
95 @Override
96 @Retryable(
97 value = SdkException.class,
98 maxAttemptsExpression = "${services.distribution.objectstore.retry-attempts}",
99 backoff = @Backoff(delayExpression = "${services.distribution.objectstore.retry-backoff}"))
100 public void putObject(String bucket, String objectName, Path filePath, Map<HeaderKey, String> headers) {
101 logRetryStatus("object upload");
102 var requestBuilder = PutObjectRequest.builder().bucket(bucket).key(objectName);
103 if (headers.containsKey(HeaderKey.AMZ_ACL)) {
104 requestBuilder.acl(headers.get(HeaderKey.AMZ_ACL));
105 }
106 if (headers.containsKey(HeaderKey.CACHE_CONTROL)) {
107 requestBuilder.cacheControl(headers.get(HeaderKey.CACHE_CONTROL));
108 }
109 if (headers.containsKey(HeaderKey.CWA_HASH)) {
110 requestBuilder.metadata(Map.of(HeaderKey.CWA_HASH.withMetaPrefix(), headers.get(HeaderKey.CWA_HASH)));
111 }
112
113 RequestBody bodyFile = RequestBody.fromFile(filePath);
114 s3Client.putObject(requestBuilder.build(), bodyFile);
115 }
116
117 @Override
118 @Retryable(value = {SdkException.class, ObjectStoreOperationFailedException.class},
119 maxAttemptsExpression = "${services.distribution.objectstore.retry-attempts}",
120 backoff = @Backoff(delayExpression = "${services.distribution.objectstore.retry-backoff}"))
121 public void removeObjects(String bucket, List<String> objectNames) {
122 if (objectNames.isEmpty()) {
123 return;
124 }
125 logRetryStatus("object deletion");
126
127 Collection<ObjectIdentifier> identifiers = objectNames.stream()
128 .map(key -> ObjectIdentifier.builder().key(key).build()).collect(toList());
129
130 DeleteObjectsResponse response = s3Client.deleteObjects(
131 DeleteObjectsRequest.builder()
132 .bucket(bucket)
133 .delete(Delete.builder().objects(identifiers).build()).build());
134
135 if (response.hasErrors()) {
136 throw new ObjectStoreOperationFailedException("Failed to remove objects from object store.");
137 }
138 }
139
140 @Recover
141 private void skipModifyingOperation(Throwable cause) {
142 throw new ObjectStoreOperationFailedException("Failed to modify objects on object store.", cause);
143 }
144
145 /**
146 * Fetches the CWA Hash for the given S3Object. Unfortunately, this is necessary for the AWS SDK, as it does not
147 * support fetching metadata within the {@link ListObjectsV2Request}.<br> MinIO actually does support this, so when
148 * they release 7.0.3, we can remove this code here.
149 *
150 * @param s3Object the S3Object to fetch the CWA hash for
151 * @param bucket the target bucket
152 * @return the CWA hash as a String, or null, if there is no CWA hash available on that object.
153 */
154 private String fetchCwaHash(software.amazon.awssdk.services.s3.model.S3Object s3Object, String bucket) {
155 var result = this.s3Client.headObject(HeadObjectRequest.builder().bucket(bucket).key(s3Object.key()).build());
156 return result.metadata().get(HeaderKey.CWA_HASH.keyValue);
157 }
158
159 private S3Object buildS3Object(software.amazon.awssdk.services.s3.model.S3Object s3Object, String bucket) {
160 String cwaHash = fetchCwaHash(s3Object, bucket);
161 return new S3Object(s3Object.key(), cwaHash);
162 }
163
164 private void logRetryStatus(String action) {
165 int retryCount = RetrySynchronizationManager.getContext().getRetryCount();
166 if (retryCount > 0) {
167 logger.warn("Retrying {} after {} failed attempt(s).", action, retryCount);
168 }
169 }
170 }
171
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/client/S3ClientWrapper.java]
</code>
Here is an example of a patch file. It consists of changes to the code base. It specifies the file names, the line numbers of each change, and the removed and added lines. A single patch file can contain changes to multiple files.
<patch>
--- a/file.py
+++ b/file.py
@@ -1,27 +1,35 @@
def euclidean(a, b):
- while b:
- a, b = b, a % b
- return a
+ if b == 0:
+ return a
+ return euclidean(b, a % b)
def bresenham(x0, y0, x1, y1):
points = []
dx = abs(x1 - x0)
dy = abs(y1 - y0)
- sx = 1 if x0 < x1 else -1
- sy = 1 if y0 < y1 else -1
- err = dx - dy
+ x, y = x0, y0
+ sx = -1 if x0 > x1 else 1
+ sy = -1 if y0 > y1 else 1
- while True:
- points.append((x0, y0))
- if x0 == x1 and y0 == y1:
- break
- e2 = 2 * err
- if e2 > -dy:
+ if dx > dy:
+ err = dx / 2.0
+ while x != x1:
+ points.append((x, y))
err -= dy
- x0 += sx
- if e2 < dx:
- err += dx
- y0 += sy
+ if err < 0:
+ y += sy
+ err += dx
+ x += sx
+ else:
+ err = dy / 2.0
+ while y != y1:
+ points.append((x, y))
+ err -= dx
+ if err < 0:
+ x += sx
+ err += dy
+ y += sy
+ points.append((x, y))
return points
</patch>
I need you to solve the provded issue by generating a single patch file that I can apply directly to this repository using git apply. Please respond with a single patch file in the format shown above.
Respond below:
| corona-warn-app/cwa-server | 97f16ca7b711a30eec695c1ae7a6f032df16533b | S3ClientWrapper getObjects: Not all objects could be received
<!--
Thanks for reporting a bug 🙌 ❤️
Before opening a new issue, please make sure that we do not have any duplicates already open. You can ensure this by searching the issue list for this repository. If there is a duplicate, please close your issue and add a comment to the existing issue instead.
Also, be sure to check our documentation first: <URL>
-->
## Describe the bug
https://github.com/corona-warn-app/cwa-server/blob/a953c054f8b4dc97d6a40525c5c3d5aa4d867394/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/client/S3ClientWrapper.java#L83
It is possible that not all objects are received, because the **listObjectsV2(ListObjectsV2Request listObjectsV2Request)** method limits them up to 1000.
Javadoc [listObjectsV2](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/s3/S3Client.html#listObjectsV2-software.amazon.awssdk.services.s3.model.ListObjectsV2Request-)
> Returns some or all (up to 1,000) of the objects in a bucket.
## Possible Fix
1. Checking the response for more data with the **isTruncated** method.
JavaDoc [isTruncated](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/s3/model/ListObjectsV2Response.html#isTruncated--)
> Set to false if all of the results were returned. Set to true if more keys are available to return. If the number of results exceeds that specified by MaxKeys, all of the results might not be returned.
2. When the response is truncated, calling the **nextContinuationToken** method for the next token.
JavaDoc [nextContinuationToken](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/s3/model/ListObjectsV2Response.html#nextContinuationToken--)
> NextContinuationToken is sent when isTruncated is true, which means there are more keys in the bucket that can be listed. The next list requests to Amazon S3 can be continued with this NextContinuationToken.
3. Build a new ListObjectsV2Request with the **continuationToken** and call **listObjectsV2** again
JavaDoc [continuationToken](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/s3/model/ListObjectsV2Request.Builder.html#continuationToken-java.lang.String-)
> ContinuationToken indicates Amazon S3 that the list is being continued on this bucket with a token. ContinuationToken is obfuscated and is not a real key.
4. Repeat everything until isTruncate is false.
Here is a pretty good example from AWS. They use a different S3Client, but it is very similar to the one you use. ([source](https://docs.aws.amazon.com/AmazonS3/latest/dev/ListingObjectKeysUsingJava.html))
```java
import com.amazonaws.AmazonServiceException;
import com.amazonaws.SdkClientException;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.ListObjectsV2Request;
import com.amazonaws.services.s3.model.ListObjectsV2Result;
import com.amazonaws.services.s3.model.S3ObjectSummary;
import java.io.IOException;
public class ListKeys {
public static void main(String[] args) throws IOException {
Regions clientRegion = Regions.DEFAULT_REGION;
String bucketName = "*** Bucket name ***";
try {
AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
.withCredentials(new ProfileCredentialsProvider())
.withRegion(clientRegion)
.build();
System.out.println("Listing objects");
// maxKeys is set to 2 to demonstrate the use of
// ListObjectsV2Result.getNextContinuationToken()
ListObjectsV2Request req = new ListObjectsV2Request().withBucketName(bucketName).withMaxKeys(2);
ListObjectsV2Result result;
do {
result = s3Client.listObjectsV2(req);
for (S3ObjectSummary objectSummary : result.getObjectSummaries()) {
System.out.printf(" - %s (size: %d)\n", objectSummary.getKey(), objectSummary.getSize());
}
// If there are more than maxKeys keys in the bucket, get a continuation token
// and list the next objects.
String token = result.getNextContinuationToken();
System.out.println("Next Continuation Token: " + token);
req.setContinuationToken(token);
} while (result.isTruncated());
} catch (AmazonServiceException e) {
// The call was transmitted successfully, but Amazon S3 couldn't process
// it, so it returned an error response.
e.printStackTrace();
} catch (SdkClientException e) {
// Amazon S3 couldn't be contacted for a response, or the client
// couldn't parse the response from Amazon S3.
e.printStackTrace();
}
}
}
``
| 2020-06-13T13:23:53 | <patch>
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/client/S3ClientWrapper.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/client/S3ClientWrapper.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/client/S3ClientWrapper.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/client/S3ClientWrapper.java
@@ -20,9 +20,11 @@
package app.coronawarn.server.services.distribution.objectstore.client;
+import static java.lang.Boolean.TRUE;
import static java.util.stream.Collectors.toList;
import java.nio.file.Path;
+import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
@@ -78,13 +80,20 @@ public boolean bucketExists(String bucketName) {
backoff = @Backoff(delayExpression = "${services.distribution.objectstore.retry-backoff}"))
public List<S3Object> getObjects(String bucket, String prefix) {
logRetryStatus("object download");
-
- ListObjectsV2Response response =
- s3Client.listObjectsV2(ListObjectsV2Request.builder().prefix(prefix).bucket(bucket).build());
-
- return response.contents().stream()
- .map(s3Object -> buildS3Object(s3Object, bucket))
- .collect(toList());
+ List<S3Object> allS3Objects = new ArrayList<>();
+ String continuationToken = null;
+
+ do {
+ ListObjectsV2Request request =
+ ListObjectsV2Request.builder().prefix(prefix).bucket(bucket).continuationToken(continuationToken).build();
+ ListObjectsV2Response response = s3Client.listObjectsV2(request);
+ response.contents().stream()
+ .map(s3Object -> buildS3Object(s3Object, bucket))
+ .forEach(allS3Objects::add);
+ continuationToken = TRUE.equals(response.isTruncated()) ? response.continuationToken() : null;
+ } while (continuationToken != null);
+
+ return allS3Objects;
}
@Recover
</patch> | diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/client/S3ClientWrapperTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/client/S3ClientWrapperTest.java
--- a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/client/S3ClientWrapperTest.java
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/client/S3ClientWrapperTest.java
@@ -150,6 +150,25 @@ void testGetObjects(List<S3Object> expResult) {
assertThat(actResult).isEqualTo(expResult);
}
+ @Test
+ void testContinuationToken() {
+ var continuationToken = "1ueGcxLPRx1Tr/XYExHnhbYLgveDs2J/wm36Hy4vbOwM=<";
+
+ when(s3Client.listObjectsV2(any(ListObjectsV2Request.class)))
+ .thenReturn(ListObjectsV2Response.builder().isTruncated(true).continuationToken(continuationToken).build(),
+ ListObjectsV2Response.builder().isTruncated(false).build());
+
+ s3ClientWrapper.getObjects(VALID_BUCKET_NAME, VALID_PREFIX);
+
+ ListObjectsV2Request continuationRequest = ListObjectsV2Request.builder()
+ .prefix(VALID_PREFIX).bucket(VALID_BUCKET_NAME).continuationToken(continuationToken).build();
+ ListObjectsV2Request noContinuationRequest = ListObjectsV2Request.builder()
+ .prefix(VALID_PREFIX).bucket(VALID_BUCKET_NAME).build();
+
+ verify(s3Client, times(1)).listObjectsV2(eq(continuationRequest));
+ verify(s3Client, times(1)).listObjectsV2(eq(noContinuationRequest));
+ }
+
private static Stream<Arguments> createGetObjectsResults() {
return Stream.of(
Lists.emptyList(),
| |||||
corona-warn-app__cwa-server-463 | You will be provided with a partial code base and an issue statement explaining a problem to resolve.
<issue>
Distribution: Add Safeguard to not generate any exposure key file > 16MB
In order to prevent issues on the mobile device & potential abuse, add a safeguard, so that we do not publish any files, which are bigger than 16MB. In case this threshold is reached for any file, an error message must be logged.
Make sure to keep consistency with the index files. In order to align with the current concept of always generating a file, we should generate an empty file in this case as well.
@pithumke
</issue>
<code>
[start of README.md]
1 <!-- markdownlint-disable MD041 -->
2 <h1 align="center">
3 Corona-Warn-App Server
4 </h1>
5
6 <p align="center">
7 <a href="https://github.com/corona-warn-app/cwa-server/commits/" title="Last Commit"><img src="https://img.shields.io/github/last-commit/corona-warn-app/cwa-server?style=flat"></a>
8 <a href="https://github.com/corona-warn-app/cwa-server/issues" title="Open Issues"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat"></a>
9 <a href="https://circleci.com/gh/corona-warn-app/cwa-server" title="Build Status"><img src="https://circleci.com/gh/corona-warn-app/cwa-server.svg?style=shield&circle-token=4ab059989d10709df19eb4b98ab7c121a25e981a"></a>
10 <a href="https://sonarcloud.io/dashboard?id=corona-warn-app_cwa-server" title="Quality Gate"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=alert_status"></a>
11 <a href="https://sonarcloud.io/component_measures?id=corona-warn-app_cwa-server&metric=Coverage&view=list" title="Coverage"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=coverage"></a>
12 <a href="https://github.com/corona-warn-app/cwa-server/blob/master/LICENSE" title="License"><img src="https://img.shields.io/badge/License-Apache%202.0-green.svg?style=flat"></a>
13 </p>
14
15 <p align="center">
16 <a href="#development">Development</a> •
17 <a href="#service-apis">Service APIs</a> •
18 <a href="#documentation">Documentation</a> •
19 <a href="#support-and-feedback">Support</a> •
20 <a href="#how-to-contribute">Contribute</a> •
21 <a href="#contributors">Contributors</a> •
22 <a href="#repositories">Repositories</a> •
23 <a href="#licensing">Licensing</a>
24 </p>
25
26 The goal of this project is to develop the official Corona-Warn-App for Germany based on the exposure notification API from [Apple](https://www.apple.com/covid19/contacttracing/) and [Google](https://www.google.com/covid19/exposurenotifications/). The apps (for both iOS and Android) use Bluetooth technology to exchange anonymous encrypted data with other mobile phones (on which the app is also installed) in the vicinity of an app user's phone. The data is stored locally on each user's device, preventing authorities or other parties from accessing or controlling the data. This repository contains the **implementation of the server for encryption keys** for the Corona-Warn-App. This implementation is still a **work in progress**, and the code it contains is currently alpha-quality code.
27
28 In this documentation, Corona-Warn-App services are also referred to as CWA services.
29
30 ## Architecture Overview
31
32 You can find the architecture overview [here](/docs/architecture-overview.md), which will give you
33 a good starting point in how the backend services interact with other services, and what purpose
34 they serve.
35
36 ## Development
37
38 After you've checked out this repository, you can run the application in one of the following ways:
39
40 * As a [Docker](https://www.docker.com/)-based deployment on your local machine. You can run either:
41 * Single components using the respective Dockerfile or
42 * The full backend using the Docker Compose (which is considered the most convenient way)
43 * As a [Maven](https://maven.apache.org)-based build on your local machine.
44 If you want to develop something in a single component, this approach is preferable.
45
46 ### Docker-Based Deployment
47
48 If you want to use Docker-based deployment, you need to install Docker on your local machine. For more information about downloading and installing Docker, see the [official Docker documentation](https://docs.docker.com/get-docker/).
49
50 #### Running the Full CWA Backend Using Docker Compose
51
52 For your convenience, a full setup including the generation of test data has been prepared using [Docker Compose](https://docs.docker.com/compose/reference/overview/). To build the backend services, run ```docker-compose build``` in the repository's root directory. A default configuration file can be found under ```.env```in the root folder of the repository. The default values for the local Postgres and Zenko Cloudserver should be changed in this file before docker-compose is run.
53
54 Once the services are built, you can start the whole backend using ```docker-compose up```.
55 The distribution service runs once and then finishes. If you want to trigger additional distribution runs, run ```docker-compose run distribution```.
56
57 The docker-compose contains the following services:
58
59 Service | Description | Endpoint and Default Credentials
60 ------------------|-------------|-----------
61 submission | The Corona-Warn-App submission service | `http://localhost:8000` <br> `http://localhost:8006` (for actuator endpoint)
62 distribution | The Corona-Warn-App distribution service | NO ENDPOINT
63 postgres | A [postgres] database installation | `postgres:8001` <br> Username: postgres <br> Password: postgres
64 pgadmin | A [pgadmin](https://www.pgadmin.org/) installation for the postgres database | `http://localhost:8002` <br> Username: [email protected] <br> Password: password
65 cloudserver | [Zenko CloudServer] is a S3-compliant object store | `http://localhost:8003/` <br> Access key: accessKey1 <br> Secret key: verySecretKey1
66 verification-fake | A very simple fake implementation for the tan verification. | `http://localhost:8004/version/v1/tan/verify` <br> The only valid tan is "edc07f08-a1aa-11ea-bb37-0242ac130002"
67
68 ##### Known Limitation
69
70 In rare cases the docker-compose runs into a timing issue if the distribution service starts before the bucket of the objectstore was created. This is not a big issue as you can simply run ```docker-compose run distribution``` to trigger additional distribution runs after the objectstore was initialized.
71
72 #### Running Single CWA Services Using Docker
73
74 If you would like to build and run a single CWA service, it's considered easiest to run them in a Docker environment. You can do this using the script provided in the respective CWA service directory. The Docker script first builds the CWA service and then creates an image for the runtime, which means that there are no additional dependencies for you to install.
75
76 To build and run the distribution service, run the following command:
77
78 ```bash
79 ./services/distribution/build_and_run.sh
80 ```
81
82 To build and run the submission service, run the following command:
83
84 ```bash
85 ./services/submission/build_and_run.sh
86 ```
87
88 The submission service is available on [localhost:8080](http://localhost:8080 ).
89
90 ### Maven-Based Build
91
92 If you want to actively develop in one of the CWA services, the Maven-based runtime is most suitable.
93 To prepare your machine to run the CWA project locally, we recommend that you first ensure that you've installed the following:
94
95 * Minimum JDK Version 11: [OpenJDK](https://openjdk.java.net/) / [SapMachine](https://sap.github.io/SapMachine/)
96 * [Maven 3.6](https://maven.apache.org/)
97 * [Postgres]
98 * [Zenko CloudServer]
99
100 #### Configure
101
102 After you made sure that the specified dependencies are running, configure them in the respective configuration files.
103
104 * Configure the Postgres connection in the [submission config](./services/submission/src/main/resources/application.yaml) and in the [distribution config](./services/distribution/src/main/resources/application.yaml)
105 * Configure the S3 compatible object storage in the [distribution config](./services/distribution/src/main/resources/application.yaml)
106 * Configure the private key for the distribution service, the path need to be prefixed with `file:`
107 * `VAULT_FILESIGNING_SECRET` should be the path to the private key, example available in `<repo-root>/docker-compose-test-secrets/private.pem`
108
109 #### Build
110
111 After you've checked out the repository, to build the project, run ```mvn install``` in your base directory.
112
113 #### Run
114
115 Navigate to the service you want to start and run the spring-boot:run target. The configured Postgres and the configured S3 compliant object storage are used as default. When you start the submission service, the endpoint is available on your local port 8080.
116
117 If you want to start the submission service, for example, you start it as follows:
118
119 ```bash
120 cd services/submission/
121 mvn spring-boot:run
122 ```
123
124 #### Debugging
125
126 To enable the `DEBUG` log level, you can run the application using the Spring `dev` profile.
127
128 ```bash
129 mvn spring-boot:run -Dspring-boot.run.profiles=dev
130 ```
131
132 To be able to set breakpoints (e.g. in IntelliJ), it may be necessary to use the ```-Dspring-boot.run.fork=false``` parameter.
133
134 ## Service APIs
135
136 The API that is being exposed by the backend services is documented in an [OpenAPI](https://www.openapis.org/) specification. The specification files are available at the following locations:
137
138 Service | OpenAPI Specification
139 -------------|-------------
140 Submission Service | [services/submission/api_v1.json](https://github.com/corona-warn-app/cwa-server/raw/master/services/submission/api_v1.json)
141 Distribution Service | [services/distribution/api_v1.json](https://github.com/corona-warn-app/cwa-server/raw/master/services/distribution/api_v1.json)
142
143 ## Spring Profiles
144
145 ### Distribution
146
147 Profile | Effect
148 -----------------|-------------
149 `dev` | Turns the log level to `DEBUG`.
150 `cloud` | Removes default values for the `datasource` and `objectstore` configurations.
151 `demo` | Includes incomplete days and hours into the distribution run, thus creating aggregates for the current day and the current hour (and including both in the respective indices). When running multiple distributions in one hour with this profile, the date aggregate for today and the hours aggregate for the current hour will be updated and overwritten. This profile also turns off the expiry policy (Keys must be expired for at least 2 hours before distribution) and the shifting policy (there must be at least 140 keys in a distribution).
152 `testdata` | Causes test data to be inserted into the database before each distribution run. By default, around 1000 random diagnosis keys will be generated per hour. If there are no diagnosis keys in the database yet, random keys will be generated for every hour from the beginning of the retention period (14 days ago at 00:00 UTC) until one hour before the present hour. If there are already keys in the database, the random keys will be generated for every hour from the latest diagnosis key in the database (by submission timestamp) until one hour before the present hour (or none at all, if the latest diagnosis key in the database was submitted one hour ago or later).
153 `signature-dev` | Sets the app package ID in the export packages' signature info to `de.rki.coronawarnapp-dev` so that test certificates (instead of production certificates) will be used for client-side validation.
154 `signature-prod` | Provides production app package IDs for the signature info
155
156 ### Submission
157
158 Profile | Effect
159 -------------|-------------
160 `dev` | Turns the log level to `DEBUG`.
161 `cloud` | Removes default values for the `datasource` configuration.
162
163 ## Documentation
164
165 The full documentation for the Corona-Warn-App can be found in the [cwa-documentation](https://github.com/corona-warn-app/cwa-documentation) repository. The documentation repository contains technical documents, architecture information, and whitepapers related to this implementation.
166
167 ## Support and Feedback
168
169 The following channels are available for discussions, feedback, and support requests:
170
171 | Type | Channel |
172 | ------------------------ | ------------------------------------------------------ |
173 | **General Discussion** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="General Discussion"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/question.svg?style=flat-square"></a> </a> |
174 | **Concept Feedback** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="Open Concept Feedback"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/architecture.svg?style=flat-square"></a> |
175 | **Backend Issue** | <a href="https://github.com/corona-warn-app/cwa-server/issues/new/choose" title="Open Backend Issue"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat-square"></a> |
176 | **Other Requests** | <a href="mailto:[email protected]" title="Email CWA Team"><img src="https://img.shields.io/badge/email-CWA%20team-green?logo=mail.ru&style=flat-square&logoColor=white"></a> |
177
178 ## How to Contribute
179
180 Contribution and feedback are 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.
181
182 ## Contributors
183
184 The German government has asked SAP and Deutsche Telekom to develop the Corona-Warn-App for Germany as open source software. Deutsche Telekom is providing the network and mobile technology and will operate and run the backend for the app in a safe, scalable and stable manner. SAP is responsible for the app development, its framework and the underlying platform. Therefore, development teams of SAP and Deutsche Telekom are contributing to this project. At the same time 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.
185
186 ## Repositories
187
188 The following public repositories are currently available for the Corona-Warn-App:
189
190 | Repository | Description |
191 | ------------------- | --------------------------------------------------------------------- |
192 | [cwa-documentation] | Project overview, general documentation, and white papers |
193 | [cwa-server] | Backend implementation for the Apple/Google exposure notification API|
194 | [cwa-verification-server] | Backend implementation of the verification process|
195
196 [cwa-documentation]: https://github.com/corona-warn-app/cwa-documentation
197 [cwa-server]: https://github.com/corona-warn-app/cwa-server
198 [cwa-verification-server]: https://github.com/corona-warn-app/cwa-verification-server
199 [Postgres]: https://www.postgresql.org/
200 [HSQLDB]: http://hsqldb.org/
201 [Zenko CloudServer]: https://github.com/scality/cloudserver
202
203 ## Licensing
204
205 Copyright (c) 2020 SAP SE or an SAP affiliate company.
206
207 Licensed under the **Apache License, Version 2.0** (the "License"); you may not use this file except in compliance with the License.
208
209 You may obtain a copy of the License at <https://www.apache.org/licenses/LICENSE-2.0>.
210
211 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.
212
[end of README.md]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/DiagnosisKeyBundler.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.distribution.assembly.diagnosiskeys;
22
23 import static java.time.ZoneOffset.UTC;
24 import static java.util.Collections.emptyList;
25
26 import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
27 import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
28 import java.time.LocalDate;
29 import java.time.LocalDateTime;
30 import java.util.Collection;
31 import java.util.HashMap;
32 import java.util.List;
33 import java.util.Map;
34 import java.util.Optional;
35 import java.util.Set;
36 import java.util.concurrent.TimeUnit;
37 import java.util.stream.Collectors;
38
39 /**
40 * An instance of this class contains a collection of {@link DiagnosisKey DiagnosisKeys}.
41 */
42 public abstract class DiagnosisKeyBundler {
43
44 /**
45 * The submission timestamp is counted in 1 hour intervals since epoch.
46 */
47 public static final long ONE_HOUR_INTERVAL_SECONDS = TimeUnit.HOURS.toSeconds(1);
48
49 /**
50 * The rolling start interval number is counted in 10 minute intervals since epoch.
51 */
52 public static final long TEN_MINUTES_INTERVAL_SECONDS = TimeUnit.MINUTES.toSeconds(10);
53
54 protected final int minNumberOfKeysPerBundle;
55 protected final long expiryPolicyMinutes;
56
57 // The hour at which the distribution runs. This field is needed to prevent the run from distributing any keys that
58 // have already been submitted but may only be distributed in the future (e.g. because they are not expired yet).
59 protected LocalDateTime distributionTime;
60
61 // A map containing diagnosis keys, grouped by the LocalDateTime on which they may be distributed
62 protected final Map<LocalDateTime, List<DiagnosisKey>> distributableDiagnosisKeys = new HashMap<>();
63
64 public DiagnosisKeyBundler(DistributionServiceConfig distributionServiceConfig) {
65 this.minNumberOfKeysPerBundle = distributionServiceConfig.getShiftingPolicyThreshold();
66 this.expiryPolicyMinutes = distributionServiceConfig.getExpiryPolicyMinutes();
67 }
68
69 /**
70 * Creates a {@link LocalDateTime} based on the specified epoch timestamp.
71 */
72 public static LocalDateTime getLocalDateTimeFromHoursSinceEpoch(long timestamp) {
73 return LocalDateTime.ofEpochSecond(TimeUnit.HOURS.toSeconds(timestamp), 0, UTC);
74 }
75
76 /**
77 * Sets the {@link DiagnosisKey DiagnosisKeys} contained by this {@link DiagnosisKeyBundler} and the time at which the
78 * distribution runs and calls {@link DiagnosisKeyBundler#createDiagnosisKeyDistributionMap}.
79 *
80 * @param diagnosisKeys The {@link DiagnosisKey DiagnosisKeys} contained by this {@link DiagnosisKeyBundler}.
81 * @param distributionTime The {@link LocalDateTime} at which the distribution runs.
82 */
83 public void setDiagnosisKeys(Collection<DiagnosisKey> diagnosisKeys, LocalDateTime distributionTime) {
84 this.distributionTime = distributionTime;
85 this.createDiagnosisKeyDistributionMap(diagnosisKeys);
86 }
87
88 /**
89 * Returns all {@link DiagnosisKey DiagnosisKeys} contained by this {@link DiagnosisKeyBundler}.
90 */
91 public List<DiagnosisKey> getAllDiagnosisKeys() {
92 return this.distributableDiagnosisKeys.values().stream()
93 .flatMap(List::stream)
94 .collect(Collectors.toList());
95 }
96
97 /**
98 * Initializes the internal {@code distributableDiagnosisKeys} map, which should contain all diagnosis keys, grouped
99 * by the LocalDateTime on which they may be distributed.
100 */
101 protected abstract void createDiagnosisKeyDistributionMap(Collection<DiagnosisKey> diagnosisKeys);
102
103 /**
104 * Returns a set of all {@link LocalDate dates} on which {@link DiagnosisKey diagnosis keys} shall be distributed.
105 */
106 public Set<LocalDate> getDatesWithDistributableDiagnosisKeys() {
107 return this.distributableDiagnosisKeys.keySet().stream()
108 .map(LocalDateTime::toLocalDate)
109 .collect(Collectors.toSet());
110 }
111
112 /**
113 * Returns a set of all {@link LocalDateTime hours} of a specified {@link LocalDate date} during which {@link
114 * DiagnosisKey diagnosis keys} shall be distributed.
115 */
116 public Set<LocalDateTime> getHoursWithDistributableDiagnosisKeys(LocalDate currentDate) {
117 return this.distributableDiagnosisKeys.keySet().stream()
118 .filter(dateTime -> dateTime.toLocalDate().equals(currentDate))
119 .collect(Collectors.toSet());
120 }
121
122 /**
123 * Returns the submission timestamp of a {@link DiagnosisKey} as a {@link LocalDateTime}.
124 */
125 protected LocalDateTime getSubmissionDateTime(DiagnosisKey diagnosisKey) {
126 return LocalDateTime.ofEpochSecond(diagnosisKey.getSubmissionTimestamp() * ONE_HOUR_INTERVAL_SECONDS, 0, UTC);
127 }
128
129 /**
130 * Returns all diagnosis keys that should be distributed on a specific date.
131 */
132 public List<DiagnosisKey> getDiagnosisKeysForDate(LocalDate date) {
133 return this.distributableDiagnosisKeys.keySet().stream()
134 .filter(dateTime -> dateTime.toLocalDate().equals(date))
135 .map(this::getDiagnosisKeysForHour)
136 .flatMap(List::stream)
137 .collect(Collectors.toList());
138 }
139
140 /**
141 * Returns all diagnosis keys that should be distributed in a specific hour.
142 */
143 public List<DiagnosisKey> getDiagnosisKeysForHour(LocalDateTime hour) {
144 return Optional
145 .ofNullable(this.distributableDiagnosisKeys.get(hour))
146 .orElse(emptyList());
147 }
148 }
149
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/DiagnosisKeyBundler.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysCountryDirectory.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.directory;
22
23 import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
24 import app.coronawarn.server.services.distribution.assembly.component.CryptoProvider;
25 import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.DiagnosisKeyBundler;
26 import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.directory.decorator.DateAggregatingDecorator;
27 import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.directory.decorator.DateIndexingDecorator;
28 import app.coronawarn.server.services.distribution.assembly.structure.WritableOnDisk;
29 import app.coronawarn.server.services.distribution.assembly.structure.directory.IndexDirectory;
30 import app.coronawarn.server.services.distribution.assembly.structure.directory.IndexDirectoryOnDisk;
31 import app.coronawarn.server.services.distribution.assembly.structure.util.ImmutableStack;
32 import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
33 import java.time.LocalDate;
34 import java.util.Set;
35
36 public class DiagnosisKeysCountryDirectory extends IndexDirectoryOnDisk<String> {
37
38 private final DiagnosisKeyBundler diagnosisKeyBundler;
39 private final CryptoProvider cryptoProvider;
40 private final DistributionServiceConfig distributionServiceConfig;
41
42 /**
43 * Constructs a {@link DiagnosisKeysCountryDirectory} instance that represents the {@code .../country/:country/...}
44 * portion of the diagnosis key directory structure.
45 *
46 * @param diagnosisKeyBundler A {@link DiagnosisKeyBundler} containing the {@link DiagnosisKey DiagnosisKeys}.
47 * @param cryptoProvider The {@link CryptoProvider} used for payload signing.
48 */
49 public DiagnosisKeysCountryDirectory(DiagnosisKeyBundler diagnosisKeyBundler,
50 CryptoProvider cryptoProvider, DistributionServiceConfig distributionServiceConfig) {
51 super(distributionServiceConfig.getApi().getCountryPath(), __ ->
52 Set.of(distributionServiceConfig.getApi().getCountryGermany()), Object::toString);
53 this.diagnosisKeyBundler = diagnosisKeyBundler;
54 this.cryptoProvider = cryptoProvider;
55 this.distributionServiceConfig = distributionServiceConfig;
56 }
57
58 @Override
59 public void prepare(ImmutableStack<Object> indices) {
60 this.addWritableToAll(__ -> {
61 DiagnosisKeysDateDirectory dateDirectory = new DiagnosisKeysDateDirectory(diagnosisKeyBundler, cryptoProvider,
62 distributionServiceConfig);
63 return decorateDateDirectory(dateDirectory);
64 });
65 super.prepare(indices);
66 }
67
68 private IndexDirectory<LocalDate, WritableOnDisk> decorateDateDirectory(DiagnosisKeysDateDirectory dateDirectory) {
69 return new DateAggregatingDecorator(new DateIndexingDecorator(dateDirectory, distributionServiceConfig),
70 cryptoProvider, distributionServiceConfig);
71 }
72 }
73
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysCountryDirectory.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/decorator/DateAggregatingDecorator.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.directory.decorator;
22
23 import static app.coronawarn.server.services.distribution.assembly.structure.util.functional.CheckedFunction.uncheckedFunction;
24
25 import app.coronawarn.server.common.protocols.external.exposurenotification.TemporaryExposureKey;
26 import app.coronawarn.server.common.protocols.external.exposurenotification.TemporaryExposureKeyExport;
27 import app.coronawarn.server.services.distribution.assembly.component.CryptoProvider;
28 import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.archive.decorator.singing.DiagnosisKeySigningDecorator;
29 import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.file.TemporaryExposureKeyExportFile;
30 import app.coronawarn.server.services.distribution.assembly.structure.Writable;
31 import app.coronawarn.server.services.distribution.assembly.structure.WritableOnDisk;
32 import app.coronawarn.server.services.distribution.assembly.structure.archive.Archive;
33 import app.coronawarn.server.services.distribution.assembly.structure.archive.ArchiveOnDisk;
34 import app.coronawarn.server.services.distribution.assembly.structure.directory.Directory;
35 import app.coronawarn.server.services.distribution.assembly.structure.directory.DirectoryOnDisk;
36 import app.coronawarn.server.services.distribution.assembly.structure.directory.IndexDirectory;
37 import app.coronawarn.server.services.distribution.assembly.structure.directory.decorator.DirectoryDecorator;
38 import app.coronawarn.server.services.distribution.assembly.structure.directory.decorator.IndexDirectoryDecorator;
39 import app.coronawarn.server.services.distribution.assembly.structure.file.File;
40 import app.coronawarn.server.services.distribution.assembly.structure.util.ImmutableStack;
41 import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
42 import java.time.LocalDate;
43 import java.util.List;
44 import java.util.NoSuchElementException;
45 import java.util.Optional;
46 import java.util.Set;
47 import java.util.stream.Collectors;
48 import java.util.stream.Stream;
49
50 /**
51 * A {@link DirectoryDecorator} that will bundle hour aggregates into date aggregates and sign them.
52 */
53 public class DateAggregatingDecorator extends IndexDirectoryDecorator<LocalDate, WritableOnDisk> {
54
55 private final CryptoProvider cryptoProvider;
56 private final DistributionServiceConfig distributionServiceConfig;
57
58 /**
59 * Creates a new DateAggregatingDecorator.
60 */
61 public DateAggregatingDecorator(IndexDirectory<LocalDate, WritableOnDisk> directory, CryptoProvider cryptoProvider,
62 DistributionServiceConfig distributionServiceConfig) {
63 super(directory);
64 this.cryptoProvider = cryptoProvider;
65 this.distributionServiceConfig = distributionServiceConfig;
66 }
67
68 @Override
69 public void prepare(ImmutableStack<Object> indices) {
70 super.prepare(indices);
71 Set<Directory<WritableOnDisk>> dayDirectories = this.getWritables().stream()
72 .filter(writable -> writable instanceof DirectoryOnDisk)
73 .map(directory -> (DirectoryOnDisk) directory)
74 .collect(Collectors.toSet());
75 if (dayDirectories.isEmpty()) {
76 return;
77 }
78
79 Set<String> dates = this.getIndex(indices).stream()
80 .map(this.getIndexFormatter())
81 .map(Object::toString)
82 .collect(Collectors.toSet());
83
84 dayDirectories.stream()
85 .filter(dayDirectory -> dates.contains(dayDirectory.getName()))
86 .forEach(currentDirectory -> Stream.of(currentDirectory)
87 .map(this::getSubSubDirectoryArchives)
88 .map(this::getTemporaryExposureKeyExportFilesFromArchives)
89 .map(this::parseTemporaryExposureKeyExportsFromFiles)
90 .map(this::reduceTemporaryExposureKeyExportsToNewFile)
91 .map(temporaryExposureKeyExportFile -> {
92 Archive<WritableOnDisk> aggregate = new ArchiveOnDisk(distributionServiceConfig.getOutputFileName());
93 aggregate.addWritable(temporaryExposureKeyExportFile);
94 return aggregate;
95 })
96 .map(file -> new DiagnosisKeySigningDecorator(file, cryptoProvider, distributionServiceConfig))
97 .forEach(aggregate -> {
98 currentDirectory.addWritable(aggregate);
99 aggregate.prepare(indices);
100 })
101 );
102 }
103
104 /**
105 * Returns all archives that are 3 levels down from the root directory.
106 */
107 private Set<Archive<WritableOnDisk>> getSubSubDirectoryArchives(Directory<WritableOnDisk> rootDirectory) {
108 return getWritablesInDirectory(rootDirectory, 3).stream()
109 .filter(Writable::isArchive)
110 .map(archive -> (Archive<WritableOnDisk>) archive)
111 .collect(Collectors.toSet());
112 }
113
114 /**
115 * Traverses a directory {@code depth} levels deep and returns a flattened list of all writables at that depth. A
116 * {@code depth} of 0 or less returns a set only containing the root directory. A depth of 1 returns a set of
117 * writables in the root directory. A depth of 2 returns a set of all writables in all directories in the root
118 * directory, and so on.
119 *
120 * @param rootDirectory The directory in which to start traversal.
121 * @param depth The depth to traverse.
122 * @return All writables that are {@code depth} levels down.
123 */
124 private Set<Writable<WritableOnDisk>> getWritablesInDirectory(Directory<WritableOnDisk> rootDirectory, int depth) {
125 if (depth <= 0) {
126 return Set.of(rootDirectory);
127 } else if (depth == 1) {
128 return rootDirectory.getWritables();
129 } else {
130 return rootDirectory.getWritables().stream()
131 .filter(Writable::isDirectory)
132 .flatMap(directory -> getWritablesInDirectory((Directory<WritableOnDisk>) directory, depth - 1).stream())
133 .collect(Collectors.toSet());
134 }
135 }
136
137 private Set<TemporaryExposureKeyExportFile> getTemporaryExposureKeyExportFilesFromArchives(
138 Set<Archive<WritableOnDisk>> hourArchives) {
139 return hourArchives.stream()
140 .map(Directory::getWritables)
141 .map(writables -> writables.stream()
142 .filter(writable -> writable.getName().equals("export.bin")))
143 .map(Stream::findFirst)
144 .map(Optional::orElseThrow)
145 .filter(writable -> writable instanceof File)
146 .map(file -> (TemporaryExposureKeyExportFile) file)
147 .collect(Collectors.toSet());
148 }
149
150 private Set<TemporaryExposureKeyExport> parseTemporaryExposureKeyExportsFromFiles(
151 Set<TemporaryExposureKeyExportFile> temporaryExposureKeyExportFiles) {
152 return temporaryExposureKeyExportFiles.stream()
153 .map(TemporaryExposureKeyExportFile::getBytesWithoutHeader)
154 .map(uncheckedFunction(TemporaryExposureKeyExport::parseFrom))
155 .collect(Collectors.toSet());
156 }
157
158 private TemporaryExposureKeyExportFile reduceTemporaryExposureKeyExportsToNewFile(
159 Set<TemporaryExposureKeyExport> temporaryExposureKeyExports) {
160 return TemporaryExposureKeyExportFile.fromTemporaryExposureKeys(
161 getTemporaryExposureKeys(temporaryExposureKeyExports),
162 getRegion(temporaryExposureKeyExports),
163 getStartTimestamp(temporaryExposureKeyExports),
164 getEndTimestamp(temporaryExposureKeyExports),
165 distributionServiceConfig
166 );
167 }
168
169 private static Set<TemporaryExposureKey> getTemporaryExposureKeys(
170 Set<TemporaryExposureKeyExport> temporaryExposureKeyExports) {
171 return temporaryExposureKeyExports.stream()
172 .map(TemporaryExposureKeyExport::getKeysList)
173 .flatMap(List::stream)
174 .collect(Collectors.toSet());
175 }
176
177 private static String getRegion(Set<TemporaryExposureKeyExport> temporaryExposureKeyExports) {
178 return temporaryExposureKeyExports.stream()
179 .map(TemporaryExposureKeyExport::getRegion)
180 .findAny()
181 .orElseThrow(NoSuchElementException::new);
182 }
183
184 private static long getStartTimestamp(
185 Set<TemporaryExposureKeyExport> temporaryExposureKeyExports) {
186 return temporaryExposureKeyExports.stream()
187 .mapToLong(TemporaryExposureKeyExport::getStartTimestamp)
188 .min()
189 .orElseThrow(NoSuchElementException::new);
190 }
191
192 private static long getEndTimestamp(Set<TemporaryExposureKeyExport> temporaryExposureKeyExports) {
193 return temporaryExposureKeyExports.stream()
194 .mapToLong(TemporaryExposureKeyExport::getEndTimestamp)
195 .max()
196 .orElseThrow(NoSuchElementException::new);
197 }
198 }
199
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/decorator/DateAggregatingDecorator.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/io/IO.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.distribution.assembly.io;
22
23 import java.io.File;
24 import java.io.FileOutputStream;
25 import java.io.IOException;
26 import java.io.UncheckedIOException;
27
28 /**
29 * A class containing helper functions for general purpose file IO.
30 */
31 public class IO {
32
33 private IO() {
34 }
35
36 /**
37 * Create a file on the disk if it does not already exist.
38 *
39 * @param root The parent file.
40 * @param name The name of the new file.
41 */
42 public static void makeNewFile(File root, String name) {
43 File directory = new File(root, name);
44 try {
45 if (!directory.createNewFile()) {
46 throw new IOException("Could not create " + name + ", file already exists");
47 }
48 } catch (IOException e) {
49 throw new UncheckedIOException("Failed to create file: " + name, e);
50 }
51 }
52
53 /**
54 * Writes bytes into a file.
55 *
56 * @param bytes The content to write
57 * @param outputFile The file to write the content into.
58 */
59 public static void writeBytesToFile(byte[] bytes, File outputFile) {
60 try (FileOutputStream outputFileStream = new FileOutputStream(outputFile)) {
61 outputFileStream.write(bytes);
62 } catch (IOException e) {
63 throw new UncheckedIOException("Could not write file " + outputFile, e);
64 }
65 }
66 }
67
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/io/IO.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/config/DistributionServiceConfig.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.distribution.config;
22
23 import app.coronawarn.server.common.protocols.external.exposurenotification.SignatureInfo;
24 import org.springframework.boot.context.properties.ConfigurationProperties;
25 import org.springframework.stereotype.Component;
26
27 @Component
28 @ConfigurationProperties(prefix = "services.distribution")
29 public class DistributionServiceConfig {
30
31 private Paths paths;
32 private TestData testData;
33 private Integer retentionDays;
34 private Integer expiryPolicyMinutes;
35 private Integer shiftingPolicyThreshold;
36 private String outputFileName;
37 private Boolean includeIncompleteDays;
38 private Boolean includeIncompleteHours;
39 private TekExport tekExport;
40 private Signature signature;
41 private Api api;
42 private ObjectStore objectStore;
43
44 public Paths getPaths() {
45 return paths;
46 }
47
48 public void setPaths(Paths paths) {
49 this.paths = paths;
50 }
51
52 public TestData getTestData() {
53 return testData;
54 }
55
56 public void setTestData(TestData testData) {
57 this.testData = testData;
58 }
59
60 public Integer getRetentionDays() {
61 return retentionDays;
62 }
63
64 public void setRetentionDays(Integer retentionDays) {
65 this.retentionDays = retentionDays;
66 }
67
68 public Integer getExpiryPolicyMinutes() {
69 return expiryPolicyMinutes;
70 }
71
72 public void setExpiryPolicyMinutes(Integer expiryPolicyMinutes) {
73 this.expiryPolicyMinutes = expiryPolicyMinutes;
74 }
75
76 public Integer getShiftingPolicyThreshold() {
77 return shiftingPolicyThreshold;
78 }
79
80 public void setShiftingPolicyThreshold(Integer shiftingPolicyThreshold) {
81 this.shiftingPolicyThreshold = shiftingPolicyThreshold;
82 }
83
84 public String getOutputFileName() {
85 return outputFileName;
86 }
87
88 public void setOutputFileName(String outputFileName) {
89 this.outputFileName = outputFileName;
90 }
91
92 public Boolean getIncludeIncompleteDays() {
93 return includeIncompleteDays;
94 }
95
96 public void setIncludeIncompleteDays(Boolean includeIncompleteDays) {
97 this.includeIncompleteDays = includeIncompleteDays;
98 }
99
100 public Boolean getIncludeIncompleteHours() {
101 return includeIncompleteHours;
102 }
103
104 public void setIncludeIncompleteHours(Boolean includeIncompleteHours) {
105 this.includeIncompleteHours = includeIncompleteHours;
106 }
107
108 public TekExport getTekExport() {
109 return tekExport;
110 }
111
112 public void setTekExport(TekExport tekExport) {
113 this.tekExport = tekExport;
114 }
115
116 public Signature getSignature() {
117 return signature;
118 }
119
120 public void setSignature(Signature signature) {
121 this.signature = signature;
122 }
123
124 public Api getApi() {
125 return api;
126 }
127
128 public void setApi(Api api) {
129 this.api = api;
130 }
131
132 public ObjectStore getObjectStore() {
133 return objectStore;
134 }
135
136 public void setObjectStore(
137 ObjectStore objectStore) {
138 this.objectStore = objectStore;
139 }
140
141 public static class TekExport {
142
143 private String fileName;
144 private String fileHeader;
145 private Integer fileHeaderWidth;
146
147 public String getFileName() {
148 return fileName;
149 }
150
151 public void setFileName(String fileName) {
152 this.fileName = fileName;
153 }
154
155 public String getFileHeader() {
156 return fileHeader;
157 }
158
159 public void setFileHeader(String fileHeader) {
160 this.fileHeader = fileHeader;
161 }
162
163 public Integer getFileHeaderWidth() {
164 return fileHeaderWidth;
165 }
166
167 public void setFileHeaderWidth(Integer fileHeaderWidth) {
168 this.fileHeaderWidth = fileHeaderWidth;
169 }
170 }
171
172 public static class TestData {
173
174 private Integer seed;
175 private Integer exposuresPerHour;
176
177 public Integer getSeed() {
178 return seed;
179 }
180
181 public void setSeed(Integer seed) {
182 this.seed = seed;
183 }
184
185 public Integer getExposuresPerHour() {
186 return exposuresPerHour;
187 }
188
189 public void setExposuresPerHour(Integer exposuresPerHour) {
190 this.exposuresPerHour = exposuresPerHour;
191 }
192 }
193
194 public static class Paths {
195
196 private String privateKey;
197 private String output;
198
199 public String getPrivateKey() {
200 return privateKey;
201 }
202
203 public void setPrivateKey(String privateKey) {
204 this.privateKey = privateKey;
205 }
206
207 public String getOutput() {
208 return output;
209 }
210
211 public void setOutput(String output) {
212 this.output = output;
213 }
214 }
215
216 public static class Api {
217
218 private String versionPath;
219 private String versionV1;
220 private String countryPath;
221 private String countryGermany;
222 private String datePath;
223 private String hourPath;
224 private String diagnosisKeysPath;
225 private String parametersPath;
226 private String appConfigFileName;
227
228 public String getVersionPath() {
229 return versionPath;
230 }
231
232 public void setVersionPath(String versionPath) {
233 this.versionPath = versionPath;
234 }
235
236 public String getVersionV1() {
237 return versionV1;
238 }
239
240 public void setVersionV1(String versionV1) {
241 this.versionV1 = versionV1;
242 }
243
244 public String getCountryPath() {
245 return countryPath;
246 }
247
248 public void setCountryPath(String countryPath) {
249 this.countryPath = countryPath;
250 }
251
252 public String getCountryGermany() {
253 return countryGermany;
254 }
255
256 public void setCountryGermany(String countryGermany) {
257 this.countryGermany = countryGermany;
258 }
259
260 public String getDatePath() {
261 return datePath;
262 }
263
264 public void setDatePath(String datePath) {
265 this.datePath = datePath;
266 }
267
268 public String getHourPath() {
269 return hourPath;
270 }
271
272 public void setHourPath(String hourPath) {
273 this.hourPath = hourPath;
274 }
275
276 public String getDiagnosisKeysPath() {
277 return diagnosisKeysPath;
278 }
279
280 public void setDiagnosisKeysPath(String diagnosisKeysPath) {
281 this.diagnosisKeysPath = diagnosisKeysPath;
282 }
283
284 public String getParametersPath() {
285 return parametersPath;
286 }
287
288 public void setParametersPath(String parametersPath) {
289 this.parametersPath = parametersPath;
290 }
291
292 public String getAppConfigFileName() {
293 return appConfigFileName;
294 }
295
296 public void setAppConfigFileName(String appConfigFileName) {
297 this.appConfigFileName = appConfigFileName;
298 }
299 }
300
301 public static class Signature {
302
303 private String appBundleId;
304 private String androidPackage;
305 private String verificationKeyId;
306 private String verificationKeyVersion;
307 private String algorithmOid;
308 private String algorithmName;
309 private String fileName;
310 private String securityProvider;
311
312 public String getAppBundleId() {
313 return appBundleId;
314 }
315
316 public void setAppBundleId(String appBundleId) {
317 this.appBundleId = appBundleId;
318 }
319
320 public String getAndroidPackage() {
321 return androidPackage;
322 }
323
324 public void setAndroidPackage(String androidPackage) {
325 this.androidPackage = androidPackage;
326 }
327
328 public String getVerificationKeyId() {
329 return verificationKeyId;
330 }
331
332 public void setVerificationKeyId(String verificationKeyId) {
333 this.verificationKeyId = verificationKeyId;
334 }
335
336 public String getVerificationKeyVersion() {
337 return verificationKeyVersion;
338 }
339
340 public void setVerificationKeyVersion(String verificationKeyVersion) {
341 this.verificationKeyVersion = verificationKeyVersion;
342 }
343
344 public String getAlgorithmOid() {
345 return algorithmOid;
346 }
347
348 public void setAlgorithmOid(String algorithmOid) {
349 this.algorithmOid = algorithmOid;
350 }
351
352 public String getAlgorithmName() {
353 return algorithmName;
354 }
355
356 public void setAlgorithmName(String algorithmName) {
357 this.algorithmName = algorithmName;
358 }
359
360 public String getFileName() {
361 return fileName;
362 }
363
364 public void setFileName(String fileName) {
365 this.fileName = fileName;
366 }
367
368 public String getSecurityProvider() {
369 return securityProvider;
370 }
371
372 public void setSecurityProvider(String securityProvider) {
373 this.securityProvider = securityProvider;
374 }
375
376 /**
377 * Returns the static {@link SignatureInfo} configured in the application properties.
378 */
379 public SignatureInfo getSignatureInfo() {
380 return SignatureInfo.newBuilder()
381 .setAppBundleId(this.getAppBundleId())
382 .setVerificationKeyVersion(this.getVerificationKeyVersion())
383 .setVerificationKeyId(this.getVerificationKeyId())
384 .setSignatureAlgorithm(this.getAlgorithmOid())
385 .build();
386 }
387 }
388
389 public static class ObjectStore {
390
391 private String accessKey;
392 private String secretKey;
393 private String endpoint;
394 private Integer port;
395 private String bucket;
396 private Boolean setPublicReadAclOnPutObject;
397 private Integer maxNumberOfFailedOperations;
398
399 public String getAccessKey() {
400 return accessKey;
401 }
402
403 public void setAccessKey(String accessKey) {
404 this.accessKey = accessKey;
405 }
406
407 public String getSecretKey() {
408 return secretKey;
409 }
410
411 public void setSecretKey(String secretKey) {
412 this.secretKey = secretKey;
413 }
414
415 public String getEndpoint() {
416 return endpoint;
417 }
418
419 public void setEndpoint(String endpoint) {
420 this.endpoint = endpoint;
421 }
422
423 public Integer getPort() {
424 return port;
425 }
426
427 public void setPort(Integer port) {
428 this.port = port;
429 }
430
431 public String getBucket() {
432 return bucket;
433 }
434
435 public void setBucket(String bucket) {
436 this.bucket = bucket;
437 }
438
439 public Boolean isSetPublicReadAclOnPutObject() {
440 return setPublicReadAclOnPutObject;
441 }
442
443 public void setSetPublicReadAclOnPutObject(Boolean setPublicReadAclOnPutObject) {
444 this.setPublicReadAclOnPutObject = setPublicReadAclOnPutObject;
445 }
446
447 public Integer getMaxNumberOfFailedOperations() {
448 return maxNumberOfFailedOperations;
449 }
450
451 public void setMaxNumberOfFailedOperations(Integer maxNumberOfFailedOperations) {
452 this.maxNumberOfFailedOperations = maxNumberOfFailedOperations;
453 }
454 }
455 }
456
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/config/DistributionServiceConfig.java]
[start of services/distribution/src/main/resources/application.yaml]
1 ---
2 logging:
3 level:
4 org:
5 springframework:
6 web: INFO
7 app:
8 coronawarn: INFO
9
10 services:
11 distribution:
12 output-file-name: index
13 retention-days: 14
14 expiry-policy-minutes: 120
15 shifting-policy-threshold: 140
16 include-incomplete-days: false
17 include-incomplete-hours: false
18 paths:
19 output: out
20 privatekey: ${VAULT_FILESIGNING_SECRET}
21 tek-export:
22 file-name: export.bin
23 file-header: EK Export v1
24 file-header-width: 16
25 api:
26 version-path: version
27 version-v1: v1
28 country-path: country
29 country-germany: DE
30 date-path: date
31 hour-path: hour
32 diagnosis-keys-path: diagnosis-keys
33 parameters-path: configuration
34 app-config-file-name: app_config
35 signature:
36 verification-key-id: 262
37 verification-key-version: v1
38 algorithm-oid: 1.2.840.10045.4.3.2
39 algorithm-name: SHA256withECDSA
40 file-name: export.sig
41 security-provider: BC
42 # Configuration for the S3 compatible object storage hosted by Telekom in Germany
43 objectstore:
44 access-key: ${CWA_OBJECTSTORE_ACCESSKEY:accessKey1}
45 secret-key: ${CWA_OBJECTSTORE_SECRETKEY:verySecretKey1}
46 endpoint: ${CWA_OBJECTSTORE_ENDPOINT:http://localhost}
47 bucket: ${CWA_OBJECTSTORE_BUCKET:cwa}
48 port: ${CWA_OBJECTSTORE_PORT:8003}
49 set-public-read-acl-on-put-object: true
50 retry-attempts: 3
51 retry-backoff: 2000
52 max-number-of-failed-operations: 5
53
54 spring:
55 main:
56 web-application-type: NONE
57 # Postgres configuration
58 jpa:
59 hibernate:
60 ddl-auto: validate
61 flyway:
62 enabled: true
63 locations: classpath:db/migration/postgres
64 password: ${POSTGRESQL_PASSWORD_FLYWAY:postgres}
65 user: ${POSTGRESQL_USER_FLYWAY:postgres}
66
67 datasource:
68 driver-class-name: org.postgresql.Driver
69 url: jdbc:postgresql://${POSTGRESQL_SERVICE_HOST:localhost}:${POSTGRESQL_SERVICE_PORT:5432}/${POSTGRESQL_DATABASE:cwa}
70 username: ${POSTGRESQL_USER_DISTRIBUTION:postgres}
71 password: ${POSTGRESQL_PASSWORD_DISTRIBUTION:postgres}
72
[end of services/distribution/src/main/resources/application.yaml]
</code>
Here is an example of a patch file. It consists of changes to the code base. It specifies the file names, the line numbers of each change, and the removed and added lines. A single patch file can contain changes to multiple files.
<patch>
--- a/file.py
+++ b/file.py
@@ -1,27 +1,35 @@
def euclidean(a, b):
- while b:
- a, b = b, a % b
- return a
+ if b == 0:
+ return a
+ return euclidean(b, a % b)
def bresenham(x0, y0, x1, y1):
points = []
dx = abs(x1 - x0)
dy = abs(y1 - y0)
- sx = 1 if x0 < x1 else -1
- sy = 1 if y0 < y1 else -1
- err = dx - dy
+ x, y = x0, y0
+ sx = -1 if x0 > x1 else 1
+ sy = -1 if y0 > y1 else 1
- while True:
- points.append((x0, y0))
- if x0 == x1 and y0 == y1:
- break
- e2 = 2 * err
- if e2 > -dy:
+ if dx > dy:
+ err = dx / 2.0
+ while x != x1:
+ points.append((x, y))
err -= dy
- x0 += sx
- if e2 < dx:
- err += dx
- y0 += sy
+ if err < 0:
+ y += sy
+ err += dx
+ x += sx
+ else:
+ err = dy / 2.0
+ while y != y1:
+ points.append((x, y))
+ err -= dx
+ if err < 0:
+ x += sx
+ err += dy
+ y += sy
+ points.append((x, y))
return points
</patch>
I need you to solve the provded issue by generating a single patch file that I can apply directly to this repository using git apply. Please respond with a single patch file in the format shown above.
Respond below:
| corona-warn-app/cwa-server | eb68e1126a4f9bcb169afef6a2ca1dbbbcf8b3cd | Distribution: Add Safeguard to not generate any exposure key file > 16MB
In order to prevent issues on the mobile device & potential abuse, add a safeguard, so that we do not publish any files, which are bigger than 16MB. In case this threshold is reached for any file, an error message must be logged.
Make sure to keep consistency with the index files. In order to align with the current concept of always generating a file, we should generate an empty file in this case as well.
@pithumke
| > In order to align with the current concept of always generating a file, we should generate an empty file in this case as well.
Will skip generating files larger than 600,000 keys in order to stay constistent with the current implementation. | 2020-06-05T22:23:20 | <patch>
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/DiagnosisKeyBundler.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/DiagnosisKeyBundler.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/DiagnosisKeyBundler.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/DiagnosisKeyBundler.java
@@ -27,6 +27,7 @@
import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
import java.time.LocalDate;
import java.time.LocalDateTime;
+import java.time.temporal.Temporal;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
@@ -35,12 +36,16 @@
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* An instance of this class contains a collection of {@link DiagnosisKey DiagnosisKeys}.
*/
public abstract class DiagnosisKeyBundler {
+ private static final Logger logger = LoggerFactory.getLogger(DiagnosisKeyBundler.class);
+
/**
* The submission timestamp is counted in 1 hour intervals since epoch.
*/
@@ -51,8 +56,9 @@ public abstract class DiagnosisKeyBundler {
*/
public static final long TEN_MINUTES_INTERVAL_SECONDS = TimeUnit.MINUTES.toSeconds(10);
- protected final int minNumberOfKeysPerBundle;
protected final long expiryPolicyMinutes;
+ protected final int minNumberOfKeysPerBundle;
+ private final int maxNumberOfKeysPerBundle;
// The hour at which the distribution runs. This field is needed to prevent the run from distributing any keys that
// have already been submitted but may only be distributed in the future (e.g. because they are not expired yet).
@@ -61,9 +67,13 @@ public abstract class DiagnosisKeyBundler {
// A map containing diagnosis keys, grouped by the LocalDateTime on which they may be distributed
protected final Map<LocalDateTime, List<DiagnosisKey>> distributableDiagnosisKeys = new HashMap<>();
+ /**
+ * Constructs a DiagnosisKeyBundler based on the specified service configuration.
+ */
public DiagnosisKeyBundler(DistributionServiceConfig distributionServiceConfig) {
- this.minNumberOfKeysPerBundle = distributionServiceConfig.getShiftingPolicyThreshold();
this.expiryPolicyMinutes = distributionServiceConfig.getExpiryPolicyMinutes();
+ this.minNumberOfKeysPerBundle = distributionServiceConfig.getShiftingPolicyThreshold();
+ this.maxNumberOfKeysPerBundle = distributionServiceConfig.getMaximumNumberOfKeysPerBundle();
}
/**
@@ -106,9 +116,14 @@ public List<DiagnosisKey> getAllDiagnosisKeys() {
public Set<LocalDate> getDatesWithDistributableDiagnosisKeys() {
return this.distributableDiagnosisKeys.keySet().stream()
.map(LocalDateTime::toLocalDate)
+ .filter(this::numberOfKeysForDateBelowMaximum)
.collect(Collectors.toSet());
}
+ public boolean numberOfKeysForDateBelowMaximum(LocalDate date) {
+ return numberOfKeysBelowMaximum(getDiagnosisKeysForDate(date).size(), date);
+ }
+
/**
* Returns a set of all {@link LocalDateTime hours} of a specified {@link LocalDate date} during which {@link
* DiagnosisKey diagnosis keys} shall be distributed.
@@ -116,9 +131,23 @@ public Set<LocalDate> getDatesWithDistributableDiagnosisKeys() {
public Set<LocalDateTime> getHoursWithDistributableDiagnosisKeys(LocalDate currentDate) {
return this.distributableDiagnosisKeys.keySet().stream()
.filter(dateTime -> dateTime.toLocalDate().equals(currentDate))
+ .filter(this::numberOfKeysForHourBelowMaximum)
.collect(Collectors.toSet());
}
+ private boolean numberOfKeysForHourBelowMaximum(LocalDateTime hour) {
+ return numberOfKeysBelowMaximum(getDiagnosisKeysForHour(hour).size(), hour);
+ }
+
+ private boolean numberOfKeysBelowMaximum(int numberOfKeys, Temporal time) {
+ if (numberOfKeys > maxNumberOfKeysPerBundle) {
+ logger.error("Number of diagnosis keys ({}) for {} exceeds the configured maximum.", numberOfKeys, time);
+ return false;
+ } else {
+ return true;
+ }
+ }
+
/**
* Returns the submission timestamp of a {@link DiagnosisKey} as a {@link LocalDateTime}.
*/
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysCountryDirectory.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysCountryDirectory.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysCountryDirectory.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysCountryDirectory.java
@@ -67,6 +67,6 @@ public void prepare(ImmutableStack<Object> indices) {
private IndexDirectory<LocalDate, WritableOnDisk> decorateDateDirectory(DiagnosisKeysDateDirectory dateDirectory) {
return new DateAggregatingDecorator(new DateIndexingDecorator(dateDirectory, distributionServiceConfig),
- cryptoProvider, distributionServiceConfig);
+ cryptoProvider, distributionServiceConfig, diagnosisKeyBundler);
}
}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/decorator/DateAggregatingDecorator.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/decorator/DateAggregatingDecorator.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/decorator/DateAggregatingDecorator.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/decorator/DateAggregatingDecorator.java
@@ -25,6 +25,7 @@
import app.coronawarn.server.common.protocols.external.exposurenotification.TemporaryExposureKey;
import app.coronawarn.server.common.protocols.external.exposurenotification.TemporaryExposureKeyExport;
import app.coronawarn.server.services.distribution.assembly.component.CryptoProvider;
+import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.DiagnosisKeyBundler;
import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.archive.decorator.singing.DiagnosisKeySigningDecorator;
import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.file.TemporaryExposureKeyExportFile;
import app.coronawarn.server.services.distribution.assembly.structure.Writable;
@@ -54,15 +55,17 @@ public class DateAggregatingDecorator extends IndexDirectoryDecorator<LocalDate,
private final CryptoProvider cryptoProvider;
private final DistributionServiceConfig distributionServiceConfig;
+ private final DiagnosisKeyBundler diagnosisKeyBundler;
/**
* Creates a new DateAggregatingDecorator.
*/
public DateAggregatingDecorator(IndexDirectory<LocalDate, WritableOnDisk> directory, CryptoProvider cryptoProvider,
- DistributionServiceConfig distributionServiceConfig) {
+ DistributionServiceConfig distributionServiceConfig, DiagnosisKeyBundler diagnosisKeyBundler) {
super(directory);
this.cryptoProvider = cryptoProvider;
this.distributionServiceConfig = distributionServiceConfig;
+ this.diagnosisKeyBundler = diagnosisKeyBundler;
}
@Override
@@ -77,6 +80,7 @@ public void prepare(ImmutableStack<Object> indices) {
}
Set<String> dates = this.getIndex(indices).stream()
+ .filter(diagnosisKeyBundler::numberOfKeysForDateBelowMaximum)
.map(this.getIndexFormatter())
.map(Object::toString)
.collect(Collectors.toSet());
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/io/IO.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/io/IO.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/io/IO.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/io/IO.java
@@ -30,6 +30,11 @@
*/
public class IO {
+ /**
+ * The maximum acceptable file size in bytes.
+ */
+ public static final int MAXIMUM_FILE_SIZE = 16000000;
+
private IO() {
}
@@ -51,12 +56,20 @@ public static void makeNewFile(File root, String name) {
}
/**
- * Writes bytes into a file.
+ * Writes bytes into a file. If the resulting file would exceed the specified maximum file size, it is not written but
+ * removed instead.
*
* @param bytes The content to write
* @param outputFile The file to write the content into.
*/
public static void writeBytesToFile(byte[] bytes, File outputFile) {
+ if (bytes.length > MAXIMUM_FILE_SIZE) {
+ String fileName = outputFile.getName();
+ throw new UncheckedIOException(
+ new IOException(
+ "File size of " + bytes.length + " bytes exceeds the maximum file size. Deleting" + fileName));
+ }
+
try (FileOutputStream outputFileStream = new FileOutputStream(outputFile)) {
outputFileStream.write(bytes);
} catch (IOException e) {
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/config/DistributionServiceConfig.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/config/DistributionServiceConfig.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/config/DistributionServiceConfig.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/config/DistributionServiceConfig.java
@@ -33,6 +33,7 @@ public class DistributionServiceConfig {
private Integer retentionDays;
private Integer expiryPolicyMinutes;
private Integer shiftingPolicyThreshold;
+ private Integer maximumNumberOfKeysPerBundle;
private String outputFileName;
private Boolean includeIncompleteDays;
private Boolean includeIncompleteHours;
@@ -81,6 +82,14 @@ public void setShiftingPolicyThreshold(Integer shiftingPolicyThreshold) {
this.shiftingPolicyThreshold = shiftingPolicyThreshold;
}
+ public Integer getMaximumNumberOfKeysPerBundle() {
+ return this.maximumNumberOfKeysPerBundle;
+ }
+
+ public void setMaximumNumberOfKeysPerBundle(Integer maximumNumberOfKeysPerBundle) {
+ this.maximumNumberOfKeysPerBundle = maximumNumberOfKeysPerBundle;
+ }
+
public String getOutputFileName() {
return outputFileName;
}
diff --git a/services/distribution/src/main/resources/application.yaml b/services/distribution/src/main/resources/application.yaml
--- a/services/distribution/src/main/resources/application.yaml
+++ b/services/distribution/src/main/resources/application.yaml
@@ -13,6 +13,7 @@ services:
retention-days: 14
expiry-policy-minutes: 120
shifting-policy-threshold: 140
+ maximum-number-of-keys-per-bundle: 600000
include-incomplete-days: false
include-incomplete-hours: false
paths:
</patch> | diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/decorator/DateIndexingDecoratorTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/decorator/DateIndexingDecoratorTest.java
--- a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/decorator/DateIndexingDecoratorTest.java
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/decorator/DateIndexingDecoratorTest.java
@@ -22,6 +22,8 @@
import static app.coronawarn.server.services.distribution.common.Helpers.buildDiagnosisKeys;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
import app.coronawarn.server.services.distribution.assembly.component.CryptoProvider;
@@ -96,6 +98,30 @@ void excludesCurrentDateFromIndex() {
assertThat(index).doesNotContain(LocalDate.of(1970, 1, 5));
}
+ @Test
+ void excludesDatesThatExceedTheMaximumNumberOfKeys() {
+ List<DiagnosisKey> diagnosisKeys = Stream
+ .of(buildDiagnosisKeys(6, LocalDateTime.of(1970, 1, 3, 6, 0), 1),
+ buildDiagnosisKeys(6, LocalDateTime.of(1970, 1, 3, 10, 0), 1))
+ .flatMap(List::stream)
+ .collect(Collectors.toList());
+
+ DistributionServiceConfig svcConfig = mock(DistributionServiceConfig.class);
+ when(svcConfig.getExpiryPolicyMinutes()).thenReturn(120);
+ when(svcConfig.getShiftingPolicyThreshold()).thenReturn(1);
+ when(svcConfig.getMaximumNumberOfKeysPerBundle()).thenReturn(1);
+
+ DiagnosisKeyBundler diagnosisKeyBundler = new ProdDiagnosisKeyBundler(svcConfig);
+ diagnosisKeyBundler.setDiagnosisKeys(diagnosisKeys, LocalDateTime.of(1970, 1, 5, 0, 0));
+
+ DateIndexingDecorator decorator = makeDecoratedDateDirectory(diagnosisKeyBundler);
+
+ decorator.prepare(new ImmutableStack<>().push("DE"));
+
+ Set<LocalDate> index = decorator.getIndex(new ImmutableStack<>());
+ assertThat(index).isEmpty();
+ }
+
private DateIndexingDecorator makeDecoratedDateDirectory(DiagnosisKeyBundler diagnosisKeyBundler) {
return new DateIndexingDecorator(
new DiagnosisKeysDateDirectory(diagnosisKeyBundler, cryptoProvider, distributionServiceConfig),
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/decorator/HourIndexingDecoratorTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/decorator/HourIndexingDecoratorTest.java
--- a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/decorator/HourIndexingDecoratorTest.java
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/decorator/HourIndexingDecoratorTest.java
@@ -22,6 +22,8 @@
import static app.coronawarn.server.services.distribution.common.Helpers.buildDiagnosisKeys;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
import app.coronawarn.server.services.distribution.assembly.component.CryptoProvider;
@@ -34,8 +36,6 @@
import java.time.LocalDateTime;
import java.util.List;
import java.util.Set;
-import java.util.stream.Collectors;
-import java.util.stream.Stream;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
@@ -65,26 +65,27 @@ void setup() {
}
@Test
- void excludesEmptyHoursFromIndex() {
- List<DiagnosisKey> diagnosisKeys = Stream
- .of(buildDiagnosisKeys(6, LocalDateTime.of(1970, 1, 3, 4, 0), 5),
- buildDiagnosisKeys(6, LocalDateTime.of(1970, 1, 3, 5, 0), 0),
- buildDiagnosisKeys(6, LocalDateTime.of(1970, 1, 3, 6, 0), 5))
- .flatMap(List::stream)
- .collect(Collectors.toList());
+ void excludesHoursThatExceedTheMaximumNumberOfKeys() {
+ List<DiagnosisKey> diagnosisKeys = buildDiagnosisKeys(6, LocalDateTime.of(1970, 1, 3, 4, 0), 2);
+
+ DistributionServiceConfig svcConfig = mock(DistributionServiceConfig.class);
+ when(svcConfig.getExpiryPolicyMinutes()).thenReturn(120);
+ when(svcConfig.getShiftingPolicyThreshold()).thenReturn(1);
+ when(svcConfig.getMaximumNumberOfKeysPerBundle()).thenReturn(1);
+
+ DiagnosisKeyBundler diagnosisKeyBundler = new ProdDiagnosisKeyBundler(svcConfig);
diagnosisKeyBundler.setDiagnosisKeys(diagnosisKeys, LocalDateTime.of(1970, 1, 5, 0, 0));
+
HourIndexingDecorator decorator = makeDecoratedHourDirectory(diagnosisKeyBundler);
- decorator.prepare(new ImmutableStack<>().push("DE").push(LocalDate.of(1970, 1, 3)));
+ decorator.prepare(new ImmutableStack<>().push("DE").push(LocalDate.of(1970, 1, 3)));
Set<LocalDateTime> index = decorator.getIndex(new ImmutableStack<>().push(LocalDate.of(1970, 1, 3)));
- assertThat(index).contains(LocalDateTime.of(1970, 1, 3, 4, 0));
- assertThat(index).doesNotContain(LocalDateTime.of(1970, 1, 3, 5, 0));
- assertThat(index).contains(LocalDateTime.of(1970, 1, 3, 6, 0));
+ assertThat(index).isEmpty();
}
@Test
- void excludesCurrentHourFromIndex() {
+ void excludesEmptyHoursFromIndex() {
List<DiagnosisKey> diagnosisKeys = buildDiagnosisKeys(6, LocalDateTime.of(1970, 1, 5, 0, 0), 5);
diagnosisKeyBundler.setDiagnosisKeys(diagnosisKeys, LocalDateTime.of(1970, 1, 5, 1, 0));
HourIndexingDecorator decorator = makeDecoratedHourDirectory(diagnosisKeyBundler);
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/io/IOTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/io/IOTest.java
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/io/IOTest.java
@@ -0,0 +1,42 @@
+/*-
+ * ---license-start
+ * Corona-Warn-App
+ * ---
+ * Copyright (C) 2020 SAP SE and all other contributors
+ * ---
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://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 for the specific language governing permissions and
+ * limitations under the License.
+ * ---license-end
+ */
+
+package app.coronawarn.server.services.distribution.assembly.io;
+
+
+import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+
+import java.io.File;
+import java.io.UncheckedIOException;
+import org.junit.jupiter.api.Test;
+
+class IOTest {
+
+ @Test
+ void doesNotWriteIfMaximumFileSize() {
+ File file = mock(File.class);
+ assertThatExceptionOfType(UncheckedIOException.class)
+ .isThrownBy(() -> IO.writeBytesToFile(new byte[IO.MAXIMUM_FILE_SIZE + 1], file));
+ verify(file, never()).getPath();
+ }
+}
diff --git a/services/distribution/src/test/resources/application.yaml b/services/distribution/src/test/resources/application.yaml
--- a/services/distribution/src/test/resources/application.yaml
+++ b/services/distribution/src/test/resources/application.yaml
@@ -11,6 +11,7 @@ services:
retention-days: 14
expiry-policy-minutes: 120
shifting-policy-threshold: 5
+ maximum-number-of-keys-per-bundle: 600000
include-incomplete-days: false
include-incomplete-hours: false
paths:
| ||||
corona-warn-app__cwa-server-272 | You will be provided with a partial code base and an issue statement explaining a problem to resolve.
<issue>
Update signature algorithm to SHA-256 + ECDSA P-256
## Feature description
The current CWA server implementation signs diagnosis key packages with the ``Ed25519`` algorithm. However, the current [Google/Apple spec](https://developer.apple.com/documentation/exposurenotification/setting_up_an_exposure_notification_server) demands ``SHA-256`` hash with ``ECDSA P-256`` signature ([OID 1.2.840.10045.4.3.2](http://oid-info.com/get/1.2.840.10045.4.3.2))
</issue>
<code>
[start of README.md]
1 <h1 align="center">
2 Corona-Warn-App Server
3 </h1>
4
5 <p align="center">
6 <a href="https://github.com/corona-warn-app/cwa-server/commits/" title="Last Commit"><img src="https://img.shields.io/github/last-commit/corona-warn-app/cwa-server?style=flat"></a>
7 <a href="https://github.com/corona-warn-app/cwa-server/issues" title="Open Issues"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat"></a>
8 <a href="https://circleci.com/gh/corona-warn-app/cwa-server" title="Build Status"><img src="https://circleci.com/gh/corona-warn-app/cwa-server.svg?style=shield&circle-token=4ab059989d10709df19eb4b98ab7c121a25e981a"></a>
9 <a href="https://sonarcloud.io/dashboard?id=corona-warn-app_cwa-server" title="Quality Gate"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=alert_status"></a>
10 <a href="https://sonarcloud.io/component_measures?id=corona-warn-app_cwa-server&metric=Coverage&view=list" title="Coverage"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=coverage"></a>
11 <a href="https://github.com/corona-warn-app/cwa-server/blob/master/LICENSE" title="License"><img src="https://img.shields.io/badge/License-Apache%202.0-green.svg?style=flat"></a>
12 </p>
13
14 <p align="center">
15 <a href="#development">Development</a> •
16 <a href="#service-apis">Service APIs</a> •
17 <a href="#documentation">Documentation</a> •
18 <a href="#support-and-feedback">Support</a> •
19 <a href="#how-to-contribute">Contribute</a> •
20 <a href="#contributors">Contributors</a> •
21 <a href="#repositories">Repositories</a> •
22 <a href="#licensing">Licensing</a>
23 </p>
24
25 The goal of this project is to develop the official Corona-Warn-App for Germany based on the exposure notification API from [Apple](https://www.apple.com/covid19/contacttracing/) and [Google](https://www.google.com/covid19/exposurenotifications/). The apps (for both iOS and Android) use Bluetooth technology to exchange anonymous encrypted data with other mobile phones (on which the app is also installed) in the vicinity of an app user's phone. The data is stored locally on each user's device, preventing authorities or other parties from accessing or controlling the data. This repository contains the **implementation of the server for encryption keys** for the Corona-Warn-App. This implementation is still a **work in progress**, and the code it contains is currently alpha-quality code.
26
27 In this documentation, Corona-Warn-App services are also referred to as CWA services.
28
29 ## Architecture Overview
30
31 You can find the architecture overview [here](/docs/architecture-overview.md), which will give you
32 a good starting point in how the backend services interact with other services, and what purpose
33 they serve.
34
35 ## Development
36
37 After you've checked out this repository, you can run the application in one of the following ways:
38
39 * As a [Docker](https://www.docker.com/)-based deployment on your local machine. You can run either:
40 * Single components using the respective Dockerfile or
41 * The full backend using the Docker Compose (which is considered the most convenient way)
42 * As a [Maven](https://maven.apache.org)-based build on your local machine.
43 If you want to develop something in a single component, this approach is preferable.
44
45 ### Docker-Based Deployment
46
47 If you want to use Docker-based deployment, you need to install Docker on your local machine. For more information about downloading and installing Docker, see the [official Docker documentation](https://docs.docker.com/get-docker/).
48
49 #### Running the Full CWA Backend Using Docker Compose
50
51 For your convenience, a full setup including the generation of test data has been prepared using [Docker Compose](https://docs.docker.com/compose/reference/overview/). To build the backend services, run ```docker-compose build``` in the repository's root directory. A default configuration file can be found under ```.env```in the root folder of the repository. The default values for the local Postgres and Zenko Cloudserver should be changed in this file before docker-compose is run.
52
53 Once the services are built, you can start the whole backend using ```docker-compose up```.
54 The distribution service runs once and then finishes. If you want to trigger additional distribution runs, run ```docker-compose run distribution```.
55
56 The docker-compose contains the following services:
57
58 Service | Description | Endpoint and Default Credentials
59 --------------|-------------|-----------
60 submission | The Corona-Warn-App submission service | http://localhost:8000
61 distribution | The Corona-Warn-App distribution service | NO ENDPOINT
62 postgres | A [postgres] database installation | postgres:8001 <br> Username: postgres <br> Password: postgres
63 pgadmin | A [pgadmin](https://www.pgadmin.org/) installation for the postgres database | http://localhost:8002 <br> Username: [email protected] <br> Password: password
64 cloudserver | [Zenko CloudServer] is a S3-compliant object store | http://localhost:8003/ <br> Access key: accessKey1 <br> Secret key: verySecretKey1
65
66 ##### Known Limitation
67
68 The docker-compose runs into a timing issue in some cases when the create-bucket target runs before the objectstore is available. The mitigation is easy: after running ```docker-compose up``` wait until all components are initialized and running. Afterwards, trigger the ```create-bucket``` service manually by running ```docker-compose run create-bucket```. If you want to trigger distribution runs, run ```docker-compose run distribution```. The timing issue will be fixed in a future release.
69
70 #### Running Single CWA Services Using Docker
71
72 If you would like to build and run a single CWA service, it's considered easiest to run them in a Docker environment. You can do this using the script provided in the respective CWA service directory. The Docker script first builds the CWA service and then creates an image for the runtime, which means that there are no additional dependencies for you to install.
73
74 To build and run the distribution service, run the following command:
75
76 ```bash
77 ./services/distribution/build_and_run.sh
78 ```
79
80 To build and run the submission service, run the following command:
81
82 ```bash
83 ./services/submission/build_and_run.sh
84 ```
85
86 The submission service is available on [localhost:8080](http://localhost:8080 ).
87
88 ### Maven-Based Build
89
90 If you want to actively develop in one of the CWA services, the Maven-based runtime is most suitable.
91 To prepare your machine to run the CWA project locally, we recommend that you first ensure that you've installed the following:
92
93 * Minimum JDK Version 11: [OpenJDK](https://openjdk.java.net/) / [SapMachine](https://sap.github.io/SapMachine/)
94 * [Maven 3.6](https://maven.apache.org/)
95 * [Postgres]
96 * [Zenko CloudServer]
97
98 #### Configure
99
100 After you made sure that the specified dependencies are running, configure them in the respective configuration files.
101
102 * Configure the Postgres connection in the [submission config](./services/submission/src/main/resources/application.properties) and in the [distribution config](./services/distribution/src/main/resources/application.properties)
103 * Configure the S3 compatible object storage in the [distribution config](./services/distribution/src/main/resources/application.properties)
104 * Configure the certificate and private key for the distribution service, the paths need to be prefixed with `file:`
105 * `VAULT_FILESIGNING_SECRET` should be the path to the private key, example available in `<repo-root>/docker-compose-test-secrets/private.pem`
106 * `VAULT_FILESIGNING_CERT` should be the path to the certificate, example available in `<repo-root>/docker-compose-test-secrets/certificate.cert`
107
108 #### Build
109
110 After you've checked out the repository, to build the project, run ```mvn install``` in your base directory.
111
112 #### Run
113
114 Navigate to the service you want to start and run the spring-boot:run target. The configured Postgres and the configured S3 compliant object storage are used as default. When you start the submission service, the endpoint is available on your local port 8080.
115
116 If you want to start the submission service, for example, you start it as follows:
117
118 ```bash
119 cd services/submission/
120 mvn spring-boot:run
121 ```
122
123 #### Debugging
124
125 To enable the `DEBUG` log level, you can run the application using the Spring `dev` profile.
126
127 ```bash
128 mvn spring-boot:run -Dspring-boot.run.profiles=dev
129 ```
130
131 To be able to set breakpoints (e.g. in IntelliJ), it may be necessary to use the ```-Dspring-boot.run.fork=false``` parameter.
132
133 ## Service APIs
134
135 The API that is being exposed by the backend services is documented in an [OpenAPI](https://www.openapis.org/) specification. The specification files are available at the following locations:
136
137 Service | OpenAPI Specification
138 -------------|-------------
139 Submission Service | https://github.com/corona-warn-app/cwa-server/raw/master/services/submission/api_v1.json
140 Distribution Service | https://github.com/corona-warn-app/cwa-server/raw/master/services/distribution/api_v1.json
141
142 ## Documentation
143
144 The full documentation for the Corona-Warn-App can be found in the [cwa-documentation](https://github.com/corona-warn-app/cwa-documentation) repository. The documentation repository contains technical documents, architecture information, and whitepapers related to this implementation.
145
146 ## Support and Feedback
147
148 The following channels are available for discussions, feedback, and support requests:
149
150 | Type | Channel |
151 | ------------------------ | ------------------------------------------------------ |
152 | **General Discussion** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="General Discussion"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/question.svg?style=flat-square"></a> </a> |
153 | **Concept Feedback** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="Open Concept Feedback"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/architecture.svg?style=flat-square"></a> |
154 | **Backend Issue** | <a href="https://github.com/corona-warn-app/cwa-server/issues/new/choose" title="Open Backend Issue"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat-square"></a> |
155 | **Other Requests** | <a href="mailto:[email protected]" title="Email CWA Team"><img src="https://img.shields.io/badge/email-CWA%20team-green?logo=mail.ru&style=flat-square&logoColor=white"></a> |
156
157 ## How to Contribute
158
159 Contribution and feedback are 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.
160
161 ## Contributors
162
163 The German government has asked SAP and Deutsche Telekom to develop the Corona-Warn-App for Germany as open source software. Deutsche Telekom is providing the network and mobile technology and will operate and run the backend for the app in a safe, scalable and stable manner. SAP is responsible for the app development, its framework and the underlying platform. Therefore, development teams of SAP and Deutsche Telekom are contributing to this project. At the same time 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.
164
165 ## Repositories
166
167 The following public repositories are currently available for the Corona-Warn-App:
168
169 | Repository | Description |
170 | ------------------- | --------------------------------------------------------------------- |
171 | [cwa-documentation] | Project overview, general documentation, and white papers |
172 | [cwa-server] | Backend implementation for the Apple/Google exposure notification API|
173
174 [cwa-documentation]: https://github.com/corona-warn-app/cwa-documentation
175 [cwa-server]: https://github.com/corona-warn-app/cwa-server
176 [Postgres]: https://www.postgresql.org/
177 [HSQLDB]: http://hsqldb.org/
178 [Zenko CloudServer]: https://github.com/scality/cloudserver
179
180 ## Licensing
181
182 Copyright (c) 2020 SAP SE or an SAP affiliate company.
183
184 Licensed under the **Apache License, Version 2.0** (the "License"); you may not use this file except in compliance with the License.
185
186 You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0.
187
188 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.
189
[end of README.md]
[start of docker-compose-test-secrets/certificate.crt]
1 -----BEGIN CERTIFICATE-----
2 MIHxMIGkAgFkMAUGAytlcDAkMSIwIAYDVQQDDBlFTkEgVGVzdCBSb290IENlcnRp
3 ZmljYXRlMB4XDTIwMDQzMDE0MDQ1NVoXDTIxMDQzMDE0MDQ1NVowJjEkMCIGA1UE
4 AwwbRU5BIFRlc3QgQ2xpZW50IENlcnRpZmljYXRlMCowBQYDK2VwAyEAKb/6ocYD
5 5sIoiGUjHSCiHP3oAZxwtBicRxQVhqZhZIUwBQYDK2VwA0EAw6EUybzXxad6U39C
6 d1AwMBQ8b2k0pgd2VeJHn46hr5uByJ/MB+fHkgj0SkFhVbfhffcjq23FQKu7lZ/Z
7 HxakDA==
8 -----END CERTIFICATE-----
9 -----BEGIN CERTIFICATE-----
10 MIIBAjCBtQIULaMo9wOjHWZrpxuH+sN3ZPeT9EUwBQYDK2VwMCQxIjAgBgNVBAMM
11 GUVOQSBUZXN0IFJvb3QgQ2VydGlmaWNhdGUwHhcNMjAwNDMwMTQwNDU1WhcNMjEw
12 NDMwMTQwNDU1WjAkMSIwIAYDVQQDDBlFTkEgVGVzdCBSb290IENlcnRpZmljYXRl
13 MCowBQYDK2VwAyEADapVfRHr20spX2u6Wx8ImeoUZiJJU5cyG3zhqOl1pJAwBQYD
14 K2VwA0EA9MRmDLKz60SiPAWtD6HDEZB7wCEC/vUm6rMZ9+VcEXQlBlGbiIabkX8C
15 9pJ00fNzlbftmI8SiO/kjWSnwyCRBA==
16 -----END CERTIFICATE-----
17
[end of docker-compose-test-secrets/certificate.crt]
[start of docker-compose-test-secrets/private.pem]
1 -----BEGIN PRIVATE KEY-----
2 MC4CAQAwBQYDK2VwBCIEICW8533MLMm66KvHObhk7Q/gUYAJ4h/+GoO/oe5e/CbU
3 -----END PRIVATE KEY-----
4
[end of docker-compose-test-secrets/private.pem]
[start of scripts/generate_certificates.sh]
1 #!/bin/bash
2
3 # Generates a new self-signed X.509 root certificate and a client certificate. Only to be used for
4 # testing purposes. This script requires openssl to be installed, see here:
5 ## https://www.openssl.org/source/
6
7 pushd "$(dirname "${BASH_SOURCE[0]}")" > /dev/null || exit
8
9 rm -rf certificates
10 mkdir certificates
11 pushd certificates > /dev/null || exit
12
13 # Generate a private key
14 # $1 = OUT Private key file
15 generate_private_key()
16 {
17 openssl genpkey \
18 -algorithm ED25519 \
19 -out "$1"
20 }
21
22 # Generate certificate signing request
23 # $1 = IN New certificate private key
24 # $2 = IN "Subject" of the certificate
25 # $3 = OUT Certificate signing request file
26 generate_certificate_signing_request()
27 {
28 openssl req \
29 -new \
30 -key "$1" \
31 -subj "$2" \
32 -out "$3"
33 }
34
35 # Self-sign a certificate request
36 # $1 = IN Certificate signing request file
37 # $2 = IN Certificate authority private key file
38 # $3 = OUT New certificate file
39 self_sign_certificate_request()
40 {
41 openssl x509 \
42 -req \
43 -days 365 \
44 -in "$1" \
45 -signkey "$2" \
46 -out "$3"
47 }
48
49 # Sign a certificate request using a CA certificate + private key
50 # $1 = IN Certificate signing request file
51 # $2 = IN Certificate authority certificate file
52 # $3 = IN Certificate authority private key file
53 # $4 = OUT New certificate file
54 ca_sign_certificate_request()
55 {
56 openssl x509 \
57 -req \
58 -days 365 \
59 -set_serial 100 \
60 -in "$1" \
61 -CA "$2" \
62 -CAkey "$3" \
63 -out "$4"
64 }
65
66 # Self-signed root certificate
67 mkdir root
68 generate_private_key root/private.pem
69 generate_certificate_signing_request root/private.pem '/CN=CWA Test Root Certificate' root/request.csr
70 self_sign_certificate_request root/request.csr root/private.pem root/certificate.crt
71
72 # Client certificate signed by root certificate
73 mkdir client
74 generate_private_key client/private.pem
75 generate_certificate_signing_request client/private.pem '/CN=CWA Test Client Certificate' client/request.csr
76 ca_sign_certificate_request client/request.csr root/certificate.crt root/private.pem client/certificate.crt
77
78 # Concatenate the root certificate and the client certificate.
79 # This way, we have the whole certificate chain in a single file.
80 mkdir chain
81 cat client/certificate.crt root/certificate.crt >> chain/certificate.crt
82
83 # Final verification of the certificate chain
84 openssl verify -CAfile root/certificate.crt chain/certificate.crt
85
86 popd > /dev/null || exit
87 popd > /dev/null || exit
[end of scripts/generate_certificates.sh]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/component/CryptoProvider.java]
1 /*
2 * Corona-Warn-App
3 *
4 * SAP SE and all other contributors /
5 * copyright owners license this file to you under the Apache
6 * License, Version 2.0 (the "License"); you may not use this
7 * file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20 package app.coronawarn.server.services.distribution.assembly.component;
21
22 import java.io.ByteArrayInputStream;
23 import java.io.IOException;
24 import java.io.InputStream;
25 import java.io.InputStreamReader;
26 import java.security.PrivateKey;
27 import java.security.Security;
28 import java.security.cert.Certificate;
29 import java.security.cert.CertificateException;
30 import java.security.cert.CertificateFactory;
31 import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
32 import org.bouncycastle.jce.provider.BouncyCastleProvider;
33 import org.bouncycastle.openssl.PEMParser;
34 import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
37 import org.springframework.beans.factory.annotation.Autowired;
38 import org.springframework.beans.factory.annotation.Value;
39 import org.springframework.core.io.Resource;
40 import org.springframework.core.io.ResourceLoader;
41 import org.springframework.stereotype.Component;
42
43 /**
44 * Wrapper component for a {@link CryptoProvider#getPrivateKey() private key} and a {@link
45 * CryptoProvider#getCertificate()} certificate} from the application properties.
46 */
47 @Component
48 public class CryptoProvider {
49
50 private static final Logger logger = LoggerFactory.getLogger(CryptoProvider.class);
51
52 @Value("${services.distribution.paths.privatekey}")
53 private String privateKeyPath;
54
55 @Value("${services.distribution.paths.certificate}")
56 private String certificatePath;
57
58 private final ResourceLoader resourceLoader;
59
60 private PrivateKey privateKey;
61 private Certificate certificate;
62
63 /**
64 * Creates a CryptoProvider, using {@link BouncyCastleProvider}.
65 */
66 @Autowired
67 public CryptoProvider(ResourceLoader resourceLoader) {
68 this.resourceLoader = resourceLoader;
69 Security.addProvider(new BouncyCastleProvider());
70 }
71
72 private static PrivateKey getPrivateKeyFromStream(final InputStream privateKeyStream)
73 throws IOException {
74 PEMParser pemParser = new PEMParser(new InputStreamReader(privateKeyStream));
75 PrivateKeyInfo privateKeyInfo = (PrivateKeyInfo) pemParser.readObject();
76 return new JcaPEMKeyConverter().getPrivateKey(privateKeyInfo);
77 }
78
79 private static Certificate getCertificateFromStream(final InputStream certificateStream)
80 throws IOException, CertificateException {
81 return getCertificateFromBytes(certificateStream.readAllBytes());
82 }
83
84 private static Certificate getCertificateFromBytes(final byte[] bytes)
85 throws CertificateException {
86 CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
87 InputStream certificateByteStream = new ByteArrayInputStream(bytes);
88 return certificateFactory.generateCertificate(certificateByteStream);
89 }
90
91 /**
92 * Reads and returns the {@link PrivateKey} configured in the application properties.
93 */
94 public PrivateKey getPrivateKey() {
95 if (privateKey == null) {
96 Resource privateKeyResource = resourceLoader.getResource(privateKeyPath);
97 try (InputStream privateKeyStream = privateKeyResource.getInputStream()) {
98 privateKey = getPrivateKeyFromStream(privateKeyStream);
99 } catch (IOException e) {
100 logger.error("Failed to load private key from {}", privateKeyPath, e);
101 throw new RuntimeException(e);
102 }
103 }
104 return privateKey;
105 }
106
107 /**
108 * Reads and returns the {@link Certificate} configured in the application properties.
109 */
110 public Certificate getCertificate() {
111 if (this.certificate == null) {
112 Resource certResource = resourceLoader.getResource(certificatePath);
113 try (InputStream certStream = certResource.getInputStream()) {
114 this.certificate = getCertificateFromStream(certStream);
115 } catch (IOException | CertificateException e) {
116 logger.error("Failed to load certificate from {}", certificatePath, e);
117 throw new RuntimeException(e);
118 }
119 }
120 return certificate;
121 }
122 }
123
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/component/CryptoProvider.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/archive/decorator/signing/AbstractSigningDecorator.java]
1 /*
2 * Corona-Warn-App
3 *
4 * SAP SE and all other contributors /
5 * copyright owners license this file to you under the Apache
6 * License, Version 2.0 (the "License"); you may not use this
7 * file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20 package app.coronawarn.server.services.distribution.assembly.structure.archive.decorator.signing;
21
22 import app.coronawarn.server.common.protocols.external.exposurenotification.SignatureInfo;
23 import app.coronawarn.server.common.protocols.external.exposurenotification.TEKSignature;
24 import app.coronawarn.server.common.protocols.external.exposurenotification.TEKSignatureList;
25 import app.coronawarn.server.services.distribution.assembly.component.CryptoProvider;
26 import app.coronawarn.server.services.distribution.assembly.structure.Writable;
27 import app.coronawarn.server.services.distribution.assembly.structure.archive.Archive;
28 import app.coronawarn.server.services.distribution.assembly.structure.archive.decorator.ArchiveDecorator;
29 import app.coronawarn.server.services.distribution.assembly.structure.util.ImmutableStack;
30 import com.google.protobuf.ByteString;
31 import java.security.GeneralSecurityException;
32 import java.security.Signature;
33 import org.slf4j.Logger;
34 import org.slf4j.LoggerFactory;
35
36 public abstract class AbstractSigningDecorator<W extends Writable<W>> extends ArchiveDecorator<W> implements
37 SigningDecorator<W> {
38
39 private static final String SIGNATURE_FILE_NAME = "export.sig";
40 private static final String SIGNATURE_ALGORITHM = "Ed25519";
41 private static final String SECURITY_PROVIDER = "BC";
42
43 private static final Logger logger = LoggerFactory.getLogger(AbstractSigningDecorator.class);
44 protected final CryptoProvider cryptoProvider;
45
46 public AbstractSigningDecorator(Archive<W> archive, CryptoProvider cryptoProvider) {
47 super(archive);
48 this.cryptoProvider = cryptoProvider;
49 }
50
51 @Override
52 public void prepare(ImmutableStack<Object> indices) {
53 super.prepare(indices);
54 this.addWritable(this.getSignatureFile(SIGNATURE_FILE_NAME));
55 }
56
57 protected TEKSignatureList createTemporaryExposureKeySignatureList(CryptoProvider cryptoProvider) {
58 return TEKSignatureList.newBuilder()
59 .addSignatures(TEKSignature.newBuilder()
60 .setSignatureInfo(getSignatureInfo())
61 .setBatchNum(getBatchNum())
62 .setBatchSize(getBatchSize())
63 .setSignature(ByteString.copyFrom(createSignature(cryptoProvider)))
64 .build())
65 .build();
66 }
67
68 private byte[] createSignature(CryptoProvider cryptoProvider) {
69 try {
70 Signature payloadSignature = Signature.getInstance(SIGNATURE_ALGORITHM, SECURITY_PROVIDER);
71 payloadSignature.initSign(cryptoProvider.getPrivateKey());
72 payloadSignature.update(this.getBytesToSign());
73 return payloadSignature.sign();
74 } catch (GeneralSecurityException e) {
75 logger.error("Failed to sign archive.", e);
76 throw new RuntimeException(e);
77 }
78 }
79
80 /**
81 * Returns the static {@link SignatureInfo} configured in the application properties. TODO Enter correct values.
82 */
83 public static SignatureInfo getSignatureInfo() {
84 // TODO cwa-server#183 cwa-server#207 cwa-server#238
85 return SignatureInfo.newBuilder()
86 .setAppBundleId("de.rki.coronawarnapp")
87 .setAndroidPackage("de.rki.coronawarnapp")
88 .setVerificationKeyVersion("")
89 .setVerificationKeyId("")
90 .setSignatureAlgorithm("1.2.840.10045.4.3.2")
91 .build();
92 }
93 }
94
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/archive/decorator/signing/AbstractSigningDecorator.java]
</code>
Here is an example of a patch file. It consists of changes to the code base. It specifies the file names, the line numbers of each change, and the removed and added lines. A single patch file can contain changes to multiple files.
<patch>
--- a/file.py
+++ b/file.py
@@ -1,27 +1,35 @@
def euclidean(a, b):
- while b:
- a, b = b, a % b
- return a
+ if b == 0:
+ return a
+ return euclidean(b, a % b)
def bresenham(x0, y0, x1, y1):
points = []
dx = abs(x1 - x0)
dy = abs(y1 - y0)
- sx = 1 if x0 < x1 else -1
- sy = 1 if y0 < y1 else -1
- err = dx - dy
+ x, y = x0, y0
+ sx = -1 if x0 > x1 else 1
+ sy = -1 if y0 > y1 else 1
- while True:
- points.append((x0, y0))
- if x0 == x1 and y0 == y1:
- break
- e2 = 2 * err
- if e2 > -dy:
+ if dx > dy:
+ err = dx / 2.0
+ while x != x1:
+ points.append((x, y))
err -= dy
- x0 += sx
- if e2 < dx:
- err += dx
- y0 += sy
+ if err < 0:
+ y += sy
+ err += dx
+ x += sx
+ else:
+ err = dy / 2.0
+ while y != y1:
+ points.append((x, y))
+ err -= dx
+ if err < 0:
+ x += sx
+ err += dy
+ y += sy
+ points.append((x, y))
return points
</patch>
I need you to solve the provded issue by generating a single patch file that I can apply directly to this repository using git apply. Please respond with a single patch file in the format shown above.
Respond below:
| corona-warn-app/cwa-server | 73b566ec755cc61fc4c08da274c133535adb6ae7 | Update signature algorithm to SHA-256 + ECDSA P-256
## Feature description
The current CWA server implementation signs diagnosis key packages with the ``Ed25519`` algorithm. However, the current [Google/Apple spec](https://developer.apple.com/documentation/exposurenotification/setting_up_an_exposure_notification_server) demands ``SHA-256`` hash with ``ECDSA P-256`` signature ([OID 1.2.840.10045.4.3.2](http://oid-info.com/get/1.2.840.10045.4.3.2))
| 2020-05-23T13:07:15 | <patch>
diff --git a/docker-compose-test-secrets/certificate.crt b/docker-compose-test-secrets/certificate.crt
--- a/docker-compose-test-secrets/certificate.crt
+++ b/docker-compose-test-secrets/certificate.crt
@@ -1,16 +1,18 @@
-----BEGIN CERTIFICATE-----
-MIHxMIGkAgFkMAUGAytlcDAkMSIwIAYDVQQDDBlFTkEgVGVzdCBSb290IENlcnRp
-ZmljYXRlMB4XDTIwMDQzMDE0MDQ1NVoXDTIxMDQzMDE0MDQ1NVowJjEkMCIGA1UE
-AwwbRU5BIFRlc3QgQ2xpZW50IENlcnRpZmljYXRlMCowBQYDK2VwAyEAKb/6ocYD
-5sIoiGUjHSCiHP3oAZxwtBicRxQVhqZhZIUwBQYDK2VwA0EAw6EUybzXxad6U39C
-d1AwMBQ8b2k0pgd2VeJHn46hr5uByJ/MB+fHkgj0SkFhVbfhffcjq23FQKu7lZ/Z
-HxakDA==
+MIIBMjCB2AIBZDAKBggqhkjOPQQDAjAkMSIwIAYDVQQDDBlDV0EgVGVzdCBSb290
+IENlcnRpZmljYXRlMB4XDTIwMDUyMzExMzAzOFoXDTIxMDUyMzExMzAzOFowJjEk
+MCIGA1UEAwwbQ1dBIFRlc3QgQ2xpZW50IENlcnRpZmljYXRlMFkwEwYHKoZIzj0C
+AQYIKoZIzj0DAQcDQgAEYQJ+sReY1L8z851VFRpLu4PCusj/7Ruvi879KjrQJ12k
+KKsfeRWytmrE65Jok1lsYqpFhRWcxG6VV5FX0yG+EjAKBggqhkjOPQQDAgNJADBG
+AiEAwP/VKVIhOuiIczrPFg0o4ns39Wu1vBpIXu+/psI/3LECIQD0FAXo5chuUkQy
+LeUtwsQaC8v2KA96ew3PfCoTilvU1Q==
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
-MIIBAjCBtQIULaMo9wOjHWZrpxuH+sN3ZPeT9EUwBQYDK2VwMCQxIjAgBgNVBAMM
-GUVOQSBUZXN0IFJvb3QgQ2VydGlmaWNhdGUwHhcNMjAwNDMwMTQwNDU1WhcNMjEw
-NDMwMTQwNDU1WjAkMSIwIAYDVQQDDBlFTkEgVGVzdCBSb290IENlcnRpZmljYXRl
-MCowBQYDK2VwAyEADapVfRHr20spX2u6Wx8ImeoUZiJJU5cyG3zhqOl1pJAwBQYD
-K2VwA0EA9MRmDLKz60SiPAWtD6HDEZB7wCEC/vUm6rMZ9+VcEXQlBlGbiIabkX8C
-9pJ00fNzlbftmI8SiO/kjWSnwyCRBA==
+MIIBQzCB6QIUN7Z6IofaE0qtz2X1xz/IUDCUXd0wCgYIKoZIzj0EAwIwJDEiMCAG
+A1UEAwwZQ1dBIFRlc3QgUm9vdCBDZXJ0aWZpY2F0ZTAeFw0yMDA1MjMxMTMwMzha
+Fw0yMTA1MjMxMTMwMzhaMCQxIjAgBgNVBAMMGUNXQSBUZXN0IFJvb3QgQ2VydGlm
+aWNhdGUwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAATBH0/vPsD62wE9jk5JZZd+
+Yf4WXZ3sKZUGbdqJssc4lxjyZJvpPLCirRQT6XWwhmBhoL8mRL5tpZ/93o+jzULe
+MAoGCCqGSM49BAMCA0kAMEYCIQCNPEtoC1QtgnncZzV/rgIoO6tktCiAkybBhHMB
+1SISZQIhAPguoBWCscYwNHtEgTDx2sQ8UZ79KvWvpHFlwDEyiHAv
-----END CERTIFICATE-----
diff --git a/docker-compose-test-secrets/private.pem b/docker-compose-test-secrets/private.pem
--- a/docker-compose-test-secrets/private.pem
+++ b/docker-compose-test-secrets/private.pem
@@ -1,3 +1,5 @@
------BEGIN PRIVATE KEY-----
-MC4CAQAwBQYDK2VwBCIEICW8533MLMm66KvHObhk7Q/gUYAJ4h/+GoO/oe5e/CbU
------END PRIVATE KEY-----
+-----BEGIN EC PRIVATE KEY-----
+MHcCAQEEILQRQFlGcfeTAclubtjQ1rBjtmIOB/d7PITZyDe1r81/oAoGCCqGSM49
+AwEHoUQDQgAEYQJ+sReY1L8z851VFRpLu4PCusj/7Ruvi879KjrQJ12kKKsfeRWy
+tmrE65Jok1lsYqpFhRWcxG6VV5FX0yG+Eg==
+-----END EC PRIVATE KEY-----
diff --git a/scripts/generate_certificates.sh b/scripts/generate_certificates.sh
--- a/scripts/generate_certificates.sh
+++ b/scripts/generate_certificates.sh
@@ -14,8 +14,10 @@ pushd certificates > /dev/null || exit
# $1 = OUT Private key file
generate_private_key()
{
- openssl genpkey \
- -algorithm ED25519 \
+ openssl ecparam \
+ -name prime256v1 \
+ -genkey \
+ -noout \
-out "$1"
}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/component/CryptoProvider.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/component/CryptoProvider.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/component/CryptoProvider.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/component/CryptoProvider.java
@@ -23,13 +23,14 @@
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
+import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.Security;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
-import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
+import org.bouncycastle.openssl.PEMKeyPair;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
import org.slf4j.Logger;
@@ -69,11 +70,11 @@ public CryptoProvider(ResourceLoader resourceLoader) {
Security.addProvider(new BouncyCastleProvider());
}
- private static PrivateKey getPrivateKeyFromStream(final InputStream privateKeyStream)
- throws IOException {
- PEMParser pemParser = new PEMParser(new InputStreamReader(privateKeyStream));
- PrivateKeyInfo privateKeyInfo = (PrivateKeyInfo) pemParser.readObject();
- return new JcaPEMKeyConverter().getPrivateKey(privateKeyInfo);
+ private static PrivateKey getPrivateKeyFromStream(final InputStream privateKeyStream) throws IOException {
+ InputStreamReader privateKeyStreamReader = new InputStreamReader(privateKeyStream);
+ Object parsed = new PEMParser(privateKeyStreamReader).readObject();
+ KeyPair pair = new JcaPEMKeyConverter().getKeyPair((PEMKeyPair) parsed);
+ return pair.getPrivate();
}
private static Certificate getCertificateFromStream(final InputStream certificateStream)
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/archive/decorator/signing/AbstractSigningDecorator.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/archive/decorator/signing/AbstractSigningDecorator.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/archive/decorator/signing/AbstractSigningDecorator.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/archive/decorator/signing/AbstractSigningDecorator.java
@@ -37,7 +37,7 @@ public abstract class AbstractSigningDecorator<W extends Writable<W>> extends Ar
SigningDecorator<W> {
private static final String SIGNATURE_FILE_NAME = "export.sig";
- private static final String SIGNATURE_ALGORITHM = "Ed25519";
+ private static final String SIGNATURE_ALGORITHM = "SHA256withECDSA";
private static final String SECURITY_PROVIDER = "BC";
private static final Logger logger = LoggerFactory.getLogger(AbstractSigningDecorator.class);
</patch> | diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/RiskScoreClassificationProviderMasterFileTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/RiskScoreClassificationProviderMasterFileTest.java
--- a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/RiskScoreClassificationProviderMasterFileTest.java
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/RiskScoreClassificationProviderMasterFileTest.java
@@ -21,15 +21,13 @@
import static org.assertj.core.api.Assertions.assertThat;
-import app.coronawarn.server.services.distribution.assembly.appconfig.validation.ExposureConfigurationValidator;
import app.coronawarn.server.services.distribution.assembly.appconfig.validation.RiskScoreClassificationValidator;
import app.coronawarn.server.services.distribution.assembly.appconfig.validation.ValidationResult;
import org.junit.jupiter.api.Test;
/**
* This test will verify that the provided risk score classification master file is syntactically correct and according
- * to spec.
- * There should never be any deployment when this test is failing.
+ * to spec. There should never be any deployment when this test is failing.
*/
public class RiskScoreClassificationProviderMasterFileTest {
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/structure/archive/decorator/signing/SigningDecoratorTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/structure/archive/decorator/signing/SigningDecoratorTest.java
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/structure/archive/decorator/signing/SigningDecoratorTest.java
@@ -0,0 +1,135 @@
+package app.coronawarn.server.services.distribution.assembly.structure.archive.decorator.signing;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import app.coronawarn.server.common.protocols.external.exposurenotification.SignatureInfo;
+import app.coronawarn.server.common.protocols.external.exposurenotification.TEKSignature;
+import app.coronawarn.server.common.protocols.external.exposurenotification.TEKSignatureList;
+import app.coronawarn.server.services.distribution.assembly.component.CryptoProvider;
+import app.coronawarn.server.services.distribution.assembly.structure.WritableOnDisk;
+import app.coronawarn.server.services.distribution.assembly.structure.archive.Archive;
+import app.coronawarn.server.services.distribution.assembly.structure.archive.ArchiveOnDisk;
+import app.coronawarn.server.services.distribution.assembly.structure.directory.Directory;
+import app.coronawarn.server.services.distribution.assembly.structure.directory.DirectoryOnDisk;
+import app.coronawarn.server.services.distribution.assembly.structure.file.File;
+import app.coronawarn.server.services.distribution.assembly.structure.file.FileOnDisk;
+import app.coronawarn.server.services.distribution.assembly.structure.util.ImmutableStack;
+import java.io.IOException;
+import java.security.InvalidKeyException;
+import java.security.NoSuchAlgorithmException;
+import java.security.NoSuchProviderException;
+import java.security.Signature;
+import java.security.SignatureException;
+import java.util.List;
+import org.junit.Rule;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.rules.TemporaryFolder;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.ConfigFileApplicationContextInitializer;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit.jupiter.SpringExtension;
+
+@ExtendWith(SpringExtension.class)
+@ContextConfiguration(classes = {CryptoProvider.class},
+ initializers = ConfigFileApplicationContextInitializer.class)
+class SigningDecoratorTest {
+
+ @Autowired
+ CryptoProvider cryptoProvider;
+
+ private File<WritableOnDisk> fileToSign;
+ private TEKSignatureList signatureList;
+
+ @Rule
+ private TemporaryFolder outputFolder = new TemporaryFolder();
+
+ @BeforeEach
+ void setup() throws IOException {
+ Archive<WritableOnDisk> archive = new ArchiveOnDisk("export.zip");
+ fileToSign = new FileOnDisk("export.bin", "123456".getBytes());
+ archive.addWritable(fileToSign);
+
+ SigningDecorator<WritableOnDisk> signingDecorator = new TestSigningDecorator(archive, cryptoProvider);
+
+ outputFolder.create();
+ java.io.File outputDir = outputFolder.newFolder();
+ Directory<WritableOnDisk> directory = new DirectoryOnDisk(outputDir);
+ directory.addWritable(signingDecorator);
+ directory.prepare(new ImmutableStack<>());
+
+ File<WritableOnDisk> signatureFile = archive.getWritables().stream()
+ .filter(writable -> writable.getName().equals("export.sig"))
+ .map(writable -> (File<WritableOnDisk>) writable)
+ .findFirst()
+ .orElseThrow();
+
+ signatureList = TEKSignatureList.parseFrom(signatureFile.getBytes());
+ }
+
+ @Test
+ void checkSignatureFileStructure() {
+
+ assertThat(signatureList).isNotNull();
+
+ List<TEKSignature> signatures = signatureList.getSignaturesList();
+ assertThat(signatures).hasSize(1);
+
+ TEKSignature signature = signatures.get(0);
+ assertThat(signature.getSignatureInfo()).isNotNull();
+ assertThat(signature.getBatchNum()).isEqualTo(1);
+ assertThat(signature.getBatchSize()).isEqualTo(1);
+ assertThat(signature.getSignature()).isNotEmpty();
+ }
+
+ @Test
+ void checkSignatureInfo() {
+ SignatureInfo signatureInfo = signatureList.getSignaturesList().get(0).getSignatureInfo();
+
+ assertThat(signatureInfo.getAppBundleId()).isEqualTo("de.rki.coronawarnapp");
+ assertThat(signatureInfo.getAndroidPackage()).isEqualTo("de.rki.coronawarnapp");
+ assertThat(signatureInfo.getSignatureAlgorithm()).isEqualTo("1.2.840.10045.4.3.2");
+ assertThat(signatureInfo.getVerificationKeyId()).isEmpty();
+ assertThat(signatureInfo.getVerificationKeyVersion()).isEmpty();
+ }
+
+ @Test
+ void checkSignature()
+ throws NoSuchProviderException, NoSuchAlgorithmException, InvalidKeyException, SignatureException {
+ byte[] fileBytes = fileToSign.getBytes();
+ byte[] signatureBytes = signatureList.getSignaturesList().get(0).getSignature().toByteArray();
+
+ Signature payloadSignature = Signature.getInstance("SHA256withECDSA", "BC");
+ payloadSignature.initVerify(cryptoProvider.getCertificate());
+ payloadSignature.update(fileBytes);
+ assertThat(payloadSignature.verify(signatureBytes)).isTrue();
+ }
+
+ private static class TestSigningDecorator extends SigningDecoratorOnDisk {
+
+ public TestSigningDecorator(Archive<WritableOnDisk> archive, CryptoProvider cryptoProvider) {
+ super(archive, cryptoProvider);
+ }
+
+ @Override
+ public byte[] getBytesToSign() {
+ return this.getWritables().stream()
+ .filter(writable -> writable.getName().equals("export.bin"))
+ .map(writable -> (File<WritableOnDisk>) writable)
+ .map(File::getBytes)
+ .findFirst()
+ .orElseThrow();
+ }
+
+ @Override
+ public int getBatchNum() {
+ return 1;
+ }
+
+ @Override
+ public int getBatchSize() {
+ return 1;
+ }
+ }
+}
diff --git a/services/distribution/src/test/resources/certificates/chain/certificate.crt b/services/distribution/src/test/resources/certificates/chain/certificate.crt
--- a/services/distribution/src/test/resources/certificates/chain/certificate.crt
+++ b/services/distribution/src/test/resources/certificates/chain/certificate.crt
@@ -1,16 +1,18 @@
-----BEGIN CERTIFICATE-----
-MIHxMIGkAgFkMAUGAytlcDAkMSIwIAYDVQQDDBlFTkEgVGVzdCBSb290IENlcnRp
-ZmljYXRlMB4XDTIwMDQzMDE0MDQ1NVoXDTIxMDQzMDE0MDQ1NVowJjEkMCIGA1UE
-AwwbRU5BIFRlc3QgQ2xpZW50IENlcnRpZmljYXRlMCowBQYDK2VwAyEAKb/6ocYD
-5sIoiGUjHSCiHP3oAZxwtBicRxQVhqZhZIUwBQYDK2VwA0EAw6EUybzXxad6U39C
-d1AwMBQ8b2k0pgd2VeJHn46hr5uByJ/MB+fHkgj0SkFhVbfhffcjq23FQKu7lZ/Z
-HxakDA==
+MIIBMjCB2AIBZDAKBggqhkjOPQQDAjAkMSIwIAYDVQQDDBlDV0EgVGVzdCBSb290
+IENlcnRpZmljYXRlMB4XDTIwMDUyMzExMzAzOFoXDTIxMDUyMzExMzAzOFowJjEk
+MCIGA1UEAwwbQ1dBIFRlc3QgQ2xpZW50IENlcnRpZmljYXRlMFkwEwYHKoZIzj0C
+AQYIKoZIzj0DAQcDQgAEYQJ+sReY1L8z851VFRpLu4PCusj/7Ruvi879KjrQJ12k
+KKsfeRWytmrE65Jok1lsYqpFhRWcxG6VV5FX0yG+EjAKBggqhkjOPQQDAgNJADBG
+AiEAwP/VKVIhOuiIczrPFg0o4ns39Wu1vBpIXu+/psI/3LECIQD0FAXo5chuUkQy
+LeUtwsQaC8v2KA96ew3PfCoTilvU1Q==
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
-MIIBAjCBtQIULaMo9wOjHWZrpxuH+sN3ZPeT9EUwBQYDK2VwMCQxIjAgBgNVBAMM
-GUVOQSBUZXN0IFJvb3QgQ2VydGlmaWNhdGUwHhcNMjAwNDMwMTQwNDU1WhcNMjEw
-NDMwMTQwNDU1WjAkMSIwIAYDVQQDDBlFTkEgVGVzdCBSb290IENlcnRpZmljYXRl
-MCowBQYDK2VwAyEADapVfRHr20spX2u6Wx8ImeoUZiJJU5cyG3zhqOl1pJAwBQYD
-K2VwA0EA9MRmDLKz60SiPAWtD6HDEZB7wCEC/vUm6rMZ9+VcEXQlBlGbiIabkX8C
-9pJ00fNzlbftmI8SiO/kjWSnwyCRBA==
+MIIBQzCB6QIUN7Z6IofaE0qtz2X1xz/IUDCUXd0wCgYIKoZIzj0EAwIwJDEiMCAG
+A1UEAwwZQ1dBIFRlc3QgUm9vdCBDZXJ0aWZpY2F0ZTAeFw0yMDA1MjMxMTMwMzha
+Fw0yMTA1MjMxMTMwMzhaMCQxIjAgBgNVBAMMGUNXQSBUZXN0IFJvb3QgQ2VydGlm
+aWNhdGUwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAATBH0/vPsD62wE9jk5JZZd+
+Yf4WXZ3sKZUGbdqJssc4lxjyZJvpPLCirRQT6XWwhmBhoL8mRL5tpZ/93o+jzULe
+MAoGCCqGSM49BAMCA0kAMEYCIQCNPEtoC1QtgnncZzV/rgIoO6tktCiAkybBhHMB
+1SISZQIhAPguoBWCscYwNHtEgTDx2sQ8UZ79KvWvpHFlwDEyiHAv
-----END CERTIFICATE-----
diff --git a/services/distribution/src/test/resources/certificates/client/private.pem b/services/distribution/src/test/resources/certificates/client/private.pem
--- a/services/distribution/src/test/resources/certificates/client/private.pem
+++ b/services/distribution/src/test/resources/certificates/client/private.pem
@@ -1,3 +1,5 @@
------BEGIN PRIVATE KEY-----
-MC4CAQAwBQYDK2VwBCIEICW8533MLMm66KvHObhk7Q/gUYAJ4h/+GoO/oe5e/CbU
------END PRIVATE KEY-----
+-----BEGIN EC PRIVATE KEY-----
+MHcCAQEEILQRQFlGcfeTAclubtjQ1rBjtmIOB/d7PITZyDe1r81/oAoGCCqGSM49
+AwEHoUQDQgAEYQJ+sReY1L8z851VFRpLu4PCusj/7Ruvi879KjrQJ12kKKsfeRWy
+tmrE65Jok1lsYqpFhRWcxG6VV5FX0yG+Eg==
+-----END EC PRIVATE KEY-----
| |||||
corona-warn-app__cwa-server-551 | You will be provided with a partial code base and an issue statement explaining a problem to resolve.
<issue>
BatchCounter uses Double for counting
## Describe the bug
BatchCounter uses `double` for integer arithmetics, which is commonly discouraged.
## Expected behaviour
BatchCounter uses `int` for counting up to `batchSize`, since `batchSize` is also of type `int`.
It's faster.
In theory it's more accurate. (In practice there is no difference in this case since the maximum value that is representable in a double is larger than `Integer.MAX_VALUE`. But for `long` instead of `int`, there would be a difference.)
## Possible Fix
~~~java
private int batch;
~~~
While here, `batch` should be renamed to `batchCount` to better express its actual meaning.
BatchCounter is not thread-safe
## Describe the bug
When multiple threads call `BatchCounter.increment` at the same time, the resulting count is unspecified.
## Expected behaviour
`synchronized void increment`
## Steps to reproduce the issue
Call `BatchCounter` from several threads at the same time.
## Possible Fix
Add `synchronized`.
</issue>
<code>
[start of README.md]
1 <!-- markdownlint-disable MD041 -->
2 <h1 align="center">
3 Corona-Warn-App Server
4 </h1>
5
6 <p align="center">
7 <a href="https://github.com/corona-warn-app/cwa-server/commits/" title="Last Commit"><img src="https://img.shields.io/github/last-commit/corona-warn-app/cwa-server?style=flat"></a>
8 <a href="https://github.com/corona-warn-app/cwa-server/issues" title="Open Issues"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat"></a>
9 <a href="https://circleci.com/gh/corona-warn-app/cwa-server" title="Build Status"><img src="https://circleci.com/gh/corona-warn-app/cwa-server.svg?style=shield&circle-token=4ab059989d10709df19eb4b98ab7c121a25e981a"></a>
10 <a href="https://sonarcloud.io/dashboard?id=corona-warn-app_cwa-server" title="Quality Gate"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=alert_status"></a>
11 <a href="https://sonarcloud.io/component_measures?id=corona-warn-app_cwa-server&metric=Coverage&view=list" title="Coverage"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=coverage"></a>
12 <a href="https://github.com/corona-warn-app/cwa-server/blob/master/LICENSE" title="License"><img src="https://img.shields.io/badge/License-Apache%202.0-green.svg?style=flat"></a>
13 </p>
14
15 <p align="center">
16 <a href="#development">Development</a> •
17 <a href="#service-apis">Service APIs</a> •
18 <a href="#documentation">Documentation</a> •
19 <a href="#support-and-feedback">Support</a> •
20 <a href="#how-to-contribute">Contribute</a> •
21 <a href="#contributors">Contributors</a> •
22 <a href="#repositories">Repositories</a> •
23 <a href="#licensing">Licensing</a>
24 </p>
25
26 The goal of this project is to develop the official Corona-Warn-App for Germany based on the exposure notification API from [Apple](https://www.apple.com/covid19/contacttracing/) and [Google](https://www.google.com/covid19/exposurenotifications/). The apps (for both iOS and Android) use Bluetooth technology to exchange anonymous encrypted data with other mobile phones (on which the app is also installed) in the vicinity of an app user's phone. The data is stored locally on each user's device, preventing authorities or other parties from accessing or controlling the data. This repository contains the **implementation of the server for encryption keys** for the Corona-Warn-App.
27
28 In this documentation, Corona-Warn-App services are also referred to as CWA services.
29
30 ## Architecture Overview
31
32 You can find the architecture overview [here](/docs/ARCHITECTURE.md), which will give you
33 a good starting point in how the backend services interact with other services, and what purpose
34 they serve.
35
36 ## Development
37
38 After you've checked out this repository, you can run the application in one of the following ways:
39
40 * As a [Docker](https://www.docker.com/)-based deployment on your local machine. You can run either:
41 * Single components using the respective Dockerfile or
42 * The full backend using the Docker Compose (which is considered the most convenient way)
43 * As a [Maven](https://maven.apache.org)-based build on your local machine.
44 If you want to develop something in a single component, this approach is preferable.
45
46 ### Docker-Based Deployment
47
48 If you want to use Docker-based deployment, you need to install Docker on your local machine. For more information about downloading and installing Docker, see the [official Docker documentation](https://docs.docker.com/get-docker/).
49
50 #### Running the Full CWA Backend Using Docker Compose
51
52 For your convenience, a full setup including the generation of test data has been prepared using [Docker Compose](https://docs.docker.com/compose/reference/overview/). To build the backend services, run ```docker-compose build``` in the repository's root directory. A default configuration file can be found under ```.env``` in the root folder of the repository. The default values for the local Postgres and Zenko Cloudserver should be changed in this file before docker-compose is run.
53
54 Once the services are built, you can start the whole backend using ```docker-compose up```.
55 The distribution service runs once and then finishes. If you want to trigger additional distribution runs, run ```docker-compose run distribution```.
56
57 The docker-compose contains the following services:
58
59 Service | Description | Endpoint and Default Credentials
60 ------------------|-------------|-----------
61 submission | The Corona-Warn-App submission service | `http://localhost:8000` <br> `http://localhost:8006` (for actuator endpoint)
62 distribution | The Corona-Warn-App distribution service | NO ENDPOINT
63 postgres | A [postgres] database installation | `localhost:8001` <br> `postgres:5432` (from containerized pgadmin) <br> Username: postgres <br> Password: postgres
64 pgadmin | A [pgadmin](https://www.pgadmin.org/) installation for the postgres database | `http://localhost:8002` <br> Username: [email protected] <br> Password: password
65 cloudserver | [Zenko CloudServer] is a S3-compliant object store | `http://localhost:8003/` <br> Access key: accessKey1 <br> Secret key: verySecretKey1
66 verification-fake | A very simple fake implementation for the tan verification. | `http://localhost:8004/version/v1/tan/verify` <br> The only valid tan is `edc07f08-a1aa-11ea-bb37-0242ac130002`.
67
68 ##### Known Limitation
69
70 In rare cases the docker-compose runs into a timing issue if the distribution service starts before the bucket of the objectstore was created. This is not a big issue as you can simply run ```docker-compose run distribution``` to trigger additional distribution runs after the objectstore was initialized.
71
72 #### Running Single CWA Services Using Docker
73
74 If you would like to build and run a single CWA service, it's considered easiest to run them in a Docker environment. You can do this using the script provided in the respective CWA service directory. The Docker script first builds the CWA service and then creates an image for the runtime, which means that there are no additional dependencies for you to install.
75
76 To build and run the distribution service, run the following command:
77
78 ```bash
79 ./services/distribution/build_and_run.sh
80 ```
81
82 To build and run the submission service, run the following command:
83
84 ```bash
85 ./services/submission/build_and_run.sh
86 ```
87
88 The submission service is available on [localhost:8080](http://localhost:8080 ).
89
90 ### Maven-Based Build
91
92 If you want to actively develop in one of the CWA services, the Maven-based runtime is most suitable.
93 To prepare your machine to run the CWA project locally, we recommend that you first ensure that you've installed the following:
94
95 * Minimum JDK Version 11: [OpenJDK](https://openjdk.java.net/) / [SapMachine](https://sap.github.io/SapMachine/)
96 * [Maven 3.6](https://maven.apache.org/)
97 * [Postgres]
98 * [Zenko CloudServer]
99
100 You can also use `docker-compose` to start Postgres and Zenko. If you do that, you have to
101 set the following environment-variables when running the Spring project:
102
103 For the distribution module:
104
105 ```bash
106 POSTGRESQL_SERVICE_PORT=8001
107 VAULT_FILESIGNING_SECRET=</path/to/your/private_key>
108 ```
109
110 For the submission module:
111
112 ```bash
113 POSTGRESQL_SERVICE_PORT=8001
114 ```
115
116 #### Configure
117
118 After you made sure that the specified dependencies are running, configure them in the respective configuration files.
119
120 * Configure the Postgres connection in the [submission config](./services/submission/src/main/resources/application.yaml) and in the [distribution config](./services/distribution/src/main/resources/application.yaml)
121 * Configure the S3 compatible object storage in the [distribution config](./services/distribution/src/main/resources/application.yaml)
122 * Configure the private key for the distribution service, the path need to be prefixed with `file:`
123 * `VAULT_FILESIGNING_SECRET` should be the path to the private key, example available in `<repo-root>/docker-compose-test-secrets/private.pem`
124
125 #### Build
126
127 After you've checked out the repository, to build the project, run ```mvn install``` in your base directory.
128
129 #### Run
130
131 Navigate to the service you want to start and run the spring-boot:run target. The configured Postgres and the configured S3 compliant object storage are used as default. When you start the submission service, the endpoint is available on your local port 8080.
132
133 If you want to start the submission service, for example, you start it as follows:
134
135 ```bash
136 cd services/submission/
137 mvn spring-boot:run
138 ```
139
140 #### Debugging
141
142 To enable the `DEBUG` log level, you can run the application using the Spring `dev` profile.
143
144 ```bash
145 mvn spring-boot:run -Dspring.profiles.active=dev
146 ```
147
148 To be able to set breakpoints (e.g. in IntelliJ), it may be necessary to use the ```-Dspring-boot.run.fork=false``` parameter.
149
150 ## Service APIs
151
152 The API that is being exposed by the backend services is documented in an [OpenAPI](https://www.openapis.org/) specification. The specification files are available at the following locations:
153
154 Service | OpenAPI Specification
155 -------------|-------------
156 Submission Service | [services/submission/api_v1.json](https://github.com/corona-warn-app/cwa-server/raw/master/services/submission/api_v1.json)
157 Distribution Service | [services/distribution/api_v1.json](https://github.com/corona-warn-app/cwa-server/raw/master/services/distribution/api_v1.json)
158
159 ## Spring Profiles
160
161 ### Distribution
162
163 Profile | Effect
164 ----------------------|-------------
165 `dev` | Turns the log level to `DEBUG`.
166 `cloud` | Removes default values for the `datasource` and `objectstore` configurations.
167 `demo` | Includes incomplete days and hours into the distribution run, thus creating aggregates for the current day and the current hour (and including both in the respective indices). When running multiple distributions in one hour with this profile, the date aggregate for today and the hours aggregate for the current hour will be updated and overwritten. This profile also turns off the expiry policy (Keys must be expired for at least 2 hours before distribution) and the shifting policy (there must be at least 140 keys in a distribution).
168 `testdata` | Causes test data to be inserted into the database before each distribution run. By default, around 1000 random diagnosis keys will be generated per hour. If there are no diagnosis keys in the database yet, random keys will be generated for every hour from the beginning of the retention period (14 days ago at 00:00 UTC) until one hour before the present hour. If there are already keys in the database, the random keys will be generated for every hour from the latest diagnosis key in the database (by submission timestamp) until one hour before the present hour (or none at all, if the latest diagnosis key in the database was submitted one hour ago or later).
169 `signature-dev` | Sets the app package ID in the export packages' signature info to `de.rki.coronawarnapp-dev` so that the non-productive/test public key will be used for client-side validation.
170 `signature-prod` | Sets the app package ID in the export packages' signature info to `de.rki.coronawarnapp` so that the productive public key will be used for client-side validation.
171 `ssl-client-postgres` | Enforces SSL with a pinned certificate for the connection to the postgres (see [here](https://github.com/corona-warn-app/cwa-server/blob/master/services/distribution/src/main/resources/application-ssl-client-postgres.yaml)).
172
173 ### Submission
174
175 Profile | Effect
176 --------------------------|-------------
177 `dev` | Turns the log level to `DEBUG`.
178 `cloud` | Removes default values for the `datasource` configuration.
179 `ssl-server` | Enables SSL for the submission endpoint (see [here](https://github.com/corona-warn-app/cwa-server/blob/master/services/submission/src/main/resources/application-ssl-server.yaml)).
180 `ssl-client-postgres` | Enforces SSL with a pinned certificate for the connection to the postgres (see [here](https://github.com/corona-warn-app/cwa-server/blob/master/services/submission/src/main/resources/application-ssl-client-postgres.yaml)).
181 `ssl-client-verification` | Enforces SSL with a pinned certificate for the connection to the verification server (see [here](https://github.com/corona-warn-app/cwa-server/blob/master/services/submission/src/main/resources/application-ssl-client-verification.yaml)).
182
183 ## Documentation
184
185 The full documentation for the Corona-Warn-App can be found in the [cwa-documentation](https://github.com/corona-warn-app/cwa-documentation) repository. The documentation repository contains technical documents, architecture information, and whitepapers related to this implementation.
186
187 ## Support and Feedback
188
189 The following channels are available for discussions, feedback, and support requests:
190
191 | Type | Channel |
192 | ------------------------ | ------------------------------------------------------ |
193 | **General Discussion** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="General Discussion"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/question.svg?style=flat-square"></a> </a> |
194 | **Concept Feedback** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="Open Concept Feedback"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/architecture.svg?style=flat-square"></a> |
195 | **Backend Issue** | <a href="https://github.com/corona-warn-app/cwa-server/issues/new/choose" title="Open Backend Issue"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat-square"></a> |
196 | **Other Requests** | <a href="mailto:[email protected]" title="Email CWA Team"><img src="https://img.shields.io/badge/email-CWA%20team-green?logo=mail.ru&style=flat-square&logoColor=white"></a> |
197
198 ## How to Contribute
199
200 Contribution and feedback are 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.
201
202 ## Contributors
203
204 The German government has asked SAP and Deutsche Telekom to develop the Corona-Warn-App for Germany as open source software. Deutsche Telekom is providing the network and mobile technology and will operate and run the backend for the app in a safe, scalable and stable manner. SAP is responsible for the app development, its framework and the underlying platform. Therefore, development teams of SAP and Deutsche Telekom are contributing to this project. At the same time 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.
205
206 ## Repositories
207
208 The following public repositories are currently available for the Corona-Warn-App:
209
210 | Repository | Description |
211 | ------------------- | --------------------------------------------------------------------- |
212 | [cwa-documentation] | Project overview, general documentation, and white papers |
213 | [cwa-server] | Backend implementation for the Apple/Google exposure notification API|
214 | [cwa-verification-server] | Backend implementation of the verification process|
215
216 [cwa-documentation]: https://github.com/corona-warn-app/cwa-documentation
217 [cwa-server]: https://github.com/corona-warn-app/cwa-server
218 [cwa-verification-server]: https://github.com/corona-warn-app/cwa-verification-server
219 [Postgres]: https://www.postgresql.org/
220 [HSQLDB]: http://hsqldb.org/
221 [Zenko CloudServer]: https://github.com/scality/cloudserver
222
223 ## Licensing
224
225 Copyright (c) 2020 SAP SE or an SAP affiliate company.
226
227 Licensed under the **Apache License, Version 2.0** (the "License"); you may not use this file except in compliance with the License.
228
229 You may obtain a copy of the License at <https://www.apache.org/licenses/LICENSE-2.0>.
230
231 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.
232
[end of README.md]
[start of services/submission/src/main/java/app/coronawarn/server/services/submission/config/SubmissionServiceConfig.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.submission.config;
22
23 import org.springframework.boot.context.properties.ConfigurationProperties;
24 import org.springframework.stereotype.Component;
25
26 @Component
27 @ConfigurationProperties(prefix = "services.submission")
28 public class SubmissionServiceConfig {
29
30 // Exponential moving average of the last N real request durations (in ms), where
31 // N = fakeDelayMovingAverageSamples.
32 private Double initialFakeDelayMilliseconds;
33 private Double fakeDelayMovingAverageSamples;
34 private Integer retentionDays;
35 private Payload payload;
36 private Verification verification;
37 private Monitoring monitoring;
38
39 public Double getInitialFakeDelayMilliseconds() {
40 return initialFakeDelayMilliseconds;
41 }
42
43 public void setInitialFakeDelayMilliseconds(Double initialFakeDelayMilliseconds) {
44 this.initialFakeDelayMilliseconds = initialFakeDelayMilliseconds;
45 }
46
47 public Double getFakeDelayMovingAverageSamples() {
48 return fakeDelayMovingAverageSamples;
49 }
50
51 public void setFakeDelayMovingAverageSamples(Double fakeDelayMovingAverageSamples) {
52 this.fakeDelayMovingAverageSamples = fakeDelayMovingAverageSamples;
53 }
54
55 public Integer getRetentionDays() {
56 return retentionDays;
57 }
58
59 public void setRetentionDays(Integer retentionDays) {
60 this.retentionDays = retentionDays;
61 }
62
63 public Integer getMaxNumberOfKeys() {
64 return payload.getMaxNumberOfKeys();
65 }
66
67 public void setPayload(Payload payload) {
68 this.payload = payload;
69 }
70
71 private static class Payload {
72
73 private Integer maxNumberOfKeys;
74
75 public Integer getMaxNumberOfKeys() {
76 return maxNumberOfKeys;
77 }
78
79 public void setMaxNumberOfKeys(Integer maxNumberOfKeys) {
80 this.maxNumberOfKeys = maxNumberOfKeys;
81 }
82 }
83
84 public String getVerificationBaseUrl() {
85 return verification.getBaseUrl();
86 }
87
88 public void setVerification(Verification verification) {
89 this.verification = verification;
90 }
91
92 public String getVerificationPath() {
93 return verification.getPath();
94 }
95
96 private static class Verification {
97 private String baseUrl;
98
99 private String path;
100
101 public String getBaseUrl() {
102 return baseUrl;
103 }
104
105 public String getPath() {
106 return path;
107 }
108
109 public void setBaseUrl(String baseUrl) {
110 this.baseUrl = baseUrl;
111 }
112
113 public void setPath(String path) {
114 this.path = path;
115 }
116 }
117
118 private static class Monitoring {
119 private Integer batchSize;
120
121 public Integer getBatchSize() {
122 return batchSize;
123 }
124
125 public void setBatchSize(Integer batchSize) {
126 this.batchSize = batchSize;
127 }
128 }
129
130 public Monitoring getMonitoring() {
131 return monitoring;
132 }
133
134 public void setMonitoring(Monitoring monitoring) {
135 this.monitoring = monitoring;
136 }
137
138 public Integer getMonitoringBatchSize() {
139 return this.monitoring.getBatchSize();
140 }
141
142 public void setMonitoringBatchSize(Integer batchSize) {
143 this.monitoring.setBatchSize(batchSize);
144 }
145 }
146
[end of services/submission/src/main/java/app/coronawarn/server/services/submission/config/SubmissionServiceConfig.java]
[start of services/submission/src/main/java/app/coronawarn/server/services/submission/monitoring/BatchCounter.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.submission.monitoring;
22
23 import io.micrometer.core.instrument.Counter;
24 import io.micrometer.core.instrument.MeterRegistry;
25
26 /**
27 * Batch counter for counting requests for monitoring. Counts up in batches, given batch size. This way, single requests
28 * cannot be traced to semantics of the counter by comparing time stamps.
29 */
30 public class BatchCounter {
31
32 private static final String SUBMISSION_CONTROLLER_REQUESTS_COUNTER_NAME = "submission_controller.requests";
33 private static final String SUBMISSION_CONTROLLER_REQUESTS_COUNTER_DESCRIPTION
34 = "Counts requests to the Submission Controller.";
35
36 private final int batchSize;
37 private final Counter counter;
38 private Double batch = 0.;
39
40 BatchCounter(MeterRegistry meterRegistry, int batchSize, String type) {
41 this.batchSize = batchSize;
42 counter = Counter.builder(SUBMISSION_CONTROLLER_REQUESTS_COUNTER_NAME)
43 .tag("type", type)
44 .description(SUBMISSION_CONTROLLER_REQUESTS_COUNTER_DESCRIPTION)
45 .register(meterRegistry);
46 }
47
48 /**
49 * Increments the {@link BatchCounter}. If the batch size is reached, it is provided to monitoring, else, the internal
50 * counter is incremented.
51 */
52 public void increment() {
53 if (batch < batchSize) {
54 batch++;
55 } else {
56 counter.increment(batch);
57 batch = 1.;
58 }
59 }
60 }
61
[end of services/submission/src/main/java/app/coronawarn/server/services/submission/monitoring/BatchCounter.java]
[start of services/submission/src/main/java/app/coronawarn/server/services/submission/monitoring/SubmissionControllerMonitor.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.submission.monitoring;
22
23 import app.coronawarn.server.services.submission.config.SubmissionServiceConfig;
24 import app.coronawarn.server.services.submission.controller.SubmissionController;
25 import io.micrometer.core.instrument.Gauge;
26 import io.micrometer.core.instrument.MeterRegistry;
27 import org.springframework.boot.context.properties.ConfigurationProperties;
28 import org.springframework.stereotype.Component;
29
30 /**
31 * Provides functionality for monitoring the application logic of the
32 * {@link app.coronawarn.server.services.submission.controller.SubmissionController}.
33 */
34 @Component
35 @ConfigurationProperties(prefix = "services.submission.monitoring")
36 public class SubmissionControllerMonitor {
37 private static final String SUBMISSION_CONTROLLER_CURRENT_FAKE_DELAY = "submission_controller.fake_delay_seconds";
38
39 private final MeterRegistry meterRegistry;
40
41 private final Integer batchSize;
42 private BatchCounter requests;
43 private BatchCounter realRequests;
44 private BatchCounter fakeRequests;
45 private BatchCounter invalidTanRequests;
46
47 /**
48 * Constructor for {@link SubmissionControllerMonitor}. Initializes all counters to 0 upon being called.
49 *
50 * @param meterRegistry the meterRegistry
51 */
52 protected SubmissionControllerMonitor(MeterRegistry meterRegistry, SubmissionServiceConfig submissionServiceConfig) {
53 this.meterRegistry = meterRegistry;
54 this.batchSize = submissionServiceConfig.getMonitoringBatchSize();
55 initializeCounters();
56 }
57
58 /**
59 * We count the following values.
60 * <ul>
61 * <li> All requests that come in to the {@link SubmissionController}.
62 * <li> As part of all, the number of requests that are not fake.
63 * <li> As part of all, the number of requests that are fake.
64 * <li> As part of all, the number of requests for that the TAN-validation failed.
65 * </ul>
66 */
67 private void initializeCounters() {
68 requests = new BatchCounter(meterRegistry, batchSize, "all");
69 realRequests = new BatchCounter(meterRegistry, batchSize, "real");
70 fakeRequests = new BatchCounter(meterRegistry, batchSize, "fake");
71 invalidTanRequests = new BatchCounter(meterRegistry, batchSize, "invalidTan");
72 }
73
74 /**
75 * Initializes the gauges for the {@link SubmissionController} that is being monitored. Currently, only the delay time
76 * of fake requests is measured.
77 *
78 * @param submissionController the submission controller for which the gauges shall be initialized
79 */
80 public void initializeGauges(SubmissionController submissionController) {
81 Gauge.builder(SUBMISSION_CONTROLLER_CURRENT_FAKE_DELAY, submissionController,
82 __ -> submissionController.getFakeDelayInSeconds())
83 .description("The time that fake requests are delayed to make them indistinguishable from real requests.")
84 .register(meterRegistry);
85 }
86
87 public void incrementRequestCounter() {
88 requests.increment();
89 }
90
91 public void incrementRealRequestCounter() {
92 realRequests.increment();
93 }
94
95 public void incrementFakeRequestCounter() {
96 fakeRequests.increment();
97 }
98
99 public void incrementInvalidTanRequestCounter() {
100 invalidTanRequests.increment();
101 }
102 }
103
[end of services/submission/src/main/java/app/coronawarn/server/services/submission/monitoring/SubmissionControllerMonitor.java]
</code>
Here is an example of a patch file. It consists of changes to the code base. It specifies the file names, the line numbers of each change, and the removed and added lines. A single patch file can contain changes to multiple files.
<patch>
--- a/file.py
+++ b/file.py
@@ -1,27 +1,35 @@
def euclidean(a, b):
- while b:
- a, b = b, a % b
- return a
+ if b == 0:
+ return a
+ return euclidean(b, a % b)
def bresenham(x0, y0, x1, y1):
points = []
dx = abs(x1 - x0)
dy = abs(y1 - y0)
- sx = 1 if x0 < x1 else -1
- sy = 1 if y0 < y1 else -1
- err = dx - dy
+ x, y = x0, y0
+ sx = -1 if x0 > x1 else 1
+ sy = -1 if y0 > y1 else 1
- while True:
- points.append((x0, y0))
- if x0 == x1 and y0 == y1:
- break
- e2 = 2 * err
- if e2 > -dy:
+ if dx > dy:
+ err = dx / 2.0
+ while x != x1:
+ points.append((x, y))
err -= dy
- x0 += sx
- if e2 < dx:
- err += dx
- y0 += sy
+ if err < 0:
+ y += sy
+ err += dx
+ x += sx
+ else:
+ err = dy / 2.0
+ while y != y1:
+ points.append((x, y))
+ err -= dx
+ if err < 0:
+ x += sx
+ err += dy
+ y += sy
+ points.append((x, y))
return points
</patch>
I need you to solve the provded issue by generating a single patch file that I can apply directly to this repository using git apply. Please respond with a single patch file in the format shown above.
Respond below:
| corona-warn-app/cwa-server | 39cf982dab39722accf5cbb2cc6f2c6ef15c8456 | BatchCounter uses Double for counting
## Describe the bug
BatchCounter uses `double` for integer arithmetics, which is commonly discouraged.
## Expected behaviour
BatchCounter uses `int` for counting up to `batchSize`, since `batchSize` is also of type `int`.
It's faster.
In theory it's more accurate. (In practice there is no difference in this case since the maximum value that is representable in a double is larger than `Integer.MAX_VALUE`. But for `long` instead of `int`, there would be a difference.)
## Possible Fix
~~~java
private int batch;
~~~
While here, `batch` should be renamed to `batchCount` to better express its actual meaning.
BatchCounter is not thread-safe
## Describe the bug
When multiple threads call `BatchCounter.increment` at the same time, the resulting count is unspecified.
## Expected behaviour
`synchronized void increment`
## Steps to reproduce the issue
Call `BatchCounter` from several threads at the same time.
## Possible Fix
Add `synchronized`.
| 2020-06-11T18:31:41 | <patch>
diff --git a/services/submission/src/main/java/app/coronawarn/server/services/submission/config/SubmissionServiceConfig.java b/services/submission/src/main/java/app/coronawarn/server/services/submission/config/SubmissionServiceConfig.java
--- a/services/submission/src/main/java/app/coronawarn/server/services/submission/config/SubmissionServiceConfig.java
+++ b/services/submission/src/main/java/app/coronawarn/server/services/submission/config/SubmissionServiceConfig.java
@@ -116,13 +116,13 @@ public void setPath(String path) {
}
private static class Monitoring {
- private Integer batchSize;
+ private Long batchSize;
- public Integer getBatchSize() {
+ public Long getBatchSize() {
return batchSize;
}
- public void setBatchSize(Integer batchSize) {
+ public void setBatchSize(Long batchSize) {
this.batchSize = batchSize;
}
}
@@ -135,11 +135,11 @@ public void setMonitoring(Monitoring monitoring) {
this.monitoring = monitoring;
}
- public Integer getMonitoringBatchSize() {
+ public Long getMonitoringBatchSize() {
return this.monitoring.getBatchSize();
}
- public void setMonitoringBatchSize(Integer batchSize) {
+ public void setMonitoringBatchSize(Long batchSize) {
this.monitoring.setBatchSize(batchSize);
}
}
diff --git a/services/submission/src/main/java/app/coronawarn/server/services/submission/monitoring/BatchCounter.java b/services/submission/src/main/java/app/coronawarn/server/services/submission/monitoring/BatchCounter.java
--- a/services/submission/src/main/java/app/coronawarn/server/services/submission/monitoring/BatchCounter.java
+++ b/services/submission/src/main/java/app/coronawarn/server/services/submission/monitoring/BatchCounter.java
@@ -22,6 +22,7 @@
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
+import java.util.concurrent.atomic.AtomicLong;
/**
* Batch counter for counting requests for monitoring. Counts up in batches, given batch size. This way, single requests
@@ -33,11 +34,11 @@ public class BatchCounter {
private static final String SUBMISSION_CONTROLLER_REQUESTS_COUNTER_DESCRIPTION
= "Counts requests to the Submission Controller.";
- private final int batchSize;
+ private final long batchSize;
private final Counter counter;
- private Double batch = 0.;
+ private final AtomicLong count = new AtomicLong(0L);
- BatchCounter(MeterRegistry meterRegistry, int batchSize, String type) {
+ BatchCounter(MeterRegistry meterRegistry, long batchSize, String type) {
this.batchSize = batchSize;
counter = Counter.builder(SUBMISSION_CONTROLLER_REQUESTS_COUNTER_NAME)
.tag("type", type)
@@ -50,11 +51,8 @@ public class BatchCounter {
* counter is incremented.
*/
public void increment() {
- if (batch < batchSize) {
- batch++;
- } else {
- counter.increment(batch);
- batch = 1.;
+ if (0 == count.incrementAndGet() % batchSize) {
+ counter.increment(batchSize);
}
}
}
diff --git a/services/submission/src/main/java/app/coronawarn/server/services/submission/monitoring/SubmissionControllerMonitor.java b/services/submission/src/main/java/app/coronawarn/server/services/submission/monitoring/SubmissionControllerMonitor.java
--- a/services/submission/src/main/java/app/coronawarn/server/services/submission/monitoring/SubmissionControllerMonitor.java
+++ b/services/submission/src/main/java/app/coronawarn/server/services/submission/monitoring/SubmissionControllerMonitor.java
@@ -38,7 +38,7 @@ public class SubmissionControllerMonitor {
private final MeterRegistry meterRegistry;
- private final Integer batchSize;
+ private final long batchSize;
private BatchCounter requests;
private BatchCounter realRequests;
private BatchCounter fakeRequests;
</patch> | diff --git a/services/submission/src/test/java/app/coronawarn/server/services/submission/monitoring/BatchCounterTest.java b/services/submission/src/test/java/app/coronawarn/server/services/submission/monitoring/BatchCounterTest.java
new file mode 100644
--- /dev/null
+++ b/services/submission/src/test/java/app/coronawarn/server/services/submission/monitoring/BatchCounterTest.java
@@ -0,0 +1,64 @@
+/*-
+ * ---license-start
+ * Corona-Warn-App
+ * ---
+ * Copyright (C) 2020 SAP SE and all other contributors
+ * ---
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://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 for the specific language governing permissions and
+ * limitations under the License.
+ * ---license-end
+ */
+
+package app.coronawarn.server.services.submission.monitoring;
+
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+
+import io.micrometer.core.instrument.Counter;
+import io.micrometer.core.instrument.MeterRegistry;
+import io.micrometer.core.instrument.MeterRegistryMock;
+import java.util.stream.LongStream;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+class BatchCounterTest {
+
+ private static final String COUNTER_TYPE = "FooCounter";
+ private MeterRegistry meterRegistry;
+ private Counter meterCounter;
+
+ @BeforeEach
+ void setUpCounter() {
+ meterCounter = mock(Counter.class);
+ meterRegistry = spy(new MeterRegistryMock(meterCounter));
+ }
+
+ @ParameterizedTest
+ @ValueSource(longs = {1L, 2L, 4L})
+ void incrementSubmittedOnceIfBatchSizeReached(long batchSize) {
+ BatchCounter batchCounter = new BatchCounter(meterRegistry, batchSize, COUNTER_TYPE);
+ LongStream.range(0, batchSize).forEach(__ -> batchCounter.increment());
+ verify(meterCounter, times(1)).increment(batchSize);
+ }
+
+ @ParameterizedTest
+ @ValueSource(longs = {2L, 4L, 7L})
+ void doesNotIncrementIfLesserThanBatchSize(long batchSize) {
+ BatchCounter batchCounter = new BatchCounter(meterRegistry, batchSize, COUNTER_TYPE);
+ LongStream.range(0, batchSize - 1).forEach(__ -> batchCounter.increment());
+ verify(meterCounter, never()).increment(batchSize);
+ }
+}
diff --git a/services/submission/src/test/java/io/micrometer/core/instrument/MeterRegistryMock.java b/services/submission/src/test/java/io/micrometer/core/instrument/MeterRegistryMock.java
new file mode 100644
--- /dev/null
+++ b/services/submission/src/test/java/io/micrometer/core/instrument/MeterRegistryMock.java
@@ -0,0 +1,40 @@
+/*-
+ * ---license-start
+ * Corona-Warn-App
+ * ---
+ * Copyright (C) 2020 SAP SE and all other contributors
+ * ---
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://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 for the specific language governing permissions and
+ * limitations under the License.
+ * ---license-end
+ */
+
+package io.micrometer.core.instrument;
+
+import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
+
+/**
+ * Used to get access to the {@link Counter} instance in BatchCounterTest.
+ */
+public class MeterRegistryMock extends SimpleMeterRegistry {
+
+ final Counter counter;
+
+ public MeterRegistryMock(Counter counter) {
+ this.counter = counter;
+ }
+
+ @Override
+ Counter counter(Meter.Id id) {
+ return counter;
+ }
+}
| |||||
corona-warn-app__cwa-server-349 | You will be provided with a partial code base and an issue statement explaining a problem to resolve.
<issue>
S3Publisher should set Cache Control Headers
The S3Publisher is currently not setting Cache Control Headers. We should cache-control: public, maxage=N
N depends on the type of file:
- for hours index files, it should be rather low (5 minutes)
- for days index files, it should be higher (2 hours)
- for all generated aggregate files, it should be 24 hours
E-Tag should already been set, but should also be verified.
</issue>
<code>
[start of README.md]
1 <!-- markdownlint-disable MD041 -->
2 <h1 align="center">
3 Corona-Warn-App Server
4 </h1>
5
6 <p align="center">
7 <a href="https://github.com/corona-warn-app/cwa-server/commits/" title="Last Commit"><img src="https://img.shields.io/github/last-commit/corona-warn-app/cwa-server?style=flat"></a>
8 <a href="https://github.com/corona-warn-app/cwa-server/issues" title="Open Issues"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat"></a>
9 <a href="https://circleci.com/gh/corona-warn-app/cwa-server" title="Build Status"><img src="https://circleci.com/gh/corona-warn-app/cwa-server.svg?style=shield&circle-token=4ab059989d10709df19eb4b98ab7c121a25e981a"></a>
10 <a href="https://sonarcloud.io/dashboard?id=corona-warn-app_cwa-server" title="Quality Gate"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=alert_status"></a>
11 <a href="https://sonarcloud.io/component_measures?id=corona-warn-app_cwa-server&metric=Coverage&view=list" title="Coverage"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=coverage"></a>
12 <a href="https://github.com/corona-warn-app/cwa-server/blob/master/LICENSE" title="License"><img src="https://img.shields.io/badge/License-Apache%202.0-green.svg?style=flat"></a>
13 </p>
14
15 <p align="center">
16 <a href="#development">Development</a> •
17 <a href="#service-apis">Service APIs</a> •
18 <a href="#documentation">Documentation</a> •
19 <a href="#support-and-feedback">Support</a> •
20 <a href="#how-to-contribute">Contribute</a> •
21 <a href="#contributors">Contributors</a> •
22 <a href="#repositories">Repositories</a> •
23 <a href="#licensing">Licensing</a>
24 </p>
25
26 The goal of this project is to develop the official Corona-Warn-App for Germany based on the exposure notification API from [Apple](https://www.apple.com/covid19/contacttracing/) and [Google](https://www.google.com/covid19/exposurenotifications/). The apps (for both iOS and Android) use Bluetooth technology to exchange anonymous encrypted data with other mobile phones (on which the app is also installed) in the vicinity of an app user's phone. The data is stored locally on each user's device, preventing authorities or other parties from accessing or controlling the data. This repository contains the **implementation of the server for encryption keys** for the Corona-Warn-App. This implementation is still a **work in progress**, and the code it contains is currently alpha-quality code.
27
28 In this documentation, Corona-Warn-App services are also referred to as CWA services.
29
30 ## Architecture Overview
31
32 You can find the architecture overview [here](/docs/architecture-overview.md), which will give you
33 a good starting point in how the backend services interact with other services, and what purpose
34 they serve.
35
36 ## Development
37
38 After you've checked out this repository, you can run the application in one of the following ways:
39
40 * As a [Docker](https://www.docker.com/)-based deployment on your local machine. You can run either:
41 * Single components using the respective Dockerfile or
42 * The full backend using the Docker Compose (which is considered the most convenient way)
43 * As a [Maven](https://maven.apache.org)-based build on your local machine.
44 If you want to develop something in a single component, this approach is preferable.
45
46 ### Docker-Based Deployment
47
48 If you want to use Docker-based deployment, you need to install Docker on your local machine. For more information about downloading and installing Docker, see the [official Docker documentation](https://docs.docker.com/get-docker/).
49
50 #### Running the Full CWA Backend Using Docker Compose
51
52 For your convenience, a full setup including the generation of test data has been prepared using [Docker Compose](https://docs.docker.com/compose/reference/overview/). To build the backend services, run ```docker-compose build``` in the repository's root directory. A default configuration file can be found under ```.env```in the root folder of the repository. The default values for the local Postgres and Zenko Cloudserver should be changed in this file before docker-compose is run.
53
54 Once the services are built, you can start the whole backend using ```docker-compose up```.
55 The distribution service runs once and then finishes. If you want to trigger additional distribution runs, run ```docker-compose run distribution```.
56
57 The docker-compose contains the following services:
58
59 Service | Description | Endpoint and Default Credentials
60 ------------------|-------------|-----------
61 submission | The Corona-Warn-App submission service | `http://localhost:8000` <br> `http://localhost:8006` (for actuator endpoint)
62 distribution | The Corona-Warn-App distribution service | NO ENDPOINT
63 postgres | A [postgres] database installation | `postgres:8001` <br> Username: postgres <br> Password: postgres
64 pgadmin | A [pgadmin](https://www.pgadmin.org/) installation for the postgres database | `http://localhost:8002` <br> Username: [email protected] <br> Password: password
65 cloudserver | [Zenko CloudServer] is a S3-compliant object store | `http://localhost:8003/` <br> Access key: accessKey1 <br> Secret key: verySecretKey1
66 verification-fake | A very simple fake implementation for the tan verification. | `http://localhost:8004/version/v1/tan/verify` <br> The only valid tan is "b69ab69f-9823-4549-8961-c41sa74b2f36"
67
68 ##### Known Limitation
69
70 In rare cases the docker-compose runs into a timing issue if the distribution service starts before the bucket of the objectstore was created. This is not a big issue as you can simply run ```docker-compose run distribution``` to trigger additional distribution runs after the objectstore was initialized.
71
72 #### Running Single CWA Services Using Docker
73
74 If you would like to build and run a single CWA service, it's considered easiest to run them in a Docker environment. You can do this using the script provided in the respective CWA service directory. The Docker script first builds the CWA service and then creates an image for the runtime, which means that there are no additional dependencies for you to install.
75
76 To build and run the distribution service, run the following command:
77
78 ```bash
79 ./services/distribution/build_and_run.sh
80 ```
81
82 To build and run the submission service, run the following command:
83
84 ```bash
85 ./services/submission/build_and_run.sh
86 ```
87
88 The submission service is available on [localhost:8080](http://localhost:8080 ).
89
90 ### Maven-Based Build
91
92 If you want to actively develop in one of the CWA services, the Maven-based runtime is most suitable.
93 To prepare your machine to run the CWA project locally, we recommend that you first ensure that you've installed the following:
94
95 * Minimum JDK Version 11: [OpenJDK](https://openjdk.java.net/) / [SapMachine](https://sap.github.io/SapMachine/)
96 * [Maven 3.6](https://maven.apache.org/)
97 * [Postgres]
98 * [Zenko CloudServer]
99
100 #### Configure
101
102 After you made sure that the specified dependencies are running, configure them in the respective configuration files.
103
104 * Configure the Postgres connection in the [submission config](./services/submission/src/main/resources/application.yaml) and in the [distribution config](./services/distribution/src/main/resources/application.yaml)
105 * Configure the S3 compatible object storage in the [distribution config](./services/distribution/src/main/resources/application.yaml)
106 * Configure the private key for the distribution service, the path need to be prefixed with `file:`
107 * `VAULT_FILESIGNING_SECRET` should be the path to the private key, example available in `<repo-root>/docker-compose-test-secrets/private.pem`
108
109 #### Build
110
111 After you've checked out the repository, to build the project, run ```mvn install``` in your base directory.
112
113 #### Run
114
115 Navigate to the service you want to start and run the spring-boot:run target. The configured Postgres and the configured S3 compliant object storage are used as default. When you start the submission service, the endpoint is available on your local port 8080.
116
117 If you want to start the submission service, for example, you start it as follows:
118
119 ```bash
120 cd services/submission/
121 mvn spring-boot:run
122 ```
123
124 #### Debugging
125
126 To enable the `DEBUG` log level, you can run the application using the Spring `dev` profile.
127
128 ```bash
129 mvn spring-boot:run -Dspring-boot.run.profiles=dev
130 ```
131
132 To be able to set breakpoints (e.g. in IntelliJ), it may be necessary to use the ```-Dspring-boot.run.fork=false``` parameter.
133
134 ## Service APIs
135
136 The API that is being exposed by the backend services is documented in an [OpenAPI](https://www.openapis.org/) specification. The specification files are available at the following locations:
137
138 Service | OpenAPI Specification
139 -------------|-------------
140 Submission Service | [services/submission/api_v1.json](https://github.com/corona-warn-app/cwa-server/raw/master/services/submission/api_v1.json)
141 Distribution Service | [services/distribution/api_v1.json)](https://github.com/corona-warn-app/cwa-server/raw/master/services/distribution/api_v1.json)
142
143 ## Spring Profiles
144
145 ### Distribution
146
147 Profile | Effect
148 -------------|-------------
149 `dev` | Turns the log level to `DEBUG` and sets the app package ID in the export packages' signature info to `de.rki.coronawarnapp-dev` so that test certificates (instead of production certificates) will be used for client-side validation.
150 `cloud` | Removes default values for the `datasource` and `objectstore` configurations.
151 `demo` | Includes incomplete days and hours into the distribution run, thus creating aggregates for the current day and the current hour (and including both in the respective indices). When running multiple distributions in one hour with this profile, the date aggregate for today and the hours aggregate for the current hour will be updated and overwritten.
152 `testdata` | Causes test data to be inserted into the database before each distribution run. By default, around 1000 random diagnosis keys will be generated per hour. If there are no diagnosis keys in the database yet, random keys will be generated for every hour from the beginning of the retention period (14 days ago at 00:00 UTC) until one hour before the present hour. If there are already keys in the database, the random keys will be generated for every hour from the latest diagnosis key in the database (by submission timestamp) until one hour before the present hour (or none at all, if the latest diagnosis key in the database was submitted one hour ago or later).
153
154 ### Submission
155
156 Profile | Effect
157 -------------|-------------
158 `dev` | Turns the log level to `DEBUG`.
159 `cloud` | Removes default values for the `datasource` configuration.
160
161 ## Documentation
162
163 The full documentation for the Corona-Warn-App can be found in the [cwa-documentation](https://github.com/corona-warn-app/cwa-documentation) repository. The documentation repository contains technical documents, architecture information, and whitepapers related to this implementation.
164
165 ## Support and Feedback
166
167 The following channels are available for discussions, feedback, and support requests:
168
169 | Type | Channel |
170 | ------------------------ | ------------------------------------------------------ |
171 | **General Discussion** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="General Discussion"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/question.svg?style=flat-square"></a> </a> |
172 | **Concept Feedback** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="Open Concept Feedback"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/architecture.svg?style=flat-square"></a> |
173 | **Backend Issue** | <a href="https://github.com/corona-warn-app/cwa-server/issues/new/choose" title="Open Backend Issue"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat-square"></a> |
174 | **Other Requests** | <a href="mailto:[email protected]" title="Email CWA Team"><img src="https://img.shields.io/badge/email-CWA%20team-green?logo=mail.ru&style=flat-square&logoColor=white"></a> |
175
176 ## How to Contribute
177
178 Contribution and feedback are 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.
179
180 ## Contributors
181
182 The German government has asked SAP and Deutsche Telekom to develop the Corona-Warn-App for Germany as open source software. Deutsche Telekom is providing the network and mobile technology and will operate and run the backend for the app in a safe, scalable and stable manner. SAP is responsible for the app development, its framework and the underlying platform. Therefore, development teams of SAP and Deutsche Telekom are contributing to this project. At the same time 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.
183
184 ## Repositories
185
186 The following public repositories are currently available for the Corona-Warn-App:
187
188 | Repository | Description |
189 | ------------------- | --------------------------------------------------------------------- |
190 | [cwa-documentation] | Project overview, general documentation, and white papers |
191 | [cwa-server] | Backend implementation for the Apple/Google exposure notification API|
192 | [cwa-verification-server] | Backend implementation of the verification process|
193
194 [cwa-documentation]: https://github.com/corona-warn-app/cwa-documentation
195 [cwa-server]: https://github.com/corona-warn-app/cwa-server
196 [cwa-verification-server]: https://github.com/corona-warn-app/cwa-verification-server
197 [Postgres]: https://www.postgresql.org/
198 [HSQLDB]: http://hsqldb.org/
199 [Zenko CloudServer]: https://github.com/scality/cloudserver
200
201 ## Licensing
202
203 Copyright (c) 2020 SAP SE or an SAP affiliate company.
204
205 Licensed under the **Apache License, Version 2.0** (the "License"); you may not use this file except in compliance with the License.
206
207 You may obtain a copy of the License at <https://www.apache.org/licenses/LICENSE-2.0>.
208
209 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.
210
[end of README.md]
[start of /dev/null]
1
[end of /dev/null]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/ObjectStoreAccess.java]
1 /*
2 * Corona-Warn-App
3 *
4 * SAP SE and all other contributors /
5 * copyright owners license this file to you under the Apache
6 * License, Version 2.0 (the "License"); you may not use this
7 * file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20 package app.coronawarn.server.services.distribution.objectstore;
21
22 import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
23 import app.coronawarn.server.services.distribution.config.DistributionServiceConfig.ObjectStore;
24 import app.coronawarn.server.services.distribution.objectstore.publish.LocalFile;
25 import io.minio.MinioClient;
26 import io.minio.PutObjectOptions;
27 import io.minio.Result;
28 import io.minio.errors.InvalidEndpointException;
29 import io.minio.errors.InvalidPortException;
30 import io.minio.errors.MinioException;
31 import io.minio.messages.DeleteError;
32 import io.minio.messages.Item;
33 import java.io.IOException;
34 import java.security.GeneralSecurityException;
35 import java.util.ArrayList;
36 import java.util.List;
37 import java.util.Map;
38 import java.util.stream.Collectors;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41 import org.springframework.stereotype.Component;
42
43 /**
44 * <p>Grants access to the S3 compatible object storage hosted by Telekom in Germany, enabling
45 * basic functionality for working with files.</p>
46 * <br>
47 * Make sure the following properties are available on the env:
48 * <ul>
49 * <li>services.distribution.objectstore.endpoint</li>
50 * <li>services.distribution.objectstore.bucket</li>
51 * <li>services.distribution.objectstore.accessKey</li>
52 * <li>services.distribution.objectstore.secretKey</li>
53 * <li>services.distribution.objectstore.port</li>
54 * </ul>
55 */
56 @Component
57 public class ObjectStoreAccess {
58
59 private static final Logger logger = LoggerFactory.getLogger(ObjectStoreAccess.class);
60
61 private static final String DEFAULT_REGION = "eu-west-1";
62
63 private final boolean isSetPublicReadAclOnPutObject;
64
65 private final String bucket;
66
67 private final MinioClient client;
68
69 /**
70 * Constructs an {@link ObjectStoreAccess} instance for communication with the specified object store endpoint and
71 * bucket.
72 *
73 * @param distributionServiceConfig The config properties
74 * @throws IOException When there were problems creating the S3 client
75 * @throws GeneralSecurityException When there were problems creating the S3 client
76 * @throws MinioException When there were problems creating the S3 client
77 */
78 ObjectStoreAccess(DistributionServiceConfig distributionServiceConfig)
79 throws IOException, GeneralSecurityException, MinioException {
80 this.client = createClient(distributionServiceConfig.getObjectStore());
81
82 this.bucket = distributionServiceConfig.getObjectStore().getBucket();
83 this.isSetPublicReadAclOnPutObject = distributionServiceConfig.getObjectStore().isSetPublicReadAclOnPutObject();
84
85 if (!this.client.bucketExists(this.bucket)) {
86 throw new IllegalArgumentException("Supplied bucket does not exist " + bucket);
87 }
88 }
89
90 private MinioClient createClient(ObjectStore objectStore)
91 throws InvalidPortException, InvalidEndpointException {
92 if (isSsl(objectStore)) {
93 return new MinioClient(
94 objectStore.getEndpoint(),
95 objectStore.getPort(),
96 objectStore.getAccessKey(), objectStore.getSecretKey(),
97 DEFAULT_REGION,
98 true
99 );
100 } else {
101 return new MinioClient(
102 objectStore.getEndpoint(),
103 objectStore.getPort(),
104 objectStore.getAccessKey(), objectStore.getSecretKey()
105 );
106 }
107 }
108
109 private boolean isSsl(ObjectStore objectStore) {
110 return objectStore.getEndpoint().startsWith("https://");
111 }
112
113 /**
114 * Stores the target file on the S3.
115 *
116 * @param localFile the file to be published
117 */
118 public void putObject(LocalFile localFile)
119 throws IOException, GeneralSecurityException, MinioException {
120 String s3Key = localFile.getS3Key();
121 PutObjectOptions options = createOptionsFor(localFile);
122
123 logger.info("... uploading {}", s3Key);
124 this.client.putObject(bucket, s3Key, localFile.getFile().toString(), options);
125 }
126
127 /**
128 * Deletes objects in the object store, based on the given prefix (folder structure).
129 *
130 * @param prefix the prefix, e.g. my/folder/
131 */
132 public void deleteObjectsWithPrefix(String prefix)
133 throws MinioException, GeneralSecurityException, IOException {
134 List<String> toDelete = getObjectsWithPrefix(prefix)
135 .stream()
136 .map(S3Object::getObjectName)
137 .collect(Collectors.toList());
138
139 logger.info("Deleting {} entries with prefix {}", toDelete.size(), prefix);
140 var deletionResponse = this.client.removeObjects(bucket, toDelete);
141
142 List<DeleteError> errors = new ArrayList<>();
143 for (Result<DeleteError> deleteErrorResult : deletionResponse) {
144 errors.add(deleteErrorResult.get());
145 }
146
147 if (!errors.isEmpty()) {
148 throw new MinioException("Can't delete files, number of errors: " + errors.size());
149 }
150 }
151
152 /**
153 * Fetches the list of objects in the store with the given prefix.
154 *
155 * @param prefix the prefix, e.g. my/folder/
156 * @return the list of objects
157 */
158 public List<S3Object> getObjectsWithPrefix(String prefix)
159 throws IOException, GeneralSecurityException, MinioException {
160 var objects = this.client.listObjects(bucket, prefix, true);
161
162 var list = new ArrayList<S3Object>();
163 for (Result<Item> item : objects) {
164 list.add(S3Object.of(item.get()));
165 }
166
167 return list;
168 }
169
170 private PutObjectOptions createOptionsFor(LocalFile file) {
171 var options = new PutObjectOptions(file.getFile().toFile().length(), -1);
172
173 if (this.isSetPublicReadAclOnPutObject) {
174 options.setHeaders(Map.of("x-amz-acl", "public-read"));
175 }
176
177 return options;
178 }
179
180 }
181
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/ObjectStoreAccess.java]
</code>
Here is an example of a patch file. It consists of changes to the code base. It specifies the file names, the line numbers of each change, and the removed and added lines. A single patch file can contain changes to multiple files.
<patch>
--- a/file.py
+++ b/file.py
@@ -1,27 +1,35 @@
def euclidean(a, b):
- while b:
- a, b = b, a % b
- return a
+ if b == 0:
+ return a
+ return euclidean(b, a % b)
def bresenham(x0, y0, x1, y1):
points = []
dx = abs(x1 - x0)
dy = abs(y1 - y0)
- sx = 1 if x0 < x1 else -1
- sy = 1 if y0 < y1 else -1
- err = dx - dy
+ x, y = x0, y0
+ sx = -1 if x0 > x1 else 1
+ sy = -1 if y0 > y1 else 1
- while True:
- points.append((x0, y0))
- if x0 == x1 and y0 == y1:
- break
- e2 = 2 * err
- if e2 > -dy:
+ if dx > dy:
+ err = dx / 2.0
+ while x != x1:
+ points.append((x, y))
err -= dy
- x0 += sx
- if e2 < dx:
- err += dx
- y0 += sy
+ if err < 0:
+ y += sy
+ err += dx
+ x += sx
+ else:
+ err = dy / 2.0
+ while y != y1:
+ points.append((x, y))
+ err -= dx
+ if err < 0:
+ x += sx
+ err += dy
+ y += sy
+ points.append((x, y))
return points
</patch>
I need you to solve the provded issue by generating a single patch file that I can apply directly to this repository using git apply. Please respond with a single patch file in the format shown above.
Respond below:
| corona-warn-app/cwa-server | ef4edb4c92fb9bf65544e22e2b4f2e8f8a55fa97 | S3Publisher should set Cache Control Headers
The S3Publisher is currently not setting Cache Control Headers. We should cache-control: public, maxage=N
N depends on the type of file:
- for hours index files, it should be rather low (5 minutes)
- for days index files, it should be higher (2 hours)
- for all generated aggregate files, it should be 24 hours
E-Tag should already been set, but should also be verified.
| For the sake of simplicity, I think we can get away with just setting everything to 5 minutes. In the worst case, we need to expect requests for all available files by all 4 CDN master cache servers every 5 minutes. We serve a peak total of 356 files (1 version index, 1 version OpenAPI JSON, 2 country indices for diagnosis keys and parameters, 1 date index, 14 date aggregates, 14 hour indices, 14*24 hour aggregates, 1 parameter configuration). If we set everything to 5 minutes, this would lead to an average of:
* 1424 requests per 5 minutes
* ~285 requests per minute
* ~5 requests per second
I think the object storage should easily be able to handle that, even if for some reason the CDN edge cache servers decided to request stuff themselves.
5 Minutes is OK for now - let's keep it simple in the first iteration. | 2020-05-27T19:29:49 | <patch>
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/ObjectStoreAccess.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/ObjectStoreAccess.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/ObjectStoreAccess.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/ObjectStoreAccess.java
@@ -20,19 +20,17 @@
package app.coronawarn.server.services.distribution.objectstore;
import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
-import app.coronawarn.server.services.distribution.config.DistributionServiceConfig.ObjectStore;
import app.coronawarn.server.services.distribution.objectstore.publish.LocalFile;
import io.minio.MinioClient;
import io.minio.PutObjectOptions;
import io.minio.Result;
-import io.minio.errors.InvalidEndpointException;
-import io.minio.errors.InvalidPortException;
import io.minio.errors.MinioException;
import io.minio.messages.DeleteError;
import io.minio.messages.Item;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
+import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@@ -58,7 +56,11 @@ public class ObjectStoreAccess {
private static final Logger logger = LoggerFactory.getLogger(ObjectStoreAccess.class);
- private static final String DEFAULT_REGION = "eu-west-1";
+ /**
+ * Specifies the default maximum amount of time in seconds that a published resource can be considered "fresh" when
+ * held in a cache.
+ */
+ public static final int DEFAULT_MAX_CACHE_AGE = 300;
private final boolean isSetPublicReadAclOnPutObject;
@@ -71,14 +73,14 @@ public class ObjectStoreAccess {
* bucket.
*
* @param distributionServiceConfig The config properties
+ * @param minioClient The client used for interaction with the object store
* @throws IOException When there were problems creating the S3 client
* @throws GeneralSecurityException When there were problems creating the S3 client
* @throws MinioException When there were problems creating the S3 client
*/
- ObjectStoreAccess(DistributionServiceConfig distributionServiceConfig)
+ ObjectStoreAccess(DistributionServiceConfig distributionServiceConfig, MinioClient minioClient)
throws IOException, GeneralSecurityException, MinioException {
- this.client = createClient(distributionServiceConfig.getObjectStore());
-
+ this.client = minioClient;
this.bucket = distributionServiceConfig.getObjectStore().getBucket();
this.isSetPublicReadAclOnPutObject = distributionServiceConfig.getObjectStore().isSetPublicReadAclOnPutObject();
@@ -87,38 +89,25 @@ public class ObjectStoreAccess {
}
}
- private MinioClient createClient(ObjectStore objectStore)
- throws InvalidPortException, InvalidEndpointException {
- if (isSsl(objectStore)) {
- return new MinioClient(
- objectStore.getEndpoint(),
- objectStore.getPort(),
- objectStore.getAccessKey(), objectStore.getSecretKey(),
- DEFAULT_REGION,
- true
- );
- } else {
- return new MinioClient(
- objectStore.getEndpoint(),
- objectStore.getPort(),
- objectStore.getAccessKey(), objectStore.getSecretKey()
- );
- }
- }
-
- private boolean isSsl(ObjectStore objectStore) {
- return objectStore.getEndpoint().startsWith("https://");
+ /**
+ * Stores the target file on the S3 and sets cache control headers according to the default maximum age value.
+ *
+ * @param localFile The file to be published.
+ */
+ public void putObject(LocalFile localFile) throws IOException, GeneralSecurityException, MinioException {
+ putObject(localFile, DEFAULT_MAX_CACHE_AGE);
}
/**
- * Stores the target file on the S3.
+ * Stores the target file on the S3 and sets cache control headers according to the specified maximum age value.
*
- * @param localFile the file to be published
+ * @param localFile The file to be published.
+ * @param maxAge A cache control parameter that specifies the maximum amount of time in seconds that a resource can
+ * be considered "fresh" when held in a cache.
*/
- public void putObject(LocalFile localFile)
- throws IOException, GeneralSecurityException, MinioException {
+ public void putObject(LocalFile localFile, int maxAge) throws IOException, GeneralSecurityException, MinioException {
String s3Key = localFile.getS3Key();
- PutObjectOptions options = createOptionsFor(localFile);
+ PutObjectOptions options = createOptionsFor(localFile, maxAge);
logger.info("... uploading {}", s3Key);
this.client.putObject(bucket, s3Key, localFile.getFile().toString(), options);
@@ -167,12 +156,14 @@ public List<S3Object> getObjectsWithPrefix(String prefix)
return list;
}
- private PutObjectOptions createOptionsFor(LocalFile file) {
+ private PutObjectOptions createOptionsFor(LocalFile file, int maxAge) {
var options = new PutObjectOptions(file.getFile().toFile().length(), -1);
+ Map<String, String> headers = new HashMap<>(Map.of("cache-control", "public,max-age=" + maxAge));
if (this.isSetPublicReadAclOnPutObject) {
- options.setHeaders(Map.of("x-amz-acl", "public-read"));
+ headers.put("x-amz-acl", "public-read");
}
+ options.setHeaders(headers);
return options;
}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/ObjectStoreClientConfig.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/ObjectStoreClientConfig.java
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/ObjectStoreClientConfig.java
@@ -0,0 +1,66 @@
+/*
+ * Corona-Warn-App
+ *
+ * SAP SE and all other contributors /
+ * copyright owners license this file to you under the Apache
+ * License, Version 2.0 (the "License"); you may not use this
+ * file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://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 for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package app.coronawarn.server.services.distribution.objectstore;
+
+import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
+import app.coronawarn.server.services.distribution.config.DistributionServiceConfig.ObjectStore;
+import io.minio.MinioClient;
+import io.minio.errors.InvalidEndpointException;
+import io.minio.errors.InvalidPortException;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+/**
+ * Manages the instantiation of the {@link MinioClient} bean.
+ */
+@Configuration
+public class ObjectStoreClientConfig {
+
+ private static final String DEFAULT_REGION = "eu-west-1";
+
+ @Bean
+ public MinioClient createMinioClient(DistributionServiceConfig distributionServiceConfig)
+ throws InvalidPortException, InvalidEndpointException {
+ return createClient(distributionServiceConfig.getObjectStore());
+ }
+
+ private MinioClient createClient(ObjectStore objectStore)
+ throws InvalidPortException, InvalidEndpointException {
+ if (isSsl(objectStore)) {
+ return new MinioClient(
+ objectStore.getEndpoint(),
+ objectStore.getPort(),
+ objectStore.getAccessKey(), objectStore.getSecretKey(),
+ DEFAULT_REGION,
+ true
+ );
+ } else {
+ return new MinioClient(
+ objectStore.getEndpoint(),
+ objectStore.getPort(),
+ objectStore.getAccessKey(), objectStore.getSecretKey()
+ );
+ }
+ }
+
+ private boolean isSsl(ObjectStore objectStore) {
+ return objectStore.getEndpoint().startsWith("https://");
+ }
+}
</patch> | diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/ObjectStoreAccessUnitTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/ObjectStoreAccessUnitTest.java
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/ObjectStoreAccessUnitTest.java
@@ -0,0 +1,113 @@
+/*
+ * Corona-Warn-App
+ *
+ * SAP SE and all other contributors /
+ * copyright owners license this file to you under the Apache
+ * License, Version 2.0 (the "License"); you may not use this
+ * file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://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 for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package app.coronawarn.server.services.distribution.objectstore;
+
+import static java.util.Map.entry;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.any;
+import static org.mockito.Mockito.atLeastOnce;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
+import app.coronawarn.server.services.distribution.objectstore.publish.LocalFile;
+import io.minio.MinioClient;
+import io.minio.PutObjectOptions;
+import java.io.File;
+import java.nio.file.Path;
+import org.assertj.core.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.ArgumentCaptor;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.context.properties.EnableConfigurationProperties;
+import org.springframework.boot.test.context.ConfigFileApplicationContextInitializer;
+import org.springframework.boot.test.mock.mockito.MockBean;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit.jupiter.SpringExtension;
+
+@EnableConfigurationProperties(value = DistributionServiceConfig.class)
+@ExtendWith(SpringExtension.class)
+@ContextConfiguration(classes = {MinioClient.class}, initializers = ConfigFileApplicationContextInitializer.class)
+class ObjectStoreAccessUnitTest {
+
+ private static final String EXP_S3_KEY = "fooS3Key";
+ private static final String EXP_FILE_CONTENT = "barFileContent";
+
+ private final DistributionServiceConfig distributionServiceConfig;
+ private final String expBucketName;
+ private LocalFile testLocalFile;
+ private ObjectStoreAccess objectStoreAccess;
+
+ @MockBean
+ private MinioClient minioClient;
+
+ @Autowired
+ public ObjectStoreAccessUnitTest(DistributionServiceConfig distributionServiceConfig) {
+ this.distributionServiceConfig = distributionServiceConfig;
+ this.expBucketName = distributionServiceConfig.getObjectStore().getBucket();
+ }
+
+ @BeforeEach
+ public void setUpMocks() throws Exception {
+ when(minioClient.bucketExists(any())).thenReturn(true);
+ this.objectStoreAccess = new ObjectStoreAccess(distributionServiceConfig, minioClient);
+ this.testLocalFile = setUpLocalFileMock();
+ }
+
+ private LocalFile setUpLocalFileMock() {
+ var testLocalFile = mock(LocalFile.class);
+ var testPath = mock(Path.class);
+
+ when(testLocalFile.getS3Key()).thenReturn(EXP_S3_KEY);
+ when(testLocalFile.getFile()).thenReturn(testPath);
+ when(testPath.toFile()).thenReturn(mock(File.class));
+ when(testPath.toString()).thenReturn(EXP_FILE_CONTENT);
+
+ return testLocalFile;
+ }
+
+ @Test
+ void testPutObjectSetsDefaultCacheControlHeader() throws Exception {
+ ArgumentCaptor<PutObjectOptions> options = ArgumentCaptor.forClass(PutObjectOptions.class);
+ var expHeader = entry("cache-control", "public,max-age=" + ObjectStoreAccess.DEFAULT_MAX_CACHE_AGE);
+
+ objectStoreAccess.putObject(testLocalFile);
+
+ verify(minioClient, atLeastOnce())
+ .putObject(eq(expBucketName), eq(EXP_S3_KEY), eq(EXP_FILE_CONTENT), options.capture());
+ Assertions.assertThat(options.getValue().headers()).contains(expHeader);
+ }
+
+ @Test
+ void testPutObjectSetsSpecifiedCacheControlHeader() throws Exception {
+ ArgumentCaptor<PutObjectOptions> options = ArgumentCaptor.forClass(PutObjectOptions.class);
+ var expMaxAge = 1337;
+ var expHeader = entry("cache-control", "public,max-age=" + expMaxAge);
+
+ objectStoreAccess.putObject(testLocalFile, expMaxAge);
+
+ verify(minioClient, atLeastOnce())
+ .putObject(eq(expBucketName), eq(EXP_S3_KEY), eq(EXP_FILE_CONTENT), options.capture());
+ Assertions.assertThat(options.getValue().headers()).contains(expHeader);
+ }
+}
| ||||
corona-warn-app__cwa-server-431 | You will be provided with a partial code base and an issue statement explaining a problem to resolve.
<issue>
Application Configuration: Attenuation Duration
The RKI requested weighting parameters for the three buckets defined by the attenuation duration threshold. Add this to the attenuation duration configuration.
@michael-burwig
```yaml
attenuation-duration:
thresholds:
lower: 50
upper: 70
weights:
low: 1 # attenuation < 50 dB
mid: 0.5 # attenuation >50 dB && < 70 dB
high: 0 # attenuation > 70dB is ignored
```
</issue>
<code>
[start of README.md]
1 <!-- markdownlint-disable MD041 -->
2 <h1 align="center">
3 Corona-Warn-App Server
4 </h1>
5
6 <p align="center">
7 <a href="https://github.com/corona-warn-app/cwa-server/commits/" title="Last Commit"><img src="https://img.shields.io/github/last-commit/corona-warn-app/cwa-server?style=flat"></a>
8 <a href="https://github.com/corona-warn-app/cwa-server/issues" title="Open Issues"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat"></a>
9 <a href="https://circleci.com/gh/corona-warn-app/cwa-server" title="Build Status"><img src="https://circleci.com/gh/corona-warn-app/cwa-server.svg?style=shield&circle-token=4ab059989d10709df19eb4b98ab7c121a25e981a"></a>
10 <a href="https://sonarcloud.io/dashboard?id=corona-warn-app_cwa-server" title="Quality Gate"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=alert_status"></a>
11 <a href="https://sonarcloud.io/component_measures?id=corona-warn-app_cwa-server&metric=Coverage&view=list" title="Coverage"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=coverage"></a>
12 <a href="https://github.com/corona-warn-app/cwa-server/blob/master/LICENSE" title="License"><img src="https://img.shields.io/badge/License-Apache%202.0-green.svg?style=flat"></a>
13 </p>
14
15 <p align="center">
16 <a href="#development">Development</a> •
17 <a href="#service-apis">Service APIs</a> •
18 <a href="#documentation">Documentation</a> •
19 <a href="#support-and-feedback">Support</a> •
20 <a href="#how-to-contribute">Contribute</a> •
21 <a href="#contributors">Contributors</a> •
22 <a href="#repositories">Repositories</a> •
23 <a href="#licensing">Licensing</a>
24 </p>
25
26 The goal of this project is to develop the official Corona-Warn-App for Germany based on the exposure notification API from [Apple](https://www.apple.com/covid19/contacttracing/) and [Google](https://www.google.com/covid19/exposurenotifications/). The apps (for both iOS and Android) use Bluetooth technology to exchange anonymous encrypted data with other mobile phones (on which the app is also installed) in the vicinity of an app user's phone. The data is stored locally on each user's device, preventing authorities or other parties from accessing or controlling the data. This repository contains the **implementation of the server for encryption keys** for the Corona-Warn-App. This implementation is still a **work in progress**, and the code it contains is currently alpha-quality code.
27
28 In this documentation, Corona-Warn-App services are also referred to as CWA services.
29
30 ## Architecture Overview
31
32 You can find the architecture overview [here](/docs/architecture-overview.md), which will give you
33 a good starting point in how the backend services interact with other services, and what purpose
34 they serve.
35
36 ## Development
37
38 After you've checked out this repository, you can run the application in one of the following ways:
39
40 * As a [Docker](https://www.docker.com/)-based deployment on your local machine. You can run either:
41 * Single components using the respective Dockerfile or
42 * The full backend using the Docker Compose (which is considered the most convenient way)
43 * As a [Maven](https://maven.apache.org)-based build on your local machine.
44 If you want to develop something in a single component, this approach is preferable.
45
46 ### Docker-Based Deployment
47
48 If you want to use Docker-based deployment, you need to install Docker on your local machine. For more information about downloading and installing Docker, see the [official Docker documentation](https://docs.docker.com/get-docker/).
49
50 #### Running the Full CWA Backend Using Docker Compose
51
52 For your convenience, a full setup including the generation of test data has been prepared using [Docker Compose](https://docs.docker.com/compose/reference/overview/). To build the backend services, run ```docker-compose build``` in the repository's root directory. A default configuration file can be found under ```.env```in the root folder of the repository. The default values for the local Postgres and Zenko Cloudserver should be changed in this file before docker-compose is run.
53
54 Once the services are built, you can start the whole backend using ```docker-compose up```.
55 The distribution service runs once and then finishes. If you want to trigger additional distribution runs, run ```docker-compose run distribution```.
56
57 The docker-compose contains the following services:
58
59 Service | Description | Endpoint and Default Credentials
60 ------------------|-------------|-----------
61 submission | The Corona-Warn-App submission service | `http://localhost:8000` <br> `http://localhost:8006` (for actuator endpoint)
62 distribution | The Corona-Warn-App distribution service | NO ENDPOINT
63 postgres | A [postgres] database installation | `postgres:8001` <br> Username: postgres <br> Password: postgres
64 pgadmin | A [pgadmin](https://www.pgadmin.org/) installation for the postgres database | `http://localhost:8002` <br> Username: [email protected] <br> Password: password
65 cloudserver | [Zenko CloudServer] is a S3-compliant object store | `http://localhost:8003/` <br> Access key: accessKey1 <br> Secret key: verySecretKey1
66 verification-fake | A very simple fake implementation for the tan verification. | `http://localhost:8004/version/v1/tan/verify` <br> The only valid tan is "edc07f08-a1aa-11ea-bb37-0242ac130002"
67
68 ##### Known Limitation
69
70 In rare cases the docker-compose runs into a timing issue if the distribution service starts before the bucket of the objectstore was created. This is not a big issue as you can simply run ```docker-compose run distribution``` to trigger additional distribution runs after the objectstore was initialized.
71
72 #### Running Single CWA Services Using Docker
73
74 If you would like to build and run a single CWA service, it's considered easiest to run them in a Docker environment. You can do this using the script provided in the respective CWA service directory. The Docker script first builds the CWA service and then creates an image for the runtime, which means that there are no additional dependencies for you to install.
75
76 To build and run the distribution service, run the following command:
77
78 ```bash
79 ./services/distribution/build_and_run.sh
80 ```
81
82 To build and run the submission service, run the following command:
83
84 ```bash
85 ./services/submission/build_and_run.sh
86 ```
87
88 The submission service is available on [localhost:8080](http://localhost:8080 ).
89
90 ### Maven-Based Build
91
92 If you want to actively develop in one of the CWA services, the Maven-based runtime is most suitable.
93 To prepare your machine to run the CWA project locally, we recommend that you first ensure that you've installed the following:
94
95 * Minimum JDK Version 11: [OpenJDK](https://openjdk.java.net/) / [SapMachine](https://sap.github.io/SapMachine/)
96 * [Maven 3.6](https://maven.apache.org/)
97 * [Postgres]
98 * [Zenko CloudServer]
99
100 #### Configure
101
102 After you made sure that the specified dependencies are running, configure them in the respective configuration files.
103
104 * Configure the Postgres connection in the [submission config](./services/submission/src/main/resources/application.yaml) and in the [distribution config](./services/distribution/src/main/resources/application.yaml)
105 * Configure the S3 compatible object storage in the [distribution config](./services/distribution/src/main/resources/application.yaml)
106 * Configure the private key for the distribution service, the path need to be prefixed with `file:`
107 * `VAULT_FILESIGNING_SECRET` should be the path to the private key, example available in `<repo-root>/docker-compose-test-secrets/private.pem`
108
109 #### Build
110
111 After you've checked out the repository, to build the project, run ```mvn install``` in your base directory.
112
113 #### Run
114
115 Navigate to the service you want to start and run the spring-boot:run target. The configured Postgres and the configured S3 compliant object storage are used as default. When you start the submission service, the endpoint is available on your local port 8080.
116
117 If you want to start the submission service, for example, you start it as follows:
118
119 ```bash
120 cd services/submission/
121 mvn spring-boot:run
122 ```
123
124 #### Debugging
125
126 To enable the `DEBUG` log level, you can run the application using the Spring `dev` profile.
127
128 ```bash
129 mvn spring-boot:run -Dspring-boot.run.profiles=dev
130 ```
131
132 To be able to set breakpoints (e.g. in IntelliJ), it may be necessary to use the ```-Dspring-boot.run.fork=false``` parameter.
133
134 ## Service APIs
135
136 The API that is being exposed by the backend services is documented in an [OpenAPI](https://www.openapis.org/) specification. The specification files are available at the following locations:
137
138 Service | OpenAPI Specification
139 -------------|-------------
140 Submission Service | [services/submission/api_v1.json](https://github.com/corona-warn-app/cwa-server/raw/master/services/submission/api_v1.json)
141 Distribution Service | [services/distribution/api_v1.json](https://github.com/corona-warn-app/cwa-server/raw/master/services/distribution/api_v1.json)
142
143 ## Spring Profiles
144
145 ### Distribution
146
147 Profile | Effect
148 -----------------|-------------
149 `dev` | Turns the log level to `DEBUG`.
150 `cloud` | Removes default values for the `datasource` and `objectstore` configurations.
151 `demo` | Includes incomplete days and hours into the distribution run, thus creating aggregates for the current day and the current hour (and including both in the respective indices). When running multiple distributions in one hour with this profile, the date aggregate for today and the hours aggregate for the current hour will be updated and overwritten. This profile also turns off the expiry policy (Keys must be expired for at least 2 hours before distribution) and the shifting policy (there must be at least 140 keys in a distribution).
152 `testdata` | Causes test data to be inserted into the database before each distribution run. By default, around 1000 random diagnosis keys will be generated per hour. If there are no diagnosis keys in the database yet, random keys will be generated for every hour from the beginning of the retention period (14 days ago at 00:00 UTC) until one hour before the present hour. If there are already keys in the database, the random keys will be generated for every hour from the latest diagnosis key in the database (by submission timestamp) until one hour before the present hour (or none at all, if the latest diagnosis key in the database was submitted one hour ago or later).
153 `signature-dev` | Sets the app package ID in the export packages' signature info to `de.rki.coronawarnapp-dev` so that test certificates (instead of production certificates) will be used for client-side validation.
154 `signature-prod` | Provides production app package IDs for the signature info
155
156 ### Submission
157
158 Profile | Effect
159 -------------|-------------
160 `dev` | Turns the log level to `DEBUG`.
161 `cloud` | Removes default values for the `datasource` configuration.
162
163 ## Documentation
164
165 The full documentation for the Corona-Warn-App can be found in the [cwa-documentation](https://github.com/corona-warn-app/cwa-documentation) repository. The documentation repository contains technical documents, architecture information, and whitepapers related to this implementation.
166
167 ## Support and Feedback
168
169 The following channels are available for discussions, feedback, and support requests:
170
171 | Type | Channel |
172 | ------------------------ | ------------------------------------------------------ |
173 | **General Discussion** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="General Discussion"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/question.svg?style=flat-square"></a> </a> |
174 | **Concept Feedback** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="Open Concept Feedback"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/architecture.svg?style=flat-square"></a> |
175 | **Backend Issue** | <a href="https://github.com/corona-warn-app/cwa-server/issues/new/choose" title="Open Backend Issue"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat-square"></a> |
176 | **Other Requests** | <a href="mailto:[email protected]" title="Email CWA Team"><img src="https://img.shields.io/badge/email-CWA%20team-green?logo=mail.ru&style=flat-square&logoColor=white"></a> |
177
178 ## How to Contribute
179
180 Contribution and feedback are 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.
181
182 ## Contributors
183
184 The German government has asked SAP and Deutsche Telekom to develop the Corona-Warn-App for Germany as open source software. Deutsche Telekom is providing the network and mobile technology and will operate and run the backend for the app in a safe, scalable and stable manner. SAP is responsible for the app development, its framework and the underlying platform. Therefore, development teams of SAP and Deutsche Telekom are contributing to this project. At the same time 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.
185
186 ## Repositories
187
188 The following public repositories are currently available for the Corona-Warn-App:
189
190 | Repository | Description |
191 | ------------------- | --------------------------------------------------------------------- |
192 | [cwa-documentation] | Project overview, general documentation, and white papers |
193 | [cwa-server] | Backend implementation for the Apple/Google exposure notification API|
194 | [cwa-verification-server] | Backend implementation of the verification process|
195
196 [cwa-documentation]: https://github.com/corona-warn-app/cwa-documentation
197 [cwa-server]: https://github.com/corona-warn-app/cwa-server
198 [cwa-verification-server]: https://github.com/corona-warn-app/cwa-verification-server
199 [Postgres]: https://www.postgresql.org/
200 [HSQLDB]: http://hsqldb.org/
201 [Zenko CloudServer]: https://github.com/scality/cloudserver
202
203 ## Licensing
204
205 Copyright (c) 2020 SAP SE or an SAP affiliate company.
206
207 Licensed under the **Apache License, Version 2.0** (the "License"); you may not use this file except in compliance with the License.
208
209 You may obtain a copy of the License at <https://www.apache.org/licenses/LICENSE-2.0>.
210
211 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.
212
[end of README.md]
[start of /dev/null]
1
[end of /dev/null]
[start of common/protocols/src/main/proto/app/coronawarn/server/common/protocols/internal/app_config.proto]
1 syntax = "proto3";
2 package app.coronawarn.server.common.protocols.internal;
3 option java_package = "app.coronawarn.server.common.protocols.internal";
4 option java_multiple_files = true;
5 import "app/coronawarn/server/common/protocols/internal/risk_score_classification.proto";
6 import "app/coronawarn/server/common/protocols/internal/risk_score_parameters.proto";
7 import "app/coronawarn/server/common/protocols/internal/app_version_config.proto";
8
9 message ApplicationConfiguration {
10
11 int32 minRiskScore = 1;
12
13 app.coronawarn.server.common.protocols.internal.RiskScoreClassification riskScoreClasses = 2;
14
15 app.coronawarn.server.common.protocols.internal.RiskScoreParameters exposureConfig = 3;
16
17 AttenuationDurationThresholds attenuationDurationThresholds = 4;
18
19 app.coronawarn.server.common.protocols.internal.ApplicationVersionConfiguration appVersion = 5;
20 }
21
22 message AttenuationDurationThresholds {
23 int32 lower = 1;
24 int32 upper = 2;
25 }
[end of common/protocols/src/main/proto/app/coronawarn/server/common/protocols/internal/app_config.proto]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ApplicationConfigurationValidator.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.distribution.assembly.appconfig.validation;
22
23 import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.GeneralValidationError.ErrorType.MIN_GREATER_THAN_MAX;
24 import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.GeneralValidationError.ErrorType.VALUE_OUT_OF_BOUNDS;
25 import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.ParameterSpec.ATTENUATION_DURATION_THRESHOLD_MAX;
26 import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.ParameterSpec.ATTENUATION_DURATION_THRESHOLD_MIN;
27
28 import app.coronawarn.server.common.protocols.internal.ApplicationConfiguration;
29 import app.coronawarn.server.common.protocols.internal.RiskScoreClassification;
30 import app.coronawarn.server.common.protocols.internal.RiskScoreParameters;
31
32 /**
33 * This validator validates a {@link ApplicationConfiguration}. It will re-use the {@link ConfigurationValidator} from
34 * the sub-configurations of {@link RiskScoreParameters} and {@link RiskScoreClassification}.
35 */
36 public class ApplicationConfigurationValidator extends ConfigurationValidator {
37
38 private final ApplicationConfiguration config;
39
40 /**
41 * Creates a new instance for the given {@link ApplicationConfiguration}.
42 *
43 * @param config the Application Configuration to validate.
44 */
45 public ApplicationConfigurationValidator(ApplicationConfiguration config) {
46 this.config = config;
47 }
48
49 @Override
50 public ValidationResult validate() {
51 this.errors = new ValidationResult();
52
53 validateMinRisk();
54 validateAttenuationDurationThresholds();
55
56 ValidationResult exposureResult = new ExposureConfigurationValidator(config.getExposureConfig()).validate();
57 ValidationResult riskScoreResult = new RiskScoreClassificationValidator(config.getRiskScoreClasses()).validate();
58
59 return errors.with(exposureResult).with(riskScoreResult);
60 }
61
62 private void validateMinRisk() {
63 int minLevel = this.config.getMinRiskScore();
64
65 if (!RiskScoreValidator.isInBounds(minLevel)) {
66 this.errors.add(new MinimumRiskLevelValidationError(minLevel));
67 }
68 }
69
70 private void validateAttenuationDurationThresholds() {
71 int lower = config.getAttenuationDurationThresholds().getLower();
72 int upper = config.getAttenuationDurationThresholds().getUpper();
73
74 checkThresholdBound("lower", lower);
75 checkThresholdBound("upper", upper);
76
77 if (lower > upper) {
78 String parameters = "attenuationDurationThreshold.lower, attenuationDurationThreshold.upper";
79 String values = lower + ", " + upper;
80 this.errors.add(new GeneralValidationError(parameters, values, MIN_GREATER_THAN_MAX));
81 }
82 }
83
84 private void checkThresholdBound(String boundLabel, int boundValue) {
85 if (boundValue < ATTENUATION_DURATION_THRESHOLD_MIN || boundValue > ATTENUATION_DURATION_THRESHOLD_MAX) {
86 this.errors.add(
87 new GeneralValidationError("attenuationDurationThreshold." + boundLabel, boundValue, VALUE_OUT_OF_BOUNDS));
88 }
89 }
90 }
91
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ApplicationConfigurationValidator.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ParameterSpec.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.distribution.assembly.appconfig.validation;
22
23 /**
24 * Definition of the spec according to Apple/Google:
25 * https://developer.apple.com/documentation/exposurenotification/enexposureconfiguration
26 */
27 public class ParameterSpec {
28
29 private ParameterSpec() {
30 }
31
32 /**
33 * The minimum weight value for mobile API.
34 */
35 public static final double WEIGHT_MIN = 0.001;
36
37 /**
38 * The maximum weight value for mobile API.
39 */
40 public static final int WEIGHT_MAX = 100;
41
42 /**
43 * Maximum number of allowed decimals.
44 */
45 public static final int WEIGHT_MAX_DECIMALS = 3;
46
47 /**
48 * The allowed minimum value for risk score.
49 */
50 public static final int RISK_SCORE_MIN = 0;
51
52 /**
53 * The allowed maximum value for a risk score.
54 */
55 public static final int RISK_SCORE_MAX = 4096;
56
57 /**
58 * The allowed minimum value for an attenuation threshold.
59 */
60 public static final int ATTENUATION_DURATION_THRESHOLD_MIN = 0;
61
62 /**
63 * The allowed maximum value for an attenuation threshold.
64 */
65 public static final int ATTENUATION_DURATION_THRESHOLD_MAX = 100;
66 }
67
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ParameterSpec.java]
[start of services/distribution/src/main/resources/master-config/app-config.yaml]
1 #----------------------------------------------------------------------
2 # This is the Corona Warn App master configuration file.
3 # ----------------------------------------------------------------------
4 #
5 # This configuration file will be fetched by the mobile app in order to function.
6 #
7 # It currently provides settings for minimum risk score, score classes and exposure configuration.
8 #
9 # Change this file with caution!
10
11 min-risk-score: 90
12 attenuationDurationThresholds:
13 lower: 50
14 upper: 70
15 risk-score-classes: !include risk-score-classification.yaml
16 exposure-config: !include exposure-config.yaml
17 app-version: !include app-version-config.yaml
[end of services/distribution/src/main/resources/master-config/app-config.yaml]
</code>
Here is an example of a patch file. It consists of changes to the code base. It specifies the file names, the line numbers of each change, and the removed and added lines. A single patch file can contain changes to multiple files.
<patch>
--- a/file.py
+++ b/file.py
@@ -1,27 +1,35 @@
def euclidean(a, b):
- while b:
- a, b = b, a % b
- return a
+ if b == 0:
+ return a
+ return euclidean(b, a % b)
def bresenham(x0, y0, x1, y1):
points = []
dx = abs(x1 - x0)
dy = abs(y1 - y0)
- sx = 1 if x0 < x1 else -1
- sy = 1 if y0 < y1 else -1
- err = dx - dy
+ x, y = x0, y0
+ sx = -1 if x0 > x1 else 1
+ sy = -1 if y0 > y1 else 1
- while True:
- points.append((x0, y0))
- if x0 == x1 and y0 == y1:
- break
- e2 = 2 * err
- if e2 > -dy:
+ if dx > dy:
+ err = dx / 2.0
+ while x != x1:
+ points.append((x, y))
err -= dy
- x0 += sx
- if e2 < dx:
- err += dx
- y0 += sy
+ if err < 0:
+ y += sy
+ err += dx
+ x += sx
+ else:
+ err = dy / 2.0
+ while y != y1:
+ points.append((x, y))
+ err -= dx
+ if err < 0:
+ x += sx
+ err += dy
+ y += sy
+ points.append((x, y))
return points
</patch>
I need you to solve the provded issue by generating a single patch file that I can apply directly to this repository using git apply. Please respond with a single patch file in the format shown above.
Respond below:
| corona-warn-app/cwa-server | 20492aaed28176142700486f99877b602b9f1cde | Application Configuration: Attenuation Duration
The RKI requested weighting parameters for the three buckets defined by the attenuation duration threshold. Add this to the attenuation duration configuration.
@michael-burwig
```yaml
attenuation-duration:
thresholds:
lower: 50
upper: 70
weights:
low: 1 # attenuation < 50 dB
mid: 0.5 # attenuation >50 dB && < 70 dB
high: 0 # attenuation > 70dB is ignored
```
| Are the weights in the range of [0, 1]?
Is the threshold value range still [0, 100]?
Thresholds remain unchanged.
For weight, lets go with 0...1 for now. There will be another RKI call in the afternoon which might change that though. | 2020-06-03T09:23:16 | <patch>
diff --git a/common/protocols/src/main/proto/app/coronawarn/server/common/protocols/internal/app_config.proto b/common/protocols/src/main/proto/app/coronawarn/server/common/protocols/internal/app_config.proto
--- a/common/protocols/src/main/proto/app/coronawarn/server/common/protocols/internal/app_config.proto
+++ b/common/protocols/src/main/proto/app/coronawarn/server/common/protocols/internal/app_config.proto
@@ -5,6 +5,7 @@ option java_multiple_files = true;
import "app/coronawarn/server/common/protocols/internal/risk_score_classification.proto";
import "app/coronawarn/server/common/protocols/internal/risk_score_parameters.proto";
import "app/coronawarn/server/common/protocols/internal/app_version_config.proto";
+import "app/coronawarn/server/common/protocols/internal/attenuation_duration.proto";
message ApplicationConfiguration {
@@ -14,12 +15,7 @@ message ApplicationConfiguration {
app.coronawarn.server.common.protocols.internal.RiskScoreParameters exposureConfig = 3;
- AttenuationDurationThresholds attenuationDurationThresholds = 4;
+ app.coronawarn.server.common.protocols.internal.AttenuationDuration attenuationDuration = 4;
app.coronawarn.server.common.protocols.internal.ApplicationVersionConfiguration appVersion = 5;
}
-
-message AttenuationDurationThresholds {
- int32 lower = 1;
- int32 upper = 2;
-}
\ No newline at end of file
diff --git a/common/protocols/src/main/proto/app/coronawarn/server/common/protocols/internal/attenuation_duration.proto b/common/protocols/src/main/proto/app/coronawarn/server/common/protocols/internal/attenuation_duration.proto
new file mode 100644
--- /dev/null
+++ b/common/protocols/src/main/proto/app/coronawarn/server/common/protocols/internal/attenuation_duration.proto
@@ -0,0 +1,20 @@
+syntax = "proto3";
+package app.coronawarn.server.common.protocols.internal;
+option java_package = "app.coronawarn.server.common.protocols.internal";
+option java_multiple_files = true;
+
+message AttenuationDuration {
+ Thresholds thresholds = 1;
+ Weights weights = 2;
+}
+
+message Thresholds {
+ int32 lower = 1;
+ int32 upper = 2;
+}
+
+message Weights {
+ double low = 1;
+ double mid = 2;
+ double high = 3;
+}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ApplicationConfigurationValidator.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ApplicationConfigurationValidator.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ApplicationConfigurationValidator.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ApplicationConfigurationValidator.java
@@ -20,11 +20,6 @@
package app.coronawarn.server.services.distribution.assembly.appconfig.validation;
-import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.GeneralValidationError.ErrorType.MIN_GREATER_THAN_MAX;
-import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.GeneralValidationError.ErrorType.VALUE_OUT_OF_BOUNDS;
-import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.ParameterSpec.ATTENUATION_DURATION_THRESHOLD_MAX;
-import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.ParameterSpec.ATTENUATION_DURATION_THRESHOLD_MIN;
-
import app.coronawarn.server.common.protocols.internal.ApplicationConfiguration;
import app.coronawarn.server.common.protocols.internal.RiskScoreClassification;
import app.coronawarn.server.common.protocols.internal.RiskScoreParameters;
@@ -51,12 +46,13 @@ public ValidationResult validate() {
this.errors = new ValidationResult();
validateMinRisk();
- validateAttenuationDurationThresholds();
- ValidationResult exposureResult = new ExposureConfigurationValidator(config.getExposureConfig()).validate();
- ValidationResult riskScoreResult = new RiskScoreClassificationValidator(config.getRiskScoreClasses()).validate();
+ errors.with(new ExposureConfigurationValidator(config.getExposureConfig()).validate());
+ errors.with(new RiskScoreClassificationValidator(config.getRiskScoreClasses()).validate());
+ errors.with(new ApplicationVersionConfigurationValidator(config.getAppVersion()).validate());
+ errors.with(new AttenuationDurationValidator(config.getAttenuationDuration()).validate());
- return errors.with(exposureResult).with(riskScoreResult);
+ return errors;
}
private void validateMinRisk() {
@@ -66,25 +62,4 @@ private void validateMinRisk() {
this.errors.add(new MinimumRiskLevelValidationError(minLevel));
}
}
-
- private void validateAttenuationDurationThresholds() {
- int lower = config.getAttenuationDurationThresholds().getLower();
- int upper = config.getAttenuationDurationThresholds().getUpper();
-
- checkThresholdBound("lower", lower);
- checkThresholdBound("upper", upper);
-
- if (lower > upper) {
- String parameters = "attenuationDurationThreshold.lower, attenuationDurationThreshold.upper";
- String values = lower + ", " + upper;
- this.errors.add(new GeneralValidationError(parameters, values, MIN_GREATER_THAN_MAX));
- }
- }
-
- private void checkThresholdBound(String boundLabel, int boundValue) {
- if (boundValue < ATTENUATION_DURATION_THRESHOLD_MIN || boundValue > ATTENUATION_DURATION_THRESHOLD_MAX) {
- this.errors.add(
- new GeneralValidationError("attenuationDurationThreshold." + boundLabel, boundValue, VALUE_OUT_OF_BOUNDS));
- }
- }
}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/AttenuationDurationValidator.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/AttenuationDurationValidator.java
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/AttenuationDurationValidator.java
@@ -0,0 +1,94 @@
+/*-
+ * ---license-start
+ * Corona-Warn-App
+ * ---
+ * Copyright (C) 2020 SAP SE and all other contributors
+ * ---
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://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 for the specific language governing permissions and
+ * limitations under the License.
+ * ---license-end
+ */
+
+package app.coronawarn.server.services.distribution.assembly.appconfig.validation;
+
+import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.GeneralValidationError.ErrorType.MIN_GREATER_THAN_MAX;
+import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.GeneralValidationError.ErrorType.VALUE_OUT_OF_BOUNDS;
+import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.ParameterSpec.ATTENUATION_DURATION_THRESHOLD_MAX;
+import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.ParameterSpec.ATTENUATION_DURATION_THRESHOLD_MIN;
+import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.ParameterSpec.ATTENUATION_DURATION_WEIGHT_MAX;
+import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.ParameterSpec.ATTENUATION_DURATION_WEIGHT_MIN;
+import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.WeightValidationError.ErrorType.OUT_OF_RANGE;
+import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.WeightValidationError.ErrorType.TOO_MANY_DECIMAL_PLACES;
+
+import app.coronawarn.server.common.protocols.internal.AttenuationDuration;
+import java.math.BigDecimal;
+
+/**
+ * The AttenuationDurationValidator validates the values of an associated {@link AttenuationDuration} instance.
+ */
+public class AttenuationDurationValidator extends ConfigurationValidator {
+
+ private final AttenuationDuration attenuationDuration;
+
+ public AttenuationDurationValidator(AttenuationDuration attenuationDuration) {
+ this.attenuationDuration = attenuationDuration;
+ }
+
+ @Override
+ public ValidationResult validate() {
+ errors = new ValidationResult();
+
+ validateThresholds();
+ validateWeights();
+
+ return errors;
+ }
+
+ private void validateThresholds() {
+ int lower = attenuationDuration.getThresholds().getLower();
+ int upper = attenuationDuration.getThresholds().getUpper();
+
+ checkThresholdBound("lower", lower);
+ checkThresholdBound("upper", upper);
+
+ if (lower > upper) {
+ String parameters = "attenuation-duration.thresholds.lower, attenuation-duration.thresholds.upper";
+ String values = lower + ", " + upper;
+ this.errors.add(new GeneralValidationError(parameters, values, MIN_GREATER_THAN_MAX));
+ }
+ }
+
+ private void checkThresholdBound(String thresholdLabel, int thresholdValue) {
+ if (thresholdValue < ATTENUATION_DURATION_THRESHOLD_MIN || thresholdValue > ATTENUATION_DURATION_THRESHOLD_MAX) {
+ this.errors.add(new GeneralValidationError(
+ "attenuation-duration.thresholds." + thresholdLabel, thresholdValue, VALUE_OUT_OF_BOUNDS));
+ }
+ }
+
+ private void validateWeights() {
+ checkWeight("low", attenuationDuration.getWeights().getLow());
+ checkWeight("mid", attenuationDuration.getWeights().getMid());
+ checkWeight("high", attenuationDuration.getWeights().getHigh());
+ }
+
+ private void checkWeight(String weightLabel, double weightValue) {
+ if (weightValue < ATTENUATION_DURATION_WEIGHT_MIN || weightValue > ATTENUATION_DURATION_WEIGHT_MAX) {
+ this.errors.add(new WeightValidationError(
+ "attenuation-duration.weights." + weightLabel, weightValue, OUT_OF_RANGE));
+ }
+
+ if (BigDecimal.valueOf(weightValue).scale() > ParameterSpec.ATTENUATION_DURATION_WEIGHT_MAX_DECIMALS) {
+ this.errors.add(new WeightValidationError(
+ "attenuation-duration.weights." + weightLabel, weightValue, TOO_MANY_DECIMAL_PLACES));
+ }
+ }
+}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ParameterSpec.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ParameterSpec.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ParameterSpec.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ParameterSpec.java
@@ -63,4 +63,19 @@ private ParameterSpec() {
* The allowed maximum value for an attenuation threshold.
*/
public static final int ATTENUATION_DURATION_THRESHOLD_MAX = 100;
+
+ /**
+ * The allowed minimum value for an attenuation weight.
+ */
+ public static final double ATTENUATION_DURATION_WEIGHT_MIN = .0;
+
+ /**
+ * The allowed maximum value for an attenuation weight.
+ */
+ public static final double ATTENUATION_DURATION_WEIGHT_MAX = 1.;
+
+ /**
+ * Maximum number of allowed decimals for an attenuation weight.
+ */
+ public static final int ATTENUATION_DURATION_WEIGHT_MAX_DECIMALS = 3;
}
diff --git a/services/distribution/src/main/resources/master-config/app-config.yaml b/services/distribution/src/main/resources/master-config/app-config.yaml
--- a/services/distribution/src/main/resources/master-config/app-config.yaml
+++ b/services/distribution/src/main/resources/master-config/app-config.yaml
@@ -9,9 +9,7 @@
# Change this file with caution!
min-risk-score: 90
-attenuationDurationThresholds:
- lower: 50
- upper: 70
+attenuation-duration: !include attenuation-duration.yaml
risk-score-classes: !include risk-score-classification.yaml
exposure-config: !include exposure-config.yaml
-app-version: !include app-version-config.yaml
\ No newline at end of file
+app-version: !include app-version-config.yaml
diff --git a/services/distribution/src/main/resources/master-config/attenuation-duration.yaml b/services/distribution/src/main/resources/master-config/attenuation-duration.yaml
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/main/resources/master-config/attenuation-duration.yaml
@@ -0,0 +1,15 @@
+# This is the attenuation and duration parameter thresholds. The lower and
+# upper threshold partitions the value range into 3 subsets: low, mid, high
+#
+# Each of the aforementioned partitions has a weight in the range of [0, 1]
+# assigned to it. The number of decimal places is restricted to 3.
+#
+# Change this file with caution!
+
+thresholds:
+ lower: 50
+ upper: 70
+weights:
+ low: 1.0
+ mid: 0.5
+ high: 0.0
</patch> | diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/AttenuationDurationMasterFileTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/AttenuationDurationMasterFileTest.java
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/AttenuationDurationMasterFileTest.java
@@ -0,0 +1,47 @@
+/*-
+ * ---license-start
+ * Corona-Warn-App
+ * ---
+ * Copyright (C) 2020 SAP SE and all other contributors
+ * ---
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://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 for the specific language governing permissions and
+ * limitations under the License.
+ * ---license-end
+ */
+
+package app.coronawarn.server.services.distribution.assembly.appconfig;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import app.coronawarn.server.common.protocols.internal.AttenuationDuration;
+import app.coronawarn.server.services.distribution.assembly.appconfig.validation.AttenuationDurationValidator;
+import app.coronawarn.server.services.distribution.assembly.appconfig.validation.ConfigurationValidator;
+import app.coronawarn.server.services.distribution.assembly.appconfig.validation.ValidationResult;
+import org.junit.jupiter.api.Test;
+
+/**
+ * This test will verify that the provided attenuation/duration parameters master file is syntactically correct and
+ * according to spec. There should never be any deployment when this test is failing.
+ */
+class AttenuationDurationMasterFileTest {
+
+ private static final ValidationResult SUCCESS = new ValidationResult();
+
+ @Test
+ void testMasterFile() throws UnableToLoadFileException {
+ AttenuationDuration config = ApplicationConfigurationProvider.readMasterFile().getAttenuationDuration();
+
+ ConfigurationValidator validator = new AttenuationDurationValidator(config);
+
+ assertThat(validator.validate()).isEqualTo(SUCCESS);
+ }
+}
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ApplicationConfigurationValidatorTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ApplicationConfigurationValidatorTest.java
--- a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ApplicationConfigurationValidatorTest.java
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ApplicationConfigurationValidatorTest.java
@@ -20,26 +20,16 @@
package app.coronawarn.server.services.distribution.assembly.appconfig.validation;
-import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.GeneralValidationError.ErrorType.MIN_GREATER_THAN_MAX;
-import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.GeneralValidationError.ErrorType.VALUE_OUT_OF_BOUNDS;
-import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.ParameterSpec.ATTENUATION_DURATION_THRESHOLD_MAX;
-import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.ParameterSpec.ATTENUATION_DURATION_THRESHOLD_MIN;
-import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.RiskScoreClassificationValidatorTest.MINIMAL_RISK_SCORE_CLASSIFICATION;
-import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.RiskScoreClassificationValidatorTest.buildExpectedResult;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
-import app.coronawarn.server.common.protocols.internal.ApplicationConfiguration;
-import app.coronawarn.server.common.protocols.internal.AttenuationDurationThresholds;
import app.coronawarn.server.services.distribution.assembly.appconfig.ApplicationConfigurationProvider;
-import app.coronawarn.server.services.distribution.assembly.appconfig.ExposureConfigurationProvider;
import app.coronawarn.server.services.distribution.assembly.appconfig.UnableToLoadFileException;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
-import org.junit.jupiter.params.provider.ValueSource;
class ApplicationConfigurationValidatorTest {
@@ -59,43 +49,6 @@ void negative(TestWithExpectedResult test) throws UnableToLoadFileException {
assertThat(getResultForTest(test)).isEqualTo(test.result);
}
- @ParameterizedTest
- @ValueSource(ints = {ATTENUATION_DURATION_THRESHOLD_MIN - 1, ATTENUATION_DURATION_THRESHOLD_MAX + 1})
- void negativeForAttenuationDurationThresholdOutOfBounds(int invalidThresholdValue) throws Exception {
- ApplicationConfigurationValidator validator = getValidatorForAttenuationDurationThreshold(
- invalidThresholdValue, invalidThresholdValue);
-
- ValidationResult expectedResult = buildExpectedResult(
- new GeneralValidationError("attenuationDurationThreshold.upper", invalidThresholdValue, VALUE_OUT_OF_BOUNDS),
- new GeneralValidationError("attenuationDurationThreshold.lower", invalidThresholdValue, VALUE_OUT_OF_BOUNDS));
-
- assertThat(validator.validate()).isEqualTo(expectedResult);
- }
-
- @Test
- void negativeForUpperAttenuationDurationThresholdLesserThanLower() throws Exception {
- ApplicationConfigurationValidator validator = getValidatorForAttenuationDurationThreshold(
- ATTENUATION_DURATION_THRESHOLD_MAX, ATTENUATION_DURATION_THRESHOLD_MIN);
-
- ValidationResult expectedResult = buildExpectedResult(
- new GeneralValidationError("attenuationDurationThreshold.lower, attenuationDurationThreshold.upper",
- (ATTENUATION_DURATION_THRESHOLD_MAX + ", " + ATTENUATION_DURATION_THRESHOLD_MIN), MIN_GREATER_THAN_MAX));
-
- assertThat(validator.validate()).isEqualTo(expectedResult);
- }
-
- private ApplicationConfigurationValidator getValidatorForAttenuationDurationThreshold(int lower, int upper)
- throws Exception {
- ApplicationConfiguration appConfig = ApplicationConfiguration.newBuilder()
- .setMinRiskScore(100)
- .setRiskScoreClasses(MINIMAL_RISK_SCORE_CLASSIFICATION)
- .setExposureConfig(ExposureConfigurationProvider.readFile("configtests/exposure-config_ok.yaml"))
- .setAttenuationDurationThresholds(AttenuationDurationThresholds.newBuilder()
- .setLower(lower)
- .setUpper(upper)).build();
- return new ApplicationConfigurationValidator(appConfig);
- }
-
@Test
void circular() {
assertThatThrownBy(() -> {
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/AttenuationDurationValidatorTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/AttenuationDurationValidatorTest.java
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/AttenuationDurationValidatorTest.java
@@ -0,0 +1,114 @@
+/*-
+ * ---license-start
+ * Corona-Warn-App
+ * ---
+ * Copyright (C) 2020 SAP SE and all other contributors
+ * ---
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://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 for the specific language governing permissions and
+ * limitations under the License.
+ * ---license-end
+ */
+
+package app.coronawarn.server.services.distribution.assembly.appconfig.validation;
+
+import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.GeneralValidationError.ErrorType.MIN_GREATER_THAN_MAX;
+import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.GeneralValidationError.ErrorType.VALUE_OUT_OF_BOUNDS;
+import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.ParameterSpec.ATTENUATION_DURATION_THRESHOLD_MAX;
+import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.ParameterSpec.ATTENUATION_DURATION_THRESHOLD_MIN;
+import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.ParameterSpec.ATTENUATION_DURATION_WEIGHT_MAX;
+import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.ParameterSpec.ATTENUATION_DURATION_WEIGHT_MIN;
+import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.RiskScoreClassificationValidatorTest.buildError;
+import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.RiskScoreClassificationValidatorTest.buildExpectedResult;
+import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.WeightValidationError.ErrorType.OUT_OF_RANGE;
+import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.WeightValidationError.ErrorType.TOO_MANY_DECIMAL_PLACES;
+import static org.assertj.core.api.Assertions.assertThat;
+
+import app.coronawarn.server.common.protocols.internal.AttenuationDuration;
+import app.coronawarn.server.common.protocols.internal.Thresholds;
+import app.coronawarn.server.common.protocols.internal.Weights;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+public class AttenuationDurationValidatorTest {
+ private static final Thresholds VALID_THRESHOLDS =
+ buildThresholds(ATTENUATION_DURATION_THRESHOLD_MIN, ATTENUATION_DURATION_THRESHOLD_MAX);
+ private static final Weights VALID_WEIGHTS =
+ buildWeights(ATTENUATION_DURATION_WEIGHT_MAX, ATTENUATION_DURATION_WEIGHT_MAX, ATTENUATION_DURATION_WEIGHT_MAX);
+
+ @ParameterizedTest
+ @ValueSource(ints = {ATTENUATION_DURATION_THRESHOLD_MIN - 1, ATTENUATION_DURATION_THRESHOLD_MAX + 1})
+ void failsIfAttenuationDurationThresholdOutOfBounds(int invalidThresholdValue) {
+ AttenuationDurationValidator validator = buildValidator(
+ buildThresholds(invalidThresholdValue, invalidThresholdValue), VALID_WEIGHTS);
+
+ ValidationResult expectedResult = buildExpectedResult(
+ buildError("attenuation-duration.thresholds.lower", invalidThresholdValue, VALUE_OUT_OF_BOUNDS),
+ buildError("attenuation-duration.thresholds.upper", invalidThresholdValue, VALUE_OUT_OF_BOUNDS));
+
+ assertThat(validator.validate()).isEqualTo(expectedResult);
+ }
+
+ @Test
+ void failsIfUpperAttenuationDurationThresholdLesserThanLower() {
+ AttenuationDurationValidator validator = buildValidator(
+ buildThresholds(ATTENUATION_DURATION_THRESHOLD_MAX, ATTENUATION_DURATION_THRESHOLD_MIN), VALID_WEIGHTS);
+
+ ValidationResult expectedResult = buildExpectedResult(
+ new GeneralValidationError("attenuation-duration.thresholds.lower, attenuation-duration.thresholds.upper",
+ (ATTENUATION_DURATION_THRESHOLD_MAX + ", " + ATTENUATION_DURATION_THRESHOLD_MIN), MIN_GREATER_THAN_MAX));
+
+ assertThat(validator.validate()).isEqualTo(expectedResult);
+ }
+
+ @ParameterizedTest
+ @ValueSource(doubles = {ATTENUATION_DURATION_WEIGHT_MIN - .1, ATTENUATION_DURATION_WEIGHT_MAX + .1})
+ void failsIfWeightsOutOfBounds(double invalidWeightValue) {
+ AttenuationDurationValidator validator = buildValidator(VALID_THRESHOLDS,
+ buildWeights(invalidWeightValue, invalidWeightValue, invalidWeightValue));
+
+ ValidationResult expectedResult = buildExpectedResult(
+ new WeightValidationError("attenuation-duration.weights.low", invalidWeightValue, OUT_OF_RANGE),
+ new WeightValidationError("attenuation-duration.weights.mid", invalidWeightValue, OUT_OF_RANGE),
+ new WeightValidationError("attenuation-duration.weights.high", invalidWeightValue, OUT_OF_RANGE));
+
+ assertThat(validator.validate()).isEqualTo(expectedResult);
+ }
+
+ @Test
+ void failsIfWeightsHaveTooManyDecimalPlaces() {
+ double invalidWeightValue = ATTENUATION_DURATION_WEIGHT_MAX - 0.0000001;
+ AttenuationDurationValidator validator = buildValidator(VALID_THRESHOLDS,
+ buildWeights(invalidWeightValue, invalidWeightValue, invalidWeightValue));
+
+ ValidationResult expectedResult = buildExpectedResult(
+ new WeightValidationError("attenuation-duration.weights.low", invalidWeightValue, TOO_MANY_DECIMAL_PLACES),
+ new WeightValidationError("attenuation-duration.weights.mid", invalidWeightValue, TOO_MANY_DECIMAL_PLACES),
+ new WeightValidationError("attenuation-duration.weights.high", invalidWeightValue, TOO_MANY_DECIMAL_PLACES));
+
+ assertThat(validator.validate()).isEqualTo(expectedResult);
+ }
+
+ private static AttenuationDurationValidator buildValidator(Thresholds thresholds, Weights weights) {
+ return new AttenuationDurationValidator(AttenuationDuration.newBuilder()
+ .setThresholds(thresholds)
+ .setWeights(weights).build());
+ }
+
+ private static Thresholds buildThresholds(int lower, int upper) {
+ return Thresholds.newBuilder().setLower(lower).setUpper(upper).build();
+ }
+
+ private static Weights buildWeights(double low, double mid, double high) {
+ return Weights.newBuilder().setLow(low).setMid(mid).setHigh(high).build();
+ }
+}
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/RiskScoreClassificationValidatorTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/RiskScoreClassificationValidatorTest.java
--- a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/RiskScoreClassificationValidatorTest.java
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/RiskScoreClassificationValidatorTest.java
@@ -166,7 +166,7 @@ private static RiskScoreClass buildRiskClass(String label, int min, int max, Str
return RiskScoreClass.newBuilder().setLabel(label).setMin(min).setMax(max).setUrl(url).build();
}
- public static ValidationResult buildExpectedResult(GeneralValidationError... errors) {
+ public static ValidationResult buildExpectedResult(ValidationError... errors) {
var validationResult = new ValidationResult();
Arrays.stream(errors).forEach(validationResult::add);
return validationResult;
diff --git a/services/distribution/src/test/resources/configtests/app-config_ok.yaml b/services/distribution/src/test/resources/configtests/app-config_ok.yaml
--- a/services/distribution/src/test/resources/configtests/app-config_ok.yaml
+++ b/services/distribution/src/test/resources/configtests/app-config_ok.yaml
@@ -1,7 +1,5 @@
min-risk-score: 100
-attenuationDurationThresholds:
- lower: 50
- upper: 70
+attenuation-duration: !include attenuation-duration.yaml
risk-score-classes: !include risk-score-class_ok.yaml
exposure-config: !include exposure-config_ok.yaml
-app-version: !include app-version-config_ok.yaml
\ No newline at end of file
+app-version: !include app-version-config_ok.yaml
diff --git a/services/distribution/src/test/resources/configtests/attenuation-duration.yaml b/services/distribution/src/test/resources/configtests/attenuation-duration.yaml
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/test/resources/configtests/attenuation-duration.yaml
@@ -0,0 +1,7 @@
+thresholds:
+ lower: 50
+ upper: 70
+weights:
+ low: 1.0
+ mid: 0.5
+ high: 0.0
| ||||
corona-warn-app__cwa-server-308 | You will be provided with a partial code base and an issue statement explaining a problem to resolve.
<issue>
Apple's Proposal for Exposure Key Validation
#92 Current Implementation
We used sensible assumptions for key validation.
## Suggested Enhancement
[Apple proposes](https://developer.apple.com/documentation/exposurenotification/setting_up_an_exposure_notification_server?changes=latest_beta):
> An EN server must reject invalid key files uploaded from a client app. Uploaded key data is considered invalid if:
>
> Any ENIntervalNumber values from the same user are not unique
>
> There are any gaps in the ENIntervalNumber values for a user
>
> Any keys in the file have overlapping time windows
>
> The period of time covered by the data file exceeds 14 days
>
> The TEKRollingPeriod value is not 144
>
> You may optionally want to validate the clock time the device submits.
## Expected Benefits
Adherence to reference implementations.
</issue>
<code>
[start of README.md]
1 <h1 align="center">
2 Corona-Warn-App Server
3 </h1>
4
5 <p align="center">
6 <a href="https://github.com/corona-warn-app/cwa-server/commits/" title="Last Commit"><img src="https://img.shields.io/github/last-commit/corona-warn-app/cwa-server?style=flat"></a>
7 <a href="https://github.com/corona-warn-app/cwa-server/issues" title="Open Issues"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat"></a>
8 <a href="https://circleci.com/gh/corona-warn-app/cwa-server" title="Build Status"><img src="https://circleci.com/gh/corona-warn-app/cwa-server.svg?style=shield&circle-token=4ab059989d10709df19eb4b98ab7c121a25e981a"></a>
9 <a href="https://sonarcloud.io/dashboard?id=corona-warn-app_cwa-server" title="Quality Gate"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=alert_status"></a>
10 <a href="https://sonarcloud.io/component_measures?id=corona-warn-app_cwa-server&metric=Coverage&view=list" title="Coverage"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=coverage"></a>
11 <a href="https://github.com/corona-warn-app/cwa-server/blob/master/LICENSE" title="License"><img src="https://img.shields.io/badge/License-Apache%202.0-green.svg?style=flat"></a>
12 </p>
13
14 <p align="center">
15 <a href="#development">Development</a> •
16 <a href="#service-apis">Service APIs</a> •
17 <a href="#documentation">Documentation</a> •
18 <a href="#support-and-feedback">Support</a> •
19 <a href="#how-to-contribute">Contribute</a> •
20 <a href="#contributors">Contributors</a> •
21 <a href="#repositories">Repositories</a> •
22 <a href="#licensing">Licensing</a>
23 </p>
24
25 The goal of this project is to develop the official Corona-Warn-App for Germany based on the exposure notification API from [Apple](https://www.apple.com/covid19/contacttracing/) and [Google](https://www.google.com/covid19/exposurenotifications/). The apps (for both iOS and Android) use Bluetooth technology to exchange anonymous encrypted data with other mobile phones (on which the app is also installed) in the vicinity of an app user's phone. The data is stored locally on each user's device, preventing authorities or other parties from accessing or controlling the data. This repository contains the **implementation of the server for encryption keys** for the Corona-Warn-App. This implementation is still a **work in progress**, and the code it contains is currently alpha-quality code.
26
27 In this documentation, Corona-Warn-App services are also referred to as CWA services.
28
29 ## Architecture Overview
30
31 You can find the architecture overview [here](/docs/architecture-overview.md), which will give you
32 a good starting point in how the backend services interact with other services, and what purpose
33 they serve.
34
35 ## Development
36
37 After you've checked out this repository, you can run the application in one of the following ways:
38
39 * As a [Docker](https://www.docker.com/)-based deployment on your local machine. You can run either:
40 * Single components using the respective Dockerfile or
41 * The full backend using the Docker Compose (which is considered the most convenient way)
42 * As a [Maven](https://maven.apache.org)-based build on your local machine.
43 If you want to develop something in a single component, this approach is preferable.
44
45 ### Docker-Based Deployment
46
47 If you want to use Docker-based deployment, you need to install Docker on your local machine. For more information about downloading and installing Docker, see the [official Docker documentation](https://docs.docker.com/get-docker/).
48
49 #### Running the Full CWA Backend Using Docker Compose
50
51 For your convenience, a full setup including the generation of test data has been prepared using [Docker Compose](https://docs.docker.com/compose/reference/overview/). To build the backend services, run ```docker-compose build``` in the repository's root directory. A default configuration file can be found under ```.env```in the root folder of the repository. The default values for the local Postgres and Zenko Cloudserver should be changed in this file before docker-compose is run.
52
53 Once the services are built, you can start the whole backend using ```docker-compose up```.
54 The distribution service runs once and then finishes. If you want to trigger additional distribution runs, run ```docker-compose run distribution```.
55
56 The docker-compose contains the following services:
57
58 Service | Description | Endpoint and Default Credentials
59 ------------------|-------------|-----------
60 submission | The Corona-Warn-App submission service | http://localhost:8000 <br> http://localhost:8005 (for actuator endpoint)
61 distribution | The Corona-Warn-App distribution service | NO ENDPOINT
62 postgres | A [postgres] database installation | postgres:8001 <br> Username: postgres <br> Password: postgres
63 pgadmin | A [pgadmin](https://www.pgadmin.org/) installation for the postgres database | http://localhost:8002 <br> Username: [email protected] <br> Password: password
64 cloudserver | [Zenko CloudServer] is a S3-compliant object store | http://localhost:8003/ <br> Access key: accessKey1 <br> Secret key: verySecretKey1
65 verification-fake | A very simple fake implementation for the tan verification. | http://localhost:8004/version/v1/tan/verify <br> The only valid tan is "b69ab69f-9823-4549-8961-c41sa74b2f36"
66
67 ##### Known Limitation
68
69 In rare cases the docker-compose runs into a timing issue if the distribution service starts before the bucket of the objectstore was created. This is not a big issue as you can simply run ```docker-compose run distribution``` to trigger additional distribution runs after the objectstore was initialized.
70
71 #### Running Single CWA Services Using Docker
72
73 If you would like to build and run a single CWA service, it's considered easiest to run them in a Docker environment. You can do this using the script provided in the respective CWA service directory. The Docker script first builds the CWA service and then creates an image for the runtime, which means that there are no additional dependencies for you to install.
74
75 To build and run the distribution service, run the following command:
76
77 ```bash
78 ./services/distribution/build_and_run.sh
79 ```
80
81 To build and run the submission service, run the following command:
82
83 ```bash
84 ./services/submission/build_and_run.sh
85 ```
86
87 The submission service is available on [localhost:8080](http://localhost:8080 ).
88
89 ### Maven-Based Build
90
91 If you want to actively develop in one of the CWA services, the Maven-based runtime is most suitable.
92 To prepare your machine to run the CWA project locally, we recommend that you first ensure that you've installed the following:
93
94 * Minimum JDK Version 11: [OpenJDK](https://openjdk.java.net/) / [SapMachine](https://sap.github.io/SapMachine/)
95 * [Maven 3.6](https://maven.apache.org/)
96 * [Postgres]
97 * [Zenko CloudServer]
98
99 #### Configure
100
101 After you made sure that the specified dependencies are running, configure them in the respective configuration files.
102
103 * Configure the Postgres connection in the [submission config](./services/submission/src/main/resources/application.yaml) and in the [distribution config](./services/distribution/src/main/resources/application.yaml)
104 * Configure the S3 compatible object storage in the [distribution config](./services/distribution/src/main/resources/application.yaml)
105 * Configure the certificate and private key for the distribution service, the paths need to be prefixed with `file:`
106 * `VAULT_FILESIGNING_SECRET` should be the path to the private key, example available in `<repo-root>/docker-compose-test-secrets/private.pem`
107 * `VAULT_FILESIGNING_CERT` should be the path to the certificate, example available in `<repo-root>/docker-compose-test-secrets/certificate.cert`
108
109 #### Build
110
111 After you've checked out the repository, to build the project, run ```mvn install``` in your base directory.
112
113 #### Run
114
115 Navigate to the service you want to start and run the spring-boot:run target. The configured Postgres and the configured S3 compliant object storage are used as default. When you start the submission service, the endpoint is available on your local port 8080.
116
117 If you want to start the submission service, for example, you start it as follows:
118
119 ```bash
120 cd services/submission/
121 mvn spring-boot:run
122 ```
123
124 #### Debugging
125
126 To enable the `DEBUG` log level, you can run the application using the Spring `dev` profile.
127
128 ```bash
129 mvn spring-boot:run -Dspring-boot.run.profiles=dev
130 ```
131
132 To be able to set breakpoints (e.g. in IntelliJ), it may be necessary to use the ```-Dspring-boot.run.fork=false``` parameter.
133
134 ## Service APIs
135
136 The API that is being exposed by the backend services is documented in an [OpenAPI](https://www.openapis.org/) specification. The specification files are available at the following locations:
137
138 Service | OpenAPI Specification
139 -------------|-------------
140 Submission Service | https://github.com/corona-warn-app/cwa-server/raw/master/services/submission/api_v1.json
141 Distribution Service | https://github.com/corona-warn-app/cwa-server/raw/master/services/distribution/api_v1.json
142
143 ## Spring Profiles
144
145 #### Distribution
146
147 Profile | Effect
148 -------------|-------------
149 `dev` | Turns the log level to `DEBUG`.
150 `cloud` | Removes default values for the `datasource` and `objectstore` configurations.
151 `demo` | Includes incomplete days and hours into the distribution run, thus creating aggregates for the current day and the current hour (and including both in the respective indices). When running multiple distributions in one hour with this profile, the date aggregate for today and the hours aggregate for the current hour will be updated and overwritten.
152 `testdata` | Causes test data to be inserted into the database before each distribution run. By default, around 1000 random diagnosis keys will be generated per hour. If there are no diagnosis keys in the database yet, random keys will be generated for every hour from the beginning of the retention period (14 days ago at 00:00 UTC) until one hour before the present hour. If there are already keys in the database, the random keys will be generated for every hour from the latest diagnosis key in the database (by submission timestamp) until one hour before the present hour (or none at all, if the latest diagnosis key in the database was submitted one hour ago or later).
153
154 #### Submission
155
156 Profile | Effect
157 -------------|-------------
158 `dev` | Turns the log level to `DEBUG`.
159 `cloud` | Removes default values for the `datasource` configuration.
160
161 ## Documentation
162
163 The full documentation for the Corona-Warn-App can be found in the [cwa-documentation](https://github.com/corona-warn-app/cwa-documentation) repository. The documentation repository contains technical documents, architecture information, and whitepapers related to this implementation.
164
165 ## Support and Feedback
166
167 The following channels are available for discussions, feedback, and support requests:
168
169 | Type | Channel |
170 | ------------------------ | ------------------------------------------------------ |
171 | **General Discussion** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="General Discussion"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/question.svg?style=flat-square"></a> </a> |
172 | **Concept Feedback** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="Open Concept Feedback"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/architecture.svg?style=flat-square"></a> |
173 | **Backend Issue** | <a href="https://github.com/corona-warn-app/cwa-server/issues/new/choose" title="Open Backend Issue"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat-square"></a> |
174 | **Other Requests** | <a href="mailto:[email protected]" title="Email CWA Team"><img src="https://img.shields.io/badge/email-CWA%20team-green?logo=mail.ru&style=flat-square&logoColor=white"></a> |
175
176 ## How to Contribute
177
178 Contribution and feedback are 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.
179
180 ## Contributors
181
182 The German government has asked SAP and Deutsche Telekom to develop the Corona-Warn-App for Germany as open source software. Deutsche Telekom is providing the network and mobile technology and will operate and run the backend for the app in a safe, scalable and stable manner. SAP is responsible for the app development, its framework and the underlying platform. Therefore, development teams of SAP and Deutsche Telekom are contributing to this project. At the same time 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.
183
184 ## Repositories
185
186 The following public repositories are currently available for the Corona-Warn-App:
187
188 | Repository | Description |
189 | ------------------- | --------------------------------------------------------------------- |
190 | [cwa-documentation] | Project overview, general documentation, and white papers |
191 | [cwa-server] | Backend implementation for the Apple/Google exposure notification API|
192 | [cwa-verification-server] | Backend implementation of the verification process|
193
194 [cwa-documentation]: https://github.com/corona-warn-app/cwa-documentation
195 [cwa-server]: https://github.com/corona-warn-app/cwa-server
196 [cwa-verification-server]: https://github.com/corona-warn-app/cwa-verification-server
197 [Postgres]: https://www.postgresql.org/
198 [HSQLDB]: http://hsqldb.org/
199 [Zenko CloudServer]: https://github.com/scality/cloudserver
200
201 ## Licensing
202
203 Copyright (c) 2020 SAP SE or an SAP affiliate company.
204
205 Licensed under the **Apache License, Version 2.0** (the "License"); you may not use this file except in compliance with the License.
206
207 You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0.
208
209 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.
210
[end of README.md]
[start of /dev/null]
1
[end of /dev/null]
[start of common/persistence/src/main/java/app/coronawarn/server/common/persistence/domain/DiagnosisKey.java]
1 /*
2 * Corona-Warn-App
3 *
4 * SAP SE and all other contributors /
5 * copyright owners license this file to you under the Apache
6 * License, Version 2.0 (the "License"); you may not use this
7 * file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20 package app.coronawarn.server.common.persistence.domain;
21
22 import static java.time.ZoneOffset.UTC;
23
24 import app.coronawarn.server.common.persistence.domain.DiagnosisKeyBuilders.Builder;
25 import app.coronawarn.server.common.persistence.domain.validation.ValidRollingStartIntervalNumber;
26 import java.time.Instant;
27 import java.time.LocalDateTime;
28 import java.util.Arrays;
29 import java.util.Objects;
30 import java.util.Set;
31 import javax.persistence.Entity;
32 import javax.persistence.GeneratedValue;
33 import javax.persistence.GenerationType;
34 import javax.persistence.Id;
35 import javax.persistence.Table;
36 import javax.validation.ConstraintViolation;
37 import javax.validation.Validation;
38 import javax.validation.Validator;
39 import javax.validation.constraints.Min;
40 import javax.validation.constraints.Size;
41 import org.hibernate.validator.constraints.Range;
42
43 /**
44 * A key generated for advertising over a window of time.
45 */
46 @Entity
47 @Table(name = "diagnosis_key")
48 public class DiagnosisKey {
49 private static final Validator VALIDATOR = Validation.buildDefaultValidatorFactory().getValidator();
50
51 @Id
52 @GeneratedValue(strategy = GenerationType.IDENTITY)
53 private Long id;
54
55 @Size(min = 16, max = 16, message = "Key data must be a byte array of length 16.")
56 private byte[] keyData;
57
58 @ValidRollingStartIntervalNumber
59 private int rollingStartIntervalNumber;
60
61 @Min(value = 1, message = "Rolling period must be greater than 0.")
62 private int rollingPeriod;
63
64 @Range(min = 0, max = 8, message = "Risk level must be between 0 and 8.")
65 private int transmissionRiskLevel;
66
67 private long submissionTimestamp;
68
69 protected DiagnosisKey() {
70 }
71
72 /**
73 * Should be called by builders.
74 */
75 DiagnosisKey(byte[] keyData, int rollingStartIntervalNumber, int rollingPeriod,
76 int transmissionRiskLevel, long submissionTimestamp) {
77 this.keyData = keyData;
78 this.rollingStartIntervalNumber = rollingStartIntervalNumber;
79 this.rollingPeriod = rollingPeriod;
80 this.transmissionRiskLevel = transmissionRiskLevel;
81 this.submissionTimestamp = submissionTimestamp;
82 }
83
84 /**
85 * Returns a DiagnosisKeyBuilder instance. A {@link DiagnosisKey} can then be build by either providing the required
86 * member values or by passing the respective protocol buffer object.
87 *
88 * @return DiagnosisKeyBuilder instance.
89 */
90 public static Builder builder() {
91 return new DiagnosisKeyBuilder();
92 }
93
94 public Long getId() {
95 return id;
96 }
97
98 /**
99 * Returns the diagnosis key.
100 */
101 public byte[] getKeyData() {
102 return keyData;
103 }
104
105 /**
106 * Returns a number describing when a key starts. It is equal to startTimeOfKeySinceEpochInSecs / (60 * 10).
107 */
108 public int getRollingStartIntervalNumber() {
109 return rollingStartIntervalNumber;
110 }
111
112 /**
113 * Returns a number describing how long a key is valid. It is expressed in increments of 10 minutes (e.g. 144 for 24
114 * hours).
115 */
116 public int getRollingPeriod() {
117 return rollingPeriod;
118 }
119
120 /**
121 * Returns the risk of transmission associated with the person this key came from.
122 */
123 public int getTransmissionRiskLevel() {
124 return transmissionRiskLevel;
125 }
126
127 /**
128 * Returns the timestamp associated with the submission of this {@link DiagnosisKey} as hours since epoch.
129 */
130 public long getSubmissionTimestamp() {
131 return submissionTimestamp;
132 }
133
134 /**
135 * Checks if this diagnosis key falls into the period between now, and the retention threshold.
136 *
137 * @param daysToRetain the number of days before a key is outdated
138 * @return true, if the rolling start number is in the time span between now, and the given days to retain
139 * @throws IllegalArgumentException if {@code daysToRetain} is negative.
140 */
141 public boolean isYoungerThanRetentionThreshold(int daysToRetain) {
142 if (daysToRetain < 0) {
143 throw new IllegalArgumentException("Retention threshold must be greater or equal to 0.");
144 }
145 long threshold = LocalDateTime
146 .ofInstant(Instant.now(), UTC)
147 .minusDays(daysToRetain)
148 .toEpochSecond(UTC) / (60 * 10);
149
150 return this.rollingStartIntervalNumber >= threshold;
151 }
152
153 /**
154 * Gets any constraint violations that this key might incorporate.
155 *
156 * <p><ul>
157 * <li>Risk level must be between 0 and 8
158 * <li>Rolling start number must be greater than 0
159 * <li>Rolling start number cannot be in the future
160 * <li>Rolling period must be positive number
161 * <li>Key data must be byte array of length 16
162 * </ul>
163 *
164 * @return A set of constraint violations of this key.
165 */
166 public Set<ConstraintViolation<DiagnosisKey>> validate() {
167 return VALIDATOR.validate(this);
168 }
169
170 @Override
171 public boolean equals(Object o) {
172 if (this == o) {
173 return true;
174 }
175 if (o == null || getClass() != o.getClass()) {
176 return false;
177 }
178 DiagnosisKey that = (DiagnosisKey) o;
179 return rollingStartIntervalNumber == that.rollingStartIntervalNumber
180 && rollingPeriod == that.rollingPeriod
181 && transmissionRiskLevel == that.transmissionRiskLevel
182 && submissionTimestamp == that.submissionTimestamp
183 && Objects.equals(id, that.id)
184 && Arrays.equals(keyData, that.keyData);
185 }
186
187 @Override
188 public int hashCode() {
189 int result = Objects
190 .hash(id, rollingStartIntervalNumber, rollingPeriod, transmissionRiskLevel, submissionTimestamp);
191 result = 31 * result + Arrays.hashCode(keyData);
192 return result;
193 }
194 }
195
[end of common/persistence/src/main/java/app/coronawarn/server/common/persistence/domain/DiagnosisKey.java]
[start of common/persistence/src/main/java/app/coronawarn/server/common/persistence/domain/DiagnosisKeyBuilder.java]
1 /*
2 * Corona-Warn-App
3 *
4 * SAP SE and all other contributors /
5 * copyright owners license this file to you under the Apache
6 * License, Version 2.0 (the "License"); you may not use this
7 * file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20 package app.coronawarn.server.common.persistence.domain;
21
22 import static app.coronawarn.server.common.persistence.domain.DiagnosisKeyBuilders.Builder;
23 import static app.coronawarn.server.common.persistence.domain.DiagnosisKeyBuilders.FinalBuilder;
24 import static app.coronawarn.server.common.persistence.domain.DiagnosisKeyBuilders.RollingPeriodBuilder;
25 import static app.coronawarn.server.common.persistence.domain.DiagnosisKeyBuilders.RollingStartIntervalNumberBuilder;
26 import static app.coronawarn.server.common.persistence.domain.DiagnosisKeyBuilders.TransmissionRiskLevelBuilder;
27
28 import app.coronawarn.server.common.persistence.exception.InvalidDiagnosisKeyException;
29 import app.coronawarn.server.common.protocols.external.exposurenotification.TemporaryExposureKey;
30 import java.time.Instant;
31 import java.util.Set;
32 import java.util.stream.Collectors;
33 import javax.validation.ConstraintViolation;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36
37 /**
38 * An instance of this builder can be retrieved by calling {@link DiagnosisKey#builder()}. A {@link DiagnosisKey} can
39 * then be build by either providing the required member values or by passing the respective protocol buffer object.
40 */
41 public class DiagnosisKeyBuilder implements Builder, RollingStartIntervalNumberBuilder,
42 RollingPeriodBuilder, TransmissionRiskLevelBuilder, FinalBuilder {
43
44 private static final Logger logger = LoggerFactory.getLogger(DiagnosisKeyBuilder.class);
45
46 private byte[] keyData;
47 private int rollingStartIntervalNumber;
48 private int rollingPeriod;
49 private int transmissionRiskLevel;
50 private long submissionTimestamp = -1L;
51
52 DiagnosisKeyBuilder() {
53 }
54
55 @Override
56 public RollingStartIntervalNumberBuilder withKeyData(byte[] keyData) {
57 this.keyData = keyData;
58 return this;
59 }
60
61 @Override
62 public RollingPeriodBuilder withRollingStartIntervalNumber(int rollingStartIntervalNumber) {
63 this.rollingStartIntervalNumber = rollingStartIntervalNumber;
64 return this;
65 }
66
67 @Override
68 public TransmissionRiskLevelBuilder withRollingPeriod(int rollingPeriod) {
69 this.rollingPeriod = rollingPeriod;
70 return this;
71 }
72
73 @Override
74 public FinalBuilder withTransmissionRiskLevel(int transmissionRiskLevel) {
75 this.transmissionRiskLevel = transmissionRiskLevel;
76 return this;
77 }
78
79 @Override
80 public FinalBuilder fromProtoBuf(TemporaryExposureKey protoBufObject) {
81 return this
82 .withKeyData(protoBufObject.getKeyData().toByteArray())
83 .withRollingStartIntervalNumber(protoBufObject.getRollingStartIntervalNumber())
84 .withRollingPeriod(protoBufObject.getRollingPeriod())
85 .withTransmissionRiskLevel(protoBufObject.getTransmissionRiskLevel());
86 }
87
88 @Override
89 public FinalBuilder withSubmissionTimestamp(long submissionTimestamp) {
90 this.submissionTimestamp = submissionTimestamp;
91 return this;
92 }
93
94 @Override
95 public DiagnosisKey build() {
96 if (submissionTimestamp < 0) {
97 // hours since epoch
98 submissionTimestamp = Instant.now().getEpochSecond() / 3600L;
99 }
100
101 var diagnosisKey = new DiagnosisKey(
102 keyData, rollingStartIntervalNumber, rollingPeriod, transmissionRiskLevel, submissionTimestamp);
103 return throwIfValidationFails(diagnosisKey);
104 }
105
106 private DiagnosisKey throwIfValidationFails(DiagnosisKey diagnosisKey) {
107 Set<ConstraintViolation<DiagnosisKey>> violations = diagnosisKey.validate();
108
109 if (!violations.isEmpty()) {
110 String violationsMessage = violations.stream()
111 .map(violation -> String.format("%s Invalid Value: %s", violation.getMessage(), violation.getInvalidValue()))
112 .collect(Collectors.toList()).toString();
113 logger.debug(violationsMessage);
114 throw new InvalidDiagnosisKeyException(violationsMessage);
115 }
116
117 return diagnosisKey;
118 }
119 }
120
[end of common/persistence/src/main/java/app/coronawarn/server/common/persistence/domain/DiagnosisKeyBuilder.java]
[start of common/persistence/src/main/java/app/coronawarn/server/common/persistence/domain/DiagnosisKeyBuilders.java]
1 /*
2 * Corona-Warn-App
3 *
4 * SAP SE and all other contributors /
5 * copyright owners license this file to you under the Apache
6 * License, Version 2.0 (the "License"); you may not use this
7 * file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20 package app.coronawarn.server.common.persistence.domain;
21
22 import app.coronawarn.server.common.protocols.external.exposurenotification.TemporaryExposureKey;
23
24 /**
25 * This interface bundles interfaces that are used for the implementation of {@link DiagnosisKeyBuilder}.
26 */
27 interface DiagnosisKeyBuilders {
28
29 interface Builder {
30
31 /**
32 * Adds the specified key data to this builder.
33 *
34 * @param keyData generated diagnosis key.
35 * @return this Builder instance.
36 */
37 RollingStartIntervalNumberBuilder withKeyData(byte[] keyData);
38
39 /**
40 * Adds the data contained in the specified protocol buffers key object to this builder.
41 *
42 * @param protoBufObject ProtocolBuffer object associated with the temporary exposure key.
43 * @return this Builder instance.
44 */
45 FinalBuilder fromProtoBuf(TemporaryExposureKey protoBufObject);
46 }
47
48 interface RollingStartIntervalNumberBuilder {
49
50 /**
51 * Adds the specified rolling start number to this builder.
52 *
53 * @param rollingStartIntervalNumber number describing when a key starts. It is equal to
54 * startTimeOfKeySinceEpochInSecs / (60 * 10).
55 * @return this Builder instance.
56 */
57 RollingPeriodBuilder withRollingStartIntervalNumber(int rollingStartIntervalNumber);
58 }
59
60 interface RollingPeriodBuilder {
61
62 /**
63 * Adds the specified rolling period to this builder.
64 *
65 * @param rollingPeriod Number describing how long a key is valid. It is expressed in increments
66 * of 10 minutes (e.g. 144 for 24 hours).
67 * @return this Builder instance.
68 */
69 TransmissionRiskLevelBuilder withRollingPeriod(int rollingPeriod);
70 }
71
72 interface TransmissionRiskLevelBuilder {
73
74 /**
75 * Adds the specified transmission risk level to this builder.
76 *
77 * @param transmissionRiskLevel risk of transmission associated with the person this key came from.
78 * @return this Builder instance.
79 */
80 FinalBuilder withTransmissionRiskLevel(int transmissionRiskLevel);
81 }
82
83 interface FinalBuilder {
84
85 /**
86 * Adds the specified submission timestamp that is expected to represent hours since epoch.
87 *
88 * @param submissionTimestamp timestamp in hours since epoch.
89 * @return this Builder instance.
90 */
91 FinalBuilder withSubmissionTimestamp(long submissionTimestamp);
92
93 /**
94 * Builds a {@link DiagnosisKey} instance. If no submission timestamp has been specified it will be set to "now" as
95 * hours since epoch.
96 */
97 DiagnosisKey build();
98 }
99 }
100
[end of common/persistence/src/main/java/app/coronawarn/server/common/persistence/domain/DiagnosisKeyBuilders.java]
[start of common/persistence/src/main/java/app/coronawarn/server/common/persistence/domain/validation/ValidRollingStartIntervalNumber.java]
1 /*
2 * Corona-Warn-App
3 * SAP SE and all other contributors /
4 * copyright owners license this file to you under the Apache
5 * License, Version 2.0 (the "License"); you may not use this
6 * file except in compliance with the License.
7 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
9 * Unless required by applicable law or agreed to in writing,
10 * software distributed under the License is distributed on an
11 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
12 * KIND, either express or implied. See the License for the
13 * specific language governing permissions and limitations
14 * under the License.
15 */
16
17 package app.coronawarn.server.common.persistence.domain.validation;
18
19 import java.lang.annotation.Documented;
20 import java.lang.annotation.ElementType;
21 import java.lang.annotation.Retention;
22 import java.lang.annotation.RetentionPolicy;
23 import java.lang.annotation.Target;
24 import javax.validation.Constraint;
25 import javax.validation.Payload;
26
27 @Constraint(validatedBy = ValidRollingStartIntervalNumberValidator.class)
28 @Target({ElementType.FIELD})
29 @Retention(RetentionPolicy.RUNTIME)
30 @Documented
31 public @interface ValidRollingStartIntervalNumber {
32
33 /**
34 * Error message.
35 *
36 * @return the error message
37 */
38 String message() default "Rolling start number must be greater 0 and cannot be in the future.";
39
40 /**
41 * Groups.
42 *
43 * @return
44 */
45 Class<?>[] groups() default {};
46
47 /**
48 * Payload.
49 *
50 * @return
51 */
52 Class<? extends Payload>[] payload() default {};
53 }
54
[end of common/persistence/src/main/java/app/coronawarn/server/common/persistence/domain/validation/ValidRollingStartIntervalNumber.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/TestDataGeneration.java]
1 /*
2 * Corona-Warn-App
3 *
4 * SAP SE and all other contributors /
5 * copyright owners license this file to you under the Apache
6 * License, Version 2.0 (the "License"); you may not use this
7 * file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20 package app.coronawarn.server.services.distribution.runner;
21
22 import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
23 import app.coronawarn.server.common.persistence.service.DiagnosisKeyService;
24 import app.coronawarn.server.common.protocols.internal.RiskLevel;
25 import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
26 import app.coronawarn.server.services.distribution.config.DistributionServiceConfig.TestData;
27 import java.time.LocalDate;
28 import java.time.LocalDateTime;
29 import java.time.ZoneOffset;
30 import java.util.List;
31 import java.util.concurrent.TimeUnit;
32 import java.util.stream.Collectors;
33 import java.util.stream.IntStream;
34 import java.util.stream.LongStream;
35 import org.apache.commons.math3.distribution.PoissonDistribution;
36 import org.apache.commons.math3.random.JDKRandomGenerator;
37 import org.apache.commons.math3.random.RandomGenerator;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
40 import org.springframework.boot.ApplicationArguments;
41 import org.springframework.boot.ApplicationRunner;
42 import org.springframework.context.annotation.Profile;
43 import org.springframework.core.annotation.Order;
44 import org.springframework.stereotype.Component;
45
46 /**
47 * Generates random diagnosis keys for the time frame between the last diagnosis key in the database and now (last full
48 * hour) and writes them to the database. If there are no diagnosis keys in the database yet, then random diagnosis keys
49 * for the time frame between the last full hour and the beginning of the retention period (14 days ago) will be
50 * generated. The average number of exposure keys to be generated per hour is configurable in the application properties
51 * (profile = {@code testdata}).
52 */
53 @Component
54 @Order(-1)
55 @Profile("testdata")
56 public class TestDataGeneration implements ApplicationRunner {
57
58 private final Logger logger = LoggerFactory.getLogger(TestDataGeneration.class);
59
60 private final Integer retentionDays;
61
62 private final TestData config;
63
64 private final DiagnosisKeyService diagnosisKeyService;
65
66 private final RandomGenerator random = new JDKRandomGenerator();
67
68 private static final int POISSON_MAX_ITERATIONS = 10_000_000;
69 private static final double POISSON_EPSILON = 1e-12;
70
71 // The submission timestamp is counted in 1 hour intervals since epoch
72 private static final long ONE_HOUR_INTERVAL_SECONDS = TimeUnit.HOURS.toSeconds(1);
73
74 // The rolling start number is counted in 10 minute intervals since epoch
75 private static final long TEN_MINUTES_INTERVAL_SECONDS = TimeUnit.MINUTES.toSeconds(10);
76
77 /**
78 * Creates a new TestDataGeneration runner.
79 */
80 TestDataGeneration(DiagnosisKeyService diagnosisKeyService,
81 DistributionServiceConfig distributionServiceConfig) {
82 this.diagnosisKeyService = diagnosisKeyService;
83 this.retentionDays = distributionServiceConfig.getRetentionDays();
84 this.config = distributionServiceConfig.getTestData();
85 }
86
87 /**
88 * See {@link TestDataGeneration} class documentation.
89 */
90 @Override
91 public void run(ApplicationArguments args) {
92 writeTestData();
93 }
94
95 /**
96 * See {@link TestDataGeneration} class documentation.
97 */
98 private void writeTestData() {
99 logger.debug("Querying diagnosis keys from the database...");
100 List<DiagnosisKey> existingDiagnosisKeys = diagnosisKeyService.getDiagnosisKeys();
101
102 // Timestamps in hours since epoch. Test data generation starts one hour after the latest diagnosis key in the
103 // database and ends one hour before the current one.
104 long startTimestamp = getGeneratorStartTimestamp(existingDiagnosisKeys) + 1; // Inclusive
105 long endTimestamp = getGeneratorEndTimestamp(); // Exclusive
106
107 // Add the startTimestamp to the seed. Otherwise we would generate the same data every hour.
108 random.setSeed(this.config.getSeed() + startTimestamp);
109 PoissonDistribution poisson =
110 new PoissonDistribution(random, this.config.getExposuresPerHour(), POISSON_EPSILON, POISSON_MAX_ITERATIONS);
111
112 if (startTimestamp == endTimestamp) {
113 logger.debug("Skipping test data generation, latest diagnosis keys are still up-to-date.");
114 return;
115 }
116 logger.debug("Generating diagnosis keys between {} and {}...", startTimestamp, endTimestamp);
117 List<DiagnosisKey> newDiagnosisKeys = LongStream.range(startTimestamp, endTimestamp)
118 .mapToObj(submissionTimestamp -> IntStream.range(0, poisson.sample())
119 .mapToObj(__ -> generateDiagnosisKey(submissionTimestamp))
120 .collect(Collectors.toList()))
121 .flatMap(List::stream)
122 .collect(Collectors.toList());
123
124 logger.debug("Writing {} new diagnosis keys to the database...", newDiagnosisKeys.size());
125 diagnosisKeyService.saveDiagnosisKeys(newDiagnosisKeys);
126
127 logger.debug("Test data generation finished successfully.");
128 }
129
130 /**
131 * Returns the submission timestamp (in 1 hour intervals since epoch) of the last diagnosis key in the database (or
132 * the result of {@link TestDataGeneration#getRetentionStartTimestamp} if there are no diagnosis keys in the database
133 * yet.
134 */
135 private long getGeneratorStartTimestamp(List<DiagnosisKey> diagnosisKeys) {
136 if (diagnosisKeys.isEmpty()) {
137 return getRetentionStartTimestamp();
138 } else {
139 DiagnosisKey latestDiagnosisKey = diagnosisKeys.get(diagnosisKeys.size() - 1);
140 return latestDiagnosisKey.getSubmissionTimestamp();
141 }
142 }
143
144 /**
145 * Returns the timestamp (in 1 hour intervals since epoch) of the last full hour. Example: If called at 15:38 UTC,
146 * this function would return the timestamp for today 14:00 UTC.
147 */
148 private long getGeneratorEndTimestamp() {
149 return (LocalDateTime.now().toEpochSecond(ZoneOffset.UTC) / ONE_HOUR_INTERVAL_SECONDS) - 1;
150 }
151
152 /**
153 * Returns the timestamp (in 1 hour intervals since epoch) at which the retention period starts. Example: If the
154 * retention period in the application properties is set to 14 days, then this function would return the timestamp for
155 * 14 days ago (from now) at 00:00 UTC.
156 */
157 private long getRetentionStartTimestamp() {
158 return LocalDate.now().minusDays(retentionDays).atStartOfDay()
159 .toEpochSecond(ZoneOffset.UTC) / ONE_HOUR_INTERVAL_SECONDS;
160 }
161
162 /**
163 * Returns a random diagnosis key with a specific submission timestamp.
164 */
165 private DiagnosisKey generateDiagnosisKey(long submissionTimestamp) {
166 return DiagnosisKey.builder()
167 .withKeyData(generateDiagnosisKeyBytes())
168 .withRollingStartIntervalNumber(generateRollingStartIntervalNumber(submissionTimestamp))
169 .withRollingPeriod(generateRollingPeriod())
170 .withTransmissionRiskLevel(generateTransmissionRiskLevel())
171 .withSubmissionTimestamp(submissionTimestamp)
172 .build();
173 }
174
175 /**
176 * Returns 16 random bytes.
177 */
178 private byte[] generateDiagnosisKeyBytes() {
179 byte[] exposureKey = new byte[16];
180 random.nextBytes(exposureKey);
181 return exposureKey;
182 }
183
184 /**
185 * Returns a random rolling start number (timestamp since when a key was active, represented by a 10 minute interval
186 * counter.) between a specific submission timestamp and the beginning of the retention period.
187 */
188 private int generateRollingStartIntervalNumber(long submissionTimestamp) {
189 long maxRollingStartIntervalNumber =
190 submissionTimestamp * ONE_HOUR_INTERVAL_SECONDS / TEN_MINUTES_INTERVAL_SECONDS;
191 long minRollingStartIntervalNumber =
192 maxRollingStartIntervalNumber
193 - TimeUnit.DAYS.toSeconds(retentionDays) / TEN_MINUTES_INTERVAL_SECONDS;
194 return Math.toIntExact(getRandomBetween(minRollingStartIntervalNumber, maxRollingStartIntervalNumber));
195 }
196
197 /**
198 * Returns a rolling period (number of 10 minute intervals that a key was active for) of 1 day.
199 */
200 private int generateRollingPeriod() {
201 return Math.toIntExact(TimeUnit.DAYS.toSeconds(1) / TEN_MINUTES_INTERVAL_SECONDS);
202 }
203
204 /**
205 * Returns a random number between {@link RiskLevel#RISK_LEVEL_LOWEST_VALUE} and {@link
206 * RiskLevel#RISK_LEVEL_HIGHEST_VALUE}.
207 */
208 private int generateTransmissionRiskLevel() {
209 return Math.toIntExact(
210 getRandomBetween(RiskLevel.RISK_LEVEL_LOWEST_VALUE, RiskLevel.RISK_LEVEL_HIGHEST_VALUE));
211 }
212
213 /**
214 * Returns a random number between {@code minIncluding} and {@code maxIncluding}.
215 */
216 private long getRandomBetween(long minIncluding, long maxIncluding) {
217 return minIncluding + (long) (random.nextDouble() * (maxIncluding - minIncluding));
218 }
219 }
220
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/TestDataGeneration.java]
[start of services/submission/src/main/java/app/coronawarn/server/services/submission/controller/ApiExceptionHandler.java]
1 /*
2 * Corona-Warn-App
3 *
4 * SAP SE and all other contributors /
5 * copyright owners license this file to you under the Apache
6 * License, Version 2.0 (the "License"); you may not use this
7 * file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20 package app.coronawarn.server.services.submission.controller;
21
22 import app.coronawarn.server.common.persistence.exception.InvalidDiagnosisKeyException;
23 import app.coronawarn.server.services.submission.exception.InvalidPayloadException;
24 import com.google.protobuf.InvalidProtocolBufferException;
25 import org.slf4j.Logger;
26 import org.slf4j.LoggerFactory;
27 import org.springframework.http.HttpStatus;
28 import org.springframework.http.converter.HttpMessageNotReadableException;
29 import org.springframework.web.bind.ServletRequestBindingException;
30 import org.springframework.web.bind.annotation.ExceptionHandler;
31 import org.springframework.web.bind.annotation.ResponseStatus;
32 import org.springframework.web.bind.annotation.RestControllerAdvice;
33 import org.springframework.web.context.request.WebRequest;
34
35 @RestControllerAdvice("app.coronawarn.server.services.submission.controller")
36 public class ApiExceptionHandler {
37
38 private static final Logger logger = LoggerFactory.getLogger(ApiExceptionHandler.class);
39
40 @ExceptionHandler(Exception.class)
41 @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
42 public void unknownException(Exception ex, WebRequest wr) {
43 logger.error("Unable to handle {}", wr.getDescription(false), ex);
44 }
45
46 @ExceptionHandler({HttpMessageNotReadableException.class, ServletRequestBindingException.class,
47 InvalidProtocolBufferException.class})
48 @ResponseStatus(HttpStatus.BAD_REQUEST)
49 public void bindingExceptions(Exception ex, WebRequest wr) {
50 logger.error("Binding failed {}", wr.getDescription(false), ex);
51 }
52
53 @ExceptionHandler({InvalidDiagnosisKeyException.class, InvalidPayloadException.class})
54 @ResponseStatus(HttpStatus.BAD_REQUEST)
55 public void diagnosisKeyExceptions(Exception ex, WebRequest wr) {
56 logger.error("Erroneous Submission Payload {}", wr.getDescription(false), ex);
57 }
58 }
59
[end of services/submission/src/main/java/app/coronawarn/server/services/submission/controller/ApiExceptionHandler.java]
[start of services/submission/src/main/java/app/coronawarn/server/services/submission/controller/SubmissionController.java]
1 /*
2 * Corona-Warn-App
3 *
4 * SAP SE and all other contributors /
5 * copyright owners license this file to you under the Apache
6 * License, Version 2.0 (the "License"); you may not use this
7 * file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20 package app.coronawarn.server.services.submission.controller;
21
22 import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
23 import app.coronawarn.server.common.persistence.service.DiagnosisKeyService;
24 import app.coronawarn.server.common.protocols.external.exposurenotification.TemporaryExposureKey;
25 import app.coronawarn.server.common.protocols.internal.SubmissionPayload;
26 import app.coronawarn.server.services.submission.config.SubmissionServiceConfig;
27 import app.coronawarn.server.services.submission.exception.InvalidPayloadException;
28 import app.coronawarn.server.services.submission.verification.TanVerifier;
29 import java.util.ArrayList;
30 import java.util.List;
31 import java.util.concurrent.Executors;
32 import java.util.concurrent.ForkJoinPool;
33 import java.util.concurrent.ScheduledExecutorService;
34 import java.util.concurrent.TimeUnit;
35 import org.apache.commons.math3.distribution.PoissonDistribution;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38 import org.springframework.beans.factory.annotation.Autowired;
39 import org.springframework.http.HttpStatus;
40 import org.springframework.http.ResponseEntity;
41 import org.springframework.util.StopWatch;
42 import org.springframework.web.bind.annotation.PostMapping;
43 import org.springframework.web.bind.annotation.RequestBody;
44 import org.springframework.web.bind.annotation.RequestHeader;
45 import org.springframework.web.bind.annotation.RequestMapping;
46 import org.springframework.web.bind.annotation.RestController;
47 import org.springframework.web.context.request.async.DeferredResult;
48
49 @RestController
50 @RequestMapping("/version/v1")
51 public class SubmissionController {
52
53 private static final Logger logger = LoggerFactory.getLogger(SubmissionController.class);
54 /**
55 * The route to the submission endpoint (version agnostic).
56 */
57 public static final String SUBMISSION_ROUTE = "/diagnosis-keys";
58
59 private final ScheduledExecutorService scheduledExecutor = Executors.newSingleThreadScheduledExecutor();
60 private final ForkJoinPool forkJoinPool = ForkJoinPool.commonPool();
61 private final DiagnosisKeyService diagnosisKeyService;
62 private final TanVerifier tanVerifier;
63 private final Double fakeDelayMovingAverageSamples;
64 private final Integer retentionDays;
65 private final Integer maxNumberOfKeys;
66 private Double fakeDelay;
67
68 @Autowired
69 SubmissionController(DiagnosisKeyService diagnosisKeyService, TanVerifier tanVerifier,
70 SubmissionServiceConfig submissionServiceConfig) {
71 this.diagnosisKeyService = diagnosisKeyService;
72 this.tanVerifier = tanVerifier;
73 fakeDelay = submissionServiceConfig.getInitialFakeDelayMilliseconds();
74 fakeDelayMovingAverageSamples = submissionServiceConfig.getFakeDelayMovingAverageSamples();
75 retentionDays = submissionServiceConfig.getRetentionDays();
76 maxNumberOfKeys = submissionServiceConfig.getMaxNumberOfKeys();
77 }
78
79 /**
80 * Handles diagnosis key submission requests.
81 *
82 * @param exposureKeys The unmarshalled protocol buffers submission payload.
83 * @param fake A header flag, marking fake requests.
84 * @param tan A tan for diagnosis verification.
85 * @return An empty response body.
86 */
87 @PostMapping(SUBMISSION_ROUTE)
88 public DeferredResult<ResponseEntity<Void>> submitDiagnosisKey(
89 @RequestBody SubmissionPayload exposureKeys,
90 @RequestHeader("cwa-fake") Integer fake,
91 @RequestHeader("cwa-authorization") String tan) {
92 if (fake != 0) {
93 return buildFakeDeferredResult();
94 } else {
95 return buildRealDeferredResult(exposureKeys, tan);
96 }
97 }
98
99 private DeferredResult<ResponseEntity<Void>> buildFakeDeferredResult() {
100 DeferredResult<ResponseEntity<Void>> deferredResult = new DeferredResult<>();
101 long delay = new PoissonDistribution(fakeDelay).sample();
102 scheduledExecutor.schedule(() -> deferredResult.setResult(buildSuccessResponseEntity()),
103 delay, TimeUnit.MILLISECONDS);
104 return deferredResult;
105 }
106
107 private DeferredResult<ResponseEntity<Void>> buildRealDeferredResult(SubmissionPayload exposureKeys, String tan) {
108 DeferredResult<ResponseEntity<Void>> deferredResult = new DeferredResult<>();
109 forkJoinPool.submit(() -> {
110 StopWatch stopWatch = new StopWatch();
111 stopWatch.start();
112 if (!this.tanVerifier.verifyTan(tan)) {
113 deferredResult.setResult(buildTanInvalidResponseEntity());
114 } else {
115 try {
116 persistDiagnosisKeysPayload(exposureKeys);
117 deferredResult.setResult(buildSuccessResponseEntity());
118 } catch (Exception e) {
119 deferredResult.setErrorResult(e);
120 }
121 }
122 stopWatch.stop();
123 updateFakeDelay(stopWatch.getTotalTimeMillis());
124 });
125 return deferredResult;
126 }
127
128 /**
129 * Returns a response that indicates successful request processing.
130 */
131 private ResponseEntity<Void> buildSuccessResponseEntity() {
132 return ResponseEntity.ok().build();
133 }
134
135 /**
136 * Returns a response that indicates that an invalid TAN was specified in the request.
137 */
138 private ResponseEntity<Void> buildTanInvalidResponseEntity() {
139 return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
140 }
141
142 /**
143 * Persists the diagnosis keys contained in the specified request payload.
144 *
145 * @param protoBufDiagnosisKeys Diagnosis keys that were specified in the request.
146 * @throws IllegalArgumentException in case the given collection contains {@literal null}.
147 */
148 public void persistDiagnosisKeysPayload(SubmissionPayload protoBufDiagnosisKeys) {
149 List<TemporaryExposureKey> protoBufferKeysList = protoBufDiagnosisKeys.getKeysList();
150 validatePayload(protoBufferKeysList);
151
152 List<DiagnosisKey> diagnosisKeys = new ArrayList<>();
153 for (TemporaryExposureKey protoBufferKey : protoBufferKeysList) {
154 DiagnosisKey diagnosisKey = DiagnosisKey.builder().fromProtoBuf(protoBufferKey).build();
155 if (diagnosisKey.isYoungerThanRetentionThreshold(retentionDays)) {
156 diagnosisKeys.add(diagnosisKey);
157 } else {
158 logger.info("Not persisting a diagnosis key, as it is outdated beyond retention threshold.");
159 }
160 }
161
162 diagnosisKeyService.saveDiagnosisKeys(diagnosisKeys);
163 }
164
165 private void validatePayload(List<TemporaryExposureKey> protoBufKeysList) {
166 if (protoBufKeysList.isEmpty() || protoBufKeysList.size() > maxNumberOfKeys) {
167 throw new InvalidPayloadException(
168 String.format("Number of keys must be between 1 and %s, but is %s.", maxNumberOfKeys, protoBufKeysList));
169 }
170 }
171
172 private synchronized void updateFakeDelay(long realRequestDuration) {
173 fakeDelay = fakeDelay + (1 / fakeDelayMovingAverageSamples) * (realRequestDuration - fakeDelay);
174 }
175 }
176
[end of services/submission/src/main/java/app/coronawarn/server/services/submission/controller/SubmissionController.java]
[start of services/submission/src/main/java/app/coronawarn/server/services/submission/exception/InvalidPayloadException.java]
1 /*
2 * Corona-Warn-App
3 *
4 * SAP SE and all other contributors /
5 * copyright owners license this file to you under the Apache
6 * License, Version 2.0 (the "License"); you may not use this
7 * file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20 package app.coronawarn.server.services.submission.exception;
21
22 /**
23 * Exception thrown to indicate an invalid payload of a
24 * {@link app.coronawarn.server.common.protocols.external.exposurenotification.TemporaryExposureKey}.
25 */
26 public class InvalidPayloadException extends RuntimeException {
27
28 public InvalidPayloadException(String message) {
29 super(message);
30 }
31
32 }
33
[end of services/submission/src/main/java/app/coronawarn/server/services/submission/exception/InvalidPayloadException.java]
</code>
Here is an example of a patch file. It consists of changes to the code base. It specifies the file names, the line numbers of each change, and the removed and added lines. A single patch file can contain changes to multiple files.
<patch>
--- a/file.py
+++ b/file.py
@@ -1,27 +1,35 @@
def euclidean(a, b):
- while b:
- a, b = b, a % b
- return a
+ if b == 0:
+ return a
+ return euclidean(b, a % b)
def bresenham(x0, y0, x1, y1):
points = []
dx = abs(x1 - x0)
dy = abs(y1 - y0)
- sx = 1 if x0 < x1 else -1
- sy = 1 if y0 < y1 else -1
- err = dx - dy
+ x, y = x0, y0
+ sx = -1 if x0 > x1 else 1
+ sy = -1 if y0 > y1 else 1
- while True:
- points.append((x0, y0))
- if x0 == x1 and y0 == y1:
- break
- e2 = 2 * err
- if e2 > -dy:
+ if dx > dy:
+ err = dx / 2.0
+ while x != x1:
+ points.append((x, y))
err -= dy
- x0 += sx
- if e2 < dx:
- err += dx
- y0 += sy
+ if err < 0:
+ y += sy
+ err += dx
+ x += sx
+ else:
+ err = dy / 2.0
+ while y != y1:
+ points.append((x, y))
+ err -= dx
+ if err < 0:
+ x += sx
+ err += dy
+ y += sy
+ points.append((x, y))
return points
</patch>
I need you to solve the provded issue by generating a single patch file that I can apply directly to this repository using git apply. Please respond with a single patch file in the format shown above.
Respond below:
| corona-warn-app/cwa-server | 9ef96cbec24163360512f3d4748a248d6eddd078 | Apple's Proposal for Exposure Key Validation
#92 Current Implementation
We used sensible assumptions for key validation.
## Suggested Enhancement
[Apple proposes](https://developer.apple.com/documentation/exposurenotification/setting_up_an_exposure_notification_server?changes=latest_beta):
> An EN server must reject invalid key files uploaded from a client app. Uploaded key data is considered invalid if:
>
> Any ENIntervalNumber values from the same user are not unique
>
> There are any gaps in the ENIntervalNumber values for a user
>
> Any keys in the file have overlapping time windows
>
> The period of time covered by the data file exceeds 14 days
>
> The TEKRollingPeriod value is not 144
>
> You may optionally want to validate the clock time the device submits.
## Expected Benefits
Adherence to reference implementations.
| Part of https://github.com/corona-warn-app/cwa-server/issues/168 | 2020-05-25T20:36:01 | <patch>
diff --git a/common/persistence/src/main/java/app/coronawarn/server/common/persistence/domain/DiagnosisKey.java b/common/persistence/src/main/java/app/coronawarn/server/common/persistence/domain/DiagnosisKey.java
--- a/common/persistence/src/main/java/app/coronawarn/server/common/persistence/domain/DiagnosisKey.java
+++ b/common/persistence/src/main/java/app/coronawarn/server/common/persistence/domain/DiagnosisKey.java
@@ -36,7 +36,6 @@
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
-import javax.validation.constraints.Min;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.Range;
@@ -46,6 +45,14 @@
@Entity
@Table(name = "diagnosis_key")
public class DiagnosisKey {
+
+ /**
+ * According to "Setting Up an Exposure Notification Server" by Apple, exposure notification servers are expected to
+ * reject any diagnosis keys that do not have a rolling period of a certain fixed value. See
+ * https://developer.apple.com/documentation/exposurenotification/setting_up_an_exposure_notification_server
+ */
+ public static final int EXPECTED_ROLLING_PERIOD = 144;
+
private static final Validator VALIDATOR = Validation.buildDefaultValidatorFactory().getValidator();
@Id
@@ -58,7 +65,8 @@ public class DiagnosisKey {
@ValidRollingStartIntervalNumber
private int rollingStartIntervalNumber;
- @Min(value = 1, message = "Rolling period must be greater than 0.")
+ @Range(min = EXPECTED_ROLLING_PERIOD, max = EXPECTED_ROLLING_PERIOD,
+ message = "Rolling period must be " + EXPECTED_ROLLING_PERIOD + ".")
private int rollingPeriod;
@Range(min = 0, max = 8, message = "Risk level must be between 0 and 8.")
@@ -135,7 +143,7 @@ public long getSubmissionTimestamp() {
* Checks if this diagnosis key falls into the period between now, and the retention threshold.
*
* @param daysToRetain the number of days before a key is outdated
- * @return true, if the rolling start number is in the time span between now, and the given days to retain
+ * @return true, if the rolling start interval number is within the time between now, and the given days to retain
* @throws IllegalArgumentException if {@code daysToRetain} is negative.
*/
public boolean isYoungerThanRetentionThreshold(int daysToRetain) {
@@ -155,7 +163,7 @@ public boolean isYoungerThanRetentionThreshold(int daysToRetain) {
*
* <p><ul>
* <li>Risk level must be between 0 and 8
- * <li>Rolling start number must be greater than 0
+ * <li>Rolling start interval number must be greater than 0
* <li>Rolling start number cannot be in the future
* <li>Rolling period must be positive number
* <li>Key data must be byte array of length 16
diff --git a/common/persistence/src/main/java/app/coronawarn/server/common/persistence/domain/DiagnosisKeyBuilder.java b/common/persistence/src/main/java/app/coronawarn/server/common/persistence/domain/DiagnosisKeyBuilder.java
--- a/common/persistence/src/main/java/app/coronawarn/server/common/persistence/domain/DiagnosisKeyBuilder.java
+++ b/common/persistence/src/main/java/app/coronawarn/server/common/persistence/domain/DiagnosisKeyBuilder.java
@@ -21,7 +21,6 @@
import static app.coronawarn.server.common.persistence.domain.DiagnosisKeyBuilders.Builder;
import static app.coronawarn.server.common.persistence.domain.DiagnosisKeyBuilders.FinalBuilder;
-import static app.coronawarn.server.common.persistence.domain.DiagnosisKeyBuilders.RollingPeriodBuilder;
import static app.coronawarn.server.common.persistence.domain.DiagnosisKeyBuilders.RollingStartIntervalNumberBuilder;
import static app.coronawarn.server.common.persistence.domain.DiagnosisKeyBuilders.TransmissionRiskLevelBuilder;
@@ -38,14 +37,14 @@
* An instance of this builder can be retrieved by calling {@link DiagnosisKey#builder()}. A {@link DiagnosisKey} can
* then be build by either providing the required member values or by passing the respective protocol buffer object.
*/
-public class DiagnosisKeyBuilder implements Builder, RollingStartIntervalNumberBuilder,
- RollingPeriodBuilder, TransmissionRiskLevelBuilder, FinalBuilder {
+public class DiagnosisKeyBuilder implements
+ Builder, RollingStartIntervalNumberBuilder, TransmissionRiskLevelBuilder, FinalBuilder {
private static final Logger logger = LoggerFactory.getLogger(DiagnosisKeyBuilder.class);
private byte[] keyData;
private int rollingStartIntervalNumber;
- private int rollingPeriod;
+ private int rollingPeriod = DiagnosisKey.EXPECTED_ROLLING_PERIOD;
private int transmissionRiskLevel;
private long submissionTimestamp = -1L;
@@ -59,17 +58,11 @@ public RollingStartIntervalNumberBuilder withKeyData(byte[] keyData) {
}
@Override
- public RollingPeriodBuilder withRollingStartIntervalNumber(int rollingStartIntervalNumber) {
+ public TransmissionRiskLevelBuilder withRollingStartIntervalNumber(int rollingStartIntervalNumber) {
this.rollingStartIntervalNumber = rollingStartIntervalNumber;
return this;
}
- @Override
- public TransmissionRiskLevelBuilder withRollingPeriod(int rollingPeriod) {
- this.rollingPeriod = rollingPeriod;
- return this;
- }
-
@Override
public FinalBuilder withTransmissionRiskLevel(int transmissionRiskLevel) {
this.transmissionRiskLevel = transmissionRiskLevel;
@@ -81,8 +74,8 @@ public FinalBuilder fromProtoBuf(TemporaryExposureKey protoBufObject) {
return this
.withKeyData(protoBufObject.getKeyData().toByteArray())
.withRollingStartIntervalNumber(protoBufObject.getRollingStartIntervalNumber())
- .withRollingPeriod(protoBufObject.getRollingPeriod())
- .withTransmissionRiskLevel(protoBufObject.getTransmissionRiskLevel());
+ .withTransmissionRiskLevel(protoBufObject.getTransmissionRiskLevel())
+ .withRollingPeriod(protoBufObject.getRollingPeriod());
}
@Override
@@ -91,6 +84,12 @@ public FinalBuilder withSubmissionTimestamp(long submissionTimestamp) {
return this;
}
+ @Override
+ public FinalBuilder withRollingPeriod(int rollingPeriod) {
+ this.rollingPeriod = rollingPeriod;
+ return this;
+ }
+
@Override
public DiagnosisKey build() {
if (submissionTimestamp < 0) {
diff --git a/common/persistence/src/main/java/app/coronawarn/server/common/persistence/domain/DiagnosisKeyBuilders.java b/common/persistence/src/main/java/app/coronawarn/server/common/persistence/domain/DiagnosisKeyBuilders.java
--- a/common/persistence/src/main/java/app/coronawarn/server/common/persistence/domain/DiagnosisKeyBuilders.java
+++ b/common/persistence/src/main/java/app/coronawarn/server/common/persistence/domain/DiagnosisKeyBuilders.java
@@ -48,25 +48,13 @@ interface Builder {
interface RollingStartIntervalNumberBuilder {
/**
- * Adds the specified rolling start number to this builder.
+ * Adds the specified rolling start interval number to this builder.
*
* @param rollingStartIntervalNumber number describing when a key starts. It is equal to
* startTimeOfKeySinceEpochInSecs / (60 * 10).
* @return this Builder instance.
*/
- RollingPeriodBuilder withRollingStartIntervalNumber(int rollingStartIntervalNumber);
- }
-
- interface RollingPeriodBuilder {
-
- /**
- * Adds the specified rolling period to this builder.
- *
- * @param rollingPeriod Number describing how long a key is valid. It is expressed in increments
- * of 10 minutes (e.g. 144 for 24 hours).
- * @return this Builder instance.
- */
- TransmissionRiskLevelBuilder withRollingPeriod(int rollingPeriod);
+ TransmissionRiskLevelBuilder withRollingStartIntervalNumber(int rollingStartIntervalNumber);
}
interface TransmissionRiskLevelBuilder {
@@ -90,6 +78,16 @@ interface FinalBuilder {
*/
FinalBuilder withSubmissionTimestamp(long submissionTimestamp);
+ /**
+ * Adds the specified rolling period to this builder. If not specified, the rolling period defaults to {@link
+ * DiagnosisKey#EXPECTED_ROLLING_PERIOD}
+ *
+ * @param rollingPeriod Number describing how long a key is valid. It is expressed in increments of 10 minutes (e.g.
+ * 144 for 24 hours).
+ * @return this Builder instance.
+ */
+ FinalBuilder withRollingPeriod(int rollingPeriod);
+
/**
* Builds a {@link DiagnosisKey} instance. If no submission timestamp has been specified it will be set to "now" as
* hours since epoch.
diff --git a/common/persistence/src/main/java/app/coronawarn/server/common/persistence/domain/validation/ValidRollingStartIntervalNumber.java b/common/persistence/src/main/java/app/coronawarn/server/common/persistence/domain/validation/ValidRollingStartIntervalNumber.java
--- a/common/persistence/src/main/java/app/coronawarn/server/common/persistence/domain/validation/ValidRollingStartIntervalNumber.java
+++ b/common/persistence/src/main/java/app/coronawarn/server/common/persistence/domain/validation/ValidRollingStartIntervalNumber.java
@@ -35,7 +35,7 @@
*
* @return the error message
*/
- String message() default "Rolling start number must be greater 0 and cannot be in the future.";
+ String message() default "Rolling start interval number must be greater 0 and cannot be in the future.";
/**
* Groups.
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/TestDataGeneration.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/TestDataGeneration.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/TestDataGeneration.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/TestDataGeneration.java
@@ -71,7 +71,7 @@ public class TestDataGeneration implements ApplicationRunner {
// The submission timestamp is counted in 1 hour intervals since epoch
private static final long ONE_HOUR_INTERVAL_SECONDS = TimeUnit.HOURS.toSeconds(1);
- // The rolling start number is counted in 10 minute intervals since epoch
+ // The rolling start interval number is counted in 10 minute intervals since epoch
private static final long TEN_MINUTES_INTERVAL_SECONDS = TimeUnit.MINUTES.toSeconds(10);
/**
@@ -166,7 +166,6 @@ private DiagnosisKey generateDiagnosisKey(long submissionTimestamp) {
return DiagnosisKey.builder()
.withKeyData(generateDiagnosisKeyBytes())
.withRollingStartIntervalNumber(generateRollingStartIntervalNumber(submissionTimestamp))
- .withRollingPeriod(generateRollingPeriod())
.withTransmissionRiskLevel(generateTransmissionRiskLevel())
.withSubmissionTimestamp(submissionTimestamp)
.build();
@@ -182,8 +181,8 @@ private byte[] generateDiagnosisKeyBytes() {
}
/**
- * Returns a random rolling start number (timestamp since when a key was active, represented by a 10 minute interval
- * counter.) between a specific submission timestamp and the beginning of the retention period.
+ * Returns a random rolling start interval number (timestamp since when a key was active, represented by a 10 minute
+ * interval counter) between a specific submission timestamp and the beginning of the retention period.
*/
private int generateRollingStartIntervalNumber(long submissionTimestamp) {
long maxRollingStartIntervalNumber =
@@ -194,13 +193,6 @@ private int generateRollingStartIntervalNumber(long submissionTimestamp) {
return Math.toIntExact(getRandomBetween(minRollingStartIntervalNumber, maxRollingStartIntervalNumber));
}
- /**
- * Returns a rolling period (number of 10 minute intervals that a key was active for) of 1 day.
- */
- private int generateRollingPeriod() {
- return Math.toIntExact(TimeUnit.DAYS.toSeconds(1) / TEN_MINUTES_INTERVAL_SECONDS);
- }
-
/**
* Returns a random number between {@link RiskLevel#RISK_LEVEL_LOWEST_VALUE} and {@link
* RiskLevel#RISK_LEVEL_HIGHEST_VALUE}.
diff --git a/services/submission/src/main/java/app/coronawarn/server/services/submission/controller/ApiExceptionHandler.java b/services/submission/src/main/java/app/coronawarn/server/services/submission/controller/ApiExceptionHandler.java
--- a/services/submission/src/main/java/app/coronawarn/server/services/submission/controller/ApiExceptionHandler.java
+++ b/services/submission/src/main/java/app/coronawarn/server/services/submission/controller/ApiExceptionHandler.java
@@ -20,8 +20,8 @@
package app.coronawarn.server.services.submission.controller;
import app.coronawarn.server.common.persistence.exception.InvalidDiagnosisKeyException;
-import app.coronawarn.server.services.submission.exception.InvalidPayloadException;
import com.google.protobuf.InvalidProtocolBufferException;
+import javax.validation.ConstraintViolationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
@@ -50,7 +50,7 @@ public void bindingExceptions(Exception ex, WebRequest wr) {
logger.error("Binding failed {}", wr.getDescription(false), ex);
}
- @ExceptionHandler({InvalidDiagnosisKeyException.class, InvalidPayloadException.class})
+ @ExceptionHandler({InvalidDiagnosisKeyException.class, ConstraintViolationException.class})
@ResponseStatus(HttpStatus.BAD_REQUEST)
public void diagnosisKeyExceptions(Exception ex, WebRequest wr) {
logger.error("Erroneous Submission Payload {}", wr.getDescription(false), ex);
diff --git a/services/submission/src/main/java/app/coronawarn/server/services/submission/controller/SubmissionController.java b/services/submission/src/main/java/app/coronawarn/server/services/submission/controller/SubmissionController.java
--- a/services/submission/src/main/java/app/coronawarn/server/services/submission/controller/SubmissionController.java
+++ b/services/submission/src/main/java/app/coronawarn/server/services/submission/controller/SubmissionController.java
@@ -24,7 +24,7 @@
import app.coronawarn.server.common.protocols.external.exposurenotification.TemporaryExposureKey;
import app.coronawarn.server.common.protocols.internal.SubmissionPayload;
import app.coronawarn.server.services.submission.config.SubmissionServiceConfig;
-import app.coronawarn.server.services.submission.exception.InvalidPayloadException;
+import app.coronawarn.server.services.submission.validation.ValidSubmissionPayload;
import app.coronawarn.server.services.submission.verification.TanVerifier;
import java.util.ArrayList;
import java.util.List;
@@ -39,6 +39,7 @@
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StopWatch;
+import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
@@ -48,6 +49,7 @@
@RestController
@RequestMapping("/version/v1")
+@Validated
public class SubmissionController {
private static final Logger logger = LoggerFactory.getLogger(SubmissionController.class);
@@ -62,7 +64,6 @@ public class SubmissionController {
private final TanVerifier tanVerifier;
private final Double fakeDelayMovingAverageSamples;
private final Integer retentionDays;
- private final Integer maxNumberOfKeys;
private Double fakeDelay;
@Autowired
@@ -73,7 +74,6 @@ public class SubmissionController {
fakeDelay = submissionServiceConfig.getInitialFakeDelayMilliseconds();
fakeDelayMovingAverageSamples = submissionServiceConfig.getFakeDelayMovingAverageSamples();
retentionDays = submissionServiceConfig.getRetentionDays();
- maxNumberOfKeys = submissionServiceConfig.getMaxNumberOfKeys();
}
/**
@@ -86,7 +86,7 @@ public class SubmissionController {
*/
@PostMapping(SUBMISSION_ROUTE)
public DeferredResult<ResponseEntity<Void>> submitDiagnosisKey(
- @RequestBody SubmissionPayload exposureKeys,
+ @ValidSubmissionPayload @RequestBody SubmissionPayload exposureKeys,
@RequestHeader("cwa-fake") Integer fake,
@RequestHeader("cwa-authorization") String tan) {
if (fake != 0) {
@@ -147,9 +147,8 @@ private ResponseEntity<Void> buildTanInvalidResponseEntity() {
*/
public void persistDiagnosisKeysPayload(SubmissionPayload protoBufDiagnosisKeys) {
List<TemporaryExposureKey> protoBufferKeysList = protoBufDiagnosisKeys.getKeysList();
- validatePayload(protoBufferKeysList);
-
List<DiagnosisKey> diagnosisKeys = new ArrayList<>();
+
for (TemporaryExposureKey protoBufferKey : protoBufferKeysList) {
DiagnosisKey diagnosisKey = DiagnosisKey.builder().fromProtoBuf(protoBufferKey).build();
if (diagnosisKey.isYoungerThanRetentionThreshold(retentionDays)) {
@@ -162,13 +161,6 @@ public void persistDiagnosisKeysPayload(SubmissionPayload protoBufDiagnosisKeys)
diagnosisKeyService.saveDiagnosisKeys(diagnosisKeys);
}
- private void validatePayload(List<TemporaryExposureKey> protoBufKeysList) {
- if (protoBufKeysList.isEmpty() || protoBufKeysList.size() > maxNumberOfKeys) {
- throw new InvalidPayloadException(
- String.format("Number of keys must be between 1 and %s, but is %s.", maxNumberOfKeys, protoBufKeysList));
- }
- }
-
private synchronized void updateFakeDelay(long realRequestDuration) {
fakeDelay = fakeDelay + (1 / fakeDelayMovingAverageSamples) * (realRequestDuration - fakeDelay);
}
diff --git a/services/submission/src/main/java/app/coronawarn/server/services/submission/exception/InvalidPayloadException.java b/services/submission/src/main/java/app/coronawarn/server/services/submission/exception/InvalidPayloadException.java
deleted file mode 100644
--- a/services/submission/src/main/java/app/coronawarn/server/services/submission/exception/InvalidPayloadException.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Corona-Warn-App
- *
- * SAP SE and all other contributors /
- * copyright owners license this file to you under the Apache
- * License, Version 2.0 (the "License"); you may not use this
- * file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://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 for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package app.coronawarn.server.services.submission.exception;
-
-/**
- * Exception thrown to indicate an invalid payload of a
- * {@link app.coronawarn.server.common.protocols.external.exposurenotification.TemporaryExposureKey}.
- */
-public class InvalidPayloadException extends RuntimeException {
-
- public InvalidPayloadException(String message) {
- super(message);
- }
-
-}
diff --git a/services/submission/src/main/java/app/coronawarn/server/services/submission/validation/ValidSubmissionPayload.java b/services/submission/src/main/java/app/coronawarn/server/services/submission/validation/ValidSubmissionPayload.java
new file mode 100644
--- /dev/null
+++ b/services/submission/src/main/java/app/coronawarn/server/services/submission/validation/ValidSubmissionPayload.java
@@ -0,0 +1,148 @@
+/*
+ * Corona-Warn-App
+ * SAP SE and all other contributors /
+ * copyright owners license this file to you under the Apache
+ * License, Version 2.0 (the "License"); you may not use this
+ * file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * http://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 for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package app.coronawarn.server.services.submission.validation;
+
+import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
+import app.coronawarn.server.common.protocols.external.exposurenotification.TemporaryExposureKey;
+import app.coronawarn.server.common.protocols.internal.SubmissionPayload;
+import app.coronawarn.server.services.submission.config.SubmissionServiceConfig;
+import java.lang.annotation.Documented;
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Objects;
+import javax.validation.Constraint;
+import javax.validation.ConstraintValidator;
+import javax.validation.ConstraintValidatorContext;
+import javax.validation.Payload;
+
+@Constraint(validatedBy = ValidSubmissionPayload.SubmissionPayloadValidator.class)
+@Target({ElementType.PARAMETER})
+@Retention(RetentionPolicy.RUNTIME)
+@Documented
+public @interface ValidSubmissionPayload {
+
+ /**
+ * Error message.
+ *
+ * @return the error message
+ */
+ String message() default "Invalid diagnosis key submission payload.";
+
+ /**
+ * Groups.
+ *
+ * @return
+ */
+ Class<?>[] groups() default {};
+
+ /**
+ * Payload.
+ *
+ * @return
+ */
+ Class<? extends Payload>[] payload() default {};
+
+ class SubmissionPayloadValidator implements
+ ConstraintValidator<ValidSubmissionPayload, SubmissionPayload> {
+
+ private final int maxNumberOfKeys;
+
+ public SubmissionPayloadValidator(SubmissionServiceConfig submissionServiceConfig) {
+ maxNumberOfKeys = submissionServiceConfig.getMaxNumberOfKeys();
+ }
+
+ /**
+ * Validates the following constraints.
+ * <ul>
+ * <li>StartIntervalNumber values from the same {@link SubmissionPayload} shall be unique.</li>
+ * <li>There must be no gaps for StartIntervalNumber values for a user.</li>
+ * <li>There must not be any keys in the {@link SubmissionPayload} have overlapping time windows.</li>
+ * <li>The period of time covered by the data file must not exceed the configured maximum number of days.</li>
+ * </ul>
+ */
+ @Override
+ public boolean isValid(SubmissionPayload submissionPayload, ConstraintValidatorContext validatorContext) {
+ List<TemporaryExposureKey> exposureKeys = submissionPayload.getKeysList();
+ validatorContext.disableDefaultConstraintViolation();
+
+ if (Objects.isNull(exposureKeys)) {
+ addViolation(validatorContext, "Field 'keys' points to Null.");
+ return false;
+ }
+
+ boolean isValid = checkKeyCollectionSize(exposureKeys, validatorContext);
+ isValid &= checkUniqueStartIntervalNumbers(exposureKeys, validatorContext);
+ isValid &= checkNoGapsInTimeWindow(exposureKeys, validatorContext);
+
+ return isValid;
+ }
+
+ private void addViolation(ConstraintValidatorContext validatorContext, String message) {
+ validatorContext.buildConstraintViolationWithTemplate(message).addConstraintViolation();
+ }
+
+ private boolean checkKeyCollectionSize(List<TemporaryExposureKey> exposureKeys,
+ ConstraintValidatorContext validatorContext) {
+ if (exposureKeys.isEmpty() || exposureKeys.size() > maxNumberOfKeys) {
+ addViolation(validatorContext, String.format(
+ "Number of keys must be between 1 and %s, but is %s.", maxNumberOfKeys, exposureKeys.size()));
+ return false;
+ }
+ return true;
+ }
+
+ private boolean checkUniqueStartIntervalNumbers(List<TemporaryExposureKey> exposureKeys,
+ ConstraintValidatorContext validatorContext) {
+ Integer[] startIntervalNumbers = exposureKeys.stream()
+ .mapToInt(TemporaryExposureKey::getRollingStartIntervalNumber).boxed().toArray(Integer[]::new);
+ long distinctSize = Arrays.stream(startIntervalNumbers)
+ .distinct()
+ .count();
+
+ if (distinctSize < exposureKeys.size()) {
+ addViolation(validatorContext, String.format(
+ "Duplicate StartIntervalNumber found. StartIntervalNumbers: %s", startIntervalNumbers));
+ return false;
+ }
+ return true;
+ }
+
+ private boolean checkNoGapsInTimeWindow(List<TemporaryExposureKey> exposureKeys,
+ ConstraintValidatorContext validatorContext) {
+ if (exposureKeys.size() < 2) {
+ return true;
+ }
+
+ Integer[] sortedStartIntervalNumbers = exposureKeys.stream()
+ .mapToInt(TemporaryExposureKey::getRollingStartIntervalNumber)
+ .sorted().boxed().toArray(Integer[]::new);
+
+ for (int i = 1; i < sortedStartIntervalNumbers.length; i++) {
+ if (sortedStartIntervalNumbers[i] != sortedStartIntervalNumbers[i - 1] + DiagnosisKey.EXPECTED_ROLLING_PERIOD) {
+ addViolation(validatorContext, String.format(
+ "Subsequent intervals do not align. StartIntervalNumbers: %s", sortedStartIntervalNumbers));
+ return false;
+ }
+ }
+ return true;
+ }
+ }
+}
</patch> | diff --git a/common/persistence/src/test/java/app/coronawarn/server/common/persistence/domain/DiagnosisKeyBuilderTest.java b/common/persistence/src/test/java/app/coronawarn/server/common/persistence/domain/DiagnosisKeyBuilderTest.java
--- a/common/persistence/src/test/java/app/coronawarn/server/common/persistence/domain/DiagnosisKeyBuilderTest.java
+++ b/common/persistence/src/test/java/app/coronawarn/server/common/persistence/domain/DiagnosisKeyBuilderTest.java
@@ -38,7 +38,6 @@ class DiagnosisKeyBuilderTest {
private final byte[] expKeyData = "16-bytelongarray".getBytes(Charset.defaultCharset());
private final int expRollingStartIntervalNumber = 73800;
- private final int expRollingPeriod = 144;
private final int expTransmissionRiskLevel = 1;
private final long expSubmissionTimestamp = 2L;
@@ -48,7 +47,7 @@ void buildFromProtoBufObjWithSubmissionTimestamp() {
.newBuilder()
.setKeyData(ByteString.copyFrom(this.expKeyData))
.setRollingStartIntervalNumber(this.expRollingStartIntervalNumber)
- .setRollingPeriod(this.expRollingPeriod)
+ .setRollingPeriod(DiagnosisKey.EXPECTED_ROLLING_PERIOD)
.setTransmissionRiskLevel(this.expTransmissionRiskLevel)
.build();
@@ -66,7 +65,7 @@ void buildFromProtoBufObjWithoutSubmissionTimestamp() {
.newBuilder()
.setKeyData(ByteString.copyFrom(this.expKeyData))
.setRollingStartIntervalNumber(this.expRollingStartIntervalNumber)
- .setRollingPeriod(this.expRollingPeriod)
+ .setRollingPeriod(DiagnosisKey.EXPECTED_ROLLING_PERIOD)
.setTransmissionRiskLevel(this.expTransmissionRiskLevel)
.build();
@@ -80,7 +79,6 @@ void buildSuccessivelyWithSubmissionTimestamp() {
DiagnosisKey actDiagnosisKey = DiagnosisKey.builder()
.withKeyData(this.expKeyData)
.withRollingStartIntervalNumber(this.expRollingStartIntervalNumber)
- .withRollingPeriod(this.expRollingPeriod)
.withTransmissionRiskLevel(this.expTransmissionRiskLevel)
.withSubmissionTimestamp(this.expSubmissionTimestamp).build();
@@ -92,18 +90,27 @@ void buildSuccessivelyWithoutSubmissionTimestamp() {
DiagnosisKey actDiagnosisKey = DiagnosisKey.builder()
.withKeyData(this.expKeyData)
.withRollingStartIntervalNumber(this.expRollingStartIntervalNumber)
- .withRollingPeriod(this.expRollingPeriod)
.withTransmissionRiskLevel(this.expTransmissionRiskLevel).build();
assertDiagnosisKeyEquals(actDiagnosisKey);
}
@Test
- void rollingStartIntervalNumberDoesNotThrowForValid() {
- assertThatCode(() -> keyWithRollingStartIntervalNumber(4200)).doesNotThrowAnyException();
+ void buildSuccessivelyWithRollingPeriod() {
+ DiagnosisKey actDiagnosisKey = DiagnosisKey.builder()
+ .withKeyData(this.expKeyData)
+ .withRollingStartIntervalNumber(this.expRollingStartIntervalNumber)
+ .withTransmissionRiskLevel(this.expTransmissionRiskLevel)
+ .withSubmissionTimestamp(this.expSubmissionTimestamp)
+ .withRollingPeriod(DiagnosisKey.EXPECTED_ROLLING_PERIOD).build();
- // Timestamp: 05/16/2020 @ 00:00 in hours
- assertThatCode(() -> keyWithRollingStartIntervalNumber(441552)).doesNotThrowAnyException();
+ assertDiagnosisKeyEquals(actDiagnosisKey, this.expSubmissionTimestamp);
+ }
+
+ @ParameterizedTest
+ @ValueSource(ints = {4200, 441552})
+ void rollingStartIntervalNumberDoesNotThrowForValid(int validRollingStartIntervalNumber) {
+ assertThatCode(() -> keyWithRollingStartIntervalNumber(validRollingStartIntervalNumber)).doesNotThrowAnyException();
}
@Test
@@ -111,7 +118,7 @@ void rollingStartIntervalNumberCannotBeInFuture() {
assertThat(catchThrowable(() -> keyWithRollingStartIntervalNumber(Integer.MAX_VALUE)))
.isInstanceOf(InvalidDiagnosisKeyException.class)
.hasMessage(
- "[Rolling start number must be greater 0 and cannot be in the future. Invalid Value: "
+ "[Rolling start interval number must be greater 0 and cannot be in the future. Invalid Value: "
+ Integer.MAX_VALUE + "]");
long tomorrow = LocalDate
@@ -123,7 +130,7 @@ void rollingStartIntervalNumberCannotBeInFuture() {
.isInstanceOf(InvalidDiagnosisKeyException.class)
.hasMessage(
String.format(
- "[Rolling start number must be greater 0 and cannot be in the future. Invalid Value: %s]",
+ "[Rolling start interval number must be greater 0 and cannot be in the future. Invalid Value: %s]",
tomorrow));
}
@@ -133,7 +140,6 @@ void failsForInvalidRollingStartIntervalNumber() {
catchThrowable(() -> DiagnosisKey.builder()
.withKeyData(this.expKeyData)
.withRollingStartIntervalNumber(0)
- .withRollingPeriod(this.expRollingPeriod)
.withTransmissionRiskLevel(this.expTransmissionRiskLevel).build()
)
).isInstanceOf(InvalidDiagnosisKeyException.class);
@@ -155,17 +161,17 @@ void transmissionRiskLevelDoesNotThrowForValid(int validRiskLevel) {
}
@ParameterizedTest
- @ValueSource(ints = {0, -3})
- void rollingPeriodMustBeLargerThanZero(int invalidRollingPeriod) {
+ @ValueSource(ints = {-3, 143, 145})
+ void rollingPeriodMustBeEpectedValue(int invalidRollingPeriod) {
assertThat(catchThrowable(() -> keyWithRollingPeriod(invalidRollingPeriod)))
.isInstanceOf(InvalidDiagnosisKeyException.class)
- .hasMessage(
- "[Rolling period must be greater than 0. Invalid Value: " + invalidRollingPeriod + "]");
+ .hasMessage("[Rolling period must be " + DiagnosisKey.EXPECTED_ROLLING_PERIOD
+ + ". Invalid Value: " + invalidRollingPeriod + "]");
}
@Test
void rollingPeriodDoesNotThrowForValid() {
- assertThatCode(() -> keyWithRollingPeriod(144)).doesNotThrowAnyException();
+ assertThatCode(() -> keyWithRollingPeriod(DiagnosisKey.EXPECTED_ROLLING_PERIOD)).doesNotThrowAnyException();
}
@ParameterizedTest
@@ -186,7 +192,6 @@ private DiagnosisKey keyWithKeyData(byte[] expKeyData) {
return DiagnosisKey.builder()
.withKeyData(expKeyData)
.withRollingStartIntervalNumber(expRollingStartIntervalNumber)
- .withRollingPeriod(expRollingPeriod)
.withTransmissionRiskLevel(expTransmissionRiskLevel).build();
}
@@ -194,7 +199,6 @@ private DiagnosisKey keyWithRollingStartIntervalNumber(int expRollingStartInterv
return DiagnosisKey.builder()
.withKeyData(expKeyData)
.withRollingStartIntervalNumber(expRollingStartIntervalNumber)
- .withRollingPeriod(expRollingPeriod)
.withTransmissionRiskLevel(expTransmissionRiskLevel).build();
}
@@ -202,15 +206,14 @@ private DiagnosisKey keyWithRollingPeriod(int expRollingPeriod) {
return DiagnosisKey.builder()
.withKeyData(expKeyData)
.withRollingStartIntervalNumber(expRollingStartIntervalNumber)
- .withRollingPeriod(expRollingPeriod)
- .withTransmissionRiskLevel(expTransmissionRiskLevel).build();
+ .withTransmissionRiskLevel(expTransmissionRiskLevel)
+ .withRollingPeriod(expRollingPeriod).build();
}
private DiagnosisKey keyWithRiskLevel(int expTransmissionRiskLevel) {
return DiagnosisKey.builder()
.withKeyData(expKeyData)
.withRollingStartIntervalNumber(expRollingStartIntervalNumber)
- .withRollingPeriod(expRollingPeriod)
.withTransmissionRiskLevel(expTransmissionRiskLevel).build();
}
@@ -226,7 +229,7 @@ private void assertDiagnosisKeyEquals(DiagnosisKey actDiagnosisKey, long expSubm
assertThat(actDiagnosisKey.getSubmissionTimestamp()).isEqualTo(expSubmissionTimestamp);
assertThat(actDiagnosisKey.getKeyData()).isEqualTo(this.expKeyData);
assertThat(actDiagnosisKey.getRollingStartIntervalNumber()).isEqualTo(this.expRollingStartIntervalNumber);
- assertThat(actDiagnosisKey.getRollingPeriod()).isEqualTo(this.expRollingPeriod);
+ assertThat(actDiagnosisKey.getRollingPeriod()).isEqualTo(DiagnosisKey.EXPECTED_ROLLING_PERIOD);
assertThat(actDiagnosisKey.getTransmissionRiskLevel()).isEqualTo(this.expTransmissionRiskLevel);
}
}
diff --git a/common/persistence/src/test/java/app/coronawarn/server/common/persistence/domain/DiagnosisKeyServiceMockedRepositoryTest.java b/common/persistence/src/test/java/app/coronawarn/server/common/persistence/domain/DiagnosisKeyServiceMockedRepositoryTest.java
--- a/common/persistence/src/test/java/app/coronawarn/server/common/persistence/domain/DiagnosisKeyServiceMockedRepositoryTest.java
+++ b/common/persistence/src/test/java/app/coronawarn/server/common/persistence/domain/DiagnosisKeyServiceMockedRepositoryTest.java
@@ -37,7 +37,6 @@ class DiagnosisKeyServiceMockedRepositoryTest {
static final byte[] expKeyData = "16-bytelongarray".getBytes(Charset.defaultCharset());
static final int expRollingStartIntervalNumber = 73800;
- static final int expRollingPeriod = 144;
static final int expTransmissionRiskLevel = 1;
@Autowired
@@ -82,12 +81,12 @@ private void mockInvalidKeyInDb(List<DiagnosisKey> keys) {
private DiagnosisKey validKey(long expSubmissionTimestamp) {
return new DiagnosisKey(expKeyData, expRollingStartIntervalNumber,
- expRollingPeriod, expTransmissionRiskLevel, expSubmissionTimestamp);
+ DiagnosisKey.EXPECTED_ROLLING_PERIOD, expTransmissionRiskLevel, expSubmissionTimestamp);
}
private DiagnosisKey invalidKey(long expSubmissionTimestamp) {
byte[] expKeyData = "17--bytelongarray".getBytes(Charset.defaultCharset());
return new DiagnosisKey(expKeyData, expRollingStartIntervalNumber,
- expRollingPeriod, expTransmissionRiskLevel, expSubmissionTimestamp);
+ DiagnosisKey.EXPECTED_ROLLING_PERIOD, expTransmissionRiskLevel, expSubmissionTimestamp);
}
}
diff --git a/common/persistence/src/test/java/app/coronawarn/server/common/persistence/service/DiagnosisKeyServiceTest.java b/common/persistence/src/test/java/app/coronawarn/server/common/persistence/service/DiagnosisKeyServiceTest.java
--- a/common/persistence/src/test/java/app/coronawarn/server/common/persistence/service/DiagnosisKeyServiceTest.java
+++ b/common/persistence/src/test/java/app/coronawarn/server/common/persistence/service/DiagnosisKeyServiceTest.java
@@ -137,7 +137,6 @@ void testNoPersistOnValidationError() {
var keys = List.of(DiagnosisKey.builder()
.withKeyData(new byte[16])
.withRollingStartIntervalNumber((int) (OffsetDateTime.now(UTC).toEpochSecond() / 600))
- .withRollingPeriod(1)
.withTransmissionRiskLevel(2)
.withSubmissionTimestamp(0L).build());
@@ -153,7 +152,6 @@ public static DiagnosisKey buildDiagnosisKeyForSubmissionTimestamp(long submissi
return DiagnosisKey.builder()
.withKeyData(new byte[16])
.withRollingStartIntervalNumber(600)
- .withRollingPeriod(1)
.withTransmissionRiskLevel(2)
.withSubmissionTimestamp(submissionTimeStamp).build();
}
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/common/Helpers.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/common/Helpers.java
--- a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/common/Helpers.java
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/common/Helpers.java
@@ -36,7 +36,6 @@ public static DiagnosisKey buildDiagnosisKeyForSubmissionTimestamp(long submissi
return DiagnosisKey.builder()
.withKeyData(new byte[16])
.withRollingStartIntervalNumber(600)
- .withRollingPeriod(1)
.withTransmissionRiskLevel(2)
.withSubmissionTimestamp(submissionTimeStamp).build();
}
diff --git a/services/submission/src/test/java/app/coronawarn/server/services/submission/ServerApplicationTests.java b/services/submission/src/test/java/app/coronawarn/server/services/submission/ServerApplicationTests.java
--- a/services/submission/src/test/java/app/coronawarn/server/services/submission/ServerApplicationTests.java
+++ b/services/submission/src/test/java/app/coronawarn/server/services/submission/ServerApplicationTests.java
@@ -25,6 +25,8 @@
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.test.mock.mockito.MockBean;
+import org.springframework.boot.test.web.client.TestRestTemplate;
@SpringBootTest
class ServerApplicationTests {
@@ -32,6 +34,9 @@ class ServerApplicationTests {
@Autowired
private SubmissionController controller;
+ @MockBean
+ private TestRestTemplate testRestTemplate;
+
@Test
void contextLoads() {
assertThat(this.controller).isNotNull();
diff --git a/services/submission/src/test/java/app/coronawarn/server/services/submission/controller/PayloadValidationTest.java b/services/submission/src/test/java/app/coronawarn/server/services/submission/controller/PayloadValidationTest.java
new file mode 100644
--- /dev/null
+++ b/services/submission/src/test/java/app/coronawarn/server/services/submission/controller/PayloadValidationTest.java
@@ -0,0 +1,136 @@
+/*
+ * Corona-Warn-App
+ *
+ * SAP SE and all other contributors /
+ * copyright owners license this file to you under the Apache
+ * License, Version 2.0 (the "License"); you may not use this
+ * file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://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 for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package app.coronawarn.server.services.submission.controller;
+
+import static app.coronawarn.server.services.submission.controller.RequestExecutor.VALID_KEY_DATA_1;
+import static app.coronawarn.server.services.submission.controller.RequestExecutor.VALID_KEY_DATA_2;
+import static app.coronawarn.server.services.submission.controller.RequestExecutor.VALID_KEY_DATA_3;
+import static app.coronawarn.server.services.submission.controller.RequestExecutor.buildOkHeaders;
+import static app.coronawarn.server.services.submission.controller.RequestExecutor.buildTemporaryExposureKey;
+import static app.coronawarn.server.services.submission.controller.RequestExecutor.createRollingStartIntervalNumber;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.when;
+import static org.springframework.http.HttpStatus.BAD_REQUEST;
+import static org.springframework.http.HttpStatus.OK;
+
+import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
+import app.coronawarn.server.common.protocols.external.exposurenotification.TemporaryExposureKey;
+import app.coronawarn.server.services.submission.verification.TanVerifier;
+import java.util.ArrayList;
+import java.util.Collection;
+import org.assertj.core.util.Lists;
+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 org.springframework.boot.test.mock.mockito.MockBean;
+import org.springframework.http.ResponseEntity;
+
+@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
+class PayloadValidationTest {
+
+ @MockBean
+ private TanVerifier tanVerifier;
+
+ @BeforeEach
+ public void setUpMocks() {
+ when(tanVerifier.verifyTan(anyString())).thenReturn(true);
+ }
+
+ @Autowired
+ RequestExecutor executor;
+
+ @Test
+ void check400ResponseStatusForMissingKeys() {
+ ResponseEntity<Void> actResponse = executor.executeRequest(Lists.emptyList(), buildOkHeaders());
+ assertThat(actResponse.getStatusCode()).isEqualTo(BAD_REQUEST);
+ }
+
+ @Test
+ void check400ResponseStatusForTooManyKeys() {
+ ResponseEntity<Void> actResponse = executor.executeRequest(buildPayloadWithTooManyKeys(), buildOkHeaders());
+
+ assertThat(actResponse.getStatusCode()).isEqualTo(BAD_REQUEST);
+ }
+
+ private Collection<TemporaryExposureKey> buildPayloadWithTooManyKeys() {
+ ArrayList<TemporaryExposureKey> tooMany = new ArrayList<>();
+ for (int i = 0; i <= 20; i++) {
+ tooMany.add(buildTemporaryExposureKey(VALID_KEY_DATA_1, createRollingStartIntervalNumber(2), 3));
+ }
+ return tooMany;
+ }
+
+ @Test
+ void check400ResponseStatusForDuplicateStartIntervalNumber() {
+ int rollingStartIntervalNumber = createRollingStartIntervalNumber(2);
+ var keysWithDuplicateStartIntervalNumber = Lists.list(
+ buildTemporaryExposureKey(VALID_KEY_DATA_1, rollingStartIntervalNumber, 1),
+ buildTemporaryExposureKey(VALID_KEY_DATA_2, rollingStartIntervalNumber, 2));
+
+ ResponseEntity<Void> actResponse = executor.executeRequest(keysWithDuplicateStartIntervalNumber, buildOkHeaders());
+
+ assertThat(actResponse.getStatusCode()).isEqualTo(BAD_REQUEST);
+ }
+
+ @Test
+ void check400ResponseStatusForGapsInTimeIntervals() {
+ int rollingStartIntervalNumber1 = createRollingStartIntervalNumber(6);
+ int rollingStartIntervalNumber2 = rollingStartIntervalNumber1 + DiagnosisKey.EXPECTED_ROLLING_PERIOD;
+ int rollingStartIntervalNumber3 = rollingStartIntervalNumber2 + 2 * DiagnosisKey.EXPECTED_ROLLING_PERIOD;
+ var keysWithDuplicateStartIntervalNumber = Lists.list(
+ buildTemporaryExposureKey(VALID_KEY_DATA_1, rollingStartIntervalNumber1, 1),
+ buildTemporaryExposureKey(VALID_KEY_DATA_3, rollingStartIntervalNumber3, 3),
+ buildTemporaryExposureKey(VALID_KEY_DATA_2, rollingStartIntervalNumber2, 2));
+
+ ResponseEntity<Void> actResponse = executor.executeRequest(keysWithDuplicateStartIntervalNumber, buildOkHeaders());
+
+ assertThat(actResponse.getStatusCode()).isEqualTo(BAD_REQUEST);
+ }
+
+ @Test
+ void check400ResponseStatusForOverlappingTimeIntervals() {
+ int rollingStartIntervalNumber1 = createRollingStartIntervalNumber(6);
+ int rollingStartIntervalNumber2 = rollingStartIntervalNumber1 + (DiagnosisKey.EXPECTED_ROLLING_PERIOD / 2);
+ var keysWithDuplicateStartIntervalNumber = Lists.list(
+ buildTemporaryExposureKey(VALID_KEY_DATA_1, rollingStartIntervalNumber1, 1),
+ buildTemporaryExposureKey(VALID_KEY_DATA_2, rollingStartIntervalNumber2, 2));
+
+ ResponseEntity<Void> actResponse = executor.executeRequest(keysWithDuplicateStartIntervalNumber, buildOkHeaders());
+
+ assertThat(actResponse.getStatusCode()).isEqualTo(BAD_REQUEST);
+ }
+
+ @Test
+ void check200ResponseStatusForValidSubmissionPayload() {
+ int rollingStartIntervalNumber1 = createRollingStartIntervalNumber(6);
+ int rollingStartIntervalNumber2 = rollingStartIntervalNumber1 + DiagnosisKey.EXPECTED_ROLLING_PERIOD;
+ int rollingStartIntervalNumber3 = rollingStartIntervalNumber2 + DiagnosisKey.EXPECTED_ROLLING_PERIOD;
+ var keysWithDuplicateStartIntervalNumber = Lists.list(
+ buildTemporaryExposureKey(VALID_KEY_DATA_1, rollingStartIntervalNumber1, 1),
+ buildTemporaryExposureKey(VALID_KEY_DATA_3, rollingStartIntervalNumber3, 3),
+ buildTemporaryExposureKey(VALID_KEY_DATA_2, rollingStartIntervalNumber2, 2));
+
+ ResponseEntity<Void> actResponse = executor.executeRequest(keysWithDuplicateStartIntervalNumber, buildOkHeaders());
+
+ assertThat(actResponse.getStatusCode()).isEqualTo(OK);
+ }
+}
diff --git a/services/submission/src/test/java/app/coronawarn/server/services/submission/controller/RequestExecutor.java b/services/submission/src/test/java/app/coronawarn/server/services/submission/controller/RequestExecutor.java
new file mode 100644
--- /dev/null
+++ b/services/submission/src/test/java/app/coronawarn/server/services/submission/controller/RequestExecutor.java
@@ -0,0 +1,99 @@
+/*
+ * Corona-Warn-App
+ *
+ * SAP SE and all other contributors /
+ * copyright owners license this file to you under the Apache
+ * License, Version 2.0 (the "License"); you may not use this
+ * file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://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 for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package app.coronawarn.server.services.submission.controller;
+
+import static java.time.ZoneOffset.UTC;
+
+import app.coronawarn.server.common.protocols.external.exposurenotification.TemporaryExposureKey;
+import app.coronawarn.server.common.protocols.internal.SubmissionPayload;
+import com.google.protobuf.ByteString;
+import java.net.URI;
+import java.time.Instant;
+import java.time.LocalDate;
+import java.util.Collection;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.web.client.TestRestTemplate;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.HttpMethod;
+import org.springframework.http.MediaType;
+import org.springframework.http.RequestEntity;
+import org.springframework.http.ResponseEntity;
+import org.springframework.stereotype.Component;
+
+/**
+ * RequestExecutor executes requests against the diagnosis key submission endpoint and holds a various methods for test
+ * request generation.
+ */
+@Component
+public class RequestExecutor {
+ public static final String VALID_KEY_DATA_1 = "testKey111111111";
+ public static final String VALID_KEY_DATA_2 = "testKey222222222";
+ public static final String VALID_KEY_DATA_3 = "testKey333333333";
+ private static final URI SUBMISSION_URL = URI.create("/version/v1/diagnosis-keys");
+ private final TestRestTemplate testRestTemplate;
+
+ @Autowired
+ public RequestExecutor(TestRestTemplate testRestTemplate) {
+ this.testRestTemplate = testRestTemplate;
+ }
+
+ public ResponseEntity<Void> executeRequest(Collection<TemporaryExposureKey> keys, HttpHeaders headers) {
+ SubmissionPayload body = SubmissionPayload.newBuilder().addAllKeys(keys).build();
+ RequestEntity<SubmissionPayload> request =
+ new RequestEntity<>(body, headers, HttpMethod.POST, SUBMISSION_URL);
+ return testRestTemplate.postForEntity(SUBMISSION_URL, request, Void.class);
+ }
+
+ public static HttpHeaders buildOkHeaders() {
+ HttpHeaders headers = setCwaAuthHeader(setContentTypeProtoBufHeader(new HttpHeaders()));
+
+ return setCwaFakeHeader(headers, "0");
+ }
+
+ public static HttpHeaders setContentTypeProtoBufHeader(HttpHeaders headers) {
+ headers.setContentType(MediaType.valueOf("application/x-protobuf"));
+ return headers;
+ }
+
+ public static HttpHeaders setCwaAuthHeader(HttpHeaders headers) {
+ headers.set("cwa-authorization", "TAN okTan");
+ return headers;
+ }
+
+ public static HttpHeaders setCwaFakeHeader(HttpHeaders headers, String value) {
+ headers.set("cwa-fake", value);
+ return headers;
+ }
+
+ public static TemporaryExposureKey buildTemporaryExposureKey(
+ String keyData, int rollingStartIntervalNumber, int transmissionRiskLevel) {
+ return TemporaryExposureKey.newBuilder()
+ .setKeyData(ByteString.copyFromUtf8(keyData))
+ .setRollingStartIntervalNumber(rollingStartIntervalNumber)
+ .setTransmissionRiskLevel(transmissionRiskLevel).build();
+ }
+
+ public static int createRollingStartIntervalNumber(Integer daysAgo) {
+ return Math.toIntExact(LocalDate
+ .ofInstant(Instant.now(), UTC)
+ .minusDays(daysAgo).atStartOfDay()
+ .toEpochSecond(UTC) / (60 * 10));
+ }
+}
diff --git a/services/submission/src/test/java/app/coronawarn/server/services/submission/controller/SubmissionControllerTest.java b/services/submission/src/test/java/app/coronawarn/server/services/submission/controller/SubmissionControllerTest.java
--- a/services/submission/src/test/java/app/coronawarn/server/services/submission/controller/SubmissionControllerTest.java
+++ b/services/submission/src/test/java/app/coronawarn/server/services/submission/controller/SubmissionControllerTest.java
@@ -19,7 +19,15 @@
package app.coronawarn.server.services.submission.controller;
-import static java.time.ZoneOffset.UTC;
+import static app.coronawarn.server.services.submission.controller.RequestExecutor.VALID_KEY_DATA_1;
+import static app.coronawarn.server.services.submission.controller.RequestExecutor.VALID_KEY_DATA_2;
+import static app.coronawarn.server.services.submission.controller.RequestExecutor.VALID_KEY_DATA_3;
+import static app.coronawarn.server.services.submission.controller.RequestExecutor.buildOkHeaders;
+import static app.coronawarn.server.services.submission.controller.RequestExecutor.buildTemporaryExposureKey;
+import static app.coronawarn.server.services.submission.controller.RequestExecutor.createRollingStartIntervalNumber;
+import static app.coronawarn.server.services.submission.controller.RequestExecutor.setContentTypeProtoBufHeader;
+import static app.coronawarn.server.services.submission.controller.RequestExecutor.setCwaAuthHeader;
+import static app.coronawarn.server.services.submission.controller.RequestExecutor.setCwaFakeHeader;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.anyString;
@@ -36,12 +44,10 @@
import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
import app.coronawarn.server.common.persistence.service.DiagnosisKeyService;
import app.coronawarn.server.common.protocols.external.exposurenotification.TemporaryExposureKey;
-import app.coronawarn.server.common.protocols.internal.SubmissionPayload;
+import app.coronawarn.server.services.submission.config.SubmissionServiceConfig;
import app.coronawarn.server.services.submission.verification.TanVerifier;
import com.google.protobuf.ByteString;
import java.net.URI;
-import java.time.Instant;
-import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
@@ -63,8 +69,6 @@
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
-import org.springframework.http.MediaType;
-import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@@ -81,6 +85,12 @@ class SubmissionControllerTest {
@Autowired
private TestRestTemplate testRestTemplate;
+ @Autowired
+ private RequestExecutor executor;
+
+ @Autowired
+ private SubmissionServiceConfig config;
+
@BeforeEach
public void setUpMocks() {
when(tanVerifier.verifyTan(anyString())).thenReturn(true);
@@ -88,33 +98,13 @@ public void setUpMocks() {
@Test
void checkResponseStatusForValidParameters() {
- ResponseEntity<Void> actResponse =
- executeRequest(buildPayloadWithMultipleKeys(), buildOkHeaders());
-
+ ResponseEntity<Void> actResponse = executor.executeRequest(buildPayloadWithMultipleKeys(), buildOkHeaders());
assertThat(actResponse.getStatusCode()).isEqualTo(OK);
}
@Test
void check400ResponseStatusForInvalidParameters() {
- ResponseEntity<Void> actResponse =
- executeRequest(buildPayloadWithInvalidKey(), buildOkHeaders());
-
- assertThat(actResponse.getStatusCode()).isEqualTo(BAD_REQUEST);
- }
-
- @Test
- void check400ResponseStatusForMissingKeys() {
- ResponseEntity<Void> actResponse =
- executeRequest(new ArrayList<>(), buildOkHeaders());
-
- assertThat(actResponse.getStatusCode()).isEqualTo(BAD_REQUEST);
- }
-
- @Test
- void check400ResponseStatusForTooManyKeys() {
- ResponseEntity<Void> actResponse =
- executeRequest(buildPayloadWithTooManyKeys(), buildOkHeaders());
-
+ ResponseEntity<Void> actResponse = executor.executeRequest(buildPayloadWithInvalidKey(), buildOkHeaders());
assertThat(actResponse.getStatusCode()).isEqualTo(BAD_REQUEST);
}
@@ -123,7 +113,7 @@ void singleKeyWithOutdatedRollingStartIntervalNumberDoesNotGetSaved() {
Collection<TemporaryExposureKey> keys = buildPayloadWithSingleOutdatedKey();
ArgumentCaptor<Collection<DiagnosisKey>> argument = ArgumentCaptor.forClass(Collection.class);
- executeRequest(keys, buildOkHeaders());
+ executor.executeRequest(keys, buildOkHeaders());
verify(diagnosisKeyService, atLeastOnce()).saveDiagnosisKeys(argument.capture());
assertThat(argument.getValue()).isEmpty();
@@ -136,7 +126,7 @@ void keysWithOutdatedRollingStartIntervalNumberDoNotGetSaved() {
keys.add(outdatedKey);
ArgumentCaptor<Collection<DiagnosisKey>> argument = ArgumentCaptor.forClass(Collection.class);
- executeRequest(keys, buildOkHeaders());
+ executor.executeRequest(keys, buildOkHeaders());
verify(diagnosisKeyService, atLeastOnce()).saveDiagnosisKeys(argument.capture());
keys.remove(outdatedKey);
@@ -148,7 +138,7 @@ void checkSaveOperationCallForValidParameters() {
Collection<TemporaryExposureKey> keys = buildPayloadWithMultipleKeys();
ArgumentCaptor<Collection<DiagnosisKey>> argument = ArgumentCaptor.forClass(Collection.class);
- executeRequest(keys, buildOkHeaders());
+ executor.executeRequest(keys, buildOkHeaders());
verify(diagnosisKeyService, atLeastOnce()).saveDiagnosisKeys(argument.capture());
assertElementsCorrespondToEachOther(keys, argument.getValue());
@@ -157,7 +147,7 @@ void checkSaveOperationCallForValidParameters() {
@ParameterizedTest
@MethodSource("createIncompleteHeaders")
void badRequestIfCwaHeadersMissing(HttpHeaders headers) {
- ResponseEntity<Void> actResponse = executeRequest(buildPayloadWithOneKey(), headers);
+ ResponseEntity<Void> actResponse = executor.executeRequest(buildPayloadWithOneKey(), headers);
verify(diagnosisKeyService, never()).saveDiagnosisKeys(any());
assertThat(actResponse.getStatusCode()).isEqualTo(BAD_REQUEST);
@@ -197,8 +187,7 @@ private static Stream<Arguments> createDeniedHttpMethods() {
void invalidTanHandling() {
when(tanVerifier.verifyTan(anyString())).thenReturn(false);
- ResponseEntity<Void> actResponse =
- executeRequest(buildPayloadWithOneKey(), buildOkHeaders());
+ ResponseEntity<Void> actResponse = executor.executeRequest(buildPayloadWithOneKey(), buildOkHeaders());
verify(diagnosisKeyService, never()).saveDiagnosisKeys(any());
assertThat(actResponse.getStatusCode()).isEqualTo(FORBIDDEN);
@@ -209,90 +198,44 @@ void fakeRequestHandling() {
HttpHeaders headers = buildOkHeaders();
setCwaFakeHeader(headers, "1");
- ResponseEntity<Void> actResponse = executeRequest(buildPayloadWithOneKey(), headers);
+ ResponseEntity<Void> actResponse = executor.executeRequest(buildPayloadWithOneKey(), headers);
verify(diagnosisKeyService, never()).saveDiagnosisKeys(any());
assertThat(actResponse.getStatusCode()).isEqualTo(OK);
}
- private static HttpHeaders buildOkHeaders() {
- HttpHeaders headers = setCwaAuthHeader(setContentTypeProtoBufHeader(new HttpHeaders()));
-
- return setCwaFakeHeader(headers, "0");
- }
-
- private static HttpHeaders setContentTypeProtoBufHeader(HttpHeaders headers) {
- headers.setContentType(MediaType.valueOf("application/x-protobuf"));
- return headers;
- }
-
- private static HttpHeaders setCwaAuthHeader(HttpHeaders headers) {
- headers.set("cwa-authorization", "TAN okTan");
- return headers;
- }
-
- private static HttpHeaders setCwaFakeHeader(HttpHeaders headers, String value) {
- headers.set("cwa-fake", value);
- return headers;
- }
-
private static Collection<TemporaryExposureKey> buildPayloadWithOneKey() {
- return Collections.singleton(buildTemporaryExposureKey("testKey111111111", 1, 2, 3));
+ return Collections.singleton(buildTemporaryExposureKey(VALID_KEY_DATA_1, 1, 3));
}
- private static Collection<TemporaryExposureKey> buildPayloadWithMultipleKeys() {
+ private Collection<TemporaryExposureKey> buildPayloadWithMultipleKeys() {
+ int rollingStartIntervalNumber1 = createRollingStartIntervalNumber(config.getRetentionDays() - 1);
+ int rollingStartIntervalNumber2 = rollingStartIntervalNumber1 + DiagnosisKey.EXPECTED_ROLLING_PERIOD;
+ int rollingStartIntervalNumber3 = rollingStartIntervalNumber2 + DiagnosisKey.EXPECTED_ROLLING_PERIOD;
return Stream.of(
- buildTemporaryExposureKey("testKey111111111", createRollingStartIntervalNumber(2), 2, 3),
- buildTemporaryExposureKey("testKey222222222", createRollingStartIntervalNumber(4), 5, 6),
- buildTemporaryExposureKey("testKey333333333", createRollingStartIntervalNumber(10), 8, 8))
+ buildTemporaryExposureKey(VALID_KEY_DATA_1, rollingStartIntervalNumber1, 3),
+ buildTemporaryExposureKey(VALID_KEY_DATA_2, rollingStartIntervalNumber3, 6),
+ buildTemporaryExposureKey(VALID_KEY_DATA_3, rollingStartIntervalNumber2, 8))
.collect(Collectors.toCollection(ArrayList::new));
}
- private static Collection<TemporaryExposureKey> buildPayloadWithSingleOutdatedKey() {
+ private Collection<TemporaryExposureKey> buildPayloadWithSingleOutdatedKey() {
TemporaryExposureKey outdatedKey = createOutdatedKey();
return Stream.of(outdatedKey).collect(Collectors.toCollection(ArrayList::new));
}
- private static TemporaryExposureKey createOutdatedKey() {
+ private TemporaryExposureKey createOutdatedKey() {
return TemporaryExposureKey.newBuilder()
- .setKeyData(ByteString.copyFromUtf8("testKey222222222"))
- .setRollingStartIntervalNumber(createRollingStartIntervalNumber(99))
- .setRollingPeriod(10)
+ .setKeyData(ByteString.copyFromUtf8(VALID_KEY_DATA_2))
+ .setRollingStartIntervalNumber(createRollingStartIntervalNumber(config.getRetentionDays()))
+ .setRollingPeriod(DiagnosisKey.EXPECTED_ROLLING_PERIOD)
.setTransmissionRiskLevel(5).build();
}
-
- private Collection<TemporaryExposureKey> buildPayloadWithTooManyKeys() {
- ArrayList<TemporaryExposureKey> tooMany = new ArrayList<>();
- for (int i = 0; i <= 99; i++) {
- tooMany.add(
- buildTemporaryExposureKey("testKey111111111", createRollingStartIntervalNumber(2), 2, 3));
- }
-
- return tooMany;
- }
-
private static Collection<TemporaryExposureKey> buildPayloadWithInvalidKey() {
return Stream.of(
- buildTemporaryExposureKey("testKey111111111", createRollingStartIntervalNumber(2), 2, 999))
+ buildTemporaryExposureKey(VALID_KEY_DATA_1, createRollingStartIntervalNumber(2), 999))
.collect(Collectors.toCollection(ArrayList::new));
}
-
- private static int createRollingStartIntervalNumber(Integer daysAgo) {
- return Math.toIntExact(LocalDate
- .ofInstant(Instant.now(), UTC)
- .minusDays(daysAgo).atStartOfDay()
- .toEpochSecond(UTC) / (60 * 10));
- }
-
- private static TemporaryExposureKey buildTemporaryExposureKey(
- String keyData, int rollingStartIntervalNumber, int rollingPeriod, int transmissionRiskLevel) {
- return TemporaryExposureKey.newBuilder()
- .setKeyData(ByteString.copyFromUtf8(keyData))
- .setRollingStartIntervalNumber(rollingStartIntervalNumber)
- .setRollingPeriod(rollingPeriod)
- .setTransmissionRiskLevel(transmissionRiskLevel).build();
- }
-
private void assertElementsCorrespondToEachOther
(Collection<TemporaryExposureKey> submittedKeys, Collection<DiagnosisKey> keyEntities) {
Set<DiagnosisKey> expKeys = submittedKeys.stream()
@@ -307,11 +250,4 @@ private static TemporaryExposureKey buildTemporaryExposureKey(
.contains(anActKey)
);
}
-
- private ResponseEntity<Void> executeRequest(Collection<TemporaryExposureKey> keys, HttpHeaders headers) {
- SubmissionPayload body = SubmissionPayload.newBuilder().addAllKeys(keys).build();
- RequestEntity<SubmissionPayload> request =
- new RequestEntity<>(body, headers, HttpMethod.POST, SUBMISSION_URL);
- return testRestTemplate.postForEntity(SUBMISSION_URL, request, Void.class);
- }
}
| ||||
corona-warn-app__cwa-server-676 | You will be provided with a partial code base and an issue statement explaining a problem to resolve.
<issue>
Wrong hash value for 2020-06-23 and 2020-06-24
<!--
Thanks for proposing an enhancement 🙌 ❤️
Before opening a new issue, please make sure that we do not have any duplicates already open. You can ensure this by searching the issue list for this repository. If there is a duplicate, please close your issue and add a comment to the existing issue instead.
-->
## Current Implementation
<!-- Describe or point to the current implementation that you would like to see improved -->
Old keys are deleted and the remaining keys are repacked by day or by hour.
60 keys moved from 24.06.2020 to 23.06.2020.
44 keys are deleted from 23.06.2020
The hour files 2020-06-23-hour-08.zip, 2020-06-23-hour-13.zip, 2020-06-23-hour-17.zip are repacked to
2020-06-23-hour-10.zip, 2020-06-23-hour-15.zip, 2020-06-23-hour-18.zip
(Even the old hour files are superseded they are still on the server.)
## Suggested Enhancement
<!-- Outline the idea of your enhancement, by e.g., describing the algorithm you propose. You can also create a Pull Request to outline your idea -->
Leave the files as they are, do not remove old keys.
## Expected Benefits
<!-- Summarize how your enhancement could aid the implementation (performance, readability, memory consumption, battery consumption, etc.). Please also back up with measurements or give detailed explanations for reduced runtimes, memory consumption, etc. -->
The files downloaded by the app have the same hash value as the file on the server.
</issue>
<code>
[start of README.md]
1 <!-- markdownlint-disable MD041 -->
2 <h1 align="center">
3 Corona-Warn-App Server
4 </h1>
5
6 <p align="center">
7 <a href="https://github.com/corona-warn-app/cwa-server/commits/" title="Last Commit"><img src="https://img.shields.io/github/last-commit/corona-warn-app/cwa-server?style=flat"></a>
8 <a href="https://github.com/corona-warn-app/cwa-server/issues" title="Open Issues"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat"></a>
9 <a href="https://circleci.com/gh/corona-warn-app/cwa-server" title="Build Status"><img src="https://circleci.com/gh/corona-warn-app/cwa-server.svg?style=shield&circle-token=4ab059989d10709df19eb4b98ab7c121a25e981a"></a>
10 <a href="https://sonarcloud.io/dashboard?id=corona-warn-app_cwa-server" title="Quality Gate"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=alert_status"></a>
11 <a href="https://sonarcloud.io/component_measures?id=corona-warn-app_cwa-server&metric=Coverage&view=list" title="Coverage"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=coverage"></a>
12 <a href="https://github.com/corona-warn-app/cwa-server/blob/master/LICENSE" title="License"><img src="https://img.shields.io/badge/License-Apache%202.0-green.svg?style=flat"></a>
13 </p>
14
15 <p align="center">
16 <a href="#development">Development</a> •
17 <a href="#service-apis">Service APIs</a> •
18 <a href="#documentation">Documentation</a> •
19 <a href="#support-and-feedback">Support</a> •
20 <a href="#how-to-contribute">Contribute</a> •
21 <a href="#contributors">Contributors</a> •
22 <a href="#repositories">Repositories</a> •
23 <a href="#licensing">Licensing</a>
24 </p>
25
26 The goal of this project is to develop the official Corona-Warn-App for Germany based on the exposure notification API from [Apple](https://www.apple.com/covid19/contacttracing/) and [Google](https://www.google.com/covid19/exposurenotifications/). The apps (for both iOS and Android) use Bluetooth technology to exchange anonymous encrypted data with other mobile phones (on which the app is also installed) in the vicinity of an app user's phone. The data is stored locally on each user's device, preventing authorities or other parties from accessing or controlling the data. This repository contains the **implementation of the server for encryption keys** for the Corona-Warn-App.
27
28 In this documentation, Corona-Warn-App services are also referred to as CWA services.
29
30 ## Architecture Overview
31
32 You can find the architecture overview [here](/docs/ARCHITECTURE.md), which will give you
33 a good starting point in how the backend services interact with other services, and what purpose
34 they serve.
35
36 ## Development
37
38 After you've checked out this repository, you can run the application in one of the following ways:
39
40 * As a [Docker](https://www.docker.com/)-based deployment on your local machine. You can run either:
41 * Single components using the respective Dockerfile or
42 * The full backend using the Docker Compose (which is considered the most convenient way)
43 * As a [Maven](https://maven.apache.org)-based build on your local machine.
44 If you want to develop something in a single component, this approach is preferable.
45
46 ### Docker-Based Deployment
47
48 If you want to use Docker-based deployment, you need to install Docker on your local machine. For more information about downloading and installing Docker, see the [official Docker documentation](https://docs.docker.com/get-docker/).
49
50 #### Running the Full CWA Backend Using Docker Compose
51
52 For your convenience, a full setup for local development and testing purposes, including the generation of test data has been prepared using [Docker Compose](https://docs.docker.com/compose/reference/overview/). To build the backend services, run ```docker-compose build``` in the repository's root directory. A default configuration file can be found under ```.env``` in the root folder of the repository. If the endpoints are to be exposed to the network the default values in this file should be changed before docker-compose is run.
53
54 Once the services are built, you can start the whole backend using ```docker-compose up```.
55 The distribution service runs once and then finishes. If you want to trigger additional distribution runs, run ```docker-compose run distribution```.
56
57 The docker-compose contains the following services:
58
59 Service | Description | Endpoint and Default Credentials
60 ------------------|-------------|-----------
61 submission | The Corona-Warn-App submission service | `http://localhost:8000` <br> `http://localhost:8006` (for actuator endpoint)
62 distribution | The Corona-Warn-App distribution service | NO ENDPOINT
63 postgres | A [postgres] database installation | `localhost:8001` <br> `postgres:5432` (from containerized pgadmin) <br> Username: postgres <br> Password: postgres
64 pgadmin | A [pgadmin](https://www.pgadmin.org/) installation for the postgres database | `http://localhost:8002` <br> Username: [email protected] <br> Password: password
65 cloudserver | [Zenko CloudServer] is a S3-compliant object store | `http://localhost:8003/` <br> Access key: accessKey1 <br> Secret key: verySecretKey1
66 verification-fake | A very simple fake implementation for the tan verification. | `http://localhost:8004/version/v1/tan/verify` <br> The only valid tan is `edc07f08-a1aa-11ea-bb37-0242ac130002`.
67
68 ##### Known Limitation
69
70 In rare cases the docker-compose runs into a timing issue if the distribution service starts before the bucket of the objectstore was created. This is not a big issue as you can simply run ```docker-compose run distribution``` to trigger additional distribution runs after the objectstore was initialized.
71
72 #### Running Single CWA Services Using Docker
73
74 If you would like to build and run a single CWA service, it's considered easiest to run them in a Docker environment. You can do this using the script provided in the respective CWA service directory. The Docker script first builds the CWA service and then creates an image for the runtime, which means that there are no additional dependencies for you to install.
75
76 To build and run the distribution service, run the following command:
77
78 ```bash
79 ./services/distribution/build_and_run.sh
80 ```
81
82 To build and run the submission service, run the following command:
83
84 ```bash
85 ./services/submission/build_and_run.sh
86 ```
87
88 The submission service is available on [localhost:8080](http://localhost:8080 ).
89
90 ### Maven-Based Build
91
92 If you want to actively develop in one of the CWA services, the Maven-based runtime is most suitable.
93 To prepare your machine to run the CWA project locally, we recommend that you first ensure that you've installed the following:
94
95 * Minimum JDK Version 11: [OpenJDK](https://openjdk.java.net/) / [SapMachine](https://sap.github.io/SapMachine/)
96 * [Maven 3.6](https://maven.apache.org/)
97 * [Postgres]
98 * [Zenko CloudServer]
99
100 If you are already running a local Postgres, you need to create a database `cwa` and run the following setup scripts:
101
102 * Create the different CWA roles first by executing [create-roles.sql](setup/create-roles.sql).
103 * Create local database users for the specific roles by running [create-users.sql](./local-setup/create-users.sql).
104 * It is recommended to also run [enable-test-data-docker-compose.sql](./local-setup/enable-test-data-docker-compose.sql)
105 , which enables the test data generation profile. If you already had CWA running before and an existing `diagnosis-key`
106 table on your database, you need to run [enable-test-data.sql](./local-setup/enable-test-data.sql) instead.
107
108 You can also use `docker-compose` to start Postgres and Zenko. If you do that, you have to
109 set the following environment-variables when running the Spring project:
110
111 For the distribution module:
112
113 ```bash
114 POSTGRESQL_SERVICE_PORT=8001
115 VAULT_FILESIGNING_SECRET=</path/to/your/private_key>
116 SPRING_PROFILES_ACTIVE=signature-dev,disable-ssl-client-postgres
117 ```
118
119 For the submission module:
120
121 ```bash
122 POSTGRESQL_SERVICE_PORT=8001
123 SPRING_PROFILES_ACTIVE=disable-ssl-server,disable-ssl-client-postgres,disable-ssl-client-verification,disable-ssl-client-verification-verify-hostname
124 ```
125
126 #### Configure
127
128 After you made sure that the specified dependencies are running, configure them in the respective configuration files.
129
130 * Configure the Postgres connection in the [submission config](./services/submission/src/main/resources/application.yaml) and in the [distribution config](./services/distribution/src/main/resources/application.yaml)
131 * Configure the S3 compatible object storage in the [distribution config](./services/distribution/src/main/resources/application.yaml)
132 * Configure the private key for the distribution service, the path need to be prefixed with `file:`
133 * `VAULT_FILESIGNING_SECRET` should be the path to the private key, example available in `<repo-root>/docker-compose-test-secrets/private.pem`
134
135 #### Build
136
137 After you've checked out the repository, to build the project, run ```mvn install``` in your base directory.
138
139 #### Run
140
141 Navigate to the service you want to start and run the spring-boot:run target. The configured Postgres and the configured S3 compliant object storage are used as default. When you start the submission service, the endpoint is available on your local port 8080.
142
143 If you want to start the submission service, for example, you start it as follows:
144
145 ```bash
146 cd services/submission/
147 mvn spring-boot:run
148 ```
149
150 #### Debugging
151
152 To enable the `DEBUG` log level, you can run the application using the Spring `dev` profile.
153
154 ```bash
155 mvn spring-boot:run -Dspring.profiles.active=dev
156 ```
157
158 To be able to set breakpoints (e.g. in IntelliJ), it may be necessary to use the ```-Dspring-boot.run.fork=false``` parameter.
159
160 ## Service APIs
161
162 The API that is being exposed by the backend services is documented in an [OpenAPI](https://www.openapis.org/) specification. The specification files are available at the following locations:
163
164 Service | OpenAPI Specification
165 --------------------------|-------------
166 Submission Service | [services/submission/api_v1.json](https://github.com/corona-warn-app/cwa-server/raw/master/services/submission/api_v1.json)
167 Distribution Service | [services/distribution/api_v1.json](https://github.com/corona-warn-app/cwa-server/raw/master/services/distribution/api_v1.json)
168
169 ## Spring Profiles
170
171 ### Distribution
172
173 See [Distribution Service - Spring Profiles](/docs/DISTRIBUTION.md#spring-profiles).
174
175 ### Submission
176
177 See [Submission Service - Spring Profiles](/docs/SUBMISSION.md#spring-profiles).
178
179 ## Documentation
180
181 The full documentation for the Corona-Warn-App can be found in the [cwa-documentation](https://github.com/corona-warn-app/cwa-documentation) repository. The documentation repository contains technical documents, architecture information, and whitepapers related to this implementation.
182
183 The documentation for cwa-server can be found under the [/docs](./docs) folder.
184
185 The JavaDoc documentation for cwa-server is hosted by Github Pages at [https://corona-warn-app.github.io/cwa-server](https://corona-warn-app.github.io/cwa-server).
186
187 ## Support and Feedback
188
189 The following channels are available for discussions, feedback, and support requests:
190
191 | Type | Channel |
192 | ------------------------ | ------------------------------------------------------ |
193 | **General Discussion** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="General Discussion"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/question.svg?style=flat-square"></a> </a> |
194 | **Concept Feedback** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="Open Concept Feedback"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/architecture.svg?style=flat-square"></a> |
195 | **Backend Issue** | <a href="https://github.com/corona-warn-app/cwa-server/issues/new/choose" title="Open Backend Issue"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat-square"></a> |
196 | **Other Requests** | <a href="mailto:[email protected]" title="Email CWA Team"><img src="https://img.shields.io/badge/email-CWA%20team-green?logo=mail.ru&style=flat-square&logoColor=white"></a> |
197
198 ## How to Contribute
199
200 Contribution and feedback are 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.
201
202 ## Contributors
203
204 The German government has asked SAP and Deutsche Telekom to develop the Corona-Warn-App for Germany as open source software. Deutsche Telekom is providing the network and mobile technology and will operate and run the backend for the app in a safe, scalable and stable manner. SAP is responsible for the app development, its framework and the underlying platform. Therefore, development teams of SAP and Deutsche Telekom are contributing to this project. At the same time 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.
205
206 ## Repositories
207
208 The following public repositories are currently available for the Corona-Warn-App:
209
210 | Repository | Description |
211 | ------------------- | --------------------------------------------------------------------- |
212 | [cwa-documentation] | Project overview, general documentation, and white papers |
213 | [cwa-server] | Backend implementation for the Apple/Google exposure notification API|
214 | [cwa-verification-server] | Backend implementation of the verification process|
215
216 [cwa-documentation]: https://github.com/corona-warn-app/cwa-documentation
217 [cwa-server]: https://github.com/corona-warn-app/cwa-server
218 [cwa-verification-server]: https://github.com/corona-warn-app/cwa-verification-server
219 [Postgres]: https://www.postgresql.org/
220 [HSQLDB]: http://hsqldb.org/
221 [Zenko CloudServer]: https://github.com/scality/cloudserver
222
223 ## Licensing
224
225 Copyright (c) 2020 SAP SE or an SAP affiliate company.
226
227 Licensed under the **Apache License, Version 2.0** (the "License"); you may not use this file except in compliance with the License.
228
229 You may obtain a copy of the License at <https://www.apache.org/licenses/LICENSE-2.0>.
230
231 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.
232
[end of README.md]
[start of docker-compose.yml]
1 version: '3'
2 services:
3 submission:
4 build:
5 context: ./
6 dockerfile: ./services/submission/Dockerfile
7 depends_on:
8 - postgres
9 - verification-fake
10 ports:
11 - "8000:8080"
12 - "8006:8081"
13 environment:
14 SPRING_PROFILES_ACTIVE: dev,disable-ssl-server,disable-ssl-client-postgres,disable-ssl-client-verification,disable-ssl-client-verification-verify-hostname
15 POSTGRESQL_SERVICE_PORT: '5432'
16 POSTGRESQL_SERVICE_HOST: postgres
17 POSTGRESQL_DATABASE: ${POSTGRES_DB}
18 POSTGRESQL_PASSWORD_SUBMISION: ${POSTGRES_SUBMISSION_PASSWORD}
19 POSTGRESQL_USER_SUBMISION: ${POSTGRES_SUBMISSION_USER}
20 POSTGRESQL_PASSWORD_FLYWAY: ${POSTGRES_FLYWAY_PASSWORD}
21 POSTGRESQL_USER_FLYWAY: ${POSTGRES_FLYWAY_USER}
22 VERIFICATION_BASE_URL: http://verification-fake:8004
23 distribution:
24 build:
25 context: ./
26 dockerfile: ./services/distribution/Dockerfile
27 depends_on:
28 - postgres
29 - objectstore
30 - create-bucket
31 environment:
32 SPRING_PROFILES_ACTIVE: dev,signature-dev,testdata,disable-ssl-client-postgres
33 POSTGRESQL_SERVICE_PORT: '5432'
34 POSTGRESQL_SERVICE_HOST: postgres
35 POSTGRESQL_DATABASE: ${POSTGRES_DB}
36 POSTGRESQL_PASSWORD_DISTRIBUTION: ${POSTGRES_DISTRIBUTION_PASSWORD}
37 POSTGRESQL_USER_DISTRIBUTION: ${POSTGRES_DISTRIBUTION_USER}
38 POSTGRESQL_PASSWORD_FLYWAY: ${POSTGRES_FLYWAY_PASSWORD}
39 POSTGRESQL_USER_FLYWAY: ${POSTGRES_FLYWAY_USER}
40 # Settings for the S3 compatible objectstore
41 CWA_OBJECTSTORE_ACCESSKEY: ${OBJECTSTORE_ACCESSKEY}
42 CWA_OBJECTSTORE_SECRETKEY: ${OBJECTSTORE_SECRETKEY}
43 CWA_OBJECTSTORE_ENDPOINT: http://objectstore
44 CWA_OBJECTSTORE_BUCKET: cwa
45 CWA_OBJECTSTORE_PORT: 8000
46 services.distribution.paths.output: /tmp/distribution
47 # Settings for cryptographic artifacts
48 VAULT_FILESIGNING_SECRET: ${SECRET_PRIVATE}
49 volumes:
50 - ./docker-compose-test-secrets:/secrets
51 postgres:
52 image: postgres:11.8
53 restart: always
54 ports:
55 - "8001:5432"
56 environment:
57 PGDATA: /data/postgres
58 POSTGRES_DB: ${POSTGRES_DB}
59 POSTGRES_USER: ${POSTGRES_USER}
60 POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
61 volumes:
62 - postgres_volume:/data/postgres
63 - ./setup/setup-roles.sql:/docker-entrypoint-initdb.d/1-roles.sql
64 - ./local-setup/create-users.sql:/docker-entrypoint-initdb.d/2-users.sql
65 - ./local-setup/enable-test-data-docker-compose.sql:/docker-entrypoint-initdb.d/3-enable-testdata.sql
66 pgadmin:
67 container_name: pgadmin_container
68 image: dpage/pgadmin4
69 volumes:
70 - pgadmin_volume:/root/.pgadmin
71 ports:
72 - "8002:80"
73 restart: unless-stopped
74 depends_on:
75 - postgres
76 environment:
77 PGADMIN_DEFAULT_EMAIL: ${PGADMIN_DEFAULT_EMAIL}
78 PGADMIN_DEFAULT_PASSWORD: ${PGADMIN_DEFAULT_PASSWORD}
79 objectstore:
80 image: "zenko/cloudserver"
81 volumes:
82 - objectstore_volume:/data
83 ports:
84 - "8003:8000"
85 environment:
86 ENDPOINT: objectstore
87 REMOTE_MANAGEMENT_DISABLE: 1
88 SCALITY_ACCESS_KEY_ID: ${OBJECTSTORE_ACCESSKEY}
89 SCALITY_SECRET_ACCESS_KEY: ${OBJECTSTORE_SECRETKEY}
90 create-bucket:
91 image: amazon/aws-cli
92 environment:
93 - AWS_ACCESS_KEY_ID=${OBJECTSTORE_ACCESSKEY}
94 - AWS_SECRET_ACCESS_KEY=${OBJECTSTORE_SECRETKEY}
95 entrypoint: ["/root/scripts/wait-for-it/wait-for-it.sh", "objectstore:8000", "-t", "30", "--"]
96 volumes:
97 - ./scripts/wait-for-it:/root/scripts/wait-for-it
98 command: aws s3api create-bucket --bucket cwa --endpoint-url http://objectstore:8000 --acl public-read
99 depends_on:
100 - objectstore
101 verification-fake:
102 image: lilienthal/cwa-verification-fake:0.0.3
103 restart: always
104 ports:
105 - "8004:8004"
106 volumes:
107 postgres_volume:
108 pgadmin_volume:
109 objectstore_volume:
110
[end of docker-compose.yml]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/ProdDiagnosisKeyBundler.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.distribution.assembly.diagnosiskeys;
22
23 import static java.time.ZoneOffset.UTC;
24 import static java.util.Collections.emptyList;
25 import static java.util.stream.Collectors.groupingBy;
26
27 import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
28 import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
29 import java.time.Duration;
30 import java.time.LocalDateTime;
31 import java.time.temporal.ChronoUnit;
32 import java.util.ArrayList;
33 import java.util.Collection;
34 import java.util.HashMap;
35 import java.util.List;
36 import java.util.Map;
37 import java.util.Optional;
38 import java.util.stream.LongStream;
39 import org.springframework.context.annotation.Profile;
40 import org.springframework.stereotype.Component;
41
42 /**
43 * An instance of this class contains a collection of {@link DiagnosisKey DiagnosisKeys}, that will be distributed while
44 * respecting expiry policy (keys must be expired for a configurable amount of time before distribution) and shifting
45 * policy (there must be at least a configurable number of keys in a distribution). The policies are configurable
46 * through the properties {@code expiry-policy-minutes} and {@code shifting-policy-threshold}.
47 */
48 @Profile("!demo")
49 @Component
50 public class ProdDiagnosisKeyBundler extends DiagnosisKeyBundler {
51
52 /**
53 * Creates a new {@link ProdDiagnosisKeyBundler}.
54 */
55 public ProdDiagnosisKeyBundler(DistributionServiceConfig distributionServiceConfig) {
56 super(distributionServiceConfig);
57 }
58
59 /**
60 * Initializes the internal {@code distributableDiagnosisKeys} map, grouping the diagnosis keys by the date on which
61 * they may be distributed, while respecting the expiry and shifting policies.
62 */
63 @Override
64 protected void createDiagnosisKeyDistributionMap(Collection<DiagnosisKey> diagnosisKeys) {
65 this.distributableDiagnosisKeys.clear();
66 if (diagnosisKeys.isEmpty()) {
67 return;
68 }
69 Map<LocalDateTime, List<DiagnosisKey>> distributableDiagnosisKeysGroupedByExpiryPolicy = new HashMap<>(
70 diagnosisKeys.stream().collect(groupingBy(this::getDistributionDateTimeByExpiryPolicy)));
71 LocalDateTime earliestDistributableTimestamp =
72 getEarliestDistributableTimestamp(distributableDiagnosisKeysGroupedByExpiryPolicy).orElseThrow();
73 LocalDateTime latestDistributableTimestamp = this.distributionTime;
74
75 List<DiagnosisKey> diagnosisKeyAccumulator = new ArrayList<>();
76 LongStream.range(0, earliestDistributableTimestamp.until(latestDistributableTimestamp, ChronoUnit.HOURS))
77 .forEach(hourCounter -> {
78 LocalDateTime currentHour = earliestDistributableTimestamp.plusHours(hourCounter);
79 Collection<DiagnosisKey> currentHourDiagnosisKeys = Optional
80 .ofNullable(distributableDiagnosisKeysGroupedByExpiryPolicy.get(currentHour))
81 .orElse(emptyList());
82 diagnosisKeyAccumulator.addAll(currentHourDiagnosisKeys);
83 if (diagnosisKeyAccumulator.size() >= minNumberOfKeysPerBundle) {
84 this.distributableDiagnosisKeys.put(currentHour, new ArrayList<>(diagnosisKeyAccumulator));
85 diagnosisKeyAccumulator.clear();
86 }
87 });
88 }
89
90 private static Optional<LocalDateTime> getEarliestDistributableTimestamp(
91 Map<LocalDateTime, List<DiagnosisKey>> distributableDiagnosisKeys) {
92 return distributableDiagnosisKeys.keySet().stream().min(LocalDateTime::compareTo);
93 }
94
95 /**
96 * Returns the end of the rolling time window that a {@link DiagnosisKey} was active for as a {@link LocalDateTime}.
97 */
98 private LocalDateTime getExpiryDateTime(DiagnosisKey diagnosisKey) {
99 return LocalDateTime
100 .ofEpochSecond(diagnosisKey.getRollingStartIntervalNumber() * TEN_MINUTES_INTERVAL_SECONDS, 0, UTC)
101 .plusMinutes(diagnosisKey.getRollingPeriod() * 10L);
102 }
103
104 /**
105 * Calculates the earliest point in time at which the specified {@link DiagnosisKey} can be distributed, while
106 * respecting the expiry policy and the submission timestamp. Before keys are allowed to be distributed, they must be
107 * expired for a configured amount of time.
108 *
109 * @return {@link LocalDateTime} at which the specified {@link DiagnosisKey} can be distributed.
110 */
111 private LocalDateTime getDistributionDateTimeByExpiryPolicy(DiagnosisKey diagnosisKey) {
112 LocalDateTime submissionDateTime = getSubmissionDateTime(diagnosisKey);
113 LocalDateTime expiryDateTime = getExpiryDateTime(diagnosisKey);
114 long minutesBetweenExpiryAndSubmission = Duration.between(expiryDateTime, submissionDateTime).toMinutes();
115 if (minutesBetweenExpiryAndSubmission <= expiryPolicyMinutes) {
116 // truncatedTo floors the value, so we need to add an hour to the DISTRIBUTION_PADDING to compensate that.
117 return expiryDateTime.plusMinutes(expiryPolicyMinutes + 60).truncatedTo(ChronoUnit.HOURS);
118 } else {
119 return submissionDateTime;
120 }
121 }
122 }
123
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/ProdDiagnosisKeyBundler.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/config/DistributionServiceConfig.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.distribution.config;
22
23 import app.coronawarn.server.common.protocols.external.exposurenotification.SignatureInfo;
24 import javax.validation.constraints.Max;
25 import javax.validation.constraints.Min;
26 import javax.validation.constraints.Pattern;
27 import org.springframework.boot.context.properties.ConfigurationProperties;
28 import org.springframework.stereotype.Component;
29 import org.springframework.validation.annotation.Validated;
30
31 @Component
32 @ConfigurationProperties(prefix = "services.distribution")
33 @Validated
34 public class DistributionServiceConfig {
35
36 private static final String PATH_REGEX = "^[/]?[a-zA-Z0-9_]+(/[a-zA-Z0-9_]+)*[/]?$";
37 private static final String FILE_NAME_REGEX = "^[a-zA-Z0-9_-]+$";
38 private static final String FILE_NAME_WITH_TYPE_REGEX = "^[a-zA-Z0-9_-]+\\.[a-z]+$";
39 private static final String CHAR_AND_NUMBER_REGEX = "^[a-zA-Z0-9_-]+$";
40 private static final String CHAR_NUMBER_AND_SPACE_REGEX = "^[a-zA-Z0-9_\\s]+$";
41 private static final String NO_WHITESPACE_REGEX = "^[\\S]+$";
42 private static final String URL_REGEX = "^http[s]?://[a-z0-9-]+([\\./][a-z0-9-]+)*[/]?$";
43 private static final String NUMBER_REGEX = "^[0-9]+$";
44 private static final String VERSION_REGEX = "^v[0-9]+$";
45 private static final String ALGORITHM_OID_REGEX = "^[0-9]+[\\.[0-9]+]*$";
46 private static final String BUNDLE_REGEX = "^[a-z-]+[\\.[a-z-]+]*$";
47 private static final String PRIVATE_KEY_REGEX = "^(classpath:|file://)[/]?[a-zA-Z0-9_]+[/[a-zA-Z0-9_]+]*(.pem)?$";
48
49 private Paths paths;
50 private TestData testData;
51 @Min(0)
52 @Max(28)
53 private Integer retentionDays;
54 @Min(120)
55 @Max(720)
56 private Integer expiryPolicyMinutes;
57 @Min(0)
58 @Max(200)
59 private Integer shiftingPolicyThreshold;
60 @Min(600000)
61 @Max(750000)
62 private Integer maximumNumberOfKeysPerBundle;
63 @Pattern(regexp = FILE_NAME_REGEX)
64 private String outputFileName;
65 private Boolean includeIncompleteDays;
66 private Boolean includeIncompleteHours;
67 private TekExport tekExport;
68 private Signature signature;
69 private Api api;
70 private ObjectStore objectStore;
71
72 public Paths getPaths() {
73 return paths;
74 }
75
76 public void setPaths(Paths paths) {
77 this.paths = paths;
78 }
79
80 public TestData getTestData() {
81 return testData;
82 }
83
84 public void setTestData(TestData testData) {
85 this.testData = testData;
86 }
87
88 public Integer getRetentionDays() {
89 return retentionDays;
90 }
91
92 public void setRetentionDays(Integer retentionDays) {
93 this.retentionDays = retentionDays;
94 }
95
96 public Integer getExpiryPolicyMinutes() {
97 return expiryPolicyMinutes;
98 }
99
100 public void setExpiryPolicyMinutes(Integer expiryPolicyMinutes) {
101 this.expiryPolicyMinutes = expiryPolicyMinutes;
102 }
103
104 public Integer getShiftingPolicyThreshold() {
105 return shiftingPolicyThreshold;
106 }
107
108 public void setShiftingPolicyThreshold(Integer shiftingPolicyThreshold) {
109 this.shiftingPolicyThreshold = shiftingPolicyThreshold;
110 }
111
112 public Integer getMaximumNumberOfKeysPerBundle() {
113 return this.maximumNumberOfKeysPerBundle;
114 }
115
116 public void setMaximumNumberOfKeysPerBundle(Integer maximumNumberOfKeysPerBundle) {
117 this.maximumNumberOfKeysPerBundle = maximumNumberOfKeysPerBundle;
118 }
119
120 public String getOutputFileName() {
121 return outputFileName;
122 }
123
124 public void setOutputFileName(String outputFileName) {
125 this.outputFileName = outputFileName;
126 }
127
128 public Boolean getIncludeIncompleteDays() {
129 return includeIncompleteDays;
130 }
131
132 public void setIncludeIncompleteDays(Boolean includeIncompleteDays) {
133 this.includeIncompleteDays = includeIncompleteDays;
134 }
135
136 public Boolean getIncludeIncompleteHours() {
137 return includeIncompleteHours;
138 }
139
140 public void setIncludeIncompleteHours(Boolean includeIncompleteHours) {
141 this.includeIncompleteHours = includeIncompleteHours;
142 }
143
144 public TekExport getTekExport() {
145 return tekExport;
146 }
147
148 public void setTekExport(TekExport tekExport) {
149 this.tekExport = tekExport;
150 }
151
152 public Signature getSignature() {
153 return signature;
154 }
155
156 public void setSignature(Signature signature) {
157 this.signature = signature;
158 }
159
160 public Api getApi() {
161 return api;
162 }
163
164 public void setApi(Api api) {
165 this.api = api;
166 }
167
168 public ObjectStore getObjectStore() {
169 return objectStore;
170 }
171
172 public void setObjectStore(
173 ObjectStore objectStore) {
174 this.objectStore = objectStore;
175 }
176
177 public static class TekExport {
178
179 @Pattern(regexp = FILE_NAME_WITH_TYPE_REGEX)
180 private String fileName;
181 @Pattern(regexp = CHAR_NUMBER_AND_SPACE_REGEX)
182 private String fileHeader;
183 @Min(0)
184 @Max(32)
185 private Integer fileHeaderWidth;
186
187 public String getFileName() {
188 return fileName;
189 }
190
191 public void setFileName(String fileName) {
192 this.fileName = fileName;
193 }
194
195 public String getFileHeader() {
196 return fileHeader;
197 }
198
199 public void setFileHeader(String fileHeader) {
200 this.fileHeader = fileHeader;
201 }
202
203 public Integer getFileHeaderWidth() {
204 return fileHeaderWidth;
205 }
206
207 public void setFileHeaderWidth(Integer fileHeaderWidth) {
208 this.fileHeaderWidth = fileHeaderWidth;
209 }
210 }
211
212 public static class TestData {
213
214 private Integer seed;
215 private Integer exposuresPerHour;
216
217 public Integer getSeed() {
218 return seed;
219 }
220
221 public void setSeed(Integer seed) {
222 this.seed = seed;
223 }
224
225 public Integer getExposuresPerHour() {
226 return exposuresPerHour;
227 }
228
229 public void setExposuresPerHour(Integer exposuresPerHour) {
230 this.exposuresPerHour = exposuresPerHour;
231 }
232 }
233
234 public static class Paths {
235
236 @Pattern(regexp = PRIVATE_KEY_REGEX)
237 private String privateKey;
238 @Pattern(regexp = PATH_REGEX)
239 private String output;
240
241 public String getPrivateKey() {
242 return privateKey;
243 }
244
245 public void setPrivateKey(String privateKey) {
246 this.privateKey = privateKey;
247 }
248
249 public String getOutput() {
250 return output;
251 }
252
253 public void setOutput(String output) {
254 this.output = output;
255 }
256 }
257
258 public static class Api {
259
260 @Pattern(regexp = CHAR_AND_NUMBER_REGEX)
261 private String versionPath;
262 @Pattern(regexp = VERSION_REGEX)
263 private String versionV1;
264 @Pattern(regexp = CHAR_AND_NUMBER_REGEX)
265 private String countryPath;
266 @Pattern(regexp = CHAR_AND_NUMBER_REGEX)
267 private String countryGermany;
268 @Pattern(regexp = CHAR_AND_NUMBER_REGEX)
269 private String datePath;
270 @Pattern(regexp = CHAR_AND_NUMBER_REGEX)
271 private String hourPath;
272 @Pattern(regexp = CHAR_AND_NUMBER_REGEX)
273 private String diagnosisKeysPath;
274 @Pattern(regexp = CHAR_AND_NUMBER_REGEX)
275 private String parametersPath;
276 @Pattern(regexp = CHAR_AND_NUMBER_REGEX)
277 private String appConfigFileName;
278
279 public String getVersionPath() {
280 return versionPath;
281 }
282
283 public void setVersionPath(String versionPath) {
284 this.versionPath = versionPath;
285 }
286
287 public String getVersionV1() {
288 return versionV1;
289 }
290
291 public void setVersionV1(String versionV1) {
292 this.versionV1 = versionV1;
293 }
294
295 public String getCountryPath() {
296 return countryPath;
297 }
298
299 public void setCountryPath(String countryPath) {
300 this.countryPath = countryPath;
301 }
302
303 public String getCountryGermany() {
304 return countryGermany;
305 }
306
307 public void setCountryGermany(String countryGermany) {
308 this.countryGermany = countryGermany;
309 }
310
311 public String getDatePath() {
312 return datePath;
313 }
314
315 public void setDatePath(String datePath) {
316 this.datePath = datePath;
317 }
318
319 public String getHourPath() {
320 return hourPath;
321 }
322
323 public void setHourPath(String hourPath) {
324 this.hourPath = hourPath;
325 }
326
327 public String getDiagnosisKeysPath() {
328 return diagnosisKeysPath;
329 }
330
331 public void setDiagnosisKeysPath(String diagnosisKeysPath) {
332 this.diagnosisKeysPath = diagnosisKeysPath;
333 }
334
335 public String getParametersPath() {
336 return parametersPath;
337 }
338
339 public void setParametersPath(String parametersPath) {
340 this.parametersPath = parametersPath;
341 }
342
343 public String getAppConfigFileName() {
344 return appConfigFileName;
345 }
346
347 public void setAppConfigFileName(String appConfigFileName) {
348 this.appConfigFileName = appConfigFileName;
349 }
350 }
351
352 public static class Signature {
353
354 @Pattern(regexp = BUNDLE_REGEX)
355 private String appBundleId;
356 private String androidPackage;
357 @Pattern(regexp = NUMBER_REGEX)
358 private String verificationKeyId;
359 @Pattern(regexp = VERSION_REGEX)
360 private String verificationKeyVersion;
361 @Pattern(regexp = ALGORITHM_OID_REGEX)
362 private String algorithmOid;
363 @Pattern(regexp = CHAR_AND_NUMBER_REGEX)
364 private String algorithmName;
365 @Pattern(regexp = FILE_NAME_WITH_TYPE_REGEX)
366 private String fileName;
367 @Pattern(regexp = CHAR_AND_NUMBER_REGEX)
368 private String securityProvider;
369
370 public String getAppBundleId() {
371 return appBundleId;
372 }
373
374 public void setAppBundleId(String appBundleId) {
375 this.appBundleId = appBundleId;
376 }
377
378 public String getAndroidPackage() {
379 return androidPackage;
380 }
381
382 public void setAndroidPackage(String androidPackage) {
383 this.androidPackage = androidPackage;
384 }
385
386 public String getVerificationKeyId() {
387 return verificationKeyId;
388 }
389
390 public void setVerificationKeyId(String verificationKeyId) {
391 this.verificationKeyId = verificationKeyId;
392 }
393
394 public String getVerificationKeyVersion() {
395 return verificationKeyVersion;
396 }
397
398 public void setVerificationKeyVersion(String verificationKeyVersion) {
399 this.verificationKeyVersion = verificationKeyVersion;
400 }
401
402 public String getAlgorithmOid() {
403 return algorithmOid;
404 }
405
406 public void setAlgorithmOid(String algorithmOid) {
407 this.algorithmOid = algorithmOid;
408 }
409
410 public String getAlgorithmName() {
411 return algorithmName;
412 }
413
414 public void setAlgorithmName(String algorithmName) {
415 this.algorithmName = algorithmName;
416 }
417
418 public String getFileName() {
419 return fileName;
420 }
421
422 public void setFileName(String fileName) {
423 this.fileName = fileName;
424 }
425
426 public String getSecurityProvider() {
427 return securityProvider;
428 }
429
430 public void setSecurityProvider(String securityProvider) {
431 this.securityProvider = securityProvider;
432 }
433
434 /**
435 * Returns the static {@link SignatureInfo} configured in the application properties.
436 */
437 public SignatureInfo getSignatureInfo() {
438 return SignatureInfo.newBuilder()
439 .setAppBundleId(this.getAppBundleId())
440 .setVerificationKeyVersion(this.getVerificationKeyVersion())
441 .setVerificationKeyId(this.getVerificationKeyId())
442 .setSignatureAlgorithm(this.getAlgorithmOid())
443 .build();
444 }
445 }
446
447 public static class ObjectStore {
448
449 @Pattern(regexp = NO_WHITESPACE_REGEX)
450 private String accessKey;
451 @Pattern(regexp = NO_WHITESPACE_REGEX)
452 private String secretKey;
453 @Pattern(regexp = URL_REGEX)
454 private String endpoint;
455 @Min(1)
456 @Max(65535)
457 private Integer port;
458 @Pattern(regexp = CHAR_AND_NUMBER_REGEX)
459 private String bucket;
460 private Boolean setPublicReadAclOnPutObject;
461 @Min(1)
462 @Max(64)
463 private Integer maxNumberOfFailedOperations;
464 @Min(1)
465 @Max(64)
466 private Integer maxNumberOfS3Threads;
467
468 public String getAccessKey() {
469 return accessKey;
470 }
471
472 public void setAccessKey(String accessKey) {
473 this.accessKey = accessKey;
474 }
475
476 public String getSecretKey() {
477 return secretKey;
478 }
479
480 public void setSecretKey(String secretKey) {
481 this.secretKey = secretKey;
482 }
483
484 public String getEndpoint() {
485 return endpoint;
486 }
487
488 public void setEndpoint(String endpoint) {
489 this.endpoint = endpoint;
490 }
491
492 public Integer getPort() {
493 return port;
494 }
495
496 public void setPort(Integer port) {
497 this.port = port;
498 }
499
500 public String getBucket() {
501 return bucket;
502 }
503
504 public void setBucket(String bucket) {
505 this.bucket = bucket;
506 }
507
508 public Boolean isSetPublicReadAclOnPutObject() {
509 return setPublicReadAclOnPutObject;
510 }
511
512 public void setSetPublicReadAclOnPutObject(Boolean setPublicReadAclOnPutObject) {
513 this.setPublicReadAclOnPutObject = setPublicReadAclOnPutObject;
514 }
515
516 public Integer getMaxNumberOfFailedOperations() {
517 return maxNumberOfFailedOperations;
518 }
519
520 public void setMaxNumberOfFailedOperations(Integer maxNumberOfFailedOperations) {
521 this.maxNumberOfFailedOperations = maxNumberOfFailedOperations;
522 }
523
524 public Integer getMaxNumberOfS3Threads() {
525 return maxNumberOfS3Threads;
526 }
527
528 public void setMaxNumberOfS3Threads(Integer maxNumberOfS3Threads) {
529 this.maxNumberOfS3Threads = maxNumberOfS3Threads;
530 }
531 }
532 }
533
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/config/DistributionServiceConfig.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/S3Publisher.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.distribution.objectstore;
22
23 import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
24 import app.coronawarn.server.services.distribution.objectstore.client.ObjectStoreOperationFailedException;
25 import app.coronawarn.server.services.distribution.objectstore.publish.LocalFile;
26 import app.coronawarn.server.services.distribution.objectstore.publish.PublishFileSet;
27 import app.coronawarn.server.services.distribution.objectstore.publish.PublishedFileSet;
28 import java.io.IOException;
29 import java.nio.file.Path;
30 import java.util.List;
31 import java.util.concurrent.ExecutionException;
32 import java.util.concurrent.Future;
33 import java.util.stream.Collectors;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36 import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
37 import org.springframework.stereotype.Component;
38
39 /**
40 * Publishes a folder on the disk to S3 while keeping the folder and file structure.<br> Moreover, does the following:
41 * <br>
42 * <ul>
43 * <li>Publishes index files on a different route, removing the trailing "/index" part.</li>
44 * <li>Adds meta information to the uploaded files, e.g. the sha256 hash value.</li>
45 * <li>Only performs the upload for files, which do not yet exist on the object store, and
46 * checks whether the existing files hash differ from the to-be-uploaded files hash. Only if the
47 * hash differs, the file will ultimately be uploaded</li>
48 * <li>Currently not implemented: Set cache control headers</li>
49 * <li>Currently not implemented: Supports multi threaded upload of files.</li>
50 * </ul>
51 */
52 @Component
53 public class S3Publisher {
54
55 private static final Logger logger = LoggerFactory.getLogger(S3Publisher.class);
56
57 private final ObjectStoreAccess objectStoreAccess;
58 private final FailedObjectStoreOperationsCounter failedOperationsCounter;
59 private final ThreadPoolTaskExecutor executor;
60 private final DistributionServiceConfig distributionServiceConfig;
61
62 /**
63 * Creates an {@link S3Publisher} instance that attempts to publish the files at the specified location to an object
64 * store. Object store operations are performed through the specified {@link ObjectStoreAccess} instance.
65 *
66 * @param objectStoreAccess The {@link ObjectStoreAccess} used to communicate with the object store.
67 * @param failedOperationsCounter The {@link FailedObjectStoreOperationsCounter} that is used to monitor the number
68 * of failed operations.
69 * @param executor The executor that manages the upload task submission.
70 * @param distributionServiceConfig The {@link DistributionServiceConfig} used for distribution service
71 * configuration.
72 */
73 public S3Publisher(ObjectStoreAccess objectStoreAccess, FailedObjectStoreOperationsCounter failedOperationsCounter,
74 ThreadPoolTaskExecutor executor, DistributionServiceConfig distributionServiceConfig) {
75 this.objectStoreAccess = objectStoreAccess;
76 this.failedOperationsCounter = failedOperationsCounter;
77 this.executor = executor;
78 this.distributionServiceConfig = distributionServiceConfig;
79 }
80
81 /**
82 * Synchronizes the files to S3.
83 *
84 * @param root The path of the directory that shall be published.
85 * @throws IOException in case there were problems reading files from the disk.
86 */
87 public void publish(Path root) throws IOException {
88 PublishedFileSet published;
89 List<LocalFile> toPublish = new PublishFileSet(root).getFiles();
90 List<LocalFile> diff;
91
92 try {
93 published = new PublishedFileSet(
94 objectStoreAccess.getObjectsWithPrefix(distributionServiceConfig.getApi().getVersionPath()));
95 diff = toPublish
96 .stream()
97 .filter(published::isNotYetPublished)
98 .collect(Collectors.toList());
99 } catch (ObjectStoreOperationFailedException e) {
100 failedOperationsCounter.incrementAndCheckThreshold(e);
101 // failed to retrieve existing files; publish everything
102 diff = toPublish;
103 }
104
105 logger.info("Beginning upload of {} files... ", diff.size());
106 try {
107 diff.stream()
108 .map(file -> executor.submit(() -> objectStoreAccess.putObject(file)))
109 .forEach(this::awaitThread);
110 } finally {
111 executor.shutdown();
112 }
113 logger.info("Upload completed.");
114 }
115
116 private void awaitThread(Future<?> result) {
117 try {
118 result.get();
119 } catch (ExecutionException e) {
120 failedOperationsCounter.incrementAndCheckThreshold(new ObjectStoreOperationFailedException(e.getMessage(), e));
121 } catch (InterruptedException e) {
122 Thread.currentThread().interrupt();
123 throw new ObjectStoreOperationFailedException(e.getMessage(), e);
124 }
125 }
126 }
127
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/S3Publisher.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/client/S3Object.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.distribution.objectstore.client;
22
23 import java.util.Objects;
24
25 /**
26 * Represents an object as discovered on S3.
27 */
28 public class S3Object {
29
30 /**
31 * the name of the object.
32 */
33 private final String objectName;
34
35 /** The cwaHash of this S3 Object. */
36 private String cwaHash;
37
38 /**
39 * Constructs a new S3Object for the given object name.
40 *
41 * @param objectName the target object name
42 */
43 public S3Object(String objectName) {
44 this.objectName = objectName;
45 }
46
47 /**
48 * Constructs a new S3Object for the given object name.
49 *
50 * @param objectName the target object name
51 * @param cwaHash the checksum for that file
52 */
53 public S3Object(String objectName, String cwaHash) {
54 this(objectName);
55 this.cwaHash = cwaHash;
56 }
57
58 public String getObjectName() {
59 return objectName;
60 }
61
62 public String getCwaHash() {
63 return cwaHash;
64 }
65
66 @Override
67 public boolean equals(Object o) {
68 if (this == o) {
69 return true;
70 }
71 if (o == null || getClass() != o.getClass()) {
72 return false;
73 }
74 S3Object s3Object = (S3Object) o;
75 return Objects.equals(objectName, s3Object.objectName) && Objects.equals(cwaHash, s3Object.cwaHash);
76 }
77
78 @Override
79 public int hashCode() {
80 return Objects.hash(objectName, cwaHash);
81 }
82 }
83
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/client/S3Object.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/publish/LocalFile.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.distribution.objectstore.publish;
22
23 import app.coronawarn.server.services.distribution.assembly.structure.file.FileOnDiskWithChecksum;
24 import java.io.IOException;
25 import java.nio.file.Files;
26 import java.nio.file.Path;
27 import org.slf4j.Logger;
28 import org.slf4j.LoggerFactory;
29
30 /**
31 * Represents a file, which is subject for publishing to S3.
32 */
33 public abstract class LocalFile {
34
35 private static final Logger logger = LoggerFactory.getLogger(LocalFile.class);
36
37 /**
38 * the path to the file to be represented.
39 */
40 private final Path file;
41
42 /**
43 * the assigned S3 key.
44 */
45 private final String s3Key;
46
47 /**
48 * the checksum of this file.
49 */
50 private String checksum = "";
51
52 /**
53 * Constructs a new file representing a file on the disk.
54 *
55 * @param file the path to the file to be represented
56 * @param basePath the base path
57 */
58 public LocalFile(Path file, Path basePath) {
59 this.file = file;
60 this.s3Key = createS3Key(file, basePath);
61 this.checksum = loadChecksum();
62 }
63
64 public String getS3Key() {
65 return s3Key;
66 }
67
68 public String getChecksum() {
69 return checksum;
70 }
71
72 public Path getFile() {
73 return file;
74 }
75
76 private String loadChecksum() {
77 try {
78 return Files.readString(FileOnDiskWithChecksum.buildChecksumPathForFile(file)).trim();
79 } catch (IOException e) {
80 logger.debug("Unable to load checksum file.");
81 return "";
82 }
83 }
84
85 protected String createS3Key(Path file, Path rootFolder) {
86 Path relativePath = rootFolder.relativize(file);
87 return relativePath.toString().replaceAll("\\\\", "/");
88 }
89
90 /**
91 * Value for the <code>content-type</code> header.
92 *
93 * @return Either <a href="https://www.iana.org/assignments/media-types/application/zip">zip</a> or
94 * <a href="https://www.iana.org/assignments/media-types/application/json">json</a>.
95 */
96 public String getContentType() {
97 if (s3Key.endsWith("app_config")) {
98 return "application/zip";
99 }
100 if (s3Key.matches(".*\\d")) {
101 // date and hourly diagnosis key files
102 return "application/zip";
103 }
104 // list of versions, dates, hours
105 return "application/json";
106 }
107 }
108
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/publish/LocalFile.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/publish/PublishedFileSet.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.distribution.objectstore.publish;
22
23 import app.coronawarn.server.services.distribution.objectstore.client.S3Object;
24 import java.util.List;
25 import java.util.Map;
26 import java.util.stream.Collectors;
27
28 /**
29 * Provides an overview about which files are currently available on S3.
30 */
31 public class PublishedFileSet {
32
33 /** ta map of S3 objects with the S3 object name as the key component of the map. */
34 private Map<String, S3Object> s3Objects;
35
36 /**
37 * Creates a new PublishedFileSet for the given S3 objects with the help of the metadata provider.
38 * The metadata provider helps to determine whether files have been changed, and are requiring
39 * re-upload.
40 *
41 * @param s3Objects the list of s3 objects.
42 */
43 public PublishedFileSet(List<S3Object> s3Objects) {
44 this.s3Objects = s3Objects.stream()
45 .collect(Collectors.toMap(S3Object::getObjectName, s3object -> s3object));
46 }
47
48 /**
49 * Checks whether the given file, which is subject for publishing, is already available on the S3.
50 * Will return true, when:
51 * <ul>
52 * <li>The S3 object key exists on S3</li>
53 * <li>The checksum of the existing S3 object matches the hash of the given file</li>
54 * </ul>
55 *
56 * @param file the to-be-published file which should be checked
57 * @return true, if it exists and is identical
58 */
59 public boolean isNotYetPublished(LocalFile file) {
60 S3Object published = s3Objects.get(file.getS3Key());
61
62 if (published == null) {
63 return true;
64 }
65
66 return !file.getChecksum().equals(published.getCwaHash());
67 }
68
69 }
70
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/publish/PublishedFileSet.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/RetentionPolicy.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.distribution.runner;
22
23 import app.coronawarn.server.common.persistence.service.DiagnosisKeyService;
24 import app.coronawarn.server.services.distribution.Application;
25 import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
26 import app.coronawarn.server.services.distribution.objectstore.S3RetentionPolicy;
27 import org.slf4j.Logger;
28 import org.slf4j.LoggerFactory;
29 import org.springframework.boot.ApplicationArguments;
30 import org.springframework.boot.ApplicationRunner;
31 import org.springframework.context.ApplicationContext;
32 import org.springframework.core.annotation.Order;
33 import org.springframework.stereotype.Component;
34
35 /**
36 * This runner removes any diagnosis keys from the database that were submitted before a configured threshold of days.
37 */
38 @Component
39 @Order(1)
40 public class RetentionPolicy implements ApplicationRunner {
41
42 private static final Logger logger = LoggerFactory
43 .getLogger(RetentionPolicy.class);
44
45 private final DiagnosisKeyService diagnosisKeyService;
46
47 private final ApplicationContext applicationContext;
48
49 private final Integer retentionDays;
50
51 private final S3RetentionPolicy s3RetentionPolicy;
52
53 /**
54 * Creates a new RetentionPolicy.
55 */
56 RetentionPolicy(DiagnosisKeyService diagnosisKeyService,
57 ApplicationContext applicationContext,
58 DistributionServiceConfig distributionServiceConfig,
59 S3RetentionPolicy s3RetentionPolicy) {
60 this.diagnosisKeyService = diagnosisKeyService;
61 this.applicationContext = applicationContext;
62 this.retentionDays = distributionServiceConfig.getRetentionDays();
63 this.s3RetentionPolicy = s3RetentionPolicy;
64 }
65
66 @Override
67 public void run(ApplicationArguments args) {
68 try {
69 diagnosisKeyService.applyRetentionPolicy(retentionDays);
70 s3RetentionPolicy.applyRetentionPolicy(retentionDays);
71 } catch (Exception e) {
72 logger.error("Application of retention policy failed.", e);
73 Application.killApplication(applicationContext);
74 }
75
76 logger.debug("Retention policy applied successfully.");
77 }
78 }
79
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/RetentionPolicy.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/S3Distribution.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.distribution.runner;
22
23 import app.coronawarn.server.services.distribution.assembly.component.OutputDirectoryProvider;
24 import app.coronawarn.server.services.distribution.objectstore.S3Publisher;
25 import app.coronawarn.server.services.distribution.objectstore.client.ObjectStoreOperationFailedException;
26 import java.io.IOException;
27 import java.nio.file.Path;
28 import org.slf4j.Logger;
29 import org.slf4j.LoggerFactory;
30 import org.springframework.boot.ApplicationArguments;
31 import org.springframework.boot.ApplicationRunner;
32 import org.springframework.core.annotation.Order;
33 import org.springframework.stereotype.Component;
34
35 /**
36 * This runner will sync the base working directory to the S3.
37 */
38 @Component
39 @Order(3)
40 public class S3Distribution implements ApplicationRunner {
41
42 private static final Logger logger = LoggerFactory.getLogger(S3Distribution.class);
43
44 private final OutputDirectoryProvider outputDirectoryProvider;
45 private final S3Publisher s3Publisher;
46
47 S3Distribution(OutputDirectoryProvider outputDirectoryProvider, S3Publisher s3Publisher) {
48 this.outputDirectoryProvider = outputDirectoryProvider;
49 this.s3Publisher = s3Publisher;
50 }
51
52 @Override
53 public void run(ApplicationArguments args) {
54 try {
55 Path pathToDistribute = outputDirectoryProvider.getFileOnDisk().toPath().toAbsolutePath();
56
57 s3Publisher.publish(pathToDistribute);
58 logger.info("Data pushed to Object Store successfully.");
59 } catch (UnsupportedOperationException | ObjectStoreOperationFailedException | IOException e) {
60 logger.error("Distribution failed.", e);
61 }
62 }
63 }
64
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/S3Distribution.java]
[start of services/distribution/src/main/resources/application.yaml]
1 ---
2 logging:
3 level:
4 org:
5 springframework:
6 web: INFO
7 app:
8 coronawarn: INFO
9
10 services:
11 distribution:
12 # The name of the distribution output file.
13 output-file-name: index
14 # The number of days to retain diagnosis keys for both database persistency layer and files stored on the object store.
15 retention-days: 14
16 # The number of minutes that diagnosis keys must have been expired for (since the end of the rolling interval window) before they can be distributed.
17 expiry-policy-minutes: 120
18 # The minimum number of diagnosis keys per bundle.
19 shifting-policy-threshold: 140
20 # The maximum number of keys per bundle.
21 maximum-number-of-keys-per-bundle: 600000
22 # Indicates whether the current incomplete day will be included in the distribution (used for testing purposes).
23 include-incomplete-days: false
24 # Indicates whether the current incomplete hour will be included in the distribution (used for testing purposes).
25 include-incomplete-hours: false
26 # Local paths, that are used during the export creation.
27 paths:
28 # The output path.
29 output: out
30 # The location of the private key.
31 privatekey: ${VAULT_FILESIGNING_SECRET}
32 # Configuration for the exported archive, that is saved on the S3-compatible storage.
33 tek-export:
34 # The TEK file name included in the zip archive, containing the list of diagnosis keys.
35 file-name: export.bin
36 # The TEK file header.
37 file-header: EK Export v1
38 # The fixed (ensured by right whitespace padding) TEK file header width.
39 file-header-width: 16
40 # Configuration for the API which is used by the mobile app to query diagnosis keys.
41 api:
42 version-path: version
43 version-v1: v1
44 country-path: country
45 country-germany: DE
46 date-path: date
47 hour-path: hour
48 diagnosis-keys-path: diagnosis-keys
49 parameters-path: configuration
50 app-config-file-name: app_config
51 # Signature configuration, used for signing the exports.
52 signature:
53 # The alias with which to identify public key to be used for verification.
54 verification-key-id: 262
55 # The key version for rollovers.
56 verification-key-version: v1
57 # The ASN.1 OID for algorithm identifier.
58 algorithm-oid: 1.2.840.10045.4.3.2
59 # The algorithm name.
60 algorithm-name: SHA256withECDSA
61 # The signature file name included in the zip archive.
62 file-name: export.sig
63 # The security provider.
64 security-provider: BC
65 # Configuration for the S3 compatible object storage hosted by Telekom in Germany.
66 objectstore:
67 access-key: ${CWA_OBJECTSTORE_ACCESSKEY:accessKey1}
68 secret-key: ${CWA_OBJECTSTORE_SECRETKEY:verySecretKey1}
69 endpoint: ${CWA_OBJECTSTORE_ENDPOINT:http://localhost}
70 bucket: ${CWA_OBJECTSTORE_BUCKET:cwa}
71 port: ${CWA_OBJECTSTORE_PORT:8003}
72 # Indicates whether the S3 Access Control List (ACL) header should be set to 'public-read' on put object.
73 set-public-read-acl-on-put-object: true
74 # The number of maximum retry attempts used for configuring Spring @Retryable annotation.
75 retry-attempts: 3
76 # The backoff period in milliseconds used for configuring Spring @Retryable annotation.
77 retry-backoff: 2000
78 # The maximum number of failed operations before giving up.
79 max-number-of-failed-operations: 5
80 # The ThreadPoolTaskExecutor's maximum thread pool size.
81 max-number-of-s3-threads: 4
82
83 spring:
84 main:
85 web-application-type: NONE
86 # Postgres configuration
87 flyway:
88 enabled: true
89 locations: classpath:/db/migration, classpath:/db/specific/{vendor}
90 password: ${POSTGRESQL_PASSWORD_FLYWAY:local_setup_flyway}
91 user: ${POSTGRESQL_USER_FLYWAY:local_setup_flyway}
92
93 datasource:
94 driver-class-name: org.postgresql.Driver
95 url: jdbc:postgresql://${POSTGRESQL_SERVICE_HOST}:${POSTGRESQL_SERVICE_PORT}/${POSTGRESQL_DATABASE}?ssl=true&sslmode=verify-full&sslrootcert=${SSL_POSTGRES_CERTIFICATE_PATH}&sslcert=${SSL_DISTRIBUTION_CERTIFICATE_PATH}&sslkey=${SSL_DISTRIBUTION_PRIVATE_KEY_PATH}
96 username: ${POSTGRESQL_USER_DISTRIBUTION:local_setup_distribution}
97 password: ${POSTGRESQL_PASSWORD_DISTRIBUTION:local_setup_distribution}
98
[end of services/distribution/src/main/resources/application.yaml]
</code>
Here is an example of a patch file. It consists of changes to the code base. It specifies the file names, the line numbers of each change, and the removed and added lines. A single patch file can contain changes to multiple files.
<patch>
--- a/file.py
+++ b/file.py
@@ -1,27 +1,35 @@
def euclidean(a, b):
- while b:
- a, b = b, a % b
- return a
+ if b == 0:
+ return a
+ return euclidean(b, a % b)
def bresenham(x0, y0, x1, y1):
points = []
dx = abs(x1 - x0)
dy = abs(y1 - y0)
- sx = 1 if x0 < x1 else -1
- sy = 1 if y0 < y1 else -1
- err = dx - dy
+ x, y = x0, y0
+ sx = -1 if x0 > x1 else 1
+ sy = -1 if y0 > y1 else 1
- while True:
- points.append((x0, y0))
- if x0 == x1 and y0 == y1:
- break
- e2 = 2 * err
- if e2 > -dy:
+ if dx > dy:
+ err = dx / 2.0
+ while x != x1:
+ points.append((x, y))
err -= dy
- x0 += sx
- if e2 < dx:
- err += dx
- y0 += sy
+ if err < 0:
+ y += sy
+ err += dx
+ x += sx
+ else:
+ err = dy / 2.0
+ while y != y1:
+ points.append((x, y))
+ err -= dx
+ if err < 0:
+ x += sx
+ err += dy
+ y += sy
+ points.append((x, y))
return points
</patch>
I need you to solve the provded issue by generating a single patch file that I can apply directly to this repository using git apply. Please respond with a single patch file in the format shown above.
Respond below:
| corona-warn-app/cwa-server | 7e519598cbf2823ab655a057f8a0f77297bf6ed1 | Wrong hash value for 2020-06-23 and 2020-06-24
<!--
Thanks for proposing an enhancement 🙌 ❤️
Before opening a new issue, please make sure that we do not have any duplicates already open. You can ensure this by searching the issue list for this repository. If there is a duplicate, please close your issue and add a comment to the existing issue instead.
-->
## Current Implementation
<!-- Describe or point to the current implementation that you would like to see improved -->
Old keys are deleted and the remaining keys are repacked by day or by hour.
60 keys moved from 24.06.2020 to 23.06.2020.
44 keys are deleted from 23.06.2020
The hour files 2020-06-23-hour-08.zip, 2020-06-23-hour-13.zip, 2020-06-23-hour-17.zip are repacked to
2020-06-23-hour-10.zip, 2020-06-23-hour-15.zip, 2020-06-23-hour-18.zip
(Even the old hour files are superseded they are still on the server.)
## Suggested Enhancement
<!-- Outline the idea of your enhancement, by e.g., describing the algorithm you propose. You can also create a Pull Request to outline your idea -->
Leave the files as they are, do not remove old keys.
## Expected Benefits
<!-- Summarize how your enhancement could aid the implementation (performance, readability, memory consumption, battery consumption, etc.). Please also back up with measurements or give detailed explanations for reduced runtimes, memory consumption, etc. -->
The files downloaded by the app have the same hash value as the file on the server.
| Initial suspicion: Retention Policy kicked in and deleted older keys, which were not immediately distributed due to shifting policy. This in turn did lead to even less keys for the first days of CWA so the other packages were now also shifted.
<del>I believe this only affects hourly packages as retention enforcement & daily package creation are part of the same job. </del>
<del>
There are some options on how this can be fixed:</del>
1. <del>(Temporary) Disable hourly files. As they are currently not being used by the mobile app, there would be no impact.</del>
2. <del>Run retention only once per day and not on every job. Can be problematic in case this one job did not trigger or failed, so the next retention run would only occur after 24 hours. Not a big issue though.</del>
3. Store some pointer/information on the database which indicates which keys were already distributed. There are some edge cases which make this approach more complicated though (e.g. shifting keys due to 2 hours key validity expiration).
Edit: Daily files are just as affected as hourly files. Guess this leaves only one option. @pithumke what do you think?
Today 2020-06-24.zip on the server has the same values and hash as it was first publish (so the 60 moved keys moved back).
2020-06-23.zip does not contain 173 keys of the original file. But this time, on IOS, the file has been downloaded again, why??
The hash and the # of keys are the same in IOS and on the server (330 keys now).
All keys publish in 2020-06-23-hour-08.zip are missing in the daily file 2020-06-23.zip, now.
Is this expected?
| 2020-07-20T15:16:34 | <patch>
diff --git a/docker-compose.yml b/docker-compose.yml
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -46,6 +46,7 @@ services:
services.distribution.paths.output: /tmp/distribution
# Settings for cryptographic artifacts
VAULT_FILESIGNING_SECRET: ${SECRET_PRIVATE}
+ FORCE_UPDATE_KEYFILES: 'false'
volumes:
- ./docker-compose-test-secrets:/secrets
postgres:
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/ProdDiagnosisKeyBundler.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/ProdDiagnosisKeyBundler.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/ProdDiagnosisKeyBundler.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/ProdDiagnosisKeyBundler.java
@@ -31,6 +31,7 @@
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Collection;
+import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -83,6 +84,9 @@ protected void createDiagnosisKeyDistributionMap(Collection<DiagnosisKey> diagno
if (diagnosisKeyAccumulator.size() >= minNumberOfKeysPerBundle) {
this.distributableDiagnosisKeys.put(currentHour, new ArrayList<>(diagnosisKeyAccumulator));
diagnosisKeyAccumulator.clear();
+ } else {
+ // placeholder list is needed to be able to generate empty file - see issue #650
+ this.distributableDiagnosisKeys.put(currentHour, Collections.emptyList());
}
});
}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/config/DistributionServiceConfig.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/config/DistributionServiceConfig.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/config/DistributionServiceConfig.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/config/DistributionServiceConfig.java
@@ -464,6 +464,7 @@ public static class ObjectStore {
@Min(1)
@Max(64)
private Integer maxNumberOfS3Threads;
+ private Boolean forceUpdateKeyfiles;
public String getAccessKey() {
return accessKey;
@@ -528,5 +529,13 @@ public Integer getMaxNumberOfS3Threads() {
public void setMaxNumberOfS3Threads(Integer maxNumberOfS3Threads) {
this.maxNumberOfS3Threads = maxNumberOfS3Threads;
}
+
+ public Boolean getForceUpdateKeyfiles() {
+ return forceUpdateKeyfiles;
+ }
+
+ public void setForceUpdateKeyfiles(Boolean forceUpdateKeyfiles) {
+ this.forceUpdateKeyfiles = forceUpdateKeyfiles;
+ }
}
}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/S3Publisher.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/S3Publisher.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/S3Publisher.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/S3Publisher.java
@@ -79,28 +79,25 @@ public S3Publisher(ObjectStoreAccess objectStoreAccess, FailedObjectStoreOperati
}
/**
- * Synchronizes the files to S3.
+ * Synchronizes the files to S3. Current strategy is to never update diagnosis key archive files already
+ * published on S3, even if the retention and shifting policies cause a diff between subsequent distribution runs.
+ * Thus, by default distribution will only add new key files, but still modify indexes. This behaviour can however
+ * be controlled through the configuration parameter <code>DistributionServiceConfig.forceUpdateKeyFiles</code>
*
* @param root The path of the directory that shall be published.
+ * @see Github issue #650
* @throws IOException in case there were problems reading files from the disk.
*/
public void publish(Path root) throws IOException {
- PublishedFileSet published;
List<LocalFile> toPublish = new PublishFileSet(root).getFiles();
- List<LocalFile> diff;
- try {
- published = new PublishedFileSet(
- objectStoreAccess.getObjectsWithPrefix(distributionServiceConfig.getApi().getVersionPath()));
- diff = toPublish
- .stream()
- .filter(published::isNotYetPublished)
- .collect(Collectors.toList());
- } catch (ObjectStoreOperationFailedException e) {
- failedOperationsCounter.incrementAndCheckThreshold(e);
- // failed to retrieve existing files; publish everything
- diff = toPublish;
- }
+ PublishedFileSet published = new PublishedFileSet(
+ objectStoreAccess.getObjectsWithPrefix(distributionServiceConfig.getApi().getVersionPath()),
+ distributionServiceConfig.getObjectStore().getForceUpdateKeyfiles());
+ List<LocalFile> diff = toPublish
+ .stream()
+ .filter(published::shouldPublish)
+ .collect(Collectors.toList());
logger.info("Beginning upload of {} files... ", diff.size());
try {
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/client/S3Object.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/client/S3Object.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/client/S3Object.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/client/S3Object.java
@@ -63,6 +63,15 @@ public String getCwaHash() {
return cwaHash;
}
+ /**
+ * Indicates if the S3 object is a file with diagnosis key content.
+ * The evaluation is based on the distribution logic which implies that such files are generated
+ * with a Date / Hour S3 key format (days: 1-31 / hours: 0-23) ending in 2 digits.
+ */
+ public boolean isDiagnosisKeyFile() {
+ return Objects.nonNull(objectName) && objectName.matches(".*\\d\\d");
+ }
+
@Override
public boolean equals(Object o) {
if (this == o) {
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/publish/LocalFile.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/publish/LocalFile.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/publish/LocalFile.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/publish/LocalFile.java
@@ -97,11 +97,21 @@ public String getContentType() {
if (s3Key.endsWith("app_config")) {
return "application/zip";
}
- if (s3Key.matches(".*\\d")) {
+ if (isKeyFile()) {
// date and hourly diagnosis key files
return "application/zip";
}
// list of versions, dates, hours
return "application/json";
}
+
+ /**
+ * Indicates if a local file is a Key-file or not. Only the Key files are stored in the Date / Hour tree structure.
+ * One file per sub-folder (days: 1-31 / hours: 0-23). The index files are not stored in folders ending with a digit.
+ *
+ * @return <code>true</code> if and only if the {@link #s3Key} ends with a digit, false otherwise.
+ */
+ public boolean isKeyFile() {
+ return s3Key.matches(".*\\d");
+ }
}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/publish/PublishedFileSet.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/publish/PublishedFileSet.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/publish/PublishedFileSet.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/publish/PublishedFileSet.java
@@ -32,37 +32,52 @@ public class PublishedFileSet {
/** ta map of S3 objects with the S3 object name as the key component of the map. */
private Map<String, S3Object> s3Objects;
+ private boolean isKeyFilePublishingAllowed;
+
/**
- * Creates a new PublishedFileSet for the given S3 objects with the help of the metadata provider.
- * The metadata provider helps to determine whether files have been changed, and are requiring
- * re-upload.
+ * Creates a new PublishedFileSet for the given S3 objects with the help of the
+ * metadata provider. The metadata provider helps to determine whether files
+ * have been changed, and are requiring re-upload.
*
- * @param s3Objects the list of s3 objects.
+ * @param s3Objects the list of s3 objects.
+ * @param isKeyFilePublishingAllowed whether the system is currently configured
+ * to allow diagnosis key file updates on S3
*/
- public PublishedFileSet(List<S3Object> s3Objects) {
+ public PublishedFileSet(List<S3Object> s3Objects, boolean isKeyFilePublishingAllowed) {
this.s3Objects = s3Objects.stream()
.collect(Collectors.toMap(S3Object::getObjectName, s3object -> s3object));
+ this.isKeyFilePublishingAllowed = isKeyFilePublishingAllowed;
}
/**
- * Checks whether the given file, which is subject for publishing, is already available on the S3.
- * Will return true, when:
+ * Checks whether the given file, which is subject for publishing, is already available on the S3. Will return true,
+ * when:
* <ul>
- * <li>The S3 object key exists on S3</li>
- * <li>The checksum of the existing S3 object matches the hash of the given file</li>
+ * <li>The S3 object key does NOT exist on S3.</li>
+ * <li>The environment variable FORCE_UPDATE_KEYFILES is set to true.</li>
+ * <li>The checksum of the existing S3 object differs to the hash of the given file.</li>
* </ul>
*
* @param file the to-be-published file which should be checked
- * @return true, if it exists and is identical
+ * @return {@code true}, if it doesn't exist or differs - {@code false}, if the file has been published already
*/
- public boolean isNotYetPublished(LocalFile file) {
+ public boolean shouldPublish(LocalFile file) {
S3Object published = s3Objects.get(file.getS3Key());
if (published == null) {
return true;
}
+ if (file.isKeyFile()) {
+ // #650 - once published key files should not be changed anymore unless explicitly forced
+ return isKeyFilePublishingAllowed && contentChanged(file, published);
+ }
+
+ return contentChanged(file, published);
+ }
+
+ private boolean contentChanged(LocalFile file, S3Object published) {
return !file.getChecksum().equals(published.getCwaHash());
}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/RetentionPolicy.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/RetentionPolicy.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/RetentionPolicy.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/RetentionPolicy.java
@@ -53,7 +53,7 @@ public class RetentionPolicy implements ApplicationRunner {
/**
* Creates a new RetentionPolicy.
*/
- RetentionPolicy(DiagnosisKeyService diagnosisKeyService,
+ public RetentionPolicy(DiagnosisKeyService diagnosisKeyService,
ApplicationContext applicationContext,
DistributionServiceConfig distributionServiceConfig,
S3RetentionPolicy s3RetentionPolicy) {
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/S3Distribution.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/S3Distribution.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/S3Distribution.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/S3Distribution.java
@@ -20,6 +20,7 @@
package app.coronawarn.server.services.distribution.runner;
+import app.coronawarn.server.services.distribution.Application;
import app.coronawarn.server.services.distribution.assembly.component.OutputDirectoryProvider;
import app.coronawarn.server.services.distribution.objectstore.S3Publisher;
import app.coronawarn.server.services.distribution.objectstore.client.ObjectStoreOperationFailedException;
@@ -29,6 +30,7 @@
import org.slf4j.LoggerFactory;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
+import org.springframework.context.ApplicationContext;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@@ -43,10 +45,13 @@ public class S3Distribution implements ApplicationRunner {
private final OutputDirectoryProvider outputDirectoryProvider;
private final S3Publisher s3Publisher;
+ private final ApplicationContext applicationContext;
- S3Distribution(OutputDirectoryProvider outputDirectoryProvider, S3Publisher s3Publisher) {
+ S3Distribution(OutputDirectoryProvider outputDirectoryProvider, S3Publisher s3Publisher,
+ ApplicationContext applicationContext) {
this.outputDirectoryProvider = outputDirectoryProvider;
this.s3Publisher = s3Publisher;
+ this.applicationContext = applicationContext;
}
@Override
@@ -58,6 +63,7 @@ public void run(ApplicationArguments args) {
logger.info("Data pushed to Object Store successfully.");
} catch (UnsupportedOperationException | ObjectStoreOperationFailedException | IOException e) {
logger.error("Distribution failed.", e);
+ Application.killApplication(applicationContext);
}
}
}
diff --git a/services/distribution/src/main/resources/application.yaml b/services/distribution/src/main/resources/application.yaml
--- a/services/distribution/src/main/resources/application.yaml
+++ b/services/distribution/src/main/resources/application.yaml
@@ -79,6 +79,8 @@ services:
max-number-of-failed-operations: 5
# The ThreadPoolTaskExecutor's maximum thread pool size.
max-number-of-s3-threads: 4
+ # Allows distribution to overwrite files which are published on the object store
+ force-update-keyfiles: ${FORCE_UPDATE_KEYFILES:false}
spring:
main:
</patch> | diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/ProdDiagnosisKeyBundlerKeyRetrievalTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/ProdDiagnosisKeyBundlerKeyRetrievalTest.java
--- a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/ProdDiagnosisKeyBundlerKeyRetrievalTest.java
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/ProdDiagnosisKeyBundlerKeyRetrievalTest.java
@@ -89,7 +89,7 @@ void testGetsDatesWithDistributableDiagnosisKeys() {
@MethodSource("createDiagnosisKeysForEpochDay0")
void testGetDatesForEpochDay0(Collection<DiagnosisKey> diagnosisKeys) {
bundler.setDiagnosisKeys(diagnosisKeys, LocalDateTime.of(1970, 1, 5, 0, 0));
- var expDates = Set.of(LocalDate.ofEpochDay(2L));
+ var expDates = Set.of(LocalDate.ofEpochDay(2L), LocalDate.ofEpochDay(3L));
var actDates = bundler.getDatesWithDistributableDiagnosisKeys();
assertThat(actDates).isEqualTo(expDates);
}
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysDateDirectoryTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysDateDirectoryTest.java
--- a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysDateDirectoryTest.java
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysDateDirectoryTest.java
@@ -46,6 +46,7 @@
import java.util.stream.IntStream;
import org.junit.Rule;
import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.rules.TemporaryFolder;
@@ -105,9 +106,10 @@ void testCreatesCorrectDirectoryStructureForMultipleDates() {
runDateDistribution(diagnosisKeys, LocalDateTime.of(1970, 1, 6, 0, 0));
Set<String> actualFiles = Helpers.getFilePaths(outputFile, outputFile.getAbsolutePath());
Set<String> expectedDateAndHourFiles = getExpectedDateAndHourFiles(Map.of(
- "1970-01-03", List.of("0", "1", "2", "3", "4"),
- "1970-01-04", List.of("0", "1", "2", "3", "4"),
- "1970-01-05", List.of("0", "1", "2", "3", "4")), "1970-01-06");
+ "1970-01-03", listOfHoursAsStrings(0, 23),
+ "1970-01-04", listOfHoursAsStrings(0, 23),
+ "1970-01-05", listOfHoursAsStrings(0, 23)),
+ "1970-01-06");
assertThat(actualFiles).isEqualTo(expectedDateAndHourFiles);
}
@@ -124,14 +126,17 @@ void testDoesNotIncludeCurrentDateInDirectoryStructure() {
runDateDistribution(diagnosisKeys, LocalDateTime.of(1970, 1, 5, 12, 0));
Set<String> actualFiles = Helpers.getFilePaths(outputFile, outputFile.getAbsolutePath());
Set<String> expectedDateAndHourFiles = getExpectedDateAndHourFiles(Map.of(
- "1970-01-03", List.of("0", "1", "2", "3", "4"),
- "1970-01-04", List.of("0", "1", "2", "3", "4"),
- "1970-01-05", List.of("0", "1", "2", "3", "4")), "1970-01-05");
+ "1970-01-03", listOfHoursAsStrings(0, 23),
+ "1970-01-04", listOfHoursAsStrings(0, 23),
+ "1970-01-05", listOfHoursAsStrings(0, 11)), "1970-01-05");
assertThat(actualFiles).isEqualTo(expectedDateAndHourFiles);
}
@Test
- void testDoesNotIncludeEmptyDatesInDirectoryStructure() {
+ @Disabled("Temporarily disabling this test as part of the fix for issue #650."
+ + "There seems to be a timing issue with this test because running it individually works, but running it"
+ + " in a suite will cause it to produce a different output then expected. Further investigation is required here ")
+ void testIncludesEmptyDatesInDirectoryStructure() {
Collection<DiagnosisKey> diagnosisKeys = IntStream.range(0, 3)
.filter(currentDate -> currentDate != 1)
.mapToObj(currentDate -> IntStream.range(0, 5)
@@ -145,13 +150,14 @@ void testDoesNotIncludeEmptyDatesInDirectoryStructure() {
runDateDistribution(diagnosisKeys, LocalDateTime.of(1970, 1, 5, 12, 0));
Set<String> actualFiles = Helpers.getFilePaths(outputFile, outputFile.getAbsolutePath());
Set<String> expectedDateAndHourFiles = getExpectedDateAndHourFiles(Map.of(
- "1970-01-03", List.of("0", "1", "2", "3", "4"),
- "1970-01-05", List.of("0", "1", "2", "3", "4")), "1970-01-05");
+ "1970-01-03", listOfHoursAsStrings(0, 23),
+ "1970-01-04", listOfHoursAsStrings(0, 23),
+ "1970-01-05", listOfHoursAsStrings(0, 11)), "1970-01-05");
assertThat(actualFiles).isEqualTo(expectedDateAndHourFiles);
}
@Test
- void testDoesNotIncludeDatesWithTooFewKeysInDirectoryStructure() {
+ void testIncludesDatesWithFewerKeysThanThresholdInDirectoryStructure() {
Collection<DiagnosisKey> diagnosisKeys = List.of(
buildDiagnosisKeys(6, LocalDateTime.of(1970, 1, 3, 1, 0), 5),
buildDiagnosisKeys(6, LocalDateTime.of(1970, 1, 4, 1, 0), 4),
@@ -162,8 +168,10 @@ void testDoesNotIncludeDatesWithTooFewKeysInDirectoryStructure() {
runDateDistribution(diagnosisKeys, LocalDateTime.of(1970, 1, 6, 12, 0));
Set<String> actualFiles = Helpers.getFilePaths(outputFile, outputFile.getAbsolutePath());
Set<String> expectedDateAndHourFiles = getExpectedDateAndHourFiles(Map.of(
- "1970-01-03", List.of("1"),
- "1970-01-05", List.of("1")), "1970-01-06");
+ "1970-01-03", listOfHoursAsStrings(1, 23),
+ "1970-01-04", listOfHoursAsStrings(0, 23),
+ "1970-01-05", listOfHoursAsStrings(0, 23),
+ "1970-01-06", listOfHoursAsStrings(0, 11)), "1970-01-06");
assertThat(actualFiles).isEqualTo(expectedDateAndHourFiles);
}
@@ -179,13 +187,16 @@ void testDoesNotIncludeDatesInTheFuture() {
runDateDistribution(diagnosisKeys, LocalDateTime.of(1970, 1, 4, 12, 0));
Set<String> actualFiles = Helpers.getFilePaths(outputFile, outputFile.getAbsolutePath());
Set<String> expectedDateAndHourFiles = getExpectedDateAndHourFiles(Map.of(
- "1970-01-03", List.of("1"),
- "1970-01-04", List.of("1")), "1970-01-04");
+ "1970-01-03", listOfHoursAsStrings(1, 23),
+ "1970-01-04", listOfHoursAsStrings(0, 11)), "1970-01-04");
assertThat(actualFiles).isEqualTo(expectedDateAndHourFiles);
}
@Test
void testWhenDemoProfileIsActiveItDoesIncludeCurrentDateInDirectoryStructure() {
+ // set the incomplete days configuration for this particular test but revert before test ends
+ // such that other tests are
+ Boolean currentIncompleteDaysConfig = distributionServiceConfig.getIncludeIncompleteDays();
distributionServiceConfig.setIncludeIncompleteDays(true);
Collection<DiagnosisKey> diagnosisKeys = IntStream.range(0, 3)
.mapToObj(currentDate -> IntStream.range(0, 5)
@@ -198,12 +209,19 @@ void testWhenDemoProfileIsActiveItDoesIncludeCurrentDateInDirectoryStructure() {
runDateDistribution(diagnosisKeys, LocalDateTime.of(1970, 1, 5, 12, 0));
Set<String> actualFiles = Helpers.getFilePaths(outputFile, outputFile.getAbsolutePath());
Set<String> expectedDateAndHourFiles = getExpectedDateAndHourFiles(Map.of(
- "1970-01-03", List.of("0", "1", "2", "3", "4"),
- "1970-01-04", List.of("0", "1", "2", "3", "4"),
- "1970-01-05", List.of("0", "1", "2", "3", "4")), "1970-01-05");
+ "1970-01-03", listOfHoursAsStrings(0, 23),
+ "1970-01-04", listOfHoursAsStrings(0, 23),
+ "1970-01-05", listOfHoursAsStrings(0, 11)), "1970-01-05");
expectedDateAndHourFiles.addAll(Set.of(
String.join(separator, "date", "1970-01-05", "index"),
String.join(separator, "date", "1970-01-05", "index.checksum")));
+
+ distributionServiceConfig.setIncludeIncompleteDays(currentIncompleteDaysConfig);
assertThat(actualFiles).isEqualTo(expectedDateAndHourFiles);
}
+
+ private static List<String> listOfHoursAsStrings(int from, int until) {
+ return IntStream.range(from, until + 1).mapToObj(String::valueOf).collect(Collectors.toList());
+ }
+
}
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysDirectoryTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysDirectoryTest.java
--- a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysDirectoryTest.java
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysDirectoryTest.java
@@ -148,7 +148,8 @@ void checkBuildsTheCorrectDirectoryStructure() {
join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-03", "hour", "17", "index"),
join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-03", "hour", "18", "index"),
join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-03", "hour", "19", "index"),
- // One missing
+ // One missing from data, but still we should a structure created because of the empty file (issue #650)
+ join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-03", "hour", "20", "index"),
join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-03", "hour", "21", "index"),
join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-03", "hour", "22", "index"),
join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-03", "hour", "23", "index"),
@@ -159,7 +160,25 @@ void checkBuildsTheCorrectDirectoryStructure() {
join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-04", "hour", "2", "index"),
join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-04", "hour", "3", "index"),
join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-04", "hour", "4", "index"),
- join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-04", "hour", "5", "index")
+ join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-04", "hour", "5", "index"),
+ join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-04", "hour", "6", "index"),
+ join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-04", "hour", "7", "index"),
+ join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-04", "hour", "8", "index"),
+ join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-04", "hour", "9", "index"),
+ join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-04", "hour", "10", "index"),
+ join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-04", "hour", "11", "index"),
+ join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-04", "hour", "12", "index"),
+ join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-04", "hour", "13", "index"),
+ join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-04", "hour", "14", "index"),
+ join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-04", "hour", "15", "index"),
+ join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-04", "hour", "16", "index"),
+ join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-04", "hour", "17", "index"),
+ join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-04", "hour", "18", "index"),
+ join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-04", "hour", "19", "index"),
+ join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-04", "hour", "20", "index"),
+ join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-04", "hour", "21", "index"),
+ join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-04", "hour", "22", "index"),
+ join(s, "diagnosis-keys", "country", "DE", "date", "1970-01-04", "hour", "23", "index")
);
Set<String> actualFiles = getFilePaths(outputFile, outputFile.getAbsolutePath());
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysHourDirectoryTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysHourDirectoryTest.java
--- a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysHourDirectoryTest.java
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysHourDirectoryTest.java
@@ -44,6 +44,7 @@
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
+
import org.junit.Rule;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -100,23 +101,11 @@ void testCreatesCorrectStructureForMultipleHours() {
.mapToObj(currentHour -> buildDiagnosisKeys(6, LocalDateTime.of(1970, 1, 3, 0, 0).plusHours(currentHour), 5))
.flatMap(List::stream)
.collect(Collectors.toList());
- runHourDistribution(diagnosisKeys, LocalDateTime.of(1970, 1, 5, 0, 0),
+ runHourDistribution(diagnosisKeys, LocalDateTime.of(1970, 1, 4, 0, 0),
LocalDate.of(1970, 1, 3));
Set<String> actualFiles = getFilePaths(outputFile, outputFile.getAbsolutePath());
- assertThat(actualFiles).isEqualTo(getExpectedHourFiles(Set.of("0", "1", "2", "3", "4")));
- }
-
- @Test
- void testDoesNotIncludeEmptyHours() {
- Collection<DiagnosisKey> diagnosisKeys = IntStream.range(0, 5)
- .filter(currentHour -> currentHour != 3)
- .mapToObj(currentHour -> buildDiagnosisKeys(6, LocalDateTime.of(1970, 1, 3, 0, 0).plusHours(currentHour), 5))
- .flatMap(List::stream)
- .collect(Collectors.toList());
- runHourDistribution(diagnosisKeys, LocalDateTime.of(1970, 1, 5, 0, 0),
- LocalDate.of(1970, 1, 3));
- Set<String> actualFiles = getFilePaths(outputFile, outputFile.getAbsolutePath());
- assertThat(actualFiles).isEqualTo(getExpectedHourFiles(Set.of("0", "1", "2", "4")));
+ assertThat(actualFiles).isEqualTo(getExpectedHourFiles(
+ IntStream.range(0, 24).mapToObj(String::valueOf).collect(Collectors.toSet())));
}
@Test
@@ -131,21 +120,6 @@ void testDoesNotIncludeCurrentHour() {
assertThat(actualFiles).isEqualTo(getExpectedHourFiles(Set.of("0", "1", "2", "3")));
}
- @Test
- void testDoesNotIncludeHoursWithTooFewKeys() {
- Collection<DiagnosisKey> diagnosisKeys = List.of(
- buildDiagnosisKeys(6, LocalDateTime.of(1970, 1, 3, 0, 0), 5),
- buildDiagnosisKeys(6, LocalDateTime.of(1970, 1, 3, 1, 0), 4),
- buildDiagnosisKeys(6, LocalDateTime.of(1970, 1, 3, 2, 0), 5))
- .stream()
- .flatMap(List::stream)
- .collect(Collectors.toList());
- runHourDistribution(diagnosisKeys, LocalDateTime.of(1970, 1, 6, 12, 0),
- LocalDate.of(1970, 1, 3));
- Set<String> actualFiles = getFilePaths(outputFile, outputFile.getAbsolutePath());
- assertThat(actualFiles).isEqualTo(getExpectedHourFiles(Set.of("0", "2")));
- }
-
@Test
void testDoesNotIncludeHoursInTheFuture() {
Collection<DiagnosisKey> diagnosisKeys = List.of(
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/decorator/DateIndexingDecoratorTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/decorator/DateIndexingDecoratorTest.java
--- a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/decorator/DateIndexingDecoratorTest.java
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/decorator/DateIndexingDecoratorTest.java
@@ -66,24 +66,6 @@ void setup() {
diagnosisKeyBundler = new ProdDiagnosisKeyBundler(distributionServiceConfig);
}
- @Test
- void excludesEmptyDatesFromIndex() {
- List<DiagnosisKey> diagnosisKeys = Stream
- .of(buildDiagnosisKeys(6, LocalDateTime.of(1970, 1, 3, 0, 0), 5),
- buildDiagnosisKeys(6, LocalDateTime.of(1970, 1, 4, 0, 0), 0),
- buildDiagnosisKeys(6, LocalDateTime.of(1970, 1, 5, 0, 0), 5))
- .flatMap(List::stream)
- .collect(Collectors.toList());
- diagnosisKeyBundler.setDiagnosisKeys(diagnosisKeys, LocalDateTime.of(1970, 1, 6, 0, 0));
- DateIndexingDecorator decorator = makeDecoratedDateDirectory(diagnosisKeyBundler);
- decorator.prepare(new ImmutableStack<>().push("DE"));
-
- Set<LocalDate> index = decorator.getIndex(new ImmutableStack<>());
-
- assertThat(index).contains(LocalDate.of(1970, 1, 3))
- .doesNotContain(LocalDate.of(1970, 1, 4))
- .contains(LocalDate.of(1970, 1, 5));
- }
@Test
void excludesCurrentDateFromIndex() {
@@ -112,7 +94,7 @@ void excludesDatesThatExceedTheMaximumNumberOfKeys() {
when(svcConfig.getMaximumNumberOfKeysPerBundle()).thenReturn(1);
DiagnosisKeyBundler diagnosisKeyBundler = new ProdDiagnosisKeyBundler(svcConfig);
- diagnosisKeyBundler.setDiagnosisKeys(diagnosisKeys, LocalDateTime.of(1970, 1, 5, 0, 0));
+ diagnosisKeyBundler.setDiagnosisKeys(diagnosisKeys, LocalDateTime.of(1970, 1, 4, 0, 0));
DateIndexingDecorator decorator = makeDecoratedDateDirectory(diagnosisKeyBundler);
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/decorator/HourIndexingDecoratorTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/decorator/HourIndexingDecoratorTest.java
--- a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/decorator/HourIndexingDecoratorTest.java
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/decorator/HourIndexingDecoratorTest.java
@@ -73,7 +73,7 @@ void tearDown() {
}
@Test
- void excludesHoursThatExceedTheMaximumNumberOfKeys() {
+ void excludesHoursThatExceedTheMaximumNumberOfKeysPerBundle() {
List<DiagnosisKey> diagnosisKeys = buildDiagnosisKeys(6, LocalDateTime.of(1970, 1, 3, 4, 0), 2);
TimeUtils.setNow(LocalDateTime.of(1970, 1, 3, 0, 0).toInstant(ZoneOffset.UTC));
@@ -84,7 +84,7 @@ void excludesHoursThatExceedTheMaximumNumberOfKeys() {
when(svcConfig.getMaximumNumberOfKeysPerBundle()).thenReturn(1);
DiagnosisKeyBundler diagnosisKeyBundler = new ProdDiagnosisKeyBundler(svcConfig);
- diagnosisKeyBundler.setDiagnosisKeys(diagnosisKeys, LocalDateTime.of(1970, 1, 5, 0, 0));
+ diagnosisKeyBundler.setDiagnosisKeys(diagnosisKeys, LocalDateTime.of(1970, 1, 3, 5, 0));
HourIndexingDecorator decorator = makeDecoratedHourDirectory(diagnosisKeyBundler);
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/common/DiagnosisTestData.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/common/DiagnosisTestData.java
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/common/DiagnosisTestData.java
@@ -0,0 +1,87 @@
+/*-
+ * ---license-start
+ * Corona-Warn-App
+ * ---
+ * Copyright (C) 2020 SAP SE and all other contributors
+ * ---
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://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 for the specific language governing permissions and
+ * limitations under the License.
+ * ---license-end
+ */
+
+package app.coronawarn.server.services.distribution.common;
+
+import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
+import java.time.LocalDate;
+import java.time.LocalDateTime;
+import java.time.ZoneOffset;
+import java.time.temporal.ChronoUnit;
+import java.util.List;
+import java.util.Random;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+
+/**
+ * A simple container class able to create diagnosis keys test data, given a set of days or day intervals expresed in
+ * <code>java.time.*</code> structures.
+ */
+public final class DiagnosisTestData {
+
+ private List<DiagnosisKey> diagnosisKeys;
+
+ private DiagnosisTestData() {
+ }
+
+ public List<DiagnosisKey> getDiagnosisKeys() {
+ return diagnosisKeys;
+ }
+
+ /**
+ * @return An instance that contains diagnosis keys computed for the given interval of days. Each day will have a
+ * number of keys equal to the given <code>casesPerDay</code> parameter, recorded, for simplicity, in the last hour of
+ * the day.
+ */
+ public static DiagnosisTestData of(LocalDate fromDay, LocalDate untilDay, int casesPerDay) {
+
+ int numberOfDays = (int) ChronoUnit.DAYS.between(fromDay, untilDay) + 1;
+ DiagnosisTestData testData = new DiagnosisTestData();
+
+ testData.diagnosisKeys = computeDiagnosisKeys(testData, fromDay, numberOfDays, casesPerDay);
+ return testData;
+ }
+
+ private static List<DiagnosisKey> computeDiagnosisKeys(DiagnosisTestData testData, LocalDate fromDay,
+ int numberOFDays, int casesPerDay) {
+ return IntStream.range(0, numberOFDays)
+ .mapToObj(day ->
+ randomDiagnosisKeys(fromDay.atStartOfDay().plusDays(day).plusHours(23), casesPerDay)
+ ).flatMap(List::stream).collect(Collectors.toList());
+ }
+
+ private static List<DiagnosisKey> randomDiagnosisKeys(LocalDateTime submissionTime, int casesPerDay) {
+ long timestamp = submissionTime.toEpochSecond(ZoneOffset.UTC) / 3600;
+ return IntStream.range(0, casesPerDay)
+ .mapToObj(dayCounter ->
+ DiagnosisKey.builder().withKeyData(randomKeyData())
+ .withRollingStartIntervalNumber(600)
+ .withTransmissionRiskLevel(5).withSubmissionTimestamp(timestamp)
+ .build())
+ .collect(Collectors.toList());
+ }
+
+ private static byte[] randomKeyData() {
+ byte[] exposureKeys = new byte[16];
+ Random random = new Random();
+ random.nextBytes(exposureKeys);
+ return exposureKeys;
+ }
+}
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/S3PublisherTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/S3PublisherTest.java
--- a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/S3PublisherTest.java
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/S3PublisherTest.java
@@ -126,15 +126,6 @@ void uploadOneDueToOneChanged() throws IOException {
verify(objectStoreAccess, times(1)).putObject(any());
}
- @Test
- void uploadAllDueToError() throws IOException {
- when(objectStoreAccess.getObjectsWithPrefix("version")).thenThrow(new ObjectStoreOperationFailedException(""));
-
- s3Publisher.publish(publishingPath);
-
- verify(objectStoreAccess, times(3)).putObject(any());
- }
-
@Test
void executorGetsShutDown() throws IOException {
when(objectStoreAccess.getObjectsWithPrefix("version")).thenReturn(emptyList());
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/client/S3ClientWrapperTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/client/S3ClientWrapperTest.java
--- a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/client/S3ClientWrapperTest.java
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/client/S3ClientWrapperTest.java
@@ -48,6 +48,7 @@
import org.junit.jupiter.params.provider.ValueSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.test.context.ConfigFileApplicationContextInitializer;
import org.springframework.boot.test.mock.mockito.MockBean;
@@ -98,7 +99,8 @@ class S3ClientWrapperTest {
public static class RetryS3ClientConfig {
@Bean
- public ObjectStoreClient createS3ClientWrapper(S3Client s3Client) {
+ @ConditionalOnMissingBean
+ public ObjectStoreClient createObjectStoreClient(S3Client s3Client) {
return new S3ClientWrapper(s3Client);
}
}
@@ -215,7 +217,7 @@ void testPutObjectForNoHeaders() {
@Test
void testPutObjectForContentTypeHeader() {
String contentType = "foo-content-type";
- s3ClientWrapper.putObject(VALID_BUCKET_NAME, VALID_NAME, Path.of(""),
+ s3ClientWrapper.putObject(VALID_BUCKET_NAME, VALID_NAME, Path.of(""),
newHashMap(HeaderKey.CONTENT_TYPE, contentType));
PutObjectRequest expRequest =
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/ObjectStoreAccessIT.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/integration/ObjectStoreAccessIT.java
similarity index 96%
rename from services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/ObjectStoreAccessIT.java
rename to services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/integration/ObjectStoreAccessIT.java
--- a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/ObjectStoreAccessIT.java
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/integration/ObjectStoreAccessIT.java
@@ -18,13 +18,14 @@
* ---license-end
*/
-package app.coronawarn.server.services.distribution.objectstore;
+package app.coronawarn.server.services.distribution.objectstore.integration;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
+import app.coronawarn.server.services.distribution.objectstore.ObjectStoreAccess;
import app.coronawarn.server.services.distribution.objectstore.client.ObjectStorePublishingConfig;
import app.coronawarn.server.services.distribution.objectstore.client.S3Object;
import app.coronawarn.server.services.distribution.objectstore.publish.LocalFile;
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/integration/ObjectStoreFilePreservationIT.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/integration/ObjectStoreFilePreservationIT.java
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/integration/ObjectStoreFilePreservationIT.java
@@ -0,0 +1,214 @@
+/*-
+ * ---license-start
+ * Corona-Warn-App
+ * ---
+ * Copyright (C) 2020 SAP SE and all other contributors
+ * ---
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://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 for the specific language governing permissions and
+ * limitations under the License.
+ * ---license-end
+ */
+
+package app.coronawarn.server.services.distribution.objectstore.integration;
+
+import java.io.File;
+import java.io.IOException;
+import java.time.LocalDate;
+import java.time.Month;
+import java.time.temporal.ChronoUnit;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+import org.junit.Rule;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.rules.TemporaryFolder;
+import org.mockito.Mockito;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.ConfigFileApplicationContextInitializer;
+import org.springframework.boot.test.mock.mockito.MockBean;
+import org.springframework.context.ApplicationContext;
+import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
+import org.springframework.test.annotation.DirtiesContext;
+import org.springframework.test.context.ActiveProfiles;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit.jupiter.SpringExtension;
+
+import app.coronawarn.server.common.persistence.service.DiagnosisKeyService;
+import app.coronawarn.server.services.distribution.Application;
+import app.coronawarn.server.services.distribution.assembly.component.OutputDirectoryProvider;
+import app.coronawarn.server.services.distribution.assembly.structure.directory.DirectoryOnDisk;
+import app.coronawarn.server.services.distribution.common.DiagnosisTestData;
+import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
+import app.coronawarn.server.services.distribution.objectstore.FailedObjectStoreOperationsCounter;
+import app.coronawarn.server.services.distribution.objectstore.ObjectStoreAccess;
+import app.coronawarn.server.services.distribution.objectstore.S3Publisher;
+import app.coronawarn.server.services.distribution.objectstore.S3RetentionPolicy;
+import app.coronawarn.server.services.distribution.objectstore.client.S3Object;
+import app.coronawarn.server.services.distribution.runner.Assembly;
+import app.coronawarn.server.services.distribution.runner.RetentionPolicy;
+
+@ExtendWith(SpringExtension.class)
+@ContextConfiguration(classes = Application.class, initializers = ConfigFileApplicationContextInitializer.class)
+@DirtiesContext
+@ActiveProfiles("integration-test")
+@Tag("s3-integration")
+class ObjectStoreFilePreservationIT {
+
+ @Autowired
+ private DiagnosisKeyService diagnosisKeyService;
+ @Autowired
+ private Assembly fileAssembler;
+ @Autowired
+ private ApplicationContext applicationContext;
+ @Autowired
+ private S3RetentionPolicy s3RetentionPolicy;
+ @Autowired
+ private ObjectStoreAccess objectStoreAccess;
+ @Autowired
+ private DistributionServiceConfig distributionServiceConfig;
+
+ @MockBean
+ private OutputDirectoryProvider distributionDirectoryProvider;
+
+ @Rule
+ private TemporaryFolder testOutputFolder = new TemporaryFolder();
+
+
+ @BeforeEach
+ public void setup() throws IOException {
+ testOutputFolder.create();
+ objectStoreAccess.deleteObjectsWithPrefix(distributionServiceConfig.getApi().getVersionPath());
+ }
+
+ /**
+ * The test covers a behaviour that manifests itself when data retention and shifting policies cause the file
+ * distribution logic to generate, in subsequent runs, different content for the same timeframes. Below the
+ * distribution problem is described with a concerete daily scenario.
+ * <p>
+ * The test presumes there are 4 consecutive days with 80 keys submitted daily. Running a distribution in Day 4 would
+ * result in:
+ * <p>
+ * Day 1 -> submission of 80 keys -> 1 empty file distributed<br>
+ * Day 2 -> submission of 80 keys -> 1 distributed containing 160 keys<br>
+ * Day 3 -> submission of 80 keys -> 1 empty file distributed<br>
+ * Day 4 -> submission of 80 keys -> 1 distributed containing 160 keys<br>
+ * <p>
+ * All day & hour files already generated should not be changed/removed from S3 even after retention policies have
+ * been applied and a second distribution is triggered.
+ * <p>
+ * If for example, data in Day 1 gets removed completely, then a second distribution run causes a shifting of keys in
+ * different files compared to the previous run, the result being:
+ * <p>
+ * Day 2 -> submission of 80 keys -> 1 empty file generated (different than what is currently on S3)<br>
+ * Day 3 -> submission of 80 keys -> 1 distributed containing 160 keys (different than 1 empty file on S3)<br>
+ * Day 4 -> submission of 80 keys -> 1 empty file (different than 1 empty file on S3)<br>
+ */
+ @Test
+ void files_once_published_to_objectstore_should_not_be_overriden_because_of_retention_or_shifting_policies()
+ throws IOException {
+
+ // keep data in the past for this test
+ LocalDate testStartDate = LocalDate.now().minusDays(10);
+ LocalDate testEndDate = LocalDate.now().minusDays(6);
+
+ // setup the 80 keys per day scenario
+ createDiagnosisKeyTestData(testStartDate, testEndDate, 80);
+
+ assembleAndDistribute(testOutputFolder.newFolder("output-before-retention"));
+ List<S3Object> filesBeforeRetention = getPublishedFiles();
+
+ triggerRetentionPolicy(testStartDate);
+
+ // Trigger second distrubution after data retention policies were applied
+ assembleAndDistribute(testOutputFolder.newFolder("output-after-retention"));
+ List<S3Object> filesAfterRetention = getPublishedFiles();
+
+ assertPreviouslyPublishedKeyFilesAreTheSame(filesBeforeRetention, filesAfterRetention);
+ }
+
+ private List<S3Object> getPublishedFiles() {
+ return objectStoreAccess.getObjectsWithPrefix(distributionServiceConfig.getApi().getVersionPath());
+ }
+
+ private void assertPreviouslyPublishedKeyFilesAreTheSame(List<S3Object> filesBeforeRetention,
+ List<S3Object> filesAfterRetention) {
+
+ Map<String, S3Object> beforeRetentionFileMap = filesBeforeRetention
+ .stream()
+ .filter(S3Object::isDiagnosisKeyFile)
+ .collect(Collectors.toMap(S3Object::getObjectName, s3object -> s3object));
+
+ filesAfterRetention
+ .stream()
+ .filter(S3Object::isDiagnosisKeyFile)
+ .forEach(secondVersion -> {
+ S3Object previouslyPublished = beforeRetentionFileMap.get(secondVersion.getObjectName());
+
+ if (filesAreDifferent(previouslyPublished, secondVersion)) {
+ throw new AssertionError("Files have been changed on object store "
+ + "due to retention policy. Before: " + previouslyPublished.getObjectName()
+ + "-" + previouslyPublished.getCwaHash()
+ + "| After:" + secondVersion.getObjectName()
+ + "-" + secondVersion.getCwaHash());
+ }
+ });
+ }
+
+ private boolean filesAreDifferent(S3Object previouslyPublished, S3Object newVerion) {
+ return previouslyPublished == null ||
+ !newVerion.getCwaHash().equals(previouslyPublished.getCwaHash());
+ }
+
+ /**
+ * Remove test data inserted for the given date
+ */
+ private void triggerRetentionPolicy(LocalDate fromDate) {
+ DistributionServiceConfig mockDistributionConfig = new DistributionServiceConfig();
+ mockDistributionConfig.setRetentionDays(numberOfDaysSince(fromDate));
+ new RetentionPolicy(diagnosisKeyService, applicationContext, mockDistributionConfig,
+ s3RetentionPolicy).run(null);
+ }
+
+ private Integer numberOfDaysSince(LocalDate testStartDate) {
+ return (int) ChronoUnit.DAYS.between(testStartDate, LocalDate.now()) - 1;
+ }
+
+ private void createDiagnosisKeyTestData(LocalDate fromDay, LocalDate untilDay, int casesPerDay) {
+ DiagnosisTestData testData = DiagnosisTestData.of(fromDay, untilDay, casesPerDay);
+ diagnosisKeyService.saveDiagnosisKeys(testData.getDiagnosisKeys());
+ }
+
+ private void assembleAndDistribute(File output) throws IOException {
+ Mockito.when(distributionDirectoryProvider.getDirectory()).thenReturn(new DirectoryOnDisk(output));
+ Mockito.when(distributionDirectoryProvider.getFileOnDisk()).thenReturn(output);
+
+ fileAssembler.run(null);
+
+ S3Publisher s3Publisher = new S3Publisher(objectStoreAccess,
+ new FailedObjectStoreOperationsCounter(distributionServiceConfig),
+ newAsyncExecutor(), distributionServiceConfig);
+ s3Publisher.publish(distributionDirectoryProvider.getFileOnDisk().toPath().toAbsolutePath());
+ }
+
+ private ThreadPoolTaskExecutor newAsyncExecutor() {
+ ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
+ executor.setCorePoolSize(8);
+ executor.setMaxPoolSize(8);
+ executor.setQueueCapacity(11);
+ executor.initialize();
+ return executor;
+ }
+}
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/S3PublisherIT.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/integration/S3PublisherIT.java
similarity index 89%
rename from services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/S3PublisherIT.java
rename to services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/integration/S3PublisherIT.java
--- a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/S3PublisherIT.java
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/integration/S3PublisherIT.java
@@ -18,11 +18,14 @@
* ---license-end
*/
-package app.coronawarn.server.services.distribution.objectstore;
+package app.coronawarn.server.services.distribution.objectstore.integration;
import static org.assertj.core.api.Assertions.assertThat;
import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
+import app.coronawarn.server.services.distribution.objectstore.FailedObjectStoreOperationsCounter;
+import app.coronawarn.server.services.distribution.objectstore.ObjectStoreAccess;
+import app.coronawarn.server.services.distribution.objectstore.S3Publisher;
import app.coronawarn.server.services.distribution.objectstore.client.ObjectStorePublishingConfig;
import app.coronawarn.server.services.distribution.objectstore.client.S3Object;
import java.io.IOException;
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/publish/LocalFileTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/publish/LocalFileTest.java
--- a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/publish/LocalFileTest.java
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/publish/LocalFileTest.java
@@ -20,6 +20,8 @@
package app.coronawarn.server.services.distribution.objectstore.publish;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.nio.file.Path;
@@ -48,4 +50,26 @@ void testGetContentTypeZip(String path) {
LocalFile test = new LocalIndexFile(Path.of("/root", path, "/index"), Path.of("/root"));
assertEquals("application/zip", test.getContentType());
}
+
+ @ParameterizedTest
+ @ValueSource(strings = {
+ "version/v1/diagnosis-keys/country/DE/date/2020-06-11",
+ "version/v1/diagnosis-keys/country/DE/date/2020-06-11/hour/13" })
+ void testIsKeyFile(String path) {
+ LocalFile test = new LocalIndexFile(Path.of("/root", path, "/index"), Path.of("/root"));
+ assertTrue(test.isKeyFile());
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {
+ "version",
+ "version/v1/configuration/country",
+ "version/v1/configuration/country/DE/app_config",
+ "version/v1/diagnosis-keys/country",
+ "version/v1/diagnosis-keys/country/DE/date",
+ "version/v1/diagnosis-keys/country/DE/date/2020-06-11/hour" })
+ void testIsNotKeyFile(String path) {
+ LocalFile test = new LocalIndexFile(Path.of("/root", path, "/index"), Path.of("/root"));
+ assertFalse(test.isKeyFile());
+ }
}
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/publish/PublishedFileSetTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/publish/PublishedFileSetTest.java
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/publish/PublishedFileSetTest.java
@@ -0,0 +1,72 @@
+/*-
+ * ---license-start
+ * Corona-Warn-App
+ * ---
+ * Copyright (C) 2020 SAP SE and all other contributors
+ * ---
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://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 for the specific language governing permissions and
+ * limitations under the License.
+ * ---license-end
+ */
+
+package app.coronawarn.server.services.distribution.objectstore.publish;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import java.nio.file.Path;
+import java.util.Collections;
+import java.util.List;
+
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import app.coronawarn.server.services.distribution.objectstore.client.S3Object;
+
+class PublishedFileSetTest {
+
+ @ParameterizedTest
+ @ValueSource(strings = {
+ "version/v1/diagnosis-keys/country/DE/date/2020-01-01",
+ "version/v1/diagnosis-keys/country/DE/date/2020-06-11/hour/0",
+ "version/v1/diagnosis-keys/country/DE/date/2020-06-11/hour/23"})
+ void testShouldNotPublishWithoutForceUpdateConfiguration(String key) {
+ List<S3Object> s3Objects = List.of(new S3Object(key, "1234"));
+ PublishedFileSet publishedSet = new PublishedFileSet(s3Objects, false);
+ LocalFile testFile = new LocalIndexFile(Path.of("/root", key, "/index"), Path.of("/root"));
+ assertFalse(publishedSet.shouldPublish(testFile));
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {
+ "version/v1/diagnosis-keys/country/DE/date/2020-01-01",
+ "version/v1/diagnosis-keys/country/DE/date/2020-06-11/hour/0",
+ "version/v1/diagnosis-keys/country/DE/date/2020-06-11/hour/23"})
+ void testShouldPublishWithForceUpdateConfiguration(String key) {
+ List<S3Object> s3Objects = List.of(new S3Object(key, "1234"));
+ PublishedFileSet publishedSet = new PublishedFileSet(s3Objects, true);
+ LocalFile testFile = new LocalIndexFile(Path.of("/root", key, "/index"), Path.of("/root"));
+ assertTrue(publishedSet.shouldPublish(testFile));
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {
+ "version/v1/diagnosis-keys/country/DE/date/2020-01-01",
+ "version/v1/diagnosis-keys/country/DE/date/2020-06-11/hour/0",
+ "version/v1/diagnosis-keys/country/DE/date/2020-06-11/hour/23"})
+ void testShouldPublishWhenObjectStoreEmpty(String key) {
+ PublishedFileSet publishedSet = new PublishedFileSet(Collections.emptyList(), false);
+ LocalFile testFile = new LocalIndexFile(Path.of("/root", key, "/index"), Path.of("/root"));
+ assertTrue(publishedSet.shouldPublish(testFile));
+ }
+
+}
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/publish/S3ObjectTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/publish/S3ObjectTest.java
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/publish/S3ObjectTest.java
@@ -0,0 +1,52 @@
+/*-
+ * ---license-start
+ * Corona-Warn-App
+ * ---
+ * Copyright (C) 2020 SAP SE and all other contributors
+ * ---
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://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 for the specific language governing permissions and
+ * limitations under the License.
+ * ---license-end
+ */
+
+package app.coronawarn.server.services.distribution.objectstore.publish;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import app.coronawarn.server.services.distribution.objectstore.client.S3Object;
+
+class S3ObjectTest {
+
+ @ParameterizedTest
+ @ValueSource(strings = {
+ "version/v1/diagnosis-keys/country/DE/date/2020-06-11",
+ "version/v1/diagnosis-keys/country/DE/date/2020-06-11/hour/13" })
+ void testIsKeyFile(String key) {
+ S3Object test = new S3Object(key);
+ assertTrue(test.isDiagnosisKeyFile());
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {
+ "version/v1/configuration/country/DE/app_config",
+ "version/v1/configuration/country",
+ "version/v1/diagnosis-keys/country/DE/date",
+ "version/v1/diagnosis-keys/country/DE/date/2020-06-11/hour" })
+ void testIsNotKeyFile(String key) {
+ S3Object test = new S3Object(key);
+ assertFalse(test.isDiagnosisKeyFile());
+ }
+}
diff --git a/services/distribution/src/test/resources/application-integration-test.yaml b/services/distribution/src/test/resources/application-integration-test.yaml
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/test/resources/application-integration-test.yaml
@@ -0,0 +1,4 @@
+---
+services:
+ distribution:
+ shifting-policy-threshold: 140
diff --git a/services/distribution/src/test/resources/application.yaml b/services/distribution/src/test/resources/application.yaml
--- a/services/distribution/src/test/resources/application.yaml
+++ b/services/distribution/src/test/resources/application.yaml
@@ -51,6 +51,7 @@ services:
retry-backoff: 1
max-number-of-failed-operations: 5
max-number-of-s3-threads: 2
+ force-update-keyfiles: ${FORCE_UPDATE_KEYFILES:false}
spring:
main:
banner-mode: off
| ||||
corona-warn-app__cwa-server-429 | You will be provided with a partial code base and an issue statement explaining a problem to resolve.
<issue>
Use Implicit Constructor Injection over Explicit
The `@Autowired` annotation for Spring components can be omitted for constructors in case there is only one constructor present on the class. Therefore, remove all the unnecessary annotation for those cases.
</issue>
<code>
[start of README.md]
1 <!-- markdownlint-disable MD041 -->
2 <h1 align="center">
3 Corona-Warn-App Server
4 </h1>
5
6 <p align="center">
7 <a href="https://github.com/corona-warn-app/cwa-server/commits/" title="Last Commit"><img src="https://img.shields.io/github/last-commit/corona-warn-app/cwa-server?style=flat"></a>
8 <a href="https://github.com/corona-warn-app/cwa-server/issues" title="Open Issues"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat"></a>
9 <a href="https://circleci.com/gh/corona-warn-app/cwa-server" title="Build Status"><img src="https://circleci.com/gh/corona-warn-app/cwa-server.svg?style=shield&circle-token=4ab059989d10709df19eb4b98ab7c121a25e981a"></a>
10 <a href="https://sonarcloud.io/dashboard?id=corona-warn-app_cwa-server" title="Quality Gate"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=alert_status"></a>
11 <a href="https://sonarcloud.io/component_measures?id=corona-warn-app_cwa-server&metric=Coverage&view=list" title="Coverage"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=coverage"></a>
12 <a href="https://github.com/corona-warn-app/cwa-server/blob/master/LICENSE" title="License"><img src="https://img.shields.io/badge/License-Apache%202.0-green.svg?style=flat"></a>
13 </p>
14
15 <p align="center">
16 <a href="#development">Development</a> •
17 <a href="#service-apis">Service APIs</a> •
18 <a href="#documentation">Documentation</a> •
19 <a href="#support-and-feedback">Support</a> •
20 <a href="#how-to-contribute">Contribute</a> •
21 <a href="#contributors">Contributors</a> •
22 <a href="#repositories">Repositories</a> •
23 <a href="#licensing">Licensing</a>
24 </p>
25
26 The goal of this project is to develop the official Corona-Warn-App for Germany based on the exposure notification API from [Apple](https://www.apple.com/covid19/contacttracing/) and [Google](https://www.google.com/covid19/exposurenotifications/). The apps (for both iOS and Android) use Bluetooth technology to exchange anonymous encrypted data with other mobile phones (on which the app is also installed) in the vicinity of an app user's phone. The data is stored locally on each user's device, preventing authorities or other parties from accessing or controlling the data. This repository contains the **implementation of the server for encryption keys** for the Corona-Warn-App. This implementation is still a **work in progress**, and the code it contains is currently alpha-quality code.
27
28 In this documentation, Corona-Warn-App services are also referred to as CWA services.
29
30 ## Architecture Overview
31
32 You can find the architecture overview [here](/docs/architecture-overview.md), which will give you
33 a good starting point in how the backend services interact with other services, and what purpose
34 they serve.
35
36 ## Development
37
38 After you've checked out this repository, you can run the application in one of the following ways:
39
40 * As a [Docker](https://www.docker.com/)-based deployment on your local machine. You can run either:
41 * Single components using the respective Dockerfile or
42 * The full backend using the Docker Compose (which is considered the most convenient way)
43 * As a [Maven](https://maven.apache.org)-based build on your local machine.
44 If you want to develop something in a single component, this approach is preferable.
45
46 ### Docker-Based Deployment
47
48 If you want to use Docker-based deployment, you need to install Docker on your local machine. For more information about downloading and installing Docker, see the [official Docker documentation](https://docs.docker.com/get-docker/).
49
50 #### Running the Full CWA Backend Using Docker Compose
51
52 For your convenience, a full setup including the generation of test data has been prepared using [Docker Compose](https://docs.docker.com/compose/reference/overview/). To build the backend services, run ```docker-compose build``` in the repository's root directory. A default configuration file can be found under ```.env```in the root folder of the repository. The default values for the local Postgres and Zenko Cloudserver should be changed in this file before docker-compose is run.
53
54 Once the services are built, you can start the whole backend using ```docker-compose up```.
55 The distribution service runs once and then finishes. If you want to trigger additional distribution runs, run ```docker-compose run distribution```.
56
57 The docker-compose contains the following services:
58
59 Service | Description | Endpoint and Default Credentials
60 ------------------|-------------|-----------
61 submission | The Corona-Warn-App submission service | `http://localhost:8000` <br> `http://localhost:8006` (for actuator endpoint)
62 distribution | The Corona-Warn-App distribution service | NO ENDPOINT
63 postgres | A [postgres] database installation | `postgres:8001` <br> Username: postgres <br> Password: postgres
64 pgadmin | A [pgadmin](https://www.pgadmin.org/) installation for the postgres database | `http://localhost:8002` <br> Username: [email protected] <br> Password: password
65 cloudserver | [Zenko CloudServer] is a S3-compliant object store | `http://localhost:8003/` <br> Access key: accessKey1 <br> Secret key: verySecretKey1
66 verification-fake | A very simple fake implementation for the tan verification. | `http://localhost:8004/version/v1/tan/verify` <br> The only valid tan is "edc07f08-a1aa-11ea-bb37-0242ac130002"
67
68 ##### Known Limitation
69
70 In rare cases the docker-compose runs into a timing issue if the distribution service starts before the bucket of the objectstore was created. This is not a big issue as you can simply run ```docker-compose run distribution``` to trigger additional distribution runs after the objectstore was initialized.
71
72 #### Running Single CWA Services Using Docker
73
74 If you would like to build and run a single CWA service, it's considered easiest to run them in a Docker environment. You can do this using the script provided in the respective CWA service directory. The Docker script first builds the CWA service and then creates an image for the runtime, which means that there are no additional dependencies for you to install.
75
76 To build and run the distribution service, run the following command:
77
78 ```bash
79 ./services/distribution/build_and_run.sh
80 ```
81
82 To build and run the submission service, run the following command:
83
84 ```bash
85 ./services/submission/build_and_run.sh
86 ```
87
88 The submission service is available on [localhost:8080](http://localhost:8080 ).
89
90 ### Maven-Based Build
91
92 If you want to actively develop in one of the CWA services, the Maven-based runtime is most suitable.
93 To prepare your machine to run the CWA project locally, we recommend that you first ensure that you've installed the following:
94
95 * Minimum JDK Version 11: [OpenJDK](https://openjdk.java.net/) / [SapMachine](https://sap.github.io/SapMachine/)
96 * [Maven 3.6](https://maven.apache.org/)
97 * [Postgres]
98 * [Zenko CloudServer]
99
100 #### Configure
101
102 After you made sure that the specified dependencies are running, configure them in the respective configuration files.
103
104 * Configure the Postgres connection in the [submission config](./services/submission/src/main/resources/application.yaml) and in the [distribution config](./services/distribution/src/main/resources/application.yaml)
105 * Configure the S3 compatible object storage in the [distribution config](./services/distribution/src/main/resources/application.yaml)
106 * Configure the private key for the distribution service, the path need to be prefixed with `file:`
107 * `VAULT_FILESIGNING_SECRET` should be the path to the private key, example available in `<repo-root>/docker-compose-test-secrets/private.pem`
108
109 #### Build
110
111 After you've checked out the repository, to build the project, run ```mvn install``` in your base directory.
112
113 #### Run
114
115 Navigate to the service you want to start and run the spring-boot:run target. The configured Postgres and the configured S3 compliant object storage are used as default. When you start the submission service, the endpoint is available on your local port 8080.
116
117 If you want to start the submission service, for example, you start it as follows:
118
119 ```bash
120 cd services/submission/
121 mvn spring-boot:run
122 ```
123
124 #### Debugging
125
126 To enable the `DEBUG` log level, you can run the application using the Spring `dev` profile.
127
128 ```bash
129 mvn spring-boot:run -Dspring-boot.run.profiles=dev
130 ```
131
132 To be able to set breakpoints (e.g. in IntelliJ), it may be necessary to use the ```-Dspring-boot.run.fork=false``` parameter.
133
134 ## Service APIs
135
136 The API that is being exposed by the backend services is documented in an [OpenAPI](https://www.openapis.org/) specification. The specification files are available at the following locations:
137
138 Service | OpenAPI Specification
139 -------------|-------------
140 Submission Service | [services/submission/api_v1.json](https://github.com/corona-warn-app/cwa-server/raw/master/services/submission/api_v1.json)
141 Distribution Service | [services/distribution/api_v1.json](https://github.com/corona-warn-app/cwa-server/raw/master/services/distribution/api_v1.json)
142
143 ## Spring Profiles
144
145 ### Distribution
146
147 Profile | Effect
148 -----------------|-------------
149 `dev` | Turns the log level to `DEBUG`.
150 `cloud` | Removes default values for the `datasource` and `objectstore` configurations.
151 `demo` | Includes incomplete days and hours into the distribution run, thus creating aggregates for the current day and the current hour (and including both in the respective indices). When running multiple distributions in one hour with this profile, the date aggregate for today and the hours aggregate for the current hour will be updated and overwritten. This profile also turns off the expiry policy (Keys must be expired for at least 2 hours before distribution) and the shifting policy (there must be at least 140 keys in a distribution).
152 `testdata` | Causes test data to be inserted into the database before each distribution run. By default, around 1000 random diagnosis keys will be generated per hour. If there are no diagnosis keys in the database yet, random keys will be generated for every hour from the beginning of the retention period (14 days ago at 00:00 UTC) until one hour before the present hour. If there are already keys in the database, the random keys will be generated for every hour from the latest diagnosis key in the database (by submission timestamp) until one hour before the present hour (or none at all, if the latest diagnosis key in the database was submitted one hour ago or later).
153 `signature-dev` | Sets the app package ID in the export packages' signature info to `de.rki.coronawarnapp-dev` so that test certificates (instead of production certificates) will be used for client-side validation.
154 `signature-prod` | Provides production app package IDs for the signature info
155
156 ### Submission
157
158 Profile | Effect
159 -------------|-------------
160 `dev` | Turns the log level to `DEBUG`.
161 `cloud` | Removes default values for the `datasource` configuration.
162
163 ## Documentation
164
165 The full documentation for the Corona-Warn-App can be found in the [cwa-documentation](https://github.com/corona-warn-app/cwa-documentation) repository. The documentation repository contains technical documents, architecture information, and whitepapers related to this implementation.
166
167 ## Support and Feedback
168
169 The following channels are available for discussions, feedback, and support requests:
170
171 | Type | Channel |
172 | ------------------------ | ------------------------------------------------------ |
173 | **General Discussion** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="General Discussion"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/question.svg?style=flat-square"></a> </a> |
174 | **Concept Feedback** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="Open Concept Feedback"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/architecture.svg?style=flat-square"></a> |
175 | **Backend Issue** | <a href="https://github.com/corona-warn-app/cwa-server/issues/new/choose" title="Open Backend Issue"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat-square"></a> |
176 | **Other Requests** | <a href="mailto:[email protected]" title="Email CWA Team"><img src="https://img.shields.io/badge/email-CWA%20team-green?logo=mail.ru&style=flat-square&logoColor=white"></a> |
177
178 ## How to Contribute
179
180 Contribution and feedback are 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.
181
182 ## Contributors
183
184 The German government has asked SAP and Deutsche Telekom to develop the Corona-Warn-App for Germany as open source software. Deutsche Telekom is providing the network and mobile technology and will operate and run the backend for the app in a safe, scalable and stable manner. SAP is responsible for the app development, its framework and the underlying platform. Therefore, development teams of SAP and Deutsche Telekom are contributing to this project. At the same time 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.
185
186 ## Repositories
187
188 The following public repositories are currently available for the Corona-Warn-App:
189
190 | Repository | Description |
191 | ------------------- | --------------------------------------------------------------------- |
192 | [cwa-documentation] | Project overview, general documentation, and white papers |
193 | [cwa-server] | Backend implementation for the Apple/Google exposure notification API|
194 | [cwa-verification-server] | Backend implementation of the verification process|
195
196 [cwa-documentation]: https://github.com/corona-warn-app/cwa-documentation
197 [cwa-server]: https://github.com/corona-warn-app/cwa-server
198 [cwa-verification-server]: https://github.com/corona-warn-app/cwa-verification-server
199 [Postgres]: https://www.postgresql.org/
200 [HSQLDB]: http://hsqldb.org/
201 [Zenko CloudServer]: https://github.com/scality/cloudserver
202
203 ## Licensing
204
205 Copyright (c) 2020 SAP SE or an SAP affiliate company.
206
207 Licensed under the **Apache License, Version 2.0** (the "License"); you may not use this file except in compliance with the License.
208
209 You may obtain a copy of the License at <https://www.apache.org/licenses/LICENSE-2.0>.
210
211 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.
212
[end of README.md]
[start of common/persistence/src/main/java/app/coronawarn/server/common/persistence/service/DiagnosisKeyService.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.common.persistence.service;
22
23 import static java.time.ZoneOffset.UTC;
24
25 import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
26 import app.coronawarn.server.common.persistence.repository.DiagnosisKeyRepository;
27 import java.time.Instant;
28 import java.time.LocalDateTime;
29 import java.util.Collection;
30 import java.util.List;
31 import java.util.stream.Collectors;
32 import javax.validation.ConstraintViolation;
33 import org.slf4j.Logger;
34 import org.slf4j.LoggerFactory;
35 import org.springframework.beans.factory.annotation.Autowired;
36 import org.springframework.data.domain.Sort;
37 import org.springframework.data.domain.Sort.Direction;
38 import org.springframework.stereotype.Component;
39 import org.springframework.transaction.annotation.Transactional;
40
41 @Component
42 public class DiagnosisKeyService {
43
44 private static final Logger logger = LoggerFactory.getLogger(DiagnosisKeyService.class);
45 private final DiagnosisKeyRepository keyRepository;
46
47 @Autowired
48 public DiagnosisKeyService(DiagnosisKeyRepository keyRepository) {
49 this.keyRepository = keyRepository;
50 }
51
52 /**
53 * Persists the specified collection of {@link DiagnosisKey} instances. If the key data of a particular diagnosis key
54 * already exists in the database, this diagnosis key is not persisted.
55 *
56 * @param diagnosisKeys must not contain {@literal null}.
57 * @throws IllegalArgumentException in case the given collection contains {@literal null}.
58 */
59 @Transactional
60 public void saveDiagnosisKeys(Collection<DiagnosisKey> diagnosisKeys) {
61 for (DiagnosisKey diagnosisKey : diagnosisKeys) {
62 keyRepository.saveDoNothingOnConflict(
63 diagnosisKey.getKeyData(), diagnosisKey.getRollingStartIntervalNumber(), diagnosisKey.getRollingPeriod(),
64 diagnosisKey.getSubmissionTimestamp(), diagnosisKey.getTransmissionRiskLevel());
65 }
66 }
67
68 /**
69 * Returns all valid persisted diagnosis keys, sorted by their submission timestamp.
70 */
71 public List<DiagnosisKey> getDiagnosisKeys() {
72 List<DiagnosisKey> diagnosisKeys = keyRepository.findAll(Sort.by(Direction.ASC, "submissionTimestamp"));
73 List<DiagnosisKey> validDiagnosisKeys =
74 diagnosisKeys.stream().filter(DiagnosisKeyService::isDiagnosisKeyValid).collect(Collectors.toList());
75
76 int numberOfDiscardedKeys = diagnosisKeys.size() - validDiagnosisKeys.size();
77 logger.info("Retrieved {} diagnosis key(s). Discarded {} diagnosis key(s) from the result as invalid.",
78 diagnosisKeys.size(), numberOfDiscardedKeys);
79
80 return validDiagnosisKeys;
81 }
82
83 private static boolean isDiagnosisKeyValid(DiagnosisKey diagnosisKey) {
84 Collection<ConstraintViolation<DiagnosisKey>> violations = diagnosisKey.validate();
85 boolean isValid = violations.isEmpty();
86
87 if (!isValid) {
88 List<String> violationMessages =
89 violations.stream().map(ConstraintViolation::getMessage).collect(Collectors.toList());
90 logger.warn("Validation failed for diagnosis key from database. Violations: {}", violationMessages);
91 }
92
93 return isValid;
94 }
95
96 /**
97 * Deletes all diagnosis key entries which have a submission timestamp that is older than the specified number of
98 * days.
99 *
100 * @param daysToRetain the number of days until which diagnosis keys will be retained.
101 * @throws IllegalArgumentException if {@code daysToRetain} is negative.
102 */
103 @Transactional
104 public void applyRetentionPolicy(int daysToRetain) {
105 if (daysToRetain < 0) {
106 throw new IllegalArgumentException("Number of days to retain must be greater or equal to 0.");
107 }
108
109 long threshold = LocalDateTime
110 .ofInstant(Instant.now(), UTC)
111 .minusDays(daysToRetain)
112 .toEpochSecond(UTC) / 3600L;
113 int numberOfDeletions = keyRepository.deleteBySubmissionTimestampIsLessThanEqual(threshold);
114 logger.info("Deleted {} diagnosis key(s) with a submission timestamp older than {} day(s) ago.",
115 numberOfDeletions, daysToRetain);
116 }
117 }
118
[end of common/persistence/src/main/java/app/coronawarn/server/common/persistence/service/DiagnosisKeyService.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/component/DiagnosisKeysStructureProvider.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.distribution.assembly.component;
22
23 import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
24 import app.coronawarn.server.common.persistence.service.DiagnosisKeyService;
25 import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.DiagnosisKeyBundler;
26 import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.directory.DiagnosisKeysDirectory;
27 import app.coronawarn.server.services.distribution.assembly.structure.WritableOnDisk;
28 import app.coronawarn.server.services.distribution.assembly.structure.directory.Directory;
29 import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
30 import java.util.Collection;
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
33 import org.springframework.beans.factory.annotation.Autowired;
34 import org.springframework.stereotype.Component;
35
36 /**
37 * Retrieves stored diagnosis keys and builds a {@link DiagnosisKeysDirectory} with them.
38 */
39 @Component
40 public class DiagnosisKeysStructureProvider {
41
42 private static final Logger logger = LoggerFactory
43 .getLogger(DiagnosisKeysStructureProvider.class);
44
45 @Autowired
46 private DiagnosisKeyBundler diagnosisKeyBundler;
47 private final DiagnosisKeyService diagnosisKeyService;
48 private final CryptoProvider cryptoProvider;
49 private final DistributionServiceConfig distributionServiceConfig;
50
51 /**
52 * Creates a new DiagnosisKeysStructureProvider.
53 */
54 DiagnosisKeysStructureProvider(DiagnosisKeyService diagnosisKeyService, CryptoProvider cryptoProvider,
55 DistributionServiceConfig distributionServiceConfig) {
56 this.diagnosisKeyService = diagnosisKeyService;
57 this.cryptoProvider = cryptoProvider;
58 this.distributionServiceConfig = distributionServiceConfig;
59 }
60
61 /**
62 * Get directory for diagnosis keys from database.
63 *
64 * @return the directory
65 */
66 public Directory<WritableOnDisk> getDiagnosisKeys() {
67 logger.debug("Querying diagnosis keys from the database...");
68 Collection<DiagnosisKey> diagnosisKeys = diagnosisKeyService.getDiagnosisKeys();
69 diagnosisKeyBundler.setDiagnosisKeys(diagnosisKeys);
70 return new DiagnosisKeysDirectory(diagnosisKeyBundler, cryptoProvider, distributionServiceConfig);
71 }
72 }
73
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/component/DiagnosisKeysStructureProvider.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/S3RetentionPolicy.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.distribution.objectstore;
22
23 import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
24 import app.coronawarn.server.services.distribution.config.DistributionServiceConfig.Api;
25 import app.coronawarn.server.services.distribution.objectstore.client.S3Object;
26 import java.time.LocalDate;
27 import java.time.ZoneOffset;
28 import java.time.format.DateTimeFormatter;
29 import java.util.List;
30 import java.util.regex.Matcher;
31 import java.util.regex.Pattern;
32 import org.springframework.beans.factory.annotation.Autowired;
33 import org.springframework.stereotype.Component;
34
35 /**
36 * Creates an S3RetentionPolicy object, which applies the retention policy to the S3 compatible storage.
37 */
38 @Component
39 public class S3RetentionPolicy {
40
41 private final ObjectStoreAccess objectStoreAccess;
42 private final Api api;
43
44 @Autowired
45 public S3RetentionPolicy(ObjectStoreAccess objectStoreAccess, DistributionServiceConfig distributionServiceConfig) {
46 this.objectStoreAccess = objectStoreAccess;
47 this.api = distributionServiceConfig.getApi();
48 }
49
50 /**
51 * Deletes all diagnosis-key files from S3 that are older than retentionDays.
52 *
53 * @param retentionDays the number of days, that files should be retained on S3.
54 */
55 public void applyRetentionPolicy(int retentionDays) {
56 List<S3Object> diagnosisKeysObjects = objectStoreAccess.getObjectsWithPrefix("version/v1/"
57 + api.getDiagnosisKeysPath() + "/"
58 + api.getCountryPath() + "/"
59 + api.getCountryGermany() + "/"
60 + api.getDatePath() + "/");
61 final String regex = ".*([0-9]{4}-[0-9]{2}-[0-9]{2}).*";
62 final Pattern pattern = Pattern.compile(regex);
63
64 final LocalDate cutOffDate = LocalDate.now(ZoneOffset.UTC).minusDays(retentionDays);
65
66 diagnosisKeysObjects.stream()
67 .filter(diagnosisKeysObject -> {
68 Matcher matcher = pattern.matcher(diagnosisKeysObject.getObjectName());
69 return matcher.matches() && LocalDate.parse(matcher.group(1), DateTimeFormatter.ISO_LOCAL_DATE)
70 .isBefore(cutOffDate);
71 })
72 .forEach(this::deleteDiagnosisKey);
73 }
74
75 /**
76 * Java stream do not support checked exceptions within streams. This helper method rethrows them as unchecked
77 * expressions, so they can be passed up to the Retention Policy.
78 *
79 * @param diagnosisKey the diagnosis key, that should be deleted.
80 */
81 public void deleteDiagnosisKey(S3Object diagnosisKey) {
82 objectStoreAccess.deleteObjectsWithPrefix(diagnosisKey.getObjectName());
83 }
84 }
85
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/S3RetentionPolicy.java]
[start of services/submission/src/main/java/app/coronawarn/server/services/submission/controller/SubmissionController.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.submission.controller;
22
23 import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
24 import app.coronawarn.server.common.persistence.service.DiagnosisKeyService;
25 import app.coronawarn.server.common.protocols.external.exposurenotification.TemporaryExposureKey;
26 import app.coronawarn.server.common.protocols.internal.SubmissionPayload;
27 import app.coronawarn.server.services.submission.config.SubmissionServiceConfig;
28 import app.coronawarn.server.services.submission.validation.ValidSubmissionPayload;
29 import app.coronawarn.server.services.submission.verification.TanVerifier;
30 import java.util.ArrayList;
31 import java.util.List;
32 import java.util.concurrent.Executors;
33 import java.util.concurrent.ForkJoinPool;
34 import java.util.concurrent.ScheduledExecutorService;
35 import java.util.concurrent.TimeUnit;
36 import org.apache.commons.math3.distribution.PoissonDistribution;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39 import org.springframework.beans.factory.annotation.Autowired;
40 import org.springframework.http.HttpStatus;
41 import org.springframework.http.ResponseEntity;
42 import org.springframework.util.StopWatch;
43 import org.springframework.validation.annotation.Validated;
44 import org.springframework.web.bind.annotation.PostMapping;
45 import org.springframework.web.bind.annotation.RequestBody;
46 import org.springframework.web.bind.annotation.RequestHeader;
47 import org.springframework.web.bind.annotation.RequestMapping;
48 import org.springframework.web.bind.annotation.RestController;
49 import org.springframework.web.context.request.async.DeferredResult;
50
51 @RestController
52 @RequestMapping("/version/v1")
53 @Validated
54 public class SubmissionController {
55
56 private static final Logger logger = LoggerFactory.getLogger(SubmissionController.class);
57 /**
58 * The route to the submission endpoint (version agnostic).
59 */
60 public static final String SUBMISSION_ROUTE = "/diagnosis-keys";
61
62 private final ScheduledExecutorService scheduledExecutor = Executors.newSingleThreadScheduledExecutor();
63 private final ForkJoinPool forkJoinPool = ForkJoinPool.commonPool();
64 private final DiagnosisKeyService diagnosisKeyService;
65 private final TanVerifier tanVerifier;
66 private final Double fakeDelayMovingAverageSamples;
67 private final Integer retentionDays;
68 private Double fakeDelay;
69
70 @Autowired
71 SubmissionController(DiagnosisKeyService diagnosisKeyService, TanVerifier tanVerifier,
72 SubmissionServiceConfig submissionServiceConfig) {
73 this.diagnosisKeyService = diagnosisKeyService;
74 this.tanVerifier = tanVerifier;
75 fakeDelay = submissionServiceConfig.getInitialFakeDelayMilliseconds();
76 fakeDelayMovingAverageSamples = submissionServiceConfig.getFakeDelayMovingAverageSamples();
77 retentionDays = submissionServiceConfig.getRetentionDays();
78 }
79
80 /**
81 * Handles diagnosis key submission requests.
82 *
83 * @param exposureKeys The unmarshalled protocol buffers submission payload.
84 * @param fake A header flag, marking fake requests.
85 * @param tan A tan for diagnosis verification.
86 * @return An empty response body.
87 */
88 @PostMapping(SUBMISSION_ROUTE)
89 public DeferredResult<ResponseEntity<Void>> submitDiagnosisKey(
90 @ValidSubmissionPayload @RequestBody SubmissionPayload exposureKeys,
91 @RequestHeader("cwa-fake") Integer fake,
92 @RequestHeader("cwa-authorization") String tan) {
93 if (fake != 0) {
94 return buildFakeDeferredResult();
95 } else {
96 return buildRealDeferredResult(exposureKeys, tan);
97 }
98 }
99
100 private DeferredResult<ResponseEntity<Void>> buildFakeDeferredResult() {
101 DeferredResult<ResponseEntity<Void>> deferredResult = new DeferredResult<>();
102 long delay = new PoissonDistribution(fakeDelay).sample();
103 scheduledExecutor.schedule(() -> deferredResult.setResult(buildSuccessResponseEntity()),
104 delay, TimeUnit.MILLISECONDS);
105 return deferredResult;
106 }
107
108 private DeferredResult<ResponseEntity<Void>> buildRealDeferredResult(SubmissionPayload exposureKeys, String tan) {
109 DeferredResult<ResponseEntity<Void>> deferredResult = new DeferredResult<>();
110
111 forkJoinPool.submit(() -> {
112 StopWatch stopWatch = new StopWatch();
113 stopWatch.start();
114 if (!this.tanVerifier.verifyTan(tan)) {
115 deferredResult.setResult(buildTanInvalidResponseEntity());
116 } else {
117 try {
118 persistDiagnosisKeysPayload(exposureKeys);
119 deferredResult.setResult(buildSuccessResponseEntity());
120 stopWatch.stop();
121 updateFakeDelay(stopWatch.getTotalTimeMillis());
122 } catch (Exception e) {
123 deferredResult.setErrorResult(e);
124 }
125 }
126 });
127
128 return deferredResult;
129 }
130
131 /**
132 * Returns a response that indicates successful request processing.
133 */
134 private ResponseEntity<Void> buildSuccessResponseEntity() {
135 return ResponseEntity.ok().build();
136 }
137
138 /**
139 * Returns a response that indicates that an invalid TAN was specified in the request.
140 */
141 private ResponseEntity<Void> buildTanInvalidResponseEntity() {
142 return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
143 }
144
145 /**
146 * Persists the diagnosis keys contained in the specified request payload.
147 *
148 * @param protoBufDiagnosisKeys Diagnosis keys that were specified in the request.
149 * @throws IllegalArgumentException in case the given collection contains {@literal null}.
150 */
151 public void persistDiagnosisKeysPayload(SubmissionPayload protoBufDiagnosisKeys) {
152 List<TemporaryExposureKey> protoBufferKeysList = protoBufDiagnosisKeys.getKeysList();
153 List<DiagnosisKey> diagnosisKeys = new ArrayList<>();
154
155 for (TemporaryExposureKey protoBufferKey : protoBufferKeysList) {
156 DiagnosisKey diagnosisKey = DiagnosisKey.builder().fromProtoBuf(protoBufferKey).build();
157 if (diagnosisKey.isYoungerThanRetentionThreshold(retentionDays)) {
158 diagnosisKeys.add(diagnosisKey);
159 } else {
160 logger.info("Not persisting a diagnosis key, as it is outdated beyond retention threshold.");
161 }
162 }
163
164 diagnosisKeyService.saveDiagnosisKeys(diagnosisKeys);
165 }
166
167 private synchronized void updateFakeDelay(long realRequestDuration) {
168 fakeDelay = fakeDelay + (1 / fakeDelayMovingAverageSamples) * (realRequestDuration - fakeDelay);
169 }
170 }
171
[end of services/submission/src/main/java/app/coronawarn/server/services/submission/controller/SubmissionController.java]
[start of services/submission/src/main/java/app/coronawarn/server/services/submission/verification/TanVerifier.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.submission.verification;
22
23 import feign.FeignException;
24 import org.slf4j.Logger;
25 import org.slf4j.LoggerFactory;
26 import org.springframework.beans.factory.annotation.Autowired;
27 import org.springframework.stereotype.Service;
28 import org.springframework.web.client.RestClientException;
29
30 /**
31 * The TanVerifier performs the verification of submission TANs.
32 */
33 @Service
34 public class TanVerifier {
35
36 private static final Logger logger = LoggerFactory.getLogger(TanVerifier.class);
37 private final VerificationServerClient verificationServerClient;
38
39 /**
40 * This class can be used to verify a TAN against a configured verification service.
41 *
42 * @param verificationServerClient The REST client to communicate with the verification server
43 */
44 @Autowired
45 public TanVerifier(VerificationServerClient verificationServerClient) {
46 this.verificationServerClient = verificationServerClient;
47 }
48
49 /**
50 * Verifies the specified TAN. Returns {@literal true} if the specified TAN is valid, {@literal false} otherwise.
51 *
52 * @param tanString Submission Authorization TAN
53 * @return {@literal true} if the specified TAN is valid, {@literal false} otherwise.
54 * @throws RestClientException if status code is neither 2xx nor 4xx
55 */
56 public boolean verifyTan(String tanString) {
57 try {
58 Tan tan = Tan.of(tanString);
59
60 return verifyWithVerificationService(tan);
61 } catch (IllegalArgumentException e) {
62 logger.debug("TAN Syntax check failed for TAN: {}", tanString.trim());
63 return false;
64 }
65 }
66
67 /**
68 * Queries the configured verification service to validate the provided TAN.
69 *
70 * @param tan Submission Authorization TAN
71 * @return {@literal true} if verification service is able to verify the provided TAN, {@literal false} otherwise
72 * @throws RestClientException if http status code is neither 2xx nor 404
73 */
74 private boolean verifyWithVerificationService(Tan tan) {
75 try {
76 verificationServerClient.verifyTan(tan);
77 return true;
78 } catch (FeignException.NotFound e) {
79 return false;
80 }
81 }
82 }
83
[end of services/submission/src/main/java/app/coronawarn/server/services/submission/verification/TanVerifier.java]
</code>
Here is an example of a patch file. It consists of changes to the code base. It specifies the file names, the line numbers of each change, and the removed and added lines. A single patch file can contain changes to multiple files.
<patch>
--- a/file.py
+++ b/file.py
@@ -1,27 +1,35 @@
def euclidean(a, b):
- while b:
- a, b = b, a % b
- return a
+ if b == 0:
+ return a
+ return euclidean(b, a % b)
def bresenham(x0, y0, x1, y1):
points = []
dx = abs(x1 - x0)
dy = abs(y1 - y0)
- sx = 1 if x0 < x1 else -1
- sy = 1 if y0 < y1 else -1
- err = dx - dy
+ x, y = x0, y0
+ sx = -1 if x0 > x1 else 1
+ sy = -1 if y0 > y1 else 1
- while True:
- points.append((x0, y0))
- if x0 == x1 and y0 == y1:
- break
- e2 = 2 * err
- if e2 > -dy:
+ if dx > dy:
+ err = dx / 2.0
+ while x != x1:
+ points.append((x, y))
err -= dy
- x0 += sx
- if e2 < dx:
- err += dx
- y0 += sy
+ if err < 0:
+ y += sy
+ err += dx
+ x += sx
+ else:
+ err = dy / 2.0
+ while y != y1:
+ points.append((x, y))
+ err -= dx
+ if err < 0:
+ x += sx
+ err += dy
+ y += sy
+ points.append((x, y))
return points
</patch>
I need you to solve the provded issue by generating a single patch file that I can apply directly to this repository using git apply. Please respond with a single patch file in the format shown above.
Respond below:
| corona-warn-app/cwa-server | 528b73595c202a8216bd321dafd431206a6fd2c0 | Use Implicit Constructor Injection over Explicit
The `@Autowired` annotation for Spring components can be omitted for constructors in case there is only one constructor present on the class. Therefore, remove all the unnecessary annotation for those cases.
| I guess it should be doable for me to get started | 2020-06-02T21:54:44 | <patch>
diff --git a/common/persistence/src/main/java/app/coronawarn/server/common/persistence/service/DiagnosisKeyService.java b/common/persistence/src/main/java/app/coronawarn/server/common/persistence/service/DiagnosisKeyService.java
--- a/common/persistence/src/main/java/app/coronawarn/server/common/persistence/service/DiagnosisKeyService.java
+++ b/common/persistence/src/main/java/app/coronawarn/server/common/persistence/service/DiagnosisKeyService.java
@@ -32,7 +32,6 @@
import javax.validation.ConstraintViolation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Component;
@@ -44,7 +43,6 @@ public class DiagnosisKeyService {
private static final Logger logger = LoggerFactory.getLogger(DiagnosisKeyService.class);
private final DiagnosisKeyRepository keyRepository;
- @Autowired
public DiagnosisKeyService(DiagnosisKeyRepository keyRepository) {
this.keyRepository = keyRepository;
}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/component/DiagnosisKeysStructureProvider.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/component/DiagnosisKeysStructureProvider.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/component/DiagnosisKeysStructureProvider.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/component/DiagnosisKeysStructureProvider.java
@@ -30,7 +30,6 @@
import java.util.Collection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
@@ -42,8 +41,7 @@ public class DiagnosisKeysStructureProvider {
private static final Logger logger = LoggerFactory
.getLogger(DiagnosisKeysStructureProvider.class);
- @Autowired
- private DiagnosisKeyBundler diagnosisKeyBundler;
+ private final DiagnosisKeyBundler diagnosisKeyBundler;
private final DiagnosisKeyService diagnosisKeyService;
private final CryptoProvider cryptoProvider;
private final DistributionServiceConfig distributionServiceConfig;
@@ -52,10 +50,11 @@ public class DiagnosisKeysStructureProvider {
* Creates a new DiagnosisKeysStructureProvider.
*/
DiagnosisKeysStructureProvider(DiagnosisKeyService diagnosisKeyService, CryptoProvider cryptoProvider,
- DistributionServiceConfig distributionServiceConfig) {
+ DistributionServiceConfig distributionServiceConfig, DiagnosisKeyBundler diagnosisKeyBundler) {
this.diagnosisKeyService = diagnosisKeyService;
this.cryptoProvider = cryptoProvider;
this.distributionServiceConfig = distributionServiceConfig;
+ this.diagnosisKeyBundler = diagnosisKeyBundler;
}
/**
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/S3RetentionPolicy.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/S3RetentionPolicy.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/S3RetentionPolicy.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/S3RetentionPolicy.java
@@ -29,7 +29,6 @@
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
-import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
@@ -41,7 +40,6 @@ public class S3RetentionPolicy {
private final ObjectStoreAccess objectStoreAccess;
private final Api api;
- @Autowired
public S3RetentionPolicy(ObjectStoreAccess objectStoreAccess, DistributionServiceConfig distributionServiceConfig) {
this.objectStoreAccess = objectStoreAccess;
this.api = distributionServiceConfig.getApi();
diff --git a/services/submission/src/main/java/app/coronawarn/server/services/submission/controller/SubmissionController.java b/services/submission/src/main/java/app/coronawarn/server/services/submission/controller/SubmissionController.java
--- a/services/submission/src/main/java/app/coronawarn/server/services/submission/controller/SubmissionController.java
+++ b/services/submission/src/main/java/app/coronawarn/server/services/submission/controller/SubmissionController.java
@@ -36,7 +36,6 @@
import org.apache.commons.math3.distribution.PoissonDistribution;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StopWatch;
@@ -67,7 +66,6 @@ public class SubmissionController {
private final Integer retentionDays;
private Double fakeDelay;
- @Autowired
SubmissionController(DiagnosisKeyService diagnosisKeyService, TanVerifier tanVerifier,
SubmissionServiceConfig submissionServiceConfig) {
this.diagnosisKeyService = diagnosisKeyService;
diff --git a/services/submission/src/main/java/app/coronawarn/server/services/submission/verification/TanVerifier.java b/services/submission/src/main/java/app/coronawarn/server/services/submission/verification/TanVerifier.java
--- a/services/submission/src/main/java/app/coronawarn/server/services/submission/verification/TanVerifier.java
+++ b/services/submission/src/main/java/app/coronawarn/server/services/submission/verification/TanVerifier.java
@@ -23,7 +23,6 @@
import feign.FeignException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
@@ -41,7 +40,6 @@ public class TanVerifier {
*
* @param verificationServerClient The REST client to communicate with the verification server
*/
- @Autowired
public TanVerifier(VerificationServerClient verificationServerClient) {
this.verificationServerClient = verificationServerClient;
}
</patch> | diff --git a/services/submission/src/test/java/app/coronawarn/server/services/submission/controller/RequestExecutor.java b/services/submission/src/test/java/app/coronawarn/server/services/submission/controller/RequestExecutor.java
--- a/services/submission/src/test/java/app/coronawarn/server/services/submission/controller/RequestExecutor.java
+++ b/services/submission/src/test/java/app/coronawarn/server/services/submission/controller/RequestExecutor.java
@@ -29,7 +29,6 @@
import java.time.Instant;
import java.time.LocalDate;
import java.util.Collection;
-import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
@@ -50,7 +49,6 @@ public class RequestExecutor {
private static final URI SUBMISSION_URL = URI.create("/version/v1/diagnosis-keys");
private final TestRestTemplate testRestTemplate;
- @Autowired
public RequestExecutor(TestRestTemplate testRestTemplate) {
this.testRestTemplate = testRestTemplate;
}
| ||||
corona-warn-app__cwa-server-419 | You will be provided with a partial code base and an issue statement explaining a problem to resolve.
<issue>
S3Publisher: Resilience
The S3Publisher/ObjectStoreAccess is currently lacking resilience features, like re-trys and error handling.
</issue>
<code>
[start of README.md]
1 <!-- markdownlint-disable MD041 -->
2 <h1 align="center">
3 Corona-Warn-App Server
4 </h1>
5
6 <p align="center">
7 <a href="https://github.com/corona-warn-app/cwa-server/commits/" title="Last Commit"><img src="https://img.shields.io/github/last-commit/corona-warn-app/cwa-server?style=flat"></a>
8 <a href="https://github.com/corona-warn-app/cwa-server/issues" title="Open Issues"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat"></a>
9 <a href="https://circleci.com/gh/corona-warn-app/cwa-server" title="Build Status"><img src="https://circleci.com/gh/corona-warn-app/cwa-server.svg?style=shield&circle-token=4ab059989d10709df19eb4b98ab7c121a25e981a"></a>
10 <a href="https://sonarcloud.io/dashboard?id=corona-warn-app_cwa-server" title="Quality Gate"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=alert_status"></a>
11 <a href="https://sonarcloud.io/component_measures?id=corona-warn-app_cwa-server&metric=Coverage&view=list" title="Coverage"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=coverage"></a>
12 <a href="https://github.com/corona-warn-app/cwa-server/blob/master/LICENSE" title="License"><img src="https://img.shields.io/badge/License-Apache%202.0-green.svg?style=flat"></a>
13 </p>
14
15 <p align="center">
16 <a href="#development">Development</a> •
17 <a href="#service-apis">Service APIs</a> •
18 <a href="#documentation">Documentation</a> •
19 <a href="#support-and-feedback">Support</a> •
20 <a href="#how-to-contribute">Contribute</a> •
21 <a href="#contributors">Contributors</a> •
22 <a href="#repositories">Repositories</a> •
23 <a href="#licensing">Licensing</a>
24 </p>
25
26 The goal of this project is to develop the official Corona-Warn-App for Germany based on the exposure notification API from [Apple](https://www.apple.com/covid19/contacttracing/) and [Google](https://www.google.com/covid19/exposurenotifications/). The apps (for both iOS and Android) use Bluetooth technology to exchange anonymous encrypted data with other mobile phones (on which the app is also installed) in the vicinity of an app user's phone. The data is stored locally on each user's device, preventing authorities or other parties from accessing or controlling the data. This repository contains the **implementation of the server for encryption keys** for the Corona-Warn-App. This implementation is still a **work in progress**, and the code it contains is currently alpha-quality code.
27
28 In this documentation, Corona-Warn-App services are also referred to as CWA services.
29
30 ## Architecture Overview
31
32 You can find the architecture overview [here](/docs/architecture-overview.md), which will give you
33 a good starting point in how the backend services interact with other services, and what purpose
34 they serve.
35
36 ## Development
37
38 After you've checked out this repository, you can run the application in one of the following ways:
39
40 * As a [Docker](https://www.docker.com/)-based deployment on your local machine. You can run either:
41 * Single components using the respective Dockerfile or
42 * The full backend using the Docker Compose (which is considered the most convenient way)
43 * As a [Maven](https://maven.apache.org)-based build on your local machine.
44 If you want to develop something in a single component, this approach is preferable.
45
46 ### Docker-Based Deployment
47
48 If you want to use Docker-based deployment, you need to install Docker on your local machine. For more information about downloading and installing Docker, see the [official Docker documentation](https://docs.docker.com/get-docker/).
49
50 #### Running the Full CWA Backend Using Docker Compose
51
52 For your convenience, a full setup including the generation of test data has been prepared using [Docker Compose](https://docs.docker.com/compose/reference/overview/). To build the backend services, run ```docker-compose build``` in the repository's root directory. A default configuration file can be found under ```.env```in the root folder of the repository. The default values for the local Postgres and Zenko Cloudserver should be changed in this file before docker-compose is run.
53
54 Once the services are built, you can start the whole backend using ```docker-compose up```.
55 The distribution service runs once and then finishes. If you want to trigger additional distribution runs, run ```docker-compose run distribution```.
56
57 The docker-compose contains the following services:
58
59 Service | Description | Endpoint and Default Credentials
60 ------------------|-------------|-----------
61 submission | The Corona-Warn-App submission service | `http://localhost:8000` <br> `http://localhost:8006` (for actuator endpoint)
62 distribution | The Corona-Warn-App distribution service | NO ENDPOINT
63 postgres | A [postgres] database installation | `postgres:8001` <br> Username: postgres <br> Password: postgres
64 pgadmin | A [pgadmin](https://www.pgadmin.org/) installation for the postgres database | `http://localhost:8002` <br> Username: [email protected] <br> Password: password
65 cloudserver | [Zenko CloudServer] is a S3-compliant object store | `http://localhost:8003/` <br> Access key: accessKey1 <br> Secret key: verySecretKey1
66 verification-fake | A very simple fake implementation for the tan verification. | `http://localhost:8004/version/v1/tan/verify` <br> The only valid tan is "edc07f08-a1aa-11ea-bb37-0242ac130002"
67
68 ##### Known Limitation
69
70 In rare cases the docker-compose runs into a timing issue if the distribution service starts before the bucket of the objectstore was created. This is not a big issue as you can simply run ```docker-compose run distribution``` to trigger additional distribution runs after the objectstore was initialized.
71
72 #### Running Single CWA Services Using Docker
73
74 If you would like to build and run a single CWA service, it's considered easiest to run them in a Docker environment. You can do this using the script provided in the respective CWA service directory. The Docker script first builds the CWA service and then creates an image for the runtime, which means that there are no additional dependencies for you to install.
75
76 To build and run the distribution service, run the following command:
77
78 ```bash
79 ./services/distribution/build_and_run.sh
80 ```
81
82 To build and run the submission service, run the following command:
83
84 ```bash
85 ./services/submission/build_and_run.sh
86 ```
87
88 The submission service is available on [localhost:8080](http://localhost:8080 ).
89
90 ### Maven-Based Build
91
92 If you want to actively develop in one of the CWA services, the Maven-based runtime is most suitable.
93 To prepare your machine to run the CWA project locally, we recommend that you first ensure that you've installed the following:
94
95 * Minimum JDK Version 11: [OpenJDK](https://openjdk.java.net/) / [SapMachine](https://sap.github.io/SapMachine/)
96 * [Maven 3.6](https://maven.apache.org/)
97 * [Postgres]
98 * [Zenko CloudServer]
99
100 #### Configure
101
102 After you made sure that the specified dependencies are running, configure them in the respective configuration files.
103
104 * Configure the Postgres connection in the [submission config](./services/submission/src/main/resources/application.yaml) and in the [distribution config](./services/distribution/src/main/resources/application.yaml)
105 * Configure the S3 compatible object storage in the [distribution config](./services/distribution/src/main/resources/application.yaml)
106 * Configure the private key for the distribution service, the path need to be prefixed with `file:`
107 * `VAULT_FILESIGNING_SECRET` should be the path to the private key, example available in `<repo-root>/docker-compose-test-secrets/private.pem`
108
109 #### Build
110
111 After you've checked out the repository, to build the project, run ```mvn install``` in your base directory.
112
113 #### Run
114
115 Navigate to the service you want to start and run the spring-boot:run target. The configured Postgres and the configured S3 compliant object storage are used as default. When you start the submission service, the endpoint is available on your local port 8080.
116
117 If you want to start the submission service, for example, you start it as follows:
118
119 ```bash
120 cd services/submission/
121 mvn spring-boot:run
122 ```
123
124 #### Debugging
125
126 To enable the `DEBUG` log level, you can run the application using the Spring `dev` profile.
127
128 ```bash
129 mvn spring-boot:run -Dspring-boot.run.profiles=dev
130 ```
131
132 To be able to set breakpoints (e.g. in IntelliJ), it may be necessary to use the ```-Dspring-boot.run.fork=false``` parameter.
133
134 ## Service APIs
135
136 The API that is being exposed by the backend services is documented in an [OpenAPI](https://www.openapis.org/) specification. The specification files are available at the following locations:
137
138 Service | OpenAPI Specification
139 -------------|-------------
140 Submission Service | [services/submission/api_v1.json](https://github.com/corona-warn-app/cwa-server/raw/master/services/submission/api_v1.json)
141 Distribution Service | [services/distribution/api_v1.json](https://github.com/corona-warn-app/cwa-server/raw/master/services/distribution/api_v1.json)
142
143 ## Spring Profiles
144
145 ### Distribution
146
147 Profile | Effect
148 -----------------|-------------
149 `dev` | Turns the log level to `DEBUG`.
150 `cloud` | Removes default values for the `datasource` and `objectstore` configurations.
151 `demo` | Includes incomplete days and hours into the distribution run, thus creating aggregates for the current day and the current hour (and including both in the respective indices). When running multiple distributions in one hour with this profile, the date aggregate for today and the hours aggregate for the current hour will be updated and overwritten. This profile also turns off the expiry policy (Keys must be expired for at least 2 hours before distribution) and the shifting policy (there must be at least 140 keys in a distribution).
152 `testdata` | Causes test data to be inserted into the database before each distribution run. By default, around 1000 random diagnosis keys will be generated per hour. If there are no diagnosis keys in the database yet, random keys will be generated for every hour from the beginning of the retention period (14 days ago at 00:00 UTC) until one hour before the present hour. If there are already keys in the database, the random keys will be generated for every hour from the latest diagnosis key in the database (by submission timestamp) until one hour before the present hour (or none at all, if the latest diagnosis key in the database was submitted one hour ago or later).
153 `signature-dev` | Sets the app package ID in the export packages' signature info to `de.rki.coronawarnapp-dev` so that test certificates (instead of production certificates) will be used for client-side validation.
154 `signature-prod` | Provides production app package IDs for the signature info
155
156 ### Submission
157
158 Profile | Effect
159 -------------|-------------
160 `dev` | Turns the log level to `DEBUG`.
161 `cloud` | Removes default values for the `datasource` configuration.
162
163 ## Documentation
164
165 The full documentation for the Corona-Warn-App can be found in the [cwa-documentation](https://github.com/corona-warn-app/cwa-documentation) repository. The documentation repository contains technical documents, architecture information, and whitepapers related to this implementation.
166
167 ## Support and Feedback
168
169 The following channels are available for discussions, feedback, and support requests:
170
171 | Type | Channel |
172 | ------------------------ | ------------------------------------------------------ |
173 | **General Discussion** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="General Discussion"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/question.svg?style=flat-square"></a> </a> |
174 | **Concept Feedback** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="Open Concept Feedback"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/architecture.svg?style=flat-square"></a> |
175 | **Backend Issue** | <a href="https://github.com/corona-warn-app/cwa-server/issues/new/choose" title="Open Backend Issue"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat-square"></a> |
176 | **Other Requests** | <a href="mailto:[email protected]" title="Email CWA Team"><img src="https://img.shields.io/badge/email-CWA%20team-green?logo=mail.ru&style=flat-square&logoColor=white"></a> |
177
178 ## How to Contribute
179
180 Contribution and feedback are 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.
181
182 ## Contributors
183
184 The German government has asked SAP and Deutsche Telekom to develop the Corona-Warn-App for Germany as open source software. Deutsche Telekom is providing the network and mobile technology and will operate and run the backend for the app in a safe, scalable and stable manner. SAP is responsible for the app development, its framework and the underlying platform. Therefore, development teams of SAP and Deutsche Telekom are contributing to this project. At the same time 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.
185
186 ## Repositories
187
188 The following public repositories are currently available for the Corona-Warn-App:
189
190 | Repository | Description |
191 | ------------------- | --------------------------------------------------------------------- |
192 | [cwa-documentation] | Project overview, general documentation, and white papers |
193 | [cwa-server] | Backend implementation for the Apple/Google exposure notification API|
194 | [cwa-verification-server] | Backend implementation of the verification process|
195
196 [cwa-documentation]: https://github.com/corona-warn-app/cwa-documentation
197 [cwa-server]: https://github.com/corona-warn-app/cwa-server
198 [cwa-verification-server]: https://github.com/corona-warn-app/cwa-verification-server
199 [Postgres]: https://www.postgresql.org/
200 [HSQLDB]: http://hsqldb.org/
201 [Zenko CloudServer]: https://github.com/scality/cloudserver
202
203 ## Licensing
204
205 Copyright (c) 2020 SAP SE or an SAP affiliate company.
206
207 Licensed under the **Apache License, Version 2.0** (the "License"); you may not use this file except in compliance with the License.
208
209 You may obtain a copy of the License at <https://www.apache.org/licenses/LICENSE-2.0>.
210
211 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.
212
[end of README.md]
[start of /dev/null]
1
[end of /dev/null]
[start of services/distribution/pom.xml]
1 <?xml version="1.0" encoding="UTF-8"?>
2 <project xmlns="http://maven.apache.org/POM/4.0.0"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
5 <parent>
6 <artifactId>services</artifactId>
7 <groupId>org.opencwa</groupId>
8 <version>${revision}</version>
9 <relativePath>../pom.xml</relativePath>
10 </parent>
11 <modelVersion>4.0.0</modelVersion>
12
13 <properties>
14 <sonar.projectKey>corona-warn-app_cwa-server_services_distribution</sonar.projectKey>
15 </properties>
16
17 <build>
18 <pluginManagement>
19 <plugins>
20 <plugin>
21 <groupId>org.apache.maven.plugins</groupId>
22 <artifactId>maven-surefire-plugin</artifactId>
23 <version>3.0.0-M3</version>
24 <configuration>
25 <excludedGroups>s3-integration</excludedGroups>
26 <trimStackTrace>false</trimStackTrace>
27 </configuration>
28 </plugin>
29 </plugins>
30 </pluginManagement>
31 <plugins>
32 <plugin>
33 <groupId>org.jacoco</groupId>
34 <artifactId>jacoco-maven-plugin</artifactId>
35 <version>0.8.5</version>
36 <executions>
37 <execution>
38 <goals>
39 <goal>prepare-agent</goal>
40 </goals>
41 </execution>
42 <execution>
43 <id>report</id>
44 <goals>
45 <goal>report</goal>
46 </goals>
47 <phase>verify</phase>
48 </execution>
49 </executions>
50 </plugin>
51 </plugins>
52 </build>
53
54 <artifactId>distribution</artifactId>
55 <dependencies>
56 <dependency>
57 <groupId>software.amazon.awssdk</groupId>
58 <artifactId>s3</artifactId>
59 <version>2.13.25</version>
60 </dependency>
61 <dependency>
62 <artifactId>bcpkix-jdk15on</artifactId>
63 <groupId>org.bouncycastle</groupId>
64 <version>1.65</version>
65 </dependency>
66 <dependency>
67 <artifactId>json-simple</artifactId>
68 <groupId>com.googlecode.json-simple</groupId>
69 <version>1.1.1</version>
70 </dependency>
71 <dependency>
72 <groupId>commons-io</groupId>
73 <artifactId>commons-io</artifactId>
74 <version>2.5</version>
75 </dependency>
76 <dependency>
77 <artifactId>commons-math3</artifactId>
78 <groupId>org.apache.commons</groupId>
79 <version>3.2</version>
80 </dependency>
81 </dependencies>
82
83 </project>
[end of services/distribution/pom.xml]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/config/DistributionServiceConfig.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.distribution.config;
22
23 import app.coronawarn.server.common.protocols.external.exposurenotification.SignatureInfo;
24 import org.springframework.boot.context.properties.ConfigurationProperties;
25 import org.springframework.stereotype.Component;
26
27 @Component
28 @ConfigurationProperties(prefix = "services.distribution")
29 public class DistributionServiceConfig {
30
31 private Paths paths;
32 private TestData testData;
33 private Integer retentionDays;
34 private Integer expiryPolicyMinutes;
35 private Integer shiftingPolicyThreshold;
36 private String outputFileName;
37 private Boolean includeIncompleteDays;
38 private Boolean includeIncompleteHours;
39 private TekExport tekExport;
40 private Signature signature;
41 private Api api;
42 private ObjectStore objectStore;
43
44 public Paths getPaths() {
45 return paths;
46 }
47
48 public void setPaths(Paths paths) {
49 this.paths = paths;
50 }
51
52 public TestData getTestData() {
53 return testData;
54 }
55
56 public void setTestData(TestData testData) {
57 this.testData = testData;
58 }
59
60 public Integer getRetentionDays() {
61 return retentionDays;
62 }
63
64 public void setRetentionDays(Integer retentionDays) {
65 this.retentionDays = retentionDays;
66 }
67
68 public Integer getExpiryPolicyMinutes() {
69 return expiryPolicyMinutes;
70 }
71
72 public void setExpiryPolicyMinutes(Integer expiryPolicyMinutes) {
73 this.expiryPolicyMinutes = expiryPolicyMinutes;
74 }
75
76 public Integer getShiftingPolicyThreshold() {
77 return shiftingPolicyThreshold;
78 }
79
80 public void setShiftingPolicyThreshold(Integer shiftingPolicyThreshold) {
81 this.shiftingPolicyThreshold = shiftingPolicyThreshold;
82 }
83
84 public String getOutputFileName() {
85 return outputFileName;
86 }
87
88 public void setOutputFileName(String outputFileName) {
89 this.outputFileName = outputFileName;
90 }
91
92 public Boolean getIncludeIncompleteDays() {
93 return includeIncompleteDays;
94 }
95
96 public void setIncludeIncompleteDays(Boolean includeIncompleteDays) {
97 this.includeIncompleteDays = includeIncompleteDays;
98 }
99
100 public Boolean getIncludeIncompleteHours() {
101 return includeIncompleteHours;
102 }
103
104 public void setIncludeIncompleteHours(Boolean includeIncompleteHours) {
105 this.includeIncompleteHours = includeIncompleteHours;
106 }
107
108 public TekExport getTekExport() {
109 return tekExport;
110 }
111
112 public void setTekExport(TekExport tekExport) {
113 this.tekExport = tekExport;
114 }
115
116 public Signature getSignature() {
117 return signature;
118 }
119
120 public void setSignature(Signature signature) {
121 this.signature = signature;
122 }
123
124 public Api getApi() {
125 return api;
126 }
127
128 public void setApi(Api api) {
129 this.api = api;
130 }
131
132 public ObjectStore getObjectStore() {
133 return objectStore;
134 }
135
136 public void setObjectStore(
137 ObjectStore objectStore) {
138 this.objectStore = objectStore;
139 }
140
141 public static class TekExport {
142
143 private String fileName;
144 private String fileHeader;
145 private Integer fileHeaderWidth;
146
147 public String getFileName() {
148 return fileName;
149 }
150
151 public void setFileName(String fileName) {
152 this.fileName = fileName;
153 }
154
155 public String getFileHeader() {
156 return fileHeader;
157 }
158
159 public void setFileHeader(String fileHeader) {
160 this.fileHeader = fileHeader;
161 }
162
163 public Integer getFileHeaderWidth() {
164 return fileHeaderWidth;
165 }
166
167 public void setFileHeaderWidth(Integer fileHeaderWidth) {
168 this.fileHeaderWidth = fileHeaderWidth;
169 }
170 }
171
172 public static class TestData {
173
174 private Integer seed;
175 private Integer exposuresPerHour;
176
177 public Integer getSeed() {
178 return seed;
179 }
180
181 public void setSeed(Integer seed) {
182 this.seed = seed;
183 }
184
185 public Integer getExposuresPerHour() {
186 return exposuresPerHour;
187 }
188
189 public void setExposuresPerHour(Integer exposuresPerHour) {
190 this.exposuresPerHour = exposuresPerHour;
191 }
192 }
193
194 public static class Paths {
195
196 private String privateKey;
197 private String output;
198
199 public String getPrivateKey() {
200 return privateKey;
201 }
202
203 public void setPrivateKey(String privateKey) {
204 this.privateKey = privateKey;
205 }
206
207 public String getOutput() {
208 return output;
209 }
210
211 public void setOutput(String output) {
212 this.output = output;
213 }
214 }
215
216 public static class Api {
217
218 private String versionPath;
219 private String versionV1;
220 private String countryPath;
221 private String countryGermany;
222 private String datePath;
223 private String hourPath;
224 private String diagnosisKeysPath;
225 private String parametersPath;
226 private String appConfigFileName;
227
228 public String getVersionPath() {
229 return versionPath;
230 }
231
232 public void setVersionPath(String versionPath) {
233 this.versionPath = versionPath;
234 }
235
236 public String getVersionV1() {
237 return versionV1;
238 }
239
240 public void setVersionV1(String versionV1) {
241 this.versionV1 = versionV1;
242 }
243
244 public String getCountryPath() {
245 return countryPath;
246 }
247
248 public void setCountryPath(String countryPath) {
249 this.countryPath = countryPath;
250 }
251
252 public String getCountryGermany() {
253 return countryGermany;
254 }
255
256 public void setCountryGermany(String countryGermany) {
257 this.countryGermany = countryGermany;
258 }
259
260 public String getDatePath() {
261 return datePath;
262 }
263
264 public void setDatePath(String datePath) {
265 this.datePath = datePath;
266 }
267
268 public String getHourPath() {
269 return hourPath;
270 }
271
272 public void setHourPath(String hourPath) {
273 this.hourPath = hourPath;
274 }
275
276 public String getDiagnosisKeysPath() {
277 return diagnosisKeysPath;
278 }
279
280 public void setDiagnosisKeysPath(String diagnosisKeysPath) {
281 this.diagnosisKeysPath = diagnosisKeysPath;
282 }
283
284 public String getParametersPath() {
285 return parametersPath;
286 }
287
288 public void setParametersPath(String parametersPath) {
289 this.parametersPath = parametersPath;
290 }
291
292 public String getAppConfigFileName() {
293 return appConfigFileName;
294 }
295
296 public void setAppConfigFileName(String appConfigFileName) {
297 this.appConfigFileName = appConfigFileName;
298 }
299 }
300
301 public static class Signature {
302
303 private String appBundleId;
304 private String androidPackage;
305 private String verificationKeyId;
306 private String verificationKeyVersion;
307 private String algorithmOid;
308 private String algorithmName;
309 private String fileName;
310 private String securityProvider;
311
312 public String getAppBundleId() {
313 return appBundleId;
314 }
315
316 public void setAppBundleId(String appBundleId) {
317 this.appBundleId = appBundleId;
318 }
319
320 public String getAndroidPackage() {
321 return androidPackage;
322 }
323
324 public void setAndroidPackage(String androidPackage) {
325 this.androidPackage = androidPackage;
326 }
327
328 public String getVerificationKeyId() {
329 return verificationKeyId;
330 }
331
332 public void setVerificationKeyId(String verificationKeyId) {
333 this.verificationKeyId = verificationKeyId;
334 }
335
336 public String getVerificationKeyVersion() {
337 return verificationKeyVersion;
338 }
339
340 public void setVerificationKeyVersion(String verificationKeyVersion) {
341 this.verificationKeyVersion = verificationKeyVersion;
342 }
343
344 public String getAlgorithmOid() {
345 return algorithmOid;
346 }
347
348 public void setAlgorithmOid(String algorithmOid) {
349 this.algorithmOid = algorithmOid;
350 }
351
352 public String getAlgorithmName() {
353 return algorithmName;
354 }
355
356 public void setAlgorithmName(String algorithmName) {
357 this.algorithmName = algorithmName;
358 }
359
360 public String getFileName() {
361 return fileName;
362 }
363
364 public void setFileName(String fileName) {
365 this.fileName = fileName;
366 }
367
368 public String getSecurityProvider() {
369 return securityProvider;
370 }
371
372 public void setSecurityProvider(String securityProvider) {
373 this.securityProvider = securityProvider;
374 }
375
376 /**
377 * Returns the static {@link SignatureInfo} configured in the application properties.
378 */
379 public SignatureInfo getSignatureInfo() {
380 return SignatureInfo.newBuilder()
381 .setAppBundleId(this.getAppBundleId())
382 .setVerificationKeyVersion(this.getVerificationKeyVersion())
383 .setVerificationKeyId(this.getVerificationKeyId())
384 .setSignatureAlgorithm(this.getAlgorithmOid())
385 .build();
386 }
387 }
388
389 public static class ObjectStore {
390
391 private String accessKey;
392 private String secretKey;
393 private String endpoint;
394 private Integer port;
395 private String bucket;
396 private Boolean setPublicReadAclOnPutObject;
397
398 public String getAccessKey() {
399 return accessKey;
400 }
401
402 public void setAccessKey(String accessKey) {
403 this.accessKey = accessKey;
404 }
405
406 public String getSecretKey() {
407 return secretKey;
408 }
409
410 public void setSecretKey(String secretKey) {
411 this.secretKey = secretKey;
412 }
413
414 public String getEndpoint() {
415 return endpoint;
416 }
417
418 public void setEndpoint(String endpoint) {
419 this.endpoint = endpoint;
420 }
421
422 public Integer getPort() {
423 return port;
424 }
425
426 public void setPort(Integer port) {
427 this.port = port;
428 }
429
430 public String getBucket() {
431 return bucket;
432 }
433
434 public void setBucket(String bucket) {
435 this.bucket = bucket;
436 }
437
438 public Boolean isSetPublicReadAclOnPutObject() {
439 return setPublicReadAclOnPutObject;
440 }
441
442 public void setSetPublicReadAclOnPutObject(Boolean setPublicReadAclOnPutObject) {
443 this.setPublicReadAclOnPutObject = setPublicReadAclOnPutObject;
444 }
445 }
446 }
447
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/config/DistributionServiceConfig.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/S3Publisher.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.distribution.objectstore;
22
23 import app.coronawarn.server.services.distribution.assembly.component.CwaApiStructureProvider;
24 import app.coronawarn.server.services.distribution.objectstore.publish.LocalFile;
25 import app.coronawarn.server.services.distribution.objectstore.publish.PublishFileSet;
26 import app.coronawarn.server.services.distribution.objectstore.publish.PublishedFileSet;
27 import java.io.IOException;
28 import java.nio.file.Path;
29 import java.util.stream.Collectors;
30 import org.slf4j.Logger;
31 import org.slf4j.LoggerFactory;
32
33 /**
34 * Publishes a folder on the disk to S3 while keeping the folder and file structure.<br>
35 * Moreover, does the following:
36 * <br>
37 * <ul>
38 * <li>Publishes index files on a different route, removing the trailing "/index" part.</li>
39 * <li>Adds meta information to the uploaded files, e.g. the sha256 hash value.</li>
40 * <li>Only performs the upload for files, which do not yet exist on the object store, and
41 * checks whether the existing files hash differ from the to-be-uploaded files hash. Only if the
42 * hash differs, the file will ultimately be uploaded</li>
43 * <li>Currently not implemented: Set cache control headers</li>
44 * <li>Currently not implemented: Supports multi threaded upload of files.</li>
45 * </ul>
46 */
47 public class S3Publisher {
48
49 private static final Logger logger = LoggerFactory.getLogger(S3Publisher.class);
50
51 /** The default CWA root folder, which contains all CWA related files. */
52 private static final String CWA_S3_ROOT = CwaApiStructureProvider.VERSION_DIRECTORY;
53
54 /** root folder for the upload on the local disk. */
55 private final Path root;
56
57 /** access to the object store. */
58 private final ObjectStoreAccess access;
59
60 public S3Publisher(Path root, ObjectStoreAccess access) {
61 this.root = root;
62 this.access = access;
63 }
64
65 /**
66 * Synchronizes the files to S3.
67 *
68 * @throws IOException in case there were problems reading files from the disk.
69 */
70 public void publish() throws IOException {
71 var published = new PublishedFileSet(access.getObjectsWithPrefix(CWA_S3_ROOT));
72 var toPublish = new PublishFileSet(root);
73
74 var diff = toPublish
75 .getFiles()
76 .stream()
77 .filter(published::isNotYetPublished)
78 .collect(Collectors.toList());
79
80 logger.info("Beginning upload... ");
81 for (LocalFile file : diff) {
82 this.access.putObject(file);
83 }
84 logger.info("Upload completed.");
85 }
86 }
87
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/S3Publisher.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/S3RetentionPolicy.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.distribution.objectstore;
22
23 import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
24 import app.coronawarn.server.services.distribution.config.DistributionServiceConfig.Api;
25 import app.coronawarn.server.services.distribution.objectstore.client.S3Object;
26 import java.time.LocalDate;
27 import java.time.ZoneOffset;
28 import java.time.format.DateTimeFormatter;
29 import java.util.List;
30 import java.util.regex.Matcher;
31 import java.util.regex.Pattern;
32 import org.springframework.stereotype.Component;
33
34 /**
35 * Creates an S3RetentionPolicy object, which applies the retention policy to the S3 compatible storage.
36 */
37 @Component
38 public class S3RetentionPolicy {
39
40 private final ObjectStoreAccess objectStoreAccess;
41 private final Api api;
42
43 public S3RetentionPolicy(ObjectStoreAccess objectStoreAccess, DistributionServiceConfig distributionServiceConfig) {
44 this.objectStoreAccess = objectStoreAccess;
45 this.api = distributionServiceConfig.getApi();
46 }
47
48 /**
49 * Deletes all diagnosis-key files from S3 that are older than retentionDays.
50 *
51 * @param retentionDays the number of days, that files should be retained on S3.
52 */
53 public void applyRetentionPolicy(int retentionDays) {
54 List<S3Object> diagnosisKeysObjects = objectStoreAccess.getObjectsWithPrefix("version/v1/"
55 + api.getDiagnosisKeysPath() + "/"
56 + api.getCountryPath() + "/"
57 + api.getCountryGermany() + "/"
58 + api.getDatePath() + "/");
59 final String regex = ".*([0-9]{4}-[0-9]{2}-[0-9]{2}).*";
60 final Pattern pattern = Pattern.compile(regex);
61
62 final LocalDate cutOffDate = LocalDate.now(ZoneOffset.UTC).minusDays(retentionDays);
63
64 diagnosisKeysObjects.stream()
65 .filter(diagnosisKeysObject -> {
66 Matcher matcher = pattern.matcher(diagnosisKeysObject.getObjectName());
67 return matcher.matches() && LocalDate.parse(matcher.group(1), DateTimeFormatter.ISO_LOCAL_DATE)
68 .isBefore(cutOffDate);
69 })
70 .forEach(this::deleteDiagnosisKey);
71 }
72
73 /**
74 * Java stream do not support checked exceptions within streams. This helper method rethrows them as unchecked
75 * expressions, so they can be passed up to the Retention Policy.
76 *
77 * @param diagnosisKey the diagnosis key, that should be deleted.
78 */
79 public void deleteDiagnosisKey(S3Object diagnosisKey) {
80 objectStoreAccess.deleteObjectsWithPrefix(diagnosisKey.getObjectName());
81 }
82 }
83
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/S3RetentionPolicy.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/client/ObjectStoreClientConfig.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.distribution.objectstore.client;
22
23 import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
24 import app.coronawarn.server.services.distribution.config.DistributionServiceConfig.ObjectStore;
25 import java.net.URI;
26 import org.springframework.context.annotation.Bean;
27 import org.springframework.context.annotation.Configuration;
28 import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
29 import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
30 import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
31 import software.amazon.awssdk.regions.Region;
32 import software.amazon.awssdk.services.s3.S3Client;
33
34 /**
35 * Manages the instantiation of the {@link ObjectStoreClient} bean.
36 */
37 @Configuration
38 public class ObjectStoreClientConfig {
39
40 private static final Region DEFAULT_REGION = Region.EU_CENTRAL_1;
41
42 @Bean
43 public ObjectStoreClient createObjectStoreClient(DistributionServiceConfig distributionServiceConfig) {
44 return createClient(distributionServiceConfig.getObjectStore());
45 }
46
47 private ObjectStoreClient createClient(ObjectStore objectStore) {
48 AwsCredentialsProvider credentialsProvider = StaticCredentialsProvider.create(
49 AwsBasicCredentials.create(objectStore.getAccessKey(), objectStore.getSecretKey()));
50 String endpoint = removeTrailingSlash(objectStore.getEndpoint()) + ":" + objectStore.getPort();
51
52 return new S3ClientWrapper(S3Client.builder()
53 .region(DEFAULT_REGION)
54 .endpointOverride(URI.create(endpoint))
55 .credentialsProvider(credentialsProvider)
56 .build());
57 }
58
59 private String removeTrailingSlash(String string) {
60 return string.endsWith("/") ? string.substring(0, string.length() - 1) : string;
61 }
62 }
63
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/client/ObjectStoreClientConfig.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/client/S3ClientWrapper.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.distribution.objectstore.client;
22
23 import static java.util.stream.Collectors.toList;
24
25 import java.nio.file.Path;
26 import java.util.Collection;
27 import java.util.List;
28 import java.util.Map;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
31 import software.amazon.awssdk.core.exception.SdkException;
32 import software.amazon.awssdk.core.sync.RequestBody;
33 import software.amazon.awssdk.services.s3.S3Client;
34 import software.amazon.awssdk.services.s3.model.Delete;
35 import software.amazon.awssdk.services.s3.model.DeleteObjectsRequest;
36 import software.amazon.awssdk.services.s3.model.DeleteObjectsResponse;
37 import software.amazon.awssdk.services.s3.model.ListObjectsV2Request;
38 import software.amazon.awssdk.services.s3.model.ListObjectsV2Response;
39 import software.amazon.awssdk.services.s3.model.NoSuchBucketException;
40 import software.amazon.awssdk.services.s3.model.ObjectIdentifier;
41 import software.amazon.awssdk.services.s3.model.PutObjectRequest;
42
43 /**
44 * Implementation of {@link ObjectStoreClient} that encapsulates an {@link S3Client}.
45 */
46 public class S3ClientWrapper implements ObjectStoreClient {
47
48 private static final Logger logger = LoggerFactory.getLogger(S3ClientWrapper.class);
49
50 private final S3Client s3Client;
51
52 public S3ClientWrapper(S3Client s3Client) {
53 this.s3Client = s3Client;
54 }
55
56 @Override
57 public boolean bucketExists(String bucketName) {
58 try {
59 // using S3Client.listObjectsV2 instead of S3Client.listBuckets/headBucket in order to limit required permissions
60 s3Client.listObjectsV2(ListObjectsV2Request.builder().bucket(bucketName).maxKeys(1).build());
61 return true;
62 } catch (NoSuchBucketException e) {
63 return false;
64 } catch (SdkException e) {
65 throw new ObjectStoreOperationFailedException("Failed to determine if bucket exists.", e);
66 }
67 }
68
69 @Override
70 public List<S3Object> getObjects(String bucket, String prefix) {
71 try {
72 ListObjectsV2Response response =
73 s3Client.listObjectsV2(ListObjectsV2Request.builder().prefix(prefix).bucket(bucket).build());
74 return response.contents().stream().map(S3ClientWrapper::buildS3Object).collect(toList());
75 } catch (SdkException e) {
76 throw new ObjectStoreOperationFailedException("Failed to upload object to object store", e);
77 }
78 }
79
80 @Override
81 public void putObject(String bucket, String objectName, Path filePath, Map<HeaderKey, String> headers) {
82 RequestBody bodyFile = RequestBody.fromFile(filePath);
83
84 var requestBuilder = PutObjectRequest.builder().bucket(bucket).key(objectName);
85 if (headers.containsKey(HeaderKey.AMZ_ACL)) {
86 requestBuilder.acl(headers.get(HeaderKey.AMZ_ACL));
87 }
88 if (headers.containsKey(HeaderKey.CACHE_CONTROL)) {
89 requestBuilder.cacheControl(headers.get(HeaderKey.CACHE_CONTROL));
90 }
91
92 try {
93 s3Client.putObject(requestBuilder.build(), bodyFile);
94 } catch (SdkException e) {
95 throw new ObjectStoreOperationFailedException("Failed to upload object to object store", e);
96 }
97 }
98
99 @Override
100 public void removeObjects(String bucket, List<String> objectNames) {
101 if (objectNames.isEmpty()) {
102 return;
103 }
104
105 Collection<ObjectIdentifier> identifiers = objectNames.stream()
106 .map(key -> ObjectIdentifier.builder().key(key).build()).collect(toList());
107
108 try {
109 DeleteObjectsResponse response = s3Client.deleteObjects(
110 DeleteObjectsRequest.builder()
111 .bucket(bucket)
112 .delete(Delete.builder().objects(identifiers).build()).build());
113
114 if (response.hasErrors()) {
115 String errMessage = "Failed to remove objects from object store.";
116 logger.error("{} {}", errMessage, response.errors());
117 throw new ObjectStoreOperationFailedException(errMessage);
118 }
119 } catch (SdkException e) {
120 throw new ObjectStoreOperationFailedException("Failed to remove objects from object store.", e);
121 }
122 }
123
124 private static S3Object buildS3Object(software.amazon.awssdk.services.s3.model.S3Object s3Object) {
125 String etag = s3Object.eTag().replaceAll("\"", "");
126 return new S3Object(s3Object.key(), etag);
127 }
128 }
129
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/client/S3ClientWrapper.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/S3Distribution.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.distribution.runner;
22
23 import app.coronawarn.server.services.distribution.assembly.component.OutputDirectoryProvider;
24 import app.coronawarn.server.services.distribution.objectstore.ObjectStoreAccess;
25 import app.coronawarn.server.services.distribution.objectstore.S3Publisher;
26 import app.coronawarn.server.services.distribution.objectstore.client.ObjectStoreOperationFailedException;
27 import java.io.IOException;
28 import java.nio.file.Path;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
31 import org.springframework.boot.ApplicationArguments;
32 import org.springframework.boot.ApplicationRunner;
33 import org.springframework.core.annotation.Order;
34 import org.springframework.stereotype.Component;
35
36 /**
37 * This runner will sync the base working directory to the S3.
38 */
39 @Component
40 @Order(3)
41 public class S3Distribution implements ApplicationRunner {
42
43 private static final Logger logger = LoggerFactory.getLogger(S3Distribution.class);
44
45 private final OutputDirectoryProvider outputDirectoryProvider;
46
47 private final ObjectStoreAccess objectStoreAccess;
48
49 S3Distribution(OutputDirectoryProvider outputDirectoryProvider, ObjectStoreAccess objectStoreAccess) {
50 this.outputDirectoryProvider = outputDirectoryProvider;
51 this.objectStoreAccess = objectStoreAccess;
52 }
53
54 @Override
55 public void run(ApplicationArguments args) {
56 try {
57 Path pathToDistribute = outputDirectoryProvider.getFileOnDisk().toPath().toAbsolutePath();
58 S3Publisher s3Publisher = new S3Publisher(pathToDistribute, objectStoreAccess);
59
60 s3Publisher.publish();
61 logger.info("Data pushed to Object Store successfully.");
62 } catch (UnsupportedOperationException | ObjectStoreOperationFailedException | IOException e) {
63 logger.error("Distribution failed.", e);
64 }
65 }
66 }
67
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/S3Distribution.java]
[start of services/distribution/src/main/resources/application.yaml]
1 ---
2 logging:
3 level:
4 org:
5 springframework:
6 web: INFO
7 app:
8 coronawarn: INFO
9
10 services:
11 distribution:
12 output-file-name: index
13 retention-days: 14
14 expiry-policy-minutes: 120
15 shifting-policy-threshold: 140
16 include-incomplete-days: false
17 include-incomplete-hours: false
18 paths:
19 output: out
20 privatekey: ${VAULT_FILESIGNING_SECRET}
21 tek-export:
22 file-name: export.bin
23 file-header: EK Export v1
24 file-header-width: 16
25 api:
26 version-path: version
27 version-v1: v1
28 country-path: country
29 country-germany: DE
30 date-path: date
31 hour-path: hour
32 diagnosis-keys-path: diagnosis-keys
33 parameters-path: configuration
34 app-config-file-name: app_config
35 signature:
36 verification-key-id: 262
37 verification-key-version: v1
38 algorithm-oid: 1.2.840.10045.4.3.2
39 algorithm-name: SHA256withECDSA
40 file-name: export.sig
41 security-provider: BC
42 # Configuration for the S3 compatible object storage hosted by Telekom in Germany
43 objectstore:
44 access-key: ${CWA_OBJECTSTORE_ACCESSKEY:accessKey1}
45 secret-key: ${CWA_OBJECTSTORE_SECRETKEY:verySecretKey1}
46 endpoint: ${CWA_OBJECTSTORE_ENDPOINT:http://localhost}
47 bucket: ${CWA_OBJECTSTORE_BUCKET:cwa}
48 port: ${CWA_OBJECTSTORE_PORT:8003}
49 set-public-read-acl-on-put-object: true
50
51 spring:
52 main:
53 web-application-type: NONE
54 # Postgres configuration
55 jpa:
56 hibernate:
57 ddl-auto: validate
58 flyway:
59 enabled: true
60 locations: classpath:db/migration/postgres
61 password: ${POSTGRESQL_PASSWORD_FLYWAY:postgres}
62 user: ${POSTGRESQL_USER_FLYWAY:postgres}
63
64 datasource:
65 driver-class-name: org.postgresql.Driver
66 url: jdbc:postgresql://${POSTGRESQL_SERVICE_HOST:localhost}:${POSTGRESQL_SERVICE_PORT:5432}/${POSTGRESQL_DATABASE:cwa}
67 username: ${POSTGRESQL_USER_DISTRIBUTION:postgres}
68 password: ${POSTGRESQL_PASSWORD_DISTRIBUTION:postgres}
69
[end of services/distribution/src/main/resources/application.yaml]
</code>
Here is an example of a patch file. It consists of changes to the code base. It specifies the file names, the line numbers of each change, and the removed and added lines. A single patch file can contain changes to multiple files.
<patch>
--- a/file.py
+++ b/file.py
@@ -1,27 +1,35 @@
def euclidean(a, b):
- while b:
- a, b = b, a % b
- return a
+ if b == 0:
+ return a
+ return euclidean(b, a % b)
def bresenham(x0, y0, x1, y1):
points = []
dx = abs(x1 - x0)
dy = abs(y1 - y0)
- sx = 1 if x0 < x1 else -1
- sy = 1 if y0 < y1 else -1
- err = dx - dy
+ x, y = x0, y0
+ sx = -1 if x0 > x1 else 1
+ sy = -1 if y0 > y1 else 1
- while True:
- points.append((x0, y0))
- if x0 == x1 and y0 == y1:
- break
- e2 = 2 * err
- if e2 > -dy:
+ if dx > dy:
+ err = dx / 2.0
+ while x != x1:
+ points.append((x, y))
err -= dy
- x0 += sx
- if e2 < dx:
- err += dx
- y0 += sy
+ if err < 0:
+ y += sy
+ err += dx
+ x += sx
+ else:
+ err = dy / 2.0
+ while y != y1:
+ points.append((x, y))
+ err -= dx
+ if err < 0:
+ x += sx
+ err += dy
+ y += sy
+ points.append((x, y))
return points
</patch>
I need you to solve the provded issue by generating a single patch file that I can apply directly to this repository using git apply. Please respond with a single patch file in the format shown above.
Respond below:
| corona-warn-app/cwa-server | 896d24d3730d455ddc7a67bdaebd843ba7bd91dd | S3Publisher: Resilience
The S3Publisher/ObjectStoreAccess is currently lacking resilience features, like re-trys and error handling.
| 2020-06-02T14:48:26 | <patch>
diff --git a/services/distribution/pom.xml b/services/distribution/pom.xml
--- a/services/distribution/pom.xml
+++ b/services/distribution/pom.xml
@@ -78,6 +78,11 @@
<groupId>org.apache.commons</groupId>
<version>3.2</version>
</dependency>
+ <dependency>
+ <artifactId>spring-retry</artifactId>
+ <groupId>org.springframework.retry</groupId>
+ <version>1.3.0</version>
+ </dependency>
</dependencies>
</project>
\ No newline at end of file
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/config/DistributionServiceConfig.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/config/DistributionServiceConfig.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/config/DistributionServiceConfig.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/config/DistributionServiceConfig.java
@@ -394,6 +394,7 @@ public static class ObjectStore {
private Integer port;
private String bucket;
private Boolean setPublicReadAclOnPutObject;
+ private Integer maxNumberOfFailedOperations;
public String getAccessKey() {
return accessKey;
@@ -442,5 +443,13 @@ public Boolean isSetPublicReadAclOnPutObject() {
public void setSetPublicReadAclOnPutObject(Boolean setPublicReadAclOnPutObject) {
this.setPublicReadAclOnPutObject = setPublicReadAclOnPutObject;
}
+
+ public Integer getMaxNumberOfFailedOperations() {
+ return maxNumberOfFailedOperations;
+ }
+
+ public void setMaxNumberOfFailedOperations(Integer maxNumberOfFailedOperations) {
+ this.maxNumberOfFailedOperations = maxNumberOfFailedOperations;
+ }
}
}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/FailedObjectStoreOperationsCounter.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/FailedObjectStoreOperationsCounter.java
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/FailedObjectStoreOperationsCounter.java
@@ -0,0 +1,58 @@
+/*-
+ * ---license-start
+ * Corona-Warn-App
+ * ---
+ * Copyright (C) 2020 SAP SE and all other contributors
+ * ---
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://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 for the specific language governing permissions and
+ * limitations under the License.
+ * ---license-end
+ */
+
+package app.coronawarn.server.services.distribution.objectstore;
+
+import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
+import app.coronawarn.server.services.distribution.objectstore.client.ObjectStoreOperationFailedException;
+import java.util.concurrent.atomic.AtomicInteger;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Component;
+
+/**
+ * Maintains the count and maximum number of failed object store operations in a thread-safe manner.
+ */
+@Component
+public class FailedObjectStoreOperationsCounter {
+
+ private static final Logger logger = LoggerFactory.getLogger(FailedObjectStoreOperationsCounter.class);
+
+ private final int maxNumberOfFailedOperations;
+ private final AtomicInteger failedOperationsCounter = new AtomicInteger(0);
+
+ public FailedObjectStoreOperationsCounter(DistributionServiceConfig distributionServiceConfig) {
+ maxNumberOfFailedOperations = distributionServiceConfig.getObjectStore().getMaxNumberOfFailedOperations();
+ }
+
+ /**
+ * Increments the internal failed operations counter and rethrows the specified exception if the configured maximum
+ * number of failed object store operation was exceeded.
+ *
+ * @param cause The {@link ObjectStoreOperationFailedException} that is associated with the failed operation.
+ */
+ public void incrementAndCheckThreshold(ObjectStoreOperationFailedException cause) {
+ logger.error("Object store operation failed.", cause);
+ if (failedOperationsCounter.incrementAndGet() > maxNumberOfFailedOperations) {
+ logger.error("Number of failed object store operations exceeded threshold of {}.", maxNumberOfFailedOperations);
+ throw cause;
+ }
+ }
+}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/S3Publisher.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/S3Publisher.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/S3Publisher.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/S3Publisher.java
@@ -21,11 +21,13 @@
package app.coronawarn.server.services.distribution.objectstore;
import app.coronawarn.server.services.distribution.assembly.component.CwaApiStructureProvider;
+import app.coronawarn.server.services.distribution.objectstore.client.ObjectStoreOperationFailedException;
import app.coronawarn.server.services.distribution.objectstore.publish.LocalFile;
import app.coronawarn.server.services.distribution.objectstore.publish.PublishFileSet;
import app.coronawarn.server.services.distribution.objectstore.publish.PublishedFileSet;
import java.io.IOException;
import java.nio.file.Path;
+import java.util.List;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -48,18 +50,29 @@ public class S3Publisher {
private static final Logger logger = LoggerFactory.getLogger(S3Publisher.class);
- /** The default CWA root folder, which contains all CWA related files. */
+ /**
+ * The default CWA root folder, which contains all CWA related files.
+ */
private static final String CWA_S3_ROOT = CwaApiStructureProvider.VERSION_DIRECTORY;
- /** root folder for the upload on the local disk. */
private final Path root;
+ private final ObjectStoreAccess objectStoreAccess;
+ private final FailedObjectStoreOperationsCounter failedOperationsCounter;
- /** access to the object store. */
- private final ObjectStoreAccess access;
-
- public S3Publisher(Path root, ObjectStoreAccess access) {
+ /**
+ * Creates an {@link S3Publisher} instance that attempts to publish the files at the specified location to an object
+ * store. Object store operations are performed through the specified {@link ObjectStoreAccess} instance.
+ *
+ * @param root The path of the directory that shall be published.
+ * @param objectStoreAccess The {@link ObjectStoreAccess} used to communicate with the object store.
+ * @param failedOperationsCounter The {@link FailedObjectStoreOperationsCounter} that is used to monitor the number of
+ * failed operations.
+ */
+ public S3Publisher(Path root, ObjectStoreAccess objectStoreAccess,
+ FailedObjectStoreOperationsCounter failedOperationsCounter) {
this.root = root;
- this.access = access;
+ this.objectStoreAccess = objectStoreAccess;
+ this.failedOperationsCounter = failedOperationsCounter;
}
/**
@@ -68,18 +81,29 @@ public S3Publisher(Path root, ObjectStoreAccess access) {
* @throws IOException in case there were problems reading files from the disk.
*/
public void publish() throws IOException {
- var published = new PublishedFileSet(access.getObjectsWithPrefix(CWA_S3_ROOT));
- var toPublish = new PublishFileSet(root);
+ PublishedFileSet published;
+ List<LocalFile> toPublish = new PublishFileSet(root).getFiles();
+ List<LocalFile> diff;
- var diff = toPublish
- .getFiles()
- .stream()
- .filter(published::isNotYetPublished)
- .collect(Collectors.toList());
+ try {
+ published = new PublishedFileSet(objectStoreAccess.getObjectsWithPrefix(CWA_S3_ROOT));
+ diff = toPublish
+ .stream()
+ .filter(published::isNotYetPublished)
+ .collect(Collectors.toList());
+ } catch (ObjectStoreOperationFailedException e) {
+ failedOperationsCounter.incrementAndCheckThreshold(e);
+ // failed to retrieve existing files; publish everything
+ diff = toPublish;
+ }
logger.info("Beginning upload... ");
for (LocalFile file : diff) {
- this.access.putObject(file);
+ try {
+ this.objectStoreAccess.putObject(file);
+ } catch (ObjectStoreOperationFailedException e) {
+ failedOperationsCounter.incrementAndCheckThreshold(e);
+ }
}
logger.info("Upload completed.");
}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/S3RetentionPolicy.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/S3RetentionPolicy.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/S3RetentionPolicy.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/S3RetentionPolicy.java
@@ -22,6 +22,7 @@
import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
import app.coronawarn.server.services.distribution.config.DistributionServiceConfig.Api;
+import app.coronawarn.server.services.distribution.objectstore.client.ObjectStoreOperationFailedException;
import app.coronawarn.server.services.distribution.objectstore.client.S3Object;
import java.time.LocalDate;
import java.time.ZoneOffset;
@@ -39,10 +40,16 @@ public class S3RetentionPolicy {
private final ObjectStoreAccess objectStoreAccess;
private final Api api;
+ private final FailedObjectStoreOperationsCounter failedObjectStoreOperationsCounter;
- public S3RetentionPolicy(ObjectStoreAccess objectStoreAccess, DistributionServiceConfig distributionServiceConfig) {
+ /**
+ * Creates an {@link S3RetentionPolicy} instance with the specified parameters.
+ */
+ public S3RetentionPolicy(ObjectStoreAccess objectStoreAccess, DistributionServiceConfig distributionServiceConfig,
+ FailedObjectStoreOperationsCounter failedOperationsCounter) {
this.objectStoreAccess = objectStoreAccess;
this.api = distributionServiceConfig.getApi();
+ this.failedObjectStoreOperationsCounter = failedOperationsCounter;
}
/**
@@ -77,6 +84,10 @@ public void applyRetentionPolicy(int retentionDays) {
* @param diagnosisKey the diagnosis key, that should be deleted.
*/
public void deleteDiagnosisKey(S3Object diagnosisKey) {
- objectStoreAccess.deleteObjectsWithPrefix(diagnosisKey.getObjectName());
+ try {
+ objectStoreAccess.deleteObjectsWithPrefix(diagnosisKey.getObjectName());
+ } catch (ObjectStoreOperationFailedException e) {
+ failedObjectStoreOperationsCounter.incrementAndCheckThreshold(e);
+ }
}
}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/client/ObjectStoreClientConfig.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/client/ObjectStoreClientConfig.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/client/ObjectStoreClientConfig.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/client/ObjectStoreClientConfig.java
@@ -25,6 +25,7 @@
import java.net.URI;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
+import org.springframework.retry.annotation.EnableRetry;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
@@ -35,6 +36,7 @@
* Manages the instantiation of the {@link ObjectStoreClient} bean.
*/
@Configuration
+@EnableRetry
public class ObjectStoreClientConfig {
private static final Region DEFAULT_REGION = Region.EU_CENTRAL_1;
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/client/S3ClientWrapper.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/client/S3ClientWrapper.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/client/S3ClientWrapper.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/client/S3ClientWrapper.java
@@ -28,6 +28,10 @@
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import org.springframework.retry.annotation.Backoff;
+import org.springframework.retry.annotation.Recover;
+import org.springframework.retry.annotation.Retryable;
+import org.springframework.retry.support.RetrySynchronizationManager;
import software.amazon.awssdk.core.exception.SdkException;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.services.s3.S3Client;
@@ -67,18 +71,29 @@ public boolean bucketExists(String bucketName) {
}
@Override
+ @Retryable(
+ value = SdkException.class,
+ maxAttemptsExpression = "${services.distribution.objectstore.retry-attempts}",
+ backoff = @Backoff(delayExpression = "${services.distribution.objectstore.retry-backoff}"))
public List<S3Object> getObjects(String bucket, String prefix) {
- try {
- ListObjectsV2Response response =
- s3Client.listObjectsV2(ListObjectsV2Request.builder().prefix(prefix).bucket(bucket).build());
- return response.contents().stream().map(S3ClientWrapper::buildS3Object).collect(toList());
- } catch (SdkException e) {
- throw new ObjectStoreOperationFailedException("Failed to upload object to object store", e);
- }
+ logRetryStatus("object download");
+ ListObjectsV2Response response =
+ s3Client.listObjectsV2(ListObjectsV2Request.builder().prefix(prefix).bucket(bucket).build());
+ return response.contents().stream().map(S3ClientWrapper::buildS3Object).collect(toList());
+ }
+
+ @Recover
+ public List<S3Object> skipReadOperation(Throwable cause) {
+ throw new ObjectStoreOperationFailedException("Failed to get objects from object store", cause);
}
@Override
+ @Retryable(
+ value = SdkException.class,
+ maxAttemptsExpression = "${services.distribution.objectstore.retry-attempts}",
+ backoff = @Backoff(delayExpression = "${services.distribution.objectstore.retry-backoff}"))
public void putObject(String bucket, String objectName, Path filePath, Map<HeaderKey, String> headers) {
+ logRetryStatus("object upload");
RequestBody bodyFile = RequestBody.fromFile(filePath);
var requestBuilder = PutObjectRequest.builder().bucket(bucket).key(objectName);
@@ -89,40 +104,46 @@ public void putObject(String bucket, String objectName, Path filePath, Map<Heade
requestBuilder.cacheControl(headers.get(HeaderKey.CACHE_CONTROL));
}
- try {
- s3Client.putObject(requestBuilder.build(), bodyFile);
- } catch (SdkException e) {
- throw new ObjectStoreOperationFailedException("Failed to upload object to object store", e);
- }
+ s3Client.putObject(requestBuilder.build(), bodyFile);
}
@Override
+ @Retryable(value = {SdkException.class, ObjectStoreOperationFailedException.class},
+ maxAttemptsExpression = "${services.distribution.objectstore.retry-attempts}",
+ backoff = @Backoff(delayExpression = "${services.distribution.objectstore.retry-backoff}"))
public void removeObjects(String bucket, List<String> objectNames) {
if (objectNames.isEmpty()) {
return;
}
+ logRetryStatus("object deletion");
Collection<ObjectIdentifier> identifiers = objectNames.stream()
.map(key -> ObjectIdentifier.builder().key(key).build()).collect(toList());
- try {
- DeleteObjectsResponse response = s3Client.deleteObjects(
- DeleteObjectsRequest.builder()
- .bucket(bucket)
- .delete(Delete.builder().objects(identifiers).build()).build());
-
- if (response.hasErrors()) {
- String errMessage = "Failed to remove objects from object store.";
- logger.error("{} {}", errMessage, response.errors());
- throw new ObjectStoreOperationFailedException(errMessage);
- }
- } catch (SdkException e) {
- throw new ObjectStoreOperationFailedException("Failed to remove objects from object store.", e);
+ DeleteObjectsResponse response = s3Client.deleteObjects(
+ DeleteObjectsRequest.builder()
+ .bucket(bucket)
+ .delete(Delete.builder().objects(identifiers).build()).build());
+
+ if (response.hasErrors()) {
+ throw new ObjectStoreOperationFailedException("Failed to remove objects from object store.");
}
}
+ @Recover
+ private void skipModifyingOperation(Throwable cause) {
+ throw new ObjectStoreOperationFailedException("Failed to modify objects on object store.", cause);
+ }
+
private static S3Object buildS3Object(software.amazon.awssdk.services.s3.model.S3Object s3Object) {
String etag = s3Object.eTag().replaceAll("\"", "");
return new S3Object(s3Object.key(), etag);
}
+
+ private void logRetryStatus(String action) {
+ int retryCount = RetrySynchronizationManager.getContext().getRetryCount();
+ if (retryCount > 0) {
+ logger.warn("Retrying {} after {} failed attempt(s).", action, retryCount);
+ }
+ }
}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/S3Distribution.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/S3Distribution.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/S3Distribution.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/S3Distribution.java
@@ -21,6 +21,7 @@
package app.coronawarn.server.services.distribution.runner;
import app.coronawarn.server.services.distribution.assembly.component.OutputDirectoryProvider;
+import app.coronawarn.server.services.distribution.objectstore.FailedObjectStoreOperationsCounter;
import app.coronawarn.server.services.distribution.objectstore.ObjectStoreAccess;
import app.coronawarn.server.services.distribution.objectstore.S3Publisher;
import app.coronawarn.server.services.distribution.objectstore.client.ObjectStoreOperationFailedException;
@@ -43,19 +44,21 @@ public class S3Distribution implements ApplicationRunner {
private static final Logger logger = LoggerFactory.getLogger(S3Distribution.class);
private final OutputDirectoryProvider outputDirectoryProvider;
-
private final ObjectStoreAccess objectStoreAccess;
+ private final FailedObjectStoreOperationsCounter failedOperationsCounter;
- S3Distribution(OutputDirectoryProvider outputDirectoryProvider, ObjectStoreAccess objectStoreAccess) {
+ S3Distribution(OutputDirectoryProvider outputDirectoryProvider, ObjectStoreAccess objectStoreAccess,
+ FailedObjectStoreOperationsCounter failedOperationsCounter) {
this.outputDirectoryProvider = outputDirectoryProvider;
this.objectStoreAccess = objectStoreAccess;
+ this.failedOperationsCounter = failedOperationsCounter;
}
@Override
public void run(ApplicationArguments args) {
try {
Path pathToDistribute = outputDirectoryProvider.getFileOnDisk().toPath().toAbsolutePath();
- S3Publisher s3Publisher = new S3Publisher(pathToDistribute, objectStoreAccess);
+ S3Publisher s3Publisher = new S3Publisher(pathToDistribute, objectStoreAccess, failedOperationsCounter);
s3Publisher.publish();
logger.info("Data pushed to Object Store successfully.");
diff --git a/services/distribution/src/main/resources/application.yaml b/services/distribution/src/main/resources/application.yaml
--- a/services/distribution/src/main/resources/application.yaml
+++ b/services/distribution/src/main/resources/application.yaml
@@ -47,6 +47,9 @@ services:
bucket: ${CWA_OBJECTSTORE_BUCKET:cwa}
port: ${CWA_OBJECTSTORE_PORT:8003}
set-public-read-acl-on-put-object: true
+ retry-attempts: 3
+ retry-backoff: 2000
+ max-number-of-failed-operations: 5
spring:
main:
</patch> | diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/ApplicationVersionConfigurationProviderMasterFileTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/ApplicationVersionConfigurationProviderMasterFileTest.java
--- a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/ApplicationVersionConfigurationProviderMasterFileTest.java
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/ApplicationVersionConfigurationProviderMasterFileTest.java
@@ -23,7 +23,6 @@
import static org.assertj.core.api.Assertions.assertThat;
import app.coronawarn.server.services.distribution.assembly.appconfig.validation.ApplicationVersionConfigurationValidator;
-import app.coronawarn.server.services.distribution.assembly.appconfig.validation.ExposureConfigurationValidator;
import app.coronawarn.server.services.distribution.assembly.appconfig.validation.ValidationResult;
import org.junit.jupiter.api.Test;
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/FailedObjectStoreOperationsCounterTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/FailedObjectStoreOperationsCounterTest.java
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/FailedObjectStoreOperationsCounterTest.java
@@ -0,0 +1,58 @@
+/*-
+ * ---license-start
+ * Corona-Warn-App
+ * ---
+ * Copyright (C) 2020 SAP SE and all other contributors
+ * ---
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://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 for the specific language governing permissions and
+ * limitations under the License.
+ * ---license-end
+ */
+
+package app.coronawarn.server.services.distribution.objectstore;
+
+import static org.assertj.core.api.Assertions.assertThatCode;
+import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
+
+import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
+import app.coronawarn.server.services.distribution.objectstore.client.ObjectStoreOperationFailedException;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.context.properties.EnableConfigurationProperties;
+import org.springframework.boot.test.context.ConfigFileApplicationContextInitializer;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit.jupiter.SpringExtension;
+
+@ExtendWith(SpringExtension.class)
+@ContextConfiguration(classes = {
+ FailedObjectStoreOperationsCounter.class}, initializers = ConfigFileApplicationContextInitializer.class)
+@EnableConfigurationProperties(value = DistributionServiceConfig.class)
+class FailedObjectStoreOperationsCounterTest {
+
+ @Autowired
+ private DistributionServiceConfig distributionServiceConfig;
+
+ @Autowired
+ private FailedObjectStoreOperationsCounter failedObjectStoreOperationsCounter;
+
+ @Test
+ void shouldThrowOnSixthAttempt() {
+ var exception = new ObjectStoreOperationFailedException("mock");
+ for (int i = 0; i < distributionServiceConfig.getObjectStore().getMaxNumberOfFailedOperations(); i++) {
+ assertThatCode(() -> failedObjectStoreOperationsCounter.incrementAndCheckThreshold(exception))
+ .doesNotThrowAnyException();
+ }
+ assertThatExceptionOfType(ObjectStoreOperationFailedException.class)
+ .isThrownBy(() -> failedObjectStoreOperationsCounter.incrementAndCheckThreshold(exception));
+ }
+}
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/ObjectStoreAccessTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/ObjectStoreAccessTest.java
--- a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/ObjectStoreAccessTest.java
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/ObjectStoreAccessTest.java
@@ -24,7 +24,8 @@
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
-import app.coronawarn.server.services.distribution.Application;
+import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
+import app.coronawarn.server.services.distribution.objectstore.client.ObjectStoreClientConfig;
import app.coronawarn.server.services.distribution.objectstore.publish.LocalFile;
import app.coronawarn.server.services.distribution.objectstore.publish.LocalGenericFile;
import java.io.IOException;
@@ -36,14 +37,14 @@
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.boot.test.context.ConfigFileApplicationContextInitializer;
+import org.springframework.boot.context.properties.EnableConfigurationProperties;
+import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.io.ResourceLoader;
-import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
@ExtendWith(SpringExtension.class)
-@ContextConfiguration(classes = {Application.class},
- initializers = ConfigFileApplicationContextInitializer.class)
+@SpringBootTest(classes = {ObjectStoreAccess.class, ObjectStoreClientConfig.class})
+@EnableConfigurationProperties(value = DistributionServiceConfig.class)
@Tag("s3-integration")
class ObjectStoreAccessTest {
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/S3PublisherIntegrationTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/S3PublisherIntegrationTest.java
--- a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/S3PublisherIntegrationTest.java
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/S3PublisherIntegrationTest.java
@@ -21,6 +21,7 @@
package app.coronawarn.server.services.distribution.objectstore;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.mock;
import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
import app.coronawarn.server.services.distribution.objectstore.client.ObjectStoreClientConfig;
@@ -35,14 +36,12 @@
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
-import org.springframework.boot.test.context.ConfigFileApplicationContextInitializer;
+import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.io.ResourceLoader;
-import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
@ExtendWith(SpringExtension.class)
-@ContextConfiguration(classes = {ObjectStoreAccess.class, ObjectStoreClientConfig.class},
- initializers = ConfigFileApplicationContextInitializer.class)
+@SpringBootTest(classes = {ObjectStoreAccess.class, ObjectStoreClientConfig.class})
@EnableConfigurationProperties(value = DistributionServiceConfig.class)
@Tag("s3-integration")
class S3PublisherIntegrationTest {
@@ -57,7 +56,8 @@ class S3PublisherIntegrationTest {
@Test
void publishTestFolderOk() throws IOException {
- S3Publisher publisher = new S3Publisher(getFolderAsPath(rootTestFolder), objectStoreAccess);
+ S3Publisher publisher = new S3Publisher(
+ getFolderAsPath(rootTestFolder), objectStoreAccess, mock(FailedObjectStoreOperationsCounter.class));
publisher.publish();
List<S3Object> s3Objects = objectStoreAccess.getObjectsWithPrefix("version");
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/S3PublisherTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/S3PublisherTest.java
--- a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/S3PublisherTest.java
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/S3PublisherTest.java
@@ -21,6 +21,7 @@
package app.coronawarn.server.services.distribution.objectstore;
import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -115,6 +116,6 @@ private List<S3Object> twoIdenticalOneOtherOneChange() {
private S3Publisher createTestPublisher() throws IOException {
var publishPath = resourceLoader.getResource(PUBLISHING_PATH).getFile().toPath();
- return new S3Publisher(publishPath, objectStoreAccess);
+ return new S3Publisher(publishPath, objectStoreAccess, mock(FailedObjectStoreOperationsCounter.class));
}
}
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/S3RetentionPolicyTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/S3RetentionPolicyTest.java
--- a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/S3RetentionPolicyTest.java
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/S3RetentionPolicyTest.java
@@ -23,12 +23,15 @@
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.atLeastOnce;
+import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
import app.coronawarn.server.services.distribution.config.DistributionServiceConfig.ObjectStore;
+import app.coronawarn.server.services.distribution.objectstore.client.ObjectStoreOperationFailedException;
import app.coronawarn.server.services.distribution.objectstore.client.S3Object;
import java.time.LocalDate;
import java.time.ZoneOffset;
@@ -44,17 +47,21 @@
@EnableConfigurationProperties(value = DistributionServiceConfig.class)
@ExtendWith(SpringExtension.class)
-@ContextConfiguration(classes = {S3RetentionPolicy.class, ObjectStore.class},
+@ContextConfiguration(classes = {S3RetentionPolicy.class, ObjectStore.class, FailedObjectStoreOperationsCounter.class},
initializers = ConfigFileApplicationContextInitializer.class)
class S3RetentionPolicyTest {
@MockBean
private ObjectStoreAccess objectStoreAccess;
+ @MockBean
+ private FailedObjectStoreOperationsCounter failedObjectStoreOperationsCounter;
+
@Autowired
private S3RetentionPolicy s3RetentionPolicy;
- @Autowired DistributionServiceConfig distributionServiceConfig;
+ @Autowired
+ private DistributionServiceConfig distributionServiceConfig;
@Test
void shouldDeleteOldFiles() {
@@ -83,6 +90,16 @@ void shouldNotDeleteFilesIfAllAreValid() {
verify(objectStoreAccess, never()).deleteObjectsWithPrefix(any());
}
+ @Test
+ void deleteDiagnosisKeysUpdatesFailedOperationCounter() {
+ doThrow(ObjectStoreOperationFailedException.class).when(objectStoreAccess).deleteObjectsWithPrefix(any());
+
+ s3RetentionPolicy.deleteDiagnosisKey(new S3Object("foo"));
+
+ verify(failedObjectStoreOperationsCounter, times(1))
+ .incrementAndCheckThreshold(any(ObjectStoreOperationFailedException.class));
+ }
+
private String generateFileName(LocalDate date) {
var api = distributionServiceConfig.getApi();
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/client/S3ClientWrapperTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/client/S3ClientWrapperTest.java
--- a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/client/S3ClientWrapperTest.java
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/client/S3ClientWrapperTest.java
@@ -27,10 +27,12 @@
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.atLeastOnce;
-import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.reset;
+import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
+import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
import app.coronawarn.server.services.distribution.objectstore.client.ObjectStoreClient.HeaderKey;
import java.nio.file.Path;
import java.util.List;
@@ -44,6 +46,15 @@
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.boot.context.properties.EnableConfigurationProperties;
+import org.springframework.boot.test.context.ConfigFileApplicationContextInitializer;
+import org.springframework.boot.test.mock.mockito.MockBean;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.retry.annotation.EnableRetry;
+import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.core.exception.SdkException;
@@ -62,19 +73,36 @@
import software.amazon.awssdk.utils.builder.SdkBuilder;
@ExtendWith(SpringExtension.class)
+@ContextConfiguration(initializers = ConfigFileApplicationContextInitializer.class)
+@EnableConfigurationProperties(value = DistributionServiceConfig.class)
class S3ClientWrapperTest {
private static final String VALID_BUCKET_NAME = "myBucket";
private static final String VALID_PREFIX = "prefix";
private static final String VALID_NAME = "object key";
+ @Value("${services.distribution.objectstore.retry-attempts}")
+ private int configuredNumberOfRetries;
+
+ @MockBean
private S3Client s3Client;
- private S3ClientWrapper s3ClientWrapper;
+
+ @Autowired
+ private ObjectStoreClient s3ClientWrapper;
+
+ @Configuration
+ @EnableRetry
+ public static class RetryS3ClientConfig {
+
+ @Bean
+ public ObjectStoreClient createS3ClientWrapper(S3Client s3Client) {
+ return new S3ClientWrapper(s3Client);
+ }
+ }
@BeforeEach
public void setUpMocks() {
- s3Client = mock(S3Client.class);
- s3ClientWrapper = new S3ClientWrapper(s3Client);
+ reset(s3Client);
}
@Test
@@ -156,6 +184,16 @@ void getObjectsThrowsObjectStoreOperationFailedExceptionIfClientThrows(Class<Exc
.isThrownBy(() -> s3ClientWrapper.getObjects(VALID_BUCKET_NAME, VALID_PREFIX));
}
+ @ParameterizedTest
+ @ValueSource(classes = {NoSuchBucketException.class, S3Exception.class, SdkClientException.class, SdkException.class})
+ void shouldRetryGettingObjectsAndThenThrow(Class<Exception> cause) {
+ when(s3Client.listObjectsV2(any(ListObjectsV2Request.class))).thenThrow(cause);
+ assertThatExceptionOfType(ObjectStoreOperationFailedException.class)
+ .isThrownBy(() -> s3ClientWrapper.getObjects(VALID_BUCKET_NAME, VALID_PREFIX));
+
+ verify(s3Client, times(configuredNumberOfRetries)).listObjectsV2(any(ListObjectsV2Request.class));
+ }
+
@Test
void testPutObjectForNoHeaders() {
s3ClientWrapper.putObject(VALID_BUCKET_NAME, VALID_NAME, Path.of(""), emptyMap());
@@ -193,6 +231,16 @@ void putObjectsThrowsObjectStoreOperationFailedExceptionIfClientThrows(Class<Exc
.isThrownBy(() -> s3ClientWrapper.putObject(VALID_BUCKET_NAME, VALID_PREFIX, Path.of(""), emptyMap()));
}
+ @ParameterizedTest
+ @ValueSource(classes = {NoSuchBucketException.class, S3Exception.class, SdkClientException.class, SdkException.class})
+ void shouldRetryUploadingObjectAndThenThrow(Class<Exception> cause) {
+ when(s3Client.putObject(any(PutObjectRequest.class), any(RequestBody.class))).thenThrow(cause);
+ assertThatExceptionOfType(ObjectStoreOperationFailedException.class)
+ .isThrownBy(() -> s3ClientWrapper.putObject(VALID_BUCKET_NAME, VALID_PREFIX, Path.of(""), emptyMap()));
+
+ verify(s3Client, times(configuredNumberOfRetries)).putObject(any(PutObjectRequest.class), any(RequestBody.class));
+ }
+
@Test
void testRemoveObjects() {
when(s3Client.deleteObjects(any(DeleteObjectsRequest.class))).thenReturn(DeleteObjectsResponse.builder().build());
@@ -227,4 +275,14 @@ void removeObjectsThrowsObjectStoreOperationFailedExceptionIfClientThrows(Class<
assertThatExceptionOfType(ObjectStoreOperationFailedException.class)
.isThrownBy(() -> s3ClientWrapper.removeObjects(VALID_BUCKET_NAME, List.of(VALID_NAME)));
}
+
+ @ParameterizedTest
+ @ValueSource(classes = {NoSuchBucketException.class, S3Exception.class, SdkClientException.class, SdkException.class})
+ void shouldRetryRemovingObjectAndThenThrow(Class<Exception> cause) {
+ when(s3Client.deleteObjects(any(DeleteObjectsRequest.class))).thenThrow(cause);
+ assertThatExceptionOfType(ObjectStoreOperationFailedException.class)
+ .isThrownBy(() -> s3ClientWrapper.removeObjects(VALID_BUCKET_NAME, List.of(VALID_NAME)));
+
+ verify(s3Client, times(configuredNumberOfRetries)).deleteObjects(any(DeleteObjectsRequest.class));
+ }
}
diff --git a/services/distribution/src/test/resources/application.yaml b/services/distribution/src/test/resources/application.yaml
--- a/services/distribution/src/test/resources/application.yaml
+++ b/services/distribution/src/test/resources/application.yaml
@@ -46,6 +46,9 @@ services:
bucket: ${CWA_OBJECTSTORE_BUCKET:cwa}
port: ${CWA_OBJECTSTORE_PORT:8003}
set-public-read-acl-on-put-object: true
+ retry-attempts: 3
+ retry-backoff: 1
+ max-number-of-failed-operations: 5
spring:
main:
banner-mode: off
| |||||
corona-warn-app__cwa-server-135 | You will be provided with a partial code base and an issue statement explaining a problem to resolve.
<issue>
Submission Service: Enable waiting for Fake Requests
When fake requests are send to the submission service, ensure that the duration of the fake requests take as long as normal requests, so attackers sniffing the traffic are unable to distinguish between fake/normal requests.
</issue>
<code>
[start of README.md]
1 <h1 align="center">
2 Corona-Warn-App Server
3 </h1>
4
5 <p align="center">
6 <a href="https://github.com/Exposure-Notification-App/ena-documentation/commits/" title="Last Commit"><img src="https://img.shields.io/github/last-commit/corona-warn-app/cwa-server?style=flat"></a>
7 <a href="https://github.com/Exposure-Notification-App/ena-documentation/issues" title="Open Issues"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat"></a>
8 <a href="https://circleci.com/gh/corona-warn-app/cwa-server" title="Build Status"><img src="https://circleci.com/gh/corona-warn-app/cwa-server.svg?style=flat&circle-token=a7294b977bb9ea2c2d53ff62c9aa442670e19b59"></a>
9 <a href="https://github.com/corona-warn-app/cwa-server/blob/master/LICENSE" title="License"><img src="https://img.shields.io/badge/License-Apache%202.0-green.svg?style=flat"></a>
10 </p>
11
12 <p align="center">
13 <a href="#development">Development</a> •
14 <a href="#service-apis">Service APIs</a> •
15 <a href="#documentation">Documentation</a> •
16 <a href="#support--feedback">Support</a> •
17 <a href="#how-to-contribute">How to Contribute</a> •
18 <a href="#contributors">Contributors</a> •
19 <a href="#repositories">Repositories</a> •
20 <a href="#licensing">Licensing</a>
21 </p>
22
23 The goal of this project is to develop the official Corona-Warn-App for Germany based on the exposure notification API from [Apple](https://www.apple.com/covid19/contacttracing/) and [Google](https://www.google.com/covid19/exposurenotifications/). The apps (for both iOS and Android) use Bluetooth technology to exchange anonymous encrypted data with other mobile phones (on which the app is also installed) in the vicinity of an app user's phone. The data is stored locally on each user's device, preventing authorities or other parties from accessing or controlling the data. This repository contains the **implementation of the server for encryption keys** for the Corona-Warn-App. This implementation is still a **work in progress**, and the code it contains is currently alpha-quality code.
24
25 In this documentation, Corona-Warn-App services are also referred to as cwa services.
26
27 ## Development
28
29 After you've checked out this repository, you can run the application in one of the following ways:
30
31 * As a [Docker](https://www.docker.com/)-based deployment on your local machine. You can run either:
32 * Single components using the respective Dockerfile or
33 * The full backend using the Docker Compose (which is considered the most convenient way)
34 * As a [Maven](https://maven.apache.org)-based build on your local machine.
35 If you want to develop something in a single component, this approach is preferable.
36
37 ### Docker-Based Deployment
38
39 If you want to use Docker-based deployment, you need to install Docker on your local machine. For more information about downloading and installing Docker, see the [official Docker documentation](https://docs.docker.com/get-docker/).
40
41 #### Running the Full cwa Backend Using Docker Compose
42
43 For your convenience, a full setup including the generation of test data has been prepared using [Docker Compose](https://docs.docker.com/compose/reference/overview/). To build the backend services, run ```docker-compose build``` in the repository's root directory. A default configuration file can be found under ```.env```in the root folder of the repository. The default values for the local Postgres and MinIO build should be changed in this file before docker-compose is run.
44
45 Once the services are built, you can start the whole backend using ```docker-compose up```.
46 The distribution service runs once and then finishes. If you want to trigger additional distribution runs, run ```docker-compose start distribution```.
47
48 The docker-compose contains the following services:
49
50 Service | Description | Endpoint and Default Credentials
51 --------------|-------------|-----------
52 submission | The Corona-Warn-App submission service | http://localhost:8080
53 distribution | The Corona-Warn-App distribution service | NO ENDPOINT
54 postgres | A [postgres] database installation | postgres:5432 <br> Username: postgres <br> Password: postgres
55 pgadmin | A [pgadmin](https://www.pgadmin.org/) installation for the postgres database | http://localhost:8081 <br> Username: [email protected] <br> Password: password
56 minio | [MinIO] is an S3-compliant object store | http://localhost:8082/ <br> Access key: cws_key_id <br> Secret key: cws_secret_key_id
57
58 #### Running Single cwa Services Using Docker
59
60 If you would like to build and run a single cwa service, it's considered easiest to run them in a Docker environment. You can do this using the script provided in the respective cwa service directory. The Docker script first builds the cwa service and then creates an image for the runtime, which means that there are no additional dependencies for you to install.
61
62 To build and run the distribution service, run the following command:
63
64 ```bash
65 ./services/distribution/build_and_run.sh
66 ```
67
68 To build and run the submission service, run the following command:
69
70 ```bash
71 ./services/submission/build_and_run.sh
72 ```
73
74 The submission service is available on localhost:8080.
75
76 ### Maven-Based Build
77
78 If you want to actively develop in one of the cwa services, the Maven-based runtime is most suitable.
79 To prepare your machine to run the cwa project locally, we recommend that you first ensure that you've installed the following:
80
81 * [Minimum JDK Version 11](https://openjdk.java.net/)
82 * [Maven 3.6](https://maven.apache.org/)
83 * [Postgres] (if you want to connect to a persistent storage; if a postgres connection is not specified, an in-memory [HSQLDB] is provided)
84 * [MinIO] (if you want to run the distribution service and write the files to an object store instead of using your local file system)
85
86 #### Build
87
88 After you've checked out the repository, to build the project, run ```mvn install``` in your base directory.
89
90 ### Run
91
92 Navigate to the service you want to start and run the spring-boot:run target. The HSQLDB is used by default.
93 When you start the submission service, the endpoint is available on your local port 8080.
94
95 If you want to start the submission service, for example, you start it as follows:
96
97 ```bash
98 cd services/submission/
99 mvn spring-boot:run
100 ```
101
102 If you want to use a Postgres database instead of the default in-memory HSQLDB, use the Postgres profile when starting the application:
103
104 ```bash
105 cd services/submission/
106 mvn spring-boot:run -Dspring-boot.run.profiles=postgres
107 ```
108
109 To enable the S3 integration in the cwa distribution service, use the S3 profile when starting the application:
110
111 ```bash
112 cd services/distribution/
113 mvn spring-boot:run -Dspring-boot.run.profiles=s3
114 ```
115
116 You can also combine multiple profiles if necessary:
117
118 ```bash
119 cd services/distribution/
120 mvn spring-boot:run -Dspring-boot.run.profiles=dev,postgres,s3
121 ```
122
123 ### Debugging
124
125 To enable the `DEBUG` log level, you can run the application using the Spring `dev` profile.
126
127 ```bash
128 mvn spring-boot:run -Dspring-boot.run.profiles=dev
129 ```
130
131 To be able to set breakpoints (e.g. in IntelliJ), it may be necessary to use the ```-Dspring-boot.run.fork=false``` parameter.
132
133 ## Service APIs
134
135 The API that is being exposed by the backend services is documented in an [OpenAPI](https://www.openapis.org/) specification. The specification files are available at the following locations:
136
137 Service | OpenAPI Specification
138 -------------|-------------
139 Submission Service | https://github.com/corona-warn-app/cwa-server/raw/master/services/submission/api_v1.json
140 Distribution Service | https://github.com/corona-warn-app/cwa-server/raw/master/services/distribution/api_v1.json
141
142 ## Documentation
143
144 The full documentation for the Corona-Warn-App can be found in the [cwa-documentation] repository. This repository contains technical documents, UI/UX specifications, architecture information, and whitepapers for this implementation.
145
146 ## Support and Feedback
147
148 The following channels are available for discussions, feedback, and support requests:
149
150 | Type | Channel |
151 | ------------------------ | ------------------------------------------------------ |
152 | **General Discussion** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="General Discussion"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/question.svg?style=flat-square"></a> </a> |
153 | **Concept Feedback** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="Open Concept Feedback"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/concept-extension.svg?style=flat-square"></a> |
154 | **Backend Issue** | <a href="https://github.com/corona-warn-app/cwa-server/issues/new/choose" title="Open Backend Issue"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server/backend.svg?style=flat-square"></a> |
155 | **Other Requests** | <a href="mailto:[email protected]" title="Email CWD Team"><img src="https://img.shields.io/badge/email-CWD%20team-green?logo=mail.ru&style=flat-square&logoColor=white"></a> |
156
157 ## How to Contribute
158
159 Contribution and feedback are 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.
160
161 ## Contributors
162
163 The German government requested SAP SE and Deutsche Telekom AG to develop the Corona-Warn-App. Deutsche Telekom is providing the infrastructure technology and is to operate and run the backend for the app in a safe, scalable, and stable manner. SAP is responsible for app development and the exposure notification backend. Development teams from both SAP and Deutsche Telekom are therefore contributing to this project. At the same time, commitment to open source means that all interested parties are being enabled **and encouraged** to contribute and become part of this developer community.
164
165 ## Repositories
166
167 The following public repositories are currently available for the Corona-Warn-App:
168
169 | Repository | Description |
170 | ------------------- | --------------------------------------------------------------------- |
171 | [cwa-documentation] | Project overview, general documentation, and white papers |
172 | [cwa-server] | Backend implementation for the Apple/Google exposure notification API|
173
174 [cwa-documentation]: https://github.com/corona-warn-app/cwa-documentation
175 [cwa-server]: https://github.com/corona-warn-app/cwa-server
176 [Postgres]: https://www.postgresql.org/
177 [MinIO]: https://min.io/
178 [HSQLDB]: http://hsqldb.org/
179 ---
180
181 ## Licensing
182
183 This project is licensed under the **Apache 2.0** license. For more information, see the [LICENSE](./LICENSE) file.
184
[end of README.md]
[start of services/submission/pom.xml]
1 <?xml version="1.0" encoding="UTF-8"?>
2 <project xmlns="http://maven.apache.org/POM/4.0.0"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
5 <parent>
6 <artifactId>services</artifactId>
7 <groupId>org.opencwa</groupId>
8 <version>0.0.1-SNAPSHOT</version>
9 <relativePath>../pom.xml</relativePath>
10 </parent>
11 <modelVersion>4.0.0</modelVersion>
12
13 <artifactId>submission</artifactId>
14 <version>0.0.1-SNAPSHOT</version>
15
16 <dependencies>
17 <dependency>
18 <groupId>org.springframework.boot</groupId>
19 <artifactId>spring-boot-starter-web</artifactId>
20 </dependency>
21 <dependency>
22 <groupId>org.springframework.boot</groupId>
23 <artifactId>spring-boot-starter-security</artifactId>
24 </dependency>
25 </dependencies>
26
27 </project>
[end of services/submission/pom.xml]
[start of services/submission/src/main/java/app/coronawarn/server/services/submission/controller/SubmissionController.java]
1 package app.coronawarn.server.services.submission.controller;
2
3 import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
4 import app.coronawarn.server.common.persistence.service.DiagnosisKeyService;
5 import app.coronawarn.server.common.protocols.internal.SubmissionPayload;
6 import app.coronawarn.server.services.submission.verification.TanVerifier;
7 import java.util.Collection;
8 import java.util.stream.Collectors;
9 import org.springframework.beans.factory.annotation.Autowired;
10 import org.springframework.http.HttpStatus;
11 import org.springframework.http.ResponseEntity;
12 import org.springframework.web.bind.annotation.PostMapping;
13 import org.springframework.web.bind.annotation.RequestBody;
14 import org.springframework.web.bind.annotation.RequestHeader;
15 import org.springframework.web.bind.annotation.RequestMapping;
16 import org.springframework.web.bind.annotation.RestController;
17
18 @RestController
19 @RequestMapping("/version/v1")
20 public class SubmissionController {
21
22 /**
23 * The route to the submission endpoint (version agnostic).
24 */
25 public static final String SUBMISSION_ROUTE = "/diagnosis-keys";
26
27 @Autowired
28 private DiagnosisKeyService diagnosisKeyService;
29
30 @Autowired
31 private TanVerifier tanVerifier;
32
33 @PostMapping(SUBMISSION_ROUTE)
34 public ResponseEntity<Void> submitDiagnosisKey(
35 @RequestBody SubmissionPayload exposureKeys,
36 @RequestHeader(value = "cwa-fake") Integer fake,
37 @RequestHeader(value = "cwa-authorization") String tan) {
38 if (fake != 0) {
39 return buildSuccessResponseEntity();
40 }
41 if (!this.tanVerifier.verifyTan(tan)) {
42 return buildTanInvalidResponseEntity();
43 }
44
45 persistDiagnosisKeysPayload(exposureKeys);
46
47 return buildSuccessResponseEntity();
48 }
49
50 /**
51 * Returns a response that indicates that an invalid TAN was specified in the request.
52 */
53 private ResponseEntity<Void> buildTanInvalidResponseEntity() {
54 return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
55 }
56
57 /**
58 * Returns a response that indicates successful request processing.
59 */
60 private ResponseEntity<Void> buildSuccessResponseEntity() {
61 return ResponseEntity.ok().build();
62 }
63
64 /**
65 * Persists the diagnosis keys contained in the specified request payload.
66 *
67 * @param protoBufDiagnosisKeys Diagnosis keys that were specified in the request.
68 * @throws IllegalArgumentException in case the given collection contains {@literal null}.
69 */
70 private void persistDiagnosisKeysPayload(SubmissionPayload protoBufDiagnosisKeys) {
71 Collection<DiagnosisKey> diagnosisKeys = protoBufDiagnosisKeys.getKeysList().stream()
72 .map(aProtoBufKey -> DiagnosisKey.builder().fromProtoBuf(aProtoBufKey).build())
73 .collect(Collectors.toList());
74
75 this.diagnosisKeyService.saveDiagnosisKeys(diagnosisKeys);
76 }
77 }
78
[end of services/submission/src/main/java/app/coronawarn/server/services/submission/controller/SubmissionController.java]
[start of services/submission/src/main/resources/application.properties]
1 logging.level.org.springframework.web=INFO
2
3 spring.flyway.locations=classpath:db/migration/h2
4 spring.flyway.enabled=true
5 spring.jpa.hibernate.ddl-auto=validate
6
[end of services/submission/src/main/resources/application.properties]
</code>
Here is an example of a patch file. It consists of changes to the code base. It specifies the file names, the line numbers of each change, and the removed and added lines. A single patch file can contain changes to multiple files.
<patch>
--- a/file.py
+++ b/file.py
@@ -1,27 +1,35 @@
def euclidean(a, b):
- while b:
- a, b = b, a % b
- return a
+ if b == 0:
+ return a
+ return euclidean(b, a % b)
def bresenham(x0, y0, x1, y1):
points = []
dx = abs(x1 - x0)
dy = abs(y1 - y0)
- sx = 1 if x0 < x1 else -1
- sy = 1 if y0 < y1 else -1
- err = dx - dy
+ x, y = x0, y0
+ sx = -1 if x0 > x1 else 1
+ sy = -1 if y0 > y1 else 1
- while True:
- points.append((x0, y0))
- if x0 == x1 and y0 == y1:
- break
- e2 = 2 * err
- if e2 > -dy:
+ if dx > dy:
+ err = dx / 2.0
+ while x != x1:
+ points.append((x, y))
err -= dy
- x0 += sx
- if e2 < dx:
- err += dx
- y0 += sy
+ if err < 0:
+ y += sy
+ err += dx
+ x += sx
+ else:
+ err = dy / 2.0
+ while y != y1:
+ points.append((x, y))
+ err -= dx
+ if err < 0:
+ x += sx
+ err += dy
+ y += sy
+ points.append((x, y))
return points
</patch>
I need you to solve the provded issue by generating a single patch file that I can apply directly to this repository using git apply. Please respond with a single patch file in the format shown above.
Respond below:
| corona-warn-app/cwa-server | 8655863c4c989c437ad9b5ef84c7e2afb699be8d | Submission Service: Enable waiting for Fake Requests
When fake requests are send to the submission service, ensure that the duration of the fake requests take as long as normal requests, so attackers sniffing the traffic are unable to distinguish between fake/normal requests.
| 2020-05-17T13:49:18 | <patch>
diff --git a/services/submission/pom.xml b/services/submission/pom.xml
--- a/services/submission/pom.xml
+++ b/services/submission/pom.xml
@@ -22,6 +22,12 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
+ <dependency>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-math3</artifactId>
+ <version>3.2</version>
+ <scope>compile</scope>
+ </dependency>
</dependencies>
</project>
\ No newline at end of file
diff --git a/services/submission/src/main/java/app/coronawarn/server/services/submission/controller/SubmissionController.java b/services/submission/src/main/java/app/coronawarn/server/services/submission/controller/SubmissionController.java
--- a/services/submission/src/main/java/app/coronawarn/server/services/submission/controller/SubmissionController.java
+++ b/services/submission/src/main/java/app/coronawarn/server/services/submission/controller/SubmissionController.java
@@ -5,15 +5,23 @@
import app.coronawarn.server.common.protocols.internal.SubmissionPayload;
import app.coronawarn.server.services.submission.verification.TanVerifier;
import java.util.Collection;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ForkJoinPool;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
+import org.apache.commons.math3.distribution.PoissonDistribution;
import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
+import org.springframework.util.StopWatch;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.context.request.async.DeferredResult;
@RestController
@RequestMapping("/version/v1")
@@ -24,27 +32,57 @@ public class SubmissionController {
*/
public static final String SUBMISSION_ROUTE = "/diagnosis-keys";
+ @Value("${services.submission.fake_delay_moving_average_samples}")
+ private Double fakeDelayMovingAverageSamples;
+
+ // Exponential moving average of the last N real request durations (in ms), where
+ // N = fakeDelayMovingAverageSamples.
+ @Value("${services.submission.initial_fake_delay_milliseconds}")
+ private Double fakeDelay;
+
@Autowired
private DiagnosisKeyService diagnosisKeyService;
@Autowired
private TanVerifier tanVerifier;
+ private ScheduledExecutorService scheduledExecutor = Executors.newSingleThreadScheduledExecutor();
+ private ForkJoinPool forkJoinPool = ForkJoinPool.commonPool();
+
@PostMapping(SUBMISSION_ROUTE)
- public ResponseEntity<Void> submitDiagnosisKey(
+ public DeferredResult<ResponseEntity<Void>> submitDiagnosisKey(
@RequestBody SubmissionPayload exposureKeys,
@RequestHeader(value = "cwa-fake") Integer fake,
@RequestHeader(value = "cwa-authorization") String tan) {
+ final DeferredResult<ResponseEntity<Void>> deferredResult = new DeferredResult<>();
if (fake != 0) {
- return buildSuccessResponseEntity();
- }
- if (!this.tanVerifier.verifyTan(tan)) {
- return buildTanInvalidResponseEntity();
+ setFakeDeferredResult(deferredResult);
+ } else {
+ setRealDeferredResult(deferredResult, exposureKeys, tan);
}
+ return deferredResult;
+ }
- persistDiagnosisKeysPayload(exposureKeys);
+ private void setFakeDeferredResult(DeferredResult<ResponseEntity<Void>> deferredResult) {
+ long delay = new PoissonDistribution(fakeDelay).sample();
+ scheduledExecutor.schedule(() -> deferredResult.setResult(buildSuccessResponseEntity()),
+ delay, TimeUnit.MILLISECONDS);
+ }
- return buildSuccessResponseEntity();
+ private void setRealDeferredResult(DeferredResult<ResponseEntity<Void>> deferredResult,
+ SubmissionPayload exposureKeys, String tan) {
+ forkJoinPool.submit(() -> {
+ StopWatch stopWatch = new StopWatch();
+ stopWatch.start();
+ if (!this.tanVerifier.verifyTan(tan)) {
+ deferredResult.setResult(buildTanInvalidResponseEntity());
+ } else {
+ persistDiagnosisKeysPayload(exposureKeys);
+ deferredResult.setResult(buildSuccessResponseEntity());
+ }
+ stopWatch.stop();
+ updateFakeDelay(stopWatch.getTotalTimeMillis());
+ });
}
/**
@@ -74,4 +112,8 @@ private void persistDiagnosisKeysPayload(SubmissionPayload protoBufDiagnosisKeys
this.diagnosisKeyService.saveDiagnosisKeys(diagnosisKeys);
}
+
+ private synchronized void updateFakeDelay(long realRequestDuration) {
+ fakeDelay = fakeDelay + (1 / fakeDelayMovingAverageSamples) * (realRequestDuration - fakeDelay);
+ }
}
diff --git a/services/submission/src/main/resources/application.properties b/services/submission/src/main/resources/application.properties
--- a/services/submission/src/main/resources/application.properties
+++ b/services/submission/src/main/resources/application.properties
@@ -1,5 +1,10 @@
logging.level.org.springframework.web=INFO
+# The initial value of the moving average for fake request delays.
+services.submission.initial_fake_delay_milliseconds=10
+# The number of samples for the calculation of the moving average for fake request delays.
+services.submission.fake_delay_moving_average_samples=10
+
spring.flyway.locations=classpath:db/migration/h2
spring.flyway.enabled=true
spring.jpa.hibernate.ddl-auto=validate
</patch> | diff --git a/services/submission/src/test/resources/application.properties b/services/submission/src/test/resources/application.properties
--- a/services/submission/src/test/resources/application.properties
+++ b/services/submission/src/test/resources/application.properties
@@ -3,4 +3,7 @@ logging.level.org.springframework=off
logging.level.root=off
spring.main.banner-mode=off
+services.submission.initial_fake_delay_milliseconds=1
+services.submission.fake_delay_moving_average_samples=1
+
spring.flyway.enabled=false
| |||||
corona-warn-app__cwa-server-45 | You will be provided with a partial code base and an issue statement explaining a problem to resolve.
<issue>
Diagnosis key submission unit tests
Implement unit tests for the diagnosis key submission service according to best practices.
</issue>
<code>
[start of README.md]
1 # cwa-server
2
3 # API
4 ## Distribution
5 ### Postman
6 https://documenter.getpostman.com/view/5099981/Szmb8Lcd?version=latest
7 ### OpenAPI
8 https://github.com/corona-warn-app/cwa-server/blob/master/services/distribution/api_v1.json
9 # Deployments
10 ## Distribution Server Mock
11 http://download-mock-ena-server.apps.p006.otc.mcs-paas.io/version/
12
[end of README.md]
[start of common/persistence/src/main/java/app/coronawarn/server/services/common/persistence/service/DiagnosisKeyService.java]
1 package app.coronawarn.server.services.common.persistence.service;
2
3 import java.util.Collection;
4 import app.coronawarn.server.services.common.persistence.domain.DiagnosisKey;
5 import app.coronawarn.server.services.common.persistence.repository.DiagnosisKeyRepository;
6 import org.springframework.beans.factory.annotation.Autowired;
7 import org.springframework.stereotype.Component;
8
9 @Component
10 public class DiagnosisKeyService {
11
12 @Autowired
13 private DiagnosisKeyRepository keyRepository;
14
15 /**
16 * Persists the specified collection of {@link DiagnosisKey} instances. Use the returned
17 * collection for further operations as the saveDiagnosisKeys operation might have changed the
18 * {@link DiagnosisKey} instances completely.
19 *
20 * @param diagnosisKeys must not contain {@literal null}.
21 * @return a collection of the saved keys; will never contain {@literal null}.
22 * @throws IllegalArgumentException in case the given collection contains {@literal null}.
23 */
24 public Collection<DiagnosisKey> saveDiagnosisKeys(
25 Collection<DiagnosisKey> diagnosisKeys) {
26 return keyRepository.saveAll(diagnosisKeys);
27 }
28 }
29
[end of common/persistence/src/main/java/app/coronawarn/server/services/common/persistence/service/DiagnosisKeyService.java]
[start of services/submission/src/main/java/app/coronawarn/server/services/submission/controller/SubmissionController.java]
1 package app.coronawarn.server.services.submission.controller;
2
3 import java.util.Collection;
4 import java.util.Collections;
5 import java.util.stream.Collectors;
6 import app.coronawarn.server.common.protocols.generated.ExposureKeys.TemporaryExposureKey;
7 import app.coronawarn.server.services.common.persistence.domain.DiagnosisKey;
8 import app.coronawarn.server.services.common.persistence.service.DiagnosisKeyService;
9 import app.coronawarn.server.services.submission.verification.TanVerifier;
10 import org.springframework.beans.factory.annotation.Autowired;
11 import org.springframework.http.ResponseEntity;
12 import org.springframework.web.bind.annotation.GetMapping;
13 import org.springframework.web.bind.annotation.PathVariable;
14 import org.springframework.web.bind.annotation.PostMapping;
15 import org.springframework.web.bind.annotation.RequestBody;
16 import org.springframework.web.bind.annotation.RequestHeader;
17 import org.springframework.web.bind.annotation.RequestMapping;
18 import org.springframework.web.bind.annotation.RestController;
19
20 // TODO Implement Unit Tests
21 @RestController
22 @RequestMapping("/version/v1")
23 public class SubmissionController {
24
25 @Autowired
26 private DiagnosisKeyService exposureKeyService;
27
28 @Autowired
29 private TanVerifier tanVerifier;
30
31 @GetMapping(value = "")
32 public ResponseEntity<String> hello() {
33 return ResponseEntity.ok().body("Diagnosis Key Submission Endpoint v1");
34 }
35
36 // TODO update protoSpec and endpoint to Collection<TemporaryExposureKey>
37 @PostMapping(value = "/diagnosis-keys/country/{country}")
38 public ResponseEntity<String> submitDiagnosisKey(
39 @PathVariable String country,
40 @RequestBody TemporaryExposureKey exposureKeys,
41 @RequestHeader(value = "cwa-fake") Integer fake,
42 @RequestHeader(value = "cwa-authorization") String tan) {
43 if (fake != 0) {
44 //TODO consider sleep or similar
45 return buildSuccessResponseEntity();
46 }
47 if (!this.tanVerifier.verifyTan(tan)) {
48 return buildTanInvalidResponseEntity();
49 }
50
51 persistDiagnosisKeysPayload(Collections.singleton(exposureKeys));
52
53 return buildSuccessResponseEntity();
54 }
55
56 /**
57 * @return A response that indicates that an invalid TAN was specified in the request.
58 */
59 private ResponseEntity<String> buildTanInvalidResponseEntity() {
60 // TODO implement
61 return null;
62 }
63
64 /**
65 * @return A response that indicates successful request processing.
66 */
67 private ResponseEntity<String> buildSuccessResponseEntity() {
68 return ResponseEntity.ok().build();
69 }
70
71 /**
72 * Persists the diagnosis keys contained in the specified request payload.
73 *
74 * @param protoBufDiagnosisKeys Diagnosis keys that were specified in the request.
75 * @throws IllegalArgumentException in case the given collection contains {@literal null}.
76 */
77 private void persistDiagnosisKeysPayload(
78 Collection<TemporaryExposureKey> protoBufDiagnosisKeys) {
79 Collection<DiagnosisKey> diagnosisKeys = protoBufDiagnosisKeys.stream()
80 .map(aProtoBufKey -> DiagnosisKey.builder().fromProtoBuf(aProtoBufKey).build())
81 .collect(Collectors.toList());
82
83 this.exposureKeyService.saveDiagnosisKeys(diagnosisKeys);
84 }
85 }
86
[end of services/submission/src/main/java/app/coronawarn/server/services/submission/controller/SubmissionController.java]
[start of services/submission/src/main/resources/application.properties]
1 logging.level.org.springframework.web=DEBUG
2 spring.jpa.hibernate.ddl-auto = create
3 spring.flyway.enabled=false
4
[end of services/submission/src/main/resources/application.properties]
</code>
Here is an example of a patch file. It consists of changes to the code base. It specifies the file names, the line numbers of each change, and the removed and added lines. A single patch file can contain changes to multiple files.
<patch>
--- a/file.py
+++ b/file.py
@@ -1,27 +1,35 @@
def euclidean(a, b):
- while b:
- a, b = b, a % b
- return a
+ if b == 0:
+ return a
+ return euclidean(b, a % b)
def bresenham(x0, y0, x1, y1):
points = []
dx = abs(x1 - x0)
dy = abs(y1 - y0)
- sx = 1 if x0 < x1 else -1
- sy = 1 if y0 < y1 else -1
- err = dx - dy
+ x, y = x0, y0
+ sx = -1 if x0 > x1 else 1
+ sy = -1 if y0 > y1 else 1
- while True:
- points.append((x0, y0))
- if x0 == x1 and y0 == y1:
- break
- e2 = 2 * err
- if e2 > -dy:
+ if dx > dy:
+ err = dx / 2.0
+ while x != x1:
+ points.append((x, y))
err -= dy
- x0 += sx
- if e2 < dx:
- err += dx
- y0 += sy
+ if err < 0:
+ y += sy
+ err += dx
+ x += sx
+ else:
+ err = dy / 2.0
+ while y != y1:
+ points.append((x, y))
+ err -= dx
+ if err < 0:
+ x += sx
+ err += dy
+ y += sy
+ points.append((x, y))
return points
</patch>
I need you to solve the provded issue by generating a single patch file that I can apply directly to this repository using git apply. Please respond with a single patch file in the format shown above.
Respond below:
| corona-warn-app/cwa-server | e8ca246da1ab3620b6340383d4a59fe2041af562 | Diagnosis key submission unit tests
Implement unit tests for the diagnosis key submission service according to best practices.
| 2020-05-08T09:00:07 | <patch>
diff --git a/common/persistence/src/main/java/app/coronawarn/server/services/common/persistence/service/DiagnosisKeyService.java b/common/persistence/src/main/java/app/coronawarn/server/services/common/persistence/service/DiagnosisKeyService.java
--- a/common/persistence/src/main/java/app/coronawarn/server/services/common/persistence/service/DiagnosisKeyService.java
+++ b/common/persistence/src/main/java/app/coronawarn/server/services/common/persistence/service/DiagnosisKeyService.java
@@ -13,16 +13,12 @@ public class DiagnosisKeyService {
private DiagnosisKeyRepository keyRepository;
/**
- * Persists the specified collection of {@link DiagnosisKey} instances. Use the returned
- * collection for further operations as the saveDiagnosisKeys operation might have changed the
- * {@link DiagnosisKey} instances completely.
+ * Persists the specified collection of {@link DiagnosisKey} instances.
*
* @param diagnosisKeys must not contain {@literal null}.
- * @return a collection of the saved keys; will never contain {@literal null}.
* @throws IllegalArgumentException in case the given collection contains {@literal null}.
*/
- public Collection<DiagnosisKey> saveDiagnosisKeys(
- Collection<DiagnosisKey> diagnosisKeys) {
- return keyRepository.saveAll(diagnosisKeys);
+ public void saveDiagnosisKeys(Collection<DiagnosisKey> diagnosisKeys) {
+ keyRepository.saveAll(diagnosisKeys);
}
}
diff --git a/services/submission/src/main/java/app/coronawarn/server/services/submission/controller/SubmissionController.java b/services/submission/src/main/java/app/coronawarn/server/services/submission/controller/SubmissionController.java
--- a/services/submission/src/main/java/app/coronawarn/server/services/submission/controller/SubmissionController.java
+++ b/services/submission/src/main/java/app/coronawarn/server/services/submission/controller/SubmissionController.java
@@ -1,23 +1,22 @@
package app.coronawarn.server.services.submission.controller;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.stream.Collectors;
import app.coronawarn.server.common.protocols.generated.ExposureKeys.TemporaryExposureKey;
import app.coronawarn.server.services.common.persistence.domain.DiagnosisKey;
import app.coronawarn.server.services.common.persistence.service.DiagnosisKeyService;
import app.coronawarn.server.services.submission.verification.TanVerifier;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
-import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
-// TODO Implement Unit Tests
@RestController
@RequestMapping("/version/v1")
public class SubmissionController {
@@ -34,9 +33,8 @@ public ResponseEntity<String> hello() {
}
// TODO update protoSpec and endpoint to Collection<TemporaryExposureKey>
- @PostMapping(value = "/diagnosis-keys/country/{country}")
- public ResponseEntity<String> submitDiagnosisKey(
- @PathVariable String country,
+ @PostMapping(value = "/diagnosis-keys")
+ public ResponseEntity<Void> submitDiagnosisKey(
@RequestBody TemporaryExposureKey exposureKeys,
@RequestHeader(value = "cwa-fake") Integer fake,
@RequestHeader(value = "cwa-authorization") String tan) {
@@ -56,15 +54,14 @@ public ResponseEntity<String> submitDiagnosisKey(
/**
* @return A response that indicates that an invalid TAN was specified in the request.
*/
- private ResponseEntity<String> buildTanInvalidResponseEntity() {
- // TODO implement
- return null;
+ private ResponseEntity<Void> buildTanInvalidResponseEntity() {
+ return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
}
/**
* @return A response that indicates successful request processing.
*/
- private ResponseEntity<String> buildSuccessResponseEntity() {
+ private ResponseEntity<Void> buildSuccessResponseEntity() {
return ResponseEntity.ok().build();
}
diff --git a/services/submission/src/main/resources/application.properties b/services/submission/src/main/resources/application.properties
--- a/services/submission/src/main/resources/application.properties
+++ b/services/submission/src/main/resources/application.properties
@@ -1,3 +1,3 @@
logging.level.org.springframework.web=DEBUG
-spring.jpa.hibernate.ddl-auto = create
+spring.jpa.hibernate.ddl-auto=create
spring.flyway.enabled=false
</patch> | diff --git a/services/distribution/src/test/resources/application.properties b/services/distribution/src/test/resources/application.properties
--- a/services/distribution/src/test/resources/application.properties
+++ b/services/distribution/src/test/resources/application.properties
@@ -1,5 +1,4 @@
-spring.datasource.driver-class-name=org.hsqldb.jdbc.JDBCDriver
-spring.datasource.url=jdbc:hsqldb:mem:testdb;DB_CLOSE_DELAY=-1
-spring.datasource.username=cwa
-spring.datasource.password=cwa
-spring.jpa.hibernate.ddl-auto=create
\ No newline at end of file
+spring.jpa.hibernate.ddl-auto=create
+logging.level.org.springframework=off
+logging.level.root=warn
+spring.main.banner-mode=off
diff --git a/services/distribution/src/test/resources/logback-test.xml b/services/distribution/src/test/resources/logback-test.xml
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/test/resources/logback-test.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<configuration>
+ <include resource="org/springframework/boot/logging/logback/base.xml" />
+ <logger name="org.springframework" level="off"/>
+</configuration>
diff --git a/services/submission/src/test/java/app/coronawarn/server/services/submission/ServerApplicationTests.java b/services/submission/src/test/java/app/coronawarn/server/services/submission/ServerApplicationTests.java
--- a/services/submission/src/test/java/app/coronawarn/server/services/submission/ServerApplicationTests.java
+++ b/services/submission/src/test/java/app/coronawarn/server/services/submission/ServerApplicationTests.java
@@ -1,13 +1,20 @@
package app.coronawarn.server.services.submission;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+
+import app.coronawarn.server.services.submission.controller.SubmissionController;
import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class ServerApplicationTests {
- @Test
- void contextLoads() {
- }
+ @Autowired
+ private SubmissionController controller;
+ @Test
+ public void contextLoads() {
+ assertNotNull(this.controller);
+ }
}
diff --git a/services/submission/src/test/java/app/coronawarn/server/services/submission/controller/SubmissionControllerTest.java b/services/submission/src/test/java/app/coronawarn/server/services/submission/controller/SubmissionControllerTest.java
new file mode 100644
--- /dev/null
+++ b/services/submission/src/test/java/app/coronawarn/server/services/submission/controller/SubmissionControllerTest.java
@@ -0,0 +1,159 @@
+package app.coronawarn.server.services.submission.controller;
+
+
+import static app.coronawarn.server.common.protocols.generated.ExposureKeys.TemporaryExposureKey;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.mockito.Mockito.any;
+import static org.mockito.Mockito.anyCollection;
+import static org.mockito.Mockito.anyString;
+import static org.mockito.Mockito.atLeastOnce;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import app.coronawarn.server.services.common.persistence.service.DiagnosisKeyService;
+import app.coronawarn.server.services.submission.verification.TanVerifier;
+import com.google.protobuf.ByteString;
+import java.net.URI;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.test.mock.mockito.MockBean;
+import org.springframework.boot.test.web.client.TestRestTemplate;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.HttpMethod;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.MediaType;
+import org.springframework.http.RequestEntity;
+import org.springframework.http.ResponseEntity;
+
+@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
+public class SubmissionControllerTest {
+
+ private static final URI SUBMISSION_URL = URI.create("/version/v1/diagnosis-keys");
+
+ @MockBean
+ private DiagnosisKeyService diagnosisKeyService;
+
+ @MockBean
+ private TanVerifier tanVerifier;
+
+ @Autowired
+ private TestRestTemplate testRestTemplate;
+
+ @BeforeEach
+ public void setUpMocks() {
+ when(tanVerifier.verifyTan(anyString())).thenReturn(true);
+ }
+
+ @Test
+ public void checkResponseStatusForValidParameters() {
+ ResponseEntity<Void> actResponse =
+ executeRequest(buildTemporaryExposureKey(), buildOkHeaders());
+
+ assertEquals(HttpStatus.OK, actResponse.getStatusCode());
+ }
+
+ @Test
+ public void checkSaveOperationCallForValidParameters() {
+ executeRequest(buildTemporaryExposureKey(), buildOkHeaders());
+
+ verify(diagnosisKeyService, atLeastOnce()).saveDiagnosisKeys(anyCollection());
+ }
+
+ @ParameterizedTest
+ @MethodSource("createIncompleteHeaders")
+ public void badRequestIfCwaHeadersMissing(HttpHeaders headers) {
+ ResponseEntity<Void> actResponse = executeRequest(buildTemporaryExposureKey(), headers);
+
+ verify(diagnosisKeyService, never()).saveDiagnosisKeys(any());
+ assertEquals(HttpStatus.BAD_REQUEST, actResponse.getStatusCode());
+ }
+
+ private static Stream<Arguments> createIncompleteHeaders() {
+ return Stream.of(
+ Arguments.of(setContentTypeProtoBufHeader(new HttpHeaders())),
+ Arguments.of(setContentTypeProtoBufHeader(setCwaFakeHeader(new HttpHeaders(), "0"))),
+ Arguments.of(setContentTypeProtoBufHeader(setCwaAuthHeader(new HttpHeaders()))));
+ }
+
+ @Test
+ public void checkAcceptedHttpMethods() {
+ Set<HttpMethod> expAllowedMethods =
+ Stream.of(HttpMethod.POST, HttpMethod.OPTIONS)
+ .collect(Collectors.toCollection(HashSet::new));
+
+ Set<HttpMethod> actAllowedMethods = testRestTemplate.optionsForAllow(SUBMISSION_URL.toString());
+
+ assertEquals(expAllowedMethods, actAllowedMethods);
+ }
+
+ @Test
+ public void invalidTanHandling() {
+ when(tanVerifier.verifyTan(anyString())).thenReturn(false);
+
+ ResponseEntity<Void> actResponse =
+ executeRequest(buildTemporaryExposureKey(), buildOkHeaders());
+
+ verify(diagnosisKeyService, never()).saveDiagnosisKeys(any());
+ assertEquals(HttpStatus.FORBIDDEN, actResponse.getStatusCode());
+ }
+
+ @Test
+ public void fakeRequestHandling() {
+ HttpHeaders headers = buildOkHeaders();
+ setCwaFakeHeader(headers, "1");
+
+ ResponseEntity<Void> actResponse = executeRequest(buildTemporaryExposureKey(), headers);
+
+ verify(diagnosisKeyService, never()).saveDiagnosisKeys(any());
+ assertEquals(HttpStatus.OK, actResponse.getStatusCode());
+ }
+
+ private static HttpHeaders buildOkHeaders() {
+ HttpHeaders headers = setCwaAuthHeader(setContentTypeProtoBufHeader(new HttpHeaders()));
+
+ return setCwaFakeHeader(headers, "0");
+ }
+
+ private static HttpHeaders setContentTypeProtoBufHeader(HttpHeaders headers) {
+ headers.setContentType(MediaType.valueOf("application/x-protobuf"));
+ return headers;
+ }
+
+ private static HttpHeaders setCwaAuthHeader(HttpHeaders headers) {
+ headers.set("cwa-authorization", "okTan");
+ return headers;
+ }
+
+ private static HttpHeaders setCwaFakeHeader(HttpHeaders headers, String value) {
+ headers.set("cwa-fake", value);
+ return headers;
+ }
+
+ private static TemporaryExposureKey buildTemporaryExposureKey() {
+ return buildTemporaryExposureKey("testKey123456789", 3L, 2);
+ }
+
+ private static TemporaryExposureKey buildTemporaryExposureKey(
+ String keyData, long rollingStartNumber, int riskLevelValue) {
+ return TemporaryExposureKey.newBuilder()
+ .setKeyData(ByteString.copyFromUtf8(keyData))
+ .setRollingStartNumber(rollingStartNumber)
+ .setRiskLevelValue(riskLevelValue).build();
+ }
+
+ private ResponseEntity<Void> executeRequest(TemporaryExposureKey body, HttpHeaders headers) {
+ RequestEntity<TemporaryExposureKey> request =
+ new RequestEntity<>(body, headers, HttpMethod.POST, SUBMISSION_URL);
+ return testRestTemplate.postForEntity(SUBMISSION_URL, request, Void.class);
+ }
+}
diff --git a/services/submission/src/test/resources/application.properties b/services/submission/src/test/resources/application.properties
--- a/services/submission/src/test/resources/application.properties
+++ b/services/submission/src/test/resources/application.properties
@@ -1,5 +1,4 @@
-spring.datasource.driver-class-name=org.hsqldb.jdbc.JDBCDriver
-spring.datasource.url=jdbc:hsqldb:mem:testdb;DB_CLOSE_DELAY=-1
-spring.datasource.username=cwa
-spring.datasource.password=cwa
-spring.jpa.hibernate.ddl-auto=create
\ No newline at end of file
+spring.jpa.hibernate.ddl-auto=create
+logging.level.org.springframework=off
+logging.level.root=warn
+spring.main.banner-mode=off
diff --git a/services/submission/src/test/resources/logback-test.xml b/services/submission/src/test/resources/logback-test.xml
new file mode 100644
--- /dev/null
+++ b/services/submission/src/test/resources/logback-test.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<configuration>
+ <include resource="org/springframework/boot/logging/logback/base.xml" />
+ <logger name="org.springframework" level="off"/>
+</configuration>
| |||||
corona-warn-app__cwa-server-386 | You will be provided with a partial code base and an issue statement explaining a problem to resolve.
<issue>
TEK Exports should not contain any keys which recently expired
Currently the system also packages keys, which expired recently. Instead, only keys which have been expired since at least 2 hours should be part of the export.
Can also be a nice prework for https://github.com/corona-warn-app/cwa-server/issues/108.
Probably should change this already when the diagnosis keys are queried for distribution:
https://github.com/corona-warn-app/cwa-server/blob/master/common/persistence/src/main/java/app/coronawarn/server/common/persistence/service/DiagnosisKeyService.java#L64
</issue>
<code>
[start of README.md]
1 <!-- markdownlint-disable MD041 -->
2 <h1 align="center">
3 Corona-Warn-App Server
4 </h1>
5
6 <p align="center">
7 <a href="https://github.com/corona-warn-app/cwa-server/commits/" title="Last Commit"><img src="https://img.shields.io/github/last-commit/corona-warn-app/cwa-server?style=flat"></a>
8 <a href="https://github.com/corona-warn-app/cwa-server/issues" title="Open Issues"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat"></a>
9 <a href="https://circleci.com/gh/corona-warn-app/cwa-server" title="Build Status"><img src="https://circleci.com/gh/corona-warn-app/cwa-server.svg?style=shield&circle-token=4ab059989d10709df19eb4b98ab7c121a25e981a"></a>
10 <a href="https://sonarcloud.io/dashboard?id=corona-warn-app_cwa-server" title="Quality Gate"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=alert_status"></a>
11 <a href="https://sonarcloud.io/component_measures?id=corona-warn-app_cwa-server&metric=Coverage&view=list" title="Coverage"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=coverage"></a>
12 <a href="https://github.com/corona-warn-app/cwa-server/blob/master/LICENSE" title="License"><img src="https://img.shields.io/badge/License-Apache%202.0-green.svg?style=flat"></a>
13 </p>
14
15 <p align="center">
16 <a href="#development">Development</a> •
17 <a href="#service-apis">Service APIs</a> •
18 <a href="#documentation">Documentation</a> •
19 <a href="#support-and-feedback">Support</a> •
20 <a href="#how-to-contribute">Contribute</a> •
21 <a href="#contributors">Contributors</a> •
22 <a href="#repositories">Repositories</a> •
23 <a href="#licensing">Licensing</a>
24 </p>
25
26 The goal of this project is to develop the official Corona-Warn-App for Germany based on the exposure notification API from [Apple](https://www.apple.com/covid19/contacttracing/) and [Google](https://www.google.com/covid19/exposurenotifications/). The apps (for both iOS and Android) use Bluetooth technology to exchange anonymous encrypted data with other mobile phones (on which the app is also installed) in the vicinity of an app user's phone. The data is stored locally on each user's device, preventing authorities or other parties from accessing or controlling the data. This repository contains the **implementation of the server for encryption keys** for the Corona-Warn-App. This implementation is still a **work in progress**, and the code it contains is currently alpha-quality code.
27
28 In this documentation, Corona-Warn-App services are also referred to as CWA services.
29
30 ## Architecture Overview
31
32 You can find the architecture overview [here](/docs/architecture-overview.md), which will give you
33 a good starting point in how the backend services interact with other services, and what purpose
34 they serve.
35
36 ## Development
37
38 After you've checked out this repository, you can run the application in one of the following ways:
39
40 * As a [Docker](https://www.docker.com/)-based deployment on your local machine. You can run either:
41 * Single components using the respective Dockerfile or
42 * The full backend using the Docker Compose (which is considered the most convenient way)
43 * As a [Maven](https://maven.apache.org)-based build on your local machine.
44 If you want to develop something in a single component, this approach is preferable.
45
46 ### Docker-Based Deployment
47
48 If you want to use Docker-based deployment, you need to install Docker on your local machine. For more information about downloading and installing Docker, see the [official Docker documentation](https://docs.docker.com/get-docker/).
49
50 #### Running the Full CWA Backend Using Docker Compose
51
52 For your convenience, a full setup including the generation of test data has been prepared using [Docker Compose](https://docs.docker.com/compose/reference/overview/). To build the backend services, run ```docker-compose build``` in the repository's root directory. A default configuration file can be found under ```.env```in the root folder of the repository. The default values for the local Postgres and Zenko Cloudserver should be changed in this file before docker-compose is run.
53
54 Once the services are built, you can start the whole backend using ```docker-compose up```.
55 The distribution service runs once and then finishes. If you want to trigger additional distribution runs, run ```docker-compose run distribution```.
56
57 The docker-compose contains the following services:
58
59 Service | Description | Endpoint and Default Credentials
60 ------------------|-------------|-----------
61 submission | The Corona-Warn-App submission service | `http://localhost:8000` <br> `http://localhost:8006` (for actuator endpoint)
62 distribution | The Corona-Warn-App distribution service | NO ENDPOINT
63 postgres | A [postgres] database installation | `postgres:8001` <br> Username: postgres <br> Password: postgres
64 pgadmin | A [pgadmin](https://www.pgadmin.org/) installation for the postgres database | `http://localhost:8002` <br> Username: [email protected] <br> Password: password
65 cloudserver | [Zenko CloudServer] is a S3-compliant object store | `http://localhost:8003/` <br> Access key: accessKey1 <br> Secret key: verySecretKey1
66 verification-fake | A very simple fake implementation for the tan verification. | `http://localhost:8004/version/v1/tan/verify` <br> The only valid tan is "edc07f08-a1aa-11ea-bb37-0242ac130002"
67
68 ##### Known Limitation
69
70 In rare cases the docker-compose runs into a timing issue if the distribution service starts before the bucket of the objectstore was created. This is not a big issue as you can simply run ```docker-compose run distribution``` to trigger additional distribution runs after the objectstore was initialized.
71
72 #### Running Single CWA Services Using Docker
73
74 If you would like to build and run a single CWA service, it's considered easiest to run them in a Docker environment. You can do this using the script provided in the respective CWA service directory. The Docker script first builds the CWA service and then creates an image for the runtime, which means that there are no additional dependencies for you to install.
75
76 To build and run the distribution service, run the following command:
77
78 ```bash
79 ./services/distribution/build_and_run.sh
80 ```
81
82 To build and run the submission service, run the following command:
83
84 ```bash
85 ./services/submission/build_and_run.sh
86 ```
87
88 The submission service is available on [localhost:8080](http://localhost:8080 ).
89
90 ### Maven-Based Build
91
92 If you want to actively develop in one of the CWA services, the Maven-based runtime is most suitable.
93 To prepare your machine to run the CWA project locally, we recommend that you first ensure that you've installed the following:
94
95 * Minimum JDK Version 11: [OpenJDK](https://openjdk.java.net/) / [SapMachine](https://sap.github.io/SapMachine/)
96 * [Maven 3.6](https://maven.apache.org/)
97 * [Postgres]
98 * [Zenko CloudServer]
99
100 #### Configure
101
102 After you made sure that the specified dependencies are running, configure them in the respective configuration files.
103
104 * Configure the Postgres connection in the [submission config](./services/submission/src/main/resources/application.yaml) and in the [distribution config](./services/distribution/src/main/resources/application.yaml)
105 * Configure the S3 compatible object storage in the [distribution config](./services/distribution/src/main/resources/application.yaml)
106 * Configure the private key for the distribution service, the path need to be prefixed with `file:`
107 * `VAULT_FILESIGNING_SECRET` should be the path to the private key, example available in `<repo-root>/docker-compose-test-secrets/private.pem`
108
109 #### Build
110
111 After you've checked out the repository, to build the project, run ```mvn install``` in your base directory.
112
113 #### Run
114
115 Navigate to the service you want to start and run the spring-boot:run target. The configured Postgres and the configured S3 compliant object storage are used as default. When you start the submission service, the endpoint is available on your local port 8080.
116
117 If you want to start the submission service, for example, you start it as follows:
118
119 ```bash
120 cd services/submission/
121 mvn spring-boot:run
122 ```
123
124 #### Debugging
125
126 To enable the `DEBUG` log level, you can run the application using the Spring `dev` profile.
127
128 ```bash
129 mvn spring-boot:run -Dspring-boot.run.profiles=dev
130 ```
131
132 To be able to set breakpoints (e.g. in IntelliJ), it may be necessary to use the ```-Dspring-boot.run.fork=false``` parameter.
133
134 ## Service APIs
135
136 The API that is being exposed by the backend services is documented in an [OpenAPI](https://www.openapis.org/) specification. The specification files are available at the following locations:
137
138 Service | OpenAPI Specification
139 -------------|-------------
140 Submission Service | [services/submission/api_v1.json](https://github.com/corona-warn-app/cwa-server/raw/master/services/submission/api_v1.json)
141 Distribution Service | [services/distribution/api_v1.json)](https://github.com/corona-warn-app/cwa-server/raw/master/services/distribution/api_v1.json)
142
143 ## Spring Profiles
144
145 ### Distribution
146
147 Profile | Effect
148 -------------|-------------
149 `dev` | Turns the log level to `DEBUG` and sets the app package ID in the export packages' signature info to `de.rki.coronawarnapp-dev` so that test certificates (instead of production certificates) will be used for client-side validation.
150 `cloud` | Removes default values for the `datasource` and `objectstore` configurations.
151 `demo` | Includes incomplete days and hours into the distribution run, thus creating aggregates for the current day and the current hour (and including both in the respective indices). When running multiple distributions in one hour with this profile, the date aggregate for today and the hours aggregate for the current hour will be updated and overwritten.
152 `testdata` | Causes test data to be inserted into the database before each distribution run. By default, around 1000 random diagnosis keys will be generated per hour. If there are no diagnosis keys in the database yet, random keys will be generated for every hour from the beginning of the retention period (14 days ago at 00:00 UTC) until one hour before the present hour. If there are already keys in the database, the random keys will be generated for every hour from the latest diagnosis key in the database (by submission timestamp) until one hour before the present hour (or none at all, if the latest diagnosis key in the database was submitted one hour ago or later).
153
154 ### Submission
155
156 Profile | Effect
157 -------------|-------------
158 `dev` | Turns the log level to `DEBUG`.
159 `cloud` | Removes default values for the `datasource` configuration.
160
161 ## Documentation
162
163 The full documentation for the Corona-Warn-App can be found in the [cwa-documentation](https://github.com/corona-warn-app/cwa-documentation) repository. The documentation repository contains technical documents, architecture information, and whitepapers related to this implementation.
164
165 ## Support and Feedback
166
167 The following channels are available for discussions, feedback, and support requests:
168
169 | Type | Channel |
170 | ------------------------ | ------------------------------------------------------ |
171 | **General Discussion** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="General Discussion"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/question.svg?style=flat-square"></a> </a> |
172 | **Concept Feedback** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="Open Concept Feedback"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/architecture.svg?style=flat-square"></a> |
173 | **Backend Issue** | <a href="https://github.com/corona-warn-app/cwa-server/issues/new/choose" title="Open Backend Issue"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat-square"></a> |
174 | **Other Requests** | <a href="mailto:[email protected]" title="Email CWA Team"><img src="https://img.shields.io/badge/email-CWA%20team-green?logo=mail.ru&style=flat-square&logoColor=white"></a> |
175
176 ## How to Contribute
177
178 Contribution and feedback are 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.
179
180 ## Contributors
181
182 The German government has asked SAP and Deutsche Telekom to develop the Corona-Warn-App for Germany as open source software. Deutsche Telekom is providing the network and mobile technology and will operate and run the backend for the app in a safe, scalable and stable manner. SAP is responsible for the app development, its framework and the underlying platform. Therefore, development teams of SAP and Deutsche Telekom are contributing to this project. At the same time 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.
183
184 ## Repositories
185
186 The following public repositories are currently available for the Corona-Warn-App:
187
188 | Repository | Description |
189 | ------------------- | --------------------------------------------------------------------- |
190 | [cwa-documentation] | Project overview, general documentation, and white papers |
191 | [cwa-server] | Backend implementation for the Apple/Google exposure notification API|
192 | [cwa-verification-server] | Backend implementation of the verification process|
193
194 [cwa-documentation]: https://github.com/corona-warn-app/cwa-documentation
195 [cwa-server]: https://github.com/corona-warn-app/cwa-server
196 [cwa-verification-server]: https://github.com/corona-warn-app/cwa-verification-server
197 [Postgres]: https://www.postgresql.org/
198 [HSQLDB]: http://hsqldb.org/
199 [Zenko CloudServer]: https://github.com/scality/cloudserver
200
201 ## Licensing
202
203 Copyright (c) 2020 SAP SE or an SAP affiliate company.
204
205 Licensed under the **Apache License, Version 2.0** (the "License"); you may not use this file except in compliance with the License.
206
207 You may obtain a copy of the License at <https://www.apache.org/licenses/LICENSE-2.0>.
208
209 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.
210
[end of README.md]
[start of /dev/null]
1
[end of /dev/null]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysHourDirectory.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.directory;
22
23 import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
24 import app.coronawarn.server.services.distribution.assembly.component.CryptoProvider;
25 import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.archive.decorator.singing.DiagnosisKeySigningDecorator;
26 import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.file.TemporaryExposureKeyExportFile;
27 import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.util.DateTime;
28 import app.coronawarn.server.services.distribution.assembly.structure.WritableOnDisk;
29 import app.coronawarn.server.services.distribution.assembly.structure.archive.Archive;
30 import app.coronawarn.server.services.distribution.assembly.structure.archive.ArchiveOnDisk;
31 import app.coronawarn.server.services.distribution.assembly.structure.directory.Directory;
32 import app.coronawarn.server.services.distribution.assembly.structure.directory.IndexDirectoryOnDisk;
33 import app.coronawarn.server.services.distribution.assembly.structure.file.File;
34 import app.coronawarn.server.services.distribution.assembly.structure.util.ImmutableStack;
35 import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
36 import java.time.LocalDate;
37 import java.time.LocalDateTime;
38 import java.time.ZoneOffset;
39 import java.util.Collection;
40 import java.util.Set;
41 import java.util.stream.Collectors;
42
43 public class DiagnosisKeysHourDirectory extends IndexDirectoryOnDisk<LocalDateTime> {
44
45 private final Collection<DiagnosisKey> diagnosisKeys;
46 private final CryptoProvider cryptoProvider;
47 private final DistributionServiceConfig distributionServiceConfig;
48
49 /**
50 * Constructs a {@link DiagnosisKeysHourDirectory} instance for the specified date.
51 *
52 * @param diagnosisKeys A collection of diagnosis keys. These will be filtered according to the specified current
53 * date.
54 * @param cryptoProvider The {@link CryptoProvider} used for cryptographic signing.
55 */
56 public DiagnosisKeysHourDirectory(Collection<DiagnosisKey> diagnosisKeys, CryptoProvider cryptoProvider,
57 DistributionServiceConfig distributionServiceConfig) {
58 super(distributionServiceConfig.getApi().getHourPath(),
59 indices -> DateTime.getHours(((LocalDate) indices.peek()), diagnosisKeys), LocalDateTime::getHour);
60 this.diagnosisKeys = diagnosisKeys;
61 this.cryptoProvider = cryptoProvider;
62 this.distributionServiceConfig = distributionServiceConfig;
63 }
64
65 @Override
66 public void prepare(ImmutableStack<Object> indices) {
67 this.addWritableToAll(currentIndices -> {
68 LocalDateTime currentHour = (LocalDateTime) currentIndices.peek();
69 // The LocalDateTime currentHour already contains both the date and the hour information, so
70 // we can throw away the LocalDate that's the second item on the stack from the "/date"
71 // IndexDirectory.
72 String region = (String) currentIndices.pop().pop().peek();
73
74 Set<DiagnosisKey> diagnosisKeysForCurrentHour = getDiagnosisKeysForHour(currentHour);
75
76 long startTimestamp = currentHour.toEpochSecond(ZoneOffset.UTC);
77 long endTimestamp = currentHour.plusHours(1).toEpochSecond(ZoneOffset.UTC);
78 File<WritableOnDisk> temporaryExposureKeyExportFile = TemporaryExposureKeyExportFile.fromDiagnosisKeys(
79 diagnosisKeysForCurrentHour, region, startTimestamp, endTimestamp, distributionServiceConfig);
80
81 Archive<WritableOnDisk> hourArchive = new ArchiveOnDisk(distributionServiceConfig.getOutputFileName());
82 hourArchive.addWritable(temporaryExposureKeyExportFile);
83
84 return decorateDiagnosisKeyArchive(hourArchive);
85 });
86 super.prepare(indices);
87 }
88
89 private Set<DiagnosisKey> getDiagnosisKeysForHour(LocalDateTime hour) {
90 return this.diagnosisKeys.stream()
91 .filter(diagnosisKey -> DateTime
92 .getLocalDateTimeFromHoursSinceEpoch(diagnosisKey.getSubmissionTimestamp())
93 .equals(hour))
94 .collect(Collectors.toSet());
95 }
96
97 private Directory<WritableOnDisk> decorateDiagnosisKeyArchive(Archive<WritableOnDisk> archive) {
98 return new DiagnosisKeySigningDecorator(archive, cryptoProvider, distributionServiceConfig);
99 }
100 }
101
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysHourDirectory.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/util/DateTime.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.distribution.assembly.diagnosiskeys.util;
22
23 import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
24 import java.time.LocalDate;
25 import java.time.LocalDateTime;
26 import java.time.ZoneOffset;
27 import java.util.Collection;
28 import java.util.Set;
29 import java.util.concurrent.TimeUnit;
30 import java.util.stream.Collectors;
31
32 /**
33 * Methods for conversions of time/date data.
34 */
35 public class DateTime {
36
37 private DateTime() {
38 }
39
40 /**
41 * Returns a set of all {@link LocalDate dates} that are associated with the submission timestamps of the specified
42 * {@link DiagnosisKey diagnosis keys}.
43 */
44 public static Set<LocalDate> getDates(Collection<DiagnosisKey> diagnosisKeys) {
45 return diagnosisKeys.stream()
46 .map(DiagnosisKey::getSubmissionTimestamp)
47 .map(timestamp -> LocalDate.ofEpochDay(timestamp / 24))
48 .collect(Collectors.toSet());
49 }
50
51 /**
52 * Returns a set of all {@link LocalDateTime hours} that are associated with the submission timestamps of the
53 * specified {@link DiagnosisKey diagnosis keys} and the specified {@link LocalDate date}.
54 */
55 public static Set<LocalDateTime> getHours(LocalDate currentDate, Collection<DiagnosisKey> diagnosisKeys) {
56 return diagnosisKeys.stream()
57 .map(DiagnosisKey::getSubmissionTimestamp)
58 .map(DateTime::getLocalDateTimeFromHoursSinceEpoch)
59 .filter(currentDateTime -> currentDateTime.toLocalDate().equals(currentDate))
60 .collect(Collectors.toSet());
61 }
62
63 /**
64 * Creates a {@link LocalDateTime} based on the specified epoch timestamp.
65 */
66 public static LocalDateTime getLocalDateTimeFromHoursSinceEpoch(long timestamp) {
67 return LocalDateTime.ofEpochSecond(TimeUnit.HOURS.toSeconds(timestamp), 0, ZoneOffset.UTC);
68 }
69 }
70
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/util/DateTime.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/TestDataGeneration.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.distribution.runner;
22
23 import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
24 import app.coronawarn.server.common.persistence.service.DiagnosisKeyService;
25 import app.coronawarn.server.common.protocols.internal.RiskLevel;
26 import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
27 import app.coronawarn.server.services.distribution.config.DistributionServiceConfig.TestData;
28 import java.time.LocalDate;
29 import java.time.LocalDateTime;
30 import java.time.ZoneOffset;
31 import java.util.List;
32 import java.util.concurrent.TimeUnit;
33 import java.util.stream.Collectors;
34 import java.util.stream.IntStream;
35 import java.util.stream.LongStream;
36 import org.apache.commons.math3.distribution.PoissonDistribution;
37 import org.apache.commons.math3.random.JDKRandomGenerator;
38 import org.apache.commons.math3.random.RandomGenerator;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41 import org.springframework.boot.ApplicationArguments;
42 import org.springframework.boot.ApplicationRunner;
43 import org.springframework.context.annotation.Profile;
44 import org.springframework.core.annotation.Order;
45 import org.springframework.stereotype.Component;
46
47 /**
48 * Generates random diagnosis keys for the time frame between the last diagnosis key in the database and now (last full
49 * hour) and writes them to the database. If there are no diagnosis keys in the database yet, then random diagnosis keys
50 * for the time frame between the last full hour and the beginning of the retention period (14 days ago) will be
51 * generated. The average number of exposure keys to be generated per hour is configurable in the application properties
52 * (profile = {@code testdata}).
53 */
54 @Component
55 @Order(-1)
56 @Profile("testdata")
57 public class TestDataGeneration implements ApplicationRunner {
58
59 private final Logger logger = LoggerFactory.getLogger(TestDataGeneration.class);
60
61 private final Integer retentionDays;
62
63 private final TestData config;
64
65 private final DiagnosisKeyService diagnosisKeyService;
66
67 private final RandomGenerator random = new JDKRandomGenerator();
68
69 private static final int POISSON_MAX_ITERATIONS = 10_000_000;
70 private static final double POISSON_EPSILON = 1e-12;
71
72 // The submission timestamp is counted in 1 hour intervals since epoch
73 private static final long ONE_HOUR_INTERVAL_SECONDS = TimeUnit.HOURS.toSeconds(1);
74
75 // The rolling start interval number is counted in 10 minute intervals since epoch
76 private static final long TEN_MINUTES_INTERVAL_SECONDS = TimeUnit.MINUTES.toSeconds(10);
77
78 /**
79 * Creates a new TestDataGeneration runner.
80 */
81 TestDataGeneration(DiagnosisKeyService diagnosisKeyService,
82 DistributionServiceConfig distributionServiceConfig) {
83 this.diagnosisKeyService = diagnosisKeyService;
84 this.retentionDays = distributionServiceConfig.getRetentionDays();
85 this.config = distributionServiceConfig.getTestData();
86 }
87
88 /**
89 * See {@link TestDataGeneration} class documentation.
90 */
91 @Override
92 public void run(ApplicationArguments args) {
93 writeTestData();
94 }
95
96 /**
97 * See {@link TestDataGeneration} class documentation.
98 */
99 private void writeTestData() {
100 logger.debug("Querying diagnosis keys from the database...");
101 List<DiagnosisKey> existingDiagnosisKeys = diagnosisKeyService.getDiagnosisKeys();
102
103 // Timestamps in hours since epoch. Test data generation starts one hour after the latest diagnosis key in the
104 // database and ends one hour before the current one.
105 long startTimestamp = getGeneratorStartTimestamp(existingDiagnosisKeys) + 1; // Inclusive
106 long endTimestamp = getGeneratorEndTimestamp(); // Exclusive
107
108 // Add the startTimestamp to the seed. Otherwise we would generate the same data every hour.
109 random.setSeed(this.config.getSeed() + startTimestamp);
110 PoissonDistribution poisson =
111 new PoissonDistribution(random, this.config.getExposuresPerHour(), POISSON_EPSILON, POISSON_MAX_ITERATIONS);
112
113 if (startTimestamp == endTimestamp) {
114 logger.debug("Skipping test data generation, latest diagnosis keys are still up-to-date.");
115 return;
116 }
117 logger.debug("Generating diagnosis keys between {} and {}...", startTimestamp, endTimestamp);
118 List<DiagnosisKey> newDiagnosisKeys = LongStream.range(startTimestamp, endTimestamp)
119 .mapToObj(submissionTimestamp -> IntStream.range(0, poisson.sample())
120 .mapToObj(__ -> generateDiagnosisKey(submissionTimestamp))
121 .collect(Collectors.toList()))
122 .flatMap(List::stream)
123 .collect(Collectors.toList());
124
125 logger.debug("Writing {} new diagnosis keys to the database...", newDiagnosisKeys.size());
126 diagnosisKeyService.saveDiagnosisKeys(newDiagnosisKeys);
127
128 logger.debug("Test data generation finished successfully.");
129 }
130
131 /**
132 * Returns the submission timestamp (in 1 hour intervals since epoch) of the last diagnosis key in the database (or
133 * the result of {@link TestDataGeneration#getRetentionStartTimestamp} if there are no diagnosis keys in the database
134 * yet.
135 */
136 private long getGeneratorStartTimestamp(List<DiagnosisKey> diagnosisKeys) {
137 if (diagnosisKeys.isEmpty()) {
138 return getRetentionStartTimestamp();
139 } else {
140 DiagnosisKey latestDiagnosisKey = diagnosisKeys.get(diagnosisKeys.size() - 1);
141 return latestDiagnosisKey.getSubmissionTimestamp();
142 }
143 }
144
145 /**
146 * Returns the timestamp (in 1 hour intervals since epoch) of the last full hour. Example: If called at 15:38 UTC,
147 * this function would return the timestamp for today 14:00 UTC.
148 */
149 private long getGeneratorEndTimestamp() {
150 return (LocalDateTime.now().toEpochSecond(ZoneOffset.UTC) / ONE_HOUR_INTERVAL_SECONDS) - 1;
151 }
152
153 /**
154 * Returns the timestamp (in 1 hour intervals since epoch) at which the retention period starts. Example: If the
155 * retention period in the application properties is set to 14 days, then this function would return the timestamp for
156 * 14 days ago (from now) at 00:00 UTC.
157 */
158 private long getRetentionStartTimestamp() {
159 return LocalDate.now().minusDays(retentionDays).atStartOfDay()
160 .toEpochSecond(ZoneOffset.UTC) / ONE_HOUR_INTERVAL_SECONDS;
161 }
162
163 /**
164 * Returns a random diagnosis key with a specific submission timestamp.
165 */
166 private DiagnosisKey generateDiagnosisKey(long submissionTimestamp) {
167 return DiagnosisKey.builder()
168 .withKeyData(generateDiagnosisKeyBytes())
169 .withRollingStartIntervalNumber(generateRollingStartIntervalNumber(submissionTimestamp))
170 .withTransmissionRiskLevel(generateTransmissionRiskLevel())
171 .withSubmissionTimestamp(submissionTimestamp)
172 .build();
173 }
174
175 /**
176 * Returns 16 random bytes.
177 */
178 private byte[] generateDiagnosisKeyBytes() {
179 byte[] exposureKey = new byte[16];
180 random.nextBytes(exposureKey);
181 return exposureKey;
182 }
183
184 /**
185 * Returns a random rolling start interval number (timestamp since when a key was active, represented by a 10 minute
186 * interval counter) between a specific submission timestamp and the beginning of the retention period.
187 */
188 private int generateRollingStartIntervalNumber(long submissionTimestamp) {
189 long maxRollingStartIntervalNumber =
190 submissionTimestamp * ONE_HOUR_INTERVAL_SECONDS / TEN_MINUTES_INTERVAL_SECONDS;
191 long minRollingStartIntervalNumber =
192 maxRollingStartIntervalNumber
193 - TimeUnit.DAYS.toSeconds(retentionDays) / TEN_MINUTES_INTERVAL_SECONDS;
194 return Math.toIntExact(getRandomBetween(minRollingStartIntervalNumber, maxRollingStartIntervalNumber));
195 }
196
197 /**
198 * Returns a random number between {@link RiskLevel#RISK_LEVEL_LOWEST_VALUE} and {@link
199 * RiskLevel#RISK_LEVEL_HIGHEST_VALUE}.
200 */
201 private int generateTransmissionRiskLevel() {
202 return Math.toIntExact(
203 getRandomBetween(RiskLevel.RISK_LEVEL_LOWEST_VALUE, RiskLevel.RISK_LEVEL_HIGHEST_VALUE));
204 }
205
206 /**
207 * Returns a random number between {@code minIncluding} and {@code maxIncluding}.
208 */
209 private long getRandomBetween(long minIncluding, long maxIncluding) {
210 return minIncluding + (long) (random.nextDouble() * (maxIncluding - minIncluding));
211 }
212 }
213
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/TestDataGeneration.java]
</code>
Here is an example of a patch file. It consists of changes to the code base. It specifies the file names, the line numbers of each change, and the removed and added lines. A single patch file can contain changes to multiple files.
<patch>
--- a/file.py
+++ b/file.py
@@ -1,27 +1,35 @@
def euclidean(a, b):
- while b:
- a, b = b, a % b
- return a
+ if b == 0:
+ return a
+ return euclidean(b, a % b)
def bresenham(x0, y0, x1, y1):
points = []
dx = abs(x1 - x0)
dy = abs(y1 - y0)
- sx = 1 if x0 < x1 else -1
- sy = 1 if y0 < y1 else -1
- err = dx - dy
+ x, y = x0, y0
+ sx = -1 if x0 > x1 else 1
+ sy = -1 if y0 > y1 else 1
- while True:
- points.append((x0, y0))
- if x0 == x1 and y0 == y1:
- break
- e2 = 2 * err
- if e2 > -dy:
+ if dx > dy:
+ err = dx / 2.0
+ while x != x1:
+ points.append((x, y))
err -= dy
- x0 += sx
- if e2 < dx:
- err += dx
- y0 += sy
+ if err < 0:
+ y += sy
+ err += dx
+ x += sx
+ else:
+ err = dy / 2.0
+ while y != y1:
+ points.append((x, y))
+ err -= dx
+ if err < 0:
+ x += sx
+ err += dy
+ y += sy
+ points.append((x, y))
return points
</patch>
I need you to solve the provded issue by generating a single patch file that I can apply directly to this repository using git apply. Please respond with a single patch file in the format shown above.
Respond below:
| corona-warn-app/cwa-server | 943a9cea975f6395f99217bb380e526e937f093e | TEK Exports should not contain any keys which recently expired
Currently the system also packages keys, which expired recently. Instead, only keys which have been expired since at least 2 hours should be part of the export.
Can also be a nice prework for https://github.com/corona-warn-app/cwa-server/issues/108.
Probably should change this already when the diagnosis keys are queried for distribution:
https://github.com/corona-warn-app/cwa-server/blob/master/common/persistence/src/main/java/app/coronawarn/server/common/persistence/service/DiagnosisKeyService.java#L64
| [Apple spec](https://developer.apple.com/documentation/exposurenotification/setting_up_an_exposure_notification_server) states:
> [Your EN Server...] must not distribute temporary exposure key data until at least 2 hours after the end of the keyʼs expiration window
I think this is a subtle but important difference to just excluding (+2h) by submission timestamp. As far as I know, the TEK API on-device does not give out "still active" keys to the app. This just leaves a 2 hour window that depends on the rolling start interval number and the rolling period, but not on the submission timestamp.
You are right Pit - I just talked to DPP to clarify whether this is OK for them, and it is.
I'll update the description of the issue accordingly. | 2020-05-30T14:56:55 | <patch>
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysHourDirectory.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysHourDirectory.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysHourDirectory.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysHourDirectory.java
@@ -88,9 +88,7 @@ public void prepare(ImmutableStack<Object> indices) {
private Set<DiagnosisKey> getDiagnosisKeysForHour(LocalDateTime hour) {
return this.diagnosisKeys.stream()
- .filter(diagnosisKey -> DateTime
- .getLocalDateTimeFromHoursSinceEpoch(diagnosisKey.getSubmissionTimestamp())
- .equals(hour))
+ .filter(diagnosisKey -> DistributionDateTimeCalculator.getDistributionDateTime(diagnosisKey).equals(hour))
.collect(Collectors.toSet());
}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DistributionDateTimeCalculator.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DistributionDateTimeCalculator.java
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DistributionDateTimeCalculator.java
@@ -0,0 +1,62 @@
+/*-
+ * ---license-start
+ * Corona-Warn-App
+ * ---
+ * Copyright (C) 2020 SAP SE and all other contributors
+ * ---
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://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 for the specific language governing permissions and
+ * limitations under the License.
+ * ---license-end
+ */
+
+package app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.directory;
+
+import static app.coronawarn.server.services.distribution.assembly.diagnosiskeys.util.DateTime.ONE_HOUR_INTERVAL_SECONDS;
+import static app.coronawarn.server.services.distribution.assembly.diagnosiskeys.util.DateTime.TEN_MINUTES_INTERVAL_SECONDS;
+import static java.time.ZoneOffset.UTC;
+
+import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
+import java.time.Duration;
+import java.time.LocalDateTime;
+import java.time.temporal.ChronoUnit;
+
+public class DistributionDateTimeCalculator {
+
+ /**
+ * Minimum time in minutes after key expiration after which it can be distributed.
+ */
+ public static final long DISTRIBUTION_PADDING = 120L;
+
+ private DistributionDateTimeCalculator() {
+ }
+
+ /**
+ * Calculates the earliest point in time at which the specified {@link DiagnosisKey} can be distributed. Before keys
+ * are allowed to be distributed, they must be expired for a configured amount of time.
+ *
+ * @return {@link LocalDateTime} at which the specified {@link DiagnosisKey} can be distributed.
+ */
+ public static LocalDateTime getDistributionDateTime(DiagnosisKey diagnosisKey) {
+ LocalDateTime submissionDateTime = LocalDateTime
+ .ofEpochSecond(diagnosisKey.getSubmissionTimestamp() * ONE_HOUR_INTERVAL_SECONDS, 0, UTC);
+ LocalDateTime keyExpiryDateTime = LocalDateTime
+ .ofEpochSecond(diagnosisKey.getRollingStartIntervalNumber() * TEN_MINUTES_INTERVAL_SECONDS, 0, UTC)
+ .plusMinutes(diagnosisKey.getRollingPeriod() * 10L);
+
+ if (Duration.between(keyExpiryDateTime, submissionDateTime).toMinutes() <= DISTRIBUTION_PADDING) {
+ // truncatedTo floors the value, so we need to add an hour to the DISTRIBUTION_PADDING to compensate that.
+ return keyExpiryDateTime.plusMinutes(DISTRIBUTION_PADDING + 60).truncatedTo(ChronoUnit.HOURS);
+ }
+
+ return submissionDateTime;
+ }
+}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/util/DateTime.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/util/DateTime.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/util/DateTime.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/util/DateTime.java
@@ -34,6 +34,16 @@
*/
public class DateTime {
+ /**
+ * The submission timestamp is counted in 1 hour intervals since epoch.
+ */
+ public static final long ONE_HOUR_INTERVAL_SECONDS = TimeUnit.HOURS.toSeconds(1);
+
+ /**
+ * The rolling start interval number is counted in 10 minute intervals since epoch.
+ */
+ public static final long TEN_MINUTES_INTERVAL_SECONDS = TimeUnit.MINUTES.toSeconds(10);
+
private DateTime() {
}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/TestDataGeneration.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/TestDataGeneration.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/TestDataGeneration.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/TestDataGeneration.java
@@ -20,6 +20,9 @@
package app.coronawarn.server.services.distribution.runner;
+import static app.coronawarn.server.services.distribution.assembly.diagnosiskeys.util.DateTime.ONE_HOUR_INTERVAL_SECONDS;
+import static app.coronawarn.server.services.distribution.assembly.diagnosiskeys.util.DateTime.TEN_MINUTES_INTERVAL_SECONDS;
+
import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
import app.coronawarn.server.common.persistence.service.DiagnosisKeyService;
import app.coronawarn.server.common.protocols.internal.RiskLevel;
@@ -69,12 +72,6 @@ public class TestDataGeneration implements ApplicationRunner {
private static final int POISSON_MAX_ITERATIONS = 10_000_000;
private static final double POISSON_EPSILON = 1e-12;
- // The submission timestamp is counted in 1 hour intervals since epoch
- private static final long ONE_HOUR_INTERVAL_SECONDS = TimeUnit.HOURS.toSeconds(1);
-
- // The rolling start interval number is counted in 10 minute intervals since epoch
- private static final long TEN_MINUTES_INTERVAL_SECONDS = TimeUnit.MINUTES.toSeconds(10);
-
/**
* Creates a new TestDataGeneration runner.
*/
</patch> | diff --git a/common/persistence/src/test/java/app/coronawarn/server/common/persistence/domain/DiagnosisKeyTest.java b/common/persistence/src/test/java/app/coronawarn/server/common/persistence/domain/DiagnosisKeyTest.java
--- a/common/persistence/src/test/java/app/coronawarn/server/common/persistence/domain/DiagnosisKeyTest.java
+++ b/common/persistence/src/test/java/app/coronawarn/server/common/persistence/domain/DiagnosisKeyTest.java
@@ -33,7 +33,6 @@
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
-
class DiagnosisKeyTest {
final static byte[] expKeyData = "testKey111111111".getBytes(Charset.defaultCharset());
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/structure/directory/DistributionDateTimeCalculatorTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/structure/directory/DistributionDateTimeCalculatorTest.java
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/structure/directory/DistributionDateTimeCalculatorTest.java
@@ -0,0 +1,72 @@
+/*-
+ * ---license-start
+ * Corona-Warn-App
+ * ---
+ * Copyright (C) 2020 SAP SE and all other contributors
+ * ---
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://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 for the specific language governing permissions and
+ * limitations under the License.
+ * ---license-end
+ */
+
+package app.coronawarn.server.services.distribution.assembly.structure.directory;
+
+import static app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.directory.DistributionDateTimeCalculator.getDistributionDateTime;
+import static org.assertj.core.api.Assertions.assertThat;
+
+import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+class DistributionDateTimeCalculatorTest {
+
+ @ParameterizedTest
+ @ValueSource(longs = {0L, 24L, 24L + 2L})
+ void testLastPeriodOfHourAndSubmissionLessThanDistributionDateTime(long submissionTimestamp) {
+ var diagnosisKey = buildDiagnosisKey(5, submissionTimestamp);
+ assertThat(getDistributionDateTime(diagnosisKey)).isEqualTo("1970-01-02T03:00");
+ }
+
+ @Test
+ void testLastPeriodOfHourAndSubmissionEqualsDistributionDateTime() {
+ var diagnosisKey = buildDiagnosisKey(5, 24L + 3L);
+ assertThat(getDistributionDateTime(diagnosisKey)).isEqualTo("1970-01-02T03:00");
+ }
+
+ @ParameterizedTest
+ @ValueSource(longs = {0L, 24L, 24L + 2L, 24L + 3L})
+ void testFirstPeriodOfHourAndSubmissionLessThanDistributionDateTime(long submissionTimestamp) {
+ var diagnosisKey = buildDiagnosisKey(6, submissionTimestamp);
+ assertThat(getDistributionDateTime(diagnosisKey)).isEqualTo("1970-01-02T04:00");
+ }
+
+ @Test
+ void testFirstPeriodOfHourAndSubmissionEqualsDistributionDateTime() {
+ var diagnosisKey = buildDiagnosisKey(6, 24L + 4L);
+ assertThat(getDistributionDateTime(diagnosisKey)).isEqualTo("1970-01-02T04:00");
+ }
+
+ @Test
+ void testLastPeriodOfHourAndSubmissionGreaterDistributionDateTime() {
+ var diagnosisKey = buildDiagnosisKey(5, 24L + 4L);
+ assertThat(getDistributionDateTime(diagnosisKey)).isEqualTo("1970-01-02T04:00");
+ }
+
+ private DiagnosisKey buildDiagnosisKey(int startIntervalNumber, long submissionTimestamp) {
+ return DiagnosisKey.builder()
+ .withKeyData(new byte[16])
+ .withRollingStartIntervalNumber(startIntervalNumber)
+ .withTransmissionRiskLevel(2)
+ .withSubmissionTimestamp(submissionTimestamp).build();
+ }
+}
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/structure/util/ImmutableStackTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/structure/util/ImmutableStackTest.java
--- a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/structure/util/ImmutableStackTest.java
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/structure/util/ImmutableStackTest.java
@@ -20,15 +20,12 @@
package app.coronawarn.server.services.distribution.assembly.structure.util;
-import org.assertj.core.api.Assertions;
-import org.junit.jupiter.api.Test;
-
-import java.util.ArrayDeque;
-import java.util.NoSuchElementException;
-
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
+import java.util.NoSuchElementException;
+import org.junit.jupiter.api.Test;
+
class ImmutableStackTest {
private final ImmutableStack<String> stack =
| ||||
corona-warn-app__cwa-server-388 | You will be provided with a partial code base and an issue statement explaining a problem to resolve.
<issue>
Ensure uniqueness of diagnosis keys
## Current Implementation
The uniqueness of diagnosis keys is neither guaranteed by the database, nor by validation logic.
## Suggested Enhancement
Ensure that diagnosis keys in the database are unique (there are no duplicates).
What needs to be decided:
- [x] Is it sufficient to guarantee the uniqueness of the diagnosis key or should the uniqueness of diagnosis key + submission timestamp (+maybe even more fields) be guaranteed?
- [x] Should the duplicate check happen on the database (`UNIQUE` constraint) or in the server logic (e.g. during the validation of submitted keys)?
- [x] If the check happens on the database: Should the `id` column be removed and replaced with the diagnosis key (+submission timestamp) as (composite) primary key?
- [x] How should the server react when a duplicate diagnosis key is submitted (update, error, etc.)?
**Edit:** Decisions are below.
</issue>
<code>
[start of README.md]
1 <!-- markdownlint-disable MD041 -->
2 <h1 align="center">
3 Corona-Warn-App Server
4 </h1>
5
6 <p align="center">
7 <a href="https://github.com/corona-warn-app/cwa-server/commits/" title="Last Commit"><img src="https://img.shields.io/github/last-commit/corona-warn-app/cwa-server?style=flat"></a>
8 <a href="https://github.com/corona-warn-app/cwa-server/issues" title="Open Issues"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat"></a>
9 <a href="https://circleci.com/gh/corona-warn-app/cwa-server" title="Build Status"><img src="https://circleci.com/gh/corona-warn-app/cwa-server.svg?style=shield&circle-token=4ab059989d10709df19eb4b98ab7c121a25e981a"></a>
10 <a href="https://sonarcloud.io/dashboard?id=corona-warn-app_cwa-server" title="Quality Gate"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=alert_status"></a>
11 <a href="https://sonarcloud.io/component_measures?id=corona-warn-app_cwa-server&metric=Coverage&view=list" title="Coverage"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=coverage"></a>
12 <a href="https://github.com/corona-warn-app/cwa-server/blob/master/LICENSE" title="License"><img src="https://img.shields.io/badge/License-Apache%202.0-green.svg?style=flat"></a>
13 </p>
14
15 <p align="center">
16 <a href="#development">Development</a> •
17 <a href="#service-apis">Service APIs</a> •
18 <a href="#documentation">Documentation</a> •
19 <a href="#support-and-feedback">Support</a> •
20 <a href="#how-to-contribute">Contribute</a> •
21 <a href="#contributors">Contributors</a> •
22 <a href="#repositories">Repositories</a> •
23 <a href="#licensing">Licensing</a>
24 </p>
25
26 The goal of this project is to develop the official Corona-Warn-App for Germany based on the exposure notification API from [Apple](https://www.apple.com/covid19/contacttracing/) and [Google](https://www.google.com/covid19/exposurenotifications/). The apps (for both iOS and Android) use Bluetooth technology to exchange anonymous encrypted data with other mobile phones (on which the app is also installed) in the vicinity of an app user's phone. The data is stored locally on each user's device, preventing authorities or other parties from accessing or controlling the data. This repository contains the **implementation of the server for encryption keys** for the Corona-Warn-App. This implementation is still a **work in progress**, and the code it contains is currently alpha-quality code.
27
28 In this documentation, Corona-Warn-App services are also referred to as CWA services.
29
30 ## Architecture Overview
31
32 You can find the architecture overview [here](/docs/architecture-overview.md), which will give you
33 a good starting point in how the backend services interact with other services, and what purpose
34 they serve.
35
36 ## Development
37
38 After you've checked out this repository, you can run the application in one of the following ways:
39
40 * As a [Docker](https://www.docker.com/)-based deployment on your local machine. You can run either:
41 * Single components using the respective Dockerfile or
42 * The full backend using the Docker Compose (which is considered the most convenient way)
43 * As a [Maven](https://maven.apache.org)-based build on your local machine.
44 If you want to develop something in a single component, this approach is preferable.
45
46 ### Docker-Based Deployment
47
48 If you want to use Docker-based deployment, you need to install Docker on your local machine. For more information about downloading and installing Docker, see the [official Docker documentation](https://docs.docker.com/get-docker/).
49
50 #### Running the Full CWA Backend Using Docker Compose
51
52 For your convenience, a full setup including the generation of test data has been prepared using [Docker Compose](https://docs.docker.com/compose/reference/overview/). To build the backend services, run ```docker-compose build``` in the repository's root directory. A default configuration file can be found under ```.env```in the root folder of the repository. The default values for the local Postgres and Zenko Cloudserver should be changed in this file before docker-compose is run.
53
54 Once the services are built, you can start the whole backend using ```docker-compose up```.
55 The distribution service runs once and then finishes. If you want to trigger additional distribution runs, run ```docker-compose run distribution```.
56
57 The docker-compose contains the following services:
58
59 Service | Description | Endpoint and Default Credentials
60 ------------------|-------------|-----------
61 submission | The Corona-Warn-App submission service | `http://localhost:8000` <br> `http://localhost:8006` (for actuator endpoint)
62 distribution | The Corona-Warn-App distribution service | NO ENDPOINT
63 postgres | A [postgres] database installation | `postgres:8001` <br> Username: postgres <br> Password: postgres
64 pgadmin | A [pgadmin](https://www.pgadmin.org/) installation for the postgres database | `http://localhost:8002` <br> Username: [email protected] <br> Password: password
65 cloudserver | [Zenko CloudServer] is a S3-compliant object store | `http://localhost:8003/` <br> Access key: accessKey1 <br> Secret key: verySecretKey1
66 verification-fake | A very simple fake implementation for the tan verification. | `http://localhost:8004/version/v1/tan/verify` <br> The only valid tan is "edc07f08-a1aa-11ea-bb37-0242ac130002"
67
68 ##### Known Limitation
69
70 In rare cases the docker-compose runs into a timing issue if the distribution service starts before the bucket of the objectstore was created. This is not a big issue as you can simply run ```docker-compose run distribution``` to trigger additional distribution runs after the objectstore was initialized.
71
72 #### Running Single CWA Services Using Docker
73
74 If you would like to build and run a single CWA service, it's considered easiest to run them in a Docker environment. You can do this using the script provided in the respective CWA service directory. The Docker script first builds the CWA service and then creates an image for the runtime, which means that there are no additional dependencies for you to install.
75
76 To build and run the distribution service, run the following command:
77
78 ```bash
79 ./services/distribution/build_and_run.sh
80 ```
81
82 To build and run the submission service, run the following command:
83
84 ```bash
85 ./services/submission/build_and_run.sh
86 ```
87
88 The submission service is available on [localhost:8080](http://localhost:8080 ).
89
90 ### Maven-Based Build
91
92 If you want to actively develop in one of the CWA services, the Maven-based runtime is most suitable.
93 To prepare your machine to run the CWA project locally, we recommend that you first ensure that you've installed the following:
94
95 * Minimum JDK Version 11: [OpenJDK](https://openjdk.java.net/) / [SapMachine](https://sap.github.io/SapMachine/)
96 * [Maven 3.6](https://maven.apache.org/)
97 * [Postgres]
98 * [Zenko CloudServer]
99
100 #### Configure
101
102 After you made sure that the specified dependencies are running, configure them in the respective configuration files.
103
104 * Configure the Postgres connection in the [submission config](./services/submission/src/main/resources/application.yaml) and in the [distribution config](./services/distribution/src/main/resources/application.yaml)
105 * Configure the S3 compatible object storage in the [distribution config](./services/distribution/src/main/resources/application.yaml)
106 * Configure the private key for the distribution service, the path need to be prefixed with `file:`
107 * `VAULT_FILESIGNING_SECRET` should be the path to the private key, example available in `<repo-root>/docker-compose-test-secrets/private.pem`
108
109 #### Build
110
111 After you've checked out the repository, to build the project, run ```mvn install``` in your base directory.
112
113 #### Run
114
115 Navigate to the service you want to start and run the spring-boot:run target. The configured Postgres and the configured S3 compliant object storage are used as default. When you start the submission service, the endpoint is available on your local port 8080.
116
117 If you want to start the submission service, for example, you start it as follows:
118
119 ```bash
120 cd services/submission/
121 mvn spring-boot:run
122 ```
123
124 #### Debugging
125
126 To enable the `DEBUG` log level, you can run the application using the Spring `dev` profile.
127
128 ```bash
129 mvn spring-boot:run -Dspring-boot.run.profiles=dev
130 ```
131
132 To be able to set breakpoints (e.g. in IntelliJ), it may be necessary to use the ```-Dspring-boot.run.fork=false``` parameter.
133
134 ## Service APIs
135
136 The API that is being exposed by the backend services is documented in an [OpenAPI](https://www.openapis.org/) specification. The specification files are available at the following locations:
137
138 Service | OpenAPI Specification
139 -------------|-------------
140 Submission Service | [services/submission/api_v1.json](https://github.com/corona-warn-app/cwa-server/raw/master/services/submission/api_v1.json)
141 Distribution Service | [services/distribution/api_v1.json](https://github.com/corona-warn-app/cwa-server/raw/master/services/distribution/api_v1.json)
142
143 ## Spring Profiles
144
145 ### Distribution
146
147 Profile | Effect
148 -----------------|-------------
149 `dev` | Turns the log level to `DEBUG`.
150 `cloud` | Removes default values for the `datasource` and `objectstore` configurations.
151 `demo` | Includes incomplete days and hours into the distribution run, thus creating aggregates for the current day and the current hour (and including both in the respective indices). When running multiple distributions in one hour with this profile, the date aggregate for today and the hours aggregate for the current hour will be updated and overwritten.
152 `testdata` | Causes test data to be inserted into the database before each distribution run. By default, around 1000 random diagnosis keys will be generated per hour. If there are no diagnosis keys in the database yet, random keys will be generated for every hour from the beginning of the retention period (14 days ago at 00:00 UTC) until one hour before the present hour. If there are already keys in the database, the random keys will be generated for every hour from the latest diagnosis key in the database (by submission timestamp) until one hour before the present hour (or none at all, if the latest diagnosis key in the database was submitted one hour ago or later).
153 `signature-dev` | Sets the app package ID in the export packages' signature info to `de.rki.coronawarnapp-dev` so that test certificates (instead of production certificates) will be used for client-side validation.
154 `signature-prod` | Provides production app package IDs for the signature info
155
156 ### Submission
157
158 Profile | Effect
159 -------------|-------------
160 `dev` | Turns the log level to `DEBUG`.
161 `cloud` | Removes default values for the `datasource` configuration.
162
163 ## Documentation
164
165 The full documentation for the Corona-Warn-App can be found in the [cwa-documentation](https://github.com/corona-warn-app/cwa-documentation) repository. The documentation repository contains technical documents, architecture information, and whitepapers related to this implementation.
166
167 ## Support and Feedback
168
169 The following channels are available for discussions, feedback, and support requests:
170
171 | Type | Channel |
172 | ------------------------ | ------------------------------------------------------ |
173 | **General Discussion** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="General Discussion"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/question.svg?style=flat-square"></a> </a> |
174 | **Concept Feedback** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="Open Concept Feedback"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/architecture.svg?style=flat-square"></a> |
175 | **Backend Issue** | <a href="https://github.com/corona-warn-app/cwa-server/issues/new/choose" title="Open Backend Issue"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat-square"></a> |
176 | **Other Requests** | <a href="mailto:[email protected]" title="Email CWA Team"><img src="https://img.shields.io/badge/email-CWA%20team-green?logo=mail.ru&style=flat-square&logoColor=white"></a> |
177
178 ## How to Contribute
179
180 Contribution and feedback are 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.
181
182 ## Contributors
183
184 The German government has asked SAP and Deutsche Telekom to develop the Corona-Warn-App for Germany as open source software. Deutsche Telekom is providing the network and mobile technology and will operate and run the backend for the app in a safe, scalable and stable manner. SAP is responsible for the app development, its framework and the underlying platform. Therefore, development teams of SAP and Deutsche Telekom are contributing to this project. At the same time 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.
185
186 ## Repositories
187
188 The following public repositories are currently available for the Corona-Warn-App:
189
190 | Repository | Description |
191 | ------------------- | --------------------------------------------------------------------- |
192 | [cwa-documentation] | Project overview, general documentation, and white papers |
193 | [cwa-server] | Backend implementation for the Apple/Google exposure notification API|
194 | [cwa-verification-server] | Backend implementation of the verification process|
195
196 [cwa-documentation]: https://github.com/corona-warn-app/cwa-documentation
197 [cwa-server]: https://github.com/corona-warn-app/cwa-server
198 [cwa-verification-server]: https://github.com/corona-warn-app/cwa-verification-server
199 [Postgres]: https://www.postgresql.org/
200 [HSQLDB]: http://hsqldb.org/
201 [Zenko CloudServer]: https://github.com/scality/cloudserver
202
203 ## Licensing
204
205 Copyright (c) 2020 SAP SE or an SAP affiliate company.
206
207 Licensed under the **Apache License, Version 2.0** (the "License"); you may not use this file except in compliance with the License.
208
209 You may obtain a copy of the License at <https://www.apache.org/licenses/LICENSE-2.0>.
210
211 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.
212
[end of README.md]
[start of /dev/null]
1
[end of /dev/null]
[start of common/persistence/pom.xml]
1 <?xml version="1.0" encoding="UTF-8"?>
2 <project xmlns="http://maven.apache.org/POM/4.0.0"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
5 <parent>
6 <groupId>org.springframework.boot</groupId>
7 <artifactId>spring-boot-starter-parent</artifactId>
8 <version>2.3.0.RELEASE</version>
9 <relativePath></relativePath>
10 </parent>
11 <modelVersion>4.0.0</modelVersion>
12
13 <groupId>org.opencwa</groupId>
14 <artifactId>persistence</artifactId>
15 <version>${revision}</version>
16
17 <organization>
18 <name>SAP SE</name>
19 </organization>
20
21 <properties>
22 <java.version>11</java.version>
23 <maven.compiler.source>11</maven.compiler.source>
24 <maven.compiler.target>11</maven.compiler.target>
25 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
26 <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
27 <sonar.projectKey>corona-warn-app_cwa-server_common_persistence</sonar.projectKey>
28 </properties>
29
30 <dependencies>
31 <dependency>
32 <groupId>org.opencwa</groupId>
33 <artifactId>protocols</artifactId>
34 <version>${project.version}</version>
35 </dependency>
36 <dependency>
37 <groupId>org.springframework.boot</groupId>
38 <artifactId>spring-boot-starter-data-jpa</artifactId>
39 </dependency>
40 <dependency>
41 <groupId>org.springframework.boot</groupId>
42 <artifactId>spring-boot-starter-validation</artifactId>
43 </dependency>
44 <dependency>
45 <groupId>org.springframework.boot</groupId>
46 <artifactId>spring-boot-starter-test</artifactId>
47 <scope>test</scope>
48 <exclusions>
49 <exclusion>
50 <groupId>org.junit.vintage</groupId>
51 <artifactId>junit-vintage-engine</artifactId>
52 </exclusion>
53 </exclusions>
54 </dependency>
55 <dependency>
56 <groupId>org.springframework.boot</groupId>
57 <artifactId>spring-boot-starter</artifactId>
58 <exclusions>
59 <exclusion>
60 <groupId>org.springframework.boot</groupId>
61 <artifactId>spring-boot-starter-logging</artifactId>
62 </exclusion>
63 </exclusions>
64 </dependency>
65 <dependency>
66 <groupId>org.springframework.boot</groupId>
67 <artifactId>spring-boot-starter-log4j2</artifactId>
68 </dependency>
69 <dependency>
70 <groupId>org.flywaydb</groupId>
71 <artifactId>flyway-core</artifactId>
72 </dependency>
73 <dependency>
74 <groupId>org.postgresql</groupId>
75 <artifactId>postgresql</artifactId>
76 <scope>runtime</scope>
77 </dependency>
78 <dependency>
79 <groupId>com.h2database</groupId>
80 <artifactId>h2</artifactId>
81 <version>1.4.199</version>
82 <scope>runtime</scope>
83 </dependency>
84 <dependency>
85 <!-- https://nvd.nist.gov/vuln/detail/CVE-2020-9488 -->
86 <groupId>org.apache.logging.log4j</groupId>
87 <artifactId>log4j-core</artifactId>
88 <version>2.13.3</version>
89 </dependency>
90 <dependency>
91 <!-- https://nvd.nist.gov/vuln/detail/CVE-2020-9488 -->
92 <groupId>org.apache.logging.log4j</groupId>
93 <artifactId>log4j-api</artifactId>
94 <version>2.13.3</version>
95 </dependency>
96 <dependency>
97 <!-- Due to https://nvd.nist.gov/vuln/detail/CVE-2020-10683 -->
98 <groupId>org.dom4j</groupId>
99 <artifactId>dom4j</artifactId>
100 <version>2.1.3</version>
101 </dependency>
102 <dependency>
103 <!-- https://nvd.nist.gov/vuln/detail/CVE-2017-18640 -->
104 <groupId>org.yaml</groupId>
105 <artifactId>snakeyaml</artifactId>
106 <version>1.26</version>
107 </dependency>
108 </dependencies>
109
110 <build>
111 <plugins>
112 <plugin>
113 <groupId>org.codehaus.mojo</groupId>
114 <artifactId>license-maven-plugin</artifactId>
115 <version>2.0.0</version>
116 <configuration>
117 <includes>**/*.java</includes>
118 <copyrightOwners>${organization.name} and all other contributors</copyrightOwners>
119 <processStartTag>---license-start</processStartTag>
120 <processEndTag>---license-end</processEndTag>
121 <sectionDelimiter>---</sectionDelimiter>
122 <addJavaLicenseAfterPackage>false</addJavaLicenseAfterPackage>
123 <trimHeaderLine>true</trimHeaderLine>
124 <emptyLineAfterHeader>true</emptyLineAfterHeader>
125 </configuration>
126 </plugin>
127 <plugin>
128 <!-- see https://maven.apache.org/maven-ci-friendly.html#install-deploy -->
129 <groupId>org.codehaus.mojo</groupId>
130 <artifactId>flatten-maven-plugin</artifactId>
131 <version>1.1.0</version>
132 <configuration>
133 <updatePomFile>true</updatePomFile>
134 <flattenMode>resolveCiFriendliesOnly</flattenMode>
135 </configuration>
136 <executions>
137 <execution>
138 <id>flatten</id>
139 <phase>process-resources</phase>
140 <goals><goal>flatten</goal></goals>
141 </execution>
142 <execution>
143 <id>flatten-clean</id>
144 <phase>clean</phase>
145 <goals><goal>clean</goal></goals>
146 </execution>
147 </executions>
148 </plugin>
149 <plugin>
150 <groupId>org.apache.maven.plugins</groupId>
151 <artifactId>maven-checkstyle-plugin</artifactId>
152 <version>3.1.1</version>
153 <configuration>
154 <configLocation>../../codestyle/checkstyle.xml</configLocation>
155 <excludes>**/module-info.java,**/target/**/*</excludes>
156 <encoding>UTF-8</encoding>
157 <consoleOutput>true</consoleOutput>
158 <failsOnError>true</failsOnError>
159 <violationSeverity>warning</violationSeverity>
160 <failOnViolation>true</failOnViolation>
161 <linkXRef>false</linkXRef>
162 </configuration>
163 <executions>
164 <execution>
165 <id>validate</id>
166 <phase>validate</phase>
167 <goals>
168 <goal>check</goal>
169 </goals>
170 </execution>
171 </executions>
172 </plugin>
173 <plugin>
174 <groupId>org.jacoco</groupId>
175 <artifactId>jacoco-maven-plugin</artifactId>
176 <version>0.8.5</version>
177 <executions>
178 <execution>
179 <goals>
180 <goal>prepare-agent</goal>
181 </goals>
182 </execution>
183 <execution>
184 <id>report</id>
185 <goals>
186 <goal>report</goal>
187 </goals>
188 <phase>verify</phase>
189 </execution>
190 </executions>
191 </plugin>
192 </plugins>
193 </build>
194 </project>
195
[end of common/persistence/pom.xml]
[start of common/persistence/src/main/java/app/coronawarn/server/common/persistence/domain/DiagnosisKey.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.common.persistence.domain;
22
23 import static java.time.ZoneOffset.UTC;
24
25 import app.coronawarn.server.common.persistence.domain.DiagnosisKeyBuilders.Builder;
26 import app.coronawarn.server.common.persistence.domain.validation.ValidRollingStartIntervalNumber;
27 import java.time.Instant;
28 import java.time.LocalDateTime;
29 import java.util.Arrays;
30 import java.util.Objects;
31 import java.util.Set;
32 import javax.persistence.Entity;
33 import javax.persistence.GeneratedValue;
34 import javax.persistence.GenerationType;
35 import javax.persistence.Id;
36 import javax.persistence.Table;
37 import javax.validation.ConstraintViolation;
38 import javax.validation.Validation;
39 import javax.validation.Validator;
40 import javax.validation.constraints.Size;
41 import org.hibernate.validator.constraints.Range;
42
43 /**
44 * A key generated for advertising over a window of time.
45 */
46 @Entity
47 @Table(name = "diagnosis_key")
48 public class DiagnosisKey {
49
50 /**
51 * According to "Setting Up an Exposure Notification Server" by Apple, exposure notification servers are expected to
52 * reject any diagnosis keys that do not have a rolling period of a certain fixed value. See
53 * https://developer.apple.com/documentation/exposurenotification/setting_up_an_exposure_notification_server
54 */
55 public static final int EXPECTED_ROLLING_PERIOD = 144;
56
57 private static final Validator VALIDATOR = Validation.buildDefaultValidatorFactory().getValidator();
58
59 @Id
60 @GeneratedValue(strategy = GenerationType.IDENTITY)
61 private Long id;
62
63 @Size(min = 16, max = 16, message = "Key data must be a byte array of length 16.")
64 private byte[] keyData;
65
66 @ValidRollingStartIntervalNumber
67 private int rollingStartIntervalNumber;
68
69 @Range(min = EXPECTED_ROLLING_PERIOD, max = EXPECTED_ROLLING_PERIOD,
70 message = "Rolling period must be " + EXPECTED_ROLLING_PERIOD + ".")
71 private int rollingPeriod;
72
73 @Range(min = 0, max = 8, message = "Risk level must be between 0 and 8.")
74 private int transmissionRiskLevel;
75
76 private long submissionTimestamp;
77
78 protected DiagnosisKey() {
79 }
80
81 /**
82 * Should be called by builders.
83 */
84 DiagnosisKey(byte[] keyData, int rollingStartIntervalNumber, int rollingPeriod,
85 int transmissionRiskLevel, long submissionTimestamp) {
86 this.keyData = keyData;
87 this.rollingStartIntervalNumber = rollingStartIntervalNumber;
88 this.rollingPeriod = rollingPeriod;
89 this.transmissionRiskLevel = transmissionRiskLevel;
90 this.submissionTimestamp = submissionTimestamp;
91 }
92
93 /**
94 * Returns a DiagnosisKeyBuilder instance. A {@link DiagnosisKey} can then be build by either providing the required
95 * member values or by passing the respective protocol buffer object.
96 *
97 * @return DiagnosisKeyBuilder instance.
98 */
99 public static Builder builder() {
100 return new DiagnosisKeyBuilder();
101 }
102
103 public Long getId() {
104 return id;
105 }
106
107 /**
108 * Returns the diagnosis key.
109 */
110 public byte[] getKeyData() {
111 return keyData;
112 }
113
114 /**
115 * Returns a number describing when a key starts. It is equal to startTimeOfKeySinceEpochInSecs / (60 * 10).
116 */
117 public int getRollingStartIntervalNumber() {
118 return rollingStartIntervalNumber;
119 }
120
121 /**
122 * Returns a number describing how long a key is valid. It is expressed in increments of 10 minutes (e.g. 144 for 24
123 * hours).
124 */
125 public int getRollingPeriod() {
126 return rollingPeriod;
127 }
128
129 /**
130 * Returns the risk of transmission associated with the person this key came from.
131 */
132 public int getTransmissionRiskLevel() {
133 return transmissionRiskLevel;
134 }
135
136 /**
137 * Returns the timestamp associated with the submission of this {@link DiagnosisKey} as hours since epoch.
138 */
139 public long getSubmissionTimestamp() {
140 return submissionTimestamp;
141 }
142
143 /**
144 * Checks if this diagnosis key falls into the period between now, and the retention threshold.
145 *
146 * @param daysToRetain the number of days before a key is outdated
147 * @return true, if the rolling start interval number is within the time between now, and the given days to retain
148 * @throws IllegalArgumentException if {@code daysToRetain} is negative.
149 */
150 public boolean isYoungerThanRetentionThreshold(int daysToRetain) {
151 if (daysToRetain < 0) {
152 throw new IllegalArgumentException("Retention threshold must be greater or equal to 0.");
153 }
154 long threshold = LocalDateTime
155 .ofInstant(Instant.now(), UTC)
156 .minusDays(daysToRetain)
157 .toEpochSecond(UTC) / (60 * 10);
158
159 return this.rollingStartIntervalNumber >= threshold;
160 }
161
162 /**
163 * Gets any constraint violations that this key might incorporate.
164 *
165 * <p><ul>
166 * <li>Risk level must be between 0 and 8
167 * <li>Rolling start interval number must be greater than 0
168 * <li>Rolling start number cannot be in the future
169 * <li>Rolling period must be positive number
170 * <li>Key data must be byte array of length 16
171 * </ul>
172 *
173 * @return A set of constraint violations of this key.
174 */
175 public Set<ConstraintViolation<DiagnosisKey>> validate() {
176 return VALIDATOR.validate(this);
177 }
178
179 @Override
180 public boolean equals(Object o) {
181 if (this == o) {
182 return true;
183 }
184 if (o == null || getClass() != o.getClass()) {
185 return false;
186 }
187 DiagnosisKey that = (DiagnosisKey) o;
188 return rollingStartIntervalNumber == that.rollingStartIntervalNumber
189 && rollingPeriod == that.rollingPeriod
190 && transmissionRiskLevel == that.transmissionRiskLevel
191 && submissionTimestamp == that.submissionTimestamp
192 && Objects.equals(id, that.id)
193 && Arrays.equals(keyData, that.keyData);
194 }
195
196 @Override
197 public int hashCode() {
198 int result = Objects
199 .hash(id, rollingStartIntervalNumber, rollingPeriod, transmissionRiskLevel, submissionTimestamp);
200 result = 31 * result + Arrays.hashCode(keyData);
201 return result;
202 }
203 }
204
[end of common/persistence/src/main/java/app/coronawarn/server/common/persistence/domain/DiagnosisKey.java]
[start of common/persistence/src/main/java/app/coronawarn/server/common/persistence/repository/DiagnosisKeyRepository.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.common.persistence.repository;
22
23 import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
24 import org.springframework.data.jpa.repository.JpaRepository;
25 import org.springframework.stereotype.Repository;
26
27 @Repository
28 public interface DiagnosisKeyRepository extends JpaRepository<DiagnosisKey, Long> {
29
30 /**
31 * Deletes all entries that have a submission timestamp lesser or equal to the specified one.
32 *
33 * @param submissionTimestamp the submission timestamp up to which entries will be deleted.
34 */
35 void deleteBySubmissionTimestampIsLessThanEqual(long submissionTimestamp);
36 }
37
[end of common/persistence/src/main/java/app/coronawarn/server/common/persistence/repository/DiagnosisKeyRepository.java]
[start of common/persistence/src/main/java/app/coronawarn/server/common/persistence/service/DiagnosisKeyService.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.common.persistence.service;
22
23 import static java.time.ZoneOffset.UTC;
24
25 import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
26 import app.coronawarn.server.common.persistence.repository.DiagnosisKeyRepository;
27 import java.time.Instant;
28 import java.time.LocalDateTime;
29 import java.util.Collection;
30 import java.util.List;
31 import java.util.stream.Collectors;
32 import javax.validation.ConstraintViolation;
33 import org.slf4j.Logger;
34 import org.slf4j.LoggerFactory;
35 import org.springframework.beans.factory.annotation.Autowired;
36 import org.springframework.data.domain.Sort;
37 import org.springframework.data.domain.Sort.Direction;
38 import org.springframework.stereotype.Component;
39 import org.springframework.transaction.annotation.Transactional;
40
41 @Component
42 public class DiagnosisKeyService {
43
44 private static final Logger logger = LoggerFactory.getLogger(DiagnosisKeyService.class);
45 private final DiagnosisKeyRepository keyRepository;
46
47 @Autowired
48 public DiagnosisKeyService(DiagnosisKeyRepository keyRepository) {
49 this.keyRepository = keyRepository;
50 }
51
52 /**
53 * Persists the specified collection of {@link DiagnosisKey} instances.
54 *
55 * @param diagnosisKeys must not contain {@literal null}.
56 * @throws IllegalArgumentException in case the given collection contains {@literal null}.
57 */
58 public void saveDiagnosisKeys(Collection<DiagnosisKey> diagnosisKeys) {
59 keyRepository.saveAll(diagnosisKeys);
60 }
61
62 /**
63 * Returns all valid persisted diagnosis keys, sorted by their submission timestamp.
64 */
65 public List<DiagnosisKey> getDiagnosisKeys() {
66 return keyRepository.findAll(Sort.by(Direction.ASC, "submissionTimestamp")).stream()
67 .filter(DiagnosisKeyService::isDiagnosisKeyValid).collect(Collectors.toList());
68 }
69
70 private static boolean isDiagnosisKeyValid(DiagnosisKey diagnosisKey) {
71 Collection<ConstraintViolation<DiagnosisKey>> violations = diagnosisKey.validate();
72 boolean isValid = violations.isEmpty();
73
74 if (!isValid) {
75 List<String> violationMessages =
76 violations.stream().map(ConstraintViolation::getMessage).collect(Collectors.toList());
77 logger.warn("Validation failed for diagnosis key from database. Violations: {}", violationMessages);
78 }
79
80 return isValid;
81 }
82
83 /**
84 * Deletes all diagnosis key entries which have a submission timestamp that is older than the specified number of
85 * days.
86 *
87 * @param daysToRetain the number of days until which diagnosis keys will be retained.
88 * @throws IllegalArgumentException if {@code daysToRetain} is negative.
89 */
90 @Transactional
91 public void applyRetentionPolicy(int daysToRetain) {
92 if (daysToRetain < 0) {
93 throw new IllegalArgumentException("Number of days to retain must be greater or equal to 0.");
94 }
95
96 long threshold = LocalDateTime
97 .ofInstant(Instant.now(), UTC)
98 .minusDays(daysToRetain)
99 .toEpochSecond(UTC) / 3600L;
100 keyRepository.deleteBySubmissionTimestampIsLessThanEqual(threshold);
101 }
102 }
103
[end of common/persistence/src/main/java/app/coronawarn/server/common/persistence/service/DiagnosisKeyService.java]
</code>
Here is an example of a patch file. It consists of changes to the code base. It specifies the file names, the line numbers of each change, and the removed and added lines. A single patch file can contain changes to multiple files.
<patch>
--- a/file.py
+++ b/file.py
@@ -1,27 +1,35 @@
def euclidean(a, b):
- while b:
- a, b = b, a % b
- return a
+ if b == 0:
+ return a
+ return euclidean(b, a % b)
def bresenham(x0, y0, x1, y1):
points = []
dx = abs(x1 - x0)
dy = abs(y1 - y0)
- sx = 1 if x0 < x1 else -1
- sy = 1 if y0 < y1 else -1
- err = dx - dy
+ x, y = x0, y0
+ sx = -1 if x0 > x1 else 1
+ sy = -1 if y0 > y1 else 1
- while True:
- points.append((x0, y0))
- if x0 == x1 and y0 == y1:
- break
- e2 = 2 * err
- if e2 > -dy:
+ if dx > dy:
+ err = dx / 2.0
+ while x != x1:
+ points.append((x, y))
err -= dy
- x0 += sx
- if e2 < dx:
- err += dx
- y0 += sy
+ if err < 0:
+ y += sy
+ err += dx
+ x += sx
+ else:
+ err = dy / 2.0
+ while y != y1:
+ points.append((x, y))
+ err -= dx
+ if err < 0:
+ x += sx
+ err += dy
+ y += sy
+ points.append((x, y))
return points
</patch>
I need you to solve the provded issue by generating a single patch file that I can apply directly to this repository using git apply. Please respond with a single patch file in the format shown above.
Respond below:
| corona-warn-app/cwa-server | 00a342298942773ee49eeea9387a2acd164c3d49 | Ensure uniqueness of diagnosis keys
## Current Implementation
The uniqueness of diagnosis keys is neither guaranteed by the database, nor by validation logic.
## Suggested Enhancement
Ensure that diagnosis keys in the database are unique (there are no duplicates).
What needs to be decided:
- [x] Is it sufficient to guarantee the uniqueness of the diagnosis key or should the uniqueness of diagnosis key + submission timestamp (+maybe even more fields) be guaranteed?
- [x] Should the duplicate check happen on the database (`UNIQUE` constraint) or in the server logic (e.g. during the validation of submitted keys)?
- [x] If the check happens on the database: Should the `id` column be removed and replaced with the diagnosis key (+submission timestamp) as (composite) primary key?
- [x] How should the server react when a duplicate diagnosis key is submitted (update, error, etc.)?
**Edit:** Decisions are below.
| Decisions made by @christian-kirschnick:
- Ensuring the uniqueness of the diagnosis key is sufficient
- Duplicate check should happen on the database
- `id` column should be removed
- `key_data` column should become primary key
- If we encounter problems with the current type (`bytea`) of `key_data` as primary key, then change the type to a base64 encoded String
- When duplicate keys are submitted, the server should just ignore them (no update, no error).
@pithumke Was referenced back to here from a different issue, What would be the value of base64 encoding the UUID? it'll just take up even more space than even using char(32). there is a UUID type already in pg that'll give better seek performance and cost 16 bytes per entry instead of 32
About the risk of collision itself, with UUIDv4 that is quite unlikely even with billions of records, However if you don't want to suffer the occasional exception on the server side you can just add `ON CONFLICT DO NOTHING` to swallow the error
Hi @oiime, thank you for the remarks! Good point with the UUID type, I'll bring it up in the team discussions and report back. However, please note that, to my knowledge, the type of the diagnosis keys is not explicitly stated as UUID by the Google/Apple spec, but only as "Data" (see [here](https://developer.apple.com/documentation/exposurenotification/entemporaryexposurekey/3583679-keydata)) containing 16 bytes (see [here](https://www.blog.google/documents/60/Exposure_Notification_-_Cryptography_Specification_v1.1.pdf)). This can, in theory, be mapped to a UUID, but I would like to investigate if the PG UUID type implies any restrictions. For example, UUIDv4 reserves 6 of the 128 bits for version information, leaving only 122 bits for the payload (see [here](https://en.wikipedia.org/wiki/Universally_unique_identifier#Version_4_(random))) - and this would cause major problems for us.
Regarding the collisions: we currently also don't see this as a major risk. Our current strategy, as you proposed, is to simply ignore duplicates.
@pithumke Well, you're the one defining both the client and the server side, the EN API is agnostic to its content to allow that freedom of implementation, so you can define that key to be whatever you want it to be, currently you are validating it as UUID in the server and the test case generates a UUIDv4. the UUID data type follows RFC 4122 as you would expect and would naturally cover UUIDv4. All UUID versions reserve a place for version information. _please_ do not try to come up with your own UUID variant if that is what is suggested here
Hi @oiime, thank you for your comment.
> Well, you're the one defining both the client and the server side, the EN API is agnostic to its content to allow that freedom of implementation, so you can define that key to be whatever you want it to be
Yes, we do specify and develop both the CWA server and client. However, we neither specify nor develop the on-device APIs - that is done by Apple and Google. Inside those on-device APIs is where the keys are being generated and that does not give us much freedom regarding data types on our end. In the specification it is stated, that the key data consists of 16 bytes (= 128 bits). Since the use of UUID would restrict that to 122 bits, we can not use it as the column type on postgres.
> currently you are validating it as UUID in the server and the test case generates a UUIDv4
I am not aware of any UUID handling in our current code base, besides for TANs (which are not stored on the server). Can you please link which specific code you are referring to?
> please do not try to come up with your own UUID variant if that is what is suggested here
I didn't mean to suggest that and we don't want to come up with an own UUID variant. This is why we decided to go for a base64 encoded string for now (if bytea turns out to cause problems).
@pithumke
> However, we neither specify nor develop the on-device API
I guess I rely on looking at the API itself, perhaps apple or google or both have a specific implementation they mandate or suggest, if that is the case then using UUID is wrong anyway
> I am not aware of any UUID handling in our current code base, besides for TANs
I am likely conflating the two, I have only skimmed through the code and what I recalled was the test generating UUIDv4
> I didn't mean to suggest that and we don't want to come up with an own UUID variant. This is why we decided to go for a base64 encoded string for now (if bytea turns out to cause problems).
base64 seems like an unnecessary step that'll just take up more space and computation, you do it to avoid just storing it in a char(16) as-is? though I don't see why bytea wouldn't work as a PK, especially as you'd never update it
| 2020-05-30T23:22:36 | <patch>
diff --git a/common/persistence/pom.xml b/common/persistence/pom.xml
--- a/common/persistence/pom.xml
+++ b/common/persistence/pom.xml
@@ -78,7 +78,7 @@
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
- <version>1.4.199</version>
+ <version>1.4.200</version>
<scope>runtime</scope>
</dependency>
<dependency>
diff --git a/common/persistence/src/main/java/app/coronawarn/server/common/persistence/domain/DiagnosisKey.java b/common/persistence/src/main/java/app/coronawarn/server/common/persistence/domain/DiagnosisKey.java
--- a/common/persistence/src/main/java/app/coronawarn/server/common/persistence/domain/DiagnosisKey.java
+++ b/common/persistence/src/main/java/app/coronawarn/server/common/persistence/domain/DiagnosisKey.java
@@ -29,9 +29,8 @@
import java.util.Arrays;
import java.util.Objects;
import java.util.Set;
+import javax.persistence.Column;
import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.ConstraintViolation;
@@ -57,10 +56,8 @@ public class DiagnosisKey {
private static final Validator VALIDATOR = Validation.buildDefaultValidatorFactory().getValidator();
@Id
- @GeneratedValue(strategy = GenerationType.IDENTITY)
- private Long id;
-
@Size(min = 16, max = 16, message = "Key data must be a byte array of length 16.")
+ @Column(unique = true)
private byte[] keyData;
@ValidRollingStartIntervalNumber
@@ -100,10 +97,6 @@ public static Builder builder() {
return new DiagnosisKeyBuilder();
}
- public Long getId() {
- return id;
- }
-
/**
* Returns the diagnosis key.
*/
@@ -189,14 +182,13 @@ public boolean equals(Object o) {
&& rollingPeriod == that.rollingPeriod
&& transmissionRiskLevel == that.transmissionRiskLevel
&& submissionTimestamp == that.submissionTimestamp
- && Objects.equals(id, that.id)
&& Arrays.equals(keyData, that.keyData);
}
@Override
public int hashCode() {
int result = Objects
- .hash(id, rollingStartIntervalNumber, rollingPeriod, transmissionRiskLevel, submissionTimestamp);
+ .hash(rollingStartIntervalNumber, rollingPeriod, transmissionRiskLevel, submissionTimestamp);
result = 31 * result + Arrays.hashCode(keyData);
return result;
}
diff --git a/common/persistence/src/main/java/app/coronawarn/server/common/persistence/repository/DiagnosisKeyRepository.java b/common/persistence/src/main/java/app/coronawarn/server/common/persistence/repository/DiagnosisKeyRepository.java
--- a/common/persistence/src/main/java/app/coronawarn/server/common/persistence/repository/DiagnosisKeyRepository.java
+++ b/common/persistence/src/main/java/app/coronawarn/server/common/persistence/repository/DiagnosisKeyRepository.java
@@ -22,6 +22,8 @@
import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.Modifying;
+import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
@Repository
@@ -33,4 +35,22 @@ public interface DiagnosisKeyRepository extends JpaRepository<DiagnosisKey, Long
* @param submissionTimestamp the submission timestamp up to which entries will be deleted.
*/
void deleteBySubmissionTimestampIsLessThanEqual(long submissionTimestamp);
+
+ /**
+ * Attempts to write the specified diagnosis key information into the database. If a row with the specified key data
+ * already exists, no data is inserted.
+ *
+ * @param keyData The key data of the diagnosis key.
+ * @param rollingStartIntervalNumber The rolling start interval number of the diagnosis key.
+ * @param rollingPeriod The rolling period of the diagnosis key.
+ * @param submissionTimestamp The submission timestamp of the diagnosis key.
+ * @param transmissionRisk The transmission risk level of the diagnosis key.
+ */
+ @Modifying
+ @Query(nativeQuery = true, value =
+ "INSERT INTO diagnosis_key"
+ + "(key_data, rolling_start_interval_number, rolling_period, submission_timestamp, transmission_risk_level)"
+ + " VALUES(?, ?, ?, ?, ?) ON CONFLICT DO NOTHING;")
+ void saveDoNothingOnConflict(byte[] keyData, int rollingStartIntervalNumber, int rollingPeriod,
+ long submissionTimestamp, int transmissionRisk);
}
diff --git a/common/persistence/src/main/java/app/coronawarn/server/common/persistence/service/DiagnosisKeyService.java b/common/persistence/src/main/java/app/coronawarn/server/common/persistence/service/DiagnosisKeyService.java
--- a/common/persistence/src/main/java/app/coronawarn/server/common/persistence/service/DiagnosisKeyService.java
+++ b/common/persistence/src/main/java/app/coronawarn/server/common/persistence/service/DiagnosisKeyService.java
@@ -50,13 +50,19 @@ public DiagnosisKeyService(DiagnosisKeyRepository keyRepository) {
}
/**
- * Persists the specified collection of {@link DiagnosisKey} instances.
+ * Persists the specified collection of {@link DiagnosisKey} instances. If the key data of a particular diagnosis key
+ * already exists in the database, this diagnosis key is not persisted.
*
* @param diagnosisKeys must not contain {@literal null}.
* @throws IllegalArgumentException in case the given collection contains {@literal null}.
*/
+ @Transactional
public void saveDiagnosisKeys(Collection<DiagnosisKey> diagnosisKeys) {
- keyRepository.saveAll(diagnosisKeys);
+ for (DiagnosisKey diagnosisKey : diagnosisKeys) {
+ keyRepository.saveDoNothingOnConflict(
+ diagnosisKey.getKeyData(), diagnosisKey.getRollingStartIntervalNumber(), diagnosisKey.getRollingPeriod(),
+ diagnosisKey.getSubmissionTimestamp(), diagnosisKey.getTransmissionRiskLevel());
+ }
}
/**
diff --git a/common/persistence/src/main/resources/db/migration/h2/V3__makeKeyDataPrimaryKey.sql b/common/persistence/src/main/resources/db/migration/h2/V3__makeKeyDataPrimaryKey.sql
new file mode 100644
--- /dev/null
+++ b/common/persistence/src/main/resources/db/migration/h2/V3__makeKeyDataPrimaryKey.sql
@@ -0,0 +1,3 @@
+ALTER TABLE diagnosis_key DROP COLUMN id;
+ALTER TABLE diagnosis_key ALTER COLUMN key_data SET NOT NULL;
+ALTER TABLE diagnosis_key ADD PRIMARY KEY (key_data);
\ No newline at end of file
diff --git a/common/persistence/src/main/resources/db/migration/postgres/V3__makeKeyDataPrimaryKey.sql b/common/persistence/src/main/resources/db/migration/postgres/V3__makeKeyDataPrimaryKey.sql
new file mode 100644
--- /dev/null
+++ b/common/persistence/src/main/resources/db/migration/postgres/V3__makeKeyDataPrimaryKey.sql
@@ -0,0 +1,3 @@
+ALTER TABLE diagnosis_key DROP COLUMN id;
+ALTER TABLE diagnosis_key ALTER COLUMN key_data SET NOT NULL;
+ALTER TABLE diagnosis_key ADD PRIMARY KEY (key_data);
\ No newline at end of file
</patch> | diff --git a/common/persistence/src/test/java/app/coronawarn/server/common/persistence/service/DiagnosisKeyServiceTest.java b/common/persistence/src/test/java/app/coronawarn/server/common/persistence/service/DiagnosisKeyServiceTest.java
--- a/common/persistence/src/test/java/app/coronawarn/server/common/persistence/service/DiagnosisKeyServiceTest.java
+++ b/common/persistence/src/test/java/app/coronawarn/server/common/persistence/service/DiagnosisKeyServiceTest.java
@@ -33,6 +33,7 @@
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
+import java.util.Random;
import org.assertj.core.util.Lists;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.DisplayName;
@@ -149,9 +150,34 @@ void testNoPersistOnValidationError() {
assertDiagnosisKeysEqual(Lists.emptyList(), actKeys);
}
+ @Test
+ void shouldNotUpdateExistingKey() {
+ var keyData = "1234567890123456";
+ var keys = List.of(DiagnosisKey.builder()
+ .withKeyData(keyData.getBytes())
+ .withRollingStartIntervalNumber(600)
+ .withTransmissionRiskLevel(2)
+ .withSubmissionTimestamp(0L).build(),
+ DiagnosisKey.builder()
+ .withKeyData(keyData.getBytes())
+ .withRollingStartIntervalNumber(600)
+ .withTransmissionRiskLevel(3)
+ .withSubmissionTimestamp(0L).build());
+
+ diagnosisKeyService.saveDiagnosisKeys(keys);
+
+ var actKeys = diagnosisKeyService.getDiagnosisKeys();
+
+ assertThat(actKeys.size()).isEqualTo(1);
+ assertThat(actKeys.iterator().next().getTransmissionRiskLevel()).isEqualTo(2);
+ }
+
public static DiagnosisKey buildDiagnosisKeyForSubmissionTimestamp(long submissionTimeStamp) {
+ byte[] randomBytes = new byte[16];
+ Random random = new Random(submissionTimeStamp);
+ random.nextBytes(randomBytes);
return DiagnosisKey.builder()
- .withKeyData(new byte[16])
+ .withKeyData(randomBytes)
.withRollingStartIntervalNumber(600)
.withTransmissionRiskLevel(2)
.withSubmissionTimestamp(submissionTimeStamp).build();
diff --git a/common/persistence/src/test/resources/application.yaml b/common/persistence/src/test/resources/application.yaml
--- a/common/persistence/src/test/resources/application.yaml
+++ b/common/persistence/src/test/resources/application.yaml
@@ -1,5 +1,8 @@
---
spring:
+ test:
+ database:
+ replace: none
flyway:
enabled: false
jpa:
@@ -8,6 +11,10 @@ spring:
properties:
hibernate:
show_sql: false
+ datasource:
+ url: jdbc:h2:mem:test;MODE=PostgreSQL
+ driverClassName: org.h2.Driver
+ platform: h2
main:
banner-mode: off
logging:
diff --git a/services/submission/src/test/resources/application.yaml b/services/submission/src/test/resources/application.yaml
--- a/services/submission/src/test/resources/application.yaml
+++ b/services/submission/src/test/resources/application.yaml
@@ -11,7 +11,13 @@ spring:
enabled: true
# default case is H2 - value will be overwritten by profile cloud or postgres
locations: classpath:db/migration/h2
-
+ datasource:
+ url: jdbc:h2:mem:test;MODE=PostgreSQL
+ driverClassName: org.h2.Driver
+ platform: h2
+ test:
+ database:
+ replace: none
jpa:
hibernate:
ddl-auto: validate
| ||||
corona-warn-app__cwa-server-642 | You will be provided with a partial code base and an issue statement explaining a problem to resolve.
<issue>
[MINOR] Incorrect value range in attenuation risk parameter
## Describe the bug
The `AttenuationRiskParameters` proto message (see [here](https://github.com/corona-warn-app/cwa-server/blob/master/common/protocols/src/main/proto/app/coronawarn/server/common/protocols/internal/risk_score_parameters.proto)) is defined as follows:
```proto3
message AttenuationRiskParameters {
RiskLevel gt_73_dbm = 1; // A > 73 dBm, lowest risk
RiskLevel gt_63_le_73_dbm = 2; // 63 < A <= 73 dBm
RiskLevel gt_51_le_63_dbm = 3; // 51 < A <= 63 dBm
RiskLevel gt_33_le_51_dbm = 4; // 33 < A <= 51 dBm
RiskLevel gt_27_le_33_dbm = 5; // 27 < A <= 33 dBm
RiskLevel gt_15_le_27_dbm = 6; // 15 < A <= 27 dBm
RiskLevel gt_10_le_15_dbm = 7; // 10 < A <= 15 dBm
RiskLevel lt_10_dbm = 8; // A <= 10 dBm, highest risk
}
```
There is no value range that includes an attenuation of **exactly** 10dBm.
## Expected behaviour
According to the [Google/Apple spec](https://developer.apple.com/documentation/exposurenotification/enexposureconfiguration), the last value range should be "less than or equal to 10dBm" (`le_10_dbm`):
![image](https://user-images.githubusercontent.com/8984460/86034663-57f91580-ba3b-11ea-9444-e5020e6dcc46.png)
## Possible Fix
- Correct the last attenuation value range according to spec
- Update dependent code/configuration respectively ([here](https://github.com/corona-warn-app/cwa-server/blob/b8afdce9a3bc8fd927fe4ec9be2e910ee8f1635d/services/distribution/src/test/resources/objectstore/publisher/examplefile), [here](https://github.com/corona-warn-app/cwa-server/tree/b8afdce9a3bc8fd927fe4ec9be2e910ee8f1635d/services/distribution/src/test/resources/parameters), [here](https://github.com/corona-warn-app/cwa-server/tree/d6c0ad58f6473bd55af9a0cbe2c0cc8db3914af6/services/distribution/src/main/resources/master-config) and possibly more).
## Additional context
- This "bug" doesn't have any technical implications and should only be fixed for consistency
- Downwards-compatibility of the proto messages should not be infringed by the proposed change
</issue>
<code>
[start of README.md]
1 <!-- markdownlint-disable MD041 -->
2 <h1 align="center">
3 Corona-Warn-App Server
4 </h1>
5
6 <p align="center">
7 <a href="https://github.com/corona-warn-app/cwa-server/commits/" title="Last Commit"><img src="https://img.shields.io/github/last-commit/corona-warn-app/cwa-server?style=flat"></a>
8 <a href="https://github.com/corona-warn-app/cwa-server/issues" title="Open Issues"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat"></a>
9 <a href="https://circleci.com/gh/corona-warn-app/cwa-server" title="Build Status"><img src="https://circleci.com/gh/corona-warn-app/cwa-server.svg?style=shield&circle-token=4ab059989d10709df19eb4b98ab7c121a25e981a"></a>
10 <a href="https://sonarcloud.io/dashboard?id=corona-warn-app_cwa-server" title="Quality Gate"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=alert_status"></a>
11 <a href="https://sonarcloud.io/component_measures?id=corona-warn-app_cwa-server&metric=Coverage&view=list" title="Coverage"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=coverage"></a>
12 <a href="https://github.com/corona-warn-app/cwa-server/blob/master/LICENSE" title="License"><img src="https://img.shields.io/badge/License-Apache%202.0-green.svg?style=flat"></a>
13 </p>
14
15 <p align="center">
16 <a href="#development">Development</a> •
17 <a href="#service-apis">Service APIs</a> •
18 <a href="#documentation">Documentation</a> •
19 <a href="#support-and-feedback">Support</a> •
20 <a href="#how-to-contribute">Contribute</a> •
21 <a href="#contributors">Contributors</a> •
22 <a href="#repositories">Repositories</a> •
23 <a href="#licensing">Licensing</a>
24 </p>
25
26 The goal of this project is to develop the official Corona-Warn-App for Germany based on the exposure notification API from [Apple](https://www.apple.com/covid19/contacttracing/) and [Google](https://www.google.com/covid19/exposurenotifications/). The apps (for both iOS and Android) use Bluetooth technology to exchange anonymous encrypted data with other mobile phones (on which the app is also installed) in the vicinity of an app user's phone. The data is stored locally on each user's device, preventing authorities or other parties from accessing or controlling the data. This repository contains the **implementation of the server for encryption keys** for the Corona-Warn-App.
27
28 In this documentation, Corona-Warn-App services are also referred to as CWA services.
29
30 ## Architecture Overview
31
32 You can find the architecture overview [here](/docs/ARCHITECTURE.md), which will give you
33 a good starting point in how the backend services interact with other services, and what purpose
34 they serve.
35
36 ## Development
37
38 After you've checked out this repository, you can run the application in one of the following ways:
39
40 * As a [Docker](https://www.docker.com/)-based deployment on your local machine. You can run either:
41 * Single components using the respective Dockerfile or
42 * The full backend using the Docker Compose (which is considered the most convenient way)
43 * As a [Maven](https://maven.apache.org)-based build on your local machine.
44 If you want to develop something in a single component, this approach is preferable.
45
46 ### Docker-Based Deployment
47
48 If you want to use Docker-based deployment, you need to install Docker on your local machine. For more information about downloading and installing Docker, see the [official Docker documentation](https://docs.docker.com/get-docker/).
49
50 #### Running the Full CWA Backend Using Docker Compose
51
52 For your convenience, a full setup including the generation of test data has been prepared using [Docker Compose](https://docs.docker.com/compose/reference/overview/). To build the backend services, run ```docker-compose build``` in the repository's root directory. A default configuration file can be found under ```.env``` in the root folder of the repository. The default values for the local Postgres and Zenko Cloudserver should be changed in this file before docker-compose is run.
53
54 Once the services are built, you can start the whole backend using ```docker-compose up```.
55 The distribution service runs once and then finishes. If you want to trigger additional distribution runs, run ```docker-compose run distribution```.
56
57 The docker-compose contains the following services:
58
59 Service | Description | Endpoint and Default Credentials
60 ------------------|-------------|-----------
61 submission | The Corona-Warn-App submission service | `http://localhost:8000` <br> `http://localhost:8006` (for actuator endpoint)
62 distribution | The Corona-Warn-App distribution service | NO ENDPOINT
63 postgres | A [postgres] database installation | `localhost:8001` <br> `postgres:5432` (from containerized pgadmin) <br> Username: postgres <br> Password: postgres
64 pgadmin | A [pgadmin](https://www.pgadmin.org/) installation for the postgres database | `http://localhost:8002` <br> Username: [email protected] <br> Password: password
65 cloudserver | [Zenko CloudServer] is a S3-compliant object store | `http://localhost:8003/` <br> Access key: accessKey1 <br> Secret key: verySecretKey1
66 verification-fake | A very simple fake implementation for the tan verification. | `http://localhost:8004/version/v1/tan/verify` <br> The only valid tan is `edc07f08-a1aa-11ea-bb37-0242ac130002`.
67
68 ##### Known Limitation
69
70 In rare cases the docker-compose runs into a timing issue if the distribution service starts before the bucket of the objectstore was created. This is not a big issue as you can simply run ```docker-compose run distribution``` to trigger additional distribution runs after the objectstore was initialized.
71
72 #### Running Single CWA Services Using Docker
73
74 If you would like to build and run a single CWA service, it's considered easiest to run them in a Docker environment. You can do this using the script provided in the respective CWA service directory. The Docker script first builds the CWA service and then creates an image for the runtime, which means that there are no additional dependencies for you to install.
75
76 To build and run the distribution service, run the following command:
77
78 ```bash
79 ./services/distribution/build_and_run.sh
80 ```
81
82 To build and run the submission service, run the following command:
83
84 ```bash
85 ./services/submission/build_and_run.sh
86 ```
87
88 The submission service is available on [localhost:8080](http://localhost:8080 ).
89
90 ### Maven-Based Build
91
92 If you want to actively develop in one of the CWA services, the Maven-based runtime is most suitable.
93 To prepare your machine to run the CWA project locally, we recommend that you first ensure that you've installed the following:
94
95 * Minimum JDK Version 11: [OpenJDK](https://openjdk.java.net/) / [SapMachine](https://sap.github.io/SapMachine/)
96 * [Maven 3.6](https://maven.apache.org/)
97 * [Postgres]
98 * [Zenko CloudServer]
99
100 If you are already running a local Postgres, you need to create a database `cwa` and run the following setup scripts:
101
102 * Create the different CWA roles first by executing [create-roles.sql](setup/create-roles.sql).
103 * Create local database users for the specific roles by running [create-users.sql](./local-setup/create-users.sql).
104 * It is recommended to also run [enable-test-data-docker-compose.sql](./local-setup/enable-test-data-docker-compose.sql)
105 , which enables the test data generation profile. If you already had CWA running before and an existing `diagnosis-key`
106 table on your database, you need to run [enable-test-data.sql](./local-setup/enable-test-data.sql) instead.
107
108 You can also use `docker-compose` to start Postgres and Zenko. If you do that, you have to
109 set the following environment-variables when running the Spring project:
110
111 For the distribution module:
112
113 ```bash
114 POSTGRESQL_SERVICE_PORT=8001
115 VAULT_FILESIGNING_SECRET=</path/to/your/private_key>
116 SPRING_PROFILES_ACTIVE=signature-dev,disable-ssl-client-postgres
117 ```
118
119 For the submission module:
120
121 ```bash
122 POSTGRESQL_SERVICE_PORT=8001
123 SPRING_PROFILES_ACTIVE=disable-ssl-server,disable-ssl-client-postgres,disable-ssl-client-verification,disable-ssl-client-verification-verify-hostname
124 ```
125
126 #### Configure
127
128 After you made sure that the specified dependencies are running, configure them in the respective configuration files.
129
130 * Configure the Postgres connection in the [submission config](./services/submission/src/main/resources/application.yaml) and in the [distribution config](./services/distribution/src/main/resources/application.yaml)
131 * Configure the S3 compatible object storage in the [distribution config](./services/distribution/src/main/resources/application.yaml)
132 * Configure the private key for the distribution service, the path need to be prefixed with `file:`
133 * `VAULT_FILESIGNING_SECRET` should be the path to the private key, example available in `<repo-root>/docker-compose-test-secrets/private.pem`
134
135 #### Build
136
137 After you've checked out the repository, to build the project, run ```mvn install``` in your base directory.
138
139 #### Run
140
141 Navigate to the service you want to start and run the spring-boot:run target. The configured Postgres and the configured S3 compliant object storage are used as default. When you start the submission service, the endpoint is available on your local port 8080.
142
143 If you want to start the submission service, for example, you start it as follows:
144
145 ```bash
146 cd services/submission/
147 mvn spring-boot:run
148 ```
149
150 #### Debugging
151
152 To enable the `DEBUG` log level, you can run the application using the Spring `dev` profile.
153
154 ```bash
155 mvn spring-boot:run -Dspring.profiles.active=dev
156 ```
157
158 To be able to set breakpoints (e.g. in IntelliJ), it may be necessary to use the ```-Dspring-boot.run.fork=false``` parameter.
159
160 ## Service APIs
161
162 The API that is being exposed by the backend services is documented in an [OpenAPI](https://www.openapis.org/) specification. The specification files are available at the following locations:
163
164 Service | OpenAPI Specification
165 --------------------------|-------------
166 Submission Service | [services/submission/api_v1.json](https://github.com/corona-warn-app/cwa-server/raw/master/services/submission/api_v1.json)
167 Distribution Service | [services/distribution/api_v1.json](https://github.com/corona-warn-app/cwa-server/raw/master/services/distribution/api_v1.json)
168
169 ## Spring Profiles
170
171 ### Distribution
172
173 See [Distribution Service - Spring Profiles](/docs/DISTRIBUTION.md#spring-profiles).
174
175 ### Submission
176
177 See [Submission Service - Spring Profiles](/docs/SUBMISSION.md#spring-profiles).
178
179 ## Documentation
180
181 The full documentation for the Corona-Warn-App can be found in the [cwa-documentation](https://github.com/corona-warn-app/cwa-documentation) repository. The documentation repository contains technical documents, architecture information, and whitepapers related to this implementation.
182
183 The documentation for cwa-server can be found under the [/docs](./docs) folder.
184
185 The JavaDoc documentation for cwa-server is hosted by Github Pages at [https://corona-warn-app.github.io/cwa-server](https://corona-warn-app.github.io/cwa-server).
186
187 ## Support and Feedback
188
189 The following channels are available for discussions, feedback, and support requests:
190
191 | Type | Channel |
192 | ------------------------ | ------------------------------------------------------ |
193 | **General Discussion** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="General Discussion"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/question.svg?style=flat-square"></a> </a> |
194 | **Concept Feedback** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="Open Concept Feedback"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/architecture.svg?style=flat-square"></a> |
195 | **Backend Issue** | <a href="https://github.com/corona-warn-app/cwa-server/issues/new/choose" title="Open Backend Issue"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat-square"></a> |
196 | **Other Requests** | <a href="mailto:[email protected]" title="Email CWA Team"><img src="https://img.shields.io/badge/email-CWA%20team-green?logo=mail.ru&style=flat-square&logoColor=white"></a> |
197
198 ## How to Contribute
199
200 Contribution and feedback are 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.
201
202 ## Contributors
203
204 The German government has asked SAP and Deutsche Telekom to develop the Corona-Warn-App for Germany as open source software. Deutsche Telekom is providing the network and mobile technology and will operate and run the backend for the app in a safe, scalable and stable manner. SAP is responsible for the app development, its framework and the underlying platform. Therefore, development teams of SAP and Deutsche Telekom are contributing to this project. At the same time 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.
205
206 ## Repositories
207
208 The following public repositories are currently available for the Corona-Warn-App:
209
210 | Repository | Description |
211 | ------------------- | --------------------------------------------------------------------- |
212 | [cwa-documentation] | Project overview, general documentation, and white papers |
213 | [cwa-server] | Backend implementation for the Apple/Google exposure notification API|
214 | [cwa-verification-server] | Backend implementation of the verification process|
215
216 [cwa-documentation]: https://github.com/corona-warn-app/cwa-documentation
217 [cwa-server]: https://github.com/corona-warn-app/cwa-server
218 [cwa-verification-server]: https://github.com/corona-warn-app/cwa-verification-server
219 [Postgres]: https://www.postgresql.org/
220 [HSQLDB]: http://hsqldb.org/
221 [Zenko CloudServer]: https://github.com/scality/cloudserver
222
223 ## Licensing
224
225 Copyright (c) 2020 SAP SE or an SAP affiliate company.
226
227 Licensed under the **Apache License, Version 2.0** (the "License"); you may not use this file except in compliance with the License.
228
229 You may obtain a copy of the License at <https://www.apache.org/licenses/LICENSE-2.0>.
230
231 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.
232
[end of README.md]
[start of common/protocols/src/main/proto/app/coronawarn/server/common/protocols/internal/risk_score_parameters.proto]
1 // See page 15:
2 // https://covid19-static.cdn-apple.com/applications/covid19/current/static/contact-tracing/pdf/ExposureNotification-FrameworkDocumentationv1.2.pdf
3 syntax = "proto3";
4 package app.coronawarn.server.common.protocols.internal;
5 option java_package = "app.coronawarn.server.common.protocols.internal";
6 option java_multiple_files = true;
7 import "app/coronawarn/server/common/protocols/internal/risk_level.proto";
8
9 message RiskScoreParameters {
10
11 // App-specific mapping
12 TransmissionRiskParameters transmission = 1;
13 double transmission_weight= 2;
14
15 DurationRiskParameters duration = 3;
16 double duration_weight= 4;
17
18 DaysSinceLastExposureRiskParameters days_since_last_exposure = 5;
19 double days_weight= 6;
20
21 AttenuationRiskParameters attenuation = 7;
22 double attenuation_weight= 8;
23
24 message TransmissionRiskParameters {
25 RiskLevel app_defined_1 = 1;
26 RiskLevel app_defined_2 = 2;
27 RiskLevel app_defined_3 = 3;
28 RiskLevel app_defined_4 = 4;
29 RiskLevel app_defined_5 = 5;
30 RiskLevel app_defined_6 = 6;
31 RiskLevel app_defined_7 = 7;
32 RiskLevel app_defined_8 = 8;
33 }
34 message DurationRiskParameters {
35 RiskLevel eq_0_min = 1; // D = 0 min, lowest risk
36 RiskLevel gt_0_le_5_min = 2; // 0 < D <= 5 min
37 RiskLevel gt_5_le_10_min = 3; // 5 < D <= 10 min
38 RiskLevel gt_10_le_15_min = 4; // 10 < D <= 15 min
39 RiskLevel gt_15_le_20_min = 5; // 15 < D <= 20 min
40 RiskLevel gt_20_le_25_min = 6; // 20 < D <= 25 min
41 RiskLevel gt_25_le_30_min = 7; // 25 < D <= 30 min
42 RiskLevel gt_30_min = 8; // > 30 min, highest risk
43 }
44 message DaysSinceLastExposureRiskParameters {
45 RiskLevel ge_14_days = 1; // D >= 14 days, lowest risk
46 RiskLevel ge_12_lt_14_days = 2; // 12 <= D < 14 days
47 RiskLevel ge_10_lt_12_days = 3; // 10 <= D < 12 days
48 RiskLevel ge_8_lt_10_days = 4; // 8 <= D < 10 days
49 RiskLevel ge_6_lt_8_days = 5; // 6 <= D < 8 days
50 RiskLevel ge_4_lt_6_days = 6; // 4 <= D < 6 days
51 RiskLevel ge_2_lt_4_days = 7; // 2 <= D < 4 days
52 RiskLevel ge_0_lt_2_days = 8; // 0 <= D < 2 days, highest risk
53 }
54 message AttenuationRiskParameters {
55 RiskLevel gt_73_dbm = 1; // A > 73 dBm, lowest risk
56 RiskLevel gt_63_le_73_dbm = 2; // 63 < A <= 73 dBm
57 RiskLevel gt_51_le_63_dbm = 3; // 51 < A <= 63 dBm
58 RiskLevel gt_33_le_51_dbm = 4; // 33 < A <= 51 dBm
59 RiskLevel gt_27_le_33_dbm = 5; // 27 < A <= 33 dBm
60 RiskLevel gt_15_le_27_dbm = 6; // 15 < A <= 27 dBm
61 RiskLevel gt_10_le_15_dbm = 7; // 10 < A <= 15 dBm
62 RiskLevel lt_10_dbm = 8; // A <= 10 dBm, highest risk
63 }
64 }
[end of common/protocols/src/main/proto/app/coronawarn/server/common/protocols/internal/risk_score_parameters.proto]
[start of services/distribution/src/main/resources/master-config/exposure-config.yaml]
1 # This is the Exposure Config master file which defines the risk parameters for the mobile clients
2 # Change this file with caution.
3 #
4 # Weights must be in range of 0.001 to 100
5 # Parameter Scores must be in range of 0 to 8.
6 #
7 # Further documentation:
8 # https://developer.apple.com/documentation/exposurenotification/enexposureconfiguration
9 #
10
11 # Weight Section
12
13 transmission_weight: 50
14 duration_weight: 50
15 attenuation_weight: 50
16 days_weight: 20
17
18 # Parameters Section
19
20 transmission:
21 app_defined_1: 1
22 app_defined_2: 2
23 app_defined_3: 3
24 app_defined_4: 4
25 app_defined_5: 5
26 app_defined_6: 6
27 app_defined_7: 7
28 app_defined_8: 8
29
30 duration:
31 eq_0_min: 0
32 gt_0_le_5_min: 0
33 gt_5_le_10_min: 0
34 gt_10_le_15_min: 1
35 gt_15_le_20_min: 1
36 gt_20_le_25_min: 1
37 gt_25_le_30_min: 1
38 gt_30_min: 1
39
40 days_since_last_exposure:
41 ge_14_days: 5
42 ge_12_lt_14_days: 5
43 ge_10_lt_12_days: 5
44 ge_8_lt_10_days: 5
45 ge_6_lt_8_days: 5
46 ge_4_lt_6_days: 5
47 ge_2_lt_4_days: 5
48 ge_0_lt_2_days: 5
49
50 attenuation:
51 gt_73_dbm: 0
52 gt_63_le_73_dbm: 1
53 gt_51_le_63_dbm: 1
54 gt_33_le_51_dbm: 1
55 gt_27_le_33_dbm: 1
56 gt_15_le_27_dbm: 1
57 gt_10_le_15_dbm: 1
58 lt_10_dbm: 1
59
[end of services/distribution/src/main/resources/master-config/exposure-config.yaml]
</code>
Here is an example of a patch file. It consists of changes to the code base. It specifies the file names, the line numbers of each change, and the removed and added lines. A single patch file can contain changes to multiple files.
<patch>
--- a/file.py
+++ b/file.py
@@ -1,27 +1,35 @@
def euclidean(a, b):
- while b:
- a, b = b, a % b
- return a
+ if b == 0:
+ return a
+ return euclidean(b, a % b)
def bresenham(x0, y0, x1, y1):
points = []
dx = abs(x1 - x0)
dy = abs(y1 - y0)
- sx = 1 if x0 < x1 else -1
- sy = 1 if y0 < y1 else -1
- err = dx - dy
+ x, y = x0, y0
+ sx = -1 if x0 > x1 else 1
+ sy = -1 if y0 > y1 else 1
- while True:
- points.append((x0, y0))
- if x0 == x1 and y0 == y1:
- break
- e2 = 2 * err
- if e2 > -dy:
+ if dx > dy:
+ err = dx / 2.0
+ while x != x1:
+ points.append((x, y))
err -= dy
- x0 += sx
- if e2 < dx:
- err += dx
- y0 += sy
+ if err < 0:
+ y += sy
+ err += dx
+ x += sx
+ else:
+ err = dy / 2.0
+ while y != y1:
+ points.append((x, y))
+ err -= dx
+ if err < 0:
+ x += sx
+ err += dy
+ y += sy
+ points.append((x, y))
return points
</patch>
I need you to solve the provded issue by generating a single patch file that I can apply directly to this repository using git apply. Please respond with a single patch file in the format shown above.
Respond below:
| corona-warn-app/cwa-server | fa9adc6631233172684910191efdf00429799365 | [MINOR] Incorrect value range in attenuation risk parameter
## Describe the bug
The `AttenuationRiskParameters` proto message (see [here](https://github.com/corona-warn-app/cwa-server/blob/master/common/protocols/src/main/proto/app/coronawarn/server/common/protocols/internal/risk_score_parameters.proto)) is defined as follows:
```proto3
message AttenuationRiskParameters {
RiskLevel gt_73_dbm = 1; // A > 73 dBm, lowest risk
RiskLevel gt_63_le_73_dbm = 2; // 63 < A <= 73 dBm
RiskLevel gt_51_le_63_dbm = 3; // 51 < A <= 63 dBm
RiskLevel gt_33_le_51_dbm = 4; // 33 < A <= 51 dBm
RiskLevel gt_27_le_33_dbm = 5; // 27 < A <= 33 dBm
RiskLevel gt_15_le_27_dbm = 6; // 15 < A <= 27 dBm
RiskLevel gt_10_le_15_dbm = 7; // 10 < A <= 15 dBm
RiskLevel lt_10_dbm = 8; // A <= 10 dBm, highest risk
}
```
There is no value range that includes an attenuation of **exactly** 10dBm.
## Expected behaviour
According to the [Google/Apple spec](https://developer.apple.com/documentation/exposurenotification/enexposureconfiguration), the last value range should be "less than or equal to 10dBm" (`le_10_dbm`):
![image](https://user-images.githubusercontent.com/8984460/86034663-57f91580-ba3b-11ea-9444-e5020e6dcc46.png)
## Possible Fix
- Correct the last attenuation value range according to spec
- Update dependent code/configuration respectively ([here](https://github.com/corona-warn-app/cwa-server/blob/b8afdce9a3bc8fd927fe4ec9be2e910ee8f1635d/services/distribution/src/test/resources/objectstore/publisher/examplefile), [here](https://github.com/corona-warn-app/cwa-server/tree/b8afdce9a3bc8fd927fe4ec9be2e910ee8f1635d/services/distribution/src/test/resources/parameters), [here](https://github.com/corona-warn-app/cwa-server/tree/d6c0ad58f6473bd55af9a0cbe2c0cc8db3914af6/services/distribution/src/main/resources/master-config) and possibly more).
## Additional context
- This "bug" doesn't have any technical implications and should only be fixed for consistency
- Downwards-compatibility of the proto messages should not be infringed by the proposed change
| 2020-07-01T11:58:13 | <patch>
diff --git a/common/protocols/src/main/proto/app/coronawarn/server/common/protocols/internal/risk_score_parameters.proto b/common/protocols/src/main/proto/app/coronawarn/server/common/protocols/internal/risk_score_parameters.proto
--- a/common/protocols/src/main/proto/app/coronawarn/server/common/protocols/internal/risk_score_parameters.proto
+++ b/common/protocols/src/main/proto/app/coronawarn/server/common/protocols/internal/risk_score_parameters.proto
@@ -59,6 +59,6 @@ message RiskScoreParameters {
RiskLevel gt_27_le_33_dbm = 5; // 27 < A <= 33 dBm
RiskLevel gt_15_le_27_dbm = 6; // 15 < A <= 27 dBm
RiskLevel gt_10_le_15_dbm = 7; // 10 < A <= 15 dBm
- RiskLevel lt_10_dbm = 8; // A <= 10 dBm, highest risk
+ RiskLevel le_10_dbm = 8; // A <= 10 dBm, highest risk
}
-}
\ No newline at end of file
+}
diff --git a/services/distribution/src/main/resources/master-config/exposure-config.yaml b/services/distribution/src/main/resources/master-config/exposure-config.yaml
--- a/services/distribution/src/main/resources/master-config/exposure-config.yaml
+++ b/services/distribution/src/main/resources/master-config/exposure-config.yaml
@@ -55,4 +55,4 @@ attenuation:
gt_27_le_33_dbm: 1
gt_15_le_27_dbm: 1
gt_10_le_15_dbm: 1
- lt_10_dbm: 1
+ le_10_dbm: 1
</patch> | diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/YamlLoaderTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/YamlLoaderTest.java
--- a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/YamlLoaderTest.java
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/YamlLoaderTest.java
@@ -40,8 +40,9 @@ void okFile() throws UnableToLoadFileException {
@ValueSource(strings = {
"configtests/app-config_empty.yaml",
"configtests/wrong_file.yaml",
- "configtests/broken_syntax.yaml",
- "file_does_not_exist_anywhere.yaml"
+ "configtests/app-config_broken_syntax.yaml",
+ "configtests/naming_mismatch.yaml",
+ "configtests/file_does_not_exist_anywhere.yaml"
})
void throwsLoadFailure(String fileName) {
assertThatExceptionOfType(UnableToLoadFileException.class).isThrownBy(() -> loadApplicationConfiguration(fileName));
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ExposureConfigurationValidatorTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ExposureConfigurationValidatorTest.java
--- a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ExposureConfigurationValidatorTest.java
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ExposureConfigurationValidatorTest.java
@@ -22,8 +22,7 @@
import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.ExposureConfigurationValidator.CONFIG_PREFIX;
import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.RiskScoreClassificationValidatorTest.buildError;
-import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.ValidationError.ErrorType.TOO_MANY_DECIMAL_PLACES;
-import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.ValidationError.ErrorType.VALUE_OUT_OF_BOUNDS;
+import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.ValidationError.ErrorType.*;
import static org.assertj.core.api.Assertions.assertThat;
import app.coronawarn.server.common.protocols.internal.RiskLevel;
diff --git a/services/distribution/src/test/resources/configtests/exposure-config_ok.yaml b/services/distribution/src/test/resources/configtests/exposure-config_ok.yaml
--- a/services/distribution/src/test/resources/configtests/exposure-config_ok.yaml
+++ b/services/distribution/src/test/resources/configtests/exposure-config_ok.yaml
@@ -55,4 +55,4 @@ attenuation:
gt_27_le_33_dbm: 5
gt_15_le_27_dbm: 6
gt_10_le_15_dbm: 7
- lt_10_dbm: 8
\ No newline at end of file
+ le_10_dbm: 8
diff --git a/services/distribution/src/test/resources/configtests/naming_mismatch.yaml b/services/distribution/src/test/resources/configtests/naming_mismatch.yaml
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/test/resources/configtests/naming_mismatch.yaml
@@ -0,0 +1,43 @@
+transmission_weight: 10.001
+duration_weight: 0.001
+attenuation_weight: 100
+
+transmission:
+ foo: 2 # "foo" does not exist in proto
+ app_defined_2: 2
+ app_defined_3: 3
+ app_defined_4: 4
+ app_defined_5: 5
+ app_defined_6: 6
+ app_defined_7: 7
+ app_defined_8: 8
+
+duration:
+ eq_0_min: 1
+ gt_0_le_5_min: 2
+ gt_5_le_10_min: 3
+ gt_10_le_15_min: 4
+ gt_15_le_20_min: 5
+ gt_20_le_25_min: 6
+ gt_25_le_30_min: 7
+ gt_30_min: 8
+
+days_since_last_exposure:
+ ge_14_days: 1
+ ge_12_lt_14_days: 2
+ ge_10_lt_12_days: 3
+ ge_8_lt_10_days: 4
+ ge_6_lt_8_days: 5
+ ge_4_lt_6_days: 6
+ ge_2_lt_4_days: 7
+ ge_0_lt_2_days: 8
+
+attenuation:
+ gt_73_dbm: 1
+ gt_63_le_73_dbm: 2
+ gt_51_le_63_dbm: 3
+ gt_33_le_51_dbm: 4
+ gt_27_le_33_dbm: 5
+ gt_15_le_27_dbm: 6
+ gt_10_le_15_dbm: 7
+ le_10_dbm: 8
diff --git a/services/distribution/src/test/resources/objectstore/publisher/examplefile b/services/distribution/src/test/resources/objectstore/publisher/examplefile
--- a/services/distribution/src/test/resources/objectstore/publisher/examplefile
+++ b/services/distribution/src/test/resources/objectstore/publisher/examplefile
@@ -43,4 +43,4 @@ attenuation:
gt_27_le_33_dbm: 5
gt_15_le_27_dbm: 6
gt_10_le_15_dbm: 7
- lt_10_dbm: 8
\ No newline at end of file
+ le_10_dbm: 8
diff --git a/services/distribution/src/test/resources/parameters/all_ok.yaml b/services/distribution/src/test/resources/parameters/all_ok.yaml
--- a/services/distribution/src/test/resources/parameters/all_ok.yaml
+++ b/services/distribution/src/test/resources/parameters/all_ok.yaml
@@ -43,4 +43,4 @@ attenuation:
gt_27_le_33_dbm: 5
gt_15_le_27_dbm: 6
gt_10_le_15_dbm: 7
- lt_10_dbm: 8
\ No newline at end of file
+ le_10_dbm: 8
diff --git a/services/distribution/src/test/resources/parameters/broken_syntax.yaml b/services/distribution/src/test/resources/parameters/broken_syntax.yaml
--- a/services/distribution/src/test/resources/parameters/broken_syntax.yaml
+++ b/services/distribution/src/test/resources/parameters/broken_syntax.yaml
@@ -40,4 +40,4 @@ attenuation:
gt_27_le_33_dbm: 5
gt_15_le_27_dbm: 6
gt_10_le_15_dbm: 7
- lt_10_dbm: 8
\ No newline at end of file
+ le_10_dbm: 8
diff --git a/services/distribution/src/test/resources/parameters/partly_filled.yaml b/services/distribution/src/test/resources/parameters/partly_filled.yaml
--- a/services/distribution/src/test/resources/parameters/partly_filled.yaml
+++ b/services/distribution/src/test/resources/parameters/partly_filled.yaml
@@ -43,4 +43,4 @@ attenuation:
gt_27_le_33_dbm: 5
gt_15_le_27_dbm: 6
gt_10_le_15_dbm: 7
- lt_10_dbm: 8
\ No newline at end of file
+ le_10_dbm: 8
diff --git a/services/distribution/src/test/resources/parameters/score_too_high.yaml b/services/distribution/src/test/resources/parameters/score_too_high.yaml
--- a/services/distribution/src/test/resources/parameters/score_too_high.yaml
+++ b/services/distribution/src/test/resources/parameters/score_too_high.yaml
@@ -40,4 +40,4 @@ attenuation:
gt_27_le_33_dbm: 5
gt_15_le_27_dbm: 6
gt_10_le_15_dbm: 7
- lt_10_dbm: 8
\ No newline at end of file
+ le_10_dbm: 8
diff --git a/services/distribution/src/test/resources/parameters/weight_negative.yaml b/services/distribution/src/test/resources/parameters/weight_negative.yaml
--- a/services/distribution/src/test/resources/parameters/weight_negative.yaml
+++ b/services/distribution/src/test/resources/parameters/weight_negative.yaml
@@ -41,4 +41,4 @@ attenuation:
gt_27_le_33_dbm: 5
gt_15_le_27_dbm: 6
gt_10_le_15_dbm: 7
- lt_10_dbm: 8
\ No newline at end of file
+ le_10_dbm: 8
diff --git a/services/distribution/src/test/resources/parameters/weight_ok.yaml b/services/distribution/src/test/resources/parameters/weight_ok.yaml
--- a/services/distribution/src/test/resources/parameters/weight_ok.yaml
+++ b/services/distribution/src/test/resources/parameters/weight_ok.yaml
@@ -40,4 +40,4 @@ attenuation:
gt_27_le_33_dbm: 5
gt_15_le_27_dbm: 6
gt_10_le_15_dbm: 7
- lt_10_dbm: 8
\ No newline at end of file
+ le_10_dbm: 8
diff --git a/services/distribution/src/test/resources/parameters/weight_too_high.yaml b/services/distribution/src/test/resources/parameters/weight_too_high.yaml
--- a/services/distribution/src/test/resources/parameters/weight_too_high.yaml
+++ b/services/distribution/src/test/resources/parameters/weight_too_high.yaml
@@ -40,4 +40,4 @@ attenuation:
gt_27_le_33_dbm: 5
gt_15_le_27_dbm: 6
gt_10_le_15_dbm: 7
- lt_10_dbm: 8
\ No newline at end of file
+ le_10_dbm: 8
| |||||
corona-warn-app__cwa-server-350 | You will be provided with a partial code base and an issue statement explaining a problem to resolve.
<issue>
Blank URL in RiskScoreClassificationValidator
In `app.coronawarn.server.services.distribution.assembly.appconfig.validation.RiskScoreClassificationValidator#validateUrl` [(link to source code)](https://github.com/corona-warn-app/cwa-server/blob/63dda0c2a5e1ff09fe998dd05637d76dea2e3833/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/RiskScoreClassificationValidator.java#L89) an empty URL does not lead to an error. This is not in line with e.g. validation of a label. In case the label is blank, an error is added. Maybe you can check that this is implemented as intended.
</issue>
<code>
[start of README.md]
1 <!-- markdownlint-disable MD041 -->
2 <h1 align="center">
3 Corona-Warn-App Server
4 </h1>
5
6 <p align="center">
7 <a href="https://github.com/corona-warn-app/cwa-server/commits/" title="Last Commit"><img src="https://img.shields.io/github/last-commit/corona-warn-app/cwa-server?style=flat"></a>
8 <a href="https://github.com/corona-warn-app/cwa-server/issues" title="Open Issues"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat"></a>
9 <a href="https://circleci.com/gh/corona-warn-app/cwa-server" title="Build Status"><img src="https://circleci.com/gh/corona-warn-app/cwa-server.svg?style=shield&circle-token=4ab059989d10709df19eb4b98ab7c121a25e981a"></a>
10 <a href="https://sonarcloud.io/dashboard?id=corona-warn-app_cwa-server" title="Quality Gate"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=alert_status"></a>
11 <a href="https://sonarcloud.io/component_measures?id=corona-warn-app_cwa-server&metric=Coverage&view=list" title="Coverage"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=coverage"></a>
12 <a href="https://github.com/corona-warn-app/cwa-server/blob/master/LICENSE" title="License"><img src="https://img.shields.io/badge/License-Apache%202.0-green.svg?style=flat"></a>
13 </p>
14
15 <p align="center">
16 <a href="#development">Development</a> •
17 <a href="#service-apis">Service APIs</a> •
18 <a href="#documentation">Documentation</a> •
19 <a href="#support-and-feedback">Support</a> •
20 <a href="#how-to-contribute">Contribute</a> •
21 <a href="#contributors">Contributors</a> •
22 <a href="#repositories">Repositories</a> •
23 <a href="#licensing">Licensing</a>
24 </p>
25
26 The goal of this project is to develop the official Corona-Warn-App for Germany based on the exposure notification API from [Apple](https://www.apple.com/covid19/contacttracing/) and [Google](https://www.google.com/covid19/exposurenotifications/). The apps (for both iOS and Android) use Bluetooth technology to exchange anonymous encrypted data with other mobile phones (on which the app is also installed) in the vicinity of an app user's phone. The data is stored locally on each user's device, preventing authorities or other parties from accessing or controlling the data. This repository contains the **implementation of the server for encryption keys** for the Corona-Warn-App. This implementation is still a **work in progress**, and the code it contains is currently alpha-quality code.
27
28 In this documentation, Corona-Warn-App services are also referred to as CWA services.
29
30 ## Architecture Overview
31
32 You can find the architecture overview [here](/docs/architecture-overview.md), which will give you
33 a good starting point in how the backend services interact with other services, and what purpose
34 they serve.
35
36 ## Development
37
38 After you've checked out this repository, you can run the application in one of the following ways:
39
40 * As a [Docker](https://www.docker.com/)-based deployment on your local machine. You can run either:
41 * Single components using the respective Dockerfile or
42 * The full backend using the Docker Compose (which is considered the most convenient way)
43 * As a [Maven](https://maven.apache.org)-based build on your local machine.
44 If you want to develop something in a single component, this approach is preferable.
45
46 ### Docker-Based Deployment
47
48 If you want to use Docker-based deployment, you need to install Docker on your local machine. For more information about downloading and installing Docker, see the [official Docker documentation](https://docs.docker.com/get-docker/).
49
50 #### Running the Full CWA Backend Using Docker Compose
51
52 For your convenience, a full setup including the generation of test data has been prepared using [Docker Compose](https://docs.docker.com/compose/reference/overview/). To build the backend services, run ```docker-compose build``` in the repository's root directory. A default configuration file can be found under ```.env```in the root folder of the repository. The default values for the local Postgres and Zenko Cloudserver should be changed in this file before docker-compose is run.
53
54 Once the services are built, you can start the whole backend using ```docker-compose up```.
55 The distribution service runs once and then finishes. If you want to trigger additional distribution runs, run ```docker-compose run distribution```.
56
57 The docker-compose contains the following services:
58
59 Service | Description | Endpoint and Default Credentials
60 ------------------|-------------|-----------
61 submission | The Corona-Warn-App submission service | `http://localhost:8000` <br> `http://localhost:8006` (for actuator endpoint)
62 distribution | The Corona-Warn-App distribution service | NO ENDPOINT
63 postgres | A [postgres] database installation | `postgres:8001` <br> Username: postgres <br> Password: postgres
64 pgadmin | A [pgadmin](https://www.pgadmin.org/) installation for the postgres database | `http://localhost:8002` <br> Username: [email protected] <br> Password: password
65 cloudserver | [Zenko CloudServer] is a S3-compliant object store | `http://localhost:8003/` <br> Access key: accessKey1 <br> Secret key: verySecretKey1
66 verification-fake | A very simple fake implementation for the tan verification. | `http://localhost:8004/version/v1/tan/verify` <br> The only valid tan is "b69ab69f-9823-4549-8961-c41sa74b2f36"
67
68 ##### Known Limitation
69
70 In rare cases the docker-compose runs into a timing issue if the distribution service starts before the bucket of the objectstore was created. This is not a big issue as you can simply run ```docker-compose run distribution``` to trigger additional distribution runs after the objectstore was initialized.
71
72 #### Running Single CWA Services Using Docker
73
74 If you would like to build and run a single CWA service, it's considered easiest to run them in a Docker environment. You can do this using the script provided in the respective CWA service directory. The Docker script first builds the CWA service and then creates an image for the runtime, which means that there are no additional dependencies for you to install.
75
76 To build and run the distribution service, run the following command:
77
78 ```bash
79 ./services/distribution/build_and_run.sh
80 ```
81
82 To build and run the submission service, run the following command:
83
84 ```bash
85 ./services/submission/build_and_run.sh
86 ```
87
88 The submission service is available on [localhost:8080](http://localhost:8080 ).
89
90 ### Maven-Based Build
91
92 If you want to actively develop in one of the CWA services, the Maven-based runtime is most suitable.
93 To prepare your machine to run the CWA project locally, we recommend that you first ensure that you've installed the following:
94
95 * Minimum JDK Version 11: [OpenJDK](https://openjdk.java.net/) / [SapMachine](https://sap.github.io/SapMachine/)
96 * [Maven 3.6](https://maven.apache.org/)
97 * [Postgres]
98 * [Zenko CloudServer]
99
100 #### Configure
101
102 After you made sure that the specified dependencies are running, configure them in the respective configuration files.
103
104 * Configure the Postgres connection in the [submission config](./services/submission/src/main/resources/application.yaml) and in the [distribution config](./services/distribution/src/main/resources/application.yaml)
105 * Configure the S3 compatible object storage in the [distribution config](./services/distribution/src/main/resources/application.yaml)
106 * Configure the certificate and private key for the distribution service, the paths need to be prefixed with `file:`
107 * `VAULT_FILESIGNING_SECRET` should be the path to the private key, example available in `<repo-root>/docker-compose-test-secrets/private.pem`
108 * `VAULT_FILESIGNING_CERT` should be the path to the certificate, example available in `<repo-root>/docker-compose-test-secrets/certificate.cert`
109
110 #### Build
111
112 After you've checked out the repository, to build the project, run ```mvn install``` in your base directory.
113
114 #### Run
115
116 Navigate to the service you want to start and run the spring-boot:run target. The configured Postgres and the configured S3 compliant object storage are used as default. When you start the submission service, the endpoint is available on your local port 8080.
117
118 If you want to start the submission service, for example, you start it as follows:
119
120 ```bash
121 cd services/submission/
122 mvn spring-boot:run
123 ```
124
125 #### Debugging
126
127 To enable the `DEBUG` log level, you can run the application using the Spring `dev` profile.
128
129 ```bash
130 mvn spring-boot:run -Dspring-boot.run.profiles=dev
131 ```
132
133 To be able to set breakpoints (e.g. in IntelliJ), it may be necessary to use the ```-Dspring-boot.run.fork=false``` parameter.
134
135 ## Service APIs
136
137 The API that is being exposed by the backend services is documented in an [OpenAPI](https://www.openapis.org/) specification. The specification files are available at the following locations:
138
139 Service | OpenAPI Specification
140 -------------|-------------
141 Submission Service | [services/submission/api_v1.json](https://github.com/corona-warn-app/cwa-server/raw/master/services/submission/api_v1.json)
142 Distribution Service | [services/distribution/api_v1.json)](https://github.com/corona-warn-app/cwa-server/raw/master/services/distribution/api_v1.json)
143
144 ## Spring Profiles
145
146 ### Distribution
147
148 Profile | Effect
149 -------------|-------------
150 `dev` | Turns the log level to `DEBUG`.
151 `cloud` | Removes default values for the `datasource` and `objectstore` configurations.
152 `demo` | Includes incomplete days and hours into the distribution run, thus creating aggregates for the current day and the current hour (and including both in the respective indices). When running multiple distributions in one hour with this profile, the date aggregate for today and the hours aggregate for the current hour will be updated and overwritten.
153 `testdata` | Causes test data to be inserted into the database before each distribution run. By default, around 1000 random diagnosis keys will be generated per hour. If there are no diagnosis keys in the database yet, random keys will be generated for every hour from the beginning of the retention period (14 days ago at 00:00 UTC) until one hour before the present hour. If there are already keys in the database, the random keys will be generated for every hour from the latest diagnosis key in the database (by submission timestamp) until one hour before the present hour (or none at all, if the latest diagnosis key in the database was submitted one hour ago or later).
154
155 ### Submission
156
157 Profile | Effect
158 -------------|-------------
159 `dev` | Turns the log level to `DEBUG`.
160 `cloud` | Removes default values for the `datasource` configuration.
161
162 ## Documentation
163
164 The full documentation for the Corona-Warn-App can be found in the [cwa-documentation](https://github.com/corona-warn-app/cwa-documentation) repository. The documentation repository contains technical documents, architecture information, and whitepapers related to this implementation.
165
166 ## Support and Feedback
167
168 The following channels are available for discussions, feedback, and support requests:
169
170 | Type | Channel |
171 | ------------------------ | ------------------------------------------------------ |
172 | **General Discussion** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="General Discussion"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/question.svg?style=flat-square"></a> </a> |
173 | **Concept Feedback** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="Open Concept Feedback"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/architecture.svg?style=flat-square"></a> |
174 | **Backend Issue** | <a href="https://github.com/corona-warn-app/cwa-server/issues/new/choose" title="Open Backend Issue"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat-square"></a> |
175 | **Other Requests** | <a href="mailto:[email protected]" title="Email CWA Team"><img src="https://img.shields.io/badge/email-CWA%20team-green?logo=mail.ru&style=flat-square&logoColor=white"></a> |
176
177 ## How to Contribute
178
179 Contribution and feedback are 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.
180
181 ## Contributors
182
183 The German government has asked SAP and Deutsche Telekom to develop the Corona-Warn-App for Germany as open source software. Deutsche Telekom is providing the network and mobile technology and will operate and run the backend for the app in a safe, scalable and stable manner. SAP is responsible for the app development, its framework and the underlying platform. Therefore, development teams of SAP and Deutsche Telekom are contributing to this project. At the same time 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.
184
185 ## Repositories
186
187 The following public repositories are currently available for the Corona-Warn-App:
188
189 | Repository | Description |
190 | ------------------- | --------------------------------------------------------------------- |
191 | [cwa-documentation] | Project overview, general documentation, and white papers |
192 | [cwa-server] | Backend implementation for the Apple/Google exposure notification API|
193 | [cwa-verification-server] | Backend implementation of the verification process|
194
195 [cwa-documentation]: https://github.com/corona-warn-app/cwa-documentation
196 [cwa-server]: https://github.com/corona-warn-app/cwa-server
197 [cwa-verification-server]: https://github.com/corona-warn-app/cwa-verification-server
198 [Postgres]: https://www.postgresql.org/
199 [HSQLDB]: http://hsqldb.org/
200 [Zenko CloudServer]: https://github.com/scality/cloudserver
201
202 ## Licensing
203
204 Copyright (c) 2020 SAP SE or an SAP affiliate company.
205
206 Licensed under the **Apache License, Version 2.0** (the "License"); you may not use this file except in compliance with the License.
207
208 You may obtain a copy of the License at <https://www.apache.org/licenses/LICENSE-2.0>.
209
210 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.
211
[end of README.md]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/RiskScoreClassificationValidator.java]
1 /*
2 * Corona-Warn-App
3 *
4 * SAP SE and all other contributors /
5 * copyright owners license this file to you under the Apache
6 * License, Version 2.0 (the "License"); you may not use this
7 * file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20 package app.coronawarn.server.services.distribution.assembly.appconfig.validation;
21
22 import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.RiskScoreClassificationValidationError.ErrorType.BLANK_LABEL;
23 import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.RiskScoreClassificationValidationError.ErrorType.INVALID_PARTITIONING;
24 import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.RiskScoreClassificationValidationError.ErrorType.INVALID_URL;
25 import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.RiskScoreClassificationValidationError.ErrorType.MIN_GREATER_THAN_MAX;
26 import static app.coronawarn.server.services.distribution.assembly.appconfig.validation.RiskScoreClassificationValidationError.ErrorType.VALUE_OUT_OF_BOUNDS;
27
28 import app.coronawarn.server.common.protocols.internal.RiskScoreClass;
29 import app.coronawarn.server.common.protocols.internal.RiskScoreClassification;
30 import java.net.MalformedURLException;
31 import java.net.URL;
32
33 /**
34 * The RiskScoreClassificationValidator validates the values of an associated {@link RiskScoreClassification} instance.
35 */
36 public class RiskScoreClassificationValidator extends ConfigurationValidator {
37
38 private final RiskScoreClassification riskScoreClassification;
39
40 public RiskScoreClassificationValidator(RiskScoreClassification riskScoreClassification) {
41 this.riskScoreClassification = riskScoreClassification;
42 }
43
44 /**
45 * Performs a validation of the associated {@link RiskScoreClassification} instance and returns information about
46 * validation failures.
47 *
48 * @return The ValidationResult instance, containing information about possible errors.
49 */
50 @Override
51 public ValidationResult validate() {
52 errors = new ValidationResult();
53
54 validateValues();
55 validateValueRangeCoverage();
56
57 return errors;
58 }
59
60 private void validateValues() {
61 for (RiskScoreClass riskScoreClass : riskScoreClassification.getRiskClassesList()) {
62 int minRiskLevel = riskScoreClass.getMin();
63 int maxRiskLevel = riskScoreClass.getMax();
64
65 validateLabel(riskScoreClass.getLabel());
66 validateRiskScoreValueBounds(minRiskLevel);
67 validateRiskScoreValueBounds(maxRiskLevel);
68 validateUrl(riskScoreClass.getUrl());
69
70 if (minRiskLevel > maxRiskLevel) {
71 errors.add(new RiskScoreClassificationValidationError(
72 "minRiskLevel, maxRiskLevel", minRiskLevel + ", " + maxRiskLevel, MIN_GREATER_THAN_MAX));
73 }
74 }
75 }
76
77 private void validateLabel(String label) {
78 if (label.isBlank()) {
79 errors.add(new RiskScoreClassificationValidationError("label", label, BLANK_LABEL));
80 }
81 }
82
83 private void validateRiskScoreValueBounds(int value) {
84 if (!RiskScoreValidator.isInBounds(value)) {
85 errors.add(new RiskScoreClassificationValidationError("minRiskLevel/maxRiskLevel", value, VALUE_OUT_OF_BOUNDS));
86 }
87 }
88
89 private void validateUrl(String url) {
90 if (!url.isBlank()) {
91 try {
92 new URL(url);
93 } catch (MalformedURLException e) {
94 errors.add(new RiskScoreClassificationValidationError("url", url, INVALID_URL));
95 }
96 }
97 }
98
99 private void validateValueRangeCoverage() {
100 int partitionSum = riskScoreClassification.getRiskClassesList().stream()
101 .mapToInt(riskScoreClass -> (riskScoreClass.getMax() - riskScoreClass.getMin() + 1))
102 .sum();
103
104 if (partitionSum != ParameterSpec.RISK_SCORE_MAX + 1) {
105 errors.add(new RiskScoreClassificationValidationError("covered value range", partitionSum, INVALID_PARTITIONING));
106 }
107 }
108 }
109
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/RiskScoreClassificationValidator.java]
</code>
Here is an example of a patch file. It consists of changes to the code base. It specifies the file names, the line numbers of each change, and the removed and added lines. A single patch file can contain changes to multiple files.
<patch>
--- a/file.py
+++ b/file.py
@@ -1,27 +1,35 @@
def euclidean(a, b):
- while b:
- a, b = b, a % b
- return a
+ if b == 0:
+ return a
+ return euclidean(b, a % b)
def bresenham(x0, y0, x1, y1):
points = []
dx = abs(x1 - x0)
dy = abs(y1 - y0)
- sx = 1 if x0 < x1 else -1
- sy = 1 if y0 < y1 else -1
- err = dx - dy
+ x, y = x0, y0
+ sx = -1 if x0 > x1 else 1
+ sy = -1 if y0 > y1 else 1
- while True:
- points.append((x0, y0))
- if x0 == x1 and y0 == y1:
- break
- e2 = 2 * err
- if e2 > -dy:
+ if dx > dy:
+ err = dx / 2.0
+ while x != x1:
+ points.append((x, y))
err -= dy
- x0 += sx
- if e2 < dx:
- err += dx
- y0 += sy
+ if err < 0:
+ y += sy
+ err += dx
+ x += sx
+ else:
+ err = dy / 2.0
+ while y != y1:
+ points.append((x, y))
+ err -= dx
+ if err < 0:
+ x += sx
+ err += dy
+ y += sy
+ points.append((x, y))
return points
</patch>
I need you to solve the provded issue by generating a single patch file that I can apply directly to this repository using git apply. Please respond with a single patch file in the format shown above.
Respond below:
| corona-warn-app/cwa-server | 8d8a0a5e16bc252364812017a85418b054d739f7 | Blank URL in RiskScoreClassificationValidator
In `app.coronawarn.server.services.distribution.assembly.appconfig.validation.RiskScoreClassificationValidator#validateUrl` [(link to source code)](https://github.com/corona-warn-app/cwa-server/blob/63dda0c2a5e1ff09fe998dd05637d76dea2e3833/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/RiskScoreClassificationValidator.java#L89) an empty URL does not lead to an error. This is not in line with e.g. validation of a label. In case the label is blank, an error is added. Maybe you can check that this is implemented as intended.
| Confirmed URL should **not** be empty - It should be a valid URL with http/https as allowed protocol | 2020-05-27T19:55:53 | <patch>
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/RiskScoreClassificationValidator.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/RiskScoreClassificationValidator.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/RiskScoreClassificationValidator.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/RiskScoreClassificationValidator.java
@@ -87,12 +87,10 @@ private void validateRiskScoreValueBounds(int value) {
}
private void validateUrl(String url) {
- if (!url.isBlank()) {
- try {
- new URL(url);
- } catch (MalformedURLException e) {
- errors.add(new RiskScoreClassificationValidationError("url", url, INVALID_URL));
- }
+ try {
+ new URL(url.trim());
+ } catch (MalformedURLException e) {
+ errors.add(new RiskScoreClassificationValidationError("url", url, INVALID_URL));
}
}
</patch> | diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/RiskScoreClassificationValidatorTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/RiskScoreClassificationValidatorTest.java
--- a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/RiskScoreClassificationValidatorTest.java
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/RiskScoreClassificationValidatorTest.java
@@ -39,19 +39,19 @@ class RiskScoreClassificationValidatorTest {
private final static int MAX_SCORE = ParameterSpec.RISK_SCORE_MAX;
private final static String VALID_LABEL = "myLabel";
- private final static String VALID_URL = "";
+ private final static String VALID_URL = "https://www.my.url";
@ParameterizedTest
@ValueSource(strings = {"", " "})
void failsForBlankLabels(String invalidLabel) {
- var validator = buildValidator(buildRiskClass(invalidLabel, 0, MAX_SCORE, ""));
+ var validator = buildValidator(buildRiskClass(invalidLabel, 0, MAX_SCORE, VALID_URL));
var expectedResult = buildExpectedResult(buildError("label", invalidLabel, ErrorType.BLANK_LABEL));
assertThat(validator.validate()).isEqualTo(expectedResult);
}
@ParameterizedTest
- @ValueSource(strings = {"invalid.Url", "invalid-url", "$$$://invalid.url"})
+ @ValueSource(strings = {"invalid.Url", "invalid-url", "$$$://invalid.url", "", " "})
void failsForInvalidUrl(String invalidUrl) {
var validator = buildValidator(buildRiskClass(VALID_LABEL, 0, MAX_SCORE, invalidUrl));
var expectedResult = buildExpectedResult(buildError("url", invalidUrl, ErrorType.INVALID_URL));
@@ -133,10 +133,8 @@ void doesNotFailForValidClassification(RiskScoreClassification validClassificati
private static Stream<Arguments> createValidClassifications() {
return Stream.of(
- // blank url
- buildClassification(buildRiskClass(VALID_LABEL, 0, MAX_SCORE, "")),
- // legit url
- buildClassification(buildRiskClass(VALID_LABEL, 0, MAX_SCORE, "http://www.sap.com")),
+ // valid url
+ buildClassification(buildRiskClass(VALID_LABEL, 0, MAX_SCORE, VALID_URL)),
// [0:MAX_SCORE/2][MAX_SCORE/2:MAX_SCORE]
buildClassification(
buildRiskClass(VALID_LABEL, 0, MAX_SCORE / 2, VALID_URL),
| ||||
corona-warn-app__cwa-server-378 | You will be provided with a partial code base and an issue statement explaining a problem to resolve.
<issue>
Remove MinIO SDK and use AWS SDK instead
Since MinIO SDK still hasn't released a fix version for fixing the XML vulnerability in the SimpleXML library, we need to consider alternative S3 SDK's. Therefore, prepare an alternative approach with AWS SDK, which is then used by the ObjectStoreAccess class.
</issue>
<code>
[start of README.md]
1 <!-- markdownlint-disable MD041 -->
2 <h1 align="center">
3 Corona-Warn-App Server
4 </h1>
5
6 <p align="center">
7 <a href="https://github.com/corona-warn-app/cwa-server/commits/" title="Last Commit"><img src="https://img.shields.io/github/last-commit/corona-warn-app/cwa-server?style=flat"></a>
8 <a href="https://github.com/corona-warn-app/cwa-server/issues" title="Open Issues"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat"></a>
9 <a href="https://circleci.com/gh/corona-warn-app/cwa-server" title="Build Status"><img src="https://circleci.com/gh/corona-warn-app/cwa-server.svg?style=shield&circle-token=4ab059989d10709df19eb4b98ab7c121a25e981a"></a>
10 <a href="https://sonarcloud.io/dashboard?id=corona-warn-app_cwa-server" title="Quality Gate"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=alert_status"></a>
11 <a href="https://sonarcloud.io/component_measures?id=corona-warn-app_cwa-server&metric=Coverage&view=list" title="Coverage"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=coverage"></a>
12 <a href="https://github.com/corona-warn-app/cwa-server/blob/master/LICENSE" title="License"><img src="https://img.shields.io/badge/License-Apache%202.0-green.svg?style=flat"></a>
13 </p>
14
15 <p align="center">
16 <a href="#development">Development</a> •
17 <a href="#service-apis">Service APIs</a> •
18 <a href="#documentation">Documentation</a> •
19 <a href="#support-and-feedback">Support</a> •
20 <a href="#how-to-contribute">Contribute</a> •
21 <a href="#contributors">Contributors</a> •
22 <a href="#repositories">Repositories</a> •
23 <a href="#licensing">Licensing</a>
24 </p>
25
26 The goal of this project is to develop the official Corona-Warn-App for Germany based on the exposure notification API from [Apple](https://www.apple.com/covid19/contacttracing/) and [Google](https://www.google.com/covid19/exposurenotifications/). The apps (for both iOS and Android) use Bluetooth technology to exchange anonymous encrypted data with other mobile phones (on which the app is also installed) in the vicinity of an app user's phone. The data is stored locally on each user's device, preventing authorities or other parties from accessing or controlling the data. This repository contains the **implementation of the server for encryption keys** for the Corona-Warn-App. This implementation is still a **work in progress**, and the code it contains is currently alpha-quality code.
27
28 In this documentation, Corona-Warn-App services are also referred to as CWA services.
29
30 ## Architecture Overview
31
32 You can find the architecture overview [here](/docs/architecture-overview.md), which will give you
33 a good starting point in how the backend services interact with other services, and what purpose
34 they serve.
35
36 ## Development
37
38 After you've checked out this repository, you can run the application in one of the following ways:
39
40 * As a [Docker](https://www.docker.com/)-based deployment on your local machine. You can run either:
41 * Single components using the respective Dockerfile or
42 * The full backend using the Docker Compose (which is considered the most convenient way)
43 * As a [Maven](https://maven.apache.org)-based build on your local machine.
44 If you want to develop something in a single component, this approach is preferable.
45
46 ### Docker-Based Deployment
47
48 If you want to use Docker-based deployment, you need to install Docker on your local machine. For more information about downloading and installing Docker, see the [official Docker documentation](https://docs.docker.com/get-docker/).
49
50 #### Running the Full CWA Backend Using Docker Compose
51
52 For your convenience, a full setup including the generation of test data has been prepared using [Docker Compose](https://docs.docker.com/compose/reference/overview/). To build the backend services, run ```docker-compose build``` in the repository's root directory. A default configuration file can be found under ```.env```in the root folder of the repository. The default values for the local Postgres and Zenko Cloudserver should be changed in this file before docker-compose is run.
53
54 Once the services are built, you can start the whole backend using ```docker-compose up```.
55 The distribution service runs once and then finishes. If you want to trigger additional distribution runs, run ```docker-compose run distribution```.
56
57 The docker-compose contains the following services:
58
59 Service | Description | Endpoint and Default Credentials
60 ------------------|-------------|-----------
61 submission | The Corona-Warn-App submission service | `http://localhost:8000` <br> `http://localhost:8006` (for actuator endpoint)
62 distribution | The Corona-Warn-App distribution service | NO ENDPOINT
63 postgres | A [postgres] database installation | `postgres:8001` <br> Username: postgres <br> Password: postgres
64 pgadmin | A [pgadmin](https://www.pgadmin.org/) installation for the postgres database | `http://localhost:8002` <br> Username: [email protected] <br> Password: password
65 cloudserver | [Zenko CloudServer] is a S3-compliant object store | `http://localhost:8003/` <br> Access key: accessKey1 <br> Secret key: verySecretKey1
66 verification-fake | A very simple fake implementation for the tan verification. | `http://localhost:8004/version/v1/tan/verify` <br> The only valid tan is "edc07f08-a1aa-11ea-bb37-0242ac130002"
67
68 ##### Known Limitation
69
70 In rare cases the docker-compose runs into a timing issue if the distribution service starts before the bucket of the objectstore was created. This is not a big issue as you can simply run ```docker-compose run distribution``` to trigger additional distribution runs after the objectstore was initialized.
71
72 #### Running Single CWA Services Using Docker
73
74 If you would like to build and run a single CWA service, it's considered easiest to run them in a Docker environment. You can do this using the script provided in the respective CWA service directory. The Docker script first builds the CWA service and then creates an image for the runtime, which means that there are no additional dependencies for you to install.
75
76 To build and run the distribution service, run the following command:
77
78 ```bash
79 ./services/distribution/build_and_run.sh
80 ```
81
82 To build and run the submission service, run the following command:
83
84 ```bash
85 ./services/submission/build_and_run.sh
86 ```
87
88 The submission service is available on [localhost:8080](http://localhost:8080 ).
89
90 ### Maven-Based Build
91
92 If you want to actively develop in one of the CWA services, the Maven-based runtime is most suitable.
93 To prepare your machine to run the CWA project locally, we recommend that you first ensure that you've installed the following:
94
95 * Minimum JDK Version 11: [OpenJDK](https://openjdk.java.net/) / [SapMachine](https://sap.github.io/SapMachine/)
96 * [Maven 3.6](https://maven.apache.org/)
97 * [Postgres]
98 * [Zenko CloudServer]
99
100 #### Configure
101
102 After you made sure that the specified dependencies are running, configure them in the respective configuration files.
103
104 * Configure the Postgres connection in the [submission config](./services/submission/src/main/resources/application.yaml) and in the [distribution config](./services/distribution/src/main/resources/application.yaml)
105 * Configure the S3 compatible object storage in the [distribution config](./services/distribution/src/main/resources/application.yaml)
106 * Configure the private key for the distribution service, the path need to be prefixed with `file:`
107 * `VAULT_FILESIGNING_SECRET` should be the path to the private key, example available in `<repo-root>/docker-compose-test-secrets/private.pem`
108
109 #### Build
110
111 After you've checked out the repository, to build the project, run ```mvn install``` in your base directory.
112
113 #### Run
114
115 Navigate to the service you want to start and run the spring-boot:run target. The configured Postgres and the configured S3 compliant object storage are used as default. When you start the submission service, the endpoint is available on your local port 8080.
116
117 If you want to start the submission service, for example, you start it as follows:
118
119 ```bash
120 cd services/submission/
121 mvn spring-boot:run
122 ```
123
124 #### Debugging
125
126 To enable the `DEBUG` log level, you can run the application using the Spring `dev` profile.
127
128 ```bash
129 mvn spring-boot:run -Dspring-boot.run.profiles=dev
130 ```
131
132 To be able to set breakpoints (e.g. in IntelliJ), it may be necessary to use the ```-Dspring-boot.run.fork=false``` parameter.
133
134 ## Service APIs
135
136 The API that is being exposed by the backend services is documented in an [OpenAPI](https://www.openapis.org/) specification. The specification files are available at the following locations:
137
138 Service | OpenAPI Specification
139 -------------|-------------
140 Submission Service | [services/submission/api_v1.json](https://github.com/corona-warn-app/cwa-server/raw/master/services/submission/api_v1.json)
141 Distribution Service | [services/distribution/api_v1.json](https://github.com/corona-warn-app/cwa-server/raw/master/services/distribution/api_v1.json)
142
143 ## Spring Profiles
144
145 ### Distribution
146
147 Profile | Effect
148 -------------|-------------
149 `dev` | Turns the log level to `DEBUG` and sets the app package ID in the export packages' signature info to `de.rki.coronawarnapp-dev` so that test certificates (instead of production certificates) will be used for client-side validation.
150 `cloud` | Removes default values for the `datasource` and `objectstore` configurations.
151 `demo` | Includes incomplete days and hours into the distribution run, thus creating aggregates for the current day and the current hour (and including both in the respective indices). When running multiple distributions in one hour with this profile, the date aggregate for today and the hours aggregate for the current hour will be updated and overwritten.
152 `testdata` | Causes test data to be inserted into the database before each distribution run. By default, around 1000 random diagnosis keys will be generated per hour. If there are no diagnosis keys in the database yet, random keys will be generated for every hour from the beginning of the retention period (14 days ago at 00:00 UTC) until one hour before the present hour. If there are already keys in the database, the random keys will be generated for every hour from the latest diagnosis key in the database (by submission timestamp) until one hour before the present hour (or none at all, if the latest diagnosis key in the database was submitted one hour ago or later).
153
154 ### Submission
155
156 Profile | Effect
157 -------------|-------------
158 `dev` | Turns the log level to `DEBUG`.
159 `cloud` | Removes default values for the `datasource` configuration.
160
161 ## Documentation
162
163 The full documentation for the Corona-Warn-App can be found in the [cwa-documentation](https://github.com/corona-warn-app/cwa-documentation) repository. The documentation repository contains technical documents, architecture information, and whitepapers related to this implementation.
164
165 ## Support and Feedback
166
167 The following channels are available for discussions, feedback, and support requests:
168
169 | Type | Channel |
170 | ------------------------ | ------------------------------------------------------ |
171 | **General Discussion** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="General Discussion"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/question.svg?style=flat-square"></a> </a> |
172 | **Concept Feedback** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="Open Concept Feedback"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/architecture.svg?style=flat-square"></a> |
173 | **Backend Issue** | <a href="https://github.com/corona-warn-app/cwa-server/issues/new/choose" title="Open Backend Issue"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat-square"></a> |
174 | **Other Requests** | <a href="mailto:[email protected]" title="Email CWA Team"><img src="https://img.shields.io/badge/email-CWA%20team-green?logo=mail.ru&style=flat-square&logoColor=white"></a> |
175
176 ## How to Contribute
177
178 Contribution and feedback are 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.
179
180 ## Contributors
181
182 The German government has asked SAP and Deutsche Telekom to develop the Corona-Warn-App for Germany as open source software. Deutsche Telekom is providing the network and mobile technology and will operate and run the backend for the app in a safe, scalable and stable manner. SAP is responsible for the app development, its framework and the underlying platform. Therefore, development teams of SAP and Deutsche Telekom are contributing to this project. At the same time 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.
183
184 ## Repositories
185
186 The following public repositories are currently available for the Corona-Warn-App:
187
188 | Repository | Description |
189 | ------------------- | --------------------------------------------------------------------- |
190 | [cwa-documentation] | Project overview, general documentation, and white papers |
191 | [cwa-server] | Backend implementation for the Apple/Google exposure notification API|
192 | [cwa-verification-server] | Backend implementation of the verification process|
193
194 [cwa-documentation]: https://github.com/corona-warn-app/cwa-documentation
195 [cwa-server]: https://github.com/corona-warn-app/cwa-server
196 [cwa-verification-server]: https://github.com/corona-warn-app/cwa-verification-server
197 [Postgres]: https://www.postgresql.org/
198 [HSQLDB]: http://hsqldb.org/
199 [Zenko CloudServer]: https://github.com/scality/cloudserver
200
201 ## Licensing
202
203 Copyright (c) 2020 SAP SE or an SAP affiliate company.
204
205 Licensed under the **Apache License, Version 2.0** (the "License"); you may not use this file except in compliance with the License.
206
207 You may obtain a copy of the License at <https://www.apache.org/licenses/LICENSE-2.0>.
208
209 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.
210
[end of README.md]
[start of /dev/null]
1
[end of /dev/null]
[start of services/distribution/pom.xml]
1 <?xml version="1.0" encoding="UTF-8"?>
2 <project xmlns="http://maven.apache.org/POM/4.0.0"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
5 <parent>
6 <artifactId>services</artifactId>
7 <groupId>org.opencwa</groupId>
8 <version>${revision}</version>
9 <relativePath>../pom.xml</relativePath>
10 </parent>
11 <modelVersion>4.0.0</modelVersion>
12
13 <properties>
14 <sonar.projectKey>corona-warn-app_cwa-server_services_distribution</sonar.projectKey>
15 </properties>
16
17 <build>
18 <pluginManagement>
19 <plugins>
20 <plugin>
21 <groupId>org.apache.maven.plugins</groupId>
22 <artifactId>maven-surefire-plugin</artifactId>
23 <version>3.0.0-M3</version>
24 <configuration>
25 <excludedGroups>s3-integration</excludedGroups>
26 <trimStackTrace>false</trimStackTrace>
27 </configuration>
28 </plugin>
29 </plugins>
30 </pluginManagement>
31 <plugins>
32 <plugin>
33 <groupId>org.jacoco</groupId>
34 <artifactId>jacoco-maven-plugin</artifactId>
35 <version>0.8.5</version>
36 <executions>
37 <execution>
38 <goals>
39 <goal>prepare-agent</goal>
40 </goals>
41 </execution>
42 <execution>
43 <id>report</id>
44 <goals>
45 <goal>report</goal>
46 </goals>
47 <phase>verify</phase>
48 </execution>
49 </executions>
50 </plugin>
51 </plugins>
52 </build>
53
54 <artifactId>distribution</artifactId>
55 <dependencies>
56 <dependency>
57 <groupId>io.minio</groupId>
58 <artifactId>minio</artifactId>
59 <version>7.0.2</version>
60 </dependency>
61 <dependency>
62 <artifactId>bcpkix-jdk15on</artifactId>
63 <groupId>org.bouncycastle</groupId>
64 <version>1.65</version>
65 </dependency>
66 <dependency>
67 <artifactId>json-simple</artifactId>
68 <groupId>com.googlecode.json-simple</groupId>
69 <version>1.1.1</version>
70 </dependency>
71 <dependency>
72 <groupId>commons-io</groupId>
73 <artifactId>commons-io</artifactId>
74 <version>2.5</version>
75 </dependency>
76 <dependency>
77 <artifactId>commons-math3</artifactId>
78 <groupId>org.apache.commons</groupId>
79 <version>3.2</version>
80 </dependency>
81 </dependencies>
82
83 </project>
[end of services/distribution/pom.xml]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/client/MinioClientWrapper.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.distribution.objectstore.client;
22
23 import io.minio.MinioClient;
24 import io.minio.PutObjectOptions;
25 import io.minio.Result;
26 import io.minio.errors.ErrorResponseException;
27 import io.minio.errors.InsufficientDataException;
28 import io.minio.errors.InternalException;
29 import io.minio.errors.InvalidBucketNameException;
30 import io.minio.errors.InvalidResponseException;
31 import io.minio.errors.XmlParserException;
32 import io.minio.messages.Item;
33 import java.io.IOException;
34 import java.nio.file.Files;
35 import java.nio.file.Path;
36 import java.security.InvalidKeyException;
37 import java.security.NoSuchAlgorithmException;
38 import java.util.ArrayList;
39 import java.util.List;
40 import java.util.Map;
41 import java.util.Map.Entry;
42 import java.util.stream.Collectors;
43
44 /**
45 * Implementation of {@link ObjectStoreClient} that encapsulates a {@link MinioClient}.
46 */
47 public class MinioClientWrapper implements ObjectStoreClient {
48
49 private final MinioClient minioClient;
50
51 public MinioClientWrapper(MinioClient minioClient) {
52 this.minioClient = minioClient;
53 }
54
55 @Override
56 public List<S3Object> getObjects(String bucket, String prefix) {
57 Iterable<Result<Item>> objects = this.minioClient.listObjects(bucket, prefix, true);
58
59 var list = new ArrayList<S3Object>();
60 for (Result<Item> item : objects) {
61 try {
62 list.add(S3Object.of(item.get()));
63 } catch (ErrorResponseException | NoSuchAlgorithmException | InternalException | IOException | InvalidKeyException
64 | InvalidResponseException | InvalidBucketNameException | InsufficientDataException | XmlParserException
65 | IllegalArgumentException e) {
66 throw new ObjectStoreOperationFailedException("Failed to download objects from object store.", e);
67 }
68 }
69 return list;
70 }
71
72 @Override
73 public void putObject(String bucket, String objectName, Path filePath, Map<HeaderKey, String> headers) {
74 try {
75 var options = new PutObjectOptions(Files.size(filePath), -1);
76 Map<String, String> minioHeaders = headers.entrySet().stream()
77 .map(entry -> Map.entry(entry.getKey().keyValue, entry.getValue()))
78 .collect(Collectors.toMap(Entry::getKey, Entry::getValue));
79
80 options.setHeaders(minioHeaders);
81 minioClient.putObject(bucket, objectName, filePath.toString(), options);
82 } catch (ErrorResponseException | NoSuchAlgorithmException | InternalException | IOException | InvalidKeyException
83 | InvalidResponseException | InvalidBucketNameException | InsufficientDataException | XmlParserException
84 | IllegalArgumentException e) {
85 throw new ObjectStoreOperationFailedException("Failed to upload object to object store.", e);
86 }
87 }
88
89 @Override
90 public void removeObjects(String bucket, List<String> objectNames) {
91 if (!objectNames.isEmpty() && minioClient.removeObjects(bucket, objectNames).iterator().hasNext()) {
92 throw new ObjectStoreOperationFailedException("Failed to remove objects from object store");
93 }
94 }
95
96 @Override
97 public boolean bucketExists(String bucket) {
98 try {
99 return minioClient.bucketExists(bucket);
100 } catch (ErrorResponseException | NoSuchAlgorithmException | InternalException | IOException | InvalidKeyException
101 | InvalidResponseException | InvalidBucketNameException | InsufficientDataException | XmlParserException
102 | IllegalArgumentException e) {
103 throw new ObjectStoreOperationFailedException("Failed to check if object store bucket exists.", e);
104 }
105 }
106 }
107
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/client/MinioClientWrapper.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/client/ObjectStoreClientConfig.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.distribution.objectstore.client;
22
23 import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
24 import app.coronawarn.server.services.distribution.config.DistributionServiceConfig.ObjectStore;
25 import io.minio.MinioClient;
26 import io.minio.errors.InvalidEndpointException;
27 import io.minio.errors.InvalidPortException;
28 import org.springframework.context.annotation.Bean;
29 import org.springframework.context.annotation.Configuration;
30
31 /**
32 * Manages the instantiation of the {@link MinioClient} bean.
33 */
34 @Configuration
35 public class ObjectStoreClientConfig {
36
37 private static final String DEFAULT_REGION = "eu-west-1";
38
39 @Bean
40 public ObjectStoreClient createObjectStoreClient(DistributionServiceConfig distributionServiceConfig)
41 throws InvalidPortException, InvalidEndpointException {
42 return createClient(distributionServiceConfig.getObjectStore());
43 }
44
45 private MinioClientWrapper createClient(ObjectStore objectStore)
46 throws InvalidPortException, InvalidEndpointException {
47 if (isSsl(objectStore)) {
48 return new MinioClientWrapper(new MinioClient(
49 objectStore.getEndpoint(),
50 objectStore.getPort(),
51 objectStore.getAccessKey(), objectStore.getSecretKey(),
52 DEFAULT_REGION,
53 true));
54 } else {
55 return new MinioClientWrapper(new MinioClient(
56 objectStore.getEndpoint(),
57 objectStore.getPort(),
58 objectStore.getAccessKey(), objectStore.getSecretKey()));
59 }
60 }
61
62 private boolean isSsl(ObjectStore objectStore) {
63 return objectStore.getEndpoint().startsWith("https://");
64 }
65 }
66
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/client/ObjectStoreClientConfig.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/client/S3Object.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.distribution.objectstore.client;
22
23 import io.minio.messages.Item;
24 import java.util.Objects;
25
26 /**
27 * Represents an object as discovered on S3.
28 */
29 public class S3Object {
30
31 /**
32 * the name of the object.
33 */
34 private final String objectName;
35
36 /** The e-Tag of this S3 Object. */
37 private String etag;
38
39 /**
40 * Constructs a new S3Object for the given object name.
41 *
42 * @param objectName the target object name
43 */
44 public S3Object(String objectName) {
45 this.objectName = objectName;
46 }
47
48 /**
49 * Constructs a new S3Object for the given object name.
50 *
51 * @param objectName the target object name
52 * @param etag the e-etag
53 */
54 public S3Object(String objectName, String etag) {
55 this(objectName);
56 this.etag = etag;
57 }
58
59 public String getObjectName() {
60 return objectName;
61 }
62
63 public String getEtag() {
64 return etag;
65 }
66
67 /**
68 * Returns a new instance of an S3Object based on the given item.
69 *
70 * @param item the item (as provided by MinIO)
71 * @return the S3Object representation
72 */
73 public static S3Object of(Item item) {
74 String etag = item.etag().replaceAll("\"", "");
75 return new S3Object(item.objectName(), etag);
76 }
77
78 @Override
79 public boolean equals(Object o) {
80 if (this == o) {
81 return true;
82 }
83 if (o == null || getClass() != o.getClass()) {
84 return false;
85 }
86 S3Object s3Object = (S3Object) o;
87 return Objects.equals(objectName, s3Object.objectName) && Objects.equals(etag, s3Object.etag);
88 }
89
90 @Override
91 public int hashCode() {
92 return Objects.hash(objectName, etag);
93 }
94 }
95
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/client/S3Object.java]
[start of services/distribution/src/main/java/io/minio/messages/Item.java]
1 /*
2 * MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2015 MinIO, Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package io.minio.messages;
18
19 import java.time.ZonedDateTime;
20 import java.util.Map;
21 import org.simpleframework.xml.Element;
22 import org.simpleframework.xml.Root;
23
24 /* ----------------------------------------------------------------
25 * Copied from MinIO due to patch not yet available.
26 * https://github.com/minio/minio-java/pull/921
27 * Waiting for new release version: 7.0.3
28 * ----------------------------------------------------------------
29 */
30
31 /**
32 * Helper class to denote Object information in {@link ListBucketResult} and {@link ListBucketResultV1}.
33 */
34 @Root(name = "Contents", strict = false)
35 public class Item {
36
37 @Element(name = "Key")
38 private String objectName;
39
40 @Element(name = "LastModified")
41 private ResponseDate lastModified;
42
43 @Element(name = "ETag")
44 private String etag;
45
46 @Element(name = "Size")
47 private long size;
48
49 @Element(name = "StorageClass")
50 private String storageClass;
51
52 @Element(name = "Owner", required = false) /* Monkeypatch: Owner should be optional */
53 private Owner owner;
54
55 @Element(name = "UserMetadata", required = false)
56 private Metadata userMetadata;
57
58 private boolean isDir = false;
59
60 public Item() {
61
62 }
63
64 /**
65 * Constructs a new Item for prefix i.e. directory.
66 */
67 public Item(String prefix) {
68 this.objectName = prefix;
69 this.isDir = true;
70 }
71
72 /**
73 * Returns object name.
74 */
75 public String objectName() {
76 return objectName;
77 }
78
79 /**
80 * Returns last modified time of the object.
81 */
82 public ZonedDateTime lastModified() {
83 return lastModified.zonedDateTime();
84 }
85
86 /**
87 * Returns ETag of the object.
88 */
89 public String etag() {
90 return etag;
91 }
92
93 /**
94 * Returns object size.
95 */
96 public long size() {
97 return size;
98 }
99
100 /**
101 * Returns storage class of the object.
102 */
103 public String storageClass() {
104 return storageClass;
105 }
106
107 /**
108 * Returns owner object of given the object.
109 */
110 public Owner owner() {
111 return owner;
112 }
113
114 /**
115 * Returns user metadata. This is MinIO specific extension to ListObjectsV2.
116 */
117 public Map<String, String> userMetadata() {
118 if (userMetadata == null) {
119 return null;
120 }
121
122 return userMetadata.get();
123 }
124
125 /**
126 * Returns whether the object is a directory or not.
127 */
128 public boolean isDir() {
129 return isDir;
130 }
131 }
132
[end of services/distribution/src/main/java/io/minio/messages/Item.java]
</code>
Here is an example of a patch file. It consists of changes to the code base. It specifies the file names, the line numbers of each change, and the removed and added lines. A single patch file can contain changes to multiple files.
<patch>
--- a/file.py
+++ b/file.py
@@ -1,27 +1,35 @@
def euclidean(a, b):
- while b:
- a, b = b, a % b
- return a
+ if b == 0:
+ return a
+ return euclidean(b, a % b)
def bresenham(x0, y0, x1, y1):
points = []
dx = abs(x1 - x0)
dy = abs(y1 - y0)
- sx = 1 if x0 < x1 else -1
- sy = 1 if y0 < y1 else -1
- err = dx - dy
+ x, y = x0, y0
+ sx = -1 if x0 > x1 else 1
+ sy = -1 if y0 > y1 else 1
- while True:
- points.append((x0, y0))
- if x0 == x1 and y0 == y1:
- break
- e2 = 2 * err
- if e2 > -dy:
+ if dx > dy:
+ err = dx / 2.0
+ while x != x1:
+ points.append((x, y))
err -= dy
- x0 += sx
- if e2 < dx:
- err += dx
- y0 += sy
+ if err < 0:
+ y += sy
+ err += dx
+ x += sx
+ else:
+ err = dy / 2.0
+ while y != y1:
+ points.append((x, y))
+ err -= dx
+ if err < 0:
+ x += sx
+ err += dy
+ y += sy
+ points.append((x, y))
return points
</patch>
I need you to solve the provded issue by generating a single patch file that I can apply directly to this repository using git apply. Please respond with a single patch file in the format shown above.
Respond below:
| corona-warn-app/cwa-server | 79eef3fa06e3e6bd1bfa9a97c0959d62551295b8 | Remove MinIO SDK and use AWS SDK instead
Since MinIO SDK still hasn't released a fix version for fixing the XML vulnerability in the SimpleXML library, we need to consider alternative S3 SDK's. Therefore, prepare an alternative approach with AWS SDK, which is then used by the ObjectStoreAccess class.
| 2020-05-29T21:57:57 | <patch>
diff --git a/services/distribution/pom.xml b/services/distribution/pom.xml
--- a/services/distribution/pom.xml
+++ b/services/distribution/pom.xml
@@ -54,9 +54,9 @@
<artifactId>distribution</artifactId>
<dependencies>
<dependency>
- <groupId>io.minio</groupId>
- <artifactId>minio</artifactId>
- <version>7.0.2</version>
+ <groupId>software.amazon.awssdk</groupId>
+ <artifactId>s3</artifactId>
+ <version>2.13.25</version>
</dependency>
<dependency>
<artifactId>bcpkix-jdk15on</artifactId>
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/client/MinioClientWrapper.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/client/MinioClientWrapper.java
deleted file mode 100644
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/client/MinioClientWrapper.java
+++ /dev/null
@@ -1,106 +0,0 @@
-/*-
- * ---license-start
- * Corona-Warn-App
- * ---
- * Copyright (C) 2020 SAP SE and all other contributors
- * ---
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://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 for the specific language governing permissions and
- * limitations under the License.
- * ---license-end
- */
-
-package app.coronawarn.server.services.distribution.objectstore.client;
-
-import io.minio.MinioClient;
-import io.minio.PutObjectOptions;
-import io.minio.Result;
-import io.minio.errors.ErrorResponseException;
-import io.minio.errors.InsufficientDataException;
-import io.minio.errors.InternalException;
-import io.minio.errors.InvalidBucketNameException;
-import io.minio.errors.InvalidResponseException;
-import io.minio.errors.XmlParserException;
-import io.minio.messages.Item;
-import java.io.IOException;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.security.InvalidKeyException;
-import java.security.NoSuchAlgorithmException;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.stream.Collectors;
-
-/**
- * Implementation of {@link ObjectStoreClient} that encapsulates a {@link MinioClient}.
- */
-public class MinioClientWrapper implements ObjectStoreClient {
-
- private final MinioClient minioClient;
-
- public MinioClientWrapper(MinioClient minioClient) {
- this.minioClient = minioClient;
- }
-
- @Override
- public List<S3Object> getObjects(String bucket, String prefix) {
- Iterable<Result<Item>> objects = this.minioClient.listObjects(bucket, prefix, true);
-
- var list = new ArrayList<S3Object>();
- for (Result<Item> item : objects) {
- try {
- list.add(S3Object.of(item.get()));
- } catch (ErrorResponseException | NoSuchAlgorithmException | InternalException | IOException | InvalidKeyException
- | InvalidResponseException | InvalidBucketNameException | InsufficientDataException | XmlParserException
- | IllegalArgumentException e) {
- throw new ObjectStoreOperationFailedException("Failed to download objects from object store.", e);
- }
- }
- return list;
- }
-
- @Override
- public void putObject(String bucket, String objectName, Path filePath, Map<HeaderKey, String> headers) {
- try {
- var options = new PutObjectOptions(Files.size(filePath), -1);
- Map<String, String> minioHeaders = headers.entrySet().stream()
- .map(entry -> Map.entry(entry.getKey().keyValue, entry.getValue()))
- .collect(Collectors.toMap(Entry::getKey, Entry::getValue));
-
- options.setHeaders(minioHeaders);
- minioClient.putObject(bucket, objectName, filePath.toString(), options);
- } catch (ErrorResponseException | NoSuchAlgorithmException | InternalException | IOException | InvalidKeyException
- | InvalidResponseException | InvalidBucketNameException | InsufficientDataException | XmlParserException
- | IllegalArgumentException e) {
- throw new ObjectStoreOperationFailedException("Failed to upload object to object store.", e);
- }
- }
-
- @Override
- public void removeObjects(String bucket, List<String> objectNames) {
- if (!objectNames.isEmpty() && minioClient.removeObjects(bucket, objectNames).iterator().hasNext()) {
- throw new ObjectStoreOperationFailedException("Failed to remove objects from object store");
- }
- }
-
- @Override
- public boolean bucketExists(String bucket) {
- try {
- return minioClient.bucketExists(bucket);
- } catch (ErrorResponseException | NoSuchAlgorithmException | InternalException | IOException | InvalidKeyException
- | InvalidResponseException | InvalidBucketNameException | InsufficientDataException | XmlParserException
- | IllegalArgumentException e) {
- throw new ObjectStoreOperationFailedException("Failed to check if object store bucket exists.", e);
- }
- }
-}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/client/ObjectStoreClientConfig.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/client/ObjectStoreClientConfig.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/client/ObjectStoreClientConfig.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/client/ObjectStoreClientConfig.java
@@ -22,14 +22,16 @@
import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
import app.coronawarn.server.services.distribution.config.DistributionServiceConfig.ObjectStore;
-import io.minio.MinioClient;
-import io.minio.errors.InvalidEndpointException;
-import io.minio.errors.InvalidPortException;
+import java.net.URI;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
+import software.amazon.awssdk.auth.credentials.AwsCredentials;
+import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
+import software.amazon.awssdk.regions.Region;
+import software.amazon.awssdk.services.s3.S3Client;
/**
- * Manages the instantiation of the {@link MinioClient} bean.
+ * Manages the instantiation of the {@link ObjectStoreClient} bean.
*/
@Configuration
public class ObjectStoreClientConfig {
@@ -37,29 +39,44 @@ public class ObjectStoreClientConfig {
private static final String DEFAULT_REGION = "eu-west-1";
@Bean
- public ObjectStoreClient createObjectStoreClient(DistributionServiceConfig distributionServiceConfig)
- throws InvalidPortException, InvalidEndpointException {
+ public ObjectStoreClient createObjectStoreClient(DistributionServiceConfig distributionServiceConfig) {
return createClient(distributionServiceConfig.getObjectStore());
}
- private MinioClientWrapper createClient(ObjectStore objectStore)
- throws InvalidPortException, InvalidEndpointException {
- if (isSsl(objectStore)) {
- return new MinioClientWrapper(new MinioClient(
- objectStore.getEndpoint(),
- objectStore.getPort(),
- objectStore.getAccessKey(), objectStore.getSecretKey(),
- DEFAULT_REGION,
- true));
- } else {
- return new MinioClientWrapper(new MinioClient(
- objectStore.getEndpoint(),
- objectStore.getPort(),
- objectStore.getAccessKey(), objectStore.getSecretKey()));
- }
+ private ObjectStoreClient createClient(ObjectStore objectStore) {
+ return new S3ClientWrapper(S3Client.builder()
+ .region(Region.of(DEFAULT_REGION))
+ .endpointOverride(URI.create(objectStore.getEndpoint() + ":" + objectStore.getPort()))
+ .credentialsProvider(new CredentialsProvider(objectStore.getAccessKey(), objectStore.getSecretKey()))
+ .build());
}
- private boolean isSsl(ObjectStore objectStore) {
- return objectStore.getEndpoint().startsWith("https://");
+ /**
+ * Statically serves credentials based on construction arguments.
+ */
+ static class CredentialsProvider implements AwsCredentialsProvider {
+
+ final String accessKeyId;
+ final String secretAccessKey;
+
+ public CredentialsProvider(String accessKeyId, String secretAccessKey) {
+ this.accessKeyId = accessKeyId;
+ this.secretAccessKey = secretAccessKey;
+ }
+
+ @Override
+ public AwsCredentials resolveCredentials() {
+ return new AwsCredentials() {
+ @Override
+ public String accessKeyId() {
+ return accessKeyId;
+ }
+
+ @Override
+ public String secretAccessKey() {
+ return secretAccessKey;
+ }
+ };
+ }
}
}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/client/S3ClientWrapper.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/client/S3ClientWrapper.java
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/client/S3ClientWrapper.java
@@ -0,0 +1,123 @@
+/*-
+ * ---license-start
+ * Corona-Warn-App
+ * ---
+ * Copyright (C) 2020 SAP SE and all other contributors
+ * ---
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://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 for the specific language governing permissions and
+ * limitations under the License.
+ * ---license-end
+ */
+
+package app.coronawarn.server.services.distribution.objectstore.client;
+
+import static java.util.stream.Collectors.toList;
+
+import java.nio.file.Path;
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import software.amazon.awssdk.core.exception.SdkException;
+import software.amazon.awssdk.core.sync.RequestBody;
+import software.amazon.awssdk.services.s3.S3Client;
+import software.amazon.awssdk.services.s3.model.Delete;
+import software.amazon.awssdk.services.s3.model.DeleteObjectsRequest;
+import software.amazon.awssdk.services.s3.model.DeleteObjectsResponse;
+import software.amazon.awssdk.services.s3.model.ListObjectsV2Request;
+import software.amazon.awssdk.services.s3.model.ListObjectsV2Response;
+import software.amazon.awssdk.services.s3.model.ObjectIdentifier;
+import software.amazon.awssdk.services.s3.model.PutObjectRequest;
+
+/**
+ * Implementation of {@link ObjectStoreClient} that encapsulates an {@link S3Client}.
+ */
+public class S3ClientWrapper implements ObjectStoreClient {
+
+ private static final Logger logger = LoggerFactory.getLogger(S3ClientWrapper.class);
+
+ private final S3Client s3Client;
+
+ public S3ClientWrapper(S3Client s3Client) {
+ this.s3Client = s3Client;
+ }
+
+ @Override
+ public boolean bucketExists(String bucketName) {
+ try {
+ return !s3Client.listBuckets().buckets().stream().findFirst().isEmpty();
+ } catch (SdkException e) {
+ throw new ObjectStoreOperationFailedException("Failed to determine if bucket exists.", e);
+ }
+ }
+
+ @Override
+ public List<S3Object> getObjects(String bucket, String prefix) {
+ try {
+ ListObjectsV2Response response =
+ s3Client.listObjectsV2(ListObjectsV2Request.builder().prefix(prefix).bucket(bucket).build());
+ return response.contents().stream().map(S3ClientWrapper::buildS3Object).collect(toList());
+ } catch (SdkException e) {
+ throw new ObjectStoreOperationFailedException("Failed to upload object to object store", e);
+ }
+ }
+
+ @Override
+ public void putObject(String bucket, String objectName, Path filePath, Map<HeaderKey, String> headers) {
+ RequestBody bodyFile = RequestBody.fromFile(filePath);
+
+ var requestBuilder = PutObjectRequest.builder().bucket(bucket).key(objectName);
+ if (headers.containsKey(HeaderKey.AMZ_ACL)) {
+ requestBuilder.acl(headers.get(HeaderKey.AMZ_ACL));
+ }
+ if (headers.containsKey(HeaderKey.CACHE_CONTROL)) {
+ requestBuilder.cacheControl(headers.get(HeaderKey.CACHE_CONTROL));
+ }
+
+ try {
+ s3Client.putObject(requestBuilder.build(), bodyFile);
+ } catch (SdkException e) {
+ throw new ObjectStoreOperationFailedException("Failed to upload object to object store", e);
+ }
+ }
+
+ @Override
+ public void removeObjects(String bucket, List<String> objectNames) {
+ if (objectNames.isEmpty()) {
+ return;
+ }
+
+ Collection<ObjectIdentifier> identifiers = objectNames.stream()
+ .map(key -> ObjectIdentifier.builder().key(key).build()).collect(toList());
+
+ try {
+ DeleteObjectsResponse response = s3Client.deleteObjects(
+ DeleteObjectsRequest.builder()
+ .bucket(bucket)
+ .delete(Delete.builder().objects(identifiers).build()).build());
+
+ if (response.hasErrors()) {
+ String errMessage = "Failed to remove objects from object store.";
+ logger.error("{} {}", errMessage, response.errors());
+ throw new ObjectStoreOperationFailedException(errMessage);
+ }
+ } catch (SdkException e) {
+ throw new ObjectStoreOperationFailedException("Failed to remove objects from object store.", e);
+ }
+ }
+
+ private static S3Object buildS3Object(software.amazon.awssdk.services.s3.model.S3Object s3Object) {
+ String etag = s3Object.eTag().replaceAll("\"", "");
+ return new S3Object(s3Object.key(), etag);
+ }
+}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/client/S3Object.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/client/S3Object.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/client/S3Object.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/client/S3Object.java
@@ -20,7 +20,6 @@
package app.coronawarn.server.services.distribution.objectstore.client;
-import io.minio.messages.Item;
import java.util.Objects;
/**
@@ -64,17 +63,6 @@ public String getEtag() {
return etag;
}
- /**
- * Returns a new instance of an S3Object based on the given item.
- *
- * @param item the item (as provided by MinIO)
- * @return the S3Object representation
- */
- public static S3Object of(Item item) {
- String etag = item.etag().replaceAll("\"", "");
- return new S3Object(item.objectName(), etag);
- }
-
@Override
public boolean equals(Object o) {
if (this == o) {
diff --git a/services/distribution/src/main/java/io/minio/messages/Item.java b/services/distribution/src/main/java/io/minio/messages/Item.java
deleted file mode 100644
--- a/services/distribution/src/main/java/io/minio/messages/Item.java
+++ /dev/null
@@ -1,131 +0,0 @@
-/*
- * MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2015 MinIO, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://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 for the specific language governing permissions and
- * limitations under the License.
- */
-
-package io.minio.messages;
-
-import java.time.ZonedDateTime;
-import java.util.Map;
-import org.simpleframework.xml.Element;
-import org.simpleframework.xml.Root;
-
-/* ----------------------------------------------------------------
- * Copied from MinIO due to patch not yet available.
- * https://github.com/minio/minio-java/pull/921
- * Waiting for new release version: 7.0.3
- * ----------------------------------------------------------------
- */
-
-/**
- * Helper class to denote Object information in {@link ListBucketResult} and {@link ListBucketResultV1}.
- */
-@Root(name = "Contents", strict = false)
-public class Item {
-
- @Element(name = "Key")
- private String objectName;
-
- @Element(name = "LastModified")
- private ResponseDate lastModified;
-
- @Element(name = "ETag")
- private String etag;
-
- @Element(name = "Size")
- private long size;
-
- @Element(name = "StorageClass")
- private String storageClass;
-
- @Element(name = "Owner", required = false) /* Monkeypatch: Owner should be optional */
- private Owner owner;
-
- @Element(name = "UserMetadata", required = false)
- private Metadata userMetadata;
-
- private boolean isDir = false;
-
- public Item() {
-
- }
-
- /**
- * Constructs a new Item for prefix i.e. directory.
- */
- public Item(String prefix) {
- this.objectName = prefix;
- this.isDir = true;
- }
-
- /**
- * Returns object name.
- */
- public String objectName() {
- return objectName;
- }
-
- /**
- * Returns last modified time of the object.
- */
- public ZonedDateTime lastModified() {
- return lastModified.zonedDateTime();
- }
-
- /**
- * Returns ETag of the object.
- */
- public String etag() {
- return etag;
- }
-
- /**
- * Returns object size.
- */
- public long size() {
- return size;
- }
-
- /**
- * Returns storage class of the object.
- */
- public String storageClass() {
- return storageClass;
- }
-
- /**
- * Returns owner object of given the object.
- */
- public Owner owner() {
- return owner;
- }
-
- /**
- * Returns user metadata. This is MinIO specific extension to ListObjectsV2.
- */
- public Map<String, String> userMetadata() {
- if (userMetadata == null) {
- return null;
- }
-
- return userMetadata.get();
- }
-
- /**
- * Returns whether the object is a directory or not.
- */
- public boolean isDir() {
- return isDir;
- }
-}
</patch> | diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/client/MinioClientWrapperTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/client/MinioClientWrapperTest.java
deleted file mode 100644
--- a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/client/MinioClientWrapperTest.java
+++ /dev/null
@@ -1,235 +0,0 @@
-/*-
- * ---license-start
- * Corona-Warn-App
- * ---
- * Copyright (C) 2020 SAP SE and all other contributors
- * ---
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://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 for the specific language governing permissions and
- * limitations under the License.
- * ---license-end
- */
-
-package app.coronawarn.server.services.distribution.objectstore.client;
-
-import static java.util.Collections.emptyMap;
-import static java.util.Map.entry;
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
-import static org.assertj.core.util.IterableUtil.iterable;
-import static org.assertj.core.util.Lists.list;
-import static org.assertj.core.util.Maps.newHashMap;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.anyBoolean;
-import static org.mockito.ArgumentMatchers.anyList;
-import static org.mockito.ArgumentMatchers.anyString;
-import static org.mockito.ArgumentMatchers.eq;
-import static org.mockito.Mockito.atLeastOnce;
-import static org.mockito.Mockito.doThrow;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
-import app.coronawarn.server.services.distribution.objectstore.client.ObjectStoreClient.HeaderKey;
-import com.fasterxml.jackson.core.JsonParseException;
-import com.fasterxml.jackson.databind.JsonMappingException;
-import io.minio.MinioClient;
-import io.minio.PutObjectOptions;
-import io.minio.Result;
-import io.minio.errors.ErrorResponseException;
-import io.minio.errors.InsufficientDataException;
-import io.minio.errors.InternalException;
-import io.minio.errors.InvalidBucketNameException;
-import io.minio.errors.InvalidResponseException;
-import io.minio.errors.XmlParserException;
-import io.minio.messages.DeleteError;
-import io.minio.messages.Item;
-import java.io.IOException;
-import java.nio.file.Path;
-import java.security.InvalidKeyException;
-import java.security.NoSuchAlgorithmException;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.stream.Stream;
-import org.assertj.core.util.Lists;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.params.ParameterizedTest;
-import org.junit.jupiter.params.provider.Arguments;
-import org.junit.jupiter.params.provider.MethodSource;
-import org.junit.jupiter.params.provider.ValueSource;
-import org.mockito.ArgumentCaptor;
-
-class MinioClientWrapperTest {
-
- private static final String VALID_BUCKET_NAME = "myBucket";
- private static final String VALID_PREFIX = "prefix";
- private static final String VALID_NAME = "object key";
-
- private MinioClient minioClient;
- private MinioClientWrapper minioClientWrapper;
-
- @BeforeEach
- public void setUpMocks() {
- minioClient = mock(MinioClient.class);
- minioClientWrapper = new MinioClientWrapper(minioClient);
- }
-
- @Test
- void testBucketExistsIfBucketExists() throws Exception {
- when(minioClient.bucketExists(any())).thenReturn(true);
- assertThat(minioClientWrapper.bucketExists(VALID_BUCKET_NAME)).isTrue();
- }
-
- @Test
- void testBucketExistsIfBucketDoesNotExist() throws Exception {
- when(minioClient.bucketExists(any())).thenReturn(false);
- assertThat(minioClientWrapper.bucketExists(VALID_BUCKET_NAME)).isFalse();
- }
-
- @ParameterizedTest
- @ValueSource(classes = {ErrorResponseException.class, InsufficientDataException.class,
- InternalException.class, IllegalArgumentException.class, InvalidBucketNameException.class,
- InvalidKeyException.class, InvalidResponseException.class,
- IOException.class, NoSuchAlgorithmException.class, XmlParserException.class})
- void bucketExistsThrowsObjectStoreOperationFailedExceptionIfClientThrows(Class<Exception> cause) throws Exception {
- when(minioClient.bucketExists(any())).thenThrow(cause);
- assertThatExceptionOfType(ObjectStoreOperationFailedException.class)
- .isThrownBy(() -> minioClientWrapper.bucketExists(VALID_BUCKET_NAME));
- }
-
- @Test
- void testGetObjectsSendsCorrectRequest() {
- when(minioClient.listObjects(anyString(), anyString(), anyBoolean())).thenReturn(iterable());
- minioClientWrapper.getObjects(VALID_BUCKET_NAME, VALID_PREFIX);
- verify(minioClient, atLeastOnce()).listObjects(eq(VALID_BUCKET_NAME), eq(VALID_PREFIX), eq(true));
- }
-
- @ParameterizedTest
- @MethodSource("createGetObjectsResults")
- void testGetObjects(List<S3Object> expResult) throws Exception {
- Iterable<Result<Item>> actResponse = buildListObjectsResponse(expResult);
- when(minioClient.listObjects(anyString(), anyString(), anyBoolean())).thenReturn(actResponse);
-
- List<S3Object> actResult = minioClientWrapper.getObjects(VALID_BUCKET_NAME, VALID_PREFIX);
-
- assertThat(actResult).isEqualTo(expResult);
- }
-
- private static Stream<Arguments> createGetObjectsResults() {
- return Stream.of(
- Lists.emptyList(),
- list(new S3Object("objName", "eTag")),
- list(new S3Object("objName1", "eTag1"), new S3Object("objName2", "eTag2"))
- ).map(Arguments::of);
- }
-
- private Iterable<Result<Item>> buildListObjectsResponse(List<S3Object> s3Objects) throws Exception {
- List<Result<Item>> response = new ArrayList<>(s3Objects.size());
-
- for (S3Object s3Object : s3Objects) {
- Item item = mock(Item.class);
- Result<Item> result = mock(Result.class);
- when(result.get()).thenReturn(item);
- when(item.etag()).thenReturn(s3Object.getEtag());
- when(item.objectName()).thenReturn(s3Object.getObjectName());
- response.add(result);
- }
-
- return iterable(response.toArray(new Result[response.size()]));
- }
-
- @Test
- void getObjectsRemovesDoubleQuotesFromEtags() throws Exception {
- String expEtag = "eTag";
- Iterable<Result<Item>> actResponse = buildListObjectsResponse(
- List.of(new S3Object(VALID_NAME, "\"" + expEtag + "\"")));
- when(minioClient.listObjects(anyString(), anyString(), anyBoolean())).thenReturn(actResponse);
-
- List<S3Object> actResult = minioClientWrapper.getObjects(VALID_BUCKET_NAME, VALID_PREFIX);
-
- assertThat(actResult).isEqualTo(List.of(new S3Object(VALID_NAME, expEtag)));
- }
-
- @ParameterizedTest
- @ValueSource(classes = {ErrorResponseException.class, InsufficientDataException.class, XmlParserException.class,
- InternalException.class, InvalidBucketNameException.class, InvalidKeyException.class, JsonParseException.class,
- InvalidResponseException.class, JsonMappingException.class, IOException.class, NoSuchAlgorithmException.class,
- IllegalArgumentException.class})
- void getObjectsThrowsObjectStoreOperationFailedExceptionIfClientThrows(Class<Exception> cause) throws Exception {
- Result<Item> actResult = mock(Result.class);
- when(actResult.get()).thenThrow(cause);
- when(minioClient.listObjects(anyString(), anyString(), anyBoolean())).thenReturn(iterable(actResult));
- assertThatExceptionOfType(ObjectStoreOperationFailedException.class)
- .isThrownBy(() -> minioClientWrapper.getObjects(VALID_BUCKET_NAME, VALID_PREFIX));
- }
-
- @Test
- void testPutObjectForNoHeaders() throws Exception {
- minioClientWrapper.putObject(VALID_BUCKET_NAME, VALID_NAME, Path.of(""), emptyMap());
- ArgumentCaptor<PutObjectOptions> options = ArgumentCaptor.forClass(PutObjectOptions.class);
- verify(minioClient, atLeastOnce()).putObject(eq(VALID_BUCKET_NAME), eq(VALID_NAME), eq(""), options.capture());
- assertThat(options.getValue().headers()).isEmpty();
- }
-
- @Test
- void testPutObjectForCacheControlHeader() throws Exception {
- String expCacheControl = "foo-cache-control";
-
- minioClientWrapper.putObject(VALID_BUCKET_NAME, VALID_NAME, Path.of(""),
- newHashMap(HeaderKey.CACHE_CONTROL, expCacheControl));
-
- ArgumentCaptor<PutObjectOptions> options = ArgumentCaptor.forClass(PutObjectOptions.class);
- verify(minioClient, atLeastOnce()).putObject(eq(VALID_BUCKET_NAME), eq(VALID_NAME), eq(""), options.capture());
- assertThat(options.getValue().headers()).hasSize(1);
- assertThat(options.getValue().headers()).contains(entry(HeaderKey.CACHE_CONTROL.keyValue, expCacheControl));
- }
-
- @Test
- void testPutObjectForAmzAclHeader() throws Exception {
- String expAcl = "foo-acl";
-
- minioClientWrapper.putObject(VALID_BUCKET_NAME, VALID_NAME, Path.of(""), newHashMap(HeaderKey.AMZ_ACL, expAcl));
-
- ArgumentCaptor<PutObjectOptions> options = ArgumentCaptor.forClass(PutObjectOptions.class);
- verify(minioClient, atLeastOnce()).putObject(eq(VALID_BUCKET_NAME), eq(VALID_NAME), eq(""), options.capture());
- assertThat(options.getValue().headers()).hasSize(1);
- assertThat(options.getValue().headers()).contains(entry(HeaderKey.AMZ_ACL.keyValue, expAcl));
- }
-
- @ParameterizedTest
- @ValueSource(classes = {ErrorResponseException.class, IllegalArgumentException.class, InsufficientDataException.class,
- InternalException.class, InvalidBucketNameException.class, InvalidKeyException.class, XmlParserException.class,
- IOException.class, NoSuchAlgorithmException.class, InvalidResponseException.class})
- void putObjectsThrowsObjectStoreOperationFailedExceptionIfClientThrows(Class<Exception> cause) throws Exception {
- doThrow(cause).when(minioClient).putObject(anyString(), anyString(), anyString(), any(PutObjectOptions.class));
- assertThatExceptionOfType(ObjectStoreOperationFailedException.class)
- .isThrownBy(() -> minioClientWrapper.putObject(VALID_BUCKET_NAME, VALID_PREFIX, Path.of(""), emptyMap()));
- }
-
- @Test
- void testRemoveObjects() {
- when(minioClient.removeObjects(anyString(), anyList())).thenReturn(iterable());
- List<String> expObjectNames = List.of("obj1", "obj2");
-
- minioClientWrapper.removeObjects(VALID_BUCKET_NAME, expObjectNames);
-
- verify(minioClient, atLeastOnce()).removeObjects(eq(VALID_BUCKET_NAME), eq(expObjectNames));
- }
-
- @Test
- void removeObjectsThrowsObjectStoreOperationFailedExceptionOnDeleteErrors() {
- Result<DeleteError> result = mock(Result.class);
- when(minioClient.removeObjects(anyString(), anyList())).thenReturn(iterable(result));
- assertThatExceptionOfType(ObjectStoreOperationFailedException.class)
- .isThrownBy(() -> minioClientWrapper.removeObjects(VALID_BUCKET_NAME, list(VALID_NAME)));
- }
-}
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/client/S3ClientWrapperTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/client/S3ClientWrapperTest.java
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/client/S3ClientWrapperTest.java
@@ -0,0 +1,238 @@
+/*-
+ * ---license-start
+ * Corona-Warn-App
+ * ---
+ * Copyright (C) 2020 SAP SE and all other contributors
+ * ---
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://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 for the specific language governing permissions and
+ * limitations under the License.
+ * ---license-end
+ */
+
+package app.coronawarn.server.services.distribution.objectstore.client;
+
+import static java.util.Collections.emptyMap;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
+import static org.assertj.core.util.Maps.newHashMap;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.atLeastOnce;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import app.coronawarn.server.services.distribution.objectstore.client.ObjectStoreClient.HeaderKey;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+import org.assertj.core.util.Lists;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.junit.jupiter.params.provider.ValueSource;
+import org.springframework.test.context.junit.jupiter.SpringExtension;
+import software.amazon.awssdk.core.exception.SdkClientException;
+import software.amazon.awssdk.core.exception.SdkException;
+import software.amazon.awssdk.core.sync.RequestBody;
+import software.amazon.awssdk.services.s3.S3Client;
+import software.amazon.awssdk.services.s3.model.Bucket;
+import software.amazon.awssdk.services.s3.model.Delete;
+import software.amazon.awssdk.services.s3.model.DeleteObjectsRequest;
+import software.amazon.awssdk.services.s3.model.DeleteObjectsResponse;
+import software.amazon.awssdk.services.s3.model.ListBucketsResponse;
+import software.amazon.awssdk.services.s3.model.ListObjectsV2Request;
+import software.amazon.awssdk.services.s3.model.ListObjectsV2Response;
+import software.amazon.awssdk.services.s3.model.NoSuchBucketException;
+import software.amazon.awssdk.services.s3.model.ObjectIdentifier;
+import software.amazon.awssdk.services.s3.model.PutObjectRequest;
+import software.amazon.awssdk.services.s3.model.S3Error;
+import software.amazon.awssdk.services.s3.model.S3Exception;
+import software.amazon.awssdk.utils.builder.SdkBuilder;
+
+@ExtendWith(SpringExtension.class)
+class S3ClientWrapperTest {
+
+ private static final String VALID_BUCKET_NAME = "myBucket";
+ private static final String VALID_PREFIX = "prefix";
+ private static final String VALID_NAME = "object key";
+
+ private S3Client s3Client;
+ private S3ClientWrapper s3ClientWrapper;
+ private List<Bucket> existingBuckets;
+
+ @BeforeEach
+ public void setUpMocks() {
+ s3Client = mock(S3Client.class);
+ s3ClientWrapper = new S3ClientWrapper(s3Client);
+ existingBuckets = new ArrayList<>();
+ ListBucketsResponse listBucketsResponse = mock(ListBucketsResponse.class);
+
+ when(listBucketsResponse.buckets()).thenReturn(existingBuckets);
+ when(s3Client.listBuckets()).thenReturn(listBucketsResponse);
+ }
+
+ @Test
+ void testBucketExistsIfBucketExists() {
+ existingBuckets.add(Bucket.builder().name(VALID_BUCKET_NAME).build());
+ assertThat(s3ClientWrapper.bucketExists(VALID_BUCKET_NAME)).isTrue();
+ }
+
+ @Test
+ void testBucketExistsIfBucketDoesNotExist() {
+ assertThat(s3ClientWrapper.bucketExists(VALID_BUCKET_NAME)).isFalse();
+ }
+
+ @ParameterizedTest
+ @ValueSource(classes = {S3Exception.class, SdkClientException.class, SdkException.class})
+ void bucketExistsThrowsObjectStoreOperationFailedExceptionIfClientThrows(Class<Exception> cause) {
+ when(s3Client.listBuckets()).thenThrow(cause);
+ assertThatExceptionOfType(ObjectStoreOperationFailedException.class)
+ .isThrownBy(() -> s3ClientWrapper.bucketExists(VALID_BUCKET_NAME));
+ }
+
+ @Test
+ void testGetObjectsSendsCorrectRequest() {
+ when(s3Client.listObjectsV2(any(ListObjectsV2Request.class))).thenReturn(ListObjectsV2Response.builder().build());
+
+ s3ClientWrapper.getObjects(VALID_BUCKET_NAME, VALID_PREFIX);
+
+ ListObjectsV2Request expRequest = ListObjectsV2Request.builder()
+ .prefix(VALID_PREFIX).bucket(VALID_BUCKET_NAME).build();
+ verify(s3Client, atLeastOnce()).listObjectsV2(eq(expRequest));
+ }
+
+ @ParameterizedTest
+ @MethodSource("createGetObjectsResults")
+ void testGetObjects(List<S3Object> expResult) {
+ ListObjectsV2Response actResponse = buildListObjectsResponse(expResult);
+ when(s3Client.listObjectsV2(any(ListObjectsV2Request.class))).thenReturn(actResponse);
+
+ List<S3Object> actResult = s3ClientWrapper.getObjects(VALID_BUCKET_NAME, VALID_PREFIX);
+
+ assertThat(actResult).isEqualTo(expResult);
+ }
+
+ private static Stream<Arguments> createGetObjectsResults() {
+ return Stream.of(
+ Lists.emptyList(),
+ Lists.list(new S3Object("objName", "eTag")),
+ Lists.list(new S3Object("objName1", "eTag1"), new S3Object("objName2", "eTag2"))
+ ).map(Arguments::of);
+ }
+
+ private ListObjectsV2Response buildListObjectsResponse(List<S3Object> s3Objects) {
+ var responseObjects = s3Objects.stream().map(
+ s3Object -> software.amazon.awssdk.services.s3.model.S3Object.builder()
+ .key(s3Object.getObjectName())
+ .eTag(s3Object.getEtag()))
+ .map(SdkBuilder::build).collect(Collectors.toList());
+ return ListObjectsV2Response.builder().contents(responseObjects).build();
+ }
+
+ @Test
+ void getObjectsRemovesDoubleQuotesFromEtags() {
+ String expEtag = "eTag";
+ ListObjectsV2Response actResponse =
+ buildListObjectsResponse(List.of(new S3Object(VALID_NAME, "\"" + expEtag + "\"")));
+ when(s3Client.listObjectsV2(any(ListObjectsV2Request.class))).thenReturn(actResponse);
+
+ List<S3Object> actResult = s3ClientWrapper.getObjects(VALID_BUCKET_NAME, VALID_PREFIX);
+
+ assertThat(actResult).isEqualTo(List.of(new S3Object(VALID_NAME, expEtag)));
+ }
+
+ @ParameterizedTest
+ @ValueSource(classes = {NoSuchBucketException.class, S3Exception.class, SdkClientException.class, SdkException.class})
+ void getObjectsThrowsObjectStoreOperationFailedExceptionIfClientThrows(Class<Exception> cause) {
+ when(s3Client.listObjectsV2(any(ListObjectsV2Request.class))).thenThrow(cause);
+ assertThatExceptionOfType(ObjectStoreOperationFailedException.class)
+ .isThrownBy(() -> s3ClientWrapper.getObjects(VALID_BUCKET_NAME, VALID_PREFIX));
+ }
+
+ @Test
+ void testPutObjectForNoHeaders() {
+ s3ClientWrapper.putObject(VALID_BUCKET_NAME, VALID_NAME, Path.of(""), emptyMap());
+
+ PutObjectRequest expRequest = PutObjectRequest.builder().bucket(VALID_BUCKET_NAME).key(VALID_NAME).build();
+ verify(s3Client, atLeastOnce()).putObject(eq(expRequest), any(RequestBody.class));
+ }
+
+ @Test
+ void testPutObjectForCacheControlHeader() {
+ var expCacheControl = "foo-cache-control";
+ s3ClientWrapper
+ .putObject(VALID_BUCKET_NAME, VALID_NAME, Path.of(""), newHashMap(HeaderKey.CACHE_CONTROL, expCacheControl));
+
+ PutObjectRequest expRequest =
+ PutObjectRequest.builder().bucket(VALID_BUCKET_NAME).key(VALID_NAME).cacheControl(expCacheControl).build();
+ verify(s3Client, atLeastOnce()).putObject(eq(expRequest), any(RequestBody.class));
+ }
+
+ @Test
+ void testPutObjectForAmzAclHeader() {
+ String expAcl = "foo-acl";
+ s3ClientWrapper.putObject(VALID_BUCKET_NAME, VALID_NAME, Path.of(""), newHashMap(HeaderKey.AMZ_ACL, expAcl));
+
+ PutObjectRequest expRequest =
+ PutObjectRequest.builder().bucket(VALID_BUCKET_NAME).key(VALID_NAME).acl(expAcl).build();
+ verify(s3Client, atLeastOnce()).putObject(eq(expRequest), any(RequestBody.class));
+ }
+
+ @ParameterizedTest
+ @ValueSource(classes = {NoSuchBucketException.class, S3Exception.class, SdkClientException.class, SdkException.class})
+ void putObjectsThrowsObjectStoreOperationFailedExceptionIfClientThrows(Class<Exception> cause) {
+ when(s3Client.putObject(any(PutObjectRequest.class), any(RequestBody.class))).thenThrow(cause);
+ assertThatExceptionOfType(ObjectStoreOperationFailedException.class)
+ .isThrownBy(() -> s3ClientWrapper.putObject(VALID_BUCKET_NAME, VALID_PREFIX, Path.of(""), emptyMap()));
+ }
+
+ @Test
+ void testRemoveObjects() {
+ when(s3Client.deleteObjects(any(DeleteObjectsRequest.class))).thenReturn(DeleteObjectsResponse.builder().build());
+ List<String> expObjectNames = List.of("obj1", "obj2");
+
+ s3ClientWrapper.removeObjects(VALID_BUCKET_NAME, expObjectNames);
+
+ DeleteObjectsRequest expRequest = DeleteObjectsRequest.builder()
+ .bucket(VALID_BUCKET_NAME).delete(buildDeleteObject(expObjectNames)).build();
+ verify(s3Client, atLeastOnce()).deleteObjects(eq(expRequest));
+ }
+
+ private Delete buildDeleteObject(List<String> objectNames) {
+ return Delete.builder().objects(objectNames.stream().map(
+ key -> ObjectIdentifier.builder().key(key).build()).collect(Collectors.toList())).build();
+ }
+
+ @Test
+ void removeObjectsThrowsOnDeletionErrors() {
+ DeleteObjectsResponse actResponse = DeleteObjectsResponse.builder().errors(S3Error.builder().build()).build();
+
+ when(s3Client.deleteObjects(any(DeleteObjectsRequest.class))).thenReturn(actResponse);
+
+ assertThatExceptionOfType(ObjectStoreOperationFailedException.class)
+ .isThrownBy(() -> s3ClientWrapper.removeObjects(VALID_BUCKET_NAME, List.of(VALID_NAME)));
+ }
+
+ @ParameterizedTest
+ @ValueSource(classes = {NoSuchBucketException.class, S3Exception.class, SdkClientException.class, SdkException.class})
+ void removeObjectsThrowsObjectStoreOperationFailedExceptionIfClientThrows(Class<Exception> cause) {
+ when(s3Client.deleteObjects(any(DeleteObjectsRequest.class))).thenThrow(cause);
+ assertThatExceptionOfType(ObjectStoreOperationFailedException.class)
+ .isThrownBy(() -> s3ClientWrapper.removeObjects(VALID_BUCKET_NAME, List.of(VALID_NAME)));
+ }
+}
| |||||
corona-warn-app__cwa-server-972 | You will be provided with a partial code base and an issue statement explaining a problem to resolve.
<issue>
[BSI][20201107] Denial-of-Service in Download Service
Rating: Informational
Description:
The download service component of the cwa-server backend can be forced into an endless loop by a malicious or faulty federation gateway server. When downloading new batches from the federation gateway server, the download service checks the nextBatchTag header of the federation gateway server’s response. If this header is set, the download service will continue requesting a batch with this tag. It will not stop as long as the server includes this header. This can trap the download service in an endless loop.
This highly depends on the behavior and implementation of the federation gateway server. However, even a non-malicious, faulty implementation might trigger this issue. Additionally, the issue was sometimes hard to reproduce as the server first has to be forced to request new batches (which in some cases required setting the EFGS_ENABLE_DATE_BASED_DOWNLOAD configuration to true).
Affected System:
cwa-server (commit 4f3f460f580ea5d548dff0e3ceb739908c83d1a7)
Proof of Concept:
The following screenshots show the offending lines in the FederationBatchProcessor.java:
<img width="846" alt="Download Service DoS Offending Code" src="https://user-images.githubusercontent.com/65443025/98435998-dcd5f900-20d7-11eb-9f5e-3fb7f449ca58.png">
The following snippets show a minimalistic federation gateway server mock that returns invalid data but sets the nextBatchTag header on each response. The first request needs to fail (in this case implemented by sending an invalid HTTP request body) so that the batch tag is added to the list of unprocessed batches.
<img width="775" alt="snippet-1" src="https://user-images.githubusercontent.com/65443025/98436046-5c63c800-20d8-11eb-843e-47e98b9c2ed7.png">
<img width="779" alt="snippet-2" src="https://user-images.githubusercontent.com/65443025/98436048-61c11280-20d8-11eb-9d77-43ebd770a556.png">
The following screenshot shows the failing first request on the first run of the download service:
<img width="824" alt="Download Service DoS First Invalid Request" src="https://user-images.githubusercontent.com/65443025/98436059-87e6b280-20d8-11eb-9ad0-7ceaaa557add.png">
The next screenshot shows the log output of the download service when it is run again. It can be seen that the server will endlessly try to request a next batch.
<img width="845" alt="Download Service DoS Endless Loop Log" src="https://user-images.githubusercontent.com/65443025/98436074-ab116200-20d8-11eb-8c3c-ac545d9c1b07.png">
Recommended Controls:
The while loop should be adapted so that it is not possible for it to continue forever. The received nextBatchTag header should be checked. If it is already contained in the list of unprocessed batches, it should not be added again. This does not protect against a malicious server that sends different batch tags on each request. Therefore, alternatively, a timeout value or a maximum number of retries could be introduced.
</issue>
<code>
[start of README.md]
1 <!-- markdownlint-disable MD041 -->
2 <h1 align="center">
3 Corona-Warn-App Server
4 </h1>
5
6 <p align="center">
7 <a href="https://github.com/corona-warn-app/cwa-server/commits/" title="Last Commit"><img src="https://img.shields.io/github/last-commit/corona-warn-app/cwa-server?style=flat"></a>
8 <a href="https://github.com/corona-warn-app/cwa-server/issues" title="Open Issues"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat"></a>
9 <a href="https://circleci.com/gh/corona-warn-app/cwa-server" title="Build Status"><img src="https://circleci.com/gh/corona-warn-app/cwa-server.svg?style=shield&circle-token=4ab059989d10709df19eb4b98ab7c121a25e981a"></a>
10 <a href="https://sonarcloud.io/dashboard?id=corona-warn-app_cwa-server" title="Quality Gate"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=alert_status"></a>
11 <a href="https://sonarcloud.io/component_measures?id=corona-warn-app_cwa-server&metric=Coverage&view=list" title="Coverage"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=coverage"></a>
12 <a href="https://github.com/corona-warn-app/cwa-server/blob/master/LICENSE" title="License"><img src="https://img.shields.io/badge/License-Apache%202.0-green.svg?style=flat"></a>
13 <a href="https://api.reuse.software/badge/github.com/corona-warn-app/cwa-server" title="REUSE Status"><img src="https://api.reuse.software/badge/github.com/corona-warn-app/cwa-server"></a>
14 </p>
15
16 <p align="center">
17 <a href="#development">Development</a> •
18 <a href="#service-apis">Service APIs</a> •
19 <a href="#documentation">Documentation</a> •
20 <a href="#support-and-feedback">Support</a> •
21 <a href="#how-to-contribute">Contribute</a> •
22 <a href="#contributors">Contributors</a> •
23 <a href="#repositories">Repositories</a> •
24 <a href="#licensing">Licensing</a>
25 </p>
26
27 The goal of this project is to develop the official Corona-Warn-App for Germany based on the exposure notification API from [Apple](https://www.apple.com/covid19/contacttracing/) and [Google](https://www.google.com/covid19/exposurenotifications/). The apps (for both iOS and Android) use Bluetooth technology to exchange anonymous encrypted data with other mobile phones (on which the app is also installed) in the vicinity of an app user's phone. The data is stored locally on each user's device, preventing authorities or other parties from accessing or controlling the data. This repository contains the **implementation of the server for encryption keys** for the Corona-Warn-App.
28
29 In this documentation, Corona-Warn-App services are also referred to as CWA services.
30
31 ## Architecture Overview
32
33 You can find the architecture overview [here](/docs/ARCHITECTURE.md), which will give you
34 a good starting point in how the backend services interact with other services, and what purpose
35 they serve.
36
37 ## Development
38
39 After you've checked out this repository, you can run the application in one of the following ways:
40
41 * As a [Docker](https://www.docker.com/)-based deployment on your local machine. You can run either:
42 * Single components using the respective Dockerfile or
43 * The full backend using the Docker Compose (which is considered the most convenient way)
44 * As a [Maven](https://maven.apache.org)-based build on your local machine.
45 If you want to develop something in a single component, this approach is preferable.
46
47 ### Docker-Based Deployment
48
49 If you want to use Docker-based deployment, you need to install Docker on your local machine. For more information about downloading and installing Docker, see the [official Docker documentation](https://docs.docker.com/get-docker/).
50
51 #### Running the Full CWA Backend Using Docker Compose
52
53 For your convenience, a full setup for local development and testing purposes, including the generation of test data has been prepared using [Docker Compose](https://docs.docker.com/compose/reference/overview/). To build the backend services, run ```docker-compose build``` in the repository's root directory. A default configuration file can be found under ```.env``` in the root folder of the repository. If the endpoints are to be exposed to the network the default values in this file should be changed before docker-compose is run.
54
55 Once the services are built, you can start the whole backend using ```docker-compose up```.
56 The distribution service runs once and then finishes. If you want to trigger additional distribution runs, run ```docker-compose run distribution```.
57
58 The docker-compose contains the following services:
59
60 Service | Description | Endpoint and Default Credentials
61 ------------------|-------------|-----------
62 submission | The Corona-Warn-App submission service | `http://localhost:8000` <br> `http://localhost:8006` (for actuator endpoint)
63 distribution | The Corona-Warn-App distribution service | NO ENDPOINT
64 postgres | A [postgres] database installation | `localhost:8001` <br> `postgres:5432` (from containerized pgadmin) <br> Username: postgres <br> Password: postgres
65 pgadmin | A [pgadmin](https://www.pgadmin.org/) installation for the postgres database | `http://localhost:8002` <br> Username: [email protected] <br> Password: password
66 cloudserver | [Zenko CloudServer] is a S3-compliant object store | `http://localhost:8003/` <br> Access key: accessKey1 <br> Secret key: verySecretKey1
67 verification-fake | A very simple fake implementation for the tan verification. | `http://localhost:8004/version/v1/tan/verify` <br> The only valid tan is `edc07f08-a1aa-11ea-bb37-0242ac130002`.
68
69 ##### Known Limitation
70
71 In rare cases the docker-compose runs into a timing issue if the distribution service starts before the bucket of the objectstore was created. This is not a big issue as you can simply run ```docker-compose run distribution``` to trigger additional distribution runs after the objectstore was initialized.
72
73 #### Running Single CWA Services Using Docker
74
75 If you would like to build and run a single CWA service, it's considered easiest to run them in a Docker environment. You can do this using the script provided in the respective CWA service directory. The Docker script first builds the CWA service and then creates an image for the runtime, which means that there are no additional dependencies for you to install.
76
77 To build and run the distribution service, run the following command:
78
79 ```bash
80 ./services/distribution/build_and_run.sh
81 ```
82
83 To build and run the submission service, run the following command:
84
85 ```bash
86 ./services/submission/build_and_run.sh
87 ```
88
89 The submission service is available on [localhost:8080](http://localhost:8080 ).
90
91 ### Maven-Based Build
92
93 If you want to actively develop in one of the CWA services, the Maven-based runtime is most suitable.
94 To prepare your machine to run the CWA project locally, we recommend that you first ensure that you've installed the following:
95
96 * Minimum JDK Version 11: [OpenJDK](https://openjdk.java.net/) / [SapMachine](https://sap.github.io/SapMachine/)
97 * [Maven 3.6](https://maven.apache.org/)
98 * [Postgres]
99 * [Zenko CloudServer]
100
101 If you are already running a local Postgres, you need to create a database `cwa` and run the following setup scripts:
102
103 * Create the different CWA roles first by executing [create-roles.sql](setup/create-roles.sql).
104 * Create local database users for the specific roles by running [create-users.sql](./local-setup/create-users.sql).
105 * It is recommended to also run [enable-test-data-docker-compose.sql](./local-setup/enable-test-data-docker-compose.sql)
106 , which enables the test data generation profile. If you already had CWA running before and an existing `diagnosis-key`
107 table on your database, you need to run [enable-test-data.sql](./local-setup/enable-test-data.sql) instead.
108
109 You can also use `docker-compose` to start Postgres and Zenko. If you do that, you have to
110 set the following environment-variables when running the Spring project:
111
112 For the distribution module:
113
114 ```bash
115 POSTGRESQL_SERVICE_PORT=8001
116 VAULT_FILESIGNING_SECRET=</path/to/your/private_key>
117 SPRING_PROFILES_ACTIVE=signature-dev,disable-ssl-client-postgres
118 ```
119
120 For the submission module:
121
122 ```bash
123 POSTGRESQL_SERVICE_PORT=8001
124 SPRING_PROFILES_ACTIVE=disable-ssl-server,disable-ssl-client-postgres,disable-ssl-client-verification,disable-ssl-client-verification-verify-hostname
125 ```
126
127 #### Configure
128
129 After you made sure that the specified dependencies are running, configure them in the respective configuration files.
130
131 * Configure the Postgres connection in the [submission config](./services/submission/src/main/resources/application.yaml) and in the [distribution config](./services/distribution/src/main/resources/application.yaml)
132 * Configure the S3 compatible object storage in the [distribution config](./services/distribution/src/main/resources/application.yaml)
133 * Configure the private key for the distribution service, the path need to be prefixed with `file:`
134 * `VAULT_FILESIGNING_SECRET` should be the path to the private key, example available in `<repo-root>/docker-compose-test-secrets/private.pem`
135
136 #### Build
137
138 After you've checked out the repository, to build the project, run ```mvn install``` in your base directory.
139
140 #### Run
141
142 Navigate to the service you want to start and run the spring-boot:run target. The configured Postgres and the configured S3 compliant object storage are used as default. When you start the submission service, the endpoint is available on your local port 8080.
143
144 If you want to start the submission service, for example, you start it as follows:
145
146 ```bash
147 cd services/submission/
148 mvn spring-boot:run
149 ```
150
151 #### Debugging
152
153 To enable the `DEBUG` log level, you can run the application using the Spring `debug` profile.
154
155 ```bash
156 mvn spring-boot:run -Dspring.profiles.active=debug
157 ```
158
159 To be able to set breakpoints (e.g. in IntelliJ), it may be necessary to use the ```-Dspring-boot.run.fork=false``` parameter.
160
161 ## Service APIs
162
163 The API that is being exposed by the backend services is documented in an [OpenAPI](https://www.openapis.org/) specification. The specification files are available at the following locations:
164
165 Service | OpenAPI Specification
166 --------------------------|-------------
167 Submission Service | [services/submission/api_v1.json](https://github.com/corona-warn-app/cwa-server/raw/master/services/submission/api_v1.json)
168 Distribution Service | [services/distribution/api_v1.json](https://github.com/corona-warn-app/cwa-server/raw/master/services/distribution/api_v1.json)
169
170 ## Spring Profiles
171
172 ### Distribution
173
174 See [Distribution Service - Spring Profiles](/docs/DISTRIBUTION.md#spring-profiles).
175
176 ### Submission
177
178 See [Submission Service - Spring Profiles](/docs/SUBMISSION.md#spring-profiles).
179
180 ## Documentation
181
182 The full documentation for the Corona-Warn-App can be found in the [cwa-documentation](https://github.com/corona-warn-app/cwa-documentation) repository. The documentation repository contains technical documents, architecture information, and whitepapers related to this implementation.
183
184 The documentation for cwa-server can be found under the [/docs](./docs) folder.
185
186 The JavaDoc documentation for cwa-server is hosted by Github Pages at [https://corona-warn-app.github.io/cwa-server](https://corona-warn-app.github.io/cwa-server).
187
188 ## Support and Feedback
189
190 The following channels are available for discussions, feedback, and support requests:
191
192 | Type | Channel |
193 | ------------------------ | ------------------------------------------------------ |
194 | **General Discussion** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="General Discussion"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/question.svg?style=flat-square"></a> </a> |
195 | **Concept Feedback** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="Open Concept Feedback"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/architecture.svg?style=flat-square"></a> |
196 | **Backend Issue** | <a href="https://github.com/corona-warn-app/cwa-server/issues/new/choose" title="Open Backend Issue"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat-square"></a> |
197 | **Other Requests** | <a href="mailto:[email protected]" title="Email CWA Team"><img src="https://img.shields.io/badge/email-CWA%20team-green?logo=mail.ru&style=flat-square&logoColor=white"></a> |
198
199 ## How to Contribute
200
201 Contribution and feedback are 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.
202
203 ## Contributors
204
205 The German government has asked SAP and Deutsche Telekom to develop the Corona-Warn-App for Germany as open source software. Deutsche Telekom is providing the network and mobile technology and will operate and run the backend for the app in a safe, scalable and stable manner. SAP is responsible for the app development, its framework and the underlying platform. Therefore, development teams of SAP and Deutsche Telekom are contributing to this project. At the same time 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.
206
207 ## Repositories
208
209 The following public repositories are currently available for the Corona-Warn-App:
210
211 | Repository | Description |
212 | ------------------- | --------------------------------------------------------------------- |
213 | [cwa-documentation] | Project overview, general documentation, and white papers |
214 | [cwa-server] | Backend implementation for the Apple/Google exposure notification API|
215 | [cwa-verification-server] | Backend implementation of the verification process|
216
217 [cwa-documentation]: https://github.com/corona-warn-app/cwa-documentation
218 [cwa-server]: https://github.com/corona-warn-app/cwa-server
219 [cwa-verification-server]: https://github.com/corona-warn-app/cwa-verification-server
220 [Postgres]: https://www.postgresql.org/
221 [HSQLDB]: http://hsqldb.org/
222 [Zenko CloudServer]: https://github.com/scality/cloudserver
223
[end of README.md]
[start of services/download/src/main/java/app/coronawarn/server/services/download/FederationBatchProcessor.java]
1 package app.coronawarn.server.services.download;
2
3 import static app.coronawarn.server.common.persistence.domain.FederationBatchStatus.ERROR;
4 import static app.coronawarn.server.common.persistence.domain.FederationBatchStatus.ERROR_WONT_RETRY;
5 import static app.coronawarn.server.common.persistence.domain.FederationBatchStatus.PROCESSED;
6 import static app.coronawarn.server.common.persistence.domain.FederationBatchStatus.PROCESSED_WITH_ERROR;
7 import static app.coronawarn.server.common.persistence.domain.FederationBatchStatus.UNPROCESSED;
8 import static java.util.stream.Collectors.toList;
9
10 import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
11 import app.coronawarn.server.common.persistence.domain.FederationBatchInfo;
12 import app.coronawarn.server.common.persistence.domain.FederationBatchStatus;
13 import app.coronawarn.server.common.persistence.exception.InvalidDiagnosisKeyException;
14 import app.coronawarn.server.common.persistence.service.DiagnosisKeyService;
15 import app.coronawarn.server.common.persistence.service.FederationBatchInfoService;
16 import app.coronawarn.server.common.protocols.external.exposurenotification.DiagnosisKeyBatch;
17 import app.coronawarn.server.common.protocols.external.exposurenotification.ReportType;
18 import app.coronawarn.server.services.download.config.DownloadServiceConfig;
19 import app.coronawarn.server.services.download.normalization.FederationKeyNormalizer;
20 import app.coronawarn.server.services.download.validation.ValidFederationKeyFilter;
21 import java.time.LocalDate;
22 import java.time.Period;
23 import java.time.ZoneOffset;
24 import java.util.Deque;
25 import java.util.LinkedList;
26 import java.util.List;
27 import java.util.Optional;
28 import java.util.concurrent.atomic.AtomicBoolean;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
31 import org.springframework.stereotype.Component;
32
33 /**
34 * Responsible for downloading and storing batch information from the federation gateway.
35 */
36 @Component
37 public class FederationBatchProcessor {
38
39 private static final Logger logger = LoggerFactory.getLogger(FederationBatchProcessor.class);
40 private final FederationBatchInfoService batchInfoService;
41 private final DiagnosisKeyService diagnosisKeyService;
42 private final FederationGatewayDownloadService federationGatewayDownloadService;
43 private final DownloadServiceConfig config;
44 private final ValidFederationKeyFilter validFederationKeyFilter;
45
46 /**
47 * Constructor.
48 *
49 * @param batchInfoService A {@link FederationBatchInfoService} for accessing diagnosis key batch
50 * information.
51 * @param diagnosisKeyService A {@link DiagnosisKeyService} for storing retrieved diagnosis keys.
52 * @param federationGatewayDownloadService A {@link FederationGatewayDownloadService} for retrieving federation
53 * diagnosis key batches.
54 * @param config A {@link DownloadServiceConfig} for retrieving federation configuration.
55 * @param federationKeyValidator A {@link ValidFederationKeyFilter} for validating keys in the downloaded
56 * batches
57 */
58 public FederationBatchProcessor(FederationBatchInfoService batchInfoService,
59 DiagnosisKeyService diagnosisKeyService, FederationGatewayDownloadService federationGatewayDownloadService,
60 DownloadServiceConfig config, ValidFederationKeyFilter federationKeyValidator) {
61 this.batchInfoService = batchInfoService;
62 this.diagnosisKeyService = diagnosisKeyService;
63 this.federationGatewayDownloadService = federationGatewayDownloadService;
64 this.config = config;
65 this.validFederationKeyFilter = federationKeyValidator;
66 }
67
68 /**
69 * Checks if the date-based download logic is enabled and prepares the FederationBatchInfo Repository accordingly. The
70 * Federation Batch Info stores information about which batches have already been processed to not download them
71 * again. If the date-based download is enabled, the entries for the specified date need to be removed. Stores the
72 * first FederationBatchTag for the specified date as a starting point for further processing.
73 */
74 public void prepareDownload() throws FatalFederationGatewayException {
75 if (config.getEfgsEnforceDateBasedDownload()) {
76 LocalDate downloadDate = LocalDate.now(ZoneOffset.UTC)
77 .minus(Period.ofDays(config.getEfgsEnforceDownloadOffsetDays()));
78 batchInfoService.deleteForDate(downloadDate);
79 saveFirstBatchInfoForDate(downloadDate);
80 }
81 }
82
83 /**
84 * Stores the batch info for the specified date. Its status is set to {@link FederationBatchStatus#UNPROCESSED}.
85 *
86 * @param date The date for which the first batch info is stored.
87 */
88 protected void saveFirstBatchInfoForDate(LocalDate date) throws FatalFederationGatewayException {
89 try {
90 logger.info("Triggering download of first batch for date {}.", date);
91 BatchDownloadResponse response = federationGatewayDownloadService.downloadBatch(date);
92 batchInfoService.save(new FederationBatchInfo(response.getBatchTag(), date));
93 } catch (BatchDownloadException e) {
94 logger.error("Triggering download of first batch for date {} failed. Reason: {}.", date, e.getMessage());
95 } catch (FatalFederationGatewayException e) {
96 throw e;
97 } catch (Exception e) {
98 logger.error("Triggering download of first batch for date {} failed.", date, e);
99 }
100 }
101
102 /**
103 * Downloads and processes all batches from the federation gateway that have previously been
104 * marked with the status value {@link FederationBatchStatus#ERROR}.
105 */
106 public void processErrorFederationBatches() {
107 List<FederationBatchInfo> federationBatchInfoWithError = batchInfoService.findByStatus(ERROR);
108 logger.info("{} error federation batches for reprocessing found.", federationBatchInfoWithError.size());
109 federationBatchInfoWithError.forEach(this::retryProcessingBatch);
110 }
111
112 private void retryProcessingBatch(FederationBatchInfo federationBatchInfo) {
113 try {
114 processBatchAndReturnNextBatchId(federationBatchInfo, ERROR_WONT_RETRY)
115 .ifPresent(nextBatchTag ->
116 batchInfoService.save(new FederationBatchInfo(nextBatchTag, federationBatchInfo.getDate())));
117 } catch (Exception e) {
118 logger.error("Failed to save next federation batch info for processing. Will not try again.", e);
119 batchInfoService.updateStatus(federationBatchInfo, ERROR_WONT_RETRY);
120 }
121 }
122
123 /**
124 * Downloads and processes all batches from the federation gateway that have previously been marked with status value
125 * {@link FederationBatchStatus#UNPROCESSED}.
126 */
127 public void processUnprocessedFederationBatches() throws FatalFederationGatewayException {
128 Deque<FederationBatchInfo> unprocessedBatches = new LinkedList<>(batchInfoService.findByStatus(UNPROCESSED));
129 logger.info("{} unprocessed federation batches found.", unprocessedBatches.size());
130
131 while (!unprocessedBatches.isEmpty()) {
132 FederationBatchInfo currentBatch = unprocessedBatches.remove();
133 processBatchAndReturnNextBatchId(currentBatch, ERROR)
134 .ifPresent(nextBatchTag -> {
135 if (config.getEfgsEnforceDateBasedDownload()) {
136 unprocessedBatches.add(new FederationBatchInfo(nextBatchTag, currentBatch.getDate()));
137 }
138 });
139 }
140 }
141
142 private Optional<String> processBatchAndReturnNextBatchId(
143 FederationBatchInfo batchInfo, FederationBatchStatus errorStatus) throws FatalFederationGatewayException {
144 LocalDate date = batchInfo.getDate();
145 String batchTag = batchInfo.getBatchTag();
146 logger.info("Processing batch for date {} and batchTag {}.", date, batchTag);
147 try {
148 BatchDownloadResponse response = federationGatewayDownloadService.downloadBatch(batchTag, date);
149 AtomicBoolean batchContainsInvalidKeys = new AtomicBoolean(false);
150 response.getDiagnosisKeyBatch().ifPresentOrElse(batch -> {
151 logger.info("Downloaded {} keys for date {} and batchTag {}.", batch.getKeysCount(), date, batchTag);
152 List<DiagnosisKey> validDiagnosisKeys = extractValidDiagnosisKeysFromBatch(batch);
153 int numOfInvalidKeys = batch.getKeysCount() - validDiagnosisKeys.size();
154 if (numOfInvalidKeys > 0) {
155 batchContainsInvalidKeys.set(true);
156 logger.info("{} keys failed validation and were skipped.", numOfInvalidKeys);
157 }
158 int insertedKeys = diagnosisKeyService.saveDiagnosisKeys(validDiagnosisKeys);
159 logger.info("Successfully inserted {} keys for date {} and batchTag {}.", insertedKeys, date, batchTag);
160 }, () -> logger.info("Batch for date {} and batchTag {} did not contain any keys.", date, batchTag));
161 batchInfoService.updateStatus(batchInfo, batchContainsInvalidKeys.get() ? PROCESSED_WITH_ERROR : PROCESSED);
162 return response.getNextBatchTag();
163 } catch (BatchDownloadException e) {
164 logger.error("Federation batch processing for date {} and batchTag {} failed. Status set to {}. Reason: {}.",
165 date, batchTag, errorStatus.name(), e.getMessage());
166 batchInfoService.updateStatus(batchInfo, errorStatus);
167 return Optional.empty();
168 } catch (FatalFederationGatewayException e) {
169 throw e;
170 } catch (Exception e) {
171 logger.error("Federation batch processing for date {} and batchTag {} failed. Status set to {}.",
172 date, batchTag, errorStatus.name(), e);
173 batchInfoService.updateStatus(batchInfo, errorStatus);
174 return Optional.empty();
175 }
176 }
177
178 private List<DiagnosisKey> extractValidDiagnosisKeysFromBatch(DiagnosisKeyBatch diagnosisKeyBatch) {
179 return diagnosisKeyBatch.getKeysList()
180 .stream()
181 .filter(validFederationKeyFilter::isValid)
182 .map(this::convertFederationDiagnosisKeyToDiagnosisKey)
183 .filter(Optional::isPresent)
184 .map(Optional::get)
185 .collect(toList());
186 }
187
188 private Optional<DiagnosisKey> convertFederationDiagnosisKeyToDiagnosisKey(
189 app.coronawarn.server.common.protocols.external.exposurenotification.DiagnosisKey diagnosisKey) {
190 try {
191 return Optional.of(DiagnosisKey.builder().fromFederationDiagnosisKey(diagnosisKey)
192 .withReportType(ReportType.CONFIRMED_TEST)
193 .withFieldNormalization(new FederationKeyNormalizer(config))
194 .build());
195 } catch (InvalidDiagnosisKeyException e) {
196 logger.info("Building diagnosis key from federation diagnosis key failed. Reason: {}.", e.getMessage());
197 return Optional.empty();
198 } catch (Exception e) {
199 logger.info("Building diagnosis key from federation diagnosis key failed.", e);
200 return Optional.empty();
201 }
202 }
203 }
204
[end of services/download/src/main/java/app/coronawarn/server/services/download/FederationBatchProcessor.java]
</code>
Here is an example of a patch file. It consists of changes to the code base. It specifies the file names, the line numbers of each change, and the removed and added lines. A single patch file can contain changes to multiple files.
<patch>
--- a/file.py
+++ b/file.py
@@ -1,27 +1,35 @@
def euclidean(a, b):
- while b:
- a, b = b, a % b
- return a
+ if b == 0:
+ return a
+ return euclidean(b, a % b)
def bresenham(x0, y0, x1, y1):
points = []
dx = abs(x1 - x0)
dy = abs(y1 - y0)
- sx = 1 if x0 < x1 else -1
- sy = 1 if y0 < y1 else -1
- err = dx - dy
+ x, y = x0, y0
+ sx = -1 if x0 > x1 else 1
+ sy = -1 if y0 > y1 else 1
- while True:
- points.append((x0, y0))
- if x0 == x1 and y0 == y1:
- break
- e2 = 2 * err
- if e2 > -dy:
+ if dx > dy:
+ err = dx / 2.0
+ while x != x1:
+ points.append((x, y))
err -= dy
- x0 += sx
- if e2 < dx:
- err += dx
- y0 += sy
+ if err < 0:
+ y += sy
+ err += dx
+ x += sx
+ else:
+ err = dy / 2.0
+ while y != y1:
+ points.append((x, y))
+ err -= dx
+ if err < 0:
+ x += sx
+ err += dy
+ y += sy
+ points.append((x, y))
return points
</patch>
I need you to solve the provded issue by generating a single patch file that I can apply directly to this repository using git apply. Please respond with a single patch file in the format shown above.
Respond below:
| corona-warn-app/cwa-server | e3f867a8005bd7f79c9eabe269d168fc01330484 | [BSI][20201107] Denial-of-Service in Download Service
Rating: Informational
Description:
The download service component of the cwa-server backend can be forced into an endless loop by a malicious or faulty federation gateway server. When downloading new batches from the federation gateway server, the download service checks the nextBatchTag header of the federation gateway server’s response. If this header is set, the download service will continue requesting a batch with this tag. It will not stop as long as the server includes this header. This can trap the download service in an endless loop.
This highly depends on the behavior and implementation of the federation gateway server. However, even a non-malicious, faulty implementation might trigger this issue. Additionally, the issue was sometimes hard to reproduce as the server first has to be forced to request new batches (which in some cases required setting the EFGS_ENABLE_DATE_BASED_DOWNLOAD configuration to true).
Affected System:
cwa-server (commit 4f3f460f580ea5d548dff0e3ceb739908c83d1a7)
Proof of Concept:
The following screenshots show the offending lines in the FederationBatchProcessor.java:
<img width="846" alt="Download Service DoS Offending Code" src="https://user-images.githubusercontent.com/65443025/98435998-dcd5f900-20d7-11eb-9f5e-3fb7f449ca58.png">
The following snippets show a minimalistic federation gateway server mock that returns invalid data but sets the nextBatchTag header on each response. The first request needs to fail (in this case implemented by sending an invalid HTTP request body) so that the batch tag is added to the list of unprocessed batches.
<img width="775" alt="snippet-1" src="https://user-images.githubusercontent.com/65443025/98436046-5c63c800-20d8-11eb-843e-47e98b9c2ed7.png">
<img width="779" alt="snippet-2" src="https://user-images.githubusercontent.com/65443025/98436048-61c11280-20d8-11eb-9d77-43ebd770a556.png">
The following screenshot shows the failing first request on the first run of the download service:
<img width="824" alt="Download Service DoS First Invalid Request" src="https://user-images.githubusercontent.com/65443025/98436059-87e6b280-20d8-11eb-9ad0-7ceaaa557add.png">
The next screenshot shows the log output of the download service when it is run again. It can be seen that the server will endlessly try to request a next batch.
<img width="845" alt="Download Service DoS Endless Loop Log" src="https://user-images.githubusercontent.com/65443025/98436074-ab116200-20d8-11eb-8c3c-ac545d9c1b07.png">
Recommended Controls:
The while loop should be adapted so that it is not possible for it to continue forever. The received nextBatchTag header should be checked. If it is already contained in the list of unprocessed batches, it should not be added again. This does not protect against a malicious server that sends different batch tags on each request. Therefore, alternatively, a timeout value or a maximum number of retries could be introduced.
| 2020-11-09T15:39:20 | <patch>
diff --git a/services/download/src/main/java/app/coronawarn/server/services/download/FederationBatchProcessor.java b/services/download/src/main/java/app/coronawarn/server/services/download/FederationBatchProcessor.java
--- a/services/download/src/main/java/app/coronawarn/server/services/download/FederationBatchProcessor.java
+++ b/services/download/src/main/java/app/coronawarn/server/services/download/FederationBatchProcessor.java
@@ -22,9 +22,11 @@
import java.time.Period;
import java.time.ZoneOffset;
import java.util.Deque;
+import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
+import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -42,6 +44,12 @@ public class FederationBatchProcessor {
private final FederationGatewayDownloadService federationGatewayDownloadService;
private final DownloadServiceConfig config;
private final ValidFederationKeyFilter validFederationKeyFilter;
+
+ // This is a potential memory-leak if there are very many batches
+ // This is an intentional decision:
+ // We'd rather run into a memory-leak if there are too many batches
+ // than run into an endless loop if a batch-tag repeats
+ private final Set<String> seenBatches;
/**
* Constructor.
@@ -63,6 +71,7 @@ public FederationBatchProcessor(FederationBatchInfoService batchInfoService,
this.federationGatewayDownloadService = federationGatewayDownloadService;
this.config = config;
this.validFederationKeyFilter = federationKeyValidator;
+ this.seenBatches = new HashSet<>();
}
/**
@@ -129,16 +138,21 @@ public void processUnprocessedFederationBatches() throws FatalFederationGatewayE
logger.info("{} unprocessed federation batches found.", unprocessedBatches.size());
while (!unprocessedBatches.isEmpty()) {
- FederationBatchInfo currentBatch = unprocessedBatches.remove();
- processBatchAndReturnNextBatchId(currentBatch, ERROR)
+ FederationBatchInfo currentBatchInfo = unprocessedBatches.remove();
+ seenBatches.add(currentBatchInfo.getBatchTag());
+ processBatchAndReturnNextBatchId(currentBatchInfo, ERROR)
.ifPresent(nextBatchTag -> {
- if (config.getEfgsEnforceDateBasedDownload()) {
- unprocessedBatches.add(new FederationBatchInfo(nextBatchTag, currentBatch.getDate()));
+ if (isEfgsEnforceDateBasedDownloadAndNotSeen(nextBatchTag)) {
+ unprocessedBatches.add(new FederationBatchInfo(nextBatchTag, currentBatchInfo.getDate()));
}
});
}
}
+ private boolean isEfgsEnforceDateBasedDownloadAndNotSeen(String batchTag) {
+ return config.getEfgsEnforceDateBasedDownload() && !seenBatches.contains(batchTag);
+ }
+
private Optional<String> processBatchAndReturnNextBatchId(
FederationBatchInfo batchInfo, FederationBatchStatus errorStatus) throws FatalFederationGatewayException {
LocalDate date = batchInfo.getDate();
</patch> | diff --git a/services/download/src/test/java/app/coronawarn/server/services/download/FederationBatchProcessorTest.java b/services/download/src/test/java/app/coronawarn/server/services/download/FederationBatchProcessorTest.java
--- a/services/download/src/test/java/app/coronawarn/server/services/download/FederationBatchProcessorTest.java
+++ b/services/download/src/test/java/app/coronawarn/server/services/download/FederationBatchProcessorTest.java
@@ -32,12 +32,14 @@
import app.coronawarn.server.services.download.validation.ValidFederationKeyFilter;
import com.google.protobuf.ByteString;
import feign.FeignException;
+import java.time.Duration;
import java.time.LocalDate;
import java.time.Period;
import java.time.ZoneOffset;
import java.util.List;
import java.util.Optional;
import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
@@ -226,6 +228,23 @@ void testOneUnprocessedBatchFails() throws Exception {
Mockito.verify(batchInfoService, times(1)).updateStatus(any(FederationBatchInfo.class), eq(ERROR));
Mockito.verify(diagnosisKeyService, never()).saveDiagnosisKeys(any());
}
+
+ @Test
+ void testNoInfiniteLoopSameBatchTag() throws FatalFederationGatewayException {
+ config.setEfgsEnforceDateBasedDownload(true);
+ FederationBatchInfo batchInfo = new FederationBatchInfo(batchTag1, date, UNPROCESSED);
+ BatchDownloadResponse serverResponse = FederationBatchTestHelper
+ .createBatchDownloadResponse(batchTag1, Optional.of(batchTag1));
+
+ when(batchInfoService.findByStatus(UNPROCESSED)).thenReturn(list(batchInfo));
+ when(federationGatewayDownloadService.downloadBatch(batchTag1, date)).thenReturn(serverResponse);
+
+ Assertions
+ .assertTimeoutPreemptively(Duration.ofSeconds(1), () -> batchProcessor.processUnprocessedFederationBatches());
+ Mockito.verify(batchInfoService, times(1)).findByStatus(UNPROCESSED);
+ Mockito.verify(federationGatewayDownloadService, times(1)).downloadBatch(batchTag1, date);
+ Mockito.verify(batchInfoService, times(1)).updateStatus(batchInfo, PROCESSED);
+ }
}
@Nested
| |||||
corona-warn-app__cwa-server-113 | You will be provided with a partial code base and an issue statement explaining a problem to resolve.
<issue>
DiagnosisKeyDistributionRunner deletes exposure configuration
``DiagnosisKeyDistributionRunner`` deletes the files written by ``ExposureConfigurationDistributionRunner`` before they are published.
</issue>
<code>
[start of README.md]
1 <h1 align="center">
2 Corona Warn App - Server
3 </h1>
4
5 <p align="center">
6 <a href="https://github.com/Exposure-Notification-App/ena-documentation/commits/" title="Last Commit"><img src="https://img.shields.io/github/last-commit/corona-warn-app/cwa-server?style=flat"></a>
7 <a href="https://github.com/Exposure-Notification-App/ena-documentation/issues" title="Open Issues"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat"></a>
8 <a href="https://circleci.com/gh/corona-warn-app/cwa-server" title="Build Status"><img src="https://circleci.com/gh/corona-warn-app/cwa-server.svg?style=flat&circle-token=a7294b977bb9ea2c2d53ff62c9aa442670e19b59"></a>
9 <a href="https://github.com/corona-warn-app/cwa-server/blob/master/LICENSE" title="License"><img src="https://img.shields.io/badge/License-Apache%202.0-green.svg?style=flat"></a>
10 </p>
11
12 <p align="center">
13 <a href="#service-apis">Service APIs</a> •
14 <a href="#development">Development</a> •
15 <a href="#architecture--documentation">Documentation</a> •
16 <a href="#contributing">Contributing</a> •
17 <a href="#support--feedback">Support</a> •
18 <a href="https://github.com/corona-warn-app/cwa-admin/releases">Changelog</a>
19 </p>
20
21 This project has the goal to develop the official Corona-Warn-App for Germany based on the Exposure Notification API by [Apple](https://www.apple.com/covid19/contacttracing/) and [Google](https://www.google.com/covid19/exposurenotifications/). The apps (for both iOS and Android) will collect anonymous data from nearby mobile phones using Bluetooth technology. The data will be stored locally on each device, preventing authorities’ access and control over tracing data. This repository contains the **implementation of the key server** for the Corona-Warn-App. This implementation is **work in progress** and contains alpha-quality code only.
22
23 ## Service APIs
24
25 Service | OpenAPI Specification
26 -------------|-------------
27 Submission Service | https://github.com/corona-warn-app/cwa-server/raw/master/services/submission/api_v1.json
28 Distribution Service | https://github.com/corona-warn-app/cwa-server/raw/master/services/distribution/api_v1.json
29
30
31 ## Development
32
33 ### Setup
34
35 To setup this project locally on your machine, we recommend to install the following prerequisites:
36 - Java OpenJDK 11
37 - Maven 3.6
38 - Docker if you would like to build Docker images
39 - Postgres if you would like to connect a persistent storage. If no postgres connection is specified an in-memory HSQLDB will be provided.
40
41 ### Build
42
43 After you checked out the repository run ```mvn install``` in your base directory to build the project.
44
45 ### Run
46
47 Navigate to the service you would like to start and run the spring-boot:run target. By default the HSQLDB will be used and after the Spring Boot application started the endpoint will be available on your local port 8080. As an example if you would like to start the submission service run:
48 ```
49 cd services/submission/
50 mvn spring-boot:run
51 ```
52
53 If you want to use a postgres DB instead please use the postgres profile when starting the application:
54
55 ```
56 cd services/submission/
57 mvn spring-boot:run -Dspring-boot.run.profiles=postgres
58 ```
59
60 In order to enable S3 integration, you will need the following vars in your env:
61
62 Var | Description
63 ----|----------------
64 AWS_ACCESS_KEY_ID | The access key
65 AWS_SECRET_ACCESS_KEY | The secret access key
66 cwa.objectstore.endpoint | The S3 endpoint
67 cwa.objectstore.bucket | The S3 bucket name
68
69 ### Build and run Docker Compose (full stack)
70 To start:
71 - Run `docker-compose up`
72 - After the initial build and startup, an initial "distribution" will run
73
74 To start additional "distribution" runs:
75 - Run `docker-compose start distribution`
76
77 ### Build and run single Docker Images
78
79 First download and install [Docker](https://www.docker.com/products/docker-desktop).
80
81 If you want to build and run a docker image of a service you can use the prepared script in the respective service directory.
82 To build and run the distribution service:
83 ```
84 ./services/distribution/build_and_run.sh
85 ```
86
87 To build and run the submission service:
88 ```
89 ./services/submission/build_and_run.sh
90 ```
91 The submission service will then be available locally on port 8080.
92
93 ## Debugging
94
95 You may run the application with the spring profile `dev` to enable the `DEBUG` log-level.
96
97 ```
98 mvn spring-boot:run -Dspring-boot.run.profiles=postgres,dev
99 ```
100
101 To be able to set breakpoints (e.g. in IntelliJ), it may be necessary to use the parameter `-Dspring-boot.run.fork=false`.
102
103
104 ## Known Issues
105
106 There are no known issues.
107
108 ## Architecture & Documentation
109
110 The full documentation for the Corona-Warn-App is in the [cwa-documentation](https://github.com/corona-warn-app/cwa-documentation) repository. Please refer to this repository for technical documents, UI/UX specifications, architectures, and whitepapers of this implementation.
111
112 ## Support & Feedback
113
114 | Type | Channel |
115 | ------------------------ | ------------------------------------------------------ |
116 | **General Discussion** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="General Discussion"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/question.svg?style=flat-square"></a> </a> |
117 | **Concept Feedback** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="Open Concept Feedback"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/concept-extension.svg?style=flat-square"></a> |
118 | **iOS App Issue** | <a href="https://github.com/corona-warn-app/cwa-app-ios/issues/new/choose" title="Open iOS Suggestion"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-app-ios/ios-app.svg?style=flat-square"></a> |
119 | **Android App Issue** | <a href="https://github.com/corona-warn-app/cwa-app-android/issues/new/choose" title="Open Android Issue"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-app-android/android-app.svg?style=flat-square"></a> |
120 | **Backend Issue** | <a href="https://github.com/corona-warn-app/cwa-server/issues/new/choose" title="Open Backend Issue"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server/backend.svg?style=flat-square"></a> |
121 | **Other Requests** | <a href="mailto:[email protected]" title="Email CWD Team"><img src="https://img.shields.io/badge/email-CWD%20team-green?logo=mail.ru&style=flat-square&logoColor=white"></a> |
122
123 ## Contributing
124
125 Contributions and feedback are encouraged and always welcome. Please see our [Contribution Guidelines](./CONTRIBUTING.md) for details on how to contribute, the project structure and additional details you need to know to work with us. By participating in this project, you agree to abide by its [Code of Conduct](./CODE_OF_CONDUCT.md).
126
127 ## Contributors
128
129 The German government has asked SAP and Deutsche Telekom to develop the Corona-Warn-App. Deutsche Telekom is providing the infrastructure technology and will operate and run the backend for the app in a safe, scalable, and stable manner. SAP is responsible for the development of the app development and the exposure notification backend. Therefore, development teams of SAP and T-Systems are contributing to this project. At the same time, our commitment to open source means that we are enabling -and encouraging- all interested parties to contribute and become part of its developer community.
130
131 ## Repositories
132
133 | Repository | Description |
134 | ------------------- | --------------------------------------------------------------------- |
135 | [cwa-documentation] | Project overview, general documentation, and white papers. |
136 | [cwa-app-ios] | Native iOS app using the Apple/Google exposure notification API. |
137 | [cwa-app-android] | Native Android app using the Apple/Google exposure notification API. |
138 | [cwa-server] | Backend implementation for the Apple/Google exposure notification API.|
139
140 [cwa-documentation]: https://github.com/corona-warn-app/cwa-documentation
141 [cwa-app-ios]: https://github.com/corona-warn-app/cwa-app-ios
142 [cwa-app-android]: https://github.com/corona-warn-app/cwa-app-android
143 [cwa-server]: https://github.com/corona-warn-app/cwa-server
144
145 ---
146
147 This project is licensed under the **Apache-2.0** license. For more information, see the [LICENSE](./LICENSE) file.
148
[end of README.md]
[start of /dev/null]
1
[end of /dev/null]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/crypto/CryptoProvider.java]
1 package app.coronawarn.server.services.distribution.crypto;
2
3 import java.io.ByteArrayInputStream;
4 import java.io.IOException;
5 import java.io.InputStream;
6 import java.io.InputStreamReader;
7 import java.security.PrivateKey;
8 import java.security.Security;
9 import java.security.cert.Certificate;
10 import java.security.cert.CertificateException;
11 import java.security.cert.CertificateFactory;
12 import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
13 import org.bouncycastle.jce.provider.BouncyCastleProvider;
14 import org.bouncycastle.openssl.PEMParser;
15 import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
16 import org.slf4j.Logger;
17 import org.slf4j.LoggerFactory;
18 import org.springframework.beans.factory.annotation.Autowired;
19 import org.springframework.beans.factory.annotation.Value;
20 import org.springframework.core.io.Resource;
21 import org.springframework.core.io.ResourceLoader;
22 import org.springframework.stereotype.Component;
23
24 /**
25 * Wrapper class for a {@link CryptoProvider#getPrivateKey() private key} and a {@link
26 * CryptoProvider#getCertificate()} certificate} from the application properties.
27 */
28 @Component
29 public class CryptoProvider {
30
31 private static final Logger logger = LoggerFactory.getLogger(CryptoProvider.class);
32
33 @Value("${app.coronawarn.server.services.distribution.paths.privatekey}")
34 private String privateKeyPath;
35
36 @Value("${app.coronawarn.server.services.distribution.paths.certificate}")
37 private String certificatePath;
38
39 @Autowired
40 private ResourceLoader resourceLoader;
41
42 private PrivateKey privateKey;
43 private Certificate certificate;
44
45 /**
46 * Creates a CryptoProvider, using {@link BouncyCastleProvider}.
47 */
48 public CryptoProvider() {
49 Security.addProvider(new BouncyCastleProvider());
50 }
51
52 private static PrivateKey getPrivateKeyFromStream(final InputStream privateKeyStream)
53 throws IOException {
54 PEMParser pemParser = new PEMParser(new InputStreamReader(privateKeyStream));
55 PrivateKeyInfo privateKeyInfo = (PrivateKeyInfo) pemParser.readObject();
56 return new JcaPEMKeyConverter().getPrivateKey(privateKeyInfo);
57 }
58
59 private static Certificate getCertificateFromStream(final InputStream certificateStream)
60 throws IOException, CertificateException {
61 return getCertificateFromBytes(certificateStream.readAllBytes());
62 }
63
64 private static Certificate getCertificateFromBytes(final byte[] bytes)
65 throws CertificateException {
66 CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
67 InputStream certificateByteStream = new ByteArrayInputStream(bytes);
68 return certificateFactory.generateCertificate(certificateByteStream);
69 }
70
71 /**
72 * Reads and returns the {@link PrivateKey} configured in the application properties.
73 */
74 public PrivateKey getPrivateKey() {
75 if (this.privateKey == null) {
76 Resource privateKeyResource = resourceLoader.getResource(privateKeyPath);
77 try (InputStream privateKeyStream = privateKeyResource.getInputStream()) {
78 this.privateKey = getPrivateKeyFromStream(privateKeyStream);
79 } catch (IOException e) {
80 logger.error("Failed to load private key from {}", privateKeyPath, e);
81 throw new RuntimeException(e);
82 }
83 }
84 return privateKey;
85 }
86
87 /**
88 * Reads and returns the {@link Certificate} configured in the application properties.
89 */
90 public Certificate getCertificate() {
91 if (this.certificate == null) {
92 Resource certResource = resourceLoader.getResource(certificatePath);
93 try (InputStream certStream = certResource.getInputStream()) {
94 this.certificate = getCertificateFromStream(certStream);
95 } catch (IOException | CertificateException e) {
96 logger.error("Failed to load certificate from {}", certificatePath, e);
97 throw new RuntimeException(e);
98 }
99 }
100 return certificate;
101 }
102 }
103
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/crypto/CryptoProvider.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/diagnosiskeys/structure/directory/DiagnosisKeysCountryDirectoryImpl.java]
1 package app.coronawarn.server.services.distribution.diagnosiskeys.structure.directory;
2
3 import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
4 import app.coronawarn.server.services.distribution.crypto.CryptoProvider;
5 import app.coronawarn.server.services.distribution.diagnosiskeys.structure.directory.decorator.DateAggregatingDecorator;
6 import app.coronawarn.server.services.distribution.structure.directory.Directory;
7 import app.coronawarn.server.services.distribution.structure.directory.IndexDirectory;
8 import app.coronawarn.server.services.distribution.structure.directory.IndexDirectoryImpl;
9 import app.coronawarn.server.services.distribution.structure.directory.decorator.IndexingDecorator;
10 import app.coronawarn.server.services.distribution.structure.util.ImmutableStack;
11 import java.time.LocalDate;
12 import java.util.Collection;
13 import java.util.Set;
14
15 public class DiagnosisKeysCountryDirectoryImpl extends IndexDirectoryImpl<String> {
16
17 private static final String COUNTRY_DIRECTORY = "country";
18 private static final String COUNTRY = "DE";
19
20 private Collection<DiagnosisKey> diagnosisKeys;
21 private CryptoProvider cryptoProvider;
22
23 public DiagnosisKeysCountryDirectoryImpl(Collection<DiagnosisKey> diagnosisKeys,
24 CryptoProvider cryptoProvider) {
25 super(COUNTRY_DIRECTORY, __ -> Set.of(COUNTRY), Object::toString);
26 this.diagnosisKeys = diagnosisKeys;
27 this.cryptoProvider = cryptoProvider;
28 }
29
30 @Override
31 public void prepare(ImmutableStack<Object> indices) {
32 this.addDirectoryToAll(__ -> {
33 IndexDirectory<LocalDate> dateDirectory = new DiagnosisKeysDateDirectoryImpl(diagnosisKeys,
34 cryptoProvider);
35 return decorateDateDirectory(dateDirectory);
36 });
37 super.prepare(indices);
38 }
39
40 private Directory decorateDateDirectory(IndexDirectory<LocalDate> dateDirectory) {
41 return new DateAggregatingDecorator(new IndexingDecorator<>(dateDirectory), cryptoProvider);
42 }
43 }
44
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/diagnosiskeys/structure/directory/DiagnosisKeysCountryDirectoryImpl.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/diagnosiskeys/structure/directory/DiagnosisKeysDateDirectoryImpl.java]
1 package app.coronawarn.server.services.distribution.diagnosiskeys.structure.directory;
2
3 import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
4 import app.coronawarn.server.services.distribution.crypto.CryptoProvider;
5 import app.coronawarn.server.services.distribution.diagnosiskeys.util.DateTime;
6 import app.coronawarn.server.services.distribution.structure.directory.Directory;
7 import app.coronawarn.server.services.distribution.structure.directory.IndexDirectory;
8 import app.coronawarn.server.services.distribution.structure.directory.IndexDirectoryImpl;
9 import app.coronawarn.server.services.distribution.structure.directory.decorator.IndexingDecorator;
10 import app.coronawarn.server.services.distribution.structure.util.ImmutableStack;
11 import java.time.LocalDate;
12 import java.time.LocalDateTime;
13 import java.time.format.DateTimeFormatter;
14 import java.util.Collection;
15
16 public class DiagnosisKeysDateDirectoryImpl extends IndexDirectoryImpl<LocalDate> {
17
18 private static final String DATE_DIRECTORY = "date";
19 private static final DateTimeFormatter ISO8601 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
20
21 private Collection<DiagnosisKey> diagnosisKeys;
22 private CryptoProvider cryptoProvider;
23
24 public DiagnosisKeysDateDirectoryImpl(Collection<DiagnosisKey> diagnosisKeys,
25 CryptoProvider cryptoProvider) {
26 super(DATE_DIRECTORY, __ -> DateTime.getDates(diagnosisKeys), ISO8601::format);
27 this.diagnosisKeys = diagnosisKeys;
28 this.cryptoProvider = cryptoProvider;
29 }
30
31 @Override
32 public void prepare(ImmutableStack<Object> indices) {
33 this.addDirectoryToAll(currentIndices -> {
34 LocalDate currentDate = (LocalDate) currentIndices.peek();
35 IndexDirectory<LocalDateTime> hourDirectory = new DiagnosisKeysHourDirectoryImpl(
36 diagnosisKeys, currentDate, cryptoProvider);
37 return decorateHourDirectory(hourDirectory);
38 });
39 super.prepare(indices);
40 }
41
42 private Directory decorateHourDirectory(IndexDirectory<LocalDateTime> hourDirectory) {
43 return new IndexingDecorator<>(hourDirectory);
44 }
45 }
46
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/diagnosiskeys/structure/directory/DiagnosisKeysDateDirectoryImpl.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/diagnosiskeys/structure/directory/DiagnosisKeysDirectoryImpl.java]
1 package app.coronawarn.server.services.distribution.diagnosiskeys.structure.directory;
2
3 import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
4 import app.coronawarn.server.services.distribution.crypto.CryptoProvider;
5 import app.coronawarn.server.services.distribution.structure.directory.Directory;
6 import app.coronawarn.server.services.distribution.structure.directory.DirectoryImpl;
7 import app.coronawarn.server.services.distribution.structure.directory.IndexDirectory;
8 import app.coronawarn.server.services.distribution.structure.directory.decorator.IndexingDecorator;
9 import app.coronawarn.server.services.distribution.structure.util.ImmutableStack;
10 import java.util.Collection;
11
12 /**
13 * A {@link Directory} containing the file and directory structure that mirrors the API defined in
14 * the OpenAPI definition {@code /services/distribution/api_v1.json}. Available countries (endpoint
15 * {@code /version/v1/diagnosis-keys/country}) are statically set to only {@code "DE"}. The dates
16 * and respective hours (endpoint {@code /version/v1/diagnosis-keys/country/DE/date}) will be
17 * created based on the actual {@link DiagnosisKey DiagnosisKeys} given to the {@link
18 * DiagnosisKeysDirectoryImpl#DiagnosisKeysDirectoryImpl constructor}.
19 */
20 public class DiagnosisKeysDirectoryImpl extends DirectoryImpl {
21
22 private static final String DIAGNOSIS_KEYS_DIRECTORY = "diagnosis-keys";
23 private final Collection<DiagnosisKey> diagnosisKeys;
24 private final CryptoProvider cryptoProvider;
25
26 public DiagnosisKeysDirectoryImpl(Collection<DiagnosisKey> diagnosisKeys,
27 CryptoProvider cryptoProvider) {
28 super(DIAGNOSIS_KEYS_DIRECTORY);
29 this.diagnosisKeys = diagnosisKeys;
30 this.cryptoProvider = cryptoProvider;
31 }
32
33 @Override
34 public void prepare(ImmutableStack<Object> indices) {
35 this.addDirectory(decorateCountryDirectory(
36 new DiagnosisKeysCountryDirectoryImpl(diagnosisKeys, cryptoProvider)));
37 super.prepare(indices);
38 }
39
40 private Directory decorateCountryDirectory(IndexDirectory<String> countryDirectory) {
41 return new IndexingDecorator<>(countryDirectory);
42 }
43 }
44
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/diagnosiskeys/structure/directory/DiagnosisKeysDirectoryImpl.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/diagnosiskeys/structure/directory/DiagnosisKeysHourDirectoryImpl.java]
1 package app.coronawarn.server.services.distribution.diagnosiskeys.structure.directory;
2
3 import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
4 import app.coronawarn.server.services.distribution.crypto.CryptoProvider;
5 import app.coronawarn.server.services.distribution.diagnosiskeys.structure.file.HourFileImpl;
6 import app.coronawarn.server.services.distribution.diagnosiskeys.util.DateTime;
7 import app.coronawarn.server.services.distribution.structure.directory.IndexDirectoryImpl;
8 import app.coronawarn.server.services.distribution.structure.file.File;
9 import app.coronawarn.server.services.distribution.structure.file.decorator.SigningDecorator;
10 import app.coronawarn.server.services.distribution.structure.util.ImmutableStack;
11 import java.time.LocalDate;
12 import java.time.LocalDateTime;
13 import java.util.Collection;
14
15 public class DiagnosisKeysHourDirectoryImpl extends IndexDirectoryImpl<LocalDateTime> {
16
17 private static final String HOUR_DIRECTORY = "hour";
18
19 private Collection<DiagnosisKey> diagnosisKeys;
20 private LocalDate currentDate;
21 private CryptoProvider cryptoProvider;
22
23 public DiagnosisKeysHourDirectoryImpl(Collection<DiagnosisKey> diagnosisKeys,
24 LocalDate currentDate, CryptoProvider cryptoProvider) {
25 super(HOUR_DIRECTORY, indices -> {
26 return DateTime.getHours(((LocalDate) indices.peek()), diagnosisKeys);
27 }, LocalDateTime::getHour);
28 this.diagnosisKeys = diagnosisKeys;
29 this.currentDate = currentDate;
30 this.cryptoProvider = cryptoProvider;
31 }
32
33 @Override
34 public void prepare(ImmutableStack<Object> indices) {
35 this.addFileToAll(currentIndices -> {
36 LocalDateTime currentHour = (LocalDateTime) currentIndices.peek();
37 // The LocalDateTime currentHour already contains both the date and the hour information, so
38 // we can throw away the LocalDate that's the second item on the stack from the "/date" IndexDirectory.
39 String region = (String) currentIndices.pop().pop().peek();
40 return decorateHourFile(new HourFileImpl(currentHour, region, diagnosisKeys));
41 });
42 super.prepare(indices);
43 }
44
45 private File decorateHourFile(File hourFile) {
46 return new SigningDecorator(hourFile, cryptoProvider);
47 }
48 }
49
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/diagnosiskeys/structure/directory/DiagnosisKeysHourDirectoryImpl.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/diagnosiskeys/structure/directory/decorator/DateAggregatingDecorator.java]
1 package app.coronawarn.server.services.distribution.diagnosiskeys.structure.directory.decorator;
2
3 import app.coronawarn.server.common.protocols.internal.FileBucket;
4 import app.coronawarn.server.common.protocols.internal.SignedPayload;
5 import app.coronawarn.server.services.distribution.crypto.CryptoProvider;
6 import app.coronawarn.server.services.distribution.structure.Writable;
7 import app.coronawarn.server.services.distribution.structure.directory.Directory;
8 import app.coronawarn.server.services.distribution.structure.directory.decorator.DirectoryDecorator;
9 import app.coronawarn.server.services.distribution.structure.file.File;
10 import app.coronawarn.server.services.distribution.structure.file.FileImpl;
11 import app.coronawarn.server.services.distribution.structure.file.decorator.SigningDecorator;
12 import app.coronawarn.server.services.distribution.structure.functional.CheckedFunction;
13 import app.coronawarn.server.services.distribution.structure.util.ImmutableStack;
14 import java.util.ArrayList;
15 import java.util.Comparator;
16 import java.util.List;
17 import java.util.Set;
18 import java.util.stream.Collectors;
19 import java.util.stream.Stream;
20 import org.slf4j.Logger;
21 import org.slf4j.LoggerFactory;
22
23 /**
24 * A {@link DirectoryDecorator} that will create a {@link SignedPayload} containing a {@link
25 * FileBucket} for each date within its directory.
26 */
27 public class DateAggregatingDecorator extends DirectoryDecorator {
28
29 private static final Logger logger = LoggerFactory.getLogger(DateAggregatingDecorator.class);
30
31 private final CryptoProvider cryptoProvider;
32
33 private static final String AGGREGATE_FILE_NAME = "index";
34
35 public DateAggregatingDecorator(Directory directory, CryptoProvider cryptoProvider) {
36 super(directory);
37 this.cryptoProvider = cryptoProvider;
38 }
39
40 @Override
41 public void prepare(ImmutableStack<Object> indices) {
42 super.prepare(indices);
43 logger.debug("Aggregating {}", this.getFileOnDisk().getPath());
44 Set<Directory> days = this.getDirectories();
45 if (days.size() == 0) {
46 return;
47 }
48
49 List<Directory> sortedDays = new ArrayList<>(days);
50 sortedDays.sort(Comparator.comparing(Writable::getName));
51
52 // Exclude the last day
53 sortedDays.subList(0, days.size() - 1).forEach(currentDirectory -> {
54 Stream.of(currentDirectory)
55 .map(this::getSubSubDirectoryFiles)
56 .map(this::parseFileBucketsFromFiles)
57 .map(this::reduceFileBuckets)
58 .map(this::makeNewFileBucket)
59 .map(FileBucket::toByteArray)
60 .map(bytes -> new FileImpl(AGGREGATE_FILE_NAME, bytes))
61 .map(file -> new SigningDecorator(file, cryptoProvider))
62 .peek(currentDirectory::addFile)
63 .forEach(aggregate -> aggregate.prepare(indices));
64 });
65 }
66
67 private Set<File> getSubSubDirectoryFiles(Directory directory) {
68 // Get all files 2 directory levels down
69 return Stream.of(directory)
70 .map(Directory::getDirectories)
71 .flatMap(Set::stream)
72 .map(Directory::getDirectories)
73 .flatMap(Set::stream)
74 .map(Directory::getFiles)
75 .flatMap(Set::stream)
76 .collect(Collectors.toSet());
77 }
78
79 private Set<FileBucket> parseFileBucketsFromFiles(Set<File> files) {
80 return files.stream()
81 .map(File::getBytes)
82 .map(CheckedFunction.uncheckedFunction(SignedPayload::parseFrom))
83 .map(SignedPayload::getPayload)
84 .map(CheckedFunction.uncheckedFunction(FileBucket::parseFrom))
85 .collect(Collectors.toSet());
86 }
87
88 private Set<app.coronawarn.server.common.protocols.external.exposurenotification.File> reduceFileBuckets(
89 Set<FileBucket> fileBuckets) {
90 return fileBuckets.stream()
91 .map(FileBucket::getFilesList)
92 .flatMap(List::stream)
93 .collect(Collectors.toSet());
94 }
95
96 private FileBucket makeNewFileBucket(
97 Set<app.coronawarn.server.common.protocols.external.exposurenotification.File> enFiles) {
98 return FileBucket.newBuilder()
99 .addAllFiles(enFiles)
100 .build();
101 }
102 }
103
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/diagnosiskeys/structure/directory/decorator/DateAggregatingDecorator.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/diagnosiskeys/structure/file/HourFileImpl.java]
1 package app.coronawarn.server.services.distribution.diagnosiskeys.structure.file;
2
3 import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
4 import app.coronawarn.server.common.protocols.external.exposurenotification.File;
5 import app.coronawarn.server.common.protocols.external.exposurenotification.Key;
6 import app.coronawarn.server.common.protocols.internal.FileBucket;
7 import app.coronawarn.server.services.distribution.diagnosiskeys.util.Batch;
8 import app.coronawarn.server.services.distribution.diagnosiskeys.util.DateTime;
9 import app.coronawarn.server.services.distribution.structure.file.FileImpl;
10 import app.coronawarn.server.services.distribution.structure.util.ImmutableStack;
11 import com.google.protobuf.ByteString;
12 import java.time.Instant;
13 import java.time.LocalDateTime;
14 import java.time.ZoneOffset;
15 import java.util.Collection;
16 import java.util.Set;
17 import java.util.stream.Collectors;
18 import org.slf4j.Logger;
19 import org.slf4j.LoggerFactory;
20
21 public class HourFileImpl extends FileImpl {
22
23 private static final Logger logger = LoggerFactory.getLogger(HourFileImpl.class);
24
25 private static final String INDEX_FILE_NAME = "index";
26
27 private final LocalDateTime currentHour;
28 private final String region;
29 private final Collection<DiagnosisKey> diagnosisKeys;
30
31 public HourFileImpl(LocalDateTime currentHour, String region,
32 Collection<DiagnosisKey> diagnosisKeys) {
33 super(INDEX_FILE_NAME, new byte[0]);
34 this.currentHour = currentHour;
35 this.region = region;
36 this.diagnosisKeys = diagnosisKeys;
37 }
38
39 @Override
40 public void prepare(ImmutableStack<Object> indices) {
41 this.setBytes(createHourBytes());
42 super.prepare(indices);
43 }
44
45 private byte[] createHourBytes() {
46 logger.debug("Creating hour file for {}", currentHour);
47 return FileBucket.newBuilder()
48 .addAllFiles(generateFiles(diagnosisKeys, currentHour, region))
49 .build()
50 .toByteArray();
51 }
52
53 private static Set<File> generateFiles(Collection<DiagnosisKey> diagnosisKeys,
54 LocalDateTime currentHour, String region) {
55 Instant startTimestamp = Instant.from(currentHour.atOffset(ZoneOffset.UTC));
56 Instant endTimestamp = Instant.from(currentHour.atOffset(ZoneOffset.UTC).plusHours(1));
57 Set<Key> keys = createKeys(diagnosisKeys, currentHour);
58 return Batch.aggregateKeys(keys, startTimestamp, endTimestamp, region);
59 }
60
61 private static Set<Key> createKeys(Collection<DiagnosisKey> diagnosisKeys,
62 LocalDateTime currentHour) {
63 return diagnosisKeys.stream()
64 .filter(diagnosisKey -> DateTime
65 .getLocalDateTimeFromHoursSinceEpoch(diagnosisKey.getSubmissionTimestamp())
66 .equals(currentHour))
67 .map(HourFileImpl::createKey)
68 .collect(Collectors.toSet());
69 }
70
71 private static Key createKey(DiagnosisKey key) {
72 return Key.newBuilder()
73 .setKeyData(ByteString.copyFrom(key.getKeyData()))
74 .setRollingStartNumber(Math.toIntExact(key.getRollingStartNumber()))
75 .setRollingPeriod(Math.toIntExact(key.getRollingPeriod()))
76 .setTransmissionRiskLevel(key.getTransmissionRiskLevel())
77 .build();
78 }
79 }
80
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/diagnosiskeys/structure/file/HourFileImpl.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/diagnosiskeys/util/Batch.java]
1 package app.coronawarn.server.services.distribution.diagnosiskeys.util;
2
3 import app.coronawarn.server.common.protocols.external.exposurenotification.File;
4 import app.coronawarn.server.common.protocols.external.exposurenotification.Header;
5 import app.coronawarn.server.common.protocols.external.exposurenotification.Key;
6 import java.time.Instant;
7 import java.util.ArrayList;
8 import java.util.HashSet;
9 import java.util.List;
10 import java.util.Set;
11 import java.util.stream.Collectors;
12 import java.util.stream.IntStream;
13
14 /**
15 * Functionality to split collections of {@link Key keys} into similar sized collections of {@link
16 * java.io.File files} containing the respecitve key data.
17 */
18 public class Batch {
19
20 private static final int KILO = 1000;
21 private static final int FILE_SIZE_LIMIT_KB = 500;
22 private static final int FILE_SIZE_LIMIT_BYTES = FILE_SIZE_LIMIT_KB * KILO;
23
24 /**
25 * Aggregates a set of {@link Key Keys} into a set of {@link File Files} of roughly equal size.
26 */
27 public static Set<File> aggregateKeys(Set<Key> keys, Instant startTimestamp,
28 Instant endTimeStamp, String region) {
29 // Because protocol buffers optimize each serialization based on the content, we can not exactly
30 // calculate the file size that any given serialization will produce ahead of time. So, in order
31 // to know into how many batches we will need to split the keys, we simply "attempt" to
32 // serialize all keys into a single file and measure its size. If we find that the resulting
33 // file goes above the file size limit, we simply partition the keys into N + 1 partitions of
34 // approximately equal size, where N = (first file size / file size limit). We add one to N
35 // for good measure, to avoid edge cases, rounding errors and varying file sizes after
36 // serialization.
37 File singleFile = aggregateKeysIntoBatches(keys, 1, startTimestamp, endTimeStamp, region)
38 .stream()
39 .findFirst()
40 .orElseThrow();
41 int singleFileSize = singleFile.getSerializedSize();
42 if (singleFileSize > FILE_SIZE_LIMIT_BYTES) {
43 int numBatches = Maths.ceilDiv(singleFileSize, FILE_SIZE_LIMIT_BYTES) + 1;
44 return aggregateKeysIntoBatches(keys, numBatches, startTimestamp, endTimeStamp, region);
45 } else {
46 return Set.of(singleFile);
47 }
48 }
49
50 /**
51 * Aggregates a set of {@link Key Keys} into a set of equally sized {@link File Files}.
52 */
53 private static Set<File> aggregateKeysIntoBatches(Set<Key> keys, int numBatches,
54 Instant startTimestamp, Instant endTimeStamp, String region) {
55 List<Set<Key>> partitions = partitionSet(keys, numBatches);
56 return IntStream.range(0, partitions.size())
57 .mapToObj(index -> {
58 Header header = Header.newBuilder()
59 .setStartTimestamp(startTimestamp.toEpochMilli())
60 .setEndTimestamp(endTimeStamp.toEpochMilli())
61 .setRegion(region)
62 .setBatchNum(index + 1)
63 .setBatchSize(numBatches)
64 .build();
65 Set<Key> partition = partitions.get(index);
66 return File
67 .newBuilder()
68 .setHeader(header)
69 .addAllKeys(partition)
70 .build();
71 })
72 .collect(Collectors.toSet());
73 }
74
75 /**
76 * Partitions a set into {@code numPartitions} equally sized sets.
77 *
78 * @param set The set to partition
79 * @param numPartitions The number of partitions
80 * @return A list of sets of equal size
81 */
82 private static <T> List<Set<T>> partitionSet(Set<T> set, int numPartitions) {
83 int partitionSize = Maths.ceilDiv(set.size(), numPartitions);
84 List<T> list = new ArrayList<>(set);
85 return IntStream.range(0, numPartitions)
86 .mapToObj(currentPartition -> new HashSet<>(list.subList(partitionSize * currentPartition,
87 Math.min(currentPartition * partitionSize + partitionSize, list.size()))))
88 .collect(Collectors.toList());
89 }
90 }
91
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/diagnosiskeys/util/Batch.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/diagnosiskeys/util/DateTime.java]
1 package app.coronawarn.server.services.distribution.diagnosiskeys.util;
2
3 import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
4 import java.time.LocalDate;
5 import java.time.LocalDateTime;
6 import java.time.ZoneOffset;
7 import java.util.Collection;
8 import java.util.Set;
9 import java.util.concurrent.TimeUnit;
10 import java.util.stream.Collectors;
11
12 /**
13 * Methods for conversions of time/date data.
14 */
15 public class DateTime {
16
17 /**
18 * Returns a set of all {@link LocalDate dates} that are associated with the submission timestamps
19 * of the specified {@link DiagnosisKey diagnosis keys}.
20 */
21 public static Set<LocalDate> getDates(Collection<DiagnosisKey> diagnosisKeys) {
22 return diagnosisKeys.stream()
23 .map(DiagnosisKey::getSubmissionTimestamp)
24 .map(timestamp -> LocalDate.ofEpochDay(timestamp / 24))
25 .collect(Collectors.toSet());
26 }
27
28
29 /**
30 * Returns a set of all {@link LocalDateTime hours} that are associated with the submission
31 * timestamps of the specified {@link DiagnosisKey diagnosis keys} and the specified {@link
32 * LocalDate date}.
33 */
34 public static Set<LocalDateTime> getHours(LocalDate currentDate,
35 Collection<DiagnosisKey> diagnosisKeys) {
36 return diagnosisKeys.stream()
37 .map(DiagnosisKey::getSubmissionTimestamp)
38 .map(DateTime::getLocalDateTimeFromHoursSinceEpoch)
39 .filter(currentDateTime -> currentDateTime.toLocalDate().equals(currentDate))
40 .collect(Collectors.toSet());
41 }
42
43 /**
44 * Creates a {@link LocalDateTime} based on the specified epoch timestamp.
45 */
46 public static LocalDateTime getLocalDateTimeFromHoursSinceEpoch(long timestamp) {
47 return LocalDateTime.ofEpochSecond(TimeUnit.HOURS.toSeconds(timestamp), 0, ZoneOffset.UTC);
48 }
49 }
50
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/diagnosiskeys/util/DateTime.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/diagnosiskeys/util/Maths.java]
1 package app.coronawarn.server.services.distribution.diagnosiskeys.util;
2
3 public class Maths {
4
5 public static int ceilDiv(int numerator, int denominator) {
6 return (numerator + denominator - 1) / denominator;
7 }
8 }
9
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/diagnosiskeys/util/Maths.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/exposureconfig/ExposureConfigurationProvider.java]
1 package app.coronawarn.server.services.distribution.exposureconfig;
2
3 import app.coronawarn.server.common.protocols.internal.RiskScoreParameters;
4 import app.coronawarn.server.common.protocols.internal.RiskScoreParameters.Builder;
5 import app.coronawarn.server.services.distribution.exposureconfig.parsing.YamlConstructorForProtoBuf;
6 import java.io.IOException;
7 import java.io.InputStream;
8 import org.springframework.core.io.ClassPathResource;
9 import org.springframework.core.io.Resource;
10 import org.yaml.snakeyaml.Yaml;
11 import org.yaml.snakeyaml.error.YAMLException;
12 import org.yaml.snakeyaml.introspector.BeanAccess;
13
14 /**
15 * Provides the Exposure Configuration based on a file in the fileystem.<br> The existing file must
16 * be a valid YAML file, and must match the specification of the proto file
17 * risk_score_parameters.proto.
18 */
19 public class ExposureConfigurationProvider {
20
21 private ExposureConfigurationProvider() {
22 }
23
24 /**
25 * The location of the exposure configuration master file.
26 */
27 public static final String MASTER_FILE = "exposure-config/master.yaml";
28
29 /**
30 * Fetches the master configuration as a RiskScoreParameters instance.
31 *
32 * @return the exposure configuration as RiskScoreParameters
33 * @throws UnableToLoadFileException when the file/transformation did not succeed
34 */
35 public static RiskScoreParameters readMasterFile() throws UnableToLoadFileException {
36 return readFile(MASTER_FILE);
37 }
38
39 /**
40 * Fetches an exposure configuration file based on the given path. The path must be available in
41 * the classloader.
42 *
43 * @param path the path, e.g. folder/my-exposure-configuration.yaml
44 * @return the RiskScoreParameters
45 * @throws UnableToLoadFileException when the file/transformation did not succeed
46 */
47 public static RiskScoreParameters readFile(String path) throws UnableToLoadFileException {
48 Yaml yaml = new Yaml(new YamlConstructorForProtoBuf());
49 yaml.setBeanAccess(BeanAccess.FIELD); /* no setters on RiskScoreParameters available */
50
51 Resource riskScoreParametersResource = new ClassPathResource(path);
52 try (InputStream inputStream = riskScoreParametersResource.getInputStream()) {
53 Builder loaded = yaml.loadAs(inputStream, RiskScoreParameters.newBuilder().getClass());
54 if (loaded == null) {
55 throw new UnableToLoadFileException(path);
56 }
57
58 return loaded.build();
59 } catch (YAMLException e) {
60 throw new UnableToLoadFileException("Parsing failed", e);
61 } catch (IOException e) {
62 throw new UnableToLoadFileException("Failed to load file " + path, e);
63 }
64 }
65 }
66
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/exposureconfig/ExposureConfigurationProvider.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/exposureconfig/UnableToLoadFileException.java]
1 package app.coronawarn.server.services.distribution.exposureconfig;
2
3 /**
4 * The file could not be loaded/parsed correctly.
5 */
6 public class UnableToLoadFileException extends Exception {
7
8 public UnableToLoadFileException(String message) {
9 super(message);
10 }
11
12 public UnableToLoadFileException(String message, Throwable cause) {
13 super(message, cause);
14 }
15 }
16
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/exposureconfig/UnableToLoadFileException.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/exposureconfig/parsing/YamlConstructorForProtoBuf.java]
1 package app.coronawarn.server.services.distribution.exposureconfig.parsing;
2
3 import java.util.Arrays;
4 import org.yaml.snakeyaml.constructor.Constructor;
5 import org.yaml.snakeyaml.introspector.BeanAccess;
6 import org.yaml.snakeyaml.introspector.Property;
7 import org.yaml.snakeyaml.introspector.PropertyUtils;
8
9 /**
10 * This Constructor implementation grants SnakeYaml compliance with the generated proto Java
11 * classes.
12 * SnakeYaml expects the Java properties to have the same name as the yaml properties. But the
13 * generated Java classes' properties have an added suffix of '_'.
14 * In addition, this implementation also allows snake case in the YAML (for better readability), as
15 * the Java properties are transformed to camel case.
16 */
17 public class YamlConstructorForProtoBuf extends Constructor {
18
19 public YamlConstructorForProtoBuf() {
20 setPropertyUtils(new ProtoBufPropertyUtils());
21 }
22
23 private class ProtoBufPropertyUtils extends PropertyUtils {
24
25 public Property getProperty(Class<? extends Object> type, String name, BeanAccess bAccess) {
26 return super.getProperty(type, transformToProtoNaming(name), bAccess);
27 }
28
29 private String transformToProtoNaming(String yamlPropertyName) {
30 return snakeToCamelCase(yamlPropertyName) + "_";
31 }
32
33 private String snakeToCamelCase(String snakeCase) {
34 String camelCase = Arrays.stream(snakeCase.split("_"))
35 .map(word -> Character.toUpperCase(word.charAt(0)) + word.substring(1))
36 .reduce("", String::concat);
37
38 return Character.toLowerCase(camelCase.charAt(0)) + camelCase.substring(1);
39 }
40 }
41
42 }
43
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/exposureconfig/parsing/YamlConstructorForProtoBuf.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/exposureconfig/structure/ExposureConfigurationDirectoryImpl.java]
1 package app.coronawarn.server.services.distribution.exposureconfig.structure;
2
3 import app.coronawarn.server.common.protocols.internal.RiskScoreParameters;
4 import app.coronawarn.server.services.distribution.crypto.CryptoProvider;
5 import app.coronawarn.server.services.distribution.structure.directory.DirectoryImpl;
6 import app.coronawarn.server.services.distribution.structure.directory.IndexDirectoryImpl;
7 import app.coronawarn.server.services.distribution.structure.directory.decorator.IndexingDecorator;
8 import app.coronawarn.server.services.distribution.structure.file.FileImpl;
9 import app.coronawarn.server.services.distribution.structure.file.decorator.SigningDecorator;
10 import java.util.Set;
11
12 /**
13 * Creates the directory structure {@code /parameters/country/:country} and writes a file called
14 * {@code index} containing {@link RiskScoreParameters} wrapped in a {@link
15 * app.coronawarn.server.common.protocols.internal.SignedPayload}.
16 */
17 public class ExposureConfigurationDirectoryImpl extends DirectoryImpl {
18
19 private static final String PARAMETERS_DIRECTORY = "parameters";
20 private static final String COUNTRY_DIRECTORY = "country";
21 private static final String INDEX_FILE_NAME = "index";
22
23 /**
24 * Constructor.
25 *
26 * @param region The region that the {@link RiskScoreParameters} apply to.
27 * @param exposureConfig The {@link RiskScoreParameters} to sign and write.
28 * @param cryptoProvider The {@link CryptoProvider} whose artifacts to use for creating the {@link
29 * app.coronawarn.server.common.protocols.internal.SignedPayload}.
30 */
31 public ExposureConfigurationDirectoryImpl(
32 String region, RiskScoreParameters exposureConfig, CryptoProvider cryptoProvider) {
33 super(PARAMETERS_DIRECTORY);
34
35 IndexDirectoryImpl<String> country =
36 new IndexDirectoryImpl<>(COUNTRY_DIRECTORY, __ -> Set.of(region), Object::toString);
37
38 country.addFileToAll(__ ->
39 new SigningDecorator(new FileImpl(INDEX_FILE_NAME, exposureConfig.toByteArray()),
40 cryptoProvider));
41
42 this.addDirectory(new IndexingDecorator<>(country));
43 }
44 }
45
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/exposureconfig/structure/ExposureConfigurationDirectoryImpl.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/exposureconfig/structure/directory/ExposureConfigurationDirectoryImpl.java]
1 package app.coronawarn.server.services.distribution.exposureconfig.structure.directory;
2
3 import app.coronawarn.server.common.protocols.internal.RiskScoreParameters;
4 import app.coronawarn.server.services.distribution.crypto.CryptoProvider;
5 import app.coronawarn.server.services.distribution.structure.directory.DirectoryImpl;
6 import app.coronawarn.server.services.distribution.structure.directory.IndexDirectoryImpl;
7 import app.coronawarn.server.services.distribution.structure.directory.decorator.IndexingDecorator;
8 import app.coronawarn.server.services.distribution.structure.file.FileImpl;
9 import app.coronawarn.server.services.distribution.structure.file.decorator.SigningDecorator;
10 import java.util.Set;
11
12 /**
13 * Creates the directory structure {@code /parameters/country/:country} and writes a file called
14 * {@code index} containing {@link RiskScoreParameters} wrapped in a {@link
15 * app.coronawarn.server.common.protocols.internal.SignedPayload}.
16 */
17 public class ExposureConfigurationDirectoryImpl extends DirectoryImpl {
18
19 private static final String PARAMETERS_DIRECTORY = "parameters";
20 private static final String COUNTRY_DIRECTORY = "country";
21 private static final String COUNTRY = "DE";
22 private static final String INDEX_FILE_NAME = "index";
23
24 /**
25 * Constructor.
26 *
27 * @param exposureConfig The {@link RiskScoreParameters} to sign and write.
28 * @param cryptoProvider The {@link CryptoProvider} whose artifacts to use for creating the {@link
29 * app.coronawarn.server.common.protocols.internal.SignedPayload}.
30 */
31 public ExposureConfigurationDirectoryImpl(RiskScoreParameters exposureConfig,
32 CryptoProvider cryptoProvider) {
33 super(PARAMETERS_DIRECTORY);
34
35 IndexDirectoryImpl<String> country =
36 new IndexDirectoryImpl<>(COUNTRY_DIRECTORY, __ -> Set.of(COUNTRY), Object::toString);
37
38 country.addFileToAll(__ ->
39 new SigningDecorator(new FileImpl(INDEX_FILE_NAME, exposureConfig.toByteArray()),
40 cryptoProvider));
41
42 this.addDirectory(new IndexingDecorator<>(country));
43 }
44 }
45
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/exposureconfig/structure/directory/ExposureConfigurationDirectoryImpl.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/exposureconfig/validation/ExposureConfigurationValidator.java]
1 package app.coronawarn.server.services.distribution.exposureconfig.validation;
2
3 import app.coronawarn.server.common.protocols.internal.RiskLevel;
4 import app.coronawarn.server.common.protocols.internal.RiskScoreParameters;
5 import app.coronawarn.server.services.distribution.exposureconfig.validation.WeightValidationError.ErrorType;
6 import java.beans.BeanInfo;
7 import java.beans.IntrospectionException;
8 import java.beans.Introspector;
9 import java.beans.PropertyDescriptor;
10 import java.lang.reflect.InvocationTargetException;
11 import java.math.BigDecimal;
12 import java.util.Arrays;
13
14 /**
15 * The Exposure Configuration Validator checks the values of a given RiskScoreParameters instance.
16 * Validation is performed according to the Apple/Google spec.<br>
17 * <br>
18 * Weights must be in the range of 0.001 to 100.<br> Scores must be in the range of 1 to 8.<br>
19 */
20 public class ExposureConfigurationValidator {
21
22 private RiskScoreParameters config;
23
24 private ValidationResult errors;
25
26 public ExposureConfigurationValidator(RiskScoreParameters config) {
27 this.config = config;
28 }
29
30 /**
31 * Triggers the validation of the configuration.
32 *
33 * @return the ValidationResult instance, containing information about possible errors.
34 * @throws ValidationFailedException in case the validation could not be performed
35 */
36 public ValidationResult validate() {
37 this.errors = new ValidationResult();
38
39 validateWeights();
40
41 try {
42 validateParameterRiskLevels("duration", config.getDuration());
43 validateParameterRiskLevels("transmission", config.getTransmission());
44 validateParameterRiskLevels("daysSinceLastExposure", config.getDaysSinceLastExposure());
45 validateParameterRiskLevels("attenuation", config.getAttenuation());
46 } catch (IntrospectionException e) {
47 throw new ValidationFailedException("Unable to check risk levels", e);
48 }
49
50 return errors;
51 }
52
53 private void validateParameterRiskLevels(String name, Object object)
54 throws IntrospectionException {
55 BeanInfo bean = Introspector.getBeanInfo(object.getClass());
56
57 Arrays.stream(bean.getPropertyDescriptors())
58 .filter(propertyDescriptor -> propertyDescriptor.getPropertyType() == RiskLevel.class)
59 .forEach(propertyDescriptor -> validateScore(propertyDescriptor, object, name));
60 }
61
62 private void validateScore(
63 PropertyDescriptor propertyDescriptor, Object object, String parameter) {
64 try {
65 RiskLevel level = (RiskLevel) propertyDescriptor.getReadMethod().invoke(object);
66
67 if (level == RiskLevel.UNRECOGNIZED || level == RiskLevel.RISK_LEVEL_UNSPECIFIED) {
68 this.errors.add(new RiskLevelValidationError(parameter, propertyDescriptor.getName()));
69 }
70 } catch (IllegalAccessException | InvocationTargetException e) {
71 throw new ValidationFailedException(
72 "Unable to read property " + propertyDescriptor.getName(), e);
73 }
74 }
75
76 private void validateWeights() {
77 validateWeight(config.getTransmissionWeight(), "transmission");
78 validateWeight(config.getDurationWeight(), "duration");
79 validateWeight(config.getAttenuationWeight(), "attenuation");
80 }
81
82 private void validateWeight(double weight, String name) {
83 if (isOutOfRange(ParameterSpec.WEIGHT_MIN, ParameterSpec.WEIGHT_MAX, weight)) {
84 this.errors.add(new WeightValidationError(name, weight, ErrorType.OUT_OF_RANGE));
85 }
86
87 if (!respectsMaximumDecimalPlaces(weight)) {
88 this.errors.add(new WeightValidationError(name, weight, ErrorType.TOO_MANY_DECIMAL_PLACES));
89 }
90 }
91
92 private boolean respectsMaximumDecimalPlaces(double weight) {
93 BigDecimal bd = new BigDecimal(String.valueOf(weight));
94
95 return bd.scale() <= ParameterSpec.WEIGHT_MAX_DECIMALS;
96 }
97
98
99 private boolean isOutOfRange(double min, double max, double x) {
100 return x < min || x > max;
101 }
102 }
103
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/exposureconfig/validation/ExposureConfigurationValidator.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/exposureconfig/validation/ParameterSpec.java]
1 package app.coronawarn.server.services.distribution.exposureconfig.validation;
2
3 /**
4 * Definition of the spec according to Apple/Google:
5 * https://developer.apple.com/documentation/exposurenotification/enexposureconfiguration
6 */
7 public class ParameterSpec {
8
9 private ParameterSpec() {
10 }
11
12 /** The minimum weight value for mobile API. */
13 public static final double WEIGHT_MIN = 0.001;
14
15 /** The maximum weight value for mobile API. */
16 public static final int WEIGHT_MAX = 100;
17
18 /** Maximmum number of allowed decimals. */
19 public static final int WEIGHT_MAX_DECIMALS = 3;
20
21 }
22
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/exposureconfig/validation/ParameterSpec.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/exposureconfig/validation/RiskLevelValidationError.java]
1 package app.coronawarn.server.services.distribution.exposureconfig.validation;
2
3 import java.util.Objects;
4
5 /**
6 * Defines a validation errors for risk levels, used by the parameter scores.
7 */
8 public class RiskLevelValidationError implements ValidationError {
9
10 private final String parameter;
11
12 private final String riskLevel;
13
14 public RiskLevelValidationError(String parameter, String riskLevel) {
15 this.parameter = parameter;
16 this.riskLevel = riskLevel;
17 }
18
19 public String getParameter() {
20 return parameter;
21 }
22
23 public String getRiskLevel() {
24 return riskLevel;
25 }
26
27 @Override
28 public boolean equals(Object o) {
29 if (this == o) {
30 return true;
31 }
32 if (o == null || getClass() != o.getClass()) {
33 return false;
34 }
35 RiskLevelValidationError that = (RiskLevelValidationError) o;
36 return Objects.equals(getParameter(), that.getParameter())
37 && Objects.equals(getRiskLevel(), that.getRiskLevel());
38 }
39
40 @Override
41 public int hashCode() {
42 return Objects.hash(getParameter(), getRiskLevel());
43 }
44
45 @Override
46 public String toString() {
47 return "RiskLevelValidationError{" +
48 "parameter='" + parameter + '\'' +
49 ", riskLevel='" + riskLevel + '\'' +
50 '}';
51 }
52 }
53
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/exposureconfig/validation/RiskLevelValidationError.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/exposureconfig/validation/ValidationError.java]
1 package app.coronawarn.server.services.distribution.exposureconfig.validation;
2
3 /**
4 * A validation error, found during the process of validating the Exposure Configuration. Can either
5 * be score or weight related.
6 */
7 public interface ValidationError {
8
9 }
10
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/exposureconfig/validation/ValidationError.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/exposureconfig/validation/ValidationFailedException.java]
1 package app.coronawarn.server.services.distribution.exposureconfig.validation;
2
3 /**
4 * The validation could not be executed. Find more information about the root cause in the cause
5 * element, and in the message property.<br>
6 */
7 public class ValidationFailedException extends RuntimeException {
8
9 public ValidationFailedException(String message, Throwable cause) {
10 super(message, cause);
11 }
12 }
13
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/exposureconfig/validation/ValidationFailedException.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/exposureconfig/validation/ValidationResult.java]
1 package app.coronawarn.server.services.distribution.exposureconfig.validation;
2
3 import java.util.HashSet;
4
5 /**
6 * The result of a validation run for Exposure Configurations. Find details about possible
7 * errors in this collection.
8 */
9 public class ValidationResult extends HashSet<ValidationError> {
10
11 /**
12 * Checks whether this validation result instance has at least one error.
13 *
14 * @return true if yes, false otherwise
15 */
16 public boolean hasErrors() {
17 return !this.isEmpty();
18 }
19
20 /**
21 * Checks whether this validation result instance has no errors.
22 *
23 * @return true if yes, false otherwise
24 */
25 public boolean isSuccessful() {
26 return !hasErrors();
27 }
28 }
29
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/exposureconfig/validation/ValidationResult.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/exposureconfig/validation/WeightValidationError.java]
1 package app.coronawarn.server.services.distribution.exposureconfig.validation;
2
3 import java.util.Objects;
4
5 public class WeightValidationError implements ValidationError {
6
7 private final ErrorType errorType;
8
9 private final String parameter;
10
11 private final double givenValue;
12
13 public WeightValidationError(String parameter, double givenValue, ErrorType errorType) {
14 this.parameter = parameter;
15 this.givenValue = givenValue;
16 this.errorType = errorType;
17 }
18
19 public String getParameter() {
20 return parameter;
21 }
22
23 public double getGivenValue() {
24 return givenValue;
25 }
26
27 public ErrorType getErrorType() {
28 return errorType;
29 }
30
31 @Override
32 public boolean equals(Object o) {
33 if (this == o) {
34 return true;
35 }
36 if (o == null || getClass() != o.getClass()) {
37 return false;
38 }
39 WeightValidationError that = (WeightValidationError) o;
40 return Double.compare(that.getGivenValue(), getGivenValue()) == 0
41 && getErrorType() == that.getErrorType()
42 && Objects.equals(getParameter(), that.getParameter());
43 }
44
45 @Override
46 public int hashCode() {
47 return Objects.hash(getErrorType(), getParameter(), getGivenValue());
48 }
49
50 @Override
51 public String toString() {
52 return "WeightValidationError{" +
53 "errorType=" + errorType +
54 ", parameter='" + parameter + '\'' +
55 ", givenValue=" + givenValue +
56 '}';
57 }
58
59 public enum ErrorType {
60 OUT_OF_RANGE,
61 TOO_MANY_DECIMAL_PLACES
62 }
63 }
64
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/exposureconfig/validation/WeightValidationError.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/io/IO.java]
1 package app.coronawarn.server.services.distribution.io;
2
3 import java.io.File;
4 import java.io.FileOutputStream;
5 import java.io.IOException;
6 import java.nio.file.Files;
7 import org.slf4j.Logger;
8 import org.slf4j.LoggerFactory;
9
10 /**
11 * A class containing helper functions for general purpose file IO.
12 */
13 public class IO {
14
15 private static final Logger logger = LoggerFactory.getLogger(IO.class);
16
17 /**
18 * Creates a new file on disk.
19 *
20 * @param root The parent file.
21 * @param name The name of the new file.
22 */
23 public static void makeFile(File root, String name) {
24 File directory = new File(root, name);
25 try {
26 directory.createNewFile();
27 } catch (IOException e) {
28 logger.error("Failed to create file: {}", name, e);
29 throw new RuntimeException(e);
30 }
31 }
32
33 /**
34 * Reads the contents of a file as {@code byte[]}.
35 *
36 * @param file The file to read.
37 * @return The contents of the file as {@code byte[]}.
38 */
39 public static byte[] getBytesFromFile(File file) {
40 try {
41 return Files.readAllBytes(file.toPath());
42 } catch (IOException e) {
43 logger.error("Read operation failed.", e);
44 throw new RuntimeException(e);
45 }
46 }
47
48 /**
49 * Writes bytes into a file.
50 *
51 * @param bytes The content to write
52 * @param outputFile The file to write the content into.
53 */
54 public static void writeBytesToFile(byte[] bytes, File outputFile) {
55 try (FileOutputStream outputFileStream = new FileOutputStream(outputFile)) {
56 outputFileStream.write(bytes);
57 } catch (IOException e) {
58 logger.error("Write operation failed.", e);
59 throw new RuntimeException(e);
60 }
61 }
62 }
63
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/io/IO.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/ObjectStoreAccess.java]
1 package app.coronawarn.server.services.distribution.objectstore;
2
3 import java.io.File;
4 import java.net.URI;
5 import java.net.URISyntaxException;
6 import java.util.Collection;
7 import java.util.stream.Collectors;
8 import org.slf4j.Logger;
9 import org.slf4j.LoggerFactory;
10 import org.springframework.beans.factory.annotation.Autowired;
11 import org.springframework.beans.factory.annotation.Value;
12 import org.springframework.stereotype.Component;
13 import software.amazon.awssdk.core.sync.RequestBody;
14 import software.amazon.awssdk.regions.Region;
15 import software.amazon.awssdk.services.s3.S3Client;
16 import software.amazon.awssdk.services.s3.model.Delete;
17 import software.amazon.awssdk.services.s3.model.DeleteObjectsRequest;
18 import software.amazon.awssdk.services.s3.model.ListObjectsV2Request;
19 import software.amazon.awssdk.services.s3.model.ListObjectsV2Response;
20 import software.amazon.awssdk.services.s3.model.ObjectIdentifier;
21 import software.amazon.awssdk.services.s3.model.PutObjectRequest;
22
23 /**
24 * <p>Grants access to the object store, enabling basic functionality for working with files.</p>
25 * <p>Use S3Publisher for more convenient access.</p>
26 * <br>
27 * Make sure the following ENV vars are available.
28 * <ul>
29 * <li>cwa.objectstore.endpoint</li>
30 * <li>cwa.objectstore.bucket</li>
31 * <li>AWS_ACCESS_KEY_ID</li>
32 * <li>AWS_SECRET_ACCESS_KEY</li>
33 * </ul>
34 *
35 */
36 @Component
37 public class ObjectStoreAccess {
38
39 private Logger logger = LoggerFactory.getLogger(this.getClass());
40
41 private String bucket;
42
43 private S3Client client;
44
45 @Autowired
46 public ObjectStoreAccess(@Value("${cwa.objectstore.endpoint:notset}") String endpoint,
47 @Value("${cwa.objectstore.bucket:notset}") String bucket) throws URISyntaxException {
48 this.bucket = bucket;
49
50 if ("notset".equals(endpoint) || "notset".equals(bucket)) {
51 logger.error("S3 Connection parameters missing - unable to serve S3 integration.");
52 return;
53 }
54
55 this.client = S3Client.builder()
56 .endpointOverride(new URI(endpoint))
57 .region(Region.EU_CENTRAL_1) /* required by SDK, but ignored on S3 side */
58 .build();
59 }
60
61 /**
62 * Stores an object in the object store.
63 *
64 * @param key the key to use, e.g. my/folder/struc/file.ext
65 * @param file the file to upload
66 */
67 public void putObject(String key, File file) {
68 RequestBody bodyFile = RequestBody.fromFile(file);
69
70 this.client
71 .putObject(PutObjectRequest.builder().bucket(this.bucket).key(key).build(), bodyFile);
72 }
73
74 /**
75 * Deletes objects in the object store, based on the given prefix (folder structure).
76 *
77 * @param prefix the prefix, e.g. my/folder/
78 */
79 public void deleteObjectsWithPrefix(String prefix) {
80 ListObjectsV2Response files = getObjectsWithPrefix(prefix);
81 Collection<ObjectIdentifier> identifiers = files
82 .contents()
83 .stream()
84 .map(s3object -> ObjectIdentifier.builder().key(s3object.key()).build())
85 .collect(Collectors.toList());
86
87 this.client.deleteObjects(DeleteObjectsRequest.builder().bucket(this.bucket).delete(
88 Delete.builder().objects(identifiers).build()).build());
89 }
90
91 /**
92 * Fetches the list of objects in the store with the given prefix.
93 *
94 * @param prefix the prefix, e.g. my/folder/
95 * @return the list of objects
96 */
97 public ListObjectsV2Response getObjectsWithPrefix(String prefix) {
98 return client
99 .listObjectsV2(ListObjectsV2Request.builder().prefix(prefix).bucket(this.bucket).build());
100 }
101
102 }
103
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/ObjectStoreAccess.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/S3Publisher.java]
1 package app.coronawarn.server.services.distribution.objectstore;
2
3 import java.io.IOException;
4 import java.nio.file.Files;
5 import java.nio.file.Path;
6 import java.util.stream.Stream;
7 import org.slf4j.Logger;
8 import org.slf4j.LoggerFactory;
9 import org.springframework.beans.factory.annotation.Autowired;
10 import org.springframework.stereotype.Component;
11
12 /**
13 * This publisher is the interface to the S3, translating a local file structure to the target S3
14 * objects.
15 */
16 @Component
17 public class S3Publisher {
18
19 private Logger logger = LoggerFactory.getLogger(this.getClass());
20
21 /**
22 * prefix path on S3, enforced for all methods on this class.
23 */
24 private String prefixPath = "cwa/";
25
26 private ObjectStoreAccess objectStoreAccess;
27
28 @Autowired
29 public S3Publisher(ObjectStoreAccess objectStoreAccess) {
30 this.objectStoreAccess = objectStoreAccess;
31 }
32
33 /**
34 * Publishes a local folder to S3. All files in the target folder will be copied over to S3,
35 * keeping the file structure. This operation is running also through all subfolders
36 * (recursively).
37 *
38 * @param path the folder on the local disk
39 * @throws IOException in case there was a problem reading the folder/contents
40 */
41 public void publishFolder(Path path) throws IOException {
42 if (!path.toFile().isDirectory()) {
43 throw new UnsupportedOperationException("Supplied path is not a folder: " + path);
44 }
45
46 try (Stream<Path> stream = Files.walk(path, Integer.MAX_VALUE)) {
47 stream.filter(Files::isRegularFile).forEach(file -> publishFile(file, path));
48 }
49 }
50
51 /**
52 * Deletes a folder on S3.
53 *
54 * @param path the folder to delete
55 */
56 public void deleteFolder(String path) {
57 objectStoreAccess.deleteObjectsWithPrefix(prefixPath + path);
58 }
59
60 /**
61 * Publishes the given file.
62 *
63 * @param file the file to publish
64 * @param root the root, needed to compute the relative path for the S3 location
65 */
66 public void publishFile(Path file, Path root) {
67 if (!file.toFile().isFile()) {
68 throw new UnsupportedOperationException("Supplied path is not a file: " + file);
69 }
70 String publishingPath = createS3Key(file, root);
71
72 logger.info("Publishing " + publishingPath);
73 this.objectStoreAccess.putObject(publishingPath, file.toFile());
74 }
75
76 /**
77 * Checks whether the given file exists.
78 * <br>
79 * Both parameters are local on disk, and the S3 path is derived relatively by the root & file.
80 * E.g.:<br> file: /folder1/folder2/file<br> root: /folder1/<br>
81 * <br>
82 * The result S3 location will be /folder2/file, which will be checked for existence.
83 *
84 * @param file the file to check
85 * @param root the root, needed to compute the relative path for the S3 location
86 * @return true, if it exists, false otherwise
87 */
88 public boolean isFileExisting(Path file, Path root) {
89 return this.objectStoreAccess.getObjectsWithPrefix(createS3Key(file, root)).hasContents();
90 }
91
92 /**
93 * Deletes the given file on S3.
94 * <br>
95 * Both parameters are local on disk, and the S3 path is derived relatively by the root & file
96 * E.g.:<br> file: /folder1/folder2/file<br> root: /folder1/<br>
97 * <br>
98 * The result S3 location will be /folder2/file, which will be deleted.
99 *
100 * @param file the file to delete
101 * @param root the root, needed to compute the relative path for the S3 location
102 */
103 public void deleteFile(Path file, Path root) {
104 this.objectStoreAccess.deleteObjectsWithPrefix(createS3Key(file, root));
105 }
106
107 private String createS3Key(Path file, Path rootFolder) {
108 Path relativePath = rootFolder.relativize(file);
109 return s3path(relativePath.toString());
110 }
111
112 private String s3path(String path) {
113 return prefixPath + path;
114 }
115
116 /**
117 * Changes the prefix path for all S3Publisher operations. The default root.
118 *
119 * @param prefixPath the new prefix path
120 */
121 public void setPrefixPath(String prefixPath) {
122 this.prefixPath = prefixPath;
123 }
124 }
125
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/S3Publisher.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/DiagnosisKeyDistributionRunner.java]
1 package app.coronawarn.server.services.distribution.runner;
2
3 import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
4 import app.coronawarn.server.common.persistence.service.DiagnosisKeyService;
5 import app.coronawarn.server.services.distribution.crypto.CryptoProvider;
6 import app.coronawarn.server.services.distribution.diagnosiskeys.structure.directory.DiagnosisKeysDirectoryImpl;
7 import app.coronawarn.server.services.distribution.structure.directory.DirectoryImpl;
8 import app.coronawarn.server.services.distribution.structure.directory.IndexDirectory;
9 import app.coronawarn.server.services.distribution.structure.directory.IndexDirectoryImpl;
10 import app.coronawarn.server.services.distribution.structure.directory.decorator.IndexingDecorator;
11 import app.coronawarn.server.services.distribution.structure.util.ImmutableStack;
12 import java.io.File;
13 import java.io.IOException;
14 import java.util.Collection;
15 import java.util.Set;
16 import org.apache.commons.io.FileUtils;
17 import org.slf4j.Logger;
18 import org.slf4j.LoggerFactory;
19 import org.springframework.beans.factory.annotation.Autowired;
20 import org.springframework.beans.factory.annotation.Value;
21 import org.springframework.boot.ApplicationArguments;
22 import org.springframework.boot.ApplicationRunner;
23 import org.springframework.core.annotation.Order;
24 import org.springframework.stereotype.Component;
25
26 @Component
27 @Order(3)
28 /**
29 * This runner retrieves stored diagnosis keys, the generates and persists the respective diagnosis
30 * key bundles.
31 */
32 public class DiagnosisKeyDistributionRunner implements ApplicationRunner {
33
34 private static final Logger logger = LoggerFactory
35 .getLogger(DiagnosisKeyDistributionRunner.class);
36
37 private static final String VERSION_DIRECTORY = "version";
38
39 @Value("${app.coronawarn.server.services.distribution.version}")
40 private String version;
41
42 @Value("${app.coronawarn.server.services.distribution.paths.output}")
43 private String outputPath;
44
45 @Autowired
46 private CryptoProvider cryptoProvider;
47
48 @Autowired
49 private DiagnosisKeyService diagnosisKeyService;
50
51
52 @Override
53 public void run(ApplicationArguments args) throws IOException {
54 Collection<DiagnosisKey> diagnosisKeys = diagnosisKeyService.getDiagnosisKeys();
55
56 DiagnosisKeysDirectoryImpl diagnosisKeysDirectory =
57 new DiagnosisKeysDirectoryImpl(diagnosisKeys, cryptoProvider);
58
59 IndexDirectory<?> versionDirectory =
60 new IndexDirectoryImpl<>(VERSION_DIRECTORY, __ -> Set.of(version), Object::toString);
61
62 versionDirectory.addDirectoryToAll(__ -> diagnosisKeysDirectory);
63
64 java.io.File outputDirectory = new File(outputPath);
65 clearDirectory(outputDirectory);
66 DirectoryImpl root = new DirectoryImpl(outputDirectory);
67 root.addDirectory(new IndexingDecorator<>(versionDirectory));
68
69 root.prepare(new ImmutableStack<>());
70 root.write();
71 logger.debug("Diagnosis key distribution structure written successfully.");
72 }
73
74 private static void clearDirectory(File directory) throws IOException {
75 FileUtils.deleteDirectory(directory);
76 directory.mkdirs();
77 }
78 }
79
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/DiagnosisKeyDistributionRunner.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/ExposureConfigurationDistributionRunner.java]
1 package app.coronawarn.server.services.distribution.runner;
2
3 import app.coronawarn.server.common.protocols.internal.RiskScoreParameters;
4 import app.coronawarn.server.services.distribution.crypto.CryptoProvider;
5 import app.coronawarn.server.services.distribution.exposureconfig.ExposureConfigurationProvider;
6 import app.coronawarn.server.services.distribution.exposureconfig.UnableToLoadFileException;
7 import app.coronawarn.server.services.distribution.exposureconfig.structure.directory.ExposureConfigurationDirectoryImpl;
8 import app.coronawarn.server.services.distribution.structure.directory.Directory;
9 import app.coronawarn.server.services.distribution.structure.directory.DirectoryImpl;
10 import app.coronawarn.server.services.distribution.structure.directory.IndexDirectory;
11 import app.coronawarn.server.services.distribution.structure.directory.IndexDirectoryImpl;
12 import app.coronawarn.server.services.distribution.structure.directory.decorator.IndexingDecorator;
13 import app.coronawarn.server.services.distribution.structure.util.ImmutableStack;
14 import java.io.File;
15 import java.util.Set;
16 import org.slf4j.Logger;
17 import org.slf4j.LoggerFactory;
18 import org.springframework.beans.factory.annotation.Autowired;
19 import org.springframework.beans.factory.annotation.Value;
20 import org.springframework.boot.ApplicationArguments;
21 import org.springframework.boot.ApplicationRunner;
22 import org.springframework.core.annotation.Order;
23 import org.springframework.stereotype.Component;
24
25 @Component
26 @Order(2)
27 /**
28 * Reads the exposure configuration parameters from the respective file in the class path, then
29 * generates and persists the respective exposure configuration bundle.
30 */
31 public class ExposureConfigurationDistributionRunner implements ApplicationRunner {
32
33 private static final Logger logger =
34 LoggerFactory.getLogger(ExposureConfigurationDistributionRunner.class);
35
36 @Value("${app.coronawarn.server.services.distribution.version}")
37 private String version;
38
39 @Value("${app.coronawarn.server.services.distribution.paths.output}")
40 private String outputPath;
41
42 @Autowired
43 private CryptoProvider cryptoProvider;
44
45 private static final String VERSION_DIRECTORY = "version";
46
47 @Override
48 public void run(ApplicationArguments args) {
49 var riskScoreParameters = readExposureConfiguration();
50 IndexDirectory<?> versionDirectory =
51 new IndexDirectoryImpl<>(VERSION_DIRECTORY, __ -> Set.of(version), Object::toString);
52 ExposureConfigurationDirectoryImpl parametersDirectory =
53 new ExposureConfigurationDirectoryImpl(riskScoreParameters, cryptoProvider);
54 Directory root = new DirectoryImpl(new File(outputPath));
55 versionDirectory.addDirectoryToAll(__ -> parametersDirectory);
56 root.addDirectory(new IndexingDecorator<>(versionDirectory));
57 root.prepare(new ImmutableStack<>());
58 root.write();
59 logger.debug("Exposure configuration structure written successfully.");
60 }
61
62 private RiskScoreParameters readExposureConfiguration() {
63 try {
64 return ExposureConfigurationProvider.readMasterFile();
65 } catch (UnableToLoadFileException e) {
66 logger.error("Could not load exposure configuration parameters", e);
67 throw new RuntimeException(e);
68 }
69 }
70 }
71
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/ExposureConfigurationDistributionRunner.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/RetentionPolicyRunner.java]
1 package app.coronawarn.server.services.distribution.runner;
2
3 import app.coronawarn.server.common.persistence.service.DiagnosisKeyService;
4 import org.slf4j.Logger;
5 import org.slf4j.LoggerFactory;
6 import org.springframework.beans.factory.annotation.Autowired;
7 import org.springframework.beans.factory.annotation.Value;
8 import org.springframework.boot.ApplicationArguments;
9 import org.springframework.boot.ApplicationRunner;
10 import org.springframework.core.annotation.Order;
11 import org.springframework.stereotype.Component;
12
13 /**
14 * This runner removes any diagnosis keys from the database that were submitted before a configured
15 * threshold of days.
16 */
17 @Component
18 @Order(1)
19 public class RetentionPolicyRunner implements ApplicationRunner {
20
21 private static final Logger logger = LoggerFactory
22 .getLogger(RetentionPolicyRunner.class);
23
24 @Autowired
25 private DiagnosisKeyService diagnosisKeyService;
26
27 @Value("${app.coronawarn.server.services.distribution.retention_days}")
28 private Integer rententionDays;
29
30 @Override
31 public void run(ApplicationArguments args) {
32 diagnosisKeyService.applyRetentionPolicy(rententionDays);
33
34 logger.debug("Retention policy applied successfully. Deleted all entries older that {} days.",
35 rententionDays);
36 }
37 }
38
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/RetentionPolicyRunner.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/S3DistributionRunner.java]
1 package app.coronawarn.server.services.distribution.runner;
2
3 import app.coronawarn.server.services.distribution.objectstore.S3Publisher;
4 import java.io.IOException;
5 import java.nio.file.Path;
6 import org.slf4j.Logger;
7 import org.slf4j.LoggerFactory;
8 import org.springframework.beans.factory.annotation.Autowired;
9 import org.springframework.beans.factory.annotation.Value;
10 import org.springframework.boot.ApplicationArguments;
11 import org.springframework.boot.ApplicationRunner;
12 import org.springframework.core.annotation.Order;
13 import org.springframework.stereotype.Component;
14
15 /**
16 * This runner will sync the base working directory to the S3.
17 */
18 @Component
19 @Order(4)
20 public class S3DistributionRunner implements ApplicationRunner {
21
22 private Logger logger = LoggerFactory.getLogger(this.getClass());
23
24 @Value("${app.coronawarn.server.services.distribution.paths.output}")
25 private String workdir;
26
27 @Autowired
28 private S3Publisher s3Publisher;
29
30 @Override
31 public void run(ApplicationArguments args) {
32 try {
33 Path pathToDistribute = Path.of(workdir).toAbsolutePath();
34
35 s3Publisher.publishFolder(pathToDistribute);
36 } catch (IOException | UnsupportedOperationException e) {
37 logger.error("Distribution failed.", e);
38 }
39 logger.debug("Data pushed to CDN successfully.");
40 }
41 }
42
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/S3DistributionRunner.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/Writable.java]
1 package app.coronawarn.server.services.distribution.structure;
2
3 import app.coronawarn.server.services.distribution.structure.directory.Directory;
4 import app.coronawarn.server.services.distribution.structure.util.ImmutableStack;
5
6 /**
7 * Something that can be written to disk.
8 */
9 public interface Writable {
10
11 /**
12 * Writes this {@link Writable} to disk.
13 */
14 void write();
15
16 /**
17 * Returns the name of this {@link Writable}.
18 */
19 String getName();
20
21 /**
22 * Returns the parent of this {@link Writable}, or {@code null} if it doesn't have a parent.
23 */
24 Directory getParent();
25
26 /**
27 * Sets the parent of this {@link Writable}.
28 */
29 void setParent(Directory parent);
30
31 /**
32 * Returns the {@link java.io.File} that this {@link Writable} represents on disk.
33 */
34 java.io.File getFileOnDisk();
35
36 /**
37 * Does preparation work for this {@link Writable} (e.g. calculate data, setup structures, etc.).
38 */
39 void prepare(ImmutableStack<Object> indices);
40 }
41
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/Writable.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/WritableImpl.java]
1 package app.coronawarn.server.services.distribution.structure;
2
3 import app.coronawarn.server.services.distribution.structure.directory.Directory;
4 import java.util.Objects;
5
6 public abstract class WritableImpl implements Writable {
7
8 private String name;
9 private Directory parent;
10 private java.io.File fileOnDisk;
11
12 protected WritableImpl(String name) {
13 this.name = name;
14 }
15
16 protected WritableImpl(java.io.File fileOnDisk) {
17 this.fileOnDisk = fileOnDisk;
18 }
19
20 @Override
21 public String getName() {
22 return this.name;
23 }
24
25 @Override
26 public Directory getParent() {
27 return this.parent;
28 }
29
30 @Override
31 public void setParent(Directory parent) {
32 this.parent = parent;
33 }
34
35 @Override
36 public java.io.File getFileOnDisk() {
37 return Objects.requireNonNullElseGet(this.fileOnDisk,
38 () -> getParent().getFileOnDisk().toPath().resolve(this.getName()).toFile());
39 }
40 }
41
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/WritableImpl.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/directory/Directory.java]
1 package app.coronawarn.server.services.distribution.structure.directory;
2
3 import app.coronawarn.server.services.distribution.structure.Writable;
4 import app.coronawarn.server.services.distribution.structure.file.File;
5 import java.util.Set;
6
7 /**
8 * A {@link Writable} containing {@link File files} and further {@link Directory directories}.
9 */
10 public interface Directory extends Writable {
11
12 /**
13 * Adds a {@link File file} to the {@link DirectoryImpl#getFiles files} of this {@link
14 * Directory}.
15 */
16 void addFile(File file);
17
18 /**
19 * Returns all {@link File files} contained in this {@link Directory}.
20 */
21 Set<File> getFiles();
22
23 /**
24 * Adds a {@link Directory directory} to the {@link DirectoryImpl#getDirectories directories} of
25 * this {@link Directory}.
26 */
27 void addDirectory(Directory directory);
28
29
30 /**
31 * Returns all {@link Directory directories} contained in this {@link Directory}.
32 */
33 Set<Directory> getDirectories();
34 }
35
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/directory/Directory.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/directory/DirectoryImpl.java]
1 package app.coronawarn.server.services.distribution.structure.directory;
2
3 import app.coronawarn.server.services.distribution.structure.WritableImpl;
4 import app.coronawarn.server.services.distribution.structure.file.File;
5 import app.coronawarn.server.services.distribution.structure.util.ImmutableStack;
6 import java.util.HashSet;
7 import java.util.Set;
8
9 /**
10 * Implementation of {@link Directory} that interfaces with {@link java.io.File Files} on disk.
11 */
12 public class DirectoryImpl extends WritableImpl implements Directory {
13
14 private final Set<File> files = new HashSet<>();
15 private final Set<Directory> directories = new HashSet<>();
16
17 /**
18 * A root {@link DirectoryImpl} representing an already existing directory on disk.
19 *
20 * @param file The {@link File File} that this {@link DirectoryImpl} represents on disk.
21 */
22 public DirectoryImpl(java.io.File file) {
23 super(file);
24 }
25
26 /**
27 * A {@link DirectoryImpl} that does not yet represent an already existing directory on disk, but
28 * one that shall be created on disk when calling {@link DirectoryImpl#write}. A parent needs to
29 * be defined by calling {@link DirectoryImpl#setParent}, before writing can succeed.
30 *
31 * @param name The name that this directory should have on disk.
32 */
33 public DirectoryImpl(String name) {
34 super(name);
35 }
36
37 @Override
38 public void addFile(File file) {
39 this.files.add(file);
40 file.setParent(this);
41 }
42
43 @Override
44 public Set<File> getFiles() {
45 return this.files;
46 }
47
48 @Override
49 public void addDirectory(Directory directory) {
50 this.directories.add(directory);
51 directory.setParent(this);
52 }
53
54 @Override
55 public Set<Directory> getDirectories() {
56 return this.directories;
57 }
58
59 @Override
60 public void prepare(ImmutableStack<Object> indices) {
61 this.prepareFiles(indices);
62 this.prepareDirectories(indices);
63 }
64
65 private void prepareDirectories(ImmutableStack<Object> indices) {
66 this.directories.forEach(directory -> directory.prepare(indices));
67 }
68
69 private void prepareFiles(ImmutableStack<Object> indices) {
70 this.files.forEach(file -> file.prepare(indices));
71 }
72
73 /**
74 * Writes this {@link DirectoryImpl} and all of its {@link DirectoryImpl#files} and {@link
75 * DirectoryImpl#directories} to disk.
76 */
77 @Override
78 public void write() {
79 this.writeOwnDirectory();
80 this.writeDirectories();
81 this.writeFiles();
82 }
83
84 private void writeOwnDirectory() {
85 java.io.File file = this.getFileOnDisk();
86 file.mkdirs();
87 }
88
89 private void writeDirectories() {
90 this.directories.forEach(Directory::write);
91 }
92
93 private void writeFiles() {
94 this.files.forEach(File::write);
95 }
96 }
97
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/directory/DirectoryImpl.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/directory/IndexDirectory.java]
1 package app.coronawarn.server.services.distribution.structure.directory;
2
3 import app.coronawarn.server.services.distribution.structure.functional.DirectoryFunction;
4 import app.coronawarn.server.services.distribution.structure.functional.FileFunction;
5 import app.coronawarn.server.services.distribution.structure.functional.Formatter;
6 import app.coronawarn.server.services.distribution.structure.util.ImmutableStack;
7 import java.util.Set;
8 import java.util.Stack;
9
10 /**
11 * A meta directory that maps its on-disk subdirectories to some list of elements. This list of
12 * elements is determined by a {@link FileFunction}.
13 *
14 * @param <T> The type of the elements in the index.
15 */
16 public interface IndexDirectory<T> extends Directory {
17
18 /**
19 * Adds a file under the name {@code name}, whose content is calculated by the {@code
20 * fileFunction} to each one of the directories created from the index. The {@code fileFunction}
21 * calculates the file content from a {@link java.util.Stack} of parent {@link IndexDirectoryImpl}
22 * indices. File content calculation happens on {@link DirectoryImpl#write}.
23 *
24 * @param fileFunction A function that can calculate the content of the file, based on
25 */
26 void addFileToAll(FileFunction fileFunction);
27
28 /**
29 * Adds a {@link DirectoryImpl} to each one of the directories created from the index. Analogous
30 * to {@link IndexDirectory#addFileToAll}.
31 */
32 void addDirectoryToAll(DirectoryFunction directoryFunction);
33
34 /**
35 * Calls the {@link app.coronawarn.server.services.distribution.structure.functional.IndexFunction}
36 * with the {@code indices} to calculate and return the elements of the index of this {@link
37 * IndexDirectory}.
38 *
39 * @param indices A {@link Stack} of parameters from all {@link IndexDirectory IndexDirectories}
40 * further up in the hierarchy. The Stack may contain different types, depending on
41 * the types {@code T} of {@link IndexDirectory IndexDirectories} further up in the
42 * hierarchy.
43 */
44 Set<T> getIndex(ImmutableStack<Object> indices);
45
46 /**
47 * Returns the function used to format elements of the index (e.g. for writing to disk).
48 */
49 Formatter<T> getIndexFormatter();
50 }
51
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/directory/IndexDirectory.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/directory/IndexDirectoryImpl.java]
1 package app.coronawarn.server.services.distribution.structure.directory;
2
3 import app.coronawarn.server.services.distribution.structure.file.File;
4 import app.coronawarn.server.services.distribution.structure.functional.DirectoryFunction;
5 import app.coronawarn.server.services.distribution.structure.functional.FileFunction;
6 import app.coronawarn.server.services.distribution.structure.functional.Formatter;
7 import app.coronawarn.server.services.distribution.structure.functional.IndexFunction;
8 import app.coronawarn.server.services.distribution.structure.util.ImmutableStack;
9 import java.util.HashSet;
10 import java.util.Set;
11 import java.util.Stack;
12
13 public class IndexDirectoryImpl<T> extends DirectoryImpl implements IndexDirectory<T> {
14
15 // Files to be written into every directory created through the index
16 private final Set<FileFunction> metaFiles = new HashSet<>();
17 // Directories to be written into every directory created through the index
18 private final Set<DirectoryFunction> metaDirectories = new HashSet<>();
19 private final IndexFunction<T> indexFunction;
20 private final Formatter<T> indexFormatter;
21
22 /**
23 * Constructor.
24 *
25 * @param name The name that this directory should have on disk.
26 * @param indexFunction An {@link IndexFunction} that calculates the index of this {@link
27 * IndexDirectoryImpl} from a {@link java.util.Stack} of parent {@link
28 * IndexDirectoryImpl} indices. The top element of the stack is from the
29 * closest {@link IndexDirectoryImpl} in the parent chain.
30 * @param indexFormatter A {@link Formatter} used to format the directory name for each index
31 * element returned by the {@link IndexDirectoryImpl#indexFunction}.
32 */
33 public IndexDirectoryImpl(String name, IndexFunction<T> indexFunction,
34 Formatter<T> indexFormatter) {
35 super(name);
36 this.indexFunction = indexFunction;
37 this.indexFormatter = indexFormatter;
38 }
39
40 @Override
41 public Formatter<T> getIndexFormatter() {
42 return this.indexFormatter;
43 }
44
45 @Override
46 public Set<T> getIndex(ImmutableStack<Object> indices) {
47 return this.indexFunction.apply(indices);
48 }
49
50 @Override
51 public void addFileToAll(FileFunction fileFunction) {
52 this.metaFiles.add(fileFunction);
53 }
54
55 @Override
56 public void addDirectoryToAll(DirectoryFunction directoryFunction) {
57 this.metaDirectories.add(directoryFunction);
58 }
59
60 /**
61 * Creates a new subdirectory for every element of the {@link IndexDirectory#getIndex index} and
62 * writes {@link IndexDirectory#addFileToAll files} and {@link IndexDirectory#addDirectory
63 * directories} to those. The respective element of the index will be pushed onto the Stack for
64 * subsequent {@link app.coronawarn.server.services.distribution.structure.Writable#prepare} calls
65 * on those files and directories.
66 *
67 * @param indices A {@link Stack} of parameters from all {@link IndexDirectory IndexDirectories}
68 * further up in the hierarchy. The Stack may contain different types, depending on
69 * the types {@code T} of {@link IndexDirectory IndexDirectories} further up in the
70 * hierarchy.
71 */
72 @Override
73 public void prepare(ImmutableStack<Object> indices) {
74 super.prepare(indices);
75 this.prepareIndex(indices);
76 }
77
78 private void prepareIndex(ImmutableStack<Object> indices) {
79 this.getIndex(indices).forEach(currentIndex -> {
80 ImmutableStack<Object> newIndices = indices.push(currentIndex);
81 Directory subDirectory = makeSubDirectory(currentIndex);
82 prepareMetaFiles(newIndices, subDirectory);
83 prepareMetaDirectories(newIndices, subDirectory);
84 });
85 }
86
87 private Directory makeSubDirectory(T index) {
88 Directory subDirectory = new DirectoryImpl(this.indexFormatter.apply(index).toString());
89 this.addDirectory(subDirectory);
90 return subDirectory;
91 }
92
93 private void prepareMetaFiles(ImmutableStack<Object> indices, Directory target) {
94 this.metaFiles.forEach(metaFileFunction -> {
95 File newFile = metaFileFunction.apply(indices);
96 target.addFile(newFile);
97 newFile.prepare(indices);
98 });
99 }
100
101 private void prepareMetaDirectories(ImmutableStack<Object> indices, Directory target) {
102 this.metaDirectories.forEach(metaDirectoryFunction -> {
103 Directory newDirectory = metaDirectoryFunction.apply(indices);
104 target.addDirectory(newDirectory);
105 newDirectory.prepare(indices);
106 });
107 }
108 }
109
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/directory/IndexDirectoryImpl.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/directory/decorator/DirectoryDecorator.java]
1 package app.coronawarn.server.services.distribution.structure.directory.decorator;
2
3 import app.coronawarn.server.services.distribution.structure.Writable;
4 import app.coronawarn.server.services.distribution.structure.directory.Directory;
5 import app.coronawarn.server.services.distribution.structure.file.File;
6 import app.coronawarn.server.services.distribution.structure.util.ImmutableStack;
7 import java.util.Set;
8
9 /**
10 * Decorates a {@link Directory} (e.g. to modify its files, subdirectories, etc.) on {@link
11 * Writable#prepare}. This class proxies all function calls to the {@link Directory} it contains.
12 */
13 public abstract class DirectoryDecorator implements Directory {
14
15 private final Directory directory;
16
17 protected DirectoryDecorator(Directory directory) {
18 this.directory = directory;
19 }
20
21 @Override
22 public void prepare(ImmutableStack<Object> indices) {
23 this.directory.prepare(indices);
24 }
25
26 @Override
27 public void addFile(File file) {
28 this.directory.addFile(file);
29 }
30
31 @Override
32 public Set<File> getFiles() {
33 return this.directory.getFiles();
34 }
35
36 @Override
37 public void addDirectory(Directory directory) {
38 this.directory.addDirectory(directory);
39 }
40
41 @Override
42 public Set<Directory> getDirectories() {
43 return this.directory.getDirectories();
44 }
45
46 @Override
47 public void write() {
48 this.directory.write();
49 }
50
51 @Override
52 public String getName() {
53 return this.directory.getName();
54 }
55
56 @Override
57 public Directory getParent() {
58 return this.directory.getParent();
59 }
60
61 @Override
62 public void setParent(Directory parent) {
63 this.directory.setParent(parent);
64 }
65
66 @Override
67 public java.io.File getFileOnDisk() {
68 return this.directory.getFileOnDisk();
69 }
70 }
71
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/directory/decorator/DirectoryDecorator.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/directory/decorator/IndexingDecorator.java]
1 package app.coronawarn.server.services.distribution.structure.directory.decorator;
2
3 import app.coronawarn.server.services.distribution.structure.directory.IndexDirectory;
4 import app.coronawarn.server.services.distribution.structure.directory.IndexDirectoryImpl;
5 import app.coronawarn.server.services.distribution.structure.file.FileImpl;
6 import app.coronawarn.server.services.distribution.structure.util.ImmutableStack;
7 import java.util.List;
8 import java.util.Set;
9 import java.util.stream.Collectors;
10 import org.json.simple.JSONArray;
11 import org.slf4j.Logger;
12 import org.slf4j.LoggerFactory;
13
14 /**
15 * A {@link DirectoryDecorator} that writes a file called {@code "index"}, containing a JSON array
16 * containing all elements returned {@link IndexDirectoryImpl#getIndex}, formatted with the {@link
17 * IndexDirectoryImpl#getIndexFormatter} on {@link app.coronawarn.server.services.distribution.structure.Writable#prepare}.
18 */
19 public class IndexingDecorator<T> extends DirectoryDecorator {
20
21 private static final String INDEX_FILE_NAME = "index";
22
23 private static final Logger logger = LoggerFactory.getLogger(IndexingDecorator.class);
24 final IndexDirectory<T> directory;
25
26 public IndexingDecorator(IndexDirectory<T> directory) {
27 super(directory);
28 this.directory = directory;
29 }
30
31 /**
32 * See {@link IndexingDecorator} class documentation.
33 */
34 @Override
35 public void prepare(ImmutableStack<Object> indices) {
36 logger.debug("Indexing {}", this.getFileOnDisk().getPath());
37 Set<T> index = this.directory.getIndex(indices);
38 JSONArray array = new JSONArray();
39 List<?> elements = index.stream()
40 .map(this.directory.getIndexFormatter())
41 .collect(Collectors.toList());
42 array.addAll(elements);
43 this.addFile(new FileImpl(INDEX_FILE_NAME, array.toJSONString().getBytes()));
44 super.prepare(indices);
45 }
46 }
47
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/directory/decorator/IndexingDecorator.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/file/File.java]
1 package app.coronawarn.server.services.distribution.structure.file;
2
3 import app.coronawarn.server.services.distribution.structure.Writable;
4
5 /**
6 * A {@link Writable} containing some bytes.
7 */
8 public interface File extends Writable {
9
10 /**
11 * Returns the bytes contained by this {@link File}.
12 */
13 byte[] getBytes();
14
15 /**
16 * Sets the bytes to be contained by this {@link File}.
17 */
18 void setBytes(byte[] bytes);
19 }
20
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/file/File.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/file/FileImpl.java]
1 package app.coronawarn.server.services.distribution.structure.file;
2
3 import app.coronawarn.server.services.distribution.io.IO;
4 import app.coronawarn.server.services.distribution.structure.Writable;
5 import app.coronawarn.server.services.distribution.structure.WritableImpl;
6 import app.coronawarn.server.services.distribution.structure.util.ImmutableStack;
7
8 /**
9 * Implementation of {@link File} that interfaces with {@link java.io.File Files} on disk.
10 */
11 public class FileImpl extends WritableImpl implements File {
12
13 private byte[] bytes;
14
15 public FileImpl(String name, byte[] bytes) {
16 super(name);
17 this.bytes = bytes;
18 }
19
20 /**
21 * Creates a {@link java.io.File} with name {@link Writable#getName} on disk and writes the {@link
22 * File#getBytes bytes} of this {@link File} into the {@link java.io.File} to disk.
23 */
24 @Override
25 public void write() {
26 IO.makeFile(this.getParent().getFileOnDisk(), this.getName());
27 IO.writeBytesToFile(this.getBytes(), this.getFileOnDisk());
28 }
29
30 @Override
31 public byte[] getBytes() {
32 return this.bytes;
33 }
34
35 @Override
36 public void setBytes(byte[] bytes) {
37 this.bytes = bytes;
38 }
39
40 /**
41 * Does nothing.
42 */
43 @Override
44 public void prepare(ImmutableStack<Object> indices) {
45 }
46 }
47
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/file/FileImpl.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/file/decorator/FileDecorator.java]
1 package app.coronawarn.server.services.distribution.structure.file.decorator;
2
3 import app.coronawarn.server.services.distribution.structure.Writable;
4 import app.coronawarn.server.services.distribution.structure.directory.Directory;
5 import app.coronawarn.server.services.distribution.structure.file.File;
6 import app.coronawarn.server.services.distribution.structure.util.ImmutableStack;
7
8 /**
9 * Decorates a {@link File} (e.g. to modify its content) on {@link Writable#prepare}. This class
10 * proxies all function calls to the {@link File} it contains.
11 */
12 public abstract class FileDecorator implements File {
13
14 private final File file;
15
16 protected FileDecorator(File file) {
17 this.file = file;
18 }
19
20 @Override
21 public void prepare(ImmutableStack<Object> indices) {
22 this.file.prepare(indices);
23 }
24
25 @Override
26 public byte[] getBytes() {
27 return this.file.getBytes();
28 }
29
30 @Override
31 public void setBytes(byte[] bytes) {
32 this.file.setBytes(bytes);
33 }
34
35 @Override
36 public void write() {
37 this.file.write();
38 }
39
40 @Override
41 public String getName() {
42 return this.file.getName();
43 }
44
45 @Override
46 public Directory getParent() {
47 return this.file.getParent();
48 }
49
50 @Override
51 public void setParent(Directory parent) {
52 this.file.setParent(parent);
53 }
54
55 @Override
56 public java.io.File getFileOnDisk() {
57 return this.file.getFileOnDisk();
58 }
59 }
60
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/file/decorator/FileDecorator.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/file/decorator/SigningDecorator.java]
1 package app.coronawarn.server.services.distribution.structure.file.decorator;
2
3 import app.coronawarn.server.common.protocols.internal.SignedPayload;
4 import app.coronawarn.server.services.distribution.crypto.CryptoProvider;
5 import app.coronawarn.server.services.distribution.structure.file.File;
6 import app.coronawarn.server.services.distribution.structure.util.ImmutableStack;
7 import com.google.protobuf.ByteString;
8 import java.security.GeneralSecurityException;
9 import java.security.PrivateKey;
10 import java.security.Signature;
11 import java.security.cert.Certificate;
12 import org.slf4j.Logger;
13 import org.slf4j.LoggerFactory;
14
15 /**
16 * A {@link FileDecorator} that will convert the contents of its {@link File} into a {@link
17 * app.coronawarn.server.common.protocols.internal.SignedPayload}.
18 */
19 public class SigningDecorator extends FileDecorator {
20
21 private static final String SIGNATURE_ALGORITHM = "Ed25519";
22 private static final String SECURITY_PROVIDER = "BC";
23
24 private static final Logger logger = LoggerFactory.getLogger(SigningDecorator.class);
25 private final CryptoProvider cryptoProvider;
26
27 public SigningDecorator(File file, CryptoProvider cryptoProvider) {
28 super(file);
29 this.cryptoProvider = cryptoProvider;
30 }
31
32 /**
33 * See {@link SigningDecorator} class documentation.
34 */
35 @Override
36 public void prepare(ImmutableStack<Object> indices) {
37 super.prepare(indices);
38 logger.debug("Signing {}", this.getFileOnDisk().getPath());
39 SignedPayload signedPayload = sign(this.getBytes(), cryptoProvider.getPrivateKey(),
40 cryptoProvider.getCertificate());
41 this.setBytes(signedPayload.toByteArray());
42 }
43
44 private static SignedPayload sign(byte[] payload, PrivateKey privateKey,
45 Certificate certificate) {
46 try {
47 Signature payloadSignature = Signature.getInstance(SIGNATURE_ALGORITHM, SECURITY_PROVIDER);
48 payloadSignature.initSign(privateKey);
49 payloadSignature.update(payload);
50 return SignedPayload.newBuilder()
51 .setCertificateChain(ByteString.copyFrom(certificate.getEncoded()))
52 .setSignature(ByteString.copyFrom(payloadSignature.sign()))
53 .setPayload(ByteString.copyFrom(payload))
54 .build();
55 } catch (GeneralSecurityException e) {
56 logger.error("Exception during payload signing.", e);
57 throw new RuntimeException(e);
58 }
59 }
60 }
61
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/file/decorator/SigningDecorator.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/functional/CheckedFunction.java]
1 package app.coronawarn.server.services.distribution.structure.functional;
2
3 import java.util.function.Function;
4
5 /**
6 * Convert checked exceptions to unchecked exceptions in Functions.
7 */
8 @FunctionalInterface
9 public interface CheckedFunction<T, R, E extends Exception> {
10
11 R apply(T t) throws E;
12
13 static <T, R> Function<T, R> uncheckedFunction(
14 CheckedFunction<T, R, ? extends Exception> function) {
15 return input -> {
16 try {
17 return function.apply(input);
18 } catch (Exception e) {
19 throw new RuntimeException(e);
20 }
21 };
22 }
23 }
24
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/functional/CheckedFunction.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/functional/DirectoryFunction.java]
1 package app.coronawarn.server.services.distribution.structure.functional;
2
3 import app.coronawarn.server.services.distribution.structure.directory.Directory;
4 import app.coronawarn.server.services.distribution.structure.util.ImmutableStack;
5 import java.util.function.Function;
6
7 /**
8 * A {@code Function<Stack<Object>, Directory>}.
9 */
10 @FunctionalInterface
11 public interface DirectoryFunction extends Function<ImmutableStack<Object>, Directory> {
12
13 Directory apply(ImmutableStack<Object> t);
14 }
15
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/functional/DirectoryFunction.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/functional/FileFunction.java]
1 package app.coronawarn.server.services.distribution.structure.functional;
2
3 import app.coronawarn.server.services.distribution.structure.file.File;
4 import app.coronawarn.server.services.distribution.structure.util.ImmutableStack;
5 import java.util.function.Function;
6
7 /**
8 * A {@code Function<Stack<Object>, File>}.
9 */
10 @FunctionalInterface
11 public interface FileFunction extends Function<ImmutableStack<Object>, File> {
12
13 File apply(ImmutableStack<Object> t);
14 }
15
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/functional/FileFunction.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/functional/Formatter.java]
1 package app.coronawarn.server.services.distribution.structure.functional;
2
3 import java.util.function.Function;
4
5 /**
6 * A {@code Function<T, Object>}.
7 *
8 * @param <T> The type of the elements to format.
9 */
10 @FunctionalInterface
11 public interface Formatter<T> extends Function<T, Object> {
12
13 Object apply(T t);
14 }
15
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/functional/Formatter.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/functional/IndexFunction.java]
1 package app.coronawarn.server.services.distribution.structure.functional;
2
3 import app.coronawarn.server.services.distribution.structure.util.ImmutableStack;
4 import java.util.Set;
5 import java.util.function.Function;
6
7 /**
8 * A {@code Function<Stack<Object>, List<T>>}.
9 *
10 * @param <T> The type of the index elements.
11 */
12 @FunctionalInterface
13 public interface IndexFunction<T> extends Function<ImmutableStack<Object>, Set<T>> {
14
15 Set<T> apply(ImmutableStack<Object> t);
16 }
17
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/functional/IndexFunction.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/util/ImmutableStack.java]
1 package app.coronawarn.server.services.distribution.structure.util;
2
3 import java.util.Stack;
4
5 public class ImmutableStack<T> {
6
7 private Stack<T> stack;
8
9 public ImmutableStack() {
10 this.stack = new Stack<>();
11 }
12
13 public ImmutableStack(ImmutableStack<T> other) {
14 this.stack = (Stack<T>)other.stack.clone();
15 }
16
17 public ImmutableStack<T> push(T item) {
18 ImmutableStack<T> clone = new ImmutableStack<>(this);
19 clone.stack.push(item);
20 return clone;
21 }
22
23 public ImmutableStack<T> pop() {
24 ImmutableStack<T> clone = new ImmutableStack<>(this);
25 clone.stack.pop();
26 return clone;
27 }
28
29 public T peek() {
30 return this.stack.peek();
31 }
32 }
33
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/util/ImmutableStack.java]
[start of services/distribution/src/main/resources/application.properties]
1 logging.level.org.springframework.web=INFO
2 logging.level.app.coronawarn=INFO
3 spring.main.web-application-type=NONE
4
5 app.coronawarn.server.services.distribution.retention_days=14
6 app.coronawarn.server.services.distribution.version=v1
7 app.coronawarn.server.services.distribution.paths.output=out
8 app.coronawarn.server.services.distribution.paths.privatekey=classpath:certificates/client/private.pem
9 app.coronawarn.server.services.distribution.paths.certificate=classpath:certificates/chain/certificate.crt
10
11 spring.flyway.enabled=false
12 spring.jpa.hibernate.ddl-auto=validate
13
[end of services/distribution/src/main/resources/application.properties]
</code>
Here is an example of a patch file. It consists of changes to the code base. It specifies the file names, the line numbers of each change, and the removed and added lines. A single patch file can contain changes to multiple files.
<patch>
--- a/file.py
+++ b/file.py
@@ -1,27 +1,35 @@
def euclidean(a, b):
- while b:
- a, b = b, a % b
- return a
+ if b == 0:
+ return a
+ return euclidean(b, a % b)
def bresenham(x0, y0, x1, y1):
points = []
dx = abs(x1 - x0)
dy = abs(y1 - y0)
- sx = 1 if x0 < x1 else -1
- sy = 1 if y0 < y1 else -1
- err = dx - dy
+ x, y = x0, y0
+ sx = -1 if x0 > x1 else 1
+ sy = -1 if y0 > y1 else 1
- while True:
- points.append((x0, y0))
- if x0 == x1 and y0 == y1:
- break
- e2 = 2 * err
- if e2 > -dy:
+ if dx > dy:
+ err = dx / 2.0
+ while x != x1:
+ points.append((x, y))
err -= dy
- x0 += sx
- if e2 < dx:
- err += dx
- y0 += sy
+ if err < 0:
+ y += sy
+ err += dx
+ x += sx
+ else:
+ err = dy / 2.0
+ while y != y1:
+ points.append((x, y))
+ err -= dx
+ if err < 0:
+ x += sx
+ err += dy
+ y += sy
+ points.append((x, y))
return points
</patch>
I need you to solve the provded issue by generating a single patch file that I can apply directly to this repository using git apply. Please respond with a single patch file in the format shown above.
Respond below:
| corona-warn-app/cwa-server | ac44b28ad79130bd39e2d002cddf3a67799a80fb | DiagnosisKeyDistributionRunner deletes exposure configuration
``DiagnosisKeyDistributionRunner`` deletes the files written by ``ExposureConfigurationDistributionRunner`` before they are published.
| 2020-05-15T14:41:59 | <patch>
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/crypto/CryptoProvider.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/component/CryptoProvider.java
similarity index 89%
rename from services/distribution/src/main/java/app/coronawarn/server/services/distribution/crypto/CryptoProvider.java
rename to services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/component/CryptoProvider.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/crypto/CryptoProvider.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/component/CryptoProvider.java
@@ -1,4 +1,4 @@
-package app.coronawarn.server.services.distribution.crypto;
+package app.coronawarn.server.services.distribution.assembly.component;
import java.io.ByteArrayInputStream;
import java.io.IOException;
@@ -22,7 +22,7 @@
import org.springframework.stereotype.Component;
/**
- * Wrapper class for a {@link CryptoProvider#getPrivateKey() private key} and a {@link
+ * Wrapper component for a {@link CryptoProvider#getPrivateKey() private key} and a {@link
* CryptoProvider#getCertificate()} certificate} from the application properties.
*/
@Component
@@ -30,10 +30,10 @@ public class CryptoProvider {
private static final Logger logger = LoggerFactory.getLogger(CryptoProvider.class);
- @Value("${app.coronawarn.server.services.distribution.paths.privatekey}")
+ @Value("${services.distribution.paths.privatekey}")
private String privateKeyPath;
- @Value("${app.coronawarn.server.services.distribution.paths.certificate}")
+ @Value("${services.distribution.paths.certificate}")
private String certificatePath;
@Autowired
@@ -72,10 +72,10 @@ private static Certificate getCertificateFromBytes(final byte[] bytes)
* Reads and returns the {@link PrivateKey} configured in the application properties.
*/
public PrivateKey getPrivateKey() {
- if (this.privateKey == null) {
+ if (privateKey == null) {
Resource privateKeyResource = resourceLoader.getResource(privateKeyPath);
try (InputStream privateKeyStream = privateKeyResource.getInputStream()) {
- this.privateKey = getPrivateKeyFromStream(privateKeyStream);
+ privateKey = getPrivateKeyFromStream(privateKeyStream);
} catch (IOException e) {
logger.error("Failed to load private key from {}", privateKeyPath, e);
throw new RuntimeException(e);
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/component/CwaApiStructureProvider.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/component/CwaApiStructureProvider.java
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/component/CwaApiStructureProvider.java
@@ -0,0 +1,35 @@
+package app.coronawarn.server.services.distribution.assembly.component;
+
+import app.coronawarn.server.services.distribution.assembly.structure.directory.Directory;
+import app.coronawarn.server.services.distribution.assembly.structure.directory.IndexDirectory;
+import app.coronawarn.server.services.distribution.assembly.structure.directory.IndexDirectoryImpl;
+import app.coronawarn.server.services.distribution.assembly.structure.directory.decorator.IndexingDecorator;
+import java.util.Set;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+/**
+ * Assembles the content underneath the {@code /version} path of the CWA API.
+ */
+@Component
+public class CwaApiStructureProvider {
+
+ private final String VERSION_DIRECTORY = "version";
+ private final String VERSION_V1 = "v1";
+
+ @Autowired
+ private ExposureConfigurationStructureProvider exposureConfigurationStructureProvider;
+
+ @Autowired
+ private DiagnosisKeysStructureProvider diagnosisKeysStructureProvider;
+
+ public Directory getDirectory() {
+ IndexDirectory<?> versionDirectory =
+ new IndexDirectoryImpl<>(VERSION_DIRECTORY, __ -> Set.of(VERSION_V1), Object::toString);
+
+ versionDirectory.addDirectoryToAll(__ -> exposureConfigurationStructureProvider.getExposureConfiguration());
+ versionDirectory.addDirectoryToAll(__ -> diagnosisKeysStructureProvider.getDiagnosisKeys());
+
+ return new IndexingDecorator<>(versionDirectory);
+ }
+}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/component/DiagnosisKeysStructureProvider.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/component/DiagnosisKeysStructureProvider.java
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/component/DiagnosisKeysStructureProvider.java
@@ -0,0 +1,37 @@
+package app.coronawarn.server.services.distribution.assembly.component;
+
+import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
+import app.coronawarn.server.common.persistence.service.DiagnosisKeyService;
+import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.directory.DiagnosisKeysDirectoryImpl;
+import app.coronawarn.server.services.distribution.assembly.structure.directory.Directory;
+import java.util.Collection;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+/**
+ * Retrieves stored diagnosis keys and builds a {@link DiagnosisKeysDirectoryImpl} with them.
+ */
+@Component
+public class DiagnosisKeysStructureProvider {
+
+ private static final Logger logger = LoggerFactory.getLogger(DiagnosisKeysStructureProvider.class);
+
+ @Autowired
+ private DiagnosisKeyService diagnosisKeyService;
+
+ @Autowired
+ private CryptoProvider cryptoProvider;
+
+ public Directory getDiagnosisKeys() {
+ Collection<DiagnosisKey> diagnosisKeys = readDiagnosisKeys();
+ return new DiagnosisKeysDirectoryImpl(diagnosisKeys, cryptoProvider);
+ }
+
+ private Collection<DiagnosisKey> readDiagnosisKeys() {
+ logger.debug("Querying diagnosis keys from the database...");
+ return diagnosisKeyService.getDiagnosisKeys();
+ }
+
+}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/component/ExposureConfigurationStructureProvider.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/component/ExposureConfigurationStructureProvider.java
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/component/ExposureConfigurationStructureProvider.java
@@ -0,0 +1,40 @@
+package app.coronawarn.server.services.distribution.assembly.component;
+
+import app.coronawarn.server.common.protocols.internal.RiskScoreParameters;
+import app.coronawarn.server.services.distribution.assembly.exposureconfig.ExposureConfigurationProvider;
+import app.coronawarn.server.services.distribution.assembly.exposureconfig.UnableToLoadFileException;
+import app.coronawarn.server.services.distribution.assembly.exposureconfig.structure.directory.ExposureConfigurationDirectoryImpl;
+import app.coronawarn.server.services.distribution.assembly.structure.directory.Directory;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+/**
+ * Reads the exposure configuration parameters from the respective file in the class path and builds
+ * a {@link ExposureConfigurationDirectoryImpl} with them.
+ */
+@Component
+public class ExposureConfigurationStructureProvider {
+
+ private static final Logger logger = LoggerFactory
+ .getLogger(ExposureConfigurationStructureProvider.class);
+
+ @Autowired
+ private CryptoProvider cryptoProvider;
+
+ public Directory getExposureConfiguration() {
+ var riskScoreParameters = readExposureConfiguration();
+ return new ExposureConfigurationDirectoryImpl(riskScoreParameters, cryptoProvider);
+ }
+
+ private RiskScoreParameters readExposureConfiguration() {
+ logger.debug("Reading exposure configuration...");
+ try {
+ return ExposureConfigurationProvider.readMasterFile();
+ } catch (UnableToLoadFileException e) {
+ logger.error("Could not load exposure configuration parameters", e);
+ throw new RuntimeException(e);
+ }
+ }
+}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/component/OutputDirectoryProvider.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/component/OutputDirectoryProvider.java
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/component/OutputDirectoryProvider.java
@@ -0,0 +1,37 @@
+package app.coronawarn.server.services.distribution.assembly.component;
+
+import app.coronawarn.server.services.distribution.assembly.structure.directory.Directory;
+import app.coronawarn.server.services.distribution.assembly.structure.directory.DirectoryImpl;
+import java.io.IOException;
+import org.apache.commons.io.FileUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.stereotype.Component;
+
+/**
+ * Creates and clears a {@link Directory} on disk, which is defined by the application properties.
+ */
+@Component
+public class OutputDirectoryProvider {
+
+ private static final Logger logger = LoggerFactory.getLogger(OutputDirectoryProvider.class);
+
+ @Value("${services.distribution.paths.output}")
+ private String outputPath;
+
+ public Directory getDirectory() {
+ return new DirectoryImpl(getFileOnDisk());
+ }
+
+ public java.io.File getFileOnDisk() {
+ return new java.io.File(outputPath);
+ }
+
+ public void clear() throws IOException {
+ logger.debug("Clearing output directory...");
+ java.io.File outputDirectory = getFileOnDisk();
+ FileUtils.deleteDirectory(outputDirectory);
+ outputDirectory.mkdirs();
+ }
+}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/diagnosiskeys/structure/directory/DiagnosisKeysCountryDirectoryImpl.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysCountryDirectoryImpl.java
similarity index 55%
rename from services/distribution/src/main/java/app/coronawarn/server/services/distribution/diagnosiskeys/structure/directory/DiagnosisKeysCountryDirectoryImpl.java
rename to services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysCountryDirectoryImpl.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/diagnosiskeys/structure/directory/DiagnosisKeysCountryDirectoryImpl.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysCountryDirectoryImpl.java
@@ -1,13 +1,13 @@
-package app.coronawarn.server.services.distribution.diagnosiskeys.structure.directory;
+package app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.directory;
import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
-import app.coronawarn.server.services.distribution.crypto.CryptoProvider;
-import app.coronawarn.server.services.distribution.diagnosiskeys.structure.directory.decorator.DateAggregatingDecorator;
-import app.coronawarn.server.services.distribution.structure.directory.Directory;
-import app.coronawarn.server.services.distribution.structure.directory.IndexDirectory;
-import app.coronawarn.server.services.distribution.structure.directory.IndexDirectoryImpl;
-import app.coronawarn.server.services.distribution.structure.directory.decorator.IndexingDecorator;
-import app.coronawarn.server.services.distribution.structure.util.ImmutableStack;
+import app.coronawarn.server.services.distribution.assembly.component.CryptoProvider;
+import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.directory.decorator.DateAggregatingDecorator;
+import app.coronawarn.server.services.distribution.assembly.structure.directory.Directory;
+import app.coronawarn.server.services.distribution.assembly.structure.directory.IndexDirectory;
+import app.coronawarn.server.services.distribution.assembly.structure.directory.IndexDirectoryImpl;
+import app.coronawarn.server.services.distribution.assembly.structure.directory.decorator.IndexingDecorator;
+import app.coronawarn.server.services.distribution.assembly.structure.util.ImmutableStack;
import java.time.LocalDate;
import java.util.Collection;
import java.util.Set;
@@ -17,8 +17,8 @@ public class DiagnosisKeysCountryDirectoryImpl extends IndexDirectoryImpl<String
private static final String COUNTRY_DIRECTORY = "country";
private static final String COUNTRY = "DE";
- private Collection<DiagnosisKey> diagnosisKeys;
- private CryptoProvider cryptoProvider;
+ private final Collection<DiagnosisKey> diagnosisKeys;
+ private final CryptoProvider cryptoProvider;
public DiagnosisKeysCountryDirectoryImpl(Collection<DiagnosisKey> diagnosisKeys,
CryptoProvider cryptoProvider) {
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/diagnosiskeys/structure/directory/DiagnosisKeysDateDirectoryImpl.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysDateDirectoryImpl.java
similarity index 59%
rename from services/distribution/src/main/java/app/coronawarn/server/services/distribution/diagnosiskeys/structure/directory/DiagnosisKeysDateDirectoryImpl.java
rename to services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysDateDirectoryImpl.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/diagnosiskeys/structure/directory/DiagnosisKeysDateDirectoryImpl.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysDateDirectoryImpl.java
@@ -1,13 +1,13 @@
-package app.coronawarn.server.services.distribution.diagnosiskeys.structure.directory;
+package app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.directory;
import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
-import app.coronawarn.server.services.distribution.crypto.CryptoProvider;
-import app.coronawarn.server.services.distribution.diagnosiskeys.util.DateTime;
-import app.coronawarn.server.services.distribution.structure.directory.Directory;
-import app.coronawarn.server.services.distribution.structure.directory.IndexDirectory;
-import app.coronawarn.server.services.distribution.structure.directory.IndexDirectoryImpl;
-import app.coronawarn.server.services.distribution.structure.directory.decorator.IndexingDecorator;
-import app.coronawarn.server.services.distribution.structure.util.ImmutableStack;
+import app.coronawarn.server.services.distribution.assembly.component.CryptoProvider;
+import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.util.DateTime;
+import app.coronawarn.server.services.distribution.assembly.structure.directory.Directory;
+import app.coronawarn.server.services.distribution.assembly.structure.directory.IndexDirectory;
+import app.coronawarn.server.services.distribution.assembly.structure.directory.IndexDirectoryImpl;
+import app.coronawarn.server.services.distribution.assembly.structure.directory.decorator.IndexingDecorator;
+import app.coronawarn.server.services.distribution.assembly.structure.util.ImmutableStack;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
@@ -18,14 +18,14 @@ public class DiagnosisKeysDateDirectoryImpl extends IndexDirectoryImpl<LocalDate
private static final String DATE_DIRECTORY = "date";
private static final DateTimeFormatter ISO8601 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
- private Collection<DiagnosisKey> diagnosisKeys;
- private CryptoProvider cryptoProvider;
+ private final Collection<DiagnosisKey> diagnosisKeys;
+ private final CryptoProvider cryptoProvider;
public DiagnosisKeysDateDirectoryImpl(Collection<DiagnosisKey> diagnosisKeys,
CryptoProvider cryptoProvider) {
super(DATE_DIRECTORY, __ -> DateTime.getDates(diagnosisKeys), ISO8601::format);
- this.diagnosisKeys = diagnosisKeys;
this.cryptoProvider = cryptoProvider;
+ this.diagnosisKeys = diagnosisKeys;
}
@Override
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/diagnosiskeys/structure/directory/DiagnosisKeysDirectoryImpl.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysDirectoryImpl.java
similarity index 69%
rename from services/distribution/src/main/java/app/coronawarn/server/services/distribution/diagnosiskeys/structure/directory/DiagnosisKeysDirectoryImpl.java
rename to services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysDirectoryImpl.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/diagnosiskeys/structure/directory/DiagnosisKeysDirectoryImpl.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysDirectoryImpl.java
@@ -1,12 +1,12 @@
-package app.coronawarn.server.services.distribution.diagnosiskeys.structure.directory;
+package app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.directory;
import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
-import app.coronawarn.server.services.distribution.crypto.CryptoProvider;
-import app.coronawarn.server.services.distribution.structure.directory.Directory;
-import app.coronawarn.server.services.distribution.structure.directory.DirectoryImpl;
-import app.coronawarn.server.services.distribution.structure.directory.IndexDirectory;
-import app.coronawarn.server.services.distribution.structure.directory.decorator.IndexingDecorator;
-import app.coronawarn.server.services.distribution.structure.util.ImmutableStack;
+import app.coronawarn.server.services.distribution.assembly.component.CryptoProvider;
+import app.coronawarn.server.services.distribution.assembly.structure.directory.Directory;
+import app.coronawarn.server.services.distribution.assembly.structure.directory.DirectoryImpl;
+import app.coronawarn.server.services.distribution.assembly.structure.directory.IndexDirectory;
+import app.coronawarn.server.services.distribution.assembly.structure.directory.decorator.IndexingDecorator;
+import app.coronawarn.server.services.distribution.assembly.structure.util.ImmutableStack;
import java.util.Collection;
/**
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/diagnosiskeys/structure/directory/DiagnosisKeysHourDirectoryImpl.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysHourDirectoryImpl.java
similarity index 61%
rename from services/distribution/src/main/java/app/coronawarn/server/services/distribution/diagnosiskeys/structure/directory/DiagnosisKeysHourDirectoryImpl.java
rename to services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysHourDirectoryImpl.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/diagnosiskeys/structure/directory/DiagnosisKeysHourDirectoryImpl.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysHourDirectoryImpl.java
@@ -1,13 +1,13 @@
-package app.coronawarn.server.services.distribution.diagnosiskeys.structure.directory;
+package app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.directory;
import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
-import app.coronawarn.server.services.distribution.crypto.CryptoProvider;
-import app.coronawarn.server.services.distribution.diagnosiskeys.structure.file.HourFileImpl;
-import app.coronawarn.server.services.distribution.diagnosiskeys.util.DateTime;
-import app.coronawarn.server.services.distribution.structure.directory.IndexDirectoryImpl;
-import app.coronawarn.server.services.distribution.structure.file.File;
-import app.coronawarn.server.services.distribution.structure.file.decorator.SigningDecorator;
-import app.coronawarn.server.services.distribution.structure.util.ImmutableStack;
+import app.coronawarn.server.services.distribution.assembly.component.CryptoProvider;
+import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.file.HourFileImpl;
+import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.util.DateTime;
+import app.coronawarn.server.services.distribution.assembly.structure.directory.IndexDirectoryImpl;
+import app.coronawarn.server.services.distribution.assembly.structure.file.File;
+import app.coronawarn.server.services.distribution.assembly.structure.file.decorator.SigningDecorator;
+import app.coronawarn.server.services.distribution.assembly.structure.util.ImmutableStack;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Collection;
@@ -16,9 +16,9 @@ public class DiagnosisKeysHourDirectoryImpl extends IndexDirectoryImpl<LocalDate
private static final String HOUR_DIRECTORY = "hour";
- private Collection<DiagnosisKey> diagnosisKeys;
- private LocalDate currentDate;
- private CryptoProvider cryptoProvider;
+ private final Collection<DiagnosisKey> diagnosisKeys;
+ private final LocalDate currentDate;
+ private final CryptoProvider cryptoProvider;
public DiagnosisKeysHourDirectoryImpl(Collection<DiagnosisKey> diagnosisKeys,
LocalDate currentDate, CryptoProvider cryptoProvider) {
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/diagnosiskeys/structure/directory/decorator/DateAggregatingDecorator.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/decorator/DateAggregatingDecorator.java
similarity index 77%
rename from services/distribution/src/main/java/app/coronawarn/server/services/distribution/diagnosiskeys/structure/directory/decorator/DateAggregatingDecorator.java
rename to services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/decorator/DateAggregatingDecorator.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/diagnosiskeys/structure/directory/decorator/DateAggregatingDecorator.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/decorator/DateAggregatingDecorator.java
@@ -1,16 +1,16 @@
-package app.coronawarn.server.services.distribution.diagnosiskeys.structure.directory.decorator;
+package app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.directory.decorator;
import app.coronawarn.server.common.protocols.internal.FileBucket;
import app.coronawarn.server.common.protocols.internal.SignedPayload;
-import app.coronawarn.server.services.distribution.crypto.CryptoProvider;
-import app.coronawarn.server.services.distribution.structure.Writable;
-import app.coronawarn.server.services.distribution.structure.directory.Directory;
-import app.coronawarn.server.services.distribution.structure.directory.decorator.DirectoryDecorator;
-import app.coronawarn.server.services.distribution.structure.file.File;
-import app.coronawarn.server.services.distribution.structure.file.FileImpl;
-import app.coronawarn.server.services.distribution.structure.file.decorator.SigningDecorator;
-import app.coronawarn.server.services.distribution.structure.functional.CheckedFunction;
-import app.coronawarn.server.services.distribution.structure.util.ImmutableStack;
+import app.coronawarn.server.services.distribution.assembly.component.CryptoProvider;
+import app.coronawarn.server.services.distribution.assembly.structure.Writable;
+import app.coronawarn.server.services.distribution.assembly.structure.directory.Directory;
+import app.coronawarn.server.services.distribution.assembly.structure.directory.decorator.DirectoryDecorator;
+import app.coronawarn.server.services.distribution.assembly.structure.file.File;
+import app.coronawarn.server.services.distribution.assembly.structure.file.FileImpl;
+import app.coronawarn.server.services.distribution.assembly.structure.file.decorator.SigningDecorator;
+import app.coronawarn.server.services.distribution.assembly.structure.functional.CheckedFunction;
+import app.coronawarn.server.services.distribution.assembly.structure.util.ImmutableStack;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/diagnosiskeys/structure/file/HourFileImpl.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/file/HourFileImpl.java
similarity index 86%
rename from services/distribution/src/main/java/app/coronawarn/server/services/distribution/diagnosiskeys/structure/file/HourFileImpl.java
rename to services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/file/HourFileImpl.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/diagnosiskeys/structure/file/HourFileImpl.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/file/HourFileImpl.java
@@ -1,13 +1,13 @@
-package app.coronawarn.server.services.distribution.diagnosiskeys.structure.file;
+package app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.file;
import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
import app.coronawarn.server.common.protocols.external.exposurenotification.File;
import app.coronawarn.server.common.protocols.external.exposurenotification.Key;
import app.coronawarn.server.common.protocols.internal.FileBucket;
-import app.coronawarn.server.services.distribution.diagnosiskeys.util.Batch;
-import app.coronawarn.server.services.distribution.diagnosiskeys.util.DateTime;
-import app.coronawarn.server.services.distribution.structure.file.FileImpl;
-import app.coronawarn.server.services.distribution.structure.util.ImmutableStack;
+import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.util.Batch;
+import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.util.DateTime;
+import app.coronawarn.server.services.distribution.assembly.structure.file.FileImpl;
+import app.coronawarn.server.services.distribution.assembly.structure.util.ImmutableStack;
import com.google.protobuf.ByteString;
import java.time.Instant;
import java.time.LocalDateTime;
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/diagnosiskeys/util/Batch.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/util/Batch.java
similarity index 97%
rename from services/distribution/src/main/java/app/coronawarn/server/services/distribution/diagnosiskeys/util/Batch.java
rename to services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/util/Batch.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/diagnosiskeys/util/Batch.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/util/Batch.java
@@ -1,4 +1,4 @@
-package app.coronawarn.server.services.distribution.diagnosiskeys.util;
+package app.coronawarn.server.services.distribution.assembly.diagnosiskeys.util;
import app.coronawarn.server.common.protocols.external.exposurenotification.File;
import app.coronawarn.server.common.protocols.external.exposurenotification.Header;
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/diagnosiskeys/util/DateTime.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/util/DateTime.java
similarity index 95%
rename from services/distribution/src/main/java/app/coronawarn/server/services/distribution/diagnosiskeys/util/DateTime.java
rename to services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/util/DateTime.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/diagnosiskeys/util/DateTime.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/util/DateTime.java
@@ -1,4 +1,4 @@
-package app.coronawarn.server.services.distribution.diagnosiskeys.util;
+package app.coronawarn.server.services.distribution.assembly.diagnosiskeys.util;
import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
import java.time.LocalDate;
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/diagnosiskeys/util/Maths.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/util/Maths.java
similarity index 64%
rename from services/distribution/src/main/java/app/coronawarn/server/services/distribution/diagnosiskeys/util/Maths.java
rename to services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/util/Maths.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/diagnosiskeys/util/Maths.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/util/Maths.java
@@ -1,4 +1,4 @@
-package app.coronawarn.server.services.distribution.diagnosiskeys.util;
+package app.coronawarn.server.services.distribution.assembly.diagnosiskeys.util;
public class Maths {
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/exposureconfig/ExposureConfigurationProvider.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/ExposureConfigurationProvider.java
similarity index 92%
rename from services/distribution/src/main/java/app/coronawarn/server/services/distribution/exposureconfig/ExposureConfigurationProvider.java
rename to services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/ExposureConfigurationProvider.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/exposureconfig/ExposureConfigurationProvider.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/ExposureConfigurationProvider.java
@@ -1,8 +1,8 @@
-package app.coronawarn.server.services.distribution.exposureconfig;
+package app.coronawarn.server.services.distribution.assembly.exposureconfig;
import app.coronawarn.server.common.protocols.internal.RiskScoreParameters;
import app.coronawarn.server.common.protocols.internal.RiskScoreParameters.Builder;
-import app.coronawarn.server.services.distribution.exposureconfig.parsing.YamlConstructorForProtoBuf;
+import app.coronawarn.server.services.distribution.assembly.exposureconfig.parsing.YamlConstructorForProtoBuf;
import java.io.IOException;
import java.io.InputStream;
import org.springframework.core.io.ClassPathResource;
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/exposureconfig/UnableToLoadFileException.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/UnableToLoadFileException.java
similarity index 79%
rename from services/distribution/src/main/java/app/coronawarn/server/services/distribution/exposureconfig/UnableToLoadFileException.java
rename to services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/UnableToLoadFileException.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/exposureconfig/UnableToLoadFileException.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/UnableToLoadFileException.java
@@ -1,4 +1,4 @@
-package app.coronawarn.server.services.distribution.exposureconfig;
+package app.coronawarn.server.services.distribution.assembly.exposureconfig;
/**
* The file could not be loaded/parsed correctly.
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/exposureconfig/parsing/YamlConstructorForProtoBuf.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/parsing/YamlConstructorForProtoBuf.java
similarity index 85%
rename from services/distribution/src/main/java/app/coronawarn/server/services/distribution/exposureconfig/parsing/YamlConstructorForProtoBuf.java
rename to services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/parsing/YamlConstructorForProtoBuf.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/exposureconfig/parsing/YamlConstructorForProtoBuf.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/parsing/YamlConstructorForProtoBuf.java
@@ -1,4 +1,4 @@
-package app.coronawarn.server.services.distribution.exposureconfig.parsing;
+package app.coronawarn.server.services.distribution.assembly.exposureconfig.parsing;
import java.util.Arrays;
import org.yaml.snakeyaml.constructor.Constructor;
@@ -20,9 +20,9 @@ public YamlConstructorForProtoBuf() {
setPropertyUtils(new ProtoBufPropertyUtils());
}
- private class ProtoBufPropertyUtils extends PropertyUtils {
+ private static class ProtoBufPropertyUtils extends PropertyUtils {
- public Property getProperty(Class<? extends Object> type, String name, BeanAccess bAccess) {
+ public Property getProperty(Class<?> type, String name, BeanAccess bAccess) {
return super.getProperty(type, transformToProtoNaming(name), bAccess);
}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/exposureconfig/structure/ExposureConfigurationDirectoryImpl.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/structure/ExposureConfigurationDirectoryImpl.java
similarity index 69%
rename from services/distribution/src/main/java/app/coronawarn/server/services/distribution/exposureconfig/structure/ExposureConfigurationDirectoryImpl.java
rename to services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/structure/ExposureConfigurationDirectoryImpl.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/exposureconfig/structure/ExposureConfigurationDirectoryImpl.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/structure/ExposureConfigurationDirectoryImpl.java
@@ -1,12 +1,12 @@
-package app.coronawarn.server.services.distribution.exposureconfig.structure;
+package app.coronawarn.server.services.distribution.assembly.exposureconfig.structure;
import app.coronawarn.server.common.protocols.internal.RiskScoreParameters;
-import app.coronawarn.server.services.distribution.crypto.CryptoProvider;
-import app.coronawarn.server.services.distribution.structure.directory.DirectoryImpl;
-import app.coronawarn.server.services.distribution.structure.directory.IndexDirectoryImpl;
-import app.coronawarn.server.services.distribution.structure.directory.decorator.IndexingDecorator;
-import app.coronawarn.server.services.distribution.structure.file.FileImpl;
-import app.coronawarn.server.services.distribution.structure.file.decorator.SigningDecorator;
+import app.coronawarn.server.services.distribution.assembly.component.CryptoProvider;
+import app.coronawarn.server.services.distribution.assembly.structure.directory.DirectoryImpl;
+import app.coronawarn.server.services.distribution.assembly.structure.directory.IndexDirectoryImpl;
+import app.coronawarn.server.services.distribution.assembly.structure.directory.decorator.IndexingDecorator;
+import app.coronawarn.server.services.distribution.assembly.structure.file.FileImpl;
+import app.coronawarn.server.services.distribution.assembly.structure.file.decorator.SigningDecorator;
import java.util.Set;
/**
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/exposureconfig/structure/directory/ExposureConfigurationDirectoryImpl.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/structure/directory/ExposureConfigurationDirectoryImpl.java
similarity index 68%
rename from services/distribution/src/main/java/app/coronawarn/server/services/distribution/exposureconfig/structure/directory/ExposureConfigurationDirectoryImpl.java
rename to services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/structure/directory/ExposureConfigurationDirectoryImpl.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/exposureconfig/structure/directory/ExposureConfigurationDirectoryImpl.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/structure/directory/ExposureConfigurationDirectoryImpl.java
@@ -1,12 +1,12 @@
-package app.coronawarn.server.services.distribution.exposureconfig.structure.directory;
+package app.coronawarn.server.services.distribution.assembly.exposureconfig.structure.directory;
import app.coronawarn.server.common.protocols.internal.RiskScoreParameters;
-import app.coronawarn.server.services.distribution.crypto.CryptoProvider;
-import app.coronawarn.server.services.distribution.structure.directory.DirectoryImpl;
-import app.coronawarn.server.services.distribution.structure.directory.IndexDirectoryImpl;
-import app.coronawarn.server.services.distribution.structure.directory.decorator.IndexingDecorator;
-import app.coronawarn.server.services.distribution.structure.file.FileImpl;
-import app.coronawarn.server.services.distribution.structure.file.decorator.SigningDecorator;
+import app.coronawarn.server.services.distribution.assembly.component.CryptoProvider;
+import app.coronawarn.server.services.distribution.assembly.structure.directory.DirectoryImpl;
+import app.coronawarn.server.services.distribution.assembly.structure.directory.IndexDirectoryImpl;
+import app.coronawarn.server.services.distribution.assembly.structure.directory.decorator.IndexingDecorator;
+import app.coronawarn.server.services.distribution.assembly.structure.file.FileImpl;
+import app.coronawarn.server.services.distribution.assembly.structure.file.decorator.SigningDecorator;
import java.util.Set;
/**
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/exposureconfig/validation/ExposureConfigurationValidator.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/validation/ExposureConfigurationValidator.java
similarity index 93%
rename from services/distribution/src/main/java/app/coronawarn/server/services/distribution/exposureconfig/validation/ExposureConfigurationValidator.java
rename to services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/validation/ExposureConfigurationValidator.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/exposureconfig/validation/ExposureConfigurationValidator.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/validation/ExposureConfigurationValidator.java
@@ -1,8 +1,8 @@
-package app.coronawarn.server.services.distribution.exposureconfig.validation;
+package app.coronawarn.server.services.distribution.assembly.exposureconfig.validation;
import app.coronawarn.server.common.protocols.internal.RiskLevel;
import app.coronawarn.server.common.protocols.internal.RiskScoreParameters;
-import app.coronawarn.server.services.distribution.exposureconfig.validation.WeightValidationError.ErrorType;
+import app.coronawarn.server.services.distribution.assembly.exposureconfig.validation.WeightValidationError.ErrorType;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
@@ -19,7 +19,7 @@
*/
public class ExposureConfigurationValidator {
- private RiskScoreParameters config;
+ private final RiskScoreParameters config;
private ValidationResult errors;
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/exposureconfig/validation/ParameterSpec.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/validation/ParameterSpec.java
similarity index 85%
rename from services/distribution/src/main/java/app/coronawarn/server/services/distribution/exposureconfig/validation/ParameterSpec.java
rename to services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/validation/ParameterSpec.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/exposureconfig/validation/ParameterSpec.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/validation/ParameterSpec.java
@@ -1,4 +1,4 @@
-package app.coronawarn.server.services.distribution.exposureconfig.validation;
+package app.coronawarn.server.services.distribution.assembly.exposureconfig.validation;
/**
* Definition of the spec according to Apple/Google:
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/exposureconfig/validation/RiskLevelValidationError.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/validation/RiskLevelValidationError.java
similarity index 93%
rename from services/distribution/src/main/java/app/coronawarn/server/services/distribution/exposureconfig/validation/RiskLevelValidationError.java
rename to services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/validation/RiskLevelValidationError.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/exposureconfig/validation/RiskLevelValidationError.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/validation/RiskLevelValidationError.java
@@ -1,4 +1,4 @@
-package app.coronawarn.server.services.distribution.exposureconfig.validation;
+package app.coronawarn.server.services.distribution.assembly.exposureconfig.validation;
import java.util.Objects;
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/exposureconfig/validation/ValidationError.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/validation/ValidationError.java
similarity index 67%
rename from services/distribution/src/main/java/app/coronawarn/server/services/distribution/exposureconfig/validation/ValidationError.java
rename to services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/validation/ValidationError.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/exposureconfig/validation/ValidationError.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/validation/ValidationError.java
@@ -1,4 +1,4 @@
-package app.coronawarn.server.services.distribution.exposureconfig.validation;
+package app.coronawarn.server.services.distribution.assembly.exposureconfig.validation;
/**
* A validation error, found during the process of validating the Exposure Configuration. Can either
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/exposureconfig/validation/ValidationFailedException.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/validation/ValidationFailedException.java
similarity index 78%
rename from services/distribution/src/main/java/app/coronawarn/server/services/distribution/exposureconfig/validation/ValidationFailedException.java
rename to services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/validation/ValidationFailedException.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/exposureconfig/validation/ValidationFailedException.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/validation/ValidationFailedException.java
@@ -1,4 +1,4 @@
-package app.coronawarn.server.services.distribution.exposureconfig.validation;
+package app.coronawarn.server.services.distribution.assembly.exposureconfig.validation;
/**
* The validation could not be executed. Find more information about the root cause in the cause
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/exposureconfig/validation/ValidationResult.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/validation/ValidationResult.java
similarity index 87%
rename from services/distribution/src/main/java/app/coronawarn/server/services/distribution/exposureconfig/validation/ValidationResult.java
rename to services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/validation/ValidationResult.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/exposureconfig/validation/ValidationResult.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/validation/ValidationResult.java
@@ -1,4 +1,4 @@
-package app.coronawarn.server.services.distribution.exposureconfig.validation;
+package app.coronawarn.server.services.distribution.assembly.exposureconfig.validation;
import java.util.HashSet;
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/exposureconfig/validation/WeightValidationError.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/validation/WeightValidationError.java
similarity index 94%
rename from services/distribution/src/main/java/app/coronawarn/server/services/distribution/exposureconfig/validation/WeightValidationError.java
rename to services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/validation/WeightValidationError.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/exposureconfig/validation/WeightValidationError.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/validation/WeightValidationError.java
@@ -1,4 +1,4 @@
-package app.coronawarn.server.services.distribution.exposureconfig.validation;
+package app.coronawarn.server.services.distribution.assembly.exposureconfig.validation;
import java.util.Objects;
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/io/IO.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/io/IO.java
similarity index 96%
rename from services/distribution/src/main/java/app/coronawarn/server/services/distribution/io/IO.java
rename to services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/io/IO.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/io/IO.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/io/IO.java
@@ -1,4 +1,4 @@
-package app.coronawarn.server.services.distribution.io;
+package app.coronawarn.server.services.distribution.assembly.io;
import java.io.File;
import java.io.FileOutputStream;
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/Writable.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/Writable.java
similarity index 74%
rename from services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/Writable.java
rename to services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/Writable.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/Writable.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/Writable.java
@@ -1,7 +1,7 @@
-package app.coronawarn.server.services.distribution.structure;
+package app.coronawarn.server.services.distribution.assembly.structure;
-import app.coronawarn.server.services.distribution.structure.directory.Directory;
-import app.coronawarn.server.services.distribution.structure.util.ImmutableStack;
+import app.coronawarn.server.services.distribution.assembly.structure.directory.Directory;
+import app.coronawarn.server.services.distribution.assembly.structure.util.ImmutableStack;
/**
* Something that can be written to disk.
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/WritableImpl.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/WritableImpl.java
similarity index 82%
rename from services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/WritableImpl.java
rename to services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/WritableImpl.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/WritableImpl.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/WritableImpl.java
@@ -1,6 +1,6 @@
-package app.coronawarn.server.services.distribution.structure;
+package app.coronawarn.server.services.distribution.assembly.structure;
-import app.coronawarn.server.services.distribution.structure.directory.Directory;
+import app.coronawarn.server.services.distribution.assembly.structure.directory.Directory;
import java.util.Objects;
public abstract class WritableImpl implements Writable {
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/directory/Directory.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/directory/Directory.java
similarity index 75%
rename from services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/directory/Directory.java
rename to services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/directory/Directory.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/directory/Directory.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/directory/Directory.java
@@ -1,7 +1,7 @@
-package app.coronawarn.server.services.distribution.structure.directory;
+package app.coronawarn.server.services.distribution.assembly.structure.directory;
-import app.coronawarn.server.services.distribution.structure.Writable;
-import app.coronawarn.server.services.distribution.structure.file.File;
+import app.coronawarn.server.services.distribution.assembly.structure.Writable;
+import app.coronawarn.server.services.distribution.assembly.structure.file.File;
import java.util.Set;
/**
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/directory/DirectoryImpl.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/directory/DirectoryImpl.java
similarity index 87%
rename from services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/directory/DirectoryImpl.java
rename to services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/directory/DirectoryImpl.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/directory/DirectoryImpl.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/directory/DirectoryImpl.java
@@ -1,8 +1,8 @@
-package app.coronawarn.server.services.distribution.structure.directory;
+package app.coronawarn.server.services.distribution.assembly.structure.directory;
-import app.coronawarn.server.services.distribution.structure.WritableImpl;
-import app.coronawarn.server.services.distribution.structure.file.File;
-import app.coronawarn.server.services.distribution.structure.util.ImmutableStack;
+import app.coronawarn.server.services.distribution.assembly.structure.WritableImpl;
+import app.coronawarn.server.services.distribution.assembly.structure.file.File;
+import app.coronawarn.server.services.distribution.assembly.structure.util.ImmutableStack;
import java.util.HashSet;
import java.util.Set;
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/directory/IndexDirectory.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/directory/IndexDirectory.java
similarity index 77%
rename from services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/directory/IndexDirectory.java
rename to services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/directory/IndexDirectory.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/directory/IndexDirectory.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/directory/IndexDirectory.java
@@ -1,9 +1,9 @@
-package app.coronawarn.server.services.distribution.structure.directory;
+package app.coronawarn.server.services.distribution.assembly.structure.directory;
-import app.coronawarn.server.services.distribution.structure.functional.DirectoryFunction;
-import app.coronawarn.server.services.distribution.structure.functional.FileFunction;
-import app.coronawarn.server.services.distribution.structure.functional.Formatter;
-import app.coronawarn.server.services.distribution.structure.util.ImmutableStack;
+import app.coronawarn.server.services.distribution.assembly.structure.functional.DirectoryFunction;
+import app.coronawarn.server.services.distribution.assembly.structure.functional.FileFunction;
+import app.coronawarn.server.services.distribution.assembly.structure.functional.Formatter;
+import app.coronawarn.server.services.distribution.assembly.structure.util.ImmutableStack;
import java.util.Set;
import java.util.Stack;
@@ -32,7 +32,7 @@ public interface IndexDirectory<T> extends Directory {
void addDirectoryToAll(DirectoryFunction directoryFunction);
/**
- * Calls the {@link app.coronawarn.server.services.distribution.structure.functional.IndexFunction}
+ * Calls the {@link app.coronawarn.server.services.distribution.assembly.structure.functional.IndexFunction}
* with the {@code indices} to calculate and return the elements of the index of this {@link
* IndexDirectory}.
*
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/directory/IndexDirectoryImpl.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/directory/IndexDirectoryImpl.java
similarity index 85%
rename from services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/directory/IndexDirectoryImpl.java
rename to services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/directory/IndexDirectoryImpl.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/directory/IndexDirectoryImpl.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/directory/IndexDirectoryImpl.java
@@ -1,11 +1,11 @@
-package app.coronawarn.server.services.distribution.structure.directory;
+package app.coronawarn.server.services.distribution.assembly.structure.directory;
-import app.coronawarn.server.services.distribution.structure.file.File;
-import app.coronawarn.server.services.distribution.structure.functional.DirectoryFunction;
-import app.coronawarn.server.services.distribution.structure.functional.FileFunction;
-import app.coronawarn.server.services.distribution.structure.functional.Formatter;
-import app.coronawarn.server.services.distribution.structure.functional.IndexFunction;
-import app.coronawarn.server.services.distribution.structure.util.ImmutableStack;
+import app.coronawarn.server.services.distribution.assembly.structure.file.File;
+import app.coronawarn.server.services.distribution.assembly.structure.functional.DirectoryFunction;
+import app.coronawarn.server.services.distribution.assembly.structure.functional.FileFunction;
+import app.coronawarn.server.services.distribution.assembly.structure.functional.Formatter;
+import app.coronawarn.server.services.distribution.assembly.structure.functional.IndexFunction;
+import app.coronawarn.server.services.distribution.assembly.structure.util.ImmutableStack;
import java.util.HashSet;
import java.util.Set;
import java.util.Stack;
@@ -61,7 +61,7 @@ public void addDirectoryToAll(DirectoryFunction directoryFunction) {
* Creates a new subdirectory for every element of the {@link IndexDirectory#getIndex index} and
* writes {@link IndexDirectory#addFileToAll files} and {@link IndexDirectory#addDirectory
* directories} to those. The respective element of the index will be pushed onto the Stack for
- * subsequent {@link app.coronawarn.server.services.distribution.structure.Writable#prepare} calls
+ * subsequent {@link app.coronawarn.server.services.distribution.assembly.structure.Writable#prepare} calls
* on those files and directories.
*
* @param indices A {@link Stack} of parameters from all {@link IndexDirectory IndexDirectories}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/directory/decorator/DirectoryDecorator.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/directory/decorator/DirectoryDecorator.java
similarity index 75%
rename from services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/directory/decorator/DirectoryDecorator.java
rename to services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/directory/decorator/DirectoryDecorator.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/directory/decorator/DirectoryDecorator.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/directory/decorator/DirectoryDecorator.java
@@ -1,9 +1,9 @@
-package app.coronawarn.server.services.distribution.structure.directory.decorator;
+package app.coronawarn.server.services.distribution.assembly.structure.directory.decorator;
-import app.coronawarn.server.services.distribution.structure.Writable;
-import app.coronawarn.server.services.distribution.structure.directory.Directory;
-import app.coronawarn.server.services.distribution.structure.file.File;
-import app.coronawarn.server.services.distribution.structure.util.ImmutableStack;
+import app.coronawarn.server.services.distribution.assembly.structure.Writable;
+import app.coronawarn.server.services.distribution.assembly.structure.directory.Directory;
+import app.coronawarn.server.services.distribution.assembly.structure.file.File;
+import app.coronawarn.server.services.distribution.assembly.structure.util.ImmutableStack;
import java.util.Set;
/**
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/directory/decorator/IndexingDecorator.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/directory/decorator/IndexingDecorator.java
similarity index 72%
rename from services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/directory/decorator/IndexingDecorator.java
rename to services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/directory/decorator/IndexingDecorator.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/directory/decorator/IndexingDecorator.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/directory/decorator/IndexingDecorator.java
@@ -1,9 +1,9 @@
-package app.coronawarn.server.services.distribution.structure.directory.decorator;
+package app.coronawarn.server.services.distribution.assembly.structure.directory.decorator;
-import app.coronawarn.server.services.distribution.structure.directory.IndexDirectory;
-import app.coronawarn.server.services.distribution.structure.directory.IndexDirectoryImpl;
-import app.coronawarn.server.services.distribution.structure.file.FileImpl;
-import app.coronawarn.server.services.distribution.structure.util.ImmutableStack;
+import app.coronawarn.server.services.distribution.assembly.structure.directory.IndexDirectory;
+import app.coronawarn.server.services.distribution.assembly.structure.directory.IndexDirectoryImpl;
+import app.coronawarn.server.services.distribution.assembly.structure.file.FileImpl;
+import app.coronawarn.server.services.distribution.assembly.structure.util.ImmutableStack;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
@@ -14,7 +14,7 @@
/**
* A {@link DirectoryDecorator} that writes a file called {@code "index"}, containing a JSON array
* containing all elements returned {@link IndexDirectoryImpl#getIndex}, formatted with the {@link
- * IndexDirectoryImpl#getIndexFormatter} on {@link app.coronawarn.server.services.distribution.structure.Writable#prepare}.
+ * IndexDirectoryImpl#getIndexFormatter} on {@link app.coronawarn.server.services.distribution.assembly.structure.Writable#prepare}.
*/
public class IndexingDecorator<T> extends DirectoryDecorator {
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/file/File.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/file/File.java
similarity index 64%
rename from services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/file/File.java
rename to services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/file/File.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/file/File.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/file/File.java
@@ -1,6 +1,6 @@
-package app.coronawarn.server.services.distribution.structure.file;
+package app.coronawarn.server.services.distribution.assembly.structure.file;
-import app.coronawarn.server.services.distribution.structure.Writable;
+import app.coronawarn.server.services.distribution.assembly.structure.Writable;
/**
* A {@link Writable} containing some bytes.
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/file/FileImpl.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/file/FileImpl.java
similarity index 69%
rename from services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/file/FileImpl.java
rename to services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/file/FileImpl.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/file/FileImpl.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/file/FileImpl.java
@@ -1,9 +1,9 @@
-package app.coronawarn.server.services.distribution.structure.file;
+package app.coronawarn.server.services.distribution.assembly.structure.file;
-import app.coronawarn.server.services.distribution.io.IO;
-import app.coronawarn.server.services.distribution.structure.Writable;
-import app.coronawarn.server.services.distribution.structure.WritableImpl;
-import app.coronawarn.server.services.distribution.structure.util.ImmutableStack;
+import app.coronawarn.server.services.distribution.assembly.io.IO;
+import app.coronawarn.server.services.distribution.assembly.structure.Writable;
+import app.coronawarn.server.services.distribution.assembly.structure.WritableImpl;
+import app.coronawarn.server.services.distribution.assembly.structure.util.ImmutableStack;
/**
* Implementation of {@link File} that interfaces with {@link java.io.File Files} on disk.
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/file/decorator/FileDecorator.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/file/decorator/FileDecorator.java
similarity index 70%
rename from services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/file/decorator/FileDecorator.java
rename to services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/file/decorator/FileDecorator.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/file/decorator/FileDecorator.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/file/decorator/FileDecorator.java
@@ -1,9 +1,9 @@
-package app.coronawarn.server.services.distribution.structure.file.decorator;
+package app.coronawarn.server.services.distribution.assembly.structure.file.decorator;
-import app.coronawarn.server.services.distribution.structure.Writable;
-import app.coronawarn.server.services.distribution.structure.directory.Directory;
-import app.coronawarn.server.services.distribution.structure.file.File;
-import app.coronawarn.server.services.distribution.structure.util.ImmutableStack;
+import app.coronawarn.server.services.distribution.assembly.structure.Writable;
+import app.coronawarn.server.services.distribution.assembly.structure.directory.Directory;
+import app.coronawarn.server.services.distribution.assembly.structure.file.File;
+import app.coronawarn.server.services.distribution.assembly.structure.util.ImmutableStack;
/**
* Decorates a {@link File} (e.g. to modify its content) on {@link Writable#prepare}. This class
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/file/decorator/SigningDecorator.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/file/decorator/SigningDecorator.java
similarity index 85%
rename from services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/file/decorator/SigningDecorator.java
rename to services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/file/decorator/SigningDecorator.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/file/decorator/SigningDecorator.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/file/decorator/SigningDecorator.java
@@ -1,9 +1,9 @@
-package app.coronawarn.server.services.distribution.structure.file.decorator;
+package app.coronawarn.server.services.distribution.assembly.structure.file.decorator;
import app.coronawarn.server.common.protocols.internal.SignedPayload;
-import app.coronawarn.server.services.distribution.crypto.CryptoProvider;
-import app.coronawarn.server.services.distribution.structure.file.File;
-import app.coronawarn.server.services.distribution.structure.util.ImmutableStack;
+import app.coronawarn.server.services.distribution.assembly.component.CryptoProvider;
+import app.coronawarn.server.services.distribution.assembly.structure.file.File;
+import app.coronawarn.server.services.distribution.assembly.structure.util.ImmutableStack;
import com.google.protobuf.ByteString;
import java.security.GeneralSecurityException;
import java.security.PrivateKey;
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/functional/CheckedFunction.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/functional/CheckedFunction.java
similarity index 85%
rename from services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/functional/CheckedFunction.java
rename to services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/functional/CheckedFunction.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/functional/CheckedFunction.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/functional/CheckedFunction.java
@@ -1,4 +1,4 @@
-package app.coronawarn.server.services.distribution.structure.functional;
+package app.coronawarn.server.services.distribution.assembly.structure.functional;
import java.util.function.Function;
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/functional/DirectoryFunction.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/functional/DirectoryFunction.java
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/functional/DirectoryFunction.java
@@ -0,0 +1,14 @@
+package app.coronawarn.server.services.distribution.assembly.structure.functional;
+
+import app.coronawarn.server.services.distribution.assembly.structure.directory.Directory;
+import app.coronawarn.server.services.distribution.assembly.structure.util.ImmutableStack;
+import java.util.function.Function;
+
+/**
+ * A {@code Function<Stack<Object>, Directory>}.
+ */
+@FunctionalInterface
+public interface DirectoryFunction extends Function<ImmutableStack<Object>, Directory> {
+
+ Directory apply(ImmutableStack<Object> t);
+}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/functional/FileFunction.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/functional/FileFunction.java
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/functional/FileFunction.java
@@ -0,0 +1,14 @@
+package app.coronawarn.server.services.distribution.assembly.structure.functional;
+
+import app.coronawarn.server.services.distribution.assembly.structure.file.File;
+import app.coronawarn.server.services.distribution.assembly.structure.util.ImmutableStack;
+import java.util.function.Function;
+
+/**
+ * A {@code Function<Stack<Object>, File>}.
+ */
+@FunctionalInterface
+public interface FileFunction extends Function<ImmutableStack<Object>, File> {
+
+ File apply(ImmutableStack<Object> t);
+}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/functional/Formatter.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/functional/Formatter.java
similarity index 74%
rename from services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/functional/Formatter.java
rename to services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/functional/Formatter.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/functional/Formatter.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/functional/Formatter.java
@@ -1,4 +1,4 @@
-package app.coronawarn.server.services.distribution.structure.functional;
+package app.coronawarn.server.services.distribution.assembly.structure.functional;
import java.util.function.Function;
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/functional/IndexFunction.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/functional/IndexFunction.java
similarity index 64%
rename from services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/functional/IndexFunction.java
rename to services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/functional/IndexFunction.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/functional/IndexFunction.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/functional/IndexFunction.java
@@ -1,6 +1,6 @@
-package app.coronawarn.server.services.distribution.structure.functional;
+package app.coronawarn.server.services.distribution.assembly.structure.functional;
-import app.coronawarn.server.services.distribution.structure.util.ImmutableStack;
+import app.coronawarn.server.services.distribution.assembly.structure.util.ImmutableStack;
import java.util.Set;
import java.util.function.Function;
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/util/ImmutableStack.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/util/ImmutableStack.java
similarity index 84%
rename from services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/util/ImmutableStack.java
rename to services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/util/ImmutableStack.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/util/ImmutableStack.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/util/ImmutableStack.java
@@ -1,10 +1,10 @@
-package app.coronawarn.server.services.distribution.structure.util;
+package app.coronawarn.server.services.distribution.assembly.structure.util;
import java.util.Stack;
public class ImmutableStack<T> {
- private Stack<T> stack;
+ private final Stack<T> stack;
public ImmutableStack() {
this.stack = new Stack<>();
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/ObjectStoreAccess.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/ObjectStoreAccess.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/ObjectStoreAccess.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/ObjectStoreAccess.java
@@ -36,9 +36,9 @@
@Component
public class ObjectStoreAccess {
- private Logger logger = LoggerFactory.getLogger(this.getClass());
+ private final Logger logger = LoggerFactory.getLogger(this.getClass());
- private String bucket;
+ private final String bucket;
private S3Client client;
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/S3Publisher.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/S3Publisher.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/S3Publisher.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/objectstore/S3Publisher.java
@@ -16,14 +16,14 @@
@Component
public class S3Publisher {
- private Logger logger = LoggerFactory.getLogger(this.getClass());
+ private final Logger logger = LoggerFactory.getLogger(this.getClass());
/**
* prefix path on S3, enforced for all methods on this class.
*/
private String prefixPath = "cwa/";
- private ObjectStoreAccess objectStoreAccess;
+ private final ObjectStoreAccess objectStoreAccess;
@Autowired
public S3Publisher(ObjectStoreAccess objectStoreAccess) {
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/Assembly.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/Assembly.java
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/Assembly.java
@@ -0,0 +1,42 @@
+package app.coronawarn.server.services.distribution.runner;
+
+import app.coronawarn.server.services.distribution.assembly.component.CwaApiStructureProvider;
+import app.coronawarn.server.services.distribution.assembly.component.OutputDirectoryProvider;
+import app.coronawarn.server.services.distribution.assembly.structure.directory.Directory;
+import app.coronawarn.server.services.distribution.assembly.structure.util.ImmutableStack;
+import java.io.IOException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.ApplicationArguments;
+import org.springframework.boot.ApplicationRunner;
+import org.springframework.core.annotation.Order;
+import org.springframework.stereotype.Component;
+
+/**
+ * This runner assembles and writes diagnosis key bundles and the parameter configuration.
+ */
+@Component
+@Order(2)
+public class Assembly implements ApplicationRunner {
+
+ private static final Logger logger = LoggerFactory.getLogger(Assembly.class);
+
+ @Autowired
+ private OutputDirectoryProvider outputDirectoryProvider;
+
+ @Autowired
+ private CwaApiStructureProvider cwaApiStructureProvider;
+
+ @Override
+ public void run(ApplicationArguments args) throws IOException {
+ Directory outputDirectory = this.outputDirectoryProvider.getDirectory();
+ outputDirectory.addDirectory(cwaApiStructureProvider.getDirectory());
+ this.outputDirectoryProvider.clear();
+ logger.debug("Preparing files...");
+ outputDirectory.prepare(new ImmutableStack<>());
+ logger.debug("Writing files...");
+ outputDirectory.write();
+ logger.debug("Distribution run finished successfully.");
+ }
+}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/DiagnosisKeyDistributionRunner.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/DiagnosisKeyDistributionRunner.java
deleted file mode 100644
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/DiagnosisKeyDistributionRunner.java
+++ /dev/null
@@ -1,78 +0,0 @@
-package app.coronawarn.server.services.distribution.runner;
-
-import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
-import app.coronawarn.server.common.persistence.service.DiagnosisKeyService;
-import app.coronawarn.server.services.distribution.crypto.CryptoProvider;
-import app.coronawarn.server.services.distribution.diagnosiskeys.structure.directory.DiagnosisKeysDirectoryImpl;
-import app.coronawarn.server.services.distribution.structure.directory.DirectoryImpl;
-import app.coronawarn.server.services.distribution.structure.directory.IndexDirectory;
-import app.coronawarn.server.services.distribution.structure.directory.IndexDirectoryImpl;
-import app.coronawarn.server.services.distribution.structure.directory.decorator.IndexingDecorator;
-import app.coronawarn.server.services.distribution.structure.util.ImmutableStack;
-import java.io.File;
-import java.io.IOException;
-import java.util.Collection;
-import java.util.Set;
-import org.apache.commons.io.FileUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.beans.factory.annotation.Value;
-import org.springframework.boot.ApplicationArguments;
-import org.springframework.boot.ApplicationRunner;
-import org.springframework.core.annotation.Order;
-import org.springframework.stereotype.Component;
-
-@Component
-@Order(3)
-/**
- * This runner retrieves stored diagnosis keys, the generates and persists the respective diagnosis
- * key bundles.
- */
-public class DiagnosisKeyDistributionRunner implements ApplicationRunner {
-
- private static final Logger logger = LoggerFactory
- .getLogger(DiagnosisKeyDistributionRunner.class);
-
- private static final String VERSION_DIRECTORY = "version";
-
- @Value("${app.coronawarn.server.services.distribution.version}")
- private String version;
-
- @Value("${app.coronawarn.server.services.distribution.paths.output}")
- private String outputPath;
-
- @Autowired
- private CryptoProvider cryptoProvider;
-
- @Autowired
- private DiagnosisKeyService diagnosisKeyService;
-
-
- @Override
- public void run(ApplicationArguments args) throws IOException {
- Collection<DiagnosisKey> diagnosisKeys = diagnosisKeyService.getDiagnosisKeys();
-
- DiagnosisKeysDirectoryImpl diagnosisKeysDirectory =
- new DiagnosisKeysDirectoryImpl(diagnosisKeys, cryptoProvider);
-
- IndexDirectory<?> versionDirectory =
- new IndexDirectoryImpl<>(VERSION_DIRECTORY, __ -> Set.of(version), Object::toString);
-
- versionDirectory.addDirectoryToAll(__ -> diagnosisKeysDirectory);
-
- java.io.File outputDirectory = new File(outputPath);
- clearDirectory(outputDirectory);
- DirectoryImpl root = new DirectoryImpl(outputDirectory);
- root.addDirectory(new IndexingDecorator<>(versionDirectory));
-
- root.prepare(new ImmutableStack<>());
- root.write();
- logger.debug("Diagnosis key distribution structure written successfully.");
- }
-
- private static void clearDirectory(File directory) throws IOException {
- FileUtils.deleteDirectory(directory);
- directory.mkdirs();
- }
-}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/ExposureConfigurationDistributionRunner.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/ExposureConfigurationDistributionRunner.java
deleted file mode 100644
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/ExposureConfigurationDistributionRunner.java
+++ /dev/null
@@ -1,70 +0,0 @@
-package app.coronawarn.server.services.distribution.runner;
-
-import app.coronawarn.server.common.protocols.internal.RiskScoreParameters;
-import app.coronawarn.server.services.distribution.crypto.CryptoProvider;
-import app.coronawarn.server.services.distribution.exposureconfig.ExposureConfigurationProvider;
-import app.coronawarn.server.services.distribution.exposureconfig.UnableToLoadFileException;
-import app.coronawarn.server.services.distribution.exposureconfig.structure.directory.ExposureConfigurationDirectoryImpl;
-import app.coronawarn.server.services.distribution.structure.directory.Directory;
-import app.coronawarn.server.services.distribution.structure.directory.DirectoryImpl;
-import app.coronawarn.server.services.distribution.structure.directory.IndexDirectory;
-import app.coronawarn.server.services.distribution.structure.directory.IndexDirectoryImpl;
-import app.coronawarn.server.services.distribution.structure.directory.decorator.IndexingDecorator;
-import app.coronawarn.server.services.distribution.structure.util.ImmutableStack;
-import java.io.File;
-import java.util.Set;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.beans.factory.annotation.Value;
-import org.springframework.boot.ApplicationArguments;
-import org.springframework.boot.ApplicationRunner;
-import org.springframework.core.annotation.Order;
-import org.springframework.stereotype.Component;
-
-@Component
-@Order(2)
-/**
- * Reads the exposure configuration parameters from the respective file in the class path, then
- * generates and persists the respective exposure configuration bundle.
- */
-public class ExposureConfigurationDistributionRunner implements ApplicationRunner {
-
- private static final Logger logger =
- LoggerFactory.getLogger(ExposureConfigurationDistributionRunner.class);
-
- @Value("${app.coronawarn.server.services.distribution.version}")
- private String version;
-
- @Value("${app.coronawarn.server.services.distribution.paths.output}")
- private String outputPath;
-
- @Autowired
- private CryptoProvider cryptoProvider;
-
- private static final String VERSION_DIRECTORY = "version";
-
- @Override
- public void run(ApplicationArguments args) {
- var riskScoreParameters = readExposureConfiguration();
- IndexDirectory<?> versionDirectory =
- new IndexDirectoryImpl<>(VERSION_DIRECTORY, __ -> Set.of(version), Object::toString);
- ExposureConfigurationDirectoryImpl parametersDirectory =
- new ExposureConfigurationDirectoryImpl(riskScoreParameters, cryptoProvider);
- Directory root = new DirectoryImpl(new File(outputPath));
- versionDirectory.addDirectoryToAll(__ -> parametersDirectory);
- root.addDirectory(new IndexingDecorator<>(versionDirectory));
- root.prepare(new ImmutableStack<>());
- root.write();
- logger.debug("Exposure configuration structure written successfully.");
- }
-
- private RiskScoreParameters readExposureConfiguration() {
- try {
- return ExposureConfigurationProvider.readMasterFile();
- } catch (UnableToLoadFileException e) {
- logger.error("Could not load exposure configuration parameters", e);
- throw new RuntimeException(e);
- }
- }
-}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/RetentionPolicyRunner.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/RetentionPolicy.java
similarity index 85%
rename from services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/RetentionPolicyRunner.java
rename to services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/RetentionPolicy.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/RetentionPolicyRunner.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/RetentionPolicy.java
@@ -16,15 +16,15 @@
*/
@Component
@Order(1)
-public class RetentionPolicyRunner implements ApplicationRunner {
+public class RetentionPolicy implements ApplicationRunner {
private static final Logger logger = LoggerFactory
- .getLogger(RetentionPolicyRunner.class);
+ .getLogger(RetentionPolicy.class);
@Autowired
private DiagnosisKeyService diagnosisKeyService;
- @Value("${app.coronawarn.server.services.distribution.retention_days}")
+ @Value("${services.distribution.retention_days}")
private Integer rententionDays;
@Override
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/S3DistributionRunner.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/S3Distribution.java
similarity index 69%
rename from services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/S3DistributionRunner.java
rename to services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/S3Distribution.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/S3DistributionRunner.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/S3Distribution.java
@@ -1,12 +1,12 @@
package app.coronawarn.server.services.distribution.runner;
+import app.coronawarn.server.services.distribution.assembly.component.OutputDirectoryProvider;
import app.coronawarn.server.services.distribution.objectstore.S3Publisher;
import java.io.IOException;
import java.nio.file.Path;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
@@ -16,13 +16,13 @@
* This runner will sync the base working directory to the S3.
*/
@Component
-@Order(4)
-public class S3DistributionRunner implements ApplicationRunner {
+@Order(3)
+public class S3Distribution implements ApplicationRunner {
- private Logger logger = LoggerFactory.getLogger(this.getClass());
+ private final Logger logger = LoggerFactory.getLogger(this.getClass());
- @Value("${app.coronawarn.server.services.distribution.paths.output}")
- private String workdir;
+ @Autowired
+ private OutputDirectoryProvider outputDirectoryProvider;
@Autowired
private S3Publisher s3Publisher;
@@ -30,8 +30,7 @@ public class S3DistributionRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) {
try {
- Path pathToDistribute = Path.of(workdir).toAbsolutePath();
-
+ Path pathToDistribute = outputDirectoryProvider.getFileOnDisk().toPath().toAbsolutePath();
s3Publisher.publishFolder(pathToDistribute);
} catch (IOException | UnsupportedOperationException e) {
logger.error("Distribution failed.", e);
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/functional/DirectoryFunction.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/functional/DirectoryFunction.java
deleted file mode 100644
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/functional/DirectoryFunction.java
+++ /dev/null
@@ -1,14 +0,0 @@
-package app.coronawarn.server.services.distribution.structure.functional;
-
-import app.coronawarn.server.services.distribution.structure.directory.Directory;
-import app.coronawarn.server.services.distribution.structure.util.ImmutableStack;
-import java.util.function.Function;
-
-/**
- * A {@code Function<Stack<Object>, Directory>}.
- */
-@FunctionalInterface
-public interface DirectoryFunction extends Function<ImmutableStack<Object>, Directory> {
-
- Directory apply(ImmutableStack<Object> t);
-}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/functional/FileFunction.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/functional/FileFunction.java
deleted file mode 100644
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/structure/functional/FileFunction.java
+++ /dev/null
@@ -1,14 +0,0 @@
-package app.coronawarn.server.services.distribution.structure.functional;
-
-import app.coronawarn.server.services.distribution.structure.file.File;
-import app.coronawarn.server.services.distribution.structure.util.ImmutableStack;
-import java.util.function.Function;
-
-/**
- * A {@code Function<Stack<Object>, File>}.
- */
-@FunctionalInterface
-public interface FileFunction extends Function<ImmutableStack<Object>, File> {
-
- File apply(ImmutableStack<Object> t);
-}
diff --git a/services/distribution/src/main/resources/application.properties b/services/distribution/src/main/resources/application.properties
--- a/services/distribution/src/main/resources/application.properties
+++ b/services/distribution/src/main/resources/application.properties
@@ -2,11 +2,10 @@ logging.level.org.springframework.web=INFO
logging.level.app.coronawarn=INFO
spring.main.web-application-type=NONE
-app.coronawarn.server.services.distribution.retention_days=14
-app.coronawarn.server.services.distribution.version=v1
-app.coronawarn.server.services.distribution.paths.output=out
-app.coronawarn.server.services.distribution.paths.privatekey=classpath:certificates/client/private.pem
-app.coronawarn.server.services.distribution.paths.certificate=classpath:certificates/chain/certificate.crt
+services.distribution.retention_days=14
+services.distribution.paths.output=out
+services.distribution.paths.privatekey=classpath:certificates/client/private.pem
+services.distribution.paths.certificate=classpath:certificates/chain/certificate.crt
spring.flyway.enabled=false
spring.jpa.hibernate.ddl-auto=validate
</patch> | diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/ApplicationInitializationTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/ApplicationInitializationTest.java
--- a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/ApplicationInitializationTest.java
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/ApplicationInitializationTest.java
@@ -3,7 +3,7 @@
import static org.junit.jupiter.api.Assertions.assertNotNull;
import app.coronawarn.server.common.persistence.service.DiagnosisKeyService;
-import app.coronawarn.server.services.distribution.crypto.CryptoProvider;
+import app.coronawarn.server.services.distribution.assembly.component.CryptoProvider;
import app.coronawarn.server.services.distribution.objectstore.S3Publisher;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/crypto/CryptoProviderTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/component/CryptoProviderTest.java
similarity index 92%
rename from services/distribution/src/test/java/app/coronawarn/server/services/distribution/crypto/CryptoProviderTest.java
rename to services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/component/CryptoProviderTest.java
--- a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/crypto/CryptoProviderTest.java
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/component/CryptoProviderTest.java
@@ -1,4 +1,4 @@
-package app.coronawarn.server.services.distribution.crypto;
+package app.coronawarn.server.services.distribution.assembly.component;
import static org.junit.jupiter.api.Assertions.assertNotNull;
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/diagnosiskeys/structure/directory/DiagnosisKeysDirectoryTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysStructureProviderDirectoryTest.java
similarity index 93%
rename from services/distribution/src/test/java/app/coronawarn/server/services/distribution/diagnosiskeys/structure/directory/DiagnosisKeysDirectoryTest.java
rename to services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysStructureProviderDirectoryTest.java
--- a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/diagnosiskeys/structure/directory/DiagnosisKeysDirectoryTest.java
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysStructureProviderDirectoryTest.java
@@ -1,14 +1,14 @@
-package app.coronawarn.server.services.distribution.diagnosiskeys.structure.directory;
+package app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.directory;
import static app.coronawarn.server.services.distribution.common.Helpers.buildDiagnosisKeyForSubmissionTimestamp;
import static java.lang.String.join;
import static org.junit.jupiter.api.Assertions.assertEquals;
import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
-import app.coronawarn.server.services.distribution.crypto.CryptoProvider;
-import app.coronawarn.server.services.distribution.structure.directory.Directory;
-import app.coronawarn.server.services.distribution.structure.directory.DirectoryImpl;
-import app.coronawarn.server.services.distribution.structure.util.ImmutableStack;
+import app.coronawarn.server.services.distribution.assembly.component.CryptoProvider;
+import app.coronawarn.server.services.distribution.assembly.structure.directory.Directory;
+import app.coronawarn.server.services.distribution.assembly.structure.directory.DirectoryImpl;
+import app.coronawarn.server.services.distribution.assembly.structure.util.ImmutableStack;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
@@ -31,7 +31,7 @@
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = {CryptoProvider.class},
initializers = ConfigFileApplicationContextInitializer.class)
-public class DiagnosisKeysDirectoryTest {
+public class DiagnosisKeysStructureProviderDirectoryTest {
@Autowired
CryptoProvider cryptoProvider;
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/diagnosiskeys/util/DateTimeTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/util/DateTimeTest.java
similarity index 97%
rename from services/distribution/src/test/java/app/coronawarn/server/services/distribution/diagnosiskeys/util/DateTimeTest.java
rename to services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/util/DateTimeTest.java
--- a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/diagnosiskeys/util/DateTimeTest.java
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/util/DateTimeTest.java
@@ -1,4 +1,4 @@
-package app.coronawarn.server.services.distribution.diagnosiskeys.util;
+package app.coronawarn.server.services.distribution.assembly.diagnosiskeys.util;
import static app.coronawarn.server.services.distribution.common.Helpers.buildDiagnosisKeyForDateTime;
import static java.util.Collections.emptyList;
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/exposureconfig/ExposureConfigurationMasterFileTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/ExposureConfigurationStructureProviderMasterFileTest.java
similarity index 64%
rename from services/distribution/src/test/java/app/coronawarn/server/services/distribution/exposureconfig/ExposureConfigurationMasterFileTest.java
rename to services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/ExposureConfigurationStructureProviderMasterFileTest.java
--- a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/exposureconfig/ExposureConfigurationMasterFileTest.java
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/ExposureConfigurationStructureProviderMasterFileTest.java
@@ -1,9 +1,9 @@
-package app.coronawarn.server.services.distribution.exposureconfig;
+package app.coronawarn.server.services.distribution.assembly.exposureconfig;
import static org.junit.jupiter.api.Assertions.assertEquals;
-import app.coronawarn.server.services.distribution.exposureconfig.validation.ExposureConfigurationValidator;
-import app.coronawarn.server.services.distribution.exposureconfig.validation.ValidationResult;
+import app.coronawarn.server.services.distribution.assembly.exposureconfig.validation.ExposureConfigurationValidator;
+import app.coronawarn.server.services.distribution.assembly.exposureconfig.validation.ValidationResult;
import org.junit.jupiter.api.Test;
/**
@@ -12,7 +12,7 @@
*
* There should never be any deployment when this test is failing.
*/
-public class ExposureConfigurationMasterFileTest {
+public class ExposureConfigurationStructureProviderMasterFileTest {
private static final ValidationResult SUCCESS = new ValidationResult();
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/exposureconfig/ExposureConfigurationProviderTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/ExposureConfigurationStructureProviderProviderTest.java
similarity index 87%
rename from services/distribution/src/test/java/app/coronawarn/server/services/distribution/exposureconfig/ExposureConfigurationProviderTest.java
rename to services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/ExposureConfigurationStructureProviderProviderTest.java
--- a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/exposureconfig/ExposureConfigurationProviderTest.java
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/ExposureConfigurationStructureProviderProviderTest.java
@@ -1,4 +1,4 @@
-package app.coronawarn.server.services.distribution.exposureconfig;
+package app.coronawarn.server.services.distribution.assembly.exposureconfig;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
@@ -6,7 +6,7 @@
import app.coronawarn.server.common.protocols.internal.RiskScoreParameters;
import org.junit.jupiter.api.Test;
-public class ExposureConfigurationProviderTest {
+public class ExposureConfigurationStructureProviderProviderTest {
@Test
public void okFile() throws UnableToLoadFileException {
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/exposureconfig/validation/ExposureConfigurationValidatorTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/validation/ExposureConfigurationStructureProviderValidatorTest.java
similarity index 87%
rename from services/distribution/src/test/java/app/coronawarn/server/services/distribution/exposureconfig/validation/ExposureConfigurationValidatorTest.java
rename to services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/validation/ExposureConfigurationStructureProviderValidatorTest.java
--- a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/exposureconfig/validation/ExposureConfigurationValidatorTest.java
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/validation/ExposureConfigurationStructureProviderValidatorTest.java
@@ -1,18 +1,18 @@
-package app.coronawarn.server.services.distribution.exposureconfig.validation;
+package app.coronawarn.server.services.distribution.assembly.exposureconfig.validation;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
-import app.coronawarn.server.services.distribution.exposureconfig.ExposureConfigurationProvider;
-import app.coronawarn.server.services.distribution.exposureconfig.UnableToLoadFileException;
-import app.coronawarn.server.services.distribution.exposureconfig.validation.WeightValidationError.ErrorType;
+import app.coronawarn.server.services.distribution.assembly.exposureconfig.ExposureConfigurationProvider;
+import app.coronawarn.server.services.distribution.assembly.exposureconfig.UnableToLoadFileException;
+import app.coronawarn.server.services.distribution.assembly.exposureconfig.validation.WeightValidationError.ErrorType;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
-public class ExposureConfigurationValidatorTest {
+public class ExposureConfigurationStructureProviderValidatorTest {
private static final ValidationResult SUCCESS = new ValidationResult();
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/exposureconfig/validation/TestWithExpectedResult.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/validation/TestWithExpectedResult.java
similarity index 83%
rename from services/distribution/src/test/java/app/coronawarn/server/services/distribution/exposureconfig/validation/TestWithExpectedResult.java
rename to services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/validation/TestWithExpectedResult.java
--- a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/exposureconfig/validation/TestWithExpectedResult.java
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/exposureconfig/validation/TestWithExpectedResult.java
@@ -1,4 +1,4 @@
-package app.coronawarn.server.services.distribution.exposureconfig.validation;
+package app.coronawarn.server.services.distribution.assembly.exposureconfig.validation;
public class TestWithExpectedResult {
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/structure/WritableTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/structure/WritableTest.java
similarity index 81%
rename from services/distribution/src/test/java/app/coronawarn/server/services/distribution/structure/WritableTest.java
rename to services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/structure/WritableTest.java
--- a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/structure/WritableTest.java
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/structure/WritableTest.java
@@ -1,11 +1,11 @@
-package app.coronawarn.server.services.distribution.structure;
+package app.coronawarn.server.services.distribution.assembly.structure;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
-import app.coronawarn.server.services.distribution.structure.directory.Directory;
-import app.coronawarn.server.services.distribution.structure.directory.DirectoryImpl;
-import app.coronawarn.server.services.distribution.structure.util.ImmutableStack;
+import app.coronawarn.server.services.distribution.assembly.structure.directory.Directory;
+import app.coronawarn.server.services.distribution.assembly.structure.directory.DirectoryImpl;
+import app.coronawarn.server.services.distribution.assembly.structure.util.ImmutableStack;
import java.io.File;
import org.junit.jupiter.api.Test;
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/structure/directory/DirectoryTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/structure/directory/DirectoryTest.java
similarity index 90%
rename from services/distribution/src/test/java/app/coronawarn/server/services/distribution/structure/directory/DirectoryTest.java
rename to services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/structure/directory/DirectoryTest.java
--- a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/structure/directory/DirectoryTest.java
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/structure/directory/DirectoryTest.java
@@ -1,13 +1,13 @@
-package app.coronawarn.server.services.distribution.structure.directory;
+package app.coronawarn.server.services.distribution.assembly.structure.directory;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
-import app.coronawarn.server.services.distribution.structure.file.File;
-import app.coronawarn.server.services.distribution.structure.file.FileImpl;
-import app.coronawarn.server.services.distribution.structure.util.ImmutableStack;
+import app.coronawarn.server.services.distribution.assembly.structure.file.File;
+import app.coronawarn.server.services.distribution.assembly.structure.file.FileImpl;
+import app.coronawarn.server.services.distribution.assembly.structure.util.ImmutableStack;
import java.io.IOException;
import java.util.Set;
import org.junit.Rule;
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/structure/directory/IndexDirectoryTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/structure/directory/IndexDirectoryTest.java
similarity index 85%
rename from services/distribution/src/test/java/app/coronawarn/server/services/distribution/structure/directory/IndexDirectoryTest.java
rename to services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/structure/directory/IndexDirectoryTest.java
--- a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/structure/directory/IndexDirectoryTest.java
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/structure/directory/IndexDirectoryTest.java
@@ -1,13 +1,13 @@
-package app.coronawarn.server.services.distribution.structure.directory;
+package app.coronawarn.server.services.distribution.assembly.structure.directory;
import static org.junit.jupiter.api.Assertions.assertEquals;
-import app.coronawarn.server.services.distribution.structure.Writable;
-import app.coronawarn.server.services.distribution.structure.file.File;
-import app.coronawarn.server.services.distribution.structure.file.FileImpl;
-import app.coronawarn.server.services.distribution.structure.functional.Formatter;
-import app.coronawarn.server.services.distribution.structure.functional.IndexFunction;
-import app.coronawarn.server.services.distribution.structure.util.ImmutableStack;
+import app.coronawarn.server.services.distribution.assembly.structure.Writable;
+import app.coronawarn.server.services.distribution.assembly.structure.file.File;
+import app.coronawarn.server.services.distribution.assembly.structure.file.FileImpl;
+import app.coronawarn.server.services.distribution.assembly.structure.functional.Formatter;
+import app.coronawarn.server.services.distribution.assembly.structure.functional.IndexFunction;
+import app.coronawarn.server.services.distribution.assembly.structure.util.ImmutableStack;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/structure/directory/decorators/DirectoryDecoratorTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/structure/directory/decorators/DirectoryDecoratorTest.java
similarity index 63%
rename from services/distribution/src/test/java/app/coronawarn/server/services/distribution/structure/directory/decorators/DirectoryDecoratorTest.java
rename to services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/structure/directory/decorators/DirectoryDecoratorTest.java
--- a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/structure/directory/decorators/DirectoryDecoratorTest.java
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/structure/directory/decorators/DirectoryDecoratorTest.java
@@ -1,14 +1,14 @@
-package app.coronawarn.server.services.distribution.structure.directory.decorators;
+package app.coronawarn.server.services.distribution.assembly.structure.directory.decorators;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
-import app.coronawarn.server.services.distribution.structure.directory.Directory;
-import app.coronawarn.server.services.distribution.structure.directory.DirectoryImpl;
-import app.coronawarn.server.services.distribution.structure.directory.decorator.DirectoryDecorator;
-import app.coronawarn.server.services.distribution.structure.file.File;
-import app.coronawarn.server.services.distribution.structure.file.FileImpl;
-import app.coronawarn.server.services.distribution.structure.util.ImmutableStack;
+import app.coronawarn.server.services.distribution.assembly.structure.directory.Directory;
+import app.coronawarn.server.services.distribution.assembly.structure.directory.DirectoryImpl;
+import app.coronawarn.server.services.distribution.assembly.structure.directory.decorator.DirectoryDecorator;
+import app.coronawarn.server.services.distribution.assembly.structure.file.File;
+import app.coronawarn.server.services.distribution.assembly.structure.file.FileImpl;
+import app.coronawarn.server.services.distribution.assembly.structure.util.ImmutableStack;
import org.junit.jupiter.api.Test;
public class DirectoryDecoratorTest {
@@ -52,7 +52,7 @@ public void checkProxiesAllMethods() {
verify(decoree).getFileOnDisk();
}
- private class TestDirectoryDecorator extends DirectoryDecorator {
+ private static class TestDirectoryDecorator extends DirectoryDecorator {
protected TestDirectoryDecorator(Directory directory) {
super(directory);
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/structure/directory/decorators/IndexingDecoratorTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/structure/directory/decorators/IndexingDecoratorTest.java
similarity index 77%
rename from services/distribution/src/test/java/app/coronawarn/server/services/distribution/structure/directory/decorators/IndexingDecoratorTest.java
rename to services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/structure/directory/decorators/IndexingDecoratorTest.java
--- a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/structure/directory/decorators/IndexingDecoratorTest.java
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/structure/directory/decorators/IndexingDecoratorTest.java
@@ -1,13 +1,13 @@
-package app.coronawarn.server.services.distribution.structure.directory.decorators;
+package app.coronawarn.server.services.distribution.assembly.structure.directory.decorators;
import static app.coronawarn.server.services.distribution.common.Helpers.prepareAndWrite;
import static org.junit.jupiter.api.Assertions.assertTrue;
-import app.coronawarn.server.services.distribution.structure.directory.Directory;
-import app.coronawarn.server.services.distribution.structure.directory.DirectoryImpl;
-import app.coronawarn.server.services.distribution.structure.directory.IndexDirectory;
-import app.coronawarn.server.services.distribution.structure.directory.IndexDirectoryImpl;
-import app.coronawarn.server.services.distribution.structure.directory.decorator.IndexingDecorator;
+import app.coronawarn.server.services.distribution.assembly.structure.directory.Directory;
+import app.coronawarn.server.services.distribution.assembly.structure.directory.DirectoryImpl;
+import app.coronawarn.server.services.distribution.assembly.structure.directory.IndexDirectory;
+import app.coronawarn.server.services.distribution.assembly.structure.directory.IndexDirectoryImpl;
+import app.coronawarn.server.services.distribution.assembly.structure.directory.decorator.IndexingDecorator;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/structure/file/FileTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/structure/file/FileTest.java
similarity index 81%
rename from services/distribution/src/test/java/app/coronawarn/server/services/distribution/structure/file/FileTest.java
rename to services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/structure/file/FileTest.java
--- a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/structure/file/FileTest.java
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/structure/file/FileTest.java
@@ -1,11 +1,11 @@
-package app.coronawarn.server.services.distribution.structure.file;
+package app.coronawarn.server.services.distribution.assembly.structure.file;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
-import app.coronawarn.server.services.distribution.structure.directory.Directory;
-import app.coronawarn.server.services.distribution.structure.directory.DirectoryImpl;
+import app.coronawarn.server.services.distribution.assembly.structure.directory.Directory;
+import app.coronawarn.server.services.distribution.assembly.structure.directory.DirectoryImpl;
import java.io.IOException;
import java.nio.file.Files;
import org.junit.Rule;
@@ -15,7 +15,7 @@
public class FileTest {
- private byte[] bytes = "World".getBytes();
+ private final byte[] bytes = "World".getBytes();
private File file;
@Rule
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/structure/file/decorators/FileDecoratorTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/structure/file/decorators/FileDecoratorTest.java
similarity index 62%
rename from services/distribution/src/test/java/app/coronawarn/server/services/distribution/structure/file/decorators/FileDecoratorTest.java
rename to services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/structure/file/decorators/FileDecoratorTest.java
--- a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/structure/file/decorators/FileDecoratorTest.java
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/structure/file/decorators/FileDecoratorTest.java
@@ -1,13 +1,13 @@
-package app.coronawarn.server.services.distribution.structure.file.decorators;
+package app.coronawarn.server.services.distribution.assembly.structure.file.decorators;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
-import app.coronawarn.server.services.distribution.structure.directory.Directory;
-import app.coronawarn.server.services.distribution.structure.directory.DirectoryImpl;
-import app.coronawarn.server.services.distribution.structure.file.File;
-import app.coronawarn.server.services.distribution.structure.file.decorator.FileDecorator;
-import app.coronawarn.server.services.distribution.structure.util.ImmutableStack;
+import app.coronawarn.server.services.distribution.assembly.structure.directory.Directory;
+import app.coronawarn.server.services.distribution.assembly.structure.directory.DirectoryImpl;
+import app.coronawarn.server.services.distribution.assembly.structure.file.File;
+import app.coronawarn.server.services.distribution.assembly.structure.file.decorator.FileDecorator;
+import app.coronawarn.server.services.distribution.assembly.structure.util.ImmutableStack;
import org.junit.jupiter.api.Test;
public class FileDecoratorTest {
@@ -45,7 +45,7 @@ public void checkProxiesAllMethods() {
verify(decoree).getFileOnDisk();
}
- private class TestFileDecorator extends FileDecorator {
+ private static class TestFileDecorator extends FileDecorator {
protected TestFileDecorator(File file) {
super(file);
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/structure/file/decorators/SigningDecoratorTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/structure/file/decorators/SigningDecoratorTest.java
similarity index 84%
rename from services/distribution/src/test/java/app/coronawarn/server/services/distribution/structure/file/decorators/SigningDecoratorTest.java
rename to services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/structure/file/decorators/SigningDecoratorTest.java
--- a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/structure/file/decorators/SigningDecoratorTest.java
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/structure/file/decorators/SigningDecoratorTest.java
@@ -1,16 +1,16 @@
-package app.coronawarn.server.services.distribution.structure.file.decorators;
+package app.coronawarn.server.services.distribution.assembly.structure.file.decorators;
import static app.coronawarn.server.services.distribution.common.Helpers.prepareAndWrite;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import app.coronawarn.server.common.protocols.internal.SignedPayload;
-import app.coronawarn.server.services.distribution.crypto.CryptoProvider;
-import app.coronawarn.server.services.distribution.structure.directory.Directory;
-import app.coronawarn.server.services.distribution.structure.directory.DirectoryImpl;
-import app.coronawarn.server.services.distribution.structure.file.File;
-import app.coronawarn.server.services.distribution.structure.file.FileImpl;
-import app.coronawarn.server.services.distribution.structure.file.decorator.SigningDecorator;
+import app.coronawarn.server.services.distribution.assembly.component.CryptoProvider;
+import app.coronawarn.server.services.distribution.assembly.structure.directory.Directory;
+import app.coronawarn.server.services.distribution.assembly.structure.directory.DirectoryImpl;
+import app.coronawarn.server.services.distribution.assembly.structure.file.File;
+import app.coronawarn.server.services.distribution.assembly.structure.file.FileImpl;
+import app.coronawarn.server.services.distribution.assembly.structure.file.decorator.SigningDecorator;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/common/Helpers.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/common/Helpers.java
--- a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/common/Helpers.java
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/common/Helpers.java
@@ -1,8 +1,8 @@
package app.coronawarn.server.services.distribution.common;
import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
-import app.coronawarn.server.services.distribution.structure.directory.Directory;
-import app.coronawarn.server.services.distribution.structure.util.ImmutableStack;
+import app.coronawarn.server.services.distribution.assembly.structure.directory.Directory;
+import app.coronawarn.server.services.distribution.assembly.structure.util.ImmutableStack;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/ObjectStoreAccessTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/ObjectStoreAccessTest.java
--- a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/ObjectStoreAccessTest.java
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/ObjectStoreAccessTest.java
@@ -20,11 +20,11 @@
public class ObjectStoreAccessTest {
- private Logger logger = LoggerFactory.getLogger(this.getClass());
+ private final Logger logger = LoggerFactory.getLogger(this.getClass());
- private String testRunId = "testing/cwa/" + UUID.randomUUID().toString() + "/";
+ private final String testRunId = "testing/cwa/" + UUID.randomUUID().toString() + "/";
- private String textFile = "objectstore/store-test-file";
+ private final String textFile = "objectstore/store-test-file";
@Autowired
private ObjectStoreAccess objectStoreAccess;
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/S3PublisherTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/S3PublisherTest.java
--- a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/S3PublisherTest.java
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/objectstore/S3PublisherTest.java
@@ -23,11 +23,11 @@
@TestInstance(Lifecycle.PER_CLASS)
public class S3PublisherTest {
- private String testRunId = "testing/cwa/" + UUID.randomUUID().toString() + "/";
+ private final String testRunId = "testing/cwa/" + UUID.randomUUID().toString() + "/";
- private String rootTestFolder = "objectstore/publisher/";
+ private final String rootTestFolder = "objectstore/publisher/";
- private String exampleFile = rootTestFolder + "rootfile";
+ private final String exampleFile = rootTestFolder + "rootfile";
@Autowired
private S3Publisher s3Publisher;
diff --git a/services/distribution/src/test/resources/application.properties b/services/distribution/src/test/resources/application.properties
--- a/services/distribution/src/test/resources/application.properties
+++ b/services/distribution/src/test/resources/application.properties
@@ -3,10 +3,9 @@ logging.level.org.springframework=off
logging.level.root=off
spring.main.banner-mode=off
-app.coronawarn.server.services.distribution.retention_days=14
-app.coronawarn.server.services.distribution.version=v1
-app.coronawarn.server.services.distribution.paths.output=out
-app.coronawarn.server.services.distribution.paths.privatekey=classpath:certificates/client/private.pem
-app.coronawarn.server.services.distribution.paths.certificate=classpath:certificates/chain/certificate.crt
+services.distribution.retention_days=14
+services.distribution.paths.output=out
+services.distribution.paths.privatekey=classpath:certificates/client/private.pem
+services.distribution.paths.certificate=classpath:certificates/chain/certificate.crt
spring.flyway.enabled=false
| |||||
corona-warn-app__cwa-server-659 | You will be provided with a partial code base and an issue statement explaining a problem to resolve.
<issue>
Plausible Deniability: Add "Padding" property to submission payload
Currently, mobile apps are collecting keys based on their install date. When a user uploads his keys (after being tested positive), the payload will contain 1-13 keys. Although the traffic between mobile & server is secured, an attacker may still sniff the packages in the network and predict, based on the request size, how many keys are probably part of the submission request. This may then lead to additional information for the attacker in an attempt to deanonymize a user.
In order to mitigate this attack, add a new field to the submission payload, called `padding` of type string. The field shall be optional and must not break compatibility to the current/older mobile implementations (which should be given due to the use of protobuf). The server shall not process this field.
</issue>
<code>
[start of README.md]
1 <!-- markdownlint-disable MD041 -->
2 <h1 align="center">
3 Corona-Warn-App Server
4 </h1>
5
6 <p align="center">
7 <a href="https://github.com/corona-warn-app/cwa-server/commits/" title="Last Commit"><img src="https://img.shields.io/github/last-commit/corona-warn-app/cwa-server?style=flat"></a>
8 <a href="https://github.com/corona-warn-app/cwa-server/issues" title="Open Issues"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat"></a>
9 <a href="https://circleci.com/gh/corona-warn-app/cwa-server" title="Build Status"><img src="https://circleci.com/gh/corona-warn-app/cwa-server.svg?style=shield&circle-token=4ab059989d10709df19eb4b98ab7c121a25e981a"></a>
10 <a href="https://sonarcloud.io/dashboard?id=corona-warn-app_cwa-server" title="Quality Gate"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=alert_status"></a>
11 <a href="https://sonarcloud.io/component_measures?id=corona-warn-app_cwa-server&metric=Coverage&view=list" title="Coverage"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=coverage"></a>
12 <a href="https://github.com/corona-warn-app/cwa-server/blob/master/LICENSE" title="License"><img src="https://img.shields.io/badge/License-Apache%202.0-green.svg?style=flat"></a>
13 </p>
14
15 <p align="center">
16 <a href="#development">Development</a> •
17 <a href="#service-apis">Service APIs</a> •
18 <a href="#documentation">Documentation</a> •
19 <a href="#support-and-feedback">Support</a> •
20 <a href="#how-to-contribute">Contribute</a> •
21 <a href="#contributors">Contributors</a> •
22 <a href="#repositories">Repositories</a> •
23 <a href="#licensing">Licensing</a>
24 </p>
25
26 The goal of this project is to develop the official Corona-Warn-App for Germany based on the exposure notification API from [Apple](https://www.apple.com/covid19/contacttracing/) and [Google](https://www.google.com/covid19/exposurenotifications/). The apps (for both iOS and Android) use Bluetooth technology to exchange anonymous encrypted data with other mobile phones (on which the app is also installed) in the vicinity of an app user's phone. The data is stored locally on each user's device, preventing authorities or other parties from accessing or controlling the data. This repository contains the **implementation of the server for encryption keys** for the Corona-Warn-App.
27
28 In this documentation, Corona-Warn-App services are also referred to as CWA services.
29
30 ## Architecture Overview
31
32 You can find the architecture overview [here](/docs/ARCHITECTURE.md), which will give you
33 a good starting point in how the backend services interact with other services, and what purpose
34 they serve.
35
36 ## Development
37
38 After you've checked out this repository, you can run the application in one of the following ways:
39
40 * As a [Docker](https://www.docker.com/)-based deployment on your local machine. You can run either:
41 * Single components using the respective Dockerfile or
42 * The full backend using the Docker Compose (which is considered the most convenient way)
43 * As a [Maven](https://maven.apache.org)-based build on your local machine.
44 If you want to develop something in a single component, this approach is preferable.
45
46 ### Docker-Based Deployment
47
48 If you want to use Docker-based deployment, you need to install Docker on your local machine. For more information about downloading and installing Docker, see the [official Docker documentation](https://docs.docker.com/get-docker/).
49
50 #### Running the Full CWA Backend Using Docker Compose
51
52 For your convenience, a full setup for local development and testing purposes, including the generation of test data has been prepared using [Docker Compose](https://docs.docker.com/compose/reference/overview/). To build the backend services, run ```docker-compose build``` in the repository's root directory. A default configuration file can be found under ```.env``` in the root folder of the repository. If the endpoints are to be exposed to the network the default values in this file should be changed before docker-compose is run.
53
54 Once the services are built, you can start the whole backend using ```docker-compose up```.
55 The distribution service runs once and then finishes. If you want to trigger additional distribution runs, run ```docker-compose run distribution```.
56
57 The docker-compose contains the following services:
58
59 Service | Description | Endpoint and Default Credentials
60 ------------------|-------------|-----------
61 submission | The Corona-Warn-App submission service | `http://localhost:8000` <br> `http://localhost:8006` (for actuator endpoint)
62 distribution | The Corona-Warn-App distribution service | NO ENDPOINT
63 postgres | A [postgres] database installation | `localhost:8001` <br> `postgres:5432` (from containerized pgadmin) <br> Username: postgres <br> Password: postgres
64 pgadmin | A [pgadmin](https://www.pgadmin.org/) installation for the postgres database | `http://localhost:8002` <br> Username: [email protected] <br> Password: password
65 cloudserver | [Zenko CloudServer] is a S3-compliant object store | `http://localhost:8003/` <br> Access key: accessKey1 <br> Secret key: verySecretKey1
66 verification-fake | A very simple fake implementation for the tan verification. | `http://localhost:8004/version/v1/tan/verify` <br> The only valid tan is `edc07f08-a1aa-11ea-bb37-0242ac130002`.
67
68 ##### Known Limitation
69
70 In rare cases the docker-compose runs into a timing issue if the distribution service starts before the bucket of the objectstore was created. This is not a big issue as you can simply run ```docker-compose run distribution``` to trigger additional distribution runs after the objectstore was initialized.
71
72 #### Running Single CWA Services Using Docker
73
74 If you would like to build and run a single CWA service, it's considered easiest to run them in a Docker environment. You can do this using the script provided in the respective CWA service directory. The Docker script first builds the CWA service and then creates an image for the runtime, which means that there are no additional dependencies for you to install.
75
76 To build and run the distribution service, run the following command:
77
78 ```bash
79 ./services/distribution/build_and_run.sh
80 ```
81
82 To build and run the submission service, run the following command:
83
84 ```bash
85 ./services/submission/build_and_run.sh
86 ```
87
88 The submission service is available on [localhost:8080](http://localhost:8080 ).
89
90 ### Maven-Based Build
91
92 If you want to actively develop in one of the CWA services, the Maven-based runtime is most suitable.
93 To prepare your machine to run the CWA project locally, we recommend that you first ensure that you've installed the following:
94
95 * Minimum JDK Version 11: [OpenJDK](https://openjdk.java.net/) / [SapMachine](https://sap.github.io/SapMachine/)
96 * [Maven 3.6](https://maven.apache.org/)
97 * [Postgres]
98 * [Zenko CloudServer]
99
100 If you are already running a local Postgres, you need to create a database `cwa` and run the following setup scripts:
101
102 * Create the different CWA roles first by executing [create-roles.sql](setup/create-roles.sql).
103 * Create local database users for the specific roles by running [create-users.sql](./local-setup/create-users.sql).
104 * It is recommended to also run [enable-test-data-docker-compose.sql](./local-setup/enable-test-data-docker-compose.sql)
105 , which enables the test data generation profile. If you already had CWA running before and an existing `diagnosis-key`
106 table on your database, you need to run [enable-test-data.sql](./local-setup/enable-test-data.sql) instead.
107
108 You can also use `docker-compose` to start Postgres and Zenko. If you do that, you have to
109 set the following environment-variables when running the Spring project:
110
111 For the distribution module:
112
113 ```bash
114 POSTGRESQL_SERVICE_PORT=8001
115 VAULT_FILESIGNING_SECRET=</path/to/your/private_key>
116 SPRING_PROFILES_ACTIVE=signature-dev,disable-ssl-client-postgres
117 ```
118
119 For the submission module:
120
121 ```bash
122 POSTGRESQL_SERVICE_PORT=8001
123 SPRING_PROFILES_ACTIVE=disable-ssl-server,disable-ssl-client-postgres,disable-ssl-client-verification,disable-ssl-client-verification-verify-hostname
124 ```
125
126 #### Configure
127
128 After you made sure that the specified dependencies are running, configure them in the respective configuration files.
129
130 * Configure the Postgres connection in the [submission config](./services/submission/src/main/resources/application.yaml) and in the [distribution config](./services/distribution/src/main/resources/application.yaml)
131 * Configure the S3 compatible object storage in the [distribution config](./services/distribution/src/main/resources/application.yaml)
132 * Configure the private key for the distribution service, the path need to be prefixed with `file:`
133 * `VAULT_FILESIGNING_SECRET` should be the path to the private key, example available in `<repo-root>/docker-compose-test-secrets/private.pem`
134
135 #### Build
136
137 After you've checked out the repository, to build the project, run ```mvn install``` in your base directory.
138
139 #### Run
140
141 Navigate to the service you want to start and run the spring-boot:run target. The configured Postgres and the configured S3 compliant object storage are used as default. When you start the submission service, the endpoint is available on your local port 8080.
142
143 If you want to start the submission service, for example, you start it as follows:
144
145 ```bash
146 cd services/submission/
147 mvn spring-boot:run
148 ```
149
150 #### Debugging
151
152 To enable the `DEBUG` log level, you can run the application using the Spring `dev` profile.
153
154 ```bash
155 mvn spring-boot:run -Dspring.profiles.active=dev
156 ```
157
158 To be able to set breakpoints (e.g. in IntelliJ), it may be necessary to use the ```-Dspring-boot.run.fork=false``` parameter.
159
160 ## Service APIs
161
162 The API that is being exposed by the backend services is documented in an [OpenAPI](https://www.openapis.org/) specification. The specification files are available at the following locations:
163
164 Service | OpenAPI Specification
165 --------------------------|-------------
166 Submission Service | [services/submission/api_v1.json](https://github.com/corona-warn-app/cwa-server/raw/master/services/submission/api_v1.json)
167 Distribution Service | [services/distribution/api_v1.json](https://github.com/corona-warn-app/cwa-server/raw/master/services/distribution/api_v1.json)
168
169 ## Spring Profiles
170
171 ### Distribution
172
173 See [Distribution Service - Spring Profiles](/docs/DISTRIBUTION.md#spring-profiles).
174
175 ### Submission
176
177 See [Submission Service - Spring Profiles](/docs/SUBMISSION.md#spring-profiles).
178
179 ## Documentation
180
181 The full documentation for the Corona-Warn-App can be found in the [cwa-documentation](https://github.com/corona-warn-app/cwa-documentation) repository. The documentation repository contains technical documents, architecture information, and whitepapers related to this implementation.
182
183 The documentation for cwa-server can be found under the [/docs](./docs) folder.
184
185 The JavaDoc documentation for cwa-server is hosted by Github Pages at [https://corona-warn-app.github.io/cwa-server](https://corona-warn-app.github.io/cwa-server).
186
187 ## Support and Feedback
188
189 The following channels are available for discussions, feedback, and support requests:
190
191 | Type | Channel |
192 | ------------------------ | ------------------------------------------------------ |
193 | **General Discussion** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="General Discussion"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/question.svg?style=flat-square"></a> </a> |
194 | **Concept Feedback** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="Open Concept Feedback"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/architecture.svg?style=flat-square"></a> |
195 | **Backend Issue** | <a href="https://github.com/corona-warn-app/cwa-server/issues/new/choose" title="Open Backend Issue"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat-square"></a> |
196 | **Other Requests** | <a href="mailto:[email protected]" title="Email CWA Team"><img src="https://img.shields.io/badge/email-CWA%20team-green?logo=mail.ru&style=flat-square&logoColor=white"></a> |
197
198 ## How to Contribute
199
200 Contribution and feedback are 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.
201
202 ## Contributors
203
204 The German government has asked SAP and Deutsche Telekom to develop the Corona-Warn-App for Germany as open source software. Deutsche Telekom is providing the network and mobile technology and will operate and run the backend for the app in a safe, scalable and stable manner. SAP is responsible for the app development, its framework and the underlying platform. Therefore, development teams of SAP and Deutsche Telekom are contributing to this project. At the same time 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.
205
206 ## Repositories
207
208 The following public repositories are currently available for the Corona-Warn-App:
209
210 | Repository | Description |
211 | ------------------- | --------------------------------------------------------------------- |
212 | [cwa-documentation] | Project overview, general documentation, and white papers |
213 | [cwa-server] | Backend implementation for the Apple/Google exposure notification API|
214 | [cwa-verification-server] | Backend implementation of the verification process|
215
216 [cwa-documentation]: https://github.com/corona-warn-app/cwa-documentation
217 [cwa-server]: https://github.com/corona-warn-app/cwa-server
218 [cwa-verification-server]: https://github.com/corona-warn-app/cwa-verification-server
219 [Postgres]: https://www.postgresql.org/
220 [HSQLDB]: http://hsqldb.org/
221 [Zenko CloudServer]: https://github.com/scality/cloudserver
222
223 ## Licensing
224
225 Copyright (c) 2020 SAP SE or an SAP affiliate company.
226
227 Licensed under the **Apache License, Version 2.0** (the "License"); you may not use this file except in compliance with the License.
228
229 You may obtain a copy of the License at <https://www.apache.org/licenses/LICENSE-2.0>.
230
231 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.
232
[end of README.md]
[start of /dev/null]
1
[end of /dev/null]
[start of common/protocols/src/main/proto/app/coronawarn/server/common/protocols/internal/submission_payload.proto]
1 syntax = "proto3";
2 package app.coronawarn.server.common.protocols.internal;
3 option java_package = "app.coronawarn.server.common.protocols.internal";
4 option java_multiple_files = true;
5 import "app/coronawarn/server/common/protocols/external/exposurenotification/temporary_exposure_key_export.proto";
6
7 message SubmissionPayload {
8 repeated app.coronawarn.server.common.protocols.external.exposurenotification.TemporaryExposureKey keys = 1;
9 }
[end of common/protocols/src/main/proto/app/coronawarn/server/common/protocols/internal/submission_payload.proto]
[start of services/submission/src/main/java/app/coronawarn/server/services/submission/ServerApplication.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.submission;
22
23 import io.micrometer.core.aop.TimedAspect;
24 import io.micrometer.core.instrument.MeterRegistry;
25 import java.util.Arrays;
26 import java.util.List;
27 import org.apache.logging.log4j.LogManager;
28 import org.slf4j.Logger;
29 import org.slf4j.LoggerFactory;
30 import org.springframework.beans.factory.DisposableBean;
31 import org.springframework.boot.SpringApplication;
32 import org.springframework.boot.autoconfigure.SpringBootApplication;
33 import org.springframework.boot.autoconfigure.domain.EntityScan;
34 import org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration;
35 import org.springframework.boot.context.properties.EnableConfigurationProperties;
36 import org.springframework.cloud.openfeign.EnableFeignClients;
37 import org.springframework.context.EnvironmentAware;
38 import org.springframework.context.annotation.Bean;
39 import org.springframework.context.annotation.ComponentScan;
40 import org.springframework.core.env.Environment;
41 import org.springframework.data.jdbc.repository.config.EnableJdbcRepositories;
42 import org.springframework.http.converter.protobuf.ProtobufHttpMessageConverter;
43
44 @SpringBootApplication(exclude = {UserDetailsServiceAutoConfiguration.class})
45 @EnableJdbcRepositories(basePackages = "app.coronawarn.server.common.persistence")
46 @EntityScan(basePackages = "app.coronawarn.server.common.persistence")
47 @ComponentScan({"app.coronawarn.server.common.persistence",
48 "app.coronawarn.server.services.submission"})
49 @EnableConfigurationProperties
50 @EnableFeignClients
51 public class ServerApplication implements EnvironmentAware, DisposableBean {
52
53 private static final Logger logger = LoggerFactory.getLogger(ServerApplication.class);
54
55 public static void main(String[] args) {
56 SpringApplication.run(ServerApplication.class);
57 }
58
59 @Bean
60 TimedAspect timedAspect(MeterRegistry registry) {
61 return new TimedAspect(registry);
62 }
63
64 /**
65 * Manual shutdown hook needed to avoid Log4j shutdown issues (see cwa-server/#589).
66 */
67 @Override
68 public void destroy() {
69 LogManager.shutdown();
70 }
71
72 @Bean
73 ProtobufHttpMessageConverter protobufHttpMessageConverter() {
74 return new ProtobufHttpMessageConverter();
75 }
76
77 @Override
78 public void setEnvironment(Environment environment) {
79 List<String> profiles = Arrays.asList(environment.getActiveProfiles());
80
81 logger.info("Enabled named groups: {}", System.getProperty("jdk.tls.namedGroups"));
82 if (profiles.contains("disable-ssl-server")) {
83 logger.warn(
84 "The submission service is started with endpoint TLS disabled. This should never be used in PRODUCTION!");
85 }
86 if (profiles.contains("disable-ssl-client-postgres")) {
87 logger.warn(
88 "The submission service is started with postgres connection TLS disabled. "
89 + "This should never be used in PRODUCTION!");
90 }
91 if (profiles.contains("disable-ssl-client-verification")) {
92 logger.warn(
93 "The submission service is started with verification service connection TLS disabled. "
94 + "This should never be used in PRODUCTION!");
95 }
96 if (profiles.contains("disable-ssl-client-verification-verify-hostname")) {
97 logger.warn(
98 "The submission service is started with verification service TLS hostname validation disabled. "
99 + "This should never be used in PRODUCTION!");
100 }
101 }
102 }
103
[end of services/submission/src/main/java/app/coronawarn/server/services/submission/ServerApplication.java]
[start of services/submission/src/main/java/app/coronawarn/server/services/submission/config/SubmissionServiceConfig.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.submission.config;
22
23 import java.io.File;
24 import javax.validation.constraints.Max;
25 import javax.validation.constraints.Min;
26 import javax.validation.constraints.Pattern;
27 import org.springframework.boot.context.properties.ConfigurationProperties;
28 import org.springframework.stereotype.Component;
29 import org.springframework.validation.annotation.Validated;
30
31 @Component
32 @ConfigurationProperties(prefix = "services.submission")
33 @Validated
34 public class SubmissionServiceConfig {
35
36 private static final String PATH_REGEX = "^[/]?[a-zA-Z0-9_]+[/[a-zA-Z0-9_]+]*$";
37 private static final String URL_WITH_PORT_REGEX = "^http[s]?://[a-z0-9-]+(\\.[a-z0-9-]+)*(:[0-9]{2,6})?$";
38
39 // Exponential moving average of the last N real request durations (in ms), where
40 // N = fakeDelayMovingAverageSamples.
41 @Min(1)
42 @Max(3000)
43 private Long initialFakeDelayMilliseconds;
44 @Min(1)
45 @Max(100)
46 private Long fakeDelayMovingAverageSamples;
47 @Min(7)
48 @Max(28)
49 private Integer retentionDays;
50 @Min(1)
51 @Max(25)
52 private Integer randomKeyPaddingMultiplier;
53 @Min(1)
54 @Max(10000)
55 private Integer connectionPoolSize;
56 private Payload payload;
57 private Verification verification;
58 private Monitoring monitoring;
59 private Client client;
60
61 public Long getInitialFakeDelayMilliseconds() {
62 return initialFakeDelayMilliseconds;
63 }
64
65 public void setInitialFakeDelayMilliseconds(Long initialFakeDelayMilliseconds) {
66 this.initialFakeDelayMilliseconds = initialFakeDelayMilliseconds;
67 }
68
69 public Long getFakeDelayMovingAverageSamples() {
70 return fakeDelayMovingAverageSamples;
71 }
72
73 public void setFakeDelayMovingAverageSamples(Long fakeDelayMovingAverageSamples) {
74 this.fakeDelayMovingAverageSamples = fakeDelayMovingAverageSamples;
75 }
76
77 public Integer getRetentionDays() {
78 return retentionDays;
79 }
80
81 public void setRetentionDays(Integer retentionDays) {
82 this.retentionDays = retentionDays;
83 }
84
85 public Integer getRandomKeyPaddingMultiplier() {
86 return randomKeyPaddingMultiplier;
87 }
88
89 public void setRandomKeyPaddingMultiplier(Integer randomKeyPaddingMultiplier) {
90 this.randomKeyPaddingMultiplier = randomKeyPaddingMultiplier;
91 }
92
93 public Integer getConnectionPoolSize() {
94 return connectionPoolSize;
95 }
96
97 public void setConnectionPoolSize(Integer connectionPoolSize) {
98 this.connectionPoolSize = connectionPoolSize;
99 }
100
101 public Integer getMaxNumberOfKeys() {
102 return payload.getMaxNumberOfKeys();
103 }
104
105 public void setPayload(Payload payload) {
106 this.payload = payload;
107 }
108
109 private static class Payload {
110
111 @Min(7)
112 @Max(28)
113 private Integer maxNumberOfKeys;
114
115 public Integer getMaxNumberOfKeys() {
116 return maxNumberOfKeys;
117 }
118
119 public void setMaxNumberOfKeys(Integer maxNumberOfKeys) {
120 this.maxNumberOfKeys = maxNumberOfKeys;
121 }
122 }
123
124 public String getVerificationBaseUrl() {
125 return verification.getBaseUrl();
126 }
127
128 public void setVerification(Verification verification) {
129 this.verification = verification;
130 }
131
132 public String getVerificationPath() {
133 return verification.getPath();
134 }
135
136 private static class Verification {
137
138 @Pattern(regexp = URL_WITH_PORT_REGEX)
139 private String baseUrl;
140
141 @Pattern(regexp = PATH_REGEX)
142 private String path;
143
144 public String getBaseUrl() {
145 return baseUrl;
146 }
147
148 public String getPath() {
149 return path;
150 }
151
152 public void setBaseUrl(String baseUrl) {
153 this.baseUrl = baseUrl;
154 }
155
156 public void setPath(String path) {
157 this.path = path;
158 }
159 }
160
161 private static class Monitoring {
162
163 @Min(1)
164 @Max(1000)
165 private Long batchSize;
166
167 public Long getBatchSize() {
168 return batchSize;
169 }
170
171 public void setBatchSize(Long batchSize) {
172 this.batchSize = batchSize;
173 }
174 }
175
176 public Monitoring getMonitoring() {
177 return monitoring;
178 }
179
180 public void setMonitoring(Monitoring monitoring) {
181 this.monitoring = monitoring;
182 }
183
184 public Long getMonitoringBatchSize() {
185 return this.monitoring.getBatchSize();
186 }
187
188 public void setMonitoringBatchSize(Long batchSize) {
189 this.monitoring.setBatchSize(batchSize);
190 }
191
192 public Client getClient() {
193 return client;
194 }
195
196 public void setClient(Client client) {
197 this.client = client;
198 }
199
200 public static class Client {
201
202 private Ssl ssl;
203
204 public Ssl getSsl() {
205 return ssl;
206 }
207
208 public void setSsl(Ssl ssl) {
209 this.ssl = ssl;
210 }
211
212 public static class Ssl {
213
214 private File keyStore;
215 private String keyStorePassword;
216 private String keyPassword;
217 private File trustStore;
218 private String trustStorePassword;
219
220 public File getKeyStore() {
221 return keyStore;
222 }
223
224 public void setKeyStore(File keyStore) {
225 this.keyStore = keyStore;
226 }
227
228 public String getKeyStorePassword() {
229 return keyStorePassword;
230 }
231
232 public void setKeyStorePassword(String keyStorePassword) {
233 this.keyStorePassword = keyStorePassword;
234 }
235
236 public String getKeyPassword() {
237 return keyPassword;
238 }
239
240 public void setKeyPassword(String keyPassword) {
241 this.keyPassword = keyPassword;
242 }
243
244 public File getTrustStore() {
245 return trustStore;
246 }
247
248 public void setTrustStore(File trustStore) {
249 this.trustStore = trustStore;
250 }
251
252 public String getTrustStorePassword() {
253 return trustStorePassword;
254 }
255
256 public void setTrustStorePassword(String trustStorePassword) {
257 this.trustStorePassword = trustStorePassword;
258 }
259 }
260 }
261 }
262
[end of services/submission/src/main/java/app/coronawarn/server/services/submission/config/SubmissionServiceConfig.java]
[start of services/submission/src/main/resources/application.yaml]
1 ---
2 logging:
3 level:
4 org:
5 springframework:
6 web: INFO
7 app:
8 coronawarn: INFO
9
10 services:
11 submission:
12 # The initial value of the moving average for fake request delays.
13 initial-fake-delay-milliseconds: 10
14 # The number of samples for the calculation of the moving average for fake request delays.
15 fake-delay-moving-average-samples: 10
16 # The retention threshold for acceptable diagnosis keys during submission.
17 retention-days: 14
18 # The number of keys to save to the DB for every real submitted key.
19 # Example: If the 'random-key-padding-multiplier' is set to 10, and 5 keys are being submitted,
20 # then the 5 real submitted keys will be saved to the DB, plus an additional 45 keys with
21 # random 'key_data'. All properties, besides the 'key_data', of the additional keys will be
22 # identical to the real key.
23 random-key-padding-multiplier: ${RANDOM_KEY_PADDING_MULTIPLIER:1}
24 # The ApacheHttpClient's connection pool size.
25 connection-pool-size: 200
26 payload:
27 # The maximum number of keys accepted for any submission.
28 max-number-of-keys: 14
29 verification:
30 base-url: ${VERIFICATION_BASE_URL:http://localhost:8004}
31 path: /version/v1/tan/verify
32 monitoring:
33 # The batch size (number of requests) to use for monitoring request count.
34 batch-size: 5
35 client:
36 ssl:
37 key-password: ${SSL_SUBMISSION_KEYSTORE_PASSWORD}
38 key-store: ${SSL_SUBMISSION_KEYSTORE_PATH}
39 key-store-password: ${SSL_SUBMISSION_KEYSTORE_PASSWORD}
40 trust-store: ${SSL_VERIFICATION_TRUSTSTORE_PATH}
41 trust-store-password: ${SSL_VERIFICATION_TRUSTSTORE_PASSWORD}
42
43 spring:
44 lifecycle:
45 # keep in sync or lower than the kubernetes setting 'terminationGracePeriodSeconds'
46 # 5s +5s Feign client + 20s DB timeout
47 timeout-per-shutdown-phase: 30s
48 transaction:
49 default-timeout: 20
50 flyway:
51 enabled: true
52 locations: classpath:/db/migration, classpath:/db/specific/{vendor}
53 password: ${POSTGRESQL_PASSWORD_FLYWAY:local_setup_flyway}
54 user: ${POSTGRESQL_USER_FLYWAY:local_setup_flyway}
55 # Postgres configuration
56 datasource:
57 driver-class-name: org.postgresql.Driver
58 url: jdbc:postgresql://${POSTGRESQL_SERVICE_HOST}:${POSTGRESQL_SERVICE_PORT}/${POSTGRESQL_DATABASE}?ssl=true&sslmode=verify-full&sslrootcert=${SSL_POSTGRES_CERTIFICATE_PATH}&sslcert=${SSL_SUBMISSION_CERTIFICATE_PATH}&sslkey=${SSL_SUBMISSION_PRIVATE_KEY_PATH}
59 username: ${POSTGRESQL_USER_SUBMISSION:local_setup_submission}
60 password: ${POSTGRESQL_PASSWORD_SUBMISSION:local_setup_submission}
61
62 # Actuator configuration
63 management:
64 server:
65 port: 8081
66 endpoint:
67 metrics:
68 enabled: true
69 prometheus:
70 enabled: true
71 health:
72 group:
73 readiness:
74 include: db, verificationService
75 show-details: always
76 endpoints:
77 web:
78 exposure:
79 include: 'health, prometheus'
80 metrics:
81 export:
82 prometheus:
83 enabled: true
84 health:
85 probes:
86 enabled: true
87
88 server:
89 shutdown: graceful
90 ssl:
91 enabled: true
92 enabled-protocols: TLSv1.2,TLSv1.3
93 protocol: TLS
94 ciphers: >-
95 TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
96 TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384
97 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
98 TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384
99 TLS_DHE_DSS_WITH_AES_128_GCM_SHA256
100 TLS_DHE_DSS_WITH_AES_256_GCM_SHA384
101 TLS_DHE_RSA_WITH_AES_128_GCM_SHA256
102 TLS_DHE_RSA_WITH_AES_256_GCM_SHA384
103 TLS_AES_128_GCM_SHA256
104 TLS_AES_256_GCM_SHA384
105 TLS_AES_128_CCM_SHA256
106 key-password: ${SSL_SUBMISSION_KEYSTORE_PASSWORD}
107 key-store: ${SSL_SUBMISSION_KEYSTORE_PATH}
108 key-store-password: ${SSL_SUBMISSION_KEYSTORE_PASSWORD}
109 key-store-provider: SUN
110 key-store-type: JKS
111
112 feign:
113 client:
114 config:
115 default:
116 connect-timeout: 5000
117 read-timeout: 5000
[end of services/submission/src/main/resources/application.yaml]
</code>
Here is an example of a patch file. It consists of changes to the code base. It specifies the file names, the line numbers of each change, and the removed and added lines. A single patch file can contain changes to multiple files.
<patch>
--- a/file.py
+++ b/file.py
@@ -1,27 +1,35 @@
def euclidean(a, b):
- while b:
- a, b = b, a % b
- return a
+ if b == 0:
+ return a
+ return euclidean(b, a % b)
def bresenham(x0, y0, x1, y1):
points = []
dx = abs(x1 - x0)
dy = abs(y1 - y0)
- sx = 1 if x0 < x1 else -1
- sy = 1 if y0 < y1 else -1
- err = dx - dy
+ x, y = x0, y0
+ sx = -1 if x0 > x1 else 1
+ sy = -1 if y0 > y1 else 1
- while True:
- points.append((x0, y0))
- if x0 == x1 and y0 == y1:
- break
- e2 = 2 * err
- if e2 > -dy:
+ if dx > dy:
+ err = dx / 2.0
+ while x != x1:
+ points.append((x, y))
err -= dy
- x0 += sx
- if e2 < dx:
- err += dx
- y0 += sy
+ if err < 0:
+ y += sy
+ err += dx
+ x += sx
+ else:
+ err = dy / 2.0
+ while y != y1:
+ points.append((x, y))
+ err -= dx
+ if err < 0:
+ x += sx
+ err += dy
+ y += sy
+ points.append((x, y))
return points
</patch>
I need you to solve the provded issue by generating a single patch file that I can apply directly to this repository using git apply. Please respond with a single patch file in the format shown above.
Respond below:
| corona-warn-app/cwa-server | ee78bf15ece7f282836149b5f39422892f055096 | Plausible Deniability: Add "Padding" property to submission payload
Currently, mobile apps are collecting keys based on their install date. When a user uploads his keys (after being tested positive), the payload will contain 1-13 keys. Although the traffic between mobile & server is secured, an attacker may still sniff the packages in the network and predict, based on the request size, how many keys are probably part of the submission request. This may then lead to additional information for the attacker in an attempt to deanonymize a user.
In order to mitigate this attack, add a new field to the submission payload, called `padding` of type string. The field shall be optional and must not break compatibility to the current/older mobile implementations (which should be given due to the use of protobuf). The server shall not process this field.
| 2020-07-10T07:37:14 | <patch>
diff --git a/common/protocols/src/main/proto/app/coronawarn/server/common/protocols/internal/submission_payload.proto b/common/protocols/src/main/proto/app/coronawarn/server/common/protocols/internal/submission_payload.proto
--- a/common/protocols/src/main/proto/app/coronawarn/server/common/protocols/internal/submission_payload.proto
+++ b/common/protocols/src/main/proto/app/coronawarn/server/common/protocols/internal/submission_payload.proto
@@ -6,4 +6,5 @@ import "app/coronawarn/server/common/protocols/external/exposurenotification/tem
message SubmissionPayload {
repeated app.coronawarn.server.common.protocols.external.exposurenotification.TemporaryExposureKey keys = 1;
-}
\ No newline at end of file
+ bytes padding = 2;
+}
diff --git a/services/submission/src/main/java/app/coronawarn/server/services/submission/ServerApplication.java b/services/submission/src/main/java/app/coronawarn/server/services/submission/ServerApplication.java
--- a/services/submission/src/main/java/app/coronawarn/server/services/submission/ServerApplication.java
+++ b/services/submission/src/main/java/app/coronawarn/server/services/submission/ServerApplication.java
@@ -20,6 +20,7 @@
package app.coronawarn.server.services.submission;
+import app.coronawarn.server.services.submission.config.SubmissionServiceConfigValidator;
import io.micrometer.core.aop.TimedAspect;
import io.micrometer.core.instrument.MeterRegistry;
import java.util.Arrays;
@@ -40,6 +41,7 @@
import org.springframework.core.env.Environment;
import org.springframework.data.jdbc.repository.config.EnableJdbcRepositories;
import org.springframework.http.converter.protobuf.ProtobufHttpMessageConverter;
+import org.springframework.validation.Validator;
@SpringBootApplication(exclude = {UserDetailsServiceAutoConfiguration.class})
@EnableJdbcRepositories(basePackages = "app.coronawarn.server.common.persistence")
@@ -74,6 +76,11 @@ ProtobufHttpMessageConverter protobufHttpMessageConverter() {
return new ProtobufHttpMessageConverter();
}
+ @Bean
+ public static Validator configurationPropertiesValidator() {
+ return new SubmissionServiceConfigValidator();
+ }
+
@Override
public void setEnvironment(Environment environment) {
List<String> profiles = Arrays.asList(environment.getActiveProfiles());
diff --git a/services/submission/src/main/java/app/coronawarn/server/services/submission/config/SubmissionPayloadSizeFilter.java b/services/submission/src/main/java/app/coronawarn/server/services/submission/config/SubmissionPayloadSizeFilter.java
new file mode 100644
--- /dev/null
+++ b/services/submission/src/main/java/app/coronawarn/server/services/submission/config/SubmissionPayloadSizeFilter.java
@@ -0,0 +1,58 @@
+/*-
+ * ---license-start
+ * Corona-Warn-App
+ * ---
+ * Copyright (C) 2020 SAP SE and all other contributors
+ * ---
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://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 for the specific language governing permissions and
+ * limitations under the License.
+ * ---license-end
+ */
+
+package app.coronawarn.server.services.submission.config;
+
+import java.io.IOException;
+import javax.servlet.FilterChain;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import org.springframework.http.HttpStatus;
+import org.springframework.stereotype.Component;
+import org.springframework.web.filter.OncePerRequestFilter;
+
+/**
+ * {@link SubmissionPayloadSizeFilter} instances filter requests exceeding a certain size limit.
+ */
+@Component
+public class SubmissionPayloadSizeFilter extends OncePerRequestFilter {
+
+ private final long maximumRequestSize;
+
+ public SubmissionPayloadSizeFilter(SubmissionServiceConfig config) {
+ this.maximumRequestSize = config.getMaximumRequestSize().toBytes();
+ }
+
+ /**
+ * Filters each request that exceeds the maximum size.
+ */
+ @Override
+ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
+ throws ServletException, IOException {
+ if (request.getContentLengthLong() > maximumRequestSize) {
+ response.setStatus(HttpStatus.BAD_REQUEST.value());
+ response.getWriter().write("Request size exceeded limit of " + maximumRequestSize + " bytes");
+ } else {
+ filterChain.doFilter(request, response);
+ }
+ }
+
+}
diff --git a/services/submission/src/main/java/app/coronawarn/server/services/submission/config/SubmissionServiceConfig.java b/services/submission/src/main/java/app/coronawarn/server/services/submission/config/SubmissionServiceConfig.java
--- a/services/submission/src/main/java/app/coronawarn/server/services/submission/config/SubmissionServiceConfig.java
+++ b/services/submission/src/main/java/app/coronawarn/server/services/submission/config/SubmissionServiceConfig.java
@@ -26,6 +26,7 @@
import javax.validation.constraints.Pattern;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
+import org.springframework.util.unit.DataSize;
import org.springframework.validation.annotation.Validated;
@Component
@@ -53,6 +54,7 @@ public class SubmissionServiceConfig {
@Min(1)
@Max(10000)
private Integer connectionPoolSize;
+ private DataSize maximumRequestSize;
private Payload payload;
private Verification verification;
private Monitoring monitoring;
@@ -98,6 +100,14 @@ public void setConnectionPoolSize(Integer connectionPoolSize) {
this.connectionPoolSize = connectionPoolSize;
}
+ public DataSize getMaximumRequestSize() {
+ return maximumRequestSize;
+ }
+
+ public void setMaximumRequestSize(DataSize maximumRequestSize) {
+ this.maximumRequestSize = maximumRequestSize;
+ }
+
public Integer getMaxNumberOfKeys() {
return payload.getMaxNumberOfKeys();
}
diff --git a/services/submission/src/main/java/app/coronawarn/server/services/submission/config/SubmissionServiceConfigValidator.java b/services/submission/src/main/java/app/coronawarn/server/services/submission/config/SubmissionServiceConfigValidator.java
new file mode 100644
--- /dev/null
+++ b/services/submission/src/main/java/app/coronawarn/server/services/submission/config/SubmissionServiceConfigValidator.java
@@ -0,0 +1,54 @@
+/*-
+ * ---license-start
+ * Corona-Warn-App
+ * ---
+ * Copyright (C) 2020 SAP SE and all other contributors
+ * ---
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://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 for the specific language governing permissions and
+ * limitations under the License.
+ * ---license-end
+ */
+
+package app.coronawarn.server.services.submission.config;
+
+import org.springframework.util.unit.DataSize;
+import org.springframework.validation.Errors;
+import org.springframework.validation.Validator;
+
+/**
+ * {@link SubmissionPayloadSizeFilter} instances validate the values of the SubmissionServiceConfig.
+ */
+public class SubmissionServiceConfigValidator implements Validator {
+
+ public static final DataSize MIN_MAXIMUM_REQUEST_SIZE = DataSize.ofBytes(280);
+ public static final DataSize MAX_MAXIMUM_REQUEST_SIZE = DataSize.ofKilobytes(200);
+
+ @Override
+ public boolean supports(Class<?> type) {
+ return type == SubmissionServiceConfig.class;
+ }
+
+ /**
+ * Validate if the MaximumRequestSize of the {@link SubmissionServiceConfig} is in the defined range.
+ */
+ @Override
+ public void validate(Object o, Errors errors) {
+ SubmissionServiceConfig properties = (SubmissionServiceConfig) o;
+
+ if (properties.getMaximumRequestSize().compareTo(MIN_MAXIMUM_REQUEST_SIZE) < 0
+ || properties.getMaximumRequestSize().compareTo(MAX_MAXIMUM_REQUEST_SIZE) > 0) {
+ errors.rejectValue("maximumRequestSize",
+ "Must be at least " + MIN_MAXIMUM_REQUEST_SIZE + " and not more than " + MAX_MAXIMUM_REQUEST_SIZE + ".");
+ }
+ }
+
+}
diff --git a/services/submission/src/main/resources/application.yaml b/services/submission/src/main/resources/application.yaml
--- a/services/submission/src/main/resources/application.yaml
+++ b/services/submission/src/main/resources/application.yaml
@@ -23,6 +23,8 @@ services:
random-key-padding-multiplier: ${RANDOM_KEY_PADDING_MULTIPLIER:1}
# The ApacheHttpClient's connection pool size.
connection-pool-size: 200
+ # The maximum request size accepted by the SubmissionController (e.g. 200B or 100KB).
+ maximum-request-size: ${MAXIMUM_REQUEST_SIZE:100KB}
payload:
# The maximum number of keys accepted for any submission.
max-number-of-keys: 14
</patch> | diff --git a/services/submission/src/test/java/app/coronawarn/server/services/submission/config/SubmissionServiceConfigValidatorTest.java b/services/submission/src/test/java/app/coronawarn/server/services/submission/config/SubmissionServiceConfigValidatorTest.java
new file mode 100644
--- /dev/null
+++ b/services/submission/src/test/java/app/coronawarn/server/services/submission/config/SubmissionServiceConfigValidatorTest.java
@@ -0,0 +1,86 @@
+/*-
+ * ---license-start
+ * Corona-Warn-App
+ * ---
+ * Copyright (C) 2020 SAP SE and all other contributors
+ * ---
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://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 for the specific language governing permissions and
+ * limitations under the License.
+ * ---license-end
+ */
+
+package app.coronawarn.server.services.submission.config;
+
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.test.context.ActiveProfiles;
+import org.springframework.util.unit.DataSize;
+import org.springframework.validation.BeanPropertyBindingResult;
+import org.springframework.validation.Errors;
+import java.util.stream.Stream;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
+@ActiveProfiles({"disable-ssl-client-verification", "disable-ssl-client-verification-verify-hostname"})
+class SubmissionServiceConfigValidatorTest {
+
+ @Autowired
+ private SubmissionServiceConfigValidator submissionServiceConfigValidator;
+
+ private SubmissionServiceConfig submissionServiceConfig;
+
+ @BeforeEach
+ void setup() {
+ submissionServiceConfig = new SubmissionServiceConfig();
+ }
+
+ @ParameterizedTest
+ @MethodSource("validRequestDataSizes")
+ void ok(DataSize dataSize) {
+ Errors errors = validateConfig(dataSize);
+ assertThat(errors.hasErrors()).isFalse();
+ }
+
+ @ParameterizedTest
+ @MethodSource("invalidRequestDataSizes")
+ void fail(DataSize dataSize) {
+ Errors errors = validateConfig(dataSize);
+ assertThat(errors.hasErrors()).isTrue();
+ }
+
+ private Errors validateConfig(DataSize dataSize) {
+ Errors errors = new BeanPropertyBindingResult(submissionServiceConfig, "submissionServiceConfig");
+ submissionServiceConfig.setMaximumRequestSize(dataSize);
+ submissionServiceConfigValidator.validate(submissionServiceConfig, errors);
+ return errors;
+ }
+
+ private static Stream<Arguments> validRequestDataSizes() {
+ return Stream.of(
+ SubmissionServiceConfigValidator.MAX_MAXIMUM_REQUEST_SIZE,
+ SubmissionServiceConfigValidator.MIN_MAXIMUM_REQUEST_SIZE
+ ).map(Arguments::of);
+ }
+
+ private static Stream<Arguments> invalidRequestDataSizes() {
+ return Stream.of(
+ DataSize.ofBytes(SubmissionServiceConfigValidator.MAX_MAXIMUM_REQUEST_SIZE.toBytes() + 1),
+ DataSize.ofBytes(SubmissionServiceConfigValidator.MIN_MAXIMUM_REQUEST_SIZE.toBytes() - 1)
+ ).map(Arguments::of);
+ }
+}
diff --git a/services/submission/src/test/java/app/coronawarn/server/services/submission/controller/RequestExecutor.java b/services/submission/src/test/java/app/coronawarn/server/services/submission/controller/RequestExecutor.java
--- a/services/submission/src/test/java/app/coronawarn/server/services/submission/controller/RequestExecutor.java
+++ b/services/submission/src/test/java/app/coronawarn/server/services/submission/controller/RequestExecutor.java
@@ -62,6 +62,10 @@ public ResponseEntity<Void> execute(HttpMethod method, RequestEntity<SubmissionP
public ResponseEntity<Void> executePost(Collection<TemporaryExposureKey> keys, HttpHeaders headers) {
SubmissionPayload body = SubmissionPayload.newBuilder().addAllKeys(keys).build();
+ return executePost(body, headers);
+ }
+
+ public ResponseEntity<Void> executePost(SubmissionPayload body, HttpHeaders headers) {
return execute(HttpMethod.POST, new RequestEntity<>(body, headers, HttpMethod.POST, SUBMISSION_URL));
}
diff --git a/services/submission/src/test/java/app/coronawarn/server/services/submission/controller/SubmissionControllerTest.java b/services/submission/src/test/java/app/coronawarn/server/services/submission/controller/SubmissionControllerTest.java
--- a/services/submission/src/test/java/app/coronawarn/server/services/submission/controller/SubmissionControllerTest.java
+++ b/services/submission/src/test/java/app/coronawarn/server/services/submission/controller/SubmissionControllerTest.java
@@ -45,9 +45,12 @@
import static org.springframework.http.HttpStatus.METHOD_NOT_ALLOWED;
import static org.springframework.http.HttpStatus.OK;
+
import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
import app.coronawarn.server.common.persistence.service.DiagnosisKeyService;
import app.coronawarn.server.common.protocols.external.exposurenotification.TemporaryExposureKey;
+import app.coronawarn.server.common.protocols.internal.SubmissionPayload;
+import app.coronawarn.server.services.submission.config.SubmissionPayloadSizeFilter;
import app.coronawarn.server.services.submission.config.SubmissionServiceConfig;
import app.coronawarn.server.services.submission.monitoring.SubmissionMonitor;
import app.coronawarn.server.services.submission.verification.TanVerifier;
@@ -104,7 +107,13 @@ public void setUpMocks() {
@Test
void checkResponseStatusForValidParameters() {
- ResponseEntity<Void> actResponse = executor.executePost(buildPayloadWithMultipleKeys(), buildOkHeaders());
+ ResponseEntity<Void> actResponse = executor.executePost(buildPayload(buildMultipleKeys()), buildOkHeaders());
+ assertThat(actResponse.getStatusCode()).isEqualTo(OK);
+ }
+
+ @Test
+ void checkResponseStatusForValidParametersWithPadding() {
+ ResponseEntity<Void> actResponse = executor.executePost(buildPayloadWithPadding(), buildOkHeaders());
assertThat(actResponse.getStatusCode()).isEqualTo(OK);
}
@@ -116,10 +125,9 @@ void check400ResponseStatusForInvalidParameters() {
@Test
void singleKeyWithOutdatedRollingStartIntervalNumberDoesNotGetSaved() {
- Collection<TemporaryExposureKey> keys = buildPayloadWithSingleOutdatedKey();
ArgumentCaptor<Collection<DiagnosisKey>> argument = ArgumentCaptor.forClass(Collection.class);
- executor.executePost(keys, buildOkHeaders());
+ executor.executePost(buildPayload(createOutdatedKey()), buildOkHeaders());
verify(diagnosisKeyService, atLeastOnce()).saveDiagnosisKeys(argument.capture());
assertThat(argument.getValue()).isEmpty();
@@ -127,12 +135,12 @@ void singleKeyWithOutdatedRollingStartIntervalNumberDoesNotGetSaved() {
@Test
void keysWithOutdatedRollingStartIntervalNumberDoNotGetSaved() {
- Collection<TemporaryExposureKey> submittedKeys = buildPayloadWithMultipleKeys();
+ Collection<TemporaryExposureKey> submittedKeys = buildMultipleKeys();
TemporaryExposureKey outdatedKey = createOutdatedKey();
submittedKeys.add(outdatedKey);
ArgumentCaptor<Collection<DiagnosisKey>> argument = ArgumentCaptor.forClass(Collection.class);
- executor.executePost(submittedKeys, buildOkHeaders());
+ executor.executePost(buildPayload(submittedKeys), buildOkHeaders());
verify(diagnosisKeyService, atLeastOnce()).saveDiagnosisKeys(argument.capture());
submittedKeys.remove(outdatedKey);
@@ -141,10 +149,10 @@ void keysWithOutdatedRollingStartIntervalNumberDoNotGetSaved() {
@Test
void checkSaveOperationCallAndFakeDelayUpdateForValidParameters() {
- Collection<TemporaryExposureKey> submittedKeys = buildPayloadWithMultipleKeys();
+ Collection<TemporaryExposureKey> submittedKeys = buildMultipleKeys();
ArgumentCaptor<Collection<DiagnosisKey>> argument = ArgumentCaptor.forClass(Collection.class);
- executor.executePost(submittedKeys, buildOkHeaders());
+ executor.executePost(buildPayload(submittedKeys), buildOkHeaders());
verify(diagnosisKeyService, atLeastOnce()).saveDiagnosisKeys(argument.capture());
verify(fakeDelayManager, times(1)).updateFakeRequestDelay(anyLong());
@@ -200,6 +208,12 @@ void invalidTanHandling() {
assertThat(actResponse.getStatusCode()).isEqualTo(FORBIDDEN);
}
+ @Test
+ void invalidSubmissionPayload() {
+ ResponseEntity<Void> actResponse = executor.executePost(buildPayloadWithTooLargePadding(), buildOkHeaders());
+ assertThat(actResponse.getStatusCode()).isEqualTo(BAD_REQUEST);
+ }
+
@Test
void checkRealRequestHandlingIsMonitored() {
executor.executePost(buildPayloadWithOneKey(), buildOkHeaders());
@@ -222,7 +236,35 @@ void checkInvalidTanHandlingIsMonitored() {
verify(submissionMonitor, times(1)).incrementInvalidTanRequestCounter();
}
- private Collection<TemporaryExposureKey> buildPayloadWithMultipleKeys() {
+ private SubmissionPayload buildPayload(TemporaryExposureKey key) {
+ Collection<TemporaryExposureKey> keys = Stream.of(key).collect(Collectors.toCollection(ArrayList::new));
+ return buildPayload(keys);
+ }
+
+ private SubmissionPayload buildPayload(Collection<TemporaryExposureKey> keys) {
+ return SubmissionPayload.newBuilder()
+ .addAllKeys(keys)
+ .build();
+ }
+
+ private SubmissionPayload buildPayloadWithPadding() {
+ return SubmissionPayload.newBuilder()
+ .addAllKeys(buildMultipleKeys())
+ .setPadding(ByteString.copyFrom("PaddingString".getBytes()))
+ .build();
+ }
+
+ private SubmissionPayload buildPayloadWithTooLargePadding() {
+ int exceedingSize = (int) (2 * config.getMaximumRequestSize().toBytes());
+ byte[] bytes = new byte[exceedingSize];
+
+ return SubmissionPayload.newBuilder()
+ .addAllKeys(buildMultipleKeys())
+ .setPadding(ByteString.copyFrom(bytes))
+ .build();
+ }
+
+ private Collection<TemporaryExposureKey> buildMultipleKeys() {
int rollingStartIntervalNumber1 = createRollingStartIntervalNumber(config.getRetentionDays() - 1);
int rollingStartIntervalNumber2 = rollingStartIntervalNumber1 + DiagnosisKey.EXPECTED_ROLLING_PERIOD;
int rollingStartIntervalNumber3 = rollingStartIntervalNumber2 + DiagnosisKey.EXPECTED_ROLLING_PERIOD;
@@ -233,11 +275,6 @@ private Collection<TemporaryExposureKey> buildPayloadWithMultipleKeys() {
.collect(Collectors.toCollection(ArrayList::new));
}
- private Collection<TemporaryExposureKey> buildPayloadWithSingleOutdatedKey() {
- TemporaryExposureKey outdatedKey = createOutdatedKey();
- return Stream.of(outdatedKey).collect(Collectors.toCollection(ArrayList::new));
- }
-
private TemporaryExposureKey createOutdatedKey() {
return TemporaryExposureKey.newBuilder()
.setKeyData(ByteString.copyFromUtf8(VALID_KEY_DATA_2))
@@ -246,14 +283,13 @@ private TemporaryExposureKey createOutdatedKey() {
.setTransmissionRiskLevel(5).build();
}
- private static Collection<TemporaryExposureKey> buildPayloadWithInvalidKey() {
- return Stream.of(
- buildTemporaryExposureKey(VALID_KEY_DATA_1, createRollingStartIntervalNumber(2), 999))
- .collect(Collectors.toCollection(ArrayList::new));
+ private SubmissionPayload buildPayloadWithInvalidKey() {
+ TemporaryExposureKey invalidKey = buildTemporaryExposureKey(VALID_KEY_DATA_1, createRollingStartIntervalNumber(2), 999);
+ return buildPayload(invalidKey);
}
private void assertElementsCorrespondToEachOther(Collection<TemporaryExposureKey> submittedTemporaryExposureKeys,
- Collection<DiagnosisKey> savedDiagnosisKeys) {
+ Collection<DiagnosisKey> savedDiagnosisKeys) {
Set<DiagnosisKey> submittedDiagnosisKeys = submittedTemporaryExposureKeys.stream()
.map(submittedDiagnosisKey -> DiagnosisKey.builder().fromProtoBuf(submittedDiagnosisKey).build())
diff --git a/services/submission/src/test/resources/application.yaml b/services/submission/src/test/resources/application.yaml
--- a/services/submission/src/test/resources/application.yaml
+++ b/services/submission/src/test/resources/application.yaml
@@ -23,6 +23,7 @@ services:
retention-days: 14
random-key-padding-multiplier: 10
connection-pool-size: 200
+ maximum-request-size: 100KB
payload:
max-number-of-keys: 14
verification:
| |||||
corona-warn-app__cwa-server-629 | You will be provided with a partial code base and an issue statement explaining a problem to resolve.
<issue>
Simplifying DateAggregatingDecorator
The DateAggregatingDecorator should make more use of the `DiagnosisKeyBundler`. Please team up with @pithumke on this.
</issue>
<code>
[start of README.md]
1 <!-- markdownlint-disable MD041 -->
2 <h1 align="center">
3 Corona-Warn-App Server
4 </h1>
5
6 <p align="center">
7 <a href="https://github.com/corona-warn-app/cwa-server/commits/" title="Last Commit"><img src="https://img.shields.io/github/last-commit/corona-warn-app/cwa-server?style=flat"></a>
8 <a href="https://github.com/corona-warn-app/cwa-server/issues" title="Open Issues"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat"></a>
9 <a href="https://circleci.com/gh/corona-warn-app/cwa-server" title="Build Status"><img src="https://circleci.com/gh/corona-warn-app/cwa-server.svg?style=shield&circle-token=4ab059989d10709df19eb4b98ab7c121a25e981a"></a>
10 <a href="https://sonarcloud.io/dashboard?id=corona-warn-app_cwa-server" title="Quality Gate"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=alert_status"></a>
11 <a href="https://sonarcloud.io/component_measures?id=corona-warn-app_cwa-server&metric=Coverage&view=list" title="Coverage"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=coverage"></a>
12 <a href="https://github.com/corona-warn-app/cwa-server/blob/master/LICENSE" title="License"><img src="https://img.shields.io/badge/License-Apache%202.0-green.svg?style=flat"></a>
13 </p>
14
15 <p align="center">
16 <a href="#development">Development</a> •
17 <a href="#service-apis">Service APIs</a> •
18 <a href="#documentation">Documentation</a> •
19 <a href="#support-and-feedback">Support</a> •
20 <a href="#how-to-contribute">Contribute</a> •
21 <a href="#contributors">Contributors</a> •
22 <a href="#repositories">Repositories</a> •
23 <a href="#licensing">Licensing</a>
24 </p>
25
26 The goal of this project is to develop the official Corona-Warn-App for Germany based on the exposure notification API from [Apple](https://www.apple.com/covid19/contacttracing/) and [Google](https://www.google.com/covid19/exposurenotifications/). The apps (for both iOS and Android) use Bluetooth technology to exchange anonymous encrypted data with other mobile phones (on which the app is also installed) in the vicinity of an app user's phone. The data is stored locally on each user's device, preventing authorities or other parties from accessing or controlling the data. This repository contains the **implementation of the server for encryption keys** for the Corona-Warn-App.
27
28 In this documentation, Corona-Warn-App services are also referred to as CWA services.
29
30 ## Architecture Overview
31
32 You can find the architecture overview [here](/docs/ARCHITECTURE.md), which will give you
33 a good starting point in how the backend services interact with other services, and what purpose
34 they serve.
35
36 ## Development
37
38 After you've checked out this repository, you can run the application in one of the following ways:
39
40 * As a [Docker](https://www.docker.com/)-based deployment on your local machine. You can run either:
41 * Single components using the respective Dockerfile or
42 * The full backend using the Docker Compose (which is considered the most convenient way)
43 * As a [Maven](https://maven.apache.org)-based build on your local machine.
44 If you want to develop something in a single component, this approach is preferable.
45
46 ### Docker-Based Deployment
47
48 If you want to use Docker-based deployment, you need to install Docker on your local machine. For more information about downloading and installing Docker, see the [official Docker documentation](https://docs.docker.com/get-docker/).
49
50 #### Running the Full CWA Backend Using Docker Compose
51
52 For your convenience, a full setup including the generation of test data has been prepared using [Docker Compose](https://docs.docker.com/compose/reference/overview/). To build the backend services, run ```docker-compose build``` in the repository's root directory. A default configuration file can be found under ```.env``` in the root folder of the repository. The default values for the local Postgres and Zenko Cloudserver should be changed in this file before docker-compose is run.
53
54 Once the services are built, you can start the whole backend using ```docker-compose up```.
55 The distribution service runs once and then finishes. If you want to trigger additional distribution runs, run ```docker-compose run distribution```.
56
57 The docker-compose contains the following services:
58
59 Service | Description | Endpoint and Default Credentials
60 ------------------|-------------|-----------
61 submission | The Corona-Warn-App submission service | `http://localhost:8000` <br> `http://localhost:8006` (for actuator endpoint)
62 distribution | The Corona-Warn-App distribution service | NO ENDPOINT
63 postgres | A [postgres] database installation | `localhost:8001` <br> `postgres:5432` (from containerized pgadmin) <br> Username: postgres <br> Password: postgres
64 pgadmin | A [pgadmin](https://www.pgadmin.org/) installation for the postgres database | `http://localhost:8002` <br> Username: [email protected] <br> Password: password
65 cloudserver | [Zenko CloudServer] is a S3-compliant object store | `http://localhost:8003/` <br> Access key: accessKey1 <br> Secret key: verySecretKey1
66 verification-fake | A very simple fake implementation for the tan verification. | `http://localhost:8004/version/v1/tan/verify` <br> The only valid tan is `edc07f08-a1aa-11ea-bb37-0242ac130002`.
67
68 ##### Known Limitation
69
70 In rare cases the docker-compose runs into a timing issue if the distribution service starts before the bucket of the objectstore was created. This is not a big issue as you can simply run ```docker-compose run distribution``` to trigger additional distribution runs after the objectstore was initialized.
71
72 #### Running Single CWA Services Using Docker
73
74 If you would like to build and run a single CWA service, it's considered easiest to run them in a Docker environment. You can do this using the script provided in the respective CWA service directory. The Docker script first builds the CWA service and then creates an image for the runtime, which means that there are no additional dependencies for you to install.
75
76 To build and run the distribution service, run the following command:
77
78 ```bash
79 ./services/distribution/build_and_run.sh
80 ```
81
82 To build and run the submission service, run the following command:
83
84 ```bash
85 ./services/submission/build_and_run.sh
86 ```
87
88 The submission service is available on [localhost:8080](http://localhost:8080 ).
89
90 ### Maven-Based Build
91
92 If you want to actively develop in one of the CWA services, the Maven-based runtime is most suitable.
93 To prepare your machine to run the CWA project locally, we recommend that you first ensure that you've installed the following:
94
95 * Minimum JDK Version 11: [OpenJDK](https://openjdk.java.net/) / [SapMachine](https://sap.github.io/SapMachine/)
96 * [Maven 3.6](https://maven.apache.org/)
97 * [Postgres]
98 * [Zenko CloudServer]
99
100 If you are already running a local Postgres, you need to create a database `cwa` and run the following setup scripts:
101
102 * Create the different CWA roles first by executing [create-roles.sql](setup/create-roles.sql).
103 * Create local database users for the specific roles by running [create-users.sql](./local-setup/create-users.sql).
104 * It is recommended to also run [enable-test-data-docker-compose.sql](./local-setup/enable-test-data-docker-compose.sql)
105 , which enables the test data generation profile. If you already had CWA running before and an existing `diagnosis-key`
106 table on your database, you need to run [enable-test-data.sql](./local-setup/enable-test-data.sql) instead.
107
108 You can also use `docker-compose` to start Postgres and Zenko. If you do that, you have to
109 set the following environment-variables when running the Spring project:
110
111 For the distribution module:
112
113 ```bash
114 POSTGRESQL_SERVICE_PORT=8001
115 VAULT_FILESIGNING_SECRET=</path/to/your/private_key>
116 SPRING_PROFILES_ACTIVE=signature-dev,disable-ssl-client-postgres
117 ```
118
119 For the submission module:
120
121 ```bash
122 POSTGRESQL_SERVICE_PORT=8001
123 SPRING_PROFILES_ACTIVE=disable-ssl-server,disable-ssl-client-postgres,disable-ssl-client-verification,disable-ssl-client-verification-verify-hostname
124 ```
125
126 #### Configure
127
128 After you made sure that the specified dependencies are running, configure them in the respective configuration files.
129
130 * Configure the Postgres connection in the [submission config](./services/submission/src/main/resources/application.yaml) and in the [distribution config](./services/distribution/src/main/resources/application.yaml)
131 * Configure the S3 compatible object storage in the [distribution config](./services/distribution/src/main/resources/application.yaml)
132 * Configure the private key for the distribution service, the path need to be prefixed with `file:`
133 * `VAULT_FILESIGNING_SECRET` should be the path to the private key, example available in `<repo-root>/docker-compose-test-secrets/private.pem`
134
135 #### Build
136
137 After you've checked out the repository, to build the project, run ```mvn install``` in your base directory.
138
139 #### Run
140
141 Navigate to the service you want to start and run the spring-boot:run target. The configured Postgres and the configured S3 compliant object storage are used as default. When you start the submission service, the endpoint is available on your local port 8080.
142
143 If you want to start the submission service, for example, you start it as follows:
144
145 ```bash
146 cd services/submission/
147 mvn spring-boot:run
148 ```
149
150 #### Debugging
151
152 To enable the `DEBUG` log level, you can run the application using the Spring `dev` profile.
153
154 ```bash
155 mvn spring-boot:run -Dspring.profiles.active=dev
156 ```
157
158 To be able to set breakpoints (e.g. in IntelliJ), it may be necessary to use the ```-Dspring-boot.run.fork=false``` parameter.
159
160 ## Service APIs
161
162 The API that is being exposed by the backend services is documented in an [OpenAPI](https://www.openapis.org/) specification. The specification files are available at the following locations:
163
164 Service | OpenAPI Specification
165 --------------------------|-------------
166 Submission Service | [services/submission/api_v1.json](https://github.com/corona-warn-app/cwa-server/raw/master/services/submission/api_v1.json)
167 Distribution Service | [services/distribution/api_v1.json](https://github.com/corona-warn-app/cwa-server/raw/master/services/distribution/api_v1.json)
168
169 ## Spring Profiles
170
171 ### Distribution
172
173 See [Distribution Service - Spring Profiles](/docs/DISTRIBUTION.md#spring-profiles).
174
175 ### Submission
176
177 See [Submission Service - Spring Profiles](/docs/SUBMISSION.md#spring-profiles).
178
179 ## Documentation
180
181 The full documentation for the Corona-Warn-App can be found in the [cwa-documentation](https://github.com/corona-warn-app/cwa-documentation) repository. The documentation repository contains technical documents, architecture information, and whitepapers related to this implementation.
182
183 ## Support and Feedback
184
185 The following channels are available for discussions, feedback, and support requests:
186
187 | Type | Channel |
188 | ------------------------ | ------------------------------------------------------ |
189 | **General Discussion** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="General Discussion"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/question.svg?style=flat-square"></a> </a> |
190 | **Concept Feedback** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="Open Concept Feedback"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/architecture.svg?style=flat-square"></a> |
191 | **Backend Issue** | <a href="https://github.com/corona-warn-app/cwa-server/issues/new/choose" title="Open Backend Issue"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat-square"></a> |
192 | **Other Requests** | <a href="mailto:[email protected]" title="Email CWA Team"><img src="https://img.shields.io/badge/email-CWA%20team-green?logo=mail.ru&style=flat-square&logoColor=white"></a> |
193
194 ## How to Contribute
195
196 Contribution and feedback are 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.
197
198 ## Contributors
199
200 The German government has asked SAP and Deutsche Telekom to develop the Corona-Warn-App for Germany as open source software. Deutsche Telekom is providing the network and mobile technology and will operate and run the backend for the app in a safe, scalable and stable manner. SAP is responsible for the app development, its framework and the underlying platform. Therefore, development teams of SAP and Deutsche Telekom are contributing to this project. At the same time 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.
201
202 ## Repositories
203
204 The following public repositories are currently available for the Corona-Warn-App:
205
206 | Repository | Description |
207 | ------------------- | --------------------------------------------------------------------- |
208 | [cwa-documentation] | Project overview, general documentation, and white papers |
209 | [cwa-server] | Backend implementation for the Apple/Google exposure notification API|
210 | [cwa-verification-server] | Backend implementation of the verification process|
211
212 [cwa-documentation]: https://github.com/corona-warn-app/cwa-documentation
213 [cwa-server]: https://github.com/corona-warn-app/cwa-server
214 [cwa-verification-server]: https://github.com/corona-warn-app/cwa-verification-server
215 [Postgres]: https://www.postgresql.org/
216 [HSQLDB]: http://hsqldb.org/
217 [Zenko CloudServer]: https://github.com/scality/cloudserver
218
219 ## Licensing
220
221 Copyright (c) 2020 SAP SE or an SAP affiliate company.
222
223 Licensed under the **Apache License, Version 2.0** (the "License"); you may not use this file except in compliance with the License.
224
225 You may obtain a copy of the License at <https://www.apache.org/licenses/LICENSE-2.0>.
226
227 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.
228
[end of README.md]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/structure/directory/AppConfigurationDirectory.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.distribution.assembly.appconfig.structure.directory;
22
23 import app.coronawarn.server.common.protocols.internal.ApplicationConfiguration;
24 import app.coronawarn.server.services.distribution.assembly.appconfig.structure.archive.decorator.signing.AppConfigurationSigningDecorator;
25 import app.coronawarn.server.services.distribution.assembly.appconfig.validation.ApplicationConfigurationValidator;
26 import app.coronawarn.server.services.distribution.assembly.appconfig.validation.ConfigurationValidator;
27 import app.coronawarn.server.services.distribution.assembly.appconfig.validation.ValidationResult;
28 import app.coronawarn.server.services.distribution.assembly.component.CryptoProvider;
29 import app.coronawarn.server.services.distribution.assembly.structure.archive.ArchiveOnDisk;
30 import app.coronawarn.server.services.distribution.assembly.structure.directory.DirectoryOnDisk;
31 import app.coronawarn.server.services.distribution.assembly.structure.directory.IndexDirectoryOnDisk;
32 import app.coronawarn.server.services.distribution.assembly.structure.directory.decorator.indexing.IndexingDecoratorOnDisk;
33 import app.coronawarn.server.services.distribution.assembly.structure.file.FileOnDisk;
34 import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
35 import java.util.Set;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38
39 /**
40 * Creates the directory structure {@code /configuration/country/:country} and writes the app configuration parameters
41 * into a zip file.
42 */
43 public class AppConfigurationDirectory extends DirectoryOnDisk {
44
45 private static final Logger logger = LoggerFactory.getLogger(AppConfigurationDirectory.class);
46
47 private final IndexDirectoryOnDisk<String> countryDirectory;
48 private final ApplicationConfiguration applicationConfiguration;
49 private final CryptoProvider cryptoProvider;
50 private final DistributionServiceConfig distributionServiceConfig;
51
52 /**
53 * Creates an {@link AppConfigurationDirectory} for the exposure configuration and risk score classification.
54 *
55 * @param cryptoProvider The {@link CryptoProvider} whose artifacts to use for creating the signature.
56 */
57 public AppConfigurationDirectory(ApplicationConfiguration applicationConfiguration, CryptoProvider cryptoProvider,
58 DistributionServiceConfig distributionServiceConfig) {
59 super(distributionServiceConfig.getApi().getParametersPath());
60 this.applicationConfiguration = applicationConfiguration;
61 this.cryptoProvider = cryptoProvider;
62 this.distributionServiceConfig = distributionServiceConfig;
63
64 countryDirectory = new IndexDirectoryOnDisk<>(distributionServiceConfig.getApi().getCountryPath(),
65 ignoredValue -> Set.of(distributionServiceConfig.getApi().getCountryGermany()), Object::toString);
66
67 addConfigurationArchiveIfValid(distributionServiceConfig.getApi().getAppConfigFileName());
68
69 this.addWritable(new IndexingDecoratorOnDisk<>(countryDirectory, distributionServiceConfig.getOutputFileName()));
70 }
71
72 /**
73 * If validation of the {@link ApplicationConfiguration} succeeds, it is written into a file, put into an archive with
74 * the specified name and added to the specified parent directory.
75 */
76 private void addConfigurationArchiveIfValid(String archiveName) {
77 ConfigurationValidator validator = new ApplicationConfigurationValidator(applicationConfiguration);
78 ValidationResult validationResult = validator.validate();
79
80 if (validationResult.hasErrors()) {
81 logger.error("App configuration file creation failed. Validation failed for {}, {}",
82 archiveName, validationResult);
83 return;
84 }
85
86 ArchiveOnDisk appConfigurationFile = new ArchiveOnDisk(archiveName);
87 appConfigurationFile.addWritable(new FileOnDisk("export.bin", applicationConfiguration.toByteArray()));
88 countryDirectory.addWritableToAll(ignoredValue ->
89 new AppConfigurationSigningDecorator(appConfigurationFile, cryptoProvider, distributionServiceConfig));
90 }
91 }
92
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/structure/directory/AppConfigurationDirectory.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/component/CwaApiStructureProvider.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.distribution.assembly.component;
22
23 import app.coronawarn.server.services.distribution.assembly.structure.WritableOnDisk;
24 import app.coronawarn.server.services.distribution.assembly.structure.directory.Directory;
25 import app.coronawarn.server.services.distribution.assembly.structure.directory.IndexDirectoryOnDisk;
26 import app.coronawarn.server.services.distribution.assembly.structure.directory.decorator.indexing.IndexingDecoratorOnDisk;
27 import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
28 import java.util.Set;
29 import org.springframework.stereotype.Component;
30
31 /**
32 * Assembles the content underneath the {@code /version} path of the CWA API.
33 */
34 @Component
35 public class CwaApiStructureProvider {
36
37 private final AppConfigurationStructureProvider appConfigurationStructureProvider;
38 private final DiagnosisKeysStructureProvider diagnosisKeysStructureProvider;
39 private final DistributionServiceConfig distributionServiceConfig;
40
41 /**
42 * Creates a new CwaApiStructureProvider.
43 */
44 CwaApiStructureProvider(
45 AppConfigurationStructureProvider appConfigurationStructureProvider,
46 DiagnosisKeysStructureProvider diagnosisKeysStructureProvider,
47 DistributionServiceConfig distributionServiceConfig) {
48 this.appConfigurationStructureProvider = appConfigurationStructureProvider;
49 this.diagnosisKeysStructureProvider = diagnosisKeysStructureProvider;
50 this.distributionServiceConfig = distributionServiceConfig;
51 }
52
53 /**
54 * Returns the base directory.
55 */
56 public Directory<WritableOnDisk> getDirectory() {
57 IndexDirectoryOnDisk<String> versionDirectory = new IndexDirectoryOnDisk<>(
58 distributionServiceConfig.getApi().getVersionPath(),
59 ignoredValue -> Set.of(distributionServiceConfig.getApi().getVersionV1()),
60 Object::toString);
61
62 versionDirectory.addWritableToAll(ignoredValue -> appConfigurationStructureProvider.getAppConfiguration());
63 versionDirectory.addWritableToAll(ignoredValue -> diagnosisKeysStructureProvider.getDiagnosisKeys());
64
65 return new IndexingDecoratorOnDisk<>(versionDirectory, distributionServiceConfig.getOutputFileName());
66 }
67 }
68
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/component/CwaApiStructureProvider.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/DiagnosisKeyBundler.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.distribution.assembly.diagnosiskeys;
22
23 import static java.time.ZoneOffset.UTC;
24 import static java.util.Collections.emptyList;
25
26 import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
27 import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
28 import java.time.LocalDate;
29 import java.time.LocalDateTime;
30 import java.time.temporal.Temporal;
31 import java.util.Collection;
32 import java.util.HashMap;
33 import java.util.List;
34 import java.util.Map;
35 import java.util.Optional;
36 import java.util.Set;
37 import java.util.concurrent.TimeUnit;
38 import java.util.stream.Collectors;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41
42 /**
43 * An instance of this class contains a collection of {@link DiagnosisKey DiagnosisKeys}.
44 */
45 public abstract class DiagnosisKeyBundler {
46
47 private static final Logger logger = LoggerFactory.getLogger(DiagnosisKeyBundler.class);
48
49 /**
50 * The submission timestamp is counted in 1 hour intervals since epoch.
51 */
52 public static final long ONE_HOUR_INTERVAL_SECONDS = TimeUnit.HOURS.toSeconds(1);
53
54 /**
55 * The rolling start interval number is counted in 10 minute intervals since epoch.
56 */
57 public static final long TEN_MINUTES_INTERVAL_SECONDS = TimeUnit.MINUTES.toSeconds(10);
58
59 protected final long expiryPolicyMinutes;
60 protected final int minNumberOfKeysPerBundle;
61 private final int maxNumberOfKeysPerBundle;
62
63 // The hour at which the distribution runs. This field is needed to prevent the run from distributing any keys that
64 // have already been submitted but may only be distributed in the future (e.g. because they are not expired yet).
65 protected LocalDateTime distributionTime;
66
67 // A map containing diagnosis keys, grouped by the LocalDateTime on which they may be distributed
68 protected final Map<LocalDateTime, List<DiagnosisKey>> distributableDiagnosisKeys = new HashMap<>();
69
70 /**
71 * Constructs a DiagnosisKeyBundler based on the specified service configuration.
72 */
73 public DiagnosisKeyBundler(DistributionServiceConfig distributionServiceConfig) {
74 this.expiryPolicyMinutes = distributionServiceConfig.getExpiryPolicyMinutes();
75 this.minNumberOfKeysPerBundle = distributionServiceConfig.getShiftingPolicyThreshold();
76 this.maxNumberOfKeysPerBundle = distributionServiceConfig.getMaximumNumberOfKeysPerBundle();
77 }
78
79 /**
80 * Creates a {@link LocalDateTime} based on the specified epoch timestamp.
81 */
82 public static LocalDateTime getLocalDateTimeFromHoursSinceEpoch(long timestamp) {
83 return LocalDateTime.ofEpochSecond(TimeUnit.HOURS.toSeconds(timestamp), 0, UTC);
84 }
85
86 /**
87 * Sets the {@link DiagnosisKey DiagnosisKeys} contained by this {@link DiagnosisKeyBundler} and the time at which the
88 * distribution runs and calls {@link DiagnosisKeyBundler#createDiagnosisKeyDistributionMap}.
89 *
90 * @param diagnosisKeys The {@link DiagnosisKey DiagnosisKeys} contained by this {@link DiagnosisKeyBundler}.
91 * @param distributionTime The {@link LocalDateTime} at which the distribution runs.
92 */
93 public void setDiagnosisKeys(Collection<DiagnosisKey> diagnosisKeys, LocalDateTime distributionTime) {
94 this.distributionTime = distributionTime;
95 this.createDiagnosisKeyDistributionMap(diagnosisKeys);
96 }
97
98 /**
99 * Returns all {@link DiagnosisKey DiagnosisKeys} contained by this {@link DiagnosisKeyBundler}.
100 */
101 public List<DiagnosisKey> getAllDiagnosisKeys() {
102 return this.distributableDiagnosisKeys.values().stream()
103 .flatMap(List::stream)
104 .collect(Collectors.toList());
105 }
106
107 /**
108 * Initializes the internal {@code distributableDiagnosisKeys} map, which should contain all diagnosis keys, grouped
109 * by the LocalDateTime on which they may be distributed.
110 */
111 protected abstract void createDiagnosisKeyDistributionMap(Collection<DiagnosisKey> diagnosisKeys);
112
113 /**
114 * Returns a set of all {@link LocalDate dates} on which {@link DiagnosisKey diagnosis keys} shall be distributed.
115 */
116 public Set<LocalDate> getDatesWithDistributableDiagnosisKeys() {
117 return this.distributableDiagnosisKeys.keySet().stream()
118 .map(LocalDateTime::toLocalDate)
119 .filter(this::numberOfKeysForDateBelowMaximum)
120 .collect(Collectors.toSet());
121 }
122
123 public boolean numberOfKeysForDateBelowMaximum(LocalDate date) {
124 return numberOfKeysBelowMaximum(getDiagnosisKeysForDate(date).size(), date);
125 }
126
127 /**
128 * Returns a set of all {@link LocalDateTime hours} of a specified {@link LocalDate date} during which {@link
129 * DiagnosisKey diagnosis keys} shall be distributed.
130 */
131 public Set<LocalDateTime> getHoursWithDistributableDiagnosisKeys(LocalDate currentDate) {
132 return this.distributableDiagnosisKeys.keySet().stream()
133 .filter(dateTime -> dateTime.toLocalDate().equals(currentDate))
134 .filter(this::numberOfKeysForHourBelowMaximum)
135 .collect(Collectors.toSet());
136 }
137
138 private boolean numberOfKeysForHourBelowMaximum(LocalDateTime hour) {
139 return numberOfKeysBelowMaximum(getDiagnosisKeysForHour(hour).size(), hour);
140 }
141
142 private boolean numberOfKeysBelowMaximum(int numberOfKeys, Temporal time) {
143 if (numberOfKeys > maxNumberOfKeysPerBundle) {
144 logger.error("Number of diagnosis keys ({}) for {} exceeds the configured maximum.", numberOfKeys, time);
145 return false;
146 } else {
147 return true;
148 }
149 }
150
151 /**
152 * Returns the submission timestamp of a {@link DiagnosisKey} as a {@link LocalDateTime}.
153 */
154 protected LocalDateTime getSubmissionDateTime(DiagnosisKey diagnosisKey) {
155 return LocalDateTime.ofEpochSecond(diagnosisKey.getSubmissionTimestamp() * ONE_HOUR_INTERVAL_SECONDS, 0, UTC);
156 }
157
158 /**
159 * Returns all diagnosis keys that should be distributed on a specific date.
160 */
161 public List<DiagnosisKey> getDiagnosisKeysForDate(LocalDate date) {
162 return this.distributableDiagnosisKeys.keySet().stream()
163 .filter(dateTime -> dateTime.toLocalDate().equals(date))
164 .map(this::getDiagnosisKeysForHour)
165 .flatMap(List::stream)
166 .collect(Collectors.toList());
167 }
168
169 /**
170 * Returns all diagnosis keys that should be distributed in a specific hour.
171 */
172 public List<DiagnosisKey> getDiagnosisKeysForHour(LocalDateTime hour) {
173 return Optional
174 .ofNullable(this.distributableDiagnosisKeys.get(hour))
175 .orElse(emptyList());
176 }
177 }
178
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/DiagnosisKeyBundler.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysCountryDirectory.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.directory;
22
23 import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
24 import app.coronawarn.server.services.distribution.assembly.component.CryptoProvider;
25 import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.DiagnosisKeyBundler;
26 import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.directory.decorator.DateAggregatingDecorator;
27 import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.directory.decorator.DateIndexingDecorator;
28 import app.coronawarn.server.services.distribution.assembly.structure.WritableOnDisk;
29 import app.coronawarn.server.services.distribution.assembly.structure.directory.IndexDirectory;
30 import app.coronawarn.server.services.distribution.assembly.structure.directory.IndexDirectoryOnDisk;
31 import app.coronawarn.server.services.distribution.assembly.structure.util.ImmutableStack;
32 import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
33 import java.time.LocalDate;
34 import java.util.Set;
35
36 public class DiagnosisKeysCountryDirectory extends IndexDirectoryOnDisk<String> {
37
38 private final DiagnosisKeyBundler diagnosisKeyBundler;
39 private final CryptoProvider cryptoProvider;
40 private final DistributionServiceConfig distributionServiceConfig;
41
42 /**
43 * Constructs a {@link DiagnosisKeysCountryDirectory} instance that represents the {@code .../country/:country/...}
44 * portion of the diagnosis key directory structure.
45 *
46 * @param diagnosisKeyBundler A {@link DiagnosisKeyBundler} containing the {@link DiagnosisKey DiagnosisKeys}.
47 * @param cryptoProvider The {@link CryptoProvider} used for payload signing.
48 */
49 public DiagnosisKeysCountryDirectory(DiagnosisKeyBundler diagnosisKeyBundler,
50 CryptoProvider cryptoProvider, DistributionServiceConfig distributionServiceConfig) {
51 super(distributionServiceConfig.getApi().getCountryPath(), ignoredValue ->
52 Set.of(distributionServiceConfig.getApi().getCountryGermany()), Object::toString);
53 this.diagnosisKeyBundler = diagnosisKeyBundler;
54 this.cryptoProvider = cryptoProvider;
55 this.distributionServiceConfig = distributionServiceConfig;
56 }
57
58 @Override
59 public void prepare(ImmutableStack<Object> indices) {
60 this.addWritableToAll(ignoredValue ->
61 decorateDateDirectory(
62 new DiagnosisKeysDateDirectory(diagnosisKeyBundler, cryptoProvider, distributionServiceConfig)));
63 super.prepare(indices);
64 }
65
66 private IndexDirectory<LocalDate, WritableOnDisk> decorateDateDirectory(DiagnosisKeysDateDirectory dateDirectory) {
67 return new DateAggregatingDecorator(new DateIndexingDecorator(dateDirectory, distributionServiceConfig),
68 cryptoProvider, distributionServiceConfig, diagnosisKeyBundler);
69 }
70 }
71
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysCountryDirectory.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysDateDirectory.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.directory;
22
23 import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
24 import app.coronawarn.server.services.distribution.assembly.component.CryptoProvider;
25 import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.DiagnosisKeyBundler;
26 import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.directory.decorator.HourIndexingDecorator;
27 import app.coronawarn.server.services.distribution.assembly.structure.WritableOnDisk;
28 import app.coronawarn.server.services.distribution.assembly.structure.directory.Directory;
29 import app.coronawarn.server.services.distribution.assembly.structure.directory.IndexDirectoryOnDisk;
30 import app.coronawarn.server.services.distribution.assembly.structure.util.ImmutableStack;
31 import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
32 import java.time.LocalDate;
33 import java.time.format.DateTimeFormatter;
34
35 public class DiagnosisKeysDateDirectory extends IndexDirectoryOnDisk<LocalDate> {
36
37 private static final DateTimeFormatter ISO8601 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
38
39 private final DiagnosisKeyBundler diagnosisKeyBundler;
40 private final CryptoProvider cryptoProvider;
41 private final DistributionServiceConfig distributionServiceConfig;
42
43 /**
44 * Constructs a {@link DiagnosisKeysDateDirectory} instance associated with the specified {@link DiagnosisKey}
45 * collection. Payload signing is be performed according to the specified {@link CryptoProvider}.
46 *
47 * @param diagnosisKeyBundler A {@link DiagnosisKeyBundler} containing the {@link DiagnosisKey DiagnosisKeys}.
48 * @param cryptoProvider The {@link CryptoProvider} used for payload signing.
49 */
50 public DiagnosisKeysDateDirectory(DiagnosisKeyBundler diagnosisKeyBundler,
51 CryptoProvider cryptoProvider, DistributionServiceConfig distributionServiceConfig) {
52 super(distributionServiceConfig.getApi().getDatePath(),
53 ignoredValue -> diagnosisKeyBundler.getDatesWithDistributableDiagnosisKeys(), ISO8601::format);
54 this.cryptoProvider = cryptoProvider;
55 this.diagnosisKeyBundler = diagnosisKeyBundler;
56 this.distributionServiceConfig = distributionServiceConfig;
57 }
58
59 @Override
60 public void prepare(ImmutableStack<Object> indices) {
61 this.addWritableToAll(ignoredValue -> {
62 DiagnosisKeysHourDirectory hourDirectory =
63 new DiagnosisKeysHourDirectory(diagnosisKeyBundler, cryptoProvider, distributionServiceConfig);
64 return decorateHourDirectory(hourDirectory);
65 });
66 super.prepare(indices);
67 }
68
69 private Directory<WritableOnDisk> decorateHourDirectory(DiagnosisKeysHourDirectory hourDirectory) {
70 return new HourIndexingDecorator(hourDirectory, distributionServiceConfig);
71 }
72 }
73
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysDateDirectory.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysHourDirectory.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.directory;
22
23 import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
24 import app.coronawarn.server.services.distribution.assembly.component.CryptoProvider;
25 import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.DiagnosisKeyBundler;
26 import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.archive.decorator.signing.DiagnosisKeySigningDecorator;
27 import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.file.TemporaryExposureKeyExportFile;
28 import app.coronawarn.server.services.distribution.assembly.structure.WritableOnDisk;
29 import app.coronawarn.server.services.distribution.assembly.structure.archive.Archive;
30 import app.coronawarn.server.services.distribution.assembly.structure.archive.ArchiveOnDisk;
31 import app.coronawarn.server.services.distribution.assembly.structure.directory.Directory;
32 import app.coronawarn.server.services.distribution.assembly.structure.directory.IndexDirectoryOnDisk;
33 import app.coronawarn.server.services.distribution.assembly.structure.file.File;
34 import app.coronawarn.server.services.distribution.assembly.structure.util.ImmutableStack;
35 import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
36 import java.time.LocalDate;
37 import java.time.LocalDateTime;
38 import java.time.ZoneOffset;
39 import java.util.List;
40
41 public class DiagnosisKeysHourDirectory extends IndexDirectoryOnDisk<LocalDateTime> {
42
43 private final DiagnosisKeyBundler diagnosisKeyBundler;
44 private final CryptoProvider cryptoProvider;
45 private final DistributionServiceConfig distributionServiceConfig;
46
47 /**
48 * Constructs a {@link DiagnosisKeysHourDirectory} instance for the specified date.
49 *
50 * @param diagnosisKeyBundler A {@link DiagnosisKeyBundler} containing the {@link DiagnosisKey DiagnosisKeys}.
51 * @param cryptoProvider The {@link CryptoProvider} used for cryptographic signing.
52 */
53 public DiagnosisKeysHourDirectory(DiagnosisKeyBundler diagnosisKeyBundler, CryptoProvider cryptoProvider,
54 DistributionServiceConfig distributionServiceConfig) {
55 super(distributionServiceConfig.getApi().getHourPath(),
56 indices -> diagnosisKeyBundler.getHoursWithDistributableDiagnosisKeys(((LocalDate) indices.peek())),
57 LocalDateTime::getHour);
58 this.diagnosisKeyBundler = diagnosisKeyBundler;
59 this.cryptoProvider = cryptoProvider;
60 this.distributionServiceConfig = distributionServiceConfig;
61 }
62
63 @Override
64 public void prepare(ImmutableStack<Object> indices) {
65 this.addWritableToAll(currentIndices -> {
66 LocalDateTime currentHour = (LocalDateTime) currentIndices.peek();
67 // The LocalDateTime currentHour already contains both the date and the hour information, so
68 // we can throw away the LocalDate that's the second item on the stack from the "/date"
69 // IndexDirectory.
70 String region = (String) currentIndices.pop().pop().peek();
71
72 List<DiagnosisKey> diagnosisKeysForCurrentHour =
73 this.diagnosisKeyBundler.getDiagnosisKeysForHour(currentHour);
74
75 long startTimestamp = currentHour.toEpochSecond(ZoneOffset.UTC);
76 long endTimestamp = currentHour.plusHours(1).toEpochSecond(ZoneOffset.UTC);
77 File<WritableOnDisk> temporaryExposureKeyExportFile = TemporaryExposureKeyExportFile.fromDiagnosisKeys(
78 diagnosisKeysForCurrentHour, region, startTimestamp, endTimestamp, distributionServiceConfig);
79
80 Archive<WritableOnDisk> hourArchive = new ArchiveOnDisk(distributionServiceConfig.getOutputFileName());
81 hourArchive.addWritable(temporaryExposureKeyExportFile);
82
83 return decorateDiagnosisKeyArchive(hourArchive);
84 });
85 super.prepare(indices);
86 }
87
88 private Directory<WritableOnDisk> decorateDiagnosisKeyArchive(Archive<WritableOnDisk> archive) {
89 return new DiagnosisKeySigningDecorator(archive, cryptoProvider, distributionServiceConfig);
90 }
91 }
92
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysHourDirectory.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/decorator/DateAggregatingDecorator.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.directory.decorator;
22
23 import static app.coronawarn.server.services.distribution.assembly.structure.util.functional.CheckedFunction.uncheckedFunction;
24
25 import app.coronawarn.server.common.protocols.external.exposurenotification.TemporaryExposureKey;
26 import app.coronawarn.server.common.protocols.external.exposurenotification.TemporaryExposureKeyExport;
27 import app.coronawarn.server.services.distribution.assembly.component.CryptoProvider;
28 import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.DiagnosisKeyBundler;
29 import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.archive.decorator.signing.DiagnosisKeySigningDecorator;
30 import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.file.TemporaryExposureKeyExportFile;
31 import app.coronawarn.server.services.distribution.assembly.structure.Writable;
32 import app.coronawarn.server.services.distribution.assembly.structure.WritableOnDisk;
33 import app.coronawarn.server.services.distribution.assembly.structure.archive.Archive;
34 import app.coronawarn.server.services.distribution.assembly.structure.archive.ArchiveOnDisk;
35 import app.coronawarn.server.services.distribution.assembly.structure.directory.Directory;
36 import app.coronawarn.server.services.distribution.assembly.structure.directory.DirectoryOnDisk;
37 import app.coronawarn.server.services.distribution.assembly.structure.directory.IndexDirectory;
38 import app.coronawarn.server.services.distribution.assembly.structure.directory.decorator.DirectoryDecorator;
39 import app.coronawarn.server.services.distribution.assembly.structure.directory.decorator.IndexDirectoryDecorator;
40 import app.coronawarn.server.services.distribution.assembly.structure.file.File;
41 import app.coronawarn.server.services.distribution.assembly.structure.util.ImmutableStack;
42 import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
43 import java.time.LocalDate;
44 import java.util.List;
45 import java.util.NoSuchElementException;
46 import java.util.Optional;
47 import java.util.Set;
48 import java.util.stream.Collectors;
49 import java.util.stream.Stream;
50
51 /**
52 * A {@link DirectoryDecorator} that will bundle hour aggregates into date aggregates and sign them.
53 */
54 public class DateAggregatingDecorator extends IndexDirectoryDecorator<LocalDate, WritableOnDisk> {
55
56 private final CryptoProvider cryptoProvider;
57 private final DistributionServiceConfig distributionServiceConfig;
58 private final DiagnosisKeyBundler diagnosisKeyBundler;
59
60 /**
61 * Creates a new DateAggregatingDecorator.
62 */
63 public DateAggregatingDecorator(IndexDirectory<LocalDate, WritableOnDisk> directory, CryptoProvider cryptoProvider,
64 DistributionServiceConfig distributionServiceConfig, DiagnosisKeyBundler diagnosisKeyBundler) {
65 super(directory);
66 this.cryptoProvider = cryptoProvider;
67 this.distributionServiceConfig = distributionServiceConfig;
68 this.diagnosisKeyBundler = diagnosisKeyBundler;
69 }
70
71 @Override
72 public void prepare(ImmutableStack<Object> indices) {
73 super.prepare(indices);
74 Set<Directory<WritableOnDisk>> dayDirectories = this.getWritables().stream()
75 .filter(writable -> writable instanceof DirectoryOnDisk)
76 .map(directory -> (DirectoryOnDisk) directory)
77 .collect(Collectors.toSet());
78 if (dayDirectories.isEmpty()) {
79 return;
80 }
81
82 Set<String> dates = this.getIndex(indices).stream()
83 .filter(diagnosisKeyBundler::numberOfKeysForDateBelowMaximum)
84 .map(this.getIndexFormatter())
85 .map(Object::toString)
86 .collect(Collectors.toSet());
87
88 dayDirectories.stream()
89 .filter(dayDirectory -> dates.contains(dayDirectory.getName()))
90 .forEach(currentDirectory -> Stream.of(currentDirectory)
91 .map(this::getSubSubDirectoryArchives)
92 .map(this::getTemporaryExposureKeyExportFilesFromArchives)
93 .map(this::parseTemporaryExposureKeyExportsFromFiles)
94 .map(this::reduceTemporaryExposureKeyExportsToNewFile)
95 .map(temporaryExposureKeyExportFile -> {
96 Archive<WritableOnDisk> aggregate = new ArchiveOnDisk(distributionServiceConfig.getOutputFileName());
97 aggregate.addWritable(temporaryExposureKeyExportFile);
98 return aggregate;
99 })
100 .map(file -> new DiagnosisKeySigningDecorator(file, cryptoProvider, distributionServiceConfig))
101 .forEach(aggregate -> {
102 currentDirectory.addWritable(aggregate);
103 aggregate.prepare(indices);
104 })
105 );
106 }
107
108 /**
109 * Returns all archives that are 3 levels down from the root directory.
110 */
111 private Set<Archive<WritableOnDisk>> getSubSubDirectoryArchives(Directory<WritableOnDisk> rootDirectory) {
112 return getWritablesInDirectory(rootDirectory, 3).stream()
113 .filter(Writable::isArchive)
114 .map(archive -> (Archive<WritableOnDisk>) archive)
115 .collect(Collectors.toSet());
116 }
117
118 /**
119 * Traverses a directory {@code depth} levels deep and returns a flattened list of all writables at that depth. A
120 * {@code depth} of 0 or less returns a set only containing the root directory. A depth of 1 returns a set of
121 * writables in the root directory. A depth of 2 returns a set of all writables in all directories in the root
122 * directory, and so on.
123 *
124 * @param rootDirectory The directory in which to start traversal.
125 * @param depth The depth to traverse.
126 * @return All writables that are {@code depth} levels down.
127 */
128 private Set<Writable<WritableOnDisk>> getWritablesInDirectory(Directory<WritableOnDisk> rootDirectory, int depth) {
129 if (depth <= 0) {
130 return Set.of(rootDirectory);
131 } else if (depth == 1) {
132 return rootDirectory.getWritables();
133 } else {
134 return rootDirectory.getWritables().stream()
135 .filter(Writable::isDirectory)
136 .flatMap(directory -> getWritablesInDirectory((Directory<WritableOnDisk>) directory, depth - 1).stream())
137 .collect(Collectors.toSet());
138 }
139 }
140
141 private Set<TemporaryExposureKeyExportFile> getTemporaryExposureKeyExportFilesFromArchives(
142 Set<Archive<WritableOnDisk>> hourArchives) {
143 return hourArchives.stream()
144 .map(Directory::getWritables)
145 .map(writables -> writables.stream()
146 .filter(writable -> writable.getName().equals("export.bin")))
147 .map(Stream::findFirst)
148 .map(Optional::orElseThrow)
149 .filter(writable -> writable instanceof File)
150 .map(file -> (TemporaryExposureKeyExportFile) file)
151 .collect(Collectors.toSet());
152 }
153
154 private Set<TemporaryExposureKeyExport> parseTemporaryExposureKeyExportsFromFiles(
155 Set<TemporaryExposureKeyExportFile> temporaryExposureKeyExportFiles) {
156 return temporaryExposureKeyExportFiles.stream()
157 .map(TemporaryExposureKeyExportFile::getBytesWithoutHeader)
158 .map(uncheckedFunction(TemporaryExposureKeyExport::parseFrom))
159 .collect(Collectors.toSet());
160 }
161
162 private TemporaryExposureKeyExportFile reduceTemporaryExposureKeyExportsToNewFile(
163 Set<TemporaryExposureKeyExport> temporaryExposureKeyExports) {
164 return TemporaryExposureKeyExportFile.fromTemporaryExposureKeys(
165 getTemporaryExposureKeys(temporaryExposureKeyExports),
166 getRegion(temporaryExposureKeyExports),
167 getStartTimestamp(temporaryExposureKeyExports),
168 getEndTimestamp(temporaryExposureKeyExports),
169 distributionServiceConfig
170 );
171 }
172
173 private static Set<TemporaryExposureKey> getTemporaryExposureKeys(
174 Set<TemporaryExposureKeyExport> temporaryExposureKeyExports) {
175 return temporaryExposureKeyExports.stream()
176 .map(TemporaryExposureKeyExport::getKeysList)
177 .flatMap(List::stream)
178 .collect(Collectors.toSet());
179 }
180
181 private static String getRegion(Set<TemporaryExposureKeyExport> temporaryExposureKeyExports) {
182 return temporaryExposureKeyExports.stream()
183 .map(TemporaryExposureKeyExport::getRegion)
184 .findAny()
185 .orElseThrow(NoSuchElementException::new);
186 }
187
188 private static long getStartTimestamp(
189 Set<TemporaryExposureKeyExport> temporaryExposureKeyExports) {
190 return temporaryExposureKeyExports.stream()
191 .mapToLong(TemporaryExposureKeyExport::getStartTimestamp)
192 .min()
193 .orElseThrow(NoSuchElementException::new);
194 }
195
196 private static long getEndTimestamp(Set<TemporaryExposureKeyExport> temporaryExposureKeyExports) {
197 return temporaryExposureKeyExports.stream()
198 .mapToLong(TemporaryExposureKeyExport::getEndTimestamp)
199 .max()
200 .orElseThrow(NoSuchElementException::new);
201 }
202 }
203
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/decorator/DateAggregatingDecorator.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/directory/IndexDirectoryOnDisk.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.distribution.assembly.structure.directory;
22
23 import app.coronawarn.server.services.distribution.assembly.structure.Writable;
24 import app.coronawarn.server.services.distribution.assembly.structure.WritableOnDisk;
25 import app.coronawarn.server.services.distribution.assembly.structure.util.ImmutableStack;
26 import app.coronawarn.server.services.distribution.assembly.structure.util.functional.Formatter;
27 import app.coronawarn.server.services.distribution.assembly.structure.util.functional.IndexFunction;
28 import app.coronawarn.server.services.distribution.assembly.structure.util.functional.WritableFunction;
29 import java.util.HashSet;
30 import java.util.Set;
31
32 /**
33 * An {@link IndexDirectory} that can be written to disk.
34 *
35 * @param <T> The type of the elements in the index.
36 */
37 public class IndexDirectoryOnDisk<T> extends DirectoryOnDisk implements IndexDirectory<T, WritableOnDisk> {
38
39 // Writables to be written into every directory created through the index
40 private final Set<WritableFunction<WritableOnDisk>> metaWritables = new HashSet<>();
41 private final IndexFunction<T> indexFunction;
42 private final Formatter<T> indexFormatter;
43
44 /**
45 * Constructs a {@link IndexDirectoryOnDisk} instance that represents a directory, containing an index in the form of
46 * sub directories.
47 *
48 * @param name The name that this directory should have on disk.
49 * @param indexFunction An {@link IndexFunction} that calculates the index of this {@link IndexDirectoryOnDisk} from
50 * a {@link ImmutableStack} of parent {@link IndexDirectoryOnDisk} indices. The top element of
51 * the stack is from the closest {@link IndexDirectoryOnDisk} in the parent chain.
52 * @param indexFormatter A {@link Formatter} used to format the directory name for each index element returned by the
53 * {@link IndexDirectoryOnDisk#indexFunction}.
54 */
55 public IndexDirectoryOnDisk(String name, IndexFunction<T> indexFunction, Formatter<T> indexFormatter) {
56 super(name);
57 this.indexFunction = indexFunction;
58 this.indexFormatter = indexFormatter;
59 }
60
61 @Override
62 public Formatter<T> getIndexFormatter() {
63 return this.indexFormatter;
64 }
65
66 @Override
67 public Set<T> getIndex(ImmutableStack<Object> indices) {
68 return this.indexFunction.apply(indices);
69 }
70
71 @Override
72 public void addWritableToAll(WritableFunction<WritableOnDisk> writableFunction) {
73 this.metaWritables.add(writableFunction);
74 }
75
76 /**
77 * Creates a new subdirectory for every element of the {@link IndexDirectory#getIndex index} and writes all its
78 * {@link IndexDirectory#addWritableToAll writables} to those. The respective element of the index will be pushed
79 * onto the Stack for subsequent {@link Writable#prepare} calls.
80 *
81 * @param indices A {@link ImmutableStack} of parameters from all {@link IndexDirectory IndexDirectories} further up
82 * in the hierarchy. The Stack may contain different types, depending on the types {@code T} of {@link
83 * IndexDirectory IndexDirectories} further up in the hierarchy.
84 */
85 @Override
86 public void prepare(ImmutableStack<Object> indices) {
87 super.prepare(indices);
88 this.prepareIndex(indices);
89 }
90
91 private void prepareIndex(ImmutableStack<Object> indices) {
92 this.getIndex(indices).forEach(currentIndex -> {
93 ImmutableStack<Object> newIndices = indices.push(currentIndex);
94 DirectoryOnDisk subDirectory = makeSubDirectory(currentIndex);
95 prepareMetaWritables(newIndices, subDirectory);
96 });
97 }
98
99 private DirectoryOnDisk makeSubDirectory(T index) {
100 DirectoryOnDisk subDirectory = new DirectoryOnDisk(this.indexFormatter.apply(index).toString());
101 this.addWritable(subDirectory);
102 return subDirectory;
103 }
104
105 private void prepareMetaWritables(ImmutableStack<Object> indices, DirectoryOnDisk target) {
106 this.metaWritables.forEach(metaWritableFunction -> {
107 Writable<WritableOnDisk> newWritable = metaWritableFunction.apply(indices);
108 target.addWritable(newWritable);
109 newWritable.prepare(indices);
110 });
111 }
112 }
113
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/directory/IndexDirectoryOnDisk.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/util/functional/WritableFunction.java]
1 /*-
2 * ---license-start
3 * Corona-Warn-App
4 * ---
5 * Copyright (C) 2020 SAP SE and all other contributors
6 * ---
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ---license-end
19 */
20
21 package app.coronawarn.server.services.distribution.assembly.structure.util.functional;
22
23 import app.coronawarn.server.services.distribution.assembly.structure.Writable;
24 import app.coronawarn.server.services.distribution.assembly.structure.util.ImmutableStack;
25 import java.util.function.Function;
26
27 /**
28 * A {@code Function<Stack<Object>, Writable>}.
29 *
30 * @param <T> The specific type of {@link Writable} that this {@link WritableFunction} can create.
31 */
32 @FunctionalInterface
33 public interface WritableFunction<T extends Writable<T>> extends Function<ImmutableStack<Object>, Writable<T>> {
34
35 Writable<T> apply(ImmutableStack<Object> t);
36 }
37
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/util/functional/WritableFunction.java]
</code>
Here is an example of a patch file. It consists of changes to the code base. It specifies the file names, the line numbers of each change, and the removed and added lines. A single patch file can contain changes to multiple files.
<patch>
--- a/file.py
+++ b/file.py
@@ -1,27 +1,35 @@
def euclidean(a, b):
- while b:
- a, b = b, a % b
- return a
+ if b == 0:
+ return a
+ return euclidean(b, a % b)
def bresenham(x0, y0, x1, y1):
points = []
dx = abs(x1 - x0)
dy = abs(y1 - y0)
- sx = 1 if x0 < x1 else -1
- sy = 1 if y0 < y1 else -1
- err = dx - dy
+ x, y = x0, y0
+ sx = -1 if x0 > x1 else 1
+ sy = -1 if y0 > y1 else 1
- while True:
- points.append((x0, y0))
- if x0 == x1 and y0 == y1:
- break
- e2 = 2 * err
- if e2 > -dy:
+ if dx > dy:
+ err = dx / 2.0
+ while x != x1:
+ points.append((x, y))
err -= dy
- x0 += sx
- if e2 < dx:
- err += dx
- y0 += sy
+ if err < 0:
+ y += sy
+ err += dx
+ x += sx
+ else:
+ err = dy / 2.0
+ while y != y1:
+ points.append((x, y))
+ err -= dx
+ if err < 0:
+ x += sx
+ err += dy
+ y += sy
+ points.append((x, y))
return points
</patch>
I need you to solve the provded issue by generating a single patch file that I can apply directly to this repository using git apply. Please respond with a single patch file in the format shown above.
Respond below:
| corona-warn-app/cwa-server | 2e2655a94ae13a663cdbbcb17c5b1065edccf90b | Simplifying DateAggregatingDecorator
The DateAggregatingDecorator should make more use of the `DiagnosisKeyBundler`. Please team up with @pithumke on this.
| 2020-06-25T15:35:31 | <patch>
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/structure/directory/AppConfigurationDirectory.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/structure/directory/AppConfigurationDirectory.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/structure/directory/AppConfigurationDirectory.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/structure/directory/AppConfigurationDirectory.java
@@ -32,6 +32,7 @@
import app.coronawarn.server.services.distribution.assembly.structure.directory.decorator.indexing.IndexingDecoratorOnDisk;
import app.coronawarn.server.services.distribution.assembly.structure.file.FileOnDisk;
import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
+import java.util.Optional;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -86,6 +87,7 @@ private void addConfigurationArchiveIfValid(String archiveName) {
ArchiveOnDisk appConfigurationFile = new ArchiveOnDisk(archiveName);
appConfigurationFile.addWritable(new FileOnDisk("export.bin", applicationConfiguration.toByteArray()));
countryDirectory.addWritableToAll(ignoredValue ->
- new AppConfigurationSigningDecorator(appConfigurationFile, cryptoProvider, distributionServiceConfig));
+ Optional
+ .of(new AppConfigurationSigningDecorator(appConfigurationFile, cryptoProvider, distributionServiceConfig)));
}
}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/component/CwaApiStructureProvider.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/component/CwaApiStructureProvider.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/component/CwaApiStructureProvider.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/component/CwaApiStructureProvider.java
@@ -25,6 +25,7 @@
import app.coronawarn.server.services.distribution.assembly.structure.directory.IndexDirectoryOnDisk;
import app.coronawarn.server.services.distribution.assembly.structure.directory.decorator.indexing.IndexingDecoratorOnDisk;
import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
+import java.util.Optional;
import java.util.Set;
import org.springframework.stereotype.Component;
@@ -59,8 +60,10 @@ public Directory<WritableOnDisk> getDirectory() {
ignoredValue -> Set.of(distributionServiceConfig.getApi().getVersionV1()),
Object::toString);
- versionDirectory.addWritableToAll(ignoredValue -> appConfigurationStructureProvider.getAppConfiguration());
- versionDirectory.addWritableToAll(ignoredValue -> diagnosisKeysStructureProvider.getDiagnosisKeys());
+ versionDirectory.addWritableToAll(ignoredValue ->
+ Optional.of(appConfigurationStructureProvider.getAppConfiguration()));
+ versionDirectory.addWritableToAll(ignoredValue ->
+ Optional.of(diagnosisKeysStructureProvider.getDiagnosisKeys()));
return new IndexingDecoratorOnDisk<>(versionDirectory, distributionServiceConfig.getOutputFileName());
}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/DiagnosisKeyBundler.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/DiagnosisKeyBundler.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/DiagnosisKeyBundler.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/DiagnosisKeyBundler.java
@@ -95,6 +95,13 @@ public void setDiagnosisKeys(Collection<DiagnosisKey> diagnosisKeys, LocalDateTi
this.createDiagnosisKeyDistributionMap(diagnosisKeys);
}
+ /**
+ * Returns the {@link LocalDateTime} at which the distribution runs.
+ */
+ public LocalDateTime getDistributionTime() {
+ return this.distributionTime;
+ }
+
/**
* Returns all {@link DiagnosisKey DiagnosisKeys} contained by this {@link DiagnosisKeyBundler}.
*/
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysCountryDirectory.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysCountryDirectory.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysCountryDirectory.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysCountryDirectory.java
@@ -23,7 +23,6 @@
import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
import app.coronawarn.server.services.distribution.assembly.component.CryptoProvider;
import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.DiagnosisKeyBundler;
-import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.directory.decorator.DateAggregatingDecorator;
import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.directory.decorator.DateIndexingDecorator;
import app.coronawarn.server.services.distribution.assembly.structure.WritableOnDisk;
import app.coronawarn.server.services.distribution.assembly.structure.directory.IndexDirectory;
@@ -31,6 +30,7 @@
import app.coronawarn.server.services.distribution.assembly.structure.util.ImmutableStack;
import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
import java.time.LocalDate;
+import java.util.Optional;
import java.util.Set;
public class DiagnosisKeysCountryDirectory extends IndexDirectoryOnDisk<String> {
@@ -57,14 +57,12 @@ public DiagnosisKeysCountryDirectory(DiagnosisKeyBundler diagnosisKeyBundler,
@Override
public void prepare(ImmutableStack<Object> indices) {
- this.addWritableToAll(ignoredValue ->
- decorateDateDirectory(
- new DiagnosisKeysDateDirectory(diagnosisKeyBundler, cryptoProvider, distributionServiceConfig)));
+ this.addWritableToAll(ignoredValue -> Optional.of(decorateDateDirectory(
+ new DiagnosisKeysDateDirectory(diagnosisKeyBundler, cryptoProvider, distributionServiceConfig))));
super.prepare(indices);
}
private IndexDirectory<LocalDate, WritableOnDisk> decorateDateDirectory(DiagnosisKeysDateDirectory dateDirectory) {
- return new DateAggregatingDecorator(new DateIndexingDecorator(dateDirectory, distributionServiceConfig),
- cryptoProvider, distributionServiceConfig, diagnosisKeyBundler);
+ return new DateIndexingDecorator(dateDirectory, distributionServiceConfig);
}
}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysDateDirectory.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysDateDirectory.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysDateDirectory.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysDateDirectory.java
@@ -23,14 +23,23 @@
import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
import app.coronawarn.server.services.distribution.assembly.component.CryptoProvider;
import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.DiagnosisKeyBundler;
+import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.archive.decorator.signing.DiagnosisKeySigningDecorator;
import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.directory.decorator.HourIndexingDecorator;
+import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.file.TemporaryExposureKeyExportFile;
+import app.coronawarn.server.services.distribution.assembly.structure.Writable;
import app.coronawarn.server.services.distribution.assembly.structure.WritableOnDisk;
+import app.coronawarn.server.services.distribution.assembly.structure.archive.Archive;
+import app.coronawarn.server.services.distribution.assembly.structure.archive.ArchiveOnDisk;
import app.coronawarn.server.services.distribution.assembly.structure.directory.Directory;
import app.coronawarn.server.services.distribution.assembly.structure.directory.IndexDirectoryOnDisk;
+import app.coronawarn.server.services.distribution.assembly.structure.file.File;
import app.coronawarn.server.services.distribution.assembly.structure.util.ImmutableStack;
import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
import java.time.LocalDate;
+import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
+import java.util.List;
+import java.util.Optional;
public class DiagnosisKeysDateDirectory extends IndexDirectoryOnDisk<LocalDate> {
@@ -61,12 +70,39 @@ public void prepare(ImmutableStack<Object> indices) {
this.addWritableToAll(ignoredValue -> {
DiagnosisKeysHourDirectory hourDirectory =
new DiagnosisKeysHourDirectory(diagnosisKeyBundler, cryptoProvider, distributionServiceConfig);
- return decorateHourDirectory(hourDirectory);
+ return Optional.of(decorateHourDirectory(hourDirectory));
});
+ this.addWritableToAll(this::indicesToDateDirectoryArchive);
super.prepare(indices);
}
+ private Optional<Writable<WritableOnDisk>> indicesToDateDirectoryArchive(ImmutableStack<Object> currentIndices) {
+ LocalDate currentDate = (LocalDate) currentIndices.peek();
+ if (currentDate.equals(diagnosisKeyBundler.getDistributionTime().toLocalDate())) {
+ return Optional.empty();
+ }
+ String region = (String) currentIndices.pop().peek();
+
+ List<DiagnosisKey> diagnosisKeysForCurrentHour =
+ this.diagnosisKeyBundler.getDiagnosisKeysForDate(currentDate);
+
+ long startTimestamp = currentDate.atStartOfDay().toEpochSecond(ZoneOffset.UTC);
+ long endTimestamp = currentDate.plusDays(1).atStartOfDay().toEpochSecond(ZoneOffset.UTC);
+
+ File<WritableOnDisk> temporaryExposureKeyExportFile = TemporaryExposureKeyExportFile.fromDiagnosisKeys(
+ diagnosisKeysForCurrentHour, region, startTimestamp, endTimestamp, distributionServiceConfig);
+
+ Archive<WritableOnDisk> dateArchive = new ArchiveOnDisk(distributionServiceConfig.getOutputFileName());
+ dateArchive.addWritable(temporaryExposureKeyExportFile);
+
+ return Optional.of(decorateDiagnosisKeyArchive(dateArchive));
+ }
+
private Directory<WritableOnDisk> decorateHourDirectory(DiagnosisKeysHourDirectory hourDirectory) {
return new HourIndexingDecorator(hourDirectory, distributionServiceConfig);
}
+
+ private Directory<WritableOnDisk> decorateDiagnosisKeyArchive(Archive<WritableOnDisk> archive) {
+ return new DiagnosisKeySigningDecorator(archive, cryptoProvider, distributionServiceConfig);
+ }
}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysHourDirectory.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysHourDirectory.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysHourDirectory.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysHourDirectory.java
@@ -37,6 +37,7 @@
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.List;
+import java.util.Optional;
public class DiagnosisKeysHourDirectory extends IndexDirectoryOnDisk<LocalDateTime> {
@@ -80,7 +81,7 @@ public void prepare(ImmutableStack<Object> indices) {
Archive<WritableOnDisk> hourArchive = new ArchiveOnDisk(distributionServiceConfig.getOutputFileName());
hourArchive.addWritable(temporaryExposureKeyExportFile);
- return decorateDiagnosisKeyArchive(hourArchive);
+ return Optional.of(decorateDiagnosisKeyArchive(hourArchive));
});
super.prepare(indices);
}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/decorator/DateAggregatingDecorator.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/decorator/DateAggregatingDecorator.java
deleted file mode 100644
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/decorator/DateAggregatingDecorator.java
+++ /dev/null
@@ -1,202 +0,0 @@
-/*-
- * ---license-start
- * Corona-Warn-App
- * ---
- * Copyright (C) 2020 SAP SE and all other contributors
- * ---
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://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 for the specific language governing permissions and
- * limitations under the License.
- * ---license-end
- */
-
-package app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.directory.decorator;
-
-import static app.coronawarn.server.services.distribution.assembly.structure.util.functional.CheckedFunction.uncheckedFunction;
-
-import app.coronawarn.server.common.protocols.external.exposurenotification.TemporaryExposureKey;
-import app.coronawarn.server.common.protocols.external.exposurenotification.TemporaryExposureKeyExport;
-import app.coronawarn.server.services.distribution.assembly.component.CryptoProvider;
-import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.DiagnosisKeyBundler;
-import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.archive.decorator.signing.DiagnosisKeySigningDecorator;
-import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.file.TemporaryExposureKeyExportFile;
-import app.coronawarn.server.services.distribution.assembly.structure.Writable;
-import app.coronawarn.server.services.distribution.assembly.structure.WritableOnDisk;
-import app.coronawarn.server.services.distribution.assembly.structure.archive.Archive;
-import app.coronawarn.server.services.distribution.assembly.structure.archive.ArchiveOnDisk;
-import app.coronawarn.server.services.distribution.assembly.structure.directory.Directory;
-import app.coronawarn.server.services.distribution.assembly.structure.directory.DirectoryOnDisk;
-import app.coronawarn.server.services.distribution.assembly.structure.directory.IndexDirectory;
-import app.coronawarn.server.services.distribution.assembly.structure.directory.decorator.DirectoryDecorator;
-import app.coronawarn.server.services.distribution.assembly.structure.directory.decorator.IndexDirectoryDecorator;
-import app.coronawarn.server.services.distribution.assembly.structure.file.File;
-import app.coronawarn.server.services.distribution.assembly.structure.util.ImmutableStack;
-import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
-import java.time.LocalDate;
-import java.util.List;
-import java.util.NoSuchElementException;
-import java.util.Optional;
-import java.util.Set;
-import java.util.stream.Collectors;
-import java.util.stream.Stream;
-
-/**
- * A {@link DirectoryDecorator} that will bundle hour aggregates into date aggregates and sign them.
- */
-public class DateAggregatingDecorator extends IndexDirectoryDecorator<LocalDate, WritableOnDisk> {
-
- private final CryptoProvider cryptoProvider;
- private final DistributionServiceConfig distributionServiceConfig;
- private final DiagnosisKeyBundler diagnosisKeyBundler;
-
- /**
- * Creates a new DateAggregatingDecorator.
- */
- public DateAggregatingDecorator(IndexDirectory<LocalDate, WritableOnDisk> directory, CryptoProvider cryptoProvider,
- DistributionServiceConfig distributionServiceConfig, DiagnosisKeyBundler diagnosisKeyBundler) {
- super(directory);
- this.cryptoProvider = cryptoProvider;
- this.distributionServiceConfig = distributionServiceConfig;
- this.diagnosisKeyBundler = diagnosisKeyBundler;
- }
-
- @Override
- public void prepare(ImmutableStack<Object> indices) {
- super.prepare(indices);
- Set<Directory<WritableOnDisk>> dayDirectories = this.getWritables().stream()
- .filter(writable -> writable instanceof DirectoryOnDisk)
- .map(directory -> (DirectoryOnDisk) directory)
- .collect(Collectors.toSet());
- if (dayDirectories.isEmpty()) {
- return;
- }
-
- Set<String> dates = this.getIndex(indices).stream()
- .filter(diagnosisKeyBundler::numberOfKeysForDateBelowMaximum)
- .map(this.getIndexFormatter())
- .map(Object::toString)
- .collect(Collectors.toSet());
-
- dayDirectories.stream()
- .filter(dayDirectory -> dates.contains(dayDirectory.getName()))
- .forEach(currentDirectory -> Stream.of(currentDirectory)
- .map(this::getSubSubDirectoryArchives)
- .map(this::getTemporaryExposureKeyExportFilesFromArchives)
- .map(this::parseTemporaryExposureKeyExportsFromFiles)
- .map(this::reduceTemporaryExposureKeyExportsToNewFile)
- .map(temporaryExposureKeyExportFile -> {
- Archive<WritableOnDisk> aggregate = new ArchiveOnDisk(distributionServiceConfig.getOutputFileName());
- aggregate.addWritable(temporaryExposureKeyExportFile);
- return aggregate;
- })
- .map(file -> new DiagnosisKeySigningDecorator(file, cryptoProvider, distributionServiceConfig))
- .forEach(aggregate -> {
- currentDirectory.addWritable(aggregate);
- aggregate.prepare(indices);
- })
- );
- }
-
- /**
- * Returns all archives that are 3 levels down from the root directory.
- */
- private Set<Archive<WritableOnDisk>> getSubSubDirectoryArchives(Directory<WritableOnDisk> rootDirectory) {
- return getWritablesInDirectory(rootDirectory, 3).stream()
- .filter(Writable::isArchive)
- .map(archive -> (Archive<WritableOnDisk>) archive)
- .collect(Collectors.toSet());
- }
-
- /**
- * Traverses a directory {@code depth} levels deep and returns a flattened list of all writables at that depth. A
- * {@code depth} of 0 or less returns a set only containing the root directory. A depth of 1 returns a set of
- * writables in the root directory. A depth of 2 returns a set of all writables in all directories in the root
- * directory, and so on.
- *
- * @param rootDirectory The directory in which to start traversal.
- * @param depth The depth to traverse.
- * @return All writables that are {@code depth} levels down.
- */
- private Set<Writable<WritableOnDisk>> getWritablesInDirectory(Directory<WritableOnDisk> rootDirectory, int depth) {
- if (depth <= 0) {
- return Set.of(rootDirectory);
- } else if (depth == 1) {
- return rootDirectory.getWritables();
- } else {
- return rootDirectory.getWritables().stream()
- .filter(Writable::isDirectory)
- .flatMap(directory -> getWritablesInDirectory((Directory<WritableOnDisk>) directory, depth - 1).stream())
- .collect(Collectors.toSet());
- }
- }
-
- private Set<TemporaryExposureKeyExportFile> getTemporaryExposureKeyExportFilesFromArchives(
- Set<Archive<WritableOnDisk>> hourArchives) {
- return hourArchives.stream()
- .map(Directory::getWritables)
- .map(writables -> writables.stream()
- .filter(writable -> writable.getName().equals("export.bin")))
- .map(Stream::findFirst)
- .map(Optional::orElseThrow)
- .filter(writable -> writable instanceof File)
- .map(file -> (TemporaryExposureKeyExportFile) file)
- .collect(Collectors.toSet());
- }
-
- private Set<TemporaryExposureKeyExport> parseTemporaryExposureKeyExportsFromFiles(
- Set<TemporaryExposureKeyExportFile> temporaryExposureKeyExportFiles) {
- return temporaryExposureKeyExportFiles.stream()
- .map(TemporaryExposureKeyExportFile::getBytesWithoutHeader)
- .map(uncheckedFunction(TemporaryExposureKeyExport::parseFrom))
- .collect(Collectors.toSet());
- }
-
- private TemporaryExposureKeyExportFile reduceTemporaryExposureKeyExportsToNewFile(
- Set<TemporaryExposureKeyExport> temporaryExposureKeyExports) {
- return TemporaryExposureKeyExportFile.fromTemporaryExposureKeys(
- getTemporaryExposureKeys(temporaryExposureKeyExports),
- getRegion(temporaryExposureKeyExports),
- getStartTimestamp(temporaryExposureKeyExports),
- getEndTimestamp(temporaryExposureKeyExports),
- distributionServiceConfig
- );
- }
-
- private static Set<TemporaryExposureKey> getTemporaryExposureKeys(
- Set<TemporaryExposureKeyExport> temporaryExposureKeyExports) {
- return temporaryExposureKeyExports.stream()
- .map(TemporaryExposureKeyExport::getKeysList)
- .flatMap(List::stream)
- .collect(Collectors.toSet());
- }
-
- private static String getRegion(Set<TemporaryExposureKeyExport> temporaryExposureKeyExports) {
- return temporaryExposureKeyExports.stream()
- .map(TemporaryExposureKeyExport::getRegion)
- .findAny()
- .orElseThrow(NoSuchElementException::new);
- }
-
- private static long getStartTimestamp(
- Set<TemporaryExposureKeyExport> temporaryExposureKeyExports) {
- return temporaryExposureKeyExports.stream()
- .mapToLong(TemporaryExposureKeyExport::getStartTimestamp)
- .min()
- .orElseThrow(NoSuchElementException::new);
- }
-
- private static long getEndTimestamp(Set<TemporaryExposureKeyExport> temporaryExposureKeyExports) {
- return temporaryExposureKeyExports.stream()
- .mapToLong(TemporaryExposureKeyExport::getEndTimestamp)
- .max()
- .orElseThrow(NoSuchElementException::new);
- }
-}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/directory/IndexDirectoryOnDisk.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/directory/IndexDirectoryOnDisk.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/directory/IndexDirectoryOnDisk.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/directory/IndexDirectoryOnDisk.java
@@ -27,6 +27,7 @@
import app.coronawarn.server.services.distribution.assembly.structure.util.functional.IndexFunction;
import app.coronawarn.server.services.distribution.assembly.structure.util.functional.WritableFunction;
import java.util.HashSet;
+import java.util.Optional;
import java.util.Set;
/**
@@ -74,9 +75,9 @@ public void addWritableToAll(WritableFunction<WritableOnDisk> writableFunction)
}
/**
- * Creates a new subdirectory for every element of the {@link IndexDirectory#getIndex index} and writes all its
- * {@link IndexDirectory#addWritableToAll writables} to those. The respective element of the index will be pushed
- * onto the Stack for subsequent {@link Writable#prepare} calls.
+ * Creates a new subdirectory for every element of the {@link IndexDirectory#getIndex index} and writes all its {@link
+ * IndexDirectory#addWritableToAll writables} to those. The respective element of the index will be pushed onto the
+ * Stack for subsequent {@link Writable#prepare} calls.
*
* @param indices A {@link ImmutableStack} of parameters from all {@link IndexDirectory IndexDirectories} further up
* in the hierarchy. The Stack may contain different types, depending on the types {@code T} of {@link
@@ -104,9 +105,11 @@ private DirectoryOnDisk makeSubDirectory(T index) {
private void prepareMetaWritables(ImmutableStack<Object> indices, DirectoryOnDisk target) {
this.metaWritables.forEach(metaWritableFunction -> {
- Writable<WritableOnDisk> newWritable = metaWritableFunction.apply(indices);
- target.addWritable(newWritable);
- newWritable.prepare(indices);
+ Optional<Writable<WritableOnDisk>> maybeNewWritable = metaWritableFunction.apply(indices);
+ maybeNewWritable.ifPresent(newWritable -> {
+ target.addWritable(newWritable);
+ newWritable.prepare(indices);
+ });
});
}
}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/util/functional/WritableFunction.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/util/functional/WritableFunction.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/util/functional/WritableFunction.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/util/functional/WritableFunction.java
@@ -22,6 +22,7 @@
import app.coronawarn.server.services.distribution.assembly.structure.Writable;
import app.coronawarn.server.services.distribution.assembly.structure.util.ImmutableStack;
+import java.util.Optional;
import java.util.function.Function;
/**
@@ -30,7 +31,8 @@
* @param <T> The specific type of {@link Writable} that this {@link WritableFunction} can create.
*/
@FunctionalInterface
-public interface WritableFunction<T extends Writable<T>> extends Function<ImmutableStack<Object>, Writable<T>> {
+public interface WritableFunction<T extends Writable<T>> extends
+ Function<ImmutableStack<Object>, Optional<Writable<T>>> {
- Writable<T> apply(ImmutableStack<Object> t);
+ Optional<Writable<T>> apply(ImmutableStack<Object> t);
}
</patch> | diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/ProdDiagnosisKeyBundlerKeyRetrievalTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/ProdDiagnosisKeyBundlerKeyRetrievalTest.java
--- a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/ProdDiagnosisKeyBundlerKeyRetrievalTest.java
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/ProdDiagnosisKeyBundlerKeyRetrievalTest.java
@@ -180,4 +180,12 @@ void testEmptyListWhenGettingDiagnosisKeysForHourBeforeEarliestDiagnosisKey() {
bundler.setDiagnosisKeys(diagnosisKeys, LocalDateTime.of(1970, 1, 5, 0, 0));
assertThat(bundler.getDiagnosisKeysForHour(LocalDateTime.of(1970, 1, 1, 0, 0, 0))).isEmpty();
}
+
+ @Test
+ void testGetsCorrectDistributionDate(){
+ LocalDateTime expected = LocalDateTime.of(1970, 1, 5, 0, 0);
+ List<DiagnosisKey> diagnosisKeys = buildDiagnosisKeys(6, LocalDateTime.of(1970, 1, 2, 4, 0), 5);
+ bundler.setDiagnosisKeys(diagnosisKeys, expected);
+ assertThat(bundler.getDistributionTime()).isEqualTo(expected);
+ }
}
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysDateDirectoryTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysDateDirectoryTest.java
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysDateDirectoryTest.java
@@ -0,0 +1,185 @@
+/*-
+ * ---license-start
+ * Corona-Warn-App
+ * ---
+ * Copyright (C) 2020 SAP SE and all other contributors
+ * ---
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://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 for the specific language governing permissions and
+ * limitations under the License.
+ * ---license-end
+ */
+
+package app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.directory;
+
+import static app.coronawarn.server.services.distribution.common.Helpers.buildDiagnosisKeys;
+import static app.coronawarn.server.services.distribution.common.Helpers.getExpectedDateAndHourFiles;
+import static org.assertj.core.api.Assertions.assertThat;
+
+import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
+import app.coronawarn.server.services.distribution.assembly.component.CryptoProvider;
+import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.DiagnosisKeyBundler;
+import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.ProdDiagnosisKeyBundler;
+import app.coronawarn.server.services.distribution.assembly.structure.WritableOnDisk;
+import app.coronawarn.server.services.distribution.assembly.structure.directory.Directory;
+import app.coronawarn.server.services.distribution.assembly.structure.directory.DirectoryOnDisk;
+import app.coronawarn.server.services.distribution.assembly.structure.util.ImmutableStack;
+import app.coronawarn.server.services.distribution.common.Helpers;
+import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
+import java.io.File;
+import java.io.IOException;
+import java.time.LocalDateTime;
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+import org.junit.Rule;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.rules.TemporaryFolder;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.context.properties.EnableConfigurationProperties;
+import org.springframework.boot.test.context.ConfigFileApplicationContextInitializer;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit.jupiter.SpringExtension;
+
+@EnableConfigurationProperties(value = DistributionServiceConfig.class)
+@ExtendWith(SpringExtension.class)
+@ContextConfiguration(classes = {CryptoProvider.class, DistributionServiceConfig.class},
+ initializers = ConfigFileApplicationContextInitializer.class)
+class DiagnosisKeysDateDirectoryTest {
+
+ @Rule
+ private final TemporaryFolder outputFolder = new TemporaryFolder();
+
+ @Autowired
+ CryptoProvider cryptoProvider;
+
+ @Autowired
+ DistributionServiceConfig distributionServiceConfig;
+
+ private File outputFile;
+
+ @BeforeEach
+ void setupAll() throws IOException {
+ outputFolder.create();
+ outputFile = outputFolder.newFolder();
+ }
+
+ private void runDateDistribution(Collection<DiagnosisKey> diagnosisKeys, LocalDateTime distributionTime) {
+ DiagnosisKeyBundler bundler = new ProdDiagnosisKeyBundler(distributionServiceConfig);
+ bundler
+ .setDiagnosisKeys(diagnosisKeys, distributionTime);
+ DiagnosisKeysDateDirectory dateDirectory = new DiagnosisKeysDateDirectory(bundler, cryptoProvider,
+ distributionServiceConfig);
+ Directory<WritableOnDisk> outputDirectory = new DirectoryOnDisk(outputFile);
+ outputDirectory.addWritable(dateDirectory);
+ dateDirectory.prepare(new ImmutableStack<>()
+ .push("version-directory")
+ .push("country-directory"));
+ outputDirectory.write();
+ }
+
+ @Test
+ void testCreatesCorrectDirectoryStructureForMultipleDates() {
+ Collection<DiagnosisKey> diagnosisKeys = IntStream.range(0, 3)
+ .mapToObj(currentDate -> IntStream.range(0, 5)
+ .mapToObj(currentHour ->
+ buildDiagnosisKeys(6, LocalDateTime.of(1970, 1, 3 + currentDate, 0, 0).plusHours(currentHour), 5))
+ .flatMap(List::stream)
+ .collect(Collectors.toList()))
+ .flatMap(List::stream)
+ .collect(Collectors.toList());
+ runDateDistribution(diagnosisKeys, LocalDateTime.of(1970, 1, 6, 0, 0));
+ Set<String> actualFiles = Helpers.getFilePaths(outputFile, outputFile.getAbsolutePath());
+ Set<String> expectedDateAndHourFiles = getExpectedDateAndHourFiles(Map.of(
+ "1970-01-03", List.of("0", "1", "2", "3", "4"),
+ "1970-01-04", List.of("0", "1", "2", "3", "4"),
+ "1970-01-05", List.of("0", "1", "2", "3", "4")), "1970-01-06");
+ assertThat(actualFiles).isEqualTo(expectedDateAndHourFiles);
+ }
+
+ @Test
+ void testDoesNotIncludeCurrentDateInDirectoryStructure() {
+ Collection<DiagnosisKey> diagnosisKeys = IntStream.range(0, 3)
+ .mapToObj(currentDate -> IntStream.range(0, 5)
+ .mapToObj(currentHour ->
+ buildDiagnosisKeys(6, LocalDateTime.of(1970, 1, 3 + currentDate, 0, 0).plusHours(currentHour), 5))
+ .flatMap(List::stream)
+ .collect(Collectors.toList()))
+ .flatMap(List::stream)
+ .collect(Collectors.toList());
+ runDateDistribution(diagnosisKeys, LocalDateTime.of(1970, 1, 5, 12, 0));
+ Set<String> actualFiles = Helpers.getFilePaths(outputFile, outputFile.getAbsolutePath());
+ Set<String> expectedDateAndHourFiles = getExpectedDateAndHourFiles(Map.of(
+ "1970-01-03", List.of("0", "1", "2", "3", "4"),
+ "1970-01-04", List.of("0", "1", "2", "3", "4"),
+ "1970-01-05", List.of("0", "1", "2", "3", "4")), "1970-01-05");
+ assertThat(actualFiles).isEqualTo(expectedDateAndHourFiles);
+ }
+
+ @Test
+ void testDoesNotIncludeEmptyDatesInDirectoryStructure() {
+ Collection<DiagnosisKey> diagnosisKeys = IntStream.range(0, 3)
+ .filter(currentDate -> currentDate != 1)
+ .mapToObj(currentDate -> IntStream.range(0, 5)
+ .mapToObj(currentHour ->
+ buildDiagnosisKeys(6, LocalDateTime.of(1970, 1, 3 + currentDate, 0, 0).plusHours(currentHour), 5))
+ .flatMap(List::stream)
+ .collect(Collectors.toList()))
+ .flatMap(List::stream)
+ .collect(Collectors.toList());
+
+ runDateDistribution(diagnosisKeys, LocalDateTime.of(1970, 1, 5, 12, 0));
+ Set<String> actualFiles = Helpers.getFilePaths(outputFile, outputFile.getAbsolutePath());
+ Set<String> expectedDateAndHourFiles = getExpectedDateAndHourFiles(Map.of(
+ "1970-01-03", List.of("0", "1", "2", "3", "4"),
+ "1970-01-05", List.of("0", "1", "2", "3", "4")), "1970-01-05");
+ assertThat(actualFiles).isEqualTo(expectedDateAndHourFiles);
+ }
+
+ @Test
+ void testDoesNotIncludeDatesWithTooFewKeysInDirectoryStructure() {
+ Collection<DiagnosisKey> diagnosisKeys = List.of(
+ buildDiagnosisKeys(6, LocalDateTime.of(1970, 1, 3, 1, 0), 5),
+ buildDiagnosisKeys(6, LocalDateTime.of(1970, 1, 4, 1, 0), 4),
+ buildDiagnosisKeys(6, LocalDateTime.of(1970, 1, 5, 1, 0), 5))
+ .stream()
+ .flatMap(List::stream)
+ .collect(Collectors.toList());
+ runDateDistribution(diagnosisKeys, LocalDateTime.of(1970, 1, 6, 12, 0));
+ Set<String> actualFiles = Helpers.getFilePaths(outputFile, outputFile.getAbsolutePath());
+ Set<String> expectedDateAndHourFiles = getExpectedDateAndHourFiles(Map.of(
+ "1970-01-03", List.of("1"),
+ "1970-01-05", List.of("1")), "1970-01-06");
+ assertThat(actualFiles).isEqualTo(expectedDateAndHourFiles);
+ }
+
+ @Test
+ void testDoesNotIncludeDatesInTheFuture() {
+ Collection<DiagnosisKey> diagnosisKeys = List.of(
+ buildDiagnosisKeys(6, LocalDateTime.of(1970, 1, 3, 1, 0), 5),
+ buildDiagnosisKeys(6, LocalDateTime.of(1970, 1, 4, 1, 0), 5),
+ buildDiagnosisKeys(6, LocalDateTime.of(1970, 1, 5, 1, 0), 5))
+ .stream()
+ .flatMap(List::stream)
+ .collect(Collectors.toList());
+ runDateDistribution(diagnosisKeys, LocalDateTime.of(1970, 1, 4, 12, 0));
+ Set<String> actualFiles = Helpers.getFilePaths(outputFile, outputFile.getAbsolutePath());
+ Set<String> expectedDateAndHourFiles = getExpectedDateAndHourFiles(Map.of(
+ "1970-01-03", List.of("1"),
+ "1970-01-04", List.of("1")), "1970-01-04");
+ assertThat(actualFiles).isEqualTo(expectedDateAndHourFiles);
+ }
+}
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysHourDirectoryTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysHourDirectoryTest.java
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/diagnosiskeys/structure/directory/DiagnosisKeysHourDirectoryTest.java
@@ -0,0 +1,156 @@
+/*-
+ * ---license-start
+ * Corona-Warn-App
+ * ---
+ * Copyright (C) 2020 SAP SE and all other contributors
+ * ---
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://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 for the specific language governing permissions and
+ * limitations under the License.
+ * ---license-end
+ */
+
+package app.coronawarn.server.services.distribution.assembly.diagnosiskeys.structure.directory;
+
+import static app.coronawarn.server.services.distribution.common.Helpers.buildDiagnosisKeys;
+import static app.coronawarn.server.services.distribution.common.Helpers.getExpectedHourFiles;
+import static app.coronawarn.server.services.distribution.common.Helpers.getFilePaths;
+import static org.assertj.core.api.Assertions.assertThat;
+
+import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
+import app.coronawarn.server.services.distribution.assembly.component.CryptoProvider;
+import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.DiagnosisKeyBundler;
+import app.coronawarn.server.services.distribution.assembly.diagnosiskeys.ProdDiagnosisKeyBundler;
+import app.coronawarn.server.services.distribution.assembly.structure.WritableOnDisk;
+import app.coronawarn.server.services.distribution.assembly.structure.directory.Directory;
+import app.coronawarn.server.services.distribution.assembly.structure.directory.DirectoryOnDisk;
+import app.coronawarn.server.services.distribution.assembly.structure.util.ImmutableStack;
+import app.coronawarn.server.services.distribution.config.DistributionServiceConfig;
+import java.io.File;
+import java.io.IOException;
+import java.time.LocalDate;
+import java.time.LocalDateTime;
+import java.util.Collection;
+import java.util.List;
+import java.util.Set;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+import org.junit.Rule;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.rules.TemporaryFolder;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.context.properties.EnableConfigurationProperties;
+import org.springframework.boot.test.context.ConfigFileApplicationContextInitializer;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit.jupiter.SpringExtension;
+
+@EnableConfigurationProperties(value = DistributionServiceConfig.class)
+@ExtendWith(SpringExtension.class)
+@ContextConfiguration(classes = {CryptoProvider.class, DistributionServiceConfig.class},
+ initializers = ConfigFileApplicationContextInitializer.class)
+class DiagnosisKeysHourDirectoryTest {
+
+ @Rule
+ private final TemporaryFolder outputFolder = new TemporaryFolder();
+
+ @Autowired
+ CryptoProvider cryptoProvider;
+
+ @Autowired
+ DistributionServiceConfig distributionServiceConfig;
+
+ private File outputFile;
+
+ @BeforeEach
+ void setupAll() throws IOException {
+ outputFolder.create();
+ outputFile = outputFolder.newFolder();
+ }
+
+ private void runHourDistribution(Collection<DiagnosisKey> diagnosisKeys, LocalDateTime distributionTime) {
+ DiagnosisKeyBundler bundler = new ProdDiagnosisKeyBundler(distributionServiceConfig);
+ bundler.setDiagnosisKeys(diagnosisKeys, distributionTime);
+ DiagnosisKeysHourDirectory hourDirectory = new DiagnosisKeysHourDirectory(bundler, cryptoProvider,
+ distributionServiceConfig);
+ Directory<WritableOnDisk> outputDirectory = new DirectoryOnDisk(outputFile);
+ outputDirectory.addWritable(hourDirectory);
+ hourDirectory.prepare(new ImmutableStack<>()
+ .push("version-directory")
+ .push("country-directory")
+ .push(LocalDate.of(1970, 1, 3)) // date-directory
+ );
+ outputDirectory.write();
+ }
+
+ @Test
+ void testCreatesCorrectStructureForMultipleHours() {
+ Collection<DiagnosisKey> diagnosisKeys = IntStream.range(0, 5)
+ .mapToObj(currentHour -> buildDiagnosisKeys(6, LocalDateTime.of(1970, 1, 3, 0, 0).plusHours(currentHour), 5))
+ .flatMap(List::stream)
+ .collect(Collectors.toList());
+ runHourDistribution(diagnosisKeys, LocalDateTime.of(1970, 1, 5, 0, 0));
+ Set<String> actualFiles = getFilePaths(outputFile, outputFile.getAbsolutePath());
+ assertThat(actualFiles).isEqualTo(getExpectedHourFiles(Set.of("0", "1", "2", "3", "4")));
+ }
+
+ @Test
+ void testDoesNotIncludeEmptyHours() {
+ Collection<DiagnosisKey> diagnosisKeys = IntStream.range(0, 5)
+ .filter(currentHour -> currentHour != 3)
+ .mapToObj(currentHour -> buildDiagnosisKeys(6, LocalDateTime.of(1970, 1, 3, 0, 0).plusHours(currentHour), 5))
+ .flatMap(List::stream)
+ .collect(Collectors.toList());
+ runHourDistribution(diagnosisKeys, LocalDateTime.of(1970, 1, 5, 0, 0));
+ Set<String> actualFiles = getFilePaths(outputFile, outputFile.getAbsolutePath());
+ assertThat(actualFiles).isEqualTo(getExpectedHourFiles(Set.of("0", "1", "2", "4")));
+ }
+
+ @Test
+ void testDoesNotIncludeCurrentHour() {
+ Collection<DiagnosisKey> diagnosisKeys = IntStream.range(0, 5)
+ .mapToObj(currentHour -> buildDiagnosisKeys(6, LocalDateTime.of(1970, 1, 3, 0, 0).plusHours(currentHour), 5))
+ .flatMap(List::stream)
+ .collect(Collectors.toList());
+ runHourDistribution(diagnosisKeys, LocalDateTime.of(1970, 1, 3, 4, 0));
+ Set<String> actualFiles = getFilePaths(outputFile, outputFile.getAbsolutePath());
+ assertThat(actualFiles).isEqualTo(getExpectedHourFiles(Set.of("0", "1", "2", "3")));
+ }
+
+ @Test
+ void testDoesNotIncludeHoursWithTooFewKeys() {
+ Collection<DiagnosisKey> diagnosisKeys = List.of(
+ buildDiagnosisKeys(6, LocalDateTime.of(1970, 1, 3, 0, 0), 5),
+ buildDiagnosisKeys(6, LocalDateTime.of(1970, 1, 3, 1, 0), 4),
+ buildDiagnosisKeys(6, LocalDateTime.of(1970, 1, 3, 2, 0), 5))
+ .stream()
+ .flatMap(List::stream)
+ .collect(Collectors.toList());
+ runHourDistribution(diagnosisKeys, LocalDateTime.of(1970, 1, 6, 12, 0));
+ Set<String> actualFiles = getFilePaths(outputFile, outputFile.getAbsolutePath());
+ assertThat(actualFiles).isEqualTo(getExpectedHourFiles(Set.of("0", "2")));
+ }
+
+ @Test
+ void testDoesNotIncludeHoursInTheFuture() {
+ Collection<DiagnosisKey> diagnosisKeys = List.of(
+ buildDiagnosisKeys(6, LocalDateTime.of(1970, 1, 3, 0, 0), 5),
+ buildDiagnosisKeys(6, LocalDateTime.of(1970, 1, 3, 1, 0), 5),
+ buildDiagnosisKeys(6, LocalDateTime.of(1970, 1, 3, 2, 0), 5))
+ .stream()
+ .flatMap(List::stream)
+ .collect(Collectors.toList());
+ runHourDistribution(diagnosisKeys, LocalDateTime.of(1970, 1, 3, 1, 0));
+ Set<String> actualFiles = getFilePaths(outputFile, outputFile.getAbsolutePath());
+ assertThat(actualFiles).isEqualTo(getExpectedHourFiles(Set.of("0")));
+ }
+}
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/structure/directory/IndexDirectoryTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/structure/directory/IndexDirectoryTest.java
--- a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/structure/directory/IndexDirectoryTest.java
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/structure/directory/IndexDirectoryTest.java
@@ -32,6 +32,7 @@
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
+import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@@ -79,7 +80,7 @@ void checkAddFileToAll() {
indexDirectory.addWritableToAll(ignoredValue -> {
FileOnDisk newFile = new FileOnDisk("index", new byte[0]);
expectedFileList.add(newFile);
- return newFile;
+ return Optional.of(newFile);
});
prepareAndWrite(outputDirectory);
@@ -104,7 +105,7 @@ void checkAddDirectoryToAll() {
indexDirectory.addWritableToAll(ignoredValue -> {
DirectoryOnDisk newDirectory = new DirectoryOnDisk("something");
expectedFileList.add(newDirectory);
- return newDirectory;
+ return Optional.of(newDirectory);
});
prepareAndWrite(outputDirectory);
diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/common/Helpers.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/common/Helpers.java
--- a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/common/Helpers.java
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/common/Helpers.java
@@ -21,6 +21,7 @@
package app.coronawarn.server.services.distribution.common;
import static app.coronawarn.server.services.distribution.assembly.appconfig.YamlLoader.loadYamlIntoProtobufBuilder;
+import static java.io.File.separator;
import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
import app.coronawarn.server.common.protocols.internal.ApplicationConfiguration;
@@ -31,7 +32,10 @@
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashSet;
import java.util.List;
+import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
@@ -95,4 +99,34 @@ public static Set<String> getFilePaths(java.io.File root, String basePath) {
public static ApplicationConfiguration loadApplicationConfiguration(String path) throws UnableToLoadFileException {
return loadYamlIntoProtobufBuilder(path, ApplicationConfiguration.Builder.class).build();
}
+
+ public static Set<String> getExpectedHourFiles(Collection<String> hours) {
+ return hours.stream()
+ .map(hour -> Set.of(
+ String.join(separator, "hour", hour, "index"),
+ String.join(separator, "hour", hour, "index.checksum")))
+ .flatMap(Set::stream)
+ .collect(Collectors.toSet());
+ }
+
+ public static Set<String> getExpectedDateAndHourFiles(Map<String, List<String>> datesAndHours, String currentDate) {
+ Set<String> expectedFiles = new HashSet<>();
+
+ datesAndHours.forEach((date, hours) -> {
+ if (!date.equals(currentDate)) {
+ expectedFiles.add(String.join(separator, "date", date, "index"));
+ expectedFiles.add(String.join(separator, "date", date, "index.checksum"));
+ }
+
+ expectedFiles.add(String.join(separator, "date", date, "hour", "index"));
+ expectedFiles.add(String.join(separator, "date", date, "hour", "index.checksum"));
+
+ hours.forEach(hour -> {
+ expectedFiles.add(String.join(separator, "date", date, "hour", hour, "index"));
+ expectedFiles.add(String.join(separator, "date", date, "hour", hour, "index.checksum"));
+ });
+ });
+
+ return expectedFiles;
+ }
}
| |||||
corona-warn-app__cwa-server-106 | You will be provided with a partial code base and an issue statement explaining a problem to resolve.
<issue>
Set Retention Days to 14
Any key data that is associated to a point in time older than 14 days shall be removed from the database and will also be removed from the CDN and therefore the index file.
</issue>
<code>
[start of README.md]
1 <h1 align="center">
2 Corona Warn App - Server
3 </h1>
4
5 <p align="center">
6 <a href="https://github.com/Exposure-Notification-App/ena-documentation/commits/" title="Last Commit"><img src="https://img.shields.io/github/last-commit/corona-warn-app/cwa-server?style=flat"></a>
7 <a href="https://github.com/Exposure-Notification-App/ena-documentation/issues" title="Open Issues"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat"></a>
8 <a href="https://circleci.com/gh/corona-warn-app/cwa-server" title="Build Status"><img src="https://circleci.com/gh/corona-warn-app/cwa-server.svg?style=flat&circle-token=a7294b977bb9ea2c2d53ff62c9aa442670e19b59"></a>
9 <a href="https://github.com/corona-warn-app/cwa-server/blob/master/LICENSE" title="License"><img src="https://img.shields.io/badge/License-Apache%202.0-green.svg?style=flat"></a>
10 </p>
11
12 <p align="center">
13 <a href="#service-apis">Service APIs</a> •
14 <a href="#development">Development</a> •
15 <a href="#architecture--documentation">Documentation</a> •
16 <a href="#contributing">Contributing</a> •
17 <a href="#support--feedback">Support</a> •
18 <a href="https://github.com/corona-warn-app/cwa-admin/releases">Changelog</a>
19 </p>
20
21 This project has the goal to develop the official Corona-Warn-App for Germany based on the Exposure Notification API by [Apple](https://www.apple.com/covid19/contacttracing/) and [Google](https://www.google.com/covid19/exposurenotifications/). The apps (for both iOS and Android) will collect anonymous data from nearby mobile phones using Bluetooth technology. The data will be stored locally on each device, preventing authorities’ access and control over tracing data. This repository contains the **implementation of the key server** for the Corona-Warn-App. This implementation is **work in progress** and contains alpha-quality code only.
22
23 ## Service APIs
24
25 Service | OpenAPI Specification
26 -------------|-------------
27 Submission Service | https://github.com/corona-warn-app/cwa-server/raw/master/services/submission/api_v1.json
28 Distribution Service | https://github.com/corona-warn-app/cwa-server/raw/master/services/distribution/api_v1.json
29
30
31 ## Development
32
33 ### Setup
34
35 To setup this project locally on your machine, we recommend to install the following prerequisites:
36 - Java OpenJDK 11
37 - Maven 3.6
38 - Docker if you would like to build Docker images
39 - Postgres if you would like to connect a persistent storage. If no postgres connection is specified an in-memory HSQLDB will be provided.
40
41 ### Build
42
43 After you checked out the repository run ```mvn install``` in your base directory to build the project.
44
45 ### Run
46
47 Navigate to the service you would like to start and run the spring-boot:run target. By default the HSQLDB will be used and after the Spring Boot application started the endpoint will be available on your local port 8080. As an example if you would like to start the submission service run:
48 ```
49 cd services/submission/
50 mvn spring-boot:run
51 ```
52
53 If you want to use a postgres DB instead please use the postgres profile when starting the application:
54
55 ```
56 cd services/submission/
57 mvn spring-boot:run -Dspring-boot.run.profiles=postgres
58 ```
59
60 In order to enable S3 integration, you will need the following vars in your env:
61
62 Var | Description
63 ----|----------------
64 AWS_ACCESS_KEY_ID | The access key
65 AWS_SECRET_ACCESS_KEY | The secret access key
66 cwa.objectstore.endpoint | The S3 endpoint
67 cwa.objectstore.bucket | The S3 bucket name
68
69 ### Build and run Docker Images
70
71 First download and install [Docker](https://www.docker.com/products/docker-desktop).
72
73 If you want to build and run a docker image of a service you can use the prepared script in the respective service directory.
74 To build and run the distribution service:
75 ```
76 ./services/distribution/build_and_run.sh
77 ```
78
79 To build and run the submission service:
80 ```
81 ./services/submission/build_and_run.sh
82 ```
83 The submission service will then be available locally on port 8080.
84
85 ## Debugging
86
87 You may run the application with the spring profile `dev` to enable the `DEBUG` log-level.
88
89 ```
90 mvn spring-boot:run -Dspring-boot.run.profiles=postgres,dev
91 ```
92
93 To be able to set breakpoints (e.g. in IntelliJ), it may be necessary to use the parameter `-Dspring-boot.run.fork=false`.
94
95
96 ## Known Issues
97
98 There are no known issues.
99
100 ## Architecture & Documentation
101
102 The full documentation for the Corona-Warn-App is in the [cwa-documentation](https://github.com/corona-warn-app/cwa-documentation) repository. Please refer to this repository for technical documents, UI/UX specifications, architectures, and whitepapers of this implementation.
103
104 ## Support & Feedback
105
106 | Type | Channel |
107 | ------------------------ | ------------------------------------------------------ |
108 | **General Discussion** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="General Discussion"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/question.svg?style=flat-square"></a> </a> |
109 | **Concept Feedback** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="Open Concept Feedback"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/concept-extension.svg?style=flat-square"></a> |
110 | **iOS App Issue** | <a href="https://github.com/corona-warn-app/cwa-app-ios/issues/new/choose" title="Open iOS Suggestion"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-app-ios/ios-app.svg?style=flat-square"></a> |
111 | **Android App Issue** | <a href="https://github.com/corona-warn-app/cwa-app-android/issues/new/choose" title="Open Android Issue"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-app-android/android-app.svg?style=flat-square"></a> |
112 | **Backend Issue** | <a href="https://github.com/corona-warn-app/cwa-server/issues/new/choose" title="Open Backend Issue"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server/backend.svg?style=flat-square"></a> |
113 | **Other Requests** | <a href="mailto:[email protected]" title="Email CWD Team"><img src="https://img.shields.io/badge/email-CWD%20team-green?logo=mail.ru&style=flat-square&logoColor=white"></a> |
114
115 ## Contributing
116
117 Contributions and feedback are encouraged and always welcome. Please see our [Contribution Guidelines](./CONTRIBUTING.md) for details on how to contribute, the project structure and additional details you need to know to work with us. By participating in this project, you agree to abide by its [Code of Conduct](./CODE_OF_CONDUCT.md).
118
119 ## Contributors
120
121 The German government has asked SAP and Deutsche Telekom to develop the Corona-Warn-App. Deutsche Telekom is providing the infrastructure technology and will operate and run the backend for the app in a safe, scalable, and stable manner. SAP is responsible for the development of the app development and the exposure notification backend. Therefore, development teams of SAP and T-Systems are contributing to this project. At the same time, our commitment to open source means that we are enabling -and encouraging- all interested parties to contribute and become part of its developer community.
122
123 ## Repositories
124
125 | Repository | Description |
126 | ------------------- | --------------------------------------------------------------------- |
127 | [cwa-documentation] | Project overview, general documentation, and white papers. |
128 | [cwa-app-ios] | Native iOS app using the Apple/Google exposure notification API. |
129 | [cwa-app-android] | Native Android app using the Apple/Google exposure notification API. |
130 | [cwa-server] | Backend implementation for the Apple/Google exposure notification API.|
131
132 [cwa-documentation]: https://github.com/corona-warn-app/cwa-documentation
133 [cwa-app-ios]: https://github.com/corona-warn-app/cwa-app-ios
134 [cwa-app-android]: https://github.com/corona-warn-app/cwa-app-android
135 [cwa-server]: https://github.com/corona-warn-app/cwa-server
136
137 ---
138
139 This project is licensed under the **Apache-2.0** license. For more information, see the [LICENSE](./LICENSE) file.
140
[end of README.md]
[start of /dev/null]
1
[end of /dev/null]
[start of common/persistence/src/main/java/app/coronawarn/server/common/persistence/repository/DiagnosisKeyRepository.java]
1 package app.coronawarn.server.common.persistence.repository;
2
3 import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
4 import org.springframework.data.jpa.repository.JpaRepository;
5 import org.springframework.stereotype.Repository;
6
7 @Repository
8 public interface DiagnosisKeyRepository extends JpaRepository<DiagnosisKey, Long> {
9 }
10
[end of common/persistence/src/main/java/app/coronawarn/server/common/persistence/repository/DiagnosisKeyRepository.java]
[start of common/persistence/src/main/java/app/coronawarn/server/common/persistence/service/DiagnosisKeyService.java]
1 package app.coronawarn.server.common.persistence.service;
2
3 import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
4 import app.coronawarn.server.common.persistence.repository.DiagnosisKeyRepository;
5 import java.util.Collection;
6 import java.util.List;
7 import org.springframework.beans.factory.annotation.Autowired;
8 import org.springframework.data.domain.Sort;
9 import org.springframework.stereotype.Component;
10
11 @Component
12 public class DiagnosisKeyService {
13
14 @Autowired
15 private DiagnosisKeyRepository keyRepository;
16
17 /**
18 * Persists the specified collection of {@link DiagnosisKey} instances.
19 *
20 * @param diagnosisKeys must not contain {@literal null}.
21 * @throws IllegalArgumentException in case the given collection contains {@literal null}.
22 */
23 public void saveDiagnosisKeys(Collection<DiagnosisKey> diagnosisKeys) {
24 keyRepository.saveAll(diagnosisKeys);
25 }
26
27 /**
28 * Returns all persisted diagnosis keys, sorted by their submission timestamp.
29 */
30 public List<DiagnosisKey> getDiagnosisKeys() {
31 return keyRepository.findAll(Sort.by(Sort.Direction.ASC, "submissionTimestamp"));
32 }
33 }
34
[end of common/persistence/src/main/java/app/coronawarn/server/common/persistence/service/DiagnosisKeyService.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/DiagnosisKeyDistributionRunner.java]
1 package app.coronawarn.server.services.distribution.runner;
2
3 import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
4 import app.coronawarn.server.common.persistence.service.DiagnosisKeyService;
5 import app.coronawarn.server.services.distribution.crypto.CryptoProvider;
6 import app.coronawarn.server.services.distribution.diagnosiskeys.structure.directory.DiagnosisKeysDirectoryImpl;
7 import app.coronawarn.server.services.distribution.structure.directory.DirectoryImpl;
8 import app.coronawarn.server.services.distribution.structure.directory.IndexDirectory;
9 import app.coronawarn.server.services.distribution.structure.directory.IndexDirectoryImpl;
10 import app.coronawarn.server.services.distribution.structure.directory.decorator.IndexingDecorator;
11 import app.coronawarn.server.services.distribution.structure.util.ImmutableStack;
12 import java.io.File;
13 import java.io.IOException;
14 import java.util.Collection;
15 import java.util.Set;
16 import org.apache.commons.io.FileUtils;
17 import org.slf4j.Logger;
18 import org.slf4j.LoggerFactory;
19 import org.springframework.beans.factory.annotation.Autowired;
20 import org.springframework.beans.factory.annotation.Value;
21 import org.springframework.boot.ApplicationArguments;
22 import org.springframework.boot.ApplicationRunner;
23 import org.springframework.core.annotation.Order;
24 import org.springframework.stereotype.Component;
25
26 @Component
27 @Order(2)
28 /**
29 * This runner retrieves stored diagnosis keys, the generates and persists the respective diagnosis
30 * key bundles.
31 */
32 public class DiagnosisKeyDistributionRunner implements ApplicationRunner {
33
34 private static final Logger logger = LoggerFactory
35 .getLogger(DiagnosisKeyDistributionRunner.class);
36
37 private static final String VERSION_DIRECTORY = "version";
38
39 @Value("${app.coronawarn.server.services.distribution.version}")
40 private String version;
41
42 @Value("${app.coronawarn.server.services.distribution.paths.output}")
43 private String outputPath;
44
45 @Autowired
46 private CryptoProvider cryptoProvider;
47
48 @Autowired
49 private DiagnosisKeyService diagnosisKeyService;
50
51
52 @Override
53 public void run(ApplicationArguments args) throws IOException {
54 Collection<DiagnosisKey> diagnosisKeys = diagnosisKeyService.getDiagnosisKeys();
55
56 DiagnosisKeysDirectoryImpl diagnosisKeysDirectory =
57 new DiagnosisKeysDirectoryImpl(diagnosisKeys, cryptoProvider);
58
59 IndexDirectory<?> versionDirectory =
60 new IndexDirectoryImpl<>(VERSION_DIRECTORY, __ -> Set.of(version), Object::toString);
61
62 versionDirectory.addDirectoryToAll(__ -> diagnosisKeysDirectory);
63
64 java.io.File outputDirectory = new File(outputPath);
65 clearDirectory(outputDirectory);
66 DirectoryImpl root = new DirectoryImpl(outputDirectory);
67 root.addDirectory(new IndexingDecorator<>(versionDirectory));
68
69 root.prepare(new ImmutableStack<>());
70 root.write();
71 logger.debug("Diagnosis key distribution structure written successfully.");
72 }
73
74 private static void clearDirectory(File directory) throws IOException {
75 FileUtils.deleteDirectory(directory);
76 directory.mkdirs();
77 }
78 }
79
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/DiagnosisKeyDistributionRunner.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/ExposureConfigurationDistributionRunner.java]
1 package app.coronawarn.server.services.distribution.runner;
2
3 import app.coronawarn.server.common.protocols.internal.RiskScoreParameters;
4 import app.coronawarn.server.services.distribution.crypto.CryptoProvider;
5 import app.coronawarn.server.services.distribution.exposureconfig.ExposureConfigurationProvider;
6 import app.coronawarn.server.services.distribution.exposureconfig.UnableToLoadFileException;
7 import app.coronawarn.server.services.distribution.exposureconfig.structure.directory.ExposureConfigurationDirectoryImpl;
8 import app.coronawarn.server.services.distribution.structure.directory.Directory;
9 import app.coronawarn.server.services.distribution.structure.directory.DirectoryImpl;
10 import app.coronawarn.server.services.distribution.structure.directory.IndexDirectory;
11 import app.coronawarn.server.services.distribution.structure.directory.IndexDirectoryImpl;
12 import app.coronawarn.server.services.distribution.structure.directory.decorator.IndexingDecorator;
13 import app.coronawarn.server.services.distribution.structure.util.ImmutableStack;
14 import java.io.File;
15 import java.util.Set;
16 import org.slf4j.Logger;
17 import org.slf4j.LoggerFactory;
18 import org.springframework.beans.factory.annotation.Autowired;
19 import org.springframework.beans.factory.annotation.Value;
20 import org.springframework.boot.ApplicationArguments;
21 import org.springframework.boot.ApplicationRunner;
22 import org.springframework.core.annotation.Order;
23 import org.springframework.stereotype.Component;
24
25 @Component
26 @Order(1)
27 /**
28 * Reads the exposure configuration parameters from the respective file in the class path, then
29 * generates and persists the respective exposure configuration bundle.
30 */
31 public class ExposureConfigurationDistributionRunner implements ApplicationRunner {
32
33 private static final Logger logger =
34 LoggerFactory.getLogger(ExposureConfigurationDistributionRunner.class);
35
36 @Value("${app.coronawarn.server.services.distribution.version}")
37 private String version;
38
39 @Value("${app.coronawarn.server.services.distribution.paths.output}")
40 private String outputPath;
41
42 @Autowired
43 private CryptoProvider cryptoProvider;
44
45 private static final String VERSION_DIRECTORY = "version";
46
47 @Override
48 public void run(ApplicationArguments args) {
49 var riskScoreParameters = readExposureConfiguration();
50 IndexDirectory<?> versionDirectory =
51 new IndexDirectoryImpl<>(VERSION_DIRECTORY, __ -> Set.of(version), Object::toString);
52 ExposureConfigurationDirectoryImpl parametersDirectory =
53 new ExposureConfigurationDirectoryImpl(riskScoreParameters, cryptoProvider);
54 Directory root = new DirectoryImpl(new File(outputPath));
55 versionDirectory.addDirectoryToAll(__ -> parametersDirectory);
56 root.addDirectory(new IndexingDecorator<>(versionDirectory));
57 root.prepare(new ImmutableStack<>());
58 root.write();
59 logger.debug("Exposure configuration structure written successfully.");
60 }
61
62 private RiskScoreParameters readExposureConfiguration() {
63 try {
64 return ExposureConfigurationProvider.readMasterFile();
65 } catch (UnableToLoadFileException e) {
66 logger.error("Could not load exposure configuration parameters", e);
67 throw new RuntimeException(e);
68 }
69 }
70 }
71
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/ExposureConfigurationDistributionRunner.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/S3DistributionRunner.java]
1 package app.coronawarn.server.services.distribution.runner;
2
3 import app.coronawarn.server.services.distribution.objectstore.S3Publisher;
4 import java.io.IOException;
5 import java.nio.file.Path;
6 import org.slf4j.Logger;
7 import org.slf4j.LoggerFactory;
8 import org.springframework.beans.factory.annotation.Autowired;
9 import org.springframework.beans.factory.annotation.Value;
10 import org.springframework.boot.ApplicationArguments;
11 import org.springframework.boot.ApplicationRunner;
12 import org.springframework.core.annotation.Order;
13 import org.springframework.stereotype.Component;
14
15 /**
16 * This runner will sync the base working directory to the S3.
17 */
18 @Component
19 @Order(3)
20 public class S3DistributionRunner implements ApplicationRunner {
21
22 private Logger logger = LoggerFactory.getLogger(this.getClass());
23
24 @Value("${app.coronawarn.server.services.distribution.paths.output}")
25 private String workdir;
26
27 @Autowired
28 private S3Publisher s3Publisher;
29
30 @Override
31 public void run(ApplicationArguments args) {
32 try {
33 Path pathToDistribute = Path.of(workdir).toAbsolutePath();
34
35 s3Publisher.publishFolder(pathToDistribute);
36 } catch (IOException | UnsupportedOperationException e) {
37 logger.error("Distribution failed.", e);
38 }
39 logger.debug("Data pushed to CDN successfully.");
40 }
41 }
42
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/S3DistributionRunner.java]
[start of services/distribution/src/main/resources/application.properties]
1 logging.level.org.springframework.web=INFO
2 logging.level.app.coronawarn=INFO
3 spring.main.web-application-type=NONE
4
5 app.coronawarn.server.services.distribution.version=v1
6 app.coronawarn.server.services.distribution.paths.output=out
7 app.coronawarn.server.services.distribution.paths.privatekey=classpath:certificates/client/private.pem
8 app.coronawarn.server.services.distribution.paths.certificate=classpath:certificates/chain/certificate.crt
9
10 spring.flyway.enabled=false
11 spring.jpa.hibernate.ddl-auto=validate
12
[end of services/distribution/src/main/resources/application.properties]
</code>
Here is an example of a patch file. It consists of changes to the code base. It specifies the file names, the line numbers of each change, and the removed and added lines. A single patch file can contain changes to multiple files.
<patch>
--- a/file.py
+++ b/file.py
@@ -1,27 +1,35 @@
def euclidean(a, b):
- while b:
- a, b = b, a % b
- return a
+ if b == 0:
+ return a
+ return euclidean(b, a % b)
def bresenham(x0, y0, x1, y1):
points = []
dx = abs(x1 - x0)
dy = abs(y1 - y0)
- sx = 1 if x0 < x1 else -1
- sy = 1 if y0 < y1 else -1
- err = dx - dy
+ x, y = x0, y0
+ sx = -1 if x0 > x1 else 1
+ sy = -1 if y0 > y1 else 1
- while True:
- points.append((x0, y0))
- if x0 == x1 and y0 == y1:
- break
- e2 = 2 * err
- if e2 > -dy:
+ if dx > dy:
+ err = dx / 2.0
+ while x != x1:
+ points.append((x, y))
err -= dy
- x0 += sx
- if e2 < dx:
- err += dx
- y0 += sy
+ if err < 0:
+ y += sy
+ err += dx
+ x += sx
+ else:
+ err = dy / 2.0
+ while y != y1:
+ points.append((x, y))
+ err -= dx
+ if err < 0:
+ x += sx
+ err += dy
+ y += sy
+ points.append((x, y))
return points
</patch>
I need you to solve the provded issue by generating a single patch file that I can apply directly to this repository using git apply. Please respond with a single patch file in the format shown above.
Respond below:
| corona-warn-app/cwa-server | 23b492fe7b9f0821f2a8c34516cb858efcfaa55b | Set Retention Days to 14
Any key data that is associated to a point in time older than 14 days shall be removed from the database and will also be removed from the CDN and therefore the index file.
| 2020-05-14T23:08:17 | <patch>
diff --git a/common/persistence/src/main/java/app/coronawarn/server/common/persistence/repository/DiagnosisKeyRepository.java b/common/persistence/src/main/java/app/coronawarn/server/common/persistence/repository/DiagnosisKeyRepository.java
--- a/common/persistence/src/main/java/app/coronawarn/server/common/persistence/repository/DiagnosisKeyRepository.java
+++ b/common/persistence/src/main/java/app/coronawarn/server/common/persistence/repository/DiagnosisKeyRepository.java
@@ -1,9 +1,18 @@
package app.coronawarn.server.common.persistence.repository;
import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
+import javax.transaction.Transactional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface DiagnosisKeyRepository extends JpaRepository<DiagnosisKey, Long> {
+
+ /**
+ * Deletes all entries that have a submission timestamp lesser or equal to the specified one.
+ *
+ * @param submissionTimestamp the submission timestamp up to which entries will be deleted.
+ */
+ @Transactional
+ public void deleteBySubmissionTimestampIsLessThanEqual(long submissionTimestamp);
}
diff --git a/common/persistence/src/main/java/app/coronawarn/server/common/persistence/service/DiagnosisKeyService.java b/common/persistence/src/main/java/app/coronawarn/server/common/persistence/service/DiagnosisKeyService.java
--- a/common/persistence/src/main/java/app/coronawarn/server/common/persistence/service/DiagnosisKeyService.java
+++ b/common/persistence/src/main/java/app/coronawarn/server/common/persistence/service/DiagnosisKeyService.java
@@ -1,7 +1,11 @@
package app.coronawarn.server.common.persistence.service;
+import static java.time.ZoneOffset.UTC;
+
import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
import app.coronawarn.server.common.persistence.repository.DiagnosisKeyRepository;
+import java.time.Instant;
+import java.time.LocalDateTime;
import java.util.Collection;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
@@ -30,4 +34,18 @@ public void saveDiagnosisKeys(Collection<DiagnosisKey> diagnosisKeys) {
public List<DiagnosisKey> getDiagnosisKeys() {
return keyRepository.findAll(Sort.by(Sort.Direction.ASC, "submissionTimestamp"));
}
+
+ /**
+ * Deletes all diagnosis key entries which have a submission timestamp that is older than the
+ * specified number of days.
+ *
+ * @param daysToRetain the number of days until which diagnosis keys will be retained.
+ */
+ public void applyRetentionPolicy(int daysToRetain) {
+ long threshold = LocalDateTime
+ .ofInstant(Instant.now(), UTC)
+ .minusDays(daysToRetain)
+ .toEpochSecond(UTC) / 3600L;
+ keyRepository.deleteBySubmissionTimestampIsLessThanEqual(threshold);
+ }
}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/DiagnosisKeyDistributionRunner.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/DiagnosisKeyDistributionRunner.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/DiagnosisKeyDistributionRunner.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/DiagnosisKeyDistributionRunner.java
@@ -24,7 +24,7 @@
import org.springframework.stereotype.Component;
@Component
-@Order(2)
+@Order(3)
/**
* This runner retrieves stored diagnosis keys, the generates and persists the respective diagnosis
* key bundles.
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/ExposureConfigurationDistributionRunner.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/ExposureConfigurationDistributionRunner.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/ExposureConfigurationDistributionRunner.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/ExposureConfigurationDistributionRunner.java
@@ -23,7 +23,7 @@
import org.springframework.stereotype.Component;
@Component
-@Order(1)
+@Order(2)
/**
* Reads the exposure configuration parameters from the respective file in the class path, then
* generates and persists the respective exposure configuration bundle.
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/RetentionPolicyRunner.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/RetentionPolicyRunner.java
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/RetentionPolicyRunner.java
@@ -0,0 +1,37 @@
+package app.coronawarn.server.services.distribution.runner;
+
+import app.coronawarn.server.common.persistence.service.DiagnosisKeyService;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.boot.ApplicationArguments;
+import org.springframework.boot.ApplicationRunner;
+import org.springframework.core.annotation.Order;
+import org.springframework.stereotype.Component;
+
+/**
+ * This runner removes any diagnosis keys from the database that were submitted before a configured
+ * threshold of days.
+ */
+@Component
+@Order(1)
+public class RetentionPolicyRunner implements ApplicationRunner {
+
+ private static final Logger logger = LoggerFactory
+ .getLogger(RetentionPolicyRunner.class);
+
+ @Autowired
+ private DiagnosisKeyService diagnosisKeyService;
+
+ @Value("${app.coronawarn.server.services.distribution.retention_days}")
+ private Integer rententionDays;
+
+ @Override
+ public void run(ApplicationArguments args) {
+ diagnosisKeyService.applyRetentionPolicy(rententionDays);
+
+ logger.debug("Retention policy applied successfully. Deleted all entries older that {} days.",
+ rententionDays);
+ }
+}
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/S3DistributionRunner.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/S3DistributionRunner.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/S3DistributionRunner.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/runner/S3DistributionRunner.java
@@ -16,7 +16,7 @@
* This runner will sync the base working directory to the S3.
*/
@Component
-@Order(3)
+@Order(4)
public class S3DistributionRunner implements ApplicationRunner {
private Logger logger = LoggerFactory.getLogger(this.getClass());
diff --git a/services/distribution/src/main/resources/application.properties b/services/distribution/src/main/resources/application.properties
--- a/services/distribution/src/main/resources/application.properties
+++ b/services/distribution/src/main/resources/application.properties
@@ -2,6 +2,7 @@ logging.level.org.springframework.web=INFO
logging.level.app.coronawarn=INFO
spring.main.web-application-type=NONE
+app.coronawarn.server.services.distribution.retention_days=14
app.coronawarn.server.services.distribution.version=v1
app.coronawarn.server.services.distribution.paths.output=out
app.coronawarn.server.services.distribution.paths.privatekey=classpath:certificates/client/private.pem
</patch> | diff --git a/common/persistence/src/test/java/app/coronawarn/server/common/persistence/TestApplication.java b/common/persistence/src/test/java/app/coronawarn/server/common/persistence/TestApplication.java
new file mode 100644
--- /dev/null
+++ b/common/persistence/src/test/java/app/coronawarn/server/common/persistence/TestApplication.java
@@ -0,0 +1,15 @@
+package app.coronawarn.server.common.persistence;
+
+import app.coronawarn.server.common.persistence.service.DiagnosisKeyService;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+@SpringBootApplication
+@Configuration
+public class TestApplication {
+ @Bean
+ DiagnosisKeyService createDiagnosisKeyService() {
+ return new DiagnosisKeyService();
+ }
+}
diff --git a/common/persistence/src/test/java/app/coronawarn/server/common/persistence/service/DiagnosisKeyServiceTest.java b/common/persistence/src/test/java/app/coronawarn/server/common/persistence/service/DiagnosisKeyServiceTest.java
new file mode 100644
--- /dev/null
+++ b/common/persistence/src/test/java/app/coronawarn/server/common/persistence/service/DiagnosisKeyServiceTest.java
@@ -0,0 +1,125 @@
+package app.coronawarn.server.common.persistence.service;
+
+import static java.time.ZoneOffset.UTC;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import app.coronawarn.server.common.persistence.domain.DiagnosisKey;
+import app.coronawarn.server.common.persistence.repository.DiagnosisKeyRepository;
+import java.time.OffsetDateTime;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import org.assertj.core.util.Lists;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
+
+@DataJpaTest
+public class DiagnosisKeyServiceTest {
+
+ @Autowired
+ private DiagnosisKeyService diagnosisKeyService;
+
+ @Autowired
+ private DiagnosisKeyRepository diagnosisKeyRepository;
+
+ @AfterEach
+ public void tearDown() {
+ diagnosisKeyRepository.deleteAll();
+ }
+
+ @Test
+ void testRetrievalForEmptyDB() {
+ var actKeys = diagnosisKeyService.getDiagnosisKeys();
+ assertDiagnosisKeysEqual(Lists.emptyList(), actKeys);
+ }
+
+ @Test
+ void testSaveAndRetrieve() {
+ var expKeys = List.of(buildDiagnosisKeyForSubmissionTimestamp(0L));
+
+ diagnosisKeyService.saveDiagnosisKeys(expKeys);
+ var actKeys = diagnosisKeyService.getDiagnosisKeys();
+
+ assertDiagnosisKeysEqual(expKeys, actKeys);
+ }
+
+ @Test
+ void testSortedRetrievalResult() {
+ var expKeys = new ArrayList<>(List.of(
+ buildDiagnosisKeyForSubmissionTimestamp(1L),
+ buildDiagnosisKeyForSubmissionTimestamp(0L)));
+
+ diagnosisKeyService.saveDiagnosisKeys(expKeys);
+
+ // reverse to match expected sort order
+ Collections.reverse(expKeys);
+ var actKeys = diagnosisKeyService.getDiagnosisKeys();
+
+ assertDiagnosisKeysEqual(expKeys, actKeys);
+ }
+
+ @Test
+ void testApplyRetentionPolicyForEmptyDb() {
+ diagnosisKeyService.applyRetentionPolicy(1);
+ var actKeys = diagnosisKeyService.getDiagnosisKeys();
+ assertDiagnosisKeysEqual(Lists.emptyList(), actKeys);
+ }
+
+ @Test
+ void testApplyRetentionPolicyForOneNotApplicableEntry() {
+ var expKeys = List.of(buildDiagnosisKeyForDateTime(OffsetDateTime.now(UTC).minusHours(23)));
+
+ diagnosisKeyService.saveDiagnosisKeys(expKeys);
+ diagnosisKeyService.applyRetentionPolicy(1);
+ var actKeys = diagnosisKeyService.getDiagnosisKeys();
+
+ assertDiagnosisKeysEqual(expKeys, actKeys);
+ }
+
+ @Test
+ void testApplyRetentionPolicyForOneApplicableEntry() {
+ var keys = List.of(buildDiagnosisKeyForDateTime(OffsetDateTime.now(UTC).minusDays(1L)));
+
+ diagnosisKeyService.saveDiagnosisKeys(keys);
+ diagnosisKeyService.applyRetentionPolicy(1);
+ var actKeys = diagnosisKeyService.getDiagnosisKeys();
+
+ assertDiagnosisKeysEqual(Lists.emptyList(), actKeys);
+ }
+
+ private void assertDiagnosisKeysEqual(List<DiagnosisKey> expDiagKeys,
+ List<DiagnosisKey> actDiagKeys) {
+ assertEquals(expDiagKeys.size(), actDiagKeys.size(), "Cardinality mismatch");
+
+ for (int i = 0; i < expDiagKeys.size(); i++) {
+ var expDiagKey = expDiagKeys.get(i);
+ var actDiagKey = actDiagKeys.get(i);
+
+ assertEquals(
+ expDiagKey.getKeyData(), actDiagKey.getKeyData(), "keyData mismatch");
+ assertEquals(expDiagKey.getRollingStartNumber(), actDiagKey.getRollingStartNumber(),
+ "rollingStartNumber mismatch");
+ assertEquals(expDiagKey.getRollingPeriod(), actDiagKey.getRollingPeriod(),
+ "rollingPeriod mismatch");
+ assertEquals(expDiagKey.getTransmissionRiskLevel(), actDiagKey.getTransmissionRiskLevel(),
+ "transmissionRiskLevel mismatch");
+ assertEquals(expDiagKey.getSubmissionTimestamp(), actDiagKey.getSubmissionTimestamp(),
+ "submissionTimestamp mismatch");
+ }
+ }
+
+ public static DiagnosisKey buildDiagnosisKeyForSubmissionTimestamp(long submissionTimeStamp) {
+ return DiagnosisKey.builder()
+ .withKeyData(new byte[16])
+ .withRollingStartNumber(0L)
+ .withRollingPeriod(1L)
+ .withTransmissionRiskLevel(2)
+ .withSubmissionTimestamp(submissionTimeStamp).build();
+ }
+
+ public static DiagnosisKey buildDiagnosisKeyForDateTime(OffsetDateTime dateTime) {
+ return buildDiagnosisKeyForSubmissionTimestamp(dateTime.toEpochSecond() / 3600);
+ }
+}
diff --git a/common/persistence/src/test/resources/application.properties b/common/persistence/src/test/resources/application.properties
new file mode 100644
--- /dev/null
+++ b/common/persistence/src/test/resources/application.properties
@@ -0,0 +1,6 @@
+spring.flyway.enabled=false
+spring.jpa.hibernate.ddl-auto=create
+spring.jpa.properties.hibernate.show_sql=false
+spring.main.banner-mode=off
+logging.level.org.springframework=off
+logging.level.root=off
\ No newline at end of file
diff --git a/common/persistence/src/test/resources/logback-test.xml b/common/persistence/src/test/resources/logback-test.xml
new file mode 100644
--- /dev/null
+++ b/common/persistence/src/test/resources/logback-test.xml
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<configuration>
+ <include resource="org/springframework/boot/logging/logback/base.xml" />
+ <logger name="org.springframework" level="off"/>
+ <logger name="root" level="ERROR"/>
+</configuration>
diff --git a/services/distribution/src/test/resources/application.properties b/services/distribution/src/test/resources/application.properties
--- a/services/distribution/src/test/resources/application.properties
+++ b/services/distribution/src/test/resources/application.properties
@@ -3,6 +3,7 @@ logging.level.org.springframework=off
logging.level.root=off
spring.main.banner-mode=off
+app.coronawarn.server.services.distribution.retention_days=14
app.coronawarn.server.services.distribution.version=v1
app.coronawarn.server.services.distribution.paths.output=out
app.coronawarn.server.services.distribution.paths.privatekey=classpath:certificates/client/private.pem
| |||||
corona-warn-app__cwa-server-352 | You will be provided with a partial code base and an issue statement explaining a problem to resolve.
<issue>
Sonar - Mitigate/Audit synchronized class "Stack"
See https://sonarcloud.io/project/issues?id=corona-warn-app_cwa-server&issues=AXI3CJu7vPFV4POpyUFA&open=AXI3CJu7vPFV4POpyUFA
Strongly consider using existing [data structure implementations.](https://www.eclipse.org/collections/javadoc/9.2.0/org/eclipse/collections/api/stack/ImmutableStack.html)
</issue>
<code>
[start of README.md]
1 <!-- markdownlint-disable MD041 -->
2 <h1 align="center">
3 Corona-Warn-App Server
4 </h1>
5
6 <p align="center">
7 <a href="https://github.com/corona-warn-app/cwa-server/commits/" title="Last Commit"><img src="https://img.shields.io/github/last-commit/corona-warn-app/cwa-server?style=flat"></a>
8 <a href="https://github.com/corona-warn-app/cwa-server/issues" title="Open Issues"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat"></a>
9 <a href="https://circleci.com/gh/corona-warn-app/cwa-server" title="Build Status"><img src="https://circleci.com/gh/corona-warn-app/cwa-server.svg?style=shield&circle-token=4ab059989d10709df19eb4b98ab7c121a25e981a"></a>
10 <a href="https://sonarcloud.io/dashboard?id=corona-warn-app_cwa-server" title="Quality Gate"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=alert_status"></a>
11 <a href="https://sonarcloud.io/component_measures?id=corona-warn-app_cwa-server&metric=Coverage&view=list" title="Coverage"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=coverage"></a>
12 <a href="https://github.com/corona-warn-app/cwa-server/blob/master/LICENSE" title="License"><img src="https://img.shields.io/badge/License-Apache%202.0-green.svg?style=flat"></a>
13 </p>
14
15 <p align="center">
16 <a href="#development">Development</a> •
17 <a href="#service-apis">Service APIs</a> •
18 <a href="#documentation">Documentation</a> •
19 <a href="#support-and-feedback">Support</a> •
20 <a href="#how-to-contribute">Contribute</a> •
21 <a href="#contributors">Contributors</a> •
22 <a href="#repositories">Repositories</a> •
23 <a href="#licensing">Licensing</a>
24 </p>
25
26 The goal of this project is to develop the official Corona-Warn-App for Germany based on the exposure notification API from [Apple](https://www.apple.com/covid19/contacttracing/) and [Google](https://www.google.com/covid19/exposurenotifications/). The apps (for both iOS and Android) use Bluetooth technology to exchange anonymous encrypted data with other mobile phones (on which the app is also installed) in the vicinity of an app user's phone. The data is stored locally on each user's device, preventing authorities or other parties from accessing or controlling the data. This repository contains the **implementation of the server for encryption keys** for the Corona-Warn-App. This implementation is still a **work in progress**, and the code it contains is currently alpha-quality code.
27
28 In this documentation, Corona-Warn-App services are also referred to as CWA services.
29
30 ## Architecture Overview
31
32 You can find the architecture overview [here](/docs/architecture-overview.md), which will give you
33 a good starting point in how the backend services interact with other services, and what purpose
34 they serve.
35
36 ## Development
37
38 After you've checked out this repository, you can run the application in one of the following ways:
39
40 * As a [Docker](https://www.docker.com/)-based deployment on your local machine. You can run either:
41 * Single components using the respective Dockerfile or
42 * The full backend using the Docker Compose (which is considered the most convenient way)
43 * As a [Maven](https://maven.apache.org)-based build on your local machine.
44 If you want to develop something in a single component, this approach is preferable.
45
46 ### Docker-Based Deployment
47
48 If you want to use Docker-based deployment, you need to install Docker on your local machine. For more information about downloading and installing Docker, see the [official Docker documentation](https://docs.docker.com/get-docker/).
49
50 #### Running the Full CWA Backend Using Docker Compose
51
52 For your convenience, a full setup including the generation of test data has been prepared using [Docker Compose](https://docs.docker.com/compose/reference/overview/). To build the backend services, run ```docker-compose build``` in the repository's root directory. A default configuration file can be found under ```.env```in the root folder of the repository. The default values for the local Postgres and Zenko Cloudserver should be changed in this file before docker-compose is run.
53
54 Once the services are built, you can start the whole backend using ```docker-compose up```.
55 The distribution service runs once and then finishes. If you want to trigger additional distribution runs, run ```docker-compose run distribution```.
56
57 The docker-compose contains the following services:
58
59 Service | Description | Endpoint and Default Credentials
60 ------------------|-------------|-----------
61 submission | The Corona-Warn-App submission service | `http://localhost:8000` <br> `http://localhost:8006` (for actuator endpoint)
62 distribution | The Corona-Warn-App distribution service | NO ENDPOINT
63 postgres | A [postgres] database installation | `postgres:8001` <br> Username: postgres <br> Password: postgres
64 pgadmin | A [pgadmin](https://www.pgadmin.org/) installation for the postgres database | `http://localhost:8002` <br> Username: [email protected] <br> Password: password
65 cloudserver | [Zenko CloudServer] is a S3-compliant object store | `http://localhost:8003/` <br> Access key: accessKey1 <br> Secret key: verySecretKey1
66 verification-fake | A very simple fake implementation for the tan verification. | `http://localhost:8004/version/v1/tan/verify` <br> The only valid tan is "b69ab69f-9823-4549-8961-c41sa74b2f36"
67
68 ##### Known Limitation
69
70 In rare cases the docker-compose runs into a timing issue if the distribution service starts before the bucket of the objectstore was created. This is not a big issue as you can simply run ```docker-compose run distribution``` to trigger additional distribution runs after the objectstore was initialized.
71
72 #### Running Single CWA Services Using Docker
73
74 If you would like to build and run a single CWA service, it's considered easiest to run them in a Docker environment. You can do this using the script provided in the respective CWA service directory. The Docker script first builds the CWA service and then creates an image for the runtime, which means that there are no additional dependencies for you to install.
75
76 To build and run the distribution service, run the following command:
77
78 ```bash
79 ./services/distribution/build_and_run.sh
80 ```
81
82 To build and run the submission service, run the following command:
83
84 ```bash
85 ./services/submission/build_and_run.sh
86 ```
87
88 The submission service is available on [localhost:8080](http://localhost:8080 ).
89
90 ### Maven-Based Build
91
92 If you want to actively develop in one of the CWA services, the Maven-based runtime is most suitable.
93 To prepare your machine to run the CWA project locally, we recommend that you first ensure that you've installed the following:
94
95 * Minimum JDK Version 11: [OpenJDK](https://openjdk.java.net/) / [SapMachine](https://sap.github.io/SapMachine/)
96 * [Maven 3.6](https://maven.apache.org/)
97 * [Postgres]
98 * [Zenko CloudServer]
99
100 #### Configure
101
102 After you made sure that the specified dependencies are running, configure them in the respective configuration files.
103
104 * Configure the Postgres connection in the [submission config](./services/submission/src/main/resources/application.yaml) and in the [distribution config](./services/distribution/src/main/resources/application.yaml)
105 * Configure the S3 compatible object storage in the [distribution config](./services/distribution/src/main/resources/application.yaml)
106 * Configure the private key for the distribution service, the path need to be prefixed with `file:`
107 * `VAULT_FILESIGNING_SECRET` should be the path to the private key, example available in `<repo-root>/docker-compose-test-secrets/private.pem`
108
109 #### Build
110
111 After you've checked out the repository, to build the project, run ```mvn install``` in your base directory.
112
113 #### Run
114
115 Navigate to the service you want to start and run the spring-boot:run target. The configured Postgres and the configured S3 compliant object storage are used as default. When you start the submission service, the endpoint is available on your local port 8080.
116
117 If you want to start the submission service, for example, you start it as follows:
118
119 ```bash
120 cd services/submission/
121 mvn spring-boot:run
122 ```
123
124 #### Debugging
125
126 To enable the `DEBUG` log level, you can run the application using the Spring `dev` profile.
127
128 ```bash
129 mvn spring-boot:run -Dspring-boot.run.profiles=dev
130 ```
131
132 To be able to set breakpoints (e.g. in IntelliJ), it may be necessary to use the ```-Dspring-boot.run.fork=false``` parameter.
133
134 ## Service APIs
135
136 The API that is being exposed by the backend services is documented in an [OpenAPI](https://www.openapis.org/) specification. The specification files are available at the following locations:
137
138 Service | OpenAPI Specification
139 -------------|-------------
140 Submission Service | [services/submission/api_v1.json](https://github.com/corona-warn-app/cwa-server/raw/master/services/submission/api_v1.json)
141 Distribution Service | [services/distribution/api_v1.json)](https://github.com/corona-warn-app/cwa-server/raw/master/services/distribution/api_v1.json)
142
143 ## Spring Profiles
144
145 ### Distribution
146
147 Profile | Effect
148 -------------|-------------
149 `dev` | Turns the log level to `DEBUG` and sets the app package ID in the export packages' signature info to `de.rki.coronawarnapp-dev` so that test certificates (instead of production certificates) will be used for client-side validation.
150 `cloud` | Removes default values for the `datasource` and `objectstore` configurations.
151 `demo` | Includes incomplete days and hours into the distribution run, thus creating aggregates for the current day and the current hour (and including both in the respective indices). When running multiple distributions in one hour with this profile, the date aggregate for today and the hours aggregate for the current hour will be updated and overwritten.
152 `testdata` | Causes test data to be inserted into the database before each distribution run. By default, around 1000 random diagnosis keys will be generated per hour. If there are no diagnosis keys in the database yet, random keys will be generated for every hour from the beginning of the retention period (14 days ago at 00:00 UTC) until one hour before the present hour. If there are already keys in the database, the random keys will be generated for every hour from the latest diagnosis key in the database (by submission timestamp) until one hour before the present hour (or none at all, if the latest diagnosis key in the database was submitted one hour ago or later).
153
154 ### Submission
155
156 Profile | Effect
157 -------------|-------------
158 `dev` | Turns the log level to `DEBUG`.
159 `cloud` | Removes default values for the `datasource` configuration.
160
161 ## Documentation
162
163 The full documentation for the Corona-Warn-App can be found in the [cwa-documentation](https://github.com/corona-warn-app/cwa-documentation) repository. The documentation repository contains technical documents, architecture information, and whitepapers related to this implementation.
164
165 ## Support and Feedback
166
167 The following channels are available for discussions, feedback, and support requests:
168
169 | Type | Channel |
170 | ------------------------ | ------------------------------------------------------ |
171 | **General Discussion** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="General Discussion"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/question.svg?style=flat-square"></a> </a> |
172 | **Concept Feedback** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="Open Concept Feedback"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/architecture.svg?style=flat-square"></a> |
173 | **Backend Issue** | <a href="https://github.com/corona-warn-app/cwa-server/issues/new/choose" title="Open Backend Issue"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat-square"></a> |
174 | **Other Requests** | <a href="mailto:[email protected]" title="Email CWA Team"><img src="https://img.shields.io/badge/email-CWA%20team-green?logo=mail.ru&style=flat-square&logoColor=white"></a> |
175
176 ## How to Contribute
177
178 Contribution and feedback are 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.
179
180 ## Contributors
181
182 The German government has asked SAP and Deutsche Telekom to develop the Corona-Warn-App for Germany as open source software. Deutsche Telekom is providing the network and mobile technology and will operate and run the backend for the app in a safe, scalable and stable manner. SAP is responsible for the app development, its framework and the underlying platform. Therefore, development teams of SAP and Deutsche Telekom are contributing to this project. At the same time 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.
183
184 ## Repositories
185
186 The following public repositories are currently available for the Corona-Warn-App:
187
188 | Repository | Description |
189 | ------------------- | --------------------------------------------------------------------- |
190 | [cwa-documentation] | Project overview, general documentation, and white papers |
191 | [cwa-server] | Backend implementation for the Apple/Google exposure notification API|
192 | [cwa-verification-server] | Backend implementation of the verification process|
193
194 [cwa-documentation]: https://github.com/corona-warn-app/cwa-documentation
195 [cwa-server]: https://github.com/corona-warn-app/cwa-server
196 [cwa-verification-server]: https://github.com/corona-warn-app/cwa-verification-server
197 [Postgres]: https://www.postgresql.org/
198 [HSQLDB]: http://hsqldb.org/
199 [Zenko CloudServer]: https://github.com/scality/cloudserver
200
201 ## Licensing
202
203 Copyright (c) 2020 SAP SE or an SAP affiliate company.
204
205 Licensed under the **Apache License, Version 2.0** (the "License"); you may not use this file except in compliance with the License.
206
207 You may obtain a copy of the License at <https://www.apache.org/licenses/LICENSE-2.0>.
208
209 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.
210
[end of README.md]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/directory/IndexDirectory.java]
1 /*
2 * Corona-Warn-App
3 *
4 * SAP SE and all other contributors /
5 * copyright owners license this file to you under the Apache
6 * License, Version 2.0 (the "License"); you may not use this
7 * file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20 package app.coronawarn.server.services.distribution.assembly.structure.directory;
21
22 import app.coronawarn.server.services.distribution.assembly.structure.Writable;
23 import app.coronawarn.server.services.distribution.assembly.structure.util.ImmutableStack;
24 import app.coronawarn.server.services.distribution.assembly.structure.util.functional.Formatter;
25 import app.coronawarn.server.services.distribution.assembly.structure.util.functional.WritableFunction;
26 import java.util.Set;
27 import java.util.Stack;
28
29 /**
30 * A "meta {@link Directory directory}" that maps its on-disk subdirectories to some list of elements. This list of
31 * elements is determined by a {@link WritableFunction}.
32 *
33 * @param <W> The specific type of {@link Writable} that this {@link IndexDirectory} can be a child of.
34 * @param <T> The type of the elements in the index.
35 */
36 public interface IndexDirectory<T, W extends Writable<W>> extends Directory<W> {
37
38 /**
39 * Adds a writable under the name {@code name}, whose content is calculated by the {@code writableFunction} to each
40 * one of the directories created from the index. The {@code fileFunction} calculates the file content from a {@link
41 * java.util.Stack} of parent {@link IndexDirectoryOnDisk} indices. File content calculation happens on {@link
42 * DirectoryOnDisk#write}.
43 *
44 * @param writableFunction A function that can output a new writable.
45 */
46 void addWritableToAll(WritableFunction<W> writableFunction);
47
48 /**
49 * Calls the {@link app.coronawarn.server.services.distribution.assembly.structure.util.functional.IndexFunction} with
50 * the {@code indices} to calculate and return the elements of the index of this {@link IndexDirectory}.
51 *
52 * @param indices A {@link Stack} of parameters from all {@link IndexDirectory IndexDirectories} further up in the
53 * hierarchy. The Stack may contain different types, depending on the types {@code T} of {@link
54 * IndexDirectory IndexDirectories} further up in the hierarchy.
55 */
56 Set<T> getIndex(ImmutableStack<Object> indices);
57
58 /**
59 * Returns the function used to format elements of the index (e.g. for writing to disk).
60 */
61 Formatter<T> getIndexFormatter();
62 }
63
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/directory/IndexDirectory.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/directory/IndexDirectoryOnDisk.java]
1 /*
2 * Corona-Warn-App
3 *
4 * SAP SE and all other contributors /
5 * copyright owners license this file to you under the Apache
6 * License, Version 2.0 (the "License"); you may not use this
7 * file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20 package app.coronawarn.server.services.distribution.assembly.structure.directory;
21
22 import app.coronawarn.server.services.distribution.assembly.structure.Writable;
23 import app.coronawarn.server.services.distribution.assembly.structure.WritableOnDisk;
24 import app.coronawarn.server.services.distribution.assembly.structure.util.ImmutableStack;
25 import app.coronawarn.server.services.distribution.assembly.structure.util.functional.Formatter;
26 import app.coronawarn.server.services.distribution.assembly.structure.util.functional.IndexFunction;
27 import app.coronawarn.server.services.distribution.assembly.structure.util.functional.WritableFunction;
28 import java.util.HashSet;
29 import java.util.Set;
30 import java.util.Stack;
31
32 /**
33 * An {@link IndexDirectory} that can be written to disk.
34 *
35 * @param <T> The type of the elements in the index.
36 */
37 public class IndexDirectoryOnDisk<T> extends DirectoryOnDisk implements IndexDirectory<T, WritableOnDisk> {
38
39 // Writables to be written into every directory created through the index
40 private final Set<WritableFunction<WritableOnDisk>> metaWritables = new HashSet<>();
41 private final IndexFunction<T> indexFunction;
42 private final Formatter<T> indexFormatter;
43
44 /**
45 * Constructs a {@link IndexDirectoryOnDisk} instance that represents a directory, containing an index in the form of
46 * sub directories.
47 *
48 * @param name The name that this directory should have on disk.
49 * @param indexFunction An {@link IndexFunction} that calculates the index of this {@link IndexDirectoryOnDisk} from
50 * a {@link java.util.Stack} of parent {@link IndexDirectoryOnDisk} indices. The top element of
51 * the stack is from the closest {@link IndexDirectoryOnDisk} in the parent chain.
52 * @param indexFormatter A {@link Formatter} used to format the directory name for each index element returned by the
53 * {@link IndexDirectoryOnDisk#indexFunction}.
54 */
55 public IndexDirectoryOnDisk(String name, IndexFunction<T> indexFunction, Formatter<T> indexFormatter) {
56 super(name);
57 this.indexFunction = indexFunction;
58 this.indexFormatter = indexFormatter;
59 }
60
61 @Override
62 public Formatter<T> getIndexFormatter() {
63 return this.indexFormatter;
64 }
65
66 @Override
67 public Set<T> getIndex(ImmutableStack<Object> indices) {
68 return this.indexFunction.apply(indices);
69 }
70
71 @Override
72 public void addWritableToAll(WritableFunction<WritableOnDisk> writableFunction) {
73 this.metaWritables.add(writableFunction);
74 }
75
76 /**
77 * Creates a new subdirectory for every element of the {@link IndexDirectory#getIndex index} and writes all its
78 * {@link IndexDirectory#addWritableToAll writables} to those. The respective element of the index will be pushed
79 * onto the Stack for subsequent {@link Writable#prepare} calls.
80 *
81 * @param indices A {@link Stack} of parameters from all {@link IndexDirectory IndexDirectories} further up in the
82 * hierarchy. The Stack may contain different types, depending on the types {@code T} of
83 * {@link IndexDirectory IndexDirectories} further up in the hierarchy.
84 */
85 @Override
86 public void prepare(ImmutableStack<Object> indices) {
87 super.prepare(indices);
88 this.prepareIndex(indices);
89 }
90
91 private void prepareIndex(ImmutableStack<Object> indices) {
92 this.getIndex(indices).forEach(currentIndex -> {
93 ImmutableStack<Object> newIndices = indices.push(currentIndex);
94 DirectoryOnDisk subDirectory = makeSubDirectory(currentIndex);
95 prepareMetaWritables(newIndices, subDirectory);
96 });
97 }
98
99 private DirectoryOnDisk makeSubDirectory(T index) {
100 DirectoryOnDisk subDirectory = new DirectoryOnDisk(this.indexFormatter.apply(index).toString());
101 this.addWritable(subDirectory);
102 return subDirectory;
103 }
104
105 private void prepareMetaWritables(ImmutableStack<Object> indices, DirectoryOnDisk target) {
106 this.metaWritables.forEach(metaWritableFunction -> {
107 Writable<WritableOnDisk> newWritable = metaWritableFunction.apply(indices);
108 target.addWritable(newWritable);
109 newWritable.prepare(indices);
110 });
111 }
112 }
113
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/directory/IndexDirectoryOnDisk.java]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/util/ImmutableStack.java]
1 /*
2 * Corona-Warn-App
3 *
4 * SAP SE and all other contributors /
5 * copyright owners license this file to you under the Apache
6 * License, Version 2.0 (the "License"); you may not use this
7 * file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20 package app.coronawarn.server.services.distribution.assembly.structure.util;
21
22 import java.util.Stack;
23
24 public class ImmutableStack<T> {
25
26 private final Stack<T> stack;
27
28 public ImmutableStack() {
29 this.stack = new Stack<>();
30 }
31
32 /**
33 * Creates a clone of the specified {@link ImmutableStack}.
34 */
35 public ImmutableStack(ImmutableStack<T> other) {
36 this.stack = (Stack<T>) other.stack.clone();
37 }
38
39 /**
40 * Returns a clone of this stack that contains the specified item at its top position.
41 */
42 public ImmutableStack<T> push(T item) {
43 ImmutableStack<T> clone = new ImmutableStack<>(this);
44 clone.stack.push(item);
45 return clone;
46 }
47
48 /**
49 * Returns a clone of this stack with its top element removed.
50 */
51 public ImmutableStack<T> pop() {
52 ImmutableStack<T> clone = new ImmutableStack<>(this);
53 clone.stack.pop();
54 return clone;
55 }
56
57 public T peek() {
58 return this.stack.peek();
59 }
60 }
61
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/util/ImmutableStack.java]
</code>
Here is an example of a patch file. It consists of changes to the code base. It specifies the file names, the line numbers of each change, and the removed and added lines. A single patch file can contain changes to multiple files.
<patch>
--- a/file.py
+++ b/file.py
@@ -1,27 +1,35 @@
def euclidean(a, b):
- while b:
- a, b = b, a % b
- return a
+ if b == 0:
+ return a
+ return euclidean(b, a % b)
def bresenham(x0, y0, x1, y1):
points = []
dx = abs(x1 - x0)
dy = abs(y1 - y0)
- sx = 1 if x0 < x1 else -1
- sy = 1 if y0 < y1 else -1
- err = dx - dy
+ x, y = x0, y0
+ sx = -1 if x0 > x1 else 1
+ sy = -1 if y0 > y1 else 1
- while True:
- points.append((x0, y0))
- if x0 == x1 and y0 == y1:
- break
- e2 = 2 * err
- if e2 > -dy:
+ if dx > dy:
+ err = dx / 2.0
+ while x != x1:
+ points.append((x, y))
err -= dy
- x0 += sx
- if e2 < dx:
- err += dx
- y0 += sy
+ if err < 0:
+ y += sy
+ err += dx
+ x += sx
+ else:
+ err = dy / 2.0
+ while y != y1:
+ points.append((x, y))
+ err -= dx
+ if err < 0:
+ x += sx
+ err += dy
+ y += sy
+ points.append((x, y))
return points
</patch>
I need you to solve the provded issue by generating a single patch file that I can apply directly to this repository using git apply. Please respond with a single patch file in the format shown above.
Respond below:
| corona-warn-app/cwa-server | 207bdd8d4d701ab8df608db7caa9f2613fa86b84 | Sonar - Mitigate/Audit synchronized class "Stack"
See https://sonarcloud.io/project/issues?id=corona-warn-app_cwa-server&issues=AXI3CJu7vPFV4POpyUFA&open=AXI3CJu7vPFV4POpyUFA
Strongly consider using existing [data structure implementations.](https://www.eclipse.org/collections/javadoc/9.2.0/org/eclipse/collections/api/stack/ImmutableStack.html)
| 2020-05-27T23:46:21 | <patch>
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/directory/IndexDirectory.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/directory/IndexDirectory.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/directory/IndexDirectory.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/directory/IndexDirectory.java
@@ -24,7 +24,6 @@
import app.coronawarn.server.services.distribution.assembly.structure.util.functional.Formatter;
import app.coronawarn.server.services.distribution.assembly.structure.util.functional.WritableFunction;
import java.util.Set;
-import java.util.Stack;
/**
* A "meta {@link Directory directory}" that maps its on-disk subdirectories to some list of elements. This list of
@@ -38,7 +37,7 @@ public interface IndexDirectory<T, W extends Writable<W>> extends Directory<W> {
/**
* Adds a writable under the name {@code name}, whose content is calculated by the {@code writableFunction} to each
* one of the directories created from the index. The {@code fileFunction} calculates the file content from a {@link
- * java.util.Stack} of parent {@link IndexDirectoryOnDisk} indices. File content calculation happens on {@link
+ * ImmutableStack} of parent {@link IndexDirectoryOnDisk} indices. File content calculation happens on {@link
* DirectoryOnDisk#write}.
*
* @param writableFunction A function that can output a new writable.
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/directory/IndexDirectoryOnDisk.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/directory/IndexDirectoryOnDisk.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/directory/IndexDirectoryOnDisk.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/directory/IndexDirectoryOnDisk.java
@@ -27,7 +27,6 @@
import app.coronawarn.server.services.distribution.assembly.structure.util.functional.WritableFunction;
import java.util.HashSet;
import java.util.Set;
-import java.util.Stack;
/**
* An {@link IndexDirectory} that can be written to disk.
@@ -47,7 +46,7 @@ public class IndexDirectoryOnDisk<T> extends DirectoryOnDisk implements IndexDir
*
* @param name The name that this directory should have on disk.
* @param indexFunction An {@link IndexFunction} that calculates the index of this {@link IndexDirectoryOnDisk} from
- * a {@link java.util.Stack} of parent {@link IndexDirectoryOnDisk} indices. The top element of
+ * a {@link ImmutableStack} of parent {@link IndexDirectoryOnDisk} indices. The top element of
* the stack is from the closest {@link IndexDirectoryOnDisk} in the parent chain.
* @param indexFormatter A {@link Formatter} used to format the directory name for each index element returned by the
* {@link IndexDirectoryOnDisk#indexFunction}.
@@ -78,9 +77,9 @@ public void addWritableToAll(WritableFunction<WritableOnDisk> writableFunction)
* {@link IndexDirectory#addWritableToAll writables} to those. The respective element of the index will be pushed
* onto the Stack for subsequent {@link Writable#prepare} calls.
*
- * @param indices A {@link Stack} of parameters from all {@link IndexDirectory IndexDirectories} further up in the
- * hierarchy. The Stack may contain different types, depending on the types {@code T} of
- * {@link IndexDirectory IndexDirectories} further up in the hierarchy.
+ * @param indices A {@link ImmutableStack} of parameters from all {@link IndexDirectory IndexDirectories} further up
+ * in the hierarchy. The Stack may contain different types, depending on the types {@code T} of {@link
+ * IndexDirectory IndexDirectories} further up in the hierarchy.
*/
@Override
public void prepare(ImmutableStack<Object> indices) {
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/util/ImmutableStack.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/util/ImmutableStack.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/util/ImmutableStack.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/structure/util/ImmutableStack.java
@@ -19,21 +19,22 @@
package app.coronawarn.server.services.distribution.assembly.structure.util;
-import java.util.Stack;
+import java.util.ArrayDeque;
+import java.util.Deque;
public class ImmutableStack<T> {
- private final Stack<T> stack;
+ private final Deque<T> stack;
public ImmutableStack() {
- this.stack = new Stack<>();
+ this.stack = new ArrayDeque<>();
}
/**
* Creates a clone of the specified {@link ImmutableStack}.
*/
public ImmutableStack(ImmutableStack<T> other) {
- this.stack = (Stack<T>) other.stack.clone();
+ this.stack = new ArrayDeque<>(other.stack);
}
/**
</patch> | diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/structure/util/ImmutableStackTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/structure/util/ImmutableStackTest.java
new file mode 100644
--- /dev/null
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/structure/util/ImmutableStackTest.java
@@ -0,0 +1,69 @@
+/*
+ * Corona-Warn-App
+ *
+ * SAP SE and all other contributors /
+ * copyright owners license this file to you under the Apache
+ * License, Version 2.0 (the "License"); you may not use this
+ * file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://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 for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package app.coronawarn.server.services.distribution.assembly.structure.util;
+
+import org.assertj.core.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+import java.util.ArrayDeque;
+import java.util.NoSuchElementException;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
+
+class ImmutableStackTest {
+
+ private final ImmutableStack<String> stack =
+ new ImmutableStack<String>().push("Joker").push("Queen").push("King");
+
+ @Test
+ void checkPushes() {
+ var newStack = stack.push("Ace");
+
+ assertThat(newStack).isNotSameAs(stack);
+ assertThat(newStack.peek()).isEqualTo("Ace");
+ assertThat(stack.peek()).isEqualTo("King");
+ }
+
+ @Test
+ void checkPops() {
+ var newStack = stack.pop();
+
+ assertThat(newStack).isNotSameAs(stack);
+ assertThat(newStack.peek()).isEqualTo("Queen");
+ assertThat(stack.peek()).isEqualTo("King");
+ }
+
+ @Test
+ void checkPeeks() {
+ assertThat(stack.peek()).isEqualTo("King");
+ }
+
+ @Test
+ void checksEmptyStackHasNoting() {
+ assertThat(new ImmutableStack<>().peek()).isNull();
+ }
+
+ @Test
+ void throwsExceptionWhenPopsFromEmptyStack() {
+ assertThatExceptionOfType(NoSuchElementException.class)
+ .isThrownBy(() -> new ImmutableStack<>().pop());
+ }
+}
| |||||
corona-warn-app__cwa-server-299 | You will be provided with a partial code base and an issue statement explaining a problem to resolve.
<issue>
RKI: Adjust Risk Score Parameters in master config
RKI decided for the following risk score parameter values:
```
1 2 3 4 5 6 7 8 // Bucket No.
----------------------------------------------------------
0 1 2 4 5 7 8 8 // Duration
0 0 1 2 5 7 8 8 // Attenuation
1 1 1 1 2 6 8 6 // Days
1 2 3 4 5 6 7 8 // Transmission Risk
```
</issue>
<code>
[start of README.md]
1 <h1 align="center">
2 Corona-Warn-App Server
3 </h1>
4
5 <p align="center">
6 <a href="https://github.com/corona-warn-app/cwa-server/commits/" title="Last Commit"><img src="https://img.shields.io/github/last-commit/corona-warn-app/cwa-server?style=flat"></a>
7 <a href="https://github.com/corona-warn-app/cwa-server/issues" title="Open Issues"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat"></a>
8 <a href="https://circleci.com/gh/corona-warn-app/cwa-server" title="Build Status"><img src="https://circleci.com/gh/corona-warn-app/cwa-server.svg?style=shield&circle-token=4ab059989d10709df19eb4b98ab7c121a25e981a"></a>
9 <a href="https://sonarcloud.io/dashboard?id=corona-warn-app_cwa-server" title="Quality Gate"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=alert_status"></a>
10 <a href="https://sonarcloud.io/component_measures?id=corona-warn-app_cwa-server&metric=Coverage&view=list" title="Coverage"><img src="https://sonarcloud.io/api/project_badges/measure?project=corona-warn-app_cwa-server&metric=coverage"></a>
11 <a href="https://github.com/corona-warn-app/cwa-server/blob/master/LICENSE" title="License"><img src="https://img.shields.io/badge/License-Apache%202.0-green.svg?style=flat"></a>
12 </p>
13
14 <p align="center">
15 <a href="#development">Development</a> •
16 <a href="#service-apis">Service APIs</a> •
17 <a href="#documentation">Documentation</a> •
18 <a href="#support-and-feedback">Support</a> •
19 <a href="#how-to-contribute">Contribute</a> •
20 <a href="#contributors">Contributors</a> •
21 <a href="#repositories">Repositories</a> •
22 <a href="#licensing">Licensing</a>
23 </p>
24
25 The goal of this project is to develop the official Corona-Warn-App for Germany based on the exposure notification API from [Apple](https://www.apple.com/covid19/contacttracing/) and [Google](https://www.google.com/covid19/exposurenotifications/). The apps (for both iOS and Android) use Bluetooth technology to exchange anonymous encrypted data with other mobile phones (on which the app is also installed) in the vicinity of an app user's phone. The data is stored locally on each user's device, preventing authorities or other parties from accessing or controlling the data. This repository contains the **implementation of the server for encryption keys** for the Corona-Warn-App. This implementation is still a **work in progress**, and the code it contains is currently alpha-quality code.
26
27 In this documentation, Corona-Warn-App services are also referred to as CWA services.
28
29 ## Architecture Overview
30
31 You can find the architecture overview [here](/docs/architecture-overview.md), which will give you
32 a good starting point in how the backend services interact with other services, and what purpose
33 they serve.
34
35 ## Development
36
37 After you've checked out this repository, you can run the application in one of the following ways:
38
39 * As a [Docker](https://www.docker.com/)-based deployment on your local machine. You can run either:
40 * Single components using the respective Dockerfile or
41 * The full backend using the Docker Compose (which is considered the most convenient way)
42 * As a [Maven](https://maven.apache.org)-based build on your local machine.
43 If you want to develop something in a single component, this approach is preferable.
44
45 ### Docker-Based Deployment
46
47 If you want to use Docker-based deployment, you need to install Docker on your local machine. For more information about downloading and installing Docker, see the [official Docker documentation](https://docs.docker.com/get-docker/).
48
49 #### Running the Full CWA Backend Using Docker Compose
50
51 For your convenience, a full setup including the generation of test data has been prepared using [Docker Compose](https://docs.docker.com/compose/reference/overview/). To build the backend services, run ```docker-compose build``` in the repository's root directory. A default configuration file can be found under ```.env```in the root folder of the repository. The default values for the local Postgres and Zenko Cloudserver should be changed in this file before docker-compose is run.
52
53 Once the services are built, you can start the whole backend using ```docker-compose up```.
54 The distribution service runs once and then finishes. If you want to trigger additional distribution runs, run ```docker-compose run distribution```.
55
56 The docker-compose contains the following services:
57
58 Service | Description | Endpoint and Default Credentials
59 ------------------|-------------|-----------
60 submission | The Corona-Warn-App submission service | http://localhost:8000 <br> http://localhost:8005 (for actuator endpoint)
61 distribution | The Corona-Warn-App distribution service | NO ENDPOINT
62 postgres | A [postgres] database installation | postgres:8001 <br> Username: postgres <br> Password: postgres
63 pgadmin | A [pgadmin](https://www.pgadmin.org/) installation for the postgres database | http://localhost:8002 <br> Username: [email protected] <br> Password: password
64 cloudserver | [Zenko CloudServer] is a S3-compliant object store | http://localhost:8003/ <br> Access key: accessKey1 <br> Secret key: verySecretKey1
65 verification-fake | A very simple fake implementation for the tan verification. | http://localhost:8004/version/v1/tan/verify <br> The only valid tan is "b69ab69f-9823-4549-8961-c41sa74b2f36"
66
67 ##### Known Limitation
68
69 In rare cases the docker-compose runs into a timing issue if the distribution service starts before the bucket of the objectstore was created. This is not a big issue as you can simply run ```docker-compose run distribution``` to trigger additional distribution runs after the objectstore was initialized.
70
71 #### Running Single CWA Services Using Docker
72
73 If you would like to build and run a single CWA service, it's considered easiest to run them in a Docker environment. You can do this using the script provided in the respective CWA service directory. The Docker script first builds the CWA service and then creates an image for the runtime, which means that there are no additional dependencies for you to install.
74
75 To build and run the distribution service, run the following command:
76
77 ```bash
78 ./services/distribution/build_and_run.sh
79 ```
80
81 To build and run the submission service, run the following command:
82
83 ```bash
84 ./services/submission/build_and_run.sh
85 ```
86
87 The submission service is available on [localhost:8080](http://localhost:8080 ).
88
89 ### Maven-Based Build
90
91 If you want to actively develop in one of the CWA services, the Maven-based runtime is most suitable.
92 To prepare your machine to run the CWA project locally, we recommend that you first ensure that you've installed the following:
93
94 * Minimum JDK Version 11: [OpenJDK](https://openjdk.java.net/) / [SapMachine](https://sap.github.io/SapMachine/)
95 * [Maven 3.6](https://maven.apache.org/)
96 * [Postgres]
97 * [Zenko CloudServer]
98
99 #### Configure
100
101 After you made sure that the specified dependencies are running, configure them in the respective configuration files.
102
103 * Configure the Postgres connection in the [submission config](./services/submission/src/main/resources/application.yaml) and in the [distribution config](./services/distribution/src/main/resources/application.yaml)
104 * Configure the S3 compatible object storage in the [distribution config](./services/distribution/src/main/resources/application.yaml)
105 * Configure the certificate and private key for the distribution service, the paths need to be prefixed with `file:`
106 * `VAULT_FILESIGNING_SECRET` should be the path to the private key, example available in `<repo-root>/docker-compose-test-secrets/private.pem`
107 * `VAULT_FILESIGNING_CERT` should be the path to the certificate, example available in `<repo-root>/docker-compose-test-secrets/certificate.cert`
108
109 #### Build
110
111 After you've checked out the repository, to build the project, run ```mvn install``` in your base directory.
112
113 #### Run
114
115 Navigate to the service you want to start and run the spring-boot:run target. The configured Postgres and the configured S3 compliant object storage are used as default. When you start the submission service, the endpoint is available on your local port 8080.
116
117 If you want to start the submission service, for example, you start it as follows:
118
119 ```bash
120 cd services/submission/
121 mvn spring-boot:run
122 ```
123
124 #### Debugging
125
126 To enable the `DEBUG` log level, you can run the application using the Spring `dev` profile.
127
128 ```bash
129 mvn spring-boot:run -Dspring-boot.run.profiles=dev
130 ```
131
132 To be able to set breakpoints (e.g. in IntelliJ), it may be necessary to use the ```-Dspring-boot.run.fork=false``` parameter.
133
134 ## Service APIs
135
136 The API that is being exposed by the backend services is documented in an [OpenAPI](https://www.openapis.org/) specification. The specification files are available at the following locations:
137
138 Service | OpenAPI Specification
139 -------------|-------------
140 Submission Service | https://github.com/corona-warn-app/cwa-server/raw/master/services/submission/api_v1.json
141 Distribution Service | https://github.com/corona-warn-app/cwa-server/raw/master/services/distribution/api_v1.json
142
143 ## Spring Profiles
144
145 #### Distribution
146
147 Profile | Effect
148 -------------|-------------
149 `dev` | Turns the log level to `DEBUG`.
150 `cloud` | Removes default values for the `datasource` and `objectstore` configurations.
151 `demo` | Includes incomplete days and hours into the distribution run, thus creating aggregates for the current day and the current hour (and including both in the respective indices). When running multiple distributions in one hour with this profile, the date aggregate for today and the hours aggregate for the current hour will be updated and overwritten.
152 `testdata` | Causes test data to be inserted into the database before each distribution run. By default, around 1000 random diagnosis keys will be generated per hour. If there are no diagnosis keys in the database yet, random keys will be generated for every hour from the beginning of the retention period (14 days ago at 00:00 UTC) until one hour before the present hour. If there are already keys in the database, the random keys will be generated for every hour from the latest diagnosis key in the database (by submission timestamp) until one hour before the present hour (or none at all, if the latest diagnosis key in the database was submitted one hour ago or later).
153
154 #### Submission
155
156 Profile | Effect
157 -------------|-------------
158 `dev` | Turns the log level to `DEBUG`.
159 `cloud` | Removes default values for the `datasource` configuration.
160
161 ## Documentation
162
163 The full documentation for the Corona-Warn-App can be found in the [cwa-documentation](https://github.com/corona-warn-app/cwa-documentation) repository. The documentation repository contains technical documents, architecture information, and whitepapers related to this implementation.
164
165 ## Support and Feedback
166
167 The following channels are available for discussions, feedback, and support requests:
168
169 | Type | Channel |
170 | ------------------------ | ------------------------------------------------------ |
171 | **General Discussion** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="General Discussion"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/question.svg?style=flat-square"></a> </a> |
172 | **Concept Feedback** | <a href="https://github.com/corona-warn-app/cwa-documentation/issues/new/choose" title="Open Concept Feedback"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-documentation/architecture.svg?style=flat-square"></a> |
173 | **Backend Issue** | <a href="https://github.com/corona-warn-app/cwa-server/issues/new/choose" title="Open Backend Issue"><img src="https://img.shields.io/github/issues/corona-warn-app/cwa-server?style=flat-square"></a> |
174 | **Other Requests** | <a href="mailto:[email protected]" title="Email CWA Team"><img src="https://img.shields.io/badge/email-CWA%20team-green?logo=mail.ru&style=flat-square&logoColor=white"></a> |
175
176 ## How to Contribute
177
178 Contribution and feedback are 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.
179
180 ## Contributors
181
182 The German government has asked SAP and Deutsche Telekom to develop the Corona-Warn-App for Germany as open source software. Deutsche Telekom is providing the network and mobile technology and will operate and run the backend for the app in a safe, scalable and stable manner. SAP is responsible for the app development, its framework and the underlying platform. Therefore, development teams of SAP and Deutsche Telekom are contributing to this project. At the same time 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.
183
184 ## Repositories
185
186 The following public repositories are currently available for the Corona-Warn-App:
187
188 | Repository | Description |
189 | ------------------- | --------------------------------------------------------------------- |
190 | [cwa-documentation] | Project overview, general documentation, and white papers |
191 | [cwa-server] | Backend implementation for the Apple/Google exposure notification API|
192 | [cwa-verification-server] | Backend implementation of the verification process|
193
194 [cwa-documentation]: https://github.com/corona-warn-app/cwa-documentation
195 [cwa-server]: https://github.com/corona-warn-app/cwa-server
196 [cwa-verification-server]: https://github.com/corona-warn-app/cwa-verification-server
197 [Postgres]: https://www.postgresql.org/
198 [HSQLDB]: http://hsqldb.org/
199 [Zenko CloudServer]: https://github.com/scality/cloudserver
200
201 ## Licensing
202
203 Copyright (c) 2020 SAP SE or an SAP affiliate company.
204
205 Licensed under the **Apache License, Version 2.0** (the "License"); you may not use this file except in compliance with the License.
206
207 You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0.
208
209 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.
210
[end of README.md]
[start of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ExposureConfigurationValidator.java]
1 /*
2 * Corona-Warn-App
3 *
4 * SAP SE and all other contributors /
5 * copyright owners license this file to you under the Apache
6 * License, Version 2.0 (the "License"); you may not use this
7 * file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20 package app.coronawarn.server.services.distribution.assembly.appconfig.validation;
21
22 import app.coronawarn.server.common.protocols.internal.RiskLevel;
23 import app.coronawarn.server.common.protocols.internal.RiskScoreParameters;
24 import app.coronawarn.server.services.distribution.assembly.appconfig.validation.WeightValidationError.ErrorType;
25 import java.beans.BeanInfo;
26 import java.beans.IntrospectionException;
27 import java.beans.Introspector;
28 import java.beans.PropertyDescriptor;
29 import java.lang.reflect.InvocationTargetException;
30 import java.math.BigDecimal;
31 import java.util.Arrays;
32
33 /**
34 * The Exposure Configuration Validator checks the values of a given RiskScoreParameters instance. Validation is
35 * performed according to the Apple/Google spec.<br>
36 * <br>
37 * Weights must be in the range of 0.001 to 100.<br> Scores must be in the range of 1 to 8.<br>
38 */
39 public class ExposureConfigurationValidator extends ConfigurationValidator {
40
41 private final RiskScoreParameters config;
42
43 public ExposureConfigurationValidator(RiskScoreParameters config) {
44 this.config = config;
45 }
46
47 /**
48 * Triggers the validation of the configuration.
49 *
50 * @return the ValidationResult instance, containing information about possible errors.
51 * @throws ValidationExecutionException in case the validation could not be performed
52 */
53 @Override
54 public ValidationResult validate() {
55 this.errors = new ValidationResult();
56
57 validateWeights();
58
59 try {
60 validateParameterRiskLevels("duration", config.getDuration());
61 validateParameterRiskLevels("transmission", config.getTransmission());
62 validateParameterRiskLevels("daysSinceLastExposure", config.getDaysSinceLastExposure());
63 validateParameterRiskLevels("attenuation", config.getAttenuation());
64 } catch (IntrospectionException e) {
65 throw new ValidationExecutionException("Unable to check risk levels", e);
66 }
67
68 return errors;
69 }
70
71 private void validateParameterRiskLevels(String name, Object object)
72 throws IntrospectionException {
73 BeanInfo bean = Introspector.getBeanInfo(object.getClass());
74
75 Arrays.stream(bean.getPropertyDescriptors())
76 .filter(propertyDescriptor -> propertyDescriptor.getPropertyType() == RiskLevel.class)
77 .forEach(propertyDescriptor -> validateScore(propertyDescriptor, object, name));
78 }
79
80 private void validateScore(
81 PropertyDescriptor propertyDescriptor, Object object, String parameter) {
82 try {
83 RiskLevel level = (RiskLevel) propertyDescriptor.getReadMethod().invoke(object);
84
85 if (level == RiskLevel.UNRECOGNIZED || level == RiskLevel.RISK_LEVEL_UNSPECIFIED) {
86 this.errors.add(new RiskLevelValidationError(parameter, propertyDescriptor.getName()));
87 }
88 } catch (IllegalAccessException | InvocationTargetException e) {
89 throw new ValidationExecutionException(
90 "Unable to read property " + propertyDescriptor.getName(), e);
91 }
92 }
93
94 private void validateWeights() {
95 validateWeight(config.getTransmissionWeight(), "transmission");
96 validateWeight(config.getDurationWeight(), "duration");
97 validateWeight(config.getAttenuationWeight(), "attenuation");
98 }
99
100 private void validateWeight(double weight, String name) {
101 if (isOutOfRange(ParameterSpec.WEIGHT_MIN, ParameterSpec.WEIGHT_MAX, weight)) {
102 this.errors.add(new WeightValidationError(name, weight, ErrorType.OUT_OF_RANGE));
103 }
104
105 if (!respectsMaximumDecimalPlaces(weight)) {
106 this.errors.add(new WeightValidationError(name, weight, ErrorType.TOO_MANY_DECIMAL_PLACES));
107 }
108 }
109
110 private boolean respectsMaximumDecimalPlaces(double weight) {
111 BigDecimal bd = new BigDecimal(String.valueOf(weight));
112
113 return bd.scale() <= ParameterSpec.WEIGHT_MAX_DECIMALS;
114 }
115
116
117 private boolean isOutOfRange(double min, double max, double x) {
118 return x < min || x > max;
119 }
120 }
121
[end of services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ExposureConfigurationValidator.java]
[start of services/distribution/src/main/resources/master-config/exposure-config.yaml]
1 # This is the Exposure Config master file which defines the risk parameters for the mobile clients
2 # Change this file with caution.
3 #
4 # Weights must be in range of 0.001 to 100
5 # Parameter Scores must be in range of 1 to 8.
6 #
7 # Further documentation:
8 # https://developer.apple.com/documentation/exposurenotification/enexposureconfiguration
9 #
10
11 # Weight Section
12
13 transmission_weight: 50
14 duration_weight: 50
15 attenuation_weight: 50
16 days_weight: 20
17
18 # Parameters Section
19
20 transmission:
21 app_defined_1: 1
22 app_defined_2: 2
23 app_defined_3: 3
24 app_defined_4: 4
25 app_defined_5: 5
26 app_defined_6: 6
27 app_defined_7: 7
28 app_defined_8: 8
29
30 duration:
31 eq_0_min: 1
32 gt_0_le_5_min: 2
33 gt_5_le_10_min: 3
34 gt_10_le_15_min: 4
35 gt_15_le_20_min: 5
36 gt_20_le_25_min: 6
37 gt_25_le_30_min: 7
38 gt_30_min: 8
39
40 days_since_last_exposure:
41 ge_14_days: 1
42 ge_12_lt_14_days: 2
43 ge_10_lt_12_days: 3
44 ge_8_lt_10_days: 4
45 ge_6_lt_8_days: 5
46 ge_4_lt_6_days: 6
47 ge_2_lt_4_days: 7
48 ge_0_lt_2_days: 8
49
50 attenuation:
51 gt_73_dbm: 1
52 gt_63_le_73_dbm: 2
53 gt_51_le_63_dbm: 3
54 gt_33_le_51_dbm: 4
55 gt_27_le_33_dbm: 5
56 gt_15_le_27_dbm: 6
57 gt_10_le_15_dbm: 7
58 lt_10_dbm: 8
[end of services/distribution/src/main/resources/master-config/exposure-config.yaml]
</code>
Here is an example of a patch file. It consists of changes to the code base. It specifies the file names, the line numbers of each change, and the removed and added lines. A single patch file can contain changes to multiple files.
<patch>
--- a/file.py
+++ b/file.py
@@ -1,27 +1,35 @@
def euclidean(a, b):
- while b:
- a, b = b, a % b
- return a
+ if b == 0:
+ return a
+ return euclidean(b, a % b)
def bresenham(x0, y0, x1, y1):
points = []
dx = abs(x1 - x0)
dy = abs(y1 - y0)
- sx = 1 if x0 < x1 else -1
- sy = 1 if y0 < y1 else -1
- err = dx - dy
+ x, y = x0, y0
+ sx = -1 if x0 > x1 else 1
+ sy = -1 if y0 > y1 else 1
- while True:
- points.append((x0, y0))
- if x0 == x1 and y0 == y1:
- break
- e2 = 2 * err
- if e2 > -dy:
+ if dx > dy:
+ err = dx / 2.0
+ while x != x1:
+ points.append((x, y))
err -= dy
- x0 += sx
- if e2 < dx:
- err += dx
- y0 += sy
+ if err < 0:
+ y += sy
+ err += dx
+ x += sx
+ else:
+ err = dy / 2.0
+ while y != y1:
+ points.append((x, y))
+ err -= dx
+ if err < 0:
+ x += sx
+ err += dy
+ y += sy
+ points.append((x, y))
return points
</patch>
I need you to solve the provded issue by generating a single patch file that I can apply directly to this repository using git apply. Please respond with a single patch file in the format shown above.
Respond below:
| corona-warn-app/cwa-server | c5991b2fcb894aa4a8eec41c51a2f2cc366a13b5 | RKI: Adjust Risk Score Parameters in master config
RKI decided for the following risk score parameter values:
```
1 2 3 4 5 6 7 8 // Bucket No.
----------------------------------------------------------
0 1 2 4 5 7 8 8 // Duration
0 0 1 2 5 7 8 8 // Attenuation
1 1 1 1 2 6 8 6 // Days
1 2 3 4 5 6 7 8 // Transmission Risk
```
| Config file that needs updating: [master.yaml](https://github.com/corona-warn-app/cwa-server/blob/master/services/distribution/src/main/resources/exposure-config/master.yaml) | 2020-05-25T09:41:14 | <patch>
diff --git a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ExposureConfigurationValidator.java b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ExposureConfigurationValidator.java
--- a/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ExposureConfigurationValidator.java
+++ b/services/distribution/src/main/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ExposureConfigurationValidator.java
@@ -82,7 +82,7 @@ private void validateScore(
try {
RiskLevel level = (RiskLevel) propertyDescriptor.getReadMethod().invoke(object);
- if (level == RiskLevel.UNRECOGNIZED || level == RiskLevel.RISK_LEVEL_UNSPECIFIED) {
+ if (level == RiskLevel.UNRECOGNIZED) {
this.errors.add(new RiskLevelValidationError(parameter, propertyDescriptor.getName()));
}
} catch (IllegalAccessException | InvocationTargetException e) {
diff --git a/services/distribution/src/main/resources/master-config/exposure-config.yaml b/services/distribution/src/main/resources/master-config/exposure-config.yaml
--- a/services/distribution/src/main/resources/master-config/exposure-config.yaml
+++ b/services/distribution/src/main/resources/master-config/exposure-config.yaml
@@ -2,7 +2,7 @@
# Change this file with caution.
#
# Weights must be in range of 0.001 to 100
-# Parameter Scores must be in range of 1 to 8.
+# Parameter Scores must be in range of 0 to 8.
#
# Further documentation:
# https://developer.apple.com/documentation/exposurenotification/enexposureconfiguration
@@ -28,31 +28,31 @@ transmission:
app_defined_8: 8
duration:
- eq_0_min: 1
- gt_0_le_5_min: 2
- gt_5_le_10_min: 3
+ eq_0_min: 0
+ gt_0_le_5_min: 1
+ gt_5_le_10_min: 2
gt_10_le_15_min: 4
gt_15_le_20_min: 5
- gt_20_le_25_min: 6
- gt_25_le_30_min: 7
+ gt_20_le_25_min: 7
+ gt_25_le_30_min: 8
gt_30_min: 8
days_since_last_exposure:
ge_14_days: 1
- ge_12_lt_14_days: 2
- ge_10_lt_12_days: 3
- ge_8_lt_10_days: 4
- ge_6_lt_8_days: 5
+ ge_12_lt_14_days: 1
+ ge_10_lt_12_days: 1
+ ge_8_lt_10_days: 1
+ ge_6_lt_8_days: 2
ge_4_lt_6_days: 6
- ge_2_lt_4_days: 7
- ge_0_lt_2_days: 8
+ ge_2_lt_4_days: 8
+ ge_0_lt_2_days: 6
attenuation:
- gt_73_dbm: 1
- gt_63_le_73_dbm: 2
- gt_51_le_63_dbm: 3
- gt_33_le_51_dbm: 4
+ gt_73_dbm: 0
+ gt_63_le_73_dbm: 0
+ gt_51_le_63_dbm: 1
+ gt_33_le_51_dbm: 2
gt_27_le_33_dbm: 5
- gt_15_le_27_dbm: 6
- gt_10_le_15_dbm: 7
- lt_10_dbm: 8
\ No newline at end of file
+ gt_15_le_27_dbm: 7
+ gt_10_le_15_dbm: 8
+ lt_10_dbm: 8
</patch> | diff --git a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ExposureConfigurationValidatorTest.java b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ExposureConfigurationValidatorTest.java
--- a/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ExposureConfigurationValidatorTest.java
+++ b/services/distribution/src/test/java/app/coronawarn/server/services/distribution/assembly/appconfig/validation/ExposureConfigurationValidatorTest.java
@@ -72,7 +72,8 @@ private static Stream<Arguments> createOkTests() {
private static Stream<Arguments> createFailedTests() {
return Stream.of(
ScoreTooHigh(),
- ScoreNegative(),
+ // TODO cwa-server/#320 Validate that no attributes are missing in .yaml
+ // ScoreNegative(),
WeightNegative(),
WeightTooHigh()
).map(Arguments::of);
@@ -107,9 +108,8 @@ public static TestWithExpectedResult WeightTooHigh() {
public static TestWithExpectedResult ScoreNegative() {
return new TestWithExpectedResult("score_negative.yaml")
- .with(new RiskLevelValidationError("transmission", "appDefined1"))
- .with(new RiskLevelValidationError("transmission", "appDefined2"))
- .with(new RiskLevelValidationError("transmission", "appDefined3"));
+ .with(new RiskLevelValidationError("transmission", "appDefined1"))
+ .with(new RiskLevelValidationError("transmission", "appDefined3"));
}
public static TestWithExpectedResult ScoreTooHigh() {
diff --git a/services/distribution/src/test/resources/parameters/score_negative.yaml b/services/distribution/src/test/resources/parameters/score_negative.yaml
--- a/services/distribution/src/test/resources/parameters/score_negative.yaml
+++ b/services/distribution/src/test/resources/parameters/score_negative.yaml
@@ -5,7 +5,7 @@ attenuation_weight: 80
transmission:
app_defined_1: -2 # not ok, negative
- app_defined_2: 0 # not ok, unspecified
+ app_defined_2: 0
#app_defined_3: 3 # not ok (missing -> unspecified)
app_defined_4: 5
app_defined_5: 5
|