stock-bot/tools/curate-etl/src/mongo_safety.rs

1068 lines
34 KiB
Rust

//! Pure, offline, `std`-only read-only MongoDB URI safety guard.
//!
//! This module ports the MongoDB target-classification rules from
//! `apps/stock/config/src/env-safety.ts` (and the authority/remainder `@` check
//! from `libs/core/config/src/schemas/database.schema.ts`) to Rust, and adds
//! stricter read-only enforcement for `curate-etl`:
//!
//! 1. Rejects malformed URIs, ASCII control characters, Unicode whitespace,
//! unencoded `#` or multiple `@` in authority, `@` in path/query when
//! authority has no credentials, invalid percent-encoding, and forbidden
//! decoded host characters.
//! 2. Rejects `trading_admin` (percent-decoded, ASCII case-insensitive) on
//! **any** host regardless of [`ReadOnlyPolicy::allowed_read_users`].
//! 3. Classifies any loopback or local-machine host on port `27017` (or omitted
//! default port) as a QA MongoDB target, and requires an allowlisted
//! read-only username (default: `["studio_stock_bot_read"]`) with explicit
//! credentials on QA targets.
//! 4. Produces a [`ValidatedReadOnlyMongoUri`] token with private fields and no
//! public constructor other than [`assert_read_only_mongo_uri`], so future
//! MongoDB cursor modules can require validated URIs by type.
//!
//! # Non-goals & boundaries
//! - **No I/O or network:** never opens sockets, never resolves DNS, and never
//! spawns subprocesses.
//! - **No URI query-option parsing:** beyond authority/remainder splitting and
//! the no-credentials remainder-`@` check, query parameters are not parsed or
//! validated (no invented option rules).
use std::collections::BTreeSet;
use std::error::Error;
use std::fmt;
/// Default allowlisted read-only MongoDB username for QA targets.
pub const DEFAULT_ALLOWED_READ_USER: &str = "studio_stock_bot_read";
/// Admin username forbidden on any MongoDB host (ASCII case-insensitive).
pub const FORBIDDEN_ADMIN_USER: &str = "trading_admin";
/// Default QA MongoDB port.
pub const QA_MONGO_PORT: u16 = 27017;
const MAX_MONGO_HOST_DECODE_PASSES: usize = 8;
/// Supported MongoDB URI schemes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MongoScheme {
/// `mongodb://` (default port `27017`, allows `.sock` Unix domain sockets).
Standard,
/// `mongodb+srv://` (no default port, single seed host, no explicit port,
/// no Unix domain sockets).
Srv,
}
/// A single decoded host/port seed entry from a MongoDB URI.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MongoTargetHost {
pub host: String,
pub port: Option<u16>,
}
/// Parsed MongoDB URI target metadata (never stores the raw URI or password).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MongoTarget {
pub scheme: MongoScheme,
pub hosts: Vec<MongoTargetHost>,
pub database: Option<String>,
pub username: Option<String>,
has_invalid_host_segment: bool,
has_explicit_port: bool,
}
impl MongoTarget {
/// Returns `true` if any comma-separated host segment was empty or had
/// malformed port/bracket syntax while at least one other host parsed.
pub fn has_invalid_host_segment(&self) -> bool {
self.has_invalid_host_segment
}
/// Returns `true` if any host segment included an explicit `:` port suffix
/// (including a trailing `:` with an empty port).
pub fn has_explicit_port(&self) -> bool {
self.has_explicit_port
}
}
/// Set of local-machine hostnames and IP addresses treated as local for QA
/// MongoDB target classification.
///
/// Injecting this set explicitly keeps tests deterministic and offline.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct LocalHosts {
hosts: BTreeSet<String>,
}
impl LocalHosts {
/// Returns an empty set (only loopback addresses will match as local).
pub fn empty() -> Self {
Self::default()
}
/// Builds a `LocalHosts` set from raw hostnames or IP strings.
pub fn new<I, S>(hosts: I) -> Self
where
I: IntoIterator<Item = S>,
S: AsRef<str>,
{
let mut set = Self::empty();
for host in hosts {
if let Some(normalized) = normalize_local_host_entry(host.as_ref()) {
set.hosts.insert(normalized);
}
}
set
}
/// Builds a `LocalHosts` set from an optional machine hostname and a list
/// of local interface IP addresses, matching `getLocalMachineHosts` in
/// `apps/stock/config/src/env-safety.ts`:
///
/// - Adds the trimmed, trailing-dot-stripped, lowercased full hostname,
/// its short label before the first `.`, and `<short>.local`.
/// - Adds each IP with outer brackets and `%zone` suffixes stripped and
/// lowercased.
pub fn from_hostname_and_ips<I, S>(hostname: Option<&str>, ips: I) -> Self
where
I: IntoIterator<Item = S>,
S: AsRef<str>,
{
let mut set = Self::empty();
if let Some(name) = hostname {
set.insert_hostname(name);
}
for ip in ips {
if let Some(normalized) = normalize_local_host_entry(ip.as_ref()) {
set.hosts.insert(normalized);
}
}
set
}
/// Adds a single normalized host or IP entry and returns `self`.
pub fn with_host(mut self, host: &str) -> Self {
if let Some(normalized) = normalize_local_host_entry(host) {
self.hosts.insert(normalized);
}
self
}
/// Returns `true` if the normalized host or IP is present in this set.
pub fn contains(&self, host: &str) -> bool {
normalize_local_host_entry(host)
.map(|normalized| self.hosts.contains(&normalized))
.unwrap_or(false)
}
/// Best-effort local host detection using only the Rust standard library.
///
/// Reads `HOSTNAME` from the environment and `/etc/hostname` (when
/// readable). Because this module is strictly `std`-only and performs no
/// network-interface enumeration or DNS lookups, multi-homed LAN IPs are
/// **not** discovered automatically; callers on multi-homed hosts should
/// inject LAN IPs explicitly via [`LocalHosts::from_hostname_and_ips`].
pub fn detect() -> Self {
let env_hostname = std::env::var("HOSTNAME").ok();
let etc_hostname = std::fs::read_to_string("/etc/hostname").ok();
Self::detect_from_sources(env_hostname.as_deref(), etc_hostname.as_deref())
}
fn detect_from_sources(env_hostname: Option<&str>, etc_hostname: Option<&str>) -> Self {
let mut set = Self::empty();
if let Some(name) = env_hostname {
set.insert_hostname(name);
}
if let Some(contents) = etc_hostname {
if let Some(first_line) = contents.lines().find(|line| !line.trim().is_empty()) {
set.insert_hostname(first_line);
}
}
set
}
fn insert_hostname(&mut self, raw: &str) {
let normalized = raw.trim().trim_end_matches('.').to_lowercase();
if normalized.is_empty() {
return;
}
self.hosts.insert(normalized.clone());
if let Some(short_name) = normalized.split('.').next() {
if !short_name.is_empty() {
self.hosts.insert(short_name.to_owned());
self.hosts.insert(format!("{short_name}.local"));
}
}
}
}
/// Policy controlling which usernames are permitted to read a QA MongoDB target.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ReadOnlyPolicy {
/// Exact allowlisted usernames for QA MongoDB targets.
///
/// Note: [`FORBIDDEN_ADMIN_USER`] (`"trading_admin"`) is always rejected on
/// every host even if a caller adds it to this list.
pub allowed_read_users: Vec<String>,
}
impl Default for ReadOnlyPolicy {
fn default() -> Self {
Self {
allowed_read_users: vec![DEFAULT_ALLOWED_READ_USER.to_owned()],
}
}
}
/// Proof token that a MongoDB URI passed [`assert_read_only_mongo_uri`].
///
/// All fields are private and there is no public constructor other than
/// [`assert_read_only_mongo_uri`]. Both [`fmt::Debug`] and [`fmt::Display`]
/// redact the password in userinfo.
#[derive(Clone, PartialEq, Eq)]
pub struct ValidatedReadOnlyMongoUri {
uri: String,
target: MongoTarget,
is_qa: bool,
}
impl ValidatedReadOnlyMongoUri {
/// Returns the original validated URI string for passing to a MongoDB
/// driver. Callers must not log this string directly; use [`Self::redacted`]
/// or `Display`/`Debug` instead.
pub fn as_str(&self) -> &str {
&self.uri
}
/// Returns the parsed target metadata.
pub fn target(&self) -> &MongoTarget {
&self.target
}
/// Returns `true` if this URI targets a local QA MongoDB instance.
pub fn is_qa_target(&self) -> bool {
self.is_qa
}
/// Returns a copy of the URI with any userinfo password replaced by
/// `[REDACTED]`.
pub fn redacted(&self) -> String {
redact_mongo_uri_password(&self.uri)
}
}
impl fmt::Display for ValidatedReadOnlyMongoUri {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.redacted())
}
}
impl fmt::Debug for ValidatedReadOnlyMongoUri {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ValidatedReadOnlyMongoUri")
.field("uri", &self.redacted())
.field("target", &self.target)
.field("is_qa", &self.is_qa)
.finish()
}
}
/// Failure reasons returned by [`parse_mongo_target`] and
/// [`assert_read_only_mongo_uri`].
///
/// Variants intentionally never store raw URIs, raw authorities, or passwords
/// so neither `Debug` nor `Display` can leak credentials.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MongoSafetyError {
EmptyUri,
ControlCharacters,
ForbiddenWhitespace,
UnsupportedScheme,
EmptyAuthority,
UnencodedHashInAuthority,
EmptyUserinfo,
MultipleAtInAuthority,
UnencodedAtInRemainderWithoutCredentials,
EmptyHostList,
InvalidUsernameEncoding,
InvalidHostEncoding,
ForbiddenHostCharacters,
NoValidHosts,
MalformedHostSegment,
InvalidSrvTarget,
ForbiddenAdminUser,
MissingCredentialsForQaTarget,
UnauthorizedQaUser,
}
impl fmt::Display for MongoSafetyError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::EmptyUri => f.write_str("Safety guard: MongoDB URI is missing or empty."),
Self::ControlCharacters => f.write_str(
"Safety guard: MongoDB URI contains forbidden ASCII control characters.",
),
Self::ForbiddenWhitespace => {
f.write_str("Safety guard: MongoDB URI contains forbidden whitespace.")
}
Self::UnsupportedScheme => f.write_str(
"Safety guard: MongoDB URI must use the mongodb:// or mongodb+srv:// scheme.",
),
Self::EmptyAuthority => f.write_str("Safety guard: MongoDB URI authority is empty."),
Self::UnencodedHashInAuthority => f.write_str(
"Safety guard: MongoDB URI authority cannot contain an unencoded \"#\" character.",
),
Self::EmptyUserinfo => f.write_str(
"Safety guard: MongoDB URI authority cannot have empty userinfo before \"@\".",
),
Self::MultipleAtInAuthority => f.write_str(
"Safety guard: MongoDB URI authority cannot contain multiple unencoded \"@\" characters.",
),
Self::UnencodedAtInRemainderWithoutCredentials => f.write_str(
"Safety guard: MongoDB URI cannot contain an unencoded \"@\" in path or query without credentials in authority.",
),
Self::EmptyHostList => f.write_str("Safety guard: MongoDB URI host list is empty."),
Self::InvalidUsernameEncoding => f.write_str(
"Safety guard: invalid percent-encoding in MongoDB URI username.",
),
Self::InvalidHostEncoding => {
f.write_str("Safety guard: invalid percent-encoding in MongoDB host.")
}
Self::ForbiddenHostCharacters => {
f.write_str("Safety guard: invalid characters in MongoDB host.")
}
Self::NoValidHosts => {
f.write_str("Safety guard: MongoDB URI did not contain any valid host.")
}
Self::MalformedHostSegment => f.write_str(
"Safety guard: MongoDB URI contains an empty or malformed host segment.",
),
Self::InvalidSrvTarget => f.write_str(
"Safety guard: mongodb+srv:// URI must contain exactly one host and no explicit port.",
),
Self::ForbiddenAdminUser => f.write_str(
"Safety guard: MongoDB admin user \"trading_admin\" is forbidden in read-only mode.",
),
Self::MissingCredentialsForQaTarget => f.write_str(
"Safety guard: QA MongoDB target requires explicit read-only credentials.",
),
Self::UnauthorizedQaUser => f.write_str(
"Safety guard: QA MongoDB target requires an allowlisted read-only username.",
),
}
}
}
impl Error for MongoSafetyError {}
/// Parses a MongoDB connection URI into its target scheme, decoded hosts/ports,
/// optional database path, and optional percent-decoded username.
///
/// Mirrors `parseMongoTarget` / `parseMongoHostPort` / `decodeMongoHost` in
/// `apps/stock/config/src/env-safety.ts` plus the no-credentials remainder-`@`
/// check from `libs/core/config/src/schemas/database.schema.ts`.
pub fn parse_mongo_target(uri: &str) -> Result<MongoTarget, MongoSafetyError> {
if uri.is_empty() {
return Err(MongoSafetyError::EmptyUri);
}
if has_ascii_control_char(uri) {
return Err(MongoSafetyError::ControlCharacters);
}
if has_forbidden_whitespace(uri) {
return Err(MongoSafetyError::ForbiddenWhitespace);
}
let Some((raw_scheme, rest)) = uri.split_once("://") else {
return Err(MongoSafetyError::UnsupportedScheme);
};
let scheme = if raw_scheme.eq_ignore_ascii_case("mongodb") {
MongoScheme::Standard
} else if raw_scheme.eq_ignore_ascii_case("mongodb+srv") {
MongoScheme::Srv
} else {
return Err(MongoSafetyError::UnsupportedScheme);
};
let default_port = match scheme {
MongoScheme::Standard => Some(QA_MONGO_PORT),
MongoScheme::Srv => None,
};
let allow_unix_socket = matches!(scheme, MongoScheme::Standard);
// Match mongodb-connection-string-url: authority ends at '/' or '?', never '#'
let (authority, remainder) = match rest.find(['/', '?']) {
Some(idx) => (&rest[..idx], &rest[idx..]),
None => (rest, ""),
};
if authority.is_empty() {
return Err(MongoSafetyError::EmptyAuthority);
}
if authority.contains('#') {
return Err(MongoSafetyError::UnencodedHashInAuthority);
}
let database = if remainder.starts_with('/') {
let path_part = remainder.split(['?', '#']).next().unwrap_or("");
let first_segment = path_part
.trim_start_matches('/')
.split('/')
.next()
.unwrap_or("");
if first_segment.is_empty() {
None
} else {
Some(first_segment.to_owned())
}
} else {
None
};
let (userinfo, host_list) = match authority.find('@') {
Some(0) => return Err(MongoSafetyError::EmptyUserinfo),
Some(at_idx) => {
if authority[at_idx + 1..].contains('@') {
return Err(MongoSafetyError::MultipleAtInAuthority);
}
(&authority[..at_idx], &authority[at_idx + 1..])
}
None => {
if remainder.contains('@') {
return Err(MongoSafetyError::UnencodedAtInRemainderWithoutCredentials);
}
("", authority)
}
};
if host_list.is_empty() {
return Err(MongoSafetyError::EmptyHostList);
}
let username = if !userinfo.is_empty() {
let raw_username = match userinfo.find(':') {
Some(colon_idx) => &userinfo[..colon_idx],
None => userinfo,
};
if raw_username.is_empty() {
None
} else {
Some(
percent_decode_utf8(raw_username)
.map_err(|()| MongoSafetyError::InvalidUsernameEncoding)?,
)
}
} else {
None
};
let mut hosts = Vec::new();
let mut has_invalid_host_segment = false;
let mut has_explicit_port = false;
for segment in host_list.split(',') {
match parse_mongo_host_port(segment, default_port, allow_unix_socket)? {
Some((parsed_host, segment_has_explicit_port)) => {
hosts.push(parsed_host);
if segment_has_explicit_port {
has_explicit_port = true;
}
}
None => {
has_invalid_host_segment = true;
}
}
}
if hosts.is_empty() {
return Err(MongoSafetyError::NoValidHosts);
}
Ok(MongoTarget {
scheme,
hosts,
database,
username,
has_invalid_host_segment,
has_explicit_port,
})
}
/// Returns `true` if any seed host in `target` resolves to loopback or a host
/// in `local_hosts` on port `27017` (or with an omitted/default port),
/// regardless of database path.
///
/// Mirrors `isQaMongoTargetHosts` in `apps/stock/config/src/env-safety.ts`.
pub fn is_qa_mongo_target(target: &MongoTarget, local_hosts: &LocalHosts) -> bool {
target.hosts.iter().any(|entry| {
is_local_machine_host(&entry.host, local_hosts)
&& matches!(entry.port, None | Some(QA_MONGO_PORT))
})
}
/// Validates a MongoDB URI for read-only use and returns a
/// [`ValidatedReadOnlyMongoUri`] proof token.
///
/// Enforces fail-closed parsing, forbids `trading_admin` (ASCII
/// case-insensitive, percent-decoded) on **any** host, and requires explicit
/// allowlisted credentials when targeting QA MongoDB.
///
/// URI query options are intentionally not parsed beyond authority/remainder
/// splitting (matching `apps/stock/config/src/env-safety.ts`).
pub fn assert_read_only_mongo_uri(
uri: &str,
policy: &ReadOnlyPolicy,
local_hosts: &LocalHosts,
) -> Result<ValidatedReadOnlyMongoUri, MongoSafetyError> {
let target = parse_mongo_target(uri)?;
if target.has_invalid_host_segment {
return Err(MongoSafetyError::MalformedHostSegment);
}
if target.scheme == MongoScheme::Srv && (target.hosts.len() != 1 || target.has_explicit_port) {
return Err(MongoSafetyError::InvalidSrvTarget);
}
if target
.username
.as_deref()
.is_some_and(|user| user.eq_ignore_ascii_case(FORBIDDEN_ADMIN_USER))
{
return Err(MongoSafetyError::ForbiddenAdminUser);
}
let is_qa = is_qa_mongo_target(&target, local_hosts);
if is_qa {
let Some(user) = target.username.as_deref() else {
return Err(MongoSafetyError::MissingCredentialsForQaTarget);
};
if !policy
.allowed_read_users
.iter()
.any(|allowed| allowed == user)
{
return Err(MongoSafetyError::UnauthorizedQaUser);
}
}
Ok(ValidatedReadOnlyMongoUri {
uri: uri.to_owned(),
target,
is_qa,
})
}
pub(crate) fn redact_mongo_uri_password(uri: &str) -> String {
let Some(scheme_end) = uri.find("://") else {
return uri.to_owned();
};
let rest_start = scheme_end + 3;
let rest = &uri[rest_start..];
let authority_end = rest.find(['/', '?']).unwrap_or(rest.len());
let authority = &rest[..authority_end];
let Some(at_idx) = authority.find('@') else {
return uri.to_owned();
};
let userinfo = &authority[..at_idx];
let Some(colon_idx) = userinfo.find(':') else {
return uri.to_owned();
};
let pass_start = rest_start + colon_idx + 1;
let pass_end = rest_start + at_idx;
let mut out = String::with_capacity(uri.len() + 10);
out.push_str(&uri[..pass_start]);
out.push_str("[REDACTED]");
out.push_str(&uri[pass_end..]);
out
}
fn has_ascii_control_char(value: &str) -> bool {
value.bytes().any(|b| b <= 0x1f || b == 0x7f)
}
fn has_forbidden_whitespace(value: &str) -> bool {
value.chars().any(|c| c.is_whitespace() || c == '\u{FEFF}')
}
fn hex_nibble(byte: u8) -> Option<u8> {
match byte {
b'0'..=b'9' => Some(byte - b'0'),
b'a'..=b'f' => Some(byte - b'a' + 10),
b'A'..=b'F' => Some(byte - b'A' + 10),
_ => None,
}
}
/// Strictly percent-decodes UTF-8 without turning `+` into space.
fn percent_decode_utf8(input: &str) -> Result<String, ()> {
let bytes = input.as_bytes();
let mut out = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'%' {
if i + 2 >= bytes.len() {
return Err(());
}
let hi = hex_nibble(bytes[i + 1]).ok_or(())?;
let lo = hex_nibble(bytes[i + 2]).ok_or(())?;
out.push((hi << 4) | lo);
i += 3;
} else {
out.push(bytes[i]);
i += 1;
}
}
String::from_utf8(out).map_err(|_| ())
}
fn is_valid_ipv6_zone_id_char(b: u8) -> bool {
b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'~' | b'-')
}
fn is_valid_ipv6_with_zone_id(host: &str) -> bool {
let Some(zone_idx) = host.find('%') else {
return false;
};
if zone_idx == 0 || host[zone_idx + 1..].contains('%') {
return false;
}
let addr = &host[..zone_idx];
let zone = &host[zone_idx + 1..];
!zone.is_empty()
&& zone.bytes().all(is_valid_ipv6_zone_id_char)
&& parse_ipv6_hextets(addr).is_some()
}
fn has_forbidden_unix_socket_char(value: &str) -> bool {
value.chars().any(|c| {
matches!(c, '?' | '#' | '@' | ':' | '\\' | '[' | ']' | ',')
|| c.is_whitespace()
|| c == '\u{FEFF}'
})
}
fn is_unix_domain_socket_host(decoded_host: &str) -> bool {
decoded_host.starts_with('/')
&& decoded_host.ends_with(".sock")
&& !has_ascii_control_char(decoded_host)
&& !has_forbidden_unix_socket_char(decoded_host)
}
fn has_forbidden_host_char(value: &str, is_bracketed_ipv6: bool) -> bool {
value.chars().any(|c| {
matches!(c, '/' | '?' | '#' | '@' | '\\' | '[' | ']' | ',')
|| (!is_bracketed_ipv6 && c == ':')
|| c.is_whitespace()
|| c == '\u{FEFF}'
})
}
fn decode_mongo_host(
raw_host: &str,
is_bracketed_ipv6: bool,
allow_unix_socket: bool,
) -> Result<String, MongoSafetyError> {
let mut current = raw_host.to_owned();
for pass in 0..MAX_MONGO_HOST_DECODE_PASSES {
match percent_decode_utf8(&current) {
Ok(decoded) => {
if decoded == current {
break;
}
current = decoded;
if is_bracketed_ipv6 && is_valid_ipv6_with_zone_id(&current) {
break;
}
}
Err(()) => {
if is_bracketed_ipv6 && pass > 0 && is_valid_ipv6_with_zone_id(&current) {
break;
}
return Err(MongoSafetyError::InvalidHostEncoding);
}
}
}
if current.contains('%') && !(is_bracketed_ipv6 && is_valid_ipv6_with_zone_id(&current)) {
return Err(MongoSafetyError::InvalidHostEncoding);
}
if !is_bracketed_ipv6 && allow_unix_socket && is_unix_domain_socket_host(&current) {
return Ok(current);
}
if has_ascii_control_char(&current) || has_forbidden_host_char(&current, is_bracketed_ipv6) {
return Err(MongoSafetyError::ForbiddenHostCharacters);
}
Ok(current.to_lowercase())
}
fn parse_port(port_str: &str) -> Option<u16> {
if port_str.is_empty() || !port_str.bytes().all(|b| b.is_ascii_digit()) {
return None;
}
let port: u16 = port_str.parse().ok()?;
if port == 0 { None } else { Some(port) }
}
fn is_valid_bracketed_ipv6(host: &str) -> bool {
if host.contains('%') {
is_valid_ipv6_with_zone_id(host)
} else {
parse_ipv6_hextets(host).is_some()
}
}
fn parse_mongo_host_port(
segment: &str,
default_port: Option<u16>,
allow_unix_socket: bool,
) -> Result<Option<(MongoTargetHost, bool)>, MongoSafetyError> {
let trimmed = segment.trim();
if trimmed.is_empty() {
return Ok(None);
}
if let Some(after_open) = trimmed.strip_prefix('[') {
let Some(close_rel) = after_open.find(']') else {
return Ok(None);
};
if close_rel == 0 {
return Ok(None);
}
let raw_host = after_open[..close_rel].trim();
if raw_host.is_empty() {
return Ok(None);
}
let host = decode_mongo_host(raw_host, true, false)?.trim().to_owned();
if host.is_empty() || !is_valid_bracketed_ipv6(&host) {
return Ok(None);
}
let after = after_open[close_rel + 1..].trim();
if after.is_empty() {
return Ok(Some((
MongoTargetHost {
host,
port: default_port,
},
false,
)));
}
let Some(port_part) = after.strip_prefix(':') else {
return Ok(None);
};
let port_str = port_part.trim();
if port_str.is_empty() {
return Ok(Some((
MongoTargetHost {
host,
port: default_port,
},
true,
)));
}
let Some(port) = parse_port(port_str) else {
return Ok(None);
};
return Ok(Some((
MongoTargetHost {
host,
port: Some(port),
},
true,
)));
}
let Some(colon_idx) = trimmed.find(':') else {
let host = decode_mongo_host(trimmed, false, allow_unix_socket)?
.trim()
.to_owned();
if host.is_empty() {
return Ok(None);
}
if allow_unix_socket && is_unix_domain_socket_host(&host) {
return Ok(Some((MongoTargetHost { host, port: None }, false)));
}
return Ok(Some((
MongoTargetHost {
host,
port: default_port,
},
false,
)));
};
if trimmed[colon_idx + 1..].contains(':') {
return Ok(None);
}
let raw_host = trimmed[..colon_idx].trim();
let port_str = trimmed[colon_idx + 1..].trim();
if raw_host.is_empty() {
return Ok(None);
}
let host = decode_mongo_host(raw_host, false, false)?.trim().to_owned();
if host.is_empty() {
return Ok(None);
}
if port_str.is_empty() {
return Ok(Some((
MongoTargetHost {
host,
port: default_port,
},
true,
)));
}
let Some(port) = parse_port(port_str) else {
return Ok(None);
};
Ok(Some((
MongoTargetHost {
host,
port: Some(port),
},
true,
)))
}
fn normalize_host(host: &str) -> String {
let s = host.trim();
let s = s.strip_prefix('[').unwrap_or(s);
let s = s.strip_suffix(']').unwrap_or(s);
s.trim_end_matches('.').to_lowercase()
}
fn normalize_local_host_entry(raw: &str) -> Option<String> {
let s = raw.trim();
let s = s.strip_prefix('[').unwrap_or(s);
let s = s.strip_suffix(']').unwrap_or(s);
let s = s.split('%').next().unwrap_or("");
let normalized = s.trim().trim_end_matches('.').to_lowercase();
if normalized.is_empty() {
None
} else {
Some(normalized)
}
}
fn parse_ipv4_octets(host: &str) -> Option<[u8; 4]> {
let mut parts = host.split('.');
let mut out = [0u8; 4];
for slot in &mut out {
let part = parts.next()?;
if part.is_empty() || part.len() > 3 || !part.bytes().all(|b| b.is_ascii_digit()) {
return None;
}
*slot = part.parse::<u8>().ok()?;
}
if parts.next().is_some() {
return None;
}
Some(out)
}
fn parse_ipv4_part(part: &str) -> Option<u32> {
if let Some(hex_digits) = part.strip_prefix("0x").or_else(|| part.strip_prefix("0X")) {
if hex_digits.is_empty() {
return Some(0);
}
if !hex_digits.bytes().all(|b| b.is_ascii_hexdigit()) {
return None;
}
return u32::from_str_radix(hex_digits, 16).ok();
}
if part.len() >= 2 && part.starts_with('0') && part.bytes().all(|b| (b'0'..=b'7').contains(&b)) {
return u32::from_str_radix(part, 8).ok();
}
if part == "0"
|| (!part.is_empty()
&& !part.starts_with('0')
&& part.bytes().all(|b| b.is_ascii_digit()))
{
return part.parse::<u32>().ok();
}
None
}
fn parse_numeric_ipv4_octets(host: &str) -> Option<[u8; 4]> {
let parts: Vec<&str> = host.split('.').collect();
if parts.is_empty() || parts.len() > 4 {
return None;
}
let mut parsed = [0u32; 4];
for (idx, part) in parts.iter().enumerate() {
parsed[idx] = parse_ipv4_part(part)?;
}
match parts.len() {
1 => {
let p0 = parsed[0];
Some([
((p0 >> 24) & 0xff) as u8,
((p0 >> 16) & 0xff) as u8,
((p0 >> 8) & 0xff) as u8,
(p0 & 0xff) as u8,
])
}
2 => {
let (p0, p1) = (parsed[0], parsed[1]);
if p0 > 0xff || p1 > 0x00ff_ffff {
return None;
}
Some([
p0 as u8,
((p1 >> 16) & 0xff) as u8,
((p1 >> 8) & 0xff) as u8,
(p1 & 0xff) as u8,
])
}
3 => {
let (p0, p1, p2) = (parsed[0], parsed[1], parsed[2]);
if p0 > 0xff || p1 > 0xff || p2 > 0xffff {
return None;
}
Some([
p0 as u8,
p1 as u8,
((p2 >> 8) & 0xff) as u8,
(p2 & 0xff) as u8,
])
}
4 => {
let (p0, p1, p2, p3) = (parsed[0], parsed[1], parsed[2], parsed[3]);
if p0 > 0xff || p1 > 0xff || p2 > 0xff || p3 > 0xff {
return None;
}
Some([p0 as u8, p1 as u8, p2 as u8, p3 as u8])
}
_ => None,
}
}
fn parse_decimal_ipv4_octets(host: &str) -> Option<[u8; 4]> {
let mut parts = host.split('.');
let mut out = [0u8; 4];
for slot in &mut out {
let part = parts.next()?;
if part.is_empty() || !part.bytes().all(|b| b.is_ascii_digit()) {
return None;
}
*slot = part.parse::<u8>().ok()?;
}
if parts.next().is_some() {
return None;
}
Some(out)
}
fn is_ipv4_loopback_octets(octets: [u8; 4]) -> bool {
octets[0] == 127 || octets == [0, 0, 0, 0]
}
fn is_ipv4_loopback(host: &str) -> bool {
parse_numeric_ipv4_octets(host).is_some_and(is_ipv4_loopback_octets)
|| parse_decimal_ipv4_octets(host).is_some_and(is_ipv4_loopback_octets)
}
fn parse_ipv6_side(side: &str, allow_ipv4_tail: bool) -> Option<Vec<u16>> {
if side.is_empty() {
return Some(Vec::new());
}
let parts: Vec<&str> = side.split(':').collect();
let mut groups = Vec::with_capacity(parts.len() + 1);
for (idx, part) in parts.iter().enumerate() {
if idx + 1 == parts.len() && allow_ipv4_tail && part.contains('.') {
let octets = parse_ipv4_octets(part)?;
groups.push(((octets[0] as u16) << 8) | (octets[1] as u16));
groups.push(((octets[2] as u16) << 8) | (octets[3] as u16));
continue;
}
if part.is_empty() || part.len() > 4 || !part.bytes().all(|b| b.is_ascii_hexdigit()) {
return None;
}
groups.push(u16::from_str_radix(part, 16).ok()?);
}
Some(groups)
}
fn parse_ipv6_hextets(host: &str) -> Option<[u16; 8]> {
if !host.contains(':') {
return None;
}
let addr = match host.find('%') {
Some(zone_idx) => &host[..zone_idx],
None => host,
};
let halves: Vec<&str> = addr.split("::").collect();
if halves.len() > 2 {
return None;
}
if halves.len() == 1 {
let groups = parse_ipv6_side(halves[0], true)?;
return groups.try_into().ok();
}
let left = parse_ipv6_side(halves[0], false)?;
let right = parse_ipv6_side(halves[1], true)?;
let total = left.len() + right.len();
if total >= 8 {
return None;
}
let missing = 8 - total;
let mut out = [0u16; 8];
out[..left.len()].copy_from_slice(&left);
out[left.len() + missing..].copy_from_slice(&right);
Some(out)
}
fn is_ipv6_loopback(host: &str) -> bool {
let Some(hextets) = parse_ipv6_hextets(host) else {
return false;
};
if hextets[..7] == [0; 7] {
return hextets[7] == 0 || hextets[7] == 1;
}
if hextets[..5] == [0; 5] && hextets[5] == 0xffff {
let first_octet = (hextets[6] >> 8) & 0xff;
return first_octet == 127 || (hextets[6] == 0 && hextets[7] == 0);
}
false
}
fn is_loopback_normalized(normalized: &str) -> bool {
normalized == "localhost"
|| normalized == "0.0.0.0"
|| is_ipv4_loopback(normalized)
|| is_ipv6_loopback(normalized)
}
fn is_local_machine_host(host: &str, local_hosts: &LocalHosts) -> bool {
if host.is_empty() {
return false;
}
let normalized = normalize_host(host);
if is_loopback_normalized(&normalized) {
return true;
}
if local_hosts.hosts.contains(&normalized) {
return true;
}
if let Some(zone_idx) = normalized.find('%') {
if local_hosts.hosts.contains(&normalized[..zone_idx]) {
return true;
}
}
if let Some([a, b, c, d]) = parse_numeric_ipv4_octets(&normalized) {
let dotted = format!("{a}.{b}.{c}.{d}");
if local_hosts.hosts.contains(&dotted) {
return true;
}
}
if let Some([a, b, c, d]) = parse_decimal_ipv4_octets(&normalized) {
let dotted = format!("{a}.{b}.{c}.{d}");
if local_hosts.hosts.contains(&dotted) {
return true;
}
}
false
}
#[cfg(test)]
#[path = "mongo_safety_tests.rs"]
mod tests;