canic-core 0.56.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
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
//! Protected Canic-to-Canic internal call API.
//!
//! This module owns the native Canic internal RPC path: method-scoped root
//! proofs, protected endpoint descriptors, generated-client transport options,
//! envelope construction, proof caching, and the narrow auth-material repair
//! retry.

mod endpoint;
mod envelope;
mod proof_cache;

pub use endpoint::ProtectedInternalEndpoint;

use super::call::{Call, CallResult};
use crate::{
    cdk::{
        candid::{CandidType, encode_one},
        types::Principal,
    },
    dto::{
        auth::{CanicInternalCallEnvelopeV1, InternalInvocationProofRequest},
        error::{Error, ErrorCode},
    },
    ids::CanisterRole,
    ops::{config::ConfigOps, ic::IcOps, runtime::env::EnvOps},
};
use candid::{encode_args, utils::ArgumentEncoder};
use envelope::{build_internal_call_envelope, encode_internal_call_envelope_raw};
use proof_cache::{
    fresh_internal_invocation_proof_for_request, internal_invocation_proof_for_request,
    invalidate_internal_invocation_proof,
};
use serde::de::DeserializeOwned;
use std::borrow::Cow;

const DEFAULT_INTERNAL_CALL_PROOF_TTL_SECS: u64 = 120;

///
/// CanicCall
///
/// Low-level protected Canic internal-call primitive.
///
/// Unlike `Call`, this API is only for Canic-to-Canic protected internal
/// endpoints. It obtains a root-signed method-scoped invocation proof, wraps
/// the original Candid arguments in `CanicInternalCallEnvelopeV1`, encodes that
/// envelope as raw ingress bytes, and dispatches through the raw call path.
///

pub struct CanicCall;

impl CanicCall {
    #[must_use]
    pub fn bounded_wait(
        canister_id: impl Into<Principal>,
        method: &str,
    ) -> CanicCallBuilder<'static> {
        CanicCallBuilder::new(WaitMode::Bounded, canister_id.into(), method)
    }

    #[must_use]
    pub fn unbounded_wait(
        canister_id: impl Into<Principal>,
        method: &str,
    ) -> CanicCallBuilder<'static> {
        CanicCallBuilder::new(WaitMode::Unbounded, canister_id.into(), method)
    }
}

///
/// CanicInternalClient
///
/// Generic protected internal client over generated endpoint descriptors.
///

#[derive(Clone, Copy, Debug)]
pub struct CanicInternalClient {
    canister_id: Principal,
    options: CanicInternalCallOptions,
}

impl CanicInternalClient {
    #[must_use]
    pub const fn new(canister_id: Principal) -> Self {
        Self {
            canister_id,
            options: CanicInternalCallOptions::new(),
        }
    }

    #[must_use]
    pub const fn with_options(mut self, options: CanicInternalCallOptions) -> Self {
        self.options = options;
        self
    }

    #[must_use]
    pub const fn with_bounded_wait(mut self) -> Self {
        self.options = self.options.with_bounded_wait();
        self
    }

    #[must_use]
    pub const fn with_unbounded_wait(mut self) -> Self {
        self.options = self.options.with_unbounded_wait();
        self
    }

    #[must_use]
    pub const fn with_cycles(mut self, cycles: u128) -> Self {
        self.options = self.options.with_cycles(cycles);
        self
    }

    #[must_use]
    pub const fn with_proof_ttl_secs(mut self, ttl_secs: u64) -> Self {
        self.options = self.options.with_proof_ttl_secs(ttl_secs);
        self
    }

    pub async fn call_update<A>(
        &self,
        endpoint: &ProtectedInternalEndpoint,
        caller_role: CanisterRole,
        args: A,
    ) -> Result<CallResult, Error>
    where
        A: ArgumentEncoder,
    {
        if !endpoint.accepts_role(&caller_role) {
            return Err(Error::invalid(format!(
                "caller role '{caller_role}' is not accepted by protected internal endpoint '{}'",
                endpoint.method()
            )));
        }

        let builder = match self.options.wait {
            CanicInternalWaitMode::Bounded => {
                CanicCall::bounded_wait(self.canister_id, endpoint.method())
            }
            CanicInternalWaitMode::Unbounded => {
                CanicCall::unbounded_wait(self.canister_id, endpoint.method())
            }
        };
        let builder = builder
            .with_caller_role(caller_role)
            .with_cycles(self.options.cycles);
        let builder = if let Some(ttl_secs) = self.options.proof_ttl_secs {
            builder.with_proof_ttl_secs(ttl_secs)
        } else {
            builder
        };

        builder.with_args(args)?.execute().await
    }

    pub async fn call_update_with_single_role<A>(
        &self,
        endpoint: &ProtectedInternalEndpoint,
        args: A,
    ) -> Result<CallResult, Error>
    where
        A: ArgumentEncoder,
    {
        let role = endpoint.required_single_role()?;
        self.call_update(endpoint, role, args).await
    }

    pub async fn call_update_result<T, A>(
        &self,
        endpoint: &ProtectedInternalEndpoint,
        caller_role: CanisterRole,
        args: A,
    ) -> Result<T, Error>
    where
        T: CandidType + DeserializeOwned,
        A: ArgumentEncoder,
    {
        let call = self.call_update(endpoint, caller_role, args).await?;
        let result: Result<T, Error> = call.candid()?;
        result
    }

    pub async fn call_update_result_with_single_role<T, A>(
        &self,
        endpoint: &ProtectedInternalEndpoint,
        args: A,
    ) -> Result<T, Error>
    where
        T: CandidType + DeserializeOwned,
        A: ArgumentEncoder,
    {
        let role = endpoint.required_single_role()?;
        self.call_update_result(endpoint, role, args).await
    }
}

///
/// CanicInternalCallOptions
///
/// Transport options shared by generated protected internal clients.
///

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct CanicInternalCallOptions {
    wait: CanicInternalWaitMode,
    cycles: u128,
    proof_ttl_secs: Option<u64>,
}

impl CanicInternalCallOptions {
    #[must_use]
    pub const fn new() -> Self {
        Self {
            wait: CanicInternalWaitMode::Unbounded,
            cycles: 0,
            proof_ttl_secs: None,
        }
    }

    #[must_use]
    pub const fn with_bounded_wait(mut self) -> Self {
        self.wait = CanicInternalWaitMode::Bounded;
        self
    }

    #[must_use]
    pub const fn with_unbounded_wait(mut self) -> Self {
        self.wait = CanicInternalWaitMode::Unbounded;
        self
    }

    #[must_use]
    pub const fn with_cycles(mut self, cycles: u128) -> Self {
        self.cycles = cycles;
        self
    }

    #[must_use]
    pub const fn with_proof_ttl_secs(mut self, ttl_secs: u64) -> Self {
        self.proof_ttl_secs = Some(ttl_secs);
        self
    }
}

impl Default for CanicInternalCallOptions {
    fn default() -> Self {
        Self::new()
    }
}

///
/// CanicInternalWaitMode
///

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CanicInternalWaitMode {
    Bounded,
    Unbounded,
}

///
/// CanicCallBuilder
///

pub struct CanicCallBuilder<'a> {
    wait: WaitMode,
    canister_id: Principal,
    method: String,
    caller_role: Option<CanisterRole>,
    ttl_secs: Option<u64>,
    cycles: u128,
    args: Cow<'a, [u8]>,
}

impl CanicCallBuilder<'_> {
    fn new(wait: WaitMode, canister_id: Principal, method: &str) -> Self {
        Self {
            wait,
            canister_id,
            method: method.to_string(),
            caller_role: None,
            ttl_secs: None,
            cycles: 0,
            args: Cow::Owned(encode_args(()).expect("empty Candid tuple must encode")),
        }
    }

    #[must_use]
    pub fn with_caller_role(mut self, role: CanisterRole) -> Self {
        self.caller_role = Some(role);
        self
    }

    #[must_use]
    pub const fn with_proof_ttl_secs(mut self, ttl_secs: u64) -> Self {
        self.ttl_secs = Some(ttl_secs);
        self
    }

    pub fn with_arg<A>(mut self, arg: A) -> Result<Self, Error>
    where
        A: CandidType,
    {
        self.args = Cow::Owned(encode_one(arg).map_err(|err| Error::invalid(err.to_string()))?);
        Ok(self)
    }

    pub fn with_args<A>(mut self, args: A) -> Result<Self, Error>
    where
        A: ArgumentEncoder,
    {
        self.args = Cow::Owned(encode_args(args).map_err(|err| Error::invalid(err.to_string()))?);
        Ok(self)
    }

    #[must_use]
    pub fn with_raw_args<'b>(self, args: impl Into<Cow<'b, [u8]>>) -> CanicCallBuilder<'b> {
        CanicCallBuilder {
            wait: self.wait,
            canister_id: self.canister_id,
            method: self.method,
            caller_role: self.caller_role,
            ttl_secs: self.ttl_secs,
            cycles: self.cycles,
            args: args.into(),
        }
    }

    #[must_use]
    pub const fn with_cycles(mut self, cycles: u128) -> Self {
        self.cycles = cycles;
        self
    }

    pub async fn execute(self) -> Result<CallResult, Error> {
        validate_internal_call_target_method(&self.method)?;
        let ttl_secs = self.proof_ttl_secs()?;
        let role = self
            .caller_role
            .ok_or_else(|| Error::invalid("CanicCall requires with_caller_role(...)"))?;
        validate_internal_call_caller_role(&role)?;
        let request = InternalInvocationProofRequest {
            subject: IcOps::canister_self(),
            role,
            subnet_id: EnvOps::subnet_pid().ok(),
            audience: self.canister_id,
            audience_method: self.method.clone(),
            ttl_secs,
            metadata: None,
        };
        let args = self.args.into_owned();
        let proof = internal_invocation_proof_for_request(request.clone()).await?;

        let envelope =
            build_internal_call_envelope(self.canister_id, &self.method, proof, args.clone());
        let result = execute_internal_call_once(
            self.wait,
            self.canister_id,
            &self.method,
            self.cycles,
            envelope,
        )
        .await?;
        if !internal_call_result_is_retryable(&result) {
            return Ok(result);
        }

        invalidate_internal_invocation_proof(&request)?;
        let proof = fresh_internal_invocation_proof_for_request(request).await?;
        let envelope = build_internal_call_envelope(self.canister_id, &self.method, proof, args);
        execute_internal_call_once(
            self.wait,
            self.canister_id,
            &self.method,
            self.cycles,
            envelope,
        )
        .await
    }

    fn proof_ttl_secs(&self) -> Result<u64, Error> {
        let requested = self
            .ttl_secs
            .unwrap_or(DEFAULT_INTERNAL_CALL_PROOF_TTL_SECS);
        let max = ConfigOps::role_attestation_config()
            .map_err(Error::from)?
            .max_ttl_secs;
        effective_internal_call_proof_ttl_secs(requested, max)
    }
}

fn validate_internal_call_target_method(method: &str) -> Result<(), Error> {
    if method.trim().is_empty() {
        return Err(Error::invalid(
            "CanicCall requires a non-empty target method",
        ));
    }
    Ok(())
}

fn validate_internal_call_caller_role(role: &CanisterRole) -> Result<(), Error> {
    if role.as_str().trim().is_empty() {
        return Err(Error::invalid("CanicCall requires a non-empty caller role"));
    }
    Ok(())
}

fn effective_internal_call_proof_ttl_secs(requested: u64, max: u64) -> Result<u64, Error> {
    if requested == 0 {
        return Err(Error::invalid(
            "CanicCall proof TTL must be greater than zero",
        ));
    }
    let effective = requested.min(max);
    if effective == 0 {
        return Err(Error::invalid(
            "CanicCall proof TTL maximum must be greater than zero",
        ));
    }
    Ok(effective)
}

async fn execute_internal_call_once(
    wait: WaitMode,
    canister_id: Principal,
    method: &str,
    cycles: u128,
    envelope: CanicInternalCallEnvelopeV1,
) -> Result<CallResult, Error> {
    let call = match wait {
        WaitMode::Bounded => Call::bounded_wait(canister_id, method),
        WaitMode::Unbounded => Call::unbounded_wait(canister_id, method),
    }
    .with_cycles(cycles)
    .with_raw_args(encode_internal_call_envelope_raw(envelope)?);

    call.execute().await
}

fn internal_call_result_is_retryable(result: &CallResult) -> bool {
    let Ok(Err(err)) = result.candid::<Result<candid::Reserved, Error>>() else {
        return false;
    };
    internal_call_error_is_retryable(&err)
}

const fn internal_call_error_is_retryable(err: &Error) -> bool {
    matches!(
        err.code,
        ErrorCode::AuthKeyUnknown | ErrorCode::AuthMaterialStale
    )
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum WaitMode {
    Bounded,
    Unbounded,
}

#[cfg(test)]
mod tests;