radixdb-catalog 1.1.0

Generational logical catalog owner for RadixDB
Documentation
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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
use crate::payload::common::{ordered_unique_ids, validate_flags};
use crate::{CatalogError, CatalogResult, ObjectId};

pub const PRIVILEGE_CONNECT: u64 = 1 << 0;
pub const PRIVILEGE_USAGE: u64 = 1 << 1;
pub const PRIVILEGE_CREATE: u64 = 1 << 7;
pub const PRIVILEGE_SELECT: u64 = 1 << 2;
pub const PRIVILEGE_INSERT: u64 = 1 << 3;
pub const PRIVILEGE_UPDATE: u64 = 1 << 4;
pub const PRIVILEGE_DELETE: u64 = 1 << 5;
pub const PRIVILEGE_EXECUTE: u64 = 1 << 6;
pub const ALL_OBJECT_PRIVILEGES: u64 = PRIVILEGE_CONNECT
    | PRIVILEGE_USAGE
    | PRIVILEGE_CREATE
    | PRIVILEGE_SELECT
    | PRIVILEGE_INSERT
    | PRIVILEGE_UPDATE
    | PRIVILEGE_DELETE
    | PRIVILEGE_EXECUTE;
const LEGACY_OBJECT_PRIVILEGES: u64 = ALL_OBJECT_PRIVILEGES & !PRIVILEGE_CREATE;

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PrincipalPayload {
    login_enabled: bool,
    system: bool,
    credential: Option<CredentialVerifier>,
}

pub const CREDENTIAL_SCHEME_ARGON2ID_PHC_V1: u16 = 1;
pub const MAX_CREDENTIAL_VERIFIER_BYTES: usize = 1024;

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CredentialVerifier {
    scheme: u16,
    encoded: Vec<u8>,
}

impl CredentialVerifier {
    pub fn new(scheme: u16, encoded: Vec<u8>) -> CatalogResult<Self> {
        if scheme != CREDENTIAL_SCHEME_ARGON2ID_PHC_V1 {
            return Err(CatalogError::InvalidCatalogObject {
                id: "principal-credential".to_owned(),
                detail: "unknown credential verifier scheme",
            });
        }
        if encoded.is_empty() || encoded.len() > MAX_CREDENTIAL_VERIFIER_BYTES {
            return Err(CatalogError::InvalidCatalogObject {
                id: "principal-credential".to_owned(),
                detail: "credential verifier length is outside the admitted range",
            });
        }
        Ok(Self { scheme, encoded })
    }

    pub const fn scheme(&self) -> u16 {
        self.scheme
    }

    pub fn encoded(&self) -> &[u8] {
        &self.encoded
    }
}

impl PrincipalPayload {
    pub fn new(login_enabled: bool, system: bool) -> Self {
        Self {
            login_enabled,
            system,
            credential: None,
        }
    }

    pub fn from_fields(
        version: u16,
        flags: u64,
        login_enabled: bool,
        system: bool,
    ) -> CatalogResult<Self> {
        if !matches!(
            version,
            super::PAYLOAD_VERSION | super::SECURITY_PAYLOAD_VERSION
        ) {
            return Err(CatalogError::UnsupportedPayloadVersion {
                kind: "principal",
                version,
            });
        }
        validate_flags("principal", flags)?;
        Ok(Self::new(login_enabled, system))
    }
    pub fn from_fields_with_credential(
        version: u16,
        flags: u64,
        login_enabled: bool,
        system: bool,
        credential: Option<CredentialVerifier>,
    ) -> CatalogResult<Self> {
        let mut payload = Self::from_fields(version, flags, login_enabled, system)?;
        if version == super::PAYLOAD_VERSION && credential.is_some() {
            return Err(CatalogError::InvalidCatalogObject {
                id: "principal-payload".to_owned(),
                detail: "payload version 1 cannot encode a credential verifier",
            });
        }
        payload.credential = credential;
        Ok(payload)
    }

    pub const fn login_enabled(&self) -> bool {
        self.login_enabled
    }
    pub fn with_login_enabled(self, login_enabled: bool) -> Self {
        Self {
            login_enabled,
            ..self
        }
    }
    pub fn credential(&self) -> Option<&CredentialVerifier> {
        self.credential.as_ref()
    }
    pub fn with_credential(mut self, credential: Option<CredentialVerifier>) -> Self {
        self.credential = credential;
        self
    }
    pub const fn system(&self) -> bool {
        self.system
    }
    pub const fn flags(&self) -> u64 {
        0
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RolePayload {
    inheritable: bool,
    enabled: bool,
}

impl RolePayload {
    pub fn new(inheritable: bool) -> Self {
        Self {
            inheritable,
            enabled: true,
        }
    }
    pub fn from_fields(
        version: u16,
        flags: u64,
        inheritable: bool,
        enabled: bool,
    ) -> CatalogResult<Self> {
        if !matches!(
            version,
            super::PAYLOAD_VERSION | super::SECURITY_PAYLOAD_VERSION
        ) {
            return Err(CatalogError::UnsupportedPayloadVersion {
                kind: "role",
                version,
            });
        }
        validate_flags("role", flags)?;
        if version == super::PAYLOAD_VERSION && !enabled {
            return Err(CatalogError::InvalidCatalogObject {
                id: "role-payload".to_owned(),
                detail: "payload version 1 cannot encode disabled roles",
            });
        }
        Ok(Self {
            inheritable,
            enabled,
        })
    }
    pub const fn inheritable(&self) -> bool {
        self.inheritable
    }
    pub const fn enabled(&self) -> bool {
        self.enabled
    }
    pub const fn with_enabled(self, enabled: bool) -> Self {
        Self { enabled, ..self }
    }
    pub const fn flags(&self) -> u64 {
        0
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ColumnPrivilegeSet {
    privilege: u64,
    column_ids: Vec<ObjectId>,
}

impl ColumnPrivilegeSet {
    pub fn new(privilege: u64, column_ids: Vec<ObjectId>) -> CatalogResult<Self> {
        if !matches!(
            privilege,
            PRIVILEGE_SELECT | PRIVILEGE_INSERT | PRIVILEGE_UPDATE
        ) {
            return Err(CatalogError::InvalidCatalogObject {
                id: "acl-payload".to_owned(),
                detail: "column privilege is not SELECT, INSERT or UPDATE",
            });
        }
        Ok(Self {
            privilege,
            column_ids: ordered_unique_ids("acl.column_ids", column_ids, false)?,
        })
    }
    pub const fn privilege(&self) -> u64 {
        self.privilege
    }
    pub fn column_ids(&self) -> &[ObjectId] {
        &self.column_ids
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AclEntryPayload {
    ObjectPrivileges {
        grantor_principal_id: ObjectId,
        privileges: u64,
        grant_option: u64,
        columns: Vec<ColumnPrivilegeSet>,
        column_grant_options: Vec<ColumnPrivilegeSet>,
    },
    RoleMembership {
        grantor_principal_id: ObjectId,
        admin_option: bool,
    },
}

impl AclEntryPayload {
    pub fn object_privileges(
        grantor_principal_id: ObjectId,
        privileges: u64,
        grant_option: u64,
        columns: Vec<ColumnPrivilegeSet>,
    ) -> CatalogResult<Self> {
        Self::object_privileges_with_column_options(
            grantor_principal_id,
            privileges,
            grant_option,
            columns,
            Vec::new(),
        )
    }

    pub fn object_privileges_with_column_options(
        grantor_principal_id: ObjectId,
        privileges: u64,
        grant_option: u64,
        mut columns: Vec<ColumnPrivilegeSet>,
        mut column_grant_options: Vec<ColumnPrivilegeSet>,
    ) -> CatalogResult<Self> {
        if privileges & !ALL_OBJECT_PRIVILEGES != 0 || grant_option & !privileges != 0 {
            return Err(CatalogError::InvalidCatalogObject {
                id: "acl-payload".to_owned(),
                detail: "object privilege bits are unknown or grant-option exceeds privileges",
            });
        }
        columns.sort_unstable_by_key(ColumnPrivilegeSet::privilege);
        if columns
            .windows(2)
            .any(|pair| pair[0].privilege == pair[1].privilege)
        {
            return Err(CatalogError::InvalidCatalogObject {
                id: "acl-payload".to_owned(),
                detail: "duplicate column privilege group",
            });
        }
        column_grant_options.sort_unstable_by_key(ColumnPrivilegeSet::privilege);
        if column_grant_options
            .windows(2)
            .any(|pair| pair[0].privilege == pair[1].privilege)
        {
            return Err(CatalogError::InvalidCatalogObject {
                id: "acl-payload".to_owned(),
                detail: "duplicate column grant-option privilege group",
            });
        }
        for option in &column_grant_options {
            let Some(granted) = columns
                .iter()
                .find(|group| group.privilege() == option.privilege())
            else {
                return Err(CatalogError::InvalidCatalogObject {
                    id: "acl-payload".to_owned(),
                    detail: "column grant option has no matching column privilege",
                });
            };
            if option
                .column_ids()
                .iter()
                .any(|id| !granted.column_ids().contains(id))
            {
                return Err(CatalogError::InvalidCatalogObject {
                    id: "acl-payload".to_owned(),
                    detail: "column grant option exceeds granted columns",
                });
            }
        }
        if privileges == 0 && columns.is_empty() {
            return Err(CatalogError::InvalidCatalogObject {
                id: "acl-payload".to_owned(),
                detail: "object and column privileges are both empty",
            });
        }
        Ok(Self::ObjectPrivileges {
            grantor_principal_id,
            privileges,
            grant_option,
            columns,
            column_grant_options,
        })
    }

    pub const fn role_membership(grantor_principal_id: ObjectId, admin_option: bool) -> Self {
        Self::RoleMembership {
            grantor_principal_id,
            admin_option,
        }
    }

    pub fn from_fields(version: u16, flags: u64, value: Self) -> CatalogResult<Self> {
        if !matches!(
            version,
            super::PAYLOAD_VERSION | super::SECURITY_PAYLOAD_VERSION
        ) {
            return Err(CatalogError::UnsupportedPayloadVersion {
                kind: "acl-entry",
                version,
            });
        }
        validate_flags("acl-entry", flags)?;
        match value {
            Self::ObjectPrivileges {
                grantor_principal_id,
                privileges,
                grant_option,
                columns,
                column_grant_options,
            } => {
                if version == super::PAYLOAD_VERSION
                    && ((privileges | grant_option) & !LEGACY_OBJECT_PRIVILEGES != 0
                        || !column_grant_options.is_empty())
                {
                    return Err(CatalogError::InvalidCatalogObject {
                        id: "acl-payload".to_owned(),
                        detail: "payload version 1 cannot encode CREATE or column grant options",
                    });
                }
                Self::object_privileges_with_column_options(
                    grantor_principal_id,
                    privileges,
                    grant_option,
                    columns,
                    column_grant_options,
                )
            }
            Self::RoleMembership {
                grantor_principal_id,
                admin_option,
            } => Ok(Self::role_membership(grantor_principal_id, admin_option)),
        }
    }

    pub const fn grantor_principal_id(&self) -> ObjectId {
        match self {
            Self::ObjectPrivileges {
                grantor_principal_id,
                ..
            }
            | Self::RoleMembership {
                grantor_principal_id,
                ..
            } => *grantor_principal_id,
        }
    }
    pub const fn flags(&self) -> u64 {
        0
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn id(marker: u8) -> ObjectId {
        let mut bytes = [marker; 16];
        bytes[0] = 1;
        ObjectId::from_user_bytes(bytes).unwrap()
    }

    #[test]
    fn column_only_privilege_does_not_invent_object_privilege() {
        let payload = AclEntryPayload::object_privileges(
            id(1),
            0,
            0,
            vec![ColumnPrivilegeSet::new(PRIVILEGE_SELECT, vec![id(2)]).unwrap()],
        )
        .unwrap();
        assert!(matches!(
            payload,
            AclEntryPayload::ObjectPrivileges { privileges: 0, .. }
        ));
    }

    #[test]
    fn empty_privilege_entry_is_rejected() {
        assert!(AclEntryPayload::object_privileges(id(1), 0, 0, vec![]).is_err());
    }

    #[test]
    fn legacy_security_payload_version_cannot_claim_new_semantics() {
        assert!(RolePayload::from_fields(super::super::PAYLOAD_VERSION, 0, true, false).is_err());
        assert!(AclEntryPayload::from_fields(
            super::super::PAYLOAD_VERSION,
            0,
            AclEntryPayload::object_privileges(id(1), PRIVILEGE_CREATE, 0, vec![]).unwrap(),
        )
        .is_err());
        assert!(AclEntryPayload::from_fields(
            super::super::PAYLOAD_VERSION,
            0,
            AclEntryPayload::object_privileges_with_column_options(
                id(1),
                0,
                0,
                vec![ColumnPrivilegeSet::new(PRIVILEGE_SELECT, vec![id(2)]).unwrap()],
                vec![ColumnPrivilegeSet::new(PRIVILEGE_SELECT, vec![id(2)]).unwrap()],
            )
            .unwrap(),
        )
        .is_err());
    }
}