Skip to main content

canic_core/api/auth/
mod.rs

1use crate::{
2    cdk::types::Principal,
3    dto::{
4        auth::{
5            AttestationKeySet, DelegatedToken, DelegatedTokenClaims, DelegationCert,
6            DelegationProof, DelegationProvisionResponse, DelegationProvisionStatus,
7            DelegationProvisionTargetKind, DelegationRequest, RoleAttestationRequest,
8            SignedRoleAttestation,
9        },
10        error::{Error, ErrorCode},
11        rpc::{Request as RootRequest, Response as RootCapabilityResponse},
12    },
13    error::InternalErrorClass,
14    log,
15    log::Topic,
16    ops::{
17        auth::DelegatedTokenOps,
18        config::ConfigOps,
19        ic::IcOps,
20        rpc::RpcOps,
21        runtime::env::EnvOps,
22        runtime::metrics::auth::{
23            record_attestation_refresh_failed, record_delegation_provision_complete,
24            record_delegation_verifier_target_count, record_delegation_verifier_target_failed,
25            record_delegation_verifier_target_missing, record_signer_issue_without_proof,
26        },
27        storage::auth::DelegationStateOps,
28    },
29    protocol,
30    workflow::rpc::request::handler::RootResponseWorkflow,
31};
32
33// Internal auth pipeline:
34// - `session` owns delegated-session ingress and replay/session state handling.
35// - `admin` owns explicit root-driven fanout preparation and routing.
36// - `proof_store` owns proof-install validation and storage/cache side effects.
37//
38// Keep these modules free of lateral calls to each other. Coordination stays here,
39// and shared invariants should live in dedicated seams like `ops::auth::audience`.
40mod admin;
41mod metadata;
42mod proof_store;
43mod session;
44mod verify_flow;
45
46///
47/// DelegationApi
48///
49/// Requires auth.delegated_tokens.enabled = true in config.
50///
51
52pub struct DelegationApi;
53
54impl DelegationApi {
55    const DELEGATED_TOKENS_DISABLED: &str =
56        "delegated token auth disabled; set auth.delegated_tokens.enabled=true in canic.toml";
57    const MAX_DELEGATED_SESSION_TTL_SECS: u64 = 24 * 60 * 60;
58    const SESSION_BOOTSTRAP_TOKEN_FINGERPRINT_DOMAIN: &[u8] =
59        b"canic-session-bootstrap-token-fingerprint:v1";
60
61    fn map_delegation_error(err: crate::InternalError) -> Error {
62        match err.class() {
63            InternalErrorClass::Infra | InternalErrorClass::Ops | InternalErrorClass::Workflow => {
64                Error::internal(err.to_string())
65            }
66            _ => Error::from(err),
67        }
68    }
69
70    /// Full delegation proof verification (structure + signature).
71    ///
72    /// Purely local verification; does not read certified data or require a
73    /// query context.
74    pub fn verify_delegation_proof(
75        proof: &DelegationProof,
76        authority_pid: Principal,
77    ) -> Result<(), Error> {
78        DelegatedTokenOps::verify_delegation_proof(proof, authority_pid)
79            .map_err(Self::map_delegation_error)
80    }
81
82    #[cfg(canic_test_delegation_material)]
83    #[must_use]
84    pub fn current_signing_proof_for_test() -> Option<DelegationProof> {
85        DelegationStateOps::latest_proof_dto()
86    }
87
88    async fn sign_token(
89        claims: DelegatedTokenClaims,
90        proof: DelegationProof,
91    ) -> Result<DelegatedToken, Error> {
92        DelegatedTokenOps::sign_token(claims, proof)
93            .await
94            .map_err(Self::map_delegation_error)
95    }
96
97    /// Issue a delegated token using a reusable local proof when possible.
98    ///
99    /// If the proof is missing or no longer valid for the requested claims, this
100    /// performs canonical shard-initiated setup and retries with the refreshed proof.
101    pub async fn issue_token(claims: DelegatedTokenClaims) -> Result<DelegatedToken, Error> {
102        let proof = Self::ensure_signing_proof(&claims).await?;
103        Self::sign_token(claims, proof).await
104    }
105
106    /// Full delegated token verification (structure + signature).
107    ///
108    /// Purely local verification; does not read certified data or require a
109    /// query context.
110    pub fn verify_token(
111        token: &DelegatedToken,
112        authority_pid: Principal,
113        now_secs: u64,
114    ) -> Result<(), Error> {
115        DelegatedTokenOps::verify_token(token, authority_pid, now_secs, IcOps::canister_self())
116            .map(|_| ())
117            .map_err(Self::map_delegation_error)
118    }
119
120    /// Verify a delegated token and return verified contents.
121    ///
122    /// This is intended for application-layer session construction.
123    /// It performs full verification and returns verified claims and cert.
124    pub fn verify_token_verified(
125        token: &DelegatedToken,
126        authority_pid: Principal,
127        now_secs: u64,
128    ) -> Result<(DelegatedTokenClaims, DelegationCert), Error> {
129        DelegatedTokenOps::verify_token(token, authority_pid, now_secs, IcOps::canister_self())
130            .map(crate::ops::auth::VerifiedDelegatedToken::into_parts)
131            .map_err(Self::map_delegation_error)
132    }
133
134    /// Canonical shard-initiated delegation request (user_shard -> root).
135    ///
136    /// Caller must match shard_pid and be registered to the subnet.
137    pub async fn request_delegation(
138        request: DelegationRequest,
139    ) -> Result<DelegationProvisionResponse, Error> {
140        let request = metadata::with_root_request_metadata(request);
141        if EnvOps::is_root() {
142            let response = RootResponseWorkflow::response(RootRequest::issue_delegation(request))
143                .await
144                .map_err(Self::map_delegation_error)?;
145
146            return match response {
147                RootCapabilityResponse::DelegationIssued(response) => Ok(response),
148                _ => Err(Error::internal(
149                    "invalid root response type for delegation request",
150                )),
151            };
152        }
153
154        let root_pid = EnvOps::root_pid().map_err(Error::from)?;
155        RpcOps::call_rpc_result(root_pid, protocol::CANIC_REQUEST_DELEGATION, request)
156            .await
157            .map_err(Self::map_delegation_error)
158    }
159
160    pub async fn request_role_attestation(
161        request: RoleAttestationRequest,
162    ) -> Result<SignedRoleAttestation, Error> {
163        let request = metadata::with_root_attestation_request_metadata(request);
164        let response = RootResponseWorkflow::response(RootRequest::issue_role_attestation(request))
165            .await
166            .map_err(Self::map_delegation_error)?;
167
168        match response {
169            RootCapabilityResponse::RoleAttestationIssued(response) => Ok(response),
170            _ => Err(Error::internal(
171                "invalid root response type for role attestation request",
172            )),
173        }
174    }
175
176    pub async fn attestation_key_set() -> Result<AttestationKeySet, Error> {
177        DelegatedTokenOps::attestation_key_set()
178            .await
179            .map_err(Self::map_delegation_error)
180    }
181
182    pub fn replace_attestation_key_set(key_set: AttestationKeySet) {
183        DelegatedTokenOps::replace_attestation_key_set(key_set);
184    }
185
186    pub async fn verify_role_attestation(
187        attestation: &SignedRoleAttestation,
188        min_accepted_epoch: u64,
189    ) -> Result<(), Error> {
190        let configured_min_accepted_epoch = ConfigOps::role_attestation_config()
191            .map_err(Error::from)?
192            .min_accepted_epoch_by_role
193            .get(attestation.payload.role.as_str())
194            .copied();
195        let min_accepted_epoch = verify_flow::resolve_min_accepted_epoch(
196            min_accepted_epoch,
197            configured_min_accepted_epoch,
198        );
199
200        let caller = IcOps::msg_caller();
201        let self_pid = IcOps::canister_self();
202        let now_secs = IcOps::now_secs();
203        let verifier_subnet = Some(EnvOps::subnet_pid().map_err(Error::from)?);
204        let root_pid = EnvOps::root_pid().map_err(Error::from)?;
205
206        let verify = || {
207            DelegatedTokenOps::verify_role_attestation_cached(
208                attestation,
209                caller,
210                self_pid,
211                verifier_subnet,
212                now_secs,
213                min_accepted_epoch,
214            )
215            .map(|_| ())
216        };
217        let refresh = || async {
218            let key_set: AttestationKeySet =
219                RpcOps::call_rpc_result(root_pid, protocol::CANIC_ATTESTATION_KEY_SET, ()).await?;
220            DelegatedTokenOps::replace_attestation_key_set(key_set);
221            Ok(())
222        };
223
224        match verify_flow::verify_role_attestation_with_single_refresh(verify, refresh).await {
225            Ok(()) => Ok(()),
226            Err(verify_flow::RoleAttestationVerifyFlowError::Initial(err)) => {
227                verify_flow::record_attestation_verifier_rejection(&err);
228                verify_flow::log_attestation_verifier_rejection(
229                    &err,
230                    attestation,
231                    caller,
232                    self_pid,
233                    "cached",
234                );
235                Err(Self::map_delegation_error(err.into()))
236            }
237            Err(verify_flow::RoleAttestationVerifyFlowError::Refresh { trigger, source }) => {
238                verify_flow::record_attestation_verifier_rejection(&trigger);
239                verify_flow::log_attestation_verifier_rejection(
240                    &trigger,
241                    attestation,
242                    caller,
243                    self_pid,
244                    "cache_miss_refresh",
245                );
246                record_attestation_refresh_failed();
247                log!(
248                    Topic::Auth,
249                    Warn,
250                    "role attestation refresh failed local={} caller={} key_id={} error={}",
251                    self_pid,
252                    caller,
253                    attestation.key_id,
254                    source
255                );
256                Err(Self::map_delegation_error(source))
257            }
258            Err(verify_flow::RoleAttestationVerifyFlowError::PostRefresh(err)) => {
259                verify_flow::record_attestation_verifier_rejection(&err);
260                verify_flow::log_attestation_verifier_rejection(
261                    &err,
262                    attestation,
263                    caller,
264                    self_pid,
265                    "post_refresh",
266                );
267                Err(Self::map_delegation_error(err.into()))
268            }
269        }
270    }
271
272    fn require_proof() -> Result<DelegationProof, Error> {
273        let cfg = ConfigOps::delegated_tokens_config().map_err(Error::from)?;
274        if !cfg.enabled {
275            return Err(Error::forbidden(Self::DELEGATED_TOKENS_DISABLED));
276        }
277
278        DelegationStateOps::latest_proof_dto().ok_or_else(|| {
279            record_signer_issue_without_proof();
280            Error::not_found("delegation proof not installed")
281        })
282    }
283
284    // Resolve a proof that is currently usable for token issuance.
285    async fn ensure_signing_proof(claims: &DelegatedTokenClaims) -> Result<DelegationProof, Error> {
286        let now_secs = IcOps::now_secs();
287
288        match Self::require_proof() {
289            Ok(proof)
290                if !DelegatedTokenOps::proof_reusable_for_claims(&proof, claims, now_secs) =>
291            {
292                Self::setup_delegation(claims).await
293            }
294            Ok(proof) => Ok(proof),
295            Err(err) if err.code == ErrorCode::NotFound => Self::setup_delegation(claims).await,
296            Err(err) => Err(err),
297        }
298    }
299
300    // Provision a fresh delegation from root, then resolve the latest locally stored proof.
301    async fn setup_delegation(claims: &DelegatedTokenClaims) -> Result<DelegationProof, Error> {
302        let request = Self::delegation_request_from_claims(claims)?;
303        let required_verifier_targets = request.verifier_targets.clone();
304        let response = Self::request_delegation(request).await?;
305        Self::ensure_required_verifier_targets_provisioned(&required_verifier_targets, &response)?;
306        Self::require_proof()
307    }
308
309    // Build a canonical delegation request from token claims.
310    fn delegation_request_from_claims(
311        claims: &DelegatedTokenClaims,
312    ) -> Result<DelegationRequest, Error> {
313        let ttl_secs = claims.exp.saturating_sub(claims.iat);
314        if ttl_secs == 0 {
315            return Err(Error::invalid(
316                "delegation ttl_secs must be greater than zero",
317            ));
318        }
319
320        let signer_pid = IcOps::canister_self();
321        let root_pid = EnvOps::root_pid().map_err(Error::from)?;
322        let verifier_targets = DelegatedTokenOps::required_verifier_targets_from_audience(
323            &claims.aud,
324            signer_pid,
325            root_pid,
326            Self::is_registered_canister,
327        )
328        .map_err(|principal| {
329            Error::invalid(format!(
330                "delegation audience principal '{principal}' is invalid for canonical verifier provisioning"
331            ))
332        })?;
333
334        Ok(DelegationRequest {
335            shard_pid: signer_pid,
336            scopes: claims.scopes.clone(),
337            aud: claims.aud.clone(),
338            ttl_secs,
339            verifier_targets,
340            include_root_verifier: true,
341            metadata: None,
342        })
343    }
344
345    // Validate required verifier fanout and fail closed when any required target is missing/failing.
346    fn ensure_required_verifier_targets_provisioned(
347        required_targets: &[Principal],
348        response: &DelegationProvisionResponse,
349    ) -> Result<(), Error> {
350        let mut checked = Vec::new();
351        for target in required_targets {
352            if checked.contains(target) {
353                continue;
354            }
355            checked.push(*target);
356        }
357        record_delegation_verifier_target_count(checked.len());
358
359        for target in &checked {
360            let Some(result) = response.results.iter().find(|entry| {
361                entry.kind == DelegationProvisionTargetKind::Verifier && entry.target == *target
362            }) else {
363                record_delegation_verifier_target_missing();
364                return Err(Error::internal(format!(
365                    "delegation provisioning missing verifier target result for '{target}'"
366                )));
367            };
368
369            if result.status != DelegationProvisionStatus::Ok {
370                record_delegation_verifier_target_failed();
371                let detail = result
372                    .error
373                    .as_ref()
374                    .map_or_else(|| "unknown error".to_string(), ToString::to_string);
375                return Err(Error::internal(format!(
376                    "delegation provisioning failed for required verifier target '{target}': {detail}"
377                )));
378            }
379        }
380
381        record_delegation_provision_complete();
382        Ok(())
383    }
384
385    // Derive required verifier targets from audience with strict filtering/validation.
386    #[cfg(test)]
387    fn derive_required_verifier_targets_from_aud<F>(
388        audience: &[Principal],
389        signer_pid: Principal,
390        root_pid: Principal,
391        is_valid_target: F,
392    ) -> Result<Vec<Principal>, Error>
393    where
394        F: FnMut(Principal) -> bool,
395    {
396        DelegatedTokenOps::required_verifier_targets_from_audience(
397            audience,
398            signer_pid,
399            root_pid,
400            is_valid_target,
401        )
402        .map_err(|principal| {
403            Error::invalid(format!(
404                "delegation audience principal '{principal}' is invalid for canonical verifier provisioning"
405            ))
406        })
407    }
408
409    // Delegated audience invariants:
410    // 1. claims.aud must be non-empty.
411    // 2. claims.aud must be a set-subset of proof.cert.aud.
412    // 3. proof installation on target T requires T ∈ proof.cert.aud.
413    // 4. token acceptance on canister C requires C ∈ claims.aud.
414    //
415    // Keep ingress, fanout, install, and runtime checks aligned to this block.
416}
417
418#[cfg(test)]
419mod tests;