#[derive(Debug, Clone)]
pub struct ServerConfig {
pub bind: String,
pub apex_domain: String,
}
impl Default for ServerConfig {
fn default() -> Self {
Self {
bind: crate::env::default_bind(&crate::env::tier_from_env()).into(),
apex_domain: "localhost".into(),
}
}
}
impl ServerConfig {
#[must_use]
pub fn from_env() -> Self {
let mut cfg = Self::default();
if let Ok(v) = std::env::var("RUSTANGO_BIND") {
cfg.bind = v;
}
if let Some(v) = configured_apex_domain() {
cfg.apex_domain = v;
}
cfg
}
}
static APEX_FROM_SETTINGS: std::sync::RwLock<Option<String>> = std::sync::RwLock::new(None);
#[cfg(test)]
pub(crate) static APEX_TEST_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
#[cfg(any(test, all(feature = "config", feature = "manage")))]
pub(crate) fn set_apex_domain_setting(apex: &str) {
if apex.is_empty() {
return;
}
let mut slot = APEX_FROM_SETTINGS
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner);
match slot.as_deref() {
None => *slot = Some(apex.to_owned()),
Some(kept) if kept != apex => tracing::warn!(
target: "rustango::tenancy",
kept,
ignored = apex,
"[tenancy] apex_domain was already set by an earlier Cli::with_settings; keeping the first"
),
Some(_) => {}
}
}
#[cfg(test)]
pub(crate) fn reset_apex_domain_setting() {
*APEX_FROM_SETTINGS
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner) = None;
}
pub(crate) fn apex_domain_setting() -> Option<String> {
APEX_FROM_SETTINGS
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.clone()
}
pub(crate) fn configured_apex_domain() -> Option<String> {
pick_apex(
std::env::var("RUSTANGO_APEX_DOMAIN").ok(),
apex_domain_setting(),
)
}
fn pick_apex(env: Option<String>, setting: Option<String>) -> Option<String> {
env.or(setting)
}
pub(crate) fn apex_domain() -> String {
configured_apex_domain().unwrap_or_else(|| "localhost".into())
}
#[derive(Clone, Debug, Default)]
pub(crate) struct LinkApex(Option<String>);
impl LinkApex {
pub(crate) fn new(apex: impl Into<String>) -> Self {
Self(Some(apex.into()))
}
pub(crate) fn get(&self) -> String {
self.0.clone().unwrap_or_else(apex_domain)
}
}
pub(crate) fn port_routing_setting() -> bool {
std::env::var("RUSTANGO_TENANT_PORT_ROUTING")
.is_ok_and(|v| matches!(v.trim(), "1" | "true" | "yes" | "on"))
}
pub(crate) fn tenant_scheme_setting() -> Option<String> {
std::env::var("RUSTANGO_TENANT_SCHEME")
.ok()
.filter(|s| !s.is_empty())
}
pub(crate) fn tenant_origin(host: &str, port_suffix: &str) -> String {
let scheme = pick_tenant_scheme(
tenant_scheme_setting(),
crate::session::secure_cookies(),
host,
);
format!("{scheme}://{host}{port_suffix}")
}
pub(crate) fn tenant_link(
org: &super::Org,
path: &str,
request_host: Option<&str>,
apex: &LinkApex,
) -> Result<String, super::TenancyError> {
if !super::provision::is_routable(
org.host_pattern.as_deref(),
org.path_prefix.as_deref(),
org.port,
) {
return Err(super::TenancyError::Validation(
super::provision::unroutable(&org.slug),
));
}
let prefix = tenant_path_prefix(org.path_prefix.as_deref());
let host = match org.host_pattern.as_deref().filter(|s| !s.is_empty()) {
Some(pattern) => pattern.to_owned(),
None if prefix.is_empty() => format!("{}.{}", org.slug, apex.get()),
None => apex.get(),
};
let port = tenant_port_suffix(org.port, request_host);
Ok(format!(
"{}{prefix}{}",
tenant_origin(&host, &port),
path.trim_end_matches('/')
))
}
pub(crate) fn tenant_path_prefix(path_prefix: Option<&str>) -> &str {
path_prefix
.map(|p| p.trim_end_matches('/'))
.filter(|p| crate::tenancy::provision::validate_path_prefix(p).is_ok())
.unwrap_or("")
}
pub(crate) fn tenant_port_suffix(org_port: Option<i32>, host: Option<&str>) -> String {
port_suffix_from(org_port, std::env::var("RUSTANGO_TENANT_PORT").ok(), host)
}
pub(crate) fn port_suffix_from(
org_port: Option<i32>,
env_port: Option<String>,
host: Option<&str>,
) -> String {
let usable = |p: &str| !p.is_empty() && p != "80" && p != "443";
if let Some(p) = org_port {
let p = p.to_string();
return if usable(&p) {
format!(":{p}")
} else {
String::new()
};
}
env_port
.filter(|p| usable(p))
.or_else(|| {
host.and_then(|h| crate::urls::split_host_port(h)?.1)
.map(|p| p.to_string())
.filter(|p| usable(p))
})
.map(|p| format!(":{p}"))
.unwrap_or_default()
}
fn pick_tenant_scheme(setting: Option<String>, secure: bool, host: &str) -> String {
if let Some(scheme) = setting.filter(|s| !s.is_empty()) {
return scheme;
}
if secure && !crate::urls::is_loopback_host(host) {
"https"
} else {
"http"
}
.into()
}
#[cfg(test)]
mod apex_tests {
use super::*;
#[test]
fn env_wins_over_the_setting() {
let s = || Some("toml.test".to_owned());
assert_eq!(
pick_apex(Some("env.test".into()), s()).as_deref(),
Some("env.test")
);
assert_eq!(pick_apex(None, s()).as_deref(), Some("toml.test"));
}
#[cfg(feature = "sqlite")]
#[test]
fn an_unroutable_org_gets_no_link() {
let apex = LinkApex::default();
let bare = crate::testkit::org_with(|o| {
o.slug = "acme".into();
o.host_pattern = None;
o.path_prefix = None;
o.port = None;
});
assert!(matches!(
tenant_link(&bare, "/x", None, &apex),
Err(crate::tenancy::TenancyError::Validation(_))
));
let mut prefixed = bare.clone();
prefixed.path_prefix = Some("acme".into());
assert!(tenant_link(&prefixed, "/x", None, &apex).is_ok());
let mut ported = bare;
ported.port = Some(8081);
assert!(tenant_link(&ported, "/x", None, &apex).is_err());
}
#[test]
fn tenant_links_default_to_https_when_cookies_are_secure() {
assert_eq!(pick_tenant_scheme(None, true, "acme.example.com"), "https");
assert_eq!(pick_tenant_scheme(None, false, "acme.example.com"), "http");
assert_eq!(pick_tenant_scheme(None, true, "acme.localhost"), "http");
assert_eq!(pick_tenant_scheme(None, true, "127.0.0.1"), "http");
assert_eq!(
pick_tenant_scheme(Some("http".into()), true, "acme.example.com"),
"http"
);
assert_eq!(
pick_tenant_scheme(Some(String::new()), true, "a.example.com"),
"https"
);
}
#[test]
fn only_real_loopback_hosts_keep_http() {
for host in [
"localhost",
"localhost:8080",
"acme.localhost:8080",
"127.0.0.1",
"127.0.0.1:8000",
"::1",
"[::1]",
"[::1]:8080",
] {
assert!(crate::urls::is_loopback_host(host), "{host}");
}
for host in [
"127.example.com",
"acme.example.com:443",
"[2001:db8::1]:80",
"10.0.0.1",
] {
assert!(!crate::urls::is_loopback_host(host), "{host}");
}
}
#[test]
fn the_first_apex_setting_wins() {
let _g = APEX_TEST_LOCK.blocking_lock();
reset_apex_domain_setting();
set_apex_domain_setting("one.test");
set_apex_domain_setting("two.test");
assert_eq!(apex_domain_setting().as_deref(), Some("one.test"));
reset_apex_domain_setting();
}
}