Line data Source code
1 : /// Test postgres_backend_async with tokio_postgres
2 : use once_cell::sync::Lazy;
3 : use postgres_backend::{AuthType, Handler, PostgresBackend, QueryError};
4 : use pq_proto::{BeMessage, RowDescriptor};
5 : use std::io::Cursor;
6 : use std::sync::Arc;
7 : use tokio::io::{AsyncRead, AsyncWrite};
8 : use tokio::net::{TcpListener, TcpStream};
9 : use tokio_postgres::config::SslMode;
10 : use tokio_postgres::tls::MakeTlsConnect;
11 : use tokio_postgres::{Config, NoTls, SimpleQueryMessage};
12 : use tokio_postgres_rustls::MakeRustlsConnect;
13 : use tokio_util::sync::CancellationToken;
14 :
15 : // generate client, server test streams
16 2 : async fn make_tcp_pair() -> (TcpStream, TcpStream) {
17 2 : let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
18 2 : let addr = listener.local_addr().unwrap();
19 2 : let client_stream = TcpStream::connect(addr).await.unwrap();
20 2 : let (server_stream, _) = listener.accept().await.unwrap();
21 2 : (client_stream, server_stream)
22 2 : }
23 :
24 : struct TestHandler {}
25 :
26 : impl<IO: AsyncRead + AsyncWrite + Unpin + Send> Handler<IO> for TestHandler {
27 : // return single col 'hey' for any query
28 2 : async fn process_query(
29 2 : &mut self,
30 2 : pgb: &mut PostgresBackend<IO>,
31 2 : _query_string: &str,
32 2 : ) -> Result<(), QueryError> {
33 2 : pgb.write_message_noflush(&BeMessage::RowDescription(&[RowDescriptor::text_col(
34 2 : b"hey",
35 2 : )]))?
36 2 : .write_message_noflush(&BeMessage::DataRow(&[Some("hey".as_bytes())]))?
37 2 : .write_message_noflush(&BeMessage::CommandComplete(b"SELECT 1"))?;
38 2 : Ok(())
39 2 : }
40 : }
41 :
42 : // test that basic select works
43 : #[tokio::test]
44 1 : async fn simple_select() {
45 1 : let (client_sock, server_sock) = make_tcp_pair().await;
46 1 :
47 1 : // create and run pgbackend
48 1 : let pgbackend =
49 1 : PostgresBackend::new(server_sock, AuthType::Trust, None).expect("pgbackend creation");
50 1 :
51 1 : tokio::spawn(async move {
52 1 : let mut handler = TestHandler {};
53 2 : pgbackend.run(&mut handler, &CancellationToken::new()).await
54 1 : });
55 1 :
56 1 : let conf = Config::new();
57 1 : let (client, connection) = conf.connect_raw(client_sock, NoTls).await.expect("connect");
58 1 : // The connection object performs the actual communication with the database,
59 1 : // so spawn it off to run on its own.
60 1 : tokio::spawn(async move {
61 1 : if let Err(e) = connection.await {
62 0 : eprintln!("connection error: {}", e);
63 0 : }
64 1 : });
65 1 :
66 1 : let first_val = &(client.simple_query("SELECT 42;").await.expect("select"))[0];
67 1 : if let SimpleQueryMessage::Row(row) = first_val {
68 1 : let first_col = row.get(0).expect("first column");
69 1 : assert_eq!(first_col, "hey");
70 1 : } else {
71 1 : panic!("expected SimpleQueryMessage::Row");
72 1 : }
73 1 : }
74 :
75 1 : static KEY: Lazy<rustls::pki_types::PrivateKeyDer<'static>> = Lazy::new(|| {
76 1 : let mut cursor = Cursor::new(include_bytes!("key.pem"));
77 1 : let key = rustls_pemfile::rsa_private_keys(&mut cursor)
78 1 : .next()
79 1 : .unwrap()
80 1 : .unwrap();
81 1 : rustls::pki_types::PrivateKeyDer::Pkcs1(key)
82 1 : });
83 :
84 1 : static CERT: Lazy<rustls::pki_types::CertificateDer<'static>> = Lazy::new(|| {
85 1 : let mut cursor = Cursor::new(include_bytes!("cert.pem"));
86 1 : let cert = rustls_pemfile::certs(&mut cursor).next().unwrap().unwrap();
87 1 : cert
88 1 : });
89 :
90 : // test that basic select with ssl works
91 : #[tokio::test]
92 1 : async fn simple_select_ssl() {
93 1 : let (client_sock, server_sock) = make_tcp_pair().await;
94 1 :
95 1 : let server_cfg = rustls::ServerConfig::builder()
96 1 : .with_no_client_auth()
97 1 : .with_single_cert(vec![CERT.clone()], KEY.clone_key())
98 1 : .unwrap();
99 1 : let tls_config = Some(Arc::new(server_cfg));
100 1 : let pgbackend =
101 1 : PostgresBackend::new(server_sock, AuthType::Trust, tls_config).expect("pgbackend creation");
102 1 :
103 1 : tokio::spawn(async move {
104 1 : let mut handler = TestHandler {};
105 5 : pgbackend.run(&mut handler, &CancellationToken::new()).await
106 1 : });
107 1 :
108 1 : let client_cfg = rustls::ClientConfig::builder()
109 1 : .with_root_certificates({
110 1 : let mut store = rustls::RootCertStore::empty();
111 1 : store.add(CERT.clone()).unwrap();
112 1 : store
113 1 : })
114 1 : .with_no_client_auth();
115 1 : let mut make_tls_connect = tokio_postgres_rustls::MakeRustlsConnect::new(client_cfg);
116 1 : let tls_connect = <MakeRustlsConnect as MakeTlsConnect<TcpStream>>::make_tls_connect(
117 1 : &mut make_tls_connect,
118 1 : "localhost",
119 1 : )
120 1 : .expect("make_tls_connect");
121 1 :
122 1 : let mut conf = Config::new();
123 1 : conf.ssl_mode(SslMode::Require);
124 1 : let (client, connection) = conf
125 1 : .connect_raw(client_sock, tls_connect)
126 4 : .await
127 1 : .expect("connect");
128 1 : // The connection object performs the actual communication with the database,
129 1 : // so spawn it off to run on its own.
130 1 : tokio::spawn(async move {
131 1 : if let Err(e) = connection.await {
132 0 : eprintln!("connection error: {}", e);
133 0 : }
134 1 : });
135 1 :
136 1 : let first_val = &(client.simple_query("SELECT 42;").await.expect("select"))[0];
137 1 : if let SimpleQueryMessage::Row(row) = first_val {
138 1 : let first_col = row.get(0).expect("first column");
139 1 : assert_eq!(first_col, "hey");
140 1 : } else {
141 1 : panic!("expected SimpleQueryMessage::Row");
142 1 : }
143 1 : }
|