T-125: M1.2ak — tools/curate-etl: pure read-only MongoDB URI safety guard (mongo_safety.rs, parity with env-safety.ts QA-target rules, blocks trading_admin) with offline tests (no new crates, no MongoDB connection)
This commit is contained in:
parent
9adc8f18c6
commit
cc39ee379a
4 changed files with 2161 additions and 0 deletions
|
|
@ -1493,6 +1493,29 @@ 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<str>` 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<MongoTarget, MongoSafetyError>` — 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<ValidatedReadOnlyMongoUri, MongoSafetyError>` — fail-closed guard returning a `ValidatedReadOnlyMongoUri` proof token whose fields are private and whose only public constructor is `assert_read_only_mongo_uri`.
|
||||
- **Password redaction:** `ValidatedReadOnlyMongoUri`'s `Display`, `Debug`, and `redacted()` always replace the password between the first `:` and `@` in userinfo with `[REDACTED]`. `MongoSafetyError` variants never store raw URIs, raw authorities, or passwords.
|
||||
- **No URI query-option parsing:** beyond authority/remainder splitting and the no-credentials remainder-`@` check, URI query options are intentionally not parsed or validated (matching `apps/stock/config/src/env-safety.ts`).
|
||||
|
||||
### 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 with identical QA / not-QA / rejected outcomes. `assert_read_only_mongo_uri` is deliberately stricter than `env-safety.ts` in five ways for read-only ETL safety:
|
||||
|
||||
1. **Global case-insensitive `trading_admin` ban:** rejects percent-decoded `trading_admin` (ASCII case-insensitive) on **any** host (QA, dev, or remote), even if a caller adds it to `ReadOnlyPolicy::allowed_read_users` (whereas `env-safety.ts` only checks `username === 'trading_admin'` on QA targets for dev `dataPipeline`).
|
||||
2. **Mandatory QA credentials & allowlist:** any QA target must provide a username present in `ReadOnlyPolicy::allowed_read_users` (default: `["studio_stock_bot_read"]`); missing credentials and non-allowlisted users are rejected.
|
||||
3. **Rejection of empty or malformed multi-host segments:** URIs like `mongodb://u:p@bad:port,localhost:27017/stock` or `mongodb://u:p@localhost:27018,,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`).
|
||||
4. **Strict `mongodb+srv://` seed rules:** `assert_read_only_mongo_uri` rejects `mongodb+srv://` URIs with multiple hosts or any explicit `:` port suffix (`InvalidSrvTarget`), matching `database.schema.ts`.
|
||||
5. **No-credentials remainder-`@` check and strict username percent-decoding:** rejects unencoded `@` in path/query when authority has no `@` (matching `database.schema.ts`) and rejects malformed percent-encoding in the username (failing closed instead of falling back to the raw username string).
|
||||
|
||||
## 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`:
|
||||
|
|
|
|||
|
|
@ -14,6 +14,7 @@ pub mod cli;
|
|||
pub mod corporate_actions;
|
||||
pub mod events;
|
||||
pub mod fx;
|
||||
pub mod mongo_safety;
|
||||
pub mod parquet_adj;
|
||||
pub mod parquet_bars;
|
||||
pub mod parquet_corporate_actions;
|
||||
|
|
@ -95,6 +96,11 @@ 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 parquet_adj::{
|
||||
adj_factors_parquet_schema, write_adj_factors_dataset, AdjFactorsParquetRow,
|
||||
AdjFactorsWriteOptions, AdjFactorsWriteStats, ParquetAdjError,
|
||||
|
|
|
|||
1060
tools/curate-etl/src/mongo_safety.rs
Normal file
1060
tools/curate-etl/src/mongo_safety.rs
Normal file
File diff suppressed because it is too large
Load diff
1072
tools/curate-etl/src/mongo_safety_tests.rs
Normal file
1072
tools/curate-etl/src/mongo_safety_tests.rs
Normal file
File diff suppressed because it is too large
Load diff
Loading…
Add table
Add a link
Reference in a new issue