Skip to main content

canic_core/api/auth/
mod.rs

1//! Module: api::auth
2//!
3//! Responsibility: expose auth endpoint helpers and auth boundary adapters.
4//! Does not own: stable auth records, proof verification internals, or runtime policy.
5//! Boundary: endpoint layer maps public DTOs into ops/workflow auth calls.
6
7use crate::{
8    cdk::types::Principal,
9    dto::{
10        auth::{
11            ActiveDelegationProofStatusResponse, DelegatedToken, DelegatedTokenGetRequest,
12            DelegatedTokenPrepareRequest, DelegatedTokenPrepareResponse,
13            InstallActiveDelegationProofRequest, InstallActiveDelegationProofResponse,
14            RoleAttestationGetRequest, RoleAttestationPrepareResponse, RoleAttestationRequest,
15            RootDelegationProofBatchGetRequest, RootDelegationProofBatchGetResponse,
16            RootDelegationProofBatchInstallRequest, RootDelegationProofBatchInstallResponse,
17            RootDelegationProofBatchPrepareRequest, RootDelegationProofBatchPrepareResponse,
18            RootIssuerPolicyResponse, RootIssuerPolicyUpsertRequest, SignedRoleAttestation,
19        },
20        error::Error,
21    },
22    error::InternalErrorClass,
23    ops::{
24        auth::{AuthOps, VerifyDelegatedTokenRuntimeInput},
25        config::ConfigOps,
26        ic::IcOps,
27        runtime::env::EnvOps,
28    },
29    workflow::runtime::auth::RuntimeAuthWorkflow,
30};
31
32// Internal auth pipeline:
33// - `session` owns delegated-session ingress and replay/session state handling.
34mod session;
35
36///
37/// AuthApi
38///
39/// Owns delegated-token helpers and root-signed role-attestation helpers.
40/// Owned by the API layer and called by generated endpoint wrappers.
41///
42
43pub struct AuthApi;
44
45impl AuthApi {
46    const DELEGATED_TOKENS_DISABLED: &str =
47        "delegated token auth disabled; set auth.delegated_tokens.enabled=true in canic.toml";
48    const DELEGATED_TOKEN_ISSUER_DISABLED: &str = "delegated token issuer disabled for this canister; set subnets.<subnet>.canisters.<role>.auth.delegated_token_issuer=true in canic.toml";
49    const MAX_DELEGATED_SESSION_TTL_SECS: u64 = 24 * 60 * 60;
50    const SESSION_BOOTSTRAP_TOKEN_FINGERPRINT_DOMAIN: &[u8] =
51        b"canic-session-bootstrap-token-fingerprint";
52
53    // Map internal auth failures onto public endpoint errors.
54    fn map_auth_error(err: crate::InternalError) -> Error {
55        match err.class() {
56            InternalErrorClass::Infra | InternalErrorClass::Ops | InternalErrorClass::Workflow => {
57                Error::internal(err.to_string())
58            }
59            _ => Error::from(err),
60        }
61    }
62
63    fn require_delegated_token_issuer_enabled() -> Result<(), Error> {
64        let delegated_tokens_cfg =
65            ConfigOps::delegated_tokens_config().map_err(Self::map_auth_error)?;
66        if !delegated_tokens_cfg.enabled {
67            return Err(Error::invalid(Self::DELEGATED_TOKENS_DISABLED));
68        }
69
70        let canister_cfg = ConfigOps::current_canister().map_err(Self::map_auth_error)?;
71        if !canister_cfg.auth.delegated_token_issuer {
72            return Err(Error::forbidden(Self::DELEGATED_TOKEN_ISSUER_DISABLED));
73        }
74
75        Ok(())
76    }
77
78    // Verify delegated-token material and return the token subject.
79    //
80    // This is intentionally private: endpoint authorization must also bind the
81    // verified subject to the caller before dispatch.
82    fn verify_token_material(
83        token: &DelegatedToken,
84        max_cert_ttl_ns: u64,
85        max_token_ttl_ns: u64,
86        required_scopes: &[String],
87        now_ns: u64,
88    ) -> Result<Principal, Error> {
89        AuthOps::verify_token(VerifyDelegatedTokenRuntimeInput {
90            token,
91            caller: IcOps::msg_caller(),
92            max_cert_ttl_ns,
93            max_token_ttl_ns,
94            required_scopes,
95            now_ns,
96        })
97        .map(|verified| verified.subject)
98        .map_err(Self::map_auth_error)
99    }
100
101    /// Prepare a delegated token from the issuer-local active delegation proof.
102    pub fn prepare_delegated_token(
103        request: DelegatedTokenPrepareRequest,
104    ) -> Result<DelegatedTokenPrepareResponse, Error> {
105        Self::require_delegated_token_issuer_enabled()?;
106        RuntimeAuthWorkflow::prepare_delegated_token(request).map_err(Self::map_auth_error)
107    }
108
109    /// Retrieve a prepared delegated token with its issuer canister-signature proof.
110    pub fn get_delegated_token(request: DelegatedTokenGetRequest) -> Result<DelegatedToken, Error> {
111        Self::require_delegated_token_issuer_enabled()?;
112
113        AuthOps::get_delegated_token_issuer_proof(request.claims_hash, IcOps::msg_caller())
114            .map_err(Self::map_auth_error)
115    }
116
117    /// Install validated root-certified delegation material for issuer-local token issuance.
118    pub fn install_active_delegation_proof(
119        request: InstallActiveDelegationProofRequest,
120    ) -> Result<InstallActiveDelegationProofResponse, Error> {
121        Self::require_delegated_token_issuer_enabled()?;
122
123        let active_proof =
124            AuthOps::install_active_delegation_proof(request.proof, IcOps::msg_caller())
125                .map_err(Self::map_auth_error)?;
126
127        Ok(InstallActiveDelegationProofResponse { active_proof })
128    }
129
130    /// Report non-secret issuer-local active proof lifecycle status for provisioners.
131    pub fn active_delegation_proof_status() -> Result<ActiveDelegationProofStatusResponse, Error> {
132        Self::require_delegated_token_issuer_enabled()?;
133        Ok(AuthOps::active_delegation_proof_status(IcOps::now_nanos()))
134    }
135
136    /// Upsert root issuer policy from the local root controller path.
137    pub fn upsert_root_issuer_policy_root(
138        request: RootIssuerPolicyUpsertRequest,
139    ) -> Result<RootIssuerPolicyResponse, Error> {
140        EnvOps::require_root().map_err(Error::from)?;
141        AuthOps::upsert_root_issuer_policy(request).map_err(Self::map_auth_error)
142    }
143
144    /// Prepare root delegation proof batch metadata from the local root update path.
145    pub fn prepare_delegation_proof_batch_root(
146        request: RootDelegationProofBatchPrepareRequest,
147    ) -> Result<RootDelegationProofBatchPrepareResponse, Error> {
148        EnvOps::require_root().map_err(Error::from)?;
149        let max_cert_ttl_ns = Self::delegated_token_max_ttl_ns()?;
150        AuthOps::prepare_delegation_proof_batch(request, max_cert_ttl_ns, IcOps::now_nanos())
151            .map_err(Self::map_auth_error)
152    }
153
154    /// Retrieve root delegation proofs from the local direct root query path.
155    pub fn get_delegation_proof_batch_root(
156        request: RootDelegationProofBatchGetRequest,
157    ) -> Result<RootDelegationProofBatchGetResponse, Error> {
158        EnvOps::require_root().map_err(Error::from)?;
159        AuthOps::get_delegation_proof_batch(request).map_err(Self::map_auth_error)
160    }
161
162    /// Install retrieved root delegation proof batches from the local root update path.
163    pub async fn install_delegation_proof_batch_root(
164        request: RootDelegationProofBatchInstallRequest,
165    ) -> Result<RootDelegationProofBatchInstallResponse, Error> {
166        EnvOps::require_root().map_err(Error::from)?;
167        RuntimeAuthWorkflow::install_delegation_proof_batch_root(request)
168            .await
169            .map_err(Self::map_auth_error)
170    }
171
172    /// Prepare a root-certified role attestation from the local root update path.
173    pub fn prepare_role_attestation_root(
174        request: RoleAttestationRequest,
175    ) -> Result<RoleAttestationPrepareResponse, Error> {
176        RuntimeAuthWorkflow::prepare_role_attestation_root(request).map_err(Self::map_auth_error)
177    }
178
179    /// Retrieve a prepared role attestation with its root canister-signature proof.
180    pub fn get_role_attestation_root(
181        request: RoleAttestationGetRequest,
182    ) -> Result<SignedRoleAttestation, Error> {
183        EnvOps::require_root().map_err(Error::from)?;
184        AuthOps::get_role_attestation(IcOps::msg_caller(), request.payload_hash)
185            .map_err(Self::map_auth_error)
186    }
187
188    /// Verify a role attestation locally from its embedded root proof.
189    pub async fn verify_role_attestation(
190        attestation: &SignedRoleAttestation,
191        min_accepted_epoch: u64,
192    ) -> Result<(), Error> {
193        crate::workflow::runtime::auth::RuntimeAuthWorkflow::verify_role_attestation(
194            attestation,
195            min_accepted_epoch,
196        )
197        .await
198        .map_err(Self::map_auth_error)
199    }
200
201    // Resolve the delegated-token TTL ceiling for endpoint auth/session callers.
202    fn delegated_token_max_ttl_ns() -> Result<u64, Error> {
203        let cfg = ConfigOps::delegated_tokens_config().map_err(Error::from)?;
204        if !cfg.enabled {
205            return Err(Error::forbidden(Self::DELEGATED_TOKENS_DISABLED));
206        }
207
208        let max_ttl_secs = cfg
209            .max_ttl_secs
210            .unwrap_or(Self::MAX_DELEGATED_SESSION_TTL_SECS);
211        max_ttl_secs.checked_mul(1_000_000_000).ok_or_else(|| {
212            Error::invalid("auth.delegated_tokens.max_ttl_secs overflows nanoseconds")
213        })
214    }
215}