sn_data_types/sequence/
metadata.rs

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