canic-core 0.29.4

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
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
mod log;
mod subnet;

pub use log::*;
pub use subnet::*;

use crate::{
    InternalError, InternalErrorOrigin,
    cdk::candid::Principal,
    ids::{CanisterRole, SubnetRole},
};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet};
use thiserror::Error as ThisError;

///
/// Configuration schema and validation.
///
/// WHY THIS MODULE EXISTS
/// -----------------------
/// This module defines the **authoritative configuration contract** for the
/// entire canister network.
///
/// All configuration MUST:
///   1. Deserialize into these types
///   2. Pass `Validate::validate()`
///
/// Invariants enforced here are assumed everywhere else in the system and
/// MUST NOT be revalidated at runtime.
///
/// This module is intentionally strict:
/// - `deny_unknown_fields` prevents silent misconfiguration
/// - Validation fails fast with human-readable errors
/// - Defaults are explicit and conservative
///
/// If validation passes, downstream code is allowed to trust the config.
///

///
/// ConfigSchemaError
///
/// Errors produced during schema validation.
/// These represent *configuration mistakes*, not runtime failures.
///
#[derive(Debug, ThisError)]
pub enum ConfigSchemaError {
    #[error("validation error: {0}")]
    ValidationError(String),
}

///
/// Maximum allowed byte length for role identifiers.
///
/// WHY THIS EXISTS:
/// - Prevents unbounded metric cardinality
/// - Keeps stable storage keys predictable
/// - Avoids accidental abuse via extremely long role names
///
#[cfg(any(not(target_arch = "wasm32"), test))]
pub const NAME_MAX_BYTES: usize = 40;

#[cfg(any(not(target_arch = "wasm32"), test))]
fn validate_canister_role_len(role: &CanisterRole, context: &str) -> Result<(), ConfigSchemaError> {
    if role.as_ref().len() > NAME_MAX_BYTES {
        return Err(ConfigSchemaError::ValidationError(format!(
            "{context} '{role}' exceeds {NAME_MAX_BYTES} bytes",
        )));
    }
    Ok(())
}

#[cfg(any(not(target_arch = "wasm32"), test))]
fn validate_subnet_role_len(role: &SubnetRole, context: &str) -> Result<(), ConfigSchemaError> {
    if role.as_ref().len() > NAME_MAX_BYTES {
        return Err(ConfigSchemaError::ValidationError(format!(
            "{context} '{role}' exceeds {NAME_MAX_BYTES} bytes",
        )));
    }
    Ok(())
}

///
/// Config schema errors are internal configuration failures.
/// They are surfaced as InternalError with origin = Config.
///
impl From<ConfigSchemaError> for InternalError {
    fn from(err: ConfigSchemaError) -> Self {
        Self::domain(InternalErrorOrigin::Config, err.to_string())
    }
}

///
/// Validate
///
/// Trait implemented by all schema elements that require validation.
///
/// Validation is:
/// - Explicit
/// - Non-recursive unless explicitly called
/// - Guaranteed to run before config is used
///
#[cfg(any(not(target_arch = "wasm32"), test))]
pub trait Validate {
    fn validate(&self) -> Result<(), ConfigSchemaError>;
}

///
/// ConfigModel
///
/// Top-level configuration object.
///
/// Invariants enforced here:
/// - A PRIME subnet MUST exist
/// - Exactly one ROOT canister MUST exist globally
/// - ROOT canister MUST be in the PRIME subnet
/// - App index canisters must be SINGLETONs in PRIME
/// - Role names are length-limited
/// - Delegated token TTL is sane
/// - Whitelist principals are valid
///
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct ConfigModel {
    /// Controllers for the canister.
    /// Stored as a Vec because they are appended directly to controller args.
    #[serde(default)]
    pub controllers: Vec<Principal>,

    #[serde(default)]
    pub standards: Option<Standards>,

    #[serde(default)]
    pub log: LogConfig,

    #[serde(default)]
    pub auth: AuthConfig,

    /// App-level configuration (init mode, whitelist).
    #[serde(default)]
    pub app: AppConfig,

    /// Canister roles that participate in the application index.
    /// These must exist in the PRIME subnet and be SINGLETON canisters.
    #[serde(default, alias = "app_directory")]
    pub app_index: BTreeSet<CanisterRole>,

    /// All subnets keyed by role.
    #[serde(default)]
    pub subnets: BTreeMap<SubnetRole, SubnetConfig>,
}

impl ConfigModel {
    /// Get a subnet configuration by role.
    #[must_use]
    pub fn get_subnet(&self, role: &SubnetRole) -> Option<SubnetConfig> {
        self.subnets.get(role).cloned()
    }

    /// Test-only helper: produces a minimally valid config.
    ///
    /// Includes:
    /// - PRIME subnet
    /// - ROOT canister of correct kind
    ///
    /// This avoids tests accidentally relying on invalid configs.
    #[cfg(test)]
    #[must_use]
    pub fn test_default() -> Self {
        let mut cfg = Self::default();
        let mut prime = SubnetConfig::default();

        prime.canisters.insert(
            CanisterRole::ROOT,
            CanisterConfig {
                kind: CanisterKind::Root,
                initial_cycles: crate::cdk::types::Cycles::new(0),
                topup_policy: None,
                randomness: RandomnessConfig::default(),
                scaling: None,
                sharding: None,
                directory: None,
                delegated_auth: DelegatedAuthCanisterConfig::default(),
                standards: StandardsCanisterConfig::default(),
            },
        );

        cfg.subnets.insert(SubnetRole::PRIME, prime);
        cfg
    }

    /// Check whether a principal is whitelisted.
    ///
    /// NOTE:
    /// Principals are stored as text intentionally so invalid values
    /// can be rejected at config load time.
    #[must_use]
    pub fn is_whitelisted(&self, principal: &Principal) -> bool {
        self.app
            .whitelist
            .as_ref()
            .is_none_or(|w| w.principals.contains(&principal.to_string()))
    }
}

#[cfg(any(not(target_arch = "wasm32"), test))]
impl Validate for ConfigModel {
    fn validate(&self) -> Result<(), ConfigSchemaError> {
        // Validation order is intentional to surface the most meaningful
        // errors first and avoid cascaded failures.

        for subnet_role in self.subnets.keys() {
            validate_subnet_role_len(subnet_role, "subnet")?;
        }

        self.log.validate()?;
        self.auth.validate()?;
        self.app.validate()?;

        // PRIME subnet must exist
        let prime = SubnetRole::PRIME;
        let prime_subnet = self
            .subnets
            .get(&prime)
            .ok_or_else(|| ConfigSchemaError::ValidationError("prime subnet not found".into()))?;

        // ROOT canister must exist in PRIME and be kind=Root
        let root_role = CanisterRole::ROOT;
        let root_cfg = prime_subnet.canisters.get(&root_role).ok_or_else(|| {
            ConfigSchemaError::ValidationError("root canister not defined in prime subnet".into())
        })?;

        if root_cfg.kind != CanisterKind::Root {
            return Err(ConfigSchemaError::ValidationError(
                "root canister must have kind = \"root\"".into(),
            ));
        }

        // App index canisters must exist in PRIME and be SINGLETONs
        for canister_role in &self.app_index {
            validate_canister_role_len(canister_role, "app index canister")?;

            let canister_cfg = prime_subnet.canisters.get(canister_role).ok_or_else(|| {
                ConfigSchemaError::ValidationError(format!(
                    "app index canister '{canister_role}' is not in prime subnet",
                ))
            })?;

            if canister_cfg.kind != CanisterKind::Singleton {
                return Err(ConfigSchemaError::ValidationError(format!(
                    "app index canister '{canister_role}' must have kind = \"singleton\"",
                )));
            }
        }

        // Exactly one ROOT canister must exist globally
        let mut root_roles = Vec::new();
        for (subnet_role, subnet) in &self.subnets {
            for (canister_role, canister_cfg) in &subnet.canisters {
                if canister_cfg.kind == CanisterKind::Root {
                    root_roles.push(format!("{subnet_role}:{canister_role}"));
                }
            }
        }

        if root_roles.len() > 1 {
            return Err(ConfigSchemaError::ValidationError(format!(
                "root kind must be unique globally (found {})",
                root_roles.join(", "),
            )));
        }

        for subnet in self.subnets.values() {
            subnet.validate()?;
        }

        Ok(())
    }
}

///
/// AppConfig
///

#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct AppConfig {
    #[serde(default)]
    pub init_mode: AppInitMode,

    /// Principal whitelist.
    ///
    /// Semantics:
    /// - None  => allow all principals (default-open)
    /// - Some  => allow only listed principals (default-closed)
    #[serde(default)]
    pub whitelist: Option<Whitelist>,
}

impl Default for AppConfig {
    fn default() -> Self {
        Self {
            init_mode: AppInitMode::Enabled,
            whitelist: None,
        }
    }
}

#[cfg(any(not(target_arch = "wasm32"), test))]
impl Validate for AppConfig {
    fn validate(&self) -> Result<(), ConfigSchemaError> {
        if let Some(list) = &self.whitelist {
            list.validate()?;
        }
        Ok(())
    }
}

///
/// AppInitMode
///
/// Configurable initial app state.
///

#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum AppInitMode {
    #[default]
    Enabled,
    Readonly,
    Disabled,
}

///
/// AuthConfig
///
/// Groups authentication-related configuration.
///

#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct AuthConfig {
    #[serde(default)]
    pub delegated_tokens: DelegatedTokenConfig,

    #[serde(default)]
    pub role_attestation: RoleAttestationConfig,
}

#[cfg(any(not(target_arch = "wasm32"), test))]
impl Validate for AuthConfig {
    fn validate(&self) -> Result<(), ConfigSchemaError> {
        self.delegated_tokens.validate()?;
        self.role_attestation.validate()
    }
}

///
/// DelegatedTokenConfig
///
/// Controls root-signed delegated token authentication.
///
/// Semantics:
/// - enabled = false => delegated token auth disabled entirely
/// - max_ttl_secs = None => no upper TTL bound
/// - max_ttl_secs = Some => hard upper bound on token lifetime
///

#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct DelegatedTokenConfig {
    #[serde(default = "default_delegated_tokens_enabled")]
    pub enabled: bool,

    #[serde(default = "default_delegated_tokens_ecdsa_key_name")]
    pub ecdsa_key_name: String,

    #[serde(default)]
    pub max_ttl_secs: Option<u64>,
}

const fn default_delegated_tokens_enabled() -> bool {
    true
}

fn default_delegated_tokens_ecdsa_key_name() -> String {
    "test_key_1".to_string()
}

impl Default for DelegatedTokenConfig {
    fn default() -> Self {
        Self {
            enabled: default_delegated_tokens_enabled(),
            ecdsa_key_name: default_delegated_tokens_ecdsa_key_name(),
            max_ttl_secs: None,
        }
    }
}

#[cfg(any(not(target_arch = "wasm32"), test))]
impl Validate for DelegatedTokenConfig {
    fn validate(&self) -> Result<(), ConfigSchemaError> {
        if self.ecdsa_key_name.trim().is_empty() {
            return Err(ConfigSchemaError::ValidationError(
                "auth.delegated_tokens.ecdsa_key_name must not be empty".into(),
            ));
        }

        if let Some(max_ttl_secs) = self.max_ttl_secs
            && max_ttl_secs == 0
        {
            return Err(ConfigSchemaError::ValidationError(
                "auth.delegated_tokens.max_ttl_secs must be greater than zero".into(),
            ));
        }

        Ok(())
    }
}

///
/// RoleAttestationConfig
///
/// Controls root-signed role attestation issuance/verification defaults.
///

#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct RoleAttestationConfig {
    #[serde(default = "default_role_attestation_ecdsa_key_name")]
    pub ecdsa_key_name: String,

    #[serde(default = "default_role_attestation_max_ttl_secs")]
    pub max_ttl_secs: u64,

    #[serde(default)]
    pub min_accepted_epoch_by_role: BTreeMap<String, u64>,
}

fn default_role_attestation_ecdsa_key_name() -> String {
    "test_key_1".to_string()
}

const fn default_role_attestation_max_ttl_secs() -> u64 {
    900
}

impl Default for RoleAttestationConfig {
    fn default() -> Self {
        Self {
            ecdsa_key_name: default_role_attestation_ecdsa_key_name(),
            max_ttl_secs: default_role_attestation_max_ttl_secs(),
            min_accepted_epoch_by_role: BTreeMap::new(),
        }
    }
}

#[cfg(any(not(target_arch = "wasm32"), test))]
impl Validate for RoleAttestationConfig {
    fn validate(&self) -> Result<(), ConfigSchemaError> {
        if self.ecdsa_key_name.trim().is_empty() {
            return Err(ConfigSchemaError::ValidationError(
                "auth.role_attestation.ecdsa_key_name must not be empty".into(),
            ));
        }

        if self.max_ttl_secs == 0 {
            return Err(ConfigSchemaError::ValidationError(
                "auth.role_attestation.max_ttl_secs must be greater than zero".into(),
            ));
        }

        for role in self.min_accepted_epoch_by_role.keys() {
            if role.trim().is_empty() {
                return Err(ConfigSchemaError::ValidationError(
                    "auth.role_attestation.min_accepted_epoch_by_role keys must not be empty"
                        .into(),
                ));
            }
        }

        Ok(())
    }
}

///
/// Whitelist
///
/// Stores principals as text to allow validation at config load time.
/// Text representation is treated as canonical.
///
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Whitelist {
    #[serde(default)]
    pub principals: BTreeSet<String>,
}

#[cfg(any(not(target_arch = "wasm32"), test))]
impl Validate for Whitelist {
    fn validate(&self) -> Result<(), ConfigSchemaError> {
        for (i, s) in self.principals.iter().enumerate() {
            if Principal::from_text(s).is_err() {
                return Err(ConfigSchemaError::ValidationError(format!(
                    "principal #{i} {s} is invalid"
                )));
            }
        }
        Ok(())
    }
}

///
/// Standards
///
/// Feature flags for supported standards.
///
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Standards {
    #[serde(default)]
    pub icrc21: bool,

    #[serde(default)]
    pub icrc103: bool,
}

///
/// TESTS
///

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cdk::types::Cycles;
    use std::collections::BTreeMap;

    fn base_canister_config(kind: CanisterKind) -> CanisterConfig {
        CanisterConfig {
            kind,
            initial_cycles: Cycles::new(0),
            topup_policy: None,
            randomness: RandomnessConfig::default(),
            scaling: None,
            sharding: None,
            directory: None,
            delegated_auth: DelegatedAuthCanisterConfig::default(),
            standards: StandardsCanisterConfig::default(),
        }
    }

    #[test]
    fn root_canister_must_exist_in_prime_subnet() {
        let mut cfg = ConfigModel::default();
        cfg.subnets
            .insert(SubnetRole::PRIME, SubnetConfig::default());

        cfg.validate()
            .expect_err("expected missing root canister to fail validation");
    }

    #[test]
    fn root_canister_must_be_kind_root() {
        let mut cfg = ConfigModel::test_default();
        let mut canisters = BTreeMap::new();

        canisters.insert(
            CanisterRole::ROOT,
            base_canister_config(CanisterKind::Singleton),
        );

        cfg.subnets.get_mut(&SubnetRole::PRIME).unwrap().canisters = canisters;

        cfg.validate().expect_err("expected non-root kind to fail");
    }

    #[test]
    fn multiple_root_canisters_are_rejected() {
        let mut cfg = ConfigModel::test_default();

        cfg.subnets.insert(
            SubnetRole::new("aux"),
            SubnetConfig {
                canisters: {
                    let mut m = BTreeMap::new();
                    m.insert(CanisterRole::ROOT, base_canister_config(CanisterKind::Root));
                    m
                },
                ..Default::default()
            },
        );

        cfg.validate().expect_err("expected multiple roots to fail");
    }

    #[test]
    fn delegated_tokens_max_ttl_zero_is_invalid() {
        let mut cfg = ConfigModel::test_default();
        cfg.auth.delegated_tokens.max_ttl_secs = Some(0);

        cfg.validate().expect_err("expected zero ttl to fail");
    }

    #[test]
    fn role_attestation_max_ttl_zero_is_invalid() {
        let mut cfg = ConfigModel::test_default();
        cfg.auth.role_attestation.max_ttl_secs = 0;

        cfg.validate().expect_err("expected zero ttl to fail");
    }

    #[test]
    fn role_attestation_empty_min_epoch_role_key_is_invalid() {
        let mut cfg = ConfigModel::test_default();
        cfg.auth
            .role_attestation
            .min_accepted_epoch_by_role
            .insert("   ".to_string(), 1);

        cfg.validate()
            .expect_err("expected empty min epoch role key to fail");
    }

    #[test]
    fn invalid_whitelist_principal_is_rejected() {
        let mut cfg = ConfigModel::test_default();
        cfg.app.whitelist = Some(Whitelist {
            principals: std::iter::once("not-a-principal".into()).collect(),
        });

        cfg.validate()
            .expect_err("expected invalid principal to fail");
    }
}