canic_core/
auth.rs

1//! Authorization helpers for canister-to-canister and user calls.
2//!
3//! Compose rule futures and enforce them with [`require_all`] or
4//! [`require_any`]. For ergonomics, prefer the macros [`auth_require_all!`]
5//! and [`auth_require_any!`], which accept async closures or functions that
6//! return [`AuthRuleResult`].
7
8use crate::{
9    Error,
10    cdk::api::{canister_self, msg_caller},
11    ids::CanisterRole,
12    log,
13    log::Topic,
14    ops::model::memory::{
15        EnvOps,
16        directory::{AppDirectoryOps, SubnetDirectoryOps},
17        topology::{SubnetCanisterChildrenOps, SubnetCanisterRegistryOps},
18    },
19};
20use candid::Principal;
21use std::pin::Pin;
22use thiserror::Error as ThisError;
23
24/// Error returned by authorization rule checks.
25///
26/// Each variant captures the principal that failed a rule (where relevant),
27/// making it easy to emit actionable diagnostics in logs.
28
29#[derive(Debug, ThisError)]
30pub enum AuthError {
31    /// Guardrail for unreachable states (should not be observed in practice).
32    #[error("invalid error state - this should never happen")]
33    InvalidState,
34
35    /// No rules were provided to an authorization check.
36    #[error("one or more rules must be defined")]
37    NoRulesDefined,
38
39    #[error("caller '{0}' does not match the app directory's canister type '{1}'")]
40    NotAppDirectoryType(Principal, CanisterRole),
41
42    #[error("caller '{0}' does not match the subnet directory's canister type '{1}'")]
43    NotSubnetDirectoryType(Principal, CanisterRole),
44
45    #[error("caller '{0}' is not a child of this canister")]
46    NotChild(Principal),
47
48    #[error("caller '{0}' is not a controller of this canister")]
49    NotController(Principal),
50
51    #[error("caller '{0}' is not the parent of this canister")]
52    NotParent(Principal),
53
54    #[error("expected caller principal '{1}' got '{0}'")]
55    NotPrincipal(Principal, Principal),
56
57    #[error("caller '{0}' is not root")]
58    NotRoot(Principal),
59
60    #[error("caller '{0}' is not the current canister")]
61    NotSameCanister(Principal),
62
63    #[error("caller '{0}' is not registered on the subnet registry")]
64    NotRegisteredToSubnet(Principal),
65
66    #[error("caller '{0}' is not on the whitelist")]
67    NotWhitelisted(Principal),
68}
69
70/// Callable issuing an authorization decision for a given caller.
71pub type AuthRuleFn =
72    Box<dyn Fn(Principal) -> Pin<Box<dyn Future<Output = Result<(), Error>> + Send>> + Send + Sync>;
73
74/// Future produced by an [`AuthRuleFn`].
75pub type AuthRuleResult = Pin<Box<dyn Future<Output = Result<(), Error>> + Send>>;
76
77/// Require that all provided rules pass for the current caller.
78///
79/// Returns the first failing rule error, or [`AuthError::NoRulesDefined`] if
80/// `rules` is empty.
81pub async fn require_all(rules: Vec<AuthRuleFn>) -> Result<(), Error> {
82    let caller = msg_caller();
83
84    if rules.is_empty() {
85        return Err(AuthError::NoRulesDefined.into());
86    }
87
88    for rule in rules {
89        if let Err(err) = rule(caller).await {
90            let err_msg = err.to_string();
91            log!(
92                Topic::Auth,
93                Warn,
94                "auth failed (all) caller={caller}: {err_msg}"
95            );
96
97            return Err(err);
98        }
99    }
100
101    Ok(())
102}
103
104/// Require that any one of the provided rules passes for the current caller.
105///
106/// Returns the last failing rule error if none pass, or
107/// [`AuthError::NoRulesDefined`] if `rules` is empty.
108pub async fn require_any(rules: Vec<AuthRuleFn>) -> Result<(), Error> {
109    let caller = msg_caller();
110
111    if rules.is_empty() {
112        return Err(AuthError::NoRulesDefined.into());
113    }
114
115    let mut last_error = None;
116    for rule in rules {
117        match rule(caller).await {
118            Ok(()) => return Ok(()),
119            Err(e) => last_error = Some(e),
120        }
121    }
122
123    let err = last_error.unwrap_or_else(|| AuthError::InvalidState.into());
124    let err_msg = err.to_string();
125    log!(
126        Topic::Auth,
127        Warn,
128        "auth failed (any) caller={caller}: {err_msg}"
129    );
130
131    Err(err)
132}
133
134/// Enforce that every supplied rule future succeeds for the current caller.
135///
136/// This is a convenience wrapper around [`require_all`], allowing guard
137/// checks to stay in expression position within async endpoints.
138#[macro_export]
139macro_rules! auth_require_all {
140    ($($f:expr),* $(,)?) => {{
141        $crate::auth::require_all(vec![
142            $( Box::new(move |caller| Box::pin($f(caller))) ),*
143        ]).await
144    }};
145}
146
147/// Enforce that at least one supplied rule future succeeds for the current
148/// caller.
149///
150/// See [`auth_require_all!`] for details on accepted rule shapes.
151#[macro_export]
152macro_rules! auth_require_any {
153    ($($f:expr),* $(,)?) => {{
154        $crate::auth::require_any(vec![
155            $( Box::new(move |caller| Box::pin($f(caller))) ),*
156        ]).await
157    }};
158}
159
160// -----------------------------------------------------------------------------
161// Rule functions
162// -----------------------------------------------------------------------------
163
164/// Ensure the caller matches the subnet directory entry recorded for `ty`.
165#[must_use]
166pub fn is_app_directory_type(caller: Principal, ty: CanisterRole) -> AuthRuleResult {
167    Box::pin(async move {
168        let pids = AppDirectoryOps::try_get(&ty)?;
169
170        if pids.contains(&caller) {
171            Ok(())
172        } else {
173            Err(AuthError::NotAppDirectoryType(caller, ty.clone()))?
174        }
175    })
176}
177
178/// Ensure the caller matches the subnet directory entry recorded for `ty`.
179#[must_use]
180pub fn is_subnet_directory_type(caller: Principal, ty: CanisterRole) -> AuthRuleResult {
181    Box::pin(async move {
182        let pids = SubnetDirectoryOps::try_get(&ty)?;
183
184        if pids.contains(&caller) {
185            Ok(())
186        } else {
187            Err(AuthError::NotSubnetDirectoryType(caller, ty.clone()))?
188        }
189    })
190}
191
192/// Require that the caller is a direct child of the current canister.
193#[must_use]
194pub fn is_child(caller: Principal) -> AuthRuleResult {
195    Box::pin(async move {
196        SubnetCanisterChildrenOps::find_by_pid(&caller).ok_or(AuthError::NotChild(caller))?;
197
198        Ok(())
199    })
200}
201
202/// Require that the caller controls the current canister.
203#[must_use]
204pub fn is_controller(caller: Principal) -> AuthRuleResult {
205    Box::pin(async move {
206        if crate::cdk::api::is_controller(&caller) {
207            Ok(())
208        } else {
209            Err(AuthError::NotController(caller).into())
210        }
211    })
212}
213
214/// Require that the caller equals the configured root canister.
215#[must_use]
216pub fn is_root(caller: Principal) -> AuthRuleResult {
217    Box::pin(async move {
218        let root_pid = EnvOps::try_get_root_pid()?;
219
220        if caller == root_pid {
221            Ok(())
222        } else {
223            Err(AuthError::NotRoot(caller))?
224        }
225    })
226}
227
228/// Require that the caller is the root or a registered parent canister.
229#[must_use]
230pub fn is_parent(caller: Principal) -> AuthRuleResult {
231    Box::pin(async move {
232        let parent_pid = EnvOps::try_get_parent_pid()?;
233
234        if parent_pid == caller {
235            Ok(())
236        } else {
237            Err(AuthError::NotParent(caller))?
238        }
239    })
240}
241
242/// Require that the caller equals the provided `expected` principal.
243#[must_use]
244pub fn is_principal(caller: Principal, expected: Principal) -> AuthRuleResult {
245    Box::pin(async move {
246        if caller == expected {
247            Ok(())
248        } else {
249            Err(AuthError::NotPrincipal(caller, expected))?
250        }
251    })
252}
253
254/// Require that the caller is the currently executing canister.
255#[must_use]
256pub fn is_same_canister(caller: Principal) -> AuthRuleResult {
257    Box::pin(async move {
258        if caller == canister_self() {
259            Ok(())
260        } else {
261            Err(AuthError::NotSameCanister(caller))?
262        }
263    })
264}
265
266/// Require that the caller is registered as an canister on this
267/// subnet
268/// *** ONLY ON ROOT FOR NOW ***
269#[must_use]
270pub fn is_registered_to_subnet(caller: Principal) -> AuthRuleResult {
271    Box::pin(async move {
272        match SubnetCanisterRegistryOps::get(caller) {
273            Some(_) => Ok(()),
274            None => Err(AuthError::NotRegisteredToSubnet(caller))?,
275        }
276    })
277}
278
279/// Require that the caller appears in the active whitelist (IC deployments).
280#[must_use]
281#[allow(unused_variables)]
282pub fn is_whitelisted(caller: Principal) -> AuthRuleResult {
283    Box::pin(async move {
284        #[cfg(feature = "ic")]
285        {
286            use crate::config::Config;
287            let cfg = Config::get();
288
289            if !cfg.is_whitelisted(&caller) {
290                Err(AuthError::NotWhitelisted(caller))?;
291            }
292        }
293
294        Ok(())
295    })
296}