wasmcloud-provider-httpserver 0.17.1

Http server for wasmcloud, using warp. This package provides a library, and a capability provider with the 'wasmcloud:httpserver' contract.
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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
//! Configuration settings for HttpServer.
//! The "values" map in the actor link definition may contain
//! one or more of the following keys,
//! which determine how the configuration is parsed.
//!
//! For the key...
use base64::{engine::Engine as _, prelude::BASE64_STANDARD_NO_PAD};
use serde::{de::Deserializer, de::Visitor, Deserialize, Serialize};
use std::net::{IpAddr, Ipv4Addr};
///   config_file:       load configuration from file name.
///                      Interprets file as json or toml, based on file extension.
///   config_b64:        Configuration is a base64-encoded json string
///   config_json:       Configuration is a raw json string
///
/// If no configuration is provided, the default settings below will be used:
/// - TLS is disabled
/// - CORS allows all hosts(origins), most methods, and common headers
///   (see constants below).
/// - Default listener is bound to 127.0.0.1 port 8000.
///
use std::path::Path;
use std::{collections::HashMap, fmt, io::ErrorKind, net::SocketAddr, ops::Deref, str::FromStr};

use crate::Error;

const DEFAULT_ADDR: &str = "127.0.0.1:8000";
const DEFAULT_LOG_LEVEL: LogLevel = LogLevel::Debug;

const CORS_ALLOWED_ORIGINS: &[&str] = &[];
const CORS_ALLOWED_METHODS: &[&str] = &["GET", "POST", "PUT", "DELETE", "HEAD", "OPTIONS"];
const CORS_ALLOWED_HEADERS: &[&str] = &[
    "accept",
    "accept-language",
    "content-type",
    "content-language",
];
const CORS_EXPOSED_HEADERS: &[&str] = &[];
const CORS_DEFAULT_MAX_AGE_SECS: u64 = 300;
// Maximum content length. Can be overridden in settings or link definition
// Syntax: number, or number followed by 'K', 'M', or 'G'
// Default value is 100M (100*1024*1024)
pub const DEFAULT_MAX_CONTENT_LEN: u64 = 100 * 1024 * 1024;
// max possible value of content length. If sending to wasm32, memory is limited to 2GB,
// practically this should be quite a bit smaller. Setting to 1GB for now.
pub const CONTENT_LEN_LIMIT: u64 = 1024 * 1024 * 1024;

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ServiceSettings {
    /// Bind address
    #[serde(default)]
    pub address: Option<SocketAddr>,

    /// tls config
    #[serde(default)]
    pub tls: Tls,

    /// cors config
    #[serde(default)]
    pub cors: Cors,

    /// logging
    #[serde(default)]
    pub log: Log,

    /// Rpc timeout - how long (milliseconds) to wait for actor's response
    /// before returning a status 503 to the http client
    /// If not set, uses the system-wide rpc timeout
    #[serde(default)]
    pub timeout_ms: Option<u64>,

    /// Max content length. Default "10m" (10MiB = 10485760 bytes)
    /// Can be overridden by link def value max_content_len
    /// Accepts number (bytes), or number with suffix 'k', 'm', or 'g', (upper or lower case)
    /// representing multiples of 1024. For example,
    /// - "500" = 5000 bytes,
    /// - "5k" = 5 * 1024 bytes,
    /// - "5m" = 5 * 1024*1024 bytes,
    /// - "1g" = 1024*1024*1024 bytes
    /// The value may not be higher than i32::MAX
    pub max_content_len: Option<String>,

    /// capture any other configuration values
    #[serde(flatten)]
    extra: HashMap<String, serde_json::Value>,
}

impl Default for ServiceSettings {
    fn default() -> ServiceSettings {
        ServiceSettings {
            address: Some(SocketAddr::from_str(DEFAULT_ADDR).unwrap()),
            tls: Tls::default(),
            cors: Cors::default(),
            log: Log::default(),
            timeout_ms: None,
            max_content_len: Some(DEFAULT_MAX_CONTENT_LEN.to_string()),
            extra: Default::default(),
        }
    }
}

macro_rules! merge {
    ( $self:ident, $other: ident, $( $field:ident),+ ) => {
        $(
            if $other.$field.is_some() {
                $self.$field = $other.$field;
            }
        )*
    };
}

impl ServiceSettings {
    /// load Settings from a file with .toml or .json extension
    fn from_file<P: AsRef<Path>>(fpath: P) -> Result<Self, Error> {
        let data = std::fs::read_to_string(&fpath).map_err(|e| {
            Error::Settings(format!("reading file {}: {}", &fpath.as_ref().display(), e))
        })?;
        if let Some(ext) = fpath.as_ref().extension() {
            let ext = ext.to_string_lossy();
            match ext.as_ref() {
                "json" => ServiceSettings::from_json(&data),
                "toml" => ServiceSettings::from_toml(&data),
                _ => Err(Error::Settings(format!("unrecognized extension {}", ext))),
            }
        } else {
            Err(Error::Settings(format!(
                "unrecognized file type {}",
                &fpath.as_ref().display()
            )))
        }
    }

    /// load settings from json
    fn from_json(data: &str) -> Result<Self, Error> {
        serde_json::from_str(data).map_err(|e| Error::Settings(format!("invalid json: {}", e)))
    }

    /// load settings from toml file
    fn from_toml(data: &str) -> Result<Self, Error> {
        toml::from_str(data).map_err(Error::SettingsToml)
    }

    /// Merge settings from other into self
    fn merge(&mut self, other: ServiceSettings) {
        merge!(self, other, address);
        self.tls.merge(other.tls);
        self.cors.merge(other.cors);
        self.log.merge(other.log);
    }

    /// perform additional validation checks on settings.
    /// Several checks have already been done during deserialization.
    /// All errors found are combined into a single error message
    fn validate(&self) -> Result<(), Error> {
        let mut errors = Vec::new();
        // 1. amke sure address is valid
        if self.address.is_none() {
            errors.push("missing bind address".to_string());
        }
        match (&self.tls.cert_file, &self.tls.priv_key_file) {
            (None, None) => {}
            (Some(_), None) | (None, Some(_)) => {
                errors.push("for tls, both 'cert_file' and 'priv_key_file' must be set".to_string())
            }
            (Some(cert_file), Some(key_file)) => {
                for f in [("cert_file", &cert_file), ("priv_key_file", &key_file)].iter() {
                    let path: &Path = f.1.as_ref();
                    if !path.is_file() {
                        errors.push(format!(
                            "missing tls.{} '{}'{}",
                            f.0,
                            &path.display(),
                            if !path.is_absolute() {
                                " : perhaps you should make the path absolute"
                            } else {
                                ""
                            }
                        ));
                    }
                }
            }
        }
        if let Some(ref methods) = self.cors.allowed_methods {
            for m in methods.0.iter() {
                if http::Method::try_from(m.as_str()).is_err() {
                    errors.push(format!("invalid CORS method: '{}'", m));
                }
            }
        }
        if !errors.is_empty() {
            Err(Error::Settings(format!(
                "\nInvalid httpserver settings: \n{}\n",
                errors.join("\n")
            )))
        } else {
            Ok(())
        }
    }
}

/// Load settings provides a flexible means for loading configuration.
/// Return value is any structure with Deserialize, or for example, HashMap<String,String>
///   config_file: load from file name. Interprets file as json, toml, yaml, based on file extension.
///   config_b64:  base64-encoded json string
///   config_json: raw json string
/// Also accept "address" (a string representing SocketAddr) and "port", a localhost port
/// If more than one key is provided, they are processed in the order above.
///   (later names override earlier names in the list)
///
pub fn load_settings(values: &HashMap<String, String>) -> Result<ServiceSettings, Error> {
    // Allow keys to be UPPERCASE, as an accommodation
    // for the lost souls who prefer ugly all-caps variable names.
    let values = crate::make_case_insensitive(values).ok_or_else(|| Error::InvalidParameter(
        "Key collision: httpserver settings (from linkdef.values) has one or more keys that are not unique based on case-insensitivity"
            .to_string(),
    ))?;

    let mut settings = ServiceSettings::default();

    if let Some(fpath) = values.get("config_file") {
        settings.merge(ServiceSettings::from_file(fpath)?);
    }

    if let Some(str) = values.get("config_b64") {
        let bytes = BASE64_STANDARD_NO_PAD
            .decode(str)
            .map_err(|e| Error::Settings(format!("invalid base64 encoding: {}", e)))?;
        settings.merge(ServiceSettings::from_json(&String::from_utf8_lossy(
            &bytes,
        ))?);
    }

    if let Some(str) = values.get("config_json") {
        settings.merge(ServiceSettings::from_json(str)?);
    }

    // accept address as value parameter
    if let Some(addr) = values.get("address") {
        settings.address = Some(
            SocketAddr::from_str(addr)
                .map_err(|_| Error::InvalidParameter(format!("invalid address: {}", addr)))?,
        );
    }

    // accept port, for compatibility with previous implementations
    if let Some(addr) = values.get("port") {
        let port = addr
            .parse::<u16>()
            .map_err(|_| Error::InvalidParameter(format!("Invalid port: {}", addr)))?;
        settings.address = Some(SocketAddr::new(
            IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)),
            port,
        ));
    }

    settings.validate()?;
    Ok(settings)
}

#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct Tls {
    /// path to server X.509 cert chain file. Must be PEM-encoded
    pub cert_file: Option<String>,

    pub priv_key_file: Option<String>,
}

impl Tls {
    fn merge(&mut self, other: Tls) {
        merge!(self, other, cert_file, priv_key_file);
    }
}

impl Tls {
    pub fn is_set(&self) -> bool {
        self.cert_file.is_some() && self.priv_key_file.is_some()
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct Cors {
    pub allowed_origins: Option<AllowedOrigins>,

    pub allowed_headers: Option<AllowedHeaders>,

    pub allowed_methods: Option<AllowedMethods>,

    pub exposed_headers: Option<ExposedHeaders>,

    // TODO: allow_credentials?
    pub max_age_secs: Option<u64>,
}

impl Default for Cors {
    fn default() -> Self {
        Cors {
            allowed_origins: Some(AllowedOrigins::default()),
            allowed_headers: Some(AllowedHeaders::default()),
            allowed_methods: Some(AllowedMethods::default()),
            exposed_headers: Some(ExposedHeaders::default()),
            max_age_secs: Some(CORS_DEFAULT_MAX_AGE_SECS),
        }
    }
}

impl Cors {
    fn merge(&mut self, other: Cors) {
        merge!(
            self,
            other,
            allowed_origins,
            allowed_headers,
            allowed_methods,
            exposed_headers,
            max_age_secs
        );
    }
}

#[derive(Debug, Clone, Default, Serialize, PartialEq, Eq)]
pub struct CorsOrigin(String);

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct AllowedOrigins(Vec<CorsOrigin>);

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct AllowedHeaders(Vec<String>);

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct AllowedMethods(Vec<String>);

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ExposedHeaders(Vec<String>);

/*
/// parse semicolon-delimited origin names
fn parse_allowed_origins(arg: &str) -> Result<AllowedOrigins, std::io::Error> {
    let mut res: Vec<CorsOrigin> = Vec::new();
    for origin_str in arg.split(';') {
        res.push(CorsOrigin::from_str(origin_str)?);
    }
    Ok(AllowedOrigins(res))
}
 */

impl<'de> Deserialize<'de> for CorsOrigin {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct CorsOriginVisitor;
        impl<'de> Visitor<'de> for CorsOriginVisitor {
            type Value = CorsOrigin;

            fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
                write!(fmt, "an origin in format http[s]://example.com[:3000]",)
            }

            fn visit_str<E>(self, v: &str) -> std::result::Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                CorsOrigin::from_str(v).map_err(E::custom)
            }
        }
        deserializer.deserialize_str(CorsOriginVisitor)
    }
}

impl FromStr for CorsOrigin {
    type Err = std::io::Error;

    fn from_str(origin: &str) -> Result<Self, Self::Err> {
        let uri = warp::http::uri::Uri::from_str(origin).map_err(|invalid_uri| {
            std::io::Error::new(
                ErrorKind::InvalidInput,
                format!("Invalid uri: {}.\n{}", origin, invalid_uri),
            )
        })?;
        if let Some(s) = uri.scheme_str() {
            if s != "http" && s != "https" {
                return Err(std::io::Error::new(
                    ErrorKind::InvalidInput,
                    format!(
                        "Cors origin invalid schema {}, only [http] and [https] are supported: ",
                        uri.scheme_str().unwrap()
                    ),
                ));
            }
        } else {
            return Err(std::io::Error::new(
                ErrorKind::InvalidInput,
                "Cors origin missing schema, only [http] or [https] are supported",
            ));
        }

        if let Some(p) = uri.path_and_query() {
            if p.as_str() != "/" {
                return Err(std::io::Error::new(
                    ErrorKind::InvalidInput,
                    format!("Invalid value {} in cors schema.", p.as_str()),
                ));
            }
        }
        Ok(CorsOrigin(origin.trim_end_matches('/').to_owned()))
    }
}

impl AsRef<str> for CorsOrigin {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl Deref for AllowedOrigins {
    type Target = Vec<CorsOrigin>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl Default for AllowedOrigins {
    fn default() -> Self {
        AllowedOrigins(
            CORS_ALLOWED_ORIGINS
                .iter()
                .map(|s| CorsOrigin(s.to_string()))
                .collect::<Vec<_>>(),
        )
    }
}

impl Deref for AllowedHeaders {
    type Target = Vec<String>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl Default for AllowedHeaders {
    fn default() -> Self {
        AllowedHeaders(from_defaults(CORS_ALLOWED_HEADERS))
    }
}

impl Default for AllowedMethods {
    fn default() -> Self {
        AllowedMethods(from_defaults(CORS_ALLOWED_METHODS))
    }
}

impl Deref for AllowedMethods {
    type Target = Vec<String>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl Deref for ExposedHeaders {
    type Target = Vec<String>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl Default for ExposedHeaders {
    fn default() -> Self {
        ExposedHeaders(
            CORS_EXPOSED_HEADERS
                .iter()
                .map(|s| s.to_string())
                .collect::<Vec<_>>(),
        )
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum LogLevel {
    Disabled,
    Error,
    Warn,
    Info,
    Debug,
    Trace,
}

#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct Log {
    log_level: Option<LogLevel>,
}

impl FromStr for LogLevel {
    type Err = std::io::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "disabled" => Ok(Self::Disabled),
            "error" => Ok(Self::Error),
            "warn" => Ok(Self::Warn),
            "info" => Ok(Self::Info),
            "debug" => Ok(Self::Debug),
            "trace" => Ok(Self::Trace),
            _ => Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                format!("{} is not a valid log level", s),
            )),
        }
    }
}

impl fmt::Display for LogLevel {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match *self {
            Self::Disabled => write!(f, "disabled"),
            Self::Error => write!(f, "error"),
            Self::Warn => write!(f, "warn"),
            Self::Info => write!(f, "info"),
            Self::Debug => write!(f, "debug"),
            Self::Trace => write!(f, "trace"),
        }
    }
}

impl Default for LogLevel {
    fn default() -> Self {
        DEFAULT_LOG_LEVEL
    }
}

impl Log {
    fn merge(&mut self, other: Log) {
        if let Some(level) = other.log_level {
            self.log_level = Some(level);
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "UPPERCASE")]
pub enum HttpMethod {
    Get,
    Post,
    Put,
    Delete,
    Head,
    Options,
    Connect,
    Patch,
    Trace,
}

impl FromStr for HttpMethod {
    type Err = std::io::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_uppercase().as_str() {
            "GET" => Ok(Self::Get),
            "PUT" => Ok(Self::Put),
            "POST" => Ok(Self::Post),
            "DELETE" => Ok(Self::Delete),
            "HEAD" => Ok(Self::Head),
            "OPTIONS" => Ok(Self::Options),
            "CONNECT" => Ok(Self::Connect),
            "PATCH" => Ok(Self::Patch),
            "TRACE" => Ok(Self::Trace),
            _ => Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                format!("{} is not a valid http method", s),
            )),
        }
    }
}

/// convert array of &str into array of T if T is From<&str>
fn from_defaults<'d, T>(d: &[&'d str]) -> Vec<T>
where
    T: std::convert::From<&'d str>,
{
    // unwrap ok here bacause this is only used for default values
    d.iter().map(|s| T::from(*s)).collect::<Vec<_>>()
}

#[cfg(test)]
mod test {
    use crate::settings::{CorsOrigin, ServiceSettings};
    //use assert_matches::assert_matches;
    use std::str::FromStr;

    const GOOD_ORIGINS: &[&str] = &[
        // origins that should be parsed correctly
        "https://www.example.com",
        "https://www.example.com:1000",
        "http://localhost",
        "http://localhost:8080",
        "http://127.0.0.1",
        "http://127.0.0.1:8080",
        "https://:8080",
    ];

    const BAD_ORIGINS: &[&str] = &[
        // invalid origin syntax
        "ftp://www.example.com", // only http,https allowed
        "localhost",
        "127.0.0.1",
        "127.0.0.1:8080",
        ":8080",
        "/path/file.txt",
        "http:",
        "https://",
    ];

    #[test]
    fn settings_init() {
        let s = ServiceSettings::default();
        assert!(s.address.is_some());

        assert!(s.cors.allowed_methods.is_some());
        assert!(s.cors.allowed_origins.is_some());

        assert!(s.cors.allowed_origins.unwrap().0.is_empty())
    }

    #[test]
    fn settings_toml() {
        let toml = r#"
    [cors]
    allowed_methods = [ "GET" ]
    "#;

        let s = ServiceSettings::from_toml(toml).expect("parse_toml");
        assert_eq!(s.cors.allowed_methods.as_ref().unwrap().0.len(), 1);
        assert_eq!(
            s.cors.allowed_methods.as_ref().unwrap().0.get(0).unwrap(),
            "GET"
        );
    }

    #[test]
    fn settings_json() {
        let json = r#"{
        "cors": {
            "allowed_headers": [ "X-Cookies" ]
         }
         }"#;

        let s = ServiceSettings::from_json(json).expect("parse_json");
        assert_eq!(s.cors.allowed_headers.as_ref().unwrap().0.len(), 1);
        assert_eq!(
            s.cors.allowed_headers.as_ref().unwrap().0.get(0).unwrap(),
            "X-Cookies"
        );
    }

    #[test]
    fn origins_deserialize() {
        // test CorsOrigin
        for valid in GOOD_ORIGINS.iter() {
            let o =
                serde_json::from_value::<CorsOrigin>(serde_json::Value::String(valid.to_string()));
            assert!(o.is_ok(), "from_value '{}'", valid);

            // test as_ref()
            assert_eq!(&o.unwrap().0, valid);
        }
    }

    #[test]
    fn origins_from_str() {
        // test CorsOrigin
        for &valid in GOOD_ORIGINS.iter() {
            let o = CorsOrigin::from_str(valid);
            println!("{}: {:?}", valid, o);
            assert!(o.is_ok(), "from_str '{}'", valid);

            // test as_ref()
            assert_eq!(&o.unwrap().0, valid);
        }
    }

    #[test]
    fn origins_negative() {
        for bad in BAD_ORIGINS.iter() {
            let o =
                serde_json::from_value::<CorsOrigin>(serde_json::Value::String(bad.to_string()));
            println!("{}: {:?}", bad, o);
            assert!(o.is_err(), "from_value '{}' (expect err)", bad);

            let o = serde_json::from_str::<CorsOrigin>(bad);
            println!("{}: {:?}", bad, o);
            assert!(o.is_err(), "from_str '{}' (expect err)", bad);
        }
    }
}