mithril_aggregator/http_server/routes/
router.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
use crate::http_server::routes::{
    artifact_routes, certificate_routes, epoch_routes, http_server_child_logger, root_routes,
    signatures_routes, signer_routes, statistics_routes, status,
};
use crate::http_server::SERVER_BASE_PATH;
use crate::DependencyContainer;

use mithril_common::api_version::APIVersionProvider;
use mithril_common::entities::{CardanoTransactionsSigningConfig, SignedEntityTypeDiscriminants};
use mithril_common::{CardanoNetwork, MITHRIL_API_VERSION_HEADER};

use slog::{warn, Logger};
use std::collections::BTreeSet;
use std::path::PathBuf;
use std::sync::Arc;
use warp::http::Method;
use warp::http::StatusCode;
use warp::reject::Reject;
use warp::{Filter, Rejection, Reply};

use super::{middlewares, proof_routes};

#[derive(Debug)]
pub struct VersionMismatchError;

impl Reject for VersionMismatchError {}

#[derive(Debug)]
pub struct VersionParseError;

impl Reject for VersionParseError {}

/// HTTP Server configuration
pub struct RouterConfig {
    pub network: CardanoNetwork,
    pub server_url: String,
    pub allowed_discriminants: BTreeSet<SignedEntityTypeDiscriminants>,
    pub cardano_transactions_prover_max_hashes_allowed_by_request: usize,
    pub cardano_transactions_signing_config: CardanoTransactionsSigningConfig,
    pub snapshot_directory: PathBuf,
    pub cardano_node_version: String,
    pub allow_http_serve_directory: bool,
}

#[cfg(test)]
impl RouterConfig {
    pub fn dummy() -> Self {
        Self {
            network: CardanoNetwork::DevNet(87),
            server_url: "http://0.0.0.0:8000/".to_string(),
            allowed_discriminants: BTreeSet::from([
                SignedEntityTypeDiscriminants::MithrilStakeDistribution,
                SignedEntityTypeDiscriminants::CardanoStakeDistribution,
            ]),
            cardano_transactions_prover_max_hashes_allowed_by_request: 1_000,
            cardano_transactions_signing_config: CardanoTransactionsSigningConfig::dummy(),
            snapshot_directory: PathBuf::from("/dummy/snapshot/directory"),
            cardano_node_version: "1.2.3".to_string(),
            allow_http_serve_directory: false,
        }
    }
}

/// Shared state for the router
pub struct RouterState {
    pub dependencies: Arc<DependencyContainer>,
    pub configuration: RouterConfig,
}

impl RouterState {
    /// `RouterState` factory
    pub fn new(dependencies: Arc<DependencyContainer>, configuration: RouterConfig) -> Self {
        Self {
            dependencies,
            configuration,
        }
    }
}

#[cfg(test)]
impl RouterState {
    pub fn new_with_dummy_config(dependencies: Arc<DependencyContainer>) -> Self {
        Self {
            dependencies,
            configuration: RouterConfig::dummy(),
        }
    }
}

/// Routes
pub fn routes(
    state: Arc<RouterState>,
) -> impl Filter<Extract = (impl Reply,), Error = Rejection> + Clone {
    let cors = warp::cors()
        .allow_any_origin()
        .allow_headers(vec!["content-type", MITHRIL_API_VERSION_HEADER])
        .allow_methods(vec![Method::GET, Method::POST, Method::OPTIONS]);

    warp::any()
        .and(header_must_be(
            state.dependencies.api_version_provider.clone(),
            http_server_child_logger(&state.dependencies.root_logger),
        ))
        .and(warp::path(SERVER_BASE_PATH))
        .and(
            certificate_routes::routes(&state)
                .or(artifact_routes::snapshot::routes(&state))
                .or(artifact_routes::cardano_database::routes(&state))
                .or(artifact_routes::mithril_stake_distribution::routes(&state))
                .or(artifact_routes::cardano_stake_distribution::routes(&state))
                .or(artifact_routes::cardano_transaction::routes(&state))
                .or(proof_routes::routes(&state))
                .or(signer_routes::routes(&state))
                .or(signatures_routes::routes(&state))
                .or(epoch_routes::routes(&state))
                .or(statistics_routes::routes(&state))
                .or(root_routes::routes(&state))
                .or(status::routes(&state)),
        )
        .recover(handle_custom)
        .and(middlewares::with_api_version_provider(&state))
        .map(|reply, api_version_provider: Arc<APIVersionProvider>| {
            warp::reply::with_header(
                reply,
                MITHRIL_API_VERSION_HEADER,
                &api_version_provider
                    .compute_current_version()
                    .unwrap()
                    .to_string(),
            )
        })
        .with(cors)
        .with(middlewares::log_route_call(&state))
}

/// API Version verification
fn header_must_be(
    api_version_provider: Arc<APIVersionProvider>,
    logger: Logger,
) -> impl Filter<Extract = (), Error = Rejection> + Clone {
    warp::header::optional(MITHRIL_API_VERSION_HEADER)
        .and(warp::any().map(move || api_version_provider.clone()))
        .and(warp::any().map(move || logger.clone()))
        .and_then(
            move |maybe_header: Option<String>,
                  api_version_provider: Arc<APIVersionProvider>,
                  logger: Logger| async move {
                match maybe_header {
                    None => Ok(()),
                    Some(version) => match semver::Version::parse(&version) {
                        Ok(version)
                            if api_version_provider
                                .compute_current_version_requirement()
                                .unwrap()
                                .matches(&version)
                                .to_owned() =>
                        {
                            Ok(())
                        }
                        Ok(_version) => Err(warp::reject::custom(VersionMismatchError)),
                        Err(err) => {
                            warn!(logger, "api_version_check::parse_error"; "error" => ?err);
                            Err(warp::reject::custom(VersionParseError))
                        }
                    },
                }
            },
        )
        .untuple_one()
}

pub async fn handle_custom(reject: Rejection) -> Result<impl Reply, Rejection> {
    if reject.find::<VersionMismatchError>().is_some() {
        Ok(StatusCode::PRECONDITION_FAILED)
    } else if reject.is_not_found() {
        Ok(StatusCode::NOT_FOUND)
    } else {
        Err(reject)
    }
}

#[cfg(test)]
mod tests {
    use semver::Version;
    use std::collections::HashMap;

    use mithril_common::{
        entities::Epoch,
        era::{EraChecker, SupportedEra},
    };

    use crate::dependency_injection::DependenciesBuilder;
    use crate::test_tools::TestLogger;
    use crate::Configuration;

    use super::*;

    #[tokio::test]
    async fn test_no_version() {
        let era_checker = EraChecker::new(SupportedEra::dummy(), Epoch(1));
        let api_version_provider = Arc::new(APIVersionProvider::new(Arc::new(era_checker)));
        let filters = header_must_be(api_version_provider, TestLogger::stdout());
        warp::test::request()
            .path("/aggregator/whatever")
            .filter(&filters)
            .await
            .expect("request without a version in headers should not be rejected");
    }

    #[tokio::test]
    async fn test_parse_version_error() {
        let era_checker = EraChecker::new(SupportedEra::dummy(), Epoch(1));
        let api_version_provider = Arc::new(APIVersionProvider::new(Arc::new(era_checker)));
        let filters = header_must_be(api_version_provider, TestLogger::stdout());
        warp::test::request()
            .header(MITHRIL_API_VERSION_HEADER, "not_a_version")
            .path("/aggregator/whatever")
            .filter(&filters)
            .await
            .expect_err(
                r#"request with an unparsable version should be rejected with a version parse error"#,
            );
    }

    #[tokio::test]
    async fn test_bad_version() {
        let era_checker = EraChecker::new(SupportedEra::dummy(), Epoch(1));
        let mut version_provider = APIVersionProvider::new(Arc::new(era_checker));
        let mut open_api_versions = HashMap::new();
        open_api_versions.insert("openapi.yaml".to_string(), Version::new(1, 0, 0));
        version_provider.update_open_api_versions(open_api_versions);
        let api_version_provider = Arc::new(version_provider);
        let filters = header_must_be(api_version_provider, TestLogger::stdout());
        warp::test::request()
            .header(MITHRIL_API_VERSION_HEADER, "0.0.999")
            .path("/aggregator/whatever")
            .filter(&filters)
            .await
            .expect_err(r#"request with bad version "0.0.999" should be rejected with a version mismatch error"#);
    }

    #[tokio::test]
    async fn test_good_version() {
        let era_checker = EraChecker::new(SupportedEra::dummy(), Epoch(1));
        let mut version_provider = APIVersionProvider::new(Arc::new(era_checker));
        let mut open_api_versions = HashMap::new();
        open_api_versions.insert("openapi.yaml".to_string(), Version::new(0, 1, 0));
        version_provider.update_open_api_versions(open_api_versions);
        let api_version_provider = Arc::new(version_provider);
        let filters = header_must_be(api_version_provider, TestLogger::stdout());
        warp::test::request()
            .header(MITHRIL_API_VERSION_HEADER, "0.1.2")
            .path("/aggregator/whatever")
            .filter(&filters)
            .await
            .expect(r#"request with the good version "0.1.2" should not be rejected"#);
    }

    #[tokio::test]
    async fn test_404_response_should_include_status_code_and_headers() {
        let container = Arc::new(
            DependenciesBuilder::new_with_stdout_logger(Configuration::new_sample())
                .build_dependency_container()
                .await
                .unwrap(),
        );
        let state = RouterState::new_with_dummy_config(container);
        let routes = routes(Arc::new(state));

        let response = warp::test::request()
            .path("/aggregator/a-route-that-does-not-exist")
            // We need to set the Origin header to trigger the CORS middleware
            .header("Origin", "http://localhost")
            .reply(&routes)
            .await;
        let response_headers = response.headers();

        assert_eq!(response.status(), StatusCode::NOT_FOUND);
        assert!(
            response_headers.get(MITHRIL_API_VERSION_HEADER).is_some(),
            "API version header should be present, headers: {response_headers:?}",
        );
        assert!(
            response_headers
                .get("access-control-allow-origin")
                .is_some(),
            "CORS headers should be present, headers: {response_headers:?}",
        );
    }
}