summaryrefslogtreecommitdiff
path: root/crates/directory/src/backend/internal/mod.rs
blob: 8bc86cc2f630a54d9aabec5c99299a139f791205 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
/*
 * Copyright (c) 2023 Stalwart Labs Ltd.
 *
 * This file is part of Stalwart Mail Server.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of
 * the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 * in the LICENSE file at the top-level directory of this distribution.
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * You can be released from the requirements of the AGPLv3 license by
 * purchasing a commercial license. Please contact licensing@stalw.art
 * for more details.
*/

pub mod lookup;
pub mod manage;

use std::{fmt::Display, slice::Iter};

use store::{write::key::KeySerializer, Deserialize, Serialize, U32_LEN};
use utils::codec::leb128::Leb128Iterator;

use crate::{Principal, Type};

pub(super) struct PrincipalIdType {
    pub account_id: u32,
    pub typ: Type,
}

impl Serialize for Principal<u32> {
    fn serialize(self) -> Vec<u8> {
        (&self).serialize()
    }
}

impl Serialize for &Principal<u32> {
    fn serialize(self) -> Vec<u8> {
        let mut serializer = KeySerializer::new(
            U32_LEN * 3
                + 2
                + self.name.len()
                + self.emails.iter().map(|s| s.len()).sum::<usize>()
                + self.secrets.iter().map(|s| s.len()).sum::<usize>()
                + self.member_of.len() * U32_LEN
                + self.description.as_ref().map(|s| s.len()).unwrap_or(0),
        )
        .write(1u8)
        .write_leb128(self.id)
        .write(self.typ as u8)
        .write_leb128(self.quota)
        .write_leb128(self.name.len())
        .write(self.name.as_bytes())
        .write_leb128(self.description.as_ref().map_or(0, |s| s.len()))
        .write(self.description.as_deref().unwrap_or_default().as_bytes());

        for list in [&self.secrets, &self.emails] {
            serializer = serializer.write_leb128(list.len());
            for value in list {
                serializer = serializer.write_leb128(value.len()).write(value.as_bytes());
            }
        }

        serializer = serializer.write_leb128(self.member_of.len());
        for id in &self.member_of {
            serializer = serializer.write_leb128(*id);
        }

        serializer.finalize()
    }
}

impl Deserialize for Principal<u32> {
    fn deserialize(bytes: &[u8]) -> store::Result<Self> {
        deserialize(bytes)
            .ok_or_else(|| store::Error::InternalError("Failed to deserialize principal".into()))
    }
}

impl Serialize for PrincipalIdType {
    fn serialize(self) -> Vec<u8> {
        KeySerializer::new(U32_LEN + 1)
            .write_leb128(self.account_id)
            .write(self.typ as u8)
            .finalize()
    }
}

impl Deserialize for PrincipalIdType {
    fn deserialize(bytes: &[u8]) -> store::Result<Self> {
        let mut bytes = bytes.iter();
        Ok(PrincipalIdType {
            account_id: bytes.next_leb128().ok_or_else(|| {
                store::Error::InternalError("Failed to deserialize principal account id".into())
            })?,
            typ: Type::from_u8(*bytes.next().ok_or_else(|| {
                store::Error::InternalError("Failed to deserialize principal id type".into())
            })?),
        })
    }
}

impl PrincipalIdType {
    pub fn new(account_id: u32, typ: Type) -> Self {
        Self { account_id, typ }
    }
}

fn deserialize(bytes: &[u8]) -> Option<Principal<u32>> {
    let mut bytes = bytes.iter();
    if bytes.next()? != &1 {
        return None;
    }

    Principal {
        id: bytes.next_leb128()?,
        typ: Type::from_u8(*bytes.next()?),
        quota: bytes.next_leb128()?,
        name: deserialize_string(&mut bytes)?,
        description: deserialize_string(&mut bytes).map(|v| {
            if !v.is_empty() {
                Some(v)
            } else {
                None
            }
        })?,
        secrets: deserialize_string_list(&mut bytes)?,
        emails: deserialize_string_list(&mut bytes)?,
        member_of: deserialize_u32_list(&mut bytes)?,
    }
    .into()
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum PrincipalField {
    #[serde(rename = "name")]
    Name,
    #[serde(rename = "type")]
    Type,
    #[serde(rename = "quota")]
    Quota,
    #[serde(rename = "description")]
    Description,
    #[serde(rename = "secrets")]
    Secrets,
    #[serde(rename = "emails")]
    Emails,
    #[serde(rename = "memberOf")]
    MemberOf,
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct PrincipalUpdate {
    action: PrincipalAction,
    field: PrincipalField,
    value: PrincipalValue,
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum PrincipalAction {
    #[serde(rename = "set")]
    Set,
    #[serde(rename = "addItem")]
    AddItem,
    #[serde(rename = "removeItem")]
    RemoveItem,
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(untagged)]
pub enum PrincipalValue {
    String(String),
    StringList(Vec<String>),
    Integer(u32),
    Type(Type),
}

impl PrincipalUpdate {
    pub fn set(field: PrincipalField, value: PrincipalValue) -> PrincipalUpdate {
        PrincipalUpdate {
            action: PrincipalAction::Set,
            field,
            value,
        }
    }

    pub fn add_item(field: PrincipalField, value: PrincipalValue) -> PrincipalUpdate {
        PrincipalUpdate {
            action: PrincipalAction::AddItem,
            field,
            value,
        }
    }

    pub fn remove_item(field: PrincipalField, value: PrincipalValue) -> PrincipalUpdate {
        PrincipalUpdate {
            action: PrincipalAction::RemoveItem,
            field,
            value,
        }
    }
}

impl Display for PrincipalField {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            PrincipalField::Name => write!(f, "name"),
            PrincipalField::Type => write!(f, "type"),
            PrincipalField::Quota => write!(f, "quota"),
            PrincipalField::Description => write!(f, "description"),
            PrincipalField::Secrets => write!(f, "secrets"),
            PrincipalField::Emails => write!(f, "emails"),
            PrincipalField::MemberOf => write!(f, "memberOf"),
        }
    }
}

fn deserialize_string(bytes: &mut Iter<'_, u8>) -> Option<String> {
    let len = bytes.next_leb128()?;
    let mut string = Vec::with_capacity(len);
    for _ in 0..len {
        string.push(*bytes.next()?);
    }
    String::from_utf8(string).ok()
}

fn deserialize_string_list(bytes: &mut Iter<'_, u8>) -> Option<Vec<String>> {
    let len = bytes.next_leb128()?;
    let mut list = Vec::with_capacity(len);
    for _ in 0..len {
        list.push(deserialize_string(bytes)?);
    }
    Some(list)
}

fn deserialize_u32_list(bytes: &mut Iter<'_, u8>) -> Option<Vec<u32>> {
    let len = bytes.next_leb128()?;
    let mut list = Vec::with_capacity(len);
    for _ in 0..len {
        list.push(bytes.next_leb128()?);
    }
    Some(list)
}

impl Type {
    pub fn parse(value: &str) -> Option<Self> {
        match value {
            "individual" | "superuser" => Some(Type::Individual),
            "group" => Some(Type::Group),
            "resource" => Some(Type::Resource),
            "location" => Some(Type::Location),
            "list" => Some(Type::List),
            _ => None,
        }
    }

    pub fn from_u8(value: u8) -> Self {
        match value {
            0 => Type::Individual,
            1 => Type::Group,
            2 => Type::Resource,
            3 => Type::Location,
            4 => Type::Superuser,
            5 => Type::List,
            _ => Type::Other,
        }
    }

    pub fn into_base_type(self) -> Self {
        match self {
            Type::Superuser => Type::Individual,
            any => any,
        }
    }
}