use std::sync::Arc;
use axum::extract::State;
use axum::response::{IntoResponse, Redirect, Response};
use axum::{Extension, Form};
use rustango::core::Column as _;
use rustango::extractors::{SessionUser, Tenant, TenantContext};
use rustango::sql::{FetcherPool as _, Pool};
use rustango::tenancy::HostError;
use serde::Deserialize;
use tera::Context;
use super::handlers::{add_admin_theme, add_chrome, render_with_csrf};
use super::AdminError;
use crate::page::Page;
use crate::site::Site;
pub const CODENAME: &str = "cms_site.manage";
async fn ensure_access(
tenant: &Tenant,
user: Option<&rustango::tenancy::auth::User>,
) -> Option<Response> {
super::codename_gate(tenant, user, CODENAME).await
}
fn host_err(e: HostError) -> AdminError {
match e {
HostError::Driver(e) => AdminError::Exec(e),
other => AdminError::Validation(other.to_string()),
}
}
fn parse_page_id(raw: &str) -> Result<i64, AdminError> {
let s = raw.trim();
if s.is_empty() {
return Ok(0);
}
s.parse()
.map_err(|_| AdminError::Validation(format!("`{s}` is not a page id")))
}
async fn resolve_root(pool: &Pool, root_page_id: i64) -> Result<Option<i64>, AdminError> {
if root_page_id == 0 {
return Ok(None);
}
let page: Option<Page> = Page::objects()
.where_(Page::id.eq(root_page_id))
.first(pool)
.await?;
if page.is_some() {
Ok(Some(root_page_id))
} else {
Err(AdminError::Validation(format!(
"no page with id {root_page_id}"
)))
}
}
async fn set_mapping(
pool: &Pool,
hostname: &str,
root_page_id: Option<i64>,
) -> Result<(), AdminError> {
let existing: Option<Site> = Site::objects()
.where_(Site::hostname.eq(hostname.to_owned()))
.first(pool)
.await?;
match (existing, root_page_id) {
(Some(mut row), Some(id)) => {
row.root_page_id = id;
row.save(pool).await?;
}
(Some(row), None) => {
row.delete(pool).await?;
}
(None, Some(id)) => {
let mut row = Site {
id: rustango::sql::Auto::Unset,
hostname: hostname.to_owned(),
root_page_id: id,
created_at: rustango::sql::Auto::Unset,
};
row.insert(pool).await?;
}
(None, None) => {}
}
Ok(())
}
pub(crate) async fn list(
State(state): State<super::AdminState>,
Extension(ctx): Extension<Arc<TenantContext>>,
tenant: Tenant,
headers: axum::http::HeaderMap,
SessionUser(session_user): SessionUser,
) -> Result<Response, AdminError> {
if let Some(r) = ensure_access(&tenant, session_user.as_ref()).await {
return Ok(r);
}
let registry = ctx.pools.registry_pool();
let hosts = rustango::tenancy::list_for_org(®istry, &tenant.org.slug)
.await
.map_err(host_err)?;
let mappings = crate::site::all(tenant.pool()).await?;
let mapped_ids: Vec<i64> = mappings.iter().map(|m| m.root_page_id).collect();
let mapped_pages: Vec<Page> = if mapped_ids.is_empty() {
Vec::new()
} else {
Page::objects()
.where_(Page::id.is_in(mapped_ids))
.fetch(tenant.pool())
.await?
};
let page_label = |id: i64| -> Option<String> {
mapped_pages
.iter()
.find(|p| p.id.get().copied() == Some(id))
.map(|p| {
if p.url_path.is_empty() {
p.title.clone()
} else {
format!("{} ({})", p.title, p.url_path)
}
})
};
let host_rows: Vec<serde_json::Value> = hosts
.iter()
.map(|h| {
let mapped = mappings.iter().find(|m| m.hostname == h.hostname);
let id = mapped.map_or(0, |m| m.root_page_id);
serde_json::json!({
"hostname": h.hostname,
"is_base": h.is_base,
"enabled": h.enabled,
"needs_approval": !h.enabled && !h.is_base && !self_service_host(&h.hostname),
"root_page_id": id,
"root_title": page_label(id),
"missing": id != 0 && page_label(id).is_none(),
})
})
.collect();
let orphan_rows: Vec<serde_json::Value> = mappings
.iter()
.filter(|m| !hosts.iter().any(|h| h.hostname == m.hostname))
.map(|m| {
serde_json::json!({
"hostname": m.hostname,
"root_title": page_label(m.root_page_id),
})
})
.collect();
let mut c = Context::new();
add_chrome(&mut c, &tenant, "sites", session_user.as_ref()).await;
add_admin_theme(&mut c, tenant.pool()).await;
c.insert("hosts", &host_rows);
c.insert("orphans", &orphan_rows);
c.insert("base_host", &tenant.org.host_pattern);
render_with_csrf(&state, &headers, "rcms_admin/sites.html", &mut c)
}
#[derive(Debug, Deserialize)]
pub(crate) struct SiteForm {
pub hostname: String,
#[serde(default)]
pub root_page_id: String,
}
#[derive(Debug, Deserialize)]
pub(crate) struct HostForm {
pub hostname: String,
}
fn self_service_host(host: &str) -> bool {
let suffixes = crate::config::var("SITE_HOST_SUFFIXES").unwrap_or_default();
host_under_suffixes(host, &suffixes)
}
fn apex_domain() -> String {
std::env::var("RUSTANGO_APEX_DOMAIN")
.ok()
.or_else(|| {
rustango::config::Settings::load_from_env()
.ok()
.and_then(|s| s.tenancy.apex_domain)
})
.unwrap_or_else(|| "localhost".to_owned())
}
fn is_apex(host: &str, apex: &str) -> bool {
host.eq_ignore_ascii_case(apex.strip_suffix('.').unwrap_or(apex))
}
fn host_under_suffixes(host: &str, suffixes: &str) -> bool {
suffixes
.split(',')
.map(|s| s.trim().trim_start_matches('.').to_ascii_lowercase())
.filter(|s| !s.is_empty())
.any(|s| host == s || host.ends_with(&format!(".{s}")))
}
async fn add_pending_host(
registry: &rustango::sql::Pool,
org: &rustango::tenancy::Org,
host: &str,
) -> Result<(), AdminError> {
use rustango::core::Column as _;
use rustango::tenancy::{Org, OrgHost};
let taken = Org::objects()
.where_(Org::host_pattern.eq(Some(host.to_owned())))
.first(registry)
.await?
.is_some()
|| OrgHost::objects()
.where_(OrgHost::hostname.eq(host.to_owned()))
.first(registry)
.await?
.is_some();
if taken {
return Err(host_err(HostError::Taken(host.to_owned())));
}
let mut row = OrgHost {
id: rustango::sql::Auto::Unset,
org_id: org.id.get().copied().unwrap_or_default(),
hostname: host.to_owned(),
enabled: false,
created_at: rustango::sql::Auto::Unset,
};
row.insert(registry).await?;
Ok(())
}
pub(crate) async fn add(
Extension(ctx): Extension<Arc<TenantContext>>,
tenant: Tenant,
SessionUser(session_user): SessionUser,
Form(form): Form<SiteForm>,
) -> Result<Response, AdminError> {
if let Some(r) = ensure_access(&tenant, session_user.as_ref()).await {
return Ok(r);
}
let host = rustango::tenancy::normalize_hostname(&form.hostname).map_err(host_err)?;
let root = resolve_root(tenant.pool(), parse_page_id(&form.root_page_id)?).await?;
let registry = ctx.pools.registry_pool();
let known = rustango::tenancy::list_for_org(®istry, &tenant.org.slug)
.await
.map_err(host_err)?;
if !known.iter().any(|h| h.hostname == host) {
let apex = apex_domain();
if is_apex(&host, &apex) {
return Err(host_err(HostError::IsApex(host)));
}
if self_service_host(&host) {
rustango::tenancy::add_host(®istry, &tenant.org.slug, &host, &apex)
.await
.map_err(host_err)?;
} else {
add_pending_host(®istry, &tenant.org, &host).await?;
}
}
set_mapping(tenant.pool(), &host, root).await?;
Ok(Redirect::to("/cms-admin/sites").into_response())
}
pub(crate) async fn set_root(
Extension(ctx): Extension<Arc<TenantContext>>,
tenant: Tenant,
SessionUser(session_user): SessionUser,
Form(form): Form<SiteForm>,
) -> Result<Response, AdminError> {
if let Some(r) = ensure_access(&tenant, session_user.as_ref()).await {
return Ok(r);
}
let host = rustango::tenancy::normalize_hostname(&form.hostname).map_err(host_err)?;
let registry = ctx.pools.registry_pool();
let known = rustango::tenancy::list_for_org(®istry, &tenant.org.slug)
.await
.map_err(host_err)?;
if !known.iter().any(|h| h.hostname == host) {
return Err(AdminError::Validation(format!(
"`{host}` is not one of this site's hostnames"
)));
}
let root = resolve_root(tenant.pool(), parse_page_id(&form.root_page_id)?).await?;
set_mapping(tenant.pool(), &host, root).await?;
Ok(Redirect::to("/cms-admin/sites").into_response())
}
pub(crate) async fn toggle(
Extension(ctx): Extension<Arc<TenantContext>>,
tenant: Tenant,
SessionUser(session_user): SessionUser,
Form(form): Form<HostForm>,
) -> Result<Response, AdminError> {
if let Some(r) = ensure_access(&tenant, session_user.as_ref()).await {
return Ok(r);
}
let host = rustango::tenancy::normalize_hostname(&form.hostname).map_err(host_err)?;
let registry = ctx.pools.registry_pool();
let known = rustango::tenancy::list_for_org(®istry, &tenant.org.slug)
.await
.map_err(host_err)?;
let enabled = known
.iter()
.find(|h| h.hostname == host)
.map(|h| h.enabled)
.ok_or(HostError::NotFound)
.map_err(host_err)?;
if !enabled && !self_service_host(&host) {
return Err(AdminError::Validation(format!(
"`{host}` is waiting for an operator to confirm this site owns it"
)));
}
rustango::tenancy::set_host_enabled(®istry, &tenant.org.slug, &host, !enabled)
.await
.map_err(host_err)?;
Ok(Redirect::to("/cms-admin/sites").into_response())
}
pub(crate) async fn remove(
Extension(ctx): Extension<Arc<TenantContext>>,
tenant: Tenant,
SessionUser(session_user): SessionUser,
Form(form): Form<HostForm>,
) -> Result<Response, AdminError> {
if let Some(r) = ensure_access(&tenant, session_user.as_ref()).await {
return Ok(r);
}
let host = rustango::tenancy::normalize_hostname(&form.hostname).map_err(host_err)?;
let registry = ctx.pools.registry_pool();
match rustango::tenancy::remove_host(®istry, &tenant.org.slug, &host).await {
Ok(()) => {}
Err(HostError::NotFound) => {}
Err(e) => return Err(host_err(e)),
}
set_mapping(tenant.pool(), &host, None).await?;
Ok(Redirect::to("/cms-admin/sites").into_response())
}
#[cfg(test)]
mod tests {
use super::parse_page_id;
#[test]
fn an_empty_chooser_means_no_mapping() {
assert_eq!(parse_page_id("").ok(), Some(0));
assert_eq!(parse_page_id(" ").ok(), Some(0));
}
#[test]
fn a_chosen_page_parses() {
assert_eq!(parse_page_id("42").ok(), Some(42));
assert_eq!(parse_page_id(" 42 ").ok(), Some(42));
}
#[test]
fn a_malformed_value_is_refused_rather_than_unmapping() {
for raw in ["abc", "1.5", "4 2", "--1", "٣"] {
assert!(
parse_page_id(raw).is_err(),
"{raw:?} should not parse as a page id"
);
}
}
}
#[cfg(test)]
mod host_approval_tests {
use super::{host_under_suffixes, is_apex};
#[test]
fn the_apex_is_never_a_tenant_host() {
assert!(is_apex("example.org", "example.org"));
assert!(is_apex("example.org", "Example.ORG."));
assert!(!is_apex("blog.example.org", "example.org"));
assert!(!is_apex("example.org.evil", "example.org"));
}
#[test]
fn only_the_operators_domains_are_self_service() {
let ops = "sites.example.com, .cms.example.net";
assert!(host_under_suffixes("sites.example.com", ops));
assert!(host_under_suffixes("acme.sites.example.com", ops));
assert!(host_under_suffixes("a.b.cms.example.net", ops));
assert!(!host_under_suffixes("shop.c-corp.com", ops), "someone else's domain");
assert!(!host_under_suffixes("evilsites.example.com", ops), "not a subdomain");
assert!(!host_under_suffixes("acme.sites.example.com", ""), "nothing is by default");
}
}