Skip to main content

ic_dbms_api/
acl.rs

1//! Access control types shared by the canister and the clients.
2//!
3//! The canister stores one [`AclGrant`] per row of its reserved
4//! `ic_dbms_acl` table: a principal, an [`AclPermission`] and an optional
5//! table name, where no table means every table.
6
7use std::borrow::Cow;
8use std::fmt;
9
10use candid::CandidType;
11use serde::{Deserialize, Serialize};
12use thiserror::Error;
13use wasm_dbms_api::prelude::{
14    DataSize, DataType, DecodeError, Encode, MSize, MemoryError, MemoryResult, PageOffset,
15};
16use wasm_dbms_macros::CustomDataType;
17
18/// An operation a grant allows.
19///
20/// Stored in the reserved `ic_dbms_acl` table as a one-byte custom data
21/// type and exposed through Candid as a variant.
22#[derive(
23    Clone,
24    Copy,
25    Debug,
26    Default,
27    PartialEq,
28    Eq,
29    PartialOrd,
30    Ord,
31    Hash,
32    CustomDataType,
33    CandidType,
34    Serialize,
35    Deserialize,
36)]
37#[type_tag = "acl_permission"]
38pub enum AclPermission {
39    /// Everything: every operation on every table, transactions, ACL
40    /// management and schema migrations. Always granted on every table.
41    Admin,
42    /// Select and aggregate on the granted table. The default, because it
43    /// is the narrowest permission.
44    #[default]
45    Read,
46    /// Insert into the granted table.
47    Insert,
48    /// Update rows of the granted table.
49    Update,
50    /// Delete rows of the granted table.
51    Delete,
52}
53
54impl AclPermission {
55    const ALL: [Self; 5] = [
56        Self::Admin,
57        Self::Read,
58        Self::Insert,
59        Self::Update,
60        Self::Delete,
61    ];
62
63    /// The byte stored in stable memory. Never reorder: persisted rows
64    /// depend on it.
65    fn tag(self) -> u8 {
66        match self {
67            Self::Admin => 0,
68            Self::Read => 1,
69            Self::Insert => 2,
70            Self::Update => 3,
71            Self::Delete => 4,
72        }
73    }
74}
75
76impl fmt::Display for AclPermission {
77    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
78        let name = match self {
79            Self::Admin => "Admin",
80            Self::Read => "Read",
81            Self::Insert => "Insert",
82            Self::Update => "Update",
83            Self::Delete => "Delete",
84        };
85        f.write_str(name)
86    }
87}
88
89/// The access required by a protected operation.
90#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, CandidType, Serialize, Deserialize)]
91pub enum AclRequirement {
92    /// One specific permission, optionally on a table.
93    Permission(AclPermission),
94    /// At least one grant of any kind.
95    AnyGrant,
96}
97
98impl From<AclPermission> for AclRequirement {
99    fn from(permission: AclPermission) -> Self {
100        Self::Permission(permission)
101    }
102}
103
104impl fmt::Display for AclRequirement {
105    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
106        match self {
107            Self::Permission(permission) => write!(f, "the {permission} permission"),
108            Self::AnyGrant => f.write_str("any grant"),
109        }
110    }
111}
112
113impl Encode for AclPermission {
114    const SIZE: DataSize = DataSize::Fixed(1);
115
116    const ALIGNMENT: PageOffset = 1;
117
118    fn encode(&'_ self) -> Cow<'_, [u8]> {
119        Cow::Owned(vec![self.tag()])
120    }
121
122    fn decode(data: Cow<[u8]>) -> MemoryResult<Self>
123    where
124        Self: Sized,
125    {
126        let byte = *data
127            .first()
128            .ok_or(MemoryError::DecodeError(DecodeError::TooShort))?;
129        Self::ALL
130            .into_iter()
131            .find(|permission| permission.tag() == byte)
132            .ok_or(MemoryError::DecodeError(DecodeError::InvalidDiscriminant(
133                byte,
134            )))
135    }
136
137    fn size(&self) -> MSize {
138        1
139    }
140}
141
142impl DataType for AclPermission {}
143
144/// One grant: `principal` may perform `permission` on `table`, or on every
145/// table when `table` is `None`.
146///
147/// [`AclPermission::Admin`] grants always have `table: None`.
148#[derive(Clone, Debug, PartialEq, Eq, Hash, CandidType, Serialize, Deserialize)]
149pub struct AclGrant {
150    /// The principal that receives the grant.
151    pub principal: candid::Principal,
152    /// The operation allowed.
153    pub permission: AclPermission,
154    /// The table the grant applies to; `None` means every table, including
155    /// tables added later.
156    pub table: Option<String>,
157}
158
159impl AclGrant {
160    /// Full access for `principal`.
161    pub fn admin(principal: candid::Principal) -> Self {
162        Self {
163            principal,
164            permission: AclPermission::Admin,
165            table: None,
166        }
167    }
168
169    /// `permission` on the table called `table`.
170    pub fn table(
171        principal: candid::Principal,
172        permission: AclPermission,
173        table: impl Into<String>,
174    ) -> Self {
175        Self {
176            principal,
177            permission,
178            table: Some(table.into()),
179        }
180    }
181
182    /// `permission` on every table, including tables added later.
183    pub fn all_tables(principal: candid::Principal, permission: AclPermission) -> Self {
184        Self {
185            principal,
186            permission,
187            table: None,
188        }
189    }
190}
191
192/// Errors raised by the canister access control list.
193#[derive(Clone, Debug, PartialEq, Eq, Error, CandidType, Serialize, Deserialize)]
194pub enum AclError {
195    /// The caller does not satisfy the operation's access requirement.
196    ///
197    /// `table` names the table where access was required, or is `None` for
198    /// operations that are not tied to a table (transactions, ACL management
199    /// and migrations).
200    #[error("access denied: the caller lacks {required}{}", on_table(.table))]
201    AccessDenied {
202        /// The access the operation requires.
203        required: AclRequirement,
204        /// The table the access is required on.
205        table: Option<String>,
206    },
207    /// Permissions cannot be granted to the anonymous principal.
208    #[error("the anonymous principal cannot hold permissions")]
209    AnonymousPrincipal,
210    /// The operation would leave the canister without any admin.
211    #[error("at least one principal must retain the Admin permission")]
212    LastAdmin,
213    /// An `Admin` grant named a table; `Admin` always covers every table.
214    #[error("the Admin permission applies to every table and cannot name one")]
215    AdminGrantWithTable,
216    /// The grant named a table that is not one of the canister's tables.
217    #[error("table `{0}` does not exist or cannot be granted")]
218    InvalidTable(String),
219}
220
221fn on_table(table: &Option<String>) -> String {
222    table
223        .as_ref()
224        .map(|table| format!(" on table `{table}`"))
225        .unwrap_or_default()
226}
227
228#[cfg(test)]
229mod tests {
230
231    use std::borrow::Cow;
232
233    use wasm_dbms_api::prelude::{CustomDataType as _, DecodeError, MemoryError, Value};
234
235    use super::*;
236
237    const ALL_PERMISSIONS: [AclPermission; 5] = [
238        AclPermission::Admin,
239        AclPermission::Read,
240        AclPermission::Insert,
241        AclPermission::Update,
242        AclPermission::Delete,
243    ];
244
245    fn principal() -> candid::Principal {
246        candid::Principal::from_text("ryjl3-tyaaa-aaaaa-aaaba-cai").unwrap()
247    }
248
249    #[test]
250    fn test_acl_permission_encode_decode_roundtrip() {
251        for permission in ALL_PERMISSIONS {
252            let encoded = permission.encode();
253            assert_eq!(encoded.len(), 1);
254            assert_eq!(permission.size(), 1);
255            assert_eq!(AclPermission::decode(encoded).unwrap(), permission);
256        }
257    }
258
259    #[test]
260    fn test_acl_permission_decode_rejects_bad_bytes() {
261        assert!(matches!(
262            AclPermission::decode(Cow::Borrowed(&[])),
263            Err(MemoryError::DecodeError(DecodeError::TooShort))
264        ));
265        assert!(matches!(
266            AclPermission::decode(Cow::Borrowed(&[9])),
267            Err(MemoryError::DecodeError(DecodeError::InvalidDiscriminant(
268                9
269            )))
270        ));
271    }
272
273    #[test]
274    fn test_acl_permission_display() {
275        let names: Vec<String> = ALL_PERMISSIONS.iter().map(ToString::to_string).collect();
276        assert_eq!(names, ["Admin", "Read", "Insert", "Update", "Delete"]);
277    }
278
279    #[test]
280    fn test_acl_permission_candid_roundtrip() {
281        for permission in ALL_PERMISSIONS {
282            let bytes = candid::encode_one(permission).expect("encode");
283            let decoded: AclPermission = candid::decode_one(&bytes).expect("decode");
284            assert_eq!(decoded, permission);
285        }
286    }
287
288    #[test]
289    fn test_acl_permission_converts_to_tagged_custom_value() {
290        assert_eq!(AclPermission::TYPE_TAG, "acl_permission");
291        let value: Value = AclPermission::Insert.into();
292        assert!(matches!(
293            value,
294            Value::Custom(ref custom)
295                if custom.type_tag == "acl_permission" && custom.display == "Insert"
296        ));
297    }
298
299    #[test]
300    fn test_acl_grant_constructors() {
301        assert_eq!(
302            AclGrant::admin(principal()),
303            AclGrant {
304                principal: principal(),
305                permission: AclPermission::Admin,
306                table: None,
307            }
308        );
309        assert_eq!(
310            AclGrant::table(principal(), AclPermission::Read, "users"),
311            AclGrant {
312                principal: principal(),
313                permission: AclPermission::Read,
314                table: Some("users".to_string()),
315            }
316        );
317        assert_eq!(
318            AclGrant::all_tables(principal(), AclPermission::Delete),
319            AclGrant {
320                principal: principal(),
321                permission: AclPermission::Delete,
322                table: None,
323            }
324        );
325    }
326
327    #[test]
328    fn test_acl_grant_candid_roundtrip() {
329        for grant in [
330            AclGrant::admin(principal()),
331            AclGrant::table(principal(), AclPermission::Update, "posts"),
332        ] {
333            let bytes = candid::encode_one(&grant).expect("encode");
334            let decoded: AclGrant = candid::decode_one(&bytes).expect("decode");
335            assert_eq!(decoded, grant);
336        }
337    }
338
339    #[test]
340    fn test_acl_error_candid_roundtrip() {
341        for error in [
342            AclError::AccessDenied {
343                required: AclPermission::Admin.into(),
344                table: None,
345            },
346            AclError::AccessDenied {
347                required: AclPermission::Read.into(),
348                table: Some("users".to_string()),
349            },
350            AclError::AccessDenied {
351                required: AclRequirement::AnyGrant,
352                table: None,
353            },
354            AclError::AnonymousPrincipal,
355            AclError::LastAdmin,
356            AclError::AdminGrantWithTable,
357            AclError::InvalidTable("nope".to_string()),
358        ] {
359            let bytes = candid::encode_one(&error).expect("encode");
360            let decoded: AclError = candid::decode_one(&bytes).expect("decode");
361            assert_eq!(decoded, error);
362        }
363    }
364
365    #[test]
366    fn test_acl_error_display() {
367        assert_eq!(
368            AclError::AccessDenied {
369                required: AclPermission::Admin.into(),
370                table: None,
371            }
372            .to_string(),
373            "access denied: the caller lacks the Admin permission"
374        );
375        assert_eq!(
376            AclError::AccessDenied {
377                required: AclPermission::Delete.into(),
378                table: Some("posts".to_string()),
379            }
380            .to_string(),
381            "access denied: the caller lacks the Delete permission on table `posts`"
382        );
383        assert_eq!(
384            AclError::AnonymousPrincipal.to_string(),
385            "the anonymous principal cannot hold permissions"
386        );
387        assert_eq!(
388            AclError::LastAdmin.to_string(),
389            "at least one principal must retain the Admin permission"
390        );
391        assert_eq!(
392            AclError::AdminGrantWithTable.to_string(),
393            "the Admin permission applies to every table and cannot name one"
394        );
395        assert_eq!(
396            AclError::InvalidTable("nope".to_string()).to_string(),
397            "table `nope` does not exist or cannot be granted"
398        );
399        assert_eq!(
400            AclError::AccessDenied {
401                required: AclRequirement::AnyGrant,
402                table: None,
403            }
404            .to_string(),
405            "access denied: the caller lacks any grant"
406        );
407    }
408}