Skip to main content

krot_client/
session.rs

1//! Authenticated Control-stream session state on the client side.
2
3use std::net::SocketAddr;
4
5use tokio::io::AsyncWriteExt;
6use tokio::net::lookup_host;
7use tracing::{debug, info, warn};
8
9use krot_proto::{sign_challenge, ClientFrame, ServerFrame, SessionId, StreamKind};
10use krot_transport::{
11    connect_tcp_fallback, install_crypto_provider, read_frame, write_frame, Connection,
12    KrotEndpoint,
13};
14
15use crate::config::{ClientConfig, Identity, ServerPin};
16use crate::error::ClientError;
17use crate::tls;
18
19/// Which transport landed us on the server. Exposed on
20/// [`AuthenticatedSession::transport`] so callers can log or drive
21/// per-transport telemetry.
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub enum SessionTransport {
24    Quic,
25    TcpFallback,
26}
27
28/// A fully-authenticated Control stream on top of a live connection —
29/// either QUIC (`krot/1`) or TLS-over-TCP (`krot-tcp/1`, §16.1).
30#[derive(Debug)]
31pub struct AuthenticatedSession {
32    pub connection: krot_transport::Connection,
33    pub send: krot_transport::SendStream,
34    pub recv: krot_transport::RecvStream,
35    pub session_id: SessionId,
36    pub transport: SessionTransport,
37    /// Kept alive for the lifetime of the session so the QUIC UDP
38    /// socket doesn't drop while streams are in flight. `None` for
39    /// the TCP fallback path — the TCP socket lives inside
40    /// `connection`.
41    _endpoint: Option<KrotEndpoint>,
42}
43
44impl AuthenticatedSession {
45    /// Connect to `pin` with §16.1 auto-fallback: try QUIC first,
46    /// and on any transport-level failure retry once against the same
47    /// host over `krot-tcp/1`. On success runs the Ed25519
48    /// challenge-response and returns the resulting session with its
49    /// Control stream ready for tunnel frames.
50    pub async fn connect(pin: &ServerPin, identity: &Identity) -> Result<Self, ClientError> {
51        install_crypto_provider();
52
53        // First attempt: QUIC.
54        match Self::connect_quic(pin, identity).await {
55            Ok(sess) => {
56                info!(transport = ?sess.transport, "session established");
57                Ok(sess)
58            }
59            Err(e) if is_transport_failure(&e) => {
60                warn!("QUIC connect failed ({e}); falling back to krot-tcp/1");
61                let sess = Self::connect_tcp(pin, identity).await?;
62                info!(transport = ?sess.transport, "session established via fallback");
63                Ok(sess)
64            }
65            // Non-transport errors (bad config, protocol violation
66            // after handshake) propagate as-is — they'd fail the same
67            // way over TCP.
68            Err(e) => Err(e),
69        }
70    }
71
72    /// Force the QUIC transport. Skips the §16.1.5 fallback; useful
73    /// for tests that want to isolate one code path.
74    pub async fn connect_quic(pin: &ServerPin, identity: &Identity) -> Result<Self, ClientError> {
75        install_crypto_provider();
76        let server_addr = resolve_server(pin, pin.quic_port).await?;
77        let endpoint = build_endpoint(pin)?;
78        let connection = endpoint.connect(server_addr, pin.effective_sni())?.await?;
79        debug!(?server_addr, "QUIC connection established");
80        Self::finish_auth(connection, identity, SessionTransport::Quic, Some(endpoint)).await
81    }
82
83    /// Force the TCP fallback transport. Skips the §16.1.5 fallback
84    /// preference; useful for tests and for operators who KNOW their
85    /// network blocks UDP.
86    pub async fn connect_tcp(pin: &ServerPin, identity: &Identity) -> Result<Self, ClientError> {
87        install_crypto_provider();
88        let server_addr = resolve_server(pin, pin.effective_tcp_port()).await?;
89        let tls_cfg = build_client_tls(pin)?;
90        let connection = connect_tcp_fallback(server_addr, pin.effective_sni(), tls_cfg).await?;
91        debug!(?server_addr, "krot-tcp/1 connection established");
92        Self::finish_auth(connection, identity, SessionTransport::TcpFallback, None).await
93    }
94
95    async fn finish_auth(
96        connection: Connection,
97        identity: &Identity,
98        transport: SessionTransport,
99        endpoint: Option<KrotEndpoint>,
100    ) -> Result<Self, ClientError> {
101        let (mut send, mut recv) = connection.open_bi().await?;
102
103        // Every stream begins with a StreamKind byte.
104        send.write_all(&[StreamKind::Control.as_byte()]).await?;
105
106        let pubkey = identity.pubkey()?;
107        write_frame(&mut send, &ClientFrame::AuthRequest { pubkey }).await?;
108
109        let ServerFrame::AuthChallenge { nonce } = read_frame(&mut recv).await? else {
110            return match read_reject(&mut recv).await {
111                Some(code) => Err(ClientError::AuthRejected(code)),
112                None => Err(ClientError::Protocol("expected AuthChallenge")),
113            };
114        };
115
116        let signing = identity.signing_key()?;
117        let signature = sign_challenge(&signing, &nonce);
118        write_frame(&mut send, &ClientFrame::AuthResponse { signature }).await?;
119
120        let session_id = match read_frame(&mut recv).await? {
121            ServerFrame::AuthOk { session_id } => session_id,
122            ServerFrame::AuthReject { code } => return Err(ClientError::AuthRejected(code)),
123            _ => return Err(ClientError::Protocol("expected AuthOk")),
124        };
125
126        Ok(Self {
127            connection,
128            send,
129            recv,
130            session_id,
131            transport,
132            _endpoint: endpoint,
133        })
134    }
135
136    /// Send `Bye` and finish the Control stream.
137    pub async fn shutdown(mut self) {
138        let _ = write_frame(&mut self.send, &ClientFrame::Bye).await;
139        let _ = self.send.finish();
140        let _ = self.send.stopped().await;
141        self.connection.close(0, b"bye");
142    }
143
144    /// §16.3.5: ask the server for the federated peer relays this
145    /// identity is authorized to publish on. The response is the
146    /// intersection of the server's static peer list (§16.3.2) and
147    /// this identity's `federation=` allowlist (§16.3.1).
148    ///
149    /// Callers use the returned apex list to open additional sessions
150    /// (one per peer) and re-publish the same tunnel on each — the
151    /// operator gets one URL per relay.
152    pub async fn list_peers(&mut self) -> Result<Vec<String>, ClientError> {
153        write_frame(&mut self.send, &ClientFrame::ListPeers).await?;
154        match read_frame(&mut self.recv).await? {
155            ServerFrame::Peers { relays } => Ok(relays),
156            _ => Err(ClientError::Protocol("expected Peers response")),
157        }
158    }
159}
160
161pub(crate) fn build_endpoint(pin: &ServerPin) -> Result<KrotEndpoint, ClientError> {
162    use std::net::{IpAddr, Ipv4Addr, SocketAddr};
163
164    let tls_cfg = build_client_tls(pin)?;
165    let bind = SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 0);
166    Ok(KrotEndpoint::client(bind, tls_cfg)?)
167}
168
169fn build_client_tls(pin: &ServerPin) -> Result<rustls::ClientConfig, ClientError> {
170    if let Some(pin_bytes) = pin.fingerprint_bytes()? {
171        Ok(tls::client_config(pin_bytes)?)
172    } else {
173        Err(ClientError::Config(
174            "server pin has no fingerprint (only IpMode is supported today)".into(),
175        ))
176    }
177}
178
179pub(crate) async fn resolve_server(pin: &ServerPin, port: u16) -> Result<SocketAddr, ClientError> {
180    let target = format!("{}:{}", pin.host, port);
181    let first = {
182        let mut addrs = lookup_host(target.as_str())
183            .await
184            .map_err(|e| ClientError::BadServerAddr(format!("{target}: {e}")))?;
185        addrs.next()
186    };
187    first.ok_or_else(|| ClientError::BadServerAddr(target))
188}
189
190/// Decide whether `err` is a transport-level failure that warrants a
191/// §16.1.5 fallback attempt. Errors that would recur over TCP (bad
192/// config, protocol violation after handshake, auth reject) are NOT
193/// eligible.
194fn is_transport_failure(err: &ClientError) -> bool {
195    match err {
196        ClientError::Transport(_) => true,
197        ClientError::BadServerAddr(_) => true,
198        // Auth-level failures, config errors, protocol violations, etc.
199        // will fail the same way over TCP.
200        _ => false,
201    }
202}
203
204async fn read_reject(recv: &mut krot_transport::RecvStream) -> Option<krot_proto::ErrorCode> {
205    match read_frame::<ServerFrame>(recv).await.ok()? {
206        ServerFrame::AuthReject { code } | ServerFrame::ServerBye { code } => Some(code),
207        _ => None,
208    }
209}
210
211/// Load the persisted [`ClientConfig`] from `dir`.
212pub fn load_config(dir: &std::path::Path) -> Result<ClientConfig, ClientError> {
213    ClientConfig::load_from(dir)
214}