Skip to content

A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.

TypeScript fluxerfluxerapp

test(app-proxy): remove route and static file unit tests

Hampus038d6b533ab7
diff --git a/fluxer_app_proxy/src/local_files.rs b/fluxer_app_proxy/src/local_files.rs
index 0df84ab91..aabe6493b 100644
--- a/fluxer_app_proxy/src/local_files.rs
+++ b/fluxer_app_proxy/src/local_files.rs
@@ -12,7 +12,6 @@ use axum::{
};
use futures_util::Stream;
use sha2::{Digest, Sha256};
-use std::fmt;
use std::path::{Component, Path, PathBuf};
use std::pin::Pin;
use std::sync::Arc;
@@ -22,7 +21,6 @@ use tokio::sync::{OwnedSemaphorePermit, Semaphore, TryAcquireError};
const LOCAL_FILE_BUFFER_BUDGET_BYTES: usize = 128 * 1024 * 1024;
const LOCAL_FILE_STREAM_BUFFER_BYTES: usize = 256 * 1024;
-const PRECOMPRESSED_SIBLINGS: &[(&str, &str)] = &[("br", "br"), ("gzip", "gz")];
#[derive(Clone)]
pub(crate) struct LocalFileStore {
@@ -59,15 +57,6 @@ impl LocalFileStore {
})
}
- #[cfg(test)]
- pub(crate) fn load_blocking(root: &Path, budgets: &AppProxyBudgets) -> anyhow::Result<Self> {
- let root = std::fs::canonicalize(root)
- .with_context(|| format!("failed to resolve static directory {}", root.display()))?;
- let metadata = std::fs::metadata(&root)
- .with_context(|| format!("failed to inspect static directory {}", root.display()))?;
- Self::from_resolved_root(root, metadata, budgets)
- }
-
async fn resolve_checked(
&self,
relative_path: &str,
@@ -576,47 +565,6 @@ pub(crate) enum LocalFileReadError {
},
}
-impl fmt::Display for LocalFileReadError {
- fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
- match self {
- Self::NotFound(path) => write!(formatter, "local file {path:?} was not found"),
- Self::InvalidPath(path) => write!(formatter, "local file path {path:?} is invalid"),
- Self::Busy(path) => {
- write!(formatter, "local file capacity is unavailable for {path:?}")
- }
- Self::ChangedDuringRead { path, expected } => write!(
- formatter,
- "local file {path:?} grew after its {expected} byte size was inspected"
- ),
- Self::TooLarge {
- path,
- actual,
- maximum,
- } => write!(
- formatter,
- "local file {path:?} is {actual} bytes and exceeds the {maximum} byte limit"
- ),
- Self::InvalidUtf8(path) => write!(formatter, "local text file {path:?} is not UTF-8"),
- Self::Io { path, source } => {
- write!(
- formatter,
- "failed to read local file {}: {source}",
- path.display()
- )
- }
- }
- }
-}
-
-impl std::error::Error for LocalFileReadError {
- fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
- match self {
- Self::Io { source, .. } => Some(source),
- _ => None,
- }
- }
-}
-
fn local_file_error_response(error: LocalFileReadError) -> Response {
match error {
LocalFileReadError::NotFound(_) | LocalFileReadError::InvalidPath(_) => {
@@ -633,7 +581,6 @@ fn local_file_error_response(error: LocalFileReadError) -> Response {
#[cfg(test)]
mod tests {
use super::*;
- use crate::state::LOCAL_FILE_READS_IN_FLIGHT_MAX;
fn temp_root(name: &str) -> PathBuf {
let root = std::env::temp_dir().join(format!(
@@ -654,92 +601,6 @@ mod tests {
}
}
- async fn body_of(response: Response) -> Vec<u8> {
- axum::body::to_bytes(response.into_body(), usize::MAX)
- .await
- .unwrap()
- .to_vec()
- }
-
- #[tokio::test]
- async fn an_open_response_never_holds_a_read_slot_against_the_next_reader() {
- let root = temp_root("in-flight");
- std::fs::write(root.join("robots.txt"), "User-agent: *\n").unwrap();
- let store = LocalFileStore::load(&root, &AppProxyBudgets::new())
- .await
- .unwrap();
-
- let mut open = Vec::with_capacity(LOCAL_FILE_READS_IN_FLIGHT_MAX + 1);
- for _ in 0..=LOCAL_FILE_READS_IN_FLIGHT_MAX {
- open.push(
- serve_binary_file(&store, "robots.txt", &HeaderMap::new(), text_options(1024))
- .await,
- );
- }
-
- let refused = open
- .iter()
- .filter(|response| response.status() != StatusCode::OK)
- .count();
- assert_eq!(
- refused, 0,
- "{refused} readers were turned away while earlier responses were still open"
- );
- assert_eq!(
- body_of(open.pop().unwrap()).await,
- b"User-agent: *\n",
- "a response served past the read slot count carried the wrong bytes"
- );
-
- std::fs::remove_dir_all(&root).unwrap();
- }
-
- #[tokio::test]
- async fn concurrent_bundle_responses_are_not_charged_their_whole_file_size() {
- let root = temp_root("bundle-budget");
- let bundle_bytes = 8 * 1024 * 1024;
- std::fs::write(root.join("bundle.js"), vec![b'x'; bundle_bytes]).unwrap();
- let store = LocalFileStore::load(&root, &AppProxyBudgets::new())
- .await
- .unwrap();
-
- let mut open = Vec::with_capacity(32);
- for _ in 0..32 {
- open.push(
- serve_binary_file(
- &store,
- "bundle.js",
- &HeaderMap::new(),
- text_options(100 * 1024 * 1024),
- )
- .await,
- );
- }
-
- let refused = open
- .iter()
- .filter(|response| response.status() != StatusCode::OK)
- .count();
- assert_eq!(
- refused, 0,
- "{refused} of 32 concurrent bundle responses were refused for buffer capacity"
- );
- let last = open.pop().unwrap();
- assert_eq!(
- last.headers().get(header::CONTENT_LENGTH).unwrap(),
- bundle_bytes.to_string().as_str(),
- "a streamed bundle response did not declare its length"
- );
- let body = body_of(last).await;
- assert_eq!(body.len(), bundle_bytes);
- assert!(
- body.iter().all(|byte| *byte == b'x'),
- "a streamed bundle response carried bytes the file does not hold"
- );
-
- std::fs::remove_dir_all(&root).unwrap();
- }
-
#[tokio::test]
async fn a_path_that_leaves_the_static_root_is_not_served() {
let root = temp_root("escape");
@@ -792,136 +653,4 @@ mod tests {
std::fs::remove_file(&outside).unwrap();
std::fs::remove_dir_all(&root).unwrap();
}
-
- #[tokio::test]
- async fn a_revalidating_client_is_answered_from_its_entity_tag() {
- let root = temp_root("revalidate");
- std::fs::write(root.join("robots.txt"), "User-agent: *\n").unwrap();
- let store = LocalFileStore::load(&root, &AppProxyBudgets::new())
- .await
- .unwrap();
-
- let first =
- serve_binary_file(&store, "robots.txt", &HeaderMap::new(), text_options(1024)).await;
- assert_eq!(first.status(), StatusCode::OK);
- let entity_tag = first.headers().get(header::ETAG).unwrap().clone();
-
- let mut revalidation = HeaderMap::new();
- revalidation.insert(header::IF_NONE_MATCH, entity_tag.clone());
- let second =
- serve_binary_file(&store, "robots.txt", &revalidation, text_options(1024)).await;
- assert_eq!(second.status(), StatusCode::NOT_MODIFIED);
- assert_eq!(second.headers().get(header::ETAG), Some(&entity_tag));
- assert!(body_of(second).await.is_empty());
-
- let mut stale = HeaderMap::new();
- stale.insert(header::IF_NONE_MATCH, HeaderValue::from_static("\"other\""));
- let third = serve_binary_file(&store, "robots.txt", &stale, text_options(1024)).await;
- assert_eq!(
- third.status(),
- StatusCode::OK,
- "a client holding a different entity tag was told its copy was current"
- );
-
- std::fs::remove_dir_all(&root).unwrap();
- }
-
- #[tokio::test]
- async fn a_file_over_its_response_limit_is_refused_before_it_is_buffered() {
- let root = temp_root("too-large");
- std::fs::write(root.join("version.json"), "x".repeat(4096)).unwrap();
- let store = LocalFileStore::load(&root, &AppProxyBudgets::new())
- .await
- .unwrap();
-
- let response = serve_binary_file(
- &store,
- "version.json",
- &HeaderMap::new(),
- text_options(1024),
- )
- .await;
-
- assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
- assert_eq!(
- store.buffer_budget.available_permits(),
- LOCAL_FILE_BUFFER_BUDGET_BYTES,
- "a refused file still holds its buffer budget"
- );
-
- std::fs::remove_dir_all(&root).unwrap();
- }
-
- #[tokio::test]
- async fn a_replacement_that_grows_past_the_response_limit_is_refused() {
- let root = temp_root("replacement");
- std::fs::write(root.join("sw.js"), "const endpoint = '{{MEDIA_ENDPOINT}}';").unwrap();
- let store = LocalFileStore::load(&root, &AppProxyBudgets::new())
- .await
- .unwrap();
-
- let served = serve_text_file(
- &store,
- "sw.js",
- &HeaderMap::new(),
- text_options(1024),
- &[("{{MEDIA_ENDPOINT}}", "https://media.example.test")],
- std::convert::identity,
- )
- .await;
- assert_eq!(served.status(), StatusCode::OK);
- assert_eq!(
- String::from_utf8(body_of(served).await).unwrap(),
- "const endpoint = 'https://media.example.test';"
- );
-
- let overflowed = serve_text_file(
- &store,
- "sw.js",
- &HeaderMap::new(),
- text_options(64),
- &[("{{MEDIA_ENDPOINT}}", &"x".repeat(64))],
- std::convert::identity,
- )
- .await;
- assert_eq!(overflowed.status(), StatusCode::INTERNAL_SERVER_ERROR);
- assert_eq!(
- store.buffer_budget.available_permits(),
- LOCAL_FILE_BUFFER_BUDGET_BYTES,
- "a refused replacement still holds its buffer budget"
- );
-
- std::fs::remove_dir_all(&root).unwrap();
- }
-
- #[tokio::test]
- async fn an_exhausted_buffer_budget_asks_the_client_to_retry() {
- let root = temp_root("busy");
- std::fs::write(root.join("robots.txt"), "User-agent: *\n").unwrap();
- let store = LocalFileStore::load(&root, &AppProxyBudgets::new())
- .await
- .unwrap();
- let held = store
- .buffer_budget
- .clone()
- .try_acquire_many_owned(u32::try_from(LOCAL_FILE_BUFFER_BUDGET_BYTES).unwrap())
- .unwrap();
-
- let response =
- serve_binary_file(&store, "robots.txt", &HeaderMap::new(), text_options(1024)).await;
-
- assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
- assert_eq!(
- response.headers().get(header::RETRY_AFTER).unwrap(),
- "1",
- "a client refused for capacity was not told when to come back"
- );
- assert_eq!(
- response.headers().get(header::CACHE_CONTROL).unwrap(),
- "no-store"
- );
- drop(held);
-
- std::fs::remove_dir_all(&root).unwrap();
- }
}
diff --git a/fluxer_app_proxy/src/routes/assets_proxy.rs b/fluxer_app_proxy/src/routes/assets_proxy.rs
index e556b98ca..82efbeb69 100644
--- a/fluxer_app_proxy/src/routes/assets_proxy.rs
+++ b/fluxer_app_proxy/src/routes/assets_proxy.rs
@@ -189,1096 +189,3 @@ pub(super) async fn serve_local_asset(
);
response
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use crate::config::AppProxyConfig;
- use crate::state::{AppProxyBudgets, SpaIndexSource, build_http_client};
- use crate::static_asset_policy::{
- CORS_ALLOW_ANY_VALUE, LONG_LIVED_ASSET_CACHE_CONTROL, REVALIDATED_ASSET_CACHE_CONTROL,
- UPSTREAM_FAILURE_CACHE_CONTROL, is_hashed_asset,
- };
- use axum::Router;
- use axum::http::Request as HttpRequest;
- use axum::http::header::{self, HeaderName};
- use std::sync::Arc;
- use std::sync::atomic::{AtomicU64, Ordering};
- use tower::ServiceExt;
-
- async fn spawn_upstream(status: StatusCode, cache_control: &'static str) -> String {
- let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
- let addr = listener.local_addr().unwrap();
- let router = Router::new().fallback(move || async move {
- let mut response = Response::new(Body::from("upstream-bytes"));
- *response.status_mut() = status;
- response.headers_mut().insert(
- header::CACHE_CONTROL,
- HeaderValue::from_static(cache_control),
- );
- response
- });
- tokio::spawn(async move {
- axum::serve(listener, router).await.unwrap();
- });
- format!("http://{addr}")
- }
-
- fn upstream_backed_state(cdn_endpoint: &str) -> AppState {
- let mut config = AppProxyConfig::from_env();
- config.static_dir = ".".to_owned();
- config.static_cdn_endpoint = Some(
- crate::config::HttpEndpoint::parse("TEST_STATIC_CDN_ENDPOINT", cdn_endpoint).unwrap(),
- );
- state_from_config(config)
- }
-
- fn locally_backed_state(static_dir: &str) -> AppState {
- let mut config = AppProxyConfig::from_env();
- config.static_cdn_endpoint = None;
- config.static_dir = static_dir.to_owned();
- state_from_config(config)
- }
-
- fn state_from_config(config: AppProxyConfig) -> AppState {
- let csp = Arc::new(
- crate::csp::CompiledCspPolicy::from_config(&config)
- .expect("the test configuration must compile to a valid CSP"),
- );
- let budgets = AppProxyBudgets::default();
- let local_files =
- LocalFileStore::load_blocking(std::path::Path::new(&config.static_dir), &budgets)
- .expect("the test static directory must exist");
- AppState {
- branding: crate::branding_images::InstanceBranding::from_config(&config),
- config: Arc::new(config),
- csp,
- http_client: build_http_client().unwrap(),
- spa_index_source: SpaIndexSource::bundled(""),
- local_asset_prefixes: None,
- bundled_app_assets: false,
- budgets,
- local_files,
- }
- }
-
- async fn proxied_asset(
- status: StatusCode,
- upstream_cache_control: &'static str,
- asset_path: &str,
- ) -> Response {
- let endpoint = spawn_upstream(status, upstream_cache_control).await;
- let state = upstream_backed_state(&endpoint);
- let request = HttpRequest::builder()
- .uri(format!("/assets/{asset_path}"))
- .body(Body::empty())
- .unwrap();
- proxy_assets(State(state), Path(asset_path.to_owned()), request).await
- }
-
- fn cache_control_of(response: &Response) -> Option<&str> {
- response
- .headers()
- .get(header::CACHE_CONTROL)
- .and_then(|value| value.to_str().ok())
- }
-
- #[tokio::test]
- async fn a_proxied_asset_overrides_a_shorter_upstream_lifetime() {
- let response = proxied_asset(
- StatusCode::OK,
- "public, max-age=3600, must-revalidate",
- "2d715e4730758083.worker.js",
- )
- .await;
-
- assert_eq!(response.status(), StatusCode::OK);
- assert_eq!(
- cache_control_of(&response),
- Some(LONG_LIVED_ASSET_CACHE_CONTROL)
- );
- }
-
- #[tokio::test]
- async fn an_asset_without_a_content_hash_is_never_promised_to_never_change() {
- let response = proxied_asset(
- StatusCode::OK,
- "public, max-age=31536000, immutable",
- "voice_engine_bg.wasm",
- )
- .await;
-
- assert_eq!(
- cache_control_of(&response),
- Some(REVALIDATED_ASSET_CACHE_CONTROL),
- "a stable filename can be redeployed over, so it must stay revalidatable"
- );
- }
-
- #[tokio::test]
- async fn revalidated_hashed_asset_keeps_our_lifetime_on_not_modified() {
- let response = proxied_asset(
- StatusCode::NOT_MODIFIED,
- "public, max-age=60",
- "2d715e4730758083.worker.js",
- )
- .await;
-
- assert_eq!(response.status(), StatusCode::NOT_MODIFIED);
- assert_eq!(
- cache_control_of(&response),
- Some(LONG_LIVED_ASSET_CACHE_CONTROL)
- );
- }
-
- #[tokio::test]
- async fn an_asset_without_a_content_hash_keeps_our_policy_on_not_modified() {
- let response = proxied_asset(
- StatusCode::NOT_MODIFIED,
- "public, max-age=31536000, immutable",
- "voice_engine_bg.wasm",
- )
- .await;
-
- assert_eq!(
- cache_control_of(&response),
- Some(REVALIDATED_ASSET_CACHE_CONTROL)
- );
- }
-
- #[tokio::test]
- async fn a_not_found_with_a_long_upstream_lifetime_is_rewritten_to_no_store() {
- let response = proxied_asset(
- StatusCode::NOT_FOUND,
- "public, max-age=31536000, immutable",
- "2d715e4730758083.worker.js",
- )
- .await;
-
- assert_eq!(response.status(), StatusCode::NOT_FOUND);
- assert_eq!(
- cache_control_of(&response),
- Some(UPSTREAM_FAILURE_CACHE_CONTROL),
- "a cdn or bucket error page with its own year would pin the miss for a year"
- );
- }
-
- fn apply_test_asset_policy(headers: &mut HeaderMap, path: &str, status: StatusCode) {
- apply_asset_response_policy(
- headers,
- path,
- status,
- HeaderValue::from_static("default-src 'none'"),
- );
- }
-
- #[test]
- fn upstream_cdn_lifetimes_never_reach_the_client() {
- let long_lived = || {
- let mut headers = HeaderMap::new();
- headers.insert(
- header::CACHE_CONTROL,
- HeaderValue::from_static("public, max-age=31536000, immutable"),
- );
- headers.insert(
- HeaderName::from_static("cdn-cache-control"),
- HeaderValue::from_static("public, max-age=31536000"),
- );
- headers.insert(
- header::EXPIRES,
- HeaderValue::from_static("Thu, 31 Dec 2099 23:59:59 GMT"),
- );
- headers
- };
-
- let upstream = long_lived();
- let mut ok = HeaderMap::new();
- copy_asset_response_headers(&upstream, &mut ok);
- apply_test_asset_policy(&mut ok, "2d715e4730758083.worker.js", StatusCode::OK);
- assert!(!ok.contains_key("cdn-cache-control"));
- assert!(!ok.contains_key(header::EXPIRES));
-
- let mut failed = HeaderMap::new();
- copy_asset_response_headers(&upstream, &mut failed);
- apply_test_asset_policy(
- &mut failed,
- "2d715e4730758083.worker.js",
- StatusCode::NOT_FOUND,
- );
- assert_eq!(
- failed
- .get(header::CACHE_CONTROL)
- .and_then(|value| value.to_str().ok()),
- Some(UPSTREAM_FAILURE_CACHE_CONTROL)
- );
- assert!(
- !failed.contains_key("cdn-cache-control"),
- "a cdn honours cdn-cache-control over cache-control, so the error would still be pinned"
- );
- assert!(!failed.contains_key(header::EXPIRES));
- }
-
- struct LocalAssetDir {
- root: std::path::PathBuf,
- }
-
- impl LocalAssetDir {
- fn with_asset(name: &str, bytes: &[u8]) -> Self {
- static NEXT_FIXTURE: AtomicU64 = AtomicU64::new(0);
- let unique = NEXT_FIXTURE.fetch_add(1, Ordering::Relaxed);
- let pid = std::process::id();
- let root =
- std::env::temp_dir().join(format!("fluxer-local-asset-{pid}-{unique}-{name}"));
- std::fs::create_dir_all(root.join("assets")).unwrap();
- std::fs::write(root.join("assets").join(name), bytes).unwrap();
- Self { root }
- }
-
- fn and_sibling(self, name: &str, bytes: &[u8]) -> Self {
- std::fs::write(self.root.join("assets").join(name), bytes).unwrap();
- self
- }
-
- fn dir(&self) -> &str {
- self.root.to_str().unwrap()
- }
-
- fn files(&self) -> LocalFileStore {
- self.files_with(&budgets())
- }
-
- fn files_with(&self, budgets: &AppProxyBudgets) -> LocalFileStore {
- LocalFileStore::load_blocking(&self.root, budgets).unwrap()
- }
- }
-
- impl Drop for LocalAssetDir {
- fn drop(&mut self) {
- let _ = std::fs::remove_dir_all(&self.root);
- }
- }
-
- fn budgets() -> AppProxyBudgets {
- AppProxyBudgets::default()
- }
-
- fn test_asset_csp() -> HeaderValue {
- let mut config = AppProxyConfig::from_env();
- config.static_cdn_endpoint = None;
- crate::csp::CompiledCspPolicy::from_config(&config)
- .expect("the test configuration must compile to a valid CSP")
- .asset_header()
- }
-
- fn entity_tag_of(response: &Response) -> Option<String> {
- response
- .headers()
- .get(header::ETAG)
- .and_then(|value| value.to_str().ok())
- .map(ToOwned::to_owned)
- }
-
- fn cors_origin_of(response: &Response) -> Option<&str> {
- response
- .headers()
- .get(header::ACCESS_CONTROL_ALLOW_ORIGIN)
- .and_then(|value| value.to_str().ok())
- }
-
- #[tokio::test]
- async fn local_font_revalidation_keeps_cross_origin_access() {
- let fixture = LocalAssetDir::with_asset("0018072843a46dc4.woff2", b"wOF2stub");
-
- let first = serve_local_asset(
- &fixture.files(),
- "assets/0018072843a46dc4.woff2",
- &HeaderMap::new(),
- test_asset_csp(),
- )
- .await;
- assert_eq!(cors_origin_of(&first), Some(CORS_ALLOW_ANY_VALUE));
- let entity_tag = entity_tag_of(&first).expect("first response has a validator");
-
- let mut conditional = HeaderMap::new();
- conditional.insert(
- header::IF_NONE_MATCH,
- HeaderValue::from_str(&entity_tag).unwrap(),
- );
- let second = serve_local_asset(
- &fixture.files(),
- "assets/0018072843a46dc4.woff2",
- &conditional,
- test_asset_csp(),
- )
- .await;
-
- assert_eq!(second.status(), StatusCode::NOT_MODIFIED);
- assert_eq!(
- cors_origin_of(&second),
- Some(CORS_ALLOW_ANY_VALUE),
- "a 304 without the CORS header fails the cross-origin font fetch the 200 allowed"
- );
- }
-
- #[tokio::test]
- async fn local_hashed_asset_is_served_with_an_entity_tag() {
- let fixture = LocalAssetDir::with_asset("356aaade04a117b1.js", b"console.log(1)");
-
- let response = serve_local_asset(
- &fixture.files(),
- "assets/356aaade04a117b1.js",
- &HeaderMap::new(),
- test_asset_csp(),
- )
- .await;
-
- assert_eq!(response.status(), StatusCode::OK);
- assert_eq!(
- cache_control_of(&response),
- Some(LONG_LIVED_ASSET_CACHE_CONTROL)
- );
- assert!(
- entity_tag_of(&response).is_some(),
- "a year-long asset with no validator forces a full re-download on any revalidation"
- );
- }
-
- #[tokio::test]
- async fn a_local_asset_download_can_be_resumed() {
- let fixture = LocalAssetDir::with_asset("fluxer-setup.exe", b"installer-payload");
-
- let mut resumed = HeaderMap::new();
- resumed.insert(header::RANGE, HeaderValue::from_static("bytes=10-"));
- let response = serve_local_asset(
- &fixture.files(),
- "assets/fluxer-setup.exe",
- &resumed,
- test_asset_csp(),
- )
- .await;
-
- assert_eq!(
- response.status(),
- StatusCode::PARTIAL_CONTENT,
- "a resumed installer download that answers 200 re-sends every byte already fetched"
- );
- assert_eq!(
- response
- .headers()
- .get(header::CONTENT_RANGE)
- .and_then(|value| value.to_str().ok()),
- Some("bytes 10-16/17")
- );
- assert_eq!(
- axum::body::to_bytes(response.into_body(), usize::MAX)
- .await
- .unwrap()
- .as_ref(),
- b"payload"
- );
- }
-
- #[tokio::test]
- async fn local_asset_revalidation_returns_not_modified() {
- let fixture = LocalAssetDir::with_asset("f00dcafe12345678.css", b"body{}");
-
- let first = serve_local_asset(
- &fixture.files(),
- "assets/f00dcafe12345678.css",
- &HeaderMap::new(),
- test_asset_csp(),
- )
- .await;
- let entity_tag = entity_tag_of(&first).expect("first response has a validator");
-
- let mut conditional = HeaderMap::new();
- conditional.insert(
- header::IF_NONE_MATCH,
- HeaderValue::from_str(&entity_tag).unwrap(),
- );
- let second = serve_local_asset(
- &fixture.files(),
- "assets/f00dcafe12345678.css",
- &conditional,
- test_asset_csp(),
- )
- .await;
-
- assert_eq!(second.status(), StatusCode::NOT_MODIFIED);
- assert_eq!(entity_tag_of(&second).as_deref(), Some(entity_tag.as_str()));
- assert_eq!(
- cache_control_of(&second),
- Some(LONG_LIVED_ASSET_CACHE_CONTROL)
- );
- }
-
- #[tokio::test]
- async fn local_asset_with_a_stale_entity_tag_is_resent_in_full() {
- let fixture = LocalAssetDir::with_asset("voice_engine_bg.wasm", b"\0asm");
-
- let mut conditional = HeaderMap::new();
- conditional.insert(
- header::IF_NONE_MATCH,
- HeaderValue::from_static("\"stale-from-a-previous-build\""),
- );
- let response = serve_local_asset(
- &fixture.files(),
- "assets/voice_engine_bg.wasm",
- &conditional,
- test_asset_csp(),
- )
- .await;
-
- assert_eq!(response.status(), StatusCode::OK);
- assert_eq!(
- cache_control_of(&response),
- Some(REVALIDATED_ASSET_CACHE_CONTROL)
- );
- assert!(
- entity_tag_of(&response).is_some(),
- "a year-long asset with no validator forces a full re-download on any revalidation"
- );
- }
-
- #[tokio::test]
- async fn a_local_content_hashed_asset_is_promised_to_never_change() {
- let fixture = LocalAssetDir::with_asset("2d715e4730758083.worker.js", b"self.onmessage=0");
-
- let response = serve_local_asset(
- &fixture.files(),
- "assets/2d715e4730758083.worker.js",
- &HeaderMap::new(),
- test_asset_csp(),
- )
- .await;
-
- assert_eq!(response.status(), StatusCode::OK);
- assert_eq!(
- cache_control_of(&response),
- Some(LONG_LIVED_ASSET_CACHE_CONTROL)
- );
- assert!(is_hashed_asset("assets/2d715e4730758083.worker.js"));
- }
-
- fn accept_encoding(value: &'static str) -> HeaderMap {
- let mut headers = HeaderMap::new();
- headers.insert(header::ACCEPT_ENCODING, HeaderValue::from_static(value));
- headers
- }
-
- fn content_encoding_of(response: &Response) -> Option<&str> {
- response
- .headers()
- .get(header::CONTENT_ENCODING)
- .and_then(|value| value.to_str().ok())
- }
-
- fn varies_on_accept_encoding(response: &Response) -> bool {
- response
- .headers()
- .get_all(header::VARY)
- .iter()
- .any(|value| {
- value
- .to_str()
- .is_ok_and(|value| value.eq_ignore_ascii_case("accept-encoding"))
- })
- }
-
- async fn body_bytes(response: Response) -> Vec<u8> {
- axum::body::to_bytes(response.into_body(), usize::MAX)
- .await
- .unwrap()
- .to_vec()
- }
-
- #[tokio::test]
- async fn a_local_asset_is_served_from_its_precompressed_brotli_sibling() {
- let fixture = LocalAssetDir::with_asset("356aaade04a117b1.js", b"console.log(1)")
- .and_sibling("356aaade04a117b1.js.br", b"brotli-bytes");
-
- let response = serve_local_asset(
- &fixture.files(),
- "assets/356aaade04a117b1.js",
- &accept_encoding("gzip, deflate, br, zstd"),
- test_asset_csp(),
- )
- .await;
-
- assert_eq!(content_encoding_of(&response), Some("br"));
- assert!(varies_on_accept_encoding(&response));
- assert_eq!(
- response
- .headers()
- .get(header::CONTENT_TYPE)
- .and_then(|value| value.to_str().ok()),
- Some("application/javascript; charset=utf-8"),
- "the encoding must not leak into the media type the browser parses"
- );
- assert_eq!(
- body_bytes(response).await,
- b"brotli-bytes",
- "the sibling produced at build time must reach the wire unmodified"
- );
- }
-
- #[tokio::test]
- async fn a_local_asset_falls_back_to_the_raw_file_without_a_sibling() {
- let fixture = LocalAssetDir::with_asset("469e0b8f10c496a1.css", b"body{color:red}");
-
- let response = serve_local_asset(
- &fixture.files(),
- "assets/469e0b8f10c496a1.css",
- &accept_encoding("gzip, deflate, br"),
- test_asset_csp(),
- )
- .await;
-
- assert_eq!(response.status(), StatusCode::OK);
- assert_eq!(content_encoding_of(&response), None);
- assert!(varies_on_accept_encoding(&response));
- assert_eq!(body_bytes(response).await, b"body{color:red}");
- }
-
- #[tokio::test]
- async fn a_local_asset_only_uses_an_encoding_the_client_accepted() {
- let fixture = LocalAssetDir::with_asset("488b87159423ca35.js", b"console.log(2)")
- .and_sibling("488b87159423ca35.js.br", b"brotli-bytes")
- .and_sibling("488b87159423ca35.js.gz", b"gzip-bytes");
-
- let gzip_only = serve_local_asset(
- &fixture.files(),
- "assets/488b87159423ca35.js",
- &accept_encoding("gzip, deflate"),
- test_asset_csp(),
- )
- .await;
- assert_eq!(content_encoding_of(&gzip_only), Some("gzip"));
- assert_eq!(body_bytes(gzip_only).await, b"gzip-bytes");
-
- let identity = serve_local_asset(
- &fixture.files(),
- "assets/488b87159423ca35.js",
- &HeaderMap::new(),
- test_asset_csp(),
- )
- .await;
- assert_eq!(
- content_encoding_of(&identity),
- None,
- "a client that advertised no encoding cannot decode the sibling"
- );
- assert_eq!(body_bytes(identity).await, b"console.log(2)");
- }
-
- #[tokio::test]
- async fn a_local_asset_refuses_a_sibling_the_client_scored_zero() {
- let fixture = LocalAssetDir::with_asset("2d715e4730758083.worker.js", b"self.onmessage=0")
- .and_sibling("2d715e4730758083.worker.js.br", b"brotli-bytes");
-
- let response = serve_local_asset(
- &fixture.files(),
- "assets/2d715e4730758083.worker.js",
- &accept_encoding("br;q=0, gzip"),
- test_asset_csp(),
- )
- .await;
-
- assert_eq!(content_encoding_of(&response), None);
- assert_eq!(body_bytes(response).await, b"self.onmessage=0");
- }
-
- #[tokio::test]
- async fn a_precompressed_variant_has_its_own_validator() {
- let fixture = LocalAssetDir::with_asset("f00dcafe12345678.css", b"body{}")
- .and_sibling("f00dcafe12345678.css.br", b"brotli-bytes-are-longer");
-
- let brotli = serve_local_asset(
- &fixture.files(),
- "assets/f00dcafe12345678.css",
- &accept_encoding("br"),
- test_asset_csp(),
- )
- .await;
- let brotli_tag = entity_tag_of(&brotli).expect("the brotli variant has a validator");
-
- let identity = serve_local_asset(
- &fixture.files(),
- "assets/f00dcafe12345678.css",
- &HeaderMap::new(),
- test_asset_csp(),
- )
- .await;
- let identity_tag = entity_tag_of(&identity).expect("the raw file has a validator");
-
- assert_ne!(
- brotli_tag, identity_tag,
- "two encodings sharing one validator let a cache hand brotli to a client that asked for identity"
- );
-
- let mut conditional = accept_encoding("br");
- conditional.insert(
- header::IF_NONE_MATCH,
- HeaderValue::from_str(&brotli_tag).unwrap(),
- );
- let revalidated = serve_local_asset(
- &fixture.files(),
- "assets/f00dcafe12345678.css",
- &conditional,
- test_asset_csp(),
- )
- .await;
- assert_eq!(revalidated.status(), StatusCode::NOT_MODIFIED);
- assert!(varies_on_accept_encoding(&revalidated));
- }
-
- #[tokio::test]
- async fn a_range_over_a_precompressed_sibling_describes_the_encoded_bytes() {
- let fixture = LocalAssetDir::with_asset("356aaade04a117b1.js", b"console.log(1)")
- .and_sibling("356aaade04a117b1.js.br", b"0123456789");
-
- let mut ranged = accept_encoding("br");
- ranged.insert(header::RANGE, HeaderValue::from_static("bytes=4-6"));
- let response = serve_local_asset(
- &fixture.files(),
- "assets/356aaade04a117b1.js",
- &ranged,
- test_asset_csp(),
- )
- .await;
-
- assert_eq!(response.status(), StatusCode::PARTIAL_CONTENT);
- assert_eq!(content_encoding_of(&response), Some("br"));
- assert_eq!(
- response
- .headers()
- .get(header::CONTENT_RANGE)
- .and_then(|value| value.to_str().ok()),
- Some("bytes 4-6/10"),
- "a range counted over the raw file cannot be reassembled from the encoded bytes we sent"
- );
- assert_eq!(
- response
- .headers()
- .get(header::CONTENT_LENGTH)
- .and_then(|value| value.to_str().ok()),
- Some("3")
- );
- assert_eq!(body_bytes(response).await, b"456");
- }
-
- async fn spawn_encoded_upstream(
- content_encoding: &'static str,
- body: &'static str,
- ) -> (String, Arc<std::sync::Mutex<Option<String>>>) {
- let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
- let addr = listener.local_addr().unwrap();
- let observed_accept_encoding: Arc<std::sync::Mutex<Option<String>>> =
- Arc::new(std::sync::Mutex::new(None));
- let recorder = Arc::clone(&observed_accept_encoding);
- let router = Router::new().fallback(move |request: HttpRequest<Body>| {
- let recorder = Arc::clone(&recorder);
- async move {
- let received = request
- .headers()
- .get(header::ACCEPT_ENCODING)
- .and_then(|value| value.to_str().ok())
- .map(str::to_owned);
- *recorder.lock().unwrap() = received;
- let mut response = Response::new(Body::from(body));
- response.headers_mut().insert(
- header::CONTENT_ENCODING,
- HeaderValue::from_static(content_encoding),
- );
- response
- }
- });
- tokio::spawn(async move {
- axum::serve(listener, router).await.unwrap();
- });
- (format!("http://{addr}"), observed_accept_encoding)
- }
-
- #[tokio::test]
- async fn a_cdn_backed_asset_streams_the_upstream_encoding_untouched() {
- let (endpoint, observed_accept_encoding) =
- spawn_encoded_upstream("br", "already-brotli").await;
- let state = upstream_backed_state(&endpoint);
- let request = HttpRequest::builder()
- .uri("/assets/356aaade04a117b1.js")
- .header(header::ACCEPT_ENCODING, "gzip, deflate, br")
- .body(Body::empty())
- .unwrap();
-
- let response = proxy_assets(
- State(state),
- Path("356aaade04a117b1.js".to_owned()),
- request,
- )
- .await;
-
- assert_eq!(
- observed_accept_encoding.lock().unwrap().as_deref(),
- Some("gzip, deflate, br"),
- "blocking accept-encoding forces the origin to hand us bytes it already had compressed"
- );
- assert_eq!(
- content_encoding_of(&response),
- Some("br"),
- "dropping content-encoding turns compressed upstream bytes into an undecodable body"
- );
- assert!(varies_on_accept_encoding(&response));
- assert_eq!(body_bytes(response).await, b"already-brotli");
- }
-
- #[tokio::test]
- async fn a_cdn_backed_asset_keeps_the_upstream_content_length() {
- let (endpoint, _observed_accept_encoding) =
- spawn_encoded_upstream("gzip", "0123456789").await;
- let state = upstream_backed_state(&endpoint);
- let request = HttpRequest::builder()
- .uri("/assets/voice_engine_bg.wasm")
- .header(header::ACCEPT_ENCODING, "gzip")
- .body(Body::empty())
- .unwrap();
-
- let response = proxy_assets(
- State(state),
- Path("voice_engine_bg.wasm".to_owned()),
- request,
- )
- .await;
-
- assert_eq!(
- response
- .headers()
- .get(header::CONTENT_LENGTH)
- .and_then(|value| value.to_str().ok()),
- Some("10"),
- "a client that cannot see the encoded length cannot show download progress"
- );
- }
-
- const COMPRESSIBLE_BODY: &[u8] =
- b"the default compression predicate ignores anything under thirty-two bytes";
-
- #[tokio::test]
- async fn an_asset_without_a_sibling_is_still_compressed_before_it_leaves() {
- let fixture = LocalAssetDir::with_asset("356aaade04a117b1.js", COMPRESSIBLE_BODY);
- let router = super::super::build_router(locally_backed_state(fixture.dir()));
-
- let asset = router
- .oneshot(
- HttpRequest::builder()
- .uri("/assets/356aaade04a117b1.js")
- .header(header::ACCEPT_ENCODING, "gzip")
- .body(Body::empty())
- .unwrap(),
- )
- .await
- .unwrap();
-
- assert_eq!(asset.status(), StatusCode::OK);
- assert_eq!(
- content_encoding_of(&asset),
- Some("gzip"),
- "an extension the build-time step does not cover must not fall off a bandwidth cliff"
- );
- assert_ne!(body_bytes(asset).await, COMPRESSIBLE_BODY);
- }
-
- #[tokio::test]
- async fn a_passed_through_cdn_encoding_is_never_recompressed_by_the_layer() {
- let (endpoint, _observed_accept_encoding) = spawn_encoded_upstream(
- "br",
- "already brotli, and long enough to clear the thirty-two byte floor",
- )
- .await;
- let router = super::super::build_router(upstream_backed_state(&endpoint));
-
- let response = router
- .oneshot(
- HttpRequest::builder()
- .uri("/assets/356aaade04a117b1.js")
- .header(header::ACCEPT_ENCODING, "gzip, deflate, br")
- .body(Body::empty())
- .unwrap(),
- )
- .await
- .unwrap();
-
- assert_eq!(content_encoding_of(&response), Some("br"));
- assert_eq!(
- body_bytes(response).await,
- b"already brotli, and long enough to clear the thirty-two byte floor",
- "re-encoding upstream bytes that already have an encoding breaks every browser"
- );
- }
-
- #[tokio::test]
- async fn a_precompressed_sibling_reaches_the_client_through_the_router() {
- let fixture = LocalAssetDir::with_asset("488b87159423ca35.js", COMPRESSIBLE_BODY)
- .and_sibling("488b87159423ca35.js.br", b"brotli-bytes");
- let router = super::super::build_router(locally_backed_state(fixture.dir()));
-
- let response = router
- .oneshot(
- HttpRequest::builder()
- .uri("/assets/488b87159423ca35.js")
- .header(header::ACCEPT_ENCODING, "gzip, deflate, br")
- .body(Body::empty())
- .unwrap(),
- )
- .await
- .unwrap();
-
- assert_eq!(content_encoding_of(&response), Some("br"));
- assert_eq!(
- body_bytes(response).await,
- b"brotli-bytes",
- "re-encoding the sibling would double-compress it and break every browser"
- );
- }
-
- #[test]
- fn known_js_asset_overrides_upstream_octet_stream() {
- let mut headers = HeaderMap::new();
- headers.insert(
- header::CONTENT_TYPE,
- HeaderValue::from_static("application/octet-stream"),
- );
-
- apply_test_asset_policy(&mut headers, "356aaade04a117b1.js", StatusCode::OK);
-
- assert_eq!(
- headers
- .get(header::CONTENT_TYPE)
- .and_then(|value| value.to_str().ok()),
- Some("application/javascript; charset=utf-8")
- );
- }
-
- #[test]
- fn proxied_font_gains_cors_when_upstream_omits_it() {
- let mut headers = HeaderMap::new();
- headers.insert(
- header::CONTENT_TYPE,
- HeaderValue::from_static("application/octet-stream"),
- );
-
- apply_test_asset_policy(&mut headers, "0018072843a46dc4.woff2", StatusCode::OK);
-
- assert_eq!(
- headers
- .get(header::ACCESS_CONTROL_ALLOW_ORIGIN)
- .and_then(|value| value.to_str().ok()),
- Some("*")
- );
- }
-
- #[test]
- fn proxied_font_cors_overrides_a_narrower_upstream_value() {
- let mut headers = HeaderMap::new();
- headers.insert(header::CONTENT_TYPE, HeaderValue::from_static("font/woff2"));
- headers.insert(
- header::ACCESS_CONTROL_ALLOW_ORIGIN,
- HeaderValue::from_static("https://example.invalid"),
- );
-
- apply_test_asset_policy(&mut headers, "0018072843a46dc4.woff2", StatusCode::OK);
-
- assert_eq!(
- headers
- .get(header::ACCESS_CONTROL_ALLOW_ORIGIN)
- .and_then(|value| value.to_str().ok()),
- Some("*")
- );
- }
-
- #[test]
- fn proxied_font_cors_tolerates_a_content_type_parameter() {
- let mut headers = HeaderMap::new();
- headers.insert(
- header::CONTENT_TYPE,
- HeaderValue::from_static("font/woff2; charset=binary"),
- );
-
- apply_test_asset_policy(&mut headers, "font-download", StatusCode::OK);
-
- assert_eq!(
- headers
- .get(header::ACCESS_CONTROL_ALLOW_ORIGIN)
- .and_then(|value| value.to_str().ok()),
- Some("*")
- );
- }
-
- #[test]
- fn proxied_non_font_keeps_upstream_cors_untouched() {
- let mut headers = HeaderMap::new();
- headers.insert(
- header::CONTENT_TYPE,
- HeaderValue::from_static("application/javascript; charset=utf-8"),
- );
-
- apply_test_asset_policy(&mut headers, "356aaade04a117b1.js", StatusCode::OK);
-
- assert!(
- headers.get(header::ACCESS_CONTROL_ALLOW_ORIGIN).is_none(),
- "non-font assets are same-origin and must not gain a wildcard"
- );
- }
-
- #[tokio::test]
- async fn a_local_asset_is_refused_once_the_read_slots_are_gone() {
- let fixture = LocalAssetDir::with_asset("356aaade04a117b1.js", b"console.log(1)");
- let budgets = AppProxyBudgets::default();
- let files = fixture.files_with(&budgets);
- let held = budgets
- .local_read_slots
- .clone()
- .try_acquire_many_owned(
- u32::try_from(crate::state::LOCAL_FILE_READS_IN_FLIGHT_MAX).unwrap(),
- )
- .expect("a fresh budget holds every local read slot");
-
- let refused = serve_local_asset(
- &files,
- "assets/356aaade04a117b1.js",
- &HeaderMap::new(),
- test_asset_csp(),
- )
- .await;
- assert_eq!(refused.status(), StatusCode::SERVICE_UNAVAILABLE);
- assert_eq!(
- refused
- .headers()
- .get(header::CACHE_CONTROL)
- .and_then(|value| value.to_str().ok()),
- Some("no-store"),
- "a cached refusal would pin the outage for every later reader"
- );
-
- drop(held);
- let served = serve_local_asset(
- &files,
- "assets/356aaade04a117b1.js",
- &HeaderMap::new(),
- test_asset_csp(),
- )
- .await;
- assert_eq!(served.status(), StatusCode::OK);
- }
-
- #[tokio::test]
- async fn an_open_local_asset_response_never_holds_a_read_slot() {
- let fixture = LocalAssetDir::with_asset("356aaade04a117b1.js", b"console.log(1)");
- let budgets = AppProxyBudgets::default();
- let files = fixture.files_with(&budgets);
-
- let mut open = Vec::with_capacity(crate::state::LOCAL_FILE_READS_IN_FLIGHT_MAX + 1);
- for _ in 0..=crate::state::LOCAL_FILE_READS_IN_FLIGHT_MAX {
- open.push(
- serve_local_asset(
- &files,
- "assets/356aaade04a117b1.js",
- &HeaderMap::new(),
- test_asset_csp(),
- )
- .await,
- );
- }
-
- let refused = open
- .iter()
- .filter(|response| response.status() != StatusCode::OK)
- .count();
- assert_eq!(
- refused, 0,
- "{refused} readers were turned away while earlier responses were still open"
- );
-
- let body = axum::body::to_bytes(open.pop().unwrap().into_body(), usize::MAX)
- .await
- .unwrap();
- assert_eq!(
- body.as_ref(),
- b"console.log(1)",
- "a response served past the read slot count had the wrong bytes"
- );
- }
-
- async fn spawn_counting_upstream() -> (String, Arc<AtomicU64>) {
- let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
- let addr = listener.local_addr().unwrap();
- let hits = Arc::new(AtomicU64::new(0));
- let counter = Arc::clone(&hits);
- let router = Router::new().fallback(move || {
- let counter = Arc::clone(&counter);
- async move {
- counter.fetch_add(1, Ordering::Relaxed);
- Response::new(Body::from("cdn-bytes"))
- }
- });
- tokio::spawn(async move {
- axum::serve(listener, router).await.unwrap();
- });
- (format!("http://{addr}"), hits)
- }
-
- fn cdn_and_local_state(cdn_endpoint: &str, static_dir: &str) -> AppState {
- let mut state = upstream_backed_state(cdn_endpoint);
- let mut config = (*state.config).clone();
- config.static_dir = static_dir.to_owned();
- state.local_files =
- LocalFileStore::load_blocking(std::path::Path::new(static_dir), &state.budgets)
- .unwrap();
- state.config = Arc::new(config);
- state.bundled_app_assets = bundles_app_assets(static_dir);
- state
- }
-
- async fn get_asset(state: AppState, asset_path: &str) -> Response {
- super::super::build_router(state)
- .oneshot(
- HttpRequest::builder()
- .uri(format!("/assets/{asset_path}"))
- .body(Body::empty())
- .unwrap(),
- )
- .await
- .unwrap()
- }
-
- #[tokio::test]
- async fn an_image_with_the_app_built_in_serves_assets_itself_when_a_cdn_is_set() {
- let fixture = LocalAssetDir::with_asset("356aaade04a117b1.js", b"local-bytes");
- let (endpoint, hits) = spawn_counting_upstream().await;
- let state = cdn_and_local_state(&endpoint, fixture.dir());
- assert!(state.bundled_app_assets);
-
- let response = get_asset(state, "356aaade04a117b1.js").await;
-
- assert_eq!(response.status(), StatusCode::OK);
- assert_eq!(body_bytes(response).await, b"local-bytes");
- assert_eq!(
- hits.load(Ordering::Relaxed),
- 0,
- "a cdn that pulls from this instance would send the request back here"
- );
- }
-
- #[tokio::test]
- async fn an_image_without_the_app_built_in_still_takes_assets_from_the_cdn() {
- let fixture = LocalAssetDir::with_asset("fonts-latin.txt", b"font list");
- let (endpoint, hits) = spawn_counting_upstream().await;
- let state = cdn_and_local_state(&endpoint, fixture.dir());
- assert!(!state.bundled_app_assets);
-
- let response = get_asset(state, "356aaade04a117b1.js").await;
-
- assert_eq!(response.status(), StatusCode::OK);
- assert_eq!(body_bytes(response).await, b"cdn-bytes");
- assert_eq!(hits.load(Ordering::Relaxed), 1);
- }
-}
diff --git a/fluxer_app_proxy/src/routes/file_stream.rs b/fluxer_app_proxy/src/routes/file_stream.rs
index deb48bb9a..b02e6e68f 100644
--- a/fluxer_app_proxy/src/routes/file_stream.rs
+++ b/fluxer_app_proxy/src/routes/file_stream.rs
@@ -92,216 +92,3 @@ fn if_range_matches(headers: &HeaderMap, entity_tag: Option<&str>) -> bool {
};
entity_tag.is_some_and(|tag| raw.trim() == tag)
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use std::sync::atomic::{AtomicU64, Ordering};
-
- struct StreamedFile {
- root: std::path::PathBuf,
- }
-
- impl StreamedFile {
- fn with_bytes(bytes: &[u8]) -> Self {
- static NEXT_FIXTURE: AtomicU64 = AtomicU64::new(0);
- let unique = NEXT_FIXTURE.fetch_add(1, Ordering::Relaxed);
- let pid = std::process::id();
- let root = std::env::temp_dir().join(format!("fluxer-file-stream-{pid}-{unique}"));
- std::fs::create_dir_all(&root).unwrap();
- std::fs::write(root.join("payload.bin"), bytes).unwrap();
- Self { root }
- }
-
- fn path(&self) -> std::path::PathBuf {
- self.root.join("payload.bin")
- }
- }
-
- impl Drop for StreamedFile {
- fn drop(&mut self) {
- let _ = std::fs::remove_dir_all(&self.root);
- }
- }
-
- fn range_headers(value: &str) -> HeaderMap {
- let mut headers = HeaderMap::new();
- headers.insert(header::RANGE, HeaderValue::from_str(value).unwrap());
- headers
- }
-
- fn header_of(response: &Response, name: header::HeaderName) -> Option<String> {
- response
- .headers()
- .get(name)
- .and_then(|value| value.to_str().ok())
- .map(ToOwned::to_owned)
- }
-
- async fn body_of(response: Response) -> Vec<u8> {
- axum::body::to_bytes(response.into_body(), usize::MAX)
- .await
- .unwrap()
- .to_vec()
- }
-
- #[tokio::test]
- async fn a_whole_file_is_streamed_with_a_length_and_a_range_offer() {
- let fixture = StreamedFile::with_bytes(b"0123456789");
-
- let response = stream_file(&fixture.path(), &HeaderMap::new(), None)
- .await
- .unwrap();
-
- assert_eq!(response.status(), StatusCode::OK);
- assert_eq!(
- header_of(&response, header::CONTENT_LENGTH).as_deref(),
- Some("10")
- );
- assert_eq!(
- header_of(&response, header::ACCEPT_RANGES).as_deref(),
- Some("bytes")
- );
- assert_eq!(body_of(response).await, b"0123456789");
- }
-
- #[tokio::test]
- async fn a_resumed_download_gets_only_the_bytes_it_asked_for() {
- let fixture = StreamedFile::with_bytes(b"0123456789");
-
- let response = stream_file(&fixture.path(), &range_headers("bytes=4-6"), None)
- .await
- .unwrap();
-
- assert_eq!(
- response.status(),
- StatusCode::PARTIAL_CONTENT,
- "a client resuming a partial download re-fetches the whole file on a 200"
- );
- assert_eq!(
- header_of(&response, header::CONTENT_RANGE).as_deref(),
- Some("bytes 4-6/10")
- );
- assert_eq!(
- header_of(&response, header::CONTENT_LENGTH).as_deref(),
- Some("3")
- );
- assert_eq!(body_of(response).await, b"456");
- }
-
- #[tokio::test]
- async fn an_open_ended_range_runs_to_the_last_byte() {
- let fixture = StreamedFile::with_bytes(b"0123456789");
-
- let response = stream_file(&fixture.path(), &range_headers("bytes=7-"), None)
- .await
- .unwrap();
-
- assert_eq!(response.status(), StatusCode::PARTIAL_CONTENT);
- assert_eq!(
- header_of(&response, header::CONTENT_RANGE).as_deref(),
- Some("bytes 7-9/10")
- );
- assert_eq!(body_of(response).await, b"789");
- }
-
- #[tokio::test]
- async fn a_suffix_range_returns_the_tail() {
- let fixture = StreamedFile::with_bytes(b"0123456789");
-
- let response = stream_file(&fixture.path(), &range_headers("bytes=-3"), None)
- .await
- .unwrap();
-
- assert_eq!(response.status(), StatusCode::PARTIAL_CONTENT);
- assert_eq!(
- header_of(&response, header::CONTENT_RANGE).as_deref(),
- Some("bytes 7-9/10")
- );
- assert_eq!(body_of(response).await, b"789");
- }
-
- #[tokio::test]
- async fn a_range_past_the_end_is_refused_with_the_real_size() {
- let fixture = StreamedFile::with_bytes(b"0123456789");
-
- let response = stream_file(&fixture.path(), &range_headers("bytes=50-60"), None)
- .await
- .unwrap();
-
- assert_eq!(response.status(), StatusCode::RANGE_NOT_SATISFIABLE);
- assert_eq!(
- header_of(&response, header::CONTENT_RANGE).as_deref(),
- Some("bytes */10")
- );
- }
-
- #[tokio::test]
- async fn a_multi_range_request_falls_back_to_the_whole_file() {
- let fixture = StreamedFile::with_bytes(b"0123456789");
-
- let response = stream_file(&fixture.path(), &range_headers("bytes=0-1,5-6"), None)
- .await
- .unwrap();
-
- assert_eq!(response.status(), StatusCode::OK);
- assert_eq!(body_of(response).await, b"0123456789");
- }
-
- #[tokio::test]
- async fn a_range_against_a_stale_validator_resends_the_whole_file() {
- let fixture = StreamedFile::with_bytes(b"0123456789");
- let mut headers = range_headers("bytes=4-6");
- headers.insert(
- header::IF_RANGE,
- HeaderValue::from_static("\"from-a-previous-build\""),
- );
-
- let response = stream_file(&fixture.path(), &headers, Some("\"current\""))
- .await
- .unwrap();
-
- assert_eq!(
- response.status(),
- StatusCode::OK,
- "stitching a range from a redeployed build onto a stale prefix corrupts the download"
- );
- assert_eq!(body_of(response).await, b"0123456789");
- }
-
- #[tokio::test]
- async fn a_range_against_the_current_validator_is_honoured() {
- let fixture = StreamedFile::with_bytes(b"0123456789");
- let mut headers = range_headers("bytes=4-6");
- headers.insert(header::IF_RANGE, HeaderValue::from_static("\"current\""));
-
- let response = stream_file(&fixture.path(), &headers, Some("\"current\""))
- .await
- .unwrap();
-
- assert_eq!(response.status(), StatusCode::PARTIAL_CONTENT);
- assert_eq!(body_of(response).await, b"456");
- }
-
- #[tokio::test]
- async fn a_missing_file_is_reported_as_not_found() {
- let fixture = StreamedFile::with_bytes(b"0123456789");
-
- let err = stream_file(&fixture.root.join("absent.bin"), &HeaderMap::new(), None)
- .await
- .expect_err("a missing file must not stream an empty body");
-
- assert_eq!(err.kind(), std::io::ErrorKind::NotFound);
- }
-
- #[tokio::test]
- async fn a_directory_is_never_streamed_as_a_file() {
- let fixture = StreamedFile::with_bytes(b"0123456789");
-
- let err = stream_file(&fixture.root, &HeaderMap::new(), None)
- .await
- .expect_err("a directory answered as 200 promises a length no body can deliver");
-
- assert_ne!(err.kind(), std::io::ErrorKind::NotFound);
- }
-}
diff --git a/fluxer_app_proxy/src/routes/health.rs b/fluxer_app_proxy/src/routes/health.rs
index 9094e778a..cf4659b61 100644
--- a/fluxer_app_proxy/src/routes/health.rs
+++ b/fluxer_app_proxy/src/routes/health.rs
@@ -7,69 +7,3 @@ pub async fn health() -> &'static str {
pub async fn ready() -> &'static str {
"OK"
}
-
-#[cfg(test)]
-mod tests {
- use crate::config::AppProxyConfig;
- use crate::state::{AppState, SpaIndexSource, build_http_client};
- use axum::body::Body;
- use axum::http::{Request as HttpRequest, StatusCode};
- use std::sync::Arc;
- use tower::ServiceExt;
-
- fn probe_state() -> AppState {
- let config = AppProxyConfig::from_env();
- let csp = Arc::new(
- crate::csp::CompiledCspPolicy::from_config(&config)
- .expect("the test configuration must compile to a valid CSP"),
- );
- let budgets = crate::state::AppProxyBudgets::default();
- let local_files =
- crate::local_files::LocalFileStore::load_blocking(std::path::Path::new("."), &budgets)
- .expect("the test static directory must exist");
- AppState {
- branding: crate::branding_images::InstanceBranding::from_config(&config),
- config: Arc::new(config),
- csp,
- http_client: build_http_client().unwrap(),
- spa_index_source: SpaIndexSource::bundled(""),
- local_asset_prefixes: None,
- bundled_app_assets: false,
- budgets,
- local_files,
- }
- }
-
- async fn probe(state: AppState, path: &str) -> (StatusCode, String) {
- let response = crate::routes::build_router(state)
- .oneshot(
- HttpRequest::builder()
- .uri(path)
- .body(Body::empty())
- .unwrap(),
- )
- .await
- .unwrap();
- let status = response.status();
- let body = axum::body::to_bytes(response.into_body(), usize::MAX)
- .await
- .unwrap();
- (status, String::from_utf8(body.to_vec()).unwrap())
- }
-
- #[tokio::test]
- async fn liveness_answers_without_any_upstream() {
- assert_eq!(
- probe(probe_state(), "/_health").await,
- (StatusCode::OK, "OK".to_owned())
- );
- }
-
- #[tokio::test]
- async fn readiness_needs_no_discovery_upstream() {
- assert_eq!(
- probe(probe_state(), "/_ready").await,
- (StatusCode::OK, "OK".to_owned())
- );
- }
-}
diff --git a/fluxer_app_proxy/src/routes/spa_static.rs b/fluxer_app_proxy/src/routes/spa_static.rs
index 2af7d16ba..59106f699 100644
--- a/fluxer_app_proxy/src/routes/spa_static.rs
+++ b/fluxer_app_proxy/src/routes/spa_static.rs
@@ -195,317 +195,3 @@ async fn serve_static_text_file_with_substitutions(
apply_static_resource_security_policy(response.headers_mut(), state.csp.asset_header());
response
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- fn substitute_placeholders(
- text: &str,
- static_cdn_endpoint: &str,
- scope_extensions: Option<&[String]>,
- ) -> String {
- let text = text.replace("{{STATIC_CDN_ENDPOINT}}", static_cdn_endpoint);
- match scope_extensions {
- Some(origins) => finish_manifest(text, origins, None),
- None => text,
- }
- }
-
- const BUILT_MANIFEST: &str = r#"{
- "id": "/",
- "start_url": "/app",
- "scope": "/",
- "scope_extensions": [],
- "icons": [
- {
- "src": "{{STATIC_CDN_ENDPOINT}}/web/android-chrome-192x192.png"
- }
- ]
-}"#;
-
- fn substituted_manifest(origins: &[&str]) -> serde_json::Value {
- let origins: Vec<String> = origins.iter().map(|origin| (*origin).to_owned()).collect();
- let text =
- substitute_placeholders(BUILT_MANIFEST, "https://fluxerstatic.com", Some(&origins));
- serde_json::from_str(&text).expect("substituted manifest must stay valid JSON")
- }
-
- #[test]
- fn manifest_scope_extensions_default_to_the_built_empty_list() {
- let manifest = substituted_manifest(&[]);
- assert_eq!(manifest["scope_extensions"], serde_json::json!([]));
- assert_eq!(
- manifest["icons"][0]["src"],
- "https://fluxerstatic.com/web/android-chrome-192x192.png"
- );
- }
-
- #[test]
- fn manifest_scope_extensions_list_each_configured_origin() {
- let manifest = substituted_manifest(&["https://fluxer.com", "https://canary.fluxer.com"]);
- assert_eq!(
- manifest["scope_extensions"],
- serde_json::json!([
- { "type": "origin", "origin": "https://fluxer.com" },
- { "type": "origin", "origin": "https://canary.fluxer.com" }
- ])
- );
- assert_eq!(manifest["id"], "/");
- assert_eq!(manifest["start_url"], "/app");
- }
-
- #[test]
- fn manifest_scope_extensions_are_added_when_the_build_has_none() {
- let text = substitute_placeholders(
- r#"{"id":"/"}"#,
- "",
- Some(&["https://fluxer.com".to_owned()]),
- );
- let manifest: serde_json::Value = serde_json::from_str(&text).expect("valid JSON");
- assert_eq!(
- manifest["scope_extensions"],
- serde_json::json!([{ "type": "origin", "origin": "https://fluxer.com" }])
- );
- }
-
- #[test]
- fn other_text_files_are_left_alone() {
- let origins = ["https://fluxer.com".to_owned()];
- assert_eq!(
- substitute_placeholders(
- "not json {{STATIC_CDN_ENDPOINT}}",
- "https://cdn",
- Some(&origins)
- ),
- "not json https://cdn"
- );
- assert_eq!(
- substitute_placeholders(BUILT_MANIFEST, "", None),
- BUILT_MANIFEST.replace("{{STATIC_CDN_ENDPOINT}}", "")
- );
- }
-
- const GENERATED_MANIFEST: &str = r##"{
- "name": "Fluxer",
- "short_name": "Fluxer",
- "description": "Fluxer is a free and open source instant messaging and VoIP platform built for friends, groups, and communities.",
- "id": "/",
- "start_url": "/app",
- "display": "standalone",
- "orientation": "portrait-primary",
- "theme_color": "#4641D9",
- "background_color": "#2b2d31",
- "categories": ["social", "communication"],
- "lang": "en",
- "scope": "/",
- "scope_extensions": [],
- "icons": [
- {
- "src": "{{STATIC_CDN_ENDPOINT}}/web/android-chrome-192x192.png",
- "sizes": "192x192",
- "type": "image/png",
- "purpose": "maskable any"
- },
- {
- "src": "{{STATIC_CDN_ENDPOINT}}/web/android-chrome-512x512.png",
- "sizes": "512x512",
- "type": "image/png",
- "purpose": "maskable any"
- }
- ]
-}"##;
-
- fn branded_manifest(branding: &BrandingSnapshot) -> serde_json::Value {
- let text = finish_manifest(
- GENERATED_MANIFEST.replace("{{STATIC_CDN_ENDPOINT}}", ""),
- &[],
- Some(branding),
- );
- serde_json::from_str(&text).expect("a branded manifest must stay valid JSON")
- }
-
- fn assert_installable_shape(manifest: &serde_json::Value) {
- for key in ["name", "short_name", "id", "start_url", "scope", "display"] {
- assert!(
- manifest[key]
- .as_str()
- .is_some_and(|value| !value.is_empty()),
- "the manifest lost its {key}"
- );
- }
- let icons = manifest["icons"]
- .as_array()
- .expect("the manifest lost its icons");
- assert!(icons.iter().any(|icon| {
- icon["src"].as_str().is_some_and(|src| !src.is_empty())
- && icon["purpose"]
- .as_str()
- .is_some_and(|purpose| purpose.split(' ').any(|purpose| purpose == "any"))
- }));
- }
-
- #[test]
- fn a_branded_product_name_stays_a_json_string() {
- let product_name = "A \"quoted\" \\ name</script>\n\u{2028}";
- let manifest = branded_manifest(&BrandingSnapshot {
- product_name: Some(product_name.into()),
- ..BrandingSnapshot::default()
- });
-
- assert_eq!(manifest["name"], product_name);
- assert_eq!(manifest["short_name"], product_name);
- }
-
- #[test]
- fn the_official_manifest_is_left_byte_identical() {
- let text =
- GENERATED_MANIFEST.replace("{{STATIC_CDN_ENDPOINT}}", "https://fluxerstatic.com");
- assert_eq!(finish_manifest(text.clone(), &[], None), text);
- }
-
- fn static_dir_with_generated_files() -> std::path::PathBuf {
- static NEXT_DIR: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
- let unique = NEXT_DIR.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
- let root =
- std::env::temp_dir().join(format!("fluxer-spa-static-{}-{unique}", std::process::id()));
- std::fs::create_dir_all(&root).unwrap();
- std::fs::write(root.join("manifest.json"), GENERATED_MANIFEST).unwrap();
- std::fs::write(root.join("browserconfig.xml"), GENERATED_BROWSERCONFIG).unwrap();
- root
- }
-
- fn state_serving(root: &std::path::Path, self_hosted: bool) -> AppState {
- let mut config = crate::config::AppProxyConfig::from_env();
- config.static_dir = root.to_str().unwrap().to_owned();
- config.static_cdn_endpoint = None;
- config.manifest_scope_extensions = Vec::new();
- config.self_hosted = self_hosted;
- config.branding = BrandingSnapshot {
- product_name: Some("Example".into()),
- icon_url: Some("https://example.test/icon.png".into()),
- favicon_url: Some("https://example.test/favicon.png".into()),
- theme_color: Some("#7b2ce4".into()),
- ..BrandingSnapshot::default()
- };
- let csp = std::sync::Arc::new(
- crate::csp::CompiledCspPolicy::from_config(&config)
- .expect("the test configuration must compile to a valid CSP"),
- );
- let budgets = crate::state::AppProxyBudgets::default();
- let local_files = crate::local_files::LocalFileStore::load_blocking(root, &budgets)
- .expect("the test static directory must load");
- AppState {
- branding: crate::branding_images::InstanceBranding::from_config(&config),
- config: std::sync::Arc::new(config),
- csp,
- http_client: reqwest::Client::new(),
- spa_index_source: crate::state::SpaIndexSource::bundled(""),
- local_asset_prefixes: None,
- bundled_app_assets: false,
- budgets,
- local_files,
- }
- }
-
- async fn fetch(state: AppState, path: &str) -> Response {
- use tower::ServiceExt as _;
- crate::routes::build_router(state)
- .oneshot(
- axum::http::Request::builder()
- .uri(path)
- .body(axum::body::Body::empty())
- .unwrap(),
- )
- .await
- .unwrap()
- }
-
- async fn body_of(response: Response) -> String {
- let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
- .await
- .unwrap();
- String::from_utf8(bytes.to_vec()).unwrap()
- }
-
- #[tokio::test]
- async fn the_served_manifest_is_branded_only_on_a_self_hosted_instance() {
- let root = static_dir_with_generated_files();
-
- let official = fetch(state_serving(&root, false), "/manifest.json").await;
- assert_eq!(official.status(), StatusCode::OK);
- assert_eq!(
- body_of(official).await,
- GENERATED_MANIFEST.replace("{{STATIC_CDN_ENDPOINT}}", "")
- );
-
- let self_hosted = fetch(state_serving(&root, true), "/manifest.json").await;
- assert_eq!(self_hosted.status(), StatusCode::OK);
- let manifest: serde_json::Value =
- serde_json::from_str(&body_of(self_hosted).await).unwrap();
- assert_eq!(manifest["name"], "Example");
- assert_eq!(manifest["icons"][0]["src"], "https://example.test/icon.png");
- assert_installable_shape(&manifest);
-
- std::fs::remove_dir_all(root).unwrap();
- }
-
- #[tokio::test]
- async fn every_response_asks_search_engines_not_to_index_it() {
- let root = static_dir_with_generated_files();
- std::fs::write(root.join("robots.txt"), "User-agent: *\nAllow: /\n").unwrap();
-
- for path in [
- "/",
- "/login",
- "/channels/@me",
- "/invite/abc",
- "/gift/abc",
- "/robots.txt",
- "/manifest.json",
- "/version.json",
- "/_health",
- "/web/missing.png",
- ] {
- let response = fetch(state_serving(&root, false), path).await;
- assert_eq!(
- response
- .headers()
- .get("x-robots-tag")
- .and_then(|value| value.to_str().ok()),
- Some("noindex, nofollow"),
- "{path} answered {} without a noindex directive",
- response.status()
- );
- }
-
- std::fs::remove_dir_all(root).unwrap();
- }
-
- const GENERATED_BROWSERCONFIG: &str = r#"<?xml version="1.0" encoding="utf-8"?>
-<browserconfig>
- <msapplication>
- <tile>
- <square150x150logo src="{{STATIC_CDN_ENDPOINT}}/web/mstile-150x150.png"/>
- <TileColor>#4641D9</TileColor>
- </tile>
- </msapplication>
-</browserconfig>"#;
-
- #[tokio::test]
- async fn the_fluxer_tile_is_served_only_on_the_official_instance() {
- let root = static_dir_with_generated_files();
-
- let official = fetch(state_serving(&root, false), "/browserconfig.xml").await;
- assert_eq!(official.status(), StatusCode::OK);
- assert_eq!(
- body_of(official).await,
- GENERATED_BROWSERCONFIG.replace("{{STATIC_CDN_ENDPOINT}}", "")
- );
-
- let self_hosted = fetch(state_serving(&root, true), "/browserconfig.xml").await;
- assert_eq!(self_hosted.status(), StatusCode::NOT_FOUND);
-
- std::fs::remove_dir_all(root).unwrap();
- }
-}
diff --git a/fluxer_app_proxy/src/state.rs b/fluxer_app_proxy/src/state.rs
index e2886a0c4..c42624cdf 100644
--- a/fluxer_app_proxy/src/state.rs
+++ b/fluxer_app_proxy/src/state.rs
@@ -49,13 +49,6 @@ pub enum SpaIndexSource {
}
impl SpaIndexSource {
- pub fn bundled(shell: &str) -> Self {
- Self::Bundled {
- shell: Arc::from(shell),
- auth_entry_shell: None,
- }
- }
-
pub async fn load(config: &AppProxyConfig) -> anyhow::Result<Self> {
if let Some(index_upstream_url) = &config.index_upstream_url {
return Ok(Self::Upstream(Arc::new(index_upstream_url.clone())));
@@ -117,7 +110,6 @@ impl AppState {
local_files,
})
}
-}
#[derive(Debug)]
pub enum BoundedFileReadError {
@@ -125,20 +117,6 @@ pub enum BoundedFileReadError {
Io(std::io::Error),
}
-impl std::fmt::Display for BoundedFileReadError {
- fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- match self {
- Self::TooLarge { actual, maximum } => write!(
- formatter,
- "file is {actual} bytes, exceeding the {maximum} byte limit"
- ),
- Self::Io(source) => source.fmt(formatter),
- }
- }
-}
-
-impl std::error::Error for BoundedFileReadError {}
-
pub async fn read_bounded_file(
path: &std::path::Path,
max_bytes: usize,
diff --git a/fluxer_app_proxy/src/static_asset_policy.rs b/fluxer_app_proxy/src/static_asset_policy.rs
index 051849837..27b3bdb44 100644
--- a/fluxer_app_proxy/src/static_asset_policy.rs
+++ b/fluxer_app_proxy/src/static_asset_policy.rs
@@ -247,54 +247,3 @@ fn set_known_asset_content_type(headers: &mut HeaderMap, path: &str) {
pub(crate) fn is_content_hash(value: &str) -> bool {
value.len() >= 8 && value.chars().all(|character| character.is_ascii_hexdigit())
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn hashed_asset_positive() {
- assert!(is_hashed_asset("app.a1b2c3d4.js"));
- assert!(is_hashed_asset("style-abcdef01.css"));
- }
-
- #[test]
- fn hashed_asset_accepts_bare_contenthash_filenames() {
- assert!(is_hashed_asset("assets/469e0b8f10c496a1.css"));
- assert!(is_hashed_asset("assets/a79f1c3119cd700d.woff2"));
- assert!(is_hashed_asset("/assets/488b87159423ca35.js"));
- }
-
- #[test]
- fn hashed_asset_accepts_the_contenthash_worker_bundle_name() {
- assert!(
- is_hashed_asset("assets/2d715e4730758083.worker.js"),
- "rspack emits workers as assets/[contenthash:16].worker.js"
- );
- }
-
- #[test]
- fn hashed_asset_negative() {
- assert!(!is_hashed_asset("app.js"));
- assert!(!is_hashed_asset("style.css"));
- assert!(!is_hashed_asset("a79f1c3119cd700d/app.js"));
- }
-
- #[test]
- fn the_bundled_font_licences_are_not_treated_as_content_hashed() {
- assert!(!is_hashed_asset("assets/fonts-NOTICE.txt"));
- assert!(!is_hashed_asset("assets/fonts-LICENSE-IBM-PLEX.txt"));
- }
-
- #[test]
- fn only_a_content_hashed_asset_is_promised_to_never_change() {
- assert_eq!(
- asset_cache_control("assets/469e0b8f10c496a1.css"),
- LONG_LIVED_ASSET_CACHE_CONTROL
- );
- assert_eq!(
- asset_cache_control("assets/fonts-NOTICE.txt"),
- REVALIDATED_ASSET_CACHE_CONTROL
- );
- }
-}