Skip to main content

stratum_node_core/
admission.rs

1//! Admission to a node: the notice a tenant reads, the claim a tenant signs
2//! to redeem an invitation, and the states a membership moves through.
3
4use std::fmt;
5use std::str::FromStr;
6
7use serde::{Deserialize, Deserializer, Serialize, Serializer};
8
9use crate::did::DidNostr;
10use crate::id::{InvitationId, Sha256Digest};
11
12/// The admission notice, version 1: what a tenant is told before joining.
13///
14/// A prospective tenant reads this text and signs its SHA-256
15/// ([`admission_notice_v1_sha256`]) into the [`AdmissionClaim`], so the node
16/// can show which text the tenant accepted. The text is pure ASCII with no
17/// trailing newline, so a client that receives it as a JSON string and
18/// hashes its UTF-8 bytes gets the same digest. It never changes: different
19/// wording would be a new constant with a new version.
20pub const ADMISSION_NOTICE_V1: &str =
21    "Before you join this Stratum node, please note three things. \
22First, the operator of this node can read the data in your pod while it is stored on the node. \
23Second, backups of this node hold your pod data, encrypted to recipients the operator chose; \
24whoever holds the key for one of those recipients can read it. \
25Third, once the node is served on its public origin, Cloudflare terminates TLS for it and \
26can read your pod traffic in transit. \
27By signing your admission request you confirm that you have read this notice.";
28
29/// Returns the SHA-256 of [`ADMISSION_NOTICE_V1`]: the value an admission
30/// claim's `notice_sha256` must carry for this notice.
31///
32/// # Examples
33///
34/// ```
35/// use stratum_node_core::{admission_notice_v1_sha256, Sha256Digest, ADMISSION_NOTICE_V1};
36///
37/// assert_eq!(admission_notice_v1_sha256(), Sha256Digest::of(ADMISSION_NOTICE_V1.as_bytes()));
38/// ```
39pub fn admission_notice_v1_sha256() -> Sha256Digest {
40    Sha256Digest::of(ADMISSION_NOTICE_V1.as_bytes())
41}
42
43/// The value of an admission claim's `purpose` member.
44pub const ADMISSION_CLAIM_PURPOSE: &str = "stratum.admission.v1";
45
46/// The fields of an admission claim, for [`AdmissionClaim::new`].
47///
48/// Every field is required; the `purpose` member is added by
49/// [`AdmissionClaim::new`].
50#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
51pub struct AdmissionFields {
52    /// The node being joined.
53    pub node: DidNostr,
54    /// The invited identity, who must sign the redemption request.
55    pub subject: DidNostr,
56    /// The invitation being redeemed.
57    pub invitation: InvitationId,
58    /// The SHA-256 of the admission notice the subject read.
59    pub notice_sha256: Sha256Digest,
60}
61
62/// The body of a redemption request, together with its exact JSON bytes.
63///
64/// The JSON shape is an object with exactly these members: `purpose` (always
65/// [`ADMISSION_CLAIM_PURPOSE`]), `node`, `subject`, `invitation` and
66/// `notice_sha256`. Unknown, duplicate and missing members are rejected, and
67/// so is any other `purpose`.
68///
69/// Unlike the bootstrap [`ClaimBody`](crate::ClaimBody), an admission claim
70/// carries no nonce and no expiry. The signed request that carries it is
71/// already fresh (±60 s), single use (its event ID is stored) and bound to
72/// the node's canonical URL, and the invitation is consumed when it is
73/// accepted. The client writes the body itself; there is no server-issued
74/// copy to compare against.
75///
76/// Equality compares the fields and the bytes. The type has no serde
77/// implementations on purpose: send the bytes from
78/// [`as_bytes`](Self::as_bytes) and parse them with [`parse`](Self::parse).
79///
80/// # Accepting a claim
81///
82/// [`AdmissionClaim::check`] is one step and proves nothing on its own. To
83/// accept a redemption the server must, committing nothing unless every step
84/// succeeds:
85///
86/// 1. Verify the signed request with [`verify_request`], passing the
87///    received body as [`ExpectedRequest::body`] and the canonical URL.
88/// 2. Parse the same bytes with [`AdmissionClaim::parse`].
89/// 3. Call [`check`](Self::check) with its own node DID, the signer from
90///    [`VerifiedRequest::signer`] and the digest of the notice it serves.
91/// 4. Look up [`invitation`](Self::invitation) and require it to be issued,
92///    unexpired and bound to [`subject`](Self::subject).
93/// 5. In one transaction, consume the invitation, record the request's event
94///    ID for replay protection and create the membership.
95///
96/// [`verify_request`]: crate::verify_request
97/// [`ExpectedRequest::body`]: crate::ExpectedRequest::body
98/// [`VerifiedRequest::signer`]: crate::VerifiedRequest::signer
99///
100/// # Examples
101///
102/// ```
103/// use stratum_node_core::{
104///     admission_notice_v1_sha256, AdmissionClaim, AdmissionFields, CheckAdmissionError,
105///     InvitationId, NostrSecretKey,
106/// };
107///
108/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
109/// let node = NostrSecretKey::from_hex(&"06".repeat(32))?.public();
110/// let tenant = NostrSecretKey::from_hex(&"07".repeat(32))?.public();
111///
112/// // Client side: build the body and sign a request over its bytes.
113/// let claim = AdmissionClaim::new(AdmissionFields {
114///     node,
115///     subject: tenant,
116///     invitation: InvitationId::from_bytes([1; 16]),
117///     notice_sha256: admission_notice_v1_sha256(),
118/// });
119///
120/// // Server side, after verifying the signed request over these bytes:
121/// let received = AdmissionClaim::parse(claim.as_bytes())?;
122/// received.check(&node, &tenant, &admission_notice_v1_sha256())?;
123///
124/// // A request signed by anyone else fails.
125/// let other = NostrSecretKey::from_hex(&"08".repeat(32))?.public();
126/// assert_eq!(
127///     received.check(&node, &other, &admission_notice_v1_sha256()),
128///     Err(CheckAdmissionError::SubjectMismatch),
129/// );
130/// # Ok(())
131/// # }
132/// ```
133#[derive(Debug, Clone, PartialEq, Eq, Hash)]
134pub struct AdmissionClaim {
135    fields: AdmissionFields,
136    bytes: Vec<u8>,
137}
138
139impl AdmissionClaim {
140    /// Serialises `fields` once, with `purpose` set to
141    /// [`ADMISSION_CLAIM_PURPOSE`], and keeps the bytes.
142    ///
143    /// The members are written in the order `purpose`, `node`, `subject`,
144    /// `invitation`, `notice_sha256`, as compact JSON.
145    ///
146    /// # Panics
147    ///
148    /// Does not panic: `serde_json` has no failure path for this struct of
149    /// strings.
150    pub fn new(fields: AdmissionFields) -> Self {
151        let wire = WireAdmission {
152            purpose: ADMISSION_CLAIM_PURPOSE.to_owned(),
153            node: fields.node,
154            subject: fields.subject,
155            invitation: fields.invitation,
156            notice_sha256: fields.notice_sha256,
157        };
158        let bytes =
159            serde_json::to_vec(&wire).expect("serde_json cannot fail on a struct of strings");
160        Self { fields, bytes }
161    }
162
163    /// Parses admission-claim bytes strictly and keeps them exactly as
164    /// given.
165    ///
166    /// # Errors
167    ///
168    /// Returns [`ParseAdmissionError::WrongPurpose`] when the body is an
169    /// object whose `purpose` is a string other than
170    /// [`ADMISSION_CLAIM_PURPOSE`], and [`ParseAdmissionError::Malformed`]
171    /// for any other deviation: not a single JSON object, a missing,
172    /// unknown or duplicate member, or an invalid member value.
173    pub fn parse(bytes: &[u8]) -> Result<Self, ParseAdmissionError> {
174        let probe: PurposeProbe =
175            serde_json::from_slice(bytes).map_err(|_| ParseAdmissionError::Malformed)?;
176        if probe.purpose != ADMISSION_CLAIM_PURPOSE {
177            return Err(ParseAdmissionError::WrongPurpose);
178        }
179        let wire: WireAdmission =
180            serde_json::from_slice(bytes).map_err(|_| ParseAdmissionError::Malformed)?;
181        Ok(Self {
182            fields: AdmissionFields {
183                node: wire.node,
184                subject: wire.subject,
185                invitation: wire.invitation,
186                notice_sha256: wire.notice_sha256,
187            },
188            bytes: bytes.to_vec(),
189        })
190    }
191
192    /// Checks the claim against the node's own DID, the verified signer of
193    /// the request that carried it and the digest of the notice the node
194    /// serves.
195    ///
196    /// This is a **partial** check; see
197    /// [Accepting a claim](Self#accepting-a-claim) for the full procedure.
198    ///
199    /// # Errors
200    ///
201    /// Returns [`CheckAdmissionError::NodeMismatch`] when the claim names
202    /// another node, [`CheckAdmissionError::SubjectMismatch`] when its
203    /// subject is not `signer`, and [`CheckAdmissionError::NoticeMismatch`]
204    /// when its notice digest is not `expected_notice`, checked in that
205    /// order.
206    pub fn check(
207        &self,
208        expected_node: &DidNostr,
209        signer: &DidNostr,
210        expected_notice: &Sha256Digest,
211    ) -> Result<(), CheckAdmissionError> {
212        if self.fields.node != *expected_node {
213            return Err(CheckAdmissionError::NodeMismatch);
214        }
215        if self.fields.subject != *signer {
216            return Err(CheckAdmissionError::SubjectMismatch);
217        }
218        if self.fields.notice_sha256 != *expected_notice {
219            return Err(CheckAdmissionError::NoticeMismatch);
220        }
221        Ok(())
222    }
223
224    /// Returns the exact bytes this claim was built or parsed from.
225    pub fn as_bytes(&self) -> &[u8] {
226        &self.bytes
227    }
228
229    /// Consumes the claim and returns its exact bytes.
230    pub fn into_bytes(self) -> Vec<u8> {
231        self.bytes
232    }
233
234    /// Returns all fields.
235    pub fn fields(&self) -> &AdmissionFields {
236        &self.fields
237    }
238
239    /// Returns the node being joined.
240    pub fn node(&self) -> DidNostr {
241        self.fields.node
242    }
243
244    /// Returns the invited identity.
245    pub fn subject(&self) -> DidNostr {
246        self.fields.subject
247    }
248
249    /// Returns the invitation being redeemed.
250    pub fn invitation(&self) -> InvitationId {
251        self.fields.invitation
252    }
253
254    /// Returns the notice digest the subject signed.
255    pub fn notice_sha256(&self) -> Sha256Digest {
256        self.fields.notice_sha256
257    }
258}
259
260/// The reasons admission-claim bytes can fail to parse.
261#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
262#[non_exhaustive]
263pub enum ParseAdmissionError {
264    /// The `purpose` member is not [`ADMISSION_CLAIM_PURPOSE`].
265    #[error("admission claim purpose is not {ADMISSION_CLAIM_PURPOSE}")]
266    WrongPurpose,
267    /// The bytes are not a valid admission claim.
268    #[error("malformed admission claim")]
269    Malformed,
270}
271
272/// The reasons a parsed admission claim can fail [`AdmissionClaim::check`].
273#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
274#[non_exhaustive]
275pub enum CheckAdmissionError {
276    /// The claim names a different node.
277    #[error("admission claim names a different node")]
278    NodeMismatch,
279    /// The claim's subject is not the signer of the request.
280    #[error("admission claim subject is not the request signer")]
281    SubjectMismatch,
282    /// The claim's notice digest is not the digest of the node's notice.
283    #[error("admission claim notice digest does not match the node's notice")]
284    NoticeMismatch,
285}
286
287/// The first parsing pass: only the purpose, ignoring other members.
288#[derive(Deserialize)]
289struct PurposeProbe {
290    purpose: String,
291}
292
293/// The wire shape of an admission claim.
294#[derive(Serialize, Deserialize)]
295#[serde(deny_unknown_fields)]
296struct WireAdmission {
297    purpose: String,
298    node: DidNostr,
299    subject: DidNostr,
300    invitation: InvitationId,
301    notice_sha256: Sha256Digest,
302}
303
304/// The state of a tenant's membership of a node.
305///
306/// The text form is the lowercase name (`reserved`, `provisioned`, `active`,
307/// `cancelled`, `suspended`, `removed`), used by [`Display`](fmt::Display),
308/// [`FromStr`] and serde. Parsing is strict: any other text, including
309/// another case, is refused. A reader that must survive a state it does not
310/// know, such as the gate reading the directory, uses
311/// [`DirectoryMemberState`] instead.
312///
313/// The transitions are:
314///
315/// | From | To |
316/// |---|---|
317/// | (none), `removed`, `cancelled` | `reserved` (redemption; a returning key gets the next generation) |
318/// | `reserved` | `provisioned`, `cancelled` |
319/// | `provisioned` | `active` |
320/// | `provisioned`, `active` | `suspended` |
321/// | `suspended` | the state it remembered (resume), `removed` |
322///
323/// Three predicates name the sets of states the node acts on, so that every
324/// component decides them in one place: [`holds_slot`](Self::holds_slot)
325/// (capacity), [`may_provision`](Self::may_provision) (repair and the
326/// reconciler) and [`is_listed`](Self::is_listed) (the gate's directory and
327/// the unsigned profile read).
328///
329/// # Examples
330///
331/// ```
332/// use stratum_node_core::MemberState;
333///
334/// # fn main() -> Result<(), stratum_node_core::ParseMemberStateError> {
335/// let state: MemberState = "suspended".parse()?;
336/// assert_eq!(state, MemberState::Suspended);
337/// assert_eq!(state.to_string(), "suspended");
338/// assert!(state.holds_slot());
339/// assert!(!state.may_provision());
340/// assert!(state.is_listed());
341/// assert!(!MemberState::Removed.holds_slot());
342/// assert!("Active".parse::<MemberState>().is_err());
343/// # Ok(())
344/// # }
345/// ```
346#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
347#[non_exhaustive]
348pub enum MemberState {
349    /// The invitation was consumed and a slot is held; the pod is not yet
350    /// confirmed created.
351    Reserved,
352    /// The pod server created the pod.
353    Provisioned,
354    /// The owner stated that a read and a write to their pod worked.
355    Active,
356    /// The administrator cancelled a reserved member; no slot is held.
357    Cancelled,
358    /// The administrator stopped this member. The membership remembers
359    /// whether it was `provisioned` or `active`, holds its slot, and every
360    /// signed request by or to the member is refused.
361    Suspended,
362    /// The administrator ended this membership. No slot is held; the pod
363    /// data stays on disk until it is purged.
364    Removed,
365}
366
367impl MemberState {
368    /// Every state, in declaration order.
369    ///
370    /// Tests and the store iterate this list to check that a rule written
371    /// elsewhere, such as an SQL predicate, agrees with the predicates here
372    /// for every state.
373    ///
374    /// # Examples
375    ///
376    /// ```
377    /// use stratum_node_core::MemberState;
378    ///
379    /// let slot_states: Vec<&str> = MemberState::ALL
380    ///     .iter()
381    ///     .filter(|s| s.holds_slot())
382    ///     .map(|s| s.as_str())
383    ///     .collect();
384    /// assert_eq!(slot_states, ["reserved", "provisioned", "active", "suspended"]);
385    /// ```
386    pub const ALL: [Self; 6] = [
387        Self::Reserved,
388        Self::Provisioned,
389        Self::Active,
390        Self::Cancelled,
391        Self::Suspended,
392        Self::Removed,
393    ];
394
395    /// Returns the lowercase name.
396    ///
397    /// # Examples
398    ///
399    /// ```
400    /// use stratum_node_core::MemberState;
401    ///
402    /// assert_eq!(MemberState::Removed.as_str(), "removed");
403    /// ```
404    pub fn as_str(self) -> &'static str {
405        match self {
406            Self::Reserved => "reserved",
407            Self::Provisioned => "provisioned",
408            Self::Active => "active",
409            Self::Cancelled => "cancelled",
410            Self::Suspended => "suspended",
411            Self::Removed => "removed",
412        }
413    }
414
415    /// Returns `true` for the states that count against the node's tenant
416    /// capacity: reserved, provisioned, active and suspended.
417    ///
418    /// This is the one definition of capacity. The store builds its SQL
419    /// count from it.
420    ///
421    /// # Examples
422    ///
423    /// ```
424    /// use stratum_node_core::MemberState;
425    ///
426    /// assert!(MemberState::Suspended.holds_slot());
427    /// assert!(!MemberState::Cancelled.holds_slot());
428    /// assert!(!MemberState::Removed.holds_slot());
429    /// ```
430    pub fn holds_slot(self) -> bool {
431        match self {
432            Self::Reserved | Self::Provisioned | Self::Active | Self::Suspended => true,
433            Self::Cancelled | Self::Removed => false,
434        }
435    }
436
437    /// Returns `true` for the states on which provisioning may act: the
438    /// reconciler, a recorded provisioning failure and an administrator's
439    /// repair. Those are reserved, provisioned and active.
440    ///
441    /// This is deliberately not [`holds_slot`](Self::holds_slot): a
442    /// `suspended` member holds a slot, but nothing may call the pod server
443    /// on its behalf, and neither may anything for a `removed` or
444    /// `cancelled` one. Callers test this before any external call.
445    ///
446    /// # Examples
447    ///
448    /// ```
449    /// use stratum_node_core::MemberState;
450    ///
451    /// assert!(MemberState::Reserved.may_provision());
452    /// assert!(MemberState::Active.may_provision());
453    /// assert!(!MemberState::Suspended.may_provision());
454    /// assert!(!MemberState::Removed.may_provision());
455    /// ```
456    pub fn may_provision(self) -> bool {
457        match self {
458            Self::Reserved | Self::Provisioned | Self::Active => true,
459            Self::Cancelled | Self::Suspended | Self::Removed => false,
460        }
461    }
462
463    /// Returns `true` for the states the controller lists in the gate's
464    /// member directory: provisioned, active and suspended.
465    ///
466    /// The same set decides whether the gate serves a key's profile
467    /// document without a signature. A `reserved`, `cancelled` or `removed`
468    /// key is absent from the directory, and the gate treats it as a key
469    /// that was never a member.
470    ///
471    /// # Examples
472    ///
473    /// ```
474    /// use stratum_node_core::MemberState;
475    ///
476    /// assert!(MemberState::Suspended.is_listed());
477    /// assert!(!MemberState::Reserved.is_listed());
478    /// assert!(!MemberState::Removed.is_listed());
479    /// ```
480    pub fn is_listed(self) -> bool {
481        match self {
482            Self::Provisioned | Self::Active | Self::Suspended => true,
483            Self::Reserved | Self::Cancelled | Self::Removed => false,
484        }
485    }
486}
487
488impl fmt::Display for MemberState {
489    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
490        f.write_str(self.as_str())
491    }
492}
493
494impl FromStr for MemberState {
495    type Err = ParseMemberStateError;
496
497    /// Parses the lowercase name exactly; other cases are refused.
498    fn from_str(text: &str) -> Result<Self, Self::Err> {
499        match text {
500            "reserved" => Ok(Self::Reserved),
501            "provisioned" => Ok(Self::Provisioned),
502            "active" => Ok(Self::Active),
503            "cancelled" => Ok(Self::Cancelled),
504            "suspended" => Ok(Self::Suspended),
505            "removed" => Ok(Self::Removed),
506            _ => Err(ParseMemberStateError::Unknown),
507        }
508    }
509}
510
511impl Serialize for MemberState {
512    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
513        serializer.serialize_str(self.as_str())
514    }
515}
516
517impl<'de> Deserialize<'de> for MemberState {
518    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
519        let text = String::deserialize(deserializer)?;
520        text.parse().map_err(serde::de::Error::custom)
521    }
522}
523
524/// The reasons a [`MemberState`] can fail to parse.
525#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
526#[non_exhaustive]
527pub enum ParseMemberStateError {
528    /// The text is not one of the lowercase state names.
529    #[error("unknown member state")]
530    Unknown,
531}
532
533/// A member state as the gate reads it from the member directory: a known
534/// [`MemberState`] or a state this build does not know.
535///
536/// Strict parsing ([`MemberState`]'s [`FromStr`] and serde) refuses an
537/// unknown name, which would make one unknown member fail the whole
538/// directory document. This type is the gate's read path only: an unknown
539/// name deserialises as [`Unknown`](Self::Unknown), so the rest of the
540/// directory is kept and that one member is refused in both roles, as
541/// requester and as owner ("unknown states fail closed, one member at a
542/// time"). Use [`MemberState`] everywhere else; nothing should store or
543/// produce an `Unknown`.
544///
545/// A non-string value is still an error: only an unknown *name* is
546/// tolerated. The unknown text is not kept, so an oversized or hostile
547/// value cannot be carried further.
548///
549/// Serialising [`Known`](Self::Known) writes the state's name;
550/// serialising [`Unknown`](Self::Unknown) writes `"unknown"`, which is not a
551/// state name and reads back as `Unknown`.
552///
553/// # Examples
554///
555/// ```
556/// use stratum_node_core::{DirectoryMemberState, MemberState};
557///
558/// # fn main() -> Result<(), serde_json::Error> {
559/// let known: DirectoryMemberState = serde_json::from_str("\"suspended\"")?;
560/// assert_eq!(known, DirectoryMemberState::Known(MemberState::Suspended));
561/// assert_eq!(known.admits(), None);
562///
563/// let unknown: DirectoryMemberState = serde_json::from_str("\"frozen\"")?;
564/// assert_eq!(unknown, DirectoryMemberState::Unknown);
565///
566/// // Strict parsing elsewhere is unchanged.
567/// assert!(serde_json::from_str::<MemberState>("\"frozen\"").is_err());
568/// # Ok(())
569/// # }
570/// ```
571#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
572#[non_exhaustive]
573pub enum DirectoryMemberState {
574    /// A state this build knows.
575    Known(MemberState),
576    /// A state name this build does not know. The member must be refused
577    /// as requester and as owner.
578    Unknown,
579}
580
581impl DirectoryMemberState {
582    /// Returns the known state when the gate may admit the member at all:
583    /// `provisioned` or `active`. Returns `None` for `suspended`, for any
584    /// other known state and for [`Unknown`](Self::Unknown).
585    ///
586    /// Whether a `provisioned` owner is admitted still depends on who signs
587    /// (Step 2's gate decision 8); this only rules out the states that are
588    /// always refused.
589    ///
590    /// # Examples
591    ///
592    /// ```
593    /// use stratum_node_core::{DirectoryMemberState, MemberState};
594    ///
595    /// let active = DirectoryMemberState::Known(MemberState::Active);
596    /// assert_eq!(active.admits(), Some(MemberState::Active));
597    /// assert_eq!(DirectoryMemberState::Unknown.admits(), None);
598    /// ```
599    pub fn admits(self) -> Option<MemberState> {
600        match self {
601            Self::Known(state @ (MemberState::Provisioned | MemberState::Active)) => Some(state),
602            Self::Known(_) | Self::Unknown => None,
603        }
604    }
605
606    /// Returns the known state, or `None` for [`Unknown`](Self::Unknown).
607    ///
608    /// # Examples
609    ///
610    /// ```
611    /// use stratum_node_core::{DirectoryMemberState, MemberState};
612    ///
613    /// assert_eq!(DirectoryMemberState::from(MemberState::Active).known(), Some(MemberState::Active));
614    /// assert_eq!(DirectoryMemberState::Unknown.known(), None);
615    /// ```
616    pub fn known(self) -> Option<MemberState> {
617        match self {
618            Self::Known(state) => Some(state),
619            Self::Unknown => None,
620        }
621    }
622}
623
624impl From<MemberState> for DirectoryMemberState {
625    fn from(state: MemberState) -> Self {
626        Self::Known(state)
627    }
628}
629
630impl Serialize for DirectoryMemberState {
631    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
632        match self {
633            Self::Known(state) => state.serialize(serializer),
634            Self::Unknown => serializer.serialize_str("unknown"),
635        }
636    }
637}
638
639impl<'de> Deserialize<'de> for DirectoryMemberState {
640    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
641        struct Visitor;
642
643        impl serde::de::Visitor<'_> for Visitor {
644            type Value = DirectoryMemberState;
645
646            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
647                f.write_str("a member state name")
648            }
649
650            fn visit_str<E: serde::de::Error>(self, text: &str) -> Result<Self::Value, E> {
651                Ok(text
652                    .parse::<MemberState>()
653                    .map_or(DirectoryMemberState::Unknown, DirectoryMemberState::Known))
654            }
655        }
656
657        deserializer.deserialize_str(Visitor)
658    }
659}