use std::collections::HashMap;
use std::fmt;
use crate::cs1::PublicKeys;
use crate::error::{RejectKind, Rejection};
use crate::types::{InternetDomain, Role};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct KeyLookupError(pub String);
impl fmt::Display for KeyLookupError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl std::error::Error for KeyLookupError {}
pub trait IntoKeys {
fn into_keys(self) -> Vec<PublicKeys>;
}
impl IntoKeys for PublicKeys {
fn into_keys(self) -> Vec<PublicKeys> {
vec![self]
}
}
impl IntoKeys for Vec<PublicKeys> {
fn into_keys(self) -> Vec<PublicKeys> {
self
}
}
impl IntoKeys for &[PublicKeys] {
fn into_keys(self) -> Vec<PublicKeys> {
self.to_vec()
}
}
impl<const N: usize> IntoKeys for [PublicKeys; N] {
fn into_keys(self) -> Vec<PublicKeys> {
self.to_vec()
}
}
pub const MAX_KEYS: usize = 2;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Participant {
pub domain: InternetDomain,
pub role: Role,
keys: Vec<PublicKeys>,
pub endpoint: Option<String>,
}
impl Participant {
#[must_use]
pub fn new(domain: InternetDomain, role: Role, keys: PublicKeys) -> Self {
Self {
domain,
role,
keys: vec![keys],
endpoint: None,
}
}
#[must_use]
pub fn with_endpoint(mut self, url: impl Into<String>) -> Self {
self.endpoint = Some(url.into());
self
}
pub fn with_next_key(mut self, keys: PublicKeys) -> Result<Self, Rejection> {
if self.keys.len() >= MAX_KEYS {
return Err(too_many_keys(self.keys.len() + 1));
}
self.keys.push(keys);
Ok(self)
}
#[must_use]
pub fn keys(&self) -> &[PublicKeys] {
&self.keys
}
}
fn too_many_keys(n: usize) -> Rejection {
Rejection::new(
RejectKind::KeyLookup,
"[UFTP App. 4 §2] up to two keys per role",
format!("A participant publishes at most {MAX_KEYS} keys per role; this one has {n}."),
)
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Directory {
participants: HashMap<(InternetDomain, Role), Participant>,
}
impl Directory {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn with(mut self, participant: Participant) -> Self {
self.insert(participant);
self
}
pub fn insert(&mut self, participant: Participant) {
self.participants
.insert((participant.domain.clone(), participant.role), participant);
}
pub fn remove(&mut self, domain: &InternetDomain, role: Role) -> Option<Participant> {
self.participants.remove(&(domain.clone(), role))
}
#[must_use]
pub fn get(&self, domain: &InternetDomain, role: Role) -> Option<&Participant> {
self.participants.get(&(domain.clone(), role))
}
pub fn iter(&self) -> impl Iterator<Item = &Participant> {
self.participants.values()
}
pub fn keys(
&self,
domain: &InternetDomain,
role: Role,
) -> Result<&[PublicKeys], KeyLookupError> {
self.get(domain, role)
.map(|p| p.keys.as_slice())
.ok_or_else(|| KeyLookupError(format!("{domain} is not a known {role}")))
}
pub fn lookup<'a>(
&'a self,
) -> impl Fn(&InternetDomain, Role) -> Result<&'a [PublicKeys], KeyLookupError> + Copy + 'a
{
move |domain, role| self.keys(domain, role)
}
}
pub mod dns {
use super::{MAX_KEYS, too_many_keys};
use crate::cs1::PublicKeys;
use crate::error::{RejectKind, Rejection};
use crate::types::{InternetDomain, Role};
fn label(role: Role) -> &'static str {
match role {
Role::Agr => "agr",
Role::Cro => "cro",
Role::Dso => "dso",
}
}
#[must_use]
pub fn version_record(domain: &InternetDomain) -> String {
format!("_usef.{domain}")
}
#[must_use]
pub fn keys_record(domain: &InternetDomain, role: Role) -> String {
format!("_{}._usef.{domain}", label(role))
}
#[must_use]
pub fn endpoint_record(domain: &InternetDomain, role: Role) -> String {
format!("_http._{}._usef.{domain}", label(role))
}
#[must_use]
pub fn authorization_record(domain: &InternetDomain, suffix: &str) -> String {
format!("_usef.{domain}.{}", suffix.trim_matches('.'))
}
pub fn parse_keys_txt(txt: &str) -> Result<Vec<PublicKeys>, Rejection> {
let keys = txt
.split_ascii_whitespace()
.map(str::parse)
.collect::<Result<Vec<PublicKeys>, _>>()?;
match keys.len() {
0 => Err(Rejection::new(
RejectKind::KeyLookup,
"[UFTP App. 4 §2] _role._usef TXT record",
"The TXT record lists no key.",
)),
n if n > MAX_KEYS => Err(too_many_keys(n)),
_ => Ok(keys),
}
}
}