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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
// Copyright Materialize, Inc. and contributors. All rights reserved.
//
// Use of this software is governed by the Business Source License
// included in the LICENSE file.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0.

//! A Materialize specific access control list abstract data type.

use std::collections::BTreeMap;
use std::fmt;
use std::mem::size_of;
use std::ops::BitOrAssign;
use std::str::FromStr;

use crate::adt::system::Oid;
use anyhow::{anyhow, Error};
use bitflags::bitflags;
use columnation::{Columnation, CopyRegion};
use mz_ore::str::StrExt;
use mz_proto::{RustType, TryFromProtoError};
use proptest::arbitrary::Arbitrary;
use proptest::proptest;
use proptest::strategy::{BoxedStrategy, Strategy};
use proptest_derive::Arbitrary;
use serde::{Deserialize, Serialize};

use crate::role_id::RoleId;

include!(concat!(env!("OUT_DIR"), "/mz_repr.adt.mz_acl_item.rs"));

// Append
const INSERT_CHAR: char = 'a';
// Read
const SELECT_CHAR: char = 'r';
// Write
const UPDATE_CHAR: char = 'w';
// Delete
const DELETE_CHAR: char = 'd';
// Usage
const USAGE_CHAR: char = 'U';
// Create
const CREATE_CHAR: char = 'C';
// Role
const CREATE_ROLE_CHAR: char = 'R';
// dataBase
const CREATE_DB_CHAR: char = 'B';
// compute Node
const CREATE_CLUSTER_CHAR: char = 'N';

const INSERT_STR: &str = "INSERT";
const SELECT_STR: &str = "SELECT";
const UPDATE_STR: &str = "UPDATE";
const DELETE_STR: &str = "DELETE";
const USAGE_STR: &str = "USAGE";
const CREATE_STR: &str = "CREATE";
const CREATE_ROLE_STR: &str = "CREATEROLE";
const CREATE_DB_STR: &str = "CREATEDB";
const CREATE_CLUSTER_STR: &str = "CREATECLUSTER";

/// The OID used to represent the PUBLIC role. See:
/// <https://github.com/postgres/postgres/blob/29a0ccbce97978e5d65b8f96c85a00611bb403c4/src/include/utils/acl.h#L46>
pub const PUBLIC_ROLE_OID: Oid = Oid(0);

bitflags! {
    /// A bit flag representing all the privileges that can be granted to a role.
    ///
    /// Modeled after:
    /// https://github.com/postgres/postgres/blob/7f5b19817eaf38e70ad1153db4e644ee9456853e/src/include/nodes/parsenodes.h#L74-L101
    ///
    /// The lower 32 bits are used for different privilege types.
    ///
    /// The upper 32 bits indicate a grant option on the privilege for the current bit shifted
    /// right by 32 bits (Currently unimplemented in Materialize).
    ///
    /// Privileges that exist in Materialize but not PostgreSQL start at the highest available bit
    /// and move down towards the PostgreSQL compatible bits. This is try to avoid collisions with
    /// privileges that PostgreSQL may add in the future.
    #[derive(Serialize, Deserialize)]
    pub struct AclMode: u64 {
        // PostgreSQL compatible privileges.
        const INSERT = 1 << 0;
        const SELECT = 1 << 1;
        const UPDATE = 1 << 2;
        const DELETE = 1 << 3;
        const USAGE = 1 << 8;
        const CREATE = 1 << 9;

        // Materialize custom privileges.
        const CREATE_CLUSTER = 1 << 29;
        const CREATE_DB = 1 << 30;
        const CREATE_ROLE = 1 << 31;

        // No additional privileges should be defined at a bit larger than 1 << 31. Those bits are
        // reserved for grant options.
    }
}

impl AclMode {
    pub fn parse_single_privilege(s: &str) -> Result<Self, Error> {
        match s.trim().to_uppercase().as_str() {
            INSERT_STR => Ok(AclMode::INSERT),
            SELECT_STR => Ok(AclMode::SELECT),
            UPDATE_STR => Ok(AclMode::UPDATE),
            DELETE_STR => Ok(AclMode::DELETE),
            USAGE_STR => Ok(AclMode::USAGE),
            CREATE_STR => Ok(AclMode::CREATE),
            CREATE_ROLE_STR => Ok(AclMode::CREATE_ROLE),
            CREATE_DB_STR => Ok(AclMode::CREATE_DB),
            CREATE_CLUSTER_STR => Ok(AclMode::CREATE_CLUSTER),
            _ => Err(anyhow!("{}", s.quoted())),
        }
    }

    pub fn parse_multiple_privileges(s: &str) -> Result<Self, Error> {
        let mut acl_mode = AclMode::empty();
        for privilege in s.split(',') {
            let privilege = AclMode::parse_single_privilege(privilege)?;
            acl_mode.bitor_assign(privilege);
        }
        Ok(acl_mode)
    }

    pub fn to_error_string(&self) -> String {
        self.explode().join(", ")
    }

    pub fn explode(&self) -> Vec<&'static str> {
        let mut privileges = Vec::new();
        if self.contains(AclMode::SELECT) {
            privileges.push(SELECT_STR);
        }
        if self.contains(AclMode::INSERT) {
            privileges.push(INSERT_STR);
        }
        if self.contains(AclMode::UPDATE) {
            privileges.push(UPDATE_STR);
        }
        if self.contains(AclMode::DELETE) {
            privileges.push(DELETE_STR);
        }
        if self.contains(AclMode::USAGE) {
            privileges.push(USAGE_STR);
        }
        if self.contains(AclMode::CREATE) {
            privileges.push(CREATE_STR);
        }
        if self.contains(AclMode::CREATE_ROLE) {
            privileges.push(CREATE_ROLE_STR);
        }
        if self.contains(AclMode::CREATE_DB) {
            privileges.push(CREATE_DB_STR);
        }
        if self.contains(AclMode::CREATE_CLUSTER) {
            privileges.push(CREATE_CLUSTER_STR);
        }
        privileges
    }
}

impl FromStr for AclMode {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut acl_mode = AclMode::empty();
        for c in s.chars() {
            match c {
                INSERT_CHAR => acl_mode.bitor_assign(AclMode::INSERT),
                SELECT_CHAR => acl_mode.bitor_assign(AclMode::SELECT),
                UPDATE_CHAR => acl_mode.bitor_assign(AclMode::UPDATE),
                DELETE_CHAR => acl_mode.bitor_assign(AclMode::DELETE),
                USAGE_CHAR => acl_mode.bitor_assign(AclMode::USAGE),
                CREATE_CHAR => acl_mode.bitor_assign(AclMode::CREATE),
                CREATE_ROLE_CHAR => acl_mode.bitor_assign(AclMode::CREATE_ROLE),
                CREATE_DB_CHAR => acl_mode.bitor_assign(AclMode::CREATE_DB),
                CREATE_CLUSTER_CHAR => acl_mode.bitor_assign(AclMode::CREATE_CLUSTER),
                _ => return Err(anyhow!("invalid privilege '{c}' in acl mode '{s}'")),
            }
        }
        Ok(acl_mode)
    }
}

impl fmt::Display for AclMode {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        // The order of each flag matches PostgreSQL, which uses the same order that they're
        // defined in.
        if self.contains(AclMode::INSERT) {
            write!(f, "{INSERT_CHAR}")?;
        }
        if self.contains(AclMode::SELECT) {
            write!(f, "{SELECT_CHAR}")?;
        }
        if self.contains(AclMode::UPDATE) {
            write!(f, "{UPDATE_CHAR}")?;
        }
        if self.contains(AclMode::DELETE) {
            write!(f, "{DELETE_CHAR}")?;
        }
        if self.contains(AclMode::USAGE) {
            write!(f, "{USAGE_CHAR}")?;
        }
        if self.contains(AclMode::CREATE) {
            write!(f, "{CREATE_CHAR}")?;
        }
        if self.contains(AclMode::CREATE_ROLE) {
            write!(f, "{CREATE_ROLE_CHAR}")?;
        }
        if self.contains(AclMode::CREATE_DB) {
            write!(f, "{CREATE_DB_CHAR}")?;
        }
        if self.contains(AclMode::CREATE_CLUSTER) {
            write!(f, "{CREATE_CLUSTER_CHAR}")?;
        }
        Ok(())
    }
}

impl RustType<ProtoAclMode> for AclMode {
    fn into_proto(&self) -> ProtoAclMode {
        ProtoAclMode {
            acl_mode: self.bits,
        }
    }

    fn from_proto(proto: ProtoAclMode) -> Result<Self, TryFromProtoError> {
        Ok(AclMode {
            bits: proto.acl_mode,
        })
    }
}

impl Columnation for AclMode {
    type InnerRegion = CopyRegion<AclMode>;
}

impl Arbitrary for AclMode {
    type Parameters = ();
    type Strategy = BoxedStrategy<AclMode>;

    fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {
        proptest::bits::BitSetStrategy::masked(AclMode::all().bits)
            .prop_map(|bits| AclMode::from_bits(bits).expect("invalid proptest implementation"))
            .boxed()
    }
}

/// A list of privileges granted to a role in Materialize.
///
/// This is modelled after the AclItem type in PostgreSQL, but the OIDs are replaced with RoleIds
/// because we don't use OID as persistent identifiers for roles.
///
/// See: <https://github.com/postgres/postgres/blob/7f5b19817eaf38e70ad1153db4e644ee9456853e/src/include/utils/acl.h#L48-L59>
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Hash, Deserialize, Arbitrary,
)]
pub struct MzAclItem {
    /// Role that this item grants privileges to.
    pub grantee: RoleId,
    /// Grantor of privileges.
    pub grantor: RoleId,
    /// Privileges bit flag.
    pub acl_mode: AclMode,
}

impl MzAclItem {
    pub fn empty(grantee: RoleId, grantor: RoleId) -> MzAclItem {
        MzAclItem {
            grantee,
            grantor,
            acl_mode: AclMode::empty(),
        }
    }

    pub fn encode_binary(&self) -> Vec<u8> {
        let mut res = Vec::with_capacity(Self::binary_size());
        res.extend_from_slice(&self.grantee.encode_binary());
        res.extend_from_slice(&self.grantor.encode_binary());
        res.extend_from_slice(&self.acl_mode.bits().to_le_bytes());
        res
    }

    pub fn decode_binary(raw: &[u8]) -> Result<MzAclItem, Error> {
        if raw.len() != MzAclItem::binary_size() {
            return Err(anyhow!(
                "invalid binary size, expecting {}, found {}",
                MzAclItem::binary_size(),
                raw.len()
            ));
        }

        let role_id_size = RoleId::binary_size();

        let grantee = RoleId::decode_binary(&raw[0..role_id_size])?;
        let raw = &raw[role_id_size..];
        let grantor = RoleId::decode_binary(&raw[0..role_id_size])?;
        let raw = &raw[role_id_size..];
        let acl_mode = u64::from_le_bytes(raw.try_into()?);

        Ok(MzAclItem {
            grantee,
            grantor,
            acl_mode: AclMode { bits: acl_mode },
        })
    }

    pub const fn binary_size() -> usize {
        RoleId::binary_size() + RoleId::binary_size() + size_of::<u64>()
    }
}

impl FromStr for MzAclItem {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let parts: Vec<_> = s.split('=').collect();
        let &[grantee, rest] = parts.as_slice() else {
            return Err(anyhow!("invalid mz_aclitem '{s}'"));
        };

        let parts: Vec<_> = rest.split('/').collect();
        let &[acl_mode, grantor] = parts.as_slice() else {
            return Err(anyhow!("invalid mz_aclitem '{s}'"));
        };

        let grantee: RoleId = if grantee.is_empty() {
            RoleId::Public
        } else {
            grantee.parse()?
        };
        let acl_mode: AclMode = acl_mode.parse()?;
        let grantor: RoleId = grantor.parse()?;

        Ok(MzAclItem {
            grantee,
            grantor,
            acl_mode,
        })
    }
}

impl fmt::Display for MzAclItem {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if !self.grantee.is_public() {
            write!(f, "{}", self.grantee)?;
        }
        write!(f, "={}/{}", self.acl_mode, self.grantor)
    }
}

impl RustType<ProtoMzAclItem> for MzAclItem {
    fn into_proto(&self) -> ProtoMzAclItem {
        ProtoMzAclItem {
            grantee: Some(self.grantee.into_proto()),
            grantor: Some(self.grantor.into_proto()),
            acl_mode: Some(self.acl_mode.into_proto()),
        }
    }

    fn from_proto(proto: ProtoMzAclItem) -> Result<Self, TryFromProtoError> {
        match (proto.grantee, proto.grantor, proto.acl_mode) {
            (Some(grantee), Some(grantor), Some(acl_mode)) => Ok(MzAclItem {
                grantee: RoleId::from_proto(grantee)?,
                grantor: RoleId::from_proto(grantor)?,
                acl_mode: AclMode::from_proto(acl_mode)?,
            }),
            (None, _, _) => Err(TryFromProtoError::missing_field("ProtoMzAclItem::grantee")),
            (_, None, _) => Err(TryFromProtoError::missing_field("ProtoMzAclItem::grantor")),
            (_, _, None) => Err(TryFromProtoError::missing_field("ProtoMzAclItem::acl_mode")),
        }
    }
}

impl Columnation for MzAclItem {
    type InnerRegion = CopyRegion<MzAclItem>;
}

/// A list of privileges granted to a role.
///
/// This is primarily used for compatibility in PostgreSQL.
///
/// See: <https://github.com/postgres/postgres/blob/7f5b19817eaf38e70ad1153db4e644ee9456853e/src/include/utils/acl.h#L48-L59>
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Hash, Deserialize, Arbitrary,
)]
pub struct AclItem {
    /// Role that this item grants privileges to.
    pub grantee: Oid,
    /// Grantor of privileges.
    pub grantor: Oid,
    /// Privileges bit flag.
    pub acl_mode: AclMode,
}

impl AclItem {
    pub fn empty(grantee: Oid, grantor: Oid) -> AclItem {
        AclItem {
            grantee,
            grantor,
            acl_mode: AclMode::empty(),
        }
    }
}

// PostgreSQL has no stable binary encoding for AclItems. However, we need to be able to convert
// types to and from binary, to pack a Datum in a row, so we invent our own encoding. The encoding
// matches the in memory format that PostgreSQL uses, which is (Oid, Oid, AclMode).
impl AclItem {
    pub fn encode_binary(&self) -> Vec<u8> {
        let mut res = Vec::with_capacity(Self::binary_size());
        res.extend_from_slice(&self.grantee.0.to_le_bytes());
        res.extend_from_slice(&self.grantor.0.to_le_bytes());
        res.extend_from_slice(&self.acl_mode.bits().to_le_bytes());
        res
    }

    pub fn decode_binary(raw: &[u8]) -> Result<AclItem, Error> {
        if raw.len() != AclItem::binary_size() {
            return Err(anyhow!(
                "invalid binary size, expecting {}, found {}",
                AclItem::binary_size(),
                raw.len()
            ));
        }

        let oid_size = size_of::<u32>();

        let grantee = Oid(u32::from_le_bytes(raw[0..oid_size].try_into()?));
        let raw = &raw[oid_size..];
        let grantor = Oid(u32::from_le_bytes(raw[0..oid_size].try_into()?));
        let raw = &raw[oid_size..];
        let acl_mode = u64::from_le_bytes(raw.try_into()?);

        Ok(AclItem {
            grantee,
            grantor,
            acl_mode: AclMode { bits: acl_mode },
        })
    }

    pub const fn binary_size() -> usize {
        size_of::<u32>() + size_of::<u32>() + size_of::<u64>()
    }
}

impl FromStr for AclItem {
    type Err = Error;

    /// For the PostgreSQL implementation see:
    ///   * <https://github.com/postgres/postgres/blob/9089287aa037fdecb5a52cec1926e5ae9569e9f9/src/backend/utils/adt/acl.c#L580-L609>
    ///   * <https://github.com/postgres/postgres/blob/9089287aa037fdecb5a52cec1926e5ae9569e9f9/src/backend/utils/adt/acl.c#L223-L390>
    ///   * <https://github.com/postgres/postgres/blob/9089287aa037fdecb5a52cec1926e5ae9569e9f9/src/backend/utils/adt/acl.c#L127-L187>
    ///
    /// PostgreSQL is able to look up OIDs in the catalog while parsing, so it accepts aclitems that
    /// contain role OIDs or role names. We have no way to access the catalog here, so we can only
    /// accept oids. Therefore our implementation is much simpler than PostgreSQL's.
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let parts: Vec<_> = s.split('=').collect();
        let &[grantee, rest] = parts.as_slice() else {
            return Err(anyhow!("invalid aclitem '{s}'"));
        };

        let parts: Vec<_> = rest.split('/').collect();
        let &[acl_mode, grantor] = parts.as_slice() else {
            return Err(anyhow!("invalid mz_aclitem '{s}'"));
        };

        let grantee: Oid = if grantee.is_empty() {
            PUBLIC_ROLE_OID
        } else {
            Oid(grantee.parse()?)
        };
        let acl_mode: AclMode = acl_mode.parse()?;
        let grantor: Oid = Oid(grantor.parse()?);

        Ok(AclItem {
            grantee,
            grantor,
            acl_mode,
        })
    }
}

impl fmt::Display for AclItem {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if self.grantee != PUBLIC_ROLE_OID {
            write!(f, "{}", self.grantee.0)?;
        }
        write!(f, "={}/{}", self.acl_mode, self.grantor.0)
    }
}

impl RustType<ProtoAclItem> for AclItem {
    fn into_proto(&self) -> ProtoAclItem {
        ProtoAclItem {
            grantee: self.grantee.0,
            grantor: self.grantor.0,
            acl_mode: Some(self.acl_mode.into_proto()),
        }
    }

    fn from_proto(proto: ProtoAclItem) -> Result<Self, TryFromProtoError> {
        match proto.acl_mode {
            Some(acl_mode) => Ok(AclItem {
                grantee: Oid(proto.grantee),
                grantor: Oid(proto.grantor),
                acl_mode: AclMode::from_proto(acl_mode)?,
            }),
            None => Err(TryFromProtoError::missing_field("ProtoMzAclItem::acl_mode")),
        }
    }
}

impl Columnation for AclItem {
    type InnerRegion = CopyRegion<AclItem>;
}

/// A container of [`MzAclItem`]s that is optimized to look up an [`MzAclItem`] by the grantee.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Serialize)]
pub struct PrivilegeMap(
    #[serde(serialize_with = "mz_ore::serde::map_key_to_string")] BTreeMap<RoleId, Vec<MzAclItem>>,
);

impl PrivilegeMap {
    /// Creates a new empty `PrivilegeMap`.
    pub fn new() -> PrivilegeMap {
        PrivilegeMap(BTreeMap::new())
    }

    /// Creates a new `PrivilegeMap` from a collection of [`MzAclItem`]s.
    pub fn from_mz_acl_items(items: impl IntoIterator<Item = MzAclItem>) -> PrivilegeMap {
        let mut map = PrivilegeMap::new();
        map.grant_all(items);
        map
    }

    /// Get the acl item granted to `grantee` by `grantor`.
    pub fn get_acl_item(&self, grantee: &RoleId, grantor: &RoleId) -> Option<&MzAclItem> {
        self.0.get(grantee).and_then(|privileges| {
            privileges
                .into_iter()
                .find(|mz_acl_item| &mz_acl_item.grantor == grantor)
        })
    }

    /// Get all acl items granted to `grantee`.
    pub fn get_acl_items_for_grantee(&self, grantee: &RoleId) -> impl Iterator<Item = &MzAclItem> {
        self.0
            .get(grantee)
            .into_iter()
            .flat_map(|privileges| privileges.into_iter())
    }

    /// Returns references to all contained [`MzAclItem`].
    pub fn all_values(&self) -> impl Iterator<Item = &MzAclItem> {
        self.0
            .values()
            .flat_map(|privileges| privileges.into_iter())
    }

    /// Returns clones of all contained [`MzAclItem`].
    pub fn all_values_owned(&self) -> impl Iterator<Item = MzAclItem> + '_ {
        self.all_values().cloned()
    }

    /// Consumes self and returns all contained [`MzAclItem`].
    pub fn into_all_values(self) -> impl Iterator<Item = MzAclItem> {
        self.0
            .into_values()
            .flat_map(|privileges| privileges.into_iter())
    }

    /// Adds an [`MzAclItem`] to this map.
    pub fn grant(&mut self, privilege: MzAclItem) {
        let grantee_privileges = self.0.entry(privilege.grantee).or_default();
        if let Some(existing_privilege) = grantee_privileges
            .iter_mut()
            .find(|cur_privilege| cur_privilege.grantor == privilege.grantor)
        {
            // sanity check that the key is consistent.
            assert_eq!(
                privilege.grantee, existing_privilege.grantee,
                "PrivilegeMap out of sync"
            );
            existing_privilege.acl_mode = existing_privilege.acl_mode.union(privilege.acl_mode);
        } else {
            grantee_privileges.push(privilege);
        }
    }

    /// Grant multiple [`MzAclItem`]s to this map.
    pub fn grant_all(&mut self, mz_acl_items: impl IntoIterator<Item = MzAclItem>) {
        for mz_acl_item in mz_acl_items {
            self.grant(mz_acl_item);
        }
    }

    /// Removes an [`MzAclItem`] from this map.
    pub fn revoke(&mut self, privilege: &MzAclItem) {
        let grantee_privileges = self.0.entry(privilege.grantee).or_default();
        if let Some(existing_privilege) = grantee_privileges
            .iter_mut()
            .find(|cur_privilege| cur_privilege.grantor == privilege.grantor)
        {
            // sanity check that the key is consistent.
            assert_eq!(
                privilege.grantee, existing_privilege.grantee,
                "PrivilegeMap out of sync"
            );
            existing_privilege.acl_mode =
                existing_privilege.acl_mode.difference(privilege.acl_mode);
        }

        // Remove empty privileges.
        grantee_privileges.retain(|privilege| !privilege.acl_mode.is_empty());
        if grantee_privileges.is_empty() {
            self.0.remove(&privilege.grantee);
        }
    }

    /// Returns a `PrivilegeMap` formatted as a `serde_json::Value` that is suitable for debugging. For
    /// example `CatalogState::dump`.
    pub fn debug_json(&self) -> serde_json::Value {
        let privileges_by_str: BTreeMap<String, _> = self
            .0
            .iter()
            .map(|(key, value)| (key.to_string(), value))
            .collect();
        serde_json::json!(privileges_by_str)
    }
}

impl Default for PrivilegeMap {
    fn default() -> PrivilegeMap {
        PrivilegeMap::new()
    }
}

/// Combines all [`MzAclItem`]s that have the same grantee and grantor.
pub fn merge_mz_acl_items(
    mz_acl_items: impl Iterator<Item = MzAclItem>,
) -> impl Iterator<Item = MzAclItem> {
    mz_acl_items
        .fold(BTreeMap::new(), |mut accum, mz_acl_item| {
            let item = accum
                .entry((mz_acl_item.grantee, mz_acl_item.grantor))
                .or_insert(MzAclItem::empty(mz_acl_item.grantee, mz_acl_item.grantor));
            item.acl_mode |= mz_acl_item.acl_mode;
            accum
        })
        .into_values()
}

#[mz_ore::test]
fn test_mz_acl_parsing() {
    let s = "u42=rw/s666";
    let mz_acl: MzAclItem = s.parse().unwrap();
    assert_eq!(RoleId::User(42), mz_acl.grantee);
    assert_eq!(RoleId::System(666), mz_acl.grantor);
    assert!(!mz_acl.acl_mode.contains(AclMode::INSERT));
    assert!(mz_acl.acl_mode.contains(AclMode::SELECT));
    assert!(mz_acl.acl_mode.contains(AclMode::UPDATE));
    assert!(!mz_acl.acl_mode.contains(AclMode::DELETE));
    assert!(!mz_acl.acl_mode.contains(AclMode::USAGE));
    assert!(!mz_acl.acl_mode.contains(AclMode::CREATE));
    assert!(!mz_acl.acl_mode.contains(AclMode::CREATE_ROLE));
    assert!(!mz_acl.acl_mode.contains(AclMode::CREATE_DB));
    assert!(!mz_acl.acl_mode.contains(AclMode::CREATE_CLUSTER));
    assert_eq!(s, mz_acl.to_string());

    let s = "=UC/u4";
    let mz_acl: MzAclItem = s.parse().unwrap();
    assert_eq!(RoleId::Public, mz_acl.grantee);
    assert_eq!(RoleId::User(4), mz_acl.grantor);
    assert!(!mz_acl.acl_mode.contains(AclMode::INSERT));
    assert!(!mz_acl.acl_mode.contains(AclMode::SELECT));
    assert!(!mz_acl.acl_mode.contains(AclMode::UPDATE));
    assert!(!mz_acl.acl_mode.contains(AclMode::DELETE));
    assert!(mz_acl.acl_mode.contains(AclMode::USAGE));
    assert!(mz_acl.acl_mode.contains(AclMode::CREATE));
    assert!(!mz_acl.acl_mode.contains(AclMode::CREATE_ROLE));
    assert!(!mz_acl.acl_mode.contains(AclMode::CREATE_DB));
    assert!(!mz_acl.acl_mode.contains(AclMode::CREATE_CLUSTER));
    assert_eq!(s, mz_acl.to_string());

    let s = "s7=/s12";
    let mz_acl: MzAclItem = s.parse().unwrap();
    assert_eq!(RoleId::System(7), mz_acl.grantee);
    assert_eq!(RoleId::System(12), mz_acl.grantor);
    assert!(!mz_acl.acl_mode.contains(AclMode::INSERT));
    assert!(!mz_acl.acl_mode.contains(AclMode::SELECT));
    assert!(!mz_acl.acl_mode.contains(AclMode::UPDATE));
    assert!(!mz_acl.acl_mode.contains(AclMode::DELETE));
    assert!(!mz_acl.acl_mode.contains(AclMode::USAGE));
    assert!(!mz_acl.acl_mode.contains(AclMode::CREATE));
    assert!(!mz_acl.acl_mode.contains(AclMode::CREATE_ROLE));
    assert!(!mz_acl.acl_mode.contains(AclMode::CREATE_DB));
    assert!(!mz_acl.acl_mode.contains(AclMode::CREATE_CLUSTER));
    assert_eq!(s, mz_acl.to_string());

    let s = "=/u100";
    let mz_acl: MzAclItem = s.parse().unwrap();
    assert_eq!(RoleId::Public, mz_acl.grantee);
    assert_eq!(RoleId::User(100), mz_acl.grantor);
    assert!(!mz_acl.acl_mode.contains(AclMode::INSERT));
    assert!(!mz_acl.acl_mode.contains(AclMode::SELECT));
    assert!(!mz_acl.acl_mode.contains(AclMode::UPDATE));
    assert!(!mz_acl.acl_mode.contains(AclMode::DELETE));
    assert!(!mz_acl.acl_mode.contains(AclMode::USAGE));
    assert!(!mz_acl.acl_mode.contains(AclMode::CREATE));
    assert!(!mz_acl.acl_mode.contains(AclMode::CREATE_ROLE));
    assert!(!mz_acl.acl_mode.contains(AclMode::CREATE_DB));
    assert!(!mz_acl.acl_mode.contains(AclMode::CREATE_CLUSTER));
    assert_eq!(s, mz_acl.to_string());

    let s = "u1=RBN/u2";
    let mz_acl: MzAclItem = s.parse().unwrap();
    assert_eq!(RoleId::User(1), mz_acl.grantee);
    assert_eq!(RoleId::User(2), mz_acl.grantor);
    assert!(!mz_acl.acl_mode.contains(AclMode::INSERT));
    assert!(!mz_acl.acl_mode.contains(AclMode::SELECT));
    assert!(!mz_acl.acl_mode.contains(AclMode::UPDATE));
    assert!(!mz_acl.acl_mode.contains(AclMode::DELETE));
    assert!(!mz_acl.acl_mode.contains(AclMode::USAGE));
    assert!(!mz_acl.acl_mode.contains(AclMode::CREATE));
    assert!(mz_acl.acl_mode.contains(AclMode::CREATE_ROLE));
    assert!(mz_acl.acl_mode.contains(AclMode::CREATE_DB));
    assert!(mz_acl.acl_mode.contains(AclMode::CREATE_CLUSTER));
    assert_eq!(s, mz_acl.to_string());

    assert!("u42/rw=u666".parse::<MzAclItem>().is_err());
    assert!("u32=C/".parse::<MzAclItem>().is_err());
    assert!("=/".parse::<MzAclItem>().is_err());
    assert!("f62hfiuew827fhh".parse::<MzAclItem>().is_err());
    assert!("u2=rw/s66=CU/u33".parse::<MzAclItem>().is_err());
}

#[mz_ore::test]
fn test_mz_acl_item_binary() {
    use std::ops::BitAnd;

    let mz_acl_item = MzAclItem {
        grantee: RoleId::User(42),
        grantor: RoleId::System(666),
        acl_mode: AclMode::empty()
            .bitand(AclMode::SELECT)
            .bitand(AclMode::UPDATE),
    };
    assert_eq!(
        mz_acl_item,
        MzAclItem::decode_binary(&mz_acl_item.encode_binary()).unwrap()
    );

    let mz_acl_item = MzAclItem {
        grantee: RoleId::Public,
        grantor: RoleId::User(4),
        acl_mode: AclMode::empty()
            .bitand(AclMode::USAGE)
            .bitand(AclMode::CREATE),
    };
    assert_eq!(
        mz_acl_item,
        MzAclItem::decode_binary(&mz_acl_item.encode_binary()).unwrap()
    );

    let mz_acl_item = MzAclItem {
        grantee: RoleId::System(7),
        grantor: RoleId::System(12),
        acl_mode: AclMode::empty(),
    };
    assert_eq!(
        mz_acl_item,
        MzAclItem::decode_binary(&mz_acl_item.encode_binary()).unwrap()
    );

    let mz_acl_item = MzAclItem {
        grantee: RoleId::Public,
        grantor: RoleId::User(100),
        acl_mode: AclMode::empty(),
    };
    assert_eq!(
        mz_acl_item,
        MzAclItem::decode_binary(&mz_acl_item.encode_binary()).unwrap()
    );

    assert!(MzAclItem::decode_binary(&[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]).is_err())
}

#[mz_ore::test]
fn test_mz_acl_item_binary_size() {
    assert_eq!(26, MzAclItem::binary_size());
}

#[mz_ore::test]
fn test_acl_parsing() {
    let s = "42=rw/666";
    let acl: AclItem = s.parse().unwrap();
    assert_eq!(42, acl.grantee.0);
    assert_eq!(666, acl.grantor.0);
    assert!(!acl.acl_mode.contains(AclMode::INSERT));
    assert!(acl.acl_mode.contains(AclMode::SELECT));
    assert!(acl.acl_mode.contains(AclMode::UPDATE));
    assert!(!acl.acl_mode.contains(AclMode::DELETE));
    assert!(!acl.acl_mode.contains(AclMode::USAGE));
    assert!(!acl.acl_mode.contains(AclMode::CREATE));
    assert!(!acl.acl_mode.contains(AclMode::CREATE_ROLE));
    assert!(!acl.acl_mode.contains(AclMode::CREATE_DB));
    assert!(!acl.acl_mode.contains(AclMode::CREATE_CLUSTER));
    assert_eq!(s, acl.to_string());

    let s = "=UC/4";
    let acl: AclItem = s.parse().unwrap();
    assert_eq!(PUBLIC_ROLE_OID, acl.grantee);
    assert_eq!(4, acl.grantor.0);
    assert!(!acl.acl_mode.contains(AclMode::INSERT));
    assert!(!acl.acl_mode.contains(AclMode::SELECT));
    assert!(!acl.acl_mode.contains(AclMode::UPDATE));
    assert!(!acl.acl_mode.contains(AclMode::DELETE));
    assert!(acl.acl_mode.contains(AclMode::USAGE));
    assert!(acl.acl_mode.contains(AclMode::CREATE));
    assert!(!acl.acl_mode.contains(AclMode::CREATE_ROLE));
    assert!(!acl.acl_mode.contains(AclMode::CREATE_DB));
    assert!(!acl.acl_mode.contains(AclMode::CREATE_CLUSTER));
    assert_eq!(s, acl.to_string());

    let s = "7=/12";
    let acl: AclItem = s.parse().unwrap();
    assert_eq!(7, acl.grantee.0);
    assert_eq!(12, acl.grantor.0);
    assert!(!acl.acl_mode.contains(AclMode::INSERT));
    assert!(!acl.acl_mode.contains(AclMode::SELECT));
    assert!(!acl.acl_mode.contains(AclMode::UPDATE));
    assert!(!acl.acl_mode.contains(AclMode::DELETE));
    assert!(!acl.acl_mode.contains(AclMode::USAGE));
    assert!(!acl.acl_mode.contains(AclMode::CREATE));
    assert!(!acl.acl_mode.contains(AclMode::CREATE_ROLE));
    assert!(!acl.acl_mode.contains(AclMode::CREATE_DB));
    assert!(!acl.acl_mode.contains(AclMode::CREATE_CLUSTER));
    assert_eq!(s, acl.to_string());

    let s = "=/100";
    let acl: AclItem = s.parse().unwrap();
    assert_eq!(PUBLIC_ROLE_OID, acl.grantee);
    assert_eq!(100, acl.grantor.0);
    assert!(!acl.acl_mode.contains(AclMode::INSERT));
    assert!(!acl.acl_mode.contains(AclMode::SELECT));
    assert!(!acl.acl_mode.contains(AclMode::UPDATE));
    assert!(!acl.acl_mode.contains(AclMode::DELETE));
    assert!(!acl.acl_mode.contains(AclMode::USAGE));
    assert!(!acl.acl_mode.contains(AclMode::CREATE));
    assert!(!acl.acl_mode.contains(AclMode::CREATE_ROLE));
    assert!(!acl.acl_mode.contains(AclMode::CREATE_DB));
    assert!(!acl.acl_mode.contains(AclMode::CREATE_CLUSTER));
    assert_eq!(s, acl.to_string());

    let s = "1=RBN/2";
    let acl: AclItem = s.parse().unwrap();
    assert_eq!(1, acl.grantee.0);
    assert_eq!(2, acl.grantor.0);
    assert!(!acl.acl_mode.contains(AclMode::INSERT));
    assert!(!acl.acl_mode.contains(AclMode::SELECT));
    assert!(!acl.acl_mode.contains(AclMode::UPDATE));
    assert!(!acl.acl_mode.contains(AclMode::DELETE));
    assert!(!acl.acl_mode.contains(AclMode::USAGE));
    assert!(!acl.acl_mode.contains(AclMode::CREATE));
    assert!(acl.acl_mode.contains(AclMode::CREATE_ROLE));
    assert!(acl.acl_mode.contains(AclMode::CREATE_DB));
    assert!(acl.acl_mode.contains(AclMode::CREATE_CLUSTER));
    assert_eq!(s, acl.to_string());

    assert!("42/rw=666".parse::<AclItem>().is_err());
    assert!("u42=rw/u666".parse::<AclItem>().is_err());
    assert!("s42=rw/s666".parse::<AclItem>().is_err());
    assert!("u32=C/".parse::<AclItem>().is_err());
    assert!("=/".parse::<AclItem>().is_err());
    assert!("f62hfiuew827fhh".parse::<AclItem>().is_err());
    assert!("u2=rw/s66=CU/u33".parse::<AclItem>().is_err());
}

#[mz_ore::test]
fn test_acl_item_binary() {
    use std::ops::BitAnd;

    let acl_item = AclItem {
        grantee: Oid(42),
        grantor: Oid(666),
        acl_mode: AclMode::empty()
            .bitand(AclMode::SELECT)
            .bitand(AclMode::UPDATE),
    };
    assert_eq!(
        acl_item,
        AclItem::decode_binary(&acl_item.encode_binary()).unwrap()
    );

    let acl_item = AclItem {
        grantee: PUBLIC_ROLE_OID,
        grantor: Oid(4),
        acl_mode: AclMode::empty()
            .bitand(AclMode::USAGE)
            .bitand(AclMode::CREATE),
    };
    assert_eq!(
        acl_item,
        AclItem::decode_binary(&acl_item.encode_binary()).unwrap()
    );

    let acl_item = AclItem {
        grantee: Oid(7),
        grantor: Oid(12),
        acl_mode: AclMode::empty(),
    };
    assert_eq!(
        acl_item,
        AclItem::decode_binary(&acl_item.encode_binary()).unwrap()
    );

    let acl_item = AclItem {
        grantee: PUBLIC_ROLE_OID,
        grantor: Oid(100),
        acl_mode: AclMode::empty(),
    };
    assert_eq!(
        acl_item,
        AclItem::decode_binary(&acl_item.encode_binary()).unwrap()
    );

    assert!(AclItem::decode_binary(&[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]).is_err())
}

#[mz_ore::test]
fn test_acl_item_binary_size() {
    assert_eq!(16, AclItem::binary_size());
}

proptest! {
  #[mz_ore::test]
  #[cfg_attr(miri, ignore)] // slow
  fn proptest_acl_item_binary_encoding_roundtrip(acl_item: AclItem) {
      let encoded = acl_item.encode_binary();
      let decoded = AclItem::decode_binary(&encoded).unwrap();
      assert_eq!(acl_item, decoded);
  }

  #[mz_ore::test]
  #[cfg_attr(miri, ignore)] // slow
  fn proptest_valid_acl_item_str(acl_item: AclItem) {
      let encoded = acl_item.to_string();
      let decoded = AclItem::from_str(&encoded).unwrap();
      assert_eq!(acl_item, decoded);
  }
}