From 6a4f003b3e77d3d989ffd5e1d5ee0697d71df3fb Mon Sep 17 00:00:00 2001 From: James Chapman Date: Fri, 27 Nov 2026 00:54:42 +0000 Subject: [PATCH 1/5] fix: name the ungranted run path by its role (ADR-0106) A Windows run refused for a missing container grant now names the grant it lacks: root N of toolchain profile NAME, the package cache root, the workspace folder, or the program file, with the access it needs and has and where to grant it. The message leaves out the host path, because the model's command tool returns the same text; the trusted CLI adds the path in a separate refused_path field. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 24 ++ Cargo.lock | 10 +- Cargo.toml | 2 +- crates/omgcode-cli/src/main.rs | 10 + crates/omgcode-cli/src/run_cli.rs | 46 +- crates/omgcode-cli/tests/run_workflow.rs | 86 +++- crates/omgcode-core/src/control/container.rs | 16 + crates/omgcode-core/src/run.rs | 155 ++++++- crates/omgcode-core/src/run/refusal.rs | 396 ++++++++++++++++++ crates/omgcode-platform/src/container.rs | 11 + crates/omgcode-platform/src/process.rs | 18 +- .../src/process/confinement.rs | 47 ++- crates/omgcode-platform/src/process/tests.rs | 47 +++ .../src/process/tests/windows_confinement.rs | 62 ++- .../omgcode-platform/src/process/windows.rs | 70 ++-- ...name-the-ungranted-run-path-by-its-role.md | 117 ++++++ docs/adr/index.md | 1 + docs/execution.md | 17 + docs/testing-standards.md | 2 +- 19 files changed, 1073 insertions(+), 64 deletions(-) create mode 100644 crates/omgcode-core/src/run/refusal.rs create mode 100644 docs/adr/0106-name-the-ungranted-run-path-by-its-role.md diff --git a/CHANGELOG.md b/CHANGELOG.md index cfeb1bbf..7d52d548 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -600,6 +600,30 @@ Changes are recorded here before a release version is assigned. ### Changed +- Version 0.70.0 makes a Windows run refused for a missing container grant + say which grant is missing (ADR-0106). The refusal used to be one fixed + sentence, "a confinement path is not granted to the container at its + listed level", for every path, so neither the operator nor a model relaying + the command tool's result could tell which folder to grant. An operator's + `rust` profile had four roots; the rustup toolchain under their own folder + had no grant, and the other three are readable by every application + package. Finding it took reading each root's access-control list by hand. + The Windows runner now returns `ProcessError::Ungranted` with the refused + entry, its path, the access it needs, and the access the container has. + Core matches the path against the paths it listed and returns + `RunError::NotGranted`, whose text names the role: root N of toolchain + profile `NAME` (numbered from 1 as `profile-show` and the `settings` + window list them), the workspace's package cache root, the workspace + folder, or the program file. The text gives the needed and held access and + says where to grant it, but never includes the path. The command tool sends + that text to the model, and a path under the user's folder can name the + account. The trusted CLI's `run` error keeps the same message and adds + `refused_path` with the role, `needed`, `granted`, and the path as `path`, + `path_display`, and `path_native`. The checked paths, their order, the + levels, the `not_started` record, and the tool's `command_failed` code are + unchanged. Windows platform and CLI tests apply real grants to temporary + folders; the desktop shell was not driven. + - Version 0.69.0 makes the read-write container grant say what it does (ADR-0104). In the desktop `settings` window, **Grant a folder** with read and write no longer opens a folder dialog: core accepts that access only on diff --git a/Cargo.lock b/Cargo.lock index ed027f00..e27ccd6c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3622,7 +3622,7 @@ dependencies = [ [[package]] name = "omgcode-app" -version = "0.69.0" +version = "0.70.0" dependencies = [ "directories", "omgcode-core", @@ -3638,7 +3638,7 @@ dependencies = [ [[package]] name = "omgcode-cli" -version = "0.69.0" +version = "0.70.0" dependencies = [ "clap", "omgcode-app", @@ -3651,7 +3651,7 @@ dependencies = [ [[package]] name = "omgcode-core" -version = "0.69.0" +version = "0.70.0" dependencies = [ "base64 0.23.1", "bytes", @@ -3675,7 +3675,7 @@ dependencies = [ [[package]] name = "omgcode-desktop" -version = "0.69.0" +version = "0.70.0" dependencies = [ "omgcode-app", "omgcode-platform", @@ -3689,7 +3689,7 @@ dependencies = [ [[package]] name = "omgcode-platform" -version = "0.69.0" +version = "0.70.0" dependencies = [ "libc", "rustix", diff --git a/Cargo.toml b/Cargo.toml index da888702..53f4f77f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,7 @@ resolver = "3" members = ["crates/omgcode-core", "crates/omgcode-cli", "crates/omgcode-platform", "crates/omgcode-app", "crates/omgcode-desktop"] [workspace.package] -version = "0.69.0" +version = "0.70.0" edition = "2024" rust-version = "1.99.1" license = "Apache-2.0" diff --git a/crates/omgcode-cli/src/main.rs b/crates/omgcode-cli/src/main.rs index c04ebe8a..da455194 100644 --- a/crates/omgcode-cli/src/main.rs +++ b/crates/omgcode-cli/src/main.rs @@ -301,6 +301,9 @@ struct CliError { message: String, #[serde(skip_serializing_if = "Option::is_none")] session: Option>, + /// The path a refused run needed, for the operator only (ADR-0106). + #[serde(skip_serializing_if = "Option::is_none")] + refused_path: Option>, } #[derive(Clone, Serialize)] @@ -331,6 +334,7 @@ impl CliError { code, message: message.into(), session: None, + refused_path: None, } } @@ -339,6 +343,12 @@ impl CliError { self.session = Some(Box::new(session)); self } + + /// Name the path a refused run needed. The message leaves it out. + fn with_refused_path(mut self, refused: run_cli::RefusedPath) -> Self { + self.refused_path = Some(Box::new(refused)); + self + } } /// Emit controlled JSON errors; never render untrusted text as terminal escapes. diff --git a/crates/omgcode-cli/src/run_cli.rs b/crates/omgcode-cli/src/run_cli.rs index 43f5eb8e..fc129025 100644 --- a/crates/omgcode-cli/src/run_cli.rs +++ b/crates/omgcode-cli/src/run_cli.rs @@ -7,18 +7,52 @@ use std::str::FromStr; use std::time::Duration; use clap::{Args, Subcommand}; +use omgcode_core::control::ContainerGrantAccess; use omgcode_core::policy::WorkspaceId; use omgcode_core::run::{ self, CancelSignal, DEFAULT_TREE_CPU_TIME, DEFAULT_TREE_DISK_BYTES, DEFAULT_TREE_MEMORY_BYTES, DEFAULT_TREE_PROCESSES, MAX_CAPTURE_BYTES, MAX_DEADLINE, MAX_TREE_CPU_TIME, MAX_TREE_DISK_BYTES, MAX_TREE_MEMORY_BYTES, MAX_TREE_PROCESSES, MIN_TREE_DISK_BYTES, - MIN_TREE_MEMORY_BYTES, ProcessLimits, RunError, RunRequest, TreeLimits, cancel_on_interrupt, + MIN_TREE_MEMORY_BYTES, ProcessLimits, RefusedPathRole, RunError, RunRequest, TreeLimits, + UngrantedRunPath, cancel_on_interrupt, }; +use omgcode_core::session::NativePath; +use serde::Serialize; use serde_json::json; use uuid::Uuid; use crate::{CliError, print_json}; +/// The path a run needed that the workspace's container cannot use, shown to +/// the operator beside the error message. The message names only the path's +/// role, because the command tool sends the same text to a model (ADR-0106). +#[derive(Serialize)] +pub(crate) struct RefusedPath { + role: RefusedPathRole, + needed: ContainerGrantAccess, + granted: Option, + /// The path when it is valid Unicode. + path: Option, + /// A lossy form for display only. + path_display: String, + /// The lossless native form, when it can be encoded. + path_native: Option, +} + +impl RefusedPath { + fn new(refusal: &UngrantedRunPath) -> Self { + let path = refusal.path(); + Self { + role: refusal.role().clone(), + needed: refusal.needed(), + granted: refusal.granted(), + path: path.to_str().map(str::to_owned), + path_display: path.to_string_lossy().into_owned(), + path_native: NativePath::from_path(path).ok(), + } + } +} + /// Run one program in a workspace under native confinement. #[derive(Args)] pub(crate) struct RunArgs { @@ -161,7 +195,15 @@ pub(crate) fn run(args: RunArgs, data_root: &Path) -> Result<(), CliError> { ), )) } - Err(error) => Err(CliError::new("run", error.to_string())), + Err(error) => { + let failure = CliError::new("run", error.to_string()); + Err(match &error { + RunError::NotGranted { refusal, .. } => { + failure.with_refused_path(RefusedPath::new(refusal)) + } + _ => failure, + }) + } } } diff --git a/crates/omgcode-cli/tests/run_workflow.rs b/crates/omgcode-cli/tests/run_workflow.rs index 6ab1428a..3b9e873b 100644 --- a/crates/omgcode-cli/tests/run_workflow.rs +++ b/crates/omgcode-cli/tests/run_workflow.rs @@ -134,6 +134,91 @@ fn an_ungranted_package_cache_root_fails_the_run() { !scene.workspace.join("ran.txt").exists(), "the refused run started its program" ); + let error = refused_error(&output, &cache_root, "package-cache-root"); + let message = error["message"].as_str().expect("message"); + assert!( + message.contains( + "has no access to the workspace's package cache root, which needs read-execute" + ), + "{message}" + ); + assert_eq!( + error["refused_path"]["role"], + serde_json::json!({"kind": "package_cache"}), + "{error}" + ); + assert_one_not_started(&scene); + scene.close(); +} + +/// The user-profile toolchain case: a profile root the workspace's container +/// cannot read fails the run before the program starts. The message, which +/// the command tool also sends to a model, names the root by its profile and +/// position; only the operator's `refused_path` has the path (ADR-0106). +#[cfg(windows)] +#[test] +fn an_ungranted_profile_root_is_named_by_its_profile_and_position() { + let scene = Scene::new(); + let tools = scene.path("ungranted-tools"); + fs::create_dir(&tools).expect("tools"); + // The system root is root 1, so the ungranted folder is root 2. + assert_success(&scene.add_profile("system", &[&tools])); + let output = scene.run("system", &[], &shell("echo ran>ran.txt")); + assert_error_code(&output, "run"); + assert!( + !scene.workspace.join("ran.txt").exists(), + "the refused run started its program" + ); + let error = refused_error(&output, &tools, "ungranted-tools"); + let message = error["message"].as_str().expect("message"); + assert!( + message.contains( + "has no access to root 2 of toolchain profile `system`, which needs read-execute" + ), + "{message}" + ); + assert!( + message.contains("Container grants") && message.contains("container-grant"), + "{message}" + ); + assert_eq!( + error["refused_path"]["role"], + serde_json::json!({"kind": "profile_root", "profile": "system", "number": 2}), + "{error}" + ); + assert_one_not_started(&scene); + scene.close(); +} + +/// The CLI error of a run refused for `expected`: the message leaves out the +/// path (`name` is its last component), and `refused_path` names it at +/// read-execute with no access held. +#[cfg(windows)] +fn refused_error(output: &std::process::Output, expected: &std::path::Path, name: &str) -> Value { + let error: Value = serde_json::from_slice(&output.stderr).expect("CLI error is JSON"); + let error = error["error"].clone(); + let message = error["message"].as_str().expect("message"); + assert!(message.contains("did not start"), "{message}"); + assert!( + !message.contains(name), + "the message names the path: {message}" + ); + let refused = &error["refused_path"]; + assert_eq!(refused["needed"], "read_execute", "{error}"); + assert_eq!(refused["granted"], Value::Null, "{error}"); + assert!(!refused["path_native"].is_null(), "{error}"); + let path = refused["path"].as_str().expect("refused path"); + assert_eq!( + fs::canonicalize(path).expect("refused path exists"), + fs::canonicalize(expected).expect("expected path exists"), + "{error}" + ); + error +} + +/// One run was recorded, and it did not start. +#[cfg(windows)] +fn assert_one_not_started(scene: &Scene) { let audit = scene.audit(); let finished: Vec<&Value> = audit["entries"] .as_array() @@ -146,7 +231,6 @@ fn an_ungranted_package_cache_root_fails_the_run() { finished[0]["action"]["payload"]["finish"]["result"]["kind"], "not_started", "{audit}" ); - scene.close(); } /// A Linux run can read only its workspace's package cache. The cache is diff --git a/crates/omgcode-core/src/control/container.rs b/crates/omgcode-core/src/control/container.rs index d3753374..1f226386 100644 --- a/crates/omgcode-core/src/control/container.rs +++ b/crates/omgcode-core/src/control/container.rs @@ -102,6 +102,22 @@ impl From for ContainerAccess { } } +impl From for ContainerGrantAccess { + fn from(value: ContainerAccess) -> Self { + match value { + ContainerAccess::ReadExecute => Self::ReadExecute, + ContainerAccess::ReadWrite => Self::ReadWrite, + } + } +} + +impl std::fmt::Display for ContainerGrantAccess { + /// The spelling the CLI's `--access` option takes. + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + ContainerAccess::from(*self).fmt(formatter) + } +} + /// Where a grant is in its lifecycle. #[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)] #[serde(rename_all = "snake_case")] diff --git a/crates/omgcode-core/src/run.rs b/crates/omgcode-core/src/run.rs index 4917ce6e..53e5e447 100644 --- a/crates/omgcode-core/src/run.rs +++ b/crates/omgcode-core/src/run.rs @@ -37,6 +37,11 @@ use crate::session::{NativePath, SessionError}; use crate::storage::{self, StorageError}; use crate::workspace::DirectoryRecord; +mod refusal; + +use refusal::ListedPaths; +pub use refusal::{RefusedPathRole, UngrantedRunPath}; + pub use omgcode_platform::interrupt::{InterruptWatch, cancel_on_interrupt, watch_interrupt}; pub use omgcode_platform::process::{CancelSignal, ProcessLimits, TreeLimits}; pub use omgcode_platform::process::{ @@ -216,6 +221,16 @@ pub enum RunError { #[source] source: ProcessError, }, + /// The intent was recorded, but the workspace's AppContainer cannot use + /// one of the run's paths at the level the run needs, so nothing started. + /// The outcome is recorded as `not_started`. The text names the path's + /// role and the missing access, never the path, because a model receives + /// it (ADR-0106); [`UngrantedRunPath::path`] has the path. + #[error("run {run_id} did not start: {refusal}")] + NotGranted { + run_id: Uuid, + refusal: Box, + }, /// The program started, but supervision failed. The tree was observed /// empty and the outcome is recorded. #[error("run {run_id} failed during supervision: {source}")] @@ -263,6 +278,8 @@ struct Prepared { spec: ProcessSpec, confinement: Confinement, scratch: Option, + /// What each path core listed is for, to name a refused one. + listed: ListedPaths, } /// The Linux per-run scratch directory, removed after the run. @@ -441,7 +458,8 @@ pub fn run( }); let revoked_because = revoked.get().copied(); let scratch_removed = prepared.scratch.as_mut().map(Scratch::remove); - let (finish, outcome, failure) = settle(run_id, result, revoked_because.is_some()); + let (finish, outcome, failure) = + settle(run_id, result, revoked_because.is_some(), &prepared.listed); let report = RunReport { start: prepared.start, finish, @@ -815,11 +833,13 @@ fn confirm_stopped( } /// Map the runner's result to a recorded outcome and, for failures, an error. -/// A tree stopped because access was withdrawn is recorded as `revoked`. +/// A tree stopped because access was withdrawn is recorded as `revoked`. A +/// refused path is named by its role in `listed`. fn settle( run_id: Uuid, result: Result, revoked: bool, + listed: &ListedPaths, ) -> (RunFinish, Option, Option) { match result { Ok(outcome) => { @@ -861,6 +881,13 @@ fn settle( RunResult::CleanupUnconfirmed, RunError::CleanupUnconfirmed { run_id, source }, ), + ProcessError::Ungranted(ungranted) => ( + RunResult::NotStarted, + RunError::NotGranted { + run_id, + refusal: Box::new(listed.refusal(*ungranted)), + }, + ), source => ( RunResult::NotStarted, RunError::NotStarted { run_id, source }, @@ -981,7 +1008,13 @@ fn prepare( let search_path = std::env::join_paths(&path_entries) .map_err(|_| RunError::Refused("a PATH entry contains the platform's list separator"))?; let mut environment = vec![(OsString::from("PATH"), search_path)]; - let (confinement, scratch, support_paths, package_cache) = platform_setup( + let listed_roots = roots.clone(); + let PlatformSetup { + confinement, + scratch, + support_paths, + package_cache, + } = platform_setup( control, request, &scope.workspace, @@ -1033,11 +1066,17 @@ fn prepare( } else { None }, - package_cache, + package_cache: package_cache.is_some(), package_cache_root, model_origin: request.model_tools, standing_allow: request.standing_allow, }; + let listed = ListedPaths { + profile: profile.name().to_owned(), + roots: listed_roots, + package_cache, + workspace, + }; Ok(Prepared { start, spec: ProcessSpec { @@ -1048,6 +1087,7 @@ fn prepare( }, confinement, scratch, + listed, }) } @@ -1163,8 +1203,18 @@ fn network_access(request: &RunRequest) -> NetworkAccess { } } -/// Build the platform confinement and the runner-owned variables. Also -/// return the resolver and certificate paths added for network access. +/// What [`platform_setup`] builds for one run. +struct PlatformSetup { + confinement: Confinement, + /// The Linux per-run scratch directory. + scratch: Option, + /// The resolver and certificate paths added for network access. + support_paths: Vec, + /// The package cache root the run lists, if any. + package_cache: Option, +} + +/// Build the platform confinement and the runner-owned variables. #[cfg(target_os = "linux")] #[allow(clippy::too_many_arguments)] fn platform_setup( @@ -1176,7 +1226,7 @@ fn platform_setup( data_root: &Path, run_id: Uuid, environment: &mut Vec<(OsString, OsString)>, -) -> Result<(Confinement, Option, Vec, bool), RunError> { +) -> Result { let parent = data_root.join("run-scratch"); crate::storage::create_private_directories(&parent) .map_err(|error| io::Error::other(error.to_string()))?; @@ -1223,12 +1273,12 @@ fn platform_setup( network: network_access(request), container: None, }; - Ok(( + Ok(PlatformSetup { confinement, - Some(scratch), + scratch: Some(scratch), support_paths, - package_cache.is_some(), - )) + package_cache, + }) } /// The private package cache for one workspace, when it exists as a plain @@ -1288,7 +1338,7 @@ fn platform_setup( data_root: &Path, _run_id: Uuid, environment: &mut Vec<(OsString, OsString)>, -) -> Result<(Confinement, Option, Vec, bool), RunError> { +) -> Result { use crate::control::container_name; workspace_access(control, request.workspace_id, workspace_record, false) @@ -1319,7 +1369,12 @@ fn platform_setup( network: network_access(request), container: Some(name), }; - Ok((confinement, None, Vec::new(), package_cache.is_some())) + Ok(PlatformSetup { + confinement, + scratch: None, + support_paths: Vec::new(), + package_cache, + }) } #[cfg(not(any(target_os = "linux", windows)))] @@ -1333,7 +1388,7 @@ fn platform_setup( _data_root: &Path, _run_id: Uuid, _environment: &mut Vec<(OsString, OsString)>, -) -> Result<(Confinement, Option, Vec, bool), RunError> { +) -> Result { Err(RunError::Refused( "trusted runs exist only on Linux and Windows", )) @@ -1568,6 +1623,78 @@ mod tests { } } + /// A path the container cannot use is a `not_started` run with no + /// confinement, like any other refused start, and its error names the + /// path's role instead of the path. Other start failures are unchanged. + #[test] + fn an_ungranted_path_is_recorded_as_not_started_and_named_by_its_role() { + use omgcode_platform::container::ContainerAccess; + use omgcode_platform::process::{ConfinementEntry, UngrantedPath}; + + let base = std::env::temp_dir().join("omgcode-settle-user"); + let root = base.join("toolchain-kappa"); + let listed = ListedPaths { + profile: "tools".into(), + roots: vec![base.join("system-lambda"), root.clone()], + package_cache: None, + workspace: base.join("work-mu"), + }; + let run_id = Uuid::new_v4(); + let ungranted = UngrantedPath { + entry: ConfinementEntry::ReadOnly(1), + path: root.clone(), + needed: ContainerAccess::ReadExecute, + granted: None, + }; + let (finish, outcome, failure) = settle( + run_id, + Err(ProcessError::Ungranted(Box::new(ungranted))), + false, + &listed, + ); + assert_eq!(finish.result, RunResult::NotStarted); + assert!(finish.confinement.is_none(), "{finish:?}"); + assert!(outcome.is_none()); + let Some(RunError::NotGranted { + run_id: refused, + refusal, + }) = failure + else { + panic!("expected a refused path, got {failure:?}"); + }; + assert_eq!(refused, run_id); + assert_eq!( + refusal.role(), + &RefusedPathRole::ProfileRoot { + profile: "tools".into(), + number: 2, + } + ); + assert_eq!(refusal.path(), root); + let text = RunError::NotGranted { run_id, refusal }.to_string(); + assert!( + text.starts_with(&format!( + "run {run_id} did not start: the workspace's sandbox has no access to root 2 of toolchain profile `tools`" + )), + "{text}" + ); + assert!(!text.contains("omgcode-settle-user"), "{text}"); + assert!(!text.contains("toolchain-kappa"), "{text}"); + + let missing = io::Error::new(io::ErrorKind::NotFound, "no profile"); + let (finish, _, failure) = settle( + run_id, + Err(ProcessError::Confinement(missing)), + false, + &listed, + ); + assert_eq!(finish.result, RunResult::NotStarted); + assert!( + matches!(failure, Some(RunError::NotStarted { .. })), + "{failure:?}" + ); + } + /// A run of a recorded profile, so the settings still allow it on Linux. #[cfg(target_os = "linux")] fn allowed_start(data: &Path, directory: &Path, workspace_id: WorkspaceId) -> RunStart { diff --git a/crates/omgcode-core/src/run/refusal.rs b/crates/omgcode-core/src/run/refusal.rs new file mode 100644 index 00000000..27341ad3 --- /dev/null +++ b/crates/omgcode-core/src/run/refusal.rs @@ -0,0 +1,396 @@ +//! What a run path the workspace's AppContainer refused is for. +//! +//! The Windows runner refuses a run before anything starts when the +//! workspace's container cannot use one of the run's paths at the level the +//! run needs. It reports the path and its place in the confinement; this +//! module maps that back to the role core gave the path, so the refusal can +//! say which grant is missing. [`UngrantedRunPath`]'s `Display` is part of +//! [`super::RunError`]'s text, which a model receives as a tool result, so it +//! names the role, the toolchain profile, and the access, never the host +//! path. Trusted operator surfaces read [`UngrantedRunPath::path`]. See +//! ADR-0106. + +use std::fmt; +use std::path::{Path, PathBuf}; + +use omgcode_platform::process::{ConfinementEntry, UngrantedPath}; +use serde::Serialize; + +use crate::control::ContainerGrantAccess; + +/// Where the operator grants a container access, in the words of the other +/// run refusals (ADR-0104). +const WHERE_TO_GRANT: &str = + "under Settings, Advanced, Container grants, or with `omgcode workspace container-grant`"; + +/// The role core gave a refused path when it built the run's confinement. +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum RefusedPathRole { + /// The workspace folder, which every run needs read-write. + Workspace, + /// A read-only root of the run's toolchain profile, numbered from 1 in + /// the order the profile records its roots, as the `settings` window and + /// `workspace profile-show` list them. + ProfileRoot { + /// The profile's recorded name. + profile: String, + /// The root's position in the profile, from 1. + number: usize, + }, + /// The workspace's package cache root. + PackageCache, + /// The program file the profile resolved. + Program, + /// A path core did not list itself. No current run has one; it keeps a + /// future path refused with its level rather than misnamed. + Other, +} + +/// A run that did not start because the workspace's AppContainer cannot use +/// one of its paths at the level the run needs (Windows only). +/// +/// `Display` names the role and the access, never the path, because it is +/// sent to the model. [`Self::path`] is for trusted operator surfaces such as +/// the CLI's `refused_path`. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct UngrantedRunPath { + role: RefusedPathRole, + needed: ContainerGrantAccess, + granted: Option, + path: PathBuf, +} + +impl UngrantedRunPath { + /// What the refused path is for. + #[must_use] + pub fn role(&self) -> &RefusedPathRole { + &self.role + } + + /// The access the run needs on the path. + #[must_use] + pub fn needed(&self) -> ContainerGrantAccess { + self.needed + } + + /// The access the container has now, from a grant or because every + /// application package has it; `None` when it has neither. + #[must_use] + pub fn granted(&self) -> Option { + self.granted + } + + /// The refused host path. Show it only on trusted operator surfaces; + /// never add it to text a model receives. + #[must_use] + pub fn path(&self) -> &Path { + &self.path + } +} + +impl fmt::Display for UngrantedRunPath { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + let needed = self.needed; + let held = match self.granted { + None => "no access".to_owned(), + Some(access) => format!("only {access} access"), + }; + match &self.role { + RefusedPathRole::Workspace => write!( + formatter, + "the workspace's sandbox has {held} to the workspace folder, which needs \ + {needed}, although a grant is recorded; its access-control entry may have \ + been changed outside OMGCode. Revoke the grant and grant it again under \ + Settings, Advanced, Container grants, or with `omgcode workspace \ + container-revoke` and `omgcode workspace container-grant`" + ), + RefusedPathRole::ProfileRoot { profile, number } => write!( + formatter, + "the workspace's sandbox has {held} to root {number} of toolchain profile \ + `{profile}`, which needs {needed}. The settings window and `omgcode \ + workspace profile-show {profile}` list the profile's roots in order; grant \ + that folder {needed} {WHERE_TO_GRANT}" + ), + RefusedPathRole::PackageCache => write!( + formatter, + "the workspace's sandbox has {held} to the workspace's package cache root, \ + which needs {needed}; grant it {needed} {WHERE_TO_GRANT}" + ), + RefusedPathRole::Program => write!( + formatter, + "the workspace's sandbox has {held} to the program file the profile \ + resolved, which needs {needed}; grant the folder that holds it {needed} \ + {WHERE_TO_GRANT}" + ), + RefusedPathRole::Other => write!( + formatter, + "the workspace's sandbox has {held} to a path the run lists, which needs \ + {needed}" + ), + } + } +} + +/// The paths core listed in a run's confinement, kept so a refusal can name +/// the role of the path it refused. Paths are in the native form the +/// confinement holds, so a refused path compares equal to one of them. +#[derive(Debug)] +pub(super) struct ListedPaths { + /// The run's toolchain profile name. + pub(super) profile: String, + /// The profile's read-only roots, in recorded order. + pub(super) roots: Vec, + /// The workspace's package cache root, when the run lists one. + pub(super) package_cache: Option, + /// The workspace folder. + pub(super) workspace: PathBuf, +} + +impl ListedPaths { + /// Describe a refusal the runner reported for this run. + pub(super) fn refusal(&self, ungranted: UngrantedPath) -> UngrantedRunPath { + UngrantedRunPath { + role: self.role(ungranted.entry, &ungranted.path), + needed: ungranted.needed.into(), + granted: ungranted.granted.map(Into::into), + path: ungranted.path, + } + } + + /// Match by path rather than by index: the lists hold other entries in a + /// platform-specific order, and only the path says which one was meant. + fn role(&self, entry: ConfinementEntry, path: &Path) -> RefusedPathRole { + match entry { + ConfinementEntry::Program => RefusedPathRole::Program, + ConfinementEntry::ReadWrite(_) if path == self.workspace => RefusedPathRole::Workspace, + ConfinementEntry::ReadWrite(_) => RefusedPathRole::Other, + ConfinementEntry::ReadOnly(_) => { + if let Some(index) = self.roots.iter().position(|root| root == path) { + RefusedPathRole::ProfileRoot { + profile: self.profile.clone(), + // At most 16 roots, so this cannot saturate. + number: index.saturating_add(1), + } + } else if self.package_cache.as_deref() == Some(path) { + RefusedPathRole::PackageCache + } else { + RefusedPathRole::Other + } + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use omgcode_platform::container::ContainerAccess; + + /// A user's home with distinctive folder names. Nothing here is opened, + /// so the paths need not exist; none of the names is a word the + /// refusal text uses. + fn listed() -> ListedPaths { + let home = PathBuf::from(if cfg!(windows) { + r"C:\Users\omgcode-test-user" + } else { + "/home/omgcode-test-user" + }); + ListedPaths { + profile: "rust".into(), + roots: vec![ + home.join("sysroot-alpha"), + home.join(".rustup-beta").join("toolchain-gamma"), + ], + package_cache: Some(home.join("pkgstore-delta")), + workspace: home.join("devroot-epsilon").join("project-zeta"), + } + } + + fn ungranted( + entry: ConfinementEntry, + path: PathBuf, + needed: ContainerAccess, + granted: Option, + ) -> UngrantedPath { + UngrantedPath { + entry, + path, + needed, + granted, + } + } + + /// Every role, the level it needs, and the access the container had. + fn cases(listed: &ListedPaths) -> Vec<(UngrantedPath, RefusedPathRole)> { + vec![ + ( + ungranted( + ConfinementEntry::ReadOnly(1), + listed.roots[1].clone(), + ContainerAccess::ReadExecute, + None, + ), + RefusedPathRole::ProfileRoot { + profile: "rust".into(), + number: 2, + }, + ), + ( + ungranted( + ConfinementEntry::ReadOnly(5), + listed.package_cache.clone().expect("cache"), + ContainerAccess::ReadExecute, + None, + ), + RefusedPathRole::PackageCache, + ), + ( + ungranted( + ConfinementEntry::ReadWrite(0), + listed.workspace.clone(), + ContainerAccess::ReadWrite, + Some(ContainerAccess::ReadExecute), + ), + RefusedPathRole::Workspace, + ), + ( + ungranted( + ConfinementEntry::ReadWrite(0), + listed.workspace.clone(), + ContainerAccess::ReadWrite, + None, + ), + RefusedPathRole::Workspace, + ), + ( + ungranted( + ConfinementEntry::Program, + listed.roots[1].join("bin-eta").join("tool-theta.exe"), + ContainerAccess::ReadExecute, + None, + ), + RefusedPathRole::Program, + ), + ( + ungranted( + ConfinementEntry::ReadOnly(3), + listed.workspace.join("other-iota"), + ContainerAccess::ReadExecute, + None, + ), + RefusedPathRole::Other, + ), + ( + ungranted( + ConfinementEntry::ReadWrite(1), + listed.roots[0].clone(), + ContainerAccess::ReadWrite, + Some(ContainerAccess::ReadExecute), + ), + RefusedPathRole::Other, + ), + ] + } + + #[test] + fn each_refused_path_is_named_by_its_role_and_level() { + let listed = listed(); + for (reported, role) in cases(&listed) { + let needed = ContainerGrantAccess::from(reported.needed); + let granted = reported.granted.map(ContainerGrantAccess::from); + let path = reported.path.clone(); + let refusal = listed.refusal(reported); + assert_eq!(refusal.role(), &role, "{path:?}"); + assert_eq!(refusal.needed(), needed, "{role:?}"); + assert_eq!(refusal.granted(), granted, "{role:?}"); + assert_eq!(refusal.path(), path, "{role:?}"); + } + } + + /// The text goes to the model, so it must say what to grant without the + /// host path or any part of the user's folder. + #[test] + fn the_refusal_text_names_the_grant_but_never_the_path() { + let listed = listed(); + for (reported, role) in cases(&listed) { + let needed = ContainerGrantAccess::from(reported.needed).to_string(); + let refusal = listed.refusal(reported); + let text = refusal.to_string(); + assert!( + text.contains(&format!("needs {needed}")), + "{role:?}: {text}" + ); + for component in refusal.path().components() { + if let std::path::Component::Normal(part) = component { + let part = part.to_string_lossy(); + assert!( + !text.contains(part.as_ref()), + "{role:?} leaked {part:?}: {text}" + ); + } + } + let expected = match &role { + RefusedPathRole::ProfileRoot { profile, number } => { + format!("root {number} of toolchain profile `{profile}`") + } + RefusedPathRole::Workspace => "the workspace folder".to_owned(), + RefusedPathRole::PackageCache => "package cache root".to_owned(), + RefusedPathRole::Program => "the program file".to_owned(), + RefusedPathRole::Other => "a path the run lists".to_owned(), + }; + assert!(text.contains(&expected), "{role:?}: {text}"); + if role != RefusedPathRole::Other { + assert!( + text.contains("Container grants") && text.contains("container-grant"), + "{role:?} does not say where to grant: {text}" + ); + } + } + } + + #[test] + fn the_refusal_text_says_what_access_the_container_has() { + let listed = listed(); + let weaker = listed.refusal(ungranted( + ConfinementEntry::ReadWrite(0), + listed.workspace.clone(), + ContainerAccess::ReadWrite, + Some(ContainerAccess::ReadExecute), + )); + assert!( + weaker.to_string().contains( + "has only read-execute access to the workspace folder, which needs read-write" + ), + "{weaker}" + ); + let missing = listed.refusal(ungranted( + ConfinementEntry::ReadOnly(0), + listed.roots[0].clone(), + ContainerAccess::ReadExecute, + None, + )); + assert!( + missing.to_string().contains( + "has no access to root 1 of toolchain profile `rust`, which needs read-execute" + ), + "{missing}" + ); + } + + #[test] + fn the_role_serializes_with_its_kind() { + let role = RefusedPathRole::ProfileRoot { + profile: "rust".into(), + number: 2, + }; + assert_eq!( + serde_json::to_value(&role).expect("role JSON"), + serde_json::json!({"kind": "profile_root", "profile": "rust", "number": 2}) + ); + assert_eq!( + serde_json::to_value(RefusedPathRole::PackageCache).expect("role JSON"), + serde_json::json!({"kind": "package_cache"}) + ); + } +} diff --git a/crates/omgcode-platform/src/container.rs b/crates/omgcode-platform/src/container.rs index 08019745..f4709598 100644 --- a/crates/omgcode-platform/src/container.rs +++ b/crates/omgcode-platform/src/container.rs @@ -21,6 +21,7 @@ //! Other platforms have no AppContainer; every operation there returns //! [`io::ErrorKind::Unsupported`]. +use std::fmt; use std::io; use std::path::{Path, PathBuf}; @@ -78,6 +79,16 @@ pub enum ContainerAccess { ReadWrite, } +impl fmt::Display for ContainerAccess { + /// The spelling the CLI's `--access` option takes. + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str(match self { + Self::ReadExecute => "read-execute", + Self::ReadWrite => "read-write", + }) + } +} + /// The container SID for `name`, in string form such as `S-1-15-2-…`. pub fn container_sid(name: &ContainerName) -> io::Result { #[cfg(windows)] diff --git a/crates/omgcode-platform/src/process.rs b/crates/omgcode-platform/src/process.rs index 18421b1d..a9e30f07 100644 --- a/crates/omgcode-platform/src/process.rs +++ b/crates/omgcode-platform/src/process.rs @@ -36,7 +36,8 @@ mod tests; #[cfg(target_os = "linux")] pub use confinement::network_support_paths; pub use confinement::{ - AppliedConfinement, Confinement, MAX_CONFINEMENT_PATHS, NetworkAccess, UnixSocketAccess, + AppliedConfinement, Confinement, ConfinementEntry, MAX_CONFINEMENT_PATHS, NetworkAccess, + UngrantedPath, UnixSocketAccess, }; /// Largest accepted run deadline. @@ -300,6 +301,10 @@ pub enum ProcessError { /// missing, is a symbolic link, or has an unsupported type. Nothing was /// started. Confinement(io::Error), + /// A listed path, or the program, is not granted to the run's + /// AppContainer at the level the run needs. Nothing was started. Only + /// Windows reports it; the display text leaves the path out. + Ungranted(Box), /// The program could not be started. No process from this run remains. Spawn(io::Error), /// Supervision failed after start. The runner terminated the tree and @@ -327,6 +332,17 @@ impl fmt::Display for ProcessError { "a confinement rule could not be prepared: {error}" ) } + Self::Ungranted(refusal) => { + let held = match refusal.granted { + Some(access) => format!("only {access}"), + None => "no access".to_owned(), + }; + write!( + formatter, + "a confinement path is not granted to the container at its listed level: {} needs {} and has {held}", + refusal.entry, refusal.needed + ) + } Self::Spawn(error) => write!(formatter, "the program could not be started: {error}"), Self::Supervision(error) => write!(formatter, "process supervision failed: {error}"), Self::CleanupUnconfirmed(reason) => { diff --git a/crates/omgcode-platform/src/process/confinement.rs b/crates/omgcode-platform/src/process/confinement.rs index a8eda556..19a9d94b 100644 --- a/crates/omgcode-platform/src/process/confinement.rs +++ b/crates/omgcode-platform/src/process/confinement.rs @@ -8,10 +8,11 @@ //! listed path is already granted to it. See `docs/execution.md`, ADR-0028, //! ADR-0029, and ADR-0032. +use std::fmt; use std::path::{Path, PathBuf}; use super::{ProcessError, contains_nul}; -use crate::container::ContainerName; +use crate::container::{ContainerAccess, ContainerName}; /// Largest number of paths, read-only and read-write together, in one confinement. pub const MAX_CONFINEMENT_PATHS: usize = 64; @@ -32,7 +33,8 @@ pub const MAX_CONFINEMENT_PATHS: usize = 64; /// On Windows the rules are not applied at start. Access comes from the /// persistent grants made with [`crate::container::grant`]; each listed path /// must already carry a grant of at least its listed level for -/// [`Confinement::container`], or nothing starts. Paths every application +/// [`Confinement::container`], or nothing starts and +/// [`ProcessError::Ungranted`] names the entry. Paths every application /// package can read, such as the Windows directory, stay readable, and grants /// that are not listed still apply. #[derive(Clone, Debug, Default, PartialEq, Eq)] @@ -98,6 +100,47 @@ pub enum UnixSocketAccess { HostServices, } +/// Which path of a run a Windows grant check refused. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ConfinementEntry { + /// The entry at this index of [`Confinement::read_only`]. + ReadOnly(usize), + /// The entry at this index of [`Confinement::read_write`]. + ReadWrite(usize), + /// The run's program, [`ProcessSpec::program`](super::ProcessSpec::program). + Program, +} + +impl fmt::Display for ConfinementEntry { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::ReadOnly(index) => write!(formatter, "read-only entry {index}"), + Self::ReadWrite(index) => write!(formatter, "read-write entry {index}"), + Self::Program => formatter.write_str("the program"), + } + } +} + +/// A path a run lists, or its program, that the run's AppContainer cannot use +/// at the level the run needs. Only the Windows runner reports it, before +/// anything starts. +/// +/// `path` is the host path exactly as the caller listed it, so the caller can +/// tell which of its paths was refused. [`ProcessError`]'s `Display` leaves it +/// out: callers pass that text on, and it reaches a model as a tool result. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct UngrantedPath { + /// Which listed path was refused. + pub entry: ConfinementEntry, + /// The refused path, as listed. + pub path: PathBuf, + /// The access the run needs on `path`. + pub needed: ContainerAccess, + /// The access the container has on `path` now, from a grant or because + /// every application package has it. `None` when it has neither. + pub granted: Option, +} + impl Confinement { /// Check the shape of every rule before anything is opened or started. pub(super) fn validate(&self) -> Result<(), ProcessError> { diff --git a/crates/omgcode-platform/src/process/tests.rs b/crates/omgcode-platform/src/process/tests.rs index 861d4c0c..24821db0 100644 --- a/crates/omgcode-platform/src/process/tests.rs +++ b/crates/omgcode-platform/src/process/tests.rs @@ -606,6 +606,53 @@ fn malformed_confinement_is_refused_before_start() { } } +/// The text names the entry and both levels but never the path, because +/// callers pass it on to a model. +#[test] +fn an_ungranted_path_error_names_the_entry_and_levels_but_not_the_path() { + use super::{ConfinementEntry, UngrantedPath}; + use crate::container::ContainerAccess; + + let path = env::temp_dir().join("omgcode-ungranted-nu"); + let cases = [ + ( + ConfinementEntry::ReadOnly(3), + ContainerAccess::ReadExecute, + None, + "read-only entry 3 needs read-execute and has no access", + ), + ( + ConfinementEntry::ReadWrite(0), + ContainerAccess::ReadWrite, + Some(ContainerAccess::ReadExecute), + "read-write entry 0 needs read-write and has only read-execute", + ), + ( + ConfinementEntry::Program, + ContainerAccess::ReadExecute, + None, + "the program needs read-execute and has no access", + ), + ]; + for (entry, needed, granted, expected) in cases { + let error = ProcessError::Ungranted(Box::new(UngrantedPath { + entry, + path: path.clone(), + needed, + granted, + })); + let text = error.to_string(); + assert_eq!( + text, + format!( + "a confinement path is not granted to the container at its listed level: {expected}" + ) + ); + assert!(!text.contains("omgcode-ungranted-nu"), "{text}"); + assert!(std::error::Error::source(&error).is_none()); + } +} + #[cfg(windows)] #[test] fn windows_refuses_programs_that_are_not_plain_exe_files() { diff --git a/crates/omgcode-platform/src/process/tests/windows_confinement.rs b/crates/omgcode-platform/src/process/tests/windows_confinement.rs index 0d160ef9..c56289f6 100644 --- a/crates/omgcode-platform/src/process/tests/windows_confinement.rs +++ b/crates/omgcode-platform/src/process/tests/windows_confinement.rs @@ -30,8 +30,9 @@ use windows_sys::Win32::System::Pipes::{ }; use super::super::{ - AppliedConfinement, CancelSignal, Confinement, NetworkAccess, ProcessError, ProcessOutcome, - ProcessSpec, ResourceLimit, Termination, UnixSocketAccess, run, run_confined, + AppliedConfinement, CancelSignal, Confinement, ConfinementEntry, NetworkAccess, ProcessError, + ProcessOutcome, ProcessSpec, ResourceLimit, Termination, UngrantedPath, UnixSocketAccess, run, + run_confined, }; use super::{FIXTURE_ENV, HARNESS_ARGS, disk_limits, grow_spec, limits, spec, text}; use crate::container::windows::tests::{TestContainer, identity, unique_name}; @@ -643,6 +644,9 @@ fn a_networked_container_reaches_the_internet() { ); } +/// A missing or weaker grant names the refused entry, its path, the level it +/// needs, and what the container has; the error text leaves the path out. +/// Another container has no profile, which stays a confinement error. #[test] fn missing_or_weaker_grants_start_nothing() { let mut scene = Scene::new(); @@ -650,14 +654,30 @@ fn missing_or_weaker_grants_start_nothing() { let mut cases = Vec::new(); let mut ungranted = scene.confinement(); ungranted.read_only.push(scene.secret.clone()); - cases.push(("ungranted path", ungranted)); + let refused = UngrantedPath { + entry: ConfinementEntry::ReadOnly(2), + path: scene.secret.clone(), + needed: ContainerAccess::ReadExecute, + granted: None, + }; + cases.push(("ungranted path", ungranted, Some(refused))); let mut weaker = scene.confinement(); weaker.read_write.push(scene.read_only_directory.clone()); - cases.push(("read-only grant listed as read-write", weaker)); + let refused = UngrantedPath { + entry: ConfinementEntry::ReadWrite(1), + path: scene.read_only_directory.clone(), + needed: ContainerAccess::ReadWrite, + granted: Some(ContainerAccess::ReadExecute), + }; + cases.push(( + "read-only grant listed as read-write", + weaker, + Some(refused), + )); let mut other_container = scene.confinement(); other_container.container = Some((*unique_name()).clone()); - cases.push(("another container", other_container)); - for (name, confinement) in cases { + cases.push(("another container", other_container, None)); + for (name, confinement, refused) in cases { let mut spec = scene.spec(); spec.environment .retain(|(variable, _)| variable != FIXTURE_ENV); @@ -669,10 +689,18 @@ fn missing_or_weaker_grants_start_nothing() { )); let error = run_confined(&spec, &confinement, &limits(), &CancelSignal::new()).expect_err(name); - assert!( - matches!(error, ProcessError::Confinement(_)), - "{name}: {error}" - ); + match (&error, refused) { + (ProcessError::Ungranted(reported), Some(refused)) => { + assert_eq!(**reported, refused, "{name}"); + let text = error.to_string(); + assert!( + !text.contains(refused.path.to_string_lossy().as_ref()), + "{name}: the error text names the path: {text}" + ); + } + (ProcessError::Confinement(_), None) => {} + _ => panic!("{name}: unexpected error: {error}"), + } assert!(!record.exists(), "{name}: the program started"); } // Stop the host TCP service on the normal path and check its count. @@ -739,9 +767,17 @@ fn a_program_the_container_cannot_read_does_not_start() { spec.program = env::current_exe().expect("test executable"); let error = run_confined(&spec, &scene.confinement(), &limits(), &CancelSignal::new()) .expect_err("the program is not granted to the container"); - assert!( - matches!(&error, ProcessError::Confinement(cause) if cause.kind() == io::ErrorKind::PermissionDenied), - "{error}" + let ProcessError::Ungranted(refused) = &error else { + panic!("expected an ungranted program, got: {error}"); + }; + assert_eq!( + **refused, + UngrantedPath { + entry: ConfinementEntry::Program, + path: spec.program.clone(), + needed: ContainerAccess::ReadExecute, + granted: None, + } ); // Stop the host TCP service on the normal path and check its count. assert_eq!( diff --git a/crates/omgcode-platform/src/process/windows.rs b/crates/omgcode-platform/src/process/windows.rs index fbfaf6d3..31ee714f 100644 --- a/crates/omgcode-platform/src/process/windows.rs +++ b/crates/omgcode-platform/src/process/windows.rs @@ -54,9 +54,10 @@ use windows_sys::Win32::System::Threading::{ }; use super::{ - AppliedConfinement, CancelSignal, Capture, Confinement, NetworkAccess, ProcessError, - ProcessLimits, ProcessOutcome, ProcessSpec, ProcessTree, ResourceLimit, Termination, - TreeLimits, TreeUsage, UnixSocketAccess, is_batch_script, stop_tree, supervise, + AppliedConfinement, CancelSignal, Capture, Confinement, ConfinementEntry, NetworkAccess, + ProcessError, ProcessLimits, ProcessOutcome, ProcessSpec, ProcessTree, ResourceLimit, + Termination, TreeLimits, TreeUsage, UngrantedPath, UnixSocketAccess, is_batch_script, + stop_tree, supervise, }; use crate::container::ContainerAccess; use crate::container::windows::{derive_sid, granted_access, profile_exists}; @@ -231,33 +232,54 @@ fn prepare_container(spec: &ProcessSpec, confinement: &Confinement) -> Result Result<(), ProcessError> { + let granted = granted_access(path, sid).map_err(ProcessError::Confinement)?; + if covers(granted, needed) { + return Ok(()); + } + Err(ProcessError::Ungranted(Box::new(UngrantedPath { + entry, + path: path.to_path_buf(), + needed, + granted, + }))) +} + const fn covers(granted: Option, needed: ContainerAccess) -> bool { matches!( (granted, needed), diff --git a/docs/adr/0106-name-the-ungranted-run-path-by-its-role.md b/docs/adr/0106-name-the-ungranted-run-path-by-its-role.md new file mode 100644 index 00000000..381682ab --- /dev/null +++ b/docs/adr/0106-name-the-ungranted-run-path-by-its-role.md @@ -0,0 +1,117 @@ +# 0106: Name the ungranted run path by its role + +- Status: Accepted +- Date: 2026-11-26 + +## Context + +On Windows a run starts only when the workspace's AppContainer can already +use every path the run lists: read-execute on each toolchain-profile root and +the package cache root, read-write on the workspace folder, and read-execute +on the resolved program +([ADR-0029](0029-confine-windows-runs-in-a-workspace-appcontainer-with-recorded-grants.md)). +The runner checks each path's live access-control list before anything +starts, and it accepts a grant to the container or an entry for every +application package. + +When a path failed, the refusal was one fixed sentence, "a confinement path +is not granted to the container at its listed level", or, for the program, +"the program is not readable and executable by the container". Neither said +which path failed or what access it needed. The trusted CLI `run` command and +the model's command tool both reported that text, and a model relays the +tool's text to the operator. + +An operator hit this from the desktop chat with a `rust` profile of four +roots. Three were under `Program Files` and `C:\Windows`, which every +application package can read. The fourth, the rustup toolchain under the +user's own folder, had no grant. The model could only ask which path had +failed, and the operator could not tell from the error. It took reading each +root's access-control list by hand to find the missing grant. + +The tool result is sent to the model provider as soon as it is recorded. +A host path outside the workspace can name the user's account, for example +`C:\Users\\.rustup\…`. No other run refusal includes a host path: they +are fixed text plus identifiers, and ADR-0104's workspace-grant refusal says +where to grant without naming a folder. + +## Decision + +1. **The runner reports which path failed.** On Windows, a path or program + the container cannot use at the level it needs returns + `ProcessError::Ungranted` with an `UngrantedPath`: the entry + (`ReadOnly(index)`, `ReadWrite(index)`, or `Program`), the path as listed, + the access needed, and the access the container has. A DACL that cannot + be read is still `ProcessError::Confinement`. The display text names the + entry and both levels, never the path. The paths checked, their order, and + the levels are unchanged. +2. **Core names the path by its role.** Core keeps the paths it listed for + the run: the profile name and roots in recorded order, the package cache + root, and the workspace folder. It matches the refused path against them, + by path rather than by index, because the lists hold other entries in an + order that differs by platform. `RunError::NotGranted` carries an + `UngrantedRunPath` with the role (`workspace`, `profile_root` with the + profile and its 1-based position, `package_cache`, `program`, or `other`), + the access needed and held, and the path. The run journal still records + `not_started` with no confinement, as for any other refused start. +3. **The text that reaches the model names the role and the access, not the + path.** For example: "the workspace's sandbox has no access to root 4 of + toolchain profile `rust`, which needs read-execute. The settings window + and `omgcode workspace profile-show rust` list the profile's roots in + order; grant that folder read-execute under Settings, Advanced, Container + grants, or with `omgcode workspace container-grant`". Profile names are + operator-chosen identifiers that the command tool already lists to the + model ([ADR-0100](0100-list-the-recorded-toolchain-profiles-in-the-command-tool.md)). + A workspace-folder refusal says the recorded grant may have been changed + outside OMGCode and should be revoked and granted again. The command + tool's result code stays `command_failed`. +4. **The trusted CLI also shows the path.** `run` keeps the same `message` + and adds `refused_path` beside it, with the role, `needed`, `granted`, and + the path as `path` (when it is valid Unicode), `path_display`, and + `path_native`, as the CLI already reports journal paths. + +## Alternatives considered + +- **Put the path in the message.** This is the most direct fix for the + operator, but the same text is the model's tool result and goes to the + provider automatically. A program that runs can print host paths in its + output; that is the program's output, which the operator chose to run. A + refusal is core's own text, written before anything runs. +- **Keep the path out of the model text but not record the reason.** Without + a role the model still cannot tell the operator what to grant, and the + operator has to repeat the access-control-list check by hand. +- **Record the reason in the run journal.** It would let the desktop's + processes tab show it, but it changes a validated journal record, which + older builds would then refuse to read. The role and position already lead + to the folder in the settings window. +- **Report the list index only.** Indexes depend on how each platform builds + the lists, and the operator never sees those lists. +- **Say whether this account can apply the grant**, as toolchain discovery + does ([ADR-0103](0103-generate-toolchain-profiles-from-installed-toolchains.md)). + It would add another access check after a refusal for a case the settings + window's grant already reports. Not done now. + +## Consequences + +- A model that relays a refused run can tell the operator which root of + which profile to grant, at which level, and where. +- An operator on the CLI gets the path itself. An operator in the desktop + finds it from the profile and position in the settings window; the + transcript does not show it. +- The model and the provider do not receive the host path from a refusal. + This is not a general rule that model-visible text never contains host + paths: command output still can. +- Windows platform tests check the reported entry, path, and levels for an + ungranted read-only path, a read-execute grant listed as read-write, and + an ungranted program, and that the error text leaves the path out. Core + tests check every role's text for the access and where to grant, and that + no path component appears. Windows CLI tests check a real ungranted + profile root and package cache root end to end, with real grants on + temporary folders. + +## References + +- [ADR-0029](0029-confine-windows-runs-in-a-workspace-appcontainer-with-recorded-grants.md), + [ADR-0100](0100-list-the-recorded-toolchain-profiles-in-the-command-tool.md), + [ADR-0103](0103-generate-toolchain-profiles-from-installed-toolchains.md), + [ADR-0104](0104-grant-the-workspace-folder-read-write-without-a-folder-dialog.md) +- [docs/execution.md](../execution.md#environment-and-confinement) diff --git a/docs/adr/index.md b/docs/adr/index.md index d8dca277..1ebe2022 100644 --- a/docs/adr/index.md +++ b/docs/adr/index.md @@ -120,3 +120,4 @@ meaningful alternative does not need an ADR. | [0103: Generate toolchain profiles from installed toolchains](0103-generate-toolchain-profiles-from-installed-toolchains.md) | Accepted | 2026-11-26 | | [0104: Grant the workspace folder read-write without a folder dialog](0104-grant-the-workspace-folder-read-write-without-a-folder-dialog.md) | Accepted | 2026-11-26 | | [0105: Show the approvals window when a turn starts waiting](0105-show-the-approvals-window-when-a-turn-starts-waiting.md) | Accepted | 2026-11-26 | +| [0106: Name the ungranted run path by its role](0106-name-the-ungranted-run-path-by-its-role.md) | Accepted | 2026-11-26 | diff --git a/docs/execution.md b/docs/execution.md index 752a10df..f87aaf41 100644 --- a/docs/execution.md +++ b/docs/execution.md @@ -568,6 +568,23 @@ Linux runs use `PairsOnly` sockets unless host services were selected. Runs have no IP networking unless `--network` was passed. Windows roots that every application package can read, such as `Program Files`, need no grant; others need a read-execute [container grant](#container-grants). +A folder under the user's own profile, such as a rustup toolchain or +`%USERPROFILE%\.cargo`, is never readable by every package, so it always +needs a grant. + +On Windows the runner checks each listed path, then the resolved program, +against its live access-control list before anything starts. When the +container lacks the access a path needs, the run is recorded as +`not_started` and fails with a refusal that names the path's role and the +access: root N of the named toolchain profile (numbered from 1 in the order +`profile-show` and the `settings` window list them), the workspace's package +cache root, the workspace folder, or the program file. The refusal says what +access the container has and where to grant it. It never includes the path, +because the model's command tool returns the same text and a path under the +user's folder can name the account. The trusted CLI's `run` error adds +`refused_path` with the role, `needed`, `granted`, and the path as `path`, +`path_display`, and `path_native` (ADR-0106). A DACL that cannot be read is +still reported as a confinement rule that could not be prepared. `SIGINT` and `SIGTERM` on Linux, and Ctrl+C and Ctrl+Break on Windows, cancel the run. The tree is terminated and the outcome is recorded as `cancelled`. diff --git a/docs/testing-standards.md b/docs/testing-standards.md index 94ce962c..e33819ac 100644 --- a/docs/testing-standards.md +++ b/docs/testing-standards.md @@ -223,7 +223,7 @@ As the relevant components are implemented, include: | Context compaction | Conservative accounting, effective trigger below/at/above, manual and pre-turn auto-compaction, schema-v3 event, summary trust label, latest-turn and tool-pair retention, chunk and depth limits, chunks that fit the full summarizer request, input-only estimates, the history-message limit, no-progress refusal for non-reducing summaries, token redaction, and original-journal retention. Saved tool results are withheld from the summarizer when either `model_tools` or `read` is disabled, a derived summary is withheld after either is revoked, and a withdrawal between summarizer requests stops before the next one | | Process-tree runner | Exit codes, exact environment, argument quoting, bounded output, deadline, cancellation, descendant escape attempts, inherited handles, observed cleanup, cancellable disk sampling, bounded traversal queues, real scan errors preserved during shutdown, invalid specifications | | Linux confinement | Read-only and read-write rules, path truncation, denied host files and directories, inheritance by descendants, IP and `io_uring` denial in both Unix-socket modes, Unix-socket and datagram-pair denial in `PairsOnly`, host Unix-socket connection, workspace socket binding, and datagram pairs in `HostServices`, unexecutable programs, missing/link/special confinement paths, ABI selection below and above the minimum | -| Windows confinement | Granted read-only and read-write paths, denied host files, directories, named pipe, and loopback TCP, a writable container temporary directory, inheritance by descendants, the same probes unconfined, missing, weaker, and foreign grants, a missing profile, `LOCALAPPDATA`, or container name, refused `HostServices`, an ungranted program | +| Windows confinement | Granted read-only and read-write paths, denied host files, directories, named pipe, and loopback TCP, a writable container temporary directory, inheritance by descendants, the same probes unconfined, missing, weaker, and foreign grants, a missing profile, `LOCALAPPDATA`, or container name, refused `HostServices`, an ungranted program, the refused entry, path, and levels reported without the path in the error text, and, through the CLI, an ungranted profile root and package cache root named by role with the path only in `refused_path` (ADR-0106) | | Container grants | SID derivation, propagation to existing and new children, exact read-back, protection state kept, junctions not followed, hard-link reach, refused replaced/junction/file/relative paths, profile creation and deletion, journal intent and outcome order, replay validation, revision rules, scope refusals, pending and revoking recovery, the revocation reserve, CLI grant/list/revoke, refusal off Windows | | Model tool chat | Preference off by default and rechecked per call, settings compatibility, confinement against parent, absolute, rooted, UNC, link, junction, and hard-link paths, strict provider tool-call parsing, token removal before journal and model, refusal of token-bearing calls, withheld replay after revocation, finish reason, one call per turn in escape cases | | Model command tool | Strict profile/program/argument/cwd parsing, tool advertised only with live model-tools/execute/read/write and a profile recorded for the platform, the recorded profiles listed in order, an unrecorded profile refused with `profile_not_recorded` before any approval and recorded as refused, a profile declared on the other platform neither offered nor accepted, and a refusal with no recorded profile not asking for a name (ADR-0100), first call records a pending approval and starts nothing, denial, approval consumption, exact digest and binding, settings-revision invalidation, run hand-off failure, output bounds, no replay, and a durable `model_tools` revocation count that stops a model-origin run even after re-enable. An end-to-end CLI case drives the real chat process, a mock provider, an operator approval, and the trusted runner to a successful confined command on both hosts | From c4eb5579f445bd77bc966bbc2c4b8b354d300d34 Mon Sep 17 00:00:00 2001 From: James Chapman Date: Fri, 27 Nov 2026 00:55:03 +0000 Subject: [PATCH 2/5] feat: assign toolchain profiles to workspaces and grant on assignment (ADR-0107) Toolchain profiles are now assigned per workspace, and a workspace runs only the profiles assigned to it. Assigning one, through the trusted CLI `workspace profile-assign` or a switch on the workspace's settings page, is the operator's consent: on Windows it grants the workspace's AppContainer read and execute on the profile's folders that this account can change, after a confirmation that names them. Registering a workspace grants its folder read and write. Unassigning, removing a profile, or unregistering revokes the grants no longer needed and stops the runs they withdraw. Core records profile_assigned and profile_unassigned events with replay validation; an assignment re-plans under the lock and refuses a changed plan. The command tool lists only assigned profiles (tool schema 0.10.0). Discovery's add with a workspace also assigns, and the separate settings_grant_discovered_roots command is removed. Existing profiles start assigned to no workspace. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 31 +- CHANGELOG.md | 38 + crates/omgcode-app/src/desktop.rs | 8 +- crates/omgcode-app/src/desktop/settings.rs | 12 + .../src/desktop/settings_changes.rs | 303 +++++-- .../src/desktop/settings_discovery.rs | 427 +++------- .../src/desktop/settings_execution.rs | 319 ++++++- crates/omgcode-app/src/desktop/wire.rs | 6 + crates/omgcode-app/tests/common/mod.rs | 54 +- .../tests/desktop_settings_changes.rs | 78 +- .../tests/desktop_settings_discovery.rs | 187 +++-- .../tests/desktop_settings_execution.rs | 257 +++++- crates/omgcode-cli/src/control_cli.rs | 219 ++++- crates/omgcode-cli/tests/control_workflow.rs | 213 +++-- crates/omgcode-cli/tests/file_workflow.rs | 28 +- .../tests/package_credential_workflow.rs | 16 +- crates/omgcode-cli/tests/packages_workflow.rs | 18 +- crates/omgcode-cli/tests/run_workflow.rs | 209 ++++- crates/omgcode-cli/tests/skills_workflow.rs | 17 +- crates/omgcode-cli/tests/support/mod.rs | 64 ++ crates/omgcode-cli/tests/support/run_scene.rs | 157 +++- crates/omgcode-core/src/control.rs | 38 +- crates/omgcode-core/src/control/assignment.rs | 785 ++++++++++++++++++ .../src/control/assignment/tests.rs | 453 ++++++++++ crates/omgcode-core/src/control/profile.rs | 4 + crates/omgcode-core/src/run.rs | 106 +++ crates/omgcode-core/src/turn.rs | 69 +- crates/omgcode-core/tests/approval_review.rs | 3 + crates/omgcode-core/tests/turn_runtime.rs | 65 +- crates/omgcode-core/tests/web_fetch_tool.rs | 11 +- .../capabilities/settings.json | 3 +- crates/omgcode-desktop/src/command_names.rs | 3 +- .../omgcode-desktop/src/commands/settings.rs | 102 ++- crates/omgcode-desktop/src/lib.rs | 3 +- crates/omgcode-desktop/src/policy.rs | 22 +- crates/omgcode-desktop/tests/layers.rs | 21 +- .../ui/src/ipc/settings_client.ts | 20 +- crates/omgcode-desktop/ui/src/ipc/types.ts | 10 + crates/omgcode-desktop/ui/src/mock/backend.ts | 152 +++- crates/omgcode-desktop/ui/src/settings/app.ts | 6 +- .../ui/src/settings/context.ts | 15 +- .../ui/src/settings/discovery_panel.ts | 58 +- .../ui/src/settings/execution_forms.ts | 2 +- .../ui/src/settings/workspace_profiles.ts | 84 ++ .../ui/src/settings/workspaces_section.ts | 4 + crates/omgcode-desktop/ui/tests/dist.test.ts | 8 +- .../ui/tests/settings_discovery.test.ts | 113 ++- .../ui/tests/settings_execution.test.ts | 54 ++ .../ui/tests/settings_sections.test.ts | 111 +++ .../ui/tests/settings_skills.test.ts | 2 + .../ui/tests/settings_window.test.ts | 2 + ...s-to-workspaces-and-grant-on-assignment.md | 169 ++++ docs/adr/index.md | 1 + docs/desktop-interface.md | 146 ++-- docs/execution.md | 132 ++- docs/testing-standards.md | 11 +- docs/workspace-permissions.md | 61 +- 57 files changed, 4500 insertions(+), 1010 deletions(-) create mode 100644 crates/omgcode-core/src/control/assignment.rs create mode 100644 crates/omgcode-core/src/control/assignment/tests.rs create mode 100644 crates/omgcode-desktop/ui/src/settings/workspace_profiles.ts create mode 100644 docs/adr/0107-assign-toolchain-profiles-to-workspaces-and-grant-on-assignment.md diff --git a/AGENTS.md b/AGENTS.md index f6132b42..ab1fb414 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -43,11 +43,20 @@ the clipboard only, with icon buttons named in their tooltips Chat offers the session's model read and list tools; when the workspace also enables `read` and `write`, six file-write tools (exact edit, multi-edit, create, rename, delete, and directory creation); and, when it also enables `execute`, `read`, and -`write` and at least one toolchain profile is recorded for the running -platform, one command tool whose `profile` parameter lists those profiles. A -command that names another profile is answered with `profile_not_recorded` -before any approval is requested +`write` and at least one toolchain profile of the running platform is +assigned to the workspace, one command tool whose `profile` parameter lists +those profiles. A command that names another profile is answered with +`profile_not_recorded` before any approval is requested ([ADR-0100](docs/adr/0100-list-the-recorded-toolchain-profiles-in-the-command-tool.md)). +A workspace runs only the profiles assigned to it, through the trusted CLI +`workspace profile-assign` or a switch on its page in the `settings` window. +On Windows assigning is the operator's consent to grant the workspace's +AppContainer read and execute on the profile's folders that this account can +change, after a confirmation that names them; registering a workspace grants +its folder read and write; and unassigning, removing a profile, or +unregistering revokes the grants no longer needed. Existing profiles start +assigned to no workspace +([ADR-0107](docs/adr/0107-assign-toolchain-profiles-to-workspaces-and-grant-on-assignment.md)). Each workspace preference except `model_tools` is `deny`, `prompt`, or `allow`, and each file-write tool has a limit that can only narrow `write` ([ADR-0063](docs/adr/0063-deny-prompt-or-allow-each-preference-wait-for-approvals-in-the-turn-and-journal-model-actions.md)). @@ -181,8 +190,9 @@ skills for one turn ([ADR-0059](docs/adr/0059-configure-trusted-settings-in-an-i The `settings` window changes the development root, workspace registrations, workspace preferences, and package cache roots, and lists workspaces under **Workspaces** in its navigation. It can unregister a workspace, which keeps -its folder, files, and sessions and is refused while a container grant names -it ([ADR-0081](docs/adr/0081-unregister-a-workspace.md)). Rust opens a native folder +its folder, files, and sessions, revokes its container grants first, and +stays registered if one cannot be revoked +([ADR-0081](docs/adr/0081-unregister-a-workspace.md), ADR-0107). Rust opens a native folder dialog for each folder and a native confirmation before each change that widens access, and creates an empty settings store on first use ([ADR-0060](docs/adr/0060-change-workspace-settings-from-the-desktop-with-native-dialogs.md)). @@ -234,10 +244,11 @@ reads install folders, the operator's `PATH`, and installer-written files, runs no program, and never reads repository configuration such as `rust-toolchain.toml`. The operator selects proposals, and one native confirmation per batch records them through the -core add call on every platform. On Windows a separate command, after its -own confirmation, grants a workspace's container the folders it needs that -this account can change; discovery grants nothing -([ADR-0103](docs/adr/0103-generate-toolchain-profiles-from-installed-toolchains.md)). +core add call on every platform. With a workspace chosen, the same +confirmation also assigns the profiles to it and, on Windows, grants its +container the folders they need that this account can change; discovery +itself grants nothing +([ADR-0103](docs/adr/0103-generate-toolchain-profiles-from-installed-toolchains.md), ADR-0107). Other credentials, apart from ChatGPT sign-in and sign-out, still change, and packages are fetched and programs run, only through the trusted CLI. The desktop shell has no working terminal, diff view, installer, or recovery interface. CI publishes unsigned archives of the newest tested merge to diff --git a/CHANGELOG.md b/CHANGELOG.md index 7d52d548..2ba82485 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -600,6 +600,44 @@ Changes are recorded here before a release version is assigned. ### Changed +- Version 0.70.0 also assigns toolchain profiles to workspaces and grants a + profile's folders when it is assigned (ADR-0107). A workspace now runs only + the profiles assigned to it: the runner refuses any other recorded profile + before anything starts, the run watcher withdraws a run whose profile is + unassigned, and the model command tool is offered only while a profile of + this platform is assigned, listing only those (tool schema 0.10.0; the + `profile_not_recorded` code is kept). Two control events, + `profile_assigned` and `profile_unassigned`, record the change, and an older + build refuses them. On Windows assigning is the consent to grant: core plans + read-execute grants for the profile's roots that the workspace's + AppContainer cannot read yet, the operator confirms the plan, and core + refuses the assignment if the plan changed, then applies the grants and + records the assignment last. Folders that need an administrator, or whose + access could not be read, are listed and not granted. Registering a + workspace grants its container read-write on its folder, and registering an + existing folder again grants it if that grant is missing. Unassigning or + removing a profile revokes the workspace's read-execute grants on its roots + that no other assigned profile lists, never the workspace folder's grant or + the package cache root's. Unregistering revokes every grant of the + workspace first and leaves it registered if a revocation fails. Each caller + waits only for the runs of the workspaces whose grants it revoked. The + trusted CLI adds `workspace profile-assign` and `workspace + profile-unassign`, and `register`, `unregister`, and `profile-remove` report + what they granted or revoked. The desktop `settings` window shows one + switch per profile on each workspace page, through + `settings_assign_toolchain_profile` and + `settings_unassign_toolchain_profile`, each after a native confirmation that + names the folders it grants or the grants it revokes. Adding discovered + profiles with a workspace chosen also assigns them in the same + confirmation, the workspace choice is shown on every platform, and + `settings_grant_discovered_roots` is removed, so the `settings` window has + 33 commands and the shell 67. Existing profiles start assigned to no + workspace: assign each workspace's profiles once. On Windows a profile whose + folders are already granted grants nothing new. Granting at run time was + drafted and dropped before it was committed. Windows CLI and desktop + service tests apply and revoke real grants on temporary folders; the + desktop shell's native dialogs were not driven. + - Version 0.70.0 makes a Windows run refused for a missing container grant say which grant is missing (ADR-0106). The refusal used to be one fixed sentence, "a confinement path is not granted to the container at its diff --git a/crates/omgcode-app/src/desktop.rs b/crates/omgcode-app/src/desktop.rs index 2510960f..361a8a9e 100644 --- a/crates/omgcode-app/src/desktop.rs +++ b/crates/omgcode-app/src/desktop.rs @@ -133,13 +133,13 @@ pub use self::processes::{ use self::review_tokens::ReviewTokens; pub use self::settings_changes::{Confirmation, FolderPurpose, SettingsPrompt}; pub use self::settings_discovery::{ - DiscoveredGrantsRequest, DiscoveredProfilesRequest, MAX_SELECTED_PROPOSALS, ProposedRootView, - ProposedVariableView, ToolchainDiscovery, ToolchainDiscoveryRequest, ToolchainProposalView, - discovery_host, + DiscoveredProfilesRequest, MAX_SELECTED_PROPOSALS, ProposedRootView, ProposedVariableView, + ToolchainDiscovery, ToolchainDiscoveryRequest, ToolchainProposalView, discovery_host, }; pub use self::settings_execution::{ ContainerAccessChoice, ContainerGrantRequest, ContainerRevokeRequest, EnvironmentEntry, - PackageProfileAddRequest, ProfileRemoveRequest, ToolchainProfileAddRequest, + PackageProfileAddRequest, ProfileAssignmentRequest, ProfileRemoveRequest, + ToolchainProfileAddRequest, }; pub use self::settings_skills::{SkillChoice, SkillRemoveRequest, SkillStateRequest}; pub use self::settings_web_hosts::WebHostChangeRequest; diff --git a/crates/omgcode-app/src/desktop/settings.rs b/crates/omgcode-app/src/desktop/settings.rs index bbd257c1..51734e9b 100644 --- a/crates/omgcode-app/src/desktop/settings.rs +++ b/crates/omgcode-app/src/desktop/settings.rs @@ -102,6 +102,17 @@ pub(super) fn overview_of(inner: &Inner, store: ControlStore) -> SettingsOvervie .map(|pattern| display_safe_line(pattern.as_str())) .collect(), write_tools: permissions.write_tools, + profiles: store + .assigned_profiles(workspace.id()) + .iter() + .filter_map(|id| { + store + .profiles() + .iter() + .find(|status| status.profile().id() == *id) + .map(|status| status.profile().name().to_owned()) + }) + .collect(), package_cache_root: store.package_cache_root_display(workspace.id()), instructions: workspace_instructions_view( &inner.data_root, @@ -203,6 +214,7 @@ pub(super) fn overview_of(inner: &Inner, store: ControlStore) -> SettingsOvervie connection, provider_profiles, toolchain_profiles, + profile_platform: ProfilePlatform::current().map(platform_name), package_profiles, container_grants, container_grants_supported: omgcode_core::control::CONTAINER_GRANTS_SUPPORTED, diff --git a/crates/omgcode-app/src/desktop/settings_changes.rs b/crates/omgcode-app/src/desktop/settings_changes.rs index 71e55171..e51ed180 100644 --- a/crates/omgcode-app/src/desktop/settings_changes.rs +++ b/crates/omgcode-app/src/desktop/settings_changes.rs @@ -44,11 +44,11 @@ use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, Ordering}; use omgcode_core::control::{ - ControlError, ControlStore, CredentialId, CredentialStore, MAX_PROVIDER_ENDPOINT_BYTES, - ProviderAuth, ProviderCredentialError, ProviderKind, ProviderProfileDeclaration, - delete_unbound_credential, + CONTAINER_GRANTS_SUPPORTED, ControlError, ControlStore, CredentialId, CredentialStore, + MAX_PROVIDER_ENDPOINT_BYTES, ProviderAuth, ProviderCredentialError, ProviderKind, + ProviderProfileDeclaration, Revocations, delete_unbound_credential, }; -use omgcode_core::policy::{Access, PermissionSet, WriteTool}; +use omgcode_core::policy::{Access, PermissionSet, WorkspaceId, WriteTool}; use omgcode_core::provider::ModelEndpoint; use omgcode_core::run::{self, REVOCATION_WAIT}; use omgcode_core::turn::display_safe_line; @@ -607,13 +607,18 @@ impl DesktopService { /// `settings` only. Ask the operator for a folder below the development /// root and, after a native confirmation, register it as a workspace with - /// the default preferences. Registering a folder again reuses its - /// identifier and changes nothing. + /// the default preferences, as `omgcode workspace register` does. On + /// Windows the same consent grants the workspace's container read and + /// write on the folder when this account can change its access list + /// (ADR-0107). Registering a folder again reuses its identifier and + /// grants the folder only if that grant is missing. /// /// # Errors /// - /// `no_development_root` before any dialog when no root is set; otherwise - /// as [`settings_choose_root`](Self::settings_choose_root). + /// `no_development_root` before any dialog when no root is set; + /// `workspace_grant_failed` when the workspace was registered but its + /// folder was not granted; otherwise as + /// [`settings_choose_root`](Self::settings_choose_root). pub fn settings_register_workspace( &self, request: SettingsRevisionRequest, @@ -640,19 +645,19 @@ impl DesktopService { .collect(); confirm( prompt, - &Confirmation { - title: "Register a workspace", - message: format!( - "Register this folder as a workspace?\n\n{}\n\nA new workspace starts with {} on and everything else off.", - shown(&folder), - on.join(" and ") - ), - }, + ®ister_confirmation(&shown(&folder), &on.join(" and ")), )?; - self.apply(|store| { - store - .register_workspace(&folder, request.revision) - .map(drop) + self.apply_reporting(|store| { + let registered = store + .register_workspace_with_access(&folder, request.revision) + .map_err(|error| DesktopError::from_control(&error))?; + Ok(( + AlsoWithdrawn::default(), + registered + .grant + .err() + .map(|error| DesktopError::workspace_grant_failed(&error)), + )) }) } @@ -755,23 +760,27 @@ impl DesktopService { /// confirmation that names its folder and lists what is removed /// (ADR-0081). /// - /// One settings event drops the registration, its preferences, its - /// package cache root selection, its skill overrides, and its checkpoint - /// folder record. The workspace's instructions file is then deleted under - /// the preferences lock, so no later turn sends its text. The folder, its - /// `.OMGCode` folder, cached packages, and the sessions recorded in the - /// workspace are not touched. Registering the folder again assigns a new - /// identifier, so those sessions stay in the journals and chat without - /// tools. + /// Every container grant of the workspace is revoked first, as `omgcode + /// workspace unregister` does (ADR-0107). When one cannot be revoked, the + /// workspace stays registered with the grants not yet revoked, and the + /// error says so. Then one settings event drops the registration, its + /// preferences, its profile assignments, its package cache root + /// selection, its skill overrides, and its checkpoint folder record. The + /// workspace's instructions file is then deleted under the preferences + /// lock, so no later turn sends its text. The folder, its `.OMGCode` + /// folder, cached packages, and the sessions recorded in the workspace are + /// not touched. Registering the folder again assigns a new identifier, so + /// those sessions stay in the journals and chat without tools. /// /// # Errors /// /// `unknown_workspace`; `turn_running` while a chat turn runs in a session /// of the workspace (checked before the dialog and again before the - /// change); `control` with core's refusal while a container grant names - /// the workspace; `instructions_orphaned` when the workspace was removed - /// and its withdrawn runs were stopped, but its instructions file could - /// not be deleted; otherwise as + /// change); `container_access_failed` or `revocation_incomplete` when a + /// grant was not revoked, so the workspace stays registered; + /// `instructions_orphaned` when the workspace was removed and its + /// withdrawn runs were stopped, but its instructions file could not be + /// deleted; otherwise as /// [`settings_choose_root`](Self::settings_choose_root). pub fn settings_unregister_workspace( &self, @@ -779,30 +788,26 @@ impl DesktopService { prompt: &dyn SettingsPrompt, ) -> Result { let _guard = ChangeGuard::take(&self.inner.settings_change)?; - let (workspace_id, workspace_folder) = { + let (workspace_id, workspace_folder, grants) = { let store = self.inner.open_or_create_control()?; check_revision(&store, request.revision)?; let workspace = store .registered_workspace(request.workspace_id) .ok_or_else(DesktopError::unknown_workspace)?; - store - .check_removable(workspace.id()) - .map_err(|error| DesktopError::from_control(&error))?; + let grants = store + .container_grants() + .iter() + .filter(|status| status.grant().workspace_id() == workspace.id()) + .map(|status| display_safe_line(&status.grant().directory_display())) + .collect::>(); ( workspace.id(), folder_of_directory(workspace.directory_path()), + grants, ) }; self.refuse_running_turns(request.workspace_id)?; - confirm( - prompt, - &Confirmation { - title: "Remove a workspace", - message: format!( - "Remove this workspace?\n\n{workspace_folder}\n\nIts preferences, instructions, package cache selection, skill overrides, and checkpoint record are removed from OMGCode. The folder and its files are not touched, and its checkpoints stay in its .OMGCode folder. Its sessions stay, and can chat without tools only. Registering the folder again makes a new workspace with the default preferences." - ), - }, - )?; + confirm(prompt, &unregister_confirmation(&workspace_folder, &grants))?; // The dialog can stay open for a long time, so a turn started meanwhile // is found here. A turn that starts after this check stops using tools, // because every tool call checks the live settings. @@ -810,28 +815,39 @@ impl DesktopService { // The preferences lock comes first, as in every other save that also // reads settings, so the removal of the instructions file never // overlaps a save or a turn's read of it. - let (listed, removed) = { + let (listed, before, revocations, removed) = { let _lock = self .inner .preferences .lock() .map_err(|_| DesktopError::poisoned())?; let mut store = self.inner.open_or_create_control()?; - store - .unregister_workspace(workspace_id, request.revision) + // A revocation withdraws every run of the workspace, which the + // settings no longer show once it is unregistered, so its runs + // are listed before the change. + let before = run::pending_runs(&store); + let revocations = store + .unregister_workspace_with_access(workspace_id, request.revision) .map_err(|error| DesktopError::from_control(&error))?; - // The removal is recorded, so the runs it withdraws are listed + // The change is recorded, so the runs it withdraws are listed // before anything else can fail, and are stopped and waited for // even when the file below cannot be deleted. let listed = run::withdrawn_runs(&store); - let removed = instructions::remove(&self.inner.data_root, *workspace_id.as_uuid()); - (listed, removed) + let removed = revocations + .failure + .is_none() + .then(|| instructions::remove(&self.inner.data_root, *workspace_id.as_uuid())); + (listed, before, revocations, removed) }; - // A run that was not stopped is reported first; a remaining - // instructions file is never sent, because the workspace is no longer - // registered. - let overview = self.finish_change(listed, AlsoWithdrawn::default())?; - removed.map_err(|_| DesktopError::removed_instructions_orphaned())?; + // A grant that was not revoked, then a run that was not stopped, is + // reported first; a remaining instructions file is never sent, + // because the workspace is no longer registered. + let (also, deferred) = + revocation_outcome(before, &revocations, RevokingChange::Unregistration); + let overview = self.finish_reporting(listed, also, deferred)?; + if let Some(Err(_)) = removed { + return Err(DesktopError::removed_instructions_orphaned()); + } Ok(overview) } @@ -1390,12 +1406,47 @@ impl DesktopService { &self, change: impl FnOnce(&mut ControlStore) -> Result, ) -> Result { - let (listed, also) = { + self.apply_reporting(|store| change(store).map(|also| (also, None))) + } + + /// As [`apply_checked_also`](Self::apply_checked_also), for a change that + /// was recorded but did not finish everything it set out to do, such as + /// an unassignment whose grant could not be revoked (ADR-0107). The + /// runs are waited for first, because the recorded part of the change + /// can have withdrawn them; the deferred error is returned afterwards, + /// with any wait failure added to its message. + pub(super) fn apply_reporting( + &self, + change: impl FnOnce( + &mut ControlStore, + ) -> Result<(AlsoWithdrawn, Option), DesktopError>, + ) -> Result { + let (listed, also, deferred) = { let mut store = self.inner.open_or_create_control()?; - let also = change(&mut store)?; - (run::withdrawn_runs(&store), also) + let (also, deferred) = change(&mut store)?; + (run::withdrawn_runs(&store), also, deferred) }; - self.finish_change(listed, also) + self.finish_reporting(listed, also, deferred) + } + + /// [`finish_change`](Self::finish_change), then `deferred`, the error of + /// a change that was recorded but not finished, with any wait failure + /// added to its message. + fn finish_reporting( + &self, + listed: Result, run::RunError>, + also: AlsoWithdrawn, + deferred: Option, + ) -> Result { + let finished = self.finish_change(listed, also); + match (deferred, finished) { + (None, finished) => finished, + (Some(error), Ok(_)) => Err(error), + (Some(error), Err(wait)) => Err(DesktopError::execution( + error.code(), + format!("{} {}", error.message(), wait.message()), + )), + } } /// After a recorded change: wait for the runs it withdrew, the runs in @@ -1433,6 +1484,138 @@ pub(super) struct AlsoWithdrawn { pub unchecked: bool, } +/// Which operator change revoked grants, which decides what a failed +/// revocation left. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum RevokingChange { + /// An unassignment or a profile removal, recorded before its revocations. + Recorded, + /// An unregistration, recorded only after every grant was revoked, so a + /// failed revocation leaves the workspace registered. + Unregistration, +} + +/// What a change that revoked grants leaves to wait for and report. +/// +/// Revoking any grant withdraws every run of its workspace. `before` holds +/// every pending run, listed by `run::pending_runs` under the lock before the +/// change; only the runs of a workspace whose grant the change tried to revoke +/// are waited for, because a run that is not withdrawn would be reported as +/// not stopped. A revocation that failed is reported after the wait, because +/// the revocations before it stand. +pub(super) fn revocation_outcome( + before: Result, run::RunError>, + revocations: &Revocations, + change: RevokingChange, +) -> (AlsoWithdrawn, Option) { + let attempted = !revocations.workspaces.is_empty(); + let also = match (attempted, before) { + (false, _) => AlsoWithdrawn::default(), + (true, Ok(runs)) => AlsoWithdrawn { + runs: revocations.withdrawn_runs(&runs), + unchecked: false, + }, + (true, Err(_)) => AlsoWithdrawn { + runs: Vec::new(), + unchecked: true, + }, + }; + let deferred = revocations + .failure + .as_ref() + .map(|(_, error)| DesktopError::revocation_incomplete(error, change)); + (also, deferred) +} + +/// The native confirmation for registering `folder`. On Windows it also asks +/// for the read-write grant registration applies (ADR-0107). +fn register_confirmation(folder: &str, on: &str) -> Confirmation { + let sandbox = if CONTAINER_GRANTS_SUPPORTED { + "\n\nOMGCode runs the workspace's commands in its own AppContainer, a Windows sandbox that starts with no access to your files. Registering also lets that sandbox read and write this folder and everything beneath it, by adding it to the folder's access-control list on disk, when this account can change that list. The access stays until you revoke it or remove the workspace." + } else { + "" + }; + Confirmation { + title: "Register a workspace", + message: format!( + "Register this folder as a workspace?\n\n{folder}\n\nA new workspace starts with {on} on and everything else off.{sandbox}" + ), + } +} + +/// The native confirmation for removing a workspace whose container grants +/// are on `grants`, display-safe. +fn unregister_confirmation(workspace_folder: &str, grants: &[String]) -> Confirmation { + let revoked = if grants.is_empty() { + String::new() + } else { + format!( + "\n\nFirst, the workspace's AppContainer, the Windows sandbox its commands run in, is removed from the access-control list of each folder it was granted, and its runs are stopped:\n{}\nIf a folder's list cannot be changed, the workspace stays registered.", + grants + .iter() + .map(|grant| format!(" {grant}")) + .collect::>() + .join("\n") + ) + }; + Confirmation { + title: "Remove a workspace", + message: format!( + "Remove this workspace?\n\n{workspace_folder}{revoked}\n\nIts preferences, toolchain profile assignments, instructions, package cache selection, skill overrides, and checkpoint record are removed from OMGCode. The folder and its files are not touched, and its checkpoints stay in its .OMGCode folder. Its sessions stay, and can chat without tools only. Registering the folder again makes a new workspace with the default preferences." + ), + } +} + +impl DesktopError { + /// The workspace was registered, but its container was not granted its + /// folder. The operating system's own text is never shown. + fn workspace_grant_failed(error: &ControlError) -> Self { + let reason = match error { + ControlError::Container(_) => { + "its folder's access list could not be changed or read back".to_owned() + } + other => Self::from_control(other).message().to_owned(), + }; + Self::execution( + "workspace_grant_failed", + format!( + "The workspace was registered, but its sandbox was not granted its folder: {reason}. Grant the folder read and write under Container grants, or revoke a pending grant and grant it again." + ), + ) + } + + /// A grant the change should have revoked was not. After a recorded + /// change the change stands; after an unregistration the workspace stays + /// registered. The operating system's own text is never shown. + pub(super) fn revocation_incomplete(error: &ControlError, change: RevokingChange) -> Self { + let (outcome, then) = match change { + RevokingChange::Recorded => ( + "The change was recorded, but a container grant it releases", + "", + ), + RevokingChange::Unregistration => ( + "The workspace stays registered, because one of its container grants", + " Then remove the workspace again.", + ), + }; + match error { + ControlError::Container(_) => Self::execution( + "container_access_failed", + format!( + "{outcome} could not be removed from its folder's access list. The grant stays revoking; the settings list it, and Revoke tries again.{then}" + ), + ), + other => Self::execution( + "revocation_incomplete", + format!( + "{outcome} was not revoked: {}. The settings list the grant, and Revoke tries again.{then}", + Self::from_control(other).message() + ), + ), + } + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/omgcode-app/src/desktop/settings_discovery.rs b/crates/omgcode-app/src/desktop/settings_discovery.rs index 7fa4c571..d06ab436 100644 --- a/crates/omgcode-app/src/desktop/settings_discovery.rs +++ b/crates/omgcode-app/src/desktop/settings_discovery.rs @@ -1,5 +1,5 @@ -//! Toolchain profiles and container grants generated from the toolchains -//! installed on this computer, for the `settings` window (ADR-0103). +//! Toolchain profiles generated from the toolchains installed on this +//! computer, for the `settings` window (ADR-0103, ADR-0107). //! //! Discovery is core's trusted host-side service //! ([`omgcode_core::toolchain_discovery`]): it reads folders and a few small @@ -12,40 +12,45 @@ //! from an outdated list is refused as `discovery_changed`. //! - Each proposal is checked with core's [`ControlStore::check_profile`], //! and its refusal reason is shown; nothing is recorded by a check. -//! - Adding profiles calls [`ControlStore::add_profile`], and granting -//! folders calls [`ControlStore::grant_container_access`], with the same -//! validation and events as the CLI and the hand-entered forms (ADR-0088). -//! Each batch is applied after one native confirmation that lists every -//! profile's roots, `PATH` entries, and variables, or every folder, and -//! uses the revision the operator confirmed, advancing it once per record. +//! - Adding profiles calls [`ControlStore::add_profile`] with the same +//! validation and events as the CLI and the hand-entered form (ADR-0088). +//! With a workspace chosen, the same batch then assigns them to it through +//! [`ControlStore::assign_profiles_with_access`], as `omgcode workspace +//! profile-assign` does. On Windows that grants the workspace's container +//! read and execute on each root it cannot read yet and this account can +//! change; the confirmation names each one, and each one left out because +//! it needs an administrator or its access could not be read. Every folder +//! to grant is checked with core's grant rules +//! ([`ControlStore::check_container_grants`]) before the dialog, and core +//! refuses the assignment when the folders changed after it was shown. +//! - The batch is applied after one native confirmation that lists every +//! profile's roots, `PATH` entries, and variables, and every folder to +//! grant, and uses the revision the operator confirmed, advancing it once +//! per record. //! - Unlike the hand-entered form, the confirmation shows variable values: //! discovery derived them from installation paths, the operator typed none //! of them, and none is a secret. Each is cut to a bounded length. -//! - On Windows the proposals say, for one selected workspace, which roots -//! its container can already read, which need a read-execute grant, and -//! which need administrator rights to grant. Only folders whose -//! access-control list this account can change are offered, so a folder -//! only an administrator can change is never recorded as a grant. A -//! recorded grant can still stay `pending` when its access list cannot be -//! changed afterwards; the command then reports `container_access_failed`, -//! and the operator revokes the grant. A folder whose access-control list -//! cannot be read is named and skipped, and every folder to grant is -//! checked with core's grant rules -//! ([`ControlStore::check_container_grants`]) before the dialog. -//! - Access-control lists are read while the settings store is closed. +//! - On Windows the proposals say, for the chosen workspace, which roots its +//! container can already read, which need a read-execute grant, and which +//! need administrator rights to grant. A recorded grant can still stay +//! `pending` when its access list cannot be changed afterwards; the command +//! then reports `container_access_failed`, and the operator revokes it. +//! - Discovery and the listing's access-control reads run while the settings +//! store is closed. Planning an assignment reads them under the store, as +//! the CLI does, so the plan and the settings it checks are one state. //! //! As for every settings change, the store is released before a dialog. //! //! [`ControlStore::check_profile`]: omgcode_core::control::ControlStore::check_profile //! [`ControlStore::add_profile`]: omgcode_core::control::ControlStore::add_profile -//! [`ControlStore::grant_container_access`]: omgcode_core::control::ControlStore::grant_container_access +//! [`ControlStore::assign_profiles_with_access`]: omgcode_core::control::ControlStore::assign_profiles_with_access //! [`ControlStore::check_container_grants`]: omgcode_core::control::ControlStore::check_container_grants use std::path::PathBuf; use omgcode_core::control::{ CONTAINER_GRANTS_SUPPORTED, ContainerGrantAccess, ContainerGrantState, ControlError, - ControlStore, RootGrantNeed, root_grant_need, + ControlStore, PlannedFolder, ProfileAccessPlan, RootGrantNeed, root_grant_need, }; use omgcode_core::policy::WorkspaceId; use omgcode_core::toolchain_discovery::{ @@ -61,6 +66,7 @@ use super::settings::overview_of; use super::settings_changes::{ ChangeGuard, Confirmation, SettingsPrompt, check_revision, confirm, shown, }; +use super::settings_execution::access_plan_text; use super::state::folder_of_directory; use super::wire::SettingsOverview; @@ -88,23 +94,12 @@ pub struct DiscoveredProfilesRequest { pub revision: u64, /// The digests of the selected proposals, 1 to 8. pub digests: Vec, - /// The workspace the refreshed list reports access for, as in - /// [`ToolchainDiscoveryRequest`]. + /// A registered workspace to assign the profiles to, which the + /// refreshed list also reports access for. `None` records the profiles + /// only. pub workspace_id: Option, } -/// Arguments of `settings_grant_discovered_roots`. -#[derive(Clone, Debug, Deserialize, Eq, PartialEq)] -#[serde(deny_unknown_fields)] -pub struct DiscoveredGrantsRequest { - /// The settings revision the window last read. - pub revision: u64, - /// The registered workspace whose container gets the grants. - pub workspace_id: Uuid, - /// The digests of the selected proposals, 1 to 8. - pub digests: Vec, -} - /// One proposed root and what the selected workspace's container needs to /// read it. #[derive(Clone, Debug, Eq, PartialEq, Serialize)] @@ -196,50 +191,23 @@ impl DesktopError { ) } - /// No root of the selected proposals can be granted: each is readable, - /// needs an administrator, or has an access-control list that could not - /// be read. - fn nothing_to_grant(administrator: usize, unknown: usize) -> Self { - if administrator == 0 && unknown == 0 { - return Self::execution( - "nothing_to_grant", - "The workspace's container can already read every folder these profiles need.", - ); - } - let mut reasons = Vec::new(); - let mut advice = Vec::new(); - if administrator > 0 { - reasons.push(format!( - "{administrator} folder(s) need an administrator to change their access-control lists" - )); - advice.push( - "Ask an administrator, or install a copy of the toolchain under your own profile.", - ); - } - if unknown > 0 { - reasons.push(format!( - "the access-control lists of {unknown} folder(s) could not be read" - )); - advice.push( - "Check that each folder still exists and is not a link, then generate the list again.", - ); - } + /// A batch stopped after recording some of its records. + fn partly_applied(what: &str, done: usize, total: usize, cause: &Self) -> Self { Self::execution( - "nothing_to_grant", + cause.code(), format!( - "No folder can be granted from this account: {}. {}", - reasons.join(", and "), - advice.join(" ") + "{done} of {total} {what} were recorded before this failure: {}", + cause.message() ), ) } - /// A batch stopped after recording some of its records. - fn partly_applied(what: &str, done: usize, total: usize, cause: &Self) -> Self { + /// Every profile was recorded, but the assignment to the workspace failed. + fn not_assigned(total: usize, cause: &Self) -> Self { Self::execution( cause.code(), format!( - "{done} of {total} {what} were recorded before this failure: {}", + "The {total} profile(s) were recorded but not assigned to the workspace: {} Assign them on the workspace's page.", cause.message() ), ) @@ -409,13 +377,25 @@ fn confirmation_entry(proposal: &ToolchainProposal) -> String { ) } -/// The native confirmation for adding the selected proposals. -fn add_confirmation(chosen: &[ToolchainProposal]) -> Confirmation { +/// The native confirmation for adding the selected proposals and, with +/// `assign`, the workspace folder and plan, assigning them to it. +fn add_confirmation( + chosen: &[ToolchainProposal], + assign: Option<(&str, &ProfileAccessPlan)>, +) -> Confirmation { let platform = if cfg!(windows) { "Windows" } else { "Linux" }; + let assignment = match assign { + None => "A profile grants nothing by itself: assign it to a workspace to use it there." + .to_owned(), + Some((workspace, plan)) => format!( + "The profiles are also assigned to the workspace\n{workspace}\nso its runs can select them.{}", + access_plan_text(plan), + ), + }; Confirmation { title: "Add generated toolchain profiles", message: format!( - "Add {} toolchain profile(s) for {platform}? A run that selects a profile can read and execute everything beneath its roots.\n\n{}\n\nOMGCode found these by reading folders on this computer; it ran no program. A profile grants nothing by itself: a run still needs the workspace's execute preference. Variable values are stored in plain text and shown by status.", + "Add {} toolchain profile(s) for {platform}? A run that selects a profile can read and execute everything beneath its roots.\n\n{}\n\nOMGCode found these by reading folders on this computer; it ran no program. Variable values are stored in plain text and shown by status. A run still needs the workspace's execute preference.\n\n{assignment}", chosen.len(), chosen .iter() @@ -426,44 +406,6 @@ fn add_confirmation(chosen: &[ToolchainProposal]) -> Confirmation { } } -/// The native confirmation for granting `folders` to a workspace. It also -/// names the folders that are not granted: those that need an administrator -/// and those whose access-control list could not be read. -fn grants_confirmation( - workspace: &str, - folders: &[PathBuf], - administrator: &[PathBuf], - unknown: &[PathBuf], -) -> Confirmation { - let list = |paths: &[PathBuf]| { - paths - .iter() - .map(|path| format!(" {}", shown(path))) - .collect::>() - .join("\n") - }; - let mut skipped = String::new(); - if !administrator.is_empty() { - skipped.push_str(&format!( - "\n\nThese folders also need a grant, but this account cannot change their access-control lists, so they are not granted:\n{}", - list(administrator) - )); - } - if !unknown.is_empty() { - skipped.push_str(&format!( - "\n\nOMGCode could not read the access-control lists of these folders, so they are not granted. Check that each still exists and is not a link, then generate the list again:\n{}", - list(unknown) - )); - } - Confirmation { - title: "Grant toolchain folders to a workspace", - message: format!( - "Let the commands OMGCode runs for the workspace\n{workspace}\nread and execute these folders and everything beneath them?\n{}\n\nThis adds the workspace's AppContainer, the Windows sandbox its commands run in, to each folder's access-control list on disk, and each grant stays until you revoke it.{skipped}", - list(folders) - ), - } -} - impl DesktopService { /// `settings` only. Find the toolchains installed on `host` and return a /// proposal for each, checked against the settings as they are now. @@ -485,18 +427,24 @@ impl DesktopService { /// `settings` only. After one native confirmation that lists each /// selected proposal's roots, `PATH` entries, and variables, record the /// proposals as `omgcode workspace profile-add` does, in the order - /// selected, starting at the confirmed revision. + /// selected, starting at the confirmed revision. With a workspace, the + /// same confirmation also names each folder its container is granted, and + /// the profiles are then assigned to it as `omgcode workspace + /// profile-assign` does (ADR-0107). /// /// # Errors /// /// `invalid_request` for a selection outside its bounds; /// `discovery_changed` when a selected proposal is no longer proposed; /// `unknown_workspace`, before any dialog; `control` with core's reason, - /// before any dialog, for a proposal core would refuse; `cancelled`; - /// `stale_revision`; `settings_change_running`; `busy`. A failure after - /// some profiles were recorded says how many. Once the profiles are - /// recorded, a workspace unregistered meanwhile only leaves the refreshed - /// list without container access. + /// before any dialog, for a proposal or a folder core would refuse; + /// `cancelled`; `stale_revision`; `settings_change_running`; `busy`; + /// `container_access_failed` when a grant was recorded but its access + /// list could not be changed (it stays `pending`; revoke it). A failure + /// after some profiles were recorded says how many, and a failed + /// assignment says the profiles were recorded but not assigned. Once the + /// profiles are recorded, a workspace unregistered meanwhile only leaves + /// the refreshed list without container access. pub fn settings_add_discovered_profiles( &self, request: DiscoveredProfilesRequest, @@ -509,14 +457,9 @@ impl DesktopService { return Err(DesktopError::discovery_unsupported()); } let chosen = selected(host, &request.digests)?; - { + let assign = { let store = self.inner.open_or_create_control()?; check_revision(&store, request.revision)?; - if let Some(workspace_id) = request.workspace_id { - store - .registered_workspace(workspace_id) - .ok_or_else(DesktopError::unknown_workspace)?; - } for proposal in &chosen { store .check_profile(&proposal.declaration()) @@ -527,138 +470,44 @@ impl DesktopService { ) })?; } - } - confirm(prompt, &add_confirmation(&chosen))?; - { - let mut store = self.inner.open_or_create_control()?; - let mut expected = request.revision; - for (done, proposal) in chosen.iter().enumerate() { - if let Err(error) = store.add_profile(&proposal.declaration(), expected) { - let cause = DesktopError::from_control(&error); - return Err(if done == 0 { - cause - } else { - DesktopError::partly_applied("profiles", done, chosen.len(), &cause) - }); - } - expected = store.revision(); - } - } - self.discovery_view(host, request.workspace_id, MissingWorkspace::Ignore) - } - - /// `settings` only. Windows only. For the selected proposals, find the - /// roots the workspace's container cannot read and this account can - /// grant, and after one native confirmation that names the workspace and - /// every folder, grant each read-execute as `omgcode workspace - /// container-grant` does, starting at the confirmed revision. Folders - /// that need administrator rights, and folders whose access-control list - /// could not be read, are named and skipped. Every folder to grant is - /// checked with core's grant rules before the dialog. - /// - /// # Errors - /// - /// `unsupported_platform` outside Windows; `invalid_request`; - /// `discovery_changed`; `unknown_workspace`; `nothing_to_grant`; - /// `control` with core's reason, before any dialog, for a folder core - /// would refuse; `cancelled`; `stale_revision`; - /// `settings_change_running`; `busy`; `container_access_failed` when a - /// grant was recorded but its access list could not be changed (it stays - /// `pending`; revoke it). A failure after some grants were applied says - /// how many. - pub fn settings_grant_discovered_roots( - &self, - request: DiscoveredGrantsRequest, - host: &DiscoveryHost, - prompt: &dyn SettingsPrompt, - ) -> Result { - if !CONTAINER_GRANTS_SUPPORTED { - return Err(DesktopError::unsupported_platform()); - } - let _guard = ChangeGuard::take(&self.inner.settings_change)?; - check_digests(&request.digests)?; - if host.platform() != current_platform()? { - return Err(DesktopError::discovery_unsupported()); - } - let chosen = selected(host, &request.digests)?; - let workspace_id = { - let store = self.inner.open_or_create_control()?; - check_revision(&store, request.revision)?; - store - .registered_workspace(request.workspace_id) - .ok_or_else(DesktopError::unknown_workspace)? - .id() - }; - // The access-control lists are read while the store is closed. - let mut folders: Vec = Vec::new(); - let mut administrator: Vec = Vec::new(); - let mut unknown: Vec = Vec::new(); - for root in chosen.iter().flat_map(ToolchainProposal::read_only_roots) { - let list = match root_grant_need(workspace_id, root) { - RootGrantNeed::NeedsGrant => &mut folders, - RootGrantNeed::NeedsAdministrator => &mut administrator, - RootGrantNeed::Unknown => &mut unknown, - RootGrantNeed::NotApplicable | RootGrantNeed::Readable => continue, - }; - if !list.contains(root) { - list.push(root.clone()); + match request.workspace_id { + None => None, + Some(id) => Some(planned_assignment(&store, id, &chosen)?), } - } - // A grant reaches everything beneath its folder. - let needed = folders.clone(); - folders.retain(|folder| { - !needed - .iter() - .any(|outer| outer != folder && folder.starts_with(outer)) - }); - if folders.is_empty() { - return Err(DesktopError::nothing_to_grant( - administrator.len(), - unknown.len(), - )); - } - let workspace_folder = { - let store = self.inner.open_or_create_control()?; - check_revision(&store, request.revision)?; - let workspace = store - .registered_workspace(request.workspace_id) - .ok_or_else(DesktopError::unknown_workspace)?; - store - .check_container_grants(workspace_id, &folders, ContainerGrantAccess::ReadExecute) - .map_err(|(index, error)| { - let folder = folders.get(index).map(|folder| shown(folder)); - DesktopError::execution( - DesktopError::from_control(&error).code(), - format!("{}: {}", folder.unwrap_or_default(), refusal_text(&error)), - ) - })?; - folder_of_directory(workspace.directory_path()) }; confirm( prompt, - &grants_confirmation(&workspace_folder, &folders, &administrator, &unknown), + &add_confirmation( + &chosen, + assign + .as_ref() + .map(|(_, folder, plan)| (folder.as_str(), plan)), + ), )?; { let mut store = self.inner.open_or_create_control()?; let mut expected = request.revision; - for (done, folder) in folders.iter().enumerate() { - if let Err(error) = store.grant_container_access( - workspace_id, - folder, - ContainerGrantAccess::ReadExecute, - expected, - ) { - let cause = DesktopError::from_grant(&error); + for (done, proposal) in chosen.iter().enumerate() { + if let Err(error) = store.add_profile(&proposal.declaration(), expected) { + let cause = DesktopError::from_control(&error); return Err(if done == 0 { cause } else { - DesktopError::partly_applied("grants", done, folders.len(), &cause) + DesktopError::partly_applied("profiles", done, chosen.len(), &cause) }); } expected = store.revision(); } + if let Some((workspace_id, _, plan)) = &assign { + let names: Vec<&str> = chosen.iter().map(ToolchainProposal::name).collect(); + store + .assign_profiles_with_access(*workspace_id, &names, plan, expected) + .map_err(|error| { + DesktopError::not_assigned(chosen.len(), &DesktopError::from_grant(&error)) + })?; + } } - self.discovery_view(host, Some(request.workspace_id), MissingWorkspace::Ignore) + self.discovery_view(host, request.workspace_id, MissingWorkspace::Ignore) } /// Discover on `host` and build the view against the store as it is now. @@ -742,6 +591,48 @@ impl DesktopService { } } +/// The workspace `id`, its display folder, and the access plan for assigning +/// the `chosen` proposals to it, checked with core's grant rules. +fn planned_assignment( + store: &ControlStore, + id: Uuid, + chosen: &[ToolchainProposal], +) -> Result<(WorkspaceId, String, ProfileAccessPlan), DesktopError> { + let workspace = store + .registered_workspace(id) + .ok_or_else(DesktopError::unknown_workspace)?; + let roots: Vec = chosen + .iter() + .flat_map(ToolchainProposal::read_only_roots) + .cloned() + .collect(); + let plan = store + .plan_folder_access(workspace.id(), &roots) + .map_err(|error| DesktopError::from_control(&error))?; + let folders: Vec = plan + .to_grant() + .iter() + .map(|folder| folder.path().to_path_buf()) + .collect(); + store + .check_container_grants(workspace.id(), &folders, ContainerGrantAccess::ReadExecute) + .map_err(|(index, error)| { + let folder = plan + .to_grant() + .get(index) + .map_or("", PlannedFolder::display); + DesktopError::execution( + DesktopError::from_control(&error).code(), + format!("{}: {}", display_safe_line(folder), refusal_text(&error)), + ) + })?; + Ok(( + workspace.id(), + folder_of_directory(workspace.directory_path()), + plan, + )) +} + /// The profile platform of this build. fn current_platform() -> Result { omgcode_core::control::ProfilePlatform::current() @@ -796,13 +687,6 @@ mod tests { })) .is_err() ); - assert!( - serde_json::from_value::(serde_json::json!({ - "revision": 1, "digests": [DIGEST], - "workspace_id": "6f1c1f0e-8f42-4c5b-9a55-0d2a3c4b5d6e", "folder": "C:\\x" - })) - .is_err() - ); } #[test] @@ -812,53 +696,4 @@ mod tests { assert!(shown.ends_with('…')); assert!(!bounded("a\nb\u{202e}", 80).contains(['\n', '\u{202e}'])); } - - #[test] - fn the_grant_confirmation_names_the_workspace_every_folder_and_the_skipped_ones() { - let confirmation = grants_confirmation( - "C:\\dev\\app", - &[PathBuf::from("C:\\Users\\a\\.rustup\\toolchains\\stable")], - &[PathBuf::from("C:\\Strawberry")], - &[PathBuf::from("C:\\Linked\\jdk")], - ); - for expected in [ - "C:\\dev\\app", - "stable", - "read and execute", - "access-control list", - "AppContainer", - "C:\\Strawberry", - "cannot change", - "C:\\Linked\\jdk", - "could not read", - ] { - assert!( - confirmation.message.contains(expected), - "{expected}: {}", - confirmation.message - ); - } - let without = grants_confirmation("w", &[PathBuf::from("C:\\x")], &[], &[]); - assert!(!without.message.contains("cannot change")); - assert!(!without.message.contains("could not read")); - } - - #[test] - fn nothing_to_grant_says_why_each_folder_was_skipped() { - let readable = DesktopError::nothing_to_grant(0, 0); - assert_eq!(readable.code(), "nothing_to_grant"); - assert!(readable.message().contains("can already read every folder")); - let unread = DesktopError::nothing_to_grant(0, 2); - assert!( - !unread.message().contains("can already read"), - "{}", - unread.message() - ); - assert!(unread.message().contains("2 folder(s) could not be read")); - assert!(unread.message().contains("not a link")); - assert!(!unread.message().contains("administrator")); - let both = DesktopError::nothing_to_grant(1, 3); - assert!(both.message().contains("1 folder(s) need an administrator")); - assert!(both.message().contains("3 folder(s) could not be read")); - } } diff --git a/crates/omgcode-app/src/desktop/settings_execution.rs b/crates/omgcode-app/src/desktop/settings_execution.rs index db486908..4f2253ab 100644 --- a/crates/omgcode-app/src/desktop/settings_execution.rs +++ b/crates/omgcode-app/src/desktop/settings_execution.rs @@ -1,11 +1,19 @@ -//! Toolchain profile, package-network profile, and container grant changes -//! from the `settings` window (ADR-0088). +//! Toolchain profile, profile assignment, package-network profile, and +//! container grant changes from the `settings` window (ADR-0088, ADR-0107). //! //! Each method calls the same `ControlStore` operation as the trusted CLI -//! (`workspace profile-add`, `profile-remove`, `package-profile-add`, -//! `package-profile-remove`, `container-grant`, `container-revoke`) with the -//! same expected-revision check and validation, and records the same events. -//! The window adds no second rule and names no path: +//! (`workspace profile-add`, `profile-remove`, `profile-assign`, +//! `profile-unassign`, `package-profile-add`, `package-profile-remove`, +//! `container-grant`, `container-revoke`) with the same expected-revision +//! check and validation, and records the same events. The window adds no +//! second rule and names no path: +//! +//! - Assigning a toolchain profile to a workspace is the operator's consent +//! to grant that workspace's container read and execute on the profile's +//! folders it cannot read yet; the confirmation names each one, and core +//! refuses the assignment if the folders changed after it was shown. +//! Unassigning, removing a profile, and unregistering a workspace revoke +//! the grants no remaining assignment needs. //! //! - Every folder (a toolchain root, a `PATH` entry, a folder granted read //! and execute) comes only from [`SettingsPrompt::pick_folder`], one dialog @@ -32,10 +40,11 @@ use std::path::PathBuf; use omgcode_core::control::{ - CONTAINER_GRANTS_SUPPORTED, ContainerGrantAccess, ControlError, CredentialStore, + CONTAINER_GRANTS_SUPPORTED, ContainerGrantAccess, ControlError, ControlStore, CredentialStore, MAX_PACKAGE_ORIGIN_BYTES, MAX_PACKAGE_ORIGINS, MAX_PROFILE_PATH_ENTRIES, MAX_PROFILE_ROOTS, MAX_PROFILE_VARIABLES, MAX_VARIABLE_NAME_BYTES, MAX_VARIABLE_VALUE_BYTES, - PackageProfileDeclaration, ProfileDeclaration, delete_unbound_credential, parse_origin, + PackageProfileDeclaration, PlannedFolder, ProfileAccessPlan, ProfileDeclaration, + delete_unbound_credential, parse_origin, }; use omgcode_core::run; use omgcode_core::turn::display_safe_line; @@ -46,8 +55,8 @@ use super::DesktopService; use super::error::DesktopError; use super::settings::overview_of; use super::settings_changes::{ - AlsoWithdrawn, ChangeGuard, Confirmation, FolderPurpose, SettingsPrompt, check_revision, - confirm, shown, + AlsoWithdrawn, ChangeGuard, Confirmation, FolderPurpose, RevokingChange, SettingsPrompt, + check_revision, confirm, revocation_outcome, shown, }; use super::state::folder_of_directory; use super::wire::SettingsOverview; @@ -105,6 +114,19 @@ pub struct ProfileRemoveRequest { pub name: String, } +/// Arguments of `settings_assign_toolchain_profile` and +/// `settings_unassign_toolchain_profile` (ADR-0107). +#[derive(Clone, Debug, Deserialize, Eq, PartialEq)] +#[serde(deny_unknown_fields)] +pub struct ProfileAssignmentRequest { + /// The settings revision the window last read. + pub revision: u64, + /// A registered workspace. + pub workspace_id: Uuid, + /// The recorded profile name. + pub name: String, +} + /// Arguments of `settings_add_package_profile`. #[derive(Clone, Debug, Deserialize, Eq, PartialEq)] #[serde(deny_unknown_fields)] @@ -253,7 +275,7 @@ fn toolchain_add_confirmation( Confirmation { title: "Add a toolchain profile", message: format!( - "Add the toolchain profile {} for {}?\n\nRead-only roots (a run that selects the profile can read and execute everything beneath them):\n{}\n\nPATH entries:\n{}\n\nEnvironment variables (names only; values are stored in plain text and shown by status):\n {variables}\n\nA profile grants nothing by itself. A run still needs the workspace's execute preference and the trusted CLI run command.", + "Add the toolchain profile {} for {}?\n\nRead-only roots (a run that selects the profile can read and execute everything beneath them):\n{}\n\nPATH entries:\n{}\n\nEnvironment variables (names only; values are stored in plain text and shown by status):\n {variables}\n\nA profile grants nothing by itself. Assign it to a workspace to let that workspace's runs use it; a run still needs the workspace's execute preference.", named(name), platform_text(), list(roots), @@ -294,6 +316,122 @@ This adds the workspace's AppContainer, the Windows sandbox its commands run in, } } +/// `folders` as indented display-safe lines. +fn folder_lines<'a>(folders: impl IntoIterator) -> String { + folders + .into_iter() + .map(|folder| format!(" {}", display_safe_line(folder))) + .collect::>() + .join("\n") +} + +/// The part of a confirmation that names what an assignment grants and +/// leaves out (ADR-0107). Empty when nothing is granted or left out. +pub(super) fn access_plan_text(plan: &ProfileAccessPlan) -> String { + let mut text = String::new(); + if !plan.to_grant().is_empty() { + text.push_str(&format!( + "\n\nOMGCode runs the workspace's commands in its AppContainer, a Windows sandbox that starts with no access to your files. So that they can use the toolchain, the sandbox is added to the access-control list on disk of each of these folders, with read and execute access to everything beneath it. The access stays until no profile assigned to the workspace needs it:\n{}", + folder_lines(plan.to_grant().iter().map(PlannedFolder::display)), + )); + } + if !plan.needs_administrator().is_empty() { + text.push_str(&format!( + "\n\nOnly an administrator can change the access-control list of these folders, so they are not granted, and a run that needs one is refused:\n{}", + folder_lines(plan.needs_administrator().iter().map(PlannedFolder::display)), + )); + } + if !plan.unknown().is_empty() { + text.push_str(&format!( + "\n\nThe access of these folders could not be read, or they are no longer where they were recorded, so they are not granted:\n{}", + folder_lines(plan.unknown().iter().map(PlannedFolder::display)), + )); + } + text +} + +/// The native confirmation for assigning a toolchain profile to a workspace. +fn assign_confirmation( + workspace_folder: &str, + name: &str, + plan: &ProfileAccessPlan, +) -> Confirmation { + Confirmation { + title: "Use a toolchain profile in a workspace", + message: format!( + "Let the commands OMGCode runs for the workspace\n{workspace_folder}\nuse the toolchain profile {}?{}\n\nThe workspace can then select the profile for its runs. Each run still needs the workspace's execute preference.", + named(name), + access_plan_text(plan), + ), + } +} + +/// The native confirmation for unassigning a toolchain profile; `revoked` +/// holds the display-safe folders of the grants it releases. +fn unassign_confirmation(workspace_folder: &str, name: &str, revoked: &[String]) -> Confirmation { + let revoked = if revoked.is_empty() { + String::new() + } else { + format!( + "\n\nThe workspace's AppContainer, the Windows sandbox its commands run in, is removed from the access-control list of each folder no other profile of the workspace needs, and every run of the workspace that started before is stopped:\n{}", + folder_lines(revoked.iter().map(String::as_str)), + ) + }; + Confirmation { + title: "Stop using a toolchain profile in a workspace", + message: format!( + "Stop the commands OMGCode runs for the workspace\n{workspace_folder}\nfrom using the toolchain profile {}?\n\nRuns of the workspace that use the profile are stopped.{revoked}", + named(name), + ), + } +} + +/// The native confirmation for removing a toolchain profile. `workspaces` +/// holds, for each workspace it is assigned to, the workspace folder and the +/// display-safe folders of the grants the removal releases there. +fn remove_confirmation(name: &str, workspaces: &[(String, Vec)]) -> Confirmation { + let assigned = if workspaces.is_empty() { + "\n\nIt is not assigned to any workspace.".to_owned() + } else { + let mut text = "\n\nIt is assigned to these workspaces, which can no longer select it; their runs that use it are stopped:".to_owned(); + for (workspace, revoked) in workspaces { + text.push_str(&format!("\n {workspace}")); + if !revoked.is_empty() { + text.push_str(&format!( + "\n Its AppContainer, the Windows sandbox its commands run in, is removed from the access-control list of these folders, and every run of the workspace that started before is stopped:\n{}", + revoked + .iter() + .map(|folder| format!(" {folder}")) + .collect::>() + .join("\n"), + )); + } + } + text + }; + Confirmation { + title: "Remove a toolchain profile", + message: format!( + "Remove the toolchain profile {}?{assigned}\n\nAdd the profile again, and assign it, to use it.", + named(name), + ), + } +} + +/// The display-safe folder of each grant in `grants` that is still recorded. +fn grant_folders(store: &ControlStore, grants: &[Uuid]) -> Vec { + grants + .iter() + .filter_map(|id| { + store + .container_grants() + .iter() + .find(|status| status.grant().id() == *id) + .map(|status| display_safe_line(&status.grant().directory_display())) + }) + .collect() +} + /// The native confirmation for revoking a container grant. fn revoke_confirmation( access: ContainerGrantAccess, @@ -406,15 +544,17 @@ impl DesktopService { } /// `settings` only. After a native confirmation, remove a toolchain - /// profile as `omgcode workspace profile-remove` does. A run already - /// started keeps its recorded profile; the runs the settings then - /// withdraw are stopped as for the CLI. + /// profile as `omgcode workspace profile-remove` does. Every assignment of + /// it ends, so its runs are stopped, and in each workspace it was assigned + /// to, the grants no other assigned profile needs are revoked, which stops + /// that workspace's runs too (ADR-0107). /// /// # Errors /// /// `control` for an unknown profile; `cancelled`; `stale_revision`; - /// `settings_change_running`; `busy`; `runs_not_stopped`; - /// `runs_unchecked`. + /// `settings_change_running`; `busy`; `container_access_failed` or + /// `revocation_incomplete` when the profile was removed but a grant was + /// not revoked; `runs_not_stopped`; `runs_unchecked`. pub fn settings_remove_toolchain_profile( &self, request: ProfileRemoveRequest, @@ -428,20 +568,143 @@ impl DesktopService { let status = store .profile(&request.name) .ok_or_else(|| DesktopError::from_control(&ControlError::UnknownProfile))?; - Confirmation { - title: "Remove a toolchain profile", - message: format!( - "Remove the toolchain profile {}?\n\nNew runs can no longer select it. A run that already started keeps the profile it recorded. Add the profile again to use it.", - named(status.profile().name()), - ), - } + let released = store + .grants_released_by_removal(&request.name) + .map_err(|error| DesktopError::from_control(&error))?; + let workspaces = released + .iter() + .map(|(workspace_id, grants)| { + let folder = store + .registered_workspace(*workspace_id.as_uuid()) + .map_or_else(String::new, |workspace| { + folder_of_directory(workspace.directory_path()) + }); + (folder, grant_folders(&store, grants)) + }) + .collect::>(); + remove_confirmation(status.profile().name(), &workspaces) }; confirm(prompt, &confirmation)?; - self.apply_checked(|store| { - store - .remove_profile(&request.name, request.revision) - .map(|_| ()) - .map_err(|error| DesktopError::from_control(&error)) + self.apply_reporting(|store| { + let before = run::pending_runs(store); + let (_, revocations) = store + .remove_profile_with_access(&request.name, request.revision) + .map_err(|error| DesktopError::from_control(&error))?; + Ok(revocation_outcome( + before, + &revocations, + RevokingChange::Recorded, + )) + }) + } + + /// `settings` only. Assign a recorded toolchain profile to a workspace as + /// `omgcode workspace profile-assign` does, after a native confirmation + /// that names the workspace, the profile, and, on Windows, each folder the + /// assignment grants the workspace's container read and execute and each + /// folder it leaves out (ADR-0107). The confirmation is the operator's + /// consent to those grants. Core plans the folders again under the lock + /// and refuses a list that changed meanwhile. + /// + /// # Errors + /// + /// `unknown_workspace`; `control` for an unknown profile, one of another + /// platform, one already assigned, or folders that changed since the + /// confirmation; `cancelled`; `stale_revision`; + /// `settings_change_running`; `busy`; `container_access_failed` when a + /// grant was recorded but the folder's list could not be changed (the + /// profile stays unassigned and the grant `pending`; revoke it). + pub fn settings_assign_toolchain_profile( + &self, + request: ProfileAssignmentRequest, + prompt: &dyn SettingsPrompt, + ) -> Result { + let _guard = ChangeGuard::take(&self.inner.settings_change)?; + check_name(&request.name)?; + let (workspace_id, plan, confirmation) = { + let store = self.inner.open_or_create_control()?; + check_revision(&store, request.revision)?; + let workspace = store + .registered_workspace(request.workspace_id) + .ok_or_else(DesktopError::unknown_workspace)?; + let name = store + .profile(&request.name) + .ok_or_else(|| DesktopError::from_control(&ControlError::UnknownProfile))? + .profile() + .name() + .to_owned(); + let plan = store + .plan_profile_access(workspace.id(), &request.name) + .map_err(|error| DesktopError::from_control(&error))?; + let confirmation = assign_confirmation( + &folder_of_directory(workspace.directory_path()), + &name, + &plan, + ); + (workspace.id(), plan, confirmation) + }; + confirm(prompt, &confirmation)?; + let mut store = self.inner.open_or_create_control()?; + store + .assign_profile_with_access(workspace_id, &request.name, &plan, request.revision) + .map_err(|error| DesktopError::from_grant(&error))?; + Ok(overview_of(&self.inner, store)) + } + + /// `settings` only. After a native confirmation, unassign a toolchain + /// profile from a workspace as `omgcode workspace profile-unassign` does: + /// its runs there are stopped, and the workspace's grants that no other + /// assigned profile needs are revoked, which stops every run of the + /// workspace that started before (ADR-0107). The workspace's read-write + /// grant on its own folder is never revoked here. + /// + /// # Errors + /// + /// `unknown_workspace`; `control` for an unknown or unassigned profile; + /// `cancelled`; `stale_revision`; `settings_change_running`; `busy`; + /// `container_access_failed` or `revocation_incomplete` when the profile + /// was unassigned but a grant was not revoked; `runs_not_stopped`; + /// `runs_unchecked`. + pub fn settings_unassign_toolchain_profile( + &self, + request: ProfileAssignmentRequest, + prompt: &dyn SettingsPrompt, + ) -> Result { + let _guard = ChangeGuard::take(&self.inner.settings_change)?; + check_name(&request.name)?; + let (workspace_id, confirmation) = { + let store = self.inner.open_or_create_control()?; + check_revision(&store, request.revision)?; + let workspace = store + .registered_workspace(request.workspace_id) + .ok_or_else(DesktopError::unknown_workspace)?; + let name = store + .profile(&request.name) + .ok_or_else(|| DesktopError::from_control(&ControlError::UnknownProfile))? + .profile() + .name() + .to_owned(); + let released = store + .grants_released_by_unassignment(workspace.id(), &request.name) + .map_err(|error| DesktopError::from_control(&error))?; + let confirmation = unassign_confirmation( + &folder_of_directory(workspace.directory_path()), + &name, + &grant_folders(&store, &released), + ); + (workspace.id(), confirmation) + }; + confirm(prompt, &confirmation)?; + self.apply_reporting(|store| { + let before = run::pending_runs(store); + let (_, revocations) = store + .unassign_profile_with_access(workspace_id, &request.name, request.revision) + .map_err(|error| DesktopError::from_control(&error))?; + Ok(revocation_outcome( + before, + &revocations, + RevokingChange::Recorded, + )) }) } diff --git a/crates/omgcode-app/src/desktop/wire.rs b/crates/omgcode-app/src/desktop/wire.rs index 791e065f..09d20b0e 100644 --- a/crates/omgcode-app/src/desktop/wire.rs +++ b/crates/omgcode-app/src/desktop/wire.rs @@ -936,6 +936,9 @@ pub struct WorkspaceSettingsView { pub web_fetch_hosts: Vec, /// Per-tool limits on the five model file-write tools. pub write_tools: WriteToolAccess, + /// The names of the toolchain profiles assigned to the workspace, in the + /// order assigned (ADR-0107). Only these can run in it. + pub profiles: Vec, /// Display-safe text of the selected package cache root, if any. pub package_cache_root: Option, /// The workspace's custom instructions (ADR-0080), empty when none are @@ -1576,6 +1579,9 @@ pub struct SettingsOverview { pub provider_profiles: Vec, /// Recorded toolchain profiles. pub toolchain_profiles: Vec, + /// The platform a toolchain profile must name to run, and so to be + /// assigned, here: `linux` or `windows`, or `null` where no profile runs. + pub profile_platform: Option<&'static str>, /// Recorded package-network profiles. pub package_profiles: Vec, /// Recorded container grants. diff --git a/crates/omgcode-app/tests/common/mod.rs b/crates/omgcode-app/tests/common/mod.rs index 830b7ef7..ccaa6fdf 100644 --- a/crates/omgcode-app/tests/common/mod.rs +++ b/crates/omgcode-app/tests/common/mod.rs @@ -510,13 +510,45 @@ pub struct Workspace { pub path: PathBuf, } +/// The toolchain profile [`Fixture::declare_profile`] records. +const DECLARED_PROFILE: &str = "system"; + /// Private application data, a development root, and registered workspaces. +/// +/// On Windows, registering a workspace through the `settings` service grants +/// its container its folder (ADR-0107), which adds an access-control entry and +/// creates an AppContainer profile on the host. Dropping the fixture revokes +/// every grant still recorded, so neither outlives the test. pub struct Fixture { _temporary: TempDir, pub data: PathBuf, pub development: PathBuf, } +impl Drop for Fixture { + fn drop(&mut self) { + let mut control = match ControlStore::open_existing(&self.data) { + Ok(Some(control)) => control, + Ok(None) => return, + Err(error) => { + eprintln!("fixture cleanup could not open the settings store: {error}"); + return; + } + }; + let grants: Vec = control + .container_grants() + .iter() + .map(|status| status.grant().id()) + .collect(); + for grant in grants { + if let Err(error) = control.revoke_container_grant(grant) { + // Never panic in drop: a second panic would abort the run. + eprintln!("fixture cleanup could not revoke container grant {grant}: {error}"); + } + } + } +} + impl Fixture { /// Application data only; no settings store exists. pub fn bare() -> Self { @@ -567,13 +599,22 @@ impl Fixture { control .set_permissions(id, permissions, control.revision()) .expect("workspace permissions"); + // A workspace runs only its assigned profiles (ADR-0107). The + // primitive records the assignment and grants nothing. + if control.profile(DECLARED_PROFILE).is_some() { + control + .assign_profile(id, DECLARED_PROFILE, control.revision()) + .expect("profile assigned"); + } Workspace { id: *id.as_uuid(), path, } } - /// Declare a toolchain profile so the command tool can be offered. + /// Declare a toolchain profile so the command tool can be offered, and + /// assign it to every registered workspace; [`Self::workspace`] assigns + /// it to a workspace registered later. No access is granted. pub fn declare_profile(&self) { let tools = self.data.parent().expect("temporary root").join("tools"); fs::create_dir_all(&tools).expect("toolchain root"); @@ -581,7 +622,7 @@ impl Fixture { control .add_profile( &ProfileDeclaration { - name: "system".into(), + name: DECLARED_PROFILE.into(), read_only_roots: vec![tools], path_entries: Vec::new(), environment: Vec::new(), @@ -589,6 +630,15 @@ impl Fixture { control.revision(), ) .expect("toolchain profile"); + let workspaces: Vec<_> = control + .workspaces() + .map(|workspace| workspace.id()) + .collect(); + for id in workspaces { + control + .assign_profile(id, DECLARED_PROFILE, control.revision()) + .expect("profile assigned"); + } } pub fn service(&self, endpoint: &str) -> DesktopService { diff --git a/crates/omgcode-app/tests/desktop_settings_changes.rs b/crates/omgcode-app/tests/desktop_settings_changes.rs index 6cf7841f..e49debde 100644 --- a/crates/omgcode-app/tests/desktop_settings_changes.rs +++ b/crates/omgcode-app/tests/desktop_settings_changes.rs @@ -15,7 +15,7 @@ use omgcode_app::desktop::{ PermissionsChangeRequest, SettingsOverview, SettingsPrompt, SettingsRevisionRequest, WorkspaceRevisionRequest, }; -use omgcode_core::control::ControlStore; +use omgcode_core::control::{ContainerGrantAccess, ContainerGrantState, ControlStore}; use omgcode_core::policy::{Access, PermissionSet}; use serde_json::json; @@ -336,7 +336,9 @@ fn registering_starts_at_the_root_and_uses_the_default_preferences() { .settings_register_workspace(revision(1), &prompt) .expect("registered"); - assert_eq!(overview.revision, 2); + // On Windows the same consent grants the workspace's container its + // folder, one more record (ADR-0107). + assert_eq!(overview.revision, if cfg!(windows) { 3 } else { 2 }); assert_eq!(overview.workspaces.len(), 1); let workspace = &overview.workspaces[0]; assert!(workspace.folder_display.ends_with("project")); @@ -375,6 +377,78 @@ fn registering_starts_at_the_root_and_uses_the_default_preferences() { "{}", confirmation.message ); + for part in ["AppContainer", "read and write", "access-control list"] { + assert_eq!( + confirmation.message.contains(part), + cfg!(windows), + "{part}: {}", + confirmation.message + ); + } + let store = ControlStore::open_existing(&fixture.data) + .expect("open") + .expect("exists"); + let grants = store.container_grants(); + if cfg!(windows) { + assert_eq!(grants.len(), 1); + assert_eq!(grants[0].grant().access(), ContainerGrantAccess::ReadWrite); + assert_eq!(grants[0].state(), ContainerGrantState::Active); + assert_eq!( + *grants[0].grant().workspace_id().as_uuid(), + workspace.workspace_id + ); + } else { + assert!(grants.is_empty()); + } + drop(store); + + // Registering the folder again reuses the workspace and grants nothing + // more, because its grant is recorded. + let again = ScriptedPrompt::new().folder(Some(&project)).answer(true); + let repeated = service(&fixture.data) + .settings_register_workspace(revision(overview.revision), &again) + .expect("registered again"); + assert_eq!(repeated.revision, overview.revision); + assert_eq!(repeated.workspaces.len(), 1); +} + +/// Unregistering revokes the workspace's grants first, so on Windows the one +/// registration made is gone with it, and the confirmation names its folder +/// (ADR-0107). +#[test] +fn unregistering_revokes_the_grant_registration_made() { + let fixture = Fixture::new(); + let project = fixture.development.join("project"); + fs::create_dir_all(&project).expect("project"); + let registered = service(&fixture.data) + .settings_register_workspace( + revision(1), + &ScriptedPrompt::new().folder(Some(&project)).answer(true), + ) + .expect("registered"); + let workspace = registered.workspaces[0].workspace_id; + + let prompt = ScriptedPrompt::new().answer(true); + let overview = service(&fixture.data) + .settings_unregister_workspace(for_workspace(workspace, registered.revision), &prompt) + .expect("unregistered"); + + assert!(overview.workspaces.is_empty()); + let message = &prompt.confirmations()[0].message; + assert_eq!( + message.contains("access-control list"), + cfg!(windows), + "{message}" + ); + assert_eq!( + message.matches("project").count(), + if cfg!(windows) { 2 } else { 1 } + ); + let store = ControlStore::open_existing(&fixture.data) + .expect("open") + .expect("exists"); + assert!(store.container_grants().is_empty()); + assert_eq!(store.workspaces().count(), 0); } #[test] diff --git a/crates/omgcode-app/tests/desktop_settings_discovery.rs b/crates/omgcode-app/tests/desktop_settings_discovery.rs index e95693f4..b9a78fc2 100644 --- a/crates/omgcode-app/tests/desktop_settings_discovery.rs +++ b/crates/omgcode-app/tests/desktop_settings_discovery.rs @@ -1,12 +1,14 @@ -//! Toolchain profiles and container grants generated from installed -//! toolchains in the desktop `settings` window (ADR-0103). A scripted prompt -//! stands in for the native dialogs, as in `desktop_settings_execution`, and a -//! fixture host laid out like this platform stands in for the computer. +//! Toolchain profiles generated from installed toolchains in the desktop +//! `settings` window, and their assignment to a chosen workspace (ADR-0103, +//! ADR-0107). A scripted prompt stands in for the native dialogs, as in +//! `desktop_settings_execution`, and a fixture host laid out like this +//! platform stands in for the computer. //! -//! No test applies a container grant: that changes a folder's access-control -//! list and creates an AppContainer profile on the host. The grant path is -//! tested up to its confirmation on Windows, and its platform refusal -//! elsewhere. +//! Workspaces are registered with core's primitive, which grants nothing. On +//! Windows, the one test that adds profiles to a workspace applies real +//! read-execute grants to the fixture host's temporary folders, as the CLI +//! tests do; dropping the fixture revokes them, which also deletes the +//! AppContainer profile. mod common; @@ -17,16 +19,17 @@ use std::path::{Path, PathBuf}; use omgcode_app::TokenSource; use omgcode_app::desktop::{ - Confirmation, DesktopConfig, DesktopError, DesktopService, DiscoveredGrantsRequest, - DiscoveredProfilesRequest, FolderPurpose, SettingsPrompt, SettingsRevisionRequest, - ToolchainDiscovery, ToolchainDiscoveryRequest, + Confirmation, DesktopConfig, DesktopError, DesktopService, DiscoveredProfilesRequest, + FolderPurpose, SettingsPrompt, ToolchainDiscovery, ToolchainDiscoveryRequest, +}; +use omgcode_core::control::{ + ContainerGrantAccess, ContainerGrantState, ControlStore, ProfileDeclaration, ProfilePlatform, }; -use omgcode_core::control::{ControlStore, ProfileDeclaration, ProfilePlatform}; use omgcode_core::toolchain_discovery::DiscoveryHost; use serde_json::{Value, json}; use uuid::Uuid; -use common::{Fixture, json_of, wire}; +use common::{Fixture, json_of}; /// Answers confirmations in order; any folder dialog or an unscripted /// confirmation fails the test. @@ -75,19 +78,6 @@ impl SettingsPrompt for ScriptedPrompt { } } -/// A folder dialog stands in for registering a workspace. -struct FolderPrompt(PathBuf); - -impl SettingsPrompt for FolderPrompt { - fn pick_folder(&self, _purpose: FolderPurpose, _start: Option<&Path>) -> Option { - Some(self.0.clone()) - } - - fn confirm(&self, _confirmation: &Confirmation) -> bool { - true - } -} - fn service(data: &Path) -> DesktopService { DesktopService::open(DesktopConfig { data_root: data.to_path_buf(), @@ -194,17 +184,20 @@ fn add_request(revision: u64, digests: Vec) -> DiscoveredProfilesRequest } } -/// Register one workspace through the service; returns its identifier. +/// Register one workspace with core's primitive, which grants nothing; +/// returns its identifier. fn with_workspace(fixture: &Fixture) -> Uuid { let project = fixture.development.join("project"); fs::create_dir_all(&project).expect("project"); - let request: SettingsRevisionRequest = - wire(json!({ "revision": current_revision(&fixture.data) })); - service(&fixture.data) - .settings_register_workspace(request, &FolderPrompt(project)) + let mut store = ControlStore::open_existing(&fixture.data) + .expect("open") + .expect("exists"); + let revision = store.revision(); + *store + .register_workspace(&project, revision) .expect("registered") - .workspaces[0] - .workspace_id + .id() + .as_uuid() } fn profile_count(data: &Path) -> usize { @@ -628,9 +621,8 @@ fn on_windows_each_root_says_what_the_workspace_container_needs() { } } -#[cfg(windows)] #[test] -fn on_windows_a_grant_confirmation_names_the_workspace_and_every_folder() { +fn adding_with_a_workspace_names_what_it_grants_in_the_one_confirmation() { let fixture = Fixture::new(); let host = Host::new(&fixture); let workspace = with_workspace(&fixture); @@ -639,11 +631,11 @@ fn on_windows_a_grant_confirmation_names_the_workspace_and_every_folder() { let prompt = ScriptedPrompt::answering(false); let error = service(&fixture.data) - .settings_grant_discovered_roots( - DiscoveredGrantsRequest { + .settings_add_discovered_profiles( + DiscoveredProfilesRequest { revision: before, - workspace_id: workspace, digests: digests_of(&discovery), + workspace_id: Some(workspace), }, &host.discovery(), &prompt, @@ -652,52 +644,102 @@ fn on_windows_a_grant_confirmation_names_the_workspace_and_every_folder() { assert_eq!(error.code(), "cancelled"); let shown = prompt.shown(); - assert_eq!(shown.len(), 1); + assert_eq!(shown.len(), 1, "one confirmation for profiles and grants"); let message = &shown[0].message; for expected in [ + "2 toolchain profile(s)", "project", - "System32", - "Go", - "go1.22.0", - "read and execute", - "access-control list", + "assigned to the workspace", ] { assert!(message.contains(expected), "{expected} in {message}"); } - // System32 is listed once although both proposals need it. - assert_eq!(message.matches("System32").count(), 1, "{message}"); + if cfg!(windows) { + for expected in [ + "System32", + "go1.22.0", + "read and execute", + "access-control list", + "AppContainer", + ] { + assert!(message.contains(expected), "{expected} in {message}"); + } + // Each grant is listed once, although both proposals need System32; + // the roots list it once per proposal. + let grants = message + .split("read and execute access to everything beneath it") + .nth(1) + .expect("a grant list"); + assert_eq!(grants.matches("System32").count(), 1, "{message}"); + } else { + assert!(!message.contains("access-control list"), "{message}"); + } let store = ControlStore::open_existing(&fixture.data) .expect("open") .expect("exists"); assert!(store.container_grants().is_empty()); + assert!(store.profiles().is_empty()); assert_eq!(store.revision(), before); } -#[cfg(windows)] #[test] -fn on_windows_a_grant_for_an_unregistered_workspace_is_refused_before_any_dialog() { +fn adding_with_a_workspace_assigns_the_profiles_and_grants_their_folders() { let fixture = Fixture::new(); let host = Host::new(&fixture); - let discovery = discover(&fixture, &host, None); + let workspace = with_workspace(&fixture); + let discovery = discover(&fixture, &host, Some(workspace)); - let error = service(&fixture.data) - .settings_grant_discovered_roots( - DiscoveredGrantsRequest { + let after = service(&fixture.data) + .settings_add_discovered_profiles( + DiscoveredProfilesRequest { revision: discovery.overview.revision, - workspace_id: Uuid::new_v4(), digests: digests_of(&discovery), + workspace_id: Some(workspace), }, &host.discovery(), - &ScriptedPrompt::silent(), + &ScriptedPrompt::answering(true), ) - .expect_err("unknown"); + .expect("added and assigned"); - assert_eq!(error.code(), "unknown_workspace"); + assert_eq!(after.overview.workspaces[0].profiles, ["go", "go-1.22.0"]); + let store = ControlStore::open_existing(&fixture.data) + .expect("open") + .expect("exists"); + let grants: Vec<_> = store + .container_grants() + .iter() + .map(|status| { + let grant = status.grant(); + assert_eq!(*grant.workspace_id().as_uuid(), workspace); + assert_eq!(grant.access(), ContainerGrantAccess::ReadExecute); + assert_eq!(status.state(), ContainerGrantState::Active, "{status:?}"); + grant.directory_display() + }) + .collect(); + if cfg!(windows) { + // System32 once, and each Go installation's own folder. + assert_eq!(grants.len(), 3, "{grants:?}"); + assert_eq!( + grants + .iter() + .filter(|grant| grant.ends_with("System32")) + .count(), + 1, + "{grants:?}" + ); + // The refreshed list shows every root as readable now. + for proposal in json_of(&after)["proposals"].as_array().expect("proposals") { + for root in proposal["read_only_roots"].as_array().expect("roots") { + assert_eq!(root["grant"], "readable", "{root}"); + } + } + } else { + assert!(grants.is_empty(), "{grants:?}"); + } } #[cfg(windows)] #[test] -fn on_windows_a_folder_core_would_not_grant_is_refused_before_any_dialog() { +fn on_windows_adding_a_proposal_inside_the_development_root_to_a_workspace_grants_nothing() { let fixture = Fixture::new(); let host = Host::new(&fixture); let workspace = with_workspace(&fixture); @@ -724,28 +766,23 @@ fn on_windows_a_folder_core_would_not_grant_is_refused_before_any_dialog() { .any(|root| root.folder == shown_root) }) .expect("the GOROOT proposal"); - // Core would refuse it as a profile too, and the list says so. + // Core would refuse it as a profile, and the list says so. assert!(proposal.refusal.is_some(), "{proposal:?}"); let before = request.overview.revision; let error = service(&fixture.data) - .settings_grant_discovered_roots( - DiscoveredGrantsRequest { + .settings_add_discovered_profiles( + DiscoveredProfilesRequest { revision: before, - workspace_id: workspace, digests: vec![proposal.digest.clone()], + workspace_id: Some(workspace), }, &host.discovery().with_goroot(inside), &ScriptedPrompt::silent(), ) - .expect_err("core refuses the grant"); + .expect_err("core refuses the profile"); assert_eq!(error.code(), "control"); - assert!( - error.message().starts_with(&shown_root), - "{}", - error.message() - ); assert!( error.message().contains("development root"), "{}", @@ -760,7 +797,7 @@ fn on_windows_a_folder_core_would_not_grant_is_refused_before_any_dialog() { #[cfg(not(windows))] #[test] -fn off_windows_grants_are_refused_and_roots_need_none() { +fn off_windows_roots_need_no_grant() { let fixture = Fixture::new(); let host = Host::new(&fixture); let workspace = with_workspace(&fixture); @@ -773,20 +810,6 @@ fn off_windows_grants_are_refused_and_roots_need_none() { { assert_eq!(root["grant"], "not_applicable"); } - - let error = service(&fixture.data) - .settings_grant_discovered_roots( - DiscoveredGrantsRequest { - revision: discovery.overview.revision, - workspace_id: workspace, - digests: digests_of(&discovery), - }, - &host.discovery(), - &ScriptedPrompt::silent(), - ) - .expect_err("unsupported"); - - assert_eq!(error.code(), "unsupported_platform"); } #[test] diff --git a/crates/omgcode-app/tests/desktop_settings_execution.rs b/crates/omgcode-app/tests/desktop_settings_execution.rs index 4687bfdf..cfb42c75 100644 --- a/crates/omgcode-app/tests/desktop_settings_execution.rs +++ b/crates/omgcode-app/tests/desktop_settings_execution.rs @@ -1,11 +1,13 @@ -//! Toolchain profile, package-network profile, and container grant changes -//! from the desktop `settings` window (ADR-0088). A scripted prompt stands in -//! for the native dialogs, as in `desktop_settings_skills`. +//! Toolchain profile, profile assignment, package-network profile, and +//! container grant changes from the desktop `settings` window (ADR-0088, +//! ADR-0107). A scripted prompt stands in for the native dialogs, as in +//! `desktop_settings_skills`. //! -//! No test applies a container grant: that changes a folder's access-control -//! list and creates an AppContainer profile on the host. The grant paths that -//! run before any change (revision, workspace, dialogs, confirmation text) are -//! tested on Windows, and the platform refusal elsewhere. +//! The hand-made grant command is tested up to its confirmation on Windows, +//! and its platform refusal elsewhere. An accepted profile assignment applies +//! a real read-execute grant to a temporary toolchain folder on Windows, as +//! the CLI tests do; dropping the fixture revokes every recorded grant, which +//! also deletes the AppContainer profile. mod common; @@ -17,10 +19,10 @@ use std::path::{Path, PathBuf}; use omgcode_app::TokenSource; use omgcode_app::desktop::{ Confirmation, ContainerGrantRequest, DesktopConfig, DesktopError, DesktopService, - FolderPurpose, PackageProfileAddRequest, ProfileRemoveRequest, SettingsOverview, - SettingsPrompt, SettingsRevisionRequest, ToolchainProfileAddRequest, WebHostChangeRequest, + FolderPurpose, PackageProfileAddRequest, ProfileAssignmentRequest, ProfileRemoveRequest, + SettingsOverview, SettingsPrompt, ToolchainProfileAddRequest, WebHostChangeRequest, }; -use omgcode_core::control::{ControlStore, PackageProfileDeclaration}; +use omgcode_core::control::{ContainerGrantAccess, ControlStore, PackageProfileDeclaration}; use serde_json::json; use uuid::Uuid; @@ -166,18 +168,47 @@ fn tool_root(fixture: &Fixture, name: &str) -> PathBuf { root } -/// Register one workspace through the service; returns its identifier. +/// Register one workspace with core's primitive, which grants nothing (the +/// service's registration grants its folder on Windows, ADR-0107); returns +/// its identifier. fn with_workspace(fixture: &Fixture) -> Uuid { let project = fixture.development.join("project"); fs::create_dir_all(&project).expect("project"); - let prompt = ScriptedPrompt::new().folder(Some(&project)).answer(true); - let request: SettingsRevisionRequest = - wire(json!({ "revision": current_revision(&fixture.data) })); - service(&fixture.data) - .settings_register_workspace(request, &prompt) + let mut store = ControlStore::open_existing(&fixture.data) + .expect("open") + .expect("exists"); + let revision = store.revision(); + *store + .register_workspace(&project, revision) .expect("registered") - .workspaces[0] - .workspace_id + .id() + .as_uuid() +} + +fn assignment(revision: u64, workspace: Uuid, name: &str) -> ProfileAssignmentRequest { + wire(json!({ "revision": revision, "workspace_id": workspace, "name": name })) +} + +/// The recorded grants as `(access, directory)`, in order. +fn recorded_grants(data: &Path) -> Vec<(ContainerGrantAccess, PathBuf)> { + ControlStore::open_existing(data) + .expect("open") + .expect("exists") + .container_grants() + .iter() + .map(|status| { + ( + status.grant().access(), + resolved(Path::new(&status.grant().directory_display())), + ) + }) + .collect() +} + +/// `path` as the operating system resolves it, for comparing with a recorded +/// directory. +fn resolved(path: &Path) -> PathBuf { + fs::canonicalize(path).expect("canonical path") } /// Record a toolchain profile through the service. @@ -419,7 +450,10 @@ fn removing_a_profile_is_confirmed_by_name_and_applied_with_the_confirmed_revisi assert_eq!(error.code(), "cancelled"); let message = declined.confirmations().remove(0).message; assert!(message.contains("rust"), "{message}"); - assert!(message.contains("already started"), "{message}"); + assert!( + message.contains("not assigned to any workspace"), + "{message}" + ); assert_eq!(current_revision(&fixture.data), added.revision); // Stale and unknown are refused before any dialog. @@ -478,6 +512,191 @@ fn a_removal_is_refused_when_the_settings_change_during_the_confirmation() { assert!(store.profile("rust").is_some()); } +/// Assigning a profile is confirmed with the workspace, the profile, and on +/// Windows the folder its container is granted; the confirmation is the +/// consent to that grant (ADR-0107). On Windows the accepted assignment +/// applies a real read-execute grant to a temporary folder, which dropping +/// the fixture revokes. +#[test] +fn assigning_a_profile_is_confirmed_with_the_folders_it_grants() { + let fixture = Fixture::new(); + let workspace = with_workspace(&fixture); + let added = profile_added(&fixture, "rust"); + let shown_root = Path::new("toolchains").join("rust").display().to_string(); + let before = added.revision; + + let declined = ScriptedPrompt::new().answer(false); + let error = error_of( + service(&fixture.data) + .settings_assign_toolchain_profile(assignment(before, workspace, "rust"), &declined), + ); + assert_eq!(error.code(), "cancelled"); + let confirmation = declined.confirmations().remove(0); + assert_eq!(confirmation.title, "Use a toolchain profile in a workspace"); + for part in ["rust", "project"] { + assert!( + confirmation.message.contains(part), + "{part}: {}", + confirmation.message + ); + } + for part in [ + shown_root.as_str(), + "read and execute", + "access-control list", + "AppContainer", + ] { + assert_eq!( + confirmation.message.contains(part), + cfg!(windows), + "{part}: {}", + confirmation.message + ); + } + assert_eq!(current_revision(&fixture.data), before); + assert!(recorded_grants(&fixture.data).is_empty()); + + // A stale revision, an unknown workspace, and an unknown profile are + // refused before any dialog. + let silent = ScriptedPrompt::new(); + for (request, code) in [ + (assignment(before + 1, workspace, "rust"), "stale_revision"), + ( + assignment(before, Uuid::new_v4(), "rust"), + "unknown_workspace", + ), + (assignment(before, workspace, "missing"), "control"), + ] { + let error = + error_of(service(&fixture.data).settings_assign_toolchain_profile(request, &silent)); + assert_eq!(error.code(), code, "{error}"); + } + assert!(silent.asked().is_empty()); + + let accepted = ScriptedPrompt::new().answer(true); + let overview = service(&fixture.data) + .settings_assign_toolchain_profile(assignment(before, workspace, "rust"), &accepted) + .expect("assigned"); + assert_eq!(overview.workspaces[0].profiles, ["rust"]); + if cfg!(windows) { + assert_eq!( + overview.revision, + before + 2, + "a grant, then the assignment" + ); + assert_eq!( + recorded_grants(&fixture.data), + [( + ContainerGrantAccess::ReadExecute, + resolved(&tool_root(&fixture, "rust")) + )] + ); + } else { + assert_eq!(overview.revision, before + 1); + assert!(recorded_grants(&fixture.data).is_empty()); + } + + // Assigning it again is refused before any dialog. + let error = error_of(service(&fixture.data).settings_assign_toolchain_profile( + assignment(overview.revision, workspace, "rust"), + &silent, + )); + assert_eq!(error.code(), "control"); + assert!(silent.asked().is_empty()); +} + +/// Unassigning revokes the grants only that profile needed and says so; +/// unassigning a profile that is not assigned is refused before any dialog. +#[test] +fn unassigning_a_profile_revokes_the_grants_it_alone_needed() { + let fixture = Fixture::new(); + let workspace = with_workspace(&fixture); + profile_added(&fixture, "rust"); + let shown_root = Path::new("toolchains").join("rust").display().to_string(); + let assigned = service(&fixture.data) + .settings_assign_toolchain_profile( + assignment(current_revision(&fixture.data), workspace, "rust"), + &ScriptedPrompt::new().answer(true), + ) + .expect("assigned"); + + let declined = ScriptedPrompt::new().answer(false); + let error = error_of(service(&fixture.data).settings_unassign_toolchain_profile( + assignment(assigned.revision, workspace, "rust"), + &declined, + )); + assert_eq!(error.code(), "cancelled"); + let confirmation = declined.confirmations().remove(0); + for part in ["rust", "project", "stopped"] { + assert!( + confirmation.message.contains(part), + "{part}: {}", + confirmation.message + ); + } + for part in [shown_root.as_str(), "access-control list"] { + assert_eq!( + confirmation.message.contains(part), + cfg!(windows), + "{part}: {}", + confirmation.message + ); + } + assert_eq!(current_revision(&fixture.data), assigned.revision); + + let overview = service(&fixture.data) + .settings_unassign_toolchain_profile( + assignment(assigned.revision, workspace, "rust"), + &ScriptedPrompt::new().answer(true), + ) + .expect("unassigned"); + assert!(overview.workspaces[0].profiles.is_empty()); + // A revocation needs no revision; the unassignment is one record. + assert_eq!(overview.revision, assigned.revision + 1); + assert!(recorded_grants(&fixture.data).is_empty()); + + let silent = ScriptedPrompt::new(); + let error = error_of(service(&fixture.data).settings_unassign_toolchain_profile( + assignment(overview.revision, workspace, "rust"), + &silent, + )); + assert_eq!(error.code(), "control"); + assert!(error.message().contains("not assigned"), "{error}"); + assert!(silent.asked().is_empty()); +} + +/// Removing an assigned profile names the workspace it leaves and, on +/// Windows, the folder whose grant it revokes. +#[test] +fn removing_an_assigned_profile_names_its_workspace_and_revokes_its_grant() { + let fixture = Fixture::new(); + let workspace = with_workspace(&fixture); + profile_added(&fixture, "rust"); + let shown_root = Path::new("toolchains").join("rust").display().to_string(); + let assigned = service(&fixture.data) + .settings_assign_toolchain_profile( + assignment(current_revision(&fixture.data), workspace, "rust"), + &ScriptedPrompt::new().answer(true), + ) + .expect("assigned"); + + let prompt = ScriptedPrompt::new().answer(true); + let overview = service(&fixture.data) + .settings_remove_toolchain_profile(remove(assigned.revision, "rust"), &prompt) + .expect("removed"); + + let message = prompt.confirmations().remove(0).message; + assert!(message.contains("project"), "{message}"); + assert_eq!( + message.contains(shown_root.as_str()), + cfg!(windows), + "{message}" + ); + assert!(overview.toolchain_profiles.is_empty()); + assert!(overview.workspaces[0].profiles.is_empty()); + assert!(recorded_grants(&fixture.data).is_empty()); +} + #[test] fn a_package_profile_is_confirmed_with_the_origins_core_parsed() { let fixture = Fixture::new(); diff --git a/crates/omgcode-cli/src/control_cli.rs b/crates/omgcode-cli/src/control_cli.rs index 7916b2ee..9804ec2c 100644 --- a/crates/omgcode-cli/src/control_cli.rs +++ b/crates/omgcode-cli/src/control_cli.rs @@ -5,7 +5,7 @@ use clap::{Args, Subcommand, ValueEnum}; use omgcode_core::control::{ ContainerGrantAccess, ControlError, ControlStore, CredentialId, PackageProfileDeclaration, - ProfileDeclaration, ProviderProfileDeclaration, + ProfileDeclaration, ProviderProfileDeclaration, Revocations, }; use omgcode_core::policy::{ Access, Operation, PermissionSet, PolicyRequest, WorkspaceId, WriteTool, @@ -45,17 +45,23 @@ pub(crate) enum WorkspaceCommand { revision: u64, }, /// Register a workspace below the configured development root. + /// + /// On Windows, registering is also the consent to grant the workspace's + /// AppContainer read and write access to its folder (ADR-0107), when this + /// account can change the folder's access. Registering a folder again + /// keeps its identifier and grants that access if it is missing. Register { path: PathBuf, #[arg(long)] revision: u64, }, /// Remove one workspace's registration and the settings that name it: its - /// preferences, `web_fetch` host allowlist, package cache selection, skill overrides, checkpoint - /// record, and saved desktop instructions. The folder and its files are - /// not touched. Refused while a container grant names the workspace; revoke - /// it with `container-revoke` first. Registering the folder again assigns a - /// new identifier. + /// preferences, `web_fetch` host allowlist, assigned toolchain profiles, + /// package cache selection, skill overrides, checkpoint record, and saved + /// desktop instructions. The folder and its files are not touched. Every + /// container grant of the workspace is revoked first (ADR-0107); if one + /// cannot be revoked, the workspace stays registered. Registering the + /// folder again assigns a new identifier. Unregister { workspace: String, #[arg(long)] @@ -94,23 +100,53 @@ pub(crate) enum WorkspaceCommand { /// /// Read-write grants are limited to the workspace directory. The grant /// persists until it is revoked. `omgcode run` needs a read-write grant - /// on the workspace. + /// on the workspace, which `register` applies; `profile-assign` grants a + /// profile's folders. ContainerGrant(ContainerGrantArgs), /// Revoke one recorded container grant. Needs no revision. ContainerRevoke { /// The grant identifier shown by `container-grant` and `status`. grant: Uuid, }, - /// Record a toolchain profile for `omgcode run`. + /// Record a toolchain profile for `omgcode run`. A workspace runs it only + /// after `profile-assign`. ProfileAdd(ProfileAddArgs), /// Show one recorded toolchain profile. ProfileShow { name: String }, - /// Remove a toolchain profile. + /// Remove a toolchain profile. Its assignments end, and in each workspace + /// it was assigned to, the grants on its folders that no profile still + /// assigned there needs are revoked. ProfileRemove { name: String, #[arg(long)] revision: u64, }, + /// Let a workspace run a recorded toolchain profile (ADR-0107). + /// + /// On Windows, running this command is the consent to grant the + /// workspace's AppContainer read and execute access to each of the + /// profile's folders it cannot read yet and this account can change. The + /// grants are applied first, then the assignment is recorded. Folders only + /// an administrator can grant, or whose access could not be read, are + /// listed under `not_granted`; a run that needs one is refused. + ProfileAssign { + workspace: String, + /// The toolchain profile name. + name: String, + #[arg(long)] + revision: u64, + }, + /// Stop a workspace from running a toolchain profile. Its runs of that + /// profile are withdrawn, and on Windows the grants on the profile's + /// folders that no profile still assigned to the workspace needs are + /// revoked, which withdraws every run of the workspace. + ProfileUnassign { + workspace: String, + /// The toolchain profile name. + name: String, + #[arg(long)] + revision: u64, + }, /// Record a package-network profile. Configuration only: no run accepts it. PackageProfileAdd(PackageProfileAddArgs), /// Show one recorded package-network profile. @@ -525,13 +561,26 @@ pub(crate) fn run(action: WorkspaceCommand, data_root: &Path) -> Result<(), CliE } WorkspaceCommand::Register { path, revision } => { let mut store = open(data_root)?; - let registration = store - .register_workspace(&path, revision) + let registered = store + .register_workspace_with_access(&path, revision) .map_err(control_error)?; - print_json(&json!({ - "registration_id": registration.id(), + let grant = registered.grant.map_err(|error| { + CliError::new( + "control", + format!( + "The workspace was registered as {}, but its container could not be granted its folder: {error}. Grant it with `workspace container-grant`.", + registered.registration.id() + ), + ) + })?; + let mut output = json!({ + "registration_id": registered.registration.id(), "snapshot": store.snapshot(), - })) + }); + if let Some(grant) = grant { + output["grant_id"] = json!(grant.id()); + } + print_json(&output) } WorkspaceCommand::Unregister { workspace, @@ -540,14 +589,16 @@ pub(crate) fn run(action: WorkspaceCommand, data_root: &Path) -> Result<(), CliE let workspace_id = parse_workspace_id(&workspace)?; let mut store = open_existing(data_root)? .ok_or_else(|| CliError::new("control", "Workspace control is not initialized"))?; - store - .unregister_workspace(workspace_id, revision) + // A revocation withdraws every run of the workspace that started + // before it, and runs start only under the lock held here. + let before = run::pending_runs(&store); + let revocations = store + .unregister_workspace_with_access(workspace_id, revision) .map_err(control_error)?; let snapshot = store.snapshot(); let listed = withdrawn_runs(&store); drop(store); - stop_withdrawn_runs(data_root, listed.as_deref().unwrap_or(&[]))?; - listed?; + finish_revocations(data_root, listed, before, &revocations, true)?; // The change is recorded. A saved desktop instructions file is // removed next, without the desktop's in-process lock; a file that // remains is never sent, because a turn reads it only for a @@ -564,6 +615,7 @@ pub(crate) fn run(action: WorkspaceCommand, data_root: &Path) -> Result<(), CliE })?; print_json(&json!({ "unregistered_workspace_id": workspace_id, + "revoked": revocations.revoked, "snapshot": snapshot, })) } @@ -629,17 +681,45 @@ pub(crate) fn run(action: WorkspaceCommand, data_root: &Path) -> Result<(), CliE WorkspaceCommand::ProfileRemove { name, revision } => { let mut store = open_existing(data_root)? .ok_or_else(|| CliError::new("control", "Workspace control is not initialized"))?; - let profile_id = store - .remove_profile(&name, revision) + let before = run::pending_runs(&store); + let (profile_id, revocations) = store + .remove_profile_with_access(&name, revision) .map_err(control_error)?; let output = json!({ "removed_profile_id": profile_id, + "revoked": revocations.revoked, "snapshot": store.snapshot(), }); let listed = withdrawn_runs(&store); drop(store); - stop_withdrawn_runs(data_root, listed.as_deref().unwrap_or(&[]))?; - listed?; + finish_revocations(data_root, listed, before, &revocations, false)?; + print_json(&output) + } + WorkspaceCommand::ProfileAssign { + workspace, + name, + revision, + } => profile_assign(&workspace, &name, revision, data_root), + WorkspaceCommand::ProfileUnassign { + workspace, + name, + revision, + } => { + let workspace_id = parse_workspace_id(&workspace)?; + let mut store = open_existing(data_root)? + .ok_or_else(|| CliError::new("control", "Workspace control is not initialized"))?; + let before = run::pending_runs(&store); + let (profile_id, revocations) = store + .unassign_profile_with_access(workspace_id, &name, revision) + .map_err(control_error)?; + let output = json!({ + "unassigned_profile_id": profile_id, + "revoked": revocations.revoked, + "snapshot": store.snapshot(), + }); + let listed = withdrawn_runs(&store); + drop(store); + finish_revocations(data_root, listed, before, &revocations, false)?; print_json(&output) } WorkspaceCommand::PackageProfileAdd(args) => package_profile_add(args, data_root), @@ -789,6 +869,101 @@ fn container_grant(args: ContainerGrantArgs, data_root: &Path) -> Result<(), Cli })) } +/// Assign a profile to a workspace and grant what it needs. The command is +/// the operator's consent, so the plan made here under the control lock is +/// the one applied. +fn profile_assign( + workspace: &str, + name: &str, + revision: u64, + data_root: &Path, +) -> Result<(), CliError> { + let workspace_id = parse_workspace_id(workspace)?; + let mut store = open_existing(data_root)? + .ok_or_else(|| CliError::new("control", "Workspace control is not initialized"))?; + let plan = store + .plan_profile_access(workspace_id, name) + .map_err(control_error)?; + let assignment = store + .assign_profile_with_access(workspace_id, name, &plan, revision) + .map_err(control_error)?; + let not_granted: Vec<_> = assignment + .plan + .needs_administrator() + .iter() + .map(|folder| (folder, "needs_administrator")) + .chain( + assignment + .plan + .unknown() + .iter() + .map(|folder| (folder, "access_unknown")), + ) + .map(|(folder, reason)| json!({ "path": folder.display(), "reason": reason })) + .collect(); + print_json(&json!({ + "assigned_profile_id": assignment.profile_ids.first(), + "granted": assignment.granted.iter().map(|grant| json!({ + "grant_id": grant.id(), + "path": grant.directory_display(), + })).collect::>(), + "not_granted": not_granted, + "snapshot": store.snapshot(), + })) +} + +/// After a recorded change that may have revoked grants, wait for the runs it +/// withdrew, then report what did not complete. `listed` holds the runs the +/// settings withdrew; `before` every pending run, listed by +/// `run::pending_runs` before the change. Any revocation, even one that failed +/// after it was requested, withdraws every run of its workspace, so the runs +/// of those workspaces are waited for too. A grant that could not be revoked +/// stays recorded, and `workspace container-revoke` retries it. +fn finish_revocations( + data_root: &Path, + listed: Result, CliError>, + before: Result, run::RunError>, + revocations: &Revocations, + unregistration: bool, +) -> Result<(), CliError> { + let mut wait = listed.as_deref().unwrap_or(&[]).to_vec(); + let mut problems = Vec::new(); + if !revocations.workspaces.is_empty() { + match before { + Ok(runs) => wait.extend(revocations.withdrawn_runs(&runs)), + Err(error) => problems.push(format!( + "The runs the revocations affect could not be found: {error}." + )), + } + } + let mut kind = "run"; + if let Some((grant, error)) = &revocations.failure { + kind = "control"; + // An unregistration is recorded only after every grant is revoked. + let message = if unregistration { + format!( + "The workspace stays registered, because grant {grant} could not be revoked: {error}. Retry with `workspace container-revoke {grant}`, then unregister it again." + ) + } else { + format!( + "The change was recorded, but grant {grant} could not be revoked: {error}. Retry with `workspace container-revoke {grant}`." + ) + }; + problems.insert(0, message); + } + if let Err(error) = stop_withdrawn_runs(data_root, &wait) { + problems.push(error.message); + } + if let Err(error) = listed { + problems.push(error.message); + } + if problems.is_empty() { + Ok(()) + } else { + Err(CliError::new(kind, problems.join(" "))) + } +} + fn profile_add(args: ProfileAddArgs, data_root: &Path) -> Result<(), CliError> { let environment = args .environment diff --git a/crates/omgcode-cli/tests/control_workflow.rs b/crates/omgcode-cli/tests/control_workflow.rs index 5149dbcf..86b34187 100644 --- a/crates/omgcode-cli/tests/control_workflow.rs +++ b/crates/omgcode-cli/tests/control_workflow.rs @@ -10,11 +10,12 @@ use std::time::Duration; use tempfile::TempDir; use uuid::Uuid; +use omgcode_core::control::ControlStore; #[cfg(unix)] use support::CLI_DEADLINE; use support::{ - HANG_FIXTURE_ENV, assert_control_error, assert_error_code, assert_success, json_output, - path_arg, run_cli, run_with_deadline, + GRANT_CLI_DEADLINE, HANG_FIXTURE_ENV, assert_control_error, assert_error_code, assert_success, + json_output, path_arg, run_cli, run_cli_for, run_with_deadline, }; /// Park only when the timeout regression launches this test in a child process. @@ -91,55 +92,56 @@ fn workspace_commands_persist_cas_permissions_policy_and_audit_results() { assert_eq!(root_snapshot["revision"], 1); assert_ne!(root_snapshot["development_root"], Value::Null); - // When two paths register, their IDs persist and an idempotent repeat does not advance revision. - let first = run_cli( - &data_root, - &[ - "workspace", - "register", - path_arg(&first_workspace), - "--revision", - "1", - ], - ); - assert_success(&first); - let first = json_output(&first); + // When two paths register, their IDs persist and an idempotent repeat + // does not advance revision. On Windows each registration also grants + // the workspace's container read-write on its folder (ADR-0107), one + // more revision; Linux records no grant. + let _cleanup = RevokeGrantsOnDrop(&data_root); + let step: u64 = if cfg!(windows) { 2 } else { 1 }; + let register_cli = |workspace: &Path, revision: u64| { + let output = run_cli_for( + &data_root, + &[ + "workspace", + "register", + path_arg(workspace), + "--revision", + &revision.to_string(), + ], + GRANT_CLI_DEADLINE, + ); + assert_success(&output); + json_output(&output) + }; + let first = register_cli(&first_workspace, 1); let first_id = first["registration_id"] .as_str() .expect("first workspace ID"); - assert_eq!(first["snapshot"]["revision"], 2); - let first_repeat = run_cli( - &data_root, - &[ - "workspace", - "register", - path_arg(&first_workspace), - "--revision", - "2", - ], - ); - assert_success(&first_repeat); - let first_repeat = json_output(&first_repeat); + assert_eq!(first["snapshot"]["revision"], 1 + step); + assert_eq!(first.get("grant_id").is_some(), cfg!(windows), "{first}"); + let first_repeat = register_cli(&first_workspace, 1 + step); assert_eq!(first_repeat["registration_id"], first_id); - assert_eq!(first_repeat["snapshot"]["revision"], 2); + assert_eq!(first_repeat["snapshot"]["revision"], 1 + step); + assert!(first_repeat.get("grant_id").is_none(), "{first_repeat}"); - let second = run_cli( - &data_root, - &[ - "workspace", - "register", - path_arg(&second_workspace), - "--revision", - "2", - ], - ); - assert_success(&second); - let second = json_output(&second); + let second = register_cli(&second_workspace, 1 + step); let second_id = second["registration_id"] .as_str() .expect("second workspace ID"); assert_ne!(first_id, second_id); - assert_eq!(second["snapshot"]["revision"], 3); + let base = 1 + 2 * step; + assert_eq!(second["snapshot"]["revision"], base); + let grants = second["snapshot"]["container_grants"].as_array(); + if cfg!(windows) { + let grants = grants.expect("grants"); + assert_eq!(grants.len(), 2, "{second}"); + for grant in grants { + assert_eq!(grant["access"], "read_write", "{grant}"); + assert_eq!(grant["state"], "active", "{grant}"); + } + } else { + assert!(grants.is_none(), "{second}"); + } // When flags are omitted, defaults allow read, prompt for write, and deny // execute, network, and host services, with model tools off. Status @@ -181,7 +183,7 @@ fn workspace_commands_persist_cas_permissions_policy_and_audit_results() { "permissions", first_id, "--revision", - "3", + &base.to_string(), "--execute", "true", "--task-network", @@ -190,7 +192,7 @@ fn workspace_commands_persist_cas_permissions_policy_and_audit_results() { ); assert_success(&permissions); let permissions = json_output(&permissions); - assert_eq!(permissions["revision"], 4); + assert_eq!(permissions["revision"], base + 1); let limited = run_cli( &data_root, &[ @@ -198,14 +200,14 @@ fn workspace_commands_persist_cas_permissions_policy_and_audit_results() { "permissions", first_id, "--revision", - "4", + &(base + 1).to_string(), "--create-directory-tool", "prompt", ], ); assert_success(&limited); let limited = json_output(&limited); - assert_eq!(limited["revision"], 5); + assert_eq!(limited["revision"], base + 2); let limits = limited["workspaces"] .as_array() .expect("workspace registrations") @@ -222,7 +224,7 @@ fn workspace_commands_persist_cas_permissions_policy_and_audit_results() { "permissions", first_id, "--revision", - "3", + &base.to_string(), "--read", "false", ], @@ -330,18 +332,7 @@ fn configured_sessions_keep_workspace_ids_and_fail_closed_outside_the_root() { fs::create_dir_all(&workspace).expect("create workspace"); fs::create_dir(&outside_workspace).expect("create outside workspace"); set_root(&data_root, &development_root); - let registration = run_cli( - &data_root, - &[ - "workspace", - "register", - path_arg(&workspace), - "--revision", - "1", - ], - ); - assert_success(®istration); - let expected_id = json_output(®istration)["registration_id"].clone(); + let expected_id = Value::from(register(&data_root, &workspace, 1)); // When new sessions use the same configured workspace, they record its stable ID. let first = run_cli( @@ -918,22 +909,56 @@ fn approvals_are_requested_decided_and_consumed_once() { assert_error_code(&output, "approval"); } +/// Register `workspace` with the core primitive, which records only the +/// registration. The CLI `register` command also grants the workspace's +/// Windows container its folder (ADR-0107); tests of other commands use this +/// so their revisions match on every platform and no AppContainer state +/// outlives them. `workspace_commands_persist_cas_permissions_policy_and_audit_results` +/// covers the command itself. fn register(data_root: &Path, workspace: &Path, revision: u64) -> String { - let output = run_cli( - data_root, - &[ - "workspace", - "register", - path_arg(workspace), - "--revision", - &revision.to_string(), - ], - ); - assert_success(&output); - json_output(&output)["registration_id"] - .as_str() - .expect("registration ID") - .to_owned() + let mut store = ControlStore::open_existing(data_root) + .expect("open settings") + .expect("settings exist"); + store + .register_workspace(workspace, revision) + .expect("register workspace") + .id() + .as_uuid() + .to_string() +} + +/// Revokes every recorded container grant when dropped, so a test that +/// registers through the CLI leaves no ACL entry or AppContainer profile +/// behind, even when it fails. It reports failures and never panics. +struct RevokeGrantsOnDrop<'a>(&'a Path); + +impl Drop for RevokeGrantsOnDrop<'_> { + fn drop(&mut self) { + let status = run_cli(self.0, &["workspace", "status"]); + if !status.status.success() { + return; + } + for grant in json_output(&status)["container_grants"] + .as_array() + .into_iter() + .flatten() + { + let Some(id) = grant["id"].as_str() else { + continue; + }; + let revoked = run_cli_for( + self.0, + &["workspace", "container-revoke", id], + GRANT_CLI_DEADLINE, + ); + if !revoked.status.success() { + eprintln!( + "grant revocation failed during cleanup: {id}: {}", + String::from_utf8_lossy(&revoked.stderr) + ); + } + } + } } #[cfg(windows)] @@ -948,6 +973,7 @@ fn container_grants_are_recorded_listed_and_revoked() { fs::create_dir_all(&workspace).expect("create workspace"); fs::create_dir_all(&toolchain).expect("create toolchain"); set_root(&data_root, &development_root); + let _cleanup = RevokeGrantsOnDrop(&data_root); let id = register(&data_root, &workspace, 1); // When the workspace and the toolchain are granted to its container. @@ -1525,10 +1551,12 @@ fn web_fetch_preference_and_hosts_are_revisioned_and_validated() { assert_control_error(&missing); } -/// A recorded container grant refuses the removal until it is revoked. +/// Unregistering revokes every container grant of the workspace first, then +/// removes the registration; the revocation needs no extra revision +/// (ADR-0107, revising ADR-0081's refusal). #[cfg(windows)] #[test] -fn unregister_is_refused_while_a_container_grant_names_the_workspace() { +fn unregister_revokes_the_workspace_grants_first() { // Given a workspace with a read-write container grant. let temporary = TempDir::new().expect("private temporary directory"); let data_root = temporary.path().join("application-data"); @@ -1536,6 +1564,7 @@ fn unregister_is_refused_while_a_container_grant_names_the_workspace() { let workspace = development_root.join("app"); fs::create_dir_all(&workspace).expect("create workspace"); set_root(&data_root, &development_root); + let _cleanup = RevokeGrantsOnDrop(&data_root); let id = register(&data_root, &workspace, 1); let grant = run_cli( &data_root, @@ -1556,26 +1585,34 @@ fn unregister_is_refused_while_a_container_grant_names_the_workspace() { .expect("grant ID") .to_owned(); - // When unregistering, it is refused and nothing changes. - let refused = run_cli( + // When unregistering with a stale revision, nothing is revoked. + let stale = run_cli( &data_root, - &["workspace", "unregister", &id, "--revision", "3"], + &["workspace", "unregister", &id, "--revision", "2"], ); - assert_control_error(&refused); + assert_control_error(&stale); let status = json_output(&run_cli(&data_root, &["workspace", "status"])); assert_eq!(status["revision"], 3); assert_eq!( - status["workspaces"].as_array().expect("workspaces").len(), + status["container_grants"].as_array().expect("grants").len(), 1 ); - // Then it succeeds once the grant is revoked. - assert_success(&run_cli( - &data_root, - &["workspace", "container-revoke", &grant_id], - )); - assert_success(&run_cli( + // Then the current revision revokes the grant, deleting the container's + // profile, and removes the workspace. + let removed = run_cli_for( &data_root, &["workspace", "unregister", &id, "--revision", "3"], - )); + GRANT_CLI_DEADLINE, + ); + assert_success(&removed); + let removed = json_output(&removed); + assert_eq!( + removed["revoked"], + json!([{"grant_id": grant_id, "profile_deleted": true}]), + "{removed}" + ); + assert_eq!(removed["snapshot"]["revision"], 4); + assert_eq!(removed["snapshot"]["workspaces"], json!([])); + assert!(removed["snapshot"].get("container_grants").is_none()); } diff --git a/crates/omgcode-cli/tests/file_workflow.rs b/crates/omgcode-cli/tests/file_workflow.rs index a81021cf..5311dda1 100644 --- a/crates/omgcode-cli/tests/file_workflow.rs +++ b/crates/omgcode-cli/tests/file_workflow.rs @@ -7,7 +7,8 @@ use tempfile::TempDir; use uuid::Uuid; use support::{ - assert_control_error, assert_error_code, assert_success, json_output, path_arg, run_cli, + assert_control_error, assert_error_code, assert_success, json_output, live_revision, path_arg, + register_workspace, run_cli, }; const FILE_CONTENT: &str = "FILE_BODY_SECRET_9fa0321d2c7e"; @@ -44,18 +45,8 @@ fn workspace_fixture() -> WorkspaceFixture { ); assert_success(&root); assert_eq!(json_output(&root)["revision"], 1); - let registered = run_cli( - &data_root, - &[ - "workspace", - "register", - path_arg(&workspace), - "--revision", - "1", - ], - ); - assert_success(®istered); - let workspace_id = json_output(®istered)["registration_id"] + let registered = register_workspace(&data_root, &workspace, 1); + let workspace_id = registered["registration_id"] .as_str() .expect("workspace ID") .to_owned(); @@ -280,6 +271,7 @@ fn current_read_and_write_preferences_deny_file_operations() { assert_success(&seed); // When trusted settings disable read and write at the current revision. + let revision = live_revision(&fixture.data_root); let permissions = run_cli( &fixture.data_root, &[ @@ -287,7 +279,7 @@ fn current_read_and_write_preferences_deny_file_operations() { "permissions", &fixture.workspace_id, "--revision", - "2", + &revision.to_string(), "--read", "false", "--write", @@ -295,7 +287,7 @@ fn current_read_and_write_preferences_deny_file_operations() { ], ); assert_success(&permissions); - assert_eq!(json_output(&permissions)["revision"], 3); + assert_eq!(json_output(&permissions)["revision"], revision + 1); // Then new reads and writes are denied, and the existing file remains unchanged. let mut read_args = scoped_args(&fixture, "read"); @@ -397,7 +389,7 @@ fn cli_archives_completed_audit_and_inspects_it_after_workspace_selection_change "set-root", path_arg(&next_root), "--revision", - "2", + &live_revision(&fixture.data_root).to_string(), ], )); @@ -506,7 +498,7 @@ fn edit_preview_fails_closed_on_denial_and_invalid_content() { "permissions", &fixture.workspace_id, "--revision", - "2", + &live_revision(&fixture.data_root).to_string(), "--read", "false", ], @@ -536,7 +528,7 @@ fn edit_preview_fails_closed_on_denial_and_invalid_content() { "permissions", &fixture.workspace_id, "--revision", - "3", + &live_revision(&fixture.data_root).to_string(), "--read", "true", ], diff --git a/crates/omgcode-cli/tests/package_credential_workflow.rs b/crates/omgcode-cli/tests/package_credential_workflow.rs index 353f73de..849bf600 100644 --- a/crates/omgcode-cli/tests/package_credential_workflow.rs +++ b/crates/omgcode-cli/tests/package_credential_workflow.rs @@ -18,7 +18,7 @@ use omgcode_core::control::{CredentialError, CredentialId, CredentialStore}; use serde_json::Value; use support::{ CLI_DEADLINE, assert_control_error, assert_error_code, assert_success, cli_command, - json_output, path_arg, run_cli, run_with_deadline, + json_output, path_arg, register_workspace, run_cli, run_with_deadline, }; use tempfile::TempDir; @@ -122,18 +122,8 @@ fn scene(origin: &str) -> Scene { &data, &["workspace", "set-root", path_arg(&root), "--revision", "0"], )); - let registered = run_cli( - &data, - &[ - "workspace", - "register", - path_arg(&workspace), - "--revision", - &revision(&data).to_string(), - ], - ); - assert_success(®istered); - let workspace_id = json_output(®istered)["registration_id"] + let registered = register_workspace(&data, &workspace, revision(&data)); + let workspace_id = registered["registration_id"] .as_str() .expect("workspace id") .to_owned(); diff --git a/crates/omgcode-cli/tests/packages_workflow.rs b/crates/omgcode-cli/tests/packages_workflow.rs index e51f9245..cc7c5672 100644 --- a/crates/omgcode-cli/tests/packages_workflow.rs +++ b/crates/omgcode-cli/tests/packages_workflow.rs @@ -10,7 +10,9 @@ use std::path::Path; use std::thread::{self, JoinHandle}; use std::time::{Duration, Instant}; -use support::{assert_error_code, assert_success, json_output, path_arg, run_cli}; +use support::{ + assert_error_code, assert_success, json_output, path_arg, register_workspace, run_cli, +}; use tempfile::TempDir; const PROFILE: &str = "registries"; @@ -121,18 +123,8 @@ fn a_trusted_fetch_writes_a_private_cache_and_is_audited() { ); assert_success(&output); let initial_revision = json_output(&output)["revision"].as_u64().expect("revision"); - let output = run_cli( - &data_root, - &[ - "workspace", - "register", - path_arg(&workspace), - "--revision", - &initial_revision.to_string(), - ], - ); - assert_success(&output); - let id = json_output(&output)["registration_id"] + let registered = register_workspace(&data_root, &workspace, initial_revision); + let id = registered["registration_id"] .as_str() .expect("workspace id") .to_owned(); diff --git a/crates/omgcode-cli/tests/run_workflow.rs b/crates/omgcode-cli/tests/run_workflow.rs index 3b9e873b..fe0bf656 100644 --- a/crates/omgcode-cli/tests/run_workflow.rs +++ b/crates/omgcode-cli/tests/run_workflow.rs @@ -163,6 +163,12 @@ fn an_ungranted_profile_root_is_named_by_its_profile_and_position() { fs::create_dir(&tools).expect("tools"); // The system root is root 1, so the ungranted folder is root 2. assert_success(&scene.add_profile("system", &[&tools])); + // Assigning the profile granted the folder (ADR-0107). Revoking that + // grant, as an operator can later, leaves the profile assigned and the + // folder ungranted. + let granted = scene.recorded_grants("read_execute"); + assert_eq!(granted.len(), 1, "{granted:?}"); + assert_success(&scene.revoke(&granted[0])); let output = scene.run("system", &[], &shell("echo ran>ran.txt")); assert_error_code(&output, "run"); assert!( @@ -361,6 +367,14 @@ fn refused_runs_record_nothing() { let output = scene.run("missing", &[], &echo); assert!(error_message(&output).contains("not recorded")); + assert_success(&scene.record_profile("unassigned", &[])); + let output = scene.run("unassigned", &[], &echo); + assert_error_code(&output, "run"); + assert!( + error_message(&output).contains("not assigned to this workspace"), + "{}", + error_message(&output) + ); let output = scene.run("system", &["--host-services"], &echo); assert!(error_message(&output).contains(if cfg!(windows) { "not available on Windows" @@ -493,7 +507,8 @@ fn a_networked_run_fetches_over_tls() { scene.close(); } -/// Windows needs a recorded read-write grant on the workspace. +/// Windows needs a recorded read-write grant on the workspace. Registering +/// applies it; this scene revokes it. #[cfg(windows)] #[test] fn windows_runs_need_the_workspace_grant() { @@ -510,15 +525,13 @@ fn windows_runs_need_the_workspace_grant() { } /// A moved or replaced profile root is stale and refused; it is usable again -/// once the recorded directory is back. +/// once the recorded directory is back. On Windows, assigning the profile +/// grants the folder. #[test] fn stale_profiles_are_refused() { - let mut scene = Scene::new(); + let scene = Scene::new(); let tools = scene.path("tools"); fs::create_dir(&tools).expect("tools"); - if cfg!(windows) { - scene.grant(&tools, "read-execute"); - } assert_success(&scene.add_profile("system", &[&tools])); run_json(&scene.run("system", &[], &shell("echo fresh"))); fs::rename(&tools, scene.path("tools-old")).expect("move tools"); @@ -891,6 +904,190 @@ fn removing_the_profile_stops_a_live_run() { scene.close(); } +/// Unassigning the run's profile from its workspace stops the run before the +/// command reports, although the profile is still recorded (ADR-0107). +#[test] +fn unassigning_the_profile_stops_a_live_run() { + let scene = Scene::new(); + assert_success(&scene.add_profile("system", &[])); + let child = scene + .command(&[], &shell(LONG_RUN)) + .spawn() + .expect("spawn run"); + wait_for_start(&scene); + let revision = scene.revision().to_string(); + let output = scene.settings_cli(&[ + "workspace", + "profile-unassign", + &scene.id, + "system", + "--revision", + &revision, + ]); + assert_success(&output); + // The system root needs no grant, so nothing was revoked. + assert_eq!(json_output(&output)["revoked"], serde_json::json!([])); + assert_eq!(scene.audit()["pending"], Value::Array(Vec::new())); + let run = run_json(&wait(child, Duration::from_secs(30))); + assert_eq!(run["finish"]["result"]["kind"], "revoked"); + assert!( + run["revoked_because"] + .as_str() + .expect("reason") + .contains("unassigned"), + "{run}" + ); + let output = scene.cli(&["workspace", "profile-show", "system"]); + assert_success(&output); + scene.close(); +} + +/// Assigning a profile grants the workspace's container each folder it +/// cannot read, and the run then starts; unassigning revokes that grant +/// and keeps the workspace's own read-write grant (ADR-0107). +#[cfg(windows)] +#[test] +fn assigning_a_profile_grants_its_folder_and_unassigning_revokes_it() { + let scene = Scene::new(); + let tools = scene.path("assigned-tools"); + fs::create_dir(&tools).expect("tools"); + assert_success(&scene.record_profile("system", &[&tools])); + let output = scene.run("system", &[], &shell("echo unassigned")); + assert!( + error_message(&output).contains("not assigned to this workspace"), + "{}", + error_message(&output) + ); + assert!(scene.recorded_grants("read_execute").is_empty()); + + let output = scene.assign("system"); + assert_success(&output); + let assigned = json_output(&output); + let granted = assigned["granted"].as_array().expect("granted"); + assert_eq!(granted.len(), 1, "{assigned}"); + assert_eq!( + fs::canonicalize(granted[0]["path"].as_str().expect("path")).expect("granted path"), + fs::canonicalize(&tools).expect("tools path"), + ); + assert_eq!(assigned["not_granted"], serde_json::json!([]), "{assigned}"); + let grant = granted[0]["grant_id"] + .as_str() + .expect("grant id") + .to_owned(); + assert_eq!( + scene.recorded_grants("read_execute"), + std::slice::from_ref(&grant) + ); + assert_eq!( + assigned["snapshot"]["workspaces"][0]["assigned_profiles"], + serde_json::json!([assigned["assigned_profile_id"]]), + "{assigned}" + ); + // Every root is checked before the program starts, so a started run + // shows the container can read the granted folder. + run_json(&scene.run("system", &[], &shell("echo granted"))); + assert_control_error(&scene.assign("system")); + + let revision = scene.revision().to_string(); + let output = scene.settings_cli(&[ + "workspace", + "profile-unassign", + &scene.id, + "system", + "--revision", + &revision, + ]); + assert_success(&output); + let unassigned = json_output(&output); + assert_eq!( + unassigned["revoked"], + serde_json::json!([{"grant_id": grant, "profile_deleted": false}]), + "{unassigned}" + ); + assert!(scene.recorded_grants("read_execute").is_empty()); + assert_eq!(scene.recorded_grants("read_write").len(), 1); + let output = scene.run("system", &[], &shell("echo unassigned")); + assert!(error_message(&output).contains("not assigned to this workspace")); + scene.close(); +} + +/// Removing an assigned profile revokes the grants on its folders that no +/// other profile assigned to the workspace needs (ADR-0107). +#[cfg(windows)] +#[test] +fn removing_an_assigned_profile_revokes_only_its_unshared_grants() { + let scene = Scene::new(); + let own = scene.path("own-tools"); + let shared = scene.path("shared-tools"); + fs::create_dir(&own).expect("own tools"); + fs::create_dir(&shared).expect("shared tools"); + assert_success(&scene.add_profile("system", &[&own, &shared])); + assert_success(&scene.add_profile("other", &[&shared])); + let before = scene.recorded_grants("read_execute"); + assert_eq!(before.len(), 2, "{before:?}"); + let revision = scene.revision().to_string(); + let output = scene.settings_cli(&[ + "workspace", + "profile-remove", + "system", + "--revision", + &revision, + ]); + assert_success(&output); + let removed = json_output(&output); + let revoked: Vec<&str> = removed["revoked"] + .as_array() + .expect("revoked") + .iter() + .map(|revocation| revocation["grant_id"].as_str().expect("grant id")) + .collect(); + assert_eq!(revoked.len(), 1, "{removed}"); + let after = scene.recorded_grants("read_execute"); + assert_eq!(after.len(), 1, "{after:?}"); + assert!(!after.iter().any(|grant| grant == revoked[0])); + // The remaining profile still runs with its grant. + run_json(&scene.run("other", &[], &shell("echo shared"))); + scene.close(); +} + +/// Unregistering a workspace revokes every grant of its container first, +/// then removes the registration (ADR-0107). +#[cfg(windows)] +#[test] +fn unregistering_revokes_the_workspace_grants() { + let scene = Scene::new(); + let tools = scene.path("tools"); + fs::create_dir(&tools).expect("tools"); + assert_success(&scene.add_profile("system", &[&tools])); + assert_eq!(scene.recorded_grants("read_execute").len(), 1); + assert_eq!(scene.recorded_grants("read_write").len(), 1); + let revision = scene.revision().to_string(); + let output = scene.settings_cli(&[ + "workspace", + "unregister", + &scene.id, + "--revision", + &revision, + ]); + assert_success(&output); + let unregistered = json_output(&output); + let revoked = unregistered["revoked"].as_array().expect("revoked"); + assert_eq!(revoked.len(), 2, "{unregistered}"); + // The last revocation deleted the container's profile. + assert_eq!(revoked[1]["profile_deleted"], true, "{unregistered}"); + // Status leaves out an empty grant list. + assert!( + unregistered["snapshot"].get("container_grants").is_none(), + "{unregistered}" + ); + assert_eq!( + unregistered["snapshot"]["workspaces"], + serde_json::json!([]), + "{unregistered}" + ); + scene.close(); +} + /// A run whose access a settings change withdrew stops even when another /// change restores that access before the run's watcher reads the settings /// (ADR-0061). The test makes that race certain: under one hold of the diff --git a/crates/omgcode-cli/tests/skills_workflow.rs b/crates/omgcode-cli/tests/skills_workflow.rs index 5c0bcb88..5770e856 100644 --- a/crates/omgcode-cli/tests/skills_workflow.rs +++ b/crates/omgcode-cli/tests/skills_workflow.rs @@ -3,7 +3,9 @@ mod support; use serde_json::Value; use std::fs; use std::path::{Path, PathBuf}; -use support::{assert_error_code, assert_success, json_output, path_arg, run_cli}; +use support::{ + assert_error_code, assert_success, json_output, path_arg, register_workspace, run_cli, +}; use tempfile::TempDir; const SKILL_MD: &str = @@ -58,18 +60,7 @@ fn scene() -> Scene { ], ); assert_success(&root); - let registered = run_cli( - &data, - &[ - "workspace", - "register", - path_arg(&workspace), - "--revision", - "1", - ], - ); - assert_success(®istered); - let registered = json_output(®istered); + let registered = register_workspace(&data, &workspace, 1); Scene { _temporary: temporary, data, diff --git a/crates/omgcode-cli/tests/support/mod.rs b/crates/omgcode-cli/tests/support/mod.rs index 4d4cf1fb..fc7734e8 100644 --- a/crates/omgcode-cli/tests/support/mod.rs +++ b/crates/omgcode-cli/tests/support/mod.rs @@ -196,3 +196,67 @@ pub(crate) fn assert_control_error(output: &Output) { pub(crate) fn path_arg(path: &Path) -> &str { path.to_str().expect("temporary paths are Unicode") } + +/// Maximum time for a CLI command that changes a container grant. On +/// Windows it creates or deletes the workspace's AppContainer profile as +/// well as updating access-control lists. +pub(crate) const GRANT_CLI_DEADLINE: Duration = Duration::from_secs(120); + +/// Register `workspace` through the CLI at `revision` and return the JSON +/// output, failing the test on error. +/// +/// On Windows, registering also grants the workspace's container read and +/// write access to its folder (ADR-0107). Tests that use this run no +/// program, so the grant is revoked at once; revoking a container's last +/// grant deletes its profile, so no per-user AppContainer state outlives the +/// test. The grant advanced the revision, so the output's +/// `snapshot.revision` is one higher on Windows than on Linux; read the live +/// revision rather than counting. +#[allow( + dead_code, + reason = "only test binaries that register without a run scene use it" +)] +pub(crate) fn register_workspace( + data_root: &Path, + workspace: &Path, + revision: u64, +) -> serde_json::Value { + let revision = revision.to_string(); + let output = run_cli_for( + data_root, + &[ + "workspace", + "register", + path_arg(workspace), + "--revision", + &revision, + ], + GRANT_CLI_DEADLINE, + ); + assert_success(&output); + let registered = json_output(&output); + if let Some(grant) = registered["grant_id"].as_str() { + assert_success(&run_cli_for( + data_root, + &["workspace", "container-revoke", grant], + GRANT_CLI_DEADLINE, + )); + } + assert_eq!( + registered.get("grant_id").is_some(), + cfg!(windows), + "{registered}" + ); + registered +} + +/// The live settings revision from `workspace status`. +#[allow( + dead_code, + reason = "only test binaries that register without a run scene use it" +)] +pub(crate) fn live_revision(data_root: &Path) -> u64 { + let output = run_cli(data_root, &["workspace", "status"]); + assert_success(&output); + json_output(&output)["revision"].as_u64().expect("revision") +} diff --git a/crates/omgcode-cli/tests/support/run_scene.rs b/crates/omgcode-cli/tests/support/run_scene.rs index 53c6b936..7ad75448 100644 --- a/crates/omgcode-cli/tests/support/run_scene.rs +++ b/crates/omgcode-cli/tests/support/run_scene.rs @@ -20,11 +20,13 @@ const GRANT_DEADLINE: Duration = Duration::from_secs(300); pub(crate) const SETTINGS_DEADLINE: Duration = Duration::from_secs(90); /// A development root with one registered workspace whose `execute` -/// preference is on, and, on Windows, a read-write grant on the workspace. +/// preference is on, and, on Windows, the read-write grant on the workspace +/// that `register` applies (ADR-0107). /// -/// End each test with [`Scene::close`], which revokes every grant and fails -/// the test if a revocation fails. `Drop` is only a fallback for a test that -/// already failed: it tries the same revocations and reports, never panics. +/// End each test with [`Scene::close`], which revokes every grant of the +/// workspace, tracked or recorded, and fails the test if a revocation fails. +/// `Drop` is only a fallback for a test that already failed: it tries the +/// same revocations and reports, never panics. pub(crate) struct Scene { pub(crate) temporary: TempDir, pub(crate) data: PathBuf, @@ -52,28 +54,67 @@ impl Scene { temporary, }; assert_success(&scene.cli(&["workspace", "set-root", path_arg(&root), "--revision", "0"])); - let registered = scene.cli(&[ - "workspace", - "register", - path_arg(&scene.workspace.clone()), - "--revision", - "1", - ]); - assert_success(®istered); - scene.id = json_output(®istered)["registration_id"] + let registered = run_cli_for( + &scene.data, + &[ + "workspace", + "register", + path_arg(&scene.workspace), + "--revision", + "1", + ], + GRANT_DEADLINE, + ); + // A failed registration can still leave a pending grant whose ACL + // entry exists, so track what was recorded before failing. + if !registered.status.success() { + scene.track_recorded_grants(); + assert_success(®istered); + } + let registered = json_output(®istered); + scene.id = registered["registration_id"] .as_str() .expect("workspace id") .to_owned(); + let own = registered["grant_id"].as_str().map(str::to_owned); + assert_eq!(own.is_some(), cfg!(windows), "{registered}"); + scene.grants.extend(own.clone()); if execute { scene.set_permission("--execute", "true"); } - if grant && cfg!(windows) { - let workspace = scene.workspace.clone(); - scene.grant(&workspace, "read-write"); + if let Some(own) = own.filter(|_| !grant) { + assert_success(&scene.revoke(&own)); + scene.grants.retain(|tracked| tracked != &own); } scene } + /// Revoke one grant through the CLI, waiting for the runs it withdraws. + pub(crate) fn revoke(&self, grant: &str) -> Output { + run_cli_for( + &self.data, + &["workspace", "container-revoke", grant], + GRANT_DEADLINE, + ) + } + + /// The identifiers of this workspace's recorded grants with `access` + /// (`read_execute` or `read_write`), in the order `status` lists them. + pub(crate) fn recorded_grants(&self, access: &str) -> Vec { + let output = self.cli(&["workspace", "status"]); + assert_success(&output); + json_output(&output)["container_grants"] + .as_array() + .into_iter() + .flatten() + .filter(|grant| { + grant["workspace_id"].as_str() == Some(self.id.as_str()) + && grant["access"].as_str() == Some(access) + }) + .map(|grant| grant["id"].as_str().expect("grant id").to_owned()) + .collect() + } + pub(crate) fn cli(&self, args: &[&str]) -> Output { run_cli(&self.data, args) } @@ -111,19 +152,28 @@ impl Scene { ); } - /// Add every recorded grant of this workspace that is not yet tracked. + /// Track exactly the recorded grants: add each one not yet tracked, and + /// forget a tracked one that a command such as `unregister` already + /// revoked. The scene's data directory is its own, so every grant in it + /// is the scene's, including one recorded by a registration that failed + /// before its identifier was known. When status cannot be read, the + /// tracked list is kept. fn track_recorded_grants(&mut self) { let output = self.cli(&["workspace", "status"]); if !output.status.success() { return; } let status = json_output(&output); - for grant in status["container_grants"].as_array().into_iter().flatten() { - if grant["workspace_id"].as_str() == Some(self.id.as_str()) - && let Some(id) = grant["id"].as_str() - && !self.grants.iter().any(|known| known == id) - { - self.grants.push(id.to_owned()); + let recorded: Vec = status["container_grants"] + .as_array() + .into_iter() + .flatten() + .filter_map(|grant| grant["id"].as_str().map(str::to_owned)) + .collect(); + self.grants.retain(|known| recorded.contains(known)); + for id in recorded { + if !self.grants.contains(&id) { + self.grants.push(id); } } } @@ -134,11 +184,14 @@ impl Scene { assert!(failures.is_empty(), "grant revocation failed: {failures:?}"); } - /// Revoke each tracked grant once, returning the failures. Revoking the - /// last grant also deletes the container profile, so test runs leave no - /// per-user AppContainer state behind. A grant whose revocation failed - /// stays tracked, so `Drop` retries it after `close` fails. + /// Revoke each tracked grant, and each recorded grant of the workspace, + /// such as those `profile-assign` applied, once, returning the failures. + /// Revoking the last grant also deletes the container profile, so test + /// runs leave no per-user AppContainer state behind. A grant whose + /// revocation failed stays tracked, so `Drop` retries it after `close` + /// fails. fn revoke_grants(&mut self) -> Vec { + self.track_recorded_grants(); let mut failures = Vec::new(); let mut unresolved = Vec::new(); for grant in std::mem::take(&mut self.grants) { @@ -186,8 +239,37 @@ impl Scene { run_cli_for(&self.data, args, SETTINGS_DEADLINE) } - /// Record the system profile, plus any extra roots. + /// Assign a recorded profile to the workspace, as an operator does once + /// before its first run. On Windows this grants the profile's folders + /// that the container cannot read; [`Self::close`] revokes them. + pub(crate) fn assign(&self, name: &str) -> Output { + let revision = self.revision().to_string(); + run_cli_for( + &self.data, + &[ + "workspace", + "profile-assign", + &self.id, + name, + "--revision", + &revision, + ], + GRANT_DEADLINE, + ) + } + + /// Record and assign the system profile, plus any extra roots. Returns + /// the `profile-add` output; a successful add must also assign. pub(crate) fn add_profile(&self, name: &str, extra_roots: &[&Path]) -> Output { + let added = self.record_profile(name, extra_roots); + if added.status.success() { + assert_success(&self.assign(name)); + } + added + } + + /// Record the system profile, plus any extra roots, without assigning it. + pub(crate) fn record_profile(&self, name: &str, extra_roots: &[&Path]) -> Output { let system = system_root(); let search = system_path(); let revision = self.revision().to_string(); @@ -207,13 +289,30 @@ impl Scene { self.cli(&args) } - /// Record a profile with explicit roots, PATH entries, and variables. + /// Record and assign a profile with explicit roots, PATH entries, and + /// variables. Returns the `profile-add` output. pub(crate) fn add_profile_with( &self, name: &str, roots: &[PathBuf], path_entries: &[PathBuf], environment: &[(String, String)], + ) -> Output { + let added = self.record_profile_with(name, roots, path_entries, environment); + if added.status.success() { + assert_success(&self.assign(name)); + } + added + } + + /// Record a profile with explicit roots, PATH entries, and variables, + /// without assigning it. + pub(crate) fn record_profile_with( + &self, + name: &str, + roots: &[PathBuf], + path_entries: &[PathBuf], + environment: &[(String, String)], ) -> Output { let revision = self.revision().to_string(); let variables: Vec = environment diff --git a/crates/omgcode-core/src/control.rs b/crates/omgcode-core/src/control.rs index 219f0eb2..51eeba4f 100644 --- a/crates/omgcode-core/src/control.rs +++ b/crates/omgcode-core/src/control.rs @@ -23,6 +23,7 @@ use crate::storage::{self, StorageError}; use crate::workspace::DirectoryRecord; mod approval; +mod assignment; mod container; mod credential; mod package; @@ -39,6 +40,9 @@ pub use approval::{ MAX_APPROVALS, MAX_PENDING_APPROVALS, MIN_APPROVAL_TTL_SECS, now_unix, }; +pub use assignment::{ + PlannedFolder, ProfileAccessPlan, ProfileAssignment, RegisteredWorkspace, Revocations, +}; pub use container::{ ContainerGrant, ContainerGrantAccess, ContainerGrantState, ContainerGrantStatus, ContainerRevocation, RootGrantNeed, container_name, root_grant_need, @@ -210,6 +214,10 @@ pub struct WorkspaceRegistration { /// replay, so a registration event neither writes nor reads it. #[serde(skip)] web_fetch_hosts: Vec, + /// The toolchain profiles the workspace may run, in assignment order + /// (ADR-0107). Derived from `Profile*ssigned` events on replay. + #[serde(skip)] + profiles: Vec, } impl WorkspaceRegistration { @@ -341,6 +349,9 @@ struct WorkspaceView<'a> { id: WorkspaceId, directory: &'a DirectoryRecord, permissions: PermissionView<'a>, + /// The assigned toolchain profiles, by identifier (ADR-0107). + #[serde(skip_serializing_if = "<[Uuid]>::is_empty")] + assigned_profiles: &'a [Uuid], } /// Every preference, including denied optional ones and unrestricted @@ -378,6 +389,7 @@ fn serialize_workspace_views( web_fetch_hosts: &workspace.web_fetch_hosts, write_tools: permissions.write_tools, }, + assigned_profiles: &workspace.profiles, } })) } @@ -450,6 +462,18 @@ enum Action { ProfileRemoved { profile_id: Uuid, }, + /// The workspace may run this toolchain profile (ADR-0107). + ProfileAssigned { + #[serde(deserialize_with = "deserialize_workspace_id")] + workspace_id: WorkspaceId, + profile_id: Uuid, + }, + /// The workspace no longer runs this toolchain profile. + ProfileUnassigned { + #[serde(deserialize_with = "deserialize_workspace_id")] + workspace_id: WorkspaceId, + profile_id: Uuid, + }, PackageProfileAdded { profile: PackageProfile, }, @@ -1158,6 +1182,7 @@ impl ControlStore { directory, permissions: PermissionSet::default(), web_fetch_hosts: Vec::new(), + profiles: Vec::new(), }; self.append( Action::WorkspaceRegistered { @@ -1178,10 +1203,12 @@ impl ControlStore { /// the revision change makes every outstanding approval unusable. /// Registering the same folder again assigns a new identifier. /// - /// Refuses while any container grant, in any state, names the workspace: - /// the operator must revoke it first so no ACL is stranded. The caller - /// holds the settings lock, and removes the workspace's instructions file - /// itself under the preferences lock. + /// Refuses while any container grant, in any state, names the workspace, + /// so no ACL is stranded; the operator surfaces use + /// [`Self::unregister_workspace_with_access`], which revokes them first + /// (ADR-0107). The event also drops the workspace's profile assignments. + /// The caller holds the settings lock, and removes the workspace's + /// instructions file itself under the preferences lock. pub fn unregister_workspace( &mut self, id: WorkspaceId, @@ -1677,6 +1704,9 @@ impl ControlStore { Action::ProfileAdded { .. } | Action::ProfileRemoved { .. } => { profile::apply(state, &entry.action, revision)?; } + Action::ProfileAssigned { .. } | Action::ProfileUnassigned { .. } => { + assignment::apply(state, &entry.action)?; + } Action::WebFetchHostAdded { .. } | Action::WebFetchHostRemoved { .. } => { web_hosts::apply(state, &entry.action)?; } diff --git a/crates/omgcode-core/src/control/assignment.rs b/crates/omgcode-core/src/control/assignment.rs new file mode 100644 index 00000000..60b12412 --- /dev/null +++ b/crates/omgcode-core/src/control/assignment.rs @@ -0,0 +1,785 @@ +//! Toolchain profiles assigned to a workspace, and the container access the +//! operator's assignment grants (ADR-0107). +//! +//! A workspace runs only the profiles assigned to it. Assigning a profile is +//! the operator's consent to give that workspace's Windows container read and +//! execute access to each of the profile's roots it cannot read yet, and +//! registering a workspace is the consent to give it read and write access to +//! its own folder. Unassigning a profile, removing it, or unregistering the +//! workspace revokes the grants that no remaining assignment needs. +//! +//! [`ControlStore::assign_profile`] and [`ControlStore::unassign_profile`] +//! record the assignment only and change no access-control list. The +//! `*_with_access` methods are for the trusted operator surfaces, the CLI and +//! the `settings` window. They grant and revoke through +//! [`ControlStore::grant_container_access`] and +//! [`ControlStore::revoke_container_grant`], so every grant is checked, +//! recorded, and revocable like any other. Off Windows they record the same +//! events and change no access. + +use std::path::{Path, PathBuf}; + +use omgcode_platform::container::{self as platform, CONTAINER_GRANTS_SUPPORTED}; +use uuid::Uuid; + +use super::{ + Action, ContainerGrant, ContainerGrantAccess, ContainerRevocation, ControlError, + ControlSnapshot, ControlStore, ProfilePlatform, RootGrantNeed, WorkspaceRegistration, + root_grant_need, +}; +use crate::policy::WorkspaceId; +use crate::workspace::DirectoryRecord; + +/// One folder an assignment would grant, or leave out. Two planned folders +/// are equal when they are the same directory, however their paths are +/// spelled, so a plan made from discovered paths matches the plan made again +/// from the recorded roots. +#[derive(Clone, Debug)] +pub struct PlannedFolder { + path: PathBuf, + display: String, + /// The directory's identity, when it could be read. + record: Option, +} + +impl PartialEq for PlannedFolder { + fn eq(&self, other: &Self) -> bool { + match (&self.record, &other.record) { + (Some(own), Some(theirs)) => own.same_directory(theirs), + (None, None) => self.path == other.path, + _ => false, + } + } +} + +impl Eq for PlannedFolder {} + +impl PlannedFolder { + /// The folder. Show it only on trusted operator surfaces; never add it to + /// text a model receives. + #[must_use] + pub fn path(&self) -> &Path { + &self.path + } + + /// The folder as display-safe text. Never reopen a path from it. + #[must_use] + pub fn display(&self) -> &str { + &self.display + } +} + +/// The folders assigning a profile to a workspace would grant that +/// workspace's container, planned before the operator confirms. Planning +/// changes and records nothing, and the answer can change before the +/// assignment, which plans again and refuses a different list. +#[derive(Clone, Debug, Default, Eq, PartialEq)] +pub struct ProfileAccessPlan { + grant: Vec, + administrator: Vec, + unknown: Vec, +} + +impl ProfileAccessPlan { + /// The folders to grant read and execute, in profile order: each root the + /// container cannot read that this account can grant, leaving out a root + /// inside another planned one and a root that already has a grant of the + /// workspace. Empty off Windows. + #[must_use] + pub fn to_grant(&self) -> &[PlannedFolder] { + &self.grant + } + + /// Roots the container cannot read that only an administrator can grant. + /// They are left out, and a run that needs one is refused (ADR-0106). + #[must_use] + pub fn needs_administrator(&self) -> &[PlannedFolder] { + &self.administrator + } + + /// Roots whose access could not be read, or that are no longer at their + /// recorded location. They are left out. + #[must_use] + pub fn unknown(&self) -> &[PlannedFolder] { + &self.unknown + } + + fn paths(&self) -> Vec { + self.grant + .iter() + .map(|folder| folder.path.clone()) + .collect() + } +} + +/// What assigning profiles with their access did. +#[derive(Debug)] +pub struct ProfileAssignment { + /// The assigned profiles, in the order named. + pub profile_ids: Vec, + /// The grants applied before the assignments were recorded, in plan + /// order. + pub granted: Vec, + /// The plan the assignment applied, with the folders it left out. + pub plan: ProfileAccessPlan, +} + +/// A registration made by [`ControlStore::register_workspace_with_access`]. +#[derive(Debug)] +pub struct RegisteredWorkspace { + /// The registration, new or the existing one for the same folder. + pub registration: WorkspaceRegistration, + /// The read-write grant on its folder applied now, if one was needed. + /// A failed grant leaves the workspace registered; a grant whose + /// access-control change failed stays `pending` until it is revoked. + pub grant: Result, ControlError>, +} + +/// The revocations an operator change made after it was recorded. +#[derive(Debug, Default)] +pub struct Revocations { + /// The confirmed revocations, in order. + pub revoked: Vec, + /// The first revocation that failed, with its grant; later ones were not + /// attempted. The grant stays recorded, `revoking` when its access-control + /// change failed, and `workspace container-revoke` retries it. + pub failure: Option<(Uuid, ControlError)>, + /// The workspace of each grant whose revocation was attempted, confirmed + /// or not, each once, in order. A revocation withdraws every run of its + /// workspace, which the settings alone do not show, so a caller waits + /// for the runs of these workspaces that it listed before the change. + pub workspaces: Vec, +} + +impl Revocations { + /// The runs in `pending`, listed by `run::pending_runs` before the change, + /// that belong to a workspace in [`Self::workspaces`]. + #[must_use] + pub fn withdrawn_runs(&self, pending: &[(WorkspaceId, Uuid)]) -> Vec { + pending + .iter() + .filter(|(workspace, _)| self.workspaces.contains(workspace)) + .map(|(_, run)| *run) + .collect() + } +} + +impl ControlStore { + /// The profiles assigned to `workspace_id`, by identifier, in the order + /// they were assigned. Empty for an unknown workspace. Configuration only. + pub fn assigned_profiles(&self, workspace_id: WorkspaceId) -> &[Uuid] { + self.workspace(workspace_id) + .map_or(&[], |workspace| workspace.profiles.as_slice()) + } + + /// Whether `profile_id` is assigned to `workspace_id`. + pub fn profile_assigned(&self, workspace_id: WorkspaceId, profile_id: Uuid) -> bool { + self.assigned_profiles(workspace_id).contains(&profile_id) + } + + /// Record that `workspace_id` may run the profile `name`, without + /// changing any access. This advances the settings revision. The operator + /// surfaces use [`Self::assign_profile_with_access`]. + /// + /// # Errors + /// + /// Refuses a stale revision, an unknown workspace or profile, a profile + /// declared on another platform, and a profile already assigned. + pub fn assign_profile( + &mut self, + workspace_id: WorkspaceId, + name: &str, + expected_revision: u64, + ) -> Result { + self.check_revision(expected_revision)?; + let profile_id = self.assignable(workspace_id, name)?; + self.append( + Action::ProfileAssigned { + workspace_id, + profile_id, + }, + self.next_revision()?, + )?; + Ok(profile_id) + } + + /// Record that `workspace_id` no longer runs the profile `name`, without + /// changing any access. This advances the settings revision and withdraws + /// the workspace's runs of that profile. The operator surfaces use + /// [`Self::unassign_profile_with_access`]. + /// + /// # Errors + /// + /// Refuses a stale revision, an unknown workspace or profile, and a + /// profile that is not assigned to the workspace. + pub fn unassign_profile( + &mut self, + workspace_id: WorkspaceId, + name: &str, + expected_revision: u64, + ) -> Result { + self.check_revision(expected_revision)?; + let workspace = self + .workspace(workspace_id) + .ok_or(ControlError::UnknownWorkspace)?; + let profile_id = self + .profile(name) + .ok_or(ControlError::UnknownProfile)? + .profile() + .id(); + if !workspace.profiles.contains(&profile_id) { + return Err(ControlError::ProfileRefused( + "the profile is not assigned to this workspace", + )); + } + self.append( + Action::ProfileUnassigned { + workspace_id, + profile_id, + }, + self.next_revision()?, + )?; + Ok(profile_id) + } + + /// Plan the grants assigning the profile `name` to `workspace_id` would + /// make. This reads access-control lists and changes nothing. + /// + /// # Errors + /// + /// What [`Self::assign_profile`] refuses, apart from the revision. + pub fn plan_profile_access( + &self, + workspace_id: WorkspaceId, + name: &str, + ) -> Result { + self.plan_profiles_access(workspace_id, &[name]) + } + + /// Plan the grants assigning every profile in `names` to `workspace_id` + /// would make, as one list over all their roots in order. + /// + /// # Errors + /// + /// What [`Self::assign_profile`] refuses for any of them, apart from the + /// revision, and a profile named twice. + pub fn plan_profiles_access( + &self, + workspace_id: WorkspaceId, + names: &[&str], + ) -> Result { + let mut ids = Vec::with_capacity(names.len()); + for name in names { + let id = self.assignable(workspace_id, name)?; + if ids.contains(&id) { + return Err(ControlError::ProfileRefused("a profile is named twice")); + } + ids.push(id); + } + let mut plan = ProfileAccessPlan::default(); + if !CONTAINER_GRANTS_SUPPORTED { + return Ok(plan); + } + let mut live = Vec::new(); + for name in names { + let status = self.profile(name).ok_or(ControlError::UnknownProfile)?; + for root in status.profile().read_only_roots() { + match root.is_current() { + Ok(true) => live.push(root.live_path()?), + Ok(false) | Err(_) => { + let folder = PlannedFolder { + path: root.live_path().unwrap_or_default(), + display: root.display(), + record: None, + }; + if !plan.unknown.contains(&folder) { + plan.unknown.push(folder); + } + } + } + } + } + self.plan_into(workspace_id, &live, &mut plan); + Ok(plan) + } + + /// Plan read-execute grants of `paths` for `workspace_id` as + /// [`Self::plan_profile_access`] does for a profile's roots, for folders + /// that are not recorded yet, such as discovered toolchains (ADR-0103). + /// + /// # Errors + /// + /// An unknown workspace. + pub fn plan_folder_access( + &self, + workspace_id: WorkspaceId, + paths: &[PathBuf], + ) -> Result { + if self.workspace(workspace_id).is_none() { + return Err(ControlError::UnknownWorkspace); + } + let mut plan = ProfileAccessPlan::default(); + if CONTAINER_GRANTS_SUPPORTED { + self.plan_into(workspace_id, paths, &mut plan); + } + Ok(plan) + } + + /// Grant the folders the operator confirmed in `confirmed`, then record + /// the assignment, under this store's lock. The plan is made again first: + /// a different list of folders to grant refuses the assignment, so the + /// operator never grants a folder they did not see. Each grant goes + /// through [`Self::grant_container_access`] and advances the revision. + /// + /// # Errors + /// + /// What [`Self::assign_profile`] refuses; a changed plan; a folder core's + /// grant rules refuse, before anything is recorded; and the first grant + /// that fails. Grants applied before a failure stay recorded, the profile + /// is then not assigned, and a grant whose access-control change failed + /// stays `pending` until it is revoked. + pub fn assign_profile_with_access( + &mut self, + workspace_id: WorkspaceId, + name: &str, + confirmed: &ProfileAccessPlan, + expected_revision: u64, + ) -> Result { + self.assign_profiles_with_access(workspace_id, &[name], confirmed, expected_revision) + } + + /// As [`Self::assign_profile_with_access`] for every profile in `names` + /// under one confirmed plan, made by [`Self::plan_profiles_access`] or, + /// for folders not yet recorded as profile roots, by + /// [`Self::plan_folder_access`]. The grants are applied first, then each + /// assignment is recorded in order. + /// + /// # Errors + /// + /// As [`Self::assign_profile_with_access`]. An assignment that fails + /// after others were recorded leaves those recorded. + pub fn assign_profiles_with_access( + &mut self, + workspace_id: WorkspaceId, + names: &[&str], + confirmed: &ProfileAccessPlan, + expected_revision: u64, + ) -> Result { + self.check_revision(expected_revision)?; + let plan = self.plan_profiles_access(workspace_id, names)?; + if plan.grant != confirmed.grant { + return Err(ControlError::ProfileRefused( + "the folders this assignment grants changed; review it again", + )); + } + let paths = plan.paths(); + self.check_container_grants(workspace_id, &paths, ContainerGrantAccess::ReadExecute) + .map_err(|(_, error)| error)?; + let mut granted = Vec::with_capacity(paths.len()); + for path in &paths { + granted.push(self.grant_container_access( + workspace_id, + path, + ContainerGrantAccess::ReadExecute, + self.revision(), + )?); + } + let mut profile_ids = Vec::with_capacity(names.len()); + for name in names { + profile_ids.push(self.assign_profile(workspace_id, name, self.revision())?); + } + Ok(ProfileAssignment { + profile_ids, + granted, + plan, + }) + } + + /// Record the unassignment, then revoke the workspace's read-execute + /// grants on the profile's roots that no profile still assigned to it + /// lists and that are not its package cache root. The workspace folder's + /// read-write grant is never revoked here. Revocations need no revision; + /// each withdraws every run of the workspace. + /// + /// # Errors + /// + /// What [`Self::unassign_profile`] refuses. A failed revocation does not + /// fail the call; it is reported in [`Revocations::failure`]. + pub fn unassign_profile_with_access( + &mut self, + workspace_id: WorkspaceId, + name: &str, + expected_revision: u64, + ) -> Result<(Uuid, Revocations), ControlError> { + self.check_revision(expected_revision)?; + let grants = self.grants_released_by_unassignment(workspace_id, name)?; + let profile_id = self.unassign_profile(workspace_id, name, expected_revision)?; + Ok((profile_id, self.revoke_each(&grants))) + } + + /// The grants of `workspace_id` that + /// [`Self::unassign_profile_with_access`] would revoke now, for a + /// confirmation shown before the change. Reads settings only. + /// + /// # Errors + /// + /// An unknown workspace or profile, and a profile not assigned to the + /// workspace. + pub fn grants_released_by_unassignment( + &self, + workspace_id: WorkspaceId, + name: &str, + ) -> Result, ControlError> { + if self.workspace(workspace_id).is_none() { + return Err(ControlError::UnknownWorkspace); + } + let profile = self + .profile(name) + .ok_or(ControlError::UnknownProfile)? + .profile(); + if !self.profile_assigned(workspace_id, profile.id()) { + return Err(ControlError::ProfileRefused( + "the profile is not assigned to this workspace", + )); + } + Ok(self.unneeded_root_grants(workspace_id, profile.id(), profile.read_only_roots())) + } + + /// For each workspace the profile `name` is assigned to, in registration + /// order, the grants [`Self::remove_profile_with_access`] would revoke + /// now. Reads settings only. + /// + /// # Errors + /// + /// An unknown profile. + pub fn grants_released_by_removal( + &self, + name: &str, + ) -> Result)>, ControlError> { + let profile = self + .profile(name) + .ok_or(ControlError::UnknownProfile)? + .profile(); + Ok(self + .snapshot + .workspaces + .iter() + .filter(|workspace| workspace.profiles.contains(&profile.id())) + .map(|workspace| { + ( + workspace.id, + self.unneeded_root_grants( + workspace.id, + profile.id(), + profile.read_only_roots(), + ), + ) + }) + .collect()) + } + + /// Remove the profile `name`, which ends every assignment of it, then + /// revoke, in each workspace it was assigned to, the grants + /// [`Self::unassign_profile_with_access`] would. + /// + /// # Errors + /// + /// What [`Self::remove_profile`] refuses. A failed revocation is reported + /// in [`Revocations::failure`]. + pub fn remove_profile_with_access( + &mut self, + name: &str, + expected_revision: u64, + ) -> Result<(Uuid, Revocations), ControlError> { + self.check_revision(expected_revision)?; + let grants: Vec = self + .grants_released_by_removal(name)? + .into_iter() + .flat_map(|(_, grants)| grants) + .collect(); + let profile_id = self.remove_profile(name, expected_revision)?; + Ok((profile_id, self.revoke_each(&grants))) + } + + /// Register `path` as [`Self::register_workspace`] does, then, on Windows, + /// grant the workspace's container read-write on its folder when no grant + /// of the workspace is recorded on that folder and this account can change + /// its access-control list. Registering a folder again that has no such + /// grant grants it. + /// + /// # Errors + /// + /// What [`Self::register_workspace`] refuses. A failed grant does not + /// fail the call; it is reported in [`RegisteredWorkspace::grant`]. + pub fn register_workspace_with_access( + &mut self, + path: &Path, + expected_revision: u64, + ) -> Result { + let registration = self.register_workspace(path, expected_revision)?; + let grant = self.grant_own_folder(®istration); + Ok(RegisteredWorkspace { + registration, + grant, + }) + } + + /// The read-write grant [`Self::register_workspace_with_access`] applies. + fn grant_own_folder( + &mut self, + registration: &WorkspaceRegistration, + ) -> Result, ControlError> { + if !CONTAINER_GRANTS_SUPPORTED + || self.container_grants().iter().any(|status| { + status.grant().workspace_id() == registration.id + && status + .grant() + .directory() + .same_directory(®istration.directory) + }) + { + return Ok(None); + } + let live = registration.directory.live_path()?; + if !platform::can_change_access(&live).unwrap_or(false) { + return Ok(None); + } + self.grant_container_access( + registration.id, + &live, + ContainerGrantAccess::ReadWrite, + self.revision(), + ) + .map(Some) + } + + /// Revoke every grant of `id`, in any state, then, when every revocation + /// was confirmed, unregister it as [`Self::unregister_workspace`] does. + /// Each revocation withdraws the workspace's runs. + /// + /// # Errors + /// + /// A stale revision or an unknown workspace, before anything changes, and + /// a failed unregistration after every grant was revoked. A failed + /// revocation does not fail the call; it is reported in + /// [`Revocations::failure`], and the workspace then stays registered with + /// the grants not yet revoked. + pub fn unregister_workspace_with_access( + &mut self, + id: WorkspaceId, + expected_revision: u64, + ) -> Result { + self.check_revision(expected_revision)?; + if self.workspace(id).is_none() { + return Err(ControlError::UnknownWorkspace); + } + let grants: Vec = self + .container_grants() + .iter() + .filter(|status| status.grant().workspace_id() == id) + .map(|status| status.grant().id()) + .collect(); + let revocations = self.revoke_each(&grants); + if revocations.failure.is_none() { + self.unregister_workspace(id, self.revision())?; + } + Ok(revocations) + } + + /// The profile `name`'s identifier when it can be assigned to + /// `workspace_id` now. + fn assignable(&self, workspace_id: WorkspaceId, name: &str) -> Result { + let workspace = self + .workspace(workspace_id) + .ok_or(ControlError::UnknownWorkspace)?; + let profile = self + .profile(name) + .ok_or(ControlError::UnknownProfile)? + .profile(); + if Some(profile.platform()) != ProfilePlatform::current() { + return Err(ControlError::ProfileRefused( + "the profile was declared on another platform", + )); + } + if workspace.profiles.contains(&profile.id()) { + return Err(ControlError::ProfileRefused( + "the profile is already assigned to this workspace", + )); + } + Ok(profile.id()) + } + + /// Sort `paths` into `plan`, in order. A folder with a grant of the + /// workspace recorded, in any state, is left out, as is one inside or + /// equal to another planned folder, which inherits that grant. + fn plan_into( + &self, + workspace_id: WorkspaceId, + paths: &[PathBuf], + plan: &mut ProfileAccessPlan, + ) { + let recorded: Vec<&DirectoryRecord> = self + .container_grants() + .iter() + .filter(|status| status.grant().workspace_id() == workspace_id) + .map(|status| status.grant().directory()) + .collect(); + let mut planned: Vec = Vec::new(); + for path in paths { + let Ok(record) = DirectoryRecord::capture(path) else { + let folder = PlannedFolder { + path: path.clone(), + display: crate::turn::display_safe_line(&path.to_string_lossy()), + record: None, + }; + if !plan.unknown.contains(&folder) { + plan.unknown.push(folder); + } + continue; + }; + let folder = PlannedFolder { + path: path.clone(), + display: record.display(), + record: Some(record.clone()), + }; + if recorded.iter().any(|grant| grant.same_directory(&record)) + || planned + .iter() + .any(|earlier| earlier.same_directory(&record)) + { + continue; + } + let list = match root_grant_need(workspace_id, path) { + RootGrantNeed::NeedsGrant => { + planned.push(record); + &mut plan.grant + } + RootGrantNeed::NeedsAdministrator => &mut plan.administrator, + RootGrantNeed::Unknown => &mut plan.unknown, + RootGrantNeed::Readable | RootGrantNeed::NotApplicable => continue, + }; + if !list.contains(&folder) { + list.push(folder); + } + } + // A grant reaches everything beneath its folder, so a folder inside + // another planned one, in either order, needs none of its own. + let inside: Vec = planned + .iter() + .map(|folder| { + planned.iter().any(|outer| { + !outer.same_directory(folder) && outer.contains(folder).unwrap_or(false) + }) + }) + .collect(); + let mut kept = inside.iter().map(|inside| !inside); + plan.grant.retain(|_| kept.next().unwrap_or(true)); + } + + /// The workspace's read-execute grants on `roots`, the roots of the + /// profile `leaving`, that no other profile assigned to it lists and that + /// are not its package cache root. + fn unneeded_root_grants( + &self, + workspace_id: WorkspaceId, + leaving: Uuid, + roots: &[DirectoryRecord], + ) -> Vec { + let still_needed: Vec<&DirectoryRecord> = self + .assigned_profiles(workspace_id) + .iter() + .filter(|id| **id != leaving) + .filter_map(|id| { + self.profiles() + .iter() + .find(|status| status.profile().id() == *id) + }) + .flat_map(|status| status.profile().read_only_roots()) + .collect(); + let cache = self + .snapshot + .package_cache_roots + .iter() + .find(|status| status.workspace_id == workspace_id) + .map(|status| &status.directory); + self.container_grants() + .iter() + .map(super::ContainerGrantStatus::grant) + .filter(|grant| { + let directory = grant.directory(); + grant.workspace_id() == workspace_id + && grant.access() == ContainerGrantAccess::ReadExecute + && roots.iter().any(|root| root.same_directory(directory)) + && !still_needed + .iter() + .any(|root| root.same_directory(directory)) + && cache.is_none_or(|cache| !cache.same_directory(directory)) + }) + .map(ContainerGrant::id) + .collect() + } + + /// Revoke each grant in order and stop at the first failure. + fn revoke_each(&mut self, grants: &[Uuid]) -> Revocations { + let mut revocations = Revocations::default(); + for grant in grants { + if let Some(workspace) = self.container_grant_workspace(*grant) + && !revocations.workspaces.contains(&workspace) + { + revocations.workspaces.push(workspace); + } + match self.revoke_container_grant(*grant) { + Ok(revocation) => revocations.revoked.push(revocation), + Err(error) => { + revocations.failure = Some((*grant, error)); + break; + } + } + } + revocations + } +} + +/// Validate and apply one assignment action during replay or append preflight. +pub(super) fn apply(state: &mut ControlSnapshot, action: &Action) -> Result<(), ControlError> { + let (workspace_id, profile_id, assign) = match action { + Action::ProfileAssigned { + workspace_id, + profile_id, + } => (*workspace_id, *profile_id, true), + Action::ProfileUnassigned { + workspace_id, + profile_id, + } => (*workspace_id, *profile_id, false), + _ => return Err(ControlError::Invalid("not a profile assignment action")), + }; + if !state + .profiles + .iter() + .any(|status| status.profile().id() == profile_id) + { + return Err(ControlError::Invalid("assignment of an unknown profile")); + } + let workspace = state + .workspaces + .iter_mut() + .find(|workspace| workspace.id == workspace_id) + .ok_or(ControlError::Invalid("assignment for an unknown workspace"))?; + let index = workspace.profiles.iter().position(|id| *id == profile_id); + match (assign, index) { + (true, None) => workspace.profiles.push(profile_id), + (false, Some(index)) => { + workspace.profiles.remove(index); + } + (true, Some(_)) => return Err(ControlError::Invalid("duplicate profile assignment")), + (false, None) => { + return Err(ControlError::Invalid( + "removal of an absent profile assignment", + )); + } + } + Ok(()) +} + +#[cfg(test)] +mod tests; diff --git a/crates/omgcode-core/src/control/assignment/tests.rs b/crates/omgcode-core/src/control/assignment/tests.rs new file mode 100644 index 00000000..3237c1b4 --- /dev/null +++ b/crates/omgcode-core/src/control/assignment/tests.rs @@ -0,0 +1,453 @@ +use super::*; +use std::fs; + +use crate::control::{FILE_NAME, ProfileDeclaration}; + +struct Scene { + store: ControlStore, + data: PathBuf, + root: PathBuf, + outside: PathBuf, + _directory: tempfile::TempDir, +} + +/// A store with a development root and a folder beside it for toolchains. +fn scene() -> Scene { + let directory = tempfile::tempdir().expect("temporary directory"); + let data = directory.path().join("data"); + let root = directory.path().join("projects"); + let outside = directory.path().join("tools"); + fs::create_dir_all(&root).expect("development root"); + fs::create_dir_all(&outside).expect("toolchain folder"); + let mut store = ControlStore::open(&data).expect("store"); + store.set_development_root(&root, 0).expect("root"); + Scene { + store, + data, + root, + outside, + _directory: directory, + } +} + +impl Scene { + fn register(&mut self, name: &str) -> WorkspaceId { + let path = self.root.join(name); + fs::create_dir(&path).expect("workspace directory"); + let revision = self.store.revision(); + self.store + .register_workspace(&path, revision) + .expect("workspace") + .id() + } + + /// A profile named `name` whose roots are these folders beside the root. + fn profile(&mut self, name: &str, roots: &[&str]) -> Uuid { + let read_only_roots = roots + .iter() + .map(|root| { + let path = self.outside.join(root); + fs::create_dir_all(&path).expect("profile root"); + path + }) + .collect(); + let revision = self.store.revision(); + self.store + .add_profile( + &ProfileDeclaration { + name: name.into(), + read_only_roots, + ..ProfileDeclaration::default() + }, + revision, + ) + .expect("profile") + .id() + } + + fn assign(&mut self, workspace: WorkspaceId, name: &str) -> Result { + let revision = self.store.revision(); + self.store.assign_profile(workspace, name, revision) + } +} + +/// Assignments are per workspace, advance the revision, show in status, +/// survive replay, and are removed. +#[test] +fn assignments_are_recorded_replayed_and_removed() { + let mut scene = scene(); + let app = scene.register("app"); + let other = scene.register("other"); + let rust = scene.profile("rust", &["rust"]); + let node = scene.profile("node", &["node"]); + let revision = scene.store.revision(); + + assert_eq!(scene.assign(app, "RUST").expect("assign"), rust); + scene.assign(app, "node").expect("assign node"); + assert_eq!(scene.store.revision(), revision + 2); + assert_eq!(scene.store.assigned_profiles(app), [rust, node]); + assert!(scene.store.profile_assigned(app, rust)); + assert!(!scene.store.profile_assigned(other, rust)); + assert!(scene.store.assigned_profiles(other).is_empty()); + + let encoded = serde_json::to_value(scene.store.snapshot()).expect("snapshot JSON"); + assert_eq!( + encoded["workspaces"][0]["assigned_profiles"], + serde_json::json!([rust, node]) + ); + assert!(encoded["workspaces"][1].get("assigned_profiles").is_none()); + + let data = scene.data.clone(); + drop(scene.store); + let mut store = ControlStore::open(&data).expect("replay"); + assert_eq!(store.assigned_profiles(app), [rust, node]); + let revision = store.revision(); + assert_eq!( + store + .unassign_profile(app, "rust", revision) + .expect("unassign"), + rust + ); + assert_eq!(store.revision(), revision + 1); + assert_eq!(store.assigned_profiles(app), [node]); + drop(store); + let store = ControlStore::open(&data).expect("replay after unassign"); + assert_eq!(store.assigned_profiles(app), [node]); +} + +/// Stale revisions, unknown workspaces and profiles, duplicates, and absent +/// unassignments are refused without changing the revision. +#[test] +fn refused_assignments_leave_the_settings_unchanged() { + let mut scene = scene(); + let app = scene.register("app"); + scene.profile("rust", &["rust"]); + scene.profile("node", &["node"]); + scene.assign(app, "rust").expect("assign"); + let revision = scene.store.revision(); + + assert!(matches!( + scene.store.assign_profile(app, "node", revision - 1), + Err(ControlError::Conflict { .. }) + )); + assert!(matches!( + scene.store.unassign_profile(app, "rust", revision - 1), + Err(ControlError::Conflict { .. }) + )); + assert!(matches!( + scene + .store + .assign_profile(WorkspaceId::fresh(), "node", revision), + Err(ControlError::UnknownWorkspace) + )); + assert!(matches!( + scene.store.assign_profile(app, "absent", revision), + Err(ControlError::UnknownProfile) + )); + assert!(matches!( + scene.store.assign_profile(app, "Rust", revision), + Err(ControlError::ProfileRefused(_)) + )); + assert!(matches!( + scene.store.unassign_profile(app, "node", revision), + Err(ControlError::ProfileRefused(_)) + )); + assert!(matches!( + scene.store.plan_profile_access(app, "rust"), + Err(ControlError::ProfileRefused(_)) + )); + assert_eq!(scene.store.revision(), revision); + assert_eq!(scene.store.assigned_profiles(app).len(), 1); +} + +/// Removing a profile ends its assignment in every workspace, and +/// unregistering a workspace drops its assignments; both survive replay. +#[test] +fn removal_and_unregistration_drop_assignments() { + let mut scene = scene(); + let app = scene.register("app"); + let other = scene.register("other"); + scene.profile("rust", &["rust"]); + let node = scene.profile("node", &["node"]); + for workspace in [app, other] { + scene.assign(workspace, "rust").expect("assign rust"); + scene.assign(workspace, "node").expect("assign node"); + } + let revision = scene.store.revision(); + scene + .store + .remove_profile("rust", revision) + .expect("remove"); + assert_eq!(scene.store.assigned_profiles(app), [node]); + assert_eq!(scene.store.assigned_profiles(other), [node]); + + let revision = scene.store.revision(); + scene + .store + .unregister_workspace(other, revision) + .expect("unregister"); + assert!(scene.store.assigned_profiles(other).is_empty()); + + let data = scene.data.clone(); + drop(scene.store); + let store = ControlStore::open(&data).expect("replay"); + assert_eq!(store.assigned_profiles(app), [node]); + assert!(store.assigned_profiles(other).is_empty()); +} + +/// Replay refuses an assignment of a profile that was never recorded. +#[test] +fn replay_refuses_an_assignment_of_an_unknown_profile() { + let mut scene = scene(); + let app = scene.register("app"); + let rust = scene.profile("rust", &["rust"]); + scene.assign(app, "rust").expect("assign"); + let data = scene.data.clone(); + drop(scene.store); + let journal = data.join(FILE_NAME); + let text = fs::read_to_string(&journal).expect("journal text"); + let assigned = text + .lines() + .find(|line| line.contains("profile_assigned")) + .expect("assignment event") + .to_owned(); + let tampered = text.replacen( + &assigned, + &assigned.replace(&rust.to_string(), &Uuid::new_v4().to_string()), + 1, + ); + assert_ne!(text, tampered); + fs::write(&journal, tampered).expect("tamper journal"); + assert!(ControlStore::open(&data).is_err()); +} + +/// Off Windows nothing is planned; on Windows a fresh folder the current +/// account owns is planned once, a root inside another planned root is left +/// out, and a root with a recorded grant is skipped. Planning reads +/// access-control lists only. +#[test] +fn a_plan_lists_each_needed_root_once() { + let mut scene = scene(); + let app = scene.register("app"); + scene.profile("nested", &["outer/inner", "outer"]); + let plan = scene + .store + .plan_profile_access(app, "nested") + .expect("plan"); + if CONTAINER_GRANTS_SUPPORTED { + let planned: Vec = plan.paths(); + assert_eq!(planned.len(), 1, "{plan:?}"); + assert!(planned[0].ends_with("outer"), "{plan:?}"); + assert!(plan.needs_administrator().is_empty()); + assert!(plan.unknown().is_empty()); + + scene.store.test_record_grant( + app, + &scene.outside.join("outer"), + ContainerGrantAccess::ReadExecute, + ); + let plan = scene + .store + .plan_profile_access(app, "nested") + .expect("plan with a grant"); + // The recorded grant is not applied, so the inner root, which no + // longer has a planned folder above it, is planned instead. + assert_eq!(plan.paths().len(), 1, "{plan:?}"); + assert!(plan.paths()[0].ends_with("inner"), "{plan:?}"); + } else { + assert_eq!(plan, ProfileAccessPlan::default()); + } +} + +/// A batch plan covers every named profile once. A plan made from folders +/// before they are recorded, as discovery does, equals the plan made again +/// from the recorded roots, however the paths were spelled. +#[test] +fn a_batch_plan_matches_the_plan_from_unrecorded_folders() { + let mut scene = scene(); + let app = scene.register("app"); + let rust = scene.outside.join("rust"); + let node = scene.outside.join("node"); + fs::create_dir_all(&rust).expect("rust"); + fs::create_dir_all(&node).expect("node"); + let spelled = [ + scene.outside.join(".").join("rust"), + scene.outside.join("node").join("."), + ]; + let before = scene + .store + .plan_folder_access(app, &spelled) + .expect("plan before recording"); + for (name, root) in [("rust", &rust), ("node", &node)] { + let revision = scene.store.revision(); + scene + .store + .add_profile( + &ProfileDeclaration { + name: name.into(), + read_only_roots: vec![root.clone()], + ..ProfileDeclaration::default() + }, + revision, + ) + .expect("profile"); + } + let after = scene + .store + .plan_profiles_access(app, &["rust", "node"]) + .expect("batch plan"); + assert_eq!(before, after); + if CONTAINER_GRANTS_SUPPORTED { + assert_eq!(after.to_grant().len(), 2, "{after:?}"); + } else { + assert_eq!(after, ProfileAccessPlan::default()); + } + assert!(matches!( + scene.store.plan_profiles_access(app, &["rust", "RUST"]), + Err(ControlError::ProfileRefused(_)) + )); +} + +/// An assignment whose plan changed since the operator confirmed it is +/// refused before anything is recorded. Off Windows the plan is empty, so the +/// assignment records the event and grants nothing. +#[test] +fn an_assignment_applies_only_the_confirmed_plan() { + let mut scene = scene(); + let app = scene.register("app"); + let rust = scene.profile("rust", &["rust"]); + let revision = scene.store.revision(); + let confirmed = ProfileAccessPlan::default(); + let result = scene + .store + .assign_profile_with_access(app, "rust", &confirmed, revision); + if CONTAINER_GRANTS_SUPPORTED { + assert!( + matches!(result, Err(ControlError::ProfileRefused(_))), + "{result:?}" + ); + assert_eq!(scene.store.revision(), revision); + assert!(scene.store.assigned_profiles(app).is_empty()); + assert!(scene.store.container_grants().is_empty()); + } else { + let assignment = result.expect("assignment off Windows"); + assert_eq!(assignment.profile_ids, [rust]); + assert!(assignment.granted.is_empty()); + assert_eq!(scene.store.assigned_profiles(app), [rust]); + assert_eq!(scene.store.revision(), revision + 1); + } +} + +/// Unassigning revokes only the read-execute grants on the profile's own +/// roots that no profile still assigned lists, never the workspace's +/// read-write grant or its package cache root. +#[test] +fn only_grants_no_remaining_profile_needs_are_unneeded() { + let mut scene = scene(); + let app = scene.register("app"); + let other = scene.register("other"); + scene.profile("rust", &["rust", "shared", "cache"]); + scene.profile("node", &["shared"]); + scene.assign(app, "rust").expect("assign rust"); + scene.assign(app, "node").expect("assign node"); + let read = ContainerGrantAccess::ReadExecute; + let own = scene + .store + .test_record_grant(app, &scene.outside.join("rust"), read); + scene + .store + .test_record_grant(app, &scene.outside.join("shared"), read); + let cache = scene.outside.join("cache"); + scene.store.test_record_grant(app, &cache, read); + let revision = scene.store.revision(); + scene + .store + .set_package_cache_root(app, &cache, revision) + .expect("cache root"); + scene.store.test_record_grant( + app, + &scene.root.join("app"), + ContainerGrantAccess::ReadWrite, + ); + scene + .store + .test_record_grant(other, &scene.outside.join("rust"), read); + + assert_eq!( + scene + .store + .grants_released_by_unassignment(app, "rust") + .expect("preview"), + [own] + ); + assert_eq!( + scene + .store + .grants_released_by_removal("rust") + .expect("removal preview"), + [(app, vec![own])] + ); + assert!(matches!( + scene.store.grants_released_by_unassignment(other, "rust"), + Err(ControlError::ProfileRefused(_)) + )); + // The unassignment itself records the event, then revokes the same + // grants; the store has no real ACL entries, so only the selection is + // checked here. + let revision = scene.store.revision(); + scene + .store + .unassign_profile(app, "rust", revision) + .expect("unassign"); + assert!( + scene + .store + .grants_released_by_removal("rust") + .expect("none") + .is_empty() + ); +} + +/// A revocation names the workspace of every grant it attempted, each once and +/// in order, whether or not the grant was revoked, and keeps only those +/// workspaces' runs to wait for. On Windows the recorded grants have no real +/// access-control entry, and removing nothing succeeds; elsewhere the first +/// revocation fails, which still names its workspace. +#[test] +fn revocations_name_each_attempted_workspace_and_its_runs() { + let mut scene = scene(); + let app = scene.register("app"); + let other = scene.register("other"); + let third = scene.register("third"); + let read = ContainerGrantAccess::ReadExecute; + let mut grant = |workspace: WorkspaceId, folder: &str| { + let path = scene.outside.join(folder); + fs::create_dir_all(&path).expect("grant folder"); + scene.store.test_record_grant(workspace, &path, read) + }; + let first = grant(app, "a"); + let second = grant(app, "b"); + let last = grant(other, "c"); + + let revocations = scene.store.revoke_each(&[first, second, last]); + + let (run_app, run_other, run_third) = (Uuid::new_v4(), Uuid::new_v4(), Uuid::new_v4()); + let pending = [(app, run_app), (other, run_other), (third, run_third)]; + if CONTAINER_GRANTS_SUPPORTED { + assert!(revocations.failure.is_none(), "{:?}", revocations.failure); + assert_eq!(revocations.revoked.len(), 3); + assert_eq!(revocations.workspaces, [app, other]); + assert_eq!(revocations.withdrawn_runs(&pending), [run_app, run_other]); + } else { + assert!(revocations.revoked.is_empty()); + assert!( + matches!(revocations.failure, Some((id, ControlError::Container(_))) if id == first), + "{:?}", + revocations.failure + ); + // The failure stops the loop, so `other` was never attempted. + assert_eq!(revocations.workspaces, [app]); + assert_eq!(revocations.withdrawn_runs(&pending), [run_app]); + } + assert!(Revocations::default().withdrawn_runs(&pending).is_empty()); +} diff --git a/crates/omgcode-core/src/control/profile.rs b/crates/omgcode-core/src/control/profile.rs index 0a784ca6..fafcab67 100644 --- a/crates/omgcode-core/src/control/profile.rs +++ b/crates/omgcode-core/src/control/profile.rs @@ -455,6 +455,10 @@ pub(super) fn apply( .position(|status| status.profile.id == *profile_id) .ok_or(ControlError::Invalid("removal of an unknown profile"))?; state.profiles.remove(index); + // Removing a profile ends every assignment of it (ADR-0107). + for workspace in &mut state.workspaces { + workspace.profiles.retain(|id| id != profile_id); + } } _ => {} } diff --git a/crates/omgcode-core/src/run.rs b/crates/omgcode-core/src/run.rs index 53e5e447..3902eb82 100644 --- a/crates/omgcode-core/src/run.rs +++ b/crates/omgcode-core/src/run.rs @@ -605,6 +605,9 @@ fn withdrawn(control: &ControlStore, start: &RunStart) -> Option<&'static str> { Some(status) if status.profile().id() == start.profile_id => {} _ => return Some("the toolchain profile was removed"), } + if !control.profile_assigned(start.workspace_id, start.profile_id) { + return Some("the toolchain profile was unassigned from the workspace"); + } if start.model_origin && !registration.permissions().model_tools { return Some("the workspace model_tools preference is disabled"); } @@ -630,6 +633,12 @@ fn withdrawn(control: &ControlStore, start: &RunStart) -> Option<&'static str> { const STANDING_ALLOW_WITHDRAWN: &str = "the workspace no longer allows this model command without an approval"; +/// Why a run of a profile not assigned to its workspace is refused +/// (ADR-0107). The command tool sends this text to a model, so it names no +/// path. +const PROFILE_NOT_ASSIGNED: &str = "the toolchain profile is not assigned to this workspace; \ + assign it in the settings window or with `omgcode workspace profile-assign`"; + /// Whether the settings still let a model command run without an approval. /// A standing-allow run is checked against this under the runner's settings /// lock, because the turn released its own lock before the run (ADR-0063). @@ -735,6 +744,24 @@ pub fn workspace_runs( .collect()) } +/// The pending runs of every workspace, each with its workspace. +/// +/// An operator change that revokes container grants (ADR-0107) calls this +/// under the control lock before it records anything, then waits for the +/// runs that [`Revocations::withdrawn_runs`](crate::control::Revocations::withdrawn_runs) +/// selects: the runs of each workspace whose grant it tried to revoke. +pub fn pending_runs(control: &ControlStore) -> Result, RunError> { + let (journal_root, store_id) = control.file_audit_context()?; + let Some(journal) = RunJournal::open_existing(&journal_root, store_id)? else { + return Ok(Vec::new()); + }; + Ok(journal + .pending_starts() + .into_iter() + .map(|start| (start.workspace_id, start.run_id)) + .collect()) +} + /// The pending runs that the settings in `control` no longer allow. /// /// A settings change calls this while it still holds the control lock, right @@ -979,6 +1006,10 @@ fn prepare( "the profile was declared on another platform", )); } + // A workspace runs only the profiles assigned to it (ADR-0107). + if !control.profile_assigned(request.workspace_id, profile.id()) { + return Err(RunError::Refused(PROFILE_NOT_ASSIGNED)); + } let roots = current_roots(control, profile)?; // On Linux this needs a delegated cgroup; without one nothing is recorded. process::check_tree_limits().map_err(RunError::Limits)?; @@ -1712,6 +1743,9 @@ mod tests { control.revision(), ) .expect("profile"); + control + .assign_profile(workspace_id, "kept", control.revision()) + .expect("assign profile"); let mut start = withdrawn_start(workspace_id); start.profile_id = profile.id(); start.profile_name = "kept".into(); @@ -2163,6 +2197,54 @@ mod tests { assert!(!journal_root.join("runs-v1.jsonl").exists()); } + /// A recorded profile that is not assigned to the workspace is refused + /// before anything is recorded, and the refusal names no path (ADR-0107). + #[test] + fn a_profile_not_assigned_to_the_workspace_is_refused_before_recording() { + let directory = tempfile::tempdir().expect("temporary directory"); + let (data, workspace_id, journal_root, _store_id) = store(directory.path()); + let tools = directory.path().join("tools"); + fs::create_dir(&tools).expect("tools"); + let mut control = ControlStore::open(&data).expect("control store"); + control + .add_profile( + &crate::control::ProfileDeclaration { + name: "system".into(), + read_only_roots: vec![tools], + ..crate::control::ProfileDeclaration::default() + }, + control.revision(), + ) + .expect("profile"); + drop(control); + let request = RunRequest { + workspace_id, + profile: "system".into(), + program: PathBuf::from("true"), + arguments: Vec::new(), + working_directory: None, + host_services: false, + network: false, + model_tools: false, + standing_allow: false, + limits: ProcessLimits { + tree: Some(process::TreeLimits { + max_memory_bytes: 1024 * 1024 * 1024, + max_processes: 64, + max_cpu_time: Duration::from_secs(60), + max_disk_bytes: Some(1024 * 1024 * 1024), + }), + ..ProcessLimits::default() + }, + }; + let result = run(&data, &request, &CancelSignal::new()); + assert!( + matches!(result, Err(RunError::Refused(PROFILE_NOT_ASSIGNED))), + "{result:?}" + ); + assert!(!journal_root.join("runs-v1.jsonl").exists()); + } + /// Only an effective `allow` lets a model command run unattended. #[test] fn unattended_runs_need_every_command_preference_at_allow() { @@ -2309,6 +2391,30 @@ mod tests { assert!(control.model_tool_revocations(workspace_id) > baseline); } + /// Unassigning the run's toolchain profile from its workspace withdraws + /// the run, even though the profile itself is still recorded. + #[cfg(target_os = "linux")] + #[test] + fn unassigning_the_profile_withdraws_the_run() { + let directory = tempfile::tempdir().expect("temporary directory"); + let (data, workspace_id, _journal_root, _store_id) = store(directory.path()); + let start = allowed_start(&data, directory.path(), workspace_id); + let control = open_control(&data).expect("control"); + assert_eq!(withdrawn(&control, &start), None); + drop(control); + let mut control = ControlStore::open(&data).expect("control store"); + control + .unassign_profile(workspace_id, "kept", control.revision()) + .expect("unassign"); + drop(control); + let control = open_control(&data).expect("control"); + assert!(control.profile("kept").is_some()); + assert_eq!( + withdrawn(&control, &start), + Some("the toolchain profile was unassigned from the workspace") + ); + } + /// A configured cache-root change withdraws a run that holds the old /// exposure. #[cfg(target_os = "linux")] diff --git a/crates/omgcode-core/src/turn.rs b/crates/omgcode-core/src/turn.rs index c312a173..80dca902 100644 --- a/crates/omgcode-core/src/turn.rs +++ b/crates/omgcode-core/src/turn.rs @@ -70,9 +70,11 @@ pub use review::{ /// limit to the create, edit, and multi-edit descriptions (ADR-0099). Version /// `0.8.0` adds `web_fetch` (ADR-0098). Version `0.9.0` lists the recorded /// toolchain profiles in `workspace_run_command`'s `profile` parameter and -/// withholds that tool while none is recorded (ADR-0100). Journals record the -/// version that was advertised; earlier versions replay unchanged. -pub const TOOL_SCHEMA_VERSION: &str = "0.9.0"; +/// withholds that tool while none is recorded (ADR-0100). Version `0.10.0` +/// lists only the profiles assigned to the session's workspace and withholds +/// the tool while none is assigned (ADR-0107). Journals record the version +/// that was advertised; earlier versions replay unchanged. +pub const TOOL_SCHEMA_VERSION: &str = "0.10.0"; /// Maximum tool calls accepted from one model response. pub const MAX_TOOL_CALLS_PER_ROUND: usize = 8; @@ -565,18 +567,19 @@ pub fn delete_tool_definition() -> ToolDefinition { pub fn command_tool_definition(profiles: &[String]) -> ToolDefinition { ToolDefinition { name: "workspace_run_command", - description: "Request one confined command under one of the operator's \ - recorded toolchain profiles, which the profile parameter \ - lists. The first call records a pending operator approval \ - and does not execute. After the operator approves, call it \ - again with the same arguments. Output is untrusted.", + description: "Request one confined command under one of the toolchain \ + profiles the operator assigned to this workspace, which the \ + profile parameter lists. The first call records a pending \ + operator approval and does not execute. After the operator \ + approves, call it again with the same arguments. Output is \ + untrusted.", parameters: json!({ "type": "object", "properties": { "profile": { "type": "string", "enum": profiles, - "description": "One of the recorded toolchain profile names." + "description": "One of the toolchain profiles assigned to this workspace." }, "program": { "type": "string", @@ -2030,9 +2033,12 @@ impl<'a> TurnRuntime<'a> { /// releasing the settings lock. Any settings failure returns `None`. fn tool_settings(&self) -> Option<(PermissionSet, Vec)> { match open_control(self.data_directory) { - Ok(Some(control)) => control - .workspace(self.workspace_id) - .map(|workspace| (workspace.permissions(), platform_profile_names(&control))), + Ok(Some(control)) => control.workspace(self.workspace_id).map(|workspace| { + ( + workspace.permissions(), + platform_profile_names(&control, self.workspace_id), + ) + }), Ok(None) | Err(_) => None, } } @@ -3839,28 +3845,30 @@ impl WorkspaceToolDispatcher<'_> { else { return ToolExecution::recoverable("invalid_command", call); }; - // A profile that is not recorded for this platform can never run, so - // it is refused under the lock that admitted this call, before any - // approval is requested or consumed (ADR-0100). The runner still - // checks the profile again under its own lock. - let recorded = platform_profile_names(&control); + // A profile that is not assigned to this workspace for this platform + // can never run, so it is refused under the lock that admitted this + // call, before any approval is requested or consumed (ADR-0100, + // ADR-0107). The runner still checks the profile again under its own + // lock. + let recorded = platform_profile_names(&control, self.workspace_id); if !recorded .iter() .any(|name| name.eq_ignore_ascii_case(profile)) { drop(control); - // The tool is withheld while no profile is recorded, but a call + // The tool is withheld while no profile is assigned, but a call // can still arrive: from an earlier turn's tool list, or after - // the last profile was removed. Naming another profile cannot + // the last profile was unassigned. Naming another profile cannot // help then, so the message does not ask for one. let message = if recorded.is_empty() { - "No toolchain profile is recorded for this platform, so no command can \ + "No toolchain profile is assigned to this workspace, so no command can \ run. Nothing ran and no approval was requested. Do not retry; tell the \ - user that the operator must add a toolchain profile." + user that the operator must assign a toolchain profile to this workspace." } else { - "No toolchain profile with this name is recorded for this platform. \ + "No toolchain profile with this name is assigned to this workspace. \ Nothing ran and no approval was requested. Name one of the listed \ - profiles; if none fits, tell the user that the operator must add one." + profiles; if none fits, tell the user that the operator must assign one \ + to this workspace." }; return status_result( call, @@ -4076,11 +4084,12 @@ pub(crate) fn longest_profile_names() -> Vec { .collect() } -/// The names of the recorded toolchain profiles that can run on this -/// platform, in the order they were added. The runner refuses a profile -/// declared on another platform, so such a profile is never offered, and a -/// build without a runner offers none. -fn platform_profile_names(control: &ControlStore) -> Vec { +/// The names of the toolchain profiles assigned to `workspace_id` that can +/// run on this platform, in the order they were added. The runner refuses a +/// profile not assigned to the workspace (ADR-0107) or declared on another +/// platform, so such a profile is never offered, and a build without a runner +/// offers none. +fn platform_profile_names(control: &ControlStore, workspace_id: WorkspaceId) -> Vec { let Some(platform) = ProfilePlatform::current() else { return Vec::new(); }; @@ -4088,7 +4097,9 @@ fn platform_profile_names(control: &ControlStore) -> Vec { .profiles() .iter() .map(ProfileStatus::profile) - .filter(|profile| profile.platform() == platform) + .filter(|profile| { + profile.platform() == platform && control.profile_assigned(workspace_id, profile.id()) + }) .map(|profile| profile.name().to_owned()) .collect() } diff --git a/crates/omgcode-core/tests/approval_review.rs b/crates/omgcode-core/tests/approval_review.rs index 98f0f680..579c1e24 100644 --- a/crates/omgcode-core/tests/approval_review.rs +++ b/crates/omgcode-core/tests/approval_review.rs @@ -82,6 +82,9 @@ impl Fixture { control.revision(), ) .expect("declare a toolchain profile"); + control + .assign_profile(workspace_id, "system", control.revision()) + .expect("assign the toolchain profile"); drop(control); let journal = SessionJournal::create_with_workspace_id(&data, &workspace, "Review", workspace_id) diff --git a/crates/omgcode-core/tests/turn_runtime.rs b/crates/omgcode-core/tests/turn_runtime.rs index 8ca710b0..ca04469d 100644 --- a/crates/omgcode-core/tests/turn_runtime.rs +++ b/crates/omgcode-core/tests/turn_runtime.rs @@ -163,10 +163,12 @@ impl Fixture { .expect("enable command tools"); } - /// Record a toolchain profile whose only root is a new empty directory. + /// Record a toolchain profile whose only root is a new empty directory, + /// and assign it to the workspace (ADR-0107). fn declare_profile(&mut self, name: &str) { let root = self._temporary.path().join(format!("tools-{name}")); fs::create_dir(&root).expect("toolchain root"); + let workspace_id = self.workspace_id; let control = self.control_mut(); control .add_profile( @@ -179,6 +181,19 @@ impl Fixture { control.revision(), ) .expect("toolchain profile"); + control + .assign_profile(workspace_id, name, control.revision()) + .expect("assign the profile"); + } + + /// Record a toolchain profile without assigning it to the workspace. + fn declare_unassigned_profile(&mut self, name: &str) { + self.declare_profile(name); + let workspace_id = self.workspace_id; + let control = self.control_mut(); + control + .unassign_profile(workspace_id, name, control.revision()) + .expect("unassign the profile"); } /// Rewrite a recorded profile as declared on the other platform, as a @@ -552,6 +567,9 @@ fn an_approved_command_consumes_the_approval_and_attempts_the_run() { control.revision(), ) .expect("profile"); + control + .assign_profile(workspace_id, "system", control.revision()) + .expect("assign the profile"); let command = || { tool_reply(vec![call( @@ -713,6 +731,49 @@ fn a_command_naming_an_unrecorded_profile_is_refused_before_an_approval() { ); } +/// A profile recorded but not assigned to the session's workspace can never +/// run there (ADR-0107), so it is neither offered nor accepted: the command +/// tool is withheld, and a call naming it is refused before any approval. +#[test] +fn a_profile_not_assigned_to_the_workspace_is_not_offered() { + let mut fixture = Fixture::new(); + fixture.enable_commands(); + fixture.declare_unassigned_profile("rust"); + let mut model = ScriptedModel::new(vec![ + tool_reply(vec![call( + "cmd-1", + "workspace_run_command", + json!({"profile": "rust", "program": "cargo", "arguments": ["fmt"]}), + )]), + text_reply("nothing can run"), + ]); + fixture + .run(&mut model, TurnLimits::default()) + .expect("the turn continues after the refusal"); + assert!( + !model.requests[0] + .tools + .iter() + .any(|name| name == "workspace_run_command"), + "the command tool was advertised for an unassigned profile" + ); + let result = fixture + .snapshot() + .messages + .iter() + .find(|message| message.text.contains("profile_not_recorded")) + .map(|message| message.text.clone()) + .expect("the result names the refusal"); + assert!(result.contains(r#""profiles":[]"#), "{result}"); + assert!(result.contains("assigned to this workspace"), "{result}"); + fixture.close_journal(); + let control = ControlStore::open_existing(&fixture.data) + .expect("open control") + .expect("control store"); + assert!(control.approval_statuses(now_unix()).is_empty()); + assert!(!fixture.data.join("runs-v1.jsonl").exists()); +} + /// A profile declared on the other platform can never run here, so alone it /// does not make the command tool appear. A call that names it anyway is /// told that no profile exists, not asked to pick from an empty list. @@ -2964,7 +3025,7 @@ fn an_older_schema_session_replays_and_accepts_a_new_turn(version: &str, tools: .map(|event| event["payload"]["manifest"]["tool_schema_version"].clone()) .collect(); assert_eq!(versions, [json!(version), json!(TOOL_SCHEMA_VERSION)]); - assert_eq!(TOOL_SCHEMA_VERSION, "0.9.0"); + assert_eq!(TOOL_SCHEMA_VERSION, "0.10.0"); } /// A session whose earlier turn advertised tool schema 0.2.0 still replays and diff --git a/crates/omgcode-core/tests/web_fetch_tool.rs b/crates/omgcode-core/tests/web_fetch_tool.rs index 63562b9b..0237084a 100644 --- a/crates/omgcode-core/tests/web_fetch_tool.rs +++ b/crates/omgcode-core/tests/web_fetch_tool.rs @@ -531,7 +531,7 @@ fn the_web_fetch_definition_has_the_documented_strict_schema() { parameters["properties"]["max_bytes"]["maximum"], MAX_RESULT_BYTES ); - assert_eq!(TOOL_SCHEMA_VERSION, "0.9.0"); + assert_eq!(TOOL_SCHEMA_VERSION, "0.10.0"); } #[test] @@ -583,7 +583,7 @@ fn web_fetch_is_offered_exactly_while_its_preference_and_model_tools_permit_it() ); assert_eq!( report.manifest.tool_schema_version.as_deref(), - Some("0.9.0") + Some("0.10.0") ); } } @@ -595,9 +595,11 @@ fn all_ten_tools_are_advertised_in_order_with_every_preference_enabled() { execute: Access::Prompt, ..fetching(Access::Prompt) }); - // The command tool is offered only while a toolchain profile is recorded. + // The command tool is offered only while a toolchain profile is assigned + // to the workspace (ADR-0107). let tools = fixture._temporary.path().join("tools"); fs::create_dir(&tools).expect("toolchain root"); + let workspace_id = fixture.workspace_id; let control = fixture.control.as_mut().expect("control store is open"); control .add_profile( @@ -610,6 +612,9 @@ fn all_ten_tools_are_advertised_in_order_with_every_preference_enabled() { control.revision(), ) .expect("toolchain profile"); + control + .assign_profile(workspace_id, "system", control.revision()) + .expect("assign the profile"); let mut model = ScriptedModel::new(vec![text_reply("done")]); let report = fixture .run(&FakeFetcher::serving("page"), &mut model) diff --git a/crates/omgcode-desktop/capabilities/settings.json b/crates/omgcode-desktop/capabilities/settings.json index 19e509a9..6bb55714 100644 --- a/crates/omgcode-desktop/capabilities/settings.json +++ b/crates/omgcode-desktop/capabilities/settings.json @@ -12,6 +12,7 @@ "allow-settings-add-package-profile", "allow-settings-add-toolchain-profile", "allow-settings-add-web-fetch-host", + "allow-settings-assign-toolchain-profile", "allow-settings-cancel-chatgpt-sign-in", "allow-settings-choose-package-cache", "allow-settings-choose-root", @@ -19,7 +20,6 @@ "allow-settings-clear-scope", "allow-settings-discover-toolchains", "allow-settings-grant-container-folder", - "allow-settings-grant-discovered-roots", "allow-settings-import-skill", "allow-settings-overview", "allow-settings-register-workspace", @@ -38,6 +38,7 @@ "allow-settings-set-workspace-instructions", "allow-settings-sign-in-chatgpt", "allow-settings-sign-out-chatgpt", + "allow-settings-unassign-toolchain-profile", "allow-settings-unregister-workspace" ] } diff --git a/crates/omgcode-desktop/src/command_names.rs b/crates/omgcode-desktop/src/command_names.rs index 624d8d75..4c3a2a21 100644 --- a/crates/omgcode-desktop/src/command_names.rs +++ b/crates/omgcode-desktop/src/command_names.rs @@ -69,5 +69,6 @@ pub const COMMAND_NAMES: &[&str] = &[ "session_web_audit", "settings_discover_toolchains", "settings_add_discovered_profiles", - "settings_grant_discovered_roots", + "settings_assign_toolchain_profile", + "settings_unassign_toolchain_profile", ]; diff --git a/crates/omgcode-desktop/src/commands/settings.rs b/crates/omgcode-desktop/src/commands/settings.rs index dccb429b..14b1f8dd 100644 --- a/crates/omgcode-desktop/src/commands/settings.rs +++ b/crates/omgcode-desktop/src/commands/settings.rs @@ -12,10 +12,10 @@ use omgcode_app::desktop::{ ApiKeySetRequest, ApiKeyText, ChatBudgetsDto, ChatBudgetsSaveRequest, ChatGptRequest, ChatGptSignOutResult, ConnectionAddRequest, ConnectionRemoveRequest, ConnectionSelectRequest, - ContainerAccessChoice, ContainerGrantRequest, ContainerRevokeRequest, DiscoveredGrantsRequest, + ContainerAccessChoice, ContainerGrantRequest, ContainerRevokeRequest, DiscoveredProfilesRequest, EnvironmentEntry, NewConnectionKind, PackageProfileAddRequest, - PermissionFlags, PermissionsChangeRequest, ProfileRemoveRequest, SettingsOverview, - SettingsRevisionRequest, SkillChoice, SkillRemoveRequest, SkillStateRequest, + PermissionFlags, PermissionsChangeRequest, ProfileAssignmentRequest, ProfileRemoveRequest, + SettingsOverview, SettingsRevisionRequest, SkillChoice, SkillRemoveRequest, SkillStateRequest, ToolchainDiscovery, ToolchainDiscoveryRequest, ToolchainProfileAddRequest, WebHostChangeRequest, WorkspaceInstructionsRequest, WorkspaceRevisionRequest, discovery_host, }; @@ -607,6 +607,69 @@ pub async fn settings_remove_toolchain_profile( .await } +/// `settings` only. After a native confirmation that names the workspace, the +/// profile, and on Windows each folder its container is granted read and +/// execute, assigns a toolchain profile to the workspace as `omgcode workspace +/// profile-assign` does (ADR-0107). +/// +/// # Errors +/// +/// `forbidden_window`, or the service's error (`unknown_workspace`, +/// `cancelled`, `stale_revision`, `container_access_failed`, or `control` +/// with core's reason). +#[tauri::command(rename_all = "snake_case")] +pub async fn settings_assign_toolchain_profile( + webview: Webview, + state: Service<'_>, + revision: u64, + workspace_id: Uuid, + name: String, +) -> Result { + authorize(Command::SettingsAssignToolchainProfile, webview.label())?; + let prompt = NativePrompt::new(webview.window()); + let request = ProfileAssignmentRequest { + revision, + workspace_id, + name, + }; + blocking(&state, move |service| { + service.settings_assign_toolchain_profile(request, &prompt) + }) + .await +} + +/// `settings` only. After a native confirmation, unassigns a toolchain +/// profile from a workspace as `omgcode workspace profile-unassign` does, +/// revokes the grants no other assigned profile needs, and stops the runs +/// that withdraws (ADR-0107). +/// +/// # Errors +/// +/// `forbidden_window`, or the service's error (`unknown_workspace`, +/// `cancelled`, `stale_revision`, `container_access_failed`, +/// `revocation_incomplete`, `runs_not_stopped`, or `control` with core's +/// reason). +#[tauri::command(rename_all = "snake_case")] +pub async fn settings_unassign_toolchain_profile( + webview: Webview, + state: Service<'_>, + revision: u64, + workspace_id: Uuid, + name: String, +) -> Result { + authorize(Command::SettingsUnassignToolchainProfile, webview.label())?; + let prompt = NativePrompt::new(webview.window()); + let request = ProfileAssignmentRequest { + revision, + workspace_id, + name, + }; + blocking(&state, move |service| { + service.settings_unassign_toolchain_profile(request, &prompt) + }) + .await +} + /// `settings` only. After a native confirmation that lists the origins core /// parsed, records a package-network profile (configuration only) as `omgcode /// workspace package-profile-add` does (ADR-0088). @@ -773,39 +836,6 @@ pub async fn settings_add_discovered_profiles( .await } -/// `settings` only, Windows only. Discovers again, and after one native -/// confirmation that names the workspace and every folder, grants the -/// workspace's container read-execute access to the selected proposals' roots -/// that it cannot read and this account can grant, as `omgcode workspace -/// container-grant` does (ADR-0103). -/// -/// # Errors -/// -/// `forbidden_window`, or the service's error (`unsupported_platform`, -/// `invalid_request`, `discovery_changed`, `unknown_workspace`, -/// `nothing_to_grant`, `cancelled`, `stale_revision`, -/// `container_access_failed`, or `control` with core's reason). -#[tauri::command(rename_all = "snake_case")] -pub async fn settings_grant_discovered_roots( - webview: Webview, - state: Service<'_>, - revision: u64, - workspace_id: Uuid, - digests: Vec, -) -> Result { - authorize(Command::SettingsGrantDiscoveredRoots, webview.label())?; - let prompt = NativePrompt::new(webview.window()); - let request = DiscoveredGrantsRequest { - revision, - workspace_id, - digests, - }; - blocking(&state, move |service| { - service.settings_grant_discovered_roots(request, &discovery_host()?, &prompt) - }) - .await -} - /// `settings` only. After a native confirmation that names the workspace /// folder and the canonical host pattern (and, for a wildcard, says it covers /// every subdomain), adds one pattern to the workspace's `web_fetch` diff --git a/crates/omgcode-desktop/src/lib.rs b/crates/omgcode-desktop/src/lib.rs index 3d0547ce..69c14391 100644 --- a/crates/omgcode-desktop/src/lib.rs +++ b/crates/omgcode-desktop/src/lib.rs @@ -224,7 +224,8 @@ fn run_app(service: Arc) -> ExitCode { commands::sessions::session_web_audit, commands::settings::settings_discover_toolchains, commands::settings::settings_add_discovered_profiles, - commands::settings::settings_grant_discovered_roots + commands::settings::settings_assign_toolchain_profile, + commands::settings::settings_unassign_toolchain_profile ]) .build(tauri::generate_context!()); match built { diff --git a/crates/omgcode-desktop/src/policy.rs b/crates/omgcode-desktop/src/policy.rs index d4b4190f..25a09ade 100644 --- a/crates/omgcode-desktop/src/policy.rs +++ b/crates/omgcode-desktop/src/policy.rs @@ -104,12 +104,13 @@ pub enum Command { SessionWebAudit, SettingsDiscoverToolchains, SettingsAddDiscoveredProfiles, - SettingsGrantDiscoveredRoots, + SettingsAssignToolchainProfile, + SettingsUnassignToolchainProfile, } impl Command { /// All commands, in the order of `command_names.rs`. - pub const ALL: [Self; 66] = [ + pub const ALL: [Self; 67] = [ Self::AppInfo, Self::SessionTree, Self::SessionSearch, @@ -175,7 +176,8 @@ impl Command { Self::SessionWebAudit, Self::SettingsDiscoverToolchains, Self::SettingsAddDiscoveredProfiles, - Self::SettingsGrantDiscoveredRoots, + Self::SettingsAssignToolchainProfile, + Self::SettingsUnassignToolchainProfile, ]; /// The command name exactly as the frontend invokes it. @@ -247,7 +249,8 @@ impl Command { Self::SessionWebAudit => "session_web_audit", Self::SettingsDiscoverToolchains => "settings_discover_toolchains", Self::SettingsAddDiscoveredProfiles => "settings_add_discovered_profiles", - Self::SettingsGrantDiscoveredRoots => "settings_grant_discovered_roots", + Self::SettingsAssignToolchainProfile => "settings_assign_toolchain_profile", + Self::SettingsUnassignToolchainProfile => "settings_unassign_toolchain_profile", } } @@ -289,7 +292,8 @@ impl Command { | Self::SettingsRemoveWebFetchHost | Self::SettingsDiscoverToolchains | Self::SettingsAddDiscoveredProfiles - | Self::SettingsGrantDiscoveredRoots => WindowLabel::Settings, + | Self::SettingsAssignToolchainProfile + | Self::SettingsUnassignToolchainProfile => WindowLabel::Settings, Self::AppInfo | Self::SessionTree | Self::SessionSearch @@ -358,10 +362,10 @@ mod tests { #[test] fn every_command_has_exactly_one_window_and_the_counts_match() { - assert_eq!(Command::ALL.len(), 66); + assert_eq!(Command::ALL.len(), 67); assert_eq!(with_window(WindowLabel::Main).len(), 31); assert_eq!(with_window(WindowLabel::Approvals).len(), 3); - assert_eq!(with_window(WindowLabel::Settings).len(), 32); + assert_eq!(with_window(WindowLabel::Settings).len(), 33); } #[test] @@ -465,8 +469,8 @@ mod tests { #[test] fn shared_name_list_has_unique_names_matching_the_enum() { let shared: BTreeSet<&str> = COMMAND_NAMES.iter().copied().collect(); - assert_eq!(COMMAND_NAMES.len(), 66); - assert_eq!(shared.len(), 66); + assert_eq!(COMMAND_NAMES.len(), 67); + assert_eq!(shared.len(), 67); let from_enum: Vec<&str> = Command::ALL.iter().map(|c| c.name()).collect(); assert_eq!(from_enum, COMMAND_NAMES); } diff --git a/crates/omgcode-desktop/tests/layers.rs b/crates/omgcode-desktop/tests/layers.rs index 66702b68..a3407322 100644 --- a/crates/omgcode-desktop/tests/layers.rs +++ b/crates/omgcode-desktop/tests/layers.rs @@ -166,6 +166,7 @@ fn settings_window_is_granted_only_its_own_commands() { "allow-settings-add-package-profile", "allow-settings-add-toolchain-profile", "allow-settings-add-web-fetch-host", + "allow-settings-assign-toolchain-profile", "allow-settings-cancel-chatgpt-sign-in", "allow-settings-choose-package-cache", "allow-settings-choose-root", @@ -173,7 +174,6 @@ fn settings_window_is_granted_only_its_own_commands() { "allow-settings-clear-scope", "allow-settings-discover-toolchains", "allow-settings-grant-container-folder", - "allow-settings-grant-discovered-roots", "allow-settings-import-skill", "allow-settings-overview", "allow-settings-register-workspace", @@ -192,6 +192,7 @@ fn settings_window_is_granted_only_its_own_commands() { "allow-settings-set-workspace-instructions", "allow-settings-sign-in-chatgpt", "allow-settings-sign-out-chatgpt", + "allow-settings-unassign-toolchain-profile", "allow-settings-unregister-workspace", ] ); @@ -251,15 +252,15 @@ fn build_script_declares_the_shared_command_list() { assert!(build.contains("include!(\"src/command_names.rs\")")); assert!(build.contains(".commands(COMMAND_NAMES)")); - // And the shared list holds the 66 unique policy names. + // And the shared list holds the 67 unique policy names. let listed: Vec<&str> = COMMAND_NAMES_SOURCE .lines() .filter_map(|line| line.trim().strip_prefix('"')) .filter_map(|rest| rest.strip_suffix("\",")) .collect(); let unique: BTreeSet<&str> = listed.iter().copied().collect(); - assert_eq!(listed.len(), 66); - assert_eq!(unique.len(), 66); + assert_eq!(listed.len(), 67); + assert_eq!(unique.len(), 67); let policy: Vec<&str> = Command::ALL.into_iter().map(Command::name).collect(); assert_eq!(listed, policy); } @@ -370,7 +371,7 @@ fn frontend_clients_call_only_commands_the_policy_gives_their_window() { .collect(); assert_eq!(settings_calls, settings_commands); - // ...and together they cover all 66 policy commands. + // ...and together they cover all 67 policy commands. let union: BTreeSet = main_calls .union(&approval_calls) .cloned() @@ -628,10 +629,10 @@ fn generate_handler_registers_exactly_the_policy_commands() { .map(|entry| entry.rsplit("::").next().expect("segment")) .collect(); - // Then they are the 66 shared names, once each. + // Then they are the 67 shared names, once each. let unique: BTreeSet<&str> = registered.iter().copied().collect(); - assert_eq!(registered.len(), 66); - assert_eq!(unique.len(), 66); + assert_eq!(registered.len(), 67); + assert_eq!(unique.len(), 67); let shared: BTreeSet<&str> = COMMAND_NAMES_SOURCE .lines() .filter_map(|line| line.trim().strip_prefix('"')) @@ -648,7 +649,7 @@ fn generate_handler_registers_exactly_the_policy_commands() { #[test] fn every_handler_authorizes_its_own_command_before_touching_the_service() { let handlers = all_handlers(); - assert_eq!(handlers.len(), 66); + assert_eq!(handlers.len(), 67); for handler in handlers { // Given the command the function name denotes. let command = Command::ALL @@ -782,7 +783,7 @@ fn handler_parameters_match_the_keys_the_frontend_passes() { } assert_eq!( expected.len(), - 66, + 67, "all commands are called by the frontend" ); diff --git a/crates/omgcode-desktop/ui/src/ipc/settings_client.ts b/crates/omgcode-desktop/ui/src/ipc/settings_client.ts index 25d1f3e2..d3811ed4 100644 --- a/crates/omgcode-desktop/ui/src/ipc/settings_client.ts +++ b/crates/omgcode-desktop/ui/src/ipc/settings_client.ts @@ -217,13 +217,23 @@ export const settingsApi = { workspace_id: workspaceId, }), /** - * Windows only. Grants the workspace's container read-execute access to the selected - * proposals' roots it cannot read, after one system confirmation that names every folder. + * Assigns a recorded toolchain profile to a workspace after a system confirmation that names, + * on Windows, each folder its container is granted read and execute (ADR-0107). */ - grantDiscoveredRoots: (revision: number, workspaceId: string, digests: string[]) => - invokeCommand("settings_grant_discovered_roots", { + assignToolchainProfile: (revision: number, workspaceId: string, name: string) => + invokeCommand("settings_assign_toolchain_profile", { revision, workspace_id: workspaceId, - digests, + name, + }), + /** + * Unassigns a toolchain profile from a workspace after a system confirmation; Rust revokes the + * grants no other assigned profile needs and stops the runs that withdraws. + */ + unassignToolchainProfile: (revision: number, workspaceId: string, name: string) => + invokeCommand("settings_unassign_toolchain_profile", { + revision, + workspace_id: workspaceId, + name, }), }; diff --git a/crates/omgcode-desktop/ui/src/ipc/types.ts b/crates/omgcode-desktop/ui/src/ipc/types.ts index 940b8642..4b1fb990 100644 --- a/crates/omgcode-desktop/ui/src/ipc/types.ts +++ b/crates/omgcode-desktop/ui/src/ipc/types.ts @@ -335,6 +335,11 @@ export interface WorkspaceSettingsView { */ web_fetch_hosts: string[]; write_tools: WriteToolAccess; + /** + * The names of the toolchain profiles assigned to the workspace, in the order assigned + * (ADR-0107). Its commands can use only these. + */ + profiles: string[]; package_cache_root: string | null; /** The workspace's custom instructions (ADR-0080); `null` when the saved file is unreadable. */ instructions: string | null; @@ -734,6 +739,11 @@ export interface SettingsOverview { connection: ConnectionView; provider_profiles: ProviderProfileView[]; toolchain_profiles: ToolchainProfileView[]; + /** + * The platform a toolchain profile must name to run, and so to be assigned, here; `null` where + * no profile runs. + */ + profile_platform: ToolchainProfileView["platform"] | null; package_profiles: PackageProfileView[]; container_grants: ContainerGrantView[]; /** Whether this computer can record container grants (Windows only). */ diff --git a/crates/omgcode-desktop/ui/src/mock/backend.ts b/crates/omgcode-desktop/ui/src/mock/backend.ts index b7ec58a3..1ea949ed 100644 --- a/crates/omgcode-desktop/ui/src/mock/backend.ts +++ b/crates/omgcode-desktop/ui/src/mock/backend.ts @@ -29,6 +29,7 @@ import type { SettingsOverview, SnippetPart, ToolchainDiscovery, + ToolchainProfileView, ToolchainProposalView, TreeSort, TreeView, @@ -108,6 +109,12 @@ const MOCK_COMPONENT_CHARS_MAX = 255; /** Rust's bound on the patterns in a workspace's host allowlist (ADR-0098). */ const MOCK_WEB_HOSTS_MAX = 32; +/** + * The platform the mock's toolchain profiles name. It matches its container grants, which exist + * only on Windows, so every sample profile can be assigned. + */ +const MOCK_PLATFORM: ToolchainProfileView["platform"] = "windows"; + /** Like core: suffixes that never name a public host, refused as a name or beneath one. */ const MOCK_WEB_HOST_RESERVED = [ "localhost", @@ -1020,6 +1027,7 @@ export function createMockBackend(now: () => number = Date.now): { invoke: Invok delete: "allow", create_directory: "allow", }, + profiles: [], package_cache_root: null, instructions: "", instructions_max_bytes: 0, @@ -1041,6 +1049,10 @@ export function createMockBackend(now: () => number = Date.now): { invoke: Invok case "settings_unregister_workspace": return changeSettings(args, () => { const removed = mockWorkspace(args); + // Like core (ADR-0107): its grants are revoked first. + settings.container_grants = settings.container_grants.filter( + (grant) => grant.workspace_id !== removed.workspace_id, + ); settings.workspaces = settings.workspaces.filter((w) => w !== removed); }); // Like core: only a local profile with an endpoint can be chosen, and the confirmation @@ -1445,7 +1457,7 @@ export function createMockBackend(now: () => number = Date.now): { invoke: Invok const roots = Array.from({ length: rootCount }, () => nextMockFolder("root")); settings.toolchain_profiles.push({ name, - platform: "linux", + platform: MOCK_PLATFORM, read_only_roots: roots, path_entries: Array.from( { length: pathCount }, @@ -1464,7 +1476,38 @@ export function createMockBackend(now: () => number = Date.now): { invoke: Invok if (index < 0) { fail("control", "unknown profile"); } - settings.toolchain_profiles.splice(index, 1); + const [removed] = settings.toolchain_profiles.splice(index, 1); + // Like core (ADR-0107): every assignment ends and the grants it alone needed go. + for (const workspace of settings.workspaces) { + if (removed !== undefined && mockAssigned(workspace, removed.name)) { + mockUnassign(workspace, removed); + } + } + }); + // Like core (ADR-0107): assigning grants the workspace's container each root it cannot read + // yet; the system confirmation that names them is accepted here. + case "settings_assign_toolchain_profile": + return changeSettings(args, () => { + const workspace = mockWorkspace(args); + const profile = mockProfile(str(args, "name")); + if (mockAssigned(workspace, profile.name)) { + fail("control", "the profile is already assigned to this workspace"); + } + for (const root of profile.read_only_roots) { + if (mockGrantNeed(workspace.workspace_id, root) === "needs_grant") { + mockGrant(workspace.workspace_id, root); + } + } + workspace.profiles.push(profile.name); + }); + case "settings_unassign_toolchain_profile": + return changeSettings(args, () => { + const workspace = mockWorkspace(args); + const profile = mockProfile(str(args, "name")); + if (!mockAssigned(workspace, profile.name)) { + fail("control", "the profile is not assigned to this workspace"); + } + mockUnassign(workspace, profile); }); case "settings_add_package_profile": return changeSettings(args, () => { @@ -1527,7 +1570,7 @@ export function createMockBackend(now: () => number = Date.now): { invoke: Invok fail("invalid_argument", "Bad access."); } settings.container_grants.push({ - grant_id: `00000000-0000-4000-8000-${String(settings.container_grants.length + 1).padStart(12, "0")}`, + grant_id: mockGrantId(), workspace_id: workspaceId, // As in Rust (ADR-0104): read and write goes on the workspace's own folder, with no // folder dialog; read and execute goes on a folder the dialog would choose. @@ -1564,44 +1607,27 @@ export function createMockBackend(now: () => number = Date.now): { invoke: Invok for (const proposal of chosen) { settings.toolchain_profiles.push({ name: proposal.name, - platform: "linux", + platform: MOCK_PLATFORM, read_only_roots: [...proposal.roots], path_entries: [...proposal.path_entries], environment_names: proposal.environment.map((variable) => variable.name), }); settings.revision += 1; } - return mockDiscovery(workspaceId); - } - case "settings_grant_discovered_roots": { - if (!settings.container_grants_supported) { - fail("unsupported_platform", "Container grants exist only on Windows."); - } - const chosen = mockSelection(args); - const workspaceId = str(args, "workspace_id"); - mockWorkspace({ workspace_id: workspaceId }); - if (args.revision !== settings.revision) { - fail("stale_revision", "The settings changed since this window read them."); - } - const folders = [ - ...new Set( - chosen - .flatMap((proposal) => proposal.roots) - .filter((root) => mockGrantNeed(workspaceId, root) === "needs_grant"), - ), - ]; - if (folders.length === 0) { - fail("nothing_to_grant", "No folder can be granted from this account."); - } - for (const directory of folders) { - settings.container_grants.push({ - grant_id: `00000000-0000-4000-8000-${String(settings.container_grants.length + 1).padStart(12, "0")}`, - workspace_id: workspaceId, - directory, - access: "read_execute", - state: "active", - }); - settings.revision += 1; + // Like core (ADR-0107): with a workspace, the same confirmation assigns them and grants + // the roots its container cannot read yet. + if (workspaceId !== null) { + const workspace = mockWorkspace({ workspace_id: workspaceId }); + for (const proposal of chosen) { + for (const root of proposal.roots) { + if (mockGrantNeed(workspaceId, root) === "needs_grant") { + mockGrant(workspaceId, root); + settings.revision += 1; + } + } + workspace.profiles.push(proposal.name); + settings.revision += 1; + } } return mockDiscovery(workspaceId); } @@ -1886,6 +1912,57 @@ export function createMockBackend(now: () => number = Date.now): { invoke: Invok return settings.toolchain_profiles.some((p) => p.name.toLowerCase() === name.toLowerCase()); } + function mockProfile(name: string): ToolchainProfileView { + const found = settings.toolchain_profiles.find( + (p) => p.name.toLowerCase() === name.toLowerCase(), + ); + if (found === undefined) { + fail("control", "unknown profile"); + } + return found; + } + + function mockAssigned(workspace: WorkspaceSettingsView, name: string): boolean { + return workspace.profiles.some((p) => p.toLowerCase() === name.toLowerCase()); + } + + function mockGrantId(): string { + return `00000000-0000-4000-8000-${String(settings.container_grants.length + 1).padStart(12, "0")}`; + } + + /** Records one active read-execute grant, as a confirmed grant ends up in core. */ + function mockGrant(workspaceId: string, directory: string): void { + settings.container_grants.push({ + grant_id: mockGrantId(), + workspace_id: workspaceId, + directory, + access: "read_execute", + state: "active", + }); + } + + /** + * Like core (ADR-0107): the assignment ends, and the workspace's read-execute grants on the + * profile's roots that no other assigned profile names are revoked. + */ + function mockUnassign(workspace: WorkspaceSettingsView, profile: ToolchainProfileView): void { + workspace.profiles = workspace.profiles.filter( + (name) => name.toLowerCase() !== profile.name.toLowerCase(), + ); + const kept = new Set( + settings.toolchain_profiles + .filter((other) => mockAssigned(workspace, other.name)) + .flatMap((other) => other.read_only_roots), + ); + settings.container_grants = settings.container_grants.filter( + (grant) => + grant.workspace_id !== workspace.workspace_id || + grant.access !== "read_execute" || + !profile.read_only_roots.includes(grant.directory) || + kept.has(grant.directory), + ); + } + /** Home folders need a grant; `/usr/local` needs an administrator; the rest is readable. */ function mockGrantNeed(workspaceId: string | null, folder: string): RootGrantNeed { if (workspaceId === null || !settings.container_grants_supported) { @@ -1996,6 +2073,7 @@ export function createMockBackend(now: () => number = Date.now): { invoke: Invok delete: "prompt", create_directory: "allow", }, + profiles: [], package_cache_root: null, instructions: "Run the tests before answering.", instructions_max_bytes: 0, @@ -2019,6 +2097,7 @@ export function createMockBackend(now: () => number = Date.now): { invoke: Invok delete: "allow", create_directory: "allow", }, + profiles: [], package_cache_root: null, instructions: "", instructions_max_bytes: 0, @@ -2056,12 +2135,13 @@ export function createMockBackend(now: () => number = Date.now): { invoke: Invok toolchain_profiles: [ { name: "rust", - platform: "linux", + platform: MOCK_PLATFORM, read_only_roots: ["/home/dev/.rustup"], path_entries: [], environment_names: ["RUSTUP_HOME"], }, ], + profile_platform: MOCK_PLATFORM, package_profiles: [], container_grants: [], container_grants_supported: true, diff --git a/crates/omgcode-desktop/ui/src/settings/app.ts b/crates/omgcode-desktop/ui/src/settings/app.ts index a1478afe..9b0e29de 100644 --- a/crates/omgcode-desktop/ui/src/settings/app.ts +++ b/crates/omgcode-desktop/ui/src/settings/app.ts @@ -146,8 +146,10 @@ const ACTIONS: Omit = { discoverToolchains: (workspaceId) => () => settingsApi.discoverToolchains(workspaceId), addDiscoveredProfiles: (digests, workspaceId) => (revision) => settingsApi.addDiscoveredProfiles(revision, digests, workspaceId), - grantDiscoveredRoots: (workspaceId, digests) => (revision) => - settingsApi.grantDiscoveredRoots(revision, workspaceId, digests), + assignToolchainProfile: (workspaceId, name) => (revision) => + settingsApi.assignToolchainProfile(revision, workspaceId, name), + unassignToolchainProfile: (workspaceId, name) => (revision) => + settingsApi.unassignToolchainProfile(revision, workspaceId, name), }; /** diff --git a/crates/omgcode-desktop/ui/src/settings/context.ts b/crates/omgcode-desktop/ui/src/settings/context.ts index f3d8d11a..89999dff 100644 --- a/crates/omgcode-desktop/ui/src/settings/context.ts +++ b/crates/omgcode-desktop/ui/src/settings/context.ts @@ -90,10 +90,19 @@ export interface Actions { * workspace, on Windows, each root says what its container needs. Records nothing. */ discoverToolchains(workspaceId: string | null): DiscoveryChange; - /** Records the proposals with these digests after one system confirmation. */ + /** + * Records the proposals with these digests after one system confirmation. With a workspace, + * the same confirmation names the folders its container is granted, and the profiles are + * assigned to it (ADR-0107). + */ addDiscoveredProfiles(digests: string[], workspaceId: string | null): DiscoveryChange; - /** Windows only. Grants the roots these proposals need after one system confirmation. */ - grantDiscoveredRoots(workspaceId: string, digests: string[]): DiscoveryChange; + /** + * Assigns a toolchain profile to a workspace (ADR-0107). Rust names the folders it grants the + * workspace's container in a system confirmation; the confirmation is the consent. + */ + assignToolchainProfile(workspaceId: string, name: string): Change; + /** Unassigns a toolchain profile and revokes the grants it alone needed; Rust confirms natively. */ + unassignToolchainProfile(workspaceId: string, name: string): Change; } /** diff --git a/crates/omgcode-desktop/ui/src/settings/discovery_panel.ts b/crates/omgcode-desktop/ui/src/settings/discovery_panel.ts index f8907266..15f91432 100644 --- a/crates/omgcode-desktop/ui/src/settings/discovery_panel.ts +++ b/crates/omgcode-desktop/ui/src/settings/discovery_panel.ts @@ -6,24 +6,25 @@ import { emptyLine, facts, row } from "./parts"; /** * Toolchain profiles proposed from the toolchains installed on this computer (ADR-0103). Rust * finds them by reading folders and runs nothing; this panel shows each proposal in full and - * sends back only the digests the operator selects. Each add or grant waits for one system - * confirmation that lists what it records. + * sends back only the digests the operator selects. An add waits for one system confirmation + * that lists what it records and, with a workspace chosen, the folders that workspace's + * container is granted when the profiles are assigned to it (ADR-0107). */ export const DISCOVER_LABEL = "Generate toolchain profiles from local packages"; export const ADD_SELECTED_LABEL = "Add selected profiles…"; -export const GRANT_SELECTED_LABEL = "Grant folders for selected…"; -/** The most proposals one add or grant sends; Rust refuses more. */ +/** The most proposals one add sends; Rust refuses more. */ export const MAX_SELECTED = 8; export const DISCOVERY_HELP = "OMGCode can look for installed toolchains (Rust, C and C++, Java, Python, Perl, Go, Node.js, .NET, and Ruby) in their standard install folders, on your PATH, and in the folders named by JAVA_HOME, GOROOT, and RUSTUP_HOME, and propose a profile for each. It only reads folders and small files the installers wrote. It runs no program and never reads a project's configuration, such as rust-toolchain.toml. Nothing is recorded until you select proposals and confirm them in a system dialog."; -export const DISCOVERY_GRANT_HELP = - "On Windows a run can read a root only when the workspace's container can. Choose a workspace to see which roots need a read-execute grant; a list already shown is generated again for it. A folder only an administrator can change is named, not granted."; +export const DISCOVERY_WORKSPACE_HELP = + "Choose a workspace to assign the profiles you add to it, so its commands can use them. On Windows each root then says whether that workspace's sandbox can read it, and the add grants the roots it cannot, after the system dialog names each folder. A folder only an administrator can change is named, not granted. A list already shown is generated again for the choice."; +export const ASSIGN_NOTE = "The profiles you add are also assigned to the chosen workspace."; export const NOTHING_FOUND = "No toolchain was found in the standard install folders, on PATH, or in the folders named by JAVA_HOME, GOROOT, and RUSTUP_HOME."; export const SELECTION_LIMIT = "Select at most 8 proposals at a time."; export const WORKSPACE_GRANT_MISSING = - "This workspace's sandbox has no active read-write grant on the workspace folder, which every run in it needs. Grant it under Container grants with Read and write the workspace's own folder."; + "This workspace's sandbox has no active read-write grant on the workspace folder, which every run in it needs. Register the folder again to grant it, or grant it under Container grants with Read and write."; export const NO_WORKSPACE = "No workspace"; /** Says how many installations the list leaves out. */ @@ -123,14 +124,14 @@ function proposalRow( } /** - * The workspace choice for container access, on Windows with a registered workspace. A list on - * screen is generated again for the new choice, so its grant states never describe another - * workspace. + * The workspace choice, with a registered workspace: the workspace an add assigns the profiles + * to and, on Windows, whose container access the roots report. A list on screen is generated + * again for the new choice, so its grant states never describe another workspace. */ function workspaceChoice(ctx: SectionContext): HTMLElement | null { const { overview, actions } = ctx; const state = ctx.view.executionForms.discovery; - if (!overview.container_grants_supported || overview.workspaces.length === 0) { + if (overview.workspaces.length === 0) { return null; } const choice = el("select", { attrs: { id: "discovery-workspace" } }); @@ -150,16 +151,16 @@ function workspaceChoice(ctx: SectionContext): HTMLElement | null { return el( "div", { class: "field" }, - el("label", { text: "Show container access for", attrs: { for: "discovery-workspace" } }), + el("label", { text: "Assign to workspace", attrs: { for: "discovery-workspace" } }), choice, ); } -/** The chosen workspace if it is still registered and grants exist here, else `null`. */ +/** The chosen workspace if it is still registered, else `null`. */ function chosenWorkspace(ctx: SectionContext): string | null { const { overview } = ctx; const chosen = ctx.view.executionForms.discovery.chosenWorkspace; - if (!overview.container_grants_supported || chosen === "") { + if (chosen === "") { return null; } return overview.workspaces.some((entry) => entry.workspace_id === chosen) ? chosen : null; @@ -167,7 +168,7 @@ function chosenWorkspace(ctx: SectionContext): string | null { /** * The discovery panel: a button that asks Rust for proposals, then each proposal with a checkbox, - * and buttons that add the selected ones or, on Windows, grant the folders they need. + * and a button that adds the selected ones and assigns them to the list's workspace, if any. */ export function discoveryPanel(ctx: SectionContext): HTMLElement { const { overview, actions } = ctx; @@ -184,7 +185,7 @@ export function discoveryPanel(ctx: SectionContext): HTMLElement { ); const choice = workspaceChoice(ctx); if (choice !== null) { - panel.append(el("p", { class: "muted", text: DISCOVERY_GRANT_HELP }), choice); + panel.append(el("p", { class: "muted", text: DISCOVERY_WORKSPACE_HELP }), choice); } panel.append(el("div", { class: "row-actions" }, generate)); const proposals = state.proposals; @@ -198,7 +199,7 @@ export function discoveryPanel(ctx: SectionContext): HTMLElement { if (state.omitted > 0) { panel.append(el("p", { class: "muted", text: omittedText(state.omitted) })); } - // The list's own workspace, not the one chosen since, decides the grants. + // The list's own workspace, not the one chosen since, decides the assignment and grants. const listWorkspace = overview.workspaces.some((w) => w.workspace_id === state.workspaceId) ? state.workspaceId : null; @@ -214,17 +215,6 @@ export function discoveryPanel(ctx: SectionContext): HTMLElement { } run(ctx, actions.addDiscoveredProfiles(digests, listWorkspace), false); }); - const grant = button(GRANT_SELECTED_LABEL, () => { - const digests = selectedDigests(); - if (digests.length > MAX_SELECTED) { - problem.textContent = SELECTION_LIMIT; - problem.hidden = false; - return; - } - if (listWorkspace !== null) { - run(ctx, actions.grantDiscoveredRoots(listWorkspace, digests), true); - } - }); /** The selected digests in list order, so the confirmation follows the list. */ function selectedDigests(): string[] { return (proposals ?? []) @@ -235,11 +225,6 @@ export function discoveryPanel(ctx: SectionContext): HTMLElement { problem.hidden = true; const chosen = (proposals ?? []).filter((proposal) => state.selected.has(proposal.digest)); add.disabled = !chosen.some((proposal) => proposal.refusal === null); - grant.disabled = - listWorkspace === null || - !chosen.some((proposal) => - proposal.read_only_roots.some((root) => root.grant === "needs_grant"), - ); } panel.append( el( @@ -249,11 +234,10 @@ export function discoveryPanel(ctx: SectionContext): HTMLElement { ), problem, ); - const buttons = el("div", { class: "row-actions" }, add); - if (overview.container_grants_supported) { - buttons.append(grant); + if (listWorkspace !== null) { + panel.append(el("p", { class: "muted", text: ASSIGN_NOTE })); } - panel.append(buttons); + panel.append(el("div", { class: "row-actions" }, add)); updateButtons(); return panel; } diff --git a/crates/omgcode-desktop/ui/src/settings/execution_forms.ts b/crates/omgcode-desktop/ui/src/settings/execution_forms.ts index aa508967..01cd2aaa 100644 --- a/crates/omgcode-desktop/ui/src/settings/execution_forms.ts +++ b/crates/omgcode-desktop/ui/src/settings/execution_forms.ts @@ -17,7 +17,7 @@ export const ENVIRONMENT_WARNING = export const PACKAGE_HELP = "A package-network profile records registry origins as configuration only. No run uses it and it grants no network access. Registry credentials are bound with the trusted CLI, not here. Removing a profile also unbinds and deletes the credentials bound to its origins. A profile cannot be edited: remove it and add it again."; export const GRANT_HELP = - "OMGCode runs each workspace's commands in that workspace's own AppContainer, a Windows sandbox that starts with no access to your files. Registering a folder as a workspace does not change that. A container grant adds the sandbox to one folder's access-control list on disk and stays until you revoke it. Every run needs read and write on the workspace's own folder; a toolchain outside it needs read and execute. A grant that shows pending or revoking did not finish: Revoke tries again."; + "OMGCode runs each workspace's commands in that workspace's own AppContainer, a Windows sandbox that starts with no access to your files. A container grant adds the sandbox to one folder's access-control list on disk and stays until you revoke it. Every run needs read and write on the workspace's own folder, which registering the folder grants; a toolchain outside it needs read and execute, which turning its profile on for the workspace grants. Grant other folders here. A grant that shows pending or revoking did not finish: Revoke tries again."; export const GRANT_READ_WRITE_HINT = "Lets the commands OMGCode runs for this workspace read and write its own folder, which every run needs. No folder dialog opens, because read and write can only be granted on the workspace's own folder. You confirm in a system dialog."; export const GRANT_READ_EXECUTE_HINT = diff --git a/crates/omgcode-desktop/ui/src/settings/workspace_profiles.ts b/crates/omgcode-desktop/ui/src/settings/workspace_profiles.ts new file mode 100644 index 00000000..3ac8beb0 --- /dev/null +++ b/crates/omgcode-desktop/ui/src/settings/workspace_profiles.ts @@ -0,0 +1,84 @@ +import { el } from "../dom"; +import type { ToolchainProfileView, WorkspaceSettingsView } from "../ipc/types"; +import type { SectionContext } from "./context"; + +/** Shown above the switches: what turning a profile on or off changes (ADR-0107). */ +export const PROFILES_HELP = + "A workspace's commands can use only the toolchain profiles turned on here. Turning one on " + + "lets them read and run its folders; on Windows a system dialog first names each folder the " + + "workspace's sandbox is granted. Turning one off stops its runs and revokes the grants no " + + "other profile here needs."; + +export const PROFILES_EMPTY = + "No toolchain profile is recorded for this computer. Add one under Advanced."; + +/** The accessible name of one profile's switch. */ +export function useProfileLabel(name: string): string { + return `Use ${name} in this workspace`; +} + +/** Whether `name` is assigned, compared as core compares names: case-insensitively. */ +function assigned(workspace: WorkspaceSettingsView, name: string): boolean { + const wanted = name.toLowerCase(); + return workspace.profiles.some((profile) => profile.toLowerCase() === wanted); +} + +function profileSwitch( + workspace: WorkspaceSettingsView, + profile: ToolchainProfileView, + { submit, actions }: SectionContext, +): HTMLElement { + const box = el("input", { + attrs: { type: "checkbox", "aria-label": useProfileLabel(profile.name) }, + }); + box.checked = assigned(workspace, profile.name); + box.addEventListener("change", () => { + const id = workspace.workspace_id; + submit( + box.checked + ? actions.assignToolchainProfile(id, profile.name) + : actions.unassignToolchainProfile(id, profile.name), + ); + }); + return el( + "label", + { class: "toggle workspace-profile" }, + box, + el( + "span", + { class: "perm-text" }, + el("span", { class: "perm-label", text: profile.name }), + el("span", { class: "perm-help", text: profile.read_only_roots.join(", ") }), + ), + ); +} + +/** + * One switch per toolchain profile recorded for this computer's platform. Turning a switch on + * asks Rust to assign the profile to the workspace, which shows the folders it grants in a system + * confirmation; turning it off asks Rust to unassign it. The window sends the workspace and the + * profile name only, and the switch shows the recorded state again after every change. + */ +export function workspaceProfilesBlock( + workspace: WorkspaceSettingsView, + ctx: SectionContext, +): HTMLElement { + // Only a profile of this computer's platform can run, and so be assigned, here. + const platform = ctx.overview.profile_platform; + const profiles = ctx.overview.toolchain_profiles.filter( + (profile) => profile.platform === platform, + ); + return el( + "div", + { class: "workspace-profiles" }, + el("span", { class: "perm-label", text: "Toolchain profiles" }), + el("p", { class: "perm-help", text: PROFILES_HELP }), + profiles.length === 0 + ? el("p", { class: "empty", text: PROFILES_EMPTY }) + : el( + "div", + { class: "workspace-profile-list" }, + ...profiles.map((profile) => profileSwitch(workspace, profile, ctx)), + ), + ); +} diff --git a/crates/omgcode-desktop/ui/src/settings/workspaces_section.ts b/crates/omgcode-desktop/ui/src/settings/workspaces_section.ts index 2cf41ab3..92440653 100644 --- a/crates/omgcode-desktop/ui/src/settings/workspaces_section.ts +++ b/crates/omgcode-desktop/ui/src/settings/workspaces_section.ts @@ -11,6 +11,7 @@ import { workspaceInstructionsBlock } from "./chat_section"; import { type SectionContext, scopedWorkspace } from "./context"; import { emptyLine, facts, sectionHead } from "./parts"; import { webHostsBlock } from "./web_hosts"; +import { workspaceProfilesBlock } from "./workspace_profiles"; export const WORKSPACES_HELP = "Workspaces are folders inside the development root. Tools reach only registered workspaces."; @@ -313,6 +314,9 @@ function workspaceBlock( if (key === "write") { return [row, toolLimits(workspace, ctx)]; } + if (key === "execute") { + return [row, workspaceProfilesBlock(workspace, ctx)]; + } return key === "web_fetch" ? [row, webHostsBlock(workspace, ctx)] : [row]; }), el( diff --git a/crates/omgcode-desktop/ui/tests/dist.test.ts b/crates/omgcode-desktop/ui/tests/dist.test.ts index 03e7d33c..3181dff1 100644 --- a/crates/omgcode-desktop/ui/tests/dist.test.ts +++ b/crates/omgcode-desktop/ui/tests/dist.test.ts @@ -85,12 +85,14 @@ suite( }); it("reads every settings-window command from the settings client", () => { - // 32 in `settings`, as `policy.rs` and the guide count them. - expect(SETTINGS_WINDOW_COMMANDS).toHaveLength(32); + // 33 in `settings`, as `policy.rs` and the guide count them. + expect(SETTINGS_WINDOW_COMMANDS).toHaveLength(33); expect(SETTINGS_WINDOW_COMMANDS).toContain("settings_overview"); expect(SETTINGS_WINDOW_COMMANDS).toContain("settings_discover_toolchains"); expect(SETTINGS_WINDOW_COMMANDS).toContain("settings_add_discovered_profiles"); - expect(SETTINGS_WINDOW_COMMANDS).toContain("settings_grant_discovered_roots"); + expect(SETTINGS_WINDOW_COMMANDS).toContain("settings_assign_toolchain_profile"); + expect(SETTINGS_WINDOW_COMMANDS).toContain("settings_unassign_toolchain_profile"); + expect(SETTINGS_WINDOW_COMMANDS).not.toContain("settings_grant_discovered_roots"); expect(SETTINGS_WINDOW_COMMANDS).toContain("settings_add_web_fetch_host"); expect(SETTINGS_WINDOW_COMMANDS).toContain("settings_remove_web_fetch_host"); expect(SETTINGS_WINDOW_COMMANDS).toContain("settings_revoke_container_grant"); diff --git a/crates/omgcode-desktop/ui/tests/settings_discovery.test.ts b/crates/omgcode-desktop/ui/tests/settings_discovery.test.ts index 9fdc3f97..e29b0598 100644 --- a/crates/omgcode-desktop/ui/tests/settings_discovery.test.ts +++ b/crates/omgcode-desktop/ui/tests/settings_discovery.test.ts @@ -6,9 +6,10 @@ import { HOSTILE } from "../src/mock/fixtures"; import { type SettingsApp, startSettings } from "../src/settings/app"; import { ADD_SELECTED_LABEL, + ASSIGN_NOTE, DISCOVER_LABEL, DISCOVERY_HELP, - GRANT_SELECTED_LABEL, + DISCOVERY_WORKSPACE_HELP, NOTHING_FOUND, omittedText, SELECTION_LIMIT, @@ -43,6 +44,7 @@ function overview(overrides: Partial = {}): SettingsOverview { host_services: "deny", web_fetch: "deny", web_fetch_hosts: [], + profiles: [], write_tools: { edit: "allow", multi_edit: "allow", @@ -65,6 +67,7 @@ function overview(overrides: Partial = {}): SettingsOverview { }, provider_profiles: [], toolchain_profiles: [], + profile_platform: "linux", package_profiles: [], container_grants: [], container_grants_supported: true, @@ -359,7 +362,7 @@ describe("adding proposals", () => { }); }); -describe("granting proposed roots on Windows", () => { +describe("assigning added proposals to a chosen workspace (ADR-0107)", () => { const NEEDS = proposal({ read_only_roots: [ { folder: "C:\\Users\\op\\go", grant: "needs_grant" }, @@ -414,7 +417,7 @@ describe("granting proposed roots on Windows", () => { // The roots now report the chosen workspace's access, and the selection is kept. expect(group().textContent).toContain("C:\\Users\\op\\go (needs a grant)"); expect(boxes()[0]?.checked).toBe(true); - expect(buttonByText(group(), GRANT_SELECTED_LABEL).disabled).toBe(false); + expect(group().textContent).toContain(ASSIGN_NOTE); choose(select(), ""); await settle(); @@ -422,6 +425,8 @@ describe("granting proposed roots on Windows", () => { workspace_id: null, }); expect(group().textContent).not.toContain("needs a grant"); + // Without a workspace an add assigns nothing, so the note is gone. + expect(group().textContent).not.toContain(ASSIGN_NOTE); }); it("does not ask Rust when a workspace is chosen before any list", async () => { @@ -437,14 +442,21 @@ describe("granting proposed roots on Windows", () => { expect(ipc.callsTo("settings_discover_toolchains")).toHaveLength(0); }); - it("sends the revision, the list's workspace, and the selected digests", async () => { + it("adds the selection to the list's workspace in one change and offers no separate grant", async () => { + const assigned = overview({ revision: 7 }); + const view = assigned.workspaces[0]; + if (view !== undefined) { + view.profiles = ["go"]; + } await start(() => overview(), { settings_discover_toolchains: () => discovery([NEEDS], { workspace_id: A }), - settings_grant_discovered_roots: () => + settings_add_discovered_profiles: () => discovery( [ { ...NEEDS, + recorded: true, + refusal: "a profile with this name already exists", read_only_roots: [ { folder: "C:\\Users\\op\\go", grant: "readable" }, { folder: "C:\\Program Files\\Go", grant: "readable" }, @@ -452,47 +464,58 @@ describe("granting proposed roots on Windows", () => { ], }, ], - { workspace_id: A, overview: overview({ revision: 6 }) }, + { workspace_id: A, overview: assigned }, ), }); await generate(); - const grant = buttonByText(group(), GRANT_SELECTED_LABEL); - expect(grant.disabled).toBe(true); + expect(group().textContent).toContain(ASSIGN_NOTE); + // Granting is part of the add's one confirmation now (ADR-0107): no other button grants. + const labels = Array.from(group().querySelectorAll("button")).map((b) => b.textContent ?? ""); + expect(labels.some((label) => label.includes("Grant"))).toBe(false); tick(0); - expect(grant.disabled).toBe(false); - grant.click(); + buttonByText(group(), ADD_SELECTED_LABEL).click(); await settle(); - expect(ipc.callsTo("settings_grant_discovered_roots")[0]?.args).toEqual({ + expect(ipc.callsTo("settings_add_discovered_profiles")[0]?.args).toEqual({ revision: 5, - workspace_id: A, digests: [digest(1)], + workspace_id: A, }); + expect(ipc.callsTo("settings_grant_discovered_roots")).toHaveLength(0); expect(group().textContent).toContain("C:\\Users\\op\\go (the container can read it)"); - // The grant keeps the selection, so the operator can add the profile next. - expect(boxes()[0]?.checked).toBe(true); - // No root of the selection needs a grant any more. - expect(buttonByText(group(), GRANT_SELECTED_LABEL).disabled).toBe(true); + expect(boxes()[0]?.checked).toBe(false); }); - it("offers no grant without a workspace in the list", async () => { + it("adds without a workspace when the list has none", async () => { await start(() => overview(), { settings_discover_toolchains: () => discovery([proposal()]), + settings_add_discovered_profiles: () => discovery([proposal({ recorded: true })]), }); await generate(); + expect(group().textContent).not.toContain(ASSIGN_NOTE); tick(0); - expect(buttonByText(group(), GRANT_SELECTED_LABEL).disabled).toBe(true); + buttonByText(group(), ADD_SELECTED_LABEL).click(); + await settle(); + expect(ipc.callsTo("settings_add_discovered_profiles")[0]?.args).toMatchObject({ + workspace_id: null, + }); }); - it("shows no workspace choice and no grant button off Windows", async () => { - await start(() => overview({ container_grants_supported: false }), { - settings_discover_toolchains: () => - discovery([proposal()], { overview: overview({ container_grants_supported: false }) }), + it("offers the workspace choice off Windows too, where an assignment grants nothing", async () => { + const linux = overview({ container_grants_supported: false }); + await start(() => linux, { + settings_discover_toolchains: (args) => + discovery([proposal()], { overview: linux, workspace_id: args.workspace_id as string }), }); - expect(group().querySelector("#discovery-workspace")).toBeNull(); + expect(group().textContent).toContain(DISCOVERY_WORKSPACE_HELP); + const select = group().querySelector("#discovery-workspace"); + if (select === null) { + throw new Error("No workspace choice"); + } + choose(select, A); await generate(); - expect(ipc.callsTo("settings_discover_toolchains")[0]?.args).toEqual({ workspace_id: null }); - expect(() => buttonByText(group(), GRANT_SELECTED_LABEL)).toThrow(); + expect(ipc.callsTo("settings_discover_toolchains")[0]?.args).toEqual({ workspace_id: A }); + expect(group().textContent).toContain(ASSIGN_NOTE); }); }); @@ -541,34 +564,54 @@ describe("mock discovery commands", () => { ).rejects.toMatchObject({ code: "invalid_request" }); }); - it("grants the home-folder roots a workspace needs and then reports them readable", async () => { + it("assigns what it adds to a workspace and grants the home-folder roots it needs", async () => { const { invoke } = createMockBackend() as { invoke: Invoke }; const settings = (await invoke("settings_overview", {})) as SettingsOverview; const workspace = settings.workspaces[0]?.workspace_id ?? ""; + // The recorded `rust` profile blocks its sample; removing it frees the one sample whose + // roots include a home folder. + const freed = (await invoke("settings_remove_toolchain_profile", { + revision: settings.revision, + name: "rust", + })) as SettingsOverview; const listed = (await invoke("settings_discover_toolchains", { workspace_id: workspace, })) as ToolchainDiscovery; - const needing = listed.proposals.find((entry) => - entry.read_only_roots.some((rootEntry) => rootEntry.grant === "needs_grant"), + const needing = listed.proposals.find( + (entry) => + entry.refusal === null && + entry.read_only_roots.some((rootEntry) => rootEntry.grant === "needs_grant"), ); if (needing === undefined) { - throw new Error("a sample needs a grant"); + throw new Error("an addable sample needs a grant"); } - const granted = (await invoke("settings_grant_discovered_roots", { - revision: listed.overview.revision, - workspace_id: workspace, + const home = needing.read_only_roots.find((rootEntry) => rootEntry.grant === "needs_grant"); + const added = (await invoke("settings_add_discovered_profiles", { + revision: freed.revision, digests: [needing.digest], + workspace_id: workspace, })) as ToolchainDiscovery; - const after = granted.proposals.find((entry) => entry.digest === needing.digest); + + expect(added.overview.workspaces[0]?.profiles).toEqual([needing.name]); + expect(added.overview.container_grants).toEqual([ + expect.objectContaining({ + workspace_id: workspace, + directory: home?.folder, + access: "read_execute", + state: "active", + }), + ]); + const after = added.proposals.find((entry) => entry.digest === needing.digest); expect(after?.read_only_roots.some((rootEntry) => rootEntry.grant === "needs_grant")).toBe( false, ); + // The separate grant command is gone (ADR-0107). await expect( invoke("settings_grant_discovered_roots", { - revision: granted.overview.revision, + revision: added.overview.revision, workspace_id: workspace, digests: [needing.digest], }), - ).rejects.toMatchObject({ code: "nothing_to_grant" }); + ).rejects.toMatchObject({ code: "unknown_command" }); }); }); diff --git a/crates/omgcode-desktop/ui/tests/settings_execution.test.ts b/crates/omgcode-desktop/ui/tests/settings_execution.test.ts index 4d489eca..758bc1a6 100644 --- a/crates/omgcode-desktop/ui/tests/settings_execution.test.ts +++ b/crates/omgcode-desktop/ui/tests/settings_execution.test.ts @@ -46,6 +46,7 @@ function overview(overrides: Partial = {}): SettingsOverview { host_services: "deny", web_fetch: "deny", web_fetch_hosts: [], + profiles: [], write_tools: { edit: "allow", multi_edit: "allow", @@ -68,6 +69,7 @@ function overview(overrides: Partial = {}): SettingsOverview { }, provider_profiles: [], toolchain_profiles: [], + profile_platform: "linux", package_profiles: [], container_grants: [], container_grants_supported: true, @@ -432,6 +434,58 @@ describe("mock execution commands", () => { expect(removed.toolchain_profiles.some((entry) => entry.name === "node")).toBe(false); }); + it("assigns a profile, grants its home-folder root, and revokes it on unassign (ADR-0107)", async () => { + const { invoke } = createMockBackend(); + const before = await overviewOf(invoke); + const workspace = before.workspaces[0]?.workspace_id ?? ""; + const change = (command: string, revision: number) => + invoke(command, { revision, workspace_id: workspace, name: "rust" }); + + const assigned = (await change( + "settings_assign_toolchain_profile", + before.revision, + )) as SettingsOverview; + expect(assigned.workspaces[0]?.profiles).toEqual(["rust"]); + expect(assigned.container_grants).toEqual([ + expect.objectContaining({ + workspace_id: workspace, + directory: "/home/dev/.rustup", + access: "read_execute", + state: "active", + }), + ]); + await expect( + change("settings_assign_toolchain_profile", assigned.revision), + ).rejects.toMatchObject({ code: "control" }); + + const unassigned = (await change( + "settings_unassign_toolchain_profile", + assigned.revision, + )) as SettingsOverview; + expect(unassigned.workspaces[0]?.profiles).toEqual([]); + expect(unassigned.container_grants).toEqual([]); + await expect( + change("settings_unassign_toolchain_profile", unassigned.revision), + ).rejects.toMatchObject({ code: "control" }); + }); + + it("ends the assignments and their grants when an assigned profile is removed", async () => { + const { invoke } = createMockBackend(); + const before = await overviewOf(invoke); + const workspace = before.workspaces[0]?.workspace_id ?? ""; + const assigned = (await invoke("settings_assign_toolchain_profile", { + revision: before.revision, + workspace_id: workspace, + name: "rust", + })) as SettingsOverview; + const removed = (await invoke("settings_remove_toolchain_profile", { + revision: assigned.revision, + name: "rust", + })) as SettingsOverview; + expect(removed.workspaces.every((entry) => entry.profiles.length === 0)).toBe(true); + expect(removed.container_grants).toEqual([]); + }); + it("adds and removes a package profile and refuses a bad origin", async () => { const { invoke } = createMockBackend(); const before = await overviewOf(invoke); diff --git a/crates/omgcode-desktop/ui/tests/settings_sections.test.ts b/crates/omgcode-desktop/ui/tests/settings_sections.test.ts index 8dcb630e..2afbd6f0 100644 --- a/crates/omgcode-desktop/ui/tests/settings_sections.test.ts +++ b/crates/omgcode-desktop/ui/tests/settings_sections.test.ts @@ -3,6 +3,7 @@ import { setInvoker } from "../src/ipc/client"; import type { ProviderProfileView, SettingsOverview, + ToolchainProfileView, WorkspaceSettingsView, WriteToolAccess, } from "../src/ipc/types"; @@ -17,6 +18,7 @@ import { WEB_HOSTS_HELP, webHostMessage, } from "../src/settings/web_hosts"; +import { PROFILES_EMPTY, PROFILES_HELP, useProfileLabel } from "../src/settings/workspace_profiles"; import { ALL_TOOLS_LABEL, PACKAGE_CACHE_HELP, @@ -56,6 +58,7 @@ function workspace(id: string, folder: string, extra: Partial = {}): SettingsOverview { }, provider_profiles: [profile()], toolchain_profiles: [], + profile_platform: "linux", package_profiles: [], container_grants: [], container_grants_supported: true, @@ -1319,3 +1323,110 @@ describe("web fetch", () => { expect(listed()).toEqual([hostile]); }); }); + +describe("toolchain profiles on the workspace page (ADR-0107)", () => { + function toolchain( + name: string, + platform: ToolchainProfileView["platform"], + ): ToolchainProfileView { + return { + name, + platform, + read_only_roots: [`/opt/${name}`], + path_entries: [`/opt/${name}/bin`], + environment_names: [], + }; + } + + const RECORDED = [ + toolchain("rust", "linux"), + toolchain("go", "linux"), + toolchain("msvc", "windows"), + ]; + + function profileSwitch(name: string): HTMLInputElement | null { + return root.querySelector(`input[aria-label="${useProfileLabel(name)}"]`); + } + + function flip(name: string): void { + const box = profileSwitch(name); + if (box === null) { + throw new Error(`No switch for ${name}`); + } + box.checked = !box.checked; + box.dispatchEvent(new Event("change")); + } + + it("shows one switch per profile of this platform, on when assigned", async () => { + await start(() => + overview({ + toolchain_profiles: RECORDED, + // Core compares names case-insensitively, and so does the page. + workspaces: [workspace(A, "/home/dev/a", { execute: "allow", profiles: ["RUST"] })], + }), + ); + expect(root.textContent).toContain(PROFILES_HELP); + expect(profileSwitch("rust")?.checked).toBe(true); + expect(profileSwitch("go")?.checked).toBe(false); + // A Windows profile cannot run here, so it is not offered. + expect(profileSwitch("msvc")).toBeNull(); + expect(root.querySelector(".workspace-profile")?.textContent).toContain("/opt/rust"); + }); + + it("asks Rust to assign or unassign with the revision, the workspace, and the name only", async () => { + await start( + () => + overview({ + toolchain_profiles: RECORDED, + workspaces: [workspace(A, "/home/dev/a", { profiles: ["rust"] })], + }), + { + settings_assign_toolchain_profile: () => + overview({ + revision: 4, + toolchain_profiles: RECORDED, + workspaces: [workspace(A, "/home/dev/a", { profiles: ["rust", "go"] })], + }), + settings_unassign_toolchain_profile: () => + overview({ + revision: 5, + toolchain_profiles: RECORDED, + workspaces: [workspace(A, "/home/dev/a", { profiles: ["go"] })], + }), + }, + ); + flip("go"); + await settle(); + expect(ipc.callsTo("settings_assign_toolchain_profile")[0]?.args).toEqual({ + revision: 3, + workspace_id: A, + name: "go", + }); + expect(profileSwitch("go")?.checked).toBe(true); + + flip("rust"); + await settle(); + expect(ipc.callsTo("settings_unassign_toolchain_profile")[0]?.args).toEqual({ + revision: 4, + workspace_id: A, + name: "rust", + }); + expect(profileSwitch("rust")?.checked).toBe(false); + }); + + it("shows the recorded state again when the operator declines", async () => { + await start(() => overview({ toolchain_profiles: RECORDED }), { + settings_assign_toolchain_profile: () => rejection("cancelled", "No change was made."), + }); + flip("go"); + await settle(); + expect(ipc.callsTo("settings_assign_toolchain_profile")).toHaveLength(1); + expect(profileSwitch("go")?.checked).toBe(false); + }); + + it("says where to add one when no profile of this platform is recorded", async () => { + await start(() => overview({ toolchain_profiles: [toolchain("msvc", "windows")] })); + expect(root.textContent).toContain(PROFILES_EMPTY); + expect(root.querySelector(".workspace-profile")).toBeNull(); + }); +}); diff --git a/crates/omgcode-desktop/ui/tests/settings_skills.test.ts b/crates/omgcode-desktop/ui/tests/settings_skills.test.ts index 88b9a274..70662ed7 100644 --- a/crates/omgcode-desktop/ui/tests/settings_skills.test.ts +++ b/crates/omgcode-desktop/ui/tests/settings_skills.test.ts @@ -31,6 +31,7 @@ function workspace(id: string, folder: string): SettingsOverview["workspaces"][n host_services: "deny", web_fetch: "deny", web_fetch_hosts: [], + profiles: [], write_tools: { edit: "allow", multi_edit: "allow", @@ -62,6 +63,7 @@ function overview( }, provider_profiles: [], toolchain_profiles: [], + profile_platform: "linux", package_profiles: [], container_grants: [], container_grants_supported: true, diff --git a/crates/omgcode-desktop/ui/tests/settings_window.test.ts b/crates/omgcode-desktop/ui/tests/settings_window.test.ts index c7d04e5c..920eb93c 100644 --- a/crates/omgcode-desktop/ui/tests/settings_window.test.ts +++ b/crates/omgcode-desktop/ui/tests/settings_window.test.ts @@ -61,6 +61,7 @@ function workspace(overrides: Partial = {}): WorkspaceSet host_services: "deny", web_fetch: "deny", web_fetch_hosts: [], + profiles: [], write_tools: { ...ALL_TOOLS }, package_cache_root: null, instructions: "", @@ -121,6 +122,7 @@ function overview(overrides: Partial = {}): SettingsOverview { environment_names: ["RUSTUP_HOME"], }, ], + profile_platform: "linux", package_profiles: [], container_grants: [], container_grants_supported: true, diff --git a/docs/adr/0107-assign-toolchain-profiles-to-workspaces-and-grant-on-assignment.md b/docs/adr/0107-assign-toolchain-profiles-to-workspaces-and-grant-on-assignment.md new file mode 100644 index 00000000..f03b4427 --- /dev/null +++ b/docs/adr/0107-assign-toolchain-profiles-to-workspaces-and-grant-on-assignment.md @@ -0,0 +1,169 @@ +# 0107: Assign toolchain profiles to workspaces and grant on assignment + +- Status: Accepted +- Date: 2026-11-27 + +## Context + +A toolchain profile was recorded once for the whole computer, and every +workspace whose `execute` preference allowed it could run any recorded +profile ([ADR-0029](0029-confine-windows-runs-in-a-workspace-appcontainer-with-recorded-grants.md), +[ADR-0100](0100-list-the-recorded-toolchain-profiles-in-the-command-tool.md)). +On Windows each workspace runs in its own AppContainer, so it can use a +profile only after its container has a read-execute grant on each of the +profile's folders that every application package cannot already read. Those +grants were a separate step, done per folder under **Container grants** or, +for discovered toolchains, with a separate command after its own +confirmation ([ADR-0103](0103-generate-toolchain-profiles-from-installed-toolchains.md)). +Registering a workspace granted nothing, and the operator then granted its +folder read-write without a folder dialog +([ADR-0104](0104-grant-the-workspace-folder-read-write-without-a-folder-dialog.md)). + +An operator's model command in one workspace failed because the container had +no grant on the rustup toolchain under the user's own folder. ADR-0106 now +names the missing grant, but the operator still had to find out that a +recorded profile does nothing in a workspace until its folders are granted +there. Recording a profile looked like the decision to use it, and the grant +looked like a technical detail. + +The operator's direction was that adding a toolchain to a workspace is the +consent to give that workspace's sandbox the toolchain's folders. A draft +that granted missing folders when a run started, automatically under `allow` +and after an approval under `prompt`, was written and dropped before it was +committed: it put a filesystem grant behind a model's request and behind a +per-call approval of a command, which is a different decision. + +## Decision + +1. **Profiles are assigned to workspaces.** A workspace records the + identifiers of the profiles assigned to it, in assignment order. Two + control events record the change, `profile_assigned` and + `profile_unassigned`, and each advances the revision. Replay rebuilds the + list and refuses an unknown workspace or profile, an assignment that + already exists, and an unassignment of one that does not. Removing a + profile ends every assignment of it, and unregistering a workspace drops + its list. `workspace status` shows each workspace's assigned profiles. An + older build refuses the new events, as it refuses any event it does not + know. Assigning refuses a profile declared on another platform. +2. **A run needs an assigned profile.** The runner refuses a recorded profile + that is not assigned to the run's workspace before anything starts, with + text that names no path and says to assign it in the `settings` window or + with `omgcode workspace profile-assign`. The run watcher withdraws a run + whose profile was unassigned, as it does for any other settings change + that withdraws a run. The model command tool is offered only while at + least one profile of this platform is assigned to the workspace, and its + `profile` parameter lists only those profiles. A command that names + another profile is still answered with `profile_not_recorded`, whose text + now says "assigned to this workspace". The tool schema version is 0.10.0. +3. **Assigning is the consent to grant.** On Windows, assigning plans the + read-execute grants first: each live root the workspace's container + cannot read yet, each folder once, skipping a folder that already has a + recorded grant of the workspace. Folders that only an administrator + can grant, and folders whose access-control list could not be read, are + listed apart and not granted. The operator confirms that plan. Under the + store's lock core plans again and refuses the assignment if the folders + to grant changed, so no folder is granted that the operator did not see. + Core then checks the batch against the grant limits, applies each grant, + and records the assignment last. A failed grant leaves the profile + unassigned; grants applied before it stay recorded, and one whose + access-control change failed stays `pending` until it is revoked. Off + Windows the plan is empty and assigning records only the event. +4. **Registering grants the workspace folder.** On Windows, registering a + folder grants its container read-write on that folder when no grant of the + workspace is recorded on it and this account can change the folder's + access-control list. Registering an already registered folder that has no + such grant grants it, which is how a workspace registered before this + change gets it. A failed grant leaves the workspace registered and is + reported. +5. **Removing revokes what is no longer needed.** Unassigning a profile, and + removing an assigned profile, revoke the workspace's read-execute grants + on that profile's roots that no profile still assigned to the workspace + lists and that are not the workspace's package cache root. The workspace + folder's read-write grant is never revoked by these. Unregistering a + workspace revokes every grant of the workspace first and unregisters it + only when every revocation was confirmed; otherwise it stays registered + with the grants not yet revoked, and the operator retries. The + unregistration primitive and replay still refuse while a grant exists + ([ADR-0081](0081-unregister-a-workspace.md)). Any revocation still + withdraws every run of its workspace, so each caller lists the pending + runs before the change and waits for those of the workspaces whose grants + it tried to revoke. +6. **The trusted CLI and the `settings` window ask for the assignment.** + - `omgcode workspace profile-assign --revision ` + plans and assigns, since running it is the consent; it prints the + assigned profile, the grants made, and the folders not granted with the + reason. `profile-unassign` prints what it revoked. `register` adds the + grant it made, and `unregister` and `profile-remove` add what they + revoked. + - The workspace page of the `settings` window shows one switch per + recorded profile of this platform. Turning one on runs + `settings_assign_toolchain_profile`, whose native confirmation names the + workspace, the profile, each folder to grant, and the folders that are + skipped; turning one off runs `settings_unassign_toolchain_profile`, + whose confirmation names the grants it revokes and says the workspace's + runs stop. The register, unregister, and remove-profile confirmations + say what they grant or revoke. + - Adding discovered profiles with a workspace chosen also assigns them in + the same confirmation, which lists the folders it grants. The separate + `settings_grant_discovered_roots` command is removed. The workspace + choice is shown on every platform. +7. **No migration.** Existing profiles start assigned to no workspace. A + workspace's model command tool is withheld, and its CLI runs are refused, + until the operator assigns a profile to it once. Grants already recorded + stay, so assigning a profile whose folders are granted grants nothing new. + +## Alternatives considered + +- **Grant at run time.** Grant missing folders when a run starts, without a + prompt under `allow` and after an approval under `prompt`. The grant would + follow a model's request rather than an operator's decision about the + workspace, and an `allow` workspace would widen its sandbox with no + operator action at all. Dropped before it was committed. +- **Keep profiles global and grant every workspace.** Recording a profile + would grant its folders to every registered workspace, and to each one + registered later. That widens every sandbox for a toolchain one project + needs, and removing it from one workspace would mean removing it from all. +- **Keep the separate grant step and only explain it better.** The + refusal already names the missing grant (ADR-0106). Separate steps still + let a recorded profile look usable when it is not. +- **Migrate by assigning every profile to every workspace.** It would keep + existing runs working but turn a global setting into many per-workspace + consents the operator never gave, and on Windows it would have to apply + grants during an upgrade. +- **Grant every planned folder, including those that need an + administrator.** This account cannot change them; listing them lets the + operator ask an administrator, and a run that needs one is refused with + ADR-0106's text. + +## Consequences + +- An operator decides once per workspace which toolchains it may run, and on + Windows that decision is also the grant. The grant is not hidden: the CLI + prints it and the `settings` window confirms it natively. +- A workspace registered before this change has no assigned profile, so its + model has no command tool and its CLI runs are refused until a profile is + assigned. On Windows, registering the folder again grants read-write if + that grant is missing. +- Unassigning or removing a profile, or unregistering a workspace, can stop + the workspace's runs, because any revocation withdraws them. +- The mapping from roots to grants is by folder: a grant whose folder is also + a root of another assigned profile, or the workspace's package cache root, + stays. +- Core tests cover recording, replay, refusals, removal, plans, plan + changes, the grants a removal releases, and the workspaces a revocation + names. Run and turn tests cover the unassigned-profile refusal, the + watcher, and the tool list. Windows CLI and desktop service tests apply and + revoke real grants on temporary folders; desktop tests that are not about + registration record workspaces without granting. The desktop shell's + native dialogs were not driven. + +## References + +- [ADR-0029](0029-confine-windows-runs-in-a-workspace-appcontainer-with-recorded-grants.md), + [ADR-0081](0081-unregister-a-workspace.md), + [ADR-0088](0088-change-execution-settings-in-the-settings-window.md), + [ADR-0100](0100-list-the-recorded-toolchain-profiles-in-the-command-tool.md), + [ADR-0103](0103-generate-toolchain-profiles-from-installed-toolchains.md), + [ADR-0104](0104-grant-the-workspace-folder-read-write-without-a-folder-dialog.md), + [ADR-0106](0106-name-the-ungranted-run-path-by-its-role.md) +- [docs/execution.md](../execution.md) diff --git a/docs/adr/index.md b/docs/adr/index.md index 1ebe2022..c3d45848 100644 --- a/docs/adr/index.md +++ b/docs/adr/index.md @@ -121,3 +121,4 @@ meaningful alternative does not need an ADR. | [0104: Grant the workspace folder read-write without a folder dialog](0104-grant-the-workspace-folder-read-write-without-a-folder-dialog.md) | Accepted | 2026-11-26 | | [0105: Show the approvals window when a turn starts waiting](0105-show-the-approvals-window-when-a-turn-starts-waiting.md) | Accepted | 2026-11-26 | | [0106: Name the ungranted run path by its role](0106-name-the-ungranted-run-path-by-its-role.md) | Accepted | 2026-11-26 | +| [0107: Assign toolchain profiles to workspaces and grant on assignment](0107-assign-toolchain-profiles-to-workspaces-and-grant-on-assignment.md) | Accepted | 2026-11-27 | diff --git a/docs/desktop-interface.md b/docs/desktop-interface.md index b58ebfdf..2a630240 100644 --- a/docs/desktop-interface.md +++ b/docs/desktop-interface.md @@ -119,11 +119,19 @@ merged to `main` at the time of writing): package-network profiles, and, on Windows, container grants. See [settings window](#settings-window). - Since version 0.68.0 (ADR-0103), the **Toolchain profiles** group generates - profile proposals from the toolchains installed on this computer, and on - Windows grants a selected workspace's container the folders it needs that - this account can change, after one native confirmation per batch; folders - that need an administrator, or whose access-control list could not be - read, are named and skipped. Discovery runs no program. + profile proposals from the toolchains installed on this computer. Since + 0.70.0 (ADR-0107), adding them with a workspace chosen also assigns them to + it and, on Windows, grants that workspace's container the folders it needs + that this account can change, in the same native confirmation; folders that + need an administrator, or whose access-control list could not be read, are + named and skipped. Discovery runs no program. +- Since version 0.70.0 (ADR-0107), each workspace's page has a switch per + toolchain profile of this platform. Turning one on assigns the profile to + the workspace and, on Windows, grants its container the profile's folders, + after a native confirmation that names them; turning one off revokes the + grants no other assigned profile needs. On Windows, registering a workspace + grants its container read and write on its folder, and removing one revokes + its grants first. Not implemented: @@ -283,7 +291,7 @@ has not been run, so how it behaves in a delegated cgroup is unverified. ## Windows and commands -The shell has three webview windows and 66 commands (31 in `main`, 3 in `approvals`, and 32 in `settings`). No other command exists. +The shell has three webview windows and 67 commands (31 in `main`, 3 in `approvals`, and 33 in `settings`). No other command exists. No command accepts a host path. Sessions are addressed by UUID, workspaces by their registered identifier, and approvals by identifier. @@ -327,13 +335,13 @@ their registered identifier, and approvals by identifier. | `settings_save_chat_defaults` | settings | Save the chat budgets and the global custom instructions; no dialog (ADR-0080) | | `settings_set_workspace_instructions` | settings | Replace one registered workspace's custom instructions; empty removes them; no dialog (ADR-0080) | | `settings_choose_root` | settings | Choose the development root in a native folder dialog, after a native confirmation | -| `settings_register_workspace` | settings | Register a folder below the root, chosen in a native dialog, after a native confirmation | +| `settings_register_workspace` | settings | Register a folder below the root, chosen in a native dialog, after a native confirmation; on Windows the confirmation also says the workspace's sandbox gets read and write on the folder, which registering grants (ADR-0107) | | `settings_set_permissions` | settings | Set one workspace's preferences and per-tool write limits; widening any needs a native confirmation | | `settings_choose_package_cache` | settings | Choose one workspace's package cache root in a native dialog, after a native confirmation | | `settings_clear_package_cache` | settings | Clear one workspace's package cache root; files stay in place | | `settings_add_web_fetch_host` | settings | Add one host pattern to a workspace's `web_fetch` allowlist after a native confirmation that names the folder and the canonical pattern (ADR-0098) | | `settings_remove_web_fetch_host` | settings | Remove one host pattern from a workspace's `web_fetch` allowlist after a native confirmation (ADR-0098) | -| `settings_unregister_workspace` | settings | Remove one workspace's registration after a native confirmation that names its folder; its settings and instructions file go, its files and sessions stay (ADR-0081) | +| `settings_unregister_workspace` | settings | Remove one workspace's registration after a native confirmation that names its folder and the container grants revoked first; its settings and instructions file go, its files and sessions stay (ADR-0081, ADR-0107) | | `settings_select_connection` | settings | Choose the default or a recorded profile with an endpoint (a hosted one also needs a bound credential) as the model connection, after a native confirmation | | `settings_add_connection` | settings | Record an `lm_studio` or `ollama_local` profile with a loopback endpoint and no credential, a named hosted profile with its fixed endpoint and a write-only API key, or an `openai_compatible` profile with a typed HTTPS endpoint and a write-only API key (ADR-0092) | | `settings_set_api_key` | settings | Replace the stored API key of a hosted `api_key` profile; the key is write-only and no dialog is shown | @@ -347,14 +355,15 @@ their registered identifier, and approvals by identifier. | `settings_set_skill_state` | settings | Set a skill's application setting or one workspace's override (`enabled`, `disabled`, `inherit`); a change that leaves it enabled needs a native confirmation that names it (ADR-0082) | | `settings_remove_skill` | settings | Remove a skill and delete its stored copy after a native confirmation that names it; the source folder is kept (ADR-0082) | | `settings_add_toolchain_profile` | settings | Open a native folder dialog for each read-only root and `PATH` entry, then, after a native confirmation that lists them and the variable names, record a toolchain profile as `workspace profile-add` does (ADR-0088) | -| `settings_remove_toolchain_profile` | settings | Remove a toolchain profile after a native confirmation; the runs the settings then withdraw are stopped (ADR-0088) | +| `settings_remove_toolchain_profile` | settings | Remove a toolchain profile after a native confirmation that names each workspace it is assigned to and the grants revoked there; the runs the settings then withdraw are stopped (ADR-0088, ADR-0107) | +| `settings_assign_toolchain_profile` | settings | Assign a toolchain profile to one workspace after a native confirmation that names the workspace, the profile, each folder the workspace's container is granted read and execute, and the folders it cannot grant (ADR-0107) | +| `settings_unassign_toolchain_profile` | settings | End one assignment after a native confirmation that names the grants it revokes and says the workspace's runs stop (ADR-0107) | | `settings_add_package_profile` | settings | Record a package-network profile (configuration only) after a native confirmation that lists the origins core parsed (ADR-0088) | | `settings_remove_package_profile` | settings | Remove a package-network profile, which also unbinds and deletes the credentials bound to its origins, after a native confirmation (ADR-0088) | | `settings_grant_container_folder` | settings | Windows only. Open a native folder dialog and, after a native confirmation that names the workspace, folder, and access and says the folder's access-control list changes, grant it to the workspace's container (ADR-0088) | | `settings_revoke_container_grant` | settings | Windows only. Revoke one recorded grant after a native confirmation and stop the workspace's earlier runs (ADR-0088) | | `settings_discover_toolchains` | settings | Read the standard install folders and the operator's `PATH` and return toolchain profile proposals with core's refusal reason for each; with a workspace, on Windows, each root's container access. Runs no program and records nothing (ADR-0103) | -| `settings_add_discovered_profiles` | settings | Discover again and, after one native confirmation that lists every root, `PATH` entry, and variable, record the proposals whose digests the window sent as `workspace profile-add` does (ADR-0103) | -| `settings_grant_discovered_roots` | settings | Windows only. Discover again, check every folder with core's grant rules, and, after one native confirmation that names the workspace and every folder, grant read-execute access to the selected proposals' roots that the container cannot read and this account can grant (ADR-0103) | +| `settings_add_discovered_profiles` | settings | Discover again and, after one native confirmation that lists every root, `PATH` entry, and variable, record the proposals whose digests the window sent as `workspace profile-add` does; with a workspace, also assign them to it, granting on Windows the folders its container needs, named in the same confirmation (ADR-0103, ADR-0107) | `main` shows the session tree, search, transcripts, and chat. It renders transcript text. `approvals` lists approval records, shows the reviewed @@ -1317,7 +1326,21 @@ waits. The window shows: preference set once with all six limits at that state and `write` unchanged, so a widening change shows one native confirmation that names each widened limit. It marks a state only while all six limits share it, - and none while they differ. Then the workspace identifier and its package cache root with + and none while they differ. Under Execute, **Toolchain profiles** + (ADR-0107) has one switch per recorded profile of this platform, named + "Use NAME in this workspace" and on while the profile is assigned, with + the profile's read-only roots beside it; with no profile of this platform + it says to add one under **Advanced**. Turning a switch on calls + `settings_assign_toolchain_profile` with the revision, the workspace + identifier, and the profile name. Rust plans the grants and shows a native + confirmation that names the workspace folder, the profile, each folder the + workspace's sandbox is granted read and execute, and the folders that need + an administrator or whose access could not be read, then grants and assigns + with the confirmed plan. Turning one off calls + `settings_unassign_toolchain_profile`, whose confirmation names the grants + it revokes and says the workspace's running commands stop. A declined + confirmation or a refusal shows the recorded state again. Then the + workspace identifier and its package cache root with **Choose…** and, when one is set, **Clear**, and one line of help: the root is where the trusted CLI command `omgcode packages fetch` stores downloads for that workspace, a trusted run exposes it read-only, and the app never @@ -1355,14 +1378,21 @@ waits. The window shows: **Workspaces**; the scoped view has none. It calls `settings_unregister_workspace` with the workspace identifier and the revision the window read, never a path. Rust refuses an unknown workspace, a - stale revision, a workspace that a container grant names (revoke it under - **Advanced** or with the trusted CLI first), and a workspace in which a chat turn is running, all - before any dialog. A native Yes/No confirmation then names the folder and - states that its preferences, instructions, package cache selection, skill + stale revision, and a workspace in which a chat turn is running, all + before any dialog. A native Yes/No confirmation then names the folder, + lists the folders its container was granted, which are revoked first and + whose runs stop (ADR-0107), and states that its preferences, toolchain + profile assignments, instructions, package cache selection, skill overrides, and checkpoint record are removed, that its files are not touched, and that its sessions stay and can chat without tools only. On - Yes, one `workspace_unregistered` event is recorded and the workspace's - instructions file is deleted under the preferences lock. If that file cannot + Yes, the grants are revoked; when every revocation is confirmed, one + `workspace_unregistered` event is recorded and the workspace's + instructions file is deleted under the preferences lock. When a grant + cannot be revoked, the workspace stays registered with the grants not yet + revoked, the runs the revocations withdrew are stopped and waited for, and + the command fails with `container_access_failed` or + `revocation_incomplete`, saying to retry the grant's **Revoke** and remove + the workspace again. If that file cannot be deleted, the command still stops and waits for the runs the removal withdraws, then fails with `instructions_orphaned` (a run that was not stopped is reported first); no turn sends the file, because `chat_send` @@ -1395,7 +1425,9 @@ waits. The window shows: root, a name in use) come back as controlled errors after the dialogs. Removing is confirmed natively and stops the runs the settings then withdraw, as `workspace profile-remove` does; a run already started keeps - its recorded profile. + its recorded profile. Since ADR-0107 the confirmation says the profile is + assigned to no workspace, or names each workspace it is assigned to and + the grants revoked there, which no profile still assigned needs. **Generate toolchain profiles from local packages** (ADR-0103) sits above the add form. It asks Rust for proposals, which core makes by reading the @@ -1405,24 +1437,24 @@ waits. The window shows: proposal shows its name, family, version, roots, `PATH` entries, variables with their values, notes, and, when core would refuse it now, the reason, with its checkbox disabled. A line says how many installations the list - left out when a bound was reached. On Windows a **Show container access - for** choice names a workspace, and each root then says whether that - workspace's container can read it, needs a grant, needs an - administrator to grant, or could not have its access-control list read; - the grant names and skips a folder in either of the last two states. - Changing the choice generates a list on screen - again, keeping the selection. A line says when the workspace lacks the - active read-write grant on its own folder. **Add selected profiles…** sends - the revision and the digests of 1 to 8 selected proposals; Rust discovers - again, refuses a list that no longer matches as `discovery_changed`, shows - one native confirmation that lists everything, and records each profile. - **Grant folders for selected…** (Windows) sends the list's workspace and - the digests; Rust checks every folder with core's grant rules before the - dialog, grants only the folders this account can change, after one native - confirmation that names the workspace and every folder, and names the - folders it skips: those that need an administrator and those whose - access-control list could not be read. A declined confirmation or a - refusal keeps the list and the selection. + left out when a bound was reached. An **Assign to workspace** choice + names a workspace on every platform (ADR-0107). On Windows each root then + says whether that workspace's container can read it, needs a grant, needs + an administrator to grant, or could not have its access-control list + read; the add names and skips a folder in either of the last two states. + Changing the choice generates a list on screen again, keeping the + selection. A line says when the workspace lacks the active read-write + grant on its own folder, and another that the profiles added are also + assigned to it. **Add selected profiles…** sends the revision, the list's + workspace or none, and the digests of 1 to 8 selected proposals; Rust + discovers again, refuses a list that no longer matches as + `discovery_changed`, checks every folder to grant with core's grant rules, + shows one native confirmation that lists everything and, with a + workspace, the folders it grants, records each profile, and then grants + those folders and assigns the profiles to the workspace. Only folders this + account can change are granted. The separate grant button of 0.68.0 is + gone. A declined confirmation or a refusal keeps the list and the + selection. **Package-network profiles** list each profile's origins and how many credentials are bound, and a **Remove** button. A line says a profile is @@ -1441,7 +1473,9 @@ waits. The window shows: folder, workspace, access, and state (`pending`, `active`, `revoking`) with a **Revoke** button. The group's help says that each workspace's commands run in its own AppContainer, a Windows sandbox with no access to the operator's - files until a grant adds it, and that registering a folder gives none. + files until a grant adds it, that registering a folder grants it read and + write there, and that turning a profile on for a workspace grants its + folders (ADR-0107). **Grant a folder** has a **Workspace whose commands get access** select, an access select (**Read and execute a folder you choose**, or **Read and write the workspace's own folder**), and a hint that follows the access. Both @@ -2231,7 +2265,7 @@ What it does not do: | Item | Value | | --- | --- | -| Commands | 66 | +| Commands | 67 | | Git status changed paths | 1,000, and a 10-second deadline | | Sessions per listing | 5,000 | | Search terms and length | 16 terms, 256 characters | @@ -2334,12 +2368,14 @@ ACLs the private store refuses, see the notes in key, and that a late detail answer is dropped; `ui/tests/settings_sections.test.ts` the sections, the workspace field, the workspace scope (one workspace, no sidebar, **All settings**, a focus read), - permission rows, and the Advanced groups; `ui/tests/settings_skills.test.ts` + permission rows, the Advanced groups, and the workspace page's toolchain + profile switches (ADR-0107); `ui/tests/settings_skills.test.ts` the Skills controls and the mock skill commands (ADR-0082); `ui/tests/settings_execution.test.ts` the profile and grant controls and - their mock commands (ADR-0088); `ui/tests/settings_discovery.test.ts` the - generated proposals, selection, add and grant requests, and their mock - commands (ADR-0103); and + their mock commands, including assignment (ADR-0088, ADR-0107); + `ui/tests/settings_discovery.test.ts` the generated proposals, selection, + add requests with and without a workspace, and their mock commands + (ADR-0103, ADR-0107); and `ui/tests/main_redesign.test.ts` the View menu, the status-bar approvals segment, the composer menus and counter, and the compact transcript rows. Since ADR-0071: `ui/tests/model_picker.test.ts` covers the model @@ -2466,9 +2502,10 @@ ACLs the private store refuses, see the notes in nothing ran on Linux. - ADR-0088: the profile and grant commands were checked by service tests with a scripted prompt (`crates/omgcode-app/tests/desktop_settings_execution.rs`), - by unit, layer, and bundle tests, and against the mock backend. No test - applies a container grant, because that changes a folder's access-control - list and creates an AppContainer profile on the host; the confirmation text + by unit, layer, and bundle tests, and against the mock backend. Until + ADR-0107 no test applied a container grant, because that changes a + folder's access-control list and creates an AppContainer profile on the + host; the confirmation text and the paths before the change are tested instead, and the platform refusal is tested only for non-Windows builds, which did not run here. A package profile with a bound credential was not exercised. The native dialogs and @@ -2479,12 +2516,27 @@ ACLs the private store refuses, see the notes in (`crates/omgcode-app/tests/desktop_settings_discovery.rs`), by layer and bundle tests, and by Vitest against a fake transport and the mock backend. On Windows the root checks read real access-control lists of fixture - folders; no test applies a grant. The Linux-only core tests (a linked root + folders; until ADR-0107 no test applied a grant. The Linux-only core tests (a linked root and a FIFO at an installer's path) and the service tests ran in WSL Ubuntu 24.04 and in CI. Discovery ran against real toolchains only through an ignored test run by hand on one Windows computer, the native dialogs and the real shell's settings window were not driven by automation, and the desktop shell never ran on Linux. +- ADR-0107: assignment was checked by core tests (recording, replay, + refusals, removal, plans, a changed plan, the grants a removal releases, + and the workspaces a revocation names), by run and turn tests, by CLI + tests, and by service tests with a scripted prompt + (`crates/omgcode-app/tests/desktop_settings_execution.rs`, + `desktop_settings_changes.rs`, and `desktop_settings_discovery.rs`). On + Windows the CLI and service tests that register, assign, add with a + workspace, unassign, remove, or unregister apply and revoke real grants on + temporary folders, and each test revokes every grant it recorded before it + ends; service tests that are not about registration record workspaces + without granting. Layer and bundle tests check the command lists, and + Vitest checks the switches and the discovery panel against a fake + transport and the mock backend. The core, CLI, and app suites also ran in + WSL Ubuntu 24.04. The native dialogs and the real shell's settings window + were not driven by automation. - Phase S2 (0.41.0): the change commands were checked by service tests with a scripted prompt, by unit, layer, and bundle tests, and in the Vite development server against the mock backend. The native dialogs and the diff --git a/docs/execution.md b/docs/execution.md index f87aaf41..8b483b1b 100644 --- a/docs/execution.md +++ b/docs/execution.md @@ -373,6 +373,12 @@ registry can log it; use `https`. The runner's environment is not touched. A grant gives one workspace's container access to one directory and everything beneath it. Grants are lasting ACL entries, recorded in the control journal. +Since 0.70.0 ([ADR-0107](adr/0107-assign-toolchain-profiles-to-workspaces-and-grant-on-assignment.md)) the operator changes that need a grant +make it through the same calls: `workspace register` grants the workspace +folder read-write, `workspace profile-assign` grants read-execute on the +profile's folders the container cannot read yet, and `profile-unassign`, +`profile-remove`, and `unregister` revoke the grants no longer needed. See +[assignments](#assignments). The commands below remain for any other folder. | Command | Effect | | --- | --- | @@ -423,6 +429,13 @@ Rules: - A run refused for a missing read-write grant says the workspace's sandbox has no read-write grant on the workspace folder, and names the `settings` window's **Container grants** group and `workspace container-grant`. +- Registering a workspace on Windows grants its container read-write on its + folder when no grant of the workspace is recorded on that folder and this + account can change the folder's access-control list. Registering a folder + that is registered already grants it if that grant is missing, which is how + a workspace registered before 0.70.0 gets it. A failed grant leaves the + workspace registered and is reported; `register` prints `grant_id` when it + granted. ## Trusted runs @@ -472,7 +485,9 @@ While holding the control journal lock, `run` checks: 3. The profile exists and was declared on this platform. Each root and `PATH` entry is still the recorded directory, and no root now overlaps the development root or application storage. Otherwise the profile is stale: - remove it and add it again. + remove it and add it again. Since 0.70.0 the profile must also be assigned + to the workspace; otherwise the run is refused with text that names no + path and says to assign it ([ADR-0107](adr/0107-assign-toolchain-profiles-to-workspaces-and-grant-on-assignment.md)). 4. The working directory is a relative path that stays inside the workspace. The default is the workspace itself. 5. The program resolves: @@ -504,7 +519,8 @@ the event count under the control lock when it starts. The checks are: - `execute`, `read`, and `write` are still enabled, `host_services` for a run that selected host services, and `task_network` for a run that selected network access; -- the run's profile still exists with the same identity; +- the run's profile still exists with the same identity and, since 0.70.0, + is still assigned to the workspace; - for a model run authorized by a standing `allow` (since 0.43.0, ADR-0063), the model command state is still `allow`. A change to `prompt` stops it, although `prompt` still permits an approved run; @@ -532,7 +548,11 @@ the watchers still stop the runs; the command waits for what it can find and then fails with code `run`. `container-revoke` also waits for every pending run of the grant's workspace that started before the revocation; it lists them while it holds the control -lock, under which every run starts. If the run journal cannot be read, for +lock, under which every run starts. `profile-unassign` records its change +first too. `profile-unassign`, `profile-remove`, and `unregister` list every +pending run under the lock before the change, and also wait for those of each +workspace whose grant they tried to revoke, because any revocation withdraws +the workspace's runs (ADR-0107). If the run journal cannot be read, for example after an interrupted append, it still revokes the grant, then fails with code `run` and says that the grant was revoked. @@ -750,6 +770,7 @@ runtime advertises it only when the session workspace's live `model_tools`, `execute`, `read`, and `write` preferences are enabled and, since 0.65.0, at least one toolchain profile is recorded for the running platform ([ADR-0100](adr/0100-list-the-recorded-toolchain-profiles-in-the-command-tool.md)). +Since 0.70.0 that profile must be assigned to the workspace ([ADR-0107](adr/0107-assign-toolchain-profiles-to-workspaces-and-grant-on-assignment.md)). Each call rechecks them, and the trusted run checks them again. Since 0.43.0 (ADR-0063) its effective state is the most restrictive of the three. At `prompt` each call @@ -777,11 +798,14 @@ disk growth. It selects no network or host services. Since 0.65.0 (tool schema 0.9.0) the `profile` parameter lists, as an `enum`, the names of the profiles recorded for the running platform, in the order they were added; the list is read from the same settings snapshot that -selects the tools. A name grants nothing. A call that names a profile not -recorded for this platform, compared case-insensitively under the lock that -admits the call, is answered with `profile_not_recorded` and the recorded -names. With no profile recorded for this platform, the result says that no -command can run instead of asking for a listed name. Nothing runs, no approval is requested or consumed, the model action +selects the tools. Since 0.70.0 (tool schema 0.10.0) it lists only the +profiles of this platform assigned to the workspace, in profile order. A name +grants nothing. A call that names a profile not assigned to the workspace for +this platform, compared case-insensitively under the lock that admits the +call, is answered with `profile_not_recorded` and the assigned names; the +code is unchanged and the text says "assigned to this workspace". With no +profile assigned, the result says that no command can run instead of asking +for a listed name. Nothing runs, no approval is requested or consumed, the model action journal records the call as refused (`invalid_request`), and the turn continues. The runner still looks the profile up under its own lock, so a profile removed after that check still refuses the run. @@ -876,16 +900,19 @@ desktop `settings` window can propose profiles from the installed toolchains, and the operator selects and confirms each one (see [generated profiles](#generated-profiles)). Every run names one, whether the trusted CLI or the model command tool starts it, and there is no fallback to -an unconfined run. The model command tool is offered only while at least one -profile is recorded for the running platform, and it lists their names -(ADR-0100). +an unconfined run. Since 0.70.0 a workspace runs only the profiles assigned +to it, and the model command tool is offered only while at least one profile +of the running platform is assigned to the workspace; it lists their names +(ADR-0100, [ADR-0107](adr/0107-assign-toolchain-profiles-to-workspaces-and-grant-on-assignment.md)). | Command | Effect | | --- | --- | | `omgcode workspace profile-add --root ... [--path ]... [--env NAME=VALUE]... --revision ` | Record a profile. Needs the expected revision and increments it. | | `omgcode workspace profile-show ` | Show one profile. | -| `omgcode workspace profile-remove --revision ` | Remove it. Needs the expected revision and increments it. | -| `omgcode workspace status` | Lists profiles under `profiles` with the revision that added each. | +| `omgcode workspace profile-remove --revision ` | Remove it, end its assignments, and revoke the grants they alone needed. Needs the expected revision and increments it. | +| `omgcode workspace profile-assign --revision ` | Let the workspace run the profile; on Windows, first grant the folders its container needs. | +| `omgcode workspace profile-unassign --revision ` | End the assignment and revoke the grants no other assigned profile needs. | +| `omgcode workspace status` | Lists profiles under `profiles` with the revision that added each, and each workspace's `assigned_profiles`. | Rules: @@ -913,6 +940,58 @@ Rules: confirmation that lists them and the variable names, and applies the change with the confirmed revision ([ADR-0088](adr/0088-change-execution-settings-in-the-settings-window.md)). +#### Assignments + +Since 0.70.0 ([ADR-0107](adr/0107-assign-toolchain-profiles-to-workspaces-and-grant-on-assignment.md)) a profile is recorded once and assigned to +each workspace that may run it. Assigning to a workspace is the operator's +consent to give that workspace's sandbox the profile's folders. + +- **Events:** `profile_assigned` and `profile_unassigned` name a workspace and + a profile, and each needs the expected revision and increments it. Replay + refuses an unknown workspace or profile, an assignment that exists already, + and an unassignment of one that does not. Assigning also refuses a profile + declared on another platform. Removing a profile ends every assignment of + it, and unregistering a workspace drops its assignments. An older build + refuses the new events. +- **Planning, on Windows:** core lists each live root of the profile that the + workspace's container cannot read yet, each folder once, skipping a folder + that already has a recorded grant of the workspace. Folders that only an + administrator can grant, and folders whose access-control list could not be + read, are listed apart and not granted. A root that is no longer the + recorded directory is listed as unknown. Off Windows the plan is empty. +- **Assigning:** under the store's lock core plans again and refuses the + assignment when the folders to grant differ from the plan the operator + confirmed. It then applies `check_container_grants` to the batch, grants + each folder read-execute through `grant_container_access`, and records the + assignment last. A failed grant leaves the profile unassigned; grants + applied before it stay recorded, and one whose access-control change failed + stays `pending` until it is revoked. `profile-assign` is itself the consent, + so it plans and assigns in one call, and prints `assigned_profile_id`, + `granted` (each `grant_id` with its folder), and `not_granted` with the + reason. +- **Unassigning and removing:** the change is recorded first. Then core + revokes the workspace's read-execute grants whose folder is one of the + profile's roots, is not a root of a profile still assigned to the + workspace, and is not the workspace's package cache root. The workspace + folder's read-write grant is never revoked here. `profile-unassign` and + `profile-remove` print what they revoked under `revoked`; a failed + revocation leaves the change recorded, is reported, and + `container-revoke` retries it. +- **Unregistering:** `workspace unregister` revokes every grant of the + workspace first and unregisters it only when every revocation was + confirmed; otherwise the workspace stays registered with the grants not yet + revoked. See [workspace settings](workspace-permissions.md#unregistering-a-workspace). +- **Runs:** each revocation withdraws every run of its workspace, as + `container-revoke` does, so these commands stop and wait for those runs. +- **Upgrading:** existing profiles start assigned to no workspace. Assign each + workspace's profiles once. A profile whose folders are already granted + grants nothing new. + +The `settings` window shows one switch per profile of this platform on each +workspace's page. Turning one on or off runs the same core calls after a +native confirmation that names the workspace, the profile, and each folder it +grants or each grant it revokes; see the [desktop interface](desktop-interface.md). + A profile lists what a toolchain needs, not just its executable. Tools that read configuration outside their installation need that directory as a root. For example, a distribution Node reads `/etc/ssl`. @@ -923,7 +1002,8 @@ Version 0.68.0 adds **Generate toolchain profiles from local packages** to the **Toolchain profiles** group of the `settings` window ([ADR-0103](adr/0103-generate-toolchain-profiles-from-installed-toolchains.md)). Core's trusted discovery service proposes profiles; it records and grants -nothing. +nothing. Adding proposals with a workspace chosen also assigns them to it +(ADR-0107). - **Families:** Rust (rustup toolchains), C and C++ (MSVC with the Windows SDK, Clang, and MinGW GCC on Windows; GCC and Clang on Linux), Java, Python, @@ -959,19 +1039,23 @@ nothing. longer matches (`discovery_changed`), shows one native confirmation that lists every root, `PATH` entry, and variable with its value, and records each profile with `add_profile` from the confirmed revision. -- **Windows grants:** with a workspace selected, each root says whether its - container can read it, needs a read-execute grant, needs an +- **Assigning to a workspace:** on every platform the operator can choose a + workspace, and adding then also assigns the added profiles to it in the + same confirmation (ADR-0107). On Windows each root says whether that + workspace's container can read it, needs a read-execute grant, needs an administrator, or could not have its access-control list read. The - access-control lists are read while the settings store is closed. **Grant folders for selected…** grants only the folders this - account can change, after one native confirmation, through - `grant_container_access`. Before the dialog, core's + access-control lists are read while the settings store is closed. The one + confirmation also names the folders the assignment grants, which are only + those this account can change. Before the dialog, core's `check_container_grants` applies every grant rule to the whole batch (the development-root scope, application storage, an existing grant, and the - 32-per-workspace and 256 limits), and a refusal names the folder. - Administrator-only folders, and folders whose access-control list could - not be read, are named and skipped. A recorded grant whose access list - then cannot be changed stays `pending` and is reported as - `container_access_failed`; revoke it. + 32-per-workspace and 256 limits), and a refusal names the folder. After it, + each profile is recorded with `add_profile`, then the grants are applied and + the profiles assigned as `profile-assign` does. Administrator-only folders, + and folders whose access-control list could not be read, are named and + skipped. A recorded grant whose access list then cannot be changed stays + `pending` and is reported as `container_access_failed`; revoke it. The + separate grant command of 0.68.0 is removed. - **Notes:** a proposal says when its family has not passed the confined acceptance runs (only Rust, MSVC, Linux GCC, Python, Go, and Node.js have), when it is a runtime without a compiler, and that offline runs cannot diff --git a/docs/testing-standards.md b/docs/testing-standards.md index e33819ac..e568bc8f 100644 --- a/docs/testing-standards.md +++ b/docs/testing-standards.md @@ -34,7 +34,14 @@ granted directory, run it in a fresh AppContainer, and record each probe as `ok`, `denied`, or the OS error. The same probes run unconfined as a positive control. Grant tests change real ACLs on temporary NTFS or ReFS directories, and each test container deletes its profile when dropped, so runs leave no per-user -AppContainer profiles. These tests ran on Windows 11 build 26300. +AppContainer profiles. These tests ran on Windows 11 build 26300. Since +0.70.0 (ADR-0107) registering a workspace on Windows grants its folder, and +assigning a profile grants its roots, so the CLI and desktop service tests that +register, assign, or add with a workspace also change real ACLs on temporary +folders; each test revokes every grant it recorded before it ends, which also +deletes the workspace's AppContainer profile. Tests that are not about these +changes record workspaces and assignments through the core primitives, which +grant nothing. The 0.16.0 `run_workflow` tests drive `omgcode run` through the real CLI with system tools. Since 0.17.0, on Linux they start the CLI through @@ -226,7 +233,7 @@ As the relevant components are implemented, include: | Windows confinement | Granted read-only and read-write paths, denied host files, directories, named pipe, and loopback TCP, a writable container temporary directory, inheritance by descendants, the same probes unconfined, missing, weaker, and foreign grants, a missing profile, `LOCALAPPDATA`, or container name, refused `HostServices`, an ungranted program, the refused entry, path, and levels reported without the path in the error text, and, through the CLI, an ungranted profile root and package cache root named by role with the path only in `refused_path` (ADR-0106) | | Container grants | SID derivation, propagation to existing and new children, exact read-back, protection state kept, junctions not followed, hard-link reach, refused replaced/junction/file/relative paths, profile creation and deletion, journal intent and outcome order, replay validation, revision rules, scope refusals, pending and revoking recovery, the revocation reserve, CLI grant/list/revoke, refusal off Windows | | Model tool chat | Preference off by default and rechecked per call, settings compatibility, confinement against parent, absolute, rooted, UNC, link, junction, and hard-link paths, strict provider tool-call parsing, token removal before journal and model, refusal of token-bearing calls, withheld replay after revocation, finish reason, one call per turn in escape cases | -| Model command tool | Strict profile/program/argument/cwd parsing, tool advertised only with live model-tools/execute/read/write and a profile recorded for the platform, the recorded profiles listed in order, an unrecorded profile refused with `profile_not_recorded` before any approval and recorded as refused, a profile declared on the other platform neither offered nor accepted, and a refusal with no recorded profile not asking for a name (ADR-0100), first call records a pending approval and starts nothing, denial, approval consumption, exact digest and binding, settings-revision invalidation, run hand-off failure, output bounds, no replay, and a durable `model_tools` revocation count that stops a model-origin run even after re-enable. An end-to-end CLI case drives the real chat process, a mock provider, an operator approval, and the trusted runner to a successful confined command on both hosts | +| Model command tool | Strict profile/program/argument/cwd parsing, tool advertised only with live model-tools/execute/read/write and a profile of the platform assigned to the workspace, the assigned profiles listed in order, a profile that is not assigned refused with `profile_not_recorded` before any approval and recorded as refused, a profile declared on the other platform neither offered nor accepted, and a refusal with no assigned profile not asking for a name (ADR-0100, ADR-0107), first call records a pending approval and starts nothing, denial, approval consumption, exact digest and binding, settings-revision invalidation, run hand-off failure, output bounds, no replay, and a durable `model_tools` revocation count that stops a model-origin run even after re-enable. An end-to-end CLI case drives the real chat process, a mock provider, an operator approval, and the trusted runner to a successful confined command on both hosts | | Model edit tool | Strict path/`old_text`/`new_text` parsing with unknown-field, empty-`old_text`, duplicate-key, absolute, and parent-path refusal; the tool advertised and dispatched only with live model-tools/read/write and denied before any file access otherwise; first call records a pending `file_write` approval and writes nothing; a summary with sizes and short digests but no file text or control characters; denial; approval consumption and one checkpointed apply; a further identical call after success needing a new approval; a same-size changed file and a same-size different replacement each needing a new approval; recoverable no-match, ambiguous (including overlaps), unchanged, non-UTF-8, oversized, too-large, and pending-checkpoint results; `session inspect` listing the exact request; schema-0.2.0 replay. A CLI case drives the real chat process, a mock provider, and operator approval to an applied edit and a recorded checkpoint ([ADR-0043](adr/0043-gate-the-model-file-edit-tool-with-approvals-and-checkpointed-apply.md)) | | Model multi-edit and create tools | Strict parsing of `edits` (zero and 17 entries, empty `old_text`, unknown or duplicate keys at both levels, wrong types) and of `content`; both tools advertised and dispatched only with live model-tools/read/write, in the documented order, and denied before any file access otherwise; first call records a pending `file_write` approval and writes nothing; summaries with sizes and short digests but no text; denial; approval consumption and one checkpointed apply for a multi-edit (edits listed out of offset order, touching matches) and one exclusive create with no checkpoint; a changed file or different request needing a new approval; an `workspace_edit_file` approval never consumed by an equivalent multi-edit and the reverse, and a create approval never authorizing an edit; recoverable no-match and ambiguous (naming the edit index), overlap, unchanged, non-UTF-8, too-large, `file_exists`, and missing-parent results that record no approval; an output-too-large refusal that keeps the approval; schema-0.2.0 and 0.3.0 replay; desktop review fields, the shared eight-candidate bound across the three tools, stale review after a change or once a created path exists, and hostile text escaped. CLI cases drive the real chat process, a mock provider, and operator approval for each tool ([ADR-0054](adr/0054-add-multi-edit-and-create-model-file-tools.md)) | | Model rename and delete tools | Strict parsing of `from`/`to` and `path` (missing, extra, wrong-type, absolute, parent, and empty values); both tools advertised and dispatched only with live model-tools/read/write, in the documented order within the tool-definition cap (ten since ADR-0098), and denied before any file access otherwise; first call records a pending `file_write` approval and writes nothing; summaries with sizes and short digests but no text; denial; approval consumption and one no-replace rename with no checkpoint or one checkpointed removal; a changed source, a different destination, or another tool's approval needing a new approval; recoverable `not_found`, `file_exists`, missing-parent, `edit_too_large`, and same-name results that record no approval; non-UTF-8 files accepted; an output-too-large refusal that keeps the approval; schema-0.4.0 replay. Platform cases refuse existing destinations, directories, links and junctions, and hard links, refuse a swapped or changed source, delete only the verified file, report a swapped name as uncertain on Linux, and inject faults before and after each native call. Ledger cases cover the `remove` kind: replay, every refusal (proposed bytes, a stage record, a carried stage identity), inventory without a stage, compaction, deletion of the entry, restore of the exact bytes including non-UTF-8, and refusal of an existing target. Review cases cover exact fields, stale destination or source, and hostile path text. CLI cases drive the real chat process, a mock provider, operator approval, and `file restore --removed` ([ADR-0055](adr/0055-add-checkpointed-delete-and-no-replace-rename-model-tools.md)) | diff --git a/docs/workspace-permissions.md b/docs/workspace-permissions.md index 393bd8de..1299eecc 100644 --- a/docs/workspace-permissions.md +++ b/docs/workspace-permissions.md @@ -126,7 +126,7 @@ zero-based sequence, UTC timestamp, global revision, and tagged `action`: | `created` | Initial store identity, sequence and revision zero | | `root_set` | Selected directory identity; increment revision | | `workspace_registered` | New ID, directory identity, default preferences; increment revision | -| `workspace_unregistered` | Remove one registration and the settings that name it; nothing on disk changes (ADR-0081); increment revision | +| `workspace_unregistered` | Remove one registration and the settings that name it, including its profile assignments; nothing on disk changes (ADR-0081); increment revision | | `permissions_changed` | Existing ID and complete preference set; increment revision | | `web_fetch_host_added` | Add one host pattern to a workspace's `web_fetch` allowlist (ADR-0098); increment revision | | `web_fetch_host_removed` | Remove one host pattern from that allowlist; increment revision | @@ -136,7 +136,9 @@ zero-based sequence, UTC timestamp, global revision, and tagged `action`: | `container_revoke_requested` | Revocation intent for a grant; preserve revision | | `container_grant_revoked` | Grant removed from the access list; preserve revision | | `profile_added` | New toolchain profile; increment revision | -| `profile_removed` | Remove a toolchain profile; increment revision | +| `profile_removed` | Remove a toolchain profile and every assignment of it; increment revision | +| `profile_assigned` | Assign a recorded toolchain profile to one workspace (ADR-0107); increment revision | +| `profile_unassigned` | End that assignment; increment revision | | `package_profile_added` | New package-network profile; increment revision | | `package_profile_removed` | Remove a package-network profile and any credential bindings it ends; increment revision | | `package_credential_bound` | Bind a stored credential to a package-network profile; increment revision | @@ -204,7 +206,13 @@ core calls, with native dialogs and confirmations; on other platforms it returns `unsupported_platform`. It adds no new event. Since [ADR-0104](adr/0104-grant-the-workspace-folder-read-write-without-a-folder-dialog.md) a read-write grant there opens no folder dialog and uses the workspace's -recorded directory. +recorded directory. Since +[ADR-0107](adr/0107-assign-toolchain-profiles-to-workspaces-and-grant-on-assignment.md) +the operator changes that need a grant make it: registering a workspace grants +its container read-write on its folder, and assigning a toolchain profile grants +read-execute on each of the profile's folders the container cannot read yet. +Unassigning or removing an assigned profile, and unregistering a workspace, +revoke the grants no longer needed. They use the same events. ## Unregistering a workspace @@ -220,10 +228,15 @@ records, and policy-audit records stay as history. The revision change makes every outstanding approval unusable, and a started run of the workspace is withdrawn like any run whose workspace is no longer registered. -The command is refused while any container grant, in any state, names the -workspace (`grant refused`): revoke it with `workspace container-revoke` -first. An unknown workspace and a stale revision are refused as for any other -settings change. Registering the same folder afterwards assigns a new +Since ADR-0107 the command first revokes every container grant of the +workspace, in any state, and lists them under `revoked`. It records +`workspace_unregistered` only when every revocation was confirmed. A failed +revocation leaves the workspace registered with the grants not yet revoked; +the command says so, and `workspace container-revoke` retries the grant before +the operator unregisters again. The event itself is still refused while any +grant names the workspace (`grant refused`), so replay keeps ADR-0081's rule. +An unknown workspace and a stale revision are refused as for any other +settings change, before anything is revoked. Registering the same folder afterwards assigns a new identifier and the default preferences; the old identifier is never reused. The desktop `settings` window removes the workspace's saved custom @@ -253,6 +266,24 @@ The desktop `settings` window adds and removes profiles through the same core calls, with a native folder dialog for each root and `PATH` entry and a native confirmation (ADR-0088); it records the same events and offers no edit. +A workspace runs only the profiles assigned to it +([ADR-0107](adr/0107-assign-toolchain-profiles-to-workspaces-and-grant-on-assignment.md)). +`workspace profile-assign --revision ` and +`profile-unassign` record `profile_assigned` and `profile_unassigned`, each +of which increments the revision. Replay refuses an unknown workspace or +profile, an assignment that exists already, and an unassignment of one that +does not; assigning also refuses a profile declared on another platform. +`workspace status` lists each workspace's assigned profile identifiers under +`assigned_profiles`, in assignment order, and omits the field when there are +none. Removing a profile ends every assignment of it, and so does +unregistering the workspace. On Windows assigning grants the folders the +workspace's container needs, and unassigning revokes those no other assigned +profile lists; the [execution guide](execution.md#toolchain-profiles) owns +those rules. The `settings` window assigns and unassigns with a switch per +profile on the workspace's page, after a native confirmation. Existing +profiles start assigned to no workspace. Version 0.69.0 refuses a settings +log that records an assignment. + ## Package-network profiles `workspace package-profile-add`, `package-profile-show`, and @@ -622,19 +653,21 @@ profile exposes a program that does. See [ADR-0079](adr/0079-add-a-model-tool-that-creates-one-directory.md). When `model_tools`, `execute`, `read`, and `write` are all enabled and at -least one toolchain profile is recorded for the running platform, the runtime -also offers `workspace_run_command`. Its `profile` parameter lists those -profiles, and a call that names another one is answered with -`profile_not_recorded` before any approval is requested -([ADR-0100](adr/0100-list-the-recorded-toolchain-profiles-in-the-command-tool.md)). +least one toolchain profile of the running platform is assigned to the +workspace, the runtime also offers `workspace_run_command`. Its `profile` +parameter lists those profiles, and a call that names another one is answered +with `profile_not_recorded` before any approval is requested +([ADR-0100](adr/0100-list-the-recorded-toolchain-profiles-in-the-command-tool.md), +[ADR-0107](adr/0107-assign-toolchain-profiles-to-workspaces-and-grant-on-assignment.md)). Its first call records a pending approval and does not run; after `approvals approve `, a second identical call consumes the approval and starts the trusted run. The model cannot approve. The tool uses fixed limits and no network or host services. See [model command tool](execution.md#model-command-tool) and [ADR-0040](adr/0040-gate-the-model-command-tool-with-approvals-and-the-trusted-runner.md). -The tool schema version is 0.9.0, which lists the recorded toolchain profiles -in `workspace_run_command` (ADR-0100); 0.8.0 added `web_fetch` (ADR-0098); +The tool schema version is 0.10.0, which lists only the toolchain profiles +assigned to the workspace in `workspace_run_command` (ADR-0107); 0.9.0 listed +the recorded profiles (ADR-0100); 0.8.0 added `web_fetch` (ADR-0098); 0.7.0 added the 32 KiB argument limit to the create, edit, and multi-edit descriptions (ADR-0099); 0.6.0 added `workspace_create_directory`; 0.5.0 added `workspace_rename_file` and `workspace_delete_file`; 0.4.0 added From a4d8f010168a19e010866158efa4a70e7693165f Mon Sep 17 00:00:00 2001 From: James Chapman Date: Fri, 27 Nov 2026 01:32:08 +0000 Subject: [PATCH 3/5] fix: address review findings on assignment grants and revocations Core (ADR-0107): - Refuse a profile or folder plan while a grant of the workspace is pending or being revoked, because its runs are refused until it settles. - Grant only a folder that is still the directory the operator confirmed. - When a grant fails, or the assignment cannot be recorded, revoke the grants that call made that no assigned profile needs. - Keep a grant on a folder that holds a still-assigned profile's root that no other grant reaches, since that root got no grant of its own. - Attempt every revocation and return each failure. - Return an unregistration's revocations and removal error together, so callers still wait for the withdrawn runs when the removal fails. CLI and desktop: - Name every grant not revoked, report a grant whose AppContainer profile could not be deleted apart, and say how to recover a pending registration grant. - Say how many discovered profiles were assigned before a failure. Tests: - App and CLI tests check that their grants are revoked, through non-panicking helpers; the CLI file workflow registers through core. - New core tests for the plan refusal, the changed folder, the nested root, the unrecorded unregistration, and (Windows) the unrecorded assignment. - The mock backend grants a registered folder and never reuses a grant id. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 19 +- .../src/desktop/settings_changes.rs | 136 ++++++--- .../src/desktop/settings_discovery.rs | 36 ++- crates/omgcode-app/tests/common/mod.rs | 48 +++- .../tests/desktop_settings_changes.rs | 17 +- .../tests/desktop_settings_discovery.rs | 12 + .../tests/desktop_settings_execution.rs | 36 ++- crates/omgcode-cli/src/control_cli.rs | 112 ++++++-- crates/omgcode-cli/tests/control_workflow.rs | 30 +- crates/omgcode-cli/tests/file_workflow.rs | 24 +- crates/omgcode-cli/tests/run_workflow.rs | 6 +- crates/omgcode-cli/tests/support/mod.rs | 120 +++++++- crates/omgcode-cli/tests/support/run_scene.rs | 18 +- crates/omgcode-core/src/control.rs | 1 + crates/omgcode-core/src/control/assignment.rs | 258 ++++++++++++++---- .../src/control/assignment/tests.rs | 252 ++++++++++++++++- crates/omgcode-core/src/control/container.rs | 44 ++- crates/omgcode-desktop/ui/src/mock/backend.ts | 20 +- .../ui/tests/settings_execution.test.ts | 48 ++++ ...s-to-workspaces-and-grant-on-assignment.md | 33 ++- docs/desktop-interface.md | 8 +- docs/execution.md | 38 ++- docs/workspace-permissions.md | 11 +- 23 files changed, 1066 insertions(+), 261 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2ba82485..09bcb500 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -612,15 +612,22 @@ Changes are recorded here before a release version is assigned. read-execute grants for the profile's roots that the workspace's AppContainer cannot read yet, the operator confirms the plan, and core refuses the assignment if the plan changed, then applies the grants and - records the assignment last. Folders that need an administrator, or whose - access could not be read, are listed and not granted. Registering a + records the assignment last, granting only a folder that is still the + confirmed directory. An assignment whose grant fails, or that cannot be + recorded, revokes the grants it made that no assigned profile needs, and a + workspace with a pending or revoking grant is refused a plan. Folders that + need an administrator, or whose access could not be read, are listed and + not granted. Registering a workspace grants its container read-write on its folder, and registering an existing folder again grants it if that grant is missing. Unassigning or removing a profile revokes the workspace's read-execute grants on its roots - that no other assigned profile lists, never the workspace folder's grant or - the package cache root's. Unregistering revokes every grant of the - workspace first and leaves it registered if a revocation fails. Each caller - waits only for the runs of the workspaces whose grants it revoked. The + that no other assigned profile needs, never the workspace folder's grant or + the package cache root's; a grant on a folder that holds a still-assigned + profile's root, which got no grant of its own, is kept. Every grant is + attempted, and each one not revoked is named. Unregistering revokes every + grant of the workspace first and leaves it registered if a revocation + fails or its removal cannot be recorded. Each caller waits only for the + runs of the workspaces whose grants it revoked. The trusted CLI adds `workspace profile-assign` and `workspace profile-unassign`, and `register`, `unregister`, and `profile-remove` report what they granted or revoked. The desktop `settings` window shows one diff --git a/crates/omgcode-app/src/desktop/settings_changes.rs b/crates/omgcode-app/src/desktop/settings_changes.rs index e51ed180..6c5b882f 100644 --- a/crates/omgcode-app/src/desktop/settings_changes.rs +++ b/crates/omgcode-app/src/desktop/settings_changes.rs @@ -815,7 +815,7 @@ impl DesktopService { // The preferences lock comes first, as in every other save that also // reads settings, so the removal of the instructions file never // overlaps a save or a turn's read of it. - let (listed, before, revocations, removed) = { + let (listed, before, unregistration, removed) = { let _lock = self .inner .preferences @@ -826,24 +826,33 @@ impl DesktopService { // settings no longer show once it is unregistered, so its runs // are listed before the change. let before = run::pending_runs(&store); - let revocations = store + let unregistration = store .unregister_workspace_with_access(workspace_id, request.revision) .map_err(|error| DesktopError::from_control(&error))?; // The change is recorded, so the runs it withdraws are listed // before anything else can fail, and are stopped and waited for // even when the file below cannot be deleted. let listed = run::withdrawn_runs(&store); - let removed = revocations - .failure - .is_none() + let removed = unregistration + .unregistered() .then(|| instructions::remove(&self.inner.data_root, *workspace_id.as_uuid())); - (listed, before, revocations, removed) + (listed, before, unregistration, removed) }; - // A grant that was not revoked, then a run that was not stopped, is - // reported first; a remaining instructions file is never sent, - // because the workspace is no longer registered. - let (also, deferred) = - revocation_outcome(before, &revocations, RevokingChange::Unregistration); + // A grant that was not revoked, or a removal that was not recorded, + // then a run that was not stopped, is reported first; a remaining + // instructions file is never sent, because the workspace is no longer + // registered. + let (also, deferred) = revocation_outcome( + before, + &unregistration.revocations, + RevokingChange::Unregistration, + ); + let deferred = deferred.or_else(|| { + unregistration + .removal + .as_ref() + .map(DesktopError::removal_not_recorded) + }); let overview = self.finish_reporting(listed, also, deferred)?; if let Some(Err(_)) = removed { return Err(DesktopError::removed_instructions_orphaned()); @@ -1520,10 +1529,8 @@ pub(super) fn revocation_outcome( unchecked: true, }, }; - let deferred = revocations - .failure - .as_ref() - .map(|(_, error)| DesktopError::revocation_incomplete(error, change)); + let deferred = (!revocations.failures.is_empty()) + .then(|| DesktopError::revocation_incomplete(&revocations.failures, change)); (also, deferred) } @@ -1584,35 +1591,80 @@ impl DesktopError { ) } - /// A grant the change should have revoked was not. After a recorded - /// change the change stands; after an unregistration the workspace stays - /// registered. The operating system's own text is never shown. - pub(super) fn revocation_incomplete(error: &ControlError, change: RevokingChange) -> Self { - let (outcome, then) = match change { - RevokingChange::Recorded => ( - "The change was recorded, but a container grant it releases", - "", - ), - RevokingChange::Unregistration => ( - "The workspace stays registered, because one of its container grants", - " Then remove the workspace again.", - ), + /// Revocations the change made did not all complete; every grant was + /// attempted. After a recorded change the change stands; after an + /// unregistration the workspace stays registered. A grant revoked whose + /// container profile could not be deleted is not listed for **Revoke**, + /// because it is gone. The operating system's own text is never shown. + pub(super) fn revocation_incomplete( + failures: &[(uuid::Uuid, ControlError)], + change: RevokingChange, + ) -> Self { + let mut message = match change { + RevokingChange::Recorded => { + "The change was recorded, but not every container grant it releases was revoked." + } + RevokingChange::Unregistration => { + "The workspace stays registered, because not every container grant of it was revoked." + } + } + .to_owned(); + let unrevoked: Vec<&ControlError> = failures + .iter() + .map(|(_, error)| error) + .filter(|error| !matches!(error, ControlError::ProfileRemoval(_))) + .collect(); + let access = unrevoked + .iter() + .any(|error| matches!(error, ControlError::Container(_))); + if let Some(other) = unrevoked + .iter() + .find(|error| !matches!(error, ControlError::Container(_))) + { + message.push_str(&format!( + " {} grant(s) were not revoked: {}.", + unrevoked.len(), + Self::from_control(other).message().trim_end_matches('.') + )); + } else if access { + message.push_str(&format!( + " {} grant(s) could not be removed from their folders' access lists and stay revoking.", + unrevoked.len() + )); + } + if !unrevoked.is_empty() { + message.push_str(" The settings list each one, and Revoke tries again."); + } + if unrevoked.len() < failures.len() { + message.push_str( + " A grant was revoked, but the workspace's AppContainer profile could not be deleted; it holds no access now.", + ); + } + if change == RevokingChange::Unregistration { + message.push_str(if unrevoked.is_empty() { + " Remove the workspace again." + } else { + " Then remove the workspace again." + }); + } + let code = if access { + "container_access_failed" + } else { + "revocation_incomplete" }; - match error { - ControlError::Container(_) => Self::execution( - "container_access_failed", - format!( - "{outcome} could not be removed from its folder's access list. The grant stays revoking; the settings list it, and Revoke tries again.{then}" - ), - ), - other => Self::execution( - "revocation_incomplete", - format!( - "{outcome} was not revoked: {}. The settings list the grant, and Revoke tries again.{then}", - Self::from_control(other).message() - ), + Self::execution(code, message) + } + + /// Every container grant of the workspace was revoked, but its removal + /// could not be recorded, so it stays registered. + fn removal_not_recorded(error: &ControlError) -> Self { + Self::execution( + "revocation_incomplete", + format!( + "Every container grant of the workspace was revoked, but its removal could not be recorded: {}. The workspace stays registered; remove it again.", + Self::from_control(error).message().trim_end_matches('.') ), - } + ) } } diff --git a/crates/omgcode-app/src/desktop/settings_discovery.rs b/crates/omgcode-app/src/desktop/settings_discovery.rs index d06ab436..f3ebb161 100644 --- a/crates/omgcode-app/src/desktop/settings_discovery.rs +++ b/crates/omgcode-app/src/desktop/settings_discovery.rs @@ -202,12 +202,20 @@ impl DesktopError { ) } - /// Every profile was recorded, but the assignment to the workspace failed. - fn not_assigned(total: usize, cause: &Self) -> Self { + /// Every profile was recorded, but the assignment to the workspace did + /// not complete: `assigned` of them were assigned before it failed. + fn not_assigned(total: usize, assigned: usize, cause: &Self) -> Self { + let outcome = if assigned == 0 { + format!("The {total} profile(s) were recorded but not assigned to the workspace") + } else { + format!( + "The {total} profile(s) were recorded, and {assigned} of them were assigned to the workspace before the assignment failed" + ) + }; Self::execution( cause.code(), format!( - "The {total} profile(s) were recorded but not assigned to the workspace: {} Assign them on the workspace's page.", + "{outcome}: {} Reload the workspace's page and turn on the others there.", cause.message() ), ) @@ -500,11 +508,23 @@ impl DesktopService { } if let Some((workspace_id, _, plan)) = &assign { let names: Vec<&str> = chosen.iter().map(ToolchainProposal::name).collect(); - store - .assign_profiles_with_access(*workspace_id, &names, plan, expected) - .map_err(|error| { - DesktopError::not_assigned(chosen.len(), &DesktopError::from_grant(&error)) - })?; + if let Err(error) = + store.assign_profiles_with_access(*workspace_id, &names, plan, expected) + { + // Assignments recorded before the failure stand. + let assigned = names + .iter() + .filter_map(|name| store.profile(name)) + .filter(|status| { + store.profile_assigned(*workspace_id, status.profile().id()) + }) + .count(); + return Err(DesktopError::not_assigned( + chosen.len(), + assigned, + &DesktopError::from_grant(&error), + )); + } } } self.discovery_view(host, request.workspace_id, MissingWorkspace::Ignore) diff --git a/crates/omgcode-app/tests/common/mod.rs b/crates/omgcode-app/tests/common/mod.rs index ccaa6fdf..49046f01 100644 --- a/crates/omgcode-app/tests/common/mod.rs +++ b/crates/omgcode-app/tests/common/mod.rs @@ -517,8 +517,11 @@ const DECLARED_PROFILE: &str = "system"; /// /// On Windows, registering a workspace through the `settings` service grants /// its container its folder (ADR-0107), which adds an access-control entry and -/// creates an AppContainer profile on the host. Dropping the fixture revokes -/// every grant still recorded, so neither outlives the test. +/// creates an AppContainer profile on the host. A test that grants ends with +/// [`Fixture::revoke_grants`], which fails it when a grant cannot be revoked, +/// before the temporary directory and the journal needed to retry are gone. +/// Dropping the fixture revokes every grant still recorded as a fallback for +/// a test that ends early, reporting a failure without panicking. pub struct Fixture { _temporary: TempDir, pub data: PathBuf, @@ -527,12 +530,26 @@ pub struct Fixture { impl Drop for Fixture { fn drop(&mut self) { + if let Err(problem) = self.revoke_grants() { + // Never panic in drop: a second panic would abort the run. + eprintln!("fixture cleanup: {problem}"); + } + } +} + +impl Fixture { + /// Revoke every container grant still recorded, attempting each one. + /// + /// # Errors + /// + /// The settings store could not be opened, or a grant could not be + /// revoked; every failure is named. + pub fn revoke_grants(&self) -> Result<(), String> { let mut control = match ControlStore::open_existing(&self.data) { Ok(Some(control)) => control, - Ok(None) => return, + Ok(None) => return Ok(()), Err(error) => { - eprintln!("fixture cleanup could not open the settings store: {error}"); - return; + return Err(format!("the settings store could not be opened: {error}")); } }; let grants: Vec = control @@ -540,16 +557,21 @@ impl Drop for Fixture { .iter() .map(|status| status.grant().id()) .collect(); - for grant in grants { - if let Err(error) = control.revoke_container_grant(grant) { - // Never panic in drop: a second panic would abort the run. - eprintln!("fixture cleanup could not revoke container grant {grant}: {error}"); - } + let failures: Vec = grants + .into_iter() + .filter_map(|grant| { + control + .revoke_container_grant(grant) + .err() + .map(|error| format!("container grant {grant} could not be revoked: {error}")) + }) + .collect(); + if failures.is_empty() { + Ok(()) + } else { + Err(failures.join("; ")) } } -} - -impl Fixture { /// Application data only; no settings store exists. pub fn bare() -> Self { let temporary = tempfile::tempdir().expect("private fixture root"); diff --git a/crates/omgcode-app/tests/desktop_settings_changes.rs b/crates/omgcode-app/tests/desktop_settings_changes.rs index e49debde..ff2bd73f 100644 --- a/crates/omgcode-app/tests/desktop_settings_changes.rs +++ b/crates/omgcode-app/tests/desktop_settings_changes.rs @@ -410,6 +410,9 @@ fn registering_starts_at_the_root_and_uses_the_default_preferences() { .expect("registered again"); assert_eq!(repeated.revision, overview.revision); assert_eq!(repeated.workspaces.len(), 1); + fixture + .revoke_grants() + .expect("every container grant is revoked"); } /// Unregistering revokes the workspace's grants first, so on Windows the one @@ -440,15 +443,25 @@ fn unregistering_revokes_the_grant_registration_made() { cfg!(windows), "{message}" ); + // The folder's own line, and on Windows its grant's line; a parent + // folder whose name contains `project` is not counted. assert_eq!( - message.matches("project").count(), - if cfg!(windows) { 2 } else { 1 } + message + .lines() + .filter(|line| line.trim_end().ends_with("project")) + .count(), + if cfg!(windows) { 2 } else { 1 }, + "{message}" ); let store = ControlStore::open_existing(&fixture.data) .expect("open") .expect("exists"); assert!(store.container_grants().is_empty()); assert_eq!(store.workspaces().count(), 0); + drop(store); + fixture + .revoke_grants() + .expect("every container grant is revoked"); } #[test] diff --git a/crates/omgcode-app/tests/desktop_settings_discovery.rs b/crates/omgcode-app/tests/desktop_settings_discovery.rs index b9a78fc2..e97e5cc7 100644 --- a/crates/omgcode-app/tests/desktop_settings_discovery.rs +++ b/crates/omgcode-app/tests/desktop_settings_discovery.rs @@ -679,6 +679,10 @@ fn adding_with_a_workspace_names_what_it_grants_in_the_one_confirmation() { assert!(store.container_grants().is_empty()); assert!(store.profiles().is_empty()); assert_eq!(store.revision(), before); + drop(store); + fixture + .revoke_grants() + .expect("every container grant is revoked"); } #[test] @@ -735,6 +739,10 @@ fn adding_with_a_workspace_assigns_the_profiles_and_grants_their_folders() { } else { assert!(grants.is_empty(), "{grants:?}"); } + drop(store); + fixture + .revoke_grants() + .expect("every container grant is revoked"); } #[cfg(windows)] @@ -793,6 +801,10 @@ fn on_windows_adding_a_proposal_inside_the_development_root_to_a_workspace_grant .expect("exists"); assert!(store.container_grants().is_empty()); assert_eq!(store.revision(), before); + drop(store); + fixture + .revoke_grants() + .expect("every container grant is revoked"); } #[cfg(not(windows))] diff --git a/crates/omgcode-app/tests/desktop_settings_execution.rs b/crates/omgcode-app/tests/desktop_settings_execution.rs index cfb42c75..b6be9631 100644 --- a/crates/omgcode-app/tests/desktop_settings_execution.rs +++ b/crates/omgcode-app/tests/desktop_settings_execution.rs @@ -22,7 +22,10 @@ use omgcode_app::desktop::{ FolderPurpose, PackageProfileAddRequest, ProfileAssignmentRequest, ProfileRemoveRequest, SettingsOverview, SettingsPrompt, ToolchainProfileAddRequest, WebHostChangeRequest, }; -use omgcode_core::control::{ContainerGrantAccess, ControlStore, PackageProfileDeclaration}; +use omgcode_core::control::{ + ContainerGrantAccess, ContainerGrantState, ControlStore, PackageProfileDeclaration, +}; +use omgcode_core::turn::display_safe_line; use serde_json::json; use uuid::Uuid; @@ -189,8 +192,8 @@ fn assignment(revision: u64, workspace: Uuid, name: &str) -> ProfileAssignmentRe wire(json!({ "revision": revision, "workspace_id": workspace, "name": name })) } -/// The recorded grants as `(access, directory)`, in order. -fn recorded_grants(data: &Path) -> Vec<(ContainerGrantAccess, PathBuf)> { +/// The recorded grants as `(access, state, directory display)`, in order. +fn recorded_grants(data: &Path) -> Vec<(ContainerGrantAccess, ContainerGrantState, String)> { ControlStore::open_existing(data) .expect("open") .expect("exists") @@ -199,16 +202,21 @@ fn recorded_grants(data: &Path) -> Vec<(ContainerGrantAccess, PathBuf)> { .map(|status| { ( status.grant().access(), - resolved(Path::new(&status.grant().directory_display())), + status.state(), + status.grant().directory_display(), ) }) .collect() } -/// `path` as the operating system resolves it, for comparing with a recorded -/// directory. -fn resolved(path: &Path) -> PathBuf { - fs::canonicalize(path).expect("canonical path") +/// The display text core records for the directory at `path`: its canonical +/// path, made display-safe. Display text is compared, never reopened. +fn displayed(path: &Path) -> String { + display_safe_line( + &fs::canonicalize(path) + .expect("canonical path") + .to_string_lossy(), + ) } /// Record a toolchain profile through the service. @@ -588,7 +596,8 @@ fn assigning_a_profile_is_confirmed_with_the_folders_it_grants() { recorded_grants(&fixture.data), [( ContainerGrantAccess::ReadExecute, - resolved(&tool_root(&fixture, "rust")) + ContainerGrantState::Active, + displayed(&tool_root(&fixture, "rust")) )] ); } else { @@ -603,6 +612,9 @@ fn assigning_a_profile_is_confirmed_with_the_folders_it_grants() { )); assert_eq!(error.code(), "control"); assert!(silent.asked().is_empty()); + fixture + .revoke_grants() + .expect("every container grant is revoked"); } /// Unassigning revokes the grants only that profile needed and says so; @@ -663,6 +675,9 @@ fn unassigning_a_profile_revokes_the_grants_it_alone_needed() { assert_eq!(error.code(), "control"); assert!(error.message().contains("not assigned"), "{error}"); assert!(silent.asked().is_empty()); + fixture + .revoke_grants() + .expect("every container grant is revoked"); } /// Removing an assigned profile names the workspace it leaves and, on @@ -695,6 +710,9 @@ fn removing_an_assigned_profile_names_its_workspace_and_revokes_its_grant() { assert!(overview.toolchain_profiles.is_empty()); assert!(overview.workspaces[0].profiles.is_empty()); assert!(recorded_grants(&fixture.data).is_empty()); + fixture + .revoke_grants() + .expect("every container grant is revoked"); } #[test] diff --git a/crates/omgcode-cli/src/control_cli.rs b/crates/omgcode-cli/src/control_cli.rs index 9804ec2c..a86ecbd0 100644 --- a/crates/omgcode-cli/src/control_cli.rs +++ b/crates/omgcode-cli/src/control_cli.rs @@ -4,8 +4,8 @@ use clap::{Args, Subcommand, ValueEnum}; use omgcode_core::control::{ - ContainerGrantAccess, ControlError, ControlStore, CredentialId, PackageProfileDeclaration, - ProfileDeclaration, ProviderProfileDeclaration, Revocations, + ContainerGrantAccess, ContainerGrantState, ControlError, ControlStore, CredentialId, + PackageProfileDeclaration, ProfileDeclaration, ProviderProfileDeclaration, Revocations, }; use omgcode_core::policy::{ Access, Operation, PermissionSet, PolicyRequest, WorkspaceId, WriteTool, @@ -565,11 +565,31 @@ pub(crate) fn run(action: WorkspaceCommand, data_root: &Path) -> Result<(), CliE .register_workspace_with_access(&path, revision) .map_err(control_error)?; let grant = registered.grant.map_err(|error| { + let id = registered.registration.id(); + // A grant whose access-control change failed is recorded + // `pending`, and a second grant of the same folder, or + // registering it again, is refused or skipped until it is + // revoked. + let pending = store + .container_grants() + .iter() + .find(|status| { + status.grant().workspace_id() == id + && status.state() != ContainerGrantState::Active + }) + .map(|status| status.grant().id()); + let recovery = pending.map_or_else( + || "Grant it with `workspace container-grant`.".to_owned(), + |grant| { + format!( + "Grant {grant} is recorded as pending: revoke it with `workspace container-revoke {grant}`, then register the folder again with the current revision from `workspace status`, which grants it." + ) + }, + ); CliError::new( "control", format!( - "The workspace was registered as {}, but its container could not be granted its folder: {error}. Grant it with `workspace container-grant`.", - registered.registration.id() + "The workspace was registered as {id}, but its container could not be granted its folder: {error}. {recovery}" ), ) })?; @@ -592,13 +612,20 @@ pub(crate) fn run(action: WorkspaceCommand, data_root: &Path) -> Result<(), CliE // A revocation withdraws every run of the workspace that started // before it, and runs start only under the lock held here. let before = run::pending_runs(&store); - let revocations = store + let unregistration = store .unregister_workspace_with_access(workspace_id, revision) .map_err(control_error)?; let snapshot = store.snapshot(); let listed = withdrawn_runs(&store); drop(store); - finish_revocations(data_root, listed, before, &revocations, true)?; + finish_revocations( + data_root, + listed, + before, + &unregistration.revocations, + RevokingChange::Unregistration(unregistration.removal.as_ref()), + )?; + let revocations = unregistration.revocations; // The change is recorded. A saved desktop instructions file is // removed next, without the desktop's in-process lock; a file that // remains is never sent, because a turn reads it only for a @@ -692,7 +719,13 @@ pub(crate) fn run(action: WorkspaceCommand, data_root: &Path) -> Result<(), CliE }); let listed = withdrawn_runs(&store); drop(store); - finish_revocations(data_root, listed, before, &revocations, false)?; + finish_revocations( + data_root, + listed, + before, + &revocations, + RevokingChange::Recorded, + )?; print_json(&output) } WorkspaceCommand::ProfileAssign { @@ -719,7 +752,13 @@ pub(crate) fn run(action: WorkspaceCommand, data_root: &Path) -> Result<(), CliE }); let listed = withdrawn_runs(&store); drop(store); - finish_revocations(data_root, listed, before, &revocations, false)?; + finish_revocations( + data_root, + listed, + before, + &revocations, + RevokingChange::Recorded, + )?; print_json(&output) } WorkspaceCommand::PackageProfileAdd(args) => package_profile_add(args, data_root), @@ -912,19 +951,30 @@ fn profile_assign( })) } +/// The change [`finish_revocations`] reports on. +#[derive(Clone, Copy)] +enum RevokingChange<'a> { + /// A recorded change, which stands whatever its revocations did. + Recorded, + /// An unregistration, recorded only after every grant was revoked, with + /// the error that kept it from being recorded after that, if any. + Unregistration(Option<&'a ControlError>), +} + /// After a recorded change that may have revoked grants, wait for the runs it /// withdrew, then report what did not complete. `listed` holds the runs the /// settings withdrew; `before` every pending run, listed by /// `run::pending_runs` before the change. Any revocation, even one that failed /// after it was requested, withdraws every run of its workspace, so the runs -/// of those workspaces are waited for too. A grant that could not be revoked -/// stays recorded, and `workspace container-revoke` retries it. +/// of those workspaces are waited for too. Every grant that could not be +/// revoked is named; it stays recorded, and `workspace container-revoke` +/// retries it. fn finish_revocations( data_root: &Path, listed: Result, CliError>, before: Result, run::RunError>, revocations: &Revocations, - unregistration: bool, + change: RevokingChange<'_>, ) -> Result<(), CliError> { let mut wait = listed.as_deref().unwrap_or(&[]).to_vec(); let mut problems = Vec::new(); @@ -937,19 +987,39 @@ fn finish_revocations( } } let mut kind = "run"; - if let Some((grant, error)) = &revocations.failure { + if !revocations.failures.is_empty() { kind = "control"; - // An unregistration is recorded only after every grant is revoked. - let message = if unregistration { - format!( - "The workspace stays registered, because grant {grant} could not be revoked: {error}. Retry with `workspace container-revoke {grant}`, then unregister it again." - ) - } else { - format!( - "The change was recorded, but grant {grant} could not be revoked: {error}. Retry with `workspace container-revoke {grant}`." - ) + let mut message = match change { + RevokingChange::Recorded => { + "The change was recorded, but not every container grant it releases was revoked.".to_owned() + } + RevokingChange::Unregistration(_) => { + "The workspace stays registered, because not every container grant of it was revoked.".to_owned() + } }; + for (grant, error) in &revocations.failures { + if matches!(error, ControlError::ProfileRemoval(_)) { + // The grant is revoked; only the container's profile, which + // holds no grant now, could not be deleted. + message.push_str(&format!(" Grant {grant}: {error}.")); + } else { + message.push_str(&format!( + " Grant {grant} could not be revoked: {error}; retry with `workspace container-revoke {grant}`." + )); + } + } + if matches!(change, RevokingChange::Unregistration(_)) { + message.push_str(" Then unregister it again."); + } problems.insert(0, message); + } else if let RevokingChange::Unregistration(Some(error)) = change { + kind = "control"; + problems.insert( + 0, + format!( + "Every container grant of the workspace was revoked, but its removal could not be recorded: {error}. The workspace stays registered; unregister it again." + ), + ); } if let Err(error) = stop_withdrawn_runs(data_root, &wait) { problems.push(error.message); diff --git a/crates/omgcode-cli/tests/control_workflow.rs b/crates/omgcode-cli/tests/control_workflow.rs index 86b34187..d63645f6 100644 --- a/crates/omgcode-cli/tests/control_workflow.rs +++ b/crates/omgcode-cli/tests/control_workflow.rs @@ -15,7 +15,7 @@ use omgcode_core::control::ControlStore; use support::CLI_DEADLINE; use support::{ GRANT_CLI_DEADLINE, HANG_FIXTURE_ENV, assert_control_error, assert_error_code, assert_success, - json_output, path_arg, run_cli, run_cli_for, run_with_deadline, + json_output, path_arg, revoke_recorded_grants, run_cli, run_cli_for, run_with_deadline, }; /// Park only when the timeout regression launches this test in a child process. @@ -934,29 +934,11 @@ struct RevokeGrantsOnDrop<'a>(&'a Path); impl Drop for RevokeGrantsOnDrop<'_> { fn drop(&mut self) { - let status = run_cli(self.0, &["workspace", "status"]); - if !status.status.success() { - return; - } - for grant in json_output(&status)["container_grants"] - .as_array() - .into_iter() - .flatten() - { - let Some(id) = grant["id"].as_str() else { - continue; - }; - let revoked = run_cli_for( - self.0, - &["workspace", "container-revoke", id], - GRANT_CLI_DEADLINE, - ); - if !revoked.status.success() { - eprintln!( - "grant revocation failed during cleanup: {id}: {}", - String::from_utf8_lossy(&revoked.stderr) - ); - } + // The helpers report a failed status read, a timeout, and a failed + // revocation instead of panicking, which would abort a run that is + // already unwinding, and every grant is attempted. + for problem in revoke_recorded_grants(self.0) { + eprintln!("grant revocation failed during cleanup: {problem}"); } } } diff --git a/crates/omgcode-cli/tests/file_workflow.rs b/crates/omgcode-cli/tests/file_workflow.rs index 5311dda1..4c0a50e6 100644 --- a/crates/omgcode-cli/tests/file_workflow.rs +++ b/crates/omgcode-cli/tests/file_workflow.rs @@ -6,9 +6,11 @@ use std::path::{Path, PathBuf}; use tempfile::TempDir; use uuid::Uuid; +use omgcode_core::control::ControlStore; +use support::spawn_gate::without_child_spawns; use support::{ assert_control_error, assert_error_code, assert_success, json_output, live_revision, path_arg, - register_workspace, run_cli, + run_cli, }; const FILE_CONTENT: &str = "FILE_BODY_SECRET_9fa0321d2c7e"; @@ -45,11 +47,21 @@ fn workspace_fixture() -> WorkspaceFixture { ); assert_success(&root); assert_eq!(json_output(&root)["revision"], 1); - let registered = register_workspace(&data_root, &workspace, 1); - let workspace_id = registered["registration_id"] - .as_str() - .expect("workspace ID") - .to_owned(); + // Core's registration primitive grants nothing. These tests run no + // program, so the workspace needs no container access, and no + // access-control entry or AppContainer profile can outlive them + // (ADR-0107). The store is closed before any child starts. + let workspace_id = without_child_spawns(|| { + let mut store = ControlStore::open_existing(&data_root) + .expect("open settings") + .expect("settings exist"); + store + .register_workspace(&workspace, 1) + .expect("register workspace") + .id() + .as_uuid() + .to_string() + }); WorkspaceFixture { _temporary: temporary, diff --git a/crates/omgcode-cli/tests/run_workflow.rs b/crates/omgcode-cli/tests/run_workflow.rs index fe0bf656..98731a2d 100644 --- a/crates/omgcode-cli/tests/run_workflow.rs +++ b/crates/omgcode-cli/tests/run_workflow.rs @@ -19,6 +19,7 @@ use std::thread; use std::time::{Duration, Instant}; use support::run_scene::{Scene, error_message, run_json, shell, system_root, wait}; +use support::spawn_gate; use support::{ CLI_DEADLINE, HOST_ENV_SENTINEL, HOST_ENV_SENTINEL_VALUE, assert_control_error, assert_error_code, assert_success, cli_command, json_output, path_arg, run_with_deadline, @@ -910,10 +911,7 @@ fn removing_the_profile_stops_a_live_run() { fn unassigning_the_profile_stops_a_live_run() { let scene = Scene::new(); assert_success(&scene.add_profile("system", &[])); - let child = scene - .command(&[], &shell(LONG_RUN)) - .spawn() - .expect("spawn run"); + let child = spawn_gate::spawn(&mut scene.command(&[], &shell(LONG_RUN))).expect("spawn run"); wait_for_start(&scene); let revision = scene.revision().to_string(); let output = scene.settings_cli(&[ diff --git a/crates/omgcode-cli/tests/support/mod.rs b/crates/omgcode-cli/tests/support/mod.rs index fc7734e8..a9bf045a 100644 --- a/crates/omgcode-cli/tests/support/mod.rs +++ b/crates/omgcode-cli/tests/support/mod.rs @@ -202,6 +202,88 @@ pub(crate) fn path_arg(path: &Path) -> &str { /// well as updating access-control lists. pub(crate) const GRANT_CLI_DEADLINE: Duration = Duration::from_secs(120); +/// The identifiers of the container grants `workspace status` lists, read +/// without panicking, for cleanup that may run while a test unwinds. +/// +/// # Errors +/// +/// Status could not run, timed out, failed, or printed no JSON. +#[allow( + dead_code, + reason = "only test binaries that clean up container grants use it" +)] +pub(crate) fn recorded_grant_ids(data_root: &Path) -> Result, String> { + let result = run_with_deadline( + cli_command(data_root, &["workspace", "status"]), + GRANT_CLI_DEADLINE, + ) + .map_err(|error| format!("status could not run: {error}"))?; + if result.timed_out { + return Err("status timed out".to_owned()); + } + if !result.output.status.success() { + return Err(format!( + "status failed: {}", + String::from_utf8_lossy(&result.output.stderr) + )); + } + let status: serde_json::Value = serde_json::from_slice(&result.output.stdout) + .map_err(|error| format!("status is not JSON: {error}"))?; + Ok(status["container_grants"] + .as_array() + .into_iter() + .flatten() + .filter_map(|grant| grant["id"].as_str().map(str::to_owned)) + .collect()) +} + +/// Revoke the grant `grant` without panicking, for cleanup code. +/// +/// # Errors +/// +/// The revocation could not run, timed out, or failed. +#[allow( + dead_code, + reason = "only test binaries that clean up container grants use it" +)] +pub(crate) fn revoke_grant_quietly( + data_root: &Path, + grant: &str, + deadline: Duration, +) -> Result<(), String> { + let result = run_with_deadline( + cli_command(data_root, &["workspace", "container-revoke", grant]), + deadline, + ) + .map_err(|error| format!("{grant}: {error}"))?; + if result.timed_out { + return Err(format!("{grant}: timed out")); + } + if !result.output.status.success() { + return Err(format!( + "{grant}: {}", + String::from_utf8_lossy(&result.output.stderr) + )); + } + Ok(()) +} + +/// Revoke every container grant `workspace status` lists, attempting each +/// one, and return the failures. Never panics. +#[allow( + dead_code, + reason = "only test binaries that clean up container grants use it" +)] +pub(crate) fn revoke_recorded_grants(data_root: &Path) -> Vec { + match recorded_grant_ids(data_root) { + Ok(grants) => grants + .iter() + .filter_map(|grant| revoke_grant_quietly(data_root, grant, GRANT_CLI_DEADLINE).err()) + .collect(), + Err(error) => vec![error], + } +} + /// Register `workspace` through the CLI at `revision` and return the JSON /// output, failing the test on error. /// @@ -222,19 +304,33 @@ pub(crate) fn register_workspace( revision: u64, ) -> serde_json::Value { let revision = revision.to_string(); - let output = run_cli_for( - data_root, - &[ - "workspace", - "register", - path_arg(workspace), - "--revision", - &revision, - ], + let result = run_with_deadline( + cli_command( + data_root, + &[ + "workspace", + "register", + path_arg(workspace), + "--revision", + &revision, + ], + ), GRANT_CLI_DEADLINE, - ); - assert_success(&output); - let registered = json_output(&output); + ) + .expect("run OMGCode CLI"); + if result.timed_out || !result.output.status.success() { + // A registration that failed after recording its grant leaves it + // pending; revoke it before failing, so no access-control entry or + // AppContainer profile outlives the test. + let cleanup = revoke_recorded_grants(data_root); + panic!( + "registration failed (timed out: {}): stdout={} stderr={}; cleanup failures: {cleanup:?}", + result.timed_out, + String::from_utf8_lossy(&result.output.stdout), + String::from_utf8_lossy(&result.output.stderr) + ); + } + let registered = json_output(&result.output); if let Some(grant) = registered["grant_id"].as_str() { assert_success(&run_cli_for( data_root, diff --git a/crates/omgcode-cli/tests/support/run_scene.rs b/crates/omgcode-cli/tests/support/run_scene.rs index 7ad75448..967d59d2 100644 --- a/crates/omgcode-cli/tests/support/run_scene.rs +++ b/crates/omgcode-cli/tests/support/run_scene.rs @@ -9,7 +9,8 @@ use std::time::{Duration, Instant}; use tempfile::TempDir; use super::{ - assert_success, cli_command, json_output, path_arg, run_cli, run_cli_for, run_with_deadline, + assert_success, cli_command, json_output, path_arg, recorded_grant_ids, run_cli, run_cli_for, + run_with_deadline, }; /// CLI deadline for a container grant or revocation. @@ -159,17 +160,12 @@ impl Scene { /// before its identifier was known. When status cannot be read, the /// tracked list is kept. fn track_recorded_grants(&mut self) { - let output = self.cli(&["workspace", "status"]); - if !output.status.success() { + // `Drop` calls this, so status is read without panicking: a second + // panic while a test unwinds would abort the run and skip the + // revocations. + let Ok(recorded) = recorded_grant_ids(&self.data) else { return; - } - let status = json_output(&output); - let recorded: Vec = status["container_grants"] - .as_array() - .into_iter() - .flatten() - .filter_map(|grant| grant["id"].as_str().map(str::to_owned)) - .collect(); + }; self.grants.retain(|known| recorded.contains(known)); for id in recorded { if !self.grants.contains(&id) { diff --git a/crates/omgcode-core/src/control.rs b/crates/omgcode-core/src/control.rs index 51eeba4f..baf87222 100644 --- a/crates/omgcode-core/src/control.rs +++ b/crates/omgcode-core/src/control.rs @@ -42,6 +42,7 @@ pub use approval::{ pub use assignment::{ PlannedFolder, ProfileAccessPlan, ProfileAssignment, RegisteredWorkspace, Revocations, + Unregistration, }; pub use container::{ ContainerGrant, ContainerGrantAccess, ContainerGrantState, ContainerGrantStatus, diff --git a/crates/omgcode-core/src/control/assignment.rs b/crates/omgcode-core/src/control/assignment.rs index 60b12412..bc8e13de 100644 --- a/crates/omgcode-core/src/control/assignment.rs +++ b/crates/omgcode-core/src/control/assignment.rs @@ -23,9 +23,9 @@ use omgcode_platform::container::{self as platform, CONTAINER_GRANTS_SUPPORTED}; use uuid::Uuid; use super::{ - Action, ContainerGrant, ContainerGrantAccess, ContainerRevocation, ControlError, - ControlSnapshot, ControlStore, ProfilePlatform, RootGrantNeed, WorkspaceRegistration, - root_grant_need, + Action, ContainerGrant, ContainerGrantAccess, ContainerGrantState, ContainerGrantStatus, + ContainerRevocation, ControlError, ControlSnapshot, ControlStore, ProfilePlatform, + RootGrantNeed, WorkspaceRegistration, root_grant_need, }; use crate::policy::WorkspaceId; use crate::workspace::DirectoryRecord; @@ -140,10 +140,13 @@ pub struct RegisteredWorkspace { pub struct Revocations { /// The confirmed revocations, in order. pub revoked: Vec, - /// The first revocation that failed, with its grant; later ones were not - /// attempted. The grant stays recorded, `revoking` when its access-control - /// change failed, and `workspace container-revoke` retries it. - pub failure: Option<(Uuid, ControlError)>, + /// Each revocation that failed, with its grant, in order. Every grant is + /// attempted, so one failure never leaves a later grant unrevoked. A + /// failed grant stays recorded, `revoking` when its access-control change + /// failed, and `workspace container-revoke` retries it. After + /// [`ControlError::ProfileRemoval`] the grant is revoked, and only the + /// container's AppContainer profile, which then holds no grant, remains. + pub failures: Vec<(Uuid, ControlError)>, /// The workspace of each grant whose revocation was attempted, confirmed /// or not, each once, in order. A revocation withdraws every run of its /// workspace, which the settings alone do not show, so a caller waits @@ -151,6 +154,25 @@ pub struct Revocations { pub workspaces: Vec, } +/// What [`ControlStore::unregister_workspace_with_access`] did. +#[derive(Debug)] +pub struct Unregistration { + /// The revocations made first. The workspace stays registered when any + /// of them failed. + pub revocations: Revocations, + /// Why the workspace stays registered although every revocation was + /// confirmed: its removal could not be recorded. `None` otherwise. + pub removal: Option, +} + +impl Unregistration { + /// Whether the workspace was unregistered. + #[must_use] + pub fn unregistered(&self) -> bool { + self.revocations.failures.is_empty() && self.removal.is_none() + } +} + impl Revocations { /// The runs in `pending`, listed by `run::pending_runs` before the change, /// that belong to a workspace in [`Self::workspaces`]. @@ -262,7 +284,8 @@ impl ControlStore { /// # Errors /// /// What [`Self::assign_profile`] refuses for any of them, apart from the - /// revision, and a profile named twice. + /// revision; a profile named twice; and a container grant of the + /// workspace that is pending or being revoked. pub fn plan_profiles_access( &self, workspace_id: WorkspaceId, @@ -276,6 +299,7 @@ impl ControlStore { } ids.push(id); } + self.check_grants_settled(workspace_id)?; let mut plan = ProfileAccessPlan::default(); if !CONTAINER_GRANTS_SUPPORTED { return Ok(plan); @@ -309,7 +333,8 @@ impl ControlStore { /// /// # Errors /// - /// An unknown workspace. + /// An unknown workspace, and a container grant of it that is pending or + /// being revoked. pub fn plan_folder_access( &self, workspace_id: WorkspaceId, @@ -318,6 +343,7 @@ impl ControlStore { if self.workspace(workspace_id).is_none() { return Err(ControlError::UnknownWorkspace); } + self.check_grants_settled(workspace_id)?; let mut plan = ProfileAccessPlan::default(); if CONTAINER_GRANTS_SUPPORTED { self.plan_into(workspace_id, paths, &mut plan); @@ -329,15 +355,18 @@ impl ControlStore { /// the assignment, under this store's lock. The plan is made again first: /// a different list of folders to grant refuses the assignment, so the /// operator never grants a folder they did not see. Each grant goes - /// through [`Self::grant_container_access`] and advances the revision. + /// through [`Self::grant_container_access`], is refused when its folder + /// is no longer the confirmed directory, and advances the revision. /// /// # Errors /// /// What [`Self::assign_profile`] refuses; a changed plan; a folder core's - /// grant rules refuse, before anything is recorded; and the first grant - /// that fails. Grants applied before a failure stay recorded, the profile - /// is then not assigned, and a grant whose access-control change failed - /// stays `pending` until it is revoked. + /// grant rules refuse, before anything is recorded; the first grant that + /// fails; and an assignment that cannot be recorded. After a failure the + /// profile is not assigned, and the grants this call made that no + /// assigned profile needs are revoked, which withdraws the workspace's + /// runs. A grant whose revocation fails then stays recorded, `pending` + /// or `revoking`, until it is revoked. pub fn assign_profile_with_access( &mut self, workspace_id: WorkspaceId, @@ -357,7 +386,8 @@ impl ControlStore { /// # Errors /// /// As [`Self::assign_profile_with_access`]. An assignment that fails - /// after others were recorded leaves those recorded. + /// after others were recorded leaves those recorded, with the grants + /// they need. pub fn assign_profiles_with_access( &mut self, workspace_id: WorkspaceId, @@ -372,21 +402,51 @@ impl ControlStore { "the folders this assignment grants changed; review it again", )); } - let paths = plan.paths(); - self.check_container_grants(workspace_id, &paths, ContainerGrantAccess::ReadExecute) - .map_err(|(_, error)| error)?; - let mut granted = Vec::with_capacity(paths.len()); - for path in &paths { - granted.push(self.grant_container_access( + self.check_container_grants( + workspace_id, + &plan.paths(), + ContainerGrantAccess::ReadExecute, + ) + .map_err(|(_, error)| error)?; + let mut granted = Vec::with_capacity(plan.grant.len()); + for folder in &plan.grant { + match self.grant_confirmed_container_access( workspace_id, - path, + &folder.path, + folder.record.as_ref(), ContainerGrantAccess::ReadExecute, self.revision(), - )?); + ) { + Ok(grant) => granted.push(grant), + Err(error) => { + // A grant whose access-control change failed is recorded + // `pending`, and it is this call's: the plan leaves out a + // folder that already has a grant of the workspace. + let mut made: Vec = granted.iter().map(ContainerGrant::id).collect(); + made.extend( + folder + .record + .as_ref() + .and_then(|record| self.workspace_grant_on(workspace_id, record)), + ); + self.release_unneeded(workspace_id, &made); + return Err(error); + } + } } let mut profile_ids = Vec::with_capacity(names.len()); for name in names { - profile_ids.push(self.assign_profile(workspace_id, name, self.revision())?); + match self.assign_profile(workspace_id, name, self.revision()) { + Ok(id) => profile_ids.push(id), + Err(error) => { + // The grants were the operator's consent to this + // assignment, so a grant no recorded assignment needs + // does not outlive it. + let made: Vec = granted.iter().map(ContainerGrant::id).collect(); + self.release_unneeded(workspace_id, &made); + return Err(error); + } + } } Ok(ProfileAssignment { profile_ids, @@ -559,16 +619,18 @@ impl ControlStore { /// /// # Errors /// - /// A stale revision or an unknown workspace, before anything changes, and - /// a failed unregistration after every grant was revoked. A failed - /// revocation does not fail the call; it is reported in - /// [`Revocations::failure`], and the workspace then stays registered with + /// A stale revision or an unknown workspace, before anything changes. + /// What fails after that does not fail the call, because the revocations + /// before it stand and their runs must be waited for: a failed revocation + /// is reported in [`Revocations::failures`], and a removal that cannot be + /// recorded after every grant was revoked in + /// [`Unregistration::removal`]. The workspace then stays registered, with /// the grants not yet revoked. pub fn unregister_workspace_with_access( &mut self, id: WorkspaceId, expected_revision: u64, - ) -> Result { + ) -> Result { self.check_revision(expected_revision)?; if self.workspace(id).is_none() { return Err(ControlError::UnknownWorkspace); @@ -580,10 +642,15 @@ impl ControlStore { .map(|status| status.grant().id()) .collect(); let revocations = self.revoke_each(&grants); - if revocations.failure.is_none() { - self.unregister_workspace(id, self.revision())?; - } - Ok(revocations) + let removal = if revocations.failures.is_empty() { + self.unregister_workspace(id, self.revision()).err() + } else { + None + }; + Ok(Unregistration { + revocations, + removal, + }) } /// The profile `name`'s identifier when it can be assigned to @@ -676,8 +743,39 @@ impl ControlStore { plan.grant.retain(|_| kept.next().unwrap_or(true)); } + /// Refuse while a container grant of `workspace_id` is pending or being + /// revoked. A run of the workspace is refused while one is, and a plan + /// leaves out a folder whose grant is recorded in any state, so an + /// assignment would look complete while its runs stay refused. + fn check_grants_settled(&self, workspace_id: WorkspaceId) -> Result<(), ControlError> { + if self.container_grants().iter().any(|status| { + status.grant().workspace_id() == workspace_id + && status.state() != ContainerGrantState::Active + }) { + return Err(ControlError::GrantRefused( + "a container grant of this workspace is pending or being revoked; revoke it under Settings, Advanced, Container grants, or with `omgcode workspace container-revoke`, then assign the profile again", + )); + } + Ok(()) + } + + /// The recorded grant of `workspace_id` on `directory`, in any state. + fn workspace_grant_on( + &self, + workspace_id: WorkspaceId, + directory: &DirectoryRecord, + ) -> Option { + self.container_grants() + .iter() + .map(ContainerGrantStatus::grant) + .find(|grant| { + grant.workspace_id() == workspace_id && grant.directory().same_directory(directory) + }) + .map(ContainerGrant::id) + } + /// The workspace's read-execute grants on `roots`, the roots of the - /// profile `leaving`, that no other profile assigned to it lists and that + /// profile `leaving`, that no other profile assigned to it needs and that /// are not its package cache root. fn unneeded_root_grants( &self, @@ -685,41 +783,94 @@ impl ControlStore { leaving: Uuid, roots: &[DirectoryRecord], ) -> Vec { - let still_needed: Vec<&DirectoryRecord> = self - .assigned_profiles(workspace_id) - .iter() - .filter(|id| **id != leaving) - .filter_map(|id| { - self.profiles() - .iter() - .find(|status| status.profile().id() == *id) - }) - .flat_map(|status| status.profile().read_only_roots()) - .collect(); let cache = self .snapshot .package_cache_roots .iter() .find(|status| status.workspace_id == workspace_id) .map(|status| &status.directory); - self.container_grants() + let candidates: Vec<&ContainerGrant> = self + .container_grants() .iter() - .map(super::ContainerGrantStatus::grant) + .map(ContainerGrantStatus::grant) .filter(|grant| { let directory = grant.directory(); grant.workspace_id() == workspace_id && grant.access() == ContainerGrantAccess::ReadExecute && roots.iter().any(|root| root.same_directory(directory)) - && !still_needed - .iter() - .any(|root| root.same_directory(directory)) && cache.is_none_or(|cache| !cache.same_directory(directory)) }) + .collect(); + let releasing: Vec = candidates.iter().map(|grant| grant.id()).collect(); + candidates + .into_iter() + .filter(|grant| !self.grant_needed(workspace_id, grant, Some(leaving), &releasing)) .map(ContainerGrant::id) .collect() } - /// Revoke each grant in order and stop at the first failure. + /// Whether a root of a profile assigned to `workspace_id`, other than + /// `leaving`, relies on `grant`: the root is the grant's folder, or lies + /// beneath it and no grant of the workspace outside `releasing` is on the + /// root or above it. A root inside another profile's root was readable + /// when it was planned, so it was given no grant of its own. A folder + /// whose containment cannot be read counts as not relying on the grant. + fn grant_needed( + &self, + workspace_id: WorkspaceId, + grant: &ContainerGrant, + leaving: Option, + releasing: &[Uuid], + ) -> bool { + let directory = grant.directory(); + let kept: Vec<&DirectoryRecord> = self + .container_grants() + .iter() + .map(ContainerGrantStatus::grant) + .filter(|other| { + other.workspace_id() == workspace_id + && other.id() != grant.id() + && !releasing.contains(&other.id()) + }) + .map(ContainerGrant::directory) + .collect(); + self.assigned_profiles(workspace_id) + .iter() + .filter(|id| Some(**id) != leaving) + .filter_map(|id| { + self.profiles() + .iter() + .find(|status| status.profile().id() == *id) + }) + .flat_map(|status| status.profile().read_only_roots()) + .any(|root| { + root.same_directory(directory) + || (directory.contains(root).unwrap_or(false) + && !kept.iter().any(|other| { + other.same_directory(root) || other.contains(root).unwrap_or(false) + })) + }) + } + + /// Revoke the grants in `made`, made by an assignment that then failed, + /// that no profile assigned to the workspace needs. A revocation that + /// fails leaves its grant recorded, as any failed revocation does. + fn release_unneeded(&mut self, workspace_id: WorkspaceId, made: &[Uuid]) { + let unneeded: Vec = made + .iter() + .filter(|id| { + self.container_grants() + .iter() + .map(ContainerGrantStatus::grant) + .find(|grant| grant.id() == **id) + .is_some_and(|grant| !self.grant_needed(workspace_id, grant, None, made)) + }) + .copied() + .collect(); + let _ = self.revoke_each(&unneeded); + } + + /// Revoke each grant in order, attempting every one. fn revoke_each(&mut self, grants: &[Uuid]) -> Revocations { let mut revocations = Revocations::default(); for grant in grants { @@ -730,10 +881,7 @@ impl ControlStore { } match self.revoke_container_grant(*grant) { Ok(revocation) => revocations.revoked.push(revocation), - Err(error) => { - revocations.failure = Some((*grant, error)); - break; - } + Err(error) => revocations.failures.push((*grant, error)), } } revocations diff --git a/crates/omgcode-core/src/control/assignment/tests.rs b/crates/omgcode-core/src/control/assignment/tests.rs index 3237c1b4..8b646580 100644 --- a/crates/omgcode-core/src/control/assignment/tests.rs +++ b/crates/omgcode-core/src/control/assignment/tests.rs @@ -218,7 +218,10 @@ fn replay_refuses_an_assignment_of_an_unknown_profile() { ); assert_ne!(text, tampered); fs::write(&journal, tampered).expect("tamper journal"); - assert!(ControlStore::open(&data).is_err()); + assert!(matches!( + ControlStore::open(&data), + Err(ControlError::Invalid("assignment of an unknown profile")) + )); } /// Off Windows nothing is planned; on Windows a fresh folder the current @@ -408,11 +411,11 @@ fn only_grants_no_remaining_profile_needs_are_unneeded() { ); } -/// A revocation names the workspace of every grant it attempted, each once and -/// in order, whether or not the grant was revoked, and keeps only those +/// A revocation attempts every grant, names the workspace of each, once and in +/// order, whether or not the grant was revoked, and keeps only those /// workspaces' runs to wait for. On Windows the recorded grants have no real -/// access-control entry, and removing nothing succeeds; elsewhere the first -/// revocation fails, which still names its workspace. +/// access-control entry, and removing nothing succeeds; elsewhere every +/// revocation fails, and a failure does not stop the later ones. #[test] fn revocations_name_each_attempted_workspace_and_its_runs() { let mut scene = scene(); @@ -434,20 +437,241 @@ fn revocations_name_each_attempted_workspace_and_its_runs() { let (run_app, run_other, run_third) = (Uuid::new_v4(), Uuid::new_v4(), Uuid::new_v4()); let pending = [(app, run_app), (other, run_other), (third, run_third)]; if CONTAINER_GRANTS_SUPPORTED { - assert!(revocations.failure.is_none(), "{:?}", revocations.failure); + assert!( + revocations.failures.is_empty(), + "{:?}", + revocations.failures + ); assert_eq!(revocations.revoked.len(), 3); - assert_eq!(revocations.workspaces, [app, other]); - assert_eq!(revocations.withdrawn_runs(&pending), [run_app, run_other]); } else { assert!(revocations.revoked.is_empty()); + let failed: Vec = revocations + .failures + .iter() + .map(|(grant, error)| { + assert!(matches!(error, ControlError::Container(_)), "{error:?}"); + *grant + }) + .collect(); + assert_eq!(failed, [first, second, last]); + } + assert_eq!(revocations.workspaces, [app, other]); + assert_eq!(revocations.withdrawn_runs(&pending), [run_app, run_other]); + assert!(Revocations::default().withdrawn_runs(&pending).is_empty()); +} + +/// A grant on an outer folder that a still-assigned profile's root lies +/// inside is kept, because that root was readable through it when it was +/// planned and has no grant of its own; it is released once the inner root +/// has its own grant or its profile is unassigned. +#[test] +fn a_grant_a_nested_root_relies_on_is_kept() { + let mut scene = scene(); + let app = scene.register("app"); + scene.profile("outer", &["sdk"]); + scene.profile("inner", &["sdk/bin"]); + scene.assign(app, "outer").expect("assign outer"); + scene.assign(app, "inner").expect("assign inner"); + let read = ContainerGrantAccess::ReadExecute; + let sdk = scene + .store + .test_record_grant(app, &scene.outside.join("sdk"), read); + let released = |store: &ControlStore| { + store + .grants_released_by_unassignment(app, "outer") + .expect("preview") + }; + + assert!(released(&scene.store).is_empty()); + assert_eq!( + scene + .store + .grants_released_by_removal("outer") + .expect("removal preview"), + [(app, Vec::new())] + ); + + let revision = scene.store.revision(); + scene + .store + .unassign_profile(app, "inner", revision) + .expect("unassign inner"); + assert_eq!(released(&scene.store), [sdk]); + + scene.assign(app, "inner").expect("assign inner again"); + scene + .store + .test_record_grant(app, &scene.outside.join("sdk/bin"), read); + assert_eq!(released(&scene.store), [sdk]); +} + +/// A workspace whose container grant is pending, or being revoked, is refused +/// a plan, because its runs are refused until that grant is settled. Another +/// workspace is not affected. +#[test] +fn a_pending_grant_refuses_an_assignment_plan() { + let mut scene = scene(); + let app = scene.register("app"); + let other = scene.register("other"); + scene.profile("rust", &["rust"]); + let cache = scene.outside.join("cache"); + fs::create_dir_all(&cache).expect("folder"); + scene + .store + .test_record_pending_grant(app, &cache, ContainerGrantAccess::ReadExecute); + + assert!(matches!( + scene.store.plan_profile_access(app, "rust"), + Err(ControlError::GrantRefused(_)) + )); + assert!(matches!( + scene + .store + .plan_folder_access(app, &[scene.outside.join("rust")]), + Err(ControlError::GrantRefused(_)) + )); + let revision = scene.store.revision(); + assert!(matches!( + scene.store.assign_profile_with_access( + app, + "rust", + &ProfileAccessPlan::default(), + revision + ), + Err(ControlError::GrantRefused(_)) + )); + assert!(scene.store.assigned_profiles(app).is_empty()); + scene + .store + .plan_profile_access(other, "rust") + .expect("another workspace plans"); +} + +/// A grant whose folder is no longer the directory the operator confirmed is +/// refused before anything is recorded. Off Windows no grant is made at all. +#[test] +fn a_grant_of_a_changed_folder_is_refused_before_it_is_recorded() { + let mut scene = scene(); + let app = scene.register("app"); + let confirmed_path = scene.outside.join("confirmed"); + let other_path = scene.outside.join("other"); + fs::create_dir_all(&confirmed_path).expect("confirmed folder"); + fs::create_dir_all(&other_path).expect("other folder"); + let confirmed = DirectoryRecord::capture(&confirmed_path).expect("identity"); + let revision = scene.store.revision(); + + let result = scene.store.grant_confirmed_container_access( + app, + &other_path, + Some(&confirmed), + ContainerGrantAccess::ReadExecute, + revision, + ); + + if CONTAINER_GRANTS_SUPPORTED { + assert!( + matches!(result, Err(ControlError::GrantRefused(_))), + "{result:?}" + ); + } else { + assert!( + matches!(result, Err(ControlError::Container(_))), + "{result:?}" + ); + } + assert_eq!(scene.store.revision(), revision); + assert!(scene.store.container_grants().is_empty()); +} + +/// An unregistration whose removal cannot be recorded after its revocations +/// returns them, so the caller waits for the runs they withdrew, and the +/// workspace stays registered. On Windows the recorded grant has no real +/// access-control entry, and removing nothing succeeds; elsewhere the +/// revocation fails, which also keeps the workspace registered. +#[test] +fn an_unregistration_that_cannot_be_recorded_returns_its_revocations() { + let mut scene = scene(); + let app = scene.register("app"); + let path = scene.outside.join("tool"); + fs::create_dir_all(&path).expect("folder"); + let grant = scene + .store + .test_record_grant(app, &path, ContainerGrantAccess::ReadExecute); + // Two events remain: the revocation's request and outcome fit in the + // reserve kept for the grant, and the removal does not. + let initial = scene.store.entries[0].clone(); + scene + .store + .entries + .resize(crate::control::MAX_EVENTS - 2, initial); + let revision = scene.store.revision(); + + let unregistration = scene + .store + .unregister_workspace_with_access(app, revision) + .expect("revocations are returned"); + + assert!(!unregistration.unregistered()); + assert!(scene.store.workspace(app).is_some()); + assert_eq!(unregistration.revocations.workspaces, [app]); + if CONTAINER_GRANTS_SUPPORTED { assert!( - matches!(revocations.failure, Some((id, ControlError::Container(_))) if id == first), + unregistration.revocations.failures.is_empty(), "{:?}", - revocations.failure + unregistration.revocations.failures ); - // The failure stops the loop, so `other` was never attempted. - assert_eq!(revocations.workspaces, [app]); - assert_eq!(revocations.withdrawn_runs(&pending), [run_app]); + assert_eq!(unregistration.revocations.revoked.len(), 1); + assert_eq!(unregistration.revocations.revoked[0].grant_id, grant); + assert!(matches!( + unregistration.removal, + Some(ControlError::LimitReached) + )); + assert!(scene.store.container_grants().is_empty()); + } else { + assert_eq!(unregistration.revocations.failures.len(), 1); + assert!(unregistration.removal.is_none()); } - assert!(Revocations::default().withdrawn_runs(&pending).is_empty()); +} + +/// Windows only, with a real grant on a temporary folder: an assignment that +/// cannot be recorded, because the journal reaches its event limit after the +/// grant, revokes that grant again, so no access outlives the failed consent. +#[cfg(windows)] +#[test] +fn an_assignment_that_cannot_be_recorded_revokes_its_grant() { + let mut scene = scene(); + let app = scene.register("app"); + scene.profile("rust", &["rust"]); + let plan = scene.store.plan_profile_access(app, "rust").expect("plan"); + assert_eq!(plan.to_grant().len(), 1, "{plan:?}"); + // With no grant and no skill recorded, the grant's request needs its + // event and the three a pending grant reserves, its outcome one more, and + // the assignment one beside the two an active grant reserves: 4,092 + // events leave room for the grant and none for the assignment. + let initial = scene.store.entries[0].clone(); + scene + .store + .entries + .resize(crate::control::MAX_EVENTS - 4, initial); + let revision = scene.store.revision(); + + let result = scene + .store + .assign_profile_with_access(app, "rust", &plan, revision); + + let left: Vec = scene + .store + .container_grants() + .iter() + .map(|status| status.grant().id()) + .collect(); + for grant in &left { + let _ = scene.store.revoke_container_grant(*grant); + } + assert!( + matches!(result, Err(ControlError::LimitReached)), + "{result:?}" + ); + assert!(left.is_empty(), "a grant outlived the failed assignment"); + assert!(scene.store.assigned_profiles(app).is_empty()); } diff --git a/crates/omgcode-core/src/control/container.rs b/crates/omgcode-core/src/control/container.rs index 1f226386..710aa29c 100644 --- a/crates/omgcode-core/src/control/container.rs +++ b/crates/omgcode-core/src/control/container.rs @@ -237,6 +237,24 @@ impl ControlStore { workspace_id: WorkspaceId, path: &Path, access: ContainerGrantAccess, + ) -> Uuid { + let id = self.test_record_pending_grant(workspace_id, path, access); + self.append( + Action::ContainerGrantApplied { grant_id: id }, + self.revision(), + ) + .expect("applied"); + id + } + + /// Record a requested grant whose access-control change was never + /// confirmed, so it stays `pending`, without changing any ACL. + #[cfg(test)] + pub(crate) fn test_record_pending_grant( + &mut self, + workspace_id: WorkspaceId, + path: &Path, + access: ContainerGrantAccess, ) -> Uuid { let grant = ContainerGrant { id: Uuid::new_v4(), @@ -253,11 +271,6 @@ impl ControlStore { let revision = self.next_revision().expect("revision"); self.append(Action::ContainerGrantRequested { grant }, revision) .expect("request"); - self.append( - Action::ContainerGrantApplied { grant_id: id }, - self.revision(), - ) - .expect("applied"); id } @@ -294,9 +307,30 @@ impl ControlStore { path: &Path, access: ContainerGrantAccess, expected_revision: u64, + ) -> Result { + self.grant_confirmed_container_access(workspace_id, path, None, access, expected_revision) + } + + /// As [`Self::grant_container_access`]. With `confirmed`, the directory + /// the operator confirmed, the grant is refused before anything is + /// recorded when the folder at `path` is no longer that directory, so the + /// access-control change, which is bound to the directory captured here, + /// reaches only the confirmed one. + pub(super) fn grant_confirmed_container_access( + &mut self, + workspace_id: WorkspaceId, + path: &Path, + confirmed: Option<&DirectoryRecord>, + access: ContainerGrantAccess, + expected_revision: u64, ) -> Result { self.check_revision(expected_revision)?; let directory = self.prepare_grant(workspace_id, path, access, &[])?; + if confirmed.is_some_and(|confirmed| !confirmed.same_directory(&directory)) { + return Err(ControlError::GrantRefused( + "a folder changed after its grant was confirmed; review the change again", + )); + } let name = container_name(workspace_id)?; let grant = ContainerGrant { id: Uuid::new_v4(), diff --git a/crates/omgcode-desktop/ui/src/mock/backend.ts b/crates/omgcode-desktop/ui/src/mock/backend.ts index 1ea949ed..3fcceff9 100644 --- a/crates/omgcode-desktop/ui/src/mock/backend.ts +++ b/crates/omgcode-desktop/ui/src/mock/backend.ts @@ -356,6 +356,9 @@ export function createMockBackend(now: () => number = Date.now): { invoke: Invok let savedPreferences: MockPreferences | null = null; let nextSkillFolder = 0; let mockFolders = 0; + // Grant identifiers come from this counter, never from the list's length, so a revoked + // grant's identifier is never reused (core gives each grant a new UUID). + let grantsMade = 0; /** The next sample folder a mock dialog "chooses". */ const nextMockFolder = (kind: string): string => { mockFolders += 1; @@ -1032,6 +1035,20 @@ export function createMockBackend(now: () => number = Date.now): { invoke: Invok instructions: "", instructions_max_bytes: 0, }); + // Like core on Windows (ADR-0107): registering grants the workspace's container read + // and write on its own folder. + if (settings.container_grants_supported) { + const registered = settings.workspaces[settings.workspaces.length - 1]; + if (registered !== undefined) { + settings.container_grants.push({ + grant_id: mockGrantId(), + workspace_id: registered.workspace_id, + directory: registered.folder_display, + access: "read_write", + state: "active", + }); + } + } }); case "settings_set_permissions": return changeSettings(args, () => { @@ -1927,7 +1944,8 @@ export function createMockBackend(now: () => number = Date.now): { invoke: Invok } function mockGrantId(): string { - return `00000000-0000-4000-8000-${String(settings.container_grants.length + 1).padStart(12, "0")}`; + grantsMade += 1; + return `00000000-0000-4000-8001-${String(grantsMade).padStart(12, "0")}`; } /** Records one active read-execute grant, as a confirmed grant ends up in core. */ diff --git a/crates/omgcode-desktop/ui/tests/settings_execution.test.ts b/crates/omgcode-desktop/ui/tests/settings_execution.test.ts index 758bc1a6..66a67433 100644 --- a/crates/omgcode-desktop/ui/tests/settings_execution.test.ts +++ b/crates/omgcode-desktop/ui/tests/settings_execution.test.ts @@ -469,6 +469,54 @@ describe("mock execution commands", () => { ).rejects.toMatchObject({ code: "control" }); }); + it("grants a registered workspace its folder and never reuses a revoked grant's identifier", async () => { + const { invoke } = createMockBackend(); + const before = await overviewOf(invoke); + const first = before.workspaces[0]?.workspace_id ?? ""; + const registered = (await invoke("settings_register_workspace", { + revision: before.revision, + })) as SettingsOverview; + const added = registered.workspaces[registered.workspaces.length - 1]; + expect(registered.container_grants).toEqual([ + expect.objectContaining({ + workspace_id: added?.workspace_id, + directory: added?.folder_display, + access: "read_write", + state: "active", + }), + ]); + const second = added?.workspace_id ?? ""; + + const change = async (command: string, workspace: string) => { + const { revision } = await overviewOf(invoke); + return (await invoke(command, { + revision, + workspace_id: workspace, + name: "rust", + })) as SettingsOverview; + }; + await change("settings_assign_toolchain_profile", first); + await change("settings_assign_toolchain_profile", second); + await change("settings_unassign_toolchain_profile", first); + const again = await change("settings_assign_toolchain_profile", first); + const ids = again.container_grants.map((grant) => grant.grant_id); + expect(new Set(ids).size).toBe(ids.length); + + const own = again.container_grants.find( + (grant) => grant.workspace_id === first && grant.access === "read_execute", + ); + const revoked = (await invoke("settings_revoke_container_grant", { + revision: again.revision, + grant_id: own?.grant_id, + })) as SettingsOverview; + expect( + revoked.container_grants.some( + (grant) => grant.workspace_id === second && grant.access === "read_execute", + ), + ).toBe(true); + expect(revoked.container_grants.some((grant) => grant.grant_id === own?.grant_id)).toBe(false); + }); + it("ends the assignments and their grants when an assigned profile is removed", async () => { const { invoke } = createMockBackend(); const before = await overviewOf(invoke); diff --git a/docs/adr/0107-assign-toolchain-profiles-to-workspaces-and-grant-on-assignment.md b/docs/adr/0107-assign-toolchain-profiles-to-workspaces-and-grant-on-assignment.md index f03b4427..e812d881 100644 --- a/docs/adr/0107-assign-toolchain-profiles-to-workspaces-and-grant-on-assignment.md +++ b/docs/adr/0107-assign-toolchain-profiles-to-workspaces-and-grant-on-assignment.md @@ -64,25 +64,38 @@ per-call approval of a command, which is a different decision. store's lock core plans again and refuses the assignment if the folders to grant changed, so no folder is granted that the operator did not see. Core then checks the batch against the grant limits, applies each grant, - and records the assignment last. A failed grant leaves the profile - unassigned; grants applied before it stay recorded, and one whose - access-control change failed stays `pending` until it is revoked. Off - Windows the plan is empty and assigning records only the event. + refusing a folder that is no longer the directory the operator confirmed, + and records the assignment last. When a grant fails, or the assignment + cannot be recorded, the profile stays unassigned and core revokes the + grants that call made that no assigned profile needs, so no access + outlives a consent that did not take effect; a grant whose revocation + fails stays recorded, `pending` or `revoking`, until it is revoked. A + workspace with a grant that is pending or being revoked is refused a plan, + because its runs are refused until that grant is settled. Off Windows the + plan is empty and assigning records only the event. 4. **Registering grants the workspace folder.** On Windows, registering a folder grants its container read-write on that folder when no grant of the workspace is recorded on it and this account can change the folder's access-control list. Registering an already registered folder that has no such grant grants it, which is how a workspace registered before this change gets it. A failed grant leaves the workspace registered and is - reported. + reported; a grant left `pending` is named, with how to revoke it and + register the folder again. 5. **Removing revokes what is no longer needed.** Unassigning a profile, and removing an assigned profile, revoke the workspace's read-execute grants on that profile's roots that no profile still assigned to the workspace - lists and that are not the workspace's package cache root. The workspace - folder's read-write grant is never revoked by these. Unregistering a - workspace revokes every grant of the workspace first and unregisters it - only when every revocation was confirmed; otherwise it stays registered - with the grants not yet revoked, and the operator retries. The + needs and that are not the workspace's package cache root. A profile still + assigned needs a grant on one of its roots, and a grant on a folder that + holds one of its roots that no other grant reaches: a root inside a + granted folder was readable when it was planned and got no grant of its + own. The workspace folder's read-write grant is never revoked by these. + Every grant is attempted even after one fails, and each grant not revoked + is reported. Unregistering a workspace revokes every grant of the + workspace first and unregisters it only when every revocation was + confirmed; otherwise it stays registered with the grants not yet revoked, + and the operator retries. A removal that cannot be recorded after every + grant was revoked also leaves it registered, and the revocations are still + returned so their runs are waited for. The unregistration primitive and replay still refuse while a grant exists ([ADR-0081](0081-unregister-a-workspace.md)). Any revocation still withdraws every run of its workspace, so each caller lists the pending diff --git a/docs/desktop-interface.md b/docs/desktop-interface.md index 2a630240..4636ab1d 100644 --- a/docs/desktop-interface.md +++ b/docs/desktop-interface.md @@ -1391,8 +1391,12 @@ waits. The window shows: cannot be revoked, the workspace stays registered with the grants not yet revoked, the runs the revocations withdrew are stopped and waited for, and the command fails with `container_access_failed` or - `revocation_incomplete`, saying to retry the grant's **Revoke** and remove - the workspace again. If that file cannot + `revocation_incomplete`, saying how many grants were not revoked, to retry + each one's **Revoke**, and to remove the workspace again; a grant revoked + whose AppContainer profile could not be deleted is reported apart, because + it is no longer listed. When every grant was revoked but the removal + cannot be recorded, the workspace stays registered and the command fails + with `revocation_incomplete` after the same wait. If that file cannot be deleted, the command still stops and waits for the runs the removal withdraws, then fails with `instructions_orphaned` (a run that was not stopped is reported first); no turn sends the file, because `chat_send` diff --git a/docs/execution.md b/docs/execution.md index 8b483b1b..9e8ead11 100644 --- a/docs/execution.md +++ b/docs/execution.md @@ -958,29 +958,43 @@ consent to give that workspace's sandbox the profile's folders. that already has a recorded grant of the workspace. Folders that only an administrator can grant, and folders whose access-control list could not be read, are listed apart and not granted. A root that is no longer the - recorded directory is listed as unknown. Off Windows the plan is empty. + recorded directory is listed as unknown. Off Windows the plan is empty. A + workspace with a container grant that is pending or being revoked is + refused a plan on every platform, because its runs are refused until that + grant is settled; revoke it first. - **Assigning:** under the store's lock core plans again and refuses the assignment when the folders to grant differ from the plan the operator confirmed. It then applies `check_container_grants` to the batch, grants - each folder read-execute through `grant_container_access`, and records the - assignment last. A failed grant leaves the profile unassigned; grants - applied before it stay recorded, and one whose access-control change failed - stays `pending` until it is revoked. `profile-assign` is itself the consent, + each folder read-execute through `grant_container_access`, refusing before + anything is recorded a folder that is no longer the directory the operator + confirmed, and records the assignment last. When a grant fails, or the + assignment cannot be recorded, the profile stays unassigned and core + revokes the grants this call made that no assigned profile needs, which + withdraws the workspace's runs; a grant whose revocation fails stays + recorded, `pending` or `revoking`, until it is revoked. `profile-assign` is itself the consent, so it plans and assigns in one call, and prints `assigned_profile_id`, `granted` (each `grant_id` with its folder), and `not_granted` with the reason. - **Unassigning and removing:** the change is recorded first. Then core revokes the workspace's read-execute grants whose folder is one of the - profile's roots, is not a root of a profile still assigned to the - workspace, and is not the workspace's package cache root. The workspace - folder's read-write grant is never revoked here. `profile-unassign` and - `profile-remove` print what they revoked under `revoked`; a failed - revocation leaves the change recorded, is reported, and - `container-revoke` retries it. + profile's roots, that no profile still assigned to the workspace needs, and + that are not on the workspace's package cache root. A profile still + assigned needs a grant on one of its roots, and a grant on a folder that + holds one of its roots when no other grant of the workspace is on that root + or above it: a root inside a granted folder was readable when it was + planned, so it got no grant of its own. A folder whose containment cannot + be read counts as not needing the grant. The workspace folder's read-write + grant is never revoked here. Every grant is attempted, even after one + fails. `profile-unassign` and `profile-remove` print what they revoked + under `revoked`; a failed revocation leaves the change recorded, each grant + not revoked is named with its `container-revoke` command, and a grant whose + AppContainer profile could not be deleted afterwards is named as revoked. - **Unregistering:** `workspace unregister` revokes every grant of the workspace first and unregisters it only when every revocation was confirmed; otherwise the workspace stays registered with the grants not yet - revoked. See [workspace settings](workspace-permissions.md#unregistering-a-workspace). + revoked, each named. When every grant was revoked but the removal cannot be + recorded, the workspace also stays registered, and the runs the + revocations withdrew are still waited for. See [workspace settings](workspace-permissions.md#unregistering-a-workspace). - **Runs:** each revocation withdraws every run of its workspace, as `container-revoke` does, so these commands stop and wait for those runs. - **Upgrading:** existing profiles start assigned to no workspace. Assign each diff --git a/docs/workspace-permissions.md b/docs/workspace-permissions.md index 1299eecc..78d7773a 100644 --- a/docs/workspace-permissions.md +++ b/docs/workspace-permissions.md @@ -230,10 +230,13 @@ withdrawn like any run whose workspace is no longer registered. Since ADR-0107 the command first revokes every container grant of the workspace, in any state, and lists them under `revoked`. It records -`workspace_unregistered` only when every revocation was confirmed. A failed -revocation leaves the workspace registered with the grants not yet revoked; -the command says so, and `workspace container-revoke` retries the grant before -the operator unregisters again. The event itself is still refused while any +`workspace_unregistered` only when every revocation was confirmed. Every +grant is attempted, even after one fails. A failed revocation leaves the +workspace registered with the grants not yet revoked; the command names each +one, and `workspace container-revoke` retries it before the operator +unregisters again. When every grant was revoked but the event cannot be +recorded, the workspace also stays registered, and the command still waits +for the runs the revocations withdrew. The event itself is still refused while any grant names the workspace (`grant refused`), so replay keeps ADR-0081's rule. An unknown workspace and a stale revision are refused as for any other settings change, before anything is revoked. Registering the same folder afterwards assigns a new From 60e0281c4487569644bb6113adaded0a524f2331 Mon Sep 17 00:00:00 2001 From: James Chapman Date: Fri, 27 Nov 2026 02:09:17 +0000 Subject: [PATCH 4/5] fix: release outer grants with their last profile and report rollback failures Core (ADR-0107): - Unassigning or removing a profile also considers the workspace's grants on a folder that holds one of its roots, so a grant kept for a nested root is released with the last profile inside it, whichever is unassigned first. The package cache root counts as a root that keeps a grant it relies on. - A failed assignment returns an `AssignmentFailure` with the revocations of the grants it made and released, instead of discarding a failed revocation. The rollback does not keep a grant for the cache root. CLI and desktop: - `profile-assign` names each grant a failed assignment could not revoke, with its `container-revoke` command; the desktop counts them. - When every failed revocation is an AppContainer profile that could not be deleted, the messages say every grant was revoked. Tests: - Core: the outer-first unassignment order, the cache root, and the returned rollback revocations; the failed-assignment tests match `AssignmentFailure`. - Unit tests for the CLI and desktop failure messages. - The cleanup `Drop` impls write to stderr without panicking. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 12 +- .../src/desktop/settings_changes.rs | 101 ++++++++-- .../src/desktop/settings_discovery.rs | 4 +- .../src/desktop/settings_execution.rs | 82 +++++++- crates/omgcode-app/tests/common/mod.rs | 5 +- crates/omgcode-cli/src/control_cli.rs | 175 ++++++++++++++++-- crates/omgcode-cli/tests/control_workflow.rs | 8 +- crates/omgcode-cli/tests/support/run_scene.rs | 7 +- crates/omgcode-core/src/control.rs | 4 +- crates/omgcode-core/src/control/assignment.rs | 109 +++++++---- .../src/control/assignment/tests.rs | 123 +++++++++++- ...s-to-workspaces-and-grant-on-assignment.md | 18 +- docs/desktop-interface.md | 7 +- docs/execution.md | 25 ++- docs/workspace-permissions.md | 2 +- 15 files changed, 571 insertions(+), 111 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 09bcb500..c7c65b93 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -614,16 +614,18 @@ Changes are recorded here before a release version is assigned. refuses the assignment if the plan changed, then applies the grants and records the assignment last, granting only a folder that is still the confirmed directory. An assignment whose grant fails, or that cannot be - recorded, revokes the grants it made that no assigned profile needs, and a + recorded, revokes the grants it made that no assigned profile needs and + reports each one it could not revoke, and a workspace with a pending or revoking grant is refused a plan. Folders that need an administrator, or whose access could not be read, are listed and not granted. Registering a workspace grants its container read-write on its folder, and registering an existing folder again grants it if that grant is missing. Unassigning or - removing a profile revokes the workspace's read-execute grants on its roots - that no other assigned profile needs, never the workspace folder's grant or - the package cache root's; a grant on a folder that holds a still-assigned - profile's root, which got no grant of its own, is kept. Every grant is + removing a profile revokes the workspace's read-execute grants on its roots, + or on a folder that holds one, that no other assigned profile and not the + package cache root needs, never the workspace folder's grant; a grant on a + folder that holds a still-assigned profile's root, which got no grant of + its own, is kept until that profile is unassigned too. Every grant is attempted, and each one not revoked is named. Unregistering revokes every grant of the workspace first and leaves it registered if a revocation fails or its removal cannot be recorded. Each caller waits only for the diff --git a/crates/omgcode-app/src/desktop/settings_changes.rs b/crates/omgcode-app/src/desktop/settings_changes.rs index 6c5b882f..e822c882 100644 --- a/crates/omgcode-app/src/desktop/settings_changes.rs +++ b/crates/omgcode-app/src/desktop/settings_changes.rs @@ -1595,25 +1595,33 @@ impl DesktopError { /// attempted. After a recorded change the change stands; after an /// unregistration the workspace stays registered. A grant revoked whose /// container profile could not be deleted is not listed for **Revoke**, - /// because it is gone. The operating system's own text is never shown. + /// because it is gone, and when no other grant failed the message says + /// every grant was revoked. The operating system's own text is never + /// shown. pub(super) fn revocation_incomplete( failures: &[(uuid::Uuid, ControlError)], change: RevokingChange, ) -> Self { - let mut message = match change { - RevokingChange::Recorded => { + let unrevoked: Vec<&ControlError> = failures + .iter() + .map(|(_, error)| error) + .filter(|error| !matches!(error, ControlError::ProfileRemoval(_))) + .collect(); + let mut message = match (change, unrevoked.is_empty()) { + (RevokingChange::Recorded, false) => { "The change was recorded, but not every container grant it releases was revoked." } - RevokingChange::Unregistration => { + (RevokingChange::Recorded, true) => { + "The change was recorded, and every container grant it releases was revoked." + } + (RevokingChange::Unregistration, false) => { "The workspace stays registered, because not every container grant of it was revoked." } + (RevokingChange::Unregistration, true) => { + "The workspace stays registered: every container grant of it was revoked, but its removal was not attempted." + } } .to_owned(); - let unrevoked: Vec<&ControlError> = failures - .iter() - .map(|(_, error)| error) - .filter(|error| !matches!(error, ControlError::ProfileRemoval(_))) - .collect(); let access = unrevoked .iter() .any(|error| matches!(error, ControlError::Container(_))); @@ -1636,9 +1644,11 @@ impl DesktopError { message.push_str(" The settings list each one, and Revoke tries again."); } if unrevoked.len() < failures.len() { - message.push_str( - " A grant was revoked, but the workspace's AppContainer profile could not be deleted; it holds no access now.", - ); + message.push_str(if unrevoked.is_empty() { + " The workspace's AppContainer profile could not be deleted afterwards; it holds no access now." + } else { + " A grant was revoked, but the workspace's AppContainer profile could not be deleted; it holds no access now." + }); } if change == RevokingChange::Unregistration { message.push_str(if unrevoked.is_empty() { @@ -1747,6 +1757,73 @@ mod tests { ); } + fn removal_failed() -> ControlError { + ControlError::ProfileRemoval(std::io::Error::other("operating system text")) + } + + /// A grant revoked whose AppContainer profile could not be deleted is + /// not reported as a grant left to revoke. + #[test] + fn a_failed_profile_deletion_alone_says_every_grant_was_revoked() { + let failures = [(uuid::Uuid::new_v4(), removal_failed())]; + for (change, lead) in [ + ( + RevokingChange::Recorded, + "The change was recorded, and every container grant it releases was revoked.", + ), + ( + RevokingChange::Unregistration, + "The workspace stays registered: every container grant of it was revoked", + ), + ] { + let error = DesktopError::revocation_incomplete(&failures, change); + let message = error.message(); + assert_eq!(error.code(), "revocation_incomplete"); + assert!(message.starts_with(lead), "{message}"); + assert!(message.contains("could not be deleted"), "{message}"); + assert!(!message.contains("not revoked"), "{message}"); + assert!(!message.contains("Revoke tries again"), "{message}"); + assert!(!message.contains("operating system text"), "{message}"); + assert_eq!( + message.ends_with(" Remove the workspace again."), + change == RevokingChange::Unregistration, + "{message}" + ); + } + } + + /// A grant left revoking is still reported beside one whose profile + /// could not be deleted. + #[test] + fn a_grant_left_revoking_is_reported_beside_a_failed_profile_deletion() { + let failures = [ + (uuid::Uuid::new_v4(), removal_failed()), + ( + uuid::Uuid::new_v4(), + ControlError::Container(std::io::Error::other("operating system text")), + ), + ]; + let error = DesktopError::revocation_incomplete(&failures, RevokingChange::Unregistration); + let message = error.message(); + assert_eq!(error.code(), "container_access_failed"); + assert!( + message.starts_with( + "The workspace stays registered, because not every container grant of it was revoked." + ), + "{message}" + ); + assert!( + message.contains(" 1 grant(s) could not be removed"), + "{message}" + ); + assert!(message.contains("A grant was revoked, but"), "{message}"); + assert!( + message.ends_with(" Then remove the workspace again."), + "{message}" + ); + assert!(!message.contains("operating system text"), "{message}"); + } + #[test] fn the_guard_admits_one_change_and_clears_on_drop() { let flag = AtomicBool::new(false); diff --git a/crates/omgcode-app/src/desktop/settings_discovery.rs b/crates/omgcode-app/src/desktop/settings_discovery.rs index f3ebb161..507a3cdf 100644 --- a/crates/omgcode-app/src/desktop/settings_discovery.rs +++ b/crates/omgcode-app/src/desktop/settings_discovery.rs @@ -508,7 +508,7 @@ impl DesktopService { } if let Some((workspace_id, _, plan)) = &assign { let names: Vec<&str> = chosen.iter().map(ToolchainProposal::name).collect(); - if let Err(error) = + if let Err(failure) = store.assign_profiles_with_access(*workspace_id, &names, plan, expected) { // Assignments recorded before the failure stand. @@ -522,7 +522,7 @@ impl DesktopService { return Err(DesktopError::not_assigned( chosen.len(), assigned, - &DesktopError::from_grant(&error), + &DesktopError::assignment_failed(&failure), )); } } diff --git a/crates/omgcode-app/src/desktop/settings_execution.rs b/crates/omgcode-app/src/desktop/settings_execution.rs index 4f2253ab..2ddedc7d 100644 --- a/crates/omgcode-app/src/desktop/settings_execution.rs +++ b/crates/omgcode-app/src/desktop/settings_execution.rs @@ -40,11 +40,11 @@ use std::path::PathBuf; use omgcode_core::control::{ - CONTAINER_GRANTS_SUPPORTED, ContainerGrantAccess, ControlError, ControlStore, CredentialStore, - MAX_PACKAGE_ORIGIN_BYTES, MAX_PACKAGE_ORIGINS, MAX_PROFILE_PATH_ENTRIES, MAX_PROFILE_ROOTS, - MAX_PROFILE_VARIABLES, MAX_VARIABLE_NAME_BYTES, MAX_VARIABLE_VALUE_BYTES, - PackageProfileDeclaration, PlannedFolder, ProfileAccessPlan, ProfileDeclaration, - delete_unbound_credential, parse_origin, + AssignmentFailure, CONTAINER_GRANTS_SUPPORTED, ContainerGrantAccess, ControlError, + ControlStore, CredentialStore, MAX_PACKAGE_ORIGIN_BYTES, MAX_PACKAGE_ORIGINS, + MAX_PROFILE_PATH_ENTRIES, MAX_PROFILE_ROOTS, MAX_PROFILE_VARIABLES, MAX_VARIABLE_NAME_BYTES, + MAX_VARIABLE_VALUE_BYTES, PackageProfileDeclaration, PlannedFolder, ProfileAccessPlan, + ProfileDeclaration, delete_unbound_credential, parse_origin, }; use omgcode_core::run; use omgcode_core::turn::display_safe_line; @@ -209,6 +209,31 @@ impl DesktopError { } } + /// An assignment that failed, as [`Self::from_grant`] reports its cause, + /// with the count of grants it made that could not be revoked afterwards; + /// the settings list each one, and **Revoke** tries again. A grant revoked + /// whose AppContainer profile alone could not be deleted holds no access + /// and is not counted. + pub(super) fn assignment_failed(failure: &AssignmentFailure) -> Self { + let cause = Self::from_grant(&failure.error); + let left = failure + .released + .failures + .iter() + .filter(|(_, error)| !matches!(error, ControlError::ProfileRemoval(_))) + .count(); + if left == 0 { + return cause; + } + Self::execution( + cause.code(), + format!( + "{}. {left} container grant(s) the failed assignment made could not be revoked; the settings list each one, and Revoke tries again.", + cause.message().trim_end_matches('.') + ), + ) + } + /// The package profile was removed, but credentials bound to it were not /// all deleted from the native store. fn package_credentials_orphaned(count: usize) -> Self { @@ -647,7 +672,7 @@ impl DesktopService { let mut store = self.inner.open_or_create_control()?; store .assign_profile_with_access(workspace_id, &request.name, &plan, request.revision) - .map_err(|error| DesktopError::from_grant(&error))?; + .map_err(|failure| DesktopError::assignment_failed(&failure))?; Ok(overview_of(&self.inner, store)) } @@ -995,6 +1020,51 @@ impl DesktopService { #[cfg(test)] mod tests { use super::*; + use omgcode_core::control::Revocations; + + fn failure(error: ControlError, failures: Vec<(Uuid, ControlError)>) -> AssignmentFailure { + AssignmentFailure { + error, + released: Revocations { + failures, + ..Revocations::default() + }, + } + } + + /// A failed assignment that left no grant reports its cause as a grant + /// failure does; one that left grants also counts them, without the + /// operating system's text, and a grant whose profile alone could not + /// be deleted is not counted. + #[test] + fn a_failed_assignment_counts_the_grants_it_left() { + let os = || std::io::Error::other("operating system text"); + let alone = DesktopError::assignment_failed(&failure( + ControlError::LimitReached, + vec![(Uuid::new_v4(), ControlError::ProfileRemoval(os()))], + )); + let cause = DesktopError::from_grant(&ControlError::LimitReached); + assert_eq!(alone.code(), cause.code()); + assert_eq!(alone.message(), cause.message()); + + let left = DesktopError::assignment_failed(&failure( + ControlError::Container(os()), + vec![ + (Uuid::new_v4(), ControlError::Container(os())), + (Uuid::new_v4(), ControlError::ProfileRemoval(os())), + ], + )); + assert_eq!(left.code(), "container_access_failed"); + let message = left.message(); + assert!( + message.contains( + " 1 container grant(s) the failed assignment made could not be revoked; the settings list each one, and Revoke tries again." + ), + "{message}" + ); + assert!(!message.contains(".."), "{message}"); + assert!(!message.contains("operating system text"), "{message}"); + } #[test] fn the_grant_and_revoke_confirmations_name_everything_they_change() { diff --git a/crates/omgcode-app/tests/common/mod.rs b/crates/omgcode-app/tests/common/mod.rs index 49046f01..2297003d 100644 --- a/crates/omgcode-app/tests/common/mod.rs +++ b/crates/omgcode-app/tests/common/mod.rs @@ -531,8 +531,9 @@ pub struct Fixture { impl Drop for Fixture { fn drop(&mut self) { if let Err(problem) = self.revoke_grants() { - // Never panic in drop: a second panic would abort the run. - eprintln!("fixture cleanup: {problem}"); + // Never panic in drop: a second panic would abort the run. A + // failed write to stderr is ignored, so the report is lost then. + let _ = writeln!(std::io::stderr(), "fixture cleanup: {problem}"); } } } diff --git a/crates/omgcode-cli/src/control_cli.rs b/crates/omgcode-cli/src/control_cli.rs index a86ecbd0..b20e60e1 100644 --- a/crates/omgcode-cli/src/control_cli.rs +++ b/crates/omgcode-cli/src/control_cli.rs @@ -4,8 +4,9 @@ use clap::{Args, Subcommand, ValueEnum}; use omgcode_core::control::{ - ContainerGrantAccess, ContainerGrantState, ControlError, ControlStore, CredentialId, - PackageProfileDeclaration, ProfileDeclaration, ProviderProfileDeclaration, Revocations, + AssignmentFailure, ContainerGrantAccess, ContainerGrantState, ControlError, ControlStore, + CredentialId, PackageProfileDeclaration, ProfileDeclaration, ProviderProfileDeclaration, + Revocations, }; use omgcode_core::policy::{ Access, Operation, PermissionSet, PolicyRequest, WorkspaceId, WriteTool, @@ -925,7 +926,7 @@ fn profile_assign( .map_err(control_error)?; let assignment = store .assign_profile_with_access(workspace_id, name, &plan, revision) - .map_err(control_error)?; + .map_err(assignment_failed)?; let not_granted: Vec<_> = assignment .plan .needs_administrator() @@ -951,6 +952,51 @@ fn profile_assign( })) } +/// The error of a failed assignment, naming each grant it made that could +/// not be revoked afterwards, with the command that retries it. +fn assignment_failed(failure: AssignmentFailure) -> CliError { + let mut error = control_error(failure.error); + let failures = &failure.released.failures; + if !failures.is_empty() { + if !error.message.ends_with('.') { + error.message.push('.'); + } + error.message.push_str(if all_revoked(failures) { + " The profile was not assigned, and every container grant the assignment made was revoked." + } else { + " The profile was not assigned, but not every container grant the assignment made was revoked." + }); + error.message.push_str(&unrevoked_grants(failures)); + } + error +} + +/// Whether every failure is a grant revoked whose AppContainer profile alone +/// could not be deleted, so no grant keeps its access. +fn all_revoked(failures: &[(Uuid, ControlError)]) -> bool { + failures + .iter() + .all(|(_, error)| matches!(error, ControlError::ProfileRemoval(_))) +} + +/// One sentence per failed revocation: a grant not revoked, with the command +/// that retries it, or a grant revoked whose profile could not be deleted. +fn unrevoked_grants(failures: &[(Uuid, ControlError)]) -> String { + let mut text = String::new(); + for (grant, error) in failures { + if matches!(error, ControlError::ProfileRemoval(_)) { + // The grant is revoked; only the container's profile, which + // holds no grant now, could not be deleted. + text.push_str(&format!(" Grant {grant}: {error}.")); + } else { + text.push_str(&format!( + " Grant {grant} could not be revoked: {error}; retry with `workspace container-revoke {grant}`." + )); + } + } + text +} + /// The change [`finish_revocations`] reports on. #[derive(Clone, Copy)] enum RevokingChange<'a> { @@ -989,27 +1035,29 @@ fn finish_revocations( let mut kind = "run"; if !revocations.failures.is_empty() { kind = "control"; - let mut message = match change { - RevokingChange::Recorded => { - "The change was recorded, but not every container grant it releases was revoked.".to_owned() + let revoked = all_revoked(&revocations.failures); + let mut message = match (change, revoked) { + (RevokingChange::Recorded, false) => { + "The change was recorded, but not every container grant it releases was revoked." } - RevokingChange::Unregistration(_) => { - "The workspace stays registered, because not every container grant of it was revoked.".to_owned() + (RevokingChange::Recorded, true) => { + "The change was recorded, and every container grant it releases was revoked." } - }; - for (grant, error) in &revocations.failures { - if matches!(error, ControlError::ProfileRemoval(_)) { - // The grant is revoked; only the container's profile, which - // holds no grant now, could not be deleted. - message.push_str(&format!(" Grant {grant}: {error}.")); - } else { - message.push_str(&format!( - " Grant {grant} could not be revoked: {error}; retry with `workspace container-revoke {grant}`." - )); + (RevokingChange::Unregistration(_), false) => { + "The workspace stays registered, because not every container grant of it was revoked." + } + (RevokingChange::Unregistration(_), true) => { + "The workspace stays registered: every container grant of it was revoked, but its removal was not attempted." } } + .to_owned(); + message.push_str(&unrevoked_grants(&revocations.failures)); if matches!(change, RevokingChange::Unregistration(_)) { - message.push_str(" Then unregister it again."); + message.push_str(if revoked { + " Unregister it again." + } else { + " Then unregister it again." + }); } problems.insert(0, message); } else if let RevokingChange::Unregistration(Some(error)) = change { @@ -1266,3 +1314,92 @@ fn parse_workspace_id(value: &str) -> Result { pub(crate) fn control_error(error: ControlError) -> CliError { CliError::new("control", error.to_string()) } + +#[cfg(test)] +mod tests { + use super::*; + use std::io; + + fn failure(released: Vec<(Uuid, ControlError)>) -> AssignmentFailure { + AssignmentFailure { + error: ControlError::LimitReached, + released: Revocations { + failures: released, + ..Revocations::default() + }, + } + } + + /// A failed assignment whose grants were all revoked reports only its + /// cause. + #[test] + fn a_failed_assignment_with_nothing_left_reports_its_cause() { + let error = assignment_failed(failure(Vec::new())); + assert_eq!(error.code, "control"); + assert_eq!(error.message, "control journal capacity reached"); + } + + /// A grant a failed assignment could not revoke is named with the + /// command that retries it; one whose profile alone could not be deleted + /// is named as revoked. + #[test] + fn a_failed_assignment_names_each_grant_it_left() { + let (left, removed) = (Uuid::new_v4(), Uuid::new_v4()); + let error = assignment_failed(failure(vec![ + (left, ControlError::Container(io::Error::other("denied"))), + ( + removed, + ControlError::ProfileRemoval(io::Error::other("busy")), + ), + ])); + assert!( + error.message.starts_with( + "control journal capacity reached. The profile was not assigned, but not every container grant the assignment made was revoked." + ), + "{}", + error.message + ); + assert!( + error.message.contains(&format!( + "Grant {left} could not be revoked: container access change failed: denied; retry with `workspace container-revoke {left}`." + )), + "{}", + error.message + ); + assert!( + error.message.contains(&format!( + "Grant {removed}: the grant was revoked, but the container profile could not be deleted: busy." + )), + "{}", + error.message + ); + } + + /// When every failure is a profile that could not be deleted, the + /// message says every grant was revoked. + #[test] + fn a_failed_profile_deletion_alone_says_every_grant_was_revoked() { + let failures = vec![( + Uuid::new_v4(), + ControlError::ProfileRemoval(io::Error::other("busy")), + )]; + assert!(all_revoked(&failures)); + let error = assignment_failed(failure(failures)); + assert!( + error + .message + .contains("every container grant the assignment made was revoked."), + "{}", + error.message + ); + assert!( + !error.message.contains("container-revoke"), + "{}", + error.message + ); + assert!(!all_revoked(&[( + Uuid::new_v4(), + ControlError::Container(io::Error::other("denied")), + )])); + } +} diff --git a/crates/omgcode-cli/tests/control_workflow.rs b/crates/omgcode-cli/tests/control_workflow.rs index d63645f6..fcf6ec0f 100644 --- a/crates/omgcode-cli/tests/control_workflow.rs +++ b/crates/omgcode-cli/tests/control_workflow.rs @@ -936,9 +936,13 @@ impl Drop for RevokeGrantsOnDrop<'_> { fn drop(&mut self) { // The helpers report a failed status read, a timeout, and a failed // revocation instead of panicking, which would abort a run that is - // already unwinding, and every grant is attempted. + // already unwinding, and every grant is attempted. A failed write to + // stderr is ignored, so that report is lost then. for problem in revoke_recorded_grants(self.0) { - eprintln!("grant revocation failed during cleanup: {problem}"); + let _ = writeln!( + io::stderr(), + "grant revocation failed during cleanup: {problem}" + ); } } } diff --git a/crates/omgcode-cli/tests/support/run_scene.rs b/crates/omgcode-cli/tests/support/run_scene.rs index 967d59d2..f0516ed7 100644 --- a/crates/omgcode-cli/tests/support/run_scene.rs +++ b/crates/omgcode-cli/tests/support/run_scene.rs @@ -2,6 +2,7 @@ use serde_json::Value; use std::fs; +use std::io::{self, Write}; use std::path::{Path, PathBuf}; use std::process::{Command, Output, Stdio}; use std::thread; @@ -420,8 +421,12 @@ pub(crate) fn run_command(data_root: &Path, args: &[&str]) -> Command { impl Drop for Scene { fn drop(&mut self) { // Fallback for a test that failed before `close`; it must not panic. + // A failed write to stderr is ignored, so that report is lost then. for failure in self.revoke_grants() { - eprintln!("grant revocation failed during cleanup: {failure}"); + let _ = writeln!( + io::stderr(), + "grant revocation failed during cleanup: {failure}" + ); } } } diff --git a/crates/omgcode-core/src/control.rs b/crates/omgcode-core/src/control.rs index baf87222..c5f1e46b 100644 --- a/crates/omgcode-core/src/control.rs +++ b/crates/omgcode-core/src/control.rs @@ -41,8 +41,8 @@ pub use approval::{ }; pub use assignment::{ - PlannedFolder, ProfileAccessPlan, ProfileAssignment, RegisteredWorkspace, Revocations, - Unregistration, + AssignmentFailure, PlannedFolder, ProfileAccessPlan, ProfileAssignment, RegisteredWorkspace, + Revocations, Unregistration, }; pub use container::{ ContainerGrant, ContainerGrantAccess, ContainerGrantState, ContainerGrantStatus, diff --git a/crates/omgcode-core/src/control/assignment.rs b/crates/omgcode-core/src/control/assignment.rs index bc8e13de..ea5b7948 100644 --- a/crates/omgcode-core/src/control/assignment.rs +++ b/crates/omgcode-core/src/control/assignment.rs @@ -154,6 +154,30 @@ pub struct Revocations { pub workspaces: Vec, } +/// Why [`ControlStore::assign_profiles_with_access`] failed, and what it +/// undid. The profiles it did not record stay unassigned. +#[derive(Debug)] +pub struct AssignmentFailure { + /// The refusal or failure that stopped the assignment. + pub error: ControlError, + /// The revocations of the grants the call made that no assigned profile + /// needs. A grant in [`Revocations::failures`] other than a + /// [`ControlError::ProfileRemoval`] stays recorded, `pending` or + /// `revoking`, with its access, until the operator revokes it. Each + /// revocation withdrew the runs of its workspace. + pub released: Revocations, +} + +impl From for AssignmentFailure { + /// A failure before any grant was made, so nothing was undone. + fn from(error: ControlError) -> Self { + Self { + error, + released: Revocations::default(), + } + } +} + /// What [`ControlStore::unregister_workspace_with_access`] did. #[derive(Debug)] pub struct Unregistration { @@ -362,18 +386,20 @@ impl ControlStore { /// /// What [`Self::assign_profile`] refuses; a changed plan; a folder core's /// grant rules refuse, before anything is recorded; the first grant that - /// fails; and an assignment that cannot be recorded. After a failure the - /// profile is not assigned, and the grants this call made that no - /// assigned profile needs are revoked, which withdraws the workspace's - /// runs. A grant whose revocation fails then stays recorded, `pending` - /// or `revoking`, until it is revoked. + /// fails; and an assignment that cannot be recorded, each in + /// [`AssignmentFailure::error`]. After a failure the profile is not + /// assigned, and the grants this call made that no assigned profile needs + /// are revoked, which withdraws the workspace's runs; those revocations + /// are returned in [`AssignmentFailure::released`]. A grant whose + /// revocation fails then stays recorded, `pending` or `revoking`, until + /// it is revoked. pub fn assign_profile_with_access( &mut self, workspace_id: WorkspaceId, name: &str, confirmed: &ProfileAccessPlan, expected_revision: u64, - ) -> Result { + ) -> Result { self.assign_profiles_with_access(workspace_id, &[name], confirmed, expected_revision) } @@ -394,13 +420,14 @@ impl ControlStore { names: &[&str], confirmed: &ProfileAccessPlan, expected_revision: u64, - ) -> Result { + ) -> Result { self.check_revision(expected_revision)?; let plan = self.plan_profiles_access(workspace_id, names)?; if plan.grant != confirmed.grant { return Err(ControlError::ProfileRefused( "the folders this assignment grants changed; review it again", - )); + ) + .into()); } self.check_container_grants( workspace_id, @@ -429,8 +456,8 @@ impl ControlStore { .as_ref() .and_then(|record| self.workspace_grant_on(workspace_id, record)), ); - self.release_unneeded(workspace_id, &made); - return Err(error); + let released = self.release_unneeded(workspace_id, &made); + return Err(AssignmentFailure { error, released }); } } } @@ -443,8 +470,8 @@ impl ControlStore { // assignment, so a grant no recorded assignment needs // does not outlive it. let made: Vec = granted.iter().map(ContainerGrant::id).collect(); - self.release_unneeded(workspace_id, &made); - return Err(error); + let released = self.release_unneeded(workspace_id, &made); + return Err(AssignmentFailure { error, released }); } } } @@ -456,10 +483,11 @@ impl ControlStore { } /// Record the unassignment, then revoke the workspace's read-execute - /// grants on the profile's roots that no profile still assigned to it - /// lists and that are not its package cache root. The workspace folder's - /// read-write grant is never revoked here. Revocations need no revision; - /// each withdraws every run of the workspace. + /// grants on the profile's roots, or on folders that hold them, that + /// neither a profile still assigned to it nor its package cache root + /// needs. The workspace folder's read-write grant is never revoked here. + /// Revocations need no revision; each withdraws every run of the + /// workspace. /// /// # Errors /// @@ -775,20 +803,17 @@ impl ControlStore { } /// The workspace's read-execute grants on `roots`, the roots of the - /// profile `leaving`, that no other profile assigned to it needs and that - /// are not its package cache root. + /// profile `leaving`, or on a folder that holds one of them, that no other + /// profile assigned to it and not its package cache root needs. A grant on + /// an outer folder kept for a nested root while its own profile was + /// unassigned is released with the last profile inside it. A folder whose + /// containment cannot be read is not a candidate. fn unneeded_root_grants( &self, workspace_id: WorkspaceId, leaving: Uuid, roots: &[DirectoryRecord], ) -> Vec { - let cache = self - .snapshot - .package_cache_roots - .iter() - .find(|status| status.workspace_id == workspace_id) - .map(|status| &status.directory); let candidates: Vec<&ContainerGrant> = self .container_grants() .iter() @@ -797,30 +822,36 @@ impl ControlStore { let directory = grant.directory(); grant.workspace_id() == workspace_id && grant.access() == ContainerGrantAccess::ReadExecute - && roots.iter().any(|root| root.same_directory(directory)) - && cache.is_none_or(|cache| !cache.same_directory(directory)) + && roots.iter().any(|root| { + root.same_directory(directory) || directory.contains(root).unwrap_or(false) + }) }) .collect(); let releasing: Vec = candidates.iter().map(|grant| grant.id()).collect(); + let cache = self.package_cache_root(workspace_id); candidates .into_iter() - .filter(|grant| !self.grant_needed(workspace_id, grant, Some(leaving), &releasing)) + .filter(|grant| { + !self.grant_needed(workspace_id, grant, Some(leaving), &releasing, cache) + }) .map(ContainerGrant::id) .collect() } /// Whether a root of a profile assigned to `workspace_id`, other than - /// `leaving`, relies on `grant`: the root is the grant's folder, or lies - /// beneath it and no grant of the workspace outside `releasing` is on the - /// root or above it. A root inside another profile's root was readable - /// when it was planned, so it was given no grant of its own. A folder - /// whose containment cannot be read counts as not relying on the grant. + /// `leaving`, or the folder `cache`, relies on `grant`: the root is the + /// grant's folder, or lies beneath it and no grant of the workspace + /// outside `releasing` is on the root or above it. A root inside another + /// profile's root was readable when it was planned, so it was given no + /// grant of its own. A folder whose containment cannot be read counts as + /// not relying on the grant. fn grant_needed( &self, workspace_id: WorkspaceId, grant: &ContainerGrant, leaving: Option, releasing: &[Uuid], + cache: Option<&DirectoryRecord>, ) -> bool { let directory = grant.directory(); let kept: Vec<&DirectoryRecord> = self @@ -843,6 +874,7 @@ impl ControlStore { .find(|status| status.profile().id() == *id) }) .flat_map(|status| status.profile().read_only_roots()) + .chain(cache) .any(|root| { root.same_directory(directory) || (directory.contains(root).unwrap_or(false) @@ -853,9 +885,12 @@ impl ControlStore { } /// Revoke the grants in `made`, made by an assignment that then failed, - /// that no profile assigned to the workspace needs. A revocation that - /// fails leaves its grant recorded, as any failed revocation does. - fn release_unneeded(&mut self, workspace_id: WorkspaceId, made: &[Uuid]) { + /// that no profile assigned to the workspace needs, and return those + /// revocations. The package cache root does not keep one: it did not rely + /// on a grant that did not exist before. A revocation that fails leaves + /// its grant recorded, as any failed revocation does, and is returned for + /// the caller to report. + fn release_unneeded(&mut self, workspace_id: WorkspaceId, made: &[Uuid]) -> Revocations { let unneeded: Vec = made .iter() .filter(|id| { @@ -863,11 +898,11 @@ impl ControlStore { .iter() .map(ContainerGrantStatus::grant) .find(|grant| grant.id() == **id) - .is_some_and(|grant| !self.grant_needed(workspace_id, grant, None, made)) + .is_some_and(|grant| !self.grant_needed(workspace_id, grant, None, made, None)) }) .copied() .collect(); - let _ = self.revoke_each(&unneeded); + self.revoke_each(&unneeded) } /// Revoke each grant in order, attempting every one. diff --git a/crates/omgcode-core/src/control/assignment/tests.rs b/crates/omgcode-core/src/control/assignment/tests.rs index 8b646580..3ef8f1dd 100644 --- a/crates/omgcode-core/src/control/assignment/tests.rs +++ b/crates/omgcode-core/src/control/assignment/tests.rs @@ -326,7 +326,13 @@ fn an_assignment_applies_only_the_confirmed_plan() { .assign_profile_with_access(app, "rust", &confirmed, revision); if CONTAINER_GRANTS_SUPPORTED { assert!( - matches!(result, Err(ControlError::ProfileRefused(_))), + matches!( + &result, + Err(AssignmentFailure { + error: ControlError::ProfileRefused(_), + released, + }) if released.workspaces.is_empty() + ), "{result:?}" ); assert_eq!(scene.store.revision(), revision); @@ -505,6 +511,54 @@ fn a_grant_a_nested_root_relies_on_is_kept() { assert_eq!(released(&scene.store), [sdk]); } +/// When the outer profile is unassigned first, its grant is kept for the +/// nested root; unassigning or removing the inner profile then releases it, +/// so the grant does not outlive both assignments. A package cache root +/// inside the outer folder keeps the grant until the cache has its own. +#[test] +fn an_outer_grant_kept_for_a_nested_root_is_released_with_it() { + let mut scene = scene(); + let app = scene.register("app"); + scene.profile("outer", &["sdk"]); + scene.profile("inner", &["sdk/bin"]); + scene.assign(app, "outer").expect("assign outer"); + scene.assign(app, "inner").expect("assign inner"); + let read = ContainerGrantAccess::ReadExecute; + let sdk = scene + .store + .test_record_grant(app, &scene.outside.join("sdk"), read); + let revision = scene.store.revision(); + scene + .store + .unassign_profile(app, "outer", revision) + .expect("unassign outer"); + let released = |store: &ControlStore| { + store + .grants_released_by_unassignment(app, "inner") + .expect("preview") + }; + + assert_eq!(released(&scene.store), [sdk]); + assert_eq!( + scene + .store + .grants_released_by_removal("inner") + .expect("removal preview"), + [(app, vec![sdk])] + ); + + let cache = scene.outside.join("sdk/cache"); + fs::create_dir_all(&cache).expect("cache folder"); + let revision = scene.store.revision(); + scene + .store + .set_package_cache_root(app, &cache, revision) + .expect("cache root"); + assert!(released(&scene.store).is_empty()); + scene.store.test_record_grant(app, &cache, read); + assert_eq!(released(&scene.store), [sdk]); +} + /// A workspace whose container grant is pending, or being revoked, is refused /// a plan, because its runs are refused until that grant is settled. Another /// workspace is not affected. @@ -538,7 +592,10 @@ fn a_pending_grant_refuses_an_assignment_plan() { &ProfileAccessPlan::default(), revision ), - Err(ControlError::GrantRefused(_)) + Err(AssignmentFailure { + error: ControlError::GrantRefused(_), + .. + }) )); assert!(scene.store.assigned_profiles(app).is_empty()); scene @@ -668,10 +725,68 @@ fn an_assignment_that_cannot_be_recorded_revokes_its_grant() { for grant in &left { let _ = scene.store.revoke_container_grant(*grant); } + let failure = result.expect_err("the assignment cannot be recorded"); assert!( - matches!(result, Err(ControlError::LimitReached)), - "{result:?}" + matches!(failure.error, ControlError::LimitReached), + "{failure:?}" ); + // The grant it made is revoked and named, with its workspace. + assert_eq!(failure.released.revoked.len(), 1, "{failure:?}"); + assert!(failure.released.failures.is_empty(), "{failure:?}"); + assert_eq!(failure.released.workspaces, [app]); assert!(left.is_empty(), "a grant outlived the failed assignment"); assert!(scene.store.assigned_profiles(app).is_empty()); } + +/// A failed assignment's release returns each revocation it attempted, and +/// a revocation that fails is returned rather than dropped; a grant a +/// still-assigned profile needs is not attempted, and a package cache root +/// inside a grant it made does not keep that grant. On Windows the recorded +/// grant has no real access-control entry and is revoked; elsewhere its +/// revocation fails and is reported with its grant. +#[test] +fn a_failed_assignment_returns_the_grants_it_could_not_release() { + let mut scene = scene(); + let app = scene.register("app"); + scene.profile("kept", &["kept"]); + scene.assign(app, "kept").expect("assign kept"); + let read = ContainerGrantAccess::ReadExecute; + let needed = scene + .store + .test_record_grant(app, &scene.outside.join("kept"), read); + let path = scene.outside.join("made"); + let cache = path.join("cache"); + fs::create_dir_all(&cache).expect("grant folder"); + let made = scene.store.test_record_grant(app, &path, read); + let revision = scene.store.revision(); + scene + .store + .set_package_cache_root(app, &cache, revision) + .expect("cache root"); + + let released = scene.store.release_unneeded(app, &[needed, made]); + + assert_eq!(released.workspaces, [app]); + if CONTAINER_GRANTS_SUPPORTED { + assert!(released.failures.is_empty(), "{:?}", released.failures); + assert_eq!(released.revoked.len(), 1); + } else { + assert!(released.revoked.is_empty()); + assert!( + matches!( + released.failures.as_slice(), + [(grant, ControlError::Container(_))] if *grant == made + ), + "{:?}", + released.failures + ); + } + assert!( + scene + .store + .container_grants() + .iter() + .any(|status| status.grant().id() == needed), + "a grant a profile still needs is kept" + ); +} diff --git a/docs/adr/0107-assign-toolchain-profiles-to-workspaces-and-grant-on-assignment.md b/docs/adr/0107-assign-toolchain-profiles-to-workspaces-and-grant-on-assignment.md index e812d881..7d095ba3 100644 --- a/docs/adr/0107-assign-toolchain-profiles-to-workspaces-and-grant-on-assignment.md +++ b/docs/adr/0107-assign-toolchain-profiles-to-workspaces-and-grant-on-assignment.md @@ -69,7 +69,9 @@ per-call approval of a command, which is a different decision. cannot be recorded, the profile stays unassigned and core revokes the grants that call made that no assigned profile needs, so no access outlives a consent that did not take effect; a grant whose revocation - fails stays recorded, `pending` or `revoking`, until it is revoked. A + fails stays recorded, `pending` or `revoking`, until it is revoked, and + the failure returns those revocations so the operator is told which + grants are left. A workspace with a grant that is pending or being revoked is refused a plan, because its runs are refused until that grant is settled. Off Windows the plan is empty and assigning records only the event. @@ -83,12 +85,14 @@ per-call approval of a command, which is a different decision. register the folder again. 5. **Removing revokes what is no longer needed.** Unassigning a profile, and removing an assigned profile, revoke the workspace's read-execute grants - on that profile's roots that no profile still assigned to the workspace - needs and that are not the workspace's package cache root. A profile still - assigned needs a grant on one of its roots, and a grant on a folder that - holds one of its roots that no other grant reaches: a root inside a - granted folder was readable when it was planned and got no grant of its - own. The workspace folder's read-write grant is never revoked by these. + on that profile's roots, or on a folder that holds one of them, that + neither a profile still assigned to the workspace nor the workspace's + package cache root needs. A profile still assigned, and the cache root, + need a grant on their folder, and a grant on a folder that holds it that + no other grant reaches: a root inside a granted folder was readable when it + was planned and got no grant of its own. A grant kept that way is revoked + with the last profile inside it, whichever is unassigned first. The + workspace folder's read-write grant is never revoked by these. Every grant is attempted even after one fails, and each grant not revoked is reported. Unregistering a workspace revokes every grant of the workspace first and unregisters it only when every revocation was diff --git a/docs/desktop-interface.md b/docs/desktop-interface.md index 4636ab1d..ac39a62c 100644 --- a/docs/desktop-interface.md +++ b/docs/desktop-interface.md @@ -1336,7 +1336,9 @@ waits. The window shows: confirmation that names the workspace folder, the profile, each folder the workspace's sandbox is granted read and execute, and the folders that need an administrator or whose access could not be read, then grants and assigns - with the confirmed plan. Turning one off calls + with the confirmed plan. When the assignment fails after granting, the + grants it made that no assigned profile needs are revoked, and the error + counts any that could not be, for their **Revoke**. Turning one off calls `settings_unassign_toolchain_profile`, whose confirmation names the grants it revokes and says the workspace's running commands stop. A declined confirmation or a refusal shows the recorded state again. Then the @@ -1394,7 +1396,8 @@ waits. The window shows: `revocation_incomplete`, saying how many grants were not revoked, to retry each one's **Revoke**, and to remove the workspace again; a grant revoked whose AppContainer profile could not be deleted is reported apart, because - it is no longer listed. When every grant was revoked but the removal + it is no longer listed, and when that is the only failure the message says + every grant was revoked. When every grant was revoked but the removal cannot be recorded, the workspace stays registered and the command fails with `revocation_incomplete` after the same wait. If that file cannot be deleted, the command still stops and waits for the runs the removal diff --git a/docs/execution.md b/docs/execution.md index 9e8ead11..1bbdcd1d 100644 --- a/docs/execution.md +++ b/docs/execution.md @@ -971,24 +971,31 @@ consent to give that workspace's sandbox the profile's folders. assignment cannot be recorded, the profile stays unassigned and core revokes the grants this call made that no assigned profile needs, which withdraws the workspace's runs; a grant whose revocation fails stays - recorded, `pending` or `revoking`, until it is revoked. `profile-assign` is itself the consent, + recorded, `pending` or `revoking`, until it is revoked. Core returns those + revocations with the error: `profile-assign` names each grant not revoked + with its `container-revoke` command, and the `settings` window counts them + and points to each one's **Revoke**. `profile-assign` is itself the consent, so it plans and assigns in one call, and prints `assigned_profile_id`, `granted` (each `grant_id` with its folder), and `not_granted` with the reason. - **Unassigning and removing:** the change is recorded first. Then core revokes the workspace's read-execute grants whose folder is one of the - profile's roots, that no profile still assigned to the workspace needs, and - that are not on the workspace's package cache root. A profile still - assigned needs a grant on one of its roots, and a grant on a folder that - holds one of its roots when no other grant of the workspace is on that root - or above it: a root inside a granted folder was readable when it was - planned, so it got no grant of its own. A folder whose containment cannot - be read counts as not needing the grant. The workspace folder's read-write + profile's roots or holds one of them, that neither a profile still assigned + to the workspace nor the workspace's package cache root needs. A profile + still assigned, and the cache root, need a grant on their folder, and a + grant on a folder that holds it when no other grant of the workspace is on + that folder or above it: a root inside a granted folder was readable when + it was planned, so it got no grant of its own. So a grant on an outer + profile's root, kept while a nested root of another profile relies on it, + is revoked when that other profile is unassigned too. A folder whose + containment cannot be read is not a candidate, and counts as not needing + the grant. The workspace folder's read-write grant is never revoked here. Every grant is attempted, even after one fails. `profile-unassign` and `profile-remove` print what they revoked under `revoked`; a failed revocation leaves the change recorded, each grant not revoked is named with its `container-revoke` command, and a grant whose - AppContainer profile could not be deleted afterwards is named as revoked. + AppContainer profile could not be deleted afterwards is named as revoked; + when that is the only failure, the message says every grant was revoked. - **Unregistering:** `workspace unregister` revokes every grant of the workspace first and unregisters it only when every revocation was confirmed; otherwise the workspace stays registered with the grants not yet diff --git a/docs/workspace-permissions.md b/docs/workspace-permissions.md index 78d7773a..2751cc4c 100644 --- a/docs/workspace-permissions.md +++ b/docs/workspace-permissions.md @@ -281,7 +281,7 @@ does not; assigning also refuses a profile declared on another platform. none. Removing a profile ends every assignment of it, and so does unregistering the workspace. On Windows assigning grants the folders the workspace's container needs, and unassigning revokes those no other assigned -profile lists; the [execution guide](execution.md#toolchain-profiles) owns +profile needs; the [execution guide](execution.md#toolchain-profiles) owns those rules. The `settings` window assigns and unassigns with a switch per profile on the workspace's page, after a native confirmation. Existing profiles start assigned to no workspace. Version 0.69.0 refuses a settings From 9e8b7b43a1cb3e67dba3c6e29f5b878b12485bac Mon Sep 17 00:00:00 2001 From: James Chapman Date: Fri, 27 Nov 2026 02:51:35 +0000 Subject: [PATCH 5/5] fix: keep grants by recorded path and wait after a failed assignment Count only active grants as cover for an outer grant, and match a moved or removed nested root by its recorded canonical path, so it neither releases the outer grant early nor keeps it after its profile goes. A failed assignment whose rollback revoked a grant, or tried to, now waits for the workspace's withdrawn runs on the CLI and in the settings window before it reports. The desktop report also says when only an AppContainer profile could not be deleted. Test cleanup reports each revocation that fails and a grant list it could not read, and a test hook checks a rollback that cannot revoke. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 10 +- .../src/desktop/settings_changes.rs | 95 ++++++++-- .../src/desktop/settings_discovery.rs | 16 +- .../src/desktop/settings_execution.rs | 84 ++++++--- crates/omgcode-cli/src/control_cli.rs | 74 ++++++-- crates/omgcode-cli/tests/support/run_scene.rs | 44 +++-- crates/omgcode-core/src/control.rs | 6 + crates/omgcode-core/src/control/assignment.rs | 46 +++-- .../src/control/assignment/tests.rs | 175 +++++++++++++++++- crates/omgcode-core/src/control/container.rs | 6 + ...s-to-workspaces-and-grant-on-assignment.md | 16 +- docs/desktop-interface.md | 6 +- docs/execution.md | 23 ++- 13 files changed, 489 insertions(+), 112 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c7c65b93..e02fb15c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -614,8 +614,9 @@ Changes are recorded here before a release version is assigned. refuses the assignment if the plan changed, then applies the grants and records the assignment last, granting only a folder that is still the confirmed directory. An assignment whose grant fails, or that cannot be - recorded, revokes the grants it made that no assigned profile needs and - reports each one it could not revoke, and a + recorded, revokes the grants it made that no assigned profile needs, + waits for the runs those revocations withdrew, and reports each grant it + could not revoke, and a workspace with a pending or revoking grant is refused a plan. Folders that need an administrator, or whose access could not be read, are listed and not granted. Registering a @@ -625,7 +626,10 @@ Changes are recorded here before a release version is assigned. or on a folder that holds one, that no other assigned profile and not the package cache root needs, never the workspace folder's grant; a grant on a folder that holds a still-assigned profile's root, which got no grant of - its own, is kept until that profile is unassigned too. Every grant is + its own, is kept until that profile is unassigned too, while no other + active grant covers that root. A moved or removed root is matched by its + recorded path, so it neither releases the grant early nor keeps it after + its profile goes. Every grant is attempted, and each one not revoked is named. Unregistering revokes every grant of the workspace first and leaves it registered if a revocation fails or its removal cannot be recorded. Each caller waits only for the diff --git a/crates/omgcode-app/src/desktop/settings_changes.rs b/crates/omgcode-app/src/desktop/settings_changes.rs index e822c882..52c59371 100644 --- a/crates/omgcode-app/src/desktop/settings_changes.rs +++ b/crates/omgcode-app/src/desktop/settings_changes.rs @@ -44,9 +44,9 @@ use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, Ordering}; use omgcode_core::control::{ - CONTAINER_GRANTS_SUPPORTED, ControlError, ControlStore, CredentialId, CredentialStore, - MAX_PROVIDER_ENDPOINT_BYTES, ProviderAuth, ProviderCredentialError, ProviderKind, - ProviderProfileDeclaration, Revocations, delete_unbound_credential, + AssignmentFailure, CONTAINER_GRANTS_SUPPORTED, ControlError, ControlStore, CredentialId, + CredentialStore, MAX_PROVIDER_ENDPOINT_BYTES, ProviderAuth, ProviderCredentialError, + ProviderKind, ProviderProfileDeclaration, Revocations, delete_unbound_credential, }; use omgcode_core::policy::{Access, PermissionSet, WorkspaceId, WriteTool}; use omgcode_core::provider::ModelEndpoint; @@ -1447,14 +1447,28 @@ impl DesktopService { also: AlsoWithdrawn, deferred: Option, ) -> Result { - let finished = self.finish_change(listed, also); - match (deferred, finished) { - (None, finished) => finished, - (Some(error), Ok(_)) => Err(error), - (Some(error), Err(wait)) => Err(DesktopError::execution( + match deferred { + None => self.finish_change(listed, also), + Some(error) => Err(self.failed_after_wait(listed, also, error)), + } + } + + /// `error`, the failure of a change that still withdrew runs, such as an + /// assignment whose rollback revoked a grant (ADR-0107), returned after + /// the wait in [`finish_change`](Self::finish_change) with any wait + /// failure added to its message. The store must be closed. + pub(super) fn failed_after_wait( + &self, + listed: Result, run::RunError>, + also: AlsoWithdrawn, + error: DesktopError, + ) -> DesktopError { + match self.wait_for_withdrawn(listed, also) { + Ok(()) => error, + Err(wait) => DesktopError::execution( error.code(), format!("{} {}", error.message(), wait.message()), - )), + ), } } @@ -1466,6 +1480,18 @@ impl DesktopService { listed: Result, run::RunError>, also: AlsoWithdrawn, ) -> Result { + self.wait_for_withdrawn(listed, also)?; + let store = self.inner.open_or_create_control()?; + Ok(overview_of(&self.inner, store)) + } + + /// Wait for the runs listed as withdrawn, the runs in `also`, and any + /// others the settings now withdraw to stop. + fn wait_for_withdrawn( + &self, + listed: Result, run::RunError>, + also: AlsoWithdrawn, + ) -> Result<(), DesktopError> { // An unreadable run journal never undoes the recorded change, and the // watchers still stop the runs: wait for what the settings now // withdraw, then report that the runs were not all checked. @@ -1479,8 +1505,7 @@ impl DesktopService { if listed.is_err() || also.unchecked { return Err(DesktopError::runs_unchecked()); } - let store = self.inner.open_or_create_control()?; - Ok(overview_of(&self.inner, store)) + Ok(()) } } @@ -1534,6 +1559,19 @@ pub(super) fn revocation_outcome( (also, deferred) } +/// The runs to wait for after a failed assignment, or `None` when its +/// rollback attempted no revocation. Revoking a grant withdraws every run of +/// its workspace that started before, so a rollback that revoked one, or +/// tried to, stops those runs as an unassignment does (ADR-0107). `before` +/// holds every pending run, listed under the lock before the assignment. +pub(super) fn rollback_withdrawn( + before: Result, run::RunError>, + failure: &AssignmentFailure, +) -> Option { + (!failure.released.workspaces.is_empty()) + .then(|| revocation_outcome(before, &failure.released, RevokingChange::Recorded).0) +} + /// The native confirmation for registering `folder`. On Windows it also asks /// for the read-write grant registration applies (ADR-0107). fn register_confirmation(folder: &str, on: &str) -> Confirmation { @@ -1761,6 +1799,41 @@ mod tests { ControlError::ProfileRemoval(std::io::Error::other("operating system text")) } + /// A failed assignment waits only when its rollback attempted a + /// revocation, and then for that workspace's pending runs alone; a run + /// list that could not be read is reported as unchecked. + #[test] + fn a_failed_assignment_waits_for_the_runs_its_rollback_withdrew() { + let id = || { + uuid::Uuid::new_v4() + .to_string() + .parse::() + .expect("workspace id") + }; + let (app, other) = (id(), id()); + let (run_app, run_other) = (uuid::Uuid::new_v4(), uuid::Uuid::new_v4()); + let before = || Ok(vec![(app, run_app), (other, run_other)]); + let failure = |workspaces| AssignmentFailure { + error: ControlError::LimitReached, + released: Revocations { + workspaces, + ..Revocations::default() + }, + }; + + assert!(rollback_withdrawn(before(), &failure(vec![])).is_none()); + let also = rollback_withdrawn(before(), &failure(vec![app])).expect("a wait"); + assert_eq!(also.runs, [run_app]); + assert!(!also.unchecked); + let unread = rollback_withdrawn( + Err(run::RunError::Refused("the run journal is unreadable")), + &failure(vec![app]), + ) + .expect("a wait"); + assert!(unread.runs.is_empty()); + assert!(unread.unchecked); + } + /// A grant revoked whose AppContainer profile could not be deleted is /// not reported as a grant left to revoke. #[test] diff --git a/crates/omgcode-app/src/desktop/settings_discovery.rs b/crates/omgcode-app/src/desktop/settings_discovery.rs index 507a3cdf..e4c58391 100644 --- a/crates/omgcode-app/src/desktop/settings_discovery.rs +++ b/crates/omgcode-app/src/desktop/settings_discovery.rs @@ -53,6 +53,7 @@ use omgcode_core::control::{ ControlStore, PlannedFolder, ProfileAccessPlan, RootGrantNeed, root_grant_need, }; use omgcode_core::policy::WorkspaceId; +use omgcode_core::run; use omgcode_core::toolchain_discovery::{ DiscoveryHost, ToolchainFamily, ToolchainProposal, discover, discover_bounded, }; @@ -64,7 +65,7 @@ use super::DesktopService; use super::error::DesktopError; use super::settings::overview_of; use super::settings_changes::{ - ChangeGuard, Confirmation, SettingsPrompt, check_revision, confirm, shown, + ChangeGuard, Confirmation, SettingsPrompt, check_revision, confirm, rollback_withdrawn, shown, }; use super::settings_execution::access_plan_text; use super::state::folder_of_directory; @@ -508,6 +509,7 @@ impl DesktopService { } if let Some((workspace_id, _, plan)) = &assign { let names: Vec<&str> = chosen.iter().map(ToolchainProposal::name).collect(); + let before = run::pending_runs(&store); if let Err(failure) = store.assign_profiles_with_access(*workspace_id, &names, plan, expected) { @@ -519,11 +521,19 @@ impl DesktopService { store.profile_assigned(*workspace_id, status.profile().id()) }) .count(); - return Err(DesktopError::not_assigned( + let error = DesktopError::not_assigned( chosen.len(), assigned, &DesktopError::assignment_failed(&failure), - )); + ); + // A rollback that revoked a grant withdrew the + // workspace's runs: wait for them with the store closed. + let Some(also) = rollback_withdrawn(before, &failure) else { + return Err(error); + }; + let listed = run::withdrawn_runs(&store); + drop(store); + return Err(self.failed_after_wait(listed, also, error)); } } } diff --git a/crates/omgcode-app/src/desktop/settings_execution.rs b/crates/omgcode-app/src/desktop/settings_execution.rs index 2ddedc7d..c73454ca 100644 --- a/crates/omgcode-app/src/desktop/settings_execution.rs +++ b/crates/omgcode-app/src/desktop/settings_execution.rs @@ -56,7 +56,7 @@ use super::error::DesktopError; use super::settings::overview_of; use super::settings_changes::{ AlsoWithdrawn, ChangeGuard, Confirmation, FolderPurpose, RevokingChange, SettingsPrompt, - check_revision, confirm, revocation_outcome, shown, + check_revision, confirm, revocation_outcome, rollback_withdrawn, shown, }; use super::state::folder_of_directory; use super::wire::SettingsOverview; @@ -213,25 +213,30 @@ impl DesktopError { /// with the count of grants it made that could not be revoked afterwards; /// the settings list each one, and **Revoke** tries again. A grant revoked /// whose AppContainer profile alone could not be deleted holds no access - /// and is not counted. + /// and is not counted, but the message says the profile was left. The + /// operating system's own text is never shown. pub(super) fn assignment_failed(failure: &AssignmentFailure) -> Self { let cause = Self::from_grant(&failure.error); - let left = failure - .released - .failures + let failures = &failure.released.failures; + if failures.is_empty() { + return cause; + } + let left = failures .iter() .filter(|(_, error)| !matches!(error, ControlError::ProfileRemoval(_))) .count(); - if left == 0 { - return cause; + let mut message = format!("{}.", cause.message().trim_end_matches('.')); + if left > 0 { + message.push_str(&format!( + " {left} container grant(s) the failed assignment made could not be revoked; the settings list each one, and Revoke tries again." + )); } - Self::execution( - cause.code(), - format!( - "{}. {left} container grant(s) the failed assignment made could not be revoked; the settings list each one, and Revoke tries again.", - cause.message().trim_end_matches('.') - ), - ) + if left < failures.len() { + message.push_str( + " A grant was revoked, but the workspace's AppContainer profile could not be deleted; it holds no access now.", + ); + } + Self::execution(cause.code(), message) } /// The package profile was removed, but credentials bound to it were not @@ -638,7 +643,10 @@ impl DesktopService { /// confirmation; `cancelled`; `stale_revision`; /// `settings_change_running`; `busy`; `container_access_failed` when a /// grant was recorded but the folder's list could not be changed (the - /// profile stays unassigned and the grant `pending`; revoke it). + /// profile stays unassigned and the grant `pending`; revoke it). A failed + /// assignment whose rollback revoked a grant, or tried to, first waits + /// for the workspace's runs that withdrew, and adds to its message any it + /// could not confirm stopped. pub fn settings_assign_toolchain_profile( &self, request: ProfileAssignmentRequest, @@ -669,11 +677,25 @@ impl DesktopService { (workspace.id(), plan, confirmation) }; confirm(prompt, &confirmation)?; - let mut store = self.inner.open_or_create_control()?; - store - .assign_profile_with_access(workspace_id, &request.name, &plan, request.revision) - .map_err(|failure| DesktopError::assignment_failed(&failure))?; - Ok(overview_of(&self.inner, store)) + let (listed, also, error) = { + let mut store = self.inner.open_or_create_control()?; + let before = run::pending_runs(&store); + let failure = match store.assign_profile_with_access( + workspace_id, + &request.name, + &plan, + request.revision, + ) { + Ok(_) => return Ok(overview_of(&self.inner, store)), + Err(failure) => failure, + }; + let error = DesktopError::assignment_failed(&failure); + let Some(also) = rollback_withdrawn(before, &failure) else { + return Err(error); + }; + (run::withdrawn_runs(&store), also, error) + }; + Err(self.failed_after_wait(listed, also, error)) } /// `settings` only. After a native confirmation, unassign a toolchain @@ -1032,20 +1054,29 @@ mod tests { } } - /// A failed assignment that left no grant reports its cause as a grant - /// failure does; one that left grants also counts them, without the - /// operating system's text, and a grant whose profile alone could not - /// be deleted is not counted. + /// A failed assignment whose rollback revoked everything reports its + /// cause as a grant failure does; one that left grants also counts them, + /// without the operating system's text. A grant whose profile alone + /// could not be deleted is not counted, but the message says the profile + /// was left. #[test] fn a_failed_assignment_counts_the_grants_it_left() { let os = || std::io::Error::other("operating system text"); + let profile_left = " A grant was revoked, but the workspace's AppContainer profile could not be deleted; it holds no access now."; + let cause = DesktopError::from_grant(&ControlError::LimitReached); + let clean = DesktopError::assignment_failed(&failure(ControlError::LimitReached, vec![])); + assert_eq!(clean.code(), cause.code()); + assert_eq!(clean.message(), cause.message()); + let alone = DesktopError::assignment_failed(&failure( ControlError::LimitReached, vec![(Uuid::new_v4(), ControlError::ProfileRemoval(os()))], )); - let cause = DesktopError::from_grant(&ControlError::LimitReached); assert_eq!(alone.code(), cause.code()); - assert_eq!(alone.message(), cause.message()); + assert_eq!( + alone.message(), + format!("{}.{profile_left}", cause.message().trim_end_matches('.')) + ); let left = DesktopError::assignment_failed(&failure( ControlError::Container(os()), @@ -1062,6 +1093,7 @@ mod tests { ), "{message}" ); + assert!(message.ends_with(profile_left), "{message}"); assert!(!message.contains(".."), "{message}"); assert!(!message.contains("operating system text"), "{message}"); } diff --git a/crates/omgcode-cli/src/control_cli.rs b/crates/omgcode-cli/src/control_cli.rs index b20e60e1..ea951b6a 100644 --- a/crates/omgcode-cli/src/control_cli.rs +++ b/crates/omgcode-cli/src/control_cli.rs @@ -911,7 +911,8 @@ fn container_grant(args: ContainerGrantArgs, data_root: &Path) -> Result<(), Cli /// Assign a profile to a workspace and grant what it needs. The command is /// the operator's consent, so the plan made here under the control lock is -/// the one applied. +/// the one applied. A failed assignment whose rollback revoked a grant, or +/// tried to, waits for the workspace's runs that withdrew before it reports. fn profile_assign( workspace: &str, name: &str, @@ -924,9 +925,29 @@ fn profile_assign( let plan = store .plan_profile_access(workspace_id, name) .map_err(control_error)?; - let assignment = store - .assign_profile_with_access(workspace_id, name, &plan, revision) - .map_err(assignment_failed)?; + let before = run::pending_runs(&store); + let assignment = match store.assign_profile_with_access(workspace_id, name, &plan, revision) { + Ok(assignment) => assignment, + Err(failure) if failure.released.workspaces.is_empty() => { + return Err(assignment_failed(failure)); + } + Err(failure) => { + // Revoking a grant withdraws every run of its workspace that + // started before: wait for them with the store closed. + let listed = withdrawn_runs(&store); + drop(store); + let problems = wait_for_revoked_runs(data_root, listed, before, &failure.released); + let mut error = assignment_failed(failure); + for problem in problems { + if !error.message.ends_with('.') { + error.message.push('.'); + } + error.message.push(' '); + error.message.push_str(&problem); + } + return Err(error); + } + }; let not_granted: Vec<_> = assignment .plan .needs_administrator() @@ -1022,16 +1043,7 @@ fn finish_revocations( revocations: &Revocations, change: RevokingChange<'_>, ) -> Result<(), CliError> { - let mut wait = listed.as_deref().unwrap_or(&[]).to_vec(); - let mut problems = Vec::new(); - if !revocations.workspaces.is_empty() { - match before { - Ok(runs) => wait.extend(revocations.withdrawn_runs(&runs)), - Err(error) => problems.push(format!( - "The runs the revocations affect could not be found: {error}." - )), - } - } + let mut problems = wait_for_revoked_runs(data_root, listed, before, revocations); let mut kind = "run"; if !revocations.failures.is_empty() { kind = "control"; @@ -1069,17 +1081,41 @@ fn finish_revocations( ), ); } + if problems.is_empty() { + Ok(()) + } else { + Err(CliError::new(kind, problems.join(" "))) + } +} + +/// Wait for the runs the settings withdrew, `listed`, and the pending runs in +/// `before` of each workspace whose grant was revoked or was tried, then +/// return each problem met, in order. Any revocation, even one that failed +/// after it was requested, withdraws every run of its workspace. The store +/// must be closed. +fn wait_for_revoked_runs( + data_root: &Path, + listed: Result, CliError>, + before: Result, run::RunError>, + revocations: &Revocations, +) -> Vec { + let mut wait = listed.as_deref().unwrap_or(&[]).to_vec(); + let mut problems = Vec::new(); + if !revocations.workspaces.is_empty() { + match before { + Ok(runs) => wait.extend(revocations.withdrawn_runs(&runs)), + Err(error) => problems.push(format!( + "The runs the revocations affect could not be found: {error}." + )), + } + } if let Err(error) = stop_withdrawn_runs(data_root, &wait) { problems.push(error.message); } if let Err(error) = listed { problems.push(error.message); } - if problems.is_empty() { - Ok(()) - } else { - Err(CliError::new(kind, problems.join(" "))) - } + problems } fn profile_add(args: ProfileAddArgs, data_root: &Path) -> Result<(), CliError> { diff --git a/crates/omgcode-cli/tests/support/run_scene.rs b/crates/omgcode-cli/tests/support/run_scene.rs index f0516ed7..63c8bdb5 100644 --- a/crates/omgcode-cli/tests/support/run_scene.rs +++ b/crates/omgcode-cli/tests/support/run_scene.rs @@ -70,8 +70,7 @@ impl Scene { // A failed registration can still leave a pending grant whose ACL // entry exists, so track what was recorded before failing. if !registered.status.success() { - scene.track_recorded_grants(); - assert_success(®istered); + scene.fail_after_tracking(®istered); } let registered = json_output(®istered); scene.id = registered["registration_id"] @@ -143,8 +142,7 @@ impl Scene { // A failed command can still leave a pending grant whose ACL // entry exists. Track every grant of this workspace so the // scene revokes it, then fail. - self.track_recorded_grants(); - assert_success(&output); + self.fail_after_tracking(&output); } self.grants.push( json_output(&output)["grant_id"] @@ -159,20 +157,35 @@ impl Scene { /// revoked. The scene's data directory is its own, so every grant in it /// is the scene's, including one recorded by a registration that failed /// before its identifier was known. When status cannot be read, the - /// tracked list is kept. - fn track_recorded_grants(&mut self) { + /// tracked list is kept and the reason is returned, so the caller + /// reports that a recorded grant may be missing from it. + fn track_recorded_grants(&mut self) -> Result<(), String> { // `Drop` calls this, so status is read without panicking: a second // panic while a test unwinds would abort the run and skip the // revocations. - let Ok(recorded) = recorded_grant_ids(&self.data) else { - return; - }; + let recorded = recorded_grant_ids(&self.data)?; self.grants.retain(|known| recorded.contains(known)); for id in recorded { if !self.grants.contains(&id) { self.grants.push(id); } } + Ok(()) + } + + /// Fail on `output`, a CLI command that failed, after tracking the + /// grants it may have recorded so `Drop` revokes them. A failure to list + /// them is reported with the command's own. + fn fail_after_tracking(&mut self, output: &Output) -> ! { + let tracked = match self.track_recorded_grants() { + Ok(()) => "tracked".to_owned(), + Err(error) => format!("not listed: {error}"), + }; + panic!( + "CLI failed: stdout={} stderr={} recorded grants: {tracked}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); } /// Revoke every grant and fail on any revocation that fails. @@ -183,13 +196,16 @@ impl Scene { /// Revoke each tracked grant, and each recorded grant of the workspace, /// such as those `profile-assign` applied, once, returning the failures. - /// Revoking the last grant also deletes the container profile, so test - /// runs leave no per-user AppContainer state behind. A grant whose - /// revocation failed stays tracked, so `Drop` retries it after `close` - /// fails. + /// When the recorded grants cannot be listed, that is a failure too, and + /// the tracked grants are still revoked. Revoking the last grant also + /// deletes the container profile, so test runs leave no per-user + /// AppContainer state behind. A grant whose revocation failed stays + /// tracked, so `Drop` retries it after `close` fails. fn revoke_grants(&mut self) -> Vec { - self.track_recorded_grants(); let mut failures = Vec::new(); + if let Err(error) = self.track_recorded_grants() { + failures.push(format!("the recorded grants could not be listed: {error}")); + } let mut unresolved = Vec::new(); for grant in std::mem::take(&mut self.grants) { let command = cli_command(&self.data, &["workspace", "container-revoke", &grant]); diff --git a/crates/omgcode-core/src/control.rs b/crates/omgcode-core/src/control.rs index c5f1e46b..7205751f 100644 --- a/crates/omgcode-core/src/control.rs +++ b/crates/omgcode-core/src/control.rs @@ -616,6 +616,10 @@ pub struct ControlStore { poisoned: bool, #[cfg(test)] fail_next_sync: bool, + /// Fail the next container revocation's access-control change, after + /// its request is recorded, as a real failure would. + #[cfg(test)] + fail_next_revocation: bool, } /// Descriptive directory records. Only the broker's live checks can authorize I/O. @@ -885,6 +889,8 @@ impl ControlStore { poisoned: false, #[cfg(test)] fail_next_sync: false, + #[cfg(test)] + fail_next_revocation: false, }) } diff --git a/crates/omgcode-core/src/control/assignment.rs b/crates/omgcode-core/src/control/assignment.rs index ea5b7948..70e63d01 100644 --- a/crates/omgcode-core/src/control/assignment.rs +++ b/crates/omgcode-core/src/control/assignment.rs @@ -806,8 +806,9 @@ impl ControlStore { /// profile `leaving`, or on a folder that holds one of them, that no other /// profile assigned to it and not its package cache root needs. A grant on /// an outer folder kept for a nested root while its own profile was - /// unassigned is released with the last profile inside it. A folder whose - /// containment cannot be read is not a candidate. + /// unassigned is released with the last profile inside it, even when that + /// root was moved or removed since: [`holds`] also reads the recorded + /// paths. fn unneeded_root_grants( &self, workspace_id: WorkspaceId, @@ -822,9 +823,9 @@ impl ControlStore { let directory = grant.directory(); grant.workspace_id() == workspace_id && grant.access() == ContainerGrantAccess::ReadExecute - && roots.iter().any(|root| { - root.same_directory(directory) || directory.contains(root).unwrap_or(false) - }) + && roots + .iter() + .any(|root| root.same_directory(directory) || holds(directory, root)) }) .collect(); let releasing: Vec = candidates.iter().map(|grant| grant.id()).collect(); @@ -840,11 +841,13 @@ impl ControlStore { /// Whether a root of a profile assigned to `workspace_id`, other than /// `leaving`, or the folder `cache`, relies on `grant`: the root is the - /// grant's folder, or lies beneath it and no grant of the workspace - /// outside `releasing` is on the root or above it. A root inside another - /// profile's root was readable when it was planned, so it was given no - /// grant of its own. A folder whose containment cannot be read counts as - /// not relying on the grant. + /// grant's folder, or lies beneath it, as [`holds`] reads it, and no + /// other active grant of the workspace outside `releasing` is on the root + /// or, by a live check, above it. A root inside another profile's root was + /// readable when it was planned, so it was given no grant of its own. A + /// pending or revoking grant may hold no access, so it never stands in + /// for this one, and neither does a grant whose containment of the root + /// cannot be read: in both cases the grant is kept. fn grant_needed( &self, workspace_id: WorkspaceId, @@ -857,13 +860,14 @@ impl ControlStore { let kept: Vec<&DirectoryRecord> = self .container_grants() .iter() - .map(ContainerGrantStatus::grant) .filter(|other| { + let other = other.grant(); other.workspace_id() == workspace_id && other.id() != grant.id() && !releasing.contains(&other.id()) }) - .map(ContainerGrant::directory) + .filter(|other| other.state() == ContainerGrantState::Active) + .map(|other| other.grant().directory()) .collect(); self.assigned_profiles(workspace_id) .iter() @@ -877,7 +881,7 @@ impl ControlStore { .chain(cache) .any(|root| { root.same_directory(directory) - || (directory.contains(root).unwrap_or(false) + || (holds(directory, root) && !kept.iter().any(|other| { other.same_directory(root) || other.contains(root).unwrap_or(false) })) @@ -923,6 +927,22 @@ impl ControlStore { } } +/// Whether `inner` lies beneath `outer` or is `outer`, by a live walk of +/// their directory identities or by their recorded canonical paths. Both +/// paths were canonical when recorded and never change, so the answer does +/// not depend on whether either folder still exists or can be read now. It +/// decides only which grants to keep or release; it never decides what a +/// run may reach, and a revocation still checks its folder's live identity. +fn holds(outer: &DirectoryRecord, inner: &DirectoryRecord) -> bool { + if outer.contains(inner).unwrap_or(false) { + return true; + } + match (outer.live_path(), inner.live_path()) { + (Ok(outer), Ok(inner)) => inner.starts_with(outer), + _ => false, + } +} + /// Validate and apply one assignment action during replay or append preflight. pub(super) fn apply(state: &mut ControlSnapshot, action: &Action) -> Result<(), ControlError> { let (workspace_id, profile_id, assign) = match action { diff --git a/crates/omgcode-core/src/control/assignment/tests.rs b/crates/omgcode-core/src/control/assignment/tests.rs index 3ef8f1dd..4c78d638 100644 --- a/crates/omgcode-core/src/control/assignment/tests.rs +++ b/crates/omgcode-core/src/control/assignment/tests.rs @@ -511,6 +511,89 @@ fn a_grant_a_nested_root_relies_on_is_kept() { assert_eq!(released(&scene.store), [sdk]); } +/// A pending grant on a nested root may hold no access, so it does not +/// stand in for the outer grant that root relies on; an active one does. +#[test] +fn only_an_active_grant_stands_in_for_an_outer_grant() { + let mut scene = scene(); + let app = scene.register("app"); + scene.profile("outer", &["sdk"]); + scene.profile("inner", &["sdk/bin"]); + scene.assign(app, "outer").expect("assign outer"); + scene.assign(app, "inner").expect("assign inner"); + let read = ContainerGrantAccess::ReadExecute; + let sdk = scene + .store + .test_record_grant(app, &scene.outside.join("sdk"), read); + let pending = scene + .store + .test_record_pending_grant(app, &scene.outside.join("sdk/bin"), read); + let released = |store: &ControlStore| { + store + .grants_released_by_unassignment(app, "outer") + .expect("preview") + }; + + assert!(released(&scene.store).is_empty()); + + scene + .store + .append( + Action::ContainerGrantApplied { grant_id: pending }, + scene.store.revision(), + ) + .expect("applied"); + assert_eq!(released(&scene.store), [sdk]); +} + +/// A nested root that was moved or removed, so its containment cannot be +/// read live, still counts by its recorded path: its profile keeps the +/// outer grant while assigned, and unassigning or removing that profile +/// then releases it. +#[test] +fn a_removed_nested_root_keeps_and_then_releases_the_outer_grant() { + let mut scene = scene(); + let app = scene.register("app"); + scene.profile("outer", &["sdk"]); + scene.profile("inner", &["sdk/bin"]); + scene.assign(app, "outer").expect("assign outer"); + scene.assign(app, "inner").expect("assign inner"); + let sdk = scene.store.test_record_grant( + app, + &scene.outside.join("sdk"), + ContainerGrantAccess::ReadExecute, + ); + fs::remove_dir(scene.outside.join("sdk/bin")).expect("remove the nested root"); + + assert!( + scene + .store + .grants_released_by_unassignment(app, "outer") + .expect("preview") + .is_empty() + ); + + let revision = scene.store.revision(); + scene + .store + .unassign_profile(app, "outer", revision) + .expect("unassign outer"); + assert_eq!( + scene + .store + .grants_released_by_unassignment(app, "inner") + .expect("preview"), + [sdk] + ); + assert_eq!( + scene + .store + .grants_released_by_removal("inner") + .expect("removal preview"), + [(app, vec![sdk])] + ); +} + /// When the outer profile is unassigned first, its grant is kept for the /// nested root; unassigning or removing the inner profile then releases it, /// so the grant does not outlive both assignments. A package cache root @@ -716,15 +799,8 @@ fn an_assignment_that_cannot_be_recorded_revokes_its_grant() { .store .assign_profile_with_access(app, "rust", &plan, revision); - let left: Vec = scene - .store - .container_grants() - .iter() - .map(|status| status.grant().id()) - .collect(); - for grant in &left { - let _ = scene.store.revoke_container_grant(*grant); - } + let (left, cleanup) = revoke_left(&mut scene.store); + assert!(cleanup.is_empty(), "cleanup failed: {cleanup:?}"); let failure = result.expect_err("the assignment cannot be recorded"); assert!( matches!(failure.error, ControlError::LimitReached), @@ -734,10 +810,89 @@ fn an_assignment_that_cannot_be_recorded_revokes_its_grant() { assert_eq!(failure.released.revoked.len(), 1, "{failure:?}"); assert!(failure.released.failures.is_empty(), "{failure:?}"); assert_eq!(failure.released.workspaces, [app]); - assert!(left.is_empty(), "a grant outlived the failed assignment"); + assert!( + left.is_empty(), + "a grant outlived the failed assignment: {left:?}" + ); assert!(scene.store.assigned_profiles(app).is_empty()); } +/// Revoke every recorded grant, attempting each, and return the grants +/// that were left and each revocation that failed, with its grant, so a +/// Windows test that applied real access-control entries can report what +/// it could not clean up. +#[cfg(windows)] +fn revoke_left(store: &mut ControlStore) -> (Vec, Vec) { + let left: Vec = store + .container_grants() + .iter() + .map(|status| status.grant().id()) + .collect(); + let failures = left + .iter() + .filter_map(|grant| { + store + .revoke_container_grant(*grant) + .err() + .map(|error| format!("{grant}: {error}")) + }) + .collect(); + (left, failures) +} + +/// When the rollback of a failed assignment cannot revoke the grant it +/// made, the failure returns that grant, and the grant stays recorded +/// `revoking` until the operator revokes it. The revocation's +/// access-control change is made to fail after its request is recorded, as +/// a real failure leaves it. +#[cfg(windows)] +#[test] +fn an_assignment_whose_rollback_cannot_revoke_returns_the_grant() { + let mut scene = scene(); + let app = scene.register("app"); + scene.profile("rust", &["rust"]); + let plan = scene.store.plan_profile_access(app, "rust").expect("plan"); + assert_eq!(plan.to_grant().len(), 1, "{plan:?}"); + // As in the test above: room for the grant and none for the assignment. + let initial = scene.store.entries[0].clone(); + scene + .store + .entries + .resize(crate::control::MAX_EVENTS - 4, initial); + let revision = scene.store.revision(); + scene.store.fail_next_revocation = true; + + let result = scene + .store + .assign_profile_with_access(app, "rust", &plan, revision); + + let states: Vec<(Uuid, ContainerGrantState)> = scene + .store + .container_grants() + .iter() + .map(|status| (status.grant().id(), status.state())) + .collect(); + let (_, cleanup) = revoke_left(&mut scene.store); + assert!(cleanup.is_empty(), "cleanup failed: {cleanup:?}"); + let failure = result.expect_err("the assignment cannot be recorded"); + assert!( + matches!(failure.error, ControlError::LimitReached), + "{failure:?}" + ); + let [(grant, ContainerGrantState::Revoking)] = states.as_slice() else { + panic!("one grant left revoking: {states:?}"); + }; + assert!(failure.released.revoked.is_empty(), "{failure:?}"); + assert!( + matches!( + failure.released.failures.as_slice(), + [(failed, ControlError::Container(_))] if failed == grant + ), + "{failure:?}" + ); + assert_eq!(failure.released.workspaces, [app]); +} + /// A failed assignment's release returns each revocation it attempted, and /// a revocation that fails is returned rather than dropped; a grant a /// still-assigned profile needs is not attempted, and a package cache root diff --git a/crates/omgcode-core/src/control/container.rs b/crates/omgcode-core/src/control/container.rs index 710aa29c..184b26cc 100644 --- a/crates/omgcode-core/src/control/container.rs +++ b/crates/omgcode-core/src/control/container.rs @@ -471,6 +471,12 @@ impl ControlStore { )?; } let live = status.grant.directory.live_path()?; + #[cfg(test)] + if std::mem::take(&mut self.fail_next_revocation) { + return Err(ControlError::Container(std::io::Error::other( + "injected revocation failure", + ))); + } platform::revoke(&live, status.grant.directory.native_identity(), &name) .map_err(ControlError::Container)?; self.append(Action::ContainerGrantRevoked { grant_id }, self.revision())?; diff --git a/docs/adr/0107-assign-toolchain-profiles-to-workspaces-and-grant-on-assignment.md b/docs/adr/0107-assign-toolchain-profiles-to-workspaces-and-grant-on-assignment.md index 7d095ba3..08bcc325 100644 --- a/docs/adr/0107-assign-toolchain-profiles-to-workspaces-and-grant-on-assignment.md +++ b/docs/adr/0107-assign-toolchain-profiles-to-workspaces-and-grant-on-assignment.md @@ -71,7 +71,9 @@ per-call approval of a command, which is a different decision. outlives a consent that did not take effect; a grant whose revocation fails stays recorded, `pending` or `revoking`, until it is revoked, and the failure returns those revocations so the operator is told which - grants are left. A + grants are left. A rollback that revoked a grant, or tried to, withdrew + the workspace's runs, so the caller waits for them before it reports, as + after an unassignment. A workspace with a grant that is pending or being revoked is refused a plan, because its runs are refused until that grant is settled. Off Windows the plan is empty and assigning records only the event. @@ -89,9 +91,15 @@ per-call approval of a command, which is a different decision. neither a profile still assigned to the workspace nor the workspace's package cache root needs. A profile still assigned, and the cache root, need a grant on their folder, and a grant on a folder that holds it that - no other grant reaches: a root inside a granted folder was readable when it - was planned and got no grant of its own. A grant kept that way is revoked - with the last profile inside it, whichever is unassigned first. The + no other active grant reaches: a root inside a granted folder was readable + when it was planned and got no grant of its own. A pending or revoking + grant may hold no access, so it never stands in. A grant kept that way is + revoked with the last profile inside it, whichever is unassigned first. + Whether a folder holds another is read from their live identities, or, + when either was moved, removed, or cannot be read, from their recorded + canonical paths, so a missing nested root neither loses the outer grant + early nor keeps it forever. That decides only what is kept; a revocation + still checks its folder's live identity. The workspace folder's read-write grant is never revoked by these. Every grant is attempted even after one fails, and each grant not revoked is reported. Unregistering a workspace revokes every grant of the diff --git a/docs/desktop-interface.md b/docs/desktop-interface.md index ac39a62c..e52e0787 100644 --- a/docs/desktop-interface.md +++ b/docs/desktop-interface.md @@ -1337,8 +1337,10 @@ waits. The window shows: workspace's sandbox is granted read and execute, and the folders that need an administrator or whose access could not be read, then grants and assigns with the confirmed plan. When the assignment fails after granting, the - grants it made that no assigned profile needs are revoked, and the error - counts any that could not be, for their **Revoke**. Turning one off calls + grants it made that no assigned profile needs are revoked, the + workspace's runs those revocations withdrew are waited for, and the error + counts any grant that could not be revoked, for its **Revoke**, and says + when only the AppContainer profile could not be deleted. Turning one off calls `settings_unassign_toolchain_profile`, whose confirmation names the grants it revokes and says the workspace's running commands stop. A declined confirmation or a refusal shows the recorded state again. Then the diff --git a/docs/execution.md b/docs/execution.md index 1bbdcd1d..7ee28674 100644 --- a/docs/execution.md +++ b/docs/execution.md @@ -974,7 +974,10 @@ consent to give that workspace's sandbox the profile's folders. recorded, `pending` or `revoking`, until it is revoked. Core returns those revocations with the error: `profile-assign` names each grant not revoked with its `container-revoke` command, and the `settings` window counts them - and points to each one's **Revoke**. `profile-assign` is itself the consent, + and points to each one's **Revoke**, and says so when only an AppContainer + profile could not be deleted. When the rollback revoked a grant, or tried + to, both wait for the workspace's withdrawn runs to stop before they report, + as an unassignment does. `profile-assign` is itself the consent, so it plans and assigns in one call, and prints `assigned_profile_id`, `granted` (each `grant_id` with its folder), and `not_granted` with the reason. @@ -983,13 +986,19 @@ consent to give that workspace's sandbox the profile's folders. profile's roots or holds one of them, that neither a profile still assigned to the workspace nor the workspace's package cache root needs. A profile still assigned, and the cache root, need a grant on their folder, and a - grant on a folder that holds it when no other grant of the workspace is on - that folder or above it: a root inside a granted folder was readable when - it was planned, so it got no grant of its own. So a grant on an outer + grant on a folder that holds it when no other active grant of the workspace + is on that folder or above it: a root inside a granted folder was readable + when it was planned, so it got no grant of its own. A pending or revoking + grant may hold no access, so it never stands in. So a grant on an outer profile's root, kept while a nested root of another profile relies on it, - is revoked when that other profile is unassigned too. A folder whose - containment cannot be read is not a candidate, and counts as not needing - the grant. The workspace folder's read-write + is revoked when that other profile is unassigned too. Whether a folder + holds another is read from their live identities, or, when either was + moved, removed, or cannot be read, from their recorded canonical paths, so + a missing nested root still keeps the outer grant while its profile is + assigned and releases it afterwards. That decides only what is kept; each + revocation still checks its folder's live identity. The workspace folder's + read-write + grant is never revoked here. grant is never revoked here. Every grant is attempted, even after one fails. `profile-unassign` and `profile-remove` print what they revoked under `revoked`; a failed revocation leaves the change recorded, each grant