Skip to main content

toolkit/bootstrap/
run.rs

1use super::config::{get_gear_runtime_config, render_gear_config_for_oop};
2use super::host::{init_logging_unified, init_panic_tracing, normalize_path};
3#[cfg(feature = "otel")]
4use super::telemetry::tracing_shutdown;
5use super::{AppConfig, RuntimeKind};
6use crate::backends::LocalProcessBackend;
7use crate::runtime::{
8    DbOptions, OopGearSpawnConfig, OopSpawnOptions, RunOptions, ShutdownOptions, run, shutdown,
9};
10use anyhow::Result;
11use figment::Figment;
12use figment::providers::Serialized;
13use std::path::{Path, PathBuf};
14use std::sync::Arc;
15use tokio_util::sync::CancellationToken;
16
17/// Spawn a signal handler task that cancels the provided token on SIGTERM/SIGINT.
18///
19/// This helper consolidates signal handling logic used by both `run_server` and `run_migrate`.
20/// The `context` parameter customizes log messages for better diagnostics.
21fn spawn_signal_handler(cancel: CancellationToken, context: &str) {
22    let context_owned = context.to_owned();
23    tokio::spawn(async move {
24        match shutdown::wait_for_shutdown().await {
25            Ok(()) => {
26                tracing::info!(target: "", "------------------");
27                tracing::info!("{}: shutdown signal received", context_owned);
28            }
29            Err(e) => {
30                tracing::warn!(
31                    error = %e,
32                    "{}: signal handler failed, falling back to ctrl_c()",
33                    context_owned
34                );
35                _ = tokio::signal::ctrl_c().await;
36            }
37        }
38        cancel.cancel();
39    });
40}
41
42/// # Errors
43///
44/// Returns an error if:
45/// - There was a critical error during initialization of the gears
46/// - Problems with the database or third-party services
47/// - An issue during runtime or shutdown
48///
49/// The TLS crypto provider is installed automatically as the first step of
50/// [`init_procedure`] (idempotent), so callers do not need to invoke
51/// [`super::init_crypto_provider`] explicitly.
52pub async fn run_server(config: AppConfig) -> Result<()> {
53    init_procedure(&config).map_err(|e| {
54        tracing::error!(error = %e, "Initialization failed");
55        e
56    })?;
57    tracing::info!("Initializing gears...");
58
59    // Generate process-level instance ID once at startup.
60    // This is shared by all gears in this process.
61    let instance_id = uuid::Uuid::new_v4();
62    tracing::info!(instance_id = %instance_id, "Generated process instance ID");
63
64    // Create root cancellation token for the entire process.
65    // This token drives shutdown for the gear runtime and all lifecycle/stateful gears.
66    let cancel = CancellationToken::new();
67
68    // Hook OS signals to the root token at the host level.
69    // This replaces the use of ShutdownOptions::Signals inside the runtime.
70    spawn_signal_handler(cancel.clone(), "server");
71
72    // Build config provider and resolve database options
73    let db_options = resolve_db_options(&config)?;
74
75    // Create OoP backend with cancellation token - it will auto-shutdown all processes on cancel
76    let oop_backend = LocalProcessBackend::new(cancel.clone());
77
78    // Build OoP spawn configuration
79    let oop_options = build_oop_spawn_options(&config, oop_backend)?;
80
81    // Remote platform-plane calls carry `X-ToolKit-Internal-Token` from
82    // `oop_http.internal_auth` (cpt-cf-adr-two-plane-auth); without it they fail.
83    // Co-hosted dependencies use local ClientHub objects and need no credential.
84    let internal_token_provider = match host_credential(&config)? {
85        Some(internal_auth) => Some(
86            toolkit_contract::runtime::platform_credential::build_internal_token_provider(
87                internal_auth,
88                &cancel,
89            )
90            .await?,
91        ),
92        None => None,
93    };
94
95    // Apply configured lifecycle deadlines (absent fields keep framework defaults).
96    let init_deadline = config.server.init_deadline();
97    let shutdown_deadline = config.server.shutdown_deadline();
98
99    // Run the ToolKit runtime with the root cancellation token.
100    // Shutdown is driven by the signal handler spawned above, not by ShutdownOptions::Signals.
101    // OoP gears are spawned after parent publication, application startup and
102    // REST provider registration, so the parent's complete API is available.
103    let run_options = RunOptions::new(
104        Arc::new(config),
105        db_options,
106        ShutdownOptions::Token(cancel.clone()),
107        instance_id,
108    )
109    .with_oop(oop_options)
110    .with_internal_token_provider(internal_token_provider)
111    .with_init_deadline(init_deadline)
112    .with_shutdown_deadline(shutdown_deadline);
113
114    let result = run(run_options).await;
115
116    // Graceful shutdown - flush remaining telemetry
117    #[cfg(feature = "otel")]
118    tracing_shutdown().await;
119
120    result
121}
122
123/// Run database migrations and exit.
124///
125/// This mode is designed for cloud deployment workflows where database
126/// migrations need to run as a separate step before starting the application.
127///
128/// Phases executed:
129/// - Pre-init (wire runtime internals)
130/// - DB migration (run all pending migrations)
131///
132/// The process exits after migrations complete. Any errors are reported
133/// and propagated as non-zero exit codes.
134///
135/// # Errors
136///
137/// Returns an error if:
138/// - No database configuration is found
139/// - Gear discovery fails
140/// - Pre-init phase fails
141/// - Migration phase fails
142///
143/// The TLS crypto provider is installed automatically as the first step of
144/// [`init_procedure`] (idempotent), so callers do not need to invoke
145/// [`super::init_crypto_provider`] explicitly.
146pub async fn run_migrate(config: AppConfig) -> Result<()> {
147    init_procedure(&config).map_err(|e| {
148        tracing::error!(error = %e, "Initialization failed");
149        e
150    })?;
151    tracing::info!("Starting migration mode...");
152
153    // Generate process-level instance ID for this migration run
154    let instance_id = uuid::Uuid::new_v4();
155    tracing::info!(instance_id = %instance_id, "Generated migration instance ID");
156
157    // Create cancellation token and wire it to OS signals
158    let cancel = CancellationToken::new();
159
160    // Hook OS signals to enable graceful cancellation of migrations
161    spawn_signal_handler(cancel.clone(), "migration");
162
163    // Build database options from configuration
164    let db_options = resolve_db_options(&config)?;
165
166    // Verify we have database configuration
167    if matches!(db_options, DbOptions::None) {
168        anyhow::bail!("Cannot run migrations: no database configuration found");
169    }
170
171    // Discover and build the gear registry
172    let registry = crate::registry::GearRegistry::discover_and_build()?;
173    tracing::info!(
174        gear_count = registry.gears().len(),
175        "Discovered gears for migration"
176    );
177
178    // Create the host runtime
179    let host = crate::runtime::HostRuntime::new(
180        registry,
181        Arc::new(config),
182        db_options,
183        Arc::new(crate::client_hub::ClientHub::new()),
184        cancel,
185        instance_id,
186        None, // No OoP spawning during migration
187    );
188
189    // Run only the migration phases (pre-init + DB migration)
190    let result = host.run_migration_phases().await;
191
192    // Graceful shutdown - flush remaining telemetry
193    #[cfg(feature = "otel")]
194    tracing_shutdown().await;
195
196    result?;
197
198    tracing::info!("All migrations completed successfully");
199    Ok(())
200}
201
202/// Options of [`run_publish_gts`].
203#[derive(Debug, Clone)]
204pub struct PublishGtsOptions {
205    /// Base URI of the remote registry, e.g. `https://registry:8443`.
206    pub registry_endpoint: String,
207    /// The overall deadline for every publication; at most
208    /// [`MAX_PUBLICATION_BUDGET`](crate::gts_publication::MAX_PUBLICATION_BUDGET) (10 minutes).
209    pub deadline: std::time::Duration,
210}
211
212/// Publish the GTS manifests of every linked gear to a remote registry and exit:
213/// a deployment step.
214///
215/// No gear runs: no `init`, database, bootstrap or plugin binding. Manifests
216/// come from the effective configuration (file, environment overrides,
217/// defaults), as at application startup. Requests carry the platform
218/// credential of `oop_http.internal_auth`. All publications run concurrently;
219/// see [`crate::gts_publication::deployment`].
220///
221/// # Errors
222/// No platform credential is configured, setup fails (manifest, ownership,
223/// wiring), or any publisher is refused or misses the deadline: the report is
224/// in the error, naming each publisher and its GTS ids.
225pub async fn run_publish_gts(config: AppConfig, options: PublishGtsOptions) -> Result<()> {
226    init_procedure(&config).map_err(|e| {
227        tracing::error!(error = %e, "Initialization failed");
228        e
229    })?;
230    // SIGTERM/SIGINT end the job, reported as cancelled. Dropping this future
231    // cancels too: the guard also ends the credential watcher.
232    let cancel = CancellationToken::new();
233    spawn_signal_handler(cancel.clone(), "publish-gts");
234    let _cancel_on_drop = cancel.clone().drop_guard();
235    let result = publish_gts(&config, &options, &cancel).await;
236
237    // The outcome is logged before the telemetry flush, on every path.
238    match &result {
239        Ok(()) => tracing::info!("GTS publication complete"),
240        Err(e) => tracing::error!(error = format!("{e:#}"), "GTS publication failed"),
241    }
242    #[cfg(feature = "otel")]
243    tracing_shutdown().await;
244    result
245}
246
247/// [`run_publish_gts`] after initialization.
248async fn publish_gts(
249    config: &AppConfig,
250    options: &PublishGtsOptions,
251    cancel: &CancellationToken,
252) -> Result<()> {
253    // Reject an over-long deadline before touching the registry or the credential.
254    crate::gts_publication::check_publication_budget("--timeout", options.deadline)?;
255    // Match startup validation without running gear lifecycle hooks.
256    let registry = crate::registry::GearRegistry::discover_and_build()?;
257    validate_deployment_configuration(&registry, config)?;
258    let internal_auth = platform_credential(config)?;
259    let provider = toolkit_contract::runtime::platform_credential::build_internal_token_provider(
260        internal_auth,
261        cancel,
262    )
263    .await?;
264    let tuning = toolkit_contract::wiring::ClientTuning::default()
265        .with_internal_token_provider(Some(provider));
266    let descriptors = crate::gts_publication::linked_descriptors();
267    tracing::info!(
268        publishers = descriptors.len(),
269        registry = %options.registry_endpoint,
270        "publishing GTS manifests"
271    );
272    let report = crate::gts_publication::deployment::publish(
273        &descriptors,
274        config,
275        &options.registry_endpoint,
276        &tuning,
277        options.deadline,
278        cancel,
279    )
280    .await?;
281    publication_result(&report)
282}
283
284fn validate_deployment_configuration(
285    registry: &crate::registry::GearRegistry,
286    config: &dyn crate::config::ConfigProvider,
287) -> Result<()> {
288    for entry in registry.gears() {
289        entry.validate_gts_publication_config(config)?;
290    }
291    Ok(())
292}
293
294/// `oop_http.internal_auth`, if configured.
295fn oop_internal_auth(config: &AppConfig) -> Option<&toolkit_security::InternalAuthConfig> {
296    config
297        .oop_http
298        .as_ref()
299        .and_then(|http| http.internal_auth.as_ref())
300}
301
302/// The host process's outbound platform credential: `oop_http.internal_auth`,
303/// or `None` when it is unset (Profile 1).
304///
305/// The host builds no inbound validator from this block; it only presents it on
306/// calls to remote dependencies. A kube block without `present` therefore does
307/// nothing here, and is refused with a host-specific message rather than the
308/// generic one, which assumes the participant sends calls.
309///
310/// # Errors
311/// When [`InternalAuthConfig::outbound`](toolkit_security::InternalAuthConfig::outbound)
312/// refuses `oop_http.internal_auth`.
313fn host_credential(config: &AppConfig) -> Result<Option<&toolkit_security::InternalAuthConfig>> {
314    let Some(internal_auth) = oop_internal_auth(config) else {
315        return Ok(None);
316    };
317    match internal_auth.outbound() {
318        Ok(_) => Ok(Some(internal_auth)),
319        Err(toolkit_security::InvalidOutboundAuth::MissingKubePresent) => anyhow::bail!(
320            "oop_http.internal_auth (provider: kube) has no `present:` block. The host process \
321             uses this block only as the outbound credential for remote platform-plane calls \
322             (`verify` is not used here): set `present.token_path`, or remove the block if no \
323             gear in this process has a remote dependency"
324        ),
325        Err(err) => anyhow::bail!(
326            "oop_http.internal_auth is unusable as the host's outbound credential: {err}"
327        ),
328    }
329}
330
331/// The platform credential `publish-gts` sends: `oop_http.internal_auth`.
332///
333/// # Errors
334/// When `oop_http.internal_auth` is unset, or
335/// [`InternalAuthConfig::outbound`](toolkit_security::InternalAuthConfig::outbound)
336/// refuses it: publish-gts always sends platform-plane calls.
337fn platform_credential(config: &AppConfig) -> Result<&toolkit_security::InternalAuthConfig> {
338    let internal_auth = oop_internal_auth(config).ok_or_else(|| {
339        anyhow::anyhow!("publish-gts needs a platform credential: configure oop_http.internal_auth")
340    })?;
341    internal_auth.outbound().map_err(|err| {
342        anyhow::anyhow!(
343            "publish-gts sends platform-plane calls, but oop_http.internal_auth is unusable as \
344             its credential: {err}"
345        )
346    })?;
347    Ok(internal_auth)
348}
349
350/// The job's result: an error carrying the report unless every publisher succeeded.
351fn publication_result(
352    report: &crate::gts_publication::deployment::GtsDeploymentReport,
353) -> Result<()> {
354    if report.succeeded() {
355        tracing::info!("GTS publication report:\n{report}");
356        Ok(())
357    } else {
358        anyhow::bail!("GTS publication failed:\n{report}")
359    }
360}
361
362fn resolve_db_options(config: &AppConfig) -> Result<DbOptions> {
363    if config.database.is_none() {
364        tracing::warn!("No global database section found; running without databases");
365        return Ok(DbOptions::None);
366    }
367
368    tracing::info!("Using DbManager with Figment-based configuration");
369    let figment = Figment::new().merge(Serialized::defaults(config));
370    let db_manager = Arc::new(toolkit_db::DbManager::from_figment(
371        figment,
372        config.server.home_dir.clone(),
373    )?);
374    Ok(DbOptions::Manager(db_manager))
375}
376
377/// Build `OoP` spawn configuration from `AppConfig`.
378///
379/// This collects all gears with `type=oop` and prepares their spawn configuration.
380/// The actual spawning happens in the `HostRuntime` after parent startup.
381fn build_oop_spawn_options(
382    config: &AppConfig,
383    backend: LocalProcessBackend,
384) -> Result<Option<OopSpawnOptions>> {
385    let home_dir = PathBuf::from(&config.server.home_dir);
386    let mut gears = Vec::new();
387
388    for gear_name in config.gears.keys() {
389        if let Some(spawn_config) = try_build_oop_gear_config(config, gear_name, &home_dir)? {
390            gears.push(spawn_config);
391        }
392    }
393
394    if gears.is_empty() {
395        Ok(None)
396    } else {
397        tracing::info!(count = gears.len(), "Prepared OoP gears for spawning");
398        Ok(Some(OopSpawnOptions {
399            gears,
400            backend: Box::new(backend),
401        }))
402    }
403}
404
405/// Try to build `OoP` gear spawn config if gear is of type `OoP`
406fn try_build_oop_gear_config(
407    config: &AppConfig,
408    gear_name: &str,
409    home_dir: &Path,
410) -> Result<Option<OopGearSpawnConfig>> {
411    let Some(runtime_cfg) = get_gear_runtime_config(config, gear_name)? else {
412        return Ok(None);
413    };
414
415    if !matches!(runtime_cfg.mod_type, RuntimeKind::Oop) {
416        return Ok(None);
417    }
418
419    let exec_cfg = runtime_cfg.execution.as_ref().ok_or_else(|| {
420        anyhow::anyhow!("gear '{gear_name}' is type=oop but execution config is missing")
421    })?;
422
423    let binary = normalize_path(&exec_cfg.executable_path)?;
424    let spawn_args = exec_cfg.args.clone();
425    let env = exec_cfg.environment.clone();
426
427    // Render the complete gear config (with resolved DB)
428    let rendered_config = render_gear_config_for_oop(config, gear_name, home_dir)?;
429    let rendered_json = rendered_config.to_json()?;
430
431    tracing::debug!(
432        gear =  %gear_name,
433        "Prepared OoP gear config: db={}",
434        rendered_config.database.is_some()
435    );
436
437    Ok(Some(OopGearSpawnConfig {
438        gear_name: gear_name.to_owned(),
439        binary,
440        args: spawn_args,
441        env,
442        working_directory: exec_cfg.working_directory.clone(),
443        rendered_config_json: rendered_json,
444    }))
445}
446
447/// Initialize process-wide bootstrap state from a provided `&AppConfig`.
448///
449/// This helper performs the common startup sequence shared by server and migration modes.
450/// It does **not** load configuration; the caller is responsible for building and passing
451/// a valid `AppConfig`.
452///
453/// Steps performed:
454///
455/// - initializes tracing/logging (once, guarded by a process-wide `Once`) and metrics
456///   when OpenTelemetry is enabled
457/// - registers the panic hook used to route panics through tracing
458/// - emits a small startup span and version metadata for diagnostics
459///
460/// The rustls crypto provider is installed inside this function (idempotent
461/// `OnceLock`), so callers do not need to invoke
462/// [`super::init_crypto_provider`] separately. Direct callers of
463/// [`super::init_crypto_provider`] outside the bootstrap path (e.g. ad-hoc
464/// probe binaries that do not call `run_server` / `run_migrate`) are still
465/// supported.
466///
467/// # Errors
468///
469/// Returns an error if OpenTelemetry tracing initialization fails while
470/// tracing is enabled, or if the crypto provider installation fails.
471#[cfg_attr(not(feature = "otel"), allow(clippy::unnecessary_wraps))]
472pub fn init_procedure(config: &AppConfig) -> Result<()> {
473    // Install the rustls crypto provider FIRST — before anything that may
474    // touch TLS (OTLP exporter over HTTPS, DB connections, etc.). The call
475    // is process-wide and idempotent; calling it twice is safe.
476    super::init_crypto_provider()?;
477
478    // Build OpenTelemetry layer before logging
479    #[cfg(feature = "otel")]
480    let otel_layer = if config.opentelemetry.tracing.enabled {
481        Some(crate::telemetry::init::init_tracing(&config.opentelemetry)?)
482    } else {
483        None
484    };
485    #[cfg(not(feature = "otel"))]
486    let otel_layer = None;
487
488    // Initialize logging + otel in one Registry
489    init_logging_unified(
490        &config.logging,
491        &config.server.home_dir,
492        otel_layer,
493        config.opentelemetry.inject_trace_ids_into_logs(),
494    );
495
496    // Register custom panic hook to reroute panic backtrace into tracing.
497    init_panic_tracing();
498
499    // Initialize OpenTelemetry metrics (or confirm noop when disabled)
500    #[cfg(feature = "otel")]
501    if let Err(e) = crate::telemetry::init::init_metrics_provider(&config.opentelemetry) {
502        tracing::error!(error = %e, "OpenTelemetry metrics not initialized");
503    }
504
505    // One-time connectivity probe
506    #[cfg(feature = "otel")]
507    if config.opentelemetry.tracing.enabled
508        && let Err(e) = crate::telemetry::init::otel_connectivity_probe(&config.opentelemetry)
509    {
510        tracing::error!(error = %e, "OTLP connectivity probe failed");
511    }
512
513    // Smoke test span to confirm traces flow to Jaeger
514    tracing::info_span!("startup_check", app = config.server.name).in_scope(|| {
515        tracing::info!("startup span alive - traces should be visible in Jaeger");
516    });
517
518    tracing::info!(
519        version = env!("CARGO_PKG_VERSION"),
520        rust_version = env!("CARGO_PKG_RUST_VERSION"),
521        "{} Server starting",
522        config.server.name,
523    );
524
525    Ok(())
526}
527
528#[cfg(test)]
529#[cfg_attr(coverage_nightly, coverage(off))]
530mod publish_gts_tests {
531    use super::*;
532    use crate::gts_publication::deployment::{GtsDeploymentOutcome, GtsDeploymentReport};
533
534    #[test]
535    fn deployment_rejects_publication_options_on_a_nonpublishing_gear() {
536        struct PlainGear;
537        #[async_trait::async_trait]
538        impl crate::Gear for PlainGear {
539            async fn init(&self, _ctx: &crate::GearCtx) -> Result<()> {
540                panic!("deployment validation must not initialize gears")
541            }
542        }
543
544        let mut builder = crate::registry::RegistryBuilder::default();
545        builder.register_core_with_meta("plain-gear", &[], Arc::new(PlainGear));
546        let registry = builder.build_topo_sorted().unwrap();
547        let mut config = AppConfig::default();
548        validate_deployment_configuration(&registry, &config).unwrap();
549        config.gears.insert(
550            "plain-gear".to_owned(),
551            serde_json::json!({"config": {"gts_publication": {"timeout": "1s"}}}),
552        );
553        let error = validate_deployment_configuration(&registry, &config).unwrap_err();
554        assert!(error.to_string().contains("plain-gear"), "{error}");
555        assert!(error.to_string().contains("gts_publication"), "{error}");
556    }
557
558    /// `publish-gts --timeout` above 10 minutes is refused first, before the
559    /// registry, the credential or the network; no clamping.
560    #[tokio::test]
561    async fn publish_gts_rejects_a_deadline_above_ten_minutes_first() {
562        let over =
563            crate::gts_publication::MAX_PUBLICATION_BUDGET + std::time::Duration::from_secs(1);
564        let err = publish_gts(
565            &AppConfig::default(),
566            &PublishGtsOptions {
567                registry_endpoint: "https://registry.example:8443".to_owned(),
568                deadline: over,
569            },
570            &CancellationToken::new(),
571        )
572        .await
573        .unwrap_err();
574        let message = format!("{err:#}");
575        assert!(
576            message.contains("--timeout")
577                && message.contains("too large to be a publication budget"),
578            "{message}"
579        );
580    }
581
582    #[test]
583    fn publish_gts_needs_the_platform_credential() {
584        let err = platform_credential(&AppConfig::default()).unwrap_err();
585        assert!(err.to_string().contains("oop_http.internal_auth"), "{err}");
586    }
587
588    /// publish-gts always sends, so a kube block without `present` is refused,
589    /// and the message must not suggest removing the block.
590    #[test]
591    fn publish_gts_needs_a_kube_present_block() {
592        let config = credential_tests::with_internal_auth(&credential_tests::kube_verify_only());
593        let err = platform_credential(&config).unwrap_err().to_string();
594        assert!(
595            err.contains("publish-gts") && err.contains("present.token_path"),
596            "{err}"
597        );
598        assert!(!err.contains("remove the block"), "{err}");
599
600        let config = credential_tests::with_internal_auth(&credential_tests::kube_present());
601        platform_credential(&config).expect("a present block is an outbound credential");
602    }
603
604    #[test]
605    fn a_failed_publisher_fails_the_job_with_the_report() {
606        let failed = GtsDeploymentReport {
607            publishers: vec![
608                ("ok", GtsDeploymentOutcome::Published { documents: 1 }),
609                (
610                    "late",
611                    GtsDeploymentOutcome::DeadlineExceeded {
612                        unconfirmed: vec![
613                            toolkit_gts::gts_id!("cf.test.publication.late.v1~").to_owned(),
614                        ],
615                    },
616                ),
617            ],
618        };
619        let err = publication_result(&failed).unwrap_err();
620        let message = format!("{err:#}");
621        assert!(
622            message.contains("late: deadline exceeded")
623                && message.contains(toolkit_gts::gts_id!("cf.test.publication.late.v1~")),
624            "{message}"
625        );
626
627        let succeeded = GtsDeploymentReport {
628            publishers: vec![("ok", GtsDeploymentOutcome::Published { documents: 1 })],
629        };
630        publication_result(&succeeded).expect("every publisher succeeded");
631    }
632}
633
634#[cfg(test)]
635#[cfg_attr(coverage_nightly, coverage(off))]
636mod credential_tests {
637    use super::*;
638
639    pub(super) fn kube_verify_only() -> serde_json::Value {
640        serde_json::json!({
641            "provider": "kube",
642            "verify": { "audiences": ["toolkit-internal"] }
643        })
644    }
645
646    pub(super) fn kube_present() -> serde_json::Value {
647        serde_json::json!({
648            "provider": "kube",
649            "present": { "token_path": "/var/run/secrets/tokens/toolkit-internal" }
650        })
651    }
652
653    /// An `AppConfig` whose `oop_http.internal_auth` is `internal_auth`.
654    pub(super) fn with_internal_auth(internal_auth: &serde_json::Value) -> AppConfig {
655        let oop_http = serde_json::from_value(serde_json::json!({
656            "listen_addr": "127.0.0.1:0",
657            "internal_auth": internal_auth,
658        }))
659        .expect("valid oop_http config");
660        AppConfig {
661            oop_http: Some(oop_http),
662            ..AppConfig::default()
663        }
664    }
665
666    #[test]
667    fn host_without_internal_auth_has_no_credential() {
668        assert!(
669            host_credential(&AppConfig::default())
670                .expect("Profile 1 needs no credential")
671                .is_none()
672        );
673    }
674
675    /// On the host `verify` is never read, so a verify-only kube block is
676    /// refused with a message that names both fixes.
677    #[test]
678    fn host_refuses_a_kube_block_without_present() {
679        let err = host_credential(&with_internal_auth(&kube_verify_only()))
680            .unwrap_err()
681            .to_string();
682        assert!(
683            err.contains("oop_http.internal_auth")
684                && err.contains("present.token_path")
685                && err.contains("remove the block"),
686            "{err}"
687        );
688    }
689
690    /// Other refusals keep `outbound()`'s own message, with host context.
691    #[test]
692    fn host_refuses_an_unusable_shared_secret() {
693        let err = host_credential(&with_internal_auth(&serde_json::json!({
694            "provider": "shared_secret",
695            "secret": "",
696        })))
697        .unwrap_err()
698        .to_string();
699        assert!(
700            err.contains("oop_http.internal_auth") && err.contains("shared_secret"),
701            "{err}"
702        );
703    }
704
705    #[test]
706    fn host_accepts_an_outbound_credential() {
707        let config = with_internal_auth(&kube_present());
708        assert!(
709            host_credential(&config)
710                .expect("a present block is an outbound credential")
711                .is_some()
712        );
713
714        let config = with_internal_auth(&serde_json::json!({
715            "provider": "shared_secret",
716            "secret": "s",
717        }));
718        assert!(
719            host_credential(&config)
720                .expect("a shared secret is symmetric")
721                .is_some()
722        );
723    }
724}