Skip to main content

reddb_wire/
conn_string.rs

1//! Connection-string parser shared across `reddb`, `reddb-client`,
2//! `red_client`, and every language driver.
3//!
4//! Pure function over a string; no I/O, no allocation beyond what the
5//! returned [`ConnectionTarget`] needs. The grammar is defined by
6//! `docs/clients/connection-strings.md`; this module is the canonical
7//! parser and is the single source of truth consumed by the rest of
8//! the workspace.
9//!
10//! The parser ports the logic that previously lived in
11//! `drivers/rust/src/connect.rs` (which keeps a thin re-export layer
12//! for backwards compatibility while drivers migrate over). Cluster
13//! URIs (`grpc://primary,replica:port`), default ports per scheme,
14//! and the `?route=primary` override behave identically to the
15//! original.
16
17use std::path::PathBuf;
18
19use url::Url;
20
21/// Stable error code for parser failures.
22///
23/// Mirrors the `ErrorCode` shape used by the language drivers so that
24/// downstream wrappers can map 1:1 without information loss.
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26pub enum ParseErrorKind {
27    /// The input was empty.
28    Empty,
29    /// `url::Url` rejected the string, or a transport-specific
30    /// invariant (missing host, empty cluster entry, bad port…) was
31    /// violated.
32    InvalidUri,
33    /// The scheme is not in the documented vocabulary.
34    UnsupportedScheme,
35    /// A DoS guardrail in [`ConnStringLimits`] was tripped.
36    /// `message` carries the limit name + the offending value so
37    /// downstream wrappers can surface the structured detail.
38    LimitExceeded,
39}
40
41impl ParseErrorKind {
42    pub fn as_str(self) -> &'static str {
43        match self {
44            ParseErrorKind::Empty => "EMPTY",
45            ParseErrorKind::InvalidUri => "INVALID_URI",
46            ParseErrorKind::UnsupportedScheme => "UNSUPPORTED_SCHEME",
47            ParseErrorKind::LimitExceeded => "LIMIT_EXCEEDED",
48        }
49    }
50}
51
52/// Error returned by [`parse`].
53#[derive(Debug, Clone, PartialEq, Eq)]
54pub struct ParseError {
55    pub kind: ParseErrorKind,
56    pub message: String,
57}
58
59impl ParseError {
60    pub fn new(kind: ParseErrorKind, message: impl Into<String>) -> Self {
61        Self {
62            kind,
63            message: message.into(),
64        }
65    }
66}
67
68impl std::fmt::Display for ParseError {
69    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
70        write!(f, "{}: {}", self.kind.as_str(), self.message)
71    }
72}
73
74impl std::error::Error for ParseError {}
75
76/// Default port per documented scheme. Centralised so other crates
77/// (the connector, server-side dispatch) can stay consistent.
78pub const DEFAULT_PORT_RED: u16 = 5050;
79pub const DEFAULT_PORT_GRPC: u16 = 55055;
80pub const DEFAULT_PORT_GRPCS: u16 = 55555;
81/// Default ports for `ws://` / `red+ws://` and `wss://` / `red+wss://` — align with the
82/// standard WS / WSS browser defaults (80 and 443) so a hosted endpoint
83/// like `*.db.reddb.io` works without an explicit port.
84pub const DEFAULT_PORT_WS: u16 = 80;
85pub const DEFAULT_PORT_WSS: u16 = 443;
86
87/// URI schemes accepted by the connection-string parser.
88///
89/// This enum is the connection-layer source for generated agent knowledge:
90/// [`crate::knowledge`] iterates [`SUPPORTED_SCHEMES`] instead of carrying a
91/// separate hand-maintained scheme list.
92#[derive(Debug, Clone, Copy, PartialEq, Eq)]
93pub enum ConnectionScheme {
94    Memory,
95    Temporary,
96    File,
97    Red,
98    Reds,
99    RedWs,
100    RedWss,
101    Ws,
102    Wss,
103    Grpc,
104    Grpcs,
105    Http,
106    Https,
107}
108
109/// Stable parser-owned list of supported URI schemes.
110pub const SUPPORTED_SCHEMES: &[ConnectionScheme] = &[
111    ConnectionScheme::Red,
112    ConnectionScheme::Reds,
113    ConnectionScheme::Grpc,
114    ConnectionScheme::Grpcs,
115    ConnectionScheme::Http,
116    ConnectionScheme::Https,
117    ConnectionScheme::Memory,
118    ConnectionScheme::Temporary,
119    ConnectionScheme::File,
120    ConnectionScheme::RedWs,
121    ConnectionScheme::RedWss,
122    ConnectionScheme::Ws,
123    ConnectionScheme::Wss,
124];
125
126impl ConnectionScheme {
127    pub fn from_uri_scheme(scheme: &str) -> Option<Self> {
128        match scheme {
129            "memory" => Some(Self::Memory),
130            "tmp" => Some(Self::Temporary),
131            "file" => Some(Self::File),
132            "red" => Some(Self::Red),
133            "reds" => Some(Self::Reds),
134            "red+ws" => Some(Self::RedWs),
135            "red+wss" => Some(Self::RedWss),
136            "ws" => Some(Self::Ws),
137            "wss" => Some(Self::Wss),
138            "grpc" => Some(Self::Grpc),
139            "grpcs" => Some(Self::Grpcs),
140            "http" => Some(Self::Http),
141            "https" => Some(Self::Https),
142            _ => None,
143        }
144    }
145
146    pub fn uri_prefix(self) -> &'static str {
147        match self {
148            Self::Memory => "memory://",
149            Self::Temporary => "tmp://",
150            Self::File => "file://",
151            Self::Red => "red://",
152            Self::Reds => "reds://",
153            Self::RedWs => "red+ws://",
154            Self::RedWss => "red+wss://",
155            Self::Ws => "ws://",
156            Self::Wss => "wss://",
157            Self::Grpc => "grpc://",
158            Self::Grpcs => "grpcs://",
159            Self::Http => "http://",
160            Self::Https => "https://",
161        }
162    }
163
164    pub fn transport(self) -> &'static str {
165        match self {
166            Self::Memory => "embedded in-memory engine",
167            Self::Temporary => "embedded temporary file-backed engine",
168            Self::File => "embedded file-backed engine",
169            Self::Red | Self::Reds => "RedWire TCP",
170            Self::RedWs | Self::RedWss | Self::Ws | Self::Wss => "RedWire WebSocket",
171            Self::Grpc | Self::Grpcs => "gRPC",
172            Self::Http | Self::Https => "HTTP REST",
173        }
174    }
175
176    pub fn mode(self) -> &'static str {
177        match self {
178            Self::Memory | Self::Temporary | Self::File => "embedded",
179            Self::Red
180            | Self::Reds
181            | Self::RedWs
182            | Self::RedWss
183            | Self::Ws
184            | Self::Wss
185            | Self::Grpc
186            | Self::Grpcs
187            | Self::Http
188            | Self::Https => "remote",
189        }
190    }
191
192    pub fn example(self) -> &'static str {
193        match self {
194            Self::Memory => "memory://",
195            Self::Temporary => "tmp://",
196            Self::File => "file:///var/lib/reddb/app.db",
197            Self::Red => "red://db.example.com:5050",
198            Self::Reds => "reds://db.example.com:5050",
199            Self::RedWs => "red+ws://db.example.com",
200            Self::RedWss => "red+wss://db.example.com",
201            Self::Ws => "ws://db.example.com",
202            Self::Wss => "wss://db.example.com",
203            Self::Grpc => "grpc://db.example.com:55055",
204            Self::Grpcs => "grpcs://db.example.com:55555",
205            Self::Http => "http://db.example.com:80",
206            Self::Https => "https://db.example.com:443",
207        }
208    }
209
210    pub fn notes(self) -> &'static str {
211        match self {
212            Self::Memory => "Process-local database backed by RAM.",
213            Self::Temporary => "Temporary database file removed on normal close.",
214            Self::File => "Embedded durable engine rooted at the URI path.",
215            Self::Red => "Principal RedWire transport without TLS.",
216            Self::Reds => "Principal RedWire transport with TLS.",
217            Self::RedWs => "Browser-native RedWire over WebSocket without TLS.",
218            Self::RedWss => "Browser-native RedWire over WebSocket with TLS.",
219            Self::Ws => "Browser-friendly alias for RedWire over WebSocket without TLS.",
220            Self::Wss => "Browser-friendly alias for RedWire over WebSocket with TLS.",
221            Self::Grpc => "Compatibility transport for existing gRPC clients.",
222            Self::Grpcs => "TLS variant of the gRPC compatibility transport.",
223            Self::Http => "REST/admin transport without TLS.",
224            Self::Https => "REST/admin transport with TLS.",
225        }
226    }
227}
228
229/// DoS guardrails applied by [`parse`] before any URI work happens.
230///
231/// The connection-string parser is the only entry point an attacker
232/// can reach BEFORE auth, so every limit here is enforced eagerly
233/// and surfaces as a structured [`ParseErrorKind::LimitExceeded`]
234/// error rather than a panic, hang, or unbounded allocation.
235#[derive(Debug, Clone, Copy, PartialEq, Eq)]
236pub struct ConnStringLimits {
237    /// Maximum length of the input URI in bytes. Default `8 KiB`.
238    pub max_uri_bytes: usize,
239    /// Maximum number of `key=value` query parameters. Default `32`.
240    pub max_query_params: usize,
241    /// Maximum number of comma-separated cluster hosts allowed in a
242    /// `grpc://`/`grpcs://` cluster URI. Default `64`.
243    pub max_cluster_hosts: usize,
244}
245
246impl Default for ConnStringLimits {
247    fn default() -> Self {
248        Self {
249            max_uri_bytes: 8 * 1024,
250            max_query_params: 32,
251            max_cluster_hosts: 64,
252        }
253    }
254}
255
256/// Normalised target produced by [`parse`].
257///
258/// Variants intentionally mirror the public Rust client target shape
259/// so callers can keep a thin compatibility layer without duplicating
260/// parser behavior.
261#[derive(Debug, Clone, PartialEq, Eq)]
262pub enum ConnectionTarget {
263    /// `memory://` — ephemeral, in-memory backend.
264    Memory,
265    /// `tmp://` — ephemeral, file-backed database.
266    Temporary,
267    /// `file:///abs/path` — embedded engine on disk.
268    File { path: PathBuf },
269    /// Single remote endpoint over `grpc://` or `grpcs://`. Stored as a
270    /// normalised `http://` or `https://` endpoint for tonic.
271    Grpc { endpoint: String },
272    /// Multi-host gRPC URI: primary + read replicas. Writes hit the
273    /// primary; reads round-robin across replicas unless
274    /// `force_primary` is set.
275    GrpcCluster {
276        primary: String,
277        replicas: Vec<String>,
278        force_primary: bool,
279    },
280    /// `http://host:port` / `https://host:port` — REST endpoint.
281    Http { base_url: String },
282    /// `red://host:port` (plain TCP) or `reds://host:port` (TLS).
283    /// RedWire binary frame protocol per ADR 0001. The connector
284    /// speaks framed binary directly; it does NOT route through
285    /// tonic.
286    RedWire { host: String, port: u16, tls: bool },
287    /// `red+ws://host:port` / `ws://host:port` (plain WS) or
288    /// `red+wss://host:port` / `wss://host:port` (WSS).
289    /// Browser-native WebSocket transport (ADR 0047 direct-when-reachable).
290    /// The UI connects directly — no local RedWire-over-TCP bridge needed.
291    WsNative { host: String, port: u16, tls: bool },
292}
293
294/// Authentication material derived from a connection string or adjacent CLI
295/// fallback. `Debug` deliberately redacts every caller-supplied credential.
296#[derive(Clone, PartialEq, Eq)]
297pub enum ConnectionAuth {
298    Anonymous,
299    Bearer(String),
300    Basic { user: String, pass: String },
301    ApiKey(String),
302}
303
304impl std::fmt::Debug for ConnectionAuth {
305    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
306        match self {
307            Self::Anonymous => f.write_str("Anonymous"),
308            Self::Bearer(_) => f.debug_tuple("Bearer").field(&"<redacted>").finish(),
309            Self::Basic { .. } => f
310                .debug_struct("Basic")
311                .field("user", &"<redacted>")
312                .field("pass", &"<redacted>")
313                .finish(),
314            Self::ApiKey(_) => f.debug_tuple("ApiKey").field(&"<redacted>").finish(),
315        }
316    }
317}
318
319impl ConnectionAuth {
320    pub fn bearer(token: impl Into<String>) -> Self {
321        Self::Bearer(token.into())
322    }
323
324    pub fn is_bearer(&self) -> bool {
325        matches!(self, Self::Bearer(_))
326    }
327}
328
329/// Connection target plus URL-derived auth metadata.
330#[derive(Debug, Clone, PartialEq, Eq)]
331pub struct ConnectionSpec {
332    pub target: ConnectionTarget,
333    pub auth: ConnectionAuth,
334    pub redacted_uri: String,
335}
336
337/// Parse a connection URI into a [`ConnectionTarget`] under the
338/// default DoS limits.
339///
340/// Pure function, no side effects. Behaviour matches
341/// `drivers/rust/src/connect.rs::parse` 1:1 with two additions:
342///   - Mixed-case schemes (e.g. `Red://`, `REDS://`) are normalised
343///     to lowercase before dispatch.
344///   - Inputs exceeding [`ConnStringLimits`] return a structured
345///     [`ParseErrorKind::LimitExceeded`] error instead of being
346///     processed.
347pub fn parse(uri: &str) -> Result<ConnectionTarget, ParseError> {
348    parse_with_limits(uri, ConnStringLimits::default())
349}
350
351/// Parse a connection URI and derive auth from RFC 3986 userinfo.
352///
353/// The existing [`parse`] function remains target-only for compatibility.
354/// New client-mode entry points should use this richer shape so credentials
355/// are identified and redacted before transport connectors are built.
356pub fn parse_with_auth(uri: &str) -> Result<ConnectionSpec, ParseError> {
357    let normalised = normalise_scheme(uri);
358    let redacted_uri = redact_connection_uri(&normalised);
359    let target =
360        parse(uri).map_err(|err| redact_parse_error(err, uri, &normalised, &redacted_uri))?;
361    let auth = auth_from_uri_userinfo(&normalised)
362        .map_err(|err| redact_parse_error(err, uri, &normalised, &redacted_uri))?;
363    Ok(ConnectionSpec {
364        target,
365        auth,
366        redacted_uri,
367    })
368}
369
370fn redact_parse_error(
371    mut err: ParseError,
372    raw_uri: &str,
373    normalised_uri: &str,
374    redacted_uri: &str,
375) -> ParseError {
376    err.message = err
377        .message
378        .replace(raw_uri, redacted_uri)
379        .replace(normalised_uri, redacted_uri);
380    err
381}
382
383/// Return true for documented embedded aliases that must not resolve to
384/// a remote transport target.
385///
386/// This is intentionally separate from [`parse`]: legacy clients may need
387/// to reject embedded targets before mapping `red://host` onto a remote
388/// compatibility transport.
389pub fn is_embedded_connection_uri(uri: &str) -> bool {
390    let trimmed = uri.trim();
391    matches!(
392        trimmed,
393        "red://" | "red:" | "red:///" | "red://:memory" | "red://:memory:"
394    ) || trimmed.starts_with("red:///")
395}
396
397/// Same as [`parse`] but with caller-supplied DoS guardrails.
398/// Useful for tests that need tighter limits or for callers (a
399/// future admin tool, an offline validator) that need to relax the
400/// defaults.
401pub fn parse_with_limits(
402    uri: &str,
403    limits: ConnStringLimits,
404) -> Result<ConnectionTarget, ParseError> {
405    if uri.is_empty() {
406        return Err(ParseError::new(
407            ParseErrorKind::Empty,
408            "empty connection string",
409        ));
410    }
411
412    if uri.len() > limits.max_uri_bytes {
413        return Err(ParseError::new(
414            ParseErrorKind::LimitExceeded,
415            format!(
416                "max_uri_bytes exceeded: limit={} actual={}",
417                limits.max_uri_bytes,
418                uri.len(),
419            ),
420        ));
421    }
422
423    // Lowercase the scheme so `Red://Host`, `REDS://Host`, etc.
424    // dispatch identically to the canonical lowercase forms. The
425    // host and path retain original casing — host is downcased by
426    // `url::Url` for IDN per spec, path stays verbatim.
427    let normalised = normalise_scheme(uri);
428    let uri = normalised.as_str();
429
430    if uri == "memory://" || uri == "memory:" {
431        return Ok(ConnectionTarget::Memory);
432    }
433    if uri == "tmp://" || uri == "tmp:" {
434        return Ok(ConnectionTarget::Temporary);
435    }
436
437    if let Some(rest) = uri.strip_prefix("file://") {
438        if rest.is_empty() {
439            return Err(ParseError::new(
440                ParseErrorKind::InvalidUri,
441                "file:// URI is missing a path",
442            ));
443        }
444        return Ok(ConnectionTarget::File {
445            path: file_uri_path(rest),
446        });
447    }
448
449    if let Some(cluster) = try_parse_grpc_cluster(uri, &limits)? {
450        return Ok(cluster);
451    }
452
453    // Before `Url::parse`, because a multi-host authority like
454    // `red://a:1,b:2` fails URL parsing with "invalid port number" — a
455    // message that hides the real problem. `red://` no longer folds to
456    // gRPC (#2159), and RedWire has no multi-host form, so a cluster URI
457    // has to name the transport that supports one.
458    if let Some(rest) = uri
459        .strip_prefix("red://")
460        .or_else(|| uri.strip_prefix("reds://"))
461    {
462        let authority = rest.split(['/', '?', '#']).next().unwrap_or(rest);
463        if authority.contains(',') {
464            return Err(ParseError::new(
465                ParseErrorKind::InvalidUri,
466                "RedWire does not support comma-separated cluster hosts; \
467                 use grpc:// or grpcs:// for a cluster URI",
468            ));
469        }
470    }
471
472    let parsed = Url::parse(uri)
473        .map_err(|e| ParseError::new(ParseErrorKind::InvalidUri, format!("{e}: {uri}")))?;
474
475    enforce_query_param_limit(&parsed, &limits)?;
476
477    match ConnectionScheme::from_uri_scheme(parsed.scheme()) {
478        Some(ConnectionScheme::Red | ConnectionScheme::Reds) => {
479            let host = parsed.host_str().ok_or_else(|| {
480                ParseError::new(ParseErrorKind::InvalidUri, "red:// URI is missing a host")
481            })?;
482            if host.contains(',') {
483                return Err(ParseError::new(
484                    ParseErrorKind::InvalidUri,
485                    "RedWire does not support comma-separated cluster hosts",
486                ));
487            }
488            let port = parsed.port().unwrap_or(DEFAULT_PORT_RED);
489            Ok(ConnectionTarget::RedWire {
490                host: host.to_string(),
491                port,
492                tls: parsed.scheme() == "reds",
493            })
494        }
495        Some(
496            ConnectionScheme::RedWs
497            | ConnectionScheme::RedWss
498            | ConnectionScheme::Ws
499            | ConnectionScheme::Wss,
500        ) => {
501            let host = parsed.host_str().ok_or_else(|| {
502                ParseError::new(
503                    ParseErrorKind::InvalidUri,
504                    "RedWire WebSocket URI is missing a host",
505                )
506            })?;
507            let tls = parsed.scheme() == "red+wss" || parsed.scheme() == "wss";
508            let port = parsed.port().unwrap_or(if tls {
509                DEFAULT_PORT_WSS
510            } else {
511                DEFAULT_PORT_WS
512            });
513            Ok(ConnectionTarget::WsNative {
514                host: host.to_string(),
515                port,
516                tls,
517            })
518        }
519        Some(ConnectionScheme::Grpc | ConnectionScheme::Grpcs) => {
520            let host = parsed.host_str().ok_or_else(|| {
521                ParseError::new(ParseErrorKind::InvalidUri, "grpc:// URI is missing a host")
522            })?;
523            let port = parsed.port().unwrap_or_else(|| {
524                if parsed.scheme() == "grpcs" {
525                    DEFAULT_PORT_GRPCS
526                } else {
527                    DEFAULT_PORT_GRPC
528                }
529            });
530            let endpoint_scheme = if parsed.scheme() == "grpcs" {
531                "https"
532            } else {
533                "http"
534            };
535            Ok(ConnectionTarget::Grpc {
536                endpoint: format!("{endpoint_scheme}://{host}:{port}"),
537            })
538        }
539        Some(ConnectionScheme::Http | ConnectionScheme::Https) => {
540            let host = parsed.host_str().ok_or_else(|| {
541                ParseError::new(
542                    ParseErrorKind::InvalidUri,
543                    "http(s):// URI is missing a host",
544                )
545            })?;
546            let scheme = parsed.scheme();
547            let port = parsed
548                .port()
549                .unwrap_or(if scheme == "https" { 443 } else { 80 });
550            Ok(ConnectionTarget::Http {
551                base_url: format!("{scheme}://{host}:{port}"),
552            })
553        }
554        Some(ConnectionScheme::Memory | ConnectionScheme::Temporary | ConnectionScheme::File)
555        | None => Err(ParseError::new(
556            ParseErrorKind::UnsupportedScheme,
557            format!("unsupported scheme: {}", parsed.scheme()),
558        )),
559    }
560}
561
562fn file_uri_path(path: &str) -> PathBuf {
563    #[cfg(windows)]
564    {
565        let bytes = path.as_bytes();
566        // RFC 8089 spells a Windows drive path as file:///C:/path. After
567        // removing `file://`, discard only the URI separator before a drive
568        // letter; retaining it produces the invalid Windows path `\C:\...`.
569        if bytes.len() >= 4
570            && bytes[0] == b'/'
571            && bytes[1].is_ascii_alphabetic()
572            && bytes[2] == b':'
573            && matches!(bytes[3], b'/' | b'\\')
574        {
575            return PathBuf::from(&path[1..]);
576        }
577    }
578    PathBuf::from(path)
579}
580
581/// Lowercase only the scheme portion (everything before the first
582/// `:`), leaving host/path/query untouched. Returns the original
583/// string when no scheme separator is present so the downstream
584/// `Url::parse` path produces the canonical "missing scheme" error
585/// instead of being masked here.
586fn normalise_scheme(uri: &str) -> String {
587    match uri.find(':') {
588        Some(i) => {
589            let scheme = &uri[..i];
590            // Only ASCII alphanumerics + `+ . -` are valid scheme
591            // bytes per RFC 3986. If the prefix violates that we
592            // leave it alone so `Url::parse` can produce the
593            // structured error.
594            if scheme.is_empty()
595                || !scheme
596                    .bytes()
597                    .all(|b| b.is_ascii_alphanumeric() || b == b'+' || b == b'.' || b == b'-')
598            {
599                return uri.to_string();
600            }
601            let mut out = String::with_capacity(uri.len());
602            out.push_str(&scheme.to_ascii_lowercase());
603            out.push_str(&uri[i..]);
604            out
605        }
606        None => uri.to_string(),
607    }
608}
609
610fn auth_from_uri_userinfo(uri: &str) -> Result<ConnectionAuth, ParseError> {
611    if matches!(uri, "memory://" | "memory:" | "tmp://" | "tmp:") || uri.starts_with("file://") {
612        return Ok(ConnectionAuth::Anonymous);
613    }
614    // URL parsers cannot parse multiple independently ported authorities.
615    // Authentication belongs to the entire seed list, not its first host.
616    let mut auth_seed = uri.to_string();
617    if uri.starts_with("grpc://") || uri.starts_with("grpcs://") {
618        if let Some((scheme, rest)) = uri.split_once("://") {
619            let end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
620            let authority = &rest[..end];
621            let (userinfo, hosts) = authority
622                .rsplit_once('@')
623                .map(|(userinfo, hosts)| (format!("{userinfo}@"), hosts))
624                .unwrap_or_else(|| (String::new(), authority));
625            if hosts.contains(',') {
626                auth_seed = format!(
627                    "{scheme}://{userinfo}{}{}",
628                    hosts.split(',').next().unwrap_or_default(),
629                    &rest[end..]
630                );
631            }
632        }
633    }
634    let parsed = Url::parse(&auth_seed)
635        .map_err(|e| ParseError::new(ParseErrorKind::InvalidUri, format!("{e}: {uri}")))?;
636    let username = parsed.username();
637    if username.is_empty() {
638        return Ok(ConnectionAuth::Anonymous);
639    }
640    match parsed.password() {
641        Some(pass) => Ok(ConnectionAuth::Basic {
642            user: username.to_string(),
643            pass: pass.to_string(),
644        }),
645        None => Ok(ConnectionAuth::ApiKey(username.to_string())),
646    }
647}
648
649fn redact_connection_uri(uri: &str) -> String {
650    let uri = redact_uri_userinfo(uri);
651    redact_uri_query_secrets(&uri)
652}
653
654fn redact_uri_userinfo(uri: &str) -> String {
655    let Some(scheme_end) = uri.find("://") else {
656        return uri.to_string();
657    };
658    let authority_start = scheme_end + 3;
659    let authority_end = uri[authority_start..]
660        .find(['/', '?', '#'])
661        .map(|i| authority_start + i)
662        .unwrap_or(uri.len());
663    let authority = &uri[authority_start..authority_end];
664    let Some(at) = authority.rfind('@') else {
665        return uri.to_string();
666    };
667    let userinfo = &authority[..at];
668    let replacement = if userinfo.contains(':') {
669        "<redacted>:<redacted>"
670    } else {
671        "<redacted>"
672    };
673    format!(
674        "{}{}{}",
675        &uri[..authority_start],
676        replacement,
677        &uri[authority_start + at..]
678    )
679}
680
681fn redact_uri_query_secrets(uri: &str) -> String {
682    let Some(query_start) = uri.find('?') else {
683        return uri.to_string();
684    };
685    let query_end = uri[query_start + 1..]
686        .find('#')
687        .map(|offset| query_start + 1 + offset)
688        .unwrap_or(uri.len());
689    let query = &uri[query_start + 1..query_end];
690    let mut redacted = String::with_capacity(uri.len());
691    redacted.push_str(&uri[..query_start + 1]);
692    for (index, parameter) in query.split('&').enumerate() {
693        if index > 0 {
694            redacted.push('&');
695        }
696        let (name, value) = parameter.split_once('=').unwrap_or((parameter, ""));
697        redacted.push_str(name);
698        if parameter.contains('=') {
699            redacted.push('=');
700            if sensitive_query_name(name) {
701                redacted.push_str("<redacted>");
702            } else {
703                redacted.push_str(value);
704            }
705        }
706    }
707    redacted.push_str(&uri[query_end..]);
708    redacted
709}
710
711fn sensitive_query_name(raw: &str) -> bool {
712    let mut decoded = Vec::with_capacity(raw.len());
713    let bytes = raw.as_bytes();
714    let mut index = 0;
715    while index < bytes.len() {
716        match bytes[index] {
717            b'%' if index + 2 < bytes.len() => {
718                let high = (bytes[index + 1] as char).to_digit(16);
719                let low = (bytes[index + 2] as char).to_digit(16);
720                if let (Some(high), Some(low)) = (high, low) {
721                    decoded.push(((high << 4) | low) as u8);
722                    index += 3;
723                    continue;
724                }
725                decoded.push(bytes[index]);
726            }
727            b'+' => decoded.push(b' '),
728            byte => decoded.push(byte),
729        }
730        index += 1;
731    }
732    let normalized: String = String::from_utf8_lossy(&decoded)
733        .chars()
734        .filter(|ch| *ch != '_' && *ch != '-')
735        .flat_map(char::to_lowercase)
736        .collect();
737    matches!(
738        normalized.as_str(),
739        "token" | "password" | "pass" | "passwd" | "secret" | "cert" | "key" | "ca" | "apikey"
740    ) || normalized.ends_with("token")
741        || normalized.ends_with("password")
742        || normalized.ends_with("passwd")
743        || normalized.ends_with("secret")
744        || normalized.ends_with("apikey")
745        || normalized.ends_with("privatekey")
746        || normalized.ends_with("keyfile")
747        || normalized.ends_with("certfile")
748        || normalized.ends_with("cafile")
749        || ((normalized.starts_with("ssl") || normalized.starts_with("tls"))
750            && (normalized.ends_with("key")
751                || normalized.ends_with("cert")
752                || normalized.ends_with("ca")))
753}
754
755fn enforce_query_param_limit(url: &Url, limits: &ConnStringLimits) -> Result<(), ParseError> {
756    let Some(q) = url.query() else {
757        return Ok(());
758    };
759    if q.is_empty() {
760        return Ok(());
761    }
762    let count = q.split('&').count();
763    if count > limits.max_query_params {
764        return Err(ParseError::new(
765            ParseErrorKind::LimitExceeded,
766            format!(
767                "max_query_params exceeded: limit={} actual={}",
768                limits.max_query_params, count,
769            ),
770        ));
771    }
772    Ok(())
773}
774
775/// Try to parse a multi-host gRPC URI. `Ok(None)` means "this is a
776/// single-host URI — fall through to the standard parser".
777fn try_parse_grpc_cluster(
778    uri: &str,
779    limits: &ConnStringLimits,
780) -> Result<Option<ConnectionTarget>, ParseError> {
781    let (rest, default_port, endpoint_scheme) = if let Some(r) = uri.strip_prefix("grpc://") {
782        (r, DEFAULT_PORT_GRPC, "http")
783    } else if let Some(r) = uri.strip_prefix("grpcs://") {
784        (r, DEFAULT_PORT_GRPCS, "https")
785    } else {
786        return Ok(None);
787    };
788
789    let (host_part, query_part) = match rest.find('?') {
790        Some(i) => (&rest[..i], Some(&rest[i + 1..])),
791        None => (rest, None),
792    };
793    let host_part = host_part
794        .rsplit_once('@')
795        .map(|(_, hosts)| hosts)
796        .unwrap_or(host_part);
797
798    if !host_part.contains(',') {
799        return Ok(None);
800    }
801
802    let raw_count = host_part.split(',').count();
803    if raw_count > limits.max_cluster_hosts {
804        return Err(ParseError::new(
805            ParseErrorKind::LimitExceeded,
806            format!(
807                "max_cluster_hosts exceeded: limit={} actual={}",
808                limits.max_cluster_hosts, raw_count,
809            ),
810        ));
811    }
812
813    let mut endpoints: Vec<String> = Vec::with_capacity(raw_count);
814    for raw in host_part.split(',') {
815        let raw = raw.trim();
816        if raw.is_empty() {
817            return Err(ParseError::new(
818                ParseErrorKind::InvalidUri,
819                "grpc cluster URI has an empty host entry",
820            ));
821        }
822        // Bracketed IPv6 literal: `[::1]:5050` or `[::1]`.
823        let (host, port) = if let Some(after_bracket) = raw.strip_prefix('[') {
824            let end = after_bracket.find(']').ok_or_else(|| {
825                ParseError::new(
826                    ParseErrorKind::InvalidUri,
827                    format!("unterminated IPv6 bracket in cluster URI: {raw}"),
828                )
829            })?;
830            let host = &after_bracket[..end];
831            let tail = &after_bracket[end + 1..];
832            let port = if tail.is_empty() {
833                default_port
834            } else if let Some(p) = tail.strip_prefix(':') {
835                p.parse::<u16>().map_err(|_| {
836                    ParseError::new(
837                        ParseErrorKind::InvalidUri,
838                        format!("invalid port in cluster URI: {raw}"),
839                    )
840                })?
841            } else {
842                return Err(ParseError::new(
843                    ParseErrorKind::InvalidUri,
844                    format!("trailing junk after IPv6 bracket in cluster URI: {raw}"),
845                ));
846            };
847            (format!("[{host}]"), port)
848        } else {
849            match raw.rsplit_once(':') {
850                Some((h, p)) => {
851                    let port: u16 = p.parse().map_err(|_| {
852                        ParseError::new(
853                            ParseErrorKind::InvalidUri,
854                            format!("invalid port in cluster URI: {raw}"),
855                        )
856                    })?;
857                    (h.to_string(), port)
858                }
859                None => (raw.to_string(), default_port),
860            }
861        };
862        if host.is_empty() || host == "[]" {
863            return Err(ParseError::new(
864                ParseErrorKind::InvalidUri,
865                "grpc cluster URI has an empty host entry",
866            ));
867        }
868        endpoints.push(format!("{endpoint_scheme}://{host}:{port}"));
869    }
870
871    if let Some(q) = query_part {
872        let qcount = if q.is_empty() {
873            0
874        } else {
875            q.split('&').count()
876        };
877        if qcount > limits.max_query_params {
878            return Err(ParseError::new(
879                ParseErrorKind::LimitExceeded,
880                format!(
881                    "max_query_params exceeded: limit={} actual={}",
882                    limits.max_query_params, qcount,
883                ),
884            ));
885        }
886    }
887
888    let force_primary = query_part
889        .map(|q| {
890            q.split('&').any(|kv| {
891                let mut parts = kv.splitn(2, '=');
892                let k = parts.next().unwrap_or("");
893                let v = parts.next().unwrap_or("");
894                k.eq_ignore_ascii_case("route") && v.eq_ignore_ascii_case("primary")
895            })
896        })
897        .unwrap_or(false);
898
899    let mut iter = endpoints.into_iter();
900    let primary = iter.next().expect("split on ',' yields at least one entry");
901    let replicas: Vec<String> = iter.collect();
902
903    Ok(Some(ConnectionTarget::GrpcCluster {
904        primary,
905        replicas,
906        force_primary,
907    }))
908}