newt-tui 0.8.0

Newt-Agent TUI surfaces (ratatui): code mode + pilot mode
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
use super::{policy_for, SessionCapability};
// The `permits_*` adaptors live on `CaveatsExt` (post-#95).
use newt_core::CaveatsExt;

/// RAII guard neutralizing the ambient `--full-access` / `NEWT_FULL_ACCESS`
/// override for the duration of a test, restoring it on drop. These tests
/// assert the DEFAULT (unconfigured / read-only) policy; if the test binary
/// is launched under `--full-access` (which exports `NEWT_FULL_ACCESS=1`),
/// `policy_for` would otherwise short-circuit to `Caveats::top()` and every
/// read-only assertion here would fail through no fault of the code. This
/// makes the preset assumption explicit and hermetic.
struct ForceDefaultPreset {
    saved: Option<String>,
}

impl ForceDefaultPreset {
    fn new() -> Self {
        let saved = std::env::var("NEWT_FULL_ACCESS").ok();
        std::env::remove_var("NEWT_FULL_ACCESS");
        Self { saved }
    }
}

impl Drop for ForceDefaultPreset {
    fn drop(&mut self) {
        match self.saved.take() {
            Some(v) => std::env::set_var("NEWT_FULL_ACCESS", v),
            None => std::env::remove_var("NEWT_FULL_ACCESS"),
        }
    }
}

fn tui_with(preset: newt_core::PermissionPreset) -> newt_core::TuiConfig {
    newt_core::TuiConfig {
        permissions: newt_core::ToolPermissions {
            preset,
            extra_exec: Vec::new(),
            net: Vec::new(),
            prompt: false,
            ..Default::default()
        },
        ..Default::default()
    }
}

#[test]
fn approved_workspace_policy_stays_frozen_until_a_new_process_session() {
    let _env = crate::test_env_guard::env_write_guard();
    let policy = newt_core::Caveats {
        fs_read: newt_core::Scope::only(["/project".into(), "/reference".into()]),
        fs_write: newt_core::Scope::only(["/project".into()]),
        exec: newt_core::Scope::All,
        net: newt_core::Scope::only(["example.test".into()]),
        ..newt_core::Caveats::top()
    };
    let mut cap = SessionCapability::establish_frozen(policy.clone(), None, None);
    for next in [
        newt_core::PermissionPreset::ReadOnly,
        newt_core::PermissionPreset::FullAccess,
    ] {
        assert!(!cap.reapply(Some(tui_with(next)), "/different-workspace"));
        assert_eq!(
            cap.caveats(),
            &policy,
            "saved edits and ordinary config refresh cannot activate a profile mid-session"
        );
    }
    let next_policy = newt_core::Caveats {
        fs_write: newt_core::Scope::none(),
        exec: newt_core::Scope::none(),
        ..policy
    };
    let next_session = SessionCapability::establish_frozen(next_policy.clone(), None, None);
    assert_eq!(next_session.caveats(), &next_policy);
    assert_ne!(next_session.caveats(), cap.caveats());
}

#[test]
fn workspace_access_launch_keeps_directory_fence_and_configured_network() {
    let _env = crate::test_env_guard::env_write_guard();
    let mut tui = tui_with(newt_core::PermissionPreset::ReadOnly);
    tui.permissions.net = vec!["docs.rs".into()];
    let policy = super::policy_for_launch(
        Some(tui),
        "/workspace",
        newt_core::launch_authority::LaunchAuthority::WORKSPACE_ACCESS,
    );
    assert!(policy.permits_exec("rm"));
    assert!(policy.permits_exec("arbitrary-workspace-program"));
    assert!(newt_core::caveats::permits_path(
        &policy.fs_write,
        "/workspace/dir/file"
    ));
    assert!(!newt_core::caveats::permits_path(
        &policy.fs_write,
        "/workspace/../sibling/file"
    ));
    assert!(!newt_core::caveats::permits_path(
        &policy.fs_read,
        "/outside/file"
    ));
    assert_eq!(policy.net, newt_core::Scope::only(["docs.rs".into()]));
    let no_config = super::policy_for_launch(
        None,
        "/workspace",
        newt_core::launch_authority::LaunchAuthority::WORKSPACE_ACCESS,
    );
    assert_eq!(no_config.net, newt_core::Scope::none());
    assert!(no_config.permits_exec("rm"));
}

#[test]
fn absent_config_is_read_only() {
    // Serialize against env-mutating tests: policy_for reads NEWT_EXEC_PATHS
    // / NEWT_VENV via scan_cli_exec_grants. We also neutralize an ambient
    // NEWT_FULL_ACCESS, which needs the exclusive (write) guard.
    let _env = crate::test_env_guard::env_write_guard();
    let _preset = ForceDefaultPreset::new();
    // #86 regression: with no [tui] config the policy must be READ-ONLY,
    // never `Caveats::top()` (the old fallback granted full access).
    let policy = policy_for(None, "/ws");
    assert_ne!(policy, newt_core::caveats::Caveats::top());
    assert!(!policy.permits_exec("cargo"), "no exec when unconfigured");
    assert!(
        !policy.permits_fs_write("/ws/x"),
        "no write when unconfigured"
    );
    // Reads are now LOCKED to the workspace (the operator wants the agent
    // confined to the CWD). The workspace root is readable; paths outside it
    // are not. (Files *under* the root, e.g. /ws/x, are reached at runtime
    // via the TUI's prefix match in `tui_permits_path`; the core method here
    // is exact-set, matching how fs_write has always stored the root.)
    assert!(policy.permits_fs_read("/ws"), "the workspace is readable");
    assert!(
        !policy.permits_fs_read("/etc/passwd"),
        "reads are locked to the workspace by default"
    );
}

#[serial_test::serial(real_fs)]
#[test]
fn establish_unconfigured_is_signed_read_only() {
    // Serialize against env-mutating tests: policy_for reads NEWT_EXEC_PATHS
    // / NEWT_VENV via scan_cli_exec_grants.
    let _env = crate::test_env_guard::env_write_guard();
    let _preset = ForceDefaultPreset::new();
    // #86 end-to-end: no config + a real (temp) key → read-only caveats via
    // the signed-capability path; the per-user key was generated.
    let dir = tempfile::TempDir::new().unwrap();
    let key = dir.path().join("identity.pem");
    let cap = SessionCapability::establish(None, Some(&key), "/ws", None);
    assert_ne!(*cap.caveats(), newt_core::caveats::Caveats::top());
    assert!(!cap.caveats().permits_exec("cargo"));
    // Reads locked to the workspace (see absent_config_is_read_only).
    assert!(cap.caveats().permits_fs_read("/ws"));
    assert!(!cap.caveats().permits_fs_read("/etc/passwd"));
    assert!(key.exists(), "the per-user identity key was generated");
}

#[test]
fn establish_without_key_is_read_only_policy() {
    // Serialize against env-mutating tests: policy_for reads NEWT_EXEC_PATHS
    // / NEWT_VENV via scan_cli_exec_grants.
    let _env = crate::test_env_guard::env_write_guard();
    let _preset = ForceDefaultPreset::new();
    let cap = SessionCapability::establish(None, None, "/ws", None);
    assert_ne!(*cap.caveats(), newt_core::caveats::Caveats::top());
    assert!(!cap.caveats().permits_exec("cargo"));
}

/// Issue #93: a subprocess plugin spawned from the TUI must inherit
/// an `AgentKey` whose cert chain walks back to the operator's
/// `UserKey` from `~/.newt/identity.pem`. This pins the chain-
/// rooting property end to end through `SessionCapability`'s
/// envelope-mint chokepoint.
#[serial_test::serial(real_fs)]
#[test]
fn plugin_envelope_chain_roots_at_operator_userkey() {
    // Serialize against env-mutating tests: policy_for reads NEWT_EXEC_PATHS
    // / NEWT_VENV via scan_cli_exec_grants.
    let _env = crate::test_env_guard::env_read_guard();
    use base64::Engine;
    let dir = tempfile::TempDir::new().unwrap();
    let key_path = dir.path().join("identity.pem");
    let cap = SessionCapability::establish(
        Some(tui_with(newt_core::PermissionPreset::WorkspaceDev)),
        Some(&key_path),
        "/ws",
        None,
    );

    // Re-load the user key to get its fingerprint for the chain walk.
    let user = newt_identity::load_or_generate(&key_path).unwrap();
    let user_fp = user.fingerprint();

    // Plugin runs read-only — strictly narrower than WorkspaceDev.
    let plugin_caveats = newt_core::Caveats {
        fs_write: newt_core::Scope::none(),
        exec: newt_core::Scope::none(),
        ..cap.caveats().clone()
    };
    let envelope = cap
        .plugin_envelope_for("tui-spawned-plugin", plugin_caveats)
        .expect("operating key present → envelope path is available")
        .expect("attenuating delegation must succeed");

    let bytes = base64::engine::general_purpose::STANDARD
        .decode(&envelope)
        .unwrap();
    let leaf: agent_mesh_protocol::CertChain = serde_json::from_slice(&bytes).unwrap();
    leaf.verify().expect("plugin cert chain must verify");
    assert_eq!(
        leaf.user_fingerprint(),
        user_fp,
        "TUI-side plugin envelope must root at the operator's UserKey, \
             not a synthetic key"
    );
}

#[test]
fn plugin_envelope_unavailable_without_operating_key() {
    // Serialize against env-mutating tests: policy_for reads NEWT_EXEC_PATHS
    // / NEWT_VENV via scan_cli_exec_grants.
    let _env = crate::test_env_guard::env_read_guard();
    // When the per-user key isn't on disk (None path), the TUI
    // degrades to a caveats-only floor. The plugin-spawn chokepoint
    // returns None — the caller must NOT manufacture an AgentKey
    // (issue #93). No synthetic-key fallback exists.
    let cap = SessionCapability::establish(None, None, "/ws", None);
    assert!(
        cap.plugin_envelope_for("tui-plugin", newt_core::Caveats::top())
            .is_none(),
        "no operating key → no envelope minted (issue #93: no synthetic fallback)"
    );
}

/// A bare TUI config must admit stdin filters without setup or saved grants.
/// Regression: `tr -cd '{'` prompted repeatedly in the default session.
#[test]
fn fresh_default_session_admits_standard_text_filters() {
    let _env = crate::test_env_guard::env_read_guard();
    let tui: newt_core::TuiConfig = toml::from_str("").unwrap();
    assert!(tui.permissions.extra_exec.is_empty());
    let policy = super::policy_for_launch(
        Some(tui),
        "/workspace",
        newt_core::launch_authority::LaunchAuthority::CONFINED,
    );
    assert_ne!(policy.exec, newt_core::Scope::All);
    for tool in ["tr", "cut", "uniq"] {
        assert!(policy.permits_exec(tool), "fresh session must admit {tool}");
    }
    assert!(!policy.permits_exec("arbitrary-ungranted-program"));
}

#[serial_test::serial(real_fs)]
#[test]
fn establish_configured_is_workspace_dev() {
    // Serialize against env-mutating tests: policy_for reads NEWT_EXEC_PATHS
    // / NEWT_VENV via scan_cli_exec_grants.
    let _env = crate::test_env_guard::env_write_guard();
    let _preset = ForceDefaultPreset::new();
    let dir = tempfile::TempDir::new().unwrap();
    let cap = SessionCapability::establish(
        Some(newt_core::TuiConfig::default()),
        Some(&dir.path().join("identity.pem")),
        "/ws",
        None,
    );
    assert!(cap.caveats().permits_exec("cargo"), "workspace-dev tools");
    assert!(!cap.caveats().permits_exec("rm"), "dangerous cmds denied");
}

#[serial_test::serial(real_fs)]
#[test]
fn reapply_narrows_but_cannot_widen() {
    // Serialize against env-mutating tests: policy_for reads NEWT_EXEC_PATHS
    // / NEWT_VENV via scan_cli_exec_grants.
    let _env = crate::test_env_guard::env_write_guard();
    let _preset = ForceDefaultPreset::new();
    // The headline runtime property: within a session, a config reload can tighten
    // authority but never loosen it (keyed off a temp identity).
    let dir = tempfile::TempDir::new().unwrap();
    let mut cap = SessionCapability::establish(
        Some(tui_with(newt_core::PermissionPreset::WorkspaceDev)),
        Some(&dir.path().join("identity.pem")),
        "/ws",
        None,
    );
    assert!(
        cap.caveats().permits_exec("cargo"),
        "starts at workspace-dev"
    );

    // Narrow to read-only: accepted, not clamped.
    let clamped = cap.reapply(Some(tui_with(newt_core::PermissionPreset::ReadOnly)), "/ws");
    assert!(!clamped, "narrowing is not a clamp");
    assert!(!cap.caveats().permits_exec("cargo"), "now read-only");

    // Try to widen back to workspace-dev: clamped, stays read-only.
    let clamped = cap.reapply(
        Some(tui_with(newt_core::PermissionPreset::WorkspaceDev)),
        "/ws",
    );
    assert!(clamped, "a widening request must be reported as clamped");
    assert!(
        !cap.caveats().permits_exec("cargo"),
        "authority must not widen within a session"
    );
}

#[serial_test::serial(real_fs)]
#[test]
fn reapply_without_key_still_narrows() {
    // Serialize against env-mutating tests: policy_for reads NEWT_EXEC_PATHS
    // / NEWT_VENV via scan_cli_exec_grants.
    let _env = crate::test_env_guard::env_write_guard();
    let _preset = ForceDefaultPreset::new();
    let mut cap = SessionCapability::establish(
        Some(tui_with(newt_core::PermissionPreset::WorkspaceDev)),
        None,
        "/ws",
        None,
    );
    assert!(cap.caveats().permits_exec("cargo"));
    let clamped = cap.reapply(Some(tui_with(newt_core::PermissionPreset::ReadOnly)), "/ws");
    assert!(!clamped);
    assert!(!cap.caveats().permits_exec("cargo"));
}

pub(crate) fn verified_delegation(
    ceiling: newt_core::Caveats,
) -> newt_identity::VerifiedDelegation {
    let parent = newt_identity::session_root(&newt_identity::UserKey::generate());
    let envelope = newt_identity::delegate_for_plugin(&parent, "newt-helper", ceiling).unwrap();
    newt_identity::verify_delegation(
        envelope.as_bytes(),
        &newt_identity::RawContentId::from_content(envelope.as_bytes()),
    )
    .unwrap()
}

fn delegated_ceiling() -> newt_core::Caveats {
    newt_core::Caveats {
        fs_read: newt_core::Scope::only(["/ws".to_string()]),
        fs_write: newt_core::Scope::none(),
        exec: newt_core::Scope::none(),
        net: newt_core::Scope::none(),
        max_calls: newt_core::CountBound::AtMost(7),
        valid_for_generation: newt_core::Scope::All,
    }
}

/// Grounds the delegated constructor's no-root-mint contract against a real
/// missing identity path; the ordinary-session control must create its key.
#[test]
fn delegated_session_does_not_create_an_operator_root_key() {
    let _env = crate::test_env_guard::env_read_guard();
    let dir = tempfile::tempdir().unwrap();
    let child_key = dir.path().join("child-root.pem");
    let ceiling = delegated_ceiling();
    let cap = SessionCapability::establish(
        Some(tui_with(newt_core::PermissionPreset::FullAccess)),
        Some(&child_key),
        "/ws",
        Some(verified_delegation(ceiling.clone())),
    );
    assert!(
        !child_key.exists(),
        "a delegated session must not mint a root"
    );
    assert_eq!(cap.caveats(), &ceiling);
    assert!(cap.plugin_envelope_for("nested-helper", ceiling).is_none());

    let operator_key = dir.path().join("operator-root.pem");
    let ordinary = SessionCapability::establish(None, Some(&operator_key), "/ws", None);
    assert!(
        operator_key.exists(),
        "ordinary startup still establishes its identity"
    );
    assert!(ordinary.delegation().is_none());
}

#[test]
fn delegated_session_without_a_key_path_still_enforces_its_signed_ceiling() {
    let _env = crate::test_env_guard::env_read_guard();
    let ceiling = delegated_ceiling();
    let cap = SessionCapability::establish(
        Some(tui_with(newt_core::PermissionPreset::FullAccess)),
        None,
        "/ws",
        Some(verified_delegation(ceiling.clone())),
    );
    assert_eq!(cap.caveats(), &ceiling);
    assert_eq!(cap.delegation().unwrap().caveats(), &ceiling);
    assert!(cap.plugin_envelope_for("nested-helper", ceiling).is_none());
}

#[test]
fn delegated_session_reapply_and_posture_off_cannot_remove_the_parent_ceiling() {
    let _env = crate::test_env_guard::env_read_guard();
    let ceiling = delegated_ceiling();
    let mut cap = SessionCapability::establish(
        Some(tui_with(newt_core::PermissionPreset::FullAccess)),
        None,
        "/ws",
        Some(verified_delegation(ceiling.clone())),
    );
    assert!(cap.reapply(
        Some(tui_with(newt_core::PermissionPreset::FullAccess)),
        "/elsewhere"
    ));
    // No named posture is the same authority path used by `/posture off`.
    let turn = crate::effective_caveats(cap.caveats(), None);
    assert_eq!(turn, ceiling);
    assert_eq!(cap.delegation().unwrap().caveats(), &ceiling);
}

#[test]
fn delegated_session_meets_a_stricter_local_policy_with_the_parent_ceiling() {
    let _env = crate::test_env_guard::env_write_guard();
    let _preset = ForceDefaultPreset::new();
    let tui = tui_with(newt_core::PermissionPreset::ReadOnly);
    let local = policy_for(Some(tui.clone()), "/ws");
    let ceiling = newt_core::Caveats {
        max_calls: newt_core::CountBound::AtMost(7),
        ..newt_core::Caveats::top()
    };
    // Keep explicit CLI grants in the local policy. Neither their absence nor
    // an ambient full-access override should decide this meet regression.
    let expected = local.meet(&ceiling);
    assert_ne!(expected, ceiling, "the local policy is strictly narrower");
    assert_ne!(expected, local, "the signed call bound also narrows policy");

    let cap = SessionCapability::establish(
        Some(tui),
        None,
        "/ws",
        Some(verified_delegation(ceiling.clone())),
    );
    assert_eq!(cap.caveats(), &expected);
    assert_eq!(cap.delegation().unwrap().caveats(), &ceiling);
}

#[test]
fn delegated_session_reapply_preserves_local_narrowing_below_the_parent_ceiling() {
    let _env = crate::test_env_guard::env_write_guard();
    let _preset = ForceDefaultPreset::new();
    let ceiling = newt_core::Caveats {
        max_calls: newt_core::CountBound::AtMost(7),
        ..newt_core::Caveats::top()
    };
    let mut cap = SessionCapability::establish(
        Some(tui_with(newt_core::PermissionPreset::FullAccess)),
        None,
        "/ws",
        Some(verified_delegation(ceiling.clone())),
    );
    let read_only = tui_with(newt_core::PermissionPreset::ReadOnly);
    let narrowed = policy_for(Some(read_only.clone()), "/ws").meet(&ceiling);
    assert_ne!(narrowed, ceiling, "reload must remove some authority");
    cap.reapply(Some(read_only), "/ws");
    assert_eq!(cap.caveats(), &narrowed);

    assert!(cap.reapply(
        Some(tui_with(newt_core::PermissionPreset::FullAccess)),
        "/ws"
    ));
    assert_eq!(
        cap.caveats(),
        &narrowed,
        "reload cannot restore removed axes"
    );
    assert_eq!(cap.delegation().unwrap().caveats(), &ceiling);
}

/// Grounds the no-operating-key boundary against a real, already-valid key.
/// This proves no authority is acquired and no bytes change, not absence of a
/// filesystem read; the ordinary-session control proves the key is usable.
#[test]
fn delegated_session_does_not_acquire_operating_authority_from_an_existing_key() {
    let _env = crate::test_env_guard::env_read_guard();
    let dir = tempfile::tempdir().unwrap();
    let key_path = dir.path().join("operator-root.pem");
    newt_identity::UserKey::generate().save(&key_path).unwrap();
    let before = std::fs::read(&key_path).unwrap();
    let ceiling = delegated_ceiling();
    let cap = SessionCapability::establish(
        Some(tui_with(newt_core::PermissionPreset::FullAccess)),
        Some(&key_path),
        "/ws",
        Some(verified_delegation(ceiling.clone())),
    );
    assert!(cap
        .plugin_envelope_for("nested-helper", ceiling.clone())
        .is_none());
    assert_eq!(cap.caveats(), &ceiling);
    assert_eq!(std::fs::read(&key_path).unwrap(), before);

    let ordinary = SessionCapability::establish(
        Some(tui_with(newt_core::PermissionPreset::FullAccess)),
        Some(&key_path),
        "/ws",
        None,
    );
    ordinary
        .plugin_envelope_for("ordinary-plugin", ceiling)
        .expect("an ordinary session can use the existing operator key")
        .expect("the control delegation stays inside ordinary authority");
    assert_eq!(std::fs::read(&key_path).unwrap(), before);
}