stratum-node-cli 0.1.0-alpha.4

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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
//! `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, profile_card_path, 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::{self, GateClient, Precondition, Request, Route, ANY, JSON};
use crate::origin::GateTarget;
use crate::output::sanitize;
use crate::profile::{self, CardOutcome, Conflicting};
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. A
    ///    `suspended` member stops here. A `removed` or `cancelled` key is
    ///    not a member: it goes on to redeem the new invitation, and the
    ///    node decides (`pod_data_present` until its old pod data is
    ///    purged).
    /// 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. Write the public profile document while the member is still
    ///    `provisioned`: the card `/pods/<pk>/profile/card` and then its ACL
    ///    `/pods/<pk>/profile/card.acl`, each read first and created with
    ///    `If-None-Match: *` only when missing, so a resumed run neither
    ///    fails nor writes twice. An existing card that names the caller is
    ///    left alone; one that does not is reported and left alone, with no
    ///    ACL written, and the join continues (`stratum profile init
    ///    --replace` fixes it later). See [`Session::profile_init`].
    /// 7. 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 membership cancelled or removed while joining, 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`, `suspended`, `pod_data_present` and
    /// `insufficient_storage` 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, options.wait)?;
        let profile = profile::ensure_profile(&gate, &key, Conflicting::Report)?;
        let card_path = profile_card_path(&me);
        profile.note(*self.output(), &card_path)?;
        if matches!(profile.card, CardOutcome::Conflict(_)) {
            self.output().note(
                "the join continues; run `stratum profile init --replace` to replace that card \
                 with the standard one",
            )?;
        }
        let card_acl = card_path
            .acl_path()
            .ok_or_else(|| CliError::Local("the profile card has no ACL path".to_owned()))?;
        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},
            "profile": profile.to_json(&card_path, &card_acl),
        }))?;
        self.output().line(&format!("member: {me}"))?;
        self.output().line("state: active")?;
        self.output().line(&format!("pod: {pod_url}"))?;
        self.output().line(&format!(
            "profile: {}",
            target.origin().url(card_path.as_str())
        ))?;
        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()),
                MemberState::Suspended => return Err(suspended()),
                MemberState::Removed => return Err(removed()),
                _ => {}
            }
        }
    }

    /// Step 5: writes, reads back and deletes a probe resource; returns its
    /// path and the SHA-256 of what was written.
    ///
    /// Retries the initial `PUT` briefly on `403 forbidden` so a gate whose
    /// member-directory long-poll is still catching up after provisioning
    /// does not turn a completed provision into a spurious failure.
    fn probe(
        &self,
        gate: &GateClient,
        key: &NostrSecretKey,
        me: &DidNostr,
        wait: Duration,
    ) -> 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 deadline = Instant::now() + wait.min(Duration::from_secs(5));
        let mut interval = Duration::from_millis(50);
        loop {
            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() {
                break;
            }
            let err = put.into_error(Route::Pod);
            let now = Instant::now();
            if matches!(&err, CliError::Server { status: 403, code, .. } if code == "forbidden")
                && now < deadline
            {
                thread::sleep(interval.min(deadline - now));
                interval = (interval * 2).min(Duration::from_millis(500));
                continue;
            }
            return Err(err);
        }
        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 suspended member is refused 403 `suspended`: say so now, rather
    // than show the notice and have the redemption refused after a prompt.
    if response.head.status == 403
        && gate::envelope_code(&response.body).as_deref() == Some(gate::SUSPENDED)
    {
        return Err(response.into_error(Route::Admission));
    }
    // 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)?;
    match operation.state {
        MemberState::Suspended => Err(suspended()),
        // An ended membership is not a membership: a removed or cancelled
        // key may hold a new invitation, so the join goes on to redeem it
        // and the node decides (`pod_data_present` until the old data is
        // purged, `forbidden` for an invitation already used).
        MemberState::Cancelled | MemberState::Removed => Ok(None),
        _ => 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 suspended membership.
fn suspended() -> CliError {
    CliError::Refused(
        "the administrator has suspended this membership; nothing can be done with this key on \
         this node until they resume it"
            .to_owned(),
    )
}

/// The error for a removed membership.
fn removed() -> CliError {
    CliError::Refused(
        "the administrator removed this membership; ask them for a new invitation, which they \
         can issue once the old pod data has been purged"
            .to_owned(),
    )
}

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