fix: add security headers, correct MIME types and long-cache hashed assets
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -429,7 +429,47 @@ pub fn router(state: HubState) -> Router {
|
|||||||
get(|| async { Json(ApiDoc::openapi()) }),
|
get(|| async { Json(ApiDoc::openapi()) }),
|
||||||
);
|
);
|
||||||
|
|
||||||
api.fallback(spa_fallback).layer(TraceLayer::new_for_http())
|
let hsts = matches!(
|
||||||
|
std::env::var("TESSERA_HSTS").as_deref(),
|
||||||
|
Ok("1" | "true")
|
||||||
|
);
|
||||||
|
api.fallback(spa_fallback)
|
||||||
|
.layer(TraceLayer::new_for_http())
|
||||||
|
.layer(axum::middleware::from_fn(move |request, next| {
|
||||||
|
security_headers(hsts, request, next)
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Policy for the bundled web app: everything from this origin. The stylesheet pulls the
|
||||||
|
/// Google Fonts CSS and font files, hence those two allowances.
|
||||||
|
const CONTENT_SECURITY_POLICY: &str = "default-src 'self'; script-src 'self'; \
|
||||||
|
style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; \
|
||||||
|
img-src 'self' data: blob:; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'";
|
||||||
|
|
||||||
|
async fn security_headers(
|
||||||
|
hsts: bool,
|
||||||
|
request: axum::extract::Request,
|
||||||
|
next: axum::middleware::Next,
|
||||||
|
) -> axum::response::Response {
|
||||||
|
let mut response = next.run(request).await;
|
||||||
|
let headers = response.headers_mut();
|
||||||
|
headers.insert(
|
||||||
|
header::CONTENT_SECURITY_POLICY,
|
||||||
|
HeaderValue::from_static(CONTENT_SECURITY_POLICY),
|
||||||
|
);
|
||||||
|
headers.insert(
|
||||||
|
header::X_CONTENT_TYPE_OPTIONS,
|
||||||
|
HeaderValue::from_static("nosniff"),
|
||||||
|
);
|
||||||
|
headers.insert(header::REFERRER_POLICY, HeaderValue::from_static("no-referrer"));
|
||||||
|
headers.insert(header::X_FRAME_OPTIONS, HeaderValue::from_static("DENY"));
|
||||||
|
if hsts {
|
||||||
|
headers.insert(
|
||||||
|
header::STRICT_TRANSPORT_SECURITY,
|
||||||
|
HeaderValue::from_static("max-age=31536000; includeSubDomains"),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
response
|
||||||
}
|
}
|
||||||
|
|
||||||
#[utoipa::path(get, path = "/health", responses((status = 200, description = "ok")))]
|
#[utoipa::path(get, path = "/health", responses((status = 200, description = "ok")))]
|
||||||
@@ -1488,18 +1528,33 @@ async fn spa_fallback(uri: Uri) -> impl IntoResponse {
|
|||||||
path = "index.html".into();
|
path = "index.html".into();
|
||||||
}
|
}
|
||||||
if let Some(file) = WEB_DIST.get_file(&path) {
|
if let Some(file) = WEB_DIST.get_file(&path) {
|
||||||
let ct = content_type(&path);
|
// Build output under /assets/ carries a content hash in its name.
|
||||||
|
let cache = if path.starts_with("assets/") {
|
||||||
|
"public, max-age=31536000, immutable"
|
||||||
|
} else {
|
||||||
|
"no-cache"
|
||||||
|
};
|
||||||
return (
|
return (
|
||||||
StatusCode::OK,
|
StatusCode::OK,
|
||||||
[(header::CONTENT_TYPE, ct)],
|
[
|
||||||
|
(header::CONTENT_TYPE, content_type(&path)),
|
||||||
|
(header::CACHE_CONTROL, cache),
|
||||||
|
],
|
||||||
file.contents(),
|
file.contents(),
|
||||||
)
|
)
|
||||||
.into_response();
|
.into_response();
|
||||||
}
|
}
|
||||||
|
// A missing asset or API path is a 404, not the app shell.
|
||||||
|
if path.starts_with("assets/") || path.starts_with("api/") {
|
||||||
|
return (StatusCode::NOT_FOUND, "not found").into_response();
|
||||||
|
}
|
||||||
if let Some(index) = WEB_DIST.get_file("index.html") {
|
if let Some(index) = WEB_DIST.get_file("index.html") {
|
||||||
return (
|
return (
|
||||||
StatusCode::OK,
|
StatusCode::OK,
|
||||||
[(header::CONTENT_TYPE, "text/html")],
|
[
|
||||||
|
(header::CONTENT_TYPE, "text/html; charset=utf-8"),
|
||||||
|
(header::CACHE_CONTROL, "no-cache"),
|
||||||
|
],
|
||||||
index.contents(),
|
index.contents(),
|
||||||
)
|
)
|
||||||
.into_response();
|
.into_response();
|
||||||
@@ -1508,14 +1563,22 @@ async fn spa_fallback(uri: Uri) -> impl IntoResponse {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn content_type(path: &str) -> &'static str {
|
fn content_type(path: &str) -> &'static str {
|
||||||
if path.ends_with(".js") {
|
let extension = path.rsplit('.').next().unwrap_or("").to_ascii_lowercase();
|
||||||
"application/javascript"
|
match extension.as_str() {
|
||||||
} else if path.ends_with(".css") {
|
"html" => "text/html; charset=utf-8",
|
||||||
"text/css"
|
"js" | "mjs" => "text/javascript; charset=utf-8",
|
||||||
} else if path.ends_with(".svg") {
|
"css" => "text/css; charset=utf-8",
|
||||||
"image/svg+xml"
|
"svg" => "image/svg+xml",
|
||||||
} else {
|
"png" => "image/png",
|
||||||
"text/html"
|
"jpg" | "jpeg" => "image/jpeg",
|
||||||
|
"webp" => "image/webp",
|
||||||
|
"ico" => "image/x-icon",
|
||||||
|
"woff" => "font/woff",
|
||||||
|
"woff2" => "font/woff2",
|
||||||
|
"json" => "application/json",
|
||||||
|
"map" => "application/json",
|
||||||
|
"txt" => "text/plain; charset=utf-8",
|
||||||
|
_ => "application/octet-stream",
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1631,6 +1694,53 @@ mod tests {
|
|||||||
assert_eq!(r.status(), StatusCode::CONFLICT);
|
assert_eq!(r.status(), StatusCode::CONFLICT);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn content_types_are_right_and_unknown_is_never_html() {
|
||||||
|
assert_eq!(content_type("assets/x.png"), "image/png");
|
||||||
|
assert_eq!(content_type("assets/x.woff2"), "font/woff2");
|
||||||
|
assert_eq!(content_type("assets/x.woff"), "font/woff");
|
||||||
|
assert_eq!(content_type("favicon.ico"), "image/x-icon");
|
||||||
|
assert_eq!(content_type("assets/x.js.map"), "application/json");
|
||||||
|
assert_eq!(content_type("manifest.json"), "application/json");
|
||||||
|
assert_eq!(content_type("assets/x.bin"), "application/octet-stream");
|
||||||
|
assert_eq!(content_type("noextension"), "application/octet-stream");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn responses_carry_security_headers_and_assets_cache_for_a_year() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault")
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let app = router(state);
|
||||||
|
let get = |uri: &str| {
|
||||||
|
Request::get(uri)
|
||||||
|
.extension(ConnectInfo("203.0.113.40:9000".parse::<SocketAddr>().unwrap()))
|
||||||
|
.body(Body::empty())
|
||||||
|
.unwrap()
|
||||||
|
};
|
||||||
|
for uri in ["/", "/health", "/api/v1/orbits"] {
|
||||||
|
let r = app.clone().oneshot(get(uri)).await.unwrap();
|
||||||
|
let h = r.headers();
|
||||||
|
let csp = h[header::CONTENT_SECURITY_POLICY].to_str().unwrap();
|
||||||
|
assert!(csp.contains("default-src 'self'") && csp.contains("frame-ancestors 'none'"));
|
||||||
|
assert_eq!(h[header::X_CONTENT_TYPE_OPTIONS], "nosniff");
|
||||||
|
assert_eq!(h[header::REFERRER_POLICY], "no-referrer");
|
||||||
|
assert_eq!(h[header::X_FRAME_OPTIONS], "DENY");
|
||||||
|
}
|
||||||
|
let missing = app.clone().oneshot(get("/assets/nope.js")).await.unwrap();
|
||||||
|
assert_eq!(missing.status(), StatusCode::NOT_FOUND);
|
||||||
|
if let Some(file) = WEB_DIST.get_dir("assets").and_then(|d| d.files().next()) {
|
||||||
|
let uri = format!("/{}", file.path().display());
|
||||||
|
let r = app.oneshot(get(&uri)).await.unwrap();
|
||||||
|
assert_eq!(r.status(), StatusCode::OK);
|
||||||
|
assert_eq!(
|
||||||
|
r.headers()[header::CACHE_CONTROL],
|
||||||
|
"public, max-age=31536000, immutable"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn a_failed_denial_audit_write_still_answers_401() {
|
async fn a_failed_denial_audit_write_still_answers_401() {
|
||||||
let dir = tempfile::tempdir().unwrap();
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
|||||||
Reference in New Issue
Block a user