p2panda-spaces 0.8.2

Data encryption for multi-device groups
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
// SPDX-License-Identifier: MIT OR Apache-2.0

use std::collections::HashMap;

use p2panda_auth::Access;
use p2panda_auth::group::GroupMember;
use p2panda_auth::traits::{Conditions, Operation};

use crate::member::AuthenticatedMember;
use crate::message::{AuthMessage, SpaceMembershipMessage};
use crate::types::{AuthGroupAction, AuthGroupState, EncryptionGroupOutput};
use crate::utils::{
    added_members_diff, demoted_members_diff, promoted_members_diff, removed_members_diff,
    sort_members,
};
use crate::{ActorId, GroupId, MemberId, OperationId, SpaceId};

#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct GroupActor {
    id: ActorId,
    is_group: bool,
}

impl GroupActor {
    pub fn individual(id: MemberId) -> Self {
        Self {
            id,
            is_group: false,
        }
    }

    pub fn group(id: GroupId) -> Self {
        Self { id, is_group: true }
    }

    pub fn from_group_member(group_member: GroupMember<ActorId>) -> Self {
        match group_member {
            GroupMember::Individual(id) => GroupActor::individual(id),
            GroupMember::Group(id) => GroupActor::group(id),
        }
    }

    pub fn id(&self) -> ActorId {
        self.id
    }

    pub fn is_group(&self) -> bool {
        self.is_group
    }
}

/// Events emitted when system state changes or application messages are processed.
#[derive(Clone, Debug, PartialEq, Eq)]
#[allow(clippy::large_enum_variant)]
pub enum Event<C> {
    /// A member's info with associated key-bundle has been received.
    Member(AuthenticatedMember),

    /// A group membership change occurred in the shared groups state.
    ///
    /// This event does _not_ signify that any space has incorporated this change yet. The
    /// Event::Spaces variant is emitted on space membership changes.
    Groups(GroupEvent<C>),

    /// An application message was decrypted.
    ///
    /// Encrypted application messages are buffered until the local member is welcomed into a
    /// space with a "create" or "add" message.
    Application {
        space_id: SpaceId,
        operation_id: OperationId,
        data: Vec<u8>,
    },

    /// A membership change occurred on a space.
    ///
    /// This event is emitted every time the membership of a space changes, also if the local
    /// member is not (yet) a member of the space. For every Event::Groups event a Event::Spaces
    /// event will be emitted for every effected space.
    Spaces(SpaceEvent<C>),
}

/// Additional context attached to group events.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct GroupContext<C> {
    /// The actor who authored the associated group action.
    pub author: ActorId,

    /// Root group actors, can be individuals or groups.
    pub actors: Vec<(GroupActor, Access<C>)>,

    /// Members of the group.
    pub members: Vec<(ActorId, Access<C>)>,

    /// All ancestor of the effected group and their members.
    pub ancestor_members: HashMap<ActorId, Vec<(ActorId, Access<C>)>>,

    /// All ancestor of the effected group and their direct actor members.
    pub ancestor_actors: HashMap<ActorId, Vec<(GroupActor, Access<C>)>>,
}

/// Additional context attached to space events.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SpaceContext<C> {
    /// The actor who applied this action to the spaces state.
    ///
    /// Note: this can be different to the author of the groups action in cases where concurrent
    /// auth changes which effect a space are applied later by other members.
    pub author: MemberId,

    /// Id of the group associated with the space.
    pub group_id: GroupId,

    /// Current members of the space.
    pub members: Vec<(MemberId, Access<C>)>,

    /// Current direct actor members of the space.
    pub actors: Vec<(GroupActor, Access<C>)>,
}

/// Events emitted when global auth state changes.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum GroupEvent<C> {
    /// A group was created.
    Created {
        /// Group id.
        group_id: GroupId,

        /// Initial group members.
        initial_members: Vec<(GroupActor, Access<C>)>,

        /// Additional event context and group state after any change occurred.
        context: GroupContext<C>,
    },

    /// A member was added to a group.
    Added {
        /// Group id.
        group_id: GroupId,

        /// Group actor that was added, can be individual or group.
        added: GroupActor,

        /// Access level assigned to the added members.
        access: Access<C>,

        /// Additional event context and group state after any change occurred.
        context: GroupContext<C>,
    },

    /// A member was removed from a group.
    Removed {
        /// Group id.
        group_id: GroupId,

        /// Group actor that was removed, can be individual or group.
        removed: GroupActor,

        /// Additional event context and group state after any change occurred.
        context: GroupContext<C>,
    },

    /// An existing group member was promoted.
    Promoted {
        /// Group id.
        group_id: GroupId,

        /// Group actor that was promoted, can be individual or group.
        promoted: GroupActor,

        /// Access level assigned to the promoted members.
        access: Access<C>,

        /// Additional event context and group state after any change occurred.
        context: GroupContext<C>,
    },

    /// An existing group member was demoted.
    Demoted {
        /// Group id.
        group_id: GroupId,

        /// Group actor that was demoted, can be individual or group.
        demoted: GroupActor,

        /// Access level assigned to the demoted members.
        access: Access<C>,

        /// Additional event context and group state after any change occurred.
        context: GroupContext<C>,
    },
}

impl<C> GroupEvent<C> {
    /// The target group of this event.
    pub fn group_id(&self) -> GroupId {
        match self {
            GroupEvent::Created { group_id, .. } => *group_id,
            GroupEvent::Added { group_id, .. } => *group_id,
            GroupEvent::Removed { group_id, .. } => *group_id,
            GroupEvent::Promoted { group_id, .. } => *group_id,
            GroupEvent::Demoted { group_id, .. } => *group_id,
        }
    }

    /// The groups context attached to this event.
    pub fn context(&self) -> &GroupContext<C> {
        match self {
            GroupEvent::Created { context, .. }
            | GroupEvent::Added { context, .. }
            | GroupEvent::Removed { context, .. }
            | GroupEvent::Promoted { context, .. }
            | GroupEvent::Demoted { context, .. } => context,
        }
    }

    /// Returns the members of any ancestor of the changed group. The returned members are
    /// individuals resolved after all nested groups have been traversed.
    ///
    /// Returns `None` if the given group was not an ancestor.
    pub fn members(&self, group_id: GroupId) -> Option<&[(ActorId, Access<C>)]> {
        let context = self.context();
        if self.group_id() == group_id {
            Some(&context.members)
        } else {
            context
                .ancestor_members
                .get(&group_id)
                .map(|members| members.as_slice())
        }
    }

    /// Returns the actors of any ancestor of the changed group. The actors are the "direct
    /// members" of the group, and may be a group or individual.
    ///
    /// Returns `None` if the given group was not effected by this event.
    pub fn actors(&self, group_id: GroupId) -> Option<&[(GroupActor, Access<C>)]> {
        let context = self.context();
        if self.group_id() == group_id {
            Some(&context.actors)
        } else {
            context
                .ancestor_actors
                .get(&group_id)
                .map(|members| members.as_slice())
        }
    }
}

/// Events emitted when space membership changes.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum SpaceEvent<C> {
    /// A space was created.
    Created {
        /// Space id.
        space_id: SpaceId,

        /// Initial members in the space.
        initial_members: Vec<(MemberId, Access<C>)>,

        /// Additional event context and space state after any change occurred.
        context: SpaceContext<C>,

        /// Additional event context and group state after any change occurred.
        groups_context: GroupContext<C>,
    },

    /// One or many individuals were added to the space.
    Added {
        /// Space id.
        space_id: SpaceId,

        /// Members added to the space.
        added: Vec<(MemberId, Access<C>)>,

        /// Additional event context and space state after any change occurred.
        context: SpaceContext<C>,

        /// Additional event context and group state after any change occurred.
        groups_context: GroupContext<C>,
    },

    /// One or many individuals were removed from the space.
    Removed {
        /// Space id.
        space_id: SpaceId,

        /// Members removed from the space.
        removed: Vec<(MemberId, Access<C>)>,

        /// Additional event context and space state after any change occurred.
        context: SpaceContext<C>,

        /// Additional event context and group state after any change occurred.
        groups_context: GroupContext<C>,
    },

    /// One or many individuals were promoted in the space.
    Promoted {
        /// Space id.
        space_id: SpaceId,

        /// Promoted members.
        promoted: Vec<(MemberId, Access<C>)>,

        /// Additional event context and space state after any change occurred.
        context: SpaceContext<C>,

        /// Additional event context and group state after any change occurred.
        groups_context: GroupContext<C>,
    },

    /// One or many individuals were demoted in the space.
    Demoted {
        /// Space id.
        space_id: SpaceId,

        /// Demoted members.
        demoted: Vec<(MemberId, Access<C>)>,

        /// Additional event context and space state after any change occurred.
        context: SpaceContext<C>,

        /// Additional event context and group state after any change occurred.
        groups_context: GroupContext<C>,
    },

    /// Local actor was removed from the space.
    Ejected {
        /// Space id.
        space_id: SpaceId,
    },
}

pub(crate) fn encryption_output_to_space_events<C>(
    space_id: &SpaceId,
    operation_ids: Vec<OperationId>,
    encryption_output: Vec<EncryptionGroupOutput>,
) -> Vec<Event<C>>
where
    C: Conditions,
{
    let plaintexts: Vec<_> = encryption_output
        .into_iter()
        .filter_map(|event| match event {
            EncryptionGroupOutput::Application { plaintext } => Some(plaintext),
            _ => None,
        })
        .collect();

    // Release either nothing or all queued messages in order.
    debug_assert!(plaintexts.is_empty() || plaintexts.len() == operation_ids.len());

    operation_ids
        .into_iter()
        .zip(plaintexts)
        .map(|(id, data)| Event::Application {
            space_id: *space_id,
            operation_id: id,
            data,
        })
        .collect()
}

pub(crate) fn to_groups_event<C>(
    auth_y: &AuthGroupState<C>,
    auth_message: &AuthMessage<C>,
) -> Event<C>
where
    C: Conditions,
{
    let group_id = auth_message.group_id();
    let context = groups_context(auth_y, auth_message);
    let group_event = match auth_message.action() {
        AuthGroupAction::Create { .. } => GroupEvent::Created {
            group_id,
            initial_members: context.actors.clone(),
            context,
        },
        AuthGroupAction::Add { member, access } => GroupEvent::Added {
            group_id,
            added: GroupActor::from_group_member(member),
            access,
            context,
        },
        AuthGroupAction::Remove { member } => GroupEvent::Removed {
            group_id,
            removed: GroupActor::from_group_member(member),
            context,
        },
        AuthGroupAction::Promote { member, access } => GroupEvent::Promoted {
            group_id,
            promoted: GroupActor::from_group_member(member),
            access,
            context,
        },
        AuthGroupAction::Demote { member, access } => GroupEvent::Demoted {
            group_id,
            demoted: GroupActor::from_group_member(member),
            access,
            context,
        },
    };
    Event::Groups(group_event)
}

pub(crate) fn to_space_event<C>(
    space_id: SpaceId,
    group_id: GroupId,
    auth_y: &AuthGroupState<C>,
    space_message: &SpaceMembershipMessage,
    auth_message: &AuthMessage<C>,
    previous_members: &[(MemberId, Access<C>)],
) -> Event<C>
where
    C: Conditions,
{
    let next_members = &auth_y.members(group_id);
    let next_actors: Vec<_> = auth_y
        .root_members(group_id)
        .into_iter()
        .map(|(member, access)| (GroupActor::from_group_member(member), access))
        .collect();
    let context = SpaceContext {
        author: space_message.author,
        group_id,
        members: next_members.to_vec(),
        actors: next_actors,
    };
    let groups_context = groups_context(auth_y, auth_message);

    let space_event = match auth_message.action() {
        AuthGroupAction::Create { .. } => SpaceEvent::Created {
            space_id,
            initial_members: next_members.to_vec(),
            context,
            groups_context,
        },
        AuthGroupAction::Add { .. } => {
            let added = added_members_diff(previous_members, next_members);
            SpaceEvent::Added {
                space_id,
                added,
                context,
                groups_context,
            }
        }
        AuthGroupAction::Remove { .. } => {
            let removed = removed_members_diff(previous_members, next_members);
            SpaceEvent::Removed {
                space_id,
                removed,
                context,
                groups_context,
            }
        }
        AuthGroupAction::Promote { .. } => {
            let promoted = promoted_members_diff(previous_members, next_members);
            SpaceEvent::Promoted {
                space_id,
                promoted,
                context,
                groups_context,
            }
        }
        AuthGroupAction::Demote { .. } => {
            let demoted = demoted_members_diff(previous_members, next_members);
            SpaceEvent::Demoted {
                space_id,
                demoted,
                context,
                groups_context,
            }
        }
    };

    Event::Spaces(space_event)
}

/// Compute groups context.
fn groups_context<C>(auth_y: &AuthGroupState<C>, auth_message: &AuthMessage<C>) -> GroupContext<C>
where
    C: Conditions,
{
    let group_id = auth_message.group_id();

    let mut actors: Vec<_> = auth_y
        .root_members(group_id)
        .into_iter()
        .map(|(member, access)| (GroupActor::from_group_member(member), access))
        .collect();
    sort_members(&mut actors);

    let mut members = auth_y.members(group_id);
    sort_members(&mut members);

    let mut ancestors = auth_y.inner.ancestors(group_id);
    ancestors.sort();

    // Retrieve members of all effected groups.
    let ancestor_members: HashMap<ActorId, Vec<(ActorId, Access<C>)>> = ancestors
        .iter()
        .map(|id| (*id, auth_y.members(*id)))
        .collect();
    let ancestor_actors: HashMap<ActorId, Vec<(GroupActor, Access<C>)>> = ancestors
        .into_iter()
        .map(|id| {
            (
                id,
                auth_y
                    .root_members(id)
                    .into_iter()
                    .map(|(member, access)| (GroupActor::from_group_member(member), access))
                    .collect(),
            )
        })
        .collect();

    GroupContext {
        author: auth_message.author(),
        members,
        actors,
        ancestor_members,
        ancestor_actors,
    }
}