vce 0.1.1

A stateful virtual OS engine with an embeddable machine and shell 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
//! The VCE application as a library.
//!
//! The playable virtual machine: boot an OS, authenticate, and run an
//! interactive (or line-mode) session against it. Exposing the session
//! machinery as a library lets separate applications built on VCE boot and
//! run the same machine the `vce` binary runs, with their own seeding and
//! observation around it.
//!
//! [`Machine`] is the supported embedding boundary. It boots and retains an
//! OS, exposes privileged [`Configuration`], generic Engine observation and
//! events, and creates authenticated [`Session`] values. A session can be
//! driven interactively, from a script, or one captured command at a time.
//! The `vce` binary and external applications therefore use the same OS and
//! shell behavior without depending on the workspace's internal layer crates.
//!
//! # Example
//!
//! ```
//! use vce::{FileMode, Machine, OsKind};
//!
//! let machine = Machine::builder(OsKind::Linux)
//!     .username("apiuser")
//!     .hostname("example-host")
//!     .build()?;
//! machine.configuration().write_file(
//!     "/etc/example.conf",
//!     b"enabled=yes\n",
//!     FileMode::FILE_644,
//! )?;
//!
//! let mut session = machine.session(None)?;
//! let output = session.execute("cat /etc/example.conf")?;
//! assert!(output.success());
//! assert_eq!(output.stdout_text(), "enabled=yes\n");
//! # Ok::<(), vce::MachineError>(())
//! ```

mod host;
mod login_screen;
mod machine;
mod repl;

pub use crate::machine::{
    Account, AuditCategory, Capability, Configuration, FileMetadata, FirewallRule, Group, Machine,
    MachineBuilder, MachineError, OsKind, PasswordPolicy, PreferenceValue, Process, RegistryValue,
    Service,
};
pub use engine::{
    ActorId, AuthorizationData, CreateOptions, DetachedNamespace, Engine, Error as EngineError,
    EventData, EventType, Id, Metadata, MetadataPatch, MetadataValue, Name, ObjectEvent, ObjectId,
    ObjectKind, Operation, SubscriptionId, Timestamp, VirtualPath,
};
pub use os::{AccessClass, FileMode, OsError, Permission};

use os::Credentials;
use os::unix::unix_os::UnixOs;
use os::windows::Windows;
use shell::Shell;
use shell::bash::Bash;
use shell::cmd::Cmd;
use shell::powershell::PowerShell;
use shell::zsh::Zsh;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

/// The distinct reason cooperative session execution stopped.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SessionInterruption {
    /// Another owner requested cancellation.
    Cancelled,
    /// The configured wall-clock deadline elapsed.
    DeadlineExceeded,
}

#[derive(Debug, Default)]
struct SessionControlState {
    cancelled: AtomicBool,
    deadline: Mutex<Option<Instant>>,
}

/// A thread-safe cooperative control handle for a running session.
#[derive(Clone, Debug, Default)]
pub struct SessionControl {
    state: Arc<SessionControlState>,
}

impl SessionControl {
    /// Requests cancellation. The request is idempotent.
    pub fn cancel(&self) {
        self.state.cancelled.store(true, Ordering::Release);
    }

    /// Clears a prior cancellation request.
    pub fn reset_cancellation(&self) {
        self.state.cancelled.store(false, Ordering::Release);
    }

    /// Sets a deadline relative to the host monotonic clock.
    pub fn set_timeout(&self, timeout: Duration) {
        *self.state.deadline.lock().expect("deadline lock poisoned") =
            Instant::now().checked_add(timeout);
    }

    /// Removes the current deadline.
    pub fn clear_deadline(&self) {
        *self.state.deadline.lock().expect("deadline lock poisoned") = None;
    }

    /// Returns the current interruption, if any.
    pub fn interruption(&self) -> Option<SessionInterruption> {
        if self.state.cancelled.load(Ordering::Acquire) {
            return Some(SessionInterruption::Cancelled);
        }
        self.state
            .deadline
            .lock()
            .expect("deadline lock poisoned")
            .is_some_and(|deadline| Instant::now() >= deadline)
            .then_some(SessionInterruption::DeadlineExceeded)
    }
}

/// The outcome of a cooperatively controlled interactive or line session.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SessionOutcome {
    /// The shell ended normally with this status.
    Exited(i32),
    /// The session was cancelled through its control handle.
    Cancelled,
    /// The session deadline elapsed.
    DeadlineExceeded,
}

impl From<SessionInterruption> for SessionOutcome {
    fn from(value: SessionInterruption) -> Self {
        match value {
            SessionInterruption::Cancelled => Self::Cancelled,
            SessionInterruption::DeadlineExceeded => Self::DeadlineExceeded,
        }
    }
}

/// Which shell a session runs.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ShellChoice {
    /// The Bash-flavored shell.
    Bash,
    /// The Zsh-flavored shell.
    Zsh,
    /// The PowerShell shell (Windows).
    PowerShell,
    /// The cmd shell (Windows Command Prompt).
    Cmd,
}

/// A running shell session against a booted OS.
///
/// Construct one with [`Session::unix`] or [`Session::windows`], then run
/// it with [`Session::run_interactive`] (the virtual terminal) or
/// [`Session::run_line`] (scripted standard input).
pub struct Session<'os> {
    shell: Box<dyn Shell + 'os>,
    exited: bool,
    control: SessionControl,
}

/// The captured result of one command submitted to a [`Session`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CommandOutput {
    status: u8,
    stdout: Vec<u8>,
    stderr: Vec<u8>,
    session_exited: bool,
}

impl CommandOutput {
    /// The command's shell exit status.
    pub const fn status(&self) -> u8 {
        self.status
    }

    /// Whether the command succeeded (status zero).
    pub const fn success(&self) -> bool {
        self.status == 0
    }

    /// The bytes written to standard output.
    pub fn stdout(&self) -> &[u8] {
        &self.stdout
    }

    /// Standard output decoded lossily as UTF-8.
    pub fn stdout_text(&self) -> String {
        String::from_utf8_lossy(&self.stdout).into_owned()
    }

    /// The bytes written to standard error.
    pub fn stderr(&self) -> &[u8] {
        &self.stderr
    }

    /// Standard error decoded lossily as UTF-8.
    pub fn stderr_text(&self) -> String {
        String::from_utf8_lossy(&self.stderr).into_owned()
    }

    /// Whether this command asked the shell session to exit.
    pub const fn session_exited(&self) -> bool {
        self.session_exited
    }
}

/// Why a session could not be built.
#[derive(Debug)]
pub enum SessionError {
    /// The shell implementation failed to start (the OS reported an error).
    Shell(String),
    /// The requested shell does not exist on the booted OS.
    ShellNotAvailable {
        /// The requested shell.
        shell: ShellChoice,
        /// The OS it was requested on.
        os: &'static str,
    },
    /// A command was submitted after the shell session had exited.
    Exited,
    /// Cooperative cancellation was requested.
    Cancelled,
    /// The configured session deadline elapsed.
    DeadlineExceeded,
}

impl std::fmt::Display for SessionError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            SessionError::Shell(message) => write!(f, "shell failed: {message}"),
            SessionError::ShellNotAvailable { shell, os } => {
                write!(f, "the {shell:?} shell is not available on {os}")
            }
            SessionError::Exited => f.write_str("the shell session has exited"),
            SessionError::Cancelled => f.write_str("the shell session was cancelled"),
            SessionError::DeadlineExceeded => f.write_str("the shell session deadline elapsed"),
        }
    }
}

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

impl<'os> Session<'os> {
    /// Builds a Unix session: a shell over the given credentials.
    ///
    /// The shell choice is the caller's (typically
    /// [`Session::default_choice`], the account's login shell).
    #[doc(hidden)]
    pub fn unix(
        unix: &'os UnixOs,
        credentials: Credentials,
        choice: ShellChoice,
    ) -> Result<Self, SessionError> {
        let shell: Box<dyn Shell + 'os> = match choice {
            ShellChoice::Bash => Box::new(
                Bash::new(unix, credentials)
                    .map_err(|error| SessionError::Shell(error.to_string()))?,
            ),
            ShellChoice::Zsh => Box::new(
                Zsh::new(unix, credentials)
                    .map_err(|error| SessionError::Shell(error.to_string()))?,
            ),
            other => {
                return Err(SessionError::ShellNotAvailable {
                    shell: other,
                    os: "Unix",
                });
            }
        };
        Ok(Self {
            shell,
            exited: false,
            control: SessionControl::default(),
        })
    }

    /// Builds a Windows session: a PowerShell or cmd over the authenticated
    /// account.
    #[doc(hidden)]
    pub fn windows(
        windows: &'os Windows,
        actor: engine::ActorId,
        choice: ShellChoice,
    ) -> Result<Self, SessionError> {
        let shell: Box<dyn Shell + 'os> = match choice {
            ShellChoice::PowerShell => Box::new(
                PowerShell::new(windows, actor, windows.environment().clone())
                    .map_err(|error| SessionError::Shell(error.to_string()))?,
            ),
            ShellChoice::Cmd => Box::new(
                Cmd::new(windows, actor, windows.environment().clone())
                    .map_err(|error| SessionError::Shell(error.to_string()))?,
            ),
            other => {
                return Err(SessionError::ShellNotAvailable {
                    shell: other,
                    os: "Windows",
                });
            }
        };
        Ok(Self {
            shell,
            exited: false,
            control: SessionControl::default(),
        })
    }

    /// The shell a Unix account's login shell declares (`/bin/zsh` on
    /// macOS, `/bin/bash` on Linux by default).
    #[doc(hidden)]
    pub fn default_choice(credentials: &Credentials) -> ShellChoice {
        if credentials.user().shell().ends_with("/zsh") {
            ShellChoice::Zsh
        } else {
            ShellChoice::Bash
        }
    }

    /// The default shell of a Windows session: PowerShell, as on a real
    /// modern system (cmd remains launchable with `--shell cmd`).
    #[doc(hidden)]
    pub const fn default_windows_choice() -> ShellChoice {
        ShellChoice::PowerShell
    }

    /// The concrete shell running this session.
    pub fn shell_name(&self) -> &'static str {
        self.shell.name()
    }

    /// Returns a cloneable handle that can cancel this session or set its deadline.
    pub fn control(&self) -> SessionControl {
        self.control.clone()
    }

    fn check_control(&self) -> Result<(), SessionError> {
        match self.control.interruption() {
            Some(SessionInterruption::Cancelled) => Err(SessionError::Cancelled),
            Some(SessionInterruption::DeadlineExceeded) => Err(SessionError::DeadlineExceeded),
            None => Ok(()),
        }
    }

    /// Executes one complete command and captures its output.
    ///
    /// The shell object is retained, so working directory, variables,
    /// aliases, history-independent shell state, background jobs, and every
    /// machine mutation remain visible to later calls. Use
    /// [`Session::execute_with_input`] when the command reads standard input.
    pub fn execute(&mut self, command: &str) -> Result<CommandOutput, SessionError> {
        self.execute_with_input(command, [])
    }

    /// Executes one complete command with the supplied standard-input bytes.
    pub fn execute_with_input(
        &mut self,
        command: &str,
        input: impl AsRef<[u8]>,
    ) -> Result<CommandOutput, SessionError> {
        if self.exited {
            return Err(SessionError::Exited);
        }
        self.check_control()?;
        let mut stdin = engine::BytesInput::new(input.as_ref().to_vec());
        let mut stdout = engine::BytesOutput::new();
        let mut stderr = engine::BytesOutput::new();
        let mut status = self
            .shell
            .execute(command, &mut stdin, &mut stdout, &mut stderr)
            .code();
        if let Some(exit_status) = self.shell.take_exit_status() {
            status = exit_status.code();
            self.exited = true;
        }
        self.check_control()?;
        Ok(CommandOutput {
            status,
            stdout: stdout.into_bytes(),
            stderr: stderr.into_bytes(),
            session_exited: self.exited,
        })
    }

    /// Runs the session interactively: the virtual terminal rendered onto
    /// the host console. Returns the session exit status.
    pub fn run_interactive(self) -> i32 {
        match self.run_interactive_controlled() {
            SessionOutcome::Exited(status) => status,
            SessionOutcome::Cancelled => 130,
            SessionOutcome::DeadlineExceeded => 124,
        }
    }

    /// Runs interactively and preserves cancellation/deadline as distinct outcomes.
    pub fn run_interactive_controlled(self) -> SessionOutcome {
        let mut session = repl::InteractiveSession::new(self.shell, self.control);
        session.run()
    }

    /// Runs the session in line mode: commands read from `input`, output
    /// to the host's stdout/stderr. Returns the session exit status.
    pub fn run_line<R: std::io::Read + Send + Sync>(mut self, input: &mut R) -> i32 {
        match repl::run_line_mode_controlled(&mut *self.shell, input, &self.control) {
            SessionOutcome::Exited(status) => status,
            SessionOutcome::Cancelled => 130,
            SessionOutcome::DeadlineExceeded => 124,
        }
    }

    /// Runs line mode and preserves cancellation/deadline as distinct outcomes.
    pub fn run_line_controlled<R: std::io::Read + Send + Sync>(
        mut self,
        input: &mut R,
    ) -> SessionOutcome {
        repl::run_line_mode_controlled(&mut *self.shell, input, &self.control)
    }
}

/// Authenticates the standard user on a Unix OS (password equals the user
/// name, the default account convention). The attempt lands in the login
/// records either way, like every other path into the machine.
#[doc(hidden)]
pub fn login(unix: &UnixOs, user_name: &str) -> Result<Credentials, os::OsError> {
    login_with_password(unix, user_name, user_name)
}

/// Authenticates a Unix account with an explicit password.
///
/// The attempt lands in the login records whether it succeeds or fails.
#[doc(hidden)]
pub fn login_with_password(
    unix: &UnixOs,
    user_name: &str,
    password: &str,
) -> Result<Credentials, os::OsError> {
    let result = unix
        .users()
        .authenticate(user_name, password, unix.groups());
    unix.record_login_attempt(user_name, result.is_ok());
    result
}

/// Authenticates a Windows logon.
///
/// An account without a password (a fresh install) opens without prompting;
/// an account with one takes `password`, an interactive no-echo prompt, or —
/// when stdin is not a terminal — the first line of standard input.
#[doc(hidden)]
pub fn login_windows(
    windows: &Windows,
    user_name: &str,
    password: Option<&str>,
    interactive: bool,
) -> Result<engine::ActorId, String> {
    let user = windows
        .users()
        .by_name(user_name)
        .ok_or_else(|| format!("login failed: no account named '{user_name}'"))?;
    if !user.enabled() {
        return Err(format!(
            "login failed: the account '{user_name}' is disabled"
        ));
    }
    let password = match password {
        Some(password) => password.to_owned(),
        None if !user.has_password() => String::new(),
        None if interactive => prompt_password(&format!("Password for {user_name}: ")),
        None => {
            let mut password = String::new();
            let _ = std::io::stdin().read_line(&mut password);
            password.trim_end().to_owned()
        }
    };
    windows
        .authenticate(user_name, &password)
        .map_err(|_| format!("login failed: incorrect password for '{user_name}'"))
}

/// Prompts for a password with echo disabled, reading keys directly.
#[doc(hidden)]
pub fn prompt_password(prompt: &str) -> String {
    use crossterm::event::{self, Event};
    use crossterm::terminal::{disable_raw_mode, enable_raw_mode};
    use std::io::Write as _;
    let _ = enable_raw_mode();
    print!("{prompt}");
    let _ = std::io::stdout().flush();
    let mut password = String::new();
    // Only keys reach the buffer; resizes and focus events are ignored
    // (ending the loop here would end the whole logon).
    loop {
        let key = match event::read() {
            Ok(Event::Key(key)) => key,
            Ok(_) => continue,
            Err(_) => break,
        };
        let Some(key) = crate::host::translate_key(&key) else {
            continue;
        };
        match key.key {
            engine::Key::Enter => break,
            engine::Key::Backspace => {
                password.pop();
            }
            engine::Key::Character => {
                if key.ctrl && key.character == Some('c') {
                    password.clear();
                    break;
                }
                if !key.ctrl
                    && let Some(character) = key.character
                {
                    password.push(character);
                }
            }
            _ => {}
        }
    }
    let _ = disable_raw_mode();
    println!();
    password
}