canic-core 0.66.6

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
use crate::{
    InternalError, InternalErrorOrigin,
    cdk::types::Principal,
    config::ConfigModel,
    dto::auth::SignedRoleAttestation,
    format::display_optional,
    ids::CanisterRole,
    ops::{
        auth::{AuthExpiryError, AuthOps, AuthOpsError},
        config::ConfigOps,
        ic::IcOps,
        runtime::env::EnvOps,
        runtime::metrics::auth::{
            record_attestation_epoch_rejected, record_attestation_verify_failed,
        },
    },
    workflow::prelude::*,
};

///
/// RuntimeAuthWorkflow
///
/// Owns delegated-auth runtime startup checks and auth-specific runtime boot
/// logging for root and non-root canisters.
///

pub struct RuntimeAuthWorkflow;

impl RuntimeAuthWorkflow {
    /// Fail fast when root delegated-auth config requires missing crypto support.
    pub fn ensure_root_crypto_contract() -> Result<(), InternalError> {
        let cfg = ConfigOps::get()?;
        if root_requires_delegated_token_proofs(&cfg)
            && !AuthOps::root_canister_sig_create_enabled()
        {
            return Err(InternalError::invariant(
                InternalErrorOrigin::Workflow,
                "delegated token proof issuance is configured in canic.toml, but this root build does not include IC canister-signature creation support; enable the `auth-root-canister-sig-create` feature for the root canister build".to_string(),
            ));
        }

        if root_requires_role_attestation_proofs(&cfg)
            && !AuthOps::root_canister_sig_create_enabled()
        {
            return Err(InternalError::invariant(
                InternalErrorOrigin::Workflow,
                "role attestation issuance is configured in canic.toml, but this root build does not include IC canister-signature creation support; enable the `auth-root-canister-sig-create` feature for the root canister build".to_string(),
            ));
        }

        Ok(())
    }

    /// Fail fast when one delegated-token issuer lacks canister-signature support.
    pub fn ensure_nonroot_crypto_contract(
        canister_role: &CanisterRole,
        canister_cfg: &crate::config::schema::CanisterConfig,
    ) -> Result<(), InternalError> {
        if nonroot_requires_delegated_token_issuer(canister_cfg)
            && !AuthOps::issuer_canister_sig_create_enabled()
        {
            return Err(InternalError::invariant(
                InternalErrorOrigin::Workflow,
                format!(
                    "canister '{canister_role}' is configured as a delegated auth issuer, but this build does not include IC canister-signature creation support; enable the `auth-issuer-canister-sig-create` feature for that canister build",
                ),
            ));
        }

        Self::ensure_delegated_token_verifier_contract(canister_role, canister_cfg)?;

        Ok(())
    }

    /// Fail fast when a non-root delegated-token verifier lacks hard-cut trust anchors.
    fn ensure_delegated_token_verifier_contract(
        canister_role: &CanisterRole,
        canister_cfg: &crate::config::schema::CanisterConfig,
    ) -> Result<(), InternalError> {
        let delegated_tokens_cfg = ConfigOps::delegated_tokens_config()?;
        if !nonroot_requires_delegated_token_verifier(canister_cfg) {
            return Ok(());
        }

        if !AuthOps::root_canister_sig_verify_enabled() {
            return Err(InternalError::invariant(
                InternalErrorOrigin::Workflow,
                format!(
                    "canister '{canister_role}' has auth proof verification enabled, but this build does not include IC canister-signature verification support; enable the `auth-delegated-token-verify` or `auth-root-canister-sig-verify` feature",
                ),
            ));
        }

        if !AuthOps::issuer_canister_sig_verify_enabled() {
            return Err(InternalError::invariant(
                InternalErrorOrigin::Workflow,
                format!(
                    "canister '{canister_role}' has delegated-token verification enabled, but this build does not include issuer IC canister-signature verification support; enable the `auth-delegated-token-verify` or `auth-issuer-canister-sig-verify` feature",
                ),
            ));
        }

        if delegated_tokens_cfg.enabled || canister_cfg.auth.role_attestation_cache {
            AuthOps::delegated_token_verifier_config().map(|_| ())
        } else {
            Ok(())
        }
    }

    /// Check local canister-signature support when the current canister mints delegated tokens.
    pub async fn check_issuer_canister_signature_support() -> Result<(), InternalError> {
        // Keep the public runtime hook async without adding hot-path outbound work.
        std::future::ready(()).await;
        let delegated_tokens_cfg = ConfigOps::delegated_tokens_config()?;
        let canister_cfg = ConfigOps::current_canister()?;
        if !delegated_tokens_cfg.enabled || !canister_cfg.auth.delegated_token_issuer {
            return Ok(());
        }

        crate::log!(
            Topic::Auth,
            Info,
            "delegated-token issuer canister-signature support ready issuer={}",
            IcOps::canister_self()
        );

        Ok(())
    }

    /// Verify a role attestation locally from its embedded root proof.
    pub async fn verify_role_attestation(
        attestation: &SignedRoleAttestation,
        min_accepted_epoch: u64,
    ) -> Result<(), InternalError> {
        // This verifier is intentionally local. The await preserves the async
        // endpoint shape; do not add root, issuer, or management-canister calls here.
        std::future::ready(()).await;
        let configured_min_accepted_epoch = ConfigOps::role_attestation_config()?
            .min_accepted_epoch_by_role
            .get(attestation.payload.role.as_str())
            .copied();
        let min_accepted_epoch =
            resolve_min_accepted_epoch(min_accepted_epoch, configured_min_accepted_epoch);

        let caller = IcOps::msg_caller();
        let self_pid = IcOps::canister_self();
        let now_ns = IcOps::now_nanos();
        let verifier_subnet = Some(EnvOps::subnet_pid()?);

        match AuthOps::verify_role_attestation_cached(
            attestation,
            caller,
            self_pid,
            verifier_subnet,
            now_ns,
            min_accepted_epoch,
        ) {
            Ok(_) => Ok(()),
            Err(err) => {
                record_attestation_verifier_rejection(&err);
                log_attestation_verifier_rejection(&err, attestation, caller, self_pid);
                Err(err.into())
            }
        }
    }
}

fn resolve_min_accepted_epoch(explicit: u64, configured: Option<u64>) -> u64 {
    if explicit > 0 {
        explicit
    } else {
        configured.unwrap_or(0)
    }
}

fn record_attestation_verifier_rejection(err: &AuthOpsError) {
    record_attestation_verify_failed();
    if let AuthOpsError::Expiry(AuthExpiryError::AttestationEpochRejected { .. }) = err {
        record_attestation_epoch_rejected();
    }
}

fn log_attestation_verifier_rejection(
    err: &AuthOpsError,
    attestation: &SignedRoleAttestation,
    caller: Principal,
    self_pid: Principal,
) {
    log!(
        Topic::Auth,
        Warn,
        "role attestation rejected local={} caller={} subject={} role={} audience={} subnet={} issued_at={} expires_at={} epoch={} error={}",
        self_pid,
        caller,
        attestation.payload.subject,
        attestation.payload.role,
        attestation.payload.audience,
        display_optional(attestation.payload.subnet_id),
        attestation.payload.issued_at_ns,
        attestation.payload.expires_at_ns,
        attestation.payload.epoch,
        err
    );
}

// Decide whether the root runtime must create canister-signature root proofs.
fn root_requires_delegated_token_proofs(cfg: &ConfigModel) -> bool {
    cfg.subnets.values().any(|subnet| {
        subnet.canisters.values().any(|canister| {
            cfg.auth.delegated_tokens.enabled && canister.auth.delegated_token_issuer
        })
    })
}

fn root_requires_role_attestation_proofs(cfg: &ConfigModel) -> bool {
    cfg.subnets.values().any(|subnet| {
        subnet
            .canisters
            .values()
            .any(|canister| canister.auth.role_attestation_cache)
    })
}

// Decide whether one non-root runtime must create issuer canister signatures.
const fn nonroot_requires_delegated_token_issuer(
    canister_cfg: &crate::config::schema::CanisterConfig,
) -> bool {
    canister_cfg.auth.delegated_token_issuer
}

// Decide whether one non-root runtime must carry delegated-token verifier support.
const fn nonroot_requires_delegated_token_verifier(
    canister_cfg: &crate::config::schema::CanisterConfig,
) -> bool {
    canister_cfg.auth.delegated_token_issuer
        || canister_cfg.auth.delegated_token_verifier
        || canister_cfg.auth.role_attestation_cache
}

#[cfg(test)]
mod tests {
    use super::{
        RuntimeAuthWorkflow, nonroot_requires_delegated_token_issuer,
        nonroot_requires_delegated_token_verifier, root_requires_delegated_token_proofs,
        root_requires_role_attestation_proofs,
    };
    use crate::{
        config::schema::{CanisterAuthConfig, CanisterKind},
        ids::CanisterRole,
        test::config::ConfigTestBuilder,
    };

    #[test]
    fn root_requires_canister_signature_proofs_for_delegated_issuer_when_enabled() {
        let mut issuer_cfg = ConfigTestBuilder::canister_config(CanisterKind::Shard);
        issuer_cfg.auth = CanisterAuthConfig {
            delegated_token_issuer: true,
            delegated_token_verifier: false,
            role_attestation_cache: false,
        };

        let cfg = ConfigTestBuilder::new()
            .with_prime_canister(
                CanisterRole::ROOT,
                ConfigTestBuilder::canister_config(CanisterKind::Root),
            )
            .with_prime_canister("user_shard", issuer_cfg)
            .build();

        assert!(root_requires_delegated_token_proofs(&cfg));
        assert!(!root_requires_role_attestation_proofs(&cfg));
    }

    #[test]
    fn root_requires_canister_signature_proofs_for_role_attestation_cache_when_delegated_tokens_disabled()
     {
        let mut verifier_cfg = ConfigTestBuilder::canister_config(CanisterKind::Singleton);
        verifier_cfg.auth = CanisterAuthConfig {
            delegated_token_issuer: false,
            delegated_token_verifier: false,
            role_attestation_cache: true,
        };

        let mut cfg = ConfigTestBuilder::new()
            .with_prime_canister(
                CanisterRole::ROOT,
                ConfigTestBuilder::canister_config(CanisterKind::Root),
            )
            .with_prime_canister("project_hub", verifier_cfg)
            .build();
        cfg.auth.delegated_tokens.enabled = false;

        assert!(!root_requires_delegated_token_proofs(&cfg));
        assert!(root_requires_role_attestation_proofs(&cfg));
    }

    #[test]
    fn root_ignores_delegated_issuer_when_delegated_tokens_disabled() {
        let mut issuer_cfg = ConfigTestBuilder::canister_config(CanisterKind::Shard);
        issuer_cfg.auth = CanisterAuthConfig {
            delegated_token_issuer: true,
            delegated_token_verifier: false,
            role_attestation_cache: false,
        };

        let mut cfg = ConfigTestBuilder::new()
            .with_prime_canister(
                CanisterRole::ROOT,
                ConfigTestBuilder::canister_config(CanisterKind::Root),
            )
            .with_prime_canister("user_shard", issuer_cfg)
            .build();
        cfg.auth.delegated_tokens.enabled = false;

        assert!(!root_requires_delegated_token_proofs(&cfg));
        assert!(!root_requires_role_attestation_proofs(&cfg));
    }

    #[test]
    fn root_does_not_require_auth_crypto_without_auth_roles() {
        let cfg = ConfigTestBuilder::new().build();

        assert!(!root_requires_delegated_token_proofs(&cfg));
        assert!(!root_requires_role_attestation_proofs(&cfg));
    }

    #[test]
    fn verifier_only_nonroot_does_not_require_auth_crypto() {
        let mut verifier_cfg = ConfigTestBuilder::canister_config(CanisterKind::Singleton);
        verifier_cfg.auth = CanisterAuthConfig {
            delegated_token_issuer: false,
            delegated_token_verifier: true,
            role_attestation_cache: false,
        };

        assert!(!nonroot_requires_delegated_token_issuer(&verifier_cfg));
        assert!(nonroot_requires_delegated_token_verifier(&verifier_cfg));
    }

    #[test]
    fn role_attestation_cache_nonroot_also_requires_delegated_token_verifier() {
        let mut verifier_cfg = ConfigTestBuilder::canister_config(CanisterKind::Singleton);
        verifier_cfg.auth = CanisterAuthConfig {
            delegated_token_issuer: false,
            delegated_token_verifier: false,
            role_attestation_cache: true,
        };

        assert!(!nonroot_requires_delegated_token_issuer(&verifier_cfg));
        assert!(nonroot_requires_delegated_token_verifier(&verifier_cfg));
    }

    #[test]
    fn default_nonroot_does_not_require_delegated_token_verifier() {
        let cfg = ConfigTestBuilder::canister_config(CanisterKind::Singleton);

        assert!(!nonroot_requires_delegated_token_verifier(&cfg));
    }

    #[test]
    fn auth_material_nonroot_requires_delegated_token_verifier() {
        let mut verifier_cfg = ConfigTestBuilder::canister_config(CanisterKind::Singleton);
        verifier_cfg.auth = CanisterAuthConfig {
            delegated_token_issuer: false,
            delegated_token_verifier: true,
            role_attestation_cache: true,
        };

        let mut issuer_cfg = ConfigTestBuilder::canister_config(CanisterKind::Shard);
        issuer_cfg.auth = CanisterAuthConfig {
            delegated_token_issuer: true,
            delegated_token_verifier: false,
            role_attestation_cache: false,
        };

        assert!(nonroot_requires_delegated_token_verifier(&verifier_cfg));
        assert!(nonroot_requires_delegated_token_verifier(&issuer_cfg));
    }

    #[cfg(not(feature = "auth-root-canister-sig-verify"))]
    #[test]
    fn delegated_token_verifier_startup_requires_canister_signature_verify_feature() {
        let _ = ConfigTestBuilder::new().install();
        let mut verifier_cfg = ConfigTestBuilder::canister_config(CanisterKind::Singleton);
        verifier_cfg.auth = CanisterAuthConfig {
            delegated_token_issuer: false,
            delegated_token_verifier: true,
            role_attestation_cache: true,
        };
        let role = CanisterRole::new("app");

        let err = RuntimeAuthWorkflow::ensure_nonroot_crypto_contract(&role, &verifier_cfg)
            .expect_err("expected verifier feature error");

        assert!(
            err.to_string().contains("auth-delegated-token-verify"),
            "expected delegated-token verifier feature error, got: {err}"
        );
    }

    #[test]
    fn issuer_nonroot_requires_issuer_canister_signature_create() {
        let mut issuer_cfg = ConfigTestBuilder::canister_config(CanisterKind::Shard);
        issuer_cfg.auth = CanisterAuthConfig {
            delegated_token_issuer: true,
            delegated_token_verifier: false,
            role_attestation_cache: true,
        };

        assert!(nonroot_requires_delegated_token_issuer(&issuer_cfg));
    }

    #[test]
    fn runtime_auth_workflow_type_exists_for_runtime_ownership() {
        let _ = RuntimeAuthWorkflow;
    }
}