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
527
528
529
530
531
532
533
534
535
536
537
538
539
540
// SPDX-License-Identifier: MIT OR Apache-2.0

use std::collections::{HashMap, HashSet};
use std::marker::PhantomData;

use p2panda_auth::traits::Conditions;
use p2panda_encryption::Rng;
use p2panda_encryption::data_scheme::SecretBundleState;
use p2panda_encryption::data_scheme::dcgka::DcgkaState;
use p2panda_encryption::key_bundle::LongTermKeyBundle;
use p2panda_encryption::key_manager::{
    KeyManager, KeyManagerError, KeyManagerState, PreKeyBundlesState,
};
use p2panda_encryption::key_registry::{KeyRegistry, KeyRegistryState};
use p2panda_encryption::two_party::TwoPartyState;
use p2panda_store::Transaction;
use p2panda_store::groups::GroupsStore;
use p2panda_store::key_registry::KeyRegistryStore;
use p2panda_store::key_secrets::PreKeyBundlesStore;
use p2panda_store::spaces::SpacesStore;
use serde::{Deserialize, Serialize};
use thiserror::Error;

use crate::encryption::dgm::EncryptionMembershipState;
use crate::encryption::orderer::EncryptionOrdererState;
use crate::identity::IdentityError;
use crate::manager::StoreError;
use crate::types::{AuthGroupState, EncryptionGroup, EncryptionGroupState};
use crate::{
    ActorId, AuthMessage, Credentials, Forge, GroupId, MemberId, SpaceId, SpacesArgs,
    global_groups_id,
};

pub struct Context<'a, S, F> {
    pub store: &'a S,
    pub forge: &'a F,
    pub credentials: &'a Credentials,
    pub rng: &'a Rng,
}

impl<S, F> Context<'_, S, F> {
    pub fn my_id(&self) -> ActorId {
        self.credentials.verifying_key()
    }

    pub async fn forge<C>(&self, args: SpacesArgs<C>) -> Result<F::Message, IdentityError<F, C>>
    where
        F: Forge<C>,
        C: Conditions,
    {
        // NOTE: Make sure the forge itself is running within the same transaction, otherwise we'll
        // end up with a deadlock caused by nested transactions.
        self.forge.forge(args).await.map_err(IdentityError::Forge)
    }
}

/// Space state, assembled from the persisted space state and the global key manager and -registry.
#[derive(Debug)]
#[cfg_attr(any(test, feature = "test_utils"), derive(Clone))]
pub struct SpaceState<C> {
    /// Id of this space.
    pub space_id: SpaceId,

    /// Local group id describing space membership.
    pub group_id: GroupId,

    /// Local group graph describing membership changes.
    pub groups_y: AuthGroupState<C>,

    /// Encryption state for this space, including global key-registry and -manager for secrets.
    ///
    /// Key manager and -registry states are global, but when a space is loaded they are moved into
    /// it's encryption state (DCGKA) as they get modified during key agreement.
    pub encryption_y: EncryptionGroupState,

    /// Grow-Only-Set of all individuals who have ever been removed from the space, either via
    /// direct removal, or transitively as a member of a removed group.
    pub removed: HashSet<MemberId>,
}

impl<C> SpaceState<C>
where
    C: Conditions,
{
    /// Initialise empty space state.
    ///
    /// Every space starts with an empty "local" group graph and orderer state.
    pub fn init(
        my_id: MemberId,
        space_id: SpaceId,
        group_id: GroupId,
        key_manager_y: KeyManagerState,
        key_registry_y: KeyRegistryState<MemberId>,
    ) -> Self {
        let groups_y = AuthGroupState::new();

        let encryption_y = {
            let encryption_orderer_y = EncryptionOrdererState::new();
            let dgm = EncryptionMembershipState {
                members: Vec::new(),
            };

            // The global key manager & -registry state is nested inside the encryption-group state
            // for the key-agreement API to work with during processing, however we treat this
            // prekey material always as global and _not_ per-space.
            EncryptionGroup::init(
                my_id,
                key_manager_y,
                key_registry_y,
                dgm,
                encryption_orderer_y,
            )
        };

        Self {
            space_id,
            group_id,
            groups_y,
            encryption_y,
            removed: HashSet::new(),
        }
    }

    /// Assemble space state from persisted state and the key manager and -registry.
    fn from_states(
        space_y: SpacesStoreState<C>,
        key_manager_y: KeyManagerState,
        key_registry_y: KeyRegistryState<MemberId>,
    ) -> Self {
        let space_id = space_y.space_id;
        let group_id = space_y.group_id;
        let removed = space_y.removed.clone();
        let (groups_y, encryption_y) =
            space_y.assemble_encryption_state(key_manager_y, key_registry_y);

        Self {
            space_id,
            group_id,
            groups_y,
            encryption_y,
            removed,
        }
    }

    pub fn key_manager_state(&self) -> &KeyManagerState {
        &self.encryption_y.dcgka.my_keys
    }

    pub fn key_registry_state(&self) -> &KeyRegistryState<MemberId> {
        &self.encryption_y.dcgka.pki
    }
}

/// Modified state which will be written to the store on commit.
///
/// Prekey-bundle states are always treated globally but might arrive here via two different paths,
/// either nested within space state (`StateChanges::Space`) or set directly
/// (`StateChanges::PrekeyBundles`).
#[derive(Debug, Default)]
#[allow(clippy::large_enum_variant)]
pub enum StateChanges<C> {
    #[default]
    Nothing,
    GlobalGroups {
        global_groups_y: AuthGroupState<C>,
    },
    PrekeyBundles {
        key_manager_y: Option<KeyManagerState>,
        key_registry_y: Option<KeyRegistryState<MemberId>>,
    },
    Space {
        global_groups_y: Option<AuthGroupState<C>>,
        space_y: SpaceState<C>,
    },
}

/// Open store transaction for the read -> modify -> write cycle, making sure all spaces changes are
/// atomic.
///
/// Dropping the transaction without committing will automatically roll back all changes.
pub struct StateTransaction<'a, S, F, C>
where
    S: Transaction,
{
    pub ctx: Context<'a, S, F>,
    permit: S::Permit,
    _marker: PhantomData<C>,
}

impl<'a, S, F, C> StateTransaction<'a, S, F, C>
where
    S: SpacesStore<SpacesStoreState<C>>
        + GroupsStore<AuthMessage<C>, C>
        + KeyRegistryStore
        + PreKeyBundlesStore
        + Transaction,
    F: Forge<C>,
    C: Conditions,
{
    pub async fn begin(
        store: &'a S,
        forge: &'a F,
        credentials: &'a Credentials,
        rng: &'a Rng,
    ) -> Result<Self, StoreError> {
        let permit = store
            .begin()
            .await
            .map_err(|err| StoreError::Transaction(err.to_string()))?;

        Ok(Self {
            ctx: Context {
                store,
                forge,
                credentials,
                rng,
            },
            permit,
            _marker: PhantomData,
        })
    }

    /// Read global groups state or initialise it on first use.
    pub async fn global_groups_state(&self) -> Result<AuthGroupState<C>, StoreError> {
        let y = self
            .ctx
            .store
            .get_groups_state_tx(global_groups_id())
            .await
            .map_err(|err| StoreError::GroupsStore(err.to_string()))?;
        Ok(y.unwrap_or_default())
    }

    /// Read global key manager state (prekey secrets) or initialise it on first use.
    pub async fn key_manager_state(&self) -> Result<KeyManagerState, StateError> {
        let y = self
            .ctx
            .store
            .get_prekey_secrets_tx()
            .await
            .map_err(|err| StoreError::KeySecretStore(err.to_string()))?;
        Ok(init_key_manager(self.ctx.credentials, y)?)
    }

    /// Read global key registry state (PKI) or initialise it on first use.
    pub async fn key_registry_state(&self) -> Result<KeyRegistryState<MemberId>, StoreError> {
        let y = self
            .ctx
            .store
            .get_key_registry_tx()
            .await
            .map_err(|err| StoreError::KeyRegistryStore(err.to_string()))?;
        Ok(y.unwrap_or_else(KeyRegistry::init))
    }

    /// Read space state, returns `None` if space does not exist.
    pub async fn space_state(
        &self,
        space_id: &SpaceId,
    ) -> Result<Option<SpaceState<C>>, StateError> {
        let Some(space_y) = self
            .ctx
            .store
            .get_space_state_tx(space_id)
            .await
            .map_err(|err| StoreError::SpacesStore(err.to_string()))?
        else {
            return Ok(None);
        };

        let key_manager_y = self.key_manager_state().await?;
        let key_registry_y = self.key_registry_state().await?;

        Ok(Some(SpaceState::from_states(
            space_y,
            key_manager_y,
            key_registry_y,
        )))
    }

    /// Write changed state to the store and commit the transaction.
    pub async fn commit(self, changes: StateChanges<C>) -> Result<(), StoreError> {
        let store = self.ctx.store;
        let mut no_changes_made = false;

        match changes {
            StateChanges::Nothing => {
                no_changes_made = true;
            }
            StateChanges::GlobalGroups { global_groups_y } => {
                store
                    .set_groups_state_tx(global_groups_id(), &global_groups_y)
                    .await
                    .map_err(|err| StoreError::GroupsStore(err.to_string()))?;
            }
            StateChanges::PrekeyBundles {
                key_manager_y,
                key_registry_y,
            } => {
                if let Some(y) = key_manager_y {
                    store
                        .set_prekey_secrets_tx(y.prekey_bundles())
                        .await
                        .map_err(|err| StoreError::KeySecretStore(err.to_string()))?;
                }

                if let Some(y) = key_registry_y {
                    store
                        .set_key_registry_tx(&y)
                        .await
                        .map_err(|err| StoreError::KeyRegistryStore(err.to_string()))?;
                }
            }
            StateChanges::Space {
                global_groups_y,
                space_y,
            } => {
                if let Some(global_groups_y) = global_groups_y {
                    store
                        .set_groups_state_tx(global_groups_id(), &global_groups_y)
                        .await
                        .map_err(|err| StoreError::GroupsStore(err.to_string()))?;
                }

                let key_manager_y = space_y.key_manager_state();
                let key_registry_y = space_y.key_registry_state();

                store
                    .set_prekey_secrets_tx(key_manager_y.prekey_bundles())
                    .await
                    .map_err(|err| StoreError::KeySecretStore(err.to_string()))?;

                store
                    .set_key_registry_tx(key_registry_y)
                    .await
                    .map_err(|err| StoreError::KeyRegistryStore(err.to_string()))?;

                let space_id = space_y.space_id;
                store
                    .set_space_state_tx(&space_id, &SpacesStoreState::from(space_y))
                    .await
                    .map_err(|err| StoreError::SpacesStore(err.to_string()))?;
            }
        }

        if no_changes_made {
            store
                .rollback(self.permit)
                .await
                .map_err(|err| StoreError::Transaction(err.to_string()))?;
        } else {
            store
                .commit(self.permit)
                .await
                .map_err(|err| StoreError::Transaction(err.to_string()))?;
        }

        Ok(())
    }

    /// Discard all changes and roll back the transaction.
    pub async fn rollback(self) -> Result<(), StoreError> {
        self.ctx
            .store
            .rollback(self.permit)
            .await
            .map_err(|err| StoreError::Transaction(err.to_string()))?;
        Ok(())
    }
}

/// Read-only access to the latest committed state.
///
/// This does not acquire a transaction and thus never blocks or gets blocked by writes.
pub struct StateReader<'a, S, C> {
    store: &'a S,
    credentials: &'a Credentials,
    _marker: PhantomData<C>,
}

impl<'a, S, C> StateReader<'a, S, C>
where
    S: SpacesStore<SpacesStoreState<C>>
        + GroupsStore<AuthMessage<C>, C>
        + KeyRegistryStore
        + PreKeyBundlesStore,
    C: Conditions,
{
    pub fn new(store: &'a S, credentials: &'a Credentials) -> Self {
        Self {
            store,
            credentials,
            _marker: PhantomData,
        }
    }

    /// Read global groups state, returns empty state if it doesn't exist yet.
    pub async fn global_groups_state(&self) -> Result<AuthGroupState<C>, StoreError> {
        let y = self
            .store
            .get_groups_state(global_groups_id())
            .await
            .map_err(|err| StoreError::GroupsStore(err.to_string()))?;
        Ok(y.unwrap_or_default())
    }

    /// Read key manager state, returns empty state if it doesn't exist yet.
    pub async fn key_manager_state(&self) -> Result<KeyManagerState, StateError> {
        let y = self
            .store
            .get_prekey_secrets()
            .await
            .map_err(|err| StoreError::KeySecretStore(err.to_string()))?;
        Ok(init_key_manager(self.credentials, y)?)
    }

    /// Read key registry state, returns empty state if it doesn't exist yet.
    pub async fn key_registry_state(&self) -> Result<KeyRegistryState<MemberId>, StoreError> {
        let y = self
            .store
            .get_key_registry()
            .await
            .map_err(|err| StoreError::KeyRegistryStore(err.to_string()))?;
        Ok(y.unwrap_or_else(KeyRegistry::init))
    }

    /// Read space state, returns `None` if space does not exist.
    pub async fn space_state(
        &self,
        space_id: &SpaceId,
    ) -> Result<Option<SpaceState<C>>, StateError> {
        let Some(space_y) = self
            .store
            .get_space_state(space_id)
            .await
            .map_err(|err| StoreError::SpacesStore(err.to_string()))?
        else {
            return Ok(None);
        };

        let key_manager_y = self.key_manager_state().await?;
        let key_registry_y = self.key_registry_state().await?;

        Ok(Some(SpaceState::from_states(
            space_y,
            key_manager_y,
            key_registry_y,
        )))
    }
}

/// Assemble key manager state from persisted pre-key bundles (initialised empty on first use) and
/// our identity secret.
fn init_key_manager(
    credentials: &Credentials,
    prekey_bundles_y: Option<PreKeyBundlesState>,
) -> Result<KeyManagerState, KeyManagerError> {
    KeyManager::init_from_prekey_bundles(
        &credentials.identity_secret(),
        prekey_bundles_y.unwrap_or_default(),
    )
}

#[derive(Debug, Error)]
pub enum StateError {
    #[error(transparent)]
    Store(#[from] StoreError),

    #[error("initialisation of key manager failed with: {0}")]
    KeyManager(#[from] KeyManagerError),
}

/// Spaces state which is encoded and persisted in database.
//
// TODO: Ideally this moves into p2panda-store eventually as the representation / encoding is only a
// concern for the database (serde).
//
// TODO: Introduce versioning and more efficient encoding.
#[derive(Debug, Serialize, Deserialize)]
pub struct SpacesStoreState<C> {
    pub my_id: MemberId,
    pub space_id: SpaceId,
    pub group_id: GroupId,
    // TODO: Check if all fields in this state need to be persisted.
    // TODO: Can we store this in the groups table instead with the given group_id?
    pub groups_y: AuthGroupState<C>,
    pub is_welcomed: bool,
    pub secrets: SecretBundleState,
    // TODO: Verify if this really required here? Maybe ordering is handled on another layer.
    pub orderer: EncryptionOrdererState,
    pub two_party: HashMap<MemberId, TwoPartyState<LongTermKeyBundle>>,
    pub removed: HashSet<MemberId>,
}

impl<C> SpacesStoreState<C> {
    pub fn assemble_encryption_state(
        self,
        my_keys: KeyManagerState,
        pki: KeyRegistryState<MemberId>,
    ) -> (AuthGroupState<C>, EncryptionGroupState) {
        let groups_y = self.groups_y;

        let encryption_y = EncryptionGroupState {
            my_id: self.my_id,
            dcgka: DcgkaState {
                // Inject latest pre-key material to DCGKA state.
                pki,
                my_keys,
                my_id: self.my_id,
                two_party: self.two_party,
                // The DGM is a no-op here, so we can just always use the default.
                dgm: EncryptionMembershipState::default(),
            },
            orderer: self.orderer,
            secrets: self.secrets,
            is_welcomed: self.is_welcomed,
        };

        (groups_y, encryption_y)
    }
}

impl<C> From<SpaceState<C>> for SpacesStoreState<C>
where
    C: Conditions,
{
    fn from(y: SpaceState<C>) -> Self {
        Self {
            my_id: y.encryption_y.my_id,
            space_id: y.space_id,
            group_id: y.group_id,
            groups_y: y.groups_y,
            is_welcomed: y.encryption_y.is_welcomed,
            secrets: y.encryption_y.secrets,
            orderer: y.encryption_y.orderer,
            two_party: y.encryption_y.dcgka.two_party,
            removed: y.removed,
        }
    }
}