2580 lines
98 KiB
Rust
2580 lines
98 KiB
Rust
use super::*;
|
|
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
enum ExpectedTargetOutcome {
|
|
Qa,
|
|
NotQa,
|
|
Rejected,
|
|
}
|
|
|
|
fn injected_local_hosts() -> LocalHosts {
|
|
LocalHosts::from_hostname_and_ips(
|
|
Some("quant.lan.local."),
|
|
["192.168.1.50", "fe80::1234:5678%eth0"],
|
|
)
|
|
}
|
|
|
|
#[test]
|
|
fn parity_table_mirrors_all_five_ts_environment_safety_test_suites() {
|
|
let local_hosts = injected_local_hosts();
|
|
|
|
// Every MongoDB target classification vector from:
|
|
// 1. test/unit/environment-safety.test.ts
|
|
// 2. test/unit/environment-safety-authority-split.test.ts
|
|
// 3. test/unit/environment-safety-edge-cases.test.ts
|
|
// 4. test/unit/environment-safety-encoded-host.test.ts
|
|
// 5. test/unit/environment-safety-multi-host.test.ts
|
|
let vectors: &[(&str, ExpectedTargetOutcome, &str)] = &[
|
|
// --- 1. test/unit/environment-safety.test.ts ---
|
|
(
|
|
"mongodb://dev_admin:dev_mongo_pass@localhost:27018/stock_dev?authSource=admin",
|
|
ExpectedTargetOutcome::NotQa,
|
|
"environment-safety.test.ts: dev port 27018",
|
|
),
|
|
(
|
|
"mongodb://studio_stock_bot_read:secret@localhost:27017/stock?authSource=stock",
|
|
ExpectedTargetOutcome::Qa,
|
|
"environment-safety.test.ts: QA localhost:27017",
|
|
),
|
|
(
|
|
"mongodb://trading_admin:trading_mongo_dev@localhost:27017/stock?authSource=admin",
|
|
ExpectedTargetOutcome::Qa,
|
|
"environment-safety.test.ts: QA trading_admin localhost:27017",
|
|
),
|
|
(
|
|
"mongodb://trading_admin:pass@localhost:27017",
|
|
ExpectedTargetOutcome::Qa,
|
|
"environment-safety.test.ts: omitted /stock path",
|
|
),
|
|
(
|
|
"mongodb://trading_admin:pass@[::1]:27017",
|
|
ExpectedTargetOutcome::Qa,
|
|
"environment-safety.test.ts: IPv6 loopback omitted path",
|
|
),
|
|
(
|
|
"mongodb://studio_stock_bot_read:secret@localhost:27017",
|
|
ExpectedTargetOutcome::Qa,
|
|
"environment-safety.test.ts: read user omitted path",
|
|
),
|
|
(
|
|
"mongodb://trading_admin:pass@0127.0.0.1:27017/stock",
|
|
ExpectedTargetOutcome::Qa,
|
|
"environment-safety.test.ts: T-37 leading-zero decimal 0127.0.0.1",
|
|
),
|
|
(
|
|
"mongodb://trading_admin:pass@00127.0.0.1:27017/stock",
|
|
ExpectedTargetOutcome::Qa,
|
|
"environment-safety.test.ts: T-37 leading-zero decimal 00127.0.0.1",
|
|
),
|
|
(
|
|
"mongodb://trading_admin:pass@0177.0.0.1:27017/stock",
|
|
ExpectedTargetOutcome::Qa,
|
|
"environment-safety.test.ts: T-37 octal 0177.0.0.1",
|
|
),
|
|
(
|
|
"mongodb://trading_admin:pass@00.00.00.00:27017/stock",
|
|
ExpectedTargetOutcome::Qa,
|
|
"environment-safety.test.ts: T-37 leading-zero 00.00.00.00",
|
|
),
|
|
(
|
|
"mongodb://prod_user:strong-prod-mongo-pass@%2Fvar%2Frun%2Fmongodb%2Fmongod.sock/stock",
|
|
ExpectedTargetOutcome::NotQa,
|
|
"environment-safety.test.ts: T-27 Unix domain socket",
|
|
),
|
|
(
|
|
"mongodb://trading_admin:pass@quant.lan.local:27017/stock",
|
|
ExpectedTargetOutcome::Qa,
|
|
"environment-safety.test.ts: T-15 local machine hostname",
|
|
),
|
|
(
|
|
"mongodb://trading_admin:pass@192.168.1.50:27017/stock",
|
|
ExpectedTargetOutcome::Qa,
|
|
"environment-safety.test.ts: T-15 local machine LAN IP",
|
|
),
|
|
(
|
|
"mongodb://u:p@localhost:27017,localhost:27018/stock",
|
|
ExpectedTargetOutcome::Qa,
|
|
"environment-safety.test.ts: multi-host QA first",
|
|
),
|
|
(
|
|
"mongodb://u:p@localhost:27018,localhost:27017/stock_dev",
|
|
ExpectedTargetOutcome::Qa,
|
|
"environment-safety.test.ts: multi-host QA second",
|
|
),
|
|
(
|
|
"mongodb://studio_stock_bot_read:secret@localhost:27018,localhost:27017/stock_dev",
|
|
ExpectedTargetOutcome::Qa,
|
|
"environment-safety.test.ts: multi-host read user QA second",
|
|
),
|
|
(
|
|
"mongodb://studio_stock_bot_read:secret@localhost:27018,localhost:27017/stock",
|
|
ExpectedTargetOutcome::Qa,
|
|
"environment-safety.test.ts: multi-host fallback uri QA second",
|
|
),
|
|
(
|
|
"mongodb://trading_admin:pass@localhost:27017,localhost:27018/stock",
|
|
ExpectedTargetOutcome::Qa,
|
|
"environment-safety.test.ts: multi-host admin QA first",
|
|
),
|
|
(
|
|
"mongodb://studio_stock_bot_read:secret@localhost:27017,localhost:27018/stock",
|
|
ExpectedTargetOutcome::Qa,
|
|
"environment-safety.test.ts: multi-host read user QA first",
|
|
),
|
|
(
|
|
"mongodb://studio_stock_bot_read:secret@localhost:27017,localhost:27018/stock?authSource=stock",
|
|
ExpectedTargetOutcome::Qa,
|
|
"environment-safety.test.ts: multi-host read user QA first with authSource",
|
|
),
|
|
(
|
|
"mongodb://trading_admin:trading_mongo_dev@[::ffff:7f00:1]:27017/stock?authSource=admin",
|
|
ExpectedTargetOutcome::Qa,
|
|
"environment-safety.test.ts: initializeStockConfig IPv4-mapped loopback",
|
|
),
|
|
(
|
|
"mongodb://prod:strongpass@mongo.prod.internal:27017/stock",
|
|
ExpectedTargetOutcome::NotQa,
|
|
"environment-safety.test.ts: prod single remote host",
|
|
),
|
|
(
|
|
"mongodb://trading%5Fadmin:pass@localhost:27018,localhost:27017/stock",
|
|
ExpectedTargetOutcome::Qa,
|
|
"environment-safety.test.ts: multi-host encoded trading_admin",
|
|
),
|
|
(
|
|
"mongodb://u:p@localhost:27018,localhost/stock_dev",
|
|
ExpectedTargetOutcome::Qa,
|
|
"environment-safety.test.ts: omitted port on second host",
|
|
),
|
|
(
|
|
"mongodb://u:p@localhost:27018,127.0.0.1/stock_dev",
|
|
ExpectedTargetOutcome::Qa,
|
|
"environment-safety.test.ts: omitted port IPv4 loopback",
|
|
),
|
|
(
|
|
"mongodb://u:p@localhost:27018,[::1]:27017/stock_dev",
|
|
ExpectedTargetOutcome::Qa,
|
|
"environment-safety.test.ts: multi-host IPv6 loopback",
|
|
),
|
|
(
|
|
"mongodb://u:p@localhost:27018,[::1]/stock_dev",
|
|
ExpectedTargetOutcome::Qa,
|
|
"environment-safety.test.ts: multi-host IPv6 omitted port",
|
|
),
|
|
(
|
|
"mongodb://u:p@[0:0:0:0:0:0:0:0001]:27017/stock",
|
|
ExpectedTargetOutcome::Qa,
|
|
"environment-safety.test.ts: expanded IPv6 loopback",
|
|
),
|
|
(
|
|
"mongodb://u:p@[::ffff:7f00:1]:27017/stock",
|
|
ExpectedTargetOutcome::Qa,
|
|
"environment-safety.test.ts: IPv4-mapped IPv6 hex 7f00:1",
|
|
),
|
|
(
|
|
"mongodb://u:p@[::ffff:7f00:0001]/stock",
|
|
ExpectedTargetOutcome::Qa,
|
|
"environment-safety.test.ts: IPv4-mapped IPv6 omitted port",
|
|
),
|
|
(
|
|
"mongodb://u:p@[::ffff:7f01:0203]:27017/stock",
|
|
ExpectedTargetOutcome::Qa,
|
|
"environment-safety.test.ts: IPv4-mapped IPv6 127.1.2.3",
|
|
),
|
|
(
|
|
"mongodb://u:p@[0:0:0:0:0:ffff:7f00:1]:27017/stock",
|
|
ExpectedTargetOutcome::Qa,
|
|
"environment-safety.test.ts: expanded IPv4-mapped IPv6",
|
|
),
|
|
(
|
|
"mongodb://u:p@[::ffff:127.0.0.2]:27017/stock",
|
|
ExpectedTargetOutcome::Qa,
|
|
"environment-safety.test.ts: IPv4-mapped IPv6 dotted 127.0.0.2",
|
|
),
|
|
(
|
|
"mongodb://u:p@localhost:27018,LOCALHOST.:27017/stock_dev",
|
|
ExpectedTargetOutcome::Qa,
|
|
"environment-safety.test.ts: uppercase trailing dot LOCALHOST.",
|
|
),
|
|
(
|
|
"mongodb://u:p@127.0.0.2:27017/stock_dev",
|
|
ExpectedTargetOutcome::Qa,
|
|
"environment-safety.test.ts: 127.0.0.2 loopback",
|
|
),
|
|
(
|
|
"mongodb+srv://u:p@localhost/stock",
|
|
ExpectedTargetOutcome::Qa,
|
|
"environment-safety.test.ts: mongodb+srv localhost",
|
|
),
|
|
(
|
|
"mongodb://u:p@[::ffff:0a00:1]:27017/stock_dev",
|
|
ExpectedTargetOutcome::NotQa,
|
|
"environment-safety.test.ts: non-loopback IPv4-mapped IPv6",
|
|
),
|
|
(
|
|
"mongodb://trading_admin:p%40ss@localhost:27018,localhost:27017/stock",
|
|
ExpectedTargetOutcome::Qa,
|
|
"environment-safety.test.ts: %40 in password",
|
|
),
|
|
(
|
|
"mongodb://trading_admin:p@ss@localhost:27018,localhost:27017/stock",
|
|
ExpectedTargetOutcome::Rejected,
|
|
"environment-safety.test.ts: unencoded double @",
|
|
),
|
|
(
|
|
"mongodb://localhost:27017,localhost:27018/stock",
|
|
ExpectedTargetOutcome::Qa,
|
|
"environment-safety.test.ts: no userinfo multi-host QA",
|
|
),
|
|
(
|
|
"mongodb://u:p@localhost:/stock",
|
|
ExpectedTargetOutcome::Qa,
|
|
"environment-safety.test.ts: trailing colon default port",
|
|
),
|
|
(
|
|
"mongodb://u:p@[::1]:/stock",
|
|
ExpectedTargetOutcome::Qa,
|
|
"environment-safety.test.ts: IPv6 trailing colon default port",
|
|
),
|
|
(
|
|
"mongodb://u:p@bad:port,localhost:27017/stock",
|
|
ExpectedTargetOutcome::Qa,
|
|
"environment-safety.test.ts: bad segment + valid QA host still classifies QA",
|
|
),
|
|
(
|
|
"mongodb://localhost:27018#,localhost/stock",
|
|
ExpectedTargetOutcome::Rejected,
|
|
"environment-safety.test.ts: T-28 raw # in authority",
|
|
),
|
|
(
|
|
"mongodb://dev_admin:dev_mongo_pass@localhost:27018#,localhost:27017/stock_dev?authSource=admin",
|
|
ExpectedTargetOutcome::Rejected,
|
|
"environment-safety.test.ts: T-28 raw # with credentials",
|
|
),
|
|
(
|
|
"mongodb://u:p@localhost:27018#x,127.0.0.1/stock",
|
|
ExpectedTargetOutcome::Rejected,
|
|
"environment-safety.test.ts: T-28 raw # before second host",
|
|
),
|
|
(
|
|
"mongodb://u:p@localhost:27017@x:27018/stock",
|
|
ExpectedTargetOutcome::Rejected,
|
|
"environment-safety.test.ts: T-28 second @ in authority",
|
|
),
|
|
(
|
|
"mongodb://localhost#x:27018/stock",
|
|
ExpectedTargetOutcome::Rejected,
|
|
"environment-safety.test.ts: T-28 raw # before port",
|
|
),
|
|
(
|
|
"mongodb://u@localhost:27017@x:27018/stock",
|
|
ExpectedTargetOutcome::Rejected,
|
|
"environment-safety.test.ts: T-28 passwordless user + second @",
|
|
),
|
|
(
|
|
"mongodb://u:p@local\nhost:27017/stock",
|
|
ExpectedTargetOutcome::Rejected,
|
|
"environment-safety.test.ts: T-28 newline control char",
|
|
),
|
|
(
|
|
"mongodb://u:p@local\thost:27017/stock",
|
|
ExpectedTargetOutcome::Rejected,
|
|
"environment-safety.test.ts: T-28 tab control char",
|
|
),
|
|
(
|
|
"mongodb:///stock",
|
|
ExpectedTargetOutcome::Rejected,
|
|
"environment-safety.test.ts: empty authority",
|
|
),
|
|
(
|
|
"mongodb://u:p@/stock",
|
|
ExpectedTargetOutcome::Rejected,
|
|
"environment-safety.test.ts: empty host list",
|
|
),
|
|
(
|
|
"mongodb://u:p@bad:port/stock",
|
|
ExpectedTargetOutcome::Rejected,
|
|
"environment-safety.test.ts: zero valid hosts",
|
|
),
|
|
(
|
|
"mongodb://,/stock",
|
|
ExpectedTargetOutcome::Rejected,
|
|
"environment-safety.test.ts: comma-only host list",
|
|
),
|
|
(
|
|
"mongodb+srv:///stock",
|
|
ExpectedTargetOutcome::Rejected,
|
|
"environment-safety.test.ts: srv empty authority",
|
|
),
|
|
(
|
|
"",
|
|
ExpectedTargetOutcome::Rejected,
|
|
"environment-safety.test.ts: empty string",
|
|
),
|
|
(
|
|
" ",
|
|
ExpectedTargetOutcome::Rejected,
|
|
"environment-safety.test.ts: whitespace-only string",
|
|
),
|
|
(
|
|
"http://localhost:27017/stock",
|
|
ExpectedTargetOutcome::Rejected,
|
|
"environment-safety.test.ts: non-mongodb scheme",
|
|
),
|
|
(
|
|
"mongodb://@localhost:27018/stock",
|
|
ExpectedTargetOutcome::Rejected,
|
|
"environment-safety.test.ts: empty userinfo before @",
|
|
),
|
|
(
|
|
"mongodb://u:p@localhost:27017/stock?a=1\nb=2",
|
|
ExpectedTargetOutcome::Rejected,
|
|
"environment-safety.test.ts: newline in query",
|
|
),
|
|
(
|
|
"mongodb://u:p@localhost:27018/stock\x00",
|
|
ExpectedTargetOutcome::Rejected,
|
|
"environment-safety.test.ts: NUL byte",
|
|
),
|
|
(
|
|
"mongodb://u:p@localhost:27018/stock\r\n",
|
|
ExpectedTargetOutcome::Rejected,
|
|
"environment-safety.test.ts: CRLF",
|
|
),
|
|
(
|
|
"mongodb://localhost:27018#frag",
|
|
ExpectedTargetOutcome::Rejected,
|
|
"environment-safety.test.ts: raw # without / or ?",
|
|
),
|
|
(
|
|
"mongodb+srv://u:p@cluster.example.com#x/stock",
|
|
ExpectedTargetOutcome::Rejected,
|
|
"environment-safety.test.ts: srv raw # in authority",
|
|
),
|
|
(
|
|
"mongodb+srv://u:p@cluster.example.com@other.example.com/stock",
|
|
ExpectedTargetOutcome::Rejected,
|
|
"environment-safety.test.ts: srv multiple @",
|
|
),
|
|
(
|
|
"mongodb://dev_admin:p%40ss@localhost:27018/stock_dev",
|
|
ExpectedTargetOutcome::NotQa,
|
|
"environment-safety.test.ts: %40 in credentials on dev port",
|
|
),
|
|
(
|
|
"mongodb://dev_admin:p%40ss@localhost:27018/stock_dev?appName=a@b#note",
|
|
ExpectedTargetOutcome::NotQa,
|
|
"environment-safety.test.ts: @/# in query with credentials",
|
|
),
|
|
(
|
|
"mongodb://localhost:27018?authSource=admin#frag",
|
|
ExpectedTargetOutcome::NotQa,
|
|
"environment-safety.test.ts: # after ? without credentials",
|
|
),
|
|
(
|
|
"mongodb://dev_user@localhost:27018/stock_dev",
|
|
ExpectedTargetOutcome::NotQa,
|
|
"environment-safety.test.ts: passwordless user on dev port",
|
|
),
|
|
(
|
|
"mongodb+srv://prod:strongpass@cluster.prod.internal/stock?appName=a@b#note",
|
|
ExpectedTargetOutcome::NotQa,
|
|
"environment-safety.test.ts: srv prod remote",
|
|
),
|
|
(
|
|
"mongodb://dev_admin:dev_mongo_pass@localhost:27018,127.0.0.1:27019/stock_dev?authSource=admin",
|
|
ExpectedTargetOutcome::NotQa,
|
|
"environment-safety.test.ts: non-QA multi-host dev",
|
|
),
|
|
(
|
|
"mongodb://prod:strongpass@mongo1.prod.internal:27017,mongo2.prod.internal:27017/stock",
|
|
ExpectedTargetOutcome::NotQa,
|
|
"environment-safety.test.ts: prod multi-host remote",
|
|
),
|
|
// --- 2. test/unit/environment-safety-authority-split.test.ts ---
|
|
(
|
|
"mongodb://\nlocalhost",
|
|
ExpectedTargetOutcome::Rejected,
|
|
"authority-split.test.ts: leading newline",
|
|
),
|
|
(
|
|
"mongodb://trading_admin:x@localhost:27018#,localhost:27017/stock",
|
|
ExpectedTargetOutcome::Rejected,
|
|
"authority-split.test.ts: smuggled trading_admin behind #",
|
|
),
|
|
(
|
|
"mongodb://dev_admin:p%23ss@localhost:27018/stock_dev",
|
|
ExpectedTargetOutcome::NotQa,
|
|
"authority-split.test.ts: %23 in password",
|
|
),
|
|
(
|
|
"mongodb://u:p@localhost:27018/stock_dev#frag@x",
|
|
ExpectedTargetOutcome::NotQa,
|
|
"authority-split.test.ts: @ in fragment with credentials",
|
|
),
|
|
(
|
|
"mongodb://dev_user@localhost:27018,127.0.0.1:27019/stock_dev",
|
|
ExpectedTargetOutcome::NotQa,
|
|
"authority-split.test.ts: passwordless non-QA multi-seed URI",
|
|
),
|
|
(
|
|
"mongodb://u:p@[::1]:27018/stock_dev",
|
|
ExpectedTargetOutcome::NotQa,
|
|
"authority-split.test.ts: IPv6 dev port 27018",
|
|
),
|
|
(
|
|
"mongodb://u:p@local\u{00A0}host:27017/stock",
|
|
ExpectedTargetOutcome::Rejected,
|
|
"authority-split.test.ts: NBSP in host",
|
|
),
|
|
(
|
|
"mongodb://u:p@local\u{2028}host:27017/stock",
|
|
ExpectedTargetOutcome::Rejected,
|
|
"authority-split.test.ts: line separator in host",
|
|
),
|
|
(
|
|
"mongodb://u:p@localhost:27018,\u{3000}localhost/stock",
|
|
ExpectedTargetOutcome::Rejected,
|
|
"authority-split.test.ts: ideographic space in host list",
|
|
),
|
|
(
|
|
"mongodb://u:p@[::1]#:27018/stock",
|
|
ExpectedTargetOutcome::Rejected,
|
|
"authority-split.test.ts: IPv6 loopback behind raw #",
|
|
),
|
|
// --- 3. test/unit/environment-safety-edge-cases.test.ts ---
|
|
(
|
|
"mongodb://studio_stock_bot_read:secret@127.0.0.1:27017/stock",
|
|
ExpectedTargetOutcome::Qa,
|
|
"edge-cases.test.ts: 127.0.0.1:27017",
|
|
),
|
|
(
|
|
"mongodb://studio_stock_bot_read:secret@0.0.0.0:27017/stock",
|
|
ExpectedTargetOutcome::Qa,
|
|
"edge-cases.test.ts: 0.0.0.0:27017",
|
|
),
|
|
(
|
|
"mongodb://studio_stock_bot_read:secret@[::1]:27017/stock",
|
|
ExpectedTargetOutcome::Qa,
|
|
"edge-cases.test.ts: [::1]:27017",
|
|
),
|
|
(
|
|
"mongodb://studio_stock_bot_read:secret@LOCALHOST:27017/stock",
|
|
ExpectedTargetOutcome::Qa,
|
|
"edge-cases.test.ts: LOCALHOST:27017",
|
|
),
|
|
(
|
|
"mongodb://studio_stock_bot_read:secret@localhost/stock",
|
|
ExpectedTargetOutcome::Qa,
|
|
"edge-cases.test.ts: omitted port",
|
|
),
|
|
(
|
|
"mongodb://studio_stock_bot_read:secret@localhost:27017/other",
|
|
ExpectedTargetOutcome::Qa,
|
|
"edge-cases.test.ts: different db name on QA server",
|
|
),
|
|
(
|
|
"mongodb://writer:pw@10.0.0.51:27017/stock",
|
|
ExpectedTargetOutcome::NotQa,
|
|
"edge-cases.test.ts: remote host 10.0.0.51:27017",
|
|
),
|
|
(
|
|
"mongodb://reader:pw@10.0.0.51:27017/stock",
|
|
ExpectedTargetOutcome::NotQa,
|
|
"edge-cases.test.ts: remote reader 10.0.0.51:27017",
|
|
),
|
|
(
|
|
"mongodb://trading%5Fadmin:pw@localhost:27017/stock",
|
|
ExpectedTargetOutcome::Qa,
|
|
"edge-cases.test.ts: percent-encoded trading_admin on QA",
|
|
),
|
|
(
|
|
"mongodb://trading_admin:pw@localhost:27017/stock",
|
|
ExpectedTargetOutcome::Qa,
|
|
"edge-cases.test.ts: fallback uri trading_admin on QA",
|
|
),
|
|
// --- 4. test/unit/environment-safety-encoded-host.test.ts ---
|
|
(
|
|
"mongodb://u:p@%6cocalhost:27017/stock",
|
|
ExpectedTargetOutcome::Qa,
|
|
"encoded-host.test.ts: %6cocalhost:27017",
|
|
),
|
|
(
|
|
"mongodb://trading_admin:pass@%6cocalhost:27017/stock",
|
|
ExpectedTargetOutcome::Qa,
|
|
"encoded-host.test.ts: trading_admin on %6cocalhost:27017",
|
|
),
|
|
(
|
|
"mongodb://studio_stock_bot_read:secret@%6cocalhost:27017/stock?authSource=stock",
|
|
ExpectedTargetOutcome::Qa,
|
|
"encoded-host.test.ts: read user on %6cocalhost:27017",
|
|
),
|
|
(
|
|
"mongodb://dev_admin:dev_mongo_pass@%6cocalhost:27017/stock?authSource=admin",
|
|
ExpectedTargetOutcome::Qa,
|
|
"encoded-host.test.ts: schema-validated encoded QA seed",
|
|
),
|
|
(
|
|
"mongodb://u:p@%31%32%37%2e%30%2e%30%2e%31:27017/stock",
|
|
ExpectedTargetOutcome::Qa,
|
|
"encoded-host.test.ts: fully encoded 127.0.0.1",
|
|
),
|
|
(
|
|
"mongodb://u:p@127%2E0.0.1:27017/stock",
|
|
ExpectedTargetOutcome::Qa,
|
|
"encoded-host.test.ts: encoded dot in 127.0.0.1",
|
|
),
|
|
(
|
|
"mongodb://u:p@%4C%6fCalHost:27017/stock",
|
|
ExpectedTargetOutcome::Qa,
|
|
"encoded-host.test.ts: mixed-case encoded localhost",
|
|
),
|
|
(
|
|
"mongodb://u:p@%4C%4F%43%41%4C%48%4F%53%54:27017/stock",
|
|
ExpectedTargetOutcome::Qa,
|
|
"encoded-host.test.ts: uppercase encoded LOCALHOST",
|
|
),
|
|
(
|
|
"mongodb://u:p@%6cocalhost%2e:27017/stock",
|
|
ExpectedTargetOutcome::Qa,
|
|
"encoded-host.test.ts: encoded trailing dot",
|
|
),
|
|
(
|
|
"mongodb://u:p@%6cocalhost/stock",
|
|
ExpectedTargetOutcome::Qa,
|
|
"encoded-host.test.ts: encoded localhost omitted port",
|
|
),
|
|
(
|
|
"mongodb+srv://u:p@%6cocalhost/stock",
|
|
ExpectedTargetOutcome::Qa,
|
|
"encoded-host.test.ts: srv encoded localhost",
|
|
),
|
|
(
|
|
"mongodb://u:p@[::1%25lo]:27017/stock",
|
|
ExpectedTargetOutcome::Qa,
|
|
"encoded-host.test.ts: IPv6 loopback with zone ID",
|
|
),
|
|
(
|
|
"mongodb://u:p@[::ffff:%37%66%30%30:1]:27017/stock",
|
|
ExpectedTargetOutcome::Qa,
|
|
"encoded-host.test.ts: encoded IPv4-mapped IPv6",
|
|
),
|
|
(
|
|
"mongodb://u:p@localhost:27018,%6cocalhost:27017/stock_dev",
|
|
ExpectedTargetOutcome::Qa,
|
|
"encoded-host.test.ts: multi-host encoded localhost",
|
|
),
|
|
(
|
|
"mongodb://u:p@localhost:27018,%31%32%37.0.0.1/stock_dev",
|
|
ExpectedTargetOutcome::Qa,
|
|
"encoded-host.test.ts: multi-host encoded 127.0.0.1 omitted port",
|
|
),
|
|
(
|
|
"mongodb://dev_admin:dev_mongo_pass@localhost:27018/stock_dev",
|
|
ExpectedTargetOutcome::NotQa,
|
|
"encoded-host.test.ts: safe dev localhost:27018",
|
|
),
|
|
(
|
|
"mongodb://dev_admin:dev_mongo_pass@%6cocalhost:27018/stock_dev",
|
|
ExpectedTargetOutcome::NotQa,
|
|
"encoded-host.test.ts: encoded localhost on dev port 27018",
|
|
),
|
|
(
|
|
"mongodb://dev_admin:dev_mongo_pass@localhost:27018,127.0.0.1:27019/stock_dev",
|
|
ExpectedTargetOutcome::NotQa,
|
|
"encoded-host.test.ts: safe dev multi-host",
|
|
),
|
|
(
|
|
"mongodb://u:p@%zz:27017/stock",
|
|
ExpectedTargetOutcome::Rejected,
|
|
"encoded-host.test.ts: malformed %zz",
|
|
),
|
|
(
|
|
"mongodb://u:p@%zz:27018/stock_dev",
|
|
ExpectedTargetOutcome::Rejected,
|
|
"encoded-host.test.ts: malformed %zz on dev port",
|
|
),
|
|
(
|
|
"mongodb://u:p@localhost:27018,%zz:27017/stock_dev",
|
|
ExpectedTargetOutcome::Rejected,
|
|
"encoded-host.test.ts: malformed %zz second seed rejects entire URI",
|
|
),
|
|
(
|
|
"mongodb://u:p@local%2:27017/stock",
|
|
ExpectedTargetOutcome::Rejected,
|
|
"encoded-host.test.ts: truncated %2",
|
|
),
|
|
(
|
|
"mongodb://u:p@localhost%:27017/stock",
|
|
ExpectedTargetOutcome::Rejected,
|
|
"encoded-host.test.ts: trailing %",
|
|
),
|
|
(
|
|
"mongodb://u:p@[::1%zz]:27017/stock",
|
|
ExpectedTargetOutcome::Rejected,
|
|
"encoded-host.test.ts: IPv6 malformed %zz",
|
|
),
|
|
(
|
|
"mongodb://u:p@[not-ipv6%25zz]:27017/stock",
|
|
ExpectedTargetOutcome::Rejected,
|
|
"encoded-host.test.ts: non-IPv6 with %25",
|
|
),
|
|
(
|
|
"mongodb://u:p@[::1%25]:27017/stock",
|
|
ExpectedTargetOutcome::Rejected,
|
|
"encoded-host.test.ts: IPv6 empty zone ID",
|
|
),
|
|
(
|
|
"mongodb://u:p@[::1%25lo%2f]:27017/stock",
|
|
ExpectedTargetOutcome::Rejected,
|
|
"encoded-host.test.ts: IPv6 zone ID with %2f",
|
|
),
|
|
(
|
|
"mongodb://u:p@%256cocalhost:27017/stock",
|
|
ExpectedTargetOutcome::Qa,
|
|
"encoded-host.test.ts: double-encoded localhost",
|
|
),
|
|
(
|
|
"mongodb://u:p@%2531%2532%2537.0.0.1:27017/stock",
|
|
ExpectedTargetOutcome::Qa,
|
|
"encoded-host.test.ts: double-encoded 127.0.0.1",
|
|
),
|
|
(
|
|
"mongodb://u:p@localhost:27018,%256cocalhost:27017/stock_dev",
|
|
ExpectedTargetOutcome::Qa,
|
|
"encoded-host.test.ts: multi-host double-encoded localhost",
|
|
),
|
|
(
|
|
"mongodb://u:p@%25256cocalhost:27017/stock",
|
|
ExpectedTargetOutcome::Qa,
|
|
"encoded-host.test.ts: triple-encoded localhost",
|
|
),
|
|
(
|
|
"mongodb://trading_admin:pass@%256cocalhost:27017/stock",
|
|
ExpectedTargetOutcome::Qa,
|
|
"encoded-host.test.ts: trading_admin on double-encoded localhost",
|
|
),
|
|
(
|
|
"mongodb://studio_stock_bot_read:secret@%256cocalhost:27017/stock?authSource=stock",
|
|
ExpectedTargetOutcome::Qa,
|
|
"encoded-host.test.ts: read user on double-encoded localhost",
|
|
),
|
|
(
|
|
"mongodb://dev_admin:dev_mongo_pass@%256cocalhost:27018/stock_dev",
|
|
ExpectedTargetOutcome::NotQa,
|
|
"encoded-host.test.ts: double-encoded localhost on 27018",
|
|
),
|
|
(
|
|
"mongodb://u:p@localhost:27018/stock_dev",
|
|
ExpectedTargetOutcome::NotQa,
|
|
"encoded-host.test.ts: parityCase dev localhost:27018",
|
|
),
|
|
(
|
|
"mongodb://u:p@%6cocalhost:27018/stock_dev",
|
|
ExpectedTargetOutcome::NotQa,
|
|
"encoded-host.test.ts: parityCase encoded dev localhost:27018",
|
|
),
|
|
(
|
|
"mongodb://u:p@%256cocalhost:27018/stock_dev",
|
|
ExpectedTargetOutcome::NotQa,
|
|
"encoded-host.test.ts: parityCase double-encoded dev localhost:27018",
|
|
),
|
|
(
|
|
"mongodb://u:p@mongo.internal:27017/stock",
|
|
ExpectedTargetOutcome::NotQa,
|
|
"encoded-host.test.ts: parityCase remote mongo.internal:27017",
|
|
),
|
|
(
|
|
"mongodb://u:p@%25zz:27017/stock",
|
|
ExpectedTargetOutcome::Rejected,
|
|
"encoded-host.test.ts: double-encoded malformed %25zz",
|
|
),
|
|
(
|
|
"mongodb://u:p@%2525252525252525256cocalhost:27017/stock",
|
|
ExpectedTargetOutcome::Rejected,
|
|
"encoded-host.test.ts: excessive percent-encoding nesting (>8 passes)",
|
|
),
|
|
(
|
|
"mongodb://u:p@localhost%2f:27018/stock_dev",
|
|
ExpectedTargetOutcome::Rejected,
|
|
"encoded-host.test.ts: delimiter smuggling %2f",
|
|
),
|
|
(
|
|
"mongodb://u:p@%6cocalhost%2f:27018/stock_dev",
|
|
ExpectedTargetOutcome::Rejected,
|
|
"encoded-host.test.ts: delimiter smuggling %6cocalhost%2f",
|
|
),
|
|
(
|
|
"mongodb://u:p@localhost:27018,localhost%2f:27019/stock_dev",
|
|
ExpectedTargetOutcome::Rejected,
|
|
"encoded-host.test.ts: multi-host delimiter smuggling second seed",
|
|
),
|
|
(
|
|
"mongodb://u:p@localhost%3f:27018/stock_dev",
|
|
ExpectedTargetOutcome::Rejected,
|
|
"encoded-host.test.ts: delimiter smuggling %3f",
|
|
),
|
|
(
|
|
"mongodb://u:p@localhost%23:27018/stock_dev",
|
|
ExpectedTargetOutcome::Rejected,
|
|
"encoded-host.test.ts: delimiter smuggling %23",
|
|
),
|
|
(
|
|
"mongodb://u:p@%6cocalhost%3a27017%2f:27018/stock_dev",
|
|
ExpectedTargetOutcome::Rejected,
|
|
"encoded-host.test.ts: delimiter smuggling %3a + %2f",
|
|
),
|
|
(
|
|
"mongodb://u:p@x%40localhost%3a27017%2f:27018/stock_dev",
|
|
ExpectedTargetOutcome::Rejected,
|
|
"encoded-host.test.ts: delimiter smuggling %40",
|
|
),
|
|
(
|
|
"mongodb://u:p@%5b%3a%3a1%5d%3a27017%2f:27018/stock_dev",
|
|
ExpectedTargetOutcome::Rejected,
|
|
"encoded-host.test.ts: delimiter smuggling brackets",
|
|
),
|
|
(
|
|
"mongodb://u:p@localhost%252f:27018/stock_dev",
|
|
ExpectedTargetOutcome::Rejected,
|
|
"encoded-host.test.ts: double-encoded %252f",
|
|
),
|
|
(
|
|
"mongodb://u:p@localhost%5c:27018/stock_dev",
|
|
ExpectedTargetOutcome::Rejected,
|
|
"encoded-host.test.ts: encoded backslash %5c",
|
|
),
|
|
(
|
|
"mongodb://u:p@localhost%20:27018/stock_dev",
|
|
ExpectedTargetOutcome::Rejected,
|
|
"encoded-host.test.ts: encoded space %20",
|
|
),
|
|
(
|
|
"mongodb://u:p@[::1%2f]:27018/stock_dev",
|
|
ExpectedTargetOutcome::Rejected,
|
|
"encoded-host.test.ts: IPv6 with %2f",
|
|
),
|
|
(
|
|
"mongodb://u:p@localhost%00:27018/stock_dev",
|
|
ExpectedTargetOutcome::Rejected,
|
|
"encoded-host.test.ts: encoded NUL %00",
|
|
),
|
|
(
|
|
"mongodb://u:p@loc%0aalhost:27018/stock_dev",
|
|
ExpectedTargetOutcome::Rejected,
|
|
"encoded-host.test.ts: encoded LF %0a",
|
|
),
|
|
(
|
|
"mongodb://u:p@localhost%1f:27018/stock_dev",
|
|
ExpectedTargetOutcome::Rejected,
|
|
"encoded-host.test.ts: encoded 0x1f",
|
|
),
|
|
(
|
|
"mongodb://u:p@localhost%7f:27018/stock_dev",
|
|
ExpectedTargetOutcome::Rejected,
|
|
"encoded-host.test.ts: encoded DEL %7f",
|
|
),
|
|
(
|
|
"mongodb://u:p@localhost%7F:27018/stock_dev",
|
|
ExpectedTargetOutcome::Rejected,
|
|
"encoded-host.test.ts: encoded DEL %7F uppercase",
|
|
),
|
|
(
|
|
"mongodb://u:p@local%01host:27018/stock_dev",
|
|
ExpectedTargetOutcome::Rejected,
|
|
"encoded-host.test.ts: encoded SOH %01",
|
|
),
|
|
(
|
|
"mongodb://u:p@localhost%2500:27018/stock_dev",
|
|
ExpectedTargetOutcome::Rejected,
|
|
"encoded-host.test.ts: double-encoded NUL %2500",
|
|
),
|
|
(
|
|
"mongodb://u:p@localhost%257f:27018/stock_dev",
|
|
ExpectedTargetOutcome::Rejected,
|
|
"encoded-host.test.ts: double-encoded DEL %257f",
|
|
),
|
|
(
|
|
"mongodb://u:p@mongo.internal:27018,localhost%1f:27018/stock_dev",
|
|
ExpectedTargetOutcome::Rejected,
|
|
"encoded-host.test.ts: multi-host encoded 0x1f second seed",
|
|
),
|
|
(
|
|
"mongodb://u:p@[::1%00]:27018/stock_dev",
|
|
ExpectedTargetOutcome::Rejected,
|
|
"encoded-host.test.ts: IPv6 encoded NUL",
|
|
),
|
|
(
|
|
"mongodb://u:p@[::1%7f]:27018/stock_dev",
|
|
ExpectedTargetOutcome::Rejected,
|
|
"encoded-host.test.ts: IPv6 encoded DEL",
|
|
),
|
|
(
|
|
"mongodb://u:p@mongo%7einternal:27018/stock_dev",
|
|
ExpectedTargetOutcome::NotQa,
|
|
"encoded-host.test.ts: printable non-delimiter 0x7e (~) allowed",
|
|
),
|
|
(
|
|
"mongodb://dev_admin:dev_mongo_pass@%6C%4F%63%61%6C%68%6F%73%74:27018/stock_dev",
|
|
ExpectedTargetOutcome::NotQa,
|
|
"encoded-host.test.ts: mixed-case encoded dev port 27018",
|
|
),
|
|
(
|
|
"mongodb://dev_admin:dev_mongo_pass@%2531%2532%2537.0.0.1:27018/stock_dev",
|
|
ExpectedTargetOutcome::NotQa,
|
|
"encoded-host.test.ts: double-encoded 127.0.0.1 on dev port 27018",
|
|
),
|
|
(
|
|
"mongodb://dev_admin:dev_mongo_pass@[::1]:27018/stock_dev",
|
|
ExpectedTargetOutcome::NotQa,
|
|
"encoded-host.test.ts: IPv6 loopback on dev port 27018",
|
|
),
|
|
(
|
|
"mongodb://dev_admin:dev_mongo_pass@%6cocalhost:27018,127%2e0.0.1:27019/stock_dev",
|
|
ExpectedTargetOutcome::NotQa,
|
|
"encoded-host.test.ts: encoded dev multi-host 27018/27019",
|
|
),
|
|
(
|
|
"mongodb+srv://prod_user:Str0ngProdSecret@cluster0.prod-db.example.net/stock?retryWrites=true",
|
|
ExpectedTargetOutcome::NotQa,
|
|
"encoded-host.test.ts: prod SRV host",
|
|
),
|
|
(
|
|
"mongodb://prod_user:Str0ngProdSecret@mongo-0.prod.internal:27017,mongo-1.prod.internal:27017/stock?replicaSet=rs0",
|
|
ExpectedTargetOutcome::NotQa,
|
|
"encoded-host.test.ts: prod TCP multi-host",
|
|
),
|
|
(
|
|
"mongodb://prod_user:Str0ngProdSecret@%6dongo-0.prod.internal:27017/stock",
|
|
ExpectedTargetOutcome::NotQa,
|
|
"encoded-host.test.ts: encoded remote host",
|
|
),
|
|
// --- 5. test/unit/environment-safety-multi-host.test.ts ---
|
|
(
|
|
"mongodb://u:p@db1.dev.internal:27018,db2.dev.internal:27018,127.0.0.1:27017/stock_dev",
|
|
ExpectedTargetOutcome::Qa,
|
|
"multi-host.test.ts: 3-host list ending in 127.0.0.1:27017",
|
|
),
|
|
(
|
|
"mongodb://u:p@localhost:27018,localhost:27019,localhost/stock_dev?replicaSet=rs0",
|
|
ExpectedTargetOutcome::Qa,
|
|
"multi-host.test.ts: 3-host list ending in omitted-port localhost",
|
|
),
|
|
(
|
|
"mongodb://u:p@localhost:27018,0.0.0.0:27017/stock_dev",
|
|
ExpectedTargetOutcome::Qa,
|
|
"multi-host.test.ts: 0.0.0.0:27017 second host",
|
|
),
|
|
(
|
|
"mongodb://u:p@localhost:27018,localhost:027017/stock_dev",
|
|
ExpectedTargetOutcome::Qa,
|
|
"multi-host.test.ts: leading-zero port 027017",
|
|
),
|
|
(
|
|
"mongodb://u:p,w@localhost:27018,localhost:27017/stock",
|
|
ExpectedTargetOutcome::Qa,
|
|
"multi-host.test.ts: comma in password",
|
|
),
|
|
(
|
|
"mongodb://localhost:27018,localhost:27017",
|
|
ExpectedTargetOutcome::Qa,
|
|
"multi-host.test.ts: no userinfo no path",
|
|
),
|
|
(
|
|
"mongodb://u:p@localhost:27018,localhost:27019/stock_dev?appName=localhost:27017",
|
|
ExpectedTargetOutcome::NotQa,
|
|
"multi-host.test.ts: localhost:27017 only in query string",
|
|
),
|
|
(
|
|
"mongodb://u:p@10.0.0.51:27017,10.0.0.52:27017/stock",
|
|
ExpectedTargetOutcome::NotQa,
|
|
"multi-host.test.ts: remote multi-host on 27017",
|
|
),
|
|
(
|
|
"mongodb://u:p@localhost:27018,localhost:27017/stock",
|
|
ExpectedTargetOutcome::Qa,
|
|
"multi-host.test.ts: non-pipeline dev service QA seed list",
|
|
),
|
|
(
|
|
"mongodb://trading_admin:pw@localhost:27018,localhost:27017/stock",
|
|
ExpectedTargetOutcome::Qa,
|
|
"multi-host.test.ts: pipeline fallback trading_admin seed list",
|
|
),
|
|
(
|
|
"mongodb://studio_stock_bot_read:pw@localhost:27018,localhost:27017/stock",
|
|
ExpectedTargetOutcome::Qa,
|
|
"multi-host.test.ts: pipeline fallback read user seed list",
|
|
),
|
|
(
|
|
"mongodb://u:p@localhost:27018,,localhost:27017/stock",
|
|
ExpectedTargetOutcome::Qa,
|
|
"multi-host.test.ts: empty middle seed still classifies QA in parse_mongo_target",
|
|
),
|
|
(
|
|
"mongodb://u:p@localhost:27018,localhost:27017,/stock",
|
|
ExpectedTargetOutcome::Qa,
|
|
"multi-host.test.ts: trailing comma seed still classifies QA in parse_mongo_target",
|
|
),
|
|
(
|
|
"mongodb://r:pw@localhost:27017,localhost:27018/stock?authSource=stock",
|
|
ExpectedTargetOutcome::Qa,
|
|
"multi-host.test.ts: container db selection QA multi-host",
|
|
),
|
|
(
|
|
"mongodb://r:pw@h1.internal:27017,h2.internal/stock%5Fqa?authSource=admin",
|
|
ExpectedTargetOutcome::NotQa,
|
|
"multi-host.test.ts: container db selection remote encoded db",
|
|
),
|
|
(
|
|
"mongodb://r:pw@h1.internal,h2.internal/stock#frag",
|
|
ExpectedTargetOutcome::NotQa,
|
|
"multi-host.test.ts: container db selection remote with fragment",
|
|
),
|
|
(
|
|
"mongodb://r:pw@h1.internal:27017,h2.internal:27018/?replicaSet=rs0",
|
|
ExpectedTargetOutcome::NotQa,
|
|
"multi-host.test.ts: container db selection remote empty db",
|
|
),
|
|
(
|
|
"mongodb://r:pw@h1.internal,h2.internal",
|
|
ExpectedTargetOutcome::NotQa,
|
|
"multi-host.test.ts: container db selection remote no path",
|
|
),
|
|
];
|
|
|
|
assert!(
|
|
vectors.len() >= 100,
|
|
"expected >= 100 parity vectors, got {}",
|
|
vectors.len()
|
|
);
|
|
|
|
for (uri, expected, label) in vectors {
|
|
match (parse_mongo_target(uri), expected) {
|
|
(Ok(target), ExpectedTargetOutcome::Qa) => {
|
|
assert!(
|
|
is_qa_mongo_target(&target, &local_hosts),
|
|
"expected QA target for {label} ({uri:?}), parsed: {target:?}"
|
|
);
|
|
}
|
|
(Ok(target), ExpectedTargetOutcome::NotQa) => {
|
|
assert!(
|
|
!is_qa_mongo_target(&target, &local_hosts),
|
|
"expected NotQa target for {label} ({uri:?}), parsed: {target:?}"
|
|
);
|
|
}
|
|
(Err(_), ExpectedTargetOutcome::Rejected) => {}
|
|
(other, exp) => {
|
|
panic!("mismatch for {label} ({uri:?}): expected {exp:?}, got {other:?}");
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn qa_target_classification_covers_all_required_host_forms() {
|
|
let local_hosts = injected_local_hosts();
|
|
|
|
let required_qa_uris = [
|
|
"mongodb://studio_stock_bot_read:pw@localhost:27017/stock",
|
|
"mongodb://studio_stock_bot_read:pw@LOCALHOST.:27017/stock",
|
|
"mongodb://studio_stock_bot_read:pw@127.0.0.1:27017/stock",
|
|
"mongodb://studio_stock_bot_read:pw@127.1:27017/stock",
|
|
"mongodb://studio_stock_bot_read:pw@2130706433:27017/stock",
|
|
"mongodb://studio_stock_bot_read:pw@0x7f000001:27017/stock",
|
|
"mongodb://studio_stock_bot_read:pw@0177.0.0.1:27017/stock",
|
|
"mongodb://studio_stock_bot_read:pw@0127.0.0.1:27017/stock",
|
|
"mongodb://studio_stock_bot_read:pw@[::1]:27017/stock",
|
|
"mongodb://studio_stock_bot_read:pw@[::ffff:127.0.0.1]:27017/stock",
|
|
"mongodb://studio_stock_bot_read:pw@%6c%6f%63%61%6c%68%6f%73%74:27017/stock",
|
|
// Injected LAN IP (plain, hex, leading-zero decimal) and hostnames (full, short, .local)
|
|
"mongodb://studio_stock_bot_read:pw@192.168.1.50:27017/stock",
|
|
"mongodb://studio_stock_bot_read:pw@0xc0a80132:27017/stock",
|
|
"mongodb://studio_stock_bot_read:pw@192.168.001.050:27017/stock",
|
|
"mongodb://studio_stock_bot_read:pw@quant.lan.local:27017/stock",
|
|
"mongodb://studio_stock_bot_read:pw@quant:27017/stock",
|
|
"mongodb://studio_stock_bot_read:pw@quant.local:27017/stock",
|
|
"mongodb://studio_stock_bot_read:pw@[fe80::1234:5678%25eth0]:27017/stock",
|
|
// Omitted port
|
|
"mongodb://studio_stock_bot_read:pw@localhost/stock",
|
|
// Multi-host where only the second host is loopback
|
|
"mongodb://studio_stock_bot_read:pw@mongo.remote.internal:27018,127.0.0.1:27017/stock",
|
|
];
|
|
|
|
for uri in required_qa_uris {
|
|
let target = parse_mongo_target(uri).unwrap_or_else(|e| panic!("failed to parse {uri}: {e}"));
|
|
assert!(
|
|
is_qa_mongo_target(&target, &local_hosts),
|
|
"expected QA target for {uri}"
|
|
);
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn assert_read_only_rejects_trading_admin_on_any_host_and_any_casing_or_encoding() {
|
|
let local_hosts = injected_local_hosts();
|
|
// Even if a caller mistakenly puts trading_admin in allowed_read_users, it must still be rejected.
|
|
let permissive_policy = ReadOnlyPolicy {
|
|
allowed_read_users: vec![
|
|
DEFAULT_ALLOWED_READ_USER.to_owned(),
|
|
FORBIDDEN_ADMIN_USER.to_owned(),
|
|
"TRADING_ADMIN".to_owned(),
|
|
],
|
|
};
|
|
|
|
let admin_uris = [
|
|
// QA hosts
|
|
"mongodb://trading_admin:pw@localhost:27017/stock",
|
|
"mongodb://TRADING_ADMIN:pw@localhost:27017/stock",
|
|
"mongodb://TrAdInG_aDmIn:pw@127.0.0.1:27017/stock",
|
|
"mongodb://trading%5Fadmin:pw@localhost:27017/stock",
|
|
"mongodb://%74%72%61%64%69%6e%67%5f%61%64%6d%69%6e:pw@[::1]:27017/stock",
|
|
// Non-QA hosts (dev port 27018, remote host, srv)
|
|
"mongodb://trading_admin:pw@localhost:27018/stock_dev",
|
|
"mongodb://TRADING_ADMIN:pw@10.0.0.51:27017/stock",
|
|
"mongodb://TrAdInG_aDmIn:pw@mongo.prod.internal:27017/stock",
|
|
"mongodb://trading%5Fadmin:pw@localhost:27018/stock_dev",
|
|
"mongodb+srv://trading_admin:pw@cluster.example.com/stock",
|
|
];
|
|
|
|
for uri in admin_uris {
|
|
assert_eq!(
|
|
assert_read_only_mongo_uri(uri, &ReadOnlyPolicy::default(), &local_hosts),
|
|
Err(MongoSafetyError::ForbiddenAdminUser),
|
|
"default policy must reject {uri}"
|
|
);
|
|
assert_eq!(
|
|
assert_read_only_mongo_uri(uri, &permissive_policy, &local_hosts),
|
|
Err(MongoSafetyError::ForbiddenAdminUser),
|
|
"permissive policy must still reject {uri}"
|
|
);
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn assert_read_only_enforces_qa_credentials_and_allowlist() {
|
|
let local_hosts = injected_local_hosts();
|
|
let policy = ReadOnlyPolicy::default();
|
|
|
|
// Missing credentials on QA targets
|
|
for uri in [
|
|
"mongodb://localhost:27017/stock",
|
|
"mongodb://127.0.0.1/stock",
|
|
"mongodb://:secret_pw@localhost:27017/stock",
|
|
"mongodb://quant.lan.local:27017/stock",
|
|
] {
|
|
assert_eq!(
|
|
assert_read_only_mongo_uri(uri, &policy, &local_hosts),
|
|
Err(MongoSafetyError::MissingCredentialsForQaTarget),
|
|
"expected MissingCredentialsForQaTarget for {uri}"
|
|
);
|
|
}
|
|
|
|
// Non-allowlisted usernames on QA targets (including case mismatch)
|
|
for uri in [
|
|
"mongodb://dev_admin:pw@localhost:27017/stock",
|
|
"mongodb://STUDIO_STOCK_BOT_READ:pw@localhost:27017/stock",
|
|
"mongodb://other_reader:pw@127.1:27017/stock",
|
|
"mongodb://reader:pw@localhost:27018,localhost:27017/stock",
|
|
] {
|
|
assert_eq!(
|
|
assert_read_only_mongo_uri(uri, &policy, &local_hosts),
|
|
Err(MongoSafetyError::UnauthorizedQaUser),
|
|
"expected UnauthorizedQaUser for {uri}"
|
|
);
|
|
}
|
|
|
|
// Custom allowlist accepts a custom read user on QA
|
|
let custom_policy = ReadOnlyPolicy {
|
|
allowed_read_users: vec!["custom_ro".to_owned()],
|
|
};
|
|
let validated = assert_read_only_mongo_uri(
|
|
"mongodb://custom_ro:s3cr3t@localhost:27017/stock",
|
|
&custom_policy,
|
|
&local_hosts,
|
|
)
|
|
.expect("custom allowlisted user should pass");
|
|
assert!(validated.is_qa_target());
|
|
assert_eq!(validated.target().username.as_deref(), Some("custom_ro"));
|
|
}
|
|
|
|
#[test]
|
|
fn assert_read_only_rejects_authority_splits_control_chars_malformed_segments_and_bad_srv() {
|
|
let local_hosts = injected_local_hosts();
|
|
let policy = ReadOnlyPolicy::default();
|
|
|
|
let cases: &[(&str, MongoSafetyError)] = &[
|
|
("", MongoSafetyError::EmptyUri),
|
|
(" ", MongoSafetyError::ForbiddenWhitespace),
|
|
("http://localhost:27017/stock", MongoSafetyError::UnsupportedScheme),
|
|
("postgres://localhost:5432/db", MongoSafetyError::UnsupportedScheme),
|
|
("not-a-uri", MongoSafetyError::UnsupportedScheme),
|
|
(
|
|
"mongodb://studio_stock_bot_read:pw@localhost:27018#,localhost:27017/stock",
|
|
MongoSafetyError::UnencodedHashInAuthority,
|
|
),
|
|
(
|
|
"mongodb://studio_stock_bot_read:pw@localhost:27017@x:27018/stock",
|
|
MongoSafetyError::MultipleAtInAuthority,
|
|
),
|
|
(
|
|
"mongodb://localhost:27018/stock_dev?appName=a@b",
|
|
MongoSafetyError::UnencodedAtInRemainderWithoutCredentials,
|
|
),
|
|
(
|
|
"mongodb://localhost:27018/stock_dev#frag@x",
|
|
MongoSafetyError::UnencodedAtInRemainderWithoutCredentials,
|
|
),
|
|
(
|
|
"mongodb://studio_stock_bot_read:pw@local\nhost:27017/stock",
|
|
MongoSafetyError::ControlCharacters,
|
|
),
|
|
(
|
|
"mongodb://studio_stock_bot_read:pw@localhost:27017/stock\x00",
|
|
MongoSafetyError::ControlCharacters,
|
|
),
|
|
(
|
|
"mongodb://studio_stock_bot_read:pw@localhost:27017/stock\x7f",
|
|
MongoSafetyError::ControlCharacters,
|
|
),
|
|
(
|
|
"mongodb://studio_stock_bot_read:pw@local\u{00A0}host:27017/stock",
|
|
MongoSafetyError::ForbiddenWhitespace,
|
|
),
|
|
(
|
|
"mongodb://studio_stock_bot_read:pw@localhost:27017/stock\u{FEFF}",
|
|
MongoSafetyError::ForbiddenWhitespace,
|
|
),
|
|
(
|
|
"mongodb://studio_stock_bot_read:pw@bad:port,localhost:27017/stock",
|
|
MongoSafetyError::MalformedHostSegment,
|
|
),
|
|
(
|
|
"mongodb://studio_stock_bot_read:pw@localhost:27018,,localhost:27017/stock",
|
|
MongoSafetyError::MalformedHostSegment,
|
|
),
|
|
(
|
|
"mongodb://studio_stock_bot_read:pw@localhost:27018,localhost:27017,/stock",
|
|
MongoSafetyError::MalformedHostSegment,
|
|
),
|
|
(
|
|
"mongodb+srv://studio_stock_bot_read:pw@cluster.example.com:27017/stock",
|
|
MongoSafetyError::InvalidSrvTarget,
|
|
),
|
|
(
|
|
"mongodb+srv://studio_stock_bot_read:pw@cluster.example.com:/stock",
|
|
MongoSafetyError::InvalidSrvTarget,
|
|
),
|
|
(
|
|
"mongodb+srv://studio_stock_bot_read:pw@a.example.com,b.example.com/stock",
|
|
MongoSafetyError::InvalidSrvTarget,
|
|
),
|
|
(
|
|
"mongodb://bad%zzuser:pw@localhost:27018/stock_dev",
|
|
MongoSafetyError::InvalidUsernameEncoding,
|
|
),
|
|
// Malformed bracketed IPv6 literals (single-seed and multi-seed)
|
|
(
|
|
"mongodb://studio_stock_bot_read:pw@[fe80::g]:27017/stock",
|
|
MongoSafetyError::NoValidHosts,
|
|
),
|
|
(
|
|
"mongodb://studio_stock_bot_read:pw@[::1::2]:27017/stock",
|
|
MongoSafetyError::NoValidHosts,
|
|
),
|
|
(
|
|
"mongodb://studio_stock_bot_read:pw@[1:2:3]:27017/stock",
|
|
MongoSafetyError::NoValidHosts,
|
|
),
|
|
(
|
|
"mongodb://studio_stock_bot_read:pw@[not-an-ipv6]:27017/stock",
|
|
MongoSafetyError::NoValidHosts,
|
|
),
|
|
(
|
|
"mongodb://studio_stock_bot_read:pw@[localhost]:27017/stock",
|
|
MongoSafetyError::NoValidHosts,
|
|
),
|
|
(
|
|
"mongodb://studio_stock_bot_read:pw@localhost:27018,[fe80::g]:27017/stock",
|
|
MongoSafetyError::MalformedHostSegment,
|
|
),
|
|
(
|
|
"mongodb://studio_stock_bot_read:pw@[fe80::g]:27017,localhost:27017/stock",
|
|
MongoSafetyError::MalformedHostSegment,
|
|
),
|
|
];
|
|
|
|
for (uri, expected_err) in cases {
|
|
assert_eq!(
|
|
assert_read_only_mongo_uri(uri, &policy, &local_hosts),
|
|
Err(expected_err.clone()),
|
|
"unexpected outcome for {uri:?}"
|
|
);
|
|
}
|
|
|
|
// Multi-seed URI with a malformed bracketed IPv6 and a valid QA seed still classifies as QA in
|
|
// parse_mongo_target + is_qa_mongo_target (preserving TS classifier behavior), while
|
|
// assert_read_only_mongo_uri above fails closed with MalformedHostSegment.
|
|
let mixed_target = parse_mongo_target(
|
|
"mongodb://studio_stock_bot_read:pw@[fe80::g]:27017,localhost:27017/stock",
|
|
)
|
|
.expect("valid second seed should survive parse_mongo_target");
|
|
assert!(mixed_target.has_invalid_host_segment());
|
|
assert!(is_qa_mongo_target(&mixed_target, &local_hosts));
|
|
|
|
// Valid non-loopback bracketed IPv6 literals are still accepted.
|
|
for valid_ipv6_uri in [
|
|
"mongodb://reader:pw@[fe80::1]:27017/stock",
|
|
"mongodb://reader:pw@[2001:db8::1]:27017/stock",
|
|
"mongodb://reader:pw@[::ffff:0a00:1]:27017/stock",
|
|
] {
|
|
let validated = assert_read_only_mongo_uri(valid_ipv6_uri, &policy, &local_hosts)
|
|
.unwrap_or_else(|e| panic!("valid non-loopback IPv6 should pass ({valid_ipv6_uri}): {e}"));
|
|
assert!(!validated.is_qa_target());
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn valid_qa_read_only_uri_is_accepted_and_passwords_are_redacted_everywhere() {
|
|
let local_hosts = injected_local_hosts();
|
|
let policy = ReadOnlyPolicy::default();
|
|
let secret = "SuperSecret_Pass:With:Colons%21";
|
|
let uri = format!(
|
|
"mongodb://studio_stock_bot_read:{secret}@localhost:27017/stock?authSource=stock"
|
|
);
|
|
|
|
let validated = assert_read_only_mongo_uri(&uri, &policy, &local_hosts)
|
|
.expect("studio_stock_bot_read on QA localhost:27017 should be accepted");
|
|
|
|
assert_eq!(validated.as_str(), uri);
|
|
assert!(validated.is_qa_target());
|
|
assert_eq!(validated.target().scheme, MongoScheme::Standard);
|
|
assert_eq!(validated.target().database.as_deref(), Some("stock"));
|
|
assert_eq!(
|
|
validated.target().username.as_deref(),
|
|
Some("studio_stock_bot_read")
|
|
);
|
|
assert_eq!(
|
|
validated.redacted(),
|
|
"mongodb://studio_stock_bot_read:[REDACTED]@localhost:27017/stock?authSource=stock"
|
|
);
|
|
|
|
let display_out = format!("{validated}");
|
|
let debug_out = format!("{validated:?}");
|
|
assert!(!display_out.contains(secret), "Display leaked password: {display_out}");
|
|
assert!(!debug_out.contains(secret), "Debug leaked password: {debug_out}");
|
|
assert!(display_out.contains("[REDACTED]"));
|
|
assert!(debug_out.contains("[REDACTED]"));
|
|
|
|
// Passwordless non-QA URI remains unchanged by redaction
|
|
let no_pass = assert_read_only_mongo_uri(
|
|
"mongodb://dev_user@localhost:27018/stock_dev",
|
|
&policy,
|
|
&local_hosts,
|
|
)
|
|
.expect("passwordless non-QA URI should be accepted");
|
|
assert!(!no_pass.is_qa_target());
|
|
assert_eq!(
|
|
no_pass.redacted(),
|
|
"mongodb://dev_user@localhost:27018/stock_dev"
|
|
);
|
|
|
|
// Exhaustive redaction check across EVERY MongoSafetyError variant.
|
|
// The match below has no wildcard arm so adding a new variant forces test coverage.
|
|
fn error_variant_index(err: &MongoSafetyError) -> usize {
|
|
match err {
|
|
MongoSafetyError::EmptyUri => 0,
|
|
MongoSafetyError::ControlCharacters => 1,
|
|
MongoSafetyError::ForbiddenWhitespace => 2,
|
|
MongoSafetyError::UnsupportedScheme => 3,
|
|
MongoSafetyError::EmptyAuthority => 4,
|
|
MongoSafetyError::UnencodedHashInAuthority => 5,
|
|
MongoSafetyError::EmptyUserinfo => 6,
|
|
MongoSafetyError::MultipleAtInAuthority => 7,
|
|
MongoSafetyError::UnencodedAtInRemainderWithoutCredentials => 8,
|
|
MongoSafetyError::EmptyHostList => 9,
|
|
MongoSafetyError::InvalidUsernameEncoding => 10,
|
|
MongoSafetyError::InvalidHostEncoding => 11,
|
|
MongoSafetyError::ForbiddenHostCharacters => 12,
|
|
MongoSafetyError::NoValidHosts => 13,
|
|
MongoSafetyError::MalformedHostSegment => 14,
|
|
MongoSafetyError::InvalidSrvTarget => 15,
|
|
MongoSafetyError::ForbiddenAdminUser => 16,
|
|
MongoSafetyError::MissingCredentialsForQaTarget => 17,
|
|
MongoSafetyError::UnauthorizedQaUser => 18,
|
|
}
|
|
}
|
|
const VARIANT_COUNT: usize = 19;
|
|
|
|
let err_secret = "LeakCheck_Pw98765";
|
|
let error_cases: Vec<(String, MongoSafetyError)> = vec![
|
|
(String::new(), MongoSafetyError::EmptyUri),
|
|
(
|
|
format!("mongodb://studio_stock_bot_read:{err_secret}@local\nhost:27017/stock"),
|
|
MongoSafetyError::ControlCharacters,
|
|
),
|
|
(
|
|
format!("mongodb://studio_stock_bot_read:{err_secret}@local\u{00A0}host:27017/stock"),
|
|
MongoSafetyError::ForbiddenWhitespace,
|
|
),
|
|
(
|
|
format!("http://studio_stock_bot_read:{err_secret}@localhost:27017/stock"),
|
|
MongoSafetyError::UnsupportedScheme,
|
|
),
|
|
(
|
|
format!("mongodb:///stock?pw={err_secret}"),
|
|
MongoSafetyError::EmptyAuthority,
|
|
),
|
|
(
|
|
format!(
|
|
"mongodb://studio_stock_bot_read:{err_secret}@localhost:27018#,localhost:27017/stock"
|
|
),
|
|
MongoSafetyError::UnencodedHashInAuthority,
|
|
),
|
|
(
|
|
format!("mongodb://@localhost:27018/stock?pw={err_secret}"),
|
|
MongoSafetyError::EmptyUserinfo,
|
|
),
|
|
(
|
|
format!(
|
|
"mongodb://studio_stock_bot_read:{err_secret}@localhost:27017@x:27018/stock"
|
|
),
|
|
MongoSafetyError::MultipleAtInAuthority,
|
|
),
|
|
(
|
|
format!("mongodb://localhost:27018/stock?pw={err_secret}@x"),
|
|
MongoSafetyError::UnencodedAtInRemainderWithoutCredentials,
|
|
),
|
|
(
|
|
format!("mongodb://studio_stock_bot_read:{err_secret}@/stock"),
|
|
MongoSafetyError::EmptyHostList,
|
|
),
|
|
(
|
|
format!("mongodb://bad%zz:{err_secret}@localhost:27018/stock_dev"),
|
|
MongoSafetyError::InvalidUsernameEncoding,
|
|
),
|
|
(
|
|
format!("mongodb://studio_stock_bot_read:{err_secret}@%zz:27017/stock"),
|
|
MongoSafetyError::InvalidHostEncoding,
|
|
),
|
|
(
|
|
format!("mongodb://studio_stock_bot_read:{err_secret}@localhost%2f:27018/stock"),
|
|
MongoSafetyError::ForbiddenHostCharacters,
|
|
),
|
|
(
|
|
format!("mongodb://studio_stock_bot_read:{err_secret}@bad:port/stock"),
|
|
MongoSafetyError::NoValidHosts,
|
|
),
|
|
(
|
|
format!("mongodb://studio_stock_bot_read:{err_secret}@bad:port,localhost:27017/stock"),
|
|
MongoSafetyError::MalformedHostSegment,
|
|
),
|
|
(
|
|
format!("mongodb+srv://studio_stock_bot_read:{err_secret}@a.example.com:27017/stock"),
|
|
MongoSafetyError::InvalidSrvTarget,
|
|
),
|
|
(
|
|
format!("mongodb://trading_admin:{err_secret}@localhost:27017/stock"),
|
|
MongoSafetyError::ForbiddenAdminUser,
|
|
),
|
|
(
|
|
format!("mongodb://:{err_secret}@localhost:27017/stock"),
|
|
MongoSafetyError::MissingCredentialsForQaTarget,
|
|
),
|
|
(
|
|
format!("mongodb://other_user:{err_secret}@localhost:27017/stock"),
|
|
MongoSafetyError::UnauthorizedQaUser,
|
|
),
|
|
// Extra malformed inputs where missing '@' pushes user:secret into host position
|
|
(
|
|
format!("mongodb://studio_stock_bot_read:{err_secret}/stock"),
|
|
MongoSafetyError::NoValidHosts,
|
|
),
|
|
(
|
|
format!("mongodb://{err_secret}%zz:27017/stock"),
|
|
MongoSafetyError::InvalidHostEncoding,
|
|
),
|
|
];
|
|
|
|
let mut covered = [false; VARIANT_COUNT];
|
|
for (bad_uri, expected_variant) in error_cases {
|
|
let err = assert_read_only_mongo_uri(&bad_uri, &policy, &local_hosts)
|
|
.expect_err("expected error for redaction test case");
|
|
assert_eq!(
|
|
err, expected_variant,
|
|
"unexpected error variant for redaction input"
|
|
);
|
|
covered[error_variant_index(&err)] = true;
|
|
let err_display = format!("{err}");
|
|
let err_debug = format!("{err:?}");
|
|
assert!(
|
|
!err_display.contains(err_secret),
|
|
"error Display leaked password for {expected_variant:?}: {err_display}"
|
|
);
|
|
assert!(
|
|
!err_debug.contains(err_secret),
|
|
"error Debug leaked password for {expected_variant:?}: {err_debug}"
|
|
);
|
|
}
|
|
assert!(
|
|
covered.iter().all(|&seen| seen),
|
|
"redaction test missed one or more MongoSafetyError variants: {covered:?}"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn deterministic_generated_parity_sweeps_match_ts_suites() {
|
|
let local_hosts = injected_local_hosts();
|
|
let policy = ReadOnlyPolicy::default();
|
|
|
|
// 1. environment-safety-encoded-host.test.ts: 14 hostSpellings x 3 ports = 42 cases.
|
|
let host_spellings: &[(&str, &str)] = &[
|
|
("localhost", "loopback"),
|
|
("%6cocalhost", "loopback"),
|
|
("%256cocalhost", "loopback"),
|
|
("127.0.0.1", "loopback"),
|
|
("%31%32%37.0.0.1", "loopback"),
|
|
("[::1]", "loopback"),
|
|
("localhost%2f", "rejected"),
|
|
("localhost%3f", "rejected"),
|
|
("localhost%23", "rejected"),
|
|
("localhost%3a27017%2f", "rejected"),
|
|
("localhost%3a27017", "rejected"),
|
|
("localhost%2c127.0.0.1", "rejected"),
|
|
("mongo.internal", "remote"),
|
|
("mongo.internal%2f", "rejected"),
|
|
];
|
|
let ports = [":27017", ":27018", ""];
|
|
|
|
let mut generated_count = 0usize;
|
|
for &(host, kind) in host_spellings {
|
|
for &port in &ports {
|
|
let uri = format!("mongodb://u:p@{host}{port}/stock_dev");
|
|
generated_count += 1;
|
|
let expected = match (kind, port) {
|
|
("rejected", _) => ExpectedTargetOutcome::Rejected,
|
|
("remote", _) => ExpectedTargetOutcome::NotQa,
|
|
("loopback", ":27018") => ExpectedTargetOutcome::NotQa,
|
|
("loopback", ":27017" | "") => ExpectedTargetOutcome::Qa,
|
|
_ => unreachable!(),
|
|
};
|
|
match (parse_mongo_target(&uri), expected) {
|
|
(Ok(target), ExpectedTargetOutcome::Qa) => {
|
|
assert!(
|
|
is_qa_mongo_target(&target, &local_hosts),
|
|
"expected Qa for generated URI {uri}"
|
|
);
|
|
assert_eq!(
|
|
assert_read_only_mongo_uri(&uri, &policy, &local_hosts),
|
|
Err(MongoSafetyError::UnauthorizedQaUser),
|
|
"read-only guard must reject unauthorized user on QA {uri}"
|
|
);
|
|
}
|
|
(Ok(target), ExpectedTargetOutcome::NotQa) => {
|
|
assert!(
|
|
!is_qa_mongo_target(&target, &local_hosts),
|
|
"expected NotQa for generated URI {uri}"
|
|
);
|
|
}
|
|
(Err(_), ExpectedTargetOutcome::Rejected) => {
|
|
assert!(assert_read_only_mongo_uri(&uri, &policy, &local_hosts).is_err());
|
|
}
|
|
(other, exp) => {
|
|
panic!("generated sweep mismatch for {uri}: expected {exp:?}, got {other:?}");
|
|
}
|
|
}
|
|
}
|
|
}
|
|
assert_eq!(generated_count, 42);
|
|
|
|
// 2. environment-safety-encoded-host.test.ts: deterministic 3,000-iteration seeded
|
|
// percent-encoding sweep (seed = 20261127, identical LCG formula).
|
|
// Pinned against the independent TypeScript env-safety.ts reference:
|
|
// qa = 885, not_qa = 479, rejected = 1636, FNV-1a64 = 0xf88a38ce1b8f844e (0 diffs).
|
|
fn fnv1a_update(hash: u64, byte: u8) -> u64 {
|
|
(hash ^ u64::from(byte)).wrapping_mul(0x0000_0100_0000_01b3)
|
|
}
|
|
const FNV_OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
|
|
const OUTCOME_QA: u8 = 1;
|
|
const OUTCOME_NOT_QA: u8 = 2;
|
|
const OUTCOME_REJECTED: u8 = 3;
|
|
|
|
let classify_rust = |uri: &str| -> (u8, Option<MongoSafetyError>) {
|
|
match parse_mongo_target(uri) {
|
|
Ok(target) => {
|
|
if is_qa_mongo_target(&target, &local_hosts) {
|
|
(OUTCOME_QA, None)
|
|
} else {
|
|
(OUTCOME_NOT_QA, None)
|
|
}
|
|
}
|
|
Err(err) => (OUTCOME_REJECTED, Some(err)),
|
|
}
|
|
};
|
|
|
|
let mut enc_state: u32 = 20261127;
|
|
let mut next_enc = || -> f64 {
|
|
enc_state = enc_state.wrapping_mul(1103515245).wrapping_add(12345) & 0x7fff_ffff;
|
|
(enc_state as f64) / (0x7fff_ffffu32 as f64)
|
|
};
|
|
let base_hosts: &[(&str, &str)] = &[
|
|
("localhost", "loopback"),
|
|
("LocalHost", "loopback"),
|
|
("localhost.", "loopback"),
|
|
("127.0.0.1", "loopback"),
|
|
("127.1.2.3", "loopback"),
|
|
("0.0.0.0", "loopback"),
|
|
("[::1]", "bracketed_loopback"),
|
|
("localhost/", "smuggled"),
|
|
("localhost?", "smuggled"),
|
|
("localhost#", "smuggled"),
|
|
("localhost:27017", "smuggled"),
|
|
("localhost:27017/", "smuggled"),
|
|
("[::1]:27017/", "smuggled"),
|
|
("localhost,localhost", "smuggled"),
|
|
("loc%0aalhost", "smuggled"),
|
|
("localhost%09", "smuggled"),
|
|
("loc%00alhost", "smuggled"),
|
|
("x%40localhost", "smuggled"),
|
|
("%5b::1%5d", "smuggled"),
|
|
("mongo.internal", "remote"),
|
|
];
|
|
let mut enc_qa = 0usize;
|
|
let mut enc_not_qa = 0usize;
|
|
let mut enc_rejected = 0usize;
|
|
let mut enc_hash = FNV_OFFSET;
|
|
for _ in 0..3000 {
|
|
let base_idx =
|
|
((next_enc() * (base_hosts.len() as f64)) as usize).min(base_hosts.len() - 1);
|
|
let port_idx = ((next_enc() * (ports.len() as f64)) as usize).min(ports.len() - 1);
|
|
let depth = 1 + ((next_enc() * 3.0) as usize).min(2);
|
|
let (base, kind) = base_hosts[base_idx];
|
|
let port = ports[port_idx];
|
|
|
|
let mut encoded = String::new();
|
|
for ch in base.chars() {
|
|
if next_enc() < 0.4 {
|
|
let code = ch as u32;
|
|
let upper = next_enc() < 0.5;
|
|
if upper {
|
|
encoded.push_str(&format!("%{code:02X}"));
|
|
} else {
|
|
encoded.push_str(&format!("%{code:02x}"));
|
|
}
|
|
} else {
|
|
encoded.push(ch);
|
|
}
|
|
}
|
|
for _ in 1..depth {
|
|
encoded = encoded.replace('%', "%25");
|
|
}
|
|
|
|
let uri = format!("mongodb://u:p@{encoded}{port}/stock_dev");
|
|
let (outcome, err) = classify_rust(&uri);
|
|
match outcome {
|
|
OUTCOME_QA => enc_qa += 1,
|
|
OUTCOME_NOT_QA => enc_not_qa += 1,
|
|
OUTCOME_REJECTED => enc_rejected += 1,
|
|
_ => unreachable!(),
|
|
}
|
|
enc_hash = fnv1a_update(enc_hash, outcome);
|
|
|
|
match (kind, port) {
|
|
("loopback", ":27017" | "") => {
|
|
assert_eq!(
|
|
outcome, OUTCOME_QA,
|
|
"encoded loopback QA URI must classify as Qa: {uri} (err={err:?})"
|
|
);
|
|
assert_eq!(
|
|
assert_read_only_mongo_uri(&uri, &policy, &local_hosts),
|
|
Err(MongoSafetyError::UnauthorizedQaUser),
|
|
"read-only guard must reject unauthorized loopback QA URI: {uri}"
|
|
);
|
|
}
|
|
("loopback", ":27018") => {
|
|
// Valid percent-encoded loopback on dev port 27018 must NEVER be rejected.
|
|
assert_eq!(
|
|
outcome, OUTCOME_NOT_QA,
|
|
"encoded loopback dev-port URI must classify as NotQa: {uri} (err={err:?})"
|
|
);
|
|
assert!(
|
|
assert_read_only_mongo_uri(&uri, &policy, &local_hosts).is_ok(),
|
|
"read-only guard must accept encoded loopback dev-port URI: {uri}"
|
|
);
|
|
}
|
|
("bracketed_loopback", ":27017" | "") => {
|
|
let brackets_intact = encoded.starts_with('[') && encoded.ends_with(']');
|
|
if brackets_intact {
|
|
assert_eq!(
|
|
outcome, OUTCOME_QA,
|
|
"bracket-intact encoded [::1] QA URI must classify as Qa: {uri}"
|
|
);
|
|
assert_eq!(
|
|
assert_read_only_mongo_uri(&uri, &policy, &local_hosts),
|
|
Err(MongoSafetyError::UnauthorizedQaUser)
|
|
);
|
|
} else {
|
|
assert_eq!(
|
|
outcome, OUTCOME_REJECTED,
|
|
"bracket-encoded [::1] URI must be rejected: {uri}"
|
|
);
|
|
}
|
|
}
|
|
("bracketed_loopback", ":27018") => {
|
|
let brackets_intact = encoded.starts_with('[') && encoded.ends_with(']');
|
|
if brackets_intact {
|
|
assert_eq!(
|
|
outcome, OUTCOME_NOT_QA,
|
|
"bracket-intact encoded [::1]:27018 must classify as NotQa: {uri}"
|
|
);
|
|
assert!(assert_read_only_mongo_uri(&uri, &policy, &local_hosts).is_ok());
|
|
} else {
|
|
assert_eq!(
|
|
outcome, OUTCOME_REJECTED,
|
|
"bracket-encoded [::1]:27018 must be rejected: {uri}"
|
|
);
|
|
}
|
|
}
|
|
("remote", _) => {
|
|
assert_eq!(
|
|
outcome, OUTCOME_NOT_QA,
|
|
"remote encoded URI must classify as NotQa: {uri} (err={err:?})"
|
|
);
|
|
assert!(assert_read_only_mongo_uri(&uri, &policy, &local_hosts).is_ok());
|
|
}
|
|
("smuggled", _) => {
|
|
assert_ne!(
|
|
outcome, OUTCOME_NOT_QA,
|
|
"smuggled URI must never classify as NotQa: {uri}"
|
|
);
|
|
}
|
|
_ => unreachable!(),
|
|
}
|
|
}
|
|
// Exact independent TypeScript env-safety.ts reference counts and 64-bit FNV-1a checksum.
|
|
assert_eq!(enc_qa, 885);
|
|
assert_eq!(enc_not_qa, 479);
|
|
assert_eq!(enc_rejected, 1636);
|
|
assert_eq!(enc_hash, 0xf88a_38ce_1b8f_844e);
|
|
|
|
// 3. environment-safety-authority-split.test.ts: full 30,000-iteration deterministic LCG
|
|
// fuzz corpora for BOTH seeds (0x7e28 and 0x28e7), pinned against the independent
|
|
// TypeScript env-safety.ts reference.
|
|
// Every difference between Rust parse_mongo_target/is_qa_mongo_target and TS env-safety.ts
|
|
// is strictly one of three documented intentional stricter-than-TS rules (never permissive):
|
|
// (a) leading/trailing whitespace rejected without trimming (ForbiddenWhitespace)
|
|
// (b) unencoded '@' in remainder without credentials (UnencodedAtInRemainderWithoutCredentials)
|
|
// (c) malformed bracketed IPv6 hosts rejected (NoValidHosts)
|
|
let fuzz_tokens = [
|
|
"localhost",
|
|
"127.0.0.1",
|
|
"[::1]",
|
|
":27017",
|
|
":27018",
|
|
"#",
|
|
"@",
|
|
"/",
|
|
"?",
|
|
",",
|
|
"u",
|
|
"p",
|
|
":",
|
|
"x",
|
|
"%40",
|
|
"%23",
|
|
"\\",
|
|
";",
|
|
"[",
|
|
"]",
|
|
"%2C",
|
|
".",
|
|
"LOCALHOST",
|
|
"\u{0000}",
|
|
"\n",
|
|
"\t",
|
|
" ",
|
|
"27017",
|
|
"%3A",
|
|
"dev_admin:dev_mongo_pass",
|
|
];
|
|
// Reference-generation command (run from repo root using Bun against a temp copy of
|
|
// apps/stock/config/src/env-safety.ts with `getLocalMachineHosts` stubbed to
|
|
// `["quant-host.lan", "quant-host", "quant-host.local", "10.0.0.51", "fe80::1"]`
|
|
// and `export { parseMongoTarget, isQaMongoTargetHosts };` appended):
|
|
// bun -e '
|
|
// import { readFileSync, writeFileSync, unlinkSync } from "node:fs";
|
|
// const src = readFileSync("./apps/stock/config/src/env-safety.ts", "utf8");
|
|
// const tmp = "/tmp/env_safety_ref.ts";
|
|
// writeFileSync(tmp, src.replace(/function getLocalMachineHosts\([\s\S]*?\n\}/,
|
|
// `function getLocalMachineHosts(){return new Set(["quant-host.lan","quant-host","quant-host.local","10.0.0.51","fe80::1"]);}`)
|
|
// + "\nexport { parseMongoTarget, isQaMongoTargetHosts };\n");
|
|
// try {
|
|
// const { parseMongoTarget, isQaMongoTargetHosts } = await import(tmp);
|
|
// // Replay the exact LCG + token table above for seed 0x7e28 / 0x28e7 (30_000 iterations)
|
|
// // or seed 20261127 (3_000 iterations). Classify each URI as:
|
|
// // 1 = Qa (parseMongoTarget succeeds && hosts.length > 0 && isQaMongoTargetHosts(t))
|
|
// // 2 = NotQa (parseMongoTarget succeeds && hosts.length > 0 && !isQaMongoTargetHosts(t))
|
|
// // 3 = Rejected (parseMongoTarget throws or hosts.length === 0)
|
|
// // Hash the ordered outcome bytes with FNV-1a64 (offset 0xcbf29ce484222325n, prime 0x100000001b3n).
|
|
// // To print the first differing URI on a future mismatch, write `<idx>\t<outcome>\t<JSON.stringify(uri)>`
|
|
// // from both this script and a temporary println! in this test loop, then run `diff -u` or scan for the first line diff.
|
|
// } finally { unlinkSync(tmp); }
|
|
// '
|
|
struct FuzzParitySpec {
|
|
seed: u32,
|
|
// Direct Rust parse_mongo_target + is_qa_mongo_target
|
|
rust_qa: usize,
|
|
rust_not_qa: usize,
|
|
rust_rejected: usize,
|
|
rust_hash: u64,
|
|
// Independent TypeScript env-safety.ts reference (all 30,000 cases)
|
|
ts_qa: usize,
|
|
ts_not_qa: usize,
|
|
ts_rejected: usize,
|
|
ts_hash: u64,
|
|
// Documented intentional stricter-than-TS difference counts
|
|
diff_total: usize,
|
|
diff_ws: usize,
|
|
diff_remainder_at: usize,
|
|
diff_invalid_bracketed_ipv6: usize,
|
|
// assert_read_only_mongo_uri (all 30,000 cases)
|
|
ro_accepted: usize,
|
|
ro_rejected: usize,
|
|
ro_hash: u64,
|
|
}
|
|
let fuzz_specs = [
|
|
FuzzParitySpec {
|
|
seed: 0x7e28,
|
|
rust_qa: 886,
|
|
rust_not_qa: 2093,
|
|
rust_rejected: 27021,
|
|
rust_hash: 0xca8b_51fb_09b0_0a54,
|
|
ts_qa: 924,
|
|
ts_not_qa: 2201,
|
|
ts_rejected: 26875,
|
|
ts_hash: 0x3016_07f9_04a5_278a,
|
|
diff_total: 146,
|
|
diff_ws: 85,
|
|
diff_remainder_at: 54,
|
|
diff_invalid_bracketed_ipv6: 9,
|
|
ro_accepted: 1861,
|
|
ro_rejected: 28139,
|
|
ro_hash: 0x0e79_7c66_e47f_7a08,
|
|
},
|
|
FuzzParitySpec {
|
|
seed: 0x28e7,
|
|
rust_qa: 873,
|
|
rust_not_qa: 2049,
|
|
rust_rejected: 27078,
|
|
rust_hash: 0xdfd6_7d8d_36a8_ce4e,
|
|
ts_qa: 916,
|
|
ts_not_qa: 2161,
|
|
ts_rejected: 26923,
|
|
ts_hash: 0x7067_39bb_7273_326c,
|
|
diff_total: 155,
|
|
diff_ws: 109,
|
|
diff_remainder_at: 44,
|
|
diff_invalid_bracketed_ipv6: 6,
|
|
ro_accepted: 1775,
|
|
ro_rejected: 28225,
|
|
ro_hash: 0x17fc_8004_407c_98d8,
|
|
},
|
|
];
|
|
|
|
for spec in &fuzz_specs {
|
|
let mut state = spec.seed;
|
|
let mut next = || -> f64 {
|
|
state = state.wrapping_mul(1103515245).wrapping_add(12345) & 0x7fff_ffff;
|
|
(state as f64) / (0x8000_0000u32 as f64)
|
|
};
|
|
let mut rust_qa = 0usize;
|
|
let mut rust_not_qa = 0usize;
|
|
let mut rust_rejected = 0usize;
|
|
let mut rust_hash = FNV_OFFSET;
|
|
|
|
let mut ts_qa = 0usize;
|
|
let mut ts_not_qa = 0usize;
|
|
let mut ts_rejected = 0usize;
|
|
let mut ts_equiv_hash = FNV_OFFSET;
|
|
|
|
let mut diff_total = 0usize;
|
|
let mut diff_ws = 0usize;
|
|
let mut diff_remainder_at = 0usize;
|
|
let mut diff_invalid_bracketed_ipv6 = 0usize;
|
|
|
|
let mut ro_accepted = 0usize;
|
|
let mut ro_rejected = 0usize;
|
|
let mut ro_hash = FNV_OFFSET;
|
|
|
|
for _ in 0..30_000 {
|
|
let length = 1 + ((next() * 8.0) as usize).min(7);
|
|
let mut body = String::new();
|
|
for _ in 0..length {
|
|
let idx =
|
|
((next() * (fuzz_tokens.len() as f64)) as usize).min(fuzz_tokens.len() - 1);
|
|
body.push_str(fuzz_tokens[idx]);
|
|
}
|
|
let prefix = if next() < 0.85 {
|
|
"mongodb://"
|
|
} else {
|
|
"mongodb+srv://"
|
|
};
|
|
let uri = format!("{prefix}{body}");
|
|
|
|
let (r, err) = classify_rust(&uri);
|
|
match r {
|
|
OUTCOME_QA => rust_qa += 1,
|
|
OUTCOME_NOT_QA => rust_not_qa += 1,
|
|
OUTCOME_REJECTED => rust_rejected += 1,
|
|
_ => unreachable!(),
|
|
}
|
|
rust_hash = fnv1a_update(rust_hash, r);
|
|
|
|
// Fold only the three documented intentional stricter-than-TS parser rules
|
|
// back to TS's permissive behavior to prove 1-to-1 parity with the
|
|
// independent env-safety.ts reference across all 30,000 cases.
|
|
let mut candidate = uri.clone();
|
|
let mut used_ws = false;
|
|
let mut used_at = false;
|
|
let mut used_ipv6 = false;
|
|
if matches!(err, Some(MongoSafetyError::ForbiddenWhitespace))
|
|
&& candidate != candidate.trim()
|
|
{
|
|
candidate = candidate.trim().to_owned();
|
|
used_ws = true;
|
|
}
|
|
let (mut ts_equiv, mut cur_err) = if used_ws {
|
|
classify_rust(&candidate)
|
|
} else {
|
|
(r, err.clone())
|
|
};
|
|
if matches!(
|
|
cur_err,
|
|
Some(MongoSafetyError::UnencodedAtInRemainderWithoutCredentials)
|
|
) {
|
|
if let Some((sch, rest)) = candidate.split_once("://") {
|
|
candidate = format!("{sch}://u:p@{rest}");
|
|
used_at = true;
|
|
(ts_equiv, cur_err) = classify_rust(&candidate);
|
|
}
|
|
}
|
|
if matches!(cur_err, Some(MongoSafetyError::NoValidHosts)) {
|
|
if let Some((sch, rest)) = candidate.split_once("://") {
|
|
let split_at = rest.find(['/', '?']).unwrap_or(rest.len());
|
|
let (auth, rem) = rest.split_at(split_at);
|
|
let (userinfo_prefix, host_list) = match auth.find('@') {
|
|
Some(idx) => (&auth[..=idx], &auth[idx + 1..]),
|
|
None => ("", auth),
|
|
};
|
|
let mut changed = false;
|
|
let rewritten_hosts: Vec<String> = host_list
|
|
.split(',')
|
|
.map(|seg| {
|
|
let t = seg.trim();
|
|
if let Some(after_open) = t.strip_prefix('[') {
|
|
if let Some(close_rel) = after_open.find(']') {
|
|
let raw_host = after_open[..close_rel].trim();
|
|
let after = after_open[close_rel + 1..].trim();
|
|
let decoded_ok = decode_mongo_host(raw_host, true, false).is_ok();
|
|
if close_rel > 0
|
|
&& !raw_host.is_empty()
|
|
&& (after.is_empty() || after.starts_with(':'))
|
|
&& decoded_ok
|
|
{
|
|
changed = true;
|
|
let lower =
|
|
raw_host.trim_end_matches('.').to_ascii_lowercase();
|
|
let repl = if lower == "localhost" || lower == "127.0.0.1" {
|
|
"localhost"
|
|
} else {
|
|
"nonqa"
|
|
};
|
|
return format!("{repl}{after}");
|
|
}
|
|
}
|
|
}
|
|
seg.to_owned()
|
|
})
|
|
.collect();
|
|
if changed {
|
|
let rewritten =
|
|
format!("{sch}://{userinfo_prefix}{}{rem}", rewritten_hosts.join(","));
|
|
let (rew_r, _) = classify_rust(&rewritten);
|
|
if rew_r != OUTCOME_REJECTED {
|
|
used_ipv6 = true;
|
|
ts_equiv = rew_r;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
if ts_equiv != r {
|
|
assert_eq!(
|
|
r, OUTCOME_REJECTED,
|
|
"Rust may only differ from TS by failing closed (Rejected), never more permissively: {uri:?}"
|
|
);
|
|
diff_total += 1;
|
|
if used_ws {
|
|
diff_ws += 1;
|
|
}
|
|
if used_at {
|
|
diff_remainder_at += 1;
|
|
}
|
|
if used_ipv6 {
|
|
diff_invalid_bracketed_ipv6 += 1;
|
|
}
|
|
}
|
|
match ts_equiv {
|
|
OUTCOME_QA => ts_qa += 1,
|
|
OUTCOME_NOT_QA => ts_not_qa += 1,
|
|
OUTCOME_REJECTED => ts_rejected += 1,
|
|
_ => unreachable!(),
|
|
}
|
|
ts_equiv_hash = fnv1a_update(ts_equiv_hash, ts_equiv);
|
|
|
|
match assert_read_only_mongo_uri(&uri, &policy, &local_hosts) {
|
|
Ok(validated) => {
|
|
ro_accepted += 1;
|
|
ro_hash = fnv1a_update(ro_hash, 1);
|
|
// None of the fuzz tokens contain studio_stock_bot_read, so no accepted URI
|
|
// can ever be a QA target (neither under Rust nor under TS classification).
|
|
assert!(
|
|
!validated.is_qa_target(),
|
|
"fuzz corpus URI accepted as QA without allowlisted user: {uri:?}"
|
|
);
|
|
assert_eq!(
|
|
ts_equiv, OUTCOME_NOT_QA,
|
|
"read-only guard must never accept a URI that TS classifies as Qa/Rejected: {uri:?}"
|
|
);
|
|
}
|
|
Err(_) => {
|
|
ro_rejected += 1;
|
|
ro_hash = fnv1a_update(ro_hash, 2);
|
|
}
|
|
}
|
|
}
|
|
|
|
assert_eq!(rust_qa, spec.rust_qa, "seed 0x{:x} rust_qa", spec.seed);
|
|
assert_eq!(
|
|
rust_not_qa, spec.rust_not_qa,
|
|
"seed 0x{:x} rust_not_qa",
|
|
spec.seed
|
|
);
|
|
assert_eq!(
|
|
rust_rejected, spec.rust_rejected,
|
|
"seed 0x{:x} rust_rejected",
|
|
spec.seed
|
|
);
|
|
assert_eq!(
|
|
rust_hash, spec.rust_hash,
|
|
"seed 0x{:x} rust_hash",
|
|
spec.seed
|
|
);
|
|
|
|
assert_eq!(ts_qa, spec.ts_qa, "seed 0x{:x} ts_qa", spec.seed);
|
|
assert_eq!(ts_not_qa, spec.ts_not_qa, "seed 0x{:x} ts_not_qa", spec.seed);
|
|
assert_eq!(
|
|
ts_rejected, spec.ts_rejected,
|
|
"seed 0x{:x} ts_rejected",
|
|
spec.seed
|
|
);
|
|
assert_eq!(
|
|
ts_equiv_hash, spec.ts_hash,
|
|
"seed 0x{:x} ts_equiv_hash must match independent env-safety.ts reference",
|
|
spec.seed
|
|
);
|
|
|
|
assert_eq!(diff_total, spec.diff_total, "seed 0x{:x} diff_total", spec.seed);
|
|
assert_eq!(diff_ws, spec.diff_ws, "seed 0x{:x} diff_ws", spec.seed);
|
|
assert_eq!(
|
|
diff_remainder_at, spec.diff_remainder_at,
|
|
"seed 0x{:x} diff_remainder_at",
|
|
spec.seed
|
|
);
|
|
assert_eq!(
|
|
diff_invalid_bracketed_ipv6, spec.diff_invalid_bracketed_ipv6,
|
|
"seed 0x{:x} diff_invalid_bracketed_ipv6",
|
|
spec.seed
|
|
);
|
|
|
|
assert_eq!(
|
|
ro_accepted, spec.ro_accepted,
|
|
"seed 0x{:x} ro_accepted",
|
|
spec.seed
|
|
);
|
|
assert_eq!(
|
|
ro_rejected, spec.ro_rejected,
|
|
"seed 0x{:x} ro_rejected",
|
|
spec.seed
|
|
);
|
|
assert_eq!(ro_hash, spec.ro_hash, "seed 0x{:x} ro_hash", spec.seed);
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn local_hosts_builders_and_detect_parse_hostnames_and_ips_offline() {
|
|
let hosts = LocalHosts::from_hostname_and_ips(
|
|
Some(" Quant-Box.Home.LAN.. "),
|
|
["10.0.0.51", "[fe80::1%eth0]", " 192.168.10.20 "],
|
|
)
|
|
.with_host("EXTRA.LOCAL.");
|
|
|
|
assert!(hosts.contains("quant-box.home.lan"));
|
|
assert!(hosts.contains("quant-box"));
|
|
assert!(hosts.contains("quant-box.local"));
|
|
assert!(hosts.contains("10.0.0.51"));
|
|
assert!(hosts.contains("fe80::1"));
|
|
assert!(hosts.contains("fe80::1%eth0"));
|
|
assert!(hosts.contains("192.168.10.20"));
|
|
assert!(hosts.contains("extra.local"));
|
|
assert!(!hosts.contains("other-host"));
|
|
|
|
let detected = LocalHosts::detect_from_sources(
|
|
Some("worker-01.corp.internal"),
|
|
Some("\n# comment-not-empty\n"),
|
|
);
|
|
assert!(detected.contains("worker-01.corp.internal"));
|
|
assert!(detected.contains("worker-01"));
|
|
assert!(detected.contains("worker-01.local"));
|
|
|
|
let from_etc = LocalHosts::detect_from_sources(None, Some(" studio-host.lan\n"));
|
|
assert!(from_etc.contains("studio-host.lan"));
|
|
assert!(from_etc.contains("studio-host"));
|
|
assert!(from_etc.contains("studio-host.local"));
|
|
|
|
// Best-effort detect() must never panic in any environment.
|
|
let _ = LocalHosts::detect();
|
|
}
|
|
|
|
#[test]
|
|
fn numeric_ipv4_port_scheme_unix_socket_and_encoding_edge_cases() {
|
|
let local_hosts = LocalHosts::empty();
|
|
let policy = ReadOnlyPolicy::default();
|
|
|
|
// Numeric IPv4 / IPv6 host edge cases on port 27017.
|
|
let host_cases: &[(&str, &str, ExpectedTargetOutcome)] = &[
|
|
("zero_short_ipv4", "mongodb://u:p@0:27017/stock", ExpectedTargetOutcome::Qa),
|
|
("hex_empty_ipv4", "mongodb://u:p@0x:27017/stock", ExpectedTargetOutcome::Qa),
|
|
("hex_short_loopback", "mongodb://u:p@0x7f.1:27017/stock", ExpectedTargetOutcome::Qa),
|
|
("three_part_loopback", "mongodb://u:p@127.0.1:27017/stock", ExpectedTargetOutcome::Qa),
|
|
("ipv6_unspecified", "mongodb://u:p@[::]:27017/stock", ExpectedTargetOutcome::Qa),
|
|
(
|
|
"ipv6_ipv4_compatible_not_mapped",
|
|
"mongodb://u:p@[::127.0.0.1]:27017/stock",
|
|
ExpectedTargetOutcome::NotQa,
|
|
),
|
|
(
|
|
"out_of_range_octet_first",
|
|
"mongodb://u:p@256.0.0.1:27017/stock",
|
|
ExpectedTargetOutcome::NotQa,
|
|
),
|
|
(
|
|
"out_of_range_octet_last",
|
|
"mongodb://u:p@127.0.0.256:27017/stock",
|
|
ExpectedTargetOutcome::NotQa,
|
|
),
|
|
(
|
|
"out_of_range_decimal_u32",
|
|
"mongodb://u:p@4294967296:27017/stock",
|
|
ExpectedTargetOutcome::NotQa,
|
|
),
|
|
(
|
|
"out_of_range_hex_u32",
|
|
"mongodb://u:p@0x100000000:27017/stock",
|
|
ExpectedTargetOutcome::NotQa,
|
|
),
|
|
(
|
|
"out_of_range_octal_last",
|
|
"mongodb://u:p@0177.0.0.256:27017/stock",
|
|
ExpectedTargetOutcome::NotQa,
|
|
),
|
|
(
|
|
"out_of_range_three_part_last",
|
|
"mongodb://u:p@127.0.65536:27017/stock",
|
|
ExpectedTargetOutcome::NotQa,
|
|
),
|
|
// Leading-zero port 27017 still resolves to QA port 27017.
|
|
(
|
|
"leading_zero_port_27017",
|
|
"mongodb://u:p@localhost:0000027017/stock",
|
|
ExpectedTargetOutcome::Qa,
|
|
),
|
|
// Uppercase schemes.
|
|
(
|
|
"uppercase_mongodb_qa",
|
|
"MONGODB://studio_stock_bot_read:pw@localhost:27017/stock",
|
|
ExpectedTargetOutcome::Qa,
|
|
),
|
|
(
|
|
"uppercase_mongodb_srv_remote",
|
|
"MONGODB+SRV://u:p@cluster.example.com/stock",
|
|
ExpectedTargetOutcome::NotQa,
|
|
),
|
|
(
|
|
"uppercase_mongodb_srv_qa",
|
|
"MONGODB+SRV://u:p@localhost/stock",
|
|
ExpectedTargetOutcome::Qa,
|
|
),
|
|
// Unix domain socket hosts are never classified as QA (same as TS).
|
|
(
|
|
"unix_socket_tmp_27017_with_creds",
|
|
"mongodb://u:p@%2Ftmp%2Fmongodb-27017.sock/stock",
|
|
ExpectedTargetOutcome::NotQa,
|
|
),
|
|
(
|
|
"unix_socket_var_run_no_creds",
|
|
"mongodb://%2Fvar%2Frun%2Fmongodb-27017.sock/stock",
|
|
ExpectedTargetOutcome::NotQa,
|
|
),
|
|
];
|
|
|
|
for &(label, uri, expected) in host_cases {
|
|
let target = parse_mongo_target(uri)
|
|
.unwrap_or_else(|e| panic!("{label}: expected parse Ok for {uri}, got {e:?}"));
|
|
let is_qa = is_qa_mongo_target(&target, &local_hosts);
|
|
match expected {
|
|
ExpectedTargetOutcome::Qa => assert!(is_qa, "{label}: expected QA for {uri}"),
|
|
ExpectedTargetOutcome::NotQa => assert!(!is_qa, "{label}: expected NotQa for {uri}"),
|
|
ExpectedTargetOutcome::Rejected => unreachable!(),
|
|
}
|
|
}
|
|
|
|
// Uppercase MONGODB:// with allowlisted QA user is accepted; unauthorized user is rejected.
|
|
let ok_upper = assert_read_only_mongo_uri(
|
|
"MONGODB://studio_stock_bot_read:pw@localhost:27017/stock",
|
|
&policy,
|
|
&local_hosts,
|
|
)
|
|
.expect("uppercase MONGODB:// with allowlisted user must pass");
|
|
assert!(ok_upper.is_qa_target());
|
|
assert_eq!(
|
|
assert_read_only_mongo_uri("MONGODB://u:p@localhost:27017/stock", &policy, &local_hosts),
|
|
Err(MongoSafetyError::UnauthorizedQaUser)
|
|
);
|
|
assert!(
|
|
assert_read_only_mongo_uri(
|
|
"MONGODB+SRV://u:p@cluster.example.com/stock",
|
|
&policy,
|
|
&local_hosts,
|
|
)
|
|
.is_ok()
|
|
);
|
|
assert!(
|
|
assert_read_only_mongo_uri(
|
|
"mongodb://u:p@%2Ftmp%2Fmongodb-27017.sock/stock",
|
|
&policy,
|
|
&local_hosts,
|
|
)
|
|
.is_ok()
|
|
);
|
|
|
|
// Exact MongoSafetyError variants for rejected port, scheme, socket, and encoding edge cases.
|
|
let rejection_cases: &[(&str, &str, MongoSafetyError)] = &[
|
|
(
|
|
"port_zero",
|
|
"mongodb://u:p@localhost:0/stock",
|
|
MongoSafetyError::NoValidHosts,
|
|
),
|
|
(
|
|
"port_65536",
|
|
"mongodb://u:p@localhost:65536/stock",
|
|
MongoSafetyError::NoValidHosts,
|
|
),
|
|
(
|
|
"port_plus_27017",
|
|
"mongodb://u:p@localhost:+27017/stock",
|
|
MongoSafetyError::NoValidHosts,
|
|
),
|
|
(
|
|
"unix_socket_on_srv_rejected",
|
|
"mongodb+srv://u:p@%2Ftmp%2Fmongodb-27017.sock/stock",
|
|
MongoSafetyError::ForbiddenHostCharacters,
|
|
),
|
|
(
|
|
"encoded_u2028_line_separator_in_host",
|
|
"mongodb://u:p@localhost%e2%80%a8:27017/stock",
|
|
MongoSafetyError::ForbiddenHostCharacters,
|
|
),
|
|
(
|
|
"invalid_utf8_percent_ff_in_host",
|
|
"mongodb://u:p@local%ffhost:27017/stock",
|
|
MongoSafetyError::InvalidHostEncoding,
|
|
),
|
|
(
|
|
"invalid_utf8_percent_ff_in_username",
|
|
"mongodb://u%ff:p@localhost:27018/stock",
|
|
MongoSafetyError::InvalidUsernameEncoding,
|
|
),
|
|
(
|
|
"invalid_utf8_percent_ff_username_remote",
|
|
"mongodb://%ff:p@mongo.internal:27017/stock",
|
|
MongoSafetyError::InvalidUsernameEncoding,
|
|
),
|
|
];
|
|
|
|
for &(label, uri, ref expected_err) in rejection_cases {
|
|
assert_eq!(
|
|
parse_mongo_target(uri),
|
|
Err(expected_err.clone()),
|
|
"{label}: parse_mongo_target mismatch for {uri}"
|
|
);
|
|
assert_eq!(
|
|
assert_read_only_mongo_uri(uri, &policy, &local_hosts),
|
|
Err(expected_err.clone()),
|
|
"{label}: assert_read_only_mongo_uri mismatch for {uri}"
|
|
);
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn conservative_local_host_matching_flags_leading_zero_lan_and_zoned_link_local() {
|
|
let local_hosts = LocalHosts::from_hostname_and_ips(
|
|
Some("quant.lan.local."),
|
|
["192.168.1.50", "fe80::1234:5678%eth0"],
|
|
);
|
|
let policy = ReadOnlyPolicy::default();
|
|
|
|
// Rust is intentionally stricter than TS here: leading-zero decimal LAN IPs and
|
|
// the machine's own zoned link-local IPv6 on port 27017 (or omitted port) are QA.
|
|
let qa_uris = [
|
|
"mongodb://u:p@quant.lan.local:27017/stock",
|
|
"mongodb://u:p@QUANT.LAN.LOCAL.:27017/stock",
|
|
"mongodb://u:p@quant:27017/stock",
|
|
"mongodb://u:p@quant.local:27017/stock",
|
|
"mongodb://u:p@192.168.1.50:27017/stock",
|
|
"mongodb://u:p@192.168.001.050:27017/stock",
|
|
"mongodb://u:p@192.168.001.050/stock",
|
|
"mongodb://u:p@0xc0a80132:27017/stock",
|
|
"mongodb://u:p@0300.0250.0001.0062:27017/stock",
|
|
"mongodb://u:p@[fe80::1234:5678%25eth0]:27017/stock",
|
|
"mongodb://u:p@[fe80::1234:5678%25en0]:27017/stock",
|
|
"mongodb://u:p@[fe80::1234:5678]:27017/stock",
|
|
"mongodb://u:p@[FE80::1234:5678%25ETH0]/stock",
|
|
];
|
|
for uri in qa_uris {
|
|
let target = parse_mongo_target(uri).expect("expected valid local host URI");
|
|
assert!(
|
|
is_qa_mongo_target(&target, &local_hosts),
|
|
"expected QA classification for local host URI: {uri}"
|
|
);
|
|
assert_eq!(
|
|
assert_read_only_mongo_uri(uri, &policy, &local_hosts),
|
|
Err(MongoSafetyError::UnauthorizedQaUser),
|
|
"expected UnauthorizedQaUser for {uri}"
|
|
);
|
|
}
|
|
|
|
let non_qa_uris = [
|
|
"mongodb://u:p@192.168.001.050:27018/stock",
|
|
"mongodb://u:p@[fe80::1234:5678%25eth0]:27018/stock",
|
|
"mongodb://u:p@192.168.001.051:27017/stock",
|
|
"mongodb://u:p@[fe80::1234:5679%25eth0]:27017/stock",
|
|
"mongodb://u:p@other.lan.local:27017/stock",
|
|
];
|
|
for uri in non_qa_uris {
|
|
let target = parse_mongo_target(uri).expect("expected valid non-QA URI");
|
|
assert!(
|
|
!is_qa_mongo_target(&target, &local_hosts),
|
|
"expected NotQa for {uri}"
|
|
);
|
|
assert!(
|
|
assert_read_only_mongo_uri(uri, &policy, &local_hosts).is_ok(),
|
|
"expected read-only acceptance for non-QA {uri}"
|
|
);
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn exact_allowlist_after_decoding_and_srv_rules() {
|
|
let local_hosts = LocalHosts::empty();
|
|
let policy = ReadOnlyPolicy::default();
|
|
|
|
// Exact match after percent-decoding succeeds.
|
|
for ok_uri in [
|
|
"mongodb://studio_stock_bot_read:pw@localhost:27017/stock",
|
|
"mongodb://studio%5fstock%5fbot%5fread:pw@localhost:27017/stock",
|
|
"mongodb://studio%5Fstock%5Fbot%5Fread:pw@127.0.0.1:27017/stock",
|
|
] {
|
|
let validated = assert_read_only_mongo_uri(ok_uri, &policy, &local_hosts)
|
|
.unwrap_or_else(|e| panic!("expected exact allowlist match for {ok_uri}, got {e:?}"));
|
|
assert!(validated.is_qa_target());
|
|
assert_eq!(
|
|
validated.target().username.as_deref(),
|
|
Some(DEFAULT_ALLOWED_READ_USER)
|
|
);
|
|
}
|
|
|
|
// No case-folding, prefix, suffix, or '+'-to-space substitution for allowlist match.
|
|
for rejected_user in [
|
|
"STUDIO_STOCK_BOT_READ",
|
|
"Studio_Stock_Bot_Read",
|
|
"studio_stock_bot_read_extra",
|
|
"studio_stock_bot_rea",
|
|
"pre_studio_stock_bot_read",
|
|
"studio+stock+bot+read",
|
|
] {
|
|
let uri = format!("mongodb://{rejected_user}:pw@localhost:27017/stock");
|
|
assert_eq!(
|
|
assert_read_only_mongo_uri(&uri, &policy, &local_hosts),
|
|
Err(MongoSafetyError::UnauthorizedQaUser),
|
|
"expected exact allowlist rejection for {uri}"
|
|
);
|
|
}
|
|
|
|
// mongodb+srv:// single-host and no-explicit-port rules.
|
|
let srv_remote = assert_read_only_mongo_uri(
|
|
"mongodb+srv://reader:pw@cluster.example.com/stock",
|
|
&policy,
|
|
&local_hosts,
|
|
)
|
|
.expect("single remote SRV host without port must pass");
|
|
assert!(!srv_remote.is_qa_target());
|
|
|
|
let srv_qa = assert_read_only_mongo_uri(
|
|
"mongodb+srv://studio_stock_bot_read:pw@localhost/stock",
|
|
&policy,
|
|
&local_hosts,
|
|
)
|
|
.expect("single QA SRV host with allowlisted user must pass");
|
|
assert!(srv_qa.is_qa_target());
|
|
|
|
assert_eq!(
|
|
assert_read_only_mongo_uri("mongodb+srv://localhost/stock", &policy, &local_hosts),
|
|
Err(MongoSafetyError::MissingCredentialsForQaTarget)
|
|
);
|
|
assert_eq!(
|
|
assert_read_only_mongo_uri(
|
|
"mongodb+srv://u:p@a.example.com,b.example.com/stock",
|
|
&policy,
|
|
&local_hosts,
|
|
),
|
|
Err(MongoSafetyError::InvalidSrvTarget)
|
|
);
|
|
assert_eq!(
|
|
assert_read_only_mongo_uri(
|
|
"mongodb+srv://u:p@a.example.com:27017/stock",
|
|
&policy,
|
|
&local_hosts,
|
|
),
|
|
Err(MongoSafetyError::InvalidSrvTarget)
|
|
);
|
|
assert_eq!(
|
|
assert_read_only_mongo_uri(
|
|
"mongodb+srv://u:p@a.example.com:/stock",
|
|
&policy,
|
|
&local_hosts,
|
|
),
|
|
Err(MongoSafetyError::InvalidSrvTarget)
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn password_redaction_covers_odd_passwords_and_boxed_dyn_error() {
|
|
let local_hosts = LocalHosts::empty();
|
|
let policy = ReadOnlyPolicy::default();
|
|
|
|
let odd_passwords = [
|
|
("with_colons", "part1:part2:part3"),
|
|
("percent_encoded_at_and_pct", "p%40ss%25word%3A99"),
|
|
("unicode_secret", "pässwörd🔒secret"),
|
|
("empty_password", ""),
|
|
];
|
|
|
|
for (label, pw) in odd_passwords {
|
|
let uri = format!("mongodb://studio_stock_bot_read:{pw}@localhost:27017/stock");
|
|
let validated = assert_read_only_mongo_uri(&uri, &policy, &local_hosts)
|
|
.unwrap_or_else(|e| panic!("{label}: expected valid URI, got {e:?}"));
|
|
|
|
let display = format!("{validated}");
|
|
let debug = format!("{validated:?}");
|
|
let redacted = validated.redacted();
|
|
|
|
assert_eq!(
|
|
redacted,
|
|
"mongodb://studio_stock_bot_read:[REDACTED]@localhost:27017/stock",
|
|
"{label}: unexpected redacted form"
|
|
);
|
|
assert_eq!(display, redacted, "{label}: Display must match redacted()");
|
|
assert!(debug.contains("[REDACTED]"), "{label}: Debug must contain [REDACTED]");
|
|
if !pw.is_empty() {
|
|
assert!(!display.contains(pw), "{label}: Display leaked password");
|
|
assert!(!debug.contains(pw), "{label}: Debug leaked password");
|
|
assert!(!redacted.contains(pw), "{label}: redacted() leaked password");
|
|
}
|
|
|
|
// Verify password never leaks through Box<dyn std::error::Error> on error paths.
|
|
let error_uris = [
|
|
(
|
|
format!("mongodb://trading_admin:{pw}@mongo.internal:27017/stock"),
|
|
MongoSafetyError::ForbiddenAdminUser,
|
|
),
|
|
(
|
|
format!("mongodb://other_user:{pw}@localhost:27017/stock"),
|
|
MongoSafetyError::UnauthorizedQaUser,
|
|
),
|
|
(
|
|
format!("mongodb://u:{pw}@localhost:27017#frag/stock"),
|
|
MongoSafetyError::UnencodedHashInAuthority,
|
|
),
|
|
(
|
|
format!("mongodb://u:{pw}@local%ffhost:27017/stock"),
|
|
MongoSafetyError::InvalidHostEncoding,
|
|
),
|
|
(
|
|
format!("mongodb://u:{pw}@/stock"),
|
|
MongoSafetyError::EmptyHostList,
|
|
),
|
|
];
|
|
for (bad_uri, expected_err) in error_uris {
|
|
let err = assert_read_only_mongo_uri(&bad_uri, &policy, &local_hosts)
|
|
.expect_err("expected error for malformed/unauthorized URI");
|
|
assert_eq!(err, expected_err, "{label}: unexpected error variant");
|
|
let boxed: Box<dyn std::error::Error> = Box::new(err);
|
|
let boxed_display = format!("{boxed}");
|
|
let boxed_debug = format!("{boxed:?}");
|
|
if !pw.is_empty() {
|
|
assert!(
|
|
!boxed_display.contains(pw),
|
|
"{label}: Box<dyn Error> Display leaked password: {boxed_display}"
|
|
);
|
|
assert!(
|
|
!boxed_debug.contains(pw),
|
|
"{label}: Box<dyn Error> Debug leaked password: {boxed_debug}"
|
|
);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn adversarial_seeded_fuzz_40k_enforces_invariants() {
|
|
let local_hosts = LocalHosts::from_hostname_and_ips(
|
|
Some("quant.lan.local."),
|
|
["192.168.1.50", "fe80::1234:5678%eth0"],
|
|
);
|
|
let policy = ReadOnlyPolicy::default();
|
|
|
|
let schemes = ["mongodb://", "mongodb+srv://", "MONGODB://", "http://"];
|
|
let userinfos = [
|
|
"",
|
|
"studio_stock_bot_read:pw@",
|
|
"studio%5fstock%5fbot%5fread:pw@",
|
|
"trading_admin:pw@",
|
|
"TrAdInG%5fAdMiN:pw@",
|
|
"other_user:pw@",
|
|
"bad%ff:pw@",
|
|
"@",
|
|
];
|
|
let hosts = [
|
|
"localhost",
|
|
"LOCALHOST.",
|
|
"%6cocalhost",
|
|
"127.0.0.1",
|
|
"127.1",
|
|
"2130706433",
|
|
"0x7f000001",
|
|
"0177.0.0.1",
|
|
"0127.0.0.1",
|
|
"[::1]",
|
|
"[::ffff:127.0.0.1]",
|
|
"quant.lan.local.",
|
|
"192.168.1.50",
|
|
"192.168.001.050",
|
|
"[fe80::1234:5678%25eth0]",
|
|
"mongo.internal",
|
|
"[fe80::g]",
|
|
"%2Ftmp%2Fmongodb-27017.sock",
|
|
"local%ffhost",
|
|
"localhost%e2%80%a8",
|
|
];
|
|
let ports = ["", ":27017", ":27018", ":0", ":65536", ":027017"];
|
|
let tails = [
|
|
"/stock",
|
|
"/stock_dev?replicaSet=rs0",
|
|
"/stock?user=a@b",
|
|
"#frag/stock",
|
|
"",
|
|
];
|
|
let prefixes = ["", " ", "\t"];
|
|
|
|
let mut state: u32 = 0x51a7e;
|
|
let mut next_idx = |len: usize| -> usize {
|
|
state = state.wrapping_mul(1103515245).wrapping_add(12345) & 0x7fff_ffff;
|
|
(state as usize) % len
|
|
};
|
|
|
|
let mut parsed_qa = 0usize;
|
|
let mut parsed_not_qa = 0usize;
|
|
let mut parsed_rejected = 0usize;
|
|
let mut accepted_total = 0usize;
|
|
let mut accepted_qa = 0usize;
|
|
let mut accepted_non_qa = 0usize;
|
|
|
|
for _ in 0..40_000 {
|
|
let prefix = if next_idx(12) == 0 {
|
|
prefixes[next_idx(prefixes.len())]
|
|
} else {
|
|
""
|
|
};
|
|
let scheme = schemes[next_idx(schemes.len())];
|
|
let userinfo = userinfos[next_idx(userinfos.len())];
|
|
let h1 = hosts[next_idx(hosts.len())];
|
|
let p1 = ports[next_idx(ports.len())];
|
|
let seed_list = if next_idx(4) == 0 {
|
|
let h2 = hosts[next_idx(hosts.len())];
|
|
let p2 = ports[next_idx(ports.len())];
|
|
format!("{h1}{p1},{h2}{p2}")
|
|
} else {
|
|
format!("{h1}{p1}")
|
|
};
|
|
let tail = tails[next_idx(tails.len())];
|
|
let uri = format!("{prefix}{scheme}{userinfo}{seed_list}{tail}");
|
|
|
|
match parse_mongo_target(&uri) {
|
|
Ok(target) => {
|
|
if is_qa_mongo_target(&target, &local_hosts) {
|
|
parsed_qa += 1;
|
|
} else {
|
|
parsed_not_qa += 1;
|
|
}
|
|
}
|
|
Err(_) => parsed_rejected += 1,
|
|
}
|
|
|
|
if let Ok(validated) = assert_read_only_mongo_uri(&uri, &policy, &local_hosts) {
|
|
accepted_total += 1;
|
|
if let Some(user) = validated.target().username.as_deref() {
|
|
assert!(
|
|
!user.eq_ignore_ascii_case(FORBIDDEN_ADMIN_USER),
|
|
"fuzz accepted forbidden admin user: {uri:?}"
|
|
);
|
|
}
|
|
if validated.is_qa_target() {
|
|
accepted_qa += 1;
|
|
let user = validated
|
|
.target()
|
|
.username
|
|
.as_deref()
|
|
.expect("accepted QA token must carry a username");
|
|
assert!(
|
|
policy.allowed_read_users.iter().any(|allowed| allowed == user),
|
|
"fuzz accepted QA token with non-allowlisted user {user:?}: {uri:?}"
|
|
);
|
|
} else {
|
|
accepted_non_qa += 1;
|
|
}
|
|
}
|
|
}
|
|
|
|
assert_eq!(parsed_qa + parsed_not_qa + parsed_rejected, 40_000);
|
|
assert_eq!(accepted_qa + accepted_non_qa, accepted_total);
|
|
// Pinned Rust counts for seed 0x51a7e (40,000 adversarial URIs).
|
|
// Independent Bun cross-check against apps/stock/config/src/env-safety.ts on the same
|
|
// 40,000 URIs produced tsQa = 10_125, tsNotQa = 7_349, tsRejected = 22_526; Rust is
|
|
// strictly more conservative (more QA flags via leading-zero LAN / zoned link-local,
|
|
// more rejections via bad %ff usernames, leading whitespace, remainder '@', [fe80::g]).
|
|
assert_eq!(parsed_qa, 10_439);
|
|
assert_eq!(parsed_not_qa, 5_437);
|
|
assert_eq!(parsed_rejected, 24_124);
|
|
assert_eq!(accepted_total, 3_393);
|
|
assert_eq!(accepted_qa, 2_518);
|
|
assert_eq!(accepted_non_qa, 875);
|
|
}
|