diff --git a/crates/common/src/auth/mod.rs b/crates/common/src/auth/mod.rs index 0ab1f016..87c1f3d9 100644 --- a/crates/common/src/auth/mod.rs +++ b/crates/common/src/auth/mod.rs @@ -73,6 +73,8 @@ pub const DOMAIN_FLAG_RELAY: u8 = 1; pub const DOMAIN_FLAG_SUB_ADDRESSING: u8 = 1 << 1; // inbuxa: SCIM-15, SCIM-58 pub const DOMAIN_FLAG_SCIM: u8 = 1 << 2; +// inbuxa: MT-24: a tenant added the domain and hasn't proven it owns its name +pub const DOMAIN_FLAG_UNVERIFIED: u8 = 1 << 3; #[derive(Debug, Clone, Default)] pub struct AccountCache { @@ -363,4 +365,21 @@ impl DomainCache { pub fn allows_scim(&self) -> bool { self.flags & DOMAIN_FLAG_SCIM != 0 } + + // inbuxa: MT-24: whether the domain's own name is proven. An unproven + // domain receives no mail, gives its accounts no addresses to send as + // and signs nothing; its unproven aliases are left out of `names`. + pub fn is_verified(&self) -> bool { + self.flags & DOMAIN_FLAG_UNVERIFIED == 0 + } + + // inbuxa: MT-24: whether mail for `name` is this domain's: a proven + // domain and one of its proven names + pub fn serves(&self, name: &str) -> bool { + self.is_verified() + && self + .names + .iter() + .any(|known| known.eq_ignore_ascii_case(name)) + } } diff --git a/crates/common/src/cache/invalidate.rs b/crates/common/src/cache/invalidate.rs index f62ea429..68c80075 100644 --- a/crates/common/src/cache/invalidate.rs +++ b/crates/common/src/cache/invalidate.rs @@ -125,11 +125,16 @@ impl CacheInvalidationBuilder { // so turning SCIM's authority on or off has to take effect // without a restart || (current.allow_scim_provisioning != new.allow_scim_provisioning) + // inbuxa: MT-24, a name proven or put back to unproven + || (current.unverified_names != new.unverified_names) { self.invalidate(CacheInvalidation::Domain(id)); } - if (current.name != new.name) || (current.aliases != new.aliases) { + if (current.name != new.name) + || (current.aliases != new.aliases) + || (current.unverified_names != new.unverified_names) + { self.invalidate(CacheInvalidation::DomainNegative); } diff --git a/crates/common/src/cache/principals.rs b/crates/common/src/cache/principals.rs index 60d854c4..14b403ab 100644 --- a/crates/common/src/cache/principals.rs +++ b/crates/common/src/cache/principals.rs @@ -66,7 +66,8 @@ impl Server { // Domain no longer exists, remove from name cache domain_names.remove(domain); } - Ok(result) + // inbuxa: MT-24: an unproven name is no local domain + Ok(result.filter(|cached| cached.serves(domain))) } else { let domain_names_negative = &self.inner.cache.domain_names_negative; if domain_names_negative.get(domain).is_none() { @@ -91,17 +92,18 @@ impl Server { .caused_by(trc::location!())?; } - if let Some(domain) = object { + if let Some(object) = object { // Cache positive result - let domain_id = domain.id().document_id(); - let domain = self.domain_by_id(domain_id).await?; - if let Some(domain) = &domain { - for name in domain.names.iter() { + let domain_id = object.id().document_id(); + let found = self.domain_by_id(domain_id).await?; + if let Some(found) = &found { + for name in found.names.iter() { domain_names.insert(name.clone(), domain_id); } } - Ok(domain) + // inbuxa: MT-24: an unproven name is no local domain + Ok(found.filter(|cached| cached.serves(domain))) } else { // Cache negative result domain_names_negative.insert( @@ -153,7 +155,8 @@ impl Server { Key = domain_id, Collection = "domainId", ); - let Some(domain) = self.registry().object::(domain_id.into()).await? else { + let Some(mut domain) = self.registry().object::(domain_id.into()).await? + else { return Ok(None); }; let mut flags = 0; @@ -165,6 +168,11 @@ impl Server { if domain.allow_scim_provisioning { flags |= crate::auth::DOMAIN_FLAG_SCIM; } + // inbuxa: MT-24: names a tenant hasn't proven it owns + if domain.unverified_names.contains(&domain.name) { + flags |= crate::auth::DOMAIN_FLAG_UNVERIFIED; + } + let unverified = std::mem::take(&mut domain.unverified_names); let sub_addressing_custom = match domain.sub_addressing { SubAddressing::Enabled => { @@ -195,6 +203,7 @@ impl Server { domain .aliases .into_iter() + .filter(|alias| !unverified.contains(alias)) .map(|alias| alias.into_boxed_str()), ) .collect(), @@ -700,7 +709,10 @@ impl Server { let mut addresses = Vec::with_capacity(account.id_member_of.len() + account.addresses.len()); for address in account.addresses.iter() { - if let Some(domain) = self.domain_by_id(address.domain_id).await? { + // inbuxa: MT-24: no addresses on a domain nobody has proven + if let Some(domain) = self.domain_by_id(address.domain_id).await? + && domain.is_verified() + { for name in domain.names.iter() { let mut addr = String::with_capacity(name.len() + address.local_part.len() + 1); addr.push_str(address.local_part.as_ref()); @@ -714,7 +726,9 @@ impl Server { for &group_id in &account.id_member_of { if let Some(group) = self.try_account(group_id).await? { for address in group.addresses.iter() { - if let Some(domain) = self.domain_by_id(address.domain_id).await? { + if let Some(domain) = self.domain_by_id(address.domain_id).await? + && domain.is_verified() + { for name in domain.names.iter() { let mut addr = String::with_capacity(name.len() + address.local_part.len() + 1); diff --git a/crates/features/src/tenancy/domain_move.rs b/crates/features/src/tenancy/domain_move.rs index a1d99ffa..c35a024f 100644 --- a/crates/features/src/tenancy/domain_move.rs +++ b/crates/features/src/tenancy/domain_move.rs @@ -167,7 +167,12 @@ pub async fn plan( // The destination's limits, the domain itself included if let Some(tenant_id) = to { - *adding.entry(TenantStorageQuota::MaxDomains).or_default() += 1; + // the domain itself, each of its names (MT-24) + let names = match registry.get(domain).await? { + Some(object) => quota::domain_names(&object.inner), + None => 1, + }; + *adding.entry(TenantStorageQuota::MaxDomains).or_default() += names; let mut quotas = adding.into_iter().collect::>(); quotas.sort_unstable_by_key(|(quota, _)| *quota as u16); for (quota, count) in quotas { diff --git a/crates/features/src/tenancy/quota.rs b/crates/features/src/tenancy/quota.rs index 8c982143..18ddd4b7 100644 --- a/crates/features/src/tenancy/quota.rs +++ b/crates/features/src/tenancy/quota.rs @@ -93,11 +93,35 @@ pub async fn count( if let Some(kind) = kind { query = query.equal(Property::Type, kind); } - registry + let ids = registry .query::>(query) .await - .map(|ids| ids.len() as u64) - .caused_by(trc::location!()) + .caused_by(trc::location!())?; + + // MT-24: every name a tenant's domains answer to counts, aliases too + if quota == TenantStorageQuota::MaxDomains { + let mut total = 0u64; + for id in ids { + if let Some(object) = registry + .get(ObjectId::new(ObjectType::Domain, id)) + .await + .caused_by(trc::location!())? + { + total += domain_names(&object.inner); + } + } + return Ok(total); + } + Ok(ids.len() as u64) +} + +/// How many names a domain counts as against maxDomains (MT-24): its own +/// and each alias. 1 for anything else. +pub fn domain_names(object: &ObjectInner) -> u64 { + match object { + ObjectInner::Domain(domain) => 1 + domain.aliases.len() as u64, + _ => 1, + } } /// An account's own disk quota, `None` when it has none (0 is none too). diff --git a/crates/features/src/tenancy/writes.rs b/crates/features/src/tenancy/writes.rs index a91fa616..72ba697f 100644 --- a/crates/features/src/tenancy/writes.rs +++ b/crates/features/src/tenancy/writes.rs @@ -129,8 +129,15 @@ pub async fn check( && !matches!(new.inner, ObjectInner::Domain(_) if old.is_some()) { let limit = limits(registry, tenant_id).await?; - if let Err(reached) = - quota::check(registry, tenant_id.document_id(), quota, limit(quota), 1).await? + let adding = quota::domain_names(&new.inner); + if let Err(reached) = quota::check( + registry, + tenant_id.document_id(), + quota, + limit(quota), + adding, + ) + .await? { return Ok(Err(over_quota(reached, tenant_id))); } @@ -153,6 +160,29 @@ pub async fn check( } } + // MT-24: a domain given more aliases counts each one against maxDomains + if let (Some(old), Some(tenant_id), ObjectInner::Domain(_)) = (old, tenant, &new.inner) + && old.inner.member_tenant_id() == tenant + { + let before = quota::domain_names(&old.inner); + let now = quota::domain_names(&new.inner); + if now > before { + let quota = TenantStorageQuota::MaxDomains; + let limit = limits(registry, tenant_id).await?; + if let Err(reached) = quota::check( + registry, + tenant_id.document_id(), + quota, + limit(quota), + now - before, + ) + .await? + { + return Ok(Err(over_quota(reached, tenant_id))); + } + } + } + Ok(Ok(after)) } @@ -199,7 +229,10 @@ pub fn locked_tenant(old: Option<&Object>, new: &Object) -> Option { let tenant = new.inner.member_tenant_id()?; let counted = quota::limit_for(&new.inner).is_some() && joins_tenant(old, new); let dkim = added_dkim_keys(old, new).is_some_and(|keys| keys > 0); - if counted || dkim { + // MT-24: a domain given more aliases takes more of maxDomains + let names = matches!(new.inner, ObjectInner::Domain(_)) + && old.is_some_and(|old| quota::domain_names(&new.inner) > quota::domain_names(&old.inner)); + if counted || dkim || names { Some(tenant) } else { disk_quota_tenant(old, new) @@ -485,6 +518,15 @@ mod disk_quota_tests { assert_eq!(locked_tenant(Some(&two), &two), None); // Disk quota growth still locks assert_eq!(locked_tenant(Some(&staying), &account(Some(7), 10)), tenant); + // A domain given another alias (MT-24), or losing one + let plain = domain(Some(7)); + let aliased = Object::from(Domain { + member_tenant_id: Some(Id::from(7u64)), + aliases: Map::new(vec!["alias.example.org".to_string()]), + ..Default::default() + }); + assert_eq!(locked_tenant(Some(&plain), &aliased), tenant); + assert_eq!(locked_tenant(Some(&aliased), &plain), None); } #[test] diff --git a/crates/jmap/src/inbuxa/domain_verification.rs b/crates/jmap/src/inbuxa/domain_verification.rs new file mode 100644 index 00000000..00ebea58 --- /dev/null +++ b/crates/jmap/src/inbuxa/domain_verification.rs @@ -0,0 +1,171 @@ +/* + * SPDX-FileCopyrightText: 2026 Coffey Labs LLC + * + * SPDX-License-Identifier: AGPL-3.0-only + */ + +//! MT-24: a tenant proves it owns the domain names it adds. +//! +//! A domain name or alias a tenant administrator adds is saved as unverified. +//! An unverified name receives no mail, gives no addresses to send as and +//! signs nothing (see `DomainCache::serves`), so a tenant can't take mail +//! meant for a name it doesn't own. The tenant proves a name by publishing a +//! TXT record at `_inbuxa-verification.` with +//! `inbuxa-verification=`, the domain's `verificationToken`, then +//! taking the name off `unverifiedNames`: the save looks the record up and +//! is refused if it isn't there. Names a server administrator adds are +//! trusted, and a server administrator can clear or add entries freely. + +use common::{Server, auth::AccessToken}; +use jmap_proto::error::set::SetError; +use rand::{RngExt, distr::Alphanumeric}; +use registry::schema::{prelude::Property, structs::Domain}; + +/// The TXT record's owner name, without the trailing dot. +pub fn record_name(name: &str) -> String { + format!("_inbuxa-verification.{name}") +} + +/// What the TXT record must contain. +pub fn record_value(token: &str) -> String { + format!("inbuxa-verification={token}") +} + +fn new_token() -> String { + rand::rng() + .sample_iter(Alphanumeric) + .take(32) + .map(char::from) + .collect() +} + +fn names(domain: &Domain) -> impl Iterator { + std::iter::once(&domain.name).chain(domain.aliases.iter()) +} + +/// Applies MT-24 to a domain about to be saved: names the domain no longer +/// has are forgotten, names a tenant adds start unverified, and names a +/// tenant takes off the list must be proven in DNS now. +pub async fn check( + server: &Server, + access_token: &AccessToken, + domain: &mut Domain, + old: Option<&Domain>, +) -> trc::Result>> { + let current = names(domain).cloned().collect::>(); + domain + .unverified_names + .inner_mut() + .retain(|name| current.contains(name)); + + if access_token.tenant_id().is_some() { + let before = old.map(|old| names(old).collect::>()); + for name in ¤t { + if before.as_ref().is_none_or(|before| !before.contains(&name)) + && !domain.unverified_names.contains(name) + { + domain.unverified_names.push(name.clone()); + } + } + + if let Some(old) = old { + let to_prove = old + .unverified_names + .iter() + .filter(|name| current.contains(name) && !domain.unverified_names.contains(name)) + .collect::>(); + if !to_prove.is_empty() { + let Some(token) = old.verification_token.as_deref() else { + return Ok(Err(unproven(to_prove[0], None))); + }; + for name in to_prove { + if !proven(server, name, token).await { + return Ok(Err(unproven(name, Some(token)))); + } + } + } + } + } + + if !domain.unverified_names.is_empty() && domain.verification_token.is_none() { + domain.verification_token = Some(new_token()); + } + Ok(Ok(())) +} + +/// Records the system tests publish, as they have no DNS of their own. +#[cfg(feature = "test_mode")] +pub static TEST_RECORDS: std::sync::LazyLock< + std::sync::Mutex>, +> = std::sync::LazyLock::new(Default::default); + +/// Whether `name`'s verification record carries `token`. +async fn proven(server: &Server, name: &str, token: &str) -> bool { + let expected = record_value(token); + #[cfg(feature = "test_mode")] + if let Some(found) = TEST_RECORDS.lock().unwrap().get(&record_name(name)) { + return record_matches(found.as_bytes(), &expected); + } + match server + .core + .smtp + .resolvers + .dns + .txt_raw_lookup(format!("{}.", record_name(name))) + .await + { + Ok(found) => record_matches(&found, &expected), + Err(_) => false, + } +} + +/// The record's text holds the expected value as a whole word. +fn record_matches(found: &[u8], expected: &str) -> bool { + std::str::from_utf8(found).is_ok_and(|text| { + text.split(|c: char| c.is_whitespace() || c == '"') + .any(|part| part == expected) + }) +} + +fn unproven(name: &str, token: Option<&str>) -> SetError { + SetError::invalid_properties() + .with_property(Property::UnverifiedNames) + .with_description(match token { + Some(token) => format!( + "{name} isn't proven yet. Publish a TXT record at {} with the value {}, \ + then try again. DNS changes can take a few minutes to appear.", + record_name(name), + record_value(token), + ), + None => format!("{name} has no verification token to check against."), + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_record_must_hold_the_whole_value() { + let expected = record_value("abc123"); + assert!(record_matches(b"inbuxa-verification=abc123", &expected)); + assert!(record_matches( + b"v=spf1 -all inbuxa-verification=abc123", + &expected + )); + assert!(record_matches(b"\"inbuxa-verification=abc123\"", &expected)); + assert!(!record_matches(b"inbuxa-verification=abc1234", &expected)); + assert!(!record_matches(b"xinbuxa-verification=abc123", &expected)); + assert!(!record_matches(b"", &expected)); + } + + #[test] + fn names_and_values() { + assert_eq!( + record_name("example.org"), + "_inbuxa-verification.example.org" + ); + assert_eq!(record_value("t"), "inbuxa-verification=t"); + assert_eq!(new_token().len(), 32); + } +} diff --git a/crates/jmap/src/inbuxa/mod.rs b/crates/jmap/src/inbuxa/mod.rs index 6b58c2bb..a4d8fadf 100644 --- a/crates/jmap/src/inbuxa/mod.rs +++ b/crates/jmap/src/inbuxa/mod.rs @@ -18,6 +18,7 @@ pub mod deleted_account; pub mod deliverability; // inbuxa: the deliverability check pub mod directory_test; pub mod dlp_settings; +pub mod domain_verification; // inbuxa: MT-24 pub mod explanation; pub mod fastmail; pub mod front_ends; diff --git a/crates/jmap/src/registry/mapping/domain.rs b/crates/jmap/src/registry/mapping/domain.rs index 038d83b1..efe5ffea 100644 --- a/crates/jmap/src/registry/mapping/domain.rs +++ b/crates/jmap/src/registry/mapping/domain.rs @@ -67,6 +67,14 @@ pub(crate) async fn validate_domain( .with_description(err))); } + // inbuxa: MT-24: a tenant proves the names it adds + if let Err(err) = + crate::inbuxa::domain_verification::check(set.server, set.access_token, domain, old_domain) + .await? + { + return Ok(Err(err)); + } + // Validate that names and aliases do not collide with another domain let registry = set.server.registry(); if old_domain.is_none_or(|old| old.name != domain.name) diff --git a/crates/registry/src/inbuxa_tests.rs b/crates/registry/src/inbuxa_tests.rs index cc65f32b..ddc9473d 100644 --- a/crates/registry/src/inbuxa_tests.rs +++ b/crates/registry/src/inbuxa_tests.rs @@ -179,6 +179,43 @@ fn without_last_field(object: &T, version: u8) -> Vec { } /// `object` saved at `version`, before the fields pickled as `tail`. +/// The MT-24 fields a domain saved before version 4 lacks, as they pickle +/// when unset: no unverified names, no token. +fn verification_tail() -> Vec { + let mut tail = Vec::new(); + Map::::default().pickle(&mut tail); + None::.pickle(&mut tail); + tail +} + +// MT-24: domains saved before name verification read back with every name +// trusted; saved now, with what's still unverified and its token +#[test] +fn domains_saved_before_verification_trust_their_names() { + let domain = Domain { + name: "example.org".to_string(), + aliases: Map::new(vec!["example.net".to_string()]), + passkeys_allowed: false, + ..Default::default() + }; + assert_eq!( + read( + ObjectType::Domain, + &without_tail(&domain, &verification_tail(), 3) + ), + ObjectInner::Domain(domain.clone()) + ); + let domain = Domain { + unverified_names: Map::new(vec!["example.net".to_string()]), + verification_token: Some("abc".to_string()), + ..domain + }; + assert_eq!( + read(ObjectType::Domain, &domain.to_pickled_vec()), + ObjectInner::Domain(domain) + ); +} + fn without_tail(object: &T, unset: &[u8], version: u8) -> Vec { let mut bytes = object.to_pickled_vec(); assert!(bytes.ends_with(&unset)); @@ -211,7 +248,14 @@ fn logos_saved_before_dark_mode_read_back_without_a_dark_logo() { None::.pickle(&mut unset); true.pickle(&mut unset); assert_eq!( - read(ObjectType::Domain, &without_tail(&domain, &unset, 1)), + read( + ObjectType::Domain, + &without_tail( + &domain, + &[unset.as_slice(), &verification_tail()].concat(), + 1 + ) + ), ObjectInner::Domain(domain.clone()) ); assert_eq!( @@ -378,7 +422,14 @@ fn passkey_settings_saved_before_read_back_allowed() { let mut unset = Vec::new(); true.pickle(&mut unset); assert_eq!( - read(ObjectType::Domain, &without_tail(&domain, &unset, 2)), + read( + ObjectType::Domain, + &without_tail( + &domain, + &[unset.as_slice(), &verification_tail()].concat(), + 2 + ) + ), ObjectInner::Domain(domain.clone()) ); assert_eq!( diff --git a/crates/registry/src/schema/properties.rs b/crates/registry/src/schema/properties.rs index aacc8f9b..e1dc23f4 100644 --- a/crates/registry/src/schema/properties.rs +++ b/crates/registry/src/schema/properties.rs @@ -1176,6 +1176,7 @@ pub enum Property { Ttl = 310, UnboundListeners = 947, UnpackDirectory = 54, + UnverifiedNames = 948, UpdateRecords = 812, UploadQuota = 445, UploadTtl = 446, @@ -1196,6 +1197,7 @@ pub enum Property { ValidateDomain = 413, Value = 492, VariableName = 675, + VerificationToken = 949, VerifyAfterWrite = 874, Version = 80, ViewName = 884, diff --git a/crates/registry/src/schema/properties_impl.rs b/crates/registry/src/schema/properties_impl.rs index e0652db0..164119e3 100644 --- a/crates/registry/src/schema/properties_impl.rs +++ b/crates/registry/src/schema/properties_impl.rs @@ -1323,6 +1323,7 @@ impl EnumImpl for Property { b"ttl" => Property::Ttl, b"unpackDirectory" => Property::UnpackDirectory, b"unboundListeners" => Property::UnboundListeners, + b"unverifiedNames" => Property::UnverifiedNames, b"updateRecords" => Property::UpdateRecords, b"uploadQuota" => Property::UploadQuota, b"uploadTtl" => Property::UploadTtl, @@ -1343,6 +1344,7 @@ impl EnumImpl for Property { b"validateDomain" => Property::ValidateDomain, b"value" => Property::Value, b"variableName" => Property::VariableName, + b"verificationToken" => Property::VerificationToken, b"verifyAfterWrite" => Property::VerifyAfterWrite, b"version" => Property::Version, b"viewName" => Property::ViewName, @@ -2276,6 +2278,8 @@ impl EnumImpl for Property { Property::Ttl => "ttl", Property::UnpackDirectory => "unpackDirectory", Property::UnboundListeners => "unboundListeners", + Property::UnverifiedNames => "unverifiedNames", + Property::VerificationToken => "verificationToken", Property::UpdateRecords => "updateRecords", Property::UploadQuota => "uploadQuota", Property::UploadTtl => "uploadTtl", @@ -3060,6 +3064,8 @@ impl EnumImpl for Property { 945 => Some(Property::PasskeyRpId), 946 => Some(Property::MaxPasskeys), 947 => Some(Property::UnboundListeners), + 948 => Some(Property::UnverifiedNames), + 949 => Some(Property::VerificationToken), 615 => Some(Property::RequireClientRegistration), 608 => Some(Property::RequireScopes), 525 => Some(Property::RequireTls), @@ -3271,7 +3277,7 @@ impl EnumImpl for Property { } } - const COUNT: usize = 948; + const COUNT: usize = 950; } impl serde::Serialize for Property { diff --git a/crates/registry/src/schema/structs.rs b/crates/registry/src/schema/structs.rs index 92aad407..31e72e9f 100644 --- a/crates/registry/src/schema/structs.rs +++ b/crates/registry/src/schema/structs.rs @@ -2753,6 +2753,12 @@ pub struct Domain { // inbuxa: passkeys spec: an off switch for this level's accounts #[serde(rename = "passkeysAllowed")] pub passkeys_allowed: bool, + // inbuxa: MT-24: names a tenant added that nobody has proven it owns + // yet, and the token its TXT records must carry + #[serde(rename = "unverifiedNames")] + pub unverified_names: Map, + #[serde(rename = "verificationToken")] + pub verification_token: Option, #[serde(rename = "certificateManagement")] pub certificate_management: CertificateManagement, #[serde(rename = "dkimManagement")] diff --git a/crates/registry/src/schema/structs_impl.rs b/crates/registry/src/schema/structs_impl.rs index d665f19a..d41ea5cf 100644 --- a/crates/registry/src/schema/structs_impl.rs +++ b/crates/registry/src/schema/structs_impl.rs @@ -19883,8 +19883,9 @@ impl RegistryJsonPropertyPatch for DnsServerYandexCloud { impl ObjectImpl for Domain { const FLAGS: u64 = OBJ_FILTER_TENANT | OBJ_SEQ_ID; - // inbuxa: 2: logoDark (branding BT-27); 3: passkeysAllowed (passkeys) - const VERSION: u8 = 3; + // inbuxa: 2: logoDark (branding BT-27); 3: passkeysAllowed (passkeys); + // 4: unverifiedNames, verificationToken (MT-24) + const VERSION: u8 = 4; const OBJECT: ObjectType = ObjectType::Domain; fn validate(&self, errors: &mut Vec) -> bool { @@ -19946,6 +19947,11 @@ impl ObjectImpl for Domain { errors.push(ValidationError::required(Property::ReportAddressUri)); } } + for value in self.unverified_names.iter() { + if value.is_empty() { + errors.push(ValidationError::required(Property::UnverifiedNames)); + } + } errors.len() == neb } @@ -19991,6 +19997,8 @@ impl Pickle for Domain { self.allow_scim_provisioning.pickle(out); self.logo_dark.pickle(out); self.passkeys_allowed.pickle(out); + self.unverified_names.pickle(out); + self.verification_token.pickle(out); } fn unpickle(stream: &mut crate::pickle::PickledStream<'_>) -> Option { @@ -20021,6 +20029,11 @@ impl Pickle for Domain { if stream.version() >= 3 { this.passkeys_allowed = Pickle::unpickle(stream)?; } + // inbuxa: MT-24, stored from version 4; names saved before are trusted + if stream.version() >= 4 { + this.unverified_names = Pickle::unpickle(stream)?; + this.verification_token = Pickle::unpickle(stream)?; + } Some(this) } } @@ -20036,6 +20049,8 @@ impl Default for Domain { logo: Default::default(), logo_dark: Default::default(), passkeys_allowed: true, + unverified_names: Default::default(), + verification_token: None, certificate_management: Default::default(), dkim_management: Default::default(), dns_management: Default::default(), @@ -20052,7 +20067,7 @@ impl Default for Domain { impl IntoValue for Domain { fn into_value(self) -> JmapValue<'static> { - let mut map = jmap_tools::Map::with_capacity(18); + let mut map = jmap_tools::Map::with_capacity(20); map.insert_unchecked(Property::Name, self.name.into_value()); map.insert_unchecked(Property::Aliases, self.aliases.into_value()); map.insert_unchecked(Property::IsEnabled, self.is_enabled.into_value()); @@ -20086,6 +20101,14 @@ impl IntoValue for Domain { Property::AllowScimProvisioning, self.allow_scim_provisioning.into_value(), ); + map.insert_unchecked( + Property::UnverifiedNames, + self.unverified_names.into_value(), + ); + map.insert_unchecked( + Property::VerificationToken, + self.verification_token.into_value(), + ); JmapValue::Object(map) } } @@ -20130,6 +20153,11 @@ impl RegistryJsonPropertyPatch for Domain { Some(Property::AllowScimProvisioning) => { self.allow_scim_provisioning.patch(pointer, value) } + // inbuxa: MT-24: what a tenant may change here is checked on save + Some(Property::UnverifiedNames) => self + .unverified_names + .patch(pointer.with_validators(&[StringValidator::Domain]), value), + Some(Property::VerificationToken) => pointer.assert_server_set(), Some(Property::Type) => Ok(MaybeUnpatched::Unpatched { property: Property::Type, value, diff --git a/docs/spec/features/multi-tenancy.md b/docs/spec/features/multi-tenancy.md index b758e274..7282a38d 100644 --- a/docs/spec/features/multi-tenancy.md +++ b/docs/spec/features/multi-tenancy.md @@ -263,6 +263,25 @@ Each requirement has an ID, and tests name the IDs they check. `usedDiskQuota` from its members' actual usage. `resetTenantQuotas` recomputes every tenant. Both can run while the server is live. +- **MT-24.** A tenant proves it owns the domain names it adds. A domain + name or alias that a tenant administrator adds is saved in the domain's + `unverifiedNames`, and the domain gets a `verificationToken` (32 + characters, set by the server, read-only). An unverified name is not a + local domain: mail for it isn't taken in, it gives no addresses to send + as, and nothing is signed for it. A domain whose own name is unverified is + all of that for every name it has. The tenant proves a name by publishing + a TXT record at `_inbuxa-verification.` with the value + `inbuxa-verification=`, then taking the name off `unverifiedNames`. + The save looks the record up and is refused with `invalidProperties` + naming the record if it isn't there. Names a server administrator adds are + trusted, and a server administrator may clear or add entries freely. + Names saved before MT-24 are trusted. Every name counts against + `maxDomains`: a domain is 1 plus its aliases, on create, on an update that + adds aliases, and on a move into a tenant. + **Why:** a domain name on a server belongs to whoever controls it in DNS, + and a tenant's names should be its own, the same rule hosted mail + services use (inbuxa-admin#257 follow-up). + ### Branding - **MT-22.** A signed-in principal can read the logo that applies to it: its @@ -343,7 +362,7 @@ Built 2026-09-18 from this spec, clean-room (hand-off brief `inbuxa: MT-n`. Acceptance tests 1 to 14 pass as `tests/src/system/tenant.rs`, called from `system_tests` with no gate. -- **MT-1 to MT-18, MT-20 to MT-23:** built. +- **MT-1 to MT-18, MT-20 to MT-24:** built. - **MT-19, MT-19a:** built, except the submission-time warning, **deferred** (see MT-19a) until the contract defines a warnings shape. - **ihasmail changes** (the section above) belong to inbuxa-webmail and diff --git a/resources/schema/schema.json.gz b/resources/schema/schema.json.gz index b0f8aaae..a5ba5160 100644 Binary files a/resources/schema/schema.json.gz and b/resources/schema/schema.json.gz differ diff --git a/resources/schema/schema.json.sha256 b/resources/schema/schema.json.sha256 index 4d83e19c..6a2d669b 100644 --- a/resources/schema/schema.json.sha256 +++ b/resources/schema/schema.json.sha256 @@ -1 +1 @@ -s1j6j79sdVPo9onPNL8iJOJRz_V5NLJAaU6MHps8z54 \ No newline at end of file +_5mtPlTNxsTQplMjHsX7vU4ka-OLfG4doD6ivgjbk3Y \ No newline at end of file diff --git a/tests/src/system/tenant.rs b/tests/src/system/tenant.rs index 10af24a1..0412eea2 100644 --- a/tests/src/system/tenant.rs +++ b/tests/src/system/tenant.rs @@ -1114,6 +1114,156 @@ pub async fn test(test: &mut TestServer) { test.wait_for_tasks().await; assert_eq!(admin.tenant_usage(d_id).await, two, "test 14"); + // MT-24: a tenant proves the domain names it adds, and every name counts + // against maxDomains + admin + .set_tenant_quota(d_id, TenantStorageQuota::MaxDomains, 3) + .await; + let claimed = "claimed.example.net"; + d_admin + .registry_update_object( + ObjectType::Domain, + d_domain, + json!({ Property::Aliases: { claimed: true } }), + ) + .await; + let stored = admin.registry_get::(d_domain).await; + assert_eq!(stored.unverified_names.as_slice(), [claimed.to_string()]); + let token = stored.verification_token.clone().expect("MT-24: a token"); + assert!( + test.server.domain(claimed).await.unwrap().is_none(), + "MT-24: an unproven alias takes no mail" + ); + assert!(test.server.domain("d.example.org").await.unwrap().is_some()); + // Taking it off the list without the record is refused, naming it + d_admin + .registry_update_object_expect_err( + ObjectType::Domain, + d_domain, + json!({ Property::UnverifiedNames: {} }), + ) + .await + .assert_type(SetErrorType::InvalidProperties) + .assert_description_contains("_inbuxa-verification.claimed.example.net"); + // A record with another token doesn't do either + ::jmap::inbuxa::domain_verification::TEST_RECORDS + .lock() + .unwrap() + .insert( + format!("_inbuxa-verification.{claimed}"), + "inbuxa-verification=someone-else".to_string(), + ); + d_admin + .registry_update_object_expect_err( + ObjectType::Domain, + d_domain, + json!({ Property::UnverifiedNames: {} }), + ) + .await + .assert_type(SetErrorType::InvalidProperties); + // With the record, it's proven and takes mail + ::jmap::inbuxa::domain_verification::TEST_RECORDS + .lock() + .unwrap() + .insert( + format!("_inbuxa-verification.{claimed}"), + format!("inbuxa-verification={token}"), + ); + d_admin + .registry_update_object( + ObjectType::Domain, + d_domain, + json!({ Property::UnverifiedNames: {} }), + ) + .await; + assert!( + test.server.domain(claimed).await.unwrap().is_some(), + "MT-24: a proven alias takes mail" + ); + // The token can't be set by anyone + d_admin + .registry_update_object_expect_err( + ObjectType::Domain, + d_domain, + json!({ Property::VerificationToken: "mine" }), + ) + .await; + // Two names in use of three: two more aliases don't fit + d_admin + .registry_update_object_expect_err( + ObjectType::Domain, + d_domain, + json!({ Property::Aliases: { claimed: true, "a1.example.net": true, "a2.example.net": true } }), + ) + .await + .assert_type(SetErrorType::OverQuota) + .assert_description_contains("maxDomains"); + // A domain the tenant creates is unproven as a whole + let created = d_admin + .registry_create_object(Domain { + name: "new.example.net".to_string(), + is_enabled: true, + certificate_management: CertificateManagement::Manual, + dns_management: DnsManagement::Manual, + dkim_management: DkimManagement::Manual, + ..Default::default() + }) + .await; + assert!( + test.server + .domain("new.example.net") + .await + .unwrap() + .is_none(), + "MT-24: an unproven domain takes no mail" + ); + assert_eq!( + admin + .registry_get::(created) + .await + .unverified_names + .as_slice(), + ["new.example.net".to_string()] + ); + // An alias the server administrator adds is trusted, and so is clearing + // the list for the tenant + admin + .registry_update_object( + ObjectType::Domain, + created, + json!({ Property::UnverifiedNames: {} }), + ) + .await; + assert!( + test.server + .domain("new.example.net") + .await + .unwrap() + .is_some() + ); + admin + .registry_destroy(ObjectType::Domain, [created]) + .await + .assert_destroyed(&[created]); + admin + .registry_update_object( + ObjectType::Domain, + d_domain, + json!({ Property::Aliases: { claimed: true, "by-admin.example.net": true } }), + ) + .await; + assert!( + test.server + .domain("by-admin.example.net") + .await + .unwrap() + .is_some() + ); + ::jmap::inbuxa::domain_verification::TEST_RECORDS + .lock() + .unwrap() + .clear(); + // Clean up, leaving the server as the other tests expect it for account in [ t_admin, t_user, t_group, u_admin, u_user, u_group, p_admin, p_user, s_user, d_admin, diff --git a/tests/src/utils/registry.rs b/tests/src/utils/registry.rs index 21808d3b..392689bd 100644 --- a/tests/src/utils/registry.rs +++ b/tests/src/utils/registry.rs @@ -2,6 +2,8 @@ * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC * * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL + * + * Modified by Coffey Labs in 2026 for INBUXA. */ use crate::utils::{ @@ -458,6 +460,7 @@ fn remove_server_set_props(typ: ObjectType, value: &mut serde_json::Value) { "retireAt", "accountKey", "accountUri", + "verificationToken", ] .contains(&k.as_str()) || (is_app_pass && k == "secret")