Skip to content

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

TypeScript fluxerfluxerapp

test(unfurl): remove most unfurl unit tests

Hampus8d81c8d0a972
diff --git a/fluxer_unfurl/src/cache_policy.rs b/fluxer_unfurl/src/cache_policy.rs
index 36e67b16a..49010c676 100644
--- a/fluxer_unfurl/src/cache_policy.rs
+++ b/fluxer_unfurl/src/cache_policy.rs
@@ -102,101 +102,3 @@ fn response_has_embeds(response: &UnfurlResponse) -> bool {
_ => false,
}
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use crate::types::MessageEmbed;
-
- const URL: &str = "https://example.com/a";
-
- const EMPTY_UNFURL_CACHE_TTL_CEILING_SECS: u64 = 5 * 60;
-
- fn resolved(embed_count: usize) -> UnfurlResponse {
- UnfurlResponse::Resolved(Arc::new(UnfurlResult {
- embeds: (0..embed_count)
- .map(|_| MessageEmbed::new("link"))
- .collect(),
- cache_ttl_seconds: None,
- }))
- }
-
- #[test]
- fn scanning_and_unscanned_requests_do_not_share_an_entry() {
- assert_ne!(
- unfurl_cache_key(URL, NsfwMode::Block, "none"),
- unfurl_cache_key(URL, NsfwMode::Allow, "none"),
- "an unscanned result has no nsfw media flag and must not serve a scanning request"
- );
- }
-
- #[test]
- fn the_two_scanning_modes_share_a_single_entry() {
- assert_eq!(
- unfurl_cache_key(URL, NsfwMode::Block, "none"),
- unfurl_cache_key(URL, NsfwMode::Flag, "none")
- );
- }
-
- #[test]
- fn capability_distinguishes_every_key_combination() {
- let all = [
- provider_capability(false, false),
- provider_capability(true, false),
- provider_capability(false, true),
- provider_capability(true, true),
- ];
- let unique: std::collections::HashSet<&str> = all.iter().copied().collect();
- assert_eq!(unique.len(), all.len());
- for capability in all {
- assert_ne!(
- unfurl_cache_key(URL, NsfwMode::Block, capability),
- unfurl_cache_key(URL, NsfwMode::Block, "unrelated")
- );
- }
- }
-
- #[test]
- fn the_url_distinguishes_entries() {
- assert_ne!(
- unfurl_cache_key(URL, NsfwMode::Block, "none"),
- unfurl_cache_key("https://example.com/b", NsfwMode::Block, "none")
- );
- }
-
- #[test]
- fn the_empty_entry_lifetime_stays_a_short_retry_window() {
- assert!(
- default_empty_entry_lifetime()
- <= Duration::from_secs(EMPTY_UNFURL_CACHE_TTL_CEILING_SECS),
- "a site that was merely down must become retryable again quickly"
- );
- }
-
- #[test]
- fn the_expiry_reads_the_short_lifetime_off_an_empty_response() {
- let expiry = UnfurlEntryExpiry::new(default_empty_entry_lifetime());
- let now = Instant::now();
- let key = unfurl_cache_key(URL, NsfwMode::Block, "none");
- assert_eq!(
- Some(default_empty_entry_lifetime()),
- Expiry::<String, UnfurlResponse>::expire_after_create(&expiry, &key, &resolved(0), now)
- );
- assert_eq!(
- None,
- Expiry::<String, UnfurlResponse>::expire_after_create(&expiry, &key, &resolved(1), now)
- );
- assert_eq!(
- Some(default_empty_entry_lifetime()),
- Expiry::<String, Arc<UnfurlResult>>::expire_after_create(
- &expiry,
- &key,
- &Arc::new(UnfurlResult {
- embeds: Vec::new(),
- cache_ttl_seconds: None,
- }),
- now
- )
- );
- }
-}
diff --git a/fluxer_unfurl/src/embed_normalizer.rs b/fluxer_unfurl/src/embed_normalizer.rs
index d01cdceae..f01967037 100644
--- a/fluxer_unfurl/src/embed_normalizer.rs
+++ b/fluxer_unfurl/src/embed_normalizer.rs
@@ -107,246 +107,3 @@ fn normalize_media(mut media: EmbedMedia, media_proxy: &MediaProxyClient) -> Emb
}
media
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use crate::types::EmbedField;
-
- fn test_proxy() -> MediaProxyClient {
- MediaProxyClient::new_with_public_endpoint(
- "http://media-proxy:8080/",
- "test-secret",
- Some("https://media.example.test/"),
- reqwest::Client::new(),
- )
- }
-
- fn embed_with_title(t: &str) -> MessageEmbed {
- let mut e = MessageEmbed::new("rich");
- e.title = Some(t.to_owned());
- e
- }
-
- #[test]
- fn long_titles_are_truncated() {
- let long = "a".repeat(500);
- let result = normalize_embeds(vec![embed_with_title(&long)], &test_proxy());
- assert!(result[0].title.as_ref().unwrap().chars().count() <= TITLE_MAX);
- }
-
- #[test]
- fn fields_limited_to_max() {
- let mut e = MessageEmbed::new("rich");
- let fields: Vec<EmbedField> = (0..50)
- .map(|i| EmbedField {
- name: format!("f{i}"),
- value: "v".into(),
- inline: false,
- })
- .collect();
- e.fields = Some(fields);
- let result = normalize_embeds(vec![e], &test_proxy());
- assert!(result[0].fields.as_ref().unwrap().len() <= MAX_FIELDS);
- }
-
- #[test]
- fn provider_with_long_name_is_truncated() {
- let mut e = MessageEmbed::new("rich");
- let long = "X".repeat(500);
- e.provider = Some(EmbedProvider {
- name: long,
- url: None,
- });
- let result = normalize_embeds(vec![e], &test_proxy());
- let p = result[0].provider.as_ref().unwrap();
- assert!(p.name.chars().count() <= PROVIDER_NAME_MAX);
- }
-
- #[test]
- fn description_clamped_to_max_lines() {
- let mut e = MessageEmbed::new("rich");
- let many_lines = (0..50)
- .map(|i| format!("line {i}"))
- .collect::<Vec<_>>()
- .join("\n");
- e.description = Some(many_lines);
- let result = normalize_embeds(vec![e], &test_proxy());
- let lines: Vec<_> = result[0].description.as_ref().unwrap().lines().collect();
- assert!(lines.len() <= DESCRIPTION_LINES_MAX + 1);
- }
-
- #[test]
- fn children_limited_to_max() {
- let mut e = MessageEmbed::new("rich");
- e.children = Some(vec![
- MessageEmbed::new("rich"),
- MessageEmbed::new("rich"),
- MessageEmbed::new("rich"),
- ]);
- let result = normalize_embeds(vec![e], &test_proxy());
- assert_eq!(result[0].children.as_ref().unwrap().len(), MAX_CHILDREN);
- }
-
- #[test]
- fn nested_children_are_normalized() {
- let mut child = MessageEmbed::new("rich");
- child.title = Some("a".repeat(500));
- let mut e = MessageEmbed::new("rich");
- e.children = Some(vec![child]);
- let result = normalize_embeds(vec![e], &test_proxy());
- let child_title = result[0].children.as_ref().unwrap()[0]
- .title
- .as_ref()
- .unwrap();
- assert!(child_title.chars().count() <= TITLE_MAX);
- }
-
- #[test]
- fn media_description_is_truncated() {
- let mut e = MessageEmbed::new("rich");
- e.thumbnail = Some(EmbedMedia {
- url: Some("https://example.com/img.png".into()),
- description: Some("d".repeat(5000)),
- ..Default::default()
- });
- let result = normalize_embeds(vec![e], &test_proxy());
- let desc = result[0]
- .thumbnail
- .as_ref()
- .unwrap()
- .description
- .as_ref()
- .unwrap();
- assert!(desc.chars().count() <= MEDIA_DESCRIPTION_MAX);
- }
-
- #[test]
- fn html_field_is_truncated() {
- let mut e = MessageEmbed::new("rich");
- e.html = Some("x".repeat(15000));
- let result = normalize_embeds(vec![e], &test_proxy());
- assert!(result[0].html.as_ref().unwrap().chars().count() <= HTML_MAX);
- }
-
- #[test]
- fn field_value_is_truncated() {
- let mut e = MessageEmbed::new("rich");
- e.fields = Some(vec![EmbedField {
- name: "ok".into(),
- value: "v".repeat(2000),
- inline: false,
- }]);
- let result = normalize_embeds(vec![e], &test_proxy());
- let val = &result[0].fields.as_ref().unwrap()[0].value;
- assert!(val.chars().count() <= FIELD_VALUE_MAX);
- }
-
- #[test]
- fn missing_proxy_url_on_media_is_populated() {
- let mut e = MessageEmbed::new("rich");
- e.image = Some(EmbedMedia {
- url: Some("https://pbs.twimg.com/media/a.jpg".into()),
- ..Default::default()
- });
- e.thumbnail = Some(EmbedMedia {
- url: Some("https://goulartnogueira.github.io/badui.gif".into()),
- ..Default::default()
- });
- e.video = Some(EmbedMedia {
- url: Some("https://cdn.bsky.app/x/video.mp4".into()),
- ..Default::default()
- });
- let result = normalize_embeds(vec![e], &test_proxy());
- let r = &result[0];
- let image_proxy = r.image.as_ref().unwrap().proxy_url.as_deref().unwrap();
- assert!(image_proxy.starts_with("https://media.example.test/external/"));
- let thumb_proxy = r.thumbnail.as_ref().unwrap().proxy_url.as_deref().unwrap();
- assert!(thumb_proxy.starts_with("https://media.example.test/external/"));
- let video_proxy = r.video.as_ref().unwrap().proxy_url.as_deref().unwrap();
- assert!(video_proxy.starts_with("https://media.example.test/external/"));
- }
-
- #[test]
- fn existing_proxy_url_is_preserved() {
- let mut e = MessageEmbed::new("rich");
- let existing = "https://media.example.test/external/already/v2/abc".to_owned();
- e.image = Some(EmbedMedia {
- url: Some("https://pbs.twimg.com/media/a.jpg".into()),
- proxy_url: Some(existing.clone()),
- ..Default::default()
- });
- let result = normalize_embeds(vec![e], &test_proxy());
- assert_eq!(
- result[0].image.as_ref().unwrap().proxy_url.as_deref(),
- Some(existing.as_str())
- );
- }
-
- #[test]
- fn author_and_footer_icon_urls_are_proxied() {
- let mut e = MessageEmbed::new("rich");
- e.author = Some(EmbedAuthor {
- name: "Someone".into(),
- url: None,
- icon_url: Some("https://bsky.social/avatar.png".into()),
- proxy_icon_url: None,
- });
- e.footer = Some(EmbedFooter {
- text: "Footer".into(),
- icon_url: Some("https://bsky.social/footer.png".into()),
- proxy_icon_url: None,
- });
- let result = normalize_embeds(vec![e], &test_proxy());
- let author_proxy = result[0]
- .author
- .as_ref()
- .unwrap()
- .proxy_icon_url
- .as_deref()
- .unwrap();
- assert!(author_proxy.starts_with("https://media.example.test/external/"));
- let footer_proxy = result[0]
- .footer
- .as_ref()
- .unwrap()
- .proxy_icon_url
- .as_deref()
- .unwrap();
- assert!(footer_proxy.starts_with("https://media.example.test/external/"));
- }
-
- #[test]
- fn already_proxied_url_is_preserved_in_proxy_field() {
- let mut e = MessageEmbed::new("rich");
- e.image = Some(EmbedMedia {
- url: Some("https://media.example.test/avatars/abc.webp".into()),
- ..Default::default()
- });
- let result = normalize_embeds(vec![e], &test_proxy());
- assert_eq!(
- result[0].image.as_ref().unwrap().proxy_url.as_deref(),
- Some("https://media.example.test/avatars/abc.webp")
- );
- }
-
- #[test]
- fn nested_children_media_is_proxied() {
- let mut child = MessageEmbed::new("rich");
- child.image = Some(EmbedMedia {
- url: Some("https://raw.githubusercontent.com/fluxer/logo.png".into()),
- ..Default::default()
- });
- let mut e = MessageEmbed::new("rich");
- e.children = Some(vec![child]);
- let result = normalize_embeds(vec![e], &test_proxy());
- let proxy = result[0].children.as_ref().unwrap()[0]
- .image
- .as_ref()
- .unwrap()
- .proxy_url
- .as_deref()
- .unwrap();
- assert!(proxy.starts_with("https://media.example.test/external/"));
- }
-}
diff --git a/fluxer_unfurl/src/html_markdown.rs b/fluxer_unfurl/src/html_markdown.rs
index 99d9c2c82..15506e746 100644
--- a/fluxer_unfurl/src/html_markdown.rs
+++ b/fluxer_unfurl/src/html_markdown.rs
@@ -112,25 +112,6 @@ mod tests {
s.to_owned()
}
- #[test]
- fn converts_basic_markup() {
- assert_eq!(to_markdown("<strong>bold</strong>", identity), "**bold**");
- assert_eq!(to_markdown("<em>x</em>", identity), "_x_");
- assert_eq!(to_markdown("a<br>b", identity), "a\nb");
- }
-
- #[test]
- fn keeps_http_links() {
- assert_eq!(
- to_markdown(r#"<a href="https://e.com">t</a>"#, identity),
- "[t](https://e.com)"
- );
- assert_eq!(
- to_markdown(r#"<a href="http://e.com">t</a>"#, identity),
- "[t](http://e.com)"
- );
- }
-
#[test]
fn drops_dangerous_link_schemes_but_keeps_text() {
assert_eq!(
@@ -142,12 +123,4 @@ mod tests {
"click"
);
}
-
- #[test]
- fn keeps_relative_links() {
- assert_eq!(
- to_markdown(r#"<a href="/path">t</a>"#, identity),
- "[t](/path)"
- );
- }
}
diff --git a/fluxer_unfurl/src/html_parser.rs b/fluxer_unfurl/src/html_parser.rs
index d12c396bf..4cd38cd95 100644
--- a/fluxer_unfurl/src/html_parser.rs
+++ b/fluxer_unfurl/src/html_parser.rs
@@ -291,23 +291,3 @@ fn normalize_image_reference_key(value: &str) -> Option<String> {
fn is_http_url(url: &url::Url) -> bool {
matches!(url.scheme(), "http" | "https")
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- fn og(html: &str) -> OgMetadata {
- parse_opengraph(html)
- }
-
- #[test]
- fn images_reject_bad_url_references() {
- let h = r#"<head>
- <meta property="og:image" content="javascript:alert(1)">
- <meta property="og:image" content="data:image/png;base64,abcd">
- <meta property="og:image" content="bad url.png">
- <meta property="og:image" content="https://a.com/ok.png">
- </head>"#;
- assert_eq!(og(h).images, vec!["https://a.com/ok.png".to_owned()]);
- }
-}
diff --git a/fluxer_unfurl/src/media_proxy.rs b/fluxer_unfurl/src/media_proxy.rs
index a9c1137ca..e8c8c5e97 100644
--- a/fluxer_unfurl/src/media_proxy.rs
+++ b/fluxer_unfurl/src/media_proxy.rs
@@ -147,22 +147,6 @@ impl MediaProxyClient {
mod tests {
use super::*;
- #[test]
- fn nsfw_mode_strings() {
- assert_eq!(
- MediaProxyClient::nsfw_mode_str(crate::types::NsfwMode::Block),
- "block"
- );
- assert_eq!(
- MediaProxyClient::nsfw_mode_str(crate::types::NsfwMode::Allow),
- "allow"
- );
- assert_eq!(
- MediaProxyClient::nsfw_mode_str(crate::types::NsfwMode::Flag),
- "flag"
- );
- }
-
#[test]
fn external_proxy_url_uses_public_endpoint_and_plain_path() {
let client = reqwest::Client::new();
diff --git a/fluxer_unfurl/src/network_policy.rs b/fluxer_unfurl/src/network_policy.rs
index f18daff8f..f5cfb6e82 100644
--- a/fluxer_unfurl/src/network_policy.rs
+++ b/fluxer_unfurl/src/network_policy.rs
@@ -2,7 +2,6 @@
use fluxer_common::public_ip::{is_public_ip, is_valid_public_hostname};
use reqwest::dns::{Addrs, Name, Resolve, Resolving};
-use std::fmt;
use std::net::{IpAddr, SocketAddr};
use tokio::net::lookup_host;
use url::Url;
@@ -17,19 +16,6 @@ pub enum Error {
HostResolvedToNoAddress,
}
-impl fmt::Display for Error {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- match self {
- Self::InvalidUrl => f.write_str("invalid URL"),
- Self::BlockedUrl => f.write_str("blocked URL"),
- Self::DnsLookupFailed => f.write_str("DNS lookup failed"),
- Self::HostResolvedToNoAddress => f.write_str("host resolved to no address"),
- }
- }
-}
-
-impl std::error::Error for Error {}
-
pub async fn validate_url(url: &Url) -> Result<(), Error> {
if url.as_str().is_empty() || url.as_str().len() > MAX_URL_LEN || contains_ctl(url.as_str()) {
return Err(Error::InvalidUrl);
@@ -187,15 +173,6 @@ mod tests {
assert_eq!(validate_url(&next).await, Err(Error::BlockedUrl));
}
- #[tokio::test]
- async fn allows_public_ip_literals_without_dns() {
- assert_eq!(validate_url(&url("https://8.8.8.8/")).await, Ok(()));
- assert_eq!(
- validate_url(&url("https://[2606:4700:4700::1111]/")).await,
- Ok(())
- );
- }
-
#[tokio::test]
async fn rejects_userinfo_and_non_http_s_schemes() {
assert_eq!(
@@ -207,31 +184,4 @@ mod tests {
Err(Error::BlockedUrl)
);
}
-
- #[test]
- fn validates_public_host_syntax() {
- assert!(is_valid_public_hostname("example.com"));
- assert!(is_valid_public_hostname("xn--bcher-kva.example"));
- assert!(!is_valid_public_hostname("localhost"));
- assert!(!is_valid_public_hostname("example"));
- assert!(!is_valid_public_hostname("bad_name.example"));
- assert!(!is_valid_public_hostname("example.123"));
- }
-
- #[test]
- fn resolves_redirects_without_fragments() {
- let base = url("https://example.com/a/b/c?x=1");
- assert_eq!(
- resolve_redirect(&base, "../d?y=2#ignored")
- .unwrap()
- .as_str(),
- "https://example.com/a/d?y=2"
- );
- assert_eq!(
- resolve_redirect(&base, "//cdn.example.com/p")
- .unwrap()
- .as_str(),
- "https://cdn.example.com/p"
- );
- }
}
diff --git a/fluxer_unfurl/src/resolvers/bluesky.rs b/fluxer_unfurl/src/resolvers/bluesky.rs
index 3d03e80ed..1e09aba83 100644
--- a/fluxer_unfurl/src/resolvers/bluesky.rs
+++ b/fluxer_unfurl/src/resolvers/bluesky.rs
@@ -1032,63 +1032,3 @@ fn format_count(count: u64) -> String {
}
use super::default_helpers::{normalize_timestamp, normalize_url, sanitize_absolute_url};
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn embed_links_skips_overlapping_facets() {
- let text = "overlap";
- let facets = vec![
- BskyFacet {
- index: BskyFacetIndex {
- byte_start: 0,
- byte_end: 4,
- },
- features: vec![BskyFacetFeature {
- facet_type: Some("app.bsky.richtext.facet#link".to_owned()),
- uri: Some("https://a.com".to_owned()),
- did: None,
- }],
- },
- BskyFacet {
- index: BskyFacetIndex {
- byte_start: 2,
- byte_end: 7,
- },
- features: vec![BskyFacetFeature {
- facet_type: Some("app.bsky.richtext.facet#link".to_owned()),
- uri: Some("https://b.com".to_owned()),
- did: None,
- }],
- },
- ];
- let result = embed_links_in_text(text, Some(&facets));
- assert!(result.contains("[a.com/](https://a.com)"));
- assert!(!result.contains("https://b.com"));
- assert!(result.ends_with("lap"));
- }
-
- #[test]
- fn embed_links_skips_out_of_bounds_facets() {
- let text = "hi";
- let facets = vec![BskyFacet {
- index: BskyFacetIndex {
- byte_start: 0,
- byte_end: 10,
- },
- features: vec![BskyFacetFeature {
- facet_type: Some("app.bsky.richtext.facet#link".to_owned()),
- uri: Some("https://e.com".to_owned()),
- did: None,
- }],
- }];
- assert_eq!(embed_links_in_text(text, Some(&facets)), "hi");
- }
-
- #[test]
- fn sanitize_optional_url_rejects_relative() {
- assert!(sanitize_absolute_url("/relative/path").is_none());
- }
-}
diff --git a/fluxer_unfurl/src/resolvers/default_resolver.rs b/fluxer_unfurl/src/resolvers/default_resolver.rs
index 84854ed7a..7bd2903aa 100644
--- a/fluxer_unfurl/src/resolvers/default_resolver.rs
+++ b/fluxer_unfurl/src/resolvers/default_resolver.rs
@@ -634,29 +634,6 @@ mod tests {
assert_eq!(classify(denied), "link");
}
- #[test]
- fn player_allowlist_accepts_verified_hosts() {
- for value in [
- "https://www.youtube.com/embed/x",
- "https://www.youtube-nocookie.com/embed/x",
- "https://youtu.be/x",
- "https://player.vimeo.com/video/1",
- "https://w.soundcloud.com/player/?url=x",
- "https://player.twitch.tv/?video=1",
- ] {
- assert!(is_allowlisted_player_url(value), "{value} must be allowed");
- }
- }
-
- #[test]
- fn classify_twitter_player_resolves_relative_references_first() {
- let html = r#"<head>
- <meta name="twitter:card" content="player">
- <meta name="twitter:player" content="//player.vimeo.com/video/1">
- </head>"#;
- assert_eq!(classify(html), "video");
- }
-
#[test]
fn player_allowlist_rejects_other_hosts() {
for value in [
diff --git a/fluxer_unfurl/src/resolvers/klipy.rs b/fluxer_unfurl/src/resolvers/klipy.rs
index 122390621..cfad608f6 100644
--- a/fluxer_unfurl/src/resolvers/klipy.rs
+++ b/fluxer_unfurl/src/resolvers/klipy.rs
@@ -2,7 +2,6 @@
use super::{ResolveContext, Resolver, ResolverResult};
use crate::http_fetch;
-use crate::media_proxy::MediaMetadata;
use crate::types::{EmbedMedia, EmbedProvider, MessageEmbed};
use std::future::Future;
use std::pin::Pin;
@@ -196,19 +195,6 @@ fn klipy_meta_dimension(
.and_then(|value| u32::try_from(value).ok())
}
-fn build_embed_media_payload(
- url: &str,
- metadata: &MediaMetadata,
- width: Option<u32>,
- height: Option<u32>,
-) -> EmbedMedia {
- EmbedMedia {
- width: width.or(metadata.width),
- height: height.or(metadata.height),
- ..metadata.to_embed_media(url)
- }
-}
-
fn extract_media_format(value: Option<&serde_json::Value>) -> Option<KlipyMediaFormat> {
let value = value?;
if let Some(url) = value.as_str().filter(|url| !url.is_empty()) {
@@ -236,14 +222,3 @@ fn extract_media_format(value: Option<&serde_json::Value>) -> Option<KlipyMediaF
}
use super::default_helpers::resolve_http_url;
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn resolve_http_url_rejects_non_http() {
- let base = Url::parse("https://klipy.com/gifs/test").unwrap();
- assert!(resolve_http_url(&base, "ftp://evil.com/file").is_none());
- }
-}
diff --git a/fluxer_unfurl/src/resolvers/tenor.rs b/fluxer_unfurl/src/resolvers/tenor.rs
index 331de09ee..2af30ca63 100644
--- a/fluxer_unfurl/src/resolvers/tenor.rs
+++ b/fluxer_unfurl/src/resolvers/tenor.rs
@@ -227,19 +227,3 @@ fn valid_absolute_url(value: &str) -> Option<String> {
None
}
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn valid_absolute_url_rejects_non_http() {
- assert!(valid_absolute_url("ftp://example.com/file").is_none());
- assert!(valid_absolute_url("javascript:alert(1)").is_none());
- }
-
- #[test]
- fn valid_absolute_url_rejects_relative() {
- assert!(valid_absolute_url("/relative/path").is_none());
- }
-}
diff --git a/fluxer_unfurl/src/router_impl.rs b/fluxer_unfurl/src/router_impl.rs
index 91444dd69..dc5a9b988 100644
--- a/fluxer_unfurl/src/router_impl.rs
+++ b/fluxer_unfurl/src/router_impl.rs
@@ -122,195 +122,3 @@ impl RouterService for UnfurlRouter {
}
}
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use crate::types::NsfwMode;
-
- fn test_lifetime() -> Duration {
- Duration::from_secs(30 * 60)
- }
-
- fn request(cache_only: bool) -> UnfurlRequest {
- UnfurlRequest::Unfurl {
- url: "https://example.com/article".to_owned(),
- nsfw_mode: Some(NsfwMode::Block),
- bypass_cache: false,
- cache_only,
- youtube_api_key: None,
- klipy_api_key: None,
- }
- }
-
- fn resolved_response() -> UnfurlResponse {
- UnfurlResponse::Resolved(std::sync::Arc::new(crate::types::UnfurlResult {
- embeds: vec![crate::types::MessageEmbed::new("link")],
- cache_ttl_seconds: None,
- }))
- }
-
- fn empty_response() -> UnfurlResponse {
- UnfurlResponse::Resolved(std::sync::Arc::new(crate::types::UnfurlResult {
- embeds: Vec::new(),
- cache_ttl_seconds: None,
- }))
- }
-
- fn unfurl(url: &str, youtube_api_key: Option<&str>) -> UnfurlRequest {
- UnfurlRequest::Unfurl {
- url: url.to_owned(),
- nsfw_mode: Some(NsfwMode::Block),
- bypass_cache: false,
- cache_only: false,
- youtube_api_key: youtube_api_key.map(str::to_owned),
- klipy_api_key: None,
- }
- }
-
- fn unfurl_with_klipy(url: &str, klipy_api_key: Option<&str>) -> UnfurlRequest {
- UnfurlRequest::Unfurl {
- url: url.to_owned(),
- nsfw_mode: Some(NsfwMode::Block),
- bypass_cache: false,
- cache_only: false,
- youtube_api_key: None,
- klipy_api_key: klipy_api_key.map(str::to_owned),
- }
- }
-
- fn probe(url: &str) -> UnfurlRequest {
- UnfurlRequest::Unfurl {
- url: url.to_owned(),
- nsfw_mode: Some(NsfwMode::Block),
- bypass_cache: false,
- cache_only: true,
- youtube_api_key: None,
- klipy_api_key: None,
- }
- }
-
- fn unfurl_allowing_nsfw(url: &str) -> UnfurlRequest {
- UnfurlRequest::Unfurl {
- url: url.to_owned(),
- nsfw_mode: Some(NsfwMode::Allow),
- bypass_cache: false,
- cache_only: false,
- youtube_api_key: None,
- klipy_api_key: None,
- }
- }
-
- #[test]
- fn configuring_a_youtube_key_does_not_reuse_the_keyless_cache_entry() {
- let router = UnfurlRouter::new(16, test_lifetime());
- let url = "https://www.youtube.com/watch?v=dQw4w9WgXcQ";
- router.l1_insert(&unfurl(url, None), &resolved_response());
- assert!(
- router.l1_lookup(&unfurl(url, Some("configured"))).is_none(),
- "a result resolved without a YouTube key must not be served once a key is configured"
- );
- assert!(
- router.l1_lookup(&unfurl(url, None)).is_some(),
- "the keyless entry must still serve keyless requests"
- );
- }
-
- #[test]
- fn coalesce_key_separates_cache_only_from_full_unfurls() {
- assert_ne!(
- UnfurlRouter::coalesce_key(&request(true)),
- UnfurlRouter::coalesce_key(&request(false))
- );
- }
- #[test]
- fn a_url_that_produced_no_embed_is_remembered_instead_of_being_resolved_again() {
- let router = UnfurlRouter::new(16, test_lifetime());
- let url = "https://example.com/no-metadata";
- router.l1_insert(&unfurl(url, None), &empty_response());
- assert!(
- router.l1_lookup(&unfurl(url, None)).is_some(),
- "an empty resolution must be served from the upper cache, not re-resolved"
- );
- }
-
- #[test]
- fn an_empty_cache_only_probe_is_never_written_to_the_upper_cache() {
- let router = UnfurlRouter::new(16, test_lifetime());
- let url = "https://example.com/never-probed-into-cache";
- router.l1_insert(&probe(url), &empty_response());
- assert!(
- router.l1_lookup(&unfurl(url, None)).is_none(),
- "a cache-only miss means unknown, not resolved-to-nothing"
- );
- }
-
- #[test]
- fn a_cache_only_probe_that_found_embeds_still_warms_the_upper_cache() {
- let router = UnfurlRouter::new(16, test_lifetime());
- let url = "https://example.com/warm";
- router.l1_insert(&probe(url), &resolved_response());
- assert!(router.l1_lookup(&unfurl(url, None)).is_some());
- }
-
- #[test]
- fn configuring_a_klipy_key_does_not_reuse_the_keyless_cache_entry() {
- let router = UnfurlRouter::new(16, test_lifetime());
- let url = "https://klipy.com/gifs/example";
- router.l1_insert(&unfurl_with_klipy(url, None), &resolved_response());
- assert!(
- router
- .l1_lookup(&unfurl_with_klipy(url, Some("configured")))
- .is_none(),
- "a result resolved without a KLIPY key must not be served once a key is configured"
- );
- assert!(
- router.l1_lookup(&unfurl_with_klipy(url, None)).is_some(),
- "the keyless entry must still serve keyless requests"
- );
- }
-
- #[test]
- fn an_unscanned_entry_is_not_served_to_a_scanning_request() {
- let router = UnfurlRouter::new(16, test_lifetime());
- let url = "https://example.com/media";
- router.l1_insert(&unfurl_allowing_nsfw(url), &resolved_response());
- assert!(
- router.l1_lookup(&unfurl(url, None)).is_none(),
- "a result resolved with nsfw scanning off has no nsfw flags and must not be reused"
- );
- assert!(router.l1_lookup(&unfurl_allowing_nsfw(url)).is_some());
- }
-
- #[tokio::test]
- async fn an_empty_upper_cache_entry_lapses_long_before_a_populated_one() {
- let router =
- UnfurlRouter::with_empty_entry_lifetime(16, test_lifetime(), Duration::from_millis(50));
- let empty_url = "https://example.com/transient";
- let populated_url = "https://example.com/stable";
- router.l1_insert(&unfurl(empty_url, None), &empty_response());
- router.l1_insert(&unfurl(populated_url, None), &resolved_response());
-
- tokio::time::sleep(Duration::from_millis(200)).await;
-
- assert!(
- router.l1_lookup(&unfurl(empty_url, None)).is_none(),
- "a link that failed to unfurl must become retryable again quickly"
- );
- assert!(
- router.l1_lookup(&unfurl(populated_url, None)).is_some(),
- "a real embed must keep the full lifetime"
- );
- }
- #[tokio::test]
- async fn the_configured_lifetime_governs_the_upper_cache() {
- let router = UnfurlRouter::new(16, Duration::from_millis(80));
- let url = "https://example.com/configured";
- router.l1_insert(&unfurl(url, None), &resolved_response());
- tokio::time::sleep(Duration::from_millis(220)).await;
- assert!(
- router.l1_lookup(&unfurl(url, None)).is_none(),
- "the configured lifetime must govern the upper cache"
- );
- }
-}
diff --git a/fluxer_unfurl/src/sanitizer.rs b/fluxer_unfurl/src/sanitizer.rs
index 572995e87..c01d8bbfd 100644
--- a/fluxer_unfurl/src/sanitizer.rs
+++ b/fluxer_unfurl/src/sanitizer.rs
@@ -132,26 +132,6 @@ mod tests {
assert_eq!(result, Some("<p>Hello</p>".to_owned()));
}
- #[test]
- fn empty_input_returns_none() {
- assert_eq!(sanitize_oembed_html(""), None);
- assert_eq!(sanitize_oembed_html(" "), None);
- }
-
- #[test]
- fn trusted_host_check() {
- assert!(is_trusted_oembed_host("youtube.com"));
- assert!(is_trusted_oembed_host("www.youtube.com"));
- assert!(!is_trusted_oembed_host("evil.com"));
- }
-
- #[test]
- fn keeps_trusted_iframe_src() {
- let html = r#"<iframe src="https://www.youtube.com/embed/abc"></iframe>"#;
- let result = sanitize_oembed_html(html).unwrap();
- assert!(result.contains(r#"src="https://www.youtube.com/embed/abc""#));
- }
-
#[test]
fn strips_untrusted_iframe_src() {
let html = r#"<iframe src="https://youtube.com.evil.test/embed"></iframe>"#;
@@ -167,31 +147,6 @@ mod tests {
assert!(!result.contains("src="));
}
- #[test]
- fn keeps_basic_formatting_tags() {
- let html = r#"<p><strong>Bold</strong> <em>italic</em> <b>b</b> <i>i</i></p>"#;
- let result = sanitize_oembed_html(html).unwrap();
- assert!(result.contains("<strong>Bold</strong>"));
- assert!(result.contains("<em>italic</em>"));
- }
-
- #[test]
- fn strips_style_and_img_tags() {
- let html = r#"<style>body{}</style><img src="x"><p>Keep</p>"#;
- let result = sanitize_oembed_html(html).unwrap();
- assert!(!result.contains("style"));
- assert!(!result.contains("img"));
- assert!(result.contains("<p>Keep</p>"));
- }
-
- #[test]
- fn keeps_blockquote_with_cite() {
- let html = r#"<blockquote cite="https://e.com/post">Quote text</blockquote>"#;
- let result = sanitize_oembed_html(html).unwrap();
- assert!(result.contains("blockquote"));
- assert!(result.contains(r#"cite="https://e.com/post""#));
- }
-
#[test]
fn anchor_gets_rel_noopener() {
let html = r#"<a href="https://e.com">Link</a>"#;
@@ -199,48 +154,6 @@ mod tests {
assert!(result.contains("noopener"));
}
- #[test]
- fn iframe_keeps_sandbox_and_dimensions() {
- let html = r#"<iframe src="https://www.youtube.com/embed/abc" width="640" height="360" sandbox="allow-scripts"></iframe>"#;
- let result = sanitize_oembed_html(html).unwrap();
- assert!(result.contains(r#"width="640""#));
- assert!(result.contains(r#"height="360""#));
- assert!(result.contains("sandbox"));
- }
-
- #[test]
- fn all_trusted_hosts_are_recognised() {
- for host in [
- "youtube.com",
- "www.youtube.com",
- "youtu.be",
- "youtube-nocookie.com",
- "vimeo.com",
- "player.vimeo.com",
- "soundcloud.com",
- "w.soundcloud.com",
- "spotify.com",
- "open.spotify.com",
- "twitter.com",
- "x.com",
- "reddit.com",
- "www.reddit.com",
- "tiktok.com",
- "www.tiktok.com",
- "codepen.io",
- "cdpn.io",
- ] {
- if host == "cdpn.io" {
- assert!(
- !is_trusted_oembed_host(host),
- "{host} should NOT be trusted"
- );
- } else {
- assert!(is_trusted_oembed_host(host), "{host} should be trusted");
- }
- }
- }
-
#[test]
fn context_sanitizer_rejects_untrusted_source_and_provider() {
let source = url::Url::parse("https://untrusted.com/page").unwrap();
@@ -252,22 +165,6 @@ mod tests {
);
}
- #[test]
- fn context_sanitizer_allows_trusted_source() {
- let source = url::Url::parse("https://www.youtube.com/watch?v=abc").unwrap();
- let html = r#"<p>Hello</p>"#;
- assert!(sanitize_oembed_html_with_context(html, &source, None).is_some());
- }
-
- #[test]
- fn context_sanitizer_allows_trusted_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, Some("https://youtube.com")).is_some()
- );
- }
-
#[test]
fn strips_javascript_uri_in_iframe() {
let html = r#"<iframe src="javascript:alert(1)"></iframe>"#;
diff --git a/fluxer_unfurl/src/shard_impl.rs b/fluxer_unfurl/src/shard_impl.rs
index 90faad1d9..2b5b984de 100644
--- a/fluxer_unfurl/src/shard_impl.rs
+++ b/fluxer_unfurl/src/shard_impl.rs
@@ -86,30 +86,6 @@ impl UnfurlShard {
}
}
- #[cfg(test)]
- fn for_test() -> Self {
- Self::for_test_with_lifetimes(long_lifetime(), default_empty_entry_lifetime())
- }
-
- #[cfg(test)]
- fn for_test_with_lifetimes(lifetime: Duration, empty_entry_lifetime: Duration) -> Self {
- Self {
- cache: build_l2_cache(lifetime, empty_entry_lifetime),
- lifetime,
- http_client: external_http_client(),
- resolvers: resolvers::build_resolver_chain(),
- media_proxy: MediaProxyClient::new_with_public_endpoint(
- "http://media-proxy.invalid",
- "test-secret",
- None,
- internal_http_client(),
- ),
- self_hosted: false,
- youtube_api_key: None,
- klipy_api_key: None,
- }
- }
-
async fn resolve_url(
&self,
url_str: &str,
@@ -219,11 +195,6 @@ impl UnfurlShard {
}
}
-#[cfg(test)]
-fn long_lifetime() -> Duration {
- Duration::from_secs(30 * 60)
-}
-
fn build_l2_cache(
lifetime: Duration,
empty_entry_lifetime: Duration,
@@ -316,298 +287,3 @@ impl ShardService for UnfurlShard {
}
}
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use crate::types::MessageEmbed;
- use std::sync::Mutex;
-
- const BLOCKED_URL: &str = "http://127.0.0.1/unreachable";
-
- static ENV_LOCK: Mutex<()> = Mutex::new(());
-
- const PUBLIC_ENDPOINT_ENV: [&str; 7] = [
- "FLUXER_MEDIA_PROXY_ENDPOINT",
- "FLUXER_MEDIA_PROXY_SECRET_KEY",
- "FLUXER_MEDIA_PROXY_PUBLIC_ENDPOINT",
- "FLUXER_SELF_HOSTED",
- "FLUXER_BASE_DOMAIN",
- "FLUXER_PUBLIC_PORT",
- "FLUXER_PUBLIC_ORIGIN",
- ];
-
- fn shard_from_env(vars: &[(&str, &str)]) -> UnfurlShard {
- let _guard = ENV_LOCK.lock().unwrap();
- for name in PUBLIC_ENDPOINT_ENV {
- unsafe { std::env::remove_var(name) };
- }
- for (name, value) in vars {
- unsafe { std::env::set_var(name, value) };
- }
- let shard = UnfurlShard::new(long_lifetime());
- for (name, _) in vars {
- unsafe { std::env::remove_var(name) };
- }
- shard
- }
-
- #[test]
- fn a_non_default_public_port_reaches_the_public_media_endpoint() {
- let shard = shard_from_env(&[
- ("FLUXER_MEDIA_PROXY_ENDPOINT", "http://media-proxy:8080"),
- ("FLUXER_MEDIA_PROXY_SECRET_KEY", "secret"),
- (
- "FLUXER_MEDIA_PROXY_PUBLIC_ENDPOINT",
- "http://fluxer.example/media",
- ),
- ("FLUXER_BASE_DOMAIN", "fluxer.example"),
- ("FLUXER_PUBLIC_PORT", "19080"),
- ]);
-
- assert!(
- shard
- .media_proxy
- .external_proxy_url("https://img.example.net/a.png")
- .expect("proxy url")
- .starts_with("http://fluxer.example:19080/media/external/")
- );
- }
-
- #[test]
- fn a_default_public_port_leaves_the_public_media_endpoint_alone() {
- let shard = shard_from_env(&[
- ("FLUXER_MEDIA_PROXY_ENDPOINT", "http://media-proxy:8080"),
- ("FLUXER_MEDIA_PROXY_SECRET_KEY", "secret"),
- (
- "FLUXER_MEDIA_PROXY_PUBLIC_ENDPOINT",
- "https://fluxer.example/media",
- ),
- ("FLUXER_BASE_DOMAIN", "fluxer.example"),
- ("FLUXER_PUBLIC_PORT", "443"),
- ]);
-
- assert!(
- shard
- .media_proxy
- .external_proxy_url("https://img.example.net/a.png")
- .expect("proxy url")
- .starts_with("https://fluxer.example/media/external/")
- );
- }
-
- #[test]
- fn self_hosted_follows_the_fluxer_self_hosted_env() {
- let media_proxy = [
- ("FLUXER_MEDIA_PROXY_ENDPOINT", "http://media-proxy:8080"),
- ("FLUXER_MEDIA_PROXY_SECRET_KEY", "secret"),
- ];
- assert!(!shard_from_env(&media_proxy).self_hosted);
- let mut vars = media_proxy.to_vec();
- vars.push(("FLUXER_SELF_HOSTED", "true"));
- assert!(shard_from_env(&vars).self_hosted);
- }
-
- fn unfurl(url: &str, youtube_api_key: Option<&str>) -> UnfurlRequest {
- UnfurlRequest::Unfurl {
- url: url.to_owned(),
- nsfw_mode: Some(NsfwMode::Block),
- bypass_cache: false,
- cache_only: false,
- youtube_api_key: youtube_api_key.map(str::to_owned),
- klipy_api_key: None,
- }
- }
-
- fn probe(url: &str) -> UnfurlRequest {
- UnfurlRequest::Unfurl {
- url: url.to_owned(),
- nsfw_mode: Some(NsfwMode::Block),
- bypass_cache: false,
- cache_only: true,
- youtube_api_key: None,
- klipy_api_key: None,
- }
- }
-
- fn keyless_block_key(url: &str) -> String {
- unfurl_cache_key(url, NsfwMode::Block, provider_capability(false, false))
- }
-
- fn embed_count(response: &UnfurlResponse) -> usize {
- match response {
- UnfurlResponse::Resolved(result) => result.embeds.len(),
- _ => panic!("expected a resolved response"),
- }
- }
-
- async fn seed_keyless_entry(shard: &UnfurlShard) {
- shard
- .cache
- .insert(
- unfurl_cache_key(
- BLOCKED_URL,
- NsfwMode::Block,
- provider_capability(false, false),
- ),
- Arc::new(UnfurlResult {
- embeds: vec![MessageEmbed::new("link")],
- cache_ttl_seconds: Some(long_lifetime().as_secs()),
- }),
- )
- .await;
- }
-
- #[tokio::test]
- async fn a_shard_entry_resolved_without_a_youtube_key_is_not_served_once_one_is_configured() {
- let shard = UnfurlShard::for_test();
- seed_keyless_entry(&shard).await;
-
- assert_eq!(
- 1,
- embed_count(&shard.handle(unfurl(BLOCKED_URL, None)).await.unwrap()),
- "the keyless entry must still serve keyless requests"
- );
- assert_eq!(
- 0,
- embed_count(
- &shard
- .handle(unfurl(BLOCKED_URL, Some("configured")))
- .await
- .unwrap()
- ),
- "a result resolved without a YouTube key must not be served once a key is configured"
- );
- }
-
- #[tokio::test]
- async fn a_url_that_produced_no_embed_is_written_to_the_shard_cache() {
- let shard = UnfurlShard::for_test();
-
- assert_eq!(
- 0,
- embed_count(&shard.handle(unfurl(BLOCKED_URL, None)).await.unwrap())
- );
- assert!(
- shard
- .cache
- .get(&keyless_block_key(BLOCKED_URL))
- .await
- .is_some(),
- "an empty resolution must be remembered so the next message does not refetch the page"
- );
- }
-
- #[tokio::test]
- async fn a_cache_only_probe_never_writes_an_entry() {
- let shard = UnfurlShard::for_test();
-
- assert_eq!(
- 0,
- embed_count(&shard.handle(probe(BLOCKED_URL)).await.unwrap())
- );
- assert!(
- shard
- .cache
- .get(&keyless_block_key(BLOCKED_URL))
- .await
- .is_none(),
- "a cache-only miss means unknown, not resolved-to-nothing"
- );
- }
-
- #[tokio::test]
- async fn an_unscanned_entry_is_not_served_to_a_scanning_request() {
- let shard = UnfurlShard::for_test();
- shard
- .cache
- .insert(
- unfurl_cache_key(
- BLOCKED_URL,
- NsfwMode::Allow,
- provider_capability(false, false),
- ),
- Arc::new(UnfurlResult {
- embeds: vec![MessageEmbed::new("link")],
- cache_ttl_seconds: Some(long_lifetime().as_secs()),
- }),
- )
- .await;
-
- assert_eq!(
- 0,
- embed_count(&shard.handle(unfurl(BLOCKED_URL, None)).await.unwrap()),
- "a result resolved with nsfw scanning off must not be served to a scanning request"
- );
- }
- #[tokio::test]
- async fn an_empty_shard_entry_lapses_long_before_a_populated_one() {
- let shard =
- UnfurlShard::for_test_with_lifetimes(long_lifetime(), Duration::from_millis(50));
- let empty_key = keyless_block_key("https://example.com/transient");
- let populated_key = keyless_block_key("https://example.com/stable");
- shard
- .cache
- .insert(
- empty_key.clone(),
- Arc::new(UnfurlResult {
- embeds: Vec::new(),
- cache_ttl_seconds: None,
- }),
- )
- .await;
- shard
- .cache
- .insert(
- populated_key.clone(),
- Arc::new(UnfurlResult {
- embeds: vec![MessageEmbed::new("link")],
- cache_ttl_seconds: Some(long_lifetime().as_secs()),
- }),
- )
- .await;
-
- tokio::time::sleep(Duration::from_millis(200)).await;
-
- assert!(
- shard.cache.get(&empty_key).await.is_none(),
- "a link that failed to unfurl must become retryable again quickly"
- );
- assert!(
- shard.cache.get(&populated_key).await.is_some(),
- "a real embed must keep the full lifetime"
- );
- }
- #[tokio::test]
- async fn the_configured_lifetime_governs_the_shard_cache_and_the_reported_ttl() {
- let shard = UnfurlShard::for_test_with_lifetimes(
- Duration::from_millis(80),
- default_empty_entry_lifetime(),
- );
- let finalized = shard.finalize_result(crate::resolvers::ResolverResult {
- embeds: vec![MessageEmbed::new("link")],
- });
- assert_eq!(
- Some(Duration::from_millis(80).as_secs()),
- finalized.cache_ttl_seconds,
- "the reported ttl must be the configured lifetime, not a compiled-in constant"
- );
-
- let key = keyless_block_key("https://example.com/configured");
- shard
- .cache
- .insert(
- key.clone(),
- Arc::new(UnfurlResult {
- embeds: vec![MessageEmbed::new("link")],
- cache_ttl_seconds: None,
- }),
- )
- .await;
- tokio::time::sleep(Duration::from_millis(220)).await;
- assert!(
- shard.cache.get(&key).await.is_none(),
- "the configured lifetime must govern the shard cache"
- );
- }
-}
diff --git a/fluxer_unfurl/src/text_limits.rs b/fluxer_unfurl/src/text_limits.rs
index d0375e816..339a74ac0 100644
--- a/fluxer_unfurl/src/text_limits.rs
+++ b/fluxer_unfurl/src/text_limits.rs
@@ -41,16 +41,3 @@ pub fn clamp_lines(s: &str, max_lines: usize) -> String {
result.push("\u{2026}");
result.join("\n")
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn truncate_preserves_multibyte_boundaries() {
- let s = "hello 🎉🎊🎁 world";
- let result = truncate(s, 10);
- assert!(result.chars().count() <= 10);
- assert!(result.ends_with('\u{2026}'));
- }
-}
diff --git a/fluxer_unfurl/src/types.rs b/fluxer_unfurl/src/types.rs
index d17b3c2bf..a7a81faf3 100644
--- a/fluxer_unfurl/src/types.rs
+++ b/fluxer_unfurl/src/types.rs
@@ -206,16 +206,4 @@ mod tests {
}
}
}
-
- #[test]
- fn provider_always_serializes_its_name() {
- let provider = EmbedProvider {
- name: "Tenor".to_owned(),
- url: None,
- };
- assert_eq!(
- serde_json::to_value(&provider).unwrap(),
- serde_json::json!({"name": "Tenor"})
- );
- }
}