skilj-core 0.2.0

The engine behind skilj: event storage, DCB consistency checks, projections and the plugin API for event and command types. Most applications use it through the skilj crate.
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
//! The access trail (docs/architecture.md ยง229, `rule RecordAccessEvent`,
//! `rule CapabilityHistory`): every change to who holds what in a bounded
//! context is also an event in the `admin` bounded context, written in the
//! same transaction as the change, so "could this grant read X on that
//! date" is answered from stored facts instead of from rows that only say
//! what is true now.
//!
//! This module is the pure half: the eight event types, how an event is
//! built from a change, and the fold behind `capabilityHistory`. The
//! transaction that writes them is `db::record_access_event` and the
//! `*_with_trail` functions around it.
//!
//! Payloads carry ids only (the Role, the bounded context, the acting
//! Role), never a name or an `external_subject`, so nothing here is
//! personal data a person could ask to have forgotten. `scope` is the one
//! free-form value, an opaque string the grant itself already stores.

use crate::access_control::AccessLevel;
use crate::bootstrap::ADMIN_BOUNDED_CONTEXT_NAME;
use crate::event_store::{BoundedContext, Event, EventOrigin, EventType};
use crate::shared::{Metadata, Tag, TagMapping};
use chrono::{DateTime, Utc};
use serde_json::{json, Value};
use std::collections::BTreeSet;

/// `access_event_type_names` in the spec: the eight event types SkilJ
/// registers in the admin bounded context itself. The first six are the
/// history of a `RoleAccessMapping` ([`AccessEventKind::is_mapping_event`]);
/// the last two record a Role sharing the private fields of its records
/// with another.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum AccessEventKind {
    /// A `RoleAccessMapping` was made.
    AccessGranted,
    /// One ended, because the mapping or its Role was revoked.
    AccessRevoked,
    /// A capability was added to a grant.
    CapabilityGranted,
    /// A capability was removed from a grant.
    CapabilityRevoked,
    /// A grant's delegable set was replaced.
    DelegableCapabilitiesSet,
    /// What an existing, active grant held when the trail began.
    AccessBaselined,
    /// A Role let another read the private fields of one record, or of all
    /// its records (`PrivateFieldGrant`). `role_id` is the grantee and
    /// `actor_role_id` the grantor.
    PrivateFieldAccessGranted,
    /// The grantor ended such a grant.
    PrivateFieldAccessRevoked,
}

impl AccessEventKind {
    /// Every kind, in the order they are registered.
    pub const ALL: [AccessEventKind; 8] = [
        AccessEventKind::AccessGranted,
        AccessEventKind::AccessRevoked,
        AccessEventKind::CapabilityGranted,
        AccessEventKind::CapabilityRevoked,
        AccessEventKind::DelegableCapabilitiesSet,
        AccessEventKind::AccessBaselined,
        AccessEventKind::PrivateFieldAccessGranted,
        AccessEventKind::PrivateFieldAccessRevoked,
    ];

    /// Whether the kind belongs to a `RoleAccessMapping`'s history, which
    /// [`fold_access_events`] folds. A private-field grant is not part of
    /// it: it names no mapping, and must not make a grant look known.
    pub fn is_mapping_event(self) -> bool {
        !matches!(
            self,
            AccessEventKind::PrivateFieldAccessGranted | AccessEventKind::PrivateFieldAccessRevoked
        )
    }

    /// The event type's name in the admin bounded context.
    pub fn name(self) -> &'static str {
        match self {
            AccessEventKind::AccessGranted => "AccessGranted",
            AccessEventKind::AccessRevoked => "AccessRevoked",
            AccessEventKind::CapabilityGranted => "CapabilityGranted",
            AccessEventKind::CapabilityRevoked => "CapabilityRevoked",
            AccessEventKind::DelegableCapabilitiesSet => "DelegableCapabilitiesSet",
            AccessEventKind::AccessBaselined => "AccessBaselined",
            AccessEventKind::PrivateFieldAccessGranted => "PrivateFieldAccessGranted",
            AccessEventKind::PrivateFieldAccessRevoked => "PrivateFieldAccessRevoked",
        }
    }

    /// The kind an event type name stands for, or `None` for any other name.
    pub fn from_name(name: &str) -> Option<AccessEventKind> {
        Self::ALL.into_iter().find(|kind| kind.name() == name)
    }

    /// The payload fields beyond `role_id` and `bounded_context`, as
    /// `(name, JSON Schema type, required)`.
    fn extra_fields(self) -> &'static [(&'static str, &'static str, bool)] {
        match self {
            AccessEventKind::AccessGranted => &[
                ("actor_role_id", "string", false),
                ("level", "string", true),
                ("can_read_sensitive", "boolean", true),
                ("scope", "string", false),
                ("capabilities", "array", false),
                ("delegable", "array", false),
            ],
            AccessEventKind::AccessRevoked => &[
                ("actor_role_id", "string", false),
                ("reason", "string", true),
            ],
            AccessEventKind::CapabilityGranted | AccessEventKind::CapabilityRevoked => &[
                ("actor_role_id", "string", false),
                ("capability", "string", true),
                ("via", "string", true),
            ],
            AccessEventKind::DelegableCapabilitiesSet => &[
                ("actor_role_id", "string", false),
                ("delegable", "array", true),
            ],
            AccessEventKind::AccessBaselined => &[
                ("actor_role_id", "string", false),
                ("level", "string", true),
                ("can_read_sensitive", "boolean", true),
                ("scope", "string", false),
                ("capabilities", "array", true),
                ("delegable", "array", true),
            ],
            AccessEventKind::PrivateFieldAccessGranted => &[
                ("actor_role_id", "string", false),
                ("grant_id", "string", true),
                ("event_sequence", "integer", false),
                ("command_id", "string", false),
            ],
            AccessEventKind::PrivateFieldAccessRevoked => &[
                ("actor_role_id", "string", false),
                ("grant_id", "string", true),
                ("reason", "string", false),
            ],
        }
    }
}

/// `access_event_schema(name)`: the JSON Schema of the kind's payload.
pub fn access_event_schema(kind: AccessEventKind) -> String {
    let mut properties = serde_json::Map::new();
    let mut required = vec![json!("role_id"), json!("bounded_context")];
    properties.insert("role_id".into(), json!({ "type": "string" }));
    properties.insert("bounded_context".into(), json!({ "type": "string" }));
    for (name, ty, is_required) in kind.extra_fields() {
        let property = if *ty == "array" {
            json!({ "type": "array", "items": { "type": "string" } })
        } else if !*is_required {
            json!({ "type": [ty, "null"] })
        } else {
            json!({ "type": ty })
        };
        properties.insert((*name).into(), property);
        if *is_required {
            required.push(json!(name));
        }
    }
    json!({
        "type": "object",
        "properties": properties,
        "required": required,
    })
    .to_string()
}

/// The event type as registered in the admin bounded context: tagged by
/// `role` and `bounded_context`, creatable by nobody but the library.
pub fn access_event_type(admin: &BoundedContext, kind: AccessEventKind) -> EventType {
    EventType {
        bounded_context: admin.clone(),
        name: kind.name().to_string(),
        schema: access_event_schema(kind),
        schema_version: 1,
        tag_mappings: vec![
            TagMapping::new("role", "role_id"),
            TagMapping::new("bounded_context", "bounded_context"),
        ],
        owner_tag_key: None,
        sensitive_fields: Vec::new(),
        private_fields: Vec::new(),
        external_creation_allowed: false,
        direct_creation_allowed: false,
        system_triggered_allowed: false,
        system_triggered_schedule: None,
        missed_occurrence_policy: None,
        schedule_position: None,
        last_fired_at: None,
        event_read_allowed: false,
    }
}

/// `level` as the payload spells it.
pub fn level_str(level: AccessLevel) -> &'static str {
    match level {
        AccessLevel::Read => "read",
        AccessLevel::Write => "write",
        AccessLevel::Admin => "admin",
    }
}

/// What a change is about, and the kind-specific payload fields.
/// `actor_role_id` is the Role that made the change, `None` for a
/// baseline or a change no Role made (local mode's seed grant).
pub struct AccessChange {
    /// Which event this is.
    pub kind: AccessEventKind,
    /// The Role whose grant changed.
    pub role_id: String,
    /// The bounded context the grant is in.
    pub bounded_context: String,
    /// The Role that made the change.
    pub actor_role_id: Option<String>,
    /// The kind-specific fields (see [`AccessEventKind`]).
    pub details: serde_json::Map<String, Value>,
}

impl AccessChange {
    /// `AccessGranted`: `mapping` as it is made. Its capabilities and
    /// delegable set are recorded too, since the fold starts both from the
    /// event (a grant made with none records empty sets).
    pub fn granted(
        mapping: &crate::access_control::RoleAccessMapping,
        actor_role_id: Option<&str>,
    ) -> Self {
        Self::new(
            AccessEventKind::AccessGranted,
            &mapping.role.id,
            &mapping.bounded_context.name,
            actor_role_id,
            json!({
                "level": level_str(mapping.level),
                "can_read_sensitive": mapping.can_read_sensitive,
                "scope": mapping.scope,
                "capabilities": mapping.capabilities,
                "delegable": mapping.delegable,
            }),
        )
    }

    /// `PrivateFieldAccessGranted`: `grant` as it is made. `role_id` is the
    /// grantee, whose access it is, and the actor is the grantor. Both
    /// record fields empty is a blanket grant.
    pub fn private_field_granted(grant: &crate::access_control::PrivateFieldGrant) -> Self {
        Self::new(
            AccessEventKind::PrivateFieldAccessGranted,
            &grant.grantee.id,
            &grant.bounded_context.name,
            Some(&grant.grantor.id),
            json!({
                "grant_id": grant.id,
                "event_sequence": grant.event_sequence,
                "command_id": grant.command_id,
            }),
        )
    }

    /// `PrivateFieldAccessRevoked`. Only the grantor can revoke, so it is
    /// the actor.
    pub fn private_field_revoked(grant: &crate::access_control::PrivateFieldGrant) -> Self {
        Self::new(
            AccessEventKind::PrivateFieldAccessRevoked,
            &grant.grantee.id,
            &grant.bounded_context.name,
            Some(&grant.grantor.id),
            json!({ "grant_id": grant.id }),
        )
    }

    /// `AccessRevoked`; `role_revoked` when the Role's revocation ended it.
    pub fn revoked(
        role_id: &str,
        bounded_context: &str,
        actor_role_id: &str,
        role_revoked: bool,
    ) -> Self {
        Self::new(
            AccessEventKind::AccessRevoked,
            role_id,
            bounded_context,
            Some(actor_role_id),
            json!({ "reason": if role_revoked { "role_revoked" } else { "grant_revoked" } }),
        )
    }

    /// `AccessRevoked` with reason `bounded_context_deleted`: the grant
    /// ended because its bounded context was deleted, by `actor_role_id`.
    pub fn context_ended(role_id: &str, bounded_context: &str, actor_role_id: &str) -> Self {
        Self::new(
            AccessEventKind::AccessRevoked,
            role_id,
            bounded_context,
            Some(actor_role_id),
            json!({ "reason": "bounded_context_deleted" }),
        )
    }

    /// `PrivateFieldAccessRevoked` for a grant that ended with its bounded
    /// context, so the actor is whoever deleted it rather than the grantor.
    pub fn private_field_ended(
        grant_id: &str,
        grantee_id: &str,
        bounded_context: &str,
        actor_role_id: &str,
    ) -> Self {
        Self::new(
            AccessEventKind::PrivateFieldAccessRevoked,
            grantee_id,
            bounded_context,
            Some(actor_role_id),
            json!({ "grant_id": grant_id, "reason": "bounded_context_deleted" }),
        )
    }

    /// `CapabilityGranted`/`CapabilityRevoked`; `via_admin` when the actor
    /// acted as a context admin rather than as a superadmin.
    pub fn capability(
        granted: bool,
        role_id: &str,
        bounded_context: &str,
        actor_role_id: &str,
        capability: &str,
        via_admin: bool,
    ) -> Self {
        Self::new(
            if granted {
                AccessEventKind::CapabilityGranted
            } else {
                AccessEventKind::CapabilityRevoked
            },
            role_id,
            bounded_context,
            Some(actor_role_id),
            json!({
                "capability": capability,
                "via": if via_admin { "admin" } else { "superadmin" },
            }),
        )
    }

    /// `DelegableCapabilitiesSet`.
    pub fn delegable_set(
        role_id: &str,
        bounded_context: &str,
        actor_role_id: &str,
        delegable: &BTreeSet<String>,
    ) -> Self {
        Self::new(
            AccessEventKind::DelegableCapabilitiesSet,
            role_id,
            bounded_context,
            Some(actor_role_id),
            json!({ "delegable": delegable }),
        )
    }

    /// `AccessBaselined`: `mapping`'s state right now.
    pub fn baselined(mapping: &crate::access_control::RoleAccessMapping) -> Self {
        Self::new(
            AccessEventKind::AccessBaselined,
            &mapping.role.id,
            &mapping.bounded_context.name,
            None,
            json!({
                "level": level_str(mapping.level),
                "can_read_sensitive": mapping.can_read_sensitive,
                "scope": mapping.scope,
                "capabilities": mapping.capabilities,
                "delegable": mapping.delegable,
            }),
        )
    }

    fn new(
        kind: AccessEventKind,
        role_id: &str,
        bounded_context: &str,
        actor_role_id: Option<&str>,
        details: Value,
    ) -> Self {
        let Value::Object(details) = details else {
            unreachable!("every constructor above passes a JSON object")
        };
        Self {
            kind,
            role_id: role_id.to_string(),
            bounded_context: bounded_context.to_string(),
            actor_role_id: actor_role_id.map(str::to_string),
            details,
        }
    }

    /// The payload `rule RecordAccessEvent` writes: the details plus the
    /// Role, the bounded context and the actor.
    pub fn payload(&self) -> String {
        let mut payload = self.details.clone();
        payload.insert("role_id".into(), json!(self.role_id));
        payload.insert("bounded_context".into(), json!(self.bounded_context));
        payload.insert("actor_role_id".into(), json!(self.actor_role_id));
        Value::Object(payload).to_string()
    }

    /// The event for this change at `sequence`: `SkiljRecorded`,
    /// `client_id` the literal `"system"`, tagged by Role and bounded
    /// context (what `derive_tags` would produce from the payload).
    pub fn into_event(self, admin: &BoundedContext, sequence: i64, now: DateTime<Utc>) -> Event {
        debug_assert_eq!(admin.name, ADMIN_BOUNDED_CONTEXT_NAME);
        let event_type = access_event_type(admin, self.kind);
        let payload = self.payload();
        Event {
            bounded_context: admin.clone(),
            metadata: Metadata {
                r#type: event_type.name.clone(),
                version: event_type.schema_version,
                client_id: "system".to_string(),
                created_at: now,
                correlation_id: Some(crate::shared::generate_token_id()),
                causation_id: None,
            },
            event_type,
            payload,
            sequence,
            tags: vec![
                Tag {
                    key: "role".into(),
                    value: Some(self.role_id),
                },
                Tag {
                    key: "bounded_context".into(),
                    value: Some(self.bounded_context),
                },
            ],
            encryption_keys: Vec::new(),
            origin: EventOrigin::SkiljRecorded,
        }
    }
}

/// One stored access event, as the fold reads it.
#[derive(Debug, Clone)]
pub struct AccessEventRecord {
    /// Which kind it is.
    pub kind: AccessEventKind,
    /// Its payload.
    pub payload: Value,
    /// When it was recorded.
    pub created_at: DateTime<Utc>,
}

/// What `capabilityHistory` answers (`CapabilityHistoryReturned`).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct AccessHistory {
    /// Whether the trail had begun for this grant by `as_of`; when not,
    /// the rest says nothing about what the grant held.
    pub known: bool,
    /// Whether the grant was active.
    pub held: bool,
    /// Its level while held.
    pub level: Option<String>,
    /// Whether it could read sensitive fields while held.
    pub can_read_sensitive: bool,
    /// Its scope while held.
    pub scope: Option<String>,
    /// The capabilities it held.
    pub capabilities: BTreeSet<String>,
    /// What it could delegate.
    pub delegable: BTreeSet<String>,
}

fn string_set(value: Option<&Value>) -> BTreeSet<String> {
    value
        .and_then(Value::as_array)
        .map(|items| {
            items
                .iter()
                .filter_map(|item| item.as_str().map(str::to_string))
                .collect()
        })
        .unwrap_or_default()
}

/// `fold_access_events`: the grant's state after every event recorded at or
/// before `as_of`, applied in the order given (stored order, i.e. by
/// sequence). A revoked grant holds nothing, so its capabilities and
/// delegable set are empty until a new grant begins.
pub fn fold_access_events(events: &[AccessEventRecord], as_of: DateTime<Utc>) -> AccessHistory {
    let mut state = AccessHistory::default();
    for event in events
        .iter()
        .filter(|event| event.kind.is_mapping_event() && event.created_at <= as_of)
    {
        state.known = true;
        let payload = &event.payload;
        match event.kind {
            AccessEventKind::AccessGranted | AccessEventKind::AccessBaselined => {
                state.held = true;
                state.level = payload["level"].as_str().map(str::to_string);
                state.can_read_sensitive = payload["can_read_sensitive"].as_bool().unwrap_or(false);
                state.scope = payload["scope"].as_str().map(str::to_string);
                state.capabilities = string_set(payload.get("capabilities"));
                state.delegable = string_set(payload.get("delegable"));
            }
            AccessEventKind::AccessRevoked => {
                state = AccessHistory {
                    known: true,
                    ..AccessHistory::default()
                };
            }
            AccessEventKind::CapabilityGranted => {
                if let Some(capability) = payload["capability"].as_str() {
                    state.capabilities.insert(capability.to_string());
                }
            }
            AccessEventKind::CapabilityRevoked => {
                if let Some(capability) = payload["capability"].as_str() {
                    state.capabilities.remove(capability);
                }
            }
            AccessEventKind::DelegableCapabilitiesSet => {
                state.delegable = string_set(payload.get("delegable"));
            }
            // Filtered out above: not part of a mapping's history.
            AccessEventKind::PrivateFieldAccessGranted
            | AccessEventKind::PrivateFieldAccessRevoked => {}
        }
    }
    state
}