pub const MAX_IDENTIFIER_LEN: usize = 64;
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("{0}")]
pub struct ValidationError(pub String);
pub fn validate_identifier(label: &str, value: &str) -> Result<(), ValidationError> {
if value.is_empty() {
return Err(ValidationError(format!("{label} must not be empty")));
}
if value.len() > MAX_IDENTIFIER_LEN {
return Err(ValidationError(format!(
"{label} is {} bytes; maximum is {MAX_IDENTIFIER_LEN}",
value.len()
)));
}
for (i, ch) in value.chars().enumerate() {
let ok = ch.is_ascii_alphanumeric() || ch == '.' || ch == '_' || ch == '-';
if !ok {
return Err(ValidationError(format!(
"{label} contains an invalid character {ch:?} at position {i}; \
allowed: A-Z, a-z, 0-9, '.', '_', '-'"
)));
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn accepts_common_identifier_shapes() {
for ok in [
"myapp",
"My-App_1",
"context.v2",
"a",
"0",
"didcomm-mediator",
"_private",
"CamelCase",
] {
validate_identifier("id", ok).unwrap_or_else(|e| panic!("{ok:?} rejected: {e:?}"));
}
}
#[test]
fn rejects_empty() {
let err = validate_identifier("id", "").expect_err("empty must be rejected");
assert_eq!(err.0, "id must not be empty");
}
#[test]
fn rejects_separator_injection() {
for bad in [
"global:evil", "../../etc", "a:b:c", "my/ctx", "with space", "tab\there", "with\nnewline", "null\0byte", "unicode:§§", "quote\"injected", ] {
validate_identifier("id", bad).expect_err(&format!("{bad:?} must be rejected"));
}
}
#[test]
fn rejects_too_long() {
let long = "a".repeat(MAX_IDENTIFIER_LEN + 1);
validate_identifier("id", &long).expect_err("overlong must be rejected");
}
#[test]
fn accepts_exactly_at_limit() {
let edge = "a".repeat(MAX_IDENTIFIER_LEN);
validate_identifier("id", &edge).expect("exactly-at-limit must pass");
}
#[test]
fn error_message_names_the_field() {
let err = validate_identifier("context_id", "bad:id").expect_err("rejected");
assert!(
err.0.contains("context_id"),
"error must name the field it is validating — got {}",
err.0
);
}
}