subduction_keyhive_policy 0.9.1

Keyhive-based authorization policy for Subduction connections
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
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
//! Keyhive-based authorization policy and handler for Subduction connections.

#![cfg_attr(not(feature = "std"), no_std)]

pub mod handler;

#[cfg(feature = "std")]
extern crate std;

extern crate alloc;

use alloc::vec::Vec;

use ed25519_dalek::VerifyingKey;
use future_form::{Local, Sendable};
use futures::{
    FutureExt,
    future::{BoxFuture, LocalBoxFuture},
};
use keyhive_core::{
    access::Access,
    keyhive::Keyhive,
    listener::membership::MembershipListener,
    principal::{document::id::DocumentId, identifier::Identifier, individual::id::IndividualId},
    store::ciphertext::CiphertextStore,
};
use keyhive_crypto::{content::reference::ContentRef, signer::async_signer::AsyncSigner};
use sedimentree_core::id::SedimentreeId;
use serde::Deserialize;
use subduction_core::{
    peer::id::PeerId,
    policy::{connection::ConnectionPolicy, storage::StoragePolicy},
};
use subduction_crypto::verified_author::VerifiedAuthor;

/// Error returned when a connection is not allowed.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
pub enum ConnectionDisallowedError {
    /// The peer ID is not a valid Ed25519 public key.
    #[error("peer ID is not a valid Ed25519 public key")]
    InvalidPeerId,

    /// The peer is not a known agent in the Keyhive.
    #[error("peer is not a known agent")]
    UnknownAgent,
}

/// Error returned when a fetch operation is not allowed.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
pub enum FetchDisallowedError {
    /// The peer ID is not a valid Ed25519 public key.
    #[error("peer ID is not a valid Ed25519 public key")]
    InvalidPeerId,

    /// The sedimentree ID is not a valid Ed25519 public key (document ID).
    #[error("sedimentree ID is not a valid document ID")]
    InvalidSedimentreeId,

    /// The document does not exist.
    #[error("document not found")]
    DocumentNotFound,

    /// The peer does not have sufficient access to fetch from this document.
    #[error("insufficient access to fetch: requires at least Relay")]
    InsufficientAccess,
}

/// Error returned when a put operation is not allowed.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
pub enum PutDisallowedError {
    /// The sedimentree ID is not a valid Ed25519 public key (document ID).
    #[error("sedimentree ID is not a valid document ID")]
    InvalidSedimentreeId,

    /// The document does not exist.
    #[error("document not found")]
    DocumentNotFound,

    /// The author does not have sufficient Edit access to this document.
    #[error("insufficient access to put: requires at least Edit")]
    InsufficientAccess,
}

/// A wrapper around [`Keyhive`] that implements [`ConnectionPolicy`] and [`StoragePolicy`] for Subduction.
#[allow(missing_debug_implementations)]
pub struct SubductionKeyhive<
    S: AsyncSigner + Clone,
    T: ContentRef,
    P: for<'de> Deserialize<'de>,
    C: CiphertextStore<T, P> + Clone,
    L: MembershipListener<S, T>,
    R: rand::CryptoRng + rand::RngCore,
>(Keyhive<S, T, P, C, L, R>);

impl<
    S: AsyncSigner + Clone,
    T: ContentRef,
    P: for<'de> Deserialize<'de>,
    C: CiphertextStore<T, P> + Clone,
    L: MembershipListener<S, T>,
    R: rand::CryptoRng + rand::RngCore,
> SubductionKeyhive<S, T, P, C, L, R>
{
    /// Create a new [`SubductionKeyhive`] from a [`Keyhive`].
    #[must_use]
    pub const fn new(keyhive: Keyhive<S, T, P, C, L, R>) -> Self {
        Self(keyhive)
    }

    /// Get a reference to the inner [`Keyhive`].
    #[must_use]
    pub const fn keyhive(&self) -> &Keyhive<S, T, P, C, L, R> {
        &self.0
    }
}

impl<
    S: AsyncSigner + Clone + Send + Sync,
    T: ContentRef + Send + Sync,
    P: for<'de> Deserialize<'de> + Send + Sync,
    C: CiphertextStore<T, P> + Clone + Send + Sync,
    L: MembershipListener<S, T> + Send + Sync,
    R: rand::CryptoRng + rand::RngCore + Send + Sync,
> ConnectionPolicy<Sendable> for SubductionKeyhive<S, T, P, C, L, R>
{
    type ConnectionDisallowed = ConnectionDisallowedError;

    fn authorize_connect(
        &self,
        peer_id: PeerId,
    ) -> BoxFuture<'_, Result<(), Self::ConnectionDisallowed>> {
        async move {
            let identifier = try_peer_id_to_identifier(peer_id)
                .ok_or(ConnectionDisallowedError::InvalidPeerId)?;

            if self.0.get_agent(identifier).await.is_some() {
                return Ok(());
            }

            Err(ConnectionDisallowedError::UnknownAgent)
        }
        .boxed()
    }
}

impl<
    S: AsyncSigner + Clone + Send + Sync,
    T: ContentRef + Send + Sync,
    P: for<'de> Deserialize<'de> + Send + Sync,
    C: CiphertextStore<T, P> + Clone + Send + Sync,
    L: MembershipListener<S, T> + Send + Sync,
    R: rand::CryptoRng + rand::RngCore + Send + Sync,
> StoragePolicy<Sendable> for SubductionKeyhive<S, T, P, C, L, R>
{
    type FetchDisallowed = FetchDisallowedError;
    type PutDisallowed = PutDisallowedError;

    fn authorize_fetch(
        &self,
        peer: PeerId,
        sedimentree_id: SedimentreeId,
    ) -> BoxFuture<'_, Result<(), Self::FetchDisallowed>> {
        async move {
            let identifier =
                try_peer_id_to_identifier(peer).ok_or(FetchDisallowedError::InvalidPeerId)?;

            let doc_id = try_sedimentree_id_to_document_id(sedimentree_id)
                .ok_or(FetchDisallowedError::InvalidSedimentreeId)?;

            let doc = self
                .0
                .get_document(doc_id)
                .await
                .ok_or(FetchDisallowedError::DocumentNotFound)?;

            let members = doc.lock().await.transitive_members().await;

            // Check if the peer has at least Relay access
            if members
                .get(&identifier)
                .is_some_and(|(_, access)| *access >= Access::Relay)
            {
                Ok(())
            } else {
                Err(FetchDisallowedError::InsufficientAccess)
            }
        }
        .boxed()
    }

    fn authorize_put(
        &self,
        _requestor: PeerId,
        author: VerifiedAuthor,
        sedimentree_id: SedimentreeId,
    ) -> BoxFuture<'_, Result<(), Self::PutDisallowed>> {
        async move {
            let identifier = Identifier::from(*author.verifying_key());

            let doc_id = try_sedimentree_id_to_document_id(sedimentree_id)
                .ok_or(PutDisallowedError::InvalidSedimentreeId)?;

            let doc = self
                .0
                .get_document(doc_id)
                .await
                .ok_or(PutDisallowedError::DocumentNotFound)?;

            let members = doc.lock().await.transitive_members().await;

            // Check if the author has at least Edit access
            if members
                .get(&identifier)
                .is_some_and(|(_, access)| *access >= Access::Edit)
            {
                Ok(())
            } else {
                Err(PutDisallowedError::InsufficientAccess)
            }
        }
        .boxed()
    }

    fn filter_authorized_fetch(
        &self,
        peer: PeerId,
        ids: Vec<SedimentreeId>,
    ) -> BoxFuture<'_, Vec<SedimentreeId>> {
        async move {
            let Some(identifier) = try_peer_id_to_identifier(peer) else {
                return Vec::new();
            };

            let mut authorized = Vec::new();
            for sedimentree_id in ids {
                let Some(doc_id) = try_sedimentree_id_to_document_id(sedimentree_id) else {
                    continue;
                };

                let Some(doc) = self.0.get_document(doc_id).await else {
                    continue;
                };

                let members = doc.lock().await.transitive_members().await;

                if members
                    .get(&identifier)
                    .is_some_and(|(_, access)| *access >= Access::Relay)
                {
                    authorized.push(sedimentree_id);
                }
            }

            authorized
        }
        .boxed()
    }
}

impl<
    S: AsyncSigner + Clone,
    T: ContentRef,
    P: for<'de> Deserialize<'de>,
    C: CiphertextStore<T, P> + Clone,
    L: MembershipListener<S, T>,
    R: rand::CryptoRng + rand::RngCore,
> From<Keyhive<S, T, P, C, L, R>> for SubductionKeyhive<S, T, P, C, L, R>
{
    fn from(keyhive: Keyhive<S, T, P, C, L, R>) -> Self {
        SubductionKeyhive(keyhive)
    }
}

impl<
    S: AsyncSigner + Clone,
    T: ContentRef,
    P: for<'de> Deserialize<'de>,
    C: CiphertextStore<T, P> + Clone,
    L: MembershipListener<S, T>,
    R: rand::CryptoRng + rand::RngCore,
> From<SubductionKeyhive<S, T, P, C, L, R>> for Keyhive<S, T, P, C, L, R>
{
    fn from(subduction_keyhive: SubductionKeyhive<S, T, P, C, L, R>) -> Self {
        subduction_keyhive.0
    }
}

// ── Local policy impls ──────────────────────────────────────────────────
//
// These are the natural form for `!Send` keyhive_core. The `Sendable`
// impls above compile but can't be used in practice until keyhive_core
// is `Send`. These `Local` impls work today in Wasm and other
// single-threaded contexts.

impl<
    S: AsyncSigner + Clone,
    T: ContentRef,
    P: for<'de> Deserialize<'de>,
    C: CiphertextStore<T, P> + Clone,
    L: MembershipListener<S, T>,
    R: rand::CryptoRng + rand::RngCore,
> ConnectionPolicy<Local> for SubductionKeyhive<S, T, P, C, L, R>
{
    type ConnectionDisallowed = ConnectionDisallowedError;

    fn authorize_connect(
        &self,
        peer_id: PeerId,
    ) -> LocalBoxFuture<'_, Result<(), Self::ConnectionDisallowed>> {
        async move {
            let identifier = try_peer_id_to_identifier(peer_id)
                .ok_or(ConnectionDisallowedError::InvalidPeerId)?;

            if self.0.get_agent(identifier).await.is_some() {
                return Ok(());
            }

            Err(ConnectionDisallowedError::UnknownAgent)
        }
        .boxed_local()
    }
}

impl<
    S: AsyncSigner + Clone,
    T: ContentRef,
    P: for<'de> Deserialize<'de>,
    C: CiphertextStore<T, P> + Clone,
    L: MembershipListener<S, T>,
    R: rand::CryptoRng + rand::RngCore,
> StoragePolicy<Local> for SubductionKeyhive<S, T, P, C, L, R>
{
    type FetchDisallowed = FetchDisallowedError;
    type PutDisallowed = PutDisallowedError;

    fn authorize_fetch(
        &self,
        peer: PeerId,
        sedimentree_id: SedimentreeId,
    ) -> LocalBoxFuture<'_, Result<(), Self::FetchDisallowed>> {
        async move {
            let identifier =
                try_peer_id_to_identifier(peer).ok_or(FetchDisallowedError::InvalidPeerId)?;

            let doc_id = try_sedimentree_id_to_document_id(sedimentree_id)
                .ok_or(FetchDisallowedError::InvalidSedimentreeId)?;

            let doc = self
                .0
                .get_document(doc_id)
                .await
                .ok_or(FetchDisallowedError::DocumentNotFound)?;

            let members = doc.lock().await.transitive_members().await;

            if members
                .get(&identifier)
                .is_some_and(|(_, access)| *access >= Access::Relay)
            {
                Ok(())
            } else {
                Err(FetchDisallowedError::InsufficientAccess)
            }
        }
        .boxed_local()
    }

    fn authorize_put(
        &self,
        _requestor: PeerId,
        author: VerifiedAuthor,
        sedimentree_id: SedimentreeId,
    ) -> LocalBoxFuture<'_, Result<(), Self::PutDisallowed>> {
        async move {
            let identifier = Identifier::from(*author.verifying_key());

            let doc_id = try_sedimentree_id_to_document_id(sedimentree_id)
                .ok_or(PutDisallowedError::InvalidSedimentreeId)?;

            let doc = self
                .0
                .get_document(doc_id)
                .await
                .ok_or(PutDisallowedError::DocumentNotFound)?;

            let members = doc.lock().await.transitive_members().await;

            if members
                .get(&identifier)
                .is_some_and(|(_, access)| *access >= Access::Edit)
            {
                Ok(())
            } else {
                Err(PutDisallowedError::InsufficientAccess)
            }
        }
        .boxed_local()
    }

    fn filter_authorized_fetch(
        &self,
        peer: PeerId,
        ids: Vec<SedimentreeId>,
    ) -> LocalBoxFuture<'_, Vec<SedimentreeId>> {
        async move {
            let Some(identifier) = try_peer_id_to_identifier(peer) else {
                return Vec::new();
            };

            let mut authorized = Vec::new();
            for sedimentree_id in ids {
                let Some(doc_id) = try_sedimentree_id_to_document_id(sedimentree_id) else {
                    continue;
                };

                let Some(doc) = self.0.get_document(doc_id).await else {
                    continue;
                };

                let members = doc.lock().await.transitive_members().await;

                if members
                    .get(&identifier)
                    .is_some_and(|(_, access)| *access >= Access::Relay)
                {
                    authorized.push(sedimentree_id);
                }
            }

            authorized
        }
        .boxed_local()
    }
}

/// Try to convert a [`PeerId`] to an [`Identifier`].
///
/// This conversion may fail because [`Identifier`] wraps an Ed25519 public key,
/// while [`PeerId`] is arbitrary bytes that may not represent a valid key.
#[must_use]
pub fn try_peer_id_to_identifier(peer_id: PeerId) -> Option<Identifier> {
    let verifying_key = VerifyingKey::from_bytes(peer_id.as_bytes()).ok()?;
    Some(Identifier::from(verifying_key))
}

/// Try to convert a [`PeerId`] to an [`IndividualId`].
///
/// This conversion may fail because [`IndividualId`] wraps an Ed25519 public key,
/// while [`PeerId`] is arbitrary bytes that may not represent a valid key.
#[must_use]
pub fn try_peer_id_to_individual_id(peer_id: PeerId) -> Option<IndividualId> {
    let verifying_key = VerifyingKey::from_bytes(peer_id.as_bytes()).ok()?;
    Some(IndividualId::from(verifying_key))
}

/// Try to convert a [`SedimentreeId`] to a [`DocumentId`].
///
/// This conversion may fail because [`DocumentId`] wraps an Ed25519 public key,
/// while [`SedimentreeId`] is arbitrary bytes that may not represent a valid key.
#[must_use]
pub fn try_sedimentree_id_to_document_id(sedimentree_id: SedimentreeId) -> Option<DocumentId> {
    let verifying_key = VerifyingKey::from_bytes(sedimentree_id.as_bytes()).ok()?;
    Some(DocumentId::from(Identifier::from(verifying_key)))
}

#[cfg(test)]
mod tests {

    use super::*;
    use ed25519_dalek::SigningKey;

    /// Generate a valid peer ID from a signing key.
    fn valid_peer_id(seed: u8) -> PeerId {
        let signing_key = SigningKey::from_bytes(&[seed; 32]);
        PeerId::new(*signing_key.verifying_key().as_bytes())
    }

    /// Generate an invalid peer ID (not a valid Ed25519 point).
    ///
    /// Finding truly invalid Ed25519 public key bytes is non-trivial since
    /// ed25519-dalek accepts many byte patterns. This uses a pattern with
    /// specific bytes known to not represent a valid curve point.
    fn invalid_peer_id() -> Option<PeerId> {
        // Try to find bytes that don't represent a valid Ed25519 point
        // by checking various patterns with the high bit manipulated
        for i in 0..=255u8 {
            let mut bytes = [i; 32];
            // Manipulate to try to create invalid point
            bytes[0] = 0xFE;
            bytes[31] = 0x80 | i;
            if VerifyingKey::from_bytes(&bytes).is_err() {
                return Some(PeerId::new(bytes));
            }
        }
        None
    }

    /// Generate a valid sedimentree ID from a signing key.
    fn valid_sedimentree_id(seed: u8) -> SedimentreeId {
        let signing_key = SigningKey::from_bytes(&[seed; 32]);
        SedimentreeId::new(*signing_key.verifying_key().as_bytes())
    }

    /// Generate an invalid sedimentree ID (not a valid Ed25519 point).
    fn invalid_sedimentree_id() -> Option<SedimentreeId> {
        // Reuse the same pattern search as invalid_peer_id
        for i in 0..=255u8 {
            let mut bytes = [i; 32];
            bytes[0] = 0xFE;
            bytes[31] = 0x80 | i;
            if VerifyingKey::from_bytes(&bytes).is_err() {
                return Some(SedimentreeId::new(bytes));
            }
        }
        None
    }

    mod conversion_functions {
        use super::*;

        #[test]
        fn try_peer_id_to_identifier_succeeds_for_valid_key() {
            let peer_id = valid_peer_id(42);
            let result = try_peer_id_to_identifier(peer_id);
            assert!(result.is_some());
        }

        #[test]
        fn try_peer_id_to_identifier_fails_for_invalid_key() {
            let Some(peer_id) = invalid_peer_id() else {
                // If we can't find an invalid pattern, skip this test
                // (ed25519-dalek may accept all patterns in some configurations)
                return;
            };
            let result = try_peer_id_to_identifier(peer_id);
            assert!(result.is_none());
        }

        #[test]
        fn try_peer_id_to_individual_id_succeeds_for_valid_key() {
            let peer_id = valid_peer_id(42);
            let result = try_peer_id_to_individual_id(peer_id);
            assert!(result.is_some());
        }

        #[test]
        fn try_peer_id_to_individual_id_fails_for_invalid_key() {
            let Some(peer_id) = invalid_peer_id() else {
                return;
            };
            let result = try_peer_id_to_individual_id(peer_id);
            assert!(result.is_none());
        }

        #[test]
        fn try_sedimentree_id_to_document_id_succeeds_for_valid_key() {
            let sed_id = valid_sedimentree_id(42);
            let result = try_sedimentree_id_to_document_id(sed_id);
            assert!(result.is_some());
        }

        #[test]
        fn try_sedimentree_id_to_document_id_fails_for_invalid_key() {
            let Some(sed_id) = invalid_sedimentree_id() else {
                return;
            };
            let result = try_sedimentree_id_to_document_id(sed_id);
            assert!(result.is_none());
        }

        #[test]
        fn different_seeds_produce_different_identifiers() {
            let peer1 = valid_peer_id(1);
            let peer2 = valid_peer_id(2);

            let id1 = try_peer_id_to_identifier(peer1);
            let id2 = try_peer_id_to_identifier(peer2);

            assert!(id1.is_some());
            assert!(id2.is_some());
            assert_ne!(id1, id2);
        }

        #[test]
        fn same_seed_produces_same_identifier() {
            let peer1 = valid_peer_id(42);
            let peer2 = valid_peer_id(42);

            let id1 = try_peer_id_to_identifier(peer1);
            let id2 = try_peer_id_to_identifier(peer2);

            assert_eq!(id1, id2);
        }
    }
}