T-125: M1.2ak — tools/curate-etl: pure read-only MongoDB URI safety guard (mongo_safety.rs, parity with env-safety.ts QA-target rules, blocks trading_admin) with offline tests (no new crates, no MongoDB connection)
This commit is contained in:
parent
a1690717c8
commit
88b7a5d141
2 changed files with 564 additions and 3 deletions
|
|
@ -1505,17 +1505,20 @@ Pure, offline, `std`-only MongoDB URI safety guard (`src/mongo_safety.rs`, zero
|
|||
- `assert_read_only_mongo_uri(uri, policy: &ReadOnlyPolicy, local_hosts) -> Result<ValidatedReadOnlyMongoUri, MongoSafetyError>` — fail-closed guard returning a `ValidatedReadOnlyMongoUri` proof token whose fields are private and whose only public constructor is `assert_read_only_mongo_uri`.
|
||||
- **Password redaction:** `ValidatedReadOnlyMongoUri`'s `Display`, `Debug`, and `redacted()` always replace the password between the first `:` and `@` in userinfo with `[REDACTED]`. `MongoSafetyError` variants never store raw URIs, raw authorities, or passwords.
|
||||
- **No URI query-option parsing:** beyond authority/remainder splitting and the no-credentials remainder-`@` check, URI query options are intentionally not parsed or validated (matching `apps/stock/config/src/env-safety.ts`).
|
||||
- **Unix domain sockets:** `.sock` Unix-socket hosts (e.g. `%2Ftmp%2Fmongodb-27017.sock`) are never classified as QA targets (same as `env-safety.ts`).
|
||||
|
||||
### Intentional Stricter-than-`env-safety.ts` Differences
|
||||
|
||||
Target classification (`parse_mongo_target` + `is_qa_mongo_target`) mirrors all five `test/unit/environment-safety*.test.ts` suites (including the 42-case `hostSpellings × ports` matrix, the 3,000-iteration seeded percent-encoding sweep, and all 30,000 cases per authority-split fuzz seed `0x7e28` / `0x28e7`) with identical QA / not-QA / rejected outcomes. `parse_mongo_target` and `assert_read_only_mongo_uri` are deliberately stricter than `env-safety.ts` in six ways for read-only ETL safety:
|
||||
Target classification (`parse_mongo_target` + `is_qa_mongo_target`) mirrors all five `test/unit/environment-safety*.test.ts` suites (including the 42-case `hostSpellings × ports` matrix, the 3,000-iteration seeded percent-encoding sweep, and all 30,000 cases per authority-split fuzz seed `0x7e28` / `0x28e7`) with identical QA / not-QA / rejected outcomes **except for the intentional stricter rules listed below**. `parse_mongo_target`, `is_qa_mongo_target`, and `assert_read_only_mongo_uri` are deliberately stricter than `env-safety.ts` in eight ways for read-only ETL safety:
|
||||
|
||||
1. **Global case-insensitive `trading_admin` ban:** rejects percent-decoded `trading_admin` (ASCII case-insensitive) on **any** host (QA, dev, or remote), even if a caller adds it to `ReadOnlyPolicy::allowed_read_users` (whereas `env-safety.ts` only checks `username === 'trading_admin'` on QA targets for dev `dataPipeline`).
|
||||
2. **Mandatory QA credentials & allowlist:** any QA target must provide a username present in `ReadOnlyPolicy::allowed_read_users` (default: `["studio_stock_bot_read"]`); missing credentials and non-allowlisted users are rejected.
|
||||
2. **Mandatory QA credentials & allowlist:** any QA target must provide a username present in `ReadOnlyPolicy::allowed_read_users` (default: `["studio_stock_bot_read"]`, exact match after percent-decoding); missing credentials and non-allowlisted users are rejected.
|
||||
3. **Rejection of empty, malformed, or invalid bracketed-IPv6 host segments:** URIs like `mongodb://u:p@bad:port,localhost:27017/stock`, `mongodb://u:p@localhost:27018,,localhost:27017/stock`, or `mongodb://u:p@[fe80::g]:27017,localhost:27017/stock` still classify as QA in `parse_mongo_target` / `is_qa_mongo_target` (matching `env-safety.ts`), and are rejected fail-closed with `MalformedHostSegment` by `assert_read_only_mongo_uri` (matching `libs/core/config/src/schemas/database.schema.ts`). Single-seed malformed bracketed IPv6 literals such as `[fe80::g]:27017` are rejected with `NoValidHosts`.
|
||||
4. **Strict `mongodb+srv://` seed rules:** `assert_read_only_mongo_uri` rejects `mongodb+srv://` URIs with multiple hosts or any explicit `:` port suffix (`InvalidSrvTarget`), matching `database.schema.ts`.
|
||||
5. **No-credentials remainder-`@` check and strict username percent-decoding:** rejects unencoded `@` in path/query when authority has no `@` (matching `database.schema.ts`) and rejects malformed percent-encoding in the username (failing closed instead of falling back to the raw username string).
|
||||
5. **No-credentials remainder-`@` check and strict username percent-decoding:** rejects unencoded `@` in path/query when authority has no `@` (matching `database.schema.ts`), and rejects invalid percent-encoding in the username (e.g. `%ff`, failing closed with `InvalidUsernameEncoding` instead of falling back to the raw username string).
|
||||
6. **No silent trimming of leading/trailing whitespace:** `env-safety.ts` calls `uri.trim()` before checking `/\s/`, whereas `parse_mongo_target` rejects any Unicode whitespace anywhere in the URI (including leading or trailing spaces) with `ForbiddenWhitespace`.
|
||||
7. **Leading-zero decimal LAN IPs matched against `LocalHosts`:** `is_qa_mongo_target` normalizes 4-part decimal IPv4 spellings with leading zeros (e.g. `192.168.001.050:27017`) before checking `LocalHosts`, flagging them as QA even where `env-safety.ts` does not.
|
||||
8. **Machine's own zoned link-local IPv6 matched against `LocalHosts`:** `is_qa_mongo_target` strips `%zone` suffixes when matching bracketed IPv6 hosts against `LocalHosts` (e.g. `[fe80::1234:5678%25eth0]:27017`), flagging the machine's own link-local IPv6 on port `27017` as QA even where `env-safety.ts` misses it.
|
||||
|
||||
## Exporting Input Files (`data-pipeline`)
|
||||
|
||||
|
|
|
|||
|
|
@ -1696,6 +1696,29 @@ fn deterministic_generated_parity_sweeps_match_ts_suites() {
|
|||
"%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
|
||||
|
|
@ -2020,3 +2043,538 @@ fn local_hosts_builders_and_detect_parse_hostnames_and_ips_offline() {
|
|||
// 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);
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue