Add key identifiers
This commit is contained in:
parent
3746f1d331
commit
c0a1d8bd44
@ -9,6 +9,10 @@ Breaking changes:
|
||||
`Into<Box<str>>` of the id type). This is technically a breaking change, but extremely unlikely
|
||||
to affect any existing code.
|
||||
|
||||
Improvements:
|
||||
|
||||
* Add `DeviceKeyId`, `KeyAlgorithm`, and `ServerKeyId`
|
||||
|
||||
# 0.16.2
|
||||
|
||||
Improvements:
|
||||
|
@ -22,7 +22,8 @@ default = ["serde"]
|
||||
[dependencies]
|
||||
either = { version = "1.5.3", optional = true }
|
||||
rand = { version = "0.7.3", optional = true }
|
||||
serde = { version = "1.0.106", optional = true }
|
||||
serde = { version = "1.0.106", optional = true, features = ["derive"] }
|
||||
strum = { version = "0.18.0", features = ["derive"] }
|
||||
|
||||
[dev-dependencies]
|
||||
serde_json = "1.0.51"
|
||||
|
136
src/device_key_id.rs
Normal file
136
src/device_key_id.rs
Normal file
@ -0,0 +1,136 @@
|
||||
//! Identifiers for device keys for end-to-end encryption.
|
||||
|
||||
use crate::{device_id::DeviceId, error::Error, key_algorithms::DeviceKeyAlgorithm};
|
||||
use std::num::NonZeroU8;
|
||||
use std::str::FromStr;
|
||||
|
||||
/// A key algorithm and a device id, combined with a ':'
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct DeviceKeyId<T> {
|
||||
full_id: T,
|
||||
colon_idx: NonZeroU8,
|
||||
}
|
||||
|
||||
impl<T> DeviceKeyId<T> {
|
||||
/// Returns key algorithm of the device key ID.
|
||||
pub fn algorithm(&self) -> DeviceKeyAlgorithm
|
||||
where
|
||||
T: AsRef<str>,
|
||||
{
|
||||
DeviceKeyAlgorithm::from_str(&self.full_id.as_ref()[..self.colon_idx.get() as usize])
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// Returns device ID of the device key ID.
|
||||
pub fn device_id(&self) -> DeviceId
|
||||
where
|
||||
T: AsRef<str>,
|
||||
{
|
||||
DeviceId::from(&self.full_id.as_ref()[self.colon_idx.get() as usize + 1..])
|
||||
}
|
||||
}
|
||||
|
||||
fn try_from<S, T>(key_id: S) -> Result<DeviceKeyId<T>, Error>
|
||||
where
|
||||
S: AsRef<str> + Into<T>,
|
||||
{
|
||||
let key_str = key_id.as_ref();
|
||||
let colon_idx =
|
||||
NonZeroU8::new(key_str.find(':').ok_or(Error::MissingDeviceKeyDelimiter)? as u8)
|
||||
.ok_or(Error::UnknownKeyAlgorithm)?;
|
||||
|
||||
DeviceKeyAlgorithm::from_str(&key_str[0..colon_idx.get() as usize])
|
||||
.map_err(|_| Error::UnknownKeyAlgorithm)?;
|
||||
|
||||
Ok(DeviceKeyId {
|
||||
full_id: key_id.into(),
|
||||
colon_idx,
|
||||
})
|
||||
}
|
||||
|
||||
common_impls!(
|
||||
DeviceKeyId,
|
||||
try_from,
|
||||
"Device key ID with algorithm and device ID"
|
||||
);
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use std::convert::TryFrom;
|
||||
|
||||
#[cfg(feature = "serde")]
|
||||
use serde_json::{from_value as from_json_value, json, to_value as to_json_value};
|
||||
|
||||
use super::DeviceKeyId;
|
||||
use crate::{device_id::DeviceId, error::Error, key_algorithms::DeviceKeyAlgorithm};
|
||||
|
||||
#[test]
|
||||
fn convert_device_key_id() {
|
||||
assert_eq!(
|
||||
DeviceKeyId::<&str>::try_from("ed25519:JLAFKJWSCS")
|
||||
.expect("Failed to create device key ID.")
|
||||
.as_ref(),
|
||||
"ed25519:JLAFKJWSCS"
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(feature = "serde")]
|
||||
#[test]
|
||||
fn serialize_device_key_id() {
|
||||
let device_key_id = DeviceKeyId::<&str>::try_from("ed25519:JLAFKJWSCS").unwrap();
|
||||
let serialized = to_json_value(device_key_id).unwrap();
|
||||
|
||||
let expected = json!("ed25519:JLAFKJWSCS");
|
||||
assert_eq!(serialized, expected);
|
||||
}
|
||||
|
||||
#[cfg(feature = "serde")]
|
||||
#[test]
|
||||
fn deserialize_device_key_id() {
|
||||
let deserialized: DeviceKeyId<_> = from_json_value(json!("ed25519:JLAFKJWSCS")).unwrap();
|
||||
|
||||
let expected = DeviceKeyId::try_from("ed25519:JLAFKJWSCS").unwrap();
|
||||
assert_eq!(deserialized, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_key_algorithm() {
|
||||
assert_eq!(
|
||||
DeviceKeyId::<&str>::try_from(":JLAFKJWSCS").unwrap_err(),
|
||||
Error::UnknownKeyAlgorithm
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_delimiter() {
|
||||
assert_eq!(
|
||||
DeviceKeyId::<&str>::try_from("ed25519|JLAFKJWSCS").unwrap_err(),
|
||||
Error::MissingDeviceKeyDelimiter,
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_key_algorithm() {
|
||||
assert_eq!(
|
||||
DeviceKeyId::<&str>::try_from("signed_curve25510:JLAFKJWSCS").unwrap_err(),
|
||||
Error::UnknownKeyAlgorithm,
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_device_id_ok() {
|
||||
assert!(DeviceKeyId::<&str>::try_from("ed25519:").is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn valid_key_algorithm() {
|
||||
let device_key_id = DeviceKeyId::<&str>::try_from("ed25519:JLAFKJWSCS").unwrap();
|
||||
assert_eq!(device_key_id.algorithm(), DeviceKeyAlgorithm::Ed25519);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn valid_device_id() {
|
||||
let device_key_id = DeviceKeyId::<&str>::try_from("ed25519:JLAFKJWSCS").unwrap();
|
||||
assert_eq!(device_key_id.device_id(), DeviceId::from("JLAFKJWSCS"));
|
||||
}
|
||||
}
|
12
src/error.rs
12
src/error.rs
@ -9,6 +9,8 @@ pub enum Error {
|
||||
///
|
||||
/// Only relevant for user IDs.
|
||||
InvalidCharacters,
|
||||
/// The key version contains outside of [a-zA-Z0-9_].
|
||||
InvalidKeyVersion,
|
||||
/// The localpart of the ID string is not valid (because it is empty).
|
||||
InvalidLocalPart,
|
||||
/// The server name part of the the ID string is not a valid server name.
|
||||
@ -19,20 +21,30 @@ pub enum Error {
|
||||
MinimumLengthNotSatisfied,
|
||||
/// The ID is missing the colon delimiter between localpart and server name.
|
||||
MissingDelimiter,
|
||||
/// The ID is missing the colon delimiter between key algorithm and device ID.
|
||||
MissingDeviceKeyDelimiter,
|
||||
/// The ID is missing the colon delimiter between key algorithm and version.
|
||||
MissingServerKeyDelimiter,
|
||||
/// The ID is missing the leading sigil.
|
||||
MissingSigil,
|
||||
/// The key algorithm is not recognized.
|
||||
UnknownKeyAlgorithm,
|
||||
}
|
||||
|
||||
impl Display for Error {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
|
||||
let message = match self {
|
||||
Error::InvalidCharacters => "localpart contains invalid characters",
|
||||
Error::InvalidKeyVersion => "key id version contains invalid characters",
|
||||
Error::InvalidLocalPart => "localpart is empty",
|
||||
Error::InvalidServerName => "server name is not a valid IP address or domain name",
|
||||
Error::MaximumLengthExceeded => "ID exceeds 255 bytes",
|
||||
Error::MinimumLengthNotSatisfied => "ID must be at least 4 characters",
|
||||
Error::MissingDelimiter => "colon is required between localpart and server name",
|
||||
Error::MissingDeviceKeyDelimiter => "colon is required between algorithm and device ID",
|
||||
Error::MissingServerKeyDelimiter => "colon is required between algorithm and version",
|
||||
Error::MissingSigil => "leading sigil is missing",
|
||||
Error::UnknownKeyAlgorithm => "unknown key algorithm specified",
|
||||
};
|
||||
|
||||
write!(f, "{}", message)
|
||||
|
33
src/key_algorithms.rs
Normal file
33
src/key_algorithms.rs
Normal file
@ -0,0 +1,33 @@
|
||||
//! Key algorithms used in Matrix spec.
|
||||
|
||||
#[cfg(feature = "serde")]
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use strum::{AsRefStr, Display, EnumString};
|
||||
|
||||
/// The basic key algorithms in the specification
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, AsRefStr, Display, EnumString)]
|
||||
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
|
||||
#[non_exhaustive]
|
||||
pub enum DeviceKeyAlgorithm {
|
||||
/// The Ed25519 signature algorithm.
|
||||
#[strum(to_string = "ed25519")]
|
||||
Ed25519,
|
||||
|
||||
/// The Curve25519 ECDH algorithm.
|
||||
#[strum(to_string = "curve25519")]
|
||||
Curve25519,
|
||||
|
||||
/// The Curve25519 ECDH algorithm, but the key also contains signatures
|
||||
#[strum(to_string = "signed_curve25519")]
|
||||
SignedCurve25519,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, AsRefStr, Display, EnumString)]
|
||||
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
|
||||
#[non_exhaustive]
|
||||
pub enum ServerKeyAlgorithm {
|
||||
/// The Ed25519 signature algorithm.
|
||||
#[strum(to_string = "ed25519")]
|
||||
Ed25519,
|
||||
}
|
@ -26,11 +26,14 @@ mod error;
|
||||
mod server_name;
|
||||
|
||||
pub mod device_id;
|
||||
pub mod device_key_id;
|
||||
pub mod event_id;
|
||||
pub mod key_algorithms;
|
||||
pub mod room_alias_id;
|
||||
pub mod room_id;
|
||||
pub mod room_id_or_room_alias_id;
|
||||
pub mod room_version_id;
|
||||
pub mod server_key_id;
|
||||
pub mod user_id;
|
||||
|
||||
/// An owned event ID.
|
||||
|
125
src/server_key_id.rs
Normal file
125
src/server_key_id.rs
Normal file
@ -0,0 +1,125 @@
|
||||
//! Identifiers for homeserver signing keys used for federation.
|
||||
|
||||
use std::{num::NonZeroU8, str::FromStr};
|
||||
|
||||
use crate::{error::Error, key_algorithms::ServerKeyAlgorithm};
|
||||
|
||||
/// Key identifiers used for homeserver signing keys.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ServerKeyId<T> {
|
||||
full_id: T,
|
||||
colon_idx: NonZeroU8,
|
||||
}
|
||||
|
||||
impl<T> ServerKeyId<T> {
|
||||
/// Returns key algorithm of the server key ID.
|
||||
pub fn algorithm(&self) -> ServerKeyAlgorithm
|
||||
where
|
||||
T: AsRef<str>,
|
||||
{
|
||||
ServerKeyAlgorithm::from_str(&self.full_id.as_ref()[..self.colon_idx.get() as usize])
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// Returns the version of the server key ID.
|
||||
pub fn version(&self) -> &str
|
||||
where
|
||||
T: AsRef<str>,
|
||||
{
|
||||
&self.full_id.as_ref()[self.colon_idx.get() as usize + 1..]
|
||||
}
|
||||
}
|
||||
|
||||
fn try_from<S, T>(key_id: S) -> Result<ServerKeyId<T>, Error>
|
||||
where
|
||||
S: AsRef<str> + Into<T>,
|
||||
{
|
||||
let key_str = key_id.as_ref();
|
||||
let colon_idx =
|
||||
NonZeroU8::new(key_str.find(':').ok_or(Error::MissingServerKeyDelimiter)? as u8)
|
||||
.ok_or(Error::UnknownKeyAlgorithm)?;
|
||||
|
||||
validate_server_key_algorithm(&key_str[..colon_idx.get() as usize])?;
|
||||
|
||||
validate_version(&key_str[colon_idx.get() as usize + 1..])?;
|
||||
|
||||
Ok(ServerKeyId {
|
||||
full_id: key_id.into(),
|
||||
colon_idx,
|
||||
})
|
||||
}
|
||||
|
||||
common_impls!(ServerKeyId, try_from, "Key ID with algorithm and version");
|
||||
|
||||
fn validate_version(version: &str) -> Result<(), Error> {
|
||||
if version.is_empty() {
|
||||
return Err(Error::MinimumLengthNotSatisfied);
|
||||
} else if !version.chars().all(|c| c.is_alphanumeric() || c == '_') {
|
||||
return Err(Error::InvalidCharacters);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_server_key_algorithm(algorithm: &str) -> Result<(), Error> {
|
||||
match ServerKeyAlgorithm::from_str(algorithm) {
|
||||
Ok(_) => Ok(()),
|
||||
Err(_) => Err(Error::UnknownKeyAlgorithm),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::convert::TryFrom;
|
||||
|
||||
#[cfg(feature = "serde")]
|
||||
use serde_json::{from_value as from_json_value, json, to_value as to_json_value};
|
||||
|
||||
use super::ServerKeyId;
|
||||
use crate::error::Error;
|
||||
|
||||
#[cfg(feature = "serde")]
|
||||
use crate::key_algorithms::ServerKeyAlgorithm;
|
||||
|
||||
#[cfg(feature = "serde")]
|
||||
#[test]
|
||||
fn deserialize_id() {
|
||||
let server_key_id: ServerKeyId<_> = from_json_value(json!("ed25519:Abc_1")).unwrap();
|
||||
assert_eq!(server_key_id.algorithm(), ServerKeyAlgorithm::Ed25519);
|
||||
assert_eq!(server_key_id.version(), "Abc_1");
|
||||
}
|
||||
|
||||
#[cfg(feature = "serde")]
|
||||
#[test]
|
||||
fn serialize_id() {
|
||||
let server_key_id: ServerKeyId<&str> = ServerKeyId::try_from("ed25519:abc123").unwrap();
|
||||
assert_eq!(
|
||||
to_json_value(&server_key_id).unwrap(),
|
||||
json!("ed25519:abc123")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_version_characters() {
|
||||
assert_eq!(
|
||||
ServerKeyId::<&str>::try_from("ed25519:Abc-1").unwrap_err(),
|
||||
Error::InvalidCharacters,
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_key_algorithm() {
|
||||
assert_eq!(
|
||||
ServerKeyId::<&str>::try_from("signed_curve25519:Abc-1").unwrap_err(),
|
||||
Error::UnknownKeyAlgorithm,
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_delimiter() {
|
||||
assert_eq!(
|
||||
ServerKeyId::<&str>::try_from("ed25519|Abc_1").unwrap_err(),
|
||||
Error::MissingServerKeyDelimiter,
|
||||
);
|
||||
}
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user