Skip to main content

stratum_node_cli/
admin.rs

1//! `stratum invite …` and `stratum member …`: the administrator's
2//! membership commands on the loopback API.
3
4use std::time::Duration;
5
6use serde_json::{json, Value as Json};
7use stratum_node_config::ConfigDocument;
8use stratum_node_core::{DidNostr, InvitationId, MemberState};
9
10use crate::client::Client;
11use crate::error::CliError;
12use crate::exit;
13use crate::origin::{CanonicalOrigin, ConnectAddress, Scheme};
14use crate::output::sanitize;
15use crate::session::{check_expected_node, operation_id, readyz, to_body, Confirmation, Session};
16use crate::wire::{
17    ConfigResponse, InvitationList, InviteRequest, InviteResponse, MemberActionResponse,
18    MemberList, OperationRequest, RevokeResponse,
19};
20
21/// `POST` and `GET` route: invitations.
22const INVITATIONS: &str = "/api/v1/invitations";
23/// `GET` route: members.
24const MEMBERS: &str = "/api/v1/members";
25/// `GET` route: the effective configuration, for the default invitation
26/// lifetime.
27const CONFIG: &str = "/api/v1/config";
28
29/// The longest invitation lifetime the node accepts: 30 days.
30pub const MAX_INVITATION_LIFETIME: Duration = Duration::from_secs(30 * 24 * 60 * 60);
31
32/// The connect address printed in the invitee's command line when none is
33/// given: the gate's default loopback port.
34const DEFAULT_GATE_CONNECT: &str = "127.0.0.1:7461";
35
36/// Options for [`Session::invite_create`].
37#[derive(Debug, Clone)]
38pub struct InviteOptions {
39    /// The identity invited (`<did>`).
40    pub subject: DidNostr,
41    /// The invitation's lifetime (`--expires-in`); the node's
42    /// `membership.invitation_ttl_secs` when `None`.
43    pub expires_in: Option<Duration>,
44    /// The operation ID; random when `None`.
45    pub operation_id: Option<String>,
46    /// Refuse unless `/readyz` reports this node DID (`--expect-node`).
47    pub expect_node: Option<DidNostr>,
48    /// The gate address the invitee should connect to, printed in the
49    /// `stratum join` command line (`--connect`); `127.0.0.1:7461` when `None`.
50    /// Not used when the canonical origin is itself a loopback `http://`
51    /// address.
52    pub gate: Option<ConnectAddress>,
53}
54
55/// Parses a duration written as a whole number of seconds, or a number
56/// followed by `s`, `m`, `h` or `d`.
57///
58/// # Examples
59///
60/// ```
61/// use std::time::Duration;
62/// use stratum_node_cli::parse_duration;
63///
64/// assert_eq!(parse_duration("7d"), Ok(Duration::from_secs(7 * 86_400)));
65/// assert_eq!(parse_duration("90m"), Ok(Duration::from_secs(5_400)));
66/// assert_eq!(parse_duration("3600"), Ok(Duration::from_secs(3_600)));
67/// assert!(parse_duration("1w").is_err());
68/// ```
69///
70/// # Errors
71///
72/// A message naming the accepted forms when `text` is none of them.
73pub fn parse_duration(text: &str) -> Result<Duration, String> {
74    let fail = || format!("{text:?} is not a duration: use seconds, or a number with s, m, h or d");
75    let (digits, unit) = match text.char_indices().last() {
76        Some((index, c)) if c.is_ascii_alphabetic() => (&text[..index], c),
77        _ => (text, 's'),
78    };
79    if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) {
80        return Err(fail());
81    }
82    let count: u64 = digits.parse().map_err(|_| fail())?;
83    let scale: u64 = match unit {
84        's' => 1,
85        'm' => 60,
86        'h' => 3_600,
87        'd' => 86_400,
88        _ => return Err(fail()),
89    };
90    count
91        .checked_mul(scale)
92        .map(Duration::from_secs)
93        .ok_or_else(fail)
94}
95
96impl Session {
97    /// `stratum invite create <did> [--expires-in <duration>]`: issues an
98    /// invitation for one identity and prints its identifier, subject,
99    /// expiry, the canonical origin and node DID, and the `stratum join`
100    /// command line the invitee runs. Signed by the administrator.
101    ///
102    /// Without `--expires-in` the lifetime is the node's configured
103    /// `membership.invitation_ttl_secs`, read from the effective
104    /// configuration. The response must name the requested subject and the
105    /// node `/readyz` reported.
106    ///
107    /// # Errors
108    ///
109    /// [`CliError::Usage`] for a lifetime over 30 days or under one second,
110    /// [`CliError::Refused`] when the response names another subject or
111    /// node, and key, transport, protocol and server errors
112    /// (`invitations_disabled` among them).
113    pub fn invite_create(&self, options: &InviteOptions) -> Result<u8, CliError> {
114        if let Some(lifetime) = options.expires_in {
115            if lifetime > MAX_INVITATION_LIFETIME || lifetime.is_zero() {
116                return Err(CliError::Usage(
117                    "--expires-in must be between 1 second and 30 days".to_owned(),
118                ));
119            }
120        }
121        let operation_id = operation_id(options.operation_id.as_deref())?;
122        let key = self.key()?;
123        let client = self.client()?;
124        let ready = readyz(&client)?;
125        check_expected_node(ready.node_did, options.expect_node.as_ref())?;
126        let expires_in = match options.expires_in {
127            Some(lifetime) => lifetime.as_secs(),
128            None => configured_lifetime(&client, &key)?,
129        };
130        self.output().note(&format!(
131            "operation id: {operation_id} (to retry after a lost response, pass --operation-id {operation_id})"
132        ))?;
133        let body = to_body(&InviteRequest {
134            node: ready.node_did,
135            operation_id: &operation_id,
136            subject: options.subject,
137            expires_in,
138        })?;
139        let (invite, _raw): (InviteResponse, Json) =
140            client.post(INVITATIONS, &body, Some(&key))?.into_json()?;
141        if invite.subject != options.subject || invite.node != ready.node_did {
142            return Err(CliError::Refused(format!(
143                "the node issued an invitation for {} on {}, not for {} on {}",
144                invite.subject, invite.node, options.subject, ready.node_did
145            )));
146        }
147        let origin: CanonicalOrigin = invite.origin.parse().map_err(|err| {
148            CliError::Protocol(format!(
149                "the invitation names origin {}: {err}",
150                sanitize(&invite.origin)
151            ))
152        })?;
153        let command = join_command(
154            &invite.invitation,
155            &invite.node,
156            &origin,
157            options.gate.as_ref(),
158        );
159        self.output().json(&json!({
160            "operation_id": operation_id.as_str(),
161            "invitation": invite.invitation,
162            "subject": invite.subject,
163            "expires_at": invite.expires_at,
164            "origin": origin.as_str(),
165            "node": invite.node,
166            "join_command": command,
167        }))?;
168        self.output()
169            .line(&format!("invitation: {}", invite.invitation))?;
170        self.output()
171            .line(&format!("subject: {}", invite.subject))?;
172        self.output()
173            .line(&format!("expires at: {} (unix time)", invite.expires_at))?;
174        self.output().line(&format!("origin: {origin}"))?;
175        self.output().line(&format!("node: {}", invite.node))?;
176        self.output()
177            .line("the invitee runs, with their own key in --key-file or STRATUM_KEY_FILE:")?;
178        self.output().line(&format!("  {command}"))?;
179        Ok(exit::OK)
180    }
181
182    /// `stratum invite list`: lists invitations with their state. Signed.
183    ///
184    /// # Errors
185    ///
186    /// Key, transport, protocol and server errors.
187    pub fn invite_list(&self) -> Result<u8, CliError> {
188        let key = self.key()?;
189        let client = self.client()?;
190        let (list, raw): (InvitationList, Json) =
191            client.get(INVITATIONS, Some(&key))?.into_json()?;
192        self.output().json(&raw)?;
193        if list.invitations.is_empty() {
194            self.output().line("no invitations")?;
195        }
196        for entry in &list.invitations {
197            self.output().line(&format!(
198                "{}  {:<8}  {}  issued {}  expires {}",
199                entry.invitation,
200                sanitize(&entry.state),
201                entry.subject,
202                entry.issued_at,
203                entry.expires_at
204            ))?;
205        }
206        Ok(exit::OK)
207    }
208
209    /// `stratum invite revoke <invitation>`: revokes an invitation that is
210    /// still `issued`. Signed.
211    ///
212    /// # Errors
213    ///
214    /// [`CliError::Refused`] when the response names another invitation or
215    /// state, and key, transport, protocol and server errors.
216    pub fn invite_revoke(
217        &self,
218        invitation: &InvitationId,
219        operation_id_arg: Option<&str>,
220    ) -> Result<u8, CliError> {
221        let operation_id = operation_id(operation_id_arg)?;
222        let key = self.key()?;
223        let client = self.client()?;
224        let ready = readyz(&client)?;
225        let body = to_body(&OperationRequest {
226            node: ready.node_did,
227            operation_id: &operation_id,
228        })?;
229        let path = format!("{INVITATIONS}/{invitation}/revoke");
230        let (revoked, _raw): (RevokeResponse, Json) =
231            client.post(&path, &body, Some(&key))?.into_json()?;
232        if revoked.invitation != *invitation || revoked.state != "revoked" {
233            return Err(CliError::Refused(format!(
234                "the node reports invitation {} as {}, not {invitation} as revoked",
235                revoked.invitation,
236                sanitize(&revoked.state)
237            )));
238        }
239        self.output().json(&json!({
240            "operation_id": operation_id.as_str(),
241            "invitation": revoked.invitation,
242            "state": "revoked",
243        }))?;
244        self.output()
245            .line(&format!("invitation {invitation}: revoked"))?;
246        Ok(exit::OK)
247    }
248
249    /// `stratum member list`: lists members with their state, pod URL and
250    /// the last provisioning error, and the capacity in use. Signed.
251    ///
252    /// # Errors
253    ///
254    /// Key, transport, protocol and server errors.
255    pub fn member_list(&self) -> Result<u8, CliError> {
256        let key = self.key()?;
257        let client = self.client()?;
258        let (list, raw): (MemberList, Json) = client.get(MEMBERS, Some(&key))?.into_json()?;
259        self.output().json(&raw)?;
260        self.output().line(&format!(
261            "capacity: {} of {} used",
262            list.used, list.capacity
263        ))?;
264        for member in &list.members {
265            self.output().line(&format!(
266                "{}  {:<11}  {}",
267                member.did,
268                member.state,
269                sanitize(&member.pod_url)
270            ))?;
271            self.output().line(&format!(
272                "    operation {}, reserved {}, activated {}",
273                sanitize(&member.operation_id),
274                member.reserved_at,
275                member
276                    .activated_at
277                    .map_or_else(|| "never".to_owned(), |t| t.to_string())
278            ))?;
279            if let Some(err) = &member.last_error {
280                self.output()
281                    .line(&format!("    last error: {}", sanitize(err)))?;
282            }
283        }
284        Ok(exit::OK)
285    }
286
287    /// `stratum member repair <did> [--yes]`: runs provisioning again for a
288    /// member, which restores a missing root ACL and leaves an existing one
289    /// alone. Asks first. Signed.
290    ///
291    /// # Errors
292    ///
293    /// [`CliError::NotConfirmed`], [`CliError::Refused`] when the response
294    /// names another member, and key, transport, protocol and server errors.
295    pub fn member_repair(
296        &self,
297        member: &DidNostr,
298        operation_id_arg: Option<&str>,
299        confirmation: Confirmation,
300    ) -> Result<u8, CliError> {
301        self.member_action(member, "repair", operation_id_arg, confirmation)
302    }
303
304    /// `stratum member cancel <did> [--yes]`: cancels a `reserved` member,
305    /// releasing its slot; the invitation stays used. Asks first. Signed.
306    ///
307    /// # Errors
308    ///
309    /// [`CliError::NotConfirmed`], [`CliError::Refused`] when the response
310    /// names another member or a state other than `cancelled`, and key,
311    /// transport, protocol and server errors.
312    pub fn member_cancel(
313        &self,
314        member: &DidNostr,
315        operation_id_arg: Option<&str>,
316        confirmation: Confirmation,
317    ) -> Result<u8, CliError> {
318        self.member_action(member, "cancel", operation_id_arg, confirmation)
319    }
320
321    /// Repair or cancel.
322    fn member_action(
323        &self,
324        member: &DidNostr,
325        action: &str,
326        operation_id_arg: Option<&str>,
327        confirmation: Confirmation,
328    ) -> Result<u8, CliError> {
329        let operation_id = operation_id(operation_id_arg)?;
330        let key = self.key()?;
331        let client = self.client()?;
332        let ready = readyz(&client)?;
333        if !self.confirmed(&format!("{action} member {member}?"), confirmation)? {
334            return Err(CliError::NotConfirmed);
335        }
336        self.output().note(&format!(
337            "operation id: {operation_id} (to retry after a lost response, pass --operation-id {operation_id})"
338        ))?;
339        let body = to_body(&OperationRequest {
340            node: ready.node_did,
341            operation_id: &operation_id,
342        })?;
343        let path = format!("{MEMBERS}/{}/{action}", member.to_hex());
344        let (done, _raw): (MemberActionResponse, Json) =
345            client.post(&path, &body, Some(&key))?.into_json()?;
346        if done.did != *member || (action == "cancel" && done.state != MemberState::Cancelled) {
347            return Err(CliError::Refused(format!(
348                "the node reports {} as {} after {action}",
349                done.did, done.state
350            )));
351        }
352        self.output().json(&json!({
353            "operation_id": operation_id.as_str(),
354            "did": done.did,
355            "state": done.state,
356        }))?;
357        self.output()
358            .line(&format!("{}: {}", done.did, done.state))?;
359        Ok(exit::OK)
360    }
361}
362
363/// Reads `membership.invitation_ttl_secs` from the node's effective
364/// configuration.
365fn configured_lifetime(
366    client: &Client,
367    key: &stratum_node_core::NostrSecretKey,
368) -> Result<u64, CliError> {
369    let (config, _raw): (ConfigResponse, Json) = client.get(CONFIG, Some(key))?.into_json()?;
370    let document = ConfigDocument::parse(&config.text).map_err(|_| {
371        CliError::Protocol("the node's configuration text does not parse".to_owned())
372    })?;
373    Ok(u64::from(document.config().invitation_ttl_secs()))
374}
375
376/// Builds the command line the invitee runs.
377fn join_command(
378    invitation: &InvitationId,
379    node: &DidNostr,
380    origin: &CanonicalOrigin,
381    gate: Option<&ConnectAddress>,
382) -> String {
383    let origin_text = origin.as_str();
384    let mut words = vec![
385        "stratum".to_owned(),
386        "join".to_owned(),
387        "--invitation".to_owned(),
388        invitation.to_string(),
389        "--node".to_owned(),
390        node.to_string(),
391        "--origin".to_owned(),
392        shell_word(&origin_text),
393    ];
394    let local_http = origin.scheme() == Scheme::Http
395        && format!("http://{}", origin.authority())
396            .parse::<crate::url::LoopbackUrl>()
397            .is_ok();
398    if gate.is_some() || !local_http {
399        let connect = gate.map_or_else(
400            || DEFAULT_GATE_CONNECT.to_owned(),
401            ConnectAddress::authority,
402        );
403        words.push("--connect".to_owned());
404        words.push(shell_word(&connect));
405    }
406    words.join(" ")
407}
408
409/// Quotes `word` for a POSIX shell when it holds anything but characters
410/// every shell takes literally.
411fn shell_word(word: &str) -> String {
412    let plain = !word.is_empty()
413        && word
414            .bytes()
415            .all(|b| b.is_ascii_alphanumeric() || b"-_.:/@%+=,".contains(&b));
416    if plain {
417        word.to_owned()
418    } else {
419        format!("'{}'", word.replace('\'', r"'\''"))
420    }
421}
422
423#[cfg(test)]
424mod tests {
425    use super::*;
426
427    #[test]
428    fn durations_parse_in_four_units_only() {
429        assert_eq!(parse_duration("45s"), Ok(Duration::from_secs(45)));
430        assert_eq!(parse_duration("2h"), Ok(Duration::from_secs(7_200)));
431        for bad in [
432            "",
433            "d",
434            "-1d",
435            "1.5d",
436            "1 d",
437            "1dd",
438            "99999999999999999999d",
439        ] {
440            assert!(parse_duration(bad).is_err(), "{bad:?}");
441        }
442    }
443
444    #[test]
445    fn the_join_command_quotes_what_a_shell_would_read() {
446        let invitation = InvitationId::from_bytes([1; 16]);
447        let node =
448            DidNostr::from_hex("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798")
449                .expect("key");
450        let https: CanonicalOrigin = "https://pod.example".parse().expect("origin");
451        let line = join_command(&invitation, &node, &https, None);
452        assert!(
453            line.ends_with("--origin https://pod.example --connect 127.0.0.1:7461"),
454            "{line}"
455        );
456        let v6: CanonicalOrigin = "https://[::1]:9443".parse().expect("origin");
457        let gate: ConnectAddress = "[::1]:7461".parse().expect("connect");
458        let line = join_command(&invitation, &node, &v6, Some(&gate));
459        assert!(
460            line.contains("--origin 'https://[::1]:9443' --connect '[::1]:7461'"),
461            "{line}"
462        );
463        let local: CanonicalOrigin = "http://127.0.0.1:7461".parse().expect("origin");
464        let line = join_command(&invitation, &node, &local, None);
465        assert!(!line.contains("--connect"), "{line}");
466    }
467}