web.rs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. use std::path::{Path, PathBuf};
  2. use rocket::{
  3. fs::NamedFile,
  4. http::ContentType,
  5. response::{content::RawCss as Css, content::RawHtml as Html, Redirect},
  6. serde::json::Json,
  7. Catcher, Route,
  8. };
  9. use serde_json::Value;
  10. use crate::{
  11. api::{core::now, ApiResult, EmptyResult},
  12. auth::decode_file_download,
  13. db::models::{AttachmentId, CipherId},
  14. error::Error,
  15. util::Cached,
  16. CONFIG,
  17. };
  18. pub fn routes() -> Vec<Route> {
  19. // If adding more routes here, consider also adding them to
  20. // crate::utils::LOGGED_ROUTES to make sure they appear in the log
  21. let mut routes = routes![attachments, alive, alive_head, static_files];
  22. if CONFIG.web_vault_enabled() {
  23. routes.append(&mut routes![web_index, web_index_direct, web_index_head, app_id, web_files, vaultwarden_css]);
  24. }
  25. #[cfg(debug_assertions)]
  26. if CONFIG.reload_templates() {
  27. routes.append(&mut routes![_static_files_dev]);
  28. }
  29. routes
  30. }
  31. pub fn catchers() -> Vec<Catcher> {
  32. if CONFIG.web_vault_enabled() {
  33. catchers![not_found]
  34. } else {
  35. catchers![]
  36. }
  37. }
  38. #[catch(404)]
  39. fn not_found() -> ApiResult<Html<String>> {
  40. // Return the page
  41. let json = json!({
  42. "urlpath": CONFIG.domain_path()
  43. });
  44. let text = CONFIG.render_template("404", &json)?;
  45. Ok(Html(text))
  46. }
  47. #[get("/css/vaultwarden.css")]
  48. fn vaultwarden_css() -> Cached<Css<String>> {
  49. let css_options = json!({
  50. "emergency_access_allowed": CONFIG.emergency_access_allowed(),
  51. "load_user_scss": true,
  52. "mail_2fa_enabled": CONFIG._enable_email_2fa(),
  53. "mail_enabled": CONFIG.mail_enabled(),
  54. "sends_allowed": CONFIG.sends_allowed(),
  55. "signup_disabled": CONFIG.is_signup_disabled(),
  56. "sso_disabled": !CONFIG.sso_enabled(),
  57. "sso_only": CONFIG.sso_enabled() && CONFIG.sso_only(),
  58. "yubico_enabled": CONFIG._enable_yubico() && CONFIG.yubico_client_id().is_some() && CONFIG.yubico_secret_key().is_some(),
  59. });
  60. let scss = match CONFIG.render_template("scss/vaultwarden.scss", &css_options) {
  61. Ok(t) => t,
  62. Err(e) => {
  63. // Something went wrong loading the template. Use the fallback
  64. warn!("Loading scss/vaultwarden.scss.hbs or scss/user.vaultwarden.scss.hbs failed. {e}");
  65. CONFIG
  66. .render_fallback_template("scss/vaultwarden.scss", &css_options)
  67. .expect("Fallback scss/vaultwarden.scss.hbs to render")
  68. }
  69. };
  70. let css = match grass_compiler::from_string(
  71. scss,
  72. &grass_compiler::Options::default().style(grass_compiler::OutputStyle::Compressed),
  73. ) {
  74. Ok(css) => css,
  75. Err(e) => {
  76. // Something went wrong compiling the scss. Use the fallback
  77. warn!("Compiling the Vaultwarden SCSS styles failed. {e}");
  78. let mut css_options = css_options;
  79. css_options["load_user_scss"] = json!(false);
  80. let scss = CONFIG
  81. .render_fallback_template("scss/vaultwarden.scss", &css_options)
  82. .expect("Fallback scss/vaultwarden.scss.hbs to render");
  83. grass_compiler::from_string(
  84. scss,
  85. &grass_compiler::Options::default().style(grass_compiler::OutputStyle::Compressed),
  86. )
  87. .expect("SCSS to compile")
  88. }
  89. };
  90. // Cache for one day should be enough and not too much
  91. Cached::ttl(Css(css), 86_400, false)
  92. }
  93. #[get("/")]
  94. async fn web_index() -> Cached<Option<NamedFile>> {
  95. Cached::short(NamedFile::open(Path::new(&CONFIG.web_vault_folder()).join("index.html")).await.ok(), false)
  96. }
  97. // Make sure that `/index.html` redirect to actual domain path.
  98. // If not, this might cause issues with the web-vault
  99. #[get("/index.html")]
  100. fn web_index_direct() -> Redirect {
  101. Redirect::to(format!("{}/", CONFIG.domain_path()))
  102. }
  103. #[head("/")]
  104. fn web_index_head() -> EmptyResult {
  105. // Add an explicit HEAD route to prevent uptime monitoring services from
  106. // generating "No matching routes for HEAD /" error messages.
  107. //
  108. // Rocket automatically implements a HEAD route when there's a matching GET
  109. // route, but relying on this behavior also means a spurious error gets
  110. // logged due to <https://github.com/SergioBenitez/Rocket/issues/1098>.
  111. Ok(())
  112. }
  113. #[get("/app-id.json")]
  114. fn app_id() -> Cached<(ContentType, Json<Value>)> {
  115. let content_type = ContentType::new("application", "fido.trusted-apps+json");
  116. Cached::long(
  117. (
  118. content_type,
  119. Json(json!({
  120. "trustedFacets": [
  121. {
  122. "version": { "major": 1, "minor": 0 },
  123. "ids": [
  124. // Per <https://fidoalliance.org/specs/fido-v2.0-id-20180227/fido-appid-and-facets-v2.0-id-20180227.html#determining-the-facetid-of-a-calling-application>:
  125. //
  126. // "In the Web case, the FacetID MUST be the Web Origin [RFC6454]
  127. // of the web page triggering the FIDO operation, written as
  128. // a URI with an empty path. Default ports are omitted and any
  129. // path component is ignored."
  130. //
  131. // This leaves it unclear as to whether the path must be empty,
  132. // or whether it can be non-empty and will be ignored. To be on
  133. // the safe side, use a proper web origin (with empty path).
  134. &CONFIG.domain_origin(),
  135. "ios:bundle-id:com.8bit.bitwarden",
  136. "android:apk-key-hash:dUGFzUzf3lmHSLBDBIv+WaFyZMI" ]
  137. }]
  138. })),
  139. ),
  140. true,
  141. )
  142. }
  143. #[get("/<p..>", rank = 10)] // Only match this if the other routes don't match
  144. async fn web_files(p: PathBuf) -> Cached<Option<NamedFile>> {
  145. Cached::long(NamedFile::open(Path::new(&CONFIG.web_vault_folder()).join(p)).await.ok(), true)
  146. }
  147. #[get("/attachments/<cipher_id>/<file_id>?<token>")]
  148. async fn attachments(cipher_id: CipherId, file_id: AttachmentId, token: String) -> Option<NamedFile> {
  149. let Ok(claims) = decode_file_download(&token) else {
  150. return None;
  151. };
  152. if claims.sub != cipher_id || claims.file_id != file_id {
  153. return None;
  154. }
  155. NamedFile::open(Path::new(&CONFIG.attachments_folder()).join(cipher_id.as_ref()).join(file_id.as_ref())).await.ok()
  156. }
  157. // We use DbConn here to let the alive healthcheck also verify the database connection.
  158. use crate::db::DbConn;
  159. #[get("/alive")]
  160. fn alive(_conn: DbConn) -> Json<String> {
  161. now()
  162. }
  163. #[head("/alive")]
  164. fn alive_head(_conn: DbConn) -> EmptyResult {
  165. // Avoid logging spurious "No matching routes for HEAD /alive" errors
  166. // due to <https://github.com/SergioBenitez/Rocket/issues/1098>.
  167. Ok(())
  168. }
  169. // This endpoint/function is used during development and development only.
  170. // It allows to easily develop the admin interface by always loading the files from disk instead from a slice of bytes
  171. // This will only be active during a debug build and only when `RELOAD_TEMPLATES` is set to `true`
  172. // NOTE: Do not forget to add any new files added to the `static_files` function below!
  173. #[cfg(debug_assertions)]
  174. #[get("/vw_static/<filename>", rank = 1)]
  175. pub async fn _static_files_dev(filename: PathBuf) -> Option<NamedFile> {
  176. warn!("LOADING STATIC FILES FROM DISK");
  177. let file = filename.to_str().unwrap_or_default();
  178. let ext = filename.extension().unwrap_or_default();
  179. let path = if ext == "png" || ext == "svg" {
  180. tokio::fs::canonicalize(Path::new(file!()).parent().unwrap().join("../static/images/").join(file)).await
  181. } else {
  182. tokio::fs::canonicalize(Path::new(file!()).parent().unwrap().join("../static/scripts/").join(file)).await
  183. };
  184. if let Ok(path) = path {
  185. return NamedFile::open(path).await.ok();
  186. };
  187. None
  188. }
  189. #[get("/vw_static/<filename>", rank = 2)]
  190. pub fn static_files(filename: &str) -> Result<(ContentType, &'static [u8]), Error> {
  191. match filename {
  192. "404.png" => Ok((ContentType::PNG, include_bytes!("../static/images/404.png"))),
  193. "mail-github.png" => Ok((ContentType::PNG, include_bytes!("../static/images/mail-github.png"))),
  194. "logo-gray.png" => Ok((ContentType::PNG, include_bytes!("../static/images/logo-gray.png"))),
  195. "error-x.svg" => Ok((ContentType::SVG, include_bytes!("../static/images/error-x.svg"))),
  196. "hibp.png" => Ok((ContentType::PNG, include_bytes!("../static/images/hibp.png"))),
  197. "vaultwarden-icon.png" => Ok((ContentType::PNG, include_bytes!("../static/images/vaultwarden-icon.png"))),
  198. "vaultwarden-favicon.png" => Ok((ContentType::PNG, include_bytes!("../static/images/vaultwarden-favicon.png"))),
  199. "404.css" => Ok((ContentType::CSS, include_bytes!("../static/scripts/404.css"))),
  200. "admin.css" => Ok((ContentType::CSS, include_bytes!("../static/scripts/admin.css"))),
  201. "admin.js" => Ok((ContentType::JavaScript, include_bytes!("../static/scripts/admin.js"))),
  202. "admin_settings.js" => Ok((ContentType::JavaScript, include_bytes!("../static/scripts/admin_settings.js"))),
  203. "admin_users.js" => Ok((ContentType::JavaScript, include_bytes!("../static/scripts/admin_users.js"))),
  204. "admin_organizations.js" => {
  205. Ok((ContentType::JavaScript, include_bytes!("../static/scripts/admin_organizations.js")))
  206. }
  207. "admin_diagnostics.js" => {
  208. Ok((ContentType::JavaScript, include_bytes!("../static/scripts/admin_diagnostics.js")))
  209. }
  210. "bootstrap.css" => Ok((ContentType::CSS, include_bytes!("../static/scripts/bootstrap.css"))),
  211. "bootstrap.bundle.js" => Ok((ContentType::JavaScript, include_bytes!("../static/scripts/bootstrap.bundle.js"))),
  212. "jdenticon-3.3.0.js" => Ok((ContentType::JavaScript, include_bytes!("../static/scripts/jdenticon-3.3.0.js"))),
  213. "datatables.js" => Ok((ContentType::JavaScript, include_bytes!("../static/scripts/datatables.js"))),
  214. "datatables.css" => Ok((ContentType::CSS, include_bytes!("../static/scripts/datatables.css"))),
  215. "jquery-3.7.1.slim.js" => {
  216. Ok((ContentType::JavaScript, include_bytes!("../static/scripts/jquery-3.7.1.slim.js")))
  217. }
  218. _ => err!(format!("Static file not found: {filename}")),
  219. }
  220. }