Skip to main content

camel_core/
startup_validation.rs

1//! ADR-0033 startup-validation phase.
2//!
3//! `ConfigCheck` impls are registered for Require-Explicit-Choice security
4//! defaults. The fail-closed `run_startup_validation()` walks the registry
5//! and returns `Err(CamelError::Config)` if any check fails. See ADR-0033 in
6//! `docs/adr/0033-…`.
7
8use crate::lifecycle::application::route_definition::{BuilderStep, RouteDefinition};
9use camel_api::{CamelError, ConfigValidationError};
10use camel_endpoint::uri::parse_bool_param;
11
12/// A single startup-time configuration check.
13///
14/// Each `ConfigCheck` is run as part of the fail-closed startup-validation phase
15/// established by ADR-0033. The check owns a name (for error reporting), a human
16/// description, and a synchronous `run` that returns `Ok(())` if the check passes
17/// or `Err(CamelError::Config)` if the check fails and the operator config is
18/// invalid.
19pub trait ConfigCheck: Send + Sync {
20    /// Stable identifier for this check (e.g. `"grpc-tls"`, `"sql-dynamic-query"`).
21    /// Used in error messages and `camel doctor` output.
22    fn name(&self) -> &'static str;
23
24    /// One-line human description of what this check enforces.
25    fn description(&self) -> &'static str;
26
27    /// Run the check. Returns `Err(CamelError::Config(_))` to fail-closed.
28    fn run(&self) -> Result<(), CamelError>;
29}
30
31/// Aggregated result of running every registered `ConfigCheck`.
32///
33/// Batch 1 ships the type so later batches can populate `failures`. Skeleton
34/// phase always produces a `StartupValidationReport { failures: vec![] }`.
35#[derive(Debug, Default, Clone)]
36pub struct StartupValidationReport {
37    /// Names of every `ConfigCheck` that returned `Err`, in registration order.
38    pub failures: Vec<String>,
39}
40
41impl StartupValidationReport {
42    /// True when no check failed. Caller MUST refuse to start the runtime when
43    /// this is `false`.
44    pub fn is_ok(&self) -> bool {
45        self.failures.is_empty()
46    }
47}
48
49/// Entry point for the startup-validation phase.
50///
51/// Walks the supplied `ConfigCheck` registry, collects failures, and fails closed
52/// when any check returns `Err`. Established by ADR-0033.
53pub fn run_startup_validation(
54    checks: Vec<Box<dyn ConfigCheck>>,
55) -> Result<StartupValidationReport, CamelError> {
56    let mut report = StartupValidationReport::default();
57    for check in &checks {
58        if let Err(e) = check.run() {
59            report.failures.push(format!("{}: {}", check.name(), e));
60        }
61    }
62    if !report.is_ok() {
63        return Err(CamelError::Config(report.failures.join("; ")));
64    }
65    Ok(report)
66}
67
68/// ConfigCheck: SQL dynamic-query intent must match capability (H7).
69///
70/// If `use_message_body_for_sql=true` but `allow_dynamic_query=false`,
71/// the operator intent (use body as query) is blocked by the capability
72/// gate — this is a misconfiguration that would silently produce empty
73/// queries. Fail closed at startup instead.
74pub struct SqlDynamicQueryCheck {
75    pub use_message_body_for_sql: bool,
76    pub allow_dynamic_query: bool,
77}
78
79impl ConfigCheck for SqlDynamicQueryCheck {
80    fn name(&self) -> &'static str {
81        "sql-dynamic-query"
82    }
83    fn description(&self) -> &'static str {
84        "SQL use_message_body_for_sql requires allow_dynamic_query=true"
85    }
86    fn run(&self) -> Result<(), CamelError> {
87        if self.use_message_body_for_sql && !self.allow_dynamic_query {
88            return Err(CamelError::from(
89                ConfigValidationError::SqlDynamicQueryWithoutAllowDynamic,
90            ));
91        }
92        Ok(())
93    }
94}
95
96/// Scan a list of `RouteDefinition`s and emit a `SqlDynamicQueryCheck` for
97/// every `sql:` URI whose parameters declare the dynamic-query intent
98/// (`useMessageBodyForSql` / `allowDynamicQuery`).
99///
100/// Walked URIs: the route's `from_uri` plus every `BuilderStep::To` URI
101/// reachable through structural step variants (filter, choice, split,
102/// multicast, throttle, etc.). Dynamic-URI steps (routing slip, recipient
103/// list, dynamic router) are skipped — their URIs are runtime-resolved and
104/// cannot be statically validated.
105///
106/// Invalid URIs are silently ignored: this scanner is best-effort defense in
107/// depth, not a primary security gate. The authoritative runtime check
108/// (`SqlProducer::resolve_query_source`) closes the SQLi vector regardless
109/// of what the static scanner finds here.
110pub fn scan_route_definitions_for_sql_checks(
111    routes: &[RouteDefinition],
112) -> Vec<Box<dyn ConfigCheck>> {
113    let mut out: Vec<Box<dyn ConfigCheck>> = Vec::new();
114    for route in routes {
115        collect_sql_checks_for_uri(route.from_uri(), &mut out);
116        for step in route.steps() {
117            for_each_step_uri(step, &mut |uri| collect_sql_checks_for_uri(uri, &mut out));
118        }
119    }
120    out
121}
122
123/// Walk every statically declared URI reachable through `step` and invoke
124/// `f` for each one. Variant coverage mirrors the prior
125/// `walk_step_uris`: `To` / `LayeredTo`, `WireTap`, `Enrich`, `PollEnrich`,
126/// plus all structural sub-pipelines whose `steps` are known at parse time
127/// (`Filter` / `DeclarativeFilter`, `Split` / `DeclarativeSplit` /
128/// `DeclarativeStreamSplit`, `Multicast`, `Throttle`, `LoadBalance`,
129/// `Loop` / `DeclarativeLoop`, `IdempotentConsumer`, `Transacted`, `Layered`),
130/// the `Choice` and
131/// `DeclarativeChoice` `whens` (and `otherwise`), and the
132/// `DeclarativeDoTry` `try_steps` / `catch` / `finally` blocks.
133///
134/// Dynamic-URI steps (RoutingSlip, RecipientList, DynamicRouter, and the
135/// declarative equivalents) are intentionally skipped — their URIs are
136/// resolved at runtime and cannot be statically validated.
137fn for_each_step_uri<F: FnMut(&str)>(step: &BuilderStep, f: &mut F) {
138    match step {
139        BuilderStep::To(uri) | BuilderStep::LayeredTo { uri, .. } => f(uri),
140        BuilderStep::WireTap { uri } | BuilderStep::Enrich { uri, .. } => {
141            f(uri);
142        }
143        BuilderStep::PollEnrich { uri, .. } => {
144            f(uri);
145        }
146        BuilderStep::Filter { steps, .. }
147        | BuilderStep::DeclarativeFilter { steps, .. }
148        | BuilderStep::Split { steps, .. }
149        | BuilderStep::DeclarativeSplit { steps, .. }
150        | BuilderStep::DeclarativeStreamSplit { steps, .. }
151        | BuilderStep::StreamSplit { steps, .. }
152        | BuilderStep::Multicast { steps, .. }
153        | BuilderStep::Throttle { steps, .. }
154        | BuilderStep::LoadBalance { steps, .. }
155        | BuilderStep::Loop { steps, .. }
156        | BuilderStep::DeclarativeLoop { steps, .. }
157        | BuilderStep::IdempotentConsumer { steps, .. }
158        | BuilderStep::Transacted { steps, .. }
159        | BuilderStep::Layered { steps, .. } => {
160            for s in steps {
161                for_each_step_uri(s, f);
162            }
163        }
164        BuilderStep::Choice { whens, otherwise } => {
165            for when in whens {
166                for s in &when.steps {
167                    for_each_step_uri(s, f);
168                }
169            }
170            if let Some(ow) = otherwise {
171                for s in ow {
172                    for_each_step_uri(s, f);
173                }
174            }
175        }
176        BuilderStep::DeclarativeChoice { whens, otherwise } => {
177            for when in whens {
178                for s in &when.steps {
179                    for_each_step_uri(s, f);
180                }
181            }
182            if let Some(ow) = otherwise {
183                for s in ow {
184                    for_each_step_uri(s, f);
185                }
186            }
187        }
188        BuilderStep::DeclarativeDoTry {
189            try_steps,
190            catch,
191            finally,
192        } => {
193            for s in try_steps {
194                for_each_step_uri(s, f);
195            }
196            for clause in catch {
197                for s in &clause.steps {
198                    for_each_step_uri(s, f);
199                }
200            }
201            if let Some(fin) = finally {
202                for s in &fin.steps {
203                    for_each_step_uri(s, f);
204                }
205            }
206        }
207        // All remaining variants are process-mode (no static URI) or
208        // runtime-resolved dynamic URIs (routing slip, recipient list,
209        // dynamic router) — skip.
210        _ => {}
211    }
212}
213
214/// Return `true` if any route statically declares the given URI scheme.
215///
216/// Scans each route's `from_uri` plus every URI reachable through the
217/// structural `BuilderStep` tree (see `for_each_step_uri`). Dynamic-URI
218/// steps (RoutingSlip, RecipientList, DynamicRouter) do not contribute —
219/// their URIs are runtime-resolved and cannot be statically validated.
220///
221/// Invalid URIs (those that fail `camel_endpoint::parse_uri`) are silently
222/// skipped, matching the best-effort semantics of the SQL scanner. An
223/// invalid `from` URI does NOT cause the route to be reported as
224/// referencing the scheme; an invalid step URI is just ignored.
225///
226/// Used by the `camel run` startup guard to decide whether a route
227/// references `exec` (a feature-gated component) so it can register the
228/// `ExecBundle` only when needed — fixing the fail-closed
229/// `ExecBundle::validate()` that previously aborted startup for any
230/// route, even ones that never used `exec:`.
231pub fn route_definitions_reference_scheme(routes: &[RouteDefinition], scheme: &str) -> bool {
232    use std::cell::Cell;
233    let found = Cell::new(false);
234    let mut check = |uri: &str| {
235        if found.get() {
236            return;
237        }
238        if let Ok(parts) = camel_endpoint::parse_uri(uri)
239            && parts.scheme == scheme
240        {
241            found.set(true);
242        }
243    };
244    for route in routes {
245        if found.get() {
246            break;
247        }
248        check(route.from_uri());
249        if found.get() {
250            break;
251        }
252        for step in route.steps() {
253            for_each_step_uri(step, &mut check);
254            if found.get() {
255                break;
256            }
257        }
258    }
259    found.get()
260}
261
262fn collect_sql_checks_for_uri(uri: &str, out: &mut Vec<Box<dyn ConfigCheck>>) {
263    let Ok(parts) = camel_endpoint::parse_uri(uri) else {
264        return;
265    };
266    if parts.scheme != "sql" {
267        return;
268    }
269    // Match the camel-sql parser: keys are case-preserved by parse_uri (it
270    // only decodes percent-encoding), and the SQL config looks them up by
271    // their camelCase name (`useMessageBodyForSql`, `allowDynamicQuery`).
272    let use_body = parts
273        .params
274        .get("useMessageBodyForSql")
275        .and_then(|v| parse_bool_param(v).ok())
276        .unwrap_or(false);
277    let allow_dynamic = parts
278        .params
279        .get("allowDynamicQuery")
280        .and_then(|v| parse_bool_param(v).ok())
281        .unwrap_or(false);
282    if use_body || allow_dynamic {
283        // Only emit a check when the operator declared an intent that
284        // participates in the matrix. Endpoints with neither flag set
285        // cannot be misconfigured in the H7 sense — skip the noise.
286        out.push(Box::new(SqlDynamicQueryCheck {
287            use_message_body_for_sql: use_body,
288            allow_dynamic_query: allow_dynamic,
289        }));
290    }
291}
292
293#[cfg(test)]
294mod tests {
295    use super::*;
296
297    /// Smoke test: the empty registry returns `Ok` with an empty failure list.
298    #[test]
299    fn empty_registry_returns_empty_ok_report() {
300        let report = run_startup_validation(vec![]).expect("empty registry must return Ok");
301        assert!(report.is_ok());
302        assert!(report.failures.is_empty());
303    }
304
305    /// Trait smoke test: a trivial `ConfigCheck` impl can be defined by callers
306    /// and dispatched dynamically. This guards the trait surface against
307    /// accidental breaking changes between batches.
308    #[test]
309    fn trait_is_object_safe_and_dispatchable() {
310        struct AlwaysOk;
311        impl ConfigCheck for AlwaysOk {
312            fn name(&self) -> &'static str {
313                "always-ok"
314            }
315            fn description(&self) -> &'static str {
316                "always-ok skeleton check"
317            }
318            fn run(&self) -> Result<(), CamelError> {
319                Ok(())
320            }
321        }
322
323        let check: Box<dyn ConfigCheck> = Box::new(AlwaysOk);
324        assert_eq!(check.name(), "always-ok");
325        assert!(check.run().is_ok());
326    }
327
328    /// H7: SQL endpoint with `use_message_body_for_sql=true` and
329    /// `allow_dynamic_query=false` is a misconfiguration that would silently
330    /// produce empty queries — fail closed at startup.
331    #[test]
332    fn sql_dynamic_query_check_refuses_startup() {
333        let check = SqlDynamicQueryCheck {
334            use_message_body_for_sql: true,
335            allow_dynamic_query: false,
336        };
337        let result = run_startup_validation(vec![Box::new(check)]);
338        match result {
339            Err(CamelError::Config(msg)) => {
340                assert!(msg.contains("sql-dynamic-query"));
341                assert!(msg.contains("allow_dynamic_query"));
342            }
343            other => panic!("expected CamelError::Config, got {other:?}"),
344        }
345    }
346
347    /// H7: the inner `SqlDynamicQueryCheck::run()` returns the typed
348    /// `ConfigValidationError::SqlDynamicQueryWithoutAllowDynamic` so
349    /// operators can match on the variant directly. The outer
350    /// `run_startup_validation` wraps it into a `Config(String)` joined
351    /// report (asserted above); this test guards the typed inner path
352    /// so the promotion to typed errors (rc-r8fd) doesn't regress.
353    #[test]
354    fn sql_dynamic_query_check_run_returns_typed_error() {
355        let check = SqlDynamicQueryCheck {
356            use_message_body_for_sql: true,
357            allow_dynamic_query: false,
358        };
359        let result = check.run();
360        assert!(
361            matches!(
362                result,
363                Err(CamelError::ConfigValidation(
364                    ConfigValidationError::SqlDynamicQueryWithoutAllowDynamic,
365                ))
366            ),
367            "expected ConfigValidation(SqlDynamicQueryWithoutAllowDynamic), got: {result:?}"
368        );
369    }
370
371    /// H7: explicit opt-in satisfies the check — startup proceeds.
372    #[test]
373    fn sql_dynamic_query_check_passes_with_opt_in() {
374        let check = SqlDynamicQueryCheck {
375            use_message_body_for_sql: true,
376            allow_dynamic_query: true,
377        };
378        let report =
379            run_startup_validation(vec![Box::new(check)]).expect("opt-in must satisfy the check");
380        assert!(report.is_ok());
381    }
382
383    /// H7: when `use_message_body_for_sql=false`, the dynamic-query gate
384    /// is irrelevant and the check passes regardless of the opt-in flag.
385    #[test]
386    fn sql_dynamic_query_check_passes_without_body_sql() {
387        let check = SqlDynamicQueryCheck {
388            use_message_body_for_sql: false,
389            allow_dynamic_query: false,
390        };
391        let report = run_startup_validation(vec![Box::new(check)])
392            .expect("no body-sourced queries → no fail-closed condition");
393        assert!(report.is_ok());
394    }
395
396    /// Scanner: a route with a `from: sql:...` URI whose params declare
397    /// `useMessageBodyForSql=true` but no `allowDynamicQuery` must produce
398    /// a failing `SqlDynamicQueryCheck`.
399    #[test]
400    fn scanner_flags_from_sql_endpoint_with_body_but_no_allow() {
401        let route = RouteDefinition::new(
402            "sql:select * from t?db_url=postgres://x/y&useMessageBodyForSql=true",
403            vec![],
404        )
405        .with_route_id("r".to_string());
406        let checks = scan_route_definitions_for_sql_checks(&[route]);
407        assert_eq!(checks.len(), 1);
408        assert!(run_startup_validation(checks).is_err());
409    }
410
411    /// Scanner: a route with a `to: sql:...` step in the top-level step
412    /// vector is found.
413    #[test]
414    fn scanner_walks_top_level_to_sql_step() {
415        let route = RouteDefinition::new(
416            "direct:start",
417            vec![BuilderStep::To(
418                "sql:select 1?db_url=postgres://x/y&useMessageBodyForSql=true".to_string(),
419            )],
420        )
421        .with_route_id("r".to_string());
422        let checks = scan_route_definitions_for_sql_checks(&[route]);
423        assert_eq!(checks.len(), 1);
424        assert!(run_startup_validation(checks).is_err());
425    }
426
427    /// Scanner: a route with no SQL URIs produces no checks.
428    #[test]
429    fn scanner_emits_nothing_for_non_sql_route() {
430        let route = RouteDefinition::new("timer:tick?period=1000", vec![]);
431        let checks = scan_route_definitions_for_sql_checks(&[route]);
432        assert!(checks.is_empty());
433    }
434
435    /// Scanner: a SQL endpoint without the body-mode flag is not flagged
436    /// (the operator has not opted into dynamic queries, so there is no
437    /// intent to validate against the capability gate).
438    #[test]
439    fn scanner_skips_sql_endpoint_without_dynamic_intent() {
440        let route = RouteDefinition::new("sql:select 1?db_url=postgres://x/y", vec![]);
441        let checks = scan_route_definitions_for_sql_checks(&[route]);
442        assert!(checks.is_empty());
443    }
444
445    // -- exec-scheme scanner tests (Task 1.1) ---------------------------------
446    //
447    // These tests exercise `route_definitions_reference_scheme`, the reusable
448    // scanner that the `camel run` startup guard calls to decide whether a
449    // route statically references the `exec` scheme. The scanner walks every
450    // structural `BuilderStep` variant whose URI is known at parse time, so
451    // each variant needs a coverage test. Dynamic-URI steps
452    // (RoutingSlip/RecipientList/DynamicRouter) must report `false` because
453    // their URIs are resolved at runtime and cannot be statically validated.
454
455    /// From-URI match: a route whose `from` is `exec:...` must be detected.
456    #[test]
457    fn scheme_scanner_detects_exec_from_uri() {
458        let route = RouteDefinition::new("exec:echo", vec![]).with_route_id("r".to_string());
459        assert!(route_definitions_reference_scheme(&[route], "exec"));
460    }
461
462    /// Top-level `To` step: a non-exec source with a `To("exec:...")` step.
463    #[test]
464    fn scheme_scanner_detects_exec_in_to_step() {
465        let route = RouteDefinition::new(
466            "timer:tick?period=500",
467            vec![BuilderStep::To("exec:echo".to_string())],
468        )
469        .with_route_id("r".to_string());
470        assert!(route_definitions_reference_scheme(&[route], "exec"));
471    }
472
473    /// `WireTap` variant — static URI in named field.
474    #[test]
475    fn scheme_scanner_detects_exec_in_wiretap() {
476        let route = RouteDefinition::new(
477            "timer:tick",
478            vec![BuilderStep::WireTap {
479                uri: "exec:audit".to_string(),
480            }],
481        )
482        .with_route_id("r".to_string());
483        assert!(route_definitions_reference_scheme(&[route], "exec"));
484    }
485
486    /// `Enrich` variant — static URI in named field alongside strategy/timeout.
487    #[test]
488    fn scheme_scanner_detects_exec_in_enrich() {
489        let route = RouteDefinition::new(
490            "direct:start",
491            vec![BuilderStep::Enrich {
492                uri: "exec:enricher".to_string(),
493                strategy: Some("agg".to_string()),
494                timeout_ms: Some(1000),
495            }],
496        )
497        .with_route_id("r".to_string());
498        assert!(route_definitions_reference_scheme(&[route], "exec"));
499    }
500
501    /// `PollEnrich` variant — static URI in named field.
502    #[test]
503    fn scheme_scanner_detects_exec_in_pollenrich() {
504        let route = RouteDefinition::new(
505            "direct:start",
506            vec![BuilderStep::PollEnrich {
507                uri: "exec:poller".to_string(),
508                strategy: None,
509                timeout_ms: Some(500),
510            }],
511        )
512        .with_route_id("r".to_string());
513        assert!(route_definitions_reference_scheme(&[route], "exec"));
514    }
515
516    /// `Filter` sub-pipeline — recurse into `steps`.
517    #[test]
518    fn scheme_scanner_detects_exec_in_filter() {
519        use camel_api::FilterPredicate;
520        let route = RouteDefinition::new(
521            "direct:start",
522            vec![BuilderStep::Filter {
523                predicate: FilterPredicate::new(|_| true),
524                steps: vec![BuilderStep::To("exec:echo".to_string())],
525            }],
526        )
527        .with_route_id("r".to_string());
528        assert!(route_definitions_reference_scheme(&[route], "exec"));
529    }
530
531    /// A middleware-wrapped send is still a send — `LayeredTo` contributes
532    /// its authored URI to the scheme scan (regression: the upstream
533    /// catch-all silently skipped it).
534    #[test]
535    fn scheme_scanner_detects_exec_in_layered_to() {
536        let route = RouteDefinition::new(
537            "direct:start",
538            vec![BuilderStep::LayeredTo {
539                uri: "exec:echo".to_string(),
540                factory: camel_api::LayerFactory::new(tower::limit::ConcurrencyLimitLayer::new(2)),
541            }],
542        )
543        .with_route_id("r".to_string());
544        assert!(route_definitions_reference_scheme(&[route], "exec"));
545    }
546
547    /// `Layered` sub-pipeline — recurse into `steps` like every other
548    /// structural container.
549    #[test]
550    fn scheme_scanner_detects_exec_in_layered() {
551        let route = RouteDefinition::new(
552            "direct:start",
553            vec![BuilderStep::Layered {
554                factory: camel_api::LayerFactory::new(tower::limit::ConcurrencyLimitLayer::new(2)),
555                steps: vec![BuilderStep::To("exec:echo".to_string())],
556            }],
557        )
558        .with_route_id("r".to_string());
559        assert!(route_definitions_reference_scheme(&[route], "exec"));
560    }
561
562    /// `Split` sub-pipeline — recurse into `steps`.
563    #[test]
564    fn scheme_scanner_detects_exec_in_split() {
565        use camel_api::splitter::{AggregationStrategy, SplitterConfig, split_body_lines};
566        let route = RouteDefinition::new(
567            "direct:start",
568            vec![BuilderStep::Split {
569                config: SplitterConfig::new(split_body_lines())
570                    .aggregation(AggregationStrategy::Original),
571                steps: vec![BuilderStep::To("exec:echo".to_string())],
572            }],
573        )
574        .with_route_id("r".to_string());
575        assert!(route_definitions_reference_scheme(&[route], "exec"));
576    }
577
578    /// `Multicast` sub-pipeline — recurse into `steps`.
579    #[test]
580    fn scheme_scanner_detects_exec_in_multicast() {
581        use camel_api::MulticastConfig;
582        let route = RouteDefinition::new(
583            "direct:start",
584            vec![BuilderStep::Multicast {
585                steps: vec![BuilderStep::To("exec:echo".to_string())],
586                config: MulticastConfig::new(),
587            }],
588        )
589        .with_route_id("r".to_string());
590        assert!(route_definitions_reference_scheme(&[route], "exec"));
591    }
592
593    /// `Loop` sub-pipeline — recurse into `steps`.
594    #[test]
595    fn scheme_scanner_detects_exec_in_loop() {
596        use camel_api::loop_eip::{LoopConfig, LoopMode};
597        let route = RouteDefinition::new(
598            "direct:start",
599            vec![BuilderStep::Loop {
600                config: LoopConfig::new(LoopMode::Count(3)),
601                steps: vec![BuilderStep::To("exec:echo".to_string())],
602            }],
603        )
604        .with_route_id("r".to_string());
605        assert!(route_definitions_reference_scheme(&[route], "exec"));
606    }
607
608    /// `IdempotentConsumer` sub-pipeline — recurse into `steps`.
609    #[test]
610    fn scheme_scanner_detects_exec_in_idempotent_consumer() {
611        use crate::lifecycle::application::route_definition::LanguageExpressionDef;
612        let expr = LanguageExpressionDef {
613            language: "simple".into(),
614            source: "${header.id}".into(),
615        };
616        let route = RouteDefinition::new(
617            "direct:start",
618            vec![BuilderStep::IdempotentConsumer {
619                repository: "myRepo".to_string(),
620                expression: expr,
621                steps: vec![BuilderStep::To("exec:echo".to_string())],
622                eager: false,
623                remove_on_failure: false,
624                on_missing_key: camel_processor::OnMissingKey::Fail,
625            }],
626        )
627        .with_route_id("r".to_string());
628        assert!(route_definitions_reference_scheme(&[route], "exec"));
629    }
630
631    /// `Throttle` sub-pipeline — recurse into `steps`.
632    #[test]
633    fn scheme_scanner_detects_exec_in_throttle() {
634        use camel_api::ThrottlerConfig;
635        let route = RouteDefinition::new(
636            "direct:start",
637            vec![BuilderStep::Throttle {
638                config: ThrottlerConfig::new(10, std::time::Duration::from_millis(10)),
639                steps: vec![BuilderStep::To("exec:echo".to_string())],
640            }],
641        )
642        .with_route_id("r".to_string());
643        assert!(route_definitions_reference_scheme(&[route], "exec"));
644    }
645
646    /// `LoadBalance` sub-pipeline — recurse into `steps`.
647    #[test]
648    fn scheme_scanner_detects_exec_in_loadbalance() {
649        use camel_api::LoadBalancerConfig;
650        let route = RouteDefinition::new(
651            "direct:start",
652            vec![BuilderStep::LoadBalance {
653                config: LoadBalancerConfig::round_robin(),
654                steps: vec![BuilderStep::To("exec:echo".to_string())],
655            }],
656        )
657        .with_route_id("r".to_string());
658        assert!(route_definitions_reference_scheme(&[route], "exec"));
659    }
660
661    /// `DeclarativeFilter` sub-pipeline — recurse into `steps`.
662    #[test]
663    fn scheme_scanner_detects_exec_in_declarative_filter() {
664        use crate::lifecycle::application::route_definition::LanguageExpressionDef;
665        let expr = LanguageExpressionDef {
666            language: "simple".into(),
667            source: "${body}".into(),
668        };
669        let route = RouteDefinition::new(
670            "direct:start",
671            vec![BuilderStep::DeclarativeFilter {
672                predicate: expr,
673                steps: vec![BuilderStep::To("exec:echo".to_string())],
674            }],
675        )
676        .with_route_id("r".to_string());
677        assert!(route_definitions_reference_scheme(&[route], "exec"));
678    }
679
680    /// `DeclarativeSplit` sub-pipeline — recurse into `steps`.
681    #[test]
682    fn scheme_scanner_detects_exec_in_declarative_split() {
683        use crate::lifecycle::application::route_definition::LanguageExpressionDef;
684        use camel_api::splitter::AggregationStrategy;
685        let expr = LanguageExpressionDef {
686            language: "simple".into(),
687            source: "${body}".into(),
688        };
689        let route = RouteDefinition::new(
690            "direct:start",
691            vec![BuilderStep::DeclarativeSplit {
692                expression: expr,
693                aggregation: AggregationStrategy::Original,
694                parallel: false,
695                parallel_limit: None,
696                trace_item_threshold: None,
697                stop_on_exception: true,
698                steps: vec![BuilderStep::To("exec:echo".to_string())],
699            }],
700        )
701        .with_route_id("r".to_string());
702        assert!(route_definitions_reference_scheme(&[route], "exec"));
703    }
704
705    /// `DeclarativeStreamSplit` sub-pipeline — recurse into `steps`.
706    #[test]
707    fn scheme_scanner_detects_exec_in_declarative_stream_split() {
708        use camel_api::splitter::{AggregationStrategy, StreamSplitConfig, StreamSplitFormat};
709        let route = RouteDefinition::new(
710            "direct:start",
711            vec![BuilderStep::DeclarativeStreamSplit {
712                stream_config: StreamSplitConfig {
713                    format: StreamSplitFormat::Ndjson,
714                    max_record_bytes: 1024,
715                    batch_size: 1,
716                    chunk_size: None,
717                    max_parts: None,
718                    max_part_size: None,
719                    content_types: None,
720                    include_origin: true,
721                },
722                aggregation: AggregationStrategy::Original,
723                stop_on_exception: true,
724                steps: vec![BuilderStep::To("exec:echo".to_string())],
725            }],
726        )
727        .with_route_id("r".to_string());
728        assert!(route_definitions_reference_scheme(&[route], "exec"));
729    }
730
731    /// `DeclarativeLoop` sub-pipeline — recurse into `steps`.
732    #[test]
733    fn scheme_scanner_detects_exec_in_declarative_loop() {
734        use crate::lifecycle::application::route_definition::LanguageExpressionDef;
735        let expr = LanguageExpressionDef {
736            language: "simple".into(),
737            source: "${body}".into(),
738        };
739        let route = RouteDefinition::new(
740            "direct:start",
741            vec![BuilderStep::DeclarativeLoop {
742                count: Some(5),
743                while_predicate: Some(expr),
744                steps: vec![BuilderStep::To("exec:echo".to_string())],
745                max_iterations: Some(100),
746            }],
747        )
748        .with_route_id("r".to_string());
749        assert!(route_definitions_reference_scheme(&[route], "exec"));
750    }
751
752    /// `Choice` with a `when` branch that contains exec.
753    #[test]
754    fn scheme_scanner_detects_exec_in_choice_branch() {
755        use crate::lifecycle::application::route_definition::WhenStep;
756        use camel_api::FilterPredicate;
757        let route = RouteDefinition::new(
758            "direct:start",
759            vec![BuilderStep::Choice {
760                whens: vec![WhenStep {
761                    predicate: FilterPredicate::new(|_| true),
762                    steps: vec![BuilderStep::To("exec:echo".to_string())],
763                }],
764                otherwise: None,
765            }],
766        )
767        .with_route_id("r".to_string());
768        assert!(route_definitions_reference_scheme(&[route], "exec"));
769    }
770
771    /// `Choice` with exec in the `otherwise` branch only.
772    #[test]
773    fn scheme_scanner_detects_exec_in_choice_otherwise() {
774        use crate::lifecycle::application::route_definition::WhenStep;
775        use camel_api::FilterPredicate;
776        let route = RouteDefinition::new(
777            "direct:start",
778            vec![BuilderStep::Choice {
779                whens: vec![WhenStep {
780                    predicate: FilterPredicate::new(|_| false),
781                    steps: vec![BuilderStep::To("log:info".to_string())],
782                }],
783                otherwise: Some(vec![BuilderStep::To("exec:echo".to_string())]),
784            }],
785        )
786        .with_route_id("r".to_string());
787        assert!(route_definitions_reference_scheme(&[route], "exec"));
788    }
789
790    /// `DeclarativeChoice` with exec in a `when` branch.
791    #[test]
792    fn scheme_scanner_detects_exec_in_declarative_choice_when() {
793        use crate::lifecycle::application::route_definition::{
794            DeclarativeWhenStep, LanguageExpressionDef,
795        };
796        let expr = LanguageExpressionDef {
797            language: "simple".into(),
798            source: "${body}".into(),
799        };
800        let route = RouteDefinition::new(
801            "direct:start",
802            vec![BuilderStep::DeclarativeChoice {
803                whens: vec![DeclarativeWhenStep {
804                    predicate: expr,
805                    steps: vec![BuilderStep::To("exec:echo".to_string())],
806                }],
807                otherwise: None,
808            }],
809        )
810        .with_route_id("r".to_string());
811        assert!(route_definitions_reference_scheme(&[route], "exec"));
812    }
813
814    /// `DeclarativeChoice` with exec in `otherwise` only.
815    #[test]
816    fn scheme_scanner_detects_exec_in_declarative_choice_otherwise() {
817        use crate::lifecycle::application::route_definition::{
818            DeclarativeWhenStep, LanguageExpressionDef,
819        };
820        let expr = LanguageExpressionDef {
821            language: "simple".into(),
822            source: "${body}".into(),
823        };
824        let route = RouteDefinition::new(
825            "direct:start",
826            vec![BuilderStep::DeclarativeChoice {
827                whens: vec![DeclarativeWhenStep {
828                    predicate: expr,
829                    steps: vec![BuilderStep::To("log:info".to_string())],
830                }],
831                otherwise: Some(vec![BuilderStep::To("exec:echo".to_string())]),
832            }],
833        )
834        .with_route_id("r".to_string());
835        assert!(route_definitions_reference_scheme(&[route], "exec"));
836    }
837
838    /// `DeclarativeDoTry` with exec in `try_steps`.
839    #[test]
840    fn scheme_scanner_detects_exec_in_dotry() {
841        let route = RouteDefinition::new(
842            "direct:start",
843            vec![BuilderStep::DeclarativeDoTry {
844                try_steps: vec![BuilderStep::To("exec:echo".to_string())],
845                catch: vec![],
846                finally: None,
847            }],
848        )
849        .with_route_id("r".to_string());
850        assert!(route_definitions_reference_scheme(&[route], "exec"));
851    }
852
853    /// `DeclarativeDoTry` with exec in a `catch` clause.
854    #[test]
855    fn scheme_scanner_detects_exec_in_dotry_catch() {
856        use crate::lifecycle::application::route_definition::DoTryCatchClauseBuilder;
857        let route = RouteDefinition::new(
858            "direct:start",
859            vec![BuilderStep::DeclarativeDoTry {
860                try_steps: vec![BuilderStep::To("log:info".to_string())],
861                catch: vec![DoTryCatchClauseBuilder {
862                    exception: None,
863                    when: None,
864                    code: None,
865                    business_kind: None,
866                    on_when: None,
867                    disposition: camel_api::error_handler::ExceptionDisposition::Propagate,
868                    steps: vec![BuilderStep::To("exec:echo".to_string())],
869                }],
870                finally: None,
871            }],
872        )
873        .with_route_id("r".to_string());
874        assert!(route_definitions_reference_scheme(&[route], "exec"));
875    }
876
877    /// `DeclarativeDoTry` with exec in `finally`.
878    #[test]
879    fn scheme_scanner_detects_exec_in_dotry_finally() {
880        use crate::lifecycle::application::route_definition::DoTryFinallyBuilder;
881        let route = RouteDefinition::new(
882            "direct:start",
883            vec![BuilderStep::DeclarativeDoTry {
884                try_steps: vec![BuilderStep::To("log:info".to_string())],
885                catch: vec![],
886                finally: Some(DoTryFinallyBuilder {
887                    on_when: None,
888                    steps: vec![BuilderStep::To("exec:echo".to_string())],
889                }),
890            }],
891        )
892        .with_route_id("r".to_string());
893        assert!(route_definitions_reference_scheme(&[route], "exec"));
894    }
895
896    /// Multi-route scan: only the second route references exec.
897    #[test]
898    fn scheme_scanner_detects_exec_across_multiple_routes() {
899        let r1 = RouteDefinition::new("timer:tick", vec![]).with_route_id("r1".to_string());
900        let r2 = RouteDefinition::new(
901            "direct:start",
902            vec![BuilderStep::To("exec:echo".to_string())],
903        )
904        .with_route_id("r2".to_string());
905        assert!(route_definitions_reference_scheme(&[r1, r2], "exec"));
906    }
907
908    /// Negative: a non-exec route produces `false`.
909    #[test]
910    fn scheme_scanner_false_for_non_exec_route() {
911        let route =
912            RouteDefinition::new("timer:tick", vec![BuilderStep::To("log:info".to_string())])
913                .with_route_id("r".to_string());
914        assert!(!route_definitions_reference_scheme(&[route], "exec"));
915    }
916
917    /// Negative: dynamic-URI step (RoutingSlip) with a closure that returns
918    /// `exec:echo` at runtime — the scanner cannot see through the closure.
919    #[test]
920    fn scheme_scanner_false_for_dynamic_uri_only() {
921        use camel_api::RoutingSlipConfig;
922        use std::sync::Arc;
923        let route = RouteDefinition::new(
924            "timer:tick",
925            vec![BuilderStep::RoutingSlip {
926                config: RoutingSlipConfig::new(camel_api::TargetSource::Sync(Arc::new(|_| {
927                    Some("exec:echo".to_string())
928                }))),
929            }],
930        )
931        .with_route_id("r".to_string());
932        assert!(!route_definitions_reference_scheme(&[route], "exec"));
933    }
934}