diff --git a/AGENTS.md b/AGENTS.md index 0e15d926..9284240f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -221,6 +221,16 @@ The `settings` window imports, enables, and removes skills and removes toolchain profiles, package-network profiles, and, on Windows, container grants, after native confirmations; none can be edited ([ADR-0088](docs/adr/0088-change-execution-settings-in-the-settings-window.md)). +It also proposes toolchain profiles for the installed Rust, C and C++, Java, +Python, Perl, Go, Node.js, .NET, and Ruby toolchains from a core service that +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)). 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 8afa4698..4361467b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,57 @@ Changes are recorded here before a release version is assigned. ### Added +- Version 0.68.0 adds **Generate toolchain profiles from local packages** to + the **Toolchain profiles** group of the desktop `settings` window. The + local packages are the toolchains installed on this computer, and it + generates toolchain profiles from those installed toolchains (ADR-0103). + A new + core service, `toolchain_discovery`, holds one detector + per family: Rust (rustup toolchains), C and C++ (MSVC with the Windows SDK, + Clang, and MinGW GCC on Windows; GCC and Clang on Linux), Java, Python, + Perl, Go, Node.js, .NET, and Ruby. It reads the standard install folders, + the operator's `PATH`, `JAVA_HOME`, `GOROOT`, and `RUSTUP_HOME`, and small + installer-written files, each checked to be a regular file before it is + opened; it runs no program, reads no registry key, and never reads + repository configuration such as `rust-toolchain.toml`. A folder that + `PATH` or one of those variables names is read like any install folder, + even inside the development root, and core refuses it as a root before + any confirmation. Each + proposal lists its roots, `PATH` entries, and derived non-secret variables + (such as `JAVA_HOME`, `GOROOT`, `DOTNET_ROOT`, and MSVC's `INCLUDE` and + `LIB`), plus the system part every profile needs, and notes when its family + has not passed the confined acceptance runs. No root is a filesystem or + drive root, the home folder or its ancestor, or itself a link (core + records a root's resolved location), and no reserved variable is + proposed. Past 32 proposals every base name keeps its first installation + first, and the list says how many installations it left out; a folder + listing keeps the first 512 directories by name. A Rust proposal is one + toolchain directory, without the rustup proxies or `~/.cargo`. Three + `settings`-only commands + (`settings_discover_toolchains`, `settings_add_discovered_profiles`, and + `settings_grant_discovered_roots`) carry only the revision, a workspace + identifier, and the digests of 1 to 8 selected proposals. Rust discovers + again and refuses a list that no longer matches as `discovery_changed`, + shows one native confirmation per batch that lists every root, `PATH` entry, + and variable with its value, and records each profile with `add_profile` + or, on Windows, grants read-execute access with `grant_container_access`, + from the confirmed revision. On Windows each root says whether the selected + workspace's container can read it, needs a grant, needs an + administrator, or could not have its access-control list read, read while + the settings store is closed, and choosing + another workspace generates the list again. Only folders this account can + change are granted; folders whose access-control list could not be read + are named and skipped. Core gains `ControlStore::check_profile`, which + applies every `add_profile` rule and records nothing, so each proposal + shows why core would refuse it, and `add_profile` now refuses a 33rd + profile with its own reason. `ControlStore::check_container_grants` does + the same for a batch of grants, counting the batch against the grant + limits, and the grant command runs it before its dialog; + `grant_container_access` uses the same checks and names both limits. A + workspace named in an add is checked before its dialog. Model runs + keep no network, a 20-second deadline, and 1 GiB of memory, so a `cargo` + build that needs crates.io dependencies still fails offline. + - Version 0.67.0 adds a per-session reasoning effort (ADR-0102). The desktop model box has an **Effort** dropdown under **Model** with "Default", which sends nothing, and None, Minimal, Low, Medium, High, Extra high, and Max. It diff --git a/Cargo.lock b/Cargo.lock index a8e0f8d2..98fdf332 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3622,7 +3622,7 @@ dependencies = [ [[package]] name = "omgcode-app" -version = "0.67.0" +version = "0.68.0" dependencies = [ "directories", "omgcode-core", @@ -3638,7 +3638,7 @@ dependencies = [ [[package]] name = "omgcode-cli" -version = "0.67.0" +version = "0.68.0" dependencies = [ "clap", "omgcode-app", @@ -3651,7 +3651,7 @@ dependencies = [ [[package]] name = "omgcode-core" -version = "0.67.0" +version = "0.68.0" dependencies = [ "base64 0.23.1", "bytes", @@ -3675,7 +3675,7 @@ dependencies = [ [[package]] name = "omgcode-desktop" -version = "0.67.0" +version = "0.68.0" dependencies = [ "omgcode-app", "rfd", @@ -3688,7 +3688,7 @@ dependencies = [ [[package]] name = "omgcode-platform" -version = "0.67.0" +version = "0.68.0" dependencies = [ "libc", "rustix", diff --git a/Cargo.toml b/Cargo.toml index 8a158303..bdc8506d 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.67.0" +version = "0.68.0" edition = "2024" rust-version = "1.99.1" license = "Apache-2.0" diff --git a/crates/omgcode-app/src/desktop.rs b/crates/omgcode-app/src/desktop.rs index 40562512..036e220d 100644 --- a/crates/omgcode-app/src/desktop.rs +++ b/crates/omgcode-app/src/desktop.rs @@ -100,6 +100,7 @@ mod settings; mod settings_changes; mod settings_chat; mod settings_chatgpt; +mod settings_discovery; mod settings_execution; mod settings_skills; mod settings_web_hosts; @@ -128,6 +129,11 @@ 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, +}; pub use self::settings_execution::{ ContainerAccessChoice, ContainerGrantRequest, ContainerRevokeRequest, EnvironmentEntry, PackageProfileAddRequest, ProfileRemoveRequest, ToolchainProfileAddRequest, diff --git a/crates/omgcode-app/src/desktop/settings_discovery.rs b/crates/omgcode-app/src/desktop/settings_discovery.rs new file mode 100644 index 00000000..dca8ba6e --- /dev/null +++ b/crates/omgcode-app/src/desktop/settings_discovery.rs @@ -0,0 +1,864 @@ +//! Toolchain profiles and container grants generated from the toolchains +//! installed on this computer, for the `settings` window (ADR-0103). +//! +//! Discovery is core's trusted host-side service +//! ([`omgcode_core::toolchain_discovery`]): it reads folders and a few small +//! installer-written files and runs no program. This module only shows its +//! proposals and applies the ones the operator selects: +//! +//! - The window receives display-safe text and a digest for each proposal, +//! and sends back digests, never a path. Each change discovers again and +//! applies only proposals whose digest still matches, so a selection made +//! 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. +//! - 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. +//! +//! 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::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, +}; +use omgcode_core::policy::WorkspaceId; +use omgcode_core::toolchain_discovery::{ + DiscoveryHost, ToolchainFamily, ToolchainProposal, discover, discover_bounded, +}; +use omgcode_core::turn::display_safe_line; +use serde::{Deserialize, Serialize}; +use uuid::Uuid; + +use super::DesktopService; +use super::error::DesktopError; +use super::settings::overview_of; +use super::settings_changes::{ + ChangeGuard, Confirmation, SettingsPrompt, check_revision, confirm, shown, +}; +use super::state::folder_of_directory; +use super::wire::SettingsOverview; + +/// Most proposals one change applies, so one confirmation stays readable. +pub const MAX_SELECTED_PROPOSALS: usize = 8; +/// Longest variable value a confirmation shows, in characters. +const SHOWN_VALUE_CHARS: usize = 160; +/// Longest version a view or confirmation shows, in characters. +const SHOWN_VERSION_CHARS: usize = 80; + +/// Arguments of `settings_discover_toolchains`. +#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)] +#[serde(deny_unknown_fields)] +pub struct ToolchainDiscoveryRequest { + /// On Windows, a registered workspace whose container access the roots + /// report. `None` reports none. + pub workspace_id: Option, +} + +/// Arguments of `settings_add_discovered_profiles`. +#[derive(Clone, Debug, Deserialize, Eq, PartialEq)] +#[serde(deny_unknown_fields)] +pub struct DiscoveredProfilesRequest { + /// The settings revision the window last read. + 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`]. + 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)] +pub struct ProposedRootView { + /// Display-safe folder text. Never reopen a path from it. + pub folder: String, + /// `not_applicable` off Windows or with no workspace selected. + pub grant: RootGrantNeed, +} + +/// One proposed variable. Values are derived setup values, not secrets. +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] +pub struct ProposedVariableView { + /// The variable name. + pub name: String, + /// The display-safe value. + pub value: String, +} + +/// One proposal as the window shows it. +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] +pub struct ToolchainProposalView { + /// Selects the proposal in a change; see the module documentation. + pub digest: String, + /// The family. + pub family: ToolchainFamily, + /// The family's fixed label. + pub family_label: &'static str, + /// The proposed profile name, which satisfies core's name rule. + pub name: String, + /// A display-safe version taken from folder or file names. + pub version: Option, + /// The roots, in order. + pub read_only_roots: Vec, + /// Display-safe `PATH` entries, in order. + pub path_entries: Vec, + /// The variables, in order. + pub environment: Vec, + /// Fixed remarks. + pub notes: Vec<&'static str>, + /// Why core would refuse the proposal now, if it would. + pub refusal: Option, + /// A profile with this name is already recorded. + pub recorded: bool, +} + +/// What `settings_discover_toolchains` and the two changes return. +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] +pub struct ToolchainDiscovery { + /// The settings as they are now. + pub overview: SettingsOverview, + /// The workspace the roots report access for, if any. + pub workspace_id: Option, + /// On Windows with a workspace selected: whether it has the active + /// read-write grant on its own folder that every run needs. `None` + /// otherwise. + pub workspace_grant_active: Option, + /// The proposals, at most 32. + pub proposals: Vec, + /// Installations found and not proposed: more than eight under one name, + /// or more than 32 in all. + pub omitted: usize, +} + +/// What a view does when its workspace is not registered. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum MissingWorkspace { + /// Refuse with `unknown_workspace`, as a plain listing does. + Refuse, + /// Report no container access, as the list after a change does: the + /// change is recorded, so a failure would misreport it. + Ignore, +} + +impl DesktopError { + /// Discovery runs only where toolchain profiles exist. + fn discovery_unsupported() -> Self { + Self::execution( + "unsupported_platform", + "Toolchain profiles exist only on Linux and Windows.", + ) + } + + /// A selected digest matched no proposal of a new discovery. + fn discovery_changed() -> Self { + Self::execution( + "discovery_changed", + "The installed toolchains or the proposals changed since the list was made. Generate the list again and select again.", + ) + } + + /// 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.", + ); + } + Self::execution( + "nothing_to_grant", + format!( + "No folder can be granted from this account: {}. {}", + reasons.join(", and "), + advice.join(" ") + ), + ) + } + + /// A batch stopped after recording some of its records. + fn partly_applied(what: &str, done: usize, total: usize, cause: &Self) -> Self { + Self::execution( + cause.code(), + format!( + "{done} of {total} {what} were recorded before this failure: {}", + cause.message() + ), + ) + } +} + +/// Check the selection's shape before any discovery or dialog. +fn check_digests(digests: &[String]) -> Result<(), DesktopError> { + if digests.is_empty() || digests.len() > MAX_SELECTED_PROPOSALS { + return Err(DesktopError::invalid_request( + "Select 1 to 8 proposals at a time.", + )); + } + for (index, digest) in digests.iter().enumerate() { + if digest.len() != 64 + || !digest + .bytes() + .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)) + { + return Err(DesktopError::invalid_request( + "A selection is not a proposal digest.", + )); + } + if digests[..index].contains(digest) { + return Err(DesktopError::invalid_request( + "A proposal is selected twice.", + )); + } + } + Ok(()) +} + +/// The selected proposals of a fresh discovery, in the order selected. +fn selected( + host: &DiscoveryHost, + digests: &[String], +) -> Result, DesktopError> { + let digested: Vec<(String, ToolchainProposal)> = discover(host) + .into_iter() + .map(|proposal| (proposal.digest(), proposal)) + .collect(); + digests + .iter() + .map(|digest| { + digested + .iter() + .find(|(known, _)| known == digest) + .map(|(_, proposal)| proposal.clone()) + .ok_or_else(DesktopError::discovery_changed) + }) + .collect() +} + +/// `text` as one bounded, display-safe line. +fn bounded(text: &str, limit: usize) -> String { + let safe = display_safe_line(text); + if safe.chars().count() <= limit { + safe + } else { + let mut cut: String = safe.chars().take(limit).collect(); + cut.push('…'); + cut + } +} + +/// Why core refuses a proposal, as the window shows it. +fn refusal_text(error: &ControlError) -> String { + match error { + ControlError::Io(_) | ControlError::WorkspacePath(_) => { + "A folder could not be read as it is now.".to_owned() + } + other => DesktopError::from_control(other).message().to_owned(), + } +} + +/// The view of one proposal against the store as it is now. `needs` gives +/// each root's container access, in root order, when a workspace is +/// selected. +fn proposal_view( + store: &ControlStore, + proposal: &ToolchainProposal, + needs: Option<&[RootGrantNeed]>, +) -> ToolchainProposalView { + ToolchainProposalView { + digest: proposal.digest(), + family: proposal.family(), + family_label: proposal.family().label(), + name: proposal.name().to_owned(), + version: proposal + .version() + .map(|version| bounded(version, SHOWN_VERSION_CHARS)), + read_only_roots: proposal + .read_only_roots() + .iter() + .enumerate() + .map(|(index, root)| ProposedRootView { + folder: shown(root), + grant: needs + .and_then(|needs| needs.get(index).copied()) + .unwrap_or(RootGrantNeed::NotApplicable), + }) + .collect(), + path_entries: proposal + .path_entries() + .iter() + .map(|entry| shown(entry)) + .collect(), + environment: proposal + .environment() + .iter() + .map(|(name, value)| ProposedVariableView { + name: display_safe_line(name), + value: display_safe_line(value), + }) + .collect(), + notes: proposal.notes().iter().map(|note| note.text()).collect(), + refusal: store + .check_profile(&proposal.declaration()) + .err() + .map(|error| refusal_text(&error)), + recorded: store.profile(proposal.name()).is_some(), + } +} + +/// One profile as a confirmation lists it. +fn confirmation_entry(proposal: &ToolchainProposal) -> String { + let heading = match proposal.version() { + Some(version) => format!( + "{} ({}, {})", + proposal.name(), + proposal.family().label(), + bounded(version, SHOWN_VERSION_CHARS) + ), + None => format!("{} ({})", proposal.name(), proposal.family().label()), + }; + let list = |paths: &[PathBuf]| { + if paths.is_empty() { + " (none)".to_owned() + } else { + paths + .iter() + .map(|path| format!(" {}", shown(path))) + .collect::>() + .join("\n") + } + }; + let variables = if proposal.environment().is_empty() { + " (none)".to_owned() + } else { + proposal + .environment() + .iter() + .map(|(name, value)| { + format!( + " {}={}", + display_safe_line(name), + bounded(value, SHOWN_VALUE_CHARS) + ) + }) + .collect::>() + .join("\n") + }; + format!( + "{heading}\n Read-only roots:\n{}\n PATH entries:\n{}\n Environment variables:\n{variables}", + list(proposal.read_only_roots()), + list(proposal.path_entries()), + ) +} + +/// The native confirmation for adding the selected proposals. +fn add_confirmation(chosen: &[ToolchainProposal]) -> Confirmation { + let platform = if cfg!(windows) { "Windows" } else { "Linux" }; + 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.", + chosen.len(), + chosen + .iter() + .map(confirmation_entry) + .collect::>() + .join("\n\n"), + ), + } +} + +/// 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!( + "Give the workspace\n{workspace}\nread and execute access to these folders?\n{}\n\nThis changes each folder's access-control list on disk for that workspace's AppContainer, and each grant stays until you revoke it. Runs in the workspace can then read and execute everything beneath them.{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. + /// Nothing is recorded, granted, or run. On Windows, with a workspace, + /// each root says whether that workspace's container can read it. + /// + /// # Errors + /// + /// `unsupported_platform` outside Linux and Windows; `unknown_workspace`; + /// `busy`. + pub fn settings_discover_toolchains( + &self, + request: ToolchainDiscoveryRequest, + host: &DiscoveryHost, + ) -> Result { + self.discovery_view(host, request.workspace_id, MissingWorkspace::Refuse) + } + + /// `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. + /// + /// # 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. + pub fn settings_add_discovered_profiles( + &self, + request: DiscoveredProfilesRequest, + host: &DiscoveryHost, + prompt: &dyn SettingsPrompt, + ) -> Result { + 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 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()) + .map_err(|error| { + DesktopError::execution( + DesktopError::from_control(&error).code(), + format!("{}: {}", proposal.name(), refusal_text(&error)), + ) + })?; + } + } + 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()); + } + } + // 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), + )?; + { + 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); + return Err(if done == 0 { + cause + } else { + DesktopError::partly_applied("grants", done, folders.len(), &cause) + }); + } + expected = store.revision(); + } + } + self.discovery_view(host, Some(request.workspace_id), MissingWorkspace::Ignore) + } + + /// Discover on `host` and build the view against the store as it is now. + /// Discovery, and the access-control reads for a workspace, run while the + /// store is closed: the settings lock is held only to resolve the + /// workspace and to build the view. + fn discovery_view( + &self, + host: &DiscoveryHost, + workspace_id: Option, + missing: MissingWorkspace, + ) -> Result { + if host.platform() != current_platform()? { + return Err(DesktopError::discovery_unsupported()); + } + let found = discover_bounded(host); + let resolve = |store: &ControlStore| -> Result, DesktopError> { + let Some(id) = workspace_id else { + return Ok(None); + }; + match (store.registered_workspace(id), missing) { + (Some(workspace), _) => Ok(Some(workspace.id())), + (None, MissingWorkspace::Refuse) => Err(DesktopError::unknown_workspace()), + (None, MissingWorkspace::Ignore) => Ok(None), + } + }; + let workspace = match workspace_id { + Some(_) => resolve(&self.inner.open_or_create_control()?)?, + None => None, + }; + let needs: Vec> = found + .proposals + .iter() + .map(|proposal| { + proposal + .read_only_roots() + .iter() + .map(|root| { + workspace.map_or(RootGrantNeed::NotApplicable, |workspace| { + root_grant_need(workspace, root) + }) + }) + .collect() + }) + .collect(); + let store = self.inner.open_or_create_control()?; + // The workspace can be unregistered while the store is closed. + let workspace = match workspace { + Some(_) => resolve(&store)?, + None => None, + }; + // Core records a read-write grant only on the workspace's own folder + // (`ControlStore::check_grant_scope` when it is granted, and the + // replay `apply` in `omgcode_core::control::container`), so an active + // read-write grant of this workspace is the one on its folder. + let workspace_grant_active = + workspace + .filter(|_| CONTAINER_GRANTS_SUPPORTED) + .map(|workspace| { + store.container_grants().iter().any(|status| { + status.grant().workspace_id() == workspace + && status.grant().access() == ContainerGrantAccess::ReadWrite + && status.state() == ContainerGrantState::Active + }) + }); + let views = found + .proposals + .iter() + .zip(&needs) + .map(|(proposal, needs)| { + proposal_view(&store, proposal, workspace.map(|_| needs.as_slice())) + }) + .collect(); + Ok(ToolchainDiscovery { + overview: overview_of(&self.inner, store), + workspace_id: workspace.map(|workspace| *workspace.as_uuid()), + workspace_grant_active, + proposals: views, + omitted: found.omitted, + }) + } +} + +/// The profile platform of this build. +fn current_platform() -> Result { + omgcode_core::control::ProfilePlatform::current() + .ok_or_else(DesktopError::discovery_unsupported) +} + +/// This computer as discovery sees it: its standard install locations and +/// the operator's `PATH`, `JAVA_HOME`, `GOROOT`, and `RUSTUP_HOME`, read from +/// this process's environment. Repository configuration such as +/// `rust-toolchain.toml` is never read. +/// +/// # Errors +/// +/// `unsupported_platform` outside Linux and Windows. +pub fn discovery_host() -> Result { + DiscoveryHost::from_environment().ok_or_else(DesktopError::discovery_unsupported) +} + +#[cfg(test)] +mod tests { + use super::*; + + const DIGEST: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; + + #[test] + fn a_selection_is_one_to_eight_distinct_lowercase_digests() { + assert!(check_digests(&[DIGEST.to_owned()]).is_ok()); + for refused in [ + Vec::new(), + vec![DIGEST.to_owned(); 2], + vec![DIGEST.to_uppercase()], + vec![DIGEST[..63].to_owned()], + vec![format!("{}g", &DIGEST[..63])], + (0..9).map(|n| format!("{:064x}", n)).collect(), + ] { + let error = check_digests(&refused).expect_err("refused"); + assert_eq!(error.code(), "invalid_request", "{refused:?}"); + } + } + + #[test] + fn requests_refuse_unknown_fields_and_paths() { + for refused in [ + serde_json::json!({ "workspace_id": null, "roots": ["C:\\x"] }), + serde_json::json!({ "path": "/usr" }), + ] { + assert!(serde_json::from_value::(refused).is_err()); + } + assert!( + serde_json::from_value::(serde_json::json!({ + "revision": 1, "digests": [DIGEST], "workspace_id": null, "name": "rust" + })) + .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] + fn long_values_and_versions_are_cut_and_made_safe() { + let shown = bounded(&format!("{}\u{202e}x", "a".repeat(200)), SHOWN_VALUE_CHARS); + assert_eq!(shown.chars().count(), SHOWN_VALUE_CHARS + 1); + 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 735107a0..da73b259 100644 --- a/crates/omgcode-app/src/desktop/settings_execution.rs +++ b/crates/omgcode-app/src/desktop/settings_execution.rs @@ -161,7 +161,7 @@ pub struct ContainerRevokeRequest { impl DesktopError { /// Container grants exist only on Windows. - fn unsupported_platform() -> Self { + pub(super) fn unsupported_platform() -> Self { Self::execution( "unsupported_platform", "Container grants exist only on Windows.", @@ -175,7 +175,7 @@ impl DesktopError { /// Map a grant or revocation failure. The operating system's own text is /// never shown, because it can name a path or an account. - fn from_grant(error: &ControlError) -> Self { + pub(super) fn from_grant(error: &ControlError) -> Self { match error { ControlError::Container(_) => Self::execution( "container_access_failed", diff --git a/crates/omgcode-app/tests/desktop_settings_discovery.rs b/crates/omgcode-app/tests/desktop_settings_discovery.rs new file mode 100644 index 00000000..e95693f4 --- /dev/null +++ b/crates/omgcode-app/tests/desktop_settings_discovery.rs @@ -0,0 +1,810 @@ +//! 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. +//! +//! 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. + +mod common; + +use std::cell::RefCell; +use std::collections::VecDeque; +use std::fs; +use std::path::{Path, PathBuf}; + +use omgcode_app::TokenSource; +use omgcode_app::desktop::{ + Confirmation, DesktopConfig, DesktopError, DesktopService, DiscoveredGrantsRequest, + DiscoveredProfilesRequest, FolderPurpose, SettingsPrompt, SettingsRevisionRequest, + ToolchainDiscovery, ToolchainDiscoveryRequest, +}; +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}; + +/// Answers confirmations in order; any folder dialog or an unscripted +/// confirmation fails the test. +#[derive(Default)] +struct ScriptedPrompt { + answers: RefCell>, + shown: RefCell>, + during_confirm: RefCell>>, +} + +impl ScriptedPrompt { + fn answering(confirmed: bool) -> Self { + let prompt = Self::default(); + prompt.answers.borrow_mut().push_back(confirmed); + prompt + } + + fn silent() -> Self { + Self::default() + } + + fn meanwhile(self, action: impl FnOnce() + 'static) -> Self { + *self.during_confirm.borrow_mut() = Some(Box::new(action)); + self + } + + fn shown(&self) -> Vec { + self.shown.take() + } +} + +impl SettingsPrompt for ScriptedPrompt { + fn pick_folder(&self, _purpose: FolderPurpose, _start: Option<&Path>) -> Option { + panic!("discovery never opens a folder dialog"); + } + + fn confirm(&self, confirmation: &Confirmation) -> bool { + self.shown.borrow_mut().push(confirmation.clone()); + if let Some(action) = self.during_confirm.borrow_mut().take() { + action(); + } + self.answers + .borrow_mut() + .pop_front() + .expect("an unexpected confirmation") + } +} + +/// 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(), + endpoint: "http://127.0.0.1:1234/v1".to_owned(), + token_source: TokenSource::Environment, + stream: false, + }) + .expect("open desktop service") +} + +fn current_revision(data: &Path) -> u64 { + ControlStore::open_existing(data) + .expect("open") + .expect("store exists") + .revision() +} + +fn platform() -> ProfilePlatform { + ProfilePlatform::current().expect("tests run on Linux or Windows") +} + +fn program(stem: &str) -> String { + if cfg!(windows) { + format!("{stem}.exe") + } else { + stem.to_owned() + } +} + +/// A Go installation at `home` whose `VERSION` names `version`. +fn go_install(home: &Path, version: &str) { + fs::create_dir_all(home.join("bin")).expect("go bin"); + fs::write(home.join("bin").join(program("go")), b"").expect("go program"); + fs::write(home.join("VERSION"), format!("go{version}\ntime x\n")).expect("go version"); +} + +/// A computer laid out like this platform, beside the fixture's data and +/// development roots, with Go 1.23.4 in the standard place and Go 1.22.0 in +/// the operator's `~/sdk`. +struct Host { + base: PathBuf, + newest: PathBuf, + older: PathBuf, +} + +impl Host { + fn new(fixture: &Fixture) -> Self { + let base = fixture.data.parent().expect("temporary root").join("host"); + let (newest, home) = match platform() { + ProfilePlatform::Windows => { + fs::create_dir_all(base.join("Windows").join("System32")).expect("System32"); + ( + base.join("Program Files").join("Go"), + base.join("Users").join("operator"), + ) + } + ProfilePlatform::Linux => { + fs::create_dir_all(base.join("usr").join("bin")).expect("usr/bin"); + ( + base.join("usr").join("local").join("go"), + base.join("home").join("operator"), + ) + } + }; + let older = home.join("sdk").join("go1.22.0"); + go_install(&newest, "1.23.4"); + go_install(&older, "1.22.0"); + Self { + base, + newest, + older, + } + } + + fn discovery(&self) -> DiscoveryHost { + DiscoveryHost::rooted_at(platform(), &self.base) + } +} + +fn discover(fixture: &Fixture, host: &Host, workspace: Option) -> ToolchainDiscovery { + service(&fixture.data) + .settings_discover_toolchains( + ToolchainDiscoveryRequest { + workspace_id: workspace, + }, + &host.discovery(), + ) + .expect("discovered") +} + +fn digests_of(discovery: &ToolchainDiscovery) -> Vec { + discovery + .proposals + .iter() + .map(|proposal| proposal.digest.clone()) + .collect() +} + +fn add_request(revision: u64, digests: Vec) -> DiscoveredProfilesRequest { + DiscoveredProfilesRequest { + revision, + digests, + workspace_id: None, + } +} + +/// Register one workspace through the service; 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)) + .expect("registered") + .workspaces[0] + .workspace_id +} + +fn profile_count(data: &Path) -> usize { + ControlStore::open_existing(data) + .expect("open") + .expect("exists") + .profiles() + .len() +} + +#[test] +fn discovery_proposes_installed_toolchains_and_records_nothing() { + let fixture = Fixture::new(); + let host = Host::new(&fixture); + let before = current_revision(&fixture.data); + + let discovery = discover(&fixture, &host, None); + + let names: Vec<&str> = discovery + .proposals + .iter() + .map(|proposal| proposal.name.as_str()) + .collect(); + assert_eq!(names, ["go", "go-1.22.0"]); + let newest = &discovery.proposals[0]; + assert_eq!(newest.family_label, "Go"); + assert_eq!(newest.version.as_deref(), Some("1.23.4")); + assert_eq!(newest.digest.len(), 64); + assert_eq!(newest.refusal, None); + assert!(!newest.recorded); + // The installation and the system part, which every proposal lists. On + // Linux `usr/local/go` sits inside the system part's `usr`, so core drops + // the nested root and `usr` alone covers the installation. + let installation = host.newest.display().to_string(); + let roots: Vec<&str> = newest + .read_only_roots + .iter() + .map(|root| root.folder.as_str()) + .collect(); + let expected = match platform() { + ProfilePlatform::Windows => vec![ + installation.clone(), + host.base + .join("Windows") + .join("System32") + .display() + .to_string(), + ], + ProfilePlatform::Linux => vec![host.base.join("usr").display().to_string()], + }; + assert_eq!(roots, expected, "{newest:?}"); + let variables: Vec<(&str, &str)> = newest + .environment + .iter() + .map(|variable| (variable.name.as_str(), variable.value.as_str())) + .collect(); + assert!( + variables.contains(&("GOTOOLCHAIN", "local")), + "{variables:?}" + ); + assert!( + variables.contains(&("GOROOT", installation.as_str())), + "{variables:?}" + ); + assert!(!newest.notes.is_empty()); + // No workspace was selected, so no root reports container access. + let wire_view = json_of(&discovery); + for root in wire_view["proposals"][0]["read_only_roots"] + .as_array() + .expect("roots") + { + assert_eq!(root["grant"], "not_applicable"); + } + assert_eq!(wire_view["workspace_grant_active"], Value::Null); + assert_eq!(wire_view["omitted"], 0); + assert_eq!(discovery.overview.revision, before); + assert_eq!(current_revision(&fixture.data), before); + assert_eq!(profile_count(&fixture.data), 0); +} + +#[test] +fn the_view_sends_no_path_back_and_requests_carry_only_digests() { + let fixture = Fixture::new(); + let host = Host::new(&fixture); + let discovery = discover(&fixture, &host, None); + let digest = discovery.proposals[0].digest.clone(); + + // A request that names a folder, a root, or a variable is refused. + for refused in [ + json!({ "revision": 1, "digests": [digest], "workspace_id": null, "roots": ["x"] }), + json!({ "revision": 1, "digests": [digest], "workspace_id": null, "environment": [] }), + ] { + assert!(serde_json::from_value::(refused).is_err()); + } +} + +#[test] +fn selected_proposals_are_added_after_one_confirmation_that_lists_everything() { + let fixture = Fixture::new(); + let host = Host::new(&fixture); + let discovery = discover(&fixture, &host, None); + let before = discovery.overview.revision; + let prompt = ScriptedPrompt::answering(true); + + let after = service(&fixture.data) + .settings_add_discovered_profiles( + add_request(before, digests_of(&discovery)), + &host.discovery(), + &prompt, + ) + .expect("added"); + + let shown = prompt.shown(); + assert_eq!(shown.len(), 1, "one confirmation for the batch"); + let message = &shown[0].message; + for expected in [ + "2 toolchain profile(s)", + "go (Go, 1.23.4)", + "go-1.22.0 (Go, 1.22.0)", + "Read-only roots:", + "PATH entries:", + "GOTOOLCHAIN=local", + "GOROOT=", + "go1.22.0", + "ran no program", + "grants nothing", + "plain text", + ] { + assert!(message.contains(expected), "{expected} in {message}"); + } + // One record per profile, at consecutive revisions. + assert_eq!(after.overview.revision, before + 2); + let store = ControlStore::open_existing(&fixture.data) + .expect("open") + .expect("exists"); + let newest = store.profile("go").expect("go recorded").profile(); + let goroot = newest + .environment() + .iter() + .find(|variable| variable.name() == "GOROOT") + .expect("GOROOT"); + assert_eq!(Path::new(goroot.value()), host.newest); + let older = store + .profile("go-1.22.0") + .expect("older recorded") + .profile(); + assert!( + older.environment().iter().any( + |variable| variable.name() == "GOROOT" && Path::new(variable.value()) == host.older + ) + ); + // The refreshed list shows both as recorded, and core now refuses them. + for proposal in &after.proposals { + assert!(proposal.recorded, "{proposal:?}"); + assert!(proposal.refusal.is_some(), "{proposal:?}"); + } +} + +#[test] +fn a_declined_confirmation_records_nothing() { + let fixture = Fixture::new(); + let host = Host::new(&fixture); + let discovery = discover(&fixture, &host, None); + let before = discovery.overview.revision; + let prompt = ScriptedPrompt::answering(false); + + let error = service(&fixture.data) + .settings_add_discovered_profiles( + add_request(before, digests_of(&discovery)), + &host.discovery(), + &prompt, + ) + .expect_err("declined"); + + assert_eq!(error.code(), "cancelled"); + assert_eq!(current_revision(&fixture.data), before); + assert_eq!(profile_count(&fixture.data), 0); +} + +#[test] +fn a_stale_revision_or_a_bad_selection_is_refused_before_any_dialog() { + let fixture = Fixture::new(); + let host = Host::new(&fixture); + let discovery = discover(&fixture, &host, None); + let before = discovery.overview.revision; + let digests = digests_of(&discovery); + + for (request, code) in [ + (add_request(before + 1, digests.clone()), "stale_revision"), + (add_request(before, Vec::new()), "invalid_request"), + ( + add_request(before, vec![digests[0].clone(), digests[0].clone()]), + "invalid_request", + ), + ( + add_request(before, vec!["ab".repeat(32).to_uppercase()]), + "invalid_request", + ), + ] { + let error = service(&fixture.data) + .settings_add_discovered_profiles(request, &host.discovery(), &ScriptedPrompt::silent()) + .expect_err("refused"); + assert_eq!(error.code(), code, "{error:?}"); + } + assert_eq!(profile_count(&fixture.data), 0); +} + +#[test] +fn a_selection_made_before_the_installations_changed_is_refused() { + let fixture = Fixture::new(); + let host = Host::new(&fixture); + let discovery = discover(&fixture, &host, None); + // The newest installation is upgraded after the list was made. + go_install(&host.newest, "1.23.5"); + + let error = service(&fixture.data) + .settings_add_discovered_profiles( + add_request(discovery.overview.revision, digests_of(&discovery)), + &host.discovery(), + &ScriptedPrompt::silent(), + ) + .expect_err("changed"); + + assert_eq!(error.code(), "discovery_changed"); + assert_eq!(profile_count(&fixture.data), 0); +} + +#[test] +fn a_proposal_core_would_refuse_shows_its_reason_and_is_refused_before_any_dialog() { + let fixture = Fixture::new(); + let host = Host::new(&fixture); + { + let mut store = ControlStore::open_existing(&fixture.data) + .expect("open") + .expect("exists"); + let revision = store.revision(); + store + .add_profile( + &ProfileDeclaration { + name: "GO".into(), + read_only_roots: vec![host.older.clone()], + path_entries: Vec::new(), + environment: Vec::new(), + }, + revision, + ) + .expect("an operator's own profile"); + } + + let discovery = discover(&fixture, &host, None); + let taken = &discovery.proposals[0]; + assert_eq!(taken.name, "go"); + assert!(taken.recorded, "names compare case-insensitively"); + let reason = taken.refusal.as_deref().expect("refused"); + assert!(reason.contains("already"), "{reason}"); + assert_eq!(discovery.proposals[1].refusal, None); + + let error = service(&fixture.data) + .settings_add_discovered_profiles( + add_request(discovery.overview.revision, digests_of(&discovery)), + &host.discovery(), + &ScriptedPrompt::silent(), + ) + .expect_err("refused"); + assert_eq!(error.code(), "control"); + assert!(error.message().starts_with("go: "), "{}", error.message()); + assert_eq!(profile_count(&fixture.data), 1); +} + +#[test] +fn a_change_made_while_the_confirmation_is_open_is_refused_as_stale() { + let fixture = Fixture::new(); + let host = Host::new(&fixture); + let discovery = discover(&fixture, &host, None); + let data = fixture.data.clone(); + let root = host.older.clone(); + let prompt = ScriptedPrompt::answering(true).meanwhile(move || { + let mut store = ControlStore::open_existing(&data) + .expect("open") + .expect("exists"); + let revision = store.revision(); + store + .add_profile( + &ProfileDeclaration { + name: "intervening".into(), + read_only_roots: vec![root], + path_entries: Vec::new(), + environment: Vec::new(), + }, + revision, + ) + .expect("an intervening change"); + }); + + let error = service(&fixture.data) + .settings_add_discovered_profiles( + add_request(discovery.overview.revision, digests_of(&discovery)), + &host.discovery(), + &prompt, + ) + .expect_err("stale"); + + assert_eq!(error.code(), "stale_revision"); + assert_eq!(profile_count(&fixture.data), 1, "only the intervening one"); +} + +#[test] +fn a_batch_that_stops_partway_says_how_many_were_recorded() { + let fixture = Fixture::new(); + let host = Host::new(&fixture); + // 31 of the 32 profiles allowed: each proposal passes its own check, but + // only the first of two fits. + { + let mut store = ControlStore::open_existing(&fixture.data) + .expect("open") + .expect("exists"); + for index in 0..31 { + let revision = store.revision(); + store + .add_profile( + &ProfileDeclaration { + name: format!("filler-{index}"), + read_only_roots: vec![host.older.clone()], + path_entries: Vec::new(), + environment: Vec::new(), + }, + revision, + ) + .expect("filler"); + } + } + let discovery = discover(&fixture, &host, None); + assert!( + discovery + .proposals + .iter() + .all(|proposal| proposal.refusal.is_none()) + ); + + let error = service(&fixture.data) + .settings_add_discovered_profiles( + add_request(discovery.overview.revision, digests_of(&discovery)), + &host.discovery(), + &ScriptedPrompt::answering(true), + ) + .expect_err("the second does not fit"); + + assert_eq!(error.code(), "control"); + assert!( + error + .message() + .starts_with("1 of 2 profiles were recorded before this failure"), + "{}", + error.message() + ); + assert_eq!(profile_count(&fixture.data), 32); +} + +#[test] +fn an_unknown_workspace_is_refused() { + let fixture = Fixture::new(); + let host = Host::new(&fixture); + + let error: DesktopError = service(&fixture.data) + .settings_discover_toolchains( + ToolchainDiscoveryRequest { + workspace_id: Some(Uuid::new_v4()), + }, + &host.discovery(), + ) + .expect_err("unknown"); + + assert_eq!(error.code(), "unknown_workspace"); +} + +#[test] +fn adding_with_an_unknown_workspace_is_refused_before_any_dialog() { + let fixture = Fixture::new(); + let host = Host::new(&fixture); + let discovery = discover(&fixture, &host, None); + let before = discovery.overview.revision; + + let error = service(&fixture.data) + .settings_add_discovered_profiles( + DiscoveredProfilesRequest { + revision: before, + digests: digests_of(&discovery), + workspace_id: Some(Uuid::new_v4()), + }, + &host.discovery(), + &ScriptedPrompt::silent(), + ) + .expect_err("unknown"); + + // Refused before the dialog and before any profile, so the window never + // reports a failure for a change that was recorded. + assert_eq!(error.code(), "unknown_workspace"); + assert_eq!(profile_count(&fixture.data), 0); + assert_eq!(current_revision(&fixture.data), before); +} + +#[cfg(windows)] +#[test] +fn on_windows_each_root_says_what_the_workspace_container_needs() { + let fixture = Fixture::new(); + let host = Host::new(&fixture); + let workspace = with_workspace(&fixture); + + let discovery = discover(&fixture, &host, Some(workspace)); + + assert_eq!(discovery.workspace_id, Some(workspace)); + // The workspace has no recorded read-write grant on its own folder. + assert_eq!(discovery.workspace_grant_active, Some(false)); + let wire_view = json_of(&discovery); + for proposal in wire_view["proposals"].as_array().expect("proposals") { + for root in proposal["read_only_roots"].as_array().expect("roots") { + // The fixture folders are this account's own, and nothing grants + // the container access to them. + assert_eq!(root["grant"], "needs_grant", "{root}"); + } + } +} + +#[cfg(windows)] +#[test] +fn on_windows_a_grant_confirmation_names_the_workspace_and_every_folder() { + let fixture = Fixture::new(); + let host = Host::new(&fixture); + let workspace = with_workspace(&fixture); + let discovery = discover(&fixture, &host, Some(workspace)); + let before = discovery.overview.revision; + let prompt = ScriptedPrompt::answering(false); + + let error = service(&fixture.data) + .settings_grant_discovered_roots( + DiscoveredGrantsRequest { + revision: before, + workspace_id: workspace, + digests: digests_of(&discovery), + }, + &host.discovery(), + &prompt, + ) + .expect_err("declined"); + + assert_eq!(error.code(), "cancelled"); + let shown = prompt.shown(); + assert_eq!(shown.len(), 1); + let message = &shown[0].message; + for expected in [ + "project", + "System32", + "Go", + "go1.22.0", + "read and execute", + "access-control list", + ] { + assert!(message.contains(expected), "{expected} in {message}"); + } + // System32 is listed once although both proposals need it. + assert_eq!(message.matches("System32").count(), 1, "{message}"); + let store = ControlStore::open_existing(&fixture.data) + .expect("open") + .expect("exists"); + assert!(store.container_grants().is_empty()); + assert_eq!(store.revision(), before); +} + +#[cfg(windows)] +#[test] +fn on_windows_a_grant_for_an_unregistered_workspace_is_refused_before_any_dialog() { + let fixture = Fixture::new(); + let host = Host::new(&fixture); + let discovery = discover(&fixture, &host, None); + + let error = service(&fixture.data) + .settings_grant_discovered_roots( + DiscoveredGrantsRequest { + revision: discovery.overview.revision, + workspace_id: Uuid::new_v4(), + digests: digests_of(&discovery), + }, + &host.discovery(), + &ScriptedPrompt::silent(), + ) + .expect_err("unknown"); + + assert_eq!(error.code(), "unknown_workspace"); +} + +#[cfg(windows)] +#[test] +fn on_windows_a_folder_core_would_not_grant_is_refused_before_any_dialog() { + let fixture = Fixture::new(); + let host = Host::new(&fixture); + let workspace = with_workspace(&fixture); + // A Go that the operator's GOROOT names inside the development root, + // beside the workspace rather than in it. + let inside = fixture.development.join("tools").join("go"); + go_install(&inside, "1.24.0"); + let request = service(&fixture.data) + .settings_discover_toolchains( + ToolchainDiscoveryRequest { + workspace_id: Some(workspace), + }, + &host.discovery().with_goroot(inside.clone()), + ) + .expect("discovered"); + let shown_root = inside.display().to_string(); + let proposal = request + .proposals + .iter() + .find(|proposal| { + proposal + .read_only_roots + .iter() + .any(|root| root.folder == shown_root) + }) + .expect("the GOROOT proposal"); + // Core would refuse it as a profile too, 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 { + revision: before, + workspace_id: workspace, + digests: vec![proposal.digest.clone()], + }, + &host.discovery().with_goroot(inside), + &ScriptedPrompt::silent(), + ) + .expect_err("core refuses the grant"); + + assert_eq!(error.code(), "control"); + assert!( + error.message().starts_with(&shown_root), + "{}", + error.message() + ); + assert!( + error.message().contains("development root"), + "{}", + error.message() + ); + let store = ControlStore::open_existing(&fixture.data) + .expect("open") + .expect("exists"); + assert!(store.container_grants().is_empty()); + assert_eq!(store.revision(), before); +} + +#[cfg(not(windows))] +#[test] +fn off_windows_grants_are_refused_and_roots_need_none() { + let fixture = Fixture::new(); + let host = Host::new(&fixture); + let workspace = with_workspace(&fixture); + let discovery = discover(&fixture, &host, Some(workspace)); + assert_eq!(discovery.workspace_grant_active, None); + let wire_view = json_of(&discovery); + for root in wire_view["proposals"][0]["read_only_roots"] + .as_array() + .expect("roots") + { + 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] +fn a_host_laid_out_for_the_other_platform_is_refused() { + let fixture = Fixture::new(); + let other = match platform() { + ProfilePlatform::Windows => ProfilePlatform::Linux, + ProfilePlatform::Linux => ProfilePlatform::Windows, + }; + let base = fixture.data.parent().expect("root").join("other"); + fs::create_dir_all(&base).expect("other host"); + + let error = service(&fixture.data) + .settings_discover_toolchains( + ToolchainDiscoveryRequest::default(), + &DiscoveryHost::rooted_at(other, &base), + ) + .expect_err("refused"); + + assert_eq!(error.code(), "unsupported_platform"); +} diff --git a/crates/omgcode-core/src/control.rs b/crates/omgcode-core/src/control.rs index b736f099..219f0eb2 100644 --- a/crates/omgcode-core/src/control.rs +++ b/crates/omgcode-core/src/control.rs @@ -41,7 +41,7 @@ pub use approval::{ pub use container::{ ContainerGrant, ContainerGrantAccess, ContainerGrantState, ContainerGrantStatus, - ContainerRevocation, container_name, + ContainerRevocation, RootGrantNeed, container_name, root_grant_need, }; pub use credential::{ CredentialBackend, CredentialBinding, CredentialError, CredentialId, CredentialStore, diff --git a/crates/omgcode-core/src/control/container.rs b/crates/omgcode-core/src/control/container.rs index e777ab19..d3753374 100644 --- a/crates/omgcode-core/src/control/container.rs +++ b/crates/omgcode-core/src/control/container.rs @@ -12,7 +12,7 @@ //! `omgcode_platform::process::run_confined` runs a program in the container. //! See `docs/execution.md` and ADR-0029. -use std::path::Path; +use std::path::{Path, PathBuf}; use omgcode_platform::container::{ self as platform, CONTAINER_GRANTS_SUPPORTED, ContainerAccess, ContainerName, @@ -37,6 +37,52 @@ pub(super) const GRANT_EVENT_RESERVE_BYTES: usize = 512; const MAX_SID_CHARS: usize = 184; const CONTAINER_PREFIX: &str = "OMGCode.Workspace."; +/// What a workspace's container needs before a run can read a toolchain +/// root, as the `settings` window's toolchain discovery shows it (ADR-0103). +#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum RootGrantNeed { + /// Not Windows: there are no container grants, and the Linux runner + /// exposes profile roots itself. + NotApplicable, + /// The container can already read and execute it, because every + /// application package can or a grant covers it. + Readable, + /// A read-execute grant is needed, and this account can change the + /// folder's access-control list. + NeedsGrant, + /// A grant is needed, but this account cannot change the folder's + /// access-control list. An administrator can, or a user-owned copy of the + /// toolchain can be granted instead. + NeedsAdministrator, + /// The access-control list could not be read, for example because the + /// folder is a link. + Unknown, +} + +/// Whether the container of `workspace_id` can read `path` now and, when it +/// cannot, whether this account could grant it. This only reads access-control +/// lists and opens the folder for the access a grant uses; nothing is changed +/// or recorded. The answer can change before a grant is attempted. +#[must_use] +pub fn root_grant_need(workspace_id: WorkspaceId, path: &Path) -> RootGrantNeed { + if !CONTAINER_GRANTS_SUPPORTED { + return RootGrantNeed::NotApplicable; + } + let Ok(name) = container_name(workspace_id) else { + return RootGrantNeed::Unknown; + }; + match platform::granted_access(path, &name) { + Ok(Some(_)) => RootGrantNeed::Readable, + Ok(None) => match platform::can_change_access(path) { + Ok(true) => RootGrantNeed::NeedsGrant, + Ok(false) => RootGrantNeed::NeedsAdministrator, + Err(_) => RootGrantNeed::Unknown, + }, + Err(_) => RootGrantNeed::Unknown, + } +} + /// Access recorded for one grant. #[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)] #[serde(rename_all = "snake_case")] @@ -234,28 +280,7 @@ impl ControlStore { expected_revision: u64, ) -> Result { self.check_revision(expected_revision)?; - if !CONTAINER_GRANTS_SUPPORTED { - return Err(ControlError::Container(std::io::Error::new( - std::io::ErrorKind::Unsupported, - "container grants exist only on Windows", - ))); - } - let workspace = self - .workspace(workspace_id) - .ok_or(ControlError::UnknownWorkspace)? - .clone(); - self.check_directory_scope(&workspace.directory)?; - let directory = DirectoryRecord::capture(path)?; - self.check_storage_overlap(&directory)?; - self.check_grant_scope(&workspace.directory, &directory, access)?; - if self.snapshot.container_grants.iter().any(|status| { - status.grant.workspace_id == workspace_id - && status.grant.directory.same_directory(&directory) - }) { - return Err(ControlError::GrantRefused( - "this directory already has a grant for the workspace; revoke it first", - )); - } + let directory = self.prepare_grant(workspace_id, path, access, &[])?; let name = container_name(workspace_id)?; let grant = ContainerGrant { id: Uuid::new_v4(), @@ -286,6 +311,90 @@ impl ControlStore { Ok(grant) } + /// Apply the rules [`Self::grant_container_access`] checks before it + /// records anything to granting each of `paths`, in order, to + /// `workspace_id` with `access`, and record and change nothing: the + /// workspace, each folder's storage and development-root scope, an + /// existing grant on the same folder or an earlier one in the batch, and + /// the grant limits counting the whole batch. The revision is not checked, + /// and the answer can change before a grant is made. + /// + /// # Errors + /// + /// The index of the first folder core would refuse, with core's reason. + pub fn check_container_grants( + &self, + workspace_id: WorkspaceId, + paths: &[PathBuf], + access: ContainerGrantAccess, + ) -> Result<(), (usize, ControlError)> { + let mut batch: Vec = Vec::with_capacity(paths.len()); + for (index, path) in paths.iter().enumerate() { + let directory = self + .prepare_grant(workspace_id, path, access, &batch) + .map_err(|error| (index, error))?; + batch.push(directory); + } + Ok(()) + } + + /// Every check a grant passes before its intent is recorded. `batch` is + /// the folders that earlier grants of the same batch would record first. + fn prepare_grant( + &self, + workspace_id: WorkspaceId, + path: &Path, + access: ContainerGrantAccess, + batch: &[DirectoryRecord], + ) -> Result { + if !CONTAINER_GRANTS_SUPPORTED { + return Err(ControlError::Container(std::io::Error::new( + std::io::ErrorKind::Unsupported, + "container grants exist only on Windows", + ))); + } + let workspace = self + .workspace(workspace_id) + .ok_or(ControlError::UnknownWorkspace)?; + self.check_directory_scope(&workspace.directory)?; + let directory = DirectoryRecord::capture(path)?; + self.check_storage_overlap(&directory)?; + self.check_grant_scope(&workspace.directory, &directory, access)?; + if self.snapshot.container_grants.iter().any(|status| { + status.grant.workspace_id == workspace_id + && status.grant.directory.same_directory(&directory) + }) { + return Err(ControlError::GrantRefused( + "this directory already has a grant for the workspace; revoke it first", + )); + } + if batch + .iter() + .any(|earlier| earlier.same_directory(&directory)) + { + return Err(ControlError::GrantRefused( + "this directory is granted twice in one batch", + )); + } + let held = self + .snapshot + .container_grants + .iter() + .filter(|status| status.grant.workspace_id == workspace_id) + .count(); + if held + batch.len() >= MAX_GRANTS_PER_WORKSPACE { + return Err(ControlError::GrantRefused( + "a workspace container can hold at most 32 grants; revoke one first", + )); + } + if self.snapshot.container_grants.len() + batch.len() >= MAX_GRANTS { + return Err(ControlError::GrantRefused( + "at most 256 container grants can be recorded; revoke one first", + )); + } + Ok(directory) + } + /// Remove a recorded grant from its directory and record the outcome. /// /// This needs no settings revision and can run when the journal is diff --git a/crates/omgcode-core/src/control/container/tests.rs b/crates/omgcode-core/src/control/container/tests.rs index 1dcd2500..fbc736a9 100644 --- a/crates/omgcode-core/src/control/container/tests.rs +++ b/crates/omgcode-core/src/control/container/tests.rs @@ -264,6 +264,15 @@ fn other_platforms_refuse_grants_without_recording_them() { matches!(&error, ControlError::Container(cause) if cause.kind() == std::io::ErrorKind::Unsupported), "{error}" ); + let checked = store.check_container_grants( + workspace, + std::slice::from_ref(&scene.toolchain), + ContainerGrantAccess::ReadExecute, + ); + assert!( + matches!(&checked, Err((0, ControlError::Container(cause))) if cause.kind() == std::io::ErrorKind::Unsupported), + "{checked:?}" + ); assert_eq!(store.entries.len(), events); } @@ -471,6 +480,79 @@ mod windows { store.revoke_container_grant(inside.id()).expect("revoke"); } + #[test] + fn a_grant_batch_is_checked_with_every_grant_rule_and_records_nothing() { + let scene = Scene::new(); + let (mut store, workspace) = scene.store(); + let read = ContainerGrantAccess::ReadExecute; + let outside = scene.toolchain.parent().expect("temporary root"); + let second = outside.join("second"); + fs::create_dir(&second).expect("second"); + let events = store.entries.len(); + + store + .check_container_grants(workspace, &[scene.toolchain.clone(), second.clone()], read) + .expect("both folders can be granted"); + let refusals: [(&str, Vec, usize); 3] = [ + ( + "another workspace under the development root", + vec![scene.toolchain.clone(), scene.other.clone()], + 1, + ), + ( + "one folder twice", + vec![scene.toolchain.clone(), scene.toolchain.clone()], + 1, + ), + ("application storage", vec![scene.data.clone()], 0), + ]; + for (name, batch, refused_at) in refusals { + let (index, error) = store + .check_container_grants(workspace, &batch, read) + .expect_err(name); + assert_eq!(index, refused_at, "{name}: {error}"); + assert!( + matches!( + error, + ControlError::GrantRefused(_) | ControlError::StorageOverlap + ), + "{name}: {error}" + ); + } + assert!(matches!( + store.check_container_grants(WorkspaceId::fresh(), std::slice::from_ref(&second), read), + Err((0, ControlError::UnknownWorkspace)) + )); + assert_eq!(store.entries.len(), events, "a check records nothing"); + assert_eq!(access(&scene.toolchain, workspace), None); + + // A grant already recorded on the folder, which a failed grant + // leaves `pending` with no access-control entry. + store.test_record_grant(workspace, &scene.toolchain, read); + let (index, error) = store + .check_container_grants(workspace, std::slice::from_ref(&scene.toolchain), read) + .expect_err("already granted"); + assert_eq!(index, 0); + assert!(error.to_string().contains("revoke it first"), "{error}"); + + // The workspace limit counts the folders earlier in the batch. + for filler in 1..MAX_GRANTS_PER_WORKSPACE - 1 { + let folder = outside.join(format!("filler-{filler}")); + fs::create_dir(&folder).expect("filler"); + store.test_record_grant(workspace, &folder, read); + } + let third = outside.join("third"); + fs::create_dir(&third).expect("third"); + store + .check_container_grants(workspace, std::slice::from_ref(&second), read) + .expect("one more fits"); + let (index, error) = store + .check_container_grants(workspace, &[second, third], read) + .expect_err("two more do not"); + assert_eq!(index, 1); + assert!(error.to_string().contains("at most 32 grants"), "{error}"); + } + #[test] fn a_pending_grant_with_an_unknown_outcome_can_be_revoked() { let scene = Scene::new(); diff --git a/crates/omgcode-core/src/control/profile.rs b/crates/omgcode-core/src/control/profile.rs index 082d5410..0a784ca6 100644 --- a/crates/omgcode-core/src/control/profile.rs +++ b/crates/omgcode-core/src/control/profile.rs @@ -209,6 +209,31 @@ impl ControlStore { expected_revision: u64, ) -> Result { self.check_revision(expected_revision)?; + let profile = self.prepare_profile(declaration)?; + self.append( + Action::ProfileAdded { + profile: profile.clone(), + }, + self.next_revision()?, + )?; + Ok(profile) + } + + /// Check `declaration` exactly as [`add_profile`](Self::add_profile) + /// would, apart from the revision, without recording anything. Each + /// directory is captured and checked as it is now; `add_profile` captures + /// and checks it again. Used to show which discovered proposals core + /// would refuse, and why (ADR-0103). + pub fn check_profile(&self, declaration: &ProfileDeclaration) -> Result<(), ControlError> { + self.prepare_profile(declaration).map(|_| ()) + } + + /// Build the profile `declaration` describes after every check + /// `add_profile` makes besides the revision. + fn prepare_profile( + &self, + declaration: &ProfileDeclaration, + ) -> Result { let platform = ProfilePlatform::current().ok_or(ControlError::ProfileRefused( "toolchain profiles exist only on Linux and Windows", ))?; @@ -217,6 +242,11 @@ impl ControlStore { "a profile with this name already exists; remove it first", )); } + if self.snapshot.profiles.len() >= MAX_PROFILES { + return Err(ControlError::ProfileRefused( + "at most 32 profiles can be recorded; remove one first", + )); + } let mut roots: Vec = Vec::new(); for path in &declaration.read_only_roots { let root = DirectoryRecord::capture(path)?; @@ -264,12 +294,6 @@ impl ControlStore { } } validate_shape(&profile)?; - self.append( - Action::ProfileAdded { - profile: profile.clone(), - }, - self.next_revision()?, - )?; Ok(profile) } diff --git a/crates/omgcode-core/src/control/profile/tests.rs b/crates/omgcode-core/src/control/profile/tests.rs index 5b08e52b..9ea957b6 100644 --- a/crates/omgcode-core/src/control/profile/tests.rs +++ b/crates/omgcode-core/src/control/profile/tests.rs @@ -304,3 +304,81 @@ fn reserved_names_and_profile_names_are_checked_case_insensitively() { assert!(!valid_profile_name("-x")); assert!(!valid_profile_name("a b")); } + +/// `check_profile` refuses what `add_profile` refuses, for the same reason, +/// and records nothing either way (ADR-0103). +#[test] +fn checking_a_profile_applies_every_add_rule_and_records_nothing() { + let mut scene = scene(); + // The open store locks the journal on Windows, so compare its length. + let journal = fs::metadata(scene.data.join(FILE_NAME)) + .expect("journal") + .len(); + scene + .store + .check_profile(&declaration(&scene)) + .expect("an acceptable declaration"); + assert_eq!(scene.store.revision(), 1); + assert!(scene.store.profiles().is_empty()); + assert_eq!( + fs::metadata(scene.data.join(FILE_NAME)) + .expect("journal") + .len(), + journal + ); + + let inside = declaration_with(&scene.root.join("app"), "inside"); + let reserved = ProfileDeclaration { + environment: vec![("Path".into(), "x".into())], + ..declaration(&scene) + }; + let outside_entry = ProfileDeclaration { + path_entries: vec![scene.root.clone()], + ..declaration(&scene) + }; + for refused in [inside, reserved, outside_entry] { + let checked = scene.store.check_profile(&refused).expect_err("refused"); + let added = scene.store.add_profile(&refused, 1).expect_err("refused"); + assert_eq!(checked.to_string(), added.to_string()); + } + scene + .store + .add_profile(&declaration(&scene), 1) + .expect("profile"); + let duplicate = scene + .store + .check_profile(&declaration(&scene)) + .expect_err("the name is recorded"); + assert!( + duplicate.to_string().contains("already exists"), + "{duplicate}" + ); +} + +/// The 33rd profile is refused with a reason before anything is appended. +#[test] +fn the_profile_limit_is_refused_with_a_reason() { + let mut scene = scene(); + for index in 0..MAX_PROFILES { + let revision = scene.store.revision(); + scene + .store + .add_profile( + &declaration_with(&scene.tools, &format!("p{index}")), + revision, + ) + .expect("profile within the limit"); + } + let revision = scene.store.revision(); + let over = declaration_with(&scene.tools, "one-more"); + let checked = scene + .store + .check_profile(&over) + .expect_err("over the limit"); + assert!( + matches!(checked, ControlError::ProfileRefused(reason) if reason.contains("at most 32")), + "{checked}" + ); + assert!(scene.store.add_profile(&over, revision).is_err()); + assert_eq!(scene.store.revision(), revision); +} diff --git a/crates/omgcode-core/src/lib.rs b/crates/omgcode-core/src/lib.rs index 8de6ba99..a9e87969 100644 --- a/crates/omgcode-core/src/lib.rs +++ b/crates/omgcode-core/src/lib.rs @@ -23,6 +23,7 @@ pub mod skills; mod storage; #[cfg(test)] mod test_support; +pub mod toolchain_discovery; pub mod turn; pub mod web_fetch; mod workspace; diff --git a/crates/omgcode-core/src/toolchain_discovery.rs b/crates/omgcode-core/src/toolchain_discovery.rs new file mode 100644 index 00000000..db21c10b --- /dev/null +++ b/crates/omgcode-core/src/toolchain_discovery.rs @@ -0,0 +1,1032 @@ +//! Discovery of installed language toolchains (ADR-0103). +//! +//! A trusted, host-side service for the desktop `settings` window. It looks in +//! each family's standard install locations, in the operator's own `PATH`, and +//! in the operator's `RUSTUP_HOME`, `JAVA_HOME`, and `GOROOT`, and proposes +//! toolchain profiles for the operator to select and confirm. +//! +//! What it does and does not do: +//! +//! - It lists directories, checks that files exist, and reads a few small +//! plain-text files that installers write, such as rustup's own +//! `settings.toml`, a JDK's `release`, and Go's `VERSION`, each bounded. It +//! starts no program, runs no version probe, and reads no registry key. +//! - It never reads repository configuration such as `rust-toolchain.toml`, +//! `.nvmrc`, `go.mod`, or `.python-version`, and never looks inside a +//! workspace on its own. A folder that the operator's `PATH`, `JAVA_HOME`, +//! `GOROOT`, or `RUSTUP_HOME` names is read like any install folder, its +//! installer files included, even inside the development root; core +//! refuses such a folder as a toolchain root before any confirmation, and +//! the window shows that refusal. +//! - No proposed root is itself a link. Core records a root by its resolved +//! identity, so a linked root, such as a `JAVA_HOME` that names a link, +//! would be recorded at a path the confirmation never showed; such a +//! candidate is left out. +//! - A proposal grants nothing. Adding one goes through +//! [`ControlStore::add_profile`](crate::control::ControlStore::add_profile) +//! with the operator's native confirmation and expected revision, which +//! captures and checks every directory again. +//! +//! Each family has one detector in a fixed table; adding a family adds a module +//! and one table entry. The shared flow adds the system part every confined +//! run needs, removes nested and duplicate directories, names the proposals, +//! and applies the bounds. + +use std::fs; +use std::io::Read; +use std::path::{Component, Path, PathBuf}; + +use serde::Serialize; +use sha2::{Digest, Sha256}; + +use crate::control::{MAX_PROFILE_NAME_CHARS, ProfileDeclaration, ProfilePlatform}; + +mod c_cpp; +mod dotnet; +mod go; +mod java; +mod node; +mod perl; +mod python; +mod ruby; +mod rust; + +#[cfg(test)] +mod tests; + +/// Most proposals one discovery returns; no more profiles can be recorded. +pub const MAX_PROPOSALS: usize = 32; +/// Most installations proposed under one base name, such as `python`. +const MAX_PER_NAME: usize = 8; +/// Most directories kept from one listing, the first by name. +const MAX_LISTED_ENTRIES: usize = 512; +/// Most entries examined in one listing, in the order the filesystem returns +/// them. Large system directories such as `/usr/lib` hold a few thousand. +const MAX_SCANNED_ENTRIES: usize = 16_384; +/// Most operator `PATH` entries considered. +const MAX_SEARCH_DIRECTORIES: usize = 256; +/// Most bytes read from one installer-written text file. +const MAX_TEXT_BYTES: u64 = 64 * 1024; + +/// The detectors, one per family, in the order their proposals are listed. +/// Each looks only at the host it is given and returns its candidates; the +/// shared flow in [`discover`] does everything else. +const DETECTORS: [fn(&DiscoveryHost) -> Vec; 9] = [ + rust::detect, + c_cpp::detect, + java::detect, + python::detect, + perl::detect, + go::detect, + node::detect, + dotnet::detect, + ruby::detect, +]; + +/// A language family that discovery can propose a profile for. +#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum ToolchainFamily { + /// Rust toolchains installed by rustup. + Rust, + /// MSVC, Clang, and GCC. + CCpp, + /// JDKs and Java runtimes. + Java, + /// CPython. + Python, + /// Perl. + Perl, + /// Go. + Go, + /// Node.js. + Node, + /// .NET. + DotNet, + /// Ruby. + Ruby, +} + +impl ToolchainFamily { + /// A fixed display label. + #[must_use] + pub const fn label(self) -> &'static str { + match self { + Self::Rust => "Rust", + Self::CCpp => "C and C++", + Self::Java => "Java", + Self::Python => "Python", + Self::Perl => "Perl", + Self::Go => "Go", + Self::Node => "Node.js", + Self::DotNet => ".NET", + Self::Ruby => "Ruby", + } + } +} + +/// A fixed remark about a proposal. None of them changes what is recorded. +#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum ProposalNote { + /// This kind of toolchain has not passed the confined acceptance runs. + NotQualified, + /// A Windows MSVC-target toolchain, but no MSVC compiler and Windows SDK + /// were found to link with. + NoMsvc, + /// Package downloads fail in an offline run. + OfflineDependencies, + /// Node on Windows: children with piped output never return. + NodeWindowsChildren, + /// A Java runtime without `javac`. + JavaRuntimeOnly, + /// A .NET runtime without an SDK. + DotnetRuntimeOnly, +} + +impl ProposalNote { + /// The fixed text shown with the proposal. + #[must_use] + pub const fn text(self) -> &'static str { + match self { + Self::NotQualified => { + "This toolchain has not passed OMGCode's confined acceptance runs, so it may need roots or variables that are not proposed here." + } + Self::NoMsvc => { + "No MSVC compiler and Windows SDK were found, so linking fails. Install the Visual Studio C++ build tools and generate the list again." + } + Self::OfflineDependencies => { + "Runs are offline unless the trusted CLI passes --network, and model runs never are. Dependencies that are not already in the workspace, such as crates from crates.io, fail to download." + } + Self::NodeWindowsChildren => { + "On Windows, a child process with piped output never returns inside the container; run node --test with --test-isolation=none." + } + Self::JavaRuntimeOnly => "No javac was found: this is a runtime without the compiler.", + Self::DotnetRuntimeOnly => { + "No .NET SDK was found: this is a runtime, so dotnet build is unavailable." + } + } + } +} + +/// One proposed toolchain profile. It is advice for the operator: nothing is +/// recorded or granted until the operator selects and confirms it. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct ToolchainProposal { + family: ToolchainFamily, + name: String, + version: Option, + read_only_roots: Vec, + path_entries: Vec, + environment: Vec<(String, String)>, + notes: Vec, +} + +impl ToolchainProposal { + /// The family. + #[must_use] + pub const fn family(&self) -> ToolchainFamily { + self.family + } + + /// The proposed profile name. It satisfies core's name rule. + #[must_use] + pub fn name(&self) -> &str { + &self.name + } + + /// A version taken from directory or file names, for display only. It is + /// untrusted text: make it display-safe before showing it. + #[must_use] + pub fn version(&self) -> Option<&str> { + self.version.as_deref() + } + + /// The proposed read-only roots, in order. + #[must_use] + pub fn read_only_roots(&self) -> &[PathBuf] { + &self.read_only_roots + } + + /// The proposed `PATH` entries, in order. Each lies inside a root. + #[must_use] + pub fn path_entries(&self) -> &[PathBuf] { + &self.path_entries + } + + /// The proposed variables. Values are derived setup values such as an + /// installation path; none is a secret. + #[must_use] + pub fn environment(&self) -> &[(String, String)] { + &self.environment + } + + /// Fixed remarks for the operator. + #[must_use] + pub fn notes(&self) -> &[ProposalNote] { + &self.notes + } + + /// The declaration that [`ControlStore::add_profile`] would record. + /// + /// [`ControlStore::add_profile`]: crate::control::ControlStore::add_profile + #[must_use] + pub fn declaration(&self) -> ProfileDeclaration { + ProfileDeclaration { + name: self.name.clone(), + read_only_roots: self.read_only_roots.clone(), + path_entries: self.path_entries.clone(), + environment: self.environment.clone(), + } + } + + /// A SHA-256 digest, as 64 lowercase hex digits, of everything that would + /// be recorded. The window selects proposals by digest, so a selection + /// made from an earlier list fails to match when anything changed. + #[must_use] + pub fn digest(&self) -> String { + let mut hasher = Sha256::new(); + let mut field = |bytes: &[u8]| { + hasher.update(u64::try_from(bytes.len()).unwrap_or(u64::MAX).to_le_bytes()); + hasher.update(bytes); + }; + field(b"omgcode.toolchain-proposal.v1"); + field(self.family.label().as_bytes()); + field(self.name.as_bytes()); + field(self.version.as_deref().unwrap_or("").as_bytes()); + for list in [&self.read_only_roots, &self.path_entries] { + field(&u64::try_from(list.len()).unwrap_or(u64::MAX).to_le_bytes()); + for path in list { + field(path.as_os_str().as_encoded_bytes()); + } + } + field( + &u64::try_from(self.environment.len()) + .unwrap_or(u64::MAX) + .to_le_bytes(), + ); + for (name, value) in &self.environment { + field(name.as_bytes()); + field(value.as_bytes()); + } + hasher + .finalize() + .iter() + .map(|byte| format!("{byte:02x}")) + .collect() + } +} + +/// The host locations discovery reads. [`from_environment`] describes this +/// computer; [`rooted_at`] describes a fixture tree, so each platform's layout +/// can be tested on either host. +/// +/// [`from_environment`]: Self::from_environment +/// [`rooted_at`]: Self::rooted_at +#[derive(Clone, Debug)] +pub struct DiscoveryHost { + platform: ProfilePlatform, + /// Linux: the filesystem root. Windows: the system drive's root. + root: PathBuf, + /// Windows only: the Windows directory. + windows_dir: Option, + home: Option, + /// Windows only. + local_app_data: Option, + /// Windows only. + roaming_app_data: Option, + /// Windows only, without duplicates. + program_files: Vec, + search_path: Vec, + rustup_home: Option, + java_home: Option, + goroot: Option, +} + +impl DiscoveryHost { + /// This computer, read from the trusted process's own environment. + /// Relative values are ignored. `None` where profiles are unsupported. + #[must_use] + pub fn from_environment() -> Option { + let platform = ProfilePlatform::current()?; + let absolute = |name: &str| { + std::env::var_os(name) + .map(PathBuf::from) + .filter(|path| path.is_absolute()) + }; + let search_path = std::env::var_os("PATH") + .map(|value| { + std::env::split_paths(&value) + .filter(|path| path.is_absolute()) + .take(MAX_SEARCH_DIRECTORIES) + .collect() + }) + .unwrap_or_default(); + let mut host = match platform { + ProfilePlatform::Windows => { + let home = absolute("USERPROFILE"); + let root = std::env::var_os("SystemDrive") + .map(|drive| { + let mut root = drive; + root.push("\\"); + PathBuf::from(root) + }) + .filter(|path| path.is_absolute()) + .unwrap_or_else(|| PathBuf::from("C:\\")); + let mut program_files: Vec = Vec::new(); + for name in ["ProgramFiles", "ProgramW6432", "ProgramFiles(x86)"] { + if let Some(path) = absolute(name) + && !program_files.iter().any(|known| same_text(known, &path)) + { + program_files.push(path); + } + } + Self { + platform, + root, + windows_dir: absolute("SystemRoot"), + rustup_home: absolute("RUSTUP_HOME") + .or_else(|| home.as_ref().map(|home| home.join(".rustup"))), + home, + local_app_data: absolute("LOCALAPPDATA"), + roaming_app_data: absolute("APPDATA"), + program_files, + search_path: Vec::new(), + java_home: None, + goroot: None, + } + } + ProfilePlatform::Linux => { + let home = absolute("HOME"); + Self { + platform, + root: PathBuf::from("/"), + windows_dir: None, + rustup_home: absolute("RUSTUP_HOME") + .or_else(|| home.as_ref().map(|home| home.join(".rustup"))), + home, + local_app_data: None, + roaming_app_data: None, + program_files: Vec::new(), + search_path: Vec::new(), + java_home: None, + goroot: None, + } + } + }; + host.search_path = search_path; + host.java_home = absolute("JAVA_HOME"); + host.goroot = absolute("GOROOT"); + Some(host) + } + + /// A host whose standard locations all lie under `base`, laid out as on + /// `platform`: on Windows `Program Files`, `Program Files (x86)`, + /// `Windows`, and `Users/operator`; on Linux `usr`, `opt`, `etc`, and + /// `home/operator`. The search path is empty. For tests and fixtures. + #[must_use] + pub fn rooted_at(platform: ProfilePlatform, base: &Path) -> Self { + match platform { + ProfilePlatform::Windows => { + let home = base.join("Users").join("operator"); + Self { + platform, + root: base.to_path_buf(), + windows_dir: Some(base.join("Windows")), + local_app_data: Some(home.join("AppData").join("Local")), + roaming_app_data: Some(home.join("AppData").join("Roaming")), + program_files: vec![ + base.join("Program Files"), + base.join("Program Files (x86)"), + ], + search_path: Vec::new(), + rustup_home: Some(home.join(".rustup")), + java_home: None, + goroot: None, + home: Some(home), + } + } + ProfilePlatform::Linux => { + let home = base.join("home").join("operator"); + Self { + platform, + root: base.to_path_buf(), + windows_dir: None, + local_app_data: None, + roaming_app_data: None, + program_files: Vec::new(), + search_path: Vec::new(), + rustup_home: Some(home.join(".rustup")), + java_home: None, + goroot: None, + home: Some(home), + } + } + } + } + + /// Replace the operator `PATH` entries, keeping at most 256 absolute ones. + #[must_use] + pub fn with_search_path(mut self, directories: Vec) -> Self { + self.search_path = directories + .into_iter() + .filter(|path| path.is_absolute()) + .take(MAX_SEARCH_DIRECTORIES) + .collect(); + self + } + + /// Set the operator's `JAVA_HOME`. + #[must_use] + pub fn with_java_home(mut self, java_home: PathBuf) -> Self { + self.java_home = Some(java_home).filter(|path| path.is_absolute()); + self + } + + /// Set the operator's `GOROOT`. + #[must_use] + pub fn with_goroot(mut self, goroot: PathBuf) -> Self { + self.goroot = Some(goroot).filter(|path| path.is_absolute()); + self + } + + /// The platform whose layout this host has. + #[must_use] + pub const fn platform(&self) -> ProfilePlatform { + self.platform + } + + const fn is_windows(&self) -> bool { + matches!(self.platform, ProfilePlatform::Windows) + } + + /// A program's file name on this host. + fn exe(&self, stem: &str) -> String { + if self.is_windows() { + format!("{stem}.exe") + } else { + stem.to_owned() + } + } + + /// `relative`, written with `/`, under the filesystem or drive root. + fn under_root(&self, relative: &str) -> PathBuf { + joined_path(&self.root, relative) + } + + /// `relative`, written with `/`, under the home directory. + fn under_home(&self, relative: &str) -> Option { + self.home.as_deref().map(|home| joined_path(home, relative)) + } + + /// The directories holding `program` among the operator's `PATH` + /// entries, in `PATH` order without duplicates. On Linux each is the + /// directory of the program's resolved file, so `/usr/bin/java` leads to + /// the JDK it links to. Windows app execution aliases are skipped. + fn search_directories(&self, program: &str) -> Vec { + let mut found: Vec = Vec::new(); + for directory in &self.search_path { + if directory.components().any(|component| { + component + .as_os_str() + .to_str() + .is_some_and(|text| text.eq_ignore_ascii_case("WindowsApps")) + }) { + continue; + } + let file = directory.join(program); + if !is_file(&file) { + continue; + } + let resolved = if self.is_windows() { + Some(directory.clone()) + } else { + fs::canonicalize(&file) + .ok() + .and_then(|real| real.parent().map(Path::to_path_buf)) + }; + if let Some(resolved) = resolved + && !found.contains(&resolved) + { + found.push(resolved); + } + } + found + } + + /// The roots and `PATH` entries every profile on this host gets: the + /// Windows `System32` directory, or Linux `/usr` and any top-level `bin`, + /// `lib`, `lib64`, or `lib32` that is a real directory rather than a link + /// into `/usr`. These hold the system loader, libraries, and shell that + /// the acceptance-tested profiles all listed. + fn system_part(&self) -> (Vec, Vec) { + let mut roots = Vec::new(); + let mut path_entries = Vec::new(); + match self.platform { + ProfilePlatform::Windows => { + if let Some(system) = self + .windows_dir + .as_ref() + .map(|windows| windows.join("System32")) + .filter(|system| real_directory(system)) + { + roots.push(system.clone()); + path_entries.push(system); + } + } + ProfilePlatform::Linux => { + let usr = self.under_root("usr"); + if real_directory(&usr) { + let bin = usr.join("bin"); + roots.push(usr); + if real_directory(&bin) { + path_entries.push(bin); + } + } + for name in ["bin", "lib", "lib64", "lib32"] { + let directory = self.under_root(name); + if real_directory(&directory) { + if name == "bin" { + path_entries.push(directory.clone()); + } + roots.push(directory); + } + } + } + } + (roots, path_entries) + } + + /// Whether `root` is too broad to propose: the filesystem or drive root, + /// or the home directory or one of its ancestors. + fn too_broad(&self, root: &Path) -> bool { + root == self.root + || root.parent().is_none() + || self + .home + .as_deref() + .is_some_and(|home| home.starts_with(root)) + } + + /// Join `paths` into one list variable with this host's separator. + /// `None` when a path is not UTF-8 or contains the separator. + fn list_value(&self, paths: &[PathBuf]) -> Option { + let separator = if self.is_windows() { ';' } else { ':' }; + let mut parts = Vec::with_capacity(paths.len()); + for path in paths { + let text = path.to_str()?; + if text.contains(separator) { + return None; + } + parts.push(text); + } + Some(parts.join(&separator.to_string())) + } +} + +/// One installation a detector found, before the shared flow completes it. +#[derive(Clone, Debug)] +struct Candidate { + family: ToolchainFamily, + /// The bare name for the preferred installation, such as `rust`. + base_name: &'static str, + /// What tells this installation apart in a longer name, such as a version. + variant: String, + version: Option, + /// Listed and named first under its base name, such as rustup's default. + preferred: bool, + /// Whether this kind of toolchain passed the confined acceptance runs. + qualified: bool, + roots: Vec, + path_entries: Vec, + environment: Vec<(String, String)>, + notes: Vec, +} + +impl Candidate { + fn new(family: ToolchainFamily, base_name: &'static str, variant: impl Into) -> Self { + Self { + family, + base_name, + variant: variant.into(), + version: None, + preferred: false, + qualified: false, + roots: Vec::new(), + path_entries: Vec::new(), + environment: Vec::new(), + notes: Vec::new(), + } + } + + /// Add a variable whose value is a path; `false` when it is not UTF-8. + fn set_path_variable(&mut self, name: &str, path: &Path) -> bool { + match path.to_str() { + Some(text) => { + self.environment.push((name.to_owned(), text.to_owned())); + true + } + None => false, + } + } + + fn set_variable(&mut self, name: &str, value: &str) { + self.environment.push((name.to_owned(), value.to_owned())); + } + + fn note(&mut self, note: ProposalNote) { + if !self.notes.contains(¬e) { + self.notes.push(note); + } + } + + /// Add the system part, drop duplicate and nested roots and duplicate + /// `PATH` entries, and refuse a candidate with a root that is too broad + /// or a `PATH` entry outside every root. + fn complete( + mut self, + host: &DiscoveryHost, + system: &(Vec, Vec), + ) -> Option { + self.roots.extend(system.0.iter().cloned()); + self.path_entries.extend(system.1.iter().cloned()); + if self.roots.iter().any(|root| host.too_broad(root)) { + return None; + } + let mut roots: Vec = Vec::new(); + for (index, root) in self.roots.iter().enumerate() { + let covered = self.roots.iter().enumerate().any(|(other, outer)| { + other != index && root.starts_with(outer) && (root != outer || other < index) + }); + if !covered { + roots.push(root.clone()); + } + } + // Core records a root by its resolved identity, so a root that is a + // link would be recorded at a path the confirmation never showed. A + // link nested inside another root, such as Debian's + // `/usr/lib/jvm/default-java` under `/usr`, was dropped above. + if roots.iter().any(|root| !real_directory(root)) { + return None; + } + self.roots = roots; + let mut path_entries: Vec = Vec::new(); + for entry in &self.path_entries { + if !path_entries.contains(entry) { + path_entries.push(entry.clone()); + } + } + self.path_entries = path_entries; + if self.roots.is_empty() + || !self + .path_entries + .iter() + .all(|entry| self.roots.iter().any(|root| entry.starts_with(root))) + { + return None; + } + if !self.qualified { + self.note(ProposalNote::NotQualified); + } + Some(self) + } + + /// Whether two candidates would record the same profile apart from the + /// name. + fn same_profile(&self, other: &Self) -> bool { + self.roots == other.roots + && self.path_entries == other.path_entries + && self.environment == other.environment + } +} + +/// What one discovery found. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct Discovered { + /// The proposals, at most [`MAX_PROPOSALS`], as [`discover`] returns them. + pub proposals: Vec, + /// Installations found and not proposed because a bound was reached: + /// eight under one name, or [`MAX_PROPOSALS`] in all. + pub omitted: usize, +} + +/// Find the toolchains installed on `host` and propose a profile for each. +/// +/// Proposals are listed by family, the preferred installation of each name +/// first and then by descending version. At most [`MAX_PROPOSALS`] are +/// returned; [`discover_bounded`] also says how many were left out. A +/// proposal can still be refused by core, for example because a root +/// overlaps the development root or its name is already recorded; check it +/// with [`ControlStore::check_profile`] before offering it. +/// +/// [`ControlStore::check_profile`]: crate::control::ControlStore::check_profile +#[must_use] +pub fn discover(host: &DiscoveryHost) -> Vec { + discover_bounded(host).proposals +} + +/// [`discover`], with the number of installations the bounds left out. When +/// more than [`MAX_PROPOSALS`] remain, each name keeps its first installation +/// before any name keeps a second, so the families listed last are not the +/// first to lose every proposal. +#[must_use] +pub fn discover_bounded(host: &DiscoveryHost) -> Discovered { + let system = host.system_part(); + let mut omitted = 0; + let mut ordered: Vec = Vec::new(); + for detect in DETECTORS { + let mut found: Vec = detect(host) + .into_iter() + .filter_map(|candidate| candidate.complete(host, &system)) + .collect(); + // Each detector's base names keep the order the detector found them. + let mut names: Vec<&'static str> = Vec::new(); + for candidate in &found { + if !names.contains(&candidate.base_name) { + names.push(candidate.base_name); + } + } + // Stable sorts: preferred first, then by descending version. + found.sort_by_key(|candidate| std::cmp::Reverse(version_key(&candidate.variant))); + found.sort_by_key(|candidate| !candidate.preferred); + let mut kept: Vec = Vec::new(); + for candidate in found { + let under_name = kept + .iter() + .filter(|other| other.base_name == candidate.base_name) + .count(); + // The same installation found twice, such as through `PATH` and + // a standard location. GCC and Clang in `/usr` share every root + // but are different tools, so only one base name is compared. + let duplicate = kept.iter().any(|other| { + other.base_name == candidate.base_name && other.same_profile(&candidate) + }); + if duplicate { + continue; + } + if under_name < MAX_PER_NAME { + kept.push(candidate); + } else { + omitted += 1; + } + } + for name in names { + ordered.extend(kept.iter().filter(|c| c.base_name == name).cloned()); + } + } + let keep = fair_share(&ordered, MAX_PROPOSALS); + omitted += ordered.len() - keep.iter().filter(|kept| **kept).count(); + let mut taken: Vec = Vec::new(); + let mut proposals = Vec::new(); + for (candidate, _) in ordered.into_iter().zip(keep).filter(|(_, kept)| *kept) { + let first_of_name = !taken + .iter() + .any(|name| name.eq_ignore_ascii_case(candidate.base_name)); + let name = unique_name( + &if first_of_name { + candidate.base_name.to_owned() + } else { + profile_name(candidate.base_name, &candidate.variant) + }, + &taken, + ); + taken.push(name.clone()); + proposals.push(ToolchainProposal { + family: candidate.family, + name, + version: candidate.version, + read_only_roots: candidate.roots, + path_entries: candidate.path_entries, + environment: candidate.environment, + notes: candidate.notes, + }); + } + Discovered { proposals, omitted } +} + +/// Which of `ordered` to keep when at most `limit` can be: every name's first +/// candidate, then every name's second, and so on, in list order within each +/// round. The kept candidates keep their place in the list. +fn fair_share(ordered: &[Candidate], limit: usize) -> Vec { + let mut seen: Vec<(&'static str, usize)> = Vec::new(); + let mut ranked: Vec<(usize, usize)> = Vec::with_capacity(ordered.len()); + for (index, candidate) in ordered.iter().enumerate() { + let rank = match seen + .iter_mut() + .find(|(name, _)| *name == candidate.base_name) + { + Some((_, count)) => { + *count += 1; + *count - 1 + } + None => { + seen.push((candidate.base_name, 1)); + 0 + } + }; + ranked.push((rank, index)); + } + ranked.sort_unstable(); + let mut keep = vec![false; ordered.len()]; + for (_, index) in ranked.into_iter().take(limit) { + if let Some(slot) = keep.get_mut(index) { + *slot = true; + } + } + keep +} + +/// `base-variant` with every character outside core's name rule replaced by +/// `-`, cut to the name limit. +fn profile_name(base: &str, variant: &str) -> String { + let cleaned: String = variant + .chars() + .map(|character| { + if character.is_ascii_alphanumeric() || "._-".contains(character) { + character + } else { + '-' + } + }) + .collect(); + let cleaned = cleaned.trim_matches(|character| "._-".contains(character)); + let mut name = if cleaned.is_empty() { + base.to_owned() + } else { + format!("{base}-{cleaned}") + }; + // Every character is ASCII, so a byte cut is a character cut. + name.truncate(MAX_PROFILE_NAME_CHARS); + name +} + +/// `name`, or `name-2`, `name-3`, and so on, whichever no earlier proposal +/// took, compared case-insensitively. +fn unique_name(name: &str, taken: &[String]) -> String { + let free = |candidate: &str| !taken.iter().any(|t| t.eq_ignore_ascii_case(candidate)); + if free(name) { + return name.to_owned(); + } + for suffix in 2..=MAX_PROPOSALS + 1 { + let tail = format!("-{suffix}"); + let mut stem = name.to_owned(); + stem.truncate(MAX_PROFILE_NAME_CHARS.saturating_sub(tail.len())); + let candidate = format!("{stem}{tail}"); + if free(&candidate) { + return candidate; + } + } + // Unreachable in practice: at most `MAX_PROPOSALS` names are taken, so + // one of the suffixes above is free. Returning the name lets core refuse + // the duplicate instead of panicking. + name.to_owned() +} + +/// The numbers in `text`, in order, for comparing versions: `1.99.1` sorts +/// after `1.9.2`. Text without digits sorts first. +fn version_key(text: &str) -> Vec { + text.split(|character: char| !character.is_ascii_digit()) + .filter(|part| !part.is_empty()) + .map(|part| part.parse::().unwrap_or(u64::MAX)) + .collect() +} + +/// The entry of `entries` whose file name has the highest [`version_key`]. +fn newest(entries: impl IntoIterator) -> Option { + entries + .into_iter() + .max_by_key(|path| version_key(&file_name(path).unwrap_or_default())) +} + +/// The final component as text, when it is UTF-8. +fn file_name(path: &Path) -> Option { + path.file_name()?.to_str().map(str::to_owned) +} + +/// `base` joined with `relative`, whose components are written with `/`. +fn joined_path(base: &Path, relative: &str) -> PathBuf { + relative + .split('/') + .filter(|part| !part.is_empty()) + .fold(base.to_path_buf(), |path, part| path.join(part)) +} + +/// Whether `path` is a directory itself, not a symbolic link, junction, or +/// other name surrogate for one. +fn real_directory(path: &Path) -> bool { + fs::symlink_metadata(path) + .is_ok_and(|metadata| metadata.is_dir() && !metadata.file_type().is_symlink()) +} + +/// Whether `path` names a file, following links. +fn is_file(path: &Path) -> bool { + fs::metadata(path).is_ok_and(|metadata| metadata.is_file()) +} + +/// The real directories directly inside `path`, sorted by name: the first +/// [`MAX_LISTED_ENTRIES`] of them by name. +fn child_directories(path: &Path) -> Vec { + listed_directories(path, None) +} + +/// The real directories inside `path` whose names start with `prefix`, +/// compared case-insensitively, sorted by name: the first +/// [`MAX_LISTED_ENTRIES`] of them by name. +fn child_directories_named(path: &Path, prefix: &str) -> Vec { + listed_directories(path, Some(prefix)) +} + +/// The listing behind [`child_directories`]. The entry type and name come +/// from the listing itself, so no entry is opened or examined further. Only +/// the first [`MAX_SCANNED_ENTRIES`] entries the filesystem returns are +/// examined; the filter and the sort come before the [`MAX_LISTED_ENTRIES`] +/// cut, so which directories are kept does not depend on listing order. +fn listed_directories(path: &Path, prefix: Option<&str>) -> Vec { + let Ok(entries) = fs::read_dir(path) else { + return Vec::new(); + }; + let mut found: Vec = entries + .take(MAX_SCANNED_ENTRIES) + .filter_map(Result::ok) + .filter(|entry| { + entry + .file_type() + .is_ok_and(|kind| kind.is_dir() && !kind.is_symlink()) + }) + .filter(|entry| { + prefix.is_none_or(|prefix| { + entry.file_name().to_str().is_some_and(|name| { + name.get(..prefix.len()) + .is_some_and(|start| start.eq_ignore_ascii_case(prefix)) + }) + }) + }) + .map(|entry| entry.path()) + .collect(); + found.sort(); + found.truncate(MAX_LISTED_ENTRIES); + found +} + +/// The text of a small installer-written file, at most 64 KiB of it, when it +/// is UTF-8. The type is checked before the file is opened, so a FIFO or +/// device already at an installer's path is never opened. One swapped in +/// between the check and the open can still block that open (ADR-0103 +/// records this). The open handle is checked again. +fn read_text(path: &Path) -> Option { + if !is_file(path) { + return None; + } + let file = fs::File::open(path).ok()?; + if !file.metadata().ok()?.is_file() { + return None; + } + let mut text = String::new(); + file.take(MAX_TEXT_BYTES).read_to_string(&mut text).ok()?; + Some(text) +} + +/// Whether two paths have the same text, ignoring ASCII case. +fn same_text(left: &Path, right: &Path) -> bool { + left.to_string_lossy() + .eq_ignore_ascii_case(&right.to_string_lossy()) +} + +/// The parent of a `bin` directory, which is the installation it belongs +/// to. `None` for a directory with no parent or a relative one. +fn install_of(bin: &Path) -> Option { + let parent = bin.parent()?; + if parent + .components() + .any(|component| matches!(component, Component::ParentDir)) + { + return None; + } + Some(parent.to_path_buf()) +} + +/// The directories that hold `program`: each of `standard` that holds it, then +/// the operator's `PATH` entries that do, without duplicates. +fn program_directories( + host: &DiscoveryHost, + standard: Vec, + program: &str, +) -> Vec { + let mut found = Vec::new(); + for directory in standard { + if real_directory(&directory) && is_file(&directory.join(program)) { + push_unique(&mut found, directory); + } + } + for directory in host.search_directories(program) { + push_unique(&mut found, directory); + } + found +} + +/// Add `path` to `list` unless it is already there. +fn push_unique(list: &mut Vec, path: PathBuf) { + if !list.contains(&path) { + list.push(path); + } +} diff --git a/crates/omgcode-core/src/toolchain_discovery/c_cpp.rs b/crates/omgcode-core/src/toolchain_discovery/c_cpp.rs new file mode 100644 index 00000000..ba017a93 --- /dev/null +++ b/crates/omgcode-core/src/toolchain_discovery/c_cpp.rs @@ -0,0 +1,234 @@ +//! C and C++ compilers. +//! +//! On Windows: the newest x64-hosted MSVC toolset with the newest Windows 10 +//! SDK, laid out as the acceptance runs used them (`INCLUDE`, `LIB`, and +//! `VCINSTALLDIR`, which also lets rustc find the linker on `PATH`); LLVM +//! Clang with the same MSVC and SDK parts; and MinGW GCC. On Linux: GCC and +//! Clang. No `vswhere`, compiler, or other program is run: the toolsets are +//! found from their directory layout alone. ARM64-hosted MSVC is not +//! proposed. + +use std::path::{Path, PathBuf}; + +use super::{ + Candidate, DiscoveryHost, ToolchainFamily, child_directories, file_name, install_of, is_file, + newest, program_directories, real_directory, +}; + +/// The MSVC and Windows SDK parts a C, C++, or Rust MSVC-target profile +/// needs. +pub(super) struct MsvcParts { + tools: PathBuf, + kits: PathBuf, + path_entries: Vec, + include: String, + lib: String, + vc_install_dir: String, + tools_version: String, + sdk_version: String, +} + +impl MsvcParts { + /// Add the roots, `PATH` entries, and variables to `candidate`. + pub(super) fn merge_into(&self, candidate: &mut Candidate) { + candidate.roots.push(self.tools.clone()); + candidate.roots.push(self.kits.clone()); + candidate + .path_entries + .extend(self.path_entries.iter().cloned()); + candidate.set_variable("INCLUDE", &self.include); + candidate.set_variable("LIB", &self.lib); + candidate.set_variable("VCINSTALLDIR", &self.vc_install_dir); + } +} + +/// The newest x64-hosted MSVC toolset, `/Microsoft Visual +/// Studio///VC/Tools/MSVC/`, and the newest +/// `Windows Kits/10` SDK with x64 `um` and `ucrt` libraries. +pub(super) fn msvc(host: &DiscoveryHost) -> Option { + if !host.is_windows() { + return None; + } + let tools = newest( + host.program_files + .iter() + .flat_map(|program_files| { + child_directories(&program_files.join("Microsoft Visual Studio")) + }) + .flat_map(|release| child_directories(&release)) + .flat_map(|edition| child_directories(&edition.join("VC").join("Tools").join("MSVC"))) + .filter(|tools| is_file(&host_bin(tools).join("cl.exe"))), + )?; + let kits = host + .program_files + .iter() + .map(|program_files| program_files.join("Windows Kits").join("10")) + .find(|kits| real_directory(kits))?; + let sdk = newest( + child_directories(&kits.join("Lib")) + .into_iter() + .filter(|version| { + real_directory(&version.join("um").join("x64")) + && real_directory(&version.join("ucrt").join("x64")) + }), + )?; + let sdk_version = file_name(&sdk)?; + let tools_version = file_name(&tools)?; + // `tools` is `/Tools/MSVC/`. + let vc = tools.ancestors().nth(3)?; + let include_root = kits.join("Include").join(&sdk_version); + let include = host.list_value(&[ + tools.join("include"), + include_root.join("ucrt"), + include_root.join("um"), + include_root.join("shared"), + ])?; + let lib = host.list_value(&[ + tools.join("lib").join("x64"), + sdk.join("ucrt").join("x64"), + sdk.join("um").join("x64"), + ])?; + let mut path_entries = vec![host_bin(&tools)]; + // The SDK's resource compiler and manifest tool, which build systems call. + let sdk_bin = kits.join("bin").join(&sdk_version).join("x64"); + if real_directory(&sdk_bin) { + path_entries.push(sdk_bin); + } + Some(MsvcParts { + vc_install_dir: format!("{}\\", vc.to_str()?), + tools, + kits, + path_entries, + include, + lib, + tools_version, + sdk_version, + }) +} + +/// The x64-hosted, x64-targeting compiler directory of an MSVC toolset. +fn host_bin(tools: &Path) -> PathBuf { + tools.join("bin").join("Hostx64").join("x64") +} + +pub(super) fn detect(host: &DiscoveryHost) -> Vec { + if host.is_windows() { + windows(host) + } else { + linux(host) + } +} + +fn windows(host: &DiscoveryHost) -> Vec { + let mut found = Vec::new(); + let msvc = msvc(host); + if let Some(parts) = &msvc { + let mut candidate = + Candidate::new(ToolchainFamily::CCpp, "msvc", parts.tools_version.clone()); + candidate.version = Some(format!( + "MSVC {}, Windows SDK {}", + parts.tools_version, parts.sdk_version + )); + candidate.qualified = true; + parts.merge_into(&mut candidate); + found.push(candidate); + } + for program_files in &host.program_files { + let llvm = program_files.join("LLVM"); + let bin = llvm.join("bin"); + if !is_file(&bin.join("clang.exe")) { + continue; + } + let version = newest(child_directories(&llvm.join("lib").join("clang"))) + .as_deref() + .and_then(file_name); + let mut candidate = Candidate::new( + ToolchainFamily::CCpp, + "clang", + version.clone().unwrap_or_default(), + ); + candidate.version = version; + candidate.roots.push(llvm); + candidate.path_entries.push(bin); + match &msvc { + Some(parts) => parts.merge_into(&mut candidate), + None => candidate.note(super::ProposalNote::NoMsvc), + } + found.push(candidate); + } + let standard: Vec = [ + "msys64/ucrt64", + "msys64/mingw64", + "msys64/clang64", + "mingw64", + ] + .iter() + .map(|relative| host.under_root(relative).join("bin")) + .collect(); + for bin in program_directories(host, standard, "gcc.exe") { + if let Some(candidate) = gnu(host, &bin, "gcc", false) { + found.push(candidate); + } + } + found +} + +fn linux(host: &DiscoveryHost) -> Vec { + let standard = vec![host.under_root("usr/bin"), host.under_root("usr/local/bin")]; + let mut found = Vec::new(); + for bin in program_directories(host, standard.clone(), "gcc") { + if let Some(candidate) = gnu(host, &bin, "gcc", true) { + found.push(candidate); + } + } + for bin in program_directories(host, standard, "clang") { + if let Some(mut candidate) = gnu(host, &bin, "clang", false) { + if candidate.version.is_none() { + // Debian and Ubuntu install Clang under `/usr/lib/llvm-`. + let version = newest(super::child_directories_named( + &host.under_root("usr/lib"), + "llvm-", + )) + .as_deref() + .and_then(file_name) + .map(|name| name.trim_start_matches("llvm-").to_owned()); + candidate.variant = version.clone().unwrap_or_default(); + candidate.version = version; + } + found.push(candidate); + } + } + found +} + +/// A GCC or Clang installation whose compiler is in `bin`. The version is +/// the newest `lib/gcc//` or `lib/clang/` name. +fn gnu( + host: &DiscoveryHost, + bin: &Path, + base_name: &'static str, + qualified: bool, +) -> Option { + let install = install_of(bin)?; + let library = install.join("lib").join(base_name); + let version_directories = if base_name == "gcc" { + child_directories(&library) + .into_iter() + .flat_map(|target| child_directories(&target)) + .collect() + } else { + child_directories(&library) + }; + let version = newest(version_directories).as_deref().and_then(file_name); + let mut candidate = Candidate::new( + ToolchainFamily::CCpp, + base_name, + version.clone().unwrap_or_default(), + ); + candidate.version = version; + // GCC 13.3 on Linux passed the acceptance runs; MinGW and Clang did not. + candidate.qualified = qualified && !host.is_windows(); + candidate.roots.push(install); + candidate.path_entries.push(bin.to_path_buf()); + Some(candidate) +} diff --git a/crates/omgcode-core/src/toolchain_discovery/dotnet.rs b/crates/omgcode-core/src/toolchain_discovery/dotnet.rs new file mode 100644 index 00000000..55e82af8 --- /dev/null +++ b/crates/omgcode-core/src/toolchain_discovery/dotnet.rs @@ -0,0 +1,83 @@ +//! .NET installations. +//! +//! An installation keeps the `dotnet` host beside its `shared` folder: +//! `Program Files\dotnet`, `~/.dotnet`, `/usr/share/dotnet`, +//! `/usr/lib/dotnet`, `/usr/lib64/dotnet`, `/opt/dotnet`, and the operator's +//! `PATH`. The version is the newest `sdk/` name, or the newest +//! runtime when there is no SDK; nothing is run. +//! +//! Each proposal sets `DOTNET_ROOT` and turns off what a first run would +//! otherwise attempt: telemetry, the banner, and the HTTPS development +//! certificate. NuGet's cache defaults to the run's private home. + +use std::path::{Path, PathBuf}; + +use super::{ + Candidate, DiscoveryHost, ProposalNote, ToolchainFamily, child_directories, file_name, is_file, + newest, push_unique, real_directory, +}; + +pub(super) fn detect(host: &DiscoveryHost) -> Vec { + let mut homes: Vec = Vec::new(); + if host.is_windows() { + for program_files in &host.program_files { + push_unique(&mut homes, program_files.join("dotnet")); + } + } else { + for relative in [ + "usr/share/dotnet", + "usr/lib/dotnet", + "usr/lib64/dotnet", + "opt/dotnet", + ] { + push_unique(&mut homes, host.under_root(relative)); + } + } + if let Some(user) = host.under_home(".dotnet") { + push_unique(&mut homes, user); + } + for directory in host.search_directories(&host.exe("dotnet")) { + push_unique(&mut homes, directory); + } + homes + .iter() + .filter_map(|home| candidate(host, home)) + .collect() +} + +fn candidate(host: &DiscoveryHost, home: &Path) -> Option { + if !real_directory(home) + || !is_file(&home.join(host.exe("dotnet"))) + || !real_directory(&home.join("shared")) + { + return None; + } + let sdk = newest(child_directories(&home.join("sdk"))) + .as_deref() + .and_then(file_name); + let runtime = newest(child_directories( + &home.join("shared").join("Microsoft.NETCore.App"), + )) + .as_deref() + .and_then(file_name); + let (variant, version) = match (&sdk, &runtime) { + (Some(sdk), _) => (sdk.clone(), Some(format!("SDK {sdk}"))), + (None, Some(runtime)) => (runtime.clone(), Some(format!("runtime {runtime}"))), + (None, None) => (String::new(), None), + }; + let mut candidate = Candidate::new(ToolchainFamily::DotNet, "dotnet", variant); + candidate.version = version; + if !candidate.set_path_variable("DOTNET_ROOT", home) { + return None; + } + candidate.set_variable("DOTNET_CLI_TELEMETRY_OPTOUT", "1"); + candidate.set_variable("DOTNET_NOLOGO", "1"); + candidate.set_variable("DOTNET_GENERATE_ASPNET_CERTIFICATE", "false"); + if sdk.is_none() { + candidate.note(ProposalNote::DotnetRuntimeOnly); + } + candidate.note(ProposalNote::OfflineDependencies); + candidate.roots.push(home.to_path_buf()); + candidate.path_entries.push(home.to_path_buf()); + Some(candidate) +} diff --git a/crates/omgcode-core/src/toolchain_discovery/go.rs b/crates/omgcode-core/src/toolchain_discovery/go.rs new file mode 100644 index 00000000..6ee73dd3 --- /dev/null +++ b/crates/omgcode-core/src/toolchain_discovery/go.rs @@ -0,0 +1,82 @@ +//! Go installations. +//! +//! Looks in the operator's `GOROOT`, `Program Files\Go`, `/usr/local/go`, +//! `/usr/lib/go-*`, `~/sdk/go*`, and the operator's `PATH`. The version is +//! the first line of the installation's `VERSION` file; nothing is run. +//! +//! Besides `GOROOT`, each proposal sets the values the Go acceptance run used +//! to keep a run inside its profile: `GOTOOLCHAIN=local`, so a module's +//! `toolchain` line can never select or download another Go; `GOENV=off`, so +//! no user configuration file is read; and `GOFLAGS=-buildvcs=false`, so the +//! build does not try to run Git. The build and module caches default to the +//! run's private home. + +use std::path::{Path, PathBuf}; + +use super::{ + Candidate, DiscoveryHost, ProposalNote, ToolchainFamily, child_directories_named, file_name, + install_of, is_file, push_unique, read_text, real_directory, +}; + +pub(super) fn detect(host: &DiscoveryHost) -> Vec { + let mut homes: Vec = Vec::new(); + if let Some(goroot) = &host.goroot { + push_unique(&mut homes, goroot.clone()); + } + if host.is_windows() { + for program_files in &host.program_files { + push_unique(&mut homes, program_files.join("Go")); + } + } else { + push_unique(&mut homes, host.under_root("usr/local/go")); + for home in child_directories_named(&host.under_root("usr/lib"), "go") { + push_unique(&mut homes, home); + } + } + if let Some(sdk) = host.under_home("sdk") { + for home in child_directories_named(&sdk, "go") { + push_unique(&mut homes, home); + } + } + for bin in host.search_directories(&host.exe("go")) { + if let Some(home) = install_of(&bin) { + push_unique(&mut homes, home); + } + } + homes + .iter() + .filter_map(|home| candidate(host, home)) + .collect() +} + +fn candidate(host: &DiscoveryHost, home: &Path) -> Option { + let bin = home.join("bin"); + if !real_directory(home) + || !is_file(&bin.join(host.exe("go"))) + || !(is_file(&home.join("VERSION")) || real_directory(&home.join("src").join("runtime"))) + { + return None; + } + let version = read_text(&home.join("VERSION")) + .and_then(|text| text.lines().next().map(str::trim).map(str::to_owned)) + .map(|line| line.trim_start_matches("go").to_owned()) + .filter(|line| !line.is_empty()) + .or_else(|| file_name(home)); + let mut candidate = Candidate::new( + ToolchainFamily::Go, + "go", + version.clone().unwrap_or_default(), + ); + candidate.version = version; + candidate.qualified = true; + if !candidate.set_path_variable("GOROOT", home) { + return None; + } + candidate.set_variable("GOTOOLCHAIN", "local"); + candidate.set_variable("GOENV", "off"); + candidate.set_variable("GOFLAGS", "-buildvcs=false"); + candidate.note(ProposalNote::OfflineDependencies); + candidate.roots.push(home.to_path_buf()); + candidate.path_entries.push(bin); + Some(candidate) +} diff --git a/crates/omgcode-core/src/toolchain_discovery/java.rs b/crates/omgcode-core/src/toolchain_discovery/java.rs new file mode 100644 index 00000000..e862004d --- /dev/null +++ b/crates/omgcode-core/src/toolchain_discovery/java.rs @@ -0,0 +1,108 @@ +//! JDKs and Java runtimes. +//! +//! Looks in the operator's `JAVA_HOME`, the vendors' Windows install folders, +//! `/usr/lib/jvm`, `/usr/lib64/jvm`, `/opt`, SDKMAN, and IntelliJ's `~/.jdks`, +//! and follows a `java` on the operator's `PATH` to its installation. The +//! version comes from the JDK's own `release` file; nothing is run. Each +//! proposal sets `JAVA_HOME`. + +use std::path::{Path, PathBuf}; + +use super::{ + Candidate, DiscoveryHost, ProposalNote, ToolchainFamily, child_directories, file_name, + install_of, is_file, push_unique, read_text, +}; + +/// Windows vendor folders under `Program Files` that hold one JDK per child. +const WINDOWS_VENDORS: [&str; 9] = [ + "Java", + "Eclipse Adoptium", + "Microsoft", + "Zulu", + "Amazon Corretto", + "BellSoft", + "OpenJDK", + "Semeru", + "Eclipse Foundation", +]; + +pub(super) fn detect(host: &DiscoveryHost) -> Vec { + let mut homes: Vec = Vec::new(); + if let Some(java_home) = &host.java_home { + push_unique(&mut homes, java_home.clone()); + } + if host.is_windows() { + for program_files in &host.program_files { + for vendor in WINDOWS_VENDORS { + for home in child_directories(&program_files.join(vendor)) { + push_unique(&mut homes, home); + } + } + } + } else { + for parent in ["usr/lib/jvm", "usr/lib64/jvm", "opt"] { + for home in child_directories(&host.under_root(parent)) { + push_unique(&mut homes, home); + } + } + if let Some(sdkman) = host.under_home(".sdkman/candidates/java") { + for home in child_directories(&sdkman) { + push_unique(&mut homes, home); + } + } + } + if let Some(jdks) = host.under_home(".jdks") { + for home in child_directories(&jdks) { + push_unique(&mut homes, home); + } + } + for bin in host.search_directories(&host.exe("java")) { + if let Some(home) = install_of(&bin) { + push_unique(&mut homes, home); + } + } + homes + .iter() + .filter_map(|home| candidate(host, home)) + .collect() +} + +fn candidate(host: &DiscoveryHost, home: &Path) -> Option { + let bin = home.join("bin"); + if !is_file(&bin.join(host.exe("java"))) { + return None; + } + let version = release_version(home).or_else(|| file_name(home)); + // `21.0.2` and `java-21-openjdk-amd64` are named `java-21`; another JDK + // 21 gets `java-21-2`. + let major = version + .as_deref() + .and_then(|text| { + text.split(['.', '+', '-', '_']) + .find(|part| !part.is_empty() && part.bytes().all(|byte| byte.is_ascii_digit())) + }) + .map(str::to_owned) + .or_else(|| version.clone()) + .unwrap_or_default(); + let mut candidate = Candidate::new(ToolchainFamily::Java, "java", major); + candidate.version = version; + if !candidate.set_path_variable("JAVA_HOME", home) { + return None; + } + if !is_file(&bin.join(host.exe("javac"))) { + candidate.note(ProposalNote::JavaRuntimeOnly); + } + candidate.note(ProposalNote::OfflineDependencies); + candidate.roots.push(home.to_path_buf()); + candidate.path_entries.push(bin); + Some(candidate) +} + +/// `JAVA_VERSION` from the JDK's `release` file, such as `21.0.2`. +fn release_version(home: &Path) -> Option { + read_text(&home.join("release"))?.lines().find_map(|line| { + let value = line.strip_prefix("JAVA_VERSION=")?; + let value = value.trim().trim_matches('"'); + (!value.is_empty()).then(|| value.to_owned()) + }) +} diff --git a/crates/omgcode-core/src/toolchain_discovery/node.rs b/crates/omgcode-core/src/toolchain_discovery/node.rs new file mode 100644 index 00000000..76ccdfbc --- /dev/null +++ b/crates/omgcode-core/src/toolchain_discovery/node.rs @@ -0,0 +1,90 @@ +//! Node.js installations. +//! +//! On Windows an installation keeps `node.exe` beside its `node_modules` +//! folder: `Program Files\nodejs`, nvm-windows versions under +//! `%APPDATA%\nvm`, and the operator's `PATH`. A shim folder with no +//! `node_modules`, such as Volta's, is skipped. On Linux it is the parent of +//! a `bin` holding `node`: `/usr`, `/usr/local`, nvm, and the operator's +//! `PATH`. The version comes from an nvm folder name; nothing is run. +//! +//! On Windows each proposal sets `NODE_OPTIONS=--preserve-symlinks +//! --preserve-symlinks-main`, because Node's module loader otherwise reads +//! every ancestor directory and fails inside the container. A distribution +//! Node in `/usr` also gets `/etc/ssl`, where its OpenSSL configuration is. + +use std::path::{Path, PathBuf}; + +use super::{ + Candidate, DiscoveryHost, ProposalNote, ToolchainFamily, child_directories, + child_directories_named, file_name, install_of, is_file, push_unique, real_directory, +}; + +pub(super) fn detect(host: &DiscoveryHost) -> Vec { + let mut homes: Vec = Vec::new(); + if host.is_windows() { + for program_files in &host.program_files { + push_unique(&mut homes, program_files.join("nodejs")); + } + if let Some(roaming) = &host.roaming_app_data { + for home in child_directories_named(&roaming.join("nvm"), "v") { + push_unique(&mut homes, home); + } + } + for home in host.search_directories("node.exe") { + push_unique(&mut homes, home); + } + } else { + let mut bins = vec![host.under_root("usr/bin"), host.under_root("usr/local/bin")]; + if let Some(nvm) = host.under_home(".nvm/versions/node") { + bins.extend(child_directories(&nvm).into_iter().map(|v| v.join("bin"))); + } + bins.extend(host.search_directories("node")); + for bin in bins { + if is_file(&bin.join("node")) + && let Some(home) = install_of(&bin) + { + push_unique(&mut homes, home); + } + } + } + homes + .iter() + .filter_map(|home| candidate(host, home)) + .collect() +} + +fn candidate(host: &DiscoveryHost, home: &Path) -> Option { + let version = file_name(home) + .filter(|name| { + name.strip_prefix('v') + .is_some_and(|rest| rest.starts_with(|c: char| c.is_ascii_digit())) + }) + .map(|name| name.trim_start_matches('v').to_owned()); + let mut candidate = Candidate::new( + ToolchainFamily::Node, + "node", + version.clone().unwrap_or_default(), + ); + candidate.version = version; + candidate.qualified = true; + candidate.note(ProposalNote::OfflineDependencies); + candidate.roots.push(home.to_path_buf()); + if host.is_windows() { + if !is_file(&home.join("node.exe")) || !real_directory(&home.join("node_modules")) { + return None; + } + candidate.path_entries.push(home.to_path_buf()); + candidate.set_variable( + "NODE_OPTIONS", + "--preserve-symlinks --preserve-symlinks-main", + ); + candidate.note(ProposalNote::NodeWindowsChildren); + } else { + candidate.path_entries.push(home.join("bin")); + let ssl = host.under_root("etc/ssl"); + if *home == host.under_root("usr") && real_directory(&ssl) { + candidate.roots.push(ssl); + } + } + Some(candidate) +} diff --git a/crates/omgcode-core/src/toolchain_discovery/perl.rs b/crates/omgcode-core/src/toolchain_discovery/perl.rs new file mode 100644 index 00000000..af32f57c --- /dev/null +++ b/crates/omgcode-core/src/toolchain_discovery/perl.rs @@ -0,0 +1,112 @@ +//! Perl installations. +//! +//! On Windows: Strawberry Perl (`C:\Strawberry`, with its MinGW `c\bin`), +//! ActiveState Perl (`C:\Perl64`, `C:\Perl`), and a `perl.exe` on the +//! operator's `PATH` whose installation holds `lib\Config.pm`, which skips +//! the MSYS Perl inside Git for Windows. On Linux: `/usr`, `/usr/local`, +//! perlbrew, and the operator's `PATH`. The version comes from the library +//! folder names; nothing is run. + +use std::path::{Path, PathBuf}; + +use super::{ + Candidate, DiscoveryHost, ProposalNote, ToolchainFamily, child_directories, + child_directories_named, file_name, install_of, is_file, newest, push_unique, real_directory, +}; + +pub(super) fn detect(host: &DiscoveryHost) -> Vec { + if host.is_windows() { + windows(host) + } else { + linux(host) + } +} + +fn windows(host: &DiscoveryHost) -> Vec { + let mut found = Vec::new(); + let strawberry = host.under_root("Strawberry"); + let perl = strawberry.join("perl"); + if is_file(&perl.join("bin").join("perl.exe")) { + let mut paths = Vec::new(); + for entry in [ + perl.join("site").join("bin"), + perl.join("bin"), + strawberry.join("c").join("bin"), + ] { + if real_directory(&entry) { + paths.push(entry); + } + } + found.push(candidate(&strawberry, &perl, paths)); + } + let mut homes: Vec = vec![host.under_root("Perl64"), host.under_root("Perl")]; + for bin in host.search_directories("perl.exe") { + if let Some(home) = install_of(&bin) { + push_unique(&mut homes, home); + } + } + for home in homes { + if home.starts_with(&strawberry) + || !is_file(&home.join("bin").join("perl.exe")) + || !is_file(&home.join("lib").join("Config.pm")) + { + continue; + } + let paths = [home.join("site").join("bin"), home.join("bin")] + .into_iter() + .filter(|entry| real_directory(entry)) + .collect(); + found.push(candidate(&home, &home, paths)); + } + found +} + +fn linux(host: &DiscoveryHost) -> Vec { + let mut bins = vec![host.under_root("usr/bin"), host.under_root("usr/local/bin")]; + if let Some(perlbrew) = host.under_home("perl5/perlbrew/perls") { + bins.extend( + child_directories(&perlbrew) + .into_iter() + .map(|v| v.join("bin")), + ); + } + bins.extend(host.search_directories("perl")); + let mut homes: Vec = Vec::new(); + for bin in bins { + if is_file(&bin.join("perl")) + && let Some(home) = install_of(&bin) + { + push_unique(&mut homes, home); + } + } + homes + .iter() + .map(|home| candidate(home, home, vec![home.join("bin")])) + .collect() +} + +/// A Perl rooted at `root`, whose own tree is `perl`. +fn candidate(root: &Path, perl: &Path, path_entries: Vec) -> Candidate { + // `lib/perl5/5.38.2` (perlbrew, `/usr/local`) or `share/perl/5.38.2` + // (Debian); Strawberry and ActiveState keep no versioned folder. + let version = newest( + child_directories_named(&perl.join("lib").join("perl5"), "5.") + .into_iter() + .chain(child_directories_named( + &perl.join("share").join("perl"), + "5.", + )), + ) + .as_deref() + .and_then(file_name); + let mut candidate = Candidate::new( + ToolchainFamily::Perl, + "perl", + version.clone().unwrap_or_default(), + ); + candidate.version = version; + candidate.note(ProposalNote::OfflineDependencies); + candidate.roots.push(root.to_path_buf()); + candidate.path_entries = path_entries; + candidate +} diff --git a/crates/omgcode-core/src/toolchain_discovery/python.rs b/crates/omgcode-core/src/toolchain_discovery/python.rs new file mode 100644 index 00000000..6614a219 --- /dev/null +++ b/crates/omgcode-core/src/toolchain_discovery/python.rs @@ -0,0 +1,108 @@ +//! CPython installations. +//! +//! On Windows an installation keeps `python.exe` beside its `Lib` folder; it +//! is found under `%LOCALAPPDATA%\Programs\Python`, the install manager's +//! `%LOCALAPPDATA%\Python\pythoncore-*`, `Program Files`, the drive root, and +//! the operator's `PATH`. On Linux it is the parent of a `bin` holding +//! `python3` and a `lib/python3.*` folder: `/usr`, `/usr/local`, pyenv, and +//! the operator's `PATH`. A virtual environment (`pyvenv.cfg`) or a launcher +//! shim with no standard library is skipped. The version comes from the +//! `python3NN.dll` or `lib/python3.N` names; nothing is run. + +use std::path::{Path, PathBuf}; + +use super::{ + Candidate, DiscoveryHost, ProposalNote, ToolchainFamily, child_directories, + child_directories_named, file_name, install_of, is_file, newest, push_unique, real_directory, + version_key, +}; + +pub(super) fn detect(host: &DiscoveryHost) -> Vec { + let mut homes: Vec = Vec::new(); + if host.is_windows() { + if let Some(local) = &host.local_app_data { + for home in child_directories(&local.join("Programs").join("Python")) { + push_unique(&mut homes, home); + } + for home in child_directories_named(&local.join("Python"), "pythoncore-") { + push_unique(&mut homes, home); + } + } + for program_files in &host.program_files { + for home in child_directories_named(program_files, "Python") { + push_unique(&mut homes, home); + } + } + for home in child_directories_named(&host.root, "Python") { + push_unique(&mut homes, home); + } + for home in host.search_directories("python.exe") { + push_unique(&mut homes, home); + } + } else { + let mut bins = vec![host.under_root("usr/bin"), host.under_root("usr/local/bin")]; + if let Some(pyenv) = host.under_home(".pyenv/versions") { + bins.extend(child_directories(&pyenv).into_iter().map(|v| v.join("bin"))); + } + bins.extend(host.search_directories("python3")); + for bin in bins { + if is_file(&bin.join("python3")) + && let Some(home) = install_of(&bin) + { + push_unique(&mut homes, home); + } + } + } + homes + .iter() + .filter_map(|home| candidate(host, home)) + .collect() +} + +fn candidate(host: &DiscoveryHost, home: &Path) -> Option { + if is_file(&home.join("pyvenv.cfg")) { + return None; + } + let (version, path_entries) = if host.is_windows() { + if !is_file(&home.join("python.exe")) || !real_directory(&home.join("Lib")) { + return None; + } + let mut entries = vec![home.to_path_buf()]; + let scripts = home.join("Scripts"); + if real_directory(&scripts) { + entries.push(scripts); + } + (windows_version(home), entries) + } else { + let library = newest(child_directories_named(&home.join("lib"), "python3."))?; + let version = file_name(&library).map(|name| name.trim_start_matches("python").to_owned()); + (version, vec![home.join("bin")]) + }; + let mut candidate = Candidate::new( + ToolchainFamily::Python, + "python", + version.clone().unwrap_or_default(), + ); + candidate.version = version; + candidate.qualified = true; + candidate.note(ProposalNote::OfflineDependencies); + candidate.roots.push(home.to_path_buf()); + candidate.path_entries = path_entries; + Some(candidate) +} + +/// `3.13` from a `python313.dll` beside `python.exe`. +fn windows_version(home: &Path) -> Option { + let entries = std::fs::read_dir(home).ok()?; + entries + .take(super::MAX_LISTED_ENTRIES) + .filter_map(Result::ok) + .filter_map(|entry| entry.file_name().into_string().ok()) + .filter_map(|name| { + let lower = name.to_ascii_lowercase(); + let digits = lower.strip_prefix("python3")?.strip_suffix(".dll")?; + (!digits.is_empty() && digits.bytes().all(|byte| byte.is_ascii_digit())) + .then(|| format!("3.{digits}")) + }) + .max_by_key(|version| version_key(version)) +} diff --git a/crates/omgcode-core/src/toolchain_discovery/ruby.rs b/crates/omgcode-core/src/toolchain_discovery/ruby.rs new file mode 100644 index 00000000..25860882 --- /dev/null +++ b/crates/omgcode-core/src/toolchain_discovery/ruby.rs @@ -0,0 +1,68 @@ +//! Ruby installations. +//! +//! An installation is the parent of a `bin` holding `ruby` beside a +//! `lib/ruby` folder: RubyInstaller's `C:\Ruby*` folders, `/usr`, +//! `/usr/local`, rbenv, RVM, and the operator's `PATH`. The version is the +//! newest `lib/ruby/` name; nothing is run. + +use std::path::{Path, PathBuf}; + +use super::{ + Candidate, DiscoveryHost, ProposalNote, ToolchainFamily, child_directories, + child_directories_named, file_name, install_of, is_file, newest, push_unique, real_directory, +}; + +pub(super) fn detect(host: &DiscoveryHost) -> Vec { + let mut bins: Vec = Vec::new(); + if host.is_windows() { + bins.extend( + child_directories_named(&host.root, "Ruby") + .into_iter() + .map(|home| home.join("bin")), + ); + } else { + bins.push(host.under_root("usr/bin")); + bins.push(host.under_root("usr/local/bin")); + for manager in [".rbenv/versions", ".rvm/rubies"] { + if let Some(versions) = host.under_home(manager) { + bins.extend( + child_directories(&versions) + .into_iter() + .map(|v| v.join("bin")), + ); + } + } + } + bins.extend(host.search_directories(&host.exe("ruby"))); + let mut homes: Vec = Vec::new(); + for bin in bins { + if is_file(&bin.join(host.exe("ruby"))) + && let Some(home) = install_of(&bin) + { + push_unique(&mut homes, home); + } + } + homes.iter().filter_map(|home| candidate(home)).collect() +} + +fn candidate(home: &Path) -> Option { + let library = home.join("lib").join("ruby"); + if !real_directory(&library) { + return None; + } + let version = newest(child_directories(&library).into_iter().filter(|child| { + file_name(child).is_some_and(|name| name.starts_with(|c: char| c.is_ascii_digit())) + })) + .as_deref() + .and_then(file_name); + let mut candidate = Candidate::new( + ToolchainFamily::Ruby, + "ruby", + version.clone().unwrap_or_default(), + ); + candidate.version = version; + candidate.note(ProposalNote::OfflineDependencies); + candidate.roots.push(home.to_path_buf()); + candidate.path_entries.push(home.join("bin")); + Some(candidate) +} diff --git a/crates/omgcode-core/src/toolchain_discovery/rust.rs b/crates/omgcode-core/src/toolchain_discovery/rust.rs new file mode 100644 index 00000000..7a5232e1 --- /dev/null +++ b/crates/omgcode-core/src/toolchain_discovery/rust.rs @@ -0,0 +1,62 @@ +//! Rust toolchains installed by rustup. +//! +//! Each proposal names one toolchain directory, such as +//! `~/.rustup/toolchains/stable-x86_64-pc-windows-msvc`, and puts its own `bin` +//! on `PATH`. The rustup proxies in `~/.cargo/bin` are not used: running the +//! toolchain's `cargo` and `rustc` directly keeps the operator's cargo home, +//! which can hold `credentials.toml`, out of the profile, and no proxy ever +//! reads a repository's `rust-toolchain.toml`. So no `RUSTUP_*` variable is +//! needed. Cargo's own home is then the run's private `HOME`. + +use std::path::Path; + +use super::{ + Candidate, DiscoveryHost, ProposalNote, ToolchainFamily, c_cpp, child_directories, file_name, + is_file, read_text, +}; + +pub(super) fn detect(host: &DiscoveryHost) -> Vec { + let Some(rustup) = host.rustup_home.as_deref() else { + return Vec::new(); + }; + let default = default_toolchain(rustup); + let msvc = c_cpp::msvc(host); + child_directories(&rustup.join("toolchains")) + .into_iter() + .filter_map(|toolchain| { + let name = file_name(&toolchain)?; + let bin = toolchain.join("bin"); + if !is_file(&bin.join(host.exe("rustc"))) { + return None; + } + let mut candidate = Candidate::new(ToolchainFamily::Rust, "rust", name.clone()); + candidate.preferred = default + .as_deref() + .is_some_and(|chosen| name == chosen || name.starts_with(&format!("{chosen}-"))); + candidate.qualified = true; + candidate.version = Some(name.clone()); + candidate.roots.push(toolchain); + candidate.path_entries.push(bin); + candidate.note(ProposalNote::OfflineDependencies); + if host.is_windows() && name.ends_with("-pc-windows-msvc") { + match &msvc { + Some(parts) => parts.merge_into(&mut candidate), + None => candidate.note(ProposalNote::NoMsvc), + } + } + Some(candidate) + }) + .collect() +} + +/// rustup's default toolchain, from the `settings.toml` rustup keeps in the +/// operator's rustup home. A repository's `rust-toolchain.toml` is never read. +fn default_toolchain(rustup: &Path) -> Option { + read_text(&rustup.join("settings.toml"))? + .lines() + .find_map(|line| { + let (key, value) = line.split_once('=')?; + (key.trim() == "default_toolchain").then(|| value.trim().trim_matches('"').to_owned()) + }) + .filter(|name| !name.is_empty()) +} diff --git a/crates/omgcode-core/src/toolchain_discovery/tests.rs b/crates/omgcode-core/src/toolchain_discovery/tests.rs new file mode 100644 index 00000000..f61bfd76 --- /dev/null +++ b/crates/omgcode-core/src/toolchain_discovery/tests.rs @@ -0,0 +1,1021 @@ +//! Detector tests on fixture trees laid out as Windows and Linux installs. +//! Detectors read the host's platform, not the build's, so both layouts run +//! on either CI host. + +use super::*; +use crate::control::{ + MAX_PROFILE_PATH_ENTRIES, MAX_PROFILE_ROOTS, MAX_PROFILE_VARIABLES, MAX_VARIABLE_VALUE_BYTES, + is_reserved_variable, valid_profile_name, +}; +use tempfile::TempDir; + +struct Tree { + dir: TempDir, +} + +impl Tree { + fn new() -> Self { + Self { + dir: tempfile::tempdir().expect("fixture tree"), + } + } + + /// The fixture root. On Unix it is resolved, because discovery resolves + /// programs found on `PATH`. + fn base(&self) -> PathBuf { + if cfg!(unix) { + fs::canonicalize(self.dir.path()).expect("resolved fixture root") + } else { + self.dir.path().to_path_buf() + } + } + + fn path(&self, relative: &str) -> PathBuf { + joined_path(&self.base(), relative) + } + + fn dir(&self, relative: &str) -> PathBuf { + let path = self.path(relative); + fs::create_dir_all(&path).expect("fixture directory"); + path + } + + fn file(&self, relative: &str) -> PathBuf { + self.text(relative, "") + } + + fn text(&self, relative: &str, contents: &str) -> PathBuf { + let path = self.path(relative); + fs::create_dir_all(path.parent().expect("parent")).expect("fixture parent"); + fs::write(&path, contents).expect("fixture file"); + path + } + + fn windows(&self) -> DiscoveryHost { + self.dir("Windows/System32"); + DiscoveryHost::rooted_at(ProfilePlatform::Windows, &self.base()) + } + + fn linux(&self) -> DiscoveryHost { + self.dir("usr/bin"); + DiscoveryHost::rooted_at(ProfilePlatform::Linux, &self.base()) + } + + /// An MSVC 14.50 toolset beside an older one, and a Windows SDK whose + /// newest version lacks x64 `ucrt` libraries. + fn msvc(&self) { + for version in ["14.44.35207", "14.50.35717"] { + self.file(&format!( + "Program Files/Microsoft Visual Studio/18/Community/VC/Tools/MSVC/{version}/bin/Hostx64/x64/cl.exe" + )); + } + let kits = "Program Files (x86)/Windows Kits/10"; + self.dir(&format!("{kits}/Lib/10.0.26100.0/um/x64")); + self.dir(&format!("{kits}/Lib/10.0.26100.0/ucrt/x64")); + self.dir(&format!("{kits}/Lib/10.0.99999.0/um/x64")); + self.dir(&format!("{kits}/bin/10.0.26100.0/x64")); + } + + fn tools(&self) -> PathBuf { + self.path("Program Files/Microsoft Visual Studio/18/Community/VC/Tools/MSVC/14.50.35717") + } + + fn kits(&self) -> PathBuf { + self.path("Program Files (x86)/Windows Kits/10") + } +} + +fn named<'a>(proposals: &'a [ToolchainProposal], name: &str) -> &'a ToolchainProposal { + proposals + .iter() + .find(|proposal| proposal.name() == name) + .unwrap_or_else(|| panic!("no proposal {name}: {:?}", names(proposals))) +} + +fn names(proposals: &[ToolchainProposal]) -> Vec<&str> { + proposals.iter().map(ToolchainProposal::name).collect() +} + +fn of_family(proposals: &[ToolchainProposal], family: ToolchainFamily) -> Vec<&str> { + proposals + .iter() + .filter(|proposal| proposal.family() == family) + .map(ToolchainProposal::name) + .collect() +} + +fn variable<'a>(proposal: &'a ToolchainProposal, name: &str) -> Option<&'a str> { + proposal + .environment() + .iter() + .find(|(variable, _)| variable == name) + .map(|(_, value)| value.as_str()) +} + +fn variable_names(proposal: &ToolchainProposal) -> Vec<&str> { + proposal + .environment() + .iter() + .map(|(name, _)| name.as_str()) + .collect() +} + +#[test] +fn windows_rust_uses_the_toolchain_directory_with_msvc_and_never_the_cargo_home() { + let tree = Tree::new(); + let host = tree.windows(); + tree.msvc(); + let rustup = "Users/operator/.rustup"; + tree.text( + &format!("{rustup}/settings.toml"), + "version = \"12\"\ndefault_toolchain = \"stable-x86_64-pc-windows-msvc\"\n", + ); + for toolchain in [ + "stable-x86_64-pc-windows-msvc", + "1.99.1-x86_64-pc-windows-msvc", + ] { + tree.file(&format!("{rustup}/toolchains/{toolchain}/bin/rustc.exe")); + } + tree.dir(&format!("{rustup}/toolchains/incomplete/bin")); + tree.file("Users/operator/.cargo/bin/cargo.exe"); + tree.text( + "Users/operator/.cargo/credentials.toml", + "token = \"secret\"", + ); + + let proposals = discover(&host.with_search_path(vec![tree.path("Users/operator/.cargo/bin")])); + assert_eq!( + of_family(&proposals, ToolchainFamily::Rust), + ["rust", "rust-1.99.1-x86_64-pc-windows-msvc"] + ); + let rust = named(&proposals, "rust"); + let toolchain = tree.path(&format!( + "{rustup}/toolchains/stable-x86_64-pc-windows-msvc" + )); + let system = tree.path("Windows/System32"); + assert_eq!( + rust.read_only_roots(), + [toolchain.clone(), tree.tools(), tree.kits(), system.clone()] + ); + assert_eq!( + rust.path_entries(), + [ + toolchain.join("bin"), + tree.tools().join("bin").join("Hostx64").join("x64"), + tree.kits().join("bin").join("10.0.26100.0").join("x64"), + system, + ] + ); + assert_eq!(variable_names(rust), ["INCLUDE", "LIB", "VCINSTALLDIR"]); + assert!(rust.notes().contains(&ProposalNote::OfflineDependencies)); + assert!(!rust.notes().contains(&ProposalNote::NoMsvc)); + assert!(!rust.notes().contains(&ProposalNote::NotQualified)); + for proposal in &proposals { + assert!( + proposal + .read_only_roots() + .iter() + .all(|root| !root.starts_with(tree.path("Users/operator/.cargo"))), + "{proposal:?}" + ); + assert!( + proposal + .environment() + .iter() + .all(|(name, _)| !name.starts_with("RUSTUP") && name != "CARGO_HOME") + ); + } +} + +#[test] +fn a_short_default_toolchain_name_selects_its_directory() { + let tree = Tree::new(); + let host = tree.linux(); + let rustup = "home/operator/.rustup"; + tree.text( + &format!("{rustup}/settings.toml"), + "default_toolchain = \"stable\"\n", + ); + for toolchain in [ + "1.99.1-x86_64-unknown-linux-gnu", + "stable-x86_64-unknown-linux-gnu", + ] { + tree.file(&format!("{rustup}/toolchains/{toolchain}/bin/rustc")); + } + let proposals = discover(&host); + let rust = named(&proposals, "rust"); + assert_eq!(rust.version(), Some("stable-x86_64-unknown-linux-gnu")); + assert!(variable_names(rust).is_empty()); + named(&proposals, "rust-1.99.1-x86_64-unknown-linux-gnu"); +} + +#[test] +fn a_windows_msvc_rust_toolchain_without_msvc_says_linking_fails() { + let tree = Tree::new(); + let host = tree.windows(); + tree.file("Users/operator/.rustup/toolchains/stable-x86_64-pc-windows-msvc/bin/rustc.exe"); + tree.file("Users/operator/.rustup/toolchains/stable-x86_64-pc-windows-gnu/bin/rustc.exe"); + let proposals = discover(&host); + let msvc = proposals + .iter() + .find(|p| p.version() == Some("stable-x86_64-pc-windows-msvc")) + .expect("msvc toolchain"); + assert!(msvc.notes().contains(&ProposalNote::NoMsvc)); + assert_eq!(msvc.read_only_roots().len(), 2); + let gnu = proposals + .iter() + .find(|p| p.version() == Some("stable-x86_64-pc-windows-gnu")) + .expect("gnu toolchain"); + assert!(!gnu.notes().contains(&ProposalNote::NoMsvc)); +} + +#[test] +fn msvc_uses_the_newest_toolset_and_the_newest_sdk_with_x64_libraries() { + let tree = Tree::new(); + let host = tree.windows(); + tree.msvc(); + let proposals = discover(&host); + assert_eq!(of_family(&proposals, ToolchainFamily::CCpp), ["msvc"]); + let msvc = named(&proposals, "msvc"); + assert_eq!( + msvc.version(), + Some("MSVC 14.50.35717, Windows SDK 10.0.26100.0") + ); + let tools = tree.tools(); + let include = tree.kits().join("Include").join("10.0.26100.0"); + let lib = tree.kits().join("Lib").join("10.0.26100.0"); + let list = |paths: &[PathBuf]| { + paths + .iter() + .map(|path| path.to_str().expect("UTF-8").to_owned()) + .collect::>() + .join(";") + }; + assert_eq!( + variable(msvc, "INCLUDE"), + Some( + list(&[ + tools.join("include"), + include.join("ucrt"), + include.join("um"), + include.join("shared"), + ]) + .as_str() + ) + ); + assert_eq!( + variable(msvc, "LIB"), + Some( + list(&[ + tools.join("lib").join("x64"), + lib.join("ucrt").join("x64"), + lib.join("um").join("x64"), + ]) + .as_str() + ) + ); + let vc = tree.path("Program Files/Microsoft Visual Studio/18/Community/VC"); + assert_eq!( + variable(msvc, "VCINSTALLDIR"), + Some(format!("{}\\", vc.to_str().expect("UTF-8")).as_str()) + ); + assert!(!msvc.notes().contains(&ProposalNote::NotQualified)); +} + +#[test] +fn windows_clang_and_mingw_gcc_are_proposed_and_marked_unqualified() { + let tree = Tree::new(); + let host = tree.windows(); + tree.msvc(); + tree.file("Program Files/LLVM/bin/clang.exe"); + tree.dir("Program Files/LLVM/lib/clang/19"); + tree.file("msys64/ucrt64/bin/gcc.exe"); + tree.dir("msys64/ucrt64/lib/gcc/x86_64-w64-mingw32/14.2.0"); + let proposals = discover(&host); + assert_eq!( + of_family(&proposals, ToolchainFamily::CCpp), + ["msvc", "clang", "gcc"] + ); + let clang = named(&proposals, "clang"); + assert_eq!(clang.version(), Some("19")); + assert_eq!( + clang.read_only_roots()[..3], + [tree.path("Program Files/LLVM"), tree.tools(), tree.kits()] + ); + assert!(clang.notes().contains(&ProposalNote::NotQualified)); + let gcc = named(&proposals, "gcc"); + assert_eq!(gcc.version(), Some("14.2.0")); + assert_eq!( + gcc.read_only_roots(), + [tree.path("msys64/ucrt64"), tree.path("Windows/System32")] + ); + assert!(gcc.notes().contains(&ProposalNote::NotQualified)); +} + +#[test] +fn java_homes_set_java_home_and_are_named_by_major_version() { + let tree = Tree::new(); + let host = tree.windows(); + let jdk = tree.dir("Program Files/Eclipse Adoptium/jdk-21.0.2.13-hotspot"); + tree.file("Program Files/Eclipse Adoptium/jdk-21.0.2.13-hotspot/bin/java.exe"); + tree.file("Program Files/Eclipse Adoptium/jdk-21.0.2.13-hotspot/bin/javac.exe"); + tree.text( + "Program Files/Eclipse Adoptium/jdk-21.0.2.13-hotspot/release", + "IMPLEMENTOR=\"Eclipse Adoptium\"\nJAVA_VERSION=\"21.0.2\"\n", + ); + tree.file("Program Files/Java/jre-17/bin/java.exe"); + tree.text( + "Program Files/Java/jre-17/release", + "JAVA_VERSION=\"17.0.1\"\n", + ); + tree.dir("Program Files/Microsoft/Edge"); + let proposals = discover(&host); + assert_eq!( + of_family(&proposals, ToolchainFamily::Java), + ["java", "java-17"] + ); + let java = named(&proposals, "java"); + assert_eq!(java.version(), Some("21.0.2")); + assert_eq!(variable(java, "JAVA_HOME"), jdk.to_str()); + assert_eq!(java.path_entries()[0], jdk.join("bin")); + assert!(!java.notes().contains(&ProposalNote::JavaRuntimeOnly)); + assert!( + named(&proposals, "java-17") + .notes() + .contains(&ProposalNote::JavaRuntimeOnly) + ); +} + +#[test] +fn windows_python_needs_its_standard_library_and_skips_shims_aliases_and_venvs() { + let tree = Tree::new(); + let local = "Users/operator/AppData/Local"; + let user = tree.dir(&format!("{local}/Programs/Python/Python313")); + tree.file(&format!("{local}/Programs/Python/Python313/python.exe")); + tree.file(&format!("{local}/Programs/Python/Python313/python313.dll")); + tree.dir(&format!("{local}/Programs/Python/Python313/Lib")); + tree.dir(&format!("{local}/Programs/Python/Python313/Scripts")); + let system = tree.dir("Python314"); + tree.file("Python314/python.exe"); + tree.file("Python314/python314.dll"); + tree.dir("Python314/Lib"); + let shim = tree.dir(&format!("{local}/Python/bin")); + tree.file(&format!("{local}/Python/bin/python.exe")); + let alias = tree.dir(&format!("{local}/Microsoft/WindowsApps")); + tree.file(&format!("{local}/Microsoft/WindowsApps/python.exe")); + let venv = tree.dir("work/.venv/Scripts"); + tree.file("work/.venv/Scripts/python.exe"); + tree.file("work/.venv/pyvenv.cfg"); + let host = tree + .windows() + .with_search_path(vec![shim, alias, venv, system.clone()]); + let proposals = discover(&host); + assert_eq!( + of_family(&proposals, ToolchainFamily::Python), + ["python", "python-3.13"] + ); + assert_eq!(named(&proposals, "python").read_only_roots()[0], system); + let older = named(&proposals, "python-3.13"); + assert_eq!(older.version(), Some("3.13")); + assert_eq!( + older.path_entries(), + [ + user.clone(), + user.join("Scripts"), + tree.path("Windows/System32") + ] + ); +} + +#[test] +fn strawberry_perl_lists_its_bins_and_git_perl_is_skipped() { + let tree = Tree::new(); + tree.file("Strawberry/perl/bin/perl.exe"); + tree.dir("Strawberry/perl/site/bin"); + tree.dir("Strawberry/c/bin"); + let git = tree.dir("Program Files/Git/usr/bin"); + tree.file("Program Files/Git/usr/bin/perl.exe"); + let host = tree.windows().with_search_path(vec![git]); + let proposals = discover(&host); + assert_eq!(of_family(&proposals, ToolchainFamily::Perl), ["perl"]); + let perl = named(&proposals, "perl"); + assert_eq!( + perl.read_only_roots(), + [tree.path("Strawberry"), tree.path("Windows/System32")] + ); + assert_eq!( + perl.path_entries()[..3], + [ + tree.path("Strawberry/perl/site/bin"), + tree.path("Strawberry/perl/bin"), + tree.path("Strawberry/c/bin"), + ] + ); + // Strawberry's MinGW is a C compiler too, but only through `PATH`. + assert!(of_family(&proposals, ToolchainFamily::CCpp).is_empty()); +} + +#[test] +fn go_sets_its_root_and_never_switches_toolchains() { + let tree = Tree::new(); + let host = tree.windows(); + let go = tree.dir("Program Files/Go"); + tree.file("Program Files/Go/bin/go.exe"); + tree.text( + "Program Files/Go/VERSION", + "go1.27.4\ntime 2026-10-01T00:00:00Z\n", + ); + let proposals = discover(&host.with_goroot(go.clone())); + assert_eq!(of_family(&proposals, ToolchainFamily::Go), ["go"]); + let proposal = named(&proposals, "go"); + assert_eq!(proposal.version(), Some("1.27.4")); + assert_eq!(variable(proposal, "GOROOT"), go.to_str()); + assert_eq!(variable(proposal, "GOTOOLCHAIN"), Some("local")); + assert_eq!(variable(proposal, "GOENV"), Some("off")); + assert_eq!(variable(proposal, "GOFLAGS"), Some("-buildvcs=false")); +} + +#[test] +fn windows_node_preserves_symlinks_and_skips_shim_folders() { + let tree = Tree::new(); + tree.file("Program Files/nodejs/node.exe"); + tree.dir("Program Files/nodejs/node_modules/npm"); + let nvm = "Users/operator/AppData/Roaming/nvm/v20.11.0"; + tree.file(&format!("{nvm}/node.exe")); + tree.dir(&format!("{nvm}/node_modules")); + let volta = tree.dir("Users/operator/AppData/Local/Volta/bin"); + tree.file("Users/operator/AppData/Local/Volta/bin/node.exe"); + let host = tree.windows().with_search_path(vec![volta]); + let proposals = discover(&host); + assert_eq!( + of_family(&proposals, ToolchainFamily::Node), + ["node", "node-2"] + ); + for proposal in proposals + .iter() + .filter(|p| p.family() == ToolchainFamily::Node) + { + assert_eq!( + variable(proposal, "NODE_OPTIONS"), + Some("--preserve-symlinks --preserve-symlinks-main") + ); + assert!( + proposal + .notes() + .contains(&ProposalNote::NodeWindowsChildren) + ); + } + assert_eq!(named(&proposals, "node").version(), Some("20.11.0")); +} + +#[test] +fn dotnet_reports_its_sdk_or_that_it_is_a_runtime() { + let tree = Tree::new(); + let host = tree.windows(); + let machine = tree.dir("Program Files/dotnet"); + tree.file("Program Files/dotnet/dotnet.exe"); + tree.dir("Program Files/dotnet/shared/Microsoft.NETCore.App/9.0.1"); + tree.dir("Program Files/dotnet/sdk/9.0.100"); + tree.file("Users/operator/.dotnet/dotnet.exe"); + tree.dir("Users/operator/.dotnet/shared/Microsoft.NETCore.App/8.0.5"); + let proposals = discover(&host); + assert_eq!( + of_family(&proposals, ToolchainFamily::DotNet), + ["dotnet", "dotnet-8.0.5"] + ); + let sdk = named(&proposals, "dotnet"); + assert_eq!(sdk.version(), Some("SDK 9.0.100")); + assert_eq!(variable(sdk, "DOTNET_ROOT"), machine.to_str()); + assert_eq!(variable(sdk, "DOTNET_CLI_TELEMETRY_OPTOUT"), Some("1")); + assert!( + named(&proposals, "dotnet-8.0.5") + .notes() + .contains(&ProposalNote::DotnetRuntimeOnly) + ); +} + +#[test] +fn windows_ruby_comes_from_rubyinstaller_folders() { + let tree = Tree::new(); + let host = tree.windows(); + tree.file("Ruby33-x64/bin/ruby.exe"); + tree.dir("Ruby33-x64/lib/ruby/3.3.0"); + tree.dir("Ruby33-x64/lib/ruby/site_ruby"); + let proposals = discover(&host); + let ruby = named(&proposals, "ruby"); + assert_eq!(ruby.version(), Some("3.3.0")); + assert_eq!(ruby.path_entries()[0], tree.path("Ruby33-x64/bin")); +} + +#[test] +fn linux_compilers_in_usr_share_the_system_roots() { + let tree = Tree::new(); + let host = tree.linux(); + tree.dir("lib/x86_64-linux-gnu"); + tree.file("usr/bin/gcc"); + tree.dir("usr/lib/gcc/x86_64-linux-gnu/13"); + tree.file("usr/bin/clang"); + tree.dir("usr/lib/llvm-18"); + let proposals = discover(&host); + assert_eq!( + of_family(&proposals, ToolchainFamily::CCpp), + ["gcc", "clang"] + ); + let gcc = named(&proposals, "gcc"); + assert_eq!(gcc.version(), Some("13")); + assert_eq!(gcc.read_only_roots(), [tree.path("usr"), tree.path("lib")]); + assert_eq!(gcc.path_entries(), [tree.path("usr/bin")]); + assert!(!gcc.notes().contains(&ProposalNote::NotQualified)); + let clang = named(&proposals, "clang"); + assert_eq!(clang.version(), Some("18")); + assert!(clang.notes().contains(&ProposalNote::NotQualified)); +} + +#[cfg(unix)] +#[test] +fn linked_top_level_directories_and_jdk_aliases_are_not_listed_twice() { + let tree = Tree::new(); + let host = tree.linux(); + tree.dir("usr/lib64"); + std::os::unix::fs::symlink(tree.path("usr/lib64"), tree.path("lib64")).expect("link"); + let jdk = "usr/lib/jvm/java-21-openjdk-amd64"; + tree.file(&format!("{jdk}/bin/java")); + tree.file(&format!("{jdk}/bin/javac")); + std::os::unix::fs::symlink(tree.path(jdk), tree.path("usr/lib/jvm/default-java")) + .expect("alias"); + let proposals = discover(&host); + assert_eq!(of_family(&proposals, ToolchainFamily::Java), ["java"]); + let java = named(&proposals, "java"); + assert_eq!(java.read_only_roots(), [tree.path("usr")]); + assert_eq!( + java.path_entries(), + [tree.path(&format!("{jdk}/bin")), tree.path("usr/bin")] + ); + assert_eq!(variable(java, "JAVA_HOME"), tree.path(jdk).to_str()); +} + +#[cfg(unix)] +#[test] +fn a_path_program_resolves_to_its_installation() { + let tree = Tree::new(); + let host = tree.linux(); + // Not a standard Go location: only the link on `PATH` leads here. + let go = "srv/toolchains/go"; + tree.file(&format!("{go}/bin/go")); + tree.text(&format!("{go}/VERSION"), "go1.22.2\n"); + std::os::unix::fs::symlink(tree.path(&format!("{go}/bin/go")), tree.path("usr/bin/go")) + .expect("link"); + assert!(of_family(&discover(&host), ToolchainFamily::Go).is_empty()); + let proposals = discover(&host.with_search_path(vec![tree.path("usr/bin")])); + assert_eq!(of_family(&proposals, ToolchainFamily::Go), ["go"]); + let proposal = named(&proposals, "go"); + assert_eq!(variable(proposal, "GOROOT"), tree.path(go).to_str()); + assert_eq!( + proposal.read_only_roots(), + [tree.path(go), tree.path("usr")] + ); +} + +#[cfg(unix)] +#[test] +fn a_bin_at_the_filesystem_root_is_never_proposed_as_a_root() { + let tree = Tree::new(); + let host = tree.linux(); + tree.file("bin/gcc"); + let proposals = discover(&host.with_search_path(vec![tree.path("bin")])); + for proposal in &proposals { + assert!( + proposal + .read_only_roots() + .iter() + .all(|root| *root != tree.base()), + "{proposal:?}" + ); + } +} + +#[test] +fn a_windows_install_at_the_drive_root_is_never_proposed() { + let tree = Tree::new(); + tree.file("python.exe"); + tree.dir("Lib"); + let host = tree.windows().with_search_path(vec![tree.base()]); + assert!(of_family(&discover(&host), ToolchainFamily::Python).is_empty()); +} + +#[test] +fn linux_python_comes_from_usr_and_pyenv_and_skips_virtual_environments() { + let tree = Tree::new(); + let host = tree.linux(); + tree.file("usr/bin/python3"); + tree.dir("usr/lib/python3.12"); + tree.dir("usr/lib/python3"); + let pyenv = "home/operator/.pyenv/versions/3.13.1"; + tree.file(&format!("{pyenv}/bin/python3")); + tree.dir(&format!("{pyenv}/lib/python3.13")); + let venv = "work/.venv"; + tree.file(&format!("{venv}/bin/python3")); + tree.dir(&format!("{venv}/lib/python3.12")); + tree.file(&format!("{venv}/pyvenv.cfg")); + let proposals = discover(&host.with_search_path(vec![tree.path(&format!("{venv}/bin"))])); + assert_eq!( + of_family(&proposals, ToolchainFamily::Python), + ["python", "python-3.12"] + ); + assert_eq!( + named(&proposals, "python").read_only_roots(), + [tree.path(pyenv), tree.path("usr")] + ); + assert_eq!( + named(&proposals, "python-3.12").read_only_roots(), + [tree.path("usr")] + ); +} + +#[test] +fn a_distribution_node_also_reads_etc_ssl() { + let tree = Tree::new(); + let host = tree.linux(); + tree.file("usr/bin/node"); + tree.dir("etc/ssl/certs"); + let nvm = "home/operator/.nvm/versions/node/v22.1.0"; + tree.file(&format!("{nvm}/bin/node")); + let proposals = discover(&host); + assert_eq!( + of_family(&proposals, ToolchainFamily::Node), + ["node", "node-2"] + ); + let nvm_node = named(&proposals, "node"); + assert_eq!(nvm_node.version(), Some("22.1.0")); + assert_eq!( + nvm_node.read_only_roots(), + [tree.path(nvm), tree.path("usr")] + ); + assert_eq!( + named(&proposals, "node-2").read_only_roots(), + [tree.path("usr"), tree.path("etc/ssl")] + ); + assert!(nvm_node.environment().is_empty()); +} + +#[test] +fn linux_go_perl_ruby_and_dotnet_are_found_in_their_standard_places() { + let tree = Tree::new(); + let host = tree.linux(); + tree.file("usr/local/go/bin/go"); + tree.text("usr/local/go/VERSION", "go1.26.10\n"); + tree.file("usr/bin/perl"); + tree.dir("usr/share/perl/5.38.2"); + tree.file("usr/bin/ruby"); + tree.dir("usr/lib/ruby/3.2.0"); + tree.dir("usr/lib/ruby/vendor_ruby"); + tree.file("home/operator/.dotnet/dotnet"); + tree.dir("home/operator/.dotnet/shared/Microsoft.NETCore.App/8.0.5"); + tree.dir("home/operator/.dotnet/sdk/8.0.100"); + let proposals = discover(&host); + assert_eq!(named(&proposals, "go").version(), Some("1.26.10")); + assert_eq!( + named(&proposals, "go").read_only_roots(), + [tree.path("usr")] + ); + assert_eq!(named(&proposals, "perl").version(), Some("5.38.2")); + assert_eq!(named(&proposals, "ruby").version(), Some("3.2.0")); + let dotnet = named(&proposals, "dotnet"); + assert_eq!(dotnet.version(), Some("SDK 8.0.100")); + assert_eq!( + dotnet.read_only_roots(), + [tree.path("home/operator/.dotnet"), tree.path("usr")] + ); +} + +/// A host with every family installed, for the invariants below. +fn everything() -> (Tree, Vec) { + let tree = Tree::new(); + let host = tree.windows(); + tree.msvc(); + tree.file("Users/operator/.rustup/toolchains/stable-x86_64-pc-windows-msvc/bin/rustc.exe"); + tree.file("Program Files/LLVM/bin/clang.exe"); + tree.file("Program Files/Java/jdk-21/bin/java.exe"); + tree.file("Python314/python.exe"); + tree.dir("Python314/Lib"); + tree.file("Strawberry/perl/bin/perl.exe"); + tree.file("Program Files/Go/bin/go.exe"); + tree.file("Program Files/Go/VERSION"); + tree.file("Program Files/nodejs/node.exe"); + tree.dir("Program Files/nodejs/node_modules"); + tree.file("Program Files/dotnet/dotnet.exe"); + tree.dir("Program Files/dotnet/shared"); + tree.file("Ruby33-x64/bin/ruby.exe"); + tree.dir("Ruby33-x64/lib/ruby"); + let proposals = discover(&host); + (tree, proposals) +} + +#[test] +fn every_family_has_a_detector_and_a_proposal_on_a_full_host() { + let (_tree, proposals) = everything(); + for family in [ + ToolchainFamily::Rust, + ToolchainFamily::CCpp, + ToolchainFamily::Java, + ToolchainFamily::Python, + ToolchainFamily::Perl, + ToolchainFamily::Go, + ToolchainFamily::Node, + ToolchainFamily::DotNet, + ToolchainFamily::Ruby, + ] { + assert!( + !of_family(&proposals, family).is_empty(), + "{family:?}: {:?}", + names(&proposals) + ); + } + assert_eq!( + names(&proposals), + [ + "rust", "msvc", "clang", "java", "python", "perl", "go", "node", "dotnet", "ruby" + ] + ); +} + +#[test] +fn every_proposal_meets_cores_shape_rules() { + let (_tree, proposals) = everything(); + assert_core_shape(&proposals); +} + +/// Discovery on this computer, for a manual check: run with `--ignored +/// --nocapture`. It only reads folders, and asserts the same shape rules as +/// the fixture tests; what it finds depends on what is installed. +#[test] +#[ignore = "reads this computer's install folders; run by hand"] +fn this_computer_yields_proposals_that_meet_cores_shape_rules() { + let host = DiscoveryHost::from_environment().expect("Linux or Windows"); + let proposals = discover(&host); + for proposal in &proposals { + println!( + "{} [{}] {:?} roots={:?} path={:?} variables={:?} notes={:?}", + proposal.name(), + proposal.family().label(), + proposal.version(), + proposal.read_only_roots(), + proposal.path_entries(), + proposal + .environment() + .iter() + .map(|(name, _)| name) + .collect::>(), + proposal.notes(), + ); + } + assert_core_shape(&proposals); + assert!(proposals.len() <= MAX_PROPOSALS); +} + +fn assert_core_shape(proposals: &[ToolchainProposal]) { + let mut seen: Vec = Vec::new(); + for proposal in proposals { + let name = proposal.name(); + assert!(valid_profile_name(name), "{name}"); + assert!(!seen.iter().any(|other| other.eq_ignore_ascii_case(name))); + seen.push(name.to_owned()); + assert!((1..=MAX_PROFILE_ROOTS).contains(&proposal.read_only_roots().len())); + assert!(proposal.path_entries().len() <= MAX_PROFILE_PATH_ENTRIES); + for entry in proposal.path_entries() { + assert!( + proposal + .read_only_roots() + .iter() + .any(|root| entry.starts_with(root)), + "{entry:?} in {proposal:?}" + ); + } + assert!(proposal.environment().len() <= MAX_PROFILE_VARIABLES); + for (variable, value) in proposal.environment() { + assert!(!is_reserved_variable(variable), "{variable}"); + assert!(value.len() <= MAX_VARIABLE_VALUE_BYTES && !value.contains('\0')); + } + let declaration = proposal.declaration(); + assert_eq!(declaration.name, name); + assert_eq!(declaration.read_only_roots, proposal.read_only_roots()); + } +} + +#[test] +fn digests_are_stable_distinct_and_cover_every_recorded_value() { + let (_tree, proposals) = everything(); + let (_again, repeated) = everything(); + let digests: Vec = proposals.iter().map(ToolchainProposal::digest).collect(); + for digest in &digests { + assert_eq!(digest.len(), 64); + assert!( + digest + .bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) + ); + } + let mut unique = digests.clone(); + unique.sort(); + unique.dedup(); + assert_eq!(unique.len(), digests.len()); + // Another tree has other paths, so the same names digest differently. + assert_ne!(digests[0], repeated[0].digest()); + let base = proposals[0].clone(); + let mut renamed = base.clone(); + renamed.name.push('x'); + let mut rooted = base.clone(); + rooted.read_only_roots.push(PathBuf::from("/other")); + let mut valued = base.clone(); + valued + .environment + .push(("EXTRA".to_owned(), "1".to_owned())); + for changed in [renamed, rooted, valued] { + assert_ne!(changed.digest(), base.digest()); + } + assert_eq!(base.clone().digest(), base.digest()); +} + +#[test] +fn a_host_with_nothing_installed_proposes_nothing() { + let tree = Tree::new(); + assert!(discover(&tree.windows()).is_empty()); + let other = Tree::new(); + assert!(discover(&other.linux()).is_empty()); +} + +#[test] +fn installations_of_one_name_are_bounded() { + let tree = Tree::new(); + let host = tree.linux(); + for minor in 0..20 { + tree.file(&format!( + "home/operator/.rustup/toolchains/1.{minor}.0-x86_64-unknown-linux-gnu/bin/rustc" + )); + } + let found = discover_bounded(&host); + assert_eq!(found.omitted, 20 - MAX_PER_NAME); + let proposals = found.proposals; + let rust = of_family(&proposals, ToolchainFamily::Rust); + assert_eq!(rust.len(), MAX_PER_NAME); + // Newest first. + assert_eq!(rust[0], "rust"); + assert_eq!( + named(&proposals, "rust").version(), + Some("1.19.0-x86_64-unknown-linux-gnu") + ); +} + +#[test] +fn past_the_proposal_bound_every_name_keeps_its_first_installation() { + let candidate = |family, name: &'static str, variant: usize| { + Candidate::new(family, name, variant.to_string()) + }; + // Listed by family: many under the first names, one under each later one. + let mut ordered: Vec = Vec::new(); + for name in ["rust", "msvc", "java", "python", "perl"] { + for variant in 0..8 { + ordered.push(candidate(ToolchainFamily::Rust, name, variant)); + } + } + ordered.push(candidate(ToolchainFamily::Go, "go", 0)); + ordered.push(candidate(ToolchainFamily::Ruby, "ruby", 0)); + let keep = fair_share(&ordered, MAX_PROPOSALS); + assert_eq!(keep.iter().filter(|kept| **kept).count(), MAX_PROPOSALS); + let kept: Vec<(&str, &str)> = ordered + .iter() + .zip(&keep) + .filter(|(_, kept)| **kept) + .map(|(candidate, _)| (candidate.base_name, candidate.variant.as_str())) + .collect(); + // Six rounds fill the bound: go and ruby keep their only installation, + // and each of the five longer names keeps its first six. + assert!(kept.contains(&("go", "0")) && kept.contains(&("ruby", "0"))); + assert!(kept.contains(&("perl", "5")) && !kept.contains(&("rust", "6"))); + // The list keeps its order. + assert_eq!(kept.first(), Some(&("rust", "0"))); + assert_eq!(kept.last(), Some(&("ruby", "0"))); + assert_eq!(fair_share(&ordered[..3], MAX_PROPOSALS), [true, true, true]); +} + +#[test] +fn a_long_listing_keeps_the_first_directories_by_name_after_filtering() { + let tree = Tree::new(); + let lib = tree.dir("usr/lib"); + for index in 0..MAX_LISTED_ENTRIES + 88 { + tree.dir(&format!("usr/lib/aa-{index:04}")); + } + tree.file("usr/lib/go-file"); + // Sorts after every `aa-` directory, so a cut before the filter could + // lose it whatever order the filesystem lists entries in. + tree.dir("usr/lib/go-1.22"); + let all = child_directories(&lib); + assert_eq!(all.len(), MAX_LISTED_ENTRIES); + assert_eq!(all.first(), Some(&tree.path("usr/lib/aa-0000"))); + assert!(all.windows(2).all(|pair| pair[0] < pair[1])); + assert_eq!( + child_directories_named(&lib, "GO"), + [tree.path("usr/lib/go-1.22")] + ); +} + +#[cfg(unix)] +#[test] +fn a_root_that_is_a_link_is_not_proposed() { + let tree = Tree::new(); + let host = tree.linux(); + // Outside every standard location, so only `JAVA_HOME` leads here. + let jdk = "srv/jdk-21"; + tree.file(&format!("{jdk}/bin/java")); + tree.file(&format!("{jdk}/bin/javac")); + std::os::unix::fs::symlink(tree.path(jdk), tree.path("srv/java-current")).expect("link"); + let linked = discover(&host.clone().with_java_home(tree.path("srv/java-current"))); + assert!(of_family(&linked, ToolchainFamily::Java).is_empty()); + let real = discover(&host.with_java_home(tree.path(jdk))); + assert_eq!(of_family(&real, ToolchainFamily::Java), ["java"]); + assert_eq!( + named(&real, "java").read_only_roots(), + [tree.path(jdk), tree.path("usr")] + ); +} + +/// A FIFO where an installer file belongs is refused before it is opened, so +/// it cannot block discovery. Discovery runs in a child process, so a +/// regression fails at a deadline instead of hanging the test run. +#[cfg(target_os = "linux")] +#[test] +fn a_fifo_at_an_installer_file_does_not_block_discovery() { + use std::process::{Command, Stdio}; + use std::thread; + use std::time::{Duration, Instant}; + + const CHILD_MARKER: &str = "OMGCODE_DISCOVERY_FIFO_CHILD"; + const DEADLINE: Duration = Duration::from_secs(5); + const POLL: Duration = Duration::from_millis(10); + + if std::env::var_os(CHILD_MARKER).is_some() { + let tree = Tree::new(); + let host = tree.linux(); + tree.file("usr/local/go/bin/go"); + tree.dir("usr/local/go/src/runtime"); + let status = Command::new("mkfifo") + .arg(tree.path("usr/local/go/VERSION")) + .status() + .expect("create FIFO fixture"); + assert!(status.success(), "mkfifo must create the fixture"); + assert_eq!(of_family(&discover(&host), ToolchainFamily::Go), ["go"]); + return; + } + + let executable = std::env::current_exe().expect("locate the unit test executable"); + let mut child = Command::new(executable) + .arg("--exact") + .arg("toolchain_discovery::tests::a_fifo_at_an_installer_file_does_not_block_discovery") + .env(CHILD_MARKER, "1") + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + .expect("start bounded FIFO child"); + let deadline = Instant::now() + DEADLINE; + loop { + match child.try_wait().expect("check FIFO child status") { + Some(status) => { + assert!(status.success(), "the FIFO child must finish discovery"); + break; + } + None if Instant::now() < deadline => thread::sleep(POLL), + None => { + child.kill().expect("terminate hung FIFO child"); + let _ = child.wait().expect("reap FIFO child"); + panic!("discovery blocked on a FIFO past the five-second deadline"); + } + } + } +} + +#[test] +fn names_keep_to_cores_rule_and_never_repeat() { + assert_eq!(profile_name("java", "21"), "java-21"); + assert_eq!( + profile_name("rust", "nightly 2026/01+x"), + "rust-nightly-2026-01-x" + ); + assert_eq!(profile_name("node", ""), "node"); + assert_eq!(profile_name("go", "..."), "go"); + let long = profile_name("rust", &"a".repeat(100)); + assert_eq!(long.len(), MAX_PROFILE_NAME_CHARS); + assert!(valid_profile_name(&long)); + let taken = vec!["node".to_owned(), "NODE-2".to_owned()]; + assert_eq!(unique_name("node", &taken), "node-3"); + assert_eq!( + unique_name(&long, std::slice::from_ref(&long)).len(), + MAX_PROFILE_NAME_CHARS + ); +} + +#[test] +fn versions_compare_by_their_numbers() { + assert!(version_key("1.99.1") > version_key("1.9.2")); + assert!(version_key("10.0.26100.0") > version_key("10.0.22621.0")); + assert!(version_key("") < version_key("0")); +} diff --git a/crates/omgcode-desktop/capabilities/settings.json b/crates/omgcode-desktop/capabilities/settings.json index ce9eb99b..19e509a9 100644 --- a/crates/omgcode-desktop/capabilities/settings.json +++ b/crates/omgcode-desktop/capabilities/settings.json @@ -8,6 +8,7 @@ ], "permissions": [ "allow-settings-add-connection", + "allow-settings-add-discovered-profiles", "allow-settings-add-package-profile", "allow-settings-add-toolchain-profile", "allow-settings-add-web-fetch-host", @@ -16,7 +17,9 @@ "allow-settings-choose-root", "allow-settings-clear-package-cache", "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", diff --git a/crates/omgcode-desktop/src/command_names.rs b/crates/omgcode-desktop/src/command_names.rs index 86510d55..624d8d75 100644 --- a/crates/omgcode-desktop/src/command_names.rs +++ b/crates/omgcode-desktop/src/command_names.rs @@ -67,4 +67,7 @@ pub const COMMAND_NAMES: &[&str] = &[ "settings_add_web_fetch_host", "settings_remove_web_fetch_host", "session_web_audit", + "settings_discover_toolchains", + "settings_add_discovered_profiles", + "settings_grant_discovered_roots", ]; diff --git a/crates/omgcode-desktop/src/commands/settings.rs b/crates/omgcode-desktop/src/commands/settings.rs index 9930cde3..dccb429b 100644 --- a/crates/omgcode-desktop/src/commands/settings.rs +++ b/crates/omgcode-desktop/src/commands/settings.rs @@ -12,11 +12,12 @@ use omgcode_app::desktop::{ ApiKeySetRequest, ApiKeyText, ChatBudgetsDto, ChatBudgetsSaveRequest, ChatGptRequest, ChatGptSignOutResult, ConnectionAddRequest, ConnectionRemoveRequest, ConnectionSelectRequest, - ContainerAccessChoice, ContainerGrantRequest, ContainerRevokeRequest, EnvironmentEntry, - NewConnectionKind, PackageProfileAddRequest, PermissionFlags, PermissionsChangeRequest, - ProfileRemoveRequest, SettingsOverview, SettingsRevisionRequest, SkillChoice, - SkillRemoveRequest, SkillStateRequest, ToolchainProfileAddRequest, WebHostChangeRequest, - WorkspaceInstructionsRequest, WorkspaceRevisionRequest, + ContainerAccessChoice, ContainerGrantRequest, ContainerRevokeRequest, DiscoveredGrantsRequest, + DiscoveredProfilesRequest, EnvironmentEntry, NewConnectionKind, PackageProfileAddRequest, + PermissionFlags, PermissionsChangeRequest, ProfileRemoveRequest, SettingsOverview, + SettingsRevisionRequest, SkillChoice, SkillRemoveRequest, SkillStateRequest, + ToolchainDiscovery, ToolchainDiscoveryRequest, ToolchainProfileAddRequest, + WebHostChangeRequest, WorkspaceInstructionsRequest, WorkspaceRevisionRequest, discovery_host, }; use tauri::Webview; use uuid::Uuid; @@ -717,6 +718,94 @@ pub async fn settings_revoke_container_grant( .await } +/// `settings` only. Reads this computer's standard install locations and the +/// operator's `PATH` and returns a toolchain profile proposal for each +/// toolchain found, checked against the settings (ADR-0103). No program runs, +/// no workspace file is read, and nothing is recorded. With `workspace_id`, +/// on Windows, each root says whether that workspace's container can read it. +/// +/// # Errors +/// +/// `forbidden_window`, or the service's error (`unsupported_platform`, +/// `unknown_workspace`, `busy`). +#[tauri::command(rename_all = "snake_case")] +pub async fn settings_discover_toolchains( + webview: Webview, + state: Service<'_>, + workspace_id: Option, +) -> Result { + authorize(Command::SettingsDiscoverToolchains, webview.label())?; + let request = ToolchainDiscoveryRequest { workspace_id }; + blocking(&state, move |service| { + service.settings_discover_toolchains(request, &discovery_host()?) + }) + .await +} + +/// `settings` only. Discovers again, and after one native confirmation that +/// lists each selected proposal's roots, `PATH` entries, and variables, +/// records the proposals whose digests the window sent as `omgcode workspace +/// profile-add` does (ADR-0103). No path is carried. +/// +/// # Errors +/// +/// `forbidden_window`, or the service's error (`invalid_request`, +/// `discovery_changed`, `cancelled`, `stale_revision`, or `control` with +/// core's reason). +#[tauri::command(rename_all = "snake_case")] +pub async fn settings_add_discovered_profiles( + webview: Webview, + state: Service<'_>, + revision: u64, + digests: Vec, + workspace_id: Option, +) -> Result { + authorize(Command::SettingsAddDiscoveredProfiles, webview.label())?; + let prompt = NativePrompt::new(webview.window()); + let request = DiscoveredProfilesRequest { + revision, + digests, + workspace_id, + }; + blocking(&state, move |service| { + service.settings_add_discovered_profiles(request, &discovery_host()?, &prompt) + }) + .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 2e8feb9c..6c67d74d 100644 --- a/crates/omgcode-desktop/src/lib.rs +++ b/crates/omgcode-desktop/src/lib.rs @@ -209,7 +209,10 @@ fn run_app(service: Arc) -> ExitCode { commands::settings::settings_revoke_container_grant, commands::settings::settings_add_web_fetch_host, commands::settings::settings_remove_web_fetch_host, - commands::sessions::session_web_audit + commands::sessions::session_web_audit, + commands::settings::settings_discover_toolchains, + commands::settings::settings_add_discovered_profiles, + commands::settings::settings_grant_discovered_roots ]) .build(tauri::generate_context!()); match built { diff --git a/crates/omgcode-desktop/src/policy.rs b/crates/omgcode-desktop/src/policy.rs index 26c53021..d4b4190f 100644 --- a/crates/omgcode-desktop/src/policy.rs +++ b/crates/omgcode-desktop/src/policy.rs @@ -102,11 +102,14 @@ pub enum Command { SettingsAddWebFetchHost, SettingsRemoveWebFetchHost, SessionWebAudit, + SettingsDiscoverToolchains, + SettingsAddDiscoveredProfiles, + SettingsGrantDiscoveredRoots, } impl Command { /// All commands, in the order of `command_names.rs`. - pub const ALL: [Self; 63] = [ + pub const ALL: [Self; 66] = [ Self::AppInfo, Self::SessionTree, Self::SessionSearch, @@ -170,6 +173,9 @@ impl Command { Self::SettingsAddWebFetchHost, Self::SettingsRemoveWebFetchHost, Self::SessionWebAudit, + Self::SettingsDiscoverToolchains, + Self::SettingsAddDiscoveredProfiles, + Self::SettingsGrantDiscoveredRoots, ]; /// The command name exactly as the frontend invokes it. @@ -239,6 +245,9 @@ impl Command { Self::SettingsAddWebFetchHost => "settings_add_web_fetch_host", Self::SettingsRemoveWebFetchHost => "settings_remove_web_fetch_host", Self::SessionWebAudit => "session_web_audit", + Self::SettingsDiscoverToolchains => "settings_discover_toolchains", + Self::SettingsAddDiscoveredProfiles => "settings_add_discovered_profiles", + Self::SettingsGrantDiscoveredRoots => "settings_grant_discovered_roots", } } @@ -277,7 +286,10 @@ impl Command { | Self::SettingsGrantContainerFolder | Self::SettingsRevokeContainerGrant | Self::SettingsAddWebFetchHost - | Self::SettingsRemoveWebFetchHost => WindowLabel::Settings, + | Self::SettingsRemoveWebFetchHost + | Self::SettingsDiscoverToolchains + | Self::SettingsAddDiscoveredProfiles + | Self::SettingsGrantDiscoveredRoots => WindowLabel::Settings, Self::AppInfo | Self::SessionTree | Self::SessionSearch @@ -346,10 +358,10 @@ mod tests { #[test] fn every_command_has_exactly_one_window_and_the_counts_match() { - assert_eq!(Command::ALL.len(), 63); + assert_eq!(Command::ALL.len(), 66); assert_eq!(with_window(WindowLabel::Main).len(), 31); assert_eq!(with_window(WindowLabel::Approvals).len(), 3); - assert_eq!(with_window(WindowLabel::Settings).len(), 29); + assert_eq!(with_window(WindowLabel::Settings).len(), 32); } #[test] @@ -453,8 +465,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(), 63); - assert_eq!(shared.len(), 63); + assert_eq!(COMMAND_NAMES.len(), 66); + assert_eq!(shared.len(), 66); 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 c107484a..66702b68 100644 --- a/crates/omgcode-desktop/tests/layers.rs +++ b/crates/omgcode-desktop/tests/layers.rs @@ -162,6 +162,7 @@ fn settings_window_is_granted_only_its_own_commands() { settings, [ "allow-settings-add-connection", + "allow-settings-add-discovered-profiles", "allow-settings-add-package-profile", "allow-settings-add-toolchain-profile", "allow-settings-add-web-fetch-host", @@ -170,7 +171,9 @@ fn settings_window_is_granted_only_its_own_commands() { "allow-settings-choose-root", "allow-settings-clear-package-cache", "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", @@ -248,15 +251,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 63 unique policy names. + // And the shared list holds the 66 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(), 63); - assert_eq!(unique.len(), 63); + assert_eq!(listed.len(), 66); + assert_eq!(unique.len(), 66); let policy: Vec<&str> = Command::ALL.into_iter().map(Command::name).collect(); assert_eq!(listed, policy); } @@ -367,7 +370,7 @@ fn frontend_clients_call_only_commands_the_policy_gives_their_window() { .collect(); assert_eq!(settings_calls, settings_commands); - // ...and together they cover all 63 policy commands. + // ...and together they cover all 66 policy commands. let union: BTreeSet = main_calls .union(&approval_calls) .cloned() @@ -625,10 +628,10 @@ fn generate_handler_registers_exactly_the_policy_commands() { .map(|entry| entry.rsplit("::").next().expect("segment")) .collect(); - // Then they are the 63 shared names, once each. + // Then they are the 66 shared names, once each. let unique: BTreeSet<&str> = registered.iter().copied().collect(); - assert_eq!(registered.len(), 63); - assert_eq!(unique.len(), 63); + assert_eq!(registered.len(), 66); + assert_eq!(unique.len(), 66); let shared: BTreeSet<&str> = COMMAND_NAMES_SOURCE .lines() .filter_map(|line| line.trim().strip_prefix('"')) @@ -645,7 +648,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(), 63); + assert_eq!(handlers.len(), 66); for handler in handlers { // Given the command the function name denotes. let command = Command::ALL @@ -779,7 +782,7 @@ fn handler_parameters_match_the_keys_the_frontend_passes() { } assert_eq!( expected.len(), - 63, + 66, "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 cdb72f80..25d1f3e2 100644 --- a/crates/omgcode-desktop/ui/src/ipc/settings_client.ts +++ b/crates/omgcode-desktop/ui/src/ipc/settings_client.ts @@ -5,6 +5,7 @@ import type { NewConnectionKind, PermissionFlags, SettingsOverview, + ToolchainDiscovery, } from "./types"; /** @@ -195,4 +196,34 @@ export const settingsApi = { revision, grant_id: grantId, }), + /** + * Asks Rust to read this computer's install folders and `PATH` and propose toolchain profiles + * (ADR-0103). Nothing runs and nothing is recorded. With a workspace, on Windows, each root + * says what that workspace's container needs to read it. + */ + discoverToolchains: (workspaceId: string | null) => + invokeCommand("settings_discover_toolchains", { + workspace_id: workspaceId, + }), + /** + * Records the selected proposals after one system confirmation that lists everything they + * hold. Sends their digests, never a path; Rust discovers again and refuses a selection that + * no longer matches. + */ + addDiscoveredProfiles: (revision: number, digests: string[], workspaceId: string | null) => + invokeCommand("settings_add_discovered_profiles", { + revision, + digests, + 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. + */ + grantDiscoveredRoots: (revision: number, workspaceId: string, digests: string[]) => + invokeCommand("settings_grant_discovered_roots", { + revision, + workspace_id: workspaceId, + digests, + }), }; diff --git a/crates/omgcode-desktop/ui/src/ipc/types.ts b/crates/omgcode-desktop/ui/src/ipc/types.ts index 5eb34b74..940b8642 100644 --- a/crates/omgcode-desktop/ui/src/ipc/types.ts +++ b/crates/omgcode-desktop/ui/src/ipc/types.ts @@ -648,6 +648,63 @@ export interface ContainerGrantView { state: "pending" | "active" | "revoking"; } +/** + * What the selected workspace's container needs before a run can read one proposed root + * (ADR-0103). `not_applicable` off Windows or with no workspace selected. + */ +export type RootGrantNeed = + | "not_applicable" + | "readable" + | "needs_grant" + | "needs_administrator" + | "unknown"; + +export type ToolchainFamily = + | "rust" + | "c_cpp" + | "java" + | "python" + | "perl" + | "go" + | "node" + | "dot_net" + | "ruby"; + +/** + * One toolchain profile proposal that Rust made by reading install folders (ADR-0103). Every + * string is display-safe text; none is ever sent back. A change names a proposal by `digest`. + */ +export interface ToolchainProposalView { + digest: string; + family: ToolchainFamily; + family_label: string; + name: string; + version: string | null; + read_only_roots: Array<{ folder: string; grant: RootGrantNeed }>; + path_entries: string[]; + environment: Array<{ name: string; value: string }>; + notes: string[]; + /** Why core would refuse to add it now, or `null`. */ + refusal: string | null; + /** A profile with this name is already recorded. */ + recorded: boolean; +} + +/** The reply to the three discovery commands. */ +export interface ToolchainDiscovery { + overview: SettingsOverview; + /** The workspace the roots report container access for, or `null`. */ + workspace_id: string | null; + /** + * Windows with a workspace: whether it has the active read-write grant on its own folder that + * every run needs. `null` otherwise. + */ + workspace_grant_active: boolean | null; + proposals: ToolchainProposalView[]; + /** Installations found and not proposed: more than eight under one name, or 32 in all. */ + omitted: number; +} + export interface SkillSettingView { name: string; application: boolean | null; diff --git a/crates/omgcode-desktop/ui/src/mock/backend.ts b/crates/omgcode-desktop/ui/src/mock/backend.ts index 35a8e2b7..7e27d763 100644 --- a/crates/omgcode-desktop/ui/src/mock/backend.ts +++ b/crates/omgcode-desktop/ui/src/mock/backend.ts @@ -21,12 +21,15 @@ import type { PermissionFlags, ProcessEntry, ReasoningEffort, + RootGrantNeed, SearchHit, SessionProcesses, SessionSummary, SessionWebAudit, SettingsOverview, SnippetPart, + ToolchainDiscovery, + ToolchainProposalView, TreeSort, TreeView, WebAuditEntry, @@ -264,6 +267,77 @@ const BUILT_IN_PREFERENCES: MockPreferences = { enter_to_send: true, }; +/** A sample toolchain proposal of the mock's discovery (ADR-0103). */ +interface MockProposal { + family: ToolchainProposalView["family"]; + family_label: string; + name: string; + version: string | null; + roots: string[]; + path_entries: string[]; + environment: Array<{ name: string; value: string }>; + notes: string[]; +} + +const MOCK_OFFLINE_NOTE = + "Runs are offline unless the trusted CLI passes --network, and model runs never are. Dependencies that are not already in the workspace, such as crates from crates.io, fail to download."; + +const MOCK_PROPOSALS: readonly MockProposal[] = [ + { + family: "rust", + family_label: "Rust", + name: "rust", + version: "stable-x86_64-unknown-linux-gnu", + roots: ["/home/dev/.rustup/toolchains/stable-x86_64-unknown-linux-gnu", "/usr"], + path_entries: ["/home/dev/.rustup/toolchains/stable-x86_64-unknown-linux-gnu/bin", "/usr/bin"], + environment: [], + notes: [MOCK_OFFLINE_NOTE], + }, + { + family: "go", + family_label: "Go", + name: "go", + version: "1.23.4", + roots: ["/usr/local/go", "/usr"], + path_entries: ["/usr/local/go/bin", "/usr/bin"], + environment: [ + { name: "GOROOT", value: "/usr/local/go" }, + { name: "GOTOOLCHAIN", value: "local" }, + { name: "GOENV", value: "off" }, + { name: "GOFLAGS", value: "-buildvcs=false" }, + ], + notes: [MOCK_OFFLINE_NOTE], + }, + { + family: "python", + family_label: "Python", + name: "python", + version: "3.12", + roots: ["/usr"], + path_entries: ["/usr/bin"], + environment: [], + notes: [], + }, + { + family: "java", + family_label: "Java", + name: "java", + version: "21.0.2", + roots: ["/usr/lib/jvm/java-21-openjdk-amd64", "/usr"], + path_entries: ["/usr/lib/jvm/java-21-openjdk-amd64/bin", "/usr/bin"], + environment: [{ name: "JAVA_HOME", value: "/usr/lib/jvm/java-21-openjdk-amd64" }], + notes: [ + "This is a Java runtime without javac; it runs Java programs but cannot compile them.", + "Not acceptance-tested: OMGCode has not run this family's build inside the confined runner.", + ], + }, +]; + +/** A stable sample digest: 64 copies of one hex digit. */ +function mockDigest(index: number): string { + return ((index % 15) + 1).toString(16).repeat(64); +} + /** Creates a fresh mock core. `now` supplies milliseconds since the epoch. */ export function createMockBackend(now: () => number = Date.now): { invoke: Invoker } { const { groups, sessions } = buildFixtures(now()); @@ -1470,6 +1544,65 @@ export function createMockBackend(now: () => number = Date.now): { invoke: Invok } settings.container_grants.splice(index, 1); }); + // The mock stands in for toolchain discovery (ADR-0103): a fixed list of sample proposals, + // checked against the recorded names. Every confirmation is accepted. + case "settings_discover_toolchains": + return mockDiscovery(optionalWorkspace(args)); + case "settings_add_discovered_profiles": { + const chosen = mockSelection(args); + const workspaceId = optionalWorkspace(args); + if (args.revision !== settings.revision) { + fail("stale_revision", "The settings changed since this window read them."); + } + for (const proposal of chosen) { + if (mockRecorded(proposal.name)) { + fail("control", `${proposal.name}: a profile with this name already exists`); + } + } + for (const proposal of chosen) { + settings.toolchain_profiles.push({ + name: proposal.name, + platform: "linux", + 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; + } + return mockDiscovery(workspaceId); + } // The mock stands in for the browser step: a sign-in succeeds at once (ADR-0093). case "settings_sign_in_chatgpt": return changeSettings(args, () => { @@ -1739,6 +1872,94 @@ export function createMockBackend(now: () => number = Date.now): { invoke: Invok return overviewView(); } + /** The optional `workspace_id` of a discovery request; a registered one or `null`. */ + function optionalWorkspace(args: Record): string | null { + if (args.workspace_id === null || args.workspace_id === undefined) { + return null; + } + return mockWorkspace(args).workspace_id; + } + + function mockRecorded(name: string): boolean { + return settings.toolchain_profiles.some((p) => p.name.toLowerCase() === name.toLowerCase()); + } + + /** 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) { + return "not_applicable"; + } + if ( + settings.container_grants.some( + (grant) => grant.workspace_id === workspaceId && folder.startsWith(grant.directory), + ) + ) { + return "readable"; + } + if (folder.startsWith("/home/")) { + return "needs_grant"; + } + return folder.startsWith("/usr/local/") ? "needs_administrator" : "readable"; + } + + function mockDiscovery(workspaceId: string | null): ToolchainDiscovery { + const proposals: ToolchainProposalView[] = MOCK_PROPOSALS.map((sample, index) => { + const recorded = mockRecorded(sample.name); + return { + digest: mockDigest(index), + family: sample.family, + family_label: sample.family_label, + name: sample.name, + version: sample.version, + read_only_roots: sample.roots.map((folder) => ({ + folder, + grant: mockGrantNeed(workspaceId, folder), + })), + path_entries: [...sample.path_entries], + environment: sample.environment.map((variable) => ({ ...variable })), + notes: [...sample.notes], + refusal: recorded ? "a profile with this name already exists; remove it first" : null, + recorded, + }; + }); + const active = + workspaceId === null || !settings.container_grants_supported + ? null + : settings.container_grants.some( + (grant) => + grant.workspace_id === workspaceId && + grant.access === "read_write" && + grant.state === "active", + ); + return { + overview: overviewView(), + workspace_id: workspaceId, + workspace_grant_active: active, + proposals, + omitted: 0, + }; + } + + /** The sample proposals a request selects, as Rust checks a selection: 1 to 8 known digests. */ + function mockSelection(args: Record): MockProposal[] { + const digests = Array.isArray(args.digests) ? args.digests.map(String) : []; + if ( + digests.length < 1 || + digests.length > 8 || + new Set(digests).size !== digests.length || + !digests.every((digest) => /^[0-9a-f]{64}$/.test(digest)) + ) { + fail("invalid_request", "Select 1 to 8 proposals at a time."); + } + return digests.map((digest) => { + const found = MOCK_PROPOSALS.find((_, at) => mockDigest(at) === digest); + if (found === undefined) { + fail("discovery_changed", "The installed toolchains or the proposals changed."); + } + return found; + }); + } + function mockWorkspace(args: Record): WorkspaceSettingsView { const id = str(args, "workspace_id"); const found = settings.workspaces.find((w) => w.workspace_id === id); diff --git a/crates/omgcode-desktop/ui/src/settings/app.ts b/crates/omgcode-desktop/ui/src/settings/app.ts index a66a8ec0..a1478afe 100644 --- a/crates/omgcode-desktop/ui/src/settings/app.ts +++ b/crates/omgcode-desktop/ui/src/settings/app.ts @@ -142,6 +142,12 @@ const ACTIONS: Omit = { settingsApi.grantContainerFolder(revision, workspaceId, access), revokeContainerGrant: (grantId) => (revision) => settingsApi.revokeContainerGrant(revision, grantId), + // A read: it records nothing, so it names no revision. + discoverToolchains: (workspaceId) => () => settingsApi.discoverToolchains(workspaceId), + addDiscoveredProfiles: (digests, workspaceId) => (revision) => + settingsApi.addDiscoveredProfiles(revision, digests, workspaceId), + grantDiscoveredRoots: (workspaceId, digests) => (revision) => + settingsApi.grantDiscoveredRoots(revision, workspaceId, digests), }; /** diff --git a/crates/omgcode-desktop/ui/src/settings/context.ts b/crates/omgcode-desktop/ui/src/settings/context.ts index 668961f3..f3d8d11a 100644 --- a/crates/omgcode-desktop/ui/src/settings/context.ts +++ b/crates/omgcode-desktop/ui/src/settings/context.ts @@ -3,6 +3,8 @@ import type { NewConnectionKind, PermissionFlags, SettingsOverview, + ToolchainDiscovery, + ToolchainProposalView, WorkspaceSettingsView, } from "../ipc/types"; @@ -12,6 +14,12 @@ export type Change = (revision: number) => Promise; /** Runs one change, or ignores it while another waits. */ export type Submit = (change: Change) => void; +/** + * A toolchain discovery read or change (ADR-0103): it returns the proposals with the overview. + * The read ignores the revision. + */ +export type DiscoveryChange = (revision: number) => Promise; + /** * The changes a control can ask for. Only the window shell reaches the command client; each * section names a change here and passes it to `submit`. Every one sends identifiers and the @@ -77,6 +85,15 @@ export interface Actions { /** Windows only. Rust opens the folder dialog. */ grantContainerFolder(workspaceId: string, access: ContainerAccess): Change; revokeContainerGrant(grantId: string): Change; + /** + * Asks Rust to propose toolchain profiles from installed toolchains (ADR-0103). With a + * 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. */ + 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; } /** @@ -159,6 +176,25 @@ export interface ExecutionForms { package: { name: string; origins: string }; grantOpen: boolean; grant: { workspaceId: string; access: ContainerAccess }; + discovery: DiscoveryState; +} + +/** + * The last toolchain proposals Rust returned and which the operator selected (ADR-0103). The + * proposals are display text; a change sends only the selected digests. + */ +export interface DiscoveryState { + /** `null` until the operator first generates the list. */ + proposals: ToolchainProposalView[] | null; + /** The workspace the list reports container access for, or `null`. */ + workspaceId: string | null; + workspaceGrantActive: boolean | null; + /** Installations the list leaves out because a bound was reached. */ + omitted: number; + /** The selected proposals, by digest. */ + selected: Set; + /** The workspace chosen for the next list and grants; `""` for none. */ + chosenWorkspace: string; } /** The forms' starting values. */ @@ -170,5 +206,13 @@ export function newExecutionForms(): ExecutionForms { package: { name: "", origins: "" }, grantOpen: false, grant: { workspaceId: "", access: "read_execute" }, + discovery: { + proposals: null, + workspaceId: null, + workspaceGrantActive: null, + omitted: 0, + selected: new Set(), + chosenWorkspace: "", + }, }; } diff --git a/crates/omgcode-desktop/ui/src/settings/discovery_panel.ts b/crates/omgcode-desktop/ui/src/settings/discovery_panel.ts new file mode 100644 index 00000000..e3e26483 --- /dev/null +++ b/crates/omgcode-desktop/ui/src/settings/discovery_panel.ts @@ -0,0 +1,259 @@ +import { button, el, neutralise } from "../dom"; +import type { RootGrantNeed, ToolchainProposalView } from "../ipc/types"; +import type { DiscoveryChange, DiscoveryState, SectionContext } from "./context"; +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. + */ +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. */ +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 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 has no active read-write grant on its own folder, which every run in it needs. Grant it under Container grants."; +export const NO_WORKSPACE = "No workspace"; + +/** Says how many installations the list leaves out. */ +export function omittedText(count: number): string { + const what = count === 1 ? "1 more installation was" : `${count} more installations were`; + return `${what} found and not listed: a list holds at most 8 installations under one name and 32 in all, each name's preferred installation first.`; +} + +const GRANT_TEXT: Record = { + not_applicable: "", + readable: "the container can read it", + needs_grant: "needs a grant", + needs_administrator: "needs an administrator to grant", + unknown: "access could not be read", +}; + +/** Runs a discovery read or change and remembers its proposals for the next draw. */ +function run(ctx: SectionContext, change: DiscoveryChange, keepSelection: boolean): void { + const state = ctx.view.executionForms.discovery; + ctx.submit(async (revision) => { + const result = await change(revision); + // Reached only on success; a refusal or a cancel keeps the list and the selection. + state.proposals = result.proposals; + state.workspaceId = result.workspace_id; + state.workspaceGrantActive = result.workspace_grant_active; + state.omitted = result.omitted; + // A kept selection loses proposals that are gone or that core would now refuse. + const addable = new Set( + result.proposals + .filter((proposal) => proposal.refusal === null) + .map((proposal) => proposal.digest), + ); + state.selected = keepSelection + ? new Set([...state.selected].filter((digest) => addable.has(digest))) + : new Set(); + return result.overview; + }); +} + +function rootLines(proposal: ToolchainProposalView): string { + return proposal.read_only_roots + .map((root) => { + const need = GRANT_TEXT[root.grant]; + return need === "" ? root.folder : `${root.folder} (${need})`; + }) + .join("\n"); +} + +function proposalRow( + proposal: ToolchainProposalView, + index: number, + state: DiscoveryState, + onSelect: () => void, +): HTMLElement { + const pairs: Array<[string, string]> = [ + [ + "Family", + proposal.version === null + ? proposal.family_label + : `${proposal.family_label}, ${proposal.version}`, + ], + ["Read-only roots", rootLines(proposal)], + ["PATH entries", proposal.path_entries.join("\n") || "none"], + [ + "Variables", + proposal.environment.map((variable) => `${variable.name}=${variable.value}`).join("\n") || + "none", + ], + ]; + if (proposal.notes.length > 0) { + pairs.push(["Notes", proposal.notes.join("\n")]); + } + const item = row(proposal.name, facts(pairs)); + item.classList.add("proposal"); + const id = `toolchain-proposal-${index}`; + const select = el("input", { attrs: { id, type: "checkbox" } }); + select.checked = state.selected.has(proposal.digest); + select.disabled = proposal.refusal !== null; + select.setAttribute("aria-label", neutralise(`Select the proposed profile ${proposal.name}`)); + select.addEventListener("change", () => { + if (select.checked) { + state.selected.add(proposal.digest); + } else { + state.selected.delete(proposal.digest); + } + onSelect(); + }); + item.querySelector(".row-head")?.prepend(select); + // Under the facts: a child of the row itself would sit beside them like a row action. + const body = item.querySelector(".row-body"); + if (proposal.recorded) { + body?.append(el("p", { class: "muted", text: "A profile with this name is recorded." })); + } else if (proposal.refusal !== null) { + body?.append(el("p", { class: "muted", text: `Cannot be added: ${proposal.refusal}` })); + } + return item; +} + +/** + * 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. + */ +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) { + return null; + } + const choice = el("select", { attrs: { id: "discovery-workspace" } }); + choice.append(el("option", { text: NO_WORKSPACE, attrs: { value: "" } })); + for (const entry of overview.workspaces) { + choice.append( + el("option", { text: entry.folder_display, attrs: { value: entry.workspace_id } }), + ); + } + choice.value = chosenWorkspace(ctx) ?? ""; + choice.addEventListener("change", () => { + state.chosenWorkspace = choice.value; + if (state.proposals !== null) { + run(ctx, actions.discoverToolchains(chosenWorkspace(ctx)), true); + } + }); + return el( + "div", + { class: "field" }, + el("label", { text: "Show container access for", attrs: { for: "discovery-workspace" } }), + choice, + ); +} + +/** The chosen workspace if it is still registered and grants exist here, else `null`. */ +function chosenWorkspace(ctx: SectionContext): string | null { + const { overview } = ctx; + const chosen = ctx.view.executionForms.discovery.chosenWorkspace; + if (!overview.container_grants_supported || chosen === "") { + return null; + } + return overview.workspaces.some((entry) => entry.workspace_id === chosen) ? chosen : 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. + */ +export function discoveryPanel(ctx: SectionContext): HTMLElement { + const { overview, actions } = ctx; + const state = ctx.view.executionForms.discovery; + const problem = el("p", { class: "error", attrs: { role: "alert" } }); + problem.hidden = true; + const generate = button(DISCOVER_LABEL, () => + run(ctx, actions.discoverToolchains(chosenWorkspace(ctx)), true), + ); + const panel = el( + "div", + { class: "discovery" }, + el("p", { class: "section-help", text: DISCOVERY_HELP }), + ); + const choice = workspaceChoice(ctx); + if (choice !== null) { + panel.append(el("p", { class: "muted", text: DISCOVERY_GRANT_HELP }), choice); + } + panel.append(el("div", { class: "row-actions" }, generate)); + const proposals = state.proposals; + if (proposals === null) { + return panel; + } + if (proposals.length === 0) { + panel.append(emptyLine(NOTHING_FOUND)); + return panel; + } + 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. + const listWorkspace = overview.workspaces.some((w) => w.workspace_id === state.workspaceId) + ? state.workspaceId + : null; + if (listWorkspace !== null && state.workspaceGrantActive === false) { + panel.append(el("p", { class: "muted", text: WORKSPACE_GRANT_MISSING })); + } + const add = button(ADD_SELECTED_LABEL, () => { + const digests = selectedDigests(); + if (digests.length > MAX_SELECTED) { + problem.textContent = SELECTION_LIMIT; + problem.hidden = false; + return; + } + 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 ?? []) + .map((proposal) => proposal.digest) + .filter((digest) => state.selected.has(digest)); + } + function updateButtons(): void { + 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( + "ul", + { class: "row-list" }, + ...proposals.map((proposal, index) => proposalRow(proposal, index, state, updateButtons)), + ), + problem, + ); + const buttons = el("div", { class: "row-actions" }, add); + if (overview.container_grants_supported) { + buttons.append(grant); + } + panel.append(buttons); + 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 bf0c773e..46380f7e 100644 --- a/crates/omgcode-desktop/ui/src/settings/execution_forms.ts +++ b/crates/omgcode-desktop/ui/src/settings/execution_forms.ts @@ -1,5 +1,6 @@ import { button, el, neutralise } from "../dom"; import type { ContainerAccess, SectionContext } from "./context"; +import { discoveryPanel } from "./discovery_panel"; import { emptyLine, facts, row } from "./parts"; /** The buttons that ask Rust to open its folder dialogs and confirmations (ADR-0088). */ @@ -300,7 +301,10 @@ function list(rows: HTMLElement[], emptyText: string): HTMLElement { return rows.length === 0 ? emptyLine(emptyText) : el("ul", { class: "row-list" }, ...rows); } -/** The Toolchain profiles group: the recorded profiles, an add form, and a remove button each. */ +/** + * The Toolchain profiles group: proposals generated from installed toolchains (ADR-0103), the + * recorded profiles, an add form, and a remove button each. + */ export function toolchainGroup(ctx: SectionContext): HTMLElement { const forms = ctx.view.executionForms; const form = disclosure("Add toolchain profile", forms.toolchainOpen, (open) => { @@ -310,6 +314,7 @@ export function toolchainGroup(ctx: SectionContext): HTMLElement { return block( "Toolchain profiles", el("p", { class: "section-help", text: TOOLCHAIN_HELP }), + discoveryPanel(ctx), form, list(toolchainRows(ctx), "No toolchain profile is recorded."), ); diff --git a/crates/omgcode-desktop/ui/tests/dist.test.ts b/crates/omgcode-desktop/ui/tests/dist.test.ts index 765fd9cd..03e7d33c 100644 --- a/crates/omgcode-desktop/ui/tests/dist.test.ts +++ b/crates/omgcode-desktop/ui/tests/dist.test.ts @@ -85,9 +85,12 @@ suite( }); it("reads every settings-window command from the settings client", () => { - // 29 in `settings`, as `policy.rs` and the guide count them. - expect(SETTINGS_WINDOW_COMMANDS).toHaveLength(29); + // 32 in `settings`, as `policy.rs` and the guide count them. + expect(SETTINGS_WINDOW_COMMANDS).toHaveLength(32); 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_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 new file mode 100644 index 00000000..9fdc3f97 --- /dev/null +++ b/crates/omgcode-desktop/ui/tests/settings_discovery.test.ts @@ -0,0 +1,574 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { setInvoker } from "../src/ipc/client"; +import type { SettingsOverview, ToolchainDiscovery, ToolchainProposalView } from "../src/ipc/types"; +import { createMockBackend } from "../src/mock/backend"; +import { HOSTILE } from "../src/mock/fixtures"; +import { type SettingsApp, startSettings } from "../src/settings/app"; +import { + ADD_SELECTED_LABEL, + DISCOVER_LABEL, + DISCOVERY_HELP, + GRANT_SELECTED_LABEL, + NOTHING_FOUND, + omittedText, + SELECTION_LIMIT, + WORKSPACE_GRANT_MISSING, +} from "../src/settings/discovery_panel"; +import { + buttonByText, + chatDefaultsView, + choose, + type FakeIpc, + installFakeIpc, + mountRoot, + rejection, + settle, +} from "./helpers"; + +const A = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"; + +function overview(overrides: Partial = {}): SettingsOverview { + return { + revision: 5, + development_root: "C:\\dev", + workspaces: [ + { + workspace_id: A, + folder_display: "C:\\dev\\a", + model_tools: true, + read: "allow", + write: "prompt", + execute: "allow", + task_network: "deny", + host_services: "deny", + web_fetch: "deny", + web_fetch_hosts: [], + write_tools: { + edit: "allow", + multi_edit: "allow", + create: "allow", + rename: "allow", + delete: "allow", + create_directory: "allow", + }, + package_cache_root: null, + instructions: "", + instructions_max_bytes: 16_360, + }, + ], + connection: { + endpoint: "http://127.0.0.1:1234/v1", + source: "active", + profile: null, + kind: null, + selectable: true, + }, + provider_profiles: [], + toolchain_profiles: [], + package_profiles: [], + container_grants: [], + container_grants_supported: true, + skills: [], + chat: chatDefaultsView(), + scope: null, + ...overrides, + }; +} + +function digest(n: number): string { + return n.toString(16).padStart(2, "0").repeat(32); +} + +function proposal(overrides: Partial = {}): ToolchainProposalView { + return { + digest: digest(1), + family: "go", + family_label: "Go", + name: "go", + version: "1.23.4", + read_only_roots: [ + { folder: "C:\\Program Files\\Go", grant: "not_applicable" }, + { folder: "C:\\Windows\\System32", grant: "not_applicable" }, + ], + path_entries: ["C:\\Program Files\\Go\\bin", "C:\\Windows\\System32"], + environment: [ + { name: "GOROOT", value: "C:\\Program Files\\Go" }, + { name: "GOTOOLCHAIN", value: "local" }, + ], + notes: ["Runs are offline."], + refusal: null, + recorded: false, + ...overrides, + }; +} + +const RUST = proposal({ + digest: digest(2), + family: "rust", + family_label: "Rust", + name: "rust", + version: "stable-x86_64-pc-windows-msvc", + read_only_roots: [ + { folder: "C:\\Users\\op\\.rustup\\toolchains\\stable", grant: "not_applicable" }, + ], + path_entries: ["C:\\Users\\op\\.rustup\\toolchains\\stable\\bin"], + environment: [], + notes: [], +}); + +function discovery( + proposals: ToolchainProposalView[], + overrides: Partial = {}, +): ToolchainDiscovery { + return { + overview: overview(), + workspace_id: null, + workspace_grant_active: null, + proposals, + omitted: 0, + ...overrides, + }; +} + +let app: SettingsApp | null = null; +let root: HTMLElement; +let ipc: FakeIpc; + +async function start( + reply: () => unknown, + more: Record) => unknown> = {}, +): Promise { + ipc = installFakeIpc({ settings_overview: reply, ...more }); + root = mountRoot(); + app = startSettings(root); + await settle(); + Array.from(root.querySelectorAll(".nav-item")) + .find((item) => item.textContent === "Advanced") + ?.click(); +} + +function group(): HTMLElement { + const found = Array.from(root.querySelectorAll(".block")).find( + (candidate) => candidate.querySelector("h3")?.textContent === "Toolchain profiles", + ); + if (found === undefined) { + throw new Error("No Toolchain profiles group"); + } + return found; +} + +function boxes(): HTMLInputElement[] { + return Array.from(group().querySelectorAll(".proposal input[type=checkbox]")); +} + +function tick(index: number): void { + const box = boxes()[index]; + if (box === undefined) { + throw new Error(`No proposal ${index}`); + } + box.checked = !box.checked; + box.dispatchEvent(new Event("change")); +} + +async function generate(): Promise { + buttonByText(group(), DISCOVER_LABEL).click(); + await settle(); +} + +beforeEach(() => { + vi.useFakeTimers(); +}); + +afterEach(() => { + app?.dispose(); + app = null; + setInvoker(null); + vi.useRealTimers(); +}); + +describe("generating toolchain profiles", () => { + it("says it runs nothing and asks Rust only for a workspace identifier", async () => { + await start(() => overview(), { + settings_discover_toolchains: () => discovery([proposal(), RUST]), + }); + expect(group().textContent).toContain(DISCOVERY_HELP); + expect(DISCOVERY_HELP).toContain("runs no program"); + expect(DISCOVERY_HELP).toContain("rust-toolchain.toml"); + // The help names every input discovery reads, not just PATH. + for (const variable of ["JAVA_HOME", "GOROOT", "RUSTUP_HOME"]) { + expect(DISCOVERY_HELP).toContain(variable); + } + // Nothing is listed until the operator asks. + expect(boxes()).toHaveLength(0); + expect(ipc.callsTo("settings_discover_toolchains")).toHaveLength(0); + + await generate(); + + expect(ipc.callsTo("settings_discover_toolchains")[0]?.args).toEqual({ workspace_id: null }); + expect(boxes()).toHaveLength(2); + }); + + it("shows every proposal's name, family, version, roots, PATH entries, variables, and notes", async () => { + await start(() => overview(), { + settings_discover_toolchains: () => discovery([proposal()]), + }); + await generate(); + const text = group().textContent ?? ""; + for (const expected of [ + "go", + "Go, 1.23.4", + "C:\\Program Files\\Go", + "C:\\Windows\\System32", + "C:\\Program Files\\Go\\bin", + "GOROOT=C:\\Program Files\\Go", + "GOTOOLCHAIN=local", + "Runs are offline.", + ]) { + expect(text).toContain(expected); + } + }); + + it("says so when nothing is installed", async () => { + await start(() => overview(), { + settings_discover_toolchains: () => discovery([]), + }); + await generate(); + expect(group().textContent).toContain(NOTHING_FOUND); + expect(() => buttonByText(group(), ADD_SELECTED_LABEL)).toThrow(); + }); + + it("renders hostile proposal text as text", async () => { + await start(() => overview(), { + settings_discover_toolchains: () => + discovery([ + proposal({ + name: HOSTILE.img, + version: HOSTILE.script, + environment: [{ name: "X", value: HOSTILE.img }], + notes: [HOSTILE.rtl], + }), + ]), + }); + await generate(); + expect(root.querySelector(".settings-body img, .settings-body script")).toBeNull(); + expect(group().textContent).toContain(HOSTILE.img); + }); + + it("says how many installations the list leaves out", async () => { + let omitted = 5; + await start(() => overview(), { + settings_discover_toolchains: () => discovery([proposal()], { omitted }), + }); + await generate(); + expect(group().textContent).toContain(omittedText(5)); + expect(omittedText(5)).toContain("5 more installations were found"); + expect(omittedText(1)).toContain("1 more installation was found"); + + omitted = 0; + await generate(); + expect(group().textContent).not.toContain("more installation"); + }); +}); + +describe("adding proposals", () => { + it("sends the revision and the selected digests in list order, never a path", async () => { + await start(() => overview(), { + settings_discover_toolchains: () => discovery([proposal(), RUST]), + settings_add_discovered_profiles: () => + discovery([ + proposal({ recorded: true, refusal: "a profile with this name already exists" }), + { ...RUST, recorded: true, refusal: "a profile with this name already exists" }, + ]), + }); + await generate(); + const add = buttonByText(group(), ADD_SELECTED_LABEL); + expect(add.disabled).toBe(true); + tick(1); + tick(0); + expect(add.disabled).toBe(false); + add.click(); + await settle(); + + expect(ipc.callsTo("settings_add_discovered_profiles")[0]?.args).toEqual({ + revision: 5, + digests: [digest(1), digest(2)], + workspace_id: null, + }); + // The refreshed list shows both as recorded, and neither can be selected again. + expect(group().textContent).toContain("A profile with this name is recorded."); + expect(boxes().every((box) => box.disabled && !box.checked)).toBe(true); + }); + + it("disables a proposal core would refuse and shows the reason", async () => { + await start(() => overview(), { + settings_discover_toolchains: () => + discovery([proposal({ refusal: "at most 32 profiles can be recorded; remove one first" })]), + }); + await generate(); + expect(boxes()[0]?.disabled).toBe(true); + expect(group().textContent).toContain( + "Cannot be added: at most 32 profiles can be recorded; remove one first", + ); + expect(buttonByText(group(), ADD_SELECTED_LABEL).disabled).toBe(true); + }); + + it("keeps the list and the selection when the operator declines", async () => { + await start(() => overview(), { + settings_discover_toolchains: () => discovery([proposal(), RUST]), + settings_add_discovered_profiles: () => rejection("cancelled", "No change was made."), + }); + await generate(); + tick(0); + buttonByText(group(), ADD_SELECTED_LABEL).click(); + await settle(); + expect(root.querySelector(".notice")?.textContent).toBe("No change was made."); + expect(boxes()).toHaveLength(2); + expect(boxes()[0]?.checked).toBe(true); + }); + + it("shows Rust's refusal when the installed toolchains changed", async () => { + await start(() => overview(), { + settings_discover_toolchains: () => discovery([proposal()]), + settings_add_discovered_profiles: () => + rejection("discovery_changed", "Generate the list again and select again."), + }); + await generate(); + tick(0); + buttonByText(group(), ADD_SELECTED_LABEL).click(); + await settle(); + expect(root.querySelector(".change-error")?.textContent).toBe( + "Generate the list again and select again. (discovery_changed)", + ); + }); + + it("refuses more than eight proposals before asking Rust", async () => { + const many = Array.from({ length: 9 }, (_, index) => + proposal({ digest: digest(index + 1), name: `go-${index}` }), + ); + await start(() => overview(), { + settings_discover_toolchains: () => discovery(many), + }); + await generate(); + for (let index = 0; index < 9; index += 1) { + tick(index); + } + buttonByText(group(), ADD_SELECTED_LABEL).click(); + await settle(); + expect(group().querySelector(".error")?.textContent).toBe(SELECTION_LIMIT); + expect(ipc.callsTo("settings_add_discovered_profiles")).toHaveLength(0); + }); +}); + +describe("granting proposed roots on Windows", () => { + const NEEDS = proposal({ + read_only_roots: [ + { folder: "C:\\Users\\op\\go", grant: "needs_grant" }, + { folder: "C:\\Program Files\\Go", grant: "readable" }, + { folder: "D:\\locked", grant: "needs_administrator" }, + ], + }); + + it("asks for container access of the chosen workspace and labels each root", async () => { + await start(() => overview(), { + settings_discover_toolchains: () => + discovery([NEEDS], { workspace_id: A, workspace_grant_active: false }), + }); + 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: A }); + const text = group().textContent ?? ""; + expect(text).toContain("C:\\Users\\op\\go (needs a grant)"); + expect(text).toContain("C:\\Program Files\\Go (the container can read it)"); + expect(text).toContain("D:\\locked (needs an administrator to grant)"); + expect(text).toContain(WORKSPACE_GRANT_MISSING); + }); + + it("generates a list on screen again when another workspace is chosen", async () => { + await start(() => overview(), { + settings_discover_toolchains: (args) => + args.workspace_id === A + ? discovery([NEEDS], { workspace_id: A, workspace_grant_active: true }) + : discovery([proposal()]), + }); + const select = (): HTMLSelectElement => { + const found = group().querySelector("#discovery-workspace"); + if (found === null) { + throw new Error("No workspace choice"); + } + return found; + }; + await generate(); + tick(0); + expect(group().textContent).not.toContain("needs a grant"); + + choose(select(), A); + await settle(); + + const calls = ipc.callsTo("settings_discover_toolchains"); + expect(calls.map((call) => call.args)).toEqual([{ workspace_id: null }, { workspace_id: A }]); + // 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); + + choose(select(), ""); + await settle(); + expect(ipc.callsTo("settings_discover_toolchains").at(-1)?.args).toEqual({ + workspace_id: null, + }); + expect(group().textContent).not.toContain("needs a grant"); + }); + + it("does not ask Rust when a workspace is chosen before any list", async () => { + await start(() => overview(), { + settings_discover_toolchains: () => discovery([NEEDS], { workspace_id: A }), + }); + const select = group().querySelector("#discovery-workspace"); + if (select === null) { + throw new Error("No workspace choice"); + } + choose(select, A); + await settle(); + expect(ipc.callsTo("settings_discover_toolchains")).toHaveLength(0); + }); + + it("sends the revision, the list's workspace, and the selected digests", async () => { + await start(() => overview(), { + settings_discover_toolchains: () => discovery([NEEDS], { workspace_id: A }), + settings_grant_discovered_roots: () => + discovery( + [ + { + ...NEEDS, + read_only_roots: [ + { folder: "C:\\Users\\op\\go", grant: "readable" }, + { folder: "C:\\Program Files\\Go", grant: "readable" }, + { folder: "D:\\locked", grant: "needs_administrator" }, + ], + }, + ], + { workspace_id: A, overview: overview({ revision: 6 }) }, + ), + }); + await generate(); + const grant = buttonByText(group(), GRANT_SELECTED_LABEL); + expect(grant.disabled).toBe(true); + tick(0); + expect(grant.disabled).toBe(false); + grant.click(); + await settle(); + + expect(ipc.callsTo("settings_grant_discovered_roots")[0]?.args).toEqual({ + revision: 5, + workspace_id: A, + digests: [digest(1)], + }); + 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); + }); + + it("offers no grant without a workspace in the list", async () => { + await start(() => overview(), { + settings_discover_toolchains: () => discovery([proposal()]), + }); + await generate(); + tick(0); + expect(buttonByText(group(), GRANT_SELECTED_LABEL).disabled).toBe(true); + }); + + 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 }) }), + }); + expect(group().querySelector("#discovery-workspace")).toBeNull(); + await generate(); + expect(ipc.callsTo("settings_discover_toolchains")[0]?.args).toEqual({ workspace_id: null }); + expect(() => buttonByText(group(), GRANT_SELECTED_LABEL)).toThrow(); + }); +}); + +describe("mock discovery commands", () => { + type Invoke = (command: string, args: Record) => Promise; + + it("adds selected samples once and refuses stale, unknown, and repeated selections", async () => { + const { invoke } = createMockBackend() as { invoke: Invoke }; + const listed = (await invoke("settings_discover_toolchains", { + workspace_id: null, + })) as ToolchainDiscovery; + // The mock starts with a recorded `rust` profile, which its sample proposal names too. + expect(listed.proposals.find((entry) => entry.name === "rust")?.refusal).not.toBeNull(); + const [first, second] = listed.proposals.filter((entry) => entry.refusal === null); + if (first === undefined || second === undefined) { + throw new Error("two addable samples"); + } + const before = listed.overview.revision; + const added = (await invoke("settings_add_discovered_profiles", { + revision: before, + digests: [first.digest, second.digest], + workspace_id: null, + })) as ToolchainDiscovery; + expect(added.overview.revision).toBe(before + 2); + expect(added.proposals.find((entry) => entry.digest === first.digest)?.recorded).toBe(true); + await expect( + invoke("settings_add_discovered_profiles", { + revision: before, + digests: [first.digest], + workspace_id: null, + }), + ).rejects.toMatchObject({ code: "stale_revision" }); + await expect( + invoke("settings_add_discovered_profiles", { + revision: added.overview.revision, + digests: ["f".repeat(64)], + workspace_id: null, + }), + ).rejects.toMatchObject({ code: "discovery_changed" }); + await expect( + invoke("settings_add_discovered_profiles", { + revision: added.overview.revision, + digests: [first.digest, first.digest], + workspace_id: null, + }), + ).rejects.toMatchObject({ code: "invalid_request" }); + }); + + it("grants the home-folder roots a workspace needs and then reports them readable", async () => { + const { invoke } = createMockBackend() as { invoke: Invoke }; + const settings = (await invoke("settings_overview", {})) as SettingsOverview; + const workspace = settings.workspaces[0]?.workspace_id ?? ""; + 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"), + ); + if (needing === undefined) { + throw new Error("a sample needs a grant"); + } + const granted = (await invoke("settings_grant_discovered_roots", { + revision: listed.overview.revision, + workspace_id: workspace, + digests: [needing.digest], + })) as ToolchainDiscovery; + const after = granted.proposals.find((entry) => entry.digest === needing.digest); + expect(after?.read_only_roots.some((rootEntry) => rootEntry.grant === "needs_grant")).toBe( + false, + ); + await expect( + invoke("settings_grant_discovered_roots", { + revision: granted.overview.revision, + workspace_id: workspace, + digests: [needing.digest], + }), + ).rejects.toMatchObject({ code: "nothing_to_grant" }); + }); +}); diff --git a/crates/omgcode-platform/src/container.rs b/crates/omgcode-platform/src/container.rs index b5e4cb65..08019745 100644 --- a/crates/omgcode-platform/src/container.rs +++ b/crates/omgcode-platform/src/container.rs @@ -197,6 +197,28 @@ pub fn granted_access(path: &Path, name: &ContainerName) -> io::Result io::Result { + #[cfg(windows)] + { + windows::can_change_access(path) + } + #[cfg(not(windows))] + { + let _ = path; + Err(unsupported()) + } +} + #[cfg(not(windows))] fn unsupported() -> io::Error { io::Error::new( diff --git a/crates/omgcode-platform/src/container/windows.rs b/crates/omgcode-platform/src/container/windows.rs index c5c2ff4f..30ba6c00 100644 --- a/crates/omgcode-platform/src/container/windows.rs +++ b/crates/omgcode-platform/src/container/windows.rs @@ -287,6 +287,22 @@ pub(crate) fn granted_access(path: &Path, sid: &Sid) -> io::Result io::Result { + require_absolute(path)?; + match OpenOptions::new() + .access_mode(GRANT_ACCESS) + .share_mode(SHARE_READ_WRITE) + .custom_flags(FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT) + .open(path) + { + Ok(_directory) => Ok(true), + Err(error) if error.kind() == io::ErrorKind::PermissionDenied => Ok(false), + Err(error) => Err(error), + } +} + const fn mask(access: ContainerAccess) -> u32 { match access { ContainerAccess::ReadExecute => READ_EXECUTE_MASK, diff --git a/docs/adr/0103-generate-toolchain-profiles-from-installed-toolchains.md b/docs/adr/0103-generate-toolchain-profiles-from-installed-toolchains.md new file mode 100644 index 00000000..36c90a87 --- /dev/null +++ b/docs/adr/0103-generate-toolchain-profiles-from-installed-toolchains.md @@ -0,0 +1,214 @@ +# 0103: Generate toolchain profiles from installed toolchains + +- Status: Accepted +- Date: 2026-11-26 + +## Context + +A model command call can run only under a recorded toolchain profile +([ADR-0030](0030-run-trusted-commands-through-recorded-toolchain-profiles.md)). +An operator's chat failed with `toolchain profile is not recorded`: their +control journal had never recorded a profile, and the model guessed `rust`. +Writing a profile by hand means knowing every root, `PATH` entry, and +variable a toolchain needs, which the acceptance runs showed is more than its +executable directory. The `settings` window can add a profile +([ADR-0088](0088-change-execution-settings-in-the-settings-window.md)), but +only from hand-chosen folders. + +[development-tools.md](../development-tools.md) allows later discovery in a +trusted host-side service that proposes resources for the operator to select, +and forbids repository-controlled discovery hooks and unconfined version +probes. Discovery must cover more than Rust, must grant nothing, and must +leave every record to the existing core calls, native confirmations, and the +confirmed settings revision. + +## Decision + +1. **A registry of detectors in core.** `omgcode_core::toolchain_discovery` + holds one detector per family: Rust, C and C++ (MSVC with the Windows SDK, + Clang, and MinGW GCC on Windows; GCC and Clang on Linux), Java, Python, + Perl, Go, Node.js, .NET, and Ruby. Each returns candidates; a shared step + completes, checks, names, orders, and bounds them. Adding a family is one + detector and one registry entry. The host layout (Windows or Linux) is a + value, not a compile-time choice, so every detector's Windows and Linux + fixture trees run on both CI hosts. +2. **Discovery reads the filesystem only.** It lists the standard install + folders, follows the operator's `PATH`, `JAVA_HOME`, `GOROOT`, and + `RUSTUP_HOME` from the trusted process environment, and reads a few small + files the installers wrote (rustup's `settings.toml`, a JDK's `release`, + Go's `VERSION`), each at most 64 KiB. Versions come from those files and + from folder names (`lib/gcc//`, `python3NN.dll`, MSVC and + Windows SDK version folders). It runs no program, confined or not, and + reads no registry key. It never reads repository configuration such as + `rust-toolchain.toml`, `.nvmrc`, `.python-version`, or `global.json`, and + never looks inside a workspace on its own. A folder that `PATH` or one of + those variables names is read like any install folder, installer files + included, even inside the development root; core refuses it as a root + before any confirmation, and the list shows why. A file is checked to be + a regular file before it is opened, and the open handle is checked again, + so a FIFO already at an installer's path is never opened; one swapped in + between the check and the open can still block discovery (see + Consequences). A listing examines at most 16,384 entries per + folder and keeps the first 512 directories by name, filtered and sorted + before the cut so the result does not depend on listing order; at most + 256 `PATH` entries are followed. +3. **What a proposal holds.** Each proposal has a name, a family, an optional + version, roots, `PATH` entries, variables, and fixed notes. + - Every proposal adds the system part the acceptance-tested profiles + listed: `System32` on Windows; `/usr` and any real top-level `bin`, + `lib`, `lib64`, or `lib32` on Linux. + - A root is never a filesystem or drive root, nor the home directory or one + of its ancestors. A nested or repeated root is dropped, and every `PATH` + entry lies inside a root. A root left after that is never itself a + symbolic link or junction: core records a root's resolved location, so + a linked root, such as a `JAVA_HOME` that names a link, would be + recorded at a path the confirmation never showed. Such a candidate is + left out. + - Only non-secret setup values are derived: `JAVA_HOME`, `GOROOT` with + `GOTOOLCHAIN=local`, `GOENV=off`, and `GOFLAGS=-buildvcs=false`, + `DOTNET_ROOT` with telemetry, logo, and certificate generation off, + Node's symlink-preserving `NODE_OPTIONS`, and MSVC's `INCLUDE`, `LIB`, + and `VCINSTALLDIR` for the x64 host and target. No reserved name is + proposed, and core checks every value again. + - A Rust proposal is one rustup toolchain directory, with its `bin` on + `PATH`. It runs that toolchain's own `cargo` and `rustc`, not the rustup + proxies, so it needs neither `RUSTUP_HOME` nor `RUSTUP_TOOLCHAIN`, and + `~/.cargo`, which can hold registry credentials, is never a root. The + rustup default toolchain is named `rust`. A Windows MSVC-target + toolchain gets the MSVC and SDK roots and variables, or a note that none + were found. + - Names follow core's name rule: the newest or default installation of a + family gets the bare name (`rust`, `go`, `java`, `python`), others a + version suffix. At most 8 proposals share a base name and 32 are + returned. Past 32, every base name keeps its first installation before + any keeps a second, so the families listed last do not lose every + proposal, and the list reports how many installations it left out. + - Notes say when a family has not passed the confined acceptance runs + (only Rust, MSVC, Linux GCC, Python, Go, and Node.js have), when a JDK + or .NET install is a runtime only, when Node on Windows needs + `--test-isolation=none`, and that offline runs cannot download + dependencies. +4. **Three `settings`-only commands; no path crosses the webview.** + `settings_discover_toolchains` returns the proposals as display-safe text + with a SHA-256 digest each. `settings_add_discovered_profiles` and + `settings_grant_discovered_roots` take the settings revision and 1 to 8 + digests. Rust discovers again and applies only proposals whose digests + still match; a selection made from an outdated list is refused as + `discovery_changed`. Discovery and the access-control reads run while the + settings store is closed; it is opened to resolve the workspace and to + build the view. A workspace the request names is checked before any + dialog; once a change is recorded, a workspace unregistered meanwhile only + leaves the refreshed list without container access. +5. **Core decides, before any dialog.** A new `ControlStore::check_profile` + applies every rule of `add_profile` except the revision and records + nothing. The list shows each proposal's refusal reason (for example, the + name is taken, or 32 profiles exist), and an add whose selection core + would refuse is refused before the confirmation. `add_profile` now gives + the 32-profile limit its own reason. `ControlStore::check_container_grants` + does the same for a batch of grants: the workspace, application storage, + the development-root scope, an existing grant or a repeat in the batch, + and the 32-per-workspace and 256 limits counting the batch. + `grant_container_access` runs the same checks. +6. **One native confirmation per batch.** Adding lists each selected + profile's name, family, version, roots, `PATH` entries, and variables with + their values, and says the list came from reading folders, no program ran, + and a profile grants nothing. Unlike the hand-entered form, values are + shown: discovery derived them from install paths, the operator typed none, + and each is cut to 160 characters. Each profile is then recorded with + `add_profile`, starting at the confirmed revision and advancing it once + per record, so a change made while the dialog was open is refused as + `stale_revision`. A failure after some records says how many were + recorded; each record is valid alone, so nothing is rolled back. +7. **Windows container grants for the proposed roots.** With a workspace + selected, each root says whether that workspace's AppContainer can read + it (`readable`, as for `Program Files`), needs a read-execute grant this + account can apply (`needs_grant`), or needs an administrator + (`needs_administrator`). Rust reads the folder's access-control list for + the derived container identity and opens the folder for `WRITE_DAC` to + learn whether a grant could be applied; nothing changes. The grant command + collects the `needs_grant` roots of the selection, drops folders beneath + another, and checks them with `check_container_grants`; a refusal names + the folder before any dialog. It then names the workspace and every + folder in one native confirmation, lists the folders it skips (those that + need an administrator and those whose access-control list could not be + read), and calls `grant_container_access` for each with the confirmed, + advancing revision. Folders whose access-control list this account + cannot change are never offered, so a folder only an administrator can + change does not become a `pending` grant that blocks the workspace's + runs. A recorded grant can still stay `pending` when its access list + cannot be changed afterwards, for example when the container identity + cannot be resolved; the command reports `container_access_failed`, and + the operator revokes the grant. The list also says whether the workspace has the active + read-write grant on its own folder that every run needs; core records a + read-write grant only on that folder. Choosing another workspace in the + window generates a list on screen again, so its access states never + describe another workspace. + +## Alternatives considered + +- **Probe versions with `rustc -vV`, `java -version`, or `vswhere`.** + Rejected for now. An unconfined probe is forbidden, and a confined one needs + a recorded profile before discovery can propose one. Folder names and + installer files gave every version the proposals need. +- **Read the Windows registry.** Rejected for now. Uninstall and vendor keys + would find installs in custom folders, but they add a second untrusted + input and an API surface the core does not need. Custom installs on `PATH`, + `JAVA_HOME`, or `GOROOT` are found. +- **Read `rust-toolchain.toml` or similar project files** to choose the + toolchain a project expects. Rejected: they are project-controlled. +- **Propose rustup proxies with `RUSTUP_HOME` and `RUSTUP_TOOLCHAIN`.** + Rejected: the roots would include every installed toolchain, rustup's + settings and downloads, and `~/.cargo`. One toolchain directory is narrower. +- **Record or grant automatically.** Rejected: discovery grants nothing, and + each record keeps its native confirmation. +- **Send the selected roots back from the webview.** Rejected, as in + ADR-0060 and ADR-0088: the window never names a path. +- **Keep the last list in Rust and select by index.** Rejected: re-discovery + with digests keeps the service stateless and refuses a list that no longer + matches the computer. +- **Offer every missing grant.** Rejected: a grant on an administrator-owned + folder fails after the record, leaving a `pending` grant that blocks runs + until revoked. +- **Skip installer files inside the development root.** Rejected for now: + discovery would have to open the settings store to learn the root before + it reads any folder. Core refuses such a root before any confirmation, and + the version read from it reaches only the list, bounded and display-safe. +- **Cut the list at 32 in family order.** Rejected: the families listed last + would lose every proposal on a computer with many toolchains of the first + families, with nothing on screen saying so. + +## Consequences + +- An operator can record working profiles for the installed toolchains in a + few clicks, and on Windows grant the folders they need, with every root, + entry, and value shown first. +- A proposal is advice. Nothing was run to confirm it, a family that has not + passed the acceptance runs may need more roots or variables, and the + proposals are only as complete as the standard folders, `PATH`, and the + three variables. Toolchains installed only in custom folders off `PATH` are + not found. +- A local process that can write to the operator's home folders can make a + folder look like a toolchain. It is proposed like any other, and the + operator sees and confirms every root. +- The known limits of model runs stay: no network, a 20-second deadline, and + 1 GiB of memory. A `cargo` build that needs crates.io dependencies fails + offline; only a trusted CLI `run --network`, under the workspace's + `task_network` preference, can download them. +- No CLI command lists proposals yet. The desktop shell has run only on + Windows; the Linux detectors are tested with fixture trees, not on a + running Linux shell. +- Windows grant checks read real access-control lists; their integration + tests stop at the confirmation and apply no grant. +- The type check before an installer file is opened narrows, but does not + close, the window in which a FIFO put at that path could block discovery. +- A folder with more than 16,384 entries is examined only in part, in the + order the filesystem lists it. + +## References + +- [execution.md](../execution.md#toolchain-profiles) +- [development-tools.md](../development-tools.md#tool-sources) +- [desktop-interface.md](../desktop-interface.md) +- [ADR-0030](0030-run-trusted-commands-through-recorded-toolchain-profiles.md), + [ADR-0060](0060-change-workspace-settings-from-the-desktop-with-native-dialogs.md), + [ADR-0088](0088-change-execution-settings-in-the-settings-window.md) diff --git a/docs/adr/index.md b/docs/adr/index.md index 1436e624..a795d345 100644 --- a/docs/adr/index.md +++ b/docs/adr/index.md @@ -117,3 +117,4 @@ meaningful alternative does not need an ADR. | [0100: List the recorded toolchain profiles in the command tool](0100-list-the-recorded-toolchain-profiles-in-the-command-tool.md) | Accepted | 2026-11-26 | | [0101: Make every section divider movable](0101-make-every-section-divider-movable.md) | Accepted | 2026-11-26 | | [0102: Choose a reasoning effort per session](0102-choose-a-reasoning-effort-per-session.md) | Accepted | 2026-11-26 | +| [0103: Generate toolchain profiles from installed toolchains](0103-generate-toolchain-profiles-from-installed-toolchains.md) | Accepted | 2026-11-26 | diff --git a/docs/desktop-interface.md b/docs/desktop-interface.md index a1197425..bb85c0b6 100644 --- a/docs/desktop-interface.md +++ b/docs/desktop-interface.md @@ -118,6 +118,12 @@ merged to `main` at the time of writing): workspace, manages skills, and adds and removes toolchain profiles, 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. Not implemented: @@ -274,7 +280,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 63 commands (31 in `main`, 3 in `approvals`, and 29 in `settings`). No other command exists. +The shell has three webview windows and 66 commands (31 in `main`, 3 in `approvals`, and 32 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. @@ -343,6 +349,9 @@ their registered identifier, and approvals by identifier. | `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) | `main` shows the session tree, search, transcripts, and chat. It renders transcript text. `approvals` lists approval records, shows the reviewed @@ -1383,6 +1392,33 @@ waits. The window shows: withdraw, as `workspace profile-remove` does; a run already started keeps its recorded profile. + **Generate toolchain profiles from local packages** (ADR-0103) sits above + the add form. It asks Rust for proposals, which core makes by reading the + standard install folders, the operator's `PATH`, `JAVA_HOME`, `GOROOT`, and + `RUSTUP_HOME`, and small installer-written files; it runs no program and + never reads repository configuration such as `rust-toolchain.toml`. Each + 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. + **Package-network profiles** list each profile's origins and how many credentials are bound, and a **Remove** button. A line says a profile is configuration only: no run uses it and it grants no network access. @@ -2263,7 +2299,9 @@ ACLs the private store refuses, see the notes in permission rows, and the Advanced groups; `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); 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 `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 @@ -2393,6 +2431,18 @@ ACLs the private store refuses, see the notes in 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 the real shell's settings window were not driven by automation. +- ADR-0103: discovery was checked by core tests with Windows and Linux fixture + trees for every family, and the commands by service tests with a scripted + prompt and a fixture host + (`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 + 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. - 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/development-tools.md b/docs/development-tools.md index 8e711d03..28d6a8ff 100644 --- a/docs/development-tools.md +++ b/docs/development-tools.md @@ -43,13 +43,18 @@ An installed toolchain may need executables, helper programs, shared libraries, SDK files, configuration, and machine-derived environment values. A single executable-path grant is often insufficient. -Profiles are currently declared by the operator, with no discovery; see +Profiles are declared by the operator; see [ADR-0030](adr/0030-run-trusted-commands-through-recorded-toolchain-profiles.md). -Any later discovery runs through a trusted host-side service. It proposes the -required resources for user selection; the model cannot approve new host -access. +Since version 0.68.0 the `settings` window can generate proposals from the +installed toolchains through a trusted host-side service in core +([ADR-0103](adr/0103-generate-toolchain-profiles-from-installed-toolchains.md)). +It reads install folders, the operator's `PATH` and a few toolchain +variables, and small installer-written files; it runs no probe and never +reads repository configuration such as `rust-toolchain.toml`. It proposes the required resources for user selection, and +each selected profile or Windows grant is recorded through the existing core +call after a native confirmation. The model cannot approve new host access. Do not execute repository-controlled discovery hooks or version probes with -unrestricted host privileges. Run executable probes in confinement. +unrestricted host privileges. Run any future executable probe in confinement. For an installed toolchain, expose only the required installation resources, normally read-only. A managed environment can provide an isolated installation diff --git a/docs/execution.md b/docs/execution.md index 6c8a9a59..fff0334c 100644 --- a/docs/execution.md +++ b/docs/execution.md @@ -843,11 +843,14 @@ its target, and every later action in the same session carries ### Toolchain profiles -Profiles are declared by the operator. Nothing is discovered automatically. -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). +Profiles are declared by the operator. Nothing is recorded automatically: the +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). | Command | Effect | | --- | --- | @@ -886,6 +889,73 @@ 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`. +#### Generated profiles + +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. + +- **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, + Perl, Go, Node.js, .NET, and Ruby. Each family is one detector in a + registry. +- **Inputs:** the standard install folders, the operator's `PATH`, + `JAVA_HOME`, `GOROOT`, and `RUSTUP_HOME`, and small files the installers + wrote (rustup's `settings.toml`, a JDK's `release`, Go's `VERSION`), each + checked to be a regular file before it is opened. Discovery runs no + program, confined or not, reads no registry key, and never reads + repository configuration such as `rust-toolchain.toml`. A folder that + `PATH` or one of those variables names is read like any install folder, + installer files included, even inside the development root; core refuses + it as a root before any confirmation, and the list shows why. +- **Proposals:** each lists its roots, `PATH` entries, and variables, plus the + system part every profile needs (`System32`, or `/usr` and the real + top-level `bin`, `lib`, `lib64`, and `lib32` directories). No root is a filesystem or drive + root, the home directory or its ancestor, or itself a link: core records a + root's resolved location, so a linked root is left out. Variables are + derived setup values only, such as `JAVA_HOME`, `GOROOT`, `DOTNET_ROOT`, + and MSVC's `INCLUDE` and `LIB`; reserved names are never proposed. A Rust + proposal is one toolchain directory, without the rustup proxies or + `~/.cargo`. At most 32 proposals are returned, 8 per base name, its + preferred installation (such as rustup's default toolchain) first and + then newest first; past 32, every base name keeps its first installation before any + keeps a second, and the list says how many installations it left out. A + folder listing examines at most 16,384 entries and keeps the first 512 + directories by name. +- **Checks:** each proposal shows the reason core would refuse it now, from + `check_profile`, which applies every `add_profile` rule and records nothing. +- **Adding:** the window sends only the settings revision and the digests of + 1 to 8 selected proposals. Rust discovers again, refuses a selection that no + 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 + 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 + `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. +- **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 + download dependencies. + +Known limits: a model command runs with no network, a 20-second deadline, and +1 GiB of memory, so a `cargo` build that needs crates.io dependencies fails +unless they are already present. Only a trusted CLI `run --network` under the +workspace's `task_network` preference can fetch them. Toolchains installed in +custom folders that are not on `PATH` are not found. No CLI command lists +proposals. + ### Run journal `/runs-v1.jsonl` sits beside the control journal and shares its