1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
use std::io;
use std::net::{SocketAddr, ToSocketAddrs};
use std::sync::Arc;

use super::{ServerConfig, TlsIncoming};
use crate::tcp::TcpIncoming;
use crate::{App, Endpoint, Executor, Server, State};

impl TlsIncoming<TcpIncoming> {
    /// Bind a socket addr.
    #[cfg_attr(feature = "docs", doc(cfg(feature = "tls")))]
    pub fn bind(addr: impl ToSocketAddrs, config: ServerConfig) -> io::Result<Self> {
        Ok(Self::new(TcpIncoming::bind(addr)?, config))
    }
}

/// An app extension.
#[cfg_attr(feature = "docs", doc(cfg(feature = "tls")))]
pub trait TlsListener {
    /// http server
    type Server;

    /// Listen on a socket addr, return a server and the real addr it binds.
    fn bind_tls(
        self,
        addr: impl ToSocketAddrs,
        config: ServerConfig,
    ) -> std::io::Result<(SocketAddr, Self::Server)>;

    /// Listen on a socket addr, return a server, and pass real addr to the callback.
    fn listen_tls(
        self,
        addr: impl ToSocketAddrs,
        config: ServerConfig,
        callback: impl Fn(SocketAddr),
    ) -> std::io::Result<Self::Server>;

    /// Listen on an unused port of 127.0.0.1, return a server and the real addr it binds.
    /// ### Example
    /// ```rust
    /// use roa::{App, Context, Status};
    /// use roa::tls::{TlsIncoming, ServerConfig, TlsListener, Certificate, PrivateKey};
    /// use roa::tls::pemfile::{certs, rsa_private_keys};
    /// use roa_core::http::StatusCode;
    /// use tokio::task::spawn;
    /// use std::time::Instant;
    /// use std::fs::File;
    /// use std::io::BufReader;
    ///
    /// async fn end(_ctx: &mut Context) -> Result<(), Status> {
    ///     Ok(())
    /// }
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let mut cert_file = BufReader::new(File::open("../assets/cert.pem")?);
    /// let mut key_file = BufReader::new(File::open("../assets/key.pem")?);
    /// let cert_chain = certs(&mut cert_file)?.into_iter().map(Certificate).collect();
    ///
    /// let config = ServerConfig::builder()
    ///     .with_safe_defaults()
    ///     .with_no_client_auth()
    ///     .with_single_cert(cert_chain, PrivateKey(rsa_private_keys(&mut key_file)?.remove(0)))?;
    ///
    /// let server = App::new().end(end).listen_tls("127.0.0.1:8000", config, |addr| {
    ///     println!("Server is listening on https://localhost:{}", addr.port());
    /// })?;
    /// // server.await
    /// Ok(())
    /// # }
    /// ```
    fn run_tls(self, config: ServerConfig) -> std::io::Result<(SocketAddr, Self::Server)>;
}

impl<S, E> TlsListener for App<S, Arc<E>>
where
    S: State,
    E: for<'a> Endpoint<'a, S>,
{
    type Server = Server<TlsIncoming<TcpIncoming>, Self, Executor>;
    fn bind_tls(
        self,
        addr: impl ToSocketAddrs,
        config: ServerConfig,
    ) -> std::io::Result<(SocketAddr, Self::Server)> {
        let incoming = TlsIncoming::bind(addr, config)?;
        let local_addr = incoming.local_addr();
        Ok((local_addr, self.accept(incoming)))
    }

    fn listen_tls(
        self,
        addr: impl ToSocketAddrs,
        config: ServerConfig,
        callback: impl Fn(SocketAddr),
    ) -> std::io::Result<Self::Server> {
        let (addr, server) = self.bind_tls(addr, config)?;
        callback(addr);
        Ok(server)
    }

    fn run_tls(self, config: ServerConfig) -> std::io::Result<(SocketAddr, Self::Server)> {
        self.bind_tls("127.0.0.1:0", config)
    }
}

#[cfg(test)]
mod tests {
    use std::fs::File;
    use std::io::{self, BufReader};

    use futures::{AsyncReadExt, TryStreamExt};
    use hyper::client::{Client, HttpConnector};
    use hyper::Body;
    use hyper_tls::{native_tls, HttpsConnector};
    use tokio::task::spawn;
    use tokio_native_tls::TlsConnector;

    use crate::http::StatusCode;
    use crate::tls::pemfile::{certs, rsa_private_keys};
    use crate::tls::{Certificate, PrivateKey, ServerConfig, TlsListener};
    use crate::{App, Context, Status};

    async fn end(ctx: &mut Context) -> Result<(), Status> {
        ctx.resp.write("Hello, World!");
        Ok(())
    }

    #[tokio::test]
    async fn run_tls() -> Result<(), Box<dyn std::error::Error>> {
        let mut cert_file = BufReader::new(File::open("../assets/cert.pem")?);
        let mut key_file = BufReader::new(File::open("../assets/key.pem")?);
        let cert_chain = certs(&mut cert_file)?
            .into_iter()
            .map(Certificate)
            .collect();

        let config = ServerConfig::builder()
            .with_safe_defaults()
            .with_no_client_auth()
            .with_single_cert(
                cert_chain,
                PrivateKey(rsa_private_keys(&mut key_file)?.remove(0)),
            )?;

        let app = App::new().end(end);
        let (addr, server) = app.run_tls(config)?;
        spawn(server);

        let native_tls_connector = native_tls::TlsConnector::builder()
            .danger_accept_invalid_hostnames(true)
            .danger_accept_invalid_certs(true)
            .build()?;
        let tls_connector = TlsConnector::from(native_tls_connector);
        let mut http_connector = HttpConnector::new();
        http_connector.enforce_http(false);
        let https_connector = HttpsConnector::from((http_connector, tls_connector));
        let client = Client::builder().build::<_, Body>(https_connector);
        let resp = client
            .get(format!("https://localhost:{}", addr.port()).parse()?)
            .await?;
        assert_eq!(StatusCode::OK, resp.status());
        let mut text = String::new();
        resp.into_body()
            .map_err(|err| io::Error::new(io::ErrorKind::Other, err))
            .into_async_read()
            .read_to_string(&mut text)
            .await?;
        assert_eq!("Hello, World!", text);
        Ok(())
    }
}