use core::fmt;
use oxicode::{Decode, Encode};
use serde::{Deserialize, Serialize};
use crate::auth::AuthToken;
use crate::handshake::features::FeatureFlags;
use crate::handshake::limits::NegotiatedLimits;
use crate::handshake::role::Role;
use crate::ids::SessionId;
use crate::version::{AstrsVersion, MIN_SUPPORTED_PROTOCOL, PROTOCOL_VERSION};
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Encode, Decode)]
pub struct Hello {
pub protocol: u16,
pub astrs_version: AstrsVersion,
pub role: Role,
pub auth: AuthToken,
pub features: FeatureFlags,
pub limits: NegotiatedLimits,
pub resume: Option<SessionId>,
pub label: Option<String>,
}
impl Hello {
#[must_use]
pub fn new(role: Role, auth: AuthToken) -> Self {
Self {
protocol: PROTOCOL_VERSION,
astrs_version: AstrsVersion::current(),
role,
auth,
features: FeatureFlags::EMPTY,
limits: NegotiatedLimits::new(),
resume: None,
label: None,
}
}
#[must_use]
pub const fn with_features(mut self, features: FeatureFlags) -> Self {
self.features = features;
self
}
#[must_use]
pub const fn with_limits(mut self, limits: NegotiatedLimits) -> Self {
self.limits = limits;
self
}
#[must_use]
pub const fn with_resume(mut self, session: SessionId) -> Self {
self.resume = Some(session);
self
}
#[must_use]
pub fn with_label(mut self, label: impl Into<String>) -> Self {
self.label = Some(label.into());
self
}
#[must_use]
pub const fn with_protocol(mut self, protocol: u16) -> Self {
self.protocol = protocol;
self
}
#[must_use]
pub const fn is_resume(&self) -> bool {
self.resume.is_some()
}
#[must_use]
pub fn display_name(&self) -> &str {
self.label.as_deref().unwrap_or_else(|| self.role.as_str())
}
}
impl fmt::Display for Hello {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"hello from {} ({}, protocol {}, astrs {}, features {})",
self.display_name(),
self.role,
self.protocol,
self.astrs_version,
self.features
)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Encode, Decode)]
pub struct Welcome {
pub protocol: u16,
pub limits: NegotiatedLimits,
pub session_id: SessionId,
pub features: FeatureFlags,
pub peer_role: Role,
pub astrs_version: AstrsVersion,
pub resumed: bool,
}
impl Welcome {
#[must_use]
pub fn new(
protocol: u16,
limits: NegotiatedLimits,
session_id: SessionId,
peer_role: Role,
) -> Self {
Self {
protocol,
limits,
session_id,
features: FeatureFlags::EMPTY,
peer_role,
astrs_version: AstrsVersion::current(),
resumed: false,
}
}
#[must_use]
pub const fn with_features(mut self, features: FeatureFlags) -> Self {
self.features = features;
self
}
#[must_use]
pub const fn with_resumed(mut self, resumed: bool) -> Self {
self.resumed = resumed;
self
}
#[must_use]
pub const fn protocol_is_supported(&self) -> bool {
self.protocol >= MIN_SUPPORTED_PROTOCOL && self.protocol <= PROTOCOL_VERSION
}
}
impl fmt::Display for Welcome {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"welcome to session {} as {} (protocol {}, features {}{})",
self.session_id,
self.peer_role,
self.protocol,
self.features,
if self.resumed { ", resumed" } else { "" }
)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Encode, Decode)]
pub struct Refused {
pub max_protocol: u16,
pub min_protocol: u16,
pub reason: RefusalReason,
}
impl Refused {
#[must_use]
pub const fn new(reason: RefusalReason) -> Self {
Self {
max_protocol: PROTOCOL_VERSION,
min_protocol: MIN_SUPPORTED_PROTOCOL,
reason,
}
}
#[must_use]
pub const fn protocol_too_old(peer: u16, min_protocol: u16, max_protocol: u16) -> Self {
Self {
max_protocol,
min_protocol,
reason: RefusalReason::ProtocolTooOld {
peer,
minimum: min_protocol,
},
}
}
#[must_use]
pub const fn is_version_problem(&self) -> bool {
matches!(self.reason, RefusalReason::ProtocolTooOld { .. })
}
#[must_use]
pub const fn retry_protocol(&self) -> Option<u16> {
if !self.is_version_problem() {
return None;
}
let candidate = if self.max_protocol < PROTOCOL_VERSION {
self.max_protocol
} else {
PROTOCOL_VERSION
};
if candidate < self.min_protocol || candidate < MIN_SUPPORTED_PROTOCOL {
None
} else {
Some(candidate)
}
}
}
impl fmt::Display for Refused {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{} (peer speaks protocol {}–{})",
self.reason, self.min_protocol, self.max_protocol
)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Encode, Decode)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum RefusalReason {
#[oxicode(variant = 0)]
ProtocolTooOld {
peer: u16,
minimum: u16,
},
#[oxicode(variant = 1)]
BadAuth,
#[oxicode(variant = 2)]
RoleNotPermitted {
role: Role,
},
#[oxicode(variant = 3)]
TooManyConnections {
limit: u32,
},
#[oxicode(variant = 4)]
ShuttingDown,
#[oxicode(variant = 5)]
UnknownSession {
session: SessionId,
},
#[oxicode(variant = 6)]
LimitsUnacceptable {
message: String,
},
#[oxicode(variant = 7)]
Internal {
message: String,
},
}
impl RefusalReason {
#[must_use]
pub const fn is_retryable(&self) -> bool {
matches!(
self,
Self::TooManyConnections { .. } | Self::ShuttingDown | Self::Internal { .. }
)
}
#[must_use]
pub const fn kind_name(&self) -> &'static str {
match self {
Self::ProtocolTooOld { .. } => "protocol_too_old",
Self::BadAuth => "bad_auth",
Self::RoleNotPermitted { .. } => "role_not_permitted",
Self::TooManyConnections { .. } => "too_many_connections",
Self::ShuttingDown => "shutting_down",
Self::UnknownSession { .. } => "unknown_session",
Self::LimitsUnacceptable { .. } => "limits_unacceptable",
Self::Internal { .. } => "internal",
}
}
}
impl fmt::Display for RefusalReason {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::ProtocolTooOld { peer, minimum } => write!(
f,
"protocol {peer} is below the minimum supported protocol {minimum}"
),
Self::BadAuth => f.write_str("authentication failed"),
Self::RoleNotPermitted { role } => write!(f, "role {role} is not accepted here"),
Self::TooManyConnections { limit } => {
write!(f, "connection limit of {limit} reached")
}
Self::ShuttingDown => f.write_str("peer is shutting down"),
Self::UnknownSession { session } => write!(f, "session {session} cannot be resumed"),
Self::LimitsUnacceptable { message } => write!(f, "limits unacceptable: {message}"),
Self::Internal { message } => write!(f, "internal error: {message}"),
}
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::*;
use crate::codec::{WireEncode, round_trip};
fn hello() -> Hello {
Hello::new(Role::Node, AuthToken::from_bytes([7; 32]))
.with_features(FeatureFlags::SHM_ZERO_COPY | FeatureFlags::TRACING)
.with_limits(NegotiatedLimits::uds().with_max_payload_bytes(1 << 20))
.with_label("camera")
}
#[test]
fn hello_defaults_to_this_builds_protocol_and_version() {
let hello = Hello::new(Role::Cli, AuthToken::ZERO);
assert_eq!(hello.protocol, PROTOCOL_VERSION);
assert_eq!(hello.astrs_version, AstrsVersion::current());
assert_eq!(hello.features, FeatureFlags::EMPTY);
assert_eq!(hello.limits, NegotiatedLimits::new());
assert!(!hello.is_resume());
assert_eq!(hello.display_name(), "cli");
}
#[test]
fn hello_builders_set_exactly_what_they_name() {
let session = SessionId::from_u128(9);
let hello = hello().with_resume(session).with_protocol(3);
assert_eq!(hello.protocol, 3);
assert_eq!(hello.resume, Some(session));
assert!(hello.is_resume());
assert_eq!(hello.display_name(), "camera");
assert_eq!(hello.role, Role::Node);
}
#[test]
fn every_handshake_message_round_trips() {
let hello = hello();
assert_eq!(round_trip(&hello).unwrap(), hello);
let welcome = Welcome::new(
1,
NegotiatedLimits::network(),
SessionId::from_u128(4),
Role::Daemon,
)
.with_features(FeatureFlags::SHM_ZERO_COPY)
.with_resumed(true);
assert_eq!(round_trip(&welcome).unwrap(), welcome);
let refused = Refused::protocol_too_old(1, 2, 3);
assert_eq!(round_trip(&refused).unwrap(), refused);
}
#[test]
fn a_hello_never_reveals_its_token_in_debug_or_display() {
let hello = hello();
let debug = format!("{hello:?}");
let display = hello.to_string();
let secret = AuthToken::from_bytes([7; 32]).reveal_hex();
assert!(!debug.contains(&secret), "Debug leaked the token");
assert!(!display.contains(&secret), "Display leaked the token");
assert!(debug.contains("redacted"));
}
#[test]
fn refusal_reason_indices_are_frozen() {
let reasons = [
RefusalReason::ProtocolTooOld {
peer: 1,
minimum: 2,
},
RefusalReason::BadAuth,
RefusalReason::RoleNotPermitted { role: Role::Node },
RefusalReason::TooManyConnections { limit: 4 },
RefusalReason::ShuttingDown,
RefusalReason::UnknownSession {
session: SessionId::from_u128(2),
},
RefusalReason::LimitsUnacceptable {
message: "too small".to_owned(),
},
RefusalReason::Internal {
message: "boom".to_owned(),
},
];
for (index, reason) in reasons.into_iter().enumerate() {
let bytes = reason.encode_to_vec().unwrap();
assert_eq!(usize::from(bytes[0]), index, "{reason:?} moved");
assert_eq!(round_trip(&reason).unwrap(), reason);
assert!(!reason.kind_name().is_empty());
assert!(!reason.to_string().is_empty());
}
}
#[test]
fn only_transient_refusals_are_retryable() {
assert!(RefusalReason::ShuttingDown.is_retryable());
assert!(RefusalReason::TooManyConnections { limit: 1 }.is_retryable());
assert!(
RefusalReason::Internal {
message: String::new()
}
.is_retryable()
);
assert!(!RefusalReason::BadAuth.is_retryable());
assert!(
!RefusalReason::ProtocolTooOld {
peer: 1,
minimum: 2
}
.is_retryable()
);
}
#[test]
fn a_bad_auth_refusal_carries_no_detail() {
let refused = Refused::new(RefusalReason::BadAuth);
assert_eq!(refused.reason, RefusalReason::BadAuth);
assert_eq!(refused.max_protocol, PROTOCOL_VERSION);
assert_eq!(refused.min_protocol, MIN_SUPPORTED_PROTOCOL);
assert!(!refused.is_version_problem());
assert_eq!(refused.retry_protocol(), None);
}
#[test]
fn retry_protocol_picks_the_highest_mutually_known_version() {
let refused = Refused::protocol_too_old(0, PROTOCOL_VERSION, PROTOCOL_VERSION + 5);
assert_eq!(refused.retry_protocol(), Some(PROTOCOL_VERSION));
let older = Refused {
max_protocol: PROTOCOL_VERSION,
min_protocol: MIN_SUPPORTED_PROTOCOL,
reason: RefusalReason::ProtocolTooOld {
peer: PROTOCOL_VERSION,
minimum: MIN_SUPPORTED_PROTOCOL,
},
};
assert_eq!(older.retry_protocol(), Some(PROTOCOL_VERSION));
let hopeless = Refused::protocol_too_old(1, PROTOCOL_VERSION + 1, PROTOCOL_VERSION + 2);
assert_eq!(hopeless.retry_protocol(), None);
}
#[test]
fn welcome_validates_the_protocol_it_reports() {
let good = Welcome::new(
PROTOCOL_VERSION,
NegotiatedLimits::uds(),
SessionId::NIL,
Role::Daemon,
);
assert!(good.protocol_is_supported());
let impossible = Welcome::new(
PROTOCOL_VERSION + 1,
NegotiatedLimits::uds(),
SessionId::NIL,
Role::Daemon,
);
assert!(!impossible.protocol_is_supported());
}
#[test]
fn display_forms_are_informative() {
assert!(hello().to_string().contains("camera"));
let welcome = Welcome::new(
1,
NegotiatedLimits::uds(),
SessionId::from_u128(1),
Role::Daemon,
)
.with_resumed(true);
assert!(welcome.to_string().contains("resumed"));
assert!(
Refused::protocol_too_old(1, 2, 3)
.to_string()
.contains("2–3")
);
}
#[test]
fn serde_round_trips_the_handshake_for_diagnostics() {
let json = serde_json::to_string(&hello()).unwrap();
assert_eq!(serde_json::from_str::<Hello>(&json).unwrap(), hello());
}
}