pb-mapper-cli 0.5.1

Unified CLI and relay server for pb-mapper
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
//! Unified command-line entry point for every pb-mapper role.
//!
//! ```text
//!                       +-> server   (relay)
//! process args -> clap -+-> register (publish a local service)
//!                       +-> connect  (open a local listener)
//!                       +-> status   (namespace-scoped inspection)
//!                       +-> admin    (credential/control plane)
//! ```
//!
//! Role-specific execution stays below this dispatch layer. Administrator parsing,
//! pagination, wire requests, and output rendering live in the `admin` module.

use std::error::Error;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use std::path::PathBuf;
use std::time::Duration;

use better_mimalloc_rs::MiMalloc;
use clap::{Args, Parser, Subcommand, ValueEnum};
use pb_mapper_auth::{
    AuthConfig, KeyPage, LegacyProtocolPolicy, MAX_TEMP_KEY_CAPACITY, MAX_TEMP_KEY_TTL,
    MIN_TEMP_KEY_TTL, acquire_state_dir_lock, discard_staged_admin_key, generate_admin_key,
    initialize_admin_key, stage_admin_key_candidate, write_admin_key_file,
};
use pb_mapper_client::client::{
    handle_status_cli_scoped, run_client_side_cli_with_callback_scoped,
};
use pb_mapper_client::server::{ServerTunnelOptions, run_server_side_cli_with_pinned_credential};
use pb_mapper_core::checksum::set_process_msg_header_key;
use pb_mapper_core::checksum::{MACHINE_MSG_HEADER_KEY_PATH, setup_machine_msg_header_key};
use pb_mapper_core::config::{
    ResolvedAddrs, StatusOp, init_tracing, keep_alive_from_env, pb_mapper_server_addr,
    resolve_addrs_async, resolve_pb_mapper_server_async,
};
use pb_mapper_protocol::command::{
    AdminConnectionPage, AdminRequest, AdminResponse, AdminServicePage,
};
use pb_mapper_protocol::forward::StreamForward;
use pb_mapper_server::run_server_with_shutdown;
use tokio_util::sync::CancellationToken;
use uni_stream::stream::{
    StreamProvider, TcpListenerProvider, TcpStreamProvider, UdpListenerProvider, UdpStreamProvider,
};

#[global_allocator]
static GLOBAL_MIMALLOC: MiMalloc = MiMalloc;

#[derive(Debug, Parser)]
#[command(
    author = "L_B__",
    version,
    about = "Expose and consume keyed TCP/UDP services through a pb-mapper relay",
    subcommand_required = true,
    arg_required_else_help = true
)]
struct Cli {
    #[command(subcommand)]
    command: Command,
}

#[derive(Debug, Subcommand)]
enum Command {
    /// Run the public relay server.
    Server(ServerArgs),
    /// Register a local service with a relay.
    Register(RegisterArgs),
    /// Expose a registered service on a local listening address.
    Connect(ConnectArgs),
    /// Query relay status.
    Status(StatusArgs),
    /// Manage temporary credentials and inspect relay authentication state.
    Admin(AdminArgs),
}

#[derive(Debug, Args)]
struct ServerArgs {
    /// Port exposed to registering services and connecting clients.
    #[arg(short, long, visible_alias = "pb-mapper-port", default_value_t = 7666)]
    port: u16,
    /// Listen on IPv6 (::) instead of IPv4 (0.0.0.0).
    #[arg(long, visible_alias = "use-ipv6", default_value_t = false)]
    ipv6: bool,
    /// Enable TCP keep-alive. PB_MAPPER_KEEP_ALIVE=ON is also supported.
    #[arg(long, default_value_t = false)]
    keep_alive: bool,
    /// Derive MSG_HEADER_KEY from this machine and persist it for other roles.
    #[arg(long, default_value_t = false)]
    use_machine_msg_header_key: bool,
    /// Directory containing encrypted authentication state and the administrator key file.
    /// Defaults to /var/lib/pb-mapper/auth for Linux services or a writable system
    /// directory; otherwise a user-writable application directory.
    #[arg(long)]
    auth_state_dir: Option<PathBuf>,
    /// Create a random administrator key before starting the relay.
    #[arg(
        long,
        conflicts_with = "use_machine_msg_header_key",
        default_value_t = false
    )]
    init_admin_key: bool,
    /// Replace an existing administrator key when used with --init-admin-key.
    #[arg(long, requires = "init_admin_key", default_value_t = false)]
    force_init_admin_key: bool,
    /// Maximum temporary-key slots allocated by the relay.
    #[arg(long)]
    max_temporary_keys: Option<usize>,
    /// Maximum accepted temporary-key TTL.
    #[arg(long, value_parser = parse_duration)]
    max_temporary_key_ttl: Option<Duration>,
    /// Allow or deny the legacy encrypted framing protocol.
    #[arg(long, value_enum)]
    legacy_protocol: Option<LegacyProtocolArg>,
}

#[path = "pb-mapper/admin.rs"]
mod admin;
use admin::AdminArgs;
#[derive(Debug, Args)]
struct RegisterArgs {
    /// Transport used by the local service.
    #[arg(value_enum)]
    transport: Transport,
    /// Service key registered with the relay.
    #[arg(short, long)]
    key: String,
    /// Local service address to forward to.
    #[arg(short, long, visible_alias = "local")]
    addr: String,
    #[command(flatten)]
    relay: RelayArgs,
    /// Encrypt forwarded traffic with the configured MSG_HEADER_KEY.
    #[arg(short, long, default_value_t = false)]
    codec: bool,
    /// Administrator-only target namespace. Temporary credentials always use their own key id.
    #[arg(long)]
    namespace: Option<u64>,
    /// Required when an administrator registers a service inside a temporary-key namespace.
    #[arg(long, requires = "namespace", default_value_t = false)]
    force: bool,
}

#[derive(Debug, Args)]
struct ConnectArgs {
    /// Transport exposed by the local listener.
    #[arg(value_enum)]
    transport: Transport,
    /// Registered service key to subscribe to.
    #[arg(short, long)]
    key: String,
    /// Local address on which downstream clients connect.
    #[arg(short, long, visible_alias = "local")]
    addr: String,
    #[command(flatten)]
    relay: RelayArgs,
    /// Administrator-only target namespace. Temporary credentials always use their own key id.
    #[arg(long)]
    namespace: Option<u64>,
}

#[derive(Debug, Args)]
struct StatusArgs {
    /// Status query to execute.
    #[arg(value_enum)]
    op: StatusOp,
    /// Relay address. Falls back to PB_MAPPER_SERVER.
    #[arg(short, long, visible_alias = "pb-mapper-server", value_name = "ADDR")]
    server: Option<String>,
    /// Administrator-only namespace to inspect.
    #[arg(long)]
    namespace: Option<u64>,
}

#[derive(Debug, Args)]
struct RelayArgs {
    /// Relay address. Falls back to PB_MAPPER_SERVER.
    #[arg(short, long, visible_alias = "pb-mapper-server", value_name = "ADDR")]
    server: Option<String>,
    /// Enable TCP keep-alive. PB_MAPPER_KEEP_ALIVE=ON is also supported.
    #[arg(long, default_value_t = false)]
    keep_alive: bool,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, ValueEnum)]
enum Transport {
    Tcp,
    Udp,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, ValueEnum)]
enum LegacyProtocolArg {
    Allow,
    Deny,
}

impl From<LegacyProtocolArg> for LegacyProtocolPolicy {
    fn from(value: LegacyProtocolArg) -> Self {
        match value {
            LegacyProtocolArg::Allow => Self::Allow,
            LegacyProtocolArg::Deny => Self::Deny,
        }
    }
}

#[tokio::main]
async fn main() {
    MiMalloc::init();
    let cli = Cli::parse();
    init_tracing();

    if let Err(error) = run(cli).await {
        tracing::error!(%error, "pb-mapper command failed");
        std::process::exit(1);
    }
}

async fn run(cli: Cli) -> Result<(), Box<dyn Error>> {
    match cli.command {
        Command::Server(args) => run_server(args).await?,
        Command::Register(args) => run_register(args).await?,
        Command::Connect(args) => run_connect(args).await?,
        Command::Status(args) => run_status(args).await?,
        Command::Admin(args) => admin::run_admin(args).await?,
    }
    Ok(())
}

/// Publishes CLI flags as environment variables, which is how the auth
/// subsystem reads its configuration.
///
/// # Safety note
///
/// Mutating the environment is unsafe in edition 2024 because it races
/// concurrent readers. Every call here happens during argument handling on the
/// main thread, before any runtime task or thread is spawned, so there is no
/// concurrent reader to race.
fn apply_server_auth_overrides(args: &ServerArgs) -> Result<(), Box<dyn Error>> {
    if let Some(auth_state_dir) = &args.auth_state_dir {
        unsafe { std::env::set_var("PB_MAPPER_AUTH_STATE_DIR", auth_state_dir) };
    }
    if let Some(max_temporary_keys) = args.max_temporary_keys {
        if !(1..=MAX_TEMP_KEY_CAPACITY).contains(&max_temporary_keys) {
            return Err(format!(
                "`--max-temporary-keys` must be between 1 and {MAX_TEMP_KEY_CAPACITY}"
            )
            .into());
        }
        unsafe {
            std::env::set_var(
                "PB_MAPPER_AUTH_MAX_TEMP_KEYS",
                max_temporary_keys.to_string(),
            )
        };
    }
    if let Some(max_temporary_key_ttl) = args.max_temporary_key_ttl {
        if max_temporary_key_ttl < MIN_TEMP_KEY_TTL || max_temporary_key_ttl > MAX_TEMP_KEY_TTL {
            return Err(format!(
                "`--max-temporary-key-ttl` must be between {}s and {}d",
                MIN_TEMP_KEY_TTL.as_secs(),
                MAX_TEMP_KEY_TTL.as_secs() / 86_400
            )
            .into());
        }
        unsafe {
            std::env::set_var(
                "PB_MAPPER_AUTH_MAX_TEMP_TTL_SECS",
                max_temporary_key_ttl.as_secs().to_string(),
            )
        };
    }
    Ok(())
}

async fn run_server(args: ServerArgs) -> Result<(), Box<dyn Error>> {
    apply_server_auth_overrides(&args)?;
    if let Some(legacy_protocol) = args.legacy_protocol {
        // SAFETY: as in `apply_server_auth_overrides` — this runs before the
        // server spawns anything that reads the environment.
        unsafe {
            std::env::set_var(
                "PB_MAPPER_LEGACY_PROTOCOL",
                match legacy_protocol {
                    LegacyProtocolArg::Allow => "allow",
                    LegacyProtocolArg::Deny => "deny",
                },
            )
        };
    }
    let auth_config = AuthConfig::default();
    if args.init_admin_key {
        std::fs::create_dir_all(&auth_config.state_dir)?;
        let _lock = acquire_state_dir_lock(&auth_config.state_dir)?;
        let key_path = auth_config.state_dir.join("admin.key");
        let key = initialize_admin_key(&key_path, args.force_init_admin_key)?;
        drop(_lock);
        set_process_msg_header_key(Some(&key))?;
        eprintln!("administrator key initialized at {}", key_path.display());
    } else if args.use_machine_msg_header_key {
        let admin_key_path = auth_config.state_dir.join("admin.key");
        if admin_key_path.exists() {
            return Err(format!(
                "--use-machine-msg-header-key cannot replace `{}`; use `pb-mapper admin root-key rotate` to change the root key",
                admin_key_path.display()
            )
            .into());
        }
        tracing::warn!(
            "--use-machine-msg-header-key is a legacy compatibility option; prefer a random administrator key"
        );
        setup_machine_msg_header_key()?;
        tracing::info!(
            path = MACHINE_MSG_HEADER_KEY_PATH,
            "derived and persisted machine MSG_HEADER_KEY"
        );
    }

    let ip_addr = if args.ipv6 {
        IpAddr::V6(Ipv6Addr::UNSPECIFIED)
    } else {
        IpAddr::V4(Ipv4Addr::UNSPECIFIED)
    };
    run_server_with_shutdown(
        (ip_addr, args.port),
        CancellationToken::new(),
        None,
        args.keep_alive || keep_alive_from_env(),
    )
    .await?;
    Ok(())
}

async fn run_register(args: RegisterArgs) -> Result<(), Box<dyn Error>> {
    let credential = pb_mapper_core::checksum::get_process_credential().map_err(|error| {
        std::io::Error::other(format!("registration credential is required: {error}"))
    })?;
    let local_addr = resolve_addrs_async(&args.addr).await?;
    let remote_addr = resolve_pb_mapper_server_async(args.relay.server.as_deref()).await?;
    let options = ServerTunnelOptions {
        need_codec: args.codec,
        is_datagram: args.transport == Transport::Udp,
        keep_alive: args.relay.keep_alive || keep_alive_from_env(),
        namespace: args.namespace,
        force_namespace: args.force,
    };

    match args.transport {
        Transport::Tcp => {
            register::<TcpStreamProvider>(local_addr, remote_addr, args.key, options, credential)
                .await
        }
        Transport::Udp => {
            register::<UdpStreamProvider>(local_addr, remote_addr, args.key, options, credential)
                .await
        }
    }
    Ok(())
}

async fn register<LocalStream: StreamProvider + Send + 'static>(
    local_addr: ResolvedAddrs,
    remote_addr: ResolvedAddrs,
    key: String,
    options: ServerTunnelOptions,
    credential: pb_mapper_core::checksum::Credential,
) where
    LocalStream::Item: StreamForward,
{
    run_server_side_cli_with_pinned_credential::<LocalStream, _>(
        local_addr.as_slice(),
        remote_addr.as_slice(),
        key.into(),
        options,
        None,
        credential,
    )
    .await;
}

async fn run_connect(args: ConnectArgs) -> Result<(), Box<dyn Error>> {
    let credential = pb_mapper_core::checksum::get_process_credential().map_err(|error| {
        std::io::Error::other(format!("client credential is required: {error}"))
    })?;
    let local_addr = resolve_addrs_async(&args.addr).await?;
    let remote_addr = resolve_pb_mapper_server_async(args.relay.server.as_deref()).await?;
    let key = args.key.into();
    let keep_alive = args.relay.keep_alive || keep_alive_from_env();

    match args.transport {
        Transport::Tcp => {
            run_client_side_cli_with_callback_scoped::<TcpListenerProvider, _>(
                local_addr.as_slice(),
                remote_addr.as_slice(),
                key,
                keep_alive,
                args.namespace,
                None,
                Some(credential),
            )
            .await;
        }
        Transport::Udp => {
            run_client_side_cli_with_callback_scoped::<UdpListenerProvider, _>(
                local_addr.as_slice(),
                remote_addr.as_slice(),
                key,
                keep_alive,
                args.namespace,
                None,
                Some(credential),
            )
            .await;
        }
    }
    Ok(())
}

async fn run_status(args: StatusArgs) -> Result<(), Box<dyn Error>> {
    let remote_addr = resolve_pb_mapper_server_async(args.server.as_deref()).await?;
    handle_status_cli_scoped(args.op, remote_addr.as_slice(), args.namespace).await
}

fn parse_duration(raw: &str) -> Result<Duration, String> {
    let raw = raw.trim();
    if raw.is_empty() {
        return Err("duration must not be empty".to_string());
    }
    let split = raw
        .find(|character: char| !character.is_ascii_digit())
        .unwrap_or(raw.len());
    let (number, unit) = raw.split_at(split);
    let value = number
        .parse::<u64>()
        .map_err(|_| format!("invalid duration `{raw}`"))?;
    let multiplier = match unit {
        "" | "s" => 1,
        "m" => 60,
        "h" => 60 * 60,
        "d" => 24 * 60 * 60,
        _ => {
            return Err(format!(
                "unsupported duration unit `{unit}`; use s, m, h, or d"
            ));
        }
    };
    value
        .checked_mul(multiplier)
        .map(Duration::from_secs)
        .ok_or_else(|| "duration is too large".to_string())
}

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

    #[test]
    fn parses_each_runtime_role() {
        let cases = [
            vec!["pb-mapper", "server", "--port", "7666", "--ipv6"],
            vec![
                "pb-mapper",
                "register",
                "tcp",
                "--key",
                "web",
                "--addr",
                "127.0.0.1:8080",
                "--server",
                "relay:7666",
                "--codec",
            ],
            vec![
                "pb-mapper",
                "connect",
                "udp",
                "--key",
                "game",
                "--addr",
                "127.0.0.1:8211",
                "--server",
                "relay:7666",
            ],
            vec!["pb-mapper", "status", "keys", "--server", "relay:7666"],
            vec![
                "pb-mapper",
                "admin",
                "--server",
                "relay:7666",
                "key",
                "issue",
                "--ttl",
                "30d",
                "--label",
                "build-agent",
            ],
            vec![
                "pb-mapper",
                "admin",
                "--output",
                "ndjson",
                "connection",
                "list",
                "--page-size",
                "1000",
                "--all",
            ],
            vec![
                "pb-mapper",
                "admin",
                "root-key",
                "rotate",
                "--key-file",
                "/tmp/pb-mapper-admin.key",
            ],
        ];

        for args in cases {
            Cli::try_parse_from(args).expect("unified command should parse");
        }
    }

    #[test]
    fn accepts_documented_option_aliases() {
        Cli::try_parse_from([
            "pb-mapper",
            "server",
            "--pb-mapper-port",
            "7666",
            "--use-ipv6",
        ])
        .expect("server aliases should parse");
        Cli::try_parse_from([
            "pb-mapper",
            "register",
            "tcp",
            "--key",
            "web",
            "--local",
            "127.0.0.1:8080",
            "--pb-mapper-server",
            "relay:7666",
        ])
        .expect("relay and local aliases should parse");
        Cli::try_parse_from([
            "pb-mapper",
            "register",
            "tcp",
            "--key",
            "web",
            "--addr",
            "127.0.0.1:8080",
            "--namespace",
            "4294967296",
            "--force",
        ])
        .expect("administrator namespace registration flags should parse");
    }

    #[test]
    fn rejects_invalid_admin_paging_and_duration() {
        assert!(
            Cli::try_parse_from(["pb-mapper", "admin", "key", "list", "--page-size", "1001",])
                .is_err()
        );
        assert!(
            Cli::try_parse_from(["pb-mapper", "admin", "key", "issue", "--ttl", "1fortnight",])
                .is_err()
        );
        assert!(
            Cli::try_parse_from([
                "pb-mapper",
                "server",
                "--init-admin-key",
                "--use-machine-msg-header-key",
            ])
            .is_err()
        );
    }

    #[test]
    fn server_auth_options_only_override_environment_when_explicit() {
        let cli =
            Cli::try_parse_from(["pb-mapper", "server"]).expect("server defaults should parse");
        let Command::Server(defaults) = cli.command else {
            panic!("expected server command");
        };
        assert_eq!(defaults.auth_state_dir, None);
        assert_eq!(defaults.max_temporary_keys, None);
        assert_eq!(defaults.max_temporary_key_ttl, None);
        assert_eq!(defaults.legacy_protocol, None);

        let cli = Cli::try_parse_from([
            "pb-mapper",
            "server",
            "--auth-state-dir",
            "/tmp/pb-mapper-auth",
            "--max-temporary-keys",
            "1024",
            "--max-temporary-key-ttl",
            "2h",
            "--legacy-protocol",
            "deny",
        ])
        .expect("explicit server authentication options should parse");
        let Command::Server(explicit) = cli.command else {
            panic!("expected server command");
        };
        assert_eq!(
            explicit.auth_state_dir,
            Some(PathBuf::from("/tmp/pb-mapper-auth"))
        );
        assert_eq!(explicit.max_temporary_keys, Some(1024));
        assert_eq!(
            explicit.max_temporary_key_ttl,
            Some(Duration::from_secs(2 * 60 * 60))
        );
        assert_eq!(explicit.legacy_protocol, Some(LegacyProtocolArg::Deny));
    }

    #[test]
    fn explicit_out_of_range_server_auth_flags_are_rejected() {
        let cli = Cli::try_parse_from(["pb-mapper", "server", "--max-temporary-keys", "0"])
            .expect("clap should accept the token before bounds checking");
        let Command::Server(args) = cli.command else {
            panic!("expected server command");
        };
        let error = apply_server_auth_overrides(&args).unwrap_err();
        assert!(error.to_string().contains("--max-temporary-keys"));

        let cli = Cli::try_parse_from(["pb-mapper", "server", "--max-temporary-key-ttl", "5s"])
            .expect("clap should accept the token before bounds checking");
        let Command::Server(args) = cli.command else {
            panic!("expected server command");
        };
        let error = apply_server_auth_overrides(&args).unwrap_err();
        assert!(error.to_string().contains("--max-temporary-key-ttl"));
    }
}