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