stratum-node-cli 0.1.0-alpha.3

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
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
//! The public profile document: writing it during `stratum join` and with
//! `stratum profile init`, and reading anyone's with `stratum profile show`.
//!
//! The card is `/pods/<pk>/profile/card`, Turtle, with exactly the text
//! [`profile_card`] gives; its ACL, `/pods/<pk>/profile/card.acl`, has
//! exactly the two rules [`profile_acl`] gives: the owner with read, write
//! and control, and everyone with read. Both come from `stratum-node-core`,
//! so the client and the node share one definition.

use serde_json::json;
use stratum_node_core::{
    card_names_owner, profile_acl, profile_card, profile_card_path, DidNostr, NostrSecretKey,
    PodPath, PROFILE_CONTENT_TYPE, PROFILE_MAX_BYTES,
};

use crate::error::CliError;
use crate::exit;
use crate::gate::{Buffered, GateClient, Precondition, Request, Route, ANY};
use crate::origin::GateTarget;
use crate::output::{sanitize, Output};
use crate::session::Session;

/// The most read of an existing card when deciding whether it names its
/// owner. A card larger than [`PROFILE_MAX_BYTES`] is never served
/// unsigned, so anything over that is reported, not parsed.
const CARD_READ_LIMIT: u64 = 16 * 1024 * 1024;

/// The most read of an existing ACL; it is only compared with the standard
/// text.
const ACL_READ_LIMIT: u64 = 1024 * 1024;

/// Options for [`Session::profile_init`].
///
/// # Examples
///
/// ```
/// use stratum_node_cli::ProfileInitOptions;
///
/// // `stratum profile init`: report a card that does not name the owner.
/// assert!(!ProfileInitOptions::default().replace);
/// // `stratum profile init --replace`.
/// let replace = ProfileInitOptions { replace: true };
/// assert!(replace.replace);
/// ```
#[derive(Debug, Clone, Copy, Default)]
pub struct ProfileInitOptions {
    /// `--replace`: replace an existing card that does not name the owner,
    /// conditionally on the version read, instead of reporting the
    /// conflict.
    pub replace: bool,
}

/// What to do with an existing card that does not qualify.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Conflicting {
    /// Report it and change nothing.
    Report,
    /// Replace it, conditionally on the version read (`--replace`).
    Replace,
}

/// What happened to the card.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum CardOutcome {
    /// There was none; the standard card was created.
    Written,
    /// One exists, is Turtle within the size limit and names the owner; it
    /// was left alone.
    Kept,
    /// One existed that did not name the owner; it was replaced (only with
    /// `--replace`).
    Replaced,
    /// One exists that does not qualify; nothing was written. The text
    /// says why.
    Conflict(String),
}

impl CardOutcome {
    fn as_str(&self) -> &'static str {
        match self {
            Self::Written => "written",
            Self::Kept => "kept",
            Self::Replaced => "replaced",
            Self::Conflict(_) => "conflict",
        }
    }
}

/// What happened to the card's ACL.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum AclOutcome {
    /// There was none; the standard ACL was created.
    Written,
    /// One exists and was left alone; `standard` says whether its bytes are
    /// the standard ACL's.
    Kept { standard: bool },
    /// Not looked at, because the card is in conflict: making an unknown
    /// card public is not this command's to decide.
    Skipped,
}

impl AclOutcome {
    fn as_str(self) -> &'static str {
        match self {
            Self::Written => "written",
            Self::Kept { .. } => "kept",
            Self::Skipped => "skipped",
        }
    }
}

/// The result of [`ensure_profile`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ProfileOutcome {
    pub(crate) card: CardOutcome,
    pub(crate) acl: AclOutcome,
}

impl ProfileOutcome {
    /// The report under `--json`.
    pub(crate) fn to_json(&self, card: &PodPath, acl: &PodPath) -> serde_json::Value {
        let conflict = match &self.card {
            CardOutcome::Conflict(why) => Some(why.clone()),
            _ => None,
        };
        let standard = match self.acl {
            AclOutcome::Kept { standard } => Some(standard),
            AclOutcome::Written => Some(true),
            AclOutcome::Skipped => None,
        };
        json!({
            "card": {"path": card, "outcome": self.card.as_str(), "conflict": conflict},
            "acl": {"path": acl, "outcome": self.acl.as_str(), "standard": standard},
        })
    }

    /// Notes what was done, on standard error.
    pub(crate) fn note(&self, output: Output, card: &PodPath) -> Result<(), CliError> {
        let line = match &self.card {
            CardOutcome::Written => format!("profile {card}: written"),
            CardOutcome::Kept => format!("profile {card}: already there and names you; left as is"),
            CardOutcome::Replaced => format!("profile {card}: replaced with the standard card"),
            CardOutcome::Conflict(why) => format!("profile {card}: {why}; left as is"),
        };
        output.note(&line)?;
        let line = match self.acl {
            AclOutcome::Written => {
                "profile ACL: written (you: read, write, control; everyone: read)".to_owned()
            }
            AclOutcome::Kept { standard: true } => {
                "profile ACL: already there; left as is".to_owned()
            }
            AclOutcome::Kept { standard: false } => "profile ACL: already there and not the \
                 standard one; left as is, so the card may not be public"
                .to_owned(),
            AclOutcome::Skipped => {
                "profile ACL: not written, because the card is not yours to publish".to_owned()
            }
        };
        output.note(&line)
    }
}

/// Makes sure the caller's pod holds the standard profile card and an ACL
/// beside it, changing nothing that is already right.
///
/// Reads before it writes, so a repeat sends no write at all:
///
/// 1. `GET` the card. On 404, `PUT` the standard card with
///    `If-None-Match: *`. On 200, the card is kept if it is `text/turtle`,
///    at most [`PROFILE_MAX_BYTES`] and names the owner
///    ([`card_names_owner`]); otherwise it is a conflict, which with
///    [`Conflicting::Replace`] is resolved by a `PUT` with `If-Match: <etag read>`.
/// 2. Unless the card is in conflict, `GET` the ACL beside it. On 404,
///    `PUT` the standard ACL with `If-None-Match: *`. An existing ACL is
///    left alone.
///
/// A create that answers 412 lost a race with another writer, and is read
/// again once.
pub(crate) fn ensure_profile(
    gate: &GateClient,
    key: &NostrSecretKey,
    conflicting: Conflicting,
) -> Result<ProfileOutcome, CliError> {
    let owner = key.public();
    let card_path = profile_card_path(&owner);
    let acl_path = acl_of_card(&card_path)?;
    let card = ensure_card(gate, key, &owner, &card_path, conflicting)?;
    if matches!(card, CardOutcome::Conflict(_)) {
        return Ok(ProfileOutcome {
            card,
            acl: AclOutcome::Skipped,
        });
    }
    let acl = ensure_acl(gate, key, &owner, &acl_path)?;
    Ok(ProfileOutcome { card, acl })
}

/// The ACL path beside the card.
fn acl_of_card(card: &PodPath) -> Result<PodPath, CliError> {
    card.acl_path()
        .ok_or_else(|| CliError::Local("the profile card has no ACL path".to_owned()))
}

/// Step 1 of [`ensure_profile`].
fn ensure_card(
    gate: &GateClient,
    key: &NostrSecretKey,
    owner: &DidNostr,
    path: &PodPath,
    conflicting: Conflicting,
) -> Result<CardOutcome, CliError> {
    let standard = profile_card(owner);
    for _attempt in 0..2 {
        let existing = gate.fetch(
            &Request::new("GET", path.as_str(), ANY),
            Some(key),
            CARD_READ_LIMIT,
        )?;
        if existing.head.status == 404 {
            let put = put_turtle(gate, key, path, &standard, Precondition::CreateOnly)?;
            if put.head.status == 412 {
                continue;
            }
            if !put.head.is_success() {
                return Err(put.into_error(Route::Pod));
            }
            return Ok(CardOutcome::Written);
        }
        if !existing.head.is_success() {
            return Err(existing.into_error(Route::Pod));
        }
        let Some(why) = card_problem(&existing, owner) else {
            return Ok(CardOutcome::Kept);
        };
        if conflicting == Conflicting::Report {
            return Ok(CardOutcome::Conflict(why));
        }
        let Some(etag) = existing.head.etag.as_deref() else {
            return Err(CliError::Refused(format!(
                "{path} {why}, and the pod server sent no entity tag, so it cannot be replaced \
                 without risking a change made meanwhile"
            )));
        };
        let put = put_turtle(gate, key, path, &standard, Precondition::IfMatch(etag))?;
        if put.head.status == 412 {
            return Err(CliError::Refused(format!(
                "{path} changed while it was being replaced; nothing was written, run the \
                 command again"
            )));
        }
        if !put.head.is_success() {
            return Err(put.into_error(Route::Pod));
        }
        return Ok(CardOutcome::Replaced);
    }
    Err(CliError::Refused(format!(
        "{path} kept appearing and disappearing while it was being created; run the command \
         again"
    )))
}

/// Step 2 of [`ensure_profile`].
fn ensure_acl(
    gate: &GateClient,
    key: &NostrSecretKey,
    owner: &DidNostr,
    path: &PodPath,
) -> Result<AclOutcome, CliError> {
    let standard = profile_acl(owner);
    for _attempt in 0..2 {
        let existing = gate.fetch(
            &Request::new("GET", path.as_str(), ANY),
            Some(key),
            ACL_READ_LIMIT,
        )?;
        if existing.head.status == 404 {
            let put = put_turtle(gate, key, path, &standard, Precondition::CreateOnly)?;
            if put.head.status == 412 {
                continue;
            }
            if !put.head.is_success() {
                return Err(put.into_error(Route::Pod));
            }
            return Ok(AclOutcome::Written);
        }
        if !existing.head.is_success() {
            return Err(existing.into_error(Route::Pod));
        }
        return Ok(AclOutcome::Kept {
            standard: existing.body == standard.as_bytes(),
        });
    }
    Err(CliError::Refused(format!(
        "{path} kept appearing and disappearing while it was being created; run the command \
         again"
    )))
}

/// `PUT`s Turtle text under a precondition.
fn put_turtle(
    gate: &GateClient,
    key: &NostrSecretKey,
    path: &PodPath,
    text: &str,
    precondition: Precondition<'_>,
) -> Result<Buffered, CliError> {
    gate.fetch(
        &Request::new("PUT", path.as_str(), ANY)
            .with_body(text.as_bytes(), PROFILE_CONTENT_TYPE)
            .with_precondition(precondition),
        Some(key),
        crate::client::MAX_RESPONSE_BYTES,
    )
}

/// Why an existing card does not qualify, or `None` when it does: it must
/// be stored as `text/turtle` (what the gate serves unsigned), within
/// [`PROFILE_MAX_BYTES`], and name its owner.
fn card_problem(card: &Buffered, owner: &DidNostr) -> Option<String> {
    let content_type = card.head.content_type.as_deref().unwrap_or("");
    if !is_turtle(content_type) {
        return Some(format!(
            "exists but is stored as {:?}, not {PROFILE_CONTENT_TYPE}, so it is never served \
             publicly",
            sanitize(content_type)
        ));
    }
    if card.body.len() > PROFILE_MAX_BYTES {
        return Some(format!(
            "exists but is {} bytes, over the {PROFILE_MAX_BYTES} bytes served publicly",
            card.body.len()
        ));
    }
    if !card_names_owner(&card.body, owner) {
        return Some(format!(
            "exists but does not name {owner} as its owner (`<#me> owl:sameAs <{owner}>`)"
        ));
    }
    None
}

/// Returns `true` when a `Content-Type` value's media type is
/// `text/turtle`, whatever its parameters.
fn is_turtle(content_type: &str) -> bool {
    content_type
        .split(';')
        .next()
        .is_some_and(|essence| essence.trim().eq_ignore_ascii_case(PROFILE_CONTENT_TYPE))
}

impl Session {
    /// `stratum profile init [--replace] --origin … [--connect …]`: writes
    /// the public profile document into the caller's own pod, for a member
    /// admitted before `join` wrote one. Signed by the caller's key.
    ///
    /// It never overwrites what is already right, and a repeat sends no
    /// write:
    ///
    /// - With no card, it writes the standard card
    ///   (`PUT /pods/<pk>/profile/card`, `If-None-Match: *`, `text/turtle`)
    ///   and then the ACL beside it if that is missing.
    /// - With a card that names the owner, it leaves the card and writes
    ///   only a missing ACL (`PUT /pods/<pk>/profile/card.acl`,
    ///   `If-None-Match: *`). An existing ACL is never changed; the output
    ///   says when it is not the standard one.
    /// - With a card that does not name the owner, or that the gate would
    ///   not serve (another content type, over 64 KiB), it reports the
    ///   conflict and changes nothing, unless `--replace` is given; then
    ///   the card is replaced with `If-Match: <etag read>` and a missing
    ///   ACL is written.
    ///
    /// # Errors
    ///
    /// [`CliError::Refused`] for a card in conflict without `--replace`, or
    /// one that changed while being replaced; and key, transport and server
    /// errors (`suspended`, `insufficient_storage` among them).
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use stratum_node_cli::{GateTarget, Output, OutputFormat, Session, ProfileInitOptions};
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let session = Session::new(
    ///     stratum_node_cli::DEFAULT_URL.parse()?,
    ///     Some("me.nsec".into()),
    ///     Output::new(OutputFormat::Human),
    /// );
    /// let target = GateTarget::new(
    ///     "https://stratum.example".parse()?,
    ///     Some("127.0.0.1:7461".parse()?),
    /// )?;
    /// session.profile_init(&target, ProfileInitOptions::default())?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn profile_init(
        &self,
        target: &GateTarget,
        options: ProfileInitOptions,
    ) -> Result<u8, CliError> {
        let key = self.key()?;
        let me = key.public();
        let gate = GateClient::new(target.clone()).with_busy_retries(*self.output());
        let conflicting = if options.replace {
            Conflicting::Replace
        } else {
            Conflicting::Report
        };
        let outcome = ensure_profile(&gate, &key, conflicting)?;
        let card = profile_card_path(&me);
        let acl = acl_of_card(&card)?;
        if let CardOutcome::Conflict(why) = &outcome.card {
            self.output().json(&outcome.to_json(&card, &acl))?;
            return Err(CliError::Refused(format!(
                "{card} {why}; nothing was changed. Pass --replace to replace it with the \
                 standard card"
            )));
        }
        self.output().json(&outcome.to_json(&card, &acl))?;
        outcome.note(*self.output(), &card)?;
        let url = target.origin().url(card.as_str());
        self.output().line(&format!("profile: {url}"))?;
        self.output().line(&format!(
            "card: {}, acl: {}",
            outcome.card.as_str(),
            outcome.acl.as_str()
        ))?;
        Ok(exit::OK)
    }

    /// `stratum profile show <did> --origin … [--connect …]`: reads any
    /// member's public profile, without a key.
    ///
    /// Sends an unsigned `GET /pods/<pk>/profile/card` with
    /// `Accept: text/turtle` to the gate, the one request the gate forwards
    /// without a signature. A 200 must be `text/turtle` and at most
    /// [`PROFILE_MAX_BYTES`]; its text is printed with control characters
    /// escaped (under `--json`: the DID, URL, content type, entity tag and
    /// text). A 404 is reported as "no public profile" with exit code
    /// [`exit::NOT_FOUND`]: the key is not a member, or the member never
    /// wrote one, deleted it or made it private; the gate does not say
    /// which.
    ///
    /// No key file is read, even when one is configured.
    ///
    /// # Errors
    ///
    /// [`CliError::Protocol`] for an answer of another content type or
    /// size, and transport and server errors (`pod_unavailable`, busy).
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use stratum_node_cli::{GateTarget, Output, OutputFormat, Session};
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let session = Session::new(
    ///     stratum_node_cli::DEFAULT_URL.parse()?,
    ///     None,
    ///     Output::new(OutputFormat::Human),
    /// );
    /// let target = GateTarget::new(
    ///     "https://stratum.example".parse()?,
    ///     Some("127.0.0.1:7461".parse()?),
    /// )?;
    /// let member = "did:nostr:79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798".parse()?;
    /// let code = session.profile_show(&target, &member)?; // 13: no public profile
    /// # let _ = code;
    /// # Ok(())
    /// # }
    /// ```
    pub fn profile_show(&self, target: &GateTarget, member: &DidNostr) -> Result<u8, CliError> {
        let path = profile_card_path(member);
        let url = target.origin().url(path.as_str());
        let gate = GateClient::new(target.clone());
        let limit = u64::try_from(PROFILE_MAX_BYTES).unwrap_or(u64::MAX);
        let response = gate.fetch(
            &Request::new("GET", path.as_str(), PROFILE_CONTENT_TYPE),
            None,
            limit,
        )?;
        if response.head.status == 404 {
            self.output()
                .json(&json!({"did": member, "url": url, "profile": null}))?;
            self.output()
                .line(&format!("no public profile for {member}"))?;
            self.output().note(
                "the key is not a member of this node, or the member has not written a \
                 profile, deleted it or made it private; the node does not say which",
            )?;
            return Ok(exit::NOT_FOUND);
        }
        if !response.head.is_success() {
            return Err(response.into_error(Route::Pod));
        }
        let content_type = response.head.content_type.clone().unwrap_or_default();
        if !is_turtle(&content_type) {
            return Err(CliError::Protocol(format!(
                "the profile was served as {:?}, not {PROFILE_CONTENT_TYPE}",
                sanitize(&content_type)
            )));
        }
        let text = sanitize(&String::from_utf8_lossy(&response.body));
        self.output().json(&json!({
            "did": member,
            "url": url,
            "content_type": PROFILE_CONTENT_TYPE,
            "etag": response.head.etag.as_deref().map(sanitize),
            "profile": text,
        }))?;
        self.output().note(&format!("profile of {member}: {url}"))?;
        for line in text.lines() {
            self.output().line(line)?;
        }
        Ok(exit::OK)
    }
}

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

    #[test]
    fn turtle_is_recognised_with_parameters_and_in_any_case() {
        assert!(is_turtle("text/turtle"));
        assert!(is_turtle("text/turtle; charset=utf-8"));
        assert!(is_turtle("Text/Turtle"));
        assert!(!is_turtle("application/ld+json"));
        assert!(!is_turtle("text/turtles"));
        assert!(!is_turtle(""));
    }
}