Skip to main content

mz_repr/adt/
mz_acl_item.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10//! A Materialize specific access control list abstract data type.
11
12use std::collections::BTreeMap;
13use std::fmt;
14use std::mem::size_of;
15use std::ops::BitOrAssign;
16use std::str::FromStr;
17
18use crate::adt::system::Oid;
19use anyhow::{Error, anyhow};
20use bitflags::bitflags;
21use mz_ore::soft_assert_no_log;
22use mz_ore::str::StrExt;
23use mz_persist_types::columnar::FixedSizeCodec;
24use mz_proto::{RustType, TryFromProtoError};
25#[cfg(any(test, feature = "proptest"))]
26use proptest::arbitrary::Arbitrary;
27#[cfg(any(test, feature = "proptest"))]
28use proptest::prelude::*;
29#[cfg(any(test, feature = "proptest"))]
30use proptest::strategy::{BoxedStrategy, Strategy};
31#[cfg(any(test, feature = "proptest"))]
32use proptest_derive::Arbitrary;
33use serde::{Deserialize, Serialize};
34
35use crate::role_id::RoleId;
36
37include!(concat!(env!("OUT_DIR"), "/mz_repr.adt.mz_acl_item.rs"));
38
39// Append
40const INSERT_CHAR: char = 'a';
41// Read
42const SELECT_CHAR: char = 'r';
43// Write
44const UPDATE_CHAR: char = 'w';
45// Delete
46const DELETE_CHAR: char = 'd';
47// Usage
48const USAGE_CHAR: char = 'U';
49// Create
50const CREATE_CHAR: char = 'C';
51// Role
52const CREATE_ROLE_CHAR: char = 'R';
53// dataBase
54const CREATE_DB_CHAR: char = 'B';
55// compute Node
56const CREATE_CLUSTER_CHAR: char = 'N';
57// compute network Policy
58const CREATE_NETWORK_POLICY_CHAR: char = 'P';
59// Query policy
60const CREATE_QUERY_POLICY_CHAR: char = 'Q';
61
62const INSERT_STR: &str = "INSERT";
63const SELECT_STR: &str = "SELECT";
64const UPDATE_STR: &str = "UPDATE";
65const DELETE_STR: &str = "DELETE";
66const USAGE_STR: &str = "USAGE";
67const CREATE_STR: &str = "CREATE";
68const CREATE_ROLE_STR: &str = "CREATEROLE";
69const CREATE_DB_STR: &str = "CREATEDB";
70const CREATE_CLUSTER_STR: &str = "CREATECLUSTER";
71const CREATE_NETWORK_POLICY_STR: &str = "CREATENETWORKPOLICY";
72const CREATE_QUERY_POLICY_STR: &str = "CREATEQUERYPOLICY";
73
74/// The OID used to represent the PUBLIC role. See:
75/// <https://github.com/postgres/postgres/blob/29a0ccbce97978e5d65b8f96c85a00611bb403c4/src/include/utils/acl.h#L46>
76pub const PUBLIC_ROLE_OID: Oid = Oid(0);
77
78/// A bit flag representing all the privileges that can be granted to a role.
79///
80/// Modeled after:
81/// <https://github.com/postgres/postgres/blob/7f5b19817eaf38e70ad1153db4e644ee9456853e/src/include/nodes/parsenodes.h#L74-L101>
82///
83/// The lower 32 bits are used for different privilege types.
84///
85/// The upper 32 bits indicate a grant option on the privilege for the current bit shifted
86/// right by 32 bits (Currently unimplemented in Materialize).
87///
88/// Privileges that exist in Materialize but not PostgreSQL start at the highest available bit
89/// and move down towards the PostgreSQL compatible bits. This is try to avoid collisions with
90/// privileges that PostgreSQL may add in the future.
91#[derive(
92    Clone,
93    Copy,
94    PartialEq,
95    Eq,
96    PartialOrd,
97    Ord,
98    Hash,
99    Serialize,
100    Deserialize
101)]
102#[serde(from = "AclModeSerde", into = "AclModeSerde")]
103pub struct AclMode(u64);
104
105bitflags! {
106    impl AclMode: u64 {
107        // PostgreSQL compatible privileges.
108        const INSERT = 1 << 0;
109        const SELECT = 1 << 1;
110        const UPDATE = 1 << 2;
111        const DELETE = 1 << 3;
112        const USAGE = 1 << 8;
113        const CREATE = 1 << 9;
114
115        // Materialize custom privileges.
116        const CREATE_QUERY_POLICY = 1 << 28;
117        const CREATE_CLUSTER = 1 << 29;
118        const CREATE_DB = 1 << 30;
119        const CREATE_ROLE = 1 << 31;
120        const CREATE_NETWORK_POLICY = 1 << 32;
121
122        // No additional privileges should be defined at a bit larger than 1 << 31. Those bits are
123        // reserved for grant options.
124    }
125}
126
127/// The serde representation of [`AclMode`], `{"bits": <u64>}`, as derived by bitflags 1.
128#[derive(Serialize, Deserialize)]
129struct AclModeSerde {
130    bits: u64,
131}
132
133impl From<AclModeSerde> for AclMode {
134    fn from(AclModeSerde { bits }: AclModeSerde) -> Self {
135        AclMode::from_bits_retain(bits)
136    }
137}
138
139impl From<AclMode> for AclModeSerde {
140    fn from(acl_mode: AclMode) -> Self {
141        AclModeSerde {
142            bits: acl_mode.bits(),
143        }
144    }
145}
146
147// Matches the `Debug` output that bitflags 1 derived, for example `INSERT | SELECT`.
148impl fmt::Debug for AclMode {
149    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
150        if self.is_empty() {
151            f.write_str("(empty)")
152        } else {
153            bitflags::parser::to_writer(self, f)
154        }
155    }
156}
157
158impl AclMode {
159    pub fn parse_single_privilege(s: &str) -> Result<Self, Error> {
160        match s.trim().to_uppercase().as_str() {
161            INSERT_STR => Ok(AclMode::INSERT),
162            SELECT_STR => Ok(AclMode::SELECT),
163            UPDATE_STR => Ok(AclMode::UPDATE),
164            DELETE_STR => Ok(AclMode::DELETE),
165            USAGE_STR => Ok(AclMode::USAGE),
166            CREATE_STR => Ok(AclMode::CREATE),
167            CREATE_ROLE_STR => Ok(AclMode::CREATE_ROLE),
168            CREATE_DB_STR => Ok(AclMode::CREATE_DB),
169            CREATE_CLUSTER_STR => Ok(AclMode::CREATE_CLUSTER),
170            CREATE_NETWORK_POLICY_STR => Ok(AclMode::CREATE_NETWORK_POLICY),
171            CREATE_QUERY_POLICY_STR => Ok(AclMode::CREATE_QUERY_POLICY),
172            _ => Err(anyhow!("{}", s.quoted())),
173        }
174    }
175
176    pub fn parse_multiple_privileges(s: &str) -> Result<Self, Error> {
177        let mut acl_mode = AclMode::empty();
178        for privilege in s.split(',') {
179            let privilege = AclMode::parse_single_privilege(privilege)?;
180            acl_mode.bitor_assign(privilege);
181        }
182        Ok(acl_mode)
183    }
184
185    pub fn to_error_string(&self) -> String {
186        self.explode().join(", ")
187    }
188
189    pub fn explode(&self) -> Vec<&'static str> {
190        let mut privileges = Vec::new();
191        if self.contains(AclMode::SELECT) {
192            privileges.push(SELECT_STR);
193        }
194        if self.contains(AclMode::INSERT) {
195            privileges.push(INSERT_STR);
196        }
197        if self.contains(AclMode::UPDATE) {
198            privileges.push(UPDATE_STR);
199        }
200        if self.contains(AclMode::DELETE) {
201            privileges.push(DELETE_STR);
202        }
203        if self.contains(AclMode::USAGE) {
204            privileges.push(USAGE_STR);
205        }
206        if self.contains(AclMode::CREATE) {
207            privileges.push(CREATE_STR);
208        }
209        if self.contains(AclMode::CREATE_ROLE) {
210            privileges.push(CREATE_ROLE_STR);
211        }
212        if self.contains(AclMode::CREATE_DB) {
213            privileges.push(CREATE_DB_STR);
214        }
215        if self.contains(AclMode::CREATE_CLUSTER) {
216            privileges.push(CREATE_CLUSTER_STR);
217        }
218        if self.contains(AclMode::CREATE_NETWORK_POLICY) {
219            privileges.push(CREATE_NETWORK_POLICY_STR);
220        }
221        if self.contains(AclMode::CREATE_QUERY_POLICY) {
222            privileges.push(CREATE_QUERY_POLICY_STR);
223        }
224        privileges
225    }
226}
227
228impl FromStr for AclMode {
229    type Err = Error;
230
231    fn from_str(s: &str) -> Result<Self, Self::Err> {
232        let mut acl_mode = AclMode::empty();
233        for c in s.chars() {
234            match c {
235                INSERT_CHAR => acl_mode.bitor_assign(AclMode::INSERT),
236                SELECT_CHAR => acl_mode.bitor_assign(AclMode::SELECT),
237                UPDATE_CHAR => acl_mode.bitor_assign(AclMode::UPDATE),
238                DELETE_CHAR => acl_mode.bitor_assign(AclMode::DELETE),
239                USAGE_CHAR => acl_mode.bitor_assign(AclMode::USAGE),
240                CREATE_CHAR => acl_mode.bitor_assign(AclMode::CREATE),
241                CREATE_ROLE_CHAR => acl_mode.bitor_assign(AclMode::CREATE_ROLE),
242                CREATE_DB_CHAR => acl_mode.bitor_assign(AclMode::CREATE_DB),
243                CREATE_CLUSTER_CHAR => acl_mode.bitor_assign(AclMode::CREATE_CLUSTER),
244                CREATE_NETWORK_POLICY_CHAR => acl_mode.bitor_assign(AclMode::CREATE_NETWORK_POLICY),
245                CREATE_QUERY_POLICY_CHAR => acl_mode.bitor_assign(AclMode::CREATE_QUERY_POLICY),
246                _ => return Err(anyhow!("invalid privilege '{c}' in acl mode '{s}'")),
247            }
248        }
249        Ok(acl_mode)
250    }
251}
252
253impl fmt::Display for AclMode {
254    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
255        // The order of each flag matches PostgreSQL, which uses the same order that they're
256        // defined in.
257        if self.contains(AclMode::INSERT) {
258            write!(f, "{INSERT_CHAR}")?;
259        }
260        if self.contains(AclMode::SELECT) {
261            write!(f, "{SELECT_CHAR}")?;
262        }
263        if self.contains(AclMode::UPDATE) {
264            write!(f, "{UPDATE_CHAR}")?;
265        }
266        if self.contains(AclMode::DELETE) {
267            write!(f, "{DELETE_CHAR}")?;
268        }
269        if self.contains(AclMode::USAGE) {
270            write!(f, "{USAGE_CHAR}")?;
271        }
272        if self.contains(AclMode::CREATE) {
273            write!(f, "{CREATE_CHAR}")?;
274        }
275        if self.contains(AclMode::CREATE_ROLE) {
276            write!(f, "{CREATE_ROLE_CHAR}")?;
277        }
278        if self.contains(AclMode::CREATE_DB) {
279            write!(f, "{CREATE_DB_CHAR}")?;
280        }
281        if self.contains(AclMode::CREATE_CLUSTER) {
282            write!(f, "{CREATE_CLUSTER_CHAR}")?;
283        }
284        if self.contains(AclMode::CREATE_NETWORK_POLICY) {
285            write!(f, "{CREATE_NETWORK_POLICY_CHAR}")?;
286        }
287        if self.contains(AclMode::CREATE_QUERY_POLICY) {
288            write!(f, "{CREATE_QUERY_POLICY_CHAR}")?;
289        }
290        Ok(())
291    }
292}
293
294impl RustType<ProtoAclMode> for AclMode {
295    fn into_proto(&self) -> ProtoAclMode {
296        ProtoAclMode {
297            acl_mode: self.bits(),
298        }
299    }
300
301    fn from_proto(proto: ProtoAclMode) -> Result<Self, TryFromProtoError> {
302        Ok(AclMode::from_bits_retain(proto.acl_mode))
303    }
304}
305
306#[cfg(any(test, feature = "proptest"))]
307impl Arbitrary for AclMode {
308    type Parameters = ();
309    type Strategy = BoxedStrategy<AclMode>;
310
311    fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {
312        proptest::bits::BitSetStrategy::masked(AclMode::all().bits())
313            .prop_map(|bits| AclMode::from_bits(bits).expect("invalid proptest implementation"))
314            .boxed()
315    }
316}
317
318/// A list of privileges granted to a role in Materialize.
319///
320/// This is modelled after the AclItem type in PostgreSQL, but the OIDs are replaced with RoleIds
321/// because we don't use OID as persistent identifiers for roles.
322///
323/// See: <https://github.com/postgres/postgres/blob/7f5b19817eaf38e70ad1153db4e644ee9456853e/src/include/utils/acl.h#L48-L59>
324#[derive(
325    Debug,
326    Clone,
327    Copy,
328    PartialEq,
329    Eq,
330    PartialOrd,
331    Ord,
332    Serialize,
333    Hash,
334    Deserialize
335)]
336#[cfg_attr(any(test, feature = "proptest"), derive(Arbitrary))]
337pub struct MzAclItem {
338    /// Role that this item grants privileges to.
339    pub grantee: RoleId,
340    /// Grantor of privileges.
341    pub grantor: RoleId,
342    /// Privileges bit flag.
343    pub acl_mode: AclMode,
344}
345
346impl MzAclItem {
347    pub fn empty(grantee: RoleId, grantor: RoleId) -> MzAclItem {
348        MzAclItem {
349            grantee,
350            grantor,
351            acl_mode: AclMode::empty(),
352        }
353    }
354
355    pub fn encode_binary(&self) -> Vec<u8> {
356        let mut res = Vec::with_capacity(Self::binary_size());
357        res.extend_from_slice(&self.grantee.encode_binary());
358        res.extend_from_slice(&self.grantor.encode_binary());
359        res.extend_from_slice(&self.acl_mode.bits().to_le_bytes());
360        res
361    }
362
363    pub fn decode_binary(raw: &[u8]) -> Result<MzAclItem, Error> {
364        if raw.len() != MzAclItem::binary_size() {
365            return Err(anyhow!(
366                "invalid binary size, expecting {}, found {}",
367                MzAclItem::binary_size(),
368                raw.len()
369            ));
370        }
371
372        let role_id_size = RoleId::binary_size();
373
374        let grantee = RoleId::decode_binary(&raw[0..role_id_size])?;
375        let raw = &raw[role_id_size..];
376        let grantor = RoleId::decode_binary(&raw[0..role_id_size])?;
377        let raw = &raw[role_id_size..];
378        let acl_mode = u64::from_le_bytes(raw.try_into()?);
379
380        Ok(MzAclItem {
381            grantee,
382            grantor,
383            acl_mode: AclMode::from_bits_retain(acl_mode),
384        })
385    }
386
387    pub const fn binary_size() -> usize {
388        RoleId::binary_size() + RoleId::binary_size() + size_of::<u64>()
389    }
390}
391
392impl FromStr for MzAclItem {
393    type Err = Error;
394
395    fn from_str(s: &str) -> Result<Self, Self::Err> {
396        let parts: Vec<_> = s.split('=').collect();
397        let &[grantee, rest] = parts.as_slice() else {
398            return Err(anyhow!("invalid mz_aclitem '{s}'"));
399        };
400
401        let parts: Vec<_> = rest.split('/').collect();
402        let &[acl_mode, grantor] = parts.as_slice() else {
403            return Err(anyhow!("invalid mz_aclitem '{s}'"));
404        };
405
406        let grantee: RoleId = if grantee.is_empty() {
407            RoleId::Public
408        } else {
409            grantee.parse()?
410        };
411        let acl_mode: AclMode = acl_mode.parse()?;
412        let grantor: RoleId = grantor.parse()?;
413
414        Ok(MzAclItem {
415            grantee,
416            grantor,
417            acl_mode,
418        })
419    }
420}
421
422impl fmt::Display for MzAclItem {
423    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
424        if !self.grantee.is_public() {
425            write!(f, "{}", self.grantee)?;
426        }
427        write!(f, "={}/{}", self.acl_mode, self.grantor)
428    }
429}
430
431impl RustType<ProtoMzAclItem> for MzAclItem {
432    fn into_proto(&self) -> ProtoMzAclItem {
433        ProtoMzAclItem {
434            grantee: Some(self.grantee.into_proto()),
435            grantor: Some(self.grantor.into_proto()),
436            acl_mode: Some(self.acl_mode.into_proto()),
437        }
438    }
439
440    fn from_proto(proto: ProtoMzAclItem) -> Result<Self, TryFromProtoError> {
441        match (proto.grantee, proto.grantor, proto.acl_mode) {
442            (Some(grantee), Some(grantor), Some(acl_mode)) => Ok(MzAclItem {
443                grantee: RoleId::from_proto(grantee)?,
444                grantor: RoleId::from_proto(grantor)?,
445                acl_mode: AclMode::from_proto(acl_mode)?,
446            }),
447            (None, _, _) => Err(TryFromProtoError::missing_field("ProtoMzAclItem::grantee")),
448            (_, None, _) => Err(TryFromProtoError::missing_field("ProtoMzAclItem::grantor")),
449            (_, _, None) => Err(TryFromProtoError::missing_field("ProtoMzAclItem::acl_mode")),
450        }
451    }
452}
453
454/// An encoded packed variant of [`MzAclItem`].
455///
456/// We uphold the variant that [`PackedMzAclItem`] sorts the same as [`MzAclItem`].
457#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
458pub struct PackedMzAclItem([u8; Self::SIZE]);
459
460impl PackedMzAclItem {
461    // Note: It's critical to the sort order guarantee that these tags sort the same as the
462    // variants of RoleId. We leave space between each tag for future variants.
463    //
464    // Note: An alternative would be to use a `u8` for the tag, while this is more memory
465    // efficient micro benchmarks show throughput increases by ~40% for the encode path and ~130%
466    // for the decode path when using a `u32`. Looking at the generated assembly there are more
467    // load and store instructions when using a `u8` and unaligned reads.
468
469    pub const SYSTEM_TAG: u32 = 100;
470    pub const PREDEFINED_TAG: u32 = 200;
471    pub const USER_TAG: u32 = 300;
472    pub const PUBLIC_TAG: u32 = 400;
473
474    #[inline]
475    fn encode_role(buf: &mut [u8], role: RoleId) {
476        soft_assert_no_log!(buf.len() == 12);
477
478        match role {
479            RoleId::System(val) => {
480                buf[..4].copy_from_slice(&Self::SYSTEM_TAG.to_be_bytes());
481                buf[4..].copy_from_slice(&val.to_be_bytes());
482            }
483            RoleId::Predefined(val) => {
484                buf[..4].copy_from_slice(&Self::PREDEFINED_TAG.to_be_bytes());
485                buf[4..].copy_from_slice(&val.to_be_bytes());
486            }
487            RoleId::User(val) => {
488                buf[..4].copy_from_slice(&Self::USER_TAG.to_be_bytes());
489                buf[4..].copy_from_slice(&val.to_be_bytes());
490            }
491            RoleId::Public => {
492                buf[..4].copy_from_slice(&Self::PUBLIC_TAG.to_be_bytes());
493            }
494        }
495    }
496
497    #[inline]
498    fn decode_role(buf: &[u8]) -> RoleId {
499        soft_assert_no_log!(buf.len() == 12);
500
501        let tag: [u8; 4] = buf[..4]
502            .try_into()
503            .expect("PackedMzAclItem should roundtrip");
504        let tag = u32::from_be_bytes(tag);
505
506        let val: [u8; 8] = buf[4..]
507            .try_into()
508            .expect("PackedMzAclItem should roundtrip");
509        let val = u64::from_be_bytes(val);
510
511        match tag {
512            Self::SYSTEM_TAG => RoleId::System(val),
513            Self::PREDEFINED_TAG => RoleId::Predefined(val),
514            Self::USER_TAG => RoleId::User(val),
515            Self::PUBLIC_TAG => RoleId::Public,
516            x => panic!("unrecognized tag {x}"),
517        }
518    }
519}
520
521impl FixedSizeCodec<MzAclItem> for PackedMzAclItem {
522    const SIZE: usize = 32;
523
524    fn as_bytes(&self) -> &[u8] {
525        &self.0
526    }
527
528    fn from_bytes(val: &[u8]) -> Result<Self, String>
529    where
530        Self: Sized,
531    {
532        let buf: [u8; Self::SIZE] = val.try_into().map_err(|_| {
533            format!(
534                "size for PackedMzAclItem is {} bytes, got {}",
535                Self::SIZE,
536                val.len()
537            )
538        })?;
539
540        Ok(PackedMzAclItem(buf))
541    }
542
543    #[inline]
544    fn from_value(value: MzAclItem) -> Self {
545        let mut buf = [0u8; 32];
546
547        Self::encode_role(&mut buf[..12], value.grantee);
548        Self::encode_role(&mut buf[12..24], value.grantor);
549        buf[24..].copy_from_slice(&value.acl_mode.bits().to_be_bytes());
550
551        PackedMzAclItem(buf)
552    }
553
554    #[inline]
555    fn into_value(self) -> MzAclItem {
556        let grantee = PackedMzAclItem::decode_role(&self.0[..12]);
557        let grantor = PackedMzAclItem::decode_role(&self.0[12..24]);
558
559        let acl_mode: [u8; 8] = self.0[24..]
560            .try_into()
561            .expect("PackedMzAclItem should roundtrip");
562        let acl_mode = AclMode::from_bits(u64::from_be_bytes(acl_mode))
563            .expect("PackedMzAclItem should roundtrip");
564
565        MzAclItem {
566            grantee,
567            grantor,
568            acl_mode,
569        }
570    }
571}
572
573/// A list of privileges granted to a role.
574///
575/// This is primarily used for compatibility in PostgreSQL.
576///
577/// See: <https://github.com/postgres/postgres/blob/7f5b19817eaf38e70ad1153db4e644ee9456853e/src/include/utils/acl.h#L48-L59>
578#[derive(
579    Debug,
580    Clone,
581    Copy,
582    PartialEq,
583    Eq,
584    PartialOrd,
585    Ord,
586    Serialize,
587    Hash,
588    Deserialize
589)]
590#[cfg_attr(any(test, feature = "proptest"), derive(Arbitrary))]
591pub struct AclItem {
592    /// Role that this item grants privileges to.
593    pub grantee: Oid,
594    /// Grantor of privileges.
595    pub grantor: Oid,
596    /// Privileges bit flag.
597    pub acl_mode: AclMode,
598}
599
600impl AclItem {
601    pub fn empty(grantee: Oid, grantor: Oid) -> AclItem {
602        AclItem {
603            grantee,
604            grantor,
605            acl_mode: AclMode::empty(),
606        }
607    }
608}
609
610// PostgreSQL has no stable binary encoding for AclItems. However, we need to be able to convert
611// types to and from binary, to pack a Datum in a row, so we invent our own encoding. The encoding
612// matches the in memory format that PostgreSQL uses, which is (Oid, Oid, AclMode).
613impl AclItem {
614    pub fn encode_binary(&self) -> Vec<u8> {
615        let mut res = Vec::with_capacity(Self::binary_size());
616        res.extend_from_slice(&self.grantee.0.to_le_bytes());
617        res.extend_from_slice(&self.grantor.0.to_le_bytes());
618        res.extend_from_slice(&self.acl_mode.bits().to_le_bytes());
619        res
620    }
621
622    pub fn decode_binary(raw: &[u8]) -> Result<AclItem, Error> {
623        if raw.len() != AclItem::binary_size() {
624            return Err(anyhow!(
625                "invalid binary size, expecting {}, found {}",
626                AclItem::binary_size(),
627                raw.len()
628            ));
629        }
630
631        let oid_size = size_of::<u32>();
632
633        let grantee = Oid(u32::from_le_bytes(raw[0..oid_size].try_into()?));
634        let raw = &raw[oid_size..];
635        let grantor = Oid(u32::from_le_bytes(raw[0..oid_size].try_into()?));
636        let raw = &raw[oid_size..];
637        let acl_mode = u64::from_le_bytes(raw.try_into()?);
638
639        Ok(AclItem {
640            grantee,
641            grantor,
642            acl_mode: AclMode::from_bits_retain(acl_mode),
643        })
644    }
645
646    pub const fn binary_size() -> usize {
647        size_of::<u32>() + size_of::<u32>() + size_of::<u64>()
648    }
649}
650
651impl FromStr for AclItem {
652    type Err = Error;
653
654    /// For the PostgreSQL implementation see:
655    ///   * <https://github.com/postgres/postgres/blob/9089287aa037fdecb5a52cec1926e5ae9569e9f9/src/backend/utils/adt/acl.c#L580-L609>
656    ///   * <https://github.com/postgres/postgres/blob/9089287aa037fdecb5a52cec1926e5ae9569e9f9/src/backend/utils/adt/acl.c#L223-L390>
657    ///   * <https://github.com/postgres/postgres/blob/9089287aa037fdecb5a52cec1926e5ae9569e9f9/src/backend/utils/adt/acl.c#L127-L187>
658    ///
659    /// PostgreSQL is able to look up OIDs in the catalog while parsing, so it accepts aclitems that
660    /// contain role OIDs or role names. We have no way to access the catalog here, so we can only
661    /// accept oids. Therefore our implementation is much simpler than PostgreSQL's.
662    fn from_str(s: &str) -> Result<Self, Self::Err> {
663        let parts: Vec<_> = s.split('=').collect();
664        let &[grantee, rest] = parts.as_slice() else {
665            return Err(anyhow!("invalid aclitem '{s}'"));
666        };
667
668        let parts: Vec<_> = rest.split('/').collect();
669        let &[acl_mode, grantor] = parts.as_slice() else {
670            return Err(anyhow!("invalid mz_aclitem '{s}'"));
671        };
672
673        let grantee: Oid = if grantee.is_empty() {
674            PUBLIC_ROLE_OID
675        } else {
676            Oid(grantee.parse()?)
677        };
678        let acl_mode: AclMode = acl_mode.parse()?;
679        let grantor: Oid = Oid(grantor.parse()?);
680
681        Ok(AclItem {
682            grantee,
683            grantor,
684            acl_mode,
685        })
686    }
687}
688
689impl fmt::Display for AclItem {
690    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
691        if self.grantee != PUBLIC_ROLE_OID {
692            write!(f, "{}", self.grantee.0)?;
693        }
694        write!(f, "={}/{}", self.acl_mode, self.grantor.0)
695    }
696}
697
698impl RustType<ProtoAclItem> for AclItem {
699    fn into_proto(&self) -> ProtoAclItem {
700        ProtoAclItem {
701            grantee: self.grantee.0,
702            grantor: self.grantor.0,
703            acl_mode: Some(self.acl_mode.into_proto()),
704        }
705    }
706
707    fn from_proto(proto: ProtoAclItem) -> Result<Self, TryFromProtoError> {
708        match proto.acl_mode {
709            Some(acl_mode) => Ok(AclItem {
710                grantee: Oid(proto.grantee),
711                grantor: Oid(proto.grantor),
712                acl_mode: AclMode::from_proto(acl_mode)?,
713            }),
714            None => Err(TryFromProtoError::missing_field("ProtoMzAclItem::acl_mode")),
715        }
716    }
717}
718
719/// An encoded packed variant of [`AclItem`].
720///
721/// We uphold the variant that [`PackedAclItem`] sorts the same as [`AclItem`].
722#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
723pub struct PackedAclItem([u8; Self::SIZE]);
724
725impl FixedSizeCodec<AclItem> for PackedAclItem {
726    const SIZE: usize = 16;
727
728    fn as_bytes(&self) -> &[u8] {
729        &self.0
730    }
731
732    fn from_bytes(slice: &[u8]) -> Result<Self, String> {
733        let buf: [u8; Self::SIZE] = slice.try_into().map_err(|_| {
734            format!(
735                "size for PackedAclItem is {} bytes, got {}",
736                Self::SIZE,
737                slice.len()
738            )
739        })?;
740        Ok(PackedAclItem(buf))
741    }
742
743    #[inline]
744    fn from_value(value: AclItem) -> Self {
745        let mut buf = [0u8; 16];
746
747        buf[..4].copy_from_slice(&value.grantee.0.to_be_bytes());
748        buf[4..8].copy_from_slice(&value.grantor.0.to_be_bytes());
749        buf[8..].copy_from_slice(&value.acl_mode.bits().to_be_bytes());
750
751        PackedAclItem(buf)
752    }
753
754    #[inline]
755    fn into_value(self) -> AclItem {
756        let mut grantee = [0; 4];
757        grantee.copy_from_slice(&self.0[..4]);
758
759        let mut grantor = [0; 4];
760        grantor.copy_from_slice(&self.0[4..8]);
761
762        let mut acl_mode = [0; 8];
763        acl_mode.copy_from_slice(&self.0[8..]);
764        let acl_mode = AclMode::from_bits(u64::from_be_bytes(acl_mode))
765            .expect("PackedAclItem should roundtrip");
766
767        AclItem {
768            grantee: Oid(u32::from_be_bytes(grantee)),
769            grantor: Oid(u32::from_be_bytes(grantor)),
770            acl_mode,
771        }
772    }
773}
774
775/// A container of [`MzAclItem`]s that is optimized to look up an [`MzAclItem`] by the grantee.
776#[derive(
777    Debug,
778    Clone,
779    PartialEq,
780    Eq,
781    PartialOrd,
782    Ord,
783    Hash,
784    Deserialize,
785    Serialize
786)]
787pub struct PrivilegeMap(
788    #[serde(serialize_with = "mz_ore::serde::map_key_to_string")] BTreeMap<RoleId, Vec<MzAclItem>>,
789);
790
791impl PrivilegeMap {
792    /// Creates a new empty `PrivilegeMap`.
793    pub fn new() -> PrivilegeMap {
794        PrivilegeMap(BTreeMap::new())
795    }
796
797    /// Creates a new `PrivilegeMap` from a collection of [`MzAclItem`]s.
798    pub fn from_mz_acl_items(items: impl IntoIterator<Item = MzAclItem>) -> PrivilegeMap {
799        let mut map = PrivilegeMap::new();
800        map.grant_all(items);
801        map
802    }
803
804    /// Get the acl item granted to `grantee` by `grantor`.
805    pub fn get_acl_item(&self, grantee: &RoleId, grantor: &RoleId) -> Option<&MzAclItem> {
806        self.0.get(grantee).and_then(|privileges| {
807            privileges
808                .into_iter()
809                .find(|mz_acl_item| &mz_acl_item.grantor == grantor)
810        })
811    }
812
813    /// Get all acl items granted to `grantee`.
814    pub fn get_acl_items_for_grantee(&self, grantee: &RoleId) -> impl Iterator<Item = &MzAclItem> {
815        self.0
816            .get(grantee)
817            .into_iter()
818            .flat_map(|privileges| privileges.into_iter())
819    }
820
821    /// Returns references to all contained [`MzAclItem`].
822    pub fn all_values(&self) -> impl Iterator<Item = &MzAclItem> {
823        self.0
824            .values()
825            .flat_map(|privileges| privileges.into_iter())
826    }
827
828    /// Returns clones of all contained [`MzAclItem`].
829    pub fn all_values_owned(&self) -> impl Iterator<Item = MzAclItem> + '_ {
830        self.all_values().cloned()
831    }
832
833    /// Consumes self and returns all contained [`MzAclItem`].
834    pub fn into_all_values(self) -> impl Iterator<Item = MzAclItem> {
835        self.0
836            .into_values()
837            .flat_map(|privileges| privileges.into_iter())
838    }
839
840    /// Adds an [`MzAclItem`] to this map.
841    pub fn grant(&mut self, privilege: MzAclItem) {
842        let grantee_privileges = self.0.entry(privilege.grantee).or_default();
843        if let Some(existing_privilege) = grantee_privileges
844            .iter_mut()
845            .find(|cur_privilege| cur_privilege.grantor == privilege.grantor)
846        {
847            // sanity check that the key is consistent.
848            assert_eq!(
849                privilege.grantee, existing_privilege.grantee,
850                "PrivilegeMap out of sync"
851            );
852            existing_privilege.acl_mode = existing_privilege.acl_mode.union(privilege.acl_mode);
853        } else {
854            grantee_privileges.push(privilege);
855        }
856    }
857
858    /// Grant multiple [`MzAclItem`]s to this map.
859    pub fn grant_all(&mut self, mz_acl_items: impl IntoIterator<Item = MzAclItem>) {
860        for mz_acl_item in mz_acl_items {
861            self.grant(mz_acl_item);
862        }
863    }
864
865    /// Removes an [`MzAclItem`] from this map.
866    pub fn revoke(&mut self, privilege: &MzAclItem) {
867        let grantee_privileges = self.0.entry(privilege.grantee).or_default();
868        if let Some(existing_privilege) = grantee_privileges
869            .iter_mut()
870            .find(|cur_privilege| cur_privilege.grantor == privilege.grantor)
871        {
872            // sanity check that the key is consistent.
873            assert_eq!(
874                privilege.grantee, existing_privilege.grantee,
875                "PrivilegeMap out of sync"
876            );
877            existing_privilege.acl_mode =
878                existing_privilege.acl_mode.difference(privilege.acl_mode);
879        }
880
881        // Remove empty privileges.
882        grantee_privileges.retain(|privilege| !privilege.acl_mode.is_empty());
883        if grantee_privileges.is_empty() {
884            self.0.remove(&privilege.grantee);
885        }
886    }
887
888    /// Returns a `PrivilegeMap` formatted as a `serde_json::Value` that is suitable for debugging. For
889    /// example `CatalogState::dump`.
890    pub fn debug_json(&self) -> serde_json::Value {
891        let privileges_by_str: BTreeMap<String, _> = self
892            .0
893            .iter()
894            .map(|(key, value)| (key.to_string(), value))
895            .collect();
896        serde_json::json!(privileges_by_str)
897    }
898}
899
900impl Default for PrivilegeMap {
901    fn default() -> PrivilegeMap {
902        PrivilegeMap::new()
903    }
904}
905
906/// Combines all [`MzAclItem`]s that have the same grantee and grantor.
907pub fn merge_mz_acl_items(
908    mz_acl_items: impl Iterator<Item = MzAclItem>,
909) -> impl Iterator<Item = MzAclItem> {
910    mz_acl_items
911        .fold(BTreeMap::new(), |mut accum, mz_acl_item| {
912            let item = accum
913                .entry((mz_acl_item.grantee, mz_acl_item.grantor))
914                .or_insert_with(|| MzAclItem::empty(mz_acl_item.grantee, mz_acl_item.grantor));
915            item.acl_mode |= mz_acl_item.acl_mode;
916            accum
917        })
918        .into_values()
919}
920
921#[mz_ore::test]
922fn test_mz_acl_parsing() {
923    let s = "u42=rw/s666";
924    let mz_acl: MzAclItem = s.parse().unwrap();
925    assert_eq!(RoleId::User(42), mz_acl.grantee);
926    assert_eq!(RoleId::System(666), mz_acl.grantor);
927    assert!(!mz_acl.acl_mode.contains(AclMode::INSERT));
928    assert!(mz_acl.acl_mode.contains(AclMode::SELECT));
929    assert!(mz_acl.acl_mode.contains(AclMode::UPDATE));
930    assert!(!mz_acl.acl_mode.contains(AclMode::DELETE));
931    assert!(!mz_acl.acl_mode.contains(AclMode::USAGE));
932    assert!(!mz_acl.acl_mode.contains(AclMode::CREATE));
933    assert!(!mz_acl.acl_mode.contains(AclMode::CREATE_ROLE));
934    assert!(!mz_acl.acl_mode.contains(AclMode::CREATE_DB));
935    assert!(!mz_acl.acl_mode.contains(AclMode::CREATE_CLUSTER));
936    assert!(!mz_acl.acl_mode.contains(AclMode::CREATE_NETWORK_POLICY));
937    assert_eq!(s, mz_acl.to_string());
938
939    let s = "=UC/u4";
940    let mz_acl: MzAclItem = s.parse().unwrap();
941    assert_eq!(RoleId::Public, mz_acl.grantee);
942    assert_eq!(RoleId::User(4), mz_acl.grantor);
943    assert!(!mz_acl.acl_mode.contains(AclMode::INSERT));
944    assert!(!mz_acl.acl_mode.contains(AclMode::SELECT));
945    assert!(!mz_acl.acl_mode.contains(AclMode::UPDATE));
946    assert!(!mz_acl.acl_mode.contains(AclMode::DELETE));
947    assert!(mz_acl.acl_mode.contains(AclMode::USAGE));
948    assert!(mz_acl.acl_mode.contains(AclMode::CREATE));
949    assert!(!mz_acl.acl_mode.contains(AclMode::CREATE_ROLE));
950    assert!(!mz_acl.acl_mode.contains(AclMode::CREATE_DB));
951    assert!(!mz_acl.acl_mode.contains(AclMode::CREATE_CLUSTER));
952    assert!(!mz_acl.acl_mode.contains(AclMode::CREATE_NETWORK_POLICY));
953    assert_eq!(s, mz_acl.to_string());
954
955    let s = "s7=/s12";
956    let mz_acl: MzAclItem = s.parse().unwrap();
957    assert_eq!(RoleId::System(7), mz_acl.grantee);
958    assert_eq!(RoleId::System(12), mz_acl.grantor);
959    assert!(!mz_acl.acl_mode.contains(AclMode::INSERT));
960    assert!(!mz_acl.acl_mode.contains(AclMode::SELECT));
961    assert!(!mz_acl.acl_mode.contains(AclMode::UPDATE));
962    assert!(!mz_acl.acl_mode.contains(AclMode::DELETE));
963    assert!(!mz_acl.acl_mode.contains(AclMode::USAGE));
964    assert!(!mz_acl.acl_mode.contains(AclMode::CREATE));
965    assert!(!mz_acl.acl_mode.contains(AclMode::CREATE_ROLE));
966    assert!(!mz_acl.acl_mode.contains(AclMode::CREATE_DB));
967    assert!(!mz_acl.acl_mode.contains(AclMode::CREATE_CLUSTER));
968    assert!(!mz_acl.acl_mode.contains(AclMode::CREATE_NETWORK_POLICY));
969    assert_eq!(s, mz_acl.to_string());
970
971    let s = "=/u100";
972    let mz_acl: MzAclItem = s.parse().unwrap();
973    assert_eq!(RoleId::Public, mz_acl.grantee);
974    assert_eq!(RoleId::User(100), mz_acl.grantor);
975    assert!(!mz_acl.acl_mode.contains(AclMode::INSERT));
976    assert!(!mz_acl.acl_mode.contains(AclMode::SELECT));
977    assert!(!mz_acl.acl_mode.contains(AclMode::UPDATE));
978    assert!(!mz_acl.acl_mode.contains(AclMode::DELETE));
979    assert!(!mz_acl.acl_mode.contains(AclMode::USAGE));
980    assert!(!mz_acl.acl_mode.contains(AclMode::CREATE));
981    assert!(!mz_acl.acl_mode.contains(AclMode::CREATE_ROLE));
982    assert!(!mz_acl.acl_mode.contains(AclMode::CREATE_DB));
983    assert!(!mz_acl.acl_mode.contains(AclMode::CREATE_CLUSTER));
984    assert!(!mz_acl.acl_mode.contains(AclMode::CREATE_NETWORK_POLICY));
985    assert_eq!(s, mz_acl.to_string());
986
987    let s = "u1=RBNP/u2";
988    let mz_acl: MzAclItem = s.parse().unwrap();
989    assert_eq!(RoleId::User(1), mz_acl.grantee);
990    assert_eq!(RoleId::User(2), mz_acl.grantor);
991    assert!(!mz_acl.acl_mode.contains(AclMode::INSERT));
992    assert!(!mz_acl.acl_mode.contains(AclMode::SELECT));
993    assert!(!mz_acl.acl_mode.contains(AclMode::UPDATE));
994    assert!(!mz_acl.acl_mode.contains(AclMode::DELETE));
995    assert!(!mz_acl.acl_mode.contains(AclMode::USAGE));
996    assert!(!mz_acl.acl_mode.contains(AclMode::CREATE));
997    assert!(mz_acl.acl_mode.contains(AclMode::CREATE_ROLE));
998    assert!(mz_acl.acl_mode.contains(AclMode::CREATE_DB));
999    assert!(mz_acl.acl_mode.contains(AclMode::CREATE_CLUSTER));
1000    assert!(mz_acl.acl_mode.contains(AclMode::CREATE_NETWORK_POLICY));
1001    assert_eq!(s, mz_acl.to_string());
1002
1003    mz_ore::assert_err!("u42/rw=u666".parse::<MzAclItem>());
1004    mz_ore::assert_err!("u32=C/".parse::<MzAclItem>());
1005    mz_ore::assert_err!("=/".parse::<MzAclItem>());
1006    mz_ore::assert_err!("f62hfiuew827fhh".parse::<MzAclItem>());
1007    mz_ore::assert_err!("u2=rw/s66=CU/u33".parse::<MzAclItem>());
1008}
1009
1010#[mz_ore::test]
1011fn test_create_query_policy_privilege() {
1012    let privilege = AclMode::CREATE_QUERY_POLICY;
1013    assert_eq!(privilege.bits(), 1 << 28);
1014    assert_eq!(
1015        AclMode::parse_single_privilege(" createquerypolicy ").unwrap(),
1016        privilege
1017    );
1018    assert_eq!("Q".parse::<AclMode>().unwrap(), privilege);
1019    assert_eq!(privilege.to_string(), "Q");
1020    assert_eq!(privilege.explode(), vec!["CREATEQUERYPOLICY"]);
1021    let combined = privilege.union(AclMode::CREATE_NETWORK_POLICY);
1022    assert_eq!(
1023        AclMode::parse_multiple_privileges("CREATENETWORKPOLICY, CREATEQUERYPOLICY").unwrap(),
1024        combined
1025    );
1026    assert_eq!("PQ".parse::<AclMode>().unwrap(), combined);
1027    assert_eq!(combined.to_string(), "PQ");
1028    let item = "u1=PQ/u2".parse::<MzAclItem>().unwrap();
1029    assert_eq!(item.acl_mode, combined);
1030    assert_eq!(item.to_string(), "u1=PQ/u2");
1031}
1032
1033#[mz_ore::test]
1034fn test_mz_acl_item_binary() {
1035    use std::ops::BitAnd;
1036
1037    let mz_acl_item = MzAclItem {
1038        grantee: RoleId::User(42),
1039        grantor: RoleId::System(666),
1040        acl_mode: AclMode::empty()
1041            .bitand(AclMode::SELECT)
1042            .bitand(AclMode::UPDATE),
1043    };
1044    assert_eq!(
1045        mz_acl_item,
1046        MzAclItem::decode_binary(&mz_acl_item.encode_binary()).unwrap()
1047    );
1048
1049    let mz_acl_item = MzAclItem {
1050        grantee: RoleId::Public,
1051        grantor: RoleId::User(4),
1052        acl_mode: AclMode::empty()
1053            .bitand(AclMode::USAGE)
1054            .bitand(AclMode::CREATE),
1055    };
1056    assert_eq!(
1057        mz_acl_item,
1058        MzAclItem::decode_binary(&mz_acl_item.encode_binary()).unwrap()
1059    );
1060
1061    let mz_acl_item = MzAclItem {
1062        grantee: RoleId::System(7),
1063        grantor: RoleId::System(12),
1064        acl_mode: AclMode::empty(),
1065    };
1066    assert_eq!(
1067        mz_acl_item,
1068        MzAclItem::decode_binary(&mz_acl_item.encode_binary()).unwrap()
1069    );
1070
1071    let mz_acl_item = MzAclItem {
1072        grantee: RoleId::Public,
1073        grantor: RoleId::User(100),
1074        acl_mode: AclMode::empty(),
1075    };
1076    assert_eq!(
1077        mz_acl_item,
1078        MzAclItem::decode_binary(&mz_acl_item.encode_binary()).unwrap()
1079    );
1080
1081    mz_ore::assert_err!(MzAclItem::decode_binary(&[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]))
1082}
1083
1084#[mz_ore::test]
1085fn test_mz_acl_item_binary_size() {
1086    assert_eq!(26, MzAclItem::binary_size());
1087}
1088
1089#[mz_ore::test]
1090fn test_acl_mode_serde_and_debug() {
1091    let acl_mode = AclMode::INSERT | AclMode::SELECT;
1092    let json = serde_json::to_string(&acl_mode).unwrap();
1093    assert_eq!(json, r#"{"bits":3}"#);
1094    assert_eq!(serde_json::from_str::<AclMode>(&json).unwrap(), acl_mode);
1095
1096    assert_eq!(format!("{acl_mode:?}"), "INSERT | SELECT");
1097    assert_eq!(format!("{:?}", AclMode::empty()), "(empty)");
1098}
1099
1100#[mz_ore::test]
1101fn test_acl_parsing() {
1102    let s = "42=rw/666";
1103    let acl: AclItem = s.parse().unwrap();
1104    assert_eq!(42, acl.grantee.0);
1105    assert_eq!(666, acl.grantor.0);
1106    assert!(!acl.acl_mode.contains(AclMode::INSERT));
1107    assert!(acl.acl_mode.contains(AclMode::SELECT));
1108    assert!(acl.acl_mode.contains(AclMode::UPDATE));
1109    assert!(!acl.acl_mode.contains(AclMode::DELETE));
1110    assert!(!acl.acl_mode.contains(AclMode::USAGE));
1111    assert!(!acl.acl_mode.contains(AclMode::CREATE));
1112    assert!(!acl.acl_mode.contains(AclMode::CREATE_ROLE));
1113    assert!(!acl.acl_mode.contains(AclMode::CREATE_DB));
1114    assert!(!acl.acl_mode.contains(AclMode::CREATE_CLUSTER));
1115    assert!(!acl.acl_mode.contains(AclMode::CREATE_NETWORK_POLICY));
1116    assert_eq!(s, acl.to_string());
1117
1118    let s = "=UC/4";
1119    let acl: AclItem = s.parse().unwrap();
1120    assert_eq!(PUBLIC_ROLE_OID, acl.grantee);
1121    assert_eq!(4, acl.grantor.0);
1122    assert!(!acl.acl_mode.contains(AclMode::INSERT));
1123    assert!(!acl.acl_mode.contains(AclMode::SELECT));
1124    assert!(!acl.acl_mode.contains(AclMode::UPDATE));
1125    assert!(!acl.acl_mode.contains(AclMode::DELETE));
1126    assert!(acl.acl_mode.contains(AclMode::USAGE));
1127    assert!(acl.acl_mode.contains(AclMode::CREATE));
1128    assert!(!acl.acl_mode.contains(AclMode::CREATE_ROLE));
1129    assert!(!acl.acl_mode.contains(AclMode::CREATE_DB));
1130    assert!(!acl.acl_mode.contains(AclMode::CREATE_CLUSTER));
1131    assert!(!acl.acl_mode.contains(AclMode::CREATE_NETWORK_POLICY));
1132    assert_eq!(s, acl.to_string());
1133
1134    let s = "7=/12";
1135    let acl: AclItem = s.parse().unwrap();
1136    assert_eq!(7, acl.grantee.0);
1137    assert_eq!(12, acl.grantor.0);
1138    assert!(!acl.acl_mode.contains(AclMode::INSERT));
1139    assert!(!acl.acl_mode.contains(AclMode::SELECT));
1140    assert!(!acl.acl_mode.contains(AclMode::UPDATE));
1141    assert!(!acl.acl_mode.contains(AclMode::DELETE));
1142    assert!(!acl.acl_mode.contains(AclMode::USAGE));
1143    assert!(!acl.acl_mode.contains(AclMode::CREATE));
1144    assert!(!acl.acl_mode.contains(AclMode::CREATE_ROLE));
1145    assert!(!acl.acl_mode.contains(AclMode::CREATE_DB));
1146    assert!(!acl.acl_mode.contains(AclMode::CREATE_CLUSTER));
1147    assert!(!acl.acl_mode.contains(AclMode::CREATE_NETWORK_POLICY));
1148    assert_eq!(s, acl.to_string());
1149
1150    let s = "=/100";
1151    let acl: AclItem = s.parse().unwrap();
1152    assert_eq!(PUBLIC_ROLE_OID, acl.grantee);
1153    assert_eq!(100, acl.grantor.0);
1154    assert!(!acl.acl_mode.contains(AclMode::INSERT));
1155    assert!(!acl.acl_mode.contains(AclMode::SELECT));
1156    assert!(!acl.acl_mode.contains(AclMode::UPDATE));
1157    assert!(!acl.acl_mode.contains(AclMode::DELETE));
1158    assert!(!acl.acl_mode.contains(AclMode::USAGE));
1159    assert!(!acl.acl_mode.contains(AclMode::CREATE));
1160    assert!(!acl.acl_mode.contains(AclMode::CREATE_ROLE));
1161    assert!(!acl.acl_mode.contains(AclMode::CREATE_DB));
1162    assert!(!acl.acl_mode.contains(AclMode::CREATE_CLUSTER));
1163    assert!(!acl.acl_mode.contains(AclMode::CREATE_NETWORK_POLICY));
1164    assert_eq!(s, acl.to_string());
1165
1166    let s = "1=RBNP/2";
1167    let acl: AclItem = s.parse().unwrap();
1168    assert_eq!(1, acl.grantee.0);
1169    assert_eq!(2, acl.grantor.0);
1170    assert!(!acl.acl_mode.contains(AclMode::INSERT));
1171    assert!(!acl.acl_mode.contains(AclMode::SELECT));
1172    assert!(!acl.acl_mode.contains(AclMode::UPDATE));
1173    assert!(!acl.acl_mode.contains(AclMode::DELETE));
1174    assert!(!acl.acl_mode.contains(AclMode::USAGE));
1175    assert!(!acl.acl_mode.contains(AclMode::CREATE));
1176    assert!(acl.acl_mode.contains(AclMode::CREATE_ROLE));
1177    assert!(acl.acl_mode.contains(AclMode::CREATE_DB));
1178    assert!(acl.acl_mode.contains(AclMode::CREATE_CLUSTER));
1179    assert!(acl.acl_mode.contains(AclMode::CREATE_NETWORK_POLICY));
1180    assert_eq!(s, acl.to_string());
1181
1182    mz_ore::assert_err!("42/rw=666".parse::<AclItem>());
1183    mz_ore::assert_err!("u42=rw/u666".parse::<AclItem>());
1184    mz_ore::assert_err!("s42=rw/s666".parse::<AclItem>());
1185    mz_ore::assert_err!("u32=C/".parse::<AclItem>());
1186    mz_ore::assert_err!("=/".parse::<AclItem>());
1187    mz_ore::assert_err!("f62hfiuew827fhh".parse::<AclItem>());
1188    mz_ore::assert_err!("u2=rw/s66=CU/u33".parse::<AclItem>());
1189}
1190
1191#[mz_ore::test]
1192fn test_acl_item_binary() {
1193    use std::ops::BitAnd;
1194
1195    let acl_item = AclItem {
1196        grantee: Oid(42),
1197        grantor: Oid(666),
1198        acl_mode: AclMode::empty()
1199            .bitand(AclMode::SELECT)
1200            .bitand(AclMode::UPDATE),
1201    };
1202    assert_eq!(
1203        acl_item,
1204        AclItem::decode_binary(&acl_item.encode_binary()).unwrap()
1205    );
1206
1207    let acl_item = AclItem {
1208        grantee: PUBLIC_ROLE_OID,
1209        grantor: Oid(4),
1210        acl_mode: AclMode::empty()
1211            .bitand(AclMode::USAGE)
1212            .bitand(AclMode::CREATE),
1213    };
1214    assert_eq!(
1215        acl_item,
1216        AclItem::decode_binary(&acl_item.encode_binary()).unwrap()
1217    );
1218
1219    let acl_item = AclItem {
1220        grantee: Oid(7),
1221        grantor: Oid(12),
1222        acl_mode: AclMode::empty(),
1223    };
1224    assert_eq!(
1225        acl_item,
1226        AclItem::decode_binary(&acl_item.encode_binary()).unwrap()
1227    );
1228
1229    let acl_item = AclItem {
1230        grantee: PUBLIC_ROLE_OID,
1231        grantor: Oid(100),
1232        acl_mode: AclMode::empty(),
1233    };
1234    assert_eq!(
1235        acl_item,
1236        AclItem::decode_binary(&acl_item.encode_binary()).unwrap()
1237    );
1238
1239    mz_ore::assert_err!(AclItem::decode_binary(&[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]))
1240}
1241
1242#[mz_ore::test]
1243fn test_acl_item_binary_size() {
1244    assert_eq!(16, AclItem::binary_size());
1245}
1246
1247#[cfg(test)]
1248proptest! {
1249  #[mz_ore::test]
1250  #[cfg_attr(miri, ignore)] // slow
1251  fn proptest_acl_item_binary_encoding_roundtrip(acl_item: AclItem) {
1252      let encoded = acl_item.encode_binary();
1253      let decoded = AclItem::decode_binary(&encoded).unwrap();
1254      assert_eq!(acl_item, decoded);
1255  }
1256
1257  #[mz_ore::test]
1258  #[cfg_attr(miri, ignore)] // slow
1259  fn proptest_valid_acl_item_str(acl_item: AclItem) {
1260      let encoded = acl_item.to_string();
1261      let decoded = AclItem::from_str(&encoded).unwrap();
1262      assert_eq!(acl_item, decoded);
1263  }
1264}
1265
1266#[mz_ore::test]
1267#[cfg(any(test, feature = "proptest"))]
1268fn proptest_packed_acl_item_roundtrips() {
1269    fn roundtrip_acl_item(og: AclItem) {
1270        let packed = PackedAclItem::from_value(og);
1271        let rnd = packed.into_value();
1272        assert_eq!(og, rnd);
1273    }
1274
1275    proptest!(|(acl_item in proptest::arbitrary::any::<AclItem>())| {
1276        roundtrip_acl_item(acl_item);
1277    })
1278}
1279
1280#[mz_ore::test]
1281#[cfg_attr(miri, ignore)] // slow
1282#[cfg(any(test, feature = "proptest"))]
1283fn proptest_packed_acl_item_sorts() {
1284    fn sort_acl_items(mut og: Vec<AclItem>) {
1285        let mut packed: Vec<_> = og.iter().copied().map(PackedAclItem::from_value).collect();
1286
1287        og.sort();
1288        packed.sort();
1289
1290        let rnd: Vec<_> = packed.into_iter().map(PackedAclItem::into_value).collect();
1291        assert_eq!(og, rnd);
1292    }
1293
1294    proptest!(|(acl_items in proptest::collection::vec(any::<AclItem>(), 0..64))| {
1295        sort_acl_items(acl_items);
1296    });
1297}
1298
1299#[mz_ore::test]
1300#[cfg(any(test, feature = "proptest"))]
1301fn proptest_packed_mz_acl_item_roundtrips() {
1302    fn roundtrip_mz_acl_item(og: MzAclItem) {
1303        let packed = PackedMzAclItem::from_value(og);
1304        let rnd = packed.into_value();
1305        assert_eq!(og, rnd);
1306    }
1307
1308    proptest!(|(acl_item in proptest::arbitrary::any::<MzAclItem>())| {
1309        roundtrip_mz_acl_item(acl_item);
1310    })
1311}
1312
1313#[mz_ore::test]
1314#[cfg_attr(miri, ignore)] // slow
1315#[cfg(any(test, feature = "proptest"))]
1316fn proptest_packed_mz_acl_item_sorts() {
1317    fn sort_mz_acl_items(mut og: Vec<MzAclItem>) {
1318        let mut packed: Vec<_> = og
1319            .iter()
1320            .copied()
1321            .map(PackedMzAclItem::from_value)
1322            .collect();
1323
1324        og.sort();
1325        packed.sort();
1326
1327        let rnd: Vec<_> = packed
1328            .into_iter()
1329            .map(PackedMzAclItem::into_value)
1330            .collect();
1331        assert_eq!(og, rnd);
1332    }
1333
1334    proptest!(|(acl_items in proptest::collection::vec(any::<MzAclItem>(), 0..64))| {
1335        sort_mz_acl_items(acl_items);
1336    });
1337}