#![forbid(unsafe_code)]
use alloc::string::String;
use core::fmt;
pub const DEFAULT_SUITE_NAME: &str = "ed25519";
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum SignatureSuite {
Ed25519,
Other(String),
}
impl SignatureSuite {
pub fn parse(s: &str) -> Self {
if s == DEFAULT_SUITE_NAME {
SignatureSuite::Ed25519
} else {
SignatureSuite::Other(String::from(s))
}
}
pub fn as_str(&self) -> &str {
match self {
SignatureSuite::Ed25519 => DEFAULT_SUITE_NAME,
SignatureSuite::Other(s) => s.as_str(),
}
}
pub fn is_implemented(&self) -> bool {
matches!(self, SignatureSuite::Ed25519)
}
}
impl fmt::Display for SignatureSuite {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum KeyIdError {
MissingSigil,
EmptySuite,
EmptyName,
}
impl fmt::Display for KeyIdError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
KeyIdError::MissingSigil => f.write_str("key identifier must start with '@'"),
KeyIdError::EmptySuite => f.write_str("key identifier has an empty suite marker"),
KeyIdError::EmptyName => f.write_str("key identifier has an empty name"),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct KeyId {
pub suite: SignatureSuite,
pub name: String,
}
impl KeyId {
pub fn from_multikey(
key: &crate::multikey::Multikey,
) -> Result<Self, crate::multikey::MultikeyError> {
if key.codec() != crate::multikey::PublicKeyCodec::Ed25519 {
return Err(crate::multikey::MultikeyError::UnsupportedSigningCodec(
key.codec().code(),
));
}
Ok(Self {
suite: SignatureSuite::Ed25519,
name: key.to_multibase(),
})
}
pub fn parse(spelling: &str) -> Result<Self, KeyIdError> {
let rest = spelling.strip_prefix('@').ok_or(KeyIdError::MissingSigil)?;
let (suite, name) = match rest.split_once(':') {
Some(("", _)) => return Err(KeyIdError::EmptySuite),
Some((s, n)) => (SignatureSuite::parse(s), n),
None => (SignatureSuite::Ed25519, rest),
};
if name.is_empty() {
return Err(KeyIdError::EmptyName);
}
Ok(KeyId {
suite,
name: String::from(name),
})
}
pub fn canonical_spelling(&self) -> String {
use alloc::format;
format!("@{}:{}", self.suite.as_str(), self.name)
}
}
impl fmt::Display for KeyId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "@{}:{}", self.suite.as_str(), self.name)
}
}
#[cfg(test)]
mod tests {
use super::*;
use alloc::collections::BTreeSet;
use alloc::string::ToString;
#[test]
fn omitted_suite_normalises_to_ed25519() {
let k = KeyId::parse("@alice").unwrap();
assert_eq!(k.suite, SignatureSuite::Ed25519);
assert_eq!(k.name, "alice");
}
#[test]
fn alias_spellings_are_one_identity() {
let bare = KeyId::parse("@alice").unwrap();
let explicit = KeyId::parse("@ed25519:alice").unwrap();
assert_eq!(bare, explicit);
let mut set = BTreeSet::new();
set.insert(bare);
set.insert(explicit);
assert_eq!(set.len(), 1);
}
#[test]
fn same_name_different_suite_is_distinct() {
let ed = KeyId::parse("@ed25519:alice").unwrap();
let pq = KeyId::parse("@pq-frodo:alice").unwrap();
assert_ne!(ed, pq);
assert_eq!(pq.suite, SignatureSuite::Other("pq-frodo".to_string()));
assert!(!pq.suite.is_implemented());
}
#[test]
fn canonical_spelling_is_suite_explicit() {
let k = KeyId::parse("@alice").unwrap();
assert_eq!(k.canonical_spelling(), "@ed25519:alice");
assert_eq!(alloc::format!("{k}"), "@ed25519:alice");
}
#[test]
fn malformed_spellings_are_typed_rejections() {
assert_eq!(KeyId::parse("alice"), Err(KeyIdError::MissingSigil));
assert_eq!(KeyIdError::MissingSigil, KeyId::parse("").unwrap_err());
assert_eq!(KeyId::parse("@:alice"), Err(KeyIdError::EmptySuite));
assert_eq!(KeyId::parse("@"), Err(KeyIdError::EmptyName));
assert_eq!(KeyId::parse("@ed25519:"), Err(KeyIdError::EmptyName));
}
#[test]
fn name_may_contain_further_colons() {
let k = KeyId::parse("@ed25519:did:crdt:xyz").unwrap();
assert_eq!(k.name, "did:crdt:xyz");
}
#[test]
fn suite_parse_roundtrip() {
assert_eq!(SignatureSuite::parse("ed25519"), SignatureSuite::Ed25519);
assert_eq!(SignatureSuite::parse("ed25519").as_str(), "ed25519");
let other = SignatureSuite::parse("sphincs+");
assert_eq!(other.as_str(), "sphincs+");
assert!(!other.is_implemented());
}
}