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`), used by [`Display`](fmt::Display), [`FromStr`] and serde.
308///
309/// # Examples
310///
311/// ```
312/// use stratum_node_core::MemberState;
313///
314/// # fn main() -> Result<(), stratum_node_core::ParseMemberStateError> {
315/// let state: MemberState = "provisioned".parse()?;
316/// assert_eq!(state, MemberState::Provisioned);
317/// assert_eq!(state.to_string(), "provisioned");
318/// assert!(state.holds_slot());
319/// assert!(!MemberState::Cancelled.holds_slot());
320/// assert!("Active".parse::<MemberState>().is_err());
321/// # Ok(())
322/// # }
323/// ```
324#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
325#[non_exhaustive]
326pub enum MemberState {
327    /// The invitation was consumed and a slot is held; the pod is not yet
328    /// confirmed created.
329    Reserved,
330    /// The pod server created the pod.
331    Provisioned,
332    /// The owner stated that a read and a write to their pod worked.
333    Active,
334    /// The administrator cancelled a reserved member; no slot is held.
335    Cancelled,
336}
337
338impl MemberState {
339    /// Returns the lowercase name.
340    pub fn as_str(self) -> &'static str {
341        match self {
342            Self::Reserved => "reserved",
343            Self::Provisioned => "provisioned",
344            Self::Active => "active",
345            Self::Cancelled => "cancelled",
346        }
347    }
348
349    /// Returns `true` for the states that count against the node's tenant
350    /// capacity: reserved, provisioned and active.
351    pub fn holds_slot(self) -> bool {
352        matches!(self, Self::Reserved | Self::Provisioned | Self::Active)
353    }
354}
355
356impl fmt::Display for MemberState {
357    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
358        f.write_str(self.as_str())
359    }
360}
361
362impl FromStr for MemberState {
363    type Err = ParseMemberStateError;
364
365    /// Parses the lowercase name exactly; other cases are refused.
366    fn from_str(text: &str) -> Result<Self, Self::Err> {
367        match text {
368            "reserved" => Ok(Self::Reserved),
369            "provisioned" => Ok(Self::Provisioned),
370            "active" => Ok(Self::Active),
371            "cancelled" => Ok(Self::Cancelled),
372            _ => Err(ParseMemberStateError::Unknown),
373        }
374    }
375}
376
377impl Serialize for MemberState {
378    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
379        serializer.serialize_str(self.as_str())
380    }
381}
382
383impl<'de> Deserialize<'de> for MemberState {
384    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
385        let text = String::deserialize(deserializer)?;
386        text.parse().map_err(serde::de::Error::custom)
387    }
388}
389
390/// The reasons a [`MemberState`] can fail to parse.
391#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
392#[non_exhaustive]
393pub enum ParseMemberStateError {
394    /// The text is not one of the lowercase state names.
395    #[error("unknown member state")]
396    Unknown,
397}