LCOV - code coverage report
Current view: top level - libs/postgres_connection/src - lib.rs (source / functions) Coverage Total Hit
Test: 2a9d99866121f170b43760bd62e1e2431e597707.info Lines: 86.2 % 188 162
Test Date: 2024-09-02 14:10:37 Functions: 71.1 % 38 27

            Line data    Source code
       1              : #![deny(unsafe_code)]
       2              : #![deny(clippy::undocumented_unsafe_blocks)]
       3              : use anyhow::{bail, Context};
       4              : use itertools::Itertools;
       5              : use std::borrow::Cow;
       6              : use std::fmt;
       7              : use url::Host;
       8              : 
       9              : /// Parses a string of format either `host:port` or `host` into a corresponding pair.
      10              : /// The `host` part should be a correct `url::Host`, while `port` (if present) should be
      11              : /// a valid decimal u16 of digits only.
      12           83 : pub fn parse_host_port<S: AsRef<str>>(host_port: S) -> Result<(Host, Option<u16>), anyhow::Error> {
      13           83 :     let (host, port) = match host_port.as_ref().rsplit_once(':') {
      14            3 :         Some((host, port)) => (
      15            3 :             host,
      16            3 :             // +80 is a valid u16, but not a valid port
      17            7 :             if port.chars().all(|c| c.is_ascii_digit()) {
      18            2 :                 Some(port.parse::<u16>().context("Unable to parse port")?)
      19              :             } else {
      20            1 :                 bail!("Port contains a non-ascii-digit")
      21              :             },
      22              :         ),
      23           80 :         None => (host_port.as_ref(), None), // No colons, no port specified
      24              :     };
      25           82 :     let host = Host::parse(host).context("Unable to parse host")?;
      26           81 :     Ok((host, port))
      27           83 : }
      28              : 
      29              : #[cfg(test)]
      30              : mod tests_parse_host_port {
      31              :     use crate::parse_host_port;
      32              :     use url::Host;
      33              : 
      34              :     #[test]
      35            1 :     fn test_normal() {
      36            1 :         let (host, port) = parse_host_port("hello:123").unwrap();
      37            1 :         assert_eq!(host, Host::Domain("hello".to_owned()));
      38            1 :         assert_eq!(port, Some(123));
      39            1 :     }
      40              : 
      41              :     #[test]
      42            1 :     fn test_no_port() {
      43            1 :         let (host, port) = parse_host_port("hello").unwrap();
      44            1 :         assert_eq!(host, Host::Domain("hello".to_owned()));
      45            1 :         assert_eq!(port, None);
      46            1 :     }
      47              : 
      48              :     #[test]
      49            1 :     fn test_ipv6() {
      50            1 :         let (host, port) = parse_host_port("[::1]:123").unwrap();
      51            1 :         assert_eq!(host, Host::<String>::Ipv6(std::net::Ipv6Addr::LOCALHOST));
      52            1 :         assert_eq!(port, Some(123));
      53            1 :     }
      54              : 
      55              :     #[test]
      56            1 :     fn test_invalid_host() {
      57            1 :         assert!(parse_host_port("hello world").is_err());
      58            1 :     }
      59              : 
      60              :     #[test]
      61            1 :     fn test_invalid_port() {
      62            1 :         assert!(parse_host_port("hello:+80").is_err());
      63            1 :     }
      64              : }
      65              : 
      66              : #[derive(Clone)]
      67              : pub struct PgConnectionConfig {
      68              :     host: Host,
      69              :     port: u16,
      70              :     password: Option<String>,
      71              :     options: Vec<String>,
      72              : }
      73              : 
      74              : /// A simplified PostgreSQL connection configuration. Supports only a subset of possible
      75              : /// settings for simplicity. A password getter or `to_connection_string` methods are not
      76              : /// added by design to avoid accidentally leaking password through logging, command line
      77              : /// arguments to a child process, or likewise.
      78              : impl PgConnectionConfig {
      79           82 :     pub fn new_host_port(host: Host, port: u16) -> Self {
      80           82 :         PgConnectionConfig {
      81           82 :             host,
      82           82 :             port,
      83           82 :             password: None,
      84           82 :             options: vec![],
      85           82 :         }
      86           82 :     }
      87              : 
      88           45 :     pub fn host(&self) -> &Host {
      89           45 :         &self.host
      90           45 :     }
      91              : 
      92            8 :     pub fn port(&self) -> u16 {
      93            8 :         self.port
      94            8 :     }
      95              : 
      96            0 :     pub fn set_host(mut self, h: Host) -> Self {
      97            0 :         self.host = h;
      98            0 :         self
      99            0 :     }
     100              : 
     101            0 :     pub fn set_port(mut self, p: u16) -> Self {
     102            0 :         self.port = p;
     103            0 :         self
     104            0 :     }
     105              : 
     106           79 :     pub fn set_password(mut self, s: Option<String>) -> Self {
     107           79 :         self.password = s;
     108           79 :         self
     109           79 :     }
     110              : 
     111           91 :     pub fn extend_options<I: IntoIterator<Item = S>, S: Into<String>>(mut self, i: I) -> Self {
     112          250 :         self.options.extend(i.into_iter().map(|s| s.into()));
     113           91 :         self
     114           91 :     }
     115              : 
     116              :     /// Return a `<host>:<port>` string.
     117            4 :     pub fn raw_address(&self) -> String {
     118            4 :         format!("{}:{}", self.host(), self.port())
     119            4 :     }
     120              : 
     121              :     /// Build a client library-specific connection configuration.
     122              :     /// Used for testing and when we need to add some obscure configuration
     123              :     /// elements at the last moment.
     124            1 :     pub fn to_tokio_postgres_config(&self) -> tokio_postgres::Config {
     125            1 :         // Use `tokio_postgres::Config` instead of `postgres::Config` because
     126            1 :         // the former supports more options to fiddle with later.
     127            1 :         let mut config = tokio_postgres::Config::new();
     128            1 :         config.host(&self.host().to_string()).port(self.port);
     129            1 :         if let Some(password) = &self.password {
     130            0 :             config.password(password);
     131            1 :         }
     132            1 :         if !self.options.is_empty() {
     133            1 :             // These options are command-line options and should be escaped before being passed
     134            1 :             // as an 'options' connection string parameter, see
     135            1 :             // https://www.postgresql.org/docs/15/libpq-connect.html#LIBPQ-CONNECT-OPTIONS
     136            1 :             //
     137            1 :             // They will be space-separated, so each space inside an option should be escaped,
     138            1 :             // and all backslashes should be escaped before that. Although we don't expect options
     139            1 :             // with spaces at the moment, they're supported by PostgreSQL. Hence we support them
     140            1 :             // in this typesafe interface.
     141            1 :             //
     142            1 :             // We use `Cow` to avoid allocations in the best case (no escaping). A fully imperative
     143            1 :             // solution would require 1-2 allocations in the worst case as well, but it's harder to
     144            1 :             // implement and this function is hardly a bottleneck. The function is only called around
     145            1 :             // establishing a new connection.
     146            1 :             #[allow(unstable_name_collisions)]
     147            1 :             config.options(
     148            1 :                 &self
     149            1 :                     .options
     150            1 :                     .iter()
     151            4 :                     .map(|s| {
     152            4 :                         if s.contains(['\\', ' ']) {
     153            2 :                             Cow::Owned(s.replace('\\', "\\\\").replace(' ', "\\ "))
     154              :                         } else {
     155            2 :                             Cow::Borrowed(s.as_str())
     156              :                         }
     157            4 :                     })
     158            1 :                     .intersperse(Cow::Borrowed(" ")) // TODO: use impl from std once it's stabilized
     159            1 :                     .collect::<String>(),
     160            1 :             );
     161            1 :         }
     162            1 :         config
     163            1 :     }
     164              : 
     165              :     /// Connect using postgres protocol with TLS disabled.
     166            0 :     pub async fn connect_no_tls(
     167            0 :         &self,
     168            0 :     ) -> Result<
     169            0 :         (
     170            0 :             tokio_postgres::Client,
     171            0 :             tokio_postgres::Connection<tokio_postgres::Socket, tokio_postgres::tls::NoTlsStream>,
     172            0 :         ),
     173            0 :         postgres::Error,
     174            0 :     > {
     175            0 :         self.to_tokio_postgres_config()
     176            0 :             .connect(postgres::NoTls)
     177            0 :             .await
     178            0 :     }
     179              : }
     180              : 
     181              : impl fmt::Display for PgConnectionConfig {
     182            0 :     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
     183            0 :         // The password is intentionally hidden and not part of this display string.
     184            0 :         write!(f, "postgresql://{}:{}", self.host, self.port)
     185            0 :     }
     186              : }
     187              : 
     188              : impl fmt::Debug for PgConnectionConfig {
     189            3 :     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
     190            3 :         // We want `password: Some(REDACTED-STRING)`, not `password: Some("REDACTED-STRING")`
     191            3 :         // so even if the password is `REDACTED-STRING` (quite unlikely) there is no confusion.
     192            3 :         // Hence `format_args!()`, it returns a "safe" string which is not escaped by `Debug`.
     193            3 :         f.debug_struct("PgConnectionConfig")
     194            3 :             .field("host", &self.host)
     195            3 :             .field("port", &self.port)
     196            3 :             .field(
     197            3 :                 "password",
     198            3 :                 &self
     199            3 :                     .password
     200            3 :                     .as_ref()
     201            3 :                     .map(|_| format_args!("REDACTED-STRING")),
     202            3 :             )
     203            3 :             .finish()
     204            3 :     }
     205              : }
     206              : 
     207              : #[cfg(test)]
     208              : mod tests_pg_connection_config {
     209              :     use crate::PgConnectionConfig;
     210              :     use once_cell::sync::Lazy;
     211              :     use url::Host;
     212              : 
     213            3 :     static STUB_HOST: Lazy<Host> = Lazy::new(|| Host::Domain("stub.host.example".to_owned()));
     214              : 
     215              :     #[test]
     216            1 :     fn test_no_password() {
     217            1 :         let cfg = PgConnectionConfig::new_host_port(STUB_HOST.clone(), 123);
     218            1 :         assert_eq!(cfg.host(), &*STUB_HOST);
     219            1 :         assert_eq!(cfg.port(), 123);
     220            1 :         assert_eq!(cfg.raw_address(), "stub.host.example:123");
     221            1 :         assert_eq!(
     222            1 :             format!("{:?}", cfg),
     223            1 :             "PgConnectionConfig { host: Domain(\"stub.host.example\"), port: 123, password: None }"
     224            1 :         );
     225            1 :     }
     226              : 
     227              :     #[test]
     228            1 :     fn test_ipv6() {
     229            1 :         // May be a special case because hostname contains a colon.
     230            1 :         let cfg = PgConnectionConfig::new_host_port(Host::parse("[::1]").unwrap(), 123);
     231            1 :         assert_eq!(
     232            1 :             cfg.host(),
     233            1 :             &Host::<String>::Ipv6(std::net::Ipv6Addr::LOCALHOST)
     234            1 :         );
     235            1 :         assert_eq!(cfg.port(), 123);
     236            1 :         assert_eq!(cfg.raw_address(), "[::1]:123");
     237            1 :         assert_eq!(
     238            1 :             format!("{:?}", cfg),
     239            1 :             "PgConnectionConfig { host: Ipv6(::1), port: 123, password: None }"
     240            1 :         );
     241            1 :     }
     242              : 
     243              :     #[test]
     244            1 :     fn test_with_password() {
     245            1 :         let cfg = PgConnectionConfig::new_host_port(STUB_HOST.clone(), 123)
     246            1 :             .set_password(Some("password".to_owned()));
     247            1 :         assert_eq!(cfg.host(), &*STUB_HOST);
     248            1 :         assert_eq!(cfg.port(), 123);
     249            1 :         assert_eq!(cfg.raw_address(), "stub.host.example:123");
     250            1 :         assert_eq!(
     251            1 :             format!("{:?}", cfg),
     252            1 :             "PgConnectionConfig { host: Domain(\"stub.host.example\"), port: 123, password: Some(REDACTED-STRING) }"
     253            1 :         );
     254            1 :     }
     255              : 
     256              :     #[test]
     257            1 :     fn test_with_options() {
     258            1 :         let cfg = PgConnectionConfig::new_host_port(STUB_HOST.clone(), 123).extend_options([
     259            1 :             "hello",
     260            1 :             "world",
     261            1 :             "with space",
     262            1 :             "and \\ backslashes",
     263            1 :         ]);
     264            1 :         assert_eq!(cfg.host(), &*STUB_HOST);
     265            1 :         assert_eq!(cfg.port(), 123);
     266            1 :         assert_eq!(cfg.raw_address(), "stub.host.example:123");
     267            1 :         assert_eq!(
     268            1 :             cfg.to_tokio_postgres_config().get_options(),
     269            1 :             Some("hello world with\\ space and\\ \\\\\\ backslashes")
     270            1 :         );
     271            1 :     }
     272              : }
        

Generated by: LCOV version 2.1-beta