A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
feat(app-proxy): add LiveKit to CSP, stable self-host, cut tests
Hampus6d69823e9bcc
diff --git a/fluxer_app_proxy/src/config.rs b/fluxer_app_proxy/src/config.rsindex 75efcafb5..dc684fe0c 100644--- a/fluxer_app_proxy/src/config.rs+++ b/fluxer_app_proxy/src/config.rs@@ -26,20 +26,6 @@ impl InvalidAppProxyEnvironmentError {}}-impl fmt::Display for InvalidAppProxyEnvironmentError {- fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {- match self {- Self::InvalidValue {- name,- value,- expected,- } => write!(formatter, "{name} must be {expected}, got {value:?}"),- }- }-}--impl std::error::Error for InvalidAppProxyEnvironmentError {}-#[derive(Clone, Debug, Eq, PartialEq)]pub struct HttpUrl(Url);@@ -370,6 +356,7 @@ pub struct AppProxyConfig {pub struct CspConfig {pub extra_default_src: Vec<CspSource>,pub extra_connect_src: Vec<CspSource>,+ pub voice_connect_src: Vec<CspSource>,pub extra_img_src: Vec<CspSource>,pub extra_media_src: Vec<CspSource>,pub extra_font_src: Vec<CspSource>,@@ -386,6 +373,9 @@ impl CspConfig {Self {extra_default_src: read_csp_sources("FLUXER_CSP_EXTRA_DEFAULT_SRC"),extra_connect_src: read_csp_sources("FLUXER_CSP_EXTRA_CONNECT_SRC"),+ voice_connect_src: cfg::env_value("FLUXER_LIVEKIT_URL")+ .map(|value| voice_connect_sources("FLUXER_LIVEKIT_URL", &value))+ .unwrap_or_default(),extra_img_src: read_csp_sources("FLUXER_CSP_EXTRA_IMG_SRC"),extra_media_src: read_csp_sources("FLUXER_CSP_EXTRA_MEDIA_SRC"),extra_font_src: read_csp_sources("FLUXER_CSP_EXTRA_FONT_SRC"),@@ -412,6 +402,32 @@ fn read_csp_sources(name: &'static str) -> Vec<CspSource> {.collect()}+pub fn voice_connect_sources(name: &'static str, value: &str) -> Vec<CspSource> {+ let Ok(url) = Url::parse(value.trim()) else {+ return Vec::new();+ };+ let twin_scheme = match url.scheme() {+ "https" => "wss",+ "wss" => "https",+ "http" => "ws",+ "ws" => "http",+ _ => return Vec::new(),+ };+ let origin = url.origin().ascii_serialization();+ let Some((_, authority)) = origin.split_once("://") else {+ return Vec::new();+ };+ let twin = format!("{twin_scheme}://{authority}");+ [origin.as_str(), twin.as_str()]+ .into_iter()+ .filter_map(|source| {+ CspSource::parse(name, source)+ .inspect_err(warn_invalid)+ .ok()+ })+ .collect()+}+fn read_csp_report_uri(name: &'static str) -> Option<CspReportUri> {let value = cfg::env_value(name)?;CspReportUri::parse(name, value.trim())@@ -433,6 +449,7 @@ impl AppProxyConfig {.ok()});+ let self_hosted = cfg::read_bool_env("FLUXER_SELF_HOSTED", false);Self {host: cfg::read_env("FLUXER_APP_PROXY_HOST", "0.0.0.0"),port: parse_env_or_warn(@@ -478,15 +495,22 @@ impl AppProxyConfig {"FLUXER_APP_PROXY_MANIFEST_SCOPE_EXTENSIONS",&cfg::read_env("FLUXER_APP_PROXY_MANIFEST_SCOPE_EXTENSIONS", ""),),- release_channel: parse_release_channel(- "RELEASE_CHANNEL",- &cfg::read_env("RELEASE_CHANNEL", ""),+ release_channel: resolve_release_channel(+ parse_release_channel("RELEASE_CHANNEL", &cfg::read_env("RELEASE_CHANNEL", "")),+ self_hosted,),- self_hosted: cfg::read_bool_env("FLUXER_SELF_HOSTED", false),+ self_hosted,}}}+fn resolve_release_channel(+ configured: Option<&'static str>,+ self_hosted: bool,+) -> Option<&'static str> {+ configured.or(if self_hosted { Some("stable") } else { None })+}+fn parse_release_channel(name: &'static str, raw: &str) -> Option<&'static str> {match raw.trim().to_ascii_lowercase().as_str() {"" => None,@@ -585,70 +609,3 @@ fn parse_same_origin_host(}Ok(host)}--#[cfg(test)]-mod tests {- use super::*;-- #[test]- fn same_origin_hosts_are_normalised_and_deduplicated() {- assert_eq!(- parse_same_origin_hosts(- "TEST_SAME_ORIGIN_HOSTS",- " web.fluxer.app, Fluxer.COM,fluxer.com. ,fluxer.com"- ),- vec!["web.fluxer.app".to_owned(), "fluxer.com".to_owned()]- );- }-- #[test]- fn same_origin_hosts_drop_anything_but_a_bare_hostname() {- assert_eq!(- parse_same_origin_hosts(- "TEST_SAME_ORIGIN_HOSTS",- "https://fluxer.com,fluxer.com:443,fluxer.com/api,[email protected],canary.fluxer.com"- ),- vec!["canary.fluxer.com".to_owned()]- );- }-- #[test]- fn release_channel_accepts_only_stable_or_canary() {- assert_eq!(- parse_release_channel("TEST_CHANNEL", " Stable "),- Some("stable")- );- assert_eq!(- parse_release_channel("TEST_CHANNEL", "canary"),- Some("canary")- );- assert_eq!(parse_release_channel("TEST_CHANNEL", ""), None);- assert_eq!(parse_release_channel("TEST_CHANNEL", "development"), None);- assert_eq!(parse_release_channel("TEST_CHANNEL", "\"><script>"), None);- }-- #[test]- fn manifest_scope_extensions_are_normalised_and_deduplicated() {- assert_eq!(- parse_manifest_scope_extensions(- "TEST_SCOPE_EXTENSIONS",- " https://Fluxer.COM, https://fluxer.com/ ,https://canary.fluxer.com:443"- ),- vec![- "https://fluxer.com".to_owned(),- "https://canary.fluxer.com".to_owned()- ]- );- }-- #[test]- fn manifest_scope_extensions_drop_anything_but_an_https_origin() {- assert_eq!(- parse_manifest_scope_extensions(- "TEST_SCOPE_EXTENSIONS",- "fluxer.com,http://fluxer.com,https://fluxer.com/app,https://fluxer.com/?a=1,https://[email protected],https://canary.fluxer.com"- ),- vec!["https://canary.fluxer.com".to_owned()]- );- }-}diff --git a/fluxer_app_proxy/src/csp.rs b/fluxer_app_proxy/src/csp.rsindex da3bea0cf..d35bf76c2 100644--- a/fluxer_app_proxy/src/csp.rs+++ b/fluxer_app_proxy/src/csp.rs@@ -151,27 +151,6 @@ pub enum CspCompileError {InvalidSpaPolicy(InvalidHeaderValue),}-impl std::fmt::Display for CspCompileError {- fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {- match self {- Self::InvalidAssetPolicy(_) => {- formatter.write_str("the asset content security policy is not a valid header value")- }- Self::InvalidSpaPolicy(_) => {- formatter.write_str("the SPA content security policy is not a valid header value")- }- }- }-}--impl std::error::Error for CspCompileError {- fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {- match self {- Self::InvalidAssetPolicy(source) | Self::InvalidSpaPolicy(source) => Some(source),- }- }-}-#[derive(Clone, Debug)]pub struct CompiledCspPolicy {config: CspConfig,@@ -329,6 +308,14 @@ fn build_csp_directives(let mut connect = vec!["'self'".to_owned(), "blob:".to_owned(), "data:".to_owned()];extend_from(&mut connect, &config.extra_connect_src, CONNECT_SOURCES);+ extend_from(&mut connect, &config.voice_connect_src, &[]);+ for source in &config.extra_connect_src {+ if let Some(twin) = http_twin_of_websocket_source(source.as_str())+ && !connect.contains(&twin)+ {+ connect.push(twin);+ }+ }extend_runtime_sources(&mut connect, runtime_sources, instance_sources, true, true);extend_runtime_s3_sources(&mut connect, runtime_sources);for origin in &instance_sources.connect_origins {@@ -402,6 +389,15 @@ fn extend_runtime_s3_sources(target: &mut Vec<String>, runtime_sources: &Runtimepush_endpoint_source(target, runtime_sources.s3_uploads_endpoint.as_ref());}+fn http_twin_of_websocket_source(source: &str) -> Option<String> {+ if let Some(rest) = source.strip_prefix("wss://") {+ return Some(format!("https://{rest}"));+ }+ source+ .strip_prefix("ws://")+ .map(|rest| format!("http://{rest}"))+}+fn extend_from(target: &mut Vec<String>, extra: &[CspSource], defaults: &[&str]) {for source in defaults.iter()@@ -435,33 +431,6 @@ mod tests {);}- #[test]- fn every_inline_script_is_hashed_and_external_scripts_are_not() {- let document = concat!(- "<head><script>first()</script>",- "<SCRIPT type=\"text/javascript\">second()</SCRIPT >",- "<script type=\"module\" src=\"/assets/app.js\"></script>",- "<script defer src='/assets/vendor.js'></script>",- "<scripts>not a script</scripts>",- "<script data-src=\"x\">\nthird()\n</script></head>",- );-- assert_eq!(- inline_script_hashes(document),- vec![- hash_of("first()"),- hash_of("second()"),- hash_of("\nthird()\n")- ]- );- }-- #[test]- fn an_inline_script_repeated_verbatim_is_granted_once() {- let document = "<script>same()</script><script>same()</script>";- assert_eq!(inline_script_hashes(document), vec![hash_of("same()")]);- }-#[test]fn an_unterminated_script_is_never_granted() {assert!(inline_script_hashes("<script>never_closed()").is_empty());@@ -479,113 +448,6 @@ mod tests {HttpEndpoint::parse("TEST_ENDPOINT", value).unwrap()}- #[test]- fn build_csp_includes_required_directives() {- let config = default_csp_config();- let csp = build_csp(- &config,- &[hash_of("boot()")],- &runtime_sources(),- &[],- &InstanceCspSources::default(),- );- assert!(csp.contains("default-src"));- assert!(csp.contains("script-src"));- assert!(csp.contains("style-src"));- assert!(csp.contains("img-src"));- assert!(csp.contains("media-src"));- assert!(csp.contains("font-src"));- assert!(csp.contains("connect-src"));- assert!(csp.contains("frame-src"));- assert!(csp.contains("worker-src"));- assert!(csp.contains("manifest-src"));- assert!(csp.contains("object-src 'none'"));- assert!(csp.contains("base-uri 'self'"));- assert!(csp.contains("frame-ancestors 'none'"));- }-- #[test]- fn build_csp_allows_the_apex_domain_for_images_and_media() {- let config = default_csp_config();- let csp = build_csp(- &config,- &[hash_of("boot()")],- &runtime_sources(),- &[],- &InstanceCspSources::default(),- );- for name in ["img-src ", "media-src "] {- let directive = csp- .split("; ")- .find(|directive| directive.starts_with(name))- .expect("directive");- assert!(- directive- .split(' ')- .any(|source| source == "https://fluxer.app"),- "{name}must allow the apex domain: {directive}"- );- }- }-- #[test]- fn build_csp_allows_blob_connections_for_camera_background_media() {- let config = default_csp_config();- let csp = build_csp(- &config,- &[hash_of("boot()")],- &runtime_sources(),- &[],- &InstanceCspSources::default(),- );- let connect = csp- .split("; ")- .find(|directive| directive.starts_with("connect-src "))- .expect("connect-src directive");- assert!(- connect.split(' ').any(|source| source == "blob:"),- "connect-src must allow blob: object URLs: {connect}"- );- }-- #[test]- fn an_asset_header_allows_blob_connections_for_the_camera_effect_worker() {- let policy = CompiledCspPolicy::compile(default_csp_config(), &runtime_sources()).unwrap();- let asset = policy.asset_header();- let asset = asset.to_str().unwrap();- let connect = asset- .split("; ")- .find(|directive| directive.starts_with("connect-src "))- .expect("connect-src directive");- assert!(- connect.split(' ').any(|source| source == "blob:"),- "the camera-effect worker is served as /assets/*.worker.js and runs under the asset \- policy, so that policy must allow blob: object URLs: {connect}"- );- }-- #[test]- fn build_csp_grants_each_script_hash_in_script_src_and_no_nonce() {- let config = default_csp_config();- let csp = build_csp(- &config,- &[hash_of("first()"), hash_of("second()")],- &runtime_sources(),- &[],- &InstanceCspSources::default(),- );- let script = csp- .split("; ")- .find(|directive| directive.starts_with("script-src "))- .expect("script-src directive");- assert!(script.starts_with(&format!(- "script-src 'self' {} {} 'wasm-unsafe-eval' blob:",- hash_of("first()").as_source(),- hash_of("second()").as_source()- )));- assert!(!csp.contains("nonce-"));- }-#[test]fn build_asset_csp_grants_no_inline_script() {let config = default_csp_config();@@ -594,90 +456,6 @@ mod tests {assert!(!csp.contains("sha256-"));}- #[test]- fn build_csp_allows_no_third_party_captcha_hosts() {- let csp = build_csp(- &default_csp_config(),- &[hash_of("boot()")],- &runtime_sources(),- &[],- &InstanceCspSources::default(),- );- assert!(!csp.contains("hcaptcha"));- assert!(!csp.contains("challenges.cloudflare.com"));- }-- #[test]- fn csp_no_double_spaces_or_trailing_semicolons() {- let config = default_csp_config();- let csp = build_csp(- &config,- &[hash_of("boot()")],- &runtime_sources(),- &[],- &InstanceCspSources::default(),- );- assert!(!csp.contains(" "), "CSP contains double spaces");- assert!(!csp.ends_with(';'), "CSP ends with semicolon");- assert!(!csp.ends_with("; "), "CSP ends with semicolon+space");- }-- #[test]- fn build_csp_includes_report_uri_when_configured() {- let config = CspConfig {- report_uri: Some(- crate::config::CspReportUri::parse(- "TEST_CSP_REPORT_URI",- "https://example.com/csp-report",- )- .unwrap(),- ),- ..Default::default()- };- let csp = build_csp(- &config,- &[hash_of("boot()")],- &runtime_sources(),- &[],- &InstanceCspSources::default(),- );- assert!(csp.contains("report-uri https://example.com/csp-report"));- }-- #[test]- fn build_csp_excludes_report_uri_when_none() {- let config = default_csp_config();- let csp = build_csp(- &config,- &[hash_of("boot()")],- &runtime_sources(),- &[],- &InstanceCspSources::default(),- );- assert!(!csp.contains("report-uri"));- }-- #[test]- fn build_csp_includes_configured_runtime_endpoints() {- let config = default_csp_config();- let runtime_sources = RuntimeCspSources {- static_cdn_endpoint: Some(endpoint("https://static.example.test/")),- media_endpoint: Some(endpoint("https://media.example.test")),- ..Default::default()- };- let csp = build_csp(- &config,- &[hash_of("boot()")],- &runtime_sources,- &[],- &InstanceCspSources::default(),- );- assert!(csp.contains("style-src 'self' 'unsafe-inline'"));- assert!(csp.contains("https://static.example.test"));- assert!(csp.contains("https://media.example.test"));- assert!(!csp.contains("https://static.example.test/ "));- }-#[test]fn a_csp_source_cannot_smuggle_a_second_directive() {for injected in [@@ -704,141 +482,6 @@ mod tests {);}- #[test]- fn build_csp_includes_s3_public_and_virtual_hosted_upload_origins() {- let config = default_csp_config();- let runtime_sources = RuntimeCspSources {- s3_public_endpoint: Some(endpoint("http://localhost:3900/")),- s3_uploads_endpoint: Some(endpoint("http://fluxer-uploads.localhost:3900/")),- ..Default::default()- };-- let csp = build_csp(- &config,- &[hash_of("boot()")],- &runtime_sources,- &[],- &InstanceCspSources::default(),- );-- assert!(csp.contains("http://localhost:3900"));- assert!(csp.contains("http://fluxer-uploads.localhost:3900"));- assert!(!csp.contains("http://localhost:3900/ "));- }-- #[test]- fn a_compiled_asset_header_is_the_policy_every_asset_response_reuses() {- let sources = RuntimeCspSources {- static_cdn_endpoint: Some(endpoint("https://static.example.test/")),- media_endpoint: Some(endpoint("https://media.example.test")),- s3_public_endpoint: Some(endpoint("http://localhost:3900/")),- ..Default::default()- };- let policy = CompiledCspPolicy::compile(default_csp_config(), &sources).unwrap();-- assert_eq!(policy.asset_header(), policy.asset_header());- let asset = policy.asset_header();- let asset = asset.to_str().unwrap();- assert!(!asset.contains("nonce-"));- assert!(!asset.contains("sha256-"));- assert!(asset.contains("https://static.example.test"));- assert!(- !asset.contains("https://media.example.test"),- "an asset response must not widen the policy with the endpoints only the document needs"- );- assert!(!asset.contains("http://localhost:3900"));- }-- #[test]- fn a_compiled_policy_stamps_the_documents_script_hashes_and_configured_endpoints() {- let configured = RuntimeCspSources {- static_cdn_endpoint: Some(endpoint("https://cdn.configured.test")),- ..Default::default()- };- let policy = CompiledCspPolicy::compile(default_csp_config(), &configured).unwrap();-- let headers = policy.spa_headers(&[hash_of("boot()")], &[], &InstanceCspSources::default());- let header = headers.enforced.to_str().unwrap();-- assert!(header.contains(hash_of("boot()").as_source()));- assert!(header.contains("https://cdn.configured.test"));- assert!(!header.contains("nonce-"));- assert!(headers.report_only.is_none());- }-- #[test]- fn the_configured_media_endpoint_reaches_every_directive_that_loads_media() {- let mut config = AppProxyConfig::from_env();- config.csp = default_csp_config();- config.media_endpoint = Some(endpoint("https://media.configured.test/"));- let policy = CompiledCspPolicy::from_config(&config).unwrap();-- let headers = policy.spa_headers(&[hash_of("boot()")], &[], &InstanceCspSources::default());- let header = headers.enforced.to_str().unwrap();- for directive in [- "img-src",- "media-src",- "font-src",- "style-src",- "connect-src",- ] {- let sources = header- .split("; ")- .find(|candidate| candidate.starts_with(directive))- .unwrap_or_else(|| panic!("the policy has no {directive}"));- assert!(- sources- .split(' ')- .any(|source| source == "https://media.configured.test"),- "{directive} does not grant the configured media endpoint"- );- }- for directive in ["script-src", "worker-src", "manifest-src"] {- let sources = header- .split("; ")- .find(|candidate| candidate.starts_with(directive))- .unwrap_or_else(|| panic!("the policy has no {directive}"));- assert!(!sources.contains("https://media.configured.test"));- }- assert!(- !policy- .asset_header()- .to_str()- .unwrap()- .contains("https://media.configured.test")- );- }-- #[test]- fn a_compiled_policy_matches_the_directives_it_was_compiled_from() {- let config = default_csp_config();- let sources = RuntimeCspSources {- static_cdn_endpoint: Some(endpoint("https://static.example.test/")),- ..Default::default()- };- let policy = CompiledCspPolicy::compile(config.clone(), &sources).unwrap();-- assert_eq!(- policy.asset_header().to_str().unwrap(),- build_asset_csp(&config, &sources)- );- let hashes = [hash_of("boot()")];- assert_eq!(- policy- .spa_headers(&hashes, &[], &InstanceCspSources::default())- .enforced- .to_str()- .unwrap(),- build_csp(- &config,- &hashes,- &sources,- &[],- &InstanceCspSources::default()- )- );- }-#[test]fn branding_image_origins_are_granted_to_images_and_nothing_else() {let policy = CompiledCspPolicy::compile(default_csp_config(), &runtime_sources()).unwrap();@@ -877,68 +520,4 @@ mod tests {.contains("example.test"));}-- #[test]- fn discovered_instance_origins_are_granted_to_the_page() {- let policy = CompiledCspPolicy::compile(default_csp_config(), &runtime_sources()).unwrap();- let instance = InstanceCspSources {- static_cdn_endpoint: None,- media_endpoint: Some(endpoint("https://chat.example.com/media")),- connect_origins: vec![- "https://chat.example.com".to_owned(),- "wss://chat.example.com".to_owned(),- ],- };-- let headers = policy.spa_headers(&[hash_of("boot()")], &[], &instance);- let header = headers.enforced.to_str().unwrap();- let directive = |name: &str| {- header- .split("; ")- .find(|directive| directive.starts_with(&format!("{name} ")))- .unwrap()- .split(' ')- .collect::<Vec<_>>()- };-- assert!(directive("connect-src").contains(&"wss://chat.example.com"));- assert!(directive("connect-src").contains(&"https://chat.example.com"));- assert!(directive("img-src").contains(&"https://chat.example.com"));- assert!(directive("media-src").contains(&"https://chat.example.com"));- assert!(!directive("script-src").contains(&"https://chat.example.com"));- assert!(- !policy- .asset_header()- .to_str()- .unwrap()- .contains("chat.example.com")- );- }-- #[test]- fn a_branding_image_origin_the_policy_already_grants_is_not_repeated() {- let configured = RuntimeCspSources {- media_endpoint: Some(endpoint("https://media.example.test/media")),- ..Default::default()- };- let policy = CompiledCspPolicy::compile(default_csp_config(), &configured).unwrap();-- let headers = policy.spa_headers(- &[hash_of("boot()")],- &[endpoint("https://media.example.test")],- &InstanceCspSources::default(),- );- let header = headers.enforced.to_str().unwrap();- let img = header- .split("; ")- .find(|directive| directive.starts_with("img-src "))- .unwrap();-- assert_eq!(- img.split(' ')- .filter(|source| *source == "https://media.example.test")- .count(),- 1- );- }}