Skip to main content

rivet/source/
mod.rs

1pub(crate) mod batch_controller;
2pub(crate) mod cdc;
3pub mod mongo;
4pub mod mssql;
5pub mod mysql;
6pub(crate) mod pg_numeric_wire;
7pub mod postgres;
8pub(crate) mod query;
9pub(crate) mod tls;
10pub(crate) mod value_checksum;
11
12use arrow::datatypes::SchemaRef;
13use arrow::record_batch::RecordBatch;
14
15use crate::config::{SourceConfig, TlsConfig};
16use crate::error::Result;
17use crate::plan::IncrementalCursorPlan;
18use crate::tuning::SourceTuning;
19use crate::types::{ColumnOverrides, CursorState, TypeMapping};
20
21/// A statement-DURATION timeout that **rivet itself** raised — distinct from a
22/// driver-native timeout that carries a structured code (PG 57014, MySQL 3024).
23///
24/// The MSSQL engine has no server-side statement-duration `SET`, so rivet
25/// enforces `tuning.statement_timeout_s` client-side and raises this when the
26/// budget is exceeded (see [`mssql`]). Before this type the retry classifier's
27/// permanence hinged on substring-matching rivet's OWN prose ("statement
28/// timeout after …"); a reworded message would silently flip the error back to
29/// *transient*, and the identical query would be retried until it burned the
30/// budget N times (measured: 3×300 s = 20 min for 0 rows). Carrying a typed
31/// marker means [`crate::pipeline::retry::classify_error`] downcasts the TYPE,
32/// so permanence survives any change to the human-facing wording. The string
33/// branches in the classifier remain a fallback for genuinely driver-native
34/// timeout messages we do not control.
35#[derive(Debug)]
36pub struct StatementDurationTimeout {
37    /// Full actionable message shown to the operator. The classifier keys off
38    /// the TYPE, not this text — it exists only for Display.
39    message: String,
40}
41
42impl StatementDurationTimeout {
43    /// MSSQL client-side statement-duration timeout (no server-side `SET`).
44    pub fn mssql(seconds: u64) -> Self {
45        Self {
46            message: format!(
47                "mssql: statement timeout after {seconds}s (tuning.statement_timeout_s) — \
48                 this query cannot finish within the budget; split it with `mode: chunked` \
49                 (per-chunk statements stay under the limit) or raise \
50                 `tuning.statement_timeout_s`"
51            ),
52        }
53    }
54
55    /// MySQL server-side `max_execution_time` timeout (ER_QUERY_TIMEOUT / 3024).
56    /// Wraps the driver's terse "maximum statement execution time exceeded" with
57    /// the actionable fix — including the WIDE-table case (a chunk that still
58    /// times out), which the field's `*_version` tables hit and the raw driver
59    /// error gave no guidance for.
60    pub fn mysql(seconds: u64) -> Self {
61        Self {
62            message: format!(
63                "mysql: statement timeout after {seconds}s (max_execution_time from \
64                 tuning.statement_timeout_s) — this query exceeded its time budget (ERROR 3024). \
65                 Split it with `mode: chunked` / `chunk_by_key` so per-chunk queries stay under \
66                 the limit; if a CHUNK still times out on a WIDE table, lower `chunk_size` or use \
67                 `chunk_size_memory_mb:` (width-aware chunking); or raise `tuning.statement_timeout_s`"
68            ),
69        }
70    }
71}
72
73impl std::fmt::Display for StatementDurationTimeout {
74    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
75        f.write_str(&self.message)
76    }
77}
78
79impl std::error::Error for StatementDurationTimeout {}
80
81/// Summary of a source table relevant to chunked-mode planning. Source-neutral
82/// shape so plan-build can ask either Postgres or MySQL for the same answer.
83///
84/// Populated by `crate::source::postgres::introspect_pg_table_for_chunking` and
85/// `crate::source::mysql::introspect_mysql_table_for_chunking`. Both helpers
86/// rely on catalog stats (`pg_class` / `information_schema.TABLES`) so the
87/// numbers are only as fresh as the last `ANALYZE` / autoanalyse.
88///
89/// # Why this is a data-shape seam, not a trait
90///
91/// The two per-engine introspection functions have identical signatures
92/// (`fn(url, tls, qualified_table) -> Result<TableIntrospection>`) and return
93/// this shared struct. The parallel shape sometimes invites a refactor along
94/// the lines of `trait Introspector { fn introspect_table(...) }` with one
95/// impl per engine — that refactor adds ceremony without reducing duplication,
96/// because the *bodies* share nothing useful: PG queries `pg_class` /
97/// `pg_index` / `pg_attribute` / `pg_type` (PG-specific type names like
98/// `int2`/`int4`/`int8`) via the `postgres` client; MySQL queries
99/// `information_schema.TABLES` / `STATISTICS` with the InnoDB
100/// `AVG_ROW_LENGTH` overflow correction via the `mysql` client. No shared
101/// implementation logic exists to extract into trait-default methods. A
102/// trait would only rename where the engine match happens
103/// (`match config.source.source_type { … }` at the call site → factory
104/// returning `Box<dyn Introspector>`); the match doesn't disappear.
105///
106/// The seam therefore lives at the **data shape**: this struct is the
107/// shared contract, the two free functions are the adapters, the per-call
108/// dispatch is an `enum`-driven `match`. See ADR-0015 for the full
109/// rationale and the architecture-review walks that led here.
110#[derive(Debug, Clone, Default)]
111pub(crate) struct TableIntrospection {
112    /// Name of the single integer-family PK column, if present and safe to
113    /// range-chunk. `None` when the table has no PK, has a composite PK, or
114    /// the PK type is not an integer family (text, uuid, decimal, …).
115    pub single_int_pk: Option<String>,
116    /// Single-column, NOT NULL, **unique** index columns usable as a keyset
117    /// (seek) pagination key — PK first, then other UNIQUE indexes (OPT-4).
118    /// Index-backed and unique by construction, so `ORDER BY key LIMIT n` is a
119    /// bounded index range scan (never a filesort) and `WHERE key > last` never
120    /// skips a duplicate key. Restricted to types the keyset CURSOR can read
121    /// (`extract_last_cursor_value`: integer / float / string / timestamp / date /
122    /// uuid) — `decimal`/`numeric` keys are EXCLUDED here so the planner refuses
123    /// them up front rather than failing mid-run after a partial write (#dogfood).
124    /// Empty when the table has no such key.
125    pub keyset_keys: Vec<String>,
126    /// Best-effort row count: PG `reltuples`, MySQL `TABLE_ROWS`. `0` means
127    /// the table is empty or stats are unavailable.
128    pub row_estimate: i64,
129    /// Heap-size-per-row in bytes. `None` for empty / unanalysed tables.
130    /// Used to convert `chunk_size_memory_mb` into a row count.
131    pub avg_row_bytes: Option<i64>,
132    /// Names of the table's integer-family columns (PG `int2`/`int4`/`int8`,
133    /// MySQL `tinyint`…`bigint`, MSSQL `tinyint`/`smallint`/`int`/`bigint`). An
134    /// explicit `chunk_column:` that is range-`BETWEEN`-sliced MUST be one of
135    /// these: chunking derives integer min/max boundaries, so a non-integer key
136    /// (numeric/decimal/real/float/…) silently DROPS every value that falls
137    /// between two integer window boundaries. Empty when the engine does not
138    /// populate it (e.g. Mongo, which does not SQL-range-chunk).
139    pub int_columns: Vec<String>,
140}
141
142impl TableIntrospection {
143    /// The auto-selected keyset key: the first usable single-column unique
144    /// NOT NULL key (PK preferred). `None` when the table has none.
145    pub fn auto_keyset_key(&self) -> Option<&str> {
146        self.keyset_keys.first().map(String::as_str)
147    }
148
149    /// Whether `col` is a usable keyset key (single-column, unique, NOT NULL,
150    /// index-backed). Used to validate an explicit `chunk_by_key`.
151    pub fn is_usable_keyset_key(&self, col: &str) -> bool {
152        self.keyset_keys.iter().any(|k| k == col)
153    }
154
155    /// Whether `col` is a known integer-family column — the safety precondition
156    /// for range chunking (`chunk_column`), which slices via integer `BETWEEN`
157    /// windows. A non-integer explicit `chunk_column` silently loses fractional
158    /// rows, so the planner refuses it (see `chunked_strategy_from_introspection`).
159    pub fn is_integer_column(&self, col: &str) -> bool {
160        // Case-INSENSITIVE: the config may write `chunk_column: ID` while the
161        // catalog stores `id` (MySQL is case-insensitive for column names; PG
162        // folds unquoted idents to lowercase). A case-sensitive match falsely
163        // refused a valid integer key with a "not an integer-family column" error
164        // (bughunt MED). A guard should not reject on casing.
165        //
166        // ponytail: #8 narrow, documented non-fix. On PostgreSQL a table could in
167        // principle hold BOTH `id` (int) and a quoted `"ID"` (numeric); the config
168        // `chunk_column: ID` would then pass this guard (matching `id`) yet the
169        // export SQL quotes `"ID"` case-sensitively and range-chunks the NUMERIC
170        // one — the #103 loss. A precise guard needs the FULL column list + the
171        // engine's quoting rule, not just the integer names, so it is not fixed
172        // here. It is vanishingly rare (MySQL cannot hold both spellings; PG needs
173        // deliberately quoted mixed-case twins), and WITHOUT the twin a case
174        // mismatch fails loudly at query time ("column ... does not exist"), never
175        // silently. The case-insensitive match's real, common benefit (MySQL)
176        // outweighs guarding this exotic PG shape.
177        self.int_columns.iter().any(|c| c.eq_ignore_ascii_case(col))
178    }
179}
180
181/// Receives schema and batches from a source, one at a time.
182pub trait BatchSink {
183    fn on_schema(&mut self, schema: SchemaRef) -> Result<()>;
184    fn on_batch(&mut self, batch: &RecordBatch) -> Result<()>;
185    /// A source whose key type is richer than its output column can express
186    /// reports its own keyset high-water mark here, as a lossless,
187    /// engine-decodable token. The keyset/parallel runners prefer it over the
188    /// string extracted from the output column — this is how MongoDB pages by a
189    /// non-ObjectId BSON `_id` (int, string, …) whose hex/text rendering in the
190    /// `_id` column would be type-ambiguous on the round-trip. No-op default:
191    /// SQL engines carry their cursor losslessly in the column already.
192    fn set_source_cursor(&mut self, _token: String) {}
193}
194
195/// Read-only inputs for a single export call.
196///
197/// Packs the parameters that used to live as 5 positional args on
198/// `Source::export` into a named struct. `sink` is **not** part of this struct
199/// — it is `&mut` and conceptually the output channel, separate from the
200/// read-only request configuration.
201pub struct ExportRequest<'a> {
202    /// Already-materialized SQL (after `resolve_query`). The driver still wraps
203    /// it with the dialect-specific incremental predicate via
204    /// [`crate::source::query::build_incremental_query`] when `incremental` is set.
205    pub query: &'a str,
206    /// The *unwrapped* base query to resolve catalog-dependent type hints from
207    /// (PostgreSQL `NUMERIC` precision/scale, which the wire protocol omits — the
208    /// driver parses the `FROM` clause and asks `pg_catalog`). Chunked, dense and
209    /// keyset runners wrap `query` in a `SELECT … FROM (<base>) …` subquery that
210    /// hides the source table from the catalog parser, so they pass the original
211    /// base query here. `None` ⇒ resolve from `query` (full/incremental, where it
212    /// is already the unwrapped form). Drivers that read precision from the wire
213    /// (MySQL) ignore this field.
214    pub catalog_hint_query: Option<&'a str>,
215    pub incremental: Option<&'a IncrementalCursorPlan>,
216    pub cursor: Option<&'a CursorState>,
217    pub tuning: &'a SourceTuning,
218    /// Per-column type declarations from `rivet.yaml` (`exports[].columns:`).
219    /// Drivers apply them during schema building so e.g. a `NUMERIC` column
220    /// without declared precision can still be exported as `Decimal128(18,2)`
221    /// when the user has stated the type explicitly.
222    pub column_overrides: &'a ColumnOverrides,
223    /// Keyset (seek) pagination page size (OPT-4). When `Some(n)` *and*
224    /// `incremental` carries the key plan, the driver builds one keyset page
225    /// (`WHERE key > cursor ORDER BY key LIMIT n`) instead of the unbounded
226    /// incremental/snapshot query. The keyset runner drives the outer loop.
227    pub page_limit: Option<usize>,
228    /// The bare source relation this export reads, when it is a `table:`
229    /// shortcut (`SELECT * FROM <ident>`) — the structured read-intent behind the
230    /// SQL string. Computed once via [`crate::sql::strip_select_star_from`], so a
231    /// non-SQL adapter (MongoDB reads a collection) uses it directly instead of
232    /// re-parsing `query`. `None` for a hand-written `query:` / any wrapped or
233    /// filtered form. SQL engines ignore it (they run `query`). See ADR-0027.
234    pub base_relation: Option<&'a str>,
235}
236
237impl<'a> ExportRequest<'a> {
238    /// A request whose `query` is already the **unwrapped base** form, so
239    /// catalog type hints resolve directly from it. Use for snapshot,
240    /// incremental and keyset runners: the driver applies any incremental /
241    /// keyset predicate internally, so the source table stays visible to the
242    /// catalog parser and `catalog_hint_query` is `None`.
243    pub fn unwrapped(
244        query: &'a str,
245        tuning: &'a SourceTuning,
246        column_overrides: &'a ColumnOverrides,
247    ) -> Self {
248        Self {
249            query,
250            catalog_hint_query: None,
251            incremental: None,
252            cursor: None,
253            tuning,
254            column_overrides,
255            page_limit: None,
256            // `query` is the unwrapped base here, so the relation (if this is a
257            // `table:` shortcut) is visible directly in it.
258            base_relation: crate::sql::strip_select_star_from(query),
259        }
260    }
261
262    /// A request whose `query` is a `SELECT … FROM (<base>) …` **wrapper** that
263    /// hides the source table (chunked / dense / time-window). `base` — the
264    /// unwrapped query catalog hints resolve from — is a required argument, so a
265    /// wrapping runner cannot silently fall back to the table-hiding wrapper and
266    /// lose PG `NUMERIC` precision (the bug the catalog-hint fix / ADR-0020
267    /// closed). Drivers that read precision from the wire (MySQL) ignore it.
268    pub fn wrapped(
269        query: &'a str,
270        base: &'a str,
271        tuning: &'a SourceTuning,
272        column_overrides: &'a ColumnOverrides,
273    ) -> Self {
274        Self {
275            query,
276            catalog_hint_query: Some(base),
277            incremental: None,
278            cursor: None,
279            tuning,
280            column_overrides,
281            page_limit: None,
282            // `query` is a table-hiding wrapper; the relation lives in `base`.
283            base_relation: crate::sql::strip_select_star_from(base),
284        }
285    }
286
287    /// Attach the incremental cursor plan (the driver builds the `WHERE cursor >
288    /// ? ORDER BY` predicate). Pass-through `Option` so mode-polymorphic callers
289    /// can forward `strategy.incremental_plan()` directly.
290    pub fn with_incremental(mut self, plan: Option<&'a IncrementalCursorPlan>) -> Self {
291        self.incremental = plan;
292        self
293    }
294
295    /// Attach the last committed cursor value the next run resumes after.
296    pub fn with_cursor(mut self, cursor: Option<&'a CursorState>) -> Self {
297        self.cursor = cursor;
298        self
299    }
300
301    /// Set the keyset (seek) page size — one bounded `… WHERE key > cursor ORDER
302    /// BY key LIMIT n` page instead of the unbounded query.
303    pub fn with_page_limit(mut self, page_limit: usize) -> Self {
304        self.page_limit = Some(page_limit);
305        self
306    }
307}
308
309pub trait Source: Send {
310    /// Execute `request.query` and stream batches into `sink`.
311    fn export(&mut self, request: &ExportRequest<'_>, sink: &mut dyn BatchSink) -> Result<()>;
312
313    fn query_scalar(&mut self, sql: &str) -> Result<Option<String>>;
314
315    /// Return `TypeMapping` for every column in `query` without fetching rows.
316    ///
317    /// Used by `rivet check --type-report` to show the full type provenance
318    /// (source native type → RivetType → Arrow type → fidelity) before export.
319    /// Implementations execute `SELECT * FROM (...) AS _q LIMIT 0` so only
320    /// server-side type metadata is transferred.
321    fn type_mappings(
322        &mut self,
323        query: &str,
324        column_overrides: &ColumnOverrides,
325    ) -> Result<Vec<TypeMapping>>;
326
327    /// Sample a monotonic source-pressure counter for the OPT-2 concurrency
328    /// governor (`pipeline::chunked::exec`).
329    ///
330    /// Higher = more pressure. The governor compares successive samples
331    /// (`cur > prev` ⇒ under pressure) — the same convention the adaptive
332    /// batch-size loop already uses. Returns `None` when the engine can't
333    /// cheaply sample a pressure proxy, in which case the governor holds
334    /// parallelism flat. Default: `None`.
335    fn sample_pressure(&mut self) -> Option<u64> {
336        None
337    }
338
339    /// A best-effort JSON snapshot of the source SERVER's forensic context —
340    /// version + the limits/session settings that shape failures (the
341    /// statement-timeout that surfaces as `ERROR 3024`, the sql_mode/timezone that
342    /// shape text rendering). Captured ONCE at run open onto the failed
343    /// `export_metrics` row (`server_context_json`), so a post-mortem can explain a
344    /// failure without re-querying a possibly-transient server. `None` when the
345    /// engine can't cheaply gather it; never fails the run.
346    fn server_context(&mut self) -> Option<String> {
347        None
348    }
349}
350
351pub fn create_source(config: &SourceConfig) -> Result<Box<dyn Source>> {
352    use crate::config::SourceType;
353    let url = config.resolve_url()?;
354    warn_if_tls_disabled(config);
355    match config.source_type {
356        SourceType::Postgres => Ok(Box::new(postgres::PostgresSource::connect_with_tls(
357            &url,
358            config.tls.as_ref(),
359        )?)),
360        SourceType::Mysql => Ok(Box::new(mysql::MysqlSource::connect_with_tls(
361            &url,
362            config.tls.as_ref(),
363        )?)),
364        SourceType::Mssql => Ok(Box::new(mssql::MssqlSource::connect_with_tls(
365            &url,
366            config.tls.as_ref(),
367        )?)),
368        SourceType::Mongo => Ok(Box::new(mongo::MongoSource::connect(
369            &url,
370            config.tls.as_ref(),
371            config.mongo.as_ref(),
372        )?)),
373    }
374}
375
376/// Pre-allocation per-value size guard, shared by every engine's
377/// `arrow_convert`. The sink-side `check_value_ceiling`
378/// (`pipeline::sink::mod`) scans the *already-built* Arrow batch, so an
379/// oversized cell costs the driver-decode copy **and** the Arrow-build copy
380/// before that guard fires. This check runs at the decode/`Value` stage — after
381/// the unavoidable driver copy, but *before* the value is appended into the
382/// `StringBuilder` / `BinaryBuilder` — so the Arrow allocation never grows to
383/// hold it. Only variable-length values (Utf8 / Binary) can be individually
384/// huge; fixed-width arms (ints/floats/dates) never call this.
385///
386/// `max_value_bytes` is `tuning.max_value_bytes()` (MB → bytes with the
387/// `Some(0)`/`None` ⇒ disabled semantics). The message mirrors the sink guard's
388/// `RIVET_VALUE_TOO_LARGE` so both read identically; the sink guard stays as the
389/// backstop (it also covers meta / enriched columns and is the contract test).
390pub(crate) fn value_within_ceiling(
391    column: &str,
392    len: usize,
393    max_value_bytes: Option<usize>,
394) -> Result<()> {
395    if let Some(limit) = max_value_bytes
396        && len > limit
397    {
398        anyhow::bail!(
399            "RIVET_VALUE_TOO_LARGE: column '{}' has a single value of {:.1} MB, exceeding the \
400             per-value ceiling of {} MB. One oversized cell can OOM the process regardless of \
401             batch size. Raise `tuning.max_value_mb` (or set it to 0 to disable the guard) if \
402             this value is expected.",
403            column,
404            len as f64 / (1024.0 * 1024.0),
405            limit / (1024 * 1024),
406        );
407    }
408    Ok(())
409}
410
411#[cfg(test)]
412mod value_ceiling_tests {
413    use super::value_within_ceiling;
414
415    #[test]
416    fn sec_value_ceiling_pre_alloc_over_limit_errors() {
417        let err = value_within_ceiling("payload", 2 * 1024 * 1024, Some(1024 * 1024)).unwrap_err();
418        let msg = format!("{err:#}");
419        assert!(msg.contains("RIVET_VALUE_TOO_LARGE"), "got: {msg}");
420        assert!(msg.contains("payload"), "names the column: {msg}");
421    }
422
423    #[test]
424    fn sec_value_ceiling_pre_alloc_at_or_under_limit_ok() {
425        assert!(value_within_ceiling("c", 1024 * 1024, Some(1024 * 1024)).is_ok());
426        assert!(value_within_ceiling("c", 0, Some(1024 * 1024)).is_ok());
427    }
428
429    #[test]
430    fn sec_value_ceiling_pre_alloc_disabled_never_errors() {
431        // `None` (set when tuning.max_value_mb is 0 or unset) disables the guard.
432        assert!(value_within_ceiling("c", usize::MAX, None).is_ok());
433    }
434}
435
436/// One-time nudge to enable TLS when the current config connects in plaintext.
437/// Emitted at `warn` level so operators see it even at the default log level.
438/// `create_source` is called multiple times per run (plan/preflight/exec/chunk
439/// workers), so we gate the warning behind a `Once` to fire exactly once per
440/// process rather than 3-4 times in stderr.
441pub(crate) fn warn_if_tls_disabled(config: &SourceConfig) {
442    let enforced = config.tls.as_ref().is_some_and(|t| t.mode.is_enforced());
443    if enforced {
444        return;
445    }
446    // Loopback (localhost / 127.0.0.0/8 / ::1) is the local-dev / docker case:
447    // the bytes never leave the box, so the plaintext warning is just noise on
448    // a newcomer's laptop. Resolve best-effort — if the URL can't be resolved we
449    // fall through and warn (fail-safe). The real CWE-319 signal still fires for
450    // any remote host.
451    if config.resolve_url().is_ok_and(|u| host_is_loopback(&u)) {
452        return;
453    }
454    static WARNED: std::sync::Once = std::sync::Once::new();
455    WARNED.call_once(|| {
456        log::warn!(
457            "source: TLS is not enforced — credentials and result rows cross the network in plaintext. \
458             Add `source.tls.mode: verify-full` (with `ca_file:` if your CA is private) to enable transport security."
459        );
460    });
461}
462
463/// Whether the host in a `scheme://[user[:pass]@]host[:port][/db][?…]`
464/// connection URL is a loopback address (`127.0.0.0/8`, `::1`) or the literal
465/// `localhost`.
466///
467/// Used by [`require_tls_or_loopback`] to decide TLS posture from the host:
468/// loopback is the docker / local-dev case where the bytes never leave the box,
469/// so plaintext is fine; a remote host without TLS leaks credentials and rows.
470///
471/// Fails **closed**: any URL we cannot confidently parse a loopback host out of
472/// is treated as non-loopback, so a parse gap can only ever *tighten* the gate
473/// (refuse a connection), never silently allow plaintext to an unverified host.
474/// The `host[:port][,host:port…]` span of a URL — scheme stripped, path/query
475/// dropped, `user[:pass]@` userinfo removed (rsplit the last `@` so an `@` in a
476/// password stays with the userinfo). Empty when the URL carries no authority.
477pub(crate) fn host_port_span(url: &str) -> &str {
478    let after_scheme = match url.split_once("://") {
479        Some((_, rest)) => rest,
480        None => url,
481    };
482    let authority = after_scheme
483        .split(['/', '?', '#'])
484        .next()
485        .unwrap_or(after_scheme);
486    match authority.rsplit_once('@') {
487        Some((_, hp)) => hp,
488        None => authority,
489    }
490}
491
492pub(crate) fn host_is_loopback(url: &str) -> bool {
493    let host_port = host_port_span(url);
494    // A comma seedlist (`host1:p1,host2:p2` — valid for MongoDB AND multi-host
495    // PostgreSQL) is loopback ONLY if EVERY host is: reading just the first host
496    // let `127.0.0.1:5432,evil.com:5432` dial evil.com in plaintext under the
497    // gate (bug-hunt find). Empty authority ⇒ not loopback (fail closed).
498    !host_port.is_empty() && host_port.split(',').all(one_host_is_loopback)
499}
500
501/// Loopback test for a single `host[:port]` (or bracketed `[ipv6][:port]`).
502fn one_host_is_loopback(host_port: &str) -> bool {
503    // IPv6 literals are bracketed (`[::1]:5432`); the host is the bracketed span,
504    // and any `:` inside is part of the address.
505    let host = if let Some(rest) = host_port.strip_prefix('[') {
506        match rest.split_once(']') {
507            Some((h, _)) => h,
508            None => return false, // unterminated bracket — fail closed
509        }
510    } else {
511        // Bare host or IPv4: the host ends at the (single) port `:`.
512        host_port.split(':').next().unwrap_or(host_port)
513    };
514
515    if host.eq_ignore_ascii_case("localhost") {
516        return true;
517    }
518    // `IpAddr::is_loopback` covers the whole 127.0.0.0/8 block and `::1`.
519    host.parse::<std::net::IpAddr>()
520        .is_ok_and(|ip| ip.is_loopback())
521}
522
523/// Refuse a URL that carries no host authority (`mysql://`, `postgres:///db`)
524/// with a clear parse error, BEFORE any engine-specific setup hint can blanket
525/// it (dogfood LOW: `rivet cdc --source mysql://` reported a binlog-grants
526/// problem for a host that doesn't exist). No URL echo — the userinfo may hold
527/// credentials — and no `user:pass@` pattern in the message (the redactor
528/// mangles it).
529pub(crate) fn require_url_has_host(url: &str) -> Result<()> {
530    if host_port_span(url).is_empty() {
531        anyhow::bail!(
532            "source: invalid URL — no host found. Expected a URL of the form \
533             scheme://host:port/database."
534        );
535    }
536    Ok(())
537}
538
539/// Gate plaintext / trust-any-cert connections by host (CWE-319 / CWE-295).
540///
541/// When no `tls:` block is configured (`tls == None`) **and** the resolved host
542/// is not loopback, refuse the connection *before any network I/O* with a
543/// TLS-required policy error. This stops the per-engine connect helpers from
544/// silently dialing a remote database in cleartext (Postgres/MySQL `NoTls`) or
545/// trusting any server certificate (MSSQL `trust_cert`).
546///
547/// Loopback hosts (docker / local dev) keep today's behaviour — plaintext is
548/// allowed there because the bytes never leave the box. An explicit
549/// `tls: { mode: disable }` is `Some(..)`, so it is the operator's opt-in to
550/// remote plaintext and is **not** refused here.
551pub(crate) fn require_tls_or_loopback(url: &str, tls: Option<&TlsConfig>) -> Result<()> {
552    // An explicit `tls: {..}` (including `mode: disable`) is the operator's
553    // opt-in and is never refused here — including for a host-LESS URL, which a
554    // driver resolves as a LOCAL unix socket (`postgres:///db?host=/var/run/
555    // postgresql`). The host-presence check must therefore live INSIDE the
556    // no-tls branch: hoisting it above (da7abbf) rejected a valid socket URL that
557    // worked on main whenever `tls: { mode: disable }` was set (#16 bughunt).
558    if tls.is_none() {
559        // A URL with NO host at all (`mysql://`, `postgres:///db`) is not a
560        // "remote host" — it is malformed. Prescribing a TLS block there sends the
561        // operator chasing a security setting for a host that doesn't exist.
562        require_url_has_host(url)?;
563    }
564    if tls.is_none() && !host_is_loopback(url) {
565        // The message must name TLS *and* that it is a policy refusal for a
566        // remote host. Emit it at `error` level (→ stderr) as well as returning
567        // it: callers like `doctor` print the `Err` to stdout in their own
568        // `[FAIL]` style and only re-raise a generic summary, so the log line is
569        // what guarantees the TLS-required reason reaches stderr. Deliberately
570        // avoids socket-error vocabulary ("could not connect", "timeout", "os
571        // error") so it is never mistaken for a connect-time failure.
572        let msg = "source: TLS required — refusing to connect to a remote (non-loopback) \
573             host without TLS; credentials and every exported row would cross the network \
574             in cleartext. Add `source.tls: { mode: verify-full }` (with `ca_file:` for a \
575             private CA) to enable transport security, or explicitly opt into remote \
576             plaintext with `source.tls: { mode: disable }` if this network path is \
577             already trusted.";
578        log::error!("{msg}");
579        anyhow::bail!("{msg}");
580    }
581    Ok(())
582}
583
584#[cfg(test)]
585mod tls_gate_tests {
586    use super::{host_is_loopback, host_port_span, require_tls_or_loopback};
587    use crate::config::{TlsConfig, TlsMode};
588
589    #[test]
590    fn loopback_variants_are_loopback() {
591        assert!(host_is_loopback(
592            "postgresql://rivet:rivet@127.0.0.1:5432/rivet"
593        ));
594        assert!(host_is_loopback(
595            "postgresql://rivet:rivet@localhost:5432/rivet"
596        ));
597        assert!(host_is_loopback("mysql://root@127.0.0.1:3306/db"));
598        // Whole 127.0.0.0/8 block is loopback.
599        assert!(host_is_loopback("postgresql://u:p@127.255.0.9/db"));
600        // IPv6 loopback, bracketed with and without a port.
601        assert!(host_is_loopback("postgresql://u:p@[::1]:5432/db"));
602        assert!(host_is_loopback("sqlserver://sa:pw@[::1]/master"));
603        // Case-insensitive host, no port, no db.
604        assert!(host_is_loopback("mysql://root@LOCALHOST"));
605        // An `@` inside the password must not be mistaken for the host boundary.
606        assert!(host_is_loopback("postgresql://u:p@ss@127.0.0.1:5432/db"));
607    }
608
609    #[test]
610    fn roast_seedlist_with_any_remote_host_is_not_loopback() {
611        // Multi-host / seedlist authority (`host1:p1,host2:p2`): the TLS gate must
612        // treat it as loopback ONLY if EVERY host is loopback. Reading just the
613        // first host let `127.0.0.1:5432,evil.com:5432` (a valid PostgreSQL and
614        // MongoDB seedlist) pass the gate and dial evil.com in plaintext
615        // (bug-hunt find; the shared gate reaches every engine, PG supports
616        // multi-host URLs).
617        assert!(!host_is_loopback(
618            "postgresql://u:p@127.0.0.1:5432,evil.com:5432/db"
619        ));
620        assert!(!host_is_loopback(
621            "mongodb://u:p@127.0.0.1:27017,evil.com:27017/db"
622        ));
623        // All-loopback seedlist stays loopback.
624        assert!(host_is_loopback(
625            "mongodb://u:p@127.0.0.1:27017,[::1]:27018/db"
626        ));
627    }
628
629    #[test]
630    fn remote_hosts_are_not_loopback() {
631        assert!(!host_is_loopback(
632            "postgresql://rivet:rivet@10.255.255.1:5432/rivet"
633        ));
634        assert!(!host_is_loopback(
635            "postgresql://u:p@db.example.com:5432/app"
636        ));
637        assert!(!host_is_loopback("mysql://root@192.168.1.10:3306/db"));
638        assert!(!host_is_loopback("sqlserver://sa:pw@10.0.0.5:1433/master"));
639        // Not loopback: an unbracketed IPv6-looking address won't parse here, so
640        // it fails closed (treated as remote).
641        assert!(!host_is_loopback("postgresql://u:p@::1:5432/db"));
642    }
643
644    #[test]
645    fn gate_refuses_remote_plaintext_only() {
646        let remote = "postgresql://rivet:rivet@10.255.255.1:5432/rivet";
647        let loopback = "postgresql://rivet:rivet@127.0.0.1:5432/rivet";
648        let disable = TlsConfig {
649            mode: TlsMode::Disable,
650            ..Default::default()
651        };
652        let verify = TlsConfig {
653            mode: TlsMode::VerifyFull,
654            ..Default::default()
655        };
656
657        // Remote + no tls block → refused.
658        assert!(require_tls_or_loopback(remote, None).is_err());
659        // Loopback + no tls block → allowed (docker / dev path).
660        assert!(require_tls_or_loopback(loopback, None).is_ok());
661        // Explicit `mode: disable` is the remote-plaintext opt-in → allowed.
662        assert!(require_tls_or_loopback(remote, Some(&disable)).is_ok());
663        // Enforced TLS to a remote host → allowed (the connect path uses TLS).
664        assert!(require_tls_or_loopback(remote, Some(&verify)).is_ok());
665    }
666
667    #[test]
668    fn host_port_span_extracts_the_authority() {
669        assert_eq!(host_port_span("mysql://u:p@host:3306/db"), "host:3306");
670        assert_eq!(
671            host_port_span("postgres://127.0.0.1:5432/db"),
672            "127.0.0.1:5432"
673        );
674        // No authority at all.
675        assert_eq!(host_port_span("mysql://"), "");
676        assert_eq!(host_port_span("postgres:///db"), "");
677    }
678
679    #[test]
680    fn hostless_url_is_a_parse_error_not_a_tls_refusal() {
681        // #dogfood LOW: `mysql://` has NO host, yet the gate reported "remote
682        // (non-loopback) host, TLS required" and prescribed a TLS block for a
683        // host that doesn't exist. It must be a clear parse error instead.
684        for u in ["mysql://", "postgres:///db", "sqlserver://"] {
685            let err = require_tls_or_loopback(u, None)
686                .expect_err("a host-less URL must error, not connect");
687            let msg = err.to_string();
688            assert!(
689                msg.contains("no host found"),
690                "host-less URL must be a parse error: {msg}"
691            );
692            assert!(
693                !msg.contains("TLS required"),
694                "host-less URL must NOT prescribe a TLS block: {msg}"
695            );
696        }
697    }
698
699    #[test]
700    fn hostless_socket_url_with_explicit_tls_disable_is_allowed() {
701        // #16 bughunt: a unix-socket URL has no authority host (the socket path
702        // lives in `?host=`), so the host-presence check rejected it. But an
703        // explicit `tls: { mode: disable }` is the operator's opt-in for a LOCAL
704        // connection — it must connect, as it did on main (where the gate was
705        // skipped whenever tls was Some). The check now lives inside the no-tls
706        // branch, so tls=Some(disable) is never refused.
707        let disable = TlsConfig {
708            mode: TlsMode::Disable,
709            ..Default::default()
710        };
711        for u in [
712            "postgres:///rivet?host=/var/run/postgresql",
713            "mysql://",
714            "postgres:///db",
715        ] {
716            require_tls_or_loopback(u, Some(&disable))
717                .expect("an explicit tls: { mode: disable } must not be refused for a socket URL");
718        }
719    }
720}
721
722/// Batch positional-mapping guard: every engine's batch decoder indexes wire
723/// rows by the RESOLVE-time column order (`SELECT *` is positional at the
724/// protocol level), so a DDL slipping between chunk reads (parallel-worker
725/// idle gaps, a chunk retry on a fresh connection) would misalign values
726/// silently. The wire carries column NAMES on all three engines — verify them
727/// against the resolved mapping before decoding each batch and fail loudly
728/// instead. (The sequential paths are already server-serialized: PG holds
729/// ACCESS SHARE across the export transaction, MySQL/InnoDB reads through a
730/// snapshot with instant-DDL row versioning — both measured live; this guard
731/// closes the residual windows.)
732pub(crate) fn verify_wire_columns(expected: &[&str], wire: &[&str]) -> anyhow::Result<()> {
733    if expected.len() != wire.len()
734        || expected
735            .iter()
736            .zip(wire)
737            .any(|(e, w)| !e.eq_ignore_ascii_case(w))
738    {
739        anyhow::bail!(
740            "the source returned columns [{}] but this export resolved [{}] — the table's \
741             schema changed while the export was running (a DDL mid-export). Re-run the \
742             export: a fresh run resolves the new schema.",
743            wire.join(", "),
744            expected.join(", "),
745        );
746    }
747    Ok(())
748}
749
750#[cfg(test)]
751mod wire_guard_tests {
752    use super::verify_wire_columns;
753
754    #[test]
755    fn verify_wire_columns_catches_every_drift_shape() {
756        let ok = verify_wire_columns(&["id", "a", "b"], &["id", "a", "b"]);
757        assert!(ok.is_ok());
758        // case-insensitive (MySQL lowercases, MSSQL preserves)
759        assert!(verify_wire_columns(&["id", "A"], &["ID", "a"]).is_ok());
760        // dropped column
761        assert!(verify_wire_columns(&["id", "a", "b"], &["id", "b"]).is_err());
762        // added column
763        assert!(verify_wire_columns(&["id", "b"], &["id", "b", "c"]).is_err());
764        // same-arity rename/reorder — the shape positional decoding CANNOT see
765        assert!(verify_wire_columns(&["id", "a", "b"], &["id", "b", "a"]).is_err());
766        let err = verify_wire_columns(&["id", "a"], &["id"]).unwrap_err();
767        assert!(err.to_string().contains("schema changed"));
768    }
769}
770
771#[cfg(test)]
772mod introspection_tests {
773    use super::TableIntrospection;
774
775    #[test]
776    fn is_integer_column_is_case_insensitive() {
777        // #bughunt MED: a case-sensitive match falsely refused `chunk_column: ID`
778        // when the catalog stores `id` — a guard must not reject on casing.
779        let intro = TableIntrospection {
780            int_columns: vec!["id".into(), "user_id".into()],
781            ..Default::default()
782        };
783        assert!(intro.is_integer_column("id"));
784        assert!(intro.is_integer_column("ID"));
785        assert!(intro.is_integer_column("User_Id"));
786        assert!(!intro.is_integer_column("name"));
787    }
788}