canic 0.110.30

Canic — a canister orchestration and management toolkit for the Internet Computer
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
use std::{error::Error, fmt, fs, io, path::Path};

use canic_core::{
    bootstrap::{
        compact_config_source,
        compiled::{ConfigModel, validate_canister_role_name},
        emit_config_model_source, emit_role_runtime_authority_source,
    },
    ids::CanisterRole,
};
use toml::Value as TomlValue;

/// Root-only build outputs retained by the full control-plane configuration owner.
#[derive(Clone, Debug)]
pub struct RootBuildSources {
    pub compact_config: String,
    pub config_model: String,
}

/// Exact generated source set for one canister role.
#[derive(Clone, Debug)]
pub struct RoleBuildSources {
    pub role_runtime_authority: String,
    pub root: Option<RootBuildSources>,
}

/// Failure while compiling the exact generated source set for one role.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RoleBuildSourcesError {
    detail: String,
}

impl fmt::Display for RoleBuildSourcesError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(&self.detail)
    }
}

impl Error for RoleBuildSourcesError {}

///
/// PackageCanicMetadata
///
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PackageCanicMetadata {
    pub app: String,
    pub role: String,
}

/// Compile only the generated sources owned by one exact role artifact.
pub fn compile_role_build_sources(
    config: &ConfigModel,
    config_source: &str,
    role: &CanisterRole,
    wasm_store: bool,
) -> Result<RoleBuildSources, RoleBuildSourcesError> {
    let role_runtime_authority = emit_role_runtime_authority_source(config, role, wasm_store)
        .map_err(|error| RoleBuildSourcesError {
            detail: error.to_string(),
        })?;
    let root = role.is_root().then(|| RootBuildSources {
        compact_config: compact_config_source(config_source),
        config_model: emit_config_model_source(config),
    });

    Ok(RoleBuildSources {
        role_runtime_authority,
        root,
    })
}

/// Preserve unchanged generated source timestamps so output repair watches settle.
///
/// Missing or different source is recreated from the current configuration.
/// Linked output files reject before reading or writing another checkout's source.
pub fn write_build_source_if_changed(path: &Path, source: &str) -> io::Result<()> {
    match fs::symlink_metadata(path) {
        Ok(metadata) if metadata.file_type().is_symlink() => {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                format!(
                    "generated build source is a symlink: {}; use an independent Cargo target/build directory",
                    path.display()
                ),
            ));
        }
        Ok(_) => {}
        Err(error) if error.kind() == io::ErrorKind::NotFound => {}
        Err(error) => return Err(error),
    }
    match fs::read(path) {
        Ok(existing) if existing == source.as_bytes() => return Ok(()),
        Ok(_) => {}
        Err(error) if error.kind() == io::ErrorKind::NotFound => {}
        Err(error) => return Err(error),
    }
    fs::write(path, source)
}

/// Reject authoritative wasm builds that bypass host role-contract validation.
///
/// # Panics
///
/// Panics for the canonical canister wasm target when the private host marker
/// is absent.
pub fn assert_canonical_role_contract_build(target: &str, marker: Option<&str>) {
    assert!(
        target != "wasm32-unknown-unknown"
            || marker == Some(canic_core::role_contract::CANONICAL_BUILD_MARKER_VALUE),
        "authoritative Canic wasm builds must use `canic build <app>` or `canic build <app> <role>`; direct `cargo build --target wasm32-unknown-unknown` is unsupported"
    );
}

/// Read a Canic config source, or generate a minimal standalone config when allowed.
///
/// # Panics
///
/// Panics when the config file is missing and no default role is available,
/// when an explicitly requested config file is missing, or when reading an
/// existing config file fails.
#[must_use]
pub fn read_config_source_or_default(
    config_path: &Path,
    explicit_config: bool,
    default_role: Option<&str>,
) -> (String, bool) {
    match fs::read_to_string(config_path) {
        Ok(source) => (source, false),
        Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
            let role = default_role
                .unwrap_or_else(|| panic!("Missing Canic config at {}", config_path.display()));

            assert!(
                !explicit_config,
                "Missing explicit Canic config at {}",
                config_path.display()
            );

            (standalone_config_source(role), true)
        }
        Err(err) => panic!("Failed to read {}: {err}", config_path.display()),
    }
}

/// Read optional Canic metadata declared in the package manifest.
#[must_use]
pub fn declared_package_metadata(manifest_dir: &Path) -> Option<PackageCanicMetadata> {
    let manifest = fs::read_to_string(manifest_dir.join("Cargo.toml")).ok()?;
    let canic = toml::from_str::<TomlValue>(&manifest)
        .ok()?
        .get("package")?
        .get("metadata")?
        .get("canic")?
        .clone();
    let app = canic.get("app")?.as_str()?.to_string();
    let role = canic.get("role")?.as_str()?.to_string();

    Some(PackageCanicMetadata { app, role })
}

/// Read an optional Canic role declared in the package manifest metadata.
#[must_use]
pub fn declared_package_role(manifest_dir: &Path) -> Option<String> {
    declared_package_metadata(manifest_dir).map(|metadata| metadata.role)
}

/// Read the required Canic metadata declared in package manifest metadata.
///
/// # Panics
///
/// Panics when `Cargo.toml` does not declare `[package.metadata.canic]` with
/// both `app` and `role`.
#[must_use]
pub fn required_package_metadata(manifest_dir: &Path) -> PackageCanicMetadata {
    let manifest_path = manifest_dir.join("Cargo.toml");
    declared_package_metadata(manifest_dir).unwrap_or_else(|| {
        panic!(
            "missing Canic package metadata in {}; add [package.metadata.canic] app = \"<app>\" and role = \"<role>\"",
            manifest_path.display()
        )
    })
}

/// Read the required Canic role declared in package manifest metadata.
#[must_use]
pub fn required_package_role(manifest_dir: &Path) -> String {
    required_package_metadata(manifest_dir).role
}

/// Return whether a validated config declares the requested App role.
#[must_use]
pub fn config_declares_role(config: &ConfigModel, app_id: &str, role_name: &str) -> bool {
    config.app_id().as_str() == app_id
        && config
            .roles
            .contains_key(&CanisterRole::owned(role_name.to_string()))
}

/// Return the App identity declared by a validated config.
#[must_use]
pub const fn config_app_id(config: &ConfigModel) -> &str {
    config.app_id().as_str()
}

/// Return whether a validated config contains the requested canister role.
#[must_use]
pub fn config_contains_role(config: &ConfigModel, role_name: &str) -> bool {
    config_declares_role(config, config.app_id().as_str(), role_name)
}

/// Render the minimal declared-only config needed by a standalone non-root canister.
///
/// # Panics
///
/// Panics when `role` is not a canonical non-root canister role.
#[must_use]
fn standalone_config_source(role: &str) -> String {
    assert!(
        role != "root" && validate_canister_role_name(role).is_ok(),
        "standalone Canic config requires a canonical non-root role"
    );

    format!(
        r#"[app]
name = "standalone"
init_mode = "enabled"


[roles.{role}]
kind = "canister"
package = "."

[auth.delegated_tokens]
enabled = false
"#
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use canic_core::bootstrap::parse_config_model;

    const ROLE_BUILD_CONFIG: &str = r#"
[app]
name = "test"

[roles.root]
kind = "root"

[roles.app]
kind = "canister"
package = "app"

[auth.delegated_tokens]
enabled = false

[component_specs.app]
component_role = "app"
maximum_instances = 1
"#;

    #[cfg(unix)]
    #[test]
    fn generated_source_links_never_reuse_or_overwrite_their_target() {
        let root = std::env::temp_dir().join(format!(
            "canic-generated-source-links-{}",
            std::process::id()
        ));
        fs::create_dir_all(&root).unwrap();
        let original = root.join("original.rs");
        let generated = root.join("generated.rs");
        fs::write(&original, "original").unwrap();
        std::os::unix::fs::symlink(&original, &generated).unwrap();
        for candidate in ["original", "changed"] {
            assert_eq!(
                write_build_source_if_changed(&generated, candidate)
                    .unwrap_err()
                    .kind(),
                io::ErrorKind::InvalidInput
            );
            assert_eq!(fs::read_to_string(&original).unwrap(), "original");
            assert!(fs::symlink_metadata(&generated).unwrap().is_symlink());
        }
        fs::remove_file(&original).unwrap();
        assert_eq!(
            write_build_source_if_changed(&generated, "new")
                .unwrap_err()
                .kind(),
            io::ErrorKind::InvalidInput
        );
        assert!(!original.exists());
        fs::remove_file(&generated).unwrap();
        write_build_source_if_changed(&generated, "local").unwrap();
        let modified = fs::metadata(&generated).unwrap().modified().unwrap();
        write_build_source_if_changed(&generated, "local").unwrap();
        assert_eq!(
            fs::metadata(&generated).unwrap().modified().unwrap(),
            modified
        );
        fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn canonical_role_contract_marker_is_required_only_for_wasm_builds() {
        assert_canonical_role_contract_build("x86_64-unknown-linux-gnu", None);
        assert_canonical_role_contract_build(
            "wasm32-unknown-unknown",
            Some(canic_core::role_contract::CANONICAL_BUILD_MARKER_VALUE),
        );

        assert!(
            std::panic::catch_unwind(|| {
                assert_canonical_role_contract_build("wasm32-unknown-unknown", None);
            })
            .is_err()
        );
    }

    #[test]
    fn role_build_sources_retain_full_configuration_only_for_root() {
        let config = parse_config_model(ROLE_BUILD_CONFIG).expect("build config parses");

        let ordinary = compile_role_build_sources(
            &config,
            ROLE_BUILD_CONFIG,
            &CanisterRole::from("app"),
            false,
        )
        .expect("ordinary build sources compile");
        assert!(ordinary.root.is_none());
        assert!(
            ordinary
                .role_runtime_authority
                .contains("RoleRuntimeAuthority")
        );

        let wasm_store =
            compile_role_build_sources(&config, ROLE_BUILD_CONFIG, &CanisterRole::WASM_STORE, true)
                .expect("Store build sources compile");
        assert!(wasm_store.root.is_none());
        assert!(
            wasm_store
                .role_runtime_authority
                .contains("RuntimeCanisterConfig")
        );

        let root =
            compile_role_build_sources(&config, ROLE_BUILD_CONFIG, &CanisterRole::ROOT, false)
                .expect("Root build sources compile");
        let root_sources = root.root.expect("Root owns full configuration outputs");
        assert!(root_sources.config_model.contains("ConfigModel"));
        assert!(root_sources.compact_config.contains("[roles.root]"));
    }

    #[test]
    fn standalone_config_source_parses_for_plain_role() {
        let source = standalone_config_source("sandbox_blank");
        let cfg = parse_config_model(&source).expect("generated standalone config parses");

        assert_eq!(cfg.app_id().as_str(), "standalone");
        assert!(cfg.roles.contains_key("sandbox_blank"));
        assert!(!cfg.roles.contains_key("root"));
        assert!(cfg.component_specs.is_empty());
        assert!(!cfg.auth.delegated_tokens.enabled);
        assert!(
            !cfg.deployable_roles()
                .contains(&CanisterRole::from("sandbox_blank"))
        );
    }

    #[test]
    fn standalone_config_source_uses_canonical_bare_role_key() {
        let source = standalone_config_source("demo_role");
        let cfg = parse_config_model(&source).expect("generated standalone config parses");

        assert_eq!(cfg.app_id().as_str(), "standalone");
        assert!(source.contains("[roles.demo_role]"));
        assert!(cfg.roles.contains_key("demo_role"));
        assert!(cfg.component_specs.is_empty());
    }

    #[test]
    fn fleet_subnet_root_is_deployable_outside_component_specs() {
        let cfg = parse_config_model(
            r#"
[app]
name = "demo"

[roles.root]
kind = "root"
"#,
        )
        .expect("root infrastructure config parses");

        assert!(cfg.deployable_roles().contains(&CanisterRole::from("root")));
        assert!(cfg.attached_roles().is_empty());
    }

    #[test]
    #[should_panic(expected = "standalone Canic config requires a canonical non-root role")]
    fn standalone_config_source_rejects_root_role() {
        let _ = standalone_config_source("root");
    }

    #[test]
    #[should_panic(expected = "standalone Canic config requires a canonical non-root role")]
    fn standalone_config_source_rejects_noncanonical_role() {
        let _ = standalone_config_source("demo.role");
    }

    #[test]
    fn read_config_source_or_default_generates_when_implicit_file_is_missing() {
        let missing_path =
            std::env::temp_dir().join(format!("canic-missing-default-{}.toml", std::process::id()));
        let (source, generated) =
            read_config_source_or_default(missing_path.as_path(), false, Some("test"));

        assert!(generated);
        assert!(source.contains("[roles.test]"));
        assert!(!source.contains("[component_specs."));
    }

    #[test]
    fn declared_package_role_reads_canic_metadata() {
        let dir = std::env::temp_dir().join(format!("canic-role-metadata-{}", std::process::id()));
        fs::create_dir_all(&dir).expect("create temp manifest dir");
        fs::write(
            dir.join("Cargo.toml"),
            r#"[package]
name = "canister_scale"
version = "0.1.0"
edition = "2024"

[package.metadata.canic]
app = "test"
role = "scale_replica"
"#,
        )
        .expect("write manifest");

        assert_eq!(
            declared_package_role(&dir).as_deref(),
            Some("scale_replica")
        );
        fs::remove_dir_all(&dir).expect("remove temp manifest dir");
    }

    #[test]
    fn required_package_role_rejects_missing_canic_metadata() {
        let dir = std::env::temp_dir().join(format!(
            "canic-missing-role-metadata-{}",
            std::process::id()
        ));
        fs::create_dir_all(&dir).expect("create temp manifest dir");
        fs::write(
            dir.join("Cargo.toml"),
            r#"[package]
name = "canister_missing"
version = "0.1.0"
edition = "2024"
"#,
        )
        .expect("write manifest");

        let panic = std::panic::catch_unwind(|| required_package_role(&dir))
            .expect_err("missing metadata should panic");
        let message = panic
            .downcast_ref::<String>()
            .map(String::as_str)
            .or_else(|| panic.downcast_ref::<&str>().copied())
            .expect("panic should include a message");

        assert!(message.contains("missing Canic package metadata"));
        fs::remove_dir_all(&dir).expect("remove temp manifest dir");
    }

    #[test]
    fn config_contains_role_accepts_exact_metadata_role() {
        let cfg = parse_config_model(
            r#"


[app]
name = "test"

[roles.root]
kind = "root"

[roles.app]
kind = "canister"
package = "app"

[auth.delegated_tokens]
enabled = false

[component_specs.app]
component_role = "app"
maximum_instances = 1
"#,
        )
        .expect("config parses");

        assert!(config_contains_role(&cfg, "root"));
        assert!(config_contains_role(&cfg, "app"));
    }

    #[test]
    fn config_contains_role_rejects_role_typos() {
        let cfg = parse_config_model(
            r#"


[app]
name = "test"

[roles.root]
kind = "root"

[roles.app]
kind = "canister"
package = "app"

[auth.delegated_tokens]
enabled = false

[component_specs.app]
component_role = "app"
maximum_instances = 1
"#,
        )
        .expect("config parses");

        assert!(!config_contains_role(&cfg, "Root"));
        assert!(!config_contains_role(&cfg, "roots"));
        assert!(!config_contains_role(&cfg, "missing"));
    }
}