rocket/config/config.rs
1use figment::{Figment, Profile, Provider, Metadata, error::Result};
2use figment::providers::{Serialized, Env, Toml, Format};
3use figment::value::{Map, Dict, magic::RelativePathBuf};
4use serde::{Deserialize, Serialize};
5
6#[cfg(feature = "secrets")]
7use crate::config::SecretKey;
8use crate::config::{ShutdownConfig, Level, TraceFormat, Ident, CliColors};
9use crate::request::{self, Request, FromRequest};
10use crate::http::uncased::Uncased;
11use crate::data::Limits;
12
13/// Rocket server configuration.
14///
15/// See the [module level docs](crate::config) as well as the [configuration
16/// guide] for further details.
17///
18/// [configuration guide]: https://rocket.rs/v0.6-rc/guide/configuration/
19///
20/// # Defaults
21///
22/// All configuration values have a default, documented in the [fields](#fields)
23/// section below. [`Config::debug_default()`] returns the default values for
24/// the debug profile while [`Config::release_default()`] the default values for
25/// the release profile. The [`Config::default()`] method automatically selects
26/// the appropriate of the two based on the selected profile. With the exception
27/// of `log_level` and `log_format`, which are `info` / `pretty` in `debug` and
28/// `error` / `compact` in `release`, and `secret_key`, which is regenerated
29/// from a random value if not set in "debug" mode only, all default values are
30/// identical in all profiles.
31///
32/// # Provider Details
33///
34/// `Config` is a Figment [`Provider`] with the following characteristics:
35///
36/// * **Profile**
37///
38/// The profile is set to the value of the `profile` field.
39///
40/// * **Metadata**
41///
42/// This provider is named `Rocket Config`. It does not specify a
43/// [`Source`](figment::Source) and uses default interpolation.
44///
45/// * **Data**
46///
47/// The data emitted by this provider are the keys and values corresponding
48/// to the fields and values of the structure. The dictionary is emitted to
49/// the "default" meta-profile.
50///
51/// Note that these behaviors differ from those of [`Config::figment()`].
52#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
53pub struct Config {
54 /// The selected profile. **(default: _debug_ `debug` / _release_ `release`)**
55 ///
56 /// _**Note:** This field is never serialized nor deserialized. When a
57 /// `Config` is merged into a `Figment` as a `Provider`, this profile is
58 /// selected on the `Figment`. When a `Config` is extracted, this field is
59 /// set to the extracting Figment's selected `Profile`._
60 #[serde(skip)]
61 pub profile: Profile,
62 /// Number of threads to use for executing futures. **(default: `num_cores`)**
63 ///
64 /// _**Note:** Rocket only reads this value from sources in the [default
65 /// provider](Config::figment())._
66 pub workers: usize,
67 /// Limit on threads to start for blocking tasks. **(default: `512`)**
68 pub max_blocking: usize,
69 /// Runtime wake interval in milliseconds; disabled when `0`.
70 /// **(default: `250`)**
71 ///
72 /// Rocket's _runtime waker_ is a separate thread that periodically wakes
73 /// an idle Tokio worker to process I/O and timers. This works around a
74 /// limitation in Tokio: a task that blocks or fails to yield can prevent
75 /// I/O and timers from making progress even when other workers are idle.
76 ///
77 /// This value sets the time between wakeups, in milliseconds. For example,
78 /// the default value of `250` means that the waker requests a wakeup every
79 /// 250 milliseconds. Decreasing this value can reduce the time spent
80 /// stalled at the cost of more wakeup overhead. Increasing the value
81 /// reduces wakeups but permits longer stalls.
82 ///
83 /// To disable the waker, set this value to `0`. This is safe when all code
84 /// executed by Rocket on your behalf, including code in dependencies, is
85 /// _cooperative_: they yield promptly and never block a worker, and
86 /// potentially blocking or long operations are executed on separate threads
87 /// via [`spawn_blocking`] or equivalent. Note that declaring a function
88 /// `async` does not ensure that its code is cooperative.
89 ///
90 /// The waker requires an available worker to restore progress. If every
91 /// worker is occupied by synchronous blocking operations or computations
92 /// that do not yield, progress cannot resume until at least one worker
93 /// becomes available. Current-thread (single-thread) runtimes necessarily
94 /// fall into this category: whenever a task blocks the only worker, there
95 /// can never be another worker to restore progress. As a result, the waker
96 /// provides no benefit on these runtimes and is disabled irrespective of
97 /// this setting.
98 ///
99 /// [`spawn_blocking`]: crate::tokio::task::spawn_blocking
100 #[serde(default = "default_wake_interval")]
101 pub wake_interval: u32,
102 /// How, if at all, to identify the server via the `Server` header.
103 /// **(default: `"Rocket"`)**
104 pub ident: Ident,
105 /// The name of a header, whose value is typically set by an intermediary
106 /// server or proxy, which contains the real IP address of the connecting
107 /// client. Used internally and by [`Request::client_ip()`] and
108 /// [`Request::real_ip()`].
109 ///
110 /// To disable using any header for this purpose, set this value to `false`
111 /// or `None`. Deserialization semantics are identical to those of [`Ident`]
112 /// except that the value must syntactically be a valid HTTP header name.
113 ///
114 /// **Warning:** Rocket does not verify that this header was set by a proxy.
115 /// Any client can set it to any value. Only use this header if all requests
116 /// go through a trusted proxy that overwrites it. Otherwise, set this to
117 /// `false`.
118 ///
119 /// **(default: `"X-Real-IP"`)**
120 #[serde(deserialize_with = "crate::config::http_header::deserialize")]
121 pub ip_header: Option<Uncased<'static>>,
122 /// The name of a header, whose value is typically set by an intermediary
123 /// server or proxy, which contains the protocol ("http" or "https") used by
124 /// the connecting client. This is usually [`"X-Forwarded-Proto"`], as that
125 /// is the de-facto standard.
126 ///
127 /// The header value is parsed into a [`ProxyProto`], accessible via
128 /// [`Request::proxy_proto()`]. The value influences
129 /// [`Request::context_is_likely_secure()`] and the default value for the
130 /// `Secure` flag in cookies added to [`CookieJar`]s.
131 ///
132 /// To disable using any header for this purpose, set this value to `false`
133 /// or `None`. Deserialization semantics are identical to those of
134 /// [`Config::ip_header`] (the value must be a valid HTTP header name).
135 ///
136 /// **Warning:** Rocket does not verify that this header was set by a proxy.
137 /// Any client can set it to any value. Only use this header if all requests
138 /// go through a trusted proxy that overwrites it.
139 ///
140 /// **(default: `None`)**
141 ///
142 /// [`CookieJar`]: crate::http::CookieJar
143 /// [`ProxyProto`]: crate::http::ProxyProto
144 /// [`"X-Forwarded-Proto"`]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-Proto
145 #[serde(deserialize_with = "crate::config::http_header::deserialize")]
146 pub proxy_proto_header: Option<Uncased<'static>>,
147 /// Streaming read size limits. **(default: [`Limits::default()`])**
148 pub limits: Limits,
149 /// Directory to store temporary files in. **(default:
150 /// [`std::env::temp_dir()`])**
151 #[serde(serialize_with = "RelativePathBuf::serialize_relative")]
152 pub temp_dir: RelativePathBuf,
153 /// Keep-alive timeout in seconds; disabled when `0`. **(default: `5`)**
154 pub keep_alive: u32,
155 /// Linger time in seconds; disabled when `0`. **(default: `10`)**
156 ///
157 /// When closing a connection, Rocket shuts down writes and then reads and
158 /// discards incoming data for at most `linger` seconds or until the client
159 /// closes the connection. This prevents a TCP reset from discarding a
160 /// response the client has yet to read, as can happen when the client is
161 /// still sending data, such as the rest of a request body Rocket didn't
162 /// read. See [RFC 9112 §9.6] for details. This is equivalent to nginx's
163 /// `lingering_time` and is unrelated to the `SO_LINGER` socket option.
164 ///
165 /// When disabled, Rocket closes connections immediately, and a client still
166 /// sending data may receive a reset instead of a response. Lingering always
167 /// ends when the shutdown grace period elapses.
168 ///
169 /// Upgraded connections, such as WebSocket connections, never linger: once
170 /// a connection is upgraded, its I/O handler decides when to stop reading.
171 ///
172 /// [RFC 9112 §9.6]: https://www.rfc-editor.org/rfc/rfc9112#section-9.6
173 #[serde(default = "default_linger")]
174 pub linger: u32,
175 /// The secret key for signing and encrypting. **(default: `0`)**
176 ///
177 /// _**Note:** This field _always_ serializes as a 256-bit array of `0`s to
178 /// aid in preventing leakage of the secret key._
179 #[cfg(feature = "secrets")]
180 #[cfg_attr(nightly, doc(cfg(feature = "secrets")))]
181 #[serde(serialize_with = "SecretKey::serialize_zero")]
182 pub secret_key: SecretKey,
183 /// Graceful shutdown configuration. **(default: [`ShutdownConfig::default()`])**
184 pub shutdown: ShutdownConfig,
185 /// Max level to log. **(default: _debug_ `info` / _release_ `error`)**
186 #[serde(with = "crate::trace::level")]
187 pub log_level: Option<Level>,
188 /// Format to use when logging. **(default: _debug_ `pretty` / _release_ `compact`)**
189 pub log_format: TraceFormat,
190 /// Whether to use colors and emoji when logging. **(default:
191 /// [`CliColors::Auto`])**
192 pub cli_colors: CliColors,
193 /// PRIVATE: This structure may grow (but never change otherwise) in a
194 /// non-breaking release. As such, constructing this structure should
195 /// _always_ be done using a public constructor or update syntax:
196 ///
197 /// ```rust
198 /// use rocket::Config;
199 ///
200 /// let config = Config {
201 /// keep_alive: 10,
202 /// ..Default::default()
203 /// };
204 /// ```
205 #[doc(hidden)]
206 #[serde(skip)]
207 pub __non_exhaustive: (),
208}
209
210impl Default for Config {
211 /// Returns the default configuration based on the Rust compilation profile.
212 /// This is [`Config::debug_default()`] in `debug` and
213 /// [`Config::release_default()`] in `release`.
214 ///
215 /// # Example
216 ///
217 /// ```rust
218 /// use rocket::Config;
219 ///
220 /// let config = Config::default();
221 /// ```
222 fn default() -> Config {
223 #[cfg(debug_assertions)] { Config::debug_default() }
224 #[cfg(not(debug_assertions))] { Config::release_default() }
225 }
226}
227
228impl Config {
229 /// Returns the default configuration for the `debug` profile, _irrespective
230 /// of the Rust compilation profile_ and `ROCKET_PROFILE`.
231 ///
232 /// This may differ from the configuration used by default,
233 /// [`Config::default()`], which is selected based on the Rust compilation
234 /// profile. See [defaults](#defaults) and [provider
235 /// details](#provider-details) for specifics.
236 ///
237 /// # Example
238 ///
239 /// ```rust
240 /// use rocket::Config;
241 ///
242 /// let config = Config::debug_default();
243 /// ```
244 pub fn debug_default() -> Config {
245 Config {
246 profile: Self::DEBUG_PROFILE,
247 workers: num_cpus::get(),
248 max_blocking: 512,
249 wake_interval: default_wake_interval(),
250 ident: Ident::default(),
251 ip_header: Some(Uncased::from_borrowed("X-Real-IP")),
252 proxy_proto_header: None,
253 limits: Limits::default(),
254 temp_dir: std::env::temp_dir().into(),
255 keep_alive: 5,
256 linger: default_linger(),
257 #[cfg(feature = "secrets")]
258 secret_key: SecretKey::zero(),
259 shutdown: ShutdownConfig::default(),
260 log_level: Some(Level::INFO),
261 log_format: TraceFormat::Pretty,
262 cli_colors: CliColors::Auto,
263 __non_exhaustive: (),
264 }
265 }
266
267 /// Returns the default configuration for the `release` profile,
268 /// _irrespective of the Rust compilation profile_ and `ROCKET_PROFILE`.
269 ///
270 /// This may differ from the configuration used by default,
271 /// [`Config::default()`], which is selected based on the Rust compilation
272 /// profile. See [defaults](#defaults) and [provider
273 /// details](#provider-details) for specifics.
274 ///
275 /// # Example
276 ///
277 /// ```rust
278 /// use rocket::Config;
279 ///
280 /// let config = Config::release_default();
281 /// ```
282 pub fn release_default() -> Config {
283 Config {
284 profile: Self::RELEASE_PROFILE,
285 log_level: Some(Level::ERROR),
286 log_format: TraceFormat::Compact,
287 ..Config::debug_default()
288 }
289 }
290
291 /// Returns the default provider figment used by [`rocket::build()`].
292 ///
293 /// The default figment reads from the following sources, in ascending
294 /// priority order:
295 ///
296 /// 1. [`Config::default()`] (see [defaults](#defaults))
297 /// 2. `Rocket.toml` _or_ filename in `ROCKET_CONFIG` environment variable
298 /// 3. `ROCKET_` prefixed environment variables
299 ///
300 /// The profile selected is the value set in the `ROCKET_PROFILE`
301 /// environment variable. If it is not set, it defaults to `debug` when
302 /// compiled in debug mode and `release` when compiled in release mode.
303 ///
304 /// [`rocket::build()`]: crate::build()
305 ///
306 /// # Example
307 ///
308 /// ```rust
309 /// use rocket::Config;
310 /// use serde::Deserialize;
311 ///
312 /// #[derive(Deserialize)]
313 /// struct MyConfig {
314 /// app_key: String,
315 /// }
316 ///
317 /// let my_config = Config::figment().extract::<MyConfig>();
318 /// ```
319 pub fn figment() -> Figment {
320 Figment::from(Config::default())
321 .merge(Toml::file(Env::var_or("ROCKET_CONFIG", "Rocket.toml")).nested())
322 .merge(Env::prefixed("ROCKET_").ignore(&["PROFILE"]).global())
323 .select(Profile::from_env_or("ROCKET_PROFILE", Self::DEFAULT_PROFILE))
324 }
325
326 /// Attempts to extract a `Config` from `provider`, returning the result.
327 ///
328 /// # Example
329 ///
330 /// ```rust
331 /// use rocket::Config;
332 /// use rocket::figment::providers::{Toml, Format, Env};
333 ///
334 /// // Use Rocket's default `Figment`, but allow values from `MyApp.toml`
335 /// // and `MY_APP_` prefixed environment variables to supersede its values.
336 /// let figment = Config::figment()
337 /// .merge(("some-thing", 123))
338 /// .merge(Env::prefixed("CONFIG_"));
339 ///
340 /// let config = Config::try_from(figment);
341 /// ```
342 pub fn try_from<T: Provider>(provider: T) -> Result<Self> {
343 let figment = Figment::from(provider);
344 let mut config = figment.extract::<Self>()?;
345 config.profile = figment.profile().clone();
346 Ok(config)
347 }
348
349 /// Extract a `Config` from `provider`, panicking if extraction fails.
350 ///
351 /// # Panics
352 ///
353 /// If extraction fails, logs an error message indicating the error and
354 /// panics. For a version that doesn't panic, use [`Config::try_from()`].
355 ///
356 /// # Example
357 ///
358 /// ```rust
359 /// use rocket::Config;
360 /// use rocket::figment::providers::{Toml, Format, Env};
361 ///
362 /// // Use Rocket's default `Figment`, but allow values from `MyApp.toml`
363 /// // and `MY_APP_` prefixed environment variables to supersede its values.
364 /// let figment = Config::figment()
365 /// .merge(Toml::file("MyApp.toml").nested())
366 /// .merge(Env::prefixed("MY_APP_"));
367 ///
368 /// let config = Config::from(figment);
369 /// ```
370 pub fn from<T: Provider>(provider: T) -> Self {
371 use crate::trace::Trace;
372
373 Self::try_from(provider).unwrap_or_else(|e| {
374 e.trace_error();
375 panic!("aborting due to configuration error(s)")
376 })
377 }
378}
379
380/// Associated constants for default profiles.
381impl Config {
382 /// The default debug profile: `debug`.
383 pub const DEBUG_PROFILE: Profile = Profile::const_new("debug");
384
385 /// The default release profile: `release`.
386 pub const RELEASE_PROFILE: Profile = Profile::const_new("release");
387
388 /// The default profile: "debug" on `debug`, "release" on `release`.
389 #[cfg(debug_assertions)]
390 pub const DEFAULT_PROFILE: Profile = Self::DEBUG_PROFILE;
391
392 /// The default profile: "debug" on `debug`, "release" on `release`.
393 #[cfg(not(debug_assertions))]
394 pub const DEFAULT_PROFILE: Profile = Self::RELEASE_PROFILE;
395}
396
397/// Associated constants for stringy versions of configuration parameters.
398impl Config {
399 /// The stringy parameter name for setting/extracting [`Config::workers`].
400 pub const WORKERS: &'static str = "workers";
401
402 /// The stringy parameter name for setting/extracting [`Config::max_blocking`].
403 pub const MAX_BLOCKING: &'static str = "max_blocking";
404
405 /// The stringy parameter name for setting/extracting [`Config::wake_interval`].
406 pub const WAKE_INTERVAL: &'static str = "wake_interval";
407
408 /// The stringy parameter name for setting/extracting [`Config::keep_alive`].
409 pub const KEEP_ALIVE: &'static str = "keep_alive";
410
411 /// The stringy parameter name for setting/extracting [`Config::linger`].
412 pub const LINGER: &'static str = "linger";
413
414 /// The stringy parameter name for setting/extracting [`Config::ident`].
415 pub const IDENT: &'static str = "ident";
416
417 /// The stringy parameter name for setting/extracting [`Config::ip_header`].
418 pub const IP_HEADER: &'static str = "ip_header";
419
420 /// The stringy parameter name for setting/extracting [`Config::proxy_proto_header`].
421 pub const PROXY_PROTO_HEADER: &'static str = "proxy_proto_header";
422
423 /// The stringy parameter name for setting/extracting [`Config::limits`].
424 pub const LIMITS: &'static str = "limits";
425
426 /// The stringy parameter name for setting/extracting [`Config::secret_key`].
427 pub const SECRET_KEY: &'static str = "secret_key";
428
429 /// The stringy parameter name for setting/extracting [`Config::temp_dir`].
430 pub const TEMP_DIR: &'static str = "temp_dir";
431
432 /// The stringy parameter name for setting/extracting [`Config::log_level`].
433 pub const LOG_LEVEL: &'static str = "log_level";
434
435 /// The stringy parameter name for setting/extracting [`Config::log_format`].
436 pub const LOG_FORMAT: &'static str = "log_format";
437
438 /// The stringy parameter name for setting/extracting [`Config::shutdown`].
439 pub const SHUTDOWN: &'static str = "shutdown";
440
441 /// The stringy parameter name for setting/extracting [`Config::cli_colors`].
442 pub const CLI_COLORS: &'static str = "cli_colors";
443
444 /// An array of all of the stringy parameter names.
445 pub const PARAMETERS: &'static [&'static str] = &[
446 Self::WORKERS, Self::MAX_BLOCKING, Self::WAKE_INTERVAL, Self::KEEP_ALIVE, Self::LINGER,
447 Self::IDENT, Self::IP_HEADER, Self::PROXY_PROTO_HEADER, Self::LIMITS,
448 Self::SECRET_KEY, Self::TEMP_DIR, Self::LOG_LEVEL, Self::LOG_FORMAT,
449 Self::SHUTDOWN, Self::CLI_COLORS,
450 ];
451
452 /// The stringy parameter name for setting/extracting [`Config::profile`].
453 ///
454 /// This isn't `pub` because setting it directly does nothing.
455 const PROFILE: &'static str = "profile";
456
457 /// An array of deprecated stringy parameter names.
458 pub(crate) const DEPRECATED_KEYS: &'static [(&'static str, Option<&'static str>)] = &[
459 ("env", Some(Self::PROFILE)), ("log", Some(Self::LOG_LEVEL)),
460 ("read_timeout", None), ("write_timeout", None),
461 ];
462
463 /// Secret keys that have been used in docs or leaked otherwise.
464 #[cfg(feature = "secrets")]
465 pub(crate) const KNOWN_SECRET_KEYS: &'static [&'static str] = &[
466 "hPRYyVRiMyxpw5sBB1XeCMN1kFsDCqKvBi2QJxBVHQk="
467 ];
468}
469
470fn default_wake_interval() -> u32 {
471 250
472}
473
474fn default_linger() -> u32 {
475 10
476}
477
478impl Provider for Config {
479 #[track_caller]
480 fn metadata(&self) -> Metadata {
481 if self == &Config::default() {
482 Metadata::named("rocket::Config::default()")
483 } else {
484 Metadata::named("rocket::Config")
485 }
486 }
487
488 #[track_caller]
489 fn data(&self) -> Result<Map<Profile, Dict>> {
490 #[allow(unused_mut)]
491 let mut map: Map<Profile, Dict> = Serialized::defaults(self).data()?;
492
493 // We need to special-case `secret_key` since its serializer zeroes.
494 #[cfg(feature = "secrets")]
495 if !self.secret_key.is_zero() {
496 if let Some(map) = map.get_mut(&Profile::Default) {
497 map.insert("secret_key".into(), self.secret_key.key.master().into());
498 }
499 }
500
501 Ok(map)
502 }
503
504 fn profile(&self) -> Option<Profile> {
505 Some(self.profile.clone())
506 }
507}
508
509#[crate::async_trait]
510impl<'r> FromRequest<'r> for &'r Config {
511 type Error = std::convert::Infallible;
512
513 async fn from_request(req: &'r Request<'_>) -> request::Outcome<Self, Self::Error> {
514 request::Outcome::Success(req.rocket().config())
515 }
516}