Skip to main content

stratum_node_cli/
join.rs

1//! `stratum join`: redeeming an invitation and activating the pod.
2
3use std::thread;
4use std::time::{Duration, Instant};
5
6use serde_json::{json, Value as Json};
7use stratum_node_core::{
8    admission_notice_v1_sha256, AdmissionClaim, AdmissionFields, DidNostr, InvitationId,
9    MemberState, NostrSecretKey, PodPath, Sha256Digest,
10};
11
12use crate::client::{self, MAX_RESPONSE_BYTES};
13use crate::error::CliError;
14use crate::exit;
15use crate::gate::{GateClient, Precondition, Request, Route, ANY, JSON};
16use crate::origin::GateTarget;
17use crate::output::sanitize;
18use crate::session::{to_body, Confirmation, Session};
19use crate::wire::{ConfirmRequest, ConfirmResponse, NoticeResponse, OperationResponse};
20
21/// `GET` route: the admission notice.
22const NOTICE: &str = "/api/v1/admission/notice";
23/// `POST` route: redeem an invitation.
24const REDEEM: &str = "/api/v1/admission/redeem";
25/// `GET` route: the caller's own provisioning operation.
26const OPERATION: &str = "/api/v1/admission/operation";
27/// `POST` route: confirm that the pod works.
28const CONFIRM: &str = "/api/v1/admission/confirm";
29
30/// The default time `join` waits for the pod to be provisioned.
31pub const DEFAULT_WAIT: Duration = Duration::from_secs(120);
32
33/// The first pause between polls of the operation; it doubles up to
34/// [`MAX_POLL_INTERVAL`].
35const FIRST_POLL_INTERVAL: Duration = Duration::from_millis(250);
36/// The longest pause between polls of the operation.
37const MAX_POLL_INTERVAL: Duration = Duration::from_secs(2);
38
39/// The name prefix of the probe resource written in the new pod. It starts
40/// with a letter: the pod server refuses names that start with a dot.
41const PROBE_PREFIX: &str = "stratum-join-probe-";
42
43/// Options for [`Session::join`].
44#[derive(Debug, Clone)]
45pub struct JoinOptions {
46    /// The invitation the administrator issued (`--invitation`).
47    pub invitation: InvitationId,
48    /// The node DID the invitation names (`--node`); the node reached must
49    /// report it.
50    pub node: DidNostr,
51    /// How long to wait for the node to provision the pod (`--wait-secs`).
52    pub wait: Duration,
53    /// Whether to ask before redeeming.
54    pub confirmation: Confirmation,
55}
56
57/// What a `join` run did, for the report.
58#[derive(Debug, Default)]
59struct Progress {
60    redeemed: bool,
61    resent: bool,
62}
63
64impl Session {
65    /// `stratum join --invitation <id> --node <did> --origin … [--connect …]`:
66    /// redeems an invitation with the caller's key and activates the pod.
67    ///
68    /// The flow:
69    ///
70    /// 1. Fetch the admission notice. The node DID it reports must be
71    ///    [`JoinOptions::node`], its origin the canonical origin, and the
72    ///    SHA-256 of the notice text received must equal both the hash the
73    ///    node reports and the hash of the notice this client was built
74    ///    with ([`admission_notice_v1_sha256`]).
75    /// 2. Ask for the caller's own operation. A caller who is already a
76    ///    member (`reserved`, `provisioned` or `active`) continues from
77    ///    where an earlier run stopped, without redeeming again.
78    /// 3. Otherwise show the notice and ask for confirmation (a terminal is
79    ///    required unless `--yes`), then redeem with the admission claim
80    ///    signed by the caller. If the connection fails after the request
81    ///    was sent, the identical signed request is resent once: the node
82    ///    returns the response it stored.
83    /// 4. Poll the operation until the member is `provisioned`, for at most
84    ///    [`JoinOptions::wait`], showing the node's last error when it
85    ///    reports one.
86    /// 5. Write a probe resource in the pod (create only), read it back and
87    ///    compare, and delete it.
88    /// 6. Confirm, and print the pod URL.
89    ///
90    /// Every request is signed with a fresh event over the canonical URL;
91    /// only the single resend reuses one. Every pod URL the node reports must
92    /// be exactly `<origin>/pods/<caller's key>/`.
93    ///
94    /// # Errors
95    ///
96    /// [`CliError::Refused`] for a notice from another node or with another
97    /// hash, a cancelled membership, a response naming another member or pod
98    /// URL, or a probe that does not read back; [`CliError::NotConfirmed`];
99    /// [`CliError::TimedOut`] when provisioning does not finish in time
100    /// (rerun `join` to continue); and key, transport and server errors
101    /// (`invitation_refused`, `invitations_disabled`, `capacity_exhausted`,
102    /// `too_many_requests` among them).
103    pub fn join(&self, target: &GateTarget, options: &JoinOptions) -> Result<u8, CliError> {
104        let key = self.key()?;
105        let me = key.public();
106        let gate = GateClient::new(target.clone());
107        let pod_url = target.origin().url(PodPath::pod_root(&me).as_str());
108        let notice = fetch_notice(&gate, options)?;
109
110        let mut progress = Progress::default();
111        let mut operation = if let Some(operation) = own_operation(&gate, &key)? {
112            self.output().note(&format!(
113                "{me} is already a member of this node ({}); continuing",
114                operation.state
115            ))?;
116            operation
117        } else {
118            self.show_notice(&notice)?;
119            if !self.confirmed(
120                "join this node, accepting the notice above?",
121                options.confirmation,
122            )? {
123                self.output().json(&json!({"joined": false}))?;
124                return Err(CliError::NotConfirmed);
125            }
126            let operation = self.redeem(&gate, &key, options, &mut progress)?;
127            progress.redeemed = true;
128            operation
129        };
130        check_operation(&operation, me, &pod_url)?;
131        self.output().note(&format!(
132            "operation {}: {}",
133            operation.operation_id, operation.state
134        ))?;
135        if !matches!(
136            operation.state,
137            MemberState::Provisioned | MemberState::Active
138        ) {
139            operation = self.wait_provisioned(&gate, &key, &pod_url, options.wait)?;
140        }
141
142        let (probe, probe_sha256) = self.probe(&gate, &key, &me)?;
143        let body = to_body(&ConfirmRequest {
144            node: options.node,
145            operation_id: &operation.operation_id,
146        })?;
147        let (confirmed, _raw): (ConfirmResponse, Json) = gate
148            .fetch(
149                &Request::new("POST", CONFIRM, JSON).with_body(&body, JSON),
150                Some(&key),
151                MAX_RESPONSE_BYTES,
152            )?
153            .into_json(Route::Admission)?;
154        if confirmed.did != me || confirmed.pod_url != pod_url {
155            return Err(CliError::Refused(format!(
156                "the confirmation names {} at {}, not {me} at {pod_url}",
157                confirmed.did,
158                sanitize(&confirmed.pod_url)
159            )));
160        }
161        if confirmed.state != MemberState::Active {
162            return Err(CliError::Refused(format!(
163                "the node reports the member {} after confirming, not active",
164                confirmed.state
165            )));
166        }
167        self.output().json(&json!({
168            "joined": true,
169            "did": me,
170            "node": options.node,
171            "origin": target.origin().as_str(),
172            "invitation": options.invitation,
173            "operation_id": operation.operation_id,
174            "state": confirmed.state,
175            "pod_url": pod_url,
176            "redeemed": progress.redeemed,
177            "resent": progress.resent,
178            "probe": {"path": probe, "sha256": probe_sha256},
179        }))?;
180        self.output().line(&format!("member: {me}"))?;
181        self.output().line("state: active")?;
182        self.output().line(&format!("pod: {pod_url}"))?;
183        Ok(exit::OK)
184    }
185
186    /// Shows the notice before asking.
187    fn show_notice(&self, notice: &NoticeResponse) -> Result<(), CliError> {
188        self.output().note(&format!(
189            "admission notice from {} (sha256 {}):",
190            notice.node, notice.notice_sha256
191        ))?;
192        self.output().note("")?;
193        self.output().note(&sanitize(&notice.notice))?;
194        self.output().note("")
195    }
196
197    /// Step 3: redeems, resending the identical request once if the
198    /// response is lost.
199    fn redeem(
200        &self,
201        gate: &GateClient,
202        key: &NostrSecretKey,
203        options: &JoinOptions,
204        progress: &mut Progress,
205    ) -> Result<OperationResponse, CliError> {
206        let claim = AdmissionClaim::new(AdmissionFields {
207            node: options.node,
208            subject: key.public(),
209            invitation: options.invitation,
210            notice_sha256: admission_notice_v1_sha256(),
211        });
212        let request = Request::new("POST", REDEEM, JSON).with_body(claim.as_bytes(), JSON);
213        let authorization = gate.sign(key, &request)?;
214        let response = match gate.fetch_with(&request, Some(&authorization), MAX_RESPONSE_BYTES) {
215            Err(CliError::Unreachable { message, .. }) => {
216                self.output().note(&format!(
217                    "the redemption response was lost ({message}); resending the identical \
218                     signed request once"
219                ))?;
220                progress.resent = true;
221                gate.fetch_with(&request, Some(&authorization), MAX_RESPONSE_BYTES)?
222            }
223            other => other?,
224        };
225        let (operation, _raw): (OperationResponse, Json) = response.into_json(Route::Admission)?;
226        if operation.state == MemberState::Cancelled {
227            return Err(cancelled());
228        }
229        Ok(operation)
230    }
231
232    /// Step 4: polls until the member is provisioned.
233    fn wait_provisioned(
234        &self,
235        gate: &GateClient,
236        key: &NostrSecretKey,
237        pod_url: &str,
238        wait: Duration,
239    ) -> Result<OperationResponse, CliError> {
240        let deadline = Instant::now() + wait;
241        let mut interval = FIRST_POLL_INTERVAL;
242        let mut shown_error: Option<String> = None;
243        loop {
244            let now = Instant::now();
245            if now >= deadline {
246                let last = shown_error
247                    .map(|err| format!("; the node's last error: {err}"))
248                    .unwrap_or_default();
249                return Err(CliError::TimedOut(format!(
250                    "the pod was not provisioned within {} s{last}; rerun the same join command \
251                     to continue",
252                    wait.as_secs()
253                )));
254            }
255            thread::sleep(interval.min(deadline - now));
256            interval = (interval * 2).min(MAX_POLL_INTERVAL);
257            let (operation, _raw): (OperationResponse, Json) = gate
258                .fetch(
259                    &Request::new("GET", OPERATION, JSON),
260                    Some(key),
261                    MAX_RESPONSE_BYTES,
262                )?
263                .into_json(Route::Admission)?;
264            check_operation(&operation, key.public(), pod_url)?;
265            if let Some(err) = &operation.last_error {
266                let err = sanitize(err);
267                if shown_error.as_deref() != Some(err.as_str()) {
268                    self.output()
269                        .note(&format!("the node reports a provisioning error: {err}"))?;
270                    shown_error = Some(err);
271                }
272            }
273            match operation.state {
274                MemberState::Provisioned | MemberState::Active => return Ok(operation),
275                MemberState::Cancelled => return Err(cancelled()),
276                _ => {}
277            }
278        }
279    }
280
281    /// Step 5: writes, reads back and deletes a probe resource; returns its
282    /// path and the SHA-256 of what was written.
283    fn probe(
284        &self,
285        gate: &GateClient,
286        key: &NostrSecretKey,
287        me: &DidNostr,
288    ) -> Result<(PodPath, Sha256Digest), CliError> {
289        let random = client::random_32()?;
290        let name = format!("{PROBE_PREFIX}{}", hex::encode(&random[..8]));
291        let path = PodPath::pod_root(me)
292            .join(&name)
293            .map_err(|err| CliError::Local(format!("probe path: {err}")))?;
294        let content = format!("stratum join probe {}\n", hex::encode(&random[8..24]));
295        let written = Sha256Digest::of(content.as_bytes());
296
297        let put = gate.fetch(
298            &Request::new("PUT", path.as_str(), ANY)
299                .with_body(content.as_bytes(), "text/plain")
300                .with_precondition(Precondition::CreateOnly),
301            Some(key),
302            MAX_RESPONSE_BYTES,
303        )?;
304        if !put.head.is_success() {
305            return Err(put.into_error(Route::Pod));
306        }
307        let get = gate.fetch(
308            &Request::new("GET", path.as_str(), ANY),
309            Some(key),
310            MAX_RESPONSE_BYTES,
311        )?;
312        if !get.head.is_success() {
313            return Err(get.into_error(Route::Pod));
314        }
315        if get.body != content.as_bytes() {
316            return Err(CliError::Refused(format!(
317                "the probe {path} read back {} bytes that differ from the {} written",
318                get.body.len(),
319                content.len()
320            )));
321        }
322        let delete = gate.fetch(
323            &Request::new("DELETE", path.as_str(), ANY),
324            Some(key),
325            MAX_RESPONSE_BYTES,
326        )?;
327        if !delete.head.is_success() {
328            return Err(delete.into_error(Route::Pod));
329        }
330        self.output()
331            .note(&format!("probe {path} written, read back and deleted"))?;
332        Ok((path, written))
333    }
334}
335
336/// Step 1: fetches and checks the notice.
337fn fetch_notice(gate: &GateClient, options: &JoinOptions) -> Result<NoticeResponse, CliError> {
338    let (notice, _raw): (NoticeResponse, Json) = gate
339        .fetch(&Request::new("GET", NOTICE, JSON), None, MAX_RESPONSE_BYTES)?
340        .into_json(Route::Admission)?;
341    if notice.node != options.node {
342        return Err(CliError::Refused(format!(
343            "the node at this origin is {}, not {} named by the invitation",
344            notice.node, options.node
345        )));
346    }
347    let origin = gate.target().origin().as_str();
348    if notice.origin != origin {
349        return Err(CliError::Refused(format!(
350            "the node reports its origin as {}, not {origin}",
351            sanitize(&notice.origin)
352        )));
353    }
354    let received = Sha256Digest::of(notice.notice.as_bytes());
355    if received != notice.notice_sha256 {
356        return Err(CliError::Refused(format!(
357            "the notice text hashes to {received}, not to the {} the node reports",
358            notice.notice_sha256
359        )));
360    }
361    let known = admission_notice_v1_sha256();
362    if received != known {
363        return Err(CliError::Refused(format!(
364            "the node's notice (sha256 {received}) is not the admission notice this client \
365             knows (sha256 {known}); nothing was signed"
366        )));
367    }
368    Ok(notice)
369}
370
371/// Step 2: the caller's own operation, or `None` when the node does not
372/// know the caller as a member.
373fn own_operation(
374    gate: &GateClient,
375    key: &NostrSecretKey,
376) -> Result<Option<OperationResponse>, CliError> {
377    let response = gate.fetch(
378        &Request::new("GET", OPERATION, JSON),
379        Some(key),
380        MAX_RESPONSE_BYTES,
381    )?;
382    // A caller who is not a member holds a valid signature and is refused
383    // by the route (403 or 404); a 401 means the request itself was refused
384    // (clock, replay, signature) and is reported as such.
385    if matches!(response.head.status, 403 | 404) {
386        return Ok(None);
387    }
388    let (operation, _raw): (OperationResponse, Json) = response.into_json(Route::Admission)?;
389    if operation.state == MemberState::Cancelled {
390        return Err(cancelled());
391    }
392    Ok(Some(operation))
393}
394
395/// Checks that an operation names the caller and the caller's pod URL (or,
396/// while `reserved`, no URL yet).
397fn check_operation(
398    operation: &OperationResponse,
399    me: DidNostr,
400    pod_url: &str,
401) -> Result<(), CliError> {
402    if operation.did != me {
403        return Err(CliError::Refused(format!(
404            "the node answered with the operation of {}, not of {me}",
405            operation.did
406        )));
407    }
408    // A member still `reserved` has no pod yet; the node may leave the URL
409    // empty until it does.
410    let pending = operation.state == MemberState::Reserved && operation.pod_url.is_empty();
411    if operation.pod_url != pod_url && !pending {
412        return Err(CliError::Refused(format!(
413            "the node reports pod url {}, not {pod_url}",
414            sanitize(&operation.pod_url)
415        )));
416    }
417    Ok(())
418}
419
420/// The error for a cancelled membership.
421fn cancelled() -> CliError {
422    CliError::Refused(
423        "the administrator cancelled this membership; ask them for a new invitation".to_owned(),
424    )
425}