canic-core 0.24.8

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
use crate::dto::{
    auth::{
        DelegationProvisionResponse, DelegationRequest, RoleAttestationRequest,
        SignedRoleAttestation,
    },
    prelude::*,
};

//
// Request
//
// Root orchestration request.
//

#[derive(CandidType, Clone, Debug, Deserialize)]
pub enum Request {
    CreateCanister(CreateCanisterRequest),
    UpgradeCanister(UpgradeCanisterRequest),
    Cycles(CyclesRequest),
    IssueDelegation(DelegationRequest),
    IssueRoleAttestation(RoleAttestationRequest),
}

impl Request {
    // create_canister
    //
    // Build a root request for canister provisioning.
    #[must_use]
    pub const fn create_canister(request: CreateCanisterRequest) -> Self {
        Self::CreateCanister(request)
    }

    // upgrade_canister
    //
    // Build a root request for upgrading an existing canister.
    #[must_use]
    pub const fn upgrade_canister(request: UpgradeCanisterRequest) -> Self {
        Self::UpgradeCanister(request)
    }

    // cycles
    //
    // Build a root request for requesting/transferring cycles.
    #[must_use]
    pub const fn cycles(request: CyclesRequest) -> Self {
        Self::Cycles(request)
    }

    // issue_delegation
    //
    // Build a root request for delegated token issuance.
    #[must_use]
    pub const fn issue_delegation(request: DelegationRequest) -> Self {
        Self::IssueDelegation(request)
    }

    // issue_role_attestation
    //
    // Build a root request for role attestation issuance.
    #[must_use]
    pub const fn issue_role_attestation(request: RoleAttestationRequest) -> Self {
        Self::IssueRoleAttestation(request)
    }

    // family
    //
    // Resolve the request capability family without exposing variant matches at call sites.
    #[must_use]
    pub const fn family(&self) -> RequestFamily {
        match self {
            Self::CreateCanister(_) => RequestFamily::Provision,
            Self::UpgradeCanister(_) => RequestFamily::Upgrade,
            Self::Cycles(_) => RequestFamily::RequestCycles,
            Self::IssueDelegation(_) => RequestFamily::IssueDelegation,
            Self::IssueRoleAttestation(_) => RequestFamily::IssueRoleAttestation,
        }
    }

    // metadata
    //
    // Return replay metadata carried by the request variant.
    #[must_use]
    pub const fn metadata(&self) -> Option<RootRequestMetadata> {
        match self {
            Self::CreateCanister(req) => req.metadata,
            Self::UpgradeCanister(req) => req.metadata,
            Self::Cycles(req) => req.metadata,
            Self::IssueDelegation(req) => req.metadata,
            Self::IssueRoleAttestation(req) => req.metadata,
        }
    }

    // with_metadata
    //
    // Attach root replay metadata to the request payload.
    #[must_use]
    pub const fn with_metadata(mut self, metadata: RootRequestMetadata) -> Self {
        match &mut self {
            Self::CreateCanister(req) => req.metadata = Some(metadata),
            Self::UpgradeCanister(req) => req.metadata = Some(metadata),
            Self::Cycles(req) => req.metadata = Some(metadata),
            Self::IssueDelegation(req) => req.metadata = Some(metadata),
            Self::IssueRoleAttestation(req) => req.metadata = Some(metadata),
        }
        self
    }

    // without_metadata
    //
    // Remove root replay metadata for canonical hashing and signature binding.
    #[must_use]
    pub const fn without_metadata(mut self) -> Self {
        match &mut self {
            Self::CreateCanister(req) => req.metadata = None,
            Self::UpgradeCanister(req) => req.metadata = None,
            Self::Cycles(req) => req.metadata = None,
            Self::IssueDelegation(req) => req.metadata = None,
            Self::IssueRoleAttestation(req) => req.metadata = None,
        }
        self
    }

    // upgrade_request
    //
    // Return the upgrade payload when this request belongs to the upgrade family.
    #[must_use]
    pub const fn upgrade_request(&self) -> Option<&UpgradeCanisterRequest> {
        match self {
            Self::UpgradeCanister(request) => Some(request),
            _ => None,
        }
    }
}

//
// RequestFamily
//
// Request family label.
//

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum RequestFamily {
    Provision,
    Upgrade,
    RequestCycles,
    IssueDelegation,
    IssueRoleAttestation,
}

impl RequestFamily {
    // label
    //
    // Return the canonical family label used across capability checks and logs.
    #[must_use]
    pub const fn label(self) -> &'static str {
        match self {
            Self::Provision => "Provision",
            Self::Upgrade => "Upgrade",
            Self::RequestCycles => "RequestCycles",
            Self::IssueDelegation => "IssueDelegation",
            Self::IssueRoleAttestation => "IssueRoleAttestation",
        }
    }
}

//
// RootCapabilityCommand
//
// Internal root command.
//

#[derive(CandidType, Clone, Debug, Deserialize)]
pub enum RootCapabilityCommand {
    ProvisionCanister(CreateCanisterRequest),
    UpgradeCanister(UpgradeCanisterRequest),
    RequestCycles(CyclesRequest),
    IssueDelegation(DelegationRequest),
    IssueRoleAttestation(RoleAttestationRequest),
}

impl From<Request> for RootCapabilityCommand {
    fn from(value: Request) -> Self {
        match value {
            Request::CreateCanister(req) => Self::ProvisionCanister(req),
            Request::UpgradeCanister(req) => Self::UpgradeCanister(req),
            Request::Cycles(req) => Self::RequestCycles(req),
            Request::IssueDelegation(req) => Self::IssueDelegation(req),
            Request::IssueRoleAttestation(req) => Self::IssueRoleAttestation(req),
        }
    }
}

//
// RootRequestMetadata
//
// Replay metadata.
//

#[derive(CandidType, Clone, Copy, Debug, Deserialize, Eq, PartialEq)]
pub struct RootRequestMetadata {
    pub request_id: [u8; 32],
    pub ttl_seconds: u64,
}

//
// CreateCanisterRequest
//
// Create-canister payload.
//

#[derive(CandidType, Clone, Debug, Deserialize)]
pub struct CreateCanisterRequest {
    pub canister_role: CanisterRole,
    pub parent: CreateCanisterParent,
    pub extra_arg: Option<Vec<u8>>,
    #[serde(default)]
    pub metadata: Option<RootRequestMetadata>,
}

//
// CreateCanisterParent
//
// Parent selection.
//

#[derive(CandidType, Clone, Debug, Deserialize)]
pub enum CreateCanisterParent {
    Root,
    // Use the requesting canister.
    ThisCanister,
    // Use the caller's parent.
    Parent,
    Canister(Principal),
    Directory(CanisterRole),
}

//
// UpgradeCanisterRequest
//
// Upgrade-canister payload.
//

#[derive(CandidType, Clone, Debug, Deserialize)]
pub struct UpgradeCanisterRequest {
    pub canister_pid: Principal,
    #[serde(default)]
    pub metadata: Option<RootRequestMetadata>,
}

//
// CyclesRequest
//
// Cycles payload.
//

#[derive(CandidType, Clone, Debug, Deserialize)]
pub struct CyclesRequest {
    pub cycles: u128,
    #[serde(default)]
    pub metadata: Option<RootRequestMetadata>,
}

//
// Response
//
// Root response payload.
//

#[derive(CandidType, Clone, Debug, Deserialize, Serialize)]
pub enum Response {
    CreateCanister(CreateCanisterResponse),
    UpgradeCanister(UpgradeCanisterResponse),
    Cycles(CyclesResponse),
    DelegationIssued(DelegationProvisionResponse),
    RoleAttestationIssued(SignedRoleAttestation),
}

//
// CreateCanisterResponse
// Result of creating and installing a new canister.
//

#[derive(CandidType, Clone, Debug, Deserialize, Serialize)]
pub struct CreateCanisterResponse {
    pub new_canister_pid: Principal,
}

//
// UpgradeCanisterResponse
// Result of an upgrade request (currently empty, reserved for metadata)
//

#[derive(CandidType, Clone, Debug, Deserialize, Serialize)]
pub struct UpgradeCanisterResponse {}

//
// CyclesResponse
// Result of transferring cycles to a child canister
//

#[derive(CandidType, Clone, Debug, Deserialize, Serialize)]
pub struct CyclesResponse {
    pub cycles_transferred: u128,
}

//
// TESTS
//

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

    fn p(id: u8) -> Principal {
        Principal::from_slice(&[id; 29])
    }

    fn metadata(id: u8) -> RootRequestMetadata {
        RootRequestMetadata {
            request_id: [id; 32],
            ttl_seconds: 60,
        }
    }

    fn requests_with_no_metadata() -> Vec<Request> {
        vec![
            Request::create_canister(CreateCanisterRequest {
                canister_role: CanisterRole::new("app"),
                parent: CreateCanisterParent::Root,
                extra_arg: None,
                metadata: None,
            }),
            Request::upgrade_canister(UpgradeCanisterRequest {
                canister_pid: p(2),
                metadata: None,
            }),
            Request::cycles(CyclesRequest {
                cycles: 100,
                metadata: None,
            }),
            Request::issue_delegation(DelegationRequest {
                shard_pid: p(3),
                scopes: vec!["rpc:verify".to_string()],
                aud: vec![p(4)],
                ttl_secs: 60,
                verifier_targets: vec![],
                include_root_verifier: false,
                metadata: None,
            }),
            Request::issue_role_attestation(RoleAttestationRequest {
                subject: p(5),
                role: CanisterRole::new("test"),
                subnet_id: None,
                audience: Some(p(6)),
                ttl_secs: 60,
                epoch: 0,
                metadata: None,
            }),
        ]
    }

    #[test]
    fn request_family_matches_all_variants() {
        let families: Vec<RequestFamily> = requests_with_no_metadata()
            .iter()
            .map(Request::family)
            .collect();
        assert_eq!(
            families,
            vec![
                RequestFamily::Provision,
                RequestFamily::Upgrade,
                RequestFamily::RequestCycles,
                RequestFamily::IssueDelegation,
                RequestFamily::IssueRoleAttestation,
            ]
        );
    }

    #[test]
    fn with_metadata_and_without_metadata_cover_all_variants() {
        let replay_meta = metadata(7);

        for request in requests_with_no_metadata() {
            let with_meta = request.clone().with_metadata(replay_meta);
            assert_eq!(
                with_meta.metadata(),
                Some(replay_meta),
                "with_metadata must set metadata for every request variant"
            );

            let without_meta = with_meta.without_metadata();
            assert_eq!(
                without_meta.metadata(),
                None,
                "without_metadata must strip metadata for every request variant"
            );
        }
    }

    #[test]
    fn upgrade_request_is_only_available_for_upgrade_variant() {
        let upgrade = Request::upgrade_canister(UpgradeCanisterRequest {
            canister_pid: p(9),
            metadata: Some(metadata(9)),
        });
        assert!(upgrade.upgrade_request().is_some());

        for request in requests_with_no_metadata() {
            if !matches!(request, Request::UpgradeCanister(_)) {
                assert!(request.upgrade_request().is_none());
            }
        }
    }
}