martin 1.16.1

Blazing fast and lightweight tile server with PostGIS, MBTiles, and PMTiles support
Documentation
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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
use std::fmt;

use actix_http::Method;
use serde::de::value::MapAccessDeserializer;
use serde::de::{self, MapAccess, Visitor};
use serde::{Deserialize, Deserializer, Serialize};
use tracing::info;

use crate::config::file::{
    CollectUnrecognizedKeys, ConfigFileError, ConfigFileResult, ConfigurationLivecycleHooks,
    UnrecognizedValues,
};

#[derive(Clone, Debug, Serialize, PartialEq, Eq, CollectUnrecognizedKeys)]
#[cfg_attr(feature = "unstable-schemas", derive(schemars::JsonSchema))]
#[serde(untagged)]
pub enum CorsConfig {
    Properties(CorsProperties),
    SimpleFlag(bool),
}

impl<'de> Deserialize<'de> for CorsConfig {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        struct CorsVisitor;

        impl<'de> Visitor<'de> for CorsVisitor {
            type Value = CorsConfig;

            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                f.write_str(
                    "either a boolean (`cors: true` / `cors: false`) or a properties map \
                     with at least an `origin` list",
                )
            }

            fn visit_bool<E: de::Error>(self, value: bool) -> Result<CorsConfig, E> {
                Ok(CorsConfig::SimpleFlag(value))
            }

            fn visit_map<M: MapAccess<'de>>(self, map: M) -> Result<CorsConfig, M::Error> {
                let props = CorsProperties::deserialize(MapAccessDeserializer::new(map))?;
                Ok(CorsConfig::Properties(props))
            }

            // Other inputs (string, number, sequence, …) fall through to serde's default,
            // which emits `de::Error::invalid_type` - saphyr attaches the source span to that
            // variant, so we get a labelled diagnostic for free.
        }

        deserializer.deserialize_any(CorsVisitor)
    }
}

impl Default for CorsConfig {
    fn default() -> Self {
        Self::SimpleFlag(true)
    }
}

#[derive(
    Clone,
    Debug,
    Deserialize,
    Serialize,
    PartialEq,
    Eq,
    CollectUnrecognizedKeys,
    ConfigurationLivecycleHooks,
)]
#[cfg_attr(feature = "unstable-schemas", derive(schemars::JsonSchema))]
pub struct CorsProperties {
    /// Sets the `Access-Control-Allow-Origin` header \[default: *\]
    /// '*' will use the requests `ORIGIN` header
    #[serde(default)]
    #[cfg_attr(
        feature = "unstable-schemas",
        schemars(example = cors_origin_example())
    )]
    pub origin: Vec<String>,
    /// Sets `Access-Control-Max-Age` Header. \[default: null\]
    /// null means not setting the header for preflight requests
    #[cfg_attr(feature = "unstable-schemas", schemars(example = &3600usize))]
    pub max_age: Option<usize>,

    #[serde(flatten, skip_serializing)]
    #[cfg_attr(feature = "unstable-schemas", schemars(skip))]
    pub unrecognized: UnrecognizedValues,
}

#[cfg(feature = "unstable-schemas")]
fn cors_origin_example() -> Vec<String> {
    vec!["https://example.org".to_owned()]
}

impl Default for CorsProperties {
    fn default() -> Self {
        Self {
            origin: vec!["*".to_owned()],
            max_age: None,
            unrecognized: UnrecognizedValues::default(),
        }
    }
}

impl CorsProperties {
    pub const fn validate(&self) -> ConfigFileResult<()> {
        if self.origin.is_empty() {
            Err(ConfigFileError::CorsNoOriginsConfigured)
        } else {
            Ok(())
        }
    }
}

impl CorsConfig {
    /// Log the current configuration
    pub fn log_current_configuration(&self) {
        match &self {
            Self::SimpleFlag(false) => info!("CORS is disabled"),
            Self::SimpleFlag(true) => {
                let CorsProperties {
                    origin,
                    max_age,
                    unrecognized: _,
                } = CorsProperties::default();
                info!("CORS enabled with defaults (origin={origin:?}, max_age={max_age:?})");
            }
            Self::Properties(props) => {
                info!("CORS enabled with custom properties: {props:?}");
            }
        }
    }

    /// Checks that that if cors is configured explicitly (instead of via `true`/`false`), `origin` is configured
    pub fn validate(&self) -> ConfigFileResult<()> {
        match self {
            Self::SimpleFlag(_) => Ok(()),
            Self::Properties(properties) => properties.validate(),
        }
    }

    #[must_use]
    /// Create [`actix_cors::Cors`] from the configuration
    pub fn make_cors_middleware(&self) -> Option<actix_cors::Cors> {
        match self {
            Self::SimpleFlag(false) => None,
            Self::SimpleFlag(true) => {
                let properties = CorsProperties::default();
                Some(Self::create_cors(&properties))
            }
            Self::Properties(properties) => Some(Self::create_cors(properties)),
        }
    }

    fn create_cors(properties: &CorsProperties) -> actix_cors::Cors {
        let mut cors = actix_cors::Cors::default();

        // allow any origin by default
        // this returns the value of the requests `ORIGIN` header in `Access-Control-Allow-Origin`
        if properties.origin.contains(&"*".to_owned()) {
            cors = cors.allow_any_origin();
        } else {
            for origin in &properties.origin {
                cors = cors.allowed_origin(origin);
            }
        }

        // only allow GET method by default
        cors = cors.allowed_methods([Method::GET]);

        // sets `Access-Control-Max-Age` if configured
        cors = cors.max_age(properties.max_age);

        cors
    }
}

#[cfg(test)]
mod tests {
    use std::assert_matches;

    use indoc::indoc;

    use super::*;
    use crate::config::test_helpers::{parse_yaml, render_failure};

    // ----- Custom `Deserialize` impl: every accepted shape and every error path -----
    //
    // Failure cases run through the full `parse_config` pipeline so the snapshot includes
    // the same graphical miette diagnostic (file path, line number, source snippet, caret,
    // help text) the user sees on the command line. Success cases use `parse_yaml` directly
    // since round-tripping through `Config` would obscure which variant was selected.

    #[test]
    fn deserialize_bool_true() {
        let cfg = parse_yaml::<CorsConfig>("true");
        assert_eq!(cfg, CorsConfig::SimpleFlag(true));
    }

    #[test]
    fn deserialize_bool_false() {
        let cfg = parse_yaml::<CorsConfig>("false");
        assert_eq!(cfg, CorsConfig::SimpleFlag(false));
    }

    #[test]
    fn deserialize_properties_map() {
        let cfg = parse_yaml::<CorsConfig>(indoc! {"
            origin:
              - https://example.org
            max_age: 3600
        "});
        let CorsConfig::Properties(props) = cfg else {
            panic!("expected Properties variant");
        };
        assert_eq!(props.origin, vec!["https://example.org".to_owned()]);
        assert_eq!(props.max_age, Some(3600));
    }

    #[test]
    fn deserialize_rejects_integer() {
        insta::assert_snapshot!(render_failure("cors: 42\n"), @"
        martin::config::yaml (https://maplibre.org/martin/config-file/)

          × invalid type: integer `42`, expected either a boolean (`cors: true` /
          │ `cors: false`) or a properties map with at least an `origin` list
           ╭─[config.yaml:1:1]
         1 │ cors: 42
           · ──┬─
           ·   ╰── invalid type: integer `42`, expected either a boolean (`cors: true` / `cors: false`) or a properties map with at least an `origin` list
           ╰────
          help: Check the highlighted token in your YAML. The error usually indicates
                a mismatched type or an unexpected shape.
        ");
    }

    #[test]
    fn deserialize_rejects_quoted_string() {
        insta::assert_snapshot!(render_failure("cors: \"yes please\"\n"), @r#"
        martin::config::yaml (https://maplibre.org/martin/config-file/)

          × invalid type: string "yes please", expected either a boolean (`cors:
          │ true` / `cors: false`) or a properties map with at least an `origin` list
           ╭─[config.yaml:1:1]
         1 │ cors: "yes please"
           · ──┬─
           ·   ╰── invalid type: string "yes please", expected either a boolean (`cors: true` / `cors: false`) or a properties map with at least an `origin` list
           ╰────
          help: Check the highlighted token in your YAML. The error usually indicates
                a mismatched type or an unexpected shape.
        "#);
    }

    #[test]
    fn deserialize_rejects_sequence() {
        insta::assert_snapshot!(render_failure("cors: [https://example.org]\n"), @"
        martin::config::yaml (https://maplibre.org/martin/config-file/)

          × invalid type: sequence, expected either a boolean (`cors: true` / `cors:
          │ false`) or a properties map with at least an `origin` list
           ╭─[config.yaml:1:1]
         1 │ cors: [https://example.org]
           · ──┬─
           ·   ╰── invalid type: sequence, expected either a boolean (`cors: true` / `cors: false`) or a properties map with at least an `origin` list
           ╰────
          help: Check the highlighted token in your YAML. The error usually indicates
                a mismatched type or an unexpected shape.
        ");
    }

    // ----- Existing behavior tests (default values, validation, middleware) -----

    #[test]
    fn cors_config_default() {
        let config = CorsConfig::default();
        let middleware = config.make_cors_middleware();
        assert!(middleware.is_some());

        // Check if it's using the default SimpleFlag(true)
        if let CorsConfig::SimpleFlag(enabled) = config {
            assert!(enabled);
        } else {
            panic!("Expected SimpleFlag variant for default config");
        }
    }

    #[test]
    fn cors_properties_default_values() {
        let default_props = CorsProperties::default();
        assert_eq!(default_props.origin, vec!["*"]);
        assert_eq!(default_props.max_age, None);
        default_props.validate().unwrap();
    }

    #[test]
    fn cors_middleware_disabled() {
        let config = CorsConfig::SimpleFlag(false);
        assert!(config.make_cors_middleware().is_none());
    }

    #[test]
    fn cors_yaml_parsing() {
        let config: CorsConfig = serde_saphyr::from_str(indoc! {"
            origin:
              - https://example.org
            max_age: 3600
        "})
        .unwrap();

        if let CorsConfig::Properties(settings) = config {
            assert_eq!(settings.origin, vec!["https://example.org".to_owned()]);
            assert_eq!(settings.max_age, Some(3600));
        } else {
            panic!("Expected Settings variant for detailed config");
        }

        let config: CorsConfig = serde_saphyr::from_str("false").unwrap();
        assert_eq!(config, CorsConfig::SimpleFlag(false));

        let config: CorsConfig = serde_saphyr::from_str("true").unwrap();
        assert_eq!(config, CorsConfig::SimpleFlag(true));

        let config: CorsConfig = serde_saphyr::from_str(indoc! {"
            origin:
              - https://example.org
              - https://martin.maplibre.org
            max_age: 3600
        "})
        .unwrap();

        if let CorsConfig::Properties(settings) = config {
            assert_eq!(
                settings.origin,
                vec![
                    "https://example.org".to_owned(),
                    "https://martin.maplibre.org".to_owned(),
                ]
            );
            assert_eq!(settings.max_age, Some(3600));
        } else {
            panic!("Expected Settings variant for detailed config");
        }
    }

    #[test]
    fn cors_validation() {
        let config: CorsConfig = serde_saphyr::from_str(indoc! {"max_age: 3600"}).unwrap();
        if let CorsConfig::Properties(settings) = config {
            // This should fail validation
            assert_matches!(
                settings.validate(),
                Err(ConfigFileError::CorsNoOriginsConfigured)
            );
        } else {
            panic!("Expected Properties variant");
        }

        let config: CorsConfig = serde_saphyr::from_str(indoc! {"
            origin:
              - https://example.org
            max_age: 3600"})
        .unwrap();

        let CorsConfig::Properties(settings) = config else {
            panic!("Expected Properties variant");
        };
        settings.validate().unwrap();
    }

    #[test]
    fn cors_validation_error_empty_origin() {
        let properties = CorsProperties {
            origin: vec![],
            max_age: Some(3600),
            unrecognized: UnrecognizedValues::default(),
        };

        assert_matches!(
            properties.validate(),
            Err(ConfigFileError::CorsNoOriginsConfigured)
        );
    }

    #[test]
    fn cors_with_valid_properties() {
        let properties = CorsProperties {
            origin: vec!["https://example.org".to_owned()],
            max_age: Some(3600),
            unrecognized: UnrecognizedValues::default(),
        };
        properties.validate().unwrap();

        let config = CorsConfig::Properties(properties);
        let middleware = config.make_cors_middleware();
        assert!(middleware.is_some());
    }

    #[test]
    fn cors_with_wildcard_origin() {
        let properties = CorsProperties::default();
        assert_eq!(properties.origin, vec!["*".to_owned()]);
        properties.validate().unwrap();

        let middleware = CorsConfig::Properties(properties).make_cors_middleware();
        assert!(middleware.is_some());
    }
}