Browse Source

Cache CSS file in a different way

Currently we set a cache ttl of 24 hours, and users need to do a force refresh if there is anything changed to the CSS file.
In the past we have had several issue reported which were related to a still cached CSS file.

This commit will change the caching and also cache the generated CSS file in memory.
Instead of letting the browser cache it for 24 hours we generate an ETag, this is just a hash of the contents.
This ETag is returned by the browser during a request, and we can match this, and if so, just return a `304` `Not Modified`.
If the ETag is not known, we return the new content.

This should make simple refreshes by clients get updated settings or a new version of Vaultwarden which has other CSS entries get updated instantly.
If a user does a hard refresh, we will not receive the ETag and the content will be served.

The same goes if someone has the `reload_templates` feature enabled, since then we should not cache anyway.
If someone adjust settings via the `/admin` interface, the cache will be invalidated and a new CSS will be generated.

Signed-off-by: BlackDex <black.dex@gmail.com>
pull/7558/head
BlackDex 2 months ago
parent
commit
de72eb4489
No known key found for this signature in database GPG Key ID: 58C80A2AA6C765E1
  1. 2
      src/api/mod.rs
  2. 43
      src/api/web.rs
  3. 6
      src/config.rs
  4. 38
      src/util.rs

2
src/api/mod.rs

@ -30,7 +30,7 @@ pub use crate::api::{
}, },
web::catchers as web_catchers, web::catchers as web_catchers,
web::routes as web_routes, web::routes as web_routes,
web::static_files, web::{invalidate_css_cache, static_files},
}; };
use crate::{ use crate::{
CONFIG, CONFIG,

43
src/api/web.rs

@ -1,4 +1,7 @@
use std::path::{Path, PathBuf}; use std::{
path::{Path, PathBuf},
sync::{Arc, RwLock},
};
use rocket::{ use rocket::{
Catcher, Route, Catcher, Route,
@ -13,12 +16,13 @@ use crate::{
CONFIG, CONFIG,
api::{ApiResult, EmptyResult, core::now}, api::{ApiResult, EmptyResult, core::now},
auth::decode_file_download, auth::decode_file_download,
crypto::sha256_hex,
db::{ db::{
DbConn, DbConn,
models::{AttachmentId, CipherId}, models::{AttachmentId, CipherId},
}, },
error::Error, error::Error,
util::Cached, util::{Cached, EtagCached},
}; };
pub fn routes() -> Vec<Route> { pub fn routes() -> Vec<Route> {
@ -63,8 +67,27 @@ fn not_found() -> ApiResult<Html<String>> {
Ok(Html(text)) Ok(Html(text))
} }
struct CssCache {
css: String,
etag: String,
}
static CSS_CACHE: RwLock<Option<Arc<CssCache>>> = RwLock::new(None);
pub fn invalidate_css_cache() {
*CSS_CACHE.write().unwrap() = None;
}
#[get("/css/vaultwarden.css")] #[get("/css/vaultwarden.css")]
fn vaultwarden_css() -> Cached<Css<String>> { fn vaultwarden_css() -> EtagCached<Css<String>> {
// If reload_templates is false, and we already have the CSS Cached, return this
if !CONFIG.reload_templates()
&& let Some(cached) = CSS_CACHE.read().unwrap().as_ref()
{
return EtagCached::new(Css(cached.css.clone()), &cached.etag);
}
// Else, there is either no cache, or reload_templates is true and we need to rebuild the CSS
let css_options = json!({ let css_options = json!({
"emergency_access_allowed": CONFIG.emergency_access_allowed(), "emergency_access_allowed": CONFIG.emergency_access_allowed(),
"load_user_scss": true, "load_user_scss": true,
@ -112,8 +135,18 @@ fn vaultwarden_css() -> Cached<Css<String>> {
} }
}; };
// Cache for one day should be enough and not too much let etag = sha256_hex(css.as_bytes());
Cached::ttl(Css(css), 86_400, false) let cached = Arc::new(CssCache {
css,
etag,
});
if !CONFIG.reload_templates() {
*CSS_CACHE.write().unwrap() = Some(Arc::clone(&cached));
}
// Etag Caching will let the browser send us an etag to verify and send new content if needed
EtagCached::new(Css(cached.css.clone()), &cached.etag)
} }
#[get("/")] #[get("/")]

6
src/config.rs

@ -1506,6 +1506,9 @@ impl Config {
let operator = storage::operator_for_path(&CONFIG_FILE_PARENT_DIR)?; let operator = storage::operator_for_path(&CONFIG_FILE_PARENT_DIR)?;
operator.write(&CONFIG_FILENAME, config_str).await?; operator.write(&CONFIG_FILENAME, config_str).await?;
// Invalidate CSS Cache because several config items might have impact on the rendered CSS
crate::api::invalidate_css_cache();
Ok(()) Ok(())
} }
@ -1588,6 +1591,9 @@ impl Config {
writer._overrides = Vec::new(); writer._overrides = Vec::new();
} }
// Invalidate CSS Cache because several config items might have impact on the rendered CSS
crate::api::invalidate_css_cache();
Ok(()) Ok(())
} }

38
src/util.rs

@ -257,6 +257,44 @@ impl<'r, R: 'r + Responder<'r, 'static> + Send> Responder<'r, 'static> for Cache
} }
} }
pub struct EtagCached<R> {
response: R,
etag: String,
}
impl<R> EtagCached<R> {
/// An `etag` response should always be quoted
pub fn new(response: R, etag: &str) -> Self {
Self {
response,
etag: format!("\"{etag}\""),
}
}
}
impl<'r, R: 'r + Responder<'r, 'static> + Send> Responder<'r, 'static> for EtagCached<R> {
fn respond_to(self, request: &'r Request<'_>) -> response::Result<'static> {
// Check and validate a `If-None-Match` ETag header
// Multiple tags could be returned for the same URI if the browser has multiple versions cached
// Also, weak tags are prefixed with `W/`, but ETags are always weak, so just strip it too before comparing
let etag_matches = request
.headers()
.get_one("If-None-Match")
.is_some_and(|v| v.split(',').any(|t| t.trim().trim_start_matches("W/") == self.etag));
let mut res = if etag_matches {
Response::build().status(Status::NotModified).ok()?
} else {
self.response.respond_to(request)?
};
// Both 200 (OK) and 304 (Not Modified) need to return the etag and cache-control
res.set_raw_header("Etag", self.etag);
res.set_raw_header("Cache-Control", "public, no-cache");
Ok(res)
}
}
// Log all the routes from the main paths list, and the attachments endpoint // Log all the routes from the main paths list, and the attachments endpoint
// Effectively ignores, any static file route, and the alive endpoint // Effectively ignores, any static file route, and the alive endpoint
const LOGGED_ROUTES: [&str; 7] = ["/api", "/admin", "/identity", "/icons", "/attachments", "/events", "/notifications"]; const LOGGED_ROUTES: [&str; 7] = ["/api", "/admin", "/identity", "/icons", "/attachments", "/events", "/notifications"];

Loading…
Cancel
Save