Skip to content

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

TypeScript fluxerfluxerapp

feat(unfurl): follow www redirects when checking domains

Hampus0de5cc9c9fbd
diff --git a/fluxer_docs/src/content/docs/http-api/connections.mdx b/fluxer_docs/src/content/docs/http-api/connections.mdx
index d64d9817c..526322c26 100644
--- a/fluxer_docs/src/content/docs/http-api/connections.mdx
+++ b/fluxer_docs/src/content/docs/http-api/connections.mdx
@@ -63,7 +63,7 @@ The flags decide which viewers see the connection on the owner's profile, using
Fluxer checks the proof once, when the connection is created. Use either method.
- Publish a TXT record at `_fluxer.<domain>` with the value `fluxer-verification=<token>`.
-- Serve the token alone, without the prefix, at `https://<domain>/.well-known/fluxer-verification` with a 2xx status. Redirects are not followed.
+- Serve the token alone, without the prefix, at `https://<domain>/.well-known/fluxer-verification` with a 2xx status. Fluxer follows up to three HTTPS redirects to the same path on the domain with or without `www.`.
## Bluesky authorization object
diff --git a/fluxer_unfurl/src/dns_txt.rs b/fluxer_unfurl/src/dns_txt.rs
new file mode 100644
index 000000000..a97b9c994
--- /dev/null
+++ b/fluxer_unfurl/src/dns_txt.rs
@@ -0,0 +1,156 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+use fluxer_common::public_ip::is_valid_public_hostname;
+use hickory_resolver::TokioResolver;
+use hickory_resolver::config::{NameServerConfig, ResolveHosts, ResolverConfig, ResolverOpts};
+use hickory_resolver::net::runtime::TokioRuntimeProvider;
+use hickory_resolver::proto::rr::{RData, RecordType};
+use std::net::{IpAddr, Ipv4Addr};
+use std::time::Duration;
+use tokio::task::JoinSet;
+use tokio::time::timeout;
+
+const DNS_TIMEOUT: Duration = Duration::from_millis(1500);
+const DNS_SERVERS: [Ipv4Addr; 8] = [
+ Ipv4Addr::new(1, 1, 1, 1),
+ Ipv4Addr::new(1, 0, 0, 1),
+ Ipv4Addr::new(8, 8, 8, 8),
+ Ipv4Addr::new(8, 8, 4, 4),
+ Ipv4Addr::new(9, 9, 9, 9),
+ Ipv4Addr::new(149, 112, 112, 112),
+ Ipv4Addr::new(208, 67, 222, 222),
+ Ipv4Addr::new(208, 67, 220, 220),
+];
+
+pub fn validate_record_name(name: &str) -> anyhow::Result<()> {
+ let host = match name.split_once('.') {
+ Some((label, rest)) if label.len() > 1 && label.starts_with('_') => {
+ if !label[1..]
+ .bytes()
+ .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
+ {
+ anyhow::bail!("invalid record name");
+ }
+ rest
+ }
+ _ => name,
+ };
+ validate_hostname(host)
+}
+
+pub fn validate_hostname(host: &str) -> anyhow::Result<()> {
+ if !is_valid_public_hostname(host) || host.bytes().any(|b| b.is_ascii_uppercase()) {
+ anyhow::bail!("invalid hostname");
+ }
+ Ok(())
+}
+
+pub async fn first_answer<F>(name: &str, accept: F) -> Option<Vec<String>>
+where
+ F: Fn(&[String]) -> bool,
+{
+ let record_name = format!("{name}.");
+ let mut lookups = JoinSet::new();
+ for server in DNS_SERVERS {
+ let record_name = record_name.clone();
+ lookups.spawn(async move { lookup_txt(IpAddr::V4(server), &record_name).await });
+ }
+ while let Some(result) = lookups.join_next().await {
+ match result {
+ Ok(Ok(records)) if accept(&records) => {
+ lookups.abort_all();
+ return Some(records);
+ }
+ Ok(Ok(_)) => {}
+ Ok(Err(err)) => {
+ tracing::debug!(error = %err, name, "DNS TXT lookup failed");
+ }
+ Err(err) => {
+ tracing::debug!(error = %err, name, "DNS TXT lookup task failed");
+ }
+ }
+ }
+ None
+}
+
+async fn lookup_txt(server: IpAddr, record_name: &str) -> anyhow::Result<Vec<String>> {
+ let mut options = ResolverOpts::default();
+ options.timeout = DNS_TIMEOUT;
+ options.cache_size = 0;
+ options.use_hosts_file = ResolveHosts::Never;
+ let config = ResolverConfig::from_name_servers(vec![NameServerConfig::udp_and_tcp(server)]);
+ let resolver: TokioResolver =
+ TokioResolver::builder_with_config(config, TokioRuntimeProvider::default())
+ .with_options(options)
+ .build()?;
+ let lookup = timeout(DNS_TIMEOUT, resolver.lookup(record_name, RecordType::TXT))
+ .await
+ .map_err(|_| anyhow::anyhow!("DNS lookup timed out"))??;
+ Ok(lookup
+ .answers()
+ .iter()
+ .filter_map(|record| match &record.data {
+ RData::TXT(txt) => Some(join_txt_strings(&txt.txt_data)),
+ _ => None,
+ })
+ .collect())
+}
+
+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 2801f3b8c..1b341f386 100644
--- a/fluxer_unfurl/src/domain_verification.rs
+++ b/fluxer_unfurl/src/domain_verification.rs
@@ -1,13 +1,7 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
-use crate::{http_fetch, network_policy};
-use fluxer_common::public_ip::is_valid_public_hostname;
-use hickory_resolver::TokioResolver;
-use hickory_resolver::config::{NameServerConfig, ResolveHosts, ResolverConfig, ResolverOpts};
-use hickory_resolver::net::runtime::TokioRuntimeProvider;
-use hickory_resolver::proto::rr::{RData, RecordType};
-use reqwest::header::{ACCEPT_ENCODING, CONTENT_ENCODING, HeaderValue};
-use std::net::{IpAddr, Ipv4Addr};
+use crate::{dns_txt, http_fetch, network_policy};
+use reqwest::header::{ACCEPT_ENCODING, CONTENT_ENCODING, HeaderValue, LOCATION};
use std::time::Duration;
use tokio::time::timeout;
use url::Url;
@@ -15,6 +9,7 @@ use url::Url;
const WELL_KNOWN_TIMEOUT: Duration = Duration::from_millis(3000);
const WELL_KNOWN_MAX_BYTES: usize = 16 * 1024;
const WELL_KNOWN_PATH: &str = "/.well-known/fluxer-verification";
+const WELL_KNOWN_MAX_REDIRECTS: usize = 3;
const MAX_TOKEN_BYTES: usize = 256;
pub async fn verify_domain(
@@ -22,7 +17,7 @@ pub async fn verify_domain(
domain: &str,
token: &str,
) -> anyhow::Result<bool> {
- validate_domain(domain)?;
+ dns_txt::validate_hostname(domain)?;
if token.is_empty() || token.len() > MAX_TOKEN_BYTES {
anyhow::bail!("invalid verification token");
}
@@ -49,27 +44,11 @@ pub async fn verify_domain(
async fn dns_txt_matches(domain: &str, token: &str) -> bool {
let expected = format!("fluxer-verification={token}");
- let mut lookups = JoinSet::new();
- for server in DNS_SERVERS {
- let record_name = record_name.clone();
- lookups.spawn(async move { lookup_txt(IpAddr::V4(server), &record_name).await });
- }
- while let Some(result) = lookups.join_next().await {
- match result {
- Ok(Ok(records)) if records.iter().any(|record| record == &expected) => {
- lookups.abort_all();
- return true;
- }
- Ok(Ok(_)) => {}
- Ok(Err(err)) => {
- tracing::debug!(error = %err, domain, "DNS TXT verification lookup failed");
- }
- Err(err) => {
- tracing::debug!(error = %err, domain, "DNS TXT verification task failed");
- }
- }
- }
- false
+ dns_txt::first_answer(&format!("_fluxer.{domain}"), |records| {
+ records.iter().any(|record| record == &expected)
+ })
+ .await
+ .is_some()
}
async fn well_known_matches(
@@ -77,34 +56,64 @@ async fn well_known_matches(
domain: &str,
token: &str,
) -> anyhow::Result<bool> {
- let url = Url::parse(&format!("https://{domain}{WELL_KNOWN_PATH}"))?;
- if url.host_str() != Some(domain) || url.port().is_some() || url.path() != WELL_KNOWN_PATH {
- anyhow::bail!("verification URL does not match the domain");
- }
- network_policy::validate_url(&url).await?;
- let response = client
- .get(url)
- .header(ACCEPT_ENCODING, HeaderValue::from_static("identity"))
- .send()
- .await?;
- if !response.status().is_success() {
- return Ok(false);
- }
- if let Some(encoding) = response.headers().get(CONTENT_ENCODING)
- && !encoding
- .to_str()
- .is_ok_and(|value| value.trim().eq_ignore_ascii_case("identity"))
- {
- return Ok(false);
- }
- if response
- .content_length()
- .is_some_and(|len| len > WELL_KNOWN_MAX_BYTES as u64)
- {
- return Ok(false);
+ let mut url = Url::parse(&format!("https://{domain}{WELL_KNOWN_PATH}"))?;
+ for _ in 0..=WELL_KNOWN_MAX_REDIRECTS {
+ if !is_same_site_well_known(&url, domain) {
+ return Ok(false);
+ }
+ network_policy::validate_url(&url).await?;
+ let response = client
+ .get(url.clone())
+ .header(ACCEPT_ENCODING, HeaderValue::from_static("identity"))
+ .send()
+ .await?;
+ if response.status().is_redirection() {
+ let Some(location) = response
+ .headers()
+ .get(LOCATION)
+ .and_then(|value| value.to_str().ok())
+ else {
+ return Ok(false);
+ };
+ url = network_policy::resolve_redirect(&url, location)?;
+ continue;
+ }
+ if !response.status().is_success() {
+ return Ok(false);
+ }
+ if let Some(encoding) = response.headers().get(CONTENT_ENCODING)
+ && !encoding
+ .to_str()
+ .is_ok_and(|value| value.trim().eq_ignore_ascii_case("identity"))
+ {
+ return Ok(false);
+ }
+ if response
+ .content_length()
+ .is_some_and(|len| len > WELL_KNOWN_MAX_BYTES as u64)
+ {
+ return Ok(false);
+ }
+ let body = http_fetch::read_body(response, WELL_KNOWN_MAX_BYTES).await?;
+ return Ok(body_matches_token(&body, token));
}
- let body = http_fetch::read_body(response, WELL_KNOWN_MAX_BYTES).await?;
- Ok(body_matches_token(&body, token))
+ Ok(false)
+}
+
+fn is_same_site_well_known(url: &Url, domain: &str) -> bool {
+ let Some(host) = url.host_str() else {
+ return false;
+ };
+ let same_site = host == domain
+ || host.strip_prefix("www.") == Some(domain)
+ || domain.strip_prefix("www.") == Some(host);
+ url.scheme() == "https"
+ && same_site
+ && url.port().is_none()
+ && url.path() == WELL_KNOWN_PATH
+ && url.query().is_none()
+ && url.username().is_empty()
+ && url.password().is_none()
}
fn body_matches_token(body: &[u8], token: &str) -> bool {
@@ -127,11 +136,45 @@ mod tests {
}
#[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");
+ 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/main.rs b/fluxer_unfurl/src/main.rs
index 195ad760a..5804c28ff 100644
--- a/fluxer_unfurl/src/main.rs
+++ b/fluxer_unfurl/src/main.rs
@@ -4,6 +4,7 @@ mod activity_pub;
mod cache_policy;
mod charset;
mod direct_media;
+mod dns_txt;
mod domain_verification;
mod embed_normalizer;
mod html_markdown;