shell-tunnel 0.4.0

Ultra-lightweight remote shell gateway with a REST/WebSocket API
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
//! Command-line interface for shell-tunnel.
//!
//! Uses lexopt for minimal binary size overhead (~34KB).

use std::ffi::OsString;
use std::net::IpAddr;
use std::path::PathBuf;

/// Command-line arguments.
#[derive(Debug, Clone)]
pub struct Args {
    /// Host address to bind to.
    pub host: IpAddr,
    /// Port to listen on.
    pub port: u16,
    /// Path to configuration file.
    pub config: Option<PathBuf>,
    /// API key for authentication (overrides config file).
    pub api_key: Option<String>,
    /// Disable authentication.
    pub no_auth: bool,
    /// Require authentication, auto-generating an API key if none is provided.
    pub require_auth: bool,
    /// Capability strings scoping the issued token(s) (empty = full-control).
    pub capabilities: Vec<String>,
    /// Role preset scoping the issued token(s) (operator/read-only/full-control).
    pub preset: Option<String>,
    /// Disable rate limiting.
    pub no_rate_limit: bool,
    /// Expose the server through a Cloudflare quick tunnel.
    pub tunnel: bool,
    /// Expose the server through an arbitrary tunnel command.
    pub tunnel_command: Option<String>,
    /// Run as a relay server (`shell-tunnel relay`) instead of a shell gateway.
    pub relay: bool,
    /// Attach to this relay instead of publishing through a tunnel.
    pub relay_url: Option<String>,
    /// Shared secret devices present to attach to this relay.
    pub enroll_token: Option<String>,
    /// Public base URL this relay is reachable at.
    pub public_base: Option<String>,
    /// Allow any CORS origin (permissive; opt-in for browser UIs).
    pub cors_allow_any: bool,
    /// Log level (error, warn, info, debug, trace).
    pub log_level: Option<String>,
    /// Show version and exit.
    pub version: bool,
    /// Show help and exit.
    pub help: bool,
    /// Check for updates and exit.
    pub check_update: bool,
    /// Perform self-update and exit.
    pub update: bool,
    /// Disable automatic update check on startup.
    pub no_update_check: bool,
}

impl Default for Args {
    fn default() -> Self {
        Self {
            host: "127.0.0.1".parse().unwrap(),
            port: 3000,
            config: None,
            api_key: None,
            no_auth: false,
            require_auth: false,
            capabilities: Vec::new(),
            preset: None,
            no_rate_limit: false,
            tunnel: false,
            tunnel_command: None,
            relay: false,
            relay_url: None,
            enroll_token: None,
            public_base: None,
            cors_allow_any: false,
            log_level: None,
            version: false,
            help: false,
            check_update: false,
            update: false,
            no_update_check: false,
        }
    }
}

/// Parse command-line arguments.
pub fn parse_args() -> Result<Args, ArgsError> {
    parse_args_from(std::env::args_os())
}

/// Parse arguments from an iterator (for testing).
pub fn parse_args_from<I>(args: I) -> Result<Args, ArgsError>
where
    I: IntoIterator<Item = OsString>,
{
    use lexopt::prelude::*;

    let mut result = Args::default();
    let mut parser = lexopt::Parser::from_iter(args);

    while let Some(arg) = parser.next()? {
        match arg {
            Short('h') | Long("help") => {
                result.help = true;
            }
            Short('V') | Long("version") => {
                result.version = true;
            }
            Short('H') | Long("host") => {
                let value: String = parser.value()?.parse()?;
                result.host = value
                    .parse()
                    .map_err(|_| ArgsError::InvalidValue("host", value))?;
            }
            Short('p') | Long("port") => {
                let value: String = parser.value()?.parse()?;
                result.port = value
                    .parse()
                    .map_err(|_| ArgsError::InvalidValue("port", value))?;
            }
            Short('c') | Long("config") => {
                result.config = Some(parser.value()?.parse()?);
            }
            Short('k') | Long("api-key") => {
                result.api_key = Some(parser.value()?.parse()?);
            }
            Long("no-auth") => {
                result.no_auth = true;
            }
            Long("require-auth") => {
                result.require_auth = true;
            }
            Long("capabilities") => {
                // Comma-separated; may be repeated. Accumulate non-empty entries.
                let value: String = parser.value()?.parse()?;
                result.capabilities.extend(
                    value
                        .split(',')
                        .map(|s| s.trim())
                        .filter(|s| !s.is_empty())
                        .map(String::from),
                );
            }
            Long("preset") => {
                result.preset = Some(parser.value()?.parse()?);
            }
            Long("no-rate-limit") => {
                result.no_rate_limit = true;
            }
            Long("tunnel") => {
                result.tunnel = true;
            }
            Long("tunnel-command") => {
                result.tunnel_command = Some(parser.value()?.parse()?);
            }
            Long("relay") => {
                result.relay_url = Some(parser.value()?.parse()?);
            }
            Long("enroll-token") => {
                result.enroll_token = Some(parser.value()?.parse()?);
            }
            Long("public-base") => {
                result.public_base = Some(parser.value()?.parse()?);
            }
            Long("cors-allow-any") => {
                result.cors_allow_any = true;
            }
            Short('l') | Long("log-level") => {
                result.log_level = Some(parser.value()?.parse()?);
            }
            #[cfg(feature = "self-update")]
            Long("check-update") => {
                result.check_update = true;
            }
            #[cfg(feature = "self-update")]
            Long("update") => {
                result.update = true;
            }
            #[cfg(feature = "self-update")]
            Long("no-update-check") => {
                result.no_update_check = true;
            }
            // The only positional is the `relay` subcommand, which switches the
            // binary into relay-server mode. Bind address and port keep using
            // -H/-p so one CLI vocabulary covers both modes.
            Value(val) if val == "relay" && !result.relay => {
                result.relay = true;
            }
            Value(val) => {
                return Err(ArgsError::UnexpectedArgument(val.to_string_lossy().into()));
            }
            _ => return Err(arg.unexpected().into()),
        }
    }

    // Relay mode serves devices, not shells: a tunnel would publish the wrong
    // thing entirely.
    if result.relay && (result.tunnel || result.tunnel_command.is_some()) {
        return Err(ArgsError::Conflicting("relay", "--tunnel"));
    }
    if result.relay_url.is_some() && result.tunnel {
        return Err(ArgsError::Conflicting("--relay", "--tunnel"));
    }
    if result.relay_url.is_some() && result.tunnel_command.is_some() {
        return Err(ArgsError::Conflicting("--relay", "--tunnel-command"));
    }

    // Reachability paths are mutually exclusive: two tunnels would each publish
    // a different public URL for the same server, and only one can be reported.
    if result.tunnel && result.tunnel_command.is_some() {
        return Err(ArgsError::Conflicting("--tunnel", "--tunnel-command"));
    }

    Ok(result)
}

/// Print help message.
pub fn print_help() {
    let version = env!("CARGO_PKG_VERSION");

    // Update flags exist only when compiled with the `self-update` feature.
    #[cfg(feature = "self-update")]
    let update_opts = "        --check-update      Check for updates and exit\n        --update            Download and install latest version\n        --no-update-check   Disable automatic update check on startup\n";
    #[cfg(not(feature = "self-update"))]
    let update_opts = "";

    #[cfg(feature = "self-update")]
    let update_examples = "\n    # Check for updates\n    shell-tunnel --check-update\n\n    # Self-update to latest version\n    shell-tunnel --update\n";
    #[cfg(not(feature = "self-update"))]
    let update_examples = "";

    println!(
        r#"shell-tunnel {version}
Ultra-lightweight remote shell gateway with a REST/WebSocket API

USAGE:
    shell-tunnel [OPTIONS]              Serve a shell gateway
    shell-tunnel relay [OPTIONS]        Serve a relay that devices dial out to

OPTIONS:
    -H, --host <ADDR>       Host address to bind [default: 127.0.0.1]
    -p, --port <PORT>       Port to listen on [default: 3000]
    -c, --config <FILE>     Path to configuration file (JSON)
    -k, --api-key <KEY>     API key for authentication
    -l, --log-level <LVL>   Log level (error, warn, info, debug, trace)
        --no-auth           Disable authentication
        --require-auth      Require auth, auto-generating an API key if none given
        --capabilities <C>  Scope issued token(s): comma-separated capabilities
                            (e.g. exec,session.read). Default: full-control
        --preset <NAME>     Scope issued token(s) by role preset
                            (operator | read-only | full-control)
        --no-rate-limit     Disable rate limiting
        --tunnel            Expose publicly via a Cloudflare quick tunnel
                            (requires `cloudflared`; implies authentication)
        --tunnel-command <C>
                            Expose publicly by running an arbitrary tunnel
                            command (ngrok, bore, frp, ...); its printed URL
                            is used. Implies authentication
        --relay <URL>       Attach to a self-hosted relay (dial out, no inbound
                            port). Needs --enroll-token; implies authentication
        --cors-allow-any    Allow any CORS origin (opt-in; for browser UIs)

RELAY OPTIONS (with `relay`):
        --enroll-token <T>  Secret devices present to attach (generated if unset)
        --public-base <URL> Public base URL of this relay
                            [default: http://<bind address>]
{update_opts}    -h, --help              Print help
    -V, --version           Print version

ENVIRONMENT VARIABLES:
    SHELL_TUNNEL_HOST       Host address (overrides config)
    SHELL_TUNNEL_PORT       Port number (overrides config)
    SHELL_TUNNEL_API_KEY    API key (overrides config)
    SHELL_TUNNEL_LOG_LEVEL  Log level (overrides config)
    RUST_LOG                Alternative log level setting

EXAMPLES:
    # Start with defaults (localhost:3000, no auth)
    shell-tunnel

    # Start on all interfaces with API key
    shell-tunnel -H 0.0.0.0 -p 8080 -k my-secret-key

    # Start with config file
    shell-tunnel -c /etc/shell-tunnel/config.json

    # Development mode (no security)
    shell-tunnel --no-auth --no-rate-limit

    # Publish on the internet with a generated key (no account needed)
    shell-tunnel --tunnel

    # Publish using a different tunnel client
    shell-tunnel --tunnel-command "ngrok http 3000"

    # Run a relay devices can dial out to
    shell-tunnel relay -H 0.0.0.0 -p 8443 --public-base https://relay.example.com

    # Issue a fine-grained, read-only token
    shell-tunnel -k readonly-key --preset read-only

    # Issue a token scoped to specific capabilities
    shell-tunnel -k ci-key --capabilities exec,session.read
{update_examples}"#
    );
}

/// Print version.
pub fn print_version() {
    println!("shell-tunnel {}", env!("CARGO_PKG_VERSION"));
}

/// Argument parsing errors.
#[derive(Debug)]
pub enum ArgsError {
    /// Lexopt parsing error.
    Lexopt(lexopt::Error),
    /// Invalid argument value.
    InvalidValue(&'static str, String),
    /// Unexpected positional argument.
    UnexpectedArgument(String),
    /// Two mutually exclusive flags were given.
    Conflicting(&'static str, &'static str),
}

impl std::fmt::Display for ArgsError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Lexopt(e) => write!(f, "{}", e),
            Self::InvalidValue(name, value) => {
                write!(f, "invalid value for --{}: '{}'", name, value)
            }
            Self::UnexpectedArgument(arg) => {
                write!(f, "unexpected argument: '{}'", arg)
            }
            Self::Conflicting(a, b) => {
                write!(f, "{} and {} cannot be used together", a, b)
            }
        }
    }
}

impl std::error::Error for ArgsError {}

impl From<lexopt::Error> for ArgsError {
    fn from(e: lexopt::Error) -> Self {
        Self::Lexopt(e)
    }
}

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

    fn args(args: &[&str]) -> Vec<OsString> {
        std::iter::once("shell-tunnel")
            .chain(args.iter().copied())
            .map(OsString::from)
            .collect()
    }

    #[test]
    fn test_default_args() {
        let result = parse_args_from(args(&[])).unwrap();
        assert_eq!(result.host.to_string(), "127.0.0.1");
        assert_eq!(result.port, 3000);
        assert!(!result.no_auth);
    }

    #[test]
    fn test_host_port() {
        let result = parse_args_from(args(&["-H", "0.0.0.0", "-p", "8080"])).unwrap();
        assert_eq!(result.host.to_string(), "0.0.0.0");
        assert_eq!(result.port, 8080);
    }

    #[test]
    fn test_long_options() {
        let result = parse_args_from(args(&["--host", "192.168.1.1", "--port", "9000"])).unwrap();
        assert_eq!(result.host.to_string(), "192.168.1.1");
        assert_eq!(result.port, 9000);
    }

    #[test]
    fn test_api_key() {
        let result = parse_args_from(args(&["-k", "my-secret"])).unwrap();
        assert_eq!(result.api_key, Some("my-secret".to_string()));
    }

    #[test]
    fn test_config_file() {
        let result = parse_args_from(args(&["-c", "/etc/config.json"])).unwrap();
        assert_eq!(result.config, Some(PathBuf::from("/etc/config.json")));
    }

    #[test]
    fn test_no_auth() {
        let result = parse_args_from(args(&["--no-auth"])).unwrap();
        assert!(result.no_auth);
    }

    #[test]
    fn test_require_auth() {
        let result = parse_args_from(args(&["--require-auth"])).unwrap();
        assert!(result.require_auth);
        assert!(!Args::default().require_auth);
    }

    #[test]
    fn test_no_rate_limit() {
        let result = parse_args_from(args(&["--no-rate-limit"])).unwrap();
        assert!(result.no_rate_limit);
    }

    #[test]
    fn test_capabilities_csv() {
        let result = parse_args_from(args(&["--capabilities", "exec,session.read"])).unwrap();
        assert_eq!(result.capabilities, vec!["exec", "session.read"]);
        assert!(Args::default().capabilities.is_empty());
    }

    #[test]
    fn test_capabilities_trims_and_ignores_blanks() {
        let result = parse_args_from(args(&["--capabilities", " exec , , session.read "])).unwrap();
        assert_eq!(result.capabilities, vec!["exec", "session.read"]);
    }

    #[test]
    fn test_capabilities_repeated_accumulate() {
        let result = parse_args_from(args(&[
            "--capabilities",
            "exec",
            "--capabilities",
            "session.read,session.manage",
        ]))
        .unwrap();
        assert_eq!(
            result.capabilities,
            vec!["exec", "session.read", "session.manage"]
        );
    }

    #[test]
    fn test_preset() {
        let result = parse_args_from(args(&["--preset", "operator"])).unwrap();
        assert_eq!(result.preset, Some("operator".to_string()));
        assert!(Args::default().preset.is_none());
    }

    #[test]
    fn test_help_flag() {
        let result = parse_args_from(args(&["-h"])).unwrap();
        assert!(result.help);

        let result = parse_args_from(args(&["--help"])).unwrap();
        assert!(result.help);
    }

    #[test]
    fn test_version_flag() {
        let result = parse_args_from(args(&["-V"])).unwrap();
        assert!(result.version);

        let result = parse_args_from(args(&["--version"])).unwrap();
        assert!(result.version);
    }

    #[test]
    fn test_log_level() {
        let result = parse_args_from(args(&["-l", "debug"])).unwrap();
        assert_eq!(result.log_level, Some("debug".to_string()));
    }

    #[test]
    fn test_invalid_port() {
        let result = parse_args_from(args(&["-p", "invalid"]));
        assert!(result.is_err());
    }

    #[test]
    fn test_invalid_host() {
        let result = parse_args_from(args(&["-H", "not-an-ip"]));
        assert!(result.is_err());
    }

    #[test]
    fn test_combined_options() {
        let result = parse_args_from(args(&[
            "-H",
            "0.0.0.0",
            "-p",
            "8080",
            "-k",
            "secret",
            "-l",
            "debug",
            "--no-rate-limit",
        ]))
        .unwrap();

        assert_eq!(result.host.to_string(), "0.0.0.0");
        assert_eq!(result.port, 8080);
        assert_eq!(result.api_key, Some("secret".to_string()));
        assert_eq!(result.log_level, Some("debug".to_string()));
        assert!(result.no_rate_limit);
        assert!(!result.no_auth);
    }

    #[test]
    fn test_tunnel_flag() {
        let result = parse_args_from(vec![
            OsString::from("shell-tunnel"),
            OsString::from("--tunnel"),
        ])
        .unwrap();
        assert!(result.tunnel);
        assert!(result.tunnel_command.is_none());
    }

    #[test]
    fn test_tunnel_command_flag() {
        let result = parse_args_from(vec![
            OsString::from("shell-tunnel"),
            OsString::from("--tunnel-command"),
            OsString::from("ngrok http 3000"),
        ])
        .unwrap();
        assert_eq!(result.tunnel_command.as_deref(), Some("ngrok http 3000"));
        assert!(!result.tunnel);
    }

    #[test]
    fn test_tunnel_paths_are_mutually_exclusive() {
        let err = parse_args_from(vec![
            OsString::from("shell-tunnel"),
            OsString::from("--tunnel"),
            OsString::from("--tunnel-command"),
            OsString::from("bore local 3000 --to bore.pub"),
        ])
        .unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("--tunnel"), "{msg}");
        assert!(msg.contains("cannot be used together"), "{msg}");
    }

    #[test]
    fn test_no_tunnel_by_default() {
        let result = parse_args_from(vec![OsString::from("shell-tunnel")]).unwrap();
        assert!(!result.tunnel);
        assert!(result.tunnel_command.is_none());
    }
}