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:
Studio 2026-11-30 02:12:18 -05:00
parent d998115dcf
commit 97fad30fd0
5 changed files with 68 additions and 370 deletions

View file

@ -103,10 +103,9 @@ pub use mongo_safety::{
ValidatedReadOnlyMongoUri, DEFAULT_ALLOWED_READ_USER, FORBIDDEN_ADMIN_USER, QA_MONGO_PORT,
};
pub use mongo_stream::{
build_filter_document, FilterDateValue, MongoDateRange, MongoDriverStage,
MongoRawDocumentSource, MongoReadSpec, MongoStreamError, RawBsonCursorReader,
RawDocumentSource, SliceRawDocumentSource, SourceCollection, VecRawDocumentSource,
DEFAULT_MONGO_BATCH_SIZE, MAX_MONGO_BATCH_SIZE,
build_filter_document, FilterDateValue, MongoDateRange, MongoReadSpec, MongoStreamError,
RawBsonCursorReader, RawDocumentSource, SliceRawDocumentSource, SourceCollection,
VecRawDocumentSource, DEFAULT_MONGO_BATCH_SIZE, MAX_MONGO_BATCH_SIZE,
};
pub use parquet_adj::{
adj_factors_parquet_schema, write_adj_factors_dataset, AdjFactorsParquetRow,

View file

@ -1,29 +1,25 @@
//! Sealed, read-only MongoDB raw-BSON cursor adapter (`M1.2al`).
//! Driver-independent read-only MongoDB raw-BSON cursor seam (`M1.2al`).
//!
//! Bridges [`ValidatedReadOnlyMongoUri`] (from [`crate::mongo_safety`]) to the
//! existing zero-copy [`crate::bson_stream`] decoders via a driver-independent
//! [`RawDocumentSource`] trait and a bounded-memory [`RawBsonCursorReader`]
//! implementing [`std::io::Read`].
//! Provides the closed [`SourceCollection`] allowlist, typed [`MongoReadSpec`]
//! filter validation/builder, driver-independent [`RawDocumentSource`] trait,
//! bounded-memory [`RawBsonCursorReader`] implementing [`std::io::Read`] for
//! the existing zero-copy [`crate::bson_stream`] decoders, and password-redacted
//! [`MongoStreamError`] sanitization reusing [`crate::mongo_safety`].
//!
//! # Safety & Sealing Guarantees
//! - Closed [`SourceCollection`] allowlist matching the 8 M1 collections in
//! `apps/stock/data-pipeline/src/security-master/export-raw-bson.ts`. No API
//! accepts a free-form collection name string.
//! - The only public constructor for [`MongoRawDocumentSource`] requires a
//! `&ValidatedReadOnlyMongoUri` proof token.
//! - Exposes no MongoDB client, database, or collection handle and performs
//! only read-only `find` cursor iteration.
//! - Lazy connection: [`MongoRawDocumentSource::open`] validates the database
//! name, read spec, and filter document upfront without opening any network
//! connection until the first [`RawDocumentSource::next_raw_document`] call.
//! - Password redaction: [`MongoStreamError`] never stores raw URIs, passwords,
//! or raw driver errors; all driver error text is sanitized at the boundary.
//! - Zero MongoDB driver surface in this module yet (no `mongodb::` imports,
//! client/database/collection handles, or write/admin/aggregation calls).
//! - Password redaction: [`MongoStreamError`] never stores raw URIs or
//! passwords; error text is sanitized at the boundary via
//! [`crate::mongo_safety::redact_mongo_uri_password`].
use std::error::Error;
use std::fmt;
use std::io;
use bson::raw::RawDocumentBuf;
use bson::{Bson, DateTime, Document};
use crate::bson_stream::{DEFAULT_MAX_DOC_BYTES, MIN_BSON_DOC_BYTES};
@ -35,10 +31,6 @@ pub const DEFAULT_MONGO_BATCH_SIZE: u32 = 4_096;
/// Maximum permitted MongoDB cursor batch size (matches `MAX_RAW_BSON_BATCH_SIZE`).
pub const MAX_MONGO_BATCH_SIZE: u32 = 100_000;
/// Default MongoDB `appName` attached to read-only ETL cursor connections when
/// the validated URI does not already specify `appName`.
const DEFAULT_APP_NAME: &str = "curate-etl-ro";
/// Closed allowlist of the 8 M1 MongoDB source collections consumed by `curate-etl`.
///
/// Order and names match `RAW_BSON_EXPORT_COLLECTIONS` in
@ -286,38 +278,11 @@ pub fn build_filter_document(
Ok(Document::from_iter(entries))
}
/// Operation stage for a sanitized MongoDB driver error.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MongoDriverStage {
Connect,
Find,
CursorAdvance,
}
impl MongoDriverStage {
pub const fn as_str(self) -> &'static str {
match self {
Self::Connect => "connect",
Self::Find => "find",
Self::CursorAdvance => "cursor_advance",
}
}
}
impl fmt::Display for MongoDriverStage {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
/// Redacted error type for MongoDB raw-BSON cursor streaming.
///
/// Intentionally never stores raw URIs, passwords, or raw driver error objects.
/// Intentionally never stores raw URIs or passwords.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MongoStreamError {
MissingDatabaseName {
redacted_uri: String,
},
InvalidBatchSize {
batch_size: u32,
max_batch_size: u32,
@ -343,24 +308,25 @@ pub enum MongoStreamError {
doc_index: u64,
detail: String,
},
Driver {
collection: SourceCollection,
stage: MongoDriverStage,
redacted_uri: String,
message: String,
},
Source {
detail: String,
},
}
impl MongoStreamError {
/// Constructs a [`MongoStreamError::Source`] after stripping any raw URI,
/// raw password, percent-decoded password, or embedded MongoDB userinfo
/// password from `raw_message`.
pub fn redacted_source(raw_message: &str, uri: &ValidatedReadOnlyMongoUri) -> Self {
Self::Source {
detail: sanitize_driver_error_message(raw_message, uri),
}
}
}
impl fmt::Display for MongoStreamError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::MissingDatabaseName { redacted_uri } => write!(
f,
"MongoDB URI {redacted_uri} must include a non-empty database name"
),
Self::InvalidBatchSize {
batch_size,
max_batch_size,
@ -394,15 +360,6 @@ impl fmt::Display for MongoStreamError {
Self::InvalidBsonFrame { doc_index, detail } => {
write!(f, "invalid raw BSON frame at doc #{doc_index}: {detail}")
}
Self::Driver {
collection,
stage,
redacted_uri,
message,
} => write!(
f,
"MongoDB driver error during {stage} on {collection} ({redacted_uri}): {message}"
),
Self::Source { detail } => write!(f, "raw BSON source error: {detail}"),
}
}
@ -778,187 +735,6 @@ pub(crate) fn sanitize_driver_error_message(
redact_embedded_mongo_uris(&sanitized)
}
pub(crate) fn build_driver_error(
collection: SourceCollection,
stage: MongoDriverStage,
uri: &ValidatedReadOnlyMongoUri,
raw_message: &str,
) -> MongoStreamError {
MongoStreamError::Driver {
collection,
stage,
redacted_uri: uri.redacted(),
message: sanitize_driver_error_message(raw_message, uri),
}
}
fn append_default_app_name(uri: &str) -> String {
let query_part = uri.split_once('?').map(|(_, q)| q).unwrap_or("");
let has_app_name = query_part.split('&').any(|pair| {
pair.split_once('=')
.map(|(k, _)| k.eq_ignore_ascii_case("appname"))
.unwrap_or(false)
});
if has_app_name {
return uri.to_owned();
}
if uri.contains('?') {
if uri.ends_with('?') || uri.ends_with('&') {
format!("{uri}appName={DEFAULT_APP_NAME}")
} else {
format!("{uri}&appName={DEFAULT_APP_NAME}")
}
} else {
format!("{uri}?appName={DEFAULT_APP_NAME}")
}
}
enum DriverCursorState {
Unopened,
Open(Box<mongodb::sync::Cursor<RawDocumentBuf>>),
Exhausted,
}
/// Sealed, read-only MongoDB raw-BSON cursor source.
///
/// The only public constructor is [`MongoRawDocumentSource::open`], which
/// requires a [`ValidatedReadOnlyMongoUri`] proof token and a closed
/// [`SourceCollection`] allowlist variant. No client, database, collection,
/// or mutating/admin operation is exposed.
pub struct MongoRawDocumentSource {
uri: ValidatedReadOnlyMongoUri,
database: String,
collection: SourceCollection,
filter: Document,
batch_size: u32,
limit: Option<i64>,
state: DriverCursorState,
}
impl MongoRawDocumentSource {
/// Validates the target database name, `spec`, and filter document without
/// opening any network connection. The underlying read-only MongoDB cursor
/// is opened lazily on the first [`RawDocumentSource::next_raw_document`] call.
pub fn open(
uri: &ValidatedReadOnlyMongoUri,
collection: SourceCollection,
spec: MongoReadSpec,
) -> Result<Self, MongoStreamError> {
let Some(database) = uri
.target()
.database
.as_deref()
.filter(|db| !db.trim().is_empty())
else {
return Err(MongoStreamError::MissingDatabaseName {
redacted_uri: uri.redacted(),
});
};
let filter = build_filter_document(collection, &spec)?;
let limit = spec.limit.map(|v| v as i64);
Ok(Self {
uri: uri.clone(),
database: database.to_owned(),
collection,
filter,
batch_size: spec.batch_size,
limit,
state: DriverCursorState::Unopened,
})
}
pub fn collection(&self) -> SourceCollection {
self.collection
}
pub fn database(&self) -> &str {
&self.database
}
pub fn redacted_uri(&self) -> String {
self.uri.redacted()
}
pub fn batch_size(&self) -> u32 {
self.batch_size
}
pub fn limit(&self) -> Option<u64> {
self.limit.map(|v| v as u64)
}
pub fn filter(&self) -> &Document {
&self.filter
}
}
impl RawDocumentSource for MongoRawDocumentSource {
fn next_raw_document(&mut self) -> Result<Option<&[u8]>, MongoStreamError> {
if let DriverCursorState::Unopened = self.state {
let connect_uri = append_default_app_name(self.uri.as_str());
let client = match mongodb::sync::Client::with_uri_str(&connect_uri) {
Ok(client) => client,
Err(err) => {
self.state = DriverCursorState::Exhausted;
return Err(build_driver_error(
self.collection,
MongoDriverStage::Connect,
&self.uri,
&err.to_string(),
));
}
};
let coll = client
.database(&self.database)
.collection::<RawDocumentBuf>(self.collection.as_str());
let mut find_action = coll.find(self.filter.clone()).batch_size(self.batch_size);
if let Some(limit) = self.limit {
find_action = find_action.limit(limit);
}
let cursor = match find_action.run() {
Ok(cursor) => cursor,
Err(err) => {
self.state = DriverCursorState::Exhausted;
return Err(build_driver_error(
self.collection,
MongoDriverStage::Find,
&self.uri,
&err.to_string(),
));
}
};
self.state = DriverCursorState::Open(Box::new(cursor));
}
let advance_res = match &mut self.state {
DriverCursorState::Open(cursor) => cursor.advance(),
DriverCursorState::Exhausted | DriverCursorState::Unopened => return Ok(None),
};
match advance_res {
Ok(true) => match &self.state {
DriverCursorState::Open(cursor) => Ok(Some(cursor.current().as_bytes())),
DriverCursorState::Exhausted | DriverCursorState::Unopened => Ok(None),
},
Ok(false) => {
self.state = DriverCursorState::Exhausted;
Ok(None)
}
Err(err) => {
self.state = DriverCursorState::Exhausted;
Err(build_driver_error(
self.collection,
MongoDriverStage::CursorAdvance,
&self.uri,
&err.to_string(),
))
}
}
}
}
#[cfg(test)]
#[path = "mongo_stream_tests.rs"]
mod tests;

View file

@ -14,11 +14,10 @@ use crate::mongo_safety::{
assert_read_only_mongo_uri, LocalHosts, ReadOnlyPolicy, ValidatedReadOnlyMongoUri,
};
use crate::mongo_stream::{
append_default_app_name, build_driver_error, build_filter_document,
sanitize_driver_error_message, FilterDateValue, MongoDateRange, MongoDriverStage,
MongoRawDocumentSource, MongoReadSpec, MongoStreamError, RawBsonCursorReader,
RawDocumentSource, SliceRawDocumentSource, SourceCollection, VecRawDocumentSource,
DEFAULT_MONGO_BATCH_SIZE, MAX_MONGO_BATCH_SIZE,
build_filter_document, sanitize_driver_error_message, FilterDateValue, MongoDateRange,
MongoReadSpec, MongoStreamError, RawBsonCursorReader, RawDocumentSource,
SliceRawDocumentSource, SourceCollection, VecRawDocumentSource, DEFAULT_MONGO_BATCH_SIZE,
MAX_MONGO_BATCH_SIZE,
};
fn build_eod_doc(code: &str, date: &str, close: f64, volume: f64) -> Vec<u8> {
@ -933,61 +932,6 @@ fn build_filter_document_and_spec_validation() {
));
}
#[test]
fn mongo_raw_document_source_open_validates_database_and_is_strictly_lazy() {
// Missing database name fails closed offline
let uri_no_db = validate_uri("mongodb://studio_stock_bot_read:s3cr3t@localhost:27017/");
let err = MongoRawDocumentSource::open(
&uri_no_db,
SourceCollection::EodPrices,
MongoReadSpec::default(),
)
.err()
.expect("missing database name must fail closed");
assert!(matches!(err, MongoStreamError::MissingDatabaseName { .. }));
assert!(!format!("{err}").contains("s3cr3t"));
assert!(format!("{err}").contains("[REDACTED]"));
// Valid URI with unreachable host succeeds lazily without touching the network
let uri_ok = validate_uri(
"mongodb://studio_stock_bot_read:s3cr3t@192.0.2.1:27017/stock?authSource=stock",
);
let source = MongoRawDocumentSource::open(
&uri_ok,
SourceCollection::QmSplits,
MongoReadSpec {
batch_size: 1024,
limit: Some(10),
..MongoReadSpec::default()
},
)
.expect("lazy open must succeed offline without connecting");
assert_eq!(source.collection(), SourceCollection::QmSplits);
assert_eq!(source.database(), "stock");
assert_eq!(source.batch_size(), 1024);
assert_eq!(source.limit(), Some(10));
assert!(!source.redacted_uri().contains("s3cr3t"));
assert!(source.redacted_uri().contains("[REDACTED]"));
// Dropped here without calling next_raw_document() -> zero network I/O.
}
#[test]
fn append_default_app_name_preserves_existing_and_adds_when_missing() {
assert_eq!(
append_default_app_name("mongodb://u:p@host:27017/stock"),
"mongodb://u:p@host:27017/stock?appName=curate-etl-ro"
);
assert_eq!(
append_default_app_name("mongodb://u:p@host:27017/stock?authSource=stock"),
"mongodb://u:p@host:27017/stock?authSource=stock&appName=curate-etl-ro"
);
assert_eq!(
append_default_app_name("mongodb://u:p@host:27017/stock?appName=custom"),
"mongodb://u:p@host:27017/stock?appName=custom"
);
}
// ---------------------------------------------------------------------------
// 5. Password redaction (plain and percent-encoded sentinel passwords)
// ---------------------------------------------------------------------------
@ -1003,16 +947,17 @@ fn error_display_and_debug_never_leak_plain_or_percent_encoded_passwords() {
let simulated_raw = format!(
"connection failed for {plain_uri_str} (auth token {plain_sentinel}) secondary mongodb://other:{plain_sentinel}@10.0.0.51:27017/stock"
);
let err = build_driver_error(
SourceCollection::EodPrices,
MongoDriverStage::Connect,
&plain_uri,
&simulated_raw,
);
let err = MongoStreamError::redacted_source(&simulated_raw, &plain_uri);
let display_out = format!("{err}");
let debug_out = format!("{err:?}");
assert!(!display_out.contains(plain_sentinel), "Display leaked plain password: {display_out}");
assert!(!debug_out.contains(plain_sentinel), "Debug leaked plain password: {debug_out}");
assert!(
!display_out.contains(plain_sentinel),
"Display leaked plain password: {display_out}"
);
assert!(
!debug_out.contains(plain_sentinel),
"Debug leaked plain password: {debug_out}"
);
assert!(display_out.contains("[REDACTED]"));
assert!(debug_out.contains("[REDACTED]"));
@ -1027,16 +972,17 @@ fn error_display_and_debug_never_leak_plain_or_percent_encoded_passwords() {
"failed parsing {enc_uri_str}; raw={encoded_sentinel}; decoded={decoded_sentinel}"
);
let sanitized = sanitize_driver_error_message(&simulated_enc_raw, &enc_uri);
assert!(!sanitized.contains(encoded_sentinel), "leaked encoded password: {sanitized}");
assert!(!sanitized.contains(decoded_sentinel), "leaked decoded password: {sanitized}");
assert!(
!sanitized.contains(encoded_sentinel),
"leaked encoded password: {sanitized}"
);
assert!(
!sanitized.contains(decoded_sentinel),
"leaked decoded password: {sanitized}"
);
assert!(sanitized.contains("[REDACTED]"));
let enc_err = build_driver_error(
SourceCollection::QmFilings,
MongoDriverStage::Find,
&enc_uri,
&simulated_enc_raw,
);
let enc_err = MongoStreamError::redacted_source(&simulated_enc_raw, &enc_uri);
let enc_display = format!("{enc_err}");
let enc_debug = format!("{enc_err:?}");
assert!(!enc_display.contains(encoded_sentinel));
@ -1047,19 +993,11 @@ fn error_display_and_debug_never_leak_plain_or_percent_encoded_passwords() {
}
// ---------------------------------------------------------------------------
// 6. Sealed-surface checks (compile-time signature + source scan)
// 6. Sealed-surface source scan (zero driver paths or mutating calls)
// ---------------------------------------------------------------------------
#[test]
fn sealed_surface_compile_time_signature_and_source_scan() {
// Compile-time function pointer check: MongoRawDocumentSource::open MUST take
// `&ValidatedReadOnlyMongoUri` and `SourceCollection`.
let _open_fn: fn(
&ValidatedReadOnlyMongoUri,
SourceCollection,
MongoReadSpec,
) -> Result<MongoRawDocumentSource, MongoStreamError> = MongoRawDocumentSource::open;
fn sealed_surface_source_scan() {
let src_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("src")
.join("mongo_stream.rs");
@ -1077,6 +1015,11 @@ fn sealed_surface_compile_time_signature_and_source_scan() {
.collect::<Vec<_>>()
.join("\n");
assert!(
!code_only.contains("mongodb::"),
"mongo_stream.rs must not contain any `mongodb::` driver path yet"
);
let forbidden_calls = [
"insert",
"update",
@ -1099,9 +1042,7 @@ fn sealed_surface_compile_time_signature_and_source_scan() {
);
}
// Check that no `pub` item exposes `mongodb::Client`, `Database`, or `Collection`,
// and every `pub fn` returning `MongoRawDocumentSource` or `Result<Self` takes
// `&ValidatedReadOnlyMongoUri`.
// Check that no `pub` item exposes `mongodb::Client`, `Database`, or `Collection`.
let lines: Vec<&str> = code_only.lines().collect();
for (idx, line) in lines.iter().enumerate() {
let trimmed = line.trim();
@ -1131,21 +1072,6 @@ fn sealed_surface_compile_time_signature_and_source_scan() {
"public item exposes forbidden MongoDB handle `{forbidden_type}`: {sig}"
);
}
if trimmed.starts_with("pub fn ")
&& (sig.contains("-> Result<Self")
|| sig.contains("-> Self")
|| sig.contains("-> MongoRawDocumentSource")
|| sig.contains("-> Result<MongoRawDocumentSource"))
{
// Only applies to constructors of MongoRawDocumentSource (not MongoReadSpec::default, etc.)
if sig.contains("open(") || sig.contains("MongoRawDocumentSource") {
assert!(
sig.contains("&ValidatedReadOnlyMongoUri"),
"public MongoRawDocumentSource constructor must require &ValidatedReadOnlyMongoUri: {sig}"
);
}
}
}
}
}