canic-core 0.111.0

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
//! Module: bootstrap
//!
//! Responsibility: install compiled configuration and expose bootstrap artifacts.
//! Does not own: config schema validation rules, runtime lifecycle ordering, or artifact builds.
//! Boundary: lifecycle and build tooling call bootstrap after config generation.

#[doc(hidden)]
pub mod release_binding;
#[cfg(any(not(target_arch = "wasm32"), test))]
mod render;

use crate::config::{Config, RoleRuntimeAuthority, RoleRuntimeConfig, schema::ConfigModel};
#[cfg(any(target_arch = "wasm32", test))]
use crate::{
    cdk::utils::hash::hex_bytes,
    domain::auth::{ic_root_public_key_raw_from_der_or_raw, is_mainnet_ic_root_public_key_raw},
};
#[cfg(any(target_arch = "wasm32", test))]
use canic_contracts::ids::BuildNetwork;
use std::sync::Arc;

#[doc(hidden)]
pub use crate::{config::ConfigError, config::ConfigTomlIssue};

#[doc(hidden)]
pub mod compiled {
    pub use crate::{
        cdk::candid::Principal, config::schema::AppConfig, config::schema::AuthConfig,
        config::schema::CanisterAuthConfig, config::schema::CanisterConfig,
        config::schema::CanisterKind, config::schema::CanisterRoleNameIssue,
        config::schema::ChainKeyPublicKeyDerivation, config::schema::ChainKeyRootProofConfig,
        config::schema::ComponentChildConfig, config::schema::ComponentChildKind,
        config::schema::ComponentDeploymentMemberLimitConfig,
        config::schema::ComponentDeploymentSpawnGrantLimitConfig,
        config::schema::ComponentGroupComponentConfig,
        config::schema::ComponentGroupDeploymentConfig,
        config::schema::ComponentGroupIncludeConfig,
        config::schema::ComponentGroupPlacementPolicyConfig,
        config::schema::ComponentGroupSpecConfig, config::schema::ComponentLimitsConfig,
        config::schema::ComponentProvisioningGrantConfig,
        config::schema::ComponentSpawnGrantConfig, config::schema::ComponentSpecConfig,
        config::schema::ConfigModel, config::schema::CyclesFundingBudgetConfig,
        config::schema::CyclesFundingPolicyConfig, config::schema::DelegatedTokenConfig,
        config::schema::DiagnosticsCanisterConfig, config::schema::FleetInitMode,
        config::schema::FleetServicePlacementPolicyConfig,
        config::schema::FleetServiceTargetConfig, config::schema::FleetServicesConfig,
        config::schema::IndexConfig, config::schema::IndexPool,
        config::schema::LocalApplicationAuthorizationConfig, config::schema::LogConfig,
        config::schema::MAX_COMPONENT_CHILD_ROLES,
        config::schema::MAX_COMPONENT_PROVISIONING_GRANTS,
        config::schema::MAX_COMPONENT_SPAWN_GRANTS, config::schema::MAX_FLEET_COMPONENT_INSTANCES,
        config::schema::MetricsCanisterConfig, config::schema::MetricsProfile,
        config::schema::NAME_MAX_BYTES, config::schema::RoleAttestationConfig,
        config::schema::RoleDeclaration, config::schema::RoleDeclarationKind,
        config::schema::RoleObservabilityConfig, config::schema::ScalePool,
        config::schema::ScalePoolPolicy, config::schema::ScalingConfig,
        config::schema::ServicesConfig, config::schema::ShardPool, config::schema::ShardPoolPolicy,
        config::schema::ShardingConfig, config::schema::Standards,
        config::schema::StandardsCanisterConfig, config::schema::TopupPolicy,
        config::schema::implicit_root_canister_config,
        config::schema::implicit_wasm_store_canister_config, config::schema::validate_app_name,
        config::schema::validate_canister_role_name,
    };
    pub use crate::{
        config::ComponentChildFundingPolicy, config::ComponentChildSpec,
        config::ComponentDeploymentConfiguration,
        config::ComponentDeploymentConfigurationDigestError, config::ComponentDeploymentLabel,
        config::ComponentDeploymentLabelKey, config::ComponentDeploymentLabelParseError,
        config::ComponentDeploymentLabelValue, config::ComponentDeploymentLimits,
        config::ComponentDeploymentMemberLimit, config::ComponentDeploymentMemberLimitError,
        config::ComponentDeploymentPurpose, config::ComponentDeploymentSpawnGrantLimit,
        config::ComponentGroupDeploymentSpec, config::ComponentGroupDeploymentTopology,
        config::ComponentGroupDeploymentTopologyError, config::ComponentGroupLeafKind,
        config::ComponentGroupMember, config::ComponentGroupPlacementPolicy,
        config::ComponentGroupSpec, config::ComponentGroupTopology,
        config::ComponentGroupTopologyError, config::ComponentLimits,
        config::ComponentProvisioningGrant, config::ComponentSpawnGrant, config::ComponentSpec,
        config::ComponentTopology, config::ComponentTopologyError, config::FlattenedComponentGroup,
        config::FlattenedComponentGroupDeploymentMember, config::FlattenedComponentGroupMember,
        config::FleetServiceMemberPurpose, config::FleetServicePlacementPolicy,
        config::FleetServiceTarget, config::FleetServiceTargetMode, config::FleetServiceTopology,
        config::FleetServiceTopologyError,
        config::MAX_COMPONENT_DEPLOYMENT_CONFIGURATION_CANONICAL_BYTES,
        config::MAX_COMPONENT_DEPLOYMENT_LABEL_KEY_BYTES,
        config::MAX_COMPONENT_DEPLOYMENT_LABEL_VALUE_BYTES,
        config::MAX_COMPONENT_DEPLOYMENT_LABELS, config::MAX_COMPONENT_DEPLOYMENT_MEMBER_LIMITS,
        config::MAX_COMPONENT_DEPLOYMENT_SPAWN_GRANT_REDUCTIONS,
        config::MAX_COMPONENT_GROUP_DECLARED_MEMBERS,
        config::MAX_COMPONENT_GROUP_DEPLOYMENT_MEMBERS,
        config::MAX_COMPONENT_GROUP_DEPLOYMENT_TOPOLOGY_CANONICAL_BYTES,
        config::MAX_COMPONENT_GROUP_DEPLOYMENTS, config::MAX_COMPONENT_GROUP_FLATTENED_MEMBERS,
        config::MAX_COMPONENT_GROUP_GRAPH_CANONICAL_BYTES, config::MAX_COMPONENT_GROUP_INCLUSIONS,
        config::MAX_COMPONENT_GROUP_MEMBERS, config::MAX_COMPONENT_GROUP_SPECS,
        config::MAX_COMPONENT_TOPOLOGY_CANONICAL_BYTES, config::MAX_FLEET_SERVICE_TARGETS,
        config::MAX_FLEET_SERVICE_TOPOLOGY_CANONICAL_BYTES, config::RoleRuntimeAuthority,
        config::RuntimeApplicationAuthorization, config::RuntimeCanisterAuthority,
        config::RuntimeCanisterConfig, config::RuntimeChildCanisterAuthority,
        config::RuntimeDeploymentMemberAuthority,
    };
    pub use crate::{
        config::caller_authority::CallerAuthorityConfig,
        config::caller_authority::CallerPermission,
        config::caller_authority::CallerPermissionDirection, config::caller_authority::CallerScope,
        config::caller_authority::CallerSourceSelector,
        config::caller_authority::CompiledCallerPolicy,
        config::caller_authority::permission_is_declared,
    };
    pub use canic_contracts::{
        cycles::Cycles, ids::AppId, ids::BuildNetwork, ids::CanisterRole,
        ids::ComponentDeploymentConfigurationDigest, ids::ComponentGroupDeploymentId,
        ids::ComponentGroupMemberId, ids::ComponentGroupMemberPath, ids::ComponentGroupSpecId,
        ids::ComponentSpecId, ids::CyclesFundingBudget, ids::FleetServiceId,
    };
}

/// init_compiled_config
///
/// Install a build-produced configuration model and its canonical TOML source.
pub fn init_compiled_config(
    config: ConfigModel,
    source_toml: &str,
) -> Result<Arc<ConfigModel>, ConfigError> {
    #[cfg(target_arch = "wasm32")]
    let config = {
        let mut config = config;
        inject_runtime_ic_root_public_key(&mut config)?;
        config
    };
    Config::init_from_model(config, source_toml)
}

/// Install one build-compiled immutable role runtime authority.
pub fn init_role_runtime_authority(
    expected_role: &crate::ids::CanisterRole,
    authority: RoleRuntimeAuthority,
) -> Result<Arc<RoleRuntimeAuthority>, crate::InternalError> {
    if &authority.role != expected_role {
        return Err(crate::InternalError::invariant());
    }
    #[cfg(target_arch = "wasm32")]
    let authority = {
        let mut authority = authority;
        inject_runtime_ic_root_public_key_into_auth(&mut authority.auth)
            .map_err(crate::InternalError::from)?;
        authority
    };
    RoleRuntimeConfig::init(authority)
}

/// parse_config_model
///
/// Parse and validate the source TOML into a configuration model on host targets.
#[cfg(any(not(target_arch = "wasm32"), test))]
pub fn parse_config_model(toml: &str) -> Result<ConfigModel, ConfigError> {
    Config::parse_toml(toml)
}

/// compact_config_source
///
/// Compact a validated Canic TOML source without changing value encodings.
#[cfg(any(not(target_arch = "wasm32"), test))]
#[must_use]
pub fn compact_config_source(toml: &str) -> String {
    let mut compact = String::new();

    for line in toml.lines() {
        let trimmed = line.trim();

        if trimmed.is_empty() || trimmed.starts_with('#') {
            continue;
        }

        compact.push_str(trimmed);
        compact.push('\n');
    }

    compact
}

/// emit_config_model_source
///
/// Render the validated configuration model as Rust source for `include!` at runtime.
#[cfg(any(not(target_arch = "wasm32"), test))]
#[must_use]
pub fn emit_config_model_source(config: &ConfigModel) -> String {
    render::config_model(config)
}

/// Render one validated role runtime authority as Rust source for `include!`.
#[cfg(any(not(target_arch = "wasm32"), test))]
pub fn emit_role_runtime_authority_source(
    config: &ConfigModel,
    role: &crate::ids::CanisterRole,
    wasm_store: bool,
) -> Result<String, crate::config::RoleRuntimeAuthorityError> {
    let authority = if wasm_store {
        crate::config::RoleRuntimeAuthority::compile_wasm_store(config)?
    } else {
        crate::config::RoleRuntimeAuthority::compile(config, role)?
    };
    Ok(render::role_runtime_authority(&authority))
}

#[cfg(target_arch = "wasm32")]
fn inject_runtime_ic_root_public_key(config: &mut ConfigModel) -> Result<(), ConfigError> {
    inject_runtime_ic_root_public_key_into_auth(&mut config.auth)
}

#[cfg(target_arch = "wasm32")]
fn inject_runtime_ic_root_public_key_into_auth(
    auth: &mut crate::config::schema::AuthConfig,
) -> Result<(), ConfigError> {
    if !should_inject_runtime_ic_root_public_key_for_auth(auth) {
        return Ok(());
    }
    let root_key = ic_cdk::api::root_key();
    inject_runtime_ic_root_public_key_into_auth_from(auth, &root_key)
}

#[cfg(test)]
fn inject_runtime_ic_root_public_key_from(
    config: &mut ConfigModel,
    root_key: &[u8],
) -> Result<(), ConfigError> {
    inject_runtime_ic_root_public_key_into_auth_from(&mut config.auth, root_key)
}

#[cfg(any(target_arch = "wasm32", test))]
fn inject_runtime_ic_root_public_key_into_auth_from(
    auth: &mut crate::config::schema::AuthConfig,
    root_key: &[u8],
) -> Result<(), ConfigError> {
    if !should_inject_runtime_ic_root_public_key_for_auth(auth) {
        return Ok(());
    }

    let build_network = auth.delegated_tokens.build_network;
    let raw_root_key =
        ic_root_public_key_raw_from_der_or_raw(root_key).map_err(ConfigError::RuntimeRootKey)?;
    if is_mainnet_ic_root_public_key_raw(&raw_root_key) {
        return Err(ConfigError::RuntimeRootKey(format!(
            "auth.delegated_tokens.build_network=\"{build_network}\" must not use the mainnet IC root public key"
        )));
    }

    auth.delegated_tokens.ic_root_public_key_raw_hex = Some(hex_bytes(&raw_root_key));
    Ok(())
}

#[cfg(any(target_arch = "wasm32", test))]
fn should_inject_runtime_ic_root_public_key_for_auth(
    auth: &crate::config::schema::AuthConfig,
) -> bool {
    if !auth.delegated_tokens.enabled || auth.delegated_tokens.ic_root_public_key_raw_hex.is_some()
    {
        return false;
    }

    auth.delegated_tokens.build_network == BuildNetwork::Local
}

// -----------------------------------------------------------------------------
// Tests
// -----------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::domain::auth::{IC_ROOT_PUBLIC_KEY_RAW_LENGTH, MAINNET_IC_ROOT_PUBLIC_KEY_RAW};

    const MINIMAL_CONFIG: &str = r#"
[app]
name = "probe"

[roles.root]
kind = "root"

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

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

    #[test]
    fn strict_schema_accepts_current_canister_fields() {
        parse_config_model(MINIMAL_CONFIG).expect("current config should parse");
    }

    #[test]
    fn role_runtime_source_contains_only_the_compiled_runtime_authority() {
        let config = parse_config_model(MINIMAL_CONFIG).expect("current config should parse");
        let role = crate::ids::CanisterRole::from("app");
        let source = emit_role_runtime_authority_source(&config, &role, false)
            .expect("compile role runtime authority");

        assert!(source.contains("RoleRuntimeAuthority"));
        assert!(source.contains("RuntimeCanisterConfig"));
        assert!(!source.contains("ConfigModel"));
        assert!(!source.contains("ComponentSpecConfig"));
        assert!(!source.contains("initial_cycles"));

        let authority = crate::config::RoleRuntimeAuthority::compile(&config, &role)
            .expect("compile role runtime authority");
        assert!(
            init_role_runtime_authority(
                &crate::ids::CanisterRole::from("other"),
                authority.clone()
            )
            .is_err()
        );
        assert!(crate::config::RoleRuntimeConfig::try_get().is_none());
        let installed =
            init_role_runtime_authority(&role, authority).expect("install exact role authority");
        assert_eq!(installed.role, role);
        crate::config::Config::reset_for_tests();
    }

    #[test]
    fn strict_schema_reports_typed_nested_unknown_field() {
        let source =
            format!("{MINIMAL_CONFIG}\n[component_specs.default.randomness]\nenabled = true\n");
        let error = parse_config_model(&source).expect_err("unknown field must reject");

        assert!(matches!(
            error,
            ConfigError::CannotParseToml {
                issue: ConfigTomlIssue::UnknownField {
                    logical_path,
                    unknown_field,
                },
                ..
            } if logical_path == "component_specs.default.randomness"
                && unknown_field == "randomness"
        ));
    }

    #[test]
    fn protected_fleet_funding_policy_is_not_application_config_authority() {
        let source = format!(
            "{MINIMAL_CONFIG}\n[component_specs.default.icp_refill]\nmax_refill_e8s_per_call = 1\n"
        );
        let error =
            parse_config_model(&source).expect_err("Fleet policy must reject in canic.toml");

        assert!(matches!(
            error,
            ConfigError::CannotParseToml {
                issue: ConfigTomlIssue::UnknownField { unknown_field, .. },
                ..
            } if unknown_field == "icp_refill"
        ));
    }

    #[test]
    fn runtime_root_key_injection_sets_local_missing_key() {
        let mut config = ConfigModel::test_default();
        config.auth.delegated_tokens.build_network = BuildNetwork::Local;

        inject_runtime_ic_root_public_key_from(&mut config, &[9; IC_ROOT_PUBLIC_KEY_RAW_LENGTH])
            .expect("local runtime root key should inject");

        let expected = hex_bytes([9; IC_ROOT_PUBLIC_KEY_RAW_LENGTH]);
        assert_eq!(
            config
                .auth
                .delegated_tokens
                .ic_root_public_key_raw_hex
                .as_deref(),
            Some(expected.as_str())
        );
    }

    #[test]
    fn runtime_root_key_injection_preserves_explicit_key() {
        let mut config = ConfigModel::test_default();
        config.auth.delegated_tokens.build_network = BuildNetwork::Local;
        config.auth.delegated_tokens.ic_root_public_key_raw_hex =
            Some(hex_bytes([8; IC_ROOT_PUBLIC_KEY_RAW_LENGTH]));

        inject_runtime_ic_root_public_key_from(&mut config, &[9; IC_ROOT_PUBLIC_KEY_RAW_LENGTH])
            .expect("explicit local runtime root key should be preserved");

        let expected = hex_bytes([8; IC_ROOT_PUBLIC_KEY_RAW_LENGTH]);
        assert_eq!(
            config
                .auth
                .delegated_tokens
                .ic_root_public_key_raw_hex
                .as_deref(),
            Some(expected.as_str())
        );
    }

    #[test]
    fn runtime_root_key_injection_leaves_ic_missing_key_unresolved() {
        let mut config = ConfigModel::test_default();
        config.auth.delegated_tokens.build_network = BuildNetwork::Ic;

        inject_runtime_ic_root_public_key_from(&mut config, &[9; IC_ROOT_PUBLIC_KEY_RAW_LENGTH])
            .expect("IC runtime root key must not be injected");

        assert!(
            config
                .auth
                .delegated_tokens
                .ic_root_public_key_raw_hex
                .is_none()
        );
    }

    #[test]
    fn runtime_root_key_injection_rejects_mainnet_key_for_local() {
        let mut config = ConfigModel::test_default();
        config.auth.delegated_tokens.build_network = BuildNetwork::Local;

        inject_runtime_ic_root_public_key_from(&mut config, &MAINNET_IC_ROOT_PUBLIC_KEY_RAW)
            .expect_err("local runtime root key must not accept mainnet key");
    }
}