use alloc::string::String;
use alloc::sync::Arc;
use alloc::vec::Vec;
use crate::connect::proto::{
AccessToken, COMMUNICATION_TOKEN_LIFETIME, CommunicationDetails, CommunicationToken,
ConnectError, SessionErrorMessage, SessionGrant, SessionInitServer, SessionRefused,
SessionRequest, TokenStore, UnpairRequest,
};
use super::store::{PairingKey, Store};
use crate::types::{ProtocolVersion, Timestamp};
pub struct SessionService {
store: Arc<dyn Store>,
websocket_url: String,
s2_message_versions: Vec<ProtocolVersion>,
issued: std::sync::Mutex<Vec<IssuedConnection>>,
rotation: std::sync::Mutex<()>,
live: std::sync::Mutex<Vec<LiveEntry>>,
next_live: core::sync::atomic::AtomicU64,
}
#[derive(Debug)]
struct IssuedConnection {
key: PairingKey,
token: CommunicationToken,
issued: Timestamp,
}
#[derive(Debug)]
struct LiveEntry {
key: PairingKey,
id: u64,
end: tokio::sync::watch::Sender<bool>,
}
#[derive(Debug)]
pub struct LiveSession {
key: PairingKey,
id: u64,
end: tokio::sync::watch::Receiver<bool>,
service: alloc::sync::Weak<SessionService>,
}
impl LiveSession {
#[must_use]
pub const fn key(&self) -> PairingKey {
self.key
}
pub async fn ended(&mut self) {
let _ = self.end.wait_for(|ended| *ended).await;
}
#[must_use]
pub fn is_ended(&self) -> bool {
*self.end.borrow()
}
pub(super) fn watch(&self) -> tokio::sync::watch::Receiver<bool> {
self.end.clone()
}
}
impl Drop for LiveSession {
fn drop(&mut self) {
if let Some(service) = self.service.upgrade()
&& let Ok(mut live) = service.live.lock()
{
live.retain(|entry| entry.id != self.id);
}
}
}
impl core::fmt::Debug for SessionService {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("SessionService")
.field("websocket_url", &self.websocket_url)
.field("s2_message_versions", &self.s2_message_versions)
.finish_non_exhaustive()
}
}
impl SessionService {
#[must_use]
pub fn new(store: Arc<dyn Store>, websocket_url: impl Into<String>) -> Self {
Self {
store,
websocket_url: websocket_url.into(),
s2_message_versions: alloc::vec![
crate::types::WireProfile::V1_0_0.connect_version(),
crate::types::WireProfile::V0_0_2Beta.connect_version(),
],
issued: std::sync::Mutex::new(Vec::new()),
rotation: std::sync::Mutex::new(()),
live: std::sync::Mutex::new(Vec::new()),
next_live: core::sync::atomic::AtomicU64::new(0),
}
}
#[must_use]
pub fn with_s2_message_versions(mut self, versions: Vec<ProtocolVersion>) -> Self {
self.s2_message_versions = versions;
self
}
#[must_use]
pub fn store(&self) -> &Arc<dyn Store> {
&self.store
}
fn machine(&self, key: PairingKey) -> Option<(bool, SessionInitServer)> {
let paired = self.store.paired(key)?;
Some((
paired.revoked,
SessionInitServer::new(key.local, key.remote, paired.tokens, &self.websocket_url)
.with_s2_message_versions(self.s2_message_versions.clone()),
))
}
pub fn initiate_session(
&self,
bearer: &AccessToken,
request: &SessionRequest,
access_entropy: &[u8],
now: Timestamp,
) -> Result<SessionGrant, ConnectError> {
let key = PairingKey {
local: request.server_node_id,
remote: request.client_node_id,
};
let _rotation = self.rotation.lock().map_err(|_| ConnectError::NotPaired)?;
let (revoked, mut machine) = self.machine(key).ok_or(ConnectError::NotPaired)?;
if revoked {
if !machine.authenticates(bearer) {
return Err(ConnectError::NotPaired);
}
self.store.unpair(key);
return Err(ConnectError::SessionRefused(SessionRefused {
error_message: SessionErrorMessage::NoLongerPaired,
additional_info: None,
}));
}
let mut grant = machine.initiate_session(bearer, request, access_entropy, now)?;
self.store.set_tokens(key, machine.tokens().clone());
grant.server_node_description = self.store.node(key.local);
Ok(grant)
}
pub fn confirm_access_token(
&self,
bearer: &AccessToken,
communication_entropy: &[u8],
now: Timestamp,
) -> Result<(PairingKey, CommunicationDetails), ConnectError> {
let details = {
let _rotation = self.rotation.lock().map_err(|_| ConnectError::NotPaired)?;
let key = self
.store
.pairing_for_token(bearer)
.ok_or(ConnectError::NotPaired)?;
let (_, mut machine) = self.machine(key).ok_or(ConnectError::NotPaired)?;
let details = machine.confirm_access_token(bearer, communication_entropy, now)?;
self.store.set_tokens(key, machine.tokens().clone());
(key, details)
};
let (key, details) = details;
let CommunicationDetails::WebSocket {
websocket_token, ..
} = &details;
if let Ok(mut issued) = self.issued.lock() {
issued.retain(|entry| {
now.saturating_duration_since(entry.issued) < COMMUNICATION_TOKEN_LIFETIME
&& entry.key != key
});
issued.push(IssuedConnection {
key,
token: websocket_token.clone(),
issued: now,
});
}
Ok((key, details))
}
pub fn authorize_connection(&self, presented: &str, now: Timestamp) -> Option<PairingKey> {
let mut issued = self.issued.lock().ok()?;
issued.retain(|entry| {
now.saturating_duration_since(entry.issued) < COMMUNICATION_TOKEN_LIFETIME
});
let mut found = None;
for (index, entry) in issued.iter().enumerate() {
if entry.token.verify_str(presented) {
found = Some((index, entry.key));
}
}
let (index, key) = found?;
issued.remove(index);
Some(key)
}
#[must_use]
pub fn pending_connections(&self) -> usize {
self.issued.lock().map_or(0, |issued| issued.len())
}
#[must_use]
pub fn register_session(self: &Arc<Self>, key: PairingKey) -> LiveSession {
let id = self
.next_live
.fetch_add(1, core::sync::atomic::Ordering::Relaxed);
let (end, watch) = tokio::sync::watch::channel(false);
if let Ok(mut live) = self.live.lock() {
live.push(LiveEntry { key, id, end });
}
LiveSession {
key,
id,
end: watch,
service: Arc::downgrade(self),
}
}
#[must_use]
pub fn live_sessions(&self, key: PairingKey) -> usize {
self.live
.lock()
.map_or(0, |live| live.iter().filter(|e| e.key == key).count())
}
pub fn end_sessions(&self, key: PairingKey) {
if let Ok(live) = self.live.lock() {
for entry in live.iter().filter(|e| e.key == key) {
let _ = entry.end.send(true);
}
}
if let Ok(mut issued) = self.issued.lock() {
issued.retain(|entry| entry.key != key);
}
}
pub fn unpair(
&self,
bearer: &AccessToken,
request: &UnpairRequest,
) -> Result<(), ConnectError> {
let key = PairingKey {
local: request.server_node_id,
remote: request.client_node_id,
};
{
let _rotation = self.rotation.lock().map_err(|_| ConnectError::NotPaired)?;
let (_, mut machine) = self.machine(key).ok_or(ConnectError::NotPaired)?;
machine.unpair(bearer, request)?;
self.store.unpair(key);
}
self.end_sessions(key);
Ok(())
}
pub fn unpair_remote(&self, key: PairingKey) {
self.store.revoke(key);
self.end_sessions(key);
}
#[must_use]
pub fn tokens(&self, key: PairingKey) -> Option<TokenStore> {
self.store.paired(key).map(|p| p.tokens)
}
}