safe_nd/sequence/
metadata.rs

1// Copyright 2020 MaidSafe.net limited.
2//
3// This SAFE Network Software is licensed to you under the MIT license <LICENSE-MIT
4// https://opensource.org/licenses/MIT> or the Modified BSD license <LICENSE-BSD
5// https://opensource.org/licenses/BSD-3-Clause>, at your option. This file may not be copied,
6// modified, or distributed except according to those terms. Please review the Licences for the
7// specific language governing permissions and limitations relating to use of the SAFE Network
8// Software.
9
10use crate::{utils, Error, PublicKey, Result, XorName};
11use serde::{Deserialize, Serialize};
12use std::{collections::BTreeMap, fmt::Debug, hash::Hash};
13
14/// An action on Sequence data type.
15#[derive(Clone, Copy, Eq, PartialEq)]
16pub enum Action {
17    /// Read from the data.
18    Read,
19    /// Append to the data.
20    Append,
21    /// Manage permissions.
22    Admin,
23}
24
25/// List of entries.
26pub type Entries = Vec<Entry>;
27
28/// An entry in a Sequence.
29pub type Entry = Vec<u8>;
30
31/// Address of a Sequence.
32#[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize, Debug)]
33pub enum Address {
34    /// Public sequence namespace.
35    Public {
36        /// Name.
37        name: XorName,
38        /// Tag.
39        tag: u64,
40    },
41    /// Private sequence namespace.
42    Private {
43        /// Name.
44        name: XorName,
45        /// Tag.
46        tag: u64,
47    },
48}
49
50impl Address {
51    /// Constructs a new `Address` given `kind`, `name`, and `tag`.
52    pub fn from_kind(kind: Kind, name: XorName, tag: u64) -> Self {
53        match kind {
54            Kind::Public => Address::Public { name, tag },
55            Kind::Private => Address::Private { name, tag },
56        }
57    }
58
59    /// Returns the kind.
60    pub fn kind(&self) -> Kind {
61        match self {
62            Address::Public { .. } => Kind::Public,
63            Address::Private { .. } => Kind::Private,
64        }
65    }
66
67    /// Returns the name.
68    pub fn name(&self) -> &XorName {
69        match self {
70            Address::Public { ref name, .. } | Address::Private { ref name, .. } => name,
71        }
72    }
73
74    /// Returns the tag.
75    pub fn tag(&self) -> u64 {
76        match self {
77            Address::Public { tag, .. } | Address::Private { tag, .. } => *tag,
78        }
79    }
80
81    /// Returns true if public.
82    pub fn is_pub(&self) -> bool {
83        self.kind().is_pub()
84    }
85
86    /// Returns true if private.
87    pub fn is_private(&self) -> bool {
88        self.kind().is_private()
89    }
90
91    /// Returns the `Address` serialised and encoded in z-base-32.
92    pub fn encode_to_zbase32(&self) -> String {
93        utils::encode(&self)
94    }
95
96    /// Creates from z-base-32 encoded string.
97    pub fn decode_from_zbase32<I: AsRef<str>>(encoded: I) -> Result<Self> {
98        utils::decode(encoded)
99    }
100}
101
102/// Kind of a Sequence.
103#[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize, Debug)]
104pub enum Kind {
105    /// Public sequence.
106    Public,
107    /// Private sequence.
108    Private,
109}
110
111impl Kind {
112    /// Returns true if public.
113    pub fn is_pub(self) -> bool {
114        self == Kind::Public
115    }
116
117    /// Returns true if private.
118    pub fn is_private(self) -> bool {
119        !self.is_pub()
120    }
121}
122
123/// Index of some data.
124#[derive(Copy, Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
125pub enum Index {
126    /// Absolute index.
127    FromStart(u64),
128    /// Relative index - start counting from the end.
129    FromEnd(u64),
130}
131
132impl From<u64> for Index {
133    fn from(index: u64) -> Self {
134        Index::FromStart(index)
135    }
136}
137
138/// Set of public permissions for a user.
139#[derive(Copy, Clone, Serialize, Deserialize, PartialEq, PartialOrd, Ord, Eq, Hash, Debug)]
140pub struct PublicPermissions {
141    /// `Some(true)` if the user can append.
142    /// `Some(false)` explicitly denies this permission (even if `Anyone` has permissions).
143    /// Use permissions for `Anyone` if `None`.
144    append: Option<bool>,
145    /// `Some(true)` if the user can manage permissions.
146    /// `Some(false)` explicitly denies this permission (even if `Anyone` has permissions).
147    /// Use permissions for `Anyone` if `None`.
148    admin: Option<bool>,
149}
150
151impl PublicPermissions {
152    /// Constructs a new public permission set.
153    pub fn new(append: impl Into<Option<bool>>, manage_perms: impl Into<Option<bool>>) -> Self {
154        Self {
155            append: append.into(),
156            admin: manage_perms.into(),
157        }
158    }
159
160    /// Sets permissions.
161    pub fn set_perms(&mut self, append: impl Into<Option<bool>>, admin: impl Into<Option<bool>>) {
162        self.append = append.into();
163        self.admin = admin.into();
164    }
165
166    /// Returns `Some(true)` if `action` is allowed and `Some(false)` if it's not permitted.
167    /// `None` means that default permissions should be applied.
168    pub fn is_allowed(self, action: Action) -> Option<bool> {
169        match action {
170            Action::Read => Some(true), // It's public data, so it's always allowed to read it.
171            Action::Append => self.append,
172            Action::Admin => self.admin,
173        }
174    }
175}
176
177/// Set of private permissions for a user.
178#[derive(Copy, Clone, Serialize, Deserialize, PartialEq, PartialOrd, Ord, Eq, Hash, Debug)]
179pub struct PrivatePermissions {
180    /// `true` if the user can read.
181    read: bool,
182    /// `true` if the user can append.
183    append: bool,
184    /// `true` if the user can manage permissions.
185    admin: bool,
186}
187
188impl PrivatePermissions {
189    /// Constructs a new private permission set.
190    pub fn new(read: bool, append: bool, manage_perms: bool) -> Self {
191        Self {
192            read,
193            append,
194            admin: manage_perms,
195        }
196    }
197
198    /// Sets permissions.
199    pub fn set_perms(&mut self, read: bool, append: bool, manage_perms: bool) {
200        self.read = read;
201        self.append = append;
202        self.admin = manage_perms;
203    }
204
205    /// Returns `true` if `action` is allowed.
206    pub fn is_allowed(self, action: Action) -> bool {
207        match action {
208            Action::Read => self.read,
209            Action::Append => self.append,
210            Action::Admin => self.admin,
211        }
212    }
213}
214
215/// User that can access Sequence.
216#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, Debug)]
217pub enum User {
218    /// Any user.
219    Anyone,
220    /// User identified by its public key.
221    Key(PublicKey),
222}
223
224/// Public permissions.
225#[derive(Clone, Serialize, Deserialize, PartialEq, PartialOrd, Ord, Eq, Hash, Debug)]
226pub struct PublicPolicy {
227    /// An owner could represent an individual user, or a group of users,
228    /// depending on the `public_key` type.
229    pub owner: PublicKey,
230    /// Map of users to their public permission set.
231    pub permissions: BTreeMap<User, PublicPermissions>,
232}
233
234impl PublicPolicy {
235    /// Returns `Some(true)` if `action` is allowed for the provided user and `Some(false)` if it's
236    /// not permitted. `None` means that default permissions should be applied.
237    fn is_action_allowed_by_user(&self, user: &User, action: Action) -> Option<bool> {
238        self.permissions
239            .get(user)
240            .and_then(|perms| perms.is_allowed(action))
241    }
242}
243
244/// Private permissions.
245#[derive(Clone, Serialize, Deserialize, PartialEq, PartialOrd, Ord, Eq, Hash, Debug)]
246pub struct PrivatePolicy {
247    /// An owner could represent an individual user, or a group of users,
248    /// depending on the `public_key` type.
249    pub owner: PublicKey,
250    /// Map of users to their private permission set.
251    pub permissions: BTreeMap<PublicKey, PrivatePermissions>,
252}
253
254pub trait Perm {
255    /// Returns true if `action` is allowed for the provided user.
256    fn is_action_allowed(&self, requester: PublicKey, action: Action) -> Result<()>;
257    /// Gets the permissions for a user if applicable.
258    fn permissions(&self, user: User) -> Option<Permissions>;
259    /// Returns the owner.
260    fn owner(&self) -> &PublicKey;
261}
262
263impl Perm for PublicPolicy {
264    /// Returns `Ok(())` if `action` is allowed for the provided user and `Err(AccessDenied)` if
265    /// this action is not permitted.
266    fn is_action_allowed(&self, requester: PublicKey, action: Action) -> Result<()> {
267        // First checks if the requester is the owner.
268        if action == Action::Read || requester == self.owner {
269            Ok(())
270        } else {
271            match self
272                .is_action_allowed_by_user(&User::Key(requester), action)
273                .or_else(|| self.is_action_allowed_by_user(&User::Anyone, action))
274            {
275                Some(true) => Ok(()),
276                Some(false) => Err(Error::AccessDenied),
277                None => Err(Error::AccessDenied),
278            }
279        }
280    }
281
282    /// Gets the permissions for a user if applicable.
283    fn permissions(&self, user: User) -> Option<Permissions> {
284        self.permissions.get(&user).map(|p| Permissions::Pub(*p))
285    }
286
287    /// Returns the owner.
288    fn owner(&self) -> &PublicKey {
289        &self.owner
290    }
291}
292
293impl Perm for PrivatePolicy {
294    /// Returns `Ok(())` if `action` is allowed for the provided user and `Err(AccessDenied)` if
295    /// this action is not permitted.
296    fn is_action_allowed(&self, requester: PublicKey, action: Action) -> Result<()> {
297        // First checks if the requester is the owner.
298        if requester == self.owner {
299            Ok(())
300        } else {
301            match self.permissions.get(&requester) {
302                Some(perms) => {
303                    if perms.is_allowed(action) {
304                        Ok(())
305                    } else {
306                        Err(Error::AccessDenied)
307                    }
308                }
309                None => Err(Error::AccessDenied),
310            }
311        }
312    }
313
314    /// Gets the permissions for a user if applicable.
315    fn permissions(&self, user: User) -> Option<Permissions> {
316        match user {
317            User::Anyone => None,
318            User::Key(key) => self.permissions.get(&key).map(|p| Permissions::Priv(*p)),
319        }
320    }
321
322    /// Returns the owner.
323    fn owner(&self) -> &PublicKey {
324        &self.owner
325    }
326}
327
328/// Wrapper type for permissions, which can be public or private.
329#[derive(Clone, Serialize, Deserialize, PartialEq, PartialOrd, Ord, Eq, Hash, Debug)]
330pub enum Policy {
331    /// Public permissions.
332    Pub(PublicPolicy),
333    /// Private permissions.
334    Priv(PrivatePolicy),
335}
336
337impl From<PrivatePolicy> for Policy {
338    fn from(policy: PrivatePolicy) -> Self {
339        Policy::Priv(policy)
340    }
341}
342
343impl From<PublicPolicy> for Policy {
344    fn from(policy: PublicPolicy) -> Self {
345        Policy::Pub(policy)
346    }
347}
348
349/// Wrapper type for permissions set, which can be public or private.
350#[derive(Clone, Serialize, Deserialize, PartialEq, PartialOrd, Ord, Eq, Hash, Debug)]
351pub enum Permissions {
352    /// Public permissions set.
353    Pub(PublicPermissions),
354    /// Private permissions set.
355    Priv(PrivatePermissions),
356}
357
358impl From<PrivatePermissions> for Permissions {
359    fn from(permission_set: PrivatePermissions) -> Self {
360        Permissions::Priv(permission_set)
361    }
362}
363
364impl From<PublicPermissions> for Permissions {
365    fn from(permission_set: PublicPermissions) -> Self {
366        Permissions::Pub(permission_set)
367    }
368}