Rename 'session_key' config parameter to 'secret_key'.

Resolves #220.
This commit is contained in:
Anton Pirker 2017-03-30 22:44:51 +02:00 committed by Sergio Benitez
parent 5e345e99d0
commit 781477fff1
8 changed files with 65 additions and 65 deletions

View File

@ -216,7 +216,7 @@ In addition to new features, Rocket saw the following smaller improvements:
* Clippy issues injected by codegen are resolved. * Clippy issues injected by codegen are resolved.
* Handlebars was updated to `0.25`. * Handlebars was updated to `0.25`.
* The `PartialEq` implementation of `Config` doesn't consider the path or * The `PartialEq` implementation of `Config` doesn't consider the path or
session key. secret key.
* Hyper dependency updated to `0.10`. * Hyper dependency updated to `0.10`.
* The `Error` type for `JSON as FromData` has been exposed as `SerdeError`. * The `Error` type for `JSON as FromData` has been exposed as `SerdeError`.
* SVG was added as a known Content-Type. * SVG was added as a known Content-Type.

View File

@ -1,4 +1,4 @@
# Except for the session key, nothing here is necessary; Rocket has sane # Except for the secret key, none of these are actually needed; Rocket has sane
# defaults. We show all of them here explicitly for demonstrative purposes. # defaults. We show all of them here explicitly for demonstrative purposes.
[global.limits] [global.limits]
@ -20,7 +20,7 @@ port = 80
log = "normal" log = "normal"
workers = 8 workers = 8
# don't use this key! generate your own and keep it private! # don't use this key! generate your own and keep it private!
session_key = "8Xui8SN4mI+7egV/9dlfYYLGQJeEx4+DwmSQLwDVXJg=" secret_key = "8Xui8SN4mI+7egV/9dlfYYLGQJeEx4+DwmSQLwDVXJg="
[production] [production]
address = "0.0.0.0" address = "0.0.0.0"
@ -28,4 +28,4 @@ port = 80
workers = 12 workers = 12
log = "critical" log = "critical"
# don't use this key! generate your own and keep it private! # don't use this key! generate your own and keep it private!
session_key = "hPRYyVRiMyxpw5sBB1XeCMN1kFsDCqKvBi2QJxBVHQk=" secret_key = "hPRYyVRiMyxpw5sBB1XeCMN1kFsDCqKvBi2QJxBVHQk="

View File

@ -1,7 +1,7 @@
[staging] [staging]
session_key = "itlYmFR2vYKrOmFhupMIn/hyB6lYCCTXz4yaQX89XVg=" secret_key = "itlYmFR2vYKrOmFhupMIn/hyB6lYCCTXz4yaQX89XVg="
address = "localhost" address = "localhost"
port = 8000 port = 8000
[production] [production]
session_key = "itlYmFR2vYKrOmFhupMIn/hyB6lYCCTXz4yaQX89XVg=" secret_key = "itlYmFR2vYKrOmFhupMIn/hyB6lYCCTXz4yaQX89XVg="

View File

@ -18,8 +18,8 @@ pub struct ConfigBuilder {
pub workers: u16, pub workers: u16,
/// How much information to log. /// How much information to log.
pub log_level: LoggingLevel, pub log_level: LoggingLevel,
/// The session key. /// The secret key.
pub session_key: Option<String>, pub secret_key: Option<String>,
/// TLS configuration (path to certificates file, path to private key file). /// TLS configuration (path to certificates file, path to private key file).
pub tls: Option<(String, String)>, pub tls: Option<(String, String)>,
/// Size limits. /// Size limits.
@ -66,7 +66,7 @@ impl ConfigBuilder {
port: config.port, port: config.port,
workers: config.workers, workers: config.workers,
log_level: config.log_level, log_level: config.log_level,
session_key: None, secret_key: None,
tls: None, tls: None,
limits: config.limits, limits: config.limits,
extras: config.extras, extras: config.extras,
@ -150,7 +150,7 @@ impl ConfigBuilder {
self self
} }
/// Sets the `session_key` in the configuration being built. /// Sets the `secret_key` in the configuration being built.
/// ///
/// # Example /// # Example
/// ///
@ -160,11 +160,11 @@ impl ConfigBuilder {
/// ///
/// let key = "8Xui8SN4mI+7egV/9dlfYYLGQJeEx4+DwmSQLwDVXJg="; /// let key = "8Xui8SN4mI+7egV/9dlfYYLGQJeEx4+DwmSQLwDVXJg=";
/// let mut config = Config::build(Environment::Staging) /// let mut config = Config::build(Environment::Staging)
/// .session_key(key) /// .secret_key(key)
/// .unwrap(); /// .unwrap();
/// ``` /// ```
pub fn session_key<K: Into<String>>(mut self, key: K) -> Self { pub fn secret_key<K: Into<String>>(mut self, key: K) -> Self {
self.session_key = Some(key.into()); self.secret_key = Some(key.into());
self self
} }
@ -271,7 +271,7 @@ impl ConfigBuilder {
/// # Errors /// # Errors
/// ///
/// If the current working directory cannot be retrieved, returns a `BadCWD` /// If the current working directory cannot be retrieved, returns a `BadCWD`
/// error. If the address or session key fail to parse, returns a `BadType` /// error. If the address or secret key fail to parse, returns a `BadType`
/// error. /// error.
/// ///
/// # Example /// # Example
@ -307,8 +307,8 @@ impl ConfigBuilder {
config.set_tls(&certs_path, &key_path)?; config.set_tls(&certs_path, &key_path)?;
} }
if let Some(key) = self.session_key { if let Some(key) = self.secret_key {
config.set_session_key(key)?; config.set_secret_key(key)?;
} }
Ok(config) Ok(config)
@ -319,7 +319,7 @@ impl ConfigBuilder {
/// # Panics /// # Panics
/// ///
/// Panics if the current working directory cannot be retrieved or if the /// Panics if the current working directory cannot be retrieved or if the
/// supplied address or session key fail to parse. /// supplied address or secret key fail to parse.
/// ///
/// # Example /// # Example
/// ///

View File

@ -40,8 +40,8 @@ pub struct Config {
pub workers: u16, pub workers: u16,
/// How much information to log. /// How much information to log.
pub log_level: LoggingLevel, pub log_level: LoggingLevel,
/// The session key. /// The secret key.
pub(crate) session_key: SessionKey, pub(crate) secret_key: SecretKey,
/// TLS configuration. /// TLS configuration.
pub(crate) tls: Option<TlsConfig>, pub(crate) tls: Option<TlsConfig>,
/// Streaming read size limits. /// Streaming read size limits.
@ -131,8 +131,8 @@ impl Config {
// Note: This may truncate if num_cpus::get() > u16::max. That's okay. // Note: This may truncate if num_cpus::get() > u16::max. That's okay.
let default_workers = ::std::cmp::max(num_cpus::get(), 2) as u16; let default_workers = ::std::cmp::max(num_cpus::get(), 2) as u16;
// Use a generated session key by default. // Use a generated secret key by default.
let key = SessionKey::Generated(Key::generate()); let key = SecretKey::Generated(Key::generate());
Ok(match env { Ok(match env {
Development => { Development => {
@ -142,7 +142,7 @@ impl Config {
port: 8000, port: 8000,
workers: default_workers, workers: default_workers,
log_level: LoggingLevel::Normal, log_level: LoggingLevel::Normal,
session_key: key, secret_key: key,
tls: None, tls: None,
limits: Limits::default(), limits: Limits::default(),
extras: HashMap::new(), extras: HashMap::new(),
@ -156,7 +156,7 @@ impl Config {
port: 80, port: 80,
workers: default_workers, workers: default_workers,
log_level: LoggingLevel::Normal, log_level: LoggingLevel::Normal,
session_key: key, secret_key: key,
tls: None, tls: None,
limits: Limits::default(), limits: Limits::default(),
extras: HashMap::new(), extras: HashMap::new(),
@ -170,7 +170,7 @@ impl Config {
port: 80, port: 80,
workers: default_workers, workers: default_workers,
log_level: LoggingLevel::Critical, log_level: LoggingLevel::Critical,
session_key: key, secret_key: key,
tls: None, tls: None,
limits: Limits::default(), limits: Limits::default(),
extras: HashMap::new(), extras: HashMap::new(),
@ -192,7 +192,7 @@ impl Config {
} }
/// Sets the configuration `val` for the `name` entry. If the `name` is one /// Sets the configuration `val` for the `name` entry. If the `name` is one
/// of "address", "port", "session_key", "log", or "workers" (the "default" /// of "address", "port", "secret_key", "log", or "workers" (the "default"
/// values), the appropriate value in the `self` Config structure is set. /// values), the appropriate value in the `self` Config structure is set.
/// Otherwise, the value is stored as an `extra`. /// Otherwise, the value is stored as an `extra`.
/// ///
@ -204,7 +204,7 @@ impl Config {
/// * **port**: Integer (16-bit unsigned) /// * **port**: Integer (16-bit unsigned)
/// * **workers**: Integer (16-bit unsigned) /// * **workers**: Integer (16-bit unsigned)
/// * **log**: String /// * **log**: String
/// * **session_key**: String (192-bit base64) /// * **secret_key**: String (192-bit base64)
/// * **tls**: Table (`certs` (path as String), `key` (path as String)) /// * **tls**: Table (`certs` (path as String), `key` (path as String))
pub(crate) fn set_raw(&mut self, name: &str, val: &Value) -> Result<()> { pub(crate) fn set_raw(&mut self, name: &str, val: &Value) -> Result<()> {
let (id, ok) = (|val| val, |_| Ok(())); let (id, ok) = (|val| val, |_| Ok(()));
@ -212,7 +212,7 @@ impl Config {
address => (str, set_address, id), address => (str, set_address, id),
port => (u16, set_port, ok), port => (u16, set_port, ok),
workers => (u16, set_workers, ok), workers => (u16, set_workers, ok),
session_key => (str, set_session_key, id), secret_key => (str, set_secret_key, id),
log => (log_level, set_log_level, ok), log => (log_level, set_log_level, ok),
tls => (tls_config, set_raw_tls, id), tls => (tls_config, set_raw_tls, id),
limits => (limits, set_limits, ok) limits => (limits, set_limits, ok)
@ -313,7 +313,7 @@ impl Config {
self.workers = workers; self.workers = workers;
} }
/// Sets the `session_key` in `self` to `key` which must be a 192-bit base64 /// Sets the `secret_key` in `self` to `key` which must be a 192-bit base64
/// encoded string. /// encoded string.
/// ///
/// # Errors /// # Errors
@ -330,14 +330,14 @@ impl Config {
/// # fn config_test() -> Result<(), ConfigError> { /// # fn config_test() -> Result<(), ConfigError> {
/// let mut config = Config::new(Environment::Staging)?; /// let mut config = Config::new(Environment::Staging)?;
/// let key = "8Xui8SN4mI+7egV/9dlfYYLGQJeEx4+DwmSQLwDVXJg="; /// let key = "8Xui8SN4mI+7egV/9dlfYYLGQJeEx4+DwmSQLwDVXJg=";
/// assert!(config.set_session_key(key).is_ok()); /// assert!(config.set_secret_key(key).is_ok());
/// assert!(config.set_session_key("hello? anyone there?").is_err()); /// assert!(config.set_secret_key("hello? anyone there?").is_err());
/// # Ok(()) /// # Ok(())
/// # } /// # }
/// ``` /// ```
pub fn set_session_key<K: Into<String>>(&mut self, key: K) -> Result<()> { pub fn set_secret_key<K: Into<String>>(&mut self, key: K) -> Result<()> {
let key = key.into(); let key = key.into();
let error = self.bad_type("session_key", "string", let error = self.bad_type("secret_key", "string",
"a 256-bit base64 encoded string"); "a 256-bit base64 encoded string");
if key.len() != 44 { if key.len() != 44 {
@ -349,7 +349,7 @@ impl Config {
Err(_) => return Err(error) Err(_) => return Err(error)
}; };
self.session_key = SessionKey::Provided(Key::from_master(&bytes)); self.secret_key = SecretKey::Provided(Key::from_master(&bytes));
Ok(()) Ok(())
} }
@ -478,10 +478,10 @@ impl Config {
self.extras.iter().map(|(k, v)| (k.as_str(), v)) self.extras.iter().map(|(k, v)| (k.as_str(), v))
} }
/// Retrieves the session key from `self`. /// Retrieves the secret key from `self`.
#[inline] #[inline]
pub(crate) fn session_key(&self) -> &Key { pub(crate) fn secret_key(&self) -> &Key {
self.session_key.inner() self.secret_key.inner()
} }
/// Attempts to retrieve the extra named `name` as a string. /// Attempts to retrieve the extra named `name` as a string.
@ -668,7 +668,7 @@ impl fmt::Debug for Config {
} }
} }
/// Doesn't consider the session key or config path. /// Doesn't consider the secret key or config path.
impl PartialEq for Config { impl PartialEq for Config {
fn eq(&self, other: &Config) -> bool { fn eq(&self, other: &Config) -> bool {
self.address == other.address self.address == other.address

View File

@ -7,24 +7,24 @@ use config::{Result, Config, Value, ConfigError};
use http::Key; use http::Key;
#[derive(Clone)] #[derive(Clone)]
pub enum SessionKey { pub enum SecretKey {
Generated(Key), Generated(Key),
Provided(Key) Provided(Key)
} }
impl SessionKey { impl SecretKey {
#[inline(always)] #[inline]
pub fn kind(&self) -> &'static str { pub fn kind(&self) -> &'static str {
match *self { match *self {
SessionKey::Generated(_) => "generated", SecretKey::Generated(_) => "generated",
SessionKey::Provided(_) => "provided", SecretKey::Provided(_) => "provided",
} }
} }
#[inline(always)] #[inline]
pub(crate) fn inner(&self) -> &Key { pub(crate) fn inner(&self) -> &Key {
match *self { match *self {
SessionKey::Generated(ref key) | SessionKey::Provided(ref key) => key SecretKey::Generated(ref key) | SecretKey::Provided(ref key) => key
} }
} }
} }

View File

@ -40,8 +40,8 @@
//! * examples: `12`, `1`, `4` //! * examples: `12`, `1`, `4`
//! * **log**: _[string]_ how much information to log; one of `"normal"`, //! * **log**: _[string]_ how much information to log; one of `"normal"`,
//! `"debug"`, or `"critical"` //! `"debug"`, or `"critical"`
//! * **session_key**: _[string]_ a 256-bit base64 encoded string (44 //! * **secret_key**: _[string]_ a 256-bit base64 encoded string (44
//! characters) to use as the session key //! characters) to use as the secret key
//! * example: `"8Xui8SN4mI+7egV/9dlfYYLGQJeEx4+DwmSQLwDVXJg="` //! * example: `"8Xui8SN4mI+7egV/9dlfYYLGQJeEx4+DwmSQLwDVXJg="`
//! * **tls**: _[table]_ a table with two keys: 1) `certs`: _[string]_ a path //! * **tls**: _[table]_ a table with two keys: 1) `certs`: _[string]_ a path
//! to a certificate chain in PEM format, and 2) `key`: _[string]_ a path to a //! to a certificate chain in PEM format, and 2) `key`: _[string]_ a path to a
@ -71,7 +71,7 @@
//! port = 8000 //! port = 8000
//! workers = max(number_of_cpus, 2) //! workers = max(number_of_cpus, 2)
//! log = "normal" //! log = "normal"
//! session_key = [randomly generated at launch] //! secret_key = [randomly generated at launch]
//! limits = { forms = 32768 } //! limits = { forms = 32768 }
//! //!
//! [staging] //! [staging]
@ -79,7 +79,7 @@
//! port = 80 //! port = 80
//! workers = max(number_of_cpus, 2) //! workers = max(number_of_cpus, 2)
//! log = "normal" //! log = "normal"
//! session_key = [randomly generated at launch] //! secret_key = [randomly generated at launch]
//! limits = { forms = 32768 } //! limits = { forms = 32768 }
//! //!
//! [production] //! [production]
@ -87,14 +87,14 @@
//! port = 80 //! port = 80
//! workers = max(number_of_cpus, 2) //! workers = max(number_of_cpus, 2)
//! log = "critical" //! log = "critical"
//! session_key = [randomly generated at launch] //! secret_key = [randomly generated at launch]
//! limits = { forms = 32768 } //! limits = { forms = 32768 }
//! ``` //! ```
//! //!
//! The `workers` and `session_key` default parameters are computed by Rocket //! The `workers` and `secret_key` default parameters are computed by Rocket
//! automatically; the values above are not valid TOML syntax. When manually //! automatically; the values above are not valid TOML syntax. When manually
//! specifying the number of workers, the value should be an integer: `workers = //! specifying the number of workers, the value should be an integer: `workers =
//! 10`. When manually specifying the session key, the value should a 256-bit //! 10`. When manually specifying the secret key, the value should a 256-bit
//! base64 encoded string. Such a string can be generated with the `openssl` //! base64 encoded string. Such a string can be generated with the `openssl`
//! command line tool: `openssl rand -base64 32`. //! command line tool: `openssl rand -base64 32`.
//! //!
@ -634,7 +634,7 @@ mod test {
port = 7810 port = 7810
workers = 21 workers = 21
log = "critical" log = "critical"
session_key = "8Xui8SN4mI+7egV/9dlfYYLGQJeEx4+DwmSQLwDVXJg=" secret_key = "8Xui8SN4mI+7egV/9dlfYYLGQJeEx4+DwmSQLwDVXJg="
template_dir = "mine" template_dir = "mine"
json = true json = true
pi = 3.14 pi = 3.14
@ -645,7 +645,7 @@ mod test {
.port(7810) .port(7810)
.workers(21) .workers(21)
.log_level(LoggingLevel::Critical) .log_level(LoggingLevel::Critical)
.session_key("8Xui8SN4mI+7egV/9dlfYYLGQJeEx4+DwmSQLwDVXJg=") .secret_key("8Xui8SN4mI+7egV/9dlfYYLGQJeEx4+DwmSQLwDVXJg=")
.extra("template_dir", "mine") .extra("template_dir", "mine")
.extra("json", true) .extra("json", true)
.extra("pi", 3.14); .extra("pi", 3.14);
@ -971,49 +971,49 @@ mod test {
} }
#[test] #[test]
fn test_good_session_key() { fn test_good_secret_key() {
// Take the lock so changing the environment doesn't cause races. // Take the lock so changing the environment doesn't cause races.
let _env_lock = ENV_LOCK.lock().unwrap(); let _env_lock = ENV_LOCK.lock().unwrap();
env::set_var(CONFIG_ENV, "stage"); env::set_var(CONFIG_ENV, "stage");
check_config!(RocketConfig::parse(r#" check_config!(RocketConfig::parse(r#"
[stage] [stage]
session_key = "TpUiXK2d/v5DFxJnWL12suJKPExKR8h9zd/o+E7SU+0=" secret_key = "TpUiXK2d/v5DFxJnWL12suJKPExKR8h9zd/o+E7SU+0="
"#.to_string(), TEST_CONFIG_FILENAME), { "#.to_string(), TEST_CONFIG_FILENAME), {
default_config(Staging).session_key( default_config(Staging).secret_key(
"TpUiXK2d/v5DFxJnWL12suJKPExKR8h9zd/o+E7SU+0=" "TpUiXK2d/v5DFxJnWL12suJKPExKR8h9zd/o+E7SU+0="
) )
}); });
check_config!(RocketConfig::parse(r#" check_config!(RocketConfig::parse(r#"
[stage] [stage]
session_key = "jTyprDberFUiUFsJ3vcb1XKsYHWNBRvWAnXTlbTgGFU=" secret_key = "jTyprDberFUiUFsJ3vcb1XKsYHWNBRvWAnXTlbTgGFU="
"#.to_string(), TEST_CONFIG_FILENAME), { "#.to_string(), TEST_CONFIG_FILENAME), {
default_config(Staging).session_key( default_config(Staging).secret_key(
"jTyprDberFUiUFsJ3vcb1XKsYHWNBRvWAnXTlbTgGFU=" "jTyprDberFUiUFsJ3vcb1XKsYHWNBRvWAnXTlbTgGFU="
) )
}); });
} }
#[test] #[test]
fn test_bad_session_key() { fn test_bad_secret_key() {
// Take the lock so changing the environment doesn't cause races. // Take the lock so changing the environment doesn't cause races.
let _env_lock = ENV_LOCK.lock().unwrap(); let _env_lock = ENV_LOCK.lock().unwrap();
env::remove_var(CONFIG_ENV); env::remove_var(CONFIG_ENV);
assert!(RocketConfig::parse(r#" assert!(RocketConfig::parse(r#"
[dev] [dev]
session_key = true secret_key = true
"#.to_string(), TEST_CONFIG_FILENAME).is_err()); "#.to_string(), TEST_CONFIG_FILENAME).is_err());
assert!(RocketConfig::parse(r#" assert!(RocketConfig::parse(r#"
[dev] [dev]
session_key = 1283724897238945234897 secret_key = 1283724897238945234897
"#.to_string(), TEST_CONFIG_FILENAME).is_err()); "#.to_string(), TEST_CONFIG_FILENAME).is_err());
assert!(RocketConfig::parse(r#" assert!(RocketConfig::parse(r#"
[dev] [dev]
session_key = "abcv" secret_key = "abcv"
"#.to_string(), TEST_CONFIG_FILENAME).is_err()); "#.to_string(), TEST_CONFIG_FILENAME).is_err());
} }
@ -1034,7 +1034,7 @@ mod test {
assert!(RocketConfig::parse(r#" assert!(RocketConfig::parse(r#"
[dev] [dev]
session_key = "abcv" = other secret_key = "abcv" = other
"#.to_string(), TEST_CONFIG_FILENAME).is_err()); "#.to_string(), TEST_CONFIG_FILENAME).is_err());
} }

View File

@ -218,7 +218,7 @@ impl Rocket {
info!("{}:", request); info!("{}:", request);
// Inform the request about all of the precomputed state. // Inform the request about all of the precomputed state.
request.set_preset_state(&self.config.session_key(), &self.state); request.set_preset_state(&self.config.secret_key(), &self.state);
// Do a bit of preprocessing before routing; run the attached fairings. // Do a bit of preprocessing before routing; run the attached fairings.
self.preprocess_request(request, &data); self.preprocess_request(request, &data);
@ -393,7 +393,7 @@ impl Rocket {
info_!("port: {}", White.paint(&config.port)); info_!("port: {}", White.paint(&config.port));
info_!("log: {}", White.paint(config.log_level)); info_!("log: {}", White.paint(config.log_level));
info_!("workers: {}", White.paint(config.workers)); info_!("workers: {}", White.paint(config.workers));
info_!("session key: {}", White.paint(config.session_key.kind())); info_!("secret key: {}", White.paint(config.secret_key.kind()));
info_!("limits: {}", White.paint(&config.limits)); info_!("limits: {}", White.paint(&config.limits));
let tls_configured = config.tls.is_some(); let tls_configured = config.tls.is_some();