stratum-node-core 0.1.0-alpha.4

Zero-I/O core types for Stratum pod nodes: did:nostr principals, typed identifiers, a strict NIP-98 signed-request verifier and bootstrap claim bodies
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
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
//! Admission to a node: the notice a tenant reads, the claim a tenant signs
//! to redeem an invitation, and the states a membership moves through.

use std::fmt;
use std::str::FromStr;

use serde::{Deserialize, Deserializer, Serialize, Serializer};

use crate::did::DidNostr;
use crate::id::{InvitationId, Sha256Digest};

/// The admission notice, version 1: what a tenant is told before joining.
///
/// A prospective tenant reads this text and signs its SHA-256
/// ([`admission_notice_v1_sha256`]) into the [`AdmissionClaim`], so the node
/// can show which text the tenant accepted. The text is pure ASCII with no
/// trailing newline, so a client that receives it as a JSON string and
/// hashes its UTF-8 bytes gets the same digest. It never changes: different
/// wording would be a new constant with a new version.
pub const ADMISSION_NOTICE_V1: &str =
    "Before you join this Stratum node, please note three things. \
First, the operator of this node can read the data in your pod while it is stored on the node. \
Second, backups of this node hold your pod data, encrypted to recipients the operator chose; \
whoever holds the key for one of those recipients can read it. \
Third, once the node is served on its public origin, Cloudflare terminates TLS for it and \
can read your pod traffic in transit. \
By signing your admission request you confirm that you have read this notice.";

/// Returns the SHA-256 of [`ADMISSION_NOTICE_V1`]: the value an admission
/// claim's `notice_sha256` must carry for this notice.
///
/// # Examples
///
/// ```
/// use stratum_node_core::{admission_notice_v1_sha256, Sha256Digest, ADMISSION_NOTICE_V1};
///
/// assert_eq!(admission_notice_v1_sha256(), Sha256Digest::of(ADMISSION_NOTICE_V1.as_bytes()));
/// ```
pub fn admission_notice_v1_sha256() -> Sha256Digest {
    Sha256Digest::of(ADMISSION_NOTICE_V1.as_bytes())
}

/// The value of an admission claim's `purpose` member.
pub const ADMISSION_CLAIM_PURPOSE: &str = "stratum.admission.v1";

/// The fields of an admission claim, for [`AdmissionClaim::new`].
///
/// Every field is required; the `purpose` member is added by
/// [`AdmissionClaim::new`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct AdmissionFields {
    /// The node being joined.
    pub node: DidNostr,
    /// The invited identity, who must sign the redemption request.
    pub subject: DidNostr,
    /// The invitation being redeemed.
    pub invitation: InvitationId,
    /// The SHA-256 of the admission notice the subject read.
    pub notice_sha256: Sha256Digest,
}

/// The body of a redemption request, together with its exact JSON bytes.
///
/// The JSON shape is an object with exactly these members: `purpose` (always
/// [`ADMISSION_CLAIM_PURPOSE`]), `node`, `subject`, `invitation` and
/// `notice_sha256`. Unknown, duplicate and missing members are rejected, and
/// so is any other `purpose`.
///
/// Unlike the bootstrap [`ClaimBody`](crate::ClaimBody), an admission claim
/// carries no nonce and no expiry. The signed request that carries it is
/// already fresh (±60 s), single use (its event ID is stored) and bound to
/// the node's canonical URL, and the invitation is consumed when it is
/// accepted. The client writes the body itself; there is no server-issued
/// copy to compare against.
///
/// Equality compares the fields and the bytes. The type has no serde
/// implementations on purpose: send the bytes from
/// [`as_bytes`](Self::as_bytes) and parse them with [`parse`](Self::parse).
///
/// # Accepting a claim
///
/// [`AdmissionClaim::check`] is one step and proves nothing on its own. To
/// accept a redemption the server must, committing nothing unless every step
/// succeeds:
///
/// 1. Verify the signed request with [`verify_request`], passing the
///    received body as [`ExpectedRequest::body`] and the canonical URL.
/// 2. Parse the same bytes with [`AdmissionClaim::parse`].
/// 3. Call [`check`](Self::check) with its own node DID, the signer from
///    [`VerifiedRequest::signer`] and the digest of the notice it serves.
/// 4. Look up [`invitation`](Self::invitation) and require it to be issued,
///    unexpired and bound to [`subject`](Self::subject).
/// 5. In one transaction, consume the invitation, record the request's event
///    ID for replay protection and create the membership.
///
/// [`verify_request`]: crate::verify_request
/// [`ExpectedRequest::body`]: crate::ExpectedRequest::body
/// [`VerifiedRequest::signer`]: crate::VerifiedRequest::signer
///
/// # Examples
///
/// ```
/// use stratum_node_core::{
///     admission_notice_v1_sha256, AdmissionClaim, AdmissionFields, CheckAdmissionError,
///     InvitationId, NostrSecretKey,
/// };
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let node = NostrSecretKey::from_hex(&"06".repeat(32))?.public();
/// let tenant = NostrSecretKey::from_hex(&"07".repeat(32))?.public();
///
/// // Client side: build the body and sign a request over its bytes.
/// let claim = AdmissionClaim::new(AdmissionFields {
///     node,
///     subject: tenant,
///     invitation: InvitationId::from_bytes([1; 16]),
///     notice_sha256: admission_notice_v1_sha256(),
/// });
///
/// // Server side, after verifying the signed request over these bytes:
/// let received = AdmissionClaim::parse(claim.as_bytes())?;
/// received.check(&node, &tenant, &admission_notice_v1_sha256())?;
///
/// // A request signed by anyone else fails.
/// let other = NostrSecretKey::from_hex(&"08".repeat(32))?.public();
/// assert_eq!(
///     received.check(&node, &other, &admission_notice_v1_sha256()),
///     Err(CheckAdmissionError::SubjectMismatch),
/// );
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct AdmissionClaim {
    fields: AdmissionFields,
    bytes: Vec<u8>,
}

impl AdmissionClaim {
    /// Serialises `fields` once, with `purpose` set to
    /// [`ADMISSION_CLAIM_PURPOSE`], and keeps the bytes.
    ///
    /// The members are written in the order `purpose`, `node`, `subject`,
    /// `invitation`, `notice_sha256`, as compact JSON.
    ///
    /// # Panics
    ///
    /// Does not panic: `serde_json` has no failure path for this struct of
    /// strings.
    pub fn new(fields: AdmissionFields) -> Self {
        let wire = WireAdmission {
            purpose: ADMISSION_CLAIM_PURPOSE.to_owned(),
            node: fields.node,
            subject: fields.subject,
            invitation: fields.invitation,
            notice_sha256: fields.notice_sha256,
        };
        let bytes =
            serde_json::to_vec(&wire).expect("serde_json cannot fail on a struct of strings");
        Self { fields, bytes }
    }

    /// Parses admission-claim bytes strictly and keeps them exactly as
    /// given.
    ///
    /// # Errors
    ///
    /// Returns [`ParseAdmissionError::WrongPurpose`] when the body is an
    /// object whose `purpose` is a string other than
    /// [`ADMISSION_CLAIM_PURPOSE`], and [`ParseAdmissionError::Malformed`]
    /// for any other deviation: not a single JSON object, a missing,
    /// unknown or duplicate member, or an invalid member value.
    pub fn parse(bytes: &[u8]) -> Result<Self, ParseAdmissionError> {
        let probe: PurposeProbe =
            serde_json::from_slice(bytes).map_err(|_| ParseAdmissionError::Malformed)?;
        if probe.purpose != ADMISSION_CLAIM_PURPOSE {
            return Err(ParseAdmissionError::WrongPurpose);
        }
        let wire: WireAdmission =
            serde_json::from_slice(bytes).map_err(|_| ParseAdmissionError::Malformed)?;
        Ok(Self {
            fields: AdmissionFields {
                node: wire.node,
                subject: wire.subject,
                invitation: wire.invitation,
                notice_sha256: wire.notice_sha256,
            },
            bytes: bytes.to_vec(),
        })
    }

    /// Checks the claim against the node's own DID, the verified signer of
    /// the request that carried it and the digest of the notice the node
    /// serves.
    ///
    /// This is a **partial** check; see
    /// [Accepting a claim](Self#accepting-a-claim) for the full procedure.
    ///
    /// # Errors
    ///
    /// Returns [`CheckAdmissionError::NodeMismatch`] when the claim names
    /// another node, [`CheckAdmissionError::SubjectMismatch`] when its
    /// subject is not `signer`, and [`CheckAdmissionError::NoticeMismatch`]
    /// when its notice digest is not `expected_notice`, checked in that
    /// order.
    pub fn check(
        &self,
        expected_node: &DidNostr,
        signer: &DidNostr,
        expected_notice: &Sha256Digest,
    ) -> Result<(), CheckAdmissionError> {
        if self.fields.node != *expected_node {
            return Err(CheckAdmissionError::NodeMismatch);
        }
        if self.fields.subject != *signer {
            return Err(CheckAdmissionError::SubjectMismatch);
        }
        if self.fields.notice_sha256 != *expected_notice {
            return Err(CheckAdmissionError::NoticeMismatch);
        }
        Ok(())
    }

    /// Returns the exact bytes this claim was built or parsed from.
    pub fn as_bytes(&self) -> &[u8] {
        &self.bytes
    }

    /// Consumes the claim and returns its exact bytes.
    pub fn into_bytes(self) -> Vec<u8> {
        self.bytes
    }

    /// Returns all fields.
    pub fn fields(&self) -> &AdmissionFields {
        &self.fields
    }

    /// Returns the node being joined.
    pub fn node(&self) -> DidNostr {
        self.fields.node
    }

    /// Returns the invited identity.
    pub fn subject(&self) -> DidNostr {
        self.fields.subject
    }

    /// Returns the invitation being redeemed.
    pub fn invitation(&self) -> InvitationId {
        self.fields.invitation
    }

    /// Returns the notice digest the subject signed.
    pub fn notice_sha256(&self) -> Sha256Digest {
        self.fields.notice_sha256
    }
}

/// The reasons admission-claim bytes can fail to parse.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum ParseAdmissionError {
    /// The `purpose` member is not [`ADMISSION_CLAIM_PURPOSE`].
    #[error("admission claim purpose is not {ADMISSION_CLAIM_PURPOSE}")]
    WrongPurpose,
    /// The bytes are not a valid admission claim.
    #[error("malformed admission claim")]
    Malformed,
}

/// The reasons a parsed admission claim can fail [`AdmissionClaim::check`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum CheckAdmissionError {
    /// The claim names a different node.
    #[error("admission claim names a different node")]
    NodeMismatch,
    /// The claim's subject is not the signer of the request.
    #[error("admission claim subject is not the request signer")]
    SubjectMismatch,
    /// The claim's notice digest is not the digest of the node's notice.
    #[error("admission claim notice digest does not match the node's notice")]
    NoticeMismatch,
}

/// The first parsing pass: only the purpose, ignoring other members.
#[derive(Deserialize)]
struct PurposeProbe {
    purpose: String,
}

/// The wire shape of an admission claim.
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct WireAdmission {
    purpose: String,
    node: DidNostr,
    subject: DidNostr,
    invitation: InvitationId,
    notice_sha256: Sha256Digest,
}

/// The state of a tenant's membership of a node.
///
/// The text form is the lowercase name (`reserved`, `provisioned`, `active`,
/// `cancelled`, `suspended`, `removed`), used by [`Display`](fmt::Display),
/// [`FromStr`] and serde. Parsing is strict: any other text, including
/// another case, is refused. A reader that must survive a state it does not
/// know, such as the gate reading the directory, uses
/// [`DirectoryMemberState`] instead.
///
/// The transitions are:
///
/// | From | To |
/// |---|---|
/// | (none), `removed`, `cancelled` | `reserved` (redemption; a returning key gets the next generation) |
/// | `reserved` | `provisioned`, `cancelled` |
/// | `provisioned` | `active` |
/// | `provisioned`, `active` | `suspended` |
/// | `suspended` | the state it remembered (resume), `removed` |
///
/// Three predicates name the sets of states the node acts on, so that every
/// component decides them in one place: [`holds_slot`](Self::holds_slot)
/// (capacity), [`may_provision`](Self::may_provision) (repair and the
/// reconciler) and [`is_listed`](Self::is_listed) (the gate's directory and
/// the unsigned profile read).
///
/// # Examples
///
/// ```
/// use stratum_node_core::MemberState;
///
/// # fn main() -> Result<(), stratum_node_core::ParseMemberStateError> {
/// let state: MemberState = "suspended".parse()?;
/// assert_eq!(state, MemberState::Suspended);
/// assert_eq!(state.to_string(), "suspended");
/// assert!(state.holds_slot());
/// assert!(!state.may_provision());
/// assert!(state.is_listed());
/// assert!(!MemberState::Removed.holds_slot());
/// assert!("Active".parse::<MemberState>().is_err());
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub enum MemberState {
    /// The invitation was consumed and a slot is held; the pod is not yet
    /// confirmed created.
    Reserved,
    /// The pod server created the pod.
    Provisioned,
    /// The owner stated that a read and a write to their pod worked.
    Active,
    /// The administrator cancelled a reserved member; no slot is held.
    Cancelled,
    /// The administrator stopped this member. The membership remembers
    /// whether it was `provisioned` or `active`, holds its slot, and every
    /// signed request by or to the member is refused.
    Suspended,
    /// The administrator ended this membership. No slot is held; the pod
    /// data stays on disk until it is purged.
    Removed,
}

impl MemberState {
    /// Every state, in declaration order.
    ///
    /// Tests and the store iterate this list to check that a rule written
    /// elsewhere, such as an SQL predicate, agrees with the predicates here
    /// for every state.
    ///
    /// # Examples
    ///
    /// ```
    /// use stratum_node_core::MemberState;
    ///
    /// let slot_states: Vec<&str> = MemberState::ALL
    ///     .iter()
    ///     .filter(|s| s.holds_slot())
    ///     .map(|s| s.as_str())
    ///     .collect();
    /// assert_eq!(slot_states, ["reserved", "provisioned", "active", "suspended"]);
    /// ```
    pub const ALL: [Self; 6] = [
        Self::Reserved,
        Self::Provisioned,
        Self::Active,
        Self::Cancelled,
        Self::Suspended,
        Self::Removed,
    ];

    /// Returns the lowercase name.
    ///
    /// # Examples
    ///
    /// ```
    /// use stratum_node_core::MemberState;
    ///
    /// assert_eq!(MemberState::Removed.as_str(), "removed");
    /// ```
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Reserved => "reserved",
            Self::Provisioned => "provisioned",
            Self::Active => "active",
            Self::Cancelled => "cancelled",
            Self::Suspended => "suspended",
            Self::Removed => "removed",
        }
    }

    /// Returns `true` for the states that count against the node's tenant
    /// capacity: reserved, provisioned, active and suspended.
    ///
    /// This is the one definition of capacity. The store builds its SQL
    /// count from it.
    ///
    /// # Examples
    ///
    /// ```
    /// use stratum_node_core::MemberState;
    ///
    /// assert!(MemberState::Suspended.holds_slot());
    /// assert!(!MemberState::Cancelled.holds_slot());
    /// assert!(!MemberState::Removed.holds_slot());
    /// ```
    pub fn holds_slot(self) -> bool {
        match self {
            Self::Reserved | Self::Provisioned | Self::Active | Self::Suspended => true,
            Self::Cancelled | Self::Removed => false,
        }
    }

    /// Returns `true` for the states on which provisioning may act: the
    /// reconciler, a recorded provisioning failure and an administrator's
    /// repair. Those are reserved, provisioned and active.
    ///
    /// This is deliberately not [`holds_slot`](Self::holds_slot): a
    /// `suspended` member holds a slot, but nothing may call the pod server
    /// on its behalf, and neither may anything for a `removed` or
    /// `cancelled` one. Callers test this before any external call.
    ///
    /// # Examples
    ///
    /// ```
    /// use stratum_node_core::MemberState;
    ///
    /// assert!(MemberState::Reserved.may_provision());
    /// assert!(MemberState::Active.may_provision());
    /// assert!(!MemberState::Suspended.may_provision());
    /// assert!(!MemberState::Removed.may_provision());
    /// ```
    pub fn may_provision(self) -> bool {
        match self {
            Self::Reserved | Self::Provisioned | Self::Active => true,
            Self::Cancelled | Self::Suspended | Self::Removed => false,
        }
    }

    /// Returns `true` for the states the controller lists in the gate's
    /// member directory: provisioned, active and suspended.
    ///
    /// The same set decides whether the gate serves a key's profile
    /// document without a signature. A `reserved`, `cancelled` or `removed`
    /// key is absent from the directory, and the gate treats it as a key
    /// that was never a member.
    ///
    /// # Examples
    ///
    /// ```
    /// use stratum_node_core::MemberState;
    ///
    /// assert!(MemberState::Suspended.is_listed());
    /// assert!(!MemberState::Reserved.is_listed());
    /// assert!(!MemberState::Removed.is_listed());
    /// ```
    pub fn is_listed(self) -> bool {
        match self {
            Self::Provisioned | Self::Active | Self::Suspended => true,
            Self::Reserved | Self::Cancelled | Self::Removed => false,
        }
    }
}

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

impl FromStr for MemberState {
    type Err = ParseMemberStateError;

    /// Parses the lowercase name exactly; other cases are refused.
    fn from_str(text: &str) -> Result<Self, Self::Err> {
        match text {
            "reserved" => Ok(Self::Reserved),
            "provisioned" => Ok(Self::Provisioned),
            "active" => Ok(Self::Active),
            "cancelled" => Ok(Self::Cancelled),
            "suspended" => Ok(Self::Suspended),
            "removed" => Ok(Self::Removed),
            _ => Err(ParseMemberStateError::Unknown),
        }
    }
}

impl Serialize for MemberState {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(self.as_str())
    }
}

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

/// The reasons a [`MemberState`] can fail to parse.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum ParseMemberStateError {
    /// The text is not one of the lowercase state names.
    #[error("unknown member state")]
    Unknown,
}

/// A member state as the gate reads it from the member directory: a known
/// [`MemberState`] or a state this build does not know.
///
/// Strict parsing ([`MemberState`]'s [`FromStr`] and serde) refuses an
/// unknown name, which would make one unknown member fail the whole
/// directory document. This type is the gate's read path only: an unknown
/// name deserialises as [`Unknown`](Self::Unknown), so the rest of the
/// directory is kept and that one member is refused in both roles, as
/// requester and as owner ("unknown states fail closed, one member at a
/// time"). Use [`MemberState`] everywhere else; nothing should store or
/// produce an `Unknown`.
///
/// A non-string value is still an error: only an unknown *name* is
/// tolerated. The unknown text is not kept, so an oversized or hostile
/// value cannot be carried further.
///
/// Serialising [`Known`](Self::Known) writes the state's name;
/// serialising [`Unknown`](Self::Unknown) writes `"unknown"`, which is not a
/// state name and reads back as `Unknown`.
///
/// # Examples
///
/// ```
/// use stratum_node_core::{DirectoryMemberState, MemberState};
///
/// # fn main() -> Result<(), serde_json::Error> {
/// let known: DirectoryMemberState = serde_json::from_str("\"suspended\"")?;
/// assert_eq!(known, DirectoryMemberState::Known(MemberState::Suspended));
/// assert_eq!(known.admits(), None);
///
/// let unknown: DirectoryMemberState = serde_json::from_str("\"frozen\"")?;
/// assert_eq!(unknown, DirectoryMemberState::Unknown);
///
/// // Strict parsing elsewhere is unchanged.
/// assert!(serde_json::from_str::<MemberState>("\"frozen\"").is_err());
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum DirectoryMemberState {
    /// A state this build knows.
    Known(MemberState),
    /// A state name this build does not know. The member must be refused
    /// as requester and as owner.
    Unknown,
}

impl DirectoryMemberState {
    /// Returns the known state when the gate may admit the member at all:
    /// `provisioned` or `active`. Returns `None` for `suspended`, for any
    /// other known state and for [`Unknown`](Self::Unknown).
    ///
    /// Whether a `provisioned` owner is admitted still depends on who signs
    /// (Step 2's gate decision 8); this only rules out the states that are
    /// always refused.
    ///
    /// # Examples
    ///
    /// ```
    /// use stratum_node_core::{DirectoryMemberState, MemberState};
    ///
    /// let active = DirectoryMemberState::Known(MemberState::Active);
    /// assert_eq!(active.admits(), Some(MemberState::Active));
    /// assert_eq!(DirectoryMemberState::Unknown.admits(), None);
    /// ```
    pub fn admits(self) -> Option<MemberState> {
        match self {
            Self::Known(state @ (MemberState::Provisioned | MemberState::Active)) => Some(state),
            Self::Known(_) | Self::Unknown => None,
        }
    }

    /// Returns the known state, or `None` for [`Unknown`](Self::Unknown).
    ///
    /// # Examples
    ///
    /// ```
    /// use stratum_node_core::{DirectoryMemberState, MemberState};
    ///
    /// assert_eq!(DirectoryMemberState::from(MemberState::Active).known(), Some(MemberState::Active));
    /// assert_eq!(DirectoryMemberState::Unknown.known(), None);
    /// ```
    pub fn known(self) -> Option<MemberState> {
        match self {
            Self::Known(state) => Some(state),
            Self::Unknown => None,
        }
    }
}

impl From<MemberState> for DirectoryMemberState {
    fn from(state: MemberState) -> Self {
        Self::Known(state)
    }
}

impl Serialize for DirectoryMemberState {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        match self {
            Self::Known(state) => state.serialize(serializer),
            Self::Unknown => serializer.serialize_str("unknown"),
        }
    }
}

impl<'de> Deserialize<'de> for DirectoryMemberState {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        struct Visitor;

        impl serde::de::Visitor<'_> for Visitor {
            type Value = DirectoryMemberState;

            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                f.write_str("a member state name")
            }

            fn visit_str<E: serde::de::Error>(self, text: &str) -> Result<Self::Value, E> {
                Ok(text
                    .parse::<MemberState>()
                    .map_or(DirectoryMemberState::Unknown, DirectoryMemberState::Known))
            }
        }

        deserializer.deserialize_str(Visitor)
    }
}