canic-core 0.110.2

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
//! Module: memory::policy
//!
//! Responsibility: enforce Canic memory-manager namespace and ID-range ownership.
//! Does not own: memory-manager storage, stable schemas, or diagnostics rendering.
//! Boundary: memory bootstrap passes this policy into `ic-memory` validation.

use crate::{
    memory::{
        CANIC_CONTROL_PLANE_MEMORY_AUTHORITY, CANIC_CORE_MEMORY_AUTHORITY,
        registry::MemoryRegistryError,
    },
    role_contract::allocation::{
        CANIC_CONTROL_PLANE_MAX_ID, CANIC_CONTROL_PLANE_MIN_ID, CANIC_CORE_LOWER_MAX_ID,
        CANIC_CORE_MAX_ID, CANIC_CORE_MIN_ID, CANIC_CORE_UPPER_MIN_ID,
        memory::control_plane::{
            FLEET_COORDINATOR_ADMISSION_ID, FLEET_COORDINATOR_FUNDING_ID, ROOT_ADMISSION_ID,
            ROOT_FUNDING_ID,
        },
    },
};
use ic_memory::{
    AllocationPolicy, AllocationSlotDescriptor, MemoryManagerAuthorityRecord, MemoryManagerIdRange,
    MemoryManagerRangeMode, MemoryManagerSlotError, PolicyIdentity, PolicyIdentityError,
    RuntimeBootstrapPolicy, StableKey,
};

pub const CANIC_CORE_AUTHORITY_PURPOSE: &str = "Canic core allocation authority";
pub const CANIC_CONTROL_PLANE_AUTHORITY_PURPOSE: &str = "Canic control-plane allocation authority";
const CANIC_MEMORY_BOOTSTRAP_POLICY_NAME: &str = "canic.memory-bootstrap-policy";
const CANIC_MEMORY_BOOTSTRAP_POLICY_VERSION: u32 = 1;

///
/// CanicMemoryManagerPolicy
///
/// Canic policy adapter for the `ic-memory` MemoryManager substrate
/// allocation slots.
/// Owned by memory policy and supplied to memory-manager bootstrap.
///

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(super) struct CanicMemoryManagerPolicy;

impl CanicMemoryManagerPolicy {
    #[must_use]
    pub(super) const fn new() -> Self {
        Self
    }
}

impl AllocationPolicy for CanicMemoryManagerPolicy {
    type Error = MemoryRegistryError;

    fn validate_key(&self, _key: &StableKey) -> Result<(), Self::Error> {
        Ok(())
    }

    fn validate_slot(
        &self,
        key: &StableKey,
        slot: &AllocationSlotDescriptor,
    ) -> Result<(), Self::Error> {
        let id = slot
            .memory_manager_id()
            .map_err(memory_slot_error_to_registry_error)?;
        validate_key_id_claim(id, key.as_str())
    }

    fn validate_reserved_slot(
        &self,
        key: &StableKey,
        slot: &AllocationSlotDescriptor,
    ) -> Result<(), Self::Error> {
        let id = slot
            .memory_manager_id()
            .map_err(memory_slot_error_to_registry_error)?;
        if !ic_memory::is_ic_memory_stable_key(key.as_str()) && !key.as_str().starts_with("canic.")
        {
            return Err(MemoryRegistryError::RangeAuthorityViolation {
                stable_key: key.as_str().to_string(),
                id,
                reason: "application stable keys may not be pre-reserved by Canic",
            });
        }
        validate_key_id_claim(id, key.as_str())
    }
}

impl RuntimeBootstrapPolicy for CanicMemoryManagerPolicy {
    fn runtime_bootstrap_identity(&self) -> Result<PolicyIdentity, PolicyIdentityError> {
        PolicyIdentity::new(
            CANIC_MEMORY_BOOTSTRAP_POLICY_NAME,
            CANIC_MEMORY_BOOTSTRAP_POLICY_VERSION,
        )
    }
}

/// Return the canonical memory-manager authority records for diagnostics.
#[must_use]
pub fn canonical_authority_records() -> Vec<MemoryManagerAuthorityRecord> {
    vec![
        MemoryManagerAuthorityRecord::new(
            ic_memory::memory_manager_governance_range(),
            ic_memory::IC_MEMORY_AUTHORITY_OWNER,
            MemoryManagerRangeMode::Reserved,
            Some(ic_memory::IC_MEMORY_AUTHORITY_PURPOSE.to_string()),
        )
        .expect("valid ic-memory authority record"),
        MemoryManagerAuthorityRecord::new(
            canic_control_plane_range(),
            CANIC_CONTROL_PLANE_MEMORY_AUTHORITY,
            MemoryManagerRangeMode::Reserved,
            Some(CANIC_CONTROL_PLANE_AUTHORITY_PURPOSE.to_string()),
        )
        .expect("valid Canic control-plane authority record"),
        MemoryManagerAuthorityRecord::new(
            canic_core_lower_range(),
            CANIC_CORE_MEMORY_AUTHORITY,
            MemoryManagerRangeMode::Reserved,
            Some(CANIC_CORE_AUTHORITY_PURPOSE.to_string()),
        )
        .expect("valid Canic core authority record"),
        MemoryManagerAuthorityRecord::new(
            control_plane_infrastructure_range(),
            CANIC_CONTROL_PLANE_MEMORY_AUTHORITY,
            MemoryManagerRangeMode::Reserved,
            Some(CANIC_CONTROL_PLANE_AUTHORITY_PURPOSE.to_string()),
        )
        .expect("valid infrastructure control-plane authority record"),
        MemoryManagerAuthorityRecord::new(
            canic_core_upper_range(),
            CANIC_CORE_MEMORY_AUTHORITY,
            MemoryManagerRangeMode::Reserved,
            Some(CANIC_CORE_AUTHORITY_PURPOSE.to_string()),
        )
        .expect("valid Canic core authority record"),
    ]
}

fn validate_key_id_claim(id: u8, stable_key: &str) -> Result<(), MemoryRegistryError> {
    if ic_memory::is_ic_memory_stable_key(stable_key) {
        return Ok(());
    }

    if stable_key.starts_with("canic.core.") {
        return require_core_range(id, stable_key);
    }

    if stable_key.starts_with("canic.control_plane.") {
        if stable_key == "canic.control_plane.fleet_coordinator.funding.v1" {
            return require_range(
                id,
                stable_key,
                MemoryManagerIdRange::new(
                    FLEET_COORDINATOR_FUNDING_ID,
                    FLEET_COORDINATOR_FUNDING_ID,
                )
                .expect("valid Coordinator funding range"),
                "the Fleet Coordinator funding key must use reserved id 62",
            );
        }
        if stable_key == "canic.control_plane.root.funding.v1" {
            return require_range(
                id,
                stable_key,
                MemoryManagerIdRange::new(ROOT_FUNDING_ID, ROOT_FUNDING_ID)
                    .expect("valid Root funding range"),
                "the Root funding key must use reserved id 63",
            );
        }
        if stable_key == "canic.control_plane.fleet_admission.v1" {
            return require_range(
                id,
                stable_key,
                MemoryManagerIdRange::new(
                    FLEET_COORDINATOR_ADMISSION_ID,
                    FLEET_COORDINATOR_ADMISSION_ID,
                )
                .expect("valid Coordinator admission range"),
                "the Fleet Coordinator admission key must use reserved id 64",
            );
        }
        if stable_key == "canic.control_plane.root.admission.v1" {
            return require_range(
                id,
                stable_key,
                MemoryManagerIdRange::new(ROOT_ADMISSION_ID, ROOT_ADMISSION_ID)
                    .expect("valid Root admission range"),
                "the Root admission key must use reserved id 65",
            );
        }
        return require_range(
            id,
            stable_key,
            canic_control_plane_range(),
            "canic.control_plane.* keys must use Canic control-plane ids 10-29",
        );
    }

    if stable_key.starts_with("canic.") {
        return Err(MemoryRegistryError::RangeAuthorityViolation {
            stable_key: stable_key.to_string(),
            id,
            reason: "unrecognized canic.* stable key namespace",
        });
    }

    validate_application_claim(id, stable_key)
}

fn validate_application_claim(id: u8, stable_key: &str) -> Result<(), MemoryRegistryError> {
    if ic_memory::memory_manager_governance_range().contains(id)
        || canic_core_lower_range().contains(id)
        || control_plane_infrastructure_range().contains(id)
        || canic_core_upper_range().contains(id)
        || canic_control_plane_range().contains(id)
    {
        return Err(MemoryRegistryError::RangeAuthorityViolation {
            stable_key: stable_key.to_string(),
            id,
            reason: "application keys may not use reserved MemoryManager IDs",
        });
    }
    Ok(())
}

fn require_range(
    id: u8,
    stable_key: &str,
    range: MemoryManagerIdRange,
    reason: &'static str,
) -> Result<(), MemoryRegistryError> {
    if range.contains(id) {
        Ok(())
    } else {
        Err(MemoryRegistryError::RangeAuthorityViolation {
            stable_key: stable_key.to_string(),
            id,
            reason,
        })
    }
}

fn require_core_range(id: u8, stable_key: &str) -> Result<(), MemoryRegistryError> {
    if canic_core_lower_range().contains(id) || canic_core_upper_range().contains(id) {
        Ok(())
    } else {
        Err(MemoryRegistryError::RangeAuthorityViolation {
            stable_key: stable_key.to_string(),
            id,
            reason: "canic.core.* keys must use Canic core ids 30-61 or 66-99",
        })
    }
}

fn canic_core_lower_range() -> MemoryManagerIdRange {
    MemoryManagerIdRange::new(CANIC_CORE_MIN_ID, CANIC_CORE_LOWER_MAX_ID)
        .expect("valid lower Canic core range")
}

fn control_plane_infrastructure_range() -> MemoryManagerIdRange {
    MemoryManagerIdRange::new(FLEET_COORDINATOR_FUNDING_ID, ROOT_ADMISSION_ID)
        .expect("valid infrastructure control-plane range")
}

fn canic_core_upper_range() -> MemoryManagerIdRange {
    MemoryManagerIdRange::new(CANIC_CORE_UPPER_MIN_ID, CANIC_CORE_MAX_ID)
        .expect("valid upper Canic core range")
}

fn canic_control_plane_range() -> MemoryManagerIdRange {
    MemoryManagerIdRange::new(CANIC_CONTROL_PLANE_MIN_ID, CANIC_CONTROL_PLANE_MAX_ID)
        .expect("valid Canic control-plane range")
}

fn memory_slot_error_to_registry_error(err: MemoryManagerSlotError) -> MemoryRegistryError {
    match err {
        MemoryManagerSlotError::InvalidMemoryManagerId { id } => {
            MemoryRegistryError::InvalidDeclaration {
                stable_key: "<slot>".to_string(),
                reason: if id == ic_memory::MEMORY_MANAGER_INVALID_ID {
                    "MemoryManager ID 255 is not usable"
                } else {
                    "MemoryManager ID is not usable"
                },
            }
        }
        _ => MemoryRegistryError::InvalidDeclaration {
            stable_key: "<slot>".to_string(),
            reason: "unsupported MemoryManager slot error",
        },
    }
}

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

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

    fn policy() -> CanicMemoryManagerPolicy {
        CanicMemoryManagerPolicy::new()
    }

    #[test]
    fn runtime_bootstrap_policy_has_explicit_v1_identity() {
        assert_eq!(
            policy()
                .runtime_bootstrap_identity()
                .expect("valid Canic policy identity"),
            PolicyIdentity::new("canic.memory-bootstrap-policy", 1)
                .expect("valid expected policy identity")
        );
    }

    fn key(value: &str) -> StableKey {
        StableKey::parse(value).expect("stable key")
    }

    fn slot(id: u8) -> AllocationSlotDescriptor {
        AllocationSlotDescriptor::memory_manager(id).expect("usable MemoryManager id")
    }

    #[test]
    fn rejects_memory_manager_sentinel_id_through_ic_memory() {
        let err = AllocationSlotDescriptor::memory_manager(ic_memory::MEMORY_MANAGER_INVALID_ID)
            .expect_err("ID 255 is the unallocated-bucket sentinel");
        std::assert_matches!(
            err,
            MemoryManagerSlotError::InvalidMemoryManagerId { id }
                if id == ic_memory::MEMORY_MANAGER_INVALID_ID
        );
    }

    fn validate(stable_key: &str, id: u8) -> Result<(), MemoryRegistryError> {
        policy().validate_slot(&key(stable_key), &slot(id))
    }

    fn validate_reserved(stable_key: &str, id: u8) -> Result<(), MemoryRegistryError> {
        policy().validate_reserved_slot(&key(stable_key), &slot(id))
    }

    #[test]
    fn accepts_canic_framework_namespaces_in_owned_ranges() {
        validate("canic.core.runtime.canister_children.v1", CANIC_CORE_MIN_ID)
            .expect("first core slot");
        validate("canic.core.future.v1", CANIC_CORE_MAX_ID).expect("last core slot");
        validate(
            "canic.control_plane.template.manifests.v1",
            CANIC_CONTROL_PLANE_MIN_ID,
        )
        .expect("first control-plane slot");
        validate("canic.control_plane.future.v1", CANIC_CONTROL_PLANE_MAX_ID)
            .expect("last control-plane slot");
        validate(
            "canic.control_plane.fleet_coordinator.funding.v1",
            FLEET_COORDINATOR_FUNDING_ID,
        )
        .expect("dedicated Fleet Coordinator funding slot");
        validate("canic.control_plane.root.funding.v1", ROOT_FUNDING_ID)
            .expect("dedicated Root funding slot");
        validate(
            "canic.control_plane.fleet_admission.v1",
            FLEET_COORDINATOR_ADMISSION_ID,
        )
        .expect("dedicated Fleet Coordinator admission slot");
        validate("canic.control_plane.root.admission.v1", ROOT_ADMISSION_ID)
            .expect("dedicated Root admission slot");
    }

    #[test]
    fn rejects_canic_framework_namespaces_outside_owned_ranges() {
        let err = validate("canic.core.fleet.state.v1", CANIC_CONTROL_PLANE_MIN_ID)
            .expect_err("core key cannot claim control-plane range");
        std::assert_matches!(err, MemoryRegistryError::RangeAuthorityViolation { .. });

        let err = validate(
            "canic.control_plane.template.manifests.v1",
            CANIC_CORE_MIN_ID,
        )
        .expect_err("control-plane key cannot claim core range");
        std::assert_matches!(err, MemoryRegistryError::RangeAuthorityViolation { .. });

        let err = validate("canic.core.future.v1", FLEET_COORDINATOR_FUNDING_ID)
            .expect_err("core key cannot claim the dedicated funding slot");
        std::assert_matches!(err, MemoryRegistryError::RangeAuthorityViolation { .. });
        let err = validate("canic.core.future.v1", ROOT_FUNDING_ID)
            .expect_err("core key cannot claim the dedicated Root funding slot");
        std::assert_matches!(err, MemoryRegistryError::RangeAuthorityViolation { .. });
        let err = validate("canic.core.future.v1", FLEET_COORDINATOR_ADMISSION_ID)
            .expect_err("core key cannot claim the dedicated Coordinator admission slot");
        std::assert_matches!(err, MemoryRegistryError::RangeAuthorityViolation { .. });
        let err = validate("canic.core.future.v1", ROOT_ADMISSION_ID)
            .expect_err("core key cannot claim the dedicated Root admission slot");
        std::assert_matches!(err, MemoryRegistryError::RangeAuthorityViolation { .. });

        let err = validate("canic.unknown.state.v1", CANIC_CORE_MAX_ID + 1)
            .expect_err("unknown canic namespace is reserved");
        std::assert_matches!(err, MemoryRegistryError::RangeAuthorityViolation { .. });
    }

    #[test]
    fn accepts_application_keys_only_outside_reserved_ranges() {
        validate("app.users.v1", CANIC_CORE_MAX_ID + 1).expect("application slot");
        validate("app.archive.v1", ic_memory::MEMORY_MANAGER_MAX_ID).expect("last app slot");

        let err = validate("app.users.v1", CANIC_CORE_MIN_ID)
            .expect_err("application key cannot claim Canic core range");
        std::assert_matches!(err, MemoryRegistryError::RangeAuthorityViolation { .. });

        let err = validate("app.users.v1", CANIC_CONTROL_PLANE_MAX_ID)
            .expect_err("application key cannot claim Canic control-plane reserve");
        std::assert_matches!(err, MemoryRegistryError::RangeAuthorityViolation { .. });

        let err = validate("app.users.v1", ic_memory::MEMORY_MANAGER_LEDGER_ID)
            .expect_err("application key cannot claim ic-memory governance range");
        std::assert_matches!(err, MemoryRegistryError::RangeAuthorityViolation { .. });
    }

    #[test]
    fn rejects_application_reservations() {
        let err = validate_reserved("app.users.v1", CANIC_CORE_MAX_ID + 1)
            .expect_err("Canic does not pre-reserve application keys");
        std::assert_matches!(err, MemoryRegistryError::RangeAuthorityViolation { .. });
    }
}