nono-cli 0.61.1

CLI for nono capability-based sandbox
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
//! nono CLI - Capability-based sandbox for AI agents
//!
//! This is the CLI binary that uses the nono library for OS-level sandboxing.

mod app_runtime;
mod audit_attestation;
mod audit_commands;
mod audit_integrity;
mod audit_ledger;
mod audit_session;
mod capability_ext;
mod cli;
mod cli_bootstrap;
mod command_blocking_deprecation;
mod command_display;
mod command_runtime;
mod completions;
mod config;
mod credential_runtime;
mod deprecated_policy;
mod deprecated_schema;
mod deprecation_warnings;
mod exec_strategy;
mod execution_runtime;
#[cfg(unix)]
mod hook_runtime;
mod instruction_deny;
mod jsonc;
mod launch_runtime;
mod learn;
mod learn_runtime;
mod legacy_cleanup;
#[cfg(target_os = "macos")]
mod macos_trust;
mod migration;
mod network_policy;
mod open_url_runtime;
mod output;
mod pack_update_hint;
mod package;
mod package_cmd;
mod package_status;
mod platform;
mod policy;
mod profile;
mod profile_cmd;
mod profile_runtime;
mod profile_save_runtime;
mod protected_paths;
mod proxy_runtime;
mod pty_proxy;
mod pull_ui;
mod query_ext;
mod registry_client;
mod rollback_commands;
mod rollback_preflight;
mod rollback_runtime;
mod rollback_session;
mod rollback_ui;
mod sandbox_log;
mod sandbox_prepare;
mod sandbox_state;
mod session;
mod session_commands;
mod setup;
mod startup_prompt;
mod startup_runtime;
mod supervised_runtime;
mod terminal_approval;
mod theme;
mod timeouts;
mod trust_cmd;
mod trust_intercept;
mod trust_keystore;
mod trust_scan;
mod update_check;
mod why_runtime;
mod wiring;

#[cfg(test)]
mod test_env;

use app_runtime::run as run_cli;
use clap::Parser;
use cli::Cli;
use cli_bootstrap::{
    collect_legacy_network_warnings, init_theme, init_tracing, normalize_legacy_flag_env_vars,
    print_legacy_network_warnings,
};
use command_blocking_deprecation::{
    collect_cli_warnings, print_warnings as print_deprecation_warnings,
};
use nono::Result;

const DETACHED_LAUNCH_ENV: &str = "NONO_DETACHED_LAUNCH";
const DETACHED_CWD_PROMPT_RESPONSE_ENV: &str = "NONO_DETACHED_CWD_PROMPT_RESPONSE";
const DETACHED_SESSION_ID_ENV: &str = "NONO_DETACHED_SESSION_ID";

pub(crate) use launch_runtime::rollback_base_exclusions;
pub(crate) use proxy_runtime::merge_dedup_ports;

fn main() {
    let legacy_network_warnings = collect_legacy_network_warnings();
    normalize_legacy_flag_env_vars();
    // Emit one deprecation warning per distinct legacy long flag before clap
    // parses. clap's `alias` rebinds `--override-deny` to `--bypass-protection`
    // silently; without this scan the user would never see a removal notice.
    let os_args: Vec<_> = std::env::args_os().collect();
    deprecated_schema::warn_for_deprecated_flags(&os_args);
    let cli = Cli::parse();
    init_tracing(&cli);
    init_theme(&cli);
    print_legacy_network_warnings(&legacy_network_warnings, cli.silent);
    let command_blocking_warnings = collect_cli_warnings(&cli);
    print_deprecation_warnings(&command_blocking_warnings, cli.silent);

    if let Err(e) = run_cli(cli) {
        if let nono::NonoError::ActionRequired(message) = &e {
            eprintln!("{message}");
            std::process::exit(1);
        }
        // User-initiated stops (declined prompt, non-TTY without
        // NONO_AUTO_MIGRATE) are surfaced as `NonoError::Cancelled`.
        // Their stderr message has already been printed at the call
        // site — exit non-zero but skip the ERROR log and the
        // duplicated `nono:` prefix so the output reads as an
        // intentional stop, not a fault.
        if matches!(e, nono::NonoError::Cancelled(_)) {
            std::process::exit(1);
        }
        eprintln!("nono: {}", e);
        std::process::exit(1);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cli::SandboxArgs;
    use crate::execution_runtime::execution_start_dir;
    use crate::launch_runtime::{
        resolve_requested_workdir, select_exec_strategy, select_threading_context,
        trust_interception_active,
    };
    use crate::proxy_runtime::{EffectiveProxySettings, resolve_effective_proxy_settings};
    use crate::sandbox_prepare::PreparedSandbox;
    #[cfg(target_os = "linux")]
    use crate::sandbox_prepare::maybe_enable_gpu;
    use crate::sandbox_prepare::maybe_enable_macos_gpu;
    #[cfg(target_os = "macos")]
    use crate::sandbox_prepare::maybe_enable_macos_launch_services;
    use crate::startup_runtime::allows_pre_exec_update_check;
    use nono::{AccessMode, CapabilitySet, FsCapability};

    fn sandbox_args() -> SandboxArgs {
        SandboxArgs::default()
    }

    #[test]
    fn test_sensitive_paths_defined() {
        let loaded_policy = policy::load_embedded_policy().expect("policy must load");
        let paths = policy::get_sensitive_paths(&loaded_policy).expect("must resolve");
        assert!(paths.iter().any(|rule| rule.expanded_path.contains("ssh")));
        assert!(paths.iter().any(|rule| rule.expanded_path.contains("aws")));
    }

    #[test]
    fn test_dangerous_commands_defined() {
        let loaded_policy = policy::load_embedded_policy().expect("policy must load");
        let commands = policy::get_dangerous_commands(&loaded_policy);
        assert!(commands.contains("rm"));
        assert!(commands.contains("dd"));
        assert!(commands.contains("chmod"));
    }

    #[test]
    fn test_check_blocked_command_basic() {
        assert!(
            config::check_blocked_command("echo", &[], &[])
                .expect("policy must load")
                .is_none()
        );
        assert!(
            config::check_blocked_command("ls", &[], &[])
                .expect("policy must load")
                .is_none()
        );
        assert!(
            config::check_blocked_command("cat", &[], &[])
                .expect("policy must load")
                .is_none()
        );
    }

    #[test]
    fn test_check_blocked_command_with_path() {
        let blocked = vec!["rm".to_string(), "dd".to_string()];
        assert!(
            config::check_blocked_command("/bin/rm", &[], &blocked)
                .expect("policy must load")
                .is_some()
        );
        assert!(
            config::check_blocked_command("/usr/bin/dd", &[], &blocked)
                .expect("policy must load")
                .is_some()
        );
        assert!(
            config::check_blocked_command("./rm", &[], &blocked)
                .expect("policy must load")
                .is_some()
        );
    }

    #[test]
    fn test_check_blocked_command_allow_override() {
        let allowed = vec!["rm".to_string()];
        let blocked = vec!["rm".to_string(), "dd".to_string()];
        assert!(
            config::check_blocked_command("rm", &allowed, &blocked)
                .expect("policy must load")
                .is_none()
        );
        assert!(
            config::check_blocked_command("dd", &allowed, &blocked)
                .expect("policy must load")
                .is_some()
        );
    }

    #[test]
    fn test_check_blocked_command_extra_blocked() {
        let extra = vec!["custom-dangerous".to_string()];
        assert!(
            config::check_blocked_command("custom-dangerous", &[], &extra)
                .expect("policy must load")
                .is_some()
        );
        assert!(
            config::check_blocked_command("rm", &[], &extra)
                .expect("policy must load")
                .is_none()
        );
    }

    #[test]
    fn test_check_blocked_command_uses_resolved_policy_only() {
        assert!(
            config::check_blocked_command("rm", &[], &[])
                .expect("policy must load")
                .is_none()
        );
    }

    #[test]
    fn test_resolve_effective_proxy_settings_allow_net_clears_profile_proxy_state() {
        let args = SandboxArgs {
            allow_net: true,
            ..sandbox_args()
        };
        let prepared = PreparedSandbox {
            caps: CapabilitySet::new(),
            secrets: Vec::new(),
            session_hooks: crate::profile::SessionHooks::default(),
            rollback_exclude_patterns: Vec::new(),
            rollback_exclude_globs: Vec::new(),
            network_profile: Some("developer".to_string()),
            allow_domain: vec![profile::AllowDomainEntry::Plain(
                "docs.python.org".to_string(),
            )],
            credentials: vec!["github".to_string()],
            custom_credentials: std::collections::HashMap::new(),
            upstream_proxy: None,
            upstream_bypass: Vec::new(),
            listen_ports: Vec::new(),
            capability_elevation: false,
            #[cfg(target_os = "linux")]
            wsl2_proxy_policy: crate::profile::Wsl2ProxyPolicy::Error,
            #[cfg(target_os = "linux")]
            af_unix_mediation: crate::profile::LinuxAfUnixMediation::Off,
            allow_launch_services_active: false,
            allow_gpu_active: false,
            open_url_origins: Vec::new(),
            open_url_allow_localhost: false,
            bypass_protection_paths: Vec::new(),
            ignored_denial_paths: Vec::new(),
            suppressed_system_service_operations: Vec::new(),
            allowed_env_vars: None,
            denied_env_vars: None,
        };

        let effective = resolve_effective_proxy_settings(&args, &prepared);

        assert_eq!(
            effective,
            EffectiveProxySettings {
                network_profile: None,
                allow_domain: Vec::new(),
                credentials: Vec::new(),
            }
        );
    }

    #[test]
    fn test_resolve_effective_proxy_settings_merges_cli_and_profile() {
        let args = SandboxArgs {
            network_profile: Some("minimal".to_string()),
            allow_proxy: vec!["example.com".to_string()],
            proxy_credential: vec!["openai".to_string()],
            ..sandbox_args()
        };
        let prepared = PreparedSandbox {
            caps: CapabilitySet::new(),
            secrets: Vec::new(),
            session_hooks: crate::profile::SessionHooks::default(),
            rollback_exclude_patterns: Vec::new(),
            rollback_exclude_globs: Vec::new(),
            network_profile: Some("developer".to_string()),
            allow_domain: vec![profile::AllowDomainEntry::Plain(
                "docs.python.org".to_string(),
            )],
            credentials: vec!["github".to_string()],
            custom_credentials: std::collections::HashMap::new(),
            upstream_proxy: None,
            upstream_bypass: Vec::new(),
            listen_ports: Vec::new(),
            capability_elevation: false,
            #[cfg(target_os = "linux")]
            wsl2_proxy_policy: crate::profile::Wsl2ProxyPolicy::Error,
            #[cfg(target_os = "linux")]
            af_unix_mediation: crate::profile::LinuxAfUnixMediation::Off,
            allow_launch_services_active: false,
            allow_gpu_active: false,
            open_url_origins: Vec::new(),
            open_url_allow_localhost: false,
            bypass_protection_paths: Vec::new(),
            ignored_denial_paths: Vec::new(),
            suppressed_system_service_operations: Vec::new(),
            allowed_env_vars: None,
            denied_env_vars: None,
        };

        let effective = resolve_effective_proxy_settings(&args, &prepared);

        assert_eq!(
            effective,
            EffectiveProxySettings {
                network_profile: Some("minimal".to_string()),
                allow_domain: vec![
                    profile::AllowDomainEntry::Plain("docs.python.org".to_string()),
                    profile::AllowDomainEntry::Plain("example.com".to_string()),
                ],
                credentials: vec!["github".to_string(), "openai".to_string()],
            }
        );
    }

    #[test]
    fn test_trust_interception_inactive_for_default_policy() {
        let policy = nono::trust::TrustPolicy::default();

        assert!(!trust_interception_active(Some(&policy)));
    }

    #[test]
    fn test_trust_interception_active_when_includes_exist() {
        let policy = nono::trust::TrustPolicy {
            includes: vec!["SKILLS.md".to_string()],
            ..nono::trust::TrustPolicy::default()
        };

        assert!(trust_interception_active(Some(&policy)));
    }

    #[test]
    fn test_select_exec_strategy_uses_supervised_for_plain_run() {
        assert_eq!(
            select_exec_strategy(false, false, false, false, false),
            exec_strategy::ExecStrategy::Supervised
        );
    }

    #[test]
    fn test_select_exec_strategy_uses_supervised_for_rollback() {
        assert_eq!(
            select_exec_strategy(true, false, false, false, false),
            exec_strategy::ExecStrategy::Supervised
        );
    }

    #[test]
    fn test_select_exec_strategy_uses_supervised_for_proxy() {
        assert_eq!(
            select_exec_strategy(false, true, false, false, false),
            exec_strategy::ExecStrategy::Supervised
        );
    }

    #[test]
    fn test_select_exec_strategy_uses_supervised_for_capability_elevation() {
        assert_eq!(
            select_exec_strategy(false, false, true, false, false),
            exec_strategy::ExecStrategy::Supervised
        );
    }

    #[test]
    fn test_select_exec_strategy_uses_supervised_for_trust_interception() {
        assert_eq!(
            select_exec_strategy(false, false, false, true, false),
            exec_strategy::ExecStrategy::Supervised
        );
    }

    #[test]
    fn test_select_exec_strategy_uses_supervised_for_detached_start() {
        assert_eq!(
            select_exec_strategy(false, false, false, false, true),
            exec_strategy::ExecStrategy::Supervised
        );
    }

    #[test]
    fn test_pre_exec_update_check_disabled_for_execution_commands() {
        let run = Cli::parse_from(["nono", "run", "--allow", "/tmp", "--", "/bin/sh"]);
        assert!(!allows_pre_exec_update_check(&run.command));

        let shell = Cli::parse_from(["nono", "shell", "--allow", "/tmp"]);
        assert!(!allows_pre_exec_update_check(&shell.command));

        let wrap = Cli::parse_from(["nono", "wrap", "--allow", "/tmp", "--", "/bin/sh"]);
        assert!(!allows_pre_exec_update_check(&wrap.command));
    }

    #[test]
    fn test_pre_exec_update_check_disabled_for_completions() {
        // `nono completions` is used in shell init scripts such as
        // `eval "$(nono completions zsh)"`.  It never shows an update
        // notification (it is dispatched directly without
        // run_command_with_update), so spawning the background update-check
        // thread would incur network I/O with no benefit.
        let completions = Cli::parse_from(["nono", "completion", "zsh"]);
        assert!(!allows_pre_exec_update_check(&completions.command));
    }

    #[test]
    fn test_pre_exec_update_check_disabled_for_pack_update_hint_helper() {
        let helper = Cli::parse_from([
            "nono",
            "pack-update-hint-helper",
            "always-further/claude",
            "1.0.0",
        ]);
        assert!(!allows_pre_exec_update_check(&helper.command));
    }

    #[test]
    fn test_pre_exec_update_check_enabled_for_non_exec_commands() {
        let why = Cli::parse_from(["nono", "why", "--path", "/tmp", "--op", "read"]);
        assert!(allows_pre_exec_update_check(&why.command));

        let ps = Cli::parse_from(["nono", "ps"]);
        assert!(allows_pre_exec_update_check(&ps.command));
    }

    #[test]
    fn test_select_threading_context_uses_crypto_for_trust_scan() {
        assert_eq!(
            select_threading_context(false, false, true, false),
            exec_strategy::ThreadingContext::CryptoExpected
        );
    }

    #[test]
    fn test_select_threading_context_uses_keyring_for_secrets_only() {
        assert_eq!(
            select_threading_context(true, false, false, false),
            exec_strategy::ThreadingContext::KeyringExpected
        );
    }

    #[test]
    fn test_resolve_requested_workdir_prefers_explicit_path() {
        let explicit = std::path::PathBuf::from("/tmp/nono-workdir");
        assert_eq!(
            resolve_requested_workdir(Some(&explicit)),
            std::path::PathBuf::from("/tmp/nono-workdir")
        );
    }

    #[test]
    fn test_execution_start_dir_keeps_workdir_when_covered() {
        let dir = tempfile::tempdir().expect("tempdir");
        let canonical = dir.path().canonicalize().expect("canonicalize");
        let mut caps = CapabilitySet::new();
        caps.add_fs(FsCapability::new_dir(dir.path(), AccessMode::Read).expect("grant"));

        let start_dir = execution_start_dir(dir.path(), &caps).expect("start dir");

        assert_eq!(start_dir, canonical);
    }

    #[test]
    fn test_execution_start_dir_falls_back_to_root_when_not_covered() {
        let dir = tempfile::tempdir().expect("tempdir");
        let caps = CapabilitySet::new();

        let start_dir = execution_start_dir(dir.path(), &caps).expect("start dir");

        assert_eq!(start_dir, std::path::PathBuf::from("/"));
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn test_maybe_enable_macos_launch_services_adds_rule_when_enabled() {
        let mut caps = CapabilitySet::new();

        let enabled = maybe_enable_macos_launch_services(
            &mut caps,
            true,
            true,
            &["https://claude.ai".to_string()],
            false,
        )
        .expect("launch services gate should apply");

        assert!(enabled, "launch services should be active");
        assert!(
            caps.platform_rules().iter().any(|r| r == "(allow lsopen)"),
            "lsopen platform rule should be present"
        );
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn test_maybe_enable_macos_launch_services_rejects_without_profile_opt_in() {
        let mut caps = CapabilitySet::new();

        let err = maybe_enable_macos_launch_services(
            &mut caps,
            true,
            false,
            &["https://claude.ai".to_string()],
            false,
        )
        .expect_err("missing profile opt-in should fail");

        assert!(
            err.to_string().contains("requires a profile"),
            "error should mention profile opt-in"
        );
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn test_maybe_enable_macos_launch_services_rejects_without_open_urls() {
        let mut caps = CapabilitySet::new();

        let err = maybe_enable_macos_launch_services(&mut caps, true, true, &[], false)
            .expect_err("missing open_urls should fail");

        assert!(
            err.to_string().contains("configure open_urls"),
            "error should mention open_urls"
        );
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn test_maybe_enable_macos_gpu_adds_rules_when_enabled() {
        let mut caps = CapabilitySet::new();

        let enabled = maybe_enable_macos_gpu(&mut caps, true, true).expect("gpu gate should apply");

        assert!(enabled);
        assert!(
            caps.platform_rules()
                .iter()
                .any(|r| r.contains("AGXDeviceUserClient")),
            "AGXDeviceUserClient platform rule should be present"
        );
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn test_maybe_enable_macos_gpu_rejects_without_profile_opt_in() {
        let mut caps = CapabilitySet::new();

        let err = maybe_enable_macos_gpu(&mut caps, true, false)
            .expect_err("missing profile opt-in should fail");

        assert!(
            err.to_string().contains("allow_gpu"),
            "error should mention allow_gpu"
        );
    }

    #[test]
    fn test_maybe_enable_macos_gpu_noop_without_flag() {
        let mut caps = CapabilitySet::new();

        let enabled =
            maybe_enable_macos_gpu(&mut caps, false, true).expect("should succeed without flag");

        assert!(!enabled);
        assert!(caps.platform_rules().is_empty());
    }

    #[cfg(not(target_os = "macos"))]
    #[test]
    fn test_maybe_enable_macos_gpu_rejects_on_non_macos() {
        let mut caps = CapabilitySet::new();

        let err =
            maybe_enable_macos_gpu(&mut caps, true, true).expect_err("should fail on non-macOS");

        assert!(
            err.to_string().contains("only supported on macOS"),
            "error should mention macOS support"
        );
    }

    /// On Linux, maybe_enable_gpu should succeed if GPU devices exist, or return
    /// a clear "no GPU devices found" error if not. It must NOT hard-fail just
    /// because /dev/dri is absent — headless NVIDIA (CUDA-only) and AMD (ROCm-only)
    /// machines may lack DRM render nodes entirely.
    #[cfg(target_os = "linux")]
    #[test]
    fn test_maybe_enable_gpu_linux_does_not_require_dri() {
        let mut caps = CapabilitySet::new();

        let result = maybe_enable_gpu(&mut caps, true, true);

        // On a GPU machine: Ok(true) with fs capabilities added.
        // On a non-GPU CI machine: Err mentioning "no GPU devices found".
        // Either outcome is correct. What must NOT happen is an error about
        // /dev/dri specifically, which would break NVIDIA/ROCm-only setups.
        match result {
            Ok(enabled) => {
                assert!(enabled, "should be active when devices are found");
                assert!(
                    caps.has_fs(),
                    "should have granted fs capabilities for GPU devices"
                );
            }
            Err(e) => {
                let msg = e.to_string();
                assert!(
                    msg.contains("no GPU devices found"),
                    "error on non-GPU machine should be generic, not DRI-specific: {msg}"
                );
                // Verify the error lists all checked paths
                assert!(
                    msg.contains("renderD"),
                    "error should mention renderD: {msg}"
                );
                assert!(msg.contains("nvidia"), "error should mention nvidia: {msg}");
                assert!(msg.contains("kfd"), "error should mention kfd: {msg}");
            }
        }
    }
}