1use 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#[derive(Debug, ThisError)]
30pub enum AuthError {
31 #[error("invalid error state - this should never happen")]
33 InvalidState,
34
35 #[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
70pub type AuthRuleFn =
72 Box<dyn Fn(Principal) -> Pin<Box<dyn Future<Output = Result<(), Error>> + Send>> + Send + Sync>;
73
74pub type AuthRuleResult = Pin<Box<dyn Future<Output = Result<(), Error>> + Send>>;
76
77pub 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
104pub 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#[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#[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#[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#[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#[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#[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#[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#[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#[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#[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#[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#[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}