canic-cli 0.78.1

Operator CLI for Canic fleet setup, builds, evidence, catalog, backup, and restore workflows
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
use super::*;
use crate::test_support::temp_dir;
use crate::{CliError, cli_error_exit_code, render_cli_error};
use serde_json::Value as JsonValue;
use std::fs;

// Ensure bare top-level medic selects the project scope without inventing a deployment.
#[test]
fn parses_bare_project_medic_options() {
    let options = MedicOptions::parse([
        OsString::from(crate::cli::globals::INTERNAL_ICP_OPTION),
        OsString::from("/tmp/icp"),
    ])
    .expect("parse medic options");

    assert_eq!(options.scope, MedicScope::Project);
    assert_eq!(options.deployment, None);
    assert_eq!(options.network, None);
    assert_eq!(options.icp, "/tmp/icp");
}

// Ensure explicit project medic keeps the same scope and accepts JSON output.
#[test]
fn parses_project_medic_options() {
    let options = MedicOptions::parse([OsString::from("project"), OsString::from("--json")])
        .expect("parse medic project options");

    assert_eq!(options.scope, MedicScope::Project);
    assert!(options.json);
    assert_eq!(options.deployment, None);
}

// Ensure deployment medic parses target, network, and ICP selectors.
#[test]
fn parses_deployment_medic_options() {
    let options = MedicOptions::parse([
        OsString::from("deployment"),
        OsString::from("demo"),
        OsString::from(crate::cli::globals::INTERNAL_NETWORK_OPTION),
        OsString::from("local"),
        OsString::from(crate::cli::globals::INTERNAL_ICP_OPTION),
        OsString::from("/tmp/icp"),
    ])
    .expect("parse medic deployment options");

    assert_eq!(options.scope, MedicScope::Deployment);
    assert_eq!(options.deployment.as_deref(), Some("demo"));
    assert_eq!(options.network.as_deref(), Some("local"));
    assert_eq!(options.icp, "/tmp/icp");
}

// Ensure targeted blob-storage medic diagnostics are deployment-only.
#[test]
fn parses_deployment_blob_storage_medic_target() {
    let options = MedicOptions::parse([
        OsString::from("deployment"),
        OsString::from("demo"),
        OsString::from("--blob-storage"),
        OsString::from("backend"),
    ])
    .expect("parse medic options");

    assert_eq!(options.deployment.as_deref(), Some("demo"));
    assert_eq!(options.blob_storage.as_deref(), Some("backend"));
}

// Ensure targeted auth-renewal medic diagnostics are deployment-only.
#[test]
fn parses_deployment_auth_renewal_medic_target() {
    let options = MedicOptions::parse([
        OsString::from("deployment"),
        OsString::from("demo"),
        OsString::from("--auth-renewal"),
        OsString::from("rrkah-fqaaa-aaaaa-aaaaq-cai"),
    ])
    .expect("parse medic options");

    assert_eq!(options.deployment.as_deref(), Some("demo"));
    assert_eq!(
        options.auth_renewal.as_deref(),
        Some("rrkah-fqaaa-aaaaa-aaaaq-cai")
    );
}

// Ensure hard-cut rejected command forms do not parse as compatibility aliases.
#[test]
fn rejects_legacy_or_shorthand_medic_forms() {
    for args in [
        vec![OsString::from("demo")],
        vec![OsString::from("--blob-storage"), OsString::from("backend")],
        vec![
            OsString::from("--auth-renewal"),
            OsString::from("rrkah-fqaaa-aaaaa-aaaaq-cai"),
        ],
        vec![
            OsString::from("project"),
            OsString::from("--blob-storage"),
            OsString::from("backend"),
        ],
        vec![
            OsString::from("project"),
            OsString::from("--auth-renewal"),
            OsString::from("rrkah-fqaaa-aaaaa-aaaaq-cai"),
        ],
    ] {
        assert!(matches!(
            MedicOptions::parse(args),
            Err(MedicCommandError::Usage(_))
        ));
    }
}

// Ensure medic help explains the new top-level command surface.
#[test]
fn medic_usage_includes_top_level_examples() {
    let text = usage();

    assert!(text.contains("Diagnose Canic project and deployment preflight readiness"));
    assert!(text.contains("Usage: canic medic"));
    assert!(text.contains("canic medic project"));
    assert!(text.contains("canic medic deployment test"));
    assert!(text.contains("canic medic deployment test --blob-storage backend"));
    assert!(text.contains("canic medic deployment test --auth-renewal"));
    assert!(text.contains("--json"));
    assert!(!text.contains("canic info medic"));
}

// Ensure aggregate status follows the 0.78 report contract.
#[test]
fn aggregate_status_follows_report_contract() {
    assert_eq!(aggregate_status(&[]), MedicStatus::NotEvaluated);
    assert_eq!(
        aggregate_status(&[MedicCheck::not_evaluated(
            MedicCategory::DeploymentState,
            "deployment_not_selected",
            "deployment",
            "none",
            "none",
            MedicSource::Command,
        )]),
        MedicStatus::NotEvaluated
    );
    assert_eq!(
        aggregate_status(&[
            sample_check(MedicStatus::Pass),
            sample_check(MedicStatus::NotEvaluated)
        ]),
        MedicStatus::Pass
    );
    assert_eq!(
        aggregate_status(&[
            sample_check(MedicStatus::Pass),
            sample_check(MedicStatus::Warn)
        ]),
        MedicStatus::Warn
    );
    assert_eq!(
        aggregate_status(&[
            sample_check(MedicStatus::Warn),
            sample_check(MedicStatus::Fail)
        ]),
        MedicStatus::Fail
    );
}

// Ensure the text report carries status, category, code, detail, next, and source.
#[test]
fn renders_medic_text_report() {
    let report = MedicReport::new(
        &MedicOptions::project(false, None, "icp".to_string()),
        vec![
            MedicCheck::warn(
                MedicCategory::ProjectConfig,
                "local_network_implicit",
                "network",
                "no network was selected",
                "select an explicit network before deployment checks",
                MedicSource::IcpConfig,
            ),
            MedicCheck::pass(
                MedicCategory::Environment,
                "icp_cli_ok",
                "icp",
                "icp 1.0.0",
                "none",
                MedicSource::IcpCli,
            ),
        ],
    );
    let rendered = render_medic_text(&report);

    assert!(rendered.starts_with("canic medic project\nstatus: warn"));
    assert!(rendered.contains("network: not selected"));
    assert!(rendered.contains("environment [pass] icp_cli_ok"));
    assert!(rendered.contains("project_config [warn] local_network_implicit"));
    assert!(rendered.contains("  detail: no network was selected"));
    assert!(rendered.contains("  next: select an explicit network"));
    assert!(rendered.contains("  source: icp_config"));
}

// Ensure JSON output emits schema_version and stable top-level fields.
#[test]
fn renders_medic_json_report() {
    let report = MedicReport::new(
        &MedicOptions::project(true, None, "icp".to_string()),
        vec![sample_check(MedicStatus::Pass)],
    );
    let rendered = render_medic_json(&report).expect("render json");
    let value: JsonValue = serde_json::from_str(&rendered).expect("parse json");

    assert!(rendered.trim_start().starts_with('{'));
    assert!(!rendered.contains("status:"));
    assert!(!rendered.contains("detail:"));
    assert!(!rendered.contains("source:"));
    assert_eq!(value["schema_version"], 1);
    assert_eq!(value["command"], "canic medic project");
    assert_eq!(value["scope"], "project");
    assert_eq!(value["network"], JsonValue::Null);
    assert_eq!(value["deployment"], JsonValue::Null);
    assert_eq!(value["status"], "pass");
    assert!(value["checks"].is_array());
}

// Ensure medic errors keep the process-level exit-code contract from the 0.78 design.
#[test]
fn medic_cli_errors_map_to_designed_exit_codes() {
    let usage = CliError::from(MedicCommandError::Usage("bad medic args".to_string()));
    let report_failed = CliError::from(MedicCommandError::ReportFailed);
    let json = CliError::from(MedicCommandError::Json(
        serde_json::from_str::<JsonValue>("{").expect_err("invalid json"),
    ));

    assert_eq!(cli_error_exit_code(&usage), 2);
    assert_eq!(cli_error_exit_code(&report_failed), 1);
    assert_eq!(cli_error_exit_code(&json), 3);
}

// Ensure aggregate fail reports do not add duplicate human diagnostics to stderr.
#[test]
fn failed_medic_report_suppresses_cli_stderr() {
    let cli_error = CliError::from(MedicCommandError::ReportFailed);

    assert_eq!(cli_error_exit_code(&cli_error), 1);
    assert_eq!(render_cli_error(&cli_error), "");
}

// Ensure usage and internal errors still produce stderr diagnostics.
#[test]
fn medic_usage_and_internal_errors_render_cli_stderr() {
    let usage = CliError::from(MedicCommandError::Usage("bad medic args".to_string()));
    let json = CliError::from(MedicCommandError::Json(
        serde_json::from_str::<JsonValue>("{").expect_err("invalid json"),
    ));

    assert_eq!(render_cli_error(&usage), "medic: bad medic args");
    assert!(render_cli_error(&json).contains("medic: failed to render medic JSON output"));
}

// Ensure deployment reports include the effective network while project reports may omit it.
#[test]
fn deployment_report_includes_effective_network() {
    let report = MedicReport::new(
        &MedicOptions {
            scope: MedicScope::Deployment,
            deployment: Some("demo".to_string()),
            blob_storage: None,
            auth_renewal: None,
            json: false,
            network: None,
            icp: "icp".to_string(),
        },
        vec![sample_check(MedicStatus::Pass)],
    );

    assert_eq!(report.network.as_deref(), Some("local"));
    assert_eq!(report.deployment.as_deref(), Some("demo"));
}

// Ensure check ordering is deterministic by category.
#[test]
fn orders_checks_by_category() {
    let report = MedicReport::new(
        &MedicOptions::project(false, None, "icp".to_string()),
        vec![
            MedicCheck::pass(
                MedicCategory::BlobStorage,
                "blob_storage_not_selected",
                "blob_storage",
                "none",
                "none",
                MedicSource::Command,
            ),
            MedicCheck::pass(
                MedicCategory::Environment,
                "icp_cli_ok",
                "icp",
                "ok",
                "none",
                MedicSource::IcpCli,
            ),
        ],
    );

    assert_eq!(report.checks[0].category, MedicCategory::Environment);
    assert_eq!(report.checks[1].category, MedicCategory::BlobStorage);
}

// Ensure blob-storage medic uses the shared status summary without reinterpreting warnings.
#[test]
fn renders_blob_storage_medic_summary() {
    let check = blob_storage_medic_check_from_summary(BlobStorageMedicSummary {
        status: BlobStorageMedicStatus::Warning,
        detail: "readiness=warning; configured=true; gateways=0; funding=funding_needed"
            .to_string(),
        next: "canic blob-storage sync-gateways demo backend".to_string(),
    });
    let report = render_medic_text(&MedicReport::new(
        &MedicOptions::project(false, None, "icp".to_string()),
        vec![check],
    ));

    assert!(report.contains("blob_storage [warn] blob_storage_billing_unready"));
    assert!(report.contains("readiness=warning"));
    assert!(report.contains("canic blob-storage sync-gateways demo backend"));
}

// Ensure auth-renewal medic uses the shared auth summary without mutating renewal state.
#[test]
fn renders_auth_renewal_medic_summary() {
    let check = auth_renewal_medic_check_from_summary(AuthRenewalMedicSummary {
        status: AuthRenewalMedicStatus::Warning,
        detail: "status=drift_detected; issuer_observation=drift_detected; drift_detected=true"
            .to_string(),
        next: "canic auth renewal status demo --issuer rrkah-fqaaa-aaaaa-aaaaq-cai".to_string(),
    });
    let report = render_medic_text(&MedicReport::new(
        &MedicOptions::project(false, None, "icp".to_string()),
        vec![check],
    ));

    assert!(report.contains("auth [warn] auth_renewal_drift_warn"));
    assert!(report.contains("status=drift_detected"));
    assert!(report.contains("canic auth renewal status demo --issuer"));
}

// Ensure default deployment medic can discover blob-storage-capable local Candid sidecars passively.
#[test]
fn passive_blob_storage_hint_uses_local_candid_only() {
    let root = temp_dir("canic-cli-medic-blob-storage-passive");
    write_candid(
        &root,
        "local",
        "backend",
        r#"
            service : {
                get_blob_storage_status : () -> () query;
                "_immutableObjectStorageUpdateGatewayPrincipals" : () -> ();
                "_immutableObjectStorageFundFromProjectCycles" : (nat) -> ();
            }
        "#,
    );
    write_candid(
        &root,
        "local",
        "other",
        r"
            service : {
                get_blob_storage_status : () -> () query;
            }
        ",
    );

    let roles = blob_storage_billing_roles_from_candid_dir(&root, "local");
    let options = MedicOptions {
        scope: MedicScope::Deployment,
        deployment: Some("demo".to_string()),
        blob_storage: None,
        auth_renewal: None,
        json: false,
        network: Some("local".to_string()),
        icp: "icp".to_string(),
    };
    let check = check_blob_storage_not_selected(&options, Some(&root), "local");

    assert_eq!(roles, vec!["backend".to_string()]);
    assert_eq!(check.status, MedicStatus::NotEvaluated);
    assert_eq!(check.code, "blob_storage_not_selected");
    assert_eq!(
        check.next,
        "run canic medic deployment demo --blob-storage backend"
    );

    fs::remove_dir_all(root).expect("remove temp root");
}

// Ensure passive Candid detection only accepts the full billing endpoint trio.
#[test]
fn blob_storage_passive_detection_rejects_partial_or_unrelated_candid() {
    assert!(candid_declares_blob_storage_billing(
        r#"
            service : {
                get_blob_storage_status : () -> () query;
                "_immutableObjectStorageUpdateGatewayPrincipals" : () -> ();
                "_immutableObjectStorageFundFromProjectCycles" : (nat) -> ();
            }
        "#
    ));
    assert!(!candid_declares_blob_storage_billing(
        r#"
            service : {
                get_blob_storage_status : () -> () query;
                "_immutableObjectStorageUpdateGatewayPrincipals" : () -> ();
            }
        "#
    ));
    assert!(!candid_declares_blob_storage_billing(
        r"
            service : {
                canic_ready : () -> (bool) query;
            }
        "
    ));
}

// Ensure long medic details and next actions wrap to terminal-readable lines.
#[test]
fn wraps_long_medic_report_fields() {
    let report = render_medic_text(&MedicReport::new(
        &MedicOptions::project(false, None, "icp".to_string()),
        vec![MedicCheck::warn(
            MedicCategory::DeploymentState,
            "deployment_target_missing",
            "deployment",
            "this is a deliberately long diagnostic message that should wrap across multiple indented lines instead of widening a terminal table",
            "run canic install <fleet-template> or canic deploy register <deployment> --fleet-template <fleet-template> --root <principal> --allow-unverified",
            MedicSource::InstalledDeployment,
        )],
    ));

    assert!(report.contains("deployment_state [warn] deployment_target_missing"));
    assert!(
        report
            .lines()
            .all(|line| line.chars().count() <= MEDIC_REPORT_WIDTH)
    );
    assert!(
        report
            .lines()
            .any(|line| line.starts_with("          ") && !line.trim().is_empty())
    );
}

// Ensure ICP identity session guidance stays informational and versionless.
#[test]
fn icp_identity_session_cache_hint_is_informational() {
    let check = check_icp_identity_session_cache_hint();

    assert_eq!(check.status, MedicStatus::Pass);
    assert_eq!(check.code, "icp_identity_session_hint");
    assert!(check.detail.contains("PEM identities"));
    assert!(check.next.contains("icp settings session-length"));
    assert!(check.next.contains("icp identity reauth"));
    assert!(!check.next.contains("1.0.0"));
}

// Ensure host installed-deployment missing-state errors remain classifiable.
#[test]
fn missing_installed_deployment_error_is_classifiable() {
    assert!(is_missing_installed_deployment(
        "deployment target demo is not installed on network local"
    ));
    assert!(!is_missing_installed_deployment(
        "failed to read canic deployment state: bad json"
    ));
}

fn sample_check(status: MedicStatus) -> MedicCheck {
    MedicCheck::new(
        MedicCategory::Environment,
        "sample",
        status,
        "subject",
        "detail",
        "next",
        MedicSource::Command,
    )
}

fn write_candid(root: &std::path::Path, network: &str, role: &str, candid: &str) {
    let path = local_canister_candid_path(root, network, role);
    fs::create_dir_all(path.parent().expect("candid parent")).expect("create candid parent");
    fs::write(path, candid).expect("write candid");
}