Skip to main content

rocket/config/
mod.rs

1//! Server and application configuration.
2//!
3//! See the [configuration guide] for full details.
4//!
5//! [configuration guide]: https://rocket.rs/v0.5/guide/configuration/
6//!
7//! ## Extracting Configuration Parameters
8//!
9//! Rocket exposes the active [`Figment`] via [`Rocket::figment()`]. Any value
10//! that implements [`Deserialize`] can be extracted from the figment:
11//!
12//! ```rust
13//! use rocket::fairing::AdHoc;
14//!
15//! #[derive(serde::Deserialize)]
16//! struct AppConfig {
17//!     id: Option<usize>,
18//!     port: u16,
19//! }
20//!
21//! #[rocket::launch]
22//! fn rocket() -> _ {
23//!     rocket::build().attach(AdHoc::config::<AppConfig>())
24//! }
25//! ```
26//!
27//! [`Figment`]: figment::Figment
28//! [`Rocket::figment()`]: crate::Rocket::figment()
29//! [`Rocket::figment()`]: crate::Rocket::figment()
30//! [`Deserialize`]: serde::Deserialize
31//!
32//! ## Workers
33//!
34//! The `workers` parameter sets the number of threads used for parallel task
35//! execution; there is no limit to the number of concurrent tasks. Due to a
36//! limitation in upstream async executers, unlike other values, the `workers`
37//! configuration value cannot be reconfigured or be configured from sources
38//! other than those provided by [`Config::figment()`]. In other words, only the
39//! values set by the `ROCKET_WORKERS` environment variable or in the `workers`
40//! property of `Rocket.toml` will be considered - all other `workers` values
41//! are ignored.
42//!
43//! ## Custom Providers
44//!
45//! A custom provider can be set via [`rocket::custom()`], which replaces calls to
46//! [`rocket::build()`]. The configured provider can be built on top of
47//! [`Config::figment()`], [`Config::default()`], both, or neither. The
48//! [Figment](figment) documentation has full details on instantiating existing
49//! providers like [`Toml`]() and [`Env`] as well as creating custom providers for
50//! more complex cases.
51//!
52//! Configuration values can be overridden at runtime by merging figment's tuple
53//! providers with Rocket's default provider:
54//!
55//! ```rust
56//! # #[macro_use] extern crate rocket;
57//! use rocket::data::{Limits, ToByteUnit};
58//!
59//! #[launch]
60//! fn rocket() -> _ {
61//!     let figment = rocket::Config::figment()
62//!         .merge(("port", 1111))
63//!         .merge(("limits", Limits::new().limit("json", 2.mebibytes())));
64//!
65//!     rocket::custom(figment).mount("/", routes![/* .. */])
66//! }
67//! ```
68//!
69//! An application that wants to use Rocket's defaults for [`Config`], but not
70//! its configuration sources, while allowing the application to be configured
71//! via an `App.toml` file that uses top-level keys as profiles (`.nested()`)
72//! and `APP_` environment variables as global overrides (`.global()`), and
73//! `APP_PROFILE` to configure the selected profile, can be structured as
74//! follows:
75//!
76//! ```rust
77//! # #[macro_use] extern crate rocket;
78//! use serde::{Serialize, Deserialize};
79//! use figment::{Figment, Profile, providers::{Format, Toml, Serialized, Env}};
80//! use rocket::fairing::AdHoc;
81//!
82//! #[derive(Debug, Deserialize, Serialize)]
83//! struct Config {
84//!     app_value: usize,
85//!     /* and so on.. */
86//! }
87//!
88//! impl Default for Config {
89//!     fn default() -> Config {
90//!         Config { app_value: 3, }
91//!     }
92//! }
93//!
94//! #[launch]
95//! fn rocket() -> _ {
96//!     let figment = Figment::from(rocket::Config::default())
97//!         .merge(Serialized::defaults(Config::default()))
98//!         .merge(Toml::file("App.toml").nested())
99//!         .merge(Env::prefixed("APP_").global())
100//!         .select(Profile::from_env_or("APP_PROFILE", "default"));
101//!
102//!     rocket::custom(figment)
103//!         .mount("/", routes![/* .. */])
104//!         .attach(AdHoc::config::<Config>())
105//! }
106//! ```
107//!
108//! [`rocket::custom()`]: crate::custom()
109//! [`rocket::build()`]: crate::build()
110//! [`Toml`]: figment::providers::Toml
111//! [`Env`]: figment::providers::Env
112
113#[macro_use]
114mod ident;
115mod config;
116mod shutdown;
117mod ip_header;
118
119#[cfg(feature = "tls")]
120mod tls;
121
122#[cfg(feature = "secrets")]
123mod secret_key;
124
125#[doc(hidden)]
126pub use config::{pretty_print_error, bail_with_config_error};
127
128pub use config::Config;
129pub use crate::log::LogLevel;
130pub use shutdown::Shutdown;
131pub use ident::Ident;
132
133#[cfg(feature = "tls")]
134pub use tls::{TlsConfig, CipherSuite};
135
136#[cfg(feature = "mtls")]
137pub use tls::MutualTls;
138
139#[cfg(feature = "secrets")]
140pub use secret_key::SecretKey;
141
142#[cfg(unix)]
143pub use shutdown::Sig;
144
145#[cfg(test)]
146mod tests {
147    use std::net::Ipv4Addr;
148    use figment::{Figment, Profile};
149    use pretty_assertions::assert_eq;
150
151    use crate::log::LogLevel;
152    use crate::data::{Limits, ToByteUnit};
153    use crate::config::Config;
154
155    #[test]
156    fn test_figment_is_default() {
157        figment::Jail::expect_with(|_| {
158            let mut default: Config = Config::figment().extract().unwrap();
159            default.profile = Config::default().profile;
160            assert_eq!(default, Config::default());
161            Ok(())
162        });
163    }
164
165    #[test]
166    fn test_default_round_trip() {
167        figment::Jail::expect_with(|_| {
168            let original = Config::figment();
169            let roundtrip = Figment::from(Config::from(&original));
170            for figment in &[original, roundtrip] {
171                let config = Config::from(figment);
172                assert_eq!(config, Config::default());
173            }
174
175            Ok(())
176        });
177    }
178
179    #[test]
180    fn test_missing_linger_is_default() {
181        use figment::{Provider, providers::Serialized};
182
183        // A complete configuration from before `linger` existed.
184        let data = Serialized::defaults(Config::default()).data().unwrap();
185        let mut dict = data[&Profile::Default].clone();
186        assert!(dict.remove(Config::LINGER).is_some());
187
188        let config: Config = Figment::from(Serialized::defaults(dict)).extract().unwrap();
189        assert_eq!(config.linger, 10);
190    }
191
192    #[test]
193    fn test_profile_env() {
194        figment::Jail::expect_with(|jail| {
195            jail.set_env("ROCKET_PROFILE", "debug");
196            let figment = Config::figment();
197            assert_eq!(figment.profile(), "debug");
198
199            jail.set_env("ROCKET_PROFILE", "release");
200            let figment = Config::figment();
201            assert_eq!(figment.profile(), "release");
202
203            jail.set_env("ROCKET_PROFILE", "random");
204            let figment = Config::figment();
205            assert_eq!(figment.profile(), "random");
206
207            Ok(())
208        });
209    }
210
211    #[test]
212    fn test_toml_file() {
213        figment::Jail::expect_with(|jail| {
214            jail.create_file("Rocket.toml", r#"
215                [default]
216                address = "1.2.3.4"
217                ident = "Something Cool"
218                port = 1234
219                workers = 20
220                keep_alive = 10
221                linger = 30
222                log_level = "off"
223                cli_colors = 0
224            "#)?;
225
226            let config = Config::from(Config::figment());
227            assert_eq!(config, Config {
228                address: Ipv4Addr::new(1, 2, 3, 4).into(),
229                port: 1234,
230                workers: 20,
231                ident: ident!("Something Cool"),
232                keep_alive: 10,
233                linger: 30,
234                log_level: LogLevel::Off,
235                cli_colors: false,
236                ..Config::default()
237            });
238
239            jail.create_file("Rocket.toml", r#"
240                [global]
241                address = "1.2.3.4"
242                ident = "Something Else Cool"
243                port = 1234
244                workers = 20
245                keep_alive = 10
246                log_level = "off"
247                cli_colors = 0
248            "#)?;
249
250            let config = Config::from(Config::figment());
251            assert_eq!(config, Config {
252                address: Ipv4Addr::new(1, 2, 3, 4).into(),
253                port: 1234,
254                workers: 20,
255                ident: ident!("Something Else Cool"),
256                keep_alive: 10,
257                log_level: LogLevel::Off,
258                cli_colors: false,
259                ..Config::default()
260            });
261
262            jail.set_env("ROCKET_CONFIG", "Other.toml");
263            jail.create_file("Other.toml", r#"
264                [default]
265                address = "1.2.3.4"
266                port = 1234
267                workers = 20
268                keep_alive = 10
269                log_level = "off"
270                cli_colors = 0
271            "#)?;
272
273            let config = Config::from(Config::figment());
274            assert_eq!(config, Config {
275                address: Ipv4Addr::new(1, 2, 3, 4).into(),
276                port: 1234,
277                workers: 20,
278                keep_alive: 10,
279                log_level: LogLevel::Off,
280                cli_colors: false,
281                ..Config::default()
282            });
283
284            Ok(())
285        });
286    }
287
288    #[test]
289    #[cfg(feature = "tls")]
290    fn test_tls_config_from_file() {
291        use crate::config::{TlsConfig, CipherSuite, Ident, Shutdown};
292
293        figment::Jail::expect_with(|jail| {
294            jail.create_file("Rocket.toml", r#"
295                [global]
296                shutdown.ctrlc = 0
297                ident = false
298
299                [global.tls]
300                certs = "/ssl/cert.pem"
301                key = "/ssl/key.pem"
302
303                [global.limits]
304                forms = "1mib"
305                json = "10mib"
306                stream = "50kib"
307            "#)?;
308
309            let config = Config::from(Config::figment());
310            assert_eq!(config, Config {
311                shutdown: Shutdown { ctrlc: false, ..Default::default() },
312                ident: Ident::none(),
313                tls: Some(TlsConfig::from_paths("/ssl/cert.pem", "/ssl/key.pem")),
314                limits: Limits::default()
315                    .limit("forms", 1.mebibytes())
316                    .limit("json", 10.mebibytes())
317                    .limit("stream", 50.kibibytes()),
318                ..Config::default()
319            });
320
321            jail.create_file("Rocket.toml", r#"
322                [global.tls]
323                certs = "cert.pem"
324                key = "key.pem"
325            "#)?;
326
327            let config = Config::from(Config::figment());
328            assert_eq!(config, Config {
329                tls: Some(TlsConfig::from_paths(
330                    jail.directory().join("cert.pem"),
331                    jail.directory().join("key.pem")
332                )),
333                ..Config::default()
334            });
335
336            jail.create_file("Rocket.toml", r#"
337                [global.tls]
338                certs = "cert.pem"
339                key = "key.pem"
340                prefer_server_cipher_order = true
341                ciphers = [
342                    "TLS_CHACHA20_POLY1305_SHA256",
343                    "TLS_AES_256_GCM_SHA384",
344                    "TLS_AES_128_GCM_SHA256",
345                    "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256",
346                    "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384",
347                    "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256",
348                ]
349            "#)?;
350
351            let config = Config::from(Config::figment());
352            let cert_path = jail.directory().join("cert.pem");
353            let key_path = jail.directory().join("key.pem");
354            assert_eq!(config, Config {
355                tls: Some(TlsConfig::from_paths(cert_path, key_path)
356                         .with_preferred_server_cipher_order(true)
357                         .with_ciphers([
358                             CipherSuite::TLS_CHACHA20_POLY1305_SHA256,
359                             CipherSuite::TLS_AES_256_GCM_SHA384,
360                             CipherSuite::TLS_AES_128_GCM_SHA256,
361                             CipherSuite::TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,
362                             CipherSuite::TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
363                             CipherSuite::TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
364                         ])),
365                ..Config::default()
366            });
367
368            jail.create_file("Rocket.toml", r#"
369                [global]
370                shutdown.ctrlc = 0
371                ident = false
372
373                [global.tls]
374                certs = "/ssl/cert.pem"
375                key = "/ssl/key.pem"
376
377                [global.limits]
378                forms = "1mib"
379                json = "10mib"
380                stream = "50kib"
381            "#)?;
382
383            let config = Config::from(Config::figment());
384            assert_eq!(config, Config {
385                shutdown: Shutdown { ctrlc: false, ..Default::default() },
386                ident: Ident::none(),
387                tls: Some(TlsConfig::from_paths("/ssl/cert.pem", "/ssl/key.pem")),
388                limits: Limits::default()
389                    .limit("forms", 1.mebibytes())
390                    .limit("json", 10.mebibytes())
391                    .limit("stream", 50.kibibytes()),
392                ..Config::default()
393            });
394
395            jail.create_file("Rocket.toml", r#"
396                [global.tls]
397                certs = "cert.pem"
398                key = "key.pem"
399            "#)?;
400
401            let config = Config::from(Config::figment());
402            assert_eq!(config, Config {
403                tls: Some(TlsConfig::from_paths(
404                    jail.directory().join("cert.pem"),
405                    jail.directory().join("key.pem")
406                )),
407                ..Config::default()
408            });
409
410            jail.create_file("Rocket.toml", r#"
411                [global.tls]
412                certs = "cert.pem"
413                key = "key.pem"
414                prefer_server_cipher_order = true
415                ciphers = [
416                    "TLS_CHACHA20_POLY1305_SHA256",
417                    "TLS_AES_256_GCM_SHA384",
418                    "TLS_AES_128_GCM_SHA256",
419                    "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256",
420                    "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384",
421                    "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256",
422                ]
423            "#)?;
424
425            let config = Config::from(Config::figment());
426            let cert_path = jail.directory().join("cert.pem");
427            let key_path = jail.directory().join("key.pem");
428            assert_eq!(config, Config {
429                tls: Some(TlsConfig::from_paths(cert_path, key_path)
430                         .with_preferred_server_cipher_order(true)
431                         .with_ciphers([
432                             CipherSuite::TLS_CHACHA20_POLY1305_SHA256,
433                             CipherSuite::TLS_AES_256_GCM_SHA384,
434                             CipherSuite::TLS_AES_128_GCM_SHA256,
435                             CipherSuite::TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,
436                             CipherSuite::TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
437                             CipherSuite::TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
438                         ])),
439                ..Config::default()
440            });
441
442            Ok(())
443        });
444    }
445
446    #[test]
447    #[cfg(feature = "mtls")]
448    fn test_mtls_config() {
449        use std::path::Path;
450
451        figment::Jail::expect_with(|jail| {
452            jail.create_file("Rocket.toml", r#"
453                [default.tls]
454                certs = "/ssl/cert.pem"
455                key = "/ssl/key.pem"
456            "#)?;
457
458            let config = Config::from(Config::figment());
459            assert!(config.tls.is_some());
460            assert!(config.tls.as_ref().unwrap().mutual.is_none());
461            assert!(config.tls_enabled());
462            assert!(!config.mtls_enabled());
463
464            jail.create_file("Rocket.toml", r#"
465                [default.tls]
466                certs = "/ssl/cert.pem"
467                key = "/ssl/key.pem"
468                mutual = { ca_certs = "/ssl/ca.pem" }
469            "#)?;
470
471            let config = Config::from(Config::figment());
472            assert!(config.tls_enabled());
473            assert!(config.mtls_enabled());
474
475            let mtls = config.tls.as_ref().unwrap().mutual.as_ref().unwrap();
476            assert_eq!(mtls.ca_certs().unwrap_left(), Path::new("/ssl/ca.pem"));
477            assert!(!mtls.mandatory);
478
479            jail.create_file("Rocket.toml", r#"
480                [default.tls]
481                certs = "/ssl/cert.pem"
482                key = "/ssl/key.pem"
483
484                [default.tls.mutual]
485                ca_certs = "/ssl/ca.pem"
486                mandatory = true
487            "#)?;
488
489            let config = Config::from(Config::figment());
490            let mtls = config.tls.as_ref().unwrap().mutual.as_ref().unwrap();
491            assert_eq!(mtls.ca_certs().unwrap_left(), Path::new("/ssl/ca.pem"));
492            assert!(mtls.mandatory);
493
494            jail.create_file("Rocket.toml", r#"
495                [default.tls]
496                certs = "/ssl/cert.pem"
497                key = "/ssl/key.pem"
498                mutual = { ca_certs = "relative/ca.pem" }
499            "#)?;
500
501            let config = Config::from(Config::figment());
502            let mtls = config.tls.as_ref().unwrap().mutual().unwrap();
503            assert_eq!(mtls.ca_certs().unwrap_left(),
504                jail.directory().join("relative/ca.pem"));
505
506            Ok(())
507        });
508    }
509
510    #[test]
511    fn test_profiles_merge() {
512        figment::Jail::expect_with(|jail| {
513            jail.create_file("Rocket.toml", r#"
514                [default.limits]
515                stream = "50kb"
516
517                [global]
518                limits = { forms = "2kb" }
519
520                [debug.limits]
521                file = "100kb"
522            "#)?;
523
524            jail.set_env("ROCKET_PROFILE", "unknown");
525            let config = Config::from(Config::figment());
526            assert_eq!(config, Config {
527                profile: Profile::const_new("unknown"),
528                limits: Limits::default()
529                    .limit("stream", 50.kilobytes())
530                    .limit("forms", 2.kilobytes()),
531                ..Config::default()
532            });
533
534            jail.set_env("ROCKET_PROFILE", "debug");
535            let config = Config::from(Config::figment());
536            assert_eq!(config, Config {
537                profile: Profile::const_new("debug"),
538                limits: Limits::default()
539                    .limit("stream", 50.kilobytes())
540                    .limit("forms", 2.kilobytes())
541                    .limit("file", 100.kilobytes()),
542                ..Config::default()
543            });
544
545            Ok(())
546        });
547    }
548
549    #[test]
550    #[cfg(feature = "tls")]
551    fn test_env_vars_merge() {
552        use crate::config::{TlsConfig, Ident};
553
554        figment::Jail::expect_with(|jail| {
555            jail.set_env("ROCKET_PORT", 9999);
556            let config = Config::from(Config::figment());
557            assert_eq!(config, Config {
558                port: 9999,
559                ..Config::default()
560            });
561
562            jail.set_env("ROCKET_TLS", r#"{certs="certs.pem"}"#);
563            let first_figment = Config::figment();
564            jail.set_env("ROCKET_TLS", r#"{key="key.pem"}"#);
565            let prev_figment = Config::figment().join(&first_figment);
566            let config = Config::from(&prev_figment);
567            assert_eq!(config, Config {
568                port: 9999,
569                tls: Some(TlsConfig::from_paths("certs.pem", "key.pem")),
570                ..Config::default()
571            });
572
573            jail.set_env("ROCKET_TLS", r#"{certs="new.pem"}"#);
574            let config = Config::from(Config::figment().join(&prev_figment));
575            assert_eq!(config, Config {
576                port: 9999,
577                tls: Some(TlsConfig::from_paths("new.pem", "key.pem")),
578                ..Config::default()
579            });
580
581            jail.set_env("ROCKET_LIMITS", r#"{stream=100kiB}"#);
582            let config = Config::from(Config::figment().join(&prev_figment));
583            assert_eq!(config, Config {
584                port: 9999,
585                tls: Some(TlsConfig::from_paths("new.pem", "key.pem")),
586                limits: Limits::default().limit("stream", 100.kibibytes()),
587                ..Config::default()
588            });
589
590            jail.set_env("ROCKET_IDENT", false);
591            let config = Config::from(Config::figment().join(&prev_figment));
592            assert_eq!(config, Config {
593                port: 9999,
594                tls: Some(TlsConfig::from_paths("new.pem", "key.pem")),
595                limits: Limits::default().limit("stream", 100.kibibytes()),
596                ident: Ident::none(),
597                ..Config::default()
598            });
599
600            Ok(())
601        });
602    }
603
604    #[test]
605    fn test_precedence() {
606        figment::Jail::expect_with(|jail| {
607            jail.create_file("Rocket.toml", r#"
608                [global.limits]
609                forms = "1mib"
610                stream = "50kb"
611                file = "100kb"
612            "#)?;
613
614            let config = Config::from(Config::figment());
615            assert_eq!(config, Config {
616                limits: Limits::default()
617                    .limit("forms", 1.mebibytes())
618                    .limit("stream", 50.kilobytes())
619                    .limit("file", 100.kilobytes()),
620                ..Config::default()
621            });
622
623            jail.set_env("ROCKET_LIMITS", r#"{stream=3MiB,capture=2MiB}"#);
624            let config = Config::from(Config::figment());
625            assert_eq!(config, Config {
626                limits: Limits::default()
627                    .limit("file", 100.kilobytes())
628                    .limit("forms", 1.mebibytes())
629                    .limit("stream", 3.mebibytes())
630                    .limit("capture", 2.mebibytes()),
631                ..Config::default()
632            });
633
634            jail.set_env("ROCKET_PROFILE", "foo");
635            let val: Result<String, _> = Config::figment().extract_inner("profile");
636            assert!(val.is_err());
637
638            Ok(())
639        });
640    }
641
642    #[test]
643    #[cfg(feature = "secrets")]
644    #[should_panic]
645    fn test_err_on_non_debug_and_no_secret_key() {
646        figment::Jail::expect_with(|jail| {
647            jail.set_env("ROCKET_PROFILE", "release");
648            let rocket = crate::custom(Config::figment());
649            let _result = crate::local::blocking::Client::untracked(rocket);
650            Ok(())
651        });
652    }
653
654    #[test]
655    #[cfg(feature = "secrets")]
656    #[should_panic]
657    fn test_err_on_non_debug2_and_no_secret_key() {
658        figment::Jail::expect_with(|jail| {
659            jail.set_env("ROCKET_PROFILE", "boop");
660            let rocket = crate::custom(Config::figment());
661            let _result = crate::local::blocking::Client::tracked(rocket);
662            Ok(())
663        });
664    }
665
666    #[test]
667    fn test_no_err_on_debug_and_no_secret_key() {
668        figment::Jail::expect_with(|jail| {
669            jail.set_env("ROCKET_PROFILE", "debug");
670            let figment = Config::figment();
671            assert!(crate::local::blocking::Client::untracked(crate::custom(&figment)).is_ok());
672            crate::async_main(async {
673                let rocket = crate::custom(&figment);
674                assert!(crate::local::asynchronous::Client::tracked(rocket).await.is_ok());
675            });
676
677            Ok(())
678        });
679    }
680
681    #[test]
682    fn test_no_err_on_release_and_custom_secret_key() {
683        figment::Jail::expect_with(|jail| {
684            jail.set_env("ROCKET_PROFILE", "release");
685            let key = "Bx4Gb+aSIfuoEyMHD4DvNs92+wmzfQK98qc6MiwyPY4=";
686            let figment = Config::figment().merge(("secret_key", key));
687
688            assert!(crate::local::blocking::Client::tracked(crate::custom(&figment)).is_ok());
689            crate::async_main(async {
690                let rocket = crate::custom(&figment);
691                assert!(crate::local::asynchronous::Client::untracked(rocket).await.is_ok());
692            });
693
694            Ok(())
695        });
696    }
697}