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
//! `stratum invite …` and `stratum member …`: the administrator's
//! membership commands on the loopback API.

use std::time::Duration;

use serde_json::{json, Value as Json};
use stratum_node_config::ConfigDocument;
use stratum_node_core::{DidNostr, InvitationId, MemberState};

use crate::client::Client;
use crate::error::CliError;
use crate::exit;
use crate::origin::{CanonicalOrigin, ConnectAddress, Scheme};
use crate::output::sanitize;
use crate::session::{check_expected_node, operation_id, readyz, to_body, Confirmation, Session};
use crate::wire::{
    ConfigResponse, InvitationList, InviteRequest, InviteResponse, MemberActionResponse,
    MemberList, OperationRequest, RevokeResponse,
};

/// `POST` and `GET` route: invitations.
const INVITATIONS: &str = "/api/v1/invitations";
/// `GET` route: members.
const MEMBERS: &str = "/api/v1/members";
/// `GET` route: the effective configuration, for the default invitation
/// lifetime.
const CONFIG: &str = "/api/v1/config";

/// The longest invitation lifetime the node accepts: 30 days.
pub const MAX_INVITATION_LIFETIME: Duration = Duration::from_secs(30 * 24 * 60 * 60);

/// The connect address printed in the invitee's command line when none is
/// given: the gate's default loopback port.
const DEFAULT_GATE_CONNECT: &str = "127.0.0.1:7461";

/// Options for [`Session::invite_create`].
#[derive(Debug, Clone)]
pub struct InviteOptions {
    /// The identity invited (`<did>`).
    pub subject: DidNostr,
    /// The invitation's lifetime (`--expires-in`); the node's
    /// `membership.invitation_ttl_secs` when `None`.
    pub expires_in: Option<Duration>,
    /// The operation ID; random when `None`.
    pub operation_id: Option<String>,
    /// Refuse unless `/readyz` reports this node DID (`--expect-node`).
    pub expect_node: Option<DidNostr>,
    /// The gate address the invitee should connect to, printed in the
    /// `stratum join` command line (`--connect`); `127.0.0.1:7461` when `None`.
    /// Not used when the canonical origin is itself a loopback `http://`
    /// address.
    pub gate: Option<ConnectAddress>,
}

/// Parses a duration written as a whole number of seconds, or a number
/// followed by `s`, `m`, `h` or `d`.
///
/// # Examples
///
/// ```
/// use std::time::Duration;
/// use stratum_node_cli::parse_duration;
///
/// assert_eq!(parse_duration("7d"), Ok(Duration::from_secs(7 * 86_400)));
/// assert_eq!(parse_duration("90m"), Ok(Duration::from_secs(5_400)));
/// assert_eq!(parse_duration("3600"), Ok(Duration::from_secs(3_600)));
/// assert!(parse_duration("1w").is_err());
/// ```
///
/// # Errors
///
/// A message naming the accepted forms when `text` is none of them.
pub fn parse_duration(text: &str) -> Result<Duration, String> {
    let fail = || format!("{text:?} is not a duration: use seconds, or a number with s, m, h or d");
    let (digits, unit) = match text.char_indices().last() {
        Some((index, c)) if c.is_ascii_alphabetic() => (&text[..index], c),
        _ => (text, 's'),
    };
    if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) {
        return Err(fail());
    }
    let count: u64 = digits.parse().map_err(|_| fail())?;
    let scale: u64 = match unit {
        's' => 1,
        'm' => 60,
        'h' => 3_600,
        'd' => 86_400,
        _ => return Err(fail()),
    };
    count
        .checked_mul(scale)
        .map(Duration::from_secs)
        .ok_or_else(fail)
}

impl Session {
    /// `stratum invite create <did> [--expires-in <duration>]`: issues an
    /// invitation for one identity and prints its identifier, subject,
    /// expiry, the canonical origin and node DID, and the `stratum join`
    /// command line the invitee runs. Signed by the administrator.
    ///
    /// Without `--expires-in` the lifetime is the node's configured
    /// `membership.invitation_ttl_secs`, read from the effective
    /// configuration. The response must name the requested subject and the
    /// node `/readyz` reported.
    ///
    /// # Errors
    ///
    /// [`CliError::Usage`] for a lifetime over 30 days or under one second,
    /// [`CliError::Refused`] when the response names another subject or
    /// node, and key, transport, protocol and server errors
    /// (`invitations_disabled` among them).
    pub fn invite_create(&self, options: &InviteOptions) -> Result<u8, CliError> {
        if let Some(lifetime) = options.expires_in {
            if lifetime > MAX_INVITATION_LIFETIME || lifetime.is_zero() {
                return Err(CliError::Usage(
                    "--expires-in must be between 1 second and 30 days".to_owned(),
                ));
            }
        }
        let operation_id = operation_id(options.operation_id.as_deref())?;
        let key = self.key()?;
        let client = self.client()?;
        let ready = readyz(&client)?;
        check_expected_node(ready.node_did, options.expect_node.as_ref())?;
        let expires_in = match options.expires_in {
            Some(lifetime) => lifetime.as_secs(),
            None => configured_lifetime(&client, &key)?,
        };
        self.output().note(&format!(
            "operation id: {operation_id} (to retry after a lost response, pass --operation-id {operation_id})"
        ))?;
        let body = to_body(&InviteRequest {
            node: ready.node_did,
            operation_id: &operation_id,
            subject: options.subject,
            expires_in,
        })?;
        let (invite, _raw): (InviteResponse, Json) =
            client.post(INVITATIONS, &body, Some(&key))?.into_json()?;
        if invite.subject != options.subject || invite.node != ready.node_did {
            return Err(CliError::Refused(format!(
                "the node issued an invitation for {} on {}, not for {} on {}",
                invite.subject, invite.node, options.subject, ready.node_did
            )));
        }
        let origin: CanonicalOrigin = invite.origin.parse().map_err(|err| {
            CliError::Protocol(format!(
                "the invitation names origin {}: {err}",
                sanitize(&invite.origin)
            ))
        })?;
        let command = join_command(
            &invite.invitation,
            &invite.node,
            &origin,
            options.gate.as_ref(),
        );
        self.output().json(&json!({
            "operation_id": operation_id.as_str(),
            "invitation": invite.invitation,
            "subject": invite.subject,
            "expires_at": invite.expires_at,
            "origin": origin.as_str(),
            "node": invite.node,
            "join_command": command,
        }))?;
        self.output()
            .line(&format!("invitation: {}", invite.invitation))?;
        self.output()
            .line(&format!("subject: {}", invite.subject))?;
        self.output()
            .line(&format!("expires at: {} (unix time)", invite.expires_at))?;
        self.output().line(&format!("origin: {origin}"))?;
        self.output().line(&format!("node: {}", invite.node))?;
        self.output()
            .line("the invitee runs, with their own key in --key-file or STRATUM_KEY_FILE:")?;
        self.output().line(&format!("  {command}"))?;
        Ok(exit::OK)
    }

    /// `stratum invite list`: lists invitations with their state. Signed.
    ///
    /// # Errors
    ///
    /// Key, transport, protocol and server errors.
    pub fn invite_list(&self) -> Result<u8, CliError> {
        let key = self.key()?;
        let client = self.client()?;
        let (list, raw): (InvitationList, Json) =
            client.get(INVITATIONS, Some(&key))?.into_json()?;
        self.output().json(&raw)?;
        if list.invitations.is_empty() {
            self.output().line("no invitations")?;
        }
        for entry in &list.invitations {
            self.output().line(&format!(
                "{}  {:<8}  {}  issued {}  expires {}",
                entry.invitation,
                sanitize(&entry.state),
                entry.subject,
                entry.issued_at,
                entry.expires_at
            ))?;
        }
        Ok(exit::OK)
    }

    /// `stratum invite revoke <invitation>`: revokes an invitation that is
    /// still `issued`. Signed.
    ///
    /// # Errors
    ///
    /// [`CliError::Refused`] when the response names another invitation or
    /// state, and key, transport, protocol and server errors.
    pub fn invite_revoke(
        &self,
        invitation: &InvitationId,
        operation_id_arg: Option<&str>,
    ) -> Result<u8, CliError> {
        let operation_id = operation_id(operation_id_arg)?;
        let key = self.key()?;
        let client = self.client()?;
        let ready = readyz(&client)?;
        let body = to_body(&OperationRequest {
            node: ready.node_did,
            operation_id: &operation_id,
        })?;
        let path = format!("{INVITATIONS}/{invitation}/revoke");
        let (revoked, _raw): (RevokeResponse, Json) =
            client.post(&path, &body, Some(&key))?.into_json()?;
        if revoked.invitation != *invitation || revoked.state != "revoked" {
            return Err(CliError::Refused(format!(
                "the node reports invitation {} as {}, not {invitation} as revoked",
                revoked.invitation,
                sanitize(&revoked.state)
            )));
        }
        self.output().json(&json!({
            "operation_id": operation_id.as_str(),
            "invitation": revoked.invitation,
            "state": "revoked",
        }))?;
        self.output()
            .line(&format!("invitation {invitation}: revoked"))?;
        Ok(exit::OK)
    }

    /// `stratum member list`: lists members with their state, pod URL and
    /// the last provisioning error, and the capacity in use. Signed.
    ///
    /// # Errors
    ///
    /// Key, transport, protocol and server errors.
    pub fn member_list(&self) -> Result<u8, CliError> {
        let key = self.key()?;
        let client = self.client()?;
        let (list, raw): (MemberList, Json) = client.get(MEMBERS, Some(&key))?.into_json()?;
        self.output().json(&raw)?;
        self.output().line(&format!(
            "capacity: {} of {} used",
            list.used, list.capacity
        ))?;
        for member in &list.members {
            self.output().line(&format!(
                "{}  {:<11}  {}",
                member.did,
                member.state,
                sanitize(&member.pod_url)
            ))?;
            self.output().line(&format!(
                "    operation {}, reserved {}, activated {}",
                sanitize(&member.operation_id),
                member.reserved_at,
                member
                    .activated_at
                    .map_or_else(|| "never".to_owned(), |t| t.to_string())
            ))?;
            if let Some(err) = &member.last_error {
                self.output()
                    .line(&format!("    last error: {}", sanitize(err)))?;
            }
        }
        Ok(exit::OK)
    }

    /// `stratum member repair <did> [--yes]`: runs provisioning again for a
    /// member, which restores a missing root ACL and leaves an existing one
    /// alone. Asks first. Signed.
    ///
    /// # Errors
    ///
    /// [`CliError::NotConfirmed`], [`CliError::Refused`] when the response
    /// names another member, and key, transport, protocol and server errors.
    pub fn member_repair(
        &self,
        member: &DidNostr,
        operation_id_arg: Option<&str>,
        confirmation: Confirmation,
    ) -> Result<u8, CliError> {
        self.member_action(member, "repair", operation_id_arg, confirmation)
    }

    /// `stratum member cancel <did> [--yes]`: cancels a `reserved` member,
    /// releasing its slot; the invitation stays used. Asks first. Signed.
    ///
    /// # Errors
    ///
    /// [`CliError::NotConfirmed`], [`CliError::Refused`] when the response
    /// names another member or a state other than `cancelled`, and key,
    /// transport, protocol and server errors.
    pub fn member_cancel(
        &self,
        member: &DidNostr,
        operation_id_arg: Option<&str>,
        confirmation: Confirmation,
    ) -> Result<u8, CliError> {
        self.member_action(member, "cancel", operation_id_arg, confirmation)
    }

    /// Repair or cancel.
    fn member_action(
        &self,
        member: &DidNostr,
        action: &str,
        operation_id_arg: Option<&str>,
        confirmation: Confirmation,
    ) -> Result<u8, CliError> {
        let operation_id = operation_id(operation_id_arg)?;
        let key = self.key()?;
        let client = self.client()?;
        let ready = readyz(&client)?;
        if !self.confirmed(&format!("{action} member {member}?"), confirmation)? {
            return Err(CliError::NotConfirmed);
        }
        self.output().note(&format!(
            "operation id: {operation_id} (to retry after a lost response, pass --operation-id {operation_id})"
        ))?;
        let body = to_body(&OperationRequest {
            node: ready.node_did,
            operation_id: &operation_id,
        })?;
        let path = format!("{MEMBERS}/{}/{action}", member.to_hex());
        let (done, _raw): (MemberActionResponse, Json) =
            client.post(&path, &body, Some(&key))?.into_json()?;
        if done.did != *member || (action == "cancel" && done.state != MemberState::Cancelled) {
            return Err(CliError::Refused(format!(
                "the node reports {} as {} after {action}",
                done.did, done.state
            )));
        }
        self.output().json(&json!({
            "operation_id": operation_id.as_str(),
            "did": done.did,
            "state": done.state,
        }))?;
        self.output()
            .line(&format!("{}: {}", done.did, done.state))?;
        Ok(exit::OK)
    }
}

/// Reads `membership.invitation_ttl_secs` from the node's effective
/// configuration.
fn configured_lifetime(
    client: &Client,
    key: &stratum_node_core::NostrSecretKey,
) -> Result<u64, CliError> {
    let (config, _raw): (ConfigResponse, Json) = client.get(CONFIG, Some(key))?.into_json()?;
    let document = ConfigDocument::parse(&config.text).map_err(|_| {
        CliError::Protocol("the node's configuration text does not parse".to_owned())
    })?;
    Ok(u64::from(document.config().invitation_ttl_secs()))
}

/// Builds the command line the invitee runs.
fn join_command(
    invitation: &InvitationId,
    node: &DidNostr,
    origin: &CanonicalOrigin,
    gate: Option<&ConnectAddress>,
) -> String {
    let origin_text = origin.as_str();
    let mut words = vec![
        "stratum".to_owned(),
        "join".to_owned(),
        "--invitation".to_owned(),
        invitation.to_string(),
        "--node".to_owned(),
        node.to_string(),
        "--origin".to_owned(),
        shell_word(&origin_text),
    ];
    let local_http = origin.scheme() == Scheme::Http
        && format!("http://{}", origin.authority())
            .parse::<crate::url::LoopbackUrl>()
            .is_ok();
    if gate.is_some() || !local_http {
        let connect = gate.map_or_else(
            || DEFAULT_GATE_CONNECT.to_owned(),
            ConnectAddress::authority,
        );
        words.push("--connect".to_owned());
        words.push(shell_word(&connect));
    }
    words.join(" ")
}

/// Quotes `word` for a POSIX shell when it holds anything but characters
/// every shell takes literally.
fn shell_word(word: &str) -> String {
    let plain = !word.is_empty()
        && word
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || b"-_.:/@%+=,".contains(&b));
    if plain {
        word.to_owned()
    } else {
        format!("'{}'", word.replace('\'', r"'\''"))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn durations_parse_in_four_units_only() {
        assert_eq!(parse_duration("45s"), Ok(Duration::from_secs(45)));
        assert_eq!(parse_duration("2h"), Ok(Duration::from_secs(7_200)));
        for bad in [
            "",
            "d",
            "-1d",
            "1.5d",
            "1 d",
            "1dd",
            "99999999999999999999d",
        ] {
            assert!(parse_duration(bad).is_err(), "{bad:?}");
        }
    }

    #[test]
    fn the_join_command_quotes_what_a_shell_would_read() {
        let invitation = InvitationId::from_bytes([1; 16]);
        let node =
            DidNostr::from_hex("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798")
                .expect("key");
        let https: CanonicalOrigin = "https://pod.example".parse().expect("origin");
        let line = join_command(&invitation, &node, &https, None);
        assert!(
            line.ends_with("--origin https://pod.example --connect 127.0.0.1:7461"),
            "{line}"
        );
        let v6: CanonicalOrigin = "https://[::1]:9443".parse().expect("origin");
        let gate: ConnectAddress = "[::1]:7461".parse().expect("connect");
        let line = join_command(&invitation, &node, &v6, Some(&gate));
        assert!(
            line.contains("--origin 'https://[::1]:9443' --connect '[::1]:7461'"),
            "{line}"
        );
        let local: CanonicalOrigin = "http://127.0.0.1:7461".parse().expect("origin");
        let line = join_command(&invitation, &node, &local, None);
        assert!(!line.contains("--connect"), "{line}");
    }
}