stratum_node_core/claim.rs
1//! The bootstrap claim body an administrator signs to claim a node.
2
3use serde::{Deserialize, Serialize};
4
5use crate::did::DidNostr;
6use crate::id::{ChallengeId, Revision, Sha256Digest, UnixTime};
7
8/// The claim-body format version this crate reads and writes.
9pub const CLAIM_BODY_VERSION: u32 = 1;
10
11/// The fields of a version-1 claim body, for [`ClaimBody::new`].
12///
13/// Every field is required; the format version is added by
14/// [`ClaimBody::new`].
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
16pub struct ClaimFields {
17 /// The single-use challenge this claim answers.
18 pub nonce: ChallengeId,
19 /// The node being claimed.
20 pub node: DidNostr,
21 /// The principal claiming the node, who must sign the claim request.
22 pub claimant: DidNostr,
23 /// The first second at which the claim is no longer accepted.
24 pub expires_at: UnixTime,
25 /// The configuration revision the initial configuration is based on.
26 pub base_revision: Revision,
27 /// The SHA-256 of the exact initial configuration text.
28 pub config_sha256: Sha256Digest,
29}
30
31/// An immutable bootstrap claim body together with its exact JSON bytes.
32///
33/// The server builds the body once with [`ClaimBody::new`], stores it as the
34/// outstanding challenge and hands out its exact bytes. The client signs a
35/// request whose `payload` tag is the SHA-256 of those bytes and sends them
36/// back verbatim. Nothing is ever re-serialised for hashing, so the bytes
37/// that were signed are the bytes that are checked.
38///
39/// The JSON shape of version [`CLAIM_BODY_VERSION`] is an object with exactly
40/// these fields: `version`, `nonce`, `node`, `claimant`, `expires_at`,
41/// `base_revision` and `config_sha256`. Unknown fields, duplicate fields and
42/// other versions are rejected.
43///
44/// Equality compares the bytes. The type has no serde implementations on
45/// purpose: transport the bytes from [`as_bytes`](Self::as_bytes) and parse
46/// them with [`parse`](Self::parse).
47///
48/// # Accepting a claim
49///
50/// [`ClaimBody::check`] is only one step, and on its own it proves nothing
51/// about where a body came from. It looks at expiry, node and claimant. A
52/// client can write a body of its own with any nonce, a later expiry, another
53/// base revision or another configuration digest, sign it, and it will pass
54/// `check`. A signature shows what the claimant signed, not that the server
55/// issued it. To accept a claim the server must do all of the following, and
56/// commit nothing unless every step succeeds:
57///
58/// 1. Verify the signed request with [`verify_request`], passing the
59/// received body as [`ExpectedRequest::body`]. This checks the signature
60/// and that the `payload` tag is the SHA-256 of exactly those bytes.
61/// 2. Parse the same bytes with [`ClaimBody::parse`].
62/// 3. Look up the outstanding challenge the server issued for
63/// [`nonce`](Self::nonce), and compare its stored bytes with the received
64/// bytes for equality (`==` on two `ClaimBody` values compares bytes).
65/// A nonce the server never issued, or any difference in the bytes, is a
66/// refusal.
67/// 4. Call [`check`](Self::check) with the server's clock, its own node DID
68/// and the request signer from [`VerifiedRequest::signer`].
69/// 5. In one transaction, consume the challenge so that the nonce can never
70/// be accepted again, record the request's event ID for replay
71/// protection, bind the administrator and commit the initial
72/// configuration. Commit only values bound by the body: the configuration
73/// text must hash to [`config_sha256`](Self::config_sha256) and apply on
74/// top of [`base_revision`](Self::base_revision). Values taken from
75/// anywhere else in the request must not affect what is committed.
76///
77/// [`verify_request`]: crate::verify_request
78/// [`ExpectedRequest::body`]: crate::ExpectedRequest::body
79/// [`VerifiedRequest::signer`]: crate::VerifiedRequest::signer
80///
81/// # Examples
82///
83/// ```
84/// use stratum_node_core::{
85/// ChallengeId, ClaimBody, ClaimFields, DidNostr, NostrSecretKey, Revision, Sha256Digest,
86/// UnixTime,
87/// };
88///
89/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
90/// let node = NostrSecretKey::from_hex(&"06".repeat(32))?.public();
91/// let admin = NostrSecretKey::from_hex(&"07".repeat(32))?.public();
92/// // The server issues the body and keeps it as the outstanding challenge.
93/// let issued = ClaimBody::new(ClaimFields {
94/// nonce: ChallengeId::from_bytes([9; 16]),
95/// node,
96/// claimant: admin,
97/// expires_at: UnixTime::from_secs(1_700_000_300),
98/// base_revision: Revision::new(0),
99/// config_sha256: Sha256Digest::of(b"[node]\n"),
100/// });
101///
102/// // The client returns the bytes verbatim (inside a signed request, which
103/// // the server verifies first). The server parses them and finds the
104/// // challenge it issued under that nonce.
105/// let returned = ClaimBody::parse(issued.as_bytes())?;
106/// assert_eq!(returned.nonce(), issued.nonce());
107///
108/// // Security check, not a formality: the returned bytes must be exactly the
109/// // bytes the server issued. `check` alone would accept a body the client
110/// // wrote itself.
111/// assert_eq!(returned, issued);
112/// returned.check(UnixTime::from_secs(1_700_000_000), &node, &admin)?;
113///
114/// // Then, atomically: consume the nonce, record the event ID, bind the
115/// // administrator and commit the configuration the body names.
116/// # Ok(())
117/// # }
118/// ```
119#[derive(Debug, Clone, PartialEq, Eq, Hash)]
120pub struct ClaimBody {
121 fields: ClaimFields,
122 bytes: Vec<u8>,
123}
124
125impl ClaimBody {
126 /// Serialises `fields` once, as version [`CLAIM_BODY_VERSION`], and keeps
127 /// the bytes.
128 ///
129 /// # Panics
130 ///
131 /// Does not panic: `serde_json` has no failure path for this struct of
132 /// strings and integers.
133 pub fn new(fields: ClaimFields) -> Self {
134 let wire = WireClaim {
135 version: CLAIM_BODY_VERSION,
136 nonce: fields.nonce,
137 node: fields.node,
138 claimant: fields.claimant,
139 expires_at: fields.expires_at,
140 base_revision: fields.base_revision,
141 config_sha256: fields.config_sha256,
142 };
143 let bytes = serde_json::to_vec(&wire)
144 .expect("serde_json cannot fail on a struct of strings and integers");
145 Self { fields, bytes }
146 }
147
148 /// Parses claim-body bytes and keeps them exactly as given.
149 ///
150 /// # Errors
151 ///
152 /// Returns [`ParseClaimError::UnsupportedVersion`] when `version` is
153 /// anything other than [`CLAIM_BODY_VERSION`], and
154 /// [`ParseClaimError::Malformed`] for any other deviation from the
155 /// format, including a missing `version`, unknown or duplicate fields
156 /// and invalid field values.
157 pub fn parse(bytes: &[u8]) -> Result<Self, ParseClaimError> {
158 let probe: VersionProbe =
159 serde_json::from_slice(bytes).map_err(|_| ParseClaimError::Malformed)?;
160 if probe.version != u64::from(CLAIM_BODY_VERSION) {
161 return Err(ParseClaimError::UnsupportedVersion {
162 version: probe.version,
163 });
164 }
165 let wire: WireClaim =
166 serde_json::from_slice(bytes).map_err(|_| ParseClaimError::Malformed)?;
167 let fields = ClaimFields {
168 nonce: wire.nonce,
169 node: wire.node,
170 claimant: wire.claimant,
171 expires_at: wire.expires_at,
172 base_revision: wire.base_revision,
173 config_sha256: wire.config_sha256,
174 };
175 Ok(Self {
176 fields,
177 bytes: bytes.to_vec(),
178 })
179 }
180
181 /// Checks the claim's expiry, node and claimant against the server's
182 /// time and expectations.
183 ///
184 /// This is a **partial** check. It does not show that the server issued
185 /// this body, that the nonce is outstanding or unused, or that the
186 /// request carrying it was signed; see
187 /// [Accepting a claim](Self#accepting-a-claim) for the full procedure.
188 ///
189 /// The claim is live while `now` is strictly before
190 /// [`expires_at`](Self::expires_at).
191 ///
192 /// # Errors
193 ///
194 /// Returns [`CheckClaimError::Expired`] at or after the expiry,
195 /// [`CheckClaimError::NodeMismatch`] when the body names another node and
196 /// [`CheckClaimError::ClaimantMismatch`] when it names another claimant,
197 /// checked in that order.
198 pub fn check(
199 &self,
200 now: UnixTime,
201 expected_node: &DidNostr,
202 expected_claimant: &DidNostr,
203 ) -> Result<(), CheckClaimError> {
204 if now >= self.fields.expires_at {
205 return Err(CheckClaimError::Expired {
206 expires_at: self.fields.expires_at,
207 now,
208 });
209 }
210 if self.fields.node != *expected_node {
211 return Err(CheckClaimError::NodeMismatch);
212 }
213 if self.fields.claimant != *expected_claimant {
214 return Err(CheckClaimError::ClaimantMismatch);
215 }
216 Ok(())
217 }
218
219 /// Returns the exact bytes this body was built or parsed from.
220 pub fn as_bytes(&self) -> &[u8] {
221 &self.bytes
222 }
223
224 /// Consumes the body and returns its exact bytes.
225 pub fn into_bytes(self) -> Vec<u8> {
226 self.bytes
227 }
228
229 /// Returns the SHA-256 of [`as_bytes`](Self::as_bytes): the value the
230 /// claim request's `payload` tag must carry.
231 pub fn sha256(&self) -> Sha256Digest {
232 Sha256Digest::of(&self.bytes)
233 }
234
235 /// Returns all fields.
236 pub fn fields(&self) -> &ClaimFields {
237 &self.fields
238 }
239
240 /// Returns the challenge this claim answers.
241 pub fn nonce(&self) -> ChallengeId {
242 self.fields.nonce
243 }
244
245 /// Returns the node being claimed.
246 pub fn node(&self) -> DidNostr {
247 self.fields.node
248 }
249
250 /// Returns the claimant.
251 pub fn claimant(&self) -> DidNostr {
252 self.fields.claimant
253 }
254
255 /// Returns the first second at which the claim is no longer accepted.
256 pub fn expires_at(&self) -> UnixTime {
257 self.fields.expires_at
258 }
259
260 /// Returns the base configuration revision.
261 pub fn base_revision(&self) -> Revision {
262 self.fields.base_revision
263 }
264
265 /// Returns the SHA-256 of the initial configuration text.
266 pub fn config_sha256(&self) -> Sha256Digest {
267 self.fields.config_sha256
268 }
269}
270
271/// The reasons claim-body bytes can fail to parse.
272#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
273#[non_exhaustive]
274pub enum ParseClaimError {
275 /// The `version` field names a format this crate does not read.
276 #[error("unsupported claim body version {version}")]
277 UnsupportedVersion {
278 /// The version the body declares.
279 version: u64,
280 },
281 /// The bytes are not a valid claim body of the supported version.
282 #[error("malformed claim body")]
283 Malformed,
284}
285
286/// The reasons a parsed claim can fail [`ClaimBody::check`].
287#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
288#[non_exhaustive]
289pub enum CheckClaimError {
290 /// `now` is at or after the claim's expiry.
291 #[error("claim expired at {expires_at} (now {now})")]
292 Expired {
293 /// The claim's expiry.
294 expires_at: UnixTime,
295 /// The time the server supplied.
296 now: UnixTime,
297 },
298 /// The claim names a different node.
299 #[error("claim names a different node")]
300 NodeMismatch,
301 /// The claim names a different claimant.
302 #[error("claim names a different claimant")]
303 ClaimantMismatch,
304}
305
306/// The first parsing pass: only the version, ignoring other fields.
307#[derive(Deserialize)]
308struct VersionProbe {
309 version: u64,
310}
311
312/// The wire shape of a version-1 claim body.
313#[derive(Serialize, Deserialize)]
314#[serde(deny_unknown_fields)]
315struct WireClaim {
316 version: u32,
317 nonce: ChallengeId,
318 node: DidNostr,
319 claimant: DidNostr,
320 expires_at: UnixTime,
321 base_revision: Revision,
322 config_sha256: Sha256Digest,
323}