diff --git a/.github/scripts/check-production-line-limit.sh b/.github/scripts/check-production-line-limit.sh index 3e284d3b28..b98f8824f3 100755 --- a/.github/scripts/check-production-line-limit.sh +++ b/.github/scripts/check-production-line-limit.sh @@ -46,7 +46,6 @@ declare -A GRANDFATHERED=( # serve.rs and directory.rs moved again in that restructure - to # pkgs/id/crates/id-cli/ and pkgs/id/crates/id-directory/ - and # their keys were re-pointed in the #9526 fix; same rule. - ["pkgs/id/crates/id-directory/src/directory.rs"]="#8591" ) # Count production lines of one file: every line that is not part of diff --git a/pkgs/id/crates/id-directory/src/directory.rs b/pkgs/id/crates/id-directory/src/directory.rs index 5b2aadcfe0..ea598a5d1d 100644 --- a/pkgs/id/crates/id-directory/src/directory.rs +++ b/pkgs/id/crates/id-directory/src/directory.rs @@ -11,7 +11,7 @@ use std::io::Write as _; use std::path::{Path, PathBuf}; use anyhow::{Context, Result, bail, ensure}; -use ed25519_dalek::{Signature, Signer as _, SigningKey, VerifyingKey}; +use ed25519_dalek::{Signer as _, SigningKey}; use rand::RngExt as _; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; @@ -23,6 +23,15 @@ use id_sync::artifact::{ }; use {id_caps::world_scopes::WorldScopes, id_core::hex::hex_encode}; +mod replica; +mod validate; + +use validate::{ + artifact_path, clean_description, clean_description_mode, clean_name, clean_name_mode, + ensure_account_id, may_act_for, pair, permissions, signing_key, +}; +pub use validate::{hex_to_array, normalize_email, normalize_key}; + const KEY_DOMAIN: &[u8] = b"id-account-v1"; const MAX_NAME_CHARS: usize = 64; const MAX_DESCRIPTION_CHARS: usize = 512; @@ -1082,227 +1091,6 @@ impl Directory { self.tiers[&Tier::Anonymous] } - /// Directory facts a read-only replica needs for spectator - /// authorization (F12.13 phase 4): everything - /// [`WorldCore::effective_scopes`] consults for the given - /// capability subjects — account ceilings (tiers and group grants) and - /// the friendship graph — as entries the replica applies to an empty - /// directory. The caller passes every account appearing in the - /// replicated journal's capability chains; unknown subjects are skipped - /// (they read back under the anonymous tier, fail-closed). - /// - /// Account secrets never cross: signed-up accounts carry only their - /// stored digest, keyed accounts only their public ID. Friendships are - /// re-expressed without envelope IDs — the request/accept pair - /// validates as a unit, and only current friendships are exported, so - /// there is nothing to void. Groups export only when the groups a - /// subject's level flows through form a contiguous `1..=k` prefix (the - /// journal replays groups in creation order); group founders are the - /// lowest-ID account already holding admin, so no authority widens. - /// - /// # Errors - /// - /// Fails when a group the subjects depend on cannot be represented as - /// such a prefix, so a gappy topology can never silently narrow a - /// subject's ceiling. Worlds without group grants (like the phase-4 - /// friendship-delegation acceptance case) never hit this. - pub fn replica_facts_for(&self, subjects: &BTreeSet) -> Result> { - // Groups that grant a subject some level, closed under nesting: a - // subject's level can flow through a nested group, and `MemberSet` - // refuses an unknown group. - let mut groups: BTreeSet = BTreeSet::new(); - let mut stack: Vec = self - .groups - .keys() - .filter(|id| subjects.iter().any(|s| self.level_in(s, **id).is_some())) - .copied() - .collect(); - while let Some(id) = stack.pop() { - if groups.insert(id) { - for ((_, member), _) in self - .members - .range((id, Member::Group { id: 0 })..=(id, Member::Group { id: u64::MAX })) - { - if let Member::Group { id: nested } = member { - stack.push(*nested); - } - } - } - } - // Journal replay creates groups in order, so the export must be the - // contiguous prefix starting at group 1. - let ordered: Vec = groups.iter().copied().collect(); - let contiguous = ordered - .iter() - .enumerate() - .all(|(index, id)| u64::try_from(index + 1).is_ok_and(|expected| expected == *id)); - ensure!( - contiguous, - "replica export cannot represent non-contiguous group IDs {ordered:?}" - ); - // Accounts to reproduce: the subjects that exist, plus founders of - // exported groups (`GroupCreated` refuses an unknown founder). - let mut accounts: BTreeSet = subjects - .iter() - .filter(|id| self.accounts.contains_key(*id)) - .cloned() - .collect(); - let mut founders: BTreeMap = BTreeMap::new(); - for id in &ordered { - // Admin can be inherited through nested-group membership; use - // the same effective-level calculation as `ensure_admins`. - let founder = self - .accounts - .keys() - .filter(|account| self.level_in(account.as_str(), *id) == Some(Level::Admin)) - .min() - .cloned(); - let Some(founder) = founder else { - anyhow::bail!("replica export cannot represent group {id} with no account admin"); - }; - accounts.insert(founder.clone()); - founders.insert(*id, founder); - } - let mut entries = Vec::new(); - let mut sorted_accounts: Vec<&String> = accounts.iter().collect(); - sorted_accounts.sort(); - for id in sorted_accounts { - let account = &self.accounts[id.as_str()]; - if let Some(digest) = self.digests.get(id.as_str()) { - entries.push(DirectoryEntry::AccountSignedUp { - id: (*id).clone(), - name: account.name.clone(), - digest: hex_encode(digest), - }); - } else { - entries.push(DirectoryEntry::AccountKeyed { - id: (*id).clone(), - name: account.name.clone(), - }); - } - // Ceilings read the verified tier (directly verified or via a - // confirmed email), so export the verified flag on that basis: - // the replica reaches the same ceiling either way. - if self.is_verified(id) { - entries.push(DirectoryEntry::AccountVerified { id: (*id).clone() }); - } - } - // Non-default tiers ride along: ceilings intersect them. - let defaults = BTreeMap::from([ - (Tier::Anonymous, WorldScopes::GUEST), - (Tier::Registered, WorldScopes::GUEST), - ( - Tier::Verified, - WorldScopes::GUEST.union(WorldScopes::DELEGATE), - ), - ]); - for (tier, scopes) in &self.tiers { - if defaults.get(tier) != Some(scopes) { - entries.push(DirectoryEntry::TierSet { - tier: *tier, - scopes: scopes.bits(), - }); - } - } - for id in &ordered { - let group = &self.groups[id]; - entries.push(DirectoryEntry::GroupCreated { - id: *id, - name: group.name.clone(), - description: group.description.clone(), - scopes: group.scopes.bits(), - founder: founders[id].clone(), - }); - } - // All groups exist before any nested `MemberSet` references them. - // Directory replay refuses a membership naming a not-yet-created - // group, even when both IDs belong to one contiguous replica prefix. - // Founder downgrades are collected here and emitted only after - // every group's memberships exist (see the deferral below). - let mut founder_downgrades: Vec = Vec::new(); - for id in &ordered { - // Subject memberships reproduce subject ceilings; nested links - // reproduce the paths levels flow through. Other accounts stay - // out: the founder above already keeps an admin in place. - let mut memberships: Vec<(Member, Level)> = self - .members - .range( - (*id, Member::Account { id: String::new() }) - ..=(*id, Member::Group { id: u64::MAX }), - ) - .map(|((_, member), level)| (member.clone(), *level)) - .filter(|(member, _)| match member { - Member::Account { id } => subjects.contains(id), - Member::Group { .. } => true, - }) - .collect(); - memberships.sort_by(|a, b| a.0.cmp(&b.0)); - for (member, level) in memberships { - // The founder's admin comes from `GroupCreated` itself. - if member - == (Member::Account { - id: founders[id].clone(), - }) - && level == Level::Admin - { - continue; - } - let is_founder = member - == (Member::Account { - id: founders[id].clone(), - }); - let entry = DirectoryEntry::MemberSet { - group: *id, - member, - level: Some(level), - }; - // A founder whose direct level is below `Admin` was chosen - // because they hold the group's admin through an inherited - // path. Sorted order emits account memberships before - // nested-group ones, so the downgrade could land before - // the nested membership carrying that path exists, leaving - // the group momentarily admin-less — `checked_mode` - // rejects it through `ensure_admins` and replica startup - // fails. Defer founder downgrades until all memberships - // are in place. - if is_founder { - founder_downgrades.push(entry); - } else { - entries.push(entry); - } - } - } - entries.extend(founder_downgrades); - // Current friendships among the exported accounts. Preserve the - // request ID when one exists: a signed FriendRemove artifact uses - // it to distinguish this friendship from an older relationship - // between the same pair after the directory is projected. - let sorted: Vec<&String> = accounts.iter().collect(); - let mut pairs: Vec<(&String, &String)> = Vec::new(); - for (index, a) in sorted.iter().enumerate() { - for b in &sorted[index + 1..] { - if self.are_friends(a, b) { - pairs.push((a, b)); - } - } - } - for (a, b) in pairs { - let request = self.friend_requests.get(&pair(a, b)).cloned(); - entries.push(DirectoryEntry::FriendRequested { - from: (*a).clone(), - to: (*b).clone(), - id: request.clone(), - }); - entries.push(DirectoryEntry::FriendAccepted { - from: (*a).clone(), - to: (*b).clone(), - request, - id: None, - }); - } - Ok(entries) - } - /// The group with this ID, if it exists. #[must_use] pub fn group(&self, id: u64) -> Option<&Group> { @@ -2391,149 +2179,6 @@ impl Directory { } } -fn artifact_path(journal: &Path) -> PathBuf { - journal.with_file_name(artifact::FILE) -} - -fn signing_key(secret: &[u8; 32]) -> SigningKey { - let mut hasher = Sha256::new(); - hasher.update(KEY_DOMAIN); - hasher.update(secret); - SigningKey::from_bytes(&hasher.finalize().into()) -} - -fn may_act_for(actor: Actor<'_>, account: &str) -> bool { - match actor { - Actor::Server => true, - Actor::Account(me) => me == account, - } -} - -/// A public key as lower-case hex, if it is an Ed25519 public key. -/// -/// # Errors -/// -/// Fails if the text is not 64 hex characters or not a valid key. -pub fn normalize_key(key: &str) -> Result { - let key = key.trim().to_ascii_lowercase(); - let bytes = hex_to_array::<32>(&key).context("a public key is 64 hex characters")?; - VerifyingKey::from_bytes(&bytes).context("not an Ed25519 public key")?; - Ok(key) -} - -/// An email address in lower case, checked for shape but not deliverability. -/// -/// # Errors -/// -/// Fails if the text does not look like `local@domain.tld`. -pub fn normalize_email(address: &str) -> Result { - let address = address.trim().to_ascii_lowercase(); - ensure!(address.len() <= 254, "email address is too long"); - let (local, domain) = address - .split_once('@') - .context("an email address has one @")?; - let local_ok = !local.is_empty() - && local.len() <= 64 - && !local.starts_with('.') - && !local.ends_with('.') - && !local.contains("..") - && local - .chars() - .all(|c| c.is_ascii_alphanumeric() || "!#$%&'*+-/=?^_`{|}~.".contains(c)); - let domain_ok = domain.contains('.') - && domain.split('.').all(|label| { - !label.is_empty() - && label.len() <= 63 - && !label.starts_with('-') - && !label.ends_with('-') - && label.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') - }); - ensure!(local_ok && domain_ok, "not an email address"); - Ok(address) -} - -fn pair(a: &str, b: &str) -> (String, String) { - if a <= b { - (a.to_owned(), b.to_owned()) - } else { - (b.to_owned(), a.to_owned()) - } -} - -fn ensure_account_id(id: &str) -> Result<()> { - ensure!( - hex_to_array::<32>(id).is_some(), - "account ID must be 64 hex characters" - ); - Ok(()) -} - -fn permissions(bits: u8) -> Result { - WorldScopes::from_bits(bits).context("unknown permission bits") -} - -fn clean_name(name: &str) -> Result { - clean_name_mode(name, true) -} - -fn clean_name_mode(name: &str, refuse_format: bool) -> Result { - let name = name.trim(); - ensure!(!name.is_empty(), "name must not be empty"); - ensure!( - name.chars().count() <= MAX_NAME_CHARS, - "name must be at most {MAX_NAME_CHARS} characters" - ); - ensure!( - !name.chars().any(char::is_control), - "name must not contain control characters" - ); - if refuse_format { - ensure!( - !name.chars().any(id_core::petname::is_format_char), - "name must not contain format characters" - ); - } - Ok(name.to_owned()) -} - -fn clean_description(description: &str) -> Result { - clean_description_mode(description, true) -} - -fn clean_description_mode(description: &str, refuse_format: bool) -> Result { - let description = description.trim(); - ensure!( - description.chars().count() <= MAX_DESCRIPTION_CHARS, - "description must be at most {MAX_DESCRIPTION_CHARS} characters" - ); - ensure!( - !description.chars().any(|c| c.is_control() && c != '\n'), - "description must not contain control characters" - ); - if refuse_format { - ensure!( - !description.chars().any(id_core::petname::is_format_char), - "description must not contain format characters" - ); - } - Ok(description.to_owned()) -} - -pub fn hex_to_array(text: &str) -> Option<[u8; N]> { - // Every byte must be an ASCII hex digit (#2517): u8::from_str_radix - // also accepts a leading '+', so without this gate a byte 0x00-0x0f - // has two accepted spellings ('0x' and '+x') and key strings stop - // being canonical. - if text.len() != N * 2 || !text.bytes().all(|b| b.is_ascii_hexdigit()) { - return None; - } - let mut out = [0_u8; N]; - for (index, byte) in out.iter_mut().enumerate() { - *byte = u8::from_str_radix(&text[index * 2..index * 2 + 2], 16).ok()?; - } - Some(out) -} - #[cfg(test)] #[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] mod tests { diff --git a/pkgs/id/crates/id-directory/src/directory/replica.rs b/pkgs/id/crates/id-directory/src/directory/replica.rs new file mode 100644 index 0000000000..8f93026839 --- /dev/null +++ b/pkgs/id/crates/id-directory/src/directory/replica.rs @@ -0,0 +1,229 @@ +//! Replica fact export, split out of directory.rs for the F11.10 +//! production-line guard (#8591). The method stays an inherent +//! Directory method at its historical path; only its home file moved. + +use super::validate::pair; +use super::*; + +impl Directory { + /// Directory facts a read-only replica needs for spectator + /// authorization (F12.13 phase 4): everything + /// [`WorldCore::effective_scopes`] consults for the given + /// capability subjects — account ceilings (tiers and group grants) and + /// the friendship graph — as entries the replica applies to an empty + /// directory. The caller passes every account appearing in the + /// replicated journal's capability chains; unknown subjects are skipped + /// (they read back under the anonymous tier, fail-closed). + /// + /// Account secrets never cross: signed-up accounts carry only their + /// stored digest, keyed accounts only their public ID. Friendships are + /// re-expressed without envelope IDs — the request/accept pair + /// validates as a unit, and only current friendships are exported, so + /// there is nothing to void. Groups export only when the groups a + /// subject's level flows through form a contiguous `1..=k` prefix (the + /// journal replays groups in creation order); group founders are the + /// lowest-ID account already holding admin, so no authority widens. + /// + /// # Errors + /// + /// Fails when a group the subjects depend on cannot be represented as + /// such a prefix, so a gappy topology can never silently narrow a + /// subject's ceiling. Worlds without group grants (like the phase-4 + /// friendship-delegation acceptance case) never hit this. + pub fn replica_facts_for(&self, subjects: &BTreeSet) -> Result> { + // Groups that grant a subject some level, closed under nesting: a + // subject's level can flow through a nested group, and `MemberSet` + // refuses an unknown group. + let mut groups: BTreeSet = BTreeSet::new(); + let mut stack: Vec = self + .groups + .keys() + .filter(|id| subjects.iter().any(|s| self.level_in(s, **id).is_some())) + .copied() + .collect(); + while let Some(id) = stack.pop() { + if groups.insert(id) { + for ((_, member), _) in self + .members + .range((id, Member::Group { id: 0 })..=(id, Member::Group { id: u64::MAX })) + { + if let Member::Group { id: nested } = member { + stack.push(*nested); + } + } + } + } + // Journal replay creates groups in order, so the export must be the + // contiguous prefix starting at group 1. + let ordered: Vec = groups.iter().copied().collect(); + let contiguous = ordered + .iter() + .enumerate() + .all(|(index, id)| u64::try_from(index + 1).is_ok_and(|expected| expected == *id)); + ensure!( + contiguous, + "replica export cannot represent non-contiguous group IDs {ordered:?}" + ); + // Accounts to reproduce: the subjects that exist, plus founders of + // exported groups (`GroupCreated` refuses an unknown founder). + let mut accounts: BTreeSet = subjects + .iter() + .filter(|id| self.accounts.contains_key(*id)) + .cloned() + .collect(); + let mut founders: BTreeMap = BTreeMap::new(); + for id in &ordered { + // Admin can be inherited through nested-group membership; use + // the same effective-level calculation as `ensure_admins`. + let founder = self + .accounts + .keys() + .filter(|account| self.level_in(account.as_str(), *id) == Some(Level::Admin)) + .min() + .cloned(); + let Some(founder) = founder else { + anyhow::bail!("replica export cannot represent group {id} with no account admin"); + }; + accounts.insert(founder.clone()); + founders.insert(*id, founder); + } + let mut entries = Vec::new(); + let mut sorted_accounts: Vec<&String> = accounts.iter().collect(); + sorted_accounts.sort(); + for id in sorted_accounts { + let account = &self.accounts[id.as_str()]; + if let Some(digest) = self.digests.get(id.as_str()) { + entries.push(DirectoryEntry::AccountSignedUp { + id: (*id).clone(), + name: account.name.clone(), + digest: hex_encode(digest), + }); + } else { + entries.push(DirectoryEntry::AccountKeyed { + id: (*id).clone(), + name: account.name.clone(), + }); + } + // Ceilings read the verified tier (directly verified or via a + // confirmed email), so export the verified flag on that basis: + // the replica reaches the same ceiling either way. + if self.is_verified(id) { + entries.push(DirectoryEntry::AccountVerified { id: (*id).clone() }); + } + } + // Non-default tiers ride along: ceilings intersect them. + let defaults = BTreeMap::from([ + (Tier::Anonymous, WorldScopes::GUEST), + (Tier::Registered, WorldScopes::GUEST), + ( + Tier::Verified, + WorldScopes::GUEST.union(WorldScopes::DELEGATE), + ), + ]); + for (tier, scopes) in &self.tiers { + if defaults.get(tier) != Some(scopes) { + entries.push(DirectoryEntry::TierSet { + tier: *tier, + scopes: scopes.bits(), + }); + } + } + for id in &ordered { + let group = &self.groups[id]; + entries.push(DirectoryEntry::GroupCreated { + id: *id, + name: group.name.clone(), + description: group.description.clone(), + scopes: group.scopes.bits(), + founder: founders[id].clone(), + }); + } + // All groups exist before any nested `MemberSet` references them. + // Directory replay refuses a membership naming a not-yet-created + // group, even when both IDs belong to one contiguous replica prefix. + // Founder downgrades are collected here and emitted only after + // every group's memberships exist (see the deferral below). + let mut founder_downgrades: Vec = Vec::new(); + for id in &ordered { + // Subject memberships reproduce subject ceilings; nested links + // reproduce the paths levels flow through. Other accounts stay + // out: the founder above already keeps an admin in place. + let mut memberships: Vec<(Member, Level)> = self + .members + .range( + (*id, Member::Account { id: String::new() }) + ..=(*id, Member::Group { id: u64::MAX }), + ) + .map(|((_, member), level)| (member.clone(), *level)) + .filter(|(member, _)| match member { + Member::Account { id } => subjects.contains(id), + Member::Group { .. } => true, + }) + .collect(); + memberships.sort_by(|a, b| a.0.cmp(&b.0)); + for (member, level) in memberships { + // The founder's admin comes from `GroupCreated` itself. + if member + == (Member::Account { + id: founders[id].clone(), + }) + && level == Level::Admin + { + continue; + } + let is_founder = member + == (Member::Account { + id: founders[id].clone(), + }); + let entry = DirectoryEntry::MemberSet { + group: *id, + member, + level: Some(level), + }; + // A founder whose direct level is below `Admin` was chosen + // because they hold the group's admin through an inherited + // path. Sorted order emits account memberships before + // nested-group ones, so the downgrade could land before + // the nested membership carrying that path exists, leaving + // the group momentarily admin-less — `checked_mode` + // rejects it through `ensure_admins` and replica startup + // fails. Defer founder downgrades until all memberships + // are in place. + if is_founder { + founder_downgrades.push(entry); + } else { + entries.push(entry); + } + } + } + entries.extend(founder_downgrades); + // Current friendships among the exported accounts. Preserve the + // request ID when one exists: a signed FriendRemove artifact uses + // it to distinguish this friendship from an older relationship + // between the same pair after the directory is projected. + let sorted: Vec<&String> = accounts.iter().collect(); + let mut pairs: Vec<(&String, &String)> = Vec::new(); + for (index, a) in sorted.iter().enumerate() { + for b in &sorted[index + 1..] { + if self.are_friends(a, b) { + pairs.push((a, b)); + } + } + } + for (a, b) in pairs { + let request = self.friend_requests.get(&pair(a, b)).cloned(); + entries.push(DirectoryEntry::FriendRequested { + from: (*a).clone(), + to: (*b).clone(), + id: request.clone(), + }); + entries.push(DirectoryEntry::FriendAccepted { + from: (*a).clone(), + to: (*b).clone(), + request, + id: None, + }); + } + Ok(entries) + } +} diff --git a/pkgs/id/crates/id-directory/src/directory/validate.rs b/pkgs/id/crates/id-directory/src/directory/validate.rs new file mode 100644 index 0000000000..aba53c4ccf --- /dev/null +++ b/pkgs/id/crates/id-directory/src/directory/validate.rs @@ -0,0 +1,158 @@ +//! Validation and normalization helpers for the directory, split out of +//! directory.rs for the F11.10 production-line guard (#8591). The public +//! helpers are re-exported from the directory module at their historical paths. + +use std::path::{Path, PathBuf}; + +use anyhow::{Context, Result, ensure}; +use ed25519_dalek::{SigningKey, VerifyingKey}; +use sha2::{Digest, Sha256}; + +use id_caps::world_scopes::WorldScopes; +use id_sync::artifact; + +use super::{Actor, KEY_DOMAIN, MAX_DESCRIPTION_CHARS, MAX_NAME_CHARS}; + +pub(super) fn artifact_path(journal: &Path) -> PathBuf { + journal.with_file_name(artifact::FILE) +} + +pub(super) fn signing_key(secret: &[u8; 32]) -> SigningKey { + let mut hasher = Sha256::new(); + hasher.update(KEY_DOMAIN); + hasher.update(secret); + SigningKey::from_bytes(&hasher.finalize().into()) +} + +pub(super) fn may_act_for(actor: Actor<'_>, account: &str) -> bool { + match actor { + Actor::Server => true, + Actor::Account(me) => me == account, + } +} + +/// A public key as lower-case hex, if it is an Ed25519 public key. +/// +/// # Errors +/// +/// Fails if the text is not 64 hex characters or not a valid key. +pub fn normalize_key(key: &str) -> Result { + let key = key.trim().to_ascii_lowercase(); + let bytes = hex_to_array::<32>(&key).context("a public key is 64 hex characters")?; + VerifyingKey::from_bytes(&bytes).context("not an Ed25519 public key")?; + Ok(key) +} + +/// An email address in lower case, checked for shape but not deliverability. +/// +/// # Errors +/// +/// Fails if the text does not look like `local@domain.tld`. +pub fn normalize_email(address: &str) -> Result { + let address = address.trim().to_ascii_lowercase(); + ensure!(address.len() <= 254, "email address is too long"); + let (local, domain) = address + .split_once('@') + .context("an email address has one @")?; + let local_ok = !local.is_empty() + && local.len() <= 64 + && !local.starts_with('.') + && !local.ends_with('.') + && !local.contains("..") + && local + .chars() + .all(|c| c.is_ascii_alphanumeric() || "!#$%&'*+-/=?^_`{|}~.".contains(c)); + let domain_ok = domain.contains('.') + && domain.split('.').all(|label| { + !label.is_empty() + && label.len() <= 63 + && !label.starts_with('-') + && !label.ends_with('-') + && label.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') + }); + ensure!(local_ok && domain_ok, "not an email address"); + Ok(address) +} + +pub(super) fn pair(a: &str, b: &str) -> (String, String) { + if a <= b { + (a.to_owned(), b.to_owned()) + } else { + (b.to_owned(), a.to_owned()) + } +} + +pub(super) fn ensure_account_id(id: &str) -> Result<()> { + ensure!( + hex_to_array::<32>(id).is_some(), + "account ID must be 64 hex characters" + ); + Ok(()) +} + +pub(super) fn permissions(bits: u8) -> Result { + WorldScopes::from_bits(bits).context("unknown permission bits") +} + +pub(super) fn clean_name(name: &str) -> Result { + clean_name_mode(name, true) +} + +pub(super) fn clean_name_mode(name: &str, refuse_format: bool) -> Result { + let name = name.trim(); + ensure!(!name.is_empty(), "name must not be empty"); + ensure!( + name.chars().count() <= MAX_NAME_CHARS, + "name must be at most {MAX_NAME_CHARS} characters" + ); + ensure!( + !name.chars().any(char::is_control), + "name must not contain control characters" + ); + if refuse_format { + ensure!( + !name.chars().any(id_core::petname::is_format_char), + "name must not contain format characters" + ); + } + Ok(name.to_owned()) +} + +pub(super) fn clean_description(description: &str) -> Result { + clean_description_mode(description, true) +} + +pub(super) fn clean_description_mode(description: &str, refuse_format: bool) -> Result { + let description = description.trim(); + ensure!( + description.chars().count() <= MAX_DESCRIPTION_CHARS, + "description must be at most {MAX_DESCRIPTION_CHARS} characters" + ); + ensure!( + !description.chars().any(|c| c.is_control() && c != '\n'), + "description must not contain control characters" + ); + if refuse_format { + ensure!( + !description.chars().any(id_core::petname::is_format_char), + "description must not contain format characters" + ); + } + Ok(description.to_owned()) +} + +/// Bytes decoded from a hex string of exactly twice N hex digits, if it is one. +pub fn hex_to_array(text: &str) -> Option<[u8; N]> { + // Every byte must be an ASCII hex digit (#2517): u8::from_str_radix + // also accepts a leading '+', so without this gate a byte 0x00-0x0f + // has two accepted spellings ('0x' and '+x') and key strings stop + // being canonical. + if text.len() != N * 2 || !text.bytes().all(|b| b.is_ascii_hexdigit()) { + return None; + } + let mut out = [0_u8; N]; + for (index, byte) in out.iter_mut().enumerate() { + *byte = u8::from_str_radix(&text[index * 2..index * 2 + 2], 16).ok()?; + } + Some(out) +}