T-126: M1.2al — tools/curate-etl: sealed read-only MongoDB raw-BSON cursor adapter (mongo_stream.rs: ValidatedReadOnlyMongoUri → allowlisted find → impl io::Read feeding the existing bson_stream decoders) with offline tests and local benchmark (adds the mongodb crate only; no live MongoDB in tests)
This commit is contained in:
parent
be144d874a
commit
76fc415db4
3 changed files with 148 additions and 87 deletions
|
|
@ -1531,7 +1531,7 @@ Library-only, driver-independent read-only MongoDB raw-BSON cursor seam (`src/mo
|
|||
### Public API & Sealing Guarantees
|
||||
|
||||
- **Closed collection allowlist (`SourceCollection`):** 8 variants matching `RAW_BSON_EXPORT_COLLECTIONS` in `apps/stock/data-pipeline/src/security-master/export-raw-bson.ts` in exact order (`eodPrices`, `qmSplits`, `qmDividends`, `qmPrices`, `teMarketData`, `ceoShorts`, `qmFilings`, `qmEarnings`). No API accepts a free-form collection name string.
|
||||
- **Typed read spec (`MongoReadSpec`, `MongoDateRange`, `FilterDateValue`, `build_filter_document`):** validates `batch_size` (`1..=100_000`, default `4_096`), `limit` (`1..=i64::MAX`), `max_doc_bytes` (`>= 5`, default `16 MiB + 16 KiB`), non-blank `key_eq`, and half-open `[gte, lt)` `date_range` (rejected on `teMarketData`; `qmFilings.timefiled` bounds require Eastern Time `YYYY-MM-DDTHH:MM:SS EST|EDT` strings validated via `parse_filing_timefiled` so UTC bounds cannot silently miss late-evening ET filings), building `bson::Document` via `Document::from_iter(...)`.
|
||||
- **Typed read spec (`MongoReadSpec`, `MongoDateRange`, `FilterDateValue`, `build_filter_document`):** validates `batch_size` (`1..=100_000`, default `4_096`), `limit` (`1..=i64::MAX`), `max_doc_bytes` (`>= 5`, default `16 MiB + 16 KiB`), non-blank `key_eq`, and half-open `[gte, lt)` `date_range` (rejected on `teMarketData`; `qmFilings.timefiled` server-side string ranges require Eastern calendar-day boundaries `YYYY-MM-DD` so neither UTC offsets nor fall-back DST local-string inversions can silently miss filings), building `bson::Document` via `Document::from_iter(...)`.
|
||||
- **Driver-independent seam (`RawDocumentSource`, `SliceRawDocumentSource`, `VecRawDocumentSource`) + bounded-memory `io::Read` adapter (`RawBsonCursorReader<S>`):** validates every raw BSON frame (`len >= 5`, `len <= max_doc_bytes`, 4-byte LE length prefix `== len`, trailing `0x00`), copies directly into the caller's buffer when it fits, spills only the unread tail of a single current document into a reused `pending` buffer, tracks `docs_read()` / `bytes_read()` / `pending_capacity()`, and surfaces mid-stream errors as sticky `io::Error`s carrying `MongoStreamError`.
|
||||
- **Error redaction (`MongoStreamError`, `MongoStreamError::redacted_source`):** never stores raw URIs or passwords; sanitizes raw URI, raw password, percent-decoded password, and embedded `mongodb://` / `mongodb+srv://` userinfo passwords (including passwords containing punctuation such as `,`, `;`, quotes, brackets, or `@`) to `[REDACTED]` (reusing `mongo_safety::redact_mongo_uri_password`).
|
||||
|
||||
|
|
|
|||
|
|
@ -215,61 +215,39 @@ impl MongoReadSpec {
|
|||
}
|
||||
}
|
||||
if collection == SourceCollection::QmFilings {
|
||||
let gte_parsed = match &range.gte {
|
||||
Some(FilterDateValue::IsoString(s)) => {
|
||||
Some(parse_filing_timefiled(s).map_err(|err| {
|
||||
MongoStreamError::InvalidDateRange {
|
||||
collection,
|
||||
detail: format!(
|
||||
"qmFilings.timefiled gte must be an Eastern Time timestamp \
|
||||
(YYYY-MM-DDTHH:MM:SS EST|EDT): {err}"
|
||||
),
|
||||
let validate_et_calendar_day =
|
||||
|bound: Option<&FilterDateValue>, label: &str| match bound {
|
||||
Some(FilterDateValue::IsoString(s)) => {
|
||||
let is_calendar_day = s.len() == 10
|
||||
&& s.is_ascii()
|
||||
&& parse_filing_timefiled(&format!("{s}T00:00:00 EST")).is_ok();
|
||||
if !is_calendar_day {
|
||||
return Err(MongoStreamError::InvalidDateRange {
|
||||
collection,
|
||||
detail: format!(
|
||||
"qmFilings.timefiled {label} must be an Eastern \
|
||||
calendar-day boundary (YYYY-MM-DD); intra-day local \
|
||||
timestamps are not monotonic across the fall-back DST \
|
||||
transition and UTC strings do not match stored Eastern \
|
||||
Time strings"
|
||||
),
|
||||
});
|
||||
}
|
||||
})?)
|
||||
}
|
||||
Some(FilterDateValue::BsonDateTimeMillis(_)) => {
|
||||
return Err(MongoStreamError::InvalidDateRange {
|
||||
collection,
|
||||
detail: "qmFilings.timefiled is stored as an Eastern Time string \
|
||||
(YYYY-MM-DDTHH:MM:SS EST|EDT); BsonDateTimeMillis bounds \
|
||||
are not supported"
|
||||
.to_owned(),
|
||||
});
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let lt_parsed = match &range.lt {
|
||||
Some(FilterDateValue::IsoString(s)) => {
|
||||
Some(parse_filing_timefiled(s).map_err(|err| {
|
||||
MongoStreamError::InvalidDateRange {
|
||||
Ok(())
|
||||
}
|
||||
Some(FilterDateValue::BsonDateTimeMillis(_)) => {
|
||||
Err(MongoStreamError::InvalidDateRange {
|
||||
collection,
|
||||
detail: format!(
|
||||
"qmFilings.timefiled lt must be an Eastern Time timestamp \
|
||||
(YYYY-MM-DDTHH:MM:SS EST|EDT): {err}"
|
||||
),
|
||||
}
|
||||
})?)
|
||||
}
|
||||
Some(FilterDateValue::BsonDateTimeMillis(_)) => {
|
||||
return Err(MongoStreamError::InvalidDateRange {
|
||||
collection,
|
||||
detail: "qmFilings.timefiled is stored as an Eastern Time string \
|
||||
(YYYY-MM-DDTHH:MM:SS EST|EDT); BsonDateTimeMillis bounds \
|
||||
are not supported"
|
||||
.to_owned(),
|
||||
});
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
if let (Some(a), Some(b)) = (gte_parsed, lt_parsed) {
|
||||
if a.utc_micros >= b.utc_micros {
|
||||
return Err(MongoStreamError::InvalidDateRange {
|
||||
collection,
|
||||
detail: "qmFilings.timefiled gte must precede lt in UTC time"
|
||||
.to_owned(),
|
||||
});
|
||||
}
|
||||
}
|
||||
detail: "qmFilings.timefiled is stored as an Eastern Time string; \
|
||||
only Eastern calendar-day boundaries (YYYY-MM-DD) are \
|
||||
supported for server-side ranges"
|
||||
.to_owned(),
|
||||
})
|
||||
}
|
||||
None => Ok(()),
|
||||
};
|
||||
validate_et_calendar_day(range.gte.as_ref(), "gte")?;
|
||||
validate_et_calendar_day(range.lt.as_ref(), "lt")?;
|
||||
}
|
||||
if let (Some(gte), Some(lt)) = (&range.gte, &range.lt) {
|
||||
match (gte, lt) {
|
||||
|
|
@ -732,24 +710,28 @@ fn hex_nibble(b: u8) -> Option<u8> {
|
|||
}
|
||||
}
|
||||
|
||||
fn find_next_mongo_scheme(lower_slice: &str) -> Option<(usize, usize)> {
|
||||
let next_std = lower_slice
|
||||
.find("mongodb://")
|
||||
.map(|i| (i, "mongodb://".len()));
|
||||
let next_srv = lower_slice
|
||||
.find("mongodb+srv://")
|
||||
.map(|i| (i, "mongodb+srv://".len()));
|
||||
match (next_std, next_srv) {
|
||||
(Some(a), Some(b)) => Some(if a.0 <= b.0 { a } else { b }),
|
||||
(Some(a), None) => Some(a),
|
||||
(None, Some(b)) => Some(b),
|
||||
(None, None) => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn redact_embedded_mongo_uris(text: &str) -> String {
|
||||
let mut result = String::with_capacity(text.len());
|
||||
let mut cursor = 0usize;
|
||||
let lower = text.to_ascii_lowercase();
|
||||
|
||||
while cursor < text.len() {
|
||||
let rem = &lower[cursor..];
|
||||
let next_std = rem.find("mongodb://").map(|i| (i, "mongodb://".len()));
|
||||
let next_srv = rem
|
||||
.find("mongodb+srv://")
|
||||
.map(|i| (i, "mongodb+srv://".len()));
|
||||
let next = match (next_std, next_srv) {
|
||||
(Some(a), Some(b)) => Some(if a.0 <= b.0 { a } else { b }),
|
||||
(Some(a), None) => Some(a),
|
||||
(None, Some(b)) => Some(b),
|
||||
(None, None) => None,
|
||||
};
|
||||
let Some((rel_start, scheme_len)) = next else {
|
||||
let Some((rel_start, scheme_len)) = find_next_mongo_scheme(&lower[cursor..]) else {
|
||||
result.push_str(&text[cursor..]);
|
||||
break;
|
||||
};
|
||||
|
|
@ -759,12 +741,18 @@ fn redact_embedded_mongo_uris(text: &str) -> String {
|
|||
|
||||
let tail = &text[start..];
|
||||
let after_scheme = &tail[scheme_len..];
|
||||
// Authority ends at `/`, `?`, or whitespace. Do not stop on punctuation
|
||||
// such as `,`, `;`, `)`, `]`, `}`, `"`, `'` before locating `@`, because
|
||||
// embedded passwords (or replica-set host lists) may contain them.
|
||||
let authority_end = after_scheme
|
||||
let after_scheme_lower = &lower[start + scheme_len..];
|
||||
// Authority ends at `/`, `?`, whitespace, or the start of a subsequent
|
||||
// MongoDB URI scheme (e.g., compact JSON `["mongodb://host","mongodb://u:p@host"]`).
|
||||
// Do not stop on punctuation such as `,`, `;`, `)`, `]`, `}`, `"`, `'` before
|
||||
// locating `@`, because embedded passwords (or replica-set host lists) may contain them.
|
||||
let delim_end = after_scheme
|
||||
.find(|c: char| c.is_whitespace() || matches!(c, '/' | '?'))
|
||||
.unwrap_or(after_scheme.len());
|
||||
let next_scheme_end = find_next_mongo_scheme(after_scheme_lower)
|
||||
.map(|(idx, _)| idx)
|
||||
.unwrap_or(after_scheme.len());
|
||||
let authority_end = delim_end.min(next_scheme_end);
|
||||
let authority_region = &after_scheme[..authority_end];
|
||||
|
||||
if let Some(at_idx) = authority_region.rfind('@') {
|
||||
|
|
|
|||
|
|
@ -948,7 +948,7 @@ fn build_filter_document_and_spec_validation() {
|
|||
}
|
||||
|
||||
#[test]
|
||||
fn qm_filings_date_range_requires_eastern_time_and_handles_et_utc_date_boundary() {
|
||||
fn qm_filings_date_range_requires_eastern_calendar_day_boundaries_and_handles_fall_back_dst() {
|
||||
// UTC ISO string must be rejected: a filing stored as "2024-12-31T21:30:00 EST"
|
||||
// (= 2025-01-01T02:30:00Z) would lexicographically sort before "2025-01-01T00:00:00Z".
|
||||
assert!(matches!(
|
||||
|
|
@ -968,13 +968,37 @@ fn qm_filings_date_range_requires_eastern_time_and_handles_et_utc_date_boundary(
|
|||
})
|
||||
));
|
||||
|
||||
// Bare YYYY-MM-DD and BsonDateTimeMillis bounds must also be rejected for qmFilings.
|
||||
// Intra-day Eastern timestamps must also be rejected for server-side string ranges:
|
||||
// on fall-back DST day (2024-11-03), "2024-11-03T01:15:00 EST" occurred 45 minutes
|
||||
// AFTER "2024-11-03T01:30:00 EDT" but sorts lexicographically BEFORE it.
|
||||
assert!(matches!(
|
||||
build_filter_document(
|
||||
SourceCollection::QmFilings,
|
||||
&MongoReadSpec {
|
||||
date_range: Some(MongoDateRange {
|
||||
gte: Some(FilterDateValue::IsoString("2025-01-01".to_owned())),
|
||||
gte: Some(FilterDateValue::IsoString(
|
||||
"2024-11-03T01:30:00 EDT".to_owned()
|
||||
)),
|
||||
lt: Some(FilterDateValue::IsoString(
|
||||
"2024-11-03T02:00:00 EST".to_owned()
|
||||
)),
|
||||
}),
|
||||
..MongoReadSpec::default()
|
||||
}
|
||||
),
|
||||
Err(MongoStreamError::InvalidDateRange {
|
||||
collection: SourceCollection::QmFilings,
|
||||
..
|
||||
})
|
||||
));
|
||||
|
||||
// Invalid calendar dates and BsonDateTimeMillis bounds must be rejected.
|
||||
assert!(matches!(
|
||||
build_filter_document(
|
||||
SourceCollection::QmFilings,
|
||||
&MongoReadSpec {
|
||||
date_range: Some(MongoDateRange {
|
||||
gte: Some(FilterDateValue::IsoString("2024-02-30".to_owned())),
|
||||
lt: None,
|
||||
}),
|
||||
..MongoReadSpec::default()
|
||||
|
|
@ -1002,32 +1026,38 @@ fn qm_filings_date_range_requires_eastern_time_and_handles_et_utc_date_boundary(
|
|||
})
|
||||
));
|
||||
|
||||
// Valid Eastern Time bounds spanning the UTC 2025-01-01 midnight boundary:
|
||||
// 2025-01-01T00:00:00Z == 2024-12-31T19:00:00 EST.
|
||||
let gte_et = "2024-12-31T19:00:00 EST";
|
||||
let lt_et = "2025-01-01T19:00:00 EST";
|
||||
let filing_across_boundary = "2024-12-31T21:30:00 EST"; // 2025-01-01T02:30:00Z
|
||||
// Eastern calendar-day boundaries (YYYY-MM-DD) are monotonic even across fall-back DST
|
||||
// (2024-11-03): both 01:30:00 EDT and 01:15:00 EST fall inside ["2024-11-03", "2024-11-04"),
|
||||
// while the previous and next days stay cleanly outside.
|
||||
let gte_day = "2024-11-03";
|
||||
let lt_day = "2024-11-04";
|
||||
let filter = build_filter_document(
|
||||
SourceCollection::QmFilings,
|
||||
&MongoReadSpec {
|
||||
date_range: Some(MongoDateRange {
|
||||
gte: Some(FilterDateValue::IsoString(gte_et.to_owned())),
|
||||
lt: Some(FilterDateValue::IsoString(lt_et.to_owned())),
|
||||
gte: Some(FilterDateValue::IsoString(gte_day.to_owned())),
|
||||
lt: Some(FilterDateValue::IsoString(lt_day.to_owned())),
|
||||
}),
|
||||
..MongoReadSpec::default()
|
||||
},
|
||||
)
|
||||
.expect("valid Eastern Time bounds for qmFilings must succeed");
|
||||
.expect("valid Eastern calendar-day bounds for qmFilings must succeed");
|
||||
|
||||
let tf = filter
|
||||
.get_document("timefiled")
|
||||
.expect("timefiled range subdocument must exist");
|
||||
assert_eq!(tf.get("$gte"), Some(&Bson::String(gte_et.to_owned())));
|
||||
assert_eq!(tf.get("$lt"), Some(&Bson::String(lt_et.to_owned())));
|
||||
assert!(
|
||||
filing_across_boundary >= gte_et && filing_across_boundary < lt_et,
|
||||
"filing {filing_across_boundary} must fall inside [{gte_et}, {lt_et})"
|
||||
);
|
||||
assert_eq!(tf.get("$gte"), Some(&Bson::String(gte_day.to_owned())));
|
||||
assert_eq!(tf.get("$lt"), Some(&Bson::String(lt_day.to_owned())));
|
||||
|
||||
let before_day = "2024-11-02T23:59:59 EDT";
|
||||
let dst_first_pass = "2024-11-03T01:30:00 EDT";
|
||||
let dst_second_pass = "2024-11-03T01:15:00 EST";
|
||||
let next_day_midnight = "2024-11-04T00:00:00 EST";
|
||||
|
||||
assert!(before_day < gte_day);
|
||||
assert!(dst_first_pass >= gte_day && dst_first_pass < lt_day);
|
||||
assert!(dst_second_pass >= gte_day && dst_second_pass < lt_day);
|
||||
assert!(next_day_midnight >= lt_day);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
|
@ -1138,6 +1168,49 @@ fn error_redaction_covers_distinct_secondary_uri_passwords_with_punctuation() {
|
|||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn error_redaction_covers_adjacent_uris_in_compact_json_list() {
|
||||
let primary_uri = validate_uri(
|
||||
"mongodb://studio_stock_bot_read:PRIMARY_PASS_222@localhost:27017/stock?authSource=stock",
|
||||
);
|
||||
let second_pass = "ADJACENT_JSON_SECRET_999";
|
||||
let third_pass = "ADJACENT_SRV_SECRET,COMMA;SEMI";
|
||||
// Compact JSON array with no whitespace between an unauthenticated URI lacking a `/db` path
|
||||
// and subsequent authenticated URIs carrying distinct passwords.
|
||||
let diagnostic = format!(
|
||||
r#"{{"uris":["mongodb://localhost:27017","mongodb://secondary:{second_pass}@10.0.0.51:27017/stock","mongodb+srv://reader:{third_pass}@cluster.internal"]}}"#
|
||||
);
|
||||
|
||||
let err = MongoStreamError::redacted_source(&diagnostic, &primary_uri);
|
||||
let display_out = format!("{err}");
|
||||
let debug_out = format!("{err:?}");
|
||||
|
||||
for secret in [
|
||||
"PRIMARY_PASS_222",
|
||||
second_pass,
|
||||
third_pass,
|
||||
"ADJACENT_SRV_SECRET",
|
||||
"COMMA",
|
||||
"SEMI",
|
||||
] {
|
||||
assert!(
|
||||
!display_out.contains(secret),
|
||||
"Display leaked adjacent JSON URI secret `{secret}`: {display_out}"
|
||||
);
|
||||
assert!(
|
||||
!debug_out.contains(secret),
|
||||
"Debug leaked adjacent JSON URI secret `{secret}`: {debug_out}"
|
||||
);
|
||||
}
|
||||
|
||||
assert!(
|
||||
display_out.contains(
|
||||
r#"["mongodb://localhost:27017","mongodb://secondary:[REDACTED]@10.0.0.51:27017/stock","mongodb+srv://reader:[REDACTED]@cluster.internal"]"#
|
||||
),
|
||||
"unexpected redacted compact JSON list in Display: {display_out}"
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 6. Sealed-surface source scan (zero driver paths or mutating calls)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue