Rename ServerKeyId to SigningKeyId

This commit is contained in:
Isaiah Inuwa 2020-08-21 15:56:51 -05:00 committed by Jonas Platte
parent 8f710a371b
commit b793a790db
No known key found for this signature in database
GPG Key ID: 7D261D771D915378
17 changed files with 91 additions and 78 deletions

View File

@ -15,7 +15,7 @@ pub mod unban_user;
use std::collections::BTreeMap; use std::collections::BTreeMap;
use ruma_common::{thirdparty::Medium, Outgoing}; use ruma_common::{thirdparty::Medium, Outgoing};
use ruma_identifiers::{ServerKeyId, ServerNameBox}; use ruma_identifiers::{ServerNameBox, SigningKeyId};
use serde::Serialize; use serde::Serialize;
/// A signature of an `m.third_party_invite` token to prove that this user owns a third party /// A signature of an `m.third_party_invite` token to prove that this user owns a third party
@ -32,7 +32,7 @@ pub struct ThirdPartySigned<'a> {
pub token: &'a str, pub token: &'a str,
/// A signatures object containing a signature of the entire signed object. /// A signatures object containing a signature of the entire signed object.
pub signatures: BTreeMap<ServerNameBox, BTreeMap<ServerKeyId, String>>, pub signatures: BTreeMap<ServerNameBox, BTreeMap<SigningKeyId, String>>,
} }
/// Represents third party IDs to invite to the room. /// Represents third party IDs to invite to the room.

View File

@ -12,7 +12,7 @@ use std::{collections::BTreeMap, time::SystemTime};
use js_int::UInt; use js_int::UInt;
use ruma_events::EventType; use ruma_events::EventType;
use ruma_identifiers::{EventId, RoomId, ServerKeyId, ServerNameBox, UserId}; use ruma_identifiers::{EventId, RoomId, ServerNameBox, SigningKeyId, UserId};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_json::Value as JsonValue; use serde_json::Value as JsonValue;
@ -86,7 +86,7 @@ pub struct RoomV1Pdu {
pub hashes: EventHash, pub hashes: EventHash,
/// Signatures for the PDU. /// Signatures for the PDU.
pub signatures: BTreeMap<ServerNameBox, BTreeMap<ServerKeyId, String>>, pub signatures: BTreeMap<ServerNameBox, BTreeMap<SigningKeyId, String>>,
} }
/// A 'persistent data unit' (event) for room versions 3 and beyond. /// A 'persistent data unit' (event) for room versions 3 and beyond.
@ -143,7 +143,7 @@ pub struct RoomV3Pdu {
pub hashes: EventHash, pub hashes: EventHash,
/// Signatures for the PDU. /// Signatures for the PDU.
pub signatures: BTreeMap<ServerNameBox, BTreeMap<ServerKeyId, String>>, pub signatures: BTreeMap<ServerNameBox, BTreeMap<SigningKeyId, String>>,
} }
/// PDU type without event and room IDs. /// PDU type without event and room IDs.
@ -220,7 +220,7 @@ pub struct RoomV1PduStub {
pub hashes: EventHash, pub hashes: EventHash,
/// Signatures for the PDU. /// Signatures for the PDU.
pub signatures: BTreeMap<ServerNameBox, BTreeMap<ServerKeyId, String>>, pub signatures: BTreeMap<ServerNameBox, BTreeMap<SigningKeyId, String>>,
} }
impl RoomV1PduStub { impl RoomV1PduStub {
@ -298,7 +298,7 @@ pub struct RoomV3PduStub {
pub hashes: EventHash, pub hashes: EventHash,
/// Signatures for the PDU. /// Signatures for the PDU.
pub signatures: BTreeMap<ServerNameBox, BTreeMap<ServerKeyId, String>>, pub signatures: BTreeMap<ServerNameBox, BTreeMap<SigningKeyId, String>>,
} }
impl RoomV3PduStub { impl RoomV3PduStub {

View File

@ -4,7 +4,7 @@ use std::collections::BTreeMap;
use ruma_common::StringEnum; use ruma_common::StringEnum;
use ruma_events_macros::StateEventContent; use ruma_events_macros::StateEventContent;
use ruma_identifiers::{ServerKeyId, ServerNameBox, UserId}; use ruma_identifiers::{ServerNameBox, SigningKeyId, UserId};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use crate::{StateEvent, StrippedStateEvent, SyncStateEvent}; use crate::{StateEvent, StrippedStateEvent, SyncStateEvent};
@ -109,7 +109,7 @@ pub struct SignedContent {
/// A single signature from the verifying server, in the format specified by the Signing Events /// A single signature from the verifying server, in the format specified by the Signing Events
/// section of the server-server API. /// section of the server-server API.
pub signatures: BTreeMap<ServerNameBox, BTreeMap<ServerKeyId, String>>, pub signatures: BTreeMap<ServerNameBox, BTreeMap<SigningKeyId, String>>,
/// The token property of the containing third_party_invite object. /// The token property of the containing third_party_invite object.
pub token: String, pub token: String,

View File

@ -2,7 +2,7 @@
use std::{collections::BTreeMap, time::SystemTime}; use std::{collections::BTreeMap, time::SystemTime};
use ruma_identifiers::{ServerKeyId, ServerNameBox}; use ruma_identifiers::{ServerNameBox, SigningKeyId};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
pub mod discover_homeserver; pub mod discover_homeserver;
@ -49,19 +49,19 @@ impl OldVerifyKey {
/// Queried server key, signed by the notary server. /// Queried server key, signed by the notary server.
#[derive(Clone, Debug, Deserialize, Serialize)] #[derive(Clone, Debug, Deserialize, Serialize)]
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)] #[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
pub struct ServerKey { pub struct SigningKey {
/// DNS name of the homeserver. /// DNS name of the homeserver.
pub server_name: ServerNameBox, pub server_name: ServerNameBox,
/// Public keys of the homeserver for verifying digital signatures. /// Public keys of the homeserver for verifying digital signatures.
pub verify_keys: BTreeMap<ServerKeyId, VerifyKey>, pub verify_keys: BTreeMap<SigningKeyId, VerifyKey>,
/// Public keys that the homeserver used to use and when it stopped using them. /// Public keys that the homeserver used to use and when it stopped using them.
pub old_verify_keys: BTreeMap<ServerKeyId, OldVerifyKey>, pub old_verify_keys: BTreeMap<SigningKeyId, OldVerifyKey>,
/// Digital signatures of this object signed using the verify_keys. Map of /// Digital signatures of this object signed using the verify_keys. Map of
/// server name to keys by key ID /// server name to keys by key ID
pub signatures: BTreeMap<ServerNameBox, BTreeMap<ServerKeyId, String>>, pub signatures: BTreeMap<ServerNameBox, BTreeMap<SigningKeyId, String>>,
/// Timestamp when the keys should be refreshed. This field MUST be ignored in room /// Timestamp when the keys should be refreshed. This field MUST be ignored in room
/// versions 1, 2, 3, and 4. /// versions 1, 2, 3, and 4.
@ -69,8 +69,8 @@ pub struct ServerKey {
pub valid_until_ts: SystemTime, pub valid_until_ts: SystemTime,
} }
impl ServerKey { impl SigningKey {
/// Creates a new `ServerKey` with the given server name and validity timestamp. /// Creates a new `SigningKey` with the given server name and validity timestamp.
/// ///
/// All other fields will be empty. /// All other fields will be empty.
pub fn new(server_name: ServerNameBox, valid_until_ts: SystemTime) -> Self { pub fn new(server_name: ServerNameBox, valid_until_ts: SystemTime) -> Self {

View File

@ -2,7 +2,7 @@
use std::time::SystemTime; use std::time::SystemTime;
use crate::discovery::ServerKey; use crate::discovery::SigningKey;
use ruma_api::ruma_api; use ruma_api::ruma_api;
use ruma_identifiers::ServerName; use ruma_identifiers::ServerName;
@ -34,7 +34,7 @@ ruma_api! {
response: { response: {
/// The queried server's keys, signed by the notary server. /// The queried server's keys, signed by the notary server.
pub server_keys: Vec<ServerKey>, pub server_keys: Vec<SigningKey>,
} }
} }
@ -47,7 +47,7 @@ impl<'a> Request<'a> {
impl Response { impl Response {
/// Creates a new `Response` with the given keys. /// Creates a new `Response` with the given keys.
pub fn new(server_keys: Vec<ServerKey>) -> Self { pub fn new(server_keys: Vec<SigningKey>) -> Self {
Self { server_keys } Self { server_keys }
} }
} }

View File

@ -2,9 +2,9 @@
use std::{collections::BTreeMap, time::SystemTime}; use std::{collections::BTreeMap, time::SystemTime};
use crate::discovery::ServerKey; use crate::discovery::SigningKey;
use ruma_api::ruma_api; use ruma_api::ruma_api;
use ruma_identifiers::{ServerKeyId, ServerNameBox}; use ruma_identifiers::{ServerNameBox, SigningKeyId};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
ruma_api! { ruma_api! {
@ -28,7 +28,7 @@ ruma_api! {
/// The notary server may return multiple keys regardless of the Key IDs /// The notary server may return multiple keys regardless of the Key IDs
/// given. /// given.
#[ruma_api(body)] #[ruma_api(body)]
pub server_keys: BTreeMap<ServerNameBox, BTreeMap<ServerKeyId, QueryCriteria>>, pub server_keys: BTreeMap<ServerNameBox, BTreeMap<SigningKeyId, QueryCriteria>>,
/// A millisecond POSIX timestamp in milliseconds indicating when the /// A millisecond POSIX timestamp in milliseconds indicating when the
/// returned certificates will need to be valid until to be useful to /// returned certificates will need to be valid until to be useful to
@ -43,14 +43,14 @@ ruma_api! {
response: { response: {
/// The queried server's keys, signed by the notary server. /// The queried server's keys, signed by the notary server.
pub server_keys: Vec<ServerKey>, pub server_keys: Vec<SigningKey>,
} }
} }
impl Request { impl Request {
/// Creates a new `Request` with the given query criteria and `minimum_valid_until` timestamp. /// Creates a new `Request` with the given query criteria and `minimum_valid_until` timestamp.
pub fn new( pub fn new(
server_keys: BTreeMap<ServerNameBox, BTreeMap<ServerKeyId, QueryCriteria>>, server_keys: BTreeMap<ServerNameBox, BTreeMap<SigningKeyId, QueryCriteria>>,
minimum_valid_until_ts: SystemTime, minimum_valid_until_ts: SystemTime,
) -> Self { ) -> Self {
Self { server_keys, minimum_valid_until_ts } Self { server_keys, minimum_valid_until_ts }
@ -59,7 +59,7 @@ impl Request {
impl Response { impl Response {
/// Creates a new `Response` with the given keys. /// Creates a new `Response` with the given keys.
pub fn new(server_keys: Vec<ServerKey>) -> Self { pub fn new(server_keys: Vec<SigningKey>) -> Self {
Self { server_keys } Self { server_keys }
} }
} }

View File

@ -1,6 +1,6 @@
//! [GET /_matrix/key/v2/server](https://matrix.org/docs/spec/server_server/r0.1.4#get-matrix-key-v2-server-keyid) //! [GET /_matrix/key/v2/server](https://matrix.org/docs/spec/server_server/r0.1.4#get-matrix-key-v2-server-keyid)
use crate::discovery::ServerKey; use crate::discovery::SigningKey;
use ruma_api::ruma_api; use ruma_api::ruma_api;
ruma_api! { ruma_api! {
@ -19,7 +19,7 @@ ruma_api! {
response: { response: {
/// Queried server key, signed by the notary server. /// Queried server key, signed by the notary server.
#[ruma_api(body)] #[ruma_api(body)]
pub server_key: ServerKey, pub server_key: SigningKey,
} }
} }
@ -32,13 +32,13 @@ impl Request {
impl Response { impl Response {
/// Creates a new `Response` with the given server key. /// Creates a new `Response` with the given server key.
pub fn new(server_key: ServerKey) -> Self { pub fn new(server_key: SigningKey) -> Self {
Self { server_key } Self { server_key }
} }
} }
impl From<ServerKey> for Response { impl From<SigningKey> for Response {
fn from(server_key: ServerKey) -> Self { fn from(server_key: SigningKey) -> Self {
Self::new(server_key) Self::new(server_key)
} }
} }

View File

@ -2,7 +2,7 @@
use ruma_api::ruma_api; use ruma_api::ruma_api;
use ruma_common::thirdparty::Medium; use ruma_common::thirdparty::Medium;
use ruma_identifiers::{RoomId, ServerKeyId, ServerNameBox, UserId}; use ruma_identifiers::{RoomId, ServerNameBox, SigningKeyId, UserId};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::collections::BTreeMap; use std::collections::BTreeMap;
@ -61,7 +61,7 @@ pub struct ThirdPartyInvite {
pub sender: UserId, pub sender: UserId,
/// Signature from the identity server using a long-term private key. /// Signature from the identity server using a long-term private key.
pub signed: BTreeMap<ServerNameBox, BTreeMap<ServerKeyId, String>>, pub signed: BTreeMap<ServerNameBox, BTreeMap<SigningKeyId, String>>,
} }
impl ThirdPartyInvite { impl ThirdPartyInvite {
@ -71,7 +71,7 @@ impl ThirdPartyInvite {
mxid: UserId, mxid: UserId,
room_id: RoomId, room_id: RoomId,
sender: UserId, sender: UserId,
signed: BTreeMap<ServerNameBox, BTreeMap<ServerKeyId, String>>, signed: BTreeMap<ServerNameBox, BTreeMap<SigningKeyId, String>>,
) -> Self { ) -> Self {
Self { medium: Medium::Email, address, mxid, room_id, sender, signed } Self { medium: Medium::Email, address, mxid, room_id, sender, signed }
} }

View File

@ -2,7 +2,7 @@ use proc_macro::TokenStream;
use quote::quote; use quote::quote;
use ruma_identifiers_validation::{ use ruma_identifiers_validation::{
device_key_id, event_id, room_alias_id, room_id, room_version_id, server_key_id, server_name, device_key_id, event_id, room_alias_id, room_id, room_version_id, server_name, signing_key_id,
user_id, user_id,
}; };
use syn::{parse::Parse, parse_macro_input, LitStr, Path, Token}; use syn::{parse::Parse, parse_macro_input, LitStr, Path, Token};
@ -85,10 +85,10 @@ pub fn room_version_id(input: TokenStream) -> TokenStream {
#[proc_macro] #[proc_macro]
pub fn server_key_id(input: TokenStream) -> TokenStream { pub fn server_key_id(input: TokenStream) -> TokenStream {
let Input { dollar_crate, id } = parse_macro_input!(input as Input); let Input { dollar_crate, id } = parse_macro_input!(input as Input);
assert!(server_key_id::validate(&id.value()).is_ok(), "Invalid server_key_id"); assert!(signing_key_id::validate(&id.value()).is_ok(), "Invalid server_key_id");
let output = quote! { let output = quote! {
<#dollar_crate::ServerKeyId as ::std::convert::TryFrom<&str>>::try_from(#id).unwrap() <#dollar_crate::SigningKeyId as ::std::convert::TryFrom<&str>>::try_from(#id).unwrap()
}; };
output.into() output.into()
@ -108,6 +108,18 @@ pub fn server_name(input: TokenStream) -> TokenStream {
output.into() output.into()
} }
#[proc_macro]
pub fn signing_key_id(input: TokenStream) -> TokenStream {
let Input { dollar_crate, id } = parse_macro_input!(input as Input);
assert!(signing_key_id::validate(&id.value()).is_ok(), "Invalid signing_key_id");
let output = quote! {
<#dollar_crate::SigningKeyId as ::std::convert::TryFrom<&str>>::try_from(#id).unwrap()
};
output.into()
}
#[proc_macro] #[proc_macro]
pub fn user_id(input: TokenStream) -> TokenStream { pub fn user_id(input: TokenStream) -> TokenStream {
let Input { dollar_crate, id } = parse_macro_input!(input as Input); let Input { dollar_crate, id } = parse_macro_input!(input as Input);

View File

@ -42,17 +42,17 @@ impl TryFrom<String> for DeviceKeyAlgorithm {
} }
} }
/// The server key algorithms defined in the Matrix spec. /// The signing key algorithms defined in the Matrix spec.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, AsRefStr, Display, EnumString)] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, AsRefStr, Display, EnumString)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize), serde(rename_all = "snake_case"))] #[cfg_attr(feature = "serde", derive(Deserialize, Serialize), serde(rename_all = "snake_case"))]
#[non_exhaustive] #[non_exhaustive]
#[strum(serialize_all = "snake_case")] #[strum(serialize_all = "snake_case")]
pub enum ServerKeyAlgorithm { pub enum SigningKeyAlgorithm {
/// The Ed25519 signature algorithm. /// The Ed25519 signature algorithm.
Ed25519, Ed25519,
} }
impl TryFrom<&'_ str> for ServerKeyAlgorithm { impl TryFrom<&'_ str> for SigningKeyAlgorithm {
type Error = strum::ParseError; type Error = strum::ParseError;
fn try_from(value: &str) -> Result<Self, Self::Error> { fn try_from(value: &str) -> Result<Self, Self::Error> {
@ -60,7 +60,7 @@ impl TryFrom<&'_ str> for ServerKeyAlgorithm {
} }
} }
impl TryFrom<String> for ServerKeyAlgorithm { impl TryFrom<String> for SigningKeyAlgorithm {
type Error = strum::ParseError; type Error = strum::ParseError;
fn try_from(value: String) -> Result<Self, Self::Error> { fn try_from(value: String) -> Result<Self, Self::Error> {
@ -132,7 +132,7 @@ mod tests {
use ruma_serde::test::serde_json_eq; use ruma_serde::test::serde_json_eq;
use serde_json::json; use serde_json::json;
use super::{DeviceKeyAlgorithm, EventEncryptionAlgorithm, ServerKeyAlgorithm}; use super::{DeviceKeyAlgorithm, EventEncryptionAlgorithm, SigningKeyAlgorithm};
#[test] #[test]
fn parse_device_key_algorithm() { fn parse_device_key_algorithm() {
@ -142,8 +142,8 @@ mod tests {
} }
#[test] #[test]
fn parse_server_key_algorithm() { fn parse_signing_key_algorithm() {
assert_eq!("ed25519".parse(), Ok(ServerKeyAlgorithm::Ed25519)); assert_eq!("ed25519".parse(), Ok(SigningKeyAlgorithm::Ed25519));
} }
#[test] #[test]

View File

@ -29,7 +29,7 @@ pub enum Error {
MissingDeviceKeyDelimiter, MissingDeviceKeyDelimiter,
/// The ID is missing the colon delimiter between key algorithm and version. /// The ID is missing the colon delimiter between key algorithm and version.
MissingServerKeyDelimiter, MissingSigningKeyDelimiter,
/// The ID is missing the correct leading sigil. /// The ID is missing the correct leading sigil.
MissingSigil, MissingSigil,
@ -48,7 +48,7 @@ impl Display for Error {
Error::MaximumLengthExceeded => "ID exceeds 255 bytes", Error::MaximumLengthExceeded => "ID exceeds 255 bytes",
Error::MissingDelimiter => "colon is required between localpart and server name", Error::MissingDelimiter => "colon is required between localpart and server name",
Error::MissingDeviceKeyDelimiter => "colon is required between algorithm and device ID", Error::MissingDeviceKeyDelimiter => "colon is required between algorithm and device ID",
Error::MissingServerKeyDelimiter => "colon is required between algorithm and version", Error::MissingSigningKeyDelimiter => "colon is required between algorithm and version",
Error::MissingSigil => "leading sigil is incorrect or missing", Error::MissingSigil => "leading sigil is incorrect or missing",
Error::UnknownKeyAlgorithm => "unknown key algorithm specified", Error::UnknownKeyAlgorithm => "unknown key algorithm specified",
}; };

View File

@ -6,8 +6,8 @@ pub mod room_alias_id;
pub mod room_id; pub mod room_id;
pub mod room_id_or_alias_id; pub mod room_id_or_alias_id;
pub mod room_version_id; pub mod room_version_id;
pub mod server_key_id;
pub mod server_name; pub mod server_name;
pub mod signing_key_id;
pub mod user_id; pub mod user_id;
use std::num::NonZeroU8; use std::num::NonZeroU8;

View File

@ -1,12 +1,12 @@
use std::{num::NonZeroU8, str::FromStr}; use std::{num::NonZeroU8, str::FromStr};
use crate::{crypto_algorithms::ServerKeyAlgorithm, Error}; use crate::{crypto_algorithms::SigningKeyAlgorithm, Error};
pub fn validate(s: &str) -> Result<NonZeroU8, Error> { pub fn validate(s: &str) -> Result<NonZeroU8, Error> {
let colon_idx = NonZeroU8::new(s.find(':').ok_or(Error::MissingServerKeyDelimiter)? as u8) let colon_idx = NonZeroU8::new(s.find(':').ok_or(Error::MissingSigningKeyDelimiter)? as u8)
.ok_or(Error::UnknownKeyAlgorithm)?; .ok_or(Error::UnknownKeyAlgorithm)?;
validate_server_key_algorithm(&s[..colon_idx.get() as usize])?; validate_signing_key_algorithm(&s[..colon_idx.get() as usize])?;
validate_version(&s[colon_idx.get() as usize + 1..])?; validate_version(&s[colon_idx.get() as usize + 1..])?;
Ok(colon_idx) Ok(colon_idx)
@ -22,8 +22,8 @@ fn validate_version(version: &str) -> Result<(), Error> {
Ok(()) Ok(())
} }
fn validate_server_key_algorithm(algorithm: &str) -> Result<(), Error> { fn validate_signing_key_algorithm(algorithm: &str) -> Result<(), Error> {
match ServerKeyAlgorithm::from_str(algorithm) { match SigningKeyAlgorithm::from_str(algorithm) {
Ok(_) => Ok(()), Ok(_) => Ok(()),
Err(_) => Err(Error::UnknownKeyAlgorithm), Err(_) => Err(Error::UnknownKeyAlgorithm),
} }

View File

@ -5,10 +5,11 @@ Breaking changes:
* Update strum dependency to 0.19 * Update strum dependency to 0.19
* Remove deprecated constructors * Remove deprecated constructors
* Remove deprecated `is_` methods * Remove deprecated `is_` methods
* Rename `ServerKeyId` to `SigningKeyId`
Improvements: Improvements:
* Add `DeviceKeyId::from_parts` and `ServerKeyId::from_parts` * Add `DeviceKeyId::from_parts` and `SigningKeyId::from_parts`
* Add `DeviceIdBox` and `ServerNameBox` type aliases * Add `DeviceIdBox` and `ServerNameBox` type aliases
# 0.17.4 # 0.17.4

View File

@ -28,13 +28,13 @@ pub use crate::{
room_id::RoomId, room_id::RoomId,
room_id_or_room_alias_id::RoomIdOrAliasId, room_id_or_room_alias_id::RoomIdOrAliasId,
room_version_id::RoomVersionId, room_version_id::RoomVersionId,
server_key_id::ServerKeyId,
server_name::{ServerName, ServerNameBox}, server_name::{ServerName, ServerNameBox},
signing_key_id::SigningKeyId,
user_id::UserId, user_id::UserId,
}; };
#[doc(inline)] #[doc(inline)]
pub use ruma_identifiers_validation::{ pub use ruma_identifiers_validation::{
crypto_algorithms::{DeviceKeyAlgorithm, EventEncryptionAlgorithm, ServerKeyAlgorithm}, crypto_algorithms::{DeviceKeyAlgorithm, EventEncryptionAlgorithm, SigningKeyAlgorithm},
error::Error, error::Error,
}; };
@ -50,8 +50,8 @@ mod room_alias_id;
mod room_id; mod room_id;
mod room_id_or_room_alias_id; mod room_id_or_room_alias_id;
mod room_version_id; mod room_version_id;
mod server_key_id;
mod server_name; mod server_name;
mod signing_key_id;
/// Check whether a given string is a valid server name according to [the specification][]. /// Check whether a given string is a valid server name according to [the specification][].
/// ///
@ -137,7 +137,7 @@ macro_rules! room_version_id {
}; };
} }
/// Compile-time checked `ServerKeyId` construction. /// Compile-time checked `SigningKeyId` construction.
#[macro_export] #[macro_export]
macro_rules! server_key_id { macro_rules! server_key_id {
($s:literal) => { ($s:literal) => {

View File

@ -2,18 +2,18 @@
use std::{convert::TryInto, num::NonZeroU8, str::FromStr}; use std::{convert::TryInto, num::NonZeroU8, str::FromStr};
use ruma_identifiers_validation::{crypto_algorithms::ServerKeyAlgorithm, Error}; use ruma_identifiers_validation::{crypto_algorithms::SigningKeyAlgorithm, Error};
/// Key identifiers used for homeserver signing keys. /// Key identifiers used for homeserver signing keys.
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct ServerKeyId { pub struct SigningKeyId {
full_id: Box<str>, full_id: Box<str>,
colon_idx: NonZeroU8, colon_idx: NonZeroU8,
} }
impl ServerKeyId { impl SigningKeyId {
/// Create a `ServerKeyId` from a `ServerKeyAlgorithm` and a `ServerId`. /// Create a `SigningKeyId` from a `SigningKeyAlgorithm` and a `ServerId`.
pub fn from_parts(algorithm: ServerKeyAlgorithm, version: &str) -> Self { pub fn from_parts(algorithm: SigningKeyAlgorithm, version: &str) -> Self {
let algorithm: &str = algorithm.as_ref(); let algorithm: &str = algorithm.as_ref();
let mut res = String::with_capacity(algorithm.len() + 1 + version.len()); let mut res = String::with_capacity(algorithm.len() + 1 + version.len());
@ -25,12 +25,12 @@ impl ServerKeyId {
NonZeroU8::new(algorithm.len().try_into().expect("no algorithm name len > 255")) NonZeroU8::new(algorithm.len().try_into().expect("no algorithm name len > 255"))
.expect("no empty algorithm name"); .expect("no empty algorithm name");
ServerKeyId { full_id: res.into(), colon_idx } SigningKeyId { full_id: res.into(), colon_idx }
} }
/// Returns key algorithm of the server key ID. /// Returns key algorithm of the server key ID.
pub fn algorithm(&self) -> ServerKeyAlgorithm { pub fn algorithm(&self) -> SigningKeyAlgorithm {
ServerKeyAlgorithm::from_str(&self.full_id[..self.colon_idx.get() as usize]).unwrap() SigningKeyAlgorithm::from_str(&self.full_id[..self.colon_idx.get() as usize]).unwrap()
} }
/// Returns the version of the server key ID. /// Returns the version of the server key ID.
@ -39,15 +39,15 @@ impl ServerKeyId {
} }
} }
fn try_from<S>(key_id: S) -> Result<ServerKeyId, Error> fn try_from<S>(key_id: S) -> Result<SigningKeyId, Error>
where where
S: AsRef<str> + Into<Box<str>>, S: AsRef<str> + Into<Box<str>>,
{ {
let colon_idx = ruma_identifiers_validation::server_key_id::validate(key_id.as_ref())?; let colon_idx = ruma_identifiers_validation::signing_key_id::validate(key_id.as_ref())?;
Ok(ServerKeyId { full_id: key_id.into(), colon_idx }) Ok(SigningKeyId { full_id: key_id.into(), colon_idx })
} }
common_impls!(ServerKeyId, try_from, "Key ID with algorithm and version"); common_impls!(SigningKeyId, try_from, "Key ID with algorithm and version");
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
@ -56,35 +56,35 @@ mod tests {
#[cfg(feature = "serde")] #[cfg(feature = "serde")]
use serde_json::{from_value as from_json_value, json, to_value as to_json_value}; use serde_json::{from_value as from_json_value, json, to_value as to_json_value};
use crate::{Error, ServerKeyId}; use crate::{Error, SigningKeyId};
#[cfg(feature = "serde")] #[cfg(feature = "serde")]
use ruma_identifiers_validation::crypto_algorithms::ServerKeyAlgorithm; use ruma_identifiers_validation::crypto_algorithms::SigningKeyAlgorithm;
#[cfg(feature = "serde")] #[cfg(feature = "serde")]
#[test] #[test]
fn deserialize_id() { fn deserialize_id() {
let server_key_id: ServerKeyId = from_json_value(json!("ed25519:Abc_1")).unwrap(); let server_key_id: SigningKeyId = from_json_value(json!("ed25519:Abc_1")).unwrap();
assert_eq!(server_key_id.algorithm(), ServerKeyAlgorithm::Ed25519); assert_eq!(server_key_id.algorithm(), SigningKeyAlgorithm::Ed25519);
assert_eq!(server_key_id.version(), "Abc_1"); assert_eq!(server_key_id.version(), "Abc_1");
} }
#[cfg(feature = "serde")] #[cfg(feature = "serde")]
#[test] #[test]
fn serialize_id() { fn serialize_id() {
let server_key_id: ServerKeyId = ServerKeyId::try_from("ed25519:abc123").unwrap(); let server_key_id: SigningKeyId = SigningKeyId::try_from("ed25519:abc123").unwrap();
assert_eq!(to_json_value(&server_key_id).unwrap(), json!("ed25519:abc123")); assert_eq!(to_json_value(&server_key_id).unwrap(), json!("ed25519:abc123"));
} }
#[test] #[test]
fn invalid_version_characters() { fn invalid_version_characters() {
assert_eq!(ServerKeyId::try_from("ed25519:Abc-1").unwrap_err(), Error::InvalidCharacters); assert_eq!(SigningKeyId::try_from("ed25519:Abc-1").unwrap_err(), Error::InvalidCharacters);
} }
#[test] #[test]
fn invalid_key_algorithm() { fn invalid_key_algorithm() {
assert_eq!( assert_eq!(
ServerKeyId::try_from("signed_curve25519:Abc-1").unwrap_err(), SigningKeyId::try_from("signed_curve25519:Abc-1").unwrap_err(),
Error::UnknownKeyAlgorithm, Error::UnknownKeyAlgorithm,
); );
} }
@ -92,8 +92,8 @@ mod tests {
#[test] #[test]
fn missing_delimiter() { fn missing_delimiter() {
assert_eq!( assert_eq!(
ServerKeyId::try_from("ed25519|Abc_1").unwrap_err(), SigningKeyId::try_from("ed25519|Abc_1").unwrap_err(),
Error::MissingServerKeyDelimiter, Error::MissingSigningKeyDelimiter,
); );
} }
} }

View File

@ -27,7 +27,7 @@ pub use ruma_serde as serde;
pub use ruma_identifiers::{ pub use ruma_identifiers::{
device_id, device_key_id, event_id, room_alias_id, room_id, room_version_id, server_key_id, device_id, device_key_id, event_id, room_alias_id, room_id, room_version_id, server_key_id,
server_name, user_id, DeviceId, DeviceKeyAlgorithm, DeviceKeyId, EventId, RoomAliasId, RoomId, server_name, user_id, DeviceId, DeviceKeyAlgorithm, DeviceKeyId, EventId, RoomAliasId, RoomId,
RoomIdOrAliasId, RoomVersionId, ServerKeyAlgorithm, ServerKeyId, ServerName, UserId, RoomIdOrAliasId, RoomVersionId, ServerName, SigningKeyAlgorithm, SigningKeyId, UserId,
}; };
#[cfg(feature = "ruma-events")] #[cfg(feature = "ruma-events")]