Skip to main content

cloudillo_types/
utils.rs

1// SPDX-FileCopyrightText: Szilárd Hajba
2// SPDX-License-Identifier: LGPL-3.0-or-later
3
4//! Utility functions
5
6use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
7use serde::de::DeserializeOwned;
8
9use crate::prelude::*;
10use rand::RngExt;
11
12pub const ID_LENGTH: usize = 24;
13pub const SAFE: [char; 62] = [
14	'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
15	'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B',
16	'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
17	'V', 'W', 'X', 'Y', 'Z',
18];
19
20/// Derive default display name from id_tag
21///
22/// Takes first portion (before '.'), capitalizes first letter.
23///
24/// # Examples
25/// - `"home.w9.hu"` → `"Home"`
26/// - `"john.example.com"` → `"John"`
27/// - `"alice"` → `"Alice"`
28pub fn derive_name_from_id_tag(id_tag: &str) -> String {
29	let first_part = id_tag.split('.').next().unwrap_or(id_tag);
30	let mut chars = first_part.chars();
31	match chars.next() {
32		Some(c) => c.to_uppercase().chain(chars).collect(),
33		None => id_tag.to_string(),
34	}
35}
36
37pub fn random_id() -> ClResult<String> {
38	let mut rng = rand::rng();
39	let mut result = String::with_capacity(ID_LENGTH);
40
41	for _ in 0..ID_LENGTH {
42		result.push(SAFE[rng.random_range(0..SAFE.len())]);
43	}
44	Ok(result)
45}
46
47/// Decode a JWT payload without verifying the signature.
48///
49/// WARNING: This MUST always be followed by proper signature verification.
50/// It only peeks at the payload to determine routing info (issuer, key_id, etc.).
51pub fn decode_jwt_no_verify<T: DeserializeOwned>(jwt: &str) -> ClResult<T> {
52	let mut parts = jwt.splitn(3, '.');
53	let _header = parts.next().ok_or(Error::Parse)?;
54	let payload = parts.next().ok_or(Error::Parse)?;
55	let _sig = parts.next().ok_or(Error::Parse)?;
56	let payload = URL_SAFE_NO_PAD.decode(payload.as_bytes()).map_err(|_| Error::Parse)?;
57	let payload: T = serde_json::from_slice(&payload).map_err(|_| Error::Parse)?;
58	Ok(payload)
59}
60
61/// Parse and validate an identity id_tag against a registrar's domain.
62///
63/// Splits a fully-qualified identity id_tag (e.g., "alice.example.com") into prefix and domain
64/// components, validating that the domain matches the registrar's domain.
65pub fn parse_and_validate_identity_id_tag(
66	id_tag: &str,
67	registrar_domain: &str,
68) -> ClResult<(String, String)> {
69	// Validate inputs
70	if registrar_domain.is_empty() {
71		return Err(Error::ValidationError("Registrar domain cannot be empty".to_string()));
72	}
73	if id_tag.is_empty() {
74		return Err(Error::ValidationError("Identity id_tag cannot be empty".to_string()));
75	}
76
77	// Check if id_tag ends with the registrar's domain as a suffix with a dot separator
78	let domain_with_dot = format!(".{}", registrar_domain);
79	if let Some(pos) = id_tag.rfind(&domain_with_dot) {
80		let prefix = id_tag[..pos].to_string();
81		if prefix.is_empty() {
82			return Err(Error::ValidationError(
83				"Invalid id_tag: prefix cannot be empty (id_tag must be in format 'prefix.domain')"
84					.to_string(),
85			));
86		}
87		Ok((prefix, registrar_domain.to_string()))
88	} else if id_tag == registrar_domain {
89		// Special case: id_tag is exactly the domain (empty prefix)
90		Err(Error::ValidationError(
91			"Invalid id_tag: prefix cannot be empty (id_tag must be in format 'prefix.domain')"
92				.to_string(),
93		))
94	} else {
95		Err(Error::ValidationError(format!(
96			"Identity id_tag '{}' does not match registrar domain '{}'",
97			id_tag, registrar_domain
98		)))
99	}
100}
101
102/// Mask an email for safe display: "al***@ex***.com"
103pub fn mask_email(email: &str) -> Option<String> {
104	let (local, domain) = email.split_once('@')?;
105	let (domain_name, tld) = domain.rsplit_once('.')?;
106
107	if local.is_empty() || domain_name.is_empty() {
108		return None;
109	}
110
111	let local_visible = &local[..local.len().min(1)];
112	let domain_visible = &domain_name[..domain_name.len().min(1)];
113
114	Some(format!("{}***@{}***.{}", local_visible, domain_visible, tld))
115}
116
117#[cfg(test)]
118mod tests {
119	use super::*;
120
121	#[test]
122	fn test_derive_name_from_id_tag() {
123		assert_eq!(derive_name_from_id_tag("home.w9.hu"), "Home");
124		assert_eq!(derive_name_from_id_tag("john.example.com"), "John");
125		assert_eq!(derive_name_from_id_tag("alice"), "Alice");
126		assert_eq!(derive_name_from_id_tag("UPPER.test"), "UPPER");
127		assert_eq!(derive_name_from_id_tag(""), "");
128	}
129
130	#[test]
131	fn test_simple_valid_identity() {
132		let result = parse_and_validate_identity_id_tag("alice.example.com", "example.com");
133		assert!(result.is_ok());
134		let (prefix, domain) = result.unwrap();
135		assert_eq!(prefix, "alice");
136		assert_eq!(domain, "example.com");
137	}
138
139	#[test]
140	fn test_multi_part_prefix_valid() {
141		let result = parse_and_validate_identity_id_tag("alice.bob.example.com", "example.com");
142		assert!(result.is_ok());
143		let (prefix, domain) = result.unwrap();
144		assert_eq!(prefix, "alice.bob");
145		assert_eq!(domain, "example.com");
146	}
147
148	#[test]
149	fn test_empty_prefix_fails() {
150		let result = parse_and_validate_identity_id_tag("example.com", "example.com");
151		assert!(result.is_err());
152	}
153
154	#[test]
155	fn test_domain_mismatch_fails() {
156		let result = parse_and_validate_identity_id_tag("alice.other.com", "example.com");
157		assert!(result.is_err());
158	}
159
160	#[test]
161	fn test_empty_id_tag_fails() {
162		let result = parse_and_validate_identity_id_tag("", "example.com");
163		assert!(result.is_err());
164	}
165
166	#[test]
167	fn test_empty_registrar_domain_fails() {
168		let result = parse_and_validate_identity_id_tag("alice.example.com", "");
169		assert!(result.is_err());
170	}
171	#[test]
172	fn test_mask_email() {
173		assert_eq!(super::mask_email("alice@example.com"), Some("a***@e***.com".to_string()));
174		assert_eq!(super::mask_email("a@x.co"), Some("a***@x***.co".to_string()));
175		assert_eq!(super::mask_email("bob@sub.domain.org"), Some("b***@s***.org".to_string()));
176		assert_eq!(super::mask_email("no-at-sign"), None);
177		assert_eq!(super::mask_email("user@nodot"), None);
178		assert_eq!(super::mask_email("@example.com"), None);
179		assert_eq!(super::mask_email("user@.com"), None);
180		assert_eq!(super::mask_email(""), None);
181	}
182}
183
184// vim: ts=4