Skip to content

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

TypeScript fluxerfluxerapp

test: drop redundant tests (#3715)

Hampusec7aa594789d
diff --git a/fluxer_admin/src/api/client.rs b/fluxer_admin/src/api/client.rs
index a3a404af2..ea67453aa 100644
--- a/fluxer_admin/src/api/client.rs
+++ b/fluxer_admin/src/api/client.rs
@@ -449,35 +449,3 @@ fn audit_log_reason_header(reason: &str) -> ApiResult<HeaderValue> {
value.set_sensitive(true);
Ok(value)
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use crate::api::generated::types;
-
- #[test]
- fn generated_error_response_keeps_api_message() {
- let client = AdminApiClient {
- generated: GeneratedClient::new_with_client(
- "http://localhost",
- reqwest::Client::new(),
- HeaderMap::new(),
- ),
- };
- let body = types::Error {
- code: "DIRECT_MESSAGES_DISABLED".to_owned(),
- errors: Vec::new(),
- message: "Direct messages are disabled on this instance.".to_owned(),
- extra: serde_json::Map::new(),
- };
- let error = progenitor_client::Error::ErrorResponse(progenitor_client::ResponseValue::new(
- body,
- reqwest::StatusCode::BAD_REQUEST,
- HeaderMap::new(),
- ));
- assert_eq!(
- client.generated_error(error).detail_message().as_deref(),
- Some("Direct messages are disabled on this instance.")
- );
- }
-}
diff --git a/fluxer_admin/src/api/types/badges.rs b/fluxer_admin/src/api/types/badges.rs
index 752e8548e..6e13589e7 100644
--- a/fluxer_admin/src/api/types/badges.rs
+++ b/fluxer_admin/src/api/types/badges.rs
@@ -108,62 +108,3 @@ pub struct CustomBadgeFields {
pub href: Option<String>,
pub image: Option<String>,
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- fn badge(id: &str, badge_type: CustomBadgeType) -> AdminCustomBadge {
- AdminCustomBadge {
- id: id.to_owned(),
- badge_type,
- name: id.to_owned(),
- description: None,
- asset_url: String::new(),
- href: None,
- }
- }
-
- fn ids(values: &[&str]) -> Option<Vec<String>> {
- Some(values.iter().map(|value| (*value).to_owned()).collect())
- }
-
- fn list() -> AdminCustomBadgeList {
- AdminCustomBadgeList {
- badges: vec![
- badge("1", CustomBadgeType::User),
- badge("2", CustomBadgeType::Guild),
- badge("3", CustomBadgeType::User),
- badge("4", CustomBadgeType::Guild),
- badge("5", CustomBadgeType::User),
- ],
- }
- }
-
- #[test]
- fn moved_order_swaps_with_the_nearest_badge_of_the_same_type() {
- let badges = list();
- assert_eq!(
- ids(&["3", "2", "1", "4", "5"]),
- badges.moved_order("3", BadgeMove::Up)
- );
- assert_eq!(
- ids(&["1", "4", "3", "2", "5"]),
- badges.moved_order("2", BadgeMove::Down)
- );
- assert_eq!(
- ids(&["1", "2", "5", "4", "3"]),
- badges.moved_order("3", BadgeMove::Down)
- );
- }
-
- #[test]
- fn moved_order_refuses_the_ends_and_unknown_badges() {
- let badges = list();
- assert_eq!(None, badges.moved_order("1", BadgeMove::Up));
- assert_eq!(None, badges.moved_order("2", BadgeMove::Up));
- assert_eq!(None, badges.moved_order("5", BadgeMove::Down));
- assert_eq!(None, badges.moved_order("4", BadgeMove::Down));
- assert_eq!(None, badges.moved_order("9", BadgeMove::Up));
- }
-}
diff --git a/fluxer_admin/src/api/types/common.rs b/fluxer_admin/src/api/types/common.rs
index 2cbc1d957..817992538 100644
--- a/fluxer_admin/src/api/types/common.rs
+++ b/fluxer_admin/src/api/types/common.rs
@@ -346,43 +346,3 @@ pub struct TerminateSessionsResponse {
pub struct RemoveRelationshipsResponse {
pub removed_count: i32,
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn role_summary_reads_icon_fields_and_defaults_them_when_absent() {
- let with_icon: GuildRoleSummary = serde_json::from_value(serde_json::json!({
- "id": "1",
- "name": "Mods",
- "color": 0,
- "position": 1,
- "permissions": "0",
- "hoist": false,
- "mentionable": false,
- "icon": "a1b2c3d4",
- "unicode_emoji": null,
- }))
- .expect("role with icon");
- assert_eq!(Some("a1b2c3d4"), with_icon.icon.as_deref());
- assert_eq!(None, with_icon.unicode_emoji);
- let round_trip: GuildRoleSummary =
- serde_json::from_value(serde_json::to_value(&with_icon).expect("serialise role"))
- .expect("role round trip");
- assert_eq!(with_icon.icon, round_trip.icon);
-
- let without_icon: GuildRoleSummary = serde_json::from_value(serde_json::json!({
- "id": "2",
- "name": "Plain",
- "color": 0,
- "position": 0,
- "permissions": "0",
- "hoist": false,
- "mentionable": false,
- }))
- .expect("role without icon fields");
- assert_eq!(None, without_icon.icon);
- assert_eq!(None, without_icon.unicode_emoji);
- }
-}
diff --git a/fluxer_admin/src/api/types/instance_billing.rs b/fluxer_admin/src/api/types/instance_billing.rs
index 768686a78..605d97442 100644
--- a/fluxer_admin/src/api/types/instance_billing.rs
+++ b/fluxer_admin/src/api/types/instance_billing.rs
@@ -235,20 +235,3 @@ fn favicon_url(favicon_url: Option<&str>, icon_url: Option<&str>) -> Option<Stri
.or_else(|| non_blank(icon_url))
.map(str::to_owned)
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- fn branding(well_known: &str) -> PremiumBranding {
- PremiumBranding::from_discovery(&serde_json::from_str(well_known).unwrap())
- }
-
- #[test]
- fn discovery_enabled_follows_the_well_known_feature_flag() {
- assert!(!branding(r#"{"features":{"discovery_enabled":false}}"#).discovery_enabled);
- assert!(branding(r#"{"features":{"discovery_enabled":true}}"#).discovery_enabled);
- assert!(branding(r#"{"features":{"premium_enabled":true}}"#).discovery_enabled);
- assert!(branding("{}").discovery_enabled);
- }
-}
diff --git a/fluxer_admin/src/routes/auth.rs b/fluxer_admin/src/routes/auth.rs
index 1786917cd..3e6ccd6f7 100644
--- a/fluxer_admin/src/routes/auth.rs
+++ b/fluxer_admin/src/routes/auth.rs
@@ -516,210 +516,3 @@ fn login_error_message(code: &str) -> &'static str {
_ => "Login error. Please try again.",
}
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn oauth_state_survives_ten_minutes_on_the_consent_page() {
- let verifier = "verifier";
- let issued = |age: u64| sign_oauth_state("secret", now_seconds() - age, [7; 16], verifier);
- assert!(verify_oauth_state("secret", &issued(10 * 60), verifier));
- assert!(!verify_oauth_state(
- "secret",
- &issued(OAUTH_STATE_MAX_AGE_SECONDS + 60),
- verifier
- ));
- }
-
- const TEST_SECRET: &str = "test-secret";
-
- fn wildcard_admin_me_body() -> serde_json::Value {
- serde_json::from_str(
- r#"{
- "user": {
- "id": "100",
- "username": "owner",
- "discriminator": 1,
- "global_name": null,
- "bot": false,
- "system": false,
- "flags": "0",
- "premium_flags": 0,
- "avatar": null,
- "banner": null,
- "bio": null,
- "pronouns": null,
- "accent_color": null,
- "email": "[email protected]",
- "email_verified": true,
- "email_bounced": false,
- "date_of_birth": null,
- "locale": null,
- "premium_type": null,
- "premium_since": null,
- "premium_until": null,
- "premium_grace_ends_at": null,
- "premium_lifetime_sequence": null,
- "profile_badges": [],
- "temp_banned_until": null,
- "pending_deletion_at": null,
- "pending_bulk_message_deletion_at": null,
- "deletion_reason_code": null,
- "deletion_public_reason": null,
- "deletion_audit_log_reason": null,
- "deletion_scheduled_by": null,
- "deletion_scheduled_at": null,
- "enforcement_decision_id": null,
- "acls": ["*"],
- "traits": [],
- "badge_ids": [],
- "has_totp": false,
- "has_password": true,
- "claimed": true,
- "account_tier": "verified",
- "date_of_birth_required": false,
- "authenticator_types": [],
- "last_active_at": null,
- "last_active_ip": null,
- "last_active_ip_reverse": null,
- "last_active_location": null
- },
- "pending_registration_count": null
- }"#,
- )
- .unwrap()
- }
-
- async fn finish_login(
- admin_me_status: u16,
- admin_me_body: serde_json::Value,
- ) -> (StatusCode, String) {
- let admin_me_status = StatusCode::from_u16(admin_me_status).unwrap();
- let api = Router::new()
- .route(
- "/oauth2/token",
- post(|| async { Json(serde_json::json!({"access_token": "token"})) }),
- )
- .route(
- "/users/@me",
- get(|| async { Json(serde_json::json!({"id": "100"})) }),
- )
- .route(
- "/admin/users/@me",
- get(move || async move { (admin_me_status, Json(admin_me_body)) }),
- );
- let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
- let api_endpoint = format!("http://{}", listener.local_addr().unwrap());
- tokio::spawn(async move { axum::serve(listener, api).await.unwrap() });
-
- let state = AppState::new(AdminConfig {
- host: "127.0.0.1".into(),
- port: 0,
- secret_key_base: TEST_SECRET.into(),
- base_path: String::new(),
- api_endpoint: api_endpoint.clone(),
- api_public_endpoint: api_endpoint,
- media_endpoint: String::new(),
- static_cdn_endpoint: String::new(),
- reports_bucket_origin: String::new(),
- admin_endpoint: "http://admin.test".into(),
- web_app_endpoint: "http://app.test".into(),
- oauth_client_id: "1234567890123456789".into(),
- oauth_client_secret: "client-secret".into(),
- oauth_redirect_uri: "http://admin.test/oauth2_callback".into(),
- build_version: "test".into(),
- self_hosted: true,
- proxy: crate::config::ProxyConfig {
- trust_client_ip_header: false,
- client_ip_header_name: "x-forwarded-for".into(),
- },
- });
- let mut headers = HeaderMap::new();
- headers.insert(OAUTH_FINISH_HEADER, "1".parse().unwrap());
- let verifier = "verifier".to_owned();
- let body = CallbackFinishBody {
- code: "code".into(),
- state: generate_oauth_state(TEST_SECRET, &verifier),
- verifier,
- };
- let response = oauth2_callback_finish(State(state), headers, Json(body)).await;
- let status = response.status();
- let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
- .await
- .unwrap();
- let body: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
- (status, body["redirect_to"].as_str().unwrap().to_owned())
- }
-
- #[tokio::test]
- async fn wildcard_admin_signs_in_when_the_api_matches() {
- let (status, redirect_to) = finish_login(200, wildcard_admin_me_body()).await;
- assert_eq!(status, StatusCode::OK);
- assert_eq!(redirect_to, "/dashboard");
- }
-
- #[tokio::test]
- async fn account_without_admin_acl_is_told_it_lacks_the_acl() {
- let (status, redirect_to) = finish_login(
- 403,
- serde_json::json!({"code": "MISSING_PERMISSIONS", "message": "Missing permissions"}),
- )
- .await;
- assert_eq!(status, StatusCode::FORBIDDEN);
- assert_eq!(redirect_to, "/login?error=missing_admin_acl");
- }
-
- #[tokio::test]
- async fn wildcard_admin_on_an_older_api_is_not_told_it_lacks_the_acl() {
- let mut body = wildcard_admin_me_body();
- body["user"].as_object_mut().unwrap().remove("badge_ids");
- let (status, redirect_to) = finish_login(200, body).await;
- assert_eq!(status, StatusCode::BAD_GATEWAY);
- assert_eq!(redirect_to, "/login?error=admin_api_mismatch");
- }
-
- #[tokio::test]
- async fn api_without_the_current_admin_route_is_not_reported_as_missing_acl() {
- let (status, redirect_to) = finish_login(
- 404,
- serde_json::json!({"code": "NOT_FOUND", "message": "Not found"}),
- )
- .await;
- assert_eq!(status, StatusCode::BAD_GATEWAY);
- assert_eq!(redirect_to, "/login?error=admin_api_mismatch");
- }
-
- #[tokio::test]
- async fn rate_limited_admin_check_is_not_reported_as_missing_acl() {
- let (status, redirect_to) = finish_login(
- 429,
- serde_json::json!({"code": "RATE_LIMITED", "message": "Too many requests"}),
- )
- .await;
- assert_eq!(status, StatusCode::BAD_GATEWAY);
- assert_eq!(redirect_to, "/login?error=admin_check_failed");
- }
-
- #[test]
- fn transport_failures_point_at_connectivity() {
- let err = ApiError::Network("connection refused".into());
- assert_eq!(admin_check_error_code(&err), "admin_api_unreachable");
- }
-
- #[test]
- fn each_admin_check_failure_has_its_own_message() {
- let messages = [
- "missing_admin_acl",
- "admin_api_mismatch",
- "admin_api_unreachable",
- "admin_check_failed",
- ]
- .map(login_error_message);
- for (index, message) in messages.iter().enumerate() {
- assert_ne!(*message, login_error_message("unknown"));
- assert!(!messages[index + 1..].contains(message), "{message}");
- }
- }
-}
diff --git a/fluxer_admin/src/routes/system_actions.rs b/fluxer_admin/src/routes/system_actions.rs
index e356c7a7f..b3ec5d19f 100644
--- a/fluxer_admin/src/routes/system_actions.rs
+++ b/fluxer_admin/src/routes/system_actions.rs
@@ -547,19 +547,3 @@ fn build_media_update(form: &MultiValueForm) -> InstanceConfigUpdateRequest {
..Default::default()
}
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn a_save_with_warnings_shows_them_instead_of_plain_success() {
- let warnings = vec!["Couldn't connect to the sign-in provider.".to_owned()];
- let flash = with_save_warnings(FlashData::success("Instance config updated"), &warnings);
- assert_eq!(flash.flash_type, "info");
- assert_eq!(
- flash.message,
- "Instance config updated. Couldn't connect to the sign-in provider."
- );
- }
-}
diff --git a/fluxer_admin/src/routes/voice_actions.rs b/fluxer_admin/src/routes/voice_actions.rs
index bd501266c..5eccb3ed7 100644
--- a/fluxer_admin/src/routes/voice_actions.rs
+++ b/fluxer_admin/src/routes/voice_actions.rs
@@ -327,65 +327,3 @@ fn servers_url(base: &str, region_id: Option<&str>) -> String {
None => format!("{base}/voice-servers"),
}
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- fn form(pairs: &[(&str, &str)]) -> MultiValueForm {
- let encoded = pairs
- .iter()
- .map(|(k, v)| format!("{}={}", urlencoding::encode(k), urlencoding::encode(v)))
- .collect::<Vec<_>>()
- .join("&");
- MultiValueForm::parse(encoded.as_bytes())
- }
-
- #[test]
- fn join_token_body_for_a_new_region_and_presets() {
- let body = build_join_token_body(&form(&[
- ("region_choice", "new"),
- ("new_region_id", "sgp"),
- ("new_region_name", "Singapore"),
- ("new_region_emoji", "🇸🇬"),
- ("server_id", "sgp-server-1"),
- ("hostname", " voice-sgp.chat.example.com "),
- ("soft_connection_limit", "300"),
- ("expires_hours", "48"),
- ]));
- assert_eq!(body["region_id"], "sgp");
- assert_eq!(body["region_name"], "Singapore");
- assert_eq!(body["server_id"], "sgp-server-1");
- assert_eq!(body["hostname"], "voice-sgp.chat.example.com");
- assert_eq!(body["soft_connection_limit"], 300);
- assert_eq!(body["expires_in_seconds"], 86400);
- }
-
- #[test]
- fn join_token_body_with_automatic_region_has_no_region() {
- let body = build_join_token_body(&form(&[("region_choice", "auto")]));
- assert!(body.get("region_id").is_none());
- assert_eq!(body["expires_in_seconds"], 3600);
- let picked = build_join_token_body(&form(&[("region_choice", "fra")]));
- assert_eq!(picked["region_id"], "fra");
- }
-
- #[test]
- fn server_body_keeps_draining_unless_the_form_shows_it() {
- let toggle = build_server_body(&form(&[
- ("region_id", "fra"),
- ("server_id", "a"),
- ("is_active", "false"),
- ]));
- assert!(toggle.get("draining").is_none());
- assert!(toggle.get("internal_endpoint").is_none());
- let edit = build_server_body(&form(&[
- ("region_id", "fra"),
- ("server_id", "a"),
- ("draining_field", "1"),
- ("internal_endpoint", ""),
- ]));
- assert_eq!(edit["draining"], false);
- assert!(edit["internal_endpoint"].is_null());
- }
-}
diff --git a/fluxer_admin/src/state.rs b/fluxer_admin/src/state.rs
index 3934e06df..53fcce0b5 100644
--- a/fluxer_admin/src/state.rs
+++ b/fluxer_admin/src/state.rs
@@ -210,73 +210,3 @@ impl axum::extract::FromRef<AppState> for AdminConfig {
state.inner.config.clone()
}
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use crate::config::ProxyConfig;
-
- fn self_hosted_state() -> AppState {
- AppState::new(AdminConfig {
- host: String::new(),
- port: 0,
- secret_key_base: String::new(),
- base_path: String::new(),
- api_endpoint: String::new(),
- api_public_endpoint: String::new(),
- media_endpoint: String::new(),
- static_cdn_endpoint: String::new(),
- reports_bucket_origin: String::new(),
- admin_endpoint: String::new(),
- web_app_endpoint: String::new(),
- oauth_client_id: String::new(),
- oauth_client_secret: String::new(),
- oauth_redirect_uri: String::new(),
- build_version: String::new(),
- self_hosted: true,
- proxy: ProxyConfig {
- trust_client_ip_header: false,
- client_ip_header_name: String::new(),
- },
- })
- }
-
- fn seed(state: &AppState, fetched_at: Instant, discovery_enabled: bool) {
- *state.inner.premium_branding.lock().unwrap() = Some((
- fetched_at,
- PremiumBranding {
- discovery_enabled,
- ..PremiumBranding::default()
- },
- ));
- }
-
- #[test]
- fn instance_config_branding_keeps_the_discovery_fetch_time() {
- let state = self_hosted_state();
- let expired = Instant::now()
- .checked_sub(PREMIUM_BRANDING_TTL + Duration::from_secs(1))
- .unwrap();
- seed(&state, expired, false);
- state.merge_instance_config_branding(PremiumBranding {
- discovery_enabled: true,
- product_name: Some("Example".to_owned()),
- ..PremiumBranding::default()
- });
- assert_eq!(None, state.cached_premium_branding());
- }
-
- #[test]
- fn instance_config_branding_updates_a_fresh_entry_and_keeps_discovery() {
- let state = self_hosted_state();
- seed(&state, Instant::now(), false);
- state.merge_instance_config_branding(PremiumBranding {
- discovery_enabled: true,
- product_name: Some("Example".to_owned()),
- ..PremiumBranding::default()
- });
- let cached = state.cached_premium_branding().unwrap();
- assert_eq!(Some("Example"), cached.product_name.as_deref());
- assert!(!cached.discovery_enabled);
- }
-}
diff --git a/fluxer_admin/src/templates/components/message_data.rs b/fluxer_admin/src/templates/components/message_data.rs
index ec0711e26..8c674cb36 100644
--- a/fluxer_admin/src/templates/components/message_data.rs
+++ b/fluxer_admin/src/templates/components/message_data.rs
@@ -191,52 +191,3 @@ fn compare_message_ids(left: &Message, right: &Message) -> Ordering {
_ => left.id.cmp(&right.id),
}
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use serde_json::json;
-
- #[test]
- fn embeds_are_read_from_the_admin_message() {
- let messages = ordered_messages(&[json!({
- "id": "200",
- "content": "",
- "webhook_id": "400",
- "author_bot": true,
- "embeds": [{
- "type": "rich",
- "title": "Deploy finished",
- "description": "Build 42 is live",
- "url": "https://example.com/builds/42",
- "author": {"name": "CI"},
- "fields": [{"name": "Region", "value": "eu-north", "inline": true}],
- "footer": {"text": "CI pipeline"},
- "image": {"url": "https://example.com/image.png", "proxy_url": "https://media.example.com/image.png"},
- "thumbnail": {"url": "https://example.com/thumb.png"},
- "nsfw": true
- }]
- })]);
- let message = &messages[0];
- assert_eq!(message.webhook_id.as_deref(), Some("400"));
- assert_eq!(message.author_bot, Some(true));
- assert_eq!(
- message.embeds,
- vec![Embed {
- title: Some("Deploy finished".to_owned()),
- url: Some("https://example.com/builds/42".to_owned()),
- description: Some("Build 42 is live".to_owned()),
- author_name: Some("CI".to_owned()),
- fields: vec![EmbedField {
- name: "Region".to_owned(),
- value: "eu-north".to_owned(),
- inline: true,
- }],
- footer_text: Some("CI pipeline".to_owned()),
- image_url: Some("https://media.example.com/image.png".to_owned()),
- thumbnail_url: Some("https://example.com/thumb.png".to_owned()),
- nsfw: true,
- }]
- );
- }
-}
diff --git a/fluxer_admin/src/templates/components/message_list.rs b/fluxer_admin/src/templates/components/message_list.rs
index c0a736ad9..a1c0386e9 100644
--- a/fluxer_admin/src/templates/components/message_list.rs
+++ b/fluxer_admin/src/templates/components/message_list.rs
@@ -455,77 +455,3 @@ const MESSAGE_DELETE_PREFILL_SCRIPT: &str = r#"(function() {
form.querySelector('[name="basis"]').focus({preventScroll: true});
});
})();"#;
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use crate::config::ProxyConfig;
- use crate::templates::components::message_data::ordered_messages;
- use serde_json::json;
-
- fn test_config() -> AdminConfig {
- AdminConfig {
- host: "127.0.0.1".to_owned(),
- port: 3020,
- secret_key_base: "secret".to_owned(),
- base_path: String::new(),
- api_endpoint: "https://api.example.com".to_owned(),
- api_public_endpoint: "https://api.example.com".to_owned(),
- media_endpoint: "https://media.example.com".to_owned(),
- static_cdn_endpoint: "https://static.example.com".to_owned(),
- reports_bucket_origin: "https://reports.example.com".to_owned(),
- admin_endpoint: "https://admin.example.com".to_owned(),
- web_app_endpoint: "https://app.example.com".to_owned(),
- oauth_client_id: "1".to_owned(),
- oauth_client_secret: "secret".to_owned(),
- oauth_redirect_uri: "https://admin.example.com/oauth2_callback".to_owned(),
- build_version: "test".to_owned(),
- self_hosted: true,
- proxy: ProxyConfig {
- trust_client_ip_header: false,
- client_ip_header_name: "x-forwarded-for".to_owned(),
- },
- }
- }
-
- #[test]
- fn webhook_message_with_only_embeds_renders_the_embed() {
- let values = vec![json!({
- "id": "200",
- "channel_id": "100",
- "guild_id": "50",
- "author_id": "300",
- "author_username": "Status Bot",
- "author_discriminator": "0000",
- "author_avatar": null,
- "author_global_name": null,
- "author_bot": true,
- "webhook_id": "400",
- "content": "",
- "timestamp": "2026-10-29T12:00:00.000Z",
- "attachments": [],
- "embeds": [{
- "type": "rich",
- "title": "Deploy finished",
- "description": "Build 42 is live",
- "url": "https://example.com/builds/42",
- "fields": [{"name": "Region", "value": "eu-north", "inline": true}],
- "footer": {"text": "CI pipeline"},
- "image": {"url": "https://media.example.com/image.png"},
- "thumbnail": {"url": "https://media.example.com/thumb.png"}
- }]
- })];
- let messages = ordered_messages(&values);
- let html = message_list(&test_config(), "", &messages, true, None, None).into_string();
- assert!(html.contains("data-message-webhook=\"400\""));
- assert!(html.contains("data-message-embed"));
- assert!(html.contains("Deploy finished"));
- assert!(html.contains("https://example.com/builds/42"));
- assert!(html.contains("Build 42 is live"));
- assert!(html.contains("Region"));
- assert!(html.contains("eu-north"));
- assert!(html.contains("CI pipeline"));
- assert!(html.contains("https://media.example.com/image.png"));
- assert!(html.contains("https://media.example.com/thumb.png"));
- }
-}
diff --git a/fluxer_admin/src/templates/pages/discovery.rs b/fluxer_admin/src/templates/pages/discovery.rs
index 7fa27c1c4..a8cf0c201 100644
--- a/fluxer_admin/src/templates/pages/discovery.rs
+++ b/fluxer_admin/src/templates/pages/discovery.rs
@@ -353,93 +353,3 @@ pub fn discovery_page(
};
admin_layout(config, auth, "Explore", "discovery", None, content)
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use crate::{
- api::types::{InstancePremiumDiscovery, PremiumBranding},
- config::ProxyConfig,
- session::Session,
- };
-
- fn self_hosted_config() -> AdminConfig {
- AdminConfig {
- host: String::new(),
- port: 0,
- secret_key_base: String::new(),
- base_path: String::new(),
- api_endpoint: String::new(),
- api_public_endpoint: String::new(),
- media_endpoint: String::new(),
- static_cdn_endpoint: String::new(),
- reports_bucket_origin: String::new(),
- admin_endpoint: String::new(),
- web_app_endpoint: String::new(),
- oauth_client_id: String::new(),
- oauth_client_secret: String::new(),
- oauth_redirect_uri: String::new(),
- build_version: String::new(),
- self_hosted: true,
- proxy: ProxyConfig {
- trust_client_ip_header: false,
- client_ip_header_name: String::new(),
- },
- }
- }
-
- fn reviewer(well_known: &str) -> AuthContext {
- let discovery: InstancePremiumDiscovery = serde_json::from_str(well_known).unwrap();
- AuthContext {
- session: Session {
- user_id: "1".to_owned(),
- access_token: String::new(),
- created_at: 0,
- },
- admin_user: Some(
- serde_json::from_value(serde_json::json!({
- "id": "1",
- "username": "admin",
- "discriminator": "0001",
- "acls": [acl::DISCOVERY_REVIEW, acl::DISCOVERY_REMOVE],
- }))
- .unwrap(),
- ),
- pending_registration_count: None,
- branding: Some(PremiumBranding::from_discovery(&discovery)),
- }
- }
-
- fn render(well_known: &str) -> String {
- discovery_page(
- &self_hosted_config(),
- &reviewer(well_known),
- "pending",
- "csrf",
- Some(&[]),
- None,
- None,
- )
- .into_string()
- }
-
- #[test]
- fn explore_review_is_hidden_when_discovery_is_turned_off() {
- let html = render(r#"{"features":{"discovery_enabled":false}}"#);
- assert!(!html.contains("Explore review"));
- assert!(!html.contains(r#"href="/discovery?tab=pending""#));
- assert!(!html.contains("No pending applications"));
- assert!(html.contains("Explore is turned off on this instance."));
- }
-
- #[test]
- fn explore_review_shows_when_discovery_is_on() {
- for well_known in [r#"{"features":{"discovery_enabled":true}}"#, "{}"] {
- let html = render(well_known);
- assert!(html.contains("Explore review"));
- assert!(html.contains(r#"href="/discovery?tab=pending""#));
- assert!(html.contains("No pending applications"));
- assert!(!html.contains("Explore is turned off on this instance."));
- }
- }
-}
diff --git a/fluxer_admin/src/templates/pages/voice_servers.rs b/fluxer_admin/src/templates/pages/voice_servers.rs
index ad658f450..594d97de2 100644
--- a/fluxer_admin/src/templates/pages/voice_servers.rs
+++ b/fluxer_admin/src/templates/pages/voice_servers.rs
@@ -463,92 +463,3 @@ pub fn join_token_created_page(
LayoutOptions::default(),
)
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use crate::{config::ProxyConfig, session::Session};
-
- fn test_config() -> AdminConfig {
- AdminConfig {
- host: String::new(),
- port: 0,
- secret_key_base: "k".repeat(64),
- base_path: "/admin".to_owned(),
- api_endpoint: String::new(),
- api_public_endpoint: String::new(),
- media_endpoint: String::new(),
- static_cdn_endpoint: String::new(),
- reports_bucket_origin: String::new(),
- admin_endpoint: String::new(),
- web_app_endpoint: String::new(),
- oauth_client_id: String::new(),
- oauth_client_secret: String::new(),
- oauth_redirect_uri: String::new(),
- build_version: String::new(),
- self_hosted: true,
- proxy: ProxyConfig {
- trust_client_ip_header: false,
- client_ip_header_name: String::new(),
- },
- }
- }
-
- fn test_auth() -> AuthContext {
- AuthContext {
- session: Session {
- user_id: "1".to_owned(),
- access_token: String::new(),
- created_at: 0,
- },
- admin_user: None,
- pending_registration_count: None,
- branding: None,
- }
- }
-
- fn token(status: &str) -> VoiceJoinToken {
- VoiceJoinToken {
- token_id: format!("1{status}"),
- status: status.to_owned(),
- created_at: "2026-10-29T20:00:00Z".to_owned(),
- expires_at: "2026-10-29T21:00:00Z".to_owned(),
- used_at: None,
- used_server_id: None,
- revoked_at: None,
- region_id: Some("fra".to_owned()),
- region_name: None,
- server_id: None,
- hostname: None,
- notes: None,
- }
- }
-
- #[test]
- fn token_table_shows_each_status_and_revoke_only_for_pending() {
- let config = test_config();
- let tokens = ["pending", "used", "expired", "revoked"].map(token);
- let html = join_tokens_table(&config, "fra", &tokens, "csrf").into_string();
- for label in ["PENDING", "USED", "EXPIRED", "REVOKED"] {
- assert!(html.contains(label), "{label} missing");
- }
- assert_eq!(html.matches("action=revoke_token").count(), 1);
- assert!(!html.contains("fvj_"));
- }
-
- #[test]
- fn created_page_shows_the_command_once() {
- let config = test_config();
- let created = CreateVoiceJoinTokenResponse {
- token_id: "1".to_owned(),
- token: "fvj_1_secret".to_owned(),
- expires_at: "2026-10-29T21:00:00Z".to_owned(),
- command: "curl -fsSL https://fluxer.dev/install.sh | sh -s -- voice chat.example.com fvj_1_secret".to_owned(),
- };
- let html =
- join_token_created_page(&config, &test_auth(), Some("fra"), &created).into_string();
- assert_eq!(html.matches("<code>curl -fsSL").count(), 1);
- assert!(html.contains("Copy command"));
- assert!(html.contains("record those calls"));
- }
-}
diff --git a/fluxer_admin/tests/dark_palette.rs b/fluxer_admin/tests/dark_palette.rs
deleted file mode 100644
index 94245914f..000000000
--- a/fluxer_admin/tests/dark_palette.rs
+++ /dev/null
@@ -1,119 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-use std::collections::BTreeSet;
-use std::fs;
-use std::path::{Path, PathBuf};
-
-const HUES: &[&str] = &[
- "red", "green", "blue", "amber", "yellow", "orange", "purple", "indigo",
-];
-
-const UTILITIES: &[&str] = &[
- "bg", "text", "border", "ring", "divide", "outline", "from", "via", "to", "fill", "stroke",
-];
-
-const KEPT_LIGHT_VALUES: &[&str] = &["red-600", "green-600"];
-
-fn manifest_dir() -> PathBuf {
- PathBuf::from(env!("CARGO_MANIFEST_DIR"))
-}
-
-fn rust_sources(dir: &Path, out: &mut Vec<PathBuf>) {
- for entry in fs::read_dir(dir).expect("read source dir") {
- let path = entry.expect("dir entry").path();
- if path.is_dir() {
- rust_sources(&path, out);
- } else if path.extension().is_some_and(|ext| ext == "rs") {
- out.push(path);
- }
- }
-}
-
-fn is_class_char(c: char) -> bool {
- c.is_ascii_alphanumeric() || c == '-'
-}
-
-fn used_shades() -> BTreeSet<String> {
- let mut files = Vec::new();
- rust_sources(&manifest_dir().join("src"), &mut files);
- let mut shades = BTreeSet::new();
- for file in files {
- let source = fs::read_to_string(&file).expect("read source");
- for token in source.split(|c: char| !is_class_char(c)) {
- let Some((utility, rest)) = token.split_once('-') else {
- continue;
- };
- if !UTILITIES.contains(&utility) {
- continue;
- }
- let Some((hue, step)) = rest.split_once('-') else {
- continue;
- };
- if HUES.contains(&hue) && !step.is_empty() && step.chars().all(|c| c.is_ascii_digit()) {
- shades.insert(format!("{hue}-{step}"));
- }
- }
- }
- shades
-}
-
-fn dark_block() -> String {
- let css = fs::read_to_string(manifest_dir().join("src/styles/app.css")).expect("read app.css");
- let start = css
- .find(":root[data-theme=\"dark\"] {")
- .expect("dark theme block");
- let body = &css[start..];
- let end = body.find('}').expect("dark theme block end");
- body[..end].to_string()
-}
-
-fn dark_value(block: &str, shade: &str) -> Option<(f64, f64, f64)> {
- let key = format!("--color-{shade}:");
- let after = &block[block.find(&key)? + key.len()..];
- let inner = after.split_once("oklch(")?.1.split_once(')')?.0;
- let parts: Vec<f64> = inner
- .split_whitespace()
- .map(|p| p.parse().expect("oklch component"))
- .collect();
- Some((parts[0], parts[1], parts[2]))
-}
-
-fn relative_luminance((l, c, h): (f64, f64, f64)) -> f64 {
- let a = c * h.to_radians().cos();
- let b = c * h.to_radians().sin();
- let l_ = (l + 0.396_337_777_4 * a + 0.215_803_757_3 * b).powi(3);
- let m_ = (l - 0.105_561_345_8 * a - 0.063_854_172_8 * b).powi(3);
- let s_ = (l - 0.089_484_177_5 * a - 1.291_485_548 * b).powi(3);
- let r = 4.076_741_662_1 * l_ - 3.307_711_591_3 * m_ + 0.230_969_929_2 * s_;
- let g = -1.268_438_004_6 * l_ + 2.609_757_401_1 * m_ - 0.341_319_396_5 * s_;
- let bl = -0.004_196_086_3 * l_ - 0.703_418_614_7 * m_ + 1.707_614_701 * s_;
- 0.2126 * r.clamp(0.0, 1.0) + 0.7152 * g.clamp(0.0, 1.0) + 0.0722 * bl.clamp(0.0, 1.0)
-}
-
-fn contrast(fg: (f64, f64, f64), bg: (f64, f64, f64)) -> f64 {
- let (x, y) = (relative_luminance(fg), relative_luminance(bg));
- (x.max(y) + 0.05) / (x.min(y) + 0.05)
-}
-
-#[test]
-fn every_used_chromatic_shade_has_a_dark_value() {
- let block = dark_block();
- let missing: Vec<String> = used_shades()
- .into_iter()
- .filter(|shade| !shade.ends_with("-500") && !KEPT_LIGHT_VALUES.contains(&shade.as_str()))
- .filter(|shade| dark_value(&block, shade).is_none())
- .collect();
- assert!(
- missing.is_empty(),
- "dark theme has no value for {missing:?}"
- );
-}
-
-#[test]
-fn purple_badge_text_is_readable_in_dark_theme() {
- let block = dark_block();
- let text = dark_value(&block, "purple-700").expect("dark purple-700");
- let background = dark_value(&block, "purple-100").expect("dark purple-100");
- let ratio = contrast(text, background);
- assert!(ratio >= 4.5, "purple badge contrast is {ratio:.2}");
-}
diff --git a/fluxer_api/src/api/admin/tests/AdminBlocklistUrlDomain.test.ts b/fluxer_api/src/api/admin/tests/AdminBlocklistUrlDomain.test.ts
deleted file mode 100644
index 4422607c2..000000000
--- a/fluxer_api/src/api/admin/tests/AdminBlocklistUrlDomain.test.ts
+++ /dev/null
@@ -1,139 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {createTestAccount, setUserACLs, type TestAccount} from '@app/api/auth/tests/AuthTestUtils';
-import {createChannel, createGuild} from '@app/api/channel/tests/ChannelTestUtils';
-import {ensureSessionStarted} from '@app/api/message/tests/MessageTestUtils';
-import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
-import {createBuilder} from '@app/api/test/TestRequestBuilder';
-import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
-import {afterAll, beforeAll, beforeEach, describe, expect, it} from 'vitest';
-
-interface ValidationErrorResponse {
- code: string;
- errors?: Array<{path: string; message: string}>;
-}
-
-interface EntryPage {
- items: Array<{value: string; match_subdomains: boolean | null}>;
-}
-
-describe('Admin url-domain blocklist patterns', () => {
- let harness: ApiTestHarness;
- let admin: TestAccount;
-
- beforeAll(async () => {
- harness = await createApiTestHarness();
- });
-
- beforeEach(async () => {
- await harness.reset();
- admin = await setUserACLs(harness, await createTestAccount(harness), [
- 'admin:authenticate',
- 'ban:url_domain:add',
- 'ban:url_domain:check',
- 'ban:url_domain:remove',
- ]);
- });
-
- afterAll(async () => {
- await harness?.shutdown();
- });
-
- async function add(domain: string, matchSubdomains?: boolean): Promise<void> {
- await createBuilder(harness, admin.token)
- .post('/admin/blocklists/url-domain/entries')
- .body(matchSubdomains === undefined ? {domain} : {domain, match_subdomains: matchSubdomains})
- .expect(204)
- .execute();
- }
-
- async function check(value: string): Promise<boolean> {
- const json = await createBuilder<{banned: boolean}>(harness, admin.token)
- .get(`/admin/blocklists/url-domain/entries/${encodeURIComponent(value)}`)
- .expect(200)
- .execute();
- return json.banned;
- }
-
- async function list(): Promise<EntryPage['items']> {
- const json = await createBuilder<EntryPage>(harness, admin.token)
- .get('/admin/blocklists/url-domain/entries?limit=200')
- .expect(200)
- .execute();
- return json.items;
- }
-
- it('stores a canonical pattern and reports the hosts it covers', async () => {
- await add('**Shop**.OnRender.com.');
- expect(await list()).toMatchObject([{value: '*shop*.onrender.com', match_subdomains: true}]);
- expect(await check('shop-2.onrender.com')).toBe(true);
- expect(await check('https://www.myshop.onrender.com/checkout')).toBe(true);
- expect(await check('onrender.com')).toBe(false);
- expect(await check('docs.onrender.com')).toBe(false);
- });
-
- it('rejects patterns that are too broad or malformed', async () => {
- for (const domain of ['*', '*.com', '*shop*.co.uk', '*.onrender.com', '*ab*.onrender.com', 'shop.*.example.com']) {
- const json = await createBuilder<ValidationErrorResponse>(harness, admin.token)
- .post('/admin/blocklists/url-domain/entries')
- .body({domain})
- .expect(400, 'INVALID_FORM_BODY')
- .execute();
- expect(json.errors?.[0]?.path, domain).toBe('domain');
- }
- expect(await list()).toEqual([]);
- });
-
- it('stores internationalized domains in ASCII form', async () => {
- await add('Bücher.Example.');
- expect((await list()).map((entry) => entry.value)).toEqual(['xn--bcher-kva.example']);
- expect(await check('www.bücher.example')).toBe(true);
- });
-
- it('removes a pattern through any spelling that canonicalizes to it', async () => {
- await add('*shop*.onrender.com');
- await createBuilder(harness, admin.token)
- .delete(`/admin/blocklists/url-domain/entries/${encodeURIComponent('*SHOP**.onrender.com')}`)
- .expect(204)
- .execute();
- expect(await list()).toEqual([]);
- expect(await check('shop.onrender.com')).toBe(false);
- });
-
- it('blocks messages whose masked links or autolinks point at a covered host', async () => {
- await add('*shop*.onrender.com');
- const member = await createTestAccount(harness);
- const guild = await createGuild(harness, member.token, 'Links');
- const channel = await createChannel(harness, member.token, guild.id, 'general');
- await ensureSessionStarted(harness, member.token);
- for (const content of [
- '[open the store](https://shop-2.onrender.com)',
- '<https://[email protected]:8443/x>',
- 'https://SHOP.onrender.com./',
- ]) {
- await createBuilder(harness, member.token)
- .post(`/channels/${channel.id}/messages`)
- .body({content})
- .expect(403, APIErrorCodes.CONTENT_BLOCKED)
- .execute();
- }
- await createBuilder(harness, member.token)
- .post(`/channels/${channel.id}/messages`)
- .body({content: '[docs](https://docs.onrender.com) and https://onrender.com'})
- .expect(200)
- .execute();
- });
-
- it('blocks rich embeds that link to a covered host', async () => {
- await add('*shop*.onrender.com');
- const member = await createTestAccount(harness);
- const guild = await createGuild(harness, member.token, 'Embeds');
- const channel = await createChannel(harness, member.token, guild.id, 'general');
- await ensureSessionStarted(harness, member.token);
- await createBuilder(harness, member.token)
- .post(`/channels/${channel.id}/messages`)
- .body({embeds: [{title: 'Store', url: 'https://shop.onrender.com/'}]})
- .expect(403, APIErrorCodes.CONTENT_BLOCKED)
- .execute();
- });
-});
diff --git a/fluxer_api/src/api/admin/tests/AdminCustomBadgeOrder.test.ts b/fluxer_api/src/api/admin/tests/AdminCustomBadgeOrder.test.ts
deleted file mode 100644
index e64e92348..000000000
--- a/fluxer_api/src/api/admin/tests/AdminCustomBadgeOrder.test.ts
+++ /dev/null
@@ -1,111 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {createTestCustomBadge} from '@app/api/admin/tests/AdminTestUtils';
-import {createTestAccount, setUserACLs, type TestAccount} from '@app/api/auth/tests/AuthTestUtils';
-import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
-import {HTTP_STATUS} from '@app/api/test/TestConstants';
-import {createBuilder} from '@app/api/test/TestRequestBuilder';
-import {AdminACLs} from '@fluxer/constants/src/AdminACLs';
-import type {AdminCustomBadgeListResponse} from '@fluxer/schema/src/domains/admin/AdminBadgeSchemas';
-import type {ProfileBadgeResponse} from '@fluxer/schema/src/domains/user/ProfileBadgeSchemas';
-import {afterAll, beforeAll, beforeEach, describe, expect, test} from 'vitest';
-
-describe('custom badge order', () => {
- let harness: ApiTestHarness;
- let admin: TestAccount;
-
- beforeAll(async () => {
- harness = await createApiTestHarness();
- });
- afterAll(async () => {
- await harness.shutdown();
- });
- beforeEach(async () => {
- await harness.resetData();
- admin = await setUserACLs(harness, await createTestAccount(harness), [AdminACLs.WILDCARD]);
- });
-
- async function listedIds(): Promise<Array<string>> {
- const response = await createBuilder<AdminCustomBadgeListResponse>(harness, admin.token)
- .get('/admin/badges')
- .expect(HTTP_STATUS.OK)
- .execute();
- return response.badges.map((badge) => badge.id);
- }
-
- async function createBadges(): Promise<Array<string>> {
- const first = await createTestCustomBadge(harness, admin.token, 'user', 'First');
- const second = await createTestCustomBadge(harness, admin.token, 'guild', 'Second');
- const third = await createTestCustomBadge(harness, admin.token, 'user', 'Third');
- return [first.id, second.id, third.id];
- }
-
- async function expectRejectedOrder(badgeIds: Array<string>, status: number, code: string) {
- const {json} = await createBuilder<{errors?: Array<{path: string}>}>(harness, admin.token)
- .put('/admin/badges/order')
- .body({badge_ids: badgeIds})
- .expect(status, code)
- .executeWithResponse();
- return json;
- }
-
- test('saves the new order and shows it in the list and on profiles', async () => {
- const [first, second, third] = await createBadges();
- const response = await createBuilder<AdminCustomBadgeListResponse>(harness, admin.token)
- .put('/admin/badges/order')
- .body({badge_ids: [third, second, first]})
- .expect(HTTP_STATUS.OK)
- .execute();
- expect(response.badges.map((badge) => badge.id)).toEqual([third, second, first]);
- expect(await listedIds()).toEqual([third, second, first]);
-
- const target = await createTestAccount(harness);
- await createBuilder(harness, admin.token)
- .patch(`/admin/users/${target.userId}/badges`)
- .body({badge_ids: [first, third]})
- .expect(HTTP_STATUS.OK)
- .execute();
- const profile = await createBuilder<{profile_badges: Array<ProfileBadgeResponse>}>(harness, target.token)
- .get(`/users/${target.userId}/profile`)
- .expect(HTTP_STATUS.OK)
- .execute();
- expect(profile.profile_badges.filter((badge) => badge.kind === 'custom').map((badge) => badge.key)).toEqual([
- `custom:${third}`,
- `custom:${first}`,
- ]);
- });
-
- test('rejects an unknown ID and keeps the order', async () => {
- const [first, second, third] = await createBadges();
- await expectRejectedOrder([third, second, first, '1'], HTTP_STATUS.NOT_FOUND, 'UNKNOWN_BADGE');
- expect(await listedIds()).toEqual([first, second, third]);
- });
-
- test('rejects a missing ID and keeps the order', async () => {
- const [first, second, third] = await createBadges();
- const json = await expectRejectedOrder([third, first], HTTP_STATUS.BAD_REQUEST, 'INVALID_FORM_BODY');
- expect(json.errors).toEqual([expect.objectContaining({path: 'badge_ids'})]);
- expect(await listedIds()).toEqual([first, second, third]);
- });
-
- test('rejects a duplicate ID and keeps the order', async () => {
- const [first, second, third] = await createBadges();
- const json = await expectRejectedOrder([third, second, first, third], HTTP_STATUS.BAD_REQUEST, 'INVALID_FORM_BODY');
- expect(json.errors).toEqual([expect.objectContaining({path: 'badge_ids'})]);
- expect(await listedIds()).toEqual([first, second, third]);
- });
-
- test('needs the badge update ACL', async () => {
- const [first, second, third] = await createBadges();
- const reader = await setUserACLs(harness, await createTestAccount(harness), [
- AdminACLs.AUTHENTICATE,
- AdminACLs.BADGE_LIST,
- ]);
- await createBuilder(harness, reader.token)
- .put('/admin/badges/order')
- .body({badge_ids: [third, second, first]})
- .expect(HTTP_STATUS.FORBIDDEN, 'MISSING_ACL')
- .execute();
- expect(await listedIds()).toEqual([first, second, third]);
- });
-});
diff --git a/fluxer_api/src/api/admin/tests/AdminMessageEmbeds.test.ts b/fluxer_api/src/api/admin/tests/AdminMessageEmbeds.test.ts
deleted file mode 100644
index fb3c56f3a..000000000
--- a/fluxer_api/src/api/admin/tests/AdminMessageEmbeds.test.ts
+++ /dev/null
@@ -1,67 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {createTestAccount, setUserACLs} from '@app/api/auth/tests/AuthTestUtils';
-import {createGuild} from '@app/api/guild/tests/GuildTestUtils';
-import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
-import {createBuilder, createBuilderWithoutAuth} from '@app/api/test/TestRequestBuilder';
-import {createWebhook} from '@app/api/webhook/tests/WebhookTestUtils';
-import {AdminACLs} from '@fluxer/constants/src/AdminACLs';
-import type {LookupMessageResponse} from '@fluxer/schema/src/domains/admin/AdminSchemas';
-import type {MessageResponse} from '@fluxer/schema/src/domains/message/MessageResponseSchemas';
-import {afterAll, beforeAll, describe, expect, it} from 'vitest';
-import type {z} from 'zod';
-
-describe('Admin message embeds', () => {
- let harness: ApiTestHarness;
- beforeAll(async () => {
- harness = await createApiTestHarness();
- });
- afterAll(async () => {
- await harness?.shutdown();
- });
- it('returns embeds and webhook details for a webhook message with only embeds', async () => {
- const owner = await createTestAccount(harness);
- const guild = await createGuild(harness, owner.token, 'Admin Embeds Guild');
- const channelId = guild.system_channel_id!;
- const webhook = await createWebhook(harness, channelId, owner.token, 'Embed Hook');
- const message = await createBuilderWithoutAuth<MessageResponse>(harness)
- .post(`/webhooks/${webhook.id}/${webhook.token}?wait=true`)
- .body({
- username: 'Status Bot',
- embeds: [
- {
- title: 'Deploy finished',
- description: 'Build 42 is live',
- url: 'https://example.com/builds/42',
- fields: [{name: 'Region', value: 'eu-north', inline: true}],
- footer: {text: 'CI pipeline'},
- image: {url: 'https://example.com/image.png'},
- thumbnail: {url: 'https://example.com/thumb.png'},
- },
- ],
- })
- .expect(200)
- .execute();
- const admin = await setUserACLs(harness, await createTestAccount(harness), [
- AdminACLs.AUTHENTICATE,
- AdminACLs.MESSAGE_LOOKUP,
- ]);
- const result = await createBuilder<z.infer<typeof LookupMessageResponse>>(harness, admin.token)
- .get(`/admin/channels/${channelId}/messages/${message.id}?context_limit=1`)
- .expect(200)
- .execute();
- const adminMessage = result.messages.find((entry) => entry.id === message.id);
- expect(adminMessage).toBeDefined();
- expect(adminMessage!.content).toBe('');
- const embed = adminMessage!.embeds?.[0];
- expect(embed?.title).toBe('Deploy finished');
- expect(embed?.description).toBe('Build 42 is live');
- expect(embed?.url).toBe('https://example.com/builds/42');
- expect(embed?.fields?.[0]).toMatchObject({name: 'Region', value: 'eu-north', inline: true});
- expect(embed?.footer?.text).toBe('CI pipeline');
- expect(embed?.image?.url).toBeTruthy();
- expect(embed?.thumbnail?.url).toBeTruthy();
- expect(adminMessage!.webhook_id).toBe(webhook.id);
- expect(adminMessage!.author_bot).toBe(true);
- });
-});
diff --git a/fluxer_api/src/api/admin/tests/VoiceAdminController.test.ts b/fluxer_api/src/api/admin/tests/VoiceAdminController.test.ts
index 4fb97f728..9de0fdc49 100644
--- a/fluxer_api/src/api/admin/tests/VoiceAdminController.test.ts
+++ b/fluxer_api/src/api/admin/tests/VoiceAdminController.test.ts
@@ -7,7 +7,6 @@ import {HTTP_STATUS} from '@app/api/test/TestConstants';
import {createBuilder} from '@app/api/test/TestRequestBuilder';
import {VoiceRepository} from '@app/api/voice/VoiceRepository';
import {AdminACLs} from '@fluxer/constants/src/AdminACLs';
-import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
import type {
CreateVoiceRegionResponse,
CreateVoiceServerResponse,
@@ -169,74 +168,4 @@ describe('VoiceAdminController', () => {
.execute();
expect((await voiceRepository.getServer(fixture.regionId, fixture.serverId))?.notes).toBeNull();
});
- test('rejects a second server with an api key that is already in use', async () => {
- const admin = await createAdminWithAcls(harness, [
- AdminACLs.VOICE_REGION_CREATE,
- AdminACLs.VOICE_SERVER_CREATE,
- AdminACLs.VOICE_SERVER_UPDATE,
- ]);
- await createVoiceFixture(harness, admin, {
- regionId: 'voice-region-keys',
- serverId: 'voice-server-keys-1',
- endpoint: 'wss://voice-keys-1.example.com/livekit',
- apiKey: 'shared-key',
- apiSecret: 'secret-1',
- });
- await createBuilder(harness, admin.token)
- .post('/admin/voice/regions/voice-region-keys/servers')
- .body({server_id: 'voice-server-keys-2', endpoint: 'wss://b.example.com', api_key: 'shared-key', api_secret: 's'})
- .expect(HTTP_STATUS.CONFLICT, APIErrorCodes.VOICE_SERVER_API_KEY_IN_USE)
- .execute();
- await createBuilder(harness, admin.token)
- .post('/admin/voice/regions/voice-region-keys/servers')
- .body({server_id: 'voice-server-keys-1', endpoint: 'wss://b.example.com', api_key: 'other-key', api_secret: 's'})
- .expect(HTTP_STATUS.CONFLICT, APIErrorCodes.VOICE_SERVER_ID_IN_USE)
- .execute();
- await createBuilder(harness, admin.token)
- .post('/admin/voice/regions/voice-region-keys/servers')
- .body({server_id: 'voice-server-keys-2', endpoint: 'wss://b.example.com', api_key: 'other-key', api_secret: 's'})
- .execute();
- await createBuilder(harness, admin.token)
- .patch('/admin/voice/regions/voice-region-keys/servers/voice-server-keys-2')
- .body({api_key: 'shared-key'})
- .expect(HTTP_STATUS.CONFLICT, APIErrorCodes.VOICE_SERVER_API_KEY_IN_USE)
- .execute();
- await createBuilder(harness, admin.token)
- .patch('/admin/voice/regions/voice-region-keys/servers/voice-server-keys-2')
- .body({api_key: 'other-key', notes: 'same key again is fine'})
- .execute();
- });
-
- test('flags existing servers that share a key and keeps internal endpoint and draining', async () => {
- const admin = await createAdminWithAcls(harness, [
- AdminACLs.VOICE_REGION_CREATE,
- AdminACLs.VOICE_SERVER_CREATE,
- AdminACLs.VOICE_SERVER_UPDATE,
- AdminACLs.VOICE_SERVER_LIST,
- ]);
- const fixture = await createVoiceFixture(harness, admin, {
- regionId: 'voice-region-flags',
- serverId: 'voice-server-flags-1',
- endpoint: 'wss://voice-flags.example.com/livekit',
- apiKey: 'flag-key',
- apiSecret: 'flag-secret',
- });
- const first = await voiceRepository.getServer(fixture.regionId, fixture.serverId);
- await voiceRepository.upsertServer({...first!, serverId: 'voice-server-flags-2'});
- const updated = await createBuilder<UpdateVoiceServerResponse>(harness, admin.token)
- .patch(`/admin/voice/regions/${fixture.regionId}/servers/${fixture.serverId}`)
- .body({internal_endpoint: 'http://voice-flags:7880', draining: true})
- .execute();
- expect(updated.server).toMatchObject({
- internal_endpoint: 'http://voice-flags:7880',
- draining: true,
- duplicate_api_key: true,
- health: {status: 'unknown', checked_at: null, error: null},
- });
- await createBuilder(harness, admin.token)
- .patch(`/admin/voice/regions/${fixture.regionId}/servers/${fixture.serverId}`)
- .body({internal_endpoint: 'ftp://voice-flags'})
- .expect(HTTP_STATUS.BAD_REQUEST)
- .execute();
- });
});
diff --git a/fluxer_api/src/api/admin/tests/audit_coverage/EnforcementAdminAuditCases.ts b/fluxer_api/src/api/admin/tests/audit_coverage/EnforcementAdminAuditCases.ts
index bc119e055..7cfdf3965 100644
--- a/fluxer_api/src/api/admin/tests/audit_coverage/EnforcementAdminAuditCases.ts
+++ b/fluxer_api/src/api/admin/tests/audit_coverage/EnforcementAdminAuditCases.ts
@@ -32,7 +32,7 @@ export const EnforcementAdminAuditCases: ReadonlyArray<AdminAuditCoverageCase> =
method: 'GET',
route: '/admin/users/:user_id/network-block-candidates',
async prepare(context) {
- const target = await createTestAccount(context.harness, {ipAddress: '45.33.10.1'});
+ const target = await createTestAccount(context.harness, {ipAddress: '203.0.113.10'});
return {
request: {path: `/admin/users/${target.userId}/network-block-candidates`},
expected: {
diff --git a/fluxer_api/src/api/auth/services/SsoIdentityRepository.test.ts b/fluxer_api/src/api/auth/services/SsoIdentityRepository.test.ts
deleted file mode 100644
index ebb49ebbb..000000000
--- a/fluxer_api/src/api/auth/services/SsoIdentityRepository.test.ts
+++ /dev/null
@@ -1,48 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {SsoIdentityRepository} from '@app/api/auth/services/SsoIdentityRepository';
-import {createUserID} from '@app/api/BrandedTypes';
-import {setCassandraQueryExecutorForTesting} from '@app/api/database/CassandraQueryExecution';
-import {InMemoryCassandraQueryExecutor} from '@app/api/test/InMemoryCassandraQueryExecutor';
-import {afterEach, beforeEach, describe, expect, it} from 'vitest';
-
-const ALICE = createUserID(1810000000000000001n);
-const BOB = createUserID(1810000000000000002n);
-
-describe('SsoIdentityRepository', () => {
- const repository = new SsoIdentityRepository();
-
- beforeEach(async () => {
- setCassandraQueryExecutorForTesting(new InMemoryCassandraQueryExecutor());
- const claimedAt = new Date('2026-10-01T00:00:00Z');
- await repository.tryClaimIdentity({providerId: 'https://idp.one', subject: 'alice', userId: ALICE, claimedAt});
- await repository.tryClaimIdentity({providerId: 'https://idp.one', subject: 'bob', userId: BOB, claimedAt});
- await repository.tryClaimIdentity({providerId: 'https://idp.two', subject: 'alice-2', userId: ALICE, claimedAt});
- });
-
- afterEach(() => {
- setCassandraQueryExecutorForTesting(new InMemoryCassandraQueryExecutor());
- });
-
- it('releases the identities of one account and leaves the others', async () => {
- expect(await repository.releaseIdentitiesForUser(ALICE)).toBe(2);
- expect(await repository.findUserId('https://idp.one', 'alice')).toBeNull();
- expect(await repository.findUserId('https://idp.two', 'alice-2')).toBeNull();
- expect(await repository.findUserId('https://idp.one', 'bob')).toBe(BOB);
- expect(await repository.listForUser(ALICE)).toEqual([]);
- expect((await repository.listForUser(BOB)).map(({subject}) => subject)).toEqual(['bob']);
- });
-
- it('skips an index entry whose identity now belongs to another account', async () => {
- await repository.releaseIdentity('https://idp.one', 'alice');
- await repository.tryClaimIdentity({
- providerId: 'https://idp.one',
- subject: 'alice',
- userId: BOB,
- claimedAt: new Date(),
- });
- expect((await repository.listForUser(ALICE)).map(({subject}) => subject)).toEqual(['alice-2']);
- expect(await repository.releaseIdentitiesForUser(ALICE)).toBe(1);
- expect(await repository.findUserId('https://idp.one', 'alice')).toBe(BOB);
- });
-});
diff --git a/fluxer_api/src/api/auth/tests/RegistrationValidation.test.ts b/fluxer_api/src/api/auth/tests/RegistrationValidation.test.ts
deleted file mode 100644
index 3a3b656e3..000000000
--- a/fluxer_api/src/api/auth/tests/RegistrationValidation.test.ts
+++ /dev/null
@@ -1,100 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {createAuthHarness, createUniqueEmail, createUniqueUsername} from '@app/api/auth/tests/AuthTestUtils';
-import {applySharedListUpdate, resetSharedListsForTests} from '@app/api/infrastructure/activity/SharedLists';
-import type {ApiTestHarness} from '@app/api/test/ApiTestHarness';
-import {createBuilder, createBuilderWithoutAuth} from '@app/api/test/TestRequestBuilder';
-import {afterAll, beforeAll, beforeEach, describe, expect, it} from 'vitest';
-
-interface ValidationErrorResponse {
- code: string;
- message: string;
- errors?: Array<{
- path: string;
- code: string;
- message: string;
- }>;
-}
-
-describe('Registration validation', () => {
- let harness: ApiTestHarness;
- beforeAll(async () => {
- harness = await createAuthHarness();
- });
- beforeEach(async () => {
- await harness.reset();
- });
- afterAll(async () => {
- await harness?.shutdown();
- });
- it('rejects blocked registration email TLDs as invalid email', async () => {
- applySharedListUpdate('email_tld_blocked', 'blocked\n');
- try {
- await createBuilderWithoutAuth(harness)
- .post('/auth/register')
- .body({
- email: '[email protected]',
- username: createUniqueUsername(),
- global_name: 'Test User',
- password: 'a-strong-password',
- date_of_birth: '2000-01-01',
- consent: true,
- })
- .expect(400)
- .execute();
- } finally {
- resetSharedListsForTests();
- }
- });
- it('defers a missing date of birth to the date of birth step', async () => {
- const registered = await createBuilderWithoutAuth<{token: string}>(harness)
- .post('/auth/register')
- .body({
- email: createUniqueEmail(),
- username: createUniqueUsername(),
- global_name: 'Test User',
- password: 'a-strong-password',
- consent: true,
- })
- .execute();
- const me = await createBuilder<{date_of_birth_required: boolean; traits: Array<string>}>(harness, registered.token)
- .get('/users/@me')
- .execute();
- expect(me.date_of_birth_required).toBe(true);
- expect(me.traits).toContain('dob_deferred');
- });
- it('rejects an impossible calendar date with INVALID_DATE_OF_BIRTH_FORMAT', async () => {
- for (const dateOfBirth of ['2000-02-30', '2000-13-45']) {
- const json = await createBuilderWithoutAuth<ValidationErrorResponse>(harness)
- .post('/auth/register')
- .body({
- email: createUniqueEmail('impossible-dob'),
- username: createUniqueUsername('impossible'),
- global_name: 'Test User',
- password: 'a-strong-password',
- date_of_birth: dateOfBirth,
- consent: true,
- })
- .expect(400, 'INVALID_FORM_BODY')
- .execute();
- const dateOfBirthError = json.errors?.find((e) => e.path === 'date_of_birth');
- expect(dateOfBirthError?.code).toBe('INVALID_DATE_OF_BIRTH_FORMAT');
- }
- });
- it('rejects a real calendar date below the minimum age with MUST_BE_MINIMUM_AGE', async () => {
- const json = await createBuilderWithoutAuth<ValidationErrorResponse>(harness)
- .post('/auth/register')
- .body({
- email: createUniqueEmail('underage'),
- username: createUniqueUsername('underage'),
- global_name: 'Test User',
- password: 'a-strong-password',
- date_of_birth: '2020-01-01',
- consent: true,
- })
- .expect(400, 'INVALID_FORM_BODY')
- .execute();
- const dateOfBirthError = json.errors?.find((e) => e.path === 'date_of_birth');
- expect(dateOfBirthError?.code).toBe('MUST_BE_MINIMUM_AGE');
- });
-});
diff --git a/fluxer_api/src/api/auth/tests/UsernameSignIn.test.ts b/fluxer_api/src/api/auth/tests/UsernameSignIn.test.ts
deleted file mode 100644
index e28db7775..000000000
--- a/fluxer_api/src/api/auth/tests/UsernameSignIn.test.ts
+++ /dev/null
@@ -1,1503 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- clearTestEmails,
- createAuthHarness,
- createTestAccount,
- createUniqueUsername,
- findLastTestEmail,
- type LoginSuccessResponse,
- listTestEmails,
- setUserACLs,
-} from '@app/api/auth/tests/AuthTestUtils';
-import {createPasswordResetToken, createUserID} from '@app/api/BrandedTypes';
-import {getConfig} from '@app/api/Config';
-import {getCachedInstancePremiumMode, setCachedInstancePremiumMode} from '@app/api/limits/InstancePremiumModeCache';
-import {
- getAdminRepository,
- getInstanceConfigRepository,
- getRateLimitService,
- getUserRepository,
-} from '@app/api/middleware/ServiceSingletons';
-import type {ApiTestHarness} from '@app/api/test/ApiTestHarness';
-import {type CaptchaErrorBody, solveCaptchaChallenge, useCheapCaptcha} from '@app/api/test/CaptchaTestUtils';
-import {createBuilder, createBuilderWithoutAuth} from '@app/api/test/TestRequestBuilder';
-import {getAccountTier} from '@app/api/user/AccountTier';
-import {grantPremium} from '@app/api/user/tests/UserTestUtils';
-import {AccountIdentityModes} from '@fluxer/constants/src/AccountIdentityConstants';
-import {AdminACLs} from '@fluxer/constants/src/AdminACLs';
-import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
-import {PremiumFlags, UserPremiumTypes} from '@fluxer/constants/src/UserConstants';
-import {ValidationErrorCodes} from '@fluxer/constants/src/ValidationErrorCodes';
-import {getSameIpDecisionKey} from '@fluxer/ip_utils/src/IpAddress';
-import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it} from 'vitest';
-
-const PASSWORD = 'username-mode-password-123';
-const NEW_PASSWORD = 'username-mode-new-password-456';
-const HAS_SESSION_STARTED = BigInt(1) << BigInt(39);
-
-interface ValidationErrorBody {
- code: string;
- errors: Array<{path: string; code: string}>;
-}
-
-interface UsernameAccount {
- userId: string;
- token: string;
- username: string;
- password: string;
-}
-
-interface CurrentUser {
- id: string;
- username: string;
- discriminator: string;
- email: string | null;
- acls?: Array<string>;
-}
-
-const EMAIL_ONLY_PUBLIC_ROUTES: ReadonlyArray<[string, string]> = [
- ['POST', '/auth/verify'],
- ['POST', '/auth/forgot'],
- ['POST', '/auth/email-revert'],
- ['POST', '/auth/authorize-ip'],
- ['POST', '/auth/ip-authorization/resend'],
- ['POST', '/reports/dsa/email/send'],
- ['POST', '/reports/dsa/email/verify'],
-];
-
-const EMAIL_ONLY_USER_ROUTES: ReadonlyArray<[string, string]> = [
- ['POST', '/auth/verify/resend'],
- ['POST', '/users/@me/mfa/backup-codes/challenge'],
- ['POST', '/users/@me/mfa/backup-codes/challenge/resend'],
- ['POST', '/users/@me/mfa/backup-codes/challenge/verify'],
- ['POST', '/users/@me/mfa/backup-codes/challenge/regenerate'],
- ['POST', '/users/@me/password-change/start'],
- ['POST', '/users/@me/password-change/resend'],
- ['POST', '/users/@me/password-change/verify'],
- ['POST', '/users/@me/password-change/complete'],
- ['POST', '/users/@me/email-change/start'],
- ['POST', '/users/@me/email-change/resend-original'],
- ['POST', '/users/@me/email-change/verify-original'],
- ['POST', '/users/@me/email-change/request-new'],
- ['POST', '/users/@me/email-change/resend-new'],
- ['POST', '/users/@me/email-change/verify-new'],
- ['POST', '/users/@me/email-change/apply'],
- ['POST', '/users/@me/email-change/bounced/request-new'],
- ['POST', '/users/@me/email-change/bounced/resend-new'],
- ['POST', '/users/@me/email-change/bounced/verify-new'],
-];
-
-describe('Username sign-in', () => {
- let harness: ApiTestHarness;
- const config = getConfig();
- let originalSelfHosted: boolean;
- let originalHosts: {webApp: string; webAppOrigins: Array<string>; baseDomain: string};
-
- beforeAll(async () => {
- harness = await createAuthHarness();
- });
- beforeEach(async () => {
- await harness.reset();
- await clearTestEmails(harness);
- originalSelfHosted = config.instance.selfHosted;
- originalHosts = {
- webApp: config.endpoints.webApp,
- webAppOrigins: config.endpoints.webAppOrigins,
- baseDomain: config.instance.baseDomain,
- };
- });
- afterEach(() => {
- config.instance.selfHosted = originalSelfHosted;
- config.endpoints.webApp = originalHosts.webApp;
- config.endpoints.webAppOrigins = originalHosts.webAppOrigins;
- config.instance.baseDomain = originalHosts.baseDomain;
- getInstanceConfigRepository().clearCacheForTesting();
- });
- afterAll(async () => {
- await harness?.shutdown();
- });
-
- async function useUsernameMode(): Promise<void> {
- config.instance.selfHosted = true;
- await getInstanceConfigRepository().setAccountIdentityMode(AccountIdentityModes.USERNAME, 'setup');
- await getInstanceConfigRepository().setAppPublicConfig({setup: {configured: true}});
- }
-
- async function allowInstantAccounts(): Promise<void> {
- await getInstanceConfigRepository().updateAuthConfig({instant_accounts: {enabled: true}});
- }
-
- function useInstanceHosts(): void {
- config.endpoints.webApp = 'https://chat.example.org';
- config.endpoints.webAppOrigins = ['https://chat.example.org', 'https://alias.example.net:8443'];
- config.instance.baseDomain = 'example.org';
- }
-
- async function registerFromOlderApp(body: Record<string, unknown>): Promise<{user_id: string; token: string}> {
- return await createBuilderWithoutAuth<{user_id: string; token: string}>(harness)
- .post('/auth/register')
- .body({password: PASSWORD, date_of_birth: '2000-01-01', ...body})
- .execute();
- }
-
- async function useSelfHostedEmailMode(): Promise<void> {
- config.instance.selfHosted = true;
- await getInstanceConfigRepository().setAccountIdentityMode(
- AccountIdentityModes.EMAIL,
- 'existing_instance',
- 'random',
- );
- await getInstanceConfigRepository().setAppPublicConfig({setup: {configured: true}});
- }
-
- async function useSelfHostedEmailUniqueMode(): Promise<void> {
- config.instance.selfHosted = true;
- await getInstanceConfigRepository().setAccountIdentityMode(AccountIdentityModes.EMAIL, 'setup', 'none');
- await getInstanceConfigRepository().setAppPublicConfig({setup: {configured: true}});
- }
-
- async function registerEmailAccount(username: string): Promise<UsernameAccount & {email: string}> {
- const email = `${username.toLowerCase()}-${Date.now()}@example.com`;
- const registration = await createBuilderWithoutAuth<{user_id: string; token: string}>(harness)
- .post('/auth/register')
- .body({email, username, global_name: 'Email Person', password: PASSWORD, date_of_birth: '2000-01-01'})
- .execute();
- await markSessionStarted(registration.user_id);
- await createBuilder(harness, '')
- .post(`/test/users/${registration.user_id}/security-flags`)
- .body({email_verified: true})
- .execute();
- return {userId: registration.user_id, token: registration.token, username, password: PASSWORD, email};
- }
-
- async function markSessionStarted(userId: string): Promise<void> {
- await createBuilder(harness, '')
- .patch(`/test/users/${userId}/flags`)
- .body({flags: HAS_SESSION_STARTED.toString()})
- .execute();
- }
-
- async function registerUsernameAccount(username = createUniqueUsername('uname')): Promise<UsernameAccount> {
- const registration = await createBuilderWithoutAuth<{user_id: string; token: string}>(harness)
- .post('/auth/register')
- .body({username, global_name: 'Username Person', password: PASSWORD, date_of_birth: '2000-01-01'})
- .execute();
- await markSessionStarted(registration.user_id);
- return {userId: registration.user_id, token: registration.token, username, password: PASSWORD};
- }
-
- async function fetchCurrentUser(token: string): Promise<CurrentUser> {
- return await createBuilder<CurrentUser>(harness, token).get('/users/@me').execute();
- }
-
- async function expectFieldErrors(
- request: {path: string; method?: string; body: unknown; token?: string},
- expected: Array<{path: string; code: string}>,
- ): Promise<void> {
- const builder = createBuilder<ValidationErrorBody>(harness, request.token ?? '');
- const method = (request.method ?? 'POST').toLowerCase() as 'post' | 'patch' | 'put';
- const {json} = await builder[method](request.path)
- .body(request.body)
- .expect(400, 'INVALID_FORM_BODY')
- .executeWithResponse();
- expect(json.errors.map(({path, code}) => ({path, code}))).toEqual(expected);
- }
-
- async function login(body: Record<string, unknown>): Promise<LoginSuccessResponse> {
- return await createBuilderWithoutAuth<LoginSuccessResponse>(harness).post('/auth/login').body(body).execute();
- }
-
- async function startSession(token: string): Promise<void> {
- await createBuilder(harness, '')
- .post('/test/rpc-session-init')
- .body({type: 'session', token, version: 1, ip: '127.0.0.1'})
- .execute();
- }
-
- async function markPremiumDiscriminator(userId: string): Promise<void> {
- await createBuilder(harness, '')
- .patch(`/test/users/${userId}/premium-flags`)
- .body({premium_flags: PremiumFlags.DISCRIMINATOR})
- .execute();
- }
-
- describe('registration', () => {
- it('accepts an email from older apps and never stores it', async () => {
- const existing = await createTestAccount(harness);
- await clearTestEmails(harness);
- await useUsernameMode();
- const registration = await createBuilderWithoutAuth<{user_id: string; token: string}>(harness)
- .post('/auth/register')
- .body({
- email: existing.email,
- username: 'withemail',
- password: PASSWORD,
- date_of_birth: '2000-01-01',
- })
- .execute();
- const user = await getUserRepository().findUniqueAssert(createUserID(BigInt(registration.user_id)));
- expect({email: user.email, emailVerified: user.emailVerified, username: user.username}).toEqual({
- email: null,
- emailVerified: true,
- username: 'withemail',
- });
- expect((await fetchCurrentUser(registration.token)).discriminator).toBe('0000');
- expect(await listTestEmails(harness, {recipient: existing.email})).toEqual([]);
- await createBuilderWithoutAuth(harness)
- .post('/auth/register')
- .body({email: 'not-an-address', username: 'withoddemail', password: PASSWORD, date_of_birth: '2000-01-01'})
- .execute();
- });
-
- it('takes the username from an address at the instance host', async () => {
- await useUsernameMode();
- useInstanceHosts();
- const registration = await createBuilderWithoutAuth<{user_id: string; token: string}>(harness)
- .post('/auth/register')
- .body({
- email: '[email protected]',
- global_name: 'Shown Name',
- password: PASSWORD,
- date_of_birth: '2000-01-01',
- })
- .execute();
- const me = await fetchCurrentUser(registration.token);
- expect({username: me.username, discriminator: me.discriminator, email: me.email}).toEqual({
- username: 'Local_Person',
- discriminator: '0000',
- email: null,
- });
- expect((await login({email: '[email protected]', password: PASSWORD})).user_id).toBe(
- registration.user_id,
- );
- const fromDomain = await createBuilderWithoutAuth<{user_id: string; token: string}>(harness)
- .post('/auth/register')
- .body({email: '[email protected]', password: PASSWORD, date_of_birth: '2000-01-01'})
- .execute();
- expect((await fetchCurrentUser(fromDomain.token)).username).toBe('domainperson');
- });
-
- it('refuses a taken username from an address at the instance host', async () => {
- await useUsernameMode();
- useInstanceHosts();
- await registerUsernameAccount('TakenLocal');
- await expectFieldErrors(
- {
- path: '/auth/register',
- body: {email: '[email protected]', password: PASSWORD, date_of_birth: '2000-01-01'},
- },
- [{path: 'username', code: ValidationErrorCodes.USERNAME_ALREADY_TAKEN}],
- );
- });
-
- it('asks for an address at the instance host instead of turning a foreign address into a username', async () => {
- await useUsernameMode();
- useInstanceHosts();
- for (const email of [
- '[email protected]@chat.example.org',
- '[email protected]/elsewhere',
- 'secretlocal',
- ]) {
- await expectFieldErrors(
- {
- path: '/auth/register',
- body: {email, global_name: 'Visible Name', password: PASSWORD, date_of_birth: '2000-01-01'},
- },
- [{path: 'email', code: ValidationErrorCodes.INSTANCE_ADDRESS_REQUIRED}],
- );
- }
- const {json} = await createBuilderWithoutAuth<{errors: Array<{message: string}>}>(harness)
- .post('/auth/register')
- .body({email: '[email protected]', password: PASSWORD, date_of_birth: '2000-01-01'})
- .expect(400, 'INVALID_FORM_BODY')
- .executeWithResponse();
- expect(json.errors[0]!.message).toContain('@chat.example.org');
- const named = await registerFromOlderApp({
- email: '[email protected]',
- username: 'chosenname',
- global_name: 'Visible Name',
- });
- const user = await getUserRepository().findUniqueAssert(createUserID(BigInt(named.user_id)));
- expect({username: user.username, email: user.email}).toEqual({username: 'chosenname', email: null});
- });
-
- it('refuses a local part that cannot be a username with the username field codes', async () => {
- await useUsernameMode();
- useInstanceHosts();
- for (const [email, code] of [
- ['[email protected]', ValidationErrorCodes.USERNAME_RESERVED_VALUE],
- ['[email protected]', ValidationErrorCodes.USERNAME_CANNOT_CONTAIN_RESERVED_TERMS],
- ['alex#[email protected]', ValidationErrorCodes.USERNAME_INVALID_CHARACTERS],
- ['[email protected]', ValidationErrorCodes.USERNAME_INVALID_CHARACTERS],
- ] as const) {
- await expectFieldErrors(
- {path: '/auth/register', body: {email, password: PASSWORD, date_of_birth: '2000-01-01'}},
- [{path: 'username', code}],
- );
- }
- });
-
- it('maps a local part to the same username at sign-up and sign-in', async () => {
- await useUsernameMode();
- useInstanceHosts();
- for (const [email, username] of [
- ['tagged#[email protected]', 'tagged'],
- ['zerotag#[email protected]', 'zerotag'],
- ['[email protected]', 'dotted_name'],
- ] as const) {
- const registration = await registerFromOlderApp({email});
- expect((await fetchCurrentUser(registration.token)).username).toBe(username);
- expect((await login({email, password: PASSWORD})).user_id).toBe(registration.user_id);
- expect((await login({login: username, password: PASSWORD})).user_id).toBe(registration.user_id);
- }
- });
-
- it('matches the instance host with a port, in any case, as an IDN and through app origin aliases', async () => {
- await useUsernameMode();
- useInstanceHosts();
- const withPort = await registerFromOlderApp({email: '[email protected]:8443'});
- expect((await fetchCurrentUser(withPort.token)).username).toBe('portperson');
- const throughAlias = await registerFromOlderApp({email: '[email protected]'});
- expect((await fetchCurrentUser(throughAlias.token)).username).toBe('aliasperson');
- expect((await login({email: '[email protected]:8443', password: PASSWORD})).user_id).toBe(
- throughAlias.user_id,
- );
- config.endpoints.webApp = 'https://bücher.example';
- config.endpoints.webAppOrigins = ['https://bücher.example'];
- const idn = await registerFromOlderApp({email: 'idnperson@Bücher.example'});
- expect((await fetchCurrentUser(idn.token)).username).toBe('idnperson');
- expect((await login({email: '[email protected]', password: PASSWORD})).user_id).toBe(idn.user_id);
- });
-
- it('requires a username when a password is given', async () => {
- await useUsernameMode();
- await expectFieldErrors({path: '/auth/register', body: {global_name: 'No Username', password: PASSWORD}}, [
- {path: 'username', code: ValidationErrorCodes.USERNAME_LENGTH_INVALID},
- ]);
- });
-
- it('creates an email-less verified account and makes the first one the admin', async () => {
- await useUsernameMode();
- const first = await registerUsernameAccount('firstperson');
- const second = await registerUsernameAccount('secondperson');
- const firstUser = await getUserRepository().findUniqueAssert(createUserID(BigInt(first.userId)));
- const secondUser = await getUserRepository().findUniqueAssert(createUserID(BigInt(second.userId)));
- expect(firstUser.email).toBeNull();
- expect(firstUser.emailVerified).toBe(true);
- expect([...firstUser.acls]).toEqual([AdminACLs.WILDCARD]);
- expect([...secondUser.acls]).toEqual([]);
- expect(await listTestEmails(harness)).toEqual([]);
- });
-
- it('refuses a username that is already taken in any case', async () => {
- await useUsernameMode();
- await registerUsernameAccount('TakenName');
- await expectFieldErrors({path: '/auth/register', body: {username: 'takenname', password: PASSWORD}}, [
- {path: 'username', code: ValidationErrorCodes.USERNAME_ALREADY_TAKEN},
- ]);
- });
-
- it('derives a free username for an unclaimed account', async () => {
- await useUsernameMode();
- await allowInstantAccounts();
- await registerUsernameAccount('sharedname');
- const unclaimed = await createBuilderWithoutAuth<{user_id: string; token: string}>(harness)
- .post('/auth/register')
- .body({global_name: 'sharedname'})
- .execute();
- const user = await getUserRepository().findUniqueAssert(createUserID(BigInt(unclaimed.user_id)));
- expect(user.username.toLowerCase()).not.toBe('sharedname');
- expect(user.username.toLowerCase().startsWith('sharedname')).toBe(true);
- expect(getAccountTier(user)).toBe('unclaimed');
- });
-
- it('refuses a credential-less approval registration on a username instance', async () => {
- await useUsernameMode();
- await getInstanceConfigRepository().setRegistrationConfig({mode: 'approval'});
- await createBuilderWithoutAuth(harness)
- .post('/auth/register')
- .body({global_name: 'No Credentials', date_of_birth: '2000-01-01'})
- .expect(400, APIErrorCodes.REGISTRATION_CREDENTIALS_REQUIRED)
- .execute();
- expect(await getInstanceConfigRepository().getPendingRegistrations()).toEqual([]);
- });
-
- it('accepts an approval registration with a username and password', async () => {
- await useUsernameMode();
- await getInstanceConfigRepository().setRegistrationConfig({mode: 'approval'});
- const registration = await createBuilderWithoutAuth<{registration_pending_approval: true; user_id: string}>(
- harness,
- )
- .post('/auth/register')
- .body({username: 'reviewedperson', password: PASSWORD, date_of_birth: '2000-01-01'})
- .execute();
- expect(registration).toEqual({registration_pending_approval: true, user_id: expect.any(String)});
- });
- });
-
- describe('login', () => {
- it('signs in with a username in any case and with the full tag', async () => {
- await useUsernameMode();
- const account = await registerUsernameAccount('LoginPerson');
- const me = await fetchCurrentUser(account.token);
- const byName = await login({login: 'loginperson', password: PASSWORD});
- expect(byName.user_id).toBe(account.userId);
- const byTag = await login({login: `LoginPerson#${me.discriminator.padStart(4, '0')}`, password: PASSWORD});
- expect(byTag.user_id).toBe(account.userId);
- });
-
- it('returns the same error for a wrong password, a wrong tag and an unknown username', async () => {
- await useUsernameMode();
- const account = await registerUsernameAccount('wrongcreds');
- const me = await fetchCurrentUser(account.token);
- const wrongTag = ((Number(me.discriminator) % 9999) + 1).toString().padStart(4, '0');
- const expected = [
- {path: 'login', code: ValidationErrorCodes.INVALID_LOGIN_OR_PASSWORD},
- {path: 'password', code: ValidationErrorCodes.INVALID_LOGIN_OR_PASSWORD},
- ];
- await expectFieldErrors({path: '/auth/login', body: {login: 'wrongcreds', password: NEW_PASSWORD}}, expected);
- await expectFieldErrors(
- {path: '/auth/login', body: {login: `wrongcreds#${wrongTag}`, password: PASSWORD}},
- expected,
- );
- await expectFieldErrors({path: '/auth/login', body: {login: 'nobodyhere', password: PASSWORD}}, expected);
- await expectFieldErrors({path: '/auth/login', body: {login: 'not a handle!', password: PASSWORD}}, expected);
- });
-
- it('signs older apps in with a username or username@host in the email field', async () => {
- await useUsernameMode();
- useInstanceHosts();
- const account = await registerUsernameAccount('OldAppPerson');
- for (const email of [
- 'oldappperson',
- 'oldappperson#[email protected]',
- 'oldappperson#[email protected]',
- ]) {
- expect((await login({email, password: PASSWORD})).user_id).toBe(account.userId);
- }
- });
-
- it('gives older apps the wrong-credentials error on the email field', async () => {
- await useUsernameMode();
- useInstanceHosts();
- await registerUsernameAccount('oldappwrong');
- const expected = [
- {path: 'email', code: ValidationErrorCodes.INVALID_LOGIN_OR_PASSWORD},
- {path: 'password', code: ValidationErrorCodes.INVALID_LOGIN_OR_PASSWORD},
- ];
- for (const body of [
- {email: '[email protected]', password: NEW_PASSWORD},
- {email: 'oldappwrong', password: NEW_PASSWORD},
- {email: '[email protected]', password: PASSWORD},
- {email: '[email protected]', password: PASSWORD},
- {email: 'oldappwrong#[email protected]', password: PASSWORD},
- {email: '[email protected]@chat.example.org', password: PASSWORD},
- {email: '[email protected]/elsewhere', password: PASSWORD},
- {email: '[email protected]', password: PASSWORD},
- {email: '[email protected]', login: 'oldappwrong', password: NEW_PASSWORD},
- ]) {
- await expectFieldErrors({path: '/auth/login', body}, expected);
- }
- });
-
- it('reports a missing identifier on email', async () => {
- await useUsernameMode();
- await expectFieldErrors({path: '/auth/login', body: {password: PASSWORD}}, [
- {path: 'email', code: ValidationErrorCodes.INVALID_FORMAT},
- ]);
- });
-
- it('limits failed sign-ins per username and source without locking out other sources', async () => {
- await useUsernameMode();
- const account = await registerUsernameAccount('lockouttarget');
- await getInstanceConfigRepository().updateCaptchaConfig({enabled: false});
- const previous = {testMode: config.dev.testModeEnabled, disabled: config.dev.disableRateLimits};
- config.dev.testModeEnabled = false;
- config.dev.disableRateLimits = false;
- try {
- for (let attempt = 0; attempt < 5; attempt++) {
- await createBuilderWithoutAuth(harness)
- .post('/auth/login')
- .header('x-forwarded-for', '198.51.100.40')
- .body({login: account.username, password: NEW_PASSWORD})
- .expect(400, 'INVALID_FORM_BODY')
- .execute();
- }
- await createBuilderWithoutAuth(harness)
- .post('/auth/login')
- .header('x-forwarded-for', '198.51.100.40')
- .body({login: account.username.toUpperCase(), password: PASSWORD})
- .expect(429)
- .execute();
- const owner = await createBuilderWithoutAuth<LoginSuccessResponse>(harness)
- .post('/auth/login')
- .header('x-forwarded-for', '198.51.100.41')
- .body({login: account.username, password: PASSWORD})
- .execute();
- expect(owner.user_id).toBe(account.userId);
- } finally {
- config.dev.testModeEnabled = previous.testMode;
- config.dev.disableRateLimits = previous.disabled;
- }
- });
-
- it('lets the owner through a spent shared limit from a known address or with a solved captcha', async () => {
- await useUsernameMode();
- const account = await registerUsernameAccount('floodtarget');
- await getInstanceConfigRepository().updateCaptchaConfig({enabled: false});
- const previous = {testMode: config.dev.testModeEnabled, disabled: config.dev.disableRateLimits};
- config.dev.testModeEnabled = false;
- config.dev.disableRateLimits = false;
- const attempt = (ip: string, password: string, captchaToken?: string) => {
- const builder = createBuilderWithoutAuth<LoginSuccessResponse>(harness)
- .post('/auth/login')
- .header('x-forwarded-for', ip)
- .body({login: account.username, password});
- if (captchaToken) builder.header('X-Captcha-Token', captchaToken);
- return builder;
- };
- try {
- expect((await attempt('198.51.100.90', PASSWORD).execute()).user_id).toBe(account.userId);
- for (let source = 0; source < 20; source++) {
- for (let failure = 0; failure < 5; failure++) {
- await attempt(`203.0.113.${source + 1}`, NEW_PASSWORD)
- .expect(400, 'INVALID_FORM_BODY')
- .execute();
- }
- }
- await attempt('198.51.100.91', NEW_PASSWORD).expect(429).execute();
- await attempt('198.51.100.92', PASSWORD).expect(429).execute();
- expect((await attempt('198.51.100.90', PASSWORD).execute()).user_id).toBe(account.userId);
- await useCheapCaptcha();
- const {json} = await createBuilderWithoutAuth<CaptchaErrorBody>(harness)
- .post('/auth/login')
- .header('x-forwarded-for', '198.51.100.93')
- .body({login: account.username, password: PASSWORD})
- .expect(400, APIErrorCodes.CAPTCHA_REQUIRED)
- .executeWithResponse();
- const token = await solveCaptchaChallenge(json);
- expect((await attempt('198.51.100.93', PASSWORD, token).execute()).user_id).toBe(account.userId);
- } finally {
- config.dev.testModeEnabled = previous.testMode;
- config.dev.disableRateLimits = previous.disabled;
- }
- });
-
- it('counts only failed sign-ins against the shared per-username limit', async () => {
- await useUsernameMode();
- const account = await registerUsernameAccount('sharedcount');
- await getInstanceConfigRepository().updateCaptchaConfig({enabled: false});
- const previous = {testMode: config.dev.testModeEnabled, disabled: config.dev.disableRateLimits};
- config.dev.testModeEnabled = false;
- config.dev.disableRateLimits = false;
- try {
- for (let source = 0; source < 20; source++) {
- for (let success = 0; success < 5; success++) {
- await createBuilderWithoutAuth(harness)
- .post('/auth/login')
- .header('x-forwarded-for', `203.0.113.${source + 101}`)
- .body({login: account.username, password: PASSWORD})
- .execute();
- }
- }
- await createBuilderWithoutAuth(harness)
- .post('/auth/login')
- .header('x-forwarded-for', '198.51.100.95')
- .body({login: account.username, password: NEW_PASSWORD})
- .expect(400, 'INVALID_FORM_BODY')
- .execute();
- } finally {
- config.dev.testModeEnabled = previous.testMode;
- config.dev.disableRateLimits = previous.disabled;
- }
- });
-
- it('never lets crafted identifiers fill another source bucket for a named user', async () => {
- await useUsernameMode();
- const account = await registerUsernameAccount('bucketvictim');
- await getInstanceConfigRepository().updateCaptchaConfig({enabled: false});
- const previous = {testMode: config.dev.testModeEnabled, disabled: config.dev.disableRateLimits};
- config.dev.testModeEnabled = false;
- config.dev.disableRateLimits = false;
- const victimSource = getSameIpDecisionKey('198.51.100.71') ?? '198.51.100.71';
- try {
- for (const [field, attackerIp] of [
- ['email', '198.51.100.70'],
- ['login', '198.51.100.72'],
- ] as const) {
- for (let attempt = 0; attempt < 5; attempt++) {
- await createBuilderWithoutAuth(harness)
- .post('/auth/login')
- .header('x-forwarded-for', attackerIp)
- .body({[field]: `${account.username}:${victimSource}`, password: NEW_PASSWORD})
- .expect(400, 'INVALID_FORM_BODY')
- .execute();
- }
- }
- const owner = await createBuilderWithoutAuth<LoginSuccessResponse>(harness)
- .post('/auth/login')
- .header('x-forwarded-for', '198.51.100.71')
- .body({login: account.username, password: PASSWORD})
- .execute();
- expect(owner.user_id).toBe(account.userId);
- } finally {
- config.dev.testModeEnabled = previous.testMode;
- config.dev.disableRateLimits = previous.disabled;
- }
- });
-
- it('counts older-app sign-ins against the same per-username limit', async () => {
- await useUsernameMode();
- useInstanceHosts();
- const account = await registerUsernameAccount('oldapplimit');
- await getInstanceConfigRepository().updateCaptchaConfig({enabled: false});
- const previous = {testMode: config.dev.testModeEnabled, disabled: config.dev.disableRateLimits};
- config.dev.testModeEnabled = false;
- config.dev.disableRateLimits = false;
- try {
- for (const email of ['oldapplimit', '[email protected]', '[email protected]']) {
- await createBuilderWithoutAuth(harness)
- .post('/auth/login')
- .header('x-forwarded-for', '198.51.100.50')
- .body({email, password: NEW_PASSWORD})
- .expect(400, 'INVALID_FORM_BODY')
- .execute();
- }
- for (let attempt = 0; attempt < 2; attempt++) {
- await createBuilderWithoutAuth(harness)
- .post('/auth/login')
- .header('x-forwarded-for', '198.51.100.50')
- .body({login: account.username, password: NEW_PASSWORD})
- .expect(400, 'INVALID_FORM_BODY')
- .execute();
- }
- await createBuilderWithoutAuth(harness)
- .post('/auth/login')
- .header('x-forwarded-for', '198.51.100.50')
- .body({email: '[email protected]', password: PASSWORD})
- .expect(429)
- .execute();
- } finally {
- config.dev.testModeEnabled = previous.testMode;
- config.dev.disableRateLimits = previous.disabled;
- }
- });
-
- it('never asks for IP authorization', async () => {
- await useUsernameMode();
- const account = await registerUsernameAccount('newipperson');
- const result = await createBuilderWithoutAuth<LoginSuccessResponse>(harness)
- .post('/auth/login')
- .header('x-forwarded-for', '203.0.113.77')
- .body({login: account.username, password: PASSWORD})
- .execute();
- expect(result.user_id).toBe(account.userId);
- expect(await listTestEmails(harness)).toEqual([]);
- });
- });
-
- describe('email-only routes', () => {
- it('refuses every email route before minting anything', async () => {
- await useUsernameMode();
- const admin = await registerUsernameAccount('emailrouteadmin');
- const account = await registerUsernameAccount('emailrouteuser');
- for (const [method, path] of EMAIL_ONLY_PUBLIC_ROUTES) {
- const {response, json} = await createBuilderWithoutAuth<{code: string}>(harness)
- [method.toLowerCase() as 'post'](path)
- .body({})
- .executeRaw();
- expect({path, status: response.status, code: json?.code}).toEqual({
- path,
- status: 400,
- code: APIErrorCodes.EMAIL_UNAVAILABLE_ON_INSTANCE,
- });
- }
- for (const [method, path] of EMAIL_ONLY_USER_ROUTES) {
- const {response, json} = await createBuilder<{code: string}>(harness, account.token)
- [method.toLowerCase() as 'post'](path)
- .body({})
- .executeRaw();
- expect({path, status: response.status, code: json?.code}).toEqual({
- path,
- status: 400,
- code: APIErrorCodes.EMAIL_UNAVAILABLE_ON_INSTANCE,
- });
- }
- for (const [method, path] of [
- ['post', `/admin/users/${account.userId}/password-reset`],
- ['post', `/admin/users/${account.userId}/verification-email`],
- ['patch', `/admin/users/${account.userId}/email`],
- ['put', `/admin/users/${account.userId}/email-verification`],
- ] as const) {
- const {response, json} = await createBuilder<{code: string}>(harness, admin.token)
- [method](path)
- .body({})
- .executeRaw();
- expect({path, status: response.status, code: json?.code}).toEqual({
- path,
- status: 400,
- code: APIErrorCodes.EMAIL_UNAVAILABLE_ON_INSTANCE,
- });
- }
- expect(await listTestEmails(harness)).toEqual([]);
- });
-
- it('treats a missing email verification as satisfied', async () => {
- await useUsernameMode();
- const account = await registerUsernameAccount('unverifiedguild');
- await createBuilder(harness, '')
- .post(`/test/users/${account.userId}/security-flags`)
- .body({email_verified: false})
- .execute();
- await createBuilder(harness, account.token).post('/guilds').body({name: 'Username Guild'}).execute();
- });
- });
-
- describe('usernames stay unique', () => {
- it('refuses a rename to a name someone else holds', async () => {
- await useUsernameMode();
- await registerUsernameAccount('holder');
- const other = await registerUsernameAccount('renamer');
- await expectFieldErrors(
- {
- path: '/users/@me',
- method: 'PATCH',
- token: other.token,
- body: {username: 'HOLDER', password: PASSWORD},
- },
- [{path: 'username', code: ValidationErrorCodes.USERNAME_ALREADY_TAKEN}],
- );
- const renamed = await createBuilder<CurrentUser>(harness, other.token)
- .patch('/users/@me')
- .body({username: 'freshname', password: PASSWORD})
- .execute();
- expect(renamed.username).toBe('freshname');
- });
-
- it('refuses an admin rename to a name someone else holds', async () => {
- await useUsernameMode();
- const admin = await registerUsernameAccount('renameadmin');
- await registerUsernameAccount('adminholder');
- const target = await registerUsernameAccount('admintarget');
- const {response, json} = await createBuilder<ValidationErrorBody>(harness, admin.token)
- .patch(`/admin/users/${target.userId}/username`)
- .body({username: 'AdminHolder'})
- .executeRaw();
- expect(response.status).toBe(400);
- expect(json.errors.map(({path, code}) => ({path, code}))).toEqual([
- {path: 'username', code: ValidationErrorCodes.USERNAME_ALREADY_TAKEN},
- ]);
- });
-
- it('lets an unclaimed account claim with a username and password', async () => {
- await useUsernameMode();
- await allowInstantAccounts();
- const unclaimed = await createBuilderWithoutAuth<{user_id: string; token: string}>(harness)
- .post('/auth/register')
- .body({global_name: 'Guest'})
- .execute();
- await markSessionStarted(unclaimed.user_id);
- const claimed = await createBuilder<CurrentUser>(harness, unclaimed.token)
- .patch('/users/@me')
- .body({username: 'claimedguest', new_password: PASSWORD})
- .execute();
- expect({username: claimed.username, discriminator: claimed.discriminator}).toEqual({
- username: 'claimedguest',
- discriminator: '0000',
- });
- const result = await login({login: 'claimedguest', password: PASSWORD});
- expect(result.user_id).toBe(unclaimed.user_id);
- });
- });
-
- describe('username availability', () => {
- async function checkAvailability(username: string): Promise<boolean> {
- const result = await createBuilderWithoutAuth<{available: boolean}>(harness)
- .get(`/auth/username-availability?username=${encodeURIComponent(username)}`)
- .execute();
- return result.available;
- }
-
- async function expectAvailabilityFieldError(username: string, code: string): Promise<void> {
- const {json} = await createBuilderWithoutAuth<ValidationErrorBody>(harness)
- .get(`/auth/username-availability?username=${encodeURIComponent(username)}`)
- .expect(400, 'INVALID_FORM_BODY')
- .executeWithResponse();
- expect(json.errors.map(({path, code}) => ({path, code}))).toEqual([{path: 'username', code}]);
- }
-
- it('reports a held name as taken in any case and a free one as available', async () => {
- await useUsernameMode();
- await registerUsernameAccount('HeldName');
- expect(await checkAvailability('heldname')).toBe(false);
- expect(await checkAvailability('HELDNAME')).toBe(false);
- expect(await checkAvailability(' heldname ')).toBe(false);
- expect(await checkAvailability('freename')).toBe(true);
- });
-
- it('rejects an invalid or reserved name with the registration field codes', async () => {
- await useUsernameMode();
- await expectAvailabilityFieldError('not valid', ValidationErrorCodes.USERNAME_INVALID_CHARACTERS);
- await expectAvailabilityFieldError('everyone', ValidationErrorCodes.USERNAME_RESERVED_VALUE);
- await expectAvailabilityFieldError('myfluxername', ValidationErrorCodes.USERNAME_CANNOT_CONTAIN_RESERVED_TERMS);
- await expectAvailabilityFieldError('a'.repeat(33), ValidationErrorCodes.USERNAME_LENGTH_INVALID);
- });
-
- it('refuses an email instance with tags and the hosted service', async () => {
- await useSelfHostedEmailMode();
- await createBuilderWithoutAuth(harness)
- .get('/auth/username-availability?username=anyname')
- .expect(400, APIErrorCodes.USERNAME_SIGN_IN_ONLY)
- .execute();
- config.instance.selfHosted = false;
- await createBuilderWithoutAuth(harness)
- .get('/auth/username-availability?username=anyname')
- .expect(400, APIErrorCodes.USERNAME_SIGN_IN_ONLY)
- .execute();
- });
- });
-
- describe('password change', () => {
- it('is username mode only', async () => {
- const account = await createTestAccount(harness);
- await createBuilder(harness, account.token)
- .post('/users/@me/password')
- .body({password: account.password, new_password: NEW_PASSWORD})
- .expect(400, APIErrorCodes.USERNAME_SIGN_IN_ONLY)
- .execute();
- });
-
- it('needs sudo, replaces the session and ends every other session', async () => {
- await useUsernameMode();
- const account = await registerUsernameAccount('changepassword');
- const otherSession = await login({login: account.username, password: PASSWORD});
- await createBuilder(harness, account.token)
- .post('/users/@me/password')
- .body({new_password: NEW_PASSWORD})
- .expect(403, APIErrorCodes.SUDO_MODE_REQUIRED)
- .execute();
- const result = await createBuilder<{token: string; auth_session_id_hash: string}>(harness, account.token)
- .post('/users/@me/password')
- .body({password: PASSWORD, new_password: NEW_PASSWORD})
- .execute();
- expect(result.token.length).toBeGreaterThan(0);
- expect(result.auth_session_id_hash.length).toBeGreaterThan(0);
- await createBuilder(harness, account.token).get('/users/@me').expect(401).execute();
- await createBuilder(harness, otherSession.token).get('/users/@me').expect(401).execute();
- expect((await fetchCurrentUser(result.token)).id).toBe(account.userId);
- await expectFieldErrors({path: '/auth/login', body: {login: account.username, password: PASSWORD}}, [
- {path: 'login', code: ValidationErrorCodes.INVALID_LOGIN_OR_PASSWORD},
- {path: 'password', code: ValidationErrorCodes.INVALID_LOGIN_OR_PASSWORD},
- ]);
- expect((await login({login: account.username, password: NEW_PASSWORD})).user_id).toBe(account.userId);
- });
- });
-
- describe('single sign-on accounts without a password', () => {
- it('cannot set a password or create a recovery kit with an empty sudo body', async () => {
- await useUsernameMode();
- const account = await registerUsernameAccount('ssoperson');
- const users = getUserRepository();
- const userId = createUserID(BigInt(account.userId));
- const user = await users.findUniqueAssert(userId);
- await users.patchUpsert(userId, {password_hash: null, traits: new Set(['sso'])}, user.toRow());
- await expectFieldErrors({path: '/users/@me/password', token: account.token, body: {new_password: NEW_PASSWORD}}, [
- {path: 'new_password', code: ValidationErrorCodes.PASSWORD_NOT_SET},
- ]);
- await expectFieldErrors({path: '/users/@me/recovery-kit', token: account.token, body: {}}, [
- {path: 'password', code: ValidationErrorCodes.PASSWORD_NOT_SET},
- ]);
- expect((await users.findUniqueAssert(userId)).passwordHash).toBeNull();
- });
- });
-
- describe('admin password reset link', () => {
- it('is username mode only', async () => {
- const admin = await setUserACLs(harness, await createTestAccount(harness), [AdminACLs.WILDCARD]);
- const target = await createTestAccount(harness);
- await createBuilder(harness, admin.token)
- .post(`/admin/users/${target.userId}/password-reset-link`)
- .expect(400, APIErrorCodes.USERNAME_SIGN_IN_ONLY)
- .execute();
- });
-
- it('needs its own ACL', async () => {
- await useUsernameMode();
- await registerUsernameAccount('bootstrapadmin');
- const limitedAdmin = await registerUsernameAccount('limitedadmin');
- await createBuilder(harness, '')
- .post(`/test/users/${limitedAdmin.userId}/acls`)
- .body({acls: [AdminACLs.AUTHENTICATE, AdminACLs.USER_UPDATE_EMAIL]})
- .execute();
- const target = await registerUsernameAccount('linktargetacl');
- await createBuilder(harness, limitedAdmin.token)
- .post(`/admin/users/${target.userId}/password-reset-link`)
- .expect(403)
- .execute();
- });
-
- it('issues a link that resets the password through /auth/reset and is audited', async () => {
- await useUsernameMode();
- const admin = await registerUsernameAccount('resetadmin');
- const target = await registerUsernameAccount('resettarget');
- const before = Date.now();
- const link = await createBuilder<{url: string; expires_at: string}>(harness, admin.token)
- .post(`/admin/users/${target.userId}/password-reset-link`)
- .execute();
- const [base, token] = link.url.split('/reset#token=');
- expect(base).toBe(config.email.appBaseUrl);
- expect(token).toMatch(/^[A-Za-z0-9_-]+$/);
- const expiresAt = Date.parse(link.expires_at);
- expect(expiresAt).toBeGreaterThan(before + 59 * 60 * 1000);
- expect(expiresAt).toBeLessThanOrEqual(Date.now() + 60 * 60 * 1000);
- const validation = await createBuilderWithoutAuth<{valid: boolean}>(harness)
- .get(`/auth/reset/${token}`)
- .execute();
- expect(validation.valid).toBe(true);
- const reset = await createBuilderWithoutAuth<LoginSuccessResponse>(harness)
- .post('/auth/reset')
- .body({token, password: NEW_PASSWORD})
- .execute();
- expect(reset.user_id).toBe(target.userId);
- await createBuilder(harness, target.token).get('/users/@me').expect(401).execute();
- expect((await login({login: target.username, password: NEW_PASSWORD})).user_id).toBe(target.userId);
- await createBuilderWithoutAuth(harness)
- .post('/auth/reset')
- .body({token, password: PASSWORD})
- .expect(400)
- .execute();
- const audit = (await getAdminRepository().listAllAuditLogsPaginated(1000)).find(
- (log) => log.action === 'create_password_reset_link',
- );
- expect(audit?.targetId.toString()).toBe(target.userId);
- expect(Object.fromEntries(audit!.metadata)).toEqual({});
- expect(await listTestEmails(harness)).toEqual([]);
- });
-
- it('issues a working link for an account that kept an email address', async () => {
- const admin = await setUserACLs(harness, await createTestAccount(harness), [AdminACLs.WILDCARD]);
- const target = await createTestAccount(harness);
- await useUsernameMode();
- const token = (
- await createBuilder<{url: string}>(harness, admin.token)
- .post(`/admin/users/${target.userId}/password-reset-link`)
- .execute()
- ).url.split('/reset#token=')[1]!;
- expect(
- (await createBuilderWithoutAuth<{valid: boolean}>(harness).get(`/auth/reset/${token}`).execute()).valid,
- ).toBe(true);
- const reset = await createBuilderWithoutAuth<LoginSuccessResponse>(harness)
- .post('/auth/reset')
- .body({token, password: NEW_PASSWORD})
- .execute();
- expect(reset.user_id).toBe(target.userId);
- });
-
- it('revokes earlier links when a new one is created', async () => {
- await useUsernameMode();
- const admin = await registerUsernameAccount('revokeadmin');
- const target = await registerUsernameAccount('revoketarget');
- const createLink = async () =>
- (
- await createBuilder<{url: string}>(harness, admin.token)
- .post(`/admin/users/${target.userId}/password-reset-link`)
- .execute()
- ).url.split('/reset#token=')[1]!;
- const first = await createLink();
- const second = await createLink();
- const validate = async (token: string) =>
- (await createBuilderWithoutAuth<{valid: boolean}>(harness).get(`/auth/reset/${token}`).execute()).valid;
- expect(await validate(first)).toBe(false);
- expect(await validate(second)).toBe(true);
- });
- });
-
- describe('tags', () => {
- const DISCRIMINATOR_REFUSED = [
- {path: 'discriminator', code: ValidationErrorCodes.DISCRIMINATOR_NOT_SUPPORTED_ON_INSTANCE},
- ];
-
- it('keeps unique names when username mode is given a random tag style', async () => {
- config.instance.selfHosted = true;
- await getInstanceConfigRepository().setAccountIdentityMode(AccountIdentityModes.USERNAME, 'setup', 'random');
- await getInstanceConfigRepository().setAppPublicConfig({setup: {configured: true}});
- expect(await getInstanceConfigRepository().getTagStyle()).toBe('none');
- const account = await registerUsernameAccount('ForcedUnique');
- expect((await fetchCurrentUser(account.token)).discriminator).toBe('0000');
- await expectFieldErrors(
- {
- path: '/auth/register',
- body: {username: 'forcedunique', password: PASSWORD, date_of_birth: '2000-01-01'},
- },
- [{path: 'username', code: ValidationErrorCodes.USERNAME_ALREADY_TAKEN}],
- );
- });
-
- it('gives every new person the 0000 tag', async () => {
- await useUsernameMode();
- await allowInstantAccounts();
- const account = await registerUsernameAccount('tagperson');
- expect((await fetchCurrentUser(account.token)).discriminator).toBe('0000');
- const unclaimed = await createBuilderWithoutAuth<{user_id: string}>(harness)
- .post('/auth/register')
- .body({global_name: 'tagperson'})
- .execute();
- const unclaimedUser = await getUserRepository().findUniqueAssert(createUserID(BigInt(unclaimed.user_id)));
- expect(unclaimedUser.discriminator).toBe(0);
- expect(unclaimedUser.username.toLowerCase()).not.toBe('tagperson');
- });
-
- it('never lets two people hold the same name', async () => {
- await useUsernameMode();
- await registerUsernameAccount('OnlyOne');
- for (const username of ['onlyone', 'ONLYONE', 'DeletedUser']) {
- await expectFieldErrors({path: '/auth/register', body: {username, password: PASSWORD}}, [
- {path: 'username', code: ValidationErrorCodes.USERNAME_ALREADY_TAKEN},
- ]);
- }
- });
-
- it('keeps a name held while an admin deletion is pending', async () => {
- await useUsernameMode();
- const admin = await registerUsernameAccount('heldadmin');
- const target = await registerUsernameAccount('PendingGone');
- await createBuilder(harness, admin.token)
- .put(`/admin/users/${target.userId}/deletion`)
- .body({days_until_deletion: 30, basis: {type: 'holder_request'}})
- .execute();
- await expectFieldErrors({path: '/auth/register', body: {username: 'pendinggone', password: PASSWORD}}, [
- {path: 'username', code: ValidationErrorCodes.USERNAME_ALREADY_TAKEN},
- ]);
- });
-
- it('signs in with name#0 and name#0000 and refuses any other tag', async () => {
- await useUsernameMode();
- const account = await registerUsernameAccount('ZeroTag');
- expect((await login({login: 'zerotag#0', password: PASSWORD})).user_id).toBe(account.userId);
- expect((await login({login: 'ZeroTag#0000', password: PASSWORD})).user_id).toBe(account.userId);
- await expectFieldErrors({path: '/auth/login', body: {login: 'zerotag#0001', password: PASSWORD}}, [
- {path: 'login', code: ValidationErrorCodes.INVALID_LOGIN_OR_PASSWORD},
- {path: 'password', code: ValidationErrorCodes.INVALID_LOGIN_OR_PASSWORD},
- ]);
- });
-
- it('refuses a tag change, even with the custom tag perk, and keeps 0000 through renames', async () => {
- await useUsernameMode();
- const account = await registerUsernameAccount('fixedtag');
- await grantPremium(harness, account.userId, UserPremiumTypes.SUBSCRIPTION);
- await expectFieldErrors(
- {path: '/users/@me', method: 'PATCH', token: account.token, body: {discriminator: '1234', password: PASSWORD}},
- DISCRIMINATOR_REFUSED,
- );
- await expectFieldErrors(
- {
- path: '/users/@me',
- method: 'PATCH',
- token: account.token,
- body: {username: 'fixedtagtwo', discriminator: '0042', password: PASSWORD},
- },
- DISCRIMINATOR_REFUSED,
- );
- const unchanged = await createBuilder<CurrentUser>(harness, account.token)
- .patch('/users/@me')
- .body({discriminator: '0000', password: PASSWORD})
- .execute();
- expect(unchanged.discriminator).toBe('0000');
- const renamed = await createBuilder<CurrentUser>(harness, account.token)
- .patch('/users/@me')
- .body({username: 'FixedTagTwo', password: PASSWORD})
- .execute();
- expect({username: renamed.username, discriminator: renamed.discriminator}).toEqual({
- username: 'FixedTagTwo',
- discriminator: '0000',
- });
- const user = await getUserRepository().findUniqueAssert(createUserID(BigInt(account.userId)));
- expect(user.premiumFlags & PremiumFlags.DISCRIMINATOR).toBe(0);
- });
-
- it('refuses an admin tag change and keeps 0000 on admin renames', async () => {
- await useUsernameMode();
- const admin = await registerUsernameAccount('tagadmin');
- const target = await registerUsernameAccount('tagtarget');
- const {response, json} = await createBuilder<ValidationErrorBody>(harness, admin.token)
- .patch(`/admin/users/${target.userId}/username`)
- .body({username: 'tagtargetnew', discriminator: '0007'})
- .executeRaw();
- expect(response.status).toBe(400);
- expect(json.errors.map(({path, code}) => ({path, code}))).toEqual(DISCRIMINATOR_REFUSED);
- await createBuilder(harness, admin.token)
- .patch(`/admin/users/${target.userId}/username`)
- .body({username: 'TagTargetNew'})
- .execute();
- const user = await getUserRepository().findUniqueAssert(createUserID(BigInt(target.userId)));
- expect({username: user.username, discriminator: user.discriminator}).toEqual({
- username: 'TagTargetNew',
- discriminator: 0,
- });
- });
-
- it('skips the premium tag reroll at session start', async () => {
- await useUsernameMode();
- const account = await registerUsernameAccount('noreroll');
- await markPremiumDiscriminator(account.userId);
- const previousPremiumMode = getCachedInstancePremiumMode();
- setCachedInstancePremiumMode('mirror');
- try {
- await startSession(account.token);
- } finally {
- setCachedInstancePremiumMode(previousPremiumMode);
- }
- const user = await getUserRepository().findUniqueAssert(createUserID(BigInt(account.userId)));
- expect(user.discriminator).toBe(0);
- expect(user.premiumFlags & PremiumFlags.DISCRIMINATOR).toBe(PremiumFlags.DISCRIMINATOR);
- });
-
- it('keeps random tags for bots', async () => {
- await useUsernameMode();
- const owner = await registerUsernameAccount('botowner');
- const app = await createBuilder<{id: string; bot?: {discriminator: string}}>(harness, owner.token)
- .post('/oauth2/applications')
- .body({name: 'botowner', redirect_uris: []})
- .execute();
- expect(app.bot?.discriminator).toMatch(/^\d{4}$/);
- expect(app.bot?.discriminator).not.toBe('0000');
- });
-
- it('checks tag availability by name alone', async () => {
- await useUsernameMode();
- await registerUsernameAccount('heldtag');
- const account = await registerUsernameAccount('checktag');
- const checkTag = async (username: string, discriminator: string) =>
- (
- await createBuilder<{taken: boolean}>(harness, account.token)
- .get(`/users/check-tag?username=${username}&discriminator=${discriminator}`)
- .execute()
- ).taken;
- expect(await checkTag('HeldTag', '0000')).toBe(true);
- expect(await checkTag('heldtag', '1234')).toBe(true);
- expect(await checkTag('CheckTag', '0000')).toBe(false);
- expect(await checkTag('freetag', '0000')).toBe(false);
- });
-
- it('shows bare names in the change log and finds people by bare name', async () => {
- await useUsernameMode();
- const admin = await registerUsernameAccount('logadmin');
- const target = await registerUsernameAccount('logbefore');
- await createBuilder(harness, target.token)
- .patch('/users/@me')
- .body({username: 'logafter', password: PASSWORD})
- .execute();
- const log = await createBuilder<{entries: Array<{field: string; old_value: string; new_value: string}>}>(
- harness,
- admin.token,
- )
- .get(`/admin/users/${target.userId}/change-log`)
- .execute();
- const tagChanges = log.entries
- .filter((entry) => entry.field === 'fluxer_tag')
- .map(({old_value, new_value}) => ({old_value, new_value}));
- expect(tagChanges).toEqual([{old_value: 'logbefore', new_value: 'logafter'}]);
- const found = await createBuilder<{users: Array<{id: string}>}>(harness, admin.token)
- .get('/admin/users?resolve=LogAfter')
- .execute();
- expect(found.users.map((user) => user.id)).toEqual([target.userId]);
- });
- });
-
- describe('email mode with unique usernames', () => {
- const TAG_REFUSED = [{path: 'discriminator', code: ValidationErrorCodes.DISCRIMINATOR_NOT_SUPPORTED_ON_INSTANCE}];
-
- it('gives email registrations 0000 and refuses a taken name in any case', async () => {
- await useSelfHostedEmailUniqueMode();
- const account = await registerEmailAccount('EmailUnique');
- expect((await fetchCurrentUser(account.token)).discriminator).toBe('0000');
- await expectFieldErrors(
- {
- path: '/auth/register',
- body: {email: '[email protected]', username: 'emailunique', password: PASSWORD},
- },
- [{path: 'username', code: ValidationErrorCodes.USERNAME_ALREADY_TAKEN}],
- );
- });
-
- it('keeps email sign-in and refuses a username login', async () => {
- await useSelfHostedEmailUniqueMode();
- const account = await registerEmailAccount('emailsignin');
- expect((await login({email: account.email, password: PASSWORD})).user_id).toBe(account.userId);
- await expectFieldErrors({path: '/auth/login', body: {login: 'emailsignin', password: PASSWORD}}, [
- {path: 'login', code: ValidationErrorCodes.INVALID_EMAIL_FORMAT},
- ]);
- });
-
- it('refuses a rename to a held name and any tag change', async () => {
- await useSelfHostedEmailUniqueMode();
- await registerEmailAccount('heldbyother');
- const account = await registerEmailAccount('renamer');
- await grantPremium(harness, account.userId, UserPremiumTypes.SUBSCRIPTION);
- await expectFieldErrors(
- {
- path: '/users/@me',
- method: 'PATCH',
- token: account.token,
- body: {username: 'HeldByOther', password: PASSWORD},
- },
- [{path: 'username', code: ValidationErrorCodes.USERNAME_ALREADY_TAKEN}],
- );
- await expectFieldErrors(
- {path: '/users/@me', method: 'PATCH', token: account.token, body: {discriminator: '1234', password: PASSWORD}},
- TAG_REFUSED,
- );
- const renamed = await createBuilder<CurrentUser>(harness, account.token)
- .patch('/users/@me')
- .body({username: 'renamedfree', password: PASSWORD})
- .execute();
- expect({username: renamed.username, discriminator: renamed.discriminator}).toEqual({
- username: 'renamedfree',
- discriminator: '0000',
- });
- const user = await getUserRepository().findUniqueAssert(createUserID(BigInt(account.userId)));
- expect(user.premiumFlags & PremiumFlags.DISCRIMINATOR).toBe(0);
- });
-
- it('skips the premium tag reroll at session start', async () => {
- await useSelfHostedEmailUniqueMode();
- const account = await registerEmailAccount('emailnoreroll');
- await markPremiumDiscriminator(account.userId);
- const previousPremiumMode = getCachedInstancePremiumMode();
- setCachedInstancePremiumMode('mirror');
- try {
- await startSession(account.token);
- } finally {
- setCachedInstancePremiumMode(previousPremiumMode);
- }
- const user = await getUserRepository().findUniqueAssert(createUserID(BigInt(account.userId)));
- expect(user.discriminator).toBe(0);
- expect(user.premiumFlags & PremiumFlags.DISCRIMINATOR).toBe(PremiumFlags.DISCRIMINATOR);
- });
-
- it('answers the availability check', async () => {
- await useSelfHostedEmailUniqueMode();
- await registerEmailAccount('availheld');
- const taken = await createBuilderWithoutAuth<{available: boolean}>(harness)
- .get('/auth/username-availability?username=AvailHeld')
- .execute();
- expect(taken.available).toBe(false);
- const free = await createBuilderWithoutAuth<{available: boolean}>(harness)
- .get('/auth/username-availability?username=availfree')
- .execute();
- expect(free.available).toBe(true);
- });
-
- it('still serves the email routes', async () => {
- await useSelfHostedEmailUniqueMode();
- const account = await registerEmailAccount('emailroutes');
- await createBuilderWithoutAuth(harness).post('/auth/forgot').body({email: account.email}).expect(204).execute();
- await createBuilder(harness, account.token)
- .get('/users/@me/recovery-kit')
- .expect(400, APIErrorCodes.USERNAME_SIGN_IN_ONLY)
- .execute();
- });
- });
-
- describe('email mode stays as it was', () => {
- it('signs in by email and by login on the hosted service', async () => {
- const account = await createTestAccount(harness);
- expect((await login({email: account.email, password: account.password})).user_id).toBe(account.userId);
- expect((await login({login: account.email, password: account.password})).user_id).toBe(account.userId);
- await expectFieldErrors({path: '/auth/login', body: {email: account.email, password: NEW_PASSWORD}}, [
- {path: 'email', code: ValidationErrorCodes.INVALID_EMAIL_OR_PASSWORD},
- {path: 'password', code: ValidationErrorCodes.INVALID_EMAIL_OR_PASSWORD},
- ]);
- await expectFieldErrors({path: '/auth/login', body: {login: account.email, password: NEW_PASSWORD}}, [
- {path: 'login', code: ValidationErrorCodes.INVALID_EMAIL_OR_PASSWORD},
- {path: 'password', code: ValidationErrorCodes.INVALID_EMAIL_OR_PASSWORD},
- ]);
- await expectFieldErrors({path: '/auth/login', body: {login: account.username, password: account.password}}, [
- {path: 'login', code: ValidationErrorCodes.INVALID_EMAIL_FORMAT},
- ]);
- });
-
- for (const variant of ['hosted', 'self-hosted email'] as const) {
- it(`answers older-app bodies as before on the ${variant} instance`, async () => {
- if (variant === 'self-hosted email') {
- await useSelfHostedEmailMode();
- }
- useInstanceHosts();
- const account = await createTestAccount(harness);
- const notAnAddress = [
- {path: 'email', code: ValidationErrorCodes.INVALID_EMAIL_FORMAT},
- {path: 'email', code: ValidationErrorCodes.INVALID_EMAIL_LOCAL_PART},
- ];
- await expectFieldErrors(
- {path: '/auth/login', body: {email: account.username, password: PASSWORD}},
- notAnAddress,
- );
- await expectFieldErrors(
- {path: '/auth/login', body: {email: `${account.username}@chat.example.org`, password: PASSWORD}},
- [
- {path: 'email', code: ValidationErrorCodes.INVALID_EMAIL_OR_PASSWORD},
- {path: 'password', code: ValidationErrorCodes.INVALID_EMAIL_OR_PASSWORD},
- ],
- );
- await expectFieldErrors({path: '/auth/login', body: {password: PASSWORD}}, [
- {path: 'email', code: ValidationErrorCodes.INVALID_FORMAT},
- ]);
- for (const login of ['', null]) {
- await expectFieldErrors({path: '/auth/login', body: {login, password: PASSWORD}}, [
- {path: 'email', code: ValidationErrorCodes.INVALID_FORMAT},
- ]);
- }
- for (const strayLogin of ['', null, 5, 'x'.repeat(400)]) {
- const signedIn = await createBuilderWithoutAuth<LoginSuccessResponse>(harness)
- .post('/auth/login')
- .body({email: account.email, login: strayLogin, password: account.password})
- .execute();
- expect(signedIn.user_id).toBe(account.userId);
- }
- await expectFieldErrors(
- {path: '/auth/register', body: {email: 'not-an-address', password: PASSWORD, consent: true}},
- notAnAddress,
- );
- await expectFieldErrors(
- {
- path: '/auth/register',
- body: {email: account.email, password: PASSWORD, date_of_birth: '2000-01-01', consent: true},
- },
- [{path: 'email', code: ValidationErrorCodes.EMAIL_ALREADY_IN_USE}],
- );
- const email = `instancelocal-${Date.now()}@chat.example.org`;
- const registration = await createBuilderWithoutAuth<{user_id: string}>(harness)
- .post('/auth/register')
- .body({email, global_name: 'Hosted Person', password: PASSWORD, date_of_birth: '2000-01-01', consent: true})
- .execute();
- const user = await getUserRepository().findUniqueAssert(createUserID(BigInt(registration.user_id)));
- expect({email: user.email, username: user.username}).toEqual({email, username: 'Hosted_Person'});
- });
- }
-
- it('counts the per-email sign-in limit before it needs a client IP', async () => {
- const account = await createTestAccount(harness);
- const emailLimit = {
- identifier: `login:email:${account.email.toLowerCase()}`,
- maxAttempts: 5,
- windowMs: 15 * 60 * 1000,
- };
- await getRateLimitService().resetLimit(emailLimit.identifier);
- await createBuilderWithoutAuth(harness)
- .post('/auth/login')
- .header('x-forwarded-for', '')
- .body({email: account.email, password: account.password})
- .expect(403)
- .execute();
- expect((await getRateLimitService().peekLimit(emailLimit)).remaining).toBe(4);
- });
-
- it('reports email in discovery on the hosted service', async () => {
- const discovery = await createBuilderWithoutAuth<{features: {account_identity: string}}>(harness)
- .get('/.well-known/fluxer')
- .execute();
- expect(discovery.features.account_identity).toBe(AccountIdentityModes.EMAIL);
- });
-
- for (const variant of ['hosted', 'self-hosted email'] as const) {
- it(`allocates random tags and allows tag changes on the ${variant} instance`, async () => {
- if (variant === 'self-hosted email') {
- await useSelfHostedEmailMode();
- }
- const account = await createTestAccount(harness);
- const me = await fetchCurrentUser(account.token);
- expect(me.discriminator).toMatch(/^\d{4}$/);
- expect(me.discriminator).not.toBe('0000');
- await grantPremium(harness, account.userId, UserPremiumTypes.SUBSCRIPTION);
- const changed = await createBuilder<CurrentUser>(harness, account.token)
- .patch('/users/@me')
- .body({discriminator: '0042', password: account.password})
- .execute();
- expect(changed.discriminator).toBe('0042');
- });
- }
-
- it('rerolls an expired premium tag on the hosted service', async () => {
- const account = await createTestAccount(harness);
- await markPremiumDiscriminator(account.userId);
- await startSession(account.token);
- const user = await getUserRepository().findUniqueAssert(createUserID(BigInt(account.userId)));
- expect(user.premiumFlags & PremiumFlags.DISCRIMINATOR).toBe(0);
- expect(user.discriminator).not.toBe(0);
- });
-
- for (const variant of ['hosted', 'self-hosted email'] as const) {
- it(`runs forgot and reset by email on the ${variant} instance`, async () => {
- if (variant === 'self-hosted email') {
- await useSelfHostedEmailMode();
- }
- const account = await createTestAccount(harness);
- await createBuilderWithoutAuth(harness).post('/auth/forgot').body({email: account.email}).expect(204).execute();
- const resetEmail = findLastTestEmail(
- await listTestEmails(harness, {recipient: account.email}),
- 'password_reset',
- );
- const token = resetEmail!.metadata!.token!;
- const reset = await createBuilderWithoutAuth<LoginSuccessResponse>(harness)
- .post('/auth/reset')
- .body({token, password: NEW_PASSWORD})
- .execute();
- expect(reset.user_id).toBe(account.userId);
- expect((await login({email: account.email, password: NEW_PASSWORD})).user_id).toBe(account.userId);
- });
- }
-
- it('uses up the emailed reset link even when the session cannot be created', async () => {
- const account = await createTestAccount(harness);
- await createBuilderWithoutAuth(harness).post('/auth/forgot').body({email: account.email}).expect(204).execute();
- const token = findLastTestEmail(await listTestEmails(harness, {recipient: account.email}), 'password_reset')!
- .metadata!.token!;
- const users = getUserRepository();
- const userId = createUserID(BigInt(account.userId));
- const user = await users.findUniqueAssert(userId);
- await users.patchUpsert(userId, {traits: new Set(['registration_pending_approval'])}, user.toRow());
- await createBuilderWithoutAuth(harness)
- .post('/auth/reset')
- .body({token, password: NEW_PASSWORD})
- .expect(403)
- .execute();
- const validation = await createBuilderWithoutAuth<{valid: boolean}>(harness)
- .get(`/auth/reset/${token}`)
- .execute();
- expect(validation.valid).toBe(false);
- });
-
- it('keeps allowing an email on self-hosted email instances', async () => {
- await useSelfHostedEmailMode();
- const account = await createTestAccount(harness);
- const user = await getUserRepository().findUniqueAssert(createUserID(BigInt(account.userId)));
- expect(user.email).toBe(account.email);
- expect((await login({email: account.email, password: account.password})).user_id).toBe(account.userId);
- });
-
- it('rejects a reset token without an email', async () => {
- const account = await createTestAccount(harness);
- const token = createPasswordResetToken('a'.repeat(64));
- await getUserRepository().createPasswordResetToken({
- token_: token,
- user_id: createUserID(BigInt(account.userId)),
- email: null,
- });
- const validation = await createBuilderWithoutAuth<{valid: boolean}>(harness)
- .get(`/auth/reset/${token}`)
- .execute();
- expect(validation.valid).toBe(false);
- await createBuilderWithoutAuth(harness)
- .post('/auth/reset')
- .body({token, password: NEW_PASSWORD})
- .expect(400)
- .execute();
- });
- });
-});
diff --git a/fluxer_api/src/api/billing/mappers/StripeToBillingMapper.test.ts b/fluxer_api/src/api/billing/mappers/StripeToBillingMapper.test.ts
deleted file mode 100644
index e7909830e..000000000
--- a/fluxer_api/src/api/billing/mappers/StripeToBillingMapper.test.ts
+++ /dev/null
@@ -1,320 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- computeStripeUpdatedAt,
- mapStripeCustomerToRow,
- mapStripeInvoiceToRow,
- mapStripeRefundToRow,
- mapStripeSubscriptionToRow,
- normalizeBillingSubscriptionRow,
- type StripeSubscriptionPayload,
-} from '@app/api/billing/mappers/StripeToBillingMapper';
-import type Stripe from 'stripe';
-import {describe, expect, it} from 'vitest';
-
-const NOW_UNIX = 1700000000;
-
-function stripeFixture<T>(value: object): T {
- return value as T;
-}
-
-function expectTupleGetValue(value: object, index: number, expected: unknown): void {
- if (!('get' in value) || typeof value.get !== 'function') {
- throw new Error('Expected tuple getter');
- }
- expect(value.get(index)).toBe(expected);
-}
-
-describe('computeStripeUpdatedAt', () => {
- it('prefers status_transitions over created', () => {
- const later = NOW_UNIX + 5000;
- const d = computeStripeUpdatedAt({created: NOW_UNIX, status_transitions: {paid_at: later}});
- expect(d.getTime()).toBe(later * 1000);
- });
- it('prefers explicit terminal timestamps over created', () => {
- const later = NOW_UNIX + 9999;
- const d = computeStripeUpdatedAt({created: NOW_UNIX, canceled_at: later});
- expect(d.getTime()).toBe(later * 1000);
- });
- it('falls back to Date.now() when nothing is present', () => {
- const before = Date.now();
- const d = computeStripeUpdatedAt({});
- const after = Date.now();
- expect(d.getTime()).toBeGreaterThanOrEqual(before);
- expect(d.getTime()).toBeLessThanOrEqual(after);
- });
-});
-
-describe('mapStripeCustomerToRow', () => {
- it('maps a normal customer with email', () => {
- const c = stripeFixture<Stripe.Customer>({
- id: 'cus_normal',
- email: '[email protected]',
- name: 'Alice',
- description: null,
- phone: null,
- invoice_settings: {default_payment_method: 'pm_123'},
- invoice_prefix: 'PFX',
- currency: 'usd',
- delinquent: false,
- balance: -500,
- livemode: true,
- metadata: {},
- created: NOW_UNIX,
- });
- const {primary, byUserId} = mapStripeCustomerToRow(c);
- expect(primary.provider_id).toBe('cus_normal');
- expect(primary.email).toBe('[email protected]');
- expect(primary.default_payment_method).toBe('pm_123');
- expect(primary.balance).toBe(-500n);
- expect(primary.deleted).toBe(false);
- expect(primary.stripe_created_at?.getTime()).toBe(NOW_UNIX * 1000);
- expect(primary.version).toBeNull();
- expect(byUserId).toBeNull();
- });
- it('maps a deleted customer with deleted=true', () => {
- const c = stripeFixture<Stripe.DeletedCustomer>({
- id: 'cus_gone',
- deleted: true,
- });
- const {primary, byUserId} = mapStripeCustomerToRow(c);
- expect(primary.deleted).toBe(true);
- expect(primary.email).toBeNull();
- expect(byUserId).toBeNull();
- });
- it('produces non-null byUserId when knownUserId hint is provided', () => {
- const c = stripeFixture<Stripe.Customer>({
- id: 'cus_user',
- email: '[email protected]',
- invoice_settings: {default_payment_method: null},
- created: NOW_UNIX,
- livemode: false,
- metadata: {},
- });
- const userId = 12345n;
- const {primary, byUserId} = mapStripeCustomerToRow(c, {knownUserId: userId});
- expect(primary.user_id).toBe(userId);
- expect(byUserId).not.toBeNull();
- expect(byUserId!.user_id).toBe(userId);
- expect(byUserId!.provider_id).toBe('cus_user');
- expect(byUserId!.livemode).toBe(false);
- });
- it('expanded default_payment_method object is reduced to id', () => {
- const c = stripeFixture<Stripe.Customer>({
- id: 'cus_exp',
- invoice_settings: {default_payment_method: {id: 'pm_exp'}},
- created: NOW_UNIX,
- metadata: {},
- });
- const {primary} = mapStripeCustomerToRow(c);
- expect(primary.default_payment_method).toBe('pm_exp');
- });
-});
-
-describe('mapStripeSubscriptionToRow', () => {
- function buildSub(overrides: Partial<StripeSubscriptionPayload> = {}): StripeSubscriptionPayload {
- return {
- id: 'sub_1',
- customer: 'cus_1',
- status: 'active',
- cancel_at_period_end: false,
- cancel_at: null,
- canceled_at: null,
- cancellation_details: null,
- trial_start: null,
- trial_end: null,
- items: {
- data: [
- {
- id: 'si_1',
- quantity: 2,
- price: {id: 'price_1', product: 'prod_1', unit_amount: 999},
- current_period_start: NOW_UNIX,
- current_period_end: NOW_UNIX + 30 * 86400,
- },
- ],
- },
- default_payment_method: null,
- latest_invoice: null,
- collection_method: 'charge_automatically',
- currency: 'usd',
- livemode: true,
- metadata: {},
- created: NOW_UNIX,
- ...overrides,
- };
- }
- it('maps an active subscription with one item', () => {
- const {primary, byCustomer, byUser} = mapStripeSubscriptionToRow(buildSub());
- expect(primary.provider_id).toBe('sub_1');
- expect(primary.primary_price_id).toBe('price_1');
- expect(primary.primary_product_id).toBe('prod_1');
- expect(primary.quantity).toBe(2);
- expect(primary.item_count).toBe(1);
- expect(primary.items?.length).toBe(1);
- expect(primary.items![0]).toEqual(['si_1', 'price_1', 2, 999n]);
- expectTupleGetValue(primary.items![0], 3, 999n);
- expect(primary.current_period_end?.getTime()).toBe((NOW_UNIX + 30 * 86400) * 1000);
- expect(byCustomer.provider_id).toBe('sub_1');
- expect(byUser).toBeNull();
- });
- it('normalizes Cassandra tuple subscription items back to array values', () => {
- const {primary} = mapStripeSubscriptionToRow(buildSub());
- const tupleLike = {
- length: 4,
- get(index: number): unknown {
- return ['si_1', 'price_1', 2, 999n][index];
- },
- };
- const normalized = normalizeBillingSubscriptionRow({
- ...primary,
- items: [tupleLike],
- });
- expect(normalized.items![0]).toEqual(['si_1', 'price_1', 2, 999n]);
- expectTupleGetValue(normalized.items![0], 3, 999n);
- });
- it('maps cancel_at_period_end=true', () => {
- const cancelAt = NOW_UNIX + 60 * 86400;
- const {primary} = mapStripeSubscriptionToRow(buildSub({cancel_at_period_end: true, cancel_at: cancelAt}));
- expect(primary.cancel_at_period_end).toBe(true);
- expect(primary.cancel_at?.getTime()).toBe(cancelAt * 1000);
- });
- it('maps cancellation_details reason+comment', () => {
- const {primary} = mapStripeSubscriptionToRow(
- buildSub({
- canceled_at: NOW_UNIX + 100,
- cancellation_details: {reason: 'cancellation_requested', comment: 'too_expensive'},
- }),
- );
- expect(primary.cancellation_reason).toBe('cancellation_requested');
- expect(primary.cancellation_comment).toBe('too_expensive');
- });
- it('emits byUser when knownUserId hint provided', () => {
- const {byUser} = mapStripeSubscriptionToRow(buildSub(), {knownUserId: 42n});
- expect(byUser).not.toBeNull();
- expect(byUser!.user_id).toBe(42n);
- expect(byUser!.customer_id).toBe('cus_1');
- });
-});
-
-describe('mapStripeInvoiceToRow', () => {
- it('maps a paid invoice with two payments', () => {
- const inv = stripeFixture<Stripe.Invoice>({
- id: 'in_1',
- customer: 'cus_1',
- parent: {type: 'subscription_details', subscription_details: {subscription: 'sub_1'}},
- status: 'paid',
- number: 'INV-001',
- currency: 'usd',
- amount_due: 1000,
- amount_paid: 1000,
- amount_remaining: 0,
- subtotal: 1000,
- tax: 0,
- total: 1000,
- starting_balance: 0,
- ending_balance: 0,
- application_fee_amount: null,
- attempt_count: 1,
- attempted: true,
- auto_advance: false,
- billing_reason: 'subscription_cycle',
- collection_method: 'charge_automatically',
- description: null,
- hosted_invoice_url: 'https://x',
- invoice_pdf: 'https://x.pdf',
- period_start: NOW_UNIX,
- period_end: NOW_UNIX + 86400,
- due_date: null,
- next_payment_attempt: null,
- status_transitions: {finalized_at: NOW_UNIX + 1, paid_at: NOW_UNIX + 2, voided_at: null},
- payments: {
- data: [
- {
- id: 'inpay_1',
- status: 'paid',
- is_default: true,
- amount_paid: 1000,
- amount_requested: 1000,
- currency: 'usd',
- created: NOW_UNIX + 1,
- status_transitions: {paid_at: NOW_UNIX + 2},
- payment: {payment_intent: 'pi_1', charge: 'ch_1'},
- },
- {
- id: 'inpay_2',
- status: 'canceled',
- is_default: false,
- amount_paid: 0,
- amount_requested: 1000,
- currency: 'usd',
- created: NOW_UNIX,
- payment: {payment_intent: {id: 'pi_2'}, charge: {id: 'ch_2'}},
- },
- ],
- },
- livemode: true,
- metadata: {},
- created: NOW_UNIX,
- });
- const result = mapStripeInvoiceToRow(inv);
- expect(result.primary.provider_id).toBe('in_1');
- expect(result.primary.subscription_id).toBe('sub_1');
- expect(result.primary.payment_ids).toEqual(['inpay_1', 'inpay_2']);
- expect(result.primary.paid_at?.getTime()).toBe((NOW_UNIX + 2) * 1000);
- expect(result.payments.length).toBe(2);
- expect(result.payments[0]!.primary.provider_id).toBe('inpay_1');
- expect(result.payments[0]!.primary.payment_intent_id).toBe('pi_1');
- expect(result.payments[0]!.primary.charge_id).toBe('ch_1');
- expect(result.payments[0]!.primary.is_default).toBe(true);
- expect(result.payments[1]!.primary.payment_intent_id).toBe('pi_2');
- expect(result.payments[1]!.primary.charge_id).toBe('ch_2');
- });
-});
-
-describe('mapStripeRefundToRow', () => {
- it('payment_intent is a string', () => {
- const r = stripeFixture<Stripe.Refund>({
- id: 're_1',
- charge: 'ch_1',
- payment_intent: 'pi_1',
- status: 'succeeded',
- amount: 500,
- currency: 'usd',
- reason: 'requested_by_customer',
- receipt_number: null,
- failure_reason: null,
- livemode: true,
- metadata: {},
- created: NOW_UNIX,
- });
- const result = mapStripeRefundToRow(r);
- expect(result.primary.payment_intent_id).toBe('pi_1');
- expect(result.primary.charge_id).toBe('ch_1');
- expect(result.byCharge).not.toBeNull();
- expect(result.byPaymentIntent).not.toBeNull();
- expect(result.byInvoice).toBeNull();
- });
- it('payment_intent is an expanded object; hints pass through', () => {
- const r = stripeFixture<Stripe.Refund>({
- id: 're_2',
- charge: null,
- payment_intent: {id: 'pi_2'},
- status: 'succeeded',
- amount: 250,
- currency: 'usd',
- created: NOW_UNIX,
- metadata: {},
- livemode: true,
- });
- const result = mapStripeRefundToRow(r, {invoiceId: 'in_z', customerId: 'cus_z', userId: 7n});
- expect(result.primary.payment_intent_id).toBe('pi_2');
- expect(result.primary.charge_id).toBeNull();
- expect(result.primary.invoice_id).toBe('in_z');
- expect(result.primary.customer_id).toBe('cus_z');
- expect(result.primary.user_id).toBe(7n);
- expect(result.byInvoice).not.toBeNull();
- expect(result.byInvoice!.invoice_id).toBe('in_z');
- expect(result.byCharge).toBeNull();
- });
-});
diff --git a/fluxer_api/src/api/billing/mappers/StripeToBillingMapper.ts b/fluxer_api/src/api/billing/mappers/StripeToBillingMapper.ts
index 99a88c9ad..86927fd5d 100644
--- a/fluxer_api/src/api/billing/mappers/StripeToBillingMapper.ts
+++ b/fluxer_api/src/api/billing/mappers/StripeToBillingMapper.ts
@@ -207,7 +207,7 @@ function safeMetadata(m: Stripe.Metadata | null | undefined): Map<string, string
return new Map(entries);
}
-export function computeStripeUpdatedAt(
+function computeStripeUpdatedAt(
obj: {
created?: number | null;
status_transitions?: object | null;
diff --git a/fluxer_api/src/api/donation/tests/DonationCheckout.test.ts b/fluxer_api/src/api/donation/tests/DonationCheckout.test.ts
deleted file mode 100644
index 57d43b6e9..000000000
--- a/fluxer_api/src/api/donation/tests/DonationCheckout.test.ts
+++ /dev/null
@@ -1,125 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- createDonationCheckoutBuilder,
- createValidCheckoutBody,
- DONATION_CURRENCY_VALUES,
- TEST_DONOR_EMAIL,
-} from '@app/api/donation/tests/DonationTestUtils';
-import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
-import {createStripeApiHandlers, type StripeApiHandlers} from '@app/api/test/msw/handlers/StripeApiHandlers';
-import {server} from '@app/api/test/msw/server';
-import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
-import {getDonationAmountConstraints} from '@fluxer/schema/src/domains/donation/DonationAmountUtils';
-import {afterAll, beforeAll, beforeEach, describe, expect, test} from 'vitest';
-
-describe('POST /donations/checkout', () => {
- let harness: ApiTestHarness;
- let stripeHandlers: StripeApiHandlers;
- beforeAll(async () => {
- harness = await createApiTestHarness();
- stripeHandlers = createStripeApiHandlers();
- });
- afterAll(async () => {
- await harness.shutdown();
- });
- beforeEach(async () => {
- await harness.resetData();
- stripeHandlers.reset();
- server.use(...stripeHandlers.handlers);
- });
- test('creates checkout session with valid params', async () => {
- const response = await createDonationCheckoutBuilder(harness).body(createValidCheckoutBody()).expect(200).execute();
- expect(response.url).toContain('https://');
- expect(response.url).toContain('checkout.stripe.com');
- expect(stripeHandlers.spies.createdCheckoutSessions).toHaveLength(1);
- });
- test('passes customer email to stripe', async () => {
- await createDonationCheckoutBuilder(harness)
- .body(createValidCheckoutBody({email: TEST_DONOR_EMAIL}))
- .expect(200)
- .execute();
- expect(stripeHandlers.spies.createdCheckoutSessions).toHaveLength(1);
- const session = stripeHandlers.spies.createdCheckoutSessions[0];
- expect(session?.customer_email).toBe(TEST_DONOR_EMAIL);
- });
- test('a one-time donation gets a Stripe invoice only when given as a business', async () => {
- await createDonationCheckoutBuilder(harness)
- .body({...createValidCheckoutBody(), interval: null, is_business: true})
- .expect(200)
- .execute();
- await createDonationCheckoutBuilder(harness)
- .body({...createValidCheckoutBody(), interval: null, is_business: false})
- .expect(200)
- .execute();
- const [business, personal] = stripeHandlers.spies.createdCheckoutSessions;
- expect(business).toMatchObject({mode: 'payment', customer_creation: 'always', invoice_creation: {enabled: 'true'}});
- expect(personal).toMatchObject({mode: 'payment', customer_creation: 'always'});
- expect(personal).not.toHaveProperty('invoice_creation');
- });
- test('sets subscription mode', async () => {
- await createDonationCheckoutBuilder(harness).body(createValidCheckoutBody()).expect(200).execute();
- expect(stripeHandlers.spies.createdCheckoutSessions).toHaveLength(1);
- const session = stripeHandlers.spies.createdCheckoutSessions[0];
- expect(session?.mode).toBe('subscription');
- });
- test('rejects amount below minimum', async () => {
- const minimumAmountMinor = getDonationAmountConstraints(DONATION_CURRENCY_VALUES.USD).minimumAmountMinor;
- await createDonationCheckoutBuilder(harness)
- .body(
- createValidCheckoutBody({
- amount_cents: minimumAmountMinor - 100,
- }),
- )
- .expect(400, APIErrorCodes.INVALID_FORM_BODY)
- .execute();
- expect(stripeHandlers.spies.createdCheckoutSessions).toHaveLength(0);
- });
- test('rejects amount above maximum', async () => {
- const maximumAmountMinor = getDonationAmountConstraints(DONATION_CURRENCY_VALUES.USD).maximumAmountMinor;
- await createDonationCheckoutBuilder(harness)
- .body(
- createValidCheckoutBody({
- amount_cents: maximumAmountMinor + 100,
- }),
- )
- .expect(400, APIErrorCodes.INVALID_FORM_BODY)
- .execute();
- expect(stripeHandlers.spies.createdCheckoutSessions).toHaveLength(0);
- });
- test.each([
- DONATION_CURRENCY_VALUES.USD,
- DONATION_CURRENCY_VALUES.EUR,
- DONATION_CURRENCY_VALUES.BRL,
- DONATION_CURRENCY_VALUES.INR,
- DONATION_CURRENCY_VALUES.PLN,
- DONATION_CURRENCY_VALUES.TRY,
- DONATION_CURRENCY_VALUES.SEK,
- DONATION_CURRENCY_VALUES.DKK,
- DONATION_CURRENCY_VALUES.NOK,
- ])('accepts %s currency', async (currency) => {
- const amount_cents = getDonationAmountConstraints(currency).minimumAmountMinor;
- const response = await createDonationCheckoutBuilder(harness)
- .body(
- createValidCheckoutBody({
- currency,
- amount_cents,
- }),
- )
- .expect(200)
- .execute();
- expect(response.url).toBeDefined();
- expect(stripeHandlers.spies.createdCheckoutSessions).toHaveLength(1);
- const session = stripeHandlers.spies.createdCheckoutSessions[0];
- const lineItem = session?.line_items?.[0] as
- | {
- price_data?: {
- currency?: string;
- };
- }
- | undefined;
- expect(lineItem?.price_data?.currency).toBe(currency);
- const nordic = ['sek', 'dkk', 'nok'].includes(currency);
- expect(session?.adaptive_pricing).toEqual(nordic ? {enabled: 'false'} : undefined);
- });
-});
diff --git a/fluxer_api/src/api/donation/tests/DonationManage.test.ts b/fluxer_api/src/api/donation/tests/DonationManage.test.ts
deleted file mode 100644
index e6c9efaa4..000000000
--- a/fluxer_api/src/api/donation/tests/DonationManage.test.ts
+++ /dev/null
@@ -1,247 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {Config} from '@app/api/Config';
-import {DonationRepository} from '@app/api/donation/DonationRepository';
-import {DonorMagicLinkToken} from '@app/api/donation/models/DonorMagicLinkToken';
-import {
- createDonationManageBuilder,
- TEST_DONOR_EMAIL,
- TEST_MAGIC_LINK_TOKEN,
-} from '@app/api/donation/tests/DonationTestUtils';
-import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
-import {createPwnedPasswordsRangeHandler} from '@app/api/test/msw/handlers/PwnedPasswordsHandlers';
-import {createStripeApiHandlers, type StripeApiHandlers} from '@app/api/test/msw/handlers/StripeApiHandlers';
-import {server} from '@app/api/test/msw/server';
-import {createBuilderWithoutAuth, type TestRequestBuilder} from '@app/api/test/TestRequestBuilder';
-import {afterAll, beforeAll, beforeEach, describe, expect, test} from 'vitest';
-
-type DonationManageAlert = 'link_expired' | 'link_used' | 'link_invalid' | 'no_customer' | 'portal_error';
-
-const STRIPE_PORTAL_URL_PATTERN = /^https:\/\/billing\.stripe\.com\/p\/session\//;
-
-describe('GET and POST /donations/manage', () => {
- let harness: ApiTestHarness;
- let stripeHandlers: StripeApiHandlers;
- let donationRepository: DonationRepository;
- beforeAll(async () => {
- harness = await createApiTestHarness();
- donationRepository = new DonationRepository();
- stripeHandlers = createStripeApiHandlers();
- });
- afterAll(async () => {
- await harness.shutdown();
- });
- beforeEach(async () => {
- await harness.reset();
- stripeHandlers.reset();
- server.use(...stripeHandlers.handlers);
- });
- function createDonationRedeemBuilder(token: string): TestRequestBuilder<void> {
- return createBuilderWithoutAuth<void>(harness).post(`/donations/manage?token=${encodeURIComponent(token)}`);
- }
- async function openManageLink(token: string): Promise<string | null> {
- const {response} = await createDonationManageBuilder(harness, token).expect(302).executeWithResponse();
- return response.headers.get('location');
- }
- async function redeemManageLink(token: string): Promise<string | null> {
- const {response} = await createDonationRedeemBuilder(token).expect(302).executeWithResponse();
- return response.headers.get('location');
- }
- function confirmUrl(token: string): string {
- return `${Config.endpoints.marketing}/donate/manage/confirm?token=${encodeURIComponent(token)}`;
- }
- function alertUrl(alert: DonationManageAlert): string {
- return `${Config.endpoints.marketing}/donate/manage?alert=${alert}`;
- }
- async function isTokenUsed(token: string): Promise<boolean | undefined> {
- const tokenModel = await donationRepository.findMagicLinkToken(token);
- return tokenModel?.isUsed();
- }
- function useFailingPortalHandlers(): void {
- server.resetHandlers();
- const failingHandlers = createStripeApiHandlers({portalShouldFail: true});
- server.use(createPwnedPasswordsRangeHandler(), ...failingHandlers.handlers);
- }
- async function createDonorWithCustomerId(email: string, customerId: string): Promise<void> {
- await donationRepository.createDonor({
- email,
- stripeCustomerId: customerId,
- businessName: null,
- taxId: null,
- taxIdType: null,
- stripeSubscriptionId: 'sub_test_1',
- subscriptionAmountCents: 2500,
- subscriptionCurrency: 'usd',
- subscriptionInterval: 'month',
- subscriptionCurrentPeriodEnd: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000),
- });
- }
- async function createDonorWithoutSubscription(email: string, customerId: string | null): Promise<void> {
- await donationRepository.createDonor({
- email,
- stripeCustomerId: customerId,
- businessName: null,
- taxId: null,
- taxIdType: null,
- stripeSubscriptionId: null,
- subscriptionAmountCents: null,
- subscriptionCurrency: null,
- subscriptionInterval: null,
- subscriptionCurrentPeriodEnd: null,
- });
- }
- async function createMagicLinkToken(email: string, token: string, expiresAt: Date, usedAt: Date | null) {
- const tokenModel = new DonorMagicLinkToken({
- token_: token,
- donor_email: email,
- expires_at: expiresAt,
- used_at: usedAt,
- });
- await donationRepository.createMagicLinkToken(tokenModel);
- }
- async function createValidMagicLinkToken(email: string, token: string): Promise<void> {
- await createMagicLinkToken(email, token, new Date(Date.now() + 15 * 60 * 1000), null);
- }
- async function createUsedMagicLinkToken(email: string, token: string): Promise<void> {
- await createMagicLinkToken(email, token, new Date(Date.now() + 15 * 60 * 1000), new Date(Date.now() - 5000));
- }
- describe('link scanner prefetch', () => {
- test('GET does not mark token as used', async () => {
- await createDonorWithCustomerId(TEST_DONOR_EMAIL, 'cus_test_prefetch');
- await createValidMagicLinkToken(TEST_DONOR_EMAIL, TEST_MAGIC_LINK_TOKEN);
- await openManageLink(TEST_MAGIC_LINK_TOKEN);
- expect(await isTokenUsed(TEST_MAGIC_LINK_TOKEN)).toBe(false);
- });
- test('repeated GETs keep redirecting to the confirmation page', async () => {
- await createDonorWithCustomerId(TEST_DONOR_EMAIL, 'cus_test_prefetch');
- await createValidMagicLinkToken(TEST_DONOR_EMAIL, TEST_MAGIC_LINK_TOKEN);
- expect(await openManageLink(TEST_MAGIC_LINK_TOKEN)).toBe(confirmUrl(TEST_MAGIC_LINK_TOKEN));
- expect(await openManageLink(TEST_MAGIC_LINK_TOKEN)).toBe(confirmUrl(TEST_MAGIC_LINK_TOKEN));
- expect(await openManageLink(TEST_MAGIC_LINK_TOKEN)).toBe(confirmUrl(TEST_MAGIC_LINK_TOKEN));
- expect(await isTokenUsed(TEST_MAGIC_LINK_TOKEN)).toBe(false);
- expect(stripeHandlers.spies.createdPortalSessions).toHaveLength(0);
- });
- test('POST still redeems a token after repeated GETs', async () => {
- const customerId = 'cus_test_prefetch';
- await createDonorWithCustomerId(TEST_DONOR_EMAIL, customerId);
- await createValidMagicLinkToken(TEST_DONOR_EMAIL, TEST_MAGIC_LINK_TOKEN);
- await openManageLink(TEST_MAGIC_LINK_TOKEN);
- await openManageLink(TEST_MAGIC_LINK_TOKEN);
- expect(await redeemManageLink(TEST_MAGIC_LINK_TOKEN)).toMatch(STRIPE_PORTAL_URL_PATTERN);
- expect(stripeHandlers.spies.createdPortalSessions).toHaveLength(1);
- expect(stripeHandlers.spies.createdPortalSessions[0]?.customer).toBe(customerId);
- expect(await isTokenUsed(TEST_MAGIC_LINK_TOKEN)).toBe(true);
- });
- });
- describe('valid token without customer ID', () => {
- test('redirects to no_customer alert when donor has no customer ID', async () => {
- await createDonorWithoutSubscription(TEST_DONOR_EMAIL, null);
- await createValidMagicLinkToken(TEST_DONOR_EMAIL, TEST_MAGIC_LINK_TOKEN);
- expect(await openManageLink(TEST_MAGIC_LINK_TOKEN)).toBe(alertUrl('no_customer'));
- expect(await redeemManageLink(TEST_MAGIC_LINK_TOKEN)).toBe(alertUrl('no_customer'));
- expect(stripeHandlers.spies.createdPortalSessions).toHaveLength(0);
- });
- test('redirects to no_customer alert when donor does not exist', async () => {
- await createValidMagicLinkToken(TEST_DONOR_EMAIL, TEST_MAGIC_LINK_TOKEN);
- expect(await openManageLink(TEST_MAGIC_LINK_TOKEN)).toBe(alertUrl('no_customer'));
- expect(await redeemManageLink(TEST_MAGIC_LINK_TOKEN)).toBe(alertUrl('no_customer'));
- expect(stripeHandlers.spies.createdPortalSessions).toHaveLength(0);
- });
- test('does not mark token as used when there is no customer', async () => {
- await createValidMagicLinkToken(TEST_DONOR_EMAIL, TEST_MAGIC_LINK_TOKEN);
- await openManageLink(TEST_MAGIC_LINK_TOKEN);
- await redeemManageLink(TEST_MAGIC_LINK_TOKEN);
- expect(await isTokenUsed(TEST_MAGIC_LINK_TOKEN)).toBe(false);
- });
- });
- describe('used token handling', () => {
- test('rejects already-used token', async () => {
- await createDonorWithCustomerId(TEST_DONOR_EMAIL, 'cus_test_used');
- await createUsedMagicLinkToken(TEST_DONOR_EMAIL, TEST_MAGIC_LINK_TOKEN);
- expect(await openManageLink(TEST_MAGIC_LINK_TOKEN)).toBe(alertUrl('link_used'));
- expect(await redeemManageLink(TEST_MAGIC_LINK_TOKEN)).toBe(alertUrl('link_used'));
- expect(stripeHandlers.spies.createdPortalSessions).toHaveLength(0);
- });
- test('prevents reuse of token after successful redemption', async () => {
- await createDonorWithCustomerId(TEST_DONOR_EMAIL, 'cus_test_reuse');
- await createValidMagicLinkToken(TEST_DONOR_EMAIL, TEST_MAGIC_LINK_TOKEN);
- expect(await redeemManageLink(TEST_MAGIC_LINK_TOKEN)).toMatch(STRIPE_PORTAL_URL_PATTERN);
- expect(await redeemManageLink(TEST_MAGIC_LINK_TOKEN)).toBe(alertUrl('link_used'));
- expect(await openManageLink(TEST_MAGIC_LINK_TOKEN)).toBe(alertUrl('link_used'));
- expect(stripeHandlers.spies.createdPortalSessions).toHaveLength(1);
- });
- });
- describe('invalid token handling', () => {
- test('rejects non-existent token', async () => {
- expect(await openManageLink(TEST_MAGIC_LINK_TOKEN)).toBe(alertUrl('link_invalid'));
- expect(await redeemManageLink(TEST_MAGIC_LINK_TOKEN)).toBe(alertUrl('link_invalid'));
- expect(stripeHandlers.spies.createdPortalSessions).toHaveLength(0);
- });
- });
- describe('Stripe portal session creation', () => {
- test('redeems the same token once Stripe recovers', async () => {
- const customerId = 'cus_test_stripe_retry';
- await createDonorWithCustomerId(TEST_DONOR_EMAIL, customerId);
- await createValidMagicLinkToken(TEST_DONOR_EMAIL, TEST_MAGIC_LINK_TOKEN);
- useFailingPortalHandlers();
- expect(await redeemManageLink(TEST_MAGIC_LINK_TOKEN)).toBe(alertUrl('portal_error'));
- server.resetHandlers();
- server.use(...stripeHandlers.handlers);
- expect(await openManageLink(TEST_MAGIC_LINK_TOKEN)).toBe(confirmUrl(TEST_MAGIC_LINK_TOKEN));
- expect(await redeemManageLink(TEST_MAGIC_LINK_TOKEN)).toMatch(STRIPE_PORTAL_URL_PATTERN);
- expect(stripeHandlers.spies.createdPortalSessions).toHaveLength(1);
- expect(stripeHandlers.spies.createdPortalSessions[0]?.customer).toBe(customerId);
- expect(await isTokenUsed(TEST_MAGIC_LINK_TOKEN)).toBe(true);
- });
- });
- describe('edge cases', () => {
- test('handles token for donor with cancelled subscription', async () => {
- const customerId = 'cus_test_cancelled';
- await createDonorWithoutSubscription(TEST_DONOR_EMAIL, customerId);
- await createValidMagicLinkToken(TEST_DONOR_EMAIL, TEST_MAGIC_LINK_TOKEN);
- expect(await openManageLink(TEST_MAGIC_LINK_TOKEN)).toBe(confirmUrl(TEST_MAGIC_LINK_TOKEN));
- expect(await redeemManageLink(TEST_MAGIC_LINK_TOKEN)).toMatch(STRIPE_PORTAL_URL_PATTERN);
- expect(stripeHandlers.spies.createdPortalSessions).toHaveLength(1);
- expect(stripeHandlers.spies.createdPortalSessions[0]?.customer).toBe(customerId);
- });
- test('rejects an expired token without using it', async () => {
- await createDonorWithCustomerId(TEST_DONOR_EMAIL, 'cus_test');
- await createMagicLinkToken(TEST_DONOR_EMAIL, TEST_MAGIC_LINK_TOKEN, new Date(Date.now() - 1000), null);
- expect(await openManageLink(TEST_MAGIC_LINK_TOKEN)).toBe(alertUrl('link_expired'));
- expect(await redeemManageLink(TEST_MAGIC_LINK_TOKEN)).toBe(alertUrl('link_expired'));
- expect(await isTokenUsed(TEST_MAGIC_LINK_TOKEN)).toBe(false);
- expect(stripeHandlers.spies.createdPortalSessions).toHaveLength(0);
- });
- test('handles case-sensitive token comparison', async () => {
- const lowerToken = 'a'.repeat(64);
- const upperToken = 'A'.repeat(64);
- await createDonorWithCustomerId(TEST_DONOR_EMAIL, 'cus_test');
- await createValidMagicLinkToken(TEST_DONOR_EMAIL, lowerToken);
- expect(await openManageLink(upperToken)).toBe(alertUrl('link_invalid'));
- expect(await redeemManageLink(upperToken)).toBe(alertUrl('link_invalid'));
- expect(await isTokenUsed(lowerToken)).toBe(false);
- expect(stripeHandlers.spies.createdPortalSessions).toHaveLength(0);
- });
- test('handles multiple valid tokens for different donors', async () => {
- const token1 = 'a'.repeat(64);
- const token2 = 'b'.repeat(64);
- const email1 = '[email protected]';
- const email2 = '[email protected]';
- const customerId1 = 'cus_test_1';
- const customerId2 = 'cus_test_2';
- await createDonorWithCustomerId(email1, customerId1);
- await createDonorWithCustomerId(email2, customerId2);
- await createValidMagicLinkToken(email1, token1);
- await createValidMagicLinkToken(email2, token2);
- expect(await openManageLink(token1)).toBe(confirmUrl(token1));
- expect(await openManageLink(token2)).toBe(confirmUrl(token2));
- expect(await redeemManageLink(token1)).toMatch(STRIPE_PORTAL_URL_PATTERN);
- expect(stripeHandlers.spies.createdPortalSessions[0]?.customer).toBe(customerId1);
- expect(await isTokenUsed(token1)).toBe(true);
- expect(await isTokenUsed(token2)).toBe(false);
- expect(await redeemManageLink(token2)).toMatch(STRIPE_PORTAL_URL_PATTERN);
- expect(stripeHandlers.spies.createdPortalSessions[1]?.customer).toBe(customerId2);
- expect(stripeHandlers.spies.createdPortalSessions).toHaveLength(2);
- });
- });
-});
diff --git a/fluxer_api/src/api/donation/tests/DonationRequestLink.test.ts b/fluxer_api/src/api/donation/tests/DonationRequestLink.test.ts
deleted file mode 100644
index 22b0aab12..000000000
--- a/fluxer_api/src/api/donation/tests/DonationRequestLink.test.ts
+++ /dev/null
@@ -1,50 +0,0 @@
-import {clearTestEmails, createUniqueEmail, listTestEmails} from '@app/api/auth/tests/AuthTestUtils';
-import {DonationRepository} from '@app/api/donation/DonationRepository';
-import {createDonationRequestLinkBuilder, TEST_DONOR_EMAIL} from '@app/api/donation/tests/DonationTestUtils';
-import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
-import {afterAll, beforeAll, beforeEach, describe, expect, test} from 'vitest';
-
-describe('POST /donations/request-link', () => {
- let harness: ApiTestHarness;
- let donationRepository: DonationRepository;
- beforeAll(async () => {
- harness = await createApiTestHarness();
- donationRepository = new DonationRepository();
- });
- afterAll(async () => {
- await harness.shutdown();
- });
- beforeEach(async () => {
- await harness.reset();
- await clearTestEmails(harness);
- });
- async function createDonor(email: string): Promise<void> {
- await donationRepository.createDonor({
- email,
- stripeCustomerId: 'cus_test_123',
- businessName: null,
- taxId: null,
- taxIdType: null,
- stripeSubscriptionId: 'sub_test_123',
- subscriptionAmountCents: 2500,
- subscriptionCurrency: 'usd',
- subscriptionInterval: 'month',
- subscriptionCurrentPeriodEnd: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000),
- });
- }
- describe('email sending behaviour', () => {
- test('sends magic link email when donor exists', async () => {
- await createDonor(TEST_DONOR_EMAIL);
- await createDonationRequestLinkBuilder(harness).body({email: TEST_DONOR_EMAIL}).expect(204).execute();
- const emails = await listTestEmails(harness, {recipient: TEST_DONOR_EMAIL});
- expect(emails).toHaveLength(1);
- expect(emails[0]?.type).toBe('donation_magic_link');
- });
- test('does not send email when donor does not exist', async () => {
- const unknownEmail = createUniqueEmail('unknown');
- await createDonationRequestLinkBuilder(harness).body({email: unknownEmail}).expect(204).execute();
- const emails = await listTestEmails(harness, {recipient: unknownEmail});
- expect(emails).toHaveLength(0);
- });
- });
-});
diff --git a/fluxer_api/src/api/donation/tests/DonationTestUtils.ts b/fluxer_api/src/api/donation/tests/DonationTestUtils.ts
deleted file mode 100644
index 2bbf2f9c4..000000000
--- a/fluxer_api/src/api/donation/tests/DonationTestUtils.ts
+++ /dev/null
@@ -1,58 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import type {ApiTestHarness} from '@app/api/test/ApiTestHarness';
-import {createBuilderWithoutAuth, type TestRequestBuilder} from '@app/api/test/TestRequestBuilder';
-import {DONATION_CURRENCIES, type DonationCurrency} from '@fluxer/schema/src/domains/donation/DonationAmountUtils';
-
-export const TEST_DONOR_EMAIL = '[email protected]';
-export const TEST_MAGIC_LINK_TOKEN = 'a'.repeat(64);
-const DONATION_AMOUNTS = {
- STANDARD: 2500,
-} as const;
-export const DONATION_CURRENCY_VALUES = {
- USD: DONATION_CURRENCIES[0],
- EUR: DONATION_CURRENCIES[1],
- BRL: DONATION_CURRENCIES[2],
- INR: DONATION_CURRENCIES[3],
- PLN: DONATION_CURRENCIES[4],
- TRY: DONATION_CURRENCIES[5],
- SEK: DONATION_CURRENCIES[6],
- DKK: DONATION_CURRENCIES[7],
- NOK: DONATION_CURRENCIES[8],
-} as const;
-const DONATION_INTERVALS = {
- MONTH: 'month',
-} as const;
-
-interface DonationCheckoutRequestBody {
- email: string;
- amount_cents: number;
- currency: DonationCurrency;
- interval: 'month' | 'year';
-}
-
-interface DonationCheckoutResponse {
- url: string;
-}
-
-export function createDonationRequestLinkBuilder(harness: ApiTestHarness): TestRequestBuilder<void> {
- return createBuilderWithoutAuth<void>(harness).post('/donations/request-link');
-}
-
-export function createDonationCheckoutBuilder(harness: ApiTestHarness): TestRequestBuilder<DonationCheckoutResponse> {
- return createBuilderWithoutAuth<DonationCheckoutResponse>(harness).post('/donations/checkout');
-}
-
-export function createDonationManageBuilder(harness: ApiTestHarness, token: string): TestRequestBuilder<void> {
- return createBuilderWithoutAuth<void>(harness).get(`/donations/manage?token=${encodeURIComponent(token)}`);
-}
-
-export function createValidCheckoutBody(overrides?: Partial<DonationCheckoutRequestBody>): DonationCheckoutRequestBody {
- return {
- email: TEST_DONOR_EMAIL,
- amount_cents: DONATION_AMOUNTS.STANDARD,
- currency: DONATION_CURRENCY_VALUES.USD,
- interval: DONATION_INTERVALS.MONTH,
- ...overrides,
- };
-}
diff --git a/fluxer_api/src/api/enforcement/tests/EnforcementNetworkBlock.test.ts b/fluxer_api/src/api/enforcement/tests/EnforcementNetworkBlock.test.ts
deleted file mode 100644
index ea1a069e4..000000000
--- a/fluxer_api/src/api/enforcement/tests/EnforcementNetworkBlock.test.ts
+++ /dev/null
@@ -1,462 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {randomBytes} from 'node:crypto';
-import {AdminRepository} from '@app/api/admin/AdminRepository';
-import {createTestAccount, type TestAccount} from '@app/api/auth/tests/AuthTestUtils';
-import {createUserID} from '@app/api/BrandedTypes';
-import {resetIpBanExemptionsForTesting} from '@app/api/ban/IpBanExemptions';
-import {getConfig} from '@app/api/Config';
-import {upsertOne} from '@app/api/database/CassandraQueryExecution';
-import {formatNoticeDate} from '@app/api/enforcement/NoticeDates';
-import {
- close,
- createStaff,
- type DecisionBody,
- decisionBody,
- endDecision,
- getDecision,
- INTERNAL_NOTE,
- loadUser,
- suspend,
- suspendRequest,
-} from '@app/api/enforcement/tests/EnforcementTestUtils';
-import {ipBanCache} from '@app/api/middleware/IpBanMiddleware';
-import {getUserRepository} from '@app/api/middleware/ServiceSingletons';
-import {AuthSessionTombstones, BannedIps} from '@app/api/Tables';
-import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
-import {HTTP_STATUS} from '@app/api/test/TestConstants';
-import {createBuilder, createBuilderWithoutAuth} from '@app/api/test/TestRequestBuilder';
-import {AdminACLs} from '@fluxer/constants/src/AdminACLs';
-import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
-import {DeletionReasons} from '@fluxer/constants/src/Core';
-import {ValidationErrorCodes} from '@fluxer/constants/src/ValidationErrorCodes';
-import {ms} from 'itty-time';
-import {afterAll, beforeAll, beforeEach, describe, expect, test} from 'vitest';
-
-interface ValidationErrorBody {
- errors: Array<{path: string; code: string}>;
-}
-
-interface RestrictionResponse {
- user: {enforcement_decision_id: string | null};
- skipped_ips: Array<{ip: string; reason: string}>;
-}
-
-interface BlockErrorBody {
- code: string;
- message: string;
- ip_address: string;
- appeal_email: string | null;
- appeals_supported: boolean;
- ban_kind: string;
- expires_at: string | null;
- reason: {title: string; url: string | null} | null;
-}
-
-const TARGET_IP = '45.33.10.1';
-const DAY = ms('1 day');
-
-describe('Enforcement network blocks', () => {
- let harness: ApiTestHarness;
- let staff: TestAccount;
- const adminRepository = new AdminRepository();
-
- beforeAll(async () => {
- harness = await createApiTestHarness();
- });
-
- beforeEach(async () => {
- await harness.reset();
- ipBanCache.resetCaches();
- staff = await createStaff(harness);
- });
-
- afterAll(async () => {
- await harness?.shutdown();
- });
-
- function blockingSuspension(
- target: TestAccount,
- ips: Array<string>,
- {decision = decisionBody(), days}: {decision?: DecisionBody; days?: number} = {},
- ) {
- return suspendRequest(harness, staff, target.userId, {
- duration_hours: 0,
- decision,
- block_networks: {ips, days},
- });
- }
-
- async function refusedBlock(target: TestAccount, ips: Array<string>): Promise<string> {
- const body = await createBuilder<ValidationErrorBody>(harness, staff.token)
- .put(`/admin/users/${target.userId}/ban`)
- .header('X-Audit-Log-Reason', INTERNAL_NOTE)
- .body({duration_hours: 0, decision: decisionBody(), block_networks: {ips}})
- .expect(HTTP_STATUS.BAD_REQUEST)
- .execute();
- return body.errors[0]!.code;
- }
-
- async function requestFrom(ip: string, path = '/users/@me') {
- return createBuilderWithoutAuth<BlockErrorBody>(harness).get(path).header('x-forwarded-for', ip).executeRaw();
- }
-
- async function insertPlainBlock(ip: string, expiresAt: Date): Promise<void> {
- await upsertOne(
- BannedIps.insertWithTtl(
- {
- ip,
- ban_kind: 'temporary_24h',
- reason: 'platform_admin_enforcement',
- expires_at: expiresAt,
- created_at: new Date(),
- decision_id: null,
- },
- Math.ceil((expiresAt.getTime() - Date.now()) / 1000),
- ),
- );
- }
-
- describe('writing blocks', () => {
- test('a permanent suspension blocks recent networks for 90 days and the notice names the end', async () => {
- const target = await createTestAccount(harness, {ipAddress: TARGET_IP});
- const before = Date.now();
- const response = await blockingSuspension(target, [TARGET_IP]).expect(HTTP_STATUS.OK).execute();
- expect(response.skipped_ips).toEqual([]);
- const decisionId = response.user.enforcement_decision_id!;
-
- const [row] = await adminRepository.listDecisionIpBans(BigInt(decisionId));
- expect(row?.ip).toBe(TARGET_IP);
- expect(row?.kind).toBe('temporary_24h');
- const expiresAt = row!.expiresAt!.getTime();
- expect(expiresAt).toBeGreaterThanOrEqual(before + 90 * DAY);
- expect(expiresAt).toBeLessThanOrEqual(Date.now() + 90 * DAY);
-
- const decision = await getDecision(harness, staff, decisionId);
- expect(decision.network_blocks).toEqual([{ip: TARGET_IP, expires_at: row!.expiresAt!.toISOString()}]);
- const line = `We also blocked access from networks this account used until ${formatNoticeDate(row!.expiresAt!, 'en-US')}.`;
- expect(decision.notice_text).toContain(line);
- expect(decision.notice.effects).toContain(line);
- expect(decision.notice_text).not.toContain(TARGET_IP);
- });
-
- test('the block length can be set and is recorded on the audit row', async () => {
- const target = await createTestAccount(harness, {ipAddress: TARGET_IP});
- const response = await blockingSuspension(target, [TARGET_IP], {days: 7}).expect(HTTP_STATUS.OK).execute();
- const [row] = await adminRepository.listDecisionIpBans(BigInt(response.user.enforcement_decision_id!));
- expect(row!.expiresAt!.getTime()).toBeLessThanOrEqual(Date.now() + 7 * DAY);
- expect(row!.expiresAt!.getTime()).toBeGreaterThan(Date.now() + 6 * DAY);
- });
-
- test('only a permanent suspension or a closure can block networks', async () => {
- const target = await createTestAccount(harness, {ipAddress: TARGET_IP});
- const body = await createBuilder<ValidationErrorBody>(harness, staff.token)
- .put(`/admin/users/${target.userId}/ban`)
- .header('X-Audit-Log-Reason', INTERNAL_NOTE)
- .body({duration_hours: 24, decision: decisionBody(), block_networks: {ips: [TARGET_IP]}})
- .expect(HTTP_STATUS.BAD_REQUEST)
- .execute();
- expect(body.errors[0]).toMatchObject({
- path: 'block_networks',
- code: ValidationErrorCodes.ENFORCEMENT_NETWORK_BLOCK_NOT_ALLOWED,
- });
- const holder = await createBuilder<ValidationErrorBody>(harness, staff.token)
- .put(`/admin/users/${target.userId}/deletion`)
- .body({days_until_deletion: 14, basis: {type: 'holder_request'}, block_networks: {ips: [TARGET_IP]}})
- .expect(HTTP_STATUS.BAD_REQUEST)
- .execute();
- expect(holder.errors[0]!.code).toBe(ValidationErrorCodes.ENFORCEMENT_NETWORK_BLOCK_NOT_ALLOWED);
- expect(await adminRepository.loadAllBannedIpEntries()).toEqual([]);
- });
-
- test('blocking networks needs the IP block and IP view permissions', async () => {
- const target = await createTestAccount(harness, {ipAddress: TARGET_IP});
- staff = await createStaff(harness, [AdminACLs.USER_TEMP_BAN, AdminACLs.BAN_IP_ADD]);
- await blockingSuspension(target, [TARGET_IP]).expect(HTTP_STATUS.FORBIDDEN, APIErrorCodes.MISSING_ACL).execute();
- expect((await loadUser(target)).enforcementDecisionId).toBeNull();
- });
-
- async function sightings(target: TestAccount, entries: Array<[string, number]>) {
- for (const [ip, lastUsed] of entries) {
- await upsertOne(
- AuthSessionTombstones.insert({
- user_id: createUserID(BigInt(target.userId)),
- session_id_hash: randomBytes(32),
- created_at: new Date(lastUsed),
- approx_last_used_at: new Date(lastUsed),
- client_ip: ip,
- client_user_agent: null,
- client_os: null,
- client_country: null,
- deleted_at: new Date(),
- version: 1,
- }),
- );
- }
- }
-
- test('only addresses the account used in the last 30 days can be blocked', async () => {
- const target = await createTestAccount(harness, {ipAddress: TARGET_IP});
- await sightings(target, [['45.33.20.1', Date.now() - 40 * DAY]]);
- expect(await refusedBlock(target, ['45.33.20.1'])).toBe(ValidationErrorCodes.ENFORCEMENT_NETWORK_UNKNOWN);
- expect(await refusedBlock(target, ['45.33.30.1'])).toBe(ValidationErrorCodes.ENFORCEMENT_NETWORK_UNKNOWN);
- await blockingSuspension(target, [TARGET_IP]).expect(HTTP_STATUS.OK).execute();
- });
-
- test('exempt addresses and special-purpose ranges are skipped and listed', async () => {
- const config = getConfig();
- const exempt = config.ipBanExemptIps;
- config.ipBanExemptIps = ['45.33.40.1'];
- resetIpBanExemptionsForTesting();
- try {
- const target = await createTestAccount(harness, {ipAddress: TARGET_IP});
- await sightings(target, [
- ['45.33.40.1', Date.now()],
- ['100.64.1.1', Date.now()],
- ['192.168.1.5', Date.now()],
- ]);
- const response = await blockingSuspension(target, ['45.33.40.1', '100.64.1.1', '192.168.1.5', TARGET_IP])
- .expect(HTTP_STATUS.OK)
- .execute();
- expect(response.skipped_ips).toEqual([
- {ip: '45.33.40.1', reason: 'exempt'},
- {ip: '100.64.1.1', reason: 'special_purpose'},
- {ip: '192.168.1.5', reason: 'special_purpose'},
- ]);
- expect((await adminRepository.loadAllBannedIpEntries()).map((entry) => entry.ip)).toEqual([TARGET_IP]);
- } finally {
- config.ipBanExemptIps = exempt;
- resetIpBanExemptionsForTesting();
- }
- });
-
- test('an address shared with an unrestricted account is refused, IPv6 by /64', async () => {
- const ipv6 = '2a01:e0a:d10:95b0::1';
- const target = await createTestAccount(harness, {ipAddress: TARGET_IP});
- await createTestAccount(harness, {ipAddress: TARGET_IP});
- expect(await refusedBlock(target, [TARGET_IP])).toBe(ValidationErrorCodes.ENFORCEMENT_NETWORK_SHARED);
-
- const v6Target = await createTestAccount(harness, {ipAddress: ipv6});
- await createTestAccount(harness, {ipAddress: '2a01:e0a:d10:95b0:abcd::7'});
- expect(await refusedBlock(v6Target, [ipv6])).toBe(ValidationErrorCodes.ENFORCEMENT_NETWORK_SHARED);
- expect(await adminRepository.loadAllBannedIpEntries()).toEqual([]);
- });
-
- test('accounts that are themselves suspended or closed do not count as sharing', async () => {
- const target = await createTestAccount(harness, {ipAddress: TARGET_IP});
- const suspended = await createTestAccount(harness, {ipAddress: TARGET_IP});
- const closed = await createTestAccount(harness, {ipAddress: TARGET_IP});
- await suspend(harness, staff, suspended.userId);
- await close(harness, staff, closed.userId);
-
- const candidates = await createBuilder<{
- networks: Array<{ip: string; skip_reason: string | null; other_unrestricted_accounts: number}>;
- }>(harness, staff.token)
- .get(`/admin/users/${target.userId}/network-block-candidates`)
- .expect(HTTP_STATUS.OK)
- .execute();
- expect(candidates.networks).toEqual([
- {ip: TARGET_IP, last_seen_at: expect.any(String), skip_reason: null, other_unrestricted_accounts: 0},
- ]);
- await blockingSuspension(target, [TARGET_IP]).expect(HTTP_STATUS.OK).execute();
- });
-
- test('a closure blocks networks too', async () => {
- const target = await createTestAccount(harness, {ipAddress: TARGET_IP});
- const {user} = await createBuilder<RestrictionResponse>(harness, staff.token)
- .put(`/admin/users/${target.userId}/deletion`)
- .header('X-Audit-Log-Reason', INTERNAL_NOTE)
- .body({
- days_until_deletion: 74,
- basis: {type: 'enforcement', decision: decisionBody()},
- block_networks: {ips: [TARGET_IP]},
- })
- .expect(HTTP_STATUS.OK)
- .execute();
- expect(await adminRepository.listDecisionIpBans(BigInt(user.enforcement_decision_id!))).toHaveLength(1);
- });
- });
-
- describe('linked rows and the blocklist', () => {
- test('a plain write never overwrites a linked row', async () => {
- await adminRepository.banIpForDecision(TARGET_IP, 42n, new Date(Date.now() + 90 * DAY));
- await adminRepository.banIp(TARGET_IP);
- await adminRepository.banIpTemp(TARGET_IP, 60);
- const [row] = await adminRepository.loadAllBannedIpEntries();
- expect(row?.decisionId).toBe(42n);
- expect(row?.kind).toBe('temporary_24h');
-
- await createBuilder(harness, staff.token)
- .post('/admin/blocklists/ip/entries')
- .body({ip: TARGET_IP})
- .expect(HTTP_STATUS.CONFLICT, APIErrorCodes.IP_BAN_LINKED_TO_DECISION)
- .execute();
- });
-
- test('a plain row becomes linked and keeps the later expiry, another decision keeps its row', async () => {
- const later = new Date(Date.now() + 200 * DAY);
- await insertPlainBlock(TARGET_IP, later);
- const linked = await adminRepository.banIpForDecision(TARGET_IP, 7n, new Date(Date.now() + 90 * DAY));
- expect(linked?.decisionId).toBe(7n);
- expect(linked?.expiresAt?.getTime()).toBe(later.getTime());
- expect(await adminRepository.banIpForDecision(TARGET_IP, 8n, new Date(Date.now() + DAY))).toBeNull();
- expect((await adminRepository.loadAllBannedIpEntries())[0]?.decisionId).toBe(7n);
-
- await adminRepository.banIp('45.33.50.1');
- expect(await adminRepository.banIpForDecision('45.33.50.1', 9n, new Date(Date.now() + DAY))).toBeNull();
- });
-
- test('the blocklist refuses to remove a linked row and the check names the decision', async () => {
- const target = await createTestAccount(harness, {ipAddress: TARGET_IP});
- const {user} = await blockingSuspension(target, [TARGET_IP]).expect(HTTP_STATUS.OK).execute();
- const decisionId = user.enforcement_decision_id!;
- const refused = await createBuilder<{decision_id: string}>(harness, staff.token)
- .delete(`/admin/blocklists/ip/entries/${encodeURIComponent(TARGET_IP)}`)
- .expect(HTTP_STATUS.CONFLICT, APIErrorCodes.IP_BAN_LINKED_TO_DECISION)
- .execute();
- expect(refused.decision_id).toBe(decisionId);
- const check = await createBuilder<{banned: boolean; decision_id: string | null}>(harness, staff.token)
- .get(`/admin/blocklists/ip/entries/${encodeURIComponent(TARGET_IP)}`)
- .expect(HTTP_STATUS.OK)
- .execute();
- expect(check).toMatchObject({banned: true, decision_id: decisionId});
- });
-
- test('ending the decision removes its rows and needs the IP removal permission', async () => {
- const target = await createTestAccount(harness, {ipAddress: TARGET_IP});
- const {user} = await blockingSuspension(target, [TARGET_IP]).expect(HTTP_STATUS.OK).execute();
- const decisionId = user.enforcement_decision_id!;
- const limited = await createStaff(harness, [AdminACLs.ENFORCEMENT_VIEW, AdminACLs.USER_TEMP_BAN]);
- await endDecision(harness, limited, decisionId)
- .expect(HTTP_STATUS.FORBIDDEN, APIErrorCodes.MISSING_ACL)
- .execute();
-
- const ended = await endDecision(harness, staff, decisionId).expect(HTTP_STATUS.OK).execute();
- expect(ended.network_blocks).toEqual([]);
- expect(await adminRepository.loadAllBannedIpEntries()).toEqual([]);
- expect(ipBanCache.isBanned(TARGET_IP)).toBe(false);
- });
-
- test('a closure takes over the blocks of the suspension it replaces and reversing it removes them', async () => {
- const target = await createTestAccount(harness, {ipAddress: TARGET_IP});
- const {user} = await blockingSuspension(target, [TARGET_IP]).expect(HTTP_STATUS.OK).execute();
- const closureId = await close(harness, staff, target.userId);
- expect(await adminRepository.listDecisionIpBans(BigInt(user.enforcement_decision_id!))).toEqual([]);
- expect(await adminRepository.listDecisionIpBans(BigInt(closureId))).toHaveLength(1);
- const closure = await getDecision(harness, staff, closureId);
- expect(closure.network_blocks).toHaveLength(1);
- await endDecision(harness, staff, closureId, 'reversed').expect(HTTP_STATUS.OK).execute();
- expect(await adminRepository.loadAllBannedIpEntries()).toEqual([]);
- await endDecision(harness, staff, user.enforcement_decision_id!, 'reversed').expect(HTTP_STATUS.OK).execute();
- });
-
- test('a temporary suspension that replaces a blocking one removes its blocks', async () => {
- const target = await createTestAccount(harness, {ipAddress: TARGET_IP});
- await blockingSuspension(target, [TARGET_IP]).expect(HTTP_STATUS.OK).execute();
- await suspend(harness, staff, target.userId);
- expect(await adminRepository.loadAllBannedIpEntries()).toEqual([]);
- });
-
- test('executing the deletion removes the rows of every decision on the account', async () => {
- const target = await createTestAccount(harness, {ipAddress: TARGET_IP});
- await blockingSuspension(target, [TARGET_IP]).expect(HTTP_STATUS.OK).execute();
- const closureId = await close(harness, staff, target.userId);
- const closed = await loadUser(target);
- const due = new Date(Date.now() - ms('1 minute'));
- await getUserRepository().updateDeletionSchedule(closed, {
- flags: closed.flags,
- pending_deletion_at: due,
- deletion_reason_code: closed.deletionReasonCode,
- deletion_scheduled_by: closed.deletionScheduledBy,
- deletion_scheduled_at: closed.deletionScheduledAt,
- });
- expect(await adminRepository.listDecisionIpBans(BigInt(closureId))).toHaveLength(1);
- await createBuilderWithoutAuth(harness)
- .post(`/test/worker/process-pending-deletion/${target.userId}`)
- .expect(HTTP_STATUS.OK)
- .execute();
- expect(await adminRepository.loadAllBannedIpEntries()).toEqual([]);
- });
- });
-
- describe('the block screen', () => {
- async function linkedBlock(reasonCode: DecisionBody['reason_code']): Promise<string> {
- const target = await createTestAccount(harness, {ipAddress: TARGET_IP});
- const {user} = await blockingSuspension(target, [TARGET_IP], {decision: decisionBody({reason_code: reasonCode})})
- .expect(HTTP_STATUS.OK)
- .execute();
- return user.enforcement_decision_id!;
- }
-
- test('a rule shown on the network screen gives its title and the appeals address', async () => {
- const decisionId = await linkedBlock(DeletionReasons.SPAM);
- expect(ipBanCache.getMatch(TARGET_IP)?.decision).toEqual({
- decisionId: BigInt(decisionId),
- reasonCode: DeletionReasons.SPAM,
- });
- const {response, json} = await requestFrom(TARGET_IP);
- expect(response.status).toBe(HTTP_STATUS.FORBIDDEN);
- expect(json.code).toBe(APIErrorCodes.GLOBAL_IP_TEMPORARILY_BANNED);
- expect(json.reason?.title).toBe('Spam');
- expect(json.appeal_email).toBe('[email protected]');
- expect(json.appeals_supported).toBe(true);
- expect(json.message).toMatch(
- /^Fluxer blocked access from this network because of activity that broke its rules\. The block ends on /,
- );
- expect(json.message).not.toMatch(/platform admin|sign in/i);
- expect(JSON.stringify(json)).not.toContain(decisionId);
- });
-
- test('a withheld reason is byte-identical to a plain block', async () => {
- const expiresAt = new Date(Date.now() + 90 * DAY);
- await insertPlainBlock(TARGET_IP, expiresAt);
- await ipBanCache.refresh();
- const plain = await requestFrom(TARGET_IP);
- expect(plain.response.status).toBe(HTTP_STATUS.FORBIDDEN);
-
- const target = await createTestAccount(harness);
- const decisionId = await suspend(
- harness,
- staff,
- target.userId,
- decisionBody({reason_code: DeletionReasons.SCAM_OR_SOCIAL_ENGINEERING}),
- );
- await adminRepository.banIpForDecision(TARGET_IP, BigInt(decisionId), expiresAt);
- await ipBanCache.refresh();
- expect(ipBanCache.getMatch(TARGET_IP)?.decision?.reasonCode).toBe(DeletionReasons.SCAM_OR_SOCIAL_ENGINEERING);
- const withheld = await requestFrom(TARGET_IP);
-
- expect(withheld.text).toBe(plain.text);
- expect(withheld.json.reason).toBeNull();
- expect(withheld.json.appeal_email).toBe('[email protected]');
- });
-
- test('self-hosted blocks give no contact and do not support appeals', async () => {
- const config = getConfig();
- const selfHosted = config.instance.selfHosted;
- config.instance.selfHosted = true;
- try {
- await linkedBlock(DeletionReasons.SPAM);
- const {json} = await requestFrom(TARGET_IP);
- expect(json.appeal_email).toBeNull();
- expect(json.appeals_supported).toBe(false);
- expect(json.message).not.toMatch(/@|Fluxer/);
- } finally {
- config.instance.selfHosted = selfHosted;
- }
- });
-
- test('instance discovery is served to a blocked network and an unknown sign-in gets the block', async () => {
- await linkedBlock(DeletionReasons.SPAM);
- const discovery = await requestFrom(TARGET_IP, '/.well-known/fluxer');
- expect(discovery.response.status).toBe(HTTP_STATUS.OK);
- const login = await createBuilderWithoutAuth<BlockErrorBody>(harness)
- .post('/auth/login')
- .header('x-forwarded-for', TARGET_IP)
- .body({email: '[email protected]', password: 'a-strong-password'})
- .executeRaw();
- expect(login.response.status).toBe(HTTP_STATUS.FORBIDDEN);
- expect(login.json.code).toBe(APIErrorCodes.GLOBAL_IP_TEMPORARILY_BANNED);
- });
- });
-});
diff --git a/fluxer_api/src/api/enforcement/tests/EnforcementSignIn.test.ts b/fluxer_api/src/api/enforcement/tests/EnforcementSignIn.test.ts
deleted file mode 100644
index 2d4dd65a5..000000000
--- a/fluxer_api/src/api/enforcement/tests/EnforcementSignIn.test.ts
+++ /dev/null
@@ -1,533 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {AdminRepository} from '@app/api/admin/AdminRepository';
-import {assertSignInAllowed} from '@app/api/auth/AuthUtility';
-import {
- clearTestEmails,
- createTestAccount,
- createTotpSecret,
- createUniqueEmail,
- disableSso,
- enableSso,
- listTestEmails,
- type TestAccount,
- totpCodeNow,
-} from '@app/api/auth/tests/AuthTestUtils';
-import {
- createAuthenticationResponse,
- createRegistrationResponse,
- createWebAuthnDevice,
- type WebAuthnAuthenticationOptions,
- type WebAuthnDevice,
- type WebAuthnRegistrationOptions,
-} from '@app/api/auth/tests/WebAuthnTestUtils';
-import {createApiContext} from '@app/api/CreateApiContext';
-import {EnforcementDecisionRepository} from '@app/api/enforcement/EnforcementDecisionRepository';
-import {formatNoticeDate} from '@app/api/enforcement/NoticeDates';
-import {
- createStaff,
- decisionBody,
- emailsTo,
- getDecision,
- loadUser,
- suspend,
- suspendRequest,
-} from '@app/api/enforcement/tests/EnforcementTestUtils';
-import {applySharedListUpdate, resetSharedListsForTests} from '@app/api/infrastructure/activity/SharedLists';
-import {ipBanCache} from '@app/api/middleware/IpBanMiddleware';
-import {getUserRepository} from '@app/api/middleware/ServiceSingletons';
-import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
-import {HTTP_STATUS} from '@app/api/test/TestConstants';
-import {createBuilder, createBuilderWithoutAuth} from '@app/api/test/TestRequestBuilder';
-import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
-import {DeletionReasons} from '@fluxer/constants/src/Core';
-import {UserFlags} from '@fluxer/constants/src/UserConstants';
-import {AccountTemporarilySuspendedError} from '@fluxer/errors/src/domains/user/AccountTemporarilySuspendedError';
-import type {EnforcementNotice} from '@fluxer/schema/src/domains/auth/EnforcementNoticeSchemas';
-import {ms} from 'itty-time';
-import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, test, vi} from 'vitest';
-
-interface SignInBody {
- code?: string;
- notice?: EnforcementNotice | null;
- token?: string;
- mfa?: boolean;
- ticket?: string;
- ip_authorization_required?: boolean;
-}
-
-const BLOCKED_IP = '45.33.10.1';
-const DAY = ms('1 day');
-
-describe('Enforcement sign-in', () => {
- let harness: ApiTestHarness;
- let staff: TestAccount;
-
- beforeAll(async () => {
- harness = await createApiTestHarness();
- });
-
- beforeEach(async () => {
- await harness.reset();
- ipBanCache.resetCaches();
- resetSharedListsForTests();
- await clearTestEmails(harness);
- staff = await createStaff(harness);
- });
-
- afterEach(() => {
- vi.restoreAllMocks();
- resetSharedListsForTests();
- });
-
- afterAll(async () => {
- await harness?.shutdown();
- });
-
- function login(account: TestAccount, ip?: string, password = account.password) {
- const builder = createBuilderWithoutAuth<SignInBody>(harness)
- .post('/auth/login')
- .body({email: account.email, password});
- if (ip) builder.header('x-forwarded-for', ip);
- return builder.executeRaw();
- }
-
- function completeTotp(ticket: string, secret: string, ip?: string) {
- const builder = createBuilderWithoutAuth<SignInBody>(harness)
- .post('/auth/login/mfa/totp')
- .body({ticket, code: totpCodeNow(secret)});
- if (ip) builder.header('x-forwarded-for', ip);
- return builder.executeRaw();
- }
-
- async function enableTotp(account: TestAccount): Promise<string> {
- const secret = createTotpSecret();
- await createBuilder(harness, account.token)
- .post('/users/@me/mfa/totp/enable')
- .body({secret, code: totpCodeNow(secret), password: account.password})
- .expect(HTTP_STATUS.OK)
- .execute();
- return secret;
- }
-
- async function middlewareBlock(ip: string): Promise<string> {
- const {response, text} = await createBuilderWithoutAuth(harness)
- .get('/users/@me')
- .header('x-forwarded-for', ip)
- .executeRaw();
- expect(response.status).toBe(HTTP_STATUS.FORBIDDEN);
- return text;
- }
-
- async function suspendPermanently(target: TestAccount, ips: Array<string> = []): Promise<string> {
- const {user} = await suspendRequest(harness, staff, target.userId, {
- duration_hours: 0,
- decision: decisionBody(),
- ...(ips.length > 0 ? {block_networks: {ips}} : {}),
- })
- .expect(HTTP_STATUS.OK)
- .execute();
- return user.enforcement_decision_id!;
- }
-
- async function setLegacySuspension(account: TestAccount, until: Date): Promise<void> {
- const users = getUserRepository();
- const user = await loadUser(account);
- await users.patchUpsert(user.id, {temp_banned_until: until}, user.toRow());
- await users.updateFlags(user.id, (flags) => flags | UserFlags.DISABLED);
- }
-
- async function ipAuthorizationEmails(account: TestAccount) {
- return (await listTestEmails(harness, {recipient: account.email})).filter(
- (email) => email.type === 'ip_authorization',
- );
- }
-
- describe('notices', () => {
- test('an account without MFA sees its notice after the password', async () => {
- const target = await createTestAccount(harness);
- const decisionId = await suspend(harness, staff, target.userId);
- const {response, json} = await login(target);
- expect(response.status).toBe(HTTP_STATUS.FORBIDDEN);
- expect(json.code).toBe(APIErrorCodes.ACCOUNT_SUSPENDED_TEMPORARILY);
- expect(json.notice).toMatchObject({
- decision_id: decisionId,
- kind: 'suspension',
- permanent: false,
- rule: {title: 'Spam'},
- appeal: {email: '[email protected]', account_has_email: true},
- });
- expect(json.notice?.summary).toMatch(/^We suspended your account until /);
- });
-
- test('a wrong password on a suspended account gets no notice', async () => {
- const target = await createTestAccount(harness);
- await suspend(harness, staff, target.userId);
- const {response, json} = await login(target, undefined, 'not-the-password-1');
- expect(response.status).toBe(HTTP_STATUS.BAD_REQUEST);
- expect(json.notice).toBeUndefined();
- });
-
- test('the notice uses the request locale', async () => {
- const target = await createTestAccount(harness);
- await suspend(harness, staff, target.userId);
- const {json} = await createBuilderWithoutAuth<SignInBody>(harness)
- .post('/auth/login')
- .header('accept-language', 'de')
- .body({email: target.email, password: target.password})
- .executeRaw();
- expect(json.notice?.summary).toMatch(/\d{2}\.\d{2}\.\d{4}/);
- });
-
- test('an MFA account gets its ticket and sees the notice only after the code', async () => {
- const target = await createTestAccount(harness);
- const secret = await enableTotp(target);
- const decisionId = await suspend(harness, staff, target.userId);
- const first = await login(target);
- expect(first.response.status).toBe(HTTP_STATUS.OK);
- expect(first.json.mfa).toBe(true);
- expect(first.json.notice).toBeUndefined();
- const second = await completeTotp(first.json.ticket!, secret);
- expect(second.response.status).toBe(HTTP_STATUS.FORBIDDEN);
- expect(second.json.code).toBe(APIErrorCodes.ACCOUNT_SUSPENDED_TEMPORARILY);
- expect(second.json.notice?.decision_id).toBe(decisionId);
- });
-
- test('a passkey sign-in sees the notice', async () => {
- const target = await createTestAccount(harness);
- const device = await registerPasskey(target);
- const decisionId = await suspend(harness, staff, target.userId);
- const {response, json} = await passkeySignIn(device);
- expect(response.status).toBe(HTTP_STATUS.FORBIDDEN);
- expect(json.notice?.decision_id).toBe(decisionId);
- });
-
- test('an SSO sign-in sees the notice', async () => {
- const admin = await createStaff(harness);
- await enableSso(harness, admin.token);
- try {
- const email = createUniqueEmail('sso-signin');
- const first = await ssoSignIn(email);
- expect(first.response.status).toBe(HTTP_STATUS.OK);
- const decisionId = await suspend(harness, staff, first.json.user_id!);
- const second = await ssoSignIn(email);
- expect(second.response.status).toBe(HTTP_STATUS.FORBIDDEN);
- expect(second.json.code).toBe(APIErrorCodes.ACCOUNT_SUSPENDED_TEMPORARILY);
- expect(second.json.notice?.decision_id).toBe(decisionId);
- } finally {
- await disableSso(harness, admin.token);
- }
- });
-
- test('a permanent suspension returns PERMANENTLY', async () => {
- const target = await createTestAccount(harness);
- await suspendPermanently(target);
- const {json} = await login(target);
- expect(json.code).toBe(APIErrorCodes.ACCOUNT_SUSPENDED_PERMANENTLY);
- expect(json.notice).toMatchObject({kind: 'suspension', permanent: true, ends_at: null});
- });
-
- test('a pre-v2 100-year ban returns PERMANENTLY with the legacy notice', async () => {
- const target = await createTestAccount(harness);
- const until = new Date();
- until.setUTCFullYear(until.getUTCFullYear() + 100);
- await setLegacySuspension(target, until);
- const {json} = await login(target);
- expect(json.code).toBe(APIErrorCodes.ACCOUNT_SUSPENDED_PERMANENTLY);
- expect(json.notice).toMatchObject({
- decision_id: null,
- kind: 'suspension',
- permanent: true,
- facts: ["We don't have more detail on record for this decision."],
- });
- });
-
- test('a pre-v2 temporary suspension returns TEMPORARILY with the legacy notice', async () => {
- const target = await createTestAccount(harness);
- await setLegacySuspension(target, new Date(Date.now() + DAY));
- const {json} = await login(target);
- expect(json.code).toBe(APIErrorCodes.ACCOUNT_SUSPENDED_TEMPORARILY);
- expect(json.notice).toMatchObject({decision_id: null, kind: 'suspension', permanent: false});
- });
-
- test('a pre-v2 closure returns PERMANENTLY with its stored public reason', async () => {
- const target = await createTestAccount(harness);
- const users = getUserRepository();
- const user = await loadUser(target);
- await users.updateDeletionSchedule(user, {
- flags: user.flags | UserFlags.DELETED,
- pending_deletion_at: new Date(Date.now() + 30 * DAY),
- deletion_reason_code: 3,
- deletion_public_reason: 'Sent spam to many people.',
- });
- const {json} = await login(target);
- expect(json.code).toBe(APIErrorCodes.ACCOUNT_SUSPENDED_PERMANENTLY);
- expect(json.notice).toMatchObject({
- decision_id: null,
- kind: 'closure',
- statement: 'Sent spam to many people.',
- });
- });
-
- test.each([DeletionReasons.USER_REQUESTED, DeletionReasons.INACTIVITY])(
- 'a pre-v2 staff deletion with code %s gets no enforcement notice',
- async (code) => {
- const target = await createTestAccount(harness);
- const user = await loadUser(target);
- await getUserRepository().updateDeletionSchedule(user, {
- flags: user.flags | UserFlags.DELETED,
- pending_deletion_at: new Date(Date.now() + 30 * DAY),
- deletion_reason_code: code,
- deletion_public_reason: 'Requested by the holder',
- });
- const {json} = await login(target);
- expect(json.code).toBe(APIErrorCodes.ACCOUNT_SUSPENDED_PERMANENTLY);
- expect(json.notice).toBeNull();
- },
- );
-
- test('an expired suspension is cleared at sign-in, recorded as expired and can still be reversed', async () => {
- const target = await createTestAccount(harness);
- const decisionId = await suspend(harness, staff, target.userId);
- const user = await loadUser(target);
- await getUserRepository().patchUpsert(user.id, {temp_banned_until: new Date(Date.now() - 1000)}, user.toRow());
- const {response} = await login(target);
- expect(response.status).toBe(HTTP_STATUS.OK);
- const cleared = await loadUser(target);
- expect(cleared.enforcementDecisionId).toBeNull();
- expect(cleared.tempBannedUntil).toBeNull();
- expect(cleared.flags & UserFlags.DISABLED).toBe(0n);
- const expired = await createBuilder<{status: string; end_outcome: string | null; ended_by: string | null}>(
- harness,
- staff.token,
- )
- .get(`/admin/enforcement-decisions/${decisionId}`)
- .expect(HTTP_STATUS.OK)
- .execute();
- expect(expired).toMatchObject({status: 'ended', end_outcome: 'expired', ended_by: '0'});
- await createBuilder(harness, staff.token)
- .post(`/admin/enforcement-decisions/${decisionId}/end`)
- .header('X-Audit-Log-Reason', 'Appeal upheld')
- .body({outcome: 'lifted'})
- .expect(HTTP_STATUS.CONFLICT)
- .execute();
- await createBuilder(harness, staff.token)
- .post(`/admin/enforcement-decisions/${decisionId}/end`)
- .header('X-Audit-Log-Reason', 'Appeal upheld')
- .body({outcome: 'reversed'})
- .expect(HTTP_STATUS.OK)
- .execute();
- const [ended] = await emailsTo(harness, target, 'enforcement_ended');
- expect(ended?.metadata).toMatchObject({outcome: 'reversed', decision_id: decisionId, restores_access: 'no'});
- });
- });
-
- describe('accounts with no email', () => {
- test('the first sign-in delivers the notice and starts the appeal deadline', async () => {
- const target = await createTestAccount(harness);
- const user = await loadUser(target);
- await getUserRepository().patchUpsert(user.id, {email: null}, user.toRow());
- const decisionId = await suspend(harness, staff, target.userId);
- expect((await getDecision(harness, staff, decisionId)).notice_status).toBe('undelivered');
-
- const before = Date.now();
- const first = await signInDirectly(target);
- const decision = await new EnforcementDecisionRepository().get(BigInt(decisionId));
- expect(decision?.notice_status).toBe('sent');
- expect(decision?.notice_channels).toEqual(new Set(['sign_in']));
- expect(decision?.notice_locale).toBe('en-US');
- expect(decision?.notice_text).toContain(first.summary);
- const sentAt = decision!.notice_sent_at!;
- expect(sentAt.getTime()).toBeGreaterThanOrEqual(before);
- expect(first.appeal).toEqual({
- email: '[email protected]',
- deadline: formatNoticeDate(new Date(sentAt.getTime() + 60 * DAY), 'en-US'),
- account_has_email: false,
- });
-
- const second = await signInDirectly(target);
- expect(second.appeal).toEqual(first.appeal);
- const unchanged = await new EnforcementDecisionRepository().get(BigInt(decisionId));
- expect(unchanged?.notice_sent_at).toEqual(sentAt);
- });
-
- async function signInDirectly(account: TestAccount): Promise<EnforcementNotice> {
- const ctx = createApiContext({
- requestId: 'sign-in-test',
- clientIp: '127.0.0.1',
- userAgent: null,
- locale: 'en-US',
- blockedNetworkSignIn: null,
- });
- const error = await assertSignInAllowed(ctx, await loadUser(account)).catch((caught: unknown) => caught);
- expect(error).toBeInstanceOf(AccountTemporarilySuspendedError);
- return (error as AccountTemporarilySuspendedError).data!['notice'] as EnforcementNotice;
- }
- });
-
- describe.each([
- {
- source: 'a linked block',
- block: async () => {
- const other = await createTestAccount(harness);
- const decisionId = await suspend(harness, staff, other.userId);
- await new AdminRepository().banIpForDecision(BLOCKED_IP, BigInt(decisionId), new Date(Date.now() + 90 * DAY));
- await ipBanCache.refresh();
- },
- },
- {
- source: 'the shared list',
- block: async () => {
- applySharedListUpdate('ip_blocked', `${BLOCKED_IP}\n`);
- },
- },
- ])('signing in from $source', ({block}) => {
- test('every outcome but a restricted account gets the same block, with no ticket and no email', async () => {
- const plain = await createTestAccount(harness);
- const withMfa = await createTestAccount(harness);
- await enableTotp(withMfa);
- await block();
- await clearTestEmails(harness);
- const expected = await middlewareBlock(BLOCKED_IP);
- const unknown = {...plain, email: createUniqueEmail('nobody')};
- const attempts = [
- await login(unknown, BLOCKED_IP),
- await login(plain, BLOCKED_IP, 'not-the-password-1'),
- await login(plain, BLOCKED_IP),
- await login(withMfa, BLOCKED_IP),
- ];
- for (const attempt of attempts) {
- expect(attempt.response.status).toBe(HTTP_STATUS.FORBIDDEN);
- expect(attempt.text).toBe(expected);
- }
- expect(await ipAuthorizationEmails(plain)).toEqual([]);
- expect((await loadUser(plain)).flags & UserFlags.DISABLED).toBe(0n);
- });
-
- test('a restricted account sees its notice', async () => {
- const target = await createTestAccount(harness);
- const decisionId = await suspend(harness, staff, target.userId);
- await block();
- const {response, json} = await login(target, BLOCKED_IP);
- expect(response.status).toBe(HTTP_STATUS.FORBIDDEN);
- expect(json.code).toBe(APIErrorCodes.ACCOUNT_SUSPENDED_TEMPORARILY);
- expect(json.notice?.decision_id).toBe(decisionId);
- });
-
- test('a restricted MFA account gets its ticket and then the notice', async () => {
- const target = await createTestAccount(harness);
- const secret = await enableTotp(target);
- const decisionId = await suspend(harness, staff, target.userId);
- await block();
- const first = await login(target, BLOCKED_IP);
- expect(first.response.status).toBe(HTTP_STATUS.OK);
- expect(first.json.ticket).toBeTruthy();
- const second = await completeTotp(first.json.ticket!, secret, BLOCKED_IP);
- expect(second.response.status).toBe(HTTP_STATUS.FORBIDDEN);
- expect(second.json.notice?.decision_id).toBe(decisionId);
- });
-
- test('an unrestricted MFA ticket from another network cannot be completed', async () => {
- const target = await createTestAccount(harness);
- const secret = await enableTotp(target);
- const first = await login(target);
- await block();
- const second = await completeTotp(first.json.ticket!, secret, BLOCKED_IP);
- expect(second.text).toBe(await middlewareBlock(BLOCKED_IP));
- });
-
- test('a self-deleted account is not reactivated', async () => {
- const target = await createTestAccount(harness);
- await createBuilderWithoutAuth(harness)
- .post(`/test/users/${target.userId}/set-pending-deletion`)
- .body({pending_deletion_at: new Date(Date.now() + 14 * DAY).toISOString(), set_self_deleted_flag: true})
- .expect(HTTP_STATUS.OK)
- .execute();
- await block();
- const {text} = await login(target, BLOCKED_IP);
- expect(text).toBe(await middlewareBlock(BLOCKED_IP));
- const user = await loadUser(target);
- expect(user.flags & UserFlags.SELF_DELETED).toBe(UserFlags.SELF_DELETED);
- expect(user.pendingDeletionAt).not.toBeNull();
- });
-
- test('other routes stay blocked', async () => {
- await block();
- const {response} = await createBuilderWithoutAuth(harness)
- .post('/auth/forgot')
- .header('x-forwarded-for', BLOCKED_IP)
- .body({email: createUniqueEmail('nobody')})
- .executeRaw();
- expect(response.status).toBe(HTTP_STATUS.FORBIDDEN);
- });
- });
-
- test('a holder behind a block from their own decision sees the notice, not the block', async () => {
- const target = await createTestAccount(harness, {ipAddress: BLOCKED_IP});
- const decisionId = await suspendPermanently(target, [BLOCKED_IP]);
- const {json} = await login(target, BLOCKED_IP);
- expect(json.code).toBe(APIErrorCodes.ACCOUNT_SUSPENDED_PERMANENTLY);
- expect(json.notice?.decision_id).toBe(decisionId);
- });
-
- test('SSO from a blocked network never provisions an account', async () => {
- const admin = await createStaff(harness);
- await enableSso(harness, admin.token);
- try {
- applySharedListUpdate('ip_blocked', `${BLOCKED_IP}\n`);
- const email = createUniqueEmail('sso-blocked');
- const {text} = await ssoSignIn(email, BLOCKED_IP);
- expect(text).toBe(await middlewareBlock(BLOCKED_IP));
- expect(await getUserRepository().findByEmail(email)).toBeNull();
- } finally {
- await disableSso(harness, admin.token);
- }
- });
-
- async function registerPasskey(account: TestAccount): Promise<WebAuthnDevice> {
- const device = createWebAuthnDevice();
- const secret = await enableTotp(account);
- const options = await createBuilder<WebAuthnRegistrationOptions>(harness, account.token)
- .post('/users/@me/mfa/webauthn/credentials/registration-options')
- .body({mfa_method: 'totp', mfa_code: totpCodeNow(secret)})
- .execute();
- if (options.rp.id) device.rpId = options.rp.id;
- await createBuilder(harness, account.token)
- .post('/users/@me/mfa/webauthn/credentials')
- .body({
- response: createRegistrationResponse(device, options, 'Passkey'),
- challenge: options.challenge,
- name: 'Passkey',
- mfa_method: 'totp',
- mfa_code: totpCodeNow(secret),
- })
- .expect(HTTP_STATUS.NO_CONTENT)
- .execute();
- return device;
- }
-
- async function passkeySignIn(device: WebAuthnDevice) {
- const options = await createBuilderWithoutAuth<WebAuthnAuthenticationOptions>(harness)
- .post('/auth/webauthn/authentication-options')
- .body(null)
- .execute();
- if (options.rpId) device.rpId = options.rpId;
- return createBuilderWithoutAuth<SignInBody>(harness)
- .post('/auth/webauthn/authenticate')
- .body({response: createAuthenticationResponse(device, options), challenge: options.challenge})
- .executeRaw();
- }
-
- async function ssoSignIn(email: string, ip?: string) {
- const start = createBuilderWithoutAuth<{state: string; client_binding: string}>(harness)
- .post('/auth/sso/start')
- .body({});
- if (ip) start.header('x-forwarded-for', ip);
- const {state, client_binding} = await start.execute();
- const complete = createBuilderWithoutAuth<SignInBody & {user_id?: string}>(harness)
- .post('/auth/sso/complete')
- .body({code: email, state, client_binding});
- if (ip) complete.header('x-forwarded-for', ip);
- return complete.executeRaw();
- }
-});
diff --git a/fluxer_api/src/api/infrastructure/activity/tests/SharedLists.test.ts b/fluxer_api/src/api/infrastructure/activity/tests/SharedLists.test.ts
deleted file mode 100644
index 51881e196..000000000
--- a/fluxer_api/src/api/infrastructure/activity/tests/SharedLists.test.ts
+++ /dev/null
@@ -1,139 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- resetSharedListsForTests,
- sharedListHas,
- startSharedListWatch,
-} from '@app/api/infrastructure/activity/SharedLists';
-import type {LoggerInterface} from '@fluxer/logger/src/LoggerInterface';
-import {JetStreamApiCodes, JetStreamApiError, type JetStreamClient} from '@nats-io/jetstream';
-import {afterEach, describe, expect, it, vi} from 'vitest';
-
-interface LogEntry {
- level: 'info' | 'debug';
- fields: object;
- message?: string;
-}
-
-class RecordingLogger implements LoggerInterface {
- readonly entries: Array<LogEntry> = [];
- trace(): void {}
- warn(): void {}
- error(): void {}
- fatal(): void {}
- info(fields: object | string, message?: string): void {
- this.record('info', fields, message);
- }
- debug(fields: object | string, message?: string): void {
- this.record('debug', fields, message);
- }
- child(): LoggerInterface {
- return this;
- }
- messages(level: LogEntry['level'], message: string): Array<LogEntry> {
- return this.entries.filter((entry) => entry.level === level && entry.message === message);
- }
- private record(level: LogEntry['level'], fields: object | string, message?: string): void {
- this.entries.push(typeof fields === 'string' ? {level, fields: {}, message: fields} : {level, fields, message});
- }
-}
-
-function isStreamNotFound(error: unknown): boolean {
- return error instanceof JetStreamApiError && error.code === JetStreamApiCodes.StreamNotFound;
-}
-
-interface FakeMessage {
- subject: string;
- headers: {get(name: string): string} | undefined;
- string(): string;
-}
-
-class FakeJetStream {
- streamExists = false;
- streamChecks = 0;
- consumerGets = 0;
- readonly pending: Array<FakeMessage> = [];
-
- get attempts(): number {
- return this.streamChecks + this.consumerGets;
- }
-
- readonly streams = {
- get: async (name: string) => {
- this.streamChecks++;
- if (!this.streamExists) {
- throw new JetStreamApiError({
- code: 404,
- err_code: JetStreamApiCodes.StreamNotFound,
- description: 'stream not found',
- });
- }
- return {name};
- },
- };
-
- readonly consumers = {
- get: async () => {
- this.consumerGets++;
- if (!this.streamExists) {
- throw new JetStreamApiError({
- code: 404,
- err_code: JetStreamApiCodes.StreamNotFound,
- description: 'stream not found',
- });
- }
- const messages = this.pending.splice(0);
- let close = () => {};
- const closed = new Promise<void>((resolve) => {
- close = resolve;
- });
- return {
- consume: async () => ({
- close: async () => close(),
- async *[Symbol.asyncIterator]() {
- yield* messages;
- await closed;
- },
- }),
- };
- },
- };
-
- client(): JetStreamClient {
- return this as unknown as JetStreamClient;
- }
-}
-
-function kvPut(name: string, value: string): FakeMessage {
- return {subject: `$KV.lists.${name}`, headers: undefined, string: () => value};
-}
-
-describe('shared list watch', () => {
- afterEach(() => {
- resetSharedListsForTests();
- });
-
- it('checks for the lists stream quietly and only consumes once it exists', async () => {
- const js = new FakeJetStream();
- const logger = new RecordingLogger();
- startSharedListWatch(js.client(), {selfHosted: true, retryDelayMs: 5, logger});
-
- await vi.waitFor(() => expect(js.attempts).toBeGreaterThanOrEqual(3));
- expect(
- logger
- .messages('debug', 'Shared list watch unavailable, retrying')
- .filter((entry) => isStreamNotFound((entry.fields as {err?: unknown}).err)),
- ).toHaveLength(0);
- expect(logger.messages('info', 'Shared list stream does not exist, checking again later')).toHaveLength(1);
- expect(js.consumerGets).toBe(0);
- expect(sharedListHas('email_tld_blocked', 'blocked')).toBe(false);
-
- js.pending.push(kvPut('email_tld_blocked', 'blocked\n'));
- js.streamExists = true;
-
- await vi.waitFor(() => expect(sharedListHas('email_tld_blocked', 'blocked')).toBe(true));
- expect(js.consumerGets).toBe(1);
- expect(logger.messages('info', 'Shared list stream found, watching lists')).toHaveLength(1);
- expect(logger.messages('info', 'Shared list stream does not exist, checking again later')).toHaveLength(1);
- });
-});
diff --git a/fluxer_api/src/api/infrastructure/tests/LiveKitWebhookPinning.test.ts b/fluxer_api/src/api/infrastructure/tests/LiveKitWebhookPinning.test.ts
deleted file mode 100644
index 0819e1803..000000000
--- a/fluxer_api/src/api/infrastructure/tests/LiveKitWebhookPinning.test.ts
+++ /dev/null
@@ -1,194 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {createHash, createHmac} from 'node:crypto';
-import type {IGatewayService} from '@app/api/infrastructure/IGatewayService';
-import type {ILiveKitService} from '@app/api/infrastructure/ILiveKitService';
-import type {IVoiceRoomStore} from '@app/api/infrastructure/IVoiceRoomStore';
-import {LiveKitWebhookService} from '@app/api/infrastructure/LiveKitWebhookService';
-import type {VoiceRegionRecord, VoiceServerRecord} from '@app/api/voice/VoiceModel';
-import type {VoiceTopology} from '@app/api/voice/VoiceTopology';
-import type {WebhookEvent} from 'livekit-server-sdk';
-import {describe, expect, it} from 'vitest';
-
-const GUILD = '100';
-const CHANNEL = '200';
-const ROOM = `guild_${GUILD}_channel_${CHANNEL}`;
-
-function server(serverId: string, apiKey: string): VoiceServerRecord {
- return {
- regionId: 'fra',
- serverId,
- endpoint: `wss://${serverId}.example.com`,
- apiKey,
- apiSecret: `${apiKey}-secret`,
- latitude: null,
- longitude: null,
- isActive: true,
- softConnectionLimit: null,
- notes: null,
- internalEndpoint: null,
- pinnedHostname: null,
- pinnedSoftLimit: false,
- draining: false,
- restrictions: {
- vipOnly: false,
- requiredGuildFeatures: new Set(),
- allowedGuildIds: new Set(),
- allowedUserIds: new Set(),
- },
- createdAt: null,
- updatedAt: null,
- };
-}
-
-function setup(servers: Array<VoiceServerRecord> = [server('pinned', 'key-pinned'), server('other', 'key-other')]) {
- const calls: Array<string> = [];
- let pinned: {regionId: string; serverId: string} | null = {regionId: 'fra', serverId: 'pinned'};
- const topology = {
- getAllRegions: () => [{id: 'fra'} as VoiceRegionRecord],
- getServersForRegion: () => servers,
- registerSubscriber: () => {},
- } as unknown as VoiceTopology;
- const roomStore = {
- getPinnedRoomServer: async () => pinned,
- deleteRoomServer: async () => {
- calls.push('delete_pin');
- pinned = null;
- },
- pinRoomServer: async () => {},
- } as unknown as IVoiceRoomStore;
- const gateway = {
- confirmVoiceConnection: async () => {
- calls.push('confirm');
- return {success: true};
- },
- disconnectVoiceUserIfInChannel: async () => {
- calls.push('disconnect');
- return {success: true};
- },
- } as unknown as IGatewayService;
- const liveKit = {
- listParticipants: async ({serverId}: {serverId: string}) => {
- calls.push(`list:${serverId}`);
- return {status: 'ok', participants: []};
- },
- disconnectParticipant: async () => calls.push('kick'),
- muteMicrophoneTrack: async () => calls.push('mute'),
- } as unknown as ILiveKitService;
- const service = new LiveKitWebhookService(roomStore, gateway, liveKit, topology);
- return {service, calls};
-}
-
-function participantEvent(event: string, metadataServer: string): WebhookEvent {
- return {
- event,
- room: {name: ROOM},
- participant: {
- identity: 'user_1_conn',
- metadata: JSON.stringify({
- user_id: '1',
- channel_id: CHANNEL,
- guild_id: GUILD,
- connection_id: 'conn',
- token_nonce: 'nonce',
- issued_at: '1',
- region_id: 'fra',
- server_id: metadataServer,
- }),
- attributes: {},
- },
- } as unknown as WebhookEvent;
-}
-
-describe('LiveKit webhooks from a server the room is not pinned to', () => {
- it('ignores forged participant events and room_finished', async () => {
- const {service, calls} = setup();
- await service.processEvent({event: participantEvent('participant_left', 'pinned'), apiKey: 'key-other'});
- await service.processEvent({event: participantEvent('participant_joined', 'pinned'), apiKey: 'key-other'});
- await service.processEvent({
- event: {event: 'room_finished', room: {name: ROOM}} as WebhookEvent,
- apiKey: 'key-other',
- });
- expect(calls).toEqual([]);
- });
-
- it('acts on events from the pinned server and checks presence on that server', async () => {
- const {service, calls} = setup();
- await service.processEvent({event: participantEvent('participant_joined', 'other'), apiKey: 'key-pinned'});
- await service.processEvent({event: participantEvent('participant_left', 'other'), apiKey: 'key-pinned'});
- await service.processEvent({
- event: {event: 'room_finished', room: {name: ROOM}} as WebhookEvent,
- apiKey: 'key-pinned',
- });
- expect(calls).toEqual(['confirm', 'list:pinned', 'disconnect', 'delete_pin']);
- });
-
- it('ignores rooms made by rexctl voice test', async () => {
- const {service, calls} = setup();
- await service.processEvent({
- event: {event: 'room_finished', room: {name: 'rexctl-test-abc'}} as WebhookEvent,
- apiKey: 'key-pinned',
- });
- expect(calls).toEqual([]);
- });
-});
-
-describe('LiveKit webhooks from servers that share an API key', () => {
- const shared = () => setup([server('pinned', 'fluxer'), server('other', 'fluxer')]);
-
- it('clears the voice state when a participant leaves the server that is not last in the list', async () => {
- const {service, calls} = shared();
- await service.processEvent({event: participantEvent('participant_left', 'pinned'), apiKey: 'fluxer'});
- expect(calls).toEqual(['list:pinned', 'disconnect']);
- });
-
- it('confirms joins on either server', async () => {
- const {service, calls} = shared();
- await service.processEvent({event: participantEvent('participant_joined', 'pinned'), apiKey: 'fluxer'});
- expect(calls).toEqual(['confirm']);
- });
-
- it('ignores events whose metadata points at a server the room is not pinned to', async () => {
- const {service, calls} = shared();
- await service.processEvent({event: participantEvent('participant_left', 'other'), apiKey: 'fluxer'});
- expect(calls).toEqual([]);
- });
-
- it('ignores metadata that points at a server with another key', async () => {
- const {service, calls} = setup([server('pinned', 'fluxer'), server('other', 'fluxer'), server('third', 'own')]);
- await service.processEvent({event: participantEvent('participant_left', 'third'), apiKey: 'fluxer'});
- expect(calls).toEqual([]);
- });
-
- it('clears the pin when the pinned server finishes the room', async () => {
- const {service, calls} = shared();
- await service.processEvent({event: {event: 'room_finished', room: {name: ROOM}} as WebhookEvent, apiKey: 'fluxer'});
- expect(calls).toEqual(['delete_pin']);
- });
-});
-
-describe('LiveKit webhook signatures', () => {
- function signed(body: string, offsetSeconds: number): string {
- const encode = (value: unknown) => Buffer.from(JSON.stringify(value)).toString('base64url');
- const now = Math.floor(Date.now() / 1000) + offsetSeconds;
- const claims = {
- iss: 'key-pinned',
- nbf: now - 10,
- exp: now + 60,
- sha256: createHash('sha256').update(body).digest('base64'),
- };
- const input = `${encode({alg: 'HS256', typ: 'JWT'})}.${encode(claims)}`;
- return `${input}.${createHmac('sha256', 'key-pinned-secret').update(input).digest('base64url')}`;
- }
-
- it('accepts a voice machine whose clock is up to a minute off', async () => {
- const {service} = setup();
- const body = JSON.stringify({event: 'room_started', id: 'EV_1', room: {name: ROOM}});
- for (const offset of [45, -45]) {
- await expect(service.verifyAndParse(body, signed(body, offset))).resolves.toMatchObject({apiKey: 'key-pinned'});
- }
- for (const offset of [180, -180]) {
- await expect(service.verifyAndParse(body, signed(body, offset))).rejects.toThrow();
- }
- });
-});
diff --git a/fluxer_api/src/api/instance/tests/DiscoverySelfHostFields.test.ts b/fluxer_api/src/api/instance/tests/DiscoverySelfHostFields.test.ts
index 166038163..fc72da02f 100644
--- a/fluxer_api/src/api/instance/tests/DiscoverySelfHostFields.test.ts
+++ b/fluxer_api/src/api/instance/tests/DiscoverySelfHostFields.test.ts
@@ -1,33 +1,16 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import {createAuthHarness} from '@app/api/auth/tests/AuthTestUtils';
-import {getConfig} from '@app/api/Config';
import {getInstanceConfigRepository} from '@app/api/middleware/ServiceSingletons';
import type {ApiTestHarness} from '@app/api/test/ApiTestHarness';
-import {server} from '@app/api/test/msw/server';
import {createBuilderWithoutAuth} from '@app/api/test/TestRequestBuilder';
import {parseInstanceDiscoveryDocument} from '@fluxer/instance_bootstrap/src/Discovery';
import type {WellKnownFluxerResponse} from '@fluxer/schema/src/domains/instance/InstanceSchemas';
-import {HttpResponse, http} from 'msw';
import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it} from 'vitest';
-const INSTATUS_SUMMARY = {page: {name: 'Status', status: 'UP'}, activeIncidents: [], activeMaintenances: []};
-
describe('discovery fields for self-hosted clients', () => {
let harness: ApiTestHarness;
- async function withSelfHostedStatusPage(statusPageUrl: string): Promise<WellKnownFluxerResponse> {
- const config = getConfig().instance;
- const originalSelfHosted = config.selfHosted;
- config.selfHosted = true;
- try {
- await getInstanceConfigRepository().setAppPublicConfig({branding: {status_page_url: statusPageUrl}});
- return await createBuilderWithoutAuth<WellKnownFluxerResponse>(harness).get('/.well-known/fluxer').execute();
- } finally {
- config.selfHosted = originalSelfHosted;
- }
- }
-
beforeAll(async () => {
harness = await createAuthHarness();
});
@@ -52,33 +35,6 @@ describe('discovery fields for self-hosted clients', () => {
expect(discovery.community).toMatchObject({direct_messages_disabled: true, friends_disabled: true});
});
- it('detects an existing Instatus status page on a self-hosted instance with no extra setting', async () => {
- const statusPageUrl = 'https://93.184.215.14';
- server.use(
- http.get(`${statusPageUrl}/summary.json`, () =>
- HttpResponse.json(INSTATUS_SUMMARY, {headers: {'access-control-allow-origin': '*'}}),
- ),
- );
- const discovery = await withSelfHostedStatusPage(statusPageUrl);
- expect(discovery.app_public.branding).toMatchObject({
- status_page_url: statusPageUrl,
- status_page_instatus: true,
- });
- expect(parseInstanceDiscoveryDocument(discovery).appPublic?.branding.status_page_instatus).toBe(true);
- });
-
- it('tells clients not to read incidents from a status page that is not Instatus', async () => {
- const statusPageUrl = 'https://93.184.215.15';
- server.use(
- http.get(`${statusPageUrl}/summary.json`, () => new HttpResponse('<!doctype html><html></html>', {status: 404})),
- );
- const discovery = await withSelfHostedStatusPage(statusPageUrl);
- expect(discovery.app_public.branding).toMatchObject({
- status_page_url: statusPageUrl,
- status_page_instatus: false,
- });
- });
-
it('fills friends_disabled from the direct message flag for an older server', () => {
const document = parseInstanceDiscoveryDocument({
api_code_version: 1,
diff --git a/fluxer_api/src/api/instance/tests/StatusPageDetector.test.ts b/fluxer_api/src/api/instance/tests/StatusPageDetector.test.ts
deleted file mode 100644
index a2fa18a3b..000000000
--- a/fluxer_api/src/api/instance/tests/StatusPageDetector.test.ts
+++ /dev/null
@@ -1,147 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {Config} from '@app/api/Config';
-import {StatusPageDetector} from '@app/api/instance/StatusPageDetector';
-import {server} from '@app/api/test/msw/server';
-import {createPublicInternetRequestUrlPolicy} from '@pkgs/http_client/src/PublicInternetRequestUrlPolicy';
-import {HttpResponse, http} from 'msw';
-import {beforeEach, describe, expect, it} from 'vitest';
-
-const URL_A = 'https://status.example.com';
-const URL_B = 'https://status.example.org';
-const SUMMARY = {page: {name: 'Status', status: 'UP'}, activeIncidents: [], activeMaintenances: []};
-const ALLOW_ANY_ORIGIN = {'access-control-allow-origin': '*'};
-const MINUTE = 60 * 1000;
-const HOUR = 60 * MINUTE;
-
-type Answer = () => Response;
-
-const instatus: Answer = () => HttpResponse.json(SUMMARY, {headers: ALLOW_ANY_ORIGIN});
-const unavailable: Answer = () => new HttpResponse('busy', {status: 503});
-const notFound: Answer = () => new HttpResponse('not found', {status: 404});
-
-describe('StatusPageDetector', () => {
- let now = 0;
- let detector: StatusPageDetector;
- let requests: Array<{url: string; origin: string | null}>;
-
- function answer(url: string, answers: Array<Answer>): void {
- server.use(
- http.get(`${url}/summary.json`, ({request}) => {
- requests.push({url, origin: request.headers.get('origin')});
- const next = answers.length > 1 ? answers.shift()! : answers[0]!;
- return next();
- }),
- );
- }
-
- function requestsTo(url: string): number {
- return requests.filter((request) => request.url === url).length;
- }
-
- beforeEach(() => {
- now = 1_000_000;
- requests = [];
- detector = new StatusPageDetector({
- now: () => now,
- requestUrlPolicy: createPublicInternetRequestUrlPolicy({lookupHost: async () => ['93.184.215.14']}),
- });
- });
-
- it('detects an Instatus page that allows the web app origin', async () => {
- answer(URL_A, [instatus]);
- await expect(detector.isInstatus(URL_A)).resolves.toBe(true);
- expect(requests).toEqual([{url: URL_A, origin: new URL(Config.endpoints.webApp).origin}]);
- });
-
- it('publishes false for a page that is not Instatus and waits a day before checking it again', async () => {
- answer(URL_A, [notFound]);
- await expect(detector.isInstatus(URL_A)).resolves.toBe(false);
- now += 23 * HOUR;
- await expect(detector.isInstatus(URL_A)).resolves.toBe(false);
- expect(requestsTo(URL_A)).toBe(1);
- now += HOUR;
- await expect(detector.isInstatus(URL_A)).resolves.toBe(false);
- expect(requestsTo(URL_A)).toBe(2);
- });
-
- it('publishes false for HTML and for JSON from another provider', async () => {
- answer(URL_A, [() => new HttpResponse('<!doctype html><html></html>', {status: 200, headers: ALLOW_ANY_ORIGIN})]);
- answer(URL_B, [() => HttpResponse.json({monitors: [], heartbeatList: {}}, {headers: ALLOW_ANY_ORIGIN})]);
- await expect(detector.isInstatus(URL_A)).resolves.toBe(false);
- await expect(detector.isInstatus(URL_B)).resolves.toBe(false);
- });
-
- it('publishes false for an Instatus summary the browser may not read across origins', async () => {
- answer(URL_A, [() => HttpResponse.json(SUMMARY)]);
- answer(URL_B, [
- () => HttpResponse.json(SUMMARY, {headers: {'access-control-allow-origin': 'https://other.example'}}),
- ]);
- await expect(detector.isInstatus(URL_A)).resolves.toBe(false);
- await expect(detector.isInstatus(URL_B)).resolves.toBe(false);
- });
-
- it('retries a transient failure after 1 and then 5 minutes and recovers', async () => {
- answer(URL_A, [unavailable, unavailable, instatus]);
- await expect(detector.isInstatus(URL_A)).resolves.toBe(false);
- now += MINUTE - 1;
- await expect(detector.isInstatus(URL_A)).resolves.toBe(false);
- expect(requestsTo(URL_A)).toBe(1);
- now += 1;
- await expect(detector.isInstatus(URL_A)).resolves.toBe(false);
- expect(requestsTo(URL_A)).toBe(2);
- now += 5 * MINUTE - 1;
- await expect(detector.isInstatus(URL_A)).resolves.toBe(false);
- expect(requestsTo(URL_A)).toBe(2);
- now += 1;
- await expect(detector.isInstatus(URL_A)).resolves.toBe(true);
- expect(requestsTo(URL_A)).toBe(3);
- });
-
- it('treats a timeout status, a rate limit and a network error as transient', async () => {
- answer(URL_A, [
- () => new HttpResponse(null, {status: 408}),
- () => new HttpResponse(null, {status: 429}),
- () => HttpResponse.error(),
- instatus,
- ]);
- await expect(detector.isInstatus(URL_A)).resolves.toBe(false);
- now += MINUTE;
- await expect(detector.isInstatus(URL_A)).resolves.toBe(false);
- now += 5 * MINUTE;
- await expect(detector.isInstatus(URL_A)).resolves.toBe(false);
- now += 15 * MINUTE;
- await expect(detector.isInstatus(URL_A)).resolves.toBe(true);
- expect(requestsTo(URL_A)).toBe(4);
- });
-
- it('keeps a known Instatus page while a later recheck fails', async () => {
- answer(URL_A, [instatus, unavailable]);
- await expect(detector.isInstatus(URL_A)).resolves.toBe(true);
- now += 6 * HOUR;
- await expect(detector.isInstatus(URL_A)).resolves.toBe(true);
- expect(requestsTo(URL_A)).toBe(2);
- });
-
- it('checks a new status page URL straight away and forgets the old verdict', async () => {
- answer(URL_A, [notFound]);
- answer(URL_B, [instatus]);
- await expect(detector.isInstatus(URL_A)).resolves.toBe(false);
- await expect(detector.isInstatus(URL_B)).resolves.toBe(true);
- await expect(detector.isInstatus(URL_A)).resolves.toBe(false);
- expect(requestsTo(URL_A)).toBe(2);
- expect(requestsTo(URL_B)).toBe(1);
- });
-
- it('sends nothing when no status page is set', async () => {
- await expect(detector.isInstatus(null)).resolves.toBe(false);
- expect(requests).toEqual([]);
- });
-
- it('sends nothing to a status page on a private address', async () => {
- const privateDetector = new StatusPageDetector({now: () => now});
- answer('http://10.0.0.5', [instatus]);
- await expect(privateDetector.isInstatus('http://10.0.0.5')).resolves.toBe(false);
- expect(requests).toEqual([]);
- });
-});
diff --git a/fluxer_api/src/api/middleware/tests/UrlBlocklistCache.test.ts b/fluxer_api/src/api/middleware/tests/UrlBlocklistCache.test.ts
deleted file mode 100644
index 529282279..000000000
--- a/fluxer_api/src/api/middleware/tests/UrlBlocklistCache.test.ts
+++ /dev/null
@@ -1,65 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {urlBlocklistCache} from '@app/api/middleware/UrlBlocklistCache';
-import {afterEach, describe, expect, it} from 'vitest';
-
-describe('urlBlocklistCache link matching', () => {
- afterEach(() => {
- urlBlocklistCache.resetForTesting();
- });
-
- it('blocks a masked markdown link whose target a pattern covers', () => {
- urlBlocklistCache.addDomain('*shop*.onrender.com', true);
- expect(urlBlocklistCache.containsBannedLink('[open the store](https://shop-2.onrender.com)')).toBe(true);
- expect(urlBlocklistCache.containsBannedLink('[open the store](<https://www.shop.onrender.com/x>)')).toBe(true);
- expect(urlBlocklistCache.containsBannedLink('[https://docs.onrender.com](https://shop.onrender.com)')).toBe(true);
- });
-
- it('blocks autolinks and bare links', () => {
- urlBlocklistCache.addDomain('*shop*.onrender.com', false);
- expect(urlBlocklistCache.containsBannedLink('<https://myshop.onrender.com/path>')).toBe(true);
- expect(urlBlocklistCache.containsBannedLink('visit myshop.onrender.com today')).toBe(true);
- });
-
- it('normalizes the link target before matching', () => {
- urlBlocklistCache.addDomain('*shop*.onrender.com', false);
- const variants = [
- 'https://user:[email protected]:8443/x',
- 'https://[email protected]',
- 'https://shop.onrender.com./',
- 'https://shop%2Eonrender%2Ecom/',
- 'https://shop。onrender。com/',
- 'https://shop-ü.onrender.com/',
- ];
- for (const text of variants) {
- expect(urlBlocklistCache.containsBannedLink(text), text).toBe(true);
- }
- });
-
- it('leaves the bare suffix and unrelated hosts alone', () => {
- urlBlocklistCache.addDomain('*shop*.onrender.com', true);
- expect(urlBlocklistCache.containsBannedLink('https://onrender.com/docs')).toBe(false);
- expect(urlBlocklistCache.containsBannedLink('[docs](https://docs.onrender.com)')).toBe(false);
- expect(urlBlocklistCache.containsBannedLink('the shop is closed')).toBe(false);
- });
-
- it('covers subdomains of a domain entry only when it is flagged to', () => {
- urlBlocklistCache.addDomain('shop.example.com', true);
- urlBlocklistCache.addDomain('store.example.com', false);
- expect(urlBlocklistCache.containsBannedLink('https://www.shop.example.com')).toBe(true);
- expect(urlBlocklistCache.containsBannedLink('https://store.example.com')).toBe(true);
- expect(urlBlocklistCache.containsBannedLink('https://www.store.example.com')).toBe(false);
- });
-
- it('stops matching after removal', () => {
- urlBlocklistCache.addDomain('*shop*.onrender.com', true);
- urlBlocklistCache.removeDomain('*shop*.onrender.com');
- expect(urlBlocklistCache.containsBannedLink('https://shop.onrender.com')).toBe(false);
- });
-
- it('applies domain rules to a single URL', () => {
- urlBlocklistCache.addDomain('*shop*.onrender.com', false);
- expect(urlBlocklistCache.isUrlOrDomainBanned('https://shop.onrender.com/checkout')).toBe(true);
- expect(urlBlocklistCache.isUrlOrDomainBanned('https://docs.onrender.com/')).toBe(false);
- });
-});
diff --git a/fluxer_api/src/api/oauth/tests/OAuth2AuthorizeRedirectURI.test.ts b/fluxer_api/src/api/oauth/tests/OAuth2AuthorizeRedirectURI.test.ts
deleted file mode 100644
index b56fe6fa1..000000000
--- a/fluxer_api/src/api/oauth/tests/OAuth2AuthorizeRedirectURI.test.ts
+++ /dev/null
@@ -1,52 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {createTestAccount} from '@app/api/auth/tests/AuthTestUtils';
-import {createOAuth2Application} from '@app/api/oauth/tests/OAuthTestUtils';
-import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
-import {HTTP_STATUS} from '@app/api/test/TestConstants';
-import {createBuilder} from '@app/api/test/TestRequestBuilder';
-import {afterAll, beforeAll, beforeEach, describe, it} from 'vitest';
-
-describe('OAuth2 authorize redirect URI validation', () => {
- let harness: ApiTestHarness;
- beforeAll(async () => {
- harness = await createApiTestHarness();
- });
- beforeEach(async () => {
- await harness.reset();
- });
- afterAll(async () => {
- await harness?.shutdown();
- });
- it('verifies that redirect URIs must match exactly (no partial matches)', async () => {
- const appOwner = await createTestAccount(harness);
- const endUser = await createTestAccount(harness);
- const registeredURI = 'https://example.com/callback';
- const app = await createOAuth2Application(harness, appOwner, {
- name: 'Exact Match',
- redirect_uris: [registeredURI],
- });
- const testCases = [
- 'https://example.com/callback/extra',
- 'https://example.com/callback?foo=bar',
- 'https://example.com/callback#fragment',
- 'http://example.com/callback',
- 'https://other.com/callback',
- 'https://example.com:8080/callback',
- 'https://example.com/callback/',
- ];
- for (const invalidURI of testCases) {
- await createBuilder(harness, endUser.token)
- .post('/oauth2/authorize/consent')
- .body({
- response_type: 'code',
- client_id: app.id,
- redirect_uri: invalidURI,
- scope: 'identify',
- state: 'test-state',
- })
- .expect(HTTP_STATUS.BAD_REQUEST)
- .execute();
- }
- });
-});
diff --git a/fluxer_api/src/api/oauth/tests/OAuth2TokenExchange.test.ts b/fluxer_api/src/api/oauth/tests/OAuth2TokenExchange.test.ts
deleted file mode 100644
index bb37fad5b..000000000
--- a/fluxer_api/src/api/oauth/tests/OAuth2TokenExchange.test.ts
+++ /dev/null
@@ -1,120 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- authorizeOAuth2,
- createOAuth2TestSetup,
- exchangeOAuth2AuthorizationCode,
-} from '@app/api/oauth/tests/OAuthTestUtils';
-import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
-import {HTTP_STATUS} from '@app/api/test/TestConstants';
-import {createBuilder} from '@app/api/test/TestRequestBuilder';
-import {beforeEach, describe, expect, test} from 'vitest';
-
-describe('OAuth2 Token Exchange', () => {
- let harness: ApiTestHarness;
- beforeEach(async () => {
- harness = await createApiTestHarness();
- });
- test('should fail without redirect_uri in token exchange', async () => {
- const {endUser, redirectURI, application} = await createOAuth2TestSetup(harness);
- const authCodeResponse = await authorizeOAuth2(harness, endUser.token, {
- client_id: application.id,
- redirect_uri: redirectURI,
- scope: 'identify',
- });
- const formData = new URLSearchParams({
- grant_type: 'authorization_code',
- code: authCodeResponse.code,
- client_id: application.id,
- });
- await createBuilder(harness, '')
- .post('/oauth2/token')
- .header('Content-Type', 'application/x-www-form-urlencoded')
- .header(
- 'Authorization',
- `Basic ${Buffer.from(`${application.id}:${application.client_secret}`).toString('base64')}`,
- )
- .body(formData.toString())
- .expect(HTTP_STATUS.BAD_REQUEST)
- .execute();
- });
- test('should fail with mismatched redirect_uri in token exchange', async () => {
- const {endUser, redirectURI, application} = await createOAuth2TestSetup(harness);
- const authCodeResponse = await authorizeOAuth2(harness, endUser.token, {
- client_id: application.id,
- redirect_uri: redirectURI,
- scope: 'identify',
- });
- const formData = new URLSearchParams({
- grant_type: 'authorization_code',
- code: authCodeResponse.code,
- redirect_uri: 'https://evil.com/callback',
- client_id: application.id,
- });
- await createBuilder(harness, '')
- .post('/oauth2/token')
- .header('Content-Type', 'application/x-www-form-urlencoded')
- .header(
- 'Authorization',
- `Basic ${Buffer.from(`${application.id}:${application.client_secret}`).toString('base64')}`,
- )
- .body(formData.toString())
- .expect(HTTP_STATUS.BAD_REQUEST)
- .execute();
- });
- test('should fail with wrong client_id', async () => {
- const {endUser, redirectURI, application} = await createOAuth2TestSetup(harness);
- const authCodeResponse = await authorizeOAuth2(harness, endUser.token, {
- client_id: application.id,
- redirect_uri: redirectURI,
- scope: 'identify',
- });
- const formData = new URLSearchParams({
- grant_type: 'authorization_code',
- code: authCodeResponse.code,
- redirect_uri: redirectURI,
- client_id: '999999999999999999',
- });
- await createBuilder(harness, '')
- .post('/oauth2/token')
- .header('Content-Type', 'application/x-www-form-urlencoded')
- .header(
- 'Authorization',
- `Basic ${Buffer.from(`999999999999999999:${application.client_secret}`).toString('base64')}`,
- )
- .body(formData.toString())
- .expect(HTTP_STATUS.BAD_REQUEST)
- .execute();
- });
- test('should fail authorization code reuse', async () => {
- const {endUser, redirectURI, application} = await createOAuth2TestSetup(harness);
- const authCodeResponse = await authorizeOAuth2(harness, endUser.token, {
- client_id: application.id,
- redirect_uri: redirectURI,
- scope: 'identify',
- });
- const tokenResponse = await exchangeOAuth2AuthorizationCode(harness, {
- client_id: application.id,
- client_secret: application.client_secret,
- code: authCodeResponse.code,
- redirect_uri: redirectURI,
- });
- expect(tokenResponse.access_token).toBeTruthy();
- const formData = new URLSearchParams({
- grant_type: 'authorization_code',
- code: authCodeResponse.code,
- redirect_uri: redirectURI,
- client_id: application.id,
- });
- await createBuilder(harness, '')
- .post('/oauth2/token')
- .header('Content-Type', 'application/x-www-form-urlencoded')
- .header(
- 'Authorization',
- `Basic ${Buffer.from(`${application.id}:${application.client_secret}`).toString('base64')}`,
- )
- .body(formData.toString())
- .expect(HTTP_STATUS.BAD_REQUEST)
- .execute();
- });
-});
diff --git a/fluxer_api/src/api/utils/tests/UrlHostRules.test.ts b/fluxer_api/src/api/utils/tests/UrlHostRules.test.ts
deleted file mode 100644
index ec7e4855d..000000000
--- a/fluxer_api/src/api/utils/tests/UrlHostRules.test.ts
+++ /dev/null
@@ -1,171 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {parseUrlDomainEntry, UrlHostRuleSet} from '@app/api/utils/UrlHostRules';
-import {describe, expect, it} from 'vitest';
-
-function rules(entries: Array<[string, boolean]>): UrlHostRuleSet {
- const set = new UrlHostRuleSet();
- for (const [value, matchSubdomains] of entries) {
- set.add(value, matchSubdomains);
- }
- return set;
-}
-
-describe('parseUrlDomainEntry', () => {
- it('canonicalizes a plain domain', () => {
- expect(parseUrlDomainEntry(' Shop.Example.COM. ')).toEqual({ok: true, value: 'shop.example.com', pattern: false});
- });
-
- it('stores an internationalized domain in punycode', () => {
- expect(parseUrlDomainEntry('bücher.example')).toEqual({ok: true, value: 'xn--bcher-kva.example', pattern: false});
- });
-
- it('keeps an exact entry for a domain under a shared hosting suffix', () => {
- expect(parseUrlDomainEntry('onrender.com')).toEqual({ok: true, value: 'onrender.com', pattern: false});
- });
-
- it('rejects malformed plain domains', () => {
- for (const value of ['localhost', 'bad_label.example.com', '-lead.example.com', 'a..example.com', 'a b.com']) {
- expect(parseUrlDomainEntry(value).ok).toBe(false);
- }
- });
-
- it('canonicalizes a pattern and collapses repeated wildcards', () => {
- expect(parseUrlDomainEntry('**Shop**.OnRender.com.')).toEqual({
- ok: true,
- value: '*shop*.onrender.com',
- pattern: true,
- });
- });
-
- it('accepts patterns under a private shared hosting suffix', () => {
- expect(parseUrlDomainEntry('*shop*.github.io').ok).toBe(true);
- expect(parseUrlDomainEntry('shop-*.example.co.uk').ok).toBe(true);
- });
-
- it('rejects patterns that are too broad', () => {
- for (const value of [
- '*',
- '*.com',
- '*shop*.com',
- 'shop*.co.uk',
- '*.example.com',
- '*ab*.example.com',
- 'a*b.example.com',
- ]) {
- expect(parseUrlDomainEntry(value).ok).toBe(false);
- }
- });
-
- it('rejects wildcards outside the leftmost label', () => {
- expect(parseUrlDomainEntry('shop.*.example.com').ok).toBe(false);
- expect(parseUrlDomainEntry('*shop*.example*.com').ok).toBe(false);
- });
-
- it('rejects wildcard labels with unsupported characters or too many wildcards', () => {
- expect(parseUrlDomainEntry('*sh?p*.example.com').ok).toBe(false);
- expect(parseUrlDomainEntry('*sh_p*.example.com').ok).toBe(false);
- expect(parseUrlDomainEntry('*a*b*c*d*.example.com').ok).toBe(false);
- });
-
- it('rejects a pattern without a domain', () => {
- expect(parseUrlDomainEntry('*shop*').ok).toBe(false);
- });
-});
-
-describe('UrlHostRuleSet', () => {
- it('matches an exact domain', () => {
- const set = rules([['shop.example.com', false]]);
- expect(set.matches('shop.example.com')).toBe(true);
- expect(set.matches('www.shop.example.com')).toBe(false);
- expect(set.matches('example.com')).toBe(false);
- });
-
- it('matches subdomains only when the entry covers them', () => {
- const set = rules([['shop.example.com', true]]);
- expect(set.matches('shop.example.com')).toBe(true);
- expect(set.matches('a.b.shop.example.com')).toBe(true);
- expect(set.matches('myshop.example.com')).toBe(false);
- });
-
- it('normalizes the checked host', () => {
- const set = rules([['shop.example.com', true]]);
- expect(set.matches('SHOP.Example.com.')).toBe(true);
- expect(set.matches('www.shop。example。com')).toBe(true);
- expect(rules([['xn--bcher-kva.example', false]]).matches('Bücher.example')).toBe(true);
- });
-
- it('matches a pattern against the label left of its suffix', () => {
- const set = rules([['*shop*.onrender.com', false]]);
- expect(set.matches('shop.onrender.com')).toBe(true);
- expect(set.matches('best-shop-2.onrender.com')).toBe(true);
- expect(set.matches('SHOPPING.onrender.com')).toBe(true);
- expect(set.matches('store.onrender.com')).toBe(false);
- });
-
- it('never matches the bare suffix of a pattern', () => {
- const set = rules([['*shop*.onrender.com', true]]);
- expect(set.matches('onrender.com')).toBe(false);
- expect(set.matches('com')).toBe(false);
- expect(set.matches('shop.com')).toBe(false);
- expect(set.matches('shop.onrender.com.evil.example')).toBe(false);
- expect(set.matches('shoponrender.com')).toBe(false);
- });
-
- it('applies anchored pattern segments', () => {
- const set = rules([
- ['shop-*.example.com', false],
- ['*-store.example.org', false],
- ['a*b*c.example.net', false],
- ]);
- expect(set.matches('shop-1.example.com')).toBe(true);
- expect(set.matches('myshop-1.example.com')).toBe(false);
- expect(set.matches('big-store.example.org')).toBe(true);
- expect(set.matches('big-store2.example.org')).toBe(false);
- expect(set.matches('axxbyyc.example.net')).toBe(true);
- expect(set.matches('abc.example.net')).toBe(true);
- expect(set.matches('acb.example.net')).toBe(false);
- });
-
- it('extends a pattern to deeper subdomains only when the entry covers them', () => {
- const exact = rules([['*shop*.onrender.com', false]]);
- const covering = rules([['*shop*.onrender.com', true]]);
- expect(exact.matches('www.shop.onrender.com')).toBe(false);
- expect(covering.matches('www.shop.onrender.com')).toBe(true);
- expect(covering.matches('shop.www.onrender.com')).toBe(false);
- });
-
- it('matches internationalized labels through their punycode form', () => {
- const set = rules([['*shop*.onrender.com', false]]);
- expect(set.matches('shop-ü.onrender.com')).toBe(true);
- });
-
- it('removes domains and patterns', () => {
- const set = rules([
- ['shop.example.com', true],
- ['*shop*.onrender.com', true],
- ['*store*.onrender.com', true],
- ]);
- set.remove('SHOP.example.com');
- set.remove('**shop*.onrender.com');
- expect(set.matches('shop.example.com')).toBe(false);
- expect(set.matches('shop.onrender.com')).toBe(false);
- expect(set.matches('store.onrender.com')).toBe(true);
- expect(set.size).toEqual({domains: 0, patterns: 1});
- });
-
- it('replaces a pattern when it is added again', () => {
- const set = rules([
- ['*shop*.onrender.com', false],
- ['*shop*.onrender.com', true],
- ]);
- expect(set.size).toEqual({domains: 0, patterns: 1});
- expect(set.matches('www.shop.onrender.com')).toBe(true);
- });
-
- it('ignores invalid stored patterns', () => {
- const set = rules([['*.com', true]]);
- expect(set.size).toEqual({domains: 0, patterns: 0});
- expect(set.matches('anything.com')).toBe(false);
- });
-});
diff --git a/fluxer_api/src/api/utils/tests/UrlNormalizer.test.ts b/fluxer_api/src/api/utils/tests/UrlNormalizer.test.ts
deleted file mode 100644
index 9bd824378..000000000
--- a/fluxer_api/src/api/utils/tests/UrlNormalizer.test.ts
+++ /dev/null
@@ -1,234 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {canonicalizeUrl, extractLinkHosts, extractUrlCandidates, normalizeHostname} from '@app/api/utils/UrlNormalizer';
-import {describe, expect, it} from 'vitest';
-
-describe('canonicalizeUrl', () => {
- it('lowercases scheme and host', () => {
- expect(canonicalizeUrl('HTTPS://EXAMPLE.COM/Path')).toBe('https://example.com/path');
- });
- it('adds trailing slash on bare host', () => {
- const result = canonicalizeUrl('https://example.com');
- expect(result).toBe('https://example.com/');
- });
- it('preserves path', () => {
- expect(canonicalizeUrl('https://example.com/foo/bar')).toBe('https://example.com/foo/bar');
- });
- it('strips ref_src and ref_url tracking params', () => {
- expect(canonicalizeUrl('https://example.com/?ref_src=twsrc&ref_url=https://t.co')).toBe('https://example.com/');
- });
- it('strips multiple tracking params but keeps non-tracking params', () => {
- expect(canonicalizeUrl('https://example.com/?page=1&utm_source=tw&fbclid=abc&sort=asc')).toBe(
- 'https://example.com/?page=1&sort=asc',
- );
- });
- it('sorts remaining query params alphabetically', () => {
- expect(canonicalizeUrl('https://example.com/?z=1&a=2&m=3')).toBe('https://example.com/?a=2&m=3&z=1');
- });
- it('strips fragment', () => {
- expect(canonicalizeUrl('https://example.com/page#section')).toBe('https://example.com/page');
- });
- it('strips default port 80 for http', () => {
- expect(canonicalizeUrl('http://example.com:80/path')).toBe('http://example.com/path');
- });
- it('strips default port 443 for https', () => {
- expect(canonicalizeUrl('https://example.com:443/path')).toBe('https://example.com/path');
- });
- it('keeps non-default ports', () => {
- const result = canonicalizeUrl('https://example.com:8443/path');
- expect(result).toContain(':8443');
- });
- it('converts IDN to punycode', () => {
- const result = canonicalizeUrl('https://xn--nxasmq6b.example.com/');
- expect(result).not.toBeNull();
- expect(result).toContain('xn--');
- });
- it('rejects mailto scheme', () => {
- expect(canonicalizeUrl('mailto:[email protected]')).toBeNull();
- });
- it('rejects ftp scheme', () => {
- expect(canonicalizeUrl('ftp://example.com/file')).toBeNull();
- });
- it('rejects invalid URLs', () => {
- expect(canonicalizeUrl('not-a-url')).toBeNull();
- });
- it('rejects empty string', () => {
- expect(canonicalizeUrl('')).toBeNull();
- });
- it('rejects whitespace-only string', () => {
- expect(canonicalizeUrl(' ')).toBeNull();
- });
- it('rejects URLs with embedded whitespace', () => {
- expect(canonicalizeUrl('https://example .com/')).toBeNull();
- });
- it('rejects URLs with null byte control characters', () => {
- expect(canonicalizeUrl('https://example.com/\x00')).toBeNull();
- });
- it('rejects URLs with embedded newlines', () => {
- expect(canonicalizeUrl('https://exam\nple.com/')).toBeNull();
- });
- it('rejects URLs with embedded tabs', () => {
- expect(canonicalizeUrl('https://exa\tmple.com/')).toBeNull();
- });
- it('trims leading/trailing whitespace before parsing', () => {
- expect(canonicalizeUrl(' https://example.com/ ')).toBe('https://example.com/');
- });
-});
-
-describe('extractUrlCandidates', () => {
- it('extracts https:// URL from text', () => {
- const result = extractUrlCandidates('visit https://example.com/page for info');
- expect(result).toHaveLength(1);
- expect(result[0]).toBe('https://example.com/page');
- });
- it('extracts http:// URL from text', () => {
- const result = extractUrlCandidates('see http://example.com/page');
- expect(result).toHaveLength(1);
- expect(result[0]).toBe('http://example.com/page');
- });
- it('extracts bare domain.tld/path URLs and adds http scheme', () => {
- const result = extractUrlCandidates('check out example.com/page');
- expect(result).toHaveLength(1);
- expect(result[0]).toBe('http://example.com/page');
- });
- it('handles URLs in parentheses', () => {
- const result = extractUrlCandidates('(https://example.com/page)');
- expect(result).toHaveLength(1);
- expect(result[0]).toBe('https://example.com/page');
- });
- it('handles URLs in quotes', () => {
- const result = extractUrlCandidates('"https://example.com/page"');
- expect(result).toHaveLength(1);
- expect(result[0]).toBe('https://example.com/page');
- });
- it('strips trailing punctuation', () => {
- const result = extractUrlCandidates('visit https://example.com/page.');
- expect(result).toHaveLength(1);
- expect(result[0]).toBe('https://example.com/page');
- });
- it('does not match full email addresses as URLs', () => {
- const result = extractUrlCandidates('contact [email protected]');
- for (const url of result) {
- expect(url).not.toContain('@');
- }
- });
- it('extracts multiple URLs from one string', () => {
- const result = extractUrlCandidates('see https://example.com and https://other.org/page for details');
- expect(result).toHaveLength(2);
- });
- it('returns empty array for empty string', () => {
- expect(extractUrlCandidates('')).toEqual([]);
- });
- it('returns empty array for null-ish input', () => {
- expect(extractUrlCandidates(null)).toEqual([]);
- expect(extractUrlCandidates(undefined)).toEqual([]);
- });
- it('returns empty array for text with no URLs', () => {
- expect(extractUrlCandidates('hello world no links here')).toEqual([]);
- });
-});
-
-describe('normalizeHostname', () => {
- it('lowercases and strips trailing dots', () => {
- expect(normalizeHostname('Shop.Example.COM..')).toBe('shop.example.com');
- });
- it('converts internationalized names to punycode', () => {
- expect(normalizeHostname('bücher.example')).toBe('xn--bcher-kva.example');
- });
- it('maps ideographic full stops to dots', () => {
- expect(normalizeHostname('shop\u3002example\u3002com')).toBe('shop.example.com');
- });
- it('rejects empty and invalid input', () => {
- expect(normalizeHostname(' ')).toBeNull();
- expect(normalizeHostname('.')).toBeNull();
- expect(normalizeHostname('a b.com')).toBeNull();
- });
-});
-
-describe('extractLinkHosts', () => {
- it('drops the closing parenthesis of a masked markdown link', () => {
- expect(extractLinkHosts('[open the shop](https://shop.example.com)')).toEqual(['shop.example.com']);
- });
- it('drops brackets and parentheses around nested links', () => {
- expect(extractLinkHosts('[[x]](https://shop.example.com)(more)')).toEqual(['shop.example.com']);
- });
- it('reads angle-bracket autolinks', () => {
- expect(extractLinkHosts('<https://Shop.Example.com/path>')).toEqual(['shop.example.com']);
- });
- it('ignores userinfo and ports', () => {
- expect(extractLinkHosts('https://user:[email protected]:8443/x')).toEqual(['shop.example.com']);
- expect(extractLinkHosts('[x](https://[email protected])')).toEqual(['shop.example.com']);
- });
- it('strips trailing dots and punctuation', () => {
- expect(extractLinkHosts('see https://shop.example.com./ and https://other.example.org, ok')).toEqual([
- 'shop.example.com',
- 'other.example.org',
- ]);
- });
- it('decodes percent-encoded hosts the way a browser does', () => {
- expect(extractLinkHosts('https://shop%2Eexample%2Ecom/')).toEqual(['shop.example.com']);
- });
- it('returns internationalized hosts in punycode', () => {
- expect(extractLinkHosts('https://bücher.example/')).toEqual(['xn--bcher-kva.example']);
- });
- it('matches the scheme case-insensitively', () => {
- expect(extractLinkHosts('HTTPS://SHOP.EXAMPLE.COM')).toEqual(['shop.example.com']);
- });
- it('stops the host at a backslash', () => {
- expect(extractLinkHosts('https://shop.example.com\\path')).toEqual(['shop.example.com']);
- });
- it('deduplicates hosts', () => {
- expect(extractLinkHosts('https://a.example.com https://A.example.com/x')).toEqual(['a.example.com']);
- });
- it('returns an empty array without links', () => {
- expect(extractLinkHosts('shop.example.com')).toEqual([]);
- expect(extractLinkHosts(null)).toEqual([]);
- });
-});
-
-describe('canonicalizeUrl character boundaries', () => {
- it.each([
- {name: 'start of heading', input: 'https://example.com/a\x01z', expected: null},
- {name: 'backspace', input: 'https://example.com/a\x08z', expected: null},
- {name: 'form feed', input: 'https://example.com/a\x0cz', expected: null},
- {name: 'last C0 control', input: 'https://example.com/a\x1fz', expected: null},
- {name: 'space after C0 range', input: 'https://example.com/a z', expected: null},
- {name: 'delete character', input: 'https://example.com/a\x7fz', expected: 'https://example.com/a%7fz'},
- {name: 'next line C1 character', input: 'https://example.com/a\x85z', expected: 'https://example.com/a%c2%85z'},
- {name: 'nonbreaking space', input: 'https://example.com/a\u00a0z', expected: null},
- {name: 'zero width space', input: 'https://example.com/a\u200bz', expected: 'https://example.com/a%e2%80%8bz'},
- {name: 'line separator', input: 'https://example.com/a\u2028z', expected: null},
- {name: 'paragraph separator', input: 'https://example.com/a\u2029z', expected: null},
- {name: 'byte order mark', input: 'https://example.com/a\ufeffz', expected: null},
- {
- name: 'outer Unicode whitespace',
- input: '\u00a0\ufeffHTTPS://Example.com/Path\u00a0\ufeff',
- expected: 'https://example.com/path',
- },
- {
- name: 'encoded controls and space',
- input: 'https://example.com/%00%1F%20',
- expected: 'https://example.com/%00%1f%20',
- },
- {name: 'leading null control', input: '\x00https://example.com/path', expected: null},
- {name: 'trailing unit separator', input: 'https://example.com/path\x1f', expected: null},
- {
- name: 'unpaired high surrogate',
- input: 'https://example.com/a\ud800z',
- expected: 'https://example.com/a%ef%bf%bdz',
- },
- {
- name: 'surrogate pair',
- input: 'https://example.com/a\ud83d\ude00z',
- expected: 'https://example.com/a%f0%9f%98%80z',
- },
- {name: 'query control', input: 'https://example.com/?q=a\x1fz', expected: null},
- {
- name: 'query zero width space',
- input: 'https://example.com/?q=a\u200bz',
- expected: 'https://example.com/?q=a%e2%80%8bz',
- },
- ])('$name', ({input, expected}) => {
- expect(canonicalizeUrl(input)).toBe(expected);
- });
-});
diff --git a/fluxer_api/src/api/voice/VoiceNodeService.ts b/fluxer_api/src/api/voice/VoiceNodeService.ts
index 5809cec76..97af9d66c 100644
--- a/fluxer_api/src/api/voice/VoiceNodeService.ts
+++ b/fluxer_api/src/api/voice/VoiceNodeService.ts
@@ -48,7 +48,7 @@ export function voiceJoinCommand(webApp: string, baseDomain: string, token: stri
return `curl -fsSL https://fluxer.dev/install.sh | sh -s -- voice ${instance} ${token}`;
}
-export const VOICE_NODE_AUDIENCE = 'fluxer-voice-node';
+const VOICE_NODE_AUDIENCE = 'fluxer-voice-node';
export const VOICE_NODE_PATH = '/voice/node';
const CLAIM_STALE_MS = 2 * 60 * 1000;
@@ -127,7 +127,7 @@ function signatureMatches(parts: NodeTokenParts, secret: string): boolean {
return expected.length === parts.signature.length && timingSafeEqual(expected, parts.signature);
}
-export type EndpointVerifier = (
+type EndpointVerifier = (
endpoint: string,
keys: {apiKey: string; apiSecret: string},
internalEndpoint: string | null,
@@ -153,12 +153,6 @@ const verifyNodeEndpoint: EndpointVerifier = async (endpoint, keys, internalEndp
await checkLiveKitKeys(base, keys, options);
};
-let endpointVerifier: EndpointVerifier = verifyNodeEndpoint;
-
-export function setVoiceNodeEndpointVerifierForTesting(verifier: EndpointVerifier | null): void {
- endpointVerifier = verifier ?? verifyNodeEndpoint;
-}
-
function asApiError(error: unknown): Error {
if (!(error instanceof VoiceEndpointError)) return error as Error;
switch (error.reason) {
@@ -254,7 +248,7 @@ export class VoiceNodeService {
}
if (servers.some((server) => server.apiKey === body.api_key)) throw new VoiceServerApiKeyInUseError();
const endpoint = this.checkEndpoint(body.endpoint, row.hostname);
- await endpointVerifier(
+ await verifyNodeEndpoint(
endpoint,
{apiKey: body.api_key, apiSecret: body.api_secret},
row.internal_endpoint,
@@ -371,7 +365,7 @@ export class VoiceNodeService {
const updated: VoiceServerRecord = {...server, updatedAt: new Date()};
if (body.endpoint !== undefined && body.endpoint !== server.endpoint) {
updated.endpoint = this.checkEndpoint(body.endpoint, server.pinnedHostname);
- await endpointVerifier(updated.endpoint, server, server.internalEndpoint, true).catch((error: unknown) => {
+ await verifyNodeEndpoint(updated.endpoint, server, server.internalEndpoint, true).catch((error: unknown) => {
throw asApiError(error);
});
}
diff --git a/fluxer_api/src/api/voice/VoiceServerEndpoints.ts b/fluxer_api/src/api/voice/VoiceServerEndpoints.ts
index 5ded297aa..ed9234285 100644
--- a/fluxer_api/src/api/voice/VoiceServerEndpoints.ts
+++ b/fluxer_api/src/api/voice/VoiceServerEndpoints.ts
@@ -67,11 +67,7 @@ export class VoiceEndpointError extends Error {
type Resolve = (host: string) => Promise<Array<string>>;
-let resolveHost: Resolve = async (host) => (await lookup(host, {all: true, verbatim: true})).map((r) => r.address);
-
-export function setVoiceEndpointResolverForTesting(resolver: Resolve | null): void {
- resolveHost = resolver ?? (async (host) => (await lookup(host, {all: true, verbatim: true})).map((r) => r.address));
-}
+const resolveHost: Resolve = async (host) => (await lookup(host, {all: true, verbatim: true})).map((r) => r.address);
function bareHost(url: URL): string {
return url.hostname.replace(/^\[|\]$/g, '');
@@ -96,7 +92,7 @@ export function parseNodeEndpoint(endpoint: string): URL {
return url;
}
-export async function resolveCheckedAddress(url: URL, allowPrivate: boolean): Promise<string> {
+async function resolveCheckedAddress(url: URL, allowPrivate: boolean): Promise<string> {
const host = bareHost(url);
const addresses = isIP(host) ? [host] : await resolveHost(host).catch(() => []);
if (addresses.length === 0) {
diff --git a/fluxer_api/src/api/voice/tests/VoiceAvailabilityService.test.ts b/fluxer_api/src/api/voice/tests/VoiceAvailabilityService.test.ts
index e1cf75169..974ecfa8d 100644
--- a/fluxer_api/src/api/voice/tests/VoiceAvailabilityService.test.ts
+++ b/fluxer_api/src/api/voice/tests/VoiceAvailabilityService.test.ts
@@ -441,76 +441,6 @@ describe('VoiceAvailabilityService', () => {
});
});
describe('selectServer', () => {
- const context: VoiceAccessContext = {requestingUserId: createUserID(123n)};
- const downOnly = (ids: Array<string>) => ({
- get: (server: {serverId: string}) => ({
- status: ids.includes(server.serverId) ? ('down' as const) : ('up' as const),
- checkedAt: null,
- error: null,
- }),
- });
- it('sends new calls past draining and down servers', async () => {
- const servers = [
- createServer({serverId: 'server-1', apiKey: 'k1', draining: true}),
- createServer({serverId: 'server-2', apiKey: 'k2'}),
- createServer({serverId: 'server-3', apiKey: 'k3'}),
- ];
- const topology = await createTopology([createRegion()], new Map([['us-default', servers]]));
- service = new VoiceAvailabilityService(topology, null, downOnly(['server-2']));
- for (let i = 0; i < 4; i++) {
- expect(service.selectServer('us-default', context)?.serverId).toBe('server-3');
- }
- expect(service.isServerAccessible(servers[0]!, context)).toBe(true);
- expect(service.isServerDown(servers[1]!)).toBe(true);
- });
- it('still places calls when every server is down or draining', async () => {
- const servers = [
- createServer({serverId: 'server-1', apiKey: 'k1', draining: true}),
- createServer({serverId: 'server-2', apiKey: 'k2'}),
- ];
- const topology = await createTopology([createRegion()], new Map([['us-default', servers]]));
- service = new VoiceAvailabilityService(topology, null, downOnly(['server-2']));
- expect(service.selectServer('us-default', context)?.serverId).toBe('server-2');
- service = new VoiceAvailabilityService(topology, null, downOnly(['server-1', 'server-2']));
- expect(service.selectServer('us-default', context)?.serverId).toBe('server-2');
- const drainingOnly = await createTopology(
- [createRegion({id: 'eu-draining', isDefault: false})],
- new Map([
- [
- 'eu-draining',
- [createServer({regionId: 'eu-draining', serverId: 'server-9', apiKey: 'k9', draining: true})],
- ],
- ]),
- );
- service = new VoiceAvailabilityService(drainingOnly);
- expect(service.selectServer('eu-draining', context)?.serverId).toBe('server-9');
- });
- it('moves a call to another region when every server in its region is down', async () => {
- const fallbackRegion = createRegion({id: 'eu-fallback', isDefault: false});
- const topology = await createTopology(
- [createRegion(), fallbackRegion],
- new Map([
- ['us-default', [createServer({serverId: 'default-server-1', apiKey: 'k1'})]],
- ['eu-fallback', [createServer({regionId: 'eu-fallback', serverId: 'eu-server-1', apiKey: 'k2'})]],
- ]),
- );
- service = new VoiceAvailabilityService(topology, null, downOnly(['default-server-1']));
- const regions = service.getAvailableRegions(context).filter((region) => region.isAccessible);
- expect(service.selectServerOrFallback('us-default', context, regions)).toMatchObject({
- regionId: 'eu-fallback',
- server: {serverId: 'eu-server-1'},
- });
- service = new VoiceAvailabilityService(topology, null, downOnly(['default-server-1', 'eu-server-1']));
- expect(service.selectServerOrFallback('us-default', context, regions)).toMatchObject({
- regionId: 'us-default',
- server: {serverId: 'default-server-1'},
- });
- service = new VoiceAvailabilityService(topology, null, downOnly([]));
- expect(service.selectServerOrFallback('us-default', context, regions)).toMatchObject({
- regionId: 'us-default',
- server: {serverId: 'default-server-1'},
- });
- });
it('returns server from specified region', async () => {
const region = createRegion();
const server = createServer();
diff --git a/fluxer_api/src/api/voice/tests/VoiceDataInitializer.test.ts b/fluxer_api/src/api/voice/tests/VoiceDataInitializer.test.ts
deleted file mode 100644
index 998cb426a..000000000
--- a/fluxer_api/src/api/voice/tests/VoiceDataInitializer.test.ts
+++ /dev/null
@@ -1,115 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {Config} from '@app/api/Config';
-import {resolveLivekitEndpoint, VoiceDataInitializer} from '@app/api/voice/VoiceDataInitializer';
-import type {VoiceServerRecord} from '@app/api/voice/VoiceModel';
-import {VoiceRepository} from '@app/api/voice/VoiceRepository';
-import {afterEach, beforeEach, describe, expect, it} from 'vitest';
-
-const BUNDLED_KEY = 'bundled-key';
-const BUNDLED_SECRET = 's'.repeat(64);
-
-function joinedServer(overrides: Partial<VoiceServerRecord> = {}): VoiceServerRecord {
- return {
- regionId: 'default',
- serverId: 'default-server-1',
- endpoint: 'wss://203.0.113.7/livekit-default-server-1',
- apiKey: 'joined-key',
- apiSecret: 'j'.repeat(64),
- latitude: null,
- longitude: null,
- isActive: true,
- softConnectionLimit: null,
- notes: null,
- internalEndpoint: null,
- pinnedHostname: null,
- pinnedSoftLimit: false,
- draining: false,
- restrictions: {
- vipOnly: false,
- requiredGuildFeatures: new Set(),
- allowedGuildIds: new Set(),
- allowedUserIds: new Set(),
- },
- createdAt: new Date(),
- updatedAt: new Date(),
- ...overrides,
- };
-}
-
-describe('VoiceDataInitializer', () => {
- let before: typeof Config.voice;
-
- beforeEach(() => {
- before = {...Config.voice};
- Config.voice.enabled = true;
- Config.voice.apiKey = BUNDLED_KEY;
- Config.voice.apiSecret = BUNDLED_SECRET;
- Config.voice.defaultRegion = {id: 'default', name: 'Default', emoji: ':earth_africa:', latitude: 0, longitude: 0};
- Config.voice.bundled = true;
- });
-
- afterEach(() => {
- Object.assign(Config.voice, before);
- });
-
- it('seeds the default region and the bundled server', async () => {
- await new VoiceDataInitializer().initialize();
- const repository = new VoiceRepository();
- expect(await repository.getRegion('default')).toMatchObject({id: 'default', isDefault: true});
- expect(await repository.getServer('default', 'default-server-1')).toMatchObject({
- apiKey: BUNDLED_KEY,
- endpoint: resolveLivekitEndpoint(Config.voice.url, Config.endpoints.apiPublic),
- });
- });
-
- it('seeds only the default region when the bundled server is off', async () => {
- Config.voice.bundled = false;
- await new VoiceDataInitializer().initialize();
- const repository = new VoiceRepository();
- expect(await repository.getRegion('default')).toMatchObject({id: 'default', isDefault: true});
- expect(await repository.listServers('default')).toEqual([]);
- });
-
- it('seeds the region without LiveKit keys when the bundled server is off', async () => {
- Config.voice.bundled = false;
- Config.voice.apiKey = undefined;
- Config.voice.apiSecret = undefined;
- await new VoiceDataInitializer().initialize();
- expect(await new VoiceRepository().getRegion('default')).not.toBeNull();
- });
-
- it('removes the bundled server once the bundled LiveKit is turned off', async () => {
- await new VoiceDataInitializer().initialize();
- Config.voice.bundled = false;
- await new VoiceDataInitializer().initialize();
- const repository = new VoiceRepository();
- expect(await repository.getServer('default', 'default-server-1')).toBeNull();
- expect(await repository.getRegion('default')).not.toBeNull();
- });
-
- it('leaves a joined server with the bundled ID unchanged', async () => {
- await new VoiceDataInitializer().initialize();
- const repository = new VoiceRepository();
- const joined = joinedServer();
- await repository.upsertServer(joined);
- await new VoiceDataInitializer().initialize();
- expect(await repository.getServer('default', 'default-server-1')).toMatchObject({
- endpoint: joined.endpoint,
- apiKey: joined.apiKey,
- apiSecret: joined.apiSecret,
- });
- Config.voice.bundled = false;
- await new VoiceDataInitializer().initialize();
- expect(await repository.getServer('default', 'default-server-1')).toMatchObject({apiKey: joined.apiKey});
- });
-
- it('syncs new LiveKit keys onto the bundled server', async () => {
- await new VoiceDataInitializer().initialize();
- Config.voice.apiKey = 'rotated-key';
- await new VoiceDataInitializer().initialize();
- expect(await new VoiceRepository().getServer('default', 'default-server-1')).toMatchObject({
- apiKey: 'rotated-key',
- });
- });
-});
diff --git a/fluxer_api/src/api/voice/tests/VoiceJoin.test.ts b/fluxer_api/src/api/voice/tests/VoiceJoin.test.ts
deleted file mode 100644
index 0952739ba..000000000
--- a/fluxer_api/src/api/voice/tests/VoiceJoin.test.ts
+++ /dev/null
@@ -1,504 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {createHash, createHmac} from 'node:crypto';
-import {createAdminWithAcls} from '@app/api/admin/tests/AdminTestUtils';
-import type {TestAccount} from '@app/api/auth/tests/AuthTestUtils';
-import {Config} from '@app/api/Config';
-import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
-import {server} from '@app/api/test/msw/server';
-import {HTTP_STATUS} from '@app/api/test/TestConstants';
-import {createBuilder, createBuilderWithoutAuth} from '@app/api/test/TestRequestBuilder';
-import {VoiceJoinTokenRepository} from '@app/api/voice/VoiceJoinTokenRepository';
-import {
- hashJoinSecret,
- setVoiceNodeEndpointVerifierForTesting,
- VOICE_NODE_AUDIENCE,
- VOICE_NODE_PATH,
- voiceJoinCommand,
-} from '@app/api/voice/VoiceNodeService';
-import {VoiceRepository} from '@app/api/voice/VoiceRepository';
-import {setVoiceEndpointResolverForTesting, VoiceEndpointError} from '@app/api/voice/VoiceServerEndpoints';
-import {AdminACLs} from '@fluxer/constants/src/AdminACLs';
-import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
-import type {
- CreateVoiceJoinTokenResponse,
- ListVoiceJoinTokensResponse,
-} from '@fluxer/schema/src/domains/admin/AdminVoiceSchemas';
-import type {
- VoiceJoinPreviewResponse,
- VoiceJoinResponse,
- VoiceNodeResponse,
-} from '@fluxer/schema/src/domains/voice/VoiceNodeSchemas';
-import {AccessToken} from 'livekit-server-sdk';
-import {HttpResponse, http} from 'msw';
-import {afterEach, beforeEach, describe, expect, test} from 'vitest';
-
-const SECRET = 'a'.repeat(64);
-
-function joinBody(overrides: Record<string, unknown> = {}) {
- return {
- endpoint: 'wss://203.0.113.7/livekit-fra-server-1',
- api_key: 'fluxer-fra-server-1',
- api_secret: SECRET,
- ...overrides,
- };
-}
-
-function nodeJwt(claims: Record<string, unknown>, secret = SECRET): string {
- const encode = (value: unknown) => Buffer.from(JSON.stringify(value)).toString('base64url');
- const input = `${encode({alg: 'HS256', typ: 'JWT'})}.${encode(claims)}`;
- return `Bearer ${input}.${createHmac('sha256', secret).update(input).digest('base64url')}`;
-}
-
-function nodeClaims(method: string, body: string, overrides: Record<string, unknown> = {}) {
- return {
- iss: 'fluxer-fra-server-1',
- aud: VOICE_NODE_AUDIENCE,
- method,
- path: VOICE_NODE_PATH,
- exp: Math.floor(Date.now() / 1000) + 60,
- sha256: body === '' ? '' : createHash('sha256').update(body).digest('base64'),
- ...overrides,
- };
-}
-
-describe('voice join tokens and node routes', () => {
- let harness: ApiTestHarness;
- let admin: TestAccount;
- let verified: Array<string>;
-
- async function createRegion(id: string) {
- await createBuilder(harness, admin.token)
- .post('/admin/voice/regions')
- .body({id, name: `Region ${id}`, emoji: ':earth_africa:', latitude: 50, longitude: 8})
- .execute();
- }
-
- async function createToken(body: Record<string, unknown> = {}) {
- return createBuilder<CreateVoiceJoinTokenResponse>(harness, admin.token)
- .post('/admin/voice/join-tokens')
- .body(body)
- .execute();
- }
-
- async function join(token: string, body = joinBody(), status: number = HTTP_STATUS.OK, code?: string) {
- return createBuilder<VoiceJoinResponse>(harness, `VoiceJoin ${token}`)
- .post('/voice/join')
- .body(body)
- .expect(status, code)
- .execute();
- }
-
- beforeEach(async () => {
- harness = await createApiTestHarness();
- admin = await createAdminWithAcls(harness, [
- AdminACLs.VOICE_REGION_CREATE,
- AdminACLs.VOICE_REGION_LIST,
- AdminACLs.VOICE_SERVER_CREATE,
- AdminACLs.VOICE_SERVER_LIST,
- AdminACLs.VOICE_SERVER_UPDATE,
- AdminACLs.VOICE_SERVER_DELETE,
- AdminACLs.VOICE_JOIN_TOKEN_CREATE,
- AdminACLs.VOICE_JOIN_TOKEN_LIST,
- AdminACLs.VOICE_JOIN_TOKEN_REVOKE,
- ]);
- verified = [];
- setVoiceNodeEndpointVerifierForTesting(async (endpoint) => {
- verified.push(endpoint);
- });
- await createRegion('fra');
- });
-
- afterEach(async () => {
- setVoiceNodeEndpointVerifierForTesting(null);
- await harness?.shutdown();
- });
-
- test('creates a token that previews without being used and joins once', async () => {
- const created = await createToken({region_id: 'fra'});
- expect(created.token).toMatch(/^fvj_\d+_[A-Za-z0-9_-]{43}$/);
- expect(created.command).toContain(`voice `);
- expect(created.command).toContain(created.token);
- const preview = await createBuilder<VoiceJoinPreviewResponse>(harness, `VoiceJoin ${created.token}`)
- .post('/voice/join/preview')
- .body({public_ipv4: '203.0.113.7'})
- .execute();
- expect(preview.region.id).toBe('fra');
- expect(preview.region.source).toBe('token');
- expect(preview.server_id).toBe('fra-server-1');
- expect(preview.server_id_pinned).toBe(false);
- expect(preview.webhook_url).toMatch(/\/webhooks\/livekit$/);
- const joined = await join(created.token);
- expect(joined).toMatchObject({server_id: 'fra-server-1', region_id: 'fra'});
- expect(verified).toEqual(['wss://203.0.113.7/livekit-fra-server-1']);
- const server = await new VoiceRepository().getServer('fra', 'fra-server-1');
- expect(server).toMatchObject({apiKey: 'fluxer-fra-server-1', isActive: true, draining: false});
- await join(
- created.token,
- joinBody({api_key: 'other'}),
- HTTP_STATUS.UNAUTHORIZED,
- APIErrorCodes.VOICE_JOIN_TOKEN_INVALID,
- );
- const list = await createBuilder<ListVoiceJoinTokensResponse>(harness, admin.token)
- .get('/admin/voice/join-tokens')
- .execute();
- expect(list.tokens[0]).toMatchObject({token_id: created.token_id, status: 'used', used_server_id: 'fra-server-1'});
- expect(JSON.stringify(list)).not.toContain(created.token);
- });
-
- test('keeps the bundled server ID for the bundled LiveKit even after it is deleted', async () => {
- const before = {defaultRegion: Config.voice.defaultRegion, bundled: Config.voice.bundled};
- Config.voice.defaultRegion = {id: 'fra', name: 'Region fra', emoji: ':earth_africa:', latitude: 50, longitude: 8};
- Config.voice.bundled = true;
- try {
- const created = await createToken({region_id: 'fra'});
- const preview = await createBuilder<VoiceJoinPreviewResponse>(harness, `VoiceJoin ${created.token}`)
- .post('/voice/join/preview')
- .body({public_ipv4: '203.0.113.7'})
- .execute();
- expect(preview.server_id).toBe('fra-server-2');
- await join(
- created.token,
- joinBody({server_id: 'fra-server-1'}),
- HTTP_STATUS.CONFLICT,
- APIErrorCodes.VOICE_SERVER_ID_IN_USE,
- );
- const joined = await join(created.token);
- expect(joined).toMatchObject({server_id: 'fra-server-2', region_id: 'fra'});
- expect(await new VoiceRepository().getServer('fra', 'fra-server-1')).toBeNull();
- await createBuilder(harness, admin.token)
- .post('/admin/voice/join-tokens')
- .body({region_id: 'fra', server_id: 'fra-server-1'})
- .expect(HTTP_STATUS.CONFLICT, APIErrorCodes.VOICE_SERVER_ID_IN_USE)
- .execute();
- Config.voice.bundled = false;
- const unbundled = await createToken({region_id: 'fra', server_id: 'fra-server-1'});
- expect(await join(unbundled.token, joinBody({api_key: 'joined-fra-1'}))).toMatchObject({
- server_id: 'fra-server-1',
- });
- } finally {
- Config.voice.defaultRegion = before.defaultRegion;
- Config.voice.bundled = before.bundled;
- }
- });
-
- test('rejects revoked, expired, malformed and misplaced tokens', async () => {
- const revoked = await createToken();
- await createBuilder(harness, admin.token).delete(`/admin/voice/join-tokens/${revoked.token_id}`).execute();
- await join(revoked.token, joinBody(), HTTP_STATUS.UNAUTHORIZED, APIErrorCodes.VOICE_JOIN_TOKEN_INVALID);
- const secret = 'b'.repeat(43);
- await new VoiceJoinTokenRepository().create({
- token_id: 42n,
- secret_hash: hashJoinSecret(secret),
- created_by: 1n,
- created_at: new Date(Date.now() - 7200_000),
- expires_at: new Date(Date.now() - 3600_000),
- claim_id: null,
- claimed_at: null,
- used_at: null,
- used_by_ip: null,
- used_server_id: null,
- revoked_at: null,
- region_id: null,
- region_name: null,
- region_emoji: null,
- region_latitude: null,
- region_longitude: null,
- server_id: null,
- hostname: null,
- internal_endpoint: null,
- soft_connection_limit: null,
- notes: null,
- vip_only: false,
- required_guild_features: null,
- allowed_guild_ids: null,
- allowed_user_ids: null,
- });
- await join(`fvj_42_${secret}`, joinBody(), HTTP_STATUS.UNAUTHORIZED, APIErrorCodes.VOICE_JOIN_TOKEN_INVALID);
- await join('fvj_1_short', joinBody(), HTTP_STATUS.UNAUTHORIZED, APIErrorCodes.VOICE_JOIN_TOKEN_INVALID);
- const pending = await createToken();
- await createBuilder(harness, `VoiceJoin ${pending.token}`)
- .get('/admin/voice/join-tokens')
- .expect(HTTP_STATUS.UNAUTHORIZED)
- .execute();
- await createBuilder(harness, `Bearer ${pending.token}`)
- .get('/users/@me')
- .expect(HTTP_STATUS.UNAUTHORIZED)
- .execute();
- });
-
- test('releases the claim when the endpoint check fails so the token works again', async () => {
- const created = await createToken();
- setVoiceNodeEndpointVerifierForTesting(async () => {
- throw new VoiceEndpointError('unreachable', 'HTTP 502');
- });
- await join(created.token, joinBody(), HTTP_STATUS.BAD_REQUEST, APIErrorCodes.VOICE_JOIN_ENDPOINT_UNREACHABLE);
- setVoiceNodeEndpointVerifierForTesting(async () => {
- throw new VoiceEndpointError('key_mismatch', 'HTTP 401');
- });
- await join(created.token, joinBody(), HTTP_STATUS.BAD_REQUEST, APIErrorCodes.VOICE_JOIN_KEY_MISMATCH);
- setVoiceNodeEndpointVerifierForTesting(async () => {});
- await join(created.token);
- });
-
- test('refuses an endpoint that is not wss, an IPv6 literal or another hostname than the preset', async () => {
- const created = await createToken({hostname: 'voice.example.com'});
- for (const endpoint of [
- 'https://voice.example.com/livekit-x',
- 'wss://[2001:db8::1]/livekit-x',
- 'wss://other.example.com/livekit-x',
- ]) {
- await createBuilder(harness, `VoiceJoin ${created.token}`)
- .post('/voice/join')
- .body(joinBody({endpoint}))
- .expect(HTTP_STATUS.BAD_REQUEST)
- .execute();
- }
- await join(created.token, joinBody({endpoint: 'wss://voice.example.com/livekit-fra-server-1'}));
- });
-
- test('rejects a duplicate server id or api key and two joins with one token', async () => {
- const first = await createToken({server_id: 'fra-server-1'});
- const pinned = await createBuilder<VoiceJoinPreviewResponse>(harness, `VoiceJoin ${first.token}`)
- .post('/voice/join/preview')
- .body({})
- .execute();
- expect(pinned).toMatchObject({
- server_id: 'fra-server-1',
- server_id_pinned: true,
- region: {id: 'fra', source: 'default'},
- });
- const requested = await createBuilder<VoiceJoinPreviewResponse>(harness, `VoiceJoin ${first.token}`)
- .post('/voice/join/preview')
- .body({region_id: 'fra'})
- .execute();
- expect(requested.region.source).toBe('requested');
- await join(first.token);
- const second = await createToken({server_id: 'fra-server-1'});
- await join(second.token, joinBody({api_key: 'fresh'}), HTTP_STATUS.CONFLICT, APIErrorCodes.VOICE_SERVER_ID_IN_USE);
- await join(second.token, joinBody({server_id: 'x'}), HTTP_STATUS.CONFLICT, APIErrorCodes.VOICE_SERVER_ID_IN_USE);
- const third = await createToken();
- await join(third.token, joinBody(), HTTP_STATUS.CONFLICT, APIErrorCodes.VOICE_SERVER_API_KEY_IN_USE);
- const racing = await createToken();
- let release: () => void = () => {};
- setVoiceNodeEndpointVerifierForTesting(() => new Promise<void>((resolve) => (release = resolve)));
- const winner = join(racing.token, joinBody({api_key: 'race-a', server_id: 'fra-race'}));
- await new Promise((resolve) => setTimeout(resolve, 50));
- await join(racing.token, joinBody({api_key: 'race-b'}), HTTP_STATUS.CONFLICT, APIErrorCodes.VOICE_JOIN_TOKEN_BUSY);
- release();
- await winner;
- expect(await new VoiceRepository().getServer('fra', 'fra-race')).toMatchObject({apiKey: 'race-a'});
- });
-
- test('creates a new region only from a token preset', async () => {
- const created = await createToken({
- region_id: 'sgp',
- region_name: 'Singapore',
- region_emoji: '🇸🇬',
- region_latitude: 1.35,
- region_longitude: 103.8,
- });
- const joined = await join(created.token);
- expect(joined.region_id).toBe('sgp');
- expect(await new VoiceRepository().getRegion('sgp')).toMatchObject({
- name: 'Singapore',
- latitude: 1.35,
- longitude: 103.8,
- });
- await createBuilder(harness, admin.token)
- .post('/admin/voice/join-tokens')
- .body({region_id: 'ams', region_name: 'Amsterdam', region_latitude: 52.4})
- .expect(HTTP_STATUS.BAD_REQUEST)
- .execute();
- await createBuilder(harness, admin.token)
- .post('/admin/voice/join-tokens')
- .body({region_id: 'fra', region_latitude: 50, region_longitude: 8})
- .expect(HTTP_STATUS.BAD_REQUEST)
- .execute();
- const other = await createToken();
- await join(other.token, joinBody({api_key: 'k2', region_id: 'nowhere'}), HTTP_STATUS.NOT_FOUND);
- });
-
- describe('node routes', () => {
- beforeEach(async () => {
- const created = await createToken({server_id: 'fra-server-1'});
- await join(created.token);
- });
-
- async function nodeRequest(method: 'GET' | 'PATCH' | 'DELETE', auth: string, body?: unknown) {
- const builder = createBuilder<VoiceNodeResponse>(harness, auth);
- const routed = {
- GET: () => builder.get(VOICE_NODE_PATH),
- PATCH: () => builder.patch(VOICE_NODE_PATH),
- DELETE: () => builder.delete(VOICE_NODE_PATH),
- }[method]();
- return body === undefined ? routed : routed.body(body);
- }
-
- test('reads and updates its own row', async () => {
- const node = await (await nodeRequest('GET', nodeJwt(nodeClaims('GET', '')))).execute();
- expect(node).toMatchObject({server_id: 'fra-server-1', draining: false, is_active: true});
- const body = {draining: true};
- const updated = await (
- await nodeRequest('PATCH', nodeJwt(nodeClaims('PATCH', JSON.stringify(body))), body)
- ).execute();
- expect(updated.draining).toBe(true);
- });
-
- test('allows a minute of clock skew and reports a larger one', async () => {
- const now = Math.floor(Date.now() / 1000);
- const ok = [
- {iat: now - 170, exp: now - 50},
- {iat: now + 50, exp: now + 170},
- ];
- for (const times of ok) {
- await (await nodeRequest('GET', nodeJwt(nodeClaims('GET', '', times)))).execute();
- }
- const skewed = [{iat: now - 300, exp: now - 180}, {iat: now + 180, exp: now + 300}, {exp: now + 3600}];
- for (const times of skewed) {
- await (await nodeRequest('GET', nodeJwt(nodeClaims('GET', '', times))))
- .expect(HTTP_STATUS.UNAUTHORIZED, APIErrorCodes.VOICE_NODE_TOKEN_EXPIRED)
- .execute();
- }
- await (await nodeRequest('GET', nodeJwt(nodeClaims('GET', '', {exp: now - 300}), 'b'.repeat(64))))
- .expect(HTTP_STATUS.UNAUTHORIZED, APIErrorCodes.VOICE_NODE_SIGNATURE_INVALID)
- .execute();
- });
-
- test('rejects tokens that are not node tokens', async () => {
- const cases: Array<[string, string]> = [
- [nodeJwt(nodeClaims('GET', ''), 'b'.repeat(64)), APIErrorCodes.VOICE_NODE_SIGNATURE_INVALID],
- [nodeJwt(nodeClaims('DELETE', '')), APIErrorCodes.VOICE_NODE_SIGNATURE_INVALID],
- [nodeJwt(nodeClaims('GET', '', {path: '/voice/other'})), APIErrorCodes.VOICE_NODE_SIGNATURE_INVALID],
- [nodeJwt(nodeClaims('GET', '', {aud: undefined})), APIErrorCodes.VOICE_NODE_SIGNATURE_INVALID],
- [nodeJwt(nodeClaims('GET', '', {video: {roomJoin: true}})), APIErrorCodes.VOICE_NODE_SIGNATURE_INVALID],
- [nodeJwt(nodeClaims('GET', '', {iss: 'nobody'})), APIErrorCodes.VOICE_NODE_UNKNOWN],
- ];
- for (const [auth, code] of cases) {
- await (await nodeRequest('GET', auth)).expect(HTTP_STATUS.UNAUTHORIZED, code).execute();
- }
- const participant = new AccessToken('fluxer-fra-server-1', SECRET, {identity: 'user_1_x'});
- participant.addGrant({roomJoin: true, room: 'guild_1_channel_2'});
- await (await nodeRequest('GET', `Bearer ${await participant.toJwt()}`))
- .expect(HTTP_STATUS.UNAUTHORIZED, APIErrorCodes.VOICE_NODE_SIGNATURE_INVALID)
- .execute();
- const body = {draining: true};
- await (await nodeRequest('PATCH', nodeJwt(nodeClaims('PATCH', '{"draining":false}')), body))
- .expect(HTTP_STATUS.UNAUTHORIZED, APIErrorCodes.VOICE_NODE_SIGNATURE_INVALID)
- .execute();
- });
-
- test('cannot turn itself on or change its region', async () => {
- for (const body of [{is_active: true}, {region_id: 'other'}, {internal_endpoint: 'http://10.0.0.1:7880'}]) {
- await (await nodeRequest('PATCH', nodeJwt(nodeClaims('PATCH', JSON.stringify(body))), body))
- .expect(HTTP_STATUS.BAD_REQUEST)
- .execute();
- }
- });
-
- test('tells a deleted server from a changed secret', async () => {
- await createBuilder(harness, admin.token)
- .patch('/admin/voice/regions/fra/servers/fra-server-1')
- .body({api_secret: 'c'.repeat(64)})
- .execute();
- await (await nodeRequest('GET', nodeJwt(nodeClaims('GET', ''))))
- .expect(HTTP_STATUS.UNAUTHORIZED, APIErrorCodes.VOICE_NODE_SIGNATURE_INVALID)
- .execute();
- await (await nodeRequest('DELETE', nodeJwt(nodeClaims('DELETE', ''), 'c'.repeat(64))))
- .expect(HTTP_STATUS.NO_CONTENT)
- .execute();
- await (await nodeRequest('GET', nodeJwt(nodeClaims('GET', ''), 'c'.repeat(64))))
- .expect(HTTP_STATUS.UNAUTHORIZED, APIErrorCodes.VOICE_NODE_UNKNOWN)
- .execute();
- });
- });
-
- describe('node routes on a server that joined with a hostname and soft limit', () => {
- const pinnedClaims = (method: string, body: string) => nodeClaims(method, body, {iss: 'fluxer-pinned'});
-
- beforeEach(async () => {
- const created = await createToken({
- server_id: 'fra-pinned',
- hostname: 'voice.example.com',
- soft_connection_limit: 100,
- internal_endpoint: 'http://10.0.0.5:7880',
- });
- await join(
- created.token,
- joinBody({api_key: 'fluxer-pinned', endpoint: 'wss://voice.example.com/livekit-fra-pinned'}),
- );
- });
-
- async function patch(body: Record<string, unknown>) {
- return createBuilder<VoiceNodeResponse>(harness, nodeJwt(pinnedClaims('PATCH', JSON.stringify(body))))
- .patch(VOICE_NODE_PATH)
- .body(body);
- }
-
- test('keeps the hostname of the token', async () => {
- await (await patch({endpoint: 'wss://other.example.com/livekit-fra-pinned'}))
- .expect(HTTP_STATUS.BAD_REQUEST, APIErrorCodes.VOICE_JOIN_ENDPOINT_INVALID)
- .execute();
- const moved = await (await patch({endpoint: 'wss://voice.example.com/livekit-moved'})).execute();
- expect(moved.endpoint).toBe('wss://voice.example.com/livekit-moved');
- });
-
- test('keeps the soft limit of the token', async () => {
- await (await patch({soft_connection_limit: 5000})).expect(HTTP_STATUS.BAD_REQUEST).execute();
- const same = await (await patch({soft_connection_limit: 100})).execute();
- expect(same.soft_connection_limit).toBe(100);
- });
-
- test('checks the new public endpoint even with an internal endpoint', async () => {
- const probes: Array<[string, boolean]> = [];
- setVoiceNodeEndpointVerifierForTesting(async (endpoint, _keys, internal, probePublic) => {
- probes.push([endpoint, probePublic && internal !== null]);
- });
- await (await patch({endpoint: 'wss://voice.example.com/livekit-new'})).execute();
- expect(probes).toEqual([['wss://voice.example.com/livekit-new', true]]);
- });
-
- test('moves when the public hostname resolves to a private address for the API', async () => {
- setVoiceNodeEndpointVerifierForTesting(null);
- setVoiceEndpointResolverForTesting(async () => ['10.0.0.9']);
- const seen: Array<string> = [];
- server.use(
- http.get('http://10.0.0.5:7880/', () => {
- seen.push('probe');
- return HttpResponse.text('OK');
- }),
- http.post('http://10.0.0.5:7880/twirp/livekit.RoomService/ListRooms', () => {
- seen.push('keys');
- return HttpResponse.json({rooms: []});
- }),
- );
- try {
- const moved = await (await patch({endpoint: 'wss://voice.example.com/livekit-split'})).execute();
- expect(moved.endpoint).toBe('wss://voice.example.com/livekit-split');
- expect(seen).toEqual(['probe', 'keys']);
- } finally {
- setVoiceEndpointResolverForTesting(null);
- }
- });
- });
-
- test('puts the public port of the instance in the join command', () => {
- expect(voiceJoinCommand('https://chat.example.com:8443', 'chat.example.com', 'fvj_1_x')).toBe(
- 'curl -fsSL https://fluxer.dev/install.sh | sh -s -- voice chat.example.com:8443 fvj_1_x',
- );
- expect(voiceJoinCommand('https://chat.example.com', 'chat.example.com', 'fvj_1_x')).toBe(
- 'curl -fsSL https://fluxer.dev/install.sh | sh -s -- voice chat.example.com fvj_1_x',
- );
- expect(voiceJoinCommand('https://chat.example.com:443/', 'chat.example.com', 'fvj_1_x')).toContain(
- ' voice chat.example.com fvj_1_x',
- );
- });
-
- test('needs a token for preview', async () => {
- await createBuilderWithoutAuth(harness)
- .post('/voice/join/preview')
- .body({})
- .expect(HTTP_STATUS.UNAUTHORIZED, APIErrorCodes.VOICE_JOIN_TOKEN_INVALID)
- .execute();
- });
-});
diff --git a/fluxer_api/src/api/voice/tests/VoiceServerEndpoints.test.ts b/fluxer_api/src/api/voice/tests/VoiceServerEndpoints.test.ts
deleted file mode 100644
index 40c818216..000000000
--- a/fluxer_api/src/api/voice/tests/VoiceServerEndpoints.test.ts
+++ /dev/null
@@ -1,73 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {server} from '@app/api/test/msw/server';
-import {
- checkLiveKitKeys,
- endpointOrigin,
- parseNodeEndpoint,
- probeLiveKit,
- resolveCheckedAddress,
- setVoiceEndpointResolverForTesting,
-} from '@app/api/voice/VoiceServerEndpoints';
-import {HttpResponse, http} from 'msw';
-import {afterEach, describe, expect, it} from 'vitest';
-
-describe('voice server endpoints', () => {
- afterEach(() => setVoiceEndpointResolverForTesting(null));
-
- it('keeps only the scheme, host and port as the origin', () => {
- expect(endpointOrigin('wss://voice.example.com/livekit-fra')).toBe('wss://voice.example.com');
- expect(endpointOrigin('wss://203.0.113.7:8443/livekit-x')).toBe('wss://203.0.113.7:8443');
- expect(endpointOrigin('https://voice.example.com')).toBeNull();
- });
-
- it('accepts only wss endpoints without IPv6 literals, credentials or queries', () => {
- expect(parseNodeEndpoint('wss://voice.example.com/livekit-a').hostname).toBe('voice.example.com');
- for (const bad of [
- 'ws://a.example.com',
- 'wss://[2001:db8::1]/x',
- 'wss://u:[email protected]',
- 'wss://a.example.com/?x=1',
- ]) {
- expect(() => parseNodeEndpoint(bad)).toThrow();
- }
- });
-
- it('refuses a host when any address is private, even after a public one', async () => {
- setVoiceEndpointResolverForTesting(async () => ['1.1.1.1']);
- await expect(resolveCheckedAddress(new URL('https://voice.example.com'), false)).resolves.toBe('1.1.1.1');
- setVoiceEndpointResolverForTesting(async () => ['1.1.1.1', '10.0.0.5']);
- await expect(resolveCheckedAddress(new URL('https://voice.example.com'), false)).rejects.toMatchObject({
- reason: 'private',
- });
- await expect(resolveCheckedAddress(new URL('https://voice.example.com'), true)).resolves.toBe('1.1.1.1');
- await expect(resolveCheckedAddress(new URL('https://127.0.0.1'), false)).rejects.toMatchObject({reason: 'private'});
- });
-
- it('probes the root of the path prefix and checks the keys against the room service', async () => {
- const seen: Array<string> = [];
- server.use(
- http.get('http://voice.test/livekit-a/', () => {
- seen.push('probe');
- return HttpResponse.text('OK');
- }),
- http.get('http://voice.test/other/', () => HttpResponse.text('down', {status: 502})),
- http.post('http://voice.test/livekit-a/twirp/livekit.RoomService/ListRooms', ({request}) => {
- seen.push('list');
- const auth = request.headers.get('authorization') ?? '';
- return HttpResponse.json({}, {status: auth.startsWith('Bearer ') ? 200 : 401});
- }),
- );
- setVoiceEndpointResolverForTesting(async () => ['1.1.1.1']);
- const options = {checkAddress: true, allowPrivate: false, timeoutMs: 2000};
- await probeLiveKit('ws://voice.test/livekit-a', options);
- await checkLiveKitKeys('ws://voice.test/livekit-a', {apiKey: 'k', apiSecret: 's'.repeat(32)}, options);
- await expect(probeLiveKit('ws://voice.test/other', options)).rejects.toMatchObject({
- reason: 'unreachable',
- message: 'HTTP 502',
- });
- setVoiceEndpointResolverForTesting(async () => ['192.168.1.2']);
- await expect(probeLiveKit('ws://voice.test/livekit-a', options)).rejects.toMatchObject({reason: 'private'});
- expect(seen).toEqual(['probe', 'list']);
- });
-});
diff --git a/fluxer_api/src/api/voice/tests/VoiceServerHealth.test.ts b/fluxer_api/src/api/voice/tests/VoiceServerHealth.test.ts
deleted file mode 100644
index 4c2a2bdca..000000000
--- a/fluxer_api/src/api/voice/tests/VoiceServerHealth.test.ts
+++ /dev/null
@@ -1,80 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import type {VoiceRegionRecord, VoiceServerRecord} from '@app/api/voice/VoiceModel';
-import {VoiceEndpointError} from '@app/api/voice/VoiceServerEndpoints';
-import {VoiceServerHealthMonitor} from '@app/api/voice/VoiceServerHealth';
-import {describe, expect, it} from 'vitest';
-
-function server(serverId: string, isActive = true): VoiceServerRecord {
- return {
- regionId: 'fra',
- serverId,
- endpoint: `wss://${serverId}.example.com`,
- apiKey: serverId,
- apiSecret: 'secret',
- latitude: null,
- longitude: null,
- isActive,
- softConnectionLimit: null,
- notes: null,
- internalEndpoint: null,
- pinnedHostname: null,
- pinnedSoftLimit: false,
- draining: false,
- restrictions: {
- vipOnly: false,
- requiredGuildFeatures: new Set(),
- allowedGuildIds: new Set(),
- allowedUserIds: new Set(),
- },
- createdAt: null,
- updatedAt: null,
- };
-}
-
-function topology(servers: Array<VoiceServerRecord>) {
- return {
- getAllRegions: () => [{id: 'fra'} as VoiceRegionRecord],
- getServersForRegion: () => servers,
- };
-}
-
-describe('VoiceServerHealthMonitor', () => {
- it('marks a server down after two failures and up after one success', async () => {
- const failing = new Set(['a']);
- const servers = [server('a'), server('b')];
- const monitor = new VoiceServerHealthMonitor(
- topology(servers),
- async (s) => {
- if (failing.has(s.serverId)) throw new VoiceEndpointError('unreachable', 'HTTP 502');
- },
- 0,
- );
- expect(monitor.get(servers[0]!).status).toBe('unknown');
- await monitor.checkAll();
- expect(monitor.get(servers[0]!)).toMatchObject({status: 'unknown', error: 'HTTP 502'});
- expect(monitor.get(servers[1]!).status).toBe('up');
- await monitor.checkAll();
- expect(monitor.get(servers[0]!).status).toBe('down');
- failing.clear();
- await monitor.checkAll();
- expect(monitor.get(servers[0]!)).toMatchObject({status: 'up', error: null});
- });
-
- it('never marks a server down for a refused address and skips inactive servers', async () => {
- const probed: Array<string> = [];
- const servers = [server('private'), server('off', false)];
- const monitor = new VoiceServerHealthMonitor(
- topology(servers),
- async (s) => {
- probed.push(s.serverId);
- throw new VoiceEndpointError('private', 'not public');
- },
- 0,
- );
- await monitor.checkAll();
- await monitor.checkAll();
- expect(monitor.get(servers[0]!)).toMatchObject({status: 'unknown', error: 'not public'});
- expect(probed).toEqual(['private', 'private']);
- });
-});
diff --git a/fluxer_api/src/api/webhook/tests/InstatusTransformer.test.ts b/fluxer_api/src/api/webhook/tests/InstatusTransformer.test.ts
deleted file mode 100644
index 85894b18c..000000000
--- a/fluxer_api/src/api/webhook/tests/InstatusTransformer.test.ts
+++ /dev/null
@@ -1,221 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {transformInstatusWebhook} from '@app/api/webhook/transformers/InstatusTransformer';
-import {RICH_EMBED_DESCRIPTION_MAX_LENGTH} from '@fluxer/schema/src/domains/message/MessageRequestSchemas';
-import {InstatusWebhook} from '@fluxer/schema/src/domains/webhook/InstatusWebhookSchemas';
-import {describe, expect, it} from 'vitest';
-
-function createMeta(): InstatusWebhook['meta'] {
- return {unsubscribe: 'https://fluxerstatus.com/unsubscribe?id=1&token=abc', documentation: ''};
-}
-
-describe('Instatus transformer', () => {
- describe('robustness', () => {
- it('accepts an empty payload and returns null', () => {
- expect(transformInstatusWebhook(InstatusWebhook.parse({}))).toBeNull();
- });
-
- it('accepts nullish event sections and returns null', () => {
- expect(
- transformInstatusWebhook(
- InstatusWebhook.parse({
- meta: null,
- page: null,
- incident: null,
- maintenance: null,
- component_update: null,
- component: null,
- }),
- ),
- ).toBeNull();
- });
-
- it('drops non-http(s) urls', () => {
- const payload: InstatusWebhook = {
- meta: createMeta(),
- page: {url: 'javascript:alert(1)'},
- incident: {name: 'Outage', status: 'INVESTIGATING', url: 'not-a-url'},
- };
- const embed = transformInstatusWebhook(payload);
- expect(embed?.url).toBeUndefined();
- });
- });
-
- describe('Instatus delivery', () => {
- it('uses the latest update and lists affected components', () => {
- const raw = {
- meta: {
- unsubscribe:
- 'https://jiralite.instatus.com/unsubscribe?id=cmr9oat950nga0kqg1688424b&token=221d8f1d-7e2f-43d1-b528-af72e7bb098c',
- documentation: '',
- },
- page: {
- id: 'cmr9kdnbr0mh40rqg5opm1nrj',
- status_indicator: 'HASISSUES',
- status_description: '',
- url: 'https://jiralite.instatus.com',
- },
- incident: {
- backfilled: false,
- created_at: '2026-07-06T20:43:40.300Z',
- name: 'Basic incident',
- resolved_at: null,
- status: 'Identified',
- updated_at: '2026-07-06T20:44:41.287Z',
- id: 'cmr9otle41c9q0rqff1okyv7q',
- incident_updates: [
- {
- id: 'cmr9otlob1c9r0rqf1mvgixhn',
- incident_id: 'cmr9otle41c9q0rqff1okyv7q',
- markdown: 'Hope Kevin Fang picks this incident up because we are so bored.',
- status: 'Investigating',
- created_at: '2026-07-06T20:43:40.667Z',
- updated_at: '2026-07-06T20:44:41.281Z',
- },
- {
- id: 'cmr9ouwgg1ca00rqfy39xauwg',
- incident_id: 'cmr9otle41c9q0rqff1okyv7q',
- markdown: 'Update - identified.',
- status: 'Identified',
- created_at: '2026-07-06T20:44:41.296Z',
- updated_at: '2026-07-06T20:44:41.296Z',
- },
- ],
- affected_components: [
- {id: 'cmr9osz9s1c9p0rqfgeiwp97t', name: 'Component', status: 'Major outage'},
- {id: 'cmr9ot5ld15is1aqfjptygehv', name: 'Component with no group', status: 'Major outage'},
- ],
- url: 'https://jiralite.instatus.com/cmr9otle41c9q0rqff1okyv7q',
- },
- };
- const embed = transformInstatusWebhook(InstatusWebhook.parse(raw));
- expect(embed?.title).toBe('Basic incident');
- expect(embed?.color).toBe(0xf97316);
- expect(embed?.description).toBe('Update - identified.');
- const affected = embed?.fields?.find((entry) => entry.name === 'Affected components');
- expect(affected?.inline).toBe(false);
- expect(affected?.value).toBe('- Component (major outage)\n- Component with no group (major outage)');
- });
-
- it('parses a component major outage', () => {
- const raw = {
- meta: {
- unsubscribe:
- 'https://jiralite.instatus.com/unsubscribe?id=cmr9oat950nga0kqg1688424b&token=221d8f1d-7e2f-43d1-b528-af72e7bb098c',
- documentation: '',
- },
- page: {
- id: 'cmr9kdnbr0mh40rqg5opm1nrj',
- status_indicator: 'HASISSUES',
- status_description: '',
- url: 'https://jiralite.instatus.com',
- },
- component_update: {
- created_at: '2026-07-06T20:44:44.403Z',
- new_status: 'MAJOROUTAGE',
- component_id: 'cmr9osz9s1c9p0rqfgeiwp97t',
- },
- component: {
- created_at: '2026-07-06T20:43:11.632Z',
- id: 'cmr9osz9s1c9p0rqfgeiwp97t',
- name: 'Component',
- status: 'MAJOROUTAGE',
- },
- };
- const embed = transformInstatusWebhook(InstatusWebhook.parse(raw));
- expect(embed?.title).toBe('Component - major outage');
- expect(embed?.color).toBe(0xe23c39);
- expect(embed?.url).toBe('https://jiralite.instatus.com');
- });
-
- it('accepts a very long update and truncates the rendered description', () => {
- const sentence =
- 'We implemented a fix somewhere. We have no idea where. In fact, not even sure it was implemented.';
- const raw = {
- meta: {unsubscribe: '', documentation: ''},
- page: {
- id: 'cmr9kdnbr0mh40rqg5opm1nrj',
- status_indicator: 'HASISSUES',
- status_description: '',
- url: 'https://jiralite.instatus.com',
- },
- incident: {
- backfilled: false,
- created_at: '2026-07-06T21:51:54.422Z',
- name: 'Monitoring',
- resolved_at: null,
- status: 'Monitoring',
- updated_at: '2026-07-06T21:51:54.422Z',
- id: 'cmr9r9cfq008f1apmu4mt0g4f',
- incident_updates: [
- {
- id: 'cmr9r9cg7008g1apm0cvk6ob4',
- incident_id: 'cmr9r9cfq008f1apmu4mt0g4f',
- markdown: Array.from({length: 150}, () => sentence).join('\n\n'),
- status: 'Monitoring',
- created_at: '2026-07-06T21:51:54.439Z',
- updated_at: '2026-07-06T21:51:54.439Z',
- },
- ],
- affected_components: [{id: 'cmr9osz9s1c9p0rqfgeiwp97t', name: 'Component', status: 'Major outage'}],
- url: 'https://jiralite.instatus.com/cmr9r9cfq008f1apmu4mt0g4f',
- },
- };
- const embed = transformInstatusWebhook(InstatusWebhook.parse(raw));
- expect(embed?.title).toBe('Monitoring');
- expect(embed?.color).toBe(0xf5a623);
- expect((embed?.description ?? '').length).toBeLessThanOrEqual(RICH_EMBED_DESCRIPTION_MAX_LENGTH);
- expect(embed?.description?.startsWith('We implemented a fix')).toBe(true);
- });
-
- it('renders a scheduled maintenance', () => {
- const raw = {
- meta: {unsubscribe: '', documentation: ''},
- page: {
- id: 'cmr9kdnbr0mh40rqg5opm1nrj',
- status_indicator: 'UNDERMAINTENANCE',
- status_description: '',
- url: 'https://jiralite.instatus.com',
- },
- maintenance: {
- backfilled: false,
- maintenance_start_date: '2026-07-07T08:00:00.000Z',
- maintenance_end_date: '2026-07-07T09:00:00.000Z',
- created_at: '2026-07-06T21:56:13.780Z',
- name: 'scheduled',
- resolved_at: null,
- status: 'Planned',
- updated_at: '2026-07-06T21:56:13.780Z',
- id: 'cmr9rewk400811ao2gp7ytf92',
- maintenance_updates: [
- {
- id: 'cmr9rewtu00821ao2agy436tp',
- maintenance_id: 'cmr9rewk400811ao2gp7ytf92',
- markdown:
- 'We are planning maintenance at this time. Just kidding, our database administrators just want to go outside. We used to call them on their cell phone too.',
- created_at: '2026-07-06T21:56:14.130Z',
- updated_at: '2026-07-06T21:56:14.130Z',
- },
- ],
- affected_components: [
- {id: 'cmr9ot5ld15is1aqfjptygehv', name: 'Component with no group', status: 'Operational'},
- ],
- url: 'https://jiralite.instatus.com/cmr9rewk400811ao2gp7ytf92',
- },
- };
- const embed = transformInstatusWebhook(InstatusWebhook.parse(raw));
- expect(embed?.title).toBe('scheduled');
- expect(embed?.color).toBe(0x3b82f6);
- expect(embed?.description).toBe(
- 'We are planning maintenance at this time. Just kidding, our database administrators just want to go outside. We used to call them on their cell phone too.',
- );
- const affected = embed?.fields?.find((entry) => entry.name === 'Affected components');
- expect(affected?.value).toBe('Component with no group (operational)');
- const windowEntry = embed?.fields?.find((entry) => entry.name === 'Window');
- const startUnix = Math.floor(Date.parse('2026-07-07T08:00:00.000Z') / 1000);
- const endUnix = Math.floor(Date.parse('2026-07-07T09:00:00.000Z') / 1000);
- expect(windowEntry?.value).toBe(`<t:${startUnix}:F>-<t:${endUnix}:F>`);
- expect(windowEntry?.inline).toBe(false);
- });
- });
-});
diff --git a/fluxer_api/src/api/worker/tests/ProcessCachePurgeQueue.test.ts b/fluxer_api/src/api/worker/tests/ProcessCachePurgeQueue.test.ts
index 37471593d..6194f5c07 100644
--- a/fluxer_api/src/api/worker/tests/ProcessCachePurgeQueue.test.ts
+++ b/fluxer_api/src/api/worker/tests/ProcessCachePurgeQueue.test.ts
@@ -128,21 +128,6 @@ describe('processCachePurgeQueue', () => {
expect(await members(kvClient, REJECTED_KEY)).toEqual([]);
});
- it('keeps every request within the Cloudflare limit of 100 prefixes', async () => {
- const {kvClient, queue} = createHarness();
- const urls = Array.from({length: 150}, (_, index) => `${MEDIA}/attachments/1/${index}/photo.png`);
- await queue.addUrls(urls);
- const requests = recordPurges((body) => new HttpResponse(null, {status: body.prefixes.length > 100 ? 400 : 200}));
-
- await processCachePurgeQueue({}, createTestWorkerHelpers());
- await kvClient.del(BUDGET_KEY);
- await processCachePurgeQueue({}, createTestWorkerHelpers());
-
- expect(requests.map((request) => request.body.prefixes.length)).toEqual([100, 50]);
- expect(await members(kvClient, REJECTED_KEY)).toEqual([]);
- expect(await members(kvClient, QUEUE_KEY)).toEqual([]);
- });
-
it('never queues a URL that is not a media CDN object', async () => {
const {kvClient, queue} = createHarness();
await queue.addUrls(['https://elsewhere.test/avatars/1/b35cc3d3', `${MEDIA}/avatars`, 'not-a-url']);
diff --git a/fluxer_app_proxy/src/branding_images.rs b/fluxer_app_proxy/src/branding_images.rs
index 6ef26e632..a432f18a4 100644
--- a/fluxer_app_proxy/src/branding_images.rs
+++ b/fluxer_app_proxy/src/branding_images.rs
@@ -383,56 +383,3 @@ impl InstanceBranding {
});
}
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn voice_origins_from_discovery_join_connect_sources_with_their_https_twins() {
- let discovery = serde_json::json!({
- "endpoints": {"api": "https://chat.example.com/api"},
- "voice_origins": [
- "wss://voice-fra.chat.example.com",
- "wss://203.0.113.7:8443",
- "not a url",
- 42
- ]
- });
- let sources = instance_sources_from_discovery(&discovery);
- for origin in [
- "wss://voice-fra.chat.example.com",
- "https://voice-fra.chat.example.com",
- "wss://203.0.113.7:8443",
- "https://203.0.113.7:8443",
- ] {
- assert!(
- sources.connect_origins.iter().any(|o| o == origin),
- "{origin} missing from {:?}",
- sources.connect_origins
- );
- }
- assert!(
- !sources
- .connect_origins
- .iter()
- .any(|o| o.contains("not a url"))
- );
- }
-
- #[test]
- fn a_server_that_leaves_discovery_leaves_the_connect_sources() {
- let with = serde_json::json!({"voice_origins": ["wss://voice-old.example.com"]});
- let without = serde_json::json!({"voice_origins": []});
- assert!(
- instance_sources_from_discovery(&with)
- .connect_origins
- .contains(&"wss://voice-old.example.com".to_owned())
- );
- assert!(
- instance_sources_from_discovery(&without)
- .connect_origins
- .is_empty()
- );
- }
-}
diff --git a/fluxer_gateway/test/gateway_nats_resubscribe_tests.erl b/fluxer_gateway/test/gateway_nats_resubscribe_tests.erl
deleted file mode 100644
index 412dbb3f8..000000000
--- a/fluxer_gateway/test/gateway_nats_resubscribe_tests.erl
+++ /dev/null
@@ -1,291 +0,0 @@
-%% SPDX-License-Identifier: AGPL-3.0-or-later
-
--module(gateway_nats_resubscribe_tests).
--typing([eqwalizer]).
--ifdef(TEST).
--include_lib("eunit/include/eunit.hrl").
-
--define(CONFIG_KEY, {fluxer_gateway, runtime_config}).
--define(RPC_SUBJECT, <<"rpc.gateway.>">>).
--define(EXTRA_SUBJECT, <<"config.gateway.rollout">>).
--define(INFO,
- <<"INFO {\"server_id\":\"fake\",\"version\":\"2.10.0\",\"proto\":1,",
- "\"max_payload\":1048576,\"headers\":true}\r\n">>
-).
-
-subscribe_retry_delay_backs_off_and_stops_growing_test() ->
- Delays = [gateway_nats_pool_conn:subscribe_retry_delay(N) || N <- lists:seq(1, 8)],
- ?assertEqual([250, 500, 1000, 2000, 4000, 5000, 5000, 5000], Delays),
- ?assertEqual(250, gateway_nats_pool_conn:subscribe_retry_delay(0)).
-
-closed_notice_before_connect_result_is_not_lost_test_() ->
- with_env(fun closed_notice_before_connect_result_is_not_lost/1).
-
-closed_notice_before_connect_result_is_not_lost(Port) ->
- State0 = rpc_state(),
- Conn = failed_conn(Port),
- Attempt = dead_pid(),
- {noreply, State1} = gateway_nats_rpc:handle_info(
- {Conn, closed}, State0#{connecting_pid => Attempt}
- ),
- ?assertNot(is_process_alive(Conn)),
- {noreply, State2} = gateway_nats_rpc:handle_info(
- {nats_connect_result, Attempt, {ok, Conn}}, State1
- ),
- MRef = maps:get(monitor_ref, State2),
- Down = receive_down(MRef, Conn),
- {noreply, State3} = gateway_nats_rpc:handle_info(Down, State2),
- ?assertEqual(undefined, maps:get(conn, State3)),
- ?assertEqual(connect, receive_message(connect, 3000)).
-
-ready_notice_before_connect_result_still_subscribes_test_() ->
- with_env(fun ready_notice_before_connect_result_still_subscribes/1).
-
-ready_notice_before_connect_result_still_subscribes(Port) ->
- Server = start_fake_nats(Port),
- State0 = rpc_state(),
- {ok, Conn} = connect(Port),
- ready = receive_message({Conn, ready}, 5000, ready),
- Attempt = dead_pid(),
- {noreply, State1} = gateway_nats_rpc:handle_info(
- {nats_connect_result, Attempt, {ok, Conn}}, State0#{connecting_pid => Attempt}
- ),
- ?assert(maps:get(ready, State1)),
- ?assert(maps:is_key(?RPC_SUBJECT, maps:get(rpc_subs, State1))),
- ?assertEqual(ok, await_subs(?RPC_SUBJECT, 1, 5000)),
- gateway_nats_pool_conn:ignore_disconnect(Conn),
- stop_fake_nats(Server).
-
-connection_that_never_becomes_ready_is_replaced_test_() ->
- with_env(fun connection_that_never_becomes_ready_is_replaced/1).
-
-connection_that_never_becomes_ready_is_replaced(Port) ->
- State0 = rpc_state(),
- Conn = failed_conn(Port),
- Attempt = dead_pid(),
- Token = make_ref(),
- {noreply, State1} = gateway_nats_rpc:handle_info(
- {nats_connect_result, Attempt, {ok, Conn}},
- State0#{connecting_pid => Attempt, connecting_token => Token}
- ),
- ?assertEqual(Conn, maps:get(conn, State1)),
- ?assertNot(maps:get(ready, State1)),
- {noreply, State2} = gateway_nats_rpc:handle_info({connect_timeout, Token}, State1),
- ?assertEqual(undefined, maps:get(conn, State2)),
- ?assertNot(is_process_alive(Conn)),
- ?assertEqual(connect, receive_message(connect, 3000)).
-
-subscribe_on_a_stuck_connection_gives_up_test_() ->
- with_env(fun subscribe_on_a_stuck_connection_gives_up/1).
-
-subscribe_on_a_stuck_connection_gives_up(Port) ->
- Conn = failed_conn(Port),
- Result = gateway_nats_pool_conn:guarded_sub(Conn, ?RPC_SUBJECT, #{}),
- ?assertMatch({error, _}, Result),
- ?assertNot(is_process_alive(Conn)).
-
-gateway_recovers_when_nats_starts_late_and_restarts_test_() ->
- with_env(fun gateway_recovers_when_nats_starts_late_and_restarts/1).
-
-gateway_recovers_when_nats_starts_late_and_restarts(Port) ->
- {ok, Rpc} = gateway_nats_rpc:start_link(),
- {ok, Pool} = gateway_nats_pool:start_link(),
- timer:sleep(1500),
- ?assertEqual({error, no_connection}, gateway_nats_pool_conn:get_pool_conn()),
- ?assertNot(gateway_nats_rpc:nats_ready()),
- ?assertEqual({error, not_connected}, gateway_nats_rpc:subscribe(?EXTRA_SUBJECT, <<>>)),
- Server = start_fake_nats(Port),
- ?assertEqual(ok, await_subs(?RPC_SUBJECT, 3, 10000)),
- ?assertEqual(ok, await_subs(?EXTRA_SUBJECT, 1, 10000)),
- ?assertEqual(ok, wait_until(fun gateway_nats_rpc:nats_ready/0, 5000)),
- stop_fake_nats(Server),
- ?assertEqual(ok, wait_until(fun() -> not gateway_nats_rpc:nats_ready() end, 5000)),
- flush_subs(),
- Restarted = start_fake_nats(Port),
- ?assertEqual(ok, await_subs(?RPC_SUBJECT, 3, 10000)),
- ?assertEqual(ok, await_subs(?EXTRA_SUBJECT, 1, 10000)),
- ?assertEqual(ok, wait_until(fun gateway_nats_rpc:nats_ready/0, 5000)),
- ok = gen_server:stop(Pool),
- ok = gen_server:stop(Rpc),
- stop_fake_nats(Restarted).
-
-with_env(Test) ->
- {setup, fun setup/0, fun cleanup/1, fun({Port, _Saved}) ->
- {timeout, 60, fun() -> run_trapping_exits(Test, Port) end}
- end}.
-
-run_trapping_exits(Test, Port) ->
- TrapExit = process_flag(trap_exit, true),
- try
- Test(Port)
- after
- process_flag(trap_exit, TrapExit),
- flush()
- end.
-
-setup() ->
- Saved = #{
- config => persistent_term:get(?CONFIG_KEY, undefined),
- logger => logger:get_primary_config()
- },
- ok = logger:set_primary_config(level, none),
- Port = free_port(),
- persistent_term:put(?CONFIG_KEY, #{
- nats_core_url => "nats://127.0.0.1:" ++ integer_to_list(Port),
- nats_auth_token => "",
- nats_rpc_enabled => true,
- nats_pool_size => 2,
- gateway_role => all,
- gateway_nats_rpc_max_handlers => 16
- }),
- {Port, Saved}.
-
-cleanup({_Port, #{config := Config, logger := Logger}}) ->
- restore_config(Config),
- persistent_term:erase({gateway_nats_rpc, subscription_status}),
- ok = logger:set_primary_config(Logger).
-
-restore_config(undefined) ->
- persistent_term:erase(?CONFIG_KEY);
-restore_config(Config) ->
- persistent_term:put(?CONFIG_KEY, Config).
-
-rpc_state() ->
- {ok, State} = gateway_nats_rpc:init([]),
- connect = receive_message(connect, 1000),
- State.
-
-connect(Port) ->
- Server = #{scheme => <<"nats">>, host => "127.0.0.1", port => Port, family => inet},
- nats:connect(Server, #{buffer_size => 0}).
-
-failed_conn(Port) ->
- {ok, Conn} = connect(Port),
- closed = receive_message({Conn, closed}, 5000, closed),
- flush_conn(Conn),
- ?assert(is_process_alive(Conn)),
- ?assertEqual(false, nats:is_ready(Conn)),
- Conn.
-
-dead_pid() ->
- {Pid, MRef} = spawn_monitor(fun() -> ok end),
- receive
- {'DOWN', MRef, process, Pid, _} -> Pid
- end.
-
-free_port() ->
- {ok, Socket} = gen_tcp:listen(0, [{ip, {127, 0, 0, 1}}]),
- {ok, Port} = inet:port(Socket),
- ok = gen_tcp:close(Socket),
- Port.
-
-start_fake_nats(Port) ->
- Owner = self(),
- Pid = spawn(fun() -> listen(Port, Owner) end),
- listening = receive_message({fake_nats_listening, Pid}, 5000, listening),
- Pid.
-
-stop_fake_nats(Pid) ->
- MRef = erlang:monitor(process, Pid),
- exit(Pid, kill),
- receive
- {'DOWN', MRef, process, Pid, _} -> ok
- end.
-
-listen(Port, Owner) ->
- Opts = [binary, {packet, line}, {active, false}, {reuseaddr, true}, {ip, {127, 0, 0, 1}}],
- {ok, Listen} = gen_tcp:listen(Port, Opts),
- Owner ! {fake_nats_listening, self()},
- accept_loop(Listen, Owner).
-
-accept_loop(Listen, Owner) ->
- {ok, Socket} = gen_tcp:accept(Listen),
- Handler = spawn_link(fun() -> serve(Owner) end),
- ok = gen_tcp:controlling_process(Socket, Handler),
- Handler ! {socket, Socket},
- accept_loop(Listen, Owner).
-
-serve(Owner) ->
- receive
- {socket, Socket} ->
- ok = gen_tcp:send(Socket, ?INFO),
- serve_loop(Socket, Owner)
- end.
-
-serve_loop(Socket, Owner) ->
- case gen_tcp:recv(Socket, 0) of
- {ok, Line} ->
- handle_line(Socket, Owner, Line),
- serve_loop(Socket, Owner);
- {error, _Reason} ->
- ok
- end.
-
-handle_line(Socket, _Owner, <<"PING", _/binary>>) ->
- gen_tcp:send(Socket, <<"PONG\r\n">>);
-handle_line(_Socket, Owner, <<"SUB ", Rest/binary>>) ->
- [Subject | _] = binary:split(Rest, <<" ">>),
- Owner ! {fake_nats_sub, Subject},
- ok;
-handle_line(_Socket, _Owner, _Line) ->
- ok.
-
-await_subs(_Subject, 0, _Timeout) ->
- ok;
-await_subs(Subject, Count, Timeout) ->
- receive
- {fake_nats_sub, Subject} -> await_subs(Subject, Count - 1, Timeout)
- after Timeout ->
- {missing, Subject, Count}
- end.
-
-wait_until(Check, Timeout) when Timeout =< 0 ->
- {timeout, Check()};
-wait_until(Check, Timeout) ->
- case Check() of
- true ->
- ok;
- false ->
- timer:sleep(50),
- wait_until(Check, Timeout - 50)
- end.
-
-receive_down(MRef, Conn) ->
- receive
- {'DOWN', MRef, process, Conn, _} = Down -> Down
- after 3000 ->
- error(no_down_message)
- end.
-
-receive_message(Message, Timeout) ->
- receive_message(Message, Timeout, Message).
-
-receive_message(Message, Timeout, Result) ->
- receive
- Message -> Result
- after Timeout ->
- {timeout, Message}
- end.
-
-flush_conn(Conn) ->
- receive
- {Conn, _} -> flush_conn(Conn)
- after 100 ->
- ok
- end.
-
-flush_subs() ->
- receive
- {fake_nats_sub, _Subject} -> flush_subs()
- after 0 ->
- ok
- end.
-
-flush() ->
- receive
- _ -> flush()
- after 0 ->
- ok
- end.
-
--endif.
diff --git a/fluxer_gateway/test/guild_data_normalize_tests.erl b/fluxer_gateway/test/guild_data_normalize_tests.erl
deleted file mode 100644
index de2600195..000000000
--- a/fluxer_gateway/test/guild_data_normalize_tests.erl
+++ /dev/null
@@ -1,38 +0,0 @@
-%% SPDX-License-Identifier: AGPL-3.0-or-later
-
--module(guild_data_normalize_tests).
--typing([eqwalizer]).
--ifdef(TEST).
--include_lib("eunit/include/eunit.hrl").
-
-role_keeps_icon_fields_when_set_test() ->
- Role = guild_data_normalize:role(role_with(<<"a1b2c3d4">>, null)),
- ?assertEqual(<<"a1b2c3d4">>, maps:get(<<"icon">>, Role)),
- ?assertEqual(null, maps:get(<<"unicode_emoji">>, Role)).
-
-role_keeps_unicode_emoji_test() ->
- Emoji = <<240, 159, 155, 161, 239, 184, 143>>,
- Role = guild_data_normalize:role(role_with(null, Emoji)),
- ?assertEqual(null, maps:get(<<"icon">>, Role)),
- ?assertEqual(Emoji, maps:get(<<"unicode_emoji">>, Role)).
-
-role_still_normalises_the_other_fields_test() ->
- Role = guild_data_normalize:role(role_with(<<"a1b2c3d4">>, null)),
- ?assertEqual(123456789012345678, maps:get(<<"id">>, Role)),
- ?assertEqual(3, maps:get(<<"position">>, Role)).
-
-role_with(Icon, UnicodeEmoji) ->
- #{
- <<"id">> => <<"123456789012345678">>,
- <<"name">> => <<"Mods">>,
- <<"color">> => 0,
- <<"position">> => 3,
- <<"hoist_position">> => null,
- <<"permissions">> => <<"0">>,
- <<"hoist">> => false,
- <<"mentionable">> => false,
- <<"icon">> => Icon,
- <<"unicode_emoji">> => UnicodeEmoji
- }.
-
--endif.
diff --git a/fluxer_gateway/test/guild_member_list_subscribe_tests.erl b/fluxer_gateway/test/guild_member_list_subscribe_tests.erl
deleted file mode 100644
index 129346686..000000000
--- a/fluxer_gateway/test/guild_member_list_subscribe_tests.erl
+++ /dev/null
@@ -1,41 +0,0 @@
-%% SPDX-License-Identifier: AGPL-3.0-or-later
-
--module(guild_member_list_subscribe_tests).
--typing([eqwalizer]).
--ifdef(TEST).
--include_lib("eunit/include/eunit.hrl").
-
--define(SESSION_ID, <<"session">>).
--define(LIST_ID, <<"0">>).
-
-first_subscribe_syncs_requested_ranges_test() ->
- State = test_state(),
- ?assertMatch({_, true, [{0, 99}]}, subscribe([{0, 99}], State)).
-
-repeated_subscribe_resyncs_requested_ranges_test() ->
- State = test_state(),
- {State1, true, [{0, 99}]} = subscribe([{0, 99}], State),
- ?assertMatch({_, true, [{0, 99}]}, subscribe([{0, 99}], State1)).
-
-narrower_subscribe_does_not_sync_test() ->
- State = test_state(),
- {State1, true, [{0, 99}, {100, 199}]} = subscribe([{0, 99}, {100, 199}], State),
- ?assertMatch({_, false, []}, subscribe([{0, 99}], State1)).
-
-wider_subscribe_syncs_only_new_ranges_test() ->
- State = test_state(),
- {State1, true, [{0, 99}]} = subscribe([{0, 99}], State),
- ?assertMatch({_, true, [{100, 199}]}, subscribe([{0, 99}, {100, 199}], State1)).
-
-empty_subscribe_does_not_sync_test() ->
- State = test_state(),
- {State1, true, [{0, 99}]} = subscribe([{0, 99}], State),
- ?assertMatch({_, false, []}, subscribe([], State1)).
-
-subscribe(Ranges, State) ->
- guild_member_list_subscribe:subscribe_ranges(?SESSION_ID, ?LIST_ID, Ranges, State).
-
-test_state() ->
- #{member_list_subscriptions => guild_member_list_subs:new()}.
-
--endif.
diff --git a/fluxer_gateway/test/guild_members_roles_tests.erl b/fluxer_gateway/test/guild_members_roles_tests.erl
deleted file mode 100644
index ee9af0165..000000000
--- a/fluxer_gateway/test/guild_members_roles_tests.erl
+++ /dev/null
@@ -1,106 +0,0 @@
-%% SPDX-License-Identifier: AGPL-3.0-or-later
-
--module(guild_members_roles_tests).
--typing([eqwalizer]).
--ifdef(TEST).
--include_lib("eunit/include/eunit.hrl").
-
--define(GUILD_ID, 100).
--define(OWNER_ID, 1).
--define(BOT_ID, 2).
--define(LOW_ID, 3).
--define(HIGH_ID, 4).
--define(PLAIN_ID, 5).
--define(TIE_FIRST_ID, 6).
--define(TIE_SECOND_ID, 7).
--define(ROLE_R, 200).
--define(ROLE_LOW, 300).
--define(ROLE_BOT, 400).
--define(ROLE_HIGH, 500).
--define(ROLE_TIE_FIRST, 600).
--define(ROLE_TIE_SECOND, 700).
-
-manager_can_give_a_role_below_them_test() ->
- ?assert(can_manage_roles(?BOT_ID, ?ROLE_R)).
-
-manager_cannot_give_a_role_above_them_test() ->
- ?assertNot(can_manage_roles(?LOW_ID, ?ROLE_R)),
- ?assertNot(can_manage_roles(?BOT_ID, ?ROLE_HIGH)).
-
-manager_can_give_a_role_to_a_member_they_cannot_moderate_test() ->
- ?assert(can_manage_roles(?BOT_ID, ?ROLE_R)),
- ?assertNot(check_target_member(?BOT_ID, ?HIGH_ID)).
-
-owner_stays_out_of_reach_for_member_actions_test() ->
- ?assertNot(check_target_member(?BOT_ID, ?OWNER_ID)),
- ?assert(check_target_member(?BOT_ID, ?PLAIN_ID)).
-
-equal_position_roles_rank_the_lower_id_higher_test() ->
- ?assert(can_manage_roles(?TIE_FIRST_ID, ?ROLE_TIE_SECOND)),
- ?assertNot(can_manage_roles(?TIE_SECOND_ID, ?ROLE_TIE_FIRST)),
- ?assert(can_manage_role(?TIE_FIRST_ID, ?ROLE_TIE_SECOND)),
- ?assertNot(can_manage_role(?TIE_SECOND_ID, ?ROLE_TIE_FIRST)),
- ?assert(check_target_member(?TIE_FIRST_ID, ?TIE_SECOND_ID)),
- ?assertNot(check_target_member(?TIE_SECOND_ID, ?TIE_FIRST_ID)).
-
-can_manage_roles(UserId, RoleId) ->
- {reply, #{can_manage := CanManage}, _} = guild_members_roles:can_manage_roles(
- #{user_id => UserId, role_id => RoleId}, test_state()
- ),
- CanManage.
-
-can_manage_role(UserId, RoleId) ->
- {reply, #{can_manage := CanManage}, _} = guild_members_roles:can_manage_role(
- #{user_id => UserId, role_id => RoleId}, test_state()
- ),
- CanManage.
-
-check_target_member(UserId, TargetUserId) ->
- {reply, #{can_manage := CanManage}, _} = guild_members_roles:check_target_member(
- #{user_id => UserId, target_user_id => TargetUserId}, test_state()
- ),
- CanManage.
-
-test_state() ->
- ViewPerm = constants:view_channel_permission(),
- ManageRoles = constants:manage_roles_permission(),
- #{
- id => ?GUILD_ID,
- data => #{
- <<"guild">> => #{<<"owner_id">> => integer_to_binary(?OWNER_ID)},
- <<"roles">> => [
- role(?GUILD_ID, 0, ViewPerm),
- role(?ROLE_R, 10, ViewPerm),
- role(?ROLE_LOW, 5, ViewPerm bor ManageRoles),
- role(?ROLE_BOT, 30, ViewPerm bor ManageRoles),
- role(?ROLE_HIGH, 40, ViewPerm),
- role(?ROLE_TIE_FIRST, 50, ViewPerm bor ManageRoles),
- role(?ROLE_TIE_SECOND, 50, ViewPerm bor ManageRoles)
- ],
- <<"channels">> => [],
- <<"members">> => [
- member(?OWNER_ID, []),
- member(?BOT_ID, [?ROLE_BOT]),
- member(?LOW_ID, [?ROLE_LOW]),
- member(?HIGH_ID, [?ROLE_HIGH]),
- member(?PLAIN_ID, []),
- member(?TIE_FIRST_ID, [?ROLE_TIE_FIRST]),
- member(?TIE_SECOND_ID, [?ROLE_TIE_SECOND])
- ]
- }
- }.
-
-role(Id, Position, Permissions) ->
- #{
- <<"id">> => integer_to_binary(Id),
- <<"permissions">> => integer_to_binary(Permissions),
- <<"position">> => Position
- }.
-
-member(UserId, RoleIds) ->
- #{
- <<"user">> => #{<<"id">> => integer_to_binary(UserId)},
- <<"roles">> => [integer_to_binary(RoleId) || RoleId <- RoleIds]
- }.
-
--endif.
diff --git a/fluxer_media_proxy/src/component_tests.rs b/fluxer_media_proxy/src/component_tests.rs
index 7b7f30f9f..e380f0669 100644
--- a/fluxer_media_proxy/src/component_tests.rs
+++ b/fluxer_media_proxy/src/component_tests.rs
@@ -14,38 +14,3 @@ fn blocked_libvips_loaders_cannot_decode_untrusted_input() {
assert!(raw.is_null());
unsafe { native::fluxer_vips_error_clear() };
}
-
-#[test]
-fn full_size_wallpaper_fits_a_small_memory_budget_instead_of_failing() {
- use crate::{
- image_quality::ImageQuality,
- image_transform::{AnimationMode, ImageOptions, ResizeMode},
- media_process::{MediaLimits, NativeCost, image_transform_cost, transform_image},
- metrics::transform::TransformMetrics,
- mime,
- output_format::OutputFormat,
- test_fixtures::synthetic_png,
- };
- let budget = 240 << 20;
- let limits = MediaLimits::default_from_config().with_native_memory_budget(budget);
- let input = synthetic_png(3840, 2160);
- let options = ImageOptions {
- width: None,
- height: None,
- format: OutputFormat::WebP,
- quality: ImageQuality::High,
- animation: AnimationMode::Static,
- effort_override: None,
- resize_mode: ResizeMode::Fit,
- deadline_ms: None,
- };
- let NativeCost::Bytes(cost) = image_transform_cost(&input, &options, &limits).unwrap() else {
- panic!("a still image has a fixed cost");
- };
- assert!(cost <= budget);
- let output = transform_image(&input, &options, &limits, &TransformMetrics::default()).unwrap();
- let served = mime::sniff(&output.bytes);
- assert_eq!("image/webp", served.mime);
- assert!(served.width >= 2400 && served.width < 3840);
- assert!((served.width * 9).abs_diff(served.height * 16) <= 16);
-}
diff --git a/fluxer_media_proxy/src/constants.rs b/fluxer_media_proxy/src/constants.rs
index 93928236a..8379bdc18 100644
--- a/fluxer_media_proxy/src/constants.rs
+++ b/fluxer_media_proxy/src/constants.rs
@@ -162,16 +162,3 @@ pub fn clamp_size(raw_target: u32, kind: AssetKind) -> u32 {
let dims = dims_for(kind);
value.clamp(dims.min, dims.max)
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn role_icon_sizes_clamp_between_16_and_512() {
- assert_eq!(Dims { min: 16, max: 512 }, dims_for(AssetKind::RoleIcon));
- assert_eq!(16, clamp_size(8, AssetKind::RoleIcon));
- assert_eq!(32, clamp_size(32, AssetKind::RoleIcon));
- assert_eq!(512, clamp_size(4096, AssetKind::RoleIcon));
- }
-}
diff --git a/fluxer_media_proxy/src/media_process/strip/av.rs b/fluxer_media_proxy/src/media_process/strip/av.rs
index 440f7b4a4..83b089436 100644
--- a/fluxer_media_proxy/src/media_process/strip/av.rs
+++ b/fluxer_media_proxy/src/media_process/strip/av.rs
@@ -127,80 +127,3 @@ pub fn audio_duration_seconds(
.or_else(|| positive(out.stream_seconds))
.or_else(|| positive(out.format_seconds)))
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- fn wav_with_info(samples: u32, sample_rate: u32) -> Vec<u8> {
- let data: Vec<u8> = (0..samples)
- .flat_map(|i| (((i % 64) as i16 - 32) * 512).to_le_bytes())
- .collect();
- let mut info = b"INFO".to_vec();
- info.extend_from_slice(b"INAM");
- info.extend_from_slice(&14u32.to_le_bytes());
- info.extend_from_slice(b"secret title\0\0");
- let mut body = b"WAVEfmt ".to_vec();
- body.extend_from_slice(&16u32.to_le_bytes());
- body.extend_from_slice(&1u16.to_le_bytes());
- body.extend_from_slice(&1u16.to_le_bytes());
- body.extend_from_slice(&sample_rate.to_le_bytes());
- body.extend_from_slice(&(sample_rate * 2).to_le_bytes());
- body.extend_from_slice(&2u16.to_le_bytes());
- body.extend_from_slice(&16u16.to_le_bytes());
- body.extend_from_slice(b"LIST");
- body.extend_from_slice(&(info.len() as u32).to_le_bytes());
- body.extend_from_slice(&info);
- body.extend_from_slice(b"data");
- body.extend_from_slice(&(data.len() as u32).to_le_bytes());
- body.extend_from_slice(&data);
- let mut wav = b"RIFF".to_vec();
- wav.extend_from_slice(&(body.len() as u32).to_le_bytes());
- wav.extend_from_slice(&body);
- wav
- }
-
- fn flv_tag(kind: u8, timestamp_ms: u32, data: &[u8]) -> Vec<u8> {
- let mut tag = vec![kind];
- tag.extend_from_slice(&(data.len() as u32).to_be_bytes()[1..]);
- tag.extend_from_slice(&timestamp_ms.to_be_bytes()[1..]);
- tag.push((timestamp_ms >> 24) as u8);
- tag.extend_from_slice(&[0, 0, 0]);
- tag.extend_from_slice(data);
- tag.extend_from_slice(&(11 + data.len() as u32).to_be_bytes());
- tag
- }
-
- #[test]
- fn remux_refuses_streams_that_appear_after_probing() {
- let mut flv = b"FLV\x01\x04\x00\x00\x00\x09\x00\x00\x00\x00".to_vec();
- let mut audio = vec![0x3E];
- audio.extend_from_slice(&[0; 8820]);
- for index in 0..700 {
- flv.extend(flv_tag(8, index * 100, &audio));
- }
- let mut video = vec![0x12];
- video.extend_from_slice(&[0; 64]);
- for index in 0..10 {
- flv.extend(flv_tag(9, 70_000 + index * 100, &video));
- }
- let container = av_container("video/x-flv").expect("flv container");
- let output = tempfile::NamedTempFile::new().expect("output file");
-
- assert!(strip_av_metadata(&flv, container, output.path(), None).is_err());
- }
-
- #[test]
- fn remux_drops_container_tags_and_keeps_every_sample() {
- let input = wav_with_info(48_000 * 3 / 2, 48_000);
- let container = av_container("audio/wav").expect("wav container");
- let output = tempfile::NamedTempFile::new().expect("output file");
-
- strip_av_metadata(&input, container, output.path(), None).expect("stripped wav");
-
- let stripped = std::fs::read(output.path()).expect("stripped bytes");
- assert!(!stripped.windows(6).any(|window| window == b"secret"));
- let duration = audio_duration_seconds(&stripped, None).expect("duration");
- assert_eq!(Some(1.5), duration);
- }
-}
diff --git a/fluxer_media_proxy/src/media_process/strip/gif.rs b/fluxer_media_proxy/src/media_process/strip/gif.rs
index c99c9c600..bd1f23b83 100644
--- a/fluxer_media_proxy/src/media_process/strip/gif.rs
+++ b/fluxer_media_proxy/src/media_process/strip/gif.rs
@@ -81,31 +81,3 @@ pub(super) fn strip_blocks(input: &[u8]) -> Result<Vec<u8>, MediaError> {
}
}
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn strip_drops_comments_and_unknown_applications_but_keeps_looping() {
- let mut input = b"GIF89a\x01\x00\x01\x00\x80\x00\x00\x00\x00\x00\xff\xff\xff".to_vec();
- input.extend_from_slice(b"\x21\xff\x0bNETSCAPE2.0\x03\x01\x00\x00\x00");
- input.extend_from_slice(b"\x21\xfe\x09GPS 59.33\x00");
- input.extend_from_slice(b"\x21\xff\x0bXMP DataXMP\x04Jane\x00");
- input.extend_from_slice(b"\x21\xf9\x04\x00\x0a\x00\x00\x00");
- input.extend_from_slice(b"\x2c\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02\x44\x01\x00");
- input.extend_from_slice(b"\x3btrailing");
-
- let stripped = strip_blocks(&input).expect("stripped gif");
-
- let contains = |needle: &[u8]| {
- stripped
- .windows(needle.len())
- .any(|window| window == needle)
- };
- assert!(contains(b"NETSCAPE2.0"));
- assert!(!contains(b"GPS"));
- assert!(!contains(b"Jane"));
- assert!(stripped.ends_with(b"\x02\x02\x44\x01\x00\x3b"));
- }
-}
diff --git a/fluxer_media_proxy/src/media_process/strip/heif.rs b/fluxer_media_proxy/src/media_process/strip/heif.rs
index cea7f0cfd..f07e6566d 100644
--- a/fluxer_media_proxy/src/media_process/strip/heif.rs
+++ b/fluxer_media_proxy/src/media_process/strip/heif.rs
@@ -370,96 +370,3 @@ fn zero_idat(meta: &mut [u8], ranges: &[Range<usize>]) -> Result<(), MediaError>
let (body, end) = (idat.body, idat.end);
zero_ranges(&mut meta[body..end], ranges)
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- fn full_box(kind: &[u8; 4], version: u8, body: &[u8]) -> Vec<u8> {
- let mut payload = vec![version, 0, 0, 0];
- payload.extend_from_slice(body);
- plain_box(kind, &payload)
- }
-
- fn plain_box(kind: &[u8; 4], body: &[u8]) -> Vec<u8> {
- let mut out = Vec::new();
- push_box(&mut out, kind, body).expect("box");
- out
- }
-
- fn infe(id: u16, item_type: &[u8; 4]) -> Vec<u8> {
- let mut body = id.to_be_bytes().to_vec();
- body.extend_from_slice(&[0, 0]);
- body.extend_from_slice(item_type);
- body.push(0);
- full_box(b"infe", 2, &body)
- }
-
- fn heif_with_exif(image_offset: u32, exif_offset: u32) -> Vec<u8> {
- heif_with_entries(image_offset, exif_offset, infe(2, b"Exif"))
- }
-
- fn heif_with_entries(image_offset: u32, exif_offset: u32, exif_entry: Vec<u8>) -> Vec<u8> {
- let mut iinf = 2u16.to_be_bytes().to_vec();
- iinf.extend(infe(1, b"hvc1"));
- iinf.extend(exif_entry);
- let mut iloc = vec![0x44, 0x00];
- iloc.extend_from_slice(&2u16.to_be_bytes());
- for (id, offset) in [(1u16, image_offset), (2u16, exif_offset)] {
- iloc.extend_from_slice(&id.to_be_bytes());
- iloc.extend_from_slice(&[0, 0, 0, 1]);
- iloc.extend_from_slice(&offset.to_be_bytes());
- iloc.extend_from_slice(&8u32.to_be_bytes());
- }
- let mut cdsc = 2u16.to_be_bytes().to_vec();
- cdsc.extend_from_slice(&1u16.to_be_bytes());
- cdsc.extend_from_slice(&1u16.to_be_bytes());
- let mut ipma = 2u32.to_be_bytes().to_vec();
- ipma.extend_from_slice(&[0, 1, 1, 0x81]);
- ipma.extend_from_slice(&[0, 2, 1, 0x81]);
- let mut iprp = plain_box(b"ipco", &plain_box(b"ispe", &[0; 12]));
- iprp.extend(full_box(b"ipma", 0, &ipma));
- let mut meta = full_box(b"hdlr", 0, &[0; 21]);
- meta.extend(full_box(b"iinf", 0, &iinf));
- meta.extend(full_box(b"iloc", 0, &iloc));
- meta.extend(full_box(b"iref", 0, &plain_box(b"cdsc", &cdsc)));
- meta.extend(plain_box(b"iprp", &iprp));
- let mut file = plain_box(b"ftyp", b"heic\0\0\0\0mif1heic");
- file.extend(full_box(b"meta", 0, &meta));
- file.extend(plain_box(b"mdat", b"IMAGEDATGPS59.33"));
- file
- }
-
- #[test]
- fn strip_removes_exif_items_without_moving_image_data() {
- let probe = heif_with_exif(0, 0);
- let mdat_payload = probe.len() as u32 - 16;
- let input = heif_with_exif(mdat_payload, mdat_payload + 8);
-
- let stripped = strip_items(&input).expect("stripped heif");
-
- assert_eq!(input.len(), stripped.len());
- let image = mdat_payload as usize;
- assert_eq!(b"IMAGEDAT", &stripped[image..image + 8]);
- assert_eq!(&[0u8; 8], &stripped[image + 8..image + 16]);
- let contains = |needle: &[u8]| {
- stripped
- .windows(needle.len())
- .any(|window| window == needle)
- };
- assert!(!contains(b"Exif"));
- assert!(!contains(b"cdsc"));
- assert!(contains(b"free"));
- let top = children(&stripped, 0, stripped.len()).expect("top-level boxes");
- let kinds: Vec<&[u8; 4]> = top.iter().map(|span| &span.kind).collect();
- assert_eq!(vec![b"ftyp", b"meta", b"free", b"mdat"], kinds);
- }
-
- #[test]
- fn strip_refuses_item_entries_it_cannot_classify() {
- let legacy_entry = full_box(b"infe", 0, b"\x00\x02\x00\x00exif\x00application/exif\x00");
- let input = heif_with_entries(0, 0, legacy_entry);
-
- assert_eq!(Err(MediaError::UnsupportedMediaType), strip_items(&input));
- }
-}
diff --git a/fluxer_media_proxy/src/media_process/strip/jpeg.rs b/fluxer_media_proxy/src/media_process/strip/jpeg.rs
index a7bfc1ed6..0a4184599 100644
--- a/fluxer_media_proxy/src/media_process/strip/jpeg.rs
+++ b/fluxer_media_proxy/src/media_process/strip/jpeg.rs
@@ -355,53 +355,3 @@ pub(super) fn reencode_upright(
}
insert_after_jfif(encoded, &icc)
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- fn segment(marker: u8, payload: &[u8]) -> Vec<u8> {
- let mut out = vec![0xFF, marker];
- out.extend_from_slice(&((payload.len() + 2) as u16).to_be_bytes());
- out.extend_from_slice(payload);
- out
- }
-
- #[test]
- fn strip_keeps_jfif_icc_and_adobe_and_drops_the_rest() {
- let mut input = vec![0xFF, SOI];
- input.extend(segment(APP0, b"JFIF\0\x01\x01\0\0\x01\0\x01\0\0"));
- input.extend(segment(0xE1, b"Exif\0\0GPS"));
- input.extend(segment(APP2, b"ICC_PROFILE\0\x01\x01data"));
- input.extend(segment(APP2, b"MPF\0data"));
- input.extend(segment(0xED, b"Photoshop 3.0\0"));
- input.extend(segment(APP14, b"Adobe\0\x64\0\0\0\0\x02"));
- input.extend(segment(COM, b"comment"));
- input.extend(segment(DQT, &[0; 65]));
- input.extend(segment(SOS, &[1, 1, 0, 0, 63, 0]));
- input.extend_from_slice(&[0x12, 0xFF, 0x00, 0x34, 0xFF, 0xD0, 0x56]);
- input.extend_from_slice(&[0xFF, EOI]);
- input.extend_from_slice(b"trailer-gps");
-
- let stripped = strip_segments(&input).expect("stripped jpeg");
- let markers: Vec<u8> = parse_layout(&stripped)
- .expect("layout")
- .header
- .iter()
- .map(|segment| segment.marker)
- .collect();
- assert_eq!(vec![APP0, APP2, APP14, DQT], markers);
- assert!(stripped.ends_with(&[0x56, 0xFF, EOI]));
- assert!(!stripped.windows(3).any(|window| window == b"GPS"));
- }
-
- #[test]
- fn quality_estimate_recovers_the_encoder_quality() {
- for quality in [55, 82, 95] {
- let encoded =
- crate::test_fixtures::synthetic_image(64, 48, &format!(".jpg[Q={quality},strip]"));
- let layout = parse_layout(&encoded).expect("layout");
- assert_eq!(Some(quality), estimate_quality(&layout.header));
- }
- }
-}
diff --git a/fluxer_media_proxy/src/server/asset_path.rs b/fluxer_media_proxy/src/server/asset_path.rs
index 6cd385440..11e8b7545 100644
--- a/fluxer_media_proxy/src/server/asset_path.rs
+++ b/fluxer_media_proxy/src/server/asset_path.rs
@@ -233,17 +233,6 @@ pub(in crate::server) fn decode_storage_key(path: &str) -> Result<String, Storag
mod tests {
use super::*;
- #[test]
- fn role_icon_paths_map_to_the_role_icon_kind() {
- let parsed = parse_standard_asset_path("/role-icons/123456789012345678/a1b2c3d4.webp")
- .expect("role icon path");
- assert_eq!(AssetKind::RoleIcon, parsed.kind);
- assert_eq!("role-icons/123456789012345678/a1b2c3d4", parsed.storage_key);
- assert_eq!(AssetExtension::Webp, parsed.original_ext);
- assert!(parse_standard_asset_path("/role-icons/not-a-snowflake/a1b2c3d4.webp").is_none());
- assert!(parse_standard_asset_path("/role-icons/123456789012345678/a1b2c3d4").is_none());
- }
-
#[test]
fn storage_keys_reject_path_changing_escapes_and_empty_components() {
assert_eq!(
diff --git a/fluxer_media_proxy/src/server/routes/dispatch.rs b/fluxer_media_proxy/src/server/routes/dispatch.rs
index 4d1220160..b546d760a 100644
--- a/fluxer_media_proxy/src/server/routes/dispatch.rs
+++ b/fluxer_media_proxy/src/server/routes/dispatch.rs
@@ -838,309 +838,4 @@ mod tests {
assert_eq!(Some("64"), filtered.get("width").map(String::as_str));
assert_eq!(Some("1"), filtered.get("download").map(String::as_str));
}
-
- #[tokio::test]
- async fn role_icons_are_served_as_webp_and_png() {
- let tmp = tempfile::tempdir().expect("storage root");
- let root = tmp.path().canonicalize().expect("canonical storage root");
- let root = root.as_path();
- write_object(
- root,
- "cdn",
- "role-icons/123456789012345678/a1b2c3d4",
- &crate::test_fixtures::synthetic_png(64, 64),
- );
- let app = dispatch_app("mp", root, &[]);
- for (uri, content_type) in [
- (
- "/role-icons/123456789012345678/a1b2c3d4.webp?size=32",
- "image/webp",
- ),
- (
- "/role-icons/123456789012345678/a1b2c3d4.png?size=16",
- "image/png",
- ),
- ] {
- let response = dispatch_uri(&app, Method::GET, uri, &[], None).await;
- assert_eq!(StatusCode::OK, response.status(), "{uri}");
- assert_eq!(
- Some(content_type.to_owned()),
- header_value(&response, header::CONTENT_TYPE),
- "{uri}"
- );
- assert!(!body_of(response).await.is_empty(), "{uri}");
- }
- }
-
- #[tokio::test]
- async fn role_icons_return_not_found_for_a_bad_owner_or_missing_object() {
- let tmp = tempfile::tempdir().expect("storage root");
- let root = tmp.path().canonicalize().expect("canonical storage root");
- let app = dispatch_app("mp", root.as_path(), &[]);
- for uri in [
- "/role-icons/not-a-snowflake/a1b2c3d4.webp",
- "/role-icons/123456789012345678/a1b2c3d4.webp?size=32",
- ] {
- let response = dispatch_uri(&app, Method::GET, uri, &[], None).await;
- assert_eq!(StatusCode::NOT_FOUND, response.status(), "{uri}");
- }
- }
-
- async fn hold_native_slot(
- app: &Arc<AppState>,
- released: std::sync::mpsc::Receiver<()>,
- ) -> std::pin::Pin<Box<impl Future<Output = anyhow::Result<()>> + '_>> {
- let mut holder = Box::pin(app.media.transforms().tasks().run_native(
- None,
- || Ok(crate::media_process::NativeCost::Bytes(0)),
- move || {
- released.recv().ok();
- Ok(())
- },
- ));
- std::future::poll_fn(|cx| {
- assert!(holder.as_mut().poll(cx).is_pending());
- std::task::Poll::Ready(())
- })
- .await;
- holder
- }
-
- #[tokio::test]
- async fn a_full_transform_queue_serves_a_displayable_stored_emoji_untransformed() {
- let tmp = tempfile::tempdir().expect("storage root");
- let root = tmp.path().canonicalize().expect("canonical storage root");
- let app = dispatch_app(
- "mp",
- &root,
- &[
- ("FLUXER_MEDIA_PROXY_MAX_NATIVE_TRANSFORMS", "1"),
- ("FLUXER_MEDIA_PROXY_WORKER_QUEUE_CAPACITY", "1"),
- ],
- );
- let cdn = &app.cfg.storage.bucket_cdn;
- let emoji = crate::test_fixtures::synthetic_image(128, 128, ".webp[strip]");
- let svg = br#"<svg xmlns="http://www.w3.org/2000/svg" width="128" height="128"><rect width="128" height="128" fill="red"/></svg>"#;
- for (key, data, content_type) in [
- ("emojis/1", emoji.as_slice(), "image/webp"),
- ("emojis/2", svg.as_slice(), "image/svg+xml"),
- ] {
- app.store
- .write_object(cdn, key, data, content_type)
- .await
- .expect("stored emoji");
- }
- let (release, released) = std::sync::mpsc::channel();
- let running = hold_native_slot(&app, released).await;
- let queued = hold_native_slot(&app, std::sync::mpsc::channel().1).await;
-
- let response = dispatch_uri(&app, Method::GET, "/emojis/1.webp?size=48", &[], None).await;
- assert_eq!(StatusCode::OK, response.status());
- assert_eq!(
- Some("image/webp".to_owned()),
- header_value(&response, header::CONTENT_TYPE)
- );
- assert_eq!(
- Some("no-store".to_owned()),
- header_value(&response, header::CACHE_CONTROL)
- );
- assert_eq!(
- Some("no-store".to_owned()),
- header_value(&response, "CDN-Cache-Control")
- );
- assert_eq!(emoji.as_slice(), body_of(response).await.as_ref());
-
- let response = dispatch_uri(&app, Method::GET, "/emojis/2.webp?size=48", &[], None).await;
- assert_eq!(StatusCode::GATEWAY_TIMEOUT, response.status());
- assert_eq!(
- Some("coalescer_timeout_asset_image"),
- response
- .extensions()
- .get::<crate::request_log::ErrorReason>()
- .map(|reason| reason.code)
- );
-
- drop(queued);
- release.send(()).expect("running holder is waiting");
- running.await.expect("running holder finished");
- }
-
- const FULL_TRANSFORM_QUEUE: &[(&str, &str)] = &[
- ("FLUXER_MEDIA_PROXY_MAX_NATIVE_TRANSFORMS", "1"),
- ("FLUXER_MEDIA_PROXY_WORKER_QUEUE_CAPACITY", "1"),
- ];
- const VECTOR_IMAGE: &[u8] = br#"<svg xmlns="http://www.w3.org/2000/svg" width="128" height="128"><rect width="128" height="128" fill="red"/></svg>"#;
-
- async fn assert_untransformed_original(response: Response, content_type: &str, body: &[u8]) {
- assert_eq!(StatusCode::OK, response.status());
- assert_eq!(
- Some(content_type.to_owned()),
- header_value(&response, header::CONTENT_TYPE)
- );
- assert_eq!(
- Some("no-store".to_owned()),
- header_value(&response, header::CACHE_CONTROL)
- );
- assert_eq!(
- Some("no-store".to_owned()),
- header_value(&response, "CDN-Cache-Control")
- );
- assert_eq!(body, body_of(response).await.as_ref());
- }
-
- fn assert_image_transform_timeout(response: &Response) {
- assert_eq!(StatusCode::GATEWAY_TIMEOUT, response.status());
- assert_eq!(
- Some("coalescer_timeout_image"),
- response
- .extensions()
- .get::<crate::request_log::ErrorReason>()
- .map(|reason| reason.code)
- );
- }
-
- #[tokio::test]
- async fn a_full_transform_queue_serves_a_displayable_attachment_untransformed() {
- let tmp = tempfile::tempdir().expect("storage root");
- let root = tmp.path().canonicalize().expect("canonical storage root");
- let picture = crate::test_fixtures::synthetic_png(128, 128);
- write_object(&root, "cdn", IMAGE_KEY, &picture);
- write_object(&root, "cdn", "attachments/1/2/vector.svg", VECTOR_IMAGE);
- let app = dispatch_app(
- "mp",
- &root,
- &[SIGNATURE_ENFORCE, FULL_TRANSFORM_QUEUE].concat(),
- );
- let (release, released) = std::sync::mpsc::channel();
- let running = hold_native_slot(&app, released).await;
- let queued = hold_native_slot(&app, std::sync::mpsc::channel().1).await;
-
- let uri = signed_uri(IMAGE_PATH, IMAGE_KEY, "width=64&height=64");
- let response = dispatch_uri(&app, Method::GET, &uri, &[], None).await;
- assert_untransformed_original(response, "image/png", &picture).await;
-
- let uri = signed_uri(
- "/attachments/1/2/vector.svg",
- "attachments/1/2/vector.svg",
- "width=64&height=64",
- );
- let response = dispatch_uri(&app, Method::GET, &uri, &[], None).await;
- assert_image_transform_timeout(&response);
-
- drop(queued);
- release.send(()).expect("running holder is waiting");
- running.await.expect("running holder finished");
- }
-
- async fn serve_external_origin(objects: Vec<(&'static str, &'static str, Vec<u8>)>) -> u16 {
- let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
- .await
- .expect("origin listener");
- let port = listener.local_addr().expect("origin address").port();
- let objects = Arc::new(objects);
- let origin =
- axum::Router::new().fallback(axum::routing::get(move |uri: axum::http::Uri| {
- let objects = Arc::clone(&objects);
- async move {
- objects
- .iter()
- .find(|(path, _, _)| *path == uri.path())
- .map(|(_, content_type, body)| {
- Response::builder()
- .header(header::CONTENT_TYPE, *content_type)
- .body(Body::from(body.clone()))
- .expect("origin response")
- })
- .unwrap_or_else(|| text(StatusCode::NOT_FOUND, "Not Found"))
- }
- }));
- tokio::spawn(async move { axum::serve(listener, origin).await });
- port
- }
-
- fn external_uri(url: &str, query: &str) -> String {
- let path = fluxer_common::external_media_path::build_external_media_proxy_path(url)
- .expect("external proxy path");
- let signature = fluxer_common::external_media_path::create_signature(&path, b"secret");
- format!("/external/{signature}/{path}?{query}")
- }
-
- #[tokio::test]
- async fn a_full_transform_queue_serves_a_displayable_external_image_untransformed() {
- let tmp = tempfile::tempdir().expect("storage root");
- let root = tmp.path().canonicalize().expect("canonical storage root");
- let picture = crate::test_fixtures::synthetic_png(128, 128);
- let port = serve_external_origin(vec![
- ("/pic.png", "image/png", picture.clone()),
- ("/vector.svg", "image/svg+xml", VECTOR_IMAGE.to_vec()),
- ])
- .await;
- let client = reqwest::Client::builder()
- .no_proxy()
- .resolve(
- "images.example.com",
- std::net::SocketAddr::from(([127, 0, 0, 1], port)),
- )
- .build()
- .expect("origin client");
- let app = Arc::new(
- AppState::for_tests(dispatch_config("mp", &root, FULL_TRANSFORM_QUEUE))
- .with_external_client(client),
- );
- let (release, released) = std::sync::mpsc::channel();
- let running = hold_native_slot(&app, released).await;
- let queued = hold_native_slot(&app, std::sync::mpsc::channel().1).await;
-
- let uri = external_uri("http://images.example.com/pic.png", "width=64&height=64");
- let response = dispatch_uri(&app, Method::GET, &uri, &[], None).await;
- assert_untransformed_original(response, "image/png", &picture).await;
-
- let uri = external_uri("http://images.example.com/vector.svg", "width=64&height=64");
- let response = dispatch_uri(&app, Method::GET, &uri, &[], None).await;
- assert_image_transform_timeout(&response);
-
- drop(queued);
- release.send(()).expect("running holder is waiting");
- running.await.expect("running holder finished");
- }
-
- #[tokio::test]
- async fn a_full_memory_budget_serves_a_stored_emoji_untransformed_without_storing() {
- let tmp = tempfile::tempdir().expect("storage root");
- let root = tmp.path().canonicalize().expect("canonical storage root");
- let app = dispatch_app(
- "mp",
- &root,
- &[("FLUXER_MEDIA_PROXY_MAX_NATIVE_TRANSFORMS", "2")],
- );
- let cdn = &app.cfg.storage.bucket_cdn;
- let emoji = crate::test_fixtures::synthetic_image(128, 128, ".webp[strip]");
- app.store
- .write_object(cdn, "emojis/1", &emoji, "image/webp")
- .await
- .expect("stored emoji");
- let (started, has_started) = tokio::sync::oneshot::channel();
- let (release, released) = std::sync::mpsc::channel::<()>();
- let mut holder = Box::pin(app.media.transforms().tasks().run_native(
- None,
- || Ok(crate::media_process::NativeCost::UpToBudget(usize::MAX)),
- move || {
- started.send(()).ok();
- released.recv().ok();
- Ok(())
- },
- ));
- std::future::poll_fn(|cx| {
- assert!(holder.as_mut().poll(cx).is_pending());
- std::task::Poll::Ready(())
- })
- .await;
- has_started.await.expect("memory budget held");
-
- let response = dispatch_uri(&app, Method::GET, "/emojis/1.webp?size=48", &[], None).await;
- assert_untransformed_original(response, "image/webp", &emoji).await;
-
- release.send(()).expect("holder is waiting");
- holder.await.expect("holder finished");
- }
}
diff --git a/fluxer_media_proxy/src/server/routes/internal.rs b/fluxer_media_proxy/src/server/routes/internal.rs
index 1179baa30..91e154af2 100644
--- a/fluxer_media_proxy/src/server/routes/internal.rs
+++ b/fluxer_media_proxy/src/server/routes/internal.rs
@@ -539,122 +539,6 @@ mod tests {
String::from_utf8(bytes.to_vec()).expect("utf8 body")
}
- #[tokio::test]
- async fn own_url_metadata_reports_the_served_dimensions() {
- let tmp = tempfile::tempdir().expect("temp storage root");
- let storage_root = tmp.path().canonicalize().expect("canonical storage root");
- let app = Arc::new(AppState::for_tests(
- Config::load_from_iter([
- (
- "FLUXER_MEDIA_PROXY_SECRET_KEY".to_owned(),
- "secret".to_owned(),
- ),
- (
- "FLUXER_MEDIA_PROXY_STORAGE_ROOT".to_owned(),
- storage_root.display().to_string(),
- ),
- (
- "FLUXER_MEDIA_PROXY_PUBLIC_ENDPOINT".to_owned(),
- "https://chat.example.test/media".to_owned(),
- ),
- ])
- .expect("test config"),
- ));
- let cdn = &app.cfg.storage.bucket_cdn;
- let emoji = crate::test_fixtures::synthetic_image(128, 128, ".webp[strip]");
- for (key, data, content_type) in [
- ("emojis/1", emoji.clone(), "image/webp"),
- (
- "emojis/2",
- crate::test_fixtures::synthetic_image(128, 256, ".webp[strip,page-height=128]"),
- "image/webp",
- ),
- (
- "attachments/1/2/cat.png",
- crate::test_fixtures::synthetic_png(128, 96),
- "image/png",
- ),
- ] {
- app.store
- .write_object(cdn, key, &data, content_type)
- .await
- .expect("stored object");
- }
- let metadata = async |path: &str, with_base64: bool| {
- let body = serde_json::json!({
- "type": "external",
- "url": format!("https://chat.example.test/media/{path}"),
- "version": 2,
- "nsfw": "allow",
- "with_base64": with_base64,
- });
- let response = metadata_handler(
- State(Arc::clone(&app)),
- authorized_headers(),
- json_request(body.to_string()),
- )
- .await;
- assert_eq!(StatusCode::OK, response.status(), "{path}");
- serde_json::from_str::<serde_json::Value>(&response_body(response).await)
- .expect("metadata json")
- };
- for (path, width, height, content_type, animated) in [
- ("emojis/1.webp?size=48", 48, 48, "image/webp", false),
- ("emojis/1.webp?size=50", 56, 56, "image/webp", false),
- ("emojis/1.webp?size=4096", 128, 128, "image/webp", false),
- ("emojis/1.png?size=48", 48, 48, "image/png", false),
- ("emojis/2.webp?size=48", 48, 48, "image/webp", true),
- ("attachments/1/2/cat.png", 128, 96, "image/png", false),
- (
- "attachments/1/2/cat.png?width=64",
- 64,
- 48,
- "image/png",
- false,
- ),
- (
- "attachments/1/2/cat.png?width=64&ex=0&is=0&hm=00&uc=dp",
- 64,
- 48,
- "image/png",
- false,
- ),
- (
- "attachments/1/2/cat.png?width=nope",
- 128,
- 96,
- "image/png",
- false,
- ),
- ] {
- let metadata = metadata(path, false).await;
- assert_eq!(
- (
- Some(width),
- Some(height),
- Some(content_type),
- Some(animated)
- ),
- (
- metadata["width"].as_u64(),
- metadata["height"].as_u64(),
- metadata["content_type"].as_str(),
- metadata["animated"].as_bool(),
- ),
- "{path}"
- );
- }
- let metadata = metadata("emojis/1.webp?size=48", true).await;
- assert_eq!(
- (Some(128), Some(128)),
- (metadata["width"].as_u64(), metadata["height"].as_u64())
- );
- assert_eq!(
- Some(general_purpose::STANDARD.encode(&emoji).as_str()),
- metadata["base64"].as_str()
- );
- }
-
#[test]
fn internal_auth_uses_bearer_secret() {
let headers = authorized_headers();
diff --git a/fluxer_media_proxy/src/server/state.rs b/fluxer_media_proxy/src/server/state.rs
index c27b677c9..df9075774 100644
--- a/fluxer_media_proxy/src/server/state.rs
+++ b/fluxer_media_proxy/src/server/state.rs
@@ -75,12 +75,6 @@ impl AppState {
signature_log: WouldDenyLog::new(),
}
}
-
- #[cfg(test)]
- pub(in crate::server) fn with_external_client(mut self, client: reqwest::Client) -> Self {
- self.media.external_client = reqwest_middleware::ClientBuilder::new(client).build();
- self
- }
}
impl MediaRuntime {
diff --git a/fluxer_media_proxy/src/server/transform/cache_key.rs b/fluxer_media_proxy/src/server/transform/cache_key.rs
index c77910b15..3816ca86f 100644
--- a/fluxer_media_proxy/src/server/transform/cache_key.rs
+++ b/fluxer_media_proxy/src/server/transform/cache_key.rs
@@ -97,17 +97,3 @@ fn serialize_optional_number(value: Option<impl ToString>) -> String {
pub(in crate::server) fn sha256_hex(data: &[u8]) -> String {
hex::encode(Sha256::digest(data))
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn role_icons_have_their_own_cache_key_name() {
- assert_eq!("role_icon", asset_kind_name(AssetKind::RoleIcon));
- assert_ne!(
- asset_kind_name(AssetKind::GuildIcon),
- asset_kind_name(AssetKind::RoleIcon)
- );
- }
-}
diff --git a/fluxer_rexctl/cmd/autoupgrade_test.go b/fluxer_rexctl/cmd/autoupgrade_test.go
deleted file mode 100644
index 59c52119c..000000000
--- a/fluxer_rexctl/cmd/autoupgrade_test.go
+++ /dev/null
@@ -1,348 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-package cmd
-
-import (
- "bytes"
- "context"
- "encoding/json"
- "errors"
- "net/http"
- "net/http/httptest"
- "os"
- "path/filepath"
- "runtime"
- "strings"
- "testing"
- "time"
-
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/backup"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/host"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/instance"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/ui"
-)
-
-func notifyRun(t *testing.T, notify bool) (*App, chan upgradeNotice) {
- t.Helper()
- got := make(chan upgradeNotice, 1)
- srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- var n upgradeNotice
- if r.Method != http.MethodPost || r.Header.Get("Content-Type") != "application/json" || json.NewDecoder(r.Body).Decode(&n) != nil {
- w.WriteHeader(http.StatusBadRequest)
- return
- }
- got <- n
- }))
- t.Cleanup(srv.Close)
- inst, err := instance.Create(t.TempDir(), "fluxer")
- if err != nil {
- t.Fatal(err)
- }
- inst.State.Release = "2026.1027.120000"
- if notify {
- inst.State.NotifyURL = srv.URL + "/hooks/secret"
- }
- if err := inst.Save(); err != nil {
- t.Fatal(err)
- }
- out := &bytes.Buffer{}
- app := &App{
- Flags: GlobalFlags{Dir: inst.Dir},
- UI: ui.New(ui.Options{Stdin: strings.NewReader(""), Stdout: out, Stderr: out}),
- }
- return app, got
-}
-
-func TestNotifyUpgrade(t *testing.T) {
- ctx := context.Background()
-
- app, got := notifyRun(t, true)
- app.outcome = "Upgraded to Fluxer 2026.1027.120000."
- notifyUpgrade(ctx, app, nil)
- n := <-got
- if n.Status != "upgraded" || n.Release != "2026.1027.120000" || n.Text != n.Content || !strings.HasSuffix(n.Text, "Upgraded to Fluxer 2026.1027.120000.") {
- t.Errorf("upgraded notice = %+v", n)
- }
-
- app, got = notifyRun(t, true)
- notifyUpgrade(ctx, app, ui.Refused("Another rexctl command is changing this instance.", "Wait for it to finish, then try again."))
- n = <-got
- if n.Status != "failed" || !strings.HasSuffix(n.Text, "Another rexctl command is changing this instance. Wait for it to finish, then try again.") {
- t.Errorf("failed notice = %+v", n)
- }
-
- app, got = notifyRun(t, true)
- app.outcome = "Fluxer 2026.1027.120000 didn't start. Went back to Fluxer 2026.1020.100000."
- app.SetExit(ui.ExitFailed)
- notifyUpgrade(ctx, app, nil)
- if n = <-got; n.Status != "failed" {
- t.Errorf("went-back notice = %+v", n)
- }
-
- app, got = notifyRun(t, true)
- notifyUpgrade(ctx, app, nil)
- notifyUpgrade(ctx, app, context.Canceled)
- app, _ = notifyRun(t, false)
- app.outcome = "Upgraded to Fluxer 2026.1027.120000."
- notifyUpgrade(ctx, app, nil)
- select {
- case n := <-got:
- t.Errorf("sent %+v for a run with nothing to tell", n)
- default:
- }
-}
-
-func TestMaskURL(t *testing.T) {
- cases := map[string]string{
- "https://discord.com/api/webhooks/1/secret": "https://discord.com/…",
- "https://ntfy.sh/topic?tpl=1": "https://ntfy.sh/…",
- "https://hooks.example.com": "https://hooks.example.com",
- }
- for in, want := range cases {
- if got := maskURL(in); got != want {
- t.Errorf("maskURL(%s) = %s, want %s", in, got, want)
- }
- }
-}
-
-func TestAutoUpgradeWhen(t *testing.T) {
- if got := autoUpgradeWhen(host.Systemd, "", "23:45"); got != "every day between 23:45 and 00:15" {
- t.Errorf("systemd: %s", got)
- }
- if got := autoUpgradeWhen(host.Cron, "", "04:00"); got != "every day at 04:00" {
- t.Errorf("cron: %s", got)
- }
- if got := autoUpgradeWhen(host.Systemd, "Sun", "04:00"); got != "every Sunday between 04:00 and 04:30" {
- t.Errorf("weekly systemd gives %q", got)
- }
- if got := autoUpgradeWhen(host.Cron, "Mon", "00:10"); got != "every Monday at 00:10" {
- t.Errorf("weekly cron gives %q", got)
- }
-}
-
-func TestUnknownDayIsRefused(t *testing.T) {
- app, _ := notifyRun(t, false)
- for _, day := range []string{"funday", "su", "8", "sundays"} {
- err := runAutoUpgradeOn(context.Background(), app, autoUpgradeOptions{At: "04:00", Day: day})
- var ee *ui.ExitError
- if !errors.As(err, &ee) || ee.Code != ui.ExitUsage || !strings.Contains(ee.Msg, "--day") {
- t.Errorf("--day %s returned %v, want a usage error about --day", day, err)
- }
- }
- err := runAutoUpgradeOn(context.Background(), app, autoUpgradeOptions{At: "04:00", Backup: "some"})
- var ee *ui.ExitError
- if !errors.As(err, &ee) || ee.Code != ui.ExitUsage || !strings.Contains(ee.Msg, "--backup") {
- t.Errorf("--backup some returned %v, want a usage error about --backup", err)
- }
-}
-
-func TestVoiceMachineRefusesBackupOptions(t *testing.T) {
- inst := voiceMachine(t)
- app, _ := testVoiceApp()
- app.Flags.Dir = inst.Dir
- for _, o := range []autoUpgradeOptions{{At: "04:00", FullBackup: "monthly"}, {At: "04:00", Backup: backup.ScopeWithoutUploads}} {
- err := runAutoUpgradeOn(context.Background(), app, o)
- var ee *ui.ExitError
- if !errors.As(err, &ee) || ee.Code != ui.ExitUsage || !strings.Contains(ee.Msg, "voice machine") {
- t.Errorf("%+v returned %v, want a usage error about the voice machine", o, err)
- }
- }
-}
-
-func TestDayAcceptsFullNames(t *testing.T) {
- for in, want := range map[string]string{"sun": "Sun", "Sunday": "Sun", "MONDAY": "Mon", "thu": "Thu", "saturday": "Sat", "": ""} {
- got, err := parseDay(in)
- if err != nil || got != want {
- t.Errorf("parseDay(%q) = %q, %v, want %q", in, got, err, want)
- }
- }
-}
-
-func scheduledStatus(t *testing.T, a host.AutoUpgrade) host.AutoUpgradeState {
- t.Helper()
- if runtime.GOOS == "windows" {
- t.Skip("needs a shell to fake systemctl")
- }
- root := t.TempDir()
- bin := filepath.Join(root, "bin")
- if err := os.MkdirAll(bin, 0o755); err != nil {
- t.Fatal(err)
- }
- if err := os.WriteFile(filepath.Join(bin, "systemctl"), []byte("#!/bin/sh\nexit 0\n"), 0o755); err != nil {
- t.Fatal(err)
- }
- t.Setenv("PATH", bin)
- t.Setenv("XDG_CONFIG_HOME", filepath.Join(root, "config"))
- if err := host.InstallAutoUpgrade(context.Background(), a); err != nil {
- t.Fatal(err)
- }
- s, err := host.CheckAutoUpgrade(context.Background(), a, time.Now())
- if err != nil {
- t.Fatal(err)
- }
- return s
-}
-
-func autoUpgradeStatus(t *testing.T, a host.AutoUpgrade) map[string]any {
- t.Helper()
- app, _ := notifyRun(t, false)
- app.Flags.JSON = true
- out := app.UI.Stdout().(*bytes.Buffer)
- inst, err := instance.Find(app.Flags.Dir)
- if err != nil {
- t.Fatal(err)
- }
- a.Dir, a.Binary = inst.Dir, filepath.Join(inst.Dir, "rexctl")
- s := scheduledStatus(t, a)
- if err := showAutoUpgrade(app, inst, a, s, time.Now()); err != nil {
- t.Fatal(err)
- }
- var got map[string]any
- if err := json.Unmarshal(out.Bytes(), &got); err != nil {
- t.Fatalf("status JSON %q doesn't decode (%v)", out.String(), err)
- }
- return got
-}
-
-func TestStatusJSONShowsDayAndBackup(t *testing.T) {
- a := host.AutoUpgrade{Scheduler: host.Systemd, Project: "fluxer", Rootless: true, At: "04:00", Day: "Sun", Backup: backup.ScopeWithoutUploads}
- got := autoUpgradeStatus(t, a)
- if got["day"] != "sun" || got["backup"] != "without-uploads" || got["at"] != "04:00" || got["on"] != true {
- t.Errorf("weekly status JSON = %v", got)
- }
- if _, ok := got["full_backup"]; ok {
- t.Errorf("status JSON without a monthly backup = %v", got)
- }
- a.Day, a.Backup = "", backup.ScopeFull
- got = autoUpgradeStatus(t, a)
- if _, ok := got["day"]; ok || got["backup"] != "full" {
- t.Errorf("daily status JSON = %v", got)
- }
- a.FullBackup = host.FullBackupMonthly
- if got = autoUpgradeStatus(t, a); got["full_backup"] != "monthly" {
- t.Errorf("status JSON with a monthly backup = %v", got)
- }
-}
-
-func TestFullBackupAcceptsOnlyMonthly(t *testing.T) {
- for in, want := range map[string]string{"": "", "monthly": "monthly", "Monthly": "monthly"} {
- if got, err := parseFullBackup(in); err != nil || got != want {
- t.Errorf("parseFullBackup(%q) = %q, %v, want %q", in, got, err, want)
- }
- }
- app, _ := notifyRun(t, false)
- err := runAutoUpgradeOn(context.Background(), app, autoUpgradeOptions{At: "04:00", FullBackup: "weekly"})
- var ee *ui.ExitError
- if !errors.As(err, &ee) || ee.Code != ui.ExitUsage || !strings.Contains(ee.Msg, "--full-backup") {
- t.Errorf("--full-backup weekly returned %v, want a usage error about --full-backup", err)
- }
-}
-
-func TestStatusWarnsWithoutRecentUploadsBackup(t *testing.T) {
- now := time.Date(2026, 11, 20, 12, 0, 0, 0, time.UTC)
- app, _ := notifyRun(t, false)
- out := app.UI.Stdout().(*bytes.Buffer)
- inst, err := instance.Find(app.Flags.Dir)
- if err != nil {
- t.Fatal(err)
- }
- a := host.AutoUpgrade{Project: "fluxer", Dir: "/opt/fluxer", Binary: "/usr/local/bin/rexctl", Podman: true}
- const warning = "No backup from the last 5 weeks has your uploads."
- weekly := host.AutoUpgradeState{On: true, Day: "Sun", At: "04:00", Backup: backup.ScopeWithoutUploads}
- uploadsBackupNote(app, inst, a, weekly, now)
- if s := out.String(); !strings.Contains(s, warning) || !strings.Contains(s, "Run rexctl backup now, and run rexctl auto-upgrade on --day sun --backup without-uploads --full-backup monthly.") || strings.Contains(s, "cron") || strings.Contains(s, "--notify") {
- t.Errorf("with no backups the status says %q", s)
- }
- out.Reset()
- cron := a
- cron.Scheduler, cron.Domain = host.Cron, "chat.example.com"
- cron.At, cron.Day = "03:30", "Sat"
- day, at, err := cron.Start()
- if err != nil {
- t.Fatal(err)
- }
- inst.State.NotifyURL = "https://ntfy.sh/fluxer-upgrades"
- uploadsBackupNote(app, inst, cron, host.AutoUpgradeState{On: true, Day: day, At: at, Backup: backup.ScopeWithoutUploads}, now)
- inst.State.NotifyURL = ""
- if s := out.String(); !strings.Contains(s, "run rexctl auto-upgrade on --day sat --at 03:30 --backup without-uploads --full-backup monthly. Add --notify with your address to that command to keep the notifications.") {
- t.Errorf("with a cron schedule and notifications the status says %q", s)
- }
- out.Reset()
- for _, tc := range []struct {
- scheduler host.Scheduler
- rootless bool
- want string
- }{
- {host.Systemd, false, "read journalctl -u fluxer-backup.service to see why the monthly backup failed"},
- {host.Systemd, true, "read journalctl --user -u fluxer-backup.service to see why"},
- {host.Cron, false, "read /opt/fluxer/.rexctl/full-backup.log to see why"},
- } {
- out.Reset()
- scheduled := a
- scheduled.Scheduler, scheduled.Rootless, scheduled.FullBackup, scheduled.Log = tc.scheduler, tc.rootless, host.FullBackupMonthly, "/opt/fluxer/.rexctl/auto-upgrade.log"
- uploadsBackupNote(app, inst, scheduled, host.AutoUpgradeState{FullBackup: host.FullBackupMonthly}, now)
- if s := out.String(); !strings.Contains(s, "Run rexctl backup now. The monthly backup hasn't run yet.") {
- t.Errorf("with a monthly %s backup that never ran the status says %q", tc.scheduler, s)
- }
- out.Reset()
- uploadsBackupNote(app, inst, scheduled, host.AutoUpgradeState{FullBackup: host.FullBackupMonthly, FullBackupRan: true}, now)
- if s := out.String(); !strings.Contains(s, warning) || !strings.Contains(s, tc.want) {
- t.Errorf("with a monthly %s backup and none recent the status says %q", tc.scheduler, s)
- }
- }
- out.Reset()
- writeTestBackup(t, inst, "2026.1020.100000", time.Date(2026, 10, 12, 4, 0, 0, 0, time.UTC), "")
- writeTestBackup(t, inst, "2026.1020.100000", time.Date(2026, 11, 15, 4, 0, 0, 0, time.UTC), backup.ScopeWithoutUploads)
- out.Reset()
- uploadsBackupNote(app, inst, a, host.AutoUpgradeState{}, now)
- if !strings.Contains(out.String(), "The newest backup with uploads is from 12 October 2026 at 04:00 UTC.") || !strings.Contains(out.String(), warning) {
- t.Errorf("with an old full backup the status says %q", out.String())
- }
- out.Reset()
- uploadsBackupNote(app, inst, a, host.AutoUpgradeState{}, time.Date(2026, 10, 20, 12, 0, 0, 0, time.UTC))
- if strings.Contains(out.String(), warning) || !strings.Contains(out.String(), "12 October 2026") {
- t.Errorf("with a recent full backup the status says %q", out.String())
- }
-}
-
-func TestLeanBackupNoteKeepsTheSchedule(t *testing.T) {
- app, _ := notifyRun(t, false)
- out := app.UI.Stdout().(*bytes.Buffer)
- leanBackupNote(app, host.AutoUpgradeState{Day: "Sun", At: "04:00", Backup: backup.ScopeWithoutUploads}, "")
- if s := out.String(); !strings.Contains(s, "Run rexctl auto-upgrade on --day sun --backup without-uploads --full-backup monthly to keep a full backup as well") || strings.Contains(s, "--notify") {
- t.Errorf("auto-upgrade on --day sun --backup without-uploads says %q", s)
- }
- out.Reset()
- leanBackupNote(app, host.AutoUpgradeState{At: "02:15", Backup: backup.ScopeWithoutUploads}, "https://ntfy.sh/fluxer-upgrades")
- if s := out.String(); !strings.Contains(s, "Run rexctl auto-upgrade on --at 02:15 --backup without-uploads --full-backup monthly to keep") || !strings.Contains(s, "Add --notify with your address to that command to keep the notifications.") {
- t.Errorf("auto-upgrade on --at 02:15 with --notify says %q", s)
- }
-}
-
-func TestMonthlyBackupOnTheFirstIsRecentAllMonth(t *testing.T) {
- app, _ := notifyRun(t, false)
- out := app.UI.Stdout().(*bytes.Buffer)
- inst, err := instance.Find(app.Flags.Dir)
- if err != nil {
- t.Fatal(err)
- }
- stockholm, err := time.LoadLocation("Europe/Stockholm")
- if err != nil {
- t.Skip(err)
- }
- writeTestBackup(t, inst, "2026.1020.100000", time.Date(2026, 10, 1, 3, 0, 0, 0, stockholm), "")
- uploadsBackupNote(app, inst, host.AutoUpgrade{Project: "fluxer"}, host.AutoUpgradeState{}, time.Date(2026, 11, 1, 2, 59, 0, 0, stockholm))
- if strings.Contains(out.String(), "No backup from the last") {
- t.Errorf("a backup from 1 October counts as too old on 1 November before 03:00, output %q", out.String())
- }
- app, _ = notifyRun(t, false)
- out = app.UI.Stdout().(*bytes.Buffer)
- if inst, err = instance.Find(app.Flags.Dir); err != nil {
- t.Fatal(err)
- }
- writeTestBackup(t, inst, "2026.1020.100000", time.Date(2026, 10, 1, 1, 0, 0, 0, stockholm), "")
- uploadsBackupNote(app, inst, host.AutoUpgrade{Project: "fluxer"}, host.AutoUpgradeState{}, time.Date(2026, 10, 2, 12, 0, 0, 0, stockholm))
- if want := "The newest backup with uploads is from 1 October 2026 at 01:00 CEST."; !strings.Contains(out.String(), want) {
- t.Errorf("a monthly backup at 01:00 on the 1st shows as %q, want %q", out.String(), want)
- }
-}
diff --git a/fluxer_rexctl/cmd/backup_test.go b/fluxer_rexctl/cmd/backup_test.go
deleted file mode 100644
index e22c8b36a..000000000
--- a/fluxer_rexctl/cmd/backup_test.go
+++ /dev/null
@@ -1,217 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-package cmd
-
-import (
- "bytes"
- "context"
- "encoding/binary"
- "encoding/json"
- "errors"
- "os"
- "path/filepath"
- "slices"
- "strings"
- "testing"
- "time"
-
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/backup"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/instance"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/ui"
-)
-
-func TestBackupCompressErrorKeepsInstanceUp(t *testing.T) {
- err := backupCreateErr(&backup.CompressError{Err: errors.New("no space left on device")})
- var ee *ui.ExitError
- if !errors.As(err, &ee) {
- t.Fatalf("backupCreateErr returned %T, want a ui.ExitError", err)
- }
- if ee.Code == ui.ExitInterrupted {
- t.Fatal("a compression failure is not a cancellation")
- }
- if !strings.Contains(ee.Msg, "running again") {
- t.Fatalf("message = %q, want it to say Fluxer is running again", ee.Msg)
- }
-}
-
-func TestBackupCompressingStageHasTitle(t *testing.T) {
- if backupStageTitle(backup.StageCompressing) == "" {
- t.Fatal("the compressing stage has no progress title")
- }
-}
-
-func writeTestBackup(t *testing.T, inst *instance.Instance, release string, at time.Time, scope string) string {
- t.Helper()
- m := backup.Manifest{Format: 1, Release: release, Project: inst.Project(), Domain: inst.Domain(), CreatedAt: at, Reason: "upgrade", Scope: scope, Volumes: []string{}}
- if scope != "" {
- m.Format = backup.FormatVersion
- }
- return writeManifestBackup(t, inst, m)
-}
-
-func writeManifestBackup(t *testing.T, inst *instance.Instance, m backup.Manifest) string {
- t.Helper()
- at := m.CreatedAt
- data, err := json.Marshal(m)
- if err != nil {
- t.Fatal(err)
- }
- var b bytes.Buffer
- b.Write(binary.LittleEndian.AppendUint32(nil, 0x184D2A5E))
- b.Write(binary.LittleEndian.AppendUint32(nil, uint32(len(data)+16)))
- b.Write(data)
- b.Write(binary.LittleEndian.AppendUint64(nil, uint64(len(data))))
- b.WriteString("RXBKMAN1")
- dir := inst.BackupDir()
- if err := os.MkdirAll(dir, 0o700); err != nil {
- t.Fatal(err)
- }
- path := filepath.Join(dir, "fluxer-test-"+at.UTC().Format("20060102-150405")+backup.Extension)
- if err := os.WriteFile(path, b.Bytes(), 0o600); err != nil {
- t.Fatal(err)
- }
- return path
-}
-
-func backupApp(t *testing.T) (*App, *instance.Instance, *bytes.Buffer) {
- t.Helper()
- app, _ := notifyRun(t, false)
- inst, err := instance.Find(app.Flags.Dir)
- if err != nil {
- t.Fatal(err)
- }
- return app, inst, app.UI.Stdout().(*bytes.Buffer)
-}
-
-func remaining(t *testing.T, inst *instance.Instance) []string {
- t.Helper()
- list, err := backup.List(inst.BackupDir())
- if err != nil {
- t.Fatal(err)
- }
- var out []string
- for _, b := range list {
- out = append(out, b.Path)
- }
- return out
-}
-
-func TestPruneKeepsNewestBackupWithUploads(t *testing.T) {
- app, inst, out := backupApp(t)
- inst.State.KeepBackups = 2
- day := time.Date(2026, 10, 1, 4, 0, 0, 0, time.UTC)
- full := writeTestBackup(t, inst, "2026.1001.100000", day, "")
- older := writeTestBackup(t, inst, "2026.1001.100000", day.Add(-24*time.Hour), "")
- var lean []string
- for i := 1; i <= 4; i++ {
- lean = append(lean, writeTestBackup(t, inst, "2026.1001.100000", day.Add(time.Duration(i)*7*24*time.Hour), backup.ScopeWithoutUploads))
- }
- pruneBackups(app, inst)
- got := remaining(t, inst)
- if !slices.Contains(got, full) {
- t.Errorf("the newest backup with uploads was deleted, left %v", got)
- }
- if slices.Contains(got, older) || slices.Contains(got, lean[0]) || slices.Contains(got, lean[1]) {
- t.Errorf("older backups were kept, left %v", got)
- }
- if !slices.Contains(got, lean[3]) || !slices.Contains(got, lean[2]) {
- t.Errorf("the newest backups were deleted, left %v", got)
- }
- want := "Deleted 3 older backups to keep the newest 2. rexctl also keeps the newest backup with uploads and the one rexctl rollback needs."
- if !strings.Contains(out.String(), want) {
- t.Errorf("prune says %q, want %q", out.String(), want)
- }
- out.Reset()
- writeTestBackup(t, inst, "2026.1001.100000", day.Add(5*7*24*time.Hour), "")
- pruneBackups(app, inst)
- if s := out.String(); !strings.Contains(s, "Deleted 2 older backups to keep the newest 2.") || strings.Contains(s, "also keeps") {
- t.Errorf("with nothing kept beyond the count, prune says %q", s)
- }
-}
-
-func TestPruneKeepsBackupForRealPreviousRelease(t *testing.T) {
- app, inst, _ := backupApp(t)
- inst.State.KeepBackups = 1
- day := time.Date(2026, 10, 1, 4, 0, 0, 0, time.UTC)
- stale := writeTestBackup(t, inst, "2026.1001.100000", day, "")
- forB := writeTestBackup(t, inst, "2026.1008.100000", day.Add(7*24*time.Hour), backup.ScopeWithoutUploads)
- writeTestBackup(t, inst, "2026.1015.100000", day.Add(14*24*time.Hour), backup.ScopeWithoutUploads)
- inst.State.PreviousRelease, inst.State.PreviousBackup = "2026.1008.100000", stale
- pruneBackups(app, inst)
- got := remaining(t, inst)
- if !slices.Contains(got, forB) {
- t.Errorf("the backup for the previous release was deleted, left %v", got)
- }
- list, err := backup.List(inst.BackupDir())
- if err != nil {
- t.Fatal(err)
- }
- if b := backupFor(inst, list, inst.State.PreviousRelease); b == nil || b.Path != forB {
- t.Errorf("rollback would restore %v, want %s", b, forB)
- }
-}
-
-func TestPruneKeepsPreviousBackup(t *testing.T) {
- app, inst, _ := backupApp(t)
- inst.State.KeepBackups = 1
- inst.State.PreviousRelease = "2026.1001.100000"
- day := time.Date(2026, 10, 1, 4, 0, 0, 0, time.UTC)
- recorded := writeTestBackup(t, inst, "2026.1001.100000", day, backup.ScopeWithoutUploads)
- later := writeTestBackup(t, inst, "2026.1001.100000", day.Add(time.Hour), backup.ScopeWithoutUploads)
- writeTestBackup(t, inst, "2026.1008.100000", day.Add(48*time.Hour), backup.ScopeWithoutUploads)
- inst.State.PreviousBackup = recorded
- pruneBackups(app, inst)
- got := remaining(t, inst)
- if !slices.Contains(got, recorded) {
- t.Errorf("the backup rollback needs was deleted, left %v", got)
- }
- if slices.Contains(got, later) {
- t.Errorf("a newer backup on the same release was kept over the recorded one, left %v", got)
- }
-}
-
-func TestBackupListMarksWithoutUploads(t *testing.T) {
- app, inst, out := backupApp(t)
- day := time.Date(2026, 10, 1, 4, 0, 0, 0, time.UTC)
- writeTestBackup(t, inst, "2026.1001.100000", day, "")
- writeTestBackup(t, inst, "2026.1001.100000", day.Add(time.Hour), backup.ScopeWithoutUploads)
- if err := runBackupList(app); err != nil {
- t.Fatal(err)
- }
- if !strings.Contains(out.String(), "upgrade, without uploads") || strings.Count(out.String(), "without uploads") != 1 {
- t.Errorf("backup list:\n%s", out.String())
- }
- out.Reset()
- app.Flags.JSON = true
- app.UI = ui.New(ui.Options{Stdin: strings.NewReader(""), Stdout: out, Stderr: out, JSON: true})
- if err := runBackupList(app); err != nil {
- t.Fatal(err)
- }
- var list []map[string]any
- if err := json.Unmarshal(out.Bytes(), &list); err != nil {
- t.Fatalf("%v in %s", err, out.String())
- }
- if len(list) != 2 || list[0]["scope"] != "without-uploads" {
- t.Errorf("JSON list = %s", out.String())
- }
- if _, ok := list[1]["scope"]; ok {
- t.Errorf("a full backup has a scope in %s", out.String())
- }
-}
-
-func TestUploadsRefusalSuggestsOnlyThisInstancesBackup(t *testing.T) {
- _, inst, _ := backupApp(t)
- own := writeTestBackup(t, inst, "2026.1020.100000", time.Date(2026, 10, 12, 4, 0, 0, 0, time.UTC), "")
- other := writeManifestBackup(t, inst, backup.Manifest{Format: backup.FormatVersion, Release: "2026.1020.100000", Project: inst.Project(), Domain: "chat-a.example.com", CreatedAt: time.Date(2026, 10, 20, 4, 0, 0, 0, time.UTC), Reason: "upgrade", Scope: backup.ScopeWithoutUploads, Volumes: []string{}})
- err := checkUploadsInPlace(context.Background(), inst.Dir, inst, nil, other)
- var ee *ui.ExitError
- if !errors.As(err, &ee) || ee.Code != ui.ExitRefused || !errors.Is(err, backup.ErrUploadsNotHere) {
- t.Fatalf("restoring another instance's backup without uploads returned %v", err)
- }
- if strings.Contains(ee.Fix, own) || ee.Fix != "Restore a backup made with rexctl backup." {
- t.Errorf("the refusal for chat-a.example.com says %q", ee.Fix)
- }
- if err := uploadsNotHere(inst, inst.Domain(), inst.Project(), backup.ErrUploadsNotHere); !errors.As(err, &ee) || !strings.Contains(ee.Fix, own) {
- t.Errorf("the refusal for this instance's own backup says %v", err)
- }
-}
diff --git a/fluxer_rexctl/cmd/bundledvoice_test.go b/fluxer_rexctl/cmd/bundledvoice_test.go
deleted file mode 100644
index 1c4cc976d..000000000
--- a/fluxer_rexctl/cmd/bundledvoice_test.go
+++ /dev/null
@@ -1,73 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-package cmd
-
-import (
- "errors"
- "slices"
- "strings"
- "testing"
-
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/host"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/instance"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/settings"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/ui"
-)
-
-func TestInstallWithoutBundledVoiceOpensNoVoicePorts(t *testing.T) {
- in := &installer{f: &installFlags{NoVoice: true}}
- for _, p := range in.firewallPorts() {
- if p.Number == 7881 || p.Number == 7882 {
- t.Fatalf("firewall ports %v include a voice port", in.firewallPorts())
- }
- }
- if got := portList(in.firewallPorts()); got != "80 and 443" {
- t.Fatalf("firewall ports %s", got)
- }
- in = &installer{f: &installFlags{}}
- if got := in.firewallPorts(); !slices.Contains(got, host.Port{Number: 7881, Proto: "tcp"}) || !slices.Contains(got, host.Port{Number: 7882, Proto: "udp"}) {
- t.Fatalf("firewall ports %v leave out the bundled LiveKit", got)
- }
-}
-
-func TestInstallRefusesVoicePortsWithoutBundledVoice(t *testing.T) {
- err := validateInstallFlags(&installFlags{Project: defaultProject, NoVoice: true, VoiceTCPPort: 7883})
- var ee *ui.ExitError
- if !errors.As(err, &ee) || ee.Code != ui.ExitUsage || !strings.Contains(ee.Msg, "--no-bundled-voice") {
- t.Fatalf("got %v", err)
- }
- if err := validateInstallFlags(&installFlags{Project: defaultProject, NoVoice: true}); err != nil {
- t.Fatalf("--no-bundled-voice on its own: %v", err)
- }
-}
-
-func TestBundledServerIDStaysTakenForVoiceAdd(t *testing.T) {
- inst := &instance.Instance{Dir: t.TempDir(), State: &instance.State{Settings: map[string]string{}}}
- if got := takenVoiceIDs(nil, inst); !slices.Contains(got, "default-server-1") {
- t.Fatalf("taken IDs %v leave out the bundled server", got)
- }
- inst.State.Settings["FLUXER_LIVEKIT_DEFAULT_REGION"] = `{"id":"fra","name":"Frankfurt","emoji":"x","latitude":50,"longitude":8}`
- if got := takenVoiceIDs(nil, inst); !slices.Contains(got, "fra-server-1") {
- t.Fatalf("taken IDs %v leave out the bundled server of the fra region", got)
- }
- inst.State.Settings[settings.VoiceBundled] = "false"
- if got := takenVoiceIDs(nil, inst); slices.Contains(got, "fra-server-1") {
- t.Fatalf("taken IDs %v keep the bundled server after it is turned off", got)
- }
-}
-
-func TestLogsWithoutBundledVoiceRefusesTheVoicePart(t *testing.T) {
- inst := &instance.Instance{Dir: t.TempDir(), State: &instance.State{Settings: map[string]string{settings.VoiceBundled: "false"}}}
- _, err := runningPart(inst, []string{"voice"}, []string{"livekit"})
- var ee *ui.ExitError
- if !errors.As(err, &ee) || ee.Code != ui.ExitRefused || !strings.Contains(ee.Msg, "bundled LiveKit") {
- t.Fatalf("got %v", err)
- }
- if got, err := runningPart(inst, []string{"api"}, []string{"api"}); err != nil || !slices.Equal(got, []string{"api"}) {
- t.Fatalf("api part = %v, %v", got, err)
- }
- inst.State.Settings[settings.VoiceBundled] = "true"
- if got, err := runningPart(inst, []string{"voice"}, []string{"livekit"}); err != nil || !slices.Equal(got, []string{"livekit"}) {
- t.Fatalf("voice part with the bundled LiveKit = %v, %v", got, err)
- }
-}
diff --git a/fluxer_rexctl/cmd/config_edit_test.go b/fluxer_rexctl/cmd/config_edit_test.go
deleted file mode 100644
index 3f237224e..000000000
--- a/fluxer_rexctl/cmd/config_edit_test.go
+++ /dev/null
@@ -1,377 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-package cmd
-
-import (
- "bytes"
- "context"
- "encoding/json"
- "errors"
- "io"
- "net/http"
- "net/http/httptest"
- "os"
- "path/filepath"
- "runtime"
- "slices"
- "strings"
- "testing"
-
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/engine"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/instance"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/release"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/settings"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/stack"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/ui"
-)
-
-func editTest(t *testing.T, yes, stopped bool, edits ...func(path string) error) (*App, *instance.Instance, *bytes.Buffer, *int) {
- t.Helper()
- app, inst, out := testInstance(t, yes)
- if stopped {
- inst.State.Stopped = true
- if err := inst.Save(); err != nil {
- t.Fatal(err)
- }
- }
- opened := 0
- prev, prevAsk := openEditor, askEdit
- t.Cleanup(func() { openEditor, askEdit = prev, prevAsk })
- openEditor = func(_ context.Context, path string) error {
- opened++
- if opened > len(edits) {
- t.Errorf("opened the editor %d times", opened)
- return errors.New("too many edits")
- }
- return edits[opened-1](path)
- }
- return app, inst, out, &opened
-}
-
-func write(data string) func(string) error {
- return func(path string) error { return os.WriteFile(path, []byte(data), 0o644) }
-}
-
-func keep(string) error { return nil }
-
-func editedCopies(t *testing.T, inst *instance.Instance) [][]byte {
- t.Helper()
- entries, _ := os.ReadDir(inst.Path(instance.StateDirName, instance.EditedDir))
- var out [][]byte
- for _, e := range entries {
- if strings.HasPrefix(e.Name(), instance.CustomCompose) {
- data, err := os.ReadFile(inst.Path(instance.StateDirName, instance.EditedDir, e.Name()))
- if err != nil {
- t.Fatal(err)
- }
- out = append(out, data)
- }
- }
- return out
-}
-
-func noCustom(t *testing.T, inst *instance.Instance) {
- t.Helper()
- if _, err := os.Stat(inst.Path(instance.CustomCompose)); !errors.Is(err, os.ErrNotExist) {
- t.Fatalf("%s was written: %v", instance.CustomCompose, err)
- }
-}
-
-func TestConfigEditUnderYesStopsAtBrokenDraft(t *testing.T) {
- app, inst, out, opened := editTest(t, true, true, write("services: [\n"))
- err := runConfigEdit(context.Background(), app)
- if exitCode(err) != ui.ExitRefused || *opened != 1 {
- t.Fatalf("err %v after %d edits", err, *opened)
- }
- noCustom(t, inst)
- if copies := editedCopies(t, inst); len(copies) != 1 || string(copies[0]) != "services: [\n" {
- t.Fatalf("kept %q", copies)
- }
- if !strings.Contains(out.String(), "Your draft is in") {
- t.Fatalf("output doesn't say where the draft is:\n%s", out)
- }
-}
-
-func TestConfigEditStopsWhenDraftUnchanged(t *testing.T) {
- app, inst, _, opened := editTest(t, true, true, write("services: [\n"), keep)
- askEdit = func(*ui.UI, string, bool) (bool, error) { return true, nil }
- err := runConfigEdit(context.Background(), app)
- if *opened != 2 || err == nil || !strings.Contains(err.Error(), "Kept "+instance.CustomCompose+" as it was.") {
- t.Fatalf("err %v after %d edits", err, *opened)
- }
- noCustom(t, inst)
-}
-
-func TestConfigEditTakesLockBeforeEditor(t *testing.T) {
- app, inst, _, opened := editTest(t, true, true, write("services: {}\n"))
- l, err := inst.Lock(context.Background())
- if err != nil {
- t.Fatal(err)
- }
- defer l.Release()
- err = runConfigEdit(context.Background(), app)
- if *opened != 0 || exitCode(err) != ui.ExitRefused || !strings.Contains(err.Error(), "Another rexctl command") {
- t.Fatalf("err %v after %d edits", err, *opened)
- }
-}
-
-func TestConfigEditKeepsDraftWhenFileChangedMeanwhile(t *testing.T) {
- var inst *instance.Instance
- var draftPath string
- byHand := []byte("services: {}\n# by hand\n")
- app, inst, out, _ := editTest(t, true, true, func(path string) error {
- draftPath = path
- if err := os.WriteFile(inst.Path(instance.CustomCompose), byHand, 0o644); err != nil {
- return err
- }
- return os.WriteFile(path, []byte("services:\n edge:\n labels:\n team: chat\n"), 0o644)
- })
- swap := filepath.Join(inst.StateDir(), editDir, ".custom.compose.yml.swp")
- if err := os.MkdirAll(filepath.Dir(swap), 0o700); err != nil {
- t.Fatal(err)
- }
- if err := os.WriteFile(swap, []byte("swap"), 0o600); err != nil {
- t.Fatal(err)
- }
- err := runConfigEdit(context.Background(), app)
- if exitCode(err) != ui.ExitRefused || !strings.Contains(err.Error(), "changed while you were editing") {
- t.Fatalf("err %v\n%s", err, out)
- }
- if got, _ := os.ReadFile(inst.Path(instance.CustomCompose)); !bytes.Equal(got, byHand) {
- t.Fatalf("overwrote the hand edit with %q", got)
- }
- if _, err := os.Stat(swap); err != nil {
- t.Fatalf("deleted a file rexctl didn't create: %v", err)
- }
- if draftPath == filepath.Join(inst.StateDir(), editDir, instance.CustomCompose) {
- t.Fatal("every run edits the same draft")
- }
- if copies := editedCopies(t, inst); len(copies) != 1 || !bytes.Contains(copies[0], []byte("team: chat")) {
- t.Fatalf("kept %q", copies)
- }
-}
-
-func TestConfigEditKeepsDraftWhenEditorFails(t *testing.T) {
- saved := "services:\n edge:\n labels:\n team: chat\n"
- app, inst, out, _ := editTest(t, true, true, func(path string) error {
- if err := os.WriteFile(path, []byte(saved), 0o644); err != nil {
- return err
- }
- return errors.New("the editor was killed")
- })
- if err := runConfigEdit(context.Background(), app); err == nil {
- t.Fatal("a failed editor counted as a change")
- }
- noCustom(t, inst)
- if copies := editedCopies(t, inst); len(copies) != 1 || string(copies[0]) != saved {
- t.Fatalf("lost what you saved before the editor failed, kept %q\n%s", copies, out)
- }
-}
-
-func TestConfigEditAsksBeforeDroppingFluxerVolumes(t *testing.T) {
- drop := "services:\n postgres:\n volumes: !reset []\n"
- app, inst, out, _ := editTest(t, true, true, write(drop))
- err := runConfigEdit(context.Background(), app)
- if exitCode(err) != ui.ExitRefused || !strings.Contains(out.String(), "loses the volume") {
- t.Fatalf("err %v\n%s", err, out)
- }
- noCustom(t, inst)
-
- app, inst, out, _ = editTest(t, true, true, write(drop))
- askEdit = func(*ui.UI, string, bool) (bool, error) { return true, nil }
- if err := runConfigEdit(context.Background(), app); err != nil {
- t.Fatalf("%v\n%s", err, out)
- }
- if got, _ := os.ReadFile(inst.Path(instance.CustomCompose)); string(got) != drop {
- t.Fatalf("saved %q", got)
- }
-}
-
-func TestConfigEditWarnsAboutImagesAndManagedVariables(t *testing.T) {
- change := "services:\n api:\n image: example/api:1\n environment:\n FLUXER_DOMAIN: other.example.com\n"
- app, inst, out, _ := editTest(t, true, true, write(change))
- if err := runConfigEdit(context.Background(), app); err != nil {
- t.Fatalf("%v\n%s", err, out)
- }
- for _, want := range []string{"api runs example/api:1", "FLUXER_DOMAIN", "rexctl config set"} {
- if !strings.Contains(out.String(), want) {
- t.Fatalf("output doesn't say %q:\n%s", want, out)
- }
- }
- if got, _ := os.ReadFile(inst.Path(instance.CustomCompose)); string(got) != change {
- t.Fatalf("saved %q", got)
- }
-}
-
-func TestConfigEditReportsDownloadFailureAccurately(t *testing.T) {
- app, inst, out, _ := editTest(t, true, false, write("services:\n edge:\n labels:\n team: chat\n"))
- err := runConfigEdit(context.Background(), app)
- if err == nil || !strings.Contains(err.Error(), "Couldn't download") || strings.Contains(out.String(), "didn't start") {
- t.Fatalf("err %v\n%s", err, out)
- }
- noCustom(t, inst)
-}
-
-func TestStartFailureSaysWhatHappenedToTheFile(t *testing.T) {
- if strings.Contains(startFailure(false), "put the old") || !strings.Contains(startFailure(true), "put the old") {
- t.Fatalf("%q / %q", startFailure(false), startFailure(true))
- }
-}
-
-func TestPlanLinesSayStartsForNewServices(t *testing.T) {
- got := planLines(&engine.Plan{Create: []string{"worker"}, Recreate: []string{"api"}})
- if want := []string{"This restarts api.", "This starts worker."}; !slices.Equal(got, want) {
- t.Fatalf("%q, want %q", got, want)
- }
-}
-
-func TestYAMLProblemNamesTheLine(t *testing.T) {
- _, inst, _ := testInstance(t, true)
- got := checkCustom(context.Background(), inst, "", []byte("services: [\n"))
- if !strings.HasPrefix(got, "Line 2 isn't valid YAML.\n") {
- t.Fatalf("%q", got)
- }
-}
-
-func TestQuickEditorGetsHint(t *testing.T) {
- app, _, out, _ := editTest(t, true, true, keep)
- if err := runConfigEdit(context.Background(), app); err != nil {
- t.Fatal(err)
- }
- if !strings.Contains(out.String(), "If your editor opens a window, use code --wait.") {
- t.Fatalf("no hint:\n%s", out)
- }
-}
-
-func TestEditorRunsThroughTheShell(t *testing.T) {
- if runtime.GOOS == "windows" {
- t.Skip("uses sh")
- }
- dir := filepath.Join(t.TempDir(), "my editor")
- if err := os.MkdirAll(dir, 0o755); err != nil {
- t.Fatal(err)
- }
- script := filepath.Join(dir, "edit.sh")
- if err := os.WriteFile(script, []byte("#!/bin/sh\nprintf '%s' \"$1\" > \"$2\"\n"), 0o755); err != nil {
- t.Fatal(err)
- }
- target := filepath.Join(t.TempDir(), "file")
- if err := editorCmd(context.Background(), "'"+script+"' edited", target).Run(); err != nil {
- t.Fatal(err)
- }
- if got, _ := os.ReadFile(target); string(got) != "edited" {
- t.Fatalf("editor wrote %q", got)
- }
-}
-
-func TestSplitCommandKeepsQuotedPaths(t *testing.T) {
- got := splitCommand(`"C:\Program Files\Notepad++\notepad++.exe" -multiInst`)
- if want := []string{`C:\Program Files\Notepad++\notepad++.exe`, "-multiInst"}; !slices.Equal(got, want) {
- t.Fatalf("%q", got)
- }
-}
-
-func TestNoEditorFound(t *testing.T) {
- if runtime.GOOS == "windows" {
- t.Skip("notepad is always there")
- }
- t.Setenv("VISUAL", "")
- t.Setenv("EDITOR", "")
- t.Setenv("PATH", t.TempDir())
- if editor, ok := editorCommand(); ok {
- t.Fatalf("found %q", editor)
- }
-}
-
-func TestNotificationSaysWhichFilesWerePutBack(t *testing.T) {
- var body []byte
- srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- body, _ = io.ReadAll(r.Body)
- }))
- defer srv.Close()
- app, inst, _ := testInstance(t, true)
- inst.State.NotifyURL = srv.URL
- if err := inst.Save(); err != nil {
- t.Fatal(err)
- }
- path := inst.Generated(stack.ComposeFile)
- data, err := os.ReadFile(path)
- if err != nil {
- t.Fatal(err)
- }
- if err := os.WriteFile(path, append(data, "# mine\n"...), 0o644); err != nil {
- t.Fatal(err)
- }
- if err := app.drift(inst, true, false); err != nil {
- t.Fatal(err)
- }
- app.outcome = "Upgraded to Fluxer 1."
- notifyUpgrade(context.Background(), app, nil)
- var n upgradeNotice
- if err := json.Unmarshal(body, &n); err != nil {
- t.Fatal(err)
- }
- if !strings.Contains(n.Text, "rexctl put back its own "+stack.ComposeFile+". Your copy is in "+inst.Path(instance.StateDirName, instance.EditedDir)) {
- t.Fatalf("notice %q", n.Text)
- }
- if len(instance.UnseenEdits(inst)) != 1 {
- t.Fatal("an unattended put back isn't left for status and doctor to show")
- }
-}
-
-func TestConfigRepairsSettingAfterUpgradePulled(t *testing.T) {
- app, inst, out := testInstance(t, true)
- inst.State.Upgrade = &instance.Upgrade{From: inst.State.Release, To: "2099.1.0", Phase: release.PhasePulled}
- inst.State.Settings[settings.EdgeHTTPPort] = "not-a-port"
- if err := inst.Save(); err != nil {
- t.Fatal(err)
- }
- if err := runConfigChange(context.Background(), app, []configChange{{name: settings.EdgeHTTPPort}}, nil); err != nil {
- t.Fatalf("%v\n%s", err, out)
- }
- found, err := instance.Find(inst.Dir)
- if err != nil {
- t.Fatal(err)
- }
- if _, ok := found.State.Settings[settings.EdgeHTTPPort]; ok {
- t.Fatal("the invalid setting is still there")
- }
- v := "8080"
- if err := runConfigChange(context.Background(), app, []configChange{{name: settings.EdgeHTTPPort, value: &v}}, nil); exitCode(err) != ui.ExitRefused {
- t.Fatalf("changed a valid setting halfway through an upgrade: %v", err)
- }
-}
-
-func TestConfigSetDuringUpgradeChecksPorts(t *testing.T) {
- app, inst, out := testInstance(t, true)
- inst.State.Upgrade = &instance.Upgrade{From: inst.State.Release, To: "2099.1.0", Phase: release.PhaseSelfUpdated}
- if err := inst.Save(); err != nil {
- t.Fatal(err)
- }
- v := "7881"
- err := runConfigChange(context.Background(), app, []configChange{{name: settings.EdgeHTTPPort, value: &v}}, nil)
- if exitCode(err) != ui.ExitRefused || !strings.Contains(err.Error(), "already uses") {
- t.Fatalf("err %v\n%s", err, out)
- }
-}
-
-func TestStatusPointsToCopiesUntilDoctorShowsThem(t *testing.T) {
- app, inst, out := testInstance(t, true)
- dir := inst.Path(instance.StateDirName, instance.EditedDir)
- if err := os.MkdirAll(dir, 0o700); err != nil {
- t.Fatal(err)
- }
- if err := os.WriteFile(filepath.Join(dir, stack.ComposeFile+".20260101-000000"), []byte("mine"), 0o600); err != nil {
- t.Fatal(err)
- }
- _ = runStatus(context.Background(), app)
- if !strings.Contains(out.String(), "Your copies are in "+dir) {
- t.Fatalf("status doesn't point to the copies:\n%s", out)
- }
- instance.SeenEdits(inst)
- out.Reset()
- _ = runStatus(context.Background(), app)
- if strings.Contains(out.String(), "Your copies are in") {
- t.Fatalf("status still points to copies you saw:\n%s", out)
- }
-}
diff --git a/fluxer_rexctl/cmd/config_help_test.go b/fluxer_rexctl/cmd/config_help_test.go
deleted file mode 100644
index d5b58c102..000000000
--- a/fluxer_rexctl/cmd/config_help_test.go
+++ /dev/null
@@ -1,33 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-package cmd
-
-import (
- "strings"
- "testing"
-
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/settings"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/stack"
-)
-
-func TestRawSettingHelp(t *testing.T) {
- set := stack.Embedded()
- raw := 0
- for _, name := range set.Vars {
- k, err := settings.Lookup(set, nil, name, nil)
- if err != nil || k.Kind != settings.Raw {
- continue
- }
- raw++
- help := keyHelp(k)
- if help == "" {
- t.Errorf("rexctl config get %s shows no help", name)
- }
- if strings.Contains(help, "docker compose ") || strings.Contains(help, "Keep this line") {
- t.Errorf("rexctl config get %s shows help for Docker Compose users, got %q", name, help)
- }
- }
- if raw == 0 {
- t.Fatal("no compose setting resolves as a raw setting")
- }
-}
diff --git a/fluxer_rexctl/cmd/email_test.go b/fluxer_rexctl/cmd/email_test.go
deleted file mode 100644
index 78f660aa3..000000000
--- a/fluxer_rexctl/cmd/email_test.go
+++ /dev/null
@@ -1,17 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-package cmd
-
-import (
- "strings"
- "testing"
-)
-
-func TestTLSFixPointsAtPrivateCA(t *testing.T) {
- for _, msg := range []string{"self-signed certificate", "unable to verify the first certificate", "self-signed certificate in certificate chain"} {
- got := tlsFix(msg, "")
- if !strings.Contains(got, "FLUXER_NODE_EXTRA_CA_CERTS") || !strings.Contains(got, "/etc/fluxer/ca/") || !strings.Contains(got, "ca folder") {
- t.Errorf("tlsFix(%q) = %q, want it to explain trusting a private CA with FLUXER_NODE_EXTRA_CA_CERTS", msg, got)
- }
- }
-}
diff --git a/fluxer_rexctl/cmd/fileid_unix_test.go b/fluxer_rexctl/cmd/fileid_unix_test.go
deleted file mode 100644
index 542a5e523..000000000
--- a/fluxer_rexctl/cmd/fileid_unix_test.go
+++ /dev/null
@@ -1,20 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-//go:build !windows
-
-package cmd
-
-import (
- "os"
- "syscall"
- "testing"
-)
-
-func uploadsInode(t *testing.T, path string) uint64 {
- t.Helper()
- info, err := os.Stat(path)
- if err != nil {
- t.Fatal(err)
- }
- return uint64(info.Sys().(*syscall.Stat_t).Ino)
-}
diff --git a/fluxer_rexctl/cmd/fileid_windows_test.go b/fluxer_rexctl/cmd/fileid_windows_test.go
deleted file mode 100644
index 9488ff42f..000000000
--- a/fluxer_rexctl/cmd/fileid_windows_test.go
+++ /dev/null
@@ -1,10 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-package cmd
-
-import "testing"
-
-func uploadsInode(t *testing.T, path string) uint64 {
- t.Helper()
- return 0
-}
diff --git a/fluxer_rexctl/cmd/install_podman_test.go b/fluxer_rexctl/cmd/install_podman_test.go
deleted file mode 100644
index 6bbe413e4..000000000
--- a/fluxer_rexctl/cmd/install_podman_test.go
+++ /dev/null
@@ -1,40 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-package cmd
-
-import (
- "os"
- "path/filepath"
- "runtime"
- "testing"
-)
-
-func TestPodmanDockerWrapper(t *testing.T) {
- if runtime.GOOS != "linux" {
- t.Skip("the podman-docker wrapper only exists on Linux")
- }
- dir := t.TempDir()
- write := func(name, body string) string {
- p := filepath.Join(dir, name)
- if err := os.WriteFile(p, []byte(body), 0o755); err != nil {
- t.Fatal(err)
- }
- return p
- }
- podman := write("podman", "\x7fELF")
- link := filepath.Join(dir, "docker-link")
- if err := os.Symlink(podman, link); err != nil {
- t.Fatal(err)
- }
- cases := map[string]bool{
- write("docker-wrapper", "#!/bin/sh\n[ -e /etc/containers/nodocker ] || echo emulate\nexec /usr/bin/podman \"$@\"\n"): true,
- link: true,
- write("docker", "\x7fELF real docker"): false,
- write("docker-other-script", "#!/bin/sh\nexec /usr/libexec/docker/cli \"$@\"\n"): false,
- }
- for path, want := range cases {
- if got := podmanDockerWrapper(path); got != want {
- t.Errorf("podmanDockerWrapper(%s) = %v, want %v", filepath.Base(path), got, want)
- }
- }
-}
diff --git a/fluxer_rexctl/cmd/install_proxy_test.go b/fluxer_rexctl/cmd/install_proxy_test.go
deleted file mode 100644
index 8eb6494a0..000000000
--- a/fluxer_rexctl/cmd/install_proxy_test.go
+++ /dev/null
@@ -1,69 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-package cmd
-
-import (
- "bytes"
- "strings"
- "testing"
-
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/ui"
-)
-
-func TestProxyHintOffer(t *testing.T) {
- cases := []struct {
- name string
- hint proxyHint
- ok bool
- def bool
- reason string
- }{
- {"nothing in the way", proxyHint{Interactive: true}, false, false, ""},
- {"not interactive", proxyHint{Busy: []int{443}, LowPorts: "Podman"}, false, false, ""},
- {"flag already decides", proxyHint{Interactive: true, Decided: true, Busy: []int{80, 443}}, false, false, ""},
- {"one port busy", proxyHint{Interactive: true, Busy: []int{443}}, true, true, "Port 443 on this machine is already in use."},
- {"both ports busy by a program", proxyHint{Interactive: true, Busy: []int{80, 443}, Owner: "caddy"}, true, true, "Ports 80 and 443 on this machine are already in use by caddy."},
- {"busy by a container", proxyHint{Interactive: true, Busy: []int{80}, Owner: "docker-proxy"}, true, true, "Port 80 on this machine is already in use by a container."},
- {"busy wins over low ports", proxyHint{Interactive: true, Busy: []int{443}, LowPorts: "Podman"}, true, true, "Port 443 on this machine is already in use."},
- {"rootless podman", proxyHint{Interactive: true, LowPorts: "Podman"}, true, false, "Rootless Podman can't use ports 80 and 443 without a change to this machine."},
- }
- for _, c := range cases {
- reason, def, ok := c.hint.offer()
- if ok != c.ok || def != c.def || reason != c.reason {
- t.Errorf("%s: got (%q, %v, %v), want (%q, %v, %v)", c.name, reason, def, ok, c.reason, c.def, c.ok)
- }
- }
-}
-
-func TestValidateBind(t *testing.T) {
- for v, ok := range map[string]bool{
- "127.0.0.1:8080": true,
- "[::1]:8080": true,
- ":8080": true,
- "127.0.0.1": false,
- "": false,
- } {
- if err := validateBind(v); (err == nil) != ok {
- t.Errorf("%q: got %v", v, err)
- }
- }
-}
-
-func TestOfferProxyNonInteractive(t *testing.T) {
- for _, yes := range []bool{false, true} {
- var out bytes.Buffer
- app := &App{UI: ui.New(ui.Options{Stdin: strings.NewReader("y\n"), Stdout: &out, Stderr: &out, Yes: yes})}
- c := newInstallCmd(app)
- if err := c.ParseFlags(nil); err != nil {
- t.Fatal(err)
- }
- f := &installFlags{Bind: "127.0.0.1:8080"}
- in := &installer{app: app, c: c, f: f, ran: map[string]bool{}}
- if err := in.offerProxy(); err != nil {
- t.Fatalf("yes=%v: %v", yes, err)
- }
- if in.offered || f.BehindProxy || len(in.plan) > 0 || out.Len() > 0 {
- t.Errorf("yes=%v: offered=%v behind=%v plan=%q output=%q", yes, in.offered, f.BehindProxy, in.plan, out.String())
- }
- }
-}
diff --git a/fluxer_rexctl/cmd/install_storage_test.go b/fluxer_rexctl/cmd/install_storage_test.go
deleted file mode 100644
index 4da2a2577..000000000
--- a/fluxer_rexctl/cmd/install_storage_test.go
+++ /dev/null
@@ -1,26 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-package cmd
-
-import "testing"
-
-func TestValidStorageEndpoint(t *testing.T) {
- for v, ok := range map[string]bool{
- "https://s3.example.com": true,
- "http://192.168.1.20:9000": true,
- "http://localhost:9000": false,
- "http://minio.localhost:9000": false,
- "http://127.0.0.1:9000": false,
- "http://[::1]:9000": false,
- "http://[::ffff:127.0.0.1]:9000": false,
- "http://169.254.169.254": false,
- "http://0.0.0.0:9000": false,
- "http://[::]:9000": false,
- "https://user:[email protected]": false,
- "ftp://s3.example.com": false,
- } {
- if err := validStorageEndpoint(v); (err == nil) != ok {
- t.Errorf("%s: got %v", v, err)
- }
- }
-}
diff --git a/fluxer_rexctl/cmd/install_voice_test.go b/fluxer_rexctl/cmd/install_voice_test.go
deleted file mode 100644
index e943452da..000000000
--- a/fluxer_rexctl/cmd/install_voice_test.go
+++ /dev/null
@@ -1,37 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-package cmd
-
-import "testing"
-
-func TestPickVoicePairDefaultFree(t *testing.T) {
- tcp, udp := pickVoicePair(func(int, string) bool { return true })
- if tcp != 7881 || udp != 7882 {
- t.Errorf("all free = %d/%d, want 7881/7882", tcp, udp)
- }
-}
-
-func TestPickVoicePairStepsByTwo(t *testing.T) {
- busy := map[int]bool{7881: true, 7882: true}
- tcp, udp := pickVoicePair(func(n int, _ string) bool { return !busy[n] })
- if tcp != 7883 || udp != 7884 {
- t.Errorf("default pair busy = %d/%d, want 7883/7884", tcp, udp)
- }
- busy[7883], busy[7884] = true, true
- tcp, udp = pickVoicePair(func(n int, _ string) bool { return !busy[n] })
- if tcp != 7885 || udp != 7886 {
- t.Errorf("two pairs busy = %d/%d, want 7885/7886", tcp, udp)
- }
-}
-
-func TestPickVoicePairNeedsBothSides(t *testing.T) {
- tcp, udp := pickVoicePair(func(n int, proto string) bool {
- if proto == "udp" && n == 7882 {
- return false
- }
- return true
- })
- if tcp != 7883 || udp != 7884 {
- t.Errorf("udp side of default busy = %d/%d, want 7883/7884", tcp, udp)
- }
-}
diff --git a/fluxer_rexctl/cmd/layout_test.go b/fluxer_rexctl/cmd/layout_test.go
deleted file mode 100644
index 97f4b5e40..000000000
--- a/fluxer_rexctl/cmd/layout_test.go
+++ /dev/null
@@ -1,168 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-package cmd
-
-import (
- "bytes"
- "context"
- "errors"
- "os"
- "path/filepath"
- "strings"
- "testing"
-
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/engine"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/instance"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/release"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/secrets"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/settings"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/stack"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/ui"
-)
-
-func testInstance(t *testing.T, yes bool) (*App, *instance.Instance, *bytes.Buffer) {
- t.Helper()
- inst, err := instance.Create(t.TempDir(), "fluxer")
- if err != nil {
- t.Fatal(err)
- }
- set := stack.Embedded()
- inst.State.Release = set.Release
- inst.State.Settings[settings.Domain] = "chat.example.com"
- if _, err := secrets.Mint(inst.State.Secrets, false); err != nil {
- t.Fatal(err)
- }
- r, err := stack.Render(set, nil, inst.State.Images.Refs, inst.Project(), inst.Dir)
- if err != nil {
- t.Fatal(err)
- }
- inst.State.Rendered = r.Hashes
- if err := inst.Save(); err != nil {
- t.Fatal(err)
- }
- out := &bytes.Buffer{}
- app := &App{
- Flags: GlobalFlags{Dir: inst.Dir, Yes: yes},
- UI: ui.New(ui.Options{Yes: yes, Stdin: strings.NewReader(""), Stdout: out, Stderr: out}),
- engine: &engine.Engine{Kind: engine.Docker},
- }
- return app, inst, out
-}
-
-func exitCode(err error) int {
- var ee *ui.ExitError
- if errors.As(err, &ee) {
- return ee.Code
- }
- return -1
-}
-
-func TestEjectExplainsAndRefusesWithoutYes(t *testing.T) {
- app, inst, out := testInstance(t, false)
- err := runEject(context.Background(), app)
- if code := exitCode(err); code != ui.ExitUsage {
- t.Fatalf("exit code %d (%v), want %d", code, err, ui.ExitUsage)
- }
- for _, want := range []string{"You probably don't need to eject.", "rexctl config set changes settings", "rexctl config list shows them", "FLUXER_*", "run rexctl takeover, rexctl upgrade and rexctl eject", "rexctl config edit", instance.CaddyDropInDir, changeHowFluxerRunsURL, "stops managing the instance"} {
- if !strings.Contains(out.String(), want) {
- t.Fatalf("output doesn't say %q:\n%s", want, out)
- }
- }
- if strings.Contains(out.String(), "config list and") || strings.Contains(out.String(), "upgrade Fluxer with") {
- t.Fatalf("output says config list changes settings or that you upgrade with compose yourself:\n%s", out)
- }
- found, err := instance.Find(inst.Dir)
- if err != nil || found.State.Ejected != nil {
- t.Fatalf("ejected without asking: %v", err)
- }
- if _, err := os.Stat(inst.Path(stack.ComposeFile)); !errors.Is(err, os.ErrNotExist) {
- t.Fatal("eject wrote files before asking")
- }
-}
-
-func TestConfigUnsetRepairsSettingDuringUnfinishedUpgrade(t *testing.T) {
- app, inst, out := testInstance(t, true)
- inst.State.Upgrade = &instance.Upgrade{From: inst.State.Release, To: "2099.1.0", Phase: release.PhaseSelfUpdated}
- inst.State.Settings[settings.EdgeHTTPPort] = "not-a-port"
- if err := inst.Save(); err != nil {
- t.Fatal(err)
- }
- if _, err := app.Instance(); exitCode(err) != ui.ExitRefused {
- t.Fatalf("loaded an invalid setting: %v", err)
- }
- if err := runConfigChange(context.Background(), app, []configChange{{name: settings.EdgeHTTPPort}}, nil); err != nil {
- t.Fatalf("%v\n%s", err, out)
- }
- found, err := instance.Find(inst.Dir)
- if err != nil {
- t.Fatal(err)
- }
- if _, ok := found.State.Settings[settings.EdgeHTTPPort]; ok {
- t.Fatal("the invalid setting is still there")
- }
- if found.State.Upgrade == nil || found.State.Upgrade.Phase != release.PhaseSelfUpdated {
- t.Fatal("the repair changed the upgrade")
- }
- if !strings.Contains(out.String(), "rexctl upgrade uses the new setting when it finishes.") || strings.Contains(out.String(), "the next time it starts") {
- t.Fatalf("output doesn't say once that the upgrade uses it:\n%s", out)
- }
-}
-
-func TestConfigEditKeepsFileUntilItWorks(t *testing.T) {
- app, inst, out := testInstance(t, true)
- inst.State.Stopped = true
- if err := inst.Save(); err != nil {
- t.Fatal(err)
- }
- edits := []string{"services: [\n", "services:\n edge:\n build: .\n", "services:\n edge:\n labels:\n team: chat\n"}
- var opened int
- prev, prevAsk := openEditor, askEdit
- t.Cleanup(func() { openEditor, askEdit = prev, prevAsk })
- askEdit = func(*ui.UI, string, bool) (bool, error) { return true, nil }
- openEditor = func(_ context.Context, path string) error {
- before, err := os.ReadFile(path)
- if err != nil {
- return err
- }
- if opened == 0 && string(before) != instance.CustomTemplate {
- t.Errorf("first edit started from %q", before)
- }
- if _, err := os.Stat(inst.Path(instance.CustomCompose)); !errors.Is(err, os.ErrNotExist) {
- t.Errorf("the file changed before it passed the check")
- }
- opened++
- return os.WriteFile(path, []byte(edits[opened-1]), 0o644)
- }
- if err := runConfigEdit(context.Background(), app); err != nil {
- t.Fatalf("%v\n%s", err, out)
- }
- if opened != len(edits) {
- t.Fatalf("opened the editor %d times, want %d", opened, len(edits))
- }
- got, err := os.ReadFile(inst.Path(instance.CustomCompose))
- if err != nil || string(got) != edits[len(edits)-1] {
- t.Fatalf("saved %q, %v", got, err)
- }
- if left, _ := os.ReadDir(filepath.Join(inst.StateDir(), editDir)); len(left) > 0 {
- t.Fatalf("left the draft behind: %v", left)
- }
-}
-
-func TestConfigEditWithoutAnswerKeepsFile(t *testing.T) {
- app, inst, _ := testInstance(t, false)
- mine := []byte("services: {}\n")
- if err := os.WriteFile(inst.Path(instance.CustomCompose), mine, 0o644); err != nil {
- t.Fatal(err)
- }
- prev := openEditor
- t.Cleanup(func() { openEditor = prev })
- openEditor = func(_ context.Context, path string) error {
- return os.WriteFile(path, []byte("services: [\n"), 0o644)
- }
- if err := runConfigEdit(context.Background(), app); err == nil {
- t.Fatal("applied a broken file")
- }
- if got, _ := os.ReadFile(inst.Path(instance.CustomCompose)); !bytes.Equal(got, mine) {
- t.Fatalf("file changed to %q", got)
- }
-}
diff --git a/fluxer_rexctl/cmd/migrate_test.go b/fluxer_rexctl/cmd/migrate_test.go
deleted file mode 100644
index d61c8a32e..000000000
--- a/fluxer_rexctl/cmd/migrate_test.go
+++ /dev/null
@@ -1,266 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-package cmd
-
-import (
- "bytes"
- "context"
- "encoding/json"
- "errors"
- "fmt"
- "net/http"
- "net/http/httptest"
- "os"
- "path/filepath"
- "runtime"
- "strings"
- "testing"
-
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/engine"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/instance"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/release"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/stack"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/ui"
-)
-
-func oldInstance(t *testing.T, yes bool) (*App, *instance.Instance, *bytes.Buffer) {
- t.Helper()
- app, inst, out := testInstance(t, yes)
- for name := range inst.State.Rendered {
- plain := stack.Plain(name, readFile(t, inst.Generated(name)))
- if err := os.WriteFile(inst.Path(name), plain, 0o644); err != nil {
- t.Fatal(err)
- }
- inst.State.Rendered[name] = stack.Hash(plain)
- }
- if err := os.RemoveAll(stack.GeneratedPath(inst.Dir)); err != nil {
- t.Fatal(err)
- }
- if err := inst.Save(); err != nil {
- t.Fatal(err)
- }
- data := bytes.Replace(readFile(t, inst.StatePath()), fmt.Appendf(nil, `"schema": %d`, instance.StateSchema), []byte(`"schema": 2`), 1)
- if err := os.WriteFile(inst.StatePath(), data, 0o600); err != nil {
- t.Fatal(err)
- }
- old, err := instance.Find(inst.Dir)
- if err != nil || !old.OldLayout() {
- t.Fatalf("the fixture isn't on the old layout: %v", err)
- }
- stubUnits(t, func() error { return nil })
- return app, old, out
-}
-
-func stubUnits(t *testing.T, fn func() error) {
- t.Helper()
- prev := refreshUnitBinaries
- t.Cleanup(func() { refreshUnitBinaries = prev })
- refreshUnitBinaries = func(context.Context, *instance.Instance) error { return fn() }
-}
-
-func readFile(t *testing.T, path string) []byte {
- t.Helper()
- data, err := os.ReadFile(path)
- if err != nil {
- t.Fatal(err)
- }
- return data
-}
-
-func schemaOnDisk(t *testing.T, inst *instance.Instance) int {
- t.Helper()
- var head struct{ Schema int }
- if err := json.Unmarshal(readFile(t, inst.StatePath()), &head); err != nil {
- t.Fatal(err)
- }
- return head.Schema
-}
-
-func requireOldLayout(t *testing.T, inst *instance.Instance) {
- t.Helper()
- if s := schemaOnDisk(t, inst); s != 2 {
- t.Fatalf("schema on disk %d, want 2", s)
- }
- if _, err := os.Stat(inst.Path(stack.ComposeFile)); err != nil {
- t.Fatalf("the compose file left the instance folder: %v", err)
- }
- if _, err := os.Stat(stack.GeneratedPath(inst.Dir)); !errors.Is(err, os.ErrNotExist) {
- t.Fatal("a read made the generated folder")
- }
-}
-
-func serveRelease(t *testing.T, rel release.Release) {
- t.Helper()
- srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
- _ = json.NewEncoder(w).Encode(rel)
- }))
- t.Cleanup(srv.Close)
- t.Setenv(release.ResolverURLEnv, srv.URL)
-}
-
-func TestReadsLeaveTheOldLayout(t *testing.T) {
- app, inst, out := oldInstance(t, true)
- serveRelease(t, release.Release{Version: "2099.101.0", StateSchema: instance.StateSchema, Assets: []release.Asset{{OS: runtime.GOOS, Arch: runtime.GOARCH}}})
- ctx := context.Background()
- for name, run := range map[string]func() error{
- "instance": func() error { _, err := app.Instance(); return err },
- "config get": func() error { _, err := loadConfigView(app, nil); return err },
- "upgrade --check": func() error { return runUpgrade(ctx, app, &upgradeFlags{Check: true}) },
- "upgrade --dry-run": func() error { return runUpgrade(ctx, app, &upgradeFlags{DryRun: true}) },
- "declined upgrade": func() error {
- app.UI = ui.New(ui.Options{Stdin: strings.NewReader("n\n"), Stdout: out, Stderr: out})
- return runUpgrade(ctx, app, &upgradeFlags{})
- },
- } {
- if err := run(); err != nil && exitCode(err) == -1 {
- t.Fatalf("%s: %v\n%s", name, err, out)
- }
- requireOldLayout(t, inst)
- }
-}
-
-func TestOldLayoutLoadsWhileAnotherCommandHoldsIt(t *testing.T) {
- app, inst, _ := oldInstance(t, true)
- l, err := inst.Lock(context.Background())
- if err != nil {
- t.Fatal(err)
- }
- defer l.Release()
- if _, err := app.Instance(); err != nil {
- t.Fatalf("status refused while another command holds the instance: %v", err)
- }
- found, err := bootInstance(app)
- if err != nil || found == nil {
- t.Fatalf("boot start gave up before waiting for the lock: %v", err)
- }
- requireOldLayout(t, inst)
-}
-
-func TestChangeMovesAfterRefreshingUnitCopies(t *testing.T) {
- app, inst, _ := oldInstance(t, true)
- var schemaThen int
- stubUnits(t, func() error {
- schemaThen = schemaOnDisk(t, inst)
- return nil
- })
- if err := app.Locked(context.Background(), inst, func() error { return nil }); err != nil {
- t.Fatal(err)
- }
- if schemaThen != 2 {
- t.Fatalf("refreshed the unit copies with schema %d on disk, want 2", schemaThen)
- }
- if s := schemaOnDisk(t, inst); s != instance.StateSchema {
- t.Fatalf("schema on disk %d after a change, want %d", s, instance.StateSchema)
- }
- if _, err := os.Stat(inst.Generated(stack.ComposeFile)); err != nil || inst.OldLayout() {
- t.Fatalf("the compose file didn't move: %v", err)
- }
-}
-
-func TestChangeKeepsOldLayoutWhenUnitCopiesCantBeRefreshed(t *testing.T) {
- app, inst, _ := oldInstance(t, true)
- stubUnits(t, func() error { return errors.New("sudo: a password is required") })
- ran := false
- if err := app.Locked(context.Background(), inst, func() error { ran = true; return nil }); err != nil {
- t.Fatal(err)
- }
- if !ran {
- t.Fatal("the command didn't run")
- }
- requireOldLayout(t, inst)
-}
-
-func TestRootGuardRunsBeforeMoving(t *testing.T) {
- if runtime.GOOS == "windows" {
- t.Skip("no root on Windows")
- }
- app, inst, _ := oldInstance(t, true)
- if uid, ok := inst.OwnerUID(); !ok || uid == 0 {
- t.Skip("the test folder belongs to root")
- }
- inst.State.Engine = instance.EngineRef{Kind: string(engine.Podman)}
- prev := euid
- t.Cleanup(func() { euid = prev })
- euid = func() int { return 0 }
- stubUnits(t, func() error { t.Error("refreshed unit copies as root"); return nil })
- if err := app.Locked(context.Background(), inst, func() error { return nil }); exitCode(err) != ui.ExitRefused {
- t.Fatalf("got %v, want the rootless refusal", err)
- }
- requireOldLayout(t, inst)
-}
-
-func TestUpgradeToAnOlderSchemaReleaseKeepsTheOldLayout(t *testing.T) {
- app, inst, out := oldInstance(t, true)
- app.Version = "2099.100.0"
- serveRelease(t, release.Release{Version: "2099.101.0", StateSchema: 2, Assets: []release.Asset{{OS: runtime.GOOS, Arch: runtime.GOARCH, URL: "https://example.invalid/rexctl.tar.gz", SHA256: strings.Repeat("0", 64)}}})
- prevUpdate, prevReexec := selfUpdate, reexec
- t.Cleanup(func() { selfUpdate, reexec = prevUpdate, prevReexec })
- updated := false
- selfUpdate = func(context.Context, release.Asset) error {
- updated = true
- requireOldLayout(t, inst)
- return nil
- }
- reexec = func([]string) error { return nil }
- if err := runUpgrade(context.Background(), app, &upgradeFlags{}); err != nil {
- t.Fatalf("%v\n%s", err, out)
- }
- if !updated {
- t.Fatalf("rexctl didn't switch to the release:\n%s", out)
- }
- requireOldLayout(t, inst)
- if _, err := os.Stat(filepath.Join(inst.Dir, stack.Caddyfile)); err != nil {
- t.Fatal(err)
- }
-}
-
-func TestStatusAndDoctorSayAnEditedRootCaddyfileIsUnused(t *testing.T) {
- app, inst, out := oldInstance(t, true)
- ctx := context.Background()
- if err := app.Locked(ctx, inst, func() error { return nil }); err != nil {
- t.Fatal(err)
- }
- if err := os.WriteFile(inst.Path(stack.Caddyfile), []byte(":443 {\n}\n"), 0o644); err != nil {
- t.Fatal(err)
- }
- compose := inst.Generated(stack.ComposeFile)
- if err := os.WriteFile(compose, stack.Managed(stack.ComposeFile, stack.Plain(stack.ComposeFile, readFile(t, compose))), 0o644); err != nil {
- t.Fatal(err)
- }
- if err := inst.DropRootCopies(ctx, true); err != nil {
- t.Fatal(err)
- }
- warnUnusedRootFiles(ctx, app, inst)
- lines := strings.Split(strings.TrimSpace(out.String()), "\n")
- last := lines[len(lines)-1]
- if len(lines) == 0 || !strings.Contains(last, "no longer uses "+inst.Path(stack.Caddyfile)) || !strings.Contains(last, instance.CaddyDropInDir+"/") {
- t.Fatalf("output:\n%s", out)
- }
-}
-
-func TestStateWithVoiceServersRefusesARexctlThatWouldDropThem(t *testing.T) {
- inst, err := instance.Create(t.TempDir(), "fluxer")
- if err != nil {
- t.Fatal(err)
- }
- inst.State.Voice = []instance.VoiceServer{{ID: "fra-server-1"}}
- if err := inst.Save(); err != nil {
- t.Fatal(err)
- }
- saved, err := instance.Find(inst.Dir)
- if err != nil {
- t.Fatal(err)
- }
- if saved.State.Schema != instance.StateSchema || instance.StateSchema <= instance.LayoutSchema {
- t.Fatalf("saved schema %d, layout schema %d", saved.State.Schema, instance.LayoutSchema)
- }
- older := &release.Release{Version: "2026.1029.100000", StateSchema: instance.LayoutSchema}
- if err := release.CheckTarget(nil, older, saved.State.Schema); !errors.Is(err, release.ErrOlderSchema) {
- t.Fatalf("CheckTarget = %v, want ErrOlderSchema", err)
- }
- data := bytes.Replace(readFile(t, saved.StatePath()), fmt.Appendf(nil, `"schema": %d`, instance.StateSchema), fmt.Appendf(nil, `"schema": %d`, instance.LayoutSchema), 1)
- s, err := instance.ParseState(data, inst.Dir)
- if err != nil || s.Schema != instance.StateSchema || len(s.Voice) != 1 {
- t.Fatalf("state from the layout schema = %+v, %v", s, err)
- }
-}
diff --git a/fluxer_rexctl/cmd/search_test.go b/fluxer_rexctl/cmd/search_test.go
deleted file mode 100644
index c7d3f62d8..000000000
--- a/fluxer_rexctl/cmd/search_test.go
+++ /dev/null
@@ -1,21 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-package cmd
-
-import "testing"
-
-func TestOlderSearch(t *testing.T) {
- for _, c := range []struct {
- to, from string
- want bool
- }{
- {"getmeili/meilisearch:v1.12", "getmeili/meilisearch:v1.53", true},
- {"getmeili/meilisearch:v1.53", "getmeili/meilisearch:v1.12", false},
- {"getmeili/meilisearch:v1.53.3", "docker.io/getmeili/meilisearch:v1.53@sha256:abc", false},
- {"registry:5000/meilisearch", "getmeili/meilisearch:v1.53", true},
- } {
- if got := olderSearch(c.to, c.from); got != c.want {
- t.Errorf("olderSearch(%q, %q) = %v, want %v", c.to, c.from, got, c.want)
- }
- }
-}
diff --git a/fluxer_rexctl/cmd/sites_test.go b/fluxer_rexctl/cmd/sites_test.go
deleted file mode 100644
index c47dba491..000000000
--- a/fluxer_rexctl/cmd/sites_test.go
+++ /dev/null
@@ -1,189 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-package cmd
-
-import (
- "bytes"
- "os"
- "path/filepath"
- "slices"
- "strings"
- "testing"
-
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/instance"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/stack"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/ui"
-)
-
-const (
- legacyCaddyfile = "{\n\temail [email protected]\n}\n\nimport /etc/caddy/conf.d/*.caddy\n\n{$FLUXER_DOMAIN} {\n\treverse_proxy app:8080\n}\n"
- mastodonSite = "mastodon.tails.ch {\n\treverse_proxy 10.0.4.22:3000\n}\n"
- importingSite = "import common\nwiki.tails.ch {\n\trespond ok\n}\n"
-)
-
-func sitesInstance(t *testing.T, release string, caddyfile []byte) (*App, *instance.Instance, *bytes.Buffer) {
- t.Helper()
- inst, err := instance.Create(t.TempDir(), "fluxer")
- if err != nil {
- t.Fatal(err)
- }
- inst.State.Release = release
- if caddyfile != nil {
- compose, err := stack.ReadFile(stack.Embedded(), stack.ComposeFile)
- if err != nil {
- t.Fatal(err)
- }
- writeFile(t, filepath.Join(inst.SetDir(release), stack.ComposeFile), compose)
- writeFile(t, filepath.Join(inst.SetDir(release), stack.Caddyfile), caddyfile)
- }
- if err := inst.Save(); err != nil {
- t.Fatal(err)
- }
- out := &bytes.Buffer{}
- app := &App{UI: ui.New(ui.Options{Stdin: strings.NewReader(""), Stdout: out, Stderr: out})}
- return app, inst, out
-}
-
-func writeFile(t *testing.T, path string, data []byte) {
- t.Helper()
- if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
- t.Fatal(err)
- }
- if err := os.WriteFile(path, data, 0o644); err != nil {
- t.Fatal(err)
- }
-}
-
-func caddyFilesIn(t *testing.T, dir string) []string {
- t.Helper()
- matches, err := filepath.Glob(filepath.Join(dir, "*.caddy"))
- if err != nil {
- t.Fatal(err)
- }
- var out []string
- for _, m := range matches {
- out = append(out, filepath.Base(m))
- }
- return out
-}
-
-func TestRollbackToLegacyMovesSitesBackAndUpgradeMovesThemAgain(t *testing.T) {
- app, inst, out := sitesInstance(t, stack.LegacyRelease, []byte(legacyCaddyfile))
- writeFile(t, inst.Path(instance.CaddySitesDir, "Mastodon.caddy"), []byte(mastodonSite))
- writeFile(t, inst.Path(instance.CaddySitesDir, "wiki.caddy"), []byte(importingSite))
- if err := matchSites(app, inst); err != nil {
- t.Fatal(err)
- }
- want := []string{"Mastodon.caddy", "wiki.caddy"}
- if got := caddyFilesIn(t, inst.Path(instance.CaddyDropInDir)); !slices.Equal(got, want) {
- t.Fatalf("caddy.d has %v, want %v", got, want)
- }
- if got := caddyFilesIn(t, inst.Path(instance.CaddySitesDir)); len(got) > 0 {
- t.Fatalf("caddy.d/sites still has %v", got)
- }
- if !slices.Equal(inst.State.MovedSites, want) {
- t.Fatalf("recorded %v, want %v", inst.State.MovedSites, want)
- }
- if !strings.Contains(out.String(), "Moved caddy.d/sites/Mastodon.caddy to caddy.d/Mastodon.caddy.") {
- t.Fatalf("output %q", out.String())
- }
- saved, err := instance.Find(inst.Dir)
- if err != nil {
- t.Fatal(err)
- }
- if !slices.Equal(saved.State.MovedSites, want) {
- t.Fatalf("saved record %v, want %v", saved.State.MovedSites, want)
- }
-
- inst.State.Release = stack.Embedded().Release
- inst.State.Upgrade = &instance.Upgrade{From: stack.LegacyRelease, To: inst.State.Release}
- if err := moveSites(app, inst); err != nil {
- t.Fatal(err)
- }
- if got := caddyFilesIn(t, inst.Path(instance.CaddySitesDir)); !slices.Equal(got, want) {
- t.Fatalf("caddy.d/sites has %v after the upgrade, want %v", got, want)
- }
- if !slices.Equal(inst.State.Upgrade.Sites, want) {
- t.Fatalf("upgrade record %v, want %v", inst.State.Upgrade.Sites, want)
- }
-
- clearUpgrade(inst)
- if got := caddyFilesIn(t, inst.Path(instance.CaddyDropInDir)); !slices.Equal(got, want) {
- t.Fatalf("caddy.d has %v after a stopped upgrade, want %v", got, want)
- }
- if !slices.Equal(inst.State.MovedSites, want) {
- t.Fatalf("record after a stopped upgrade %v, want %v", inst.State.MovedSites, want)
- }
-}
-
-func TestRollbackToReleaseWithSitesLeavesThemPut(t *testing.T) {
- app, inst, out := sitesInstance(t, stack.Embedded().Release, nil)
- writeFile(t, inst.Path(instance.CaddySitesDir, "Mastodon.caddy"), []byte(mastodonSite))
- if err := matchSites(app, inst); err != nil {
- t.Fatal(err)
- }
- if got := caddyFilesIn(t, inst.Path(instance.CaddySitesDir)); !slices.Equal(got, []string{"Mastodon.caddy"}) {
- t.Fatalf("caddy.d/sites has %v", got)
- }
- if got := caddyFilesIn(t, inst.Path(instance.CaddyDropInDir)); len(got) > 0 {
- t.Fatalf("caddy.d has %v", got)
- }
- if len(inst.State.MovedSites) > 0 || out.Len() > 0 {
- t.Fatalf("recorded %v, output %q", inst.State.MovedSites, out.String())
- }
-}
-
-func TestGoingForwardToReleaseWithSitesRestoresRecordedFiles(t *testing.T) {
- app, inst, _ := sitesInstance(t, stack.Embedded().Release, nil)
- writeFile(t, inst.Path(instance.CaddyDropInDir, "wiki.caddy"), []byte(importingSite))
- inst.State.MovedSites = []string{"wiki.caddy"}
- if err := matchSites(app, inst); err != nil {
- t.Fatal(err)
- }
- if got := caddyFilesIn(t, inst.Path(instance.CaddySitesDir)); !slices.Equal(got, []string{"wiki.caddy"}) {
- t.Fatalf("caddy.d/sites has %v", got)
- }
- if inst.State.MovedSites != nil {
- t.Fatalf("record %v left", inst.State.MovedSites)
- }
-}
-
-func TestRollbackToReleaseWithoutSitesImportLeavesThemPut(t *testing.T) {
- data, err := stack.ReadFile(stack.Embedded(), stack.Caddyfile)
- if err != nil {
- t.Fatal(err)
- }
- older := bytes.Replace(data, []byte("\nimport /etc/caddy/conf.d/sites/*.caddy\n"), nil, 1)
- if bytes.Equal(older, data) {
- t.Fatal("the shipped Caddyfile has no sites import to take out")
- }
- app, inst, out := sitesInstance(t, "2026.1029.100000", older)
- writeFile(t, inst.Path(instance.CaddySitesDir, "Mastodon.caddy"), []byte(mastodonSite))
- if err := matchSites(app, inst); err != nil {
- t.Fatal(err)
- }
- if got := caddyFilesIn(t, inst.Path(instance.CaddySitesDir)); !slices.Equal(got, []string{"Mastodon.caddy"}) {
- t.Fatalf("caddy.d/sites has %v", got)
- }
- if len(inst.State.MovedSites) > 0 {
- t.Fatalf("recorded %v", inst.State.MovedSites)
- }
- if !strings.Contains(out.String(), "doesn't load caddy.d/sites") {
- t.Fatalf("output %q", out.String())
- }
-}
-
-func TestRestoredLegacyBackupLoadsSitesFromCaddyDropIns(t *testing.T) {
- app, inst, _ := sitesInstance(t, stack.LegacyRelease, []byte(legacyCaddyfile))
- writeFile(t, inst.Path(instance.CaddySitesDir, "Mastodon.caddy"), []byte(mastodonSite))
- matchRestoredSites(app)(inst)
- if got := caddyFilesIn(t, inst.Path(instance.CaddyDropInDir)); !slices.Equal(got, []string{"Mastodon.caddy"}) {
- t.Fatalf("caddy.d has %v", got)
- }
- if got := caddyFilesIn(t, inst.Path(instance.CaddySitesDir)); len(got) > 0 {
- t.Fatalf("caddy.d/sites still has %v", got)
- }
- if !slices.Equal(inst.State.MovedSites, []string{"Mastodon.caddy"}) {
- t.Fatalf("recorded %v", inst.State.MovedSites)
- }
-}
diff --git a/fluxer_rexctl/cmd/upgrade_log_test.go b/fluxer_rexctl/cmd/upgrade_log_test.go
deleted file mode 100644
index 973947944..000000000
--- a/fluxer_rexctl/cmd/upgrade_log_test.go
+++ /dev/null
@@ -1,95 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-package cmd
-
-import (
- "bytes"
- "context"
- "errors"
- "os"
- "strings"
- "testing"
- "time"
-
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/engine"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/instance"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/release"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/ui"
-)
-
-func pendingUpgrade(t *testing.T, phase string) (*App, *instance.Instance) {
- t.Helper()
- inst, err := instance.Create(t.TempDir(), "fluxer")
- if err != nil {
- t.Fatal(err)
- }
- inst.State.Release = recoveryFrom
- inst.State.Upgrade = &instance.Upgrade{From: recoveryFrom, To: recoveryLatest, Phase: phase, StartedAt: time.Now().UTC().Add(-time.Minute)}
- if err := inst.Save(); err != nil {
- t.Fatal(err)
- }
- out := &bytes.Buffer{}
- app := &App{
- Version: recoveryLatest,
- Flags: GlobalFlags{Dir: inst.Dir},
- UI: ui.New(ui.Options{Stdin: strings.NewReader(""), Stdout: out, Stderr: out}),
- engine: &engine.Engine{Kind: engine.Docker},
- }
- return app, inst
-}
-
-func upgradeLogText(t *testing.T, inst *instance.Instance) string {
- t.Helper()
- data, err := os.ReadFile(inst.Path(instance.StateDirName, upgradeLog(recoveryLatest)))
- if err != nil {
- t.Fatalf("no upgrade log: %v", err)
- }
- return string(data)
-}
-
-func TestAbortedUpgradeWritesItsLogWhenGoingBackFails(t *testing.T) {
- app, inst := pendingUpgrade(t, release.PhaseMigrated)
- cause := errors.New("couldn't write docker-compose.yml")
- err := abortUpgrade(context.Background(), app, inst, app.engine, cause, ui.Wrap(cause, "Couldn't write the files.", ""))
- if err == nil {
- t.Fatal("going back worked without an engine")
- }
- if got := upgradeLogText(t, inst); !strings.Contains(got, cause.Error()) {
- t.Fatalf("upgrade log = %q, want the cause", got)
- }
-}
-
-func TestRecoveringAnInterruptedUpgradeWritesItsLog(t *testing.T) {
- app, inst := pendingUpgrade(t, release.PhaseRecreated)
- _ = recoverUpgrade(context.Background(), app, inst, true)
- if got := upgradeLogText(t, inst); !strings.Contains(got, "didn't finish") {
- t.Fatalf("upgrade log = %q", got)
- }
-}
-
-func TestRecoveringKeepsTheLogOfTheFailedAttempt(t *testing.T) {
- app, inst := pendingUpgrade(t, release.PhaseRecreated)
- path := inst.Path(instance.StateDirName, upgradeLog(recoveryLatest))
- if err := os.WriteFile(path, []byte("rexctl: api isn't ready\n"), 0o600); err != nil {
- t.Fatal(err)
- }
- _ = recoverUpgrade(context.Background(), app, inst, true)
- if got := upgradeLogText(t, inst); !strings.HasPrefix(got, "rexctl: api isn't ready\n") {
- t.Fatalf("upgrade log = %q", got)
- }
-}
-
-func TestAPanicDuringAnUpgradeWritesItsLog(t *testing.T) {
- _, inst := pendingUpgrade(t, release.PhaseRecreated)
- err := func() (err error) {
- defer guardUpgrade(inst, recoveryLatest, &err)
- panic("interface conversion: interface {} is nil")
- }()
- var ee *ui.ExitError
- if !errors.As(err, &ee) || !strings.Contains(ee.Fix, upgradeLog(recoveryLatest)) {
- t.Fatalf("err = %#v, want a fix that points at the log", err)
- }
- if got := upgradeLogText(t, inst); !strings.Contains(got, "interface conversion") || !strings.Contains(got, "goroutine") {
- t.Fatalf("upgrade log = %q", got)
- }
-}
diff --git a/fluxer_rexctl/cmd/upgrade_recovery_test.go b/fluxer_rexctl/cmd/upgrade_recovery_test.go
deleted file mode 100644
index 7d018f677..000000000
--- a/fluxer_rexctl/cmd/upgrade_recovery_test.go
+++ /dev/null
@@ -1,681 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-package cmd
-
-import (
- "bytes"
- "context"
- "encoding/json"
- "errors"
- "fmt"
- "io/fs"
- "maps"
- "net/http"
- "net/http/httptest"
- "os"
- "path/filepath"
- "runtime"
- "slices"
- "strings"
- "testing"
- "testing/fstest"
- "time"
-
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/backup"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/engine"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/host"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/instance"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/release"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/secrets"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/stack"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/ui"
-)
-
-const (
- recoveryFrom = "2026.1020.100000"
- recoveryRexctl = "2026.1025.120000"
- recoveryLatest = "2026.1025.233929"
-)
-
-type recoveryRun struct {
- app *App
- dir string
- out *bytes.Buffer
- events []string
-}
-
-func newRecoveryRun(t *testing.T, latest string) *recoveryRun {
- t.Helper()
- inst, err := instance.Create(t.TempDir(), "fluxer")
- if err != nil {
- t.Fatal(err)
- }
- inst.State.Release = recoveryFrom
- inst.State.Upgrade = &instance.Upgrade{From: recoveryFrom, To: recoveryRexctl, Phase: release.PhaseResolved}
- if err := inst.Save(); err != nil {
- t.Fatal(err)
- }
- srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
- if latest == "" {
- w.WriteHeader(http.StatusServiceUnavailable)
- return
- }
- _ = json.NewEncoder(w).Encode(release.Release{Version: latest, Assets: []release.Asset{{OS: runtime.GOOS, Arch: runtime.GOARCH, URL: "https://example.invalid/rexctl.tar.gz", SHA256: strings.Repeat("0", 64)}}})
- }))
- t.Cleanup(srv.Close)
- t.Setenv(release.ResolverURLEnv, srv.URL)
- r := &recoveryRun{dir: inst.Dir, out: &bytes.Buffer{}}
- r.app = &App{
- Version: recoveryRexctl,
- Flags: GlobalFlags{Dir: inst.Dir},
- UI: ui.New(ui.Options{Stdin: strings.NewReader(""), Stdout: r.out, Stderr: r.out}),
- engine: &engine.Engine{Kind: engine.Docker},
- }
- prevUpdate, prevReexec := selfUpdate, reexec
- t.Cleanup(func() { selfUpdate, reexec = prevUpdate, prevReexec })
- selfUpdate = func(context.Context, release.Asset) error {
- r.events = append(r.events, fmt.Sprintf("self-update pending=%v", r.pending(t)))
- return nil
- }
- reexec = func(args []string) error {
- r.events = append(r.events, "reexec "+strings.Join(args[len(args)-2:], " "))
- return nil
- }
- return r
-}
-
-func (r *recoveryRun) pending(t *testing.T) bool {
- t.Helper()
- inst, err := instance.Find(r.dir)
- if err != nil {
- t.Fatal(err)
- }
- return inst.State.Upgrade != nil
-}
-
-func TestPendingUpgradeUpdatesRexctlBeforeRecovery(t *testing.T) {
- for name, run := range map[string]func(*recoveryRun) error{
- "upgrade": func(r *recoveryRun) error { return runUpgrade(context.Background(), r.app, &upgradeFlags{}) },
- "rollback": func(r *recoveryRun) error { return runRollback(context.Background(), r.app, &rollbackFlags{}) },
- } {
- t.Run(name, func(t *testing.T) {
- r := newRecoveryRun(t, recoveryLatest)
- if err := run(r); err != nil {
- t.Fatal(err)
- }
- want := []string{"self-update pending=true", "reexec --resume " + release.ResumeRecovery}
- if !slices.Equal(r.events, want) {
- t.Fatalf("events = %q, want %q", r.events, want)
- }
- if !r.pending(t) {
- t.Fatal("the old rexctl recovered the upgrade before handing over")
- }
- })
- }
-}
-
-func TestReexecutedRecoveryDoesNotUpdateRexctlAgain(t *testing.T) {
- for name, run := range map[string]func(*recoveryRun) error{
- "upgrade": func(r *recoveryRun) error {
- return runUpgrade(context.Background(), r.app, &upgradeFlags{Resume: release.ResumeRecovery})
- },
- "rollback": func(r *recoveryRun) error {
- return runRollback(context.Background(), r.app, &rollbackFlags{Resume: release.ResumeRecovery})
- },
- } {
- t.Run(name, func(t *testing.T) {
- r := newRecoveryRun(t, recoveryLatest)
- _ = run(r)
- if len(r.events) > 0 {
- t.Fatalf("events = %q, want none", r.events)
- }
- if r.pending(t) {
- t.Fatal("the upgrade wasn't recovered")
- }
- })
- }
-}
-
-func TestPendingUpgradeRecoversWithCurrentRexctlWhenResolverFails(t *testing.T) {
- r := newRecoveryRun(t, "")
- _ = runUpgrade(context.Background(), r.app, &upgradeFlags{})
- if len(r.events) > 0 {
- t.Fatalf("events = %q, want none", r.events)
- }
- if r.pending(t) {
- t.Fatal("the upgrade wasn't recovered")
- }
- if note := "Couldn't check for a newer rexctl. Continuing with rexctl " + recoveryRexctl + "."; !strings.Contains(r.out.String(), note) {
- t.Fatalf("output %q doesn't say %q", r.out.String(), note)
- }
-}
-
-func TestPendingUpgradeRecoversWithCurrentRexctlWhenItIsLatest(t *testing.T) {
- r := newRecoveryRun(t, recoveryRexctl)
- if err := runRollback(context.Background(), r.app, &rollbackFlags{}); err != nil {
- t.Fatal(err)
- }
- if len(r.events) > 0 {
- t.Fatalf("events = %q, want none", r.events)
- }
- if r.pending(t) {
- t.Fatal("the upgrade wasn't recovered")
- }
-}
-
-func recoveryInstance(t *testing.T, r *recoveryRun) *instance.Instance {
- t.Helper()
- inst, err := instance.Find(r.dir)
- if err != nil {
- t.Fatal(err)
- }
- return inst
-}
-
-func TestFinishUpgradeRecordsPreviousBackup(t *testing.T) {
- r := newRecoveryRun(t, "")
- inst := recoveryInstance(t, r)
- made := writeTestBackup(t, inst, recoveryFrom, time.Date(2026, 10, 25, 4, 0, 0, 0, time.UTC), backup.ScopeWithoutUploads)
- inst.State.Upgrade = &instance.Upgrade{From: recoveryFrom, To: recoveryRexctl, Phase: release.PhaseVerified, Backup: made}
- next := *inst.State
- next.Release, next.Upgrade = recoveryRexctl, nil
- if err := release.Snapshot(&instance.Instance{Dir: inst.Dir, State: &next}, recoveryRexctl, nil); err != nil {
- t.Fatal(err)
- }
- if err := finishUpgrade(context.Background(), r.app, inst, r.app.engine); err != nil {
- t.Fatal(err)
- }
- saved := recoveryInstance(t, r)
- if saved.State.PreviousBackup != made || saved.State.PreviousRelease != recoveryFrom || saved.State.Release != recoveryRexctl {
- t.Errorf("after the upgrade the release is %s, the previous one %s and the previous backup %q", saved.State.Release, saved.State.PreviousRelease, saved.State.PreviousBackup)
- }
-}
-
-func TestRollbackUsesRecordedBackup(t *testing.T) {
- r := newRecoveryRun(t, "")
- inst := recoveryInstance(t, r)
- inst.State.Upgrade = nil
- day := time.Date(2026, 10, 25, 4, 0, 0, 0, time.UTC)
- recorded := writeTestBackup(t, inst, recoveryFrom, day, backup.ScopeWithoutUploads)
- manual := writeTestBackup(t, inst, recoveryFrom, day.Add(2*time.Hour), "")
- inst.State.PreviousRelease, inst.State.PreviousBackup = recoveryFrom, recorded
- b, err := upgradeBackup(inst, recoveryFrom)
- if err != nil || b.Path != recorded {
- t.Fatalf("upgradeBackup = %v, %v, want the recorded backup %s", b, err, recorded)
- }
- inst.State.PreviousBackup = filepath.Join(inst.BackupDir(), "gone"+backup.Extension)
- if b, _ := upgradeBackup(inst, recoveryFrom); b == nil || b.Path != manual {
- t.Errorf("with the recorded backup gone, upgradeBackup = %v, want the newest backup %s", b, manual)
- }
- inst.State.PreviousBackup = recorded
- if b, _ := upgradeBackup(inst, "2026.1001.100000"); b != nil {
- t.Errorf("upgradeBackup for another release = %v, want none", b)
- }
-}
-
-func TestSearchGoBackUsesUpgradeBackup(t *testing.T) {
- r := newRecoveryRun(t, "")
- inst := recoveryInstance(t, r)
- day := time.Date(2026, 10, 25, 4, 0, 0, 0, time.UTC)
- made := writeTestBackup(t, inst, recoveryFrom, day, backup.ScopeWithoutUploads)
- writeTestBackup(t, inst, recoveryFrom, day.Add(time.Hour), "")
- inst.State.Upgrade.Backup = made
- list, err := backup.List(inst.BackupDir())
- if err != nil {
- t.Fatal(err)
- }
- if b := backupFor(inst, list, recoveryFrom); b == nil || b.Path != made {
- t.Errorf("backupFor = %v, want the backup made for this upgrade %s", b, made)
- }
- inst.State.Upgrade.Backup = ""
- if b := backupFor(inst, list, recoveryFrom); b == nil || b.Path == made {
- t.Errorf("without an upgrade backup, backupFor = %v, want the newest one", b)
- }
-}
-
-func testSet(t *testing.T, name string, edit func(string) string) *stack.Set {
- t.Helper()
- src := stack.Embedded()
- files := fstest.MapFS{}
- err := fs.WalkDir(src.Files, ".", func(p string, d fs.DirEntry, err error) error {
- if err != nil || d.IsDir() {
- return err
- }
- data, err := fs.ReadFile(src.Files, p)
- if err != nil {
- return err
- }
- if p == stack.ComposeFile && edit != nil {
- data = []byte(edit(string(data)))
- }
- files[p] = &fstest.MapFile{Data: data, Mode: 0o644}
- return nil
- })
- if err != nil {
- t.Fatal(err)
- }
- return &stack.Set{Release: name, Files: files, Profiles: src.Profiles, Vars: src.Vars}
-}
-
-func TestUploadsChangeForcesFullBackup(t *testing.T) {
- r := newRecoveryRun(t, "")
- inst := recoveryInstance(t, r)
- images, err := stack.EmbeddedImages()
- if err != nil {
- t.Fatal(err)
- }
- inst.State.Images = instance.Images{Release: recoveryFrom, Refs: images.Images}
- if err := release.WriteRelease(inst, testSet(t, recoveryFrom, nil)); err != nil {
- t.Fatal(err)
- }
- next := *inst.State
- if uploadsChange(inst, recoveryFrom, testSet(t, recoveryRexctl, nil), &next) {
- t.Error("the same uploads services count as a change")
- }
- api := testSet(t, recoveryRexctl, func(c string) string {
- return strings.Replace(c, "FLUXER_API_HEADERS_TIMEOUT_MS:-}", "FLUXER_API_HEADERS_TIMEOUT_MS:-5}", 1)
- })
- if uploadsChange(inst, recoveryFrom, api, &next) {
- t.Error("a change to another service counts as an uploads change")
- }
- changed := testSet(t, recoveryRexctl, func(c string) string {
- return strings.Replace(c, "-volume.max=${FLUXER_SEAWEEDFS_VOLUME_MAX:-10000}", "-volume.max=${FLUXER_SEAWEEDFS_VOLUME_MAX:-20000}", 1)
- })
- if !uploadsChange(inst, recoveryFrom, changed, &next) {
- t.Error("a new seaweedfs command doesn't count as an uploads change")
- }
- init := testSet(t, recoveryRexctl, func(c string) string {
- return strings.Replace(c, "FLUXER_SEAWEEDFS_UPLOADS_TTL:-1d", "FLUXER_SEAWEEDFS_UPLOADS_TTL:-2d", 1)
- })
- if !uploadsChange(inst, recoveryFrom, init, &next) {
- t.Error("a new seaweedfs-init definition doesn't count as an uploads change")
- }
- bumped := next
- bumped.Images.Refs = map[string]string{}
- for k, v := range next.Images.Refs {
- bumped.Images.Refs[k] = v
- }
- bumped.Images.Refs["seaweedfs"] = "chrislusf/seaweedfs:99.1"
- if !uploadsChange(inst, recoveryFrom, testSet(t, recoveryRexctl, nil), &bumped) {
- t.Error("a new seaweedfs image doesn't count as an uploads change")
- }
- if !uploadsChange(inst, "2026.0101.000000", testSet(t, recoveryRexctl, nil), &next) {
- t.Error("a release without saved files doesn't fall back to a full backup")
- }
-
- lean := &upgradeFlags{Backup: backup.ScopeWithoutUploads}
- if f := backupFlagsFor(r.app, inst, recoveryFrom, testSet(t, recoveryRexctl, nil), &next, lean, "2026.1025"); f != lean || strings.Contains(r.out.String(), "changes how uploads are stored") {
- t.Errorf("an upgrade that keeps the uploads services got %+v and printed %q", f, r.out.String())
- }
- f := backupFlagsFor(r.app, inst, recoveryFrom, changed, &next, lean, "2026.1025")
- if upgradeScope(f) != backup.ScopeFull || upgradeScope(lean) != backup.ScopeWithoutUploads {
- t.Fatalf("an upgrade that changes uploads backs up with %s", upgradeScope(f))
- }
- if !strings.Contains(r.out.String(), "Fluxer 2026.1025 changes how uploads are stored. This backup includes them.") {
- t.Errorf("the forced full backup printed %q", r.out.String())
- }
- var scopes []string
- prevCreate, prevEstimate := createBackup, estimateBackup
- t.Cleanup(func() { createBackup, estimateBackup = prevCreate, prevEstimate })
- estimateBackup = func(_ context.Context, _ *instance.Instance, _ *engine.Project, scope string) (uint64, error) {
- scopes = append(scopes, "estimate "+scope)
- return 0, nil
- }
- createBackup = func(_ context.Context, _ *instance.Instance, _ *engine.Project, o backup.CreateOptions) (*backup.Info, error) {
- scopes = append(scopes, "create "+o.Scope)
- return nil, backup.ErrNeverStarted
- }
- upgradeSpace(context.Background(), r.app, inst, r.app.engine, next.Images.Refs, f)
- if err := backUpForUpgrade(context.Background(), r.app, inst, r.app.engine.Named(inst.Project(), inst.Dir), upgradeScope(f)); err != nil {
- t.Fatal(err)
- }
- if want := []string{"estimate full", "create full"}; !slices.Equal(scopes, want) {
- t.Errorf("the forced full backup ran %q, want %q", scopes, want)
- }
- scopes = nil
- upgradeSpace(context.Background(), r.app, inst, r.app.engine, next.Images.Refs, lean)
- if want := []string{"estimate without-uploads"}; !slices.Equal(scopes, want) {
- t.Errorf("a lean upgrade estimates %q, want %q", scopes, want)
- }
-}
-
-func TestLeanBackupVerifyFailureAbortsUpgrade(t *testing.T) {
- r := newRecoveryRun(t, "")
- inst := recoveryInstance(t, r)
- inst.State.Upgrade.Phase = release.PhasePulled
- bad := filepath.Join(t.TempDir(), "broken"+backup.Extension)
- prev := createBackup
- t.Cleanup(func() { createBackup = prev })
- var got backup.CreateOptions
- createBackup = func(_ context.Context, _ *instance.Instance, _ *engine.Project, o backup.CreateOptions) (*backup.Info, error) {
- got = o
- if err := os.WriteFile(bad, []byte("not a backup"), 0o600); err != nil {
- return nil, err
- }
- return &backup.Info{Path: bad, Release: recoveryFrom, Scope: backup.ScopeWithoutUploads}, nil
- }
- err := backUpForUpgrade(context.Background(), r.app, inst, r.app.engine.Named(inst.Project(), inst.Dir), backup.ScopeWithoutUploads)
- if err == nil {
- t.Fatal("a backup that fails its check let the upgrade go on")
- }
- if got.Scope != backup.ScopeWithoutUploads || got.Reason != "upgrade" {
- t.Errorf("Create got %+v", got)
- }
- if inst.State.Upgrade.Backup != "" {
- t.Errorf("the broken backup was recorded as %s", inst.State.Upgrade.Backup)
- }
- if fileExists(bad) {
- t.Error("the broken backup was left on disk")
- }
- if inst.State.Upgrade.Phase != release.PhasePulled {
- t.Errorf("phase = %s, want %s", inst.State.Upgrade.Phase, release.PhasePulled)
- }
-}
-
-func TestReexecKeepsBackupFlag(t *testing.T) {
- args := resumeArgs([]string{"upgrade", "--yes", "--backup", "without-uploads", "--dir", "/opt/fluxer"}, release.PhaseSelfUpdated, "")
- if i := slices.Index(args, "--backup"); i < 0 || i+1 >= len(args) || args[i+1] != "without-uploads" {
- t.Errorf("resume args = %q", args)
- }
- r := newRecoveryRun(t, recoveryLatest)
- prevArgs := os.Args
- t.Cleanup(func() { os.Args = prevArgs })
- os.Args = []string{"rexctl", "upgrade", "--yes", "--backup=without-uploads"}
- var handed []string
- reexec = func(args []string) error {
- handed = args
- return nil
- }
- if err := runUpgrade(context.Background(), r.app, &upgradeFlags{Backup: backup.ScopeWithoutUploads}); err != nil {
- t.Fatal(err)
- }
- if !slices.Contains(handed, "--backup=without-uploads") || !slices.Contains(handed, release.ResumeRecovery) {
- t.Errorf("rexctl started again with %q", handed)
- }
-}
-
-func TestBackupFlagConflictsWithNoBackup(t *testing.T) {
- r := newRecoveryRun(t, "")
- for _, f := range []upgradeFlags{
- {Backup: backup.ScopeWithoutUploads, NoBackup: true},
- {Backup: backup.ScopeFull, NoBackup: true},
- {Backup: backup.ScopeWithoutUploads, Check: true},
- {Backup: backup.ScopeWithoutUploads, Prefetch: true},
- {Backup: backup.ScopeFull, Prefetch: true},
- {Backup: "uploads"},
- } {
- err := runUpgrade(context.Background(), r.app, &f)
- var ee *ui.ExitError
- if !errors.As(err, &ee) || ee.Code != ui.ExitUsage {
- t.Errorf("runUpgrade(%+v) = %v, want a usage error", f, err)
- }
- }
-}
-
-func TestSwitchingRexctlBackDropsBackupFlag(t *testing.T) {
- r := newRecoveryRun(t, "2026.1022.100000")
- r.app.UI = ui.New(ui.Options{Stdin: strings.NewReader(""), Stdout: r.out, Stderr: r.out, Yes: true})
- inst, err := instance.Find(r.dir)
- if err != nil {
- t.Fatal(err)
- }
- inst.State.Upgrade = nil
- if err := inst.Save(); err != nil {
- t.Fatal(err)
- }
- scheduled := 0
- prevDrop := dropScheduledBackup
- t.Cleanup(func() { dropScheduledBackup = prevDrop })
- dropScheduledBackup = func(context.Context, *instance.Instance, *engine.Engine) (host.AutoUpgradeState, bool, error) {
- scheduled++
- return host.AutoUpgradeState{On: true, At: autoUpgradeDefault, Backup: backup.ScopeWithoutUploads}, true, nil
- }
- prevArgs := os.Args
- t.Cleanup(func() { os.Args = prevArgs })
- for _, args := range [][]string{
- {"rexctl", "upgrade", "--to", "2026.1022.100000", "--backup", "without-uploads", "--yes"},
- {"rexctl", "upgrade", "--to", "2026.1022.100000", "--backup=without-uploads", "--yes"},
- } {
- os.Args = args
- var handed []string
- reexec = func(args []string) error {
- handed = args
- return nil
- }
- r.out.Reset()
- if err := runUpgrade(context.Background(), r.app, &upgradeFlags{To: "2026.1022.100000", Backup: backup.ScopeWithoutUploads}); err != nil {
- t.Fatalf("%q: %v", args, err)
- }
- if handed == nil || slices.ContainsFunc(handed, func(a string) bool { return strings.HasPrefix(a, "--backup") }) || slices.Contains(handed, "without-uploads") {
- t.Errorf("%q started the older rexctl with %q", args, handed)
- }
- if !slices.Contains(handed, "--to") || !slices.Contains(handed, release.PhaseSelfUpdated) {
- t.Errorf("%q lost other flags, started with %q", args, handed)
- }
- for _, want := range []string{"This upgrade makes a full backup.", "Automatic upgrades make full backups from now on as well.", "Switched rexctl back to"} {
- if !strings.Contains(r.out.String(), want) {
- t.Errorf("%q printed %q, want %q", args, r.out.String(), want)
- }
- }
- inst, err := instance.Find(r.dir)
- if err != nil {
- t.Fatal(err)
- }
- inst.State.Upgrade = nil
- if err := inst.Save(); err != nil {
- t.Fatal(err)
- }
- }
- if scheduled != 2 {
- t.Errorf("the schedule was checked %d times, want 2", scheduled)
- }
-}
-
-func TestSwitchBackRefusesWhenScheduleCantChange(t *testing.T) {
- r := newRecoveryRun(t, "")
- prevDrop := dropScheduledBackup
- t.Cleanup(func() { dropScheduledBackup = prevDrop })
- dropScheduledBackup = func(context.Context, *instance.Instance, *engine.Engine) (host.AutoUpgradeState, bool, error) {
- return host.AutoUpgradeState{}, false, host.ErrNeedsRoot
- }
- _, err := switchBack(context.Background(), r.app, nil, nil, []string{"upgrade", "--to", "2026.1022.100000"}, "2026.1022")
- var ee *ui.ExitError
- if !errors.As(err, &ee) || ee.Code != ui.ExitRefused || !strings.Contains(ee.Fix, "sudo") {
- t.Errorf("switchBack = %v, want a refusal that asks for root", err)
- }
- dropScheduledBackup = func(context.Context, *instance.Instance, *engine.Engine) (host.AutoUpgradeState, bool, error) {
- return host.AutoUpgradeState{}, false, nil
- }
- r.out.Reset()
- dropScheduledBackup = func(context.Context, *instance.Instance, *engine.Engine) (host.AutoUpgradeState, bool, error) {
- return host.AutoUpgradeState{On: true, At: autoUpgradeDefault, Backup: backup.ScopeWithoutUploads}, true, nil
- }
- if _, err := switchBack(context.Background(), r.app, nil, nil, []string{"upgrade", "--to", "2026.1022.100000"}, "2026.1022"); err != nil || !strings.Contains(r.out.String(), "rexctl 2026.1022 may not know --backup. Automatic upgrades make full backups from now on.") {
- t.Errorf("switchBack without --backup = %v, printed %q", err, r.out.String())
- }
- dropScheduledBackup = func(context.Context, *instance.Instance, *engine.Engine) (host.AutoUpgradeState, bool, error) {
- return host.AutoUpgradeState{}, false, nil
- }
- r.out.Reset()
- args, err := switchBack(context.Background(), r.app, nil, nil, []string{"upgrade", "--backup", "full", "--to", "2026.1022.100000"}, "2026.1022")
- if err != nil || slices.Contains(args, "--backup") || strings.Contains(r.out.String(), "full backup") {
- t.Errorf("switchBack with --backup full = %q, %v, printed %q", args, err, r.out.String())
- }
-}
-
-func TestSwitchBackKeepsTheWholeSchedule(t *testing.T) {
- r := newRecoveryRun(t, "")
- inst := recoveryInstance(t, r)
- inst.State.NotifyURL = "https://ntfy.sh/fluxer-upgrades"
- prevDrop := dropScheduledBackup
- t.Cleanup(func() { dropScheduledBackup = prevDrop })
- dropScheduledBackup = func(context.Context, *instance.Instance, *engine.Engine) (host.AutoUpgradeState, bool, error) {
- return host.AutoUpgradeState{On: true, Day: "Sun", At: "03:30", Backup: backup.ScopeWithoutUploads, FullBackup: host.FullBackupMonthly}, true, nil
- }
- if _, err := switchBack(context.Background(), r.app, inst, nil, []string{"upgrade", "--backup", "without-uploads", "--to", "2026.1022.100000"}, "2026.1022"); err != nil {
- t.Fatal(err)
- }
- out := r.out.String()
- for _, want := range []string{
- "run rexctl auto-upgrade on --day sun --at 03:30 --backup without-uploads --full-backup monthly again.",
- "Add --notify with your address to that command to keep the notifications.",
- "The monthly full backup keeps running. rexctl 2026.1022 doesn't know about it, and rexctl auto-upgrade off from rexctl 2026.1022 leaves it on.",
- } {
- if !strings.Contains(out, want) {
- t.Errorf("switchBack printed %q, want %q", out, want)
- }
- }
- r.out.Reset()
- dropScheduledBackup = func(context.Context, *instance.Instance, *engine.Engine) (host.AutoUpgradeState, bool, error) {
- return host.AutoUpgradeState{On: true, At: autoUpgradeDefault, Backup: backup.ScopeFull, FullBackup: host.FullBackupMonthly}, false, nil
- }
- if _, err := switchBack(context.Background(), r.app, inst, nil, []string{"upgrade", "--to", "2026.1022.100000"}, "2026.1022"); err != nil {
- t.Fatal(err)
- }
- if out := r.out.String(); !strings.Contains(out, "The monthly full backup keeps running.") || strings.Contains(out, "--notify") {
- t.Errorf("switchBack with full backups before upgrades printed %q", out)
- }
- r.out.Reset()
- dropScheduledBackup = func(context.Context, *instance.Instance, *engine.Engine) (host.AutoUpgradeState, bool, error) {
- return host.AutoUpgradeState{On: true, At: autoUpgradeDefault, Backup: backup.ScopeWithoutUploads}, true, nil
- }
- inst.State.NotifyURL = ""
- if _, err := switchBack(context.Background(), r.app, inst, nil, []string{"upgrade", "--backup", "without-uploads", "--to", "2026.1022.100000"}, "2026.1022"); err != nil {
- t.Fatal(err)
- }
- if out := r.out.String(); !strings.Contains(out, "run rexctl auto-upgrade on --backup without-uploads again.") || strings.Contains(out, "monthly") || strings.Contains(out, "weekly") {
- t.Errorf("switchBack with a daily schedule printed %q", out)
- }
-}
-
-func TestSwitchBackWarnsAboutWeeklySchedule(t *testing.T) {
- r := newRecoveryRun(t, "")
- inst := recoveryInstance(t, r)
- inst.State.NotifyURL = "https://ntfy.sh/fluxer-upgrades"
- prevDrop := dropScheduledBackup
- t.Cleanup(func() { dropScheduledBackup = prevDrop })
- dropScheduledBackup = func(context.Context, *instance.Instance, *engine.Engine) (host.AutoUpgradeState, bool, error) {
- return host.AutoUpgradeState{On: true, Day: "Sun", At: autoUpgradeDefault, Backup: backup.ScopeFull, FullBackup: host.FullBackupMonthly}, false, nil
- }
- if _, err := switchBack(context.Background(), r.app, inst, nil, []string{"upgrade", "--to", "2026.1022.100000"}, "2026.1022"); err != nil {
- t.Fatal(err)
- }
- out := r.out.String()
- for _, want := range []string{
- "rexctl 2026.1022 shows this weekly schedule as every day, and it keeps running every Sunday. Once rexctl is newer than 2026.1022, run rexctl auto-upgrade to see it again.",
- "rexctl auto-upgrade on from rexctl 2026.1022 makes the schedule daily. Once rexctl is newer than 2026.1022, run rexctl auto-upgrade on --day sun --full-backup monthly to make it weekly again.",
- "Add --notify with your address to that command to keep the notifications.",
- "The monthly full backup keeps running.",
- } {
- if !strings.Contains(out, want) {
- t.Errorf("switchBack with a weekly schedule and full backups printed %q, want %q", out, want)
- }
- }
- r.out.Reset()
- dropScheduledBackup = func(context.Context, *instance.Instance, *engine.Engine) (host.AutoUpgradeState, bool, error) {
- return host.AutoUpgradeState{On: true, Day: "Sun", At: "03:30", Backup: backup.ScopeWithoutUploads}, true, nil
- }
- if _, err := switchBack(context.Background(), r.app, inst, nil, []string{"upgrade", "--to", "2026.1022.100000"}, "2026.1022"); err != nil {
- t.Fatal(err)
- }
- out = r.out.String()
- if !strings.Contains(out, "run rexctl auto-upgrade on --day sun --at 03:30 --backup without-uploads again.") || !strings.Contains(out, "it keeps running every Sunday") || strings.Contains(out, "makes the schedule daily") || strings.Count(out, "--notify") != 1 {
- t.Errorf("switchBack with a weekly lean schedule printed %q", out)
- }
-}
-
-func TestDryRunShowsForcedFullBackup(t *testing.T) {
- r := newRecoveryRun(t, "")
- inst := recoveryInstance(t, r)
- images, err := stack.EmbeddedImages()
- if err != nil {
- t.Fatal(err)
- }
- inst.State.Images = instance.Images{Release: recoveryFrom, Refs: maps.Clone(images.Images)}
- if _, err := secrets.Mint(inst.State.Secrets, false); err != nil {
- t.Fatal(err)
- }
- if err := release.WriteRelease(inst, testSet(t, recoveryFrom, nil)); err != nil {
- t.Fatal(err)
- }
- var scopes []string
- prevEstimate := estimateBackup
- t.Cleanup(func() { estimateBackup = prevEstimate })
- estimateBackup = func(_ context.Context, _ *instance.Instance, _ *engine.Project, scope string) (uint64, error) {
- scopes = append(scopes, scope)
- return 0, nil
- }
- lean := &upgradeFlags{Backup: backup.ScopeWithoutUploads, DryRun: true}
- version := stack.Embedded().Release
- printUpgradePlan(context.Background(), r.app, inst, lean, false, recoveryFrom, version)
- if out := r.out.String(); !strings.Contains(out, "backed up first, without uploads") || strings.Contains(out, "changes how uploads are stored") || !slices.Equal(scopes, []string{backup.ScopeWithoutUploads}) {
- t.Errorf("a dry run that keeps seaweedfs estimated %q and printed %q", scopes, out)
- }
- r.out.Reset()
- scopes = nil
- inst.State.Images.Refs["seaweedfs"] = "chrislusf/seaweedfs:3.1"
- printUpgradePlan(context.Background(), r.app, inst, lean, false, recoveryFrom, version)
- out := r.out.String()
- if !strings.Contains(out, "changes how uploads are stored. The backup before it includes them.") || strings.Contains(out, "without uploads") || !strings.Contains(out, "Your instance is backed up first.") {
- t.Errorf("a dry run with a new seaweedfs printed %q", out)
- }
- if !slices.Equal(scopes, []string{backup.ScopeFull}) {
- t.Errorf("a dry run with a new seaweedfs estimated %q, want a full backup", scopes)
- }
- r.out.Reset()
- scopes = nil
- printUpgradePlan(context.Background(), r.app, inst, lean, true, recoveryFrom, recoveryLatest)
- if !slices.Equal(scopes, []string{backup.ScopeWithoutUploads, backup.ScopeWithoutUploads, backup.ScopeFull}) {
- t.Errorf("a dry run that updates rexctl first estimated %q, want both scopes", scopes)
- }
- if out := r.out.String(); !strings.Contains(out, "without uploads unless Fluxer") {
- t.Errorf("a dry run that updates rexctl first printed %q", out)
- }
-}
-
-func TestRollbackDryRunChecksUploads(t *testing.T) {
- r := newRecoveryRun(t, "")
- inst := recoveryInstance(t, r)
- inst.State.Upgrade = nil
- uploads := t.TempDir()
- if err := os.WriteFile(filepath.Join(uploads, backup.UploadsIDFile), []byte("made-again\n"), 0o644); err != nil {
- t.Fatal(err)
- }
- if err := release.WriteRelease(inst, testSet(t, recoveryFrom, nil)); err != nil {
- t.Fatal(err)
- }
- set, err := release.LoadSet(inst, recoveryFrom)
- if err != nil {
- t.Fatal(err)
- }
- day := time.Date(2026, 10, 25, 4, 0, 0, 0, time.UTC)
- ref := &backup.UploadsRef{Bind: uploads, ID: "made-before", Definition: backup.UploadsDefinition(set, inst.State)}
- if ref.Definition == "" {
- t.Fatal("no uploads definition for the test release")
- }
- made := writeManifestBackup(t, inst, backup.Manifest{Format: backup.FormatVersion, Release: recoveryFrom, Project: inst.Project(), Domain: inst.Domain(), CreatedAt: day, Reason: "upgrade", Scope: backup.ScopeWithoutUploads, Uploads: ref, Volumes: []string{}})
- inst.State.PreviousRelease, inst.State.PreviousBackup = recoveryFrom, made
- err = rollbackWithBackup(context.Background(), r.app, inst, nil, &rollbackFlags{DryRun: true, RestoreDB: true}, recoveryFrom, "2026.1020")
- var ee *ui.ExitError
- var why *backup.UploadsNotHereError
- if !errors.As(err, &ee) || ee.Code != ui.ExitRefused || !errors.As(err, &why) || !strings.Contains(why.Why, "made again") {
- t.Errorf("a dry run with uploads made again returned %v (%v)", err, why)
- }
- if strings.Contains(r.out.String(), "Uploads stay as they are") {
- t.Errorf("the dry run promised a restore without uploads: %q", r.out.String())
- }
- if err := os.WriteFile(filepath.Join(uploads, backup.UploadsIDFile), []byte("made-before\n"), 0o644); err != nil {
- t.Fatal(err)
- }
- ref.Inode = uploadsInode(t, uploads)
- made = writeManifestBackup(t, inst, backup.Manifest{Format: backup.FormatVersion, Release: recoveryFrom, Project: inst.Project(), Domain: inst.Domain(), CreatedAt: day.Add(time.Minute), Reason: "upgrade", Scope: backup.ScopeWithoutUploads, Uploads: ref, Volumes: []string{}})
- inst.State.PreviousBackup = made
- r.out.Reset()
- if err := rollbackWithBackup(context.Background(), r.app, inst, nil, &rollbackFlags{DryRun: true, RestoreDB: true}, recoveryFrom, "2026.1020"); err != nil {
- t.Fatalf("a dry run with the uploads in place returned %v", err)
- }
- out := r.out.String()
- if !strings.Contains(out, "Messages and changes since then are lost. Uploads stay as they are.") || strings.Contains(out, "Anything that changed") {
- t.Errorf("the dry run of a restore without uploads says %q", out)
- }
-}
diff --git a/fluxer_rexctl/cmd/use_test.go b/fluxer_rexctl/cmd/use_test.go
deleted file mode 100644
index b79aabd93..000000000
--- a/fluxer_rexctl/cmd/use_test.go
+++ /dev/null
@@ -1,155 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-package cmd
-
-import (
- "bytes"
- "os"
- "path/filepath"
- "slices"
- "strings"
- "testing"
-
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/instance"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/release"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/ui"
-)
-
-func TestMain(m *testing.M) {
- home, err := os.MkdirTemp("", "rexctl-home")
- if err != nil {
- panic(err)
- }
- os.Setenv("HOME", home)
- os.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))
- os.Setenv("AppData", filepath.Join(home, "AppData"))
- instance.MachineRecordPath = filepath.Join(home, "etc", "rexctl", instance.RecordFileName)
- code := m.Run()
- os.RemoveAll(home)
- os.Exit(code)
-}
-
-func clearRecords(t *testing.T) {
- t.Helper()
- for _, s := range []instance.Scope{instance.ScopeUser, instance.ScopeMachine} {
- if err := instance.SaveRecord(s, instance.Record{}); err != nil {
- t.Fatal(err)
- }
- }
- t.Cleanup(func() {
- for _, s := range []instance.Scope{instance.ScopeUser, instance.ScopeMachine} {
- _ = instance.SaveRecord(s, instance.Record{})
- }
- })
-}
-
-func recordApp(t *testing.T) (*App, string) {
- t.Helper()
- clearRecords(t)
- inst, err := instance.Create(t.TempDir(), "fluxer")
- if err != nil {
- t.Fatal(err)
- }
- if err := inst.Save(); err != nil {
- t.Fatal(err)
- }
- out := &bytes.Buffer{}
- return &App{
- Flags: GlobalFlags{Dir: inst.Dir},
- UI: ui.New(ui.Options{Stdin: strings.NewReader(""), Stdout: out, Stderr: out}),
- }, inst.Dir
-}
-
-func resolved(t *testing.T, dir string) string {
- t.Helper()
- real, err := filepath.EvalSymlinks(dir)
- if err != nil {
- t.Fatal(err)
- }
- return real
-}
-
-func TestFirstUseRecordsInstance(t *testing.T) {
- app, dir := recordApp(t)
- if _, err := app.Instance(); err != nil {
- t.Fatal(err)
- }
- if got := instance.ReadRecord(instance.OwnScope()).Instances; !slices.Equal(got, []string{resolved(t, dir)}) {
- t.Errorf("recorded = %v, want %s", got, dir)
- }
-}
-
-func TestForgetRemovesInstance(t *testing.T) {
- app, dir := recordApp(t)
- if _, err := app.Instance(); err != nil {
- t.Fatal(err)
- }
- app.forget(dir)
- if r := instance.ReadRecord(instance.OwnScope()); !r.Empty() {
- t.Errorf("recorded = %+v, want nothing", r)
- }
-}
-
-func TestRememberWithDirKeepsStandardFolder(t *testing.T) {
- app, dir := recordApp(t)
- home, _ := os.UserHomeDir()
- standard := filepath.Join(home, "fluxer")
- inst, err := instance.Create(standard, "fluxer")
- if err != nil {
- t.Fatal(err)
- }
- if err := inst.Save(); err != nil {
- t.Fatal(err)
- }
- t.Cleanup(func() { os.RemoveAll(standard) })
- if fb, _ := instance.Fallback(); fb != standard {
- t.Skipf("the standard folder here is %s", fb)
- }
- app.remember(dir)
- t.Chdir(t.TempDir())
- l, err := instance.Resolve("")
- if err != nil || l.Dir != resolved(t, standard) || l.From != instance.FromRecord {
- t.Errorf("Resolve = %+v, %v", l, err)
- }
-}
-
-func TestRerunKeepsThePickedInstance(t *testing.T) {
- app, dir := recordApp(t)
- app.Flags.Dir = ""
- app.located = &instance.Located{Dir: dir, From: instance.FromPicked}
- args := resumeArgs([]string{"upgrade", "--yes"}, release.PhaseSelfUpdated, app.pickedDir())
- if !slices.Equal(args, []string{"upgrade", "--yes", "--dir", dir, "--" + release.ResumeFlag, release.PhaseSelfUpdated}) {
- t.Errorf("resume args %q", args)
- }
- if got := app.takeOverCommand(); got != "rexctl takeover --dir "+dir {
- t.Errorf("takeover command %q", got)
- }
- app.located = &instance.Located{Dir: dir, From: instance.FromWorkdir}
- if args := resumeArgs([]string{"upgrade"}, release.PhaseSelfUpdated, app.pickedDir()); slices.Contains(args, "--dir") {
- t.Errorf("resume args %q added --dir for the current folder", args)
- }
-}
-
-func TestUseOnlyChangesTheRecord(t *testing.T) {
- clearRecords(t)
- app, inst, out := oldInstance(t, true)
- tree := func() []string {
- var files []string
- _ = filepath.WalkDir(inst.Dir, func(path string, _ os.DirEntry, err error) error {
- files = append(files, path)
- return err
- })
- return files
- }
- before := tree()
- if err := runUseShow(app); err != nil {
- t.Fatalf("%v\n%s", err, out)
- }
- if err := runUse(app, inst.Dir); err != nil {
- t.Fatalf("%v\n%s", err, out)
- }
- if after := tree(); !slices.Equal(before, after) {
- t.Fatalf("rexctl use changed the instance folder:\n%v\n%v", before, after)
- }
- requireOldLayout(t, inst)
-}
diff --git a/fluxer_rexctl/cmd/voice_installsh_test.go b/fluxer_rexctl/cmd/voice_installsh_test.go
deleted file mode 100644
index 5b2dd5e0e..000000000
--- a/fluxer_rexctl/cmd/voice_installsh_test.go
+++ /dev/null
@@ -1,117 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-package cmd
-
-import (
- "archive/tar"
- "bytes"
- "compress/gzip"
- "crypto/sha256"
- "encoding/hex"
- "encoding/pem"
- "fmt"
- "net/http"
- "net/http/httptest"
- "os"
- "os/exec"
- "path/filepath"
- "runtime"
- "strings"
- "testing"
-)
-
-func fakeRexctlArchive(t *testing.T, argsFile string) []byte {
- t.Helper()
- script := fmt.Sprintf("#!/bin/sh\nfor a in \"$@\"; do printf '%%s\\n' \"$a\"; done > %q\n", argsFile)
- var buf bytes.Buffer
- gz := gzip.NewWriter(&buf)
- tw := tar.NewWriter(gz)
- if err := tw.WriteHeader(&tar.Header{Name: "rexctl", Mode: 0o755, Size: int64(len(script))}); err != nil {
- t.Fatal(err)
- }
- if _, err := tw.Write([]byte(script)); err != nil {
- t.Fatal(err)
- }
- if err := tw.Close(); err != nil {
- t.Fatal(err)
- }
- if err := gz.Close(); err != nil {
- t.Fatal(err)
- }
- return buf.Bytes()
-}
-
-func TestInstallScriptMapsVoiceShorthand(t *testing.T) {
- if runtime.GOOS == "windows" {
- t.Skip("install.sh runs on Linux and macOS")
- }
- for _, tool := range []string{"sh", "curl", "tar"} {
- if _, err := exec.LookPath(tool); err != nil {
- t.Skipf("%s is missing", tool)
- }
- }
- script, err := filepath.Abs("../../fluxer_docs/src/installer/install.sh")
- if err != nil {
- t.Fatal(err)
- }
- cases := []struct {
- args []string
- want []string
- }{
- {[]string{"voice", "chat.example.com", "fvj_1_x"}, []string{"voice", "join", "chat.example.com", "fvj_1_x"}},
- {[]string{"voice", "chat.example.com", "fvj_1_x", "--yes"}, []string{"voice", "join", "chat.example.com", "fvj_1_x", "--yes"}},
- {[]string{"voice", "chat.example.com"}, []string{"voice", "join", "chat.example.com"}},
- {[]string{"voice", "chat.example.com", "--yes"}, []string{"voice", "join", "chat.example.com", "--yes"}},
- {[]string{"voice", "join", "chat.example.com", "fvj_1_x"}, []string{"voice", "join", "chat.example.com", "fvj_1_x"}},
- {[]string{"voice", "--help"}, []string{"voice", "--help"}},
- {[]string{"voice", "list"}, []string{"voice", "list"}},
- {[]string{"voice", "remove", "fra-server-1"}, []string{"voice", "remove", "fra-server-1"}},
- {[]string{"voice", "token", "list"}, []string{"voice", "token", "list"}},
- {[]string{"voice", "token", "revoke", "123"}, []string{"voice", "token", "revoke", "123"}},
- {[]string{"voice", "hostname", "fra-server-1", "voice.example.com"}, []string{"voice", "hostname", "fra-server-1", "voice.example.com"}},
- {[]string{"voice", "status", "fra-server-1", "--yes"}, []string{"voice", "status", "fra-server-1", "--yes"}},
- }
- for _, tc := range cases {
- t.Run(strings.Join(tc.args, " "), func(t *testing.T) {
- dir := t.TempDir()
- argsFile := filepath.Join(dir, "args")
- archive := fakeRexctlArchive(t, argsFile)
- sum := sha256.Sum256(archive)
- var srv *httptest.Server
- srv = httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- if strings.HasSuffix(r.URL.Path, ".tar.gz") {
- _, _ = w.Write(archive)
- return
- }
- fmt.Fprintf(w, "version v9.9.9\nurl %s/rexctl.tar.gz\nsha256 %s\n", srv.URL, hex.EncodeToString(sum[:]))
- }))
- defer srv.Close()
- ca := filepath.Join(dir, "ca.pem")
- certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: srv.Certificate().Raw})
- if err := os.WriteFile(ca, certPEM, 0o644); err != nil {
- t.Fatal(err)
- }
- cmd := exec.Command("sh", append([]string{script}, tc.args...)...)
- cmd.Env = []string{
- "PATH=" + os.Getenv("PATH"),
- "HOME=" + dir,
- "REXCTL_RELEASE_URL=" + srv.URL + "/release.json",
- "CURL_CA_BUNDLE=" + ca,
- "SSL_CERT_FILE=" + ca,
- "FLUXER_VOICE_JOIN_TOKEN=fvj_1_x",
- }
- cmd.Stdin = strings.NewReader("")
- out, err := cmd.CombinedOutput()
- if err != nil {
- t.Fatalf("install.sh: %v\n%s", err, out)
- }
- got, err := os.ReadFile(argsFile)
- if err != nil {
- t.Fatalf("rexctl never ran: %v\n%s", err, out)
- }
- if strings.TrimSpace(string(got)) != strings.Join(tc.want, "\n") {
- t.Fatalf("rexctl got %q, want %q", strings.Fields(string(got)), tc.want)
- }
- })
- }
-}
diff --git a/fluxer_rexctl/cmd/voice_join_test.go b/fluxer_rexctl/cmd/voice_join_test.go
deleted file mode 100644
index e28c1893c..000000000
--- a/fluxer_rexctl/cmd/voice_join_test.go
+++ /dev/null
@@ -1,152 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-package cmd
-
-import (
- "context"
- "errors"
- "strings"
- "testing"
-
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/adminapi"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/engine"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/instance"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/ui"
-)
-
-func TestJoinInstallsDockerOnBareLinux(t *testing.T) {
- unreachable := engineFailure(&engine.Error{Op: "connect", Class: engine.ClassUnreachable})
- denied := engineFailure(&engine.Error{Op: "connect", Class: engine.ClassDenied})
- cases := []struct {
- name string
- err error
- goos string
- dryRun bool
- want bool
- }{
- {"no engine on linux", unreachable, "linux", false, true},
- {"dry run", unreachable, "linux", true, false},
- {"macOS", unreachable, "darwin", false, false},
- {"permission denied", denied, "linux", false, false},
- {"cancelled", context.Canceled, "linux", false, false},
- }
- for _, c := range cases {
- if got := joinInstallsDocker(c.err, c.goos, c.dryRun); got != c.want {
- t.Errorf("%s: got %v, want %v", c.name, got, c.want)
- }
- }
-}
-
-func TestVoiceServersFollowThePinnedLiveKitImage(t *testing.T) {
- inst := &instance.Instance{Dir: t.TempDir(), State: &instance.State{
- Settings: map[string]string{},
- Images: instance.Images{Release: "2026.1030.2", Refs: map[string]string{"livekit": "livekit/livekit-server:v1.13.11"}},
- }}
- if got := instanceLiveKitImage(inst); got != "livekit/livekit-server:v1.13.11" {
- t.Errorf("pinned: got %s", got)
- }
- inst.State.Settings["images.livekit"] = "registry.example.com/livekit:v1"
- if got := instanceLiveKitImage(inst); got != "registry.example.com/livekit:v1" {
- t.Errorf("operator setting: got %s", got)
- }
-}
-
-func TestUpgradeLeavesOffAndDrainingServersAsTheyWere(t *testing.T) {
- cases := []struct {
- active, draining, want bool
- }{
- {true, false, true},
- {false, false, false},
- {true, true, false},
- {false, true, false},
- }
- for _, c := range cases {
- if got := upgradeDrains(c.active, c.draining); got != c.want {
- t.Errorf("active %v, draining %v: got %v", c.active, c.draining, got)
- }
- }
-}
-
-func TestJoinTakesIPForAShared100Dot64Route(t *testing.T) {
- local := []string{"100.64.12.7"}
- _, err := assessJoin("203.0.113.9", "", local, "100.64.12.7")
- var ee *ui.ExitError
- if !errors.As(err, &ee) || !strings.Contains(ee.Fix, "--ip") {
- t.Fatalf("without --ip: %v", err)
- }
- reach, err := assessJoin("203.0.113.9", "203.0.113.9", local, "100.64.12.7")
- if err != nil {
- t.Fatalf("with --ip: %v", err)
- }
- if reach.CGNAT || !reach.BehindNAT || reach.PublicIPv4 != "203.0.113.9" {
- t.Fatalf("reach = %+v", reach)
- }
- if bindAddress("203.0.113.9", local) != "" {
- t.Fatal("bound to an address this machine doesn't have")
- }
-}
-
-func TestNewRegionsNeedCoordinates(t *testing.T) {
- app, _ := testVoiceApp()
- for _, args := range [][]string{
- {"--new-region", "fra", "--region-name", "Frankfurt"},
- {"--new-region", "fra", "--region-name", "Frankfurt", "--lat", "50.1"},
- {"--new-region", "fra", "--region-name", "Frankfurt", "--lat", "95", "--long", "8.7"},
- } {
- c := newVoiceAddCmd(app)
- c.SetArgs(args)
- c.SilenceUsage, c.SilenceErrors = true, true
- err := c.Execute()
- var ee *ui.ExitError
- if !errors.As(err, &ee) || ee.Code != ui.ExitUsage || !strings.Contains(ee.Msg, "--lat") {
- t.Errorf("%v: %v", args, err)
- }
- }
- c := newVoiceTokenCmd(app)
- c.SetArgs([]string{"--region", "fra", "--lat", "50.1", "--long", "8.7"})
- c.SilenceUsage, c.SilenceErrors = true, true
- if err := c.Execute(); err == nil || !strings.Contains(err.Error(), "--new-region") {
- t.Errorf("token coordinates without a new region: %v", err)
- }
-}
-
-func TestVoiceListShowsRegionsWithoutServers(t *testing.T) {
- inst := &instance.Instance{State: &instance.State{Settings: map[string]string{}}}
- regions := []adminapi.VoiceRegion{
- {VoiceRegionAdminResponse: adminapi.VoiceRegionAdminResponse{Id: "default"}, Servers: []adminapi.VoiceServerAdminResponse{{ServerId: "default-server-1", IsActive: true}}},
- {VoiceRegionAdminResponse: adminapi.VoiceRegionAdminResponse{Id: "fra"}},
- }
- rows, servers := voiceListRows(regions, inst)
- if servers != 1 || len(rows) != 2 || rows[1][0] != "-" || rows[1][1] != "fra" || rows[1][2] != "no servers" {
- t.Fatalf("rows = %v, servers = %d", rows, servers)
- }
-}
-
-func TestJoinRefusesOlderPodmanWithoutAFluxerInstance(t *testing.T) {
- old := &engine.Engine{Kind: engine.Podman, Version: "5.4.2"}
- if err := podmanJoinRefusal(old, &joinPlan{}); err == nil {
- t.Fatal("Podman 5.4.2 on a voice machine was allowed")
- }
- if err := podmanJoinRefusal(old, &joinPlan{edgeInst: &instance.Instance{}}); err != nil {
- t.Fatalf("a server next to Fluxer was refused: %v", err)
- }
- if err := podmanJoinRefusal(&engine.Engine{Kind: engine.Podman, Version: podmanRestartsContainers}, &joinPlan{}); err != nil {
- t.Fatalf("Podman %s was refused: %v", podmanRestartsContainers, err)
- }
- if err := podmanJoinRefusal(&engine.Engine{Kind: engine.Docker, Version: "27.0.0"}, &joinPlan{}); err != nil {
- t.Fatalf("Docker was refused: %v", err)
- }
-}
-
-func TestSysctlCommandsMatchTheComposePage(t *testing.T) {
- app, out := testVoiceApp()
- showVoiceSysctlCommands(app)
- for _, want := range []string{
- `printf 'net.core.rmem_max = 16777216\nnet.core.wmem_max = 16777216\n' | sudo tee /etc/sysctl.d/61-fluxer-voice.conf`,
- "sudo sysctl -p /etc/sysctl.d/61-fluxer-voice.conf",
- } {
- if !strings.Contains(out.String(), want) {
- t.Fatalf("missing %q in %s", want, out.String())
- }
- }
-}
diff --git a/fluxer_rexctl/cmd/voice_lifecycle_test.go b/fluxer_rexctl/cmd/voice_lifecycle_test.go
deleted file mode 100644
index 0e396dd71..000000000
--- a/fluxer_rexctl/cmd/voice_lifecycle_test.go
+++ /dev/null
@@ -1,456 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-package cmd
-
-import (
- "bytes"
- "context"
- "encoding/json"
- "errors"
- "net"
- "net/http"
- "net/http/httptest"
- "os"
- "path/filepath"
- "strings"
- "sync"
- "testing"
- "time"
-
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/engine"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/host"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/instance"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/ui"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/voice"
-)
-
-func testVoiceApp() (*App, *bytes.Buffer) {
- out := &bytes.Buffer{}
- return &App{UI: ui.New(ui.Options{Stdin: strings.NewReader(""), Stdout: out, Stderr: out})}, out
-}
-
-func voiceMachine(t *testing.T, servers ...instance.VoiceServer) *instance.Instance {
- t.Helper()
- dir := resolved(t, t.TempDir())
- inst := &instance.Instance{Dir: dir, State: &instance.State{
- Schema: instance.StateSchema, Kind: instance.KindVoice, Project: voice.MachineProject,
- Settings: map[string]string{}, Secrets: map[string]string{}, Voice: servers,
- }}
- if err := os.MkdirAll(inst.Path(instance.StateDirName), 0o700); err != nil {
- t.Fatal(err)
- }
- if err := inst.Save(); err != nil {
- t.Fatal(err)
- }
- if err := instance.Remember(instance.OwnScope(), dir, false); err != nil {
- t.Fatal(err)
- }
- return inst
-}
-
-func TestRemovingAVoiceMachineTurnsOffAutoUpgrade(t *testing.T) {
- clearRecords(t)
- inst := voiceMachine(t)
- var removed []string
- removeAutoUpgradeFor = func(_ context.Context, inst *instance.Instance, _ *engine.Engine) (bool, error) {
- removed = append(removed, inst.Dir)
- return true, nil
- }
- t.Cleanup(func() { removeAutoUpgradeFor = removeAutoUpgrade })
- app, _ := testVoiceApp()
- if err := removeVoiceMachine(context.Background(), app, nil, inst); err != nil {
- t.Fatal(err)
- }
- if len(removed) != 1 || removed[0] != inst.Dir {
- t.Fatalf("auto-upgrade removed for %v, want %s", removed, inst.Dir)
- }
- if _, err := os.Stat(inst.Dir); !os.IsNotExist(err) {
- t.Fatalf("%s is still there", inst.Dir)
- }
-}
-
-func TestAJoinedServerNextToFluxerIsFoundWithoutDir(t *testing.T) {
- clearRecords(t)
- fluxer, err := instance.Create(resolved(t, t.TempDir()), "fluxer")
- if err != nil {
- t.Fatal(err)
- }
- if err := fluxer.Save(); err != nil {
- t.Fatal(err)
- }
- if err := instance.Remember(instance.OwnScope(), fluxer.Dir, true); err != nil {
- t.Fatal(err)
- }
- machine := voiceMachine(t, instance.VoiceServer{ID: "fra-server-1", Edge: voice.EdgeInstance})
- machine.State.VoiceEdge = &instance.VoiceEdge{Instance: fluxer.Dir}
- if err := machine.Save(); err != nil {
- t.Fatal(err)
- }
- owner, srv := findVoiceServer(fluxer, "fra-server-1")
- if srv == nil || owner.Dir != machine.Dir {
- t.Fatalf("findVoiceServer found %v in %s", srv, owner.Dir)
- }
- if _, _, err := localVoiceServers(fluxer, []string{"fra-server-9"}); err == nil {
- t.Fatal("an unknown ID was found")
- }
- if got := voiceDirFlag(machine.Dir); got != " --dir "+machine.Dir {
- t.Fatalf("voiceDirFlag = %q", got)
- }
- if got := voiceDirFlag(fluxer.Dir); got != "" {
- t.Fatalf("voiceDirFlag for the default = %q", got)
- }
- using := voiceMachinesUsing(fluxer)
- if len(using) != 1 || using[0].Dir != machine.Dir {
- t.Fatalf("voiceMachinesUsing = %v", using)
- }
-}
-
-func TestVoiceServerStaleFollowsTheShippedFiles(t *testing.T) {
- srv := instance.VoiceServer{ID: "fra-server-1", Key: "fluxer-fra-server-1", Secret: strings.Repeat("a", 64), TCPPort: 7883, UDPPort: 7884, Image: "livekit/livekit-server:v1", Memory: "1g", Webhook: "https://chat.example.com/api/webhooks/livekit", Network: voice.MachineNetwork}
- inst := voiceMachine(t, srv)
- saved := &inst.State.Voice[0]
- if err := writeVoiceServer(inst, saved); err != nil {
- t.Fatal(err)
- }
- if voiceServerStale(inst, saved, saved.Image) {
- t.Fatal("a freshly written server is stale")
- }
- if !voiceServerStale(inst, saved, "livekit/livekit-server:v2") {
- t.Fatal("a new image isn't stale")
- }
- compose := filepath.Join(voice.ServerDir(inst.Dir, saved.ID), voice.ComposeFile)
- if err := os.WriteFile(compose, []byte("services: {}\n"), 0o644); err != nil {
- t.Fatal(err)
- }
- if !voiceServerStale(inst, saved, saved.Image) {
- t.Fatal("a changed compose file isn't stale")
- }
- saved.Pinned = true
- if got := voiceTargetImage(saved, "livekit/livekit-server:v2"); got != saved.Image {
- t.Fatalf("a pinned server moves to %s", got)
- }
-}
-
-func TestRestoreDropsServersMissingFromTheBackup(t *testing.T) {
- before := []instance.VoiceServer{{ID: "a", Project: "fluxer-voice-a"}, {ID: "b", Project: "fluxer-voice-b"}}
- after := []instance.VoiceServer{{ID: "a", Project: "fluxer-voice-a"}}
- got := droppedVoiceServers(before, after)
- if len(got) != 1 || got[0].ID != "b" {
- t.Fatalf("dropped %v", got)
- }
-}
-
-func TestBindAddressOnlyWhenTheMachineHasIt(t *testing.T) {
- local := []string{"10.0.0.5", "198.51.100.8"}
- if got := bindAddress("198.51.100.8", local); got != "198.51.100.8" {
- t.Errorf("a local address binds to %q", got)
- }
- if got := bindAddress("203.0.113.7", local); got != "" {
- t.Errorf("an address behind NAT binds to %q", got)
- }
-}
-
-func TestJoinFirewallText(t *testing.T) {
- if got := joinFirewallText(host.FirewallNone, 4, true); !strings.HasPrefix(got, "none found") {
- t.Errorf("no firewall: %s", got)
- }
- if got := joinFirewallText(host.Firewall("ufw"), 4, true); !strings.Contains(got, "left alone") {
- t.Errorf("--no-firewall: %s", got)
- }
- if got := joinFirewallText(host.Firewall("ufw"), 4, false); !strings.Contains(got, "will open 4 ports") {
- t.Errorf("ufw: %s", got)
- }
-}
-
-func TestTakenVoicePortsIncludeTheHTTPPort(t *testing.T) {
- clearRecords(t)
- inst := voiceMachine(t, instance.VoiceServer{ID: "b", TCPPort: 7883, UDPPort: 7884, HTTPPort: 7882, Edge: voice.EdgeNone})
- taken := takenVoicePorts(context.Background(), nil, inst)
- if !taken[host.Port{Number: 7882, Proto: "tcp"}] {
- t.Fatalf("the HTTP port of a stopped server is free: %v", taken)
- }
- if !instancePortsContain(instance.RecordedVoicePorts(), 7882, "tcp") {
- t.Fatal("the recorded voice ports miss the HTTP port")
- }
-}
-
-func instancePortsContain(ports []instance.VoicePort, number int, proto string) bool {
- for _, p := range ports {
- if p.Number == number && p.Proto == proto {
- return true
- }
- }
- return false
-}
-
-func TestDrainWaitDoesNotTreatAnUnreadableServerAsEmpty(t *testing.T) {
- srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
- w.WriteHeader(http.StatusBadGateway)
- }))
- defer srv.Close()
- port := srv.Listener.Addr().(*net.TCPAddr).Port
- inst := &instance.Instance{Dir: t.TempDir(), State: &instance.State{Kind: instance.KindVoice}}
- server := &instance.VoiceServer{ID: "fra-server-1", Edge: voice.EdgeNone, HTTPPort: port, Endpoint: "wss://voice.example.com/livekit-fra-server-1", Key: "k", Secret: "s"}
- app, out := testVoiceApp()
- start := time.Now()
- waitForDrain(context.Background(), app, inst, server, time.Second)
- if time.Since(start) < time.Second {
- t.Fatal("the wait ended before its limit")
- }
- if strings.Contains(out.String(), "No calls left") || !strings.Contains(out.String(), "couldn't read the calls") {
- t.Fatalf("output: %s", out.String())
- }
-}
-
-func TestPickHTTPPortSkipsTheServersOwnTCPPort(t *testing.T) {
- taken := map[host.Port]bool{{Number: 7880, Proto: "tcp"}: true}
- free := func(int, string) bool { return true }
- if got := pickHTTPPort(taken, 7881, free); got != 7882 {
- t.Fatalf("pickHTTPPort = %d, want 7882", got)
- }
-}
-
-func TestInstallAfterAJoinUsesTheStandardFolder(t *testing.T) {
- clearRecords(t)
- machine := voiceMachine(t, instance.VoiceServer{ID: "fra-server-1", Instance: "chat.example.com"})
- app, out := testVoiceApp()
- dir, err := installTarget(app)
- if err != nil {
- t.Fatal(err)
- }
- want, err := instance.DefaultDir()
- if err != nil {
- t.Fatal(err)
- }
- if dir != want {
- t.Fatalf("install goes to %s, want %s", dir, want)
- }
- if !strings.Contains(out.String(), machine.Dir) {
- t.Fatalf("output: %s", out.String())
- }
-
- app, _ = testVoiceApp()
- app.Flags.Dir = machine.Dir
- _, err = installTarget(app)
- var exit *ui.ExitError
- if !errors.As(err, &exit) || exit.Code != ui.ExitRefused || !strings.Contains(exit.Msg, "chat.example.com") {
- t.Fatalf("install with --dir of a voice machine: %v", err)
- }
-}
-
-func TestBootStartStartsVoiceServersWhenFluxerIsAlreadyUp(t *testing.T) {
- clearRecords(t)
- inst, err := instance.Create(resolved(t, t.TempDir()), "fluxer")
- if err != nil {
- t.Fatal(err)
- }
- inst.State.Voice = []instance.VoiceServer{{ID: "fra-server-1", Network: "fluxer_fluxer"}}
- if err := inst.Save(); err != nil {
- t.Fatal(err)
- }
- app, _ := testVoiceApp()
- app.Flags.Dir = inst.Dir
- app.engine = &engine.Engine{Kind: engine.Podman}
- var started []string
- prevUp, prevStart := bootStackUp, startVoiceAtBoot
- t.Cleanup(func() { bootStackUp, startVoiceAtBoot = prevUp, prevStart })
- bootStackUp = func(context.Context, *App, *instance.Instance) bool { return true }
- startVoiceAtBoot = func(_ context.Context, _ *App, got *instance.Instance, _ *engine.Engine) {
- started = append(started, got.Dir)
- }
- if err := runBootStart(context.Background(), app); err != nil {
- t.Fatal(err)
- }
- if len(started) != 1 || started[0] != inst.Dir {
- t.Fatalf("voice servers started for %v", started)
- }
-
- started = nil
- inst.State.Stopped = true
- if err := inst.Save(); err != nil {
- t.Fatal(err)
- }
- if err := runBootStart(context.Background(), app); err != nil {
- t.Fatal(err)
- }
- if len(started) != 0 {
- t.Fatalf("a stopped instance started voice servers for %v", started)
- }
-}
-
-func TestVoiceCommandsRefuseAnEjectedInstance(t *testing.T) {
- clearRecords(t)
- inst, err := instance.Create(resolved(t, t.TempDir()), "fluxer")
- if err != nil {
- t.Fatal(err)
- }
- inst.State.Ejected = &instance.Ejected{At: time.Now()}
- inst.State.Voice = []instance.VoiceServer{{ID: "fra-server-1", Edge: voice.EdgeInstance}}
- if err := inst.Save(); err != nil {
- t.Fatal(err)
- }
- before, err := os.ReadFile(inst.StatePath())
- if err != nil {
- t.Fatal(err)
- }
- sites, _ := os.ReadDir(inst.Path("caddy.d"))
- refused := func(name string, err error) {
- t.Helper()
- var exit *ui.ExitError
- if !errors.As(err, &exit) || exit.Code != ui.ExitRefused || !strings.Contains(exit.Fix, "rexctl takeover") {
- t.Fatalf("%s: %v", name, err)
- }
- }
- app, _ := testVoiceApp()
- app.Flags.Dir = inst.Dir
- refused("voice add", runVoiceAdd(context.Background(), app, nil, &voiceFlags{}))
- refused("voice remove", removeVoiceServers(context.Background(), app, inst, []*instance.VoiceServer{&inst.State.Voice[0]}, 0, false))
- after, err := os.ReadFile(inst.StatePath())
- if err != nil {
- t.Fatal(err)
- }
- if !bytes.Equal(before, after) {
- t.Fatal("the state changed")
- }
- if now, _ := os.ReadDir(inst.Path("caddy.d")); len(now) != len(sites) {
- t.Fatalf("caddy.d went from %d to %d files", len(sites), len(now))
- }
-}
-
-func TestRemovingAJoinedServerThatNeverRegisteredSkipsTheInstance(t *testing.T) {
- clearRecords(t)
- inst := voiceMachine(t, instance.VoiceServer{ID: "fra-server-1", Instance: "chat.example.com", Edge: voice.EdgeOwn, Joined: true})
- app, out := testVoiceApp()
- if err := unregisterVoiceServer(context.Background(), app, nil, inst, &inst.State.Voice[0], time.Minute); err != nil {
- t.Fatal(err)
- }
- if !strings.Contains(out.String(), "fra-server-1 never joined chat.example.com") {
- t.Fatalf("output: %s", out.String())
- }
-}
-
-func TestVoiceMachineUpgradeRefusesPrefetchAndTo(t *testing.T) {
- clearRecords(t)
- inst := voiceMachine(t, instance.VoiceServer{ID: "fra-server-1", Edge: voice.EdgeInstance})
- for _, f := range []*upgradeFlags{{Prefetch: true}, {To: "2026.1029.100000"}} {
- app, out := testVoiceApp()
- app.Flags.Dir = inst.Dir
- err := runUpgrade(context.Background(), app, f)
- var ee *ui.ExitError
- if !errors.As(err, &ee) || ee.Code != ui.ExitUsage || !strings.Contains(ee.Msg, "voice machine") {
- t.Fatalf("flags %+v gave %v", f, err)
- }
- if strings.Contains(out.String(), "drain") {
- t.Fatalf("flags %+v drained: %q", f, out.String())
- }
- }
-}
-
-type drainNode struct {
- mu sync.Mutex
- draining bool
- patches []bool
-}
-
-func (n *drainNode) serve(t *testing.T) string {
- t.Helper()
- srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- n.mu.Lock()
- defer n.mu.Unlock()
- if r.Method == http.MethodPatch {
- var update voice.NodeUpdate
- if err := json.NewDecoder(r.Body).Decode(&update); err == nil && update.Draining != nil {
- n.draining = *update.Draining
- n.patches = append(n.patches, *update.Draining)
- }
- }
- w.Header().Set("Content-Type", "application/json")
- _ = json.NewEncoder(w).Encode(map[string]any{"is_active": true, "draining": n.draining})
- }))
- t.Cleanup(srv.Close)
- return srv.URL
-}
-
-func stubUpgradedVoiceStart(t *testing.T, start func() error) {
- t.Helper()
- prev := startUpgradedVoiceServer
- t.Cleanup(func() { startUpgradedVoiceServer = prev })
- startUpgradedVoiceServer = func(context.Context, *App, *engine.Engine, *instance.Instance, *instance.VoiceServer, *ui.Step) error {
- return start()
- }
-}
-
-func TestFailedVoiceUpgradeClearsItsDrainAndStaysStale(t *testing.T) {
- clearRecords(t)
- node := &drainNode{}
- inst := voiceMachine(t, instance.VoiceServer{ID: "fra-server-1", NodeURL: node.serve(t), Key: "k", Secret: strings.Repeat("s", 64), Image: "livekit:old", Edge: voice.EdgeNone})
- stubUpgradedVoiceStart(t, func() error { return errors.New("pull failed") })
- app, _ := testVoiceApp()
- srv := &inst.State.Voice[0]
- if err := upgradeVoiceServer(context.Background(), app, nil, nil, inst, srv, "livekit:new", time.Second); err == nil {
- t.Fatal("the failed start gave no error")
- }
- if node.draining || len(node.patches) != 2 || !node.patches[0] || node.patches[1] {
- t.Fatalf("draining %v after patches %v", node.draining, node.patches)
- }
- saved, err := instance.Find(inst.Dir)
- if err != nil {
- t.Fatal(err)
- }
- if got := saved.State.Voice[0]; got.Image != "livekit:old" || got.Drained {
- t.Fatalf("saved server %+v", got)
- }
- if !voiceServerStale(saved, &saved.State.Voice[0], "livekit:new") {
- t.Fatal("the failed server reads as current")
- }
-}
-
-func TestVoiceUpgradeClearsADrainLeftByAnEarlierRun(t *testing.T) {
- clearRecords(t)
- node := &drainNode{draining: true}
- inst := voiceMachine(t, instance.VoiceServer{ID: "fra-server-1", NodeURL: node.serve(t), Key: "k", Secret: strings.Repeat("s", 64), Image: "livekit:old", Edge: voice.EdgeNone, Drained: true})
- stubUpgradedVoiceStart(t, func() error { return nil })
- app, _ := testVoiceApp()
- srv := &inst.State.Voice[0]
- if err := upgradeVoiceServer(context.Background(), app, nil, nil, inst, srv, "livekit:new", time.Second); err != nil {
- t.Fatal(err)
- }
- if node.draining || len(node.patches) != 1 || node.patches[0] {
- t.Fatalf("draining %v after patches %v", node.draining, node.patches)
- }
- if srv.Image != "livekit:new" || srv.Drained {
- t.Fatalf("server %+v", srv)
- }
-}
-
-func TestVoiceUpgradeLeavesAnAdminDrainAlone(t *testing.T) {
- clearRecords(t)
- node := &drainNode{draining: true}
- inst := voiceMachine(t, instance.VoiceServer{ID: "fra-server-1", NodeURL: node.serve(t), Key: "k", Secret: strings.Repeat("s", 64), Image: "livekit:old", Edge: voice.EdgeNone})
- stubUpgradedVoiceStart(t, func() error { return nil })
- app, _ := testVoiceApp()
- if err := upgradeVoiceServer(context.Background(), app, nil, nil, inst, &inst.State.Voice[0], "livekit:new", time.Second); err != nil {
- t.Fatal(err)
- }
- if !node.draining || len(node.patches) > 0 {
- t.Fatalf("draining %v after patches %v", node.draining, node.patches)
- }
-}
-
-func TestCancelledVoiceUpgradeStillClearsItsDrain(t *testing.T) {
- clearRecords(t)
- node := &drainNode{}
- inst := voiceMachine(t, instance.VoiceServer{ID: "fra-server-1", NodeURL: node.serve(t), Key: "k", Secret: strings.Repeat("s", 64), Image: "livekit:old", Edge: voice.EdgeNone})
- ctx, cancel := context.WithCancel(context.Background())
- stubUpgradedVoiceStart(t, func() error {
- cancel()
- return context.Canceled
- })
- app, _ := testVoiceApp()
- if err := upgradeVoiceServer(ctx, app, nil, nil, inst, &inst.State.Voice[0], "livekit:new", time.Second); err == nil {
- t.Fatal("the cancelled upgrade gave no error")
- }
- if node.draining {
- t.Fatalf("still draining after patches %v", node.patches)
- }
-}
diff --git a/fluxer_rexctl/cmd/voice_plan_test.go b/fluxer_rexctl/cmd/voice_plan_test.go
deleted file mode 100644
index 5554ce200..000000000
--- a/fluxer_rexctl/cmd/voice_plan_test.go
+++ /dev/null
@@ -1,326 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-package cmd
-
-import (
- "context"
- "encoding/json"
- "errors"
- "net/http"
- "net/http/httptest"
- "os"
- "path/filepath"
- "slices"
- "strings"
- "testing"
-
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/adminapi"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/instance"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/settings"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/ui"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/voice"
-)
-
-func fluxerWithVoice(t *testing.T, servers ...instance.VoiceServer) *instance.Instance {
- t.Helper()
- inst, err := instance.Create(resolved(t, t.TempDir()), "fluxer")
- if err != nil {
- t.Fatal(err)
- }
- inst.State.Settings["domain"] = "chat.example.com"
- inst.State.Voice = servers
- if err := os.MkdirAll(inst.Path(instance.CaddyDropInDir), 0o755); err != nil {
- t.Fatal(err)
- }
- if err := inst.Save(); err != nil {
- t.Fatal(err)
- }
- if err := instance.Remember(instance.OwnScope(), inst.Dir, true); err != nil {
- t.Fatal(err)
- }
- return inst
-}
-
-func refusal(t *testing.T, err error) *ui.ExitError {
- t.Helper()
- var ee *ui.ExitError
- if !errors.As(err, &ee) {
- t.Fatalf("not a refusal: %v", err)
- }
- return ee
-}
-
-func TestVoiceIDsAreUniqueOnTheWholeMachine(t *testing.T) {
- clearRecords(t)
- fluxer := fluxerWithVoice(t, instance.VoiceServer{ID: "default-server-2", Edge: voice.EdgeInstance})
- if err := os.WriteFile(filepath.Join(fluxer.Path(instance.CaddyDropInDir), voice.DropInName("hand-made")), voice.DropIn("hand-made"), 0o644); err != nil {
- t.Fatal(err)
- }
- machine := voiceMachine(t, instance.VoiceServer{ID: "default-server-3", Edge: voice.EdgeInstance, Joined: true})
- machine.State.VoiceEdge = &instance.VoiceEdge{Instance: fluxer.Dir}
- if err := machine.Save(); err != nil {
- t.Fatal(err)
- }
- for _, inst := range []*instance.Instance{fluxer, machine} {
- taken := voiceIDsInUse(context.Background(), nil, inst, voice.JoinedProject(""))
- for _, id := range []string{"edge", "default-server-2", "default-server-3", "hand-made"} {
- if !slices.Contains(taken, id) {
- t.Errorf("from %s: %s is free in %v", inst.Dir, id, taken)
- }
- }
- }
-}
-
-func TestJoinSkipsAnIDThatAServerNextDoorUses(t *testing.T) {
- clearRecords(t)
- machine := voiceMachine(t)
- preview := &voice.Preview{ServerID: "default-server-2"}
- preview.Region.ID = "default"
- taken := []string{"edge", "default-server-1", "default-server-2"}
- id, err := chooseJoinID(preview, "", machine, taken)
- if err != nil || id != "default-server-3" {
- t.Fatalf("suggested ID: %s, %v", id, err)
- }
- if _, err := chooseJoinID(preview, "default-server-1", machine, taken); !strings.Contains(refusal(t, err).Fix, "--id") {
- t.Fatalf("taken --id: %v", err)
- }
- preview.ServerIDPinned = true
- if _, err := chooseJoinID(preview, "", machine, taken); !strings.Contains(refusal(t, err).Fix, "new token") {
- t.Fatalf("taken pinned ID: %v", err)
- }
- if _, err := chooseJoinID(preview, "other", machine, nil); !strings.Contains(refusal(t, err).Fix, "Leave out --id") {
- t.Fatalf("--id against a pinned ID: %v", err)
- }
- preview = &voice.Preview{ServerID: "edge"}
- preview.Region.ID = "edge"
- if id, err := chooseJoinID(preview, "", machine, []string{"edge"}); err != nil || id != "edge-server-1" {
- t.Fatalf("edge: %s, %v", id, err)
- }
-}
-
-func TestJoinRetryKeepsItsOwnID(t *testing.T) {
- clearRecords(t)
- machine := voiceMachine(t, instance.VoiceServer{ID: "fra-server-1"})
- preview := &voice.Preview{ServerID: "fra-server-1"}
- if id, err := chooseJoinID(preview, "", machine, []string{"fra-server-1"}); err != nil || id != "fra-server-1" {
- t.Fatalf("retry: %s, %v", id, err)
- }
- machine.State.Voice[0].NodeURL = "https://chat.example.com/api/voice/node"
- if _, err := chooseJoinID(preview, "", machine, nil); err == nil {
- t.Fatal("a joined server was joined again")
- }
-}
-
-func TestVoiceAddSkipsIDsOfJoinedServersNextDoor(t *testing.T) {
- clearRecords(t)
- fluxer := fluxerWithVoice(t)
- machine := voiceMachine(t, instance.VoiceServer{ID: "default-server-2", Edge: voice.EdgeInstance, Joined: true})
- machine.State.VoiceEdge = &instance.VoiceEdge{Instance: fluxer.Dir}
- if err := machine.Save(); err != nil {
- t.Fatal(err)
- }
- regions := []adminapi.VoiceRegion{{VoiceRegionAdminResponse: adminapi.VoiceRegionAdminResponse{Id: "default"}, Servers: []adminapi.VoiceServerAdminResponse{{ServerId: "default-server-1"}}}}
- app, _ := testVoiceApp()
- f := &voiceFlags{Count: 1, IP: "203.0.113.9", TCPPort: 7883, UDPPort: 7884}
- plans, err := planVoiceAdd(context.Background(), app, nil, fluxer, regions, "default", f)
- if err != nil || len(plans) != 1 || plans[0].srv.ID != "default-server-3" {
- t.Fatalf("plans %v, %v", plans, err)
- }
- f.ID = "default-server-2"
- if _, err := planVoiceAdd(context.Background(), app, nil, fluxer, regions, "default", f); !strings.Contains(refusal(t, err).Fix, "--id") {
- t.Fatalf("taken --id: %v", err)
- }
-}
-
-func TestEdgeIsNotAServerID(t *testing.T) {
- if err := checkServerID("edge"); err == nil {
- t.Fatal("edge is a server ID")
- }
- if err := checkServerID("fra-server-1"); err != nil {
- t.Fatal(err)
- }
- app, _ := testVoiceApp()
- c := newVoiceTokenCmd(app)
- c.SetArgs([]string{"--id", "edge"})
- c.SilenceUsage, c.SilenceErrors = true, true
- if err := c.Execute(); refusal(t, err).Code != ui.ExitUsage {
- t.Fatalf("token --id edge: %v", err)
- }
-}
-
-func nodeServer(t *testing.T, status int, node map[string]any) string {
- t.Helper()
- srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
- w.Header().Set("Content-Type", "application/json")
- w.WriteHeader(status)
- _ = json.NewEncoder(w).Encode(node)
- }))
- t.Cleanup(srv.Close)
- return srv.URL
-}
-
-func TestUpgradeReadsDrainingOnAVoiceMachine(t *testing.T) {
- url := nodeServer(t, http.StatusOK, map[string]any{"is_active": true, "draining": true})
- inst := &instance.Instance{Dir: t.TempDir(), State: &instance.State{Kind: instance.KindVoice}}
- srv := &instance.VoiceServer{ID: "fra-server-1", NodeURL: url, Key: "k", Secret: strings.Repeat("s", 64)}
- active, draining, err := voiceServerFlags(context.Background(), nil, inst, srv)
- if err != nil || !active || !draining {
- t.Fatalf("active %v, draining %v, %v", active, draining, err)
- }
- if upgradeDrains(active, draining) {
- t.Fatal("the upgrade clears a draining flag an admin set")
- }
- srv.NodeURL = nodeServer(t, http.StatusBadGateway, map[string]any{})
- if _, _, err := voiceServerFlags(context.Background(), nil, inst, srv); err == nil {
- t.Fatal("an unreadable node gave a state")
- }
- fluxer := &instance.Instance{Dir: t.TempDir(), State: &instance.State{}}
- if _, _, err := voiceServerFlags(context.Background(), nil, fluxer, srv); err == nil {
- t.Fatal("no admin API gave a state")
- }
-}
-
-func TestVoiceAddServersFollowThePublicIP(t *testing.T) {
- inst := &instance.Instance{Dir: t.TempDir(), State: &instance.State{Settings: map[string]string{settings.VoicePublicIP: "198.51.100.20"}, Voice: []instance.VoiceServer{
- {ID: "a", NodeIP: "198.51.100.10"},
- {ID: "b", NodeIP: "198.51.100.11", IPPinned: true},
- {ID: "c", NodeIP: "198.51.100.10", Joined: true},
- {ID: "d", NodeIP: "198.51.100.20"},
- }}}
- moved := followVoicePublicIP(inst)
- if len(moved) != 1 || moved[0].ID != "a" || inst.State.Voice[0].NodeIP != "198.51.100.20" {
- t.Fatalf("moved %v", moved)
- }
- if inst.State.Voice[1].NodeIP != "198.51.100.11" || inst.State.Voice[2].NodeIP != "198.51.100.10" {
- t.Fatalf("a pinned or joined server moved: %+v", inst.State.Voice)
- }
- delete(inst.State.Settings, settings.VoicePublicIP)
- moved = followVoicePublicIP(inst)
- if len(moved) != 2 || inst.State.Voice[0].NodeIP != "" || inst.State.Voice[3].NodeIP != "" {
- t.Fatalf("clearing the setting moved %v", moved)
- }
-}
-
-func TestPinnedHostnameIsRequired(t *testing.T) {
- old, oldWait := hostnameLookup, dnsWait
- t.Cleanup(func() { hostnameLookup, dnsWait = old, oldWait })
- dnsWait = 0
- hostnameLookup = func() voice.Resolver {
- return func(context.Context, string) (voice.DNSAnswer, error) {
- return voice.DNSAnswer{A: []string{"192.0.2.1"}}, nil
- }
- }
- pinned := "voice.example.com"
- plan := &joinPlan{preview: &voice.Preview{Hostname: &pinned}, reach: voice.Reachability{PublicIPv4: "203.0.113.7"}}
- app, out := testVoiceApp()
- if err := chooseAddress(context.Background(), app, plan, "fra-server-1", &voiceFlags{Hostname: "other.example.com"}); !strings.Contains(refusal(t, err).Msg, pinned) {
- t.Fatalf("another --hostname: %v", err)
- }
- err := chooseAddress(context.Background(), app, plan, "fra-server-1", &voiceFlags{})
- if ee := refusal(t, err); !strings.Contains(ee.Msg, pinned) || plan.address != "" {
- t.Fatalf("pinned name not on this machine: %v, address %q", err, plan.address)
- }
- if strings.Contains(out.String(), "rexctl voice hostname") {
- t.Fatalf("offered the IP address: %s", out.String())
- }
- plan.preview.Hostname = nil
- if err := chooseAddress(context.Background(), app, plan, "fra-server-1", &voiceFlags{Hostname: "other.example.com"}); err != nil || plan.address != "203.0.113.7" || !plan.ipCert {
- t.Fatalf("unpinned name: %v, address %q", err, plan.address)
- }
-}
-
-func TestEndpointRefusalShowsThePinnedHostname(t *testing.T) {
- err := joinError(&voice.APIError{Code: voice.CodeEndpointInvalid, Detail: "The endpoint must use the hostname voice.example.com"}, "chat.example.com", "fra-server-1")
- if ee := refusal(t, err); !strings.Contains(ee.Fix, "voice.example.com") || strings.Contains(ee.Fix, "IPv4") {
- t.Fatalf("refusal: %+v", ee)
- }
-}
-
-func TestOriginWarningSaysWhatToDo(t *testing.T) {
- if got := originFix(originUnlisted, "chat.example.com", "2026.1030.400"); got != "Upgrade Fluxer on chat.example.com to 2026.1030.400, then reload open pages." {
- t.Errorf("old release: %s", got)
- }
- if got := originFix(originPending, "chat.example.com", "2026.1030.400"); !strings.Contains(got, "rexctl voice status") {
- t.Errorf("pending: %s", got)
- }
- for _, c := range []struct {
- body string
- listed bool
- }{
- {`{"endpoints":{"api_public":"https://chat.example.com/api"}}`, false},
- {`{"endpoints":{"api_public":"https://chat.example.com/api"},"voice_origins":[]}`, true},
- } {
- srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
- _, _ = w.Write([]byte(c.body))
- }))
- disc, err := (&voice.Client{}).Discover(context.Background(), srv.URL)
- srv.Close()
- if err != nil || disc.ListsOrigins != c.listed {
- t.Errorf("%s: %+v, %v", c.body, disc, err)
- }
- }
-}
-
-func TestVoiceAddListsTheProviderPorts(t *testing.T) {
- got := providerPortsText(&instance.VoiceServer{TCPPort: 7883, UDPPort: 7884})
- if !strings.Contains(got, "7883/tcp and 7884/udp") {
- t.Fatal(got)
- }
-}
-
-func TestATakenPinnedIDDoesNotAskForID(t *testing.T) {
- taken := &voice.APIError{Code: voice.CodeIDInUse}
- ee := refusal(t, pinnedJoinError(taken, "chat.example.com", "fra-server-1"))
- if !strings.Contains(ee.Msg, "fra-server-1") || strings.Contains(ee.Fix, "Pass --id") || !strings.Contains(ee.Fix, "rexctl voice token --id") {
- t.Fatalf("pinned: %+v", ee)
- }
- if ee := refusal(t, joinError(taken, "chat.example.com", "fra-server-1")); ee.Fix != "Pass --id with another ID." {
- t.Fatalf("unpinned: %+v", ee)
- }
- var exit *ui.ExitError
- if err := joinError(&voice.APIError{Code: "SOMETHING_ELSE", Message: "No"}, "chat.example.com", "fra-server-1"); !errors.As(err, &exit) || !strings.HasPrefix(exit.Msg, "chat.example.com refused the request (") {
- t.Fatalf("other refusal: %v", err)
- }
-}
-
-func TestJoinSummarySaysWhyItPickedTheRegion(t *testing.T) {
- km := 6200.0
- preview := func(source string) *voice.Preview {
- p := &voice.Preview{}
- p.Region.ID, p.Region.Name, p.Region.DistanceKm, p.Region.Source = "fra", "Frankfurt", &km, source
- return p
- }
- cases := map[string]string{
- "nearest": "fra (Frankfurt), nearest existing region, 6200 km",
- "token": "fra (Frankfurt), from the token, 6200 km away",
- "requested": "fra (Frankfurt), from --region, 6200 km away",
- "": "fra (Frankfurt), 6200 km away",
- }
- for source, want := range cases {
- if got := joinRegionText(preview(source), ""); got != want {
- t.Errorf("%q: %s, want %s", source, got, want)
- }
- }
- if got := joinRegionText(preview(""), "fra"); got != "fra (Frankfurt), from --region, 6200 km away" {
- t.Errorf("an older API with --region: %s", got)
- }
-}
-
-func TestAFailedLocalTestSaysWhatToCheck(t *testing.T) {
- const hint = "Run rexctl doctor to check the ports"
- failed := []transportResult{{Transport: "udp", Err: errors.New("timeout")}}
- app, out := testVoiceApp()
- if reportTransports(app, failed, true) || strings.Count(out.String(), hint) != 1 {
- t.Fatalf("local failure: %s", out.String())
- }
- app, out = testVoiceApp()
- reportTransports(app, []transportResult{{Transport: "udp"}}, true)
- if strings.Contains(out.String(), hint) {
- t.Fatalf("a passing test asks for doctor: %s", out.String())
- }
- app, out = testVoiceApp()
- reportTransports(app, failed, false)
- if strings.Contains(out.String(), hint) {
- t.Fatalf("a remote test asks for doctor: %s", out.String())
- }
-}
diff --git a/fluxer_rexctl/internal/adminapi/explain_test.go b/fluxer_rexctl/internal/adminapi/explain_test.go
deleted file mode 100644
index dc0c02b7d..000000000
--- a/fluxer_rexctl/internal/adminapi/explain_test.go
+++ /dev/null
@@ -1,68 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-package adminapi_test
-
-import (
- "errors"
- "strings"
- "testing"
-
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/adminapi"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/settings"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/ui"
-)
-
-func TestPrivateSSOAddressPointsAtTheSetting(t *testing.T) {
- for _, field := range []string{"issuer", "authorization_url", "token_url", "userinfo_url", "jwks_url"} {
- err := adminapi.Explain(&adminapi.APIError{Status: 400, Fields: []adminapi.FieldError{
- {Path: field, Code: "URL_NOT_PUBLICLY_ROUTABLE", Message: "URL must resolve to a publicly routable address."},
- }})
- var exit *ui.ExitError
- if !errors.As(err, &exit) || exit.Fix != adminapi.SSOPrivateFix {
- t.Errorf("Explain() for %s = %#v, want the private address fix", field, err)
- }
- }
- if !strings.Contains(adminapi.SSOPrivateFix, "config set "+settings.SSOPrivate+" true") {
- t.Errorf("fix %q doesn't name %s", adminapi.SSOPrivateFix, settings.SSOPrivate)
- }
-}
-
-func TestUnresolvableSSOHostnamePointsAtTheSpelling(t *testing.T) {
- err := adminapi.Explain(&adminapi.APIError{Status: 400, Fields: []adminapi.FieldError{
- {Path: "issuer", Code: "URL_HOSTNAME_NOT_RESOLVABLE", Message: "Fluxer couldn't look up the hostname in this URL."},
- }})
- var exit *ui.ExitError
- if !errors.As(err, &exit) || exit.Fix != adminapi.SSOHostnameFix {
- t.Fatalf("Explain() = %#v, want the hostname fix", err)
- }
-}
-
-func TestUnreachableSSOProviderPointsAtTheIssuer(t *testing.T) {
- err := adminapi.Explain(&adminapi.APIError{Status: 400, Fields: []adminapi.FieldError{
- {Path: "sso", Code: "SSO_DISCOVERY_FAILED", Message: "Couldn't connect to the sign-in provider at its issuer URL."},
- }})
- var exit *ui.ExitError
- if !errors.As(err, &exit) || exit.Fix != adminapi.SSODiscoveryFix {
- t.Fatalf("Explain() = %#v, want the discovery fix", err)
- }
-}
-
-func TestMissingSSOIssuerPointsAtTheSetting(t *testing.T) {
- err := adminapi.Explain(&adminapi.APIError{Status: 400, Fields: []adminapi.FieldError{
- {Path: "issuer", Code: "SSO_ISSUER_REQUIRED", Message: "Enter the issuer URL of your sign-in provider."},
- }})
- var exit *ui.ExitError
- if !errors.As(err, &exit) || exit.Fix != adminapi.SSOIssuerRequiredFix {
- t.Fatalf("Explain() = %#v, want the issuer fix", err)
- }
-}
-
-func TestSSOIssuerChangeWithLinksPointsAtTheFlags(t *testing.T) {
- err := adminapi.Explain(&adminapi.APIError{Status: 400, Fields: []adminapi.FieldError{
- {Path: "issuer", Code: "SSO_ISSUER_CHANGE_HAS_IDENTITIES", Message: "2 accounts are linked to the old issuer."},
- }})
- var exit *ui.ExitError
- if !errors.As(err, &exit) || exit.Fix != adminapi.SSOIssuerChangeFix {
- t.Fatalf("Explain() = %#v, want the migrate fix", err)
- }
-}
diff --git a/fluxer_rexctl/internal/backup/fastbackup_test.go b/fluxer_rexctl/internal/backup/fastbackup_test.go
deleted file mode 100644
index 82d629a2a..000000000
--- a/fluxer_rexctl/internal/backup/fastbackup_test.go
+++ /dev/null
@@ -1,215 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-package backup
-
-import (
- "archive/tar"
- "bytes"
- "context"
- "errors"
- "io"
- "os"
- "path/filepath"
- "strings"
- "testing"
- "time"
-)
-
-type spoolEntry struct {
- name string
- typ byte
- data []byte
-}
-
-func writeSpool(t *testing.T, path string, entries []spoolEntry) {
- t.Helper()
- s, err := createSpool(path)
- if err != nil {
- t.Fatalf("create spool: %v", err)
- }
- for _, e := range entries {
- hdr := &tar.Header{Name: e.name, Mode: 0o644, Typeflag: e.typ, ModTime: time.Unix(1700000000, 0)}
- if e.typ == tar.TypeReg {
- hdr.Size = int64(len(e.data))
- }
- if err := s.add(hdr, bytes.NewReader(e.data)); err != nil {
- s.abort()
- t.Fatalf("spool add %s: %v", e.name, err)
- }
- }
- if err := s.finish(); err != nil {
- s.abort()
- t.Fatalf("finish spool: %v", err)
- }
-}
-
-func TestVolumeSpoolStaysUncompressed(t *testing.T) {
- path := filepath.Join(t.TempDir(), "spool")
- writeSpool(t, path, []spoolEntry{
- {name: VolumesPrefix + "seaweedfs-data/", typ: tar.TypeDir},
- {name: VolumesPrefix + "seaweedfs-data/a.bin", typ: tar.TypeReg, data: []byte("hello volume")},
- })
- raw, err := os.ReadFile(path)
- if err != nil {
- t.Fatal(err)
- }
- if len(raw) >= 4 && raw[0] == 0x28 && raw[1] == 0xb5 && raw[2] == 0x2f && raw[3] == 0xfd {
- t.Fatal("the offline spool is a zstd stream; compression still runs while Fluxer is stopped")
- }
- tr := tar.NewReader(bytes.NewReader(raw))
- hdr, err := tr.Next()
- for err == nil && hdr.Typeflag == tar.TypeDir {
- hdr, err = tr.Next()
- }
- if err != nil {
- t.Fatalf("the spool is not a plain readable tar: %v", err)
- }
- body, _ := io.ReadAll(tr)
- if hdr.Name != VolumesPrefix+"seaweedfs-data/a.bin" || string(body) != "hello volume" {
- t.Fatalf("spool content = %q %q", hdr.Name, body)
- }
-}
-
-func TestFastBackupArchiveRoundTrip(t *testing.T) {
- dir := t.TempDir()
- spool := filepath.Join(dir, "spool")
- big := bytes.Repeat([]byte{0x7f, 0x11, 0x42, 0xa0}, 2048)
- entries := []spoolEntry{
- {name: VolumesPrefix + "seaweedfs-data/", typ: tar.TypeDir},
- {name: VolumesPrefix + "seaweedfs-data/a.bin", typ: tar.TypeReg, data: big},
- {name: VolumesPrefix + "seaweedfs-data/sub/b.txt", typ: tar.TypeReg, data: []byte("second file")},
- {name: VolumesPrefix + "valkey-data/dump.rdb", typ: tar.TypeReg, data: []byte("valkey state")},
- }
- writeSpool(t, spool, entries)
-
- final := filepath.Join(dir, "backup"+Extension)
- partial := final + PartialSuffix
- w, err := createArchive(partial)
- if err != nil {
- t.Fatal(err)
- }
- if err := w.addBytes(FilesPrefix+"compose.yaml", 0o644, []byte("services: {}")); err != nil {
- t.Fatal(err)
- }
- if err := w.addBytes(DumpName, 0o600, []byte("PGDMP fake dump")); err != nil {
- t.Fatal(err)
- }
- if err := compressSpool(context.Background(), w, spool); err != nil {
- t.Fatalf("compressSpool: %v", err)
- }
- m := &Manifest{
- Project: "fluxer",
- Domain: "chat.example.com",
- CreatedAt: time.Now().UTC().Truncate(time.Second),
- Database: DumpName,
- Volumes: []string{"seaweedfs-data", "valkey-data"},
- }
- if err := w.finish(m); err != nil {
- t.Fatalf("finish: %v", err)
- }
- if err := os.Rename(partial, final); err != nil {
- t.Fatal(err)
- }
-
- if _, err := Verify(final); err != nil {
- t.Fatalf("Verify rejected the recompressed archive: %v", err)
- }
-
- got := map[string]string{}
- err = walkArchive(final, func(hdr *tar.Header, r io.Reader) error {
- if hdr.Typeflag != tar.TypeReg {
- return nil
- }
- b, err := io.ReadAll(r)
- if err != nil {
- return err
- }
- got[hdr.Name] = string(b)
- return nil
- })
- if err != nil {
- t.Fatalf("walkArchive: %v", err)
- }
- want := map[string]string{
- FilesPrefix + "compose.yaml": "services: {}",
- DumpName: "PGDMP fake dump",
- VolumesPrefix + "seaweedfs-data/a.bin": string(big),
- VolumesPrefix + "seaweedfs-data/sub/b.txt": "second file",
- VolumesPrefix + "valkey-data/dump.rdb": "valkey state",
- }
- for name, body := range want {
- if got[name] != body {
- t.Fatalf("%s round-tripped to %d bytes, want %d", name, len(got[name]), len(body))
- }
- }
- if _, ok := got[ManifestName]; !ok {
- t.Fatal("the archive has no manifest")
- }
-}
-
-func TestCompressSpoolCancelKeepsInstanceUp(t *testing.T) {
- dir := t.TempDir()
- spool := filepath.Join(dir, "spool")
- writeSpool(t, spool, []spoolEntry{{name: VolumesPrefix + "valkey-data/x", typ: tar.TypeReg, data: []byte("x")}})
- w, err := createArchive(filepath.Join(dir, "out"+PartialSuffix))
- if err != nil {
- t.Fatal(err)
- }
- defer w.abort()
- ctx, cancel := context.WithCancel(context.Background())
- cancel()
- err = compressSpool(ctx, w, spool)
- var ie *InterruptedError
- if !errors.As(err, &ie) || !ie.Restarted {
- t.Fatalf("a cancelled online compression returned %v, want an interrupted error flagged as restarted", err)
- }
-}
-
-func TestCompressSpoolCorruptReportsCompressError(t *testing.T) {
- dir := t.TempDir()
- spool := filepath.Join(dir, "spool")
- if err := os.WriteFile(spool, bytes.Repeat([]byte{0xff}, 1024), 0o600); err != nil {
- t.Fatal(err)
- }
- w, err := createArchive(filepath.Join(dir, "out"+PartialSuffix))
- if err != nil {
- t.Fatal(err)
- }
- defer w.abort()
- err = compressSpool(context.Background(), w, spool)
- var ce *CompressError
- if !errors.As(err, &ce) {
- t.Fatalf("a broken spool returned %v, want a CompressError", err)
- }
- var ie *InterruptedError
- if errors.As(err, &ie) {
- t.Fatal("a broken spool must not look like an interruption")
- }
-}
-
-func TestBackupDiskNeedCountsRawIntermediate(t *testing.T) {
- const db = uint64(1 << 30)
- const vol = uint64(10 << 30)
- got := backupDiskNeed(db, vol)
- want := (db + vol*2) * diskHeadroomPct / 100
- if got != want {
- t.Fatalf("backupDiskNeed = %d, want %d", got, want)
- }
- single := (db + vol) * diskHeadroomPct / 100
- if got <= single {
- t.Fatalf("backupDiskNeed = %d does not reserve room for the raw intermediate (a single copy needs %d)", got, single)
- }
- if backupDiskNeed(db, 0) != db*diskHeadroomPct/100 {
- t.Fatal("with no volumes the need should not double anything")
- }
-}
-
-func TestCompressErrorMessageNamesCompression(t *testing.T) {
- e := &CompressError{Err: errors.New("no space left on device")}
- if !strings.Contains(e.Error(), "compressing") {
- t.Fatalf("CompressError message = %q", e.Error())
- }
- if !errors.Is(e, e.Err) {
- t.Fatal("CompressError should unwrap to its cause")
- }
-}
diff --git a/fluxer_rexctl/internal/backup/layout_test.go b/fluxer_rexctl/internal/backup/layout_test.go
deleted file mode 100644
index b75f0f20c..000000000
--- a/fluxer_rexctl/internal/backup/layout_test.go
+++ /dev/null
@@ -1,135 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-package backup
-
-import (
- "bytes"
- "errors"
- "os"
- "path/filepath"
- "testing"
-
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/instance"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/stack"
-)
-
-const oldState = `{"schema": 2, "project": "fluxer", "release": "", "settings": {}, "rendered": {}}`
-
-func oldLayoutDir(t *testing.T) (string, map[string][]byte) {
- t.Helper()
- dir := t.TempDir()
- files := map[string][]byte{
- stack.ComposeFile: []byte("name: fluxer\nservices: {}\n"),
- stack.Caddyfile: []byte(":80 {\n}\n"),
- instance.CustomCompose: []byte("services: {}\n"),
- filepath.Join(instance.CaddyDropInDir, "x.caddy"): []byte("header X-Mine yes\n"),
- filepath.Join("ca", "ca.pem"): []byte("pem\n"),
- filepath.Join(instance.StateDirName, instance.StateFileName): []byte(oldState),
- }
- for name, data := range files {
- if err := os.MkdirAll(filepath.Dir(filepath.Join(dir, name)), 0o700); err != nil {
- t.Fatal(err)
- }
- if err := os.WriteFile(filepath.Join(dir, name), data, 0o644); err != nil {
- t.Fatal(err)
- }
- }
- return dir, files
-}
-
-func archiveOf(t *testing.T, inst *instance.Instance) string {
- t.Helper()
- path := filepath.Join(t.TempDir(), "backup.tar.zst")
- w, err := createArchive(path)
- if err != nil {
- t.Fatal(err)
- }
- if err := addInstanceFiles(w, inst); err != nil {
- w.abort()
- t.Fatal(err)
- }
- if err := w.finish(&Manifest{Project: "fluxer"}); err != nil {
- t.Fatal(err)
- }
- return path
-}
-
-func restoredFrom(t *testing.T, archive string) *instance.Instance {
- t.Helper()
- dir := t.TempDir()
- if err := extractFiles(archive, dir); err != nil {
- t.Fatal(err)
- }
- inst, err := instance.Find(dir)
- if err != nil {
- t.Fatal(err)
- }
- return inst
-}
-
-func movedInstance(t *testing.T, dir string) *instance.Instance {
- t.Helper()
- inst, err := instance.Find(dir)
- if err != nil {
- t.Fatal(err)
- }
- if err := inst.Migrate(nil); err != nil {
- t.Fatal(err)
- }
- return inst
-}
-
-func TestOldBackupRestoresOnTheOldLayout(t *testing.T) {
- dir, files := oldLayoutDir(t)
- inst := restoredFrom(t, archiveOf(t, &instance.Instance{Dir: dir}))
- if !inst.OldLayout() {
- t.Fatal("an old backup restored as the new layout")
- }
- for _, name := range []string{stack.ComposeFile, stack.Caddyfile} {
- if inst.Generated(name) != inst.Path(name) {
- t.Fatalf("%s resolves to %s", name, inst.Generated(name))
- }
- got, err := os.ReadFile(inst.Path(name))
- if err != nil || !bytes.Equal(got, files[name]) {
- t.Fatalf("%s: %q, %v", name, got, err)
- }
- }
- moved := movedInstance(t, inst.Dir)
- for _, name := range []string{stack.ComposeFile, stack.Caddyfile} {
- got, err := os.ReadFile(moved.Generated(name))
- if err != nil || !bytes.Equal(got, files[name]) {
- t.Fatalf("%s after moving: %q, %v", name, got, err)
- }
- }
- for _, name := range []string{instance.CustomCompose, filepath.Join(instance.CaddyDropInDir, "x.caddy")} {
- if got, err := os.ReadFile(inst.Path(name)); err != nil || !bytes.Equal(got, files[name]) {
- t.Fatalf("%s: %q, %v", name, got, err)
- }
- }
-}
-
-func TestNewBackupKeepsGeneratedFolder(t *testing.T) {
- dir, files := oldLayoutDir(t)
- inst := restoredFrom(t, archiveOf(t, movedInstance(t, dir)))
- if got, err := os.ReadFile(inst.Generated(stack.ComposeFile)); err != nil || !bytes.Equal(got, files[stack.ComposeFile]) {
- t.Fatalf("compose file: %q, %v", got, err)
- }
- ca := filepath.Join("ca", "ca.pem")
- if got, err := os.ReadFile(inst.Path(ca)); err != nil || !bytes.Equal(got, files[ca]) {
- t.Fatalf("%s: %q, %v", ca, got, err)
- }
- if _, err := os.Stat(inst.Path(stack.ComposeFile)); !errors.Is(err, os.ErrNotExist) {
- t.Fatal("a compose file showed up in the instance folder")
- }
-}
-
-func TestClearingAnInstanceRemovesGeneratedFolder(t *testing.T) {
- dir, _ := oldLayoutDir(t)
- movedInstance(t, dir)
- if err := clearInstanceFiles(dir); err != nil {
- t.Fatal(err)
- }
- if _, err := os.Stat(stack.GeneratedPath(dir)); !errors.Is(err, os.ErrNotExist) {
- t.Fatal("generated files stayed behind before the restore")
- }
-}
diff --git a/fluxer_rexctl/internal/backup/scope_test.go b/fluxer_rexctl/internal/backup/scope_test.go
deleted file mode 100644
index 11167de44..000000000
--- a/fluxer_rexctl/internal/backup/scope_test.go
+++ /dev/null
@@ -1,644 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-package backup
-
-import (
- "archive/tar"
- "bytes"
- "context"
- "encoding/json"
- "errors"
- "maps"
- "os"
- "path/filepath"
- "slices"
- "strings"
- "testing"
- "time"
-
- "github.com/compose-spec/compose-go/v2/types"
-
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/engine"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/instance"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/stack"
-)
-
-const (
- uploadsCreated = "2026-10-01T04:00:00Z"
- testDefinition = "sha256:uploads"
-)
-
-func projectVolumes() []engine.Volume {
- var out []engine.Volume
- for _, short := range []string{"postgres-data", "valkey-data", "nats-data", "meilisearch-data", UploadsVolume} {
- out = append(out, engine.Volume{Name: "fluxer_" + short, Project: "fluxer", Labels: map[string]string{"com.docker.compose.volume": short}, CreatedAt: uploadsCreated})
- }
- return out
-}
-
-func shorts(vols []volumeRef) []string {
- var out []string
- for _, v := range vols {
- out = append(out, v.short)
- }
- return out
-}
-
-func TestWithoutUploadsLeavesSeaweedOut(t *testing.T) {
- m := &Manifest{}
- got := shorts(pickVolumes(nil, "fluxer", projectVolumes(), false, ScopeWithoutUploads, testDefinition, true, m))
- if slices.Contains(got, UploadsVolume) || !slices.Equal(got, []string{"valkey-data", "nats-data", "meilisearch-data"}) {
- t.Errorf("a backup without uploads copies %v", got)
- }
- if m.Scope != ScopeWithoutUploads || m.Uploads == nil || m.Uploads.Volume != "fluxer_seaweedfs-data" || m.Uploads.CreatedAt != uploadsCreated {
- t.Errorf("manifest = %+v, uploads %+v", m, m.Uploads)
- }
- if m.HasSkipped(SkippedUploads) {
- t.Error("leaving uploads out on purpose was recorded as uploads stored outside Fluxer")
- }
- if m.Uploads.Definition != testDefinition {
- t.Errorf("the backup records the uploads service as %q", m.Uploads.Definition)
- }
- unknown := &Manifest{}
- if got := shorts(pickVolumes(nil, "fluxer", projectVolumes(), false, ScopeWithoutUploads, "", true, unknown)); !slices.Contains(got, UploadsVolume) || unknown.WithoutUploads() {
- t.Errorf("without a known uploads service the backup copies %v with scope %q", got, unknown.Scope)
- }
- full := &Manifest{}
- if got := shorts(pickVolumes(nil, "fluxer", projectVolumes(), false, ScopeFull, testDefinition, true, full)); !slices.Contains(got, UploadsVolume) || full.Scope != "" || full.Uploads != nil {
- t.Errorf("a full backup copies %v with scope %q", got, full.Scope)
- }
- none := &Manifest{}
- pickVolumes(nil, "fluxer", projectVolumes()[:4], false, ScopeWithoutUploads, testDefinition, true, none)
- if none.Scope != "" {
- t.Error("an instance without an uploads volume made a backup that can't restore on its own")
- }
-}
-
-func writeScoped(t *testing.T, m *Manifest) string {
- t.Helper()
- final := filepath.Join(t.TempDir(), "fluxer-test"+Extension)
- w, err := createArchive(final + PartialSuffix)
- if err != nil {
- t.Fatal(err)
- }
- if err := w.addBytes(FilesPrefix+"compose.yaml", 0o644, []byte("services: {}")); err != nil {
- t.Fatal(err)
- }
- if err := w.finish(m); err != nil {
- t.Fatal(err)
- }
- if err := os.Rename(final+PartialSuffix, final); err != nil {
- t.Fatal(err)
- }
- return final
-}
-
-func TestWithoutUploadsWritesFormatTwo(t *testing.T) {
- path := writeScoped(t, &Manifest{Project: "fluxer", Domain: "chat.example.com", CreatedAt: time.Now().UTC(), Scope: ScopeWithoutUploads, Uploads: &UploadsRef{Volume: "fluxer_seaweedfs-data", CreatedAt: uploadsCreated}})
- m, err := Verify(path)
- if err != nil {
- t.Fatal(err)
- }
- if m.Format != 2 || !m.WithoutUploads() || m.Uploads.Volume != "fluxer_seaweedfs-data" {
- t.Errorf("manifest = %+v", m)
- }
- info, err := Stat(path)
- if err != nil || !info.WithoutUploads() {
- t.Errorf("Stat = %+v, %v", info, err)
- }
- if _, err := parseManifest([]byte(`{"format":3,"release":"x"}`)); !errors.Is(err, ErrNewer) {
- t.Errorf("format 3 = %v, want ErrNewer", err)
- }
-}
-
-func TestFullBackupStaysFormatOne(t *testing.T) {
- path := writeScoped(t, &Manifest{Project: "fluxer", Domain: "chat.example.com", CreatedAt: time.Now().UTC()})
- m, err := ReadManifest(path)
- if err != nil {
- t.Fatal(err)
- }
- if m.Format != 1 || m.Scope != "" || m.Uploads != nil {
- t.Errorf("manifest = %+v", m)
- }
-}
-
-func TestEstimateAndCreatePickTheSameVolumes(t *testing.T) {
- lean := pickVolumes(nil, "fluxer", projectVolumes(), false, ScopeWithoutUploads, testDefinition, true, &Manifest{})
- full := pickVolumes(nil, "fluxer", projectVolumes(), false, ScopeFull, "", true, &Manifest{})
- if len(full)-len(lean) != 1 || slices.Contains(shorts(lean), UploadsVolume) {
- t.Errorf("the estimate measures %v without uploads and %v with them", shorts(lean), shorts(full))
- }
-}
-
-func TestExternalUploadsStillMarkedSkipped(t *testing.T) {
- for _, scope := range []string{ScopeFull, ScopeWithoutUploads} {
- m := &Manifest{}
- got := shorts(pickVolumes(nil, "fluxer", projectVolumes(), true, scope, testDefinition, true, m))
- if slices.Contains(got, UploadsVolume) || !m.HasSkipped(SkippedUploads) || m.Scope != "" || m.Uploads != nil {
- t.Errorf("%s with external uploads copies %v with manifest %+v", scope, got, m)
- }
- }
-}
-
-func leanInstance(t *testing.T) *instance.Instance {
- t.Helper()
- inst, err := instance.Create(t.TempDir(), "fluxer")
- if err != nil {
- t.Fatal(err)
- }
- inst.State.Settings["FLUXER_DOMAIN"] = "chat.example.com"
- inst.State.Engine = instance.EngineRef{Kind: "docker", ID: "engine-1"}
- if err := inst.Save(); err != nil {
- t.Fatal(err)
- }
- return inst
-}
-
-func leanManifest(inst *instance.Instance) *Manifest {
- return &Manifest{Project: inst.Project(), Domain: inst.Domain(), Scope: ScopeWithoutUploads, Uploads: &UploadsRef{Volume: "fluxer_seaweedfs-data", CreatedAt: uploadsCreated, Definition: uploadsDefinition(inst)}}
-}
-
-var dockerEngine = &engine.Engine{Kind: engine.Docker, ID: "engine-1"}
-
-func recordDown(t *testing.T) *[]string {
- t.Helper()
- var calls []string
- prev := downProject
- t.Cleanup(func() { downProject = prev })
- downProject = func(_ context.Context, p *engine.Project, keep []string) error {
- calls = append(calls, p.Name+" keeping "+strings.Join(keep, ","))
- return nil
- }
- return &calls
-}
-
-func TestRestoreWithoutUploadsKeepsUploadsVolume(t *testing.T) {
- inst := leanInstance(t)
- m := leanManifest(inst)
- if err := uploadsInPlace(inst.Dir, inst, dockerEngine, projectVolumes(), m); err != nil {
- t.Fatalf("the instance the backup was made for refused it with %v", err)
- }
- calls := recordDown(t)
- if _, err := clearForRestore(context.Background(), inst.Dir, inst, dockerEngine, m); err != nil {
- t.Fatal(err)
- }
- if want := []string{"fluxer keeping " + UploadsVolume}; !slices.Equal(*calls, want) {
- t.Errorf("a restore without uploads ran %q, want %q", *calls, want)
- }
- *calls = nil
- full := leanInstance(t)
- if _, err := clearForRestore(context.Background(), full.Dir, full, dockerEngine, &Manifest{Project: "fluxer"}); err != nil {
- t.Fatal(err)
- }
- if want := []string{"fluxer keeping "}; !slices.Equal(*calls, want) {
- t.Errorf("a full restore ran %q, want %q", *calls, want)
- }
- if _, err := os.Stat(restoreMarkerPath(full.Dir)); !errors.Is(err, os.ErrNotExist) {
- t.Errorf("a full restore left a marker (%v)", err)
- }
-}
-
-func TestRestoreWithoutUploadsLeavesUploadsDataAlone(t *testing.T) {
- inst := leanInstance(t)
- m := leanManifest(inst)
- m.Volumes = []string{"valkey-data"}
- final := filepath.Join(t.TempDir(), "fluxer-test"+Extension)
- w, err := createArchive(final + PartialSuffix)
- if err != nil {
- t.Fatal(err)
- }
- if err := w.addBytes(FilesPrefix+"compose.yaml", 0o644, []byte("services: {}")); err != nil {
- t.Fatal(err)
- }
- if err := w.addBytes(VolumesPrefix+UploadsVolume+"/1.dat", 0o644, []byte("volume")); err != nil {
- t.Fatal(err)
- }
- if err := w.finish(m); err != nil {
- t.Fatal(err)
- }
- err = restoreData(context.Background(), final+PartialSuffix, &engine.Project{Name: "fluxer"}, "helper", m, projectVolumes(), "", func(string) {})
- if !errors.Is(err, ErrDamaged) {
- t.Errorf("restoring uploads data from a backup without uploads gave %v, want ErrDamaged", err)
- }
-}
-
-func TestRestoreWithoutUploadsRefusesNewerUploadsService(t *testing.T) {
- inst := leanInstance(t)
- images, err := stack.EmbeddedImages()
- if err != nil {
- t.Fatal(err)
- }
- inst.State.Images.Refs = maps.Clone(images.Images)
- onB := leanManifest(inst)
- if onB.Uploads.Definition == "" {
- t.Fatal("the uploads service of release B has no definition")
- }
- if err := uploadsInPlace(inst.Dir, inst, dockerEngine, projectVolumes(), onB); err != nil {
- t.Fatalf("the same seaweedfs was refused with %v", err)
- }
- inst.State.Images.Refs["seaweedfs"] = "chrislusf/seaweedfs:99.1"
- refused(t, uploadsInPlace(inst.Dir, inst, dockerEngine, projectVolumes(), onB), "a backup from before a new seaweedfs")
- onB.Uploads.Definition = ""
- refused(t, uploadsInPlace(inst.Dir, inst, dockerEngine, projectVolumes(), onB), "a backup that doesn't record the uploads service")
-}
-
-func TestRestoreWithoutUploadsRefusesSeaweedImageSetting(t *testing.T) {
- inst := leanInstance(t)
- images, err := stack.EmbeddedImages()
- if err != nil {
- t.Fatal(err)
- }
- inst.State.Images.Refs = maps.Clone(images.Images)
- m := leanManifest(inst)
- inst.State.Settings["images.seaweedfs"] = "chrislusf/seaweedfs:99.1"
- refused(t, uploadsInPlace(inst.Dir, inst, dockerEngine, projectVolumes(), m), "a backup from before images.seaweedfs was set")
- delete(inst.State.Settings, "images.seaweedfs")
- inst.State.Settings["FLUXER_SEAWEEDFS_IMAGE"] = "chrislusf/seaweedfs:99.1"
- refused(t, uploadsInPlace(inst.Dir, inst, dockerEngine, projectVolumes(), m), "a backup from before FLUXER_SEAWEEDFS_IMAGE was set")
- delete(inst.State.Settings, "FLUXER_SEAWEEDFS_IMAGE")
- if err := uploadsInPlace(inst.Dir, inst, dockerEngine, projectVolumes(), m); err != nil {
- t.Errorf("the same seaweedfs image was refused with %v", err)
- }
-}
-
-func TestLeanRestoreCanRunAgainAfterFailing(t *testing.T) {
- inst := leanInstance(t)
- uploads := filepath.Join(inst.Dir, "uploads")
- if err := os.Mkdir(uploads, 0o755); err != nil {
- t.Fatal(err)
- }
- m := &Manifest{Project: inst.Project(), Domain: inst.Domain(), Scope: ScopeWithoutUploads, Uploads: bindRef(t, uploads, uploadsDefinition(inst))}
- path := writeScoped(t, m)
- recordDown(t)
- if _, err := clearForRestore(context.Background(), inst.Dir, inst, dockerEngine, m); err != nil {
- t.Fatal(err)
- }
- if _, err := instance.Find(inst.Dir); !errors.Is(err, instance.ErrNotFound) {
- t.Fatalf("after clearing, Find = %v", err)
- }
- if err := CheckUploadsInPlace(context.Background(), inst.Dir, nil, dockerEngine, m); err != nil {
- t.Errorf("running the same restore again was refused with %v", err)
- }
- if !ResumesRestore(inst.Dir, m) {
- t.Error("the restore that was cut short isn't recognised")
- }
- if err := uploadsInPlace(inst.Dir, nil, &engine.Engine{Kind: engine.Podman, ID: "engine-1"}, nil, m); err == nil {
- t.Error("running it again on another engine was allowed")
- }
- other := *m
- otherRef := *m.Uploads
- otherRef.Definition = "sha256:other"
- other.Uploads = &otherRef
- refused(t, uploadsInPlace(inst.Dir, nil, dockerEngine, nil, &other), "another backup without uploads")
- if err := os.RemoveAll(uploads); err != nil {
- t.Fatal(err)
- }
- refused(t, uploadsInPlace(inst.Dir, nil, dockerEngine, nil, m), "the same restore with the uploads gone")
- if err := os.Remove(restoreMarkerPath(inst.Dir)); err != nil {
- t.Fatal(err)
- }
- _, err := Restore(context.Background(), path, inst.Dir, dockerEngine, RestoreOptions{})
- refused(t, err, "a restore without the marker or the state")
-}
-
-func TestRestoreWithoutUploadsKeepsBindMount(t *testing.T) {
- inst := leanInstance(t)
- uploads := filepath.Join(inst.Dir, "uploads")
- if err := os.MkdirAll(uploads, 0o755); err != nil {
- t.Fatal(err)
- }
- if err := os.WriteFile(filepath.Join(uploads, "a.bin"), []byte("attachment"), 0o600); err != nil {
- t.Fatal(err)
- }
- model := &types.Project{Services: types.Services{"seaweedfs": {Name: "seaweedfs", Volumes: []types.ServiceVolumeConfig{{Type: types.VolumeTypeBind, Source: uploads, Target: "/data"}}}}}
- m := &Manifest{Project: inst.Project(), Domain: inst.Domain()}
- got := shorts(pickVolumes(model, "fluxer", projectVolumes(), false, ScopeWithoutUploads, uploadsDefinition(inst), true, m))
- if slices.Contains(got, UploadsVolume) || m.Uploads == nil || m.Uploads.Bind != uploads {
- t.Fatalf("volumes %v, uploads %+v", got, m.Uploads)
- }
- if m.Uploads.ID == "" {
- t.Fatal("the backup doesn't record which uploads folder it belongs with")
- }
- if err := uploadsInPlace("", inst, dockerEngine, nil, m); err != nil {
- t.Fatalf("the bind mount the backup was made with was refused with %v", err)
- }
- again := &Manifest{Project: inst.Project(), Domain: inst.Domain()}
- pickVolumes(model, "fluxer", projectVolumes(), false, ScopeWithoutUploads, uploadsDefinition(inst), true, again)
- if again.Uploads == nil || again.Uploads.ID != m.Uploads.ID {
- t.Errorf("a second backup records %+v, want the same identity as %+v", again.Uploads, m.Uploads)
- }
- if err := clearInstanceFiles(inst.Dir); err != nil {
- t.Fatal(err)
- }
- if data, err := os.ReadFile(filepath.Join(uploads, "a.bin")); err != nil || string(data) != "attachment" {
- t.Errorf("clearing the instance touched the uploads, which hold %q (%v)", data, err)
- }
- if err := os.RemoveAll(uploads); err != nil {
- t.Fatal(err)
- }
- if err := os.Mkdir(uploads, 0o755); err != nil {
- t.Fatal(err)
- }
- refused(t, uploadsInPlace("", inst, dockerEngine, nil, m), "an uploads folder removed and made again")
- recreated := *m.Uploads
- recreated.Inode, _ = fileInode(uploads)
- refused(t, uploadsIdentity(&recreated, nil), "a folder made again with the same inode")
- if err := os.WriteFile(filepath.Join(uploads, UploadsIDFile), []byte("someone-else\n"), 0o644); err != nil {
- t.Fatal(err)
- }
- refused(t, uploadsIdentity(&recreated, nil), "a folder with another identity")
-}
-
-func TestBindMountIdentityIgnoresDeviceNumber(t *testing.T) {
- inst := leanInstance(t)
- uploads := filepath.Join(inst.Dir, "uploads")
- if err := os.MkdirAll(uploads, 0o755); err != nil {
- t.Fatal(err)
- }
- model := &types.Project{Services: types.Services{"seaweedfs": {Name: "seaweedfs", Volumes: []types.ServiceVolumeConfig{{Type: types.VolumeTypeBind, Source: uploads, Target: "/data"}}}}}
- m := &Manifest{Project: inst.Project(), Domain: inst.Domain()}
- pickVolumes(model, "fluxer", projectVolumes(), false, ScopeWithoutUploads, uploadsDefinition(inst), true, m)
- if m.Uploads == nil || m.Uploads.ID == "" {
- t.Fatalf("uploads %+v", m.Uploads)
- }
- data, err := json.Marshal(m.Uploads)
- if err != nil {
- t.Fatal(err)
- }
- if strings.Contains(string(data), `"dev"`) {
- t.Errorf("the backup records the device number of the uploads folder in %s", data)
- }
- var afterReboot UploadsRef
- moved := strings.Replace(string(data), "{", `{"dev":4242,`, 1)
- if err := json.Unmarshal([]byte(moved), &afterReboot); err != nil {
- t.Fatal(err)
- }
- if err := uploadsIdentity(&afterReboot, nil); err != nil {
- t.Errorf("the same folder with another device number was refused with %v", err)
- }
- otherInode := *m.Uploads
- otherInode.Inode++
- refused(t, uploadsIdentity(&otherInode, nil), "the same identity file in another folder")
-}
-
-func TestEstimateDoesNotMarkBindMount(t *testing.T) {
- uploads := t.TempDir()
- model := &types.Project{Services: types.Services{"seaweedfs": {Name: "seaweedfs", Volumes: []types.ServiceVolumeConfig{{Type: types.VolumeTypeBind, Source: uploads, Target: "/data"}}}}}
- got := shorts(pickVolumes(model, "fluxer", projectVolumes(), false, ScopeWithoutUploads, testDefinition, false, &Manifest{}))
- if slices.Contains(got, UploadsVolume) {
- t.Errorf("the estimate for a bind mount copies %v", got)
- }
- if _, err := os.Stat(filepath.Join(uploads, UploadsIDFile)); !errors.Is(err, os.ErrNotExist) {
- t.Errorf("the estimate wrote %s (%v)", UploadsIDFile, err)
- }
-}
-
-func TestBindMountWithoutIdentityGetsFullBackup(t *testing.T) {
- uploads := t.TempDir()
- if err := os.Mkdir(filepath.Join(uploads, UploadsIDFile), 0o755); err != nil {
- t.Fatal(err)
- }
- model := &types.Project{Services: types.Services{"seaweedfs": {Name: "seaweedfs", Volumes: []types.ServiceVolumeConfig{{Type: types.VolumeTypeBind, Source: uploads, Target: "/data"}}}}}
- m := &Manifest{}
- got := shorts(pickVolumes(model, "fluxer", projectVolumes(), false, ScopeWithoutUploads, testDefinition, true, m))
- if !slices.Contains(got, UploadsVolume) || m.WithoutUploads() {
- t.Errorf("a bind mount rexctl can't mark copies %v with scope %q", got, m.Scope)
- }
-}
-
-func refused(t *testing.T, err error, what string) {
- t.Helper()
- var ue *UploadsNotHereError
- if !errors.Is(err, ErrUploadsNotHere) || !errors.As(err, &ue) {
- t.Errorf("%s gave %v, want a refusal", what, err)
- }
-}
-
-func TestRestoreWithoutUploadsRefusesNewMachine(t *testing.T) {
- inst := leanInstance(t)
- m := leanManifest(inst)
- refused(t, uploadsInPlace("", nil, dockerEngine, nil, m), "no instance")
- path := writeScoped(t, m)
- fresh := filepath.Join(t.TempDir(), "fluxer")
- _, err := Restore(context.Background(), path, fresh, dockerEngine, RestoreOptions{})
- refused(t, err, "Restore on a new machine")
- if _, err := os.Stat(fresh); !errors.Is(err, os.ErrNotExist) {
- t.Errorf("the refused restore made %s", fresh)
- }
- if err := CheckUploadsInPlace(context.Background(), "", nil, nil, &Manifest{}); err != nil {
- t.Errorf("a full backup was refused with %v", err)
- }
-}
-
-func TestRestoreWithoutUploadsRefusesOtherInstance(t *testing.T) {
- inst := leanInstance(t)
- m := leanManifest(inst)
- m.Domain = "other.example.com"
- refused(t, uploadsInPlace("", inst, dockerEngine, projectVolumes(), m), "another domain")
- m = leanManifest(inst)
- m.Project = "blue"
- refused(t, uploadsInPlace("", inst, dockerEngine, projectVolumes(), m), "another project")
-}
-
-func TestRestoreWithoutUploadsRefusesReplacedVolume(t *testing.T) {
- inst := leanInstance(t)
- m := leanManifest(inst)
- vols := projectVolumes()
- vols[4].CreatedAt = "2026-11-02T09:00:00Z"
- refused(t, uploadsInPlace("", inst, dockerEngine, vols, m), "a volume made again")
- refused(t, uploadsInPlace("", inst, dockerEngine, projectVolumes()[:4], m), "a missing volume")
-
- root := t.TempDir()
- uploads := filepath.Join(root, "uploads")
- if err := os.Mkdir(uploads, 0o755); err != nil {
- t.Fatal(err)
- }
- b := &Manifest{Project: inst.Project(), Domain: inst.Domain(), Scope: ScopeWithoutUploads, Uploads: bindRef(t, uploads, uploadsDefinition(inst))}
- if err := uploadsInPlace("", inst, dockerEngine, nil, b); err != nil {
- t.Fatalf("the same folder was refused with %v", err)
- }
- if err := os.Rename(uploads, filepath.Join(root, "old")); err != nil {
- t.Fatal(err)
- }
- refused(t, uploadsInPlace("", inst, dockerEngine, nil, b), "a missing folder")
- if err := os.Mkdir(uploads, 0o755); err != nil {
- t.Fatal(err)
- }
- refused(t, uploadsInPlace("", inst, dockerEngine, nil, b), "a folder made again")
-}
-
-func bindRef(t *testing.T, dir, definition string) *UploadsRef {
- t.Helper()
- ref := uploadsRef(volumeRef{short: UploadsVolume, bind: dir}, nil, true)
- if ref == nil || ref.ID == "" {
- t.Fatalf("no identity for %s: %+v", dir, ref)
- }
- ref.Definition = definition
- return ref
-}
-
-func TestRestoreWithoutUploadsRefusesEngineMove(t *testing.T) {
- inst := leanInstance(t)
- m := leanManifest(inst)
- refused(t, uploadsInPlace("", inst, &engine.Engine{Kind: engine.Podman, ID: "engine-1"}, projectVolumes(), m), "another kind of engine")
- refused(t, uploadsInPlace("", inst, &engine.Engine{Kind: engine.Docker, ID: "engine-2"}, projectVolumes(), m), "another engine")
- refused(t, uploadsInPlace("", inst, nil, projectVolumes(), m), "no engine")
-}
-
-func TestRestoreForgetsBackupOfAMissingRelease(t *testing.T) {
- inst := leanInstance(t)
- kept := filepath.Join(inst.BackupDir(), "fluxer-a"+Extension)
- if err := os.WriteFile(kept, []byte("x"), 0o600); err != nil {
- t.Fatal(err)
- }
- inst.State.PreviousRelease, inst.State.PreviousBackup = "2026.1001.100000", kept
- if err := adoptRestored(inst, dockerEngine, nil); err != nil {
- t.Fatal(err)
- }
- if inst.State.PreviousRelease != "" || inst.State.PreviousBackup != "" {
- t.Errorf("after the restore the previous release is %q and the previous backup %q", inst.State.PreviousRelease, inst.State.PreviousBackup)
- }
-}
-
-func TestRestoreLetsTheCallerFixFilesBeforeRendering(t *testing.T) {
- inst := leanInstance(t)
- inst.State.Upgrade = &instance.Upgrade{From: "2026.1001.100000", To: "2026.1029.100000", Sites: []string{"Mastodon.caddy"}}
- var seen *instance.Upgrade
- calls := 0
- err := adoptRestored(inst, dockerEngine, func(got *instance.Instance) {
- calls++
- seen = got.State.Upgrade
- })
- if err != nil {
- t.Fatal(err)
- }
- if calls != 1 || seen != nil {
- t.Fatalf("hook ran %d times and saw upgrade %+v", calls, seen)
- }
-}
-
-func TestLeftoverRestoreMarkerKeepsUploadsServiceCheck(t *testing.T) {
- inst := leanInstance(t)
- images, err := stack.EmbeddedImages()
- if err != nil {
- t.Fatal(err)
- }
- inst.State.Images.Refs = maps.Clone(images.Images)
- if err := inst.Save(); err != nil {
- t.Fatal(err)
- }
- uploads := filepath.Join(inst.Dir, "uploads")
- if err := os.Mkdir(uploads, 0o755); err != nil {
- t.Fatal(err)
- }
- m := &Manifest{Project: inst.Project(), Domain: inst.Domain(), Scope: ScopeWithoutUploads, Uploads: bindRef(t, uploads, uploadsDefinition(inst))}
- if err := writeRestoreMarker(inst.Dir, m, dockerEngine); err != nil {
- t.Fatal(err)
- }
- if err := uploadsInPlace(inst.Dir, inst, dockerEngine, nil, m); err != nil {
- t.Fatalf("the same backup after a failed restore was refused with %v", err)
- }
- inst.State.Images.Refs["seaweedfs"] = "chrislusf/seaweedfs:99.1"
- if err := inst.Save(); err != nil {
- t.Fatal(err)
- }
- refused(t, uploadsInPlace(inst.Dir, inst, dockerEngine, nil, m), "a leftover marker with a newer seaweedfs")
- refused(t, CheckUploadsInPlace(context.Background(), inst.Dir, inst, dockerEngine, m), "the check with a leftover marker and a newer seaweedfs")
- if _, err := os.Stat(restoreMarkerPath(inst.Dir)); !errors.Is(err, os.ErrNotExist) {
- t.Errorf("the check left the marker in place (%v)", err)
- }
- if err := writeRestoreMarker(inst.Dir, m, dockerEngine); err != nil {
- t.Fatal(err)
- }
- path := writeScoped(t, m)
- _, err = Restore(context.Background(), path, inst.Dir, dockerEngine, RestoreOptions{})
- refused(t, err, "Restore with a leftover marker and a newer seaweedfs")
- if _, err := os.Stat(restoreMarkerPath(inst.Dir)); !errors.Is(err, os.ErrNotExist) {
- t.Errorf("the leftover marker is still there (%v)", err)
- }
-}
-
-func TestFullRestoreGivesBindUploadsNewIdentity(t *testing.T) {
- uploads := t.TempDir()
- if err := os.WriteFile(filepath.Join(uploads, "new.bin"), []byte("after the full backup"), 0o600); err != nil {
- t.Fatal(err)
- }
- lean := bindRef(t, uploads, testDefinition)
- idFile := filepath.Join(uploads, UploadsIDFile)
- ents, err := os.ReadDir(uploads)
- if err != nil {
- t.Fatal(err)
- }
- for _, e := range ents {
- if err := os.RemoveAll(filepath.Join(uploads, e.Name())); err != nil {
- t.Fatal(err)
- }
- }
- if err := os.WriteFile(idFile, []byte(lean.ID+"\n"), 0o644); err != nil {
- t.Fatal(err)
- }
- if err := os.WriteFile(filepath.Join(uploads, "old.bin"), []byte("from the full backup"), 0o600); err != nil {
- t.Fatal(err)
- }
- if err := forgetUploadsID(uploads); err != nil {
- t.Fatal(err)
- }
- refused(t, uploadsIdentity(lean, nil), "a newer backup without uploads after a full restore")
- again := bindRef(t, uploads, testDefinition)
- if again.ID == lean.ID {
- t.Error("the next backup without uploads kept the identity from before the full restore")
- }
- if err := forgetUploadsID(t.TempDir()); err != nil {
- t.Errorf("a folder without an identity gave %v", err)
- }
-}
-
-func TestVolumeCopyLeavesUploadsIdentityOut(t *testing.T) {
- var src bytes.Buffer
- tw := tar.NewWriter(&src)
- for _, e := range []struct{ name, body string }{{"./" + UploadsIDFile, "abc\n"}, {"./a.bin", "attachment"}} {
- if err := tw.WriteHeader(&tar.Header{Name: e.name, Mode: 0o644, Size: int64(len(e.body)), Typeflag: tar.TypeReg}); err != nil {
- t.Fatal(err)
- }
- if _, err := tw.Write([]byte(e.body)); err != nil {
- t.Fatal(err)
- }
- }
- if err := tw.Close(); err != nil {
- t.Fatal(err)
- }
- for _, short := range []string{UploadsVolume, "valkey-data"} {
- path := filepath.Join(t.TempDir(), "spool")
- s, err := createSpool(path)
- if err != nil {
- t.Fatal(err)
- }
- copied, err := relayVolume(s, short, tar.NewReader(bytes.NewReader(src.Bytes())))
- if err != nil {
- t.Fatal(err)
- }
- if err := s.finish(); err != nil {
- t.Fatal(err)
- }
- if copied != int64(len("abc\n")+len("attachment")) {
- t.Errorf("%s counted %d bytes", short, copied)
- }
- raw, err := os.ReadFile(path)
- if err != nil {
- t.Fatal(err)
- }
- var names []string
- tr := tar.NewReader(bytes.NewReader(raw))
- for {
- hdr, err := tr.Next()
- if err != nil {
- break
- }
- names = append(names, hdr.Name)
- }
- stored := slices.Contains(names, VolumesPrefix+short+"/"+UploadsIDFile)
- if stored != (short != UploadsVolume) {
- t.Errorf("%s stored %v", short, names)
- }
- }
-}
diff --git a/fluxer_rexctl/internal/checks/bundledvoice_test.go b/fluxer_rexctl/internal/checks/bundledvoice_test.go
deleted file mode 100644
index bf4d5b4e9..000000000
--- a/fluxer_rexctl/internal/checks/bundledvoice_test.go
+++ /dev/null
@@ -1,39 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-package checks
-
-import (
- "context"
- "testing"
-
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/engine"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/instance"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/stack"
-)
-
-func TestInstallWithoutBundledVoiceWantsNoVoicePorts(t *testing.T) {
- e := &Env{prepared: true, Settings: map[string]string{stack.VoiceBundledKey: "false"}}
- for _, p := range e.wantedPorts() {
- if p.Number == 7881 || p.Number == 7882 {
- t.Fatalf("wanted ports %v include a voice port", e.wantedPorts())
- }
- }
- e = &Env{prepared: true, Settings: map[string]string{}}
- voice := 0
- for _, p := range e.wantedPorts() {
- if p.Number == 7881 || p.Number == 7882 {
- voice++
- }
- }
- if voice != 2 {
- t.Fatalf("wanted ports %v, want both voice ports", e.wantedPorts())
- }
-}
-
-func TestLiveKitIPSkipsWithoutTheBundledLiveKit(t *testing.T) {
- e := &Env{prepared: true, psDone: true, Instance: &instance.Instance{State: &instance.State{}},
- ps: []engine.Container{{Service: "api", State: "running"}, {Service: "edge", State: "running"}}}
- if r := runLiveKitIP(context.Background(), e); r.Status != Skip {
- t.Fatalf("result = %+v, want a skip", r)
- }
-}
diff --git a/fluxer_rexctl/internal/checks/disk_test.go b/fluxer_rexctl/internal/checks/disk_test.go
deleted file mode 100644
index 6e13821d5..000000000
--- a/fluxer_rexctl/internal/checks/disk_test.go
+++ /dev/null
@@ -1,22 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-package checks
-
-import (
- "path/filepath"
- "testing"
-
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/instance"
-)
-
-func TestSpaceAddsNeedsOnOneDisk(t *testing.T) {
- dir := t.TempDir()
- e := &Env{Dir: dir, Instance: &instance.Instance{Dir: dir, State: &instance.State{BackupDir: filepath.Join(dir, "backups")}}}
- got := e.Space(3<<30, 2<<30)
- if len(got) != 1 {
- t.Fatalf("got %d disks, want 1", len(got))
- }
- if want := uint64(5<<30 + diskCritical); got[0].Need != want || !got[0].Images {
- t.Fatalf("got %+v, want need %d on the image disk", got[0], want)
- }
-}
diff --git a/fluxer_rexctl/internal/checks/overcommit_test.go b/fluxer_rexctl/internal/checks/overcommit_test.go
deleted file mode 100644
index d5ecb5595..000000000
--- a/fluxer_rexctl/internal/checks/overcommit_test.go
+++ /dev/null
@@ -1,49 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-package checks
-
-import (
- "context"
- "errors"
- "strings"
- "testing"
-
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/host"
-)
-
-func stubOvercommit(t *testing.T, state host.OvercommitState, enable func(context.Context) error) {
- t.Helper()
- prevState, prevEnable := overcommit, enableOvercommit
- t.Cleanup(func() { overcommit, enableOvercommit = prevState, prevEnable })
- overcommit = func() host.OvercommitState { return state }
- enableOvercommit = enable
-}
-
-func TestOvercommitInAContainerGivesTheHostCommand(t *testing.T) {
- stubOvercommit(t, host.OvercommitLocked, func(context.Context) error {
- t.Fatal("offered a fix that can't work")
- return nil
- })
- c, _ := Get("memory-overcommit")
- r := RunOne(context.Background(), &Env{prepared: true}, c)
- if r.Status != Warn || r.Fixable {
- t.Fatalf("result = %+v, want a warning without a fix", r)
- }
- if want := "This machine is a container and can't change it. Run this on the container host: " + host.OvercommitCommand; r.Fix != want {
- t.Fatalf("fix = %q, want %q", r.Fix, want)
- }
-}
-
-func TestOvercommitFixThatChangesNothingFails(t *testing.T) {
- stubOvercommit(t, host.OvercommitOff, func(context.Context) error {
- return host.ErrOvercommitUnchanged
- })
- c, _ := Get("memory-overcommit")
- r := RunOne(context.Background(), &Env{prepared: true}, c)
- if !r.Fixable || !strings.Contains(r.Manual, host.OvercommitCommand) {
- t.Fatalf("result = %+v", r)
- }
- if _, err := ApplyFix(context.Background(), &Env{prepared: true}, "memory-overcommit"); !errors.Is(err, host.ErrOvercommitUnchanged) {
- t.Fatalf("ApplyFix error = %v, want %v", err, host.ErrOvercommitUnchanged)
- }
-}
diff --git a/fluxer_rexctl/internal/checks/sso_provider_test.go b/fluxer_rexctl/internal/checks/sso_provider_test.go
deleted file mode 100644
index c78e85720..000000000
--- a/fluxer_rexctl/internal/checks/sso_provider_test.go
+++ /dev/null
@@ -1,223 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-package checks
-
-import (
- "context"
- "encoding/json"
- "errors"
- "strings"
- "testing"
-
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/adminapi"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/engine"
-)
-
-type fakeAdmin struct {
- sso map[string]any
- err error
-}
-
-func (f fakeAdmin) Do(_ context.Context, req adminapi.Request) (*adminapi.Response, error) {
- if f.err != nil {
- return nil, f.err
- }
- if req.Path != "/admin/instance/config" {
- return &adminapi.Response{Status: 404, Body: json.RawMessage(`{}`)}, nil
- }
- body, err := json.Marshal(map[string]any{"sso": f.sso})
- if err != nil {
- return nil, err
- }
- return &adminapi.Response{Status: 200, Body: body}, nil
-}
-
-type fakeExec struct {
- out string
- err error
- called bool
- service string
- stdin ssoProbeInput
- command []string
-}
-
-func (f *fakeExec) run(_ context.Context, service, stdin string, command ...string) (string, error) {
- f.called, f.service, f.command = true, service, command
- if err := json.Unmarshal([]byte(stdin), &f.stdin); err != nil {
- return "", err
- }
- return f.out, f.err
-}
-
-func ssoEnv(sso map[string]any, apiState string) *Env {
- e := &Env{prepared: true, psDone: true}
- if sso != nil {
- e.Admin = adminapi.New(fakeAdmin{sso: sso}, "")
- }
- if apiState != "" {
- e.ps = []engine.Container{{Service: "api", State: apiState}}
- }
- return e
-}
-
-func ssoOn() map[string]any {
- return map[string]any{"enabled": true, "issuer": "https://id.example.com/"}
-}
-
-func TestSSOProviderSkips(t *testing.T) {
- cases := map[string]struct {
- env *Env
- exec fakeExec
- }{
- "no admin API": {env: ssoEnv(nil, "running")},
- "api not running": {env: ssoEnv(ssoOn(), "exited")},
- "SSO off": {env: ssoEnv(map[string]any{"enabled": false, "issuer": "https://id.example.com"}, "running")},
- "no issuer": {env: ssoEnv(map[string]any{"enabled": true, "issuer": nil}, "running")},
- "blank issuer": {env: ssoEnv(map[string]any{"enabled": true, "issuer": " "}, "running")},
- "exec fails": {env: ssoEnv(ssoOn(), "running"), exec: fakeExec{err: errors.New("container gone")}},
- "no probe output": {env: ssoEnv(ssoOn(), "running"), exec: fakeExec{out: "node: not found"}},
- "probe threw": {env: ssoEnv(ssoOn(), "running"), exec: fakeExec{out: `{"ok":false,"stage":"probe","code":"TypeError"}`}},
- "admin API failed": {env: &Env{prepared: true, psDone: true, ps: []engine.Container{{Service: "api", State: "running"}}, Admin: adminapi.New(fakeAdmin{err: errors.New("relay down")}, "")}},
- }
- for name, c := range cases {
- t.Run(name, func(t *testing.T) {
- exec := c.exec
- r := ssoProvider(context.Background(), c.env, exec.run)
- if r.Status != Skip || r.Message != "" {
- t.Fatalf("got %+v, want a quiet skip", r)
- }
- })
- }
-}
-
-func TestSSOProviderPass(t *testing.T) {
- exec := &fakeExec{out: `{"ok":true,"host":"id.example.com","token_host":"auth.example.com"}`}
- r := ssoProvider(context.Background(), ssoEnv(ssoOn(), "running"), exec.run)
- if r.Status != Pass {
- t.Fatalf("got %+v, want pass", r)
- }
- if want := "The API connects to your SSO provider at id.example.com and its token endpoint at auth.example.com."; r.Message != want {
- t.Fatalf("message %q, want %q", r.Message, want)
- }
- if exec.service != "api" || len(exec.command) != 3 || exec.command[0] != "node" || exec.command[1] != "-e" {
- t.Fatalf("ran %s %v, want node -e in api", exec.service, exec.command)
- }
- if want := "https://id.example.com/.well-known/openid-configuration"; exec.stdin.Discovery != want {
- t.Fatalf("discovery %q, want %q", exec.stdin.Discovery, want)
- }
- if exec.stdin.Token != "" || exec.stdin.Timeout != ssoProbeSeconds*1000 {
- t.Fatalf("got input %+v", exec.stdin)
- }
-}
-
-func TestSSOProviderPassOneHost(t *testing.T) {
- exec := &fakeExec{out: `{"ok":true,"host":"id.example.com","token_host":"id.example.com"}`}
- r := ssoProvider(context.Background(), ssoEnv(ssoOn(), "running"), exec.run)
- if want := "The API connects to your SSO provider at id.example.com."; r.Status != Pass || r.Message != want {
- t.Fatalf("got %+v, want pass with %q", r, want)
- }
-}
-
-func TestSSOProviderUsesSetEndpoints(t *testing.T) {
- sso := ssoOn()
- sso["token_url"] = "https://auth.example.com/token"
- exec := &fakeExec{out: `{"ok":true,"host":"id.example.com","token_host":"auth.example.com"}`}
- ssoProvider(context.Background(), ssoEnv(sso, "running"), exec.run)
- if exec.stdin.Token != "https://auth.example.com/token" || exec.stdin.Discovery == "" {
- t.Fatalf("got input %+v, want discovery and the set token URL", exec.stdin)
- }
- sso["authorization_url"] = "https://id.example.com/authorize"
- sso["jwks_url"] = "https://id.example.com/jwks"
- sso["userinfo_url"] = "https://id.example.com/userinfo"
- exec = &fakeExec{out: `{"ok":true,"host":"","token_host":"auth.example.com"}`}
- r := ssoProvider(context.Background(), ssoEnv(sso, "running"), exec.run)
- if exec.stdin.Discovery != "" {
- t.Fatalf("got input %+v, want no discovery when every endpoint is set", exec.stdin)
- }
- if want := "The API connects to your SSO provider at auth.example.com."; r.Status != Pass || r.Message != want {
- t.Fatalf("got %+v, want pass with %q", r, want)
- }
-}
-
-func TestSSOProviderFailures(t *testing.T) {
- network := `Make id.example.com resolve to an address the API container can connect to. Add "id.example.com:host-gateway" to extra_hosts for the api service with rexctl config edit, and make your reverse proxy accept connections from Docker.`
- cases := []struct {
- name string
- out string
- message string
- fix string
- }{
- {
- name: "not found",
- out: `{"ok":false,"stage":"discovery","host":"id.example.com","code":"ENOTFOUND","message":"getaddrinfo ENOTFOUND id.example.com"}`,
- message: "The API can't look up the address of your SSO provider at id.example.com (ENOTFOUND).",
- fix: network,
- },
- {
- name: "refused",
- out: `{"ok":false,"stage":"discovery","host":"id.example.com","code":"ECONNREFUSED","message":"connect ECONNREFUSED 203.0.113.7:443"}`,
- message: "The API can't connect to your SSO provider at id.example.com because the connection was refused (ECONNREFUSED).",
- fix: network,
- },
- {
- name: "fetch timeout",
- out: `{"ok":false,"stage":"discovery","host":"id.example.com","code":"TimeoutError","message":"The operation was aborted due to timeout"}`,
- message: "The API can't connect to your SSO provider at id.example.com because the connection timed out after 8 seconds.",
- fix: network,
- },
- {
- name: "no route",
- out: `{"ok":false,"stage":"discovery","host":"id.example.com","code":"ENETUNREACH","message":"connect ENETUNREACH 2001:db8::7:443"}`,
- message: "The API can't connect to your SSO provider at id.example.com because there is no network route to it (ENETUNREACH).",
- fix: network,
- },
- {
- name: "certificate",
- out: `{"ok":false,"stage":"discovery","host":"id.example.com","code":"CERT_HAS_EXPIRED","message":"certificate has expired"}`,
- message: "The API doesn't trust the certificate of your SSO provider at id.example.com (CERT_HAS_EXPIRED).",
- fix: "Give id.example.com a certificate for that name from a public certificate authority, or check that extra_hosts for the api service sends id.example.com to the proxy that serves it.",
- },
- {
- name: "HTTP status",
- out: `{"ok":false,"stage":"discovery","host":"id.example.com","status":404}`,
- message: "Your SSO provider at id.example.com answered the API with HTTP 404.",
- fix: "Check sso.issuer with rexctl config get sso.issuer. Your provider has to serve its discovery document at https://id.example.com/.well-known/openid-configuration.",
- },
- {
- name: "not a discovery document",
- out: `{"ok":false,"stage":"discovery","host":"id.example.com","code":"NOT_DISCOVERY"}`,
- message: "Your SSO provider at id.example.com didn't send the API a discovery document.",
- fix: "Check sso.issuer with rexctl config get sso.issuer. Your provider has to serve its discovery document at https://id.example.com/.well-known/openid-configuration.",
- },
- {
- name: "token endpoint timeout",
- out: `{"ok":false,"stage":"token","host":"auth.example.com","code":"ETIMEDOUT","message":"connection timed out"}`,
- message: "The API can't connect to your SSO provider's token endpoint at auth.example.com because the connection timed out after 8 seconds.",
- fix: `Make auth.example.com resolve to an address the API container can connect to. Add "auth.example.com:host-gateway" to extra_hosts for the api service with rexctl config edit, and make your reverse proxy accept connections from Docker.`,
- },
- {
- name: "other cause",
- out: `{"ok":false,"stage":"discovery","host":"id.example.com","code":"EPIPE","message":"write EPIPE"}`,
- message: "The API can't connect to your SSO provider at id.example.com (EPIPE).",
- fix: network,
- },
- }
- for _, c := range cases {
- t.Run(c.name, func(t *testing.T) {
- exec := &fakeExec{out: "(node:1) ExperimentalWarning\n" + c.out + "\n"}
- r := ssoProvider(context.Background(), ssoEnv(ssoOn(), "running"), exec.run)
- if r.Status != Fail || r.Fixable {
- t.Fatalf("got %+v, want a failure rexctl can't fix", r)
- }
- if r.Message != c.message {
- t.Errorf("message %q, want %q", r.Message, c.message)
- }
- if r.Fix != c.fix {
- t.Errorf("fix %q, want %q", r.Fix, c.fix)
- }
- if strings.Contains(c.out, `"message"`) && len(r.Details) != 1 {
- t.Errorf("details %v, want the probe's error", r.Details)
- }
- })
- }
-}
diff --git a/fluxer_rexctl/internal/checks/voice_test.go b/fluxer_rexctl/internal/checks/voice_test.go
deleted file mode 100644
index 0ea3ec135..000000000
--- a/fluxer_rexctl/internal/checks/voice_test.go
+++ /dev/null
@@ -1,105 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-package checks
-
-import (
- "context"
- "crypto/hmac"
- "crypto/sha256"
- "encoding/base64"
- "encoding/json"
- "io"
- "net/http"
- "net/http/httptest"
- "strings"
- "testing"
- "time"
-
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/instance"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/voice"
-)
-
-func webhookReceiver(t *testing.T, secret string) *httptest.Server {
- t.Helper()
- return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- body, _ := io.ReadAll(r.Body)
- parts := strings.Split(r.Header.Get("Authorization"), ".")
- if len(parts) != 3 {
- w.WriteHeader(http.StatusBadRequest)
- return
- }
- mac := hmac.New(sha256.New, []byte(secret))
- mac.Write([]byte(parts[0] + "." + parts[1]))
- if base64.RawURLEncoding.EncodeToString(mac.Sum(nil)) != parts[2] {
- w.WriteHeader(http.StatusBadRequest)
- return
- }
- payload, _ := base64.RawURLEncoding.DecodeString(parts[1])
- var claims map[string]any
- _ = json.Unmarshal(payload, &claims)
- sum := sha256.Sum256(body)
- var event struct {
- Room struct{ Name string } `json:"room"`
- }
- _ = json.Unmarshal(body, &event)
- if claims["sha256"] != base64.StdEncoding.EncodeToString(sum[:]) || claims["iss"] != "fluxer-fra-server-1" || !strings.HasPrefix(event.Room.Name, voice.TestRoomPrefix) {
- w.WriteHeader(http.StatusBadRequest)
- return
- }
- w.WriteHeader(http.StatusOK)
- }))
-}
-
-func TestWebhookCheckSendsASignedTestEvent(t *testing.T) {
- srv := webhookReceiver(t, "right")
- defer srv.Close()
- client := &voice.Client{HTTP: srv.Client()}
- s := instance.VoiceServer{ID: "fra-server-1", Key: "fluxer-fra-server-1", Secret: "right"}
- if problem, _ := webhookProblem(context.Background(), client, s, srv.URL); problem != "" {
- t.Errorf("right secret: %s", problem)
- }
- s.Secret = "wrong"
- problem, fault := webhookProblem(context.Background(), client, s, srv.URL)
- if fault != webhookSecret || !strings.Contains(problem, "signed with the secret of fra-server-1") {
- t.Errorf("wrong secret: %q, %v", problem, fault)
- }
-}
-
-func TestWebhookTargetForServersOnTheFluxerMachine(t *testing.T) {
- inst := &instance.Instance{State: &instance.State{Settings: map[string]string{}}}
- inst.State.Settings["FLUXER_PUBLIC_ORIGIN"] = "https://chat.example.com"
- e := &Env{Instance: inst}
- if got := e.webhookTarget(instance.VoiceServer{Webhook: "http://api:8080/webhooks/livekit"}); got != "https://chat.example.com/api/webhooks/livekit" {
- t.Errorf("same machine: %s", got)
- }
- if got := e.webhookTarget(instance.VoiceServer{Webhook: "https://chat.example.com/api/webhooks/livekit"}); got != "https://chat.example.com/api/webhooks/livekit" {
- t.Errorf("joined: %s", got)
- }
-}
-
-func TestVoiceEndpointsCheckSeesAnOldDomain(t *testing.T) {
- inst := &instance.Instance{State: &instance.State{Settings: map[string]string{"FLUXER_PUBLIC_ORIGIN": "https://new.example.com"}}}
- inst.State.Voice = []instance.VoiceServer{{ID: "default-server-2", Endpoint: "wss://old.example.com/livekit-default-server-2", Edge: voice.EdgeInstance}}
- r := runVoiceEndpoints(context.Background(), &Env{Instance: inst})
- if r.Status != Fail || !r.Fixable || !strings.Contains(r.Message, "default-server-2") || !strings.Contains(r.Fix, "wss://new.example.com") {
- t.Fatalf("old domain: %+v", r)
- }
- inst.State.Voice[0].Endpoint = "wss://new.example.com/livekit-default-server-2"
- if r := runVoiceEndpoints(context.Background(), &Env{Instance: inst}); r.Status != Pass {
- t.Fatalf("new domain: %+v", r)
- }
-}
-
-func TestWebhookCheckReportsAClockThatIsOff(t *testing.T) {
- srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- w.Header().Set("Date", time.Now().Add(-3*time.Minute).UTC().Format(http.TimeFormat))
- w.WriteHeader(http.StatusUnauthorized)
- }))
- defer srv.Close()
- client := &voice.Client{HTTP: srv.Client()}
- s := instance.VoiceServer{ID: "fra-server-1", Key: "fluxer-fra-server-1", Secret: "right"}
- problem, fault := webhookProblem(context.Background(), client, s, srv.URL)
- if fault != webhookClock || !strings.Contains(problem, "about 3 minutes ahead") {
- t.Fatalf("clock ahead: %q, %v", problem, fault)
- }
-}
diff --git a/fluxer_rexctl/internal/deploy/apply_test.go b/fluxer_rexctl/internal/deploy/apply_test.go
deleted file mode 100644
index 74f722fde..000000000
--- a/fluxer_rexctl/internal/deploy/apply_test.go
+++ /dev/null
@@ -1,29 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-package deploy
-
-import (
- "slices"
- "testing"
-)
-
-func TestMountRestarts(t *testing.T) {
- saved := map[string]string{"ca": "c", "certs": "a", "caddy.d": "b"}
- cases := []struct {
- name string
- files []string
- mounted map[string]string
- want []string
- }{
- {"nothing changed", nil, map[string]string{"ca": "c", "certs": "a", "caddy.d": "b"}, nil},
- {"ca changed", nil, map[string]string{"ca": "x", "certs": "a", "caddy.d": "b"}, []string{"api", "worker"}},
- {"certs changed", nil, map[string]string{"ca": "c", "certs": "x", "caddy.d": "b"}, []string{"edge"}},
- {"caddy.d changed", nil, map[string]string{"ca": "c", "certs": "a", "caddy.d": "x"}, []string{"edge"}},
- {"Caddyfile and ca changed", []string{"edge"}, map[string]string{"ca": "x", "certs": "a", "caddy.d": "b"}, []string{"api", "edge", "worker"}},
- }
- for _, c := range cases {
- if got := mountRestarts(c.files, c.mounted, saved); !slices.Equal(got, c.want) {
- t.Errorf("%s: mountRestarts = %v, want %v", c.name, got, c.want)
- }
- }
-}
diff --git a/fluxer_rexctl/internal/deploy/edge_test.go b/fluxer_rexctl/internal/deploy/edge_test.go
deleted file mode 100644
index de30cdd31..000000000
--- a/fluxer_rexctl/internal/deploy/edge_test.go
+++ /dev/null
@@ -1,82 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-package deploy
-
-import (
- "os"
- "path/filepath"
- "strings"
- "testing"
-
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/instance"
-)
-
-const nestedSiteStderr = `{"level":"info","ts":1793328334.3,"msg":"using config from file","file":"/etc/caddy/Caddyfile"}
-{"level":"error","ts":1793328334.371964,"msg":"/etc/caddy/conf.d/Mastodon.caddy:1: unrecognized directive: mastodon.tails.ch"}
-`
-
-func writeDropIn(t *testing.T, dir, file, data string) {
- t.Helper()
- path := filepath.Join(dir, instance.CaddyDropInDir, file)
- if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
- t.Fatal(err)
- }
- if err := os.WriteFile(path, []byte(data), 0o644); err != nil {
- t.Fatal(err)
- }
-}
-
-func TestCaddyMessage(t *testing.T) {
- for _, tc := range []struct {
- stderr, want string
- }{
- {nestedSiteStderr, "/etc/caddy/conf.d/Mastodon.caddy:1: unrecognized directive: mastodon.tails.ch"},
- {"Error: adapting config using caddyfile: /etc/caddy/Caddyfile:3: unknown directive\n", "/etc/caddy/Caddyfile:3: unknown directive"},
- {"", ""},
- } {
- if got := caddyMessage(tc.stderr); got != tc.want {
- t.Errorf("caddyMessage(%q) = %q, want %q", tc.stderr, got, tc.want)
- }
- }
-}
-
-func TestEdgeProblemPointsAtSiteFile(t *testing.T) {
- dir := t.TempDir()
- writeDropIn(t, dir, "Mastodon.caddy", "mastodon.tails.ch {\n\treverse_proxy 10.0.4.22:3000\n}\n")
- e := edgeProblem(dir, nestedSiteStderr)
- if e.Caddy != "caddy.d/Mastodon.caddy:1: unrecognized directive: mastodon.tails.ch" {
- t.Fatalf("caddy error %q", e.Caddy)
- }
- if e.Site != "caddy.d/Mastodon.caddy" {
- t.Fatalf("site file %q", e.Site)
- }
- if fix := e.Fix("try again"); fix != "caddy.d/Mastodon.caddy defines its own site. Move it to caddy.d/sites, then try again." {
- t.Fatalf("fix %q", fix)
- }
-}
-
-func TestEdgeProblemLooksForSitesWhenCaddyBlamesTheCaddyfile(t *testing.T) {
- dir := t.TempDir()
- writeDropIn(t, dir, "headers.caddy", "header X-Mine yes\n")
- writeDropIn(t, dir, "tails.caddy", "header X-Mine yes\ntails.ch {\n\trespond ok\n}\n")
- e := edgeProblem(dir, "Error: adapting config using caddyfile: /etc/caddy/Caddyfile:20: unrecognized directive: tails.ch\n")
- if e.Site != "caddy.d/tails.caddy" {
- t.Fatalf("site file %q", e.Site)
- }
- if !strings.HasPrefix(e.Caddy, "Caddyfile:20:") {
- t.Fatalf("caddy error %q", e.Caddy)
- }
-}
-
-func TestEdgeProblemWithoutSiteFile(t *testing.T) {
- dir := t.TempDir()
- writeDropIn(t, dir, "headers.caddy", "header X-Mine yes\nbogus\n")
- writeDropIn(t, dir, "sites/tails.caddy", "tails.ch {\n\tbogus\n}\n")
- e := edgeProblem(dir, `{"level":"error","msg":"/etc/caddy/conf.d/sites/tails.caddy:2: unrecognized directive: bogus"}`)
- if e.Site != "" {
- t.Fatalf("site file %q", e.Site)
- }
- if fix := e.Fix("try again"); fix != "Fix the file Caddy reports, then try again." {
- t.Fatalf("fix %q", fix)
- }
-}
diff --git a/fluxer_rexctl/internal/deploy/ports_test.go b/fluxer_rexctl/internal/deploy/ports_test.go
deleted file mode 100644
index 904733f7c..000000000
--- a/fluxer_rexctl/internal/deploy/ports_test.go
+++ /dev/null
@@ -1,131 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-package deploy
-
-import (
- "errors"
- "strings"
- "testing"
-
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/host"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/settings"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/ui"
-)
-
-func TestPortOfDefaults(t *testing.T) {
- for _, v := range portVars {
- if got := portOf(nil, v); got != v.def {
- t.Errorf("portOf(%s) = %d, want default %d", v.name, got, v.def)
- }
- for _, bad := range []string{"", "0", "-5", "70000", "x"} {
- if got := portOf(map[string]string{v.name: bad}, v); got != v.def {
- t.Errorf("portOf(%s=%q) = %d, want default %d", v.name, bad, got, v.def)
- }
- }
- if got := portOf(map[string]string{v.name: "7999"}, v); got != 7999 {
- t.Errorf("portOf(%s=7999) = %d, want 7999", v.name, got)
- }
- }
-}
-
-func TestPortDiffVoiceOnly(t *testing.T) {
- old := map[string]string{}
- next := map[string]string{"FLUXER_LIVEKIT_TCP_PORT": "7883", "FLUXER_LIVEKIT_UDP_PORT": "7884"}
- added, removed := portDiff(old, next)
- wantAdded := []host.Port{{Number: 7883, Proto: "tcp"}, {Number: 7884, Proto: "udp"}}
- wantRemoved := []host.Port{{Number: 7881, Proto: "tcp"}, {Number: 7882, Proto: "udp"}}
- if !samePorts(added, wantAdded) || !samePorts(removed, wantRemoved) {
- t.Errorf("portDiff = added %v removed %v, want added %v removed %v", added, removed, wantAdded, wantRemoved)
- }
- if a, _ := portDiff(next, next); len(a) != 0 {
- t.Errorf("portDiff of equal envs added %v, want none", a)
- }
-}
-
-func TestPortKeyChanged(t *testing.T) {
- cases := map[bool][]string{
- true: {settings.VoiceTCPPort},
- false: {settings.Domain, settings.MemoryProfile},
- }
- for want, changed := range cases {
- if got := portKeyChanged(changed); got != want {
- t.Errorf("portKeyChanged(%v) = %v, want %v", changed, got, want)
- }
- }
- for _, k := range []string{settings.EdgeHTTPPort, settings.EdgeHTTPSPort, settings.VoiceTCPPort, settings.VoiceUDPPort} {
- if !portKeyChanged([]string{settings.Domain, k}) {
- t.Errorf("portKeyChanged should be true for %s", k)
- }
- }
-}
-
-func TestCheckPortsDistinctDefaults(t *testing.T) {
- for _, mode := range []string{settings.EdgeBundled, settings.EdgeProxy, settings.EdgeTunnel} {
- if err := checkPortsDistinct(effectivePorts(nil, mode)); err != nil {
- t.Errorf("default %s install should have distinct ports, got %v", mode, err)
- }
- }
-}
-
-func TestCheckPortsDistinctVoiceHitsWeb(t *testing.T) {
- env := map[string]string{"FLUXER_LIVEKIT_TCP_PORT": "443"}
- err := checkPortsDistinct(effectivePorts(env, settings.EdgeBundled))
- if err == nil {
- t.Fatal("voice.tcp_port 443 in bundled mode should be refused")
- }
- if !strings.Contains(err.Error(), "the web address") || !strings.Contains(err.Error(), "443") {
- t.Errorf("message should name the web address and the port, got %q", err.Error())
- }
- var ee *ui.ExitError
- if errors.As(err, &ee) && !strings.Contains(ee.Fix, settings.VoiceTCPPort) {
- t.Errorf("fix should point at %s, got %q", settings.VoiceTCPPort, ee.Fix)
- }
-}
-
-func TestCheckPortsDistinctProxyModeDropsEdge(t *testing.T) {
- env := map[string]string{"FLUXER_LIVEKIT_TCP_PORT": "443"}
- if err := checkPortsDistinct(effectivePorts(env, settings.EdgeProxy)); err != nil {
- t.Errorf("voice.tcp_port 443 is fine in proxy mode, got %v", err)
- }
-}
-
-func samePorts(a, b []host.Port) bool {
- if len(a) != len(b) {
- return false
- }
- for i := range a {
- if a[i] != b[i] {
- return false
- }
- }
- return true
-}
-
-func TestPortDiffTurningBundledVoiceOffAndOn(t *testing.T) {
- on := map[string]string{"FLUXER_LIVEKIT_TCP_PORT": "7883"}
- off := map[string]string{"FLUXER_LIVEKIT_TCP_PORT": "7883", "FLUXER_LIVEKIT_BUNDLED": "false"}
- voicePorts := []host.Port{{Number: 7883, Proto: "tcp"}, {Number: 7882, Proto: "udp"}}
- added, removed := portDiff(on, off)
- if len(added) != 0 || !samePorts(removed, voicePorts) {
- t.Errorf("turning bundled voice off: added %v removed %v", added, removed)
- }
- added, removed = portDiff(off, on)
- if !samePorts(added, voicePorts) || len(removed) != 0 {
- t.Errorf("turning bundled voice on: added %v removed %v", added, removed)
- }
- if added, removed := portDiff(off, map[string]string{"FLUXER_LIVEKIT_TCP_PORT": "7885", "FLUXER_LIVEKIT_BUNDLED": "false"}); len(added)+len(removed) != 0 {
- t.Errorf("moving an unused voice port: added %v removed %v", added, removed)
- }
-}
-
-func TestEffectivePortsWithoutBundledVoice(t *testing.T) {
- env := map[string]string{"FLUXER_LIVEKIT_TCP_PORT": "443", "FLUXER_LIVEKIT_BUNDLED": "false"}
- if err := checkPortsDistinct(effectivePorts(env, settings.EdgeBundled)); err != nil {
- t.Errorf("an unused voice port can't clash, got %v", err)
- }
- for _, p := range effectivePorts(env, settings.EdgeBundled) {
- if p.subject == "Voice" {
- t.Errorf("effective ports list %v without the bundled LiveKit", p)
- }
- }
-}
diff --git a/fluxer_rexctl/internal/deploy/voice_test.go b/fluxer_rexctl/internal/deploy/voice_test.go
deleted file mode 100644
index fa4bb18d5..000000000
--- a/fluxer_rexctl/internal/deploy/voice_test.go
+++ /dev/null
@@ -1,222 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-package deploy
-
-import (
- "context"
- "encoding/json"
- "errors"
- "net/http"
- "os"
- "path/filepath"
- "slices"
- "strings"
- "testing"
-
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/adminapi"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/engine"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/instance"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/settings"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/voice"
-)
-
-type voiceEvents struct {
- got []string
- fail map[string]bool
-}
-
-func recordVoice(t *testing.T) *voiceEvents {
- t.Helper()
- ev := &voiceEvents{fail: map[string]bool{}}
- oldDown, oldStop, oldStart := downInstance, stopVoice, startVoice
- t.Cleanup(func() { downInstance, stopVoice, startVoice = oldDown, oldStop, oldStart })
- downInstance = func(_ context.Context, _ *engine.Engine, inst *instance.Instance) error {
- ev.got = append(ev.got, "down "+inst.Project())
- return nil
- }
- stopVoice = func(_ context.Context, _ *engine.Engine, v AttachedVoice) error {
- ev.got = append(ev.got, "stop "+v.Server.ID)
- if ev.fail["stop "+v.Server.ID] {
- return errors.New("stuck")
- }
- return nil
- }
- startVoice = func(_ context.Context, _ *engine.Engine, v AttachedVoice) error {
- ev.got = append(ev.got, "start "+v.Server.ID)
- if ev.fail["start "+v.Server.ID] {
- return errors.New("no network")
- }
- return nil
- }
- return ev
-}
-
-func voiceHome(t *testing.T) string {
- t.Helper()
- home := t.TempDir()
- t.Setenv("HOME", home)
- t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))
- return home
-}
-
-func fluxerWithVoice(t *testing.T, home string, servers ...instance.VoiceServer) *instance.Instance {
- t.Helper()
- inst, err := instance.Create(filepath.Join(home, "fluxer"), "fluxer")
- if err != nil {
- t.Fatal(err)
- }
- inst.State.Voice = servers
- if err := inst.Save(); err != nil {
- t.Fatal(err)
- }
- if err := instance.Remember(instance.OwnScope(), inst.Dir, true); err != nil {
- t.Fatal(err)
- }
- return inst
-}
-
-func joinedMachine(t *testing.T, home string, servers ...instance.VoiceServer) {
- t.Helper()
- inst := &instance.Instance{Dir: filepath.Join(home, "voice"), State: &instance.State{
- Schema: instance.StateSchema, Kind: instance.KindVoice, Project: voice.MachineProject,
- Settings: map[string]string{}, Secrets: map[string]string{}, Voice: servers,
- }}
- if err := os.MkdirAll(inst.Path(instance.StateDirName), 0o700); err != nil {
- t.Fatal(err)
- }
- if err := inst.Save(); err != nil {
- t.Fatal(err)
- }
- if err := instance.Remember(instance.OwnScope(), inst.Dir, false); err != nil {
- t.Fatal(err)
- }
-}
-
-func TestIPv6ChangeTakesVoiceServersOffTheNetworkFirst(t *testing.T) {
- home := voiceHome(t)
- inst := fluxerWithVoice(t, home, instance.VoiceServer{ID: "fra-server-1", Project: "fluxer-voice-fra-server-1", Network: "fluxer_fluxer"})
- joinedMachine(t, home,
- instance.VoiceServer{ID: "fra-server-2", Project: "fluxer-voice-fra-server-2", Network: "fluxer_fluxer"},
- instance.VoiceServer{ID: "sgp-server-1", Project: "fluxer-voice-sgp-server-1", Network: voice.MachineNetwork},
- )
- inst.State.Stopped = true
- inst.State.Pending = &instance.Pending{Settings: map[string]string{settings.IPv6: "true"}, Keys: []string{settings.IPv6}}
- if err := inst.Save(); err != nil {
- t.Fatal(err)
- }
- ev := recordVoice(t)
- if err := Resolve(context.Background(), inst, nil); err != nil {
- t.Fatal(err)
- }
- want := []string{"stop fra-server-1", "stop fra-server-2", "down fluxer"}
- if !slices.Equal(ev.got, want) {
- t.Fatalf("events = %v, want %v", ev.got, want)
- }
- if inst.State.Pending != nil {
- t.Fatal("the pending change is still there")
- }
-}
-
-func TestVoiceServersStartAgainAfterTheNetworkChange(t *testing.T) {
- home := voiceHome(t)
- inst := fluxerWithVoice(t, home,
- instance.VoiceServer{ID: "fra-server-1", Project: "fluxer-voice-fra-server-1", Network: "fluxer_fluxer"},
- instance.VoiceServer{ID: "fra-server-2", Project: "fluxer-voice-fra-server-2", Network: "fluxer_fluxer"},
- )
- ev := recordVoice(t)
- ev.fail["start fra-server-2"] = true
- detached, err := detachVoice(context.Background(), nil, inst)
- if err != nil {
- t.Fatal(err)
- }
- failed := attachVoice(context.Background(), nil, detached)
- want := []string{"stop fra-server-1", "stop fra-server-2", "start fra-server-1", "start fra-server-2"}
- if !slices.Equal(ev.got, want) {
- t.Fatalf("events = %v, want %v", ev.got, want)
- }
- if !slices.Equal(failed, []string{"fra-server-2"}) {
- t.Fatalf("failed = %v", failed)
- }
-}
-
-func TestAServerThatWontStopBringsTheOthersBack(t *testing.T) {
- home := voiceHome(t)
- inst := fluxerWithVoice(t, home,
- instance.VoiceServer{ID: "fra-server-1", Project: "fluxer-voice-fra-server-1", Network: "fluxer_fluxer"},
- instance.VoiceServer{ID: "fra-server-2", Project: "fluxer-voice-fra-server-2", Network: "fluxer_fluxer"},
- )
- ev := recordVoice(t)
- ev.fail["stop fra-server-2"] = true
- if _, err := detachVoice(context.Background(), nil, inst); err == nil {
- t.Fatal("detach succeeded with a stuck server")
- }
- want := []string{"stop fra-server-1", "stop fra-server-2", "start fra-server-1"}
- if !slices.Equal(ev.got, want) {
- t.Fatalf("events = %v, want %v", ev.got, want)
- }
-}
-
-type endpointAdmin struct {
- sent map[string]string
- fail string
-}
-
-func (f *endpointAdmin) Do(_ context.Context, req adminapi.Request) (*adminapi.Response, error) {
- if req.Method != http.MethodPatch {
- return &adminapi.Response{Status: 404, Body: json.RawMessage(`{}`)}, nil
- }
- if strings.HasSuffix(req.Path, "/"+f.fail) {
- return &adminapi.Response{Status: 500, Body: json.RawMessage(`{"code":"GENERAL_ERROR","message":"boom"}`)}, nil
- }
- var body struct {
- Endpoint string `json:"endpoint"`
- }
- if err := json.Unmarshal(req.Body, &body); err != nil {
- return nil, err
- }
- f.sent[req.Path] = body.Endpoint
- return &adminapi.Response{Status: 200, Body: json.RawMessage(`{"server":{}}`)}, nil
-}
-
-func TestANewDomainMovesVoiceAddEndpoints(t *testing.T) {
- dir := t.TempDir()
- inst := &instance.Instance{Dir: dir, State: &instance.State{
- Schema: instance.StateSchema, Project: "fluxer", Secrets: map[string]string{},
- Settings: map[string]string{"FLUXER_PUBLIC_ORIGIN": "https://new.example.com"},
- Voice: []instance.VoiceServer{
- {ID: "default-server-2", Region: "default", Endpoint: "wss://old.example.com/livekit-default-server-2", Edge: voice.EdgeInstance},
- {ID: "default-server-3", Region: "default", Endpoint: "wss://old.example.com/livekit-default-server-3", Edge: voice.EdgeInstance},
- {ID: "fra-server-1", Region: "fra", Endpoint: "wss://voice.example.net/livekit-fra-server-1", Edge: voice.EdgeOwn},
- },
- }}
- if err := os.MkdirAll(inst.Path(instance.StateDirName), 0o700); err != nil {
- t.Fatal(err)
- }
- if got := StaleVoiceEndpoints(inst); !slices.Equal(got, []string{"default-server-2", "default-server-3"}) {
- t.Fatalf("stale = %v", got)
- }
- fake := &endpointAdmin{sent: map[string]string{}, fail: "default-server-3"}
- moved, err := MoveVoiceEndpoints(context.Background(), adminapi.New(fake, ""), inst)
- if err == nil || !strings.Contains(err.Error(), "default-server-3") {
- t.Fatalf("err = %v", err)
- }
- if !slices.Equal(moved, []string{"default-server-2"}) {
- t.Fatalf("moved = %v", moved)
- }
- if got := fake.sent["/admin/voice/regions/default/servers/default-server-2"]; got != "wss://new.example.com/livekit-default-server-2" {
- t.Fatalf("sent %v", fake.sent)
- }
- saved, err := instance.Find(dir)
- if err != nil {
- t.Fatal(err)
- }
- if got := saved.State.VoiceServer("default-server-2").Endpoint; got != "wss://new.example.com/livekit-default-server-2" {
- t.Fatalf("saved endpoint = %s", got)
- }
- if got := saved.State.VoiceServer("default-server-3").Endpoint; got != "wss://old.example.com/livekit-default-server-3" {
- t.Fatalf("failed server changed to %s", got)
- }
- if got := StaleVoiceEndpoints(inst); !slices.Equal(got, []string{"default-server-3"}) {
- t.Fatalf("stale after the move = %v", got)
- }
-}
diff --git a/fluxer_rexctl/internal/deploy/voiceports_test.go b/fluxer_rexctl/internal/deploy/voiceports_test.go
deleted file mode 100644
index 8296f443d..000000000
--- a/fluxer_rexctl/internal/deploy/voiceports_test.go
+++ /dev/null
@@ -1,41 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-package deploy
-
-import (
- "context"
- "os"
- "path/filepath"
- "strings"
- "testing"
-
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/host"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/instance"
-)
-
-func TestCheckPortsFreeSeesStoppedVoiceServers(t *testing.T) {
- home := t.TempDir()
- t.Setenv("HOME", home)
- t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))
- inst := &instance.Instance{Dir: filepath.Join(home, "voice"), State: &instance.State{
- Schema: instance.StateSchema, Kind: instance.KindVoice, Project: "fluxer-voice",
- Settings: map[string]string{}, Secrets: map[string]string{},
- Voice: []instance.VoiceServer{{ID: "fra-server-1", TCPPort: 47883, UDPPort: 47884}},
- }}
- if err := os.MkdirAll(inst.Path(instance.StateDirName), 0o700); err != nil {
- t.Fatal(err)
- }
- if err := inst.Save(); err != nil {
- t.Fatal(err)
- }
- if err := instance.Remember(instance.OwnScope(), inst.Dir, false); err != nil {
- t.Fatal(err)
- }
- err := checkPortsFree(context.Background(), nil, "fluxer", []host.Port{{Number: 47883, Proto: "tcp"}})
- if err == nil || !strings.Contains(err.Error(), "fra-server-1") {
- t.Fatalf("checkPortsFree = %v", err)
- }
- if err := checkPortsFree(context.Background(), nil, "fluxer", []host.Port{{Number: 47885, Proto: "tcp"}}); err != nil {
- t.Fatalf("a free port: %v", err)
- }
-}
diff --git a/fluxer_rexctl/internal/engine/binds_test.go b/fluxer_rexctl/internal/engine/binds_test.go
deleted file mode 100644
index 04ca033f9..000000000
--- a/fluxer_rexctl/internal/engine/binds_test.go
+++ /dev/null
@@ -1,47 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-package engine
-
-import (
- "context"
- "os"
- "path/filepath"
- "slices"
- "testing"
-)
-
-func writeCompose(t *testing.T, dir, name, data string) {
- t.Helper()
- if err := os.WriteFile(filepath.Join(dir, name), []byte(data), 0o600); err != nil {
- t.Fatal(err)
- }
-}
-
-func TestBindSourcesMergesAServiceWithNoBodyLikeLoad(t *testing.T) {
- dir := t.TempDir()
- writeCompose(t, dir, "compose.yml", "services:\n livekit:\n image: livekit\n edge:\n image: caddy\n")
- writeCompose(t, dir, "custom.compose.yml", "services:\n livekit:\n edge:\n volumes:\n - ${PWD}/Caddyfile:/etc/caddy/Caddyfile\n")
- s := Spec{Name: "fluxer", Dir: dir, Files: []string{"compose.yml", "custom.compose.yml"}}
- if _, err := (&Engine{}).Load(context.Background(), s); err != nil {
- t.Fatalf("Load: %v", err)
- }
- got, err := BindSources(context.Background(), s)
- if err != nil {
- t.Fatal(err)
- }
- if want := filepath.Join(dir, "Caddyfile"); !slices.Equal(got, []string{want}) {
- t.Fatalf("BindSources = %q, want %q", got, want)
- }
-}
-
-func TestBindSourcesReturnsAnErrorForAServiceWithNoBodyOnItsOwn(t *testing.T) {
- dir := t.TempDir()
- writeCompose(t, dir, "custom.compose.yml", "services:\n livekit:\n")
- s := Spec{Name: "fluxer", Dir: dir, Files: []string{"custom.compose.yml"}}
- if _, err := BindSources(context.Background(), s); err == nil {
- t.Fatal("BindSources read a service with no body and nothing to merge it with")
- }
- if _, err := (&Engine{}).Load(context.Background(), s); err == nil {
- t.Fatal("Load read a service with no body and nothing to merge it with")
- }
-}
diff --git a/fluxer_rexctl/internal/engine/down_test.go b/fluxer_rexctl/internal/engine/down_test.go
deleted file mode 100644
index 1a5d3b690..000000000
--- a/fluxer_rexctl/internal/engine/down_test.go
+++ /dev/null
@@ -1,65 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-package engine
-
-import (
- "slices"
- "testing"
-
- "github.com/compose-spec/compose-go/v2/types"
-)
-
-func TestDownKeepingRemovesOtherVolumes(t *testing.T) {
- label := func(short string) map[string]string { return map[string]string{"com.docker.compose.volume": short} }
- vols := []Volume{
- {Name: "fluxer_postgres-data", Project: "fluxer", Labels: label("postgres-data")},
- {Name: "fluxer_seaweedfs-data", Project: "fluxer", Labels: label("seaweedfs-data")},
- {Name: "fluxer_meilisearch-data", Project: "fluxer", Labels: label("meilisearch-data")},
- {Name: "custom-uploads", Project: "fluxer", Labels: label("seaweedfs-data")},
- {Name: "fluxer_valkey-data", Project: "fluxer", Labels: map[string]string{}},
- {Name: "fluxer_seaweedfs-old", Project: "", Labels: map[string]string{}},
- {Name: "blue_postgres-data", Project: "blue", Labels: label("postgres-data")},
- }
- got := volumesToDrop(nil, vols, "fluxer", []string{"seaweedfs-data"})
- want := []string{"fluxer_meilisearch-data", "fluxer_postgres-data", "fluxer_valkey-data"}
- if !slices.Equal(got, want) {
- t.Errorf("volumesToDrop = %v, want %v", got, want)
- }
- if got := volumesToDrop(nil, vols, "fluxer", nil); len(got) != 5 {
- t.Errorf("keeping nothing drops %v", got)
- }
-}
-
-func TestDownKeepingRemovesUnlabelledModelVolumes(t *testing.T) {
- model := &types.Project{Name: "fluxer", Volumes: types.Volumes{
- "postgres-data": {Name: "fluxer_postgres-data"},
- "seaweedfs-data": {Name: "fluxer_seaweedfs-data"},
- "edge-data": {Name: "fluxer_edge-data"},
- "edge-config": {Name: "fluxer_edge-config"},
- "shared": {Name: "shared", External: true},
- }}
- unlabelled := map[string]string{}
- vols := []Volume{
- {Name: "fluxer_edge-config", Labels: unlabelled},
- {Name: "fluxer_edge-data", Labels: unlabelled},
- {Name: "fluxer_postgres-data", Labels: unlabelled},
- {Name: "fluxer_seaweedfs-data", Labels: unlabelled},
- {Name: "shared", Labels: unlabelled},
- }
- got := volumesToDrop(model, vols, "fluxer", []string{"seaweedfs-data"})
- want := []string{"fluxer_edge-config", "fluxer_edge-data", "fluxer_postgres-data"}
- if !slices.Equal(got, want) {
- t.Errorf("volumesToDrop = %v, want %v", got, want)
- }
- renamed := &types.Project{Name: "fluxer", Volumes: types.Volumes{
- "postgres-data": {Name: "fluxer_postgres-data"},
- "seaweedfs-data": {Name: "custom-uploads"},
- }}
- labelled := []Volume{
- {Name: "custom-uploads", Project: "fluxer", Labels: map[string]string{"com.docker.compose.volume": "uploads-old"}},
- {Name: "fluxer_postgres-data", Project: "fluxer", Labels: map[string]string{"com.docker.compose.volume": "postgres-data"}},
- }
- if got := volumesToDrop(renamed, labelled, "fluxer", []string{"seaweedfs-data"}); !slices.Equal(got, []string{"fluxer_postgres-data"}) {
- t.Errorf("volumesToDrop with a renamed uploads volume = %v", got)
- }
-}
diff --git a/fluxer_rexctl/internal/engine/load_test.go b/fluxer_rexctl/internal/engine/load_test.go
deleted file mode 100644
index 9d65b1771..000000000
--- a/fluxer_rexctl/internal/engine/load_test.go
+++ /dev/null
@@ -1,26 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-package engine
-
-import (
- "context"
- "os"
- "path/filepath"
- "testing"
-)
-
-func TestLoadResolvesPWDToTheInstanceFolder(t *testing.T) {
- dir := t.TempDir()
- compose := "services:\n edge:\n image: caddy\n volumes:\n - ${PWD}/Caddyfile:/etc/caddy/Caddyfile\n"
- if err := os.WriteFile(filepath.Join(dir, "compose.yml"), []byte(compose), 0o600); err != nil {
- t.Fatal(err)
- }
- p, err := (&Engine{}).Load(context.Background(), Spec{Name: "fluxer", Dir: dir, Files: []string{"compose.yml"}})
- if err != nil {
- t.Fatal(err)
- }
- want := filepath.Join(dir, "Caddyfile")
- if got := p.Model.Services["edge"].Volumes[0].Source; got != want {
- t.Errorf("bind source = %q, want %q", got, want)
- }
-}
diff --git a/fluxer_rexctl/internal/host/autoupgrade_test.go b/fluxer_rexctl/internal/host/autoupgrade_test.go
deleted file mode 100644
index 837ec4371..000000000
--- a/fluxer_rexctl/internal/host/autoupgrade_test.go
+++ /dev/null
@@ -1,753 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-package host
-
-import (
- "context"
- "fmt"
- "os"
- "path/filepath"
- "runtime"
- "strings"
- "testing"
- "time"
-)
-
-func TestAutoUpgradeService(t *testing.T) {
- a := AutoUpgrade{Scheduler: Systemd, Project: "fluxer", Dir: "/opt/fluxer", Binary: "/usr/local/bin/rexctl", At: "04:00"}
- want := `[Unit]
-Description=Upgrade Fluxer in /opt/fluxer
-Wants=network-online.target
-After=network-online.target fluxer.service
-
-[Service]
-Type=oneshot
-ExecStart=/usr/local/bin/rexctl upgrade --yes --dir /opt/fluxer
-`
- if got := a.service(""); got != want {
- t.Errorf("service as root:\n%s\nwant:\n%s", got, want)
- }
- a.Dir, a.Binary = "/home/alice/my fluxer", "/home/alice/.local/bin/rexctl"
- want = `[Unit]
-Description=Upgrade Fluxer in /home/alice/my fluxer
-Wants=network-online.target
-After=network-online.target fluxer.service
-
-[Service]
-Type=oneshot
-User=alice
-ExecStart=/home/alice/.local/bin/rexctl upgrade --yes --dir "/home/alice/my fluxer"
-ExecStopPost=-+/usr/bin/install -D -m 0755 /home/alice/.local/bin/rexctl /usr/local/libexec/rexctl/rexctl
-`
- if got := a.service("alice"); got != want {
- t.Errorf("service as owner:\n%s\nwant:\n%s", got, want)
- }
- a.Rootless = true
- if got := a.service(""); strings.Contains(got, "network-online") || !strings.Contains(got, "After=fluxer.service\n") {
- t.Errorf("rootless service waits for the wrong units:\n%s", got)
- }
-}
-
-func TestUpgradeWaitsForMonthlyBackup(t *testing.T) {
- a := AutoUpgrade{Scheduler: Systemd, Project: "fluxer", Dir: "/opt/fluxer", Binary: "/usr/local/bin/rexctl", At: "04:00"}
- if got := a.service(""); !strings.Contains(got, "\nAfter=network-online.target fluxer.service\n") {
- t.Errorf("without a monthly backup the upgrade waits for:\n%s", got)
- }
- a.FullBackup = FullBackupMonthly
- if got := a.service(""); !strings.Contains(got, "\nAfter=network-online.target fluxer.service fluxer-backup.service\n") {
- t.Errorf("with a monthly backup the upgrade doesn't wait for it:\n%s", got)
- }
- a.Rootless = true
- if got := a.service(""); !strings.Contains(got, "\nAfter=fluxer.service fluxer-backup.service\n") {
- t.Errorf("rootless, with a monthly backup the upgrade doesn't wait for it:\n%s", got)
- }
-}
-
-func TestAutoUpgradeTimer(t *testing.T) {
- a := AutoUpgrade{Scheduler: Systemd, Project: "blue", Dir: "/srv/blue", Binary: "/usr/local/bin/rexctl", At: "23:05"}
- hour, minute, err := a.clock()
- if err != nil {
- t.Fatal(err)
- }
- want := `[Unit]
-Description=Upgrade Fluxer in /srv/blue every day
-
-[Timer]
-OnCalendar=*-*-* 23:05:00
-RandomizedDelaySec=30min
-Persistent=true
-
-[Install]
-WantedBy=timers.target
-`
- got := a.timer(-1, hour, minute)
- if got != want {
- t.Errorf("timer:\n%s\nwant:\n%s", got, want)
- }
- if day, at := timerSchedule([]byte(got)); day != "" || at != "23:05" {
- t.Errorf("timerSchedule = %q %q, want every day at 23:05", day, at)
- }
- if a.TimerName() != "blue-upgrade.timer" || a.ServiceName() != "blue-upgrade.service" {
- t.Errorf("unit names are %s and %s", a.TimerName(), a.ServiceName())
- }
-}
-
-func TestAutoUpgradeCron(t *testing.T) {
- a := AutoUpgrade{Scheduler: Cron, Project: "fluxer", Dir: "/srv/it's 100%", Binary: "/usr/local/bin/rexctl", At: "04:07", Log: "/srv/it's 100%/.rexctl/auto-upgrade.log"}
- want := `SHELL=/bin/sh
-PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
-7 4 * * * root '/usr/local/bin/rexctl' upgrade --yes --dir '/srv/it'\''s 100\%' >'/srv/it'\''s 100\%/.rexctl/auto-upgrade.log' 2>&1; echo "rexctl exited with $?" >>'/srv/it'\''s 100\%/.rexctl/auto-upgrade.log'
-`
- got := a.cron(-1, 4, 7, "")
- if got != want {
- t.Errorf("cron:\n%s\nwant:\n%s", got, want)
- }
- if day, at := cronSchedule([]byte(got)); day != "" || at != "04:07" {
- t.Errorf("cronSchedule = %q %q, want every day at 04:07", day, at)
- }
- if !strings.Contains(a.cron(-1, 4, 7, "alice"), " * * * alice ") {
- t.Error("cron doesn't run as the instance owner")
- }
- paths, err := a.Paths()
- if err != nil || len(paths) != 1 || paths[0] != "/etc/cron.d/fluxer-upgrade" {
- t.Errorf("Paths() = %v, %v", paths, err)
- }
-}
-
-func TestAutoUpgradeRefusesBadInput(t *testing.T) {
- for _, a := range []AutoUpgrade{
- {Scheduler: Systemd, Project: "fluxer", Dir: "fluxer", Binary: "/usr/local/bin/rexctl", At: "04:00"},
- {Scheduler: Systemd, Project: "fluxer", Dir: "/opt/fluxer", Binary: "/usr/local/bin/rexctl", At: "4am"},
- {Scheduler: Cron, Project: "fluxer", Dir: "/opt/fluxer", Binary: "/usr/local/bin/rexctl", At: "04:00"},
- {Project: "fluxer", Dir: "/opt/fluxer", Binary: "/usr/local/bin/rexctl", At: "04:00"},
- } {
- if _, err := a.files(); err == nil {
- t.Errorf("files() accepted %+v", a)
- }
- }
-}
-
-func TestAutoUpgradeCronStart(t *testing.T) {
- a := AutoUpgrade{Scheduler: Cron, Project: "fluxer", Domain: "chat.example.com", Dir: "/srv/fluxer", Binary: "/usr/local/bin/rexctl", At: "04:00", Log: "/srv/fluxer/.rexctl/auto-upgrade.log"}
- _, start, err := a.Start()
- if err != nil {
- t.Fatal(err)
- }
- if _, again, _ := a.Start(); again != start {
- t.Errorf("Start() = %q then %q, want the same time every time", start, again)
- }
- if start < "04:00" || start >= "04:30" {
- t.Errorf("Start() = %q, want a time from 04:00 to 04:29", start)
- }
- files, err := a.files()
- if _, at := cronSchedule(files[0]); err != nil || at != start {
- t.Errorf("cron file runs at %q, want %q (%v)", at, start, err)
- }
- spread := func(vary func(*AutoUpgrade, int)) int {
- starts := map[string]bool{}
- for i := range 8 {
- b := a
- vary(&b, i)
- _, s, _ := b.Start()
- starts[s] = true
- }
- return len(starts)
- }
- if n := spread(func(b *AutoUpgrade, i int) { b.Domain = fmt.Sprintf("chat%d.example.com", i) }); n < 2 {
- t.Errorf("eight servers with the default project and folder start at %d time, want them spread out", n)
- }
- if n := spread(func(b *AutoUpgrade, i int) { b.Dir = fmt.Sprintf("/srv/fluxer%d", i) }); n < 2 {
- t.Errorf("eight instances on one host start at %d time, want them spread out", n)
- }
- late := a
- late.At = "23:59"
- if _, s, _ := late.Start(); s >= "00:29" && s < "23:59" {
- t.Errorf("Start() for 23:59 = %q, want it to wrap past midnight", s)
- }
- sd := a
- sd.Scheduler = Systemd
- if _, s, _ := sd.Start(); s != "04:00" {
- t.Errorf("systemd Start() = %q, want 04:00 because the timer adds its own delay", s)
- }
-}
-
-func TestCronExit(t *testing.T) {
- log := filepath.Join(t.TempDir(), "auto-upgrade.log")
- if ran, _ := cronExit(log); ran {
- t.Error("a missing log counts as a run")
- }
- if err := os.WriteFile(log, []byte("✓ Fluxer is up to date.\n"), 0o600); err != nil {
- t.Fatal(err)
- }
- if ran, _ := cronExit(log); ran {
- t.Error("a log without an exit line counts as a finished run")
- }
- if err := os.WriteFile(log, []byte("✗ Another rexctl command is changing this instance.\nrexctl exited with 3\n"), 0o600); err != nil {
- t.Fatal(err)
- }
- if ran, code := cronExit(log); !ran || code != 3 {
- t.Errorf("cronExit = %v, %d, want true, 3", ran, code)
- }
-}
-
-func TestNextRunDaily(t *testing.T) {
- loc := time.FixedZone("CET", 3600)
- now := time.Date(2026, 10, 27, 5, 0, 0, 0, loc)
- if got := nextRun(now, "", 4, 0); !got.Equal(time.Date(2026, 10, 28, 4, 0, 0, 0, loc)) {
- t.Errorf("after the time: %v", got)
- }
- if got := nextRun(now, "", 6, 30); !got.Equal(time.Date(2026, 10, 27, 6, 30, 0, 0, loc)) {
- t.Errorf("before the time: %v", got)
- }
-}
-
-func TestNextRunWeeklyAcrossDST(t *testing.T) {
- loc, err := time.LoadLocation("Europe/Stockholm")
- if err != nil {
- t.Skip("no time zone data on this machine")
- }
- now := time.Date(2026, 10, 18, 5, 0, 0, 0, loc)
- got := nextRun(now, "Sun", 4, 0)
- want := time.Date(2026, 10, 25, 4, 0, 0, 0, loc)
- if !got.Equal(want) || got.Hour() != 4 {
- t.Errorf("next Sunday run across the clock change = %v, want %v", got, want)
- }
- if got.Sub(now) == 7*24*time.Hour-time.Hour {
- t.Error("the next run was counted in hours and lost the clock change")
- }
- if got := nextRun(time.Date(2026, 10, 25, 3, 0, 0, 0, loc), "sun", 4, 0); !got.Equal(want) {
- t.Errorf("earlier the same Sunday = %v, want %v", got, want)
- }
- if got := nextRun(time.Date(2026, 10, 26, 3, 0, 0, 0, loc), "Mon", 4, 0); got.Weekday() != time.Monday || got.Day() != 26 {
- t.Errorf("Monday run = %v, want Monday 26 October", got)
- }
-}
-
-func TestTimerDailyIsUnchanged(t *testing.T) {
- a := AutoUpgrade{Scheduler: Systemd, Project: "fluxer", Dir: "/opt/fluxer", Binary: "/usr/local/bin/rexctl", At: "04:00"}
- files, err := a.files()
- if err != nil {
- t.Fatal(err)
- }
- want := `[Unit]
-Description=Upgrade Fluxer in /opt/fluxer every day
-
-[Timer]
-OnCalendar=*-*-* 04:00:00
-RandomizedDelaySec=30min
-Persistent=true
-
-[Install]
-WantedBy=timers.target
-`
- if string(files[1]) != want {
- t.Errorf("daily timer:\n%s\nwant:\n%s", files[1], want)
- }
- a.Backup = BackupFull
- full, err := a.files()
- if err != nil || string(full[0]) != string(files[0]) || string(full[1]) != want {
- t.Errorf("a full backup changed the units (%v)", err)
- }
-}
-
-func TestTimerWeeklyAddsWeekday(t *testing.T) {
- a := AutoUpgrade{Scheduler: Systemd, Project: "fluxer", Dir: "/opt/fluxer", Binary: "/usr/local/bin/rexctl", At: "04:00", Day: "Sun"}
- files, err := a.files()
- if err != nil {
- t.Fatal(err)
- }
- timer := string(files[1])
- for _, line := range []string{"Description=Upgrade Fluxer in /opt/fluxer every Sunday\n", "OnCalendar=Sun *-*-* 04:00:00\n", "RandomizedDelaySec=30min\n", "Persistent=true\n"} {
- if !strings.Contains(timer, line) {
- t.Errorf("weekly timer has no %q:\n%s", line, timer)
- }
- }
- if day, at := timerSchedule(files[1]); day != "Sun" || at != "04:00" {
- t.Errorf("timerSchedule = %q %q, want Sun 04:00", day, at)
- }
- day, start, err := a.Start()
- if err != nil || day != "Sun" || start != "04:00" {
- t.Errorf("Start() = %q %q %v, want Sun 04:00", day, start, err)
- }
- a.Day = "Funday"
- if _, err := a.files(); err == nil {
- t.Error("files() accepted a day that doesn't exist")
- }
-}
-
-func TestCronWeeklyDayField(t *testing.T) {
- a := AutoUpgrade{Scheduler: Cron, Project: "fluxer", Dir: "/srv/fluxer", Binary: "/usr/local/bin/rexctl", At: "04:00", Day: "Wed", Log: "/srv/fluxer/.rexctl/auto-upgrade.log"}
- got := a.cron(3, 4, 7, "")
- if !strings.Contains(got, "\n7 4 * * 3 root ") {
- t.Errorf("weekly cron line:\n%s", got)
- }
- if day, at := cronSchedule([]byte(got)); day != "Wed" || at != "04:07" {
- t.Errorf("cronSchedule = %q %q, want Wed 04:07", day, at)
- }
- files, err := a.files()
- if err != nil {
- t.Fatal(err)
- }
- day, start, _ := a.Start()
- if d, at := cronSchedule(files[0]); d != day || at != start || day != "Wed" {
- t.Errorf("cron file runs %q %q, Start() says %q %q", d, at, day, start)
- }
-}
-
-func TestCronOffsetPastMidnightMovesWeekday(t *testing.T) {
- a := AutoUpgrade{Scheduler: Cron, Project: "fluxer", Dir: "/srv/fluxer", Binary: "/usr/local/bin/rexctl", Day: "sun", At: "23:50", Log: "/srv/fluxer/.rexctl/auto-upgrade.log"}
- found := false
- for i := range 64 {
- b := a
- b.Domain = fmt.Sprintf("chat%d.example.com", i)
- day, hour, minute, err := b.start()
- if err != nil {
- t.Fatal(err)
- }
- if hour*60+minute >= 23*60+50 {
- if day != 0 {
- t.Errorf("%s starts at %02d:%02d on day %d, want Sunday", b.Domain, hour, minute, day)
- }
- continue
- }
- found = true
- if day != 1 {
- t.Errorf("%s starts at %02d:%02d on day %d, want Monday", b.Domain, hour, minute, day)
- }
- files, err := b.files()
- if err != nil {
- t.Fatal(err)
- }
- want := fmt.Sprintf("\n%d %d * * 1 root ", minute, hour)
- if !strings.Contains(string(files[0]), want) {
- t.Errorf("cron file has no %q:\n%s", want, files[0])
- }
- }
- if !found {
- t.Fatal("no domain pushed the start past midnight")
- }
- sat := a
- sat.Day = "Saturday"
- for i := range 64 {
- sat.Domain = fmt.Sprintf("chat%d.example.com", i)
- if day, hour, _, _ := sat.start(); hour == 0 && day != 0 {
- t.Errorf("Saturday 23:50 moved past midnight to day %d, want Sunday", day)
- }
- }
-}
-
-func TestScheduleReadsOlderFiles(t *testing.T) {
- timer := "[Unit]\nDescription=Upgrade Fluxer in /opt/fluxer every day\n\n[Timer]\nOnCalendar=*-*-* 04:00:00\nRandomizedDelaySec=30min\nPersistent=true\n"
- if day, at := timerSchedule([]byte(timer)); day != "" || at != "04:00" {
- t.Errorf("older timer reads as %q %q", day, at)
- }
- cron := "SHELL=/bin/sh\nPATH=/usr/bin:/bin\n12 4 * * * root '/usr/local/bin/rexctl' upgrade --yes --dir '/opt/fluxer' >'/opt/fluxer/.rexctl/auto-upgrade.log' 2>&1\n"
- if day, at := cronSchedule([]byte(cron)); day != "" || at != "04:12" {
- t.Errorf("older cron reads as %q %q", day, at)
- }
- if b := serviceBackup([]byte(cron)); b != BackupFull {
- t.Errorf("older cron reads as backup %q", b)
- }
- if day, _ := cronSchedule([]byte("0 4 * * 7 root rexctl upgrade --yes\n")); day != "Sun" {
- t.Errorf("cron day 7 reads as %q, want Sun", day)
- }
-}
-
-func TestServiceAddsBackupFlagOnlyWhenLean(t *testing.T) {
- a := AutoUpgrade{Scheduler: Systemd, Project: "fluxer", Dir: "/opt/fluxer", Binary: "/usr/local/bin/rexctl", At: "04:00"}
- if got := a.service(""); strings.Contains(got, "--backup") {
- t.Errorf("default service passes --backup:\n%s", got)
- }
- a.Backup = "without-uploads"
- got := a.service("")
- if !strings.Contains(got, "ExecStart=/usr/local/bin/rexctl upgrade --yes --backup without-uploads --dir /opt/fluxer\n") {
- t.Errorf("lean service:\n%s", got)
- }
- if b := serviceBackup([]byte(got)); b != "without-uploads" {
- t.Errorf("serviceBackup = %q", b)
- }
- c := AutoUpgrade{Scheduler: Cron, Project: "fluxer", Dir: "/opt/fluxer", Binary: "/usr/local/bin/rexctl", Backup: "without-uploads", Log: "/opt/fluxer/.rexctl/auto-upgrade.log"}
- line := c.cron(-1, 4, 0, "")
- if !strings.Contains(line, "upgrade --yes --backup without-uploads --dir '/opt/fluxer'") || serviceBackup([]byte(line)) != "without-uploads" {
- t.Errorf("lean cron line:\n%s", line)
- }
-}
-
-func TestServiceWithoutBackupFlagReadsFull(t *testing.T) {
- a := AutoUpgrade{Scheduler: Systemd, Project: "fluxer", Dir: "/opt/fluxer", Binary: "/usr/local/bin/rexctl", At: "04:00"}
- if b := serviceBackup([]byte(a.service(""))); b != BackupFull {
- t.Errorf("serviceBackup = %q, want full", b)
- }
- if b := serviceBackup(nil); b != BackupFull {
- t.Errorf("serviceBackup of nothing = %q, want full", b)
- }
-}
-
-func TestWeekday(t *testing.T) {
- for in, want := range map[string]int{"sun": 0, "Mon": 1, "TUESDAY": 2, "wednesday": 3, "Sat": 6} {
- if got, ok := Weekday(in); !ok || got != want {
- t.Errorf("Weekday(%q) = %d, %v, want %d", in, got, ok, want)
- }
- }
- for _, in := range []string{"", "su", "mond", "funday", "7"} {
- if _, ok := Weekday(in); ok {
- t.Errorf("Weekday(%q) accepted", in)
- }
- }
-}
-
-func TestParseShow(t *testing.T) {
- m := parseShow([]byte("NextElapseUSecRealtime=Wed 2026-10-28 04:12:09 CET\nLastTriggerUSec=n/a\nExecMainStatus=0\nExecMainExitTimestamp=\n"))
- if m["NextElapseUSecRealtime"] != "Wed 2026-10-28 04:12:09 CET" || m["LastTriggerUSec"] != "" || m["ExecMainStatus"] != "0" || m["ExecMainExitTimestamp"] != "" {
- t.Errorf("parseShow = %v", m)
- }
-}
-
-func TestRequestedUndoesCronOffset(t *testing.T) {
- for _, sched := range []Scheduler{Cron, Systemd} {
- for _, c := range []struct{ day, at string }{{"", "04:00"}, {"", "23:50"}, {"Sun", "23:50"}, {"Sat", "23:59"}, {"Mon", "00:00"}} {
- a := AutoUpgrade{Scheduler: sched, Project: "fluxer", Domain: "chat.example.com", Dir: "/opt/fluxer", Day: c.day, At: c.at}
- day, at, err := a.Start()
- if err != nil {
- t.Fatal(err)
- }
- if sched == Systemd {
- day = c.day
- }
- gotDay, gotAt := a.Requested(day, at)
- if gotDay != c.day || gotAt != c.at {
- t.Errorf("%s %q %s started %q %s and reads back as %q %s", sched, c.day, c.at, day, at, gotDay, gotAt)
- }
- }
- }
-}
-
-func TestMonthlyRunPassedSurvivesReboot(t *testing.T) {
- stockholm, err := time.LoadLocation("Europe/Stockholm")
- if err != nil {
- t.Skip(err)
- }
- turnedOn := time.Date(2026, 10, 20, 12, 0, 0, 0, stockholm)
- for _, c := range []struct {
- now time.Time
- want bool
- }{
- {time.Date(2026, 10, 30, 9, 0, 0, 0, stockholm), false},
- {time.Date(2026, 11, 1, 0, 29, 0, 0, stockholm), false},
- {time.Date(2026, 11, 1, 0, 30, 0, 0, stockholm), true},
- {time.Date(2026, 12, 15, 9, 0, 0, 0, stockholm), true},
- } {
- if got := monthlyRunPassed(turnedOn, c.now, "00:30"); got != c.want {
- t.Errorf("turned on %s, at %s the monthly backup has run = %v, want %v", turnedOn, c.now, got, c.want)
- }
- }
- if monthlyRunPassed(time.Time{}, time.Date(2026, 12, 15, 9, 0, 0, 0, stockholm), "00:30") || monthlyRunPassed(turnedOn, time.Date(2026, 12, 15, 9, 0, 0, 0, stockholm), "") {
- t.Error("a monthly backup with no known start or time reads as run")
- }
-}
-
-const fakeSystemctl = `#!/bin/sh
-echo "$*" >> "$SYSTEMCTL_LOG"
-case "$2" in
-enable) echo 1 > "$SYSTEMCTL_STATE.enabled" ;;
-restart) echo 1 > "$SYSTEMCTL_STATE.active" ;;
-disable) : > "$SYSTEMCTL_STATE.enabled"; : > "$SYSTEMCTL_STATE.active" ;;
-is-enabled) v=""; read -r v < "$SYSTEMCTL_STATE.enabled"; [ "$v" = 1 ] && echo enabled ;;
-is-active) v=""; read -r v < "$SYSTEMCTL_STATE.active"; [ "$v" = 1 ] && echo active ;;
-esac
-exit 0
-`
-
-func TestAutoUpgradeInstallAndRemove(t *testing.T) {
- if runtime.GOOS == "windows" {
- t.Skip("needs a shell to fake systemctl")
- }
- root := t.TempDir()
- bin := filepath.Join(root, "bin")
- if err := os.MkdirAll(bin, 0o755); err != nil {
- t.Fatal(err)
- }
- if err := os.WriteFile(filepath.Join(bin, "systemctl"), []byte(fakeSystemctl), 0o755); err != nil {
- t.Fatal(err)
- }
- state := filepath.Join(root, "unit")
- for _, s := range []string{".enabled", ".active"} {
- if err := os.WriteFile(state+s, nil, 0o600); err != nil {
- t.Fatal(err)
- }
- }
- log := filepath.Join(root, "systemctl.log")
- t.Setenv("PATH", bin)
- t.Setenv("XDG_CONFIG_HOME", filepath.Join(root, "config"))
- t.Setenv("SYSTEMCTL_LOG", log)
- t.Setenv("SYSTEMCTL_STATE", state)
- calls := func() []string {
- data, _ := os.ReadFile(log)
- _ = os.Remove(log)
- return strings.Fields(strings.ReplaceAll(strings.TrimSpace(string(data)), " ", "_"))
- }
- ctx := context.Background()
- a := AutoUpgrade{Scheduler: Systemd, Project: "fluxer", Dir: filepath.Join(root, "fluxer"), Binary: filepath.Join(bin, "rexctl"), Rootless: true, At: "04:00"}
- if err := InstallAutoUpgrade(ctx, a); err != nil {
- t.Fatal(err)
- }
- want := []string{"--user_daemon-reload", "--user_is-enabled_fluxer-upgrade.timer", "--user_enable_fluxer-upgrade.timer", "--user_restart_fluxer-upgrade.timer"}
- if got := calls(); strings.Join(got, " ") != strings.Join(want, " ") {
- t.Errorf("first install ran %v, want %v", got, want)
- }
- unitDir := filepath.Join(root, "config", "systemd", "user")
- for _, name := range []string{"fluxer-upgrade.service", "fluxer-upgrade.timer"} {
- if _, err := os.Stat(filepath.Join(unitDir, name)); err != nil {
- t.Errorf("%s wasn't written: %v", name, err)
- }
- }
- if err := InstallAutoUpgrade(ctx, a); err != nil {
- t.Fatal(err)
- }
- want = []string{"--user_is-enabled_fluxer-upgrade.timer", "--user_is-active_fluxer-upgrade.timer"}
- if got := calls(); strings.Join(got, " ") != strings.Join(want, " ") {
- t.Errorf("second install ran %v, want only %v", got, want)
- }
- a.At = "05:30"
- if err := InstallAutoUpgrade(ctx, a); err != nil {
- t.Fatal(err)
- }
- want = []string{"--user_daemon-reload", "--user_is-enabled_fluxer-upgrade.timer", "--user_restart_fluxer-upgrade.timer"}
- if got := calls(); strings.Join(got, " ") != strings.Join(want, " ") {
- t.Errorf("changing the time ran %v, want %v", got, want)
- }
- timer, err := os.ReadFile(filepath.Join(unitDir, "fluxer-upgrade.timer"))
- if _, at := timerSchedule(timer); err != nil || at != "05:30" {
- t.Errorf("the timer doesn't run at 05:30: %v", err)
- }
- removed, err := RemoveAutoUpgrade(ctx, a)
- if err != nil || !removed {
- t.Fatalf("RemoveAutoUpgrade = %v, %v", removed, err)
- }
- want = []string{"--user_is-enabled_fluxer-upgrade.timer", "--user_disable_--now_fluxer-upgrade.timer", "--user_daemon-reload"}
- if got := calls(); strings.Join(got, " ") != strings.Join(want, " ") {
- t.Errorf("remove ran %v, want %v", got, want)
- }
- entries, _ := os.ReadDir(unitDir)
- if len(entries) != 0 {
- t.Errorf("remove left %d files", len(entries))
- }
- removed, err = RemoveAutoUpgrade(ctx, a)
- if err != nil || removed {
- t.Errorf("second RemoveAutoUpgrade = %v, %v, want false, nil", removed, err)
- }
- if got := calls(); len(got) != 0 {
- t.Errorf("second remove ran %v", got)
- }
-}
-
-func TestFullBackupRunsHoursBeforeUpgrades(t *testing.T) {
- for _, tc := range []struct{ at, want string }{{"04:00", "01:00"}, {"02:45", "23:45"}, {"03:00", "00:00"}, {"03:30", "00:30"}, {"00:10", "21:10"}} {
- a := AutoUpgrade{Scheduler: Cron, Project: "fluxer", Domain: "chat.example.com", Dir: "/opt/fluxer", At: tc.at}
- got, err := a.BackupStart()
- if err != nil || got != tc.want {
- t.Errorf("--at %s backs up at %q (%v), want %s", tc.at, got, err, tc.want)
- continue
- }
- _, start, _ := a.Start()
- up, _ := time.Parse("15:04", start)
- back, _ := time.Parse("15:04", got)
- gap := up.Sub(back)
- if gap < 0 {
- gap += 24 * time.Hour
- }
- if gap < 3*time.Hour || gap+UpgradeWindow > 24*time.Hour-time.Hour {
- t.Errorf("--at %s upgrades at %s and backs up at %s, %v apart", tc.at, start, got, gap)
- }
- }
-}
-
-func TestFullBackupUnitsUseFullPaths(t *testing.T) {
- a := AutoUpgrade{Scheduler: Systemd, Project: "fluxer", Dir: "/opt/fluxer-missing", Binary: "/usr/local/bin/rexctl", Podman: true, At: "02:45", Log: "/opt/fluxer-missing/.rexctl/auto-upgrade.log"}
- files, err := a.backupFiles()
- if err != nil {
- t.Fatal(err)
- }
- wantService := `[Unit]
-Description=Back up Fluxer in /opt/fluxer-missing
-After=fluxer.service
-
-[Service]
-Type=oneshot
-ExecStart=/usr/local/bin/rexctl backup --dir /opt/fluxer-missing
-`
- wantTimer := `[Unit]
-Description=Back up Fluxer in /opt/fluxer-missing once a month
-
-[Timer]
-OnCalendar=*-*-01 23:45:00
-Persistent=true
-
-[Install]
-WantedBy=timers.target
-`
- if len(files) != 2 || string(files[0]) != wantService || string(files[1]) != wantTimer {
- t.Errorf("systemd backup units:\n%s\n%s", files[0], files[1])
- }
- paths, err := a.BackupPaths()
- if err != nil || len(paths) != 2 || paths[0] != "/etc/systemd/system/fluxer-backup.service" || paths[1] != "/etc/systemd/system/fluxer-backup.timer" {
- t.Errorf("systemd backup paths = %v, %v", paths, err)
- }
- a.Scheduler = Cron
- files, err = a.backupFiles()
- if err != nil {
- t.Fatal(err)
- }
- wantCron := "SHELL=/bin/sh\nPATH=" + cronPath + "\n45 23 1 * * root '/usr/local/bin/rexctl' backup --dir '/opt/fluxer-missing' >'/opt/fluxer-missing/.rexctl/full-backup.log' 2>&1; echo \"rexctl exited with $?\" >>'/opt/fluxer-missing/.rexctl/full-backup.log'\n"
- if len(files) != 1 || string(files[0]) != wantCron {
- t.Errorf("cron backup file:\n%s\nwant:\n%s", files[0], wantCron)
- }
- if day, at := cronSchedule(files[0]); day != "" || at != "23:45" {
- t.Errorf("the cron backup file reads back as %q %q", day, at)
- }
- a.Domain = "chat.example.com"
- if _, start, _ := a.Start(); start == "02:45" {
- t.Fatal("the test needs a cron offset")
- }
- if files, _ := a.backupFiles(); !strings.Contains(string(files[0]), "\n45 23 1 * * ") {
- t.Errorf("the cron offset moved the backup:\n%s", files[0])
- }
- if paths, _ := a.BackupPaths(); len(paths) != 1 || paths[0] != "/etc/cron.d/fluxer-backup" {
- t.Errorf("cron backup paths = %v", paths)
- }
-}
-
-func fakeSystemd(t *testing.T) (string, func() []string) {
- t.Helper()
- if runtime.GOOS == "windows" {
- t.Skip("needs a shell to fake systemctl")
- }
- root := t.TempDir()
- bin := filepath.Join(root, "bin")
- if err := os.MkdirAll(bin, 0o755); err != nil {
- t.Fatal(err)
- }
- if err := os.WriteFile(filepath.Join(bin, "systemctl"), []byte(fakeSystemctl), 0o755); err != nil {
- t.Fatal(err)
- }
- state := filepath.Join(root, "unit")
- for _, s := range []string{".enabled", ".active"} {
- if err := os.WriteFile(state+s, nil, 0o600); err != nil {
- t.Fatal(err)
- }
- }
- log := filepath.Join(root, "systemctl.log")
- t.Setenv("PATH", bin)
- t.Setenv("XDG_CONFIG_HOME", filepath.Join(root, "config"))
- t.Setenv("SYSTEMCTL_LOG", log)
- t.Setenv("SYSTEMCTL_STATE", state)
- return root, func() []string {
- data, _ := os.ReadFile(log)
- _ = os.Remove(log)
- return strings.Fields(strings.ReplaceAll(strings.TrimSpace(string(data)), " ", "_"))
- }
-}
-
-func TestFullBackupTimerInstallAndRemove(t *testing.T) {
- root, calls := fakeSystemd(t)
- ctx := context.Background()
- a := AutoUpgrade{Scheduler: Systemd, Project: "fluxer", Dir: filepath.Join(root, "fluxer"), Binary: filepath.Join(root, "bin", "rexctl"), Rootless: true, At: "04:00", FullBackup: FullBackupMonthly, Log: filepath.Join(root, "fluxer", ".rexctl", "auto-upgrade.log")}
- if err := InstallAutoUpgrade(ctx, a); err != nil {
- t.Fatal(err)
- }
- got := strings.Join(calls(), " ")
- if !strings.Contains(got, "--user_restart_fluxer-backup.timer") || !strings.Contains(got, "--user_restart_fluxer-upgrade.timer") {
- t.Errorf("installing with a monthly full backup ran %s", got)
- }
- unitDir := filepath.Join(root, "config", "systemd", "user")
- timer, err := os.ReadFile(filepath.Join(unitDir, "fluxer-backup.timer"))
- if err != nil || !strings.Contains(string(timer), "OnCalendar=*-*-01 01:00:00\n") {
- t.Errorf("backup timer = %q, %v", timer, err)
- }
- s, err := CheckAutoUpgrade(ctx, a, time.Now())
- if err != nil || s.FullBackup != FullBackupMonthly || s.FullBackupAt != "01:00" || s.FullBackupRan {
- t.Errorf("status = %+v, %v, want a monthly full backup at 01:00 that hasn't run", s, err)
- }
- if !strings.Contains(string(timer), "Persistent=true\n") {
- t.Errorf("a monthly backup missed while the machine is off isn't made later, timer %q", timer)
- }
- installed := time.Now().AddDate(0, -2, 0)
- if err := os.Chtimes(filepath.Join(unitDir, "fluxer-backup.timer"), installed, installed); err != nil {
- t.Fatal(err)
- }
- if s, err := CheckAutoUpgrade(ctx, a, time.Now()); err != nil || !s.FullBackupRan {
- t.Errorf("status = %+v, %v, want a monthly full backup that was due since it was turned on", s, err)
- }
- a.FullBackup = ""
- if err := InstallAutoUpgrade(ctx, a); err != nil {
- t.Fatal(err)
- }
- if got := strings.Join(calls(), " "); !strings.Contains(got, "--user_disable_--now_fluxer-backup.timer") {
- t.Errorf("installing without a full backup ran %s", got)
- }
- for _, name := range []string{"fluxer-backup.service", "fluxer-backup.timer"} {
- if _, err := os.Stat(filepath.Join(unitDir, name)); !os.IsNotExist(err) {
- t.Errorf("%s is still there (%v)", name, err)
- }
- }
- if s, _ := CheckAutoUpgrade(ctx, a, time.Now()); s.FullBackup != "" {
- t.Errorf("status still shows a full backup %q", s.FullBackup)
- }
- a.FullBackup = FullBackupMonthly
- if err := InstallAutoUpgrade(ctx, a); err != nil {
- t.Fatal(err)
- }
- calls()
- removed, err := RemoveAutoUpgrade(ctx, a)
- if err != nil || !removed {
- t.Fatalf("RemoveAutoUpgrade = %v, %v", removed, err)
- }
- if got := strings.Join(calls(), " "); !strings.Contains(got, "fluxer-backup.timer") || !strings.Contains(got, "fluxer-upgrade.timer") {
- t.Errorf("remove ran %s", got)
- }
- if entries, _ := os.ReadDir(unitDir); len(entries) != 0 {
- t.Errorf("remove left %d files", len(entries))
- }
-}
-
-func TestDropBackupFlagKeepsTheSchedule(t *testing.T) {
- root, calls := fakeSystemd(t)
- ctx := context.Background()
- a := AutoUpgrade{Scheduler: Systemd, Project: "fluxer", Dir: filepath.Join(root, "fluxer"), Binary: filepath.Join(root, "bin", "rexctl"), Rootless: true, At: "02:45", Day: "Sun", Backup: "without-uploads"}
- if err := InstallAutoUpgrade(ctx, a); err != nil {
- t.Fatal(err)
- }
- unitDir := filepath.Join(root, "config", "systemd", "user")
- timerBefore, _ := os.ReadFile(filepath.Join(unitDir, "fluxer-upgrade.timer"))
- calls()
- changed, err := DropBackupFlag(ctx, a)
- if err != nil || !changed {
- t.Fatalf("DropBackupFlag = %v, %v", changed, err)
- }
- service, _ := os.ReadFile(filepath.Join(unitDir, "fluxer-upgrade.service"))
- full := a
- full.Backup = BackupFull
- if string(service) != full.service("") {
- t.Errorf("service after dropping --backup:\n%s\nwant:\n%s", service, full.service(""))
- }
- if timer, _ := os.ReadFile(filepath.Join(unitDir, "fluxer-upgrade.timer")); string(timer) != string(timerBefore) {
- t.Errorf("dropping --backup changed the timer to\n%s", timer)
- }
- if got := calls(); strings.Join(got, " ") != "--user_daemon-reload" {
- t.Errorf("dropping --backup ran %v", got)
- }
- if changed, err := DropBackupFlag(ctx, a); err != nil || changed {
- t.Errorf("second DropBackupFlag = %v, %v, want false, nil", changed, err)
- }
-
- cron := AutoUpgrade{Scheduler: Cron, Project: "fluxer", Domain: "chat.example.com", Dir: "/opt/fluxer", Binary: "/usr/local/bin/rexctl", At: "23:50", Day: "Sun", Backup: "without-uploads", Log: "/opt/fluxer/.rexctl/auto-upgrade.log"}
- day, hour, minute, err := cron.start()
- if err != nil {
- t.Fatal(err)
- }
- lean := cron.cron(day, hour, minute, "root")
- cron.Backup = BackupFull
- if got := strings.ReplaceAll(lean, " upgrade --yes --backup without-uploads ", " upgrade --yes "); got != cron.cron(day, hour, minute, "root") {
- t.Errorf("the cron line without --backup is\n%s\nwant\n%s", got, cron.cron(day, hour, minute, "root"))
- }
-}
diff --git a/fluxer_rexctl/internal/host/bootunit_test.go b/fluxer_rexctl/internal/host/bootunit_test.go
deleted file mode 100644
index c4c14f59d..000000000
--- a/fluxer_rexctl/internal/host/bootunit_test.go
+++ /dev/null
@@ -1,78 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-package host
-
-import (
- "os"
- "path/filepath"
- "runtime"
- "slices"
- "strconv"
- "strings"
- "testing"
-)
-
-func TestUnitBinariesReadWhatRexctlWrites(t *testing.T) {
- const bin = `/home/a b/it's 100%/$rexctl`
- a := AutoUpgrade{Project: "fluxer", Dir: "/srv/fluxer", Binary: bin, At: "04:00", Log: "/srv/fluxer/.rexctl/upgrade.log"}
- for name, c := range map[string]struct {
- unit string
- want string
- }{
- "rootful boot unit": {BootUnit{Project: "fluxer", Dir: "/srv/fluxer", Binary: bin}.render(false, "fluxer"), LibexecBinary},
- "rootless boot unit": {BootUnit{Project: "fluxer", Dir: "/srv/fluxer", Binary: bin, Rootless: true}.render(false, ""), bin},
- "upgrade service": {a.service("fluxer"), bin},
- "cron job": {a.cron(-1, 4, 0, "fluxer"), bin},
- } {
- if got := unitBinaries([]byte(c.unit)); !slices.Equal(got, []string{c.want}) {
- t.Errorf("%s runs %q, want %q", name, got, c.want)
- }
- }
-}
-
-func TestRootRefreshesOnlyUnitsRootOwns(t *testing.T) {
- home := t.TempDir()
- t.Setenv("HOME", home)
- t.Setenv("XDG_CONFIG_HOME", "")
- prev := asRoot
- t.Cleanup(func() { asRoot = prev })
- for _, root := range []bool{false, true} {
- asRoot = func() bool { return root }
- units, err := unitFiles("fluxer")
- if err != nil {
- t.Fatal(err)
- }
- inHome := 0
- for path := range units {
- if strings.HasPrefix(path, home) {
- inHome++
- }
- }
- if root && inHome > 0 {
- t.Errorf("as root, rexctl reads units from $HOME, which sudo may keep: %v", units)
- }
- if !root && inHome != 2 {
- t.Errorf("without root, rexctl skips your own units: %v", units)
- }
- }
-}
-
-func TestInstallKeepsTheBinarysOwner(t *testing.T) {
- if runtime.GOOS == "windows" {
- t.Skip("no owners on Windows")
- }
- dir := t.TempDir()
- dst := filepath.Join(dir, "rexctl")
- if got := installArgs("/tmp/new", dst); slices.Contains(got, "-o") {
- t.Fatalf("a new binary got an owner: %q", got)
- }
- if err := os.WriteFile(dst, []byte("old"), 0o755); err != nil {
- t.Fatal(err)
- }
- uid, gid := strconv.Itoa(os.Getuid()), strconv.Itoa(os.Getgid())
- got := installArgs("/tmp/new", dst)
- want := []string{"-D", "-m", "0755", "-o", uid, "-g", gid, "/tmp/new", dst}
- if !slices.Equal(got, want) {
- t.Fatalf("install %q, want %q", got, want)
- }
-}
diff --git a/fluxer_rexctl/internal/host/overcommit_test.go b/fluxer_rexctl/internal/host/overcommit_test.go
deleted file mode 100644
index d7cc37aa0..000000000
--- a/fluxer_rexctl/internal/host/overcommit_test.go
+++ /dev/null
@@ -1,41 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-package host
-
-import (
- "os"
- "path/filepath"
- "testing"
-)
-
-func TestOvercommitAtReadsTheSetting(t *testing.T) {
- dir := t.TempDir()
- path := filepath.Join(dir, "overcommit_memory")
- for value, want := range map[string]OvercommitState{"1\n": OvercommitOn, "0\n": OvercommitOff, "2\n": OvercommitOff} {
- if err := os.WriteFile(path, []byte(value), 0o644); err != nil {
- t.Fatal(err)
- }
- if got := overcommitAt(path, false); got != want {
- t.Errorf("overcommitAt(%q) = %v, want %v", value, got, want)
- }
- }
- if got := overcommitAt(filepath.Join(dir, "missing"), false); got != OvercommitOn {
- t.Errorf("a missing file = %v, want %v", got, OvercommitOn)
- }
-}
-
-func TestOvercommitAtSeesASettingRootCantWrite(t *testing.T) {
- if os.Geteuid() == 0 {
- t.Skip("root can write a read-only file")
- }
- path := filepath.Join(t.TempDir(), "overcommit_memory")
- if err := os.WriteFile(path, []byte("0\n"), 0o444); err != nil {
- t.Fatal(err)
- }
- if got := overcommitAt(path, true); got != OvercommitLocked {
- t.Errorf("as root = %v, want %v", got, OvercommitLocked)
- }
- if got := overcommitAt(path, false); got != OvercommitOff {
- t.Errorf("as a user who can use sudo = %v, want %v", got, OvercommitOff)
- }
-}
diff --git a/fluxer_rexctl/internal/instance/bundledvoice_test.go b/fluxer_rexctl/internal/instance/bundledvoice_test.go
deleted file mode 100644
index 4044fc047..000000000
--- a/fluxer_rexctl/internal/instance/bundledvoice_test.go
+++ /dev/null
@@ -1,69 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-package instance
-
-import (
- "context"
- "slices"
- "testing"
-
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/engine"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/secrets"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/settings"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/stack"
-)
-
-func loadWithVoice(t *testing.T, bundled string) *engine.Project {
- t.Helper()
- inst, err := Create(t.TempDir(), "fluxer")
- if err != nil {
- t.Fatal(err)
- }
- set := stack.Embedded()
- inst.State.Release = set.Release
- inst.State.Images = Images{Release: set.Release, Refs: fluxerRefs("a")}
- inst.State.Settings[settings.Domain] = "chat.example.com"
- if bundled != "" {
- inst.State.Settings[settings.VoiceBundled] = bundled
- }
- if _, err := secrets.Mint(inst.State.Secrets, false); err != nil {
- t.Fatal(err)
- }
- if _, err := inst.Render(set, stack.OverlaysFor(inst.State.Settings), inst.State.Images.Refs); err != nil {
- t.Fatal(err)
- }
- env, err := inst.Environment()
- if err != nil {
- t.Fatal(err)
- }
- var none engine.Engine
- p, err := none.Load(context.Background(), engine.Spec{Name: "fluxer", Dir: inst.Dir, Files: inst.ComposeFiles(), Env: env})
- if err != nil {
- t.Fatalf("voice.bundled %q: %v", bundled, err)
- }
- return p
-}
-
-func TestWithoutBundledVoiceLiveKitDoesNotRun(t *testing.T) {
- for _, tc := range []struct {
- bundled string
- runs bool
- env string
- }{
- {"", true, "true"},
- {"true", true, "true"},
- {"false", false, "false"},
- } {
- p := loadWithVoice(t, tc.bundled)
- if got := slices.Contains(p.Services(), "livekit"); got != tc.runs {
- t.Errorf("voice.bundled %q: livekit runs = %v, want %v", tc.bundled, got, tc.runs)
- }
- if !slices.Contains(p.Services(), "api") || !slices.Contains(p.Services(), "edge") {
- t.Errorf("voice.bundled %q: services %v", tc.bundled, p.Services())
- }
- got := p.Model.Services["api"].Environment["FLUXER_LIVEKIT_BUNDLED"]
- if got == nil || *got != tc.env {
- t.Errorf("voice.bundled %q: api FLUXER_LIVEKIT_BUNDLED = %v, want %s", tc.bundled, got, tc.env)
- }
- }
-}
diff --git a/fluxer_rexctl/internal/instance/bundleenv_test.go b/fluxer_rexctl/internal/instance/bundleenv_test.go
deleted file mode 100644
index 5f9092d75..000000000
--- a/fluxer_rexctl/internal/instance/bundleenv_test.go
+++ /dev/null
@@ -1,52 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-package instance
-
-import (
- "maps"
- "regexp"
- "slices"
- "testing"
-
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/envfile"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/secrets"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/stack"
-)
-
-func TestBundleEnvKeys(t *testing.T) {
- out := BundleEnv()
- if out != BundleEnv() {
- t.Fatal("BundleEnv is not deterministic")
- }
- f, err := envfile.Parse(".env.example", []byte(out))
- if err != nil {
- t.Fatal(err)
- }
-
- wantActive := map[string]string{stack.SettingsLoadedVar: "true", "FLUXER_DOMAIN": "", SetupTokenVar: ""}
- for _, s := range secrets.Required {
- wantActive[s.Key] = ""
- if s.Kind == secrets.KindFixed {
- wantActive[s.Key] = s.Fixed
- }
- }
- if got := f.Map(); !maps.Equal(got, wantActive) {
- t.Errorf("active keys\n got %v\nwant %v", got, wantActive)
- }
-
- var wantCommented []string
- for _, d := range envDocs() {
- if _, ok := wantActive[d.name]; !ok && d.bundled {
- wantCommented = append(wantCommented, d.name)
- }
- }
- var gotCommented []string
- for _, m := range regexp.MustCompile(`(?m)^# ([A-Z][A-Z0-9_]*)=$`).FindAllStringSubmatch(out, -1) {
- gotCommented = append(gotCommented, m[1])
- }
- slices.Sort(wantCommented)
- slices.Sort(gotCommented)
- if !slices.Equal(gotCommented, wantCommented) {
- t.Errorf("commented keys\n got %v\nwant %v", gotCommented, wantCommented)
- }
-}
diff --git a/fluxer_rexctl/internal/instance/eject_test.go b/fluxer_rexctl/internal/instance/eject_test.go
deleted file mode 100644
index 92e9b60ad..000000000
--- a/fluxer_rexctl/internal/instance/eject_test.go
+++ /dev/null
@@ -1,160 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-package instance
-
-import (
- "encoding/json"
- "errors"
- "maps"
- "os"
- "path/filepath"
- "strings"
- "testing"
- "time"
-
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/secrets"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/stack"
-)
-
-const (
- ejectedAt = "2026.10.0"
- shippedAt = "2026.11.0"
-)
-
-func fluxerRefs(digit string) map[string]string {
- refs := map[string]string{}
- for _, svc := range []string{"api", "worker", "gateway", "media-proxy", "push", "static-proxy", "app-proxy", "admin", "snowflakes", "users", "gifs", "messages", "unfurl"} {
- refs[svc] = "ghcr.io/fluxerapp/fluxer-" + svc + "@sha256:" + strings.Repeat(digit, 64)
- }
- return refs
-}
-
-func TestMain(m *testing.M) {
- dir, err := os.MkdirTemp("", "rexctl-imageset")
- if err != nil {
- panic(err)
- }
- data, err := json.Marshal(stack.ImageSet{Release: shippedAt, Images: fluxerRefs("b")})
- if err != nil {
- panic(err)
- }
- path := filepath.Join(dir, "imageset.json")
- if err := os.WriteFile(path, data, 0o644); err != nil {
- panic(err)
- }
- os.Setenv(stack.ImageSetEnv, path)
- code := m.Run()
- os.RemoveAll(dir)
- os.Exit(code)
-}
-
-func ejectedInstance(t *testing.T, declared *stack.Set, refs map[string]string) string {
- t.Helper()
- dir := t.TempDir()
- shipped := stack.Embedded()
- old := &stack.Set{Release: ejectedAt, Files: shipped.Files, Profiles: shipped.Profiles, Vars: shipped.Vars}
- if err := stack.WriteSet(filepath.Join(dir, StateDirName, ReleasesDir, ejectedAt, StackDir), old); err != nil {
- t.Fatal(err)
- }
- if _, err := stack.Render(old, nil, fluxerRefs("a"), "fluxer", dir); err != nil {
- t.Fatal(err)
- }
- rendered, err := writePlain(&Instance{Dir: dir})
- if err != nil {
- t.Fatal(err)
- }
- compose, err := stack.RenderCompose(declared, refs, "fluxer")
- if err != nil {
- t.Fatal(err)
- }
- if err := os.WriteFile(filepath.Join(dir, stack.ComposeFile), compose, 0o644); err != nil {
- t.Fatal(err)
- }
- s := &State{
- Project: "fluxer",
- Release: ejectedAt,
- Images: Images{Release: ejectedAt, Refs: fluxerRefs("a")},
- Settings: map[string]string{},
- Secrets: map[string]string{},
- Rendered: rendered,
- SetupDone: true,
- Ejected: &Ejected{At: time.Now().UTC().Truncate(time.Second)},
- }
- if _, err := secrets.Mint(s.Secrets, false); err != nil {
- t.Fatal(err)
- }
- if err := s.Save(filepath.Join(dir, StateDirName, StateFileName)); err != nil {
- t.Fatal(err)
- }
- return dir
-}
-
-func TestTakeoverOfEjectedInstanceNeverGoesBack(t *testing.T) {
- shipped := stack.Embedded()
- old := &stack.Set{Release: ejectedAt, Files: shipped.Files, Profiles: shipped.Profiles, Vars: shipped.Vars}
-
- t.Run("same release", func(t *testing.T) {
- s, r, err := Import(ejectedInstance(t, old, fluxerRefs("a")), nil)
- if err != nil {
- t.Fatal(err)
- }
- if s.Release != ejectedAt || len(r.KeepAsMine) != 0 {
- t.Fatalf("release %s, kept %v", s.Release, r.KeepAsMine)
- }
- })
-
- t.Run("updated to the release rexctl ships", func(t *testing.T) {
- s, r, err := Import(ejectedInstance(t, shipped, fluxerRefs("b")), nil)
- if err != nil {
- t.Fatal(err)
- }
- if s.Release != shippedAt || s.Images.Release != shippedAt || !maps.Equal(s.Images.Refs, fluxerRefs("b")) {
- t.Fatalf("took over on %s with %v", s.Release, s.Images)
- }
- if s.PreviousRelease != ejectedAt || len(r.KeepAsMine) != 0 {
- t.Fatalf("previous %s, kept %v", s.PreviousRelease, r.KeepAsMine)
- }
- })
-
- t.Run("updated to a release rexctl doesn't know", func(t *testing.T) {
- dir := ejectedInstance(t, shipped, fluxerRefs("c"))
- _, _, err := Import(dir, nil)
- var ae *AdoptError
- if !errors.As(err, &ae) {
- t.Fatalf("took over an instance on unknown images: %v", err)
- }
- data, err := os.ReadFile(filepath.Join(dir, StateDirName, StateFileName))
- if err != nil {
- t.Fatal(err)
- }
- s, err := ParseState(data, dir)
- if err != nil || s.Ejected == nil || s.Release != ejectedAt {
- t.Fatalf("state changed after the refusal: %v", err)
- }
- })
-}
-
-func TestTakeoverAfterHandUpgradeForgetsPreviousBackup(t *testing.T) {
- shipped := stack.Embedded()
- dir := ejectedInstance(t, shipped, fluxerRefs("b"))
- path := filepath.Join(dir, StateDirName, StateFileName)
- data, err := os.ReadFile(path)
- if err != nil {
- t.Fatal(err)
- }
- s, err := ParseState(data, dir)
- if err != nil {
- t.Fatal(err)
- }
- s.PreviousRelease, s.PreviousBackup = "2026.1001.100000", filepath.Join(dir, "backups", "fluxer-a.tar.zst")
- if err := s.Save(path); err != nil {
- t.Fatal(err)
- }
- got, _, err := Import(dir, nil)
- if err != nil {
- t.Fatal(err)
- }
- if got.PreviousRelease != ejectedAt || got.PreviousBackup != "" {
- t.Errorf("after takeover the previous release is %s and the previous backup %q", got.PreviousRelease, got.PreviousBackup)
- }
-}
diff --git a/fluxer_rexctl/internal/instance/envdocs_test.go b/fluxer_rexctl/internal/instance/envdocs_test.go
deleted file mode 100644
index 1fecedf0a..000000000
--- a/fluxer_rexctl/internal/instance/envdocs_test.go
+++ /dev/null
@@ -1,188 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-package instance
-
-import (
- "io/fs"
- "maps"
- "os"
- "path/filepath"
- "regexp"
- "slices"
- "strings"
- "testing"
-
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/adminapi"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/secrets"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/settings"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/stack"
-)
-
-const docsContent = "fluxer_docs/src/content/docs"
-
-var (
- docsEnvName = regexp.MustCompile(`\bFLUXER_[A-Z0-9_]*[A-Z0-9]\b(\*)?`)
- docsConfigCmd = regexp.MustCompile("rexctl config (?:set|unset|get) ([A-Za-z0-9_.]+)")
- docsDottedName = regexp.MustCompile("`([a-z][a-z0-9_]*(?:\\.[a-z0-9_]+)+)`")
- composeSecret = regexp.MustCompile(`(?m)^sed -i "s\|\^([A-Z0-9_]+)=\.\*\|[A-Z0-9_]+=\$\((.*)\)\|" \.env$`)
- composeLoop = regexp.MustCompile(`(?s)for key in (.*?); do\n\s*sed -i "s\|\^\$key=\.\*\|\$key=\$\((.*?)\)\|" \.env\ndone`)
-)
-
-var helmPages = []string{docsContent + "/operator/kubernetes.mdx"}
-
-func docsPages(t *testing.T) map[string]string {
- t.Helper()
- pages := map[string]string{}
- root := filepath.Join(repoRoot, docsContent)
- err := filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error {
- if err != nil || d.IsDir() || (filepath.Ext(p) != ".md" && filepath.Ext(p) != ".mdx") {
- return err
- }
- data, err := os.ReadFile(p)
- if err != nil {
- return err
- }
- rel, _ := filepath.Rel(repoRoot, p)
- pages[filepath.ToSlash(rel)] = string(data)
- return nil
- })
- if err != nil {
- t.Fatal(err)
- }
- return pages
-}
-
-func TestDocsEnvNames(t *testing.T) {
- registry := map[string]bool{}
- for _, v := range envVars {
- registry[v.name] = true
- }
- set := stack.Embedded()
- schema, err := adminapi.ConfigSchema()
- if err != nil {
- t.Fatal(err)
- }
- prefixes := map[string]bool{}
- for _, k := range settings.Named() {
- first, _, _ := strings.Cut(k.Name, ".")
- prefixes[first] = true
- }
- for _, k := range schema {
- first, _, _ := strings.Cut(k.Key, ".")
- prefixes[first] = true
- }
- for rel, data := range docsPages(t) {
- for _, m := range docsEnvName.FindAllStringSubmatch(data, -1) {
- name := m[0]
- if m[1] != "" || slices.Contains(notEnvNames, name) {
- continue
- }
- if base, ok := strings.CutSuffix(name, "_FILE"); ok && registry[base] {
- continue
- }
- if !registry[name] {
- t.Errorf("%s mentions %s, but it has no entry in envVars", rel, name)
- }
- }
- keys := map[string]bool{}
- for _, m := range docsConfigCmd.FindAllStringSubmatch(data, -1) {
- keys[strings.TrimSuffix(m[1], ".")] = true
- }
- for _, m := range docsDottedName.FindAllStringSubmatch(data, -1) {
- first, _, _ := strings.Cut(m[1], ".")
- if slices.ContainsFunc([]string{".yml", ".yaml", ".env", ".example"}, func(ext string) bool { return strings.HasSuffix(m[1], ext) }) {
- continue
- }
- if prefixes[first] && strings.HasPrefix(rel, docsContent+"/operator/") && !slices.Contains(helmPages, rel) {
- keys[m[1]] = true
- }
- }
- for key := range keys {
- if _, err := settings.Lookup(set, nil, key, schema); err != nil {
- t.Errorf("%s mentions the setting %s, but rexctl doesn't take it: %v", rel, key, err)
- }
- }
- }
-}
-
-func TestComposePageSecrets(t *testing.T) {
- data, err := os.ReadFile(filepath.Join(repoRoot, docsContent, "operator/docker-compose.mdx"))
- if err != nil {
- t.Fatal(err)
- }
- page := string(data)
- commands := map[string]string{}
- if m := composeLoop.FindStringSubmatch(page); m != nil {
- for _, key := range strings.Fields(strings.ReplaceAll(m[1], "\\", " ")) {
- commands[key] = m[2]
- }
- } else {
- t.Error("docker-compose.mdx has no loop that fills in the hex secrets")
- }
- for _, m := range composeSecret.FindAllStringSubmatch(page, -1) {
- commands[m[1]] = m[2]
- }
- want := map[secrets.Kind]string{
- secrets.KindHex32: "openssl rand -hex 32",
- secrets.KindBase64_32: "openssl rand -base64 32",
- secrets.KindRSA: "openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:2048 -outform DER | base64",
- secrets.KindVAPID: "openssl ec -in vapid.pem",
- secrets.KindAlnum64: "openssl rand -base64 96 | tr -dc A-Za-z0-9 | head -c 64",
- }
- for _, s := range secrets.Required {
- if s.Kind == secrets.KindFixed {
- continue
- }
- cmd, ok := commands[s.Key]
- switch {
- case !ok:
- t.Errorf("docker-compose.mdx doesn't fill in %s", s.Key)
- case !strings.Contains(cmd, want[s.Kind]):
- t.Errorf("docker-compose.mdx fills in %s with %q, but it needs %q", s.Key, cmd, want[s.Kind])
- }
- delete(commands, s.Key)
- }
- if cmd := commands[SetupTokenVar]; !strings.Contains(envVars[slices.IndexFunc(envVars, func(v envVar) bool { return v.name == SetupTokenVar })].help, cmd) {
- t.Errorf("docker-compose.mdx fills in %s with %q, but its entry in envVars suggests another command", SetupTokenVar, cmd)
- }
- delete(commands, SetupTokenVar)
- for key := range commands {
- t.Errorf("docker-compose.mdx fills in %s, but it isn't a generated secret", key)
- }
-}
-
-var (
- docsLink = regexp.MustCompile(`\]\((/[a-z0-9/_-]*?)/?#([a-z0-9_-]+)\)`)
- docsHeading = regexp.MustCompile(`(?m)^#{1,6} (.+)$`)
- slugDrop = regexp.MustCompile(`[^a-z0-9 _-]`)
-)
-
-func docsSlug(heading string) string {
- return strings.ReplaceAll(slugDrop.ReplaceAllString(strings.ToLower(heading), ""), " ", "-")
-}
-
-func TestDocsAnchors(t *testing.T) {
- pages := docsPages(t)
- for _, name := range slices.Sorted(maps.Keys(pages)) {
- if !strings.HasPrefix(name, docsContent+"/operator/") {
- continue
- }
- for _, m := range docsLink.FindAllStringSubmatch(pages[name], -1) {
- base := docsContent + m[1]
- target, ok := "", false
- for _, c := range []string{base + ".mdx", base + ".md", base + "/index.mdx", base + "/index.md"} {
- if _, found := pages[c]; found {
- target, ok = c, true
- break
- }
- }
- if !ok {
- t.Errorf("%s links to %s, but there is no such page", name, m[1])
- continue
- }
- if !slices.ContainsFunc(docsHeading.FindAllStringSubmatch(pages[target], -1), func(h []string) bool { return docsSlug(h[1]) == m[2] }) {
- t.Errorf("%s links to %s#%s, but %s has no heading with that anchor", name, m[1], m[2], target)
- }
- }
- }
-}
diff --git a/fluxer_rexctl/internal/instance/envinventory_test.go b/fluxer_rexctl/internal/instance/envinventory_test.go
deleted file mode 100644
index 6beb56d00..000000000
--- a/fluxer_rexctl/internal/instance/envinventory_test.go
+++ /dev/null
@@ -1,1921 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-package instance
-
-import (
- "encoding/json"
- "fmt"
- "io/fs"
- "maps"
- "os"
- "path"
- "path/filepath"
- "regexp"
- "slices"
- "strconv"
- "strings"
- "testing"
- "unicode/utf8"
-
- "go.yaml.in/yaml/v4"
-
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/secrets"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/settings"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/stack"
-)
-
-const repoRoot = "../../.."
-
-var codeRoots = []string{
- "fluxer_api/src", "fluxer_api/pkgs", "fluxer_api/bin", "packages",
- "fluxer_gateway/src", "fluxer_gateway/include", "fluxer_gateway/native", "fluxer_gateway/config", "fluxer_gateway/scripts",
- "fluxer_media_proxy/src", "fluxer_push/src", "fluxer_app_proxy/src", "fluxer_admin/src",
- "fluxer_common/src", "fluxer_svc/src", "fluxer_gifs/src", "fluxer_messages/src",
- "fluxer_snowflakes/src", "fluxer_users/src", "fluxer_unfurl/src", "fluxer_docs/src/server", "fluxer_docs/src/pages",
- "fluxer_docs/src/installer", "fluxer_docs/scripts",
- "fluxer_static",
-}
-
-var devScripts = "packages/config/scripts/"
-
-var caddyfiles = map[string]string{"fluxer_static/Caddyfile": "static-proxy"}
-
-var dockerOSVars = []string{"HOME", "PATH", "XDG_CONFIG_HOME", "XDG_DATA_HOME"}
-
-var libraryEnvVars = []string{"ALL_PROXY", "NODE_TLS_REJECT_UNAUTHORIZED", "PGSSLMODE", "SSL_CERT_DIR", "SSL_CERT_FILE"}
-
-var libraryEnvAnchors = map[string][][2]string{
- "ALL_PROXY": {{"fluxer_push/Cargo.toml", `reqwest = [^\n]*"rustls"`}},
- "NODE_TLS_REJECT_UNAUTHORIZED": {{"fluxer_api/Dockerfile", `(?m)^CMD \["node"`}},
- "PGSSLMODE": {{"fluxer_api/pkgs/postgres/src/Client.ts", `\bssl: this\.config\.ssl \?[^\n]*: undefined,`}},
- "SSL_CERT_DIR": {{"fluxer_svc/src/postgres.rs", `MakeRustlsConnect::with_native_certs\(\)`}, {"fluxer_push/Cargo.toml", `reqwest = [^\n]*"rustls"`}},
- "SSL_CERT_FILE": {{"fluxer_svc/src/postgres.rs", `MakeRustlsConnect::with_native_certs\(\)`}, {"fluxer_push/Cargo.toml", `reqwest = [^\n]*"rustls"`}},
-}
-
-var noProxyFiles = []string{"fluxer_common/src/healthcheck.rs"}
-
-var chartInputVars = []string{"FLUXER_VALKEY_PASSWORD"}
-
-var codeServices = map[string][]string{
- "fluxer_api/": {"api", "worker"},
- "packages/": {"api", "worker"},
- "fluxer_gateway/": {"gateway"},
- "fluxer_media_proxy/": {"media-proxy"},
- "fluxer_push/": {"push"},
- "fluxer_app_proxy/": {"app-proxy"},
- "fluxer_admin/": {"admin"},
- "fluxer_common/": {"admin", "app-proxy", "gifs", "media-proxy", "messages", "push", "snowflakes", "unfurl", "users"},
- "fluxer_svc/": {"gifs", "messages", "push", "snowflakes", "unfurl", "users"},
- "fluxer_gifs/": {"gifs"},
- "fluxer_messages/": {"messages"},
- "fluxer_snowflakes/": {"snowflakes"},
- "fluxer_users/": {"users"},
- "fluxer_unfurl/": {"unfurl"},
- "fluxer_static/": {"static-proxy"},
-}
-
-const helmChart = "deploy/helm/fluxer"
-
-var rexctlRoots = []string{"fluxer_rexctl", "fluxer_docs/src/installer"}
-
-var rexctlOSVars = []string{
- "HOME", "LOCALAPPDATA", "OS", "PATH", "PROCESSOR_ARCHITECTURE", "PROCESSOR_ARCHITEW6432", "PWD", "Path",
- "ProgramFiles", "SUDO_USER", "TERM", "USER", "USERNAME", "XDG_CONFIG_HOME", "XDG_RUNTIME_DIR",
-}
-
-var rexctlLibraryVars = []string{"DOCKER_CONFIG", "DOCKER_CONTEXT"}
-
-var rexctlProxyVars = []string{"HTTPS_PROXY", "HTTP_PROXY", "NO_PROXY"}
-
-var runtimeEnvVars = []string{"MALLOC_ARENA_MAX", "NODE_EXTRA_CA_CERTS", "NODE_OPTIONS", "TOKIO_WORKER_THREADS"}
-
-var (
- quotedEnv = regexp.MustCompile("[\"'`](FLUXER_[A-Z0-9_]*[A-Z0-9])[\"'`]")
- keyEnv = regexp.MustCompile(`(?m)^\s*(FLUXER_[A-Z0-9_]*[A-Z0-9]): \{`)
- envCall = regexp.MustCompile(`(?:\b[a-z_]*(?:env|getenv|var|from)[a-z_]*|\b[a-z]*[A-Z][A-Za-z]*Env[A-Za-z]*)\s*\(\s*(?:&?get,\s*|&?env,\s*|process\.env,\s*)?["']([A-Z][A-Z0-9_]*)["']`)
- envListCall = regexp.MustCompile(`(?:\b[a-z_]*(?:env|getenv|var|from)[a-z_]*|\b[a-z]*[A-Z][A-Za-z]*Env[A-Za-z]*)\s*\(\s*(?:&?get,\s*|&?env,\s*|process\.env,\s*)?&?\[([^\]]*)\]`)
- listName = regexp.MustCompile("[\"'`]([A-Z][A-Z0-9_]*)[\"'`]")
- processEnv = regexp.MustCompile("(?:process\\.env|Bun\\.env|import\\.meta\\.env|\\benv)(?:\\??\\.|\\??\\.?\\[[\"'`])([A-Z_][A-Z0-9_]*)")
- destructEnv = regexp.MustCompile(`\{([^{}]*)\}\s*=\s*(?:process|Bun|import\.meta)\.env\b`)
- envPrefix = regexp.MustCompile(`\b[a-z_]+_config\(\s*&?env,\s*"([A-Z][A-Z0-9_]*)"`)
- envSuffix = regexp.MustCompile(`format!\("\{prefix\}_([A-Z][A-Z0-9_]*)"\)`)
- builtEnv = regexp.MustCompile(`env::var(?:_os)?\(\s*&?(?:format|concat)!\(\s*"([A-Z][A-Z0-9_]*)`)
- mapEnv = regexp.MustCompile(`\.(?:get|require)\(\s*"([A-Z][A-Z0-9_]*)"`)
- shellEnv = regexp.MustCompile(`\$\{?([A-Z][A-Z0-9_]*)`)
- psEnv = regexp.MustCompile(`\$env:([A-Za-z_][A-Za-z0-9_]*)`)
- directEnv = regexp.MustCompile("(?:process\\.env|Bun\\.env|import\\.meta\\.env)(?:\\??\\.|\\??\\.?\\[[\"'`])([A-Z_][A-Z0-9_]*)|os:getenv\\(\"([A-Z][A-Z0-9_]*)\"|env::var(?:_os)?\\(\"([A-Z][A-Z0-9_]*)\"|\\b(?:g_|secure_)?getenv\\(\\s*\"([A-Z_][A-Z0-9_]*)\"")
- goEnv = regexp.MustCompile(`os\.(?:Getenv|LookupEnv)\(\s*"([A-Za-z_][A-Za-z0-9_]*)"|(?s)range \[\]string\{([^}]*)\}\s*\{[^}]*?os\.(?:Getenv|LookupEnv)\(|Env\s*=\s*"([A-Z][A-Z0-9_]*)"`)
- dockerEnv = regexp.MustCompile(`(?m)^ENV\s+((?:[^\n]*\\\n)*[^\n]*)`)
- envAssign = regexp.MustCompile(`\b([A-Z_][A-Z0-9_]*)=`)
- caddyEnv = regexp.MustCompile(`\{(?:\$|env\.)([A-Z][A-Z0-9_]*)`)
- composeSh = regexp.MustCompile(`\$\$\{?([A-Z][A-Z0-9_]*)`)
- constEnv = regexp.MustCompile("(?m)(?:\\bconst|\\bstatic|\\blet|\\bvar)\\s+([A-Za-z_][A-Za-z0-9_]*)\\s*(?::[^=\\n]+)?=\\s*[\"'`]([A-Z][A-Z0-9_]*)[\"'`]|-define\\(\\s*([A-Za-z_][A-Za-z0-9_]*)\\s*,\\s*\"([A-Z][A-Z0-9_]*)\"")
- identEnv = regexp.MustCompile(`(?:\b[a-z_]*(?:env|getenv|var|from)[a-z_]*|\b[a-z]*[A-Z][A-Za-z]*Env[A-Za-z]*)\s*\(\s*(?:&?get,\s*|&?env,\s*|process\.env,\s*|&\[\s*)?&?\??([A-Z][A-Z0-9_]*)\s*[,)\]]|(?:process\.env|Bun\.env|import\.meta\.env|\benv)\??\.?\[\s*([A-Z][A-Z0-9_]*)\s*\]`)
- cEnv = regexp.MustCompile(`\b(?:g_|secure_)?getenv\(\s*"([A-Z_][A-Z0-9_]*)"`)
- tsImport = regexp.MustCompile(`(?:from|import)\s*\(?\s*'([^']+)'`)
- goConst = regexp.MustCompile(`(?m)^\s*(?:const\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*(?:string\s*)?(?:=|:=)\s*"([A-Z][A-Z0-9_]*)"`)
- goIdentEnv = regexp.MustCompile(`os\.(?:Getenv|LookupEnv)\(\s*(?:[a-z][A-Za-z0-9_]*\.)?([A-Za-z_][A-Za-z0-9_]*)\s*\)`)
- goEnviron = regexp.MustCompile(`\bk == "([A-Z][A-Z0-9_]*)"|\blookup\("([A-Z][A-Z0-9_]*)"\)`)
- dockerRun = regexp.MustCompile(`(?m)^(?:HEALTHCHECK|CMD|ENTRYPOINT)\b((?:[^\n]*\\\n)*[^\n]*)`)
- tsFunc = regexp.MustCompile(`\bfunction\s+([A-Za-z_$][\w$]*)\s*(?:<[^>]*>)?\s*\(([^)]*)\)|\b(?:const|let)\s+([A-Za-z_$][\w$]*)\s*=\s*(?:async\s*)?\(([^)]*)\)[^=;]*=>`)
- rsFunc = regexp.MustCompile(`\bfn\s+([a-z_][a-z0-9_]*)\s*(?:<[^>]*>)?\s*\(([^)]*)\)`)
- erlFunc = regexp.MustCompile(`(?m)^([a-z][A-Za-z0-9_]*)\(((?:[^()\n]|\([^()\n]*\))*)\)\s*(?:when\b[^\n]*?)?->`)
- erlForm = regexp.MustCompile(`(?m)^[a-z-]`)
- erlEnvCallee = regexp.MustCompile(`^(?:getenv|env_[a-z_]+|[a-z_]+_env)$`)
- callStart = regexp.MustCompile(`\b([A-Za-z_$][\w$]*)\s*\(`)
- quotedName = regexp.MustCompile("^[\"'`]([A-Z][A-Z0-9_]*)[\"'`]$")
- identName = regexp.MustCompile(`^&?([A-Z][A-Z0-9_]*)$`)
- paramEnv = regexp.MustCompile(`(?:process\.env|Bun\.env|import\.meta\.env|\benv)\??\.?\[\s*([a-z_$][\w$]*)\s*\]|env::var(?:_os)?\(\s*&?([a-z_][a-z0-9_]*)\s*\)|\b(?:env|vars)\.get\(\s*&?([a-z_][a-z0-9_]*)\b`)
- envCallee = regexp.MustCompile(`^(?:[a-z_]*(?:env|getenv|var|from)[a-z_]*|[a-z]*[A-Z][A-Za-z]*Env[A-Za-z]*)$`)
- localEnv = regexp.MustCompile(`(?:\b[a-z_]*(?:env|getenv|var|from)[a-z_]*|\b[a-z]*[A-Z][A-Za-z]*Env[A-Za-z]*)\s*\(\s*(?:&?get,\s*|&?env,\s*|process\.env,\s*)?&?\??([A-Za-z_][A-Za-z0-9_]*)\s*[,)]|(?:process\.env|Bun\.env|import\.meta\.env|\benv)\??\.?\[\s*([A-Za-z_$][\w$]*)\s*\]`)
- erlBind = regexp.MustCompile(`\b([A-Z][A-Za-z0-9_]*)\s*=\s*"([A-Z][A-Z0-9_]*)"`)
- rustForList = regexp.MustCompile(`\bfor\s+([a-z_][a-z0-9_]*)\s+in\s+&?\[([^\]]*)\]\s*\{`)
- fieldRead = regexp.MustCompile(`\|\(\s*_\s*,\s*([a-z_][a-z0-9_]*)\s*\)\|\s*([a-z_][a-z0-9_]*)\(\s*&?([a-z_][a-z0-9_]*)\s*\)`)
- fieldPair = regexp.MustCompile(`\(\s*"[a-z_]+"\s*,\s*"([A-Z][A-Z0-9_]*)"\s*\)`)
-)
-
-var notEnvNames = []string{"FLUXER_MESSAGE", "FLUXER_CACHE_PURGE_HTTP", "FLUXER_CACHE_PURGE_CONTROLLER"}
-
-func testPath(p string) bool {
- for _, part := range strings.Split(filepath.ToSlash(p), "/") {
- switch part {
- case "test", "tests", "__tests__", "fuzz", "node_modules", "target", "dist":
- return true
- }
- }
- base := filepath.Base(p)
- return strings.Contains(base, ".test.") || strings.HasSuffix(base, "_test.rs") || strings.HasSuffix(base, "_tests.rs") ||
- base == "tests.rs" || base == "test_fixtures.rs" || strings.HasPrefix(base, "test_") || strings.HasSuffix(base, "_SUITE.erl")
-}
-
-func scriptLang(p string) string {
- switch filepath.Ext(p) {
- case ".ts", ".mts", ".tsx", ".mjs", ".js", ".cjs", ".astro":
- return "ts"
- case ".rs", ".erl", ".hrl":
- return "native"
- case ".c", ".h":
- return "c"
- case ".sh", ".src", ".template":
- return "shell"
- case ".ps1":
- return "ps"
- case ".go":
- if !strings.HasSuffix(p, "_test.go") {
- return "go"
- }
- }
- return ""
-}
-
-func addFound(found map[string][]string, name, rel string) {
- if name != "" && !slices.Contains(notEnvNames, name) && !slices.Contains(found[name], rel) {
- found[name] = append(found[name], rel)
- }
-}
-
-type codeFile struct {
- rel, lang, data string
- test bool
-}
-
-func walkCode(t *testing.T, roots []string, fn func(rel, lang, data string)) {
- t.Helper()
- var files []codeFile
- byRel := map[string]bool{}
- for _, root := range roots {
- dir := filepath.Join(repoRoot, root)
- err := filepath.WalkDir(dir, func(p string, d fs.DirEntry, err error) error {
- if err != nil {
- return err
- }
- if d.IsDir() {
- if base := d.Name(); base == "node_modules" || base == "target" || base == "dist" {
- return filepath.SkipDir
- }
- return nil
- }
- lang := scriptLang(p)
- if lang == "" {
- return nil
- }
- data, err := os.ReadFile(p)
- if err != nil {
- return err
- }
- inner, _ := filepath.Rel(dir, p)
- rel, _ := filepath.Rel(repoRoot, p)
- rel = filepath.ToSlash(rel)
- text := string(data)
- if filepath.Ext(p) == ".rs" {
- text = stripRustTests(text)
- }
- files = append(files, codeFile{rel: rel, lang: lang, data: text, test: testPath(inner)})
- byRel[rel] = true
- return nil
- })
- if err != nil {
- t.Fatal(err)
- }
- }
- imported := map[string]bool{}
- for _, f := range files {
- if f.test || f.lang != "ts" {
- continue
- }
- for _, m := range tsImport.FindAllStringSubmatch(f.data, -1) {
- if rel := resolveImport(f.rel, m[1], byRel); rel != "" {
- imported[rel] = true
- }
- }
- }
- for _, f := range files {
- if !f.test || imported[f.rel] {
- fn(f.rel, f.lang, f.data)
- }
- }
-}
-
-func resolveImport(from, spec string, files map[string]bool) string {
- var base string
- switch {
- case strings.HasPrefix(spec, "@app/"):
- base = "fluxer_api/src/" + strings.TrimPrefix(spec, "@app/")
- case strings.HasPrefix(spec, "@fluxer/"):
- pkg, rest, _ := strings.Cut(strings.TrimPrefix(spec, "@fluxer/"), "/")
- base = "packages/" + pkg + "/" + rest
- if _, err := os.Stat(filepath.Join(repoRoot, "packages", pkg)); err != nil {
- base = "fluxer_api/pkgs/" + pkg + "/" + rest
- }
- case strings.HasPrefix(spec, "."):
- base = path.Join(path.Dir(from), spec)
- default:
- return ""
- }
- base = strings.TrimSuffix(base, ".js")
- for _, c := range []string{base, base + ".ts", base + ".tsx", base + "/index.ts"} {
- if files[c] {
- return c
- }
- }
- return ""
-}
-
-func codeEnvNames(t *testing.T) (reads, mentions map[string][]string) {
- t.Helper()
- var files []codeFile
- walkCode(t, codeRoots, func(rel, lang, data string) {
- files = append(files, codeFile{rel: rel, lang: lang, data: data})
- })
- return scanEnvNames(files)
-}
-
-func runtimeReads(code map[string][]string) map[string][]string {
- out := map[string][]string{}
- for name, rels := range code {
- for _, rel := range rels {
- if !strings.HasPrefix(rel, devScripts) {
- out[name] = append(out[name], rel)
- }
- }
- }
- return out
-}
-
-func addListNames(found map[string][]string, list, rel string) {
- for _, m := range listName.FindAllStringSubmatch(list, -1) {
- addFound(found, m[1], rel)
- }
-}
-
-func scanEnvNames(files []codeFile) (reads, mentions map[string][]string) {
- found := map[string][]string{}
- mentions = map[string][]string{}
- consts := map[string][]string{}
- type pending struct{ rel, ident string }
- var idents []pending
- sources := map[string]string{}
- for _, f := range files {
- rel, lang, data := f.rel, f.lang, f.data
- if lang == "ts" || lang == "native" {
- sources[rel] = data
- for _, m := range envListCall.FindAllStringSubmatch(data, -1) {
- addListNames(found, m[1], rel)
- }
- }
- if (lang == "shell" || lang == "ps") && slices.ContainsFunc(rexctlRoots, func(root string) bool { return strings.HasPrefix(rel, root+"/") }) {
- continue
- }
- if lang == "ts" || lang == "native" {
- local := map[string][]string{}
- for _, m := range constEnv.FindAllStringSubmatch(data, -1) {
- ident, value := m[1]+m[3], m[2]+m[4]
- local[ident] = append(local[ident], value)
- consts[ident] = append(consts[ident], value)
- }
- if erlangFile(rel) {
- for _, m := range erlBind.FindAllStringSubmatch(data, -1) {
- local[m[1]] = append(local[m[1]], m[2])
- }
- }
- for _, m := range localEnv.FindAllStringSubmatch(data, -1) {
- for _, v := range local[m[1]+m[2]] {
- addFound(found, v, rel)
- }
- }
- for _, loc := range rustForList.FindAllStringSubmatchIndex(data, -1) {
- ident, open := data[loc[2]:loc[3]], loc[1]-1
- for _, m := range localEnv.FindAllStringSubmatch(data[open:rustBlockEnd(data, open)], -1) {
- if m[1]+m[2] == ident {
- addListNames(found, data[loc[4]:loc[5]], rel)
- }
- }
- }
- for _, m := range fieldRead.FindAllStringSubmatch(data, -1) {
- if m[1] == m[3] && envCallee.MatchString(m[2]) {
- for _, p := range fieldPair.FindAllStringSubmatch(data, -1) {
- addFound(found, p[1], rel)
- }
- }
- }
- for _, m := range identEnv.FindAllStringSubmatch(data, -1) {
- ident := m[1] + m[2]
- if values, ok := local[ident]; ok {
- for _, v := range values {
- addFound(found, v, rel)
- }
- } else {
- idents = append(idents, pending{rel, ident})
- }
- }
- }
- var patterns, named []*regexp.Regexp
- prefixes := map[string]bool{}
- switch lang {
- case "ts":
- patterns, named = []*regexp.Regexp{envCall, processEnv}, []*regexp.Regexp{quotedEnv, keyEnv}
- if rel == configOverrides {
- patterns = append(patterns, keyEnv)
- if block := namedAliases.FindStringSubmatch(data); block != nil {
- for _, m := range aliasPair.FindAllStringSubmatch(block[1], -1) {
- addFound(found, m[2], rel)
- }
- }
- }
- for _, m := range destructEnv.FindAllStringSubmatch(data, -1) {
- for _, field := range strings.Split(m[1], ",") {
- name, _, _ := strings.Cut(strings.TrimSpace(field), ":")
- name, _, _ = strings.Cut(name, "=")
- addFound(found, strings.TrimSpace(name), rel)
- }
- }
- case "native":
- patterns, named = []*regexp.Regexp{envCall, mapEnv, builtEnv}, []*regexp.Regexp{quotedEnv}
- for _, m := range envPrefix.FindAllStringSubmatch(data, -1) {
- prefixes[m[1]] = true
- for _, s := range envSuffix.FindAllStringSubmatch(data, -1) {
- addFound(found, m[1]+"_"+s[1], rel)
- }
- }
- case "c":
- patterns = []*regexp.Regexp{cEnv}
- case "shell":
- patterns = []*regexp.Regexp{shellEnv}
- case "ps":
- patterns = []*regexp.Regexp{psEnv}
- }
- for _, re := range patterns {
- for _, m := range re.FindAllStringSubmatch(data, -1) {
- if !prefixes[m[1]] {
- addFound(found, m[1], rel)
- }
- }
- }
- for _, re := range named {
- for _, m := range re.FindAllStringSubmatch(data, -1) {
- if !prefixes[m[1]] {
- addFound(mentions, m[1], rel)
- }
- }
- }
- }
- helpers := envHelpers(sources)
- for rel, data := range sources {
- for _, h := range helpers {
- if h.erl != erlangFile(rel) || !strings.Contains(data, h.name) {
- continue
- }
- for _, c := range regexp.MustCompile(`\b`+regexp.QuoteMeta(h.name)+`\s*\(`).FindAllStringIndex(data, -1) {
- args := splitArgs(data, c[1]-1)
- if h.arg >= len(args) {
- continue
- }
- arg := args[h.arg]
- if strings.HasPrefix(strings.TrimPrefix(arg, "&"), "[") {
- addListNames(found, arg, rel)
- } else if m := quotedName.FindStringSubmatch(arg); m != nil {
- addFound(found, m[1], rel)
- } else if m := identName.FindStringSubmatch(arg); m != nil {
- idents = append(idents, pending{rel, m[1]})
- }
- }
- }
- }
- for _, p := range idents {
- for _, v := range consts[p.ident] {
- addFound(found, v, p.rel)
- }
- }
- for name, rels := range found {
- for _, rel := range rels {
- addFound(mentions, name, rel)
- }
- }
- return found, mentions
-}
-
-type envHelper struct {
- name string
- arg int
- erl bool
-}
-
-func erlangFile(rel string) bool {
- ext := filepath.Ext(rel)
- return ext == ".erl" || ext == ".hrl"
-}
-
-func splitArgs(data string, open int) []string {
- var args []string
- depth, start := 0, open+1
- var quote byte
- for i := open; i < len(data); i++ {
- c := data[i]
- switch {
- case quote != 0:
- if c == '\\' {
- i++
- } else if c == quote {
- quote = 0
- }
- case c == '"' || c == '\'' || c == '`':
- quote = c
- case c == '(' || c == '[' || c == '{':
- depth++
- case c == ')' || c == ']' || c == '}':
- depth--
- if depth == 0 {
- return append(args, strings.TrimSpace(data[start:i]))
- }
- case c == ',' && depth == 1:
- args = append(args, strings.TrimSpace(data[start:i]))
- start = i + 1
- }
- }
- return args
-}
-
-func funcBody(data string, from int) string {
- end := min(len(data), from+4000)
- i := strings.IndexAny(data[from:end], "{\n")
- if i < 0 {
- return data[from:end]
- }
- if data[from+i] == '\n' {
- return data[from : from+i]
- }
- depth := 0
- for j := from + i; j < end; j++ {
- switch data[j] {
- case '{':
- depth++
- case '}':
- depth--
- if depth == 0 {
- return data[from : j+1]
- }
- }
- }
- return data[from:end]
-}
-
-func splitParams(params string) []string {
- var out []string
- depth, start := 0, 0
- for i, c := range params {
- switch c {
- case '<', '(', '[', '{':
- depth++
- case '>', ')', ']', '}':
- depth--
- case ',':
- if depth == 0 {
- out = append(out, params[start:i])
- start = i + 1
- }
- }
- }
- return append(out, params[start:])
-}
-
-func paramName(p string) string {
- p = strings.TrimSpace(p)
- p = strings.TrimPrefix(strings.TrimPrefix(p, "mut "), "...")
- if i := strings.IndexAny(p, ":=?"); i >= 0 {
- p = p[:i]
- }
- return strings.TrimSpace(p)
-}
-
-func erlParam(p string) string {
- p = strings.TrimPrefix(strings.TrimSpace(p), "[")
- p, _, _ = strings.Cut(p, "|")
- return strings.TrimSpace(p)
-}
-
-func stripRustTests(data string) string {
- const attr = "#[cfg(test)]"
- var b strings.Builder
- for {
- i := strings.Index(data, attr)
- if i < 0 {
- b.WriteString(data)
- return b.String()
- }
- b.WriteString(data[:i])
- data = data[rustItemEnd(data, i+len(attr)):]
- }
-}
-
-func rustSkip(data string, i int) int {
- switch {
- case strings.HasPrefix(data[i:], "//"):
- if j := strings.IndexByte(data[i:], '\n'); j >= 0 {
- return i + j
- }
- return len(data)
- case strings.HasPrefix(data[i:], "/*"):
- if j := strings.Index(data[i+2:], "*/"); j >= 0 {
- return i + 2 + j + 1
- }
- return len(data)
- case data[i] == 'r' && (strings.HasPrefix(data[i+1:], "\"") || strings.HasPrefix(data[i+1:], "#")) && (i == 0 || !isIdent(data[i-1])):
- hashes := 0
- for i+1+hashes < len(data) && data[i+1+hashes] == '#' {
- hashes++
- }
- if i+1+hashes >= len(data) || data[i+1+hashes] != '"' {
- return i
- }
- if j := strings.Index(data[i+2+hashes:], "\""+strings.Repeat("#", hashes)); j >= 0 {
- return i + 2 + hashes + j + hashes
- }
- return len(data)
- case data[i] == '"':
- for j := i + 1; j < len(data); j++ {
- switch data[j] {
- case '\\':
- j++
- case '"':
- return j
- }
- }
- return len(data)
- case data[i] == '\'':
- if i+1 < len(data) && data[i+1] == '\\' {
- if j := strings.IndexByte(data[i+2:], '\''); j >= 0 {
- return i + 2 + j
- }
- }
- _, size := utf8.DecodeRuneInString(data[i+1:])
- if i+1+size < len(data) && data[i+1+size] == '\'' {
- return i + 1 + size
- }
- }
- return i
-}
-
-func isIdent(c byte) bool {
- return c == '_' || c >= '0' && c <= '9' || c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z'
-}
-
-func rustItemEnd(data string, from int) int {
- depth, angle := 0, 0
- for i := from; i < len(data); i++ {
- if j := rustSkip(data, i); j != i {
- i = j
- continue
- }
- switch c := data[i]; {
- case (c == '-' || c == '=') && i+1 < len(data) && data[i+1] == '>':
- i++
- case c == '(' || c == '[':
- depth++
- case c == ')' || c == ']':
- depth--
- case c == '<' && depth == 0:
- angle++
- case c == '>' && depth == 0 && angle > 0:
- angle--
- case c == '{' && depth == 0 && angle == 0:
- return rustBlockEnd(data, i)
- case c == '{':
- depth++
- case c == '}' && depth == 0:
- return i
- case c == '}':
- depth--
- case (c == ';' || c == ',') && depth == 0 && angle == 0:
- return i + 1
- }
- }
- return len(data)
-}
-
-func rustBlockEnd(data string, open int) int {
- depth := 0
- for i := open; i < len(data); i++ {
- if j := rustSkip(data, i); j != i {
- i = j
- continue
- }
- switch data[i] {
- case '{':
- depth++
- case '}':
- depth--
- if depth == 0 {
- return i + 1
- }
- }
- }
- return len(data)
-}
-
-func envHelpers(files map[string]string) []envHelper {
- type fn struct {
- name string
- params []string
- body string
- }
- var fns, erlFns []fn
- for rel, data := range files {
- if erlangFile(rel) {
- for _, m := range erlFunc.FindAllStringSubmatchIndex(data, -1) {
- var names []string
- for _, p := range splitParams(data[m[4]:m[5]]) {
- names = append(names, erlParam(p))
- }
- end := len(data)
- if next := erlForm.FindStringIndex(data[m[1]:]); next != nil {
- end = m[1] + next[0]
- }
- erlFns = append(erlFns, fn{data[m[2]:m[3]], names, data[m[1]:end]})
- }
- continue
- }
- re := tsFunc
- if scriptLang(rel) == "native" {
- re = rsFunc
- }
- for _, m := range re.FindAllStringSubmatchIndex(data, -1) {
- name, params := "", ""
- if m[2] >= 0 {
- name, params = data[m[2]:m[3]], data[m[4]:m[5]]
- }
- if len(m) > 6 && m[6] >= 0 {
- name, params = data[m[6]:m[7]], data[m[8]:m[9]]
- }
- var names []string
- for _, p := range splitParams(params) {
- names = append(names, paramName(p))
- }
- fns = append(fns, fn{name, names, funcBody(data, m[1])})
- }
- }
- known := map[string]bool{}
- var out []envHelper
- add := func(f fn, i int) bool {
- key := f.name + "/" + strconv.Itoa(i)
- if known[key] || envCallee.MatchString(f.name) {
- return false
- }
- known[key] = true
- out = append(out, envHelper{name: f.name, arg: i})
- return true
- }
- for _, f := range fns {
- if !strings.Contains(f.body, "env") && !strings.Contains(f.body, "vars") {
- continue
- }
- for _, m := range paramEnv.FindAllStringSubmatch(f.body, -1) {
- if i := slices.Index(f.params, m[1]+m[2]+m[3]); i >= 0 {
- add(f, i)
- }
- }
- }
- for changed := len(out) > 0; changed; {
- changed = false
- for _, f := range fns {
- for _, c := range callStart.FindAllStringSubmatchIndex(f.body, -1) {
- callee := f.body[c[2]:c[3]]
- if callee == f.name || !envCallee.MatchString(callee) && !slices.ContainsFunc(out, func(h envHelper) bool { return h.name == callee }) {
- continue
- }
- for j, arg := range splitArgs(f.body, c[1]-1) {
- i := slices.Index(f.params, strings.TrimPrefix(arg, "&"))
- if i >= 0 && (envCallee.MatchString(callee) || known[callee+"/"+strconv.Itoa(j)]) && add(f, i) {
- changed = true
- }
- }
- }
- }
- }
- for changed := true; changed; {
- changed = false
- for _, f := range erlFns {
- for _, c := range callStart.FindAllStringSubmatchIndex(f.body, -1) {
- callee := f.body[c[2]:c[3]]
- for j, arg := range splitArgs(f.body, c[1]-1) {
- i := slices.Index(f.params, arg)
- key := f.name + "/" + strconv.Itoa(i)
- if i < 0 || callee == f.name || known[key] || envCallee.MatchString(f.name) ||
- !erlEnvCallee.MatchString(callee) && !known[callee+"/"+strconv.Itoa(j)] {
- continue
- }
- known[key] = true
- out = append(out, envHelper{name: f.name, arg: i, erl: true})
- changed = true
- }
- }
- }
- }
- return out
-}
-
-func dockerfileEnvNames(t *testing.T) map[string][]string {
- t.Helper()
- files, err := filepath.Glob(filepath.Join(repoRoot, "fluxer_*", "Dockerfile"))
- if err != nil {
- t.Fatal(err)
- }
- found := map[string][]string{}
- for _, p := range files {
- data, err := os.ReadFile(p)
- if err != nil {
- t.Fatal(err)
- }
- rel, _ := filepath.Rel(repoRoot, p)
- final := string(data)
- if i := strings.LastIndex(final, "\nFROM "); i >= 0 {
- final = final[i:]
- }
- for _, m := range dockerEnv.FindAllStringSubmatch(final, -1) {
- for _, a := range envAssign.FindAllStringSubmatch(m[1], -1) {
- addFound(found, a[1], filepath.ToSlash(rel))
- }
- }
- for _, m := range dockerRun.FindAllStringSubmatch(final, -1) {
- for _, a := range shellEnv.FindAllStringSubmatch(m[1], -1) {
- addFound(found, a[1], filepath.ToSlash(rel))
- }
- }
- }
- return found
-}
-
-type composeService struct {
- Image string `yaml:"image"`
- Environment map[string]any `yaml:"environment"`
-}
-
-func composeEnv(t *testing.T, set *stack.Set) (fluxer, other map[string][]string, feeds map[[2]string][]string) {
- t.Helper()
- fluxer, other, feeds = map[string][]string{}, map[string][]string{}, map[[2]string][]string{}
- names, err := stack.ComposeFileNames(set.Files)
- if err != nil {
- t.Fatal(err)
- }
- images := map[string]string{}
- files := map[string]map[string]composeService{}
- for _, name := range names {
- data, err := fs.ReadFile(set.Files, name)
- if err != nil {
- t.Fatal(err)
- }
- var file struct {
- Services map[string]composeService `yaml:"services"`
- }
- if err := yaml.Unmarshal(data, &file); err != nil {
- t.Fatalf("%s: %v", name, err)
- }
- files[name] = file.Services
- for svc, body := range file.Services {
- if body.Image != "" {
- images[svc] = body.Image
- }
- }
- }
- for _, services := range files {
- for svc, body := range services {
- to := other
- if strings.Contains(images[svc], "/fluxer-") {
- to = fluxer
- }
- for k, value := range body.Environment {
- if !slices.Contains(to[k], svc) {
- to[k] = append(to[k], svc)
- }
- for _, m := range composeRef.FindAllStringSubmatch(fmt.Sprint(value), -1) {
- if from := [2]string{m[1], svc}; m[1] != k && !slices.Contains(feeds[from], k) {
- feeds[from] = append(feeds[from], k)
- }
- }
- }
- }
- }
- return fluxer, other, feeds
-}
-
-var composeRef = regexp.MustCompile(`\$\{([A-Z][A-Z0-9_]*)`)
-
-type composeScripts struct {
- Command any `yaml:"command"`
- Entrypoint any `yaml:"entrypoint"`
- Healthcheck struct {
- Test any `yaml:"test"`
- } `yaml:"healthcheck"`
-}
-
-func composeOwnEnv(t *testing.T, set *stack.Set) (own map[string][]string, scripts map[string][]string) {
- t.Helper()
- own, scripts = map[string][]string{}, map[string][]string{}
- names, err := stack.ComposeFileNames(set.Files)
- if err != nil {
- t.Fatal(err)
- }
- for _, name := range names {
- data, err := fs.ReadFile(set.Files, name)
- if err != nil {
- t.Fatal(err)
- }
- var file struct {
- Services map[string]yaml.Node `yaml:"services"`
- }
- if err := yaml.Unmarshal(data, &file); err != nil {
- t.Fatalf("%s: %v", name, err)
- }
- for svc, node := range file.Services {
- var body composeScripts
- if err := node.Decode(&body); err != nil {
- t.Fatalf("%s: %s: %v", name, svc, err)
- }
- for _, part := range []any{body.Command, body.Entrypoint, body.Healthcheck.Test} {
- if part != nil {
- scripts[svc] = append(scripts[svc], fmt.Sprint(part))
- }
- }
- for i := 0; i+1 < len(node.Content); i += 2 {
- if node.Content[i].Value != "environment" || node.Content[i+1].Kind != yaml.MappingNode {
- continue
- }
- env := node.Content[i+1].Content
- for j := 0; j+1 < len(env); j += 2 {
- if k := env[j].Value; k != "<<" && !slices.Contains(own[k], svc) {
- own[k] = append(own[k], svc)
- }
- }
- }
- }
- }
- return own, scripts
-}
-
-var (
- emptyClause = regexp.MustCompile(`\b(?:it's|both are|[Aa]n) empty\b`)
- suchAs = regexp.MustCompile("such as [^,.]*")
- backticked = regexp.MustCompile("`([^`]+)`")
- anyEmpty = regexp.MustCompile(`(?:^|[^-\w])empty\b`)
- otherEmpty = regexp.MustCompile("(?:\\b[A-Z][A-Z0-9_]+`?|\\bthat) is empty\\b")
- overridePath = regexp.MustCompile(`(?m)^\s*(FLUXER_[A-Z0-9_]*[A-Z0-9]): \{path: \[([^\]]*)\]`)
- defaultLine = regexp.MustCompile(`^(\t*)(\w+): (.*?),?$`)
- rustRead = regexp.MustCompile(`"([A-Z][A-Z0-9_]*[A-Z0-9])"`)
- rustFallback = regexp.MustCompile(`\.unwrap_or(?:_else)?\((?:\|\|\s*)?("[^"]*"|-?[\d_.]+|true|false|[A-Z][A-Z0-9_]*)[),.]`)
- rustArgument = regexp.MustCompile(`^\)\s*,\s*("[^"]*"|-?[\d_.]+|true|false|[A-Z][A-Z0-9_]*)\s*,`)
- rustConst = regexp.MustCompile(`(?m)^\s*(?:pub(?:\([a-z]+\))? )?const ([A-Z][A-Z0-9_]*): [^=]+= ([^;]+);`)
- codeRange = regexp.MustCompile(`\bfrom (\d+(?:\.\d+)?(?: [KMG]iB)?) to (\d+(?:\.\d+)?(?: [KMG]iB)?)\b`)
- codeBound = regexp.MustCompile("\\b(?:at least|at most|capped at) `(\\d+)`|\\bValues (?:under|over) (\\d+)(?: [a-z]+)? count as (\\d+)\\b")
- digitGroups = regexp.MustCompile(`(\d)_(\d)`)
- products = regexp.MustCompile(`\b\d+(?:\s*\*\s*\d+)+\b`)
-)
-
-var configOverrides = "packages/config/src/config_loader/EnvironmentOverrides.ts"
-
-var configDefaults = []string{"packages/config/src/ConfigLoader.ts", "packages/config/src/EndpointDerivation.ts"}
-
-var envDefaultFiles = map[string][]string{
- "FLUXER_GATEWAY_ZSTD_WINDOW_LOG": {"fluxer_gateway/src/gateway/gateway_compress.erl"},
- "FLUXER_MEDIA_PROXY_MAX_ENCODE_FRAMES": {"fluxer_media_proxy/src/constants.rs"},
- "DISCOVERY_REFRESH_INTERVAL_MS": {"fluxer_app_proxy/src/branding_images.rs"},
- "FLUXER_EMAIL_SMTP_PORT": {"fluxer_api/src/api/instance/EmailDelivery.ts"},
- "FLUXER_GATEWAY_ENDPOINT": {"packages/config/src/EndpointDerivation.ts"},
- "FLUXER_CLAMAV_HOST": {"packages/config/src/ConfigLoader.ts"},
- "FLUXER_CLAMAV_PORT": {"packages/config/src/ConfigLoader.ts"},
- "FLUXER_MEDIA_PROXY_UPLOAD_RELAY_TOKEN_TTL_SECS": {"packages/config/src/ConfigLoader.ts"},
- "FLUXER_CACHE_PURGE_HTTP_TIMEOUT_MS": {"packages/config/src/ConfigLoader.ts"},
- "FLUXER_CACHE_PURGE_CONTROLLER_TIMEOUT_MS": {"packages/config/src/ConfigLoader.ts"},
- "FLUXER_DISCOVERY_MIN_MEMBER_COUNT": {"packages/config/src/ConfigLoader.ts"},
- "FLUXER_DELETION_GRACE_PERIOD_HOURS": {"packages/config/src/ConfigLoader.ts"},
- "FLUXER_S3_READ_BUCKET_STYLE": {"fluxer_media_proxy/src/config/parse.rs"},
- "FLUXER_GATEWAY_API_RPC_ENDPOINT": {"fluxer_gateway/src/gateway/rpc_client.erl"},
- "RUST_LOG": {"fluxer_admin/src/main.rs", "fluxer_app_proxy/src/main.rs", "fluxer_media_proxy/src/main.rs", "fluxer_svc/src/lib.rs"},
-}
-
-var (
- namedAliases = regexp.MustCompile(`(?s)NAMED_FLUXER_ENV_ALIASES\b[^=]*=\s*\{(.*?)\n\}`)
- aliasPair = regexp.MustCompile(`\b(FLUXER_[A-Z0-9_]*[A-Z0-9])\s*:\s*'(FLUXER_[A-Z0-9_]*[A-Z0-9])'`)
-)
-
-func configAliases(t *testing.T, overrides string) map[string]string {
- t.Helper()
- block := namedAliases.FindStringSubmatch(overrides)
- if block == nil {
- t.Fatalf("%s has no NAMED_FLUXER_ENV_ALIASES", configOverrides)
- }
- out := map[string]string{}
- for _, m := range aliasPair.FindAllStringSubmatch(block[1], -1) {
- out[m[2]] = m[1]
- }
- if len(out) == 0 {
- t.Fatalf("NAMED_FLUXER_ENV_ALIASES in %s has no entries", configOverrides)
- }
- return out
-}
-
-func helpSentences(help string) []string {
- var sentences []string
- start, quoted := 0, false
- for i, r := range help {
- switch {
- case r == '`':
- quoted = !quoted
- case r == '.' && !quoted && (i+1 == len(help) || help[i+1] == ' '):
- sentences = append(sentences, help[start:i])
- start = i + 1
- }
- }
- return append(sentences, help[start:])
-}
-
-func emptyDefaults(help string) []string {
- var out []string
- for _, sentence := range helpSentences(help) {
- if !emptyClause.MatchString(sentence) {
- continue
- }
- for _, m := range backticked.FindAllStringSubmatch(suchAs.ReplaceAllString(sentence, ""), -1) {
- if !slices.Contains(out, m[1]) {
- out = append(out, m[1])
- }
- }
- }
- return out
-}
-
-func literal(v string) string {
- v = strings.TrimSpace(digitGroups.ReplaceAllString(v, "$1$2"))
- if len(v) >= 2 && (v[0] == '\'' || v[0] == '"') && v[len(v)-1] == v[0] {
- return v[1 : len(v)-1]
- }
- if _, err := strconv.ParseFloat(v, 64); err == nil || v == "true" || v == "false" {
- return v
- }
- return ""
-}
-
-func configDefaultValues(t *testing.T, overrides string) map[string]string {
- t.Helper()
- data, err := os.ReadFile(filepath.Join(repoRoot, configDefaults[0]))
- if err != nil {
- t.Fatal(err)
- }
- _, body, ok := strings.Cut(string(data), "function defaultConfig(): MasterConfig {\n\treturn {\n")
- body, _, _ = strings.Cut(body, "\n\t};\n}")
- if !ok || body == "" {
- t.Fatalf("%s has no defaultConfig()", configDefaults[0])
- }
- byPath := map[string]string{}
- var keys []string
- for _, line := range strings.Split(body, "\n") {
- m := defaultLine.FindStringSubmatch(line)
- if m == nil {
- continue
- }
- depth := len(m[1]) - 2
- if depth < 0 || depth > len(keys) {
- t.Fatalf("defaultConfig() in %s has an unexpected indent at %q", configDefaults[0], line)
- }
- keys = append(keys[:depth], m[2])
- byPath[strings.Join(keys, ".")] = literal(m[3])
- }
- out := map[string]string{}
- for _, m := range overridePath.FindAllStringSubmatch(overrides, -1) {
- var path []string
- for _, part := range strings.Split(m[2], ",") {
- path = append(path, strings.Trim(strings.TrimSpace(part), "'"))
- }
- if v, ok := byPath[strings.Join(path, ".")]; ok && v != "" {
- out[m[1]] = v
- }
- }
- if len(out) == 0 {
- t.Fatalf("found no defaults for NAMED_FLUXER_ENV_OVERRIDES in %s", configDefaults[0])
- }
- return out
-}
-
-func rustDefaultValues(name string, rels []string, sources map[string]string) []string {
- var out []string
- for _, rel := range rels {
- if !strings.HasSuffix(rel, ".rs") {
- continue
- }
- data := sources[rel]
- consts := map[string]string{}
- for _, m := range rustConst.FindAllStringSubmatch(data, -1) {
- consts[m[1]] = m[2]
- }
- for _, loc := range rustRead.FindAllStringSubmatchIndex(data, -1) {
- if data[loc[2]:loc[3]] != name {
- continue
- }
- rest := data[loc[1]:]
- if next := rustRead.FindStringIndex(rest); next != nil {
- rest = rest[:next[0]]
- }
- rest, _, _ = strings.Cut(rest, ";")
- depth := 0
- for i, r := range rest {
- if r == '(' {
- depth++
- } else if r == ')' {
- depth--
- }
- if depth < -1 {
- rest = rest[:i]
- break
- }
- }
- m := rustArgument.FindStringSubmatch(rest)
- if m == nil {
- m = rustFallback.FindStringSubmatch(rest)
- }
- if m != nil {
- raw := m[1]
- if c, ok := consts[raw]; ok {
- raw = c
- }
- if v := literal(raw); v != "" && !slices.Contains(out, v) {
- out = append(out, v)
- }
- }
- }
- }
- return out
-}
-
-func codeDefaultValues(name string, rels []string, sources map[string]string) []string {
- out := rustDefaultValues(name, rels, sources)
- q := regexp.QuoteMeta(name)
- reads := map[string]*regexp.Regexp{
- ".erl": regexp.MustCompile(`\b(?:env_[a-z_]+|os:getenv)\(\s*"` + q + `"\s*,\s*(<<"[^"]*">>|<<>>|"[^"]*"|-?[\d.]+|true|false)\s*\)`),
- ".ts": regexp.MustCompile(`(?:\(\s*["'` + "`" + `]` + q + `["'` + "`" + `]\s*\)|\benv\??\.` + q + `\b)(?:\??\.[A-Za-z]+\(\))*\s*(?:\?\?|\|\|)\s*('[^']*'|"[^"]*"|-?[\d.]+|true|false)`),
- ".sh": regexp.MustCompile(`\|\|\s*` + q + `=([^\s;]+)|\$\{` + q + `:[-=]([^}]+)\}`),
- }
- for _, rel := range rels {
- ext := path.Ext(rel)
- if ext == ".hrl" {
- ext = ".erl"
- } else if slices.Contains([]string{".mts", ".tsx", ".mjs", ".js", ".cjs"}, ext) {
- ext = ".ts"
- }
- re := reads[ext]
- if re == nil {
- continue
- }
- for _, m := range re.FindAllStringSubmatch(sources[rel], -1) {
- raw := strings.TrimSuffix(strings.TrimPrefix(m[1], "<<"), ">>")
- v := literal(raw)
- if ext == ".sh" {
- v = strings.Trim(m[1]+m[2], `"'`)
- }
- if v != "" && !slices.Contains(out, v) {
- out = append(out, v)
- }
- }
- }
- return out
-}
-
-func clampBounds(name string, rels []string, sources map[string]string) []string {
- re := regexp.MustCompile(`(?m)^\s*` + regexp.QuoteMeta(name) + `="\$\(clamp_int\s+"[^"]*"\s+("?[^"\s)]+"?)\s+("?[^"\s)]+"?)\)"`)
- var out []string
- for _, rel := range rels {
- if !strings.HasSuffix(rel, ".sh") {
- continue
- }
- for _, m := range re.FindAllStringSubmatch(sources[rel], -1) {
- for _, b := range m[1:] {
- if _, err := strconv.Atoi(b); err == nil {
- out = append(out, b)
- }
- }
- }
- }
- return out
-}
-
-func rangeValue(v string) string {
- n, unit, ok := strings.Cut(v, " ")
- if !ok {
- return v
- }
- x, _ := strconv.ParseInt(n, 10, 64)
- return strconv.FormatInt(x<<map[string]int{"KiB": 10, "MiB": 20, "GiB": 30}[unit], 10)
-}
-
-func TestEnvInventory(t *testing.T) {
- var err error
- set := stack.Embedded()
- voiceFiles, err := fs.Sub(set.Files, "voice")
- if err != nil {
- t.Fatal(err)
- }
- voiceVars, err := stack.FilesVars(voiceFiles)
- if err != nil {
- t.Fatal(err)
- }
- reads, all := codeEnvNames(t)
- code := runtimeReads(reads)
- fluxer, other, feeds := composeEnv(t, set)
- docker := dockerfileEnvNames(t)
- helm := helmEnvNames(t)
- passed := func(name string) bool { return fluxer[name] != nil || other[name] != nil }
- registry := map[string]envVar{}
- sections := map[string]bool{}
- for _, s := range slices.Concat(envSections, envInternalGroups) {
- sections[s.id] = true
- }
- for _, v := range envVars {
- if _, dup := registry[v.name]; dup {
- t.Errorf("%s is listed twice", v.name)
- }
- registry[v.name] = v
- switch {
- case !sections[v.section]:
- t.Errorf("%s has an unknown section %q", v.name, v.section)
- case v.section == envStackSection:
- if slices.Contains(set.Vars, v.name) || !passed(v.name) {
- t.Errorf("%s is listed as set by the compose stack, but compose doesn't set it for any service, or it's a .env setting", v.name)
- }
- case v.section == envVoiceServerSection || v.section == envVoiceEdgeSection:
- if !slices.Contains(voiceVars, v.name) {
- t.Errorf("%s is listed as a voice server setting, but no voice compose file uses it", v.name)
- }
- case v.section == envRexctlSection:
- if passed(v.name) {
- t.Errorf("%s is listed in the rexctl section, but compose passes it", v.name)
- }
- case envTopSection(v.section) == envInternalSection:
- used := code[v.name] != nil || slices.Contains(libraryEnvVars, v.name)
- if !strings.HasPrefix(v.name, "FLUXER_") || slices.Contains(chartInputVars, v.name) {
- used = used || docker[v.name] != nil || helm[v.name] != nil
- }
- if !used || passed(v.name) {
- t.Errorf("%s is listed as not passed by the compose stack, but no code reads it, or compose passes it", v.name)
- }
- case !slices.Contains(set.Vars, v.name) && !strings.HasPrefix(v.name, "COMPOSE_"):
- t.Errorf("%s is listed as a .env setting, but no compose file uses it", v.name)
- }
- }
-
- for _, v := range set.Vars {
- if _, ok := registry[v]; !ok {
- t.Errorf("%s is used by a compose file but has no entry in envVars", v)
- }
- }
- for _, v := range voiceVars {
- if _, ok := registry[v]; !ok {
- t.Errorf("%s is used by a voice compose file but has no entry in envVars", v)
- }
- }
- for _, k := range slices.Sorted(maps.Keys(fluxer)) {
- if _, ok := registry[k]; !ok {
- t.Errorf("compose sets %s for %v but it has no entry in envVars", k, fluxer[k])
- }
- }
- for _, k := range slices.Sorted(maps.Keys(other)) {
- if _, ok := registry[k]; !ok {
- t.Errorf("compose sets %s for %v but it has no entry in envVars", k, other[k])
- }
- }
- for _, name := range slices.Sorted(maps.Keys(all)) {
- if _, ok := registry[name]; !ok {
- t.Errorf("%s is looked up in %v but has no entry in envVars", name, all[name])
- }
- }
-
- runtime := slices.Concat(libraryEnvVars, runtimeEnvVars, rexctlProxyVars)
- for _, k := range slices.Sorted(maps.Keys(fluxer)) {
- if code[k] == nil && !slices.Contains(runtime, strings.ToUpper(k)) {
- t.Errorf("compose passes %s to %v but no Fluxer code looks it up", k, fluxer[k])
- }
- }
- serviceReads := func(k, svc string) bool {
- var prefixes []string
- for prefix, services := range codeServices {
- if slices.Contains(services, svc) {
- prefixes = append(prefixes, prefix)
- }
- }
- return slices.ContainsFunc(code[k], func(rel string) bool {
- return slices.ContainsFunc(prefixes, func(p string) bool { return strings.HasPrefix(rel, p) })
- }) || slices.ContainsFunc(docker[k], func(f string) bool {
- return slices.ContainsFunc(prefixes, func(p string) bool { return f == p+"Dockerfile" })
- })
- }
- own, scripts := composeOwnEnv(t, set)
- for _, k := range slices.Sorted(maps.Keys(own)) {
- if slices.Contains(runtime, strings.ToUpper(k)) {
- continue
- }
- for _, svc := range own[k] {
- if slices.Contains(fluxer[k], svc) && !serviceReads(k, svc) {
- t.Errorf("compose passes %s to %s, but no code that service runs looks it up", k, svc)
- }
- }
- }
- services := map[string]bool{}
- for _, list := range codeServices {
- for _, svc := range list {
- services[svc] = true
- }
- }
- for _, v := range envVars {
- for _, m := range serviceList.FindAllStringSubmatch(v.help, -1) {
- for _, svc := range strings.FieldsFunc(strings.ReplaceAll(m[1], " and ", ","), func(r rune) bool { return r == ',' || r == ' ' }) {
- if services[svc] && !serviceReads(v.name, svc) && !slices.ContainsFunc(feeds[[2]string{v.name, svc}], func(k string) bool { return serviceReads(k, svc) }) && !slices.Contains(runtime, v.name) {
- t.Errorf("the entry for %s says the %s service uses it, but no code that service runs looks it up", v.name, svc)
- }
- }
- }
- }
- for _, svc := range slices.Sorted(maps.Keys(scripts)) {
- seen := map[string]bool{}
- for _, text := range scripts[svc] {
- for _, m := range composeSh.FindAllStringSubmatch(text, -1) {
- if seen[m[1]] {
- continue
- }
- seen[m[1]] = true
- if _, ok := registry[m[1]]; !ok {
- t.Errorf("the %s service's command uses %s but it has no entry in envVars", svc, m[1])
- }
- if !slices.Contains(other[m[1]], svc) && !slices.Contains(fluxer[m[1]], svc) {
- t.Errorf("the %s service's command uses %s but compose doesn't set it for that service", svc, m[1])
- }
- }
- }
- }
- shell := map[string]bool{}
- for _, name := range []string{stack.ComposeFile, stack.Caddyfile} {
- data, err := fs.ReadFile(set.Files, name)
- if err != nil {
- t.Fatal(err)
- }
- for _, re := range []*regexp.Regexp{caddyEnv, composeSh} {
- for _, m := range re.FindAllStringSubmatch(string(data), -1) {
- shell[m[1]] = true
- }
- }
- }
- for _, k := range slices.Sorted(maps.Keys(other)) {
- if strings.HasPrefix(k, "FLUXER_") && !shell[k] {
- t.Errorf("compose passes %s to %v but nothing there uses it", k, other[k])
- }
- }
-
- caddy := map[string][]byte{}
- if caddy[stack.Caddyfile], err = fs.ReadFile(set.Files, stack.Caddyfile); err != nil {
- t.Fatal(err)
- }
- for name := range caddyfiles {
- if caddy[name], err = os.ReadFile(filepath.Join(repoRoot, name)); err != nil {
- t.Fatal(err)
- }
- }
- for _, name := range slices.Sorted(maps.Keys(caddy)) {
- svc := caddyfiles[name]
- if svc == "" {
- svc = "edge"
- }
- for _, m := range caddyEnv.FindAllStringSubmatch(string(caddy[name]), -1) {
- if _, ok := registry[m[1]]; !ok {
- t.Errorf("%s uses %s but it has no entry in envVars", name, m[1])
- }
- if !slices.Contains(other[m[1]], svc) && !slices.Contains(fluxer[m[1]], svc) {
- t.Errorf("%s uses %s but compose doesn't set it for the %s service", name, m[1], svc)
- }
- }
- }
-
- for _, name := range slices.Sorted(maps.Keys(docker)) {
- if _, ok := registry[name]; !ok && !slices.Contains(dockerOSVars, name) {
- t.Errorf("%v sets %s but it has no entry in envVars", docker[name], name)
- }
- }
-
- for _, k := range settings.Named() {
- for _, v := range k.Vars {
- if _, ok := registry[v]; !ok || !slices.Contains(set.Vars, v) {
- t.Errorf("the %s setting writes %s, but compose doesn't use it or it has no entry in envVars", k.Name, v)
- }
- }
- }
- written := slices.Concat(stack.SizingKeys(), stack.ProfileKeys(set), settings.DerivedVars(), slices.Sorted(maps.Keys(settings.Twins)),
- slices.Sorted(maps.Keys(stack.FoldWorker(stack.Hardware{}, nil, map[string]string{stack.EmbeddedWorkerVar: "true"}))))
- for _, v := range written {
- if _, ok := registry[v]; !ok || !slices.Contains(set.Vars, v) {
- t.Errorf("rexctl writes %s, but compose doesn't use it or it has no entry in envVars", v)
- }
- }
-
- values := composeValues(set)
- literals := composeLiterals(set)
- for _, v := range envVars {
- if v.section != envStackSection {
- continue
- }
- if lit := literals[v.name]; lit != "" && strings.Contains(v.help, lit) {
- t.Errorf("%s repeats the compose value %q in its description", v.name, lit)
- }
- if _, from, ok := strings.Cut(v.help, " from "); ok {
- for _, ref := range envNamePattern.FindAllString(from, -1) {
- if !slices.ContainsFunc(values[v.name], func(s string) bool { return strings.Contains(s, ref) }) {
- t.Errorf("%s says compose sets it from %s, but its compose value is %v", v.name, ref, values[v.name])
- }
- }
- }
- }
-
- sources := map[string]string{}
- byRel := map[string]bool{}
- walkCode(t, codeRoots, func(rel, lang, data string) {
- data = digitGroups.ReplaceAllString(data, "$1$2")
- for _, m := range products.FindAllString(data, -1) {
- n := 1
- for _, f := range strings.Split(m, "*") {
- x, _ := strconv.Atoi(strings.TrimSpace(f))
- n *= x
- }
- data += " " + strconv.Itoa(n)
- }
- sources[rel] = data
- byRel[rel] = true
- })
- overrides, err := os.ReadFile(filepath.Join(repoRoot, configOverrides))
- if err != nil {
- t.Fatal(err)
- }
- loaderDefaults := configDefaultValues(t, string(overrides))
- for _, v := range envVars {
- if code[v.name] == nil {
- continue
- }
- defaults := emptyDefaults(v.help)
- inCompose := func(w string) bool {
- token := regexp.MustCompile(`(?:^|[^\w.])` + regexp.QuoteMeta(w) + `(?:$|[^\w.]|\.(?:\D|$))`)
- return slices.ContainsFunc(values[v.name], func(s string) bool { return token.MatchString(s) })
- }
- if len(defaults) > 0 && !slices.ContainsFunc(defaults, inCompose) {
- exact := codeDefaultValues(v.name, code[v.name], sources)
- if lit := loaderDefaults[v.name]; lit != "" && slices.Contains(code[v.name], configOverrides) {
- exact = append(exact, lit)
- }
- for _, lit := range exact {
- if !slices.Contains(defaults, lit) {
- t.Errorf("%s says an empty value gives %v, but the code falls back to %q", v.name, defaults, lit)
- }
- }
- }
- for _, b := range clampBounds(v.name, code[v.name], sources) {
- if !regexp.MustCompile(`\b` + b + `\b`).MatchString(v.help) {
- t.Errorf("%s doesn't mention %s, a bound the code keeps an empty value within", v.name, b)
- }
- }
- want := slices.Clone(defaults)
- for _, m := range codeRange.FindAllStringSubmatch(v.help, -1) {
- want = append(want, rangeValue(m[1]), rangeValue(m[2]))
- }
- for _, m := range codeBound.FindAllStringSubmatch(v.help, -1) {
- for _, n := range m[1:] {
- if n != "" && !slices.Contains(want, n) {
- want = append(want, n)
- }
- }
- }
- files := slices.Concat(code[v.name], envDefaultFiles[v.name])
- if envDefaultFiles[v.name] == nil {
- if slices.Contains(code[v.name], configOverrides) {
- files = append(files, configDefaults...)
- }
- for _, rel := range code[v.name] {
- for _, m := range tsImport.FindAllStringSubmatch(sources[rel], -1) {
- if imp := resolveImport(rel, m[1], byRel); imp != "" {
- files = append(files, imp)
- }
- }
- }
- }
- for _, w := range want {
- token := regexp.MustCompile(`(?:^|[^\w.])` + regexp.QuoteMeta(w) + `(?:$|[^\w.]|\.(?:\D|$))`)
- inCode := slices.ContainsFunc(files, func(rel string) bool { return token.MatchString(sources[rel]) })
- if !inCode && !inCompose(w) {
- t.Errorf("%s says %q, but neither compose nor %v has it", v.name, w, slices.Concat(code[v.name], envDefaultFiles[v.name]))
- }
- }
- }
-
- composeFiles := []string{stack.ComposeFile}
- for _, o := range envOverlays {
- composeFiles = append(composeFiles, stack.OverlayFiles[o.overlay])
- }
- for i, file := range composeFiles {
- data, err := stack.ReadFile(set, file)
- if err != nil {
- t.Fatal(err)
- }
- defs := map[string][]string{}
- scanDefaults(string(data), defs, map[string]bool{})
- for _, k := range slices.Sorted(maps.Keys(defs)) {
- var lits []string
- empty := false
- for _, d := range defs[k] {
- if d == "" {
- empty = true
- } else if !strings.Contains(d, "$") && !slices.Contains(lits, d) {
- lits = append(lits, d)
- }
- }
- if len(lits) > 1 {
- t.Errorf("%s gives %s different defaults %v", file, k, lits)
- continue
- }
- if i > 0 || len(lits) == 0 {
- continue
- }
- if d := emptyDefaults(registry[k].help); len(d) > 0 && !slices.Contains(d, lits[0]) && !strings.Contains(registry[k].help, "Outside Docker Compose") {
- t.Errorf("%s says an empty value gives %v, but compose falls back to %q", k, d, lits[0])
- }
- if !empty {
- continue
- }
- exact := codeDefaultValues(k, code[k], sources)
- if lit := loaderDefaults[k]; lit != "" && slices.Contains(code[k], configOverrides) {
- exact = append(exact, lit)
- }
- slices.Sort(exact)
- for _, lit := range slices.Compact(exact) {
- if lit != lits[0] {
- t.Errorf("compose gives %s the default %q for one service and an empty value for another, where the code falls back to %q", k, lits[0], lit)
- }
- }
- }
- }
-
- aliases := configAliases(t, string(overrides))
- for _, alias := range slices.Sorted(maps.Keys(aliases)) {
- if v, ok := registry[alias]; !ok || !strings.Contains(v.help, aliases[alias]) {
- t.Errorf("the config loader reads %s when %s is empty, but the entry for %s doesn't mention %s", alias, aliases[alias], alias, aliases[alias])
- }
- }
- for _, m := range keyEnv.FindAllStringSubmatch(string(overrides), -1) {
- if envTopSection(registry[m[1]].section) != envInternalSection && !slices.Contains(fluxer[m[1]], "api") && !slices.Contains(workerOnlyVars, m[1]) {
- t.Errorf("the config loader looks up %s, but compose doesn't pass it to the api", m[1])
- }
- }
- for _, name := range workerOnlyVars {
- if slices.Contains(fluxer[name], "api") || !slices.Contains(fluxer[name], "worker") {
- t.Errorf("%s is listed as passed to the worker only, but compose passes it to %v", name, fluxer[name])
- }
- }
- for _, name := range slices.Sorted(maps.Keys(code)) {
- if envTopSection(registry[name].section) == envInternalSection {
- continue
- }
- for _, rel := range code[name] {
- if rel == configOverrides && aliases[name] != "" {
- continue
- }
- var want []string
- image := ""
- for prefix, services := range codeServices {
- if strings.HasPrefix(rel, prefix) {
- want, image = services, prefix+"Dockerfile"
- }
- }
- if len(want) > 0 && !slices.Contains(docker[name], image) && !slices.ContainsFunc(want, func(svc string) bool {
- return slices.Contains(fluxer[name], svc) || slices.Contains(other[name], svc)
- }) {
- t.Errorf("%s looks up %s, but compose passes it to none of %v", rel, name, want)
- }
- }
- }
- for _, name := range slices.Sorted(maps.Keys(helm)) {
- if _, ok := registry[name]; !ok {
- t.Errorf("%v sets %s but it has no entry in envVars", helm[name], name)
- }
- }
-
- for _, name := range envSecretVars {
- if v, ok := registry[name]; !ok || slices.Contains(envUnbundledSections, envTopSection(v.section)) {
- t.Errorf("%s is listed as a secret but isn't a .env setting", name)
- }
- }
- for _, s := range secrets.Required {
- if s.Kind != secrets.KindFixed && s.Key != secrets.VAPIDPublicKey && !slices.Contains(envSecretVars, s.Key) {
- t.Errorf("%s is a generated secret but isn't in envSecretVars", s.Key)
- }
- }
-}
-
-var serviceList = regexp.MustCompile(`\b((?:[a-z][a-z-]*, )*[a-z][a-z-]* and [a-z][a-z-]*) services\b`)
-
-var workerOnlyVars = []string{"FLUXER_API_WORKER_ENABLE_CRON_SCHEDULER", "FLUXER_API_WORKER_MODE"}
-
-var helmPodEnv = regexp.MustCompile(`(?m)^\s*-\s*name:\s*"?([A-Z][A-Z0-9_]*)"?\s*$|"name"\s+"([A-Z][A-Z0-9_]*)"|\bset \$c "([A-Z][A-Z0-9_]*)"`)
-
-func helmEnvNames(t *testing.T) map[string][]string {
- t.Helper()
- found := map[string][]string{}
- root := filepath.Join(repoRoot, helmChart)
- err := filepath.WalkDir(filepath.Join(root, "templates"), func(p string, d fs.DirEntry, err error) error {
- if err != nil {
- return err
- }
- if d.IsDir() {
- if d.Name() == "tests" {
- return filepath.SkipDir
- }
- return nil
- }
- data, err := os.ReadFile(p)
- if err != nil {
- return err
- }
- rel, _ := filepath.Rel(repoRoot, p)
- for _, m := range helmPodEnv.FindAllStringSubmatch(string(data), -1) {
- addFound(found, m[1]+m[2]+m[3], filepath.ToSlash(rel))
- }
- return nil
- })
- if err != nil {
- t.Fatal(err)
- }
- data, err := os.ReadFile(filepath.Join(root, "values.yaml"))
- if err != nil {
- t.Fatal(err)
- }
- var values struct {
- Secrets struct {
- Values map[string]any `yaml:"values"`
- } `yaml:"secrets"`
- }
- if err := yaml.Unmarshal(data, &values); err != nil {
- t.Fatal(err)
- }
- if len(values.Secrets.Values) == 0 {
- t.Fatal("the Helm chart values have no secrets.values keys")
- }
- for _, name := range slices.Sorted(maps.Keys(values.Secrets.Values)) {
- addFound(found, name, helmChart+"/values.yaml")
- }
- return found
-}
-
-func TestEnvDefaults(t *testing.T) {
- docs := envDocs()
- if d := docs.get("FLUXER_LIVEKIT_DEFAULT_REGION"); len(d.defaults) != 1 || !json.Valid([]byte(d.defaults[0].value)) {
- t.Errorf("the FLUXER_LIVEKIT_DEFAULT_REGION default isn't one JSON value, got %v", d.defaults)
- }
- for _, name := range []string{"FLUXER_API_NODE_HEAP_MB", "FLUXER_WORKER_NODE_HEAP_MB"} {
- if d := docs.get(name); len(d.defaults) != 0 {
- t.Errorf("%s has the default %v, which belongs to another flag", name, d.defaults)
- }
- }
-}
-
-func TestEnvFileForms(t *testing.T) {
- direct := map[string]bool{}
- shellNames := map[string]bool{}
- walkCode(t, codeRoots, func(rel, lang, data string) {
- if strings.HasPrefix(rel, "fluxer_docs/") {
- return
- }
- switch lang {
- case "ts", "native", "c":
- for _, m := range directEnv.FindAllStringSubmatch(data, -1) {
- direct[m[1]+m[2]+m[3]+m[4]] = true
- }
- case "shell":
- for _, m := range shellEnv.FindAllStringSubmatch(data, -1) {
- shellNames[m[1]] = true
- }
- }
- })
- for name := range shellNames {
- if !strings.HasSuffix(name, "_FILE") && !shellNames[name+"_FILE"] {
- direct[name] = true
- }
- }
- got := slices.Sorted(maps.Keys(direct))
- want := slices.Sorted(slices.Values(envNoFileVars))
- if !slices.Equal(got, want) {
- t.Errorf("Fluxer code looks up these variables without the _FILE form\n got %v\nwant %v (envNoFileVars)", got, want)
- }
-}
-
-func TestRexctlEnv(t *testing.T) {
- found := map[string][]string{}
- local := map[string]map[string][]string{}
- global := map[string][]string{}
- type pending struct{ rel, ident string }
- var idents []pending
- walkCode(t, rexctlRoots, func(rel, lang, data string) {
- switch lang {
- case "go":
- dir := path.Dir(rel)
- if local[dir] == nil {
- local[dir] = map[string][]string{}
- }
- for _, m := range goConst.FindAllStringSubmatch(data, -1) {
- local[dir][m[1]] = append(local[dir][m[1]], m[2])
- global[m[1]] = append(global[m[1]], m[2])
- }
- for _, m := range goIdentEnv.FindAllStringSubmatch(data, -1) {
- idents = append(idents, pending{rel, m[1]})
- }
- if strings.Contains(data, "os.Environ()") || strings.Contains(data, "environ []string") {
- for _, m := range goEnviron.FindAllStringSubmatch(data, -1) {
- addFound(found, m[1]+m[2], rel)
- }
- }
- for _, m := range goEnv.FindAllStringSubmatch(data, -1) {
- addFound(found, m[1]+m[3], rel)
- for _, q := range regexp.MustCompile(`"([A-Za-z_][A-Za-z0-9_]*)"`).FindAllStringSubmatch(m[2], -1) {
- addFound(found, q[1], rel)
- }
- }
- case "shell":
- for _, m := range shellEnv.FindAllStringSubmatch(data, -1) {
- addFound(found, m[1], rel)
- }
- case "ps":
- for _, m := range psEnv.FindAllStringSubmatch(data, -1) {
- addFound(found, m[1], rel)
- }
- }
- })
- for _, p := range idents {
- values, ok := local[path.Dir(p.rel)][p.ident]
- if !ok && p.ident[0] >= 'A' && p.ident[0] <= 'Z' {
- values = global[p.ident]
- }
- for _, v := range values {
- addFound(found, v, p.rel)
- }
- }
- registry := map[string]envVar{}
- for _, v := range envVars {
- registry[v.name] = v
- }
- for _, name := range rexctlLibraryVars {
- addFound(found, name, "the Docker CLI library")
- }
- network := slices.IndexFunc(envSections, func(s envSection) bool { return s.id == envNetworkSection })
- for _, name := range rexctlProxyVars {
- if registry[name].section != envNetworkSection || network < 0 || !strings.Contains(envSections[network].intro, name) {
- t.Errorf("rexctl and install.sh take %s from the shell, but the outgoing proxy section doesn't say so", name)
- }
- }
- for _, name := range slices.Sorted(maps.Keys(found)) {
- if s := registry[name].section; s != envRexctlSection && s != envComposeSection && !slices.Contains(rexctlOSVars, name) {
- t.Errorf("%v looks up %s but envVars doesn't list it in the rexctl or compose section", found[name], name)
- }
- }
- for _, v := range envVars {
- if v.section == envRexctlSection && found[v.name] == nil {
- t.Errorf("%s is listed in the rexctl section but neither rexctl nor its install scripts look it up", v.name)
- }
- }
-}
-
-var unbundledImages = []string{"fluxer_docs"}
-
-func TestEnvCodeRoots(t *testing.T) {
- dockerfiles, err := filepath.Glob(filepath.Join(repoRoot, "fluxer_*", "Dockerfile"))
- if err != nil {
- t.Fatal(err)
- }
- for _, p := range dockerfiles {
- dir := filepath.Base(filepath.Dir(p))
- if !slices.ContainsFunc(codeRoots, func(root string) bool { return strings.HasPrefix(root, dir+"/") || root == dir }) {
- t.Errorf("%s has a Dockerfile but no directory of it is in codeRoots", dir)
- }
- if _, ok := codeServices[dir+"/"]; !ok && !slices.Contains(unbundledImages, dir) {
- t.Errorf("%s has a Dockerfile but codeServices doesn't list its compose services", dir)
- }
- }
- fluxer, _, _ := composeEnv(t, stack.Embedded())
- services := map[string]bool{}
- for _, svcs := range fluxer {
- for _, svc := range svcs {
- services[svc] = true
- }
- }
- for _, svc := range slices.Sorted(maps.Keys(services)) {
- if !slices.ContainsFunc(slices.Collect(maps.Values(codeServices)), func(list []string) bool { return slices.Contains(list, svc) }) {
- t.Errorf("compose runs %s from a Fluxer image, but no codeServices entry lists it", svc)
- }
- }
-}
-
-func TestEnvWorkflowPaths(t *testing.T) {
- data, err := os.ReadFile(filepath.Join(repoRoot, ".github/workflows/env-reference.yaml"))
- if err != nil {
- t.Fatal(err)
- }
- var wf struct {
- On struct {
- PullRequest struct {
- Paths []string `yaml:"paths"`
- } `yaml:"pull_request"`
- Push struct {
- Paths []string `yaml:"paths"`
- } `yaml:"push"`
- } `yaml:"on"`
- }
- if err := yaml.Unmarshal(data, &wf); err != nil {
- t.Fatal(err)
- }
- if !slices.Equal(wf.On.PullRequest.Paths, wf.On.Push.Paths) {
- t.Errorf("the pull_request and push paths of env-reference.yaml differ")
- }
- dockerfiles, err := filepath.Glob(filepath.Join(repoRoot, "fluxer_*", "Dockerfile"))
- if err != nil {
- t.Fatal(err)
- }
- inputs := slices.Concat(codeRoots, rexctlRoots, slices.Sorted(maps.Keys(caddyfiles)), []string{configOverrides, docsContent, helmChart})
- for _, p := range dockerfiles {
- rel, _ := filepath.Rel(repoRoot, p)
- inputs = append(inputs, filepath.ToSlash(rel))
- }
- for _, in := range inputs {
- if !slices.ContainsFunc(wf.On.PullRequest.Paths, func(glob string) bool {
- if dir, ok := strings.CutSuffix(glob, "**"); ok {
- return strings.HasPrefix(in+"/", dir)
- }
- ok, _ := path.Match(glob, in)
- return ok
- }) {
- t.Errorf("env-reference.yaml doesn't run for changes to %s", in)
- }
- }
-}
-
-var envHelpBanned = regexp.MustCompile(`[<>{}|;–—“”‘’]|[a-z)]: [A-Za-z]`)
-
-func envProse(text string) string {
- parts := strings.Split(text, "`")
- for i := 1; i < len(parts); i += 2 {
- parts[i] = "code"
- }
- return strings.Join(parts, "")
-}
-
-func TestEnvHelp(t *testing.T) {
- named := map[string]bool{}
- for _, k := range settings.Named() {
- for _, v := range k.Vars {
- named[v] = true
- }
- }
- for _, v := range envVars {
- if v.help == "" && !named[v.name] {
- t.Errorf("%s has no description", v.name)
- }
- for _, sentence := range helpSentences(v.help) {
- rest := suchAs.ReplaceAllString(sentence, "")
- if anyEmpty.MatchString(rest) && backticked.MatchString(rest) && !emptyClause.MatchString(rest) && !otherEmpty.MatchString(rest) {
- t.Errorf("%s states a value for an empty setting in a form the default check can't read: %q", v.name, strings.TrimSpace(sentence))
- }
- }
- }
- check := func(what, text string) {
- if text == "" {
- return
- }
- if !strings.HasSuffix(text, ".") {
- t.Errorf("%s doesn't end with a full stop", what)
- }
- if m := envHelpBanned.FindString(envProse(text)); m != "" {
- t.Errorf("%s has %q", what, m)
- }
- }
- for _, d := range envDocs() {
- if strings.TrimSpace(d.text) == "" {
- t.Errorf("%s renders without a description", d.name)
- }
- check(d.name, d.text)
- check(d.name+" note", d.note)
- }
- for _, s := range slices.Concat(envSections, envInternalGroups) {
- check("the "+s.title+" section intro", s.intro)
- check("the "+s.title+" page intro", s.page)
- if m := envHelpBanned.FindString(s.title); m != "" {
- t.Errorf("the %s section title has %q", s.title, m)
- }
- }
- check("the note on values from files", envNoFileNote)
- check("the reference note", referenceEnvNote)
- for _, g := range []*secretGroup{{kind: secrets.KindFixed}, {kind: secrets.KindHex32, stateful: true}, {kind: secrets.KindVAPID, stateful: true}} {
- text, _ := secretHelp(g)
- check("the secrets help", text)
- }
-}
-
-func TestLibraryEnvAnchors(t *testing.T) {
- for _, name := range libraryEnvVars {
- anchors := libraryEnvAnchors[name]
- if len(anchors) == 0 {
- t.Errorf("%s has no code anchor in libraryEnvAnchors", name)
- }
- for _, a := range anchors {
- data, err := os.ReadFile(filepath.Join(repoRoot, a[0]))
- if err != nil {
- t.Fatal(err)
- }
- if !regexp.MustCompile(a[1]).Match(data) {
- t.Errorf("%s no longer matches %s, which the %s entry depends on", a[0], a[1], name)
- }
- }
- }
- walkCode(t, codeRoots, func(rel, lang, data string) {
- if lang == "native" && strings.Contains(data, ".no_proxy()") && !slices.Contains(noProxyFiles, rel) {
- t.Errorf("%s turns off the proxy, which the ALL_PROXY entry doesn't cover", rel)
- }
- })
-}
-
-func TestEnvScanner(t *testing.T) {
- files := []codeFile{
- {rel: "fixture/timings.erl", lang: "native", data: "pod() ->\n first_name([\"FX_POD\", \"FX_HOST\"], x).\n\nfirst_name([], Fallback) ->\n Fallback;\nfirst_name([Name | Rest], Fallback) ->\n case config:env_value(Name) of\n undefined -> first_name(Rest, Fallback);\n Value -> Value\n end.\n"},
- {rel: "fixture/version.rs", lang: "native", data: stripRustTests("fn version() -> String {\n read_first_env(&[\"FX_BUILD\", \"FX_VERSION\"])\n}\n#[cfg(test)]\nmod tests {\n fn reads() {\n let _ = (\"}\", '{');\n std::env::var(\"FX_TEST_ONLY\");\n }\n}\nfn after() {\n std::env::var(\"FX_AFTER\");\n}\n")},
- {rel: "fixture/built.rs", lang: "native", data: "fn built(x: &str) {\n std::env::var(format!(\"FX_BUILT_{}\", x));\n std::env::var_os(concat!(\"FX_JOINED_\", \"X\"));\n}\n"},
- {rel: "fixture/check.ts", lang: "ts", data: "if (days < 1) {\n\tthrow new Error('FLUXER_FX_MESSAGE must be at least 1');\n}\nassertIntegerInRange(days, 'FLUXER_FX_MESSAGE', 1, 10);\n"},
- {rel: "fixture/mod.rs", lang: "native", data: stripRustTests("#[cfg(test)]\nmod tests;\nfn port(env: &Env) {\n read(env, \"FX_PORT\");\n}\nfn read(env: &Env, name: &str) {\n env.get(name);\n}\n")},
- {rel: "fixture/required.rs", lang: "native", data: "fn load(env: &Env) {\n env.require(\"FX_REQUIRED\");\n}\n"},
- {rel: "fixture/key.ts", lang: "ts", data: "const key = 'FX_KEY';\nexport const value = process.env[key];\n"},
- {rel: "fixture/list.rs", lang: "native", data: "fn first() {\n for k in [\"FX_FIRST\", \"FX_SECOND\"] {\n let _ = std::env::var(k);\n }\n let n = \"FX_LOCAL\";\n let _ = std::env::var(n);\n}\n"},
- {rel: "fixture/node.erl", lang: "native", data: "node() ->\n Name = \"FX_NODE\",\n os:getenv(Name).\n"},
- {rel: "fixture/branding.rs", lang: "native", data: "const ICON: (&str, &str) = (\"icon_url\", \"FX_ICON\");\nfn snapshot<F: FnMut(&str) -> Option<String>>(mut read_var: F) {\n fields(|(_, name)| read_var(name));\n}\n"},
- {rel: "fixture/scheme.ts", lang: "ts", data: "function readString(name: string, fallback: string) {\n\treturn process.env[name] ?? fallback;\n}\nfunction readScheme(name: string) {\n\treturn readString(name, 'http');\n}\nexport const scheme = readScheme('FX_SCHEME');\n"},
- }
- got, mentioned := scanEnvNames(files)
- for _, name := range []string{"FX_POD", "FX_HOST", "FX_BUILD", "FX_VERSION", "FX_AFTER", "FX_PORT", "FX_BUILT_", "FX_JOINED_", "FX_REQUIRED", "FX_SCHEME", "FX_KEY", "FX_FIRST", "FX_SECOND", "FX_LOCAL", "FX_NODE", "FX_ICON"} {
- if got[name] == nil {
- t.Errorf("the scanner misses %s", name)
- }
- }
- if got["FX_TEST_ONLY"] != nil {
- t.Errorf("the scanner counts FX_TEST_ONLY, which only test code reads")
- }
- if got["FLUXER_FX_MESSAGE"] != nil || mentioned["FLUXER_FX_MESSAGE"] == nil {
- t.Errorf("the scanner counts FLUXER_FX_MESSAGE as a read, which only an error message has, or misses it as a mention")
- }
-}
-
-var envAlias = regexp.MustCompile(`([A-Za-z_$][\w$]*)\??\s*(?::\s*[^=,;()\n]+)?=\s*(?:process|Bun|import\.meta)\.env\s*(?:[,;)\n]|$)|([A-Za-z_$][\w$]*)\??\s*:\s*NodeJS\.ProcessEnv\b`)
-
-func TestEnvAliases(t *testing.T) {
- walkCode(t, codeRoots, func(rel, lang, data string) {
- if lang != "ts" {
- return
- }
- for _, m := range envAlias.FindAllStringSubmatch(data, -1) {
- if name := m[1] + m[2]; name != "env" {
- t.Errorf("%s keeps the environment in %s, and the scanner only follows reads through env", rel, name)
- }
- }
- })
-}
diff --git a/fluxer_rexctl/internal/instance/import_test.go b/fluxer_rexctl/internal/instance/import_test.go
deleted file mode 100644
index 5b6073796..000000000
--- a/fluxer_rexctl/internal/instance/import_test.go
+++ /dev/null
@@ -1,104 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-package instance
-
-import (
- "os"
- "path/filepath"
- "slices"
- "testing"
-)
-
-func TestDropMergedShards(t *testing.T) {
- dir := t.TempDir()
- in := `x-local-env: &local-env
- FLUXER_S3_ENDPOINT: http://storage:8333
-
-services:
- # Keep SeaweedFS from starting
- seaweedfs:
- profiles: ["seaweedfs-disabled"]
- api:
- environment: *local-env
- depends_on:
- seaweedfs-init: !reset null
- gifs:
- environment: *local-env
- gifs-shard:
- environment: *local-env
-
- # messages
- messages:
- environment: *local-env
- messages-shard:
- environment:
- FLUXER_S3_ENDPOINT: http://storage:8333
- users-shard:
- environment:
- OTHER: "1"
- unfurl:
- environment: *local-env
- unfurl-shard: {environment: *local-env}
-`
- want := `x-local-env: &local-env
- FLUXER_S3_ENDPOINT: http://storage:8333
-
-services:
- # Keep SeaweedFS from starting
- seaweedfs:
- profiles: ["seaweedfs-disabled"]
- api:
- environment: *local-env
- depends_on:
- seaweedfs-init: !reset null
- gifs:
- environment: *local-env
-
- # messages
- messages:
- environment: *local-env
- users-shard:
- environment:
- OTHER: "1"
- unfurl:
- environment: *local-env
-`
- path := filepath.Join(dir, CustomCompose)
- if err := os.WriteFile(path, []byte(in), 0o644); err != nil {
- t.Fatal(err)
- }
- dropped, err := DropMergedShards(dir)
- if err != nil {
- t.Fatal(err)
- }
- if !slices.Equal(dropped, []string{"gifs-shard", "messages-shard", "unfurl-shard"}) {
- t.Fatalf("dropped %v", dropped)
- }
- got, _ := os.ReadFile(path)
- if string(got) != want {
- t.Fatalf("got\n%s", got)
- }
- if got := RetiredService(dir); got != "users-shard" {
- t.Fatalf("retired %q", got)
- }
-}
-
-func TestDropMergedShardsKeepsSharedAnchor(t *testing.T) {
- dir := t.TempDir()
- in := `services:
- gifs-shard: &shared
- environment:
- A: "1"
- gifs: *shared
-`
- path := filepath.Join(dir, CustomCompose)
- if err := os.WriteFile(path, []byte(in), 0o644); err != nil {
- t.Fatal(err)
- }
- if dropped, err := DropMergedShards(dir); err != nil || dropped != nil {
- t.Fatalf("dropped %v, %v", dropped, err)
- }
- if got, _ := os.ReadFile(path); string(got) != in {
- t.Fatalf("changed to\n%s", got)
- }
-}
diff --git a/fluxer_rexctl/internal/instance/layout_test.go b/fluxer_rexctl/internal/instance/layout_test.go
deleted file mode 100644
index 4f8bb6ac7..000000000
--- a/fluxer_rexctl/internal/instance/layout_test.go
+++ /dev/null
@@ -1,620 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-package instance
-
-import (
- "bytes"
- "context"
- "encoding/json"
- "errors"
- "fmt"
- "maps"
- "os"
- "path/filepath"
- "runtime"
- "slices"
- "strings"
- "testing"
-
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/engine"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/envfile"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/secrets"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/settings"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/stack"
-)
-
-var userFiles = map[string]string{
- CustomCompose: "services:\n edge:\n labels:\n team: chat\n",
- filepath.Join(CaddyDropInDir, "x.caddy"): "header X-Mine yes\n",
- filepath.Join(CertsDir, "site.pem"): "pem\n",
-}
-
-func oldLayout(t *testing.T) (string, map[string][]byte) {
- t.Helper()
- dir := t.TempDir()
- set := stack.Embedded()
- refs := fluxerRefs("a")
- s := &State{
- Project: "fluxer",
- Release: set.Release,
- Images: Images{Release: set.Release, Refs: refs},
- Settings: map[string]string{settings.Domain: "chat.example.com"},
- Secrets: map[string]string{},
- }
- if _, err := secrets.Mint(s.Secrets, false); err != nil {
- t.Fatal(err)
- }
- managed, err := stack.Files(set, nil, refs, "fluxer")
- if err != nil {
- t.Fatal(err)
- }
- if s.Rendered, err = stack.Hashes(set, nil, refs, "fluxer"); err != nil {
- t.Fatal(err)
- }
- files := map[string][]byte{}
- for name, data := range managed {
- files[name] = stack.Plain(name, data)
- if stack.Hash(files[name]) != s.Rendered[name] {
- t.Fatalf("the old layout fixture of %s doesn't match what older rexctl wrote", name)
- }
- }
- for name, data := range userFiles {
- files[name] = []byte(data)
- }
- for name, data := range files {
- writeTestFile(t, filepath.Join(dir, name), data)
- }
- if err := os.MkdirAll(filepath.Join(dir, StateDirName), 0o700); err != nil {
- t.Fatal(err)
- }
- s.rootLayout = true
- if err := s.Save(filepath.Join(dir, StateDirName, StateFileName)); err != nil {
- t.Fatal(err)
- }
- return dir, files
-}
-
-func writeTestFile(t *testing.T, path string, data []byte) {
- t.Helper()
- if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
- t.Fatal(err)
- }
- if err := os.WriteFile(path, data, 0o644); err != nil {
- t.Fatal(err)
- }
-}
-
-func readTestFile(t *testing.T, path string) []byte {
- t.Helper()
- data, err := os.ReadFile(path)
- if err != nil {
- t.Fatal(err)
- }
- return data
-}
-
-func diskSchema(t *testing.T, dir string) int {
- t.Helper()
- var head struct{ Schema int }
- if err := json.Unmarshal(readTestFile(t, filepath.Join(dir, StateDirName, StateFileName)), &head); err != nil {
- t.Fatal(err)
- }
- return head.Schema
-}
-
-func migrated(t *testing.T, dir string, old map[string][]byte) *Instance {
- t.Helper()
- inst, err := Find(dir)
- if err != nil {
- t.Fatal(err)
- }
- if err := inst.Migrate(nil); err != nil {
- t.Fatal(err)
- }
- return checkMigrated(t, dir, old)
-}
-
-func checkMigrated(t *testing.T, dir string, old map[string][]byte) *Instance {
- t.Helper()
- inst, err := Find(dir)
- if err != nil {
- t.Fatal(err)
- }
- if inst.OldLayout() {
- t.Fatal("the instance is still on the old layout")
- }
- for _, name := range stack.FileNames() {
- want, ok := old[name]
- if !ok {
- continue
- }
- if got := readTestFile(t, inst.Generated(name)); !bytes.Equal(got, want) {
- t.Fatalf("%s changed while moving", name)
- }
- _, err := os.Lstat(inst.Path(name))
- if _, mounted := stack.MountedFiles[name]; !mounted && !errors.Is(err, os.ErrNotExist) {
- t.Fatalf("%s is still in the instance folder: %v", name, err)
- }
- }
- for name, data := range userFiles {
- if got := readTestFile(t, inst.Path(name)); string(got) != data {
- t.Fatalf("%s changed", name)
- }
- }
- if s := diskSchema(t, dir); s != StateSchema {
- t.Fatalf("schema on disk %d, want %d", s, StateSchema)
- }
- r, err := Drift(inst)
- if err != nil || len(r.Changed) > 0 || len(r.Missing) > 0 {
- t.Fatalf("drift after moving: %+v %v", r, err)
- }
- for _, f := range inst.ComposeFiles() {
- if f != inst.Path(CustomCompose) && !strings.HasPrefix(f, stack.GeneratedPath(dir)) {
- t.Fatalf("compose file %s isn't in %s", f, stack.GeneratedDir)
- }
- }
- return inst
-}
-
-func checkOldLayout(t *testing.T, dir string, old map[string][]byte) {
- t.Helper()
- if s := diskSchema(t, dir); s != 2 {
- t.Fatalf("schema on disk %d, want 2", s)
- }
- for name, want := range old {
- if got := readTestFile(t, filepath.Join(dir, name)); !bytes.Equal(got, want) {
- t.Fatalf("%s changed", name)
- }
- }
-}
-
-func TestFindLeavesOldLayout(t *testing.T) {
- dir, old := oldLayout(t)
- inst, err := Find(dir)
- if err != nil {
- t.Fatal(err)
- }
- if !inst.OldLayout() {
- t.Fatal("an older rexctl's instance loaded as the new layout")
- }
- checkOldLayout(t, dir, old)
- if _, err := os.Stat(stack.GeneratedPath(dir)); !errors.Is(err, os.ErrNotExist) {
- t.Fatal("loading the instance made the generated folder")
- }
- r, err := Drift(inst)
- if err != nil || len(r.Changed) > 0 || len(r.Missing) > 0 || len(inst.MissingFiles()) > 0 {
- t.Fatalf("drift on the old layout: %+v %v %v", r, err, inst.MissingFiles())
- }
- for _, f := range inst.ComposeFiles() {
- if filepath.Dir(f) != dir {
- t.Fatalf("compose file %s isn't in the instance folder", f)
- }
- }
- if err := inst.Save(); err != nil {
- t.Fatal(err)
- }
- checkOldLayout(t, dir, old)
-}
-
-func TestFindWorksWhileLockedAndReadOnly(t *testing.T) {
- dir, old := oldLayout(t)
- l, err := (&Instance{Dir: dir}).Lock(context.Background())
- if err != nil {
- t.Fatal(err)
- }
- defer l.Release()
- if runtime.GOOS != "windows" && os.Geteuid() != 0 {
- if err := os.Chmod(filepath.Join(dir, StateDirName), 0o500); err != nil {
- t.Fatal(err)
- }
- t.Cleanup(func() { os.Chmod(filepath.Join(dir, StateDirName), 0o700) })
- }
- if _, err := Find(dir); err != nil {
- t.Fatalf("Find on an old layout another command holds: %v", err)
- }
- checkOldLayout(t, dir, old)
-}
-
-func TestOldLayoutRendersInPlace(t *testing.T) {
- dir, old := oldLayout(t)
- inst, err := Find(dir)
- if err != nil {
- t.Fatal(err)
- }
- inst.State.Settings[settings.EdgeMode] = settings.EdgeProxy
- r, err := inst.Render(stack.Embedded(), inst.Overlays(), inst.State.Images.Refs)
- if err != nil {
- t.Fatal(err)
- }
- if _, err := os.Stat(stack.GeneratedPath(dir)); !errors.Is(err, os.ErrNotExist) {
- t.Fatal("rendering the old layout wrote the generated folder")
- }
- for name, hash := range r.Hashes {
- data := readTestFile(t, filepath.Join(dir, name))
- if stack.Hash(data) != hash || bytes.HasPrefix(data, []byte("# rexctl writes this file")) {
- t.Fatalf("%s isn't what an older rexctl writes", name)
- }
- }
- if !bytes.Equal(readTestFile(t, filepath.Join(dir, stack.ComposeFile)), old[stack.ComposeFile]) {
- t.Fatal("the compose file changed")
- }
-}
-
-func TestMigrateMovesOldLayout(t *testing.T) {
- dir, old := oldLayout(t)
- migrated(t, dir, old)
- if got := readTestFile(t, filepath.Join(dir, stack.Caddyfile)); !bytes.Equal(got, old[stack.Caddyfile]) {
- t.Fatal("the Caddyfile the running edge mounts went away before the next start")
- }
-}
-
-func TestMigrateOnce(t *testing.T) {
- dir, old := oldLayout(t)
- inst := migrated(t, dir, old)
- before := readTestFile(t, filepath.Join(dir, StateDirName, StateFileName))
- if err := inst.Migrate(func() error { return errors.New("ran again") }); err != nil {
- t.Fatal(err)
- }
- if after := readTestFile(t, filepath.Join(dir, StateDirName, StateFileName)); !bytes.Equal(before, after) {
- t.Fatal("a second migration changed the state again")
- }
-}
-
-func TestMigrateNoticesAnotherProcessMoved(t *testing.T) {
- dir, old := oldLayout(t)
- stale, err := Find(dir)
- if err != nil {
- t.Fatal(err)
- }
- migrated(t, dir, old)
- if err := stale.Migrate(func() error { return errors.New("ran again") }); err != nil {
- t.Fatal(err)
- }
- if err := stale.Save(); err != nil {
- t.Fatal(err)
- }
- checkMigrated(t, dir, old)
-}
-
-func TestMigrateStopsBeforeSavingWhenPrepareFails(t *testing.T) {
- dir, old := oldLayout(t)
- inst, err := Find(dir)
- if err != nil {
- t.Fatal(err)
- }
- var schemaThen int
- err = inst.Migrate(func() error {
- schemaThen = diskSchema(t, dir)
- return errors.New("no copy of rexctl")
- })
- if err == nil || schemaThen != 2 {
- t.Fatalf("got %v with schema %d while preparing", err, schemaThen)
- }
- if !inst.OldLayout() {
- t.Fatal("the instance switched layouts without its files")
- }
- checkOldLayout(t, dir, old)
-}
-
-func TestMigrateAfterCrashBeforeSave(t *testing.T) {
- dir, old := oldLayout(t)
- inst, err := Find(dir)
- if err != nil {
- t.Fatal(err)
- }
- if _, err := copyGenerated(inst); err != nil {
- t.Fatal(err)
- }
- checkOldLayout(t, dir, old)
- again, err := Find(dir)
- if err != nil || !again.OldLayout() {
- t.Fatalf("after the crash: %v", err)
- }
- migrated(t, dir, old)
-}
-
-func TestMigrateAsRootGivesFilesToOwner(t *testing.T) {
- if runtime.GOOS == "windows" {
- t.Skip("no owners on Windows")
- }
- dir, _ := oldLayout(t)
- inst, err := Find(dir)
- if err != nil {
- t.Fatal(err)
- }
- owner, _ := inst.OwnerUID()
- prevUID, prevChown := euid, chown
- t.Cleanup(func() { euid, chown = prevUID, prevChown })
- euid = func() int { return 0 }
- given := map[string]int{}
- chown = func(path string, uid, _ int) error {
- given[path] = uid
- return nil
- }
- if owner == 0 {
- t.Skip("the test folder belongs to root")
- }
- if err := inst.Migrate(nil); err != nil {
- t.Fatal(err)
- }
- for _, path := range []string{stack.GeneratedPath(dir), inst.Generated(stack.ComposeFile), inst.Generated(stack.Caddyfile)} {
- if uid, ok := given[path]; !ok || uid != owner {
- t.Fatalf("%s wasn't given to the folder's owner: %v", path, given)
- }
- }
-}
-
-func startedWithGenerated(t *testing.T, inst *Instance) {
- t.Helper()
- compose := inst.Generated(stack.ComposeFile)
- writeTestFile(t, compose, stack.Managed(stack.ComposeFile, stack.Plain(stack.ComposeFile, readTestFile(t, compose))))
- if err := inst.DropRootCopies(context.Background(), true); err != nil {
- t.Fatal(err)
- }
-}
-
-func TestDropRootCopiesRemovesOnlyWhatMigrationLeft(t *testing.T) {
- dir, old := oldLayout(t)
- inst := migrated(t, dir, old)
- root := inst.Path(stack.Caddyfile)
- if err := inst.DropRootCopies(context.Background(), true); err != nil {
- t.Fatal(err)
- }
- if _, err := os.Stat(root); err != nil {
- t.Fatal("removed the Caddyfile an older compose file still mounts")
- }
- startedWithGenerated(t, inst)
- if _, err := os.Stat(root); !errors.Is(err, os.ErrNotExist) {
- t.Fatal("kept the Caddyfile the migration left after edge moved to the generated one")
- }
- again, err := Find(dir)
- if err != nil || len(again.State.LeftInRoot) != 0 {
- t.Fatalf("the state still lists %v, %v", again.State.LeftInRoot, err)
- }
-}
-
-func TestDropRootCopiesKeepsYourCaddyfile(t *testing.T) {
- for name, change := range map[string]func(t *testing.T, inst *Instance){
- "mounted from custom.compose.yml": func(t *testing.T, inst *Instance) {
- writeTestFile(t, inst.Path(CustomCompose), []byte("services:\n edge:\n volumes:\n - ./Caddyfile:/etc/caddy/Caddyfile:ro\n"))
- },
- "mounted from ${PWD}": func(t *testing.T, inst *Instance) {
- writeTestFile(t, inst.Path(CustomCompose), []byte("services:\n edge:\n volumes:\n - ${PWD}/Caddyfile:/etc/caddy/Caddyfile:ro\n"))
- },
- "mounted with the long syntax": func(t *testing.T, inst *Instance) {
- writeTestFile(t, inst.Path(CustomCompose), []byte("services:\n edge:\n volumes:\n - type: bind\n source: Caddyfile\n target: /etc/caddy/Caddyfile\n"))
- },
- "custom.compose.yml that doesn't load": func(t *testing.T, inst *Instance) {
- writeTestFile(t, inst.Path(CustomCompose), []byte("services: [\n"))
- },
- "changed by you": func(t *testing.T, inst *Instance) {
- writeTestFile(t, inst.Path(stack.Caddyfile), []byte(":443 {\n}\n"))
- },
- "never left by rexctl": func(t *testing.T, inst *Instance) {
- inst.State.LeftInRoot = nil
- },
- } {
- t.Run(name, func(t *testing.T) {
- dir, old := oldLayout(t)
- inst := migrated(t, dir, old)
- change(t, inst)
- startedWithGenerated(t, inst)
- if _, err := os.Stat(inst.Path(stack.Caddyfile)); err != nil {
- t.Fatalf("removed your Caddyfile: %v", err)
- }
- })
- }
-}
-
-func TestDropRootCopiesLooksAtWhatCustomComposeMounts(t *testing.T) {
- dir, old := oldLayout(t)
- inst := migrated(t, dir, old)
- writeTestFile(t, inst.Path(CustomCompose), []byte("services:\n edge:\n volumes:\n - ${PWD}/caddy.d/x.caddy:/etc/caddy/x.caddy:ro\n - ./Caddyfile.mine:/etc/caddy/mine:ro\n"))
- startedWithGenerated(t, inst)
- if _, err := os.Stat(inst.Path(stack.Caddyfile)); !errors.Is(err, os.ErrNotExist) {
- t.Fatal("kept the Caddyfile though custom.compose.yml mounts other files")
- }
-}
-
-func TestUnusedRootFilesNamesAnEditedCaddyfile(t *testing.T) {
- dir, old := oldLayout(t)
- inst := migrated(t, dir, old)
- ctx := context.Background()
- writeTestFile(t, inst.Path(stack.Caddyfile), []byte(":443 {\n}\n"))
- if got := inst.UnusedRootFiles(ctx); len(got) != 0 {
- t.Fatalf("the edge still mounts the root Caddyfile, but got %v", got)
- }
- startedWithGenerated(t, inst)
- if got := inst.UnusedRootFiles(ctx); !slices.Equal(got, []string{stack.Caddyfile}) {
- t.Fatalf("UnusedRootFiles = %v", got)
- }
- writeTestFile(t, inst.Path(CustomCompose), []byte("services:\n edge:\n volumes:\n - type: bind\n source: Caddyfile\n target: /etc/caddy/Caddyfile\n"))
- if got := inst.UnusedRootFiles(ctx); len(got) != 0 {
- t.Fatalf("custom.compose.yml mounts it, but got %v", got)
- }
-}
-
-func TestDropRootCopiesLeavesTheOldLayoutAlone(t *testing.T) {
- dir, old := oldLayout(t)
- inst, err := Find(dir)
- if err != nil {
- t.Fatal(err)
- }
- inst.State.LeftInRoot = map[string]string{}
- for _, name := range []string{stack.ComposeFile, stack.Caddyfile} {
- inst.State.LeftInRoot[name] = stack.Hash(old[name])
- }
- if err := inst.DropRootCopies(context.Background(), true); err != nil {
- t.Fatal(err)
- }
- checkOldLayout(t, dir, old)
-}
-
-func TestEjectAfterMoveGivesTheOldFiles(t *testing.T) {
- dir, old := oldLayout(t)
- inst := migrated(t, dir, old)
- if err := Eject(inst, EjectOptions{Rexctl: "test"}); err != nil {
- t.Fatal(err)
- }
- for _, name := range stack.FileNames() {
- want, ok := old[name]
- if !ok {
- continue
- }
- if got := readTestFile(t, inst.Path(name)); !bytes.Equal(got, want) {
- t.Fatalf("ejected %s differs from the file older rexctl left", name)
- }
- _, err := os.Stat(inst.Generated(name))
- if _, mounted := stack.MountedFiles[name]; !mounted && !errors.Is(err, os.ErrNotExist) {
- t.Fatalf("%s stayed in %s after eject", name, stack.GeneratedDir)
- }
- }
- env, err := envfile.Load(inst.Path(EnvFileName))
- if err != nil {
- t.Fatal(err)
- }
- if got, want := env.Value("COMPOSE_FILE"), stack.ComposeFile+string(os.PathListSeparator)+CustomCompose; got != want {
- t.Fatalf("COMPOSE_FILE = %q, want %q", got, want)
- }
- again, err := Find(dir)
- if err != nil || again.State.Ejected == nil {
- t.Fatalf("not ejected: %v", err)
- }
- if _, err := os.Stat(inst.Generated(stack.ComposeFile)); !errors.Is(err, os.ErrNotExist) {
- t.Fatal("loading an ejected instance moved its files")
- }
-
- s, r, err := Import(dir, nil)
- if err != nil {
- t.Fatal(err)
- }
- if len(r.KeepAsMine) > 0 || s.Ejected != nil {
- t.Fatalf("takeover kept %v", r.KeepAsMine)
- }
- checkOldLayout(t, dir, old)
- migrated(t, dir, old)
-}
-
-func TestFreshLayoutLoadsWithTemplate(t *testing.T) {
- inst, err := Create(t.TempDir(), "fluxer")
- if err != nil {
- t.Fatal(err)
- }
- set := stack.Embedded()
- inst.State.Release = set.Release
- inst.State.Images = Images{Release: set.Release, Refs: fluxerRefs("a")}
- inst.State.Settings[settings.Domain] = "chat.example.com"
- if _, err := secrets.Mint(inst.State.Secrets, false); err != nil {
- t.Fatal(err)
- }
- r, err := stack.Render(set, nil, inst.State.Images.Refs, "fluxer", inst.Dir)
- if err != nil {
- t.Fatal(err)
- }
- inst.State.Rendered = r.Hashes
- if err := inst.WriteCustomTemplate(); err != nil {
- t.Fatal(err)
- }
- if got := string(readTestFile(t, inst.Path(CustomCompose))); got != CustomTemplate {
- t.Fatalf("template %q", got)
- }
- mine := []byte("services: {}\n")
- writeTestFile(t, inst.Path(CustomCompose), mine)
- if err := inst.WriteCustomTemplate(); err != nil {
- t.Fatal(err)
- }
- if !bytes.Equal(readTestFile(t, inst.Path(CustomCompose)), mine) {
- t.Fatal("the template replaced the file you wrote")
- }
- writeTestFile(t, inst.Path(CustomCompose), []byte(CustomTemplate))
- for _, name := range slices.Sorted(maps.Keys(r.Hashes)) {
- if !bytes.HasPrefix(readTestFile(t, inst.Generated(name)), []byte("# rexctl writes this file and puts its own version back")) {
- t.Fatalf("%s has no header", name)
- }
- if _, err := os.Stat(inst.Path(name)); !errors.Is(err, os.ErrNotExist) {
- t.Fatalf("%s is in the instance folder", name)
- }
- }
- env, err := inst.Environment()
- if err != nil {
- t.Fatal(err)
- }
- var none engine.Engine
- p, err := none.Load(context.Background(), engine.Spec{Name: "fluxer", Dir: inst.Dir, Files: inst.ComposeFiles(), Env: env})
- if err != nil {
- t.Fatal(err)
- }
- if p.Model.WorkingDir != inst.Dir {
- t.Fatalf("project folder %s, want %s", p.Model.WorkingDir, inst.Dir)
- }
- var sources []string
- for _, v := range p.Model.Services["edge"].Volumes {
- sources = append(sources, v.Source)
- }
- for _, want := range []string{inst.Generated(stack.Caddyfile), inst.Path(CertsDir), inst.Path(CaddyDropInDir)} {
- if !slices.Contains(sources, want) {
- t.Fatalf("edge mounts %v, want %s", sources, want)
- }
- }
-}
-
-func TestOlderRexctlRefusesMovedState(t *testing.T) {
- dir, old := oldLayout(t)
- migrated(t, dir, old)
- data := readTestFile(t, filepath.Join(dir, StateDirName, StateFileName))
- newer := strings.Replace(string(data), fmt.Sprintf(`"schema": %d`, StateSchema), fmt.Sprintf(`"schema": %d`, StateSchema+1), 1)
- if _, err := ParseState([]byte(newer), dir); !errors.Is(err, ErrNewerState) {
- t.Fatalf("got %v, want ErrNewerState", err)
- }
- if !bytes.Contains(data, fmt.Appendf(nil, `"schema": %d`, StateSchema)) || StateSchema <= LayoutSchema {
- t.Fatalf("the moved state has another schema than %d, and an older rexctl would read it", StateSchema)
- }
-}
-
-func TestKeepEditsKeepsOneCopyWithDiff(t *testing.T) {
- dir, old := oldLayout(t)
- inst := migrated(t, dir, old)
- path := inst.Generated(stack.ComposeFile)
- writeTestFile(t, path, append(readTestFile(t, path), []byte("# my change\n")...))
- edits, err := KeepEdits(inst)
- if err != nil || len(edits) != 1 {
- t.Fatalf("edits %v, %v", edits, err)
- }
- if !slices.Contains(edits[0].Diff, "+ # my change") {
- t.Fatalf("diff %q", edits[0].Diff)
- }
- if !strings.HasPrefix(edits[0].Copy, inst.Path(StateDirName, EditedDir)) || !bytes.Equal(readTestFile(t, edits[0].Copy), readTestFile(t, path)) {
- t.Fatalf("copy %s", edits[0].Copy)
- }
- again, err := KeepEdits(inst)
- if err != nil || len(again) != 1 || again[0].Copy != edits[0].Copy {
- t.Fatalf("second copy %v, %v", again, err)
- }
-}
-
-func TestEjectOnTheOldLayoutKeepsTheFiles(t *testing.T) {
- dir, old := oldLayout(t)
- inst, err := Find(dir)
- if err != nil {
- t.Fatal(err)
- }
- if err := Eject(inst, EjectOptions{Rexctl: "test"}); err != nil {
- t.Fatal(err)
- }
- checkOldLayout(t, dir, old)
-}
-
-func TestDropRootCopiesReadsACustomComposeServiceWithNoBody(t *testing.T) {
- dir, old := oldLayout(t)
- inst := migrated(t, dir, old)
- writeTestFile(t, inst.Path(CustomCompose), []byte("services:\n livekit:\n"))
- startedWithGenerated(t, inst)
- if _, err := os.Stat(inst.Path(stack.Caddyfile)); !errors.Is(err, os.ErrNotExist) {
- t.Fatal("kept the Caddyfile though custom.compose.yml mounts nothing")
- }
- writeTestFile(t, inst.Path(stack.Caddyfile), []byte(":443 {\n}\n"))
- writeTestFile(t, inst.Path(CustomCompose), []byte("services:\n livekit:\n edge:\n volumes:\n - ./Caddyfile:/etc/caddy/Caddyfile:ro\n"))
- if !inst.rootMounted(context.Background(), stack.Caddyfile) {
- t.Fatal("missed the Caddyfile that custom.compose.yml mounts next to a service with no body")
- }
-}
diff --git a/fluxer_rexctl/internal/instance/record_test.go b/fluxer_rexctl/internal/instance/record_test.go
deleted file mode 100644
index 3dd459a79..000000000
--- a/fluxer_rexctl/internal/instance/record_test.go
+++ /dev/null
@@ -1,447 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-package instance
-
-import (
- "errors"
- "os"
- "path/filepath"
- "runtime"
- "slices"
- "strings"
- "sync"
- "testing"
-)
-
-func isolateRecords(t *testing.T) string {
- t.Helper()
- home := t.TempDir()
- t.Setenv("HOME", home)
- t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))
- t.Setenv("AppData", filepath.Join(home, "AppData"))
- old := MachineRecordPath
- MachineRecordPath = filepath.Join(t.TempDir(), "etc", "rexctl", RecordFileName)
- t.Cleanup(func() { MachineRecordPath = old })
- oldRoot := asRoot
- asRoot = func() bool { return false }
- t.Cleanup(func() { asRoot = oldRoot })
- t.Chdir(t.TempDir())
- return home
-}
-
-func actAsRoot(t *testing.T) {
- t.Helper()
- if runtime.GOOS == "windows" {
- t.Skip("there's no machine record on Windows")
- }
- oldRoot, oldUID := asRoot, rootUID
- asRoot, rootUID = func() bool { return true }, os.Getuid()
- t.Cleanup(func() { asRoot, rootUID = oldRoot, oldUID })
-}
-
-func managedAt(t *testing.T, dir string) string {
- t.Helper()
- inst, err := Create(dir, "fluxer")
- if err != nil {
- t.Fatal(err)
- }
- if err := inst.Save(); err != nil {
- t.Fatal(err)
- }
- if err := os.Chmod(inst.Dir, 0o755); err != nil {
- t.Fatal(err)
- }
- return clean(inst.Dir)
-}
-
-func record(t *testing.T, s Scope, r Record) {
- t.Helper()
- if err := SaveRecord(s, r); err != nil {
- t.Fatal(err)
- }
-}
-
-func remember(t *testing.T, s Scope, dir string, makeDefault bool) {
- t.Helper()
- if err := Remember(s, dir, makeDefault); err != nil {
- t.Fatal(err)
- }
-}
-
-func TestResolveOrder(t *testing.T) {
- isolateRecords(t)
- here := managedAt(t, t.TempDir())
- saved := managedAt(t, t.TempDir())
- record(t, ScopeUser, Record{Default: saved, Instances: []string{saved}})
- elsewhere, _ := os.Getwd()
-
- t.Chdir(here)
- if l, _ := Resolve("/srv/other"); l.From != FromFlag || l.Dir != "/srv/other" {
- t.Errorf("with --dir = %+v", l)
- }
- if l, _ := Resolve(""); l.From != FromWorkdir || clean(l.Dir) != here {
- t.Errorf("inside an instance = %+v", l)
- }
- t.Chdir(elsewhere)
- if l, _ := Resolve(""); l.From != FromRecord || l.Dir != saved {
- t.Errorf("with a record = %+v", l)
- }
- record(t, ScopeUser, Record{})
- fallback, _ := Fallback()
- if l, _ := Resolve(""); l.From != FromFallback || l.Dir != fallback {
- t.Errorf("with nothing recorded = %+v, want %s", l, fallback)
- }
-}
-
-func TestResolveSeveralAsks(t *testing.T) {
- isolateRecords(t)
- a, b := managedAt(t, t.TempDir()), managedAt(t, t.TempDir())
- record(t, ScopeUser, Record{Instances: []string{a, b}})
- _, err := Resolve("")
- var several *SeveralError
- if !errors.As(err, &several) || !slices.Equal(several.Dirs, []string{a, b}) {
- t.Errorf("err = %v", err)
- }
-}
-
-func TestOnlyRecordSaysSo(t *testing.T) {
- isolateRecords(t)
- dir := managedAt(t, t.TempDir())
- record(t, ScopeUser, Record{Instances: []string{dir}})
- l, err := Resolve("")
- if err != nil || l.Dir != dir || l.Why() != "the only instance rexctl remembers" {
- t.Errorf("Resolve = %+v (%s), %v", l, l.Why(), err)
- }
-}
-
-func TestStaleDefaultUsesTheLiveOne(t *testing.T) {
- isolateRecords(t)
- old, live := managedAt(t, t.TempDir()), managedAt(t, t.TempDir())
- record(t, ScopeUser, Record{Default: old, Instances: []string{old, live}})
- if err := os.RemoveAll(old); err != nil {
- t.Fatal(err)
- }
- l, err := Resolve("")
- if err != nil || l.Dir != live || l.Stale != old {
- t.Errorf("Resolve = %+v, %v", l, err)
- }
-}
-
-func TestStaleDefaultWithSeveralListsThem(t *testing.T) {
- isolateRecords(t)
- old, a, b := managedAt(t, t.TempDir()), managedAt(t, t.TempDir()), managedAt(t, t.TempDir())
- record(t, ScopeUser, Record{Default: old, Instances: []string{old, a, b}})
- if err := os.RemoveAll(old); err != nil {
- t.Fatal(err)
- }
- _, err := Resolve("")
- var several *SeveralError
- if !errors.As(err, &several) || !slices.Equal(several.Dirs, []string{a, b}) || several.Stale != old {
- t.Errorf("err = %+v", err)
- }
-}
-
-func TestAllGoneFallsBackAndForgets(t *testing.T) {
- isolateRecords(t)
- dir := managedAt(t, t.TempDir())
- remember(t, ScopeUser, dir, false)
- if err := os.RemoveAll(dir); err != nil {
- t.Fatal(err)
- }
- l, err := Resolve("")
- if fb, _ := Fallback(); err != nil || l.From != FromFallback || l.Dir != fb || l.Stale != "" {
- t.Errorf("Resolve = %+v, %v", l, err)
- }
- if r := ReadRecord(ScopeUser); !r.Empty() {
- t.Errorf("record kept %+v", r)
- }
-}
-
-func TestOnlyAChosenStaleDefaultIsKept(t *testing.T) {
- isolateRecords(t)
- chosen := managedAt(t, t.TempDir())
- remember(t, ScopeUser, chosen, true)
- if err := os.RemoveAll(chosen); err != nil {
- t.Fatal(err)
- }
- l, err := Resolve("")
- if err != nil || l.From != FromFallback || l.Stale != chosen || !l.Chosen {
- t.Errorf("chosen: Resolve = %+v, %v", l, err)
- }
- if l, _ := Resolve(""); l.Stale != chosen {
- t.Errorf("the chosen default was forgotten: %+v", l)
- }
-
- auto, other := managedAt(t, t.TempDir()), managedAt(t, t.TempDir())
- record(t, ScopeUser, Record{})
- remember(t, ScopeUser, auto, false)
- remember(t, ScopeUser, other, false)
- if r := ReadRecord(ScopeUser); r.Default != auto || r.Used {
- t.Fatalf("record %+v", r)
- }
- if err := os.RemoveAll(auto); err != nil {
- t.Fatal(err)
- }
- if l, err := Resolve(""); err != nil || l.Chosen || l.Dir != other {
- t.Errorf("automatic: Resolve = %+v, %v", l, err)
- }
-}
-
-func TestRememberKeepsTheFirstAsDefault(t *testing.T) {
- isolateRecords(t)
- first, second := managedAt(t, t.TempDir()), managedAt(t, t.TempDir())
- remember(t, ScopeUser, first, false)
- remember(t, ScopeUser, second, false)
- if l, err := Resolve(""); err != nil || l.Dir != first {
- t.Errorf("Resolve = %+v, %v", l, err)
- }
-}
-
-func voiceMachineAt(t *testing.T, dir string) string {
- t.Helper()
- inst, err := Create(dir, "fluxer-voice")
- if err != nil {
- t.Fatal(err)
- }
- inst.State.Kind = KindVoice
- if err := inst.Save(); err != nil {
- t.Fatal(err)
- }
- return clean(inst.Dir)
-}
-
-func TestRememberDoesNotMakeAVoiceMachineTheDefault(t *testing.T) {
- isolateRecords(t)
- machine, fluxer := voiceMachineAt(t, t.TempDir()), managedAt(t, t.TempDir())
- remember(t, ScopeUser, machine, false)
- if r := ReadRecord(ScopeUser); r.Default != "" {
- t.Fatalf("a lone voice machine became the default: %+v", r)
- }
- remember(t, ScopeUser, fluxer, false)
- r := ReadRecord(ScopeUser)
- if r.Default != fluxer || !slices.Equal(r.Instances, []string{machine, fluxer}) {
- t.Fatalf("record = %+v", r)
- }
- second := voiceMachineAt(t, t.TempDir())
- remember(t, ScopeUser, second, false)
- if l, err := Resolve(""); err != nil || l.Dir != fluxer {
- t.Errorf("Resolve = %+v, %v", l, err)
- }
-}
-
-func TestRememberTakesTheDefaultFromItsOwnScope(t *testing.T) {
- isolateRecords(t)
- machine := managedAt(t, t.TempDir())
- record(t, ScopeMachine, Record{Instances: []string{machine}})
- first, second := managedAt(t, t.TempDir()), managedAt(t, t.TempDir())
- remember(t, ScopeUser, first, false)
- remember(t, ScopeUser, second, false)
- r := ReadRecord(ScopeUser)
- if r.Default != first || !slices.Equal(r.Instances, []string{first, second}) {
- t.Errorf("user record = %+v", r)
- }
-}
-
-func TestRememberFirstKeepsStandardFolder(t *testing.T) {
- home := isolateRecords(t)
- standard := managedAt(t, filepath.Join(home, "fluxer"))
- other := managedAt(t, t.TempDir())
- if fb, _ := Fallback(); clean(fb) != standard {
- t.Skipf("the standard folder here is %s", fb)
- }
- if err := RememberFirst(ScopeUser, other); err != nil {
- t.Fatal(err)
- }
- if r := ReadRecord(ScopeUser); r.Default != standard || !slices.Equal(r.Instances, []string{standard, other}) {
- t.Errorf("record = %+v", r)
- }
-}
-
-func TestRememberFirstLooksOnlyAtItsOwnScope(t *testing.T) {
- isolateRecords(t)
- machine := managedAt(t, t.TempDir())
- record(t, ScopeMachine, Record{Default: machine, Instances: []string{machine}})
- mine := managedAt(t, t.TempDir())
- if err := RememberFirst(ScopeUser, mine); err != nil {
- t.Fatal(err)
- }
- if r := ReadRecord(ScopeUser); !slices.Equal(r.Instances, []string{mine}) {
- t.Errorf("user record = %+v", r)
- }
- if l, err := Resolve(""); err != nil || l.Dir != mine {
- t.Errorf("Resolve = %+v, %v", l, err)
- }
-}
-
-func TestStandardFolderComesBeforeTheMachineRecord(t *testing.T) {
- home := isolateRecords(t)
- if asRoot() {
- t.Skip("runs as root")
- }
- standard := managedAt(t, filepath.Join(home, "fluxer"))
- machine := managedAt(t, t.TempDir())
- record(t, ScopeMachine, Record{Default: machine, Instances: []string{machine}})
- if l, err := Resolve(""); err != nil || clean(l.Dir) != standard || l.From != FromFallback {
- t.Errorf("Resolve = %+v, %v", l, err)
- }
-}
-
-func TestMachineRecordSkipsInstancesYouCantRead(t *testing.T) {
- isolateRecords(t)
- if runtime.GOOS == "windows" || os.Geteuid() == 0 {
- t.Skip("needs file permissions that keep this account out")
- }
- theirs := managedAt(t, t.TempDir())
- record(t, ScopeMachine, Record{Default: theirs, Instances: []string{theirs}})
- if err := os.Chmod(filepath.Join(theirs, StateDirName), 0); err != nil {
- t.Fatal(err)
- }
- t.Cleanup(func() { os.Chmod(filepath.Join(theirs, StateDirName), 0o700) })
- if l, err := Resolve(""); err != nil || l.From != FromFallback {
- t.Errorf("Resolve = %+v, %v", l, err)
- }
-}
-
-func TestRootIgnoresTheUserRecord(t *testing.T) {
- isolateRecords(t)
- user := managedAt(t, t.TempDir())
- record(t, ScopeUser, Record{Default: user, Instances: []string{user}})
- actAsRoot(t)
- if l, err := Resolve(""); err != nil || l.From != FromFallback {
- t.Errorf("only a user record: Resolve = %+v, %v", l, err)
- }
- machine := managedAt(t, t.TempDir())
- if OwnScope() != ScopeMachine {
- t.Fatal("root records in the user scope")
- }
- remember(t, OwnScope(), machine, false)
- if l, err := Resolve(""); err != nil || l.Dir != machine || l.Scope != ScopeMachine {
- t.Errorf("Resolve = %+v, %v", l, err)
- }
- if err := Remember(ScopeUser, user, true); err == nil {
- t.Error("root wrote a user record")
- }
-}
-
-func TestRootRefusesRecordsOthersCanChange(t *testing.T) {
- isolateRecords(t)
- actAsRoot(t)
- dir := managedAt(t, t.TempDir())
- remember(t, ScopeMachine, dir, true)
- if l, err := Resolve(""); err != nil || l.Dir != dir {
- t.Fatalf("Resolve = %+v, %v", l, err)
- }
- if err := os.Chmod(MachineRecordPath, 0o666); err != nil {
- t.Fatal(err)
- }
- var untrusted *UntrustedError
- if _, err := Resolve(""); !errors.As(err, &untrusted) || untrusted.Path != MachineRecordPath {
- t.Errorf("writable record: err = %v", err)
- }
- if err := os.Chmod(MachineRecordPath, 0o644); err != nil {
- t.Fatal(err)
- }
- if err := os.Chmod(dir, 0o777); err != nil {
- t.Fatal(err)
- }
- if _, err := Resolve(""); !errors.As(err, &untrusted) || !untrusted.Folder || clean(untrusted.Path) != dir {
- t.Errorf("writable folder: err = %v", err)
- }
- rootUID = os.Getuid() + 1
- if _, err := Resolve(""); !errors.As(err, &untrusted) || untrusted.Folder {
- t.Errorf("record owned by another account: err = %v", err)
- }
-}
-
-func TestSymlinkRecordsTheSameInstance(t *testing.T) {
- isolateRecords(t)
- dir := managedAt(t, t.TempDir())
- link := filepath.Join(t.TempDir(), "link")
- if err := os.Symlink(dir, link); err != nil {
- t.Skip(err)
- }
- remember(t, ScopeUser, dir, false)
- remember(t, ScopeUser, link, false)
- if r := ReadRecord(ScopeUser); !slices.Equal(r.Instances, []string{dir}) {
- t.Errorf("record = %+v", r)
- }
-}
-
-func TestSameIgnoresCaseOnWindows(t *testing.T) {
- if runtime.GOOS != "windows" {
- t.Skip("only Windows paths ignore case")
- }
- if !same(`C:\Fluxer`, `c:\fluxer`) {
- t.Error("the same folder in another case counts as another instance")
- }
-}
-
-func TestRememberAtTheSameTimeKeepsEveryInstance(t *testing.T) {
- isolateRecords(t)
- var dirs []string
- for range 12 {
- dirs = append(dirs, managedAt(t, t.TempDir()))
- }
- var wg sync.WaitGroup
- errs := make(chan error, len(dirs))
- for _, d := range dirs {
- wg.Go(func() { errs <- Remember(ScopeUser, d, false) })
- }
- wg.Wait()
- close(errs)
- for err := range errs {
- if err != nil {
- t.Fatal(err)
- }
- }
- got := ReadRecord(ScopeUser).Instances
- for _, d := range dirs {
- if !slices.Contains(got, d) {
- t.Fatalf("lost %s, record has %d of %d", d, len(got), len(dirs))
- }
- }
-}
-
-func TestUserRecordLivesInHome(t *testing.T) {
- home := isolateRecords(t)
- want := map[string]string{
- "linux": filepath.Join(home, ".config"),
- "darwin": filepath.Join(home, "Library", "Application Support"),
- "windows": filepath.Join(home, "AppData"),
- }[runtime.GOOS]
- if want == "" {
- t.Skipf("no known config folder on %s", runtime.GOOS)
- }
- want = filepath.Join(want, "rexctl", RecordFileName)
- if got := RecordPath(ScopeUser); got != want || !strings.HasPrefix(got, home) {
- t.Fatalf("user record = %s, want %s", got, want)
- }
- dir := managedAt(t, t.TempDir())
- record(t, ScopeUser, Record{Instances: []string{dir}})
- if _, err := os.Stat(want); err != nil {
- t.Fatal(err)
- }
- if l, err := Resolve(""); err != nil || l.Dir != dir || l.Scope != ScopeUser {
- t.Errorf("Resolve = %+v, %v", l, err)
- }
-}
-
-func TestRootLooksInItsOwnHomeNotHOME(t *testing.T) {
- home := isolateRecords(t)
- actAsRoot(t)
- rootsHome := t.TempDir()
- prev := rootHome
- rootHome = func() (string, error) { return rootsHome, nil }
- t.Cleanup(func() { rootHome = prev })
- theirs := managedAt(t, filepath.Join(home, "fluxer"))
- if fb, err := Fallback(); err != nil || same(fb, theirs) {
- t.Fatalf("root followed $HOME to %s, %v", fb, err)
- }
- if l, err := Resolve(""); err != nil || same(l.Dir, theirs) {
- t.Fatalf("Resolve = %+v, %v", l, err)
- }
- mine := managedAt(t, filepath.Join(rootsHome, "fluxer"))
- if fb, err := Fallback(); err != nil || !same(fb, mine) {
- t.Fatalf("Fallback = %s, %v, want root's own %s", fb, err, mine)
- }
-}
diff --git a/fluxer_rexctl/internal/instance/sites_test.go b/fluxer_rexctl/internal/instance/sites_test.go
deleted file mode 100644
index 6e3bd058e..000000000
--- a/fluxer_rexctl/internal/instance/sites_test.go
+++ /dev/null
@@ -1,271 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-package instance
-
-import (
- "context"
- "os"
- "path/filepath"
- "slices"
- "strings"
- "testing"
-
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/engine"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/secrets"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/settings"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/stack"
-)
-
-const mastodonSites = `mastodon.tails.ch {
- tls internal
- reverse_proxy 10.0.4.22:3000
-}
-
-tails.ch {
- tls internal
- respond "hello {http.request.host}"
-}
-`
-
-func TestDefinesSite(t *testing.T) {
- for _, tc := range []struct {
- label string
- file string
- want bool
- }{
- {"two site blocks", mastodonSites, true},
- {"site list with commas", "a.example.com, b.example.com {\n\trespond ok\n}\n", true},
- {"site list over two lines", "a.example.com,\nb.example.com {\n\trespond ok\n}\n", true},
- {"port only", ":8443 {\n\trespond ok\n}\n", true},
- {"scheme and localhost", "http://localhost {\n\trespond ok\n}\n", true},
- {"single label with port", "intranet:8080 {\n\trespond ok\n}\n", true},
- {"ipv6 address", "[::1]:8080 {\n\trespond ok\n}\n", true},
- {"wildcard host", "*.example.com {\n\trespond ok\n}\n", true},
- {"snippet", "(cors) {\n\theader Access-Control-Allow-Origin *\n}\n", false},
- {"global options", "{\n\temail [email protected]\n}\n", false},
- {"plain directives", "header X-Mine yes\nencode gzip\n", false},
- {"directive blocks", "handle /extra/* {\n\trespond ok\n}\nreverse_proxy 10.0.4.22:3000 {\n\theader_up Host {host}\n}\nroute {\n\trespond ok\n}\n", false},
- {"matcher block", "@blocked {\n\tpath /secret/*\n}\nrespond @blocked 403\n", false},
- {"comment with a site", "# mastodon.tails.ch {\n# }\nheader X-Mine yes\n", false},
- {"brace inside a string", "respond \"example.com {\"\nheader X-Mine yes\n", false},
- {"backtick string", "respond `a.example.com {\n}`\n", false},
- {"import line", "import /etc/caddy/extra/*.caddy\n", false},
- {"env placeholder key", "{$MASTODON_HOST} {\n\treverse_proxy 10.0.4.22:3000\n}\n", false},
- {"env placeholder in host", "{$SUB}.example.com {\n\trespond ok\n}\n", false},
- {"placeholder inside a directive", "respond \"{system.hostname}\" 200\n", false},
- {"heredoc", "respond <<EOF\n\texample.com {\n\tEOF\n", false},
- {"unbalanced braces", "example.com {\n\trespond ok\n", false},
- } {
- if got := DefinesSite([]byte(tc.file)); got != tc.want {
- t.Errorf("%s: DefinesSite = %v, want %v", tc.label, got, tc.want)
- }
- }
-}
-
-func TestOnlySites(t *testing.T) {
- for _, tc := range []struct {
- label string
- file string
- want bool
- }{
- {"two site blocks", mastodonSites, true},
- {"sites and a snippet", "(common) {\n\tencode gzip\n}\n" + mastodonSites, true},
- {"sites with comments", "# my sites\n" + mastodonSites + "# end\n", true},
- {"site and global options", "{\n\temail [email protected]\n}\n" + mastodonSites, false},
- {"site and import line", "import common.caddy\n" + mastodonSites, false},
- {"site and directive", "header X-Mine yes\n" + mastodonSites, false},
- {"snippet only", "(cors) {\n\theader Access-Control-Allow-Origin *\n}\n", false},
- {"env placeholder key", "{$MASTODON_HOST} {\n\treverse_proxy 10.0.4.22:3000\n}\n", false},
- {"empty file", "", false},
- } {
- if got := onlySites([]byte(tc.file)); got != tc.want {
- t.Errorf("%s: onlySites = %v, want %v", tc.label, got, tc.want)
- }
- }
-}
-
-func TestMoveSitesMovesOnlySiteFiles(t *testing.T) {
- inst, err := Create(t.TempDir(), "fluxer")
- if err != nil {
- t.Fatal(err)
- }
- files := map[string]string{
- "Mastodon.caddy": mastodonSites,
- "headers.caddy": "header X-Mine yes\n",
- "mixed.caddy": "header X-Mine yes\n" + mastodonSites,
- "env.caddy": "{$MASTODON_HOST} {\n\treverse_proxy 10.0.4.22:3000\n}\n",
- "notes.txt": mastodonSites,
- "taken.caddy": mastodonSites,
- }
- for f, data := range files {
- writeTestFile(t, inst.Path(CaddyDropInDir, f), []byte(data))
- }
- writeTestFile(t, inst.Path(CaddySitesDir, "taken.caddy"), []byte("other.example.com {\n}\n"))
- moved, err := inst.MoveSites()
- if err != nil {
- t.Fatal(err)
- }
- if !slices.Equal(moved, []string{"Mastodon.caddy"}) {
- t.Fatalf("moved %v, want [Mastodon.caddy]", moved)
- }
- if got := string(readTestFile(t, inst.Path(CaddySitesDir, "Mastodon.caddy"))); got != mastodonSites {
- t.Fatalf("moved file %q", got)
- }
- for f := range files {
- _, err := os.Stat(inst.Path(CaddyDropInDir, f))
- if gone := os.IsNotExist(err); gone != (f == "Mastodon.caddy") {
- t.Errorf("%s left in caddy.d = %v", f, !gone)
- }
- }
- if again, err := inst.MoveSites(); err != nil || len(again) > 0 {
- t.Fatalf("second run moved %v, %v", again, err)
- }
- if err := inst.PutBackSites(moved); err != nil {
- t.Fatal(err)
- }
- if got := string(readTestFile(t, inst.Path(CaddyDropInDir, "Mastodon.caddy"))); got != mastodonSites {
- t.Fatalf("put back %q", got)
- }
- if _, err := os.Stat(inst.Path(CaddySitesDir, "Mastodon.caddy")); !os.IsNotExist(err) {
- t.Fatal("the site file is still in caddy.d/sites")
- }
-}
-
-func TestMoveSitesWithoutDropInFolder(t *testing.T) {
- inst := &Instance{Dir: filepath.Join(t.TempDir(), "missing")}
- moved, err := inst.MoveSites()
- if err != nil || moved != nil {
- t.Fatalf("got %v, %v", moved, err)
- }
-}
-
-func TestShippedCaddyfileImportsSitesAtTopLevel(t *testing.T) {
- data, err := stack.ReadFile(stack.Embedded(), stack.Caddyfile)
- if err != nil {
- t.Fatal(err)
- }
- entries, ok := caddyEntries(data)
- if !ok {
- t.Fatal("the shipped Caddyfile doesn't parse")
- }
- var top []string
- for _, e := range entries {
- if !e.block {
- var keys []string
- for _, k := range e.keys {
- keys = append(keys, k.text)
- }
- top = append(top, strings.Join(keys, " "))
- }
- }
- if !slices.Contains(top, "import /etc/caddy/conf.d/sites/*.caddy") {
- t.Fatalf("top level lines %q, want the sites import", top)
- }
- if slices.Contains(top, "import /etc/caddy/conf.d/*.caddy") {
- t.Fatal("caddy.d directives load at the top level")
- }
- if !strings.Contains(string(data), "\timport /etc/caddy/conf.d/*.caddy\n") {
- t.Fatal("caddy.d directives no longer load inside the site")
- }
-}
-
-func TestEdgeMountsCoverSitesFolder(t *testing.T) {
- for _, mode := range []string{"", "proxy", "tunnel"} {
- inst, err := Create(t.TempDir(), "fluxer")
- if err != nil {
- t.Fatal(err)
- }
- if _, err := os.Stat(inst.Path(CaddySitesDir)); err != nil {
- t.Fatalf("Create made no %s: %v", CaddySitesDir, err)
- }
- set := stack.Embedded()
- inst.State.Release = set.Release
- inst.State.Images = Images{Release: set.Release, Refs: fluxerRefs("a")}
- inst.State.Settings[settings.Domain] = "chat.example.com"
- if mode != "" {
- inst.State.Settings[settings.EdgeMode] = mode
- }
- if _, err := secrets.Mint(inst.State.Secrets, false); err != nil {
- t.Fatal(err)
- }
- if _, err := inst.Render(set, stack.OverlaysFor(inst.State.Settings), inst.State.Images.Refs); err != nil {
- t.Fatal(err)
- }
- env, err := inst.Environment()
- if err != nil {
- t.Fatal(err)
- }
- var none engine.Engine
- p, err := none.Load(context.Background(), engine.Spec{Name: "fluxer", Dir: inst.Dir, Files: inst.ComposeFiles(), Env: env})
- if err != nil {
- t.Fatalf("%q: %v", mode, err)
- }
- o := p.HelperFor("edge")
- if o.Image == "" {
- t.Fatalf("%q: no edge image", mode)
- }
- want := map[string]string{"/etc/caddy/Caddyfile": inst.Generated(stack.Caddyfile), "/etc/caddy/conf.d": inst.Path(CaddyDropInDir)}
- for _, m := range o.Mounts {
- if src, ok := want[m.Target]; ok && m.Bind == src {
- delete(want, m.Target)
- }
- }
- if len(want) > 0 {
- t.Fatalf("%q: edge mounts %v, missing %v", mode, o.Mounts, want)
- }
- if !slices.ContainsFunc(o.Env, func(kv string) bool { return strings.HasPrefix(kv, "FLUXER_EDGE_SITE_ADDRESS=") }) {
- t.Fatalf("%q: edge env %v", mode, o.Env)
- }
- }
-}
-
-func TestTopLevelImports(t *testing.T) {
- shipped, err := stack.ReadFile(stack.Embedded(), stack.Caddyfile)
- if err != nil {
- t.Fatal(err)
- }
- for _, tc := range []struct {
- label string
- file string
- sites, dropIns bool
- }{
- {"shipped Caddyfile", string(shipped), true, false},
- {"legacy Caddyfile", "{\n\temail [email protected]\n}\nimport /etc/caddy/conf.d/*.caddy\n{$FLUXER_DOMAIN} {\n\treverse_proxy app:8080\n}\n", false, true},
- {"nested drop-ins only", "example.com {\n\timport /etc/caddy/conf.d/*.caddy\n}\n", false, false},
- {"commented sites import", "# import /etc/caddy/conf.d/sites/*.caddy\nexample.com {\n}\n", false, false},
- {"snippet import", "(x) {\n}\nimport x\n", false, false},
- } {
- sites, dropIns := TopLevelImports([]byte(tc.file))
- if sites != tc.sites || dropIns != tc.dropIns {
- t.Errorf("%s: TopLevelImports = %v, %v, want %v, %v", tc.label, sites, dropIns, tc.sites, tc.dropIns)
- }
- }
-}
-
-func TestUnloadAndRestoreSites(t *testing.T) {
- inst, err := Create(t.TempDir(), "fluxer")
- if err != nil {
- t.Fatal(err)
- }
- writeTestFile(t, inst.Path(CaddySitesDir, "a.caddy"), []byte(mastodonSites))
- writeTestFile(t, inst.Path(CaddySitesDir, "b.caddy"), []byte(mastodonSites))
- writeTestFile(t, inst.Path(CaddySitesDir, "notes.txt"), []byte("x\n"))
- writeTestFile(t, inst.Path(CaddyDropInDir, "b.caddy"), []byte("header X-Mine yes\n"))
- moved, err := inst.UnloadSites()
- if err != nil {
- t.Fatal(err)
- }
- if !slices.Equal(moved, []string{"a.caddy"}) {
- t.Fatalf("unloaded %v, want [a.caddy]", moved)
- }
- back, err := inst.RestoreSites([]string{"a.caddy", "missing.caddy"})
- if err != nil {
- t.Fatal(err)
- }
- if !slices.Equal(back, []string{"a.caddy"}) {
- t.Fatalf("restored %v, want [a.caddy]", back)
- }
- if got := string(readTestFile(t, inst.Path(CaddySitesDir, "a.caddy"))); got != mastodonSites {
- t.Fatalf("restored file %q", got)
- }
-}
diff --git a/fluxer_rexctl/internal/instance/state_test.go b/fluxer_rexctl/internal/instance/state_test.go
deleted file mode 100644
index 8df7882af..000000000
--- a/fluxer_rexctl/internal/instance/state_test.go
+++ /dev/null
@@ -1,34 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-package instance
-
-import (
- "slices"
- "testing"
-)
-
-func TestStateKnowsPreviousBackup(t *testing.T) {
- inst, err := Create(t.TempDir(), "fluxer")
- if err != nil {
- t.Fatal(err)
- }
- inst.State.PreviousRelease = "2026.1020.100000"
- inst.State.PreviousBackup = "/opt/fluxer/backups/fluxer-chat.example.com-20261025-040000.tar.zst"
- if err := inst.Save(); err != nil {
- t.Fatal(err)
- }
- again, err := Find(inst.Dir)
- if err != nil {
- t.Fatal(err)
- }
- if again.State.PreviousBackup != inst.State.PreviousBackup {
- t.Errorf("PreviousBackup = %q, want %q", again.State.PreviousBackup, inst.State.PreviousBackup)
- }
- if slices.Contains(again.State.Unknown, "previous_backup") {
- t.Errorf("previous_backup reads as an unknown setting in %v", again.State.Unknown)
- }
- s, err := ParseState([]byte(`{"schema":1,"project":"fluxer","previous_release":"2026.1020.100000"}`), inst.Dir)
- if err != nil || s.PreviousBackup != "" {
- t.Errorf("older state = %+v, %v", s, err)
- }
-}
diff --git a/fluxer_rexctl/internal/objectstore/objectstore_test.go b/fluxer_rexctl/internal/objectstore/objectstore_test.go
deleted file mode 100644
index dcf6e3c66..000000000
--- a/fluxer_rexctl/internal/objectstore/objectstore_test.go
+++ /dev/null
@@ -1,57 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-package objectstore
-
-import (
- "crypto/tls"
- "crypto/x509"
- "errors"
- "net/url"
- "testing"
-)
-
-func TestClassify(t *testing.T) {
- cases := []struct {
- name string
- status int
- code string
- message string
- want Problem
- }{
- {"aws wrong secret", 403, "SignatureDoesNotMatch", "The request signature we calculated does not match the signature you provided. Check your key and signing method.", Credentials},
- {"aws unknown key", 403, "InvalidAccessKeyId", "The AWS Access Key Id you provided does not exist in our records.", Credentials},
- {"aws denied", 403, "AccessDenied", "Access Denied", Denied},
- {"aws wrong region", 400, "AuthorizationHeaderMalformed", "The authorization header is malformed; the region 'us-east-1' is wrong; expecting 'eu-west-1'", WrongRegion},
- {"aws missing bucket", 404, "NoSuchBucket", "The specified bucket does not exist", MissingBuckets},
- {"garage wrong secret", 403, "AccessDenied", "Forbidden: Invalid signature", Credentials},
- {"garage unknown key", 403, "AccessDenied", "Forbidden: No such key: GK0123456789abcdef", Credentials},
- {"garage denied", 403, "AccessDenied", "Forbidden: Operation is not allowed for this key.", Denied},
- {"r2 malformed key", 400, "InvalidArgument", "Credential access key has length 3, should be 32", Credentials},
- {"r2 unauthorized", 401, "Unauthorized", "Unauthorized", Credentials},
- {"b2 unknown key", 403, "InvalidAccessKeyId", "Malformed Access Key Id", Credentials},
- {"head missing bucket", 404, "404 Not Found", "", MissingBuckets},
- }
- for _, c := range cases {
- if got := classify(c.status, c.code, c.message); got != c.want {
- t.Errorf("%s: got %d, want %d", c.name, got, c.want)
- }
- }
-}
-
-func TestTransportProblem(t *testing.T) {
- cases := []struct {
- name string
- err error
- want Problem
- }{
- {"unknown authority", &url.Error{Op: "Put", Err: &tls.CertificateVerificationError{Err: x509.UnknownAuthorityError{}}}, Untrusted},
- {"wrong name", &url.Error{Op: "Put", Err: &tls.CertificateVerificationError{Err: x509.HostnameError{Certificate: &x509.Certificate{}, Host: "s3.example.com"}}}, WrongName},
- {"expired", &url.Error{Op: "Put", Err: x509.CertificateInvalidError{Reason: x509.Expired}}, Untrusted},
- {"refused", &url.Error{Op: "Put", Err: errors.New("connection refused")}, Unreachable},
- }
- for _, c := range cases {
- if got := transportProblem(c.err); got != c.want {
- t.Errorf("%s: got %d, want %d", c.name, got, c.want)
- }
- }
-}
diff --git a/fluxer_rexctl/internal/release/files_test.go b/fluxer_rexctl/internal/release/files_test.go
deleted file mode 100644
index 1d294ec3d..000000000
--- a/fluxer_rexctl/internal/release/files_test.go
+++ /dev/null
@@ -1,89 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-package release
-
-import (
- "os"
- "path/filepath"
- "slices"
- "testing"
-
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/instance"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/stack"
-)
-
-func TestPruneReleases(t *testing.T) {
- images := map[string][]string{
- stack.LegacyRelease: {"fluxer:legacy", "postgres:16"},
- "2026.1.0": {"fluxer:1", "postgres:17"},
- "2026.2.0": {"fluxer:2", "postgres:17"},
- "2026.3.0": {"fluxer:3", "postgres:17"},
- "2026.4.0": {"fluxer:4", "postgres:17"},
- }
- cases := []struct {
- name string
- state instance.State
- remove []string
- kept []string
- legacyOn bool
- }{
- {
- name: "current and previous",
- state: instance.State{Release: "2026.4.0", PreviousRelease: "2026.3.0"},
- remove: []string{"fluxer:1", "fluxer:2", "fluxer:legacy", "postgres:16"},
- kept: []string{"2026.3.0", "2026.4.0"},
- },
- {
- name: "legacy is the rollback target",
- state: instance.State{Release: "2026.1.0", PreviousRelease: stack.LegacyRelease},
- remove: []string{"fluxer:2", "fluxer:3", "fluxer:4"},
- kept: []string{"2026.1.0"},
- legacyOn: true,
- },
- {
- name: "unfinished upgrade",
- state: instance.State{Release: "2026.2.0", PreviousRelease: "2026.1.0",
- Upgrade: &instance.Upgrade{From: "2026.2.0", To: "2026.4.0"}},
- remove: []string{"fluxer:3", "fluxer:legacy", "postgres:16"},
- kept: []string{"2026.1.0", "2026.2.0", "2026.4.0"},
- },
- }
- for _, tc := range cases {
- t.Run(tc.name, func(t *testing.T) {
- inst := &instance.Instance{Dir: t.TempDir(), State: &tc.state}
- for v, refs := range images {
- if err := writeImages(Dir(inst, v), v, refs); err != nil {
- t.Fatal(err)
- }
- }
- remove, err := pruneReleases(inst)
- if err != nil {
- t.Fatal(err)
- }
- slices.Sort(remove)
- if !slices.Equal(remove, tc.remove) {
- t.Errorf("removed images %v, want %v", remove, tc.remove)
- }
- entries, err := os.ReadDir(filepath.Dir(Dir(inst, stack.LegacyRelease)))
- if err != nil {
- t.Fatal(err)
- }
- var dirs []string
- for _, d := range entries {
- if d.Name() != stack.LegacyRelease {
- dirs = append(dirs, d.Name())
- }
- }
- if !slices.Equal(dirs, tc.kept) {
- t.Errorf("release folders %v, want %v", dirs, tc.kept)
- }
- refs, err := Images(inst, stack.LegacyRelease)
- if tc.legacyOn != (err == nil && len(refs) > 0) {
- t.Errorf("legacy images %v (%v), want kept %v", refs, err, tc.legacyOn)
- }
- if !exists(Dir(inst, stack.LegacyRelease)) {
- t.Error("the legacy folder was removed")
- }
- })
- }
-}
diff --git a/fluxer_rexctl/internal/settings/keys_test.go b/fluxer_rexctl/internal/settings/keys_test.go
deleted file mode 100644
index 22f48d941..000000000
--- a/fluxer_rexctl/internal/settings/keys_test.go
+++ /dev/null
@@ -1,27 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-package settings
-
-import (
- "errors"
- "testing"
-
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/stack"
-)
-
-func TestSSOPrivateAddressesIsANamedSetting(t *testing.T) {
- set := stack.Embedded()
- if _, err := Lookup(set, nil, SSOPrivate, nil); err != nil {
- t.Fatalf("Lookup(%s) = %v", SSOPrivate, err)
- }
- if _, err := Lookup(set, nil, "FLUXER_SSO_ALLOW_PRIVATE_ADDRESSES", nil); !errors.Is(err, ErrOtherName) {
- t.Errorf("raw name lookup = %v, want it to point at %s", err, SSOPrivate)
- }
- env, err := Effective(set, map[string]string{SSOPrivate: "true"}, nil, nil)
- if err != nil {
- t.Fatal(err)
- }
- if got := env["FLUXER_SSO_ALLOW_PRIVATE_ADDRESSES"]; got != "true" {
- t.Errorf("FLUXER_SSO_ALLOW_PRIVATE_ADDRESSES = %q, want true", got)
- }
-}
diff --git a/fluxer_rexctl/internal/stack/bundle_test.go b/fluxer_rexctl/internal/stack/bundle_test.go
deleted file mode 100644
index f477509f4..000000000
--- a/fluxer_rexctl/internal/stack/bundle_test.go
+++ /dev/null
@@ -1,41 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-package stack
-
-import (
- "os"
- "path/filepath"
- "strings"
- "testing"
-)
-
-func TestBundlePinsTheVoiceImages(t *testing.T) {
- compose, err := ReadFile(Embedded(), ComposeFile)
- if err != nil {
- t.Fatal(err)
- }
- found, err := imageLines(compose)
- if err != nil {
- t.Fatal(err)
- }
- images := map[string]string{}
- for _, img := range found {
- images[img.service] = "registry.example.com/" + img.service + ":pinned"
- }
- dir := t.TempDir()
- if err := Bundle(dir, images); err != nil {
- t.Fatal(err)
- }
- for file, want := range map[string]string{
- "voice.compose.yml": "${FLUXER_LIVEKIT_IMAGE:-registry.example.com/livekit:pinned}",
- "voice-edge.compose.yml": "${FLUXER_CADDY_IMAGE:-registry.example.com/edge:pinned}",
- } {
- data, err := os.ReadFile(filepath.Join(dir, "voice", file))
- if err != nil {
- t.Fatal(err)
- }
- if !strings.Contains(string(data), want) {
- t.Errorf("%s doesn't pin %s", file, want)
- }
- }
-}
diff --git a/fluxer_rexctl/internal/stack/cacerts_test.go b/fluxer_rexctl/internal/stack/cacerts_test.go
deleted file mode 100644
index a6119e5e3..000000000
--- a/fluxer_rexctl/internal/stack/cacerts_test.go
+++ /dev/null
@@ -1,62 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-package stack
-
-import (
- "slices"
- "strings"
- "testing"
-
- "go.yaml.in/yaml/v4"
-)
-
-func composeVolumes(t *testing.T) map[string][]string {
- t.Helper()
- data, err := ReadFile(Embedded(), "docker-compose.yml")
- if err != nil {
- t.Fatal(err)
- }
- var compose struct {
- Services map[string]struct {
- Volumes []string `yaml:"volumes"`
- } `yaml:"services"`
- }
- if err := yaml.Unmarshal(data, &compose); err != nil {
- t.Fatal(err)
- }
- out := map[string][]string{}
- for name, svc := range compose.Services {
- out[name] = svc.Volumes
- }
- return out
-}
-
-func TestNodeServicesMountOnlyTheCAFolder(t *testing.T) {
- vols := composeVolumes(t)
- want := "./ca:/etc/fluxer/ca:ro"
- for _, svc := range []string{"api", "worker"} {
- if !slices.Contains(vols[svc], want) {
- t.Errorf("%s volumes = %v, want %q so FLUXER_NODE_EXTRA_CA_CERTS can point at a CA file", svc, vols[svc], want)
- }
- for _, v := range vols[svc] {
- if strings.HasPrefix(v, "./certs") {
- t.Errorf("%s mounts %q, which holds the edge TLS private keys", svc, v)
- }
- }
- }
- if !slices.Contains(vols["edge"], "./certs:/certs:ro") {
- t.Errorf("edge volumes = %v, want the certs folder", vols["edge"])
- }
-}
-
-func TestMountedDirsMatchCompose(t *testing.T) {
- vols := composeVolumes(t)
- for dir, services := range MountedDirs {
- for name, mounts := range vols {
- uses := slices.ContainsFunc(mounts, func(v string) bool { return strings.HasPrefix(v, "./"+dir+":") })
- if uses != slices.Contains(services, name) {
- t.Errorf("%s mounts ./%s = %v, but MountedDirs lists %v", name, dir, uses, services)
- }
- }
- }
-}
diff --git a/fluxer_rexctl/internal/stack/generated_test.go b/fluxer_rexctl/internal/stack/generated_test.go
deleted file mode 100644
index b53ccf29e..000000000
--- a/fluxer_rexctl/internal/stack/generated_test.go
+++ /dev/null
@@ -1,54 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-package stack
-
-import (
- "bytes"
- "path/filepath"
- "testing"
-)
-
-func TestManagedFilesRoundTrip(t *testing.T) {
- set := Embedded()
- for _, name := range FileNames() {
- plain, err := ReadFile(set, name)
- if err != nil {
- t.Fatal(err)
- }
- managed := Managed(name, plain)
- if !bytes.HasPrefix(managed, header(name)) {
- t.Fatalf("%s has no header", name)
- }
- if !bytes.Equal(Plain(name, managed), plain) {
- t.Fatalf("%s doesn't come back the same after eject", name)
- }
- }
- compose, err := ReadFile(set, ComposeFile)
- if err != nil {
- t.Fatal(err)
- }
- plain, managed := mountRefs(Caddyfile)
- if !bytes.Contains(compose, plain) || bytes.Contains(Managed(ComposeFile, compose), plain) || !bytes.Contains(Managed(ComposeFile, compose), managed) {
- t.Fatal("the edge service doesn't mount the generated Caddyfile")
- }
-}
-
-func TestProjectDirOfGeneratedComposeFile(t *testing.T) {
- dir := filepath.Join(t.TempDir(), "fluxer")
- for _, f := range []string{filepath.Join(dir, ComposeFile), GeneratedPath(dir, ComposeFile)} {
- if got := ProjectDir(f); got != dir {
- t.Fatalf("ProjectDir(%s) = %s, want %s", f, got, dir)
- }
- }
-}
-
-func TestHeaderSaysHowToChangeTheFile(t *testing.T) {
- for name, want := range map[string]string{
- ComposeFile: "# rexctl writes this file and puts its own version back when it changes Fluxer.\n# To change it, run rexctl config edit.\n\n",
- Caddyfile: "# rexctl writes this file and puts its own version back when it changes Fluxer.\n# To add Caddy directives, put a .caddy file in caddy.d in your instance folder.\n\n",
- } {
- if got := string(header(name)); got != want {
- t.Errorf("%s header %q, want %q", name, got, want)
- }
- }
-}
diff --git a/fluxer_rexctl/internal/stack/livekit_test.go b/fluxer_rexctl/internal/stack/livekit_test.go
deleted file mode 100644
index b94e84b2b..000000000
--- a/fluxer_rexctl/internal/stack/livekit_test.go
+++ /dev/null
@@ -1,78 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-package stack
-
-import (
- "testing"
-
- "github.com/compose-spec/compose-go/v2/template"
- "go.yaml.in/yaml/v4"
-)
-
-type livekitTURNServer struct {
- Host string `yaml:"host"`
- Port int `yaml:"port"`
- Protocol string `yaml:"protocol"`
- Username string `yaml:"username"`
- Credential string `yaml:"credential"`
-}
-
-type livekitConfig struct {
- RTC struct {
- UseExternalIP bool `yaml:"use_external_ip"`
- STUNServers []string `yaml:"stun_servers"`
- TURNServers []livekitTURNServer `yaml:"turn_servers"`
- } `yaml:"rtc"`
-}
-
-func renderLivekitConfig(t *testing.T, env map[string]string) livekitConfig {
- t.Helper()
- data, err := ReadFile(Embedded(), "docker-compose.yml")
- if err != nil {
- t.Fatal(err)
- }
- var compose struct {
- Services map[string]struct {
- Environment map[string]string `yaml:"environment"`
- } `yaml:"services"`
- }
- if err := yaml.Unmarshal(data, &compose); err != nil {
- t.Fatal(err)
- }
- raw, ok := compose.Services["livekit"].Environment["LIVEKIT_CONFIG"]
- if !ok {
- t.Fatal("livekit service has no LIVEKIT_CONFIG")
- }
- rendered, err := template.Substitute(raw, func(k string) (string, bool) {
- v, ok := env[k]
- return v, ok
- })
- if err != nil {
- t.Fatal(err)
- }
- var cfg livekitConfig
- if err := yaml.Unmarshal([]byte(rendered), &cfg); err != nil {
- t.Fatalf("LIVEKIT_CONFIG is not valid YAML: %v\n%s", err, rendered)
- }
- return cfg
-}
-
-func TestLivekitConfigTURNServersFromEnv(t *testing.T) {
- cfg := renderLivekitConfig(t, map[string]string{
- "FLUXER_LIVEKIT_TURN_SERVERS": `[{"host":"turn.example.com","port":3478,"protocol":"udp","username":"u","credential":"p"}]`,
- })
- want := []livekitTURNServer{{Host: "turn.example.com", Port: 3478, Protocol: "udp", Username: "u", Credential: "p"}}
- if len(cfg.RTC.TURNServers) != 1 || cfg.RTC.TURNServers[0] != want[0] {
- t.Errorf("rtc.turn_servers = %+v, want %+v", cfg.RTC.TURNServers, want)
- }
- if !cfg.RTC.UseExternalIP || len(cfg.RTC.STUNServers) != 2 {
- t.Errorf("rtc = %+v, want use_external_ip and two STUN servers kept", cfg.RTC)
- }
-}
-
-func TestLivekitConfigNoTURNServersByDefault(t *testing.T) {
- cfg := renderLivekitConfig(t, nil)
- if len(cfg.RTC.TURNServers) != 0 {
- t.Errorf("rtc.turn_servers = %+v, want none", cfg.RTC.TURNServers)
- }
-}
diff --git a/fluxer_rexctl/internal/stack/services_test.go b/fluxer_rexctl/internal/stack/services_test.go
deleted file mode 100644
index 8dbfff0eb..000000000
--- a/fluxer_rexctl/internal/stack/services_test.go
+++ /dev/null
@@ -1,138 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-package stack
-
-import (
- "slices"
- "strings"
- "testing"
-
- "go.yaml.in/yaml/v4"
-)
-
-func TestPortsDefaults(t *testing.T) {
- for _, env := range []map[string]string{nil, {}, {VoiceTCPPortKey: "", VoiceUDPPortKey: " "}} {
- got := Ports(env)
- if !slices.Equal(got, PublishedPorts) {
- t.Errorf("Ports(%v) = %v, want defaults %v", env, got, PublishedPorts)
- }
- }
-}
-
-func TestPortsOverride(t *testing.T) {
- got := Ports(map[string]string{VoiceTCPPortKey: "7883", VoiceUDPPortKey: "7884"})
- want := []Port{
- {Number: 80, Proto: "tcp"},
- {Number: 443, Proto: "tcp"},
- {Number: 443, Proto: "udp"},
- {Number: 7883, Proto: "tcp"},
- {Number: 7884, Proto: "udp"},
- }
- if !slices.Equal(got, want) {
- t.Errorf("Ports override = %v, want %v", got, want)
- }
-}
-
-func TestPortsInvalidKeepsDefault(t *testing.T) {
- for _, bad := range []string{"0", "-1", "70000", "notaport"} {
- got := Ports(map[string]string{VoiceTCPPortKey: bad, VoiceUDPPortKey: bad})
- if got[3].Number != 7881 || got[4].Number != 7882 {
- t.Errorf("Ports with %q = %v, want voice defaults 7881/7882", bad, got)
- }
- }
-}
-
-func TestComposeVoicePortsShareOneVar(t *testing.T) {
- data, err := ReadFile(Embedded(), "docker-compose.yml")
- if err != nil {
- t.Fatal(err)
- }
- s := string(data)
- wants := []string{
- "tcp_port: ${FLUXER_LIVEKIT_TCP_PORT:-7881}",
- "udp_port: ${FLUXER_LIVEKIT_UDP_PORT:-7882}",
- `"${FLUXER_LIVEKIT_TCP_PORT:-7881}:${FLUXER_LIVEKIT_TCP_PORT:-7881}"`,
- `"${FLUXER_LIVEKIT_UDP_PORT:-7882}:${FLUXER_LIVEKIT_UDP_PORT:-7882}/udp"`,
- }
- for _, want := range wants {
- if !strings.Contains(s, want) {
- t.Errorf("docker-compose.yml is missing %q", want)
- }
- }
- if !strings.Contains(s, "port: 7880") {
- t.Error("docker-compose.yml should keep the livekit signal port 7880 fixed and internal")
- }
-}
-
-func TestNatsClientsWaitForHealthyNats(t *testing.T) {
- data, err := ReadFile(Embedded(), "docker-compose.yml")
- if err != nil {
- t.Fatal(err)
- }
- var compose struct {
- Services map[string]struct {
- DependsOn map[string]struct {
- Condition string `yaml:"condition"`
- } `yaml:"depends_on"`
- Healthcheck struct {
- Test []string `yaml:"test"`
- } `yaml:"healthcheck"`
- } `yaml:"services"`
- }
- if err := yaml.Unmarshal(data, &compose); err != nil {
- t.Fatal(err)
- }
- for _, name := range []string{"api", "worker", "gateway", "push", "media-proxy", "snowflakes", "users", "gifs", "messages", "unfurl"} {
- service, ok := compose.Services[name]
- if !ok {
- t.Errorf("docker-compose.yml has no %s service", name)
- continue
- }
- if got := service.DependsOn["nats"].Condition; got != "service_healthy" {
- t.Errorf("%s depends on nats with condition %q, want service_healthy", name, got)
- }
- }
- check := strings.Join(compose.Services["gateway"].Healthcheck.Test, " ")
- if !strings.Contains(check, "GET /_health/ready ") {
- t.Errorf("gateway healthcheck %q should ask /_health/ready, which fails while the gateway's NATS subscriptions are missing", check)
- }
-}
-
-func TestPortsWithoutBundledVoice(t *testing.T) {
- got := Ports(map[string]string{VoiceBundledKey: "false", VoiceTCPPortKey: "7883"})
- want := []Port{
- {Number: 80, Proto: "tcp"},
- {Number: 443, Proto: "tcp"},
- {Number: 443, Proto: "udp"},
- }
- if !slices.Equal(got, want) {
- t.Errorf("Ports without bundled voice = %v, want %v", got, want)
- }
- if got := Ports(map[string]string{VoiceBundledKey: "true"}); !slices.Equal(got, PublishedPorts) {
- t.Errorf("Ports with bundled voice = %v", got)
- }
-}
-
-func TestOverlaysForBundledVoice(t *testing.T) {
- for value, want := range map[string]bool{"": false, "true": false, "1": false, "false": true, "0": true, "nonsense": false} {
- got := slices.Contains(OverlaysFor(map[string]string{"voice.bundled": value}), OverlayExternalVoice)
- if got != want {
- t.Errorf("voice.bundled %q: external voice overlay = %v, want %v", value, got, want)
- }
- }
- data, err := ReadFile(Embedded(), OverlayFiles[OverlayExternalVoice])
- if err != nil {
- t.Fatal(err)
- }
- var overlay struct {
- Services map[string]struct {
- Profiles []string `yaml:"profiles"`
- } `yaml:"services"`
- }
- if err := yaml.Unmarshal(data, &overlay); err != nil {
- t.Fatal(err)
- }
- if got := overlay.Services["livekit"].Profiles; !slices.Equal(got, []string{"bundled-voice"}) {
- t.Errorf("livekit profiles = %v", got)
- }
-}
diff --git a/fluxer_rexctl/internal/voice/voice_test.go b/fluxer_rexctl/internal/voice/voice_test.go
deleted file mode 100644
index 67753e529..000000000
--- a/fluxer_rexctl/internal/voice/voice_test.go
+++ /dev/null
@@ -1,440 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-package voice
-
-import (
- "context"
- "crypto/hmac"
- "crypto/sha256"
- "encoding/base64"
- "encoding/json"
- "errors"
- "io"
- "net"
- "net/http"
- "net/http/httptest"
- "slices"
- "strings"
- "testing"
- "time"
-
- "github.com/compose-spec/compose-go/v2/template"
- "go.yaml.in/yaml/v4"
-
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/host"
- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/stack"
-)
-
-func TestPickPortsSkipsEveryTakenPort(t *testing.T) {
- taken := map[host.Port]bool{
- {Number: 7881, Proto: "tcp"}: true,
- {Number: 7884, Proto: "udp"}: true,
- }
- busy := func(n int, proto string) bool { return !(n == 7885 && proto == "tcp") }
- tcp, udp := PickPorts(taken, busy)
- if tcp != 7887 || udp != 7888 {
- t.Fatalf("got %d/%d, want 7887/7888", tcp, udp)
- }
-}
-
-func TestNextIDIsUniqueAcrossRegions(t *testing.T) {
- if got := NextID("fra", []string{"fra-server-1", "default-server-2", "fra-server-3"}); got != "fra-server-2" {
- t.Fatalf("got %s", got)
- }
-}
-
-func TestEnvSetsExternalIPOnlyWithoutNodeIP(t *testing.T) {
- e := Env{ID: "fra-server-1", Key: "fluxer-fra-server-1", Secret: "s", WebhookURL: "http://api:8080/webhooks/livekit", Network: "fluxer_fluxer", TCPPort: 7883, UDPPort: 7884, Memory: "2g"}
- v := e.Values()
- if v["FLUXER_VOICE_USE_EXTERNAL_IP"] != "true" || v["FLUXER_VOICE_GOMEMLIMIT"] != "1740MiB" || v["FLUXER_LIVEKIT_IMAGE"] != DefaultImage {
- t.Fatalf("unexpected values %v", v)
- }
- e.NodeIP = "198.51.100.8"
- if e.Values()["FLUXER_VOICE_USE_EXTERNAL_IP"] != "false" {
- t.Fatal("node IP must turn off external IP discovery")
- }
- if _, ok := e.Values()["FLUXER_VOICE_HTTP_PORT"]; ok {
- t.Fatal("no HTTP port without --no-edge")
- }
- if !strings.Contains(string(e.File()), "FLUXER_VOICE_API_SECRET=s\n") {
- t.Fatal("env file misses the secret")
- }
-}
-
-func TestShippedComposeRendersWithTheEnv(t *testing.T) {
- data, err := ShippedFile(stack.Embedded(), ComposeFile)
- if err != nil {
- t.Fatal(err)
- }
- e := Env{ID: "fra-server-1", Key: "k", Secret: "s", WebhookURL: "http://api:8080/webhooks/livekit", Network: "fluxer_fluxer", TCPPort: 7883, UDPPort: 7884, NodeIP: "198.51.100.8", BindIP: "198.51.100.8"}
- values := e.Values()
- out, err := template.Substitute(string(data), func(k string) (string, bool) {
- v, ok := values[k]
- return v, ok
- })
- if err != nil {
- t.Fatal(err)
- }
- var doc struct {
- Services map[string]struct {
- Ports []string `yaml:"ports"`
- Networks map[string]struct {
- Aliases []string `yaml:"aliases"`
- } `yaml:"networks"`
- Environment map[string]string `yaml:"environment"`
- } `yaml:"services"`
- Networks map[string]struct {
- Name string `yaml:"name"`
- } `yaml:"networks"`
- }
- if err := yaml.Unmarshal([]byte(out), &doc); err != nil {
- t.Fatal(err)
- }
- svc := doc.Services["livekit"]
- if !slices.Equal(svc.Ports, []string{"198.51.100.8:7883:7883/tcp", "198.51.100.8:7884:7884/udp"}) {
- t.Fatalf("ports %v", svc.Ports)
- }
- if !slices.Equal(svc.Networks["voice"].Aliases, []string{"voice-fra-server-1"}) || doc.Networks["voice"].Name != "fluxer_fluxer" {
- t.Fatalf("network %+v %+v", svc.Networks, doc.Networks)
- }
- for _, want := range []string{"node_ip: \"198.51.100.8\"", "use_external_ip: false", "tcp_port: 7883", "- http://api:8080/webhooks/livekit"} {
- if !strings.Contains(svc.Environment["LIVEKIT_CONFIG"], want) {
- t.Fatalf("LIVEKIT_CONFIG misses %q:\n%s", want, svc.Environment["LIVEKIT_CONFIG"])
- }
- }
- if svc.Environment["LIVEKIT_KEYS"] != "k: s" {
- t.Fatalf("keys %q", svc.Environment["LIVEKIT_KEYS"])
- }
-}
-
-func TestEdgeFiles(t *testing.T) {
- if got := string(DropIn("fra-server-2")); got != "handle_path /livekit-fra-server-2/* {\n\timport upstream voice-fra-server-2:7880\n}\n" {
- t.Fatalf("drop-in %q", got)
- }
- site := string(SiteFile("203.0.113.7", []string{"b", "a"}, true))
- for _, want := range []string{"203.0.113.7 {", "profile shortlived", "handle_path /livekit-a/*", "import livekit voice-b:7880", "respond 404"} {
- if !strings.Contains(site, want) {
- t.Fatalf("site misses %q:\n%s", want, site)
- }
- }
- if strings.Index(site, "/livekit-a/") > strings.Index(site, "/livekit-b/") {
- t.Fatal("routes are not sorted")
- }
- if strings.Contains(string(SiteFile("voice.example.com", []string{"a"}, false)), "issuer") {
- t.Fatal("a hostname site must use Caddy's default issuers")
- }
- if Endpoint("203.0.113.7", "a") != "wss://203.0.113.7/livekit-a" {
- t.Fatal("endpoint")
- }
-}
-
-func TestSizing(t *testing.T) {
- if MachineMemory(1<<30) != "512m" || MachineMemory(4<<30) != "2048m" || MachineMemory(64<<30) != "8192m" {
- t.Fatal("machine memory must be half the host, between 512 MB and 8 GB")
- }
- if SoftLimit(4) != 300 || SoftLimit(0) != 75 {
- t.Fatal("soft limit")
- }
- if n, ok := ParseBytes("1536m"); !ok || n != 1536<<20 {
- t.Fatal("parse")
- }
-}
-
-func TestCheckHostname(t *testing.T) {
- cases := []struct {
- answer DNSAnswer
- want HostnameCheck
- }{
- {DNSAnswer{}, HostnameMissing},
- {DNSAnswer{A: []string{"203.0.113.7"}}, HostnameOK},
- {DNSAnswer{A: []string{"203.0.113.9"}}, HostnameElsewhere},
- {DNSAnswer{A: []string{"104.16.1.1", "172.67.1.1"}}, HostnameProxied},
- {DNSAnswer{A: []string{"203.0.113.7"}, AAAA: []string{"2001:db8::9"}}, HostnameIPv6Elsewhere},
- {DNSAnswer{A: []string{"203.0.113.7"}, AAAA: []string{"2001:db8::7"}}, HostnameOK},
- }
- for _, c := range cases {
- if got := CheckHostname(c.answer, "203.0.113.7", []string{"2001:db8::7"}); got != c.want {
- t.Errorf("%+v: got %d, want %d", c.answer, got, c.want)
- }
- }
-}
-
-func TestReachability(t *testing.T) {
- if r := Assess("203.0.113.7", []string{"10.0.0.4"}, "10.0.0.4"); !r.BehindNAT || r.CGNAT {
- t.Fatalf("%+v", r)
- }
- if r := Assess("203.0.113.7", []string{"100.64.3.2"}, "100.64.3.2"); !r.CGNAT {
- t.Fatalf("%+v", r)
- }
- if r := Assess("203.0.113.7", []string{"203.0.113.7", "100.100.1.1"}, "203.0.113.7"); r.BehindNAT || r.CGNAT {
- t.Fatalf("tailscale on another interface is fine: %+v", r)
- }
-}
-
-func TestValidToken(t *testing.T) {
- good := "fvj_123_" + strings.Repeat("a", 43)
- if !ValidToken(good) || ValidToken("fvj_x_"+strings.Repeat("a", 43)) || ValidToken("flx_123") {
- t.Fatal("token format")
- }
-}
-
-func verifyNodeToken(t *testing.T, header, secret, method string, body []byte) map[string]any {
- t.Helper()
- token := strings.TrimPrefix(header, "Bearer ")
- parts := strings.Split(token, ".")
- mac := hmac.New(sha256.New, []byte(secret))
- mac.Write([]byte(parts[0] + "." + parts[1]))
- if base64.RawURLEncoding.EncodeToString(mac.Sum(nil)) != parts[2] {
- t.Fatal("bad signature")
- }
- payload, _ := base64.RawURLEncoding.DecodeString(parts[1])
- var claims map[string]any
- _ = json.Unmarshal(payload, &claims)
- digest := ""
- if len(body) > 0 {
- sum := sha256.Sum256(body)
- digest = base64.StdEncoding.EncodeToString(sum[:])
- }
- if claims["aud"] != NodeAudience || claims["method"] != method || claims["path"] != NodePath || claims["sha256"] != digest {
- t.Fatalf("claims %v", claims)
- }
- return claims
-}
-
-func TestNodeClientSignsEveryRequest(t *testing.T) {
- var seen []string
- srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- body, _ := io.ReadAll(r.Body)
- claims := verifyNodeToken(t, r.Header.Get("Authorization"), "secret", r.Method, body)
- if claims["iss"] != "fluxer-a" {
- t.Fatalf("iss %v", claims["iss"])
- }
- seen = append(seen, r.Method+" "+string(body))
- if r.Method == http.MethodDelete {
- w.WriteHeader(http.StatusNoContent)
- return
- }
- _, _ = w.Write([]byte(`{"server_id":"a","region_id":"fra","endpoint":"wss://x/livekit-a","is_active":true,"draining":true,"health":{"status":"up"}}`))
- }))
- defer srv.Close()
- c := &Client{HTTP: srv.Client()}
- ctx := context.Background()
- if n, err := c.GetNode(ctx, srv.URL, "fluxer-a", "secret"); err != nil || n.Health.Status != "up" {
- t.Fatal(err)
- }
- draining := true
- if _, err := c.UpdateNode(ctx, srv.URL, "fluxer-a", "secret", NodeUpdate{Draining: &draining}); err != nil {
- t.Fatal(err)
- }
- if err := c.DeleteNode(ctx, srv.URL, "fluxer-a", "secret"); err != nil {
- t.Fatal(err)
- }
- if !slices.Equal(seen, []string{"GET ", `PATCH {"draining":true}`, "DELETE "}) {
- t.Fatalf("requests %v", seen)
- }
-}
-
-func TestJoinClientErrors(t *testing.T) {
- for _, code := range []string{CodeTokenInvalid, CodeTokenBusy, CodeEndpointUnreachable, CodeKeyMismatch, CodeIDInUse, CodeKeyInUse} {
- srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- if r.Header.Get("Authorization") != "VoiceJoin fvj_1_t" {
- t.Fatalf("auth %q", r.Header.Get("Authorization"))
- }
- w.WriteHeader(http.StatusConflict)
- _, _ = w.Write([]byte(`{"code":"` + code + `","message":"no","detail":"HTTP 502"}`))
- }))
- _, err := (&Client{HTTP: srv.Client()}).Join(context.Background(), srv.URL, "fvj_1_t", JoinRequest{})
- srv.Close()
- if CodeOf(err) != code || !strings.Contains(err.Error(), "HTTP 502") {
- t.Fatalf("%s: %v", code, err)
- }
- }
-}
-
-func TestDiscover(t *testing.T) {
- srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- if r.URL.Path != "/.well-known/fluxer" {
- t.Fatalf("path %s", r.URL.Path)
- }
- _, _ = w.Write([]byte(`{"api_code_version":7,"endpoints":{"api_public":"https://chat.example.com/api/"},"features":{"voice_enabled":true},"voice_origins":["wss://v.example.com"]}`))
- }))
- defer srv.Close()
- d, err := (&Client{HTTP: srv.Client()}).Discover(context.Background(), srv.URL)
- if err != nil || d.APIPublic != "https://chat.example.com/api" || !d.VoiceEnabled || d.VoiceOrigins[0] != "wss://v.example.com" {
- t.Fatalf("%+v %v", d, err)
- }
-}
-
-func TestTestTokenIsHiddenAndShort(t *testing.T) {
- tok := TestToken("k", "s", "rexctl-test-abc", time.Unix(1000, 0))
- payload, _ := base64.RawURLEncoding.DecodeString(strings.Split(tok, ".")[1])
- var claims struct {
- Exp int64 `json:"exp"`
- Video map[string]any `json:"video"`
- }
- _ = json.Unmarshal(payload, &claims)
- if claims.Exp != 1060 || claims.Video["hidden"] != true || claims.Video["room"] != "rexctl-test-abc" {
- t.Fatalf("%+v", claims)
- }
-}
-
-func TestClosedSignallingAfterTheAnswerMeansNoMediaPath(t *testing.T) {
- eof := io.EOF
- if got := signallingClosed(TransportUDP, true, eof).Error(); got != "voice: no UDP media path to the server" {
- t.Errorf("after the answer: %q", got)
- }
- if got := signallingClosed(TransportTCP, false, eof).Error(); !strings.Contains(got, "signalling closed") {
- t.Errorf("before the answer: %q", got)
- }
-}
-
-func TestRejectedTokenIsReportedAndNotPrinted(t *testing.T) {
- srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- http.Error(w, "invalid token", http.StatusUnauthorized)
- }))
- defer srv.Close()
- endpoint := "wss://" + strings.TrimPrefix(srv.URL, "https://") + "/livekit-x"
- err := TestTransport(context.Background(), endpoint, "secret-token-value", TransportUDP, true, 5*time.Second)
- if !errors.Is(err, ErrTokenRejected) {
- t.Fatalf("got %v", err)
- }
- if strings.Contains(err.Error(), "secret-token-value") {
- t.Errorf("the error shows the token: %v", err)
- }
-}
-
-func TestFailedDialHidesTheToken(t *testing.T) {
- srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- http.Error(w, "gone", http.StatusBadGateway)
- }))
- defer srv.Close()
- endpoint := "wss://" + strings.TrimPrefix(srv.URL, "https://") + "/livekit-x"
- err := TestTransport(context.Background(), endpoint, "secret-token-value", TransportTCP, true, 5*time.Second)
- if err == nil || errors.Is(err, ErrTokenRejected) || strings.Contains(err.Error(), "secret-token-value") {
- t.Errorf("got %v", err)
- }
-}
-
-func TestConnectSrcAllows(t *testing.T) {
- csp := []string{"default-src 'self'; connect-src 'self' wss://voice.example.com https://voice.example.com; img-src *"}
- if !ConnectSrcAllows(csp, "wss://voice.example.com") {
- t.Error("listed origin refused")
- }
- if ConnectSrcAllows(csp, "wss://other.example.com") || ConnectSrcAllows([]string{"img-src wss://voice.example.com"}, "wss://voice.example.com") {
- t.Error("unlisted origin allowed")
- }
-}
-
-func TestLocalProbesSpeakPlainHTTPWithoutThePublicPath(t *testing.T) {
- var paths []string
- srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- paths = append(paths, r.URL.Path)
- switch r.URL.Path {
- case "/":
- _, _ = io.WriteString(w, "OK")
- case "/twirp/livekit.RoomService/ListRooms":
- _, _ = io.WriteString(w, `{"rooms":[{"name":"guild_1_channel_2","num_participants":3},{"name":"`+TestRoomPrefix+`x","num_participants":1}]}`)
- default:
- http.NotFound(w, r)
- }
- }))
- defer srv.Close()
- port := srv.Listener.Addr().(*net.TCPAddr).Port
- base := LocalBase(port)
- if err := ProbeThroughEdge(context.Background(), base, "", true); err != nil {
- t.Fatalf("probe: %v", err)
- }
- load, err := ListRooms(context.Background(), base, "", "key", "secret", true)
- if err != nil {
- t.Fatalf("list rooms: %v", err)
- }
- if load != (RoomLoad{Rooms: 1, Participants: 3}) {
- t.Fatalf("load = %+v", load)
- }
- if !slices.Equal(paths, []string{"/", "/twirp/livekit.RoomService/ListRooms"}) {
- t.Fatalf("paths = %v", paths)
- }
-}
-
-func TestHTTPBaseKeepsThePathOfTheEndpoint(t *testing.T) {
- for in, want := range map[string]string{
- "wss://chat.example.com/livekit-fra-server-1/": "https://chat.example.com/livekit-fra-server-1",
- "ws://127.0.0.1:8080/livekit-x": "http://127.0.0.1:8080/livekit-x",
- } {
- if got := HTTPBase(in); got != want {
- t.Fatalf("HTTPBase(%q) = %q, want %q", in, got, want)
- }
- }
-}
-
-func TestInstanceEdgeFollowsTheEdgeMode(t *testing.T) {
- const endpoint = "wss://chat.example.com/livekit-fra-server-1"
- cases := []struct {
- mode, port, bind, base, addr string
- }{
- {"", "", "", "https://chat.example.com/livekit-fra-server-1", "127.0.0.1:443"},
- {"", "8443", "", "https://chat.example.com/livekit-fra-server-1", "127.0.0.1:8443"},
- {"", "${FLUXER_HTTPS_PORT}", "", "https://chat.example.com/livekit-fra-server-1", "127.0.0.1:443"},
- {"proxy", "443", "", "http://chat.example.com/livekit-fra-server-1", "127.0.0.1:8080"},
- {"proxy", "443", "0.0.0.0:9000", "http://chat.example.com/livekit-fra-server-1", "127.0.0.1:9000"},
- {"proxy", "443", "[::]:9000", "http://chat.example.com/livekit-fra-server-1", "127.0.0.1:9000"},
- {"proxy", "443", "10.0.0.5:8080", "http://chat.example.com/livekit-fra-server-1", "10.0.0.5:8080"},
- {"tunnel", "443", "", "http://chat.example.com/livekit-fra-server-1", "127.0.0.1:80"},
- {"tunnel", "443", "127.0.0.1:8081", "http://chat.example.com/livekit-fra-server-1", "127.0.0.1:8081"},
- }
- for _, c := range cases {
- base, addr := InstanceEdge(endpoint, c.mode, c.port, c.bind)
- if base != c.base || addr != c.addr {
- t.Errorf("InstanceEdge(%q, %q, %q) = %s, %s, want %s, %s", c.mode, c.port, c.bind, base, addr, c.base, c.addr)
- }
- }
-}
-
-func TestProxyModeProbeSpeaksPlainHTTPWithTheDomain(t *testing.T) {
- var hosts, paths []string
- srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- hosts, paths = append(hosts, r.Host), append(paths, r.URL.Path)
- _, _ = io.WriteString(w, "OK")
- }))
- defer srv.Close()
- base, addr := InstanceEdge("wss://chat.example.com/livekit-fra-server-1", "proxy", "443", srv.Listener.Addr().String())
- if err := ProbeThroughEdge(context.Background(), base, addr, false); err != nil {
- t.Fatalf("probe: %v", err)
- }
- if !slices.Equal(hosts, []string{"chat.example.com"}) || !slices.Equal(paths, []string{"/livekit-fra-server-1/"}) {
- t.Fatalf("hosts = %v, paths = %v", hosts, paths)
- }
-}
-
-func TestAClockProblemIsNotAWrongSecret(t *testing.T) {
- now := time.Date(2026, 10, 30, 12, 0, 0, 0, time.UTC)
- srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- w.Header().Set("Date", now.Add(-3*time.Minute).Format(http.TimeFormat))
- w.WriteHeader(http.StatusUnauthorized)
- _, _ = io.WriteString(w, `{"code":"VOICE_NODE_TOKEN_EXPIRED","message":"expired"}`)
- }))
- defer srv.Close()
- client := &Client{HTTP: srv.Client()}
- _, err := client.GetNode(context.Background(), srv.URL, "fluxer-fra-server-1", "secret")
- if CodeOf(err) != CodeTokenExpired {
- t.Fatalf("code = %q", CodeOf(err))
- }
- if got := ClockProblem(err, "chat.example.com", now); got != "The clock on this machine is about 3 minutes ahead of chat.example.com" {
- t.Fatalf("ahead: %q", got)
- }
- if got := ClockProblem(err, "chat.example.com", now.Add(-6*time.Minute)); got != "The clock on this machine is about 3 minutes behind chat.example.com" {
- t.Fatalf("behind: %q", got)
- }
- if got := ClockProblem(&APIError{Code: CodeSignatureInvalid}, "chat.example.com", now); got != "" {
- t.Fatalf("wrong secret: %q", got)
- }
-}
-
-func TestJoinedServersUseTheMachineProjectPrefix(t *testing.T) {
- if got := JoinedProject("fra-server-1"); got != "fluxer-voice-fra-server-1" {
- t.Fatalf("JoinedProject = %s", got)
- }
- if JoinedProject(EdgeID) != EdgeProject {
- t.Fatal("the edge ID no longer matches the edge project")
- }
-}
diff --git a/fluxer_snowflakes/src/router_impl.rs b/fluxer_snowflakes/src/router_impl.rs
index a91688094..9493d6fb4 100644
--- a/fluxer_snowflakes/src/router_impl.rs
+++ b/fluxer_snowflakes/src/router_impl.rs
@@ -41,27 +41,3 @@ impl RouterService for SnowflakesRouter {
}
}
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn keyed_requests_only_go_to_the_owner_and_unkeyed_ones_fail_over() {
- let router = SnowflakesRouter::new(8);
- let ring = HashRing::new(8);
- let keyed = SnowflakeRequest::GenerateBatch {
- count: 1,
- routing_key: Some("channel:1".to_owned()),
- };
- assert_eq!(
- router.shard_candidates(&keyed, &ring),
- vec![ring.owner("channel:1")]
- );
- let unkeyed = SnowflakeRequest::GenerateBatch {
- count: 1,
- routing_key: None,
- };
- assert_eq!(router.shard_candidates(&unkeyed, &ring).len(), 8);
- }
-}
diff --git a/fluxer_svc/src/combined.rs b/fluxer_svc/src/combined.rs
index e3a83684a..064314b03 100644
--- a/fluxer_svc/src/combined.rs
+++ b/fluxer_svc/src/combined.rs
@@ -200,89 +200,3 @@ async fn reply(
}
}
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use crate::config::Mode;
- use crate::transport::InMemoryTransport;
- use serde::{Deserialize, Serialize};
- use std::time::Duration;
-
- #[derive(Clone, Serialize, Deserialize)]
- struct EchoRequest {
- key: String,
- }
-
- #[derive(Clone, Serialize, Deserialize)]
- struct EchoResponse {
- key: String,
- }
-
- struct EchoRouter;
-
- impl RouterService for EchoRouter {
- type Request = EchoRequest;
- type Response = EchoResponse;
-
- fn service_name(&self) -> &str {
- "echo"
- }
-
- fn route_key(request: &EchoRequest) -> String {
- request.key.clone()
- }
-
- fn coalesce_key(request: &EchoRequest) -> Option<String> {
- Some(request.key.clone())
- }
- }
-
- struct EchoShard;
-
- impl ShardService for EchoShard {
- type Request = EchoRequest;
- type Response = EchoResponse;
-
- fn service_name(&self) -> &str {
- "echo"
- }
-
- async fn handle(&self, request: EchoRequest) -> anyhow::Result<EchoResponse> {
- if request.key.is_empty() {
- anyhow::bail!("empty key");
- }
- Ok(EchoResponse { key: request.key })
- }
- }
-
- #[tokio::test]
- async fn combined_answers_the_service_subject_from_the_shard_handler() {
- let transport = InMemoryTransport::new();
- let server_transport = transport.clone();
- let server = tokio::spawn(async move {
- run_combined(
- &ServiceConfig::for_test(Mode::Combined, 0, 1),
- EchoRouter,
- EchoShard,
- server_transport,
- )
- .await
- });
- tokio::time::sleep(Duration::from_millis(25)).await;
-
- let response = transport
- .request("svc.echo", br#"{"key":"a"}"#, Duration::from_secs(1))
- .await
- .unwrap();
- assert_eq!(response, br#"{"key":"a"}"#);
-
- let error = transport
- .request("svc.echo", br#"{"key":""}"#, Duration::from_secs(1))
- .await
- .unwrap();
- assert_eq!(error, br#"{"error":"shard_handler_error"}"#);
-
- server.abort();
- }
-}
diff --git a/fluxer_svc/src/router.rs b/fluxer_svc/src/router.rs
index 810c77776..b38f9e4e7 100644
--- a/fluxer_svc/src/router.rs
+++ b/fluxer_svc/src/router.rs
@@ -485,177 +485,3 @@ where
listener.abort();
result
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use crate::config::Mode;
- use crate::shard::{ShardService, run_shard};
- use crate::transport::InMemoryTransport;
- use serde::{Deserialize, Serialize};
-
- #[derive(Serialize, Deserialize)]
- enum KvRequest {
- Get { key: String },
- Invalidate,
- }
-
- #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
- enum KvResponse {
- Value { key: String, shard_id: u32 },
- Invalidated,
- }
-
- struct KvRouter {
- pinned: bool,
- }
-
- impl RouterService for KvRouter {
- type Request = KvRequest;
- type Response = KvResponse;
- const CACHES_RESPONSES: bool = false;
-
- fn service_name(&self) -> &str {
- "kv"
- }
-
- fn route_key(request: &KvRequest) -> String {
- match request {
- KvRequest::Get { key } => key.clone(),
- KvRequest::Invalidate => String::new(),
- }
- }
-
- fn shard_candidates(&self, request: &KvRequest, ring: &HashRing) -> Vec<u32> {
- let key = Self::route_key(request);
- if self.pinned {
- vec![ring.owner(&key)]
- } else {
- ring.ranked(&key)
- }
- }
-
- fn is_broadcast_request(request: &KvRequest) -> bool {
- matches!(request, KvRequest::Invalidate)
- }
-
- fn is_broadcast_acknowledgement(response: &KvResponse) -> bool {
- matches!(response, KvResponse::Invalidated)
- }
- }
-
- struct KvShard(u32);
-
- impl ShardService for KvShard {
- type Request = KvRequest;
- type Response = KvResponse;
-
- fn service_name(&self) -> &str {
- "kv"
- }
-
- async fn handle(&self, request: KvRequest) -> anyhow::Result<KvResponse> {
- Ok(match request {
- KvRequest::Get { key } => KvResponse::Value {
- key,
- shard_id: self.0,
- },
- KvRequest::Invalidate => KvResponse::Invalidated,
- })
- }
- }
-
- fn start_shard(transport: &InMemoryTransport, shard_id: u32) -> tokio::task::JoinHandle<()> {
- let transport = transport.clone();
- tokio::spawn(async move {
- let config = ServiceConfig::for_test(Mode::Shard, shard_id, 4);
- run_shard(&config, KvShard(shard_id), transport)
- .await
- .unwrap();
- })
- }
-
- fn start_router(transport: &InMemoryTransport, pinned: bool) -> tokio::task::JoinHandle<()> {
- let transport = transport.clone();
- tokio::spawn(async move {
- let config = ServiceConfig::for_test(Mode::Router, 0, 4);
- run_router(&config, KvRouter { pinned }, transport)
- .await
- .unwrap();
- })
- }
-
- async fn call(transport: &InMemoryTransport, payload: &[u8]) -> KvResponse {
- let response = transport
- .request("svc.kv", payload, Duration::from_secs(10))
- .await
- .unwrap();
- serde_json::from_slice(&response).unwrap()
- }
-
- fn value(shard_id: u32) -> KvResponse {
- KvResponse::Value {
- key: "k".to_owned(),
- shard_id,
- }
- }
-
- const GET: &[u8] = br#"{"Get":{"key":"k"}}"#;
-
- #[tokio::test(start_paused = true)]
- async fn router_fails_over_from_missing_and_draining_shards() {
- let transport = InMemoryTransport::new();
- let ranked = HashRing::new(4).ranked("k");
- let mut servers: Vec<_> = ranked[1..]
- .iter()
- .map(|&shard_id| start_shard(&transport, shard_id))
- .collect();
- servers.push(start_router(&transport, false));
- tokio::time::sleep(Duration::from_millis(25)).await;
-
- assert_eq!(call(&transport, GET).await, value(ranked[1]));
- assert_eq!(
- call(&transport, br#""Invalidate""#).await,
- KvResponse::Invalidated
- );
-
- let notice = format!(r#"{{"shard_id":{},"state":"draining"}}"#, ranked[1]);
- transport
- .publish("svc.kv.ctl", notice.as_bytes())
- .await
- .unwrap();
- tokio::time::sleep(Duration::from_millis(10)).await;
- assert_eq!(call(&transport, GET).await, value(ranked[2]));
-
- for server in servers {
- server.abort();
- }
- }
-
- #[tokio::test(start_paused = true)]
- async fn pinned_requests_wait_for_the_owner_to_come_back() {
- let transport = InMemoryTransport::new();
- let owner = HashRing::new(4).owner("k");
- let mut servers: Vec<_> = (0..4)
- .filter(|&shard_id| shard_id != owner)
- .map(|shard_id| start_shard(&transport, shard_id))
- .collect();
- servers.push(start_router(&transport, true));
- tokio::time::sleep(Duration::from_millis(25)).await;
-
- let request_transport = transport.clone();
- let mut request = tokio::spawn(async move { call(&request_transport, GET).await });
- assert!(
- tokio::time::timeout(Duration::from_secs(2), &mut request)
- .await
- .is_err()
- );
-
- servers.push(start_shard(&transport, owner));
- assert_eq!(request.await.unwrap(), value(owner));
-
- for server in servers {
- server.abort();
- }
- }
-}
diff --git a/fluxer_svc/src/shard.rs b/fluxer_svc/src/shard.rs
index 699375667..6e9b76562 100644
--- a/fluxer_svc/src/shard.rs
+++ b/fluxer_svc/src/shard.rs
@@ -509,60 +509,4 @@ mod tests {
shard_task.abort();
}
-
- #[tokio::test]
- async fn requests_arriving_after_sigterm_are_answered_before_exit() {
- let transport = InMemoryTransport::new();
- let config = ServiceConfig::for_test(Mode::Shard, 0, 1);
- let (shutdown_tx, shutdown_rx) = oneshot::channel::<()>();
- let release = Arc::new(tokio::sync::Notify::new());
- let handler_release = release.clone();
- let handler_transport = transport.clone();
- let server_transport = transport.clone();
- let server = tokio::spawn(async move {
- serve(
- &config,
- Endpoint {
- name: "mock".to_owned(),
- subject: "svc.mock.shard.0".to_owned(),
- queue_group: None,
- announce: None,
- linger: Duration::from_millis(50),
- },
- Arc::new(ServiceMetrics::default()),
- server_transport,
- move |msg| {
- let transport = handler_transport.clone();
- let release = handler_release.clone();
- async move {
- release.notified().await;
- reply_bytes(&msg, &transport, msg.payload()).await
- }
- },
- async {
- let _ = shutdown_rx.await;
- },
- )
- .await
- });
- tokio::time::sleep(Duration::from_millis(25)).await;
- shutdown_tx.send(()).unwrap();
- tokio::time::sleep(Duration::from_millis(10)).await;
-
- let requests = tokio::spawn(futures::future::join_all((0..8u8).map(|i| {
- let transport = transport.clone();
- async move {
- transport
- .request("svc.mock.shard.0", &[i], Duration::from_secs(1))
- .await
- }
- })));
- tokio::time::sleep(Duration::from_millis(100)).await;
- release.notify_waiters();
-
- for (i, response) in requests.await.unwrap().into_iter().enumerate() {
- assert_eq!(response.unwrap(), vec![i as u8]);
- }
- server.await.unwrap().unwrap();
- }
}
diff --git a/fluxer_unfurl/src/activity_pub/signature.rs b/fluxer_unfurl/src/activity_pub/signature.rs
index 54ee97756..6f2808a8f 100644
--- a/fluxer_unfurl/src/activity_pub/signature.rs
+++ b/fluxer_unfurl/src/activity_pub/signature.rs
@@ -75,135 +75,3 @@ impl RequestSigner {
Ok(headers)
}
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use crate::http_fetch::{DEFAULT_MAX_BYTES, fetch_url_with_headers};
- use serde::Deserialize;
- use std::io::{BufRead, BufReader, Write};
- use std::net::TcpListener;
- use std::time::{Duration, UNIX_EPOCH};
-
- #[derive(Deserialize)]
- struct Vectors {
- key_id: String,
- private_key_pkcs8_base64: String,
- private_key_pkcs1_base64: String,
- public_key_pkcs1_base64: String,
- vectors: Vec<Vector>,
- }
-
- #[derive(Deserialize)]
- struct Vector {
- name: String,
- url: String,
- unix_seconds: u64,
- host: String,
- date: String,
- signature: String,
- }
-
- #[test]
- fn signs_known_answer_vectors_with_pkcs8_and_pkcs1_keys() {
- let raw = include_str!("testdata/http_signature_vectors.json");
- let vectors: Vectors = serde_json::from_str(raw).expect("valid vector file");
- for encoded in [
- &vectors.private_key_pkcs8_base64,
- &vectors.private_key_pkcs1_base64,
- ] {
- let key = parse_signing_key(encoded).expect("test key parses");
- assert_eq!(public_key_base64(&key), vectors.public_key_pkcs1_base64);
- let signer = RequestSigner::new(Arc::new(key), vectors.key_id.clone());
- for vector in &vectors.vectors {
- let url = Url::parse(&vector.url).unwrap();
- let at = UNIX_EPOCH + Duration::from_secs(vector.unix_seconds);
- let headers = signer.headers(&url, at).unwrap();
- assert_eq!(headers[HOST], vector.host.as_str(), "{}", vector.name);
- assert_eq!(headers[DATE], vector.date.as_str(), "{}", vector.name);
- assert_eq!(
- headers[SIGNATURE],
- vector.signature.as_str(),
- "{}",
- vector.name
- );
- }
- }
- }
-
- #[tokio::test]
- async fn signs_every_redirect_hop_for_its_own_target_and_host() {
- let raw = include_str!("testdata/http_signature_vectors.json");
- let vectors: Vectors = serde_json::from_str(raw).expect("valid vector file");
- let key = parse_signing_key(&vectors.private_key_pkcs8_base64).expect("test key parses");
- let signer = RequestSigner::new(Arc::new(key), vectors.key_id.clone());
- let at = UNIX_EPOCH + Duration::from_secs(1_790_000_000);
-
- let listener = TcpListener::bind("127.0.0.1:0").unwrap();
- let proxy = format!("http://{}", listener.local_addr().unwrap());
- let server = std::thread::spawn(move || {
- let mut hops = Vec::new();
- for response in [
- "HTTP/1.1 301 Moved Permanently\r\nLocation: http://8.8.8.8:8080/users/alice/statuses/1\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
- "HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{}",
- ] {
- let (mut stream, _) = listener.accept().unwrap();
- let mut reader = BufReader::new(stream.try_clone().unwrap());
- let mut request = Vec::new();
- loop {
- let mut line = String::new();
- reader.read_line(&mut line).unwrap();
- if line.trim_end().is_empty() {
- break;
- }
- request.push(line.trim_end().to_owned());
- }
- stream.write_all(response.as_bytes()).unwrap();
- hops.push(request);
- }
- hops
- });
-
- let client = reqwest::Client::builder()
- .redirect(reqwest::redirect::Policy::none())
- .proxy(reqwest::Proxy::http(proxy).unwrap())
- .build()
- .unwrap();
- let result = fetch_url_with_headers(
- &client,
- "http://1.1.1.1/@alice/1?x=1",
- |url| signer.headers(url, at),
- DEFAULT_MAX_BYTES,
- Duration::from_secs(5),
- )
- .await
- .unwrap();
- assert_eq!(result.status, 200);
-
- let hops = server.join().unwrap();
- for (request, url) in hops.iter().zip([
- "http://1.1.1.1/@alice/1?x=1",
- "http://8.8.8.8:8080/users/alice/statuses/1",
- ]) {
- let expected = signer.headers(&Url::parse(url).unwrap(), at).unwrap();
- let header = |name: &str| {
- request
- .iter()
- .find_map(|line| {
- let (key, value) = line.split_once(':')?;
- key.eq_ignore_ascii_case(name)
- .then(|| value.trim().to_owned())
- })
- .unwrap_or_default()
- };
- assert_eq!(request[0], format!("GET {url} HTTP/1.1"));
- assert_eq!(header("host"), expected[HOST].to_str().unwrap(), "{url}");
- assert_eq!(
- header("signature"),
- expected[SIGNATURE].to_str().unwrap(),
- "{url}"
- );
- }
- assert_ne!(hops[0], hops[1]);
- }
-}
diff --git a/fluxer_unfurl/src/activity_pub/visibility.rs b/fluxer_unfurl/src/activity_pub/visibility.rs
index b9b45ab68..3ff1ce11e 100644
--- a/fluxer_unfurl/src/activity_pub/visibility.rs
+++ b/fluxer_unfurl/src/activity_pub/visibility.rs
@@ -60,104 +60,3 @@ fn addresses_public(value: Option<&serde_json::Value>) -> bool {
fn is_public_uri(value: &str) -> bool {
PUBLIC_URIS.contains(&value)
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use serde_json::json;
-
- fn post(value: serde_json::Value) -> ActivityPubPost {
- serde_json::from_value(value).expect("valid post")
- }
-
- fn actor(value: serde_json::Value) -> ActivityPubActor {
- serde_json::from_value(value).expect("valid actor")
- }
-
- const PUBLIC: &str = "https://www.w3.org/ns/activitystreams#Public";
-
- #[test]
- fn public_post_from_an_unhidden_actor_is_shown() {
- let post = post(json!({
- "to": [PUBLIC],
- "cc": ["https://gts.test/users/alice/followers"],
- }));
- let actor = actor(json!({
- "hidesToPublicFromUnauthedWeb": false,
- "hidesCcPublicFromUnauthedWeb": false,
- }));
- assert!(!is_hidden_from_unauthed_web(&post, Some(&actor)));
- }
-
- #[test]
- fn public_post_is_hidden_when_actor_hides_public_from_web() {
- let post = post(json!({ "to": [PUBLIC] }));
- let actor = actor(json!({
- "hidesToPublicFromUnauthedWeb": true,
- "hidesCcPublicFromUnauthedWeb": false,
- }));
- assert!(is_hidden_from_unauthed_web(&post, Some(&actor)));
- }
-
- #[test]
- fn unlisted_post_is_hidden_by_gotosocial_default() {
- let post = post(json!({
- "to": ["https://gts.test/users/alice/followers"],
- "cc": [PUBLIC],
- }));
- let actor = actor(json!({ "hidesToPublicFromUnauthedWeb": false }));
- assert!(is_hidden_from_unauthed_web(&post, Some(&actor)));
- }
-
- #[test]
- fn unlisted_post_is_shown_when_actor_allows_cc_on_web() {
- let post = post(json!({
- "to": ["https://gts.test/users/alice/followers"],
- "cc": [PUBLIC],
- }));
- let actor = actor(json!({
- "hidesToPublicFromUnauthedWeb": false,
- "hidesCcPublicFromUnauthedWeb": false,
- }));
- assert!(!is_hidden_from_unauthed_web(&post, Some(&actor)));
- }
-
- #[test]
- fn followers_only_post_is_always_hidden_for_a_gotosocial_actor() {
- let post = post(json!({
- "to": ["https://gts.test/users/alice/followers"],
- }));
- let actor = actor(json!({
- "hidesToPublicFromUnauthedWeb": false,
- "hidesCcPublicFromUnauthedWeb": false,
- }));
- assert!(is_hidden_from_unauthed_web(&post, Some(&actor)));
- }
-
- #[test]
- fn non_gotosocial_actor_without_flags_is_never_filtered() {
- let post = post(json!({
- "to": ["https://mastodon.test/users/bob/followers"],
- "cc": [PUBLIC],
- }));
- let actor = actor(json!({ "preferredUsername": "bob" }));
- assert!(!is_hidden_from_unauthed_web(&post, Some(&actor)));
- }
-
- #[test]
- fn missing_author_actor_is_never_filtered() {
- let post = post(json!({ "to": ["https://gts.test/users/alice/followers"] }));
- assert!(!is_hidden_from_unauthed_web(&post, None));
- }
-
- #[test]
- fn single_string_and_alias_public_addresses_are_recognised() {
- let string_public = post(json!({ "to": PUBLIC }));
- let hides_to = actor(json!({ "hidesToPublicFromUnauthedWeb": true }));
- assert!(is_hidden_from_unauthed_web(&string_public, Some(&hides_to)));
-
- let aliased = post(json!({ "cc": "as:Public" }));
- let hides_cc = actor(json!({ "hidesCcPublicFromUnauthedWeb": true }));
- assert!(is_hidden_from_unauthed_web(&aliased, Some(&hides_cc)));
- }
-}
diff --git a/fluxer_unfurl/src/dns_txt.rs b/fluxer_unfurl/src/dns_txt.rs
index a97b9c994..e5a0334d1 100644
--- a/fluxer_unfurl/src/dns_txt.rs
+++ b/fluxer_unfurl/src/dns_txt.rs
@@ -100,57 +100,3 @@ fn join_txt_strings(strings: &[Box<[u8]>]) -> String {
let joined: Vec<u8> = strings.iter().flat_map(|s| s.iter().copied()).collect();
String::from_utf8_lossy(&joined).into_owned()
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn joins_split_txt_strings() {
- let strings: Vec<Box<[u8]>> = vec![
- b"fluxer-verification=".to_vec().into_boxed_slice(),
- b"abc123".to_vec().into_boxed_slice(),
- ];
- assert_eq!(join_txt_strings(&strings), "fluxer-verification=abc123");
- }
-
- #[test]
- fn accepts_only_plain_lowercase_fqdns() {
- assert!(validate_hostname("example.com").is_ok());
- assert!(validate_hostname("sub.example-site.co.uk").is_ok());
- for domain in [
- "",
- "localhost",
- "example.com:8443",
- "127.0.0.1",
- "[::1]",
- "::1",
- "example.com.",
- "Example.com",
- "example.com/path",
- "-example.com",
- "exa mple.com",
- ] {
- assert!(validate_hostname(domain).is_err(), "{domain}");
- }
- }
-
- #[test]
- fn record_names_allow_one_service_label() {
- assert!(validate_record_name("_atproto.alice.example.com").is_ok());
- assert!(validate_record_name("alice.example.com").is_ok());
- for name in [
- "_atproto._x.example.com",
- "_.example.com",
- "_atproto.localhost",
- "_atproto.127.0.0.1",
- "_ATPROTO.example.com",
- "_atproto.Example.com",
- "_atproto.example.com.",
- "",
- ] {
- assert!(validate_record_name(name).is_err(), "{name}");
- }
- }
-}
diff --git a/fluxer_unfurl/src/domain_verification.rs b/fluxer_unfurl/src/domain_verification.rs
index 1b341f386..952477fd6 100644
--- a/fluxer_unfurl/src/domain_verification.rs
+++ b/fluxer_unfurl/src/domain_verification.rs
@@ -120,61 +120,3 @@ fn body_matches_token(body: &[u8], token: &str) -> bool {
let text = String::from_utf8_lossy(body);
text.strip_prefix('\u{feff}').unwrap_or(&text).trim() == token
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn body_must_equal_token_after_trimming() {
- assert!(body_matches_token(b"abc123", "abc123"));
- assert!(body_matches_token(b" abc123\r\n", "abc123"));
- assert!(body_matches_token("\u{feff}abc123\n".as_bytes(), "abc123"));
- assert!(!body_matches_token(b"abc1234", "abc123"));
- assert!(!body_matches_token(b"fluxer-verification=abc123", "abc123"));
- assert!(!body_matches_token(b"", "abc123"));
- }
-
- #[test]
- fn redirects_stay_on_the_same_site() {
- let check =
- |raw: &str, domain: &str| is_same_site_well_known(&Url::parse(raw).unwrap(), domain);
- assert!(check(
- "https://example.com/.well-known/fluxer-verification",
- "example.com"
- ));
- assert!(check(
- "https://www.example.com/.well-known/fluxer-verification",
- "example.com"
- ));
- assert!(check(
- "https://example.com/.well-known/fluxer-verification",
- "www.example.com"
- ));
- assert!(!check(
- "http://www.example.com/.well-known/fluxer-verification",
- "example.com"
- ));
- assert!(!check(
- "https://evil.example.com/.well-known/fluxer-verification",
- "example.com"
- ));
- assert!(!check(
- "https://www.www.example.com/.well-known/fluxer-verification",
- "example.com"
- ));
- assert!(!check(
- "https://example.net/.well-known/fluxer-verification",
- "example.com"
- ));
- assert!(!check(
- "https://www.example.com:8443/.well-known/fluxer-verification",
- "example.com"
- ));
- assert!(!check("https://www.example.com/token.txt", "example.com"));
- assert!(!check(
- "https://www.example.com/.well-known/fluxer-verification?x=1",
- "example.com"
- ));
- }
-}
diff --git a/fluxer_unfurl/src/external_fetch.rs b/fluxer_unfurl/src/external_fetch.rs
index 46cac78a6..c13e158cc 100644
--- a/fluxer_unfurl/src/external_fetch.rs
+++ b/fluxer_unfurl/src/external_fetch.rs
@@ -108,49 +108,3 @@ fn forwarded_headers(headers: &[(String, String)]) -> anyhow::Result<HeaderMap>
forwarded.insert(ACCEPT_ENCODING, HeaderValue::from_static("identity"));
Ok(forwarded)
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn only_https_hostnames_on_the_default_port() {
- for raw in [
- "https://bsky.social/xrpc/x",
- "https://plc.directory/did:plc:abc",
- ] {
- assert!(validate_target(&Url::parse(raw).unwrap()).is_ok(), "{raw}");
- }
- for raw in [
- "http://bsky.social/",
- "https://bsky.social:8443/",
- "https://1.1.1.1/",
- "https://[2606:4700::1111]/",
- "https://bsky.social/#x",
- ] {
- assert!(validate_target(&Url::parse(raw).unwrap()).is_err(), "{raw}");
- }
- }
-
- #[test]
- fn forwards_only_known_headers_and_asks_for_identity() {
- let forwarded = forwarded_headers(&[
- ("Accept".into(), "application/json".into()),
- ("DPoP".into(), "proof".into()),
- ("Authorization".into(), "DPoP token".into()),
- (
- "Content-Type".into(),
- "application/x-www-form-urlencoded".into(),
- ),
- ("Host".into(), "internal".into()),
- ("Accept-Encoding".into(), "br".into()),
- ("Cookie".into(), "a=b".into()),
- ])
- .unwrap();
- assert_eq!(forwarded.len(), 5);
- assert_eq!(forwarded[ACCEPT_ENCODING], "identity");
- assert_eq!(forwarded[DPOP], "proof");
- assert!(forwarded.get("host").is_none());
- assert!(forwarded.get("cookie").is_none());
- }
-}
diff --git a/fluxer_unfurl/src/resolvers/default_resolver.rs b/fluxer_unfurl/src/resolvers/default_resolver.rs
index bb10a4a97..e73da81b0 100644
--- a/fluxer_unfurl/src/resolvers/default_resolver.rs
+++ b/fluxer_unfurl/src/resolvers/default_resolver.rs
@@ -601,36 +601,6 @@ mod tests {
assert_eq!(classify(denied), "link");
}
- #[test]
- fn vimeo_player_media_keeps_no_dimensions() {
- let html = r#"<head>
- <meta property="og:type" content="video.other">
- <meta property="og:video:url" content="https://player.vimeo.com/video/1">
- <meta property="og:video:width" content="1280">
- <meta property="og:video:height" content="720">
- <meta name="twitter:card" content="player">
- <meta name="twitter:player" content="https://player.vimeo.com/video/1">
- <meta name="twitter:player:width" content="1280">
- <meta name="twitter:player:height" content="720">
- </head>"#;
- let page = url("https://vimeo.com/1");
- let og = html_parser::parse_opengraph(html);
- let twitter_card = html_parser::parse_twitter_card(html);
- for value in [og.video_primary, twitter_card.player] {
- let player_url = value
- .as_deref()
- .and_then(|value| resolve_media_url(&page, value))
- .filter(|value| is_allowlisted_player_url(value))
- .expect("allowlisted Vimeo player");
- let media = player_embed_media(player_url);
- assert_eq!(
- media.url.as_deref(),
- Some("https://player.vimeo.com/video/1")
- );
- assert_eq!((media.width, media.height), (None, None));
- }
- }
-
#[test]
fn player_allowlist_rejects_other_hosts() {
for value in [
diff --git a/fluxer_unfurl/src/resolvers/youtube.rs b/fluxer_unfurl/src/resolvers/youtube.rs
index 0503db583..b75d8b434 100644
--- a/fluxer_unfurl/src/resolvers/youtube.rs
+++ b/fluxer_unfurl/src/resolvers/youtube.rs
@@ -420,105 +420,3 @@ fn extract_timestamp(url: &Url) -> Option<u64> {
}
t.parse().ok()
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use crate::media_proxy::MediaProxyClient;
- use crate::types::NsfwMode;
- use std::io::{BufRead, BufReader, Write};
- use std::net::TcpListener;
-
- const QUOTA_EXCEEDED_BODY: &str = r#"{"error":{"code":403,"message":"The request cannot be completed because you have exceeded your quota.","errors":[{"message":"The request cannot be completed because you have exceeded your quota.","domain":"youtube.quota","reason":"quotaExceeded"}]}}"#;
-
- fn spawn_google_stub() -> String {
- let listener = TcpListener::bind("127.0.0.1:0").unwrap();
- let proxy = format!("http://{}", listener.local_addr().unwrap());
- std::thread::spawn(move || {
- for stream in listener.incoming() {
- let mut stream = stream.unwrap();
- let mut reader = BufReader::new(stream.try_clone().unwrap());
- let mut request_line = String::new();
- reader.read_line(&mut request_line).unwrap();
- loop {
- let mut line = String::new();
- reader.read_line(&mut line).unwrap();
- if line.trim_end().is_empty() {
- break;
- }
- }
- let body = QUOTA_EXCEEDED_BODY;
- let response = format!(
- "HTTP/1.1 403 Forbidden\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
- body.len()
- );
- stream.write_all(response.as_bytes()).unwrap();
- }
- });
- proxy
- }
-
- async fn resolve_against_stub(api_key: Option<&str>) -> Vec<MessageEmbed> {
- let proxy = spawn_google_stub();
- let http_client = reqwest::Client::builder()
- .redirect(reqwest::redirect::Policy::none())
- .proxy(reqwest::Proxy::http(proxy).unwrap())
- .build()
- .unwrap();
- let media_proxy = MediaProxyClient::new_with_public_endpoint(
- "http://127.0.0.1:1",
- "secret",
- None,
- reqwest::Client::new(),
- );
- let watch = Url::parse("https://www.youtube.com/watch?v=dQw4w9WgXcQ").unwrap();
- let ctx = ResolveContext {
- url: watch.clone(),
- original_url: watch,
- http_client,
- nsfw_mode: NsfwMode::Allow,
- media_proxy: &media_proxy,
- self_hosted: true,
- youtube_api_key: api_key.map(ToOwned::to_owned),
- klipy_api_key: None,
- activity_pub_signer: None,
- };
- resolve_video(&ctx, "http://1.1.1.1/youtube/v3/videos")
- .await
- .unwrap()
- .embeds
- }
-
- #[tokio::test]
- async fn rejected_api_key_yields_no_embed() {
- assert!(
- resolve_against_stub(Some("restricted-key"))
- .await
- .is_empty()
- );
- }
-
- #[tokio::test]
- async fn missing_api_key_yields_no_embed() {
- assert!(resolve_against_stub(None).await.is_empty());
- }
-
- #[test]
- fn api_error_reports_google_reason() {
- assert_eq!(
- api_error(QUOTA_EXCEEDED_BODY.as_bytes()).reason.as_deref(),
- Some("quotaExceeded")
- );
-
- let referrer_blocked = br#"{"error":{"code":403,"message":"Requests from referer <empty> are blocked.","errors":[{"message":"Requests from referer <empty> are blocked.","domain":"global","reason":"forbidden"}],"status":"PERMISSION_DENIED","details":[{"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":"API_KEY_HTTP_REFERRER_BLOCKED","domain":"googleapis.com"}]}}"#;
- assert_eq!(
- api_error(referrer_blocked),
- YouTubeApiError {
- reason: Some("API_KEY_HTTP_REFERRER_BLOCKED".to_owned()),
- message: Some("Requests from referer <empty> are blocked.".to_owned()),
- }
- );
-
- assert_eq!(api_error(b"not json"), YouTubeApiError::default());
- }
-}
diff --git a/fluxer_unfurl/src/sanitizer.rs b/fluxer_unfurl/src/sanitizer.rs
index c01d8bbfd..94d8c8616 100644
--- a/fluxer_unfurl/src/sanitizer.rs
+++ b/fluxer_unfurl/src/sanitizer.rs
@@ -120,62 +120,3 @@ fn is_trusted_oembed_src(src: &str) -> bool {
&& url.host_str().is_some_and(is_trusted_oembed_host)
})
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn strips_script_tags() {
- let html = r#"<script>alert(1)</script><p>Hello</p>"#;
- let result = sanitize_oembed_html(html);
- assert_eq!(result, Some("<p>Hello</p>".to_owned()));
- }
-
- #[test]
- fn strips_untrusted_iframe_src() {
- let html = r#"<iframe src="https://youtube.com.evil.test/embed"></iframe>"#;
- let result = sanitize_oembed_html(html).unwrap();
- assert!(!result.contains("youtube.com.evil.test"));
- assert!(!result.contains("src="));
- }
-
- #[test]
- fn strips_relative_iframe_src() {
- let html = r#"<iframe src="/embed"></iframe>"#;
- let result = sanitize_oembed_html(html).unwrap();
- assert!(!result.contains("src="));
- }
-
- #[test]
- fn anchor_gets_rel_noopener() {
- let html = r#"<a href="https://e.com">Link</a>"#;
- let result = sanitize_oembed_html(html).unwrap();
- assert!(result.contains("noopener"));
- }
-
- #[test]
- fn context_sanitizer_rejects_untrusted_source_and_provider() {
- let source = url::Url::parse("https://untrusted.com/page").unwrap();
- let html = r#"<p>Hello</p>"#;
- assert!(sanitize_oembed_html_with_context(html, &source, None).is_none());
- assert!(
- sanitize_oembed_html_with_context(html, &source, Some("https://also-untrusted.com"))
- .is_none()
- );
- }
-
- #[test]
- fn strips_javascript_uri_in_iframe() {
- let html = r#"<iframe src="javascript:alert(1)"></iframe>"#;
- let result = sanitize_oembed_html(html).unwrap();
- assert!(!result.contains("javascript"));
- }
-
- #[test]
- fn strips_data_uri_in_iframe() {
- let html = r#"<iframe src="data:text/html,<h1>pwned</h1>"></iframe>"#;
- let result = sanitize_oembed_html(html).unwrap();
- assert!(!result.contains("data:"));
- }
-}
diff --git a/fluxer_users/src/types.rs b/fluxer_users/src/types.rs
index 7747288fa..4841d5abd 100644
--- a/fluxer_users/src/types.rs
+++ b/fluxer_users/src/types.rs
@@ -3,8 +3,6 @@
use crate::pseudonym::pseudonym;
use fluxer_common::user_flags::AccountStanding;
#[cfg(test)]
-use fluxer_common::user_flags::USER_FLAG_PARTNER;
-#[cfg(test)]
use fluxer_common::user_flags::USER_FLAG_STAFF;
pub use fluxer_common::user_partial::ApiUserPartial;
use fluxer_common::user_partial::{
@@ -202,17 +200,4 @@ mod tests {
})
);
}
-
- #[test]
- fn api_partial_drops_the_flags_of_hidden_badges() {
- let mut partial = partial_with_flags(123, USER_FLAG_STAFF | USER_FLAG_PARTNER);
- partial.hidden_profile_badges = vec!["staff".to_owned()];
-
- let api_partial = partial.to_api_partial();
-
- assert_eq!(api_partial.flags, USER_FLAG_PARTNER as i32);
- assert_eq!(api_partial.bot, None);
- assert_eq!(api_partial.system, None);
- assert_eq!(api_partial.mention_flags, None);
- }
}
diff --git a/packages/hono/src/middleware/tests/Cors.test.ts b/packages/hono/src/middleware/tests/Cors.test.ts
deleted file mode 100644
index 157b6d5f6..000000000
--- a/packages/hono/src/middleware/tests/Cors.test.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {cors} from '@fluxer/hono/src/middleware/Cors';
-import {Hono} from 'hono';
-import {describe, expect, test} from 'vitest';
-
-describe('CORS Middleware', () => {
- describe('specific origins', () => {
- test('allows requests from whitelisted origin', async () => {
- const app = new Hono();
- app.use('*', cors({origins: ['https://allowed.com', 'https://also-allowed.com']}));
- app.get('/test', (c) => c.json({ok: true}));
- const response = await app.request('/test', {
- headers: {origin: 'https://allowed.com'},
- });
- expect(response.status).toBe(200);
- expect(response.headers.get('Access-Control-Allow-Origin')).toBe('https://allowed.com');
- expect(response.headers.get('Vary')).toBe('Origin');
- });
- test('does not set origin header for non-whitelisted origin', async () => {
- const app = new Hono();
- app.use('*', cors({origins: ['https://allowed.com']}));
- app.get('/test', (c) => c.json({ok: true}));
- const response = await app.request('/test', {
- headers: {origin: 'https://not-allowed.com'},
- });
- expect(response.status).toBe(200);
- expect(response.headers.get('Access-Control-Allow-Origin')).toBeNull();
- expect(response.headers.get('Vary')).toBe('Origin');
- });
- });
-});
diff --git a/packages/markdown_parser/rust/tests/linear_time.rs b/packages/markdown_parser/rust/tests/linear_time.rs
deleted file mode 100644
index 582542390..000000000
--- a/packages/markdown_parser/rust/tests/linear_time.rs
+++ /dev/null
@@ -1,21 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-use std::time::{Duration, Instant};
-
-use fluxer_markdown_parser::{EmojiContext, MarkdownParser, ParserFlags};
-
-#[test]
-fn unclosed_masked_links_parse_in_linear_time() {
- let line = "[a](".repeat(1024);
- let input = format!("{line}\n").repeat(400);
- let mut parser = MarkdownParser::new(ParserFlags::ALL, EmojiContext::default());
- let started = Instant::now();
- let nodes = parser.parse(&input).expect("parse succeeds");
- let elapsed = started.elapsed();
- assert_eq!(nodes.len(), 1);
- assert!(
- elapsed < Duration::from_secs(20),
- "parsing {} bytes took {elapsed:?}",
- input.len()
- );
-}
diff --git a/tools/ci/src/s3.rs b/tools/ci/src/s3.rs
index b07e20b64..fda398970 100644
--- a/tools/ci/src/s3.rs
+++ b/tools/ci/src/s3.rs
@@ -586,133 +586,3 @@ async fn send_s3_list_objects_v2_page(
}
unreachable!("S3 retry attempts are always greater than zero")
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn append_only_plan_skips_existing_keys_without_reordering_pending_uploads() {
- let temp = tempfile::tempdir().unwrap();
- let root = temp.path();
- fs::write(root.join("a"), "a").unwrap();
- fs::write(root.join("b"), "b").unwrap();
- fs::write(root.join("c"), "c").unwrap();
- let plan = vec![
- S3UploadPlanItem::new(root.join("a"), "desktop/a".to_string()),
- S3UploadPlanItem::new(root.join("b"), "desktop/b".to_string())
- .with_content_type("text/plain; charset=utf-8")
- .repair_existing_metadata(),
- S3UploadPlanItem::new(root.join("c"), "desktop/c".to_string()),
- ];
- let b_identity = s3_file_identity(&root.join("b")).unwrap();
- let existing = BTreeMap::from([(
- "desktop/b".to_string(),
- S3ObjectMetadata {
- e_tag: Some(format!("\"{}\"", b_identity.md5_hex)),
- size: Some(b_identity.size as i64),
- },
- )]);
-
- let (pending, skipped) = split_append_only_upload_plan("bucket", plan, &existing).unwrap();
-
- assert_eq!(
- pending.into_iter().map(|item| item.key).collect::<Vec<_>>(),
- vec!["desktop/a", "desktop/c"]
- );
- assert_eq!(
- skipped
- .iter()
- .map(|item| item.key.as_str())
- .collect::<Vec<_>>(),
- vec!["desktop/b"]
- );
- assert_eq!(
- skipped[0].content_type.as_deref(),
- Some("text/plain; charset=utf-8")
- );
- assert!(skipped[0].repair_existing_metadata);
- }
-
- #[test]
- fn append_only_plan_rejects_existing_key_with_different_checksum() {
- let temp = tempfile::tempdir().unwrap();
- let path = temp.path().join("asset.svg");
- fs::write(&path, "local").unwrap();
- let plan = vec![S3UploadPlanItem::new(path, "emoji/asset.svg".to_string())];
- let existing = BTreeMap::from([(
- "emoji/asset.svg".to_string(),
- S3ObjectMetadata {
- e_tag: Some("\"00000000000000000000000000000000\"".to_string()),
- size: Some(5),
- },
- )]);
-
- let error = split_append_only_upload_plan("bucket", plan, &existing).unwrap_err();
-
- assert!(error.to_string().contains("differs from local file"));
- }
-
- #[test]
- fn append_only_plan_keeps_a_published_source_map_that_differs() {
- let temp = tempfile::tempdir().unwrap();
- let path = temp.path().join("abc.worker.js.map");
- fs::write(&path, "local").unwrap();
- let plan = vec![S3UploadPlanItem::new(
- path,
- "assets/abc.worker.js.map".to_string(),
- )];
- let existing = BTreeMap::from([(
- "assets/abc.worker.js.map".to_string(),
- S3ObjectMetadata {
- e_tag: Some("\"00000000000000000000000000000000\"".to_string()),
- size: Some(9),
- },
- )]);
-
- let (pending, skipped) = split_append_only_upload_plan("bucket", plan, &existing).unwrap();
-
- assert!(pending.is_empty());
- assert_eq!(
- skipped
- .iter()
- .map(|item| item.key.as_str())
- .collect::<Vec<_>>(),
- vec!["assets/abc.worker.js.map"]
- );
- }
-
- #[test]
- fn append_only_plan_rejects_existing_key_without_comparable_etag() {
- let temp = tempfile::tempdir().unwrap();
- let path = temp.path().join("asset.bin");
- fs::write(&path, "local").unwrap();
- let plan = vec![S3UploadPlanItem::new(path, "assets/asset.bin".to_string())];
- let existing = BTreeMap::from([(
- "assets/asset.bin".to_string(),
- S3ObjectMetadata {
- e_tag: Some("\"multipart-etag-2\"".to_string()),
- size: Some(5),
- },
- )]);
-
- let error = split_append_only_upload_plan("bucket", plan, &existing).unwrap_err();
-
- assert!(error.to_string().contains("not a single-part MD5"));
- }
-
- #[test]
- fn append_only_plan_rejects_duplicate_local_keys() {
- let plan = vec![
- S3UploadPlanItem::new(PathBuf::from("a"), "same/key".to_string()),
- S3UploadPlanItem::new(PathBuf::from("b"), "same/key".to_string()),
- ];
-
- assert_eq!(
- split_append_only_upload_plan("bucket", plan, &BTreeMap::new())
- .unwrap_err()
- .to_string(),
- "Duplicate S3 upload key in local plan: same/key"
- );
- }
-}