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
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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
//! `stratum pod …`: reading and writing resources in a pod through the gate.

use std::fs::{self, File, OpenOptions};
use std::io::{self, IsTerminal as _, Read as _, Write as _};
use std::os::unix::fs::OpenOptionsExt as _;
use std::path::{Path, PathBuf};

use serde_json::json;
use stratum_node_core::{DidNostr, NostrSecretKey, ParsePodPathError, PodPath};

use crate::error::CliError;
use crate::exit;
use crate::gate::{
    self, GateClient, Head, Precondition, Request, Route, ANY, LD_JSON, MAX_LISTING_BYTES,
    MAX_RESOURCE_BYTES,
};
use crate::listing::{self, Child};
use crate::origin::GateTarget;
use crate::output::sanitize;
use crate::session::{Confirmation, Session};

/// The content type an ACL is written with unless another is given.
const TURTLE: &str = "text/turtle";

/// The content type of a resource whose file name says nothing.
const OCTET_STREAM: &str = "application/octet-stream";

/// The condition a `PUT` is sent under.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum WriteCondition {
    /// Write whatever is there.
    #[default]
    Always,
    /// Write only if the resource's current entity tag is this one
    /// (`--if-match`); a resource changed since it was read is refused with
    /// `precondition_failed`.
    IfMatch(String),
    /// Write only if nothing is there yet (`--create-only`, sent as
    /// `If-None-Match: *`).
    CreateOnly,
}

/// Options for [`Session::pod_put`] and [`Session::pod_acl_put`].
#[derive(Debug, Clone, Default)]
pub struct PutOptions {
    /// The pod path: relative to the caller's own pod root, or absolute
    /// `/pods/<pk>/…`. For [`Session::pod_acl_put`], the resource or
    /// container whose ACL is written.
    pub path: String,
    /// The file whose bytes are written.
    pub file: PathBuf,
    /// The content type; guessed from the file name when `None` (`text/turtle`
    /// for an ACL).
    pub content_type: Option<String>,
    /// The condition the write is sent under.
    pub condition: WriteCondition,
}

impl Session {
    /// `stratum pod ls [<path>]`: lists a container in a pod. Signed by the
    /// caller's key over the canonical URL.
    ///
    /// `path` is relative to the caller's own pod root (empty for the root
    /// itself) or absolute `/pods/<pk>/…`; a missing trailing `/` is added.
    /// Each listed child is resolved against the listing's address and
    /// shown only if it lies under the container; anything else is
    /// reported as refused.
    ///
    /// # Errors
    ///
    /// [`CliError::Usage`] for a path the Step 2 rules refuse, and key,
    /// transport and server errors.
    pub fn pod_ls(&self, target: &GateTarget, path: &str) -> Result<u8, CliError> {
        let key = self.key()?;
        let mut text = path.to_owned();
        if !text.is_empty() && !text.ends_with('/') {
            text.push('/');
        }
        let container = resolve_path(&key.public(), &text)?;
        if !container.is_container() {
            return Err(CliError::Usage(format!("{container} is not a container")));
        }
        let gate = GateClient::new(target.clone());
        let response = gate.fetch(
            &Request::new("GET", container.as_str(), LD_JSON),
            Some(&key),
            MAX_LISTING_BYTES,
        )?;
        if !response.head.is_success() {
            return Err(response.into_error(Route::Pod));
        }
        let children = listing::children(target.origin(), &container, &response.body)?;
        let mut listed = Vec::new();
        let mut refused = Vec::new();
        for child in children {
            match child {
                Child::Accepted(path) => {
                    self.output().line(path.as_str())?;
                    listed.push(json!({"path": path, "container": path.is_container()}));
                }
                Child::Refused { id, reason } => {
                    self.output()
                        .note(&format!("refused listed child {id:?}: {reason}"))?;
                    refused.push(json!({"id": id, "reason": reason}));
                }
            }
        }
        self.output().json(&json!({
            "path": container,
            "children": listed,
            "refused": refused,
        }))?;
        Ok(exit::OK)
    }

    /// `stratum pod get <path> [-o <file>]`: reads a resource. Signed.
    ///
    /// The body is written byte for byte to `output`, a new file created
    /// with mode `0600` (an existing file is never overwritten), or to
    /// standard output. On a terminal, control characters are escaped; in a
    /// pipe the bytes are written unchanged. Under `--json` an output file
    /// is required, and a report of the status, content type, entity tag,
    /// size and SHA-256 is printed.
    ///
    /// # Errors
    ///
    /// [`CliError::Usage`] for a refused path or `--json` without `-o`,
    /// [`CliError::File`] when the output file exists, and key, transport
    /// and server errors.
    pub fn pod_get(
        &self,
        target: &GateTarget,
        path: &str,
        output: Option<&Path>,
    ) -> Result<u8, CliError> {
        let key = self.key()?;
        let resource = resolve_path(&key.public(), path)?;
        self.download(target, &key, &resource, output)
    }

    /// `stratum pod acl get <path> [-o <file>]`: reads the ACL beside a
    /// resource or container, as [`pod_get`](Self::pod_get) does. For the
    /// pod root (an empty path) that is the root ACL `/pods/<pk>.acl`.
    ///
    /// # Errors
    ///
    /// As [`pod_get`](Self::pod_get); [`CliError::Usage`] when the path is
    /// itself an ACL.
    pub fn pod_acl_get(
        &self,
        target: &GateTarget,
        path: &str,
        output: Option<&Path>,
    ) -> Result<u8, CliError> {
        let key = self.key()?;
        let acl = acl_of(&resolve_path(&key.public(), path)?)?;
        self.download(target, &key, &acl, output)
    }

    /// `stratum pod put <path> <file> [--content-type …] [--if-match <etag> |
    /// --create-only]`: writes a resource. Signed over the body, which is
    /// read whole (at most 1 GiB) and sent with `Content-Length`.
    ///
    /// # Errors
    ///
    /// [`CliError::Usage`] for a refused path or a container path,
    /// [`CliError::FileContents`] for an unreadable or oversized file,
    /// `precondition_failed` when the condition does not hold, and key,
    /// transport and server errors.
    pub fn pod_put(&self, target: &GateTarget, options: &PutOptions) -> Result<u8, CliError> {
        let key = self.key()?;
        let resource = resolve_path(&key.public(), &options.path)?;
        if resource.is_container() {
            return Err(CliError::Usage(format!(
                "{resource} is a container; give a resource path"
            )));
        }
        let content_type = options
            .content_type
            .clone()
            .unwrap_or_else(|| guess_content_type(&options.file, &resource).to_owned());
        self.upload(target, &key, &resource, options, &content_type)
    }

    /// `stratum pod acl put <path> <file>`: writes the ACL beside a resource
    /// or container (the root ACL for the pod root), as
    /// [`pod_put`](Self::pod_put) does, with content type `text/turtle`
    /// unless another is given.
    ///
    /// # Errors
    ///
    /// As [`pod_put`](Self::pod_put); [`CliError::Usage`] when the path is
    /// itself an ACL.
    pub fn pod_acl_put(&self, target: &GateTarget, options: &PutOptions) -> Result<u8, CliError> {
        let key = self.key()?;
        let acl = acl_of(&resolve_path(&key.public(), &options.path)?)?;
        let content_type = options.content_type.as_deref().unwrap_or(TURTLE).to_owned();
        self.upload(target, &key, &acl, options, &content_type)
    }

    /// `stratum pod rm <path> [--yes]`: deletes a resource or an empty
    /// container after confirmation. Signed. The root ACL cannot be
    /// deleted: that would lock the owner out of their own pod.
    ///
    /// # Errors
    ///
    /// [`CliError::Usage`] for a refused path or the root ACL,
    /// [`CliError::NotConfirmed`], and key, transport and server errors.
    pub fn pod_rm(
        &self,
        target: &GateTarget,
        path: &str,
        confirmation: Confirmation,
    ) -> Result<u8, CliError> {
        let key = self.key()?;
        let resource = resolve_path(&key.public(), path)?;
        if resource.is_root_acl() {
            return Err(CliError::Usage(
                "the root ACL cannot be deleted: it would lock everyone out of the pod, \
                 its owner included; change it with `stratum pod acl put`"
                    .to_owned(),
            ));
        }
        if !self.confirmed(&format!("delete {resource}?"), confirmation)? {
            return Err(CliError::NotConfirmed);
        }
        let gate = GateClient::new(target.clone());
        let response = gate.fetch(
            &Request::new("DELETE", resource.as_str(), ANY),
            Some(&key),
            crate::client::MAX_RESPONSE_BYTES,
        )?;
        if !response.head.is_success() {
            return Err(response.into_error(Route::Pod));
        }
        self.output().json(&json!({
            "path": resource,
            "status": response.head.status,
            "deleted": true,
        }))?;
        self.output().line(&format!("deleted {resource}"))?;
        Ok(exit::OK)
    }

    /// Reads `resource` into `output` or standard output.
    fn download(
        &self,
        target: &GateTarget,
        key: &NostrSecretKey,
        resource: &PodPath,
        output: Option<&Path>,
    ) -> Result<u8, CliError> {
        if output.is_none() && self.output().is_json() {
            return Err(CliError::Usage(
                "--json reports on the resource and needs -o <file> for its bytes".to_owned(),
            ));
        }
        let gate = GateClient::new(target.clone());
        let request = Request::new("GET", resource.as_str(), ANY);
        let (head, streamed) = match output {
            Some(path) => {
                let mut file = create_output(path)?;
                let result = gate.stream(&request, key, &mut file, MAX_RESOURCE_BYTES);
                let finished = match result {
                    Ok((head, Ok(streamed))) => {
                        file.sync_all().map(|()| (head, streamed)).map_err(|err| {
                            CliError::Local(format!("writing {} failed: {err}", path.display()))
                        })
                    }
                    Ok((head, Err(body))) => Err(gate::error_from(&head, &body, Route::Pod)),
                    Err(err) => Err(err),
                };
                match finished {
                    Ok(done) => done,
                    Err(err) => {
                        drop(file);
                        // The partial file is ours, created a moment ago.
                        let _removed = fs::remove_file(path);
                        return Err(err);
                    }
                }
            }
            None => self.to_stdout(&gate, &request, key)?,
        };
        let report = json!({
            "path": resource,
            "status": head.status,
            "content_type": head.content_type.as_deref().map(sanitize),
            "etag": head.etag.as_deref().map(sanitize),
            "size": streamed.size,
            "sha256": streamed.sha256,
            "output": output.map(|p| p.display().to_string()),
        });
        self.output().json(&report)?;
        if let Some(path) = output {
            self.output().line(&format!(
                "wrote {} bytes to {} (sha256 {})",
                streamed.size,
                path.display(),
                streamed.sha256
            ))?;
            if let Some(etag) = &head.etag {
                self.output().line(&format!("etag: {}", sanitize(etag)))?;
            }
        }
        Ok(exit::OK)
    }

    /// Streams a resource to standard output: raw bytes into a pipe,
    /// escaped text on a terminal.
    fn to_stdout(
        &self,
        gate: &GateClient,
        request: &Request<'_>,
        key: &NostrSecretKey,
    ) -> Result<(Head, gate::Streamed), CliError> {
        let stdout = io::stdout();
        if stdout.is_terminal() {
            let mut buffer = Vec::new();
            let (head, streamed) = gate.stream(request, key, &mut buffer, MAX_RESOURCE_BYTES)?;
            let streamed = streamed.map_err(|body| gate::error_from(&head, &body, Route::Pod))?;
            self.output()
                .line(sanitize(&String::from_utf8_lossy(&buffer)).trim_end())?;
            return Ok((head, streamed));
        }
        let mut lock = stdout.lock();
        let (head, streamed) = gate.stream(request, key, &mut lock, MAX_RESOURCE_BYTES)?;
        let streamed = streamed.map_err(|body| gate::error_from(&head, &body, Route::Pod))?;
        lock.flush()
            .map_err(|err| CliError::Local(format!("writing output failed: {err}")))?;
        Ok((head, streamed))
    }

    /// Writes `options.file` to `resource`.
    fn upload(
        &self,
        target: &GateTarget,
        key: &NostrSecretKey,
        resource: &PodPath,
        options: &PutOptions,
        content_type: &str,
    ) -> Result<u8, CliError> {
        if !is_header_value(content_type) {
            return Err(CliError::Usage(
                "--content-type must be printable ASCII".to_owned(),
            ));
        }
        if let WriteCondition::IfMatch(etag) = &options.condition {
            if !is_header_value(etag) {
                return Err(CliError::Usage(
                    "--if-match must be printable ASCII, such as \"<64 hex>\"".to_owned(),
                ));
            }
        }
        let body = read_upload(&options.file)?;
        let precondition = match &options.condition {
            WriteCondition::Always => Precondition::None,
            WriteCondition::IfMatch(etag) => Precondition::IfMatch(etag),
            WriteCondition::CreateOnly => Precondition::CreateOnly,
        };
        let gate = GateClient::new(target.clone()).with_busy_retries(*self.output());
        let request = Request::new("PUT", resource.as_str(), ANY)
            .with_body(&body, content_type)
            .with_precondition(precondition);
        let response = gate.fetch(&request, Some(key), crate::client::MAX_RESPONSE_BYTES)?;
        if !response.head.is_success() {
            return Err(response.into_error(Route::Pod));
        }
        let head = response.head;
        let digest = stratum_node_core::Sha256Digest::of(&body);
        self.output().json(&json!({
            "path": resource,
            "status": head.status,
            "created": head.status == 201,
            "size": body.len(),
            "sha256": digest,
            "content_type": content_type,
            "etag": head.etag.as_deref().map(sanitize),
        }))?;
        let verb = if head.status == 201 {
            "created"
        } else {
            "wrote"
        };
        self.output().line(&format!(
            "{verb} {resource} ({} bytes, sha256 {digest})",
            body.len()
        ))?;
        if let Some(etag) = &head.etag {
            self.output().line(&format!("etag: {}", sanitize(etag)))?;
        }
        Ok(exit::OK)
    }
}

/// Resolves a command-line pod path: absolute `/pods/<pk>/…` or
/// `/pods/<pk>.acl`, or relative to `owner`'s pod root (empty for the root).
///
/// # Errors
///
/// [`CliError::Usage`], saying which rule refused the path.
pub(crate) fn resolve_path(owner: &DidNostr, text: &str) -> Result<PodPath, CliError> {
    let root = PodPath::pod_root(owner);
    let result = if text.starts_with('/') {
        PodPath::parse(text)
    } else if text.is_empty() {
        Ok(root)
    } else {
        root.join(text)
    };
    result.map_err(|err| CliError::Usage(path_refusal(text, err)))
}

/// Explains why a command-line path was refused.
fn path_refusal(text: &str, err: ParsePodPathError) -> String {
    let shown = sanitize(text);
    match err {
        ParsePodPathError::ForbiddenCharacter => format!(
            "{shown:?} is refused by the Step 2 character rule: names may use only \
             A-Z a-z 0-9 - . _ ~ and / between segments; no spaces and no percent-encoding"
        ),
        ParsePodPathError::DotSegment => {
            format!("{shown:?} has a . or .. segment, which pod paths may not have")
        }
        ParsePodPathError::EmptySegment => format!(
            "{shown:?} has an empty segment (// or a leading /); relative paths start with a name"
        ),
        _ => format!(
            "{shown:?} is not a pod path: give a path relative to your pod, or an absolute \
             /pods/<64 lowercase hex>/… or /pods/<64 lowercase hex>.acl"
        ),
    }
}

/// Returns the ACL beside `path`.
fn acl_of(path: &PodPath) -> Result<PodPath, CliError> {
    path.acl_path().ok_or_else(|| {
        CliError::Usage(format!(
            "{path} is itself an ACL; give the resource or container it controls"
        ))
    })
}

/// Guesses a content type from the file name, then the pod path.
fn guess_content_type(file: &Path, resource: &PodPath) -> &'static str {
    let name = resource.as_str();
    let extension = file
        .extension()
        .and_then(|e| e.to_str())
        .or_else(|| name.rsplit_once('.').map(|(_, e)| e))
        .unwrap_or("")
        .to_ascii_lowercase();
    match extension.as_str() {
        "acl" | "ttl" => TURTLE,
        "txt" => "text/plain",
        "md" => "text/markdown",
        "html" | "htm" => "text/html",
        "json" => "application/json",
        "jsonld" => "application/ld+json",
        "png" => "image/png",
        "jpg" | "jpeg" => "image/jpeg",
        "pdf" => "application/pdf",
        _ => OCTET_STREAM,
    }
}

/// Returns `true` for a value that can be sent as a header as given.
fn is_header_value(text: &str) -> bool {
    !text.is_empty() && text.bytes().all(|b| (0x20..0x7f).contains(&b))
}

/// Reads a file to upload: a regular file of at most 1 GiB.
fn read_upload(path: &Path) -> Result<Vec<u8>, CliError> {
    let fail = |message: String| CliError::FileContents {
        path: path.to_owned(),
        message,
    };
    let file = File::open(path).map_err(|err| fail(format!("cannot be opened: {err}")))?;
    let metadata = file
        .metadata()
        .map_err(|err| fail(format!("cannot be read: {err}")))?;
    if !metadata.is_file() {
        return Err(fail("is not a regular file".to_owned()));
    }
    if metadata.len() > MAX_RESOURCE_BYTES {
        return Err(fail(format!(
            "is larger than {MAX_RESOURCE_BYTES} bytes, the most a pod accepts"
        )));
    }
    let mut body = Vec::new();
    file.take(MAX_RESOURCE_BYTES + 1)
        .read_to_end(&mut body)
        .map_err(|err| fail(format!("cannot be read: {err}")))?;
    if u64::try_from(body.len()).unwrap_or(u64::MAX) > MAX_RESOURCE_BYTES {
        return Err(fail(format!(
            "is larger than {MAX_RESOURCE_BYTES} bytes, the most a pod accepts"
        )));
    }
    Ok(body)
}

/// Creates a new output file with mode `0600`; an existing file is never
/// overwritten.
fn create_output(path: &Path) -> Result<File, CliError> {
    OpenOptions::new()
        .write(true)
        .create_new(true)
        .mode(0o600)
        .open(path)
        .map_err(|err| {
            if err.kind() == io::ErrorKind::AlreadyExists {
                CliError::File {
                    path: path.to_owned(),
                    source: crate::private_file::PrivateFileError::AlreadyExists,
                }
            } else {
                CliError::File {
                    path: path.to_owned(),
                    source: crate::private_file::PrivateFileError::Io(err),
                }
            }
        })
}

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

    const A: &str = "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798";

    #[test]
    fn command_line_paths_resolve_or_say_why_not() {
        let owner = DidNostr::from_hex(A).expect("key");
        assert_eq!(
            resolve_path(&owner, "").expect("root").as_str(),
            format!("/pods/{A}/")
        );
        assert_eq!(
            resolve_path(&owner, "private/x.txt")
                .expect("relative")
                .as_str(),
            format!("/pods/{A}/private/x.txt")
        );
        assert_eq!(
            resolve_path(&owner, &format!("/pods/{A}.acl"))
                .expect("root acl")
                .as_str(),
            format!("/pods/{A}.acl")
        );
        let err = resolve_path(&owner, "my file.txt").expect_err("space");
        assert!(err.to_string().contains("Step 2 character rule"), "{err}");
        let err = resolve_path(&owner, "a%20b").expect_err("percent");
        assert!(err.to_string().contains("no percent-encoding"), "{err}");
        let err = resolve_path(&owner, "a/../b").expect_err("dot");
        assert!(err.to_string().contains(". or .."), "{err}");
        let err = resolve_path(&owner, "/etc/passwd").expect_err("outside");
        assert!(err.to_string().contains("not a pod path"), "{err}");
        assert_eq!(err.exit_code(), exit::USAGE);
    }

    #[test]
    fn acl_paths_sit_beside_their_resource() {
        let owner = DidNostr::from_hex(A).expect("key");
        let root = resolve_path(&owner, "").expect("root");
        assert_eq!(
            acl_of(&root).expect("acl").as_str(),
            format!("/pods/{A}.acl")
        );
        let acl = resolve_path(&owner, "x.txt.acl").expect("acl");
        assert!(acl_of(&acl).is_err());
    }
}