gatekeep 2.0.1

Code-first authorization engine for Rust
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
use std::fmt;

use serde::{Deserialize, Deserializer, Serialize, Serializer};
use thiserror::Error;
use time::{OffsetDateTime, UtcOffset};

/// Result type used by gatekeep constructors and validators.
pub type GatekeepResult<T> = Result<T, GatekeepError>;

/// Validation errors returned by typed gatekeep records.
#[derive(Debug, Error, Clone, PartialEq, Eq)]
pub enum GatekeepError {
    /// Identifier input was empty or whitespace only.
    #[error("{field} must not be empty")]
    EmptyIdentifier {
        /// Name of the identifier field that failed validation.
        field: &'static str,
    },
    /// An identifier uses a prefix reserved for imported legacy identities.
    #[error("{field} uses the reserved prefix {prefix:?}")]
    ReservedIdentifierPrefix {
        /// Name of the identifier field that failed validation.
        field: &'static str,
        /// Prefix reserved for migration identities.
        prefix: &'static str,
    },
    /// Locale input was not a simple BCP 47-style tag.
    #[error("invalid locale tag: {value}")]
    InvalidLocale {
        /// Rejected locale value.
        value: String,
    },
    /// A legacy decision identity was missing the migration namespace.
    #[error("invalid imported legacy decision audit id: {value}")]
    InvalidLegacyIdentifier {
        /// Rejected imported identity.
        value: String,
    },
    /// A policy model record failed structural validation.
    #[error("policy record is invalid: {reason}")]
    InvalidPolicyRecord {
        /// Static validation reason.
        reason: &'static str,
    },
}

fn validate_identifier(field: &'static str, value: impl Into<String>) -> GatekeepResult<String> {
    let value = value.into();
    if value.trim().is_empty() {
        Err(GatekeepError::EmptyIdentifier { field })
    } else if field == "decision_audit_id" && value.starts_with("legacy-") {
        Err(GatekeepError::ReservedIdentifierPrefix {
            field,
            prefix: "legacy-",
        })
    } else {
        Ok(value)
    }
}

fn validate_locale(value: impl Into<String>) -> GatekeepResult<String> {
    let value = value.into();
    let valid = !value.trim().is_empty()
        && value
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-');
    if valid {
        Ok(value)
    } else {
        Err(GatekeepError::InvalidLocale { value })
    }
}

macro_rules! owned_id {
    ($name:ident, $field:literal) => {
        /// Owned gatekeep identifier.
        #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
        pub struct $name(String);

        impl $name {
            /// Creates a validated identifier.
            ///
            /// # Errors
            ///
            /// Returns [`GatekeepError::EmptyIdentifier`] when `value` is empty
            /// or contains only whitespace.
            pub fn new(value: impl Into<String>) -> GatekeepResult<Self> {
                validate_identifier($field, value).map(Self)
            }

            #[allow(dead_code)]
            pub(crate) fn from_trusted(value: impl Into<String>) -> Self {
                Self(value.into())
            }

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

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

        impl Serialize for $name {
            fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
            where
                S: Serializer,
            {
                self.0.serialize(serializer)
            }
        }

        impl<'de> Deserialize<'de> for $name {
            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
            where
                D: Deserializer<'de>,
            {
                let value = String::deserialize(deserializer)?;
                Self::new(value).map_err(serde::de::Error::custom)
            }
        }
    };
}

macro_rules! static_id {
    ($name:ident, $owned:ident) => {
        /// Static gatekeep identifier.
        #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
        pub struct $name(&'static str);

        impl $name {
            /// Creates a compile-time validated static identifier.
            #[must_use]
            pub const fn new(value: &'static str) -> Self {
                assert_valid_static_id(value);
                Self(value)
            }

            /// Returns the identifier string.
            #[must_use]
            pub const fn as_str(self) -> &'static str {
                self.0
            }

            /// Converts this static identifier into its owned form.
            ///
            /// # Errors
            ///
            /// Returns [`GatekeepError::EmptyIdentifier`] if the static and
            /// owned identifier validation rules have drifted apart.
            pub fn to_owned_id(self) -> GatekeepResult<$owned> {
                $owned::new(self.0)
            }
        }
    };
}

const fn assert_valid_static_id(value: &str) {
    let bytes = value.as_bytes();
    assert!(!bytes.is_empty(), "static identity must not be empty");
    let mut index = 0;
    let mut has_non_whitespace = false;
    while index < bytes.len() {
        let byte = bytes[index];
        if !(byte == b' ' || byte == b'\n' || byte == b'\r' || byte == b'\t') {
            has_non_whitespace = true;
        }
        index += 1;
    }
    assert!(has_non_whitespace, "static identity must not be whitespace");
}

owned_id!(FactId, "fact_id");
owned_id!(ClauseLabel, "clause_label");
owned_id!(ObligationId, "obligation_id");
owned_id!(ParamKey, "param_key");
owned_id!(PolicyHash, "policy_hash");
owned_id!(PolicyId, "policy_id");
owned_id!(ReasonCode, "reason_code");
owned_id!(RequestId, "request_id");
owned_id!(DecisionAuditId, "decision_audit_id");
owned_id!(SubjectSlot, "subject_slot");
owned_id!(TenantId, "tenant_id");

impl DecisionAuditId {
    /// Generates a new sortable identifier for one decision occurrence.
    ///
    /// Generate this once at the authorization or application orchestration
    /// boundary and retain it when the owning operation is retried. The
    /// identifier is a domain identity, not a database row id.
    #[must_use]
    pub fn generate() -> Self {
        Self::from_trusted(uuid::Uuid::now_v7().to_string())
    }

    /// Constructs an identity while importing a legacy decision audit record.
    ///
    /// The `legacy-` namespace is reserved so ordinary new decision identities
    /// cannot collide with imported history. This escape hatch is intentionally
    /// named for migration code; new decisions must use [`Self::new`] or
    /// [`Self::generate`].
    ///
    /// # Errors
    ///
    /// Returns [`GatekeepError::InvalidLegacyIdentifier`] unless `value` has
    /// the exact, case-sensitive `legacy-` prefix and a non-empty suffix.
    pub fn from_legacy_import(value: impl Into<String>) -> GatekeepResult<Self> {
        let value = value.into();
        if value
            .strip_prefix("legacy-")
            .is_some_and(|suffix| !suffix.is_empty())
        {
            Ok(Self::from_trusted(value))
        } else {
            Err(GatekeepError::InvalidLegacyIdentifier { value })
        }
    }
}

/// The stable identity and authoritative occurrence time for one decision.
///
/// Applications may construct and retain this value at their authorization
/// orchestration boundary. Reusing it for an ambiguous retry keeps both the
/// `CloudEvents` identity and the serialized occurrence time unchanged.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct DecisionAuditOccurrence {
    /// Stable identity of the decision occurrence.
    pub decision_audit_id: DecisionAuditId,
    /// Occurrence time normalized to UTC at exact microsecond precision.
    pub occurred_at: OffsetDateTime,
}

impl DecisionAuditOccurrence {
    /// Validates and normalizes a decision occurrence for Dovecote storage.
    ///
    /// Dovecote's portable instant range starts at the Unix epoch and ends at
    /// the final microsecond of 9999-12-31. Sub-microsecond values are
    /// truncated once, before serialization, so a retry cannot silently
    /// change the durable event bytes.
    ///
    /// # Errors
    ///
    /// Returns [`DecisionAuditOccurrenceError`] when the time is outside the
    /// portable range.
    pub fn new(
        decision_audit_id: DecisionAuditId,
        occurred_at: OffsetDateTime,
    ) -> Result<Self, DecisionAuditOccurrenceError> {
        const MAX_PORTABLE_UNIX_SECONDS: i64 = 253_402_300_799;
        if decision_audit_id.as_str().starts_with("legacy-") {
            return Err(DecisionAuditOccurrenceError::ReservedLegacyIdentity);
        }

        let seconds = occurred_at.unix_timestamp();
        if !(0..=MAX_PORTABLE_UNIX_SECONDS).contains(&seconds) {
            return Err(DecisionAuditOccurrenceError::OutOfRange);
        }

        let nanosecond = occurred_at.nanosecond();
        let normalized_nanosecond = nanosecond - (nanosecond % 1_000);
        if seconds == MAX_PORTABLE_UNIX_SECONDS && normalized_nanosecond > 999_999_000 {
            return Err(DecisionAuditOccurrenceError::OutOfRange);
        }

        let normalized = occurred_at
            .replace_nanosecond(normalized_nanosecond)
            .map_err(|_| DecisionAuditOccurrenceError::OutOfRange)?;

        Ok(Self {
            decision_audit_id,
            occurred_at: normalized.to_offset(UtcOffset::UTC),
        })
    }
}

/// Validation failure for a decision occurrence crossing the SQL audit
/// boundary.
#[derive(Clone, Debug, Error, PartialEq, Eq)]
pub enum DecisionAuditOccurrenceError {
    /// Imported legacy identities cannot be used for new occurrences.
    #[error("legacy decision identities are valid only while importing history")]
    ReservedLegacyIdentity,
    /// The occurrence is outside Dovecote's portable instant range.
    #[error("decision occurrence is outside Dovecote's portable instant range")]
    OutOfRange,
}

static_id!(StaticFactId, FactId);
static_id!(StaticClauseLabel, ClauseLabel);
static_id!(StaticObligationId, ObligationId);
static_id!(StaticParamKey, ParamKey);
static_id!(StaticReasonCode, ReasonCode);
static_id!(StaticRequestId, RequestId);
static_id!(StaticSubjectSlot, SubjectSlot);
static_id!(StaticTenantId, TenantId);

#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
/// Language or locale tag used by human-facing reason text.
pub struct Locale(String);

impl Locale {
    /// Creates a locale tag from non-empty ASCII alphanumeric and `-` input.
    ///
    /// # Errors
    ///
    /// Returns [`GatekeepError::InvalidLocale`] when `value` is empty or
    /// contains unsupported characters.
    pub fn new(value: impl Into<String>) -> GatekeepResult<Self> {
        validate_locale(value).map(Self)
    }

    /// Returns the locale tag.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl Serialize for Locale {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        self.0.serialize(serializer)
    }
}

impl<'de> Deserialize<'de> for Locale {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value = String::deserialize(deserializer)?;
        Self::new(value).map_err(serde::de::Error::custom)
    }
}

/// Marker trait for compile-time known facts.
pub trait Fact {
    /// Stable fact identifier.
    const ID: StaticFactId;
}

/// Marker trait for compile-time known obligations.
pub trait ObligationSpec {
    /// Stable obligation identifier.
    const ID: StaticObligationId;
}

/// Application-owned subject reference.
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct SubjectRef {
    /// Subject namespace, such as `user` or `team`.
    kind: String,
    /// Subject identifier inside the namespace.
    id: String,
}

impl SubjectRef {
    /// Creates a validated subject reference.
    ///
    /// # Errors
    ///
    /// Returns [`GatekeepError::EmptyIdentifier`] when either component is
    /// empty or contains only whitespace.
    pub fn new(kind: impl Into<String>, id: impl Into<String>) -> GatekeepResult<Self> {
        Ok(Self {
            kind: validate_identifier("subject_kind", kind)?,
            id: validate_identifier("subject_id", id)?,
        })
    }

    /// Returns the subject namespace.
    #[must_use]
    pub fn kind(&self) -> &str {
        &self.kind
    }

    /// Returns the subject identifier inside its namespace.
    #[must_use]
    pub fn id(&self) -> &str {
        &self.id
    }
}

impl<'de> Deserialize<'de> for SubjectRef {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        #[derive(Deserialize)]
        struct SubjectRefRecord {
            kind: String,
            id: String,
        }

        let record = SubjectRefRecord::deserialize(deserializer)?;
        Self::new(record.kind, record.id).map_err(serde::de::Error::custom)
    }
}