Skip to main content

smgw_cls/
transport.rs

1//! A bounded, one-session TLS proxy for loopback integration tests.
2//!
3//! Each leg has a private trust store and a provisioned peer certificate.
4//! TLS Server Name Indication (SNI) selects a configured route. Peer identity
5//! comes from the provisioned certificate and verified chain.
6
7use openssl::{
8    ssl::NameType,
9    x509::{X509, X509Ref},
10};
11pub use smgw_sec::tls::TlsIdentity;
12use smgw_sec::transport::{TlsEndpoint as PeerEndpoint, check_loopback, check_server_name};
13use std::{fs, io, net::SocketAddr, path::Path, time::Duration};
14use tokio::{io::copy_bidirectional, net::TcpStream, time::timeout};
15use tokio_openssl::SslStream;
16
17/// A pinned loopback TLS endpoint for one leg of a CLS proxy.
18pub struct TlsEndpoint(PeerEndpoint);
19
20impl TlsEndpoint {
21    /// Load an endpoint from the test PKI generated by `cargo run -p xtask -- gen-pki`.
22    ///
23    /// Select `han/cls` ↔ `han/smgw` or `wan/smgw` ↔ `wan/aemt`.
24    /// The peer's chain file supplies the provisioned leaf pin. Verifying its chain
25    /// at connection time also enforces certificate purpose and validity.
26    pub fn load(dir: &Path, domain: &str, role: &str, peer: &str) -> io::Result<Self> {
27        if !matches!(
28            (domain, role, peer),
29            ("han", "cls", "smgw")
30                | ("han", "smgw", "cls")
31                | ("wan", "smgw", "aemt")
32                | ("wan", "aemt", "smgw")
33        ) {
34            return Err(io::Error::new(
35                io::ErrorKind::InvalidInput,
36                "unknown PKI role pair",
37            ));
38        }
39        let dir = dir.join(domain);
40        let identity = TlsIdentity::from_pem(
41            &fs::read(dir.join(format!("{role}.chain.pem")))?,
42            &fs::read(dir.join(format!("{role}.key.pem")))?,
43        )?;
44        let root = X509::from_pem(&fs::read(dir.join("root.pem"))?)?;
45        let peer = X509::from_pem(&fs::read(dir.join(format!("{peer}.chain.pem")))?)?;
46        Self::from_identity(identity, &root, &peer)
47    }
48
49    /// Configure an endpoint from its signing identity, trusted root and exact peer pin.
50    pub fn from_identity(
51        identity: TlsIdentity,
52        trust_anchor: &X509Ref,
53        peer_leaf: &X509Ref,
54    ) -> io::Result<Self> {
55        PeerEndpoint::from_identity(identity, trust_anchor, peer_leaf).map(Self)
56    }
57
58    /// Dial the literal loopback address and send SNI within one setup budget.
59    pub async fn connect(
60        &self,
61        address: SocketAddr,
62        sni: &str,
63        budget: Duration,
64    ) -> io::Result<SslStream<TcpStream>> {
65        self.0.connect(address, sni, budget).await
66    }
67
68    /// Accept a mutually authenticated CLS session on a loopback socket.
69    pub async fn accept(
70        &self,
71        tcp: TcpStream,
72        budget: Duration,
73    ) -> io::Result<SslStream<TcpStream>> {
74        self.0.accept(tcp, budget).await
75    }
76}
77
78/// A single authorized HAN-to-WAN route. A mutable borrow admits one session at a time.
79pub struct SmgwProxy {
80    han: TlsEndpoint,
81    wan: TlsEndpoint,
82    route: String,
83    wan_address: SocketAddr,
84    wan_sni: String,
85    handshake_timeout: Duration,
86    session_timeout: Duration,
87}
88
89impl SmgwProxy {
90    /// Configures the SNI route and its fixed loopback WAN destination.
91    pub fn new(
92        han: TlsEndpoint,
93        wan: TlsEndpoint,
94        route: String,
95        wan_address: SocketAddr,
96        wan_sni: String,
97        handshake_timeout: Duration,
98        session_timeout: Duration,
99    ) -> io::Result<Self> {
100        check_loopback(wan_address)?;
101        check_server_name(&route)?;
102        check_server_name(&wan_sni)?;
103        if handshake_timeout.is_zero() || session_timeout.is_zero() {
104            return Err(io::Error::new(
105                io::ErrorKind::InvalidInput,
106                "timeouts must be positive",
107            ));
108        }
109        Ok(Self {
110            han,
111            wan,
112            route,
113            wan_address,
114            wan_sni,
115            handshake_timeout,
116            session_timeout,
117        })
118    }
119
120    /// Authenticates the CLS and authorizes its SNI before opening a WAN socket.
121    ///
122    /// The session deadline covers both handshakes and relay. Dropping this future
123    /// closes the streams. The return value counts plaintext bytes in HAN-to-WAN
124    /// and WAN-to-HAN order. Tokio bounds the relay buffer in each direction.
125    pub async fn relay(&mut self, tcp: TcpStream) -> io::Result<(u64, u64)> {
126        timeout(self.session_timeout, async {
127            let mut han = self.han.accept(tcp, self.handshake_timeout).await?;
128            let authorized = han
129                .ssl()
130                .servername(NameType::HOST_NAME)
131                .is_some_and(|sni| sni.eq_ignore_ascii_case(&self.route));
132            if !authorized {
133                return Err(io::Error::new(
134                    io::ErrorKind::PermissionDenied,
135                    "unknown CLS proxy route",
136                ));
137            }
138            let mut wan = self
139                .wan
140                .connect(self.wan_address, &self.wan_sni, self.handshake_timeout)
141                .await?;
142            copy_bidirectional(&mut han, &mut wan).await
143        })
144        .await?
145    }
146}