canic-core 0.92.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
//! Module: workflow::runtime::auth::provisioning
//!
//! Responsibility: orchestrate root-triggered delegated-auth proof provisioning.
//! Does not own: endpoint authorization, proof storage, or proof verification.
//! Boundary: root auth API calls this to validate pending proof batches and
//! broadcast issuer-local install requests.

use crate::{
    InternalError, InternalErrorOrigin,
    cdk::types::Principal,
    config::schema::DelegatedTokenConfig,
    domain::auth::DelegatedAuthNetwork,
    dto::{
        auth::{
            InstallActiveDelegationProofRequest, InstallActiveDelegationProofResponse,
            RootDelegationProofBatchInstallRequest, RootDelegationProofBatchProof,
            RootDelegationProofInstallOutcome, RootProof,
        },
        error::{Error, ErrorCode},
    },
    ids::BuildNetwork,
    ops::{
        auth::AuthOps,
        ic::{
            IcOps,
            call::{CallOps, CallResult},
        },
        runtime::env::EnvOps,
    },
    protocol,
    workflow::runtime::auth::RuntimeAuthWorkflow,
};
use std::future::Future;

impl RuntimeAuthWorkflow {
    /// Create or reuse and install one chain-key root delegation proof.
    pub async fn provision_chain_key_delegation_proof_for_issuer_root(
        issuer_pid: Principal,
    ) -> Result<(), InternalError> {
        EnvOps::require_root()?;
        let proof =
            Self::get_or_create_chain_key_delegation_proof_for_issuer_root(issuer_pid).await?;
        let RootProof::IcChainKeyBatchSignatureV1(root_proof) = &proof.proof.root_proof;
        let result = install_chain_key_delegation_proof_batch(
            RootDelegationProofBatchInstallRequest {
                batch_id: root_proof.header.batch_id,
                proofs: vec![proof],
            },
            IcOps::now_nanos(),
        )
        .await;
        result.into_explicit_result(issuer_pid)
    }

    /// Return or create one chain-key root delegation proof for the calling issuer.
    pub async fn get_or_create_chain_key_delegation_proof_for_issuer_root(
        issuer_pid: Principal,
    ) -> Result<RootDelegationProofBatchProof, InternalError> {
        EnvOps::require_root()?;
        let config = crate::ops::config::ConfigOps::delegated_tokens_config()?;
        require_chain_key_root_proof_mode(&config)?;
        let build_network = build_network_from_delegated_auth_config(&config)?;
        let max_cert_ttl_ns = delegated_token_max_ttl_ns(&config)?;
        let min_accepted_proof_epoch = chain_key_min_accepted_proof_epoch(&config)?;
        let now_ns = IcOps::now_nanos();

        AuthOps::get_or_create_chain_key_delegation_proof_for_issuer(
            issuer_pid,
            build_network,
            max_cert_ttl_ns,
            min_accepted_proof_epoch,
            now_ns,
        )
        .await?
        .ok_or_else(|| {
            InternalError::auth_proof_pending(
                "chain-key root delegation proof is not available yet; retry",
            )
        })
    }
}

pub(super) async fn install_chain_key_delegation_proof_batch(
    request: RootDelegationProofBatchInstallRequest,
    now_ns: u64,
) -> ChainKeyDelegationProofBatchInstallResult {
    install_chain_key_delegation_proof_batch_with_issuer_install(
        request,
        now_ns,
        install_delegation_proof_on_issuer,
    )
    .await
}

async fn install_chain_key_delegation_proof_batch_with_issuer_install<F, Fut>(
    request: RootDelegationProofBatchInstallRequest,
    now_ns: u64,
    mut install_issuer: F,
) -> ChainKeyDelegationProofBatchInstallResult
where
    F: FnMut(Principal, InstallActiveDelegationProofRequest) -> Fut,
    Fut: Future<Output = Result<RootDelegationProofInstallOutcome, IssuerProofInstallError>>,
{
    let mut installed_any = false;
    let mut first_failure = None;
    for proof in request.proofs {
        let issuer_pid = proof.issuer_pid;
        let cert_hash = proof.cert_hash;
        let result = install_issuer(
            issuer_pid,
            InstallActiveDelegationProofRequest { proof: proof.proof },
        )
        .await;
        match result {
            Ok(
                RootDelegationProofInstallOutcome::Installed
                | RootDelegationProofInstallOutcome::AlreadyInstalled,
            ) => {
                installed_any = AuthOps::record_chain_key_root_delegation_install_success(
                    request.batch_id,
                    issuer_pid,
                    cert_hash,
                    now_ns,
                ) || installed_any;
            }
            Ok(outcome) => {
                AuthOps::record_chain_key_root_delegation_install_failure(
                    request.batch_id,
                    issuer_pid,
                    cert_hash,
                    outcome,
                );
            }
            Err(failure) => {
                AuthOps::record_chain_key_root_delegation_install_failure(
                    request.batch_id,
                    issuer_pid,
                    cert_hash,
                    failure.record_outcome(),
                );
                if first_failure.is_none() {
                    first_failure = Some(failure);
                }
            }
        }
    }
    ChainKeyDelegationProofBatchInstallResult {
        installed_any,
        first_failure,
    }
}

async fn install_delegation_proof_on_issuer(
    issuer_pid: Principal,
    request: InstallActiveDelegationProofRequest,
) -> Result<RootDelegationProofInstallOutcome, IssuerProofInstallError> {
    let builder =
        CallOps::unbounded_wait(issuer_pid, protocol::CANIC_INSTALL_ACTIVE_DELEGATION_PROOF)
            .with_arg(request)
            .map_err(IssuerProofInstallError::RequestEncoding)?;
    let call = builder
        .execute()
        .await
        .map_err(IssuerProofInstallError::Transport)?;
    issuer_install_outcome(call)
}

fn issuer_install_outcome(
    call: CallResult,
) -> Result<RootDelegationProofInstallOutcome, IssuerProofInstallError> {
    let result: Result<InstallActiveDelegationProofResponse, Error> = call
        .candid()
        .map_err(IssuerProofInstallError::InvalidResponse)?;
    issuer_install_response(result)
}

fn issuer_install_response(
    result: Result<InstallActiveDelegationProofResponse, Error>,
) -> Result<RootDelegationProofInstallOutcome, IssuerProofInstallError> {
    match result {
        Ok(_) => Ok(RootDelegationProofInstallOutcome::Installed),
        Err(err) => Err(IssuerProofInstallError::RejectedByIssuer(err)),
    }
}

pub(super) struct ChainKeyDelegationProofBatchInstallResult {
    pub(super) installed_any: bool,
    first_failure: Option<IssuerProofInstallError>,
}

impl ChainKeyDelegationProofBatchInstallResult {
    fn into_explicit_result(self, issuer_pid: Principal) -> Result<(), InternalError> {
        if self.installed_any {
            return Ok(());
        }
        match self.first_failure {
            Some(failure) => Err(failure.into_internal_error(issuer_pid)),
            None => Err(InternalError::public(Error::unavailable(format!(
                "chain-key delegation proof installation for issuer {issuer_pid} did not complete"
            )))),
        }
    }
}

enum IssuerProofInstallError {
    RequestEncoding(InternalError),
    Transport(InternalError),
    InvalidResponse(InternalError),
    RejectedByIssuer(Error),
}

impl IssuerProofInstallError {
    const fn record_outcome(&self) -> RootDelegationProofInstallOutcome {
        match self {
            Self::RequestEncoding(_) | Self::Transport(_) | Self::InvalidResponse(_) => {
                RootDelegationProofInstallOutcome::CallFailed
            }
            Self::RejectedByIssuer(err) => match err.code {
                ErrorCode::AuthProofExpired => {
                    RootDelegationProofInstallOutcome::ExpiredOrSuperseded
                }
                ErrorCode::AuthMaterialStale
                | ErrorCode::AuthProofPending
                | ErrorCode::InvalidInput => RootDelegationProofInstallOutcome::ProofMismatch,
                _ => RootDelegationProofInstallOutcome::RejectedBySigner,
            },
        }
    }

    fn into_internal_error(self, issuer_pid: Principal) -> InternalError {
        match self {
            Self::RequestEncoding(cause) => InternalError::public(Error::internal(format!(
                "chain-key delegation proof request for issuer {issuer_pid} could not be encoded"
            )))
            .with_diagnostic_context(cause.to_string()),
            Self::Transport(cause) => InternalError::public(Error::unavailable(format!(
                "chain-key delegation proof installation transport for issuer {issuer_pid} failed"
            )))
            .with_diagnostic_context(cause.to_string()),
            Self::InvalidResponse(cause) => InternalError::public(Error::internal(format!(
                "chain-key delegation proof installation response from issuer {issuer_pid} was invalid"
            )))
            .with_diagnostic_context(cause.to_string()),
            Self::RejectedByIssuer(err) => InternalError::public(err),
        }
    }
}

fn require_chain_key_root_proof_mode(config: &DelegatedTokenConfig) -> Result<(), InternalError> {
    if config.root_proof_mode.trim() == "chain_key_batch" {
        return Ok(());
    }
    Err(InternalError::invariant(
        InternalErrorOrigin::Workflow,
        "delegated-auth lazy repair requires root_proof_mode=\"chain_key_batch\"",
    ))
}

fn build_network_from_delegated_auth_config(
    config: &DelegatedTokenConfig,
) -> Result<BuildNetwork, InternalError> {
    let network = DelegatedAuthNetwork::parse(config.network.trim()).ok_or_else(|| {
        InternalError::invalid_input(
            "auth.delegated_tokens.network must be one of mainnet, local, pocketic, testnet",
        )
    })?;
    if network.is_mainnet() {
        Ok(BuildNetwork::Ic)
    } else {
        Ok(BuildNetwork::Local)
    }
}

fn delegated_token_max_ttl_ns(config: &DelegatedTokenConfig) -> Result<u64, InternalError> {
    let max_ttl_secs = config.max_ttl_secs.unwrap_or(24 * 60 * 60);
    max_ttl_secs.checked_mul(1_000_000_000).ok_or_else(|| {
        InternalError::invalid_input("auth.delegated_tokens.max_ttl_secs overflows nanoseconds")
    })
}

fn chain_key_min_accepted_proof_epoch(config: &DelegatedTokenConfig) -> Result<u64, InternalError> {
    config
        .chain_key_root_proof
        .min_accepted_proof_epoch
        .ok_or_else(|| {
            InternalError::invariant(
                InternalErrorOrigin::Workflow,
                "auth.delegated_tokens.chain_key_root_proof.min_accepted_proof_epoch is required for chain-key lazy repair",
            )
        })
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        cdk::types::Principal,
        dto::auth::{
            DelegatedRoleGrant, DelegationAudience, DelegationCert, DelegationProof,
            IssuerProofAlgorithm, IssuerProofBinding, RootDelegationProofBatchProof,
        },
        ids::{CanisterRole, cap},
    };
    use futures::executor::block_on;
    use std::cell::Cell;

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

    fn proof() -> RootDelegationProofBatchProof {
        RootDelegationProofBatchProof {
            issuer_pid: p(2),
            cert_hash: [3; 32],
            proof: DelegationProof {
                cert: DelegationCert {
                    root_pid: p(1),
                    issuer_pid: p(2),
                    issuer_proof_alg: IssuerProofAlgorithm::IcCanisterSignatureV1,
                    issuer_proof_binding_hash: [4; 32],
                    issuer_proof_binding: IssuerProofBinding::IcCanisterSignatureV1 {
                        seed_hash: [5; 32],
                    },
                    issued_at_ns: 10,
                    not_before_ns: 10,
                    expires_at_ns: 100,
                    max_token_ttl_ns: 30,
                    aud: DelegationAudience::Project("test".to_string()),
                    grants: vec![DelegatedRoleGrant {
                        target: CanisterRole::owned("project_instance".to_string()),
                        scopes: vec![cap::READ.to_string()],
                    }],
                },
                root_proof: crate::ops::auth::test_fixtures::chain_key_root_proof(8),
            },
        }
    }

    #[test]
    fn install_chain_key_batch_empty_request_is_noop() {
        let result = block_on(
            install_chain_key_delegation_proof_batch_with_issuer_install(
                RootDelegationProofBatchInstallRequest {
                    batch_id: [1; 32],
                    proofs: vec![],
                },
                20,
                |_issuer_pid, _request| async { Ok(RootDelegationProofInstallOutcome::Installed) },
            ),
        );

        assert!(!result.installed_any);
        assert!(result.first_failure.is_none());
    }

    #[test]
    fn install_chain_key_batch_broadcasts_proofs_to_issuers() {
        let calls = Cell::new(0);
        let result = block_on(
            install_chain_key_delegation_proof_batch_with_issuer_install(
                RootDelegationProofBatchInstallRequest {
                    batch_id: [2; 32],
                    proofs: vec![proof()],
                },
                20,
                |issuer_pid, _request| {
                    assert_eq!(issuer_pid, p(2));
                    calls.set(calls.get() + 1);
                    async { Ok(RootDelegationProofInstallOutcome::CallFailed) }
                },
            ),
        );

        assert_eq!(calls.get(), 1);
        assert!(!result.installed_any);
    }

    #[test]
    fn explicit_provisioning_transport_failure_is_typed_as_unavailable() {
        let result = ChainKeyDelegationProofBatchInstallResult {
            installed_any: false,
            first_failure: Some(IssuerProofInstallError::Transport(InternalError::infra(
                InternalErrorOrigin::Infra,
                "transport failed",
            ))),
        };
        let err = result
            .into_explicit_result(p(2))
            .expect_err("transport failure must reject explicit provisioning");

        assert_eq!(
            err.public_error().map(|err| err.code),
            Some(crate::dto::error::ErrorCode::Unavailable)
        );
    }

    #[test]
    fn explicit_provisioning_preserves_issuer_application_error() {
        let rejected = Error::new(
            ErrorCode::AuthProofExpired,
            "issuer rejected expired proof".to_string(),
        );
        let failure = issuer_install_response(Err(rejected.clone()))
            .expect_err("issuer application rejection must remain an error");
        assert_eq!(
            failure.record_outcome(),
            RootDelegationProofInstallOutcome::ExpiredOrSuperseded
        );

        let result = ChainKeyDelegationProofBatchInstallResult {
            installed_any: false,
            first_failure: Some(failure),
        };
        let err = result
            .into_explicit_result(p(2))
            .expect_err("issuer application rejection must reach the root facade");

        assert_eq!(err.public_error(), Some(&rejected));
    }
}