rivet/config/mod.rs
1pub mod cursor;
2mod destination;
3mod export;
4mod format;
5mod lints;
6mod notifications;
7pub mod resolve;
8pub mod schema;
9mod source;
10
11pub use cursor::IncrementalCursorMode;
12pub use destination::*;
13pub use export::*;
14pub use format::*;
15pub use notifications::*;
16#[allow(unused_imports)]
17pub(crate) use resolve::resolve_env_vars;
18pub use resolve::{parse_file_size, resolve_vars};
19pub use schema::generate_config_schema_pretty;
20pub use source::*;
21
22use schemars::JsonSchema;
23use serde::Deserialize;
24
25/// Top-level Rivet configuration root.
26///
27/// Operators write this struct as YAML (typically `rivet.yaml`). The
28/// `JsonSchema` derive is the source of truth for the `schemas/rivet.schema.json`
29/// artifact and the `rivet schema config` command's output (v0.7.3 P0).
30#[derive(Debug, Deserialize, JsonSchema, Clone)]
31#[serde(deny_unknown_fields)]
32pub struct Config {
33 pub source: SourceConfig,
34 pub exports: Vec<ExportConfig>,
35 #[serde(default)]
36 pub notifications: Option<NotificationsConfig>,
37 #[serde(default)]
38 pub parallel_exports: bool,
39 #[serde(default)]
40 pub parallel_export_processes: bool,
41 /// The warehouse **load** target — consumed by `rivet load` (and `rivet load
42 /// --cdc`), so ONE config drives both the export and the downstream load. The
43 /// extraction commands (`rivet check` / `run` / `apply`) accept and ignore it:
44 /// it shapes the load, not the extract.
45 // Kept as a raw `serde_json::Value` so the extraction path neither depends on
46 // nor validates the load schema — the load module (`crate::load::plan`) parses
47 // it into a typed `LoadSection`.
48 #[serde(default)]
49 pub load: Option<serde_json::Value>,
50}
51
52impl Config {
53 pub fn load(path: &str) -> crate::error::Result<Self> {
54 Self::load_with_params(path, None)
55 }
56
57 pub fn load_with_params(
58 path: &str,
59 params: Option<&std::collections::HashMap<String, String>>,
60 ) -> crate::error::Result<Self> {
61 // F11 (0.7.5 audit): raw `std::io::Error` lost the path on
62 // not-found. Wrap with the file path + a hint so the operator
63 // can see *which* config the tool could not open.
64 let contents = std::fs::read_to_string(path).map_err(|e| {
65 if e.kind() == std::io::ErrorKind::NotFound {
66 anyhow::anyhow!(
67 "config file '{}' not found.\n Hint: check the path, or run `rivet init` to generate one.",
68 path
69 )
70 } else {
71 anyhow::anyhow!("cannot read config file '{}': {}", path, e)
72 }
73 })?;
74 // Warn about typo'd `--param` keys once per CLI invocation, using the
75 // un-resolved YAML as the haystack so the placeholders are still there.
76 // We pass the raw `contents` (not `resolved`) on purpose: after
77 // resolution the placeholders are gone, and every key would look unused.
78 resolve::warn_unused_params(&contents, params);
79 let resolved = resolve_vars(&contents, params)?;
80 // F12 (0.7.5 audit): YAML parse errors did not name the config
81 // file. When loading from disk we know the path — thread it
82 // into the parse error.
83 // `.context` (not `anyhow!("…{:#}", e)`, which stringifies into a fresh
84 // error) so a typed `CodedError` raised by validation survives the chain —
85 // `error::error_code` downcasts it for the `[CODE]` prefix. `{e:#}` in
86 // `main` still renders the full "config file '…': <message>" chain.
87 Self::from_yaml(&resolved).map_err(|e| e.context(format!("config file '{}'", path)))
88 }
89
90 pub fn from_yaml(yaml: &str) -> crate::error::Result<Self> {
91 // Intercept the unquoted-`{partition}` footgun before the raw-YAML
92 // pre-scans below (they `from_str::<Value>` too and would re-emit the
93 // same cryptic libyaml message). A document that does not even parse as
94 // a `Value` is malformed; if the failure looks like a flow-mapping
95 // scanner error *and* the source carries an unquoted brace value, point
96 // straight at the quoting fix. On a valid config this `Value` parse
97 // succeeds and the block is skipped, so the success path is unchanged.
98 if let Err(e) = serde_yaml_ng::from_str::<serde_yaml_ng::Value>(yaml) {
99 let m = e.to_string();
100 if let Some(hint) = Self::unquoted_template_brace_hint(yaml, &m) {
101 return Err(anyhow::anyhow!("{e}\n {hint}"));
102 }
103 // A TAB in indentation is the most common beginner YAML mistake; it
104 // trips libyaml before serde ever sees a field, so it must be caught
105 // here in the raw scan, not in `enhance_parse_error`.
106 if let Some(hint) = Self::tab_indent_hint(yaml, &m) {
107 return Err(anyhow::anyhow!("{e}\n {hint}"));
108 }
109 }
110 Self::check_misplaced_tuning_fields(yaml)?;
111 Self::check_csv_compression(yaml)?;
112 Self::check_tls_mode_downgrade(yaml)?;
113 let config: Config = serde_yaml_ng::from_str(yaml).map_err(|e| {
114 // A well-formed flow map (`prefix: {partition}`) parses as a YAML
115 // value but serde then rejects it with `invalid type: map, expected
116 // a string`. That is the same unquoted-brace footgun, surfacing one
117 // layer later than the scanner errors caught above — so try the same
118 // hint here before falling back to the generic field-typo enhancer.
119 if let Some(hint) = Self::unquoted_template_brace_hint(yaml, &e.to_string()) {
120 anyhow::anyhow!("{e}\n {hint}")
121 } else {
122 lints::enhance_parse_error(e)
123 }
124 })?;
125 config.validate()?;
126 Ok(config)
127 }
128
129 /// Detect the unquoted-`{partition}` (or `{date}`, …) template footgun and
130 /// return an actionable quoting hint, or `None` when the error is unrelated.
131 ///
132 /// A YAML value that *starts* a flow mapping — `prefix: {partition}` — is
133 /// the common copy-paste mistake: `{partition}` is the required token for
134 /// `partition_by`, but unquoted it parses as a YAML map (or, with trailing
135 /// text, trips the libyaml scanner). serde then emits a cryptic
136 /// `did not find expected ',' or '}'` / `while parsing a flow mapping` /
137 /// `invalid type: map, expected a string` with no hint that a pair of
138 /// quotes is the fix.
139 ///
140 /// Two guards keep this from firing on unrelated parse errors: the error
141 /// message must carry one of the flow-mapping symptoms, AND the raw source
142 /// must actually contain an unquoted `{…}` value. Both must hold, so a
143 /// valid config (every brace value quoted) never sees the hint, and a
144 /// genuine map-typed field error elsewhere is left alone.
145 /// A YAML document indented with a TAB trips libyaml with `found character
146 /// that cannot start any token`. Point straight at the fix (spaces, not
147 /// tabs) — but only when the cited line really begins with a tab, so an
148 /// unrelated scanner error is left with its original message.
149 fn tab_indent_hint(yaml: &str, err_msg: &str) -> Option<String> {
150 if !err_msg.contains("tab character") {
151 return None;
152 }
153 // serde_yaml_ng reports `found a tab character … at line N column C …`;
154 // the FIRST `line N` is where the offending tab is.
155 let line_no: usize = err_msg
156 .split_once("line ")
157 .and_then(|(_, rest)| rest.split([' ', ',']).next())
158 .and_then(|n| n.parse().ok())?;
159 let line = yaml.lines().nth(line_no.checked_sub(1)?)?;
160 let leading = &line[..line.len() - line.trim_start().len()];
161 leading.contains('\t').then(|| {
162 format!(
163 "line {line_no} is indented with a TAB — YAML requires spaces. Replace the tab(s) with spaces."
164 )
165 })
166 }
167
168 fn unquoted_template_brace_hint(yaml: &str, err_msg: &str) -> Option<String> {
169 const FLOW_SYMPTOMS: &[&str] = &[
170 "did not find expected ',' or '}'",
171 "while parsing a flow mapping",
172 // A bare `key: {token}` parses as a map, then serde rejects the
173 // map where it wanted a scalar — same root cause, later layer.
174 "invalid type: map, expected a string",
175 // `key: {token}/more` runs the flow map into block context.
176 "did not find expected key",
177 ];
178 if !FLOW_SYMPTOMS.iter().any(|s| err_msg.contains(s)) {
179 return None;
180 }
181 if !yaml.lines().any(line_has_unquoted_brace_value) {
182 return None;
183 }
184 Some(
185 "a YAML value containing { } (such as {partition} or {date}) must be quoted, \
186 e.g. prefix: \"exports/{partition}/\""
187 .to_string(),
188 )
189 }
190
191 /// Reject `format: csv` paired with an explicitly-requested compression
192 /// codec (Finding #10). The CSV writer has no compression encoder, so the
193 /// codec is silently dropped on write while the run manifest still records
194 /// it — a degraded, dishonest no-op. We reject loudly at config-validate
195 /// time so `rivet check` / `rivet doctor` catch it before any run.
196 ///
197 /// This is a raw-YAML scan (like [`Self::check_misplaced_tuning_fields`])
198 /// rather than a `validate_export` check on purpose: `ExportConfig.
199 /// compression` is `#[serde(default)]` and `CompressionType::default()` is
200 /// `Zstd`, so a parsed export cannot distinguish "user asked for zstd" from
201 /// "user omitted the field". Only a user who *wrote* `compression:`/
202 /// `compression_profile:` is asking for something the CSV writer cannot
203 /// honour; the bare-`format: csv` default writes uncompressed and is fine.
204 fn check_csv_compression(yaml: &str) -> crate::error::Result<()> {
205 let root: serde_yaml_ng::Value = serde_yaml_ng::from_str(yaml)?;
206 let Some(exports) = root.get("exports").and_then(|e| e.as_sequence()) else {
207 return Ok(());
208 };
209 for export in exports {
210 if export.get("format").and_then(|f| f.as_str()) != Some("csv") {
211 continue;
212 }
213 let name = export
214 .get("name")
215 .and_then(|n| n.as_str())
216 .unwrap_or("<unnamed>");
217
218 // Explicit `compression:` codec that the CSV writer cannot apply.
219 // An unrecognised label is left for serde to reject during the real
220 // parse; we only act on a codec we understand and that CSV cannot
221 // honour (everything but `none`).
222 if let Some(codec) = export.get("compression").and_then(|c| c.as_str())
223 && let Some(ct) = CompressionType::from_label(codec)
224 && !format::compression_supported(FormatType::Csv, ct)
225 {
226 anyhow::bail!(
227 "export '{}': CSV output does not support compression: {}. \
228 CSV has no compression encoder, so the codec would be silently dropped \
229 while the manifest records it.\n \
230 Hint: use `format: parquet` for compression, or set `compression: none`.",
231 name,
232 codec,
233 );
234 }
235
236 // A `compression_profile:` other than `none` resolves to a real
237 // codec too (fast→snappy, balanced/compact→zstd) — same no-op.
238 if let Some(profile) = export.get("compression_profile").and_then(|c| c.as_str())
239 && profile != CompressionProfile::None.label()
240 {
241 anyhow::bail!(
242 "export '{}': CSV output does not support compression_profile: {} \
243 (it resolves to a compression codec the CSV writer cannot apply).\n \
244 Hint: use `format: parquet` for compression, or set `compression_profile: none`.",
245 name,
246 profile,
247 );
248 }
249 }
250 Ok(())
251 }
252
253 /// V13: reject a `source.tls` block that pairs an *explicitly chosen*
254 /// enforced `mode:` with a verification-disabling danger knob
255 /// (`accept_invalid_certs` / `accept_invalid_hostnames`). `mode: verify-full`
256 /// promises chain + hostname verification, but the knob silently downgrades
257 /// it to "trust anything" — a MITM exposure that contradicts the stated
258 /// intent (see `src/source/tls.rs::build_native_tls`, whose comment claims
259 /// this is warned about at config-time but is not).
260 ///
261 /// Like [`Self::check_csv_compression`], this is a raw-YAML scan rather than
262 /// a `validate` check on purpose: `TlsMode` is `#[serde(default)]` and the
263 /// default is `VerifyFull`, so a parsed config cannot distinguish "user
264 /// wrote `mode: verify-full`" (a contradiction to flag) from "user omitted
265 /// `mode:`" (the common dev-container case `tls: { accept_invalid_certs:
266 /// true }` against a loopback self-signed cert — which must keep working).
267 /// Only an *explicit* enforced `mode:` next to a danger knob is the footgun.
268 fn check_tls_mode_downgrade(yaml: &str) -> crate::error::Result<()> {
269 let root: serde_yaml_ng::Value = serde_yaml_ng::from_str(yaml)?;
270 let Some(tls) = root.get("source").and_then(|s| s.get("tls")) else {
271 return Ok(());
272 };
273
274 // Only an explicitly written `mode:` is a deliberate, contradicted
275 // choice; an omitted mode is the dev-container default path.
276 let Some(mode) = tls.get("mode").and_then(|m| m.as_str()) else {
277 return Ok(());
278 };
279 // `disable` carries no verification promise to contradict; the danger
280 // knobs are a no-op there. Flag only the enforced modes.
281 if mode == "disable" {
282 return Ok(());
283 }
284
285 let knob = if tls
286 .get("accept_invalid_certs")
287 .and_then(|v| v.as_bool())
288 .unwrap_or(false)
289 {
290 Some("accept_invalid_certs")
291 } else if tls
292 .get("accept_invalid_hostnames")
293 .and_then(|v| v.as_bool())
294 .unwrap_or(false)
295 {
296 Some("accept_invalid_hostnames")
297 } else {
298 None
299 };
300
301 if let Some(knob) = knob {
302 anyhow::bail!(
303 "source.tls: {} disables certificate verification, silently downgrading the \
304 chosen `mode: {}` to trust-anything (MITM exposure — credentials and rows \
305 readable/forgeable on the wire).\n \
306 Hint: drop the danger knob and trust a private CA with `tls.ca_file: <pem>`; \
307 only use a danger knob for a loopback self-signed dev container, and then omit \
308 the explicit `mode:` so the contradiction is gone.",
309 knob,
310 mode,
311 );
312 }
313 Ok(())
314 }
315
316 /// Detect tuning-related fields placed directly under `source:` or an
317 /// `exports[]` entry instead of inside the `tuning:` sub-key. Without this
318 /// check serde silently ignores unknown keys and the user gets unexpected
319 /// defaults (e.g. batch_size=10 000 instead of the intended 1 000).
320 fn check_misplaced_tuning_fields(yaml: &str) -> crate::error::Result<()> {
321 const TUNING_FIELDS: &[&str] = &[
322 "batch_size",
323 "batch_size_memory_mb",
324 "throttle_ms",
325 "statement_timeout_s",
326 "max_retries",
327 "retry_backoff_ms",
328 "lock_timeout_s",
329 "memory_threshold_mb",
330 "profile",
331 ];
332
333 let root: serde_yaml_ng::Value = serde_yaml_ng::from_str(yaml)?;
334
335 if let Some(source) = root.get("source") {
336 let misplaced: Vec<&str> = TUNING_FIELDS
337 .iter()
338 .copied()
339 .filter(|&f| source.get(f).is_some())
340 .collect();
341 if !misplaced.is_empty() {
342 anyhow::bail!(
343 "source: field(s) [{}] belong under 'source.tuning:', not directly under 'source:'. \
344 Example:\n source:\n tuning:\n {}: <value>",
345 misplaced.join(", "),
346 misplaced[0],
347 );
348 }
349 }
350
351 if let Some(exports) = root.get("exports").and_then(|e| e.as_sequence()) {
352 for (i, export) in exports.iter().enumerate() {
353 let name = export
354 .get("name")
355 .and_then(|n| n.as_str())
356 .unwrap_or("<unnamed>");
357 let misplaced: Vec<&str> = TUNING_FIELDS
358 .iter()
359 .copied()
360 .filter(|&f| export.get(f).is_some())
361 .collect();
362 if !misplaced.is_empty() {
363 anyhow::bail!(
364 "export '{}' (index {}): field(s) [{}] belong under 'exports[].tuning:', \
365 not directly in the export. Example:\n exports:\n - name: {}\n tuning:\n {}: <value>",
366 name,
367 i,
368 misplaced.join(", "),
369 name,
370 misplaced[0],
371 );
372 }
373 }
374 }
375
376 Ok(())
377 }
378
379 /// Reject a config before any plan/connect step. The body is split into
380 /// three cohesive validators so each can be read — and unit-tested — on its
381 /// own: the export-list shape, the source connection block, and the
382 /// per-export rules. The end-to-end surface (`Config::from_yaml`) is
383 /// covered by `config/tests/{validation,secops}.rs`; the split additionally
384 /// lets a rule be exercised directly via `validate_export`.
385 fn validate(&self) -> crate::error::Result<()> {
386 self.validate_exports_list()?;
387 self.validate_source_connection()?;
388 for export in &self.exports {
389 self.validate_export(export)?;
390 }
391 self.validate_cdc_resource_conflicts()?;
392 self.validate_non_sql_source_modes()?;
393 Ok(())
394 }
395
396 /// Non-SQL sources (MongoDB) support only `mode: full` today. Chunked /
397 /// incremental / keyset / time-window all build SQL predicates over an
398 /// introspectable columnar schema, and CDC (change streams) is a separate,
399 /// not-yet-implemented seam. Rejecting the other modes here is precisely
400 /// what makes the SQL-only builders' `unreachable!` arms
401 /// (`sql::quote_ident`, `query::cursor_rhs`, …) provably unreachable for a
402 /// document-store source.
403 fn validate_non_sql_source_modes(&self) -> crate::error::Result<()> {
404 if self.source.source_type.is_sql() {
405 return Ok(());
406 }
407 for e in &self.exports {
408 if !matches!(e.mode, ExportMode::Full | ExportMode::Cdc) {
409 crate::config_bail!(
410 crate::error::codes::CONFIG_SOURCE_MODE_UNSUPPORTED,
411 "export '{}': source type '{:?}' supports `mode: full` (batch) and \
412 `mode: cdc` (change streams) (got `mode: {:?}`). MongoDB has no SQL, so \
413 chunked / incremental / keyset / time-window are not available; every \
414 document exports as `_id` + a `document` JSON column.",
415 e.name,
416 self.source.source_type,
417 e.mode
418 );
419 }
420 // An impossible combination must be a config error, not a silent
421 // behavior downgrade: the parallel `_id`-range path keeps NO keyset
422 // checkpoint, so `resume: true` was silently ignored — the whole
423 // collection re-read every run with no warning (bug-hunt find).
424 if e.parallel > 1 && self.source.mongo.as_ref().is_some_and(|m| m.resume) {
425 crate::config_bail!(
426 crate::error::codes::CONFIG_SOURCE_MODE_UNSUPPORTED,
427 "export '{}': `source.mongo.resume: true` cannot be combined with \
428 `parallel: {}` — the parallel `_id`-range fan-out keeps no keyset \
429 checkpoint, so resume would be silently ignored. Drop `parallel` \
430 to keep cross-run resume, or drop `resume` to keep the fan-out.",
431 e.name,
432 e.parallel
433 );
434 }
435 }
436 Ok(())
437 }
438
439 /// CDC stream resources are per-export and their **defaults collide**: two
440 /// PostgreSQL cdc exports without an explicit `slot:` both resolve to
441 /// `rivet_slot` — each export's ack advances `confirmed_flush_lsn` past
442 /// changes the *other* never read (mutual, silent data loss). Two MySQL
443 /// exports both default to `server_id: 4271` — the server kills the older
444 /// replica connection. A shared `checkpoint:` path makes exports overwrite
445 /// each other's resume position on any engine. All three are config bugs a
446 /// naive multi-table CDC config hits by default, so reject them at load, on
447 /// the RESOLVED values (defaults included). SQL Server `capture_instance`
448 /// sharing is deliberately allowed: the change-table poll is read-only and
449 /// resume state lives in the per-export checkpoint.
450 fn validate_cdc_resource_conflicts(&self) -> crate::error::Result<()> {
451 use std::collections::HashMap;
452
453 let mut slots: HashMap<String, &str> = HashMap::new();
454 let mut server_ids: HashMap<u32, &str> = HashMap::new();
455 let mut checkpoints: HashMap<&str, &str> = HashMap::new();
456
457 for e in self.exports.iter().filter(|e| e.mode == ExportMode::Cdc) {
458 let cdc = e.cdc.as_ref();
459 match self.source.source_type {
460 SourceType::Postgres => {
461 let slot = cdc
462 .and_then(|c| c.slot.clone())
463 .unwrap_or_else(|| DEFAULT_PG_SLOT.to_string());
464 if let Some(prev) = slots.insert(slot.clone(), &e.name) {
465 crate::config_bail!(
466 crate::error::codes::CONFIG_CDC_RESOURCE_CONFLICT,
467 "exports '{prev}' and '{}': same PostgreSQL slot '{slot}' — a slot \
468 has ONE consumer; each export's ack would advance it past changes \
469 the other never read (silent data loss). Set a distinct `cdc.slot:` \
470 per export (the default is '{DEFAULT_PG_SLOT}').",
471 e.name
472 );
473 }
474 }
475 SourceType::Mysql => {
476 let sid = cdc
477 .and_then(|c| c.server_id)
478 .unwrap_or(DEFAULT_MYSQL_SERVER_ID);
479 if let Some(prev) = server_ids.insert(sid, &e.name) {
480 crate::config_bail!(
481 crate::error::codes::CONFIG_CDC_RESOURCE_CONFLICT,
482 "exports '{prev}' and '{}': same MySQL server_id {sid} — the server \
483 kills the older replica connection when a new one registers with \
484 the same id. Set a distinct `cdc.server_id:` per export (the \
485 default is {DEFAULT_MYSQL_SERVER_ID}).",
486 e.name
487 );
488 }
489 }
490 SourceType::Mssql => {}
491 // MongoDB change streams watch the whole database — no per-export
492 // slot or server_id to collide. Two Mongo CDC exports sharing a
493 // `checkpoint:` path IS still a conflict, caught by the shared
494 // checkpoint check below.
495 SourceType::Mongo => {}
496 }
497 if let Some(ckpt) = cdc.and_then(|c| c.checkpoint.as_deref())
498 && let Some(prev) = checkpoints.insert(ckpt, &e.name)
499 {
500 crate::config_bail!(
501 crate::error::codes::CONFIG_CDC_RESOURCE_CONFLICT,
502 "exports '{prev}' and '{}': same checkpoint path '{ckpt}' — each export \
503 must own its resume position or they overwrite each other's. Set a \
504 distinct `cdc.checkpoint:` per export.",
505 e.name
506 );
507 }
508 }
509 Ok(())
510 }
511
512 /// Whole-config shape: at least one export, names unique.
513 fn validate_exports_list(&self) -> crate::error::Result<()> {
514 // An empty `exports:` list is almost always a typo (wrong config file,
515 // dropped anchor, merged doc with the anchor section missing). Running
516 // with zero exports is a silent no-op that looks like success in CI;
517 // reject fast instead. See QA backlog Task 5.1.
518 if self.exports.is_empty() {
519 crate::config_bail!(
520 crate::error::codes::CONFIG_NO_EXPORTS,
521 "exports: at least one export must be defined (got empty list)"
522 );
523 }
524
525 // Duplicate export names break state tracking: `export_state`,
526 // `file_log`, and `chunk_run` are all keyed by `export_name`, so
527 // two configs with the same name silently share cursor/file-log rows.
528 // QA backlog Task 5.1.
529 let mut seen: std::collections::HashSet<&str> =
530 std::collections::HashSet::with_capacity(self.exports.len());
531 for e in &self.exports {
532 if !seen.insert(e.name.as_str()) {
533 crate::config_bail!(
534 crate::error::codes::CONFIG_DUPLICATE_EXPORT,
535 "exports: duplicate export name '{}' (each export must have a unique name; state is keyed by name)",
536 e.name
537 );
538 }
539 }
540 Ok(())
541 }
542
543 /// Source connection block: exactly one connection method, well-formed,
544 /// and the source-level tuning that is shared by every export.
545 fn validate_source_connection(&self) -> crate::error::Result<()> {
546 if let Some(t) = &self.source.tuning
547 && t.batch_size.is_some()
548 && t.batch_size_memory_mb.is_some()
549 {
550 anyhow::bail!(
551 "tuning: batch_size and batch_size_memory_mb are mutually exclusive. \
552 Prefer batch_size_memory_mb (rivet sizes the batch to a memory budget, \
553 adapting to row width); set batch_size only to pin an exact row count."
554 );
555 }
556
557 if !self.source.has_url_fields() && !self.source.has_structured_fields() {
558 // First-run footgun: a config that forgot the source block
559 // entirely. Show the recommended path (`url_env`) up-front;
560 // operators who actually want structured fields know to look
561 // for them.
562 anyhow::bail!(
563 "source: no connection method configured. Add one of:\n url_env: DATABASE_URL (URL from env var — recommended)\n url: 'postgresql://user:pass@host:5432/db' (inline — not recommended for committed configs)\n url_file: /etc/rivet/source.url (URL from file — rotation-friendly)\n host/user/database/... (structured fields under `source:`)"
564 );
565 }
566
567 if self.source.has_url_fields() {
568 let url_count = [
569 &self.source.url,
570 &self.source.url_env,
571 &self.source.url_file,
572 ]
573 .iter()
574 .filter(|u| u.is_some())
575 .count();
576 if url_count > 1 {
577 anyhow::bail!(
578 "source: specify exactly one of 'url', 'url_env', or 'url_file' (got {} set).\n Hint: pick one — `url_env` is recommended so credentials never enter the YAML.",
579 url_count
580 );
581 }
582 }
583
584 if self.source.has_url_fields() && self.source.has_structured_fields() {
585 anyhow::bail!(
586 "source: pick either URL-based config (url/url_env/url_file) OR structured fields (host/user/database/port/password_env), not both.\n Hint: remove whichever block you don't want; mixing the two is ambiguous."
587 );
588 }
589
590 if self.source.has_structured_fields() {
591 if self.source.host.is_none() {
592 anyhow::bail!(
593 "source: structured config is missing 'host'.\n Hint: add `host: localhost` (or your DB host) under `source:` in rivet.yaml.\n Or switch to URL-based config: `url_env: DATABASE_URL`."
594 );
595 }
596 if self.source.user.is_none() {
597 anyhow::bail!(
598 "source: structured config is missing 'user'.\n Hint: add `user: <username>` under `source:` in rivet.yaml."
599 );
600 }
601 if self.source.database.is_none() {
602 anyhow::bail!(
603 "source: structured config is missing 'database'.\n Hint: add `database: <dbname>` under `source:` in rivet.yaml."
604 );
605 }
606 if self.source.password.is_some() && self.source.password_env.is_some() {
607 anyhow::bail!(
608 "source: specify 'password' OR 'password_env', not both.\n Hint: prefer `password_env: DB_PASSWORD` so credentials never enter the YAML."
609 );
610 }
611 }
612 Ok(())
613 }
614
615 /// Per-export rules: effective tuning, query source, `query_file` SecOps,
616 /// destination auth, compression, and the mode/chunk matrix. Takes `&self`
617 /// because effective tuning merges the source-level block.
618 fn validate_export(&self, export: &ExportConfig) -> crate::error::Result<()> {
619 // V5: `name` is keyed into output paths, file logs, and on-disk state,
620 // yet is otherwise free-form. A traversal (`../../etc/x`), absolute or
621 // slash-bearing (`/abs/x`, `sub/dir`), leading-dot, or NUL-bearing name
622 // escapes the intended output tree and corrupts name-keyed state.
623 // Mirror the `query_file` `..`/absolute guard: reject at config-load,
624 // accepting only a filename-safe charset.
625 if !is_filename_safe_name(&export.name) {
626 anyhow::bail!(
627 "export name '{}' is not filename-safe: it must not be absolute, contain \
628 '/', '\\', '..', a NUL, or start with '.' (the name is used in output paths \
629 and state keys). Use a plain identifier like `orders` or `daily_events`.",
630 export.name.escape_default(),
631 );
632 }
633
634 // V5 (round-2 audit #5): each `tables:` entry becomes a destination path
635 // SEGMENT in dest_for_table (local `<path>/<table>`, cloud `<prefix>/
636 // <table>/`), so an entry with `..`/`/` escapes the configured tree exactly
637 // like an unsafe export.name — the multi-tenant-wrapper threat model V5/V15
638 // defend. The single `table:` shortcut and export.name are guarded; the
639 // `tables:` list was not. Reject an unsafe segment at config-load, before
640 // dest_for_table (or the pre-write manifest FS probe) ever sees it.
641 for t in export.tables.iter().flatten() {
642 if !is_filename_safe_name(t) {
643 anyhow::bail!(
644 "export '{}': tables entry '{}' is not filename-safe: it must not contain \
645 '/', '\\', '..', a NUL, or start with '.' (each table becomes a destination \
646 path segment).",
647 export.name,
648 t.escape_default(),
649 );
650 }
651 }
652
653 // Round-2 audit #15/#16/#6: partition_by has purely-static rules (mode
654 // compatibility, the `{partition}` token, a filename-safe column name) that
655 // only lived in the run-time expansion step, so `rivet check` gave a false
656 // green and `rivet run` failed later — after a live DB probe, or (mode: cdc)
657 // with a misleading "requires table:". Enforce them at config-load so check
658 // and run agree, mirroring the chunk_dense/chunk_by_days guards.
659 if let Some(col) = export.partition_by.as_deref() {
660 if col.trim().is_empty() {
661 anyhow::bail!("export '{}': partition_by must name a column", export.name);
662 }
663 // #6: the column name becomes the Hive `col=value` path segment, so a
664 // quoted DB column named `../x` would inject a traversal — filename-gate it.
665 if !is_filename_safe_name(col) {
666 anyhow::bail!(
667 "export '{}': partition_by column '{}' is not filename-safe: it must not \
668 contain '/', '\\', '..', a NUL, or start with '.' (it becomes a `col=value` \
669 destination path segment).",
670 export.name,
671 col.escape_default(),
672 );
673 }
674 if matches!(export.mode, ExportMode::TimeWindow | ExportMode::Cdc) {
675 anyhow::bail!(
676 "export '{}': partition_by is not compatible with `mode: {:?}` — it is a batch \
677 output-layout feature; partition a full/chunked/incremental export instead.",
678 export.name,
679 export.mode,
680 );
681 }
682 // Round-5: partition_by writes N per-partition manifests (one per
683 // col=value/ sub-prefix), but `rivet load` (reconcile.rs select_runs)
684 // picks a SINGLE latest-manifest for the export and would load only ONE
685 // partition, silently dropping the rest. Reject the combo at config-load
686 // until the loader is partition-aware.
687 if export.load.is_some() {
688 anyhow::bail!(
689 "export '{}': partition_by is not compatible with a `load:` block — a \
690 partitioned export writes one manifest per partition sub-prefix, but the \
691 warehouse loader would load only a single partition. Load a non-partitioned \
692 export, or drop `load:` and run `rivet load` per partition.",
693 export.name,
694 );
695 }
696 if export.chunk_by_key.is_some() {
697 anyhow::bail!(
698 "export '{}': partition_by is not compatible with chunk_by_key — keyset needs \
699 the `table:` shortcut to verify the index, but partitioning rewrites the query \
700 into a subquery. Use a range `chunk_column`, a smaller `partition_granularity`, \
701 or `mode: full`.",
702 export.name
703 );
704 }
705 let has_token = export
706 .destination
707 .path
708 .as_deref()
709 .is_some_and(|s| s.contains("{partition}"))
710 || export
711 .destination
712 .prefix
713 .as_deref()
714 .is_some_and(|s| s.contains("{partition}"));
715 if !has_token {
716 anyhow::bail!(
717 "export '{}': partition_by requires a '{{partition}}' token in destination.path \
718 or destination.prefix (otherwise every partition would overwrite the same prefix).",
719 export.name
720 );
721 }
722 }
723
724 // Round-2 audit #17: chunk_size_memory_mb is documented mutually exclusive
725 // with an explicit chunk_size — build.rs takes the memory budget and
726 // silently drops chunk_size when both are set, mirroring the batch_size pair.
727 if export.chunk_size_memory_mb.is_some() && export.chunk_size != default_chunk_size() {
728 anyhow::bail!(
729 "export '{}': chunk_size and chunk_size_memory_mb are mutually exclusive — \
730 chunk_size_memory_mb derives the window size from a memory budget, so an explicit \
731 chunk_size would be silently ignored. Set one or the other.",
732 export.name
733 );
734 }
735
736 let merged =
737 crate::tuning::merge_tuning_config(self.source.tuning.as_ref(), export.tuning.as_ref());
738 if let Some(t) = merged
739 && t.batch_size.is_some()
740 && t.batch_size_memory_mb.is_some()
741 {
742 anyhow::bail!(
743 "export '{}': effective tuning has both batch_size and batch_size_memory_mb (mutually exclusive)",
744 export.name
745 );
746 }
747 if let Some(et) = &export.tuning
748 && et.batch_size.is_some()
749 && et.batch_size_memory_mb.is_some()
750 {
751 anyhow::bail!(
752 "export '{}': tuning.batch_size and tuning.batch_size_memory_mb are mutually exclusive",
753 export.name
754 );
755 }
756
757 // Before the generic exactly-one counting: the `table:`/`tables:` pair
758 // gets its specific message (the generic one doesn't mention `tables`).
759 if export.table.is_some() && export.tables.is_some() {
760 anyhow::bail!(
761 "export '{}': `table:` and `tables:` are mutually exclusive — use \
762 `tables: [a, b]` for a multi-table stream",
763 export.name
764 );
765 }
766
767 let set_count = [
768 export.query.is_some(),
769 export.query_file.is_some(),
770 export.table.is_some(),
771 // A multi-table CDC stream (`tables:`) is that export's source
772 // specification — the CDC arm below owns its shape rules.
773 export.tables.is_some(),
774 ]
775 .iter()
776 .filter(|b| **b)
777 .count();
778 if set_count == 0 {
779 anyhow::bail!(
780 "export '{}': specify exactly one of 'query', 'query_file', 'table', or 'tables'. \
781 Use table: <name> for a whole table (enables PK auto-chunking); \
782 query: \"SELECT …\" for an inline one-liner; \
783 query_file: <path> for SQL you keep in version control.",
784 export.name
785 );
786 }
787 if set_count > 1 {
788 anyhow::bail!(
789 "export '{}': specify exactly one of 'query', 'query_file', 'table', or 'tables' (got {} set)",
790 export.name,
791 set_count
792 );
793 }
794 // SecOps: syntactic `query_file` checks must run at config-validate
795 // time so `rivet check` / `rivet doctor` catch them before any
796 // plan step. The same checks repeat (with a canonicalize-based
797 // symlink probe) in `ExportConfig::resolve_query` because the
798 // file may have been swapped between validation and read.
799 if let Some(file) = &export.query_file {
800 let p = std::path::Path::new(file);
801 if p.is_absolute() {
802 anyhow::bail!(
803 "export '{}': query_file must be a relative path: '{}'",
804 export.name,
805 file
806 );
807 }
808 if p.components().any(|c| c == std::path::Component::ParentDir) {
809 anyhow::bail!(
810 "export '{}': query_file path must not contain '..': '{}'",
811 export.name,
812 file
813 );
814 }
815 }
816 // V2/V12: a custom cloud `endpoint` is handed straight to the opendal
817 // S3/GCS/Azure builder with no validation, so a committed config can
818 // silently redirect every upload to an attacker host (exfiltration) or
819 // send credentials + rows over cleartext `http://`. The legitimate use
820 // is a local emulator (Minio / Azurite / fake-gcs on `127.0.0.1`), so
821 // accept a loopback host (any scheme), and otherwise accept a remote
822 // endpoint only when the operator has explicitly opted into anonymous
823 // (emulator) mode. Reject every other custom endpoint at config-load.
824 if matches!(
825 export.destination.destination_type,
826 DestinationType::S3 | DestinationType::Gcs | DestinationType::Azure
827 ) && let Some(endpoint) = &export.destination.endpoint
828 {
829 // Loopback emulator (Minio/Azurite/fake-gcs) is the legitimate
830 // local-dev path — accept any scheme. A non-loopback (or
831 // unparseable) custom endpoint is only accepted when the operator
832 // has explicitly opted into anonymous (emulator) mode, where no
833 // credentials are sent. Everything else is rejected.
834 let loopback = endpoint_host(endpoint).is_some_and(|host| is_loopback_host(&host));
835 if !loopback && !export.destination.allow_anonymous {
836 anyhow::bail!(
837 "export '{}': destination.endpoint '{}' points at a non-loopback host. \
838 A custom endpoint redirects every upload there — committing one is a \
839 data-exfiltration / cleartext-credential risk.\n \
840 Hint: drop `endpoint:` to use the provider default, point it at a \
841 loopback emulator (e.g. http://127.0.0.1:9000 with allow_anonymous: true \
842 for Minio/Azurite), or set `allow_anonymous: true` for an anonymous \
843 emulator.",
844 export.name,
845 endpoint,
846 );
847 }
848 }
849
850 // V15: a `type: local` destination `path` (or `prefix`) is written
851 // verbatim to the filesystem. A `..` component lets a committed config
852 // climb out of the intended output tree (`../../../../tmp/x`) — mirror
853 // the `query_file` traversal guard and reject it at config-load.
854 //
855 // Absolute paths are deliberately *not* rejected: `path: /output` is a
856 // legitimate Docker volume-mount pattern (see `examples/rivet.yaml`) and
857 // an explicit operator choice, not a hidden escape. The `..` climb is
858 // the unambiguous traversal footgun.
859 if export.destination.destination_type == DestinationType::Local {
860 for (field, value) in [
861 ("path", export.destination.path.as_deref()),
862 ("prefix", export.destination.prefix.as_deref()),
863 ] {
864 let Some(value) = value else { continue };
865 if std::path::Path::new(value)
866 .components()
867 .any(|c| c == std::path::Component::ParentDir)
868 {
869 anyhow::bail!(
870 "export '{}': local destination {} must not contain a '..' component: \
871 '{}' (a parent-dir climb writes outside the output tree).",
872 export.name,
873 field,
874 value
875 );
876 }
877 }
878 }
879
880 if export.destination.destination_type == DestinationType::S3 {
881 let ak = export.destination.access_key_env.is_some();
882 let sk = export.destination.secret_key_env.is_some();
883 if ak != sk {
884 anyhow::bail!(
885 "export '{}': S3 requires both access_key_env and secret_key_env, or neither (use default AWS credential chain)",
886 export.name
887 );
888 }
889 }
890
891 if export.destination.destination_type == DestinationType::Gcs
892 && export.destination.allow_anonymous
893 && export.destination.credentials_file.is_some()
894 {
895 anyhow::bail!(
896 "export '{}': GCS allow_anonymous cannot be used together with credentials_file",
897 export.name
898 );
899 }
900
901 if export.destination.destination_type == DestinationType::Azure {
902 let has_name = export.destination.account_name.is_some();
903 let has_key = export.destination.account_key_env.is_some();
904 let has_sas = export.destination.sas_token_env.is_some();
905 if export.destination.allow_anonymous {
906 if has_name || has_key || has_sas {
907 anyhow::bail!(
908 "export '{}': Azure allow_anonymous cannot be combined with account_name/account_key_env/sas_token_env",
909 export.name
910 );
911 }
912 } else if has_key && has_sas {
913 anyhow::bail!(
914 "export '{}': Azure account_key_env and sas_token_env are mutually exclusive — pick one auth mode",
915 export.name
916 );
917 } else if !has_name {
918 anyhow::bail!(
919 "export '{}': Azure requires account_name (plus account_key_env or sas_token_env), or allow_anonymous: true for Azurite",
920 export.name
921 );
922 } else if !has_key && !has_sas {
923 anyhow::bail!(
924 "export '{}': Azure requires account_key_env or sas_token_env (or allow_anonymous: true for Azurite)",
925 export.name
926 );
927 }
928 }
929
930 if let Some(cred_path) = &export.destination.credentials_file
931 && !std::path::Path::new(cred_path).exists()
932 {
933 anyhow::bail!(
934 "export '{}': credentials_file '{}' does not exist",
935 export.name,
936 cred_path
937 );
938 }
939
940 if let Some(ref size_str) = export.max_file_size {
941 parse_file_size(size_str).map_err(|_| {
942 anyhow::anyhow!(
943 "export '{}': invalid max_file_size '{}'",
944 export.name,
945 size_str
946 )
947 })?;
948 }
949
950 if let Some(level) = export.compression_level {
951 match export.compression {
952 CompressionType::Zstd => {
953 if !(1..=22).contains(&level) {
954 anyhow::bail!(
955 "export '{}': zstd compression_level must be 1..22, got {}",
956 export.name,
957 level
958 );
959 }
960 }
961 CompressionType::Gzip => {
962 if level > 10 {
963 anyhow::bail!(
964 "export '{}': gzip compression_level must be 0..10, got {}",
965 export.name,
966 level
967 );
968 }
969 }
970 _ => {
971 anyhow::bail!(
972 "export '{}': compression_level is only supported for zstd and gzip",
973 export.name
974 );
975 }
976 }
977 }
978
979 match export.mode {
980 ExportMode::Incremental => {
981 if export.cursor_column.is_none() {
982 anyhow::bail!(
983 "export '{}': incremental mode requires cursor_column",
984 export.name
985 );
986 }
987 match export.incremental_cursor_mode {
988 IncrementalCursorMode::Coalesce => {
989 if export.cursor_fallback_column.is_none() {
990 anyhow::bail!(
991 "export '{}': incremental_cursor_mode: coalesce requires cursor_fallback_column",
992 export.name
993 );
994 }
995 }
996 IncrementalCursorMode::SingleColumn => {
997 if export.cursor_fallback_column.is_some() {
998 anyhow::bail!(
999 "export '{}': cursor_fallback_column is only valid with incremental_cursor_mode: coalesce",
1000 export.name
1001 );
1002 }
1003 }
1004 }
1005 }
1006 ExportMode::Chunked => {
1007 // `chunk_column` is mandatory unless the user used the `table:`
1008 // shortcut on a Postgres source — in that case it is auto-resolved
1009 // from the table's single-integer PK at plan-build time (see
1010 // `crate::plan::build::resolve_chunk_column`).
1011 if export.chunk_column.is_none() && export.table.is_none() {
1012 anyhow::bail!(
1013 "export '{}': chunked mode needs a chunking strategy. Pick one:\n \
1014 chunk_column: <int col> range chunks on an integer column (most common)\n \
1015 chunk_by_key: <unique col> keyset pagination when there's no integer PK\n \
1016 chunk_count: <N> split the range into N equal chunks\n \
1017 chunk_by_days: <D> time-bucketed chunks (needs a date/timestamp column)\n \
1018 Or use the `table:` shortcut on a single table — rivet auto-resolves the column from the primary key.",
1019 export.name
1020 );
1021 }
1022 // chunk_size == 0 would divide the range into zero-width
1023 // slices and (before the saturating fix in generate_chunks)
1024 // either infinite-loop or produce no progress. QA backlog
1025 // Task 5.1.
1026 if export.chunk_size == 0 {
1027 anyhow::bail!(
1028 "export '{}': chunked mode requires chunk_size >= 1 (got 0)",
1029 export.name
1030 );
1031 }
1032 // parallel == 0 means "spawn zero workers". Claiming tasks
1033 // with no workers stalls the pipeline. QA backlog Task 5.1.
1034 if export.parallel == 0 {
1035 anyhow::bail!(
1036 "export '{}': chunked mode requires parallel >= 1 (got 0)",
1037 export.name
1038 );
1039 }
1040 if let Some(0) = export.chunk_count {
1041 crate::config_bail!(
1042 crate::error::codes::CONFIG_CHUNK_COUNT_INVALID,
1043 "export '{}': chunk_count must be >= 1",
1044 export.name
1045 );
1046 }
1047 if export.chunk_count.is_some() && export.chunk_dense {
1048 anyhow::bail!(
1049 "export '{}': chunk_count and chunk_dense are mutually exclusive. \
1050 Use chunk_count for equal-sized chunks over a sparse key; \
1051 use chunk_dense only when the key has no gaps.",
1052 export.name
1053 );
1054 }
1055 if export.chunk_count.is_some() && export.chunk_by_days.is_some() {
1056 anyhow::bail!(
1057 "export '{}': chunk_count and chunk_by_days are mutually exclusive. \
1058 Use chunk_count: N to split an integer range into N chunks; \
1059 use chunk_by_days: D to bucket a date/timestamp column by D-day windows.",
1060 export.name
1061 );
1062 }
1063 }
1064 ExportMode::TimeWindow => {
1065 if export.time_column.is_none() {
1066 anyhow::bail!(
1067 "export '{}': time_window mode requires time_column",
1068 export.name
1069 );
1070 }
1071 if export.days_window.is_none() {
1072 anyhow::bail!(
1073 "export '{}': time_window mode requires days_window",
1074 export.name
1075 );
1076 }
1077 }
1078 ExportMode::Full => {}
1079 ExportMode::Cdc => {
1080 match (&export.table, &export.tables) {
1081 (None, None) => anyhow::bail!(
1082 "export '{}': cdc mode requires `table:` (or `tables:` for a \
1083 multi-table stream)",
1084 export.name
1085 ),
1086 (Some(_), Some(_)) => anyhow::bail!(
1087 "export '{}': `table:` and `tables:` are mutually exclusive — \
1088 use `tables: [a, b]` for a multi-table stream",
1089 export.name
1090 ),
1091 (None, Some(ts)) => {
1092 if ts.is_empty() {
1093 anyhow::bail!(
1094 "export '{}': `tables:` must list at least one table",
1095 export.name
1096 );
1097 }
1098 let mut seen = std::collections::HashSet::new();
1099 for t in ts {
1100 if !seen.insert(t.as_str()) {
1101 anyhow::bail!(
1102 "export '{}': duplicate table '{}' in `tables:`",
1103 export.name,
1104 t
1105 );
1106 }
1107 }
1108 if self.source.source_type == SourceType::Mssql {
1109 anyhow::bail!(
1110 "export '{}': `tables:` is not yet supported for SQL Server — \
1111 its capture instances are per-table; use one cdc export per \
1112 table (capture_instance each)",
1113 export.name
1114 );
1115 }
1116 }
1117 (Some(_), None) => {}
1118 }
1119 if export.query.is_some() || export.query_file.is_some() {
1120 anyhow::bail!(
1121 "export '{}': cdc mode reads the transaction log, not a query — \
1122 remove query/query_file and use `table:`",
1123 export.name
1124 );
1125 }
1126 }
1127 }
1128
1129 if export.tables.is_some() && export.mode != ExportMode::Cdc {
1130 anyhow::bail!(
1131 "export '{}': `tables:` is only valid with `mode: cdc` (batch exports \
1132 are one query/table per export)",
1133 export.name
1134 );
1135 }
1136
1137 if export.chunk_dense && export.mode != ExportMode::Chunked {
1138 anyhow::bail!(
1139 "export '{}': chunk_dense is only valid with mode: chunked",
1140 export.name
1141 );
1142 }
1143
1144 // Round-2 audit #14: the load-bearing chunk knobs are silently dropped
1145 // outside `mode: chunked` — `build_plan` routes Full/Incremental/
1146 // TimeWindow to a single-cursor snapshot that never consults them, so a
1147 // config that sets them but forgets `mode: chunked` degrades to the
1148 // unbounded whole-table snapshot chunking exists to prevent, with no
1149 // error or warn. Gate them the same way chunk_dense/chunk_by_days are.
1150 // (`parallel` is intentionally excluded — the Mongo full/keyset reader
1151 // legitimately fans workers with it, so it is not chunked-only.)
1152 if export.mode != ExportMode::Chunked {
1153 let offending = if export.chunk_column.is_some() {
1154 Some("chunk_column")
1155 } else if export.chunk_by_key.is_some() {
1156 Some("chunk_by_key")
1157 } else if export.chunk_count.is_some() {
1158 Some("chunk_count")
1159 } else if export.chunk_size_memory_mb.is_some() {
1160 Some("chunk_size_memory_mb")
1161 } else if export.chunk_max_attempts.is_some() {
1162 Some("chunk_max_attempts")
1163 } else if export.chunk_checkpoint {
1164 Some("chunk_checkpoint")
1165 } else if export.chunk_size != default_chunk_size() {
1166 Some("chunk_size")
1167 } else {
1168 None
1169 };
1170 if let Some(knob) = offending {
1171 anyhow::bail!(
1172 "export '{}': `{}` requires `mode: chunked` — it is silently ignored in \
1173 `mode: {:?}`, which runs a single unbounded snapshot over the whole table \
1174 instead of chunking (the source-pressure footgun chunked mode prevents).\n \
1175 Hint: add `mode: chunked`, or remove the `{}` setting.",
1176 export.name,
1177 knob,
1178 export.mode,
1179 knob,
1180 );
1181 }
1182 }
1183
1184 if export.cdc.is_some() && export.mode != ExportMode::Cdc {
1185 anyhow::bail!(
1186 "export '{}': a `cdc:` block is only valid with `mode: cdc`",
1187 export.name
1188 );
1189 }
1190
1191 // Table-qualified `columns:` override keys ("table.column"): the named
1192 // table must be one this export captures — a typo must fail at load,
1193 // never silently miss its target. Bare keys stay export-wide.
1194 {
1195 for key in export.columns.keys() {
1196 let Some((tbl, _col)) = key.split_once('.') else {
1197 continue;
1198 };
1199 if export.query.is_some() || export.query_file.is_some() {
1200 anyhow::bail!(
1201 "export '{}': qualified column override '{key}' needs a table-shaped \
1202 export (`table:`/`tables:`), not a query",
1203 export.name
1204 );
1205 }
1206 let bare = |t: &str| t.rsplit('.').next().unwrap_or(t).to_string();
1207 let captures = export
1208 .table
1209 .as_deref()
1210 .map(bare)
1211 .into_iter()
1212 .chain(export.tables.iter().flatten().map(|t| bare(t)))
1213 .any(|t| t == tbl);
1214 if !captures {
1215 anyhow::bail!(
1216 "export '{}': column override '{key}' names table '{tbl}', which this \
1217 export does not capture — fix the table name or use a bare column key \
1218 to apply it to every captured table",
1219 export.name
1220 );
1221 }
1222 }
1223 }
1224
1225 // `initial: snapshot` writes each table's snapshot under the reserved
1226 // sub-prefix `snapshot/` — a table actually NAMED "snapshot" would share
1227 // a prefix with another table's marker. Refuse the collision at load.
1228 if let Some(cdc) = &export.cdc
1229 && cdc.initial == Some(CdcInitialMode::Snapshot)
1230 {
1231 let clashes = |t: &str| t.rsplit('.').next().unwrap_or(t) == "snapshot";
1232 if export.table.as_deref().is_some_and(clashes)
1233 || export.tables.iter().flatten().any(|t| clashes(t))
1234 {
1235 anyhow::bail!(
1236 "export '{}': a table named 'snapshot' collides with the reserved \
1237 `snapshot/` sub-prefix that `cdc.initial: snapshot` writes — rename \
1238 the table or use a separate export without `initial:`",
1239 export.name
1240 );
1241 }
1242 }
1243
1244 // `initial: snapshot` needs a durable anchor BEFORE the snapshot reads.
1245 // PostgreSQL pins server-side (the slot); MySQL / SQL Server have no
1246 // server-side anchor, so the checkpoint file is mandatory there.
1247 if let Some(cdc) = &export.cdc
1248 && cdc.initial == Some(CdcInitialMode::Snapshot)
1249 && self.source.source_type != SourceType::Postgres
1250 && cdc.checkpoint.is_none()
1251 {
1252 anyhow::bail!(
1253 "export '{}': `cdc.initial: snapshot` on {:?} requires `cdc.checkpoint:` — \
1254 the checkpoint file is the anchor that makes snapshot-then-stream gap-free",
1255 export.name,
1256 self.source.source_type
1257 );
1258 }
1259
1260 // MongoDB change streams have NO server-side resume anchor (unlike a
1261 // PostgreSQL slot): the checkpoint file IS the anchor. Without it, every
1262 // run re-anchors at "now" and silently loses every change since the last
1263 // run — so `mode: cdc` on mongo requires `cdc.checkpoint:` ALWAYS, not
1264 // only under `initial: snapshot` (bug-hunt find).
1265 if export.mode == ExportMode::Cdc
1266 && self.source.source_type == SourceType::Mongo
1267 && export
1268 .cdc
1269 .as_ref()
1270 .and_then(|c| c.checkpoint.as_ref())
1271 .is_none()
1272 {
1273 anyhow::bail!(
1274 "export '{}': MongoDB `mode: cdc` requires `cdc.checkpoint:` — a change \
1275 stream has no server-side resume anchor, so without the checkpoint file \
1276 each run re-anchors at the current time and silently loses every change \
1277 between runs.",
1278 export.name
1279 );
1280 }
1281
1282 // A collection whose name contains a dot does not route through the
1283 // change-stream capture — its events are silently dropped. Refuse loudly
1284 // rather than report 0-row success forever (bug-hunt find). Batch handles
1285 // dotted names fine, so this is CDC-only.
1286 if export.mode == ExportMode::Cdc && self.source.source_type == SourceType::Mongo {
1287 let dotted = |t: &str| t.contains('.');
1288 if export.table.as_deref().is_some_and(dotted)
1289 || export.tables.iter().flatten().any(|t| dotted(t))
1290 {
1291 anyhow::bail!(
1292 "export '{}': MongoDB `mode: cdc` does not support a collection name \
1293 containing a dot — the change-stream router cannot address it and its \
1294 events would be silently dropped. Rename the collection, or capture it \
1295 with `mode: full` (batch handles dotted names).",
1296 export.name
1297 );
1298 }
1299 }
1300
1301 if let Some(days) = export.chunk_by_days {
1302 if export.mode != ExportMode::Chunked {
1303 anyhow::bail!(
1304 "export '{}': chunk_by_days requires mode: chunked",
1305 export.name
1306 );
1307 }
1308 if export.chunk_dense {
1309 anyhow::bail!(
1310 "export '{}': chunk_by_days cannot be combined with chunk_dense",
1311 export.name
1312 );
1313 }
1314 if days == 0 {
1315 crate::config_bail!(
1316 crate::error::codes::CONFIG_CHUNK_BY_DAYS_INVALID,
1317 "export '{}': chunk_by_days must be at least 1",
1318 export.name
1319 );
1320 }
1321 }
1322 Ok(())
1323 }
1324}
1325
1326/// True when a single YAML line carries a mapping value (text after `key:`)
1327/// that contains a `{` outside of any quotes — the unquoted-template-brace
1328/// shape (`prefix: {partition}`, `path: {date}/out`).
1329///
1330/// Quote-aware so a properly quoted value (`prefix: "exports/{partition}/"`)
1331/// does *not* match, and `$`-prefixed braces (`${VAR}` env placeholders) are
1332/// ignored — they are resolved before the parse and are not the footgun.
1333fn line_has_unquoted_brace_value(line: &str) -> bool {
1334 // Whole-line comments never carry a value — skip before splitting.
1335 if line.trim_start().starts_with('#') {
1336 return false;
1337 }
1338 // Split key from value at the first `": "` / `":\t"` / trailing `:`.
1339 // A YAML plain-key separator is a colon followed by whitespace or EOL.
1340 let bytes = line.as_bytes();
1341 let mut sep = None;
1342 let mut i = 0;
1343 while i < bytes.len() {
1344 if bytes[i] == b':' && (i + 1 == bytes.len() || bytes[i + 1].is_ascii_whitespace()) {
1345 sep = Some(i + 1);
1346 break;
1347 }
1348 i += 1;
1349 }
1350 let Some(value_start) = sep else {
1351 return false;
1352 };
1353 let value = line[value_start..].trim_start();
1354 // A trailing `#` after the value starts an inline comment; an empty or
1355 // comment-only value carries no brace to flag.
1356 if value.is_empty() || value.starts_with('#') {
1357 return false;
1358 }
1359
1360 let mut in_single = false;
1361 let mut in_double = false;
1362 let vbytes = value.as_bytes();
1363 for (j, &c) in vbytes.iter().enumerate() {
1364 match c {
1365 b'\'' if !in_double => in_single = !in_single,
1366 b'"' if !in_single => in_double = !in_double,
1367 b'{' if !in_single && !in_double => {
1368 // Ignore `${...}` env placeholders (resolved pre-parse).
1369 if j > 0 && vbytes[j - 1] == b'$' {
1370 continue;
1371 }
1372 return true;
1373 }
1374 _ => {}
1375 }
1376 }
1377 false
1378}
1379
1380/// Extract the lower-cased host from a `scheme://host[:port][/path]` endpoint,
1381/// or `None` when it does not look like a URL.
1382///
1383/// SecOps helper for the cloud-`endpoint` exfiltration guard (V2/V12): the host
1384/// decides whether a custom endpoint is a local emulator (loopback) or a remote
1385/// redirect target. We reject every non-loopback custom endpoint regardless of
1386/// scheme (covering both the exfil and the cleartext-`http` gaps), so only the
1387/// host is needed. We hand-parse rather than pull in a URL crate — the inputs
1388/// are operator-typed endpoints, not arbitrary URIs. A bracketed IPv6 literal
1389/// authority (`http://[::1]:9000`) keeps its address so it compares against the
1390/// loopback list.
1391fn endpoint_host(endpoint: &str) -> Option<String> {
1392 let (scheme, rest) = endpoint.split_once("://")?;
1393 if scheme.is_empty() {
1394 return None;
1395 }
1396 // Authority ends at the first `/` (path), `?` (query), or `#` (fragment);
1397 // any `user[:pass]@` userinfo head is dropped (host is after the last `@`).
1398 let authority = rest
1399 .split(['/', '?', '#'])
1400 .next()
1401 .unwrap_or("")
1402 .rsplit('@')
1403 .next()
1404 .unwrap_or("");
1405 let host = if let Some(stripped) = authority.strip_prefix('[') {
1406 // Bracketed IPv6 literal: take up to the closing `]`.
1407 stripped.split(']').next().unwrap_or("")
1408 } else {
1409 // host[:port] — strip the port suffix.
1410 authority.split(':').next().unwrap_or("")
1411 };
1412 if host.is_empty() {
1413 return None;
1414 }
1415 Some(host.to_ascii_lowercase())
1416}
1417
1418/// True when `host` names the local machine — the legitimate cloud-emulator
1419/// target (Minio / Azurite / fake-gcs on `127.0.0.1`). Anything else is a
1420/// remote host and a potential exfiltration redirect.
1421fn is_loopback_host(host: &str) -> bool {
1422 // `localhost` is the only non-IP host that counts as loopback. Everything
1423 // else must PARSE as an IP literal in the loopback range — a lexical
1424 // `starts_with("127.")` would accept attacker-controlled DNS like
1425 // `127.attacker.com` or `127.0.0.1.evil.com` (both resolve off-box), turning
1426 // the credential-exfil gate into a bypass (V2/V12). Parse strictly: only a
1427 // real `127.0.0.0/8` / `::1` address is loopback; a hostname is not.
1428 if host == "localhost" {
1429 return true;
1430 }
1431 // Tolerate a bracketed IPv6 literal (`[::1]`) in case a caller forwards one.
1432 let h = host
1433 .strip_prefix('[')
1434 .and_then(|s| s.strip_suffix(']'))
1435 .unwrap_or(host);
1436 h.parse::<std::net::IpAddr>()
1437 .is_ok_and(|ip| ip.is_loopback())
1438}
1439
1440/// True when `name` is filename-safe: rejects path-traversal (`..`), absolute
1441/// or slash-bearing names (`/`, `\`), a leading `.` (hidden / current-dir), and
1442/// embedded NULs. `ExportConfig.name` is keyed into output paths and on-disk
1443/// state, so a `../../etc/x` or absolute name escapes the output tree (V5).
1444fn is_filename_safe_name(name: &str) -> bool {
1445 !name.is_empty()
1446 && !name.starts_with('.')
1447 && !name.contains('/')
1448 && !name.contains('\\')
1449 && !name.contains("..")
1450 && !name.contains('\0')
1451}
1452
1453#[cfg(test)]
1454mod tests;
1455
1456#[cfg(test)]
1457mod audit_csv_compression {
1458 //! Finding #10: `format: csv` + a compression codec is a silent no-op
1459 //! (the file stays uncompressed but the manifest records the codec). The
1460 //! combo must be rejected at config-validate time. These tests encode the
1461 //! new rule, so reverting the fix turns them red.
1462 use super::*;
1463
1464 fn yaml(format: &str, compression_line: &str) -> String {
1465 format!(
1466 "source:\n type: postgres\n url: \"postgresql://localhost/test\"\n\
1467 exports:\n - name: t\n query: \"SELECT 1\"\n format: {format}\n\
1468 {compression_line} destination:\n type: local\n path: ./out\n"
1469 )
1470 }
1471
1472 #[test]
1473 fn audit_csv_compression_is_rejected() {
1474 // csv + gzip → rejected, with an actionable message.
1475 let err = Config::from_yaml(&yaml("csv", " compression: gzip\n")).unwrap_err();
1476 let msg = format!("{err:#}");
1477 assert!(
1478 msg.contains("CSV output does not support compression") && msg.contains("gzip"),
1479 "csv+gzip must be rejected with an actionable message; got: {msg}"
1480 );
1481 assert!(
1482 msg.contains("parquet") && msg.contains("none"),
1483 "message must point to the real options (parquet / none); got: {msg}"
1484 );
1485
1486 // Guard the boundaries: parquet+gzip and csv+none still validate.
1487 Config::from_yaml(&yaml("parquet", " compression: gzip\n"))
1488 .expect("parquet+gzip must validate");
1489 Config::from_yaml(&yaml("csv", " compression: none\n")).expect("csv+none must validate");
1490 }
1491
1492 #[test]
1493 fn audit_csv_every_real_codec_is_rejected() {
1494 // Each non-None codec is a silent no-op for CSV — none may slip through.
1495 for codec in ["zstd", "snappy", "gzip", "lz4"] {
1496 let err = Config::from_yaml(&yaml("csv", &format!(" compression: {codec}\n")))
1497 .unwrap_err();
1498 let msg = format!("{err:#}");
1499 assert!(
1500 msg.contains("CSV output does not support compression") && msg.contains(codec),
1501 "csv+{codec} must be rejected; got: {msg}"
1502 );
1503 }
1504 }
1505
1506 #[test]
1507 fn audit_csv_compression_profile_is_rejected() {
1508 // A `compression_profile:` other than `none` resolves to a real codec,
1509 // so it is the same silent no-op for CSV.
1510 for profile in ["fast", "balanced", "compact"] {
1511 let err = Config::from_yaml(&yaml(
1512 "csv",
1513 &format!(" compression_profile: {profile}\n"),
1514 ))
1515 .unwrap_err();
1516 let msg = format!("{err:#}");
1517 assert!(
1518 msg.contains("CSV output does not support compression_profile")
1519 && msg.contains(profile),
1520 "csv+profile {profile} must be rejected; got: {msg}"
1521 );
1522 }
1523 // profile: none is a no-op request and is fine.
1524 Config::from_yaml(&yaml("csv", " compression_profile: none\n"))
1525 .expect("csv + compression_profile: none must validate");
1526 }
1527
1528 #[test]
1529 fn audit_csv_default_compression_still_validates() {
1530 // Regression guard: a bare `format: csv` (no explicit codec) must keep
1531 // validating. `CompressionType::default()` is `Zstd`, but the user did
1532 // not *ask* for it — only an explicit codec is a no-op request. This
1533 // pins that the fix scans for explicit intent, not the struct default
1534 // (which would break ~60 existing csv configs).
1535 Config::from_yaml(&yaml("csv", "")).expect("bare format: csv must validate");
1536 }
1537
1538 #[test]
1539 fn audit_compression_supported_predicate() {
1540 // `compression_supported` is re-exported via `pub use format::*`.
1541 // Parquet supports every codec; CSV supports only None.
1542 for ct in [
1543 CompressionType::Zstd,
1544 CompressionType::Snappy,
1545 CompressionType::Gzip,
1546 CompressionType::Lz4,
1547 CompressionType::None,
1548 ] {
1549 assert!(compression_supported(FormatType::Parquet, ct));
1550 }
1551 assert!(compression_supported(
1552 FormatType::Csv,
1553 CompressionType::None
1554 ));
1555 for ct in [
1556 CompressionType::Zstd,
1557 CompressionType::Snappy,
1558 CompressionType::Gzip,
1559 CompressionType::Lz4,
1560 ] {
1561 assert!(
1562 !compression_supported(FormatType::Csv, ct),
1563 "CSV must not claim to support {}",
1564 ct.label()
1565 );
1566 }
1567 }
1568}
1569
1570#[cfg(test)]
1571mod reserved_load_extension {
1572 //! A downstream first-party loader carries its warehouse target in a
1573 //! top-level `load:` block so ONE config drives export + load. OSS must
1574 //! accept and ignore it — otherwise `check`/`run`/`apply` would reject the
1575 //! single-file config. Reverting the reserved field turns this red.
1576 use super::*;
1577
1578 #[test]
1579 fn reserved_top_level_load_block_is_accepted_and_ignored() {
1580 let yaml = "source:\n type: postgres\n url: \"postgresql://localhost/test\"\n\
1581 exports:\n - name: t\n query: \"SELECT 1\"\n format: parquet\n destination:\n type: gcs\n bucket: b\n prefix: \"t/\"\n\
1582 load:\n project: p\n dataset: d\n cleanup_source: true\n";
1583 let cfg = Config::from_yaml(yaml).expect("config with a reserved `load:` block must parse");
1584 assert!(cfg.load.is_some(), "the load block is captured opaquely");
1585 }
1586}
1587
1588#[cfg(test)]
1589mod audit_unquoted_template_brace {
1590 //! yaml-hint: an unquoted `{partition}` (or `{date}`) in a path/prefix
1591 //! value trips serde_yaml_ng's flow-mapping parser with a cryptic message
1592 //! that gives no clue the brace needs quoting. Since `{partition}` is the
1593 //! required token for `partition_by`, this is a common copy-paste footgun.
1594 //! `Config::from_yaml` augments the parser error with a quoting hint; these
1595 //! tests pin that behavior (and guard that valid configs are untouched).
1596 use super::*;
1597
1598 /// A full, otherwise-valid config whose `prefix:` value is whatever the
1599 /// caller passes verbatim (quoted or not). Only the `prefix:` line varies,
1600 /// so any parse error is attributable to the brace under test.
1601 fn yaml_with_prefix(prefix_value: &str) -> String {
1602 format!(
1603 "source:\n\
1604 \x20 type: postgres\n\
1605 \x20 url: \"postgresql://localhost/test\"\n\
1606 exports:\n\
1607 \x20 - name: t\n\
1608 \x20 query: \"SELECT 1\"\n\
1609 \x20 format: parquet\n\
1610 \x20 partition_by: created_date\n\
1611 \x20 destination:\n\
1612 \x20 type: local\n\
1613 \x20 path: ./out\n\
1614 \x20 prefix: {prefix_value}\n"
1615 )
1616 }
1617
1618 const HINT_FRAGMENT: &str =
1619 "a YAML value containing { } (such as {partition} or {date}) must be quoted";
1620
1621 #[test]
1622 fn bare_partition_token_gets_quoting_hint() {
1623 // `prefix: {partition}` parses as a YAML map, so serde rejects it with
1624 // `invalid type: map, expected a string` — no clue it's a quoting bug.
1625 let err = Config::from_yaml(&yaml_with_prefix("{partition}")).unwrap_err();
1626 let msg = format!("{err:#}");
1627 assert!(
1628 msg.contains(HINT_FRAGMENT),
1629 "bare {{partition}} must carry the quoting hint; got: {msg}"
1630 );
1631 // The original parser detail (type + location) is preserved.
1632 assert!(
1633 msg.contains("invalid type: map") || msg.contains("line"),
1634 "the original parser error must be kept; got: {msg}"
1635 );
1636 }
1637
1638 #[test]
1639 fn trailing_text_after_brace_gets_quoting_hint() {
1640 // `prefix: {date}/{partition}/` runs the flow map into block context:
1641 // serde emits `did not find expected key ... while parsing a block
1642 // mapping`. Same footgun, different libyaml symptom.
1643 let err = Config::from_yaml(&yaml_with_prefix("{date}/{partition}/")).unwrap_err();
1644 let msg = format!("{err:#}");
1645 assert!(
1646 msg.contains(HINT_FRAGMENT),
1647 "{{date}}/{{partition}}/ must carry the quoting hint; got: {msg}"
1648 );
1649 }
1650
1651 #[test]
1652 fn unclosed_brace_gets_quoting_hint() {
1653 // `prefix: {partition` (unclosed) is the canonical flow-mapping scanner
1654 // error: `did not find expected ',' or '}' ... while parsing a flow
1655 // mapping`. The hint must still fire.
1656 let err = Config::from_yaml(&yaml_with_prefix("{partition")).unwrap_err();
1657 let msg = format!("{err:#}");
1658 assert!(
1659 msg.contains(HINT_FRAGMENT),
1660 "unclosed brace must carry the quoting hint; got: {msg}"
1661 );
1662 }
1663
1664 #[test]
1665 fn quoted_brace_value_loads_ok() {
1666 // The fix itself, applied: a properly quoted brace value parses and
1667 // validates. This is the guard that the hint never reaches a valid
1668 // config and the success path is unchanged.
1669 let cfg = Config::from_yaml(&yaml_with_prefix("\"exports/{partition}/\""))
1670 .expect("quoted {partition} prefix must load");
1671 assert_eq!(
1672 cfg.exports[0].destination.prefix.as_deref(),
1673 Some("exports/{partition}/")
1674 );
1675 }
1676
1677 #[test]
1678 fn config_without_braces_is_untouched() {
1679 // No brace anywhere: a plain valid config still loads, and an unrelated
1680 // YAML error elsewhere must not pick up a spurious quoting hint. (No
1681 // partition_by here — a braceless prefix is invalid WITH partition_by,
1682 // which requires a `{partition}` token; this test is about brace
1683 // detection, not partitioning.)
1684 let yaml = "source:\n type: postgres\n url: \"postgresql://localhost/test\"\n\
1685 exports:\n - name: t\n query: \"SELECT 1\"\n format: parquet\n\
1686 \x20 destination:\n type: local\n path: ./out\n prefix: exports/data/\n";
1687 Config::from_yaml(yaml).expect("a brace-free prefix must load");
1688 }
1689
1690 // ── line_has_unquoted_brace_value() unit coverage ──────────────────────
1691
1692 #[test]
1693 fn unquoted_brace_value_is_detected() {
1694 assert!(line_has_unquoted_brace_value(" prefix: {partition}"));
1695 assert!(line_has_unquoted_brace_value(" path: {date}/out"));
1696 assert!(line_has_unquoted_brace_value("prefix: {partition")); // unclosed
1697 }
1698
1699 #[test]
1700 fn quoted_brace_value_is_not_flagged() {
1701 // Quotes around the value hide the brace from the scanner — not a bug.
1702 assert!(!line_has_unquoted_brace_value(
1703 " prefix: \"exports/{partition}/\""
1704 ));
1705 assert!(!line_has_unquoted_brace_value(" prefix: 'data/{date}/'"));
1706 }
1707
1708 #[test]
1709 fn env_placeholder_and_plain_values_are_not_flagged() {
1710 // `${VAR}` placeholders are resolved before the parse and are not the
1711 // footgun; plain brace-free values are obviously fine.
1712 assert!(!line_has_unquoted_brace_value(" url: ${DATABASE_URL}"));
1713 assert!(!line_has_unquoted_brace_value(" path: ./out"));
1714 assert!(!line_has_unquoted_brace_value(" # prefix: {partition}")); // comment
1715 assert!(!line_has_unquoted_brace_value(" prefix:")); // no value
1716 }
1717}
1718
1719#[cfg(test)]
1720mod sec_config_validation_regression {
1721 //! Regression edge-cases that pin the *compat boundaries* of the
1722 //! config-validation security fixes — the cases that distinguish a real
1723 //! attack from a legitimate loopback / dev-container / Docker pattern.
1724 //! These complement the RED tests in `sec_config_validation`: the RED
1725 //! tests assert the attack is rejected; these assert the fix stays narrow
1726 //! enough not to break local-dev usage (see CRITICAL COMPAT).
1727 use super::*;
1728
1729 /// A full, otherwise-valid config whose single export's `destination:`
1730 /// block is whatever the caller passes verbatim.
1731 fn yaml_with_destination(dest_block: &str) -> String {
1732 format!(
1733 "source:\n type: postgres\n url: \"postgresql://localhost/test\"\n\
1734 exports:\n - name: t\n query: \"SELECT 1\"\n format: parquet\n\
1735 {dest_block}"
1736 )
1737 }
1738
1739 // ── endpoint_host / is_loopback_host helpers ─────────────────────────────
1740
1741 #[test]
1742 fn endpoint_host_parses_forms() {
1743 assert_eq!(
1744 endpoint_host("https://attacker.example.com").as_deref(),
1745 Some("attacker.example.com")
1746 );
1747 // Port and path are stripped from the host.
1748 assert_eq!(
1749 endpoint_host("http://127.0.0.1:10000/devstoreaccount1").as_deref(),
1750 Some("127.0.0.1")
1751 );
1752 // userinfo head is dropped (host is after the last `@`).
1753 assert_eq!(
1754 endpoint_host("http://user:pass@127.0.0.1:9000").as_deref(),
1755 Some("127.0.0.1")
1756 );
1757 // Bracketed IPv6 literal keeps its address.
1758 assert_eq!(endpoint_host("http://[::1]:9000").as_deref(), Some("::1"));
1759 // Not a URL → None (treated as a non-loopback custom endpoint upstream).
1760 assert_eq!(endpoint_host("not-a-url"), None);
1761 assert_eq!(endpoint_host("://nohost"), None);
1762 }
1763
1764 #[test]
1765 fn loopback_host_classification() {
1766 for h in ["127.0.0.1", "127.0.0.53", "localhost", "::1"] {
1767 assert!(is_loopback_host(h), "{h} must be loopback");
1768 }
1769 for h in ["attacker.example.com", "evil.com", "10.0.0.1", "::2"] {
1770 assert!(!is_loopback_host(h), "{h} must be remote");
1771 }
1772 }
1773
1774 // ── V2/V12 endpoint: loopback accepted regardless of allow_anonymous ─────
1775
1776 #[test]
1777 fn loopback_endpoint_without_allow_anonymous_still_accepted() {
1778 // A loopback emulator endpoint with credentials (no allow_anonymous) is
1779 // the Minio-with-keys local-dev pattern and must stay accepted — the
1780 // exfil guard targets *remote* hosts, not localhost.
1781 let cfg = yaml_with_destination(
1782 " destination:\n type: s3\n bucket: b\n region: us-east-1\n\
1783 \x20 endpoint: http://127.0.0.1:9000\n access_key_env: AK\n secret_key_env: SK\n",
1784 );
1785 Config::from_yaml(&cfg).expect("loopback endpoint with creds must stay accepted");
1786 }
1787
1788 #[test]
1789 fn remote_https_endpoint_with_allow_anonymous_is_the_only_remote_escape() {
1790 // The documented escape hatch: an explicit anonymous (emulator) opt-in
1791 // permits a non-loopback endpoint (no credentials are sent). Without
1792 // allow_anonymous the same endpoint is rejected (covered by the RED
1793 // test); with it, accepted.
1794 let cfg = yaml_with_destination(
1795 " destination:\n type: gcs\n bucket: b\n\
1796 \x20 endpoint: https://emulator.example.com\n allow_anonymous: true\n",
1797 );
1798 Config::from_yaml(&cfg).expect("remote endpoint + allow_anonymous opt-in must be accepted");
1799 }
1800
1801 // ── V15 local path: absolute allowed (Docker mount), `..` rejected ───────
1802
1803 #[test]
1804 fn absolute_local_path_is_allowed() {
1805 // `path: /output` is a legitimate Docker volume-mount pattern
1806 // (examples/rivet.yaml) and must keep validating — only `..` climbs are
1807 // the traversal footgun.
1808 let cfg =
1809 yaml_with_destination(" destination:\n type: local\n path: /output\n");
1810 Config::from_yaml(&cfg).expect("absolute local path (Docker mount) must validate");
1811 }
1812
1813 #[test]
1814 fn dotdot_in_local_prefix_is_rejected() {
1815 // `prefix` is guarded the same as `path`.
1816 let cfg = yaml_with_destination(
1817 " destination:\n type: local\n path: ./out\n prefix: a/../b\n",
1818 );
1819 let err = Config::from_yaml(&cfg).unwrap_err();
1820 let msg = format!("{err:#}");
1821 assert!(
1822 msg.contains("prefix") && msg.contains(".."),
1823 "a '..' in the local prefix must be rejected naming prefix/..; got: {msg}"
1824 );
1825 }
1826
1827 // ── V13 TLS: explicit enforced mode + knob rejected; default-mode kept ───
1828
1829 #[test]
1830 fn tls_danger_knob_without_explicit_mode_still_accepted() {
1831 // The dev-container pattern `tls: { accept_invalid_certs: true }` against
1832 // a loopback self-signed cert (e.g. the MSSQL docker container) omits
1833 // `mode:` — there is no *explicit* mode to contradict, so it must keep
1834 // validating. The RED test rejects only the explicit-mode contradiction.
1835 let yaml = "source:\n type: mssql\n url: \"sqlserver://sa:pw@127.0.0.1:1433/db\"\n \
1836 tls:\n accept_invalid_certs: true\n\
1837 exports:\n - name: t\n query: \"SELECT 1\"\n format: parquet\n \
1838 destination:\n type: local\n path: ./out\n";
1839 Config::from_yaml(yaml)
1840 .expect("dev-container default-mode + accept_invalid_certs must stay accepted");
1841 }
1842
1843 #[test]
1844 fn tls_explicit_verify_ca_plus_invalid_hostnames_rejected() {
1845 // The hostname knob is flagged too, against any explicit enforced mode.
1846 let yaml = "source:\n type: postgres\n url: \"postgresql://localhost/test\"\n \
1847 tls:\n mode: verify-ca\n accept_invalid_hostnames: true\n\
1848 exports:\n - name: t\n query: \"SELECT 1\"\n format: parquet\n \
1849 destination:\n type: local\n path: ./out\n";
1850 let err = Config::from_yaml(yaml).unwrap_err();
1851 let msg = format!("{err:#}");
1852 assert!(
1853 msg.contains("accept_invalid_hostnames") && msg.contains("verify-ca"),
1854 "explicit verify-ca + accept_invalid_hostnames must be rejected; got: {msg}"
1855 );
1856 }
1857
1858 #[test]
1859 fn tls_explicit_disable_with_knob_is_not_flagged() {
1860 // `mode: disable` carries no verification promise to contradict, so the
1861 // danger knob is a no-op there and must not be rejected.
1862 let yaml = "source:\n type: postgres\n url: \"postgresql://localhost/test\"\n \
1863 tls:\n mode: disable\n accept_invalid_certs: true\n\
1864 exports:\n - name: t\n query: \"SELECT 1\"\n format: parquet\n \
1865 destination:\n type: local\n path: ./out\n";
1866 Config::from_yaml(yaml).expect("mode: disable + knob is a no-op and must validate");
1867 }
1868
1869 // ── V5 name: filename-safe predicate boundaries ──────────────────────────
1870
1871 #[test]
1872 fn filename_safe_name_boundaries() {
1873 for ok in ["t", "orders", "daily_events", "v2-2024", "name.with.dots"] {
1874 assert!(is_filename_safe_name(ok), "{ok:?} must be accepted");
1875 }
1876 for bad in [
1877 "",
1878 "..",
1879 "../x",
1880 "/abs",
1881 "sub/dir",
1882 "back\\slash",
1883 ".hidden",
1884 "with\u{0000}nul",
1885 ] {
1886 assert!(!is_filename_safe_name(bad), "{bad:?} must be rejected");
1887 }
1888 }
1889}
1890
1891#[cfg(test)]
1892mod sec_config_validation {
1893 //! RED security tests for config-load validation gaps (cluster:
1894 //! config-validation). Each asserts the SECURE behavior through the
1895 //! stable `Config::from_yaml` seam: a malicious config that is accepted
1896 //! today must be REJECTED (or, for warn-only knobs, surfaced as an
1897 //! error/loud warning) at config-load. These are expected to FAIL until
1898 //! the corresponding production fix lands.
1899 //!
1900 //! The pattern mirrors the existing `query_file` `..`/absolute-path guard
1901 //! in `validate_export` (see `config/tests/validation.rs`): a syntactic
1902 //! check that runs at config-validate time so `rivet check` / `rivet
1903 //! doctor` catch the problem before any connect/plan/upload step.
1904 use super::*;
1905
1906 /// A full, otherwise-valid config whose single export's `destination:`
1907 /// block is whatever the caller passes verbatim. Only the destination
1908 /// varies, so any rejection is attributable to the destination under test.
1909 fn yaml_with_destination(dest_block: &str) -> String {
1910 format!(
1911 "source:\n type: postgres\n url: \"postgresql://localhost/test\"\n\
1912 exports:\n - name: t\n query: \"SELECT 1\"\n format: parquet\n\
1913 {dest_block}"
1914 )
1915 }
1916
1917 // ── V2/V12: cloud-endpoint exfiltration + http cleartext ────────────────
1918 //
1919 // `destination.endpoint` is passed straight to the opendal S3/GCS/Azure
1920 // builder with no validation (see `src/destination/{s3,gcs,azure}.rs`),
1921 // so a committed config can silently redirect every export to an
1922 // attacker-controlled host. Two distinct gaps:
1923 // V2 — a custom *non-loopback* endpoint (data exfiltration target).
1924 // V12 — an `http://` (plaintext) endpoint (credentials + data on the
1925 // wire in cleartext).
1926 // The secure behavior is to reject (or require explicit opt-in) at
1927 // config-load. Loopback/emulator endpoints (Minio/Azurite/fake-gcs on
1928 // 127.0.0.1) MUST stay accepted — that path is exercised by the existing
1929 // `gcs_allow_anonymous_parses` test and the guard test below.
1930
1931 #[test]
1932 fn sec_s3_custom_endpoint_rejected() {
1933 // SEC-RED V2: a non-loopback custom S3 endpoint is an exfiltration
1934 // target — every part upload goes to attacker.example.com. Must be
1935 // rejected (or require explicit opt-in) at config-load. Accepted today.
1936 let cfg = yaml_with_destination(
1937 " destination:\n type: s3\n bucket: my-bucket\n region: us-east-1\n\
1938 \x20 endpoint: https://attacker.example.com\n",
1939 );
1940 let res = Config::from_yaml(&cfg);
1941 assert!(
1942 res.is_err(),
1943 "a non-loopback custom S3 endpoint (https://attacker.example.com) must be \
1944 rejected at config-load (data-exfiltration target); got Ok"
1945 );
1946 let msg = format!("{:#}", res.unwrap_err());
1947 assert!(
1948 msg.contains("endpoint"),
1949 "rejection must name the offending 'endpoint' field; got: {msg}"
1950 );
1951 }
1952
1953 #[test]
1954 fn sec_http_endpoint_rejected() {
1955 // SEC-RED V12: a plaintext http:// endpoint to a *remote* host sends
1956 // credentials and exported rows over the wire in cleartext. Must be
1957 // rejected (or require explicit opt-in) at config-load. Accepted today.
1958 // Use a non-loopback host so this is distinct from the Minio/Azurite
1959 // loopback emulator case (guarded below).
1960 let cfg = yaml_with_destination(
1961 " destination:\n type: s3\n bucket: my-bucket\n region: us-east-1\n\
1962 \x20 endpoint: http://evil.com\n",
1963 );
1964 let res = Config::from_yaml(&cfg);
1965 assert!(
1966 res.is_err(),
1967 "a plaintext http:// endpoint to a remote host (http://evil.com) must be \
1968 rejected at config-load (cleartext credentials + data); got Ok"
1969 );
1970 let msg = format!("{:#}", res.unwrap_err());
1971 assert!(
1972 msg.contains("endpoint") || msg.to_lowercase().contains("http"),
1973 "rejection must name the endpoint / cleartext problem; got: {msg}"
1974 );
1975 }
1976
1977 #[test]
1978 fn sec_loopback_endpoint_still_accepted_guard() {
1979 // SEC-RED V2/V12 (guard): a loopback emulator endpoint
1980 // (`http://127.0.0.1:9000` Minio, with allow_anonymous) is the
1981 // legitimate local-dev path and MUST stay accepted after the fix.
1982 // This pins that the endpoint rejection targets *remote* hosts, not
1983 // localhost — otherwise the fix breaks every Minio/Azurite/fake-gcs
1984 // integration test (see `gcs_allow_anonymous_parses`).
1985 let cfg = yaml_with_destination(
1986 " destination:\n type: s3\n bucket: my-bucket\n region: us-east-1\n\
1987 \x20 endpoint: http://127.0.0.1:9000\n allow_anonymous: true\n",
1988 );
1989 Config::from_yaml(&cfg)
1990 .expect("a loopback emulator endpoint with allow_anonymous must stay accepted");
1991 }
1992
1993 // ── V5: export `name` path traversal ────────────────────────────────────
1994 //
1995 // `ExportConfig.name` is a free-form `String` keyed into state tracking,
1996 // file logs, and (via the destination layout) output paths — yet it is
1997 // never validated. A name like `../../../etc/x`, an absolute `/abs/x`, a
1998 // bare slash, or an embedded NUL can escape the intended output tree.
1999 // Mirror the `query_file` `..`/absolute guard: reject at config-load.
2000
2001 #[test]
2002 fn sec_export_name_traversal_rejected() {
2003 // SEC-RED V5: a traversal / absolute / slash / NUL export name escapes
2004 // the output tree (and corrupts name-keyed state). Must be rejected at
2005 // config-load. Accepted today.
2006 for bad in ["../../../etc/x", "/abs/x", "sub/dir", "with\u{0000}nul"] {
2007 // `name:` is JSON-encoded so embedded slashes / NULs survive the
2008 // YAML parse verbatim and reach validation.
2009 let name_yaml = serde_json::to_string(bad).expect("encode name");
2010 let cfg = format!(
2011 "source:\n type: postgres\n url: \"postgresql://localhost/test\"\n\
2012 exports:\n - name: {name_yaml}\n query: \"SELECT 1\"\n format: parquet\n\
2013 \x20 destination:\n type: local\n path: ./out\n"
2014 );
2015 let res = Config::from_yaml(&cfg);
2016 assert!(
2017 res.is_err(),
2018 "export name {bad:?} (traversal/absolute/slash/NUL) must be rejected at \
2019 config-load; got Ok"
2020 );
2021 let msg = format!("{:#}", res.unwrap_err());
2022 assert!(
2023 msg.contains("name"),
2024 "rejection of name {bad:?} must name the offending 'name' field; got: {msg}"
2025 );
2026 }
2027 }
2028
2029 #[test]
2030 fn sec_export_name_normal_still_accepted_guard() {
2031 // SEC-RED V5 (guard): a plain, well-formed export name must keep
2032 // loading after the fix. Pins that the traversal check is narrow.
2033 let cfg = yaml_with_destination(" destination:\n type: local\n path: ./out\n");
2034 Config::from_yaml(&cfg).expect("a normal export name ('t') must stay accepted");
2035 }
2036
2037 // ── V15: local destination `path` traversal ─────────────────────────────
2038 //
2039 // `destination.path` for a `type: local` export is written verbatim to the
2040 // filesystem. A relative `../../../../tmp/x` or absolute path lets a
2041 // committed config write outside the intended output directory. Must be
2042 // rejected (or at minimum loudly surfaced) at config-load. Accepted today.
2043
2044 #[test]
2045 fn sec_local_dest_path_traversal_rejected() {
2046 // SEC-RED V15: a traversal local-destination path writes outside the
2047 // intended output tree. Must be rejected at config-load. Accepted today.
2048 let cfg = yaml_with_destination(
2049 " destination:\n type: local\n path: ../../../../tmp/x\n",
2050 );
2051 let res = Config::from_yaml(&cfg);
2052 assert!(
2053 res.is_err(),
2054 "a local destination path containing '..' (../../../../tmp/x) must be rejected \
2055 at config-load (writes outside the output tree); got Ok"
2056 );
2057 let msg = format!("{:#}", res.unwrap_err());
2058 assert!(
2059 msg.contains("path") || msg.contains(".."),
2060 "rejection must name the offending 'path' / traversal; got: {msg}"
2061 );
2062 }
2063
2064 // ── V13: dangerous TLS cert-knob combination ─────────────────────────────
2065 //
2066 // `tls: { mode: verify-full, accept_invalid_certs: true }` silently
2067 // *downgrades* the strongest mode to "accept any cert" — `verify-full`
2068 // promises chain + hostname verification, but the danger knob disables
2069 // chain verification (see `src/source/tls.rs::build_native_tls`). The
2070 // comment at `src/source/tls.rs:55-56` claims "Each one emits a warning at
2071 // config-time (see `Config::validate`)" — but `Config::validate` emits no
2072 // such warning today. The secure behavior is a LOUD error (or surfaced
2073 // warning) at config-load. No `Err`/warning is produced today, so this is
2074 // RED.
2075
2076 #[test]
2077 fn sec_accept_invalid_certs_warns() {
2078 // SEC-RED V13: verify-full + accept_invalid_certs: true is a silent
2079 // security downgrade that contradicts the chosen mode. It must be
2080 // loudly surfaced at config-load. The only stable secure seam is an
2081 // `Err` from `Config::from_yaml` (validate returns Ok today, and there
2082 // is no captured-warning seam exposed from here — see notes). Asserting
2083 // `Err` is the strongest secure assertion and is RED against current
2084 // code.
2085 let cfg = yaml_with_destination(" destination:\n type: local\n path: ./out\n");
2086 // Splice the TLS block into the source rather than the destination so
2087 // the rest of the config stays valid.
2088 let cfg = cfg.replace(
2089 " url: \"postgresql://localhost/test\"\n",
2090 " url: \"postgresql://localhost/test\"\n tls:\n mode: verify-full\n accept_invalid_certs: true\n",
2091 );
2092 let res = Config::from_yaml(&cfg);
2093 assert!(
2094 res.is_err(),
2095 "tls mode: verify-full with accept_invalid_certs: true is a silent security \
2096 downgrade and must be loudly surfaced (error) at config-load; got Ok"
2097 );
2098 let msg = format!("{:#}", res.unwrap_err());
2099 assert!(
2100 msg.contains("accept_invalid_certs") || msg.to_lowercase().contains("verify"),
2101 "the surfaced error must name the dangerous knob / mode contradiction; got: {msg}"
2102 );
2103 }
2104}