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
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
//! `stratum`: the client for a Stratum node, for its administrator on the
//! loopback API and for tenants through the gate.
//!
//! This file only parses the command line; the commands live in the
//! `stratum_node_cli` library.

use std::path::PathBuf;
use std::process::ExitCode;
use std::time::Duration;

use clap::{Args, Parser, Subcommand};
use stratum_node_cli::{
    exit, parse_duration, ApplyOptions, CanonicalOrigin, CliError, Confirmation, ConnectAddress,
    ExportOptions, GateTarget, InviteOptions, JoinOptions, LoopbackUrl, Output, OutputFormat,
    PutOptions, Session, SetupOptions, WriteCondition, DEFAULT_URL,
};
use stratum_node_core::{DidNostr, InvitationId};

/// The exit-code table shown at the end of `--help`.
const EXIT_CODES: &str = "\
Exit codes:
   0  success; for `status`, the node is ready
   1  local failure (key, token or resume file, clock, output)
   2  the node could not be reached
   3  status: the node is unconfigured
   4  status: the node is degraded
   5  the node's response does not follow the API contract
   6  previewed but not applied: no confirmation (pass --yes)
   7  a local check refused the node's answer (claim body, backup manifest,
      admission notice, join probe)
   8  join: the pod was not provisioned within --wait-secs (rerun to continue)
   9  export: written, but entries changed, vanished or were skipped
  10  bad_request            11  unauthorized          12  forbidden
  13  not_found              14  conflict              15  payload_too_large
  16  unsupported_media_type 17  invalid (also an invalid preview)
  18  too_many_challenges    19  backup_refused        20  internal
  21  unknown server error code                    22  request_timeout
  23  capacity_exhausted     24  invitation_refused    25  invitations_disabled
  26  gate_unavailable       27  too_many_requests     28  misdirected_request
  29  method_not_allowed     30  insufficient_storage  31  precondition_failed
  32  bad_gateway            33  gateway_timeout
  64  invalid command line

Server errors are printed as `code: message`.";

/// The client for a Stratum node.
///
/// Administrator commands talk to the node's loopback API (--url) over plain
/// HTTP and sign requests with the operator's Nostr key. Tenant commands
/// (join, pod, export) reach the node's gate (--origin, --connect) and sign
/// with the tenant's own key. PRE-RELEASE (0.1.0-alpha): commands and output
/// may change.
#[derive(Debug, Parser)]
#[command(name = "stratum", version, after_help = EXIT_CODES)]
struct Cli {
    /// Node API URL; the host must be an address in 127.0.0.0/8 (such as
    /// 127.0.0.1), `[::1]` or localhost, which is dialled as 127.0.0.1
    /// without a name lookup (no TLS in Step 1). For sign-challenge: the
    /// claim URL.
    #[arg(long, global = true, env = "STRATUM_URL", default_value = DEFAULT_URL)]
    url: LoopbackUrl,

    /// Key file (one nsec line, mode 0600): the operator's for administrator
    /// commands, the tenant's own for join, pod and export.
    #[arg(long, global = true, env = "STRATUM_KEY_FILE", value_name = "FILE")]
    key_file: Option<PathBuf>,

    /// Write machine-readable JSON to standard output.
    #[arg(long, global = true)]
    json: bool,

    #[command(subcommand)]
    command: Command,
}

#[derive(Debug, Subcommand)]
enum Command {
    /// Create or inspect an operator key file.
    Key {
        #[command(subcommand)]
        command: KeyCommand,
    },
    /// Show the node's readiness (exit 0 ready, 3 unconfigured, 4 degraded,
    /// 2 unreachable).
    Status,
    /// Read, preview and apply configuration.
    Config {
        #[command(subcommand)]
        command: ConfigCommand,
    },
    /// Claim an unconfigured node with the bootstrap token and this key.
    Setup(SetupArgs),
    /// Sign a claim body offline and print the Authorization header value.
    ///
    /// Refuses a body that names another claimant, another node than
    /// --expect-node, or has expired. The configuration hash in the body
    /// cannot be checked offline and is signed as issued; `stratum setup`
    /// checks it. Uses --url as the claim URL: a bare origin gets
    /// /api/v1/bootstrap/claim appended, and a URL with a path must end in
    /// exactly that path. It must equal the `url` in the challenge
    /// response. No network access.
    SignChallenge {
        /// File holding the claim body bytes exactly as the node issued them.
        #[arg(long, value_name = "FILE")]
        claim_body_file: PathBuf,

        /// The node DID the claim must name, as stratumd printed it at start
        /// (never taken from the claim file).
        #[arg(long, value_name = "DID")]
        expect_node: DidNostr,
    },
    /// Audit log operations.
    Audit {
        #[command(subcommand)]
        command: AuditCommand,
    },
    /// Ask the node for a backup and verify its signed manifest.
    Backup {
        /// Operation ID to reuse when retrying; random when omitted.
        #[arg(long, value_name = "ID")]
        operation_id: Option<String>,

        /// Refuse unless /readyz reports this node DID.
        #[arg(long, value_name = "DID")]
        expect_node: Option<DidNostr>,
    },
    /// Issue, list and revoke invitations (administrator).
    Invite {
        #[command(subcommand)]
        command: InviteCommand,
    },
    /// List, repair and cancel members (administrator).
    Member {
        #[command(subcommand)]
        command: MemberCommand,
    },
    /// Redeem an invitation with this key and activate the pod (tenant).
    ///
    /// Shows the node's admission notice and checks it is the one this
    /// client knows and that the node is the one the invitation names, asks
    /// for confirmation, redeems, waits for the pod, writes and reads a
    /// probe, and confirms. Safe to rerun after a partial run.
    Join(JoinArgs),
    /// Read and write resources in a pod (tenant).
    ///
    /// PATH is relative to your own pod root, or absolute `/pods/<pk>/…` for
    /// another member's pod (which needs their grant). Names may use only
    /// A-Z a-z 0-9 - . _ ~ (no spaces, no percent-encoding).
    Pod {
        #[command(subcommand)]
        command: PodCommand,
    },
    /// Export your own pod to a .tar.zst archive and a manifest (tenant).
    Export(ExportArgs),
}

#[derive(Debug, Subcommand)]
enum InviteCommand {
    /// Issue an invitation for one identity and print the invitee's
    /// `stratum join` command line.
    Create {
        /// The did:nostr of the person invited.
        did: DidNostr,

        /// Lifetime: seconds, or a number with s, m, h or d (at most 30d);
        /// the node's `membership.invitation_ttl_secs` when omitted.
        #[arg(long, value_name = "DURATION", value_parser = parse_duration)]
        expires_in: Option<Duration>,

        /// The gate address printed in the invitee's command line;
        /// 127.0.0.1:7461 when omitted.
        #[arg(long, value_name = "HOST:PORT")]
        connect: Option<ConnectAddress>,

        /// Operation ID to reuse when retrying; random when omitted.
        #[arg(long, value_name = "ID")]
        operation_id: Option<String>,

        /// Refuse unless /readyz reports this node DID.
        #[arg(long, value_name = "DID")]
        expect_node: Option<DidNostr>,
    },
    /// List invitations and their state.
    List,
    /// Revoke an invitation that is still issued.
    Revoke {
        /// The invitation identifier (32 hex characters).
        invitation: InvitationId,

        /// Operation ID to reuse when retrying; random when omitted.
        #[arg(long, value_name = "ID")]
        operation_id: Option<String>,
    },
}

#[derive(Debug, Subcommand)]
enum MemberCommand {
    /// List members, their state and pod, and the capacity in use.
    List,
    /// Run provisioning again for a member (restores a missing root ACL).
    Repair(MemberArgs),
    /// Cancel a reserved member, releasing its slot.
    Cancel(MemberArgs),
}

#[derive(Debug, Args)]
struct MemberArgs {
    /// The member's did:nostr.
    did: DidNostr,

    /// Operation ID to reuse when retrying; random when omitted.
    #[arg(long, value_name = "ID")]
    operation_id: Option<String>,

    /// Proceed without asking.
    #[arg(long, short = 'y')]
    yes: bool,
}

/// Where tenant commands reach the node.
#[derive(Debug, Args)]
struct GateArgs {
    /// The node's canonical origin, such as `https://stratum.visionclaw.pro`;
    /// every request is signed for it and names it in Host.
    #[arg(long, env = "STRATUM_ORIGIN", value_name = "ORIGIN")]
    origin: CanonicalOrigin,

    /// The loopback address of the gate, such as 127.0.0.1:7461; plain HTTP
    /// is sent there. Required for an https:// origin.
    #[arg(long, env = "STRATUM_CONNECT", value_name = "HOST:PORT")]
    connect: Option<ConnectAddress>,
}

impl GateArgs {
    fn target(self) -> Result<GateTarget, CliError> {
        GateTarget::new(self.origin, self.connect)
    }
}

#[derive(Debug, Args)]
struct JoinArgs {
    /// The invitation identifier the administrator gave you.
    #[arg(long, value_name = "ID")]
    invitation: InvitationId,

    /// The node DID the administrator gave you; the node reached must
    /// report it.
    #[arg(long, value_name = "DID")]
    node: DidNostr,

    #[command(flatten)]
    gate: GateArgs,

    /// How long to wait for the pod to be provisioned.
    #[arg(long, value_name = "SECONDS", default_value_t = 120)]
    wait_secs: u64,

    /// Accept the notice without asking.
    #[arg(long, short = 'y')]
    yes: bool,
}

#[derive(Debug, Subcommand)]
enum PodCommand {
    /// List a container (your pod root when PATH is omitted).
    Ls {
        /// The container.
        #[arg(default_value = "")]
        path: String,

        #[command(flatten)]
        gate: GateArgs,
    },
    /// Read a resource to standard output or a new file.
    Get {
        /// The resource.
        path: String,

        /// Write the bytes to this new file (mode 0600) instead.
        #[arg(short = 'o', long = "output", value_name = "FILE")]
        output: Option<PathBuf>,

        #[command(flatten)]
        gate: GateArgs,
    },
    /// Write a file to a resource.
    Put(PutArgs),
    /// Delete a resource or an empty container.
    Rm(RmArgs),
    /// Read or write the ACL beside a resource or container.
    Acl {
        #[command(subcommand)]
        command: AclCommand,
    },
}

#[derive(Debug, Args)]
struct RmArgs {
    /// The resource or container.
    path: String,

    #[command(flatten)]
    gate: GateArgs,

    /// Delete without asking.
    #[arg(long, short = 'y')]
    yes: bool,
}

#[derive(Debug, Subcommand)]
enum AclCommand {
    /// Read the ACL beside PATH (the root ACL `/pods/<pk>.acl` for the pod
    /// root, an empty PATH).
    Get {
        /// The resource or container whose ACL is read.
        #[arg(default_value = "")]
        path: String,

        /// Write the bytes to this new file (mode 0600) instead.
        #[arg(short = 'o', long = "output", value_name = "FILE")]
        output: Option<PathBuf>,

        #[command(flatten)]
        gate: GateArgs,
    },
    /// Write FILE as the ACL beside PATH (text/turtle unless
    /// --content-type is given).
    Put(PutArgs),
}

#[derive(Debug, Args)]
struct PutArgs {
    /// The resource (for `acl put`: the resource or container whose ACL is
    /// written; "" for the pod root).
    path: String,

    /// The file whose bytes are written (at most 1 GiB).
    file: PathBuf,

    /// The content type; guessed from the file name when omitted.
    #[arg(long, value_name = "TYPE")]
    content_type: Option<String>,

    /// Write only if the resource's entity tag is still this one.
    #[arg(long, value_name = "ETAG", conflicts_with = "create_only")]
    if_match: Option<String>,

    /// Write only if nothing is there yet.
    #[arg(long)]
    create_only: bool,

    #[command(flatten)]
    gate: GateArgs,
}

impl PutArgs {
    fn into_parts(self) -> (PutOptions, GateArgs) {
        let condition = match (self.if_match, self.create_only) {
            (Some(etag), _) => WriteCondition::IfMatch(etag),
            (None, true) => WriteCondition::CreateOnly,
            (None, false) => WriteCondition::Always,
        };
        (
            PutOptions {
                path: self.path,
                file: self.file,
                content_type: self.content_type,
                condition,
            },
            self.gate,
        )
    }
}

#[derive(Debug, Args)]
struct ExportArgs {
    /// The archive to write, such as pod.tar.zst; the manifest goes beside
    /// it as ARCHIVE.manifest.json.
    #[arg(short = 'o', long = "output", value_name = "ARCHIVE")]
    output: PathBuf,

    /// Replace an existing archive and manifest.
    #[arg(long)]
    force: bool,

    #[command(flatten)]
    gate: GateArgs,
}

#[derive(Debug, Subcommand)]
enum KeyCommand {
    /// Generate a new operator key into a new 0600 file; prints its DID and
    /// npub only.
    Generate {
        /// The key file to create; an existing file is never overwritten.
        #[arg(long, value_name = "FILE")]
        out: PathBuf,
    },
    /// Print the DID and npub of the key in --key-file.
    Show,
}

#[derive(Debug, Subcommand)]
enum ConfigCommand {
    /// Print the configuration schema.
    Schema,
    /// Print the effective configuration and revisions.
    Show,
    /// Show what a change would do, without applying it.
    Preview(PreviewArgs),
    /// Preview a change, confirm, then apply it.
    Apply(ApplyArgs),
}

#[derive(Debug, Subcommand)]
enum AuditCommand {
    /// Print the audit checkpoint `<seq>:<hex>` and the node DID.
    Checkpoint,
}

/// `--set` and `--base-revision`, shared by preview and apply.
#[derive(Debug, Args)]
struct ChangeArgs {
    /// A change, typed by the schema: booleans `true`/`false`, integers in
    /// decimal, strings as given; lists comma-separated or by repeating
    /// --set for the same path (`path=` is the empty list).
    #[arg(long = "set", value_name = "PATH=VALUE")]
    sets: Vec<String>,

    /// The revision the change is based on; the node's head when omitted.
    #[arg(long, value_name = "N")]
    base_revision: Option<u64>,
}

#[derive(Debug, Args)]
struct PreviewArgs {
    #[command(flatten)]
    changes: ChangeArgs,
}

#[derive(Debug, Args)]
struct ApplyArgs {
    #[command(flatten)]
    changes: ChangeArgs,

    /// Operation ID to reuse when retrying; random (and printed) when
    /// omitted.
    #[arg(long, value_name = "ID")]
    operation_id: Option<String>,

    /// Apply without asking.
    #[arg(long, short = 'y')]
    yes: bool,
}

#[derive(Debug, Args)]
struct SetupArgs {
    /// The node's bootstrap token file, STATE_DIR/bootstrap-token.
    #[arg(long, value_name = "FILE")]
    token_file: PathBuf,

    /// An initial configuration change (as for `config apply`); optional:
    /// with none, the node is claimed with its seed configuration.
    #[arg(long = "set", value_name = "PATH=VALUE")]
    sets: Vec<String>,

    /// The node DID stratumd printed at start. The bootstrap token is sent
    /// only if /readyz reports it. Without it, setup trusts whatever answers
    /// on the loopback port.
    #[arg(long, value_name = "DID")]
    expect_node: Option<DidNostr>,

    /// Also print the full configuration text whose SHA-256 the claim binds.
    #[arg(long)]
    show_text: bool,

    /// Where the signed claim is saved before sending (0600); defaults to
    /// KEY_FILE.setup-resume. If it exists, it is resent unchanged.
    #[arg(long, value_name = "FILE")]
    resume_file: Option<PathBuf>,

    /// Claim without asking.
    #[arg(long, short = 'y')]
    yes: bool,
}

/// Maps the `--yes` flag of a command that changes the node.
trait YesFlag {
    /// Returns the flag's value.
    fn yes(&self) -> bool;

    /// Returns [`Confirmation::Assumed`] under `--yes`, else
    /// [`Confirmation::Prompt`].
    fn confirmation(&self) -> Confirmation {
        if self.yes() {
            Confirmation::Assumed
        } else {
            Confirmation::Prompt
        }
    }
}

impl YesFlag for ApplyArgs {
    fn yes(&self) -> bool {
        self.yes
    }
}

impl YesFlag for SetupArgs {
    fn yes(&self) -> bool {
        self.yes
    }
}

impl YesFlag for MemberArgs {
    fn yes(&self) -> bool {
        self.yes
    }
}

impl YesFlag for JoinArgs {
    fn yes(&self) -> bool {
        self.yes
    }
}

impl YesFlag for RmArgs {
    fn yes(&self) -> bool {
        self.yes
    }
}

fn main() -> ExitCode {
    let cli = match Cli::try_parse() {
        Ok(cli) => cli,
        Err(err) => {
            let code = if err.use_stderr() {
                exit::USAGE
            } else {
                exit::OK
            };
            // Nothing useful can be done if printing the usage message fails.
            let _printed = err.print();
            return ExitCode::from(code);
        }
    };
    let output = Output::new(if cli.json {
        OutputFormat::Json
    } else {
        OutputFormat::Human
    });
    let session = Session::new(cli.url, cli.key_file, output);
    let result = match cli.command {
        Command::Key {
            command: KeyCommand::Generate { out },
        } => session.key_generate(&out),
        Command::Key {
            command: KeyCommand::Show,
        } => session.key_show(),
        Command::Status => session.status(),
        Command::Config { command } => match command {
            ConfigCommand::Schema => session.config_schema(),
            ConfigCommand::Show => session.config_show(),
            ConfigCommand::Preview(args) => {
                session.config_preview(&args.changes.sets, args.changes.base_revision)
            }
            ConfigCommand::Apply(args) => session.config_apply(&ApplyOptions {
                confirmation: args.confirmation(),
                sets: args.changes.sets,
                base_revision: args.changes.base_revision,
                operation_id: args.operation_id,
            }),
        },
        Command::Setup(args) => session.setup(&SetupOptions {
            confirmation: args.confirmation(),
            token_file: args.token_file,
            sets: args.sets,
            resume_file: args.resume_file,
            expect_node: args.expect_node,
            show_text: args.show_text,
        }),
        Command::SignChallenge {
            claim_body_file,
            expect_node,
        } => session.sign_challenge(&claim_body_file, &expect_node),
        Command::Audit {
            command: AuditCommand::Checkpoint,
        } => session.audit_checkpoint(),
        Command::Backup {
            operation_id,
            expect_node,
        } => session.backup(operation_id.as_deref(), expect_node.as_ref()),
        Command::Invite { command } => run_invite(&session, command),
        Command::Member { command } => run_member(&session, command),
        Command::Join(args) => {
            let confirmation = args.confirmation();
            args.gate.target().and_then(|target| {
                session.join(
                    &target,
                    &JoinOptions {
                        invitation: args.invitation,
                        node: args.node,
                        wait: Duration::from_secs(args.wait_secs),
                        confirmation,
                    },
                )
            })
        }
        Command::Pod { command } => run_pod(&session, command),
        Command::Export(args) => args.gate.target().and_then(|target| {
            session.export(
                &target,
                &ExportOptions {
                    output: args.output,
                    force: args.force,
                },
            )
        }),
    };
    match result {
        Ok(code) => ExitCode::from(code),
        Err(err) => {
            output.error(&err);
            ExitCode::from(err.exit_code())
        }
    }
}

/// Runs an `invite` command.
fn run_invite(session: &Session, command: InviteCommand) -> Result<u8, CliError> {
    match command {
        InviteCommand::Create {
            did,
            expires_in,
            connect,
            operation_id,
            expect_node,
        } => session.invite_create(&InviteOptions {
            subject: did,
            expires_in,
            operation_id,
            expect_node,
            gate: connect,
        }),
        InviteCommand::List => session.invite_list(),
        InviteCommand::Revoke {
            invitation,
            operation_id,
        } => session.invite_revoke(&invitation, operation_id.as_deref()),
    }
}

/// Runs a `member` command.
fn run_member(session: &Session, command: MemberCommand) -> Result<u8, CliError> {
    match command {
        MemberCommand::List => session.member_list(),
        MemberCommand::Repair(args) => {
            session.member_repair(&args.did, args.operation_id.as_deref(), args.confirmation())
        }
        MemberCommand::Cancel(args) => {
            session.member_cancel(&args.did, args.operation_id.as_deref(), args.confirmation())
        }
    }
}

/// Runs a `pod` command.
fn run_pod(session: &Session, command: PodCommand) -> Result<u8, CliError> {
    match command {
        PodCommand::Ls { path, gate } => session.pod_ls(&gate.target()?, &path),
        PodCommand::Get { path, output, gate } => {
            session.pod_get(&gate.target()?, &path, output.as_deref())
        }
        PodCommand::Put(args) => {
            let (options, gate) = args.into_parts();
            session.pod_put(&gate.target()?, &options)
        }
        PodCommand::Rm(args) => {
            let confirmation = args.confirmation();
            session.pod_rm(&args.gate.target()?, &args.path, confirmation)
        }
        PodCommand::Acl {
            command: AclCommand::Get { path, output, gate },
        } => session.pod_acl_get(&gate.target()?, &path, output.as_deref()),
        PodCommand::Acl {
            command: AclCommand::Put(args),
        } => {
            let (options, gate) = args.into_parts();
            session.pod_acl_put(&gate.target()?, &options)
        }
    }
}