diff --git a/design/README.md b/design/README.md index 0157ab05..978b8c69 100644 --- a/design/README.md +++ b/design/README.md @@ -13,6 +13,7 @@ Start here. Every document below has a single responsibility; historical sprint | **[DATA-CONTRACTS.md](DATA-CONTRACTS.md)** | Raw MongoDB provider quirks, PostgreSQL security-master DDL, split/volume un-adjustment rules, `known_at` derivation, DuckDB/Parquet & QuestDB `10.2.0` schemas, and `MarketDataStore` API | Before touching `data-pipeline`, `data-ingestion`, SQL migrations, or `MarketDataStore` | | **[VALIDATION-AND-RIGOR.md](VALIDATION-AND-RIGOR.md)** | Canonical metric definitions, `trial_ledger` schema, effective-trials DSR ($\hat{N}$), CSCV PBO, Purged CPCV/Walk-Forward, rolling 6-month Vault + Post-2023 Recency Gate, lifecycle gates, and Dual Live Drift + IB/TSX execution rules | Before touching `libs/calculations`, `libs/research`, validation workflows, or paper/live execution | | **[servers.md](servers.md)** | Host roles (`quant` `12900K` research/data server, `9900K` isolated IB live/paper host, `TrueNAS` cold storage, dev workstation) and port/storage layout | Infrastructure, deployment, and worker sizing | +| **[data-pipeline/rust-migration-evaluation.md](data-pipeline/rust-migration-evaluation.md)** | Evidence-based evaluation of keeping `apps/stock/data-pipeline` in TypeScript vs. moving bulk MongoDB streaming or the full pipeline into Rust (`tools/curate-etl`) | Before `M2` adds PIT fundamentals, `ceoPosts`, or `bars_1m` QuestDB ingestion | --- diff --git a/design/data-pipeline/rust-migration-evaluation.md b/design/data-pipeline/rust-migration-evaluation.md new file mode 100644 index 00000000..a7525188 --- /dev/null +++ b/design/data-pipeline/rust-migration-evaluation.md @@ -0,0 +1,249 @@ +# Evaluation: Moving `apps/stock/data-pipeline` into Rust + +**Date:** 2026-11-29 +**Status:** Decision brief for the director (docs-only spike; no code, crate, config, or milestone changes enacted) +**Scope:** Evaluate the second half of the settled Rust ETL decision — whether to keep `apps/stock/data-pipeline` in TypeScript, move bulk MongoDB streaming into `tools/curate-etl` (Rust), or port all of `apps/stock/data-pipeline` to Rust before Milestone `M2` adds PIT fundamentals, `ceoPosts`, and `bars_1m` intraday QuestDB ingestion. + +## Bottom Line (Recommendation) + +**Adopt Option B: keep `apps/stock/data-pipeline` in TypeScript for security-master resolution, TSV export, probes, and BullMQ/HTTP orchestration, and add direct read-only MongoDB `RawDocumentBuf` streaming (with Rust-side read-only safety guards) to `tools/curate-etl` for bulk curation.** + +- **Why not full port (Option C):** 88.1% of `apps/stock/data-pipeline/src/` (`17,924` of `20,349` LOC, backed by `40` test files / `32,435` test LOC) is logic- and review-bound security-master code operating on `319` exchanges and `396k` symbol catalog rows that already runs in sub-second synthetic benchmarks (`479.6 ms` for `100k` records in `run.ts`, `402.8 ms` for `500k` TSV mappings in `export-curate-inputs.ts`). Porting it adds weeks of parity risk, requires re-implementing BullMQ/PostgreSQL/env-safety adapters, and reopens settled decision `D5` / §4 layer boundaries for negligible wall-time gain. +- **Why not keep the JS raw-BSON file bridge forever (Option A):** While `export-raw-bson.ts` avoids JS object decoding (`3.57M–3.83M docs/s` synthetic), staging `845.7M` `eodPrices` and `3.40B` `eodIntraday1M` + `173.3M` `qmIntraday` rows through intermediate `.bson` files forces an unnecessary full NVMe write + read of hundreds of GiB (synthetic estimate: ~127–225 GiB peak file capacity / ~255–450 GiB total write+read I/O for `eodPrices`; ~499–832 GiB peak capacity / ~998–1,664 GiB total write+read I/O for the two intraday collections) before Rust even begins curating. Streaming directly from read-only MongoDB cursors in `tools/curate-etl` eliminates that scratch hop without touching the TypeScript security master. +- **Decision ownership:** The final choice among Options A, B, and C belongs to the director. None of the follow-up tasks in Section 6 are queued or enacted by this document. + +--- + +## 1. Current `apps/stock/data-pipeline` Inventory + +Measured directly from the repository working tree (no database connections). Every production file under `apps/stock/data-pipeline/src/` is `.ts` (zero non-`.ts` files). + +| Area under `apps/stock/data-pipeline/src/` | Prod Files | Non-Test LOC | Dedicated Test Files | Test LOC | Primary I/O & Role | +| --- | ---: | ---: | ---: | ---: | --- | +| `security-master/` | 21 | 17,924 | 40 | 32,435 | Pure in-memory Passes 1–6 + read-only MongoDB readers (`eodSymbols`, `ibSymbols`, `qmSymbols`, `ceoSymbols`, `eodSymbolChange`, `eodPrices`, `qmPrices`, exchanges, raw BSON, field-shape probe) + PostgreSQL master read/write (`persist.ts`, `export-curate-inputs.ts`) + local file output | +| `normalization/` | 4 | 1,318 | 6 | 2,468 | Pure in-memory (`identifiers.ts`, `provider-symbol.ts`, `ticker.ts`) + read-only MongoDB aggregation reader (`bar-spans.ts`: `$match`/`$group`/`$project`/`$sort` only, `$out`/`$merge` forbidden) | +| `handlers/` | 12 | 809 | 1* | 290* | BullMQ job handlers (`{data-pipeline_exchanges}`, `{data-pipeline_symbols}` queues via `getFullQueueName`), read-only MongoDB reads, PostgreSQL master reads/writes via `PipelineSyncRepository` | +| `repositories/` | 1 | 166 | (shared)* | (shared)* | PostgreSQL transactional sync/reset (`PipelineSyncRepository`, `pg_advisory_xact_lock(1937007472, 1)`) using `@stock-bot/types` `parseReferenceDataResetRequest` | +| `routes/` | 2 | 23 | 0 | 0 | HTTP `GET /health` via Hono (`create-routes.ts`, `health.routes.ts`) | +| `types/` | 1 | 21 | 0 | 0 | Pure in-memory TypeScript interfaces (`job-payloads.ts`: `JobPayload`, `SyncResult`, `SyncStatus`) | +| `index.ts` | 1 | 88 | 0 | 0 | Service bootstrap (`ServiceApplication`, `initializeStockConfig('dataPipeline', { mongoReadOnly: true })`, port `2002`, BullMQ + HTTP + Postgres + read-only Mongo) | +| **Total (`src/`)** | **42** | **20,349** | **47** | **35,193** | — | + +*\*`test/postgres/pipeline-safety.test.ts` (1 file, 290 lines) exercises both `handlers/` operations and `PipelineSyncRepository`; it is counted once in the total. `routes/`, `types/`, and `index.ts` have no dedicated unit test files and are covered indirectly by `test/unit/environment-safety*.test.ts` and `test/unit/mongodb-read-only.test.ts`.* + +Separately from production LOC, `apps/stock/data-pipeline/benchmarks/` holds **5 files / 1,144 LOC** of local synthetic benchmark scripts (`export-curate-inputs-benchmark.ts`, `export-raw-bson-benchmark.ts`, `run-security-master-pass4-benchmark.ts`, `sample-closes-benchmark.ts`, `source-field-shapes-benchmark.ts`). + +### Key CLI & Exporter Subsystems Inside `security-master/` + +- **`run-security-master.ts` (T-89 / T-105, `1,042` LOC) + `run.ts` (`1,345` LOC):** Runs the full read-only MongoDB security-master pipeline (`read-exchanges` → `read-sources` → `compute-bar-spans` → Pass 4 `readSampleCloses` + `crossCheckPrices` → `composeSecurityMasterRun`) and writes deterministic `match-report.md`, `conflicts.csv`, `override-template.sql`, and `run-stats.json`, with opt-in `--persist` to isolated dev PostgreSQL guarded by `assertSecurityMasterPersistSafety()`. **Source note:** Pass 4 is **wired and enabled by default** in `run-security-master.ts` (`--skip-price-cross-check`, `--sample-dates `), even though `apps/stock/data-pipeline/README.md` line 201 still states it is not yet wired. +- **TSV Exporter (T-116, `export-curate-inputs.ts` `2,040` LOC + `run-export-curate-inputs.ts` `345` LOC = `2,385` LOC):** Reads PostgreSQL security-master tables inside a `REPEATABLE READ READ ONLY` transaction (server-side `NO SCROLL` cursor, chunk size `<= 5,000`) and atomically publishes `provider_mapping.tsv`, `listing_currencies.tsv`, and Pass 6 `delistings.tsv` into `/generations/` behind `/.publish.lock` and a single `/current` symlink. +- **Raw-BSON Exporter (T-117, `export-raw-bson.ts` `670` LOC + `run-export-raw-bson.ts` `477` LOC = `1,147` LOC):** Streams 8 allowlisted M1 MongoDB collections (`eodPrices`, `qmSplits`, `qmDividends`, `qmPrices`, `teMarketData`, `ceoShorts`, `qmFilings`, `qmEarnings`) via `find(filter, { raw: true, batchSize })` with zero per-document JS decoding, validating BSON frame lengths, coalescing through an `8 MiB` write buffer, computing SHA-256, and publishing `.bson` atomically. +- **Field-Shape Probe (`source-field-shapes.ts` `915` LOC + `probe-source-field-shapes.ts` `291` LOC = `1,206` LOC):** Bounded read-only `find({}, { limit <= 10_000, promoteValues: false, promoteLongs: false })` probe over the 8 M1 collections to confirm live BSON field names and types before curation runs. + +### Cross-App Coupling & Safety Guards + +- **Zero direct package imports:** No other app or library imports `@stock-bot/data-pipeline`. +- **`web-api` runtime contract:** `apps/stock/web-api/src/services/pipeline.service.ts` enqueues BullMQ jobs onto `{data-pipeline_exchanges}` and `{data-pipeline_symbols}` via `getFullQueueName` (`libs/core/queue/src/service-utils.ts`, re-exported by `@stock-bot/queue`; using shared `@stock-bot/types` `parseReferenceDataResetRequest` / `ReferenceDataResetScope` for reset confirmation), and `apps/stock/web-api/src/services/monitoring.service.ts` monitors those two queues and polls `GET /health` on port `2002`. +- **Safety guard stack:** Every service and CLI entrypoint calls `initializeStockConfig('dataPipeline', { mongoReadOnly: true })` and `assertEnvironmentSafety()` (`apps/stock/config/src/env-safety.ts`, `706` LOC), which resolves loopback/LAN/numeric IPv4 aliases and throws if `development` targets QA PostgreSQL (`localhost:5432/trading_bot`) or opens QA MongoDB (`localhost:27017`) without `mongoReadOnly: true` or with `trading_admin`. At the driver layer, `MongoDBClient` (`libs/data/mongodb/src/client.ts`) wraps databases, collections, and cursors in read-only proxies that reject all write, index, and collection-mutation operations. + +### Reproducible Inventory Commands + +Re-running these POSIX commands from the repository root at the same commit reproduces every count in the table above: + +```bash +# 1. Production source file counts & non-test LOC per area +for area in security-master normalization handlers repositories routes types; do + files=$(find "apps/stock/data-pipeline/src/$area" -type f -name '*.ts' | sort) + count=$(printf '%s\n' "$files" | grep -c .) + lines=$(printf '%s\n' "$files" | xargs wc -l | tail -n 1 | awk '{print $1}') + printf '%-18s files=%2d loc=%5d\n' "$area/" "$count" "$lines" +done +printf '%-18s files=%2d loc=%5d\n' "index.ts" 1 "$(wc -l < apps/stock/data-pipeline/src/index.ts)" +total_files=$(find apps/stock/data-pipeline/src -type f -name '*.ts' | wc -l) +total_lines=$(find apps/stock/data-pipeline/src -type f -name '*.ts' | sort | xargs wc -l | tail -n 1 | awk '{print $1}') +printf '%-18s files=%2d loc=%5d\n' "TOTAL" "$total_files" "$total_lines" + +# 2. Dedicated test files & benchmark scripts +printf 'data-pipeline/test: %2d files %5d lines\n' \ + "$(find apps/stock/data-pipeline/test -type f -name '*.test.ts' | wc -l)" \ + "$(find apps/stock/data-pipeline/test -type f -name '*.test.ts' | sort | xargs wc -l | tail -n 1 | awk '{print $1}')" +printf 'unit security-master: %2d files %5d lines\n' \ + "$(find test/unit -type f -name 'security-master-*.test.ts' | wc -l)" \ + "$(find test/unit -type f -name 'security-master-*.test.ts' | sort | xargs wc -l | tail -n 1 | awk '{print $1}')" +printf 'postgres security-master: %2d files %5d lines\n' \ + "$(find test/postgres -type f -name 'security-master-*.test.ts' | wc -l)" \ + "$(find test/postgres -type f -name 'security-master-*.test.ts' | sort | xargs wc -l | tail -n 1 | awk '{print $1}')" +printf 'unit normalization: %2d files %5d lines\n' \ + "$(find test/unit -type f -name 'normalization-*.test.ts' | wc -l)" \ + "$(find test/unit -type f -name 'normalization-*.test.ts' | sort | xargs wc -l | tail -n 1 | awk '{print $1}')" +printf 'integration provider-symbol: %2d files %5d lines\n' \ + 1 "$(wc -l < test/integration/provider-symbol.test.ts)" +printf 'postgres pipeline-safety: %2d files %5d lines\n' \ + 1 "$(wc -l < test/postgres/pipeline-safety.test.ts)" +printf 'benchmarks (separate): %2d files %5d lines\n' \ + "$(find apps/stock/data-pipeline/benchmarks -type f -name '*.ts' | wc -l)" \ + "$(find apps/stock/data-pipeline/benchmarks -type f -name '*.ts' | sort | xargs wc -l | tail -n 1 | awk '{print $1}')" +``` + +--- + +## 2. What Already Lives in Rust (`tools/curate-etl`) + +`tools/curate-etl` is a standalone Cargo workspace member with **three exact-pinned dependencies** (`bson = "=3.1.0"` with `compat-3-0-0`, `parquet = "=60.2.0"` Zstd-only, `rayon = "=1.12.0"`), **zero async runtime**, and **zero database clients**. + +| Module Group under `tools/curate-etl/src/` | Files | LOC | Contents | +| --- | ---: | ---: | --- | +| Domain builders | 9 | 8,170 | `adj.rs`, `bars.rs`, `corporate_actions.rs`, `events.rs`, `fx.rs`, `provider_mapping.rs`, `session_close.rs`, `shorts.rs`, `split.rs` | +| Zero-copy BSON decoders & framing | 7 | 5,594 | `bson_ceo_shorts.rs`, `bson_eod_prices.rs`, `bson_qm_actions.rs`, `bson_qm_events.rs`, `bson_qm_prices.rs`, `bson_stream.rs`, `bson_te_market_data.rs` | +| Zstd Parquet writers & atomic publish | 7 | 9,841 | `parquet_adj.rs`, `parquet_bars.rs`, `parquet_corporate_actions.rs`, `parquet_events.rs`, `parquet_fx.rs`, `parquet_publish.rs`, `parquet_shorts.rs` | +| Curation stages | 6 | 3,726 | `curate_adj.rs`, `curate_bars.rs`, `curate_corporate_actions.rs`, `curate_events.rs`, `curate_fx.rs`, `curate_shorts.rs` | +| Runnable `curate-*` CLI runners | 6 | 5,202 | `run_curate_adj.rs`, `run_curate_bars.rs`, `run_curate_corporate_actions.rs`, `run_curate_events.rs`, `run_curate_fx.rs`, `run_curate_shorts.rs` | +| CLI, benchmarks, entrypoints | 4 | 16,884 | `bench.rs`, `cli.rs`, `lib.rs`, `main.rs` | +| Dedicated test modules (`*_tests.rs`) | 26 | 27,215 | Unit, property, parity, and TSV/BSON fixture tests | +| **Total (`tools/curate-etl/src/`)** | **65** | **76,632** | **39 non-test files (49,417 LOC) + 26 test files (27,215 LOC)** | + +Reproducible command: + +```bash +find tools/curate-etl/src -type f -name '*.rs' ! -name '*_tests.rs' | wc -l +find tools/curate-etl/src -type f -name '*.rs' ! -name '*_tests.rs' | sort | xargs wc -l | tail -n 1 +find tools/curate-etl/src -type f -name '*_tests.rs' | wc -l +find tools/curate-etl/src -type f -name '*_tests.rs' | sort | xargs wc -l | tail -n 1 +``` + +The binary already implements all **six M1 curation commands** (`curate-bars-1d`, `curate-adj-factors`, `curate-corporate-actions`, `curate-fx-1d`, `curate-shorts`, `curate-events`) reading local TSVs + concatenated raw-BSON files and atomically publishing Hive-partitioned Zstd Parquet. + +### Measured Local Baselines (Synthetic / Offline — Zero Live QA MongoDB or `quant` Runs) + +| Benchmark | Source & Date | Command | Workload & Measured Result | +| --- | --- | --- | --- | +| `curate-bars-1d` (1-thread baseline) | `tools/curate-etl/README.md` (`2026-11-29`) | `cargo run -p curate-etl --release --offline -- bench-curate-bars-cmd 1000000` | `1,000,000` EOD + `227,439` QM + `2,040` splits: `decode 234.63 ms` (`4.26M rows/s`), `curate 208.07 ms`, `write 456.39 ms` (`2.06M rows/s`), **total `899.09 ms` (`1.11M rows/s`, `193.78 MB/s`)** | +| `curate-bars-1d` (`rayon` parallel write, **local re-run**) | Local sandbox re-run (`2026-11-29`, 32-thread host, synthetic) | `CARGO_BUILD_JOBS=2 cargo run --release -p curate-etl --offline -- bench-curate-bars-cmd 1000000` | Same `1,000,000`-row synthetic input: `decode 233.19 ms` (`4.29M rows/s`), `curate 207.45 ms`, `write_1 (threads=1) 445.79 ms` (`2.10M rows/s`) vs **`write (threads=32) 94.42 ms` (`9.93M rows/s`, `259.56 MB/s`, `4.72x` speedup)**, **total `535.06 ms` (`1.87M rows/s`, `325.63 MB/s`)** | +| `curate-bars-1d` (5M rows, 1-thread) | `tools/curate-etl/README.md` (`2026-11-29`) | `cargo run -p curate-etl --release --offline -- bench-curate-bars-cmd 5000000` | `5,000,000` EOD + `1.14M` QM + `4,080` splits: **total `3,525.02 ms` (`1.42M rows/s`, `247.01 MB/s`)** | +| `curate-adj-factors` | `tools/curate-etl/README.md` (`2026-11-29`) | `cargo run -p curate-etl --release --offline -- bench-curate-adj-cmd` | `500,000` events + `62,720` `bars_1d`: **total `436.90–500.88 ms` (`998k–1.14M events/s`)** across 2 runs | +| `curate-corporate-actions` | `tools/curate-etl/README.md` (`2026-11-29`) | `cargo run -p curate-etl --release --offline -- bench-curate-corporate-actions-cmd 1000000` | `1,000,000` events (`39,186` splits, `950,896` divs, `9,918` delistings): **total `752.71–775.67 ms` (`1.29M–1.33M events/s`)** | +| `curate-fx-1d` | `tools/curate-etl/README.md` (`2026-11-29`) | `cargo run -p curate-etl --release --offline -- bench-curate-fx-cmd` | `20,000` FX rows (`CAD.FOREX` + `USDCAD`): **total `20.19–29.97 ms` (`667k–990k rows/s`)** | +| `curate-shorts` | `tools/curate-etl/README.md` (`2026-11-29`) | `cargo run -p curate-etl --release --offline -- bench-curate-shorts-command` | `700,000` `ceoShorts` docs (`64.78 MiB`): **total `365.73–369.48 ms` (`1.89M–1.91M rows/s`)**, `peak_chunk_bytes = 8 MiB` | +| `curate-events` | `tools/curate-etl/README.md` (`2026-11-29`) | `cargo run -p curate-etl --release --offline -- bench-curate-events-cmd` | `500,000` rows (`492.5k` filings, `7.5k` earnings): **total `838.71–861.10 ms` (`581k–596k rows/s`)**; linear synthetic extrapolation to `30.96M` rows: `51.9–53.3 s` single-core | +| `bson_eod_prices` decode-only | `tools/curate-etl/README.md` (`2026-11-28`) | `cargo run --release -p curate-etl --offline -- bench-bson-eod-prices` | `1,000,000` docs (`272.4 MiB`): **`217.38–221.82 ms` (`4.51M–4.60M rows/s`, `1.23–1.25 GB/s`)** | +| `bson_stream` short-read | `tools/curate-etl/README.md` (`2026-11-28`) | `cargo run --release -p curate-etl --offline -- bench-bson-stream` | `2,000,000` docs (`544.8 MiB`): **`544.59 ms` (`3.67M rows/s`, `1.00 GiB/s`, `0.963x` vs in-memory buffer, `8 MiB` peak buffer)** | +| `parquet_bars` write-only | `tools/curate-etl/README.md` (`2026-11-28`) | `cargo run --release -p curate-etl --offline -- bench-parquet-bars` | `5,000,000` rows, 20 year files: **`1,422.27 ms` (`3.52M rows/s`, `155.11 MB/s`, `1.82x` Zstd)** | +| `split` builder | `tools/curate-etl/README.md` (date omitted in README) | `cargo run --release -p curate-etl --offline -- bench-split` | `10,000,000` synthetic rows: **`367.40 ms` (`27.22M rows/s`)** | +| `bars` builder | `tools/curate-etl/README.md` (date omitted in README) | `cargo run --release -p curate-etl --offline -- bench-bars` | `10,000,000` synthetic rows: **`842.38 ms` (`11.87M rows/s`)** | +| `provider_mapping` lookup | `tools/curate-etl/README.md` (date omitted in README) | `cargo run --release -p curate-etl --offline -- bench-provider-mapping` | `10,000,000` synthetic lookups: **`447.14 ms` (`22.36M lookups/s`)** | +| TS `export-raw-bson` | `apps/stock/data-pipeline/README.md` (`2026-11-29`) | `bun run apps/stock/data-pipeline/benchmarks/export-raw-bson-benchmark.ts` | `1,000,000` synthetic `eodPrices` frames (`123.9 B` avg): **`270.8–279.8 ms` (`3.57M–3.69M docs/s`, `422–436 MiB/s`, `peak_rss 150–151 MiB`)**; `2M` docs: `3.83M docs/s`, `peak_rss 146.88 MiB` | +| TS `export-curate-inputs` | `apps/stock/data-pipeline/README.md` (`2026-11-29`) | `bun run apps/stock/data-pipeline/benchmarks/export-curate-inputs-benchmark.ts` | `500k` mappings + `100k` listings + `2k` OTC (`606,680` TSV rows, `17.2 MB`): **`402.8 ms` (`1.51M rows/s`, `277.01 MiB` peak RSS)** | +| TS `sample-closes` (Pass 4a) | `apps/stock/data-pipeline/README.md` (`2026-11-28`) | `bun run apps/stock/data-pipeline/benchmarks/sample-closes-benchmark.ts` | `500,025` synthetic docs (25 dates × 20k IDs + FX): **`190.3 ms` (`2.63M docs/s`)** | +| TS `source-symbol-readers` | `apps/stock/data-pipeline/README.md` (`2026-11-28`) | `bun test test/unit/security-master-source-symbol-readers.test.ts` | `368,000` synthetic symbol docs: **`488.0 ms` (`754k docs/s`)** | +| TS `security-type` classifier | `apps/stock/data-pipeline/README.md` (`2026-11-28`) | `bun test test/unit/security-master-security-type.test.ts` | `300,000` synthetic EOD records (`100k` distinct ISIN buckets, `20` conflicting ISINs): **`70.1 ms` (`4.28M records/s`, floor `>= 100k records/s`)** | +| TS `run.ts` composer (Passes 3–6) | `apps/stock/data-pipeline/README.md` (`2026-11-28`) | `bun test test/unit/security-master-run.test.ts` | `100,000` synthetic source records end-to-end: **`479.6 ms` (`208.5k records/s`)** | +| TS `persistSecurityMaster` | `apps/stock/data-pipeline/README.md` (`2026-11-28`, host Postgres safety schema) | `bun --env-file=/home/boki/.studio/test-env/stock-bot.env test test/postgres/security-master-persist.test.ts` | `20k` instruments + `20k` listings + `60k` mappings (`140k` total rows): **`2.36 s` full test wall time (`>= 59.3k total rows/s`)** | +| TS `source-field-shapes` probe | `apps/stock/data-pipeline/README.md` (`2026-11-28`) | `bun run apps/stock/data-pipeline/benchmarks/source-field-shapes-benchmark.ts` | `80,000` synthetic docs (8 collections × 10k): **`218.7 ms` (`365.8k docs/s`)** | + +--- + +## 3. Workload Classification by Area + +Row volumes come from the measured 2026-11-26 QA MongoDB inventory in `design/data-pipeline/phase1-investigation.md` and `design/DATA-CONTRACTS.md` §1. + +| Area / Pipeline Stage | Raw / Target Volume | Bottleneck Class | Run Cadence | Rust Value-Add | +| --- | --- | --- | --- | --- | +| Pass 1 Exchanges (`exchange-pass1.ts`, `generate-exchange-seed.ts`) | `319` rows (`eodExchanges` 76, `ibExchanges` 214, `qmExchanges` 25, `ceoExchanges` 4) | **Logic / human-review-bound** | Rare (initial seed + schema override migrations) | **None** | +| Pass 2–3–5–6 Security Master (`source-symbol-readers.ts`, `instrument-stage-a.ts`, `listing-stage-b.ts`, `delisting-chains.ts`, `match-report.ts`, `run.ts`, `persist.ts`) | `396,041` symbol docs (`eodSymbols` 317.8k, `qmSymbols` 47.2k, `ibSymbols` 18.4k, `ceoSymbols` 12.6k) + `230` `eodSymbolChange` | **Logic / edge-case / review-bound** (ISIN Luhn + CUSIP rescue, IB ATS venues, ticker-reuse spans, OTC delisting chains, override precedence) | Infrequent (initial US+CA build, then periodic delta refreshes) | **Negligible** (TS already does `100k` records in `0.48 s` and `140k` PG rows in `2.36 s`) | +| Pass 2 `bar-spans.ts` & Pass 4 `sample-closes.ts` | Server-side Mongo `$group` on `eodPrices`/`qmPrices` + 25-date `$in` slice (~500k docs) | **MongoDB index/server I/O-bound** | Same as security master | **Negligible** (MongoDB server does the scan; TS client processes 500k closes in `0.19 s`) | +| TSV Export (`export-curate-inputs.ts`) | ~100k–500k PostgreSQL rows (~17 MB) | **Small Postgres read** | Before each curation batch | **Negligible** (`0.40 s` synthetic; ~17 MB on disk) | +| Field-Shape Probe (`source-field-shapes.ts`) | `<= 80,000` sampled docs (`8 × 10k`) | **Diagnostic / interactive** | Occasional schema check | **None** | +| Service Control Plane (`handlers/`, `repositories/`, `routes/`, `index.ts`) | Legacy BullMQ sync jobs + `GET /health` | **Control-plane / queue glue** | Always-on daemon (low QPS) | **Negative** (BullMQ/DI/Hono already in TS) | +| **M1 Bulk Raw-BSON Export → Parquet (`eodPrices`, `qmPrices`, `qmFilings`, `qmDividends`, `qmSplits`, `ceoShorts`, `qmEarnings`, `teMarketData`)** | **`845.7M` `eodPrices` + `51.5M` `qmPrices` + `30.5M` `qmFilings` + `1.65M` others** | **CPU + NVMe-scratch / throughput-bound** | Full backfill + nightly/weekly incremental | **High — already in Rust for curation; JS file hop adds huge NVMe scratch write+read** | +| **M2 Bulk Raw-BSON → Parquet / QuestDB ILP v2 (`eodIntraday1M`, `qmIntraday`, `ceoPosts`, `qmFinancials`)** | **`3.40B` `eodIntraday1M` + `173.3M` `qmIntraday` + `14.8M` `ceoPosts` + `2.77M` `qmFinancials`/`-old`** | **CPU + NVMe-scratch + network/ILP throughput-bound** | Multi-billion-row backfill + incremental | **Critical — staging `3.57B` intraday docs through local `.bson` files is an estimated ~499–832 GiB peak capacity (~998–1,664 GiB total write+read I/O) NVMe bottleneck** | + +### Why the Intermediate `.bson` File Hop Hurts at M1/M2 Scale + +Even though `export-raw-bson.ts` avoids JS object deserialization (`3.57M–3.83M docs/s` synthetic), it writes every raw document to `.bson` on NVMe before `curate-etl` reads the file back (so total NVMe bytes moved is **2×** the peak file size, using binary `1 GiB = 2^30` bytes throughout): + +- **M1 `eodPrices` (`845.7M` docs):** Under the synthetic average frame-size assumption of `161.7–285.6 B/doc` (`bench-curate-bars-cmd` / `bench-bson-eod-prices`), staging `eodPrices.bson` requires roughly **~127–225 GiB peak scratch file capacity** and **~255–450 GiB total NVMe I/O (write + read-back)** before `qmPrices` (`51.5M`) and `qmFilings` (`30.5M`). +- **M2 intraday (`3.40B` `eodIntraday1M` + `173.3M` `qmIntraday` = `3.57B` docs):** Under an assumed synthetic `150–250 B/doc` average frame size, staging both intraday collections to `.bson` files requires roughly **~499–832 GiB peak scratch file capacity** and **~998–1,664 GiB total NVMe I/O (write + read-back)** on `quant`'s 4 TB SN850X NVMe (which also holds the `~638 GB` MongoDB corpus, PostgreSQL, QuestDB, and curated Parquet). Eliminating that intermediate file via direct Rust `RawDocumentBuf` cursors saves that entire scratch file footprint and extra NVMe write+read pass. *(All byte-size figures are extrapolated from synthetic documents; actual live BSON document sizes are unverified — see Section 7.)* + +--- + +## 4. Options Comparison + +| Dimension | Option A: Keep Current TS + File-Bridge Rust Split | Option B: Direct Read-Only MongoDB Streaming in `tools/curate-etl` (Recommended) | Option C: Full Port of `apps/stock/data-pipeline` to Rust | +| --- | --- | --- | --- | +| **Architecture** | Status quo (`PLATFORM-PLAN.md` §4): TS owns security master, TSV export, raw-BSON export, probes, BullMQ/HTTP; Rust `curate-etl` reads local TSV + `.bson` files | TS keeps security master (Passes 1–6), TSV export (`export-curate-inputs.ts`), probes, BullMQ/HTTP. Rust `curate-etl` gains a read-only MongoDB cursor adapter (`--mongo-uri` / `MONGODB_READ_URI`) feeding the existing `RawDocumentBuf` decoders directly, while **retaining** file-based CLI mode for offline/reproducible tests | Rewrite all 42 TS files (`20,349` LOC) + 47 test files (`35,193` LOC) in Rust (security master, Postgres persistence, TSV/direct PG read, probes, BullMQ worker, HTTP `/health`, plus direct Mongo cursors) | +| **Estimated Effort** | **0 new files/LOC** for M1 bridge; in M2 must extend `RAW_BSON_EXPORT_COLLECTIONS` and add scratch-space management / chunked export for `3.40B` `eodIntraday1M` | **Two-stage effort:**
1. **Cursor-only swap (~4–6 new `.rs` files, ~1,200–1,800 LOC + ~1,000–1,500 test LOC):** Rust `env-safety` URI/host/user read-only guard, sealed `mongodb` read-only `RawDocumentBuf` cursor adapter, and `--mongo-uri` / `--collection` CLI wiring alongside existing file mode.
2. **Bounded-memory partitioning & overlapped I/O (additional ~3–5 `.rs` files / runner refactors, ~1,500–2,500 LOC + ~1,500–2,000 test LOC):** Date/year or key-range partitioned streaming in `run_curate_bars.rs` and `run_curate_events.rs` (which currently accumulate all decoded rows in RAM before sorting/curation) plus bounded channel pipelining between MongoDB cursor reads and `rayon` Parquet / ILP writes.
**Combined:** ~7–11 files, ~2,700–4,300 LOC + ~2,500–3,500 test LOC | **Very large (~40+ `.rs` files, ~15,000–22,000 LOC + ~25,000–35,000 test LOC):** Re-implement Passes 1–6, `persist.ts`, `bar-spans.ts`, `sample-closes.ts`, `source-field-shapes.ts`, `PipelineSyncRepository`, BullMQ Redis protocol, Hono `/health`, and re-verify all 47 test suites (plus Option B's Stage 1+2 work) | +| **New Rust Crates Required** | None (`bson =3.1.0`, `parquet =60.2.0`, `rayon =1.12.0` stay unchanged) | `mongodb` (with `bson-3` feature matching `bson =3.1.0`), `tokio` (minimal `rt-multi-thread`/`net`/`time` for async driver), `url` (or strict custom URI parser for safety guard). *Note: keeps zero Postgres/HTTP/Redis crates in `curate-etl`.* | Everything in Option B **plus** `tokio-postgres` / `sqlx`, `axum` / `hyper` (HTTP `/health`), `redis` + custom BullMQ Lua/stream worker compatibility (no official Rust BullMQ crate), `serde` / `serde_json`, `chrono` / `time` | +| **Expected Runtime & NVMe Gain (Evidence-Backed)** | Baseline: TS `export-raw-bson` (`3.57M–3.83M docs/s` synthetic) + Rust `curate-bars-1d` (`1.87M rows/s` with `rayon` write). Pays full NVMe scratch footprint (~127–225 GiB peak / ~255–450 GiB write+read for M1 `eodPrices`; ~499–832 GiB peak / ~998–1,664 GiB write+read for M2 intraday, synthetic estimates) | **Stage 1 (cursor-only):** Eliminates intermediate `.bson` scratch files (~100% of bulk scratch NVMe capacity and the extra write+read pass) and removes the TS process hop, **without** reducing decoded-row RAM or overlapping curation/Parquet writes (since `run_curate_bars.rs` and `run_curate_events.rs` still buffer decoded rows before sorting).
**Stage 2 (partitioned streaming + pipelining):** Adds bounded-memory execution (needed for global `845.7M` `eodPrices` on `quant`'s `125 GiB` RAM) and overlaps MongoDB wire reads with Rust decode/Parquet/ILP writes.
**End-to-end wall-time speedup is unmeasured** (see Section 7). Zero change to sub-second security-master runs | Same bulk gain as Option B; **< 1–3 seconds saved** on security master (`run.ts` is already `479.6 ms` / `100k` records; `persist.ts` is `2.36 s` / `140k` rows, bound by Postgres `UNNEST` I/O; `export-curate-inputs.ts` is `402.8 ms` / `500k` rows) | +| **Key Risks** | 1. NVMe capacity/wear spike on `quant` when exporting `3.57B` intraday docs to `.bson` files.
2. Two-step manual/scripted orchestration per bulk collection | 1. **Safety-guard parity:** Bypassing TS `assertEnvironmentSafety()` and `MongoDBClient` `mongoReadOnly: true` requires a battle-tested Rust read-only guard (blocking `trading_admin`, loopback/LAN IPv4 variants, and any write command).
2. **Memory scope:** A cursor swap alone does not bound RAM on global `845.7M` `eodPrices` until Stage 2 partitioning lands.
3. **Crate/async footprint:** Adds `mongodb` + `tokio` to Cargo workspace (requires crates.io fetch and offline cache refresh). | 1. **Pass 1–6 parity risk:** Re-verifying 17,924 LOC of subtle ISIN/CUSIP/ATS/ticker-reuse/delisting-chain rules against 40 test suites.
2. **Shared TS contract loss:** Loses `@stock-bot/types` (`ReferenceDataResetRequest`), `@stock-bot/stock-config`, `@stock-bot/postgres` migrations, and BullMQ `{data-pipeline_exchanges}`/`{data-pipeline_symbols}` queue parity with `web-api`.
3. **Safety-guard duplication** for both MongoDB and PostgreSQL.
4. **Multi-week M2 delay** with no user-visible research value | +| **Impact on M2 Work Items** | Slows M2 `bars_1m` (`3.40B` `eodIntraday1M` + `173.3M` `qmIntraday` → QuestDB ILP v2) because raw `.bson` staging doesn't scale cleanly to multi-billion-row streams; `ceoPosts` (`14.8M`) and `qmFinancials` (`2.77M`) remain workable | **Directly accelerates M2:** `tools/curate-etl` streams `eodIntraday1M` (`3.40B`, **split-unadjusting** retroactively adjusted OHLCV via `qmSplits`) and `qmIntraday` (`173.3M`, taking **already-raw** `open..close` and `sharevolume` directly — **no** split un-adjustment) into multi-socket QuestDB ILP v2 (`bars_1m`, `DEDUP UPSERT KEYS(ts, listing_id)`) with zero `.bson` scratch files, verified by the M2 split-boundary comparison (`NEXM.V` `1:20` and `NVDA.US` `10:1` `bars_1m` session closes within `0.5%` of raw `bars_1d` closes); same cursor adapter serves `ceoPosts` (`14.8M`) and `qmFinancials` | **Blocks M2** for weeks while porting already-working M1 security-master code instead of building MCP, PIT fundamentals, QuestDB `10.2.0` `bars_1m`, and Feature Library | + +*Why Option B keeps `export-curate-inputs.ts` in TypeScript:* Exporting `500k` security-master mappings + `100k` listings takes `402.8 ms` (`17.2 MB`) synthetically and already ships with atomic `/current` generation pinning consumed by `curate-etl --curate-inputs`. Keeping it in TypeScript avoids pulling a PostgreSQL driver and `assertSecurityMasterPersistSafety()` duplication into `tools/curate-etl`. + +--- + +## 5. Compliance Check (`D1`–`D12` & QA Database Safety Rules) + +### Locked Decisions `D1`–`D12` (`design/PLATFORM-PLAN.md` §3) + +| Decision | Option A | Option B (Recommended) | Option C | +| --- | --- | --- | --- | +| **D1** (Parquet+DuckDB daily/PIT; QuestDB `10.2.0` intraday) | Compliant | Compliant (directly enables M2 `3.40B` ILP v2 streaming to QuestDB) | Compliant | +| **D2** (Desktop copilot MCP; isolated campaign containers) | Compliant | Compliant | Compliant | +| **D3** (US+CA priority + FX; `ttFutures` out of scope) | Compliant | Compliant | Compliant | +| **D4** (Incremental `web-app` evolution; no rewrite) | Compliant | Compliant | Risk of `web-api` / `PipelinePage` BullMQ contract drift | +| **D5** (Cross-source entity resolution in `data-pipeline`) | Compliant | Compliant — matches `PLATFORM-PLAN.md` §4 (`data-pipeline` TS + `curate-etl` Rust) and `DATA-CONTRACTS.md` §3A (`mongodb::bson::RawDocumentBuf` cursors) | **Reopens §4 layer table** (moves TS entity resolution & orchestration out of TS `data-pipeline` into Rust; requires director sign-off to amend `PLATFORM-PLAN.md`) | +| **D6** (IB Margin `USD`/`CAD` on isolated `9900K`) | Compliant (no paper/live touch) | Compliant (no paper/live touch) | Compliant (no paper/live touch) | +| **D7** (Multi-strategy scope; no macro surprises / Form 4 $) | Compliant | Compliant | Compliant | +| **D8** (Incremental Research Playground) | Compliant | Compliant | Compliant (delays M2 timeline) | +| **D9** (`marimo` Python labs) | Compliant | Compliant | Compliant | +| **D10** (Rolling 6-month Air-Gapped Vault + Post-2023 Recency) | Compliant | Compliant | Compliant | +| **D11** (Materialized batch feature jobs; no Python→TS rewrites) | Compliant | Compliant | Compliant | +| **D12** (Read-only Studio `library.yml` + Postgres findings) | Compliant | Compliant | Compliant | + +### QA Database Safety Rules (`AGENTS.md`) + +| Safety Rule | Option A | Option B (Recommended) | Option C | +| --- | --- | --- | --- | +| **Never drop/reset/write QA MongoDB (`localhost:27017/stock`) from `dev` or tests** | Enforced by `assertEnvironmentSafety()` + `MongoDBClient` `mongoReadOnly: true` + `studio_stock_bot_read` | **Must implement Rust read-only guard parity** before enabling `--mongo-uri`: (1) connect strictly via `MONGODB_READ_URI` with server-side `read@stock` user (`studio_stock_bot_read`); (2) reject `trading_admin` and any non-read-only URI targeting loopback/local-LAN port `27017` (matching `env-safety.ts` IPv4/octal/hex/loopback rules); (3) expose **only** `find` / `RawDocumentBuf` cursor reads in a sealed Rust module with no `insert`/`update`/`delete`/`drop`/`create_index`/`run_command` surface; (4) unit-test all rejected URIs offline | Requires Option B's Rust Mongo guard **plus** full Rust parity for PostgreSQL dev-isolation guards (`assertSecurityMasterPersistSafety`, `NODE_ENV=development` blocking `localhost:5432/trading_bot`, `pg_advisory_xact_lock`, and `rejectDestructiveSync`) | +| **Tests never mutate QA Postgres (`trading_bot`) or QA Mongo (`stock`)** | Compliant (`stock_bot_safety*` + in-memory fakes) | Compliant — retain file-based CLI mode so all `cargo test --workspace --lib --offline` tests run with zero DB connections | Compliant only if every ported Postgres test preserves isolated `stock_bot_safety*` schema creation/teardown | +| **No `data-ingestion` or `9900K` live/paper side effects** | Compliant | Compliant | Compliant | + +--- + +## 6. Recommendation, Implied Follow-Up Tasks & What Not to Port + +### Recommendation + +**Select Option B.** It captures virtually 100% of the real throughput and NVMe-storage benefit of Rust where the data is actually large (`845.7M` `eodPrices`, `51.5M` `qmPrices`, `30.5M` `qmFilings`, and M2's `3.40B` `eodIntraday1M` + `173.3M` `qmIntraday` + `14.8M` `ceoPosts`), aligns word-for-word with `design/PLATFORM-PLAN.md` §4 and `design/DATA-CONTRACTS.md` §3A, requires no reopened locked decisions, and avoids risking or delaying M2 to rewrite 20k LOC of already-fast, heavily-tested TypeScript security-master logic. + +### Implied Follow-Up Tasks (Director-Gated — Not Yet Queued or Enacted) + +If the director approves Option B, the concrete follow-up sequence is: + +1. **Add Rust read-only MongoDB safety guard (`tools/curate-etl/src/mongo_safety.rs`):** Port the URI/host/loopback/IPv4-normalization and `trading_admin`-blocking rules from `apps/stock/config/src/env-safety.ts` with offline unit tests mirroring `test/unit/environment-safety*.test.ts`. +2. **Add sealed read-only MongoDB `RawDocumentBuf` cursor adapter (`tools/curate-etl/src/mongo_stream.rs`):** Add exact-pinned `mongodb` (`bson-3`) + minimal `tokio` to `tools/curate-etl/Cargo.toml`, exposing only allowlisted read-only `find` streams feeding the existing `bson_*` decoders (zero write/admin methods exposed). +3. **Wire `--mongo-uri` / `MONGODB_READ_URI` cursor mode into `curate-bars-1d` and `curate-events` (Stage 1 — cursor swap + adoption parity & provenance checks):** Allow bulk M1 commands to stream directly from read-only QA MongoDB without intermediate `.bson` files while preserving `--eod-prices ` file mode for offline fixture replay. **Adoption gate:** assert byte-identical file-versus-cursor output parity on pinned fixtures, and emit a per-run provenance manifest recording the source snapshot or retained input identifier, exact query bounds (`filter`/date bounds and run timestamp), and the pinned `curate-inputs` security-master `generationId` (so production datasets remain traceable even if a provider later corrects a bar or filing). +4. **Add partitioned bounded-memory streaming & overlapped read/write pipelining to `curate-bars-1d` and `curate-events` (Stage 2 — global-backfill RAM & I/O):** Partition MongoDB queries by calendar year or listing-key range and pipeline async cursor reads with `rayon` Parquet writes so global `845.7M` `eodPrices` and `30.5M` `qmFilings` runs fit comfortably inside `quant`'s `125 GiB` RAM instead of buffering all decoded rows in memory. +5. **Reuse the Rust cursor adapter for M2 `curate-bars-1m` (QuestDB `10.2.0` ILP v2) and `curate-ceo-posts`:** Stream `eodIntraday1M` (`3.40B`, **un-adjusting** retroactively split-adjusted OHLCV via `qmSplits`), `qmIntraday` (`173.3M`, ingesting **already-raw** `open..close` and `sharevolume` directly without split un-adjustment), `CAD.FOREX` `1m` (`5.2M`), and `ceoPosts` (`14.8M`) directly from read-only MongoDB with zero `.bson` scratch files; enforce the M2 exit-criterion split-boundary comparison on `NEXM.V` (`1:20`) and `NVDA.US` (`10:1`) confirming `bars_1m` session closes match raw `bars_1d` closes within `0.5%`. +6. **Keep `run-export-raw-bson.ts` as a diagnostic/fixture tool (optional deprecation later):** Retain T-117 for bounded `--limit` fixture captures and offline debugging; remove it from the bulk production path once Step 3 (and Step 4 for global backfills) is verified on `quant`. + +### What Should NOT Be Ported to Rust + +- **Pass 1–6 Security Master (`apps/stock/data-pipeline/src/security-master/` — 17,924 LOC, 40 test files):** Logic- and review-bound, runs in sub-second synthetic time, and has complex domain heuristics (ISIN/CUSIP rescue, IB ATS routing, ticker-reuse spans, OTC delisting chains, override precedence) that are faster to inspect and iterate in TypeScript. +- **PostgreSQL Security-Master Persistence (`persist.ts`) & TSV Exporter (`export-curate-inputs.ts`):** Already batched via `UNNEST` / server-side `NO SCROLL` cursor (`2.36 s` / `140k` rows; `0.40 s` / `500k` mappings) and tightly integrated with `@stock-bot/postgres` migrations and `assertSecurityMasterPersistSafety()`. +- **Field-Shape Probe (`source-field-shapes.ts` / `probe-source-field-shapes.ts`):** Bounded `<= 10k`-doc diagnostic utility. +- **Service Control Plane (`handlers/`, `repositories/`, `routes/`, `index.ts`):** BullMQ `{data-pipeline_exchanges}`/`{data-pipeline_symbols}` queue consumers (`getFullQueueName` in `libs/core/queue/src/service-utils.ts`), `PipelineSyncRepository`, and Hono `GET /health` tightly integrated with `@stock-bot/di`, `@stock-bot/queue`, `@stock-bot/types`, and `web-api`. + +--- + +## 7. Not Verified + +The following items were **not measured** in this docs-only spike and can only be verified on the `quant` host (`10.0.0.51`) or against live read-only QA MongoDB / dev PostgreSQL: + +1. **Live MongoDB cursor throughput, WiredTiger contention, and end-to-end Option B wall-time speedup:** All `export-raw-bson.ts` (`3.57M–3.83M docs/s`) and `curate-etl` (`1.87M rows/s` with `rayon` write) numbers are local synthetic benchmarks. Actual `quant` wall time and the net end-to-end speedup of Option B (both Stage 1 cursor-only and Stage 2 overlapped I/O) are **unmeasured** and depend on WiredTiger disk reads (`--wiredTigerCacheSizeGB 16`), localhost TCP framing, BSON wire overhead on `stock` (`~638 GB`), and NVMe contention. +2. **Real BSON document sizes & NVMe scratch footprint:** The intermediate `.bson` size estimates — **~127–225 GiB peak file capacity (~255–450 GiB total write+read I/O)** for `845.7M` `eodPrices` at synthetic `161.7–285.6 B/doc`, and **~499–832 GiB peak file capacity (~998–1,664 GiB total write+read I/O)** for `3.40B` `eodIntraday1M` + `173.3M` `qmIntraday` at assumed `150–250 B/doc` (binary `1 GiB = 2^30` bytes) — extrapolate from synthetic document byte sizes; actual uncompressed BSON sizes in QA MongoDB are unmeasured. +3. **`quant` 24-thread `rayon` scaling and peak RAM:** The `4.72x` parallel Parquet write speedup (`94.42 ms` vs `445.79 ms`) was measured locally on a 32-thread host on `1,000,000` synthetic rows. Peak RAM and scaling on `quant` (`12900K`, 24 threads, `125 GiB` RAM) for the US+CA subset (~100–150M `eodPrices` rows, estimated `20–30 GiB` peak RAM) vs. full `845.7M` global rows (`> 160 GiB` unsharded, requiring date/key sharding or `--threads 1`) remain unverified. +4. **Live `bar-spans.ts` and Pass 4 `sample-closes.ts` wall time:** MongoDB `$group` aggregation time on `845.7M` `eodPrices` and `51.5M` `qmPrices`, plus live 25-date `{ date: { $in: sampleDates } }` index selectivity, have not been timed against live QA MongoDB. +5. **Unverified live provider field shapes:** Exact field names and BSON types on live QA MongoDB for `ceoShorts` (`--shares-short-field`, `timestamp` unit), `qmFilings` (`--filings-form-type-field`, `symbol` vs `qmSearchCode`), `qmEarnings` optional fields, `qmDividends` (`amount`/`currency`), `teMarketData` (`t` epoch unit), and `qmPrices.date` string vs `DateTime` format remain pending the first host run of `probe-source-field-shapes.ts`. +6. **QuestDB `10.2.0` ILP v2 throughput (M2):** Multi-socket Rust ILP v2 ingestion rate into `bars_1m` (`PARTITION BY MONTH`, `DEDUP UPSERT KEYS(ts, listing_id)`) on `quant` has not been benchmarked. +7. **Rust `mongodb` crate compile time and transitive crate count:** Exact transitive dependency footprint and offline build time for `mongodb` (`bson-3`) + `tokio` inside this workspace have not been measured because this spike adds no crates. diff --git a/test/unit/data-pipeline-rust-evaluation-doc.test.ts b/test/unit/data-pipeline-rust-evaluation-doc.test.ts new file mode 100644 index 00000000..aa5f1489 --- /dev/null +++ b/test/unit/data-pipeline-rust-evaluation-doc.test.ts @@ -0,0 +1,192 @@ +import { describe, expect, test } from 'bun:test'; +import { existsSync, readFileSync } from 'node:fs'; +import { dirname, join, resolve } from 'node:path'; + +// Guards the T-124 decision brief (design/data-pipeline/rust-migration-evaluation.md) against +// silent drift: it must stay linked, keep its seven required sections, keep internally consistent +// totals and derived figures, and every quoted benchmark figure must still appear verbatim in the +// README it cites. Live file counts are deliberately not pinned here (they change with every +// data-pipeline task); the document's own reproducible commands cover that at its commit. +const repoRoot = join(import.meta.dir, '..', '..'); +const evalRel = 'design/data-pipeline/rust-migration-evaluation.md'; +const evalPath = join(repoRoot, evalRel); +const designReadmePath = join(repoRoot, 'design/README.md'); +const curateReadme = readFileSync(join(repoRoot, 'tools/curate-etl/README.md'), 'utf8'); +const pipelineReadme = readFileSync(join(repoRoot, 'apps/stock/data-pipeline/README.md'), 'utf8'); +const doc = readFileSync(evalPath, 'utf8'); + +function num(text: string): number { + return Number(text.replace(/[`,*]/g, '').trim()); +} + +function section(title: RegExp): string { + const lines = doc.split('\n'); + const start = lines.findIndex(line => /^## /.test(line) && title.test(line)); + expect(start).toBeGreaterThan(-1); + const rest = lines.slice(start + 1); + const end = rest.findIndex(line => /^## /.test(line)); + return rest.slice(0, end === -1 ? undefined : end).join('\n'); +} + +function tableRows(body: string, firstCell: RegExp): string[][] { + return body + .split('\n') + .filter(line => line.startsWith('|')) + .map(line => line.split('|').slice(1, -1).map(cell => cell.trim())) + .filter(cells => firstCell.test(cells[0] ?? '')); +} + +describe('data-pipeline Rust migration evaluation document', () => { + test('design/README.md links to the evaluation and the link resolves', () => { + const readme = readFileSync(designReadmePath, 'utf8'); + expect(readme).toContain('](data-pipeline/rust-migration-evaluation.md)'); + expect(existsSync(evalPath)).toBe(true); + }); + + test('contains all seven required sections in order', () => { + const headings = doc.split('\n').filter(line => /^## \d\./.test(line)); + expect(headings.map(h => h.match(/^## (\d)\./)![1])).toEqual(['1', '2', '3', '4', '5', '6', '7']); + expect(headings[0]).toMatch(/Inventory/); + expect(headings[1]).toMatch(/Rust/); + expect(headings[2]).toMatch(/Workload Classification/); + expect(headings[3]).toMatch(/Options Comparison/); + expect(headings[4]).toMatch(/Compliance/); + expect(headings[5]).toMatch(/Recommendation/); + expect(headings[6]).toMatch(/Not Verified/); + }); + + test('inventory covers the T-89/T-105 CLI, T-116 TSV exporter, T-117 raw-BSON exporter and web-api coupling', () => { + const inventory = section(/^## 1\./); + for (const needle of ['T-89', 'T-105', 'T-116', 'T-117', 'run-security-master.ts', 'export-curate-inputs.ts', 'export-raw-bson.ts', '{data-pipeline_exchanges}', '{data-pipeline_symbols}', 'getFullQueueName', '@stock-bot/types', 'mongoReadOnly: true', 'assertEnvironmentSafety()']) { + expect(inventory).toContain(needle); + } + // The commands that make the counts reproducible are printed verbatim. + expect(inventory).toContain("find \"apps/stock/data-pipeline/src/$area\" -type f -name '*.ts'"); + }); + + test('every path referenced by the inventory commands exists', () => { + const inventory = section(/^## 1\./); + const block = inventory.match(/```bash\n([\s\S]*?)```/)![1]!; + for (const area of ['security-master', 'normalization', 'handlers', 'repositories', 'routes', 'types']) { + expect(existsSync(join(repoRoot, 'apps/stock/data-pipeline/src', area))).toBe(true); + } + const paths = new Set(block.match(/(?:apps|test|tools)\/[\w./-]+/g) ?? []); + expect(paths.size).toBeGreaterThan(0); + for (const path of paths) { + expect({ path, exists: existsSync(join(repoRoot, path)) }).toEqual({ path, exists: true }); + } + }); + + test('per-area inventory rows sum to the stated src/ total', () => { + const rows = tableRows(section(/^## 1\./), /^`(security-master|normalization|handlers|repositories|routes|types)\/`$|^`index\.ts`$|Total/); + const areas = rows.filter(r => !/Total/.test(r[0]!)); + const total = rows.find(r => /Total/.test(r[0]!))!; + expect(areas).toHaveLength(7); + const sum = (col: number) => areas.reduce((acc, r) => acc + (Number.isNaN(num(r[col]!)) ? 0 : num(r[col]!)), 0); + expect(sum(1)).toBe(num(total[1]!)); + expect(sum(2)).toBe(num(total[2]!)); + // pipeline-safety.test.ts is attributed to handlers/ and shared with repositories/ (counted once). + expect(sum(3)).toBe(num(total[3]!)); + expect(sum(4)).toBe(num(total[4]!)); + }); + + test('curate-etl module groups sum to the stated Rust total and the non-test/test split', () => { + const rows = tableRows(section(/^## 2\./), /./).filter(r => /^\d/.test(r[1]?.replace(/\*/g, '') ?? '')); + const total = rows.find(r => /Total/.test(r[0]!))!; + const groups = rows.filter(r => r !== total); + const tests = groups.find(r => /test modules/.test(r[0]!))!; + const files = groups.reduce((acc, r) => acc + num(r[1]!), 0); + const loc = groups.reduce((acc, r) => acc + num(r[2]!), 0); + expect(files).toBe(num(total[1]!)); + expect(loc).toBe(num(total[2]!)); + expect(total[3]).toContain(`${files - num(tests[1]!)} non-test files (${(loc - num(tests[2]!)).toLocaleString('en-US')} LOC)`); + expect(total[3]).toContain(`${num(tests[1]!)} test files (${num(tests[2]!).toLocaleString('en-US')} LOC)`); + }); + + test('derived figures in the brief are arithmetically consistent', () => { + // 88.1% of src/ LOC is security-master/. + expect(doc).toContain('88.1%'); + expect(((17_924 / 20_349) * 100).toFixed(1)).toBe('88.1'); + // rayon write speedup from the dated local re-run. + expect(doc).toContain('4.72x'); + expect((445.79 / 94.42).toFixed(2)).toBe('4.72'); + // Scratch estimates are binary GiB: docs x bytes/doc / 2^30, total I/O = 2x peak. + const gib = (docs: number, bytes: number) => Math.round((docs * bytes) / 2 ** 30); + expect([gib(845.7e6, 161.7), gib(845.7e6, 285.6)]).toEqual([127, 225]); + expect([gib(3.40e9 + 173.3e6, 150), gib(3.40e9 + 173.3e6, 250)]).toEqual([499, 832]); + expect(doc).toContain('~127–225 GiB'); + expect(doc).toContain('~255–450 GiB'); + expect(doc).toContain('~499–832 GiB'); + expect(doc).toContain('~998–1,664 GiB'); + expect(doc).not.toMatch(/\d\s?GB peak/); + }); + + test('every README-sourced benchmark row quotes figures present in the cited README', () => { + const rows = tableRows(section(/^## 2\./), /./).filter(r => /README\.md/.test(r[1] ?? '')); + expect(rows.length).toBeGreaterThanOrEqual(15); + for (const [name, source, command, result] of rows) { + const readme = source!.includes('tools/curate-etl/README.md') ? curateReadme : pipelineReadme; + // Each row states a date or explicitly says the README omits one. + expect({ name, dated: /\d{4}-\d{2}-\d{2}|date omitted/.test(source!) }).toEqual({ name, dated: true }); + // The command is copied in full (no ellipsis abbreviations) and appears in the README. + const cmd = command!.replace(/`/g, ''); + expect({ name, abbreviated: cmd.includes('...') || cmd.includes('…') }).toEqual({ name, abbreviated: false }); + const bin = cmd.match(/-- (\S+)/)?.[1] ?? cmd.match(/(\S+\.(?:test\.)?ts)/)?.[1]; + expect({ name, bin, inReadme: readme.includes(bin!) }).toEqual({ name, bin, inReadme: true }); + // Every millisecond figure in the bolded result appears verbatim in the README. + const bold = (result!.match(/\*\*([^*]+)\*\*/g) ?? []).join(' '); + for (const ms of bold.match(/[\d,]+\.\d+(?= ms)/g) ?? []) { + expect({ name, ms, inReadme: readme.includes(ms) || readme.includes(ms.replace(/,/g, '')) }).toEqual({ name, ms, inReadme: true }); + } + } + }); + + test('the only non-README benchmark is a labelled local synthetic re-run, never quant or live Mongo', () => { + const rows = tableRows(section(/^## 2\./), /^`/).filter(r => r.length === 4 && !/README\.md/.test(r[1]!)); + expect(rows).toHaveLength(1); + const [, source, command] = rows[0]!; + expect(source).toMatch(/Local sandbox re-run/); + expect(source).toMatch(/2026-11-29/); + expect(source).toMatch(/synthetic/); + expect(command).toContain('--offline'); + expect(section(/^## 2\./)).toContain('Zero Live QA MongoDB or `quant` Runs'); + }); + + test('options table compares at least three options across the required dimensions', () => { + const body = section(/^## 4\./); + const header = body.split('\n').find(line => line.startsWith('| Dimension'))!; + expect(header.match(/Option [A-Z]/g)!.length).toBeGreaterThanOrEqual(3); + for (const dim of ['Estimated Effort', 'New Rust Crates Required', 'Expected Runtime', 'Key Risks', 'Impact on M2']) { + expect(body).toContain(dim); + } + expect(body).toMatch(/End-to-end wall-time speedup is unmeasured/); + }); + + test('compliance matrix covers D1–D12 and QA safety rules for every option', () => { + const body = section(/^## 5\./); + for (let d = 1; d <= 12; d++) { + const row = tableRows(body, new RegExp(`^\\*\\*D${d}\\*\\*`)); + expect({ d, rows: row.length, cells: row[0]?.length }).toEqual({ d, rows: 1, cells: 4 }); + } + expect(body).toMatch(/Reopens §4 layer table/); + for (const needle of ['studio_stock_bot_read', 'trading_admin', 'stock_bot_safety*']) { + expect(body).toContain(needle); + } + }); + + test('gives exactly one recommendation, director-gated follow-ups and a non-port list', () => { + const body = section(/^## 6\./); + expect(body.match(/\*\*Select Option [A-C]\.\*\*/g)).toEqual(['**Select Option B.**']); + expect(body).toMatch(/Director-Gated — Not Yet Queued or Enacted/); + expect(body.match(/^\d+\. \*\*/gm)!.length).toBeGreaterThanOrEqual(3); + expect(body).toContain('### What Should NOT Be Ported to Rust'); + }); + + test('every relative Markdown link in the brief resolves', () => { + const links = [...doc.matchAll(/\]\(([^)#\s]+)(?:#[^)]*)?\)/g)].map(m => m[1]!).filter(l => !/^[a-z]+:/i.test(l)); + for (const link of links) { + const target = resolve(dirname(evalPath), link); + expect({ link, exists: existsSync(target) }).toEqual({ link, exists: true }); + } + }); +}); diff --git a/tools/curate-etl/README.md b/tools/curate-etl/README.md index cec33908..3ee2358d 100644 --- a/tools/curate-etl/README.md +++ b/tools/curate-etl/README.md @@ -1,6 +1,6 @@ # `curate-etl` -Dedicated Rust crate (three exact-pinned direct dependencies: `bson` `=3.1.0` with `default-features = false, features = ["compat-3-0-0"]`, `parquet` `=60.2.0` with `default-features = false, features = ["zstd"]`, and `rayon` `=1.12.0`) for the `M1.2a` split-factor lookup table / bar un-adjustment core, the `M1.2b` pure `adj_factors` builder, the `M1.2c` pure `corporate_actions` event-log builder, the `M1.2d` pure `bars_1d` daily bar builder + `qmPrices.sharevolume` cross-check, the `M1.2e` pure `fx_1d` USD/CAD builder + carry-forward lookup, the `M1.2f` pure `shorts` (`ceoShorts`) point-in-time builder + Canadian TSX business-day / `America/Toronto` DST calendar, the `M1.2g` pure `events` (`qmFilings` + `qmEarnings`) point-in-time builder, the `M1.2h` pure in-RAM `provider_mapping` `(source, source_id, bar_date) -> listing_id` lookup table, the `M1.2i` streaming Zstd Parquet writer for `bars_1d`, the `M1.2j` streaming Zstd Parquet writer for `shorts`, the `M1.2k` streaming Zstd Parquet writer for `events`, the `M1.2l` streaming Zstd Parquet writer for `fx_1d`, the `M1.2m` streaming Zstd Parquet writer for `adj_factors`, the `M1.2n` streaming Zstd Parquet writer for `corporate_actions`, the `M1.2o` zero-copy raw BSON decoder for `eodPrices`, the `M1.2w` zero-copy raw BSON decoders for `qmSplits` and `qmDividends`, the `M1.2y` bounded-memory streaming reader for concatenated raw BSON (`bson_stream`), the `M1.2ad` `ceoShorts` decoder + `curate-shorts` command, the `M1.2ae` `qmFilings` / `qmEarnings` decoders + `curate-events` command, the `M1.2ah` zero-copy `qmPrices` decoder + optional `--qm-prices` volume cross-check in `curate-bars-1d`, and the `M1.2ai` `rayon` year-sharded parallel Zstd Parquet writer (`--threads`) for `curate-bars-1d`. +Dedicated Rust crate (three exact-pinned direct dependencies: `bson` `=3.1.0` with `default-features = false, features = ["compat-3-0-0"]`, `parquet` `=60.2.0` with `default-features = false, features = ["zstd"]`, and `rayon` `=1.12.0`) for the `M1.2a` split-factor lookup table / bar un-adjustment core, the `M1.2b` pure `adj_factors` builder, the `M1.2c` pure `corporate_actions` event-log builder, the `M1.2d` pure `bars_1d` daily bar builder + `qmPrices.sharevolume` cross-check, the `M1.2e` pure `fx_1d` USD/CAD builder + carry-forward lookup, the `M1.2f` pure `shorts` (`ceoShorts`) point-in-time builder + Canadian TSX business-day / `America/Toronto` DST calendar, the `M1.2g` pure `events` (`qmFilings` + `qmEarnings`) point-in-time builder, the `M1.2h` pure in-RAM `provider_mapping` `(source, source_id, bar_date) -> listing_id` lookup table, the `M1.2i` streaming Zstd Parquet writer for `bars_1d`, the `M1.2j` streaming Zstd Parquet writer for `shorts`, the `M1.2k` streaming Zstd Parquet writer for `events`, the `M1.2l` streaming Zstd Parquet writer for `fx_1d`, the `M1.2m` streaming Zstd Parquet writer for `adj_factors`, the `M1.2n` streaming Zstd Parquet writer for `corporate_actions`, the `M1.2o` zero-copy raw BSON decoder for `eodPrices`, the `M1.2w` zero-copy raw BSON decoders for `qmSplits` and `qmDividends`, the `M1.2y` bounded-memory streaming reader for concatenated raw BSON (`bson_stream`), the `M1.2ad` `ceoShorts` decoder + `curate-shorts` command, the `M1.2ae` `qmFilings` / `qmEarnings` decoders + `curate-events` command, the `M1.2ah` zero-copy `qmPrices` decoder + optional `--qm-prices` volume cross-check in `curate-bars-1d`, the `M1.2ai` `rayon` year-sharded parallel Zstd Parquet writer (`--threads`) for `curate-bars-1d`, the `M1.2ak` read-only MongoDB URI safety guard (`mongo_safety`), and the `M1.2al` driver-independent read-only MongoDB raw-BSON cursor seam (`mongo_stream`). ## Scope & Sign Conventions @@ -1493,6 +1493,66 @@ Measured locally (`2026-11-29`, default `500,000` rows; two back-to-back runs wi - **Key-namespace alignment between `qmFilings` and `qmEarnings`:** `qmFilings` defaults to `symbol` while `qmEarnings` defaults to `qmSearchCode`. Both exports must carry an unambiguous key in the `provider_mapping` namespace (for example, the QuoteMedia security ID, not a bare ticker — the security master records distinct QuoteMedia IDs such as `VOY:CNX` and `VOY:CC` for the same symbol and exchange, so switching earnings to bare `symbol` can merge distinct identities or drop rows). If a live `qmFilings` export lacks that unambiguous key, prepare the export with verified QuoteMedia IDs and exclude unresolved rows rather than downgrading `qmEarnings` to bare tickers. - **In-RAM buffering & single-threaded execution:** decoded filings and earnings are buffered in RAM (with shared `Arc` key interning) before sorting/curation; `rayon` key-sharded streaming, direct MongoDB/PostgreSQL connections, and M2 `fundamentals_pit` joins remain out of scope. +## Read-Only MongoDB URI Safety Guard (`M1.2ak`) + +Pure, offline, `std`-only MongoDB URI safety guard (`src/mongo_safety.rs`, zero new crates, no sockets, no DNS resolution, no subprocesses) that ports the QA MongoDB target-classification rules from `apps/stock/config/src/env-safety.ts` before any Rust code may open a MongoDB connection. + +### Public API + +- `parse_mongo_target(uri: &str) -> Result` — parses `mongodb://` and `mongodb+srv://` URIs, splits authority at `/` or `?` (never `#`), percent-decodes usernames (strict UTF-8, without converting `+` to space), iteratively percent-decodes seed hosts up to `8` passes (handling bracketed IPv6 with zone IDs and `mongodb://` `.sock` Unix domain sockets), and rejects control characters, Unicode whitespace, unencoded `#` or multiple `@` in authority, `@` in path/query when authority has no credentials, invalid percent-encoding, and forbidden decoded host characters. +- `is_qa_mongo_target(target: &MongoTarget, local_hosts: &LocalHosts) -> bool` — returns `true` when any seed host is loopback (`localhost`, trailing-dot/case variants, `0.0.0.0`, `127.0.0.0/8` in dotted, shorthand `127.1`, decimal `2130706433`, hex `0x7f000001`, octal `0177.0.0.1`, leading-zero decimal `0127.0.0.1`, IPv6 `::` / `::1` with optional zone ID, and IPv4-mapped `::ffff:127.0.0.0/8` / `::ffff:0.0.0.0`) or matches an injected `LocalHosts` entry on port `27017` (or omitted/default port), regardless of database path. +- `LocalHosts` — deterministic injected set (`LocalHosts::empty()`, `new(...)`, `from_hostname_and_ips(...)`, `with_host(...)`, `contains(...)`) plus `LocalHosts::detect()`, which is **best-effort** and `std`-only (reads `HOSTNAME` and `/etc/hostname` without NIC enumeration or DNS lookups; multi-homed callers should inject LAN IPs via `LocalHosts::from_hostname_and_ips`). +- `assert_read_only_mongo_uri(uri, policy: &ReadOnlyPolicy, local_hosts) -> Result` — 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 **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"]`, 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 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. + +## Driver-Independent MongoDB Raw-BSON Cursor Seam (`M1.2al`) + +Library-only, driver-independent read-only MongoDB raw-BSON cursor seam (`src/mongo_stream.rs`, tested offline in `src/mongo_stream_tests.rs`) bridging the read-only safety model (`src/mongo_safety.rs`) into the existing `bson_stream` zero-copy decoders (`RawBsonChunkReader` and `decode_*_stream`) with zero new dependencies and zero CLI/command wiring yet. + +### Dependencies + +- **No new dependency added:** `tools/curate-etl/Cargo.toml` and `Cargo.lock` are unchanged (still three exact-pinned direct dependencies: `bson = "=3.1.0"`, `parquet = "=60.2.0"`, and `rayon = "=1.12.0"`). `src/mongo_stream.rs` contains no `mongodb::` driver paths yet. + +### 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` 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`):** 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`). + +### `bench-mongo-stream` + +Offline fixed-seed benchmark comparing decoding `1,000,000` synthetic `eodPrices` documents (`285,639,152` bytes) through plain `io::Cursor<&[u8]>` → `decode_eod_price_stream` vs. `SliceRawDocumentSource` → `RawBsonCursorReader` → `decode_eod_price_stream`: + +```bash +cargo run -p curate-etl --release --offline -- bench-mongo-stream 1000000 +``` + +Measured locally (`2026-11-30`, two back-to-back offline runs on the final code with identical stats `decoded=995008`, `rejected=4992`, and checksum `0x05af9d2746d1b5e3`): + +- **Run 1:** plain `264.49 ms` (`3,780,816 docs/s`, `1,029.92 MiB/s`) vs. `RawBsonCursorReader` `263.32 ms` (`3,797,634 docs/s`, `1,034.50 MiB/s`, ratio `1.004x`, `peak_pending_capacity=271 bytes`) +- **Run 2:** plain `281.99 ms` (`3,546,241 docs/s`, `966.02 MiB/s`) vs. `RawBsonCursorReader` `270.90 ms` (`3,691,390 docs/s`, `1,005.56 MiB/s`, ratio `1.041x`, `peak_pending_capacity=271 bytes`) + +### Not Done / Not Verified + +- **Deferred `mongodb`-backed `MongoRawDocumentSource`:** the `mongodb` crate could not be fetched into the offline Cargo cache from the sandbox (`cargo fetch` failed with `failed to download from https://index.crates.io/config.json: [6] Could not resolve hostname (Could not resolve host: index.crates.io)`), and its driver-backed code has never been compiled. Adding exact-pinned `mongodb` (`Cargo.toml` / `Cargo.lock`) and `MongoRawDocumentSource::open(&ValidatedReadOnlyMongoUri, ...)` is deferred to a follow-up task once `mongodb` and its transitive crates are cached via a host-side `cargo fetch` or working crates.io egress. +- **Live QA MongoDB cursor throughput on `quant`:** not run (all tests and benchmarks run 100% offline with zero network connections; live cursor throughput against read-only QA MongoDB on `quant` is deferred to the driver/CLI wiring and live-host verification tasks). + ## Exporting Input Files (`data-pipeline`) All `curate-*` commands read local TSV and concatenated raw-BSON files produced by the read-only exporters in `@stock-bot/data-pipeline`: diff --git a/tools/curate-etl/src/bench.rs b/tools/curate-etl/src/bench.rs index 0ea4c1b0..b4a351ea 100644 --- a/tools/curate-etl/src/bench.rs +++ b/tools/curate-etl/src/bench.rs @@ -16,13 +16,15 @@ use parquet::file::reader::{FileReader, SerializedFileReader}; use crate::adj::{build_adj_factors, AdjBuildStats, AdjError, DividendEvent}; use crate::bars::{build_bars_1d, Bars1dStats, BarsError, EodDailyBar, QmRawVolume}; -use crate::bson_eod_prices::{decode_eod_price_buffer, BsonEodDecodeStats}; +use crate::bson_eod_prices::{decode_eod_price_buffer, iter_raw_bson_docs, BsonEodDecodeStats}; use crate::bson_qm_actions::{ decode_qm_dividend_buffer, decode_qm_split_buffer, BsonQmActionDecodeStats, }; use crate::bson_stream::{ - decode_eod_price_chunks, BsonStreamError, BsonStreamOptions, RawBsonChunkReader, + decode_eod_price_chunks, decode_eod_price_stream, BsonStreamError, BsonStreamOptions, + RawBsonChunkReader, }; +use crate::mongo_stream::{RawBsonCursorReader, SliceRawDocumentSource}; use crate::corporate_actions::{ build_corporate_actions, CorporateActionError, CorporateActionKind, CorporateActionsStats, DelistingOutcomeEvent, DividendActionEvent, KnownAtSource, SplitActionEvent, @@ -87,6 +89,7 @@ pub const PARQUET_CORPORATE_ACTIONS_RAW_ROW_BYTES: usize = 72; pub const DEFAULT_BSON_EOD_PRICES_BENCH_ROWS: usize = 1_000_000; pub const DEFAULT_BSON_QM_ACTIONS_BENCH_ROWS: usize = 1_000_000; pub const DEFAULT_BSON_STREAM_BENCH_ROWS: usize = 2_000_000; +pub const DEFAULT_MONGO_STREAM_BENCH_ROWS: usize = 1_000_000; pub const BENCH_KEY_COUNT: usize = 20_000; pub const BENCH_EVENT_COUNT: usize = 19_000; pub const PROVIDER_MAPPING_BENCH_KEY_COUNT: usize = 60_000; @@ -3992,6 +3995,150 @@ pub fn run_bson_stream_benchmark(rows: usize) -> Result` +/// decode benchmark for `rows` synthetic `eodPrices` documents. +pub fn run_mongo_stream_benchmark(rows: usize) -> Result { + if rows == 0 { + return Ok(MongoStreamBenchReport { + rows: 0, + bytes: 0, + plain_elapsed_ms: 0.0, + plain_docs_per_sec: 0.0, + plain_mib_per_sec: 0.0, + cursor_elapsed_ms: 0.0, + cursor_docs_per_sec: 0.0, + cursor_mib_per_sec: 0.0, + cursor_to_plain_ratio: 0.0, + peak_pending_capacity: 0, + checksum: 0, + stats: BsonEodDecodeStats::default(), + }); + } + + let buffer = build_bson_eod_prices_bench_buffer(rows); + let bytes = buffer.len(); + + let mut doc_slices: Vec<&[u8]> = Vec::with_capacity(rows); + for doc_res in iter_raw_bson_docs(&buffer) { + let raw_doc = doc_res.expect("synthetic benchmark buffer must have valid BSON frames"); + doc_slices.push(raw_doc.as_bytes()); + } + assert_eq!(doc_slices.len(), rows); + + // Baseline: plain in-memory io::Cursor<&[u8]> -> decode_eod_price_stream. + let mut plain_hash = 0u64; + let mut plain_err_hash = 0u64; + let plain_start = Instant::now(); + let plain_stats = decode_eod_price_stream( + io::Cursor::new(buffer.as_slice()), + BsonStreamOptions::default(), + |bar| { + plain_hash = mix_bytes(plain_hash, bar.eod_search_code.as_bytes()); + plain_hash = mix_u64(plain_hash, bar.session_date as u64); + plain_hash = mix_u64(plain_hash, bar.open.to_bits()); + plain_hash = mix_u64(plain_hash, bar.high.to_bits()); + plain_hash = mix_u64(plain_hash, bar.low.to_bits()); + plain_hash = mix_u64(plain_hash, bar.close.to_bits()); + plain_hash = mix_u64(plain_hash, bar.adj_volume.to_bits()); + }, + |offset, _err| { + plain_err_hash = mix_u64(plain_err_hash, offset ^ 0xDEAD_BEEF_CAFE_BABEu64); + }, + )?; + let plain_elapsed_secs = plain_start.elapsed().as_secs_f64(); + let plain_checksum = black_box(plain_hash ^ plain_err_hash); + + // Candidate: in-memory RawDocumentSource -> RawBsonCursorReader -> decode_eod_price_stream. + let mut cursor_reader = RawBsonCursorReader::new(SliceRawDocumentSource::new(&doc_slices)); + let mut cursor_hash = 0u64; + let mut cursor_err_hash = 0u64; + let cursor_start = Instant::now(); + let cursor_stats = decode_eod_price_stream( + &mut cursor_reader, + BsonStreamOptions::default(), + |bar| { + cursor_hash = mix_bytes(cursor_hash, bar.eod_search_code.as_bytes()); + cursor_hash = mix_u64(cursor_hash, bar.session_date as u64); + cursor_hash = mix_u64(cursor_hash, bar.open.to_bits()); + cursor_hash = mix_u64(cursor_hash, bar.high.to_bits()); + cursor_hash = mix_u64(cursor_hash, bar.low.to_bits()); + cursor_hash = mix_u64(cursor_hash, bar.close.to_bits()); + cursor_hash = mix_u64(cursor_hash, bar.adj_volume.to_bits()); + }, + |offset, _err| { + cursor_err_hash = mix_u64(cursor_err_hash, offset ^ 0xDEAD_BEEF_CAFE_BABEu64); + }, + )?; + let cursor_elapsed_secs = cursor_start.elapsed().as_secs_f64(); + let cursor_checksum = black_box(cursor_hash ^ cursor_err_hash); + let peak_pending_capacity = cursor_reader.pending_capacity(); + + assert_eq!( + cursor_stats, plain_stats, + "cursor reader decode stats must match plain in-memory reader" + ); + assert_eq!( + cursor_checksum, plain_checksum, + "cursor reader decode checksum must match plain in-memory reader" + ); + assert_eq!(cursor_reader.docs_read(), rows as u64); + assert_eq!(cursor_reader.bytes_read(), bytes as u64); + + let plain_elapsed_ms = plain_elapsed_secs * 1_000.0; + let (plain_docs_per_sec, _) = compute_rates(rows, plain_elapsed_secs); + let plain_mib_per_sec = if plain_elapsed_secs > 0.0 && plain_elapsed_secs.is_finite() { + (bytes as f64 / (1024.0 * 1024.0)) / plain_elapsed_secs + } else { + 0.0 + }; + + let cursor_elapsed_ms = cursor_elapsed_secs * 1_000.0; + let (cursor_docs_per_sec, _) = compute_rates(rows, cursor_elapsed_secs); + let cursor_mib_per_sec = if cursor_elapsed_secs > 0.0 && cursor_elapsed_secs.is_finite() { + (bytes as f64 / (1024.0 * 1024.0)) / cursor_elapsed_secs + } else { + 0.0 + }; + + let cursor_to_plain_ratio = if plain_docs_per_sec > 0.0 { + cursor_docs_per_sec / plain_docs_per_sec + } else { + 0.0 + }; + + Ok(MongoStreamBenchReport { + rows, + bytes, + plain_elapsed_ms, + plain_docs_per_sec, + plain_mib_per_sec, + cursor_elapsed_ms, + cursor_docs_per_sec, + cursor_mib_per_sec, + cursor_to_plain_ratio, + peak_pending_capacity, + checksum: cursor_checksum, + stats: cursor_stats, + }) +} + /// Summary metrics produced by [`run_bson_qm_actions_benchmark`]. #[derive(Debug, Clone, Copy, PartialEq)] pub struct BsonQmActionsBenchReport { @@ -11188,6 +11335,36 @@ mod tests { assert_eq!(report.stats, BsonEodDecodeStats::default()); } + #[test] + fn mongo_stream_benchmark_small_run_is_deterministic_with_parity() { + let a = run_mongo_stream_benchmark(2_000).expect("mongo-stream bench must succeed"); + let b = run_mongo_stream_benchmark(2_000).expect("mongo-stream bench must be deterministic"); + + assert_eq!(a.rows, 2_000); + assert_eq!(a.bytes, b.bytes); + assert!(a.bytes > 0); + assert_eq!(a.checksum, b.checksum); + assert_eq!(a.stats, b.stats); + assert_eq!(a.stats.docs_in, 2_000); + assert_eq!(a.stats.decoded + a.stats.rejected_total(), a.stats.docs_in); + assert!(a.plain_docs_per_sec.is_finite() && a.plain_docs_per_sec >= 0.0); + assert!(a.cursor_docs_per_sec.is_finite() && a.cursor_docs_per_sec >= 0.0); + assert!(a.cursor_to_plain_ratio.is_finite() && a.cursor_to_plain_ratio >= 0.0); + } + + #[test] + fn mongo_stream_benchmark_zero_rows_handles_cleanly() { + let report = run_mongo_stream_benchmark(0).expect("zero-row mongo-stream bench must succeed"); + assert_eq!(report.rows, 0); + assert_eq!(report.bytes, 0); + assert_eq!(report.plain_elapsed_ms, 0.0); + assert_eq!(report.cursor_elapsed_ms, 0.0); + assert_eq!(report.cursor_to_plain_ratio, 0.0); + assert_eq!(report.peak_pending_capacity, 0); + assert_eq!(report.checksum, 0); + assert_eq!(report.stats, BsonEodDecodeStats::default()); + } + #[test] fn bson_qm_actions_benchmark_small_run_is_deterministic() { let a = run_bson_qm_actions_benchmark(20_000); diff --git a/tools/curate-etl/src/cli.rs b/tools/curate-etl/src/cli.rs index a99a68d1..34f8c5da 100644 --- a/tools/curate-etl/src/cli.rs +++ b/tools/curate-etl/src/cli.rs @@ -18,7 +18,8 @@ use crate::bench::{ DEFAULT_CURATE_EVENTS_CMD_BENCH_ROWS, DEFAULT_CURATE_FX_BENCH_ROWS, DEFAULT_CURATE_FX_CMD_BENCH_ROWS, DEFAULT_CURATE_SHORTS_BENCH_ROWS, DEFAULT_CURATE_SHORTS_COMMAND_BENCH_ROWS, DEFAULT_EVENTS_BENCH_ROWS, DEFAULT_FX_BENCH_ROWS, - DEFAULT_PARQUET_ADJ_BENCH_ROWS, DEFAULT_PARQUET_BARS_BENCH_ROWS, + DEFAULT_MONGO_STREAM_BENCH_ROWS, DEFAULT_PARQUET_ADJ_BENCH_ROWS, + DEFAULT_PARQUET_BARS_BENCH_ROWS, DEFAULT_PARQUET_CORPORATE_ACTIONS_BENCH_ROWS, DEFAULT_PARQUET_EVENTS_BENCH_ROWS, DEFAULT_PARQUET_FX_BENCH_ROWS, DEFAULT_PARQUET_SHORTS_BENCH_ROWS, DEFAULT_PROVIDER_MAPPING_BENCH_LOOKUPS, DEFAULT_SHORTS_BENCH_ROWS, @@ -65,6 +66,7 @@ pub enum CliAction { BenchBsonEodPrices(usize), BenchBsonQmActions(usize), BenchBsonStream(usize), + BenchMongoStream(usize), BenchCurateBars(usize), BenchCurateBarsCmd(usize), BenchCurateShorts(usize), @@ -116,6 +118,7 @@ pub fn format_usage(name: &str, version: &str) -> String { {name} bench-bson-eod-prices [rows] Run fixed-seed eodPrices raw BSON zero-copy decode benchmark (default: {DEFAULT_BSON_EOD_PRICES_BENCH_ROWS})\n\ {name} bench-bson-qm-actions [rows] Run fixed-seed qmSplits/qmDividends raw BSON zero-copy decode benchmark (default: {DEFAULT_BSON_QM_ACTIONS_BENCH_ROWS})\n\ {name} bench-bson-stream [rows] Run fixed-seed eodPrices raw BSON stream vs buffer decode benchmark (default: {DEFAULT_BSON_STREAM_BENCH_ROWS})\n\ + {name} bench-mongo-stream [rows] Run offline fixed-seed RawBsonCursorReader vs plain in-memory eodPrices decode benchmark (default: {DEFAULT_MONGO_STREAM_BENCH_ROWS})\n\ {name} bench-curate-bars [rows] Run fixed-seed bars_1d curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_BARS_BENCH_ROWS})\n\ {name} bench-curate-bars-cmd [rows] Run fixed-seed end-to-end curate-bars-1d file->Parquet benchmark (default: {DEFAULT_CURATE_BARS_CMD_BENCH_ROWS})\n\ {name} bench-curate-shorts [rows] Run fixed-seed shorts curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_SHORTS_BENCH_ROWS})\n\ @@ -160,6 +163,7 @@ pub fn format_usage_stderr(name: &str) -> String { {name} bench-bson-eod-prices [rows]\n\ {name} bench-bson-qm-actions [rows]\n\ {name} bench-bson-stream [rows]\n\ + {name} bench-mongo-stream [rows]\n\ {name} bench-curate-bars [rows]\n\ {name} bench-curate-bars-cmd [rows]\n\ {name} bench-curate-shorts [rows]\n\ @@ -1057,6 +1061,16 @@ pub fn parse_args(args: &[String]) -> Result { ["bench-bson-stream", _, ..] => { Err("too many arguments for bench-bson-stream".to_string()) } + ["bench-mongo-stream"] => Ok(CliAction::BenchMongoStream(DEFAULT_MONGO_STREAM_BENCH_ROWS)), + ["bench-mongo-stream", raw] => match raw.parse::() { + Ok(n) if n > 0 => Ok(CliAction::BenchMongoStream(n)), + _ => Err(format!( + "invalid row count '{raw}' (expected a positive integer)" + )), + }, + ["bench-mongo-stream", _, ..] => { + Err("too many arguments for bench-mongo-stream".to_string()) + } ["bench-curate-bars"] => Ok(CliAction::BenchCurateBars(DEFAULT_CURATE_BARS_BENCH_ROWS)), ["bench-curate-bars", raw] => match raw.parse::() { Ok(n) if n > 0 => Ok(CliAction::BenchCurateBars(n)), @@ -1512,6 +1526,22 @@ mod tests { assert!(parse_args(&to_args(&["bench-bson-stream", "10", "20"])).is_err()); } + #[test] + fn parses_and_validates_bench_mongo_stream_args() { + assert_eq!( + parse_args(&to_args(&["bench-mongo-stream"])), + Ok(CliAction::BenchMongoStream(DEFAULT_MONGO_STREAM_BENCH_ROWS)) + ); + assert_eq!( + parse_args(&to_args(&["bench-mongo-stream", "100000"])), + Ok(CliAction::BenchMongoStream(100_000)) + ); + assert!(parse_args(&to_args(&["bench-mongo-stream", "0"])).is_err()); + assert!(parse_args(&to_args(&["bench-mongo-stream", "-5"])).is_err()); + assert!(parse_args(&to_args(&["bench-mongo-stream", "abc"])).is_err()); + assert!(parse_args(&to_args(&["bench-mongo-stream", "10", "20"])).is_err()); + } + #[test] fn usage_strings_mention_all_benchmarks() { let full = format_usage("curate-etl", "0.1.0"); diff --git a/tools/curate-etl/src/lib.rs b/tools/curate-etl/src/lib.rs index ab444317..038e88c0 100644 --- a/tools/curate-etl/src/lib.rs +++ b/tools/curate-etl/src/lib.rs @@ -14,6 +14,8 @@ pub mod cli; pub mod corporate_actions; pub mod events; pub mod fx; +pub mod mongo_safety; +pub mod mongo_stream; pub mod parquet_adj; pub mod parquet_bars; pub mod parquet_corporate_actions; @@ -95,6 +97,16 @@ pub use fx::{ build_fx_1d, fx_rate_on_or_before, Fx1dBuild, Fx1dRow, Fx1dStats, FxDailyBar, FxSource, FxSourceStats, FX_OVERLAP_REL_TOLERANCE, FX_PAIR_USDCAD, }; +pub use mongo_safety::{ + assert_read_only_mongo_uri, is_qa_mongo_target, parse_mongo_target, LocalHosts, + MongoSafetyError, MongoScheme, MongoTarget, MongoTargetHost, ReadOnlyPolicy, + ValidatedReadOnlyMongoUri, DEFAULT_ALLOWED_READ_USER, FORBIDDEN_ADMIN_USER, QA_MONGO_PORT, +}; +pub use mongo_stream::{ + 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, AdjFactorsWriteOptions, AdjFactorsWriteStats, ParquetAdjError, diff --git a/tools/curate-etl/src/main.rs b/tools/curate-etl/src/main.rs index e60629d7..df915935 100644 --- a/tools/curate-etl/src/main.rs +++ b/tools/curate-etl/src/main.rs @@ -11,7 +11,8 @@ use curate_etl::bench::{ run_curate_corporate_actions_cmd_benchmark, run_curate_events_benchmark, run_curate_events_cmd_benchmark, run_curate_fx_benchmark, run_curate_fx_cmd_benchmark, run_curate_shorts_benchmark, run_curate_shorts_command_benchmark, run_events_benchmark, - run_fx_benchmark, run_parquet_adj_benchmark, run_parquet_bars_benchmark, + run_fx_benchmark, run_mongo_stream_benchmark, run_parquet_adj_benchmark, + run_parquet_bars_benchmark, run_parquet_corporate_actions_benchmark, run_parquet_events_benchmark, run_parquet_fx_benchmark, run_parquet_shorts_benchmark, run_provider_mapping_benchmark, run_shorts_benchmark, run_split_benchmark, @@ -656,6 +657,42 @@ fn main() -> ExitCode { ); ExitCode::SUCCESS } + Ok(CliAction::BenchMongoStream(rows)) => { + let report = match run_mongo_stream_benchmark(rows) { + Ok(report) => report, + Err(err) => { + eprintln!("error: mongo-stream benchmark failed: {err}"); + return ExitCode::FAILURE; + } + }; + println!("curate-etl bench-mongo-stream"); + println!(" input: rows={} bytes={}", report.rows, report.bytes); + println!( + " decode: decoded={} rejected={} (missing={} empty={} wrong_type={} malformed_date={} invalid_number={} corrupt={}) checksum=0x{:016x}", + report.stats.decoded, + report.stats.rejected_total(), + report.stats.rejected_missing_field, + report.stats.rejected_empty_field, + report.stats.rejected_wrong_type, + report.stats.rejected_malformed_date, + report.stats.rejected_invalid_number, + report.stats.rejected_corrupt_document, + report.checksum + ); + println!( + " plain: elapsed={:.2} ms throughput={:.0} docs/s scan={:.2} MiB/s", + report.plain_elapsed_ms, report.plain_docs_per_sec, report.plain_mib_per_sec + ); + println!( + " cursor: elapsed={:.2} ms throughput={:.0} docs/s scan={:.2} MiB/s ratio={:.3}x peak_pending_capacity={} bytes", + report.cursor_elapsed_ms, + report.cursor_docs_per_sec, + report.cursor_mib_per_sec, + report.cursor_to_plain_ratio, + report.peak_pending_capacity + ); + ExitCode::SUCCESS + } Ok(CliAction::BenchCurateBars(rows)) => { let report = match run_curate_bars_benchmark(rows) { Ok(report) => report, diff --git a/tools/curate-etl/src/mongo_safety.rs b/tools/curate-etl/src/mongo_safety.rs new file mode 100644 index 00000000..32ead4fc --- /dev/null +++ b/tools/curate-etl/src/mongo_safety.rs @@ -0,0 +1,1068 @@ +//! Pure, offline, `std`-only read-only MongoDB URI safety guard. +//! +//! This module ports the MongoDB target-classification rules from +//! `apps/stock/config/src/env-safety.ts` (and the authority/remainder `@` check +//! from `libs/core/config/src/schemas/database.schema.ts`) to Rust, and adds +//! stricter read-only enforcement for `curate-etl`: +//! +//! 1. Rejects malformed URIs, ASCII control characters, Unicode whitespace, +//! unencoded `#` or multiple `@` in authority, `@` in path/query when +//! authority has no credentials, invalid percent-encoding, and forbidden +//! decoded host characters. +//! 2. Rejects `trading_admin` (percent-decoded, ASCII case-insensitive) on +//! **any** host regardless of [`ReadOnlyPolicy::allowed_read_users`]. +//! 3. Classifies any loopback or local-machine host on port `27017` (or omitted +//! default port) as a QA MongoDB target, and requires an allowlisted +//! read-only username (default: `["studio_stock_bot_read"]`) with explicit +//! credentials on QA targets. +//! 4. Produces a [`ValidatedReadOnlyMongoUri`] token with private fields and no +//! public constructor other than [`assert_read_only_mongo_uri`], so future +//! MongoDB cursor modules can require validated URIs by type. +//! +//! # Non-goals & boundaries +//! - **No I/O or network:** never opens sockets, never resolves DNS, and never +//! spawns subprocesses. +//! - **No URI query-option parsing:** beyond authority/remainder splitting and +//! the no-credentials remainder-`@` check, query parameters are not parsed or +//! validated (no invented option rules). + +use std::collections::BTreeSet; +use std::error::Error; +use std::fmt; + +/// Default allowlisted read-only MongoDB username for QA targets. +pub const DEFAULT_ALLOWED_READ_USER: &str = "studio_stock_bot_read"; + +/// Admin username forbidden on any MongoDB host (ASCII case-insensitive). +pub const FORBIDDEN_ADMIN_USER: &str = "trading_admin"; + +/// Default QA MongoDB port. +pub const QA_MONGO_PORT: u16 = 27017; + +const MAX_MONGO_HOST_DECODE_PASSES: usize = 8; + +/// Supported MongoDB URI schemes. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum MongoScheme { + /// `mongodb://` (default port `27017`, allows `.sock` Unix domain sockets). + Standard, + /// `mongodb+srv://` (no default port, single seed host, no explicit port, + /// no Unix domain sockets). + Srv, +} + +/// A single decoded host/port seed entry from a MongoDB URI. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct MongoTargetHost { + pub host: String, + pub port: Option, +} + +/// Parsed MongoDB URI target metadata (never stores the raw URI or password). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct MongoTarget { + pub scheme: MongoScheme, + pub hosts: Vec, + pub database: Option, + pub username: Option, + has_invalid_host_segment: bool, + has_explicit_port: bool, +} + +impl MongoTarget { + /// Returns `true` if any comma-separated host segment was empty or had + /// malformed port/bracket syntax while at least one other host parsed. + pub fn has_invalid_host_segment(&self) -> bool { + self.has_invalid_host_segment + } + + /// Returns `true` if any host segment included an explicit `:` port suffix + /// (including a trailing `:` with an empty port). + pub fn has_explicit_port(&self) -> bool { + self.has_explicit_port + } +} + +/// Set of local-machine hostnames and IP addresses treated as local for QA +/// MongoDB target classification. +/// +/// Injecting this set explicitly keeps tests deterministic and offline. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct LocalHosts { + hosts: BTreeSet, +} + +impl LocalHosts { + /// Returns an empty set (only loopback addresses will match as local). + pub fn empty() -> Self { + Self::default() + } + + /// Builds a `LocalHosts` set from raw hostnames or IP strings. + pub fn new(hosts: I) -> Self + where + I: IntoIterator, + S: AsRef, + { + let mut set = Self::empty(); + for host in hosts { + if let Some(normalized) = normalize_local_host_entry(host.as_ref()) { + set.hosts.insert(normalized); + } + } + set + } + + /// Builds a `LocalHosts` set from an optional machine hostname and a list + /// of local interface IP addresses, matching `getLocalMachineHosts` in + /// `apps/stock/config/src/env-safety.ts`: + /// + /// - Adds the trimmed, trailing-dot-stripped, lowercased full hostname, + /// its short label before the first `.`, and `.local`. + /// - Adds each IP with outer brackets and `%zone` suffixes stripped and + /// lowercased. + pub fn from_hostname_and_ips(hostname: Option<&str>, ips: I) -> Self + where + I: IntoIterator, + S: AsRef, + { + let mut set = Self::empty(); + if let Some(name) = hostname { + set.insert_hostname(name); + } + for ip in ips { + if let Some(normalized) = normalize_local_host_entry(ip.as_ref()) { + set.hosts.insert(normalized); + } + } + set + } + + /// Adds a single normalized host or IP entry and returns `self`. + pub fn with_host(mut self, host: &str) -> Self { + if let Some(normalized) = normalize_local_host_entry(host) { + self.hosts.insert(normalized); + } + self + } + + /// Returns `true` if the normalized host or IP is present in this set. + pub fn contains(&self, host: &str) -> bool { + normalize_local_host_entry(host) + .map(|normalized| self.hosts.contains(&normalized)) + .unwrap_or(false) + } + + /// Best-effort local host detection using only the Rust standard library. + /// + /// Reads `HOSTNAME` from the environment and `/etc/hostname` (when + /// readable). Because this module is strictly `std`-only and performs no + /// network-interface enumeration or DNS lookups, multi-homed LAN IPs are + /// **not** discovered automatically; callers on multi-homed hosts should + /// inject LAN IPs explicitly via [`LocalHosts::from_hostname_and_ips`]. + pub fn detect() -> Self { + let env_hostname = std::env::var("HOSTNAME").ok(); + let etc_hostname = std::fs::read_to_string("/etc/hostname").ok(); + Self::detect_from_sources(env_hostname.as_deref(), etc_hostname.as_deref()) + } + + fn detect_from_sources(env_hostname: Option<&str>, etc_hostname: Option<&str>) -> Self { + let mut set = Self::empty(); + if let Some(name) = env_hostname { + set.insert_hostname(name); + } + if let Some(contents) = etc_hostname { + if let Some(first_line) = contents.lines().find(|line| !line.trim().is_empty()) { + set.insert_hostname(first_line); + } + } + set + } + + fn insert_hostname(&mut self, raw: &str) { + let normalized = raw.trim().trim_end_matches('.').to_lowercase(); + if normalized.is_empty() { + return; + } + self.hosts.insert(normalized.clone()); + if let Some(short_name) = normalized.split('.').next() { + if !short_name.is_empty() { + self.hosts.insert(short_name.to_owned()); + self.hosts.insert(format!("{short_name}.local")); + } + } + } +} + +/// Policy controlling which usernames are permitted to read a QA MongoDB target. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ReadOnlyPolicy { + /// Exact allowlisted usernames for QA MongoDB targets. + /// + /// Note: [`FORBIDDEN_ADMIN_USER`] (`"trading_admin"`) is always rejected on + /// every host even if a caller adds it to this list. + pub allowed_read_users: Vec, +} + +impl Default for ReadOnlyPolicy { + fn default() -> Self { + Self { + allowed_read_users: vec![DEFAULT_ALLOWED_READ_USER.to_owned()], + } + } +} + +/// Proof token that a MongoDB URI passed [`assert_read_only_mongo_uri`]. +/// +/// All fields are private and there is no public constructor other than +/// [`assert_read_only_mongo_uri`]. Both [`fmt::Debug`] and [`fmt::Display`] +/// redact the password in userinfo. +#[derive(Clone, PartialEq, Eq)] +pub struct ValidatedReadOnlyMongoUri { + uri: String, + target: MongoTarget, + is_qa: bool, +} + +impl ValidatedReadOnlyMongoUri { + /// Returns the original validated URI string for passing to a MongoDB + /// driver. Callers must not log this string directly; use [`Self::redacted`] + /// or `Display`/`Debug` instead. + pub fn as_str(&self) -> &str { + &self.uri + } + + /// Returns the parsed target metadata. + pub fn target(&self) -> &MongoTarget { + &self.target + } + + /// Returns `true` if this URI targets a local QA MongoDB instance. + pub fn is_qa_target(&self) -> bool { + self.is_qa + } + + /// Returns a copy of the URI with any userinfo password replaced by + /// `[REDACTED]`. + pub fn redacted(&self) -> String { + redact_mongo_uri_password(&self.uri) + } +} + +impl fmt::Display for ValidatedReadOnlyMongoUri { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.redacted()) + } +} + +impl fmt::Debug for ValidatedReadOnlyMongoUri { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("ValidatedReadOnlyMongoUri") + .field("uri", &self.redacted()) + .field("target", &self.target) + .field("is_qa", &self.is_qa) + .finish() + } +} + +/// Failure reasons returned by [`parse_mongo_target`] and +/// [`assert_read_only_mongo_uri`]. +/// +/// Variants intentionally never store raw URIs, raw authorities, or passwords +/// so neither `Debug` nor `Display` can leak credentials. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum MongoSafetyError { + EmptyUri, + ControlCharacters, + ForbiddenWhitespace, + UnsupportedScheme, + EmptyAuthority, + UnencodedHashInAuthority, + EmptyUserinfo, + MultipleAtInAuthority, + UnencodedAtInRemainderWithoutCredentials, + EmptyHostList, + InvalidUsernameEncoding, + InvalidHostEncoding, + ForbiddenHostCharacters, + NoValidHosts, + MalformedHostSegment, + InvalidSrvTarget, + ForbiddenAdminUser, + MissingCredentialsForQaTarget, + UnauthorizedQaUser, +} + +impl fmt::Display for MongoSafetyError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::EmptyUri => f.write_str("Safety guard: MongoDB URI is missing or empty."), + Self::ControlCharacters => f.write_str( + "Safety guard: MongoDB URI contains forbidden ASCII control characters.", + ), + Self::ForbiddenWhitespace => { + f.write_str("Safety guard: MongoDB URI contains forbidden whitespace.") + } + Self::UnsupportedScheme => f.write_str( + "Safety guard: MongoDB URI must use the mongodb:// or mongodb+srv:// scheme.", + ), + Self::EmptyAuthority => f.write_str("Safety guard: MongoDB URI authority is empty."), + Self::UnencodedHashInAuthority => f.write_str( + "Safety guard: MongoDB URI authority cannot contain an unencoded \"#\" character.", + ), + Self::EmptyUserinfo => f.write_str( + "Safety guard: MongoDB URI authority cannot have empty userinfo before \"@\".", + ), + Self::MultipleAtInAuthority => f.write_str( + "Safety guard: MongoDB URI authority cannot contain multiple unencoded \"@\" characters.", + ), + Self::UnencodedAtInRemainderWithoutCredentials => f.write_str( + "Safety guard: MongoDB URI cannot contain an unencoded \"@\" in path or query without credentials in authority.", + ), + Self::EmptyHostList => f.write_str("Safety guard: MongoDB URI host list is empty."), + Self::InvalidUsernameEncoding => f.write_str( + "Safety guard: invalid percent-encoding in MongoDB URI username.", + ), + Self::InvalidHostEncoding => { + f.write_str("Safety guard: invalid percent-encoding in MongoDB host.") + } + Self::ForbiddenHostCharacters => { + f.write_str("Safety guard: invalid characters in MongoDB host.") + } + Self::NoValidHosts => { + f.write_str("Safety guard: MongoDB URI did not contain any valid host.") + } + Self::MalformedHostSegment => f.write_str( + "Safety guard: MongoDB URI contains an empty or malformed host segment.", + ), + Self::InvalidSrvTarget => f.write_str( + "Safety guard: mongodb+srv:// URI must contain exactly one host and no explicit port.", + ), + Self::ForbiddenAdminUser => f.write_str( + "Safety guard: MongoDB admin user \"trading_admin\" is forbidden in read-only mode.", + ), + Self::MissingCredentialsForQaTarget => f.write_str( + "Safety guard: QA MongoDB target requires explicit read-only credentials.", + ), + Self::UnauthorizedQaUser => f.write_str( + "Safety guard: QA MongoDB target requires an allowlisted read-only username.", + ), + } + } +} + +impl Error for MongoSafetyError {} + +/// Parses a MongoDB connection URI into its target scheme, decoded hosts/ports, +/// optional database path, and optional percent-decoded username. +/// +/// Mirrors `parseMongoTarget` / `parseMongoHostPort` / `decodeMongoHost` in +/// `apps/stock/config/src/env-safety.ts` plus the no-credentials remainder-`@` +/// check from `libs/core/config/src/schemas/database.schema.ts`. +pub fn parse_mongo_target(uri: &str) -> Result { + if uri.is_empty() { + return Err(MongoSafetyError::EmptyUri); + } + if has_ascii_control_char(uri) { + return Err(MongoSafetyError::ControlCharacters); + } + if has_forbidden_whitespace(uri) { + return Err(MongoSafetyError::ForbiddenWhitespace); + } + + let Some((raw_scheme, rest)) = uri.split_once("://") else { + return Err(MongoSafetyError::UnsupportedScheme); + }; + let scheme = if raw_scheme.eq_ignore_ascii_case("mongodb") { + MongoScheme::Standard + } else if raw_scheme.eq_ignore_ascii_case("mongodb+srv") { + MongoScheme::Srv + } else { + return Err(MongoSafetyError::UnsupportedScheme); + }; + + let default_port = match scheme { + MongoScheme::Standard => Some(QA_MONGO_PORT), + MongoScheme::Srv => None, + }; + let allow_unix_socket = matches!(scheme, MongoScheme::Standard); + + // Match mongodb-connection-string-url: authority ends at '/' or '?', never '#' + let (authority, remainder) = match rest.find(['/', '?']) { + Some(idx) => (&rest[..idx], &rest[idx..]), + None => (rest, ""), + }; + if authority.is_empty() { + return Err(MongoSafetyError::EmptyAuthority); + } + if authority.contains('#') { + return Err(MongoSafetyError::UnencodedHashInAuthority); + } + + let database = if remainder.starts_with('/') { + let path_part = remainder.split(['?', '#']).next().unwrap_or(""); + let first_segment = path_part + .trim_start_matches('/') + .split('/') + .next() + .unwrap_or(""); + if first_segment.is_empty() { + None + } else { + Some(first_segment.to_owned()) + } + } else { + None + }; + + let (userinfo, host_list) = match authority.find('@') { + Some(0) => return Err(MongoSafetyError::EmptyUserinfo), + Some(at_idx) => { + if authority[at_idx + 1..].contains('@') { + return Err(MongoSafetyError::MultipleAtInAuthority); + } + (&authority[..at_idx], &authority[at_idx + 1..]) + } + None => { + if remainder.contains('@') { + return Err(MongoSafetyError::UnencodedAtInRemainderWithoutCredentials); + } + ("", authority) + } + }; + + if host_list.is_empty() { + return Err(MongoSafetyError::EmptyHostList); + } + + let username = if !userinfo.is_empty() { + let raw_username = match userinfo.find(':') { + Some(colon_idx) => &userinfo[..colon_idx], + None => userinfo, + }; + if raw_username.is_empty() { + None + } else { + Some( + percent_decode_utf8(raw_username) + .map_err(|()| MongoSafetyError::InvalidUsernameEncoding)?, + ) + } + } else { + None + }; + + let mut hosts = Vec::new(); + let mut has_invalid_host_segment = false; + let mut has_explicit_port = false; + + for segment in host_list.split(',') { + match parse_mongo_host_port(segment, default_port, allow_unix_socket)? { + Some((parsed_host, segment_has_explicit_port)) => { + hosts.push(parsed_host); + if segment_has_explicit_port { + has_explicit_port = true; + } + } + None => { + has_invalid_host_segment = true; + } + } + } + + if hosts.is_empty() { + return Err(MongoSafetyError::NoValidHosts); + } + + Ok(MongoTarget { + scheme, + hosts, + database, + username, + has_invalid_host_segment, + has_explicit_port, + }) +} + +/// Returns `true` if any seed host in `target` resolves to loopback or a host +/// in `local_hosts` on port `27017` (or with an omitted/default port), +/// regardless of database path. +/// +/// Mirrors `isQaMongoTargetHosts` in `apps/stock/config/src/env-safety.ts`. +pub fn is_qa_mongo_target(target: &MongoTarget, local_hosts: &LocalHosts) -> bool { + target.hosts.iter().any(|entry| { + is_local_machine_host(&entry.host, local_hosts) + && matches!(entry.port, None | Some(QA_MONGO_PORT)) + }) +} + +/// Validates a MongoDB URI for read-only use and returns a +/// [`ValidatedReadOnlyMongoUri`] proof token. +/// +/// Enforces fail-closed parsing, forbids `trading_admin` (ASCII +/// case-insensitive, percent-decoded) on **any** host, and requires explicit +/// allowlisted credentials when targeting QA MongoDB. +/// +/// URI query options are intentionally not parsed beyond authority/remainder +/// splitting (matching `apps/stock/config/src/env-safety.ts`). +pub fn assert_read_only_mongo_uri( + uri: &str, + policy: &ReadOnlyPolicy, + local_hosts: &LocalHosts, +) -> Result { + let target = parse_mongo_target(uri)?; + + if target.has_invalid_host_segment { + return Err(MongoSafetyError::MalformedHostSegment); + } + if target.scheme == MongoScheme::Srv && (target.hosts.len() != 1 || target.has_explicit_port) { + return Err(MongoSafetyError::InvalidSrvTarget); + } + + if target + .username + .as_deref() + .is_some_and(|user| user.eq_ignore_ascii_case(FORBIDDEN_ADMIN_USER)) + { + return Err(MongoSafetyError::ForbiddenAdminUser); + } + + let is_qa = is_qa_mongo_target(&target, local_hosts); + if is_qa { + let Some(user) = target.username.as_deref() else { + return Err(MongoSafetyError::MissingCredentialsForQaTarget); + }; + if !policy + .allowed_read_users + .iter() + .any(|allowed| allowed == user) + { + return Err(MongoSafetyError::UnauthorizedQaUser); + } + } + + Ok(ValidatedReadOnlyMongoUri { + uri: uri.to_owned(), + target, + is_qa, + }) +} + +pub(crate) fn redact_mongo_uri_password(uri: &str) -> String { + let Some(scheme_end) = uri.find("://") else { + return uri.to_owned(); + }; + let rest_start = scheme_end + 3; + let rest = &uri[rest_start..]; + let authority_end = rest.find(['/', '?']).unwrap_or(rest.len()); + let authority = &rest[..authority_end]; + let Some(at_idx) = authority.find('@') else { + return uri.to_owned(); + }; + let userinfo = &authority[..at_idx]; + let Some(colon_idx) = userinfo.find(':') else { + return uri.to_owned(); + }; + + let pass_start = rest_start + colon_idx + 1; + let pass_end = rest_start + at_idx; + let mut out = String::with_capacity(uri.len() + 10); + out.push_str(&uri[..pass_start]); + out.push_str("[REDACTED]"); + out.push_str(&uri[pass_end..]); + out +} + +fn has_ascii_control_char(value: &str) -> bool { + value.bytes().any(|b| b <= 0x1f || b == 0x7f) +} + +fn has_forbidden_whitespace(value: &str) -> bool { + value.chars().any(|c| c.is_whitespace() || c == '\u{FEFF}') +} + +fn hex_nibble(byte: u8) -> Option { + match byte { + b'0'..=b'9' => Some(byte - b'0'), + b'a'..=b'f' => Some(byte - b'a' + 10), + b'A'..=b'F' => Some(byte - b'A' + 10), + _ => None, + } +} + +/// Strictly percent-decodes UTF-8 without turning `+` into space. +fn percent_decode_utf8(input: &str) -> Result { + let bytes = input.as_bytes(); + let mut out = Vec::with_capacity(bytes.len()); + let mut i = 0; + while i < bytes.len() { + if bytes[i] == b'%' { + if i + 2 >= bytes.len() { + return Err(()); + } + let hi = hex_nibble(bytes[i + 1]).ok_or(())?; + let lo = hex_nibble(bytes[i + 2]).ok_or(())?; + out.push((hi << 4) | lo); + i += 3; + } else { + out.push(bytes[i]); + i += 1; + } + } + String::from_utf8(out).map_err(|_| ()) +} + +fn is_valid_ipv6_zone_id_char(b: u8) -> bool { + b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'~' | b'-') +} + +fn is_valid_ipv6_with_zone_id(host: &str) -> bool { + let Some(zone_idx) = host.find('%') else { + return false; + }; + if zone_idx == 0 || host[zone_idx + 1..].contains('%') { + return false; + } + let addr = &host[..zone_idx]; + let zone = &host[zone_idx + 1..]; + !zone.is_empty() + && zone.bytes().all(is_valid_ipv6_zone_id_char) + && parse_ipv6_hextets(addr).is_some() +} + +fn has_forbidden_unix_socket_char(value: &str) -> bool { + value.chars().any(|c| { + matches!(c, '?' | '#' | '@' | ':' | '\\' | '[' | ']' | ',') + || c.is_whitespace() + || c == '\u{FEFF}' + }) +} + +fn is_unix_domain_socket_host(decoded_host: &str) -> bool { + decoded_host.starts_with('/') + && decoded_host.ends_with(".sock") + && !has_ascii_control_char(decoded_host) + && !has_forbidden_unix_socket_char(decoded_host) +} + +fn has_forbidden_host_char(value: &str, is_bracketed_ipv6: bool) -> bool { + value.chars().any(|c| { + matches!(c, '/' | '?' | '#' | '@' | '\\' | '[' | ']' | ',') + || (!is_bracketed_ipv6 && c == ':') + || c.is_whitespace() + || c == '\u{FEFF}' + }) +} + +fn decode_mongo_host( + raw_host: &str, + is_bracketed_ipv6: bool, + allow_unix_socket: bool, +) -> Result { + let mut current = raw_host.to_owned(); + for pass in 0..MAX_MONGO_HOST_DECODE_PASSES { + match percent_decode_utf8(¤t) { + Ok(decoded) => { + if decoded == current { + break; + } + current = decoded; + if is_bracketed_ipv6 && is_valid_ipv6_with_zone_id(¤t) { + break; + } + } + Err(()) => { + if is_bracketed_ipv6 && pass > 0 && is_valid_ipv6_with_zone_id(¤t) { + break; + } + return Err(MongoSafetyError::InvalidHostEncoding); + } + } + } + + if current.contains('%') && !(is_bracketed_ipv6 && is_valid_ipv6_with_zone_id(¤t)) { + return Err(MongoSafetyError::InvalidHostEncoding); + } + if !is_bracketed_ipv6 && allow_unix_socket && is_unix_domain_socket_host(¤t) { + return Ok(current); + } + if has_ascii_control_char(¤t) || has_forbidden_host_char(¤t, is_bracketed_ipv6) { + return Err(MongoSafetyError::ForbiddenHostCharacters); + } + Ok(current.to_lowercase()) +} + +fn parse_port(port_str: &str) -> Option { + if port_str.is_empty() || !port_str.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + let port: u16 = port_str.parse().ok()?; + if port == 0 { None } else { Some(port) } +} + +fn is_valid_bracketed_ipv6(host: &str) -> bool { + if host.contains('%') { + is_valid_ipv6_with_zone_id(host) + } else { + parse_ipv6_hextets(host).is_some() + } +} + +fn parse_mongo_host_port( + segment: &str, + default_port: Option, + allow_unix_socket: bool, +) -> Result, MongoSafetyError> { + let trimmed = segment.trim(); + if trimmed.is_empty() { + return Ok(None); + } + + if let Some(after_open) = trimmed.strip_prefix('[') { + let Some(close_rel) = after_open.find(']') else { + return Ok(None); + }; + if close_rel == 0 { + return Ok(None); + } + let raw_host = after_open[..close_rel].trim(); + if raw_host.is_empty() { + return Ok(None); + } + let host = decode_mongo_host(raw_host, true, false)?.trim().to_owned(); + if host.is_empty() || !is_valid_bracketed_ipv6(&host) { + return Ok(None); + } + let after = after_open[close_rel + 1..].trim(); + if after.is_empty() { + return Ok(Some(( + MongoTargetHost { + host, + port: default_port, + }, + false, + ))); + } + let Some(port_part) = after.strip_prefix(':') else { + return Ok(None); + }; + let port_str = port_part.trim(); + if port_str.is_empty() { + return Ok(Some(( + MongoTargetHost { + host, + port: default_port, + }, + true, + ))); + } + let Some(port) = parse_port(port_str) else { + return Ok(None); + }; + return Ok(Some(( + MongoTargetHost { + host, + port: Some(port), + }, + true, + ))); + } + + let Some(colon_idx) = trimmed.find(':') else { + let host = decode_mongo_host(trimmed, false, allow_unix_socket)? + .trim() + .to_owned(); + if host.is_empty() { + return Ok(None); + } + if allow_unix_socket && is_unix_domain_socket_host(&host) { + return Ok(Some((MongoTargetHost { host, port: None }, false))); + } + return Ok(Some(( + MongoTargetHost { + host, + port: default_port, + }, + false, + ))); + }; + + if trimmed[colon_idx + 1..].contains(':') { + return Ok(None); + } + + let raw_host = trimmed[..colon_idx].trim(); + let port_str = trimmed[colon_idx + 1..].trim(); + if raw_host.is_empty() { + return Ok(None); + } + let host = decode_mongo_host(raw_host, false, false)?.trim().to_owned(); + if host.is_empty() { + return Ok(None); + } + if port_str.is_empty() { + return Ok(Some(( + MongoTargetHost { + host, + port: default_port, + }, + true, + ))); + } + let Some(port) = parse_port(port_str) else { + return Ok(None); + }; + Ok(Some(( + MongoTargetHost { + host, + port: Some(port), + }, + true, + ))) +} + +fn normalize_host(host: &str) -> String { + let s = host.trim(); + let s = s.strip_prefix('[').unwrap_or(s); + let s = s.strip_suffix(']').unwrap_or(s); + s.trim_end_matches('.').to_lowercase() +} + +fn normalize_local_host_entry(raw: &str) -> Option { + let s = raw.trim(); + let s = s.strip_prefix('[').unwrap_or(s); + let s = s.strip_suffix(']').unwrap_or(s); + let s = s.split('%').next().unwrap_or(""); + let normalized = s.trim().trim_end_matches('.').to_lowercase(); + if normalized.is_empty() { + None + } else { + Some(normalized) + } +} + +fn parse_ipv4_octets(host: &str) -> Option<[u8; 4]> { + let mut parts = host.split('.'); + let mut out = [0u8; 4]; + for slot in &mut out { + let part = parts.next()?; + if part.is_empty() || part.len() > 3 || !part.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + *slot = part.parse::().ok()?; + } + if parts.next().is_some() { + return None; + } + Some(out) +} + +fn parse_ipv4_part(part: &str) -> Option { + if let Some(hex_digits) = part.strip_prefix("0x").or_else(|| part.strip_prefix("0X")) { + if hex_digits.is_empty() { + return Some(0); + } + if !hex_digits.bytes().all(|b| b.is_ascii_hexdigit()) { + return None; + } + return u32::from_str_radix(hex_digits, 16).ok(); + } + if part.len() >= 2 && part.starts_with('0') && part.bytes().all(|b| (b'0'..=b'7').contains(&b)) { + return u32::from_str_radix(part, 8).ok(); + } + if part == "0" + || (!part.is_empty() + && !part.starts_with('0') + && part.bytes().all(|b| b.is_ascii_digit())) + { + return part.parse::().ok(); + } + None +} + +fn parse_numeric_ipv4_octets(host: &str) -> Option<[u8; 4]> { + let parts: Vec<&str> = host.split('.').collect(); + if parts.is_empty() || parts.len() > 4 { + return None; + } + let mut parsed = [0u32; 4]; + for (idx, part) in parts.iter().enumerate() { + parsed[idx] = parse_ipv4_part(part)?; + } + + match parts.len() { + 1 => { + let p0 = parsed[0]; + Some([ + ((p0 >> 24) & 0xff) as u8, + ((p0 >> 16) & 0xff) as u8, + ((p0 >> 8) & 0xff) as u8, + (p0 & 0xff) as u8, + ]) + } + 2 => { + let (p0, p1) = (parsed[0], parsed[1]); + if p0 > 0xff || p1 > 0x00ff_ffff { + return None; + } + Some([ + p0 as u8, + ((p1 >> 16) & 0xff) as u8, + ((p1 >> 8) & 0xff) as u8, + (p1 & 0xff) as u8, + ]) + } + 3 => { + let (p0, p1, p2) = (parsed[0], parsed[1], parsed[2]); + if p0 > 0xff || p1 > 0xff || p2 > 0xffff { + return None; + } + Some([ + p0 as u8, + p1 as u8, + ((p2 >> 8) & 0xff) as u8, + (p2 & 0xff) as u8, + ]) + } + 4 => { + let (p0, p1, p2, p3) = (parsed[0], parsed[1], parsed[2], parsed[3]); + if p0 > 0xff || p1 > 0xff || p2 > 0xff || p3 > 0xff { + return None; + } + Some([p0 as u8, p1 as u8, p2 as u8, p3 as u8]) + } + _ => None, + } +} + +fn parse_decimal_ipv4_octets(host: &str) -> Option<[u8; 4]> { + let mut parts = host.split('.'); + let mut out = [0u8; 4]; + for slot in &mut out { + let part = parts.next()?; + if part.is_empty() || !part.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + *slot = part.parse::().ok()?; + } + if parts.next().is_some() { + return None; + } + Some(out) +} + +fn is_ipv4_loopback_octets(octets: [u8; 4]) -> bool { + octets[0] == 127 || octets == [0, 0, 0, 0] +} + +fn is_ipv4_loopback(host: &str) -> bool { + parse_numeric_ipv4_octets(host).is_some_and(is_ipv4_loopback_octets) + || parse_decimal_ipv4_octets(host).is_some_and(is_ipv4_loopback_octets) +} + +fn parse_ipv6_side(side: &str, allow_ipv4_tail: bool) -> Option> { + if side.is_empty() { + return Some(Vec::new()); + } + let parts: Vec<&str> = side.split(':').collect(); + let mut groups = Vec::with_capacity(parts.len() + 1); + for (idx, part) in parts.iter().enumerate() { + if idx + 1 == parts.len() && allow_ipv4_tail && part.contains('.') { + let octets = parse_ipv4_octets(part)?; + groups.push(((octets[0] as u16) << 8) | (octets[1] as u16)); + groups.push(((octets[2] as u16) << 8) | (octets[3] as u16)); + continue; + } + if part.is_empty() || part.len() > 4 || !part.bytes().all(|b| b.is_ascii_hexdigit()) { + return None; + } + groups.push(u16::from_str_radix(part, 16).ok()?); + } + Some(groups) +} + +fn parse_ipv6_hextets(host: &str) -> Option<[u16; 8]> { + if !host.contains(':') { + return None; + } + let addr = match host.find('%') { + Some(zone_idx) => &host[..zone_idx], + None => host, + }; + let halves: Vec<&str> = addr.split("::").collect(); + if halves.len() > 2 { + return None; + } + if halves.len() == 1 { + let groups = parse_ipv6_side(halves[0], true)?; + return groups.try_into().ok(); + } + + let left = parse_ipv6_side(halves[0], false)?; + let right = parse_ipv6_side(halves[1], true)?; + let total = left.len() + right.len(); + if total >= 8 { + return None; + } + let missing = 8 - total; + let mut out = [0u16; 8]; + out[..left.len()].copy_from_slice(&left); + out[left.len() + missing..].copy_from_slice(&right); + Some(out) +} + +fn is_ipv6_loopback(host: &str) -> bool { + let Some(hextets) = parse_ipv6_hextets(host) else { + return false; + }; + if hextets[..7] == [0; 7] { + return hextets[7] == 0 || hextets[7] == 1; + } + if hextets[..5] == [0; 5] && hextets[5] == 0xffff { + let first_octet = (hextets[6] >> 8) & 0xff; + return first_octet == 127 || (hextets[6] == 0 && hextets[7] == 0); + } + false +} + +fn is_loopback_normalized(normalized: &str) -> bool { + normalized == "localhost" + || normalized == "0.0.0.0" + || is_ipv4_loopback(normalized) + || is_ipv6_loopback(normalized) +} + +fn is_local_machine_host(host: &str, local_hosts: &LocalHosts) -> bool { + if host.is_empty() { + return false; + } + let normalized = normalize_host(host); + if is_loopback_normalized(&normalized) { + return true; + } + if local_hosts.hosts.contains(&normalized) { + return true; + } + if let Some(zone_idx) = normalized.find('%') { + if local_hosts.hosts.contains(&normalized[..zone_idx]) { + return true; + } + } + if let Some([a, b, c, d]) = parse_numeric_ipv4_octets(&normalized) { + let dotted = format!("{a}.{b}.{c}.{d}"); + if local_hosts.hosts.contains(&dotted) { + return true; + } + } + if let Some([a, b, c, d]) = parse_decimal_ipv4_octets(&normalized) { + let dotted = format!("{a}.{b}.{c}.{d}"); + if local_hosts.hosts.contains(&dotted) { + return true; + } + } + false +} + +#[cfg(test)] +#[path = "mongo_safety_tests.rs"] +mod tests; diff --git a/tools/curate-etl/src/mongo_safety_tests.rs b/tools/curate-etl/src/mongo_safety_tests.rs new file mode 100644 index 00000000..dbc12fe8 --- /dev/null +++ b/tools/curate-etl/src/mongo_safety_tests.rs @@ -0,0 +1,2580 @@ +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) { + 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 `\t\t` + // // 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 = 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 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 = Box::new(err); + let boxed_display = format!("{boxed}"); + let boxed_debug = format!("{boxed:?}"); + if !pw.is_empty() { + assert!( + !boxed_display.contains(pw), + "{label}: Box Display leaked password: {boxed_display}" + ); + assert!( + !boxed_debug.contains(pw), + "{label}: Box 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); +} diff --git a/tools/curate-etl/src/mongo_stream.rs b/tools/curate-etl/src/mongo_stream.rs new file mode 100644 index 00000000..1ae0ff76 --- /dev/null +++ b/tools/curate-etl/src/mongo_stream.rs @@ -0,0 +1,807 @@ +//! Driver-independent read-only MongoDB raw-BSON cursor seam (`M1.2al`). +//! +//! 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. +//! - 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::{Bson, DateTime, Document}; + +use crate::bson_stream::{DEFAULT_MAX_DOC_BYTES, MIN_BSON_DOC_BYTES}; +use crate::events::parse_filing_timefiled; +use crate::mongo_safety::{redact_mongo_uri_password, ValidatedReadOnlyMongoUri}; + +/// Default MongoDB cursor batch size (matches `DEFAULT_RAW_BSON_BATCH_SIZE`). +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; + +/// Closed allowlist of the 8 M1 MongoDB source collections consumed by `curate-etl`. +/// +/// Order and names match `RAW_BSON_EXPORT_COLLECTIONS` in +/// `apps/stock/data-pipeline/src/security-master/export-raw-bson.ts`. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum SourceCollection { + EodPrices, + QmSplits, + QmDividends, + QmPrices, + TeMarketData, + CeoShorts, + QmFilings, + QmEarnings, +} + +impl SourceCollection { + /// All 8 allowlisted M1 source collections in canonical order. + pub const ALL: [SourceCollection; 8] = [ + Self::EodPrices, + Self::QmSplits, + Self::QmDividends, + Self::QmPrices, + Self::TeMarketData, + Self::CeoShorts, + Self::QmFilings, + Self::QmEarnings, + ]; + + /// Exact MongoDB collection name. + pub const fn as_str(self) -> &'static str { + match self { + Self::EodPrices => "eodPrices", + Self::QmSplits => "qmSplits", + Self::QmDividends => "qmDividends", + Self::QmPrices => "qmPrices", + Self::TeMarketData => "teMarketData", + Self::CeoShorts => "ceoShorts", + Self::QmFilings => "qmFilings", + Self::QmEarnings => "qmEarnings", + } + } + + /// Primary provider key field used for exact equality filters (`key_eq`). + pub const fn key_field(self) -> &'static str { + match self { + Self::EodPrices => "eodSearchCode", + Self::QmSplits => "qmSearchCode", + Self::QmDividends => "qmSearchCode", + Self::QmPrices => "qmSearchCode", + Self::TeMarketData => "teSymbol", + Self::CeoShorts => "symbol", + Self::QmFilings => "symbol", + Self::QmEarnings => "qmSearchCode", + } + } + + /// Date/timestamp field used for range filters (`date_range`), or `None` + /// for document-per-symbol collections (`teMarketData`). + pub const fn date_field(self) -> Option<&'static str> { + match self { + Self::EodPrices => Some("date"), + Self::QmSplits => Some("date"), + Self::QmDividends => Some("date"), + Self::QmPrices => Some("date"), + Self::TeMarketData => None, + Self::CeoShorts => Some("timestamp"), + Self::QmFilings => Some("timefiled"), + Self::QmEarnings => Some("reportDate"), + } + } +} + +impl fmt::Display for SourceCollection { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.as_str()) + } +} + +/// Typed date bound value for [`MongoDateRange`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum FilterDateValue { + /// Lexicographically ordered ISO-8601 date/timestamp string (e.g. `"2024-01-01"`). + IsoString(String), + /// BSON UTC `DateTime` expressed as milliseconds since the Unix epoch. + BsonDateTimeMillis(i64), +} + +impl FilterDateValue { + fn to_bson(&self) -> Bson { + match self { + Self::IsoString(s) => Bson::String(s.clone()), + Self::BsonDateTimeMillis(ms) => Bson::DateTime(DateTime::from_millis(*ms)), + } + } +} + +/// Half-open `[gte, lt)` date filter for a [`SourceCollection`] with a date field. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct MongoDateRange { + pub gte: Option, + pub lt: Option, +} + +/// Typed read specification for a read-only MongoDB cursor query. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct MongoReadSpec { + /// Optional exact match on [`SourceCollection::key_field`]. + pub key_eq: Option, + /// Optional `[gte, lt)` range on [`SourceCollection::date_field`]. + pub date_range: Option, + /// MongoDB cursor `batchSize` (in `1..=MAX_MONGO_BATCH_SIZE`). + pub batch_size: u32, + /// Optional maximum number of documents to return (in `1..=i64::MAX`). + pub limit: Option, + /// Maximum allowed single raw BSON document length in bytes (`>= MIN_BSON_DOC_BYTES`). + pub max_doc_bytes: usize, +} + +impl Default for MongoReadSpec { + fn default() -> Self { + Self { + key_eq: None, + date_range: None, + batch_size: DEFAULT_MONGO_BATCH_SIZE, + limit: None, + max_doc_bytes: DEFAULT_MAX_DOC_BYTES, + } + } +} + +impl MongoReadSpec { + /// Validates all read specification invariants for `collection`. + pub fn validate(&self, collection: SourceCollection) -> Result<(), MongoStreamError> { + if self.batch_size == 0 || self.batch_size > MAX_MONGO_BATCH_SIZE { + return Err(MongoStreamError::InvalidBatchSize { + batch_size: self.batch_size, + max_batch_size: MAX_MONGO_BATCH_SIZE, + }); + } + if let Some(limit) = self.limit { + if limit == 0 || limit > i64::MAX as u64 { + return Err(MongoStreamError::InvalidLimit { limit }); + } + } + if self.max_doc_bytes < MIN_BSON_DOC_BYTES { + return Err(MongoStreamError::InvalidMaxDocBytes { + max_doc_bytes: self.max_doc_bytes, + min_doc_bytes: MIN_BSON_DOC_BYTES, + }); + } + if let Some(key) = &self.key_eq { + if key.trim().is_empty() { + return Err(MongoStreamError::InvalidKeyFilter { collection }); + } + } + if let Some(range) = &self.date_range { + if collection.date_field().is_none() { + return Err(MongoStreamError::DateRangeNotSupported { collection }); + } + if range.gte.is_none() && range.lt.is_none() { + return Err(MongoStreamError::InvalidDateRange { + collection, + detail: "at least one of gte or lt must be set".to_owned(), + }); + } + if let Some(FilterDateValue::IsoString(s)) = &range.gte { + if s.trim().is_empty() { + return Err(MongoStreamError::InvalidDateRange { + collection, + detail: "gte ISO string must not be empty or blank".to_owned(), + }); + } + } + if let Some(FilterDateValue::IsoString(s)) = &range.lt { + if s.trim().is_empty() { + return Err(MongoStreamError::InvalidDateRange { + collection, + detail: "lt ISO string must not be empty or blank".to_owned(), + }); + } + } + if collection == SourceCollection::QmFilings { + 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" + ), + }); + } + Ok(()) + } + Some(FilterDateValue::BsonDateTimeMillis(_)) => { + Err(MongoStreamError::InvalidDateRange { + collection, + 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) { + (FilterDateValue::IsoString(a), FilterDateValue::IsoString(b)) => { + if a >= b { + return Err(MongoStreamError::InvalidDateRange { + collection, + detail: format!("gte ({a:?}) must be strictly less than lt ({b:?})"), + }); + } + } + ( + FilterDateValue::BsonDateTimeMillis(a), + FilterDateValue::BsonDateTimeMillis(b), + ) => { + if a >= b { + return Err(MongoStreamError::InvalidDateRange { + collection, + detail: format!("gte ({a}) must be strictly less than lt ({b})"), + }); + } + } + _ => { + return Err(MongoStreamError::InvalidDateRange { + collection, + detail: "gte and lt must use the same FilterDateValue variant" + .to_owned(), + }); + } + } + } + } + Ok(()) + } +} + +/// Validates `spec` and constructs the corresponding MongoDB `find` filter [`Document`]. +pub fn build_filter_document( + collection: SourceCollection, + spec: &MongoReadSpec, +) -> Result { + spec.validate(collection)?; + + let mut entries: Vec<(String, Bson)> = Vec::with_capacity(2); + if let Some(key) = &spec.key_eq { + entries.push((collection.key_field().to_owned(), Bson::String(key.clone()))); + } + if let Some(range) = &spec.date_range { + if let Some(date_field) = collection.date_field() { + let mut range_entries: Vec<(String, Bson)> = Vec::with_capacity(2); + if let Some(gte) = &range.gte { + range_entries.push(("$gte".to_owned(), gte.to_bson())); + } + if let Some(lt) = &range.lt { + range_entries.push(("$lt".to_owned(), lt.to_bson())); + } + entries.push(( + date_field.to_owned(), + Bson::Document(Document::from_iter(range_entries)), + )); + } + } + + Ok(Document::from_iter(entries)) +} + +/// Redacted error type for MongoDB raw-BSON cursor streaming. +/// +/// Intentionally never stores raw URIs or passwords. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum MongoStreamError { + InvalidBatchSize { + batch_size: u32, + max_batch_size: u32, + }, + InvalidLimit { + limit: u64, + }, + InvalidMaxDocBytes { + max_doc_bytes: usize, + min_doc_bytes: usize, + }, + InvalidKeyFilter { + collection: SourceCollection, + }, + DateRangeNotSupported { + collection: SourceCollection, + }, + InvalidDateRange { + collection: SourceCollection, + detail: String, + }, + InvalidBsonFrame { + doc_index: u64, + detail: 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::InvalidBatchSize { + batch_size, + max_batch_size, + } => write!( + f, + "invalid MongoDB batch_size {batch_size}: must be in 1..={max_batch_size}" + ), + Self::InvalidLimit { limit } => write!( + f, + "invalid MongoDB limit {limit}: must be in 1..={}", + i64::MAX + ), + Self::InvalidMaxDocBytes { + max_doc_bytes, + min_doc_bytes, + } => write!( + f, + "invalid max_doc_bytes {max_doc_bytes}: must be >= {min_doc_bytes}" + ), + Self::InvalidKeyFilter { collection } => write!( + f, + "invalid key_eq filter for collection {collection}: must not be empty or blank" + ), + Self::DateRangeNotSupported { collection } => write!( + f, + "date_range filter is not supported for collection {collection}" + ), + Self::InvalidDateRange { collection, detail } => { + write!(f, "invalid date_range for collection {collection}: {detail}") + } + Self::InvalidBsonFrame { doc_index, detail } => { + write!(f, "invalid raw BSON frame at doc #{doc_index}: {detail}") + } + Self::Source { detail } => write!(f, "raw BSON source error: {detail}"), + } + } +} + +impl Error for MongoStreamError {} + +/// Driver-independent seam yielding one raw length-prefixed BSON document at a time. +pub trait RawDocumentSource { + /// Advances to the next raw BSON document and returns its byte slice, + /// or `Ok(None)` when the source is exhausted. + fn next_raw_document(&mut self) -> Result, MongoStreamError>; +} + +/// Zero-copy in-memory [`RawDocumentSource`] over a slice of borrowed raw BSON frames. +#[derive(Debug, Clone)] +pub struct SliceRawDocumentSource<'a> { + docs: &'a [&'a [u8]], + index: usize, +} + +impl<'a> SliceRawDocumentSource<'a> { + pub fn new(docs: &'a [&'a [u8]]) -> Self { + Self { docs, index: 0 } + } +} + +impl<'a> RawDocumentSource for SliceRawDocumentSource<'a> { + #[inline] + fn next_raw_document(&mut self) -> Result, MongoStreamError> { + let Some(&doc) = self.docs.get(self.index) else { + return Ok(None); + }; + self.index += 1; + Ok(Some(doc)) + } +} + +/// Owned in-memory [`RawDocumentSource`] over a `Vec>` of raw BSON frames. +#[derive(Debug, Clone)] +pub struct VecRawDocumentSource { + docs: Vec>, + index: usize, +} + +impl VecRawDocumentSource { + pub fn new(docs: Vec>) -> Self { + Self { docs, index: 0 } + } +} + +impl RawDocumentSource for VecRawDocumentSource { + #[inline] + fn next_raw_document(&mut self) -> Result, MongoStreamError> { + if self.index >= self.docs.len() { + return Ok(None); + } + let doc = self.docs[self.index].as_slice(); + self.index += 1; + Ok(Some(doc)) + } +} + +fn validate_raw_bson_frame( + doc: &[u8], + doc_index: u64, + max_doc_bytes: usize, +) -> Result<(), MongoStreamError> { + if doc.len() < MIN_BSON_DOC_BYTES { + return Err(MongoStreamError::InvalidBsonFrame { + doc_index, + detail: format!( + "frame length {} is below minimum BSON document size ({MIN_BSON_DOC_BYTES})", + doc.len() + ), + }); + } + if doc.len() > max_doc_bytes { + return Err(MongoStreamError::InvalidBsonFrame { + doc_index, + detail: format!( + "frame length {} exceeds max_doc_bytes ({max_doc_bytes})", + doc.len() + ), + }); + } + let declared_len = i32::from_le_bytes([doc[0], doc[1], doc[2], doc[3]]); + if declared_len < MIN_BSON_DOC_BYTES as i32 || (declared_len as usize) != doc.len() { + return Err(MongoStreamError::InvalidBsonFrame { + doc_index, + detail: format!( + "4-byte LE length prefix ({declared_len}) disagrees with byte length ({})", + doc.len() + ), + }); + } + let last_byte = doc[doc.len() - 1]; + if last_byte != 0x00 { + return Err(MongoStreamError::InvalidBsonFrame { + doc_index, + detail: format!("missing trailing 0x00 terminator (got 0x{last_byte:02x})"), + }); + } + Ok(()) +} + +/// Bounded-memory [`io::Read`] adapter that turns any [`RawDocumentSource`] +/// into a concatenated raw BSON byte stream for [`crate::bson_stream::RawBsonChunkReader`] +/// and `decode_*_stream`. +/// +/// Copies documents directly into the caller's buffer whenever they fit, +/// spilling only the unread tail of a single current document into a reused +/// `pending` buffer when the caller's buffer is smaller. +pub struct RawBsonCursorReader { + source: S, + max_doc_bytes: usize, + pending: Vec, + pending_pos: usize, + docs_read: u64, + bytes_read: u64, + eof: bool, + stashed_error: Option, + sticky_error: Option, +} + +impl RawBsonCursorReader { + /// Wraps `source` with the default maximum BSON document size ([`DEFAULT_MAX_DOC_BYTES`]). + pub fn new(source: S) -> Self { + Self { + source, + max_doc_bytes: DEFAULT_MAX_DOC_BYTES, + pending: Vec::new(), + pending_pos: 0, + docs_read: 0, + bytes_read: 0, + eof: false, + stashed_error: None, + sticky_error: None, + } + } + + /// Wraps `source` with an explicit `max_doc_bytes` ceiling (`>= MIN_BSON_DOC_BYTES`). + pub fn with_max_doc_bytes(source: S, max_doc_bytes: usize) -> Result { + if max_doc_bytes < MIN_BSON_DOC_BYTES { + return Err(MongoStreamError::InvalidMaxDocBytes { + max_doc_bytes, + min_doc_bytes: MIN_BSON_DOC_BYTES, + }); + } + Ok(Self { + source, + max_doc_bytes, + pending: Vec::new(), + pending_pos: 0, + docs_read: 0, + bytes_read: 0, + eof: false, + stashed_error: None, + sticky_error: None, + }) + } + + /// Number of valid raw BSON documents accepted from the underlying source. + #[inline] + pub fn docs_read(&self) -> u64 { + self.docs_read + } + + /// Total bytes across all valid raw BSON documents accepted from the underlying source. + #[inline] + pub fn bytes_read(&self) -> u64 { + self.bytes_read + } + + /// Current allocated capacity of the single-document tail spill buffer. + #[inline] + pub fn pending_capacity(&self) -> usize { + self.pending.capacity() + } + + /// Consumes the adapter and returns the underlying source. + pub fn into_inner(self) -> S { + self.source + } +} + +impl io::Read for RawBsonCursorReader { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + if buf.is_empty() { + return Ok(0); + } + if let Some(err) = &self.sticky_error { + return Err(io::Error::other(err.clone())); + } + if let Some(err) = self.stashed_error.take() { + self.sticky_error = Some(err.clone()); + return Err(io::Error::other(err)); + } + + let mut written = 0usize; + while written < buf.len() { + if self.pending_pos < self.pending.len() { + let avail = self.pending.len() - self.pending_pos; + let take = avail.min(buf.len() - written); + buf[written..written + take] + .copy_from_slice(&self.pending[self.pending_pos..self.pending_pos + take]); + self.pending_pos += take; + written += take; + if self.pending_pos == self.pending.len() { + self.pending.clear(); + self.pending_pos = 0; + } + continue; + } + + if self.eof { + break; + } + + match self.source.next_raw_document() { + Ok(None) => { + self.eof = true; + break; + } + Ok(Some(doc)) => { + if let Err(err) = + validate_raw_bson_frame(doc, self.docs_read, self.max_doc_bytes) + { + if written > 0 { + self.stashed_error = Some(err); + return Ok(written); + } + self.sticky_error = Some(err.clone()); + return Err(io::Error::other(err)); + } + + self.docs_read += 1; + self.bytes_read += doc.len() as u64; + + let remaining = buf.len() - written; + if doc.len() <= remaining { + buf[written..written + doc.len()].copy_from_slice(doc); + written += doc.len(); + } else { + buf[written..written + remaining].copy_from_slice(&doc[..remaining]); + written += remaining; + let tail = &doc[remaining..]; + self.pending.clear(); + if self.pending.capacity() < tail.len() { + self.pending.reserve_exact(tail.len()); + } + self.pending.extend_from_slice(tail); + self.pending_pos = 0; + break; + } + } + Err(err) => { + if written > 0 { + self.stashed_error = Some(err); + return Ok(written); + } + self.sticky_error = Some(err.clone()); + return Err(io::Error::other(err)); + } + } + } + + Ok(written) + } +} + +fn extract_raw_uri_password(uri: &str) -> Option<&str> { + let scheme_end = uri.find("://")?; + let rest = &uri[scheme_end + 3..]; + let authority_end = rest.find(['/', '?']).unwrap_or(rest.len()); + let authority = &rest[..authority_end]; + let at_idx = authority.find('@')?; + let userinfo = &authority[..at_idx]; + let colon_idx = userinfo.find(':')?; + let pass = &userinfo[colon_idx + 1..]; + if pass.is_empty() { + None + } else { + Some(pass) + } +} + +fn percent_decode_best_effort(input: &str) -> Option { + let bytes = input.as_bytes(); + let mut out = Vec::with_capacity(bytes.len()); + let mut i = 0; + while i < bytes.len() { + if bytes[i] == b'%' && i + 2 < bytes.len() { + let hi = hex_nibble(bytes[i + 1])?; + let lo = hex_nibble(bytes[i + 2])?; + out.push((hi << 4) | lo); + i += 3; + } else { + out.push(bytes[i]); + i += 1; + } + } + String::from_utf8(out).ok() +} + +fn hex_nibble(b: u8) -> Option { + match b { + b'0'..=b'9' => Some(b - b'0'), + b'a'..=b'f' => Some(b - b'a' + 10), + b'A'..=b'F' => Some(b - b'A' + 10), + _ => None, + } +} + +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 Some((rel_start, scheme_len)) = find_next_mongo_scheme(&lower[cursor..]) else { + result.push_str(&text[cursor..]); + break; + }; + + let start = cursor + rel_start; + result.push_str(&text[cursor..start]); + + let tail = &text[start..]; + let after_scheme = &tail[scheme_len..]; + 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('@') { + let userinfo = &authority_region[..at_idx]; + if let Some(colon_idx) = userinfo.find(':') { + let prefix_with_at = &tail[..scheme_len + at_idx + 1]; + if !userinfo.contains('@') { + result.push_str(&redact_mongo_uri_password(prefix_with_at)); + } else { + result.push_str(&tail[..scheme_len + colon_idx + 1]); + result.push_str("[REDACTED]@"); + } + cursor = start + scheme_len + at_idx + 1; + continue; + } + } + + let advance = scheme_len + authority_end; + result.push_str(&tail[..advance]); + cursor = start + advance; + } + + result +} + +/// Strips raw URI, raw password, percent-decoded password, and any embedded +/// `mongodb://` / `mongodb+srv://` userinfo passwords from driver error text. +pub(crate) fn sanitize_driver_error_message( + raw_message: &str, + uri: &ValidatedReadOnlyMongoUri, +) -> String { + let redacted_uri = uri.redacted(); + let mut sanitized = raw_message.split(uri.as_str()).collect::>().join(&redacted_uri); + + if let Some(raw_pass) = extract_raw_uri_password(uri.as_str()) { + sanitized = sanitized.split(raw_pass).collect::>().join("[REDACTED]"); + if let Some(decoded_pass) = percent_decode_best_effort(raw_pass) { + if !decoded_pass.is_empty() && decoded_pass != raw_pass { + sanitized = sanitized + .split(&decoded_pass) + .collect::>() + .join("[REDACTED]"); + } + } + } + + redact_embedded_mongo_uris(&sanitized) +} + +#[cfg(test)] +#[path = "mongo_stream_tests.rs"] +mod tests; diff --git a/tools/curate-etl/src/mongo_stream_tests.rs b/tools/curate-etl/src/mongo_stream_tests.rs new file mode 100644 index 00000000..208faaa4 --- /dev/null +++ b/tools/curate-etl/src/mongo_stream_tests.rs @@ -0,0 +1,1906 @@ +use std::fs; +use std::io::{self, Cursor, Read}; +use std::path::PathBuf; + +use bson::raw::{cstr, RawDocumentBuf}; +use bson::{Bson, DateTime}; + +use crate::bson_qm_events::QmFilingsFieldNames; +use crate::bson_stream::{ + decode_eod_price_stream, decode_qm_dividend_stream, decode_qm_filings_stream, + decode_qm_split_stream, BsonStreamError, BsonStreamOptions, MIN_BSON_DOC_BYTES, +}; +use crate::mongo_safety::{ + assert_read_only_mongo_uri, LocalHosts, ReadOnlyPolicy, ValidatedReadOnlyMongoUri, +}; +use crate::mongo_stream::{ + 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 { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("eodSearchCode"), code); + doc.append(cstr!("date"), date); + doc.append(cstr!("open"), close); + doc.append(cstr!("high"), close + 1.0); + doc.append(cstr!("low"), (close - 1.0).max(0.1)); + doc.append(cstr!("close"), close); + doc.append(cstr!("volume"), volume); + doc.into_bytes() +} + +fn build_eod_reject_doc(code: &str) -> Vec { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("eodSearchCode"), code); + doc.append(cstr!("date"), "not-a-date"); + doc.append(cstr!("open"), 10.0); + doc.append(cstr!("high"), 11.0); + doc.append(cstr!("low"), 9.0); + doc.append(cstr!("close"), 10.5); + doc.append(cstr!("volume"), 100.0); + doc.into_bytes() +} + +fn build_qm_split_doc(code: &str, date: &str, ratio: f64) -> Vec { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("qmSearchCode"), code); + doc.append(cstr!("date"), date); + doc.append(cstr!("splitratio"), ratio); + doc.into_bytes() +} + +fn build_qm_split_reject_doc(code: &str) -> Vec { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("qmSearchCode"), code); + doc.append(cstr!("date"), "2024-06-10"); + doc.append(cstr!("splitratio"), "bad-type"); + doc.into_bytes() +} + +fn build_qm_dividend_doc(code: &str, date: &str, cash: f64, currency: &str) -> Vec { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("qmSearchCode"), code); + doc.append(cstr!("date"), date); + doc.append(cstr!("amount"), cash); + doc.append(cstr!("currency"), currency); + doc.into_bytes() +} + +fn build_qm_dividend_reject_doc(code: &str) -> Vec { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("qmSearchCode"), code); + doc.append(cstr!("date"), "2024-06-10"); + doc.append(cstr!("amount"), -1.0); + doc.append(cstr!("currency"), "USD"); + doc.into_bytes() +} + +fn build_qm_filing_doc( + symbol: &str, + timefiled: &str, + form_type: &str, + filing_id: Option<&str>, +) -> Vec { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("symbol"), symbol); + doc.append(cstr!("timefiled"), timefiled); + doc.append(cstr!("formtype"), form_type); + if let Some(id) = filing_id { + doc.append(cstr!("filingid"), id); + } + doc.into_bytes() +} + +fn build_qm_filing_reject_doc(symbol: &str) -> Vec { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("symbol"), symbol); + doc.append(cstr!("timefiled"), "2024-06-10T16:30:00 EDT"); + // Missing required formtype -> semantic skip + doc.into_bytes() +} + +fn concat_docs(docs: &[Vec]) -> Vec { + let total: usize = docs.iter().map(Vec::len).sum(); + let mut out = Vec::with_capacity(total); + for doc in docs { + out.extend_from_slice(doc); + } + out +} + +/// Wraps any `io::Read` and caps every single `read()` call to `max_step` bytes, +/// exercising tiny (1-byte) and odd-sized (`3`, `7`, `13`, `37` B) read buffers. +struct CappedRead { + inner: R, + max_step: usize, +} + +impl CappedRead { + fn new(inner: R, max_step: usize) -> Self { + Self { inner, max_step } + } +} + +impl Read for CappedRead { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + let cap = buf.len().min(self.max_step); + self.inner.read(&mut buf[..cap]) + } +} + +fn read_all_with_step(reader: &mut R, step: usize) -> io::Result> { + let mut out = Vec::new(); + let mut buf = vec![0u8; step]; + loop { + let n = reader.read(&mut buf)?; + if n == 0 { + break; + } + out.extend_from_slice(&buf[..n]); + } + Ok(out) +} + +fn validate_uri(raw: &str) -> ValidatedReadOnlyMongoUri { + assert_read_only_mongo_uri(raw, &ReadOnlyPolicy::default(), &LocalHosts::empty()) + .expect("test URI must pass read-only safety guard") +} + +struct FailingSource { + docs: Vec>, + index: usize, + fail_at: usize, + err: MongoStreamError, +} + +impl RawDocumentSource for FailingSource { + fn next_raw_document(&mut self) -> Result, MongoStreamError> { + if self.index == self.fail_at { + return Err(self.err.clone()); + } + if self.index >= self.docs.len() { + return Ok(None); + } + let doc = self.docs[self.index].as_slice(); + self.index += 1; + Ok(Some(doc)) + } +} + +// --------------------------------------------------------------------------- +// 1. Allowlist parity against export-raw-bson.ts +// --------------------------------------------------------------------------- + +#[test] +fn source_collection_allowlist_matches_export_raw_bson_ts_exactly() { + let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")); + let ts_path = manifest_dir + .join("..") + .join("..") + .join("apps") + .join("stock") + .join("data-pipeline") + .join("src") + .join("security-master") + .join("export-raw-bson.ts"); + + let contents = fs::read_to_string(&ts_path) + .unwrap_or_else(|err| panic!("failed to read {}: {err}", ts_path.display())); + + let anchor = "export const RAW_BSON_EXPORT_COLLECTIONS = Object.freeze(["; + let start = contents + .find(anchor) + .expect("RAW_BSON_EXPORT_COLLECTIONS declaration not found in export-raw-bson.ts") + + anchor.len(); + let rest = &contents[start..]; + let end = rest + .find("] as const") + .expect("closing `] as const` not found for RAW_BSON_EXPORT_COLLECTIONS"); + let block = &rest[..end]; + + let ts_names: Vec = block + .lines() + .filter_map(|line| { + let trimmed = line.trim(); + let first_quote = trimmed.find('\'')?; + let after_first = &trimmed[first_quote + 1..]; + let second_quote = after_first.find('\'')?; + Some(after_first[..second_quote].to_owned()) + }) + .collect(); + + let rust_names: Vec<&str> = SourceCollection::ALL.iter().map(|c| c.as_str()).collect(); + let expected = vec![ + "eodPrices", + "qmSplits", + "qmDividends", + "qmPrices", + "teMarketData", + "ceoShorts", + "qmFilings", + "qmEarnings", + ]; + + assert_eq!(rust_names, expected); + assert_eq!( + ts_names, + rust_names + .iter() + .map(|s| (*s).to_owned()) + .collect::>(), + "SourceCollection::ALL must match RAW_BSON_EXPORT_COLLECTIONS in exact names and order" + ); + assert_eq!(SourceCollection::ALL.len(), 8); +} + +// --------------------------------------------------------------------------- +// 2. Decoder parity across 4 collections + 1-byte and odd-sized buffers +// --------------------------------------------------------------------------- + +#[test] +fn parity_eod_prices_stream_across_default_and_odd_buffers() { + let docs = vec![ + build_eod_doc("AAPL.US", "2024-01-02", 185.5, 1000.0), + build_eod_reject_doc("BAD.US"), + build_eod_doc("NVDA.US", "2024-06-10", 121.75, 50_000.0), + build_eod_doc("RY.TO", "2024-12-31", 173.25, 250_000.0), + ]; + let concat = concat_docs(&docs); + let total_bytes = concat.len() as u64; + + let mut expected_rows = Vec::new(); + let mut expected_errs = Vec::new(); + let expected_stats = decode_eod_price_stream( + Cursor::new(&concat), + BsonStreamOptions::default(), + |bar| { + expected_rows.push(( + bar.eod_search_code.to_owned(), + bar.session_date, + bar.open.to_bits(), + bar.high.to_bits(), + bar.low.to_bits(), + bar.close.to_bits(), + bar.adj_volume.to_bits(), + )); + }, + |offset, err| expected_errs.push((offset, err)), + ) + .expect("baseline cursor decode must succeed"); + assert_eq!(expected_rows.len(), 3, "baseline eodPrices must decode 3 valid rows"); + assert_eq!(expected_errs.len(), 1, "baseline eodPrices must reject 1 invalid doc"); + assert_eq!(expected_stats.decoded, 3); + assert_eq!(expected_stats.rejected_total(), 1); + + for step in [usize::MAX, 1, 3, 7, 13, 37] { + let mut cursor_reader = RawBsonCursorReader::new(VecRawDocumentSource::new(docs.clone())); + let mut rows = Vec::new(); + let mut errs = Vec::new(); + let stats = if step == usize::MAX { + decode_eod_price_stream( + &mut cursor_reader, + BsonStreamOptions::default(), + |bar| { + rows.push(( + bar.eod_search_code.to_owned(), + bar.session_date, + bar.open.to_bits(), + bar.high.to_bits(), + bar.low.to_bits(), + bar.close.to_bits(), + bar.adj_volume.to_bits(), + )); + }, + |offset, err| errs.push((offset, err)), + ) + .expect("stream decode must succeed") + } else { + decode_eod_price_stream( + CappedRead::new(&mut cursor_reader, step), + BsonStreamOptions::default(), + |bar| { + rows.push(( + bar.eod_search_code.to_owned(), + bar.session_date, + bar.open.to_bits(), + bar.high.to_bits(), + bar.low.to_bits(), + bar.close.to_bits(), + bar.adj_volume.to_bits(), + )); + }, + |offset, err| errs.push((offset, err)), + ) + .expect("capped stream decode must succeed") + }; + + assert_eq!(stats, expected_stats, "eodPrices stats mismatch at step={step}"); + assert_eq!(rows, expected_rows, "eodPrices rows mismatch at step={step}"); + assert_eq!(errs, expected_errs, "eodPrices errors mismatch at step={step}"); + assert_eq!(cursor_reader.docs_read(), docs.len() as u64); + assert_eq!(cursor_reader.bytes_read(), total_bytes); + } +} + +#[test] +fn parity_qm_splits_stream_across_default_and_odd_buffers() { + let docs = vec![ + build_qm_split_doc("NVDA:US", "2024-06-10", 10.0), + build_qm_split_reject_doc("BAD:US"), + build_qm_split_doc("NEXM:CA", "2025-06-18", 0.05), + ]; + let concat = concat_docs(&docs); + + let mut expected_rows = Vec::new(); + let mut expected_errs = Vec::new(); + let expected_stats = decode_qm_split_stream( + Cursor::new(&concat), + BsonStreamOptions::default(), + |row| { + expected_rows.push(( + row.qm_search_code.to_owned(), + row.ex_date, + row.ratio.to_bits(), + row.declared_date, + )); + }, + |offset, err| expected_errs.push((offset, err)), + ) + .expect("baseline qmSplits decode must succeed"); + assert_eq!(expected_rows.len(), 2, "baseline qmSplits must decode 2 valid rows"); + assert_eq!(expected_errs.len(), 1, "baseline qmSplits must reject 1 invalid doc"); + assert_eq!(expected_stats.decoded, 2); + assert_eq!(expected_stats.rejected_total(), 1); + + for step in [usize::MAX, 1, 3, 7, 13, 37] { + let mut cursor_reader = RawBsonCursorReader::new(VecRawDocumentSource::new(docs.clone())); + let mut rows = Vec::new(); + let mut errs = Vec::new(); + let stats = if step == usize::MAX { + decode_qm_split_stream( + &mut cursor_reader, + BsonStreamOptions::default(), + |row| { + rows.push(( + row.qm_search_code.to_owned(), + row.ex_date, + row.ratio.to_bits(), + row.declared_date, + )); + }, + |offset, err| errs.push((offset, err)), + ) + .expect("qmSplits stream decode must succeed") + } else { + decode_qm_split_stream( + CappedRead::new(&mut cursor_reader, step), + BsonStreamOptions::default(), + |row| { + rows.push(( + row.qm_search_code.to_owned(), + row.ex_date, + row.ratio.to_bits(), + row.declared_date, + )); + }, + |offset, err| errs.push((offset, err)), + ) + .expect("capped qmSplits stream decode must succeed") + }; + + assert_eq!(stats, expected_stats, "qmSplits stats mismatch at step={step}"); + assert_eq!(rows, expected_rows, "qmSplits rows mismatch at step={step}"); + assert_eq!(errs, expected_errs, "qmSplits errors mismatch at step={step}"); + assert_eq!(cursor_reader.docs_read(), docs.len() as u64); + assert_eq!(cursor_reader.bytes_read(), concat.len() as u64); + } +} + +#[test] +fn parity_qm_dividends_stream_across_default_and_odd_buffers() { + let docs = vec![ + build_qm_dividend_doc("AAPL:US", "2024-05-10", 0.25, "USD"), + build_qm_dividend_reject_doc("BAD:US"), + build_qm_dividend_doc("RY:CA", "2024-07-25", 1.42, "CAD"), + ]; + let concat = concat_docs(&docs); + + let mut expected_rows = Vec::new(); + let mut expected_errs = Vec::new(); + let expected_stats = decode_qm_dividend_stream( + Cursor::new(&concat), + BsonStreamOptions::default(), + |row| { + expected_rows.push(( + row.qm_search_code.to_owned(), + row.ex_date, + row.cash.to_bits(), + row.currency.to_owned(), + row.declared_date, + )); + }, + |offset, err| expected_errs.push((offset, err)), + ) + .expect("baseline qmDividends decode must succeed"); + assert_eq!(expected_rows.len(), 2, "baseline qmDividends must decode 2 valid rows"); + assert_eq!(expected_errs.len(), 1, "baseline qmDividends must reject 1 invalid doc"); + assert_eq!(expected_stats.decoded, 2); + assert_eq!(expected_stats.rejected_total(), 1); + + for step in [usize::MAX, 1, 3, 7, 13, 37] { + let mut cursor_reader = RawBsonCursorReader::new(VecRawDocumentSource::new(docs.clone())); + let mut rows = Vec::new(); + let mut errs = Vec::new(); + let stats = if step == usize::MAX { + decode_qm_dividend_stream( + &mut cursor_reader, + BsonStreamOptions::default(), + |row| { + rows.push(( + row.qm_search_code.to_owned(), + row.ex_date, + row.cash.to_bits(), + row.currency.to_owned(), + row.declared_date, + )); + }, + |offset, err| errs.push((offset, err)), + ) + .expect("qmDividends stream decode must succeed") + } else { + decode_qm_dividend_stream( + CappedRead::new(&mut cursor_reader, step), + BsonStreamOptions::default(), + |row| { + rows.push(( + row.qm_search_code.to_owned(), + row.ex_date, + row.cash.to_bits(), + row.currency.to_owned(), + row.declared_date, + )); + }, + |offset, err| errs.push((offset, err)), + ) + .expect("capped qmDividends stream decode must succeed") + }; + + assert_eq!(stats, expected_stats, "qmDividends stats mismatch at step={step}"); + assert_eq!(rows, expected_rows, "qmDividends rows mismatch at step={step}"); + assert_eq!(errs, expected_errs, "qmDividends errors mismatch at step={step}"); + assert_eq!(cursor_reader.docs_read(), docs.len() as u64); + assert_eq!(cursor_reader.bytes_read(), concat.len() as u64); + } +} + +#[test] +fn parity_qm_filings_stream_across_default_and_odd_buffers() { + let docs = vec![ + build_qm_filing_doc("AAPL:US", "2024-05-03T16:30:00 EDT", "10-Q", Some("F-101")), + build_qm_filing_reject_doc("BAD:US"), + build_qm_filing_doc("RY:CA", "2024-12-04T08:05:00 EST", "Annual financial statements", None), + ]; + let concat = concat_docs(&docs); + let fields = QmFilingsFieldNames { + key: "symbol", + timefiled: "timefiled", + form_type: "formtype", + filing_id: Some("filingid"), + url: None, + }; + + let mut expected_rows = Vec::new(); + let expected_stats = decode_qm_filings_stream( + Cursor::new(&concat), + BsonStreamOptions::default(), + &fields, + |row| { + expected_rows.push(( + row.key.to_owned(), + row.timefiled.to_owned(), + row.form_type.to_owned(), + row.filing_id.map(str::to_owned), + row.url.map(str::to_owned), + )); + }, + ) + .expect("baseline qmFilings decode must succeed"); + assert_eq!(expected_rows.len(), 2, "baseline qmFilings must decode 2 valid rows"); + assert_eq!(expected_stats.rows_out, 2); + assert_eq!(expected_stats.skipped_total(), 1); + + for step in [usize::MAX, 1, 3, 7, 13, 37] { + let mut cursor_reader = RawBsonCursorReader::new(VecRawDocumentSource::new(docs.clone())); + let mut rows = Vec::new(); + let stats = if step == usize::MAX { + decode_qm_filings_stream( + &mut cursor_reader, + BsonStreamOptions::default(), + &fields, + |row| { + rows.push(( + row.key.to_owned(), + row.timefiled.to_owned(), + row.form_type.to_owned(), + row.filing_id.map(str::to_owned), + row.url.map(str::to_owned), + )); + }, + ) + .expect("qmFilings stream decode must succeed") + } else { + decode_qm_filings_stream( + CappedRead::new(&mut cursor_reader, step), + BsonStreamOptions::default(), + &fields, + |row| { + rows.push(( + row.key.to_owned(), + row.timefiled.to_owned(), + row.form_type.to_owned(), + row.filing_id.map(str::to_owned), + row.url.map(str::to_owned), + )); + }, + ) + .expect("capped qmFilings stream decode must succeed") + }; + + assert_eq!(stats, expected_stats, "qmFilings stats mismatch at step={step}"); + assert_eq!(rows, expected_rows, "qmFilings rows mismatch at step={step}"); + assert_eq!(cursor_reader.docs_read(), docs.len() as u64); + assert_eq!(cursor_reader.bytes_read(), concat.len() as u64); + } +} + +// --------------------------------------------------------------------------- +// 3. Bounded memory, counters, framing validation & error handling +// --------------------------------------------------------------------------- + +#[test] +fn empty_source_yields_eof_with_zero_counts() { + let empty: [&[u8]; 0] = []; + let mut reader = RawBsonCursorReader::new(SliceRawDocumentSource::new(&empty)); + let mut buf = [0u8; 64]; + assert_eq!(reader.read(&mut buf).expect("empty read must succeed"), 0); + assert_eq!(reader.read(&mut buf).expect("repeated EOF must succeed"), 0); + assert_eq!(reader.docs_read(), 0); + assert_eq!(reader.bytes_read(), 0); + assert_eq!(reader.pending_capacity(), 0); +} + +#[test] +fn zero_length_read_buffer_returns_zero_without_advancing() { + let docs = vec![build_eod_doc("AAPL.US", "2024-01-02", 100.0, 50.0)]; + let mut reader = RawBsonCursorReader::new(VecRawDocumentSource::new(docs.clone())); + assert_eq!(reader.read(&mut []).expect("empty buf read must succeed"), 0); + assert_eq!(reader.docs_read(), 0); + assert_eq!(reader.bytes_read(), 0); + + let got = read_all_with_step(&mut reader, 64).expect("full read must succeed"); + assert_eq!(got, docs[0]); + assert_eq!(reader.docs_read(), 1); + assert_eq!(reader.bytes_read(), docs[0].len() as u64); +} + +#[test] +fn pending_capacity_stays_bounded_to_single_document_under_one_byte_reads() { + let docs: Vec> = (0..50) + .map(|i| build_eod_doc(&format!("SYM{i:03}.US"), "2024-01-02", 10.0 + i as f64, 100.0)) + .collect(); + let max_doc_len = docs.iter().map(Vec::len).max().unwrap(); + let expected = concat_docs(&docs); + + let mut reader = RawBsonCursorReader::new(VecRawDocumentSource::new(docs)); + let got = read_all_with_step(&mut reader, 1).expect("1-byte read must succeed"); + + assert_eq!(got, expected); + assert_eq!(reader.docs_read(), 50); + assert_eq!(reader.bytes_read(), expected.len() as u64); + assert!( + reader.pending_capacity() <= max_doc_len, + "pending_capacity ({}) exceeded max single doc length ({max_doc_len})", + reader.pending_capacity() + ); +} + +#[test] +fn mid_stream_source_error_delivers_prior_docs_then_surfaces_sticky_mongo_stream_error() { + let doc0 = build_eod_doc("AAPL.US", "2024-01-02", 100.0, 10.0); + let doc1 = build_eod_doc("MSFT.US", "2024-01-03", 200.0, 20.0); + let expected_err = MongoStreamError::Source { + detail: "simulated cursor drop mid-stream".to_owned(), + }; + let source = FailingSource { + docs: vec![doc0.clone(), doc1.clone()], + index: 0, + fail_at: 2, + err: expected_err.clone(), + }; + + let mut reader = RawBsonCursorReader::new(source); + let mut big_buf = vec![0u8; 4096]; + let n = reader + .read(&mut big_buf) + .expect("first read must return bytes from prior valid docs"); + assert_eq!(n, doc0.len() + doc1.len()); + assert_eq!(&big_buf[..doc0.len()], doc0.as_slice()); + assert_eq!(&big_buf[doc0.len()..n], doc1.as_slice()); + assert_eq!(reader.docs_read(), 2); + assert_eq!(reader.bytes_read(), (doc0.len() + doc1.len()) as u64); + + // Next read surfaces the stashed MongoStreamError wrapped in io::Error. + let io_err = reader + .read(&mut big_buf) + .expect_err("next read must surface stashed error"); + let downcast = io_err + .get_ref() + .and_then(|e| e.downcast_ref::()) + .expect("io::Error must carry MongoStreamError"); + assert_eq!(downcast, &expected_err); + + // Subsequent reads stay sticky with the same MongoStreamError. + let io_err2 = reader + .read(&mut big_buf) + .expect_err("reader must remain in sticky error state"); + let downcast2 = io_err2 + .get_ref() + .and_then(|e| e.downcast_ref::()) + .expect("sticky io::Error must carry MongoStreamError"); + assert_eq!(downcast2, &expected_err); +} + +#[test] +fn first_doc_source_error_surfaces_through_bson_stream_error_io() { + let expected_err = MongoStreamError::Source { + detail: "initial cursor failure".to_owned(), + }; + let source = FailingSource { + docs: vec![], + index: 0, + fail_at: 0, + err: expected_err.clone(), + }; + let reader = RawBsonCursorReader::new(source); + let err = decode_eod_price_stream(reader, BsonStreamOptions::default(), |_| {}, |_, _| {}) + .expect_err("decode_eod_price_stream must propagate source error"); + + match err { + BsonStreamError::Io { offset, source } => { + assert_eq!(offset, 0); + let inner = source + .get_ref() + .and_then(|e| e.downcast_ref::()) + .expect("BsonStreamError::Io must wrap MongoStreamError"); + assert_eq!(inner, &expected_err); + } + other => panic!("expected BsonStreamError::Io, got {other:?}"), + } +} + +#[test] +fn malformed_bson_frames_are_rejected_without_incrementing_counters() { + let valid_doc = build_eod_doc("AAPL.US", "2024-01-02", 100.0, 10.0); + + // 1. Shorter than MIN_BSON_DOC_BYTES (5) + let too_short = vec![4u8, 0, 0, 0]; + // 2. Negative declared length + let negative_len = vec![0xff, 0xff, 0xff, 0xff, 0x00]; + // 3. Declared length < actual byte length + let mut declared_lt_actual = valid_doc.clone(); + declared_lt_actual.push(0x00); + // 4. Declared length > actual byte length + let mut declared_gt_actual = valid_doc.clone(); + let bad_len = (valid_doc.len() as i32 + 4).to_le_bytes(); + declared_gt_actual[..4].copy_from_slice(&bad_len); + // 5. Missing trailing 0x00 terminator + let mut missing_null = valid_doc.clone(); + *missing_null.last_mut().unwrap() = 0x7f; + + let bad_cases = [ + ("too_short", too_short), + ("negative_len", negative_len), + ("declared_lt_actual", declared_lt_actual), + ("declared_gt_actual", declared_gt_actual), + ("missing_null", missing_null), + ]; + + for (label, bad_frame) in bad_cases { + let mut reader = RawBsonCursorReader::new(VecRawDocumentSource::new(vec![ + valid_doc.clone(), + bad_frame, + ])); + let mut buf = vec![0u8; 4096]; + let n = reader + .read(&mut buf) + .unwrap_or_else(|e| panic!("{label}: first doc should succeed, got {e}")); + assert_eq!(n, valid_doc.len(), "{label}"); + assert_eq!(reader.docs_read(), 1, "{label}"); + assert_eq!(reader.bytes_read(), valid_doc.len() as u64, "{label}"); + + let err = reader + .read(&mut buf) + .expect_err(&format!("{label}: bad frame must fail")); + let mongo_err = err + .get_ref() + .and_then(|e| e.downcast_ref::()) + .expect("must downcast to MongoStreamError"); + match mongo_err { + MongoStreamError::InvalidBsonFrame { doc_index, .. } => { + assert_eq!(*doc_index, 1, "{label}: doc_index must be 1"); + } + other => panic!("{label}: expected InvalidBsonFrame, got {other:?}"), + } + assert_eq!(reader.docs_read(), 1, "{label}: counters must not advance"); + assert_eq!(reader.bytes_read(), valid_doc.len() as u64, "{label}"); + } + + // 6. Exceeds max_doc_bytes + let mut reader = RawBsonCursorReader::with_max_doc_bytes( + VecRawDocumentSource::new(vec![valid_doc.clone()]), + valid_doc.len() - 1, + ) + .expect("with_max_doc_bytes >= 5 must succeed"); + let mut buf = vec![0u8; 4096]; + let err = reader.read(&mut buf).expect_err("oversized doc must fail"); + let mongo_err = err + .get_ref() + .and_then(|e| e.downcast_ref::()) + .expect("must downcast to MongoStreamError"); + assert!(matches!( + mongo_err, + MongoStreamError::InvalidBsonFrame { doc_index: 0, .. } + )); + assert_eq!(reader.docs_read(), 0); + assert_eq!(reader.bytes_read(), 0); + + // 7. with_max_doc_bytes < MIN_BSON_DOC_BYTES rejected + let err = RawBsonCursorReader::with_max_doc_bytes( + VecRawDocumentSource::new(vec![]), + MIN_BSON_DOC_BYTES - 1, + ) + .err() + .expect("max_doc_bytes < 5 must fail"); + assert!(matches!(err, MongoStreamError::InvalidMaxDocBytes { .. })); +} + +// --------------------------------------------------------------------------- +// 4. Filter & spec validation + lazy non-connecting open() +// --------------------------------------------------------------------------- + +#[test] +fn build_filter_document_and_spec_validation() { + // Empty spec -> empty filter document + let empty_filter = + build_filter_document(SourceCollection::EodPrices, &MongoReadSpec::default()) + .expect("default spec must be valid"); + assert!(empty_filter.is_empty()); + + // Key + ISO date range + let spec = MongoReadSpec { + key_eq: Some("AAPL.US".to_owned()), + date_range: Some(MongoDateRange { + gte: Some(FilterDateValue::IsoString("2024-01-01".to_owned())), + lt: Some(FilterDateValue::IsoString("2025-01-01".to_owned())), + }), + batch_size: DEFAULT_MONGO_BATCH_SIZE, + limit: Some(500), + ..MongoReadSpec::default() + }; + let doc = build_filter_document(SourceCollection::EodPrices, &spec) + .expect("valid key + date_range spec must succeed"); + assert_eq!( + doc.get("eodSearchCode"), + Some(&Bson::String("AAPL.US".to_owned())) + ); + let date_sub = doc + .get_document("date") + .expect("date range subdocument must exist"); + assert_eq!( + date_sub.get("$gte"), + Some(&Bson::String("2024-01-01".to_owned())) + ); + assert_eq!( + date_sub.get("$lt"), + Some(&Bson::String("2025-01-01".to_owned())) + ); + + // BSON DateTime millis range + let dt_spec = MongoReadSpec { + date_range: Some(MongoDateRange { + gte: Some(FilterDateValue::BsonDateTimeMillis(1_704_067_200_000)), + lt: Some(FilterDateValue::BsonDateTimeMillis(1_735_689_600_000)), + }), + ..MongoReadSpec::default() + }; + let dt_doc = build_filter_document(SourceCollection::QmEarnings, &dt_spec) + .expect("valid DateTime range must succeed"); + let rd = dt_doc + .get_document("reportDate") + .expect("reportDate subdocument must exist"); + assert_eq!( + rd.get("$gte"), + Some(&Bson::DateTime(DateTime::from_millis(1_704_067_200_000))) + ); + + // Invalid batch_size == 0 and > MAX_MONGO_BATCH_SIZE + assert!(matches!( + build_filter_document( + SourceCollection::EodPrices, + &MongoReadSpec { + batch_size: 0, + ..MongoReadSpec::default() + } + ), + Err(MongoStreamError::InvalidBatchSize { batch_size: 0, .. }) + )); + assert!(matches!( + build_filter_document( + SourceCollection::EodPrices, + &MongoReadSpec { + batch_size: MAX_MONGO_BATCH_SIZE + 1, + ..MongoReadSpec::default() + } + ), + Err(MongoStreamError::InvalidBatchSize { .. }) + )); + + // Invalid limit == Some(0) and > i64::MAX + assert!(matches!( + build_filter_document( + SourceCollection::EodPrices, + &MongoReadSpec { + limit: Some(0), + ..MongoReadSpec::default() + } + ), + Err(MongoStreamError::InvalidLimit { limit: 0 }) + )); + assert!(matches!( + build_filter_document( + SourceCollection::EodPrices, + &MongoReadSpec { + limit: Some(i64::MAX as u64 + 1), + ..MongoReadSpec::default() + } + ), + Err(MongoStreamError::InvalidLimit { .. }) + )); + + // Blank key_eq + assert!(matches!( + build_filter_document( + SourceCollection::EodPrices, + &MongoReadSpec { + key_eq: Some(" ".to_owned()), + ..MongoReadSpec::default() + } + ), + Err(MongoStreamError::InvalidKeyFilter { + collection: SourceCollection::EodPrices + }) + )); + + // date_range on TeMarketData + assert!(matches!( + build_filter_document( + SourceCollection::TeMarketData, + &MongoReadSpec { + date_range: Some(MongoDateRange { + gte: Some(FilterDateValue::IsoString("2024-01-01".to_owned())), + lt: None, + }), + ..MongoReadSpec::default() + } + ), + Err(MongoStreamError::DateRangeNotSupported { + collection: SourceCollection::TeMarketData + }) + )); + + // Empty date_range (neither gte nor lt) + assert!(matches!( + build_filter_document( + SourceCollection::EodPrices, + &MongoReadSpec { + date_range: Some(MongoDateRange { + gte: None, + lt: None, + }), + ..MongoReadSpec::default() + } + ), + Err(MongoStreamError::InvalidDateRange { .. }) + )); + + // Inverted date_range (gte >= lt) + assert!(matches!( + build_filter_document( + SourceCollection::EodPrices, + &MongoReadSpec { + date_range: Some(MongoDateRange { + gte: Some(FilterDateValue::IsoString("2025-01-01".to_owned())), + lt: Some(FilterDateValue::IsoString("2024-01-01".to_owned())), + }), + ..MongoReadSpec::default() + } + ), + Err(MongoStreamError::InvalidDateRange { .. }) + )); + + // Mismatched FilterDateValue variants + assert!(matches!( + build_filter_document( + SourceCollection::EodPrices, + &MongoReadSpec { + date_range: Some(MongoDateRange { + gte: Some(FilterDateValue::IsoString("2024-01-01".to_owned())), + lt: Some(FilterDateValue::BsonDateTimeMillis(1_735_689_600_000)), + }), + ..MongoReadSpec::default() + } + ), + Err(MongoStreamError::InvalidDateRange { .. }) + )); +} + +#[test] +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!( + build_filter_document( + SourceCollection::QmFilings, + &MongoReadSpec { + date_range: Some(MongoDateRange { + gte: Some(FilterDateValue::IsoString("2025-01-01T00:00:00Z".to_owned())), + lt: Some(FilterDateValue::IsoString("2025-01-02T00:00:00Z".to_owned())), + }), + ..MongoReadSpec::default() + } + ), + Err(MongoStreamError::InvalidDateRange { + collection: SourceCollection::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( + "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() + } + ), + Err(MongoStreamError::InvalidDateRange { + collection: SourceCollection::QmFilings, + .. + }) + )); + assert!(matches!( + build_filter_document( + SourceCollection::QmFilings, + &MongoReadSpec { + date_range: Some(MongoDateRange { + gte: Some(FilterDateValue::BsonDateTimeMillis(1_735_689_600_000)), + lt: None, + }), + ..MongoReadSpec::default() + } + ), + Err(MongoStreamError::InvalidDateRange { + collection: SourceCollection::QmFilings, + .. + }) + )); + + // 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_day.to_owned())), + lt: Some(FilterDateValue::IsoString(lt_day.to_owned())), + }), + ..MongoReadSpec::default() + }, + ) + .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_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); +} + +// --------------------------------------------------------------------------- +// 5. Password redaction (plain and percent-encoded sentinel passwords) +// --------------------------------------------------------------------------- + +#[test] +fn error_display_and_debug_never_leak_plain_or_percent_encoded_passwords() { + // Plain sentinel password + let plain_sentinel = "SENTINEL_PLAIN_PASS_998877"; + let plain_uri_str = format!( + "mongodb://studio_stock_bot_read:{plain_sentinel}@localhost:27017/stock?authSource=stock" + ); + let plain_uri = validate_uri(&plain_uri_str); + 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 = 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("[REDACTED]")); + assert!(debug_out.contains("[REDACTED]")); + + // Percent-encoded sentinel password (contains %40 -> @ and %21 -> !) + let encoded_sentinel = "SENTINEL%40ENC%21PASS_554433"; + let decoded_sentinel = "SENTINEL@ENC!PASS_554433"; + let enc_uri_str = format!( + "mongodb://studio_stock_bot_read:{encoded_sentinel}@localhost:27017/stock" + ); + let enc_uri = validate_uri(&enc_uri_str); + let simulated_enc_raw = format!( + "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("[REDACTED]")); + + 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)); + assert!(!enc_display.contains(decoded_sentinel)); + assert!(!enc_debug.contains(encoded_sentinel)); + assert!(!enc_debug.contains(decoded_sentinel)); + assert!(enc_display.contains("[REDACTED]")); +} + +#[test] +fn error_redaction_covers_distinct_secondary_uri_passwords_with_punctuation() { + let primary_uri = validate_uri( + "mongodb://studio_stock_bot_read:PRIMARY_PASS_111@localhost:27017/stock?authSource=stock", + ); + let secondary_pass_comma = "SEC_ALPHA,BETA;GAMMA)DELTA"; + let secondary_pass_srv = "SRV_PASS\"QUOTE]BRACKET@AT"; + let diagnostic = format!( + "primary timed out; fallback mongodb://secondary:{secondary_pass_comma}@10.0.0.51:27017,10.0.0.52:27017/stock, \ + and srv \"mongodb+srv://reader:{secondary_pass_srv}@cluster.internal/stock?retryReads=true\"" + ); + + let err = MongoStreamError::redacted_source(&diagnostic, &primary_uri); + let display_out = format!("{err}"); + let debug_out = format!("{err:?}"); + + for secret in [ + "PRIMARY_PASS_111", + secondary_pass_comma, + "SEC_ALPHA", + "BETA", + "GAMMA", + "DELTA", + secondary_pass_srv, + "SRV_PASS", + "QUOTE", + "BRACKET", + ] { + assert!( + !display_out.contains(secret), + "Display leaked secondary password fragment `{secret}`: {display_out}" + ); + assert!( + !debug_out.contains(secret), + "Debug leaked secondary password fragment `{secret}`: {debug_out}" + ); + } + + assert!( + display_out.contains("mongodb://secondary:[REDACTED]@10.0.0.51:27017,10.0.0.52:27017/stock"), + "unexpected redacted secondary URI in Display: {display_out}" + ); + assert!( + display_out.contains("mongodb+srv://reader:[REDACTED]@cluster.internal/stock?retryReads=true"), + "unexpected redacted srv URI in Display: {display_out}" + ); +} + +#[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) +// --------------------------------------------------------------------------- + +#[test] +fn sealed_surface_source_scan() { + let src_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("src") + .join("mongo_stream.rs"); + let raw_src = fs::read_to_string(&src_path) + .unwrap_or_else(|err| panic!("failed to read {}: {err}", src_path.display())); + + // Strip line comments (`//...`) so documentation prose does not produce false positives, + // while keeping all code lines verbatim. + let code_only: String = raw_src + .lines() + .map(|line| match line.find("//") { + Some(idx) => &line[..idx], + None => line, + }) + .collect::>() + .join("\n"); + + assert!( + !code_only.contains("mongodb::"), + "mongo_stream.rs must not contain any `mongodb::` driver path yet" + ); + + let forbidden_calls = [ + "insert", + "update", + "delete", + "replace", + "drop", + "aggregate", + "create_index", + "run_command", + "bulk_write", + ]; + + for word in forbidden_calls { + // Check for `.word(` or `word(` identifier calls in code. + let method_pat = format!(".{word}"); + let call_pat = format!("{word}("); + assert!( + !code_only.contains(&method_pat) && !code_only.contains(&call_pat), + "forbidden driver/mutation call `{word}` found in mongo_stream.rs" + ); + } + + // 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(); + if trimmed.starts_with("pub ") && !trimmed.starts_with("pub(crate)") { + // Gather signature up to `{` or `;` + let mut sig = String::new(); + for next_line in &lines[idx..] { + sig.push_str(next_line.trim()); + sig.push(' '); + if next_line.contains('{') || next_line.contains(';') { + break; + } + } + for forbidden_type in [ + "mongodb::Client", + "mongodb::sync::Client", + "mongodb::Database", + "mongodb::sync::Database", + "mongodb::Collection", + "mongodb::sync::Collection", + "-> Client", + "-> Database", + "-> Collection", + ] { + assert!( + !sig.contains(forbidden_type), + "public item exposes forbidden MongoDB handle `{forbidden_type}`: {sig}" + ); + } + } + } +} + +// --------------------------------------------------------------------------- +// 7. Additional edge-case coverage +// --------------------------------------------------------------------------- + +struct CountingSource { + docs: Vec>, + index: usize, + polls: usize, +} + +impl CountingSource { + fn new(docs: Vec>) -> Self { + Self { + docs, + index: 0, + polls: 0, + } + } +} + +impl RawDocumentSource for CountingSource { + fn next_raw_document(&mut self) -> Result, MongoStreamError> { + self.polls += 1; + if self.index >= self.docs.len() { + return Ok(None); + } + let doc = self.docs[self.index].as_slice(); + self.index += 1; + Ok(Some(doc)) + } +} + +#[test] +fn source_is_not_polled_again_after_eof_across_repeated_reads() { + let docs = vec![ + build_eod_doc("AAPL.US", "2024-01-02", 185.5, 1000.0), + build_eod_doc("MSFT.US", "2024-01-03", 370.0, 2000.0), + ]; + let expected = concat_docs(&docs); + let mut reader = RawBsonCursorReader::new(CountingSource::new(docs)); + + let got = read_all_with_step(&mut reader, 64).expect("initial read must succeed"); + assert_eq!(got, expected); + assert_eq!(reader.docs_read(), 2); + assert_eq!(reader.bytes_read(), expected.len() as u64); + + let mut buf = [0u8; 32]; + for _ in 0..5 { + assert_eq!( + reader.read(&mut buf).expect("post-EOF read must return Ok(0)"), + 0 + ); + } + + let inner = reader.into_inner(); + assert_eq!( + inner.polls, 3, + "source must be polled only once per doc plus one EOF poll" + ); +} + +#[test] +fn source_error_after_split_document_delivers_all_doc_bytes_then_sticky_error() { + let doc0 = build_eod_doc("AAPL.US", "2024-01-02", 185.5, 1000.0); + assert!(doc0.len() > 25, "test doc must span multiple small reads"); + let expected_err = MongoStreamError::Source { + detail: "cursor dropped after split doc".to_owned(), + }; + let source = FailingSource { + docs: vec![doc0.clone()], + index: 0, + fail_at: 1, + err: expected_err.clone(), + }; + + let mut reader = RawBsonCursorReader::new(source); + let mut received = Vec::new(); + let mut buf = [0u8; 13]; + + let first_err = loop { + match reader.read(&mut buf) { + Ok(0) => panic!("expected source error after split document, got EOF"), + Ok(n) => received.extend_from_slice(&buf[..n]), + Err(err) => break err, + } + }; + + assert_eq!(received, doc0, "all split document bytes must be delivered before error"); + assert_eq!(reader.docs_read(), 1); + assert_eq!(reader.bytes_read(), doc0.len() as u64); + + let downcast = first_err + .get_ref() + .and_then(|e| e.downcast_ref::()) + .expect("io::Error must wrap MongoStreamError"); + assert_eq!(downcast, &expected_err); + + // Subsequent reads stay sticky with the same error. + let second_err = reader + .read(&mut buf) + .expect_err("reader must remain in sticky error state"); + let downcast2 = second_err + .get_ref() + .and_then(|e| e.downcast_ref::()) + .expect("sticky io::Error must wrap MongoStreamError"); + assert_eq!(downcast2, &expected_err); +} + +#[test] +fn malformed_first_document_fails_immediately_with_zero_counts_and_stays_sticky() { + let valid_doc = build_eod_doc("AAPL.US", "2024-01-02", 100.0, 10.0); + let mut bad_first = valid_doc.clone(); + *bad_first.last_mut().unwrap() = 0x42; // missing trailing 0x00 + + let mut reader = + RawBsonCursorReader::new(VecRawDocumentSource::new(vec![bad_first, valid_doc])); + let mut buf = [0u8; 256]; + + let first_err = reader + .read(&mut buf) + .expect_err("malformed doc #0 must fail on first read"); + let first_mongo_err = first_err + .get_ref() + .and_then(|e| e.downcast_ref::()) + .expect("must downcast to MongoStreamError") + .clone(); + assert!( + matches!( + first_mongo_err, + MongoStreamError::InvalidBsonFrame { doc_index: 0, .. } + ), + "expected InvalidBsonFrame at doc_index 0, got {first_mongo_err:?}" + ); + assert_eq!(reader.docs_read(), 0); + assert_eq!(reader.bytes_read(), 0); + + for _ in 0..3 { + let sticky_err = reader + .read(&mut buf) + .expect_err("subsequent reads must stay sticky after malformed doc #0"); + let sticky_mongo_err = sticky_err + .get_ref() + .and_then(|e| e.downcast_ref::()) + .expect("sticky error must downcast to MongoStreamError"); + assert_eq!(sticky_mongo_err, &first_mongo_err); + assert_eq!(reader.docs_read(), 0); + assert_eq!(reader.bytes_read(), 0); + } +} + +#[test] +fn boundary_document_sizes_min_five_bytes_and_exact_max_doc_bytes() { + // Minimum valid 5-byte empty BSON document succeeds at max_doc_bytes == MIN_BSON_DOC_BYTES. + let empty_bson = vec![5u8, 0, 0, 0, 0]; + assert_eq!(empty_bson.len(), MIN_BSON_DOC_BYTES); + let mut min_reader = RawBsonCursorReader::with_max_doc_bytes( + VecRawDocumentSource::new(vec![empty_bson.clone()]), + MIN_BSON_DOC_BYTES, + ) + .expect("MIN_BSON_DOC_BYTES must be accepted"); + let min_out = read_all_with_step(&mut min_reader, 2).expect("5-byte doc must succeed"); + assert_eq!(min_out, empty_bson); + assert_eq!(min_reader.docs_read(), 1); + assert_eq!(min_reader.bytes_read(), MIN_BSON_DOC_BYTES as u64); + + // Exact max_doc_bytes succeeds while max_doc_bytes + 1 fails with InvalidBsonFrame. + let exact_doc = build_eod_doc("AAPL.US", "2024-01-02", 185.5, 1000.0); + let one_byte_larger = build_eod_doc("AAPLX.US", "2024-01-02", 185.5, 1000.0); + assert_eq!(one_byte_larger.len(), exact_doc.len() + 1); + let ceiling = exact_doc.len(); + + let mut exact_reader = RawBsonCursorReader::with_max_doc_bytes( + VecRawDocumentSource::new(vec![exact_doc.clone()]), + ceiling, + ) + .expect("exact ceiling must be valid"); + let exact_out = read_all_with_step(&mut exact_reader, 37).expect("exact-size doc must succeed"); + assert_eq!(exact_out, exact_doc); + assert_eq!(exact_reader.docs_read(), 1); + assert_eq!(exact_reader.bytes_read(), ceiling as u64); + + let mut over_reader = RawBsonCursorReader::with_max_doc_bytes( + VecRawDocumentSource::new(vec![one_byte_larger]), + ceiling, + ) + .expect("ceiling must be valid"); + let mut buf = [0u8; 512]; + let err = over_reader + .read(&mut buf) + .expect_err("max_doc_bytes + 1 must fail"); + let mongo_err = err + .get_ref() + .and_then(|e| e.downcast_ref::()) + .expect("must downcast to MongoStreamError"); + assert!(matches!( + mongo_err, + MongoStreamError::InvalidBsonFrame { doc_index: 0, .. } + )); + assert_eq!(over_reader.docs_read(), 0); + assert_eq!(over_reader.bytes_read(), 0); +} + +#[test] +fn large_200kib_document_parity_and_bounded_pending_capacity() { + let payload = "X".repeat(200 * 1024); + let mut large_doc = RawDocumentBuf::new(); + large_doc.append(cstr!("eodSearchCode"), "BIG.US"); + large_doc.append(cstr!("date"), "2024-08-15"); + large_doc.append(cstr!("open"), 42.0_f64); + large_doc.append(cstr!("high"), 43.0_f64); + large_doc.append(cstr!("low"), 41.0_f64); + large_doc.append(cstr!("close"), 42.5_f64); + large_doc.append(cstr!("volume"), 999.0_f64); + large_doc.append(cstr!("padding"), payload.as_str()); + let large_bytes = large_doc.into_bytes(); + assert!(large_bytes.len() > 200 * 1024); + + let small_doc = build_eod_doc("SMALL.US", "2024-08-16", 12.25, 50.0); + let docs = vec![large_bytes.clone(), small_doc]; + let concat = concat_docs(&docs); + let max_doc_len = docs.iter().map(Vec::len).max().unwrap(); + + let mut expected_rows = Vec::new(); + let expected_stats = decode_eod_price_stream( + Cursor::new(&concat), + BsonStreamOptions::default(), + |bar| { + expected_rows.push(( + bar.eod_search_code.to_owned(), + bar.session_date, + bar.close.to_bits(), + )); + }, + |offset, err| panic!("unexpected baseline error at {offset}: {err:?}"), + ) + .expect("baseline large-doc decode must succeed"); + assert_eq!(expected_rows.len(), 2); + + for step in [13usize, 37, 4099] { + let mut cursor_reader = RawBsonCursorReader::new(VecRawDocumentSource::new(docs.clone())); + let mut rows = Vec::new(); + let stats = decode_eod_price_stream( + CappedRead::new(&mut cursor_reader, step), + BsonStreamOptions::default(), + |bar| { + rows.push(( + bar.eod_search_code.to_owned(), + bar.session_date, + bar.close.to_bits(), + )); + }, + |offset, err| panic!("unexpected stream error at {offset} (step={step}): {err:?}"), + ) + .expect("large-doc stream decode must succeed"); + + assert_eq!(stats, expected_stats, "stats mismatch at step={step}"); + assert_eq!(rows, expected_rows, "rows mismatch at step={step}"); + assert_eq!(cursor_reader.docs_read(), 2); + assert_eq!(cursor_reader.bytes_read(), concat.len() as u64); + assert!( + cursor_reader.pending_capacity() <= max_doc_len, + "pending_capacity ({}) exceeded single large doc length ({max_doc_len}) at step={step}", + cursor_reader.pending_capacity() + ); + } +} + +#[test] +fn read_spec_validate_accepts_all_boundary_limits() { + let min_spec = MongoReadSpec { + batch_size: 1, + limit: Some(1), + max_doc_bytes: MIN_BSON_DOC_BYTES, + ..MongoReadSpec::default() + }; + min_spec + .validate(SourceCollection::EodPrices) + .expect("min boundary spec must validate"); + assert!( + build_filter_document(SourceCollection::EodPrices, &min_spec) + .expect("min boundary filter must succeed") + .is_empty() + ); + + let max_spec = MongoReadSpec { + batch_size: MAX_MONGO_BATCH_SIZE, + limit: Some(i64::MAX as u64), + max_doc_bytes: MIN_BSON_DOC_BYTES, + ..MongoReadSpec::default() + }; + max_spec + .validate(SourceCollection::EodPrices) + .expect("max boundary spec must validate"); + assert!( + build_filter_document(SourceCollection::EodPrices, &max_spec) + .expect("max boundary filter must succeed") + .is_empty() + ); +} + +#[test] +fn one_sided_date_range_bounds_and_equal_bound_rejection() { + // ISO string: gte-only + let iso_gte = build_filter_document( + SourceCollection::EodPrices, + &MongoReadSpec { + date_range: Some(MongoDateRange { + gte: Some(FilterDateValue::IsoString("2024-01-01".to_owned())), + lt: None, + }), + ..MongoReadSpec::default() + }, + ) + .expect("ISO gte-only must succeed"); + let sub = iso_gte.get_document("date").unwrap(); + assert_eq!(sub.get("$gte"), Some(&Bson::String("2024-01-01".to_owned()))); + assert_eq!(sub.get("$lt"), None); + + // ISO string: lt-only + let iso_lt = build_filter_document( + SourceCollection::EodPrices, + &MongoReadSpec { + date_range: Some(MongoDateRange { + gte: None, + lt: Some(FilterDateValue::IsoString("2025-01-01".to_owned())), + }), + ..MongoReadSpec::default() + }, + ) + .expect("ISO lt-only must succeed"); + let sub = iso_lt.get_document("date").unwrap(); + assert_eq!(sub.get("$gte"), None); + assert_eq!(sub.get("$lt"), Some(&Bson::String("2025-01-01".to_owned()))); + + // BSON DateTime millis: gte-only + let dt_gte = build_filter_document( + SourceCollection::CeoShorts, + &MongoReadSpec { + date_range: Some(MongoDateRange { + gte: Some(FilterDateValue::BsonDateTimeMillis(1_704_067_200_000)), + lt: None, + }), + ..MongoReadSpec::default() + }, + ) + .expect("DateTime gte-only must succeed"); + let sub = dt_gte.get_document("timestamp").unwrap(); + assert_eq!( + sub.get("$gte"), + Some(&Bson::DateTime(DateTime::from_millis(1_704_067_200_000))) + ); + assert_eq!(sub.get("$lt"), None); + + // BSON DateTime millis: lt-only + let dt_lt = build_filter_document( + SourceCollection::CeoShorts, + &MongoReadSpec { + date_range: Some(MongoDateRange { + gte: None, + lt: Some(FilterDateValue::BsonDateTimeMillis(1_735_689_600_000)), + }), + ..MongoReadSpec::default() + }, + ) + .expect("DateTime lt-only must succeed"); + let sub = dt_lt.get_document("timestamp").unwrap(); + assert_eq!(sub.get("$gte"), None); + assert_eq!( + sub.get("$lt"), + Some(&Bson::DateTime(DateTime::from_millis(1_735_689_600_000))) + ); + + // Equal bounds (gte == lt) must be rejected for both variants. + assert!(matches!( + build_filter_document( + SourceCollection::EodPrices, + &MongoReadSpec { + date_range: Some(MongoDateRange { + gte: Some(FilterDateValue::IsoString("2024-06-01".to_owned())), + lt: Some(FilterDateValue::IsoString("2024-06-01".to_owned())), + }), + ..MongoReadSpec::default() + } + ), + Err(MongoStreamError::InvalidDateRange { + collection: SourceCollection::EodPrices, + .. + }) + )); + assert!(matches!( + build_filter_document( + SourceCollection::CeoShorts, + &MongoReadSpec { + date_range: Some(MongoDateRange { + gte: Some(FilterDateValue::BsonDateTimeMillis(1_704_067_200_000)), + lt: Some(FilterDateValue::BsonDateTimeMillis(1_704_067_200_000)), + }), + ..MongoReadSpec::default() + } + ), + Err(MongoStreamError::InvalidDateRange { + collection: SourceCollection::CeoShorts, + .. + }) + )); +} + +#[test] +fn qm_filings_rejects_invalid_eastern_calendar_day_bounds() { + let invalid_days = [ + "2023-02-29", // non-leap year Feb 29 + "2024-13-01", // month > 12 + "2024-00-10", // month == 0 + "2024-01-00", // day == 0 + "2024-04-31", // April has 30 days + "2024-01-01 ", // trailing space + "2024-01-01Z", // trailing UTC marker + "2024-01-0é", // non-ASCII byte + "2024-01-01", // fullwidth digits (non-ASCII) + ]; + + for bad in invalid_days { + assert!( + matches!( + build_filter_document( + SourceCollection::QmFilings, + &MongoReadSpec { + date_range: Some(MongoDateRange { + gte: Some(FilterDateValue::IsoString(bad.to_owned())), + lt: None, + }), + ..MongoReadSpec::default() + } + ), + Err(MongoStreamError::InvalidDateRange { + collection: SourceCollection::QmFilings, + .. + }) + ), + "expected gte={bad:?} to be rejected for qmFilings" + ); + assert!( + matches!( + build_filter_document( + SourceCollection::QmFilings, + &MongoReadSpec { + date_range: Some(MongoDateRange { + gte: None, + lt: Some(FilterDateValue::IsoString(bad.to_owned())), + }), + ..MongoReadSpec::default() + } + ), + Err(MongoStreamError::InvalidDateRange { + collection: SourceCollection::QmFilings, + .. + }) + ), + "expected lt={bad:?} to be rejected for qmFilings" + ); + } + + // Leap-year Feb 29 is valid. + build_filter_document( + SourceCollection::QmFilings, + &MongoReadSpec { + date_range: Some(MongoDateRange { + gte: Some(FilterDateValue::IsoString("2024-02-29".to_owned())), + lt: Some(FilterDateValue::IsoString("2024-03-01".to_owned())), + }), + ..MongoReadSpec::default() + }, + ) + .expect("valid leap-year calendar day 2024-02-29 must succeed"); +} + +#[test] +fn source_collection_exhaustive_key_date_and_display_mappings() { + let expected: [(SourceCollection, &str, &str, Option<&str>); 8] = [ + ( + SourceCollection::EodPrices, + "eodPrices", + "eodSearchCode", + Some("date"), + ), + ( + SourceCollection::QmSplits, + "qmSplits", + "qmSearchCode", + Some("date"), + ), + ( + SourceCollection::QmDividends, + "qmDividends", + "qmSearchCode", + Some("date"), + ), + ( + SourceCollection::QmPrices, + "qmPrices", + "qmSearchCode", + Some("date"), + ), + ( + SourceCollection::TeMarketData, + "teMarketData", + "teSymbol", + None, + ), + ( + SourceCollection::CeoShorts, + "ceoShorts", + "symbol", + Some("timestamp"), + ), + ( + SourceCollection::QmFilings, + "qmFilings", + "symbol", + Some("timefiled"), + ), + ( + SourceCollection::QmEarnings, + "qmEarnings", + "qmSearchCode", + Some("reportDate"), + ), + ]; + + assert_eq!(SourceCollection::ALL.len(), expected.len()); + for (actual, (exp_variant, exp_name, exp_key, exp_date)) in + SourceCollection::ALL.into_iter().zip(expected) + { + assert_eq!(actual, exp_variant); + assert_eq!(actual.as_str(), exp_name); + assert_eq!(format!("{actual}"), exp_name); + assert_eq!(actual.key_field(), exp_key); + assert_eq!(actual.date_field(), exp_date); + } +} + +#[test] +fn error_redaction_handles_uppercase_and_mixed_case_mongo_schemes() { + let primary_uri = validate_uri( + "mongodb://studio_stock_bot_read:PRIMARY_CASE_PASS@localhost:27017/stock?authSource=stock", + ); + let upper_secret = "UPPER_SCHEME_SECRET_777"; + let mixed_secret = "MIXED_SRV_SECRET_888"; + let diagnostic = format!( + "tried MONGODB://reader:{upper_secret}@10.0.0.51:27017/stock then MongoDB+SRV://srvuser:{mixed_secret}@cluster.internal/stock" + ); + + let err = MongoStreamError::redacted_source(&diagnostic, &primary_uri); + let display_out = format!("{err}"); + let debug_out = format!("{err:?}"); + + for secret in ["PRIMARY_CASE_PASS", upper_secret, mixed_secret] { + assert!( + !display_out.contains(secret), + "Display leaked `{secret}` under uppercase/mixed-case scheme: {display_out}" + ); + assert!( + !debug_out.contains(secret), + "Debug leaked `{secret}` under uppercase/mixed-case scheme: {debug_out}" + ); + } + assert!( + display_out.contains("[REDACTED]@10.0.0.51:27017/stock"), + "expected redacted MONGODB:// URI in Display: {display_out}" + ); + assert!( + display_out.contains("[REDACTED]@cluster.internal/stock"), + "expected redacted MongoDB+SRV:// URI in Display: {display_out}" + ); + assert!(debug_out.contains("[REDACTED]")); +} + +#[test] +fn error_redaction_scrubs_repeated_password_occurrences_across_message() { + let repeated_pass = "REPEATED_SENTINEL_PASS_4242"; + let primary_uri_str = format!( + "mongodb://studio_stock_bot_read:{repeated_pass}@localhost:27017/stock?authSource=stock" + ); + let primary_uri = validate_uri(&primary_uri_str); + let diagnostic = format!( + "attempt1={primary_uri_str}; raw1={repeated_pass}; fallback=mongodb://alt:{repeated_pass}@10.0.0.51:27017/stock; raw2={repeated_pass}; attempt2={primary_uri_str}" + ); + + let err = MongoStreamError::redacted_source(&diagnostic, &primary_uri); + let display_out = format!("{err}"); + let debug_out = format!("{err:?}"); + + assert!( + !display_out.contains(repeated_pass), + "Display leaked repeated password: {display_out}" + ); + assert!( + !debug_out.contains(repeated_pass), + "Debug leaked repeated password: {debug_out}" + ); + assert!( + display_out.matches("[REDACTED]").count() >= 5, + "expected every occurrence to be redacted in Display: {display_out}" + ); + assert!( + debug_out.matches("[REDACTED]").count() >= 5, + "expected every occurrence to be redacted in Debug: {debug_out}" + ); +} diff --git a/tools/curate-etl/tests/mongo_stream_qa_contract.rs b/tools/curate-etl/tests/mongo_stream_qa_contract.rs new file mode 100644 index 00000000..507a3271 --- /dev/null +++ b/tools/curate-etl/tests/mongo_stream_qa_contract.rs @@ -0,0 +1,322 @@ +//! QA contract tests for the public `mongo_stream` API (T-126 / M1.2al). +//! +//! Covers gaps left by `src/mongo_stream_tests.rs`, using only the public crate API and +//! in-memory sources (no MongoDB, no network): +//! - a source that fails exactly once is never polled again; the reader replays the same +//! sticky error (stashed-after-partial-write path and split-document path); +//! - an invalid frame after a valid one in the same `read()` is deferred, then sticky, and +//! never counted; +//! - seeded random documents + random read sizes: concatenated output is byte-identical to +//! the inputs, counters match, and `pending` never exceeds the largest single document; +//! - `RawBsonChunkReader` frames the adapter's output with the same chunks as a plain cursor; +//! - `with_max_doc_bytes` rejects ceilings below the BSON minimum; `into_inner` returns the +//! source at its current position; +//! - `build_filter_document` emits the exact key / `$gte` / `$lt` shape, and an empty spec +//! yields an empty filter; +//! - `MongoStreamError::redacted_source` (public path) hides the validated URI's password in +//! `Display` and `Debug` even when the raw URI is absent from the message. + +use std::io::{self, Cursor, Read}; + +use bson::raw::{cstr, RawDocumentBuf}; +use bson::{doc, Bson, DateTime}; +use curate_etl::{ + assert_read_only_mongo_uri, build_filter_document, FilterDateValue, LocalHosts, MongoDateRange, + MongoReadSpec, MongoStreamError, RawBsonChunkReader, RawBsonCursorReader, RawDocumentSource, + ReadOnlyPolicy, SliceRawDocumentSource, SourceCollection, VecRawDocumentSource, + MIN_BSON_DOC_BYTES, +}; + +struct SplitMix64(u64); + +impl SplitMix64 { + fn next_u64(&mut self) -> u64 { + self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15); + let mut z = self.0; + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) + } + + fn below(&mut self, n: u64) -> u64 { + self.next_u64() % n + } +} + +fn doc_with_payload(tag: u64, payload_len: usize) -> Vec { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("tag"), tag as i64); + doc.append(cstr!("payload"), "x".repeat(payload_len)); + doc.into_bytes() +} + +/// Yields `docs`, fails exactly once at `fail_at`, and counts every poll. +struct FailOnceSource { + docs: Vec>, + index: usize, + fail_at: usize, + failed: bool, + polls: usize, +} + +impl FailOnceSource { + fn new(docs: Vec>, fail_at: usize) -> Self { + Self { + docs, + index: 0, + fail_at, + failed: false, + polls: 0, + } + } +} + +impl RawDocumentSource for FailOnceSource { + fn next_raw_document(&mut self) -> Result, MongoStreamError> { + self.polls += 1; + if self.index == self.fail_at && !self.failed { + self.failed = true; + return Err(MongoStreamError::Source { + detail: "simulated cursor failure".to_owned(), + }); + } + if self.index >= self.docs.len() { + return Ok(None); + } + let doc = self.docs[self.index].as_slice(); + self.index += 1; + Ok(Some(doc)) + } +} + +fn downcast_stream_err(err: &io::Error) -> MongoStreamError { + err.get_ref() + .and_then(|e| e.downcast_ref::()) + .cloned() + .expect("io::Error must carry MongoStreamError") +} + +#[test] +fn fail_once_source_after_split_document_is_not_repolled_and_error_is_sticky() { + let doc0 = doc_with_payload(0, 40); + let docs = vec![doc0.clone(), doc_with_payload(1, 40)]; + let mut reader = RawBsonCursorReader::new(FailOnceSource::new(docs, 1)); + + let mut out = Vec::new(); + let mut buf = [0u8; 7]; + let err = loop { + match reader.read(&mut buf) { + Ok(0) => panic!("reader must not report EOF after a source failure"), + Ok(n) => out.extend_from_slice(&buf[..n]), + Err(err) => break err, + } + }; + assert_eq!( + out, doc0, + "split document must be fully delivered before the error" + ); + let first = downcast_stream_err(&err); + assert!(matches!(first, MongoStreamError::Source { .. })); + + for _ in 0..3 { + let again = reader.read(&mut buf).expect_err("error must stay sticky"); + assert_eq!(downcast_stream_err(&again), first); + } + assert_eq!(reader.docs_read(), 1); + assert_eq!(reader.bytes_read(), doc0.len() as u64); + assert_eq!( + reader.into_inner().polls, + 2, + "sticky error must be replayed without polling the source again" + ); +} + +#[test] +fn fail_once_source_after_whole_document_returns_partial_then_sticky_without_repoll() { + let doc0 = doc_with_payload(0, 10); + let mut reader = RawBsonCursorReader::new(FailOnceSource::new(vec![doc0.clone()], 1)); + + let mut buf = [0u8; 4096]; + let n = reader + .read(&mut buf) + .expect("first read returns the bytes already written"); + assert_eq!(&buf[..n], doc0.as_slice()); + + let err = reader + .read(&mut buf) + .expect_err("stashed error surfaces on the next read"); + let first = downcast_stream_err(&err); + let err2 = reader.read(&mut buf).expect_err("error stays sticky"); + assert_eq!(downcast_stream_err(&err2), first); + assert_eq!(reader.docs_read(), 1); + assert_eq!(reader.into_inner().polls, 2); +} + +#[test] +fn invalid_frame_after_valid_frame_is_deferred_sticky_and_uncounted() { + let good = doc_with_payload(7, 3); + let mut bad = doc_with_payload(8, 3); + let last = bad.len() - 1; + bad[last] = 0x01; + let docs: Vec<&[u8]> = vec![&good, &bad, &good]; + let mut reader = RawBsonCursorReader::new(SliceRawDocumentSource::new(&docs)); + + let mut buf = [0u8; 4096]; + let n = reader.read(&mut buf).expect("valid prefix delivered first"); + assert_eq!(&buf[..n], good.as_slice()); + + let err = reader.read(&mut buf).expect_err("bad frame surfaces next"); + match downcast_stream_err(&err) { + MongoStreamError::InvalidBsonFrame { doc_index, .. } => assert_eq!(doc_index, 1), + other => panic!("unexpected error: {other:?}"), + } + assert!(reader.read(&mut buf).is_err(), "error must stay sticky"); + assert_eq!(reader.docs_read(), 1); + assert_eq!(reader.bytes_read(), good.len() as u64); +} + +#[test] +fn seeded_random_documents_and_read_sizes_round_trip_byte_identically() { + let mut rng = SplitMix64(0x5EED_126A); + for _round in 0..40 { + let doc_count = rng.below(12) as usize; + let docs: Vec> = (0..doc_count) + .map(|i| doc_with_payload(i as u64, rng.below(600) as usize)) + .collect(); + let expected: Vec = docs.concat(); + let largest = docs.iter().map(Vec::len).max().unwrap_or(0); + + let mut reader = RawBsonCursorReader::new(VecRawDocumentSource::new(docs.clone())); + let mut out = Vec::new(); + loop { + let step = 1 + rng.below(700) as usize; + let mut buf = vec![0u8; step]; + let n = reader.read(&mut buf).expect("valid stream must read"); + if n == 0 { + break; + } + out.extend_from_slice(&buf[..n]); + assert!( + reader.pending_capacity() <= largest, + "pending {} exceeds largest doc {largest}", + reader.pending_capacity() + ); + } + assert_eq!(out, expected); + assert_eq!(reader.docs_read(), doc_count as u64); + assert_eq!(reader.bytes_read(), expected.len() as u64); + } +} + +#[test] +fn chunk_reader_frames_cursor_output_identically_to_plain_cursor() { + let docs: Vec> = (0..50) + .map(|i| doc_with_payload(i, (i as usize * 37) % 900)) + .collect(); + let concat = docs.concat(); + + let collect = |mut chunker: RawBsonChunkReader>| { + let mut chunks = Vec::new(); + while let Some(chunk) = chunker.next_chunk().expect("framing must succeed") { + chunks.push((chunk.start_offset, chunk.bytes.to_vec())); + } + chunks + }; + let plain = collect(RawBsonChunkReader::new(Box::new(Cursor::new( + concat.clone(), + )))); + let via_cursor = collect(RawBsonChunkReader::new(Box::new(RawBsonCursorReader::new( + VecRawDocumentSource::new(docs), + )))); + + let flatten = + |chunks: &[(u64, Vec)]| chunks.iter().flat_map(|c| c.1.clone()).collect::>(); + assert_eq!(flatten(&plain), concat); + assert_eq!(flatten(&via_cursor), concat); + assert_eq!(via_cursor.first().map(|c| c.0), Some(0)); +} + +#[test] +fn with_max_doc_bytes_rejects_ceiling_below_bson_minimum() { + let empty: [&[u8]; 0] = []; + let err = RawBsonCursorReader::with_max_doc_bytes( + SliceRawDocumentSource::new(&empty), + MIN_BSON_DOC_BYTES - 1, + ) + .err() + .expect("ceiling below minimum must be rejected"); + assert!(matches!(err, MongoStreamError::InvalidMaxDocBytes { .. })); + assert!(RawBsonCursorReader::with_max_doc_bytes( + SliceRawDocumentSource::new(&empty), + MIN_BSON_DOC_BYTES + ) + .is_ok()); +} + +#[test] +fn into_inner_returns_source_at_current_position() { + let docs = vec![doc_with_payload(0, 1), doc_with_payload(1, 1)]; + let mut reader = RawBsonCursorReader::new(VecRawDocumentSource::new(docs.clone())); + let mut buf = vec![0u8; docs[0].len()]; + reader.read_exact(&mut buf).expect("first doc"); + let mut source = reader.into_inner(); + let next = source + .next_raw_document() + .expect("source ok") + .map(<[u8]>::to_vec); + assert_eq!(next, Some(docs[1].clone())); + assert!(source.next_raw_document().expect("source ok").is_none()); +} + +#[test] +fn build_filter_document_emits_exact_key_and_range_shape() { + let spec = MongoReadSpec { + key_eq: Some("AAPL.US".to_owned()), + date_range: Some(MongoDateRange { + gte: Some(FilterDateValue::IsoString("2024-01-01".to_owned())), + lt: Some(FilterDateValue::IsoString("2025-01-01".to_owned())), + }), + ..MongoReadSpec::default() + }; + let filter = build_filter_document(SourceCollection::EodPrices, &spec).expect("valid spec"); + assert_eq!( + filter, + doc! { "eodSearchCode": "AAPL.US", "date": { "$gte": "2024-01-01", "$lt": "2025-01-01" } } + ); + + let ms_spec = MongoReadSpec { + date_range: Some(MongoDateRange { + gte: None, + lt: Some(FilterDateValue::BsonDateTimeMillis(1_700_000_000_000)), + }), + ..MongoReadSpec::default() + }; + let ms_filter = build_filter_document(SourceCollection::CeoShorts, &ms_spec).expect("valid"); + assert_eq!( + ms_filter.get("timestamp"), + Some(&Bson::Document( + doc! { "$lt": DateTime::from_millis(1_700_000_000_000) } + )) + ); + + let empty = build_filter_document(SourceCollection::TeMarketData, &MongoReadSpec::default()) + .expect("default spec is valid"); + assert!(empty.is_empty()); +} + +#[test] +fn redacted_source_hides_validated_password_even_without_full_uri_in_message() { + let sentinel = "QA_SENTINEL_PW_4242"; + let uri = assert_read_only_mongo_uri( + &format!("mongodb://studio_stock_bot_read:{sentinel}@localhost:27017/stock"), + &ReadOnlyPolicy::default(), + &LocalHosts::empty(), + ) + .expect("valid read-only URI"); + let raw = format!("SCRAM failure: password={sentinel}; retry with '{sentinel}'"); + let err = MongoStreamError::redacted_source(&raw, &uri); + for rendered in [format!("{err}"), format!("{err:?}")] { + assert!(!rendered.contains(sentinel), "leaked: {rendered}"); + assert!(rendered.contains("[REDACTED]")); + } +}