stratum-node-cli 0.1.0-alpha.2

The `stratum` client for Stratum pod nodes: operator key files, bootstrap, config, backup, invitations and members over the loopback API; join, pod access and export for tenants through the gate
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
//! `stratum join`: redeeming an invitation and activating the pod.

use std::thread;
use std::time::{Duration, Instant};

use serde_json::{json, Value as Json};
use stratum_node_core::{
    admission_notice_v1_sha256, AdmissionClaim, AdmissionFields, DidNostr, InvitationId,
    MemberState, NostrSecretKey, PodPath, Sha256Digest,
};

use crate::client::{self, MAX_RESPONSE_BYTES};
use crate::error::CliError;
use crate::exit;
use crate::gate::{GateClient, Precondition, Request, Route, ANY, JSON};
use crate::origin::GateTarget;
use crate::output::sanitize;
use crate::session::{to_body, Confirmation, Session};
use crate::wire::{ConfirmRequest, ConfirmResponse, NoticeResponse, OperationResponse};

/// `GET` route: the admission notice.
const NOTICE: &str = "/api/v1/admission/notice";
/// `POST` route: redeem an invitation.
const REDEEM: &str = "/api/v1/admission/redeem";
/// `GET` route: the caller's own provisioning operation.
const OPERATION: &str = "/api/v1/admission/operation";
/// `POST` route: confirm that the pod works.
const CONFIRM: &str = "/api/v1/admission/confirm";

/// The default time `join` waits for the pod to be provisioned.
pub const DEFAULT_WAIT: Duration = Duration::from_secs(120);

/// The first pause between polls of the operation; it doubles up to
/// [`MAX_POLL_INTERVAL`].
const FIRST_POLL_INTERVAL: Duration = Duration::from_millis(250);
/// The longest pause between polls of the operation.
const MAX_POLL_INTERVAL: Duration = Duration::from_secs(2);

/// The name prefix of the probe resource written in the new pod. It starts
/// with a letter: the pod server refuses names that start with a dot.
const PROBE_PREFIX: &str = "stratum-join-probe-";

/// Options for [`Session::join`].
#[derive(Debug, Clone)]
pub struct JoinOptions {
    /// The invitation the administrator issued (`--invitation`).
    pub invitation: InvitationId,
    /// The node DID the invitation names (`--node`); the node reached must
    /// report it.
    pub node: DidNostr,
    /// How long to wait for the node to provision the pod (`--wait-secs`).
    pub wait: Duration,
    /// Whether to ask before redeeming.
    pub confirmation: Confirmation,
}

/// What a `join` run did, for the report.
#[derive(Debug, Default)]
struct Progress {
    redeemed: bool,
    resent: bool,
}

impl Session {
    /// `stratum join --invitation <id> --node <did> --origin … [--connect …]`:
    /// redeems an invitation with the caller's key and activates the pod.
    ///
    /// The flow:
    ///
    /// 1. Fetch the admission notice. The node DID it reports must be
    ///    [`JoinOptions::node`], its origin the canonical origin, and the
    ///    SHA-256 of the notice text received must equal both the hash the
    ///    node reports and the hash of the notice this client was built
    ///    with ([`admission_notice_v1_sha256`]).
    /// 2. Ask for the caller's own operation. A caller who is already a
    ///    member (`reserved`, `provisioned` or `active`) continues from
    ///    where an earlier run stopped, without redeeming again.
    /// 3. Otherwise show the notice and ask for confirmation (a terminal is
    ///    required unless `--yes`), then redeem with the admission claim
    ///    signed by the caller. If the connection fails after the request
    ///    was sent, the identical signed request is resent once: the node
    ///    returns the response it stored.
    /// 4. Poll the operation until the member is `provisioned`, for at most
    ///    [`JoinOptions::wait`], showing the node's last error when it
    ///    reports one.
    /// 5. Write a probe resource in the pod (create only), read it back and
    ///    compare, and delete it.
    /// 6. Confirm, and print the pod URL.
    ///
    /// Every request is signed with a fresh event over the canonical URL;
    /// only the single resend reuses one. Every pod URL the node reports must
    /// be exactly `<origin>/pods/<caller's key>/`.
    ///
    /// # Errors
    ///
    /// [`CliError::Refused`] for a notice from another node or with another
    /// hash, a cancelled membership, a response naming another member or pod
    /// URL, or a probe that does not read back; [`CliError::NotConfirmed`];
    /// [`CliError::TimedOut`] when provisioning does not finish in time
    /// (rerun `join` to continue); and key, transport and server errors
    /// (`invitation_refused`, `invitations_disabled`, `capacity_exhausted`,
    /// `too_many_requests` among them).
    pub fn join(&self, target: &GateTarget, options: &JoinOptions) -> Result<u8, CliError> {
        let key = self.key()?;
        let me = key.public();
        let gate = GateClient::new(target.clone());
        let pod_url = target.origin().url(PodPath::pod_root(&me).as_str());
        let notice = fetch_notice(&gate, options)?;

        let mut progress = Progress::default();
        let mut operation = if let Some(operation) = own_operation(&gate, &key)? {
            self.output().note(&format!(
                "{me} is already a member of this node ({}); continuing",
                operation.state
            ))?;
            operation
        } else {
            self.show_notice(&notice)?;
            if !self.confirmed(
                "join this node, accepting the notice above?",
                options.confirmation,
            )? {
                self.output().json(&json!({"joined": false}))?;
                return Err(CliError::NotConfirmed);
            }
            let operation = self.redeem(&gate, &key, options, &mut progress)?;
            progress.redeemed = true;
            operation
        };
        check_operation(&operation, me, &pod_url)?;
        self.output().note(&format!(
            "operation {}: {}",
            operation.operation_id, operation.state
        ))?;
        if !matches!(
            operation.state,
            MemberState::Provisioned | MemberState::Active
        ) {
            operation = self.wait_provisioned(&gate, &key, &pod_url, options.wait)?;
        }

        let (probe, probe_sha256) = self.probe(&gate, &key, &me)?;
        let body = to_body(&ConfirmRequest {
            node: options.node,
            operation_id: &operation.operation_id,
        })?;
        let (confirmed, _raw): (ConfirmResponse, Json) = gate
            .fetch(
                &Request::new("POST", CONFIRM, JSON).with_body(&body, JSON),
                Some(&key),
                MAX_RESPONSE_BYTES,
            )?
            .into_json(Route::Admission)?;
        if confirmed.did != me || confirmed.pod_url != pod_url {
            return Err(CliError::Refused(format!(
                "the confirmation names {} at {}, not {me} at {pod_url}",
                confirmed.did,
                sanitize(&confirmed.pod_url)
            )));
        }
        if confirmed.state != MemberState::Active {
            return Err(CliError::Refused(format!(
                "the node reports the member {} after confirming, not active",
                confirmed.state
            )));
        }
        self.output().json(&json!({
            "joined": true,
            "did": me,
            "node": options.node,
            "origin": target.origin().as_str(),
            "invitation": options.invitation,
            "operation_id": operation.operation_id,
            "state": confirmed.state,
            "pod_url": pod_url,
            "redeemed": progress.redeemed,
            "resent": progress.resent,
            "probe": {"path": probe, "sha256": probe_sha256},
        }))?;
        self.output().line(&format!("member: {me}"))?;
        self.output().line("state: active")?;
        self.output().line(&format!("pod: {pod_url}"))?;
        Ok(exit::OK)
    }

    /// Shows the notice before asking.
    fn show_notice(&self, notice: &NoticeResponse) -> Result<(), CliError> {
        self.output().note(&format!(
            "admission notice from {} (sha256 {}):",
            notice.node, notice.notice_sha256
        ))?;
        self.output().note("")?;
        self.output().note(&sanitize(&notice.notice))?;
        self.output().note("")
    }

    /// Step 3: redeems, resending the identical request once if the
    /// response is lost.
    fn redeem(
        &self,
        gate: &GateClient,
        key: &NostrSecretKey,
        options: &JoinOptions,
        progress: &mut Progress,
    ) -> Result<OperationResponse, CliError> {
        let claim = AdmissionClaim::new(AdmissionFields {
            node: options.node,
            subject: key.public(),
            invitation: options.invitation,
            notice_sha256: admission_notice_v1_sha256(),
        });
        let request = Request::new("POST", REDEEM, JSON).with_body(claim.as_bytes(), JSON);
        let authorization = gate.sign(key, &request)?;
        let response = match gate.fetch_with(&request, Some(&authorization), MAX_RESPONSE_BYTES) {
            Err(CliError::Unreachable { message, .. }) => {
                self.output().note(&format!(
                    "the redemption response was lost ({message}); resending the identical \
                     signed request once"
                ))?;
                progress.resent = true;
                gate.fetch_with(&request, Some(&authorization), MAX_RESPONSE_BYTES)?
            }
            other => other?,
        };
        let (operation, _raw): (OperationResponse, Json) = response.into_json(Route::Admission)?;
        if operation.state == MemberState::Cancelled {
            return Err(cancelled());
        }
        Ok(operation)
    }

    /// Step 4: polls until the member is provisioned.
    fn wait_provisioned(
        &self,
        gate: &GateClient,
        key: &NostrSecretKey,
        pod_url: &str,
        wait: Duration,
    ) -> Result<OperationResponse, CliError> {
        let deadline = Instant::now() + wait;
        let mut interval = FIRST_POLL_INTERVAL;
        let mut shown_error: Option<String> = None;
        loop {
            let now = Instant::now();
            if now >= deadline {
                let last = shown_error
                    .map(|err| format!("; the node's last error: {err}"))
                    .unwrap_or_default();
                return Err(CliError::TimedOut(format!(
                    "the pod was not provisioned within {} s{last}; rerun the same join command \
                     to continue",
                    wait.as_secs()
                )));
            }
            thread::sleep(interval.min(deadline - now));
            interval = (interval * 2).min(MAX_POLL_INTERVAL);
            let (operation, _raw): (OperationResponse, Json) = gate
                .fetch(
                    &Request::new("GET", OPERATION, JSON),
                    Some(key),
                    MAX_RESPONSE_BYTES,
                )?
                .into_json(Route::Admission)?;
            check_operation(&operation, key.public(), pod_url)?;
            if let Some(err) = &operation.last_error {
                let err = sanitize(err);
                if shown_error.as_deref() != Some(err.as_str()) {
                    self.output()
                        .note(&format!("the node reports a provisioning error: {err}"))?;
                    shown_error = Some(err);
                }
            }
            match operation.state {
                MemberState::Provisioned | MemberState::Active => return Ok(operation),
                MemberState::Cancelled => return Err(cancelled()),
                _ => {}
            }
        }
    }

    /// Step 5: writes, reads back and deletes a probe resource; returns its
    /// path and the SHA-256 of what was written.
    fn probe(
        &self,
        gate: &GateClient,
        key: &NostrSecretKey,
        me: &DidNostr,
    ) -> Result<(PodPath, Sha256Digest), CliError> {
        let random = client::random_32()?;
        let name = format!("{PROBE_PREFIX}{}", hex::encode(&random[..8]));
        let path = PodPath::pod_root(me)
            .join(&name)
            .map_err(|err| CliError::Local(format!("probe path: {err}")))?;
        let content = format!("stratum join probe {}\n", hex::encode(&random[8..24]));
        let written = Sha256Digest::of(content.as_bytes());

        let put = gate.fetch(
            &Request::new("PUT", path.as_str(), ANY)
                .with_body(content.as_bytes(), "text/plain")
                .with_precondition(Precondition::CreateOnly),
            Some(key),
            MAX_RESPONSE_BYTES,
        )?;
        if !put.head.is_success() {
            return Err(put.into_error(Route::Pod));
        }
        let get = gate.fetch(
            &Request::new("GET", path.as_str(), ANY),
            Some(key),
            MAX_RESPONSE_BYTES,
        )?;
        if !get.head.is_success() {
            return Err(get.into_error(Route::Pod));
        }
        if get.body != content.as_bytes() {
            return Err(CliError::Refused(format!(
                "the probe {path} read back {} bytes that differ from the {} written",
                get.body.len(),
                content.len()
            )));
        }
        let delete = gate.fetch(
            &Request::new("DELETE", path.as_str(), ANY),
            Some(key),
            MAX_RESPONSE_BYTES,
        )?;
        if !delete.head.is_success() {
            return Err(delete.into_error(Route::Pod));
        }
        self.output()
            .note(&format!("probe {path} written, read back and deleted"))?;
        Ok((path, written))
    }
}

/// Step 1: fetches and checks the notice.
fn fetch_notice(gate: &GateClient, options: &JoinOptions) -> Result<NoticeResponse, CliError> {
    let (notice, _raw): (NoticeResponse, Json) = gate
        .fetch(&Request::new("GET", NOTICE, JSON), None, MAX_RESPONSE_BYTES)?
        .into_json(Route::Admission)?;
    if notice.node != options.node {
        return Err(CliError::Refused(format!(
            "the node at this origin is {}, not {} named by the invitation",
            notice.node, options.node
        )));
    }
    let origin = gate.target().origin().as_str();
    if notice.origin != origin {
        return Err(CliError::Refused(format!(
            "the node reports its origin as {}, not {origin}",
            sanitize(&notice.origin)
        )));
    }
    let received = Sha256Digest::of(notice.notice.as_bytes());
    if received != notice.notice_sha256 {
        return Err(CliError::Refused(format!(
            "the notice text hashes to {received}, not to the {} the node reports",
            notice.notice_sha256
        )));
    }
    let known = admission_notice_v1_sha256();
    if received != known {
        return Err(CliError::Refused(format!(
            "the node's notice (sha256 {received}) is not the admission notice this client \
             knows (sha256 {known}); nothing was signed"
        )));
    }
    Ok(notice)
}

/// Step 2: the caller's own operation, or `None` when the node does not
/// know the caller as a member.
fn own_operation(
    gate: &GateClient,
    key: &NostrSecretKey,
) -> Result<Option<OperationResponse>, CliError> {
    let response = gate.fetch(
        &Request::new("GET", OPERATION, JSON),
        Some(key),
        MAX_RESPONSE_BYTES,
    )?;
    // A caller who is not a member holds a valid signature and is refused
    // by the route (403 or 404); a 401 means the request itself was refused
    // (clock, replay, signature) and is reported as such.
    if matches!(response.head.status, 403 | 404) {
        return Ok(None);
    }
    let (operation, _raw): (OperationResponse, Json) = response.into_json(Route::Admission)?;
    if operation.state == MemberState::Cancelled {
        return Err(cancelled());
    }
    Ok(Some(operation))
}

/// Checks that an operation names the caller and the caller's pod URL (or,
/// while `reserved`, no URL yet).
fn check_operation(
    operation: &OperationResponse,
    me: DidNostr,
    pod_url: &str,
) -> Result<(), CliError> {
    if operation.did != me {
        return Err(CliError::Refused(format!(
            "the node answered with the operation of {}, not of {me}",
            operation.did
        )));
    }
    // A member still `reserved` has no pod yet; the node may leave the URL
    // empty until it does.
    let pending = operation.state == MemberState::Reserved && operation.pod_url.is_empty();
    if operation.pod_url != pod_url && !pending {
        return Err(CliError::Refused(format!(
            "the node reports pod url {}, not {pod_url}",
            sanitize(&operation.pod_url)
        )));
    }
    Ok(())
}

/// The error for a cancelled membership.
fn cancelled() -> CliError {
    CliError::Refused(
        "the administrator cancelled this membership; ask them for a new invitation".to_owned(),
    )
}