cf-gears-toolkit 0.16.0

Core ToolKit library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
use super::config::{get_gear_runtime_config, render_gear_config_for_oop};
use super::host::{init_logging_unified, init_panic_tracing, normalize_path};
#[cfg(feature = "otel")]
use super::telemetry::tracing_shutdown;
use super::{AppConfig, RuntimeKind};
use crate::backends::LocalProcessBackend;
use crate::runtime::{
    DbOptions, OopGearSpawnConfig, OopSpawnOptions, RunOptions, ShutdownOptions, run, shutdown,
};
use anyhow::Result;
use figment::Figment;
use figment::providers::Serialized;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use tokio_util::sync::CancellationToken;

/// Spawn a signal handler task that cancels the provided token on SIGTERM/SIGINT.
///
/// This helper consolidates signal handling logic used by both `run_server` and `run_migrate`.
/// The `context` parameter customizes log messages for better diagnostics.
fn spawn_signal_handler(cancel: CancellationToken, context: &str) {
    let context_owned = context.to_owned();
    tokio::spawn(async move {
        match shutdown::wait_for_shutdown().await {
            Ok(()) => {
                tracing::info!(target: "", "------------------");
                tracing::info!("{}: shutdown signal received", context_owned);
            }
            Err(e) => {
                tracing::warn!(
                    error = %e,
                    "{}: signal handler failed, falling back to ctrl_c()",
                    context_owned
                );
                _ = tokio::signal::ctrl_c().await;
            }
        }
        cancel.cancel();
    });
}

/// # Errors
///
/// Returns an error if:
/// - There was a critical error during initialization of the gears
/// - Problems with the database or third-party services
/// - An issue during runtime or shutdown
///
/// The TLS crypto provider is installed automatically as the first step of
/// [`init_procedure`] (idempotent), so callers do not need to invoke
/// [`super::init_crypto_provider`] explicitly.
pub async fn run_server(config: AppConfig) -> Result<()> {
    init_procedure(&config).map_err(|e| {
        tracing::error!(error = %e, "Initialization failed");
        e
    })?;
    tracing::info!("Initializing gears...");

    // Generate process-level instance ID once at startup.
    // This is shared by all gears in this process.
    let instance_id = uuid::Uuid::new_v4();
    tracing::info!(instance_id = %instance_id, "Generated process instance ID");

    // Create root cancellation token for the entire process.
    // This token drives shutdown for the gear runtime and all lifecycle/stateful gears.
    let cancel = CancellationToken::new();

    // Hook OS signals to the root token at the host level.
    // This replaces the use of ShutdownOptions::Signals inside the runtime.
    spawn_signal_handler(cancel.clone(), "server");

    // Build config provider and resolve database options
    let db_options = resolve_db_options(&config)?;

    // Create OoP backend with cancellation token - it will auto-shutdown all processes on cancel
    let oop_backend = LocalProcessBackend::new(cancel.clone());

    // Build OoP spawn configuration
    let oop_options = build_oop_spawn_options(&config, oop_backend)?;

    // Remote platform-plane calls carry `X-ToolKit-Internal-Token` from
    // `oop_http.internal_auth` (cpt-cf-adr-two-plane-auth); without it they fail.
    // Co-hosted dependencies use local ClientHub objects and need no credential.
    let internal_token_provider = match host_credential(&config)? {
        Some(internal_auth) => Some(
            toolkit_contract::runtime::platform_credential::build_internal_token_provider(
                internal_auth,
                &cancel,
            )
            .await?,
        ),
        None => None,
    };

    // Apply configured lifecycle deadlines (absent fields keep framework defaults).
    let init_deadline = config.server.init_deadline();
    let shutdown_deadline = config.server.shutdown_deadline();

    // Run the ToolKit runtime with the root cancellation token.
    // Shutdown is driven by the signal handler spawned above, not by ShutdownOptions::Signals.
    // OoP gears are spawned after parent publication, application startup and
    // REST provider registration, so the parent's complete API is available.
    let run_options = RunOptions::new(
        Arc::new(config),
        db_options,
        ShutdownOptions::Token(cancel.clone()),
        instance_id,
    )
    .with_oop(oop_options)
    .with_internal_token_provider(internal_token_provider)
    .with_init_deadline(init_deadline)
    .with_shutdown_deadline(shutdown_deadline);

    let result = run(run_options).await;

    // Graceful shutdown - flush remaining telemetry
    #[cfg(feature = "otel")]
    tracing_shutdown().await;

    result
}

/// Run database migrations and exit.
///
/// This mode is designed for cloud deployment workflows where database
/// migrations need to run as a separate step before starting the application.
///
/// Phases executed:
/// - Pre-init (wire runtime internals)
/// - DB migration (run all pending migrations)
///
/// The process exits after migrations complete. Any errors are reported
/// and propagated as non-zero exit codes.
///
/// # Errors
///
/// Returns an error if:
/// - No database configuration is found
/// - Gear discovery fails
/// - Pre-init phase fails
/// - Migration phase fails
///
/// The TLS crypto provider is installed automatically as the first step of
/// [`init_procedure`] (idempotent), so callers do not need to invoke
/// [`super::init_crypto_provider`] explicitly.
pub async fn run_migrate(config: AppConfig) -> Result<()> {
    init_procedure(&config).map_err(|e| {
        tracing::error!(error = %e, "Initialization failed");
        e
    })?;
    tracing::info!("Starting migration mode...");

    // Generate process-level instance ID for this migration run
    let instance_id = uuid::Uuid::new_v4();
    tracing::info!(instance_id = %instance_id, "Generated migration instance ID");

    // Create cancellation token and wire it to OS signals
    let cancel = CancellationToken::new();

    // Hook OS signals to enable graceful cancellation of migrations
    spawn_signal_handler(cancel.clone(), "migration");

    // Build database options from configuration
    let db_options = resolve_db_options(&config)?;

    // Verify we have database configuration
    if matches!(db_options, DbOptions::None) {
        anyhow::bail!("Cannot run migrations: no database configuration found");
    }

    // Discover and build the gear registry
    let registry = crate::registry::GearRegistry::discover_and_build()?;
    tracing::info!(
        gear_count = registry.gears().len(),
        "Discovered gears for migration"
    );

    // Create the host runtime
    let host = crate::runtime::HostRuntime::new(
        registry,
        Arc::new(config),
        db_options,
        Arc::new(crate::client_hub::ClientHub::new()),
        cancel,
        instance_id,
        None, // No OoP spawning during migration
    );

    // Run only the migration phases (pre-init + DB migration)
    let result = host.run_migration_phases().await;

    // Graceful shutdown - flush remaining telemetry
    #[cfg(feature = "otel")]
    tracing_shutdown().await;

    result?;

    tracing::info!("All migrations completed successfully");
    Ok(())
}

/// Options of [`run_publish_gts`].
#[derive(Debug, Clone)]
pub struct PublishGtsOptions {
    /// Base URI of the remote registry, e.g. `https://registry:8443`.
    pub registry_endpoint: String,
    /// The overall deadline for every publication; at most
    /// [`MAX_PUBLICATION_BUDGET`](crate::gts_publication::MAX_PUBLICATION_BUDGET) (10 minutes).
    pub deadline: std::time::Duration,
}

/// Publish the GTS manifests of every linked gear to a remote registry and exit:
/// a deployment step.
///
/// No gear runs: no `init`, database, bootstrap or plugin binding. Manifests
/// come from the effective configuration (file, environment overrides,
/// defaults), as at application startup. Requests carry the platform
/// credential of `oop_http.internal_auth`. All publications run concurrently;
/// see [`crate::gts_publication::deployment`].
///
/// # Errors
/// No platform credential is configured, setup fails (manifest, ownership,
/// wiring), or any publisher is refused or misses the deadline: the report is
/// in the error, naming each publisher and its GTS ids.
pub async fn run_publish_gts(config: AppConfig, options: PublishGtsOptions) -> Result<()> {
    init_procedure(&config).map_err(|e| {
        tracing::error!(error = %e, "Initialization failed");
        e
    })?;
    // SIGTERM/SIGINT end the job, reported as cancelled. Dropping this future
    // cancels too: the guard also ends the credential watcher.
    let cancel = CancellationToken::new();
    spawn_signal_handler(cancel.clone(), "publish-gts");
    let _cancel_on_drop = cancel.clone().drop_guard();
    let result = publish_gts(&config, &options, &cancel).await;

    // The outcome is logged before the telemetry flush, on every path.
    match &result {
        Ok(()) => tracing::info!("GTS publication complete"),
        Err(e) => tracing::error!(error = format!("{e:#}"), "GTS publication failed"),
    }
    #[cfg(feature = "otel")]
    tracing_shutdown().await;
    result
}

/// [`run_publish_gts`] after initialization.
async fn publish_gts(
    config: &AppConfig,
    options: &PublishGtsOptions,
    cancel: &CancellationToken,
) -> Result<()> {
    // Reject an over-long deadline before touching the registry or the credential.
    crate::gts_publication::check_publication_budget("--timeout", options.deadline)?;
    // Match startup validation without running gear lifecycle hooks.
    let registry = crate::registry::GearRegistry::discover_and_build()?;
    validate_deployment_configuration(&registry, config)?;
    let internal_auth = platform_credential(config)?;
    let provider = toolkit_contract::runtime::platform_credential::build_internal_token_provider(
        internal_auth,
        cancel,
    )
    .await?;
    let tuning = toolkit_contract::wiring::ClientTuning::default()
        .with_internal_token_provider(Some(provider));
    let descriptors = crate::gts_publication::linked_descriptors();
    tracing::info!(
        publishers = descriptors.len(),
        registry = %options.registry_endpoint,
        "publishing GTS manifests"
    );
    let report = crate::gts_publication::deployment::publish(
        &descriptors,
        config,
        &options.registry_endpoint,
        &tuning,
        options.deadline,
        cancel,
    )
    .await?;
    publication_result(&report)
}

fn validate_deployment_configuration(
    registry: &crate::registry::GearRegistry,
    config: &dyn crate::config::ConfigProvider,
) -> Result<()> {
    for entry in registry.gears() {
        entry.validate_gts_publication_config(config)?;
    }
    Ok(())
}

/// `oop_http.internal_auth`, if configured.
fn oop_internal_auth(config: &AppConfig) -> Option<&toolkit_security::InternalAuthConfig> {
    config
        .oop_http
        .as_ref()
        .and_then(|http| http.internal_auth.as_ref())
}

/// The host process's outbound platform credential: `oop_http.internal_auth`,
/// or `None` when it is unset (Profile 1).
///
/// The host builds no inbound validator from this block; it only presents it on
/// calls to remote dependencies. A kube block without `present` therefore does
/// nothing here, and is refused with a host-specific message rather than the
/// generic one, which assumes the participant sends calls.
///
/// # Errors
/// When [`InternalAuthConfig::outbound`](toolkit_security::InternalAuthConfig::outbound)
/// refuses `oop_http.internal_auth`.
fn host_credential(config: &AppConfig) -> Result<Option<&toolkit_security::InternalAuthConfig>> {
    let Some(internal_auth) = oop_internal_auth(config) else {
        return Ok(None);
    };
    match internal_auth.outbound() {
        Ok(_) => Ok(Some(internal_auth)),
        Err(toolkit_security::InvalidOutboundAuth::MissingKubePresent) => anyhow::bail!(
            "oop_http.internal_auth (provider: kube) has no `present:` block. The host process \
             uses this block only as the outbound credential for remote platform-plane calls \
             (`verify` is not used here): set `present.token_path`, or remove the block if no \
             gear in this process has a remote dependency"
        ),
        Err(err) => anyhow::bail!(
            "oop_http.internal_auth is unusable as the host's outbound credential: {err}"
        ),
    }
}

/// The platform credential `publish-gts` sends: `oop_http.internal_auth`.
///
/// # Errors
/// When `oop_http.internal_auth` is unset, or
/// [`InternalAuthConfig::outbound`](toolkit_security::InternalAuthConfig::outbound)
/// refuses it: publish-gts always sends platform-plane calls.
fn platform_credential(config: &AppConfig) -> Result<&toolkit_security::InternalAuthConfig> {
    let internal_auth = oop_internal_auth(config).ok_or_else(|| {
        anyhow::anyhow!("publish-gts needs a platform credential: configure oop_http.internal_auth")
    })?;
    internal_auth.outbound().map_err(|err| {
        anyhow::anyhow!(
            "publish-gts sends platform-plane calls, but oop_http.internal_auth is unusable as \
             its credential: {err}"
        )
    })?;
    Ok(internal_auth)
}

/// The job's result: an error carrying the report unless every publisher succeeded.
fn publication_result(
    report: &crate::gts_publication::deployment::GtsDeploymentReport,
) -> Result<()> {
    if report.succeeded() {
        tracing::info!("GTS publication report:\n{report}");
        Ok(())
    } else {
        anyhow::bail!("GTS publication failed:\n{report}")
    }
}

fn resolve_db_options(config: &AppConfig) -> Result<DbOptions> {
    if config.database.is_none() {
        tracing::warn!("No global database section found; running without databases");
        return Ok(DbOptions::None);
    }

    tracing::info!("Using DbManager with Figment-based configuration");
    let figment = Figment::new().merge(Serialized::defaults(config));
    let db_manager = Arc::new(toolkit_db::DbManager::from_figment(
        figment,
        config.server.home_dir.clone(),
    )?);
    Ok(DbOptions::Manager(db_manager))
}

/// Build `OoP` spawn configuration from `AppConfig`.
///
/// This collects all gears with `type=oop` and prepares their spawn configuration.
/// The actual spawning happens in the `HostRuntime` after parent startup.
fn build_oop_spawn_options(
    config: &AppConfig,
    backend: LocalProcessBackend,
) -> Result<Option<OopSpawnOptions>> {
    let home_dir = PathBuf::from(&config.server.home_dir);
    let mut gears = Vec::new();

    for gear_name in config.gears.keys() {
        if let Some(spawn_config) = try_build_oop_gear_config(config, gear_name, &home_dir)? {
            gears.push(spawn_config);
        }
    }

    if gears.is_empty() {
        Ok(None)
    } else {
        tracing::info!(count = gears.len(), "Prepared OoP gears for spawning");
        Ok(Some(OopSpawnOptions {
            gears,
            backend: Box::new(backend),
        }))
    }
}

/// Try to build `OoP` gear spawn config if gear is of type `OoP`
fn try_build_oop_gear_config(
    config: &AppConfig,
    gear_name: &str,
    home_dir: &Path,
) -> Result<Option<OopGearSpawnConfig>> {
    let Some(runtime_cfg) = get_gear_runtime_config(config, gear_name)? else {
        return Ok(None);
    };

    if !matches!(runtime_cfg.mod_type, RuntimeKind::Oop) {
        return Ok(None);
    }

    let exec_cfg = runtime_cfg.execution.as_ref().ok_or_else(|| {
        anyhow::anyhow!("gear '{gear_name}' is type=oop but execution config is missing")
    })?;

    let binary = normalize_path(&exec_cfg.executable_path)?;
    let spawn_args = exec_cfg.args.clone();
    let env = exec_cfg.environment.clone();

    // Render the complete gear config (with resolved DB)
    let rendered_config = render_gear_config_for_oop(config, gear_name, home_dir)?;
    let rendered_json = rendered_config.to_json()?;

    tracing::debug!(
        gear =  %gear_name,
        "Prepared OoP gear config: db={}",
        rendered_config.database.is_some()
    );

    Ok(Some(OopGearSpawnConfig {
        gear_name: gear_name.to_owned(),
        binary,
        args: spawn_args,
        env,
        working_directory: exec_cfg.working_directory.clone(),
        rendered_config_json: rendered_json,
    }))
}

/// Initialize process-wide bootstrap state from a provided `&AppConfig`.
///
/// This helper performs the common startup sequence shared by server and migration modes.
/// It does **not** load configuration; the caller is responsible for building and passing
/// a valid `AppConfig`.
///
/// Steps performed:
///
/// - initializes tracing/logging (once, guarded by a process-wide `Once`) and metrics
///   when OpenTelemetry is enabled
/// - registers the panic hook used to route panics through tracing
/// - emits a small startup span and version metadata for diagnostics
///
/// The rustls crypto provider is installed inside this function (idempotent
/// `OnceLock`), so callers do not need to invoke
/// [`super::init_crypto_provider`] separately. Direct callers of
/// [`super::init_crypto_provider`] outside the bootstrap path (e.g. ad-hoc
/// probe binaries that do not call `run_server` / `run_migrate`) are still
/// supported.
///
/// # Errors
///
/// Returns an error if OpenTelemetry tracing initialization fails while
/// tracing is enabled, or if the crypto provider installation fails.
#[cfg_attr(not(feature = "otel"), allow(clippy::unnecessary_wraps))]
pub fn init_procedure(config: &AppConfig) -> Result<()> {
    // Install the rustls crypto provider FIRST — before anything that may
    // touch TLS (OTLP exporter over HTTPS, DB connections, etc.). The call
    // is process-wide and idempotent; calling it twice is safe.
    super::init_crypto_provider()?;

    // Build OpenTelemetry layer before logging
    #[cfg(feature = "otel")]
    let otel_layer = if config.opentelemetry.tracing.enabled {
        Some(crate::telemetry::init::init_tracing(&config.opentelemetry)?)
    } else {
        None
    };
    #[cfg(not(feature = "otel"))]
    let otel_layer = None;

    // Initialize logging + otel in one Registry
    init_logging_unified(
        &config.logging,
        &config.server.home_dir,
        otel_layer,
        config.opentelemetry.inject_trace_ids_into_logs(),
    );

    // Register custom panic hook to reroute panic backtrace into tracing.
    init_panic_tracing();

    // Initialize OpenTelemetry metrics (or confirm noop when disabled)
    #[cfg(feature = "otel")]
    if let Err(e) = crate::telemetry::init::init_metrics_provider(&config.opentelemetry) {
        tracing::error!(error = %e, "OpenTelemetry metrics not initialized");
    }

    // One-time connectivity probe
    #[cfg(feature = "otel")]
    if config.opentelemetry.tracing.enabled
        && let Err(e) = crate::telemetry::init::otel_connectivity_probe(&config.opentelemetry)
    {
        tracing::error!(error = %e, "OTLP connectivity probe failed");
    }

    // Smoke test span to confirm traces flow to Jaeger
    tracing::info_span!("startup_check", app = config.server.name).in_scope(|| {
        tracing::info!("startup span alive - traces should be visible in Jaeger");
    });

    tracing::info!(
        version = env!("CARGO_PKG_VERSION"),
        rust_version = env!("CARGO_PKG_RUST_VERSION"),
        "{} Server starting",
        config.server.name,
    );

    Ok(())
}

#[cfg(test)]
#[cfg_attr(coverage_nightly, coverage(off))]
mod publish_gts_tests {
    use super::*;
    use crate::gts_publication::deployment::{GtsDeploymentOutcome, GtsDeploymentReport};

    #[test]
    fn deployment_rejects_publication_options_on_a_nonpublishing_gear() {
        struct PlainGear;
        #[async_trait::async_trait]
        impl crate::Gear for PlainGear {
            async fn init(&self, _ctx: &crate::GearCtx) -> Result<()> {
                panic!("deployment validation must not initialize gears")
            }
        }

        let mut builder = crate::registry::RegistryBuilder::default();
        builder.register_core_with_meta("plain-gear", &[], Arc::new(PlainGear));
        let registry = builder.build_topo_sorted().unwrap();
        let mut config = AppConfig::default();
        validate_deployment_configuration(&registry, &config).unwrap();
        config.gears.insert(
            "plain-gear".to_owned(),
            serde_json::json!({"config": {"gts_publication": {"timeout": "1s"}}}),
        );
        let error = validate_deployment_configuration(&registry, &config).unwrap_err();
        assert!(error.to_string().contains("plain-gear"), "{error}");
        assert!(error.to_string().contains("gts_publication"), "{error}");
    }

    /// `publish-gts --timeout` above 10 minutes is refused first, before the
    /// registry, the credential or the network; no clamping.
    #[tokio::test]
    async fn publish_gts_rejects_a_deadline_above_ten_minutes_first() {
        let over =
            crate::gts_publication::MAX_PUBLICATION_BUDGET + std::time::Duration::from_secs(1);
        let err = publish_gts(
            &AppConfig::default(),
            &PublishGtsOptions {
                registry_endpoint: "https://registry.example:8443".to_owned(),
                deadline: over,
            },
            &CancellationToken::new(),
        )
        .await
        .unwrap_err();
        let message = format!("{err:#}");
        assert!(
            message.contains("--timeout")
                && message.contains("too large to be a publication budget"),
            "{message}"
        );
    }

    #[test]
    fn publish_gts_needs_the_platform_credential() {
        let err = platform_credential(&AppConfig::default()).unwrap_err();
        assert!(err.to_string().contains("oop_http.internal_auth"), "{err}");
    }

    /// publish-gts always sends, so a kube block without `present` is refused,
    /// and the message must not suggest removing the block.
    #[test]
    fn publish_gts_needs_a_kube_present_block() {
        let config = credential_tests::with_internal_auth(&credential_tests::kube_verify_only());
        let err = platform_credential(&config).unwrap_err().to_string();
        assert!(
            err.contains("publish-gts") && err.contains("present.token_path"),
            "{err}"
        );
        assert!(!err.contains("remove the block"), "{err}");

        let config = credential_tests::with_internal_auth(&credential_tests::kube_present());
        platform_credential(&config).expect("a present block is an outbound credential");
    }

    #[test]
    fn a_failed_publisher_fails_the_job_with_the_report() {
        let failed = GtsDeploymentReport {
            publishers: vec![
                ("ok", GtsDeploymentOutcome::Published { documents: 1 }),
                (
                    "late",
                    GtsDeploymentOutcome::DeadlineExceeded {
                        unconfirmed: vec![
                            toolkit_gts::gts_id!("cf.test.publication.late.v1~").to_owned(),
                        ],
                    },
                ),
            ],
        };
        let err = publication_result(&failed).unwrap_err();
        let message = format!("{err:#}");
        assert!(
            message.contains("late: deadline exceeded")
                && message.contains(toolkit_gts::gts_id!("cf.test.publication.late.v1~")),
            "{message}"
        );

        let succeeded = GtsDeploymentReport {
            publishers: vec![("ok", GtsDeploymentOutcome::Published { documents: 1 })],
        };
        publication_result(&succeeded).expect("every publisher succeeded");
    }
}

#[cfg(test)]
#[cfg_attr(coverage_nightly, coverage(off))]
mod credential_tests {
    use super::*;

    pub(super) fn kube_verify_only() -> serde_json::Value {
        serde_json::json!({
            "provider": "kube",
            "verify": { "audiences": ["toolkit-internal"] }
        })
    }

    pub(super) fn kube_present() -> serde_json::Value {
        serde_json::json!({
            "provider": "kube",
            "present": { "token_path": "/var/run/secrets/tokens/toolkit-internal" }
        })
    }

    /// An `AppConfig` whose `oop_http.internal_auth` is `internal_auth`.
    pub(super) fn with_internal_auth(internal_auth: &serde_json::Value) -> AppConfig {
        let oop_http = serde_json::from_value(serde_json::json!({
            "listen_addr": "127.0.0.1:0",
            "internal_auth": internal_auth,
        }))
        .expect("valid oop_http config");
        AppConfig {
            oop_http: Some(oop_http),
            ..AppConfig::default()
        }
    }

    #[test]
    fn host_without_internal_auth_has_no_credential() {
        assert!(
            host_credential(&AppConfig::default())
                .expect("Profile 1 needs no credential")
                .is_none()
        );
    }

    /// On the host `verify` is never read, so a verify-only kube block is
    /// refused with a message that names both fixes.
    #[test]
    fn host_refuses_a_kube_block_without_present() {
        let err = host_credential(&with_internal_auth(&kube_verify_only()))
            .unwrap_err()
            .to_string();
        assert!(
            err.contains("oop_http.internal_auth")
                && err.contains("present.token_path")
                && err.contains("remove the block"),
            "{err}"
        );
    }

    /// Other refusals keep `outbound()`'s own message, with host context.
    #[test]
    fn host_refuses_an_unusable_shared_secret() {
        let err = host_credential(&with_internal_auth(&serde_json::json!({
            "provider": "shared_secret",
            "secret": "",
        })))
        .unwrap_err()
        .to_string();
        assert!(
            err.contains("oop_http.internal_auth") && err.contains("shared_secret"),
            "{err}"
        );
    }

    #[test]
    fn host_accepts_an_outbound_credential() {
        let config = with_internal_auth(&kube_present());
        assert!(
            host_credential(&config)
                .expect("a present block is an outbound credential")
                .is_some()
        );

        let config = with_internal_auth(&serde_json::json!({
            "provider": "shared_secret",
            "secret": "s",
        }));
        assert!(
            host_credential(&config)
                .expect("a shared secret is symmetric")
                .is_some()
        );
    }
}