From cb0f3acacad3aa2b3ba3082367cde22642e71dd6 Mon Sep 17 00:00:00 2001 From: Vincent Breitmoser Date: Sat, 22 Jun 2019 23:12:14 +0200 Subject: [PATCH] web: add RequestOrigin request guard --- Rocket.toml.dist | 1 + src/web/mod.rs | 37 ++++++++++++++++++++++++++++++++++++- 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/Rocket.toml.dist b/Rocket.toml.dist index e4fff3c..f9b364f 100644 --- a/Rocket.toml.dist +++ b/Rocket.toml.dist @@ -34,6 +34,7 @@ maintenance_file = "maintenance" [production] base-URI = "https://keys.openpgp.org" +base-URI-Onion = "https://keys.openpgp.org" from = "keys.openpgp.org " x-accel-redirect = true token_secret = "generated production secret" diff --git a/src/web/mod.rs b/src/web/mod.rs index 46fc778..9db3387 100644 --- a/src/web/mod.rs +++ b/src/web/mod.rs @@ -1,5 +1,7 @@ use rocket; use rocket::http::Header; +use rocket::request; +use rocket::outcome::Outcome; use rocket::response::NamedFile; use rocket::config::Config; use rocket_contrib::templates::Template; @@ -198,12 +200,41 @@ pub struct HagridState { /// XXX base_uri: String, + base_uri_onion: String, /// x_accel_redirect: bool, x_accel_prefix: Option, } +#[derive(Debug)] +enum RequestOrigin { + Direct(String), + OnionService(String), +} + +impl<'a, 'r> request::FromRequest<'a, 'r> for RequestOrigin { + type Error = (); + + fn from_request(request: &'a request::Request<'r>) -> request::Outcome { + let hagrid_state = request.guard::>().unwrap(); + let result = match request.headers().get("x-is-tor").next() { + Some(_) => RequestOrigin::OnionService(hagrid_state.base_uri_onion.clone()), + None => RequestOrigin::Direct(hagrid_state.base_uri.clone()), + }; + Outcome::Success(result) + } +} + +impl RequestOrigin { + fn get_base_uri(&self) -> &str { + match self { + RequestOrigin::Direct(uri) => uri.as_str(), + RequestOrigin::OnionService(uri) => uri.as_str(), + } + } +} + pub fn key_to_response_plain( state: rocket::State, db: rocket::State, @@ -359,10 +390,14 @@ fn configure_hagrid_state(config: &Config) -> Result { // State let base_uri = config.get_str("base-URI")?.to_string(); + let base_uri_onion = config.get_str("base-URI-Onion") + .map(|c| c.to_string()) + .unwrap_or(base_uri.clone()); Ok(HagridState { assets_dir, keys_external_dir: keys_external_dir, - base_uri: base_uri.clone(), + base_uri, + base_uri_onion, x_accel_redirect: config.get_bool("x-accel-redirect")?, x_accel_prefix, })