From 16079edd94417ee6fe09396fe7ef98037bf7f14b Mon Sep 17 00:00:00 2001 From: David Venhoek Date: Tue, 24 Mar 2026 15:57:02 +0100 Subject: [PATCH] Adapted to newest version of s2connect openAPI spec. --- .../examples/communication-client.rs | 10 +- .../examples/communication-server.rs | 6 +- .../examples/discovery-client.rs | 4 +- .../examples/discovery-server.rs | 4 +- .../examples/pairing-client.rs | 14 +- .../examples/pairing-server.rs | 14 +- s2energy-connection/src/common/wire.rs | 48 +- .../src/communication/client.rs | 50 +- s2energy-connection/src/communication/mod.rs | 38 +- .../src/communication/server.rs | 18 +- s2energy-connection/src/communication/wire.rs | 36 +- s2energy-connection/src/discovery/mod.rs | 16 +- s2energy-connection/src/lib.rs | 3 +- s2energy-connection/src/pairing/client.rs | 306 ++++++------ s2energy-connection/src/pairing/mod.rs | 96 ++-- s2energy-connection/src/pairing/server.rs | 468 +++++++++--------- s2energy-connection/src/pairing/wire.rs | 62 +-- 17 files changed, 600 insertions(+), 593 deletions(-) diff --git a/s2energy-connection/examples/communication-client.rs b/s2energy-connection/examples/communication-client.rs index 408f78a..6d42f5d 100644 --- a/s2energy-connection/examples/communication-client.rs +++ b/s2energy-connection/examples/communication-client.rs @@ -4,7 +4,7 @@ use uuid::uuid; use rustls::pki_types::{CertificateDer, pem::PemObject}; use s2energy_common::S2Transport; use s2energy_connection::{ - AccessToken, MessageVersion, S2NodeId, + AccessToken, MessageVersion, NodeId, communication::{Client, ClientConfig, ClientPairing, NodeConfig}, }; use tracing_subscriber::{EnvFilter, fmt, prelude::*}; @@ -12,18 +12,18 @@ use tracing_subscriber::{EnvFilter, fmt, prelude::*}; struct MemoryPairing { communication_url: String, tokens: Vec, - server: S2NodeId, - client: S2NodeId, + server: NodeId, + client: NodeId, } impl ClientPairing for &mut MemoryPairing { type Error = Infallible; - fn client_id(&self) -> S2NodeId { + fn client_id(&self) -> NodeId { self.client.clone() } - fn server_id(&self) -> S2NodeId { + fn server_id(&self) -> NodeId { self.server.clone() } diff --git a/s2energy-connection/examples/communication-server.rs b/s2energy-connection/examples/communication-server.rs index 7bfb2d5..ec8a9b9 100644 --- a/s2energy-connection/examples/communication-server.rs +++ b/s2energy-connection/examples/communication-server.rs @@ -9,7 +9,7 @@ use uuid::uuid; use axum_server::tls_rustls::RustlsConfig; use s2energy_common::S2Transport; use s2energy_connection::{ - AccessToken, MessageVersion, S2NodeId, + AccessToken, MessageVersion, NodeId, communication::{NodeConfig, PairingLookupResult, Server, ServerConfig, ServerPairing, ServerPairingStore}, }; use tracing_subscriber::{EnvFilter, fmt, prelude::*}; @@ -17,8 +17,8 @@ use tracing_subscriber::{EnvFilter, fmt, prelude::*}; struct MemoryPairingStoreInner { token: AccessToken, config: Arc, - server: S2NodeId, - client: S2NodeId, + server: NodeId, + client: NodeId, // indication of whether the client has unpaired with us. unpaired: bool, } diff --git a/s2energy-connection/examples/discovery-client.rs b/s2energy-connection/examples/discovery-client.rs index 92fda48..3cd40fe 100644 --- a/s2energy-connection/examples/discovery-client.rs +++ b/s2energy-connection/examples/discovery-client.rs @@ -1,8 +1,8 @@ -use s2energy_connection::{S2Role, discovery::S2Discoverer}; +use s2energy_connection::{Role, discovery::S2Discoverer}; #[tokio::main(flavor = "current_thread")] async fn main() { - let mut discoverer = S2Discoverer::new(S2Role::Cem).await.unwrap(); + let mut discoverer = S2Discoverer::new(Role::Cem).await.unwrap(); while let Ok(event) = discoverer.next_event().await { match event { diff --git a/s2energy-connection/examples/discovery-server.rs b/s2energy-connection/examples/discovery-server.rs index 8de8c77..adbd8b0 100644 --- a/s2energy-connection/examples/discovery-server.rs +++ b/s2energy-connection/examples/discovery-server.rs @@ -1,11 +1,11 @@ use s2energy_connection::{ - S2Role, + Role, discovery::{DiscoverableS2Endpoint, advertise}, }; #[tokio::main(flavor = "current_thread")] async fn main() { - let endpoint = DiscoverableS2Endpoint::build_with_pairing(vec![S2Role::Cem], "https://example.com/".into()) + let endpoint = DiscoverableS2Endpoint::build_with_pairing(vec![Role::Cem], "https://example.com/".into()) .unwrap() .with_endpoint_name("test endpoint".into()) .build(); diff --git a/s2energy-connection/examples/pairing-client.rs b/s2energy-connection/examples/pairing-client.rs index 4911bca..3748f17 100644 --- a/s2energy-connection/examples/pairing-client.rs +++ b/s2energy-connection/examples/pairing-client.rs @@ -3,8 +3,8 @@ use std::path::PathBuf; use uuid::uuid; use s2energy_connection::{ - Deployment, MessageVersion, S2EndpointDescription, S2NodeDescription, S2Role, - pairing::{Client, ClientConfig, NodeConfig, PairingRemote, PairingS2NodeId}, + Deployment, EndpointDescription, MessageVersion, NodeDescription, Role, + pairing::{Client, ClientConfig, NodeConfig, NodeIdAlias, PairingRemote}, }; use tracing_subscriber::{EnvFilter, fmt, prelude::*}; @@ -18,14 +18,14 @@ async fn main() { .init(); let config = NodeConfig::builder( - S2NodeDescription { + NodeDescription { id: uuid!("67e55044-10b1-426f-9247-bb680e5fe0c7").into(), brand: String::from("super-reliable-corp"), - logo_uri: None, + logo_url: None, type_: String::from("fancy"), model_name: String::from("the best"), user_defined_name: None, - role: S2Role::Rm, + role: Role::Rm, }, vec![MessageVersion("v1".into())], ) @@ -37,7 +37,7 @@ async fn main() { additional_certificates: vec![ CertificateDer::from_pem_file(PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("testdata").join("root.pem")).unwrap(), ], - endpoint_description: S2EndpointDescription::default(), + endpoint_description: EndpointDescription::default(), pairing_deployment: Deployment::Lan, }) .unwrap(); @@ -48,7 +48,7 @@ async fn main() { &config, PairingRemote { url: "https://localhost:8005".into(), - id: Some(PairingS2NodeId("ninechars".into())), + id: Some(NodeIdAlias("ninechars".into())), }, PAIRING_TOKEN, async |pairing| { diff --git a/s2energy-connection/examples/pairing-server.rs b/s2energy-connection/examples/pairing-server.rs index 110baa8..a9f8380 100644 --- a/s2energy-connection/examples/pairing-server.rs +++ b/s2energy-connection/examples/pairing-server.rs @@ -3,8 +3,8 @@ use std::{net::SocketAddr, path::PathBuf, sync::Arc}; use uuid::uuid; use s2energy_connection::{ - MessageVersion, S2EndpointDescription, S2NodeDescription, S2Role, - pairing::{NodeConfig, PairingS2NodeId, PairingToken, Server, ServerConfig}, + EndpointDescription, MessageVersion, NodeDescription, Role, + pairing::{NodeConfig, NodeIdAlias, PairingToken, Server, ServerConfig}, }; use tracing_subscriber::{EnvFilter, fmt, prelude::*}; @@ -20,18 +20,18 @@ async fn main() { let server = Server::new(ServerConfig { leaf_certificate: None, - endpoint_description: S2EndpointDescription::default(), + endpoint_description: EndpointDescription::default(), advertised_nodes: vec![], }); let config = NodeConfig::builder( - S2NodeDescription { + NodeDescription { id: uuid!("67e55044-10b1-426f-9247-bb680e5fe0c8").into(), brand: String::from("super-reliable-corp"), - logo_uri: None, + logo_url: None, type_: String::from("fancy"), model_name: String::from("the best"), user_defined_name: None, - role: S2Role::Cem, + role: Role::Cem, }, vec![MessageVersion("v1".into())], ) @@ -59,7 +59,7 @@ async fn main() { .unwrap(); }); - let pairing_node_id = PairingS2NodeId("ninechars".into()); + let pairing_node_id = NodeIdAlias("ninechars".into()); let server_clone = server.clone(); server diff --git a/s2energy-connection/src/common/wire.rs b/s2energy-connection/src/common/wire.rs index b37cb50..d2268b9 100644 --- a/s2energy-connection/src/common/wire.rs +++ b/s2energy-connection/src/common/wire.rs @@ -38,13 +38,13 @@ pub struct MessageVersion(pub String); /// Information about the pairing endpoint of a S2 node. #[derive(Default, Debug, Serialize, Deserialize, Clone, PartialEq, Eq, Hash)] #[serde(rename_all = "camelCase")] -pub struct S2EndpointDescription { +pub struct EndpointDescription { /// Name of the endpoint. #[serde(default)] pub name: Option, /// URI of a logo to be used for the endpoint in GUIs. #[serde(default)] - pub logo_uri: Option, + pub logo_url: Option, /// Type of deployment used by the endpoint (local or globally routable). #[serde(default)] pub deployment: Option, @@ -130,21 +130,21 @@ impl From for InvalidNodeId { /// Unique identifier of the S2 node. #[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub struct S2NodeId(Uuid); +pub struct NodeId(Uuid); -impl From for S2NodeId { +impl From for NodeId { fn from(value: Uuid) -> Self { Self(value) } } -impl From for Uuid { - fn from(value: S2NodeId) -> Self { +impl From for Uuid { + fn from(value: NodeId) -> Self { value.0 } } -impl TryFrom for S2NodeId { +impl TryFrom for NodeId { type Error = InvalidNodeId; fn try_from(value: String) -> Result { @@ -152,7 +152,7 @@ impl TryFrom for S2NodeId { } } -impl TryFrom<&str> for S2NodeId { +impl TryFrom<&str> for NodeId { type Error = InvalidNodeId; fn try_from(value: &str) -> Result { @@ -160,7 +160,7 @@ impl TryFrom<&str> for S2NodeId { } } -impl std::ops::Deref for S2NodeId { +impl std::ops::Deref for NodeId { type Target = Uuid; fn deref(&self) -> &Self::Target { @@ -168,19 +168,19 @@ impl std::ops::Deref for S2NodeId { } } -impl std::ops::DerefMut for S2NodeId { +impl std::ops::DerefMut for NodeId { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } -impl core::fmt::Display for S2NodeId { +impl core::fmt::Display for NodeId { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { self.0.as_hyphenated().fmt(f) } } -impl S2NodeId { +impl NodeId { /// Generate a new random node id. #[expect(clippy::new_without_default, reason = "New uses non-trivial randomness")] pub fn new() -> Self { @@ -191,14 +191,14 @@ impl S2NodeId { /// Information about the S2 node. #[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, Hash)] #[serde(rename_all = "camelCase")] -pub struct S2NodeDescription { +pub struct NodeDescription { /// Unique identifier of the node. - pub id: S2NodeId, + pub id: NodeId, /// Brandname used for the node. pub brand: String, /// URI of a logo to be used for the node in GUIs. #[serde(default)] - pub logo_uri: Option, + pub logo_url: Option, /// The type of this node. pub type_: String, /// Model name of the device this node belongs to. @@ -207,7 +207,7 @@ pub struct S2NodeDescription { #[serde(default)] pub user_defined_name: Option, /// The S2 role this device has (e.g. CEM or RM). - pub role: S2Role, + pub role: Role, } /// Identifier of a protocol that can be used for communication of S2 messages between nodes. @@ -220,14 +220,14 @@ pub struct CommunicationProtocol(pub String); /// Role within the S2 standard. #[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Hash)] #[serde(rename_all = "UPPERCASE")] -pub enum S2Role { +pub enum Role { /// Customer Energy Manager. Cem, /// Resource Manager. Rm, } -impl S2Role { +impl Role { pub(crate) fn service_subtype(self) -> &'static str { match self { Self::Cem => "cem", @@ -267,20 +267,20 @@ impl TryFrom> for Deployment { pub(crate) mod test { use uuid::{Uuid, uuid}; - use crate::{S2NodeDescription, S2Role, pairing::PairingS2NodeId}; + use crate::{NodeDescription, Role, pairing::NodeIdAlias}; pub(crate) const UUID_A: Uuid = uuid!("67e55044-10b1-426f-9247-bb680e5fe0c8"); pub(crate) const UUID_B: Uuid = uuid!("67e55044-10b1-426f-9247-bb680e5fe0c7"); - pub(crate) fn pairing_s2_node_id() -> PairingS2NodeId { - PairingS2NodeId("test_pairing_id".into()) + pub(crate) fn pairing_s2_node_id() -> NodeIdAlias { + NodeIdAlias("test_pairing_id".into()) } - pub(crate) fn basic_node_description(uuid: Uuid, role: S2Role) -> S2NodeDescription { - S2NodeDescription { + pub(crate) fn basic_node_description(uuid: Uuid, role: Role) -> NodeDescription { + NodeDescription { id: uuid.into(), brand: String::from("super-reliable-corp"), - logo_uri: None, + logo_url: None, type_: String::from("fancy"), model_name: String::from("the best"), user_defined_name: None, diff --git a/s2energy-connection/src/communication/client.rs b/s2energy-connection/src/communication/client.rs index 08a8f42..e02563a 100644 --- a/s2energy-connection/src/communication/client.rs +++ b/s2energy-connection/src/communication/client.rs @@ -7,7 +7,7 @@ use tokio_tungstenite::{Connector, connect_async_tls_with_config, tungstenite::C use tracing::{debug, trace}; use crate::{ - AccessToken, CommunicationProtocol, S2EndpointDescription, S2NodeId, + AccessToken, CommunicationProtocol, EndpointDescription, NodeId, common::negotiate_version, communication::{ CommunicationResult, ConnectionInfo, Error, ErrorKind, NodeConfig, WebSocketTransport, @@ -25,7 +25,7 @@ pub struct ClientConfig { /// When the remote is on the LAN, this is not used. pub additional_certificates: Vec>, /// Optional description of this endpoint, sent as update to the server. - pub endpoint_description: Option, + pub endpoint_description: Option, } /// Client used to setup communication sessions for a node. @@ -33,7 +33,7 @@ pub struct ClientConfig { pub struct Client { config: Arc, additional_certificates: Vec>, - endpoint_description: Option, + endpoint_description: Option, } /// A description of a pairing between two S2 Nodes. @@ -45,9 +45,9 @@ pub trait ClientPairing: Send { type Error: std::error::Error + 'static; /// The Node ID of the S2 node initiating communication. - fn client_id(&self) -> S2NodeId; + fn client_id(&self) -> NodeId; /// The Node Id of the S2 node receiving the request to communicate. - fn server_id(&self) -> S2NodeId; + fn server_id(&self) -> NodeId; /// The currently stored access tokens for the connection. fn access_tokens(&self) -> impl AsRef<[AccessToken]>; /// The communication url the client can use to contact the server. @@ -301,7 +301,7 @@ mod tests { use tokio::net::TcpListener; use crate::{ - AccessToken, CommunicationProtocol, MessageVersion, S2EndpointDescription, S2NodeId, S2Role, + AccessToken, CommunicationProtocol, EndpointDescription, MessageVersion, NodeId, Role, common::wire::test::{UUID_A, UUID_B, basic_node_description}, communication::{ self, Client, ClientConfig, ClientPairing, ErrorKind, NodeConfig, PairingLookup, Server, ServerConfig, ServerPairing, @@ -366,8 +366,8 @@ mod tests { } struct TestPairing { - client: S2NodeId, - server: S2NodeId, + client: NodeId, + server: NodeId, tokens: Arc>>, url: String, } @@ -375,11 +375,11 @@ mod tests { impl ClientPairing for &TestPairing { type Error = Infallible; - fn client_id(&self) -> S2NodeId { + fn client_id(&self) -> NodeId { self.server } - fn server_id(&self) -> S2NodeId { + fn server_id(&self) -> NodeId { self.client } @@ -399,7 +399,7 @@ mod tests { async fn setup_server( store: S, - endpoint: Option, + endpoint: Option, overrides: Router<()>, ) -> (Handle, Server) { let rustls_config = RustlsConfig::from_pem( @@ -563,9 +563,9 @@ mod tests { let client = Client::new( ClientConfig { additional_certificates: vec![CertificateDer::from_pem_slice(include_bytes!("../../testdata/root.pem")).unwrap()], - endpoint_description: Some(S2EndpointDescription { + endpoint_description: Some(EndpointDescription { name: Some("a".into()), - logo_uri: Some("b".into()), + logo_url: Some("b".into()), deployment: None, }), }, @@ -589,9 +589,9 @@ mod tests { assert_eq!(server_connection.message_version, MessageVersion("v1".into())); assert_eq!( server_connection.remote_endpoint_description.unwrap(), - S2EndpointDescription { + EndpointDescription { name: Some("a".into()), - logo_uri: Some("b".into()), + logo_url: Some("b".into()), deployment: None, } ); @@ -614,9 +614,9 @@ mod tests { ); let (handle, mut server) = setup_server( store.clone(), - Some(S2EndpointDescription { + Some(EndpointDescription { name: Some("a".into()), - logo_uri: Some("b".into()), + logo_url: Some("b".into()), deployment: None, }), Router::new(), @@ -643,9 +643,9 @@ mod tests { assert_eq!(client_connection.message_version, MessageVersion("v1".into())); assert_eq!( client_connection.remote_endpoint_description.unwrap(), - S2EndpointDescription { + EndpointDescription { name: Some("a".into()), - logo_uri: Some("b".into()), + logo_url: Some("b".into()), deployment: None, } ); @@ -682,7 +682,7 @@ mod tests { }, Arc::new( NodeConfig::builder(vec![MessageVersion("v1".into())]) - .with_node_description(basic_node_description(UUID_A, S2Role::Rm)) + .with_node_description(basic_node_description(UUID_A, Role::Rm)) .build(), ), ); @@ -730,7 +730,7 @@ mod tests { }, Arc::new( NodeConfig::builder(vec![MessageVersion("v1".into())]) - .with_node_description(basic_node_description(UUID_B, S2Role::Cem)) + .with_node_description(basic_node_description(UUID_B, Role::Cem)) .build(), ), ); @@ -948,8 +948,8 @@ mod tests { ); struct NonPersistingPairing { - client: S2NodeId, - server: S2NodeId, + client: NodeId, + server: NodeId, tokens: Vec, url: String, } @@ -957,11 +957,11 @@ mod tests { impl ClientPairing for NonPersistingPairing { type Error = std::io::Error; - fn client_id(&self) -> S2NodeId { + fn client_id(&self) -> NodeId { self.server } - fn server_id(&self) -> S2NodeId { + fn server_id(&self) -> NodeId { self.client } diff --git a/s2energy-connection/src/communication/mod.rs b/s2energy-connection/src/communication/mod.rs index b481fd4..ad84fa5 100644 --- a/s2energy-connection/src/communication/mod.rs +++ b/s2energy-connection/src/communication/mod.rs @@ -16,16 +16,16 @@ //! up of communication, can be added through methods on the builder: //! ```rust //! # use s2energy_connection::communication::NodeConfig; -//! # use s2energy_connection::{MessageVersion, S2NodeDescription, S2NodeId, S2Role}; +//! # use s2energy_connection::{MessageVersion, NodeDescription, NodeId, Role}; //! let _config = NodeConfig::builder(vec![MessageVersion("v1".into())]) -//! .with_node_description(S2NodeDescription { -//! id: S2NodeId::try_from("67e55044-10b1-426f-9247-bb680e5fe0c8").unwrap(), +//! .with_node_description(NodeDescription { +//! id: NodeId::try_from("67e55044-10b1-426f-9247-bb680e5fe0c8").unwrap(), //! brand: String::from("super-reliable-corp"), -//! logo_uri: None, +//! logo_url: None, //! type_: String::from("fancy"), //! model_name: String::from("the best"), //! user_defined_name: None, -//! role: S2Role::Rm, +//! role: Role::Rm, //! }).build(); //! ``` //! @@ -44,10 +44,10 @@ //! # use std::sync::Arc; //! # use std::convert::Infallible; //! # use s2energy_connection::communication::{NodeConfig, Client, ClientConfig, ClientPairing}; -//! # use s2energy_connection::{MessageVersion, AccessToken, S2NodeId}; +//! # use s2energy_connection::{MessageVersion, AccessToken, NodeId}; //! struct MemoryClientPairing { -//! client_id: S2NodeId, -//! server_id: S2NodeId, +//! client_id: NodeId, +//! server_id: NodeId, //! communication_url: String, //! access_tokens: Vec, //! } @@ -55,11 +55,11 @@ //! impl ClientPairing for MemoryClientPairing { //! type Error = Infallible; //! -//! fn client_id(&self) -> S2NodeId { +//! fn client_id(&self) -> NodeId { //! self.client_id //! } //! -//! fn server_id(&self) -> S2NodeId { +//! fn server_id(&self) -> NodeId { //! self.server_id //! } //! @@ -80,8 +80,8 @@ //! let config = NodeConfig::builder(vec![MessageVersion("v1".into())]).build(); //! let client = Client::new(ClientConfig::default(), Arc::new(config)); //! let connection_result = client.connect(MemoryClientPairing { -//! client_id: S2NodeId::try_from("67e55044-10b1-426f-9247-bb680e5fe0c8").unwrap(), -//! server_id: S2NodeId::try_from("67e55044-10b1-426f-9247-bb680e5fe0c6").unwrap(), +//! client_id: NodeId::try_from("67e55044-10b1-426f-9247-bb680e5fe0c8").unwrap(), +//! server_id: NodeId::try_from("67e55044-10b1-426f-9247-bb680e5fe0c6").unwrap(), //! communication_url: "https://example.com".into(), //! access_tokens: vec![AccessToken("some-token-value".into())], //! }); @@ -205,7 +205,7 @@ //! //! A complete example of a communication client and communication server are present in the examples folder. These demonstrate also more completely //! how a simple server setup can be done using the [`axum-server`](https://docs.rs/axum-server/0.8.0/axum_server/) crate. -use crate::{MessageVersion, S2EndpointDescription, S2NodeDescription}; +use crate::{EndpointDescription, MessageVersion, NodeDescription}; mod client; mod error; @@ -221,13 +221,13 @@ pub use websocket::{WebSocketError, WebSocketTransport}; /// Full description of an S2 Node for communication. #[derive(Debug, Clone)] pub struct NodeConfig { - node_description: Option, + node_description: Option, supported_message_versions: Vec, } impl NodeConfig { /// Description of the S2 node. - pub fn node_description(&self) -> Option<&S2NodeDescription> { + pub fn node_description(&self) -> Option<&NodeDescription> { self.node_description.as_ref() } @@ -256,7 +256,7 @@ impl AsRef for NodeConfig { /// Builder for a [`NodeConfig`]. pub struct ConfigBuilder { - node_description: Option, + node_description: Option, supported_message_versions: Vec, } @@ -264,7 +264,7 @@ impl ConfigBuilder { /// Set the node description. /// /// Note that this replaces any previous node decriptions passed. - pub fn with_node_description(mut self, node_description: S2NodeDescription) -> Self { + pub fn with_node_description(mut self, node_description: NodeDescription) -> Self { self.node_description = Some(node_description); self } @@ -285,9 +285,9 @@ pub type CommunicationResult = Result; #[derive(Debug)] pub struct ConnectionInfo { /// New description of the remote node received during establishing of this connection. - pub remote_node_description: Option, + pub remote_node_description: Option, /// New description of the remote endpoint received during establishing of this connection. - pub remote_endpoint_description: Option, + pub remote_endpoint_description: Option, /// The version of the S2 Messages negotiated for this connection. pub message_version: MessageVersion, diff --git a/s2energy-connection/src/communication/server.rs b/s2energy-connection/src/communication/server.rs index f278774..4fd23d1 100644 --- a/s2energy-connection/src/communication/server.rs +++ b/s2energy-connection/src/communication/server.rs @@ -15,7 +15,7 @@ use tokio::time::Instant; use tracing::{Instrument, info, trace}; use crate::{ - CommunicationProtocol, MessageVersion, S2EndpointDescription, S2NodeDescription, S2NodeId, + CommunicationProtocol, EndpointDescription, MessageVersion, NodeDescription, NodeId, common::{AbortingJoinHandle, root, websocket_extractor::WebSocketUpgrade, wire::AccessToken}, communication::{ ConnectionInfo, NodeConfig, WebSocketTransport, @@ -36,9 +36,9 @@ const BUFFER_SIZE: usize = 1; /// A pairing to be looked up. pub struct PairingLookup { /// Identifier of the remote end of the pairing. - pub client: S2NodeId, + pub client: NodeId, /// Identifier of the local end of the pairing. - pub server: S2NodeId, + pub server: NodeId, } /// Result of looking up a pairing. @@ -90,7 +90,7 @@ pub struct ServerConfig { /// URL at which the communication server is reachable. pub base_url: String, /// Updated description of this endpoint to send during communication requests. - pub endpoint_description: Option, + pub endpoint_description: Option, } /// Server for handling the S2 Communication establishment subprotocol. @@ -106,7 +106,7 @@ struct AppStateInner { pending_tokens: Mutex>>, pending_websockets: Mutex>>, base_url: String, - endpoint_description: Option, + endpoint_description: Option, connection_sender: tokio::sync::mpsc::Sender<(PairingLookup, ConnectionInfo)>, cleanup_task: OnceLock>, } @@ -131,16 +131,16 @@ struct Session { span: tracing::Span, lookup: PairingLookup, token: AccessToken, - node_description: Option, - endpoint_description: Option, + node_description: Option, + endpoint_description: Option, message_version: MessageVersion, communication_protocol: CommunicationProtocol, } struct PendingWebsocket { lookup: PairingLookup, - node_description: Option, - endpoint_description: Option, + node_description: Option, + endpoint_description: Option, message_version: MessageVersion, } diff --git a/s2energy-connection/src/communication/wire.rs b/s2energy-connection/src/communication/wire.rs index 25ba3c8..bd947ac 100644 --- a/s2energy-connection/src/communication/wire.rs +++ b/s2energy-connection/src/communication/wire.rs @@ -6,9 +6,10 @@ use subtle::ConstantTimeEq; use thiserror::Error; use tracing::info; -use crate::{CommunicationProtocol, MessageVersion, S2EndpointDescription, S2NodeDescription, S2NodeId, common::wire::AccessToken}; +use crate::{CommunicationProtocol, EndpointDescription, MessageVersion, NodeDescription, NodeId, common::wire::AccessToken}; #[derive(Serialize, Deserialize, Clone, PartialEq, Eq, Hash)] +#[serde(tag = "communicationProtocol")] pub(crate) enum CommunicationDetails { WebSocket(WebSocketCommunicationDetails), } @@ -20,6 +21,7 @@ pub(crate) struct WebSocketCommunicationDetails { } #[derive(Serialize, Deserialize, Debug, Error, Clone, PartialEq, Eq, Hash)] +#[serde(tag = "errorMessage")] pub(crate) enum CommunicationDetailsErrorMessage { #[error("Incompatible S2 message versions")] IncompatibleS2MessageVersions, @@ -35,18 +37,18 @@ pub(crate) enum CommunicationDetailsErrorMessage { #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Hash)] pub(crate) struct InitiateConnectionRequest { - #[serde(rename = "clientS2NodeId")] - pub(crate) client_node_id: S2NodeId, - #[serde(rename = "serverS2NodeId")] - pub(crate) server_node_id: S2NodeId, + #[serde(rename = "clientNodeId")] + pub(crate) client_node_id: NodeId, + #[serde(rename = "serverNodeId")] + pub(crate) server_node_id: NodeId, #[serde(rename = "supportedS2MessageVersions")] pub(crate) supported_message_versions: Vec, #[serde(rename = "supportedCommunicationProtocols")] pub(crate) supported_communication_protocols: Vec, - #[serde(rename = "clientS2NodeDescription")] - pub(crate) node_description: Option, - #[serde(rename = "clientS2EndpointDescription")] - pub(crate) endpoint_description: Option, + #[serde(rename = "clientNodeDescription")] + pub(crate) node_description: Option, + #[serde(rename = "clientEndpointDescription")] + pub(crate) endpoint_description: Option, } #[derive(Serialize, Deserialize, Clone, PartialEq, Eq, Hash)] @@ -57,18 +59,18 @@ pub(crate) struct InitiateConnectionResponse { pub(crate) message_version: MessageVersion, #[serde(rename = "accessToken")] pub(crate) access_token: AccessToken, - #[serde(rename = "serverS2NodeDescription")] - pub(crate) node_description: Option, - #[serde(rename = "serverS2EndpointDescription")] - pub(crate) endpoint_description: Option, + #[serde(rename = "serverNodeDescription")] + pub(crate) node_description: Option, + #[serde(rename = "serverEndpointDescription")] + pub(crate) endpoint_description: Option, } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Hash)] pub(crate) struct UnpairRequest { - #[serde(rename = "clientS2NodeId")] - pub(crate) client_node_id: S2NodeId, - #[serde(rename = "serverS2NodeId")] - pub(crate) server_node_id: S2NodeId, + #[serde(rename = "clientNodeId")] + pub(crate) client_node_id: NodeId, + #[serde(rename = "serverNodeId")] + pub(crate) server_node_id: NodeId, } /// One-time access token for secure access to the S2 message communication channel. It must be renewed every time a client wants to access diff --git a/s2energy-connection/src/discovery/mod.rs b/s2energy-connection/src/discovery/mod.rs index 8d4c816..4a57a4b 100644 --- a/s2energy-connection/src/discovery/mod.rs +++ b/s2energy-connection/src/discovery/mod.rs @@ -24,7 +24,7 @@ use zeroconf_tokio::{ }; use crate::{ - Deployment, S2Role, + Deployment, Role, discovery::error::{Error, ErrorKind}, }; @@ -44,7 +44,7 @@ pub struct DiscoverableS2Endpoint { deployment: Deployment, pairing_url: Option, longpolling_url: Option, - roles: Vec, + roles: Vec, } impl DiscoverableS2Endpoint { @@ -74,7 +74,7 @@ impl DiscoverableS2Endpoint { } /// Build a new [`DiscoverableS2Endpoint`] with support for pairing. - pub fn build_with_pairing(roles: Vec, pairing_url: String) -> Result { + pub fn build_with_pairing(roles: Vec, pairing_url: String) -> Result { let parsed_url: Url = pairing_url.parse().map_err(|_| BuilderError::InvalidUrl)?; let host = parsed_url.host().ok_or(BuilderError::InvalidUrl)?; let deployment = Deployment::try_from(host).map_err(|_| BuilderError::InvalidUrl)?; @@ -90,7 +90,7 @@ impl DiscoverableS2Endpoint { } /// Build a new [`DiscoverableS2Endpoint`] with support for longpolling. - pub fn build_with_longpolling(roles: Vec, longpolling_url: String) -> Result { + pub fn build_with_longpolling(roles: Vec, longpolling_url: String) -> Result { let parsed_url: Url = longpolling_url.parse().map_err(|_| BuilderError::InvalidUrl)?; let host = parsed_url.host().ok_or(BuilderError::InvalidUrl)?; let deployment = Deployment::try_from(host).map_err(|_| BuilderError::InvalidUrl)?; @@ -121,8 +121,8 @@ impl DiscoverableS2Endpoint { .sub_types() .iter() .filter_map(|v| match v.as_str() { - "cem" => Some(S2Role::Cem), - "rm" => Some(S2Role::Rm), + "cem" => Some(Role::Cem), + "rm" => Some(Role::Rm), _ => None, }) .collect::>(); @@ -183,7 +183,7 @@ pub struct DiscoverableS2EndpointBuilder { deployment: Deployment, pairing_url: Option, longpolling_url: Option, - roles: Vec, + roles: Vec, } impl DiscoverableS2EndpointBuilder { @@ -320,7 +320,7 @@ pub enum DiscoveryEvent { impl S2Discoverer { /// Create a new discovery client for endpoints providing the given role. - pub async fn new(role: S2Role) -> Result { + pub async fn new(role: Role) -> Result { // The unwrap on service type is fine as its arguments are always valid. let mut browser = MdnsBrowserAsync::new(MdnsBrowser::new( ServiceType::with_sub_types("s2connect", "tcp", vec![role.service_subtype()]).unwrap(), diff --git a/s2energy-connection/src/lib.rs b/s2energy-connection/src/lib.rs index 5fb91e7..b38c993 100644 --- a/s2energy-connection/src/lib.rs +++ b/s2energy-connection/src/lib.rs @@ -16,6 +16,5 @@ pub mod discovery; pub mod pairing; pub use common::wire::{ - AccessToken, CommunicationProtocol, Deployment, InvalidNodeId, MessageVersion, S2EndpointDescription, S2NodeDescription, S2NodeId, - S2Role, + AccessToken, CommunicationProtocol, Deployment, EndpointDescription, InvalidNodeId, MessageVersion, NodeDescription, NodeId, Role, }; diff --git a/s2energy-connection/src/pairing/client.rs b/s2energy-connection/src/pairing/client.rs index f329c95..b05999f 100644 --- a/s2energy-connection/src/pairing/client.rs +++ b/s2energy-connection/src/pairing/client.rs @@ -5,10 +5,10 @@ use rustls::pki_types::CertificateDer; use tracing::{Instrument, Span, debug, span, trace}; use crate::common::negotiate_version; -use crate::common::wire::{AccessToken, Deployment, PairingVersion, S2Role}; +use crate::common::wire::{AccessToken, Deployment, PairingVersion, Role}; use crate::pairing::transport::{HashProvider, hash_providing_https_client}; use crate::pairing::{ConfigError, Error, Pairing, PairingRole}; -use crate::{S2EndpointDescription, S2NodeDescription, S2NodeId}; +use crate::{EndpointDescription, NodeDescription, NodeId}; use super::NodeConfig; use super::wire::*; @@ -20,7 +20,7 @@ pub struct PairingRemote { /// URL at which the remote node can be reached pub url: String, /// S2 node id of the remote node. - pub id: Option, + pub id: Option, } /// Remote node to pair with. @@ -29,7 +29,7 @@ pub struct PrePairingRemote { /// URL at which the remote node can be reached pub url: String, /// S2 node id of the remote node. - pub id: S2NodeId, + pub id: NodeId, } /// Configuration for pairing clients. @@ -39,7 +39,7 @@ pub struct ClientConfig { /// When the remote is on the LAN, this is not used. pub additional_certificates: Vec>, /// Description of our endpoint. - pub endpoint_description: S2EndpointDescription, + pub endpoint_description: EndpointDescription, /// Where the pairing is deployed. pub pairing_deployment: Deployment, } @@ -48,7 +48,7 @@ pub struct ClientConfig { /// /// Used as the client end of a pairing interaction. pub struct Client { - endpoint_description: S2EndpointDescription, + endpoint_description: EndpointDescription, additional_certificates: Vec>, pairing_deployment: Deployment, } @@ -56,7 +56,7 @@ pub struct Client { /// A currently active pre-pairing session with a remote. pub struct PrePairing<'a> { span: tracing::Span, - remote_id: S2NodeId, + remote_id: NodeId, session: V1Session<'a>, local_deployment: Deployment, certhash: Option, @@ -88,7 +88,7 @@ impl PrePairing<'_> { /// When the callback returns an error, the client will be notified of the error. pub async fn pair( self, - remote_id: Option, + remote_id: Option, pairing_token: &[u8], callback: impl AsyncFnOnce(Pairing) -> Result<(), E>, ) -> PairingResult<()> { @@ -110,7 +110,7 @@ pub struct Longpoller(Arc); struct LongpollerInner { span: Span, nodes: std::sync::Mutex>, - endpoint_description: S2EndpointDescription, + endpoint_description: EndpointDescription, // Client is held by the runner longterm, hence we use a tokio mutex. client: tokio::sync::Mutex, base_url: Url, @@ -121,11 +121,11 @@ pub trait LongpollHandler { /// Remote requests pairing /// /// Return value indicates whether we are able to start pairing with the remote. - fn request_pairing(&mut self, node: S2NodeId) -> impl Future + Send; + fn request_pairing(&mut self, node: NodeId) -> impl Future + Send; /// Remote requests us to prepare for pairing. - fn prepare_pairing(&mut self, node: S2NodeId) -> impl Future + Send; + fn prepare_pairing(&mut self, node: NodeId) -> impl Future + Send; /// Remote cancels a previous request to prepare for pairing. - fn cancel_prepare_pairing(&mut self, node: S2NodeId) -> impl Future + Send; + fn cancel_prepare_pairing(&mut self, node: NodeId) -> impl Future + Send; } impl Longpoller { @@ -141,8 +141,8 @@ impl Longpoller { #[derive(Clone, Copy, PartialEq, Eq)] enum Action { None, - ProvideDescription(S2NodeId), - ReturnError(S2NodeId, WaitForPairingErrorMessage), + ProvideDescription(NodeId), + ReturnError(NodeId, WaitForPairingErrorMessage), } let mut action = Action::None; @@ -155,21 +155,21 @@ impl Longpoller { .iter() .map(|node| match action { Action::ProvideDescription(id) if id == node.node_description.id => WaitForPairingRequest { - client_s2_node_id: node.node_description.id, - client_s2_node_description: Some(node.node_description.clone()), - client_s2_endpoint_description: Some(self.0.endpoint_description.clone()), + client_node_id: node.node_description.id, + clien_node_description: Some(node.node_description.clone()), + client_endpoint_description: Some(self.0.endpoint_description.clone()), error_message: None, }, Action::ReturnError(id, error_message) if id == node.node_description.id => WaitForPairingRequest { - client_s2_node_id: node.node_description.id, - client_s2_node_description: None, - client_s2_endpoint_description: None, + client_node_id: node.node_description.id, + clien_node_description: None, + client_endpoint_description: None, error_message: Some(error_message), }, _ => WaitForPairingRequest { - client_s2_node_id: node.node_description.id, - client_s2_node_description: None, - client_s2_endpoint_description: None, + client_node_id: node.node_description.id, + clien_node_description: None, + client_endpoint_description: None, error_message: None, }, }) @@ -199,13 +199,12 @@ impl Longpoller { let response: WaitForPairingResponse = response.json().await.map_err(|e| Error::new(ErrorKind::ProtocolError, e))?; match response.action { - WaitForPairingAction::SendS2NodeDescription => action = Action::ProvideDescription(response.client_s2_node_id), - WaitForPairingAction::PreparePairing => handler.prepare_pairing(response.client_s2_node_id).await, - WaitForPairingAction::CancelPreparePairing => handler.cancel_prepare_pairing(response.client_s2_node_id).await, + WaitForPairingAction::SendNodeDescription => action = Action::ProvideDescription(response.client_node_id), + WaitForPairingAction::PreparePairing => handler.prepare_pairing(response.client_node_id).await, + WaitForPairingAction::CancelPreparePairing => handler.cancel_prepare_pairing(response.client_node_id).await, WaitForPairingAction::RequestPairing => { - if !handler.request_pairing(response.client_s2_node_id).await { - action = - Action::ReturnError(response.client_s2_node_id, WaitForPairingErrorMessage::NoValidTokenOnPairingClient) + if !handler.request_pairing(response.client_node_id).await { + action = Action::ReturnError(response.client_node_id, WaitForPairingErrorMessage::NoValidTokenOnPairingClient) } } } @@ -226,7 +225,7 @@ impl Longpoller { } /// Stop longpolling for the local node with the given id. - pub fn remove_node(&self, id: S2NodeId) { + pub fn remove_node(&self, id: NodeId) { self.0.nodes.lock().unwrap().retain(|node| node.node_description.id != id); } } @@ -243,7 +242,7 @@ impl Client { /// Get information about a specific endpoint and its nodes #[tracing::instrument(skip_all, fields(remote = ?remote), level = tracing::Level::ERROR)] - pub async fn get_endpoint_descriptors(&self, remote: String) -> PairingResult<(S2EndpointDescription, Vec)> { + pub async fn get_endpoint_descriptors(&self, remote: String) -> PairingResult<(EndpointDescription, Vec)> { trace!("Querying remote for descriptors"); let url = Url::try_from(remote.as_str()).map_err(|e| Error::new(ErrorKind::InvalidUrl, e))?; @@ -259,7 +258,7 @@ impl Client { let base_url = url.join("v1/").unwrap(); let endpoint_response = client - .get(base_url.join("s2endpoint").unwrap()) + .get(base_url.join("endpoint").unwrap()) .send() .await .map_err(|e| Error::new(ErrorKind::TransportFailed, e))?; @@ -271,13 +270,13 @@ impl Client { return Err(ErrorKind::ProtocolError.into()); } - let endpoint: S2EndpointDescription = endpoint_response + let endpoint: EndpointDescription = endpoint_response .json() .await .map_err(|e| Error::new(ErrorKind::ProtocolError, e))?; let node_response = client - .get(base_url.join("s2nodes").unwrap()) + .get(base_url.join("nodes").unwrap()) .send() .await .map_err(|e| Error::new(ErrorKind::TransportFailed, e))?; @@ -289,7 +288,7 @@ impl Client { return Err(ErrorKind::ProtocolError.into()); } - let nodes: Vec = node_response.json().await.map_err(|e| Error::new(ErrorKind::ProtocolError, e))?; + let nodes: Vec = node_response.json().await.map_err(|e| Error::new(ErrorKind::ProtocolError, e))?; Ok((endpoint, nodes)) } @@ -415,13 +414,13 @@ impl Client { struct V1Session<'a> { client: reqwest::Client, - endpoint_description: S2EndpointDescription, + endpoint_description: EndpointDescription, base_url: Url, config: &'a NodeConfig, } impl<'a> V1Session<'a> { - fn new(client: reqwest::Client, url: Url, config: &'a NodeConfig, endpoint_description: S2EndpointDescription) -> Self { + fn new(client: reqwest::Client, url: Url, config: &'a NodeConfig, endpoint_description: EndpointDescription) -> Self { V1Session { client, endpoint_description, @@ -434,15 +433,15 @@ impl<'a> V1Session<'a> { self, certhash: Option, local_deployment: Deployment, - id: S2NodeId, + id: NodeId, span: Span, ) -> PairingResult> { let response = self .client .post(self.base_url.join("preparePairing").unwrap()) .json(&PrePairingRequest { - client_s2_endpoint_description: self.endpoint_description.clone(), - client_s2_node_description: self.config.node_description.clone(), + client_endpoint_description: self.endpoint_description.clone(), + client_node_description: self.config.node_description.clone(), server_id: Some(id), }) .send() @@ -470,7 +469,7 @@ impl<'a> V1Session<'a> { self, certhash: Option, local_deployment: Deployment, - id: Option, + id: Option, pairing_token: &[u8], callback: impl AsyncFnOnce(Pairing) -> Result<(), E>, ) -> PairingResult<()> { @@ -497,10 +496,10 @@ impl<'a> V1Session<'a> { let request_pairing_response = self.request_pairing(id, &client_hmac_challenge).await?; let attempt_id = request_pairing_response.pairing_attempt_id; let remote_deployment = request_pairing_response - .server_s2_endpoint_description + .server_endpoint_description .deployment .unwrap_or_else(|| network.as_deployment()); - let remote_role = request_pairing_response.server_s2_node_description.role; + let remote_role = request_pairing_response.server_node_description.role; trace!("Requested pairing from remote."); @@ -530,16 +529,16 @@ impl<'a> V1Session<'a> { } let role = match (our_deployment, our_role, remote_deployment, remote_role) { - (_, S2Role::Rm, _, S2Role::Rm) | (_, S2Role::Cem, _, S2Role::Cem) => { + (_, Role::Rm, _, Role::Rm) | (_, Role::Cem, _, Role::Cem) => { let _ = self.finalize(&attempt_id, false).await; return Err(ErrorKind::RemoteOfSameType.into()); } (Deployment::Lan, _, Deployment::Wan, _) => CommunicationRole::CommunicationClient, // unwrap is okay here, as Deployment::Wan or S2Role::Cem locally means we will ALWAYS have a connection initiate url. - (Deployment::Wan, _, Deployment::Lan, _) | (_, S2Role::Cem, _, S2Role::Rm) => CommunicationRole::CommunicationServer { + (Deployment::Wan, _, Deployment::Lan, _) | (_, Role::Cem, _, Role::Rm) => CommunicationRole::CommunicationServer { initiate_connection_url: self.config.connection_initiate_url.as_ref().unwrap().into(), }, - (_, S2Role::Rm, _, S2Role::Cem) => CommunicationRole::CommunicationClient, + (_, Role::Rm, _, Role::Cem) => CommunicationRole::CommunicationClient, }; trace!("Determined communication role."); @@ -560,8 +559,8 @@ impl<'a> V1Session<'a> { return Err(e); } Pairing { - remote_endpoint_description: request_pairing_response.server_s2_endpoint_description, - remote_node_description: request_pairing_response.server_s2_node_description, + remote_endpoint_description: request_pairing_response.server_endpoint_description, + remote_node_description: request_pairing_response.server_node_description, token: access_token, role: PairingRole::CommunicationServer, } @@ -575,8 +574,8 @@ impl<'a> V1Session<'a> { } }; Pairing { - remote_endpoint_description: request_pairing_response.server_s2_endpoint_description, - remote_node_description: request_pairing_response.server_s2_node_description, + remote_endpoint_description: request_pairing_response.server_endpoint_description, + remote_node_description: request_pairing_response.server_node_description, token: connection_details.access_token, role: PairingRole::CommunicationClient { initiate_url: connection_details.initiate_connection_url, @@ -671,7 +670,7 @@ impl<'a> V1Session<'a> { async fn request_pairing( &self, - id: Option, + id: Option, client_hmac_challenge: &HmacChallenge, ) -> PairingResult { let request = RequestPairing { @@ -714,7 +713,7 @@ impl<'a> V1Session<'a> { .client .post(self.base_url.join("finalizePairing").unwrap()) .bearer_auth(&attempt_id.0) - .json(&success) + .json(&FinalizePairingRequest { success }) .send() .await .map_err(|e| Error::new(ErrorKind::TransportFailed, e))?; @@ -735,14 +734,15 @@ mod tests { }; use crate::{ - Deployment, MessageVersion, S2EndpointDescription, S2NodeDescription, S2NodeId, S2Role, + Deployment, EndpointDescription, MessageVersion, NodeDescription, NodeId, Role, common::wire::test::{UUID_A, UUID_B, basic_node_description, pairing_s2_node_id}, pairing::{ Client, ClientConfig, ErrorKind, LongpollHandler, Longpoller, Network, NodeConfig, NoopPrePairingHandler, Pairing, PairingRemote, PairingRole, PairingToken, PrePairingHandler, PrePairingResponse, Server, ServerConfig, client::PrePairingRemote, wire::{ - HmacChallenge, HmacChallengeResponse, PairingAttemptId, PairingResponseErrorMessage, RequestPairing, RequestPairingResponse, + FinalizePairingRequest, HmacChallenge, HmacChallengeResponse, PairingAttemptId, PairingResponseErrorMessage, + RequestPairing, RequestPairingResponse, }, }, }; @@ -764,7 +764,7 @@ mod tests { let mut server = Server::new_with_prepairing( ServerConfig { leaf_certificate: None, - endpoint_description: S2EndpointDescription::default(), + endpoint_description: EndpointDescription::default(), advertised_nodes: vec![], }, handler, @@ -815,7 +815,7 @@ mod tests { #[tokio::test] async fn descriptors() { - let server_config = NodeConfig::builder(basic_node_description(UUID_A, S2Role::Cem), vec![MessageVersion("v1".into())]) + let server_config = NodeConfig::builder(basic_node_description(UUID_A, Role::Cem), vec![MessageVersion("v1".into())]) .with_connection_initiate_url("test.example.com".into()) .build() .unwrap(); @@ -823,13 +823,13 @@ mod tests { let (server_handle, _server_pairing, _) = setup_server( server_config, Router::new() - .route("/v1/s2endpoint", get(|| async { Json(S2EndpointDescription::default()) })) + .route("/v1/endpoint", get(|| async { Json(EndpointDescription::default()) })) .route( - "/v1/s2nodes", + "/v1/nodes", get(|| async { Json(vec![ - basic_node_description(UUID_A, S2Role::Cem), - basic_node_description(UUID_B, S2Role::Rm), + basic_node_description(UUID_A, Role::Cem), + basic_node_description(UUID_B, Role::Rm), ]) }), ), @@ -840,7 +840,7 @@ mod tests { let client = Client::new(ClientConfig { additional_certificates: vec![CertificateDer::from_pem_slice(include_bytes!("../../testdata/root.pem")).unwrap()], - endpoint_description: S2EndpointDescription::default(), + endpoint_description: EndpointDescription::default(), pairing_deployment: Deployment::Wan, }) .unwrap(); @@ -856,7 +856,7 @@ mod tests { #[tokio::test] async fn descriptors_forbidden() { - let server_config = NodeConfig::builder(basic_node_description(UUID_A, S2Role::Cem), vec![MessageVersion("v1".into())]) + let server_config = NodeConfig::builder(basic_node_description(UUID_A, Role::Cem), vec![MessageVersion("v1".into())]) .with_connection_initiate_url("test.example.com".into()) .build() .unwrap(); @@ -864,8 +864,8 @@ mod tests { let (server_handle, _server_pairing, _) = setup_server( server_config, Router::new() - .route("/v1/s2endpoint", get(|| async { StatusCode::UNAUTHORIZED })) - .route("/v1/s2nodes", get(|| async { StatusCode::UNAUTHORIZED })), + .route("/v1/endpoint", get(|| async { StatusCode::UNAUTHORIZED })) + .route("/v1/nodes", get(|| async { StatusCode::UNAUTHORIZED })), ) .await; @@ -873,7 +873,7 @@ mod tests { let client = Client::new(ClientConfig { additional_certificates: vec![CertificateDer::from_pem_slice(include_bytes!("../../testdata/root.pem")).unwrap()], - endpoint_description: S2EndpointDescription::default(), + endpoint_description: EndpointDescription::default(), pairing_deployment: Deployment::Wan, }) .unwrap(); @@ -887,12 +887,12 @@ mod tests { #[tokio::test] async fn pairing_ok_rm_initiates() { - let server_config = NodeConfig::builder(basic_node_description(UUID_A, S2Role::Cem), vec![MessageVersion("v1".into())]) + let server_config = NodeConfig::builder(basic_node_description(UUID_A, Role::Cem), vec![MessageVersion("v1".into())]) .with_connection_initiate_url("test.example.com".into()) .build() .unwrap(); - let client_config = NodeConfig::builder(basic_node_description(UUID_B, S2Role::Rm), vec![MessageVersion("v1".into())]) + let client_config = NodeConfig::builder(basic_node_description(UUID_B, Role::Rm), vec![MessageVersion("v1".into())]) .with_connection_initiate_url("client.example.com".into()) .build() .unwrap(); @@ -907,7 +907,7 @@ mod tests { let client = Client::new(ClientConfig { additional_certificates: vec![CertificateDer::from_pem_slice(include_bytes!("../../testdata/root.pem")).unwrap()], - endpoint_description: S2EndpointDescription::default(), + endpoint_description: EndpointDescription::default(), pairing_deployment: Deployment::Wan, }) .unwrap(); @@ -931,12 +931,12 @@ mod tests { #[tokio::test] async fn pairing_ok_cem_initiates() { - let server_config = NodeConfig::builder(basic_node_description(UUID_A, S2Role::Rm), vec![MessageVersion("v1".into())]) + let server_config = NodeConfig::builder(basic_node_description(UUID_A, Role::Rm), vec![MessageVersion("v1".into())]) .with_connection_initiate_url("test.example.com".into()) .build() .unwrap(); - let client_config = NodeConfig::builder(basic_node_description(UUID_B, S2Role::Cem), vec![MessageVersion("v1".into())]) + let client_config = NodeConfig::builder(basic_node_description(UUID_B, Role::Cem), vec![MessageVersion("v1".into())]) .with_connection_initiate_url("client.example.com".into()) .build() .unwrap(); @@ -951,7 +951,7 @@ mod tests { let client = Client::new(ClientConfig { additional_certificates: vec![CertificateDer::from_pem_slice(include_bytes!("../../testdata/root.pem")).unwrap()], - endpoint_description: S2EndpointDescription::default(), + endpoint_description: EndpointDescription::default(), pairing_deployment: Deployment::Wan, }) .unwrap(); @@ -975,10 +975,10 @@ mod tests { #[derive(Debug, Clone)] struct TestPrePairingHandler { - endpoint: Arc>>, - node: Arc>>, - client_id: Arc>>, - target_node: Arc>>>, + endpoint: Arc>>, + node: Arc>>, + client_id: Arc>>, + target_node: Arc>>>, response: PrePairingResponse, } @@ -997,9 +997,9 @@ mod tests { impl PrePairingHandler for TestPrePairingHandler { fn prepairing_requested( &self, - endpoint: S2EndpointDescription, - node: S2NodeDescription, - target_node: Option, + endpoint: EndpointDescription, + node: NodeDescription, + target_node: Option, ) -> PrePairingResponse { *self.endpoint.lock().unwrap() = Some(endpoint); *self.node.lock().unwrap() = Some(node); @@ -1007,7 +1007,7 @@ mod tests { self.response } - fn prepairing_cancelled(&self, id: crate::S2NodeId, target_node: Option) { + fn prepairing_cancelled(&self, id: crate::NodeId, target_node: Option) { *self.client_id.lock().unwrap() = Some(id); *self.target_node.lock().unwrap() = Some(target_node); } @@ -1015,12 +1015,12 @@ mod tests { #[tokio::test] async fn prepairing_then_pair() { - let server_config = NodeConfig::builder(basic_node_description(UUID_A, S2Role::Rm), vec![MessageVersion("v1".into())]) + let server_config = NodeConfig::builder(basic_node_description(UUID_A, Role::Rm), vec![MessageVersion("v1".into())]) .with_connection_initiate_url("test.example.com".into()) .build() .unwrap(); - let client_config = NodeConfig::builder(basic_node_description(UUID_B, S2Role::Cem), vec![MessageVersion("v1".into())]) + let client_config = NodeConfig::builder(basic_node_description(UUID_B, Role::Cem), vec![MessageVersion("v1".into())]) .with_connection_initiate_url("client.example.com".into()) .build() .unwrap(); @@ -1036,7 +1036,7 @@ mod tests { let client = Client::new(ClientConfig { additional_certificates: vec![CertificateDer::from_pem_slice(include_bytes!("../../testdata/root.pem")).unwrap()], - endpoint_description: S2EndpointDescription::default(), + endpoint_description: EndpointDescription::default(), pairing_deployment: Deployment::Wan, }) .unwrap(); @@ -1068,12 +1068,12 @@ mod tests { #[tokio::test] async fn prepairing_then_cancel() { - let server_config = NodeConfig::builder(basic_node_description(UUID_A, S2Role::Rm), vec![MessageVersion("v1".into())]) + let server_config = NodeConfig::builder(basic_node_description(UUID_A, Role::Rm), vec![MessageVersion("v1".into())]) .with_connection_initiate_url("test.example.com".into()) .build() .unwrap(); - let client_config = NodeConfig::builder(basic_node_description(UUID_B, S2Role::Cem), vec![MessageVersion("v1".into())]) + let client_config = NodeConfig::builder(basic_node_description(UUID_B, Role::Cem), vec![MessageVersion("v1".into())]) .with_connection_initiate_url("client.example.com".into()) .build() .unwrap(); @@ -1089,7 +1089,7 @@ mod tests { let client = Client::new(ClientConfig { additional_certificates: vec![CertificateDer::from_pem_slice(include_bytes!("../../testdata/root.pem")).unwrap()], - endpoint_description: S2EndpointDescription::default(), + endpoint_description: EndpointDescription::default(), pairing_deployment: Deployment::Wan, }) .unwrap(); @@ -1115,12 +1115,12 @@ mod tests { #[tokio::test] async fn prepairing_rejected() { - let server_config = NodeConfig::builder(basic_node_description(UUID_A, S2Role::Rm), vec![MessageVersion("v1".into())]) + let server_config = NodeConfig::builder(basic_node_description(UUID_A, Role::Rm), vec![MessageVersion("v1".into())]) .with_connection_initiate_url("test.example.com".into()) .build() .unwrap(); - let client_config = NodeConfig::builder(basic_node_description(UUID_B, S2Role::Cem), vec![MessageVersion("v1".into())]) + let client_config = NodeConfig::builder(basic_node_description(UUID_B, Role::Cem), vec![MessageVersion("v1".into())]) .with_connection_initiate_url("client.example.com".into()) .build() .unwrap(); @@ -1136,7 +1136,7 @@ mod tests { let client = Client::new(ClientConfig { additional_certificates: vec![CertificateDer::from_pem_slice(include_bytes!("../../testdata/root.pem")).unwrap()], - endpoint_description: S2EndpointDescription::default(), + endpoint_description: EndpointDescription::default(), pairing_deployment: Deployment::Wan, }) .unwrap(); @@ -1150,12 +1150,12 @@ mod tests { #[tokio::test] async fn pairing_rejects_invalid_hmac() { - let server_config = NodeConfig::builder(basic_node_description(UUID_A, S2Role::Cem), vec![MessageVersion("v1".into())]) + let server_config = NodeConfig::builder(basic_node_description(UUID_A, Role::Cem), vec![MessageVersion("v1".into())]) .with_connection_initiate_url("test.example.com".into()) .build() .unwrap(); - let client_config = NodeConfig::builder(basic_node_description(UUID_B, S2Role::Rm), vec![MessageVersion("v1".into())]) + let client_config = NodeConfig::builder(basic_node_description(UUID_B, Role::Rm), vec![MessageVersion("v1".into())]) .with_connection_initiate_url("client.example.com".into()) .build() .unwrap(); @@ -1170,8 +1170,8 @@ mod tests { post(|| async { Json(RequestPairingResponse { pairing_attempt_id: PairingAttemptId("testid".into()), - server_s2_node_description: basic_node_description(UUID_A, S2Role::Cem), - server_s2_endpoint_description: S2EndpointDescription::default(), + server_node_description: basic_node_description(UUID_A, Role::Cem), + server_endpoint_description: EndpointDescription::default(), selected_hmac_hashing_algorithm: crate::pairing::wire::HmacHashingAlgorithm::Sha256, client_hmac_challenge_response: HmacChallengeResponse(vec![0; 64]), server_hmac_challenge: HmacChallenge::new(&mut rand::rng(), 32), @@ -1180,10 +1180,12 @@ mod tests { ) .route( "/v1/finalizePairing", - post(|attempt_id: PairingAttemptId, Json(success): Json| async move { - assert_eq!(attempt_id.0, "testid"); - *finalize_result_clone.lock().unwrap() = Some(success); - }), + post( + |attempt_id: PairingAttemptId, Json(FinalizePairingRequest { success })| async move { + assert_eq!(attempt_id.0, "testid"); + *finalize_result_clone.lock().unwrap() = Some(success); + }, + ), ), ) .await; @@ -1196,7 +1198,7 @@ mod tests { let client = Client::new(ClientConfig { additional_certificates: vec![CertificateDer::from_pem_slice(include_bytes!("../../testdata/root.pem")).unwrap()], - endpoint_description: S2EndpointDescription::default(), + endpoint_description: EndpointDescription::default(), pairing_deployment: Deployment::Wan, }) .unwrap(); @@ -1215,12 +1217,12 @@ mod tests { #[tokio::test] async fn pairing_rejects_same_role() { - let server_config = NodeConfig::builder(basic_node_description(UUID_A, S2Role::Rm), vec![MessageVersion("v1".into())]) + let server_config = NodeConfig::builder(basic_node_description(UUID_A, Role::Rm), vec![MessageVersion("v1".into())]) .with_connection_initiate_url("test.example.com".into()) .build() .unwrap(); - let client_config = NodeConfig::builder(basic_node_description(UUID_B, S2Role::Rm), vec![MessageVersion("v1".into())]) + let client_config = NodeConfig::builder(basic_node_description(UUID_B, Role::Rm), vec![MessageVersion("v1".into())]) .with_connection_initiate_url("client.example.com".into()) .build() .unwrap(); @@ -1235,8 +1237,8 @@ mod tests { post(|Json(request): Json| async move { Json(RequestPairingResponse { pairing_attempt_id: PairingAttemptId("testid".into()), - server_s2_node_description: basic_node_description(UUID_A, S2Role::Rm), - server_s2_endpoint_description: S2EndpointDescription::default(), + server_node_description: basic_node_description(UUID_A, Role::Rm), + server_endpoint_description: EndpointDescription::default(), selected_hmac_hashing_algorithm: crate::pairing::wire::HmacHashingAlgorithm::Sha256, client_hmac_challenge_response: request.client_hmac_challenge.sha256(&Network::Wan, b"testtoken"), server_hmac_challenge: HmacChallenge::new(&mut rand::rng(), 32), @@ -1245,10 +1247,12 @@ mod tests { ) .route( "/v1/finalizePairing", - post(|attempt_id: PairingAttemptId, Json(success): Json| async move { - assert_eq!(attempt_id.0, "testid"); - *finalize_result_clone.lock().unwrap() = Some(success); - }), + post( + |attempt_id: PairingAttemptId, Json(FinalizePairingRequest { success })| async move { + assert_eq!(attempt_id.0, "testid"); + *finalize_result_clone.lock().unwrap() = Some(success); + }, + ), ), ) .await; @@ -1261,7 +1265,7 @@ mod tests { let client = Client::new(ClientConfig { additional_certificates: vec![CertificateDer::from_pem_slice(include_bytes!("../../testdata/root.pem")).unwrap()], - endpoint_description: S2EndpointDescription::default(), + endpoint_description: EndpointDescription::default(), pairing_deployment: Deployment::Wan, }) .unwrap(); @@ -1280,12 +1284,12 @@ mod tests { #[tokio::test] async fn pairing_rejects_same_role_reported_by_server() { - let server_config = NodeConfig::builder(basic_node_description(UUID_A, S2Role::Rm), vec![MessageVersion("v1".into())]) + let server_config = NodeConfig::builder(basic_node_description(UUID_A, Role::Rm), vec![MessageVersion("v1".into())]) .with_connection_initiate_url("test.example.com".into()) .build() .unwrap(); - let client_config = NodeConfig::builder(basic_node_description(UUID_B, S2Role::Rm), vec![MessageVersion("v1".into())]) + let client_config = NodeConfig::builder(basic_node_description(UUID_B, Role::Rm), vec![MessageVersion("v1".into())]) .with_connection_initiate_url("client.example.com".into()) .build() .unwrap(); @@ -1306,10 +1310,12 @@ mod tests { ) .route( "/v1/finalizePairing", - post(|attempt_id: PairingAttemptId, Json(success): Json| async move { - assert_eq!(attempt_id.0, "testid"); - *finalize_result_clone.lock().unwrap() = Some(success); - }), + post( + |attempt_id: PairingAttemptId, Json(FinalizePairingRequest { success })| async move { + assert_eq!(attempt_id.0, "testid"); + *finalize_result_clone.lock().unwrap() = Some(success); + }, + ), ), ) .await; @@ -1322,7 +1328,7 @@ mod tests { let client = Client::new(ClientConfig { additional_certificates: vec![CertificateDer::from_pem_slice(include_bytes!("../../testdata/root.pem")).unwrap()], - endpoint_description: S2EndpointDescription::default(), + endpoint_description: EndpointDescription::default(), pairing_deployment: Deployment::Wan, }) .unwrap(); @@ -1341,12 +1347,12 @@ mod tests { #[tokio::test] async fn pairing_invokes_finalize_on_bad_request_connection_details() { - let server_config = NodeConfig::builder(basic_node_description(UUID_A, S2Role::Cem), vec![MessageVersion("v1".into())]) + let server_config = NodeConfig::builder(basic_node_description(UUID_A, Role::Cem), vec![MessageVersion("v1".into())]) .with_connection_initiate_url("test.example.com".into()) .build() .unwrap(); - let client_config = NodeConfig::builder(basic_node_description(UUID_B, S2Role::Rm), vec![MessageVersion("v1".into())]) + let client_config = NodeConfig::builder(basic_node_description(UUID_B, Role::Rm), vec![MessageVersion("v1".into())]) .with_connection_initiate_url("client.example.com".into()) .build() .unwrap(); @@ -1359,7 +1365,7 @@ mod tests { .route("/v1/requestConnectionDetails", post(|| async { StatusCode::BAD_GATEWAY })) .route( "/v1/finalizePairing", - post(|Json(success): Json| async move { + post(|Json(FinalizePairingRequest { success })| async move { *finalize_result_clone.lock().unwrap() = Some(success); }), ), @@ -1374,7 +1380,7 @@ mod tests { let client = Client::new(ClientConfig { additional_certificates: vec![CertificateDer::from_pem_slice(include_bytes!("../../testdata/root.pem")).unwrap()], - endpoint_description: S2EndpointDescription::default(), + endpoint_description: EndpointDescription::default(), pairing_deployment: Deployment::Wan, }) .unwrap(); @@ -1393,12 +1399,12 @@ mod tests { #[tokio::test] async fn pairing_invokes_finalize_on_bad_post_connection_details() { - let server_config = NodeConfig::builder(basic_node_description(UUID_A, S2Role::Rm), vec![MessageVersion("v1".into())]) + let server_config = NodeConfig::builder(basic_node_description(UUID_A, Role::Rm), vec![MessageVersion("v1".into())]) .with_connection_initiate_url("test.example.com".into()) .build() .unwrap(); - let client_config = NodeConfig::builder(basic_node_description(UUID_B, S2Role::Cem), vec![MessageVersion("v1".into())]) + let client_config = NodeConfig::builder(basic_node_description(UUID_B, Role::Cem), vec![MessageVersion("v1".into())]) .with_connection_initiate_url("client.example.com".into()) .build() .unwrap(); @@ -1411,7 +1417,7 @@ mod tests { .route("/v1/postConnectionDetails", post(|| async { StatusCode::BAD_GATEWAY })) .route( "/v1/finalizePairing", - post(|Json(success): Json| async move { + post(|Json(FinalizePairingRequest { success })| async move { *finalize_result_clone.lock().unwrap() = Some(success); }), ), @@ -1426,7 +1432,7 @@ mod tests { let client = Client::new(ClientConfig { additional_certificates: vec![CertificateDer::from_pem_slice(include_bytes!("../../testdata/root.pem")).unwrap()], - endpoint_description: S2EndpointDescription::default(), + endpoint_description: EndpointDescription::default(), pairing_deployment: Deployment::Wan, }) .unwrap(); @@ -1445,12 +1451,12 @@ mod tests { #[tokio::test] async fn pairing_invokes_finalize_on_callback_failure() { - let server_config = NodeConfig::builder(basic_node_description(UUID_A, S2Role::Rm), vec![MessageVersion("v1".into())]) + let server_config = NodeConfig::builder(basic_node_description(UUID_A, Role::Rm), vec![MessageVersion("v1".into())]) .with_connection_initiate_url("test.example.com".into()) .build() .unwrap(); - let client_config = NodeConfig::builder(basic_node_description(UUID_B, S2Role::Cem), vec![MessageVersion("v1".into())]) + let client_config = NodeConfig::builder(basic_node_description(UUID_B, Role::Cem), vec![MessageVersion("v1".into())]) .with_connection_initiate_url("client.example.com".into()) .build() .unwrap(); @@ -1461,7 +1467,7 @@ mod tests { server_config, Router::new().route( "/v1/finalizePairing", - post(|Json(success): Json| async move { + post(|Json(FinalizePairingRequest { success })| async move { *finalize_result_clone.lock().unwrap() = Some(success); }), ), @@ -1476,7 +1482,7 @@ mod tests { let client = Client::new(ClientConfig { additional_certificates: vec![CertificateDer::from_pem_slice(include_bytes!("../../testdata/root.pem")).unwrap()], - endpoint_description: S2EndpointDescription::default(), + endpoint_description: EndpointDescription::default(), pairing_deployment: Deployment::Wan, }) .unwrap(); @@ -1495,7 +1501,7 @@ mod tests { #[tokio::test] async fn longpolling() { - let server_config = NodeConfig::builder(basic_node_description(UUID_A, S2Role::Cem), vec![MessageVersion("v1".into())]) + let server_config = NodeConfig::builder(basic_node_description(UUID_A, Role::Cem), vec![MessageVersion("v1".into())]) .with_connection_initiate_url("test.example.com".into()) .build() .unwrap(); @@ -1505,14 +1511,14 @@ mod tests { let addr = server_handle.listening().await.unwrap(); let client_task = async move { - let client_config = NodeConfig::builder(basic_node_description(UUID_B, S2Role::Rm), vec![MessageVersion("v1".into())]) + let client_config = NodeConfig::builder(basic_node_description(UUID_B, Role::Rm), vec![MessageVersion("v1".into())]) .with_connection_initiate_url("client.example.com".into()) .build() .unwrap(); let client = Client::new(ClientConfig { additional_certificates: vec![CertificateDer::from_pem_slice(include_bytes!("../../testdata/root.pem")).unwrap()], - endpoint_description: S2EndpointDescription::default(), + endpoint_description: EndpointDescription::default(), pairing_deployment: Deployment::Wan, }) .unwrap(); @@ -1526,19 +1532,19 @@ mod tests { } impl LongpollHandler for TestHandler<'_> { - async fn request_pairing(&mut self, node: S2NodeId) -> bool { + async fn request_pairing(&mut self, node: NodeId) -> bool { assert!(self.have_cancel); assert_eq!(node, UUID_B.into()); self.poller.remove_node(node); true } - async fn prepare_pairing(&mut self, node: S2NodeId) { + async fn prepare_pairing(&mut self, node: NodeId) { assert_eq!(node, UUID_B.into()); self.have_prepare = true; } - async fn cancel_prepare_pairing(&mut self, node: S2NodeId) { + async fn cancel_prepare_pairing(&mut self, node: NodeId) { assert_eq!(node, UUID_B.into()); assert!(self.have_prepare); self.have_cancel = true; @@ -1579,7 +1585,7 @@ mod tests { assert_eq!(longpoll_session.client_id(), UUID_B.into()); let node_description = longpoll_session.node_description().await.unwrap(); assert_eq!(node_description.id, UUID_B.into()); - assert_eq!(node_description.role, S2Role::Rm); + assert_eq!(node_description.role, Role::Rm); assert!(longpoll_session.prepare_pairing().await.is_ok()); assert!(longpoll_session.cancel_prepare_pairing().await.is_ok()); @@ -1598,7 +1604,7 @@ mod tests { #[tokio::test] async fn longpolling_request_pairing_not_ready() { - let server_config = NodeConfig::builder(basic_node_description(UUID_A, S2Role::Cem), vec![MessageVersion("v1".into())]) + let server_config = NodeConfig::builder(basic_node_description(UUID_A, Role::Cem), vec![MessageVersion("v1".into())]) .with_connection_initiate_url("test.example.com".into()) .build() .unwrap(); @@ -1608,14 +1614,14 @@ mod tests { let addr = server_handle.listening().await.unwrap(); let client_task = tokio::spawn(async move { - let client_config = NodeConfig::builder(basic_node_description(UUID_B, S2Role::Rm), vec![MessageVersion("v1".into())]) + let client_config = NodeConfig::builder(basic_node_description(UUID_B, Role::Rm), vec![MessageVersion("v1".into())]) .with_connection_initiate_url("client.example.com".into()) .build() .unwrap(); let client = Client::new(ClientConfig { additional_certificates: vec![CertificateDer::from_pem_slice(include_bytes!("../../testdata/root.pem")).unwrap()], - endpoint_description: S2EndpointDescription::default(), + endpoint_description: EndpointDescription::default(), pairing_deployment: Deployment::Wan, }) .unwrap(); @@ -1625,16 +1631,16 @@ mod tests { struct TestHandler; impl LongpollHandler for TestHandler { - async fn request_pairing(&mut self, node: S2NodeId) -> bool { + async fn request_pairing(&mut self, node: NodeId) -> bool { assert_eq!(node, UUID_B.into()); false } - async fn prepare_pairing(&mut self, _node: S2NodeId) { + async fn prepare_pairing(&mut self, _node: NodeId) { unimplemented!() } - async fn cancel_prepare_pairing(&mut self, _node: S2NodeId) { + async fn cancel_prepare_pairing(&mut self, _node: NodeId) { unimplemented!() } } @@ -1654,12 +1660,12 @@ mod tests { #[tokio::test] async fn longpolling_cancelled() { - let server_config = NodeConfig::builder(basic_node_description(UUID_A, S2Role::Cem), vec![MessageVersion("v1".into())]) + let server_config = NodeConfig::builder(basic_node_description(UUID_A, Role::Cem), vec![MessageVersion("v1".into())]) .with_connection_initiate_url("test.example.com".into()) .build() .unwrap(); - let client_config = NodeConfig::builder(basic_node_description(UUID_B, S2Role::Rm), vec![MessageVersion("v1".into())]) + let client_config = NodeConfig::builder(basic_node_description(UUID_B, Role::Rm), vec![MessageVersion("v1".into())]) .with_connection_initiate_url("client.example.com".into()) .build() .unwrap(); @@ -1672,7 +1678,7 @@ mod tests { let client = Client::new(ClientConfig { additional_certificates: vec![CertificateDer::from_pem_slice(include_bytes!("../../testdata/root.pem")).unwrap()], - endpoint_description: S2EndpointDescription::default(), + endpoint_description: EndpointDescription::default(), pairing_deployment: Deployment::Wan, }) .unwrap(); @@ -1687,15 +1693,15 @@ mod tests { struct TestHandler; impl LongpollHandler for TestHandler { - async fn request_pairing(&mut self, _node: S2NodeId) -> bool { + async fn request_pairing(&mut self, _node: NodeId) -> bool { unimplemented!() } - async fn prepare_pairing(&mut self, _node: S2NodeId) { + async fn prepare_pairing(&mut self, _node: NodeId) { unimplemented!() } - async fn cancel_prepare_pairing(&mut self, _node: S2NodeId) { + async fn cancel_prepare_pairing(&mut self, _node: NodeId) { unimplemented!() } } @@ -1707,12 +1713,12 @@ mod tests { #[tokio::test] async fn longpolling_rejected() { - let server_config = NodeConfig::builder(basic_node_description(UUID_A, S2Role::Cem), vec![MessageVersion("v1".into())]) + let server_config = NodeConfig::builder(basic_node_description(UUID_A, Role::Cem), vec![MessageVersion("v1".into())]) .with_connection_initiate_url("test.example.com".into()) .build() .unwrap(); - let client_config = NodeConfig::builder(basic_node_description(UUID_B, S2Role::Rm), vec![MessageVersion("v1".into())]) + let client_config = NodeConfig::builder(basic_node_description(UUID_B, Role::Rm), vec![MessageVersion("v1".into())]) .with_connection_initiate_url("client.example.com".into()) .build() .unwrap(); @@ -1725,7 +1731,7 @@ mod tests { let client = Client::new(ClientConfig { additional_certificates: vec![CertificateDer::from_pem_slice(include_bytes!("../../testdata/root.pem")).unwrap()], - endpoint_description: S2EndpointDescription::default(), + endpoint_description: EndpointDescription::default(), pairing_deployment: Deployment::Wan, }) .unwrap(); @@ -1740,15 +1746,15 @@ mod tests { struct TestHandler; impl LongpollHandler for TestHandler { - async fn request_pairing(&mut self, _node: S2NodeId) -> bool { + async fn request_pairing(&mut self, _node: NodeId) -> bool { unimplemented!() } - async fn prepare_pairing(&mut self, _node: S2NodeId) { + async fn prepare_pairing(&mut self, _node: NodeId) { unimplemented!() } - async fn cancel_prepare_pairing(&mut self, _node: S2NodeId) { + async fn cancel_prepare_pairing(&mut self, _node: NodeId) { unimplemented!() } } diff --git a/s2energy-connection/src/pairing/mod.rs b/s2energy-connection/src/pairing/mod.rs index 578db49..58ff60a 100644 --- a/s2energy-connection/src/pairing/mod.rs +++ b/s2energy-connection/src/pairing/mod.rs @@ -8,15 +8,15 @@ //! a builder pattern. For simple configuration, the builder can immediately be build: //! ```rust //! # use s2energy_connection::pairing::NodeConfig; -//! # use s2energy_connection::{MessageVersion, S2NodeDescription, S2NodeId, S2Role}; -//! let _config = NodeConfig::builder(S2NodeDescription { -//! id: S2NodeId::try_from("67e55044-10b1-426f-9247-bb680e5fe0c8").unwrap(), +//! # use s2energy_connection::{MessageVersion, NodeDescription, NodeId, Role}; +//! let _config = NodeConfig::builder(NodeDescription { +//! id: NodeId::try_from("67e55044-10b1-426f-9247-bb680e5fe0c8").unwrap(), //! brand: String::from("super-reliable-corp"), -//! logo_uri: None, +//! logo_url: None, //! type_: String::from("fancy"), //! model_name: String::from("the best"), //! user_defined_name: None, -//! role: S2Role::Rm, +//! role: Role::Rm, //! }, vec![MessageVersion("v1".into())]) //! .build() //! .unwrap(); @@ -25,15 +25,15 @@ //! Additional information can be added through methods on the builder. For example, we can add a connection initiate url through: //! ```rust //! # use s2energy_connection::pairing::NodeConfig; -//! # use s2energy_connection::{MessageVersion, S2NodeDescription, S2NodeId, S2Role}; -//! let _config = NodeConfig::builder(S2NodeDescription { -//! id: S2NodeId::try_from("67e55044-10b1-426f-9247-bb680e5fe0c8").unwrap(), +//! # use s2energy_connection::{MessageVersion, NodeDescription, NodeId, Role}; +//! let _config = NodeConfig::builder(NodeDescription { +//! id: NodeId::try_from("67e55044-10b1-426f-9247-bb680e5fe0c8").unwrap(), //! brand: String::from("super-reliable-corp"), -//! logo_uri: None, +//! logo_url: None, //! type_: String::from("fancy"), //! model_name: String::from("the best"), //! user_defined_name: None, -//! role: S2Role::Rm, +//! role: Role::Rm, //! }, vec![MessageVersion("v1".into())]) //! .with_connection_initiate_url("https://example.com/".into()) //! .build() @@ -46,16 +46,16 @@ //! server. For this, you will also need to know the id of the node, and the URL on which its pairing server is reachable. //! ```rust //! # use std::sync::Arc; -//! # use s2energy_connection::pairing::{Client, ClientConfig, NodeConfig, PairingRemote, PairingS2NodeId}; -//! # use s2energy_connection::{Deployment, MessageVersion, S2NodeDescription, S2EndpointDescription, S2NodeId, S2Role}; -//! # let local_node = NodeConfig::builder(S2NodeDescription { -//! # id: S2NodeId::new(), +//! # use s2energy_connection::pairing::{Client, ClientConfig, NodeConfig, PairingRemote, NodeIdAlias}; +//! # use s2energy_connection::{Deployment, MessageVersion, NodeDescription, EndpointDescription, NodeId, Role}; +//! # let local_node = NodeConfig::builder(NodeDescription { +//! # id: NodeId::new(), //! # brand: String::from("super-reliable-corp"), -//! # logo_uri: None, +//! # logo_url: None, //! # type_: String::from("fancy"), //! # model_name: String::from("the best"), //! # user_defined_name: None, -//! # role: S2Role::Rm, +//! # role: Role::Rm, //! # }, vec![MessageVersion("v1".into())]) //! # .with_connection_initiate_url("https://example.com/".into()) //! # .build() @@ -63,13 +63,13 @@ //! //! let client = Client::new(ClientConfig { //! pairing_deployment: Deployment::Lan, -//! endpoint_description: S2EndpointDescription::default(), +//! endpoint_description: EndpointDescription::default(), //! additional_certificates: vec![], //! }).unwrap(); //! //! let pairing_result = client.pair(&local_node, PairingRemote { //! url: "https://remote.example.com".into(), -//! id: Some(PairingS2NodeId("test_pairing_id".into())), +//! id: Some(NodeIdAlias("test_pairing_id".into())), //! }, b"ABCDEF0123456", async |pairing| { /* do something with pairing */ Ok::<_, std::convert::Infallible>(())}); //! ``` //! @@ -80,7 +80,7 @@ //! # use std::{path::PathBuf, net::SocketAddr}; //! # use axum_server::tls_rustls::RustlsConfig; //! # use s2energy_connection::pairing::{Server, ServerConfig}; -//! # use s2energy_connection::S2EndpointDescription; +//! # use s2energy_connection::EndpointDescription; //! # #[tokio::main(flavor = "current_thread")] //! # async fn main() { //! # let tls_config = RustlsConfig::from_pem_file( @@ -94,7 +94,7 @@ //! # let addr = SocketAddr::from(([127, 0, 0, 1], 8005)); //! let server = Server::new(ServerConfig { //! leaf_certificate: None, -//! endpoint_description: S2EndpointDescription::default(), +//! endpoint_description: EndpointDescription::default(), //! advertised_nodes: vec![], //! }); //! tokio::spawn(async move { @@ -109,8 +109,8 @@ //! ```no_run //! # use std::{path::PathBuf, net::SocketAddr, sync::Arc}; //! # use axum_server::tls_rustls::RustlsConfig; -//! # use s2energy_connection::pairing::{NodeConfig, PairingToken, Server, ServerConfig, PairingS2NodeId}; -//! # use s2energy_connection::{MessageVersion, S2NodeDescription, S2EndpointDescription, S2NodeId, S2Role}; +//! # use s2energy_connection::pairing::{NodeConfig, PairingToken, Server, ServerConfig, NodeIdAlias}; +//! # use s2energy_connection::{MessageVersion, NodeDescription, EndpointDescription, NodeId, Role}; //! # #[tokio::main(flavor = "current_thread")] //! # async fn main() { //! # let tls_config = RustlsConfig::from_pem_file( @@ -124,24 +124,24 @@ //! # let addr = SocketAddr::from(([127, 0, 0, 1], 8005)); //! # let server = Server::new(ServerConfig { //! # leaf_certificate: None, -//! # endpoint_description: S2EndpointDescription::default(), +//! # endpoint_description: EndpointDescription::default(), //! # advertised_nodes: vec![], //! # }); -//! # let config = Arc::new(NodeConfig::builder(S2NodeDescription { -//! # id: S2NodeId::new(), +//! # let config = Arc::new(NodeConfig::builder(NodeDescription { +//! # id: NodeId::new(), //! # brand: String::from("super-reliable-corp"), -//! # logo_uri: None, +//! # logo_url: None, //! # type_: String::from("fancy"), //! # model_name: String::from("the best"), //! # user_defined_name: None, -//! # role: S2Role::Rm, +//! # role: Role::Rm, //! # }, vec![MessageVersion("v1".into())]) //! # .with_connection_initiate_url("https://example.com/".into()) //! # .build() //! # .unwrap()); //! server.allow_pair_once( //! config, -//! Some(PairingS2NodeId("XYZ".into())), +//! Some(NodeIdAlias("XYZ".into())), //! PairingToken(b"ABCDEF0123456".as_slice().into()), //! async |pairing_result| { //! /* ensure the pairing becomes usable/gets used */ @@ -155,8 +155,8 @@ //! ```no_run //! # use std::{path::PathBuf, net::SocketAddr, sync::Arc}; //! # use axum_server::tls_rustls::RustlsConfig; -//! # use s2energy_connection::pairing::{NodeConfig, PairingToken, Server, ServerConfig, PairingS2NodeId}; -//! # use s2energy_connection::{MessageVersion, S2NodeDescription, S2EndpointDescription, S2NodeId, S2Role}; +//! # use s2energy_connection::pairing::{NodeConfig, PairingToken, Server, ServerConfig, NodeIdAlias}; +//! # use s2energy_connection::{MessageVersion, NodeDescription, EndpointDescription, NodeId, Role}; //! # #[tokio::main(flavor = "current_thread")] //! # async fn main() { //! # let tls_config = RustlsConfig::from_pem_file( @@ -170,24 +170,24 @@ //! # let addr = SocketAddr::from(([127, 0, 0, 1], 8005)); //! # let server = Server::new(ServerConfig { //! # leaf_certificate: None, -//! # endpoint_description: S2EndpointDescription::default(), +//! # endpoint_description: EndpointDescription::default(), //! # advertised_nodes: vec![], //! # }); -//! # let config = Arc::new(NodeConfig::builder(S2NodeDescription { -//! # id: S2NodeId::new(), +//! # let config = Arc::new(NodeConfig::builder(NodeDescription { +//! # id: NodeId::new(), //! # brand: String::from("super-reliable-corp"), -//! # logo_uri: None, +//! # logo_url: None, //! # type_: String::from("fancy"), //! # model_name: String::from("the best"), //! # user_defined_name: None, -//! # role: S2Role::Rm, +//! # role: Role::Rm, //! # }, vec![MessageVersion("v1".into())]) //! # .with_connection_initiate_url("https://example.com/".into()) //! # .build() //! # .unwrap()); //! server.allow_pair_repeated( //! config, -//! Some(PairingS2NodeId("XYZ".into())), +//! Some(NodeIdAlias("XYZ".into())), //! PairingToken(b"ABCDEF0123456".as_slice().into()), //! async |pairing_result| { //! /* ensure the pairing becomes usable/gets used */ @@ -217,16 +217,14 @@ pub use error::{ConfigError, Error, ErrorKind}; pub use server::{ LongpollingHandle, NoopPrePairingHandler, PairingToken, PairingTokenError, PrePairingHandler, PrePairingResponse, Server, ServerConfig, }; -pub use wire::PairingS2NodeId; +pub use wire::NodeIdAlias; -use crate::{ - CommunicationProtocol, Deployment, MessageVersion, S2EndpointDescription, S2NodeDescription, S2Role, common::wire::AccessToken, -}; +use crate::{CommunicationProtocol, Deployment, EndpointDescription, MessageVersion, NodeDescription, Role, common::wire::AccessToken}; /// Full description of an S2 node. #[derive(Debug, Clone)] pub struct NodeConfig { - node_description: S2NodeDescription, + node_description: NodeDescription, supported_message_versions: Vec, supported_communication_protocols: Vec, connection_initiate_url: Option, @@ -234,7 +232,7 @@ pub struct NodeConfig { impl NodeConfig { /// Description of the S2 node. - pub fn node_description(&self) -> &S2NodeDescription { + pub fn node_description(&self) -> &NodeDescription { &self.node_description } @@ -257,7 +255,7 @@ impl NodeConfig { /// /// All node configurations must at least contain description of the node and supported message versions. Additional /// properties can be configured through the builder. - pub fn builder(node_description: S2NodeDescription, supported_message_versions: Vec) -> ConfigBuilder { + pub fn builder(node_description: NodeDescription, supported_message_versions: Vec) -> ConfigBuilder { ConfigBuilder { node_description, supported_message_versions, @@ -269,7 +267,7 @@ impl NodeConfig { /// Builder for an [`NodeConfig`]. pub struct ConfigBuilder { - node_description: S2NodeDescription, + node_description: NodeDescription, supported_message_versions: Vec, supported_communication_protocols: Vec, connection_initiate_url: Option, @@ -292,7 +290,7 @@ impl ConfigBuilder { /// Create the actual [`NodeConfig`], validating that it is reasonable. pub fn build(self) -> Result { - if self.node_description.role == S2Role::Cem && self.connection_initiate_url.is_none() { + if self.node_description.role == Role::Cem && self.connection_initiate_url.is_none() { return Err(ConfigError::MissingInitiateUrl); } Ok(NodeConfig { @@ -322,9 +320,9 @@ pub enum PairingRole { #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct Pairing { /// Description of the remote S2 Node. - pub remote_node_description: S2NodeDescription, + pub remote_node_description: NodeDescription, /// Description of the remote S2 Endpoint hosting the node. - pub remote_endpoint_description: S2EndpointDescription, + pub remote_endpoint_description: EndpointDescription, /// Token used during communication setup. pub token: AccessToken, /// Role this node has for initiating communication. @@ -349,7 +347,7 @@ pub enum PairingCodeParseError { /// /// It is not recommended to use this outside of testing. A much better user /// experience can be had by a parser more closely integrated with the UI. -pub fn parse_pairing_code(code: &str) -> Result<(Option, PairingToken), PairingCodeParseError> { +pub fn parse_pairing_code(code: &str) -> Result<(Option, PairingToken), PairingCodeParseError> { if let Some((alias, token)) = code.split_once('-') { if token.contains('-') { return Err(PairingCodeParseError::TooManyParts); @@ -361,7 +359,7 @@ pub fn parse_pairing_code(code: &str) -> Result<(Option, Pairin let token: PairingToken = token.parse().map_err(|_| PairingCodeParseError::InvalidToken)?; - Ok((Some(PairingS2NodeId(alias.to_string())), token)) + Ok((Some(NodeIdAlias(alias.to_string())), token)) } else { Ok((None, code.parse().map_err(|_| PairingCodeParseError::InvalidToken)?)) } diff --git a/s2energy-connection/src/pairing/server.rs b/s2energy-connection/src/pairing/server.rs index 4ddf896..3efeaa0 100644 --- a/s2energy-connection/src/pairing/server.rs +++ b/s2energy-connection/src/pairing/server.rs @@ -30,7 +30,7 @@ use tracing::{Instrument, info, trace}; use crate::{ common::{ AbortingJoinHandle, root, - wire::{AccessToken, PairingVersion, S2EndpointDescription, S2NodeDescription, S2NodeId}, + wire::{AccessToken, EndpointDescription, NodeDescription, NodeId, PairingVersion}, }, pairing::{Error, PairingRole}, }; @@ -137,10 +137,10 @@ pub struct ServerConfig { /// Presence of this field indicates we are deployed on LAN. pub leaf_certificate: Option>, /// Endpoint description of the server - pub endpoint_description: S2EndpointDescription, + pub endpoint_description: EndpointDescription, /// Initial set of nodes to advertise. This is only used if the server /// is deployed on LAN. - pub advertised_nodes: Vec, + pub advertised_nodes: Vec, } /// Description of what response to @@ -164,16 +164,12 @@ pub enum PrePairingResponse { // operations. pub trait PrePairingHandler: Send + Sync + 'static { /// Handle a request for pre-pairing, and indicate our willingness. - fn prepairing_requested( - &self, - endpoint: S2EndpointDescription, - node: S2NodeDescription, - target_node: Option, - ) -> PrePairingResponse; + fn prepairing_requested(&self, endpoint: EndpointDescription, node: NodeDescription, target_node: Option) + -> PrePairingResponse; /// Handle a cancel event for pre-pairing. Note that not every pre-pairing /// request will result in a cancel or a pairing interaction, so timeouts /// may be needed. - fn prepairing_cancelled(&self, id: S2NodeId, target_node: Option); + fn prepairing_cancelled(&self, id: NodeId, target_node: Option); } /// A pre-pairing handler that does nothing on receiving a pre-pairing request. @@ -184,15 +180,15 @@ pub struct NoopPrePairingHandler; impl PrePairingHandler for NoopPrePairingHandler { fn prepairing_requested( &self, - _endpoint: S2EndpointDescription, - _node: S2NodeDescription, - _target_node: Option, + _endpoint: EndpointDescription, + _node: NodeDescription, + _target_node: Option, ) -> PrePairingResponse { // no reason not to accept PrePairingResponse::Accept } - fn prepairing_cancelled(&self, _id: S2NodeId, _target_node: Option) { + fn prepairing_cancelled(&self, _id: NodeId, _target_node: Option) { // noop } } @@ -262,7 +258,7 @@ impl Server { /// Update the nodes advertised by this server. /// /// These are only used when the server is on a LAN. - pub fn update_advertised_nodes(&self, advertised_nodes: Vec) { + pub fn update_advertised_nodes(&self, advertised_nodes: Vec) { *self.state.advertised_nodes.lock().unwrap() = advertised_nodes; } @@ -304,7 +300,7 @@ impl Server { pub fn allow_pair_once> + Send>( &self, config: Arc, - pairing_node_id: Option, + pairing_node_id: Option, pairing_token: PairingToken, callback: impl (FnOnce(PairingResult) -> F) + Send + 'static, ) -> Result<(), ErrorKind> { @@ -312,7 +308,7 @@ impl Server { return Err(ErrorKind::InvalidConfig(super::ConfigError::MissingInitiateUrl)); } - let pairing_node_id = pairing_node_id.unwrap_or(PairingS2NodeId(String::default())); + let pairing_node_id = pairing_node_id.unwrap_or(NodeIdAlias(String::default())); // We hit issues here, because the node node_description only has S2NodeId with no // efficient way of mapping that back. @@ -345,7 +341,7 @@ impl Server { pub fn allow_pair_repeated> + Send>( &self, config: Arc, - pairing_node_id: Option, + pairing_node_id: Option, pairing_token: PairingToken, callback: impl (Fn(PairingResult) -> F) + Send + Sync + 'static, ) -> Result<(), ErrorKind> { @@ -353,7 +349,7 @@ impl Server { return Err(ErrorKind::InvalidConfig(super::ConfigError::MissingInitiateUrl)); } - let pairing_node_id = pairing_node_id.unwrap_or(PairingS2NodeId(String::default())); + let pairing_node_id = pairing_node_id.unwrap_or(NodeIdAlias(String::default())); let mut open_pairings = self.state.open_pairings.lock().unwrap(); let mut permanent_pairings = self.state.permanent_pairings.lock().unwrap(); @@ -380,25 +376,25 @@ impl Server { /// Handle for a longpolling connection with a client S2 Node. pub struct LongpollingHandle { commands: tokio::sync::mpsc::Sender, - endpoint: tokio::sync::watch::Receiver>, - node: tokio::sync::watch::Receiver>, + endpoint: tokio::sync::watch::Receiver>, + node: tokio::sync::watch::Receiver>, last_pairing_response: tokio::sync::watch::Receiver>>, - client_id: S2NodeId, + client_id: NodeId, } impl LongpollingHandle { /// Client S2NodeId of the remote. - pub fn client_id(&self) -> S2NodeId { + pub fn client_id(&self) -> NodeId { self.client_id } /// Node description of the remote. /// /// This is fallible as it is not send by default, so we need to ask the remote. - pub async fn node_description(&mut self) -> Result { + pub async fn node_description(&mut self) -> Result { if self.node.borrow().is_none() { self.commands - .send(WaitForPairingAction::SendS2NodeDescription) + .send(WaitForPairingAction::SendNodeDescription) .await .map_err(|_| ErrorKind::Cancelled)?; } @@ -414,10 +410,10 @@ impl LongpollingHandle { /// Endpoint description of the remote. /// /// This is fallible as it is not send by default, so we need to ask the remote. - pub async fn endpoint_description(&mut self) -> Result { + pub async fn endpoint_description(&mut self) -> Result { if self.endpoint.borrow().is_none() { self.commands - .send(WaitForPairingAction::SendS2NodeDescription) + .send(WaitForPairingAction::SendNodeDescription) .await .map_err(|_| ErrorKind::Cancelled)?; } @@ -504,8 +500,8 @@ impl LongpollingState { struct LongpollingStateInner { commands: tokio::sync::mpsc::Receiver, - endpoint: tokio::sync::watch::Sender>, - node: tokio::sync::watch::Sender>, + endpoint: tokio::sync::watch::Sender>, + node: tokio::sync::watch::Sender>, last_pairing_response: tokio::sync::watch::Sender>>, } @@ -546,14 +542,14 @@ struct InitialPairingState { sender: ResultHandler, challenge: HmacChallenge, token: PairingToken, - remote_node_description: S2NodeDescription, - remote_endpoint_description: S2EndpointDescription, + remote_node_description: NodeDescription, + remote_endpoint_description: EndpointDescription, } struct CompletePairingState { session_span: tracing::Span, sender: ResultHandler, - remote_node_description: S2NodeDescription, - remote_endpoint_description: S2EndpointDescription, + remote_node_description: NodeDescription, + remote_endpoint_description: EndpointDescription, access_token: AccessToken, role: PairingRole, } @@ -601,10 +597,10 @@ type AppState = Arc>; struct AppStateInner { network: Network, - endpoint_description: S2EndpointDescription, - advertised_nodes: Mutex>, - permanent_pairings: Mutex>, - open_pairings: Mutex>, + endpoint_description: EndpointDescription, + advertised_nodes: Mutex>, + permanent_pairings: Mutex>, + open_pairings: Mutex>, attempts: Mutex>, prepairing_handler: Arc, longpolling_enabled: tokio::sync::watch::Receiver, @@ -613,7 +609,7 @@ struct AppStateInner { // each request will hold a read lock on this for its duration. // the enable/disable logic will keep a write lock. longpolling_sessions_active: Arc>, - longpolling_sessions: Mutex>, + longpolling_sessions: Mutex>, longpolling_handle_sender: tokio::sync::mpsc::Sender, cleanup_task: OnceLock>, } @@ -621,7 +617,7 @@ struct AppStateInner { // Holder for longpolling sessions during a session. Returns // them to the appstate on drop. struct LocalLongpollingCache { - sessions: HashMap, + sessions: HashMap, state: AppState, } @@ -635,7 +631,7 @@ impl LocalLongpollingCache { } impl std::ops::Deref for LocalLongpollingCache { - type Target = HashMap; + type Target = HashMap; fn deref(&self) -> &Self::Target { &self.sessions @@ -704,8 +700,8 @@ async fn periodic_cleanup(state: Weak>) { fn v1_router() -> Router> { Router::new() - .route("/s2endpoint", get(v1_s2endpoint)) - .route("/s2nodes", get(v1_s2nodes)) + .route("/endpoint", get(v1_s2endpoint)) + .route("/nodes", get(v1_s2nodes)) .route("/preparePairing", post(v1_prepare_pairing)) .route("/cancelPreparePairing", post(v1_cancel_prepare_pairing)) .route("/waitForPairing", post(v1_wait_for_pairing)) @@ -733,7 +729,7 @@ async fn v1_wait_for_pairing( { let mut longpolling_sessions = state.longpolling_sessions.lock().unwrap(); for request in &requests { - let state = match longpolling_sessions.entry(request.client_s2_node_id) { + let state = match longpolling_sessions.entry(request.client_node_id) { std::collections::hash_map::Entry::Occupied(mut occupied_entry) => match occupied_entry.get_mut().take() { Some(state) => state, None => { @@ -750,7 +746,7 @@ async fn v1_wait_for_pairing( endpoint: endpoint_receiver, node: node_receiver, last_pairing_response: last_pairing_receiver, - client_id: request.client_s2_node_id, + client_id: request.client_node_id, }); vacant_entry.insert(LongpollingState::Running { since: Instant::now(), @@ -764,18 +760,18 @@ async fn v1_wait_for_pairing( } } }; - states.insert(request.client_s2_node_id, state); + states.insert(request.client_node_id, state); } } // Update sessions based on request data for request in requests { // Guaranteed to be present because of previous loop - let state = states.get_mut(&request.client_s2_node_id).unwrap(); - if let Some(endpoint) = request.client_s2_endpoint_description { + let state = states.get_mut(&request.client_node_id).unwrap(); + if let Some(endpoint) = request.client_endpoint_description { state.endpoint.send_replace(Some(endpoint)); } - if let Some(node) = request.client_s2_node_description { + if let Some(node) = request.clien_node_description { state.node.send_replace(Some(node)); } if let Some(error_message) = request.error_message { @@ -804,7 +800,7 @@ async fn v1_wait_for_pairing( std::task::Poll::Pending }), ) => return match outcome { - Ok(Some((client_s2_node_id, action))) => Ok(Json(WaitForPairingResponse { client_s2_node_id, action })), + Ok(Some((client_node_id, action))) => Ok(Json(WaitForPairingResponse { client_node_id, action })), Ok(None) | Err(_) => Err(StatusCode::NO_CONTENT), }, _ = enabled.wait_for(|v| !*v) => return Err(StatusCode::BAD_REQUEST), @@ -812,7 +808,7 @@ async fn v1_wait_for_pairing( } #[tracing::instrument(skip_all, level = tracing::Level::INFO)] -async fn v1_s2endpoint(State(state): State>) -> Result, StatusCode> { +async fn v1_s2endpoint(State(state): State>) -> Result, StatusCode> { if state.network.is_lan() { Ok(Json(state.endpoint_description.clone())) } else { @@ -821,7 +817,7 @@ async fn v1_s2endpoint(State(state): State>) -> Result(State(state): State>) -> Result>, StatusCode> { +async fn v1_s2nodes(State(state): State>) -> Result>, StatusCode> { if state.network.is_lan() { Ok(Json(state.advertised_nodes.lock().unwrap().clone())) } else { @@ -835,8 +831,8 @@ async fn v1_prepare_pairing( Json(request): Json, ) -> Result { match state.prepairing_handler.prepairing_requested( - request.client_s2_endpoint_description, - request.client_s2_node_description, + request.client_endpoint_description, + request.client_node_description, request.server_id, ) { PrePairingResponse::Accept => Ok(StatusCode::NO_CONTENT), @@ -874,7 +870,7 @@ async fn v1_request_pairing( let server_hmac_challenge = HmacChallenge::new(&mut rand::rng(), HMAC_CHALLENGE_BYTES); - let pairing_s2_node_id = request_pairing.id.unwrap_or(PairingS2NodeId(String::default())); + let pairing_s2_node_id = request_pairing.id.unwrap_or(NodeIdAlias(String::default())); let open_pairing = { let mut open_pairings = state.open_pairings.lock().unwrap(); if let Some((_, request)) = open_pairings.remove_entry(&pairing_s2_node_id) { @@ -969,8 +965,8 @@ async fn v1_request_pairing( let resp = RequestPairingResponse { pairing_attempt_id, - server_s2_node_description: open_pairing.config.node_description.clone(), - server_s2_endpoint_description: state.endpoint_description.clone(), + server_node_description: open_pairing.config.node_description.clone(), + server_endpoint_description: state.endpoint_description.clone(), selected_hmac_hashing_algorithm: HmacHashingAlgorithm::Sha256, client_hmac_challenge_response, server_hmac_challenge, @@ -1122,7 +1118,7 @@ async fn v1_post_connection_details( async fn v1_finalize_pairing( State(state): State>, pairing_attempt_id: PairingAttemptId, - Json(success): Json, + Json(FinalizePairingRequest { success }): Json, ) -> StatusCode { trace!("Received request to finalize pairing session."); @@ -1203,14 +1199,14 @@ mod tests { use tracing::{Level, span}; use crate::{ - AccessToken, CommunicationProtocol, MessageVersion, S2EndpointDescription, S2NodeDescription, S2NodeId, S2Role, + AccessToken, CommunicationProtocol, EndpointDescription, MessageVersion, NodeDescription, NodeId, Role, common::wire::test::{UUID_A, UUID_B, basic_node_description, pairing_s2_node_id}, pairing::{ - ErrorKind, Network, NodeConfig, PairingRole, PairingS2NodeId, PairingToken, PrePairingHandler, PrePairingResponse, Server, + ErrorKind, Network, NodeConfig, NodeIdAlias, PairingRole, PairingToken, PrePairingHandler, PrePairingResponse, Server, ServerConfig, server::{CompletePairingState, ExpiringPairingState, InitialPairingState, PairingRequest, PairingState, ResultHandler}, wire::{ - CancelPrePairingRequest, ConnectionDetails, HmacChallenge, HmacHashingAlgorithm, PairingAttemptId, + CancelPrePairingRequest, ConnectionDetails, FinalizePairingRequest, HmacChallenge, HmacHashingAlgorithm, PairingAttemptId, PairingResponseErrorMessage, PostConnectionDetailsRequest, PrePairingRequest, RequestConnectionDetailsRequest, RequestPairing, RequestPairingResponse, WaitForPairingAction, WaitForPairingErrorMessage, WaitForPairingRequest, WaitForPairingResponse, @@ -1229,7 +1225,7 @@ mod tests { async fn version_negotiation() { let server = Server::new(ServerConfig { leaf_certificate: None, - endpoint_description: S2EndpointDescription::default(), + endpoint_description: EndpointDescription::default(), advertised_nodes: vec![], }); @@ -1247,22 +1243,22 @@ mod tests { async fn advertised_endpoint() { let server = Server::new(ServerConfig { leaf_certificate: Some(CertificateDer::from_pem_slice(include_bytes!("../../testdata/root.pem")).unwrap()), - endpoint_description: S2EndpointDescription { + endpoint_description: EndpointDescription { name: Some("Testendpoint".into()), - logo_uri: None, + logo_url: None, deployment: None, }, - advertised_nodes: vec![basic_node_description(UUID_A, S2Role::Cem)], + advertised_nodes: vec![basic_node_description(UUID_A, Role::Cem)], }); let response = server .get_router() - .oneshot(http::Request::get("/v1/s2endpoint").body(Body::empty()).unwrap()) + .oneshot(http::Request::get("/v1/endpoint").body(Body::empty()).unwrap()) .await .unwrap(); assert_eq!(response.status(), StatusCode::OK); let body = response.into_body().collect().await.unwrap().to_bytes(); - let body_data: S2EndpointDescription = serde_json::from_slice(&body).unwrap(); + let body_data: EndpointDescription = serde_json::from_slice(&body).unwrap(); assert_eq!(body_data.name.as_deref(), Some("Testendpoint")); } @@ -1270,17 +1266,17 @@ mod tests { async fn advertised_endpoint_wan() { let server = Server::new(ServerConfig { leaf_certificate: None, - endpoint_description: S2EndpointDescription { + endpoint_description: EndpointDescription { name: Some("Testendpoint".into()), - logo_uri: None, + logo_url: None, deployment: None, }, - advertised_nodes: vec![basic_node_description(UUID_A, S2Role::Cem)], + advertised_nodes: vec![basic_node_description(UUID_A, Role::Cem)], }); let response = server .get_router() - .oneshot(http::Request::get("/v1/s2endpoint").body(Body::empty()).unwrap()) + .oneshot(http::Request::get("/v1/endpoint").body(Body::empty()).unwrap()) .await .unwrap(); assert_eq!(response.status(), StatusCode::UNAUTHORIZED); @@ -1290,40 +1286,40 @@ mod tests { async fn advertised_nodes() { let server = Server::new(ServerConfig { leaf_certificate: Some(CertificateDer::from_pem_slice(include_bytes!("../../testdata/root.pem")).unwrap()), - endpoint_description: S2EndpointDescription { + endpoint_description: EndpointDescription { name: Some("Testendpoint".into()), - logo_uri: None, + logo_url: None, deployment: None, }, - advertised_nodes: vec![basic_node_description(UUID_A, S2Role::Cem)], + advertised_nodes: vec![basic_node_description(UUID_A, Role::Cem)], }); let response = server .get_router() - .oneshot(http::Request::get("/v1/s2nodes").body(Body::empty()).unwrap()) + .oneshot(http::Request::get("/v1/nodes").body(Body::empty()).unwrap()) .await .unwrap(); assert_eq!(response.status(), StatusCode::OK); let body = response.into_body().collect().await.unwrap().to_bytes(); - let body_data: Vec = serde_json::from_slice(&body).unwrap(); - assert_eq!(body_data, vec![basic_node_description(UUID_A, S2Role::Cem)]); + let body_data: Vec = serde_json::from_slice(&body).unwrap(); + assert_eq!(body_data, vec![basic_node_description(UUID_A, Role::Cem)]); } #[tokio::test] async fn advertised_nodes_wan() { let server = Server::new(ServerConfig { leaf_certificate: None, - endpoint_description: S2EndpointDescription { + endpoint_description: EndpointDescription { name: Some("Testendpoint".into()), - logo_uri: None, + logo_url: None, deployment: None, }, - advertised_nodes: vec![basic_node_description(UUID_A, S2Role::Cem)], + advertised_nodes: vec![basic_node_description(UUID_A, Role::Cem)], }); let response = server .get_router() - .oneshot(http::Request::get("/v1/s2nodes").body(Body::empty()).unwrap()) + .oneshot(http::Request::get("/v1/nodes").body(Body::empty()).unwrap()) .await .unwrap(); assert_eq!(response.status(), StatusCode::UNAUTHORIZED); @@ -1331,10 +1327,10 @@ mod tests { #[derive(Debug, Clone)] struct TestPrePairingHandler { - endpoint: Arc>>, - node: Arc>>, - client_id: Arc>>, - target_node: Arc>>>, + endpoint: Arc>>, + node: Arc>>, + client_id: Arc>>, + target_node: Arc>>>, response: PrePairingResponse, } @@ -1353,9 +1349,9 @@ mod tests { impl PrePairingHandler for TestPrePairingHandler { fn prepairing_requested( &self, - endpoint: S2EndpointDescription, - node: S2NodeDescription, - target_node: Option, + endpoint: EndpointDescription, + node: NodeDescription, + target_node: Option, ) -> super::PrePairingResponse { *self.endpoint.lock().unwrap() = Some(endpoint); *self.node.lock().unwrap() = Some(node); @@ -1363,7 +1359,7 @@ mod tests { self.response } - fn prepairing_cancelled(&self, id: crate::S2NodeId, target_node: Option) { + fn prepairing_cancelled(&self, id: crate::NodeId, target_node: Option) { *self.client_id.lock().unwrap() = Some(id); *self.target_node.lock().unwrap() = Some(target_node); } @@ -1375,7 +1371,7 @@ mod tests { let server = Server::new_with_prepairing( ServerConfig { leaf_certificate: None, - endpoint_description: S2EndpointDescription::default(), + endpoint_description: EndpointDescription::default(), advertised_nodes: vec![], }, test_handler.clone(), @@ -1387,8 +1383,8 @@ mod tests { .header(http::header::CONTENT_TYPE, "application/json") .body(Body::from( serde_json::to_vec(&PrePairingRequest { - client_s2_endpoint_description: S2EndpointDescription::default(), - client_s2_node_description: basic_node_description(UUID_A, S2Role::Cem), + client_endpoint_description: EndpointDescription::default(), + client_node_description: basic_node_description(UUID_A, Role::Cem), server_id: None, }) .unwrap(), @@ -1403,7 +1399,7 @@ mod tests { let node = test_handler.node.lock().unwrap().take().unwrap(); let target_node = test_handler.target_node.lock().unwrap().take().unwrap(); assert_eq!(endpoint.deployment, None); - assert_eq!(node.role, S2Role::Cem); + assert_eq!(node.role, Role::Cem); assert_eq!(node.id, UUID_A.into()); assert_eq!(target_node, None); } @@ -1414,7 +1410,7 @@ mod tests { let server = Server::new_with_prepairing( ServerConfig { leaf_certificate: None, - endpoint_description: S2EndpointDescription::default(), + endpoint_description: EndpointDescription::default(), advertised_nodes: vec![], }, test_handler.clone(), @@ -1426,8 +1422,8 @@ mod tests { .header(http::header::CONTENT_TYPE, "application/json") .body(Body::from( serde_json::to_vec(&PrePairingRequest { - client_s2_endpoint_description: S2EndpointDescription::default(), - client_s2_node_description: basic_node_description(UUID_A, S2Role::Cem), + client_endpoint_description: EndpointDescription::default(), + client_node_description: basic_node_description(UUID_A, Role::Cem), server_id: None, }) .unwrap(), @@ -1445,7 +1441,7 @@ mod tests { let node = test_handler.node.lock().unwrap().take().unwrap(); let target_node = test_handler.target_node.lock().unwrap().take().unwrap(); assert_eq!(endpoint.deployment, None); - assert_eq!(node.role, S2Role::Cem); + assert_eq!(node.role, Role::Cem); assert_eq!(node.id, UUID_A.into()); assert_eq!(target_node, None); } @@ -1456,7 +1452,7 @@ mod tests { let server = Server::new_with_prepairing( ServerConfig { leaf_certificate: None, - endpoint_description: S2EndpointDescription::default(), + endpoint_description: EndpointDescription::default(), advertised_nodes: vec![], }, test_handler.clone(), @@ -1468,8 +1464,8 @@ mod tests { .header(http::header::CONTENT_TYPE, "application/json") .body(Body::from( serde_json::to_vec(&PrePairingRequest { - client_s2_endpoint_description: S2EndpointDescription::default(), - client_s2_node_description: basic_node_description(UUID_A, S2Role::Cem), + client_endpoint_description: EndpointDescription::default(), + client_node_description: basic_node_description(UUID_A, Role::Cem), server_id: None, }) .unwrap(), @@ -1487,7 +1483,7 @@ mod tests { let node = test_handler.node.lock().unwrap().take().unwrap(); let target_node = test_handler.target_node.lock().unwrap().take().unwrap(); assert_eq!(endpoint.deployment, None); - assert_eq!(node.role, S2Role::Cem); + assert_eq!(node.role, Role::Cem); assert_eq!(node.id, UUID_A.into()); assert_eq!(target_node, None); } @@ -1498,7 +1494,7 @@ mod tests { let server = Server::new_with_prepairing( ServerConfig { leaf_certificate: None, - endpoint_description: S2EndpointDescription::default(), + endpoint_description: EndpointDescription::default(), advertised_nodes: vec![], }, test_handler.clone(), @@ -1531,13 +1527,13 @@ mod tests { async fn pair_attempt() { let server = Server::new(ServerConfig { leaf_certificate: None, - endpoint_description: S2EndpointDescription::default(), + endpoint_description: EndpointDescription::default(), advertised_nodes: vec![], }); server .allow_pair_once( Arc::new( - NodeConfig::builder(basic_node_description(UUID_A, S2Role::Rm), vec![MessageVersion("v1".into())]) + NodeConfig::builder(basic_node_description(UUID_A, Role::Rm), vec![MessageVersion("v1".into())]) .with_connection_initiate_url("https://example.com/".into()) .build() .unwrap(), @@ -1556,8 +1552,8 @@ mod tests { .header(http::header::CONTENT_TYPE, "application/json") .body(Body::from( serde_json::to_vec(&RequestPairing { - node_description: basic_node_description(UUID_B, S2Role::Cem), - endpoint_description: S2EndpointDescription::default(), + node_description: basic_node_description(UUID_B, Role::Cem), + endpoint_description: EndpointDescription::default(), id: Some(pairing_s2_node_id()), supported_protocols: vec![CommunicationProtocol("WebSocket".into())], supported_versions: vec![MessageVersion("v1".into())], @@ -1583,13 +1579,13 @@ mod tests { async fn pair_attempt_no_common_communication() { let server = Server::new(ServerConfig { leaf_certificate: None, - endpoint_description: S2EndpointDescription::default(), + endpoint_description: EndpointDescription::default(), advertised_nodes: vec![], }); server .allow_pair_once( Arc::new( - NodeConfig::builder(basic_node_description(UUID_A, S2Role::Rm), vec![MessageVersion("v1".into())]) + NodeConfig::builder(basic_node_description(UUID_A, Role::Rm), vec![MessageVersion("v1".into())]) .with_connection_initiate_url("https://example.com/".into()) .build() .unwrap(), @@ -1608,8 +1604,8 @@ mod tests { .header(http::header::CONTENT_TYPE, "application/json") .body(Body::from( serde_json::to_vec(&RequestPairing { - node_description: basic_node_description(UUID_B, S2Role::Cem), - endpoint_description: S2EndpointDescription::default(), + node_description: basic_node_description(UUID_B, Role::Cem), + endpoint_description: EndpointDescription::default(), id: Some(pairing_s2_node_id()), supported_protocols: vec![CommunicationProtocol("HTTP/3".into())], supported_versions: vec![MessageVersion("v1".into())], @@ -1634,13 +1630,13 @@ mod tests { async fn pair_attempt_no_common_messages() { let server = Server::new(ServerConfig { leaf_certificate: None, - endpoint_description: S2EndpointDescription::default(), + endpoint_description: EndpointDescription::default(), advertised_nodes: vec![], }); server .allow_pair_once( Arc::new( - NodeConfig::builder(basic_node_description(UUID_A, S2Role::Rm), vec![MessageVersion("v1".into())]) + NodeConfig::builder(basic_node_description(UUID_A, Role::Rm), vec![MessageVersion("v1".into())]) .with_connection_initiate_url("https://example.com/".into()) .build() .unwrap(), @@ -1659,8 +1655,8 @@ mod tests { .header(http::header::CONTENT_TYPE, "application/json") .body(Body::from( serde_json::to_vec(&RequestPairing { - node_description: basic_node_description(UUID_B, S2Role::Cem), - endpoint_description: S2EndpointDescription::default(), + node_description: basic_node_description(UUID_B, Role::Cem), + endpoint_description: EndpointDescription::default(), id: Some(pairing_s2_node_id()), supported_protocols: vec![CommunicationProtocol("WebSocket".into())], supported_versions: vec![MessageVersion("v0".into())], @@ -1685,13 +1681,13 @@ mod tests { async fn pair_attempt_forced() { let server = Server::new(ServerConfig { leaf_certificate: None, - endpoint_description: S2EndpointDescription::default(), + endpoint_description: EndpointDescription::default(), advertised_nodes: vec![], }); server .allow_pair_once( Arc::new( - NodeConfig::builder(basic_node_description(UUID_A, S2Role::Rm), vec![MessageVersion("v1".into())]) + NodeConfig::builder(basic_node_description(UUID_A, Role::Rm), vec![MessageVersion("v1".into())]) .with_connection_initiate_url("https://example.com/".into()) .build() .unwrap(), @@ -1710,8 +1706,8 @@ mod tests { .header(http::header::CONTENT_TYPE, "application/json") .body(Body::from( serde_json::to_vec(&RequestPairing { - node_description: basic_node_description(UUID_B, S2Role::Cem), - endpoint_description: S2EndpointDescription::default(), + node_description: basic_node_description(UUID_B, Role::Cem), + endpoint_description: EndpointDescription::default(), id: Some(pairing_s2_node_id()), supported_protocols: vec![CommunicationProtocol("HTTP/3".into())], supported_versions: vec![MessageVersion("v0".into())], @@ -1737,7 +1733,7 @@ mod tests { async fn pair_attempt_with_unknown_node() { let server = Server::new(ServerConfig { leaf_certificate: None, - endpoint_description: S2EndpointDescription::default(), + endpoint_description: EndpointDescription::default(), advertised_nodes: vec![], }); @@ -1748,8 +1744,8 @@ mod tests { .header(http::header::CONTENT_TYPE, "application/json") .body(Body::from( serde_json::to_vec(&RequestPairing { - node_description: basic_node_description(UUID_A, S2Role::Cem), - endpoint_description: S2EndpointDescription::default(), + node_description: basic_node_description(UUID_A, Role::Cem), + endpoint_description: EndpointDescription::default(), id: Some(pairing_s2_node_id()), supported_protocols: vec![CommunicationProtocol("WebSocket".into())], supported_versions: vec![MessageVersion("v1".into())], @@ -1774,13 +1770,13 @@ mod tests { async fn pair_attempt_same_role() { let server = Server::new(ServerConfig { leaf_certificate: None, - endpoint_description: S2EndpointDescription::default(), + endpoint_description: EndpointDescription::default(), advertised_nodes: vec![], }); server .allow_pair_once( Arc::new( - NodeConfig::builder(basic_node_description(UUID_A, S2Role::Rm), vec![MessageVersion("v1".into())]) + NodeConfig::builder(basic_node_description(UUID_A, Role::Rm), vec![MessageVersion("v1".into())]) .with_connection_initiate_url("https://example.com/".into()) .build() .unwrap(), @@ -1799,8 +1795,8 @@ mod tests { .header(http::header::CONTENT_TYPE, "application/json") .body(Body::from( serde_json::to_vec(&RequestPairing { - node_description: basic_node_description(UUID_B, S2Role::Rm), - endpoint_description: S2EndpointDescription::default(), + node_description: basic_node_description(UUID_B, Role::Rm), + endpoint_description: EndpointDescription::default(), id: Some(pairing_s2_node_id()), supported_protocols: vec![CommunicationProtocol("WebSocket".into())], supported_versions: vec![MessageVersion("v1".into())], @@ -1825,7 +1821,7 @@ mod tests { async fn request_connection_details() { let server = Server::new(ServerConfig { leaf_certificate: None, - endpoint_description: S2EndpointDescription::default(), + endpoint_description: EndpointDescription::default(), advertised_nodes: vec![], }); let mut attempts = server.state.attempts.lock().unwrap(); @@ -1837,7 +1833,7 @@ mod tests { state: PairingState::Initial(InitialPairingState { session_span: span!(Level::TRACE, "testspan"), config: Arc::new( - NodeConfig::builder(basic_node_description(UUID_A, S2Role::Rm), vec![MessageVersion("v1".into())]) + NodeConfig::builder(basic_node_description(UUID_A, Role::Rm), vec![MessageVersion("v1".into())]) .with_connection_initiate_url("https://example.com/".into()) .build() .unwrap(), @@ -1845,8 +1841,8 @@ mod tests { sender: ResultHandler::Oneshot(Box::new(|_| Box::pin(async { Ok(()) }))), challenge: challenge.clone(), token: PairingToken(b"testtoken".as_slice().into()), - remote_node_description: basic_node_description(UUID_B, S2Role::Cem), - remote_endpoint_description: S2EndpointDescription::default(), + remote_node_description: basic_node_description(UUID_B, Role::Cem), + remote_endpoint_description: EndpointDescription::default(), }), }, ); @@ -1879,7 +1875,7 @@ mod tests { async fn request_connection_details_invalid_response() { let server = Server::new(ServerConfig { leaf_certificate: None, - endpoint_description: S2EndpointDescription::default(), + endpoint_description: EndpointDescription::default(), advertised_nodes: vec![], }); let mut attempts = server.state.attempts.lock().unwrap(); @@ -1891,7 +1887,7 @@ mod tests { state: PairingState::Initial(InitialPairingState { session_span: span!(Level::TRACE, "testspan"), config: Arc::new( - NodeConfig::builder(basic_node_description(UUID_A, S2Role::Rm), vec![MessageVersion("v1".into())]) + NodeConfig::builder(basic_node_description(UUID_A, Role::Rm), vec![MessageVersion("v1".into())]) .with_connection_initiate_url("https://example.com/".into()) .build() .unwrap(), @@ -1899,8 +1895,8 @@ mod tests { sender: ResultHandler::Oneshot(Box::new(|_| Box::pin(async { Ok(()) }))), challenge: challenge.clone(), token: PairingToken(b"testtoken".as_slice().into()), - remote_node_description: basic_node_description(UUID_B, S2Role::Cem), - remote_endpoint_description: S2EndpointDescription::default(), + remote_node_description: basic_node_description(UUID_B, Role::Cem), + remote_endpoint_description: EndpointDescription::default(), }), }, ); @@ -1930,7 +1926,7 @@ mod tests { async fn request_connection_details_too_late() { let server = Server::new(ServerConfig { leaf_certificate: None, - endpoint_description: S2EndpointDescription::default(), + endpoint_description: EndpointDescription::default(), advertised_nodes: vec![], }); let mut attempts = server.state.attempts.lock().unwrap(); @@ -1942,7 +1938,7 @@ mod tests { state: PairingState::Initial(InitialPairingState { session_span: span!(Level::TRACE, "testspan"), config: Arc::new( - NodeConfig::builder(basic_node_description(UUID_A, S2Role::Rm), vec![MessageVersion("v1".into())]) + NodeConfig::builder(basic_node_description(UUID_A, Role::Rm), vec![MessageVersion("v1".into())]) .with_connection_initiate_url("https://example.com/".into()) .build() .unwrap(), @@ -1950,8 +1946,8 @@ mod tests { sender: ResultHandler::Oneshot(Box::new(|_| Box::pin(async { Ok(()) }))), challenge: challenge.clone(), token: PairingToken(b"testtoken".as_slice().into()), - remote_node_description: basic_node_description(UUID_B, S2Role::Cem), - remote_endpoint_description: S2EndpointDescription::default(), + remote_node_description: basic_node_description(UUID_B, Role::Cem), + remote_endpoint_description: EndpointDescription::default(), }), }, ); @@ -1983,7 +1979,7 @@ mod tests { async fn post_connection_details() { let server = Server::new(ServerConfig { leaf_certificate: None, - endpoint_description: S2EndpointDescription::default(), + endpoint_description: EndpointDescription::default(), advertised_nodes: vec![], }); let mut attempts = server.state.attempts.lock().unwrap(); @@ -1995,7 +1991,7 @@ mod tests { state: PairingState::Initial(InitialPairingState { session_span: span!(Level::TRACE, "testspan"), config: Arc::new( - NodeConfig::builder(basic_node_description(UUID_A, S2Role::Rm), vec![MessageVersion("v1".into())]) + NodeConfig::builder(basic_node_description(UUID_A, Role::Rm), vec![MessageVersion("v1".into())]) .with_connection_initiate_url("https://example.com/".into()) .build() .unwrap(), @@ -2003,8 +1999,8 @@ mod tests { sender: ResultHandler::Oneshot(Box::new(|_| Box::pin(async { Ok(()) }))), challenge: challenge.clone(), token: PairingToken(b"testtoken".as_slice().into()), - remote_node_description: basic_node_description(UUID_B, S2Role::Cem), - remote_endpoint_description: S2EndpointDescription::default(), + remote_node_description: basic_node_description(UUID_B, Role::Cem), + remote_endpoint_description: EndpointDescription::default(), }), }, ); @@ -2038,7 +2034,7 @@ mod tests { async fn post_connection_details_invalid_response() { let server = Server::new(ServerConfig { leaf_certificate: None, - endpoint_description: S2EndpointDescription::default(), + endpoint_description: EndpointDescription::default(), advertised_nodes: vec![], }); let mut attempts = server.state.attempts.lock().unwrap(); @@ -2050,7 +2046,7 @@ mod tests { state: PairingState::Initial(InitialPairingState { session_span: span!(Level::TRACE, "testspan"), config: Arc::new( - NodeConfig::builder(basic_node_description(UUID_A, S2Role::Rm), vec![MessageVersion("v1".into())]) + NodeConfig::builder(basic_node_description(UUID_A, Role::Rm), vec![MessageVersion("v1".into())]) .with_connection_initiate_url("https://example.com/".into()) .build() .unwrap(), @@ -2058,8 +2054,8 @@ mod tests { sender: ResultHandler::Oneshot(Box::new(|_| Box::pin(async { Ok(()) }))), challenge: challenge.clone(), token: PairingToken(b"testtoken".as_slice().into()), - remote_node_description: basic_node_description(UUID_B, S2Role::Cem), - remote_endpoint_description: S2EndpointDescription::default(), + remote_node_description: basic_node_description(UUID_B, Role::Cem), + remote_endpoint_description: EndpointDescription::default(), }), }, ); @@ -2093,7 +2089,7 @@ mod tests { async fn post_connection_details_too_late() { let server = Server::new(ServerConfig { leaf_certificate: None, - endpoint_description: S2EndpointDescription::default(), + endpoint_description: EndpointDescription::default(), advertised_nodes: vec![], }); let mut attempts = server.state.attempts.lock().unwrap(); @@ -2105,7 +2101,7 @@ mod tests { state: PairingState::Initial(InitialPairingState { session_span: span!(Level::TRACE, "testspan"), config: Arc::new( - NodeConfig::builder(basic_node_description(UUID_A, S2Role::Rm), vec![MessageVersion("v1".into())]) + NodeConfig::builder(basic_node_description(UUID_A, Role::Rm), vec![MessageVersion("v1".into())]) .with_connection_initiate_url("https://example.com/".into()) .build() .unwrap(), @@ -2113,8 +2109,8 @@ mod tests { sender: ResultHandler::Oneshot(Box::new(|_| Box::pin(async { Ok(()) }))), challenge: challenge.clone(), token: PairingToken(b"testtoken".as_slice().into()), - remote_node_description: basic_node_description(UUID_B, S2Role::Cem), - remote_endpoint_description: S2EndpointDescription::default(), + remote_node_description: basic_node_description(UUID_B, Role::Cem), + remote_endpoint_description: EndpointDescription::default(), }), }, ); @@ -2150,7 +2146,7 @@ mod tests { async fn finalize() { let server = Server::new(ServerConfig { leaf_certificate: None, - endpoint_description: S2EndpointDescription::default(), + endpoint_description: EndpointDescription::default(), advertised_nodes: vec![], }); let mut attempts = server.state.attempts.lock().unwrap(); @@ -2168,8 +2164,8 @@ mod tests { Ok(()) }) })), - remote_node_description: basic_node_description(UUID_B, S2Role::Cem), - remote_endpoint_description: S2EndpointDescription::default(), + remote_node_description: basic_node_description(UUID_B, Role::Cem), + remote_endpoint_description: EndpointDescription::default(), access_token: AccessToken::new(&mut rand::rng()), role: PairingRole::CommunicationServer, }), @@ -2183,7 +2179,7 @@ mod tests { http::Request::post("/v1/finalizePairing") .header(http::header::AUTHORIZATION, "Bearer testid") .header(http::header::CONTENT_TYPE, "application/json") - .body(Body::from(serde_json::to_vec(&true).unwrap())) + .body(Body::from(serde_json::to_vec(&FinalizePairingRequest { success: true }).unwrap())) .unwrap(), ) .await @@ -2198,7 +2194,7 @@ mod tests { async fn finalize_cancel() { let server = Server::new(ServerConfig { leaf_certificate: None, - endpoint_description: S2EndpointDescription::default(), + endpoint_description: EndpointDescription::default(), advertised_nodes: vec![], }); let mut attempts = server.state.attempts.lock().unwrap(); @@ -2216,8 +2212,8 @@ mod tests { Ok(()) }) })), - remote_node_description: basic_node_description(UUID_B, S2Role::Cem), - remote_endpoint_description: S2EndpointDescription::default(), + remote_node_description: basic_node_description(UUID_B, Role::Cem), + remote_endpoint_description: EndpointDescription::default(), access_token: AccessToken::new(&mut rand::rng()), role: PairingRole::CommunicationServer, }), @@ -2231,7 +2227,7 @@ mod tests { http::Request::post("/v1/finalizePairing") .header(http::header::AUTHORIZATION, "Bearer testid") .header(http::header::CONTENT_TYPE, "application/json") - .body(Body::from(serde_json::to_vec(&false).unwrap())) + .body(Body::from(serde_json::to_vec(&FinalizePairingRequest { success: false }).unwrap())) .unwrap(), ) .await @@ -2246,7 +2242,7 @@ mod tests { async fn finalize_cancel_at_intermediate() { let server = Server::new(ServerConfig { leaf_certificate: None, - endpoint_description: S2EndpointDescription::default(), + endpoint_description: EndpointDescription::default(), advertised_nodes: vec![], }); let mut attempts = server.state.attempts.lock().unwrap(); @@ -2259,7 +2255,7 @@ mod tests { state: PairingState::Initial(InitialPairingState { session_span: span!(Level::TRACE, "testspan"), config: Arc::new( - NodeConfig::builder(basic_node_description(UUID_A, S2Role::Rm), vec![MessageVersion("v1".into())]) + NodeConfig::builder(basic_node_description(UUID_A, Role::Rm), vec![MessageVersion("v1".into())]) .with_connection_initiate_url("https://example.com/".into()) .build() .unwrap(), @@ -2272,8 +2268,8 @@ mod tests { })), challenge: challenge.clone(), token: PairingToken(b"testtoken".as_slice().into()), - remote_node_description: basic_node_description(UUID_B, S2Role::Cem), - remote_endpoint_description: S2EndpointDescription::default(), + remote_node_description: basic_node_description(UUID_B, Role::Cem), + remote_endpoint_description: EndpointDescription::default(), }), }, ); @@ -2285,7 +2281,7 @@ mod tests { http::Request::post("/v1/finalizePairing") .header(http::header::AUTHORIZATION, "Bearer testid") .header(http::header::CONTENT_TYPE, "application/json") - .body(Body::from(serde_json::to_vec(&false).unwrap())) + .body(Body::from(serde_json::to_vec(&FinalizePairingRequest { success: false }).unwrap())) .unwrap(), ) .await @@ -2300,7 +2296,7 @@ mod tests { async fn finalize_unknown_session() { let server = Server::new(ServerConfig { leaf_certificate: None, - endpoint_description: S2EndpointDescription::default(), + endpoint_description: EndpointDescription::default(), advertised_nodes: vec![], }); @@ -2310,7 +2306,7 @@ mod tests { http::Request::post("/v1/finalizePairing") .header(http::header::AUTHORIZATION, "Bearer testid") .header(http::header::CONTENT_TYPE, "application/json") - .body(Body::from(serde_json::to_vec(&true).unwrap())) + .body(Body::from(serde_json::to_vec(&FinalizePairingRequest { success: true }).unwrap())) .unwrap(), ) .await @@ -2323,7 +2319,7 @@ mod tests { async fn finalize_cancel_unknown_session() { let server = Server::new(ServerConfig { leaf_certificate: None, - endpoint_description: S2EndpointDescription::default(), + endpoint_description: EndpointDescription::default(), advertised_nodes: vec![], }); @@ -2333,7 +2329,7 @@ mod tests { http::Request::post("/v1/finalizePairing") .header(http::header::AUTHORIZATION, "Bearer testid") .header(http::header::CONTENT_TYPE, "application/json") - .body(Body::from(serde_json::to_vec(&false).unwrap())) + .body(Body::from(serde_json::to_vec(&FinalizePairingRequest { success: false }).unwrap())) .unwrap(), ) .await @@ -2346,7 +2342,7 @@ mod tests { async fn finalize_handler_failed() { let server = Server::new(ServerConfig { leaf_certificate: None, - endpoint_description: S2EndpointDescription::default(), + endpoint_description: EndpointDescription::default(), advertised_nodes: vec![], }); let mut attempts = server.state.attempts.lock().unwrap(); @@ -2364,8 +2360,8 @@ mod tests { Err(()) }) })), - remote_node_description: basic_node_description(UUID_B, S2Role::Cem), - remote_endpoint_description: S2EndpointDescription::default(), + remote_node_description: basic_node_description(UUID_B, Role::Cem), + remote_endpoint_description: EndpointDescription::default(), access_token: AccessToken::new(&mut rand::rng()), role: PairingRole::CommunicationServer, }), @@ -2379,7 +2375,7 @@ mod tests { http::Request::post("/v1/finalizePairing") .header(http::header::AUTHORIZATION, "Bearer testid") .header(http::header::CONTENT_TYPE, "application/json") - .body(Body::from(serde_json::to_vec(&true).unwrap())) + .body(Body::from(serde_json::to_vec(&FinalizePairingRequest { success: true }).unwrap())) .unwrap(), ) .await @@ -2394,7 +2390,7 @@ mod tests { async fn longpolling_timeout() { let mut server = Server::new(ServerConfig { leaf_certificate: None, - endpoint_description: S2EndpointDescription::default(), + endpoint_description: EndpointDescription::default(), advertised_nodes: vec![], }); @@ -2407,9 +2403,9 @@ mod tests { .header(http::header::CONTENT_TYPE, "application/json") .body(Body::from( serde_json::to_vec(&vec![WaitForPairingRequest { - client_s2_node_id: UUID_A.into(), - client_s2_node_description: None, - client_s2_endpoint_description: None, + client_node_id: UUID_A.into(), + clien_node_description: None, + client_endpoint_description: None, error_message: None, }]) .unwrap(), @@ -2425,7 +2421,7 @@ mod tests { async fn longpolling_descriptions() { let mut server = Server::new(ServerConfig { leaf_certificate: None, - endpoint_description: S2EndpointDescription::default(), + endpoint_description: EndpointDescription::default(), advertised_nodes: vec![], }); @@ -2441,9 +2437,9 @@ mod tests { .header(http::header::CONTENT_TYPE, "application/json") .body(Body::from( serde_json::to_vec(&vec![WaitForPairingRequest { - client_s2_node_id: UUID_A.into(), - client_s2_node_description: None, - client_s2_endpoint_description: None, + client_node_id: UUID_A.into(), + clien_node_description: None, + client_endpoint_description: None, error_message: None, }]) .unwrap(), @@ -2455,8 +2451,8 @@ mod tests { assert_eq!(response.status(), StatusCode::OK); let body = response.into_body().collect().await.unwrap().to_bytes(); let response_data: WaitForPairingResponse = serde_json::from_slice(&body).unwrap(); - assert_eq!(response_data.client_s2_node_id, UUID_A.into()); - assert_eq!(response_data.action, WaitForPairingAction::SendS2NodeDescription); + assert_eq!(response_data.client_node_id, UUID_A.into()); + assert_eq!(response_data.action, WaitForPairingAction::SendNodeDescription); server_clone .get_router() @@ -2465,9 +2461,9 @@ mod tests { .header(http::header::CONTENT_TYPE, "application/json") .body(Body::from( serde_json::to_vec(&vec![WaitForPairingRequest { - client_s2_node_id: UUID_A.into(), - client_s2_node_description: Some(basic_node_description(UUID_A, S2Role::Cem)), - client_s2_endpoint_description: Some(S2EndpointDescription::default()), + client_node_id: UUID_A.into(), + clien_node_description: Some(basic_node_description(UUID_A, Role::Cem)), + client_endpoint_description: Some(EndpointDescription::default()), error_message: None, }]) .unwrap(), @@ -2482,11 +2478,11 @@ mod tests { let mut longpolling_handle = server.get_longpolling().await; assert_eq!( longpolling_handle.node_description().await.unwrap(), - basic_node_description(UUID_A, S2Role::Cem) + basic_node_description(UUID_A, Role::Cem) ); assert_eq!( longpolling_handle.endpoint_description().await.unwrap(), - S2EndpointDescription::default() + EndpointDescription::default() ); }; @@ -2497,7 +2493,7 @@ mod tests { async fn longpolling_prepare_pairing() { let mut server = Server::new(ServerConfig { leaf_certificate: None, - endpoint_description: S2EndpointDescription::default(), + endpoint_description: EndpointDescription::default(), advertised_nodes: vec![], }); @@ -2513,9 +2509,9 @@ mod tests { .header(http::header::CONTENT_TYPE, "application/json") .body(Body::from( serde_json::to_vec(&vec![WaitForPairingRequest { - client_s2_node_id: UUID_A.into(), - client_s2_node_description: None, - client_s2_endpoint_description: None, + client_node_id: UUID_A.into(), + clien_node_description: None, + client_endpoint_description: None, error_message: None, }]) .unwrap(), @@ -2527,7 +2523,7 @@ mod tests { assert_eq!(response.status(), StatusCode::OK); let body = response.into_body().collect().await.unwrap().to_bytes(); let response_data: WaitForPairingResponse = serde_json::from_slice(&body).unwrap(); - assert_eq!(response_data.client_s2_node_id, UUID_A.into()); + assert_eq!(response_data.client_node_id, UUID_A.into()); assert_eq!(response_data.action, WaitForPairingAction::PreparePairing); server_clone @@ -2537,9 +2533,9 @@ mod tests { .header(http::header::CONTENT_TYPE, "application/json") .body(Body::from( serde_json::to_vec(&vec![WaitForPairingRequest { - client_s2_node_id: UUID_A.into(), - client_s2_node_description: None, - client_s2_endpoint_description: None, + client_node_id: UUID_A.into(), + clien_node_description: None, + client_endpoint_description: None, error_message: None, }]) .unwrap(), @@ -2562,7 +2558,7 @@ mod tests { async fn longpolling_cancel_prepare_pairing() { let mut server = Server::new(ServerConfig { leaf_certificate: None, - endpoint_description: S2EndpointDescription::default(), + endpoint_description: EndpointDescription::default(), advertised_nodes: vec![], }); @@ -2578,9 +2574,9 @@ mod tests { .header(http::header::CONTENT_TYPE, "application/json") .body(Body::from( serde_json::to_vec(&vec![WaitForPairingRequest { - client_s2_node_id: UUID_A.into(), - client_s2_node_description: None, - client_s2_endpoint_description: None, + client_node_id: UUID_A.into(), + clien_node_description: None, + client_endpoint_description: None, error_message: None, }]) .unwrap(), @@ -2592,7 +2588,7 @@ mod tests { assert_eq!(response.status(), StatusCode::OK); let body = response.into_body().collect().await.unwrap().to_bytes(); let response_data: WaitForPairingResponse = serde_json::from_slice(&body).unwrap(); - assert_eq!(response_data.client_s2_node_id, UUID_A.into()); + assert_eq!(response_data.client_node_id, UUID_A.into()); assert_eq!(response_data.action, WaitForPairingAction::CancelPreparePairing); server_clone @@ -2602,9 +2598,9 @@ mod tests { .header(http::header::CONTENT_TYPE, "application/json") .body(Body::from( serde_json::to_vec(&vec![WaitForPairingRequest { - client_s2_node_id: UUID_A.into(), - client_s2_node_description: None, - client_s2_endpoint_description: None, + client_node_id: UUID_A.into(), + clien_node_description: None, + client_endpoint_description: None, error_message: None, }]) .unwrap(), @@ -2627,7 +2623,7 @@ mod tests { async fn longpolling_request_pairing_success() { let mut server = Server::new(ServerConfig { leaf_certificate: None, - endpoint_description: S2EndpointDescription::default(), + endpoint_description: EndpointDescription::default(), advertised_nodes: vec![], }); @@ -2643,9 +2639,9 @@ mod tests { .header(http::header::CONTENT_TYPE, "application/json") .body(Body::from( serde_json::to_vec(&vec![WaitForPairingRequest { - client_s2_node_id: UUID_A.into(), - client_s2_node_description: None, - client_s2_endpoint_description: None, + client_node_id: UUID_A.into(), + clien_node_description: None, + client_endpoint_description: None, error_message: None, }]) .unwrap(), @@ -2657,7 +2653,7 @@ mod tests { assert_eq!(response.status(), StatusCode::OK); let body = response.into_body().collect().await.unwrap().to_bytes(); let response_data: WaitForPairingResponse = serde_json::from_slice(&body).unwrap(); - assert_eq!(response_data.client_s2_node_id, UUID_A.into()); + assert_eq!(response_data.client_node_id, UUID_A.into()); assert_eq!(response_data.action, WaitForPairingAction::RequestPairing); let poll_req = server_clone.get_router().oneshot( @@ -2665,9 +2661,9 @@ mod tests { .header(http::header::CONTENT_TYPE, "application/json") .body(Body::from( serde_json::to_vec(&vec![WaitForPairingRequest { - client_s2_node_id: UUID_A.into(), - client_s2_node_description: None, - client_s2_endpoint_description: None, + client_node_id: UUID_A.into(), + clien_node_description: None, + client_endpoint_description: None, error_message: None, }]) .unwrap(), @@ -2679,8 +2675,8 @@ mod tests { .header(http::header::CONTENT_TYPE, "application/json") .body(Body::from( serde_json::to_vec(&RequestPairing { - node_description: basic_node_description(UUID_A, S2Role::Cem), - endpoint_description: S2EndpointDescription::default(), + node_description: basic_node_description(UUID_A, Role::Cem), + endpoint_description: EndpointDescription::default(), id: Some(pairing_s2_node_id()), supported_protocols: vec![CommunicationProtocol("WebSocket".into())], supported_versions: vec![MessageVersion("v1".into())], @@ -2708,7 +2704,7 @@ mod tests { async fn longpolling_request_pairing_failure() { let mut server = Server::new(ServerConfig { leaf_certificate: None, - endpoint_description: S2EndpointDescription::default(), + endpoint_description: EndpointDescription::default(), advertised_nodes: vec![], }); @@ -2724,9 +2720,9 @@ mod tests { .header(http::header::CONTENT_TYPE, "application/json") .body(Body::from( serde_json::to_vec(&vec![WaitForPairingRequest { - client_s2_node_id: UUID_A.into(), - client_s2_node_description: None, - client_s2_endpoint_description: None, + client_node_id: UUID_A.into(), + clien_node_description: None, + client_endpoint_description: None, error_message: None, }]) .unwrap(), @@ -2738,7 +2734,7 @@ mod tests { assert_eq!(response.status(), StatusCode::OK); let body = response.into_body().collect().await.unwrap().to_bytes(); let response_data: WaitForPairingResponse = serde_json::from_slice(&body).unwrap(); - assert_eq!(response_data.client_s2_node_id, UUID_A.into()); + assert_eq!(response_data.client_node_id, UUID_A.into()); assert_eq!(response_data.action, WaitForPairingAction::RequestPairing); server_clone @@ -2748,9 +2744,9 @@ mod tests { .header(http::header::CONTENT_TYPE, "application/json") .body(Body::from( serde_json::to_vec(&vec![WaitForPairingRequest { - client_s2_node_id: UUID_A.into(), - client_s2_node_description: None, - client_s2_endpoint_description: None, + client_node_id: UUID_A.into(), + clien_node_description: None, + client_endpoint_description: None, error_message: Some(WaitForPairingErrorMessage::NoValidTokenOnPairingClient), }]) .unwrap(), @@ -2776,7 +2772,7 @@ mod tests { async fn longpolling_aborted_request_keeps_session_alive() { let mut server = Server::new(ServerConfig { leaf_certificate: None, - endpoint_description: S2EndpointDescription::default(), + endpoint_description: EndpointDescription::default(), advertised_nodes: vec![], }); @@ -2793,9 +2789,9 @@ mod tests { .header(http::header::CONTENT_TYPE, "application/json") .body(Body::from( serde_json::to_vec(&vec![WaitForPairingRequest { - client_s2_node_id: UUID_A.into(), - client_s2_node_description: None, - client_s2_endpoint_description: None, + client_node_id: UUID_A.into(), + clien_node_description: None, + client_endpoint_description: None, error_message: None, }]) .unwrap(), @@ -2813,9 +2809,9 @@ mod tests { .header(http::header::CONTENT_TYPE, "application/json") .body(Body::from( serde_json::to_vec(&vec![WaitForPairingRequest { - client_s2_node_id: UUID_A.into(), - client_s2_node_description: None, - client_s2_endpoint_description: None, + client_node_id: UUID_A.into(), + clien_node_description: None, + client_endpoint_description: None, error_message: None, }]) .unwrap(), @@ -2827,8 +2823,8 @@ mod tests { assert_eq!(response.status(), StatusCode::OK); let body = response.into_body().collect().await.unwrap().to_bytes(); let response_data: WaitForPairingResponse = serde_json::from_slice(&body).unwrap(); - assert_eq!(response_data.client_s2_node_id, UUID_A.into()); - assert_eq!(response_data.action, WaitForPairingAction::SendS2NodeDescription); + assert_eq!(response_data.client_node_id, UUID_A.into()); + assert_eq!(response_data.action, WaitForPairingAction::SendNodeDescription); server_clone .get_router() @@ -2837,9 +2833,9 @@ mod tests { .header(http::header::CONTENT_TYPE, "application/json") .body(Body::from( serde_json::to_vec(&vec![WaitForPairingRequest { - client_s2_node_id: UUID_A.into(), - client_s2_node_description: Some(basic_node_description(UUID_A, S2Role::Cem)), - client_s2_endpoint_description: Some(S2EndpointDescription::default()), + client_node_id: UUID_A.into(), + clien_node_description: Some(basic_node_description(UUID_A, Role::Cem)), + client_endpoint_description: Some(EndpointDescription::default()), error_message: None, }]) .unwrap(), @@ -2855,11 +2851,11 @@ mod tests { sleep(Duration::from_secs(10)).await; assert_eq!( longpolling_handle.node_description().await.unwrap(), - basic_node_description(UUID_A, S2Role::Cem) + basic_node_description(UUID_A, Role::Cem) ); assert_eq!( longpolling_handle.endpoint_description().await.unwrap(), - S2EndpointDescription::default() + EndpointDescription::default() ); }; @@ -2869,7 +2865,7 @@ mod tests { async fn longpolling_disable_during_request() { let mut server = Server::new(ServerConfig { leaf_certificate: None, - endpoint_description: S2EndpointDescription::default(), + endpoint_description: EndpointDescription::default(), advertised_nodes: vec![], }); @@ -2885,9 +2881,9 @@ mod tests { .header(http::header::CONTENT_TYPE, "application/json") .body(Body::from( serde_json::to_vec(&vec![WaitForPairingRequest { - client_s2_node_id: UUID_A.into(), - client_s2_node_description: None, - client_s2_endpoint_description: None, + client_node_id: UUID_A.into(), + clien_node_description: None, + client_endpoint_description: None, error_message: None, }]) .unwrap(), diff --git a/s2energy-connection/src/pairing/wire.rs b/s2energy-connection/src/pairing/wire.rs index 0fa617b..f5bd5f2 100644 --- a/s2energy-connection/src/pairing/wire.rs +++ b/s2energy-connection/src/pairing/wire.rs @@ -8,11 +8,12 @@ use thiserror::Error; use tracing::info; use crate::{ - S2NodeId, - common::wire::{AccessToken, CommunicationProtocol, MessageVersion, S2EndpointDescription, S2NodeDescription}, + NodeId, + common::wire::{AccessToken, CommunicationProtocol, EndpointDescription, MessageVersion, NodeDescription}, }; #[derive(Error, Debug, Serialize, Deserialize, PartialEq, Eq, Hash, Clone, Copy)] +#[serde(tag = "errorMessage")] pub(crate) enum PairingResponseErrorMessage { #[error("Invalid combination of roles")] InvalidCombinationOfRoles, @@ -60,6 +61,7 @@ impl IntoResponse for PairingResponseErrorMessage { } #[derive(Error, Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)] +#[serde(tag = "errorMessage")] pub(crate) enum WaitForPairingErrorMessage { #[error("No valid token available on remote.")] NoValidTokenOnPairingClient, @@ -106,16 +108,16 @@ impl PartialEq for HmacChallengeResponse { /// It is used as a short identifier (since the user might have to type it in manually) /// for the S2Node, which can be used to lookup the actual [`S2NodeId`]. #[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub struct PairingS2NodeId(pub String); +pub struct NodeIdAlias(pub String); -impl PairingS2NodeId { +impl NodeIdAlias { /// Create a new id. pub fn new(rng: &mut impl rand::CryptoRng) -> Self { Self(Alphanumeric.sample_string(rng, 12)) } } -impl std::fmt::Display for PairingS2NodeId { +impl std::fmt::Display for NodeIdAlias { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { self.0.fmt(f) } @@ -123,14 +125,14 @@ impl std::fmt::Display for PairingS2NodeId { #[derive(Serialize, Deserialize)] pub(crate) struct RequestPairing { - #[serde(rename = "clientS2NodeDescription")] - pub node_description: S2NodeDescription, - #[serde(rename = "clientS2EndpointDescription")] - pub endpoint_description: S2EndpointDescription, + #[serde(rename = "clientNodeDescription")] + pub node_description: NodeDescription, + #[serde(rename = "clientEndpointDescription")] + pub endpoint_description: EndpointDescription, /// A server-assigned identifier of the S2Node that this server represents. - #[serde(rename = "pairingS2NodeId")] + #[serde(rename = "nodeIdAlias")] #[serde(default)] - pub id: Option, + pub id: Option, #[serde(rename = "supportedCommunicationProtocols")] pub supported_protocols: Vec, /// The versions of the S2 JSON message schemas this S2Node implementation currently supports. @@ -196,8 +198,8 @@ impl FromRequestParts for PairingAttemptId { #[serde(rename_all = "camelCase")] pub(crate) struct RequestPairingResponse { pub pairing_attempt_id: PairingAttemptId, - pub server_s2_node_description: S2NodeDescription, - pub server_s2_endpoint_description: S2EndpointDescription, + pub server_node_description: NodeDescription, + pub server_endpoint_description: EndpointDescription, pub selected_hmac_hashing_algorithm: HmacHashingAlgorithm, pub client_hmac_challenge_response: HmacChallengeResponse, pub server_hmac_challenge: HmacChallenge, @@ -212,20 +214,18 @@ pub(crate) struct RequestConnectionDetailsRequest { #[derive(Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub(crate) struct PrePairingRequest { - pub client_s2_endpoint_description: S2EndpointDescription, - pub client_s2_node_description: S2NodeDescription, - // TODO: Update to Pairing S2 Node ID - #[serde(rename = "serverS2PairingNodeId")] - pub server_id: Option, + pub client_endpoint_description: EndpointDescription, + pub client_node_description: NodeDescription, + #[serde(rename = "serverNodeId")] + pub server_id: Option, } #[derive(Serialize, Deserialize)] pub(crate) struct CancelPrePairingRequest { - #[serde(rename = "clientS2NodeId")] - pub client_id: S2NodeId, - // TODO: Update to Pairing S2 Node ID - #[serde(rename = "serverS2PairingNodeId")] - pub server_id: Option, + #[serde(rename = "clientNodeId")] + pub client_id: NodeId, + #[serde(rename = "serverNodeId")] + pub server_id: Option, } /// Details the Connection client needs to set up an S2 session. @@ -246,16 +246,22 @@ pub(crate) struct PostConnectionDetailsRequest { #[derive(Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub(crate) struct WaitForPairingRequest { - pub client_s2_node_id: S2NodeId, - pub client_s2_node_description: Option, - pub client_s2_endpoint_description: Option, + pub client_node_id: NodeId, + pub clien_node_description: Option, + pub client_endpoint_description: Option, + #[serde(flatten)] pub error_message: Option, } +#[derive(Serialize, Deserialize)] +pub(crate) struct FinalizePairingRequest { + pub success: bool, +} + #[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Hash)] #[serde(rename_all = "camelCase")] pub(crate) enum WaitForPairingAction { - SendS2NodeDescription, + SendNodeDescription, PreparePairing, CancelPreparePairing, RequestPairing, @@ -264,7 +270,7 @@ pub(crate) enum WaitForPairingAction { #[derive(Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub(crate) struct WaitForPairingResponse { - pub client_s2_node_id: S2NodeId, + pub client_node_id: NodeId, pub action: WaitForPairingAction, }