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

Generated by: LCOV version 2.1-beta