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