rustango 0.67.0

Batteries-included web framework for Rust: ORM + migrations + auto-admin + multi-tenancy + audit log + auth (sessions, JWT, OAuth2/OIDC, HMAC) + APIs (ViewSet, OpenAPI auto-derive, JSON:API) + jobs (in-mem + Postgres) + email + media (S3 / R2 / B2 / MinIO + presigned uploads + collections + tags) + production middleware (CSRF, CSP, rate-limiting, compression, idempotency, etc.).
Documentation
//! `manage run-server` — the development server.
//!
//! Boots a complete operator + tenant admin stack with sensible
//! defaults from env. Users running `cargo run --
//! run-server` get:
//!
//! * Operator console at the apex (form login, sidebar layout) —
//!   only `rustango_orgs` and `rustango_operators` visible.
//! * Tenant admin at every subdomain — every `#[derive(Model)]`
//!   linked into the binary is automatically visible.
//! * Host-based dispatch matching the production routing story.
//! * Graceful shutdown on Ctrl-C.
//!
//! ## Env vars consumed
//!
//! | Var | Default | Effect |
//! |-----|---------|--------|
//! | `RUSTANGO_BIND` | `0.0.0.0:8080` | listener address |
//! | `RUSTANGO_APEX_DOMAIN` | `localhost` | apex host (operator surface); subdomains route to tenants |
//! | `RUSTANGO_SESSION_SECRET` | random + warn | HMAC key for operator session cookies |
//!
//! ## When to use it
//!
//! When your operator-experience defaults are good enough — read-only
//! operator on `rustango_orgs` + `rustango_operators`, every other
//! `#[derive(Model)]` available under tenant subdomains. If you need
//! per-model allow-lists, custom resolver chains, operator routes that
//! mutate, or arbitrary middleware, hand-roll your binary using
//! `operator_console::router` + `admin::TenantAdminBuilder` directly
//! (`examples/multitenant_demo.rs` shows the full shape).

/// Defaults for `manage run-server`. All fields are env-overridable;
/// the struct is exposed so programmatic callers can tweak them.
#[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 {
    /// Read overrides from env: `RUSTANGO_BIND` and the apex from
    /// [`apex_domain`]. Anything unset uses the default.
    #[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
    }
}

/// `[tenancy] apex_domain`, recorded at boot by `Cli::with_settings`.
static APEX_FROM_SETTINGS: std::sync::RwLock<Option<String>> = std::sync::RwLock::new(None);

/// Serializes tests that touch [`APEX_FROM_SETTINGS`].
#[cfg(test)]
pub(crate) static APEX_TEST_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());

/// Record `[tenancy] apex_domain`. The first call wins, like the other boot
/// globals; a later, different value is logged rather than dropped silently.
#[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(_) => {}
    }
}

/// Forget the recorded apex, so each test starts clean.
#[cfg(test)]
pub(crate) fn reset_apex_domain_setting() {
    *APEX_FROM_SETTINGS
        .write()
        .unwrap_or_else(std::sync::PoisonError::into_inner) = None;
}

/// The recorded `[tenancy] apex_domain`, ignoring the env var.
pub(crate) fn apex_domain_setting() -> Option<String> {
    APEX_FROM_SETTINGS
        .read()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
        .clone()
}

/// `RUSTANGO_APEX_DOMAIN`, else `[tenancy] apex_domain`; env wins, as for `bind`.
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)
}

/// The apex host, defaulting to `localhost`.
pub(crate) fn apex_domain() -> String {
    configured_apex_domain().unwrap_or_else(|| "localhost".into())
}

/// The apex tenant links point at: a `server::Builder`'s own, which its
/// dispatch matches, else [`apex_domain`].
#[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)
    }
}

/// `RUSTANGO_TENANT_PORT_ROUTING=1`: the app routes tenants by listener port itself.
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"))
}

/// `RUSTANGO_TENANT_SCHEME`, empty counted as unset. The one reader of it.
pub(crate) fn tenant_scheme_setting() -> Option<String> {
    std::env::var("RUSTANGO_TENANT_SCHEME")
        .ok()
        .filter(|s| !s.is_empty())
}

/// `{scheme}://{host}{port_suffix}` for a link into a tenant host. The
/// scheme is [`tenant_scheme_setting`], else https wherever cookies are
/// `Secure`, so a handoff token is not sent in clear by default (#2425).
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}")
}

/// A link to `path` on `org`'s tenant host. `request_host` is the
/// caller's own `Host`, whose port is the last fallback.
///
/// # Errors
/// [`super::TenancyError::Validation`] for an org no resolver routes: no
/// host or path prefix (a port alone counts only with port routing on).
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(),
        // A path-prefix tenant lives on the apex; a port-routed one links to `<slug>.<apex>`.
        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('/')
    ))
}

/// The org's path prefix for a tenant link, or `""` when the stored
/// value is not one segment: `//evil.example` would redirect off-site.
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("")
}

/// Port for a tenant link. A port-routed org's own port wins;
/// then `RUSTANGO_TENANT_PORT`; then the caller's request port.
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)
}

/// [`tenant_port_suffix`] with the env value passed in.
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()
}

/// A loopback host stays http: it never crosses the network, and browsers
/// keep `Secure` cookies on it.
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"));
    }

    /// An org with no host, path prefix or port gets no link: no resolver
    /// would route it. Any one of the three is enough.
    #[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());
        // The built-in server does not route by port, so a port alone gets no link.
        let mut ported = bare;
        ported.port = Some(8081);
        assert!(tenant_link(&ported, "/x", None, &apex).is_err());
    }

    /// #2425 — a handoff link defaults to https where cookies are Secure.
    #[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");
        // Loopback dev keeps http; the env var always wins.
        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"
        );
    }

    /// #2425 — loopback is an address or `localhost`, port or not; a
    /// public name that starts with `127.` is not loopback.
    #[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}");
        }
    }

    /// A second, different apex keeps the first (and warns) (#2225).
    #[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();
    }
}