LCOV - code coverage report
Current view: top level - libs/postgres_connection/src - lib.rs (source / functions) Coverage Total Hit
Test: 2aa98e37cd3250b9a68c97ef6050b16fe702ab33.info Lines: 86.2 % 188 162
Test Date: 2024-08-29 11:33:10 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          108 : pub fn parse_host_port<S: AsRef<str>>(host_port: S) -> Result<(Host, Option<u16>), anyhow::Error> {
      13          108 :     let (host, port) = match host_port.as_ref().rsplit_once(':') {
      14           18 :         Some((host, port)) => (
      15           18 :             host,
      16           18 :             // +80 is a valid u16, but not a valid port
      17           42 :             if port.chars().all(|c| c.is_ascii_digit()) {
      18           12 :                 Some(port.parse::<u16>().context("Unable to parse port")?)
      19              :             } else {
      20            6 :                 bail!("Port contains a non-ascii-digit")
      21              :             },
      22              :         ),
      23           90 :         None => (host_port.as_ref(), None), // No colons, no port specified
      24              :     };
      25          102 :     let host = Host::parse(host).context("Unable to parse host")?;
      26           96 :     Ok((host, port))
      27          108 : }
      28              : 
      29              : #[cfg(test)]
      30              : mod tests_parse_host_port {
      31              :     use crate::parse_host_port;
      32              :     use url::Host;
      33              : 
      34              :     #[test]
      35            6 :     fn test_normal() {
      36            6 :         let (host, port) = parse_host_port("hello:123").unwrap();
      37            6 :         assert_eq!(host, Host::Domain("hello".to_owned()));
      38            6 :         assert_eq!(port, Some(123));
      39            6 :     }
      40              : 
      41              :     #[test]
      42            6 :     fn test_no_port() {
      43            6 :         let (host, port) = parse_host_port("hello").unwrap();
      44            6 :         assert_eq!(host, Host::Domain("hello".to_owned()));
      45            6 :         assert_eq!(port, None);
      46            6 :     }
      47              : 
      48              :     #[test]
      49            6 :     fn test_ipv6() {
      50            6 :         let (host, port) = parse_host_port("[::1]:123").unwrap();
      51            6 :         assert_eq!(host, Host::<String>::Ipv6(std::net::Ipv6Addr::LOCALHOST));
      52            6 :         assert_eq!(port, Some(123));
      53            6 :     }
      54              : 
      55              :     #[test]
      56            6 :     fn test_invalid_host() {
      57            6 :         assert!(parse_host_port("hello world").is_err());
      58            6 :     }
      59              : 
      60              :     #[test]
      61            6 :     fn test_invalid_port() {
      62            6 :         assert!(parse_host_port("hello:+80").is_err());
      63            6 :     }
      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          102 :     pub fn new_host_port(host: Host, port: u16) -> Self {
      80          102 :         PgConnectionConfig {
      81          102 :             host,
      82          102 :             port,
      83          102 :             password: None,
      84          102 :             options: vec![],
      85          102 :         }
      86          102 :     }
      87              : 
      88           90 :     pub fn host(&self) -> &Host {
      89           90 :         &self.host
      90           90 :     }
      91              : 
      92           48 :     pub fn port(&self) -> u16 {
      93           48 :         self.port
      94           48 :     }
      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           84 :     pub fn set_password(mut self, s: Option<String>) -> Self {
     107           84 :         self.password = s;
     108           84 :         self
     109           84 :     }
     110              : 
     111           96 :     pub fn extend_options<I: IntoIterator<Item = S>, S: Into<String>>(mut self, i: I) -> Self {
     112          270 :         self.options.extend(i.into_iter().map(|s| s.into()));
     113           96 :         self
     114           96 :     }
     115              : 
     116              :     /// Return a `<host>:<port>` string.
     117           24 :     pub fn raw_address(&self) -> String {
     118           24 :         format!("{}:{}", self.host(), self.port())
     119           24 :     }
     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            6 :     pub fn to_tokio_postgres_config(&self) -> tokio_postgres::Config {
     125            6 :         // Use `tokio_postgres::Config` instead of `postgres::Config` because
     126            6 :         // the former supports more options to fiddle with later.
     127            6 :         let mut config = tokio_postgres::Config::new();
     128            6 :         config.host(&self.host().to_string()).port(self.port);
     129            6 :         if let Some(password) = &self.password {
     130            0 :             config.password(password);
     131            6 :         }
     132            6 :         if !self.options.is_empty() {
     133            6 :             // These options are command-line options and should be escaped before being passed
     134            6 :             // as an 'options' connection string parameter, see
     135            6 :             // https://www.postgresql.org/docs/15/libpq-connect.html#LIBPQ-CONNECT-OPTIONS
     136            6 :             //
     137            6 :             // They will be space-separated, so each space inside an option should be escaped,
     138            6 :             // and all backslashes should be escaped before that. Although we don't expect options
     139            6 :             // with spaces at the moment, they're supported by PostgreSQL. Hence we support them
     140            6 :             // in this typesafe interface.
     141            6 :             //
     142            6 :             // We use `Cow` to avoid allocations in the best case (no escaping). A fully imperative
     143            6 :             // solution would require 1-2 allocations in the worst case as well, but it's harder to
     144            6 :             // implement and this function is hardly a bottleneck. The function is only called around
     145            6 :             // establishing a new connection.
     146            6 :             #[allow(unstable_name_collisions)]
     147            6 :             config.options(
     148            6 :                 &self
     149            6 :                     .options
     150            6 :                     .iter()
     151           24 :                     .map(|s| {
     152           24 :                         if s.contains(['\\', ' ']) {
     153           12 :                             Cow::Owned(s.replace('\\', "\\\\").replace(' ', "\\ "))
     154              :                         } else {
     155           12 :                             Cow::Borrowed(s.as_str())
     156              :                         }
     157           24 :                     })
     158            6 :                     .intersperse(Cow::Borrowed(" ")) // TODO: use impl from std once it's stabilized
     159            6 :                     .collect::<String>(),
     160            6 :             );
     161            6 :         }
     162            6 :         config
     163            6 :     }
     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           18 :     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
     190           18 :         // We want `password: Some(REDACTED-STRING)`, not `password: Some("REDACTED-STRING")`
     191           18 :         // so even if the password is `REDACTED-STRING` (quite unlikely) there is no confusion.
     192           18 :         // Hence `format_args!()`, it returns a "safe" string which is not escaped by `Debug`.
     193           18 :         f.debug_struct("PgConnectionConfig")
     194           18 :             .field("host", &self.host)
     195           18 :             .field("port", &self.port)
     196           18 :             .field(
     197           18 :                 "password",
     198           18 :                 &self
     199           18 :                     .password
     200           18 :                     .as_ref()
     201           18 :                     .map(|_| format_args!("REDACTED-STRING")),
     202           18 :             )
     203           18 :             .finish()
     204           18 :     }
     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           18 :     static STUB_HOST: Lazy<Host> = Lazy::new(|| Host::Domain("stub.host.example".to_owned()));
     214              : 
     215              :     #[test]
     216            6 :     fn test_no_password() {
     217            6 :         let cfg = PgConnectionConfig::new_host_port(STUB_HOST.clone(), 123);
     218            6 :         assert_eq!(cfg.host(), &*STUB_HOST);
     219            6 :         assert_eq!(cfg.port(), 123);
     220            6 :         assert_eq!(cfg.raw_address(), "stub.host.example:123");
     221            6 :         assert_eq!(
     222            6 :             format!("{:?}", cfg),
     223            6 :             "PgConnectionConfig { host: Domain(\"stub.host.example\"), port: 123, password: None }"
     224            6 :         );
     225            6 :     }
     226              : 
     227              :     #[test]
     228            6 :     fn test_ipv6() {
     229            6 :         // May be a special case because hostname contains a colon.
     230            6 :         let cfg = PgConnectionConfig::new_host_port(Host::parse("[::1]").unwrap(), 123);
     231            6 :         assert_eq!(
     232            6 :             cfg.host(),
     233            6 :             &Host::<String>::Ipv6(std::net::Ipv6Addr::LOCALHOST)
     234            6 :         );
     235            6 :         assert_eq!(cfg.port(), 123);
     236            6 :         assert_eq!(cfg.raw_address(), "[::1]:123");
     237            6 :         assert_eq!(
     238            6 :             format!("{:?}", cfg),
     239            6 :             "PgConnectionConfig { host: Ipv6(::1), port: 123, password: None }"
     240            6 :         );
     241            6 :     }
     242              : 
     243              :     #[test]
     244            6 :     fn test_with_password() {
     245            6 :         let cfg = PgConnectionConfig::new_host_port(STUB_HOST.clone(), 123)
     246            6 :             .set_password(Some("password".to_owned()));
     247            6 :         assert_eq!(cfg.host(), &*STUB_HOST);
     248            6 :         assert_eq!(cfg.port(), 123);
     249            6 :         assert_eq!(cfg.raw_address(), "stub.host.example:123");
     250            6 :         assert_eq!(
     251            6 :             format!("{:?}", cfg),
     252            6 :             "PgConnectionConfig { host: Domain(\"stub.host.example\"), port: 123, password: Some(REDACTED-STRING) }"
     253            6 :         );
     254            6 :     }
     255              : 
     256              :     #[test]
     257            6 :     fn test_with_options() {
     258            6 :         let cfg = PgConnectionConfig::new_host_port(STUB_HOST.clone(), 123).extend_options([
     259            6 :             "hello",
     260            6 :             "world",
     261            6 :             "with space",
     262            6 :             "and \\ backslashes",
     263            6 :         ]);
     264            6 :         assert_eq!(cfg.host(), &*STUB_HOST);
     265            6 :         assert_eq!(cfg.port(), 123);
     266            6 :         assert_eq!(cfg.raw_address(), "stub.host.example:123");
     267            6 :         assert_eq!(
     268            6 :             cfg.to_tokio_postgres_config().get_options(),
     269            6 :             Some("hello world with\\ space and\\ \\\\\\ backslashes")
     270            6 :         );
     271            6 :     }
     272              : }
        

Generated by: LCOV version 2.1-beta