Skip to main content

utopia_dsn/
lib.rs

1//! Parse data source names (`scheme://user:password@host:port/path?query`):
2//! the connection strings that configure databases, caches, queues and other
3//! services.
4//!
5//! [`Dsn::parse`] splits a DSN into its scheme, credentials, host, port, path
6//! and query, and [`Dsn::param`] reads one query parameter. Error messages
7//! never quote the DSN, and the `Debug` output of a [`Dsn`] hides the
8//! password, so credentials do not leak into logs.
9//!
10//! PHP: ports `utopia-php/dsn`.
11//!
12//! | PHP | Rust |
13//! |---|---|
14//! | `new DSN($dsn)` | [`Dsn::parse`] |
15//! | `getScheme()`, `getHost()` | [`Dsn::scheme`], [`Dsn::host`] |
16//! | `getUser()`, `getPassword()` | [`Dsn::user`], [`Dsn::password`] (bytes: they are URL-decoded) |
17//! | `getPort()` (`?string`) | [`Dsn::port`] (`Option<u16>`; PHP's string is its decimal form) |
18//! | `DSN::from(...)` | [`Dsn::from`] |
19//! | `getPath()`, `getQuery()` | [`Dsn::path`] (bytes: it is URL-decoded), [`Dsn::query`] |
20//! | `__toString()` | [`Dsn`]'s `Display` |
21//! | `getParam($key, $default)` | [`Dsn::param`] (`Ok(None)` where PHP returns `$default`), [`Dsn::param_or`] |
22//! | `\InvalidArgumentException`, `\TypeError` | [`Error::InvalidArgument`], [`Error::Type`] |
23//!
24//! PHP: the DSN is split by PHP's `parse_url` and the query by PHP's
25//! `parse_str` ([`php_std`]), so every input reads exactly as it does in PHP.
26//! PHP marks the argument `#[\SensitiveParameter]`.
27//!
28//! Read a database connection string:
29//!
30//! ```
31//! use utopia_dsn::Dsn;
32//!
33//! let dsn = Dsn::parse("mariadb://user:secret@localhost:3306/appwrite?charset=utf8mb4")?;
34//! assert_eq!(dsn.scheme(), "mariadb");
35//! assert_eq!(dsn.host(), "localhost");
36//! assert_eq!(dsn.port(), Some(3306));
37//! assert_eq!(dsn.path(), b"appwrite");
38//! assert_eq!(dsn.param("charset")?, Some(&b"utf8mb4"[..]));
39//! # Ok::<(), Box<dyn std::error::Error>>(())
40//! ```
41//!
42//! ```php
43//! use Utopia\DSN\DSN;
44//!
45//! $dsn = new DSN('mariadb://user:secret@localhost:3306/appwrite?charset=utf8mb4');
46//! echo $dsn->getScheme(), "\n";          // mariadb
47//! echo $dsn->getHost(), "\n";            // localhost
48//! echo $dsn->getPort(), "\n";            // 3306
49//! echo $dsn->getPath(), "\n";            // appwrite
50//! echo $dsn->getParam('charset'), "\n";  // utf8mb4
51//! ```
52
53#![warn(missing_docs)]
54
55use std::fmt;
56
57/// The getting started guide (`guide.md`), compiled and run with the doctests.
58#[cfg(doctest)]
59#[doc = include_str!("../guide.md")]
60pub struct GettingStarted;
61use std::ops::Range;
62use std::sync::OnceLock;
63
64use php_std::encoding::{parse_str, rawurldecode_into, rawurlencode, urldecode_into};
65use php_std::{Array, ArrayKey, Value};
66
67/// Why a DSN was refused or a parameter could not be read.
68#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
69pub enum Error {
70    /// The DSN is malformed or lacks a scheme or host.
71    ///
72    /// PHP: `\InvalidArgumentException`.
73    ///
74    /// ```
75    /// use utopia_dsn::{Dsn, Error};
76    ///
77    /// let error = Dsn::parse("localhost:3306").unwrap_err();
78    /// assert!(matches!(error, Error::InvalidArgument(_)));
79    /// assert_eq!(error.to_string(), "Unable to parse DSN: scheme is required");
80    /// ```
81    ///
82    /// ```php
83    /// use Utopia\DSN\DSN;
84    ///
85    /// try {
86    ///     new DSN('localhost:3306');
87    /// } catch (\InvalidArgumentException $e) {
88    ///     echo $e->getMessage(), "\n"; // Unable to parse DSN: scheme is required
89    /// }
90    /// ```
91    #[error("{0}")]
92    InvalidArgument(&'static str),
93    /// [`Dsn::param`] was called on a key the query holds as a list or map
94    /// (`a[b]=c`), which has no single value to return.
95    ///
96    /// PHP: `\TypeError`, as PHP cannot return an array as a string.
97    #[error("{0}")]
98    Type(&'static str),
99}
100
101impl Error {
102    /// The name of the exception class this error matches, such as
103    /// `InvalidArgumentException`.
104    ///
105    /// PHP: the class of the exception `utopia-php/dsn` throws for the same
106    /// input.
107    ///
108    /// ```
109    /// use utopia_dsn::Dsn;
110    ///
111    /// let error = Dsn::parse("redis://").unwrap_err();
112    /// assert_eq!(error.php_class(), "InvalidArgumentException");
113    /// ```
114    ///
115    /// ```php
116    /// use Utopia\DSN\DSN;
117    ///
118    /// try {
119    ///     new DSN('redis://');
120    /// } catch (\Throwable $e) {
121    ///     echo get_class($e), "\n"; // InvalidArgumentException
122    /// }
123    /// ```
124    pub fn php_class(&self) -> &'static str {
125        match self {
126            Error::InvalidArgument(_) => "InvalidArgumentException",
127            Error::Type(_) => "TypeError",
128        }
129    }
130}
131
132/// A parsed DSN.
133///
134/// Its `Debug` output hides the password:
135///
136/// ```
137/// use utopia_dsn::Dsn;
138///
139/// let dsn = Dsn::parse("redis://default:secret@cache:6379")?;
140/// let printed = format!("{dsn:?}");
141/// assert!(printed.contains("cache"));
142/// assert!(!printed.contains("secret"));
143/// # Ok::<(), Box<dyn std::error::Error>>(())
144/// ```
145///
146/// ```php
147/// use Utopia\DSN\DSN;
148///
149/// $dsn = new DSN('redis://default:secret@cache:6379');
150/// echo $dsn->getHost(), "\n"; // cache
151/// ```
152#[derive(Clone)]
153pub struct Dsn {
154    /// Every component, decoded, in one allocation; the ranges index it.
155    /// The scheme, host and query are copied from the `&str` input whole, so
156    /// they are UTF-8.
157    buffer: Box<[u8]>,
158    scheme: Range<usize>,
159    user: Option<Range<usize>>,
160    password: Option<Range<usize>>,
161    host: Range<usize>,
162    port: Option<u16>,
163    path: Range<usize>,
164    query: Option<Range<usize>>,
165    /// The query parsed by `parse_str`, on first use.
166    params: OnceLock<Array>,
167}
168
169impl Dsn {
170    /// Parses a DSN.
171    ///
172    /// Fails with [`Error::InvalidArgument`] when the input is malformed, or
173    /// the scheme or host is missing or empty. A scheme or host of `"0"`
174    /// counts as missing.
175    ///
176    /// PHP: `new DSN($dsn)`. It fails where PHP's `parse_url` rejects the
177    /// input, and `"0"` is missing because PHP's `empty()` says so.
178    ///
179    /// ```
180    /// use utopia_dsn::Dsn;
181    ///
182    /// let dsn = Dsn::parse("redis://cache:6379")?;
183    /// assert_eq!(dsn.host(), "cache");
184    /// assert!(Dsn::parse("redis://").is_err());
185    /// # Ok::<(), Box<dyn std::error::Error>>(())
186    /// ```
187    ///
188    /// ```php
189    /// use Utopia\DSN\DSN;
190    ///
191    /// $dsn = new DSN('redis://cache:6379');
192    /// echo $dsn->getHost(), "\n"; // cache
193    /// ```
194    pub fn parse(dsn: &str) -> Result<Self, Error> {
195        let url =
196            php_std::url::parse_url(dsn.as_bytes()).ok_or(Error::InvalidArgument("Unable to parse DSN: malformed"))?;
197        let scheme = url.scheme().filter(|s| !blank(s));
198        let host = url.host().filter(|h| !blank(h));
199        let (Some(scheme), Some(host)) = (scheme, host) else {
200            return Err(Error::InvalidArgument(if url.scheme().is_none_or(|s| blank(&s)) {
201                "Unable to parse DSN: scheme is required"
202            } else {
203                "Unable to parse DSN: host is required"
204            }));
205        };
206        // Decoding never lengthens a component, so one allocation holds them all.
207        let mut buffer = Vec::with_capacity(dsn.len());
208        let scheme = append(&mut buffer, |b| b.extend_from_slice(&scheme));
209        let user = url.user().map(|u| append(&mut buffer, |b| urldecode_into(b, &u)));
210        let password = url.pass().map(|p| append(&mut buffer, |b| urldecode_into(b, &p)));
211        let host = append(&mut buffer, |b| b.extend_from_slice(&host));
212        let path = append(&mut buffer, |b| {
213            if let Some(p) = url.path() {
214                rawurldecode_into(b, php_std::string::ltrim(&p, b"/"));
215            }
216        });
217        let query = url.query().map(|q| append(&mut buffer, |b| b.extend_from_slice(&q)));
218        Ok(Self {
219            buffer: buffer.into_boxed_slice(),
220            scheme,
221            user,
222            password,
223            host,
224            port: url.port(),
225            path,
226            query,
227            params: OnceLock::new(),
228        })
229    }
230
231    /// Builds a DSN from its parts, encoding each one, so a value cannot
232    /// reshape it (a `?` in the path starting the query, an `@` in the user
233    /// moving the host).
234    ///
235    /// Fails with [`Error::InvalidArgument`] when `password` is given without
236    /// `user`, or when a part would not read back exactly as given (a host
237    /// holding `/`, `@` or `:`, a parameter key `getParam` rewrites, like
238    /// `a.b` or `x[y]`).
239    ///
240    /// PHP: `DSN::from($scheme, $host, $user, $password, $port, $path,
241    /// $params)`. The port is PHP's `?int`; a key of `params` that is a
242    /// canonical integer is an integer key, as in a PHP array literal, and a
243    /// repeated key keeps its last value.
244    ///
245    /// ```
246    /// use utopia_dsn::Dsn;
247    ///
248    /// let dsn = Dsn::from(
249    ///     "s3",
250    ///     "minio.example.com",
251    ///     Some(b"admin@example.com"),
252    ///     Some(b"p@ss/word"),
253    ///     Some(9000),
254    ///     b"bucket",
255    ///     &[("region", "us-east-1")],
256    /// )?;
257    /// assert_eq!(dsn.to_string(), "s3://admin%40example.com:p%40ss%2Fword@minio.example.com:9000/bucket?region=us-east-1");
258    /// assert!(Dsn::from("s3", "user@minio.example.com", None, None, None, b"", &[]).is_err());
259    /// # Ok::<(), Box<dyn std::error::Error>>(())
260    /// ```
261    ///
262    /// ```php
263    /// use Utopia\DSN\DSN;
264    ///
265    /// $dsn = DSN::from(
266    ///     scheme: 's3',
267    ///     host: 'minio.example.com',
268    ///     user: 'admin@example.com',
269    ///     password: 'p@ss/word',
270    ///     port: 9000,
271    ///     path: 'bucket',
272    ///     params: ['region' => 'us-east-1'],
273    /// );
274    /// echo $dsn, "\n"; // s3://admin%40example.com:p%40ss%2Fword@minio.example.com:9000/bucket?region=us-east-1
275    /// ```
276    pub fn from(
277        scheme: &str,
278        host: &str,
279        user: Option<&[u8]>,
280        password: Option<&[u8]>,
281        port: Option<i64>,
282        path: &[u8],
283        params: &[(&str, &str)],
284    ) -> Result<Self, Error> {
285        if user.is_none() && password.is_some() {
286            return Err(Error::InvalidArgument("Unable to build DSN: a password needs a user"));
287        }
288        let mut wanted = Array::new();
289        for (key, value) in params {
290            wanted.set(ArrayKey::from(*key), Value::from(*value));
291        }
292
293        let mut dsn = format!("{scheme}://");
294        write_credentials(&mut dsn, user, password);
295        dsn.push_str(host);
296        if let Some(port) = port {
297            dsn.push(':');
298            dsn.push_str(&port.to_string());
299        }
300        write_path(&mut dsn, path);
301        if !wanted.is_empty() {
302            // http_build_query($params, '', '&', PHP_QUERY_RFC3986) of string values.
303            dsn.push('?');
304            for (index, (key, value)) in wanted.iter().enumerate() {
305                if index > 0 {
306                    dsn.push('&');
307                }
308                let key = match key {
309                    php_std::types::KeyRef::Int(i) => i.to_string(),
310                    php_std::types::KeyRef::Str(s) => rawurlencode(s),
311                };
312                dsn.push_str(&key);
313                dsn.push('=');
314                if let Value::Str(value) = value {
315                    dsn.push_str(&rawurlencode(value));
316                }
317            }
318        }
319
320        let parsed = Self::parse(&dsn)?;
321        drop(dsn);
322
323        // getParam() reads the query with parse_str, which nests `a[b]` and
324        // rewrites `.` and spaces in keys.
325        let query = parse_str(parsed.query().unwrap_or_default().as_bytes());
326        if parsed.scheme() != scheme
327            || parsed.host() != host
328            || parsed.user() != user
329            || parsed.password() != password
330            || parsed.port.map(i64::from) != port
331            || parsed.path() != path
332            || !Value::Array(query).strict_eq(&Value::Array(wanted))
333        {
334            return Err(Error::InvalidArgument("Unable to build DSN: a part does not survive encoding"));
335        }
336        Ok(parsed)
337    }
338
339    /// The scheme: the part before `://`.
340    ///
341    /// PHP: `getScheme()`.
342    ///
343    /// ```
344    /// use utopia_dsn::Dsn;
345    ///
346    /// let dsn = Dsn::parse("postgresql://db:5432/appwrite")?;
347    /// assert_eq!(dsn.scheme(), "postgresql");
348    /// # Ok::<(), Box<dyn std::error::Error>>(())
349    /// ```
350    ///
351    /// ```php
352    /// use Utopia\DSN\DSN;
353    ///
354    /// $dsn = new DSN('postgresql://db:5432/appwrite');
355    /// echo $dsn->getScheme(), "\n"; // postgresql
356    /// ```
357    pub fn scheme(&self) -> &str {
358        self.text(&self.scheme)
359    }
360
361    /// The URL-decoded user, which can be any bytes (`%FF`).
362    ///
363    /// PHP: `getUser()`.
364    ///
365    /// ```
366    /// use utopia_dsn::Dsn;
367    ///
368    /// let dsn = Dsn::parse("smtp://mail%40example.com:secret@smtp.example.com:587")?;
369    /// assert_eq!(dsn.user(), Some(&b"mail@example.com"[..]));
370    /// # Ok::<(), Box<dyn std::error::Error>>(())
371    /// ```
372    ///
373    /// ```php
374    /// use Utopia\DSN\DSN;
375    ///
376    /// $dsn = new DSN('smtp://mail%40example.com:secret@smtp.example.com:587');
377    /// echo $dsn->getUser(), "\n"; // mail@example.com
378    /// ```
379    pub fn user(&self) -> Option<&[u8]> {
380        self.user.clone().map(|range| &self.buffer[range])
381    }
382
383    /// The URL-decoded password, which can be any bytes (`%FF`).
384    ///
385    /// PHP: `getPassword()`.
386    ///
387    /// ```
388    /// use utopia_dsn::Dsn;
389    ///
390    /// let dsn = Dsn::parse("redis://default:p%40ss%2Fword@cache")?;
391    /// assert_eq!(dsn.password(), Some(&b"p@ss/word"[..]));
392    /// # Ok::<(), Box<dyn std::error::Error>>(())
393    /// ```
394    ///
395    /// ```php
396    /// use Utopia\DSN\DSN;
397    ///
398    /// $dsn = new DSN('redis://default:p%40ss%2Fword@cache');
399    /// echo $dsn->getPassword(), "\n"; // p@ss/word
400    /// ```
401    pub fn password(&self) -> Option<&[u8]> {
402        self.password.clone().map(|range| &self.buffer[range])
403    }
404
405    /// The host name or address.
406    ///
407    /// PHP: `getHost()`.
408    ///
409    /// ```
410    /// use utopia_dsn::Dsn;
411    ///
412    /// let dsn = Dsn::parse("mongodb://user:secret@mongo.internal:27017/appwrite")?;
413    /// assert_eq!(dsn.host(), "mongo.internal");
414    /// # Ok::<(), Box<dyn std::error::Error>>(())
415    /// ```
416    ///
417    /// ```php
418    /// use Utopia\DSN\DSN;
419    ///
420    /// $dsn = new DSN('mongodb://user:secret@mongo.internal:27017/appwrite');
421    /// echo $dsn->getHost(), "\n"; // mongo.internal
422    /// ```
423    pub fn host(&self) -> &str {
424        self.text(&self.host)
425    }
426
427    /// The port, or `None` when the DSN has none.
428    ///
429    /// PHP: `getPort()` returns the port as a string (or `null`); Rust as a
430    /// number.
431    ///
432    /// ```
433    /// use utopia_dsn::Dsn;
434    ///
435    /// assert_eq!(Dsn::parse("redis://cache:6379")?.port(), Some(6379));
436    /// assert_eq!(Dsn::parse("redis://cache")?.port(), None);
437    /// # Ok::<(), Box<dyn std::error::Error>>(())
438    /// ```
439    ///
440    /// ```php
441    /// use Utopia\DSN\DSN;
442    ///
443    /// var_dump((new DSN('redis://cache:6379'))->getPort()); // string(4) "6379"
444    /// var_dump((new DSN('redis://cache'))->getPort());      // NULL
445    /// ```
446    pub fn port(&self) -> Option<u16> {
447        self.port
448    }
449
450    /// The URL-decoded path without its leading slashes, which can be any
451    /// bytes (`%FF`); empty when there is none.
452    ///
453    /// PHP: `getPath()`.
454    ///
455    /// ```
456    /// use utopia_dsn::Dsn;
457    ///
458    /// assert_eq!(Dsn::parse("s3://key:secret@s3.amazonaws.com/backups/daily")?.path(), b"backups/daily");
459    /// assert_eq!(Dsn::parse("s3://localhost/b%3Furl%3Dx")?.path(), b"b?url=x");
460    /// assert_eq!(Dsn::parse("redis://cache")?.path(), b"");
461    /// # Ok::<(), Box<dyn std::error::Error>>(())
462    /// ```
463    ///
464    /// ```php
465    /// use Utopia\DSN\DSN;
466    ///
467    /// echo (new DSN('s3://key:secret@s3.amazonaws.com/backups/daily'))->getPath(), "\n"; // backups/daily
468    /// ```
469    pub fn path(&self) -> &[u8] {
470        &self.buffer[self.path.clone()]
471    }
472
473    /// The raw query string, or `None` when the DSN has none.
474    ///
475    /// PHP: `getQuery()`.
476    ///
477    /// ```
478    /// use utopia_dsn::Dsn;
479    ///
480    /// let dsn = Dsn::parse("mariadb://db/appwrite?charset=utf8mb4&timeout=5")?;
481    /// assert_eq!(dsn.query(), Some("charset=utf8mb4&timeout=5"));
482    /// # Ok::<(), Box<dyn std::error::Error>>(())
483    /// ```
484    ///
485    /// ```php
486    /// use Utopia\DSN\DSN;
487    ///
488    /// echo (new DSN('mariadb://db/appwrite?charset=utf8mb4&timeout=5'))->getQuery(), "\n"; // charset=utf8mb4&timeout=5
489    /// ```
490    pub fn query(&self) -> Option<&str> {
491        self.query.as_ref().map(|range| self.text(range))
492    }
493
494    /// The URL-decoded value of a query parameter, or `Ok(None)` when it is
495    /// absent.
496    ///
497    /// A query that is empty or `"0"` has no parameters. Dots and spaces in
498    /// keys read as underscores (`a.b` is `a_b`), and a key written with
499    /// brackets (`a[b]=c`) holds a list or map, so reading it fails with
500    /// [`Error::Type`].
501    ///
502    /// PHP: `getParam($key)`, where `Ok(None)` stands for PHP returning the
503    /// default. Keys follow PHP's `parse_str`.
504    ///
505    /// ```
506    /// use utopia_dsn::Dsn;
507    ///
508    /// let dsn = Dsn::parse("sms://key:secret@api.twilio.com?from=%2B15550100")?;
509    /// assert_eq!(dsn.param("from")?, Some(&b"+15550100"[..]));
510    /// assert_eq!(dsn.param("region")?, None);
511    /// # Ok::<(), Box<dyn std::error::Error>>(())
512    /// ```
513    ///
514    /// ```php
515    /// use Utopia\DSN\DSN;
516    ///
517    /// $dsn = new DSN('sms://key:secret@api.twilio.com?from=%2B15550100');
518    /// echo $dsn->getParam('from'), "\n";          // +15550100
519    /// var_dump($dsn->getParam('region'));         // string(0) ""
520    /// ```
521    pub fn param(&self, key: impl AsRef<[u8]>) -> Result<Option<&[u8]>, Error> {
522        let query = match self.query() {
523            None | Some("" | "0") => return Ok(None),
524            Some(q) => q,
525        };
526        let params = self.params.get_or_init(|| parse_str(query.as_bytes()));
527        match params.get_ref(php_std::types::KeyRef::normalize(key.as_ref())) {
528            None => Ok(None),
529            Some(Value::Str(value)) => Ok(Some(value)),
530            Some(_) => {
531                Err(Error::Type("Utopia\\DSN\\DSN::getParam(): Return value must be of type string, array returned"))
532            }
533        }
534    }
535
536    /// The parameter, or `default` when it is absent.
537    ///
538    /// PHP: `getParam($key, $default)`.
539    ///
540    /// ```
541    /// use utopia_dsn::Dsn;
542    ///
543    /// let dsn = Dsn::parse("s3://key:secret@s3.amazonaws.com/backups")?;
544    /// assert_eq!(dsn.param_or("region", b"us-east-1")?, b"us-east-1");
545    /// # Ok::<(), Box<dyn std::error::Error>>(())
546    /// ```
547    ///
548    /// ```php
549    /// use Utopia\DSN\DSN;
550    ///
551    /// $dsn = new DSN('s3://key:secret@s3.amazonaws.com/backups');
552    /// echo $dsn->getParam('region', 'us-east-1'), "\n"; // us-east-1
553    /// ```
554    pub fn param_or<'a>(&'a self, key: impl AsRef<[u8]>, default: &'a [u8]) -> Result<&'a [u8], Error> {
555        Ok(self.param(key)?.unwrap_or(default))
556    }
557}
558
559/// `user[:password]@`, each part `rawurlencode`d.
560fn write_credentials(dsn: &mut String, user: Option<&[u8]>, password: Option<&[u8]>) {
561    if let Some(user) = user {
562        dsn.push_str(&rawurlencode(user));
563        if let Some(password) = password {
564            dsn.push(':');
565            dsn.push_str(&rawurlencode(password));
566        }
567        dsn.push('@');
568    }
569}
570
571/// `/` and the path's segments, each `rawurlencode`d; nothing for an empty path.
572fn write_path(dsn: &mut String, path: &[u8]) {
573    if !path.is_empty() {
574        for segment in path.split(|&b| b == b'/') {
575            dsn.push('/');
576            dsn.push_str(&rawurlencode(segment));
577        }
578    }
579}
580
581impl fmt::Display for Dsn {
582    /// The DSN, with each part encoded as [`Dsn::from`] encodes it, and the
583    /// query as it was given.
584    ///
585    /// PHP: `__toString()`.
586    ///
587    /// ```
588    /// use utopia_dsn::Dsn;
589    ///
590    /// let dsn = Dsn::parse("mariadb://user:p%40ss@localhost:3306/data%20base?charset=utf8")?;
591    /// assert_eq!(dsn.to_string(), "mariadb://user:p%40ss@localhost:3306/data%20base?charset=utf8");
592    /// # Ok::<(), Box<dyn std::error::Error>>(())
593    /// ```
594    ///
595    /// ```php
596    /// use Utopia\DSN\DSN;
597    ///
598    /// echo new DSN('mariadb://user:p%40ss@localhost:3306/data%20base?charset=utf8'), "\n";
599    /// // mariadb://user:p%40ss@localhost:3306/data%20base?charset=utf8
600    /// ```
601    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
602        let mut dsn = format!("{}://", self.scheme());
603        write_credentials(&mut dsn, self.user(), self.password());
604        dsn.push_str(self.host());
605        if let Some(port) = self.port {
606            dsn.push(':');
607            dsn.push_str(&port.to_string());
608        }
609        write_path(&mut dsn, self.path());
610        if let Some(query) = self.query() {
611            dsn.push('?');
612            dsn.push_str(query);
613        }
614        f.write_str(&dsn)
615    }
616}
617
618/// The range of `buffer` that `write` appends.
619fn append(buffer: &mut Vec<u8>, write: impl FnOnce(&mut Vec<u8>)) -> Range<usize> {
620    let start = buffer.len();
621    write(buffer);
622    start..buffer.len()
623}
624
625impl Dsn {
626    /// A UTF-8 component: the scheme, the host or the query.
627    fn text(&self, range: &Range<usize>) -> &str {
628        std::str::from_utf8(&self.buffer[range.clone()]).unwrap_or_default()
629    }
630}
631
632/// PHP `empty()` on a string: `""` and `"0"`.
633fn blank(s: &[u8]) -> bool {
634    s.is_empty() || s == b"0"
635}
636
637impl fmt::Debug for Dsn {
638    /// Formats every component except the password, which shows as
639    /// `<hidden>`.
640    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
641        f.debug_struct("Dsn")
642            .field("scheme", &self.scheme())
643            .field("user", &self.user().map(String::from_utf8_lossy))
644            .field("password", &self.password.as_ref().map(|_| "<hidden>"))
645            .field("host", &self.host())
646            .field("port", &self.port)
647            .field("path", &String::from_utf8_lossy(self.path()))
648            .field("query", &self.query())
649            .finish()
650    }
651}
652
653#[cfg(test)]
654mod tests {
655    use super::*;
656
657    #[test]
658    fn parses_like_php() {
659        let d = Dsn::parse("mariadb://user:password@localhost:3306/database?charset=utf8&timezone=UTC").unwrap();
660        assert_eq!(d.scheme(), "mariadb");
661        assert_eq!(d.user(), Some(&b"user"[..]));
662        assert_eq!(d.password(), Some(&b"password"[..]));
663        assert_eq!(d.port(), Some(3306));
664        assert_eq!(d.path(), b"database");
665        assert_eq!(d.param("timezone").unwrap(), Some(&b"UTC"[..]));
666        assert_eq!(d.param_or("region", b"us-east-1").unwrap(), b"us-east-1");
667        assert_eq!(Dsn::parse("s://h?%ff=1&=2").unwrap().param(b"\xff").unwrap(), Some(&b"1"[..]));
668        let d = Dsn::parse("sms://user:sl%2Fsh%2B%24%40no%3Aher@localhost").unwrap();
669        assert_eq!(d.password(), Some(&b"sl/sh+$@no:her"[..]));
670        assert_eq!(d.path(), b"");
671        assert_eq!(d.query(), None);
672    }
673
674    #[test]
675    fn refuses_without_quoting_credentials() {
676        for dsn in
677            ["s3://AKIAKEY:SECRETKEY@/backups", "//AKIAKEY:SECRETKEY@localhost/db", "AKIAKEY:SECRETKEY@localhost"]
678        {
679            let e = Dsn::parse(dsn).unwrap_err();
680            let printed = format!("{e} {e:?}");
681            assert!(!printed.contains("AKIAKEY") && !printed.contains("SECRETKEY"), "{printed}");
682            assert_eq!(e.php_class(), "InvalidArgumentException");
683        }
684        let d = Dsn::parse("redis://user:SECRETKEY@host").unwrap();
685        assert!(!format!("{d:?}").contains("SECRETKEY"));
686    }
687
688    #[test]
689    fn array_params_are_type_errors() {
690        let d = Dsn::parse("x://h?a[b]=1&c=2").unwrap();
691        assert_eq!(d.param("a").unwrap_err().php_class(), "TypeError");
692        assert_eq!(d.param("c").unwrap(), Some(&b"2"[..]));
693        assert_eq!(Dsn::parse("x://h?0").unwrap().param("0").unwrap(), None);
694    }
695}