simple-zanzibar 0.3.0

A simplified Rust implementation of Google's Zanzibar authorization system with DSL support
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
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
//! Validated domain primitives for the local Zanzibar engine.

use std::{fmt, str::FromStr};

use crate::model::{Object, Relation, RelationTuple, User};

const MAX_TYPE_BYTES: usize = 64;
const MAX_RELATION_BYTES: usize = 64;
const MAX_ID_BYTES: usize = 256;
const MAX_RELATIONSHIP_BYTES: usize = 768;
const LEGACY_USER_SUBJECT_TYPE: &str = "user";

/// Identifies a kind of validated domain identifier.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IdentifierKind {
    /// Object type, also called namespace in the legacy model.
    ObjectType,
    /// Object identifier inside an object type.
    ObjectId,
    /// Relation or permission name.
    RelationName,
    /// Subject type for direct users.
    SubjectType,
    /// Subject identifier inside a subject type.
    SubjectId,
}

impl fmt::Display for IdentifierKind {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::ObjectType => formatter.write_str("object type"),
            Self::ObjectId => formatter.write_str("object id"),
            Self::RelationName => formatter.write_str("relation name"),
            Self::SubjectType => formatter.write_str("subject type"),
            Self::SubjectId => formatter.write_str("subject id"),
        }
    }
}

/// Errors produced while validating domain primitives.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum DomainError {
    /// An identifier exceeds the configured byte cap.
    #[error("identifier {kind} exceeds {max_bytes} bytes")]
    IdentifierTooLong {
        /// Identifier category.
        kind: IdentifierKind,
        /// Maximum accepted byte length.
        max_bytes: usize,
    },

    /// An identifier is empty.
    #[error("identifier {kind} must not be empty")]
    EmptyIdentifier {
        /// Identifier category.
        kind: IdentifierKind,
    },

    /// An identifier contains a byte outside its allowlist.
    #[error("identifier {kind} contains invalid byte at offset {offset}")]
    InvalidIdentifierByte {
        /// Identifier category.
        kind: IdentifierKind,
        /// Byte offset of the rejected input byte.
        offset: usize,
    },

    /// A relationship string does not match the accepted grammar.
    #[error("relationship is malformed: {reason}")]
    MalformedRelationship {
        /// Static parse failure reason.
        reason: &'static str,
    },
}

macro_rules! validated_identifier {
    ($name:ident, $kind:expr, $max:expr, $validator:ident) => {
        #[doc = concat!("Validated ", stringify!($name), " domain primitive.")]
        #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
        pub struct $name(String);

        impl $name {
            #[doc = concat!("Creates a validated ", stringify!($name), ".")]
            ///
            /// # Errors
            ///
            /// Returns [`DomainError`] when the value is empty, too long, or contains bytes outside
            /// the identifier allowlist.
            pub fn new(value: impl Into<String>) -> Result<Self, DomainError> {
                let value = value.into();
                $validator($kind, &value, $max)?;
                Ok(Self(value))
            }

            /// Returns the validated identifier as a string slice.
            #[must_use]
            pub fn as_str(&self) -> &str {
                &self.0
            }
        }

        impl fmt::Display for $name {
            fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
                formatter.write_str(&self.0)
            }
        }

        impl FromStr for $name {
            type Err = DomainError;

            fn from_str(value: &str) -> Result<Self, Self::Err> {
                Self::new(value)
            }
        }

        impl TryFrom<&str> for $name {
            type Error = DomainError;

            fn try_from(value: &str) -> Result<Self, Self::Error> {
                Self::new(value)
            }
        }

        impl TryFrom<String> for $name {
            type Error = DomainError;

            fn try_from(value: String) -> Result<Self, Self::Error> {
                Self::new(value)
            }
        }

        #[cfg(feature = "serde")]
        impl serde::Serialize for $name {
            fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
            where
                S: serde::Serializer,
            {
                serializer.serialize_str(self.as_str())
            }
        }

        #[cfg(feature = "serde")]
        impl<'de> serde::Deserialize<'de> for $name {
            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
            where
                D: serde::Deserializer<'de>,
            {
                let value = <String as serde::Deserialize>::deserialize(deserializer)?;
                Self::try_from(value).map_err(serde::de::Error::custom)
            }
        }
    };
}

validated_identifier!(
    ObjectType,
    IdentifierKind::ObjectType,
    MAX_TYPE_BYTES,
    validate_type_identifier
);
validated_identifier!(
    ObjectId,
    IdentifierKind::ObjectId,
    MAX_ID_BYTES,
    validate_id_identifier
);
validated_identifier!(
    RelationName,
    IdentifierKind::RelationName,
    MAX_RELATION_BYTES,
    validate_type_identifier
);
validated_identifier!(
    SubjectType,
    IdentifierKind::SubjectType,
    MAX_TYPE_BYTES,
    validate_type_identifier
);
validated_identifier!(
    SubjectId,
    IdentifierKind::SubjectId,
    MAX_ID_BYTES,
    validate_id_identifier
);

/// A validated object reference.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct ObjectRef {
    object_type: ObjectType,
    object_id: ObjectId,
}

impl ObjectRef {
    /// Creates a validated object reference.
    #[must_use]
    pub fn new(object_type: ObjectType, object_id: ObjectId) -> Self {
        Self {
            object_type,
            object_id,
        }
    }

    /// Returns the object type.
    #[must_use]
    pub fn object_type(&self) -> &ObjectType {
        &self.object_type
    }

    /// Returns the object identifier.
    #[must_use]
    pub fn object_id(&self) -> &ObjectId {
        &self.object_id
    }
}

impl fmt::Display for ObjectRef {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "{}:{}", self.object_type, self.object_id)
    }
}

impl FromStr for ObjectRef {
    type Err = DomainError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        let (object_type, object_id) = split_once(value, ':', "object reference must contain ':'")?;
        Ok(Self::new(
            ObjectType::try_from(object_type)?,
            ObjectId::try_from(object_id)?,
        ))
    }
}

#[cfg(feature = "serde")]
impl serde::Serialize for ObjectRef {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_str(&self.to_string())
    }
}

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for ObjectRef {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let value = <String as serde::Deserialize>::deserialize(deserializer)?;
        Self::from_str(&value).map_err(serde::de::Error::custom)
    }
}

impl TryFrom<&Object> for ObjectRef {
    type Error = DomainError;

    fn try_from(value: &Object) -> Result<Self, Self::Error> {
        Ok(Self::new(
            ObjectType::try_from(value.namespace.as_str())?,
            ObjectId::try_from(value.id.as_str())?,
        ))
    }
}

/// A validated subject reference.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum SubjectRef {
    /// A direct subject object, usually `user:<id>`.
    Object(ObjectRef),
    /// A userset subject such as `group:eng#member`.
    Userset {
        /// Userset object.
        object: ObjectRef,
        /// Userset relation.
        relation: RelationName,
    },
}

impl fmt::Display for SubjectRef {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Object(object) => write!(formatter, "{object}"),
            Self::Userset { object, relation } => write!(formatter, "{object}#{relation}"),
        }
    }
}

impl FromStr for SubjectRef {
    type Err = DomainError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        match value.split_once('#') {
            Some((object, relation)) => Ok(Self::Userset {
                object: object.parse()?,
                relation: RelationName::try_from(relation)?,
            }),
            None => Ok(Self::Object(parse_subject_object(value)?)),
        }
    }
}

#[cfg(feature = "serde")]
impl serde::Serialize for SubjectRef {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_str(&self.to_string())
    }
}

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for SubjectRef {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let value = <String as serde::Deserialize>::deserialize(deserializer)?;
        Self::from_str(&value).map_err(serde::de::Error::custom)
    }
}

impl TryFrom<&User> for SubjectRef {
    type Error = DomainError;

    fn try_from(value: &User) -> Result<Self, Self::Error> {
        match value {
            User::UserId(id) => Ok(Self::Object(ObjectRef::new(
                ObjectType::try_from(LEGACY_USER_SUBJECT_TYPE)?,
                ObjectId::try_from(id.as_str())?,
            ))),
            User::Userset(object, relation) => Ok(Self::Userset {
                object: ObjectRef::try_from(object)?,
                relation: RelationName::try_from(relation.0.as_str())?,
            }),
        }
    }
}

/// A validated relationship tuple.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Relationship {
    resource: ObjectRef,
    relation: RelationName,
    subject: SubjectRef,
}

impl Relationship {
    /// Creates a validated relationship from already validated parts.
    #[must_use]
    pub fn new(resource: ObjectRef, relation: RelationName, subject: SubjectRef) -> Self {
        Self {
            resource,
            relation,
            subject,
        }
    }

    /// Returns the relationship resource object.
    #[must_use]
    pub fn resource(&self) -> &ObjectRef {
        &self.resource
    }

    /// Returns the relationship relation.
    #[must_use]
    pub fn relation(&self) -> &RelationName {
        &self.relation
    }

    /// Returns the relationship subject.
    #[must_use]
    pub fn subject(&self) -> &SubjectRef {
        &self.subject
    }
}

impl fmt::Display for Relationship {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            formatter,
            "{}#{}@{}",
            self.resource, self.relation, self.subject
        )
    }
}

impl FromStr for Relationship {
    type Err = DomainError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        if value.len() > MAX_RELATIONSHIP_BYTES {
            return Err(DomainError::IdentifierTooLong {
                kind: IdentifierKind::ObjectId,
                max_bytes: MAX_RELATIONSHIP_BYTES,
            });
        }

        let (resource, subject) =
            split_once(value, '@', "relationship must contain one '@' separator")?;
        if subject.contains('@') {
            return Err(DomainError::MalformedRelationship {
                reason: "relationship must contain one '@' separator",
            });
        }

        let (object, relation) =
            split_once(resource, '#', "relationship resource must contain '#'")?;
        if relation.contains('#') {
            return Err(DomainError::MalformedRelationship {
                reason: "relationship resource must contain one '#'",
            });
        }

        Ok(Self::new(
            object.parse()?,
            RelationName::try_from(relation)?,
            subject.parse()?,
        ))
    }
}

#[cfg(feature = "serde")]
impl serde::Serialize for Relationship {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_str(&self.to_string())
    }
}

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for Relationship {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let value = <String as serde::Deserialize>::deserialize(deserializer)?;
        Self::from_str(&value).map_err(serde::de::Error::custom)
    }
}

impl TryFrom<&RelationTuple> for Relationship {
    type Error = DomainError;

    fn try_from(value: &RelationTuple) -> Result<Self, Self::Error> {
        Ok(Self::new(
            ObjectRef::try_from(&value.object)?,
            RelationName::try_from(value.relation.0.as_str())?,
            SubjectRef::try_from(&value.user)?,
        ))
    }
}

fn parse_subject_object(value: &str) -> Result<ObjectRef, DomainError> {
    let (subject_type, subject_id) = split_once(value, ':', "subject reference must contain ':'")?;
    Ok(ObjectRef::new(
        ObjectType::new(SubjectType::try_from(subject_type)?.as_str())?,
        ObjectId::new(SubjectId::try_from(subject_id)?.as_str())?,
    ))
}

fn split_once<'a>(
    value: &'a str,
    delimiter: char,
    missing_reason: &'static str,
) -> Result<(&'a str, &'a str), DomainError> {
    let (left, right) = value
        .split_once(delimiter)
        .ok_or(DomainError::MalformedRelationship {
            reason: missing_reason,
        })?;
    if left.is_empty() || right.is_empty() {
        return Err(DomainError::MalformedRelationship {
            reason: missing_reason,
        });
    }
    Ok((left, right))
}

fn validate_type_identifier(
    kind: IdentifierKind,
    value: &str,
    max_bytes: usize,
) -> Result<(), DomainError> {
    if value.is_empty() {
        return Err(DomainError::EmptyIdentifier { kind });
    }
    if value.len() > max_bytes {
        return Err(DomainError::IdentifierTooLong { kind, max_bytes });
    }

    for (offset, byte) in value.bytes().enumerate() {
        let valid = if offset == 0 {
            byte.is_ascii_alphabetic()
        } else {
            byte.is_ascii_alphanumeric() || byte == b'_'
        };
        if !valid {
            return Err(DomainError::InvalidIdentifierByte { kind, offset });
        }
    }

    Ok(())
}

fn validate_id_identifier(
    kind: IdentifierKind,
    value: &str,
    max_bytes: usize,
) -> Result<(), DomainError> {
    if value.is_empty() {
        return Err(DomainError::EmptyIdentifier { kind });
    }
    if value.len() > max_bytes {
        return Err(DomainError::IdentifierTooLong { kind, max_bytes });
    }

    for (offset, byte) in value.bytes().enumerate() {
        let valid = byte.is_ascii_graphic()
            && !matches!(byte, b'#' | b'@' | b':' | b'/' | b'\\')
            && !byte.is_ascii_whitespace();
        if !valid {
            return Err(DomainError::InvalidIdentifierByte { kind, offset });
        }
    }

    Ok(())
}

impl TryFrom<&Relation> for RelationName {
    type Error = DomainError;

    fn try_from(value: &Relation) -> Result<Self, Self::Error> {
        Self::try_from(value.0.as_str())
    }
}

impl From<&ObjectType> for SubjectType {
    fn from(value: &ObjectType) -> Self {
        Self(value.0.clone())
    }
}

impl From<&ObjectId> for SubjectId {
    fn from(value: &ObjectId) -> Self {
        Self(value.0.clone())
    }
}