diff --git a/crates/now-package-broker/src/command_builder/bun.rs b/crates/now-package-broker/src/command_builder/bun.rs index db65d8368..b59c7cd53 100644 --- a/crates/now-package-broker/src/command_builder/bun.rs +++ b/crates/now-package-broker/src/command_builder/bun.rs @@ -13,7 +13,7 @@ use anyhow::bail; use now_policy_api::{Architecture, Elevation, Operation, PackageRequest, Scope}; -use super::{uses_default_source, validate_npm_package_name}; +use super::{SourceChoice, uses_default_source, validate_npm_package_name}; const BUN_SOURCE_NAME: &str = "Bun"; const BUN_SOURCE_URL: &str = "https://www.npmjs.com"; @@ -22,7 +22,20 @@ const BUN_SOURCE_URL: &str = "https://www.npmjs.com"; /// /// Returns the command as a list of arguments (first element is the executable). pub fn build_bun_command(request: &PackageRequest) -> anyhow::Result> { - validate_bun_request(request)?; + build_bun_command_as( + request, + SourceChoice::Request, + crate::evaluator::effective_execution_elevation(request), + ) +} + +/// Build the command of a run whose token has the elevation `elevation`, on the source that `source` chooses. +pub(crate) fn build_bun_command_as( + request: &PackageRequest, + source: SourceChoice, + elevation: Elevation, +) -> anyhow::Result> { + validate_bun_request(request, source, elevation)?; let operation = match request.operation { Operation::Install | Operation::Update => "add", @@ -44,16 +57,16 @@ pub fn build_bun_command(request: &PackageRequest) -> anyhow::Result ]) } -fn validate_bun_request(request: &PackageRequest) -> anyhow::Result<()> { +fn validate_bun_request(request: &PackageRequest, source: SourceChoice, elevation: Elevation) -> anyhow::Result<()> { if request.options.scope == Some(Scope::Machine) { bail!("machine-scope Bun package operations are not supported by the broker"); } - if crate::evaluator::effective_execution_elevation(request) == Elevation::Elevated { + if elevation == Elevation::Elevated { bail!("elevated Bun package operations are not supported by the broker"); } - if !uses_default_source("Bun", request)? + if !uses_default_source("Bun", request, source)? && (!request.source.name.eq_ignore_ascii_case(BUN_SOURCE_NAME) || request .source diff --git a/crates/now-package-broker/src/command_builder/cargo.rs b/crates/now-package-broker/src/command_builder/cargo.rs index cdf7cb536..1032600b4 100644 --- a/crates/now-package-broker/src/command_builder/cargo.rs +++ b/crates/now-package-broker/src/command_builder/cargo.rs @@ -3,7 +3,7 @@ use anyhow::bail; use now_policy_api::{Architecture, Elevation, Operation, PackageRequest, Scope}; -use super::{set_if_specified, uses_default_source, validate_batch_arguments, validate_package_version}; +use super::{SourceChoice, set_if_specified, uses_default_source, validate_batch_arguments, validate_package_version}; const CRATES_IO_SOURCE_NAME: &str = "crates.io"; const CRATES_IO_SOURCE_URL: &str = "https://index.crates.io"; @@ -14,7 +14,20 @@ const CARGO_VERSION_EXTRA_CHARACTERS: &[char] = &['=', '~', '*']; /// /// Returns the command as a list of arguments (first element is the executable). pub fn build_cargo_command(request: &PackageRequest) -> anyhow::Result> { - validate_cargo_request(request)?; + build_cargo_command_as( + request, + SourceChoice::Request, + crate::evaluator::effective_execution_elevation(request), + ) +} + +/// Build the command of a run whose token has the elevation `elevation`, on the source that `source` chooses. +pub(crate) fn build_cargo_command_as( + request: &PackageRequest, + source: SourceChoice, + elevation: Elevation, +) -> anyhow::Result> { + validate_cargo_request(request, source, elevation)?; let operation = match request.operation { Operation::Install | Operation::Update => "install", @@ -60,14 +73,14 @@ pub fn build_cargo_command(request: &PackageRequest) -> anyhow::Result anyhow::Result<()> { +fn validate_cargo_request(request: &PackageRequest, source: SourceChoice, elevation: Elevation) -> anyhow::Result<()> { if request.options.scope == Some(Scope::Machine) { bail!("cargo machine-scope operations are not supported by the broker"); } - if crate::evaluator::effective_execution_elevation(request) == Elevation::Elevated { + if elevation == Elevation::Elevated { bail!("cargo elevated operations are not supported by the broker"); } - if !uses_default_source("cargo", request)? { + if !uses_default_source("cargo", request, source)? { if !request.source.name.eq_ignore_ascii_case(CRATES_IO_SOURCE_NAME) { bail!("cargo package source must be crates.io"); } diff --git a/crates/now-package-broker/src/command_builder/chocolatey.rs b/crates/now-package-broker/src/command_builder/chocolatey.rs index 4a2313d24..d27da4424 100644 --- a/crates/now-package-broker/src/command_builder/chocolatey.rs +++ b/crates/now-package-broker/src/command_builder/chocolatey.rs @@ -4,14 +4,23 @@ use anyhow::bail; use now_policy_api::{Architecture, Operation, PackageRequest, Scope}; use super::{ - set_if_true, uses_default_source, validate_batch_arguments, validate_package_version, validate_source_name, + SourceChoice, set_if_true, uses_default_source, validate_batch_arguments, validate_package_version, + validate_source_name, }; /// Build the Chocolatey command line from a validated request. /// /// Returns the command as a list of arguments (first element is the executable). pub fn build_chocolatey_command(request: &PackageRequest) -> anyhow::Result> { - validate_chocolatey_request(request)?; + build_chocolatey_command_with(request, SourceChoice::Request) +} + +/// Build the Chocolatey command line of a request, on the source that `source` chooses. +pub(crate) fn build_chocolatey_command_with( + request: &PackageRequest, + source: SourceChoice, +) -> anyhow::Result> { + validate_chocolatey_request(request, source)?; let operation = match request.operation { Operation::Install => "install", @@ -30,7 +39,7 @@ pub fn build_chocolatey_command(request: &PackageRequest) -> anyhow::Result anyhow::Result anyhow::Result<()> { +fn validate_chocolatey_request(request: &PackageRequest, source: SourceChoice) -> anyhow::Result<()> { validate_chocolatey_package_id(&request.package.id.0)?; if request.source.url.is_some() { @@ -116,7 +125,7 @@ fn validate_chocolatey_request(request: &PackageRequest) -> anyhow::Result<()> { } if matches!(request.operation, Operation::Install | Operation::Update) { - chocolatey_source(request)?; + chocolatey_source(request, source)?; if let Some(version) = request.package.version.as_deref() { validate_package_version("Chocolatey", version, &[])?; } @@ -176,19 +185,19 @@ fn selects_chocolatey_source_type(source: &str) -> bool { } /// The named source for `--source`, or `None` to use Chocolatey's configured default sources. -fn chocolatey_source(request: &PackageRequest) -> anyhow::Result> { - if uses_default_source("Chocolatey", request)? { +fn chocolatey_source(request: &PackageRequest, source: SourceChoice) -> anyhow::Result> { + if uses_default_source("Chocolatey", request, source)? { return Ok(None); } - let source = request.source.name.trim(); - if source.is_empty() { + let name = request.source.name.trim(); + if name.is_empty() { bail!("Chocolatey package source name is required"); } - validate_source_name("Chocolatey", source)?; - if selects_chocolatey_source_type(source) { - bail!("Chocolatey package source name '{source}' selects a Chocolatey source type, not a configured source"); + validate_source_name("Chocolatey", name)?; + if selects_chocolatey_source_type(name) { + bail!("Chocolatey package source name '{name}' selects a Chocolatey source type, not a configured source"); } - Ok(Some(source)) + Ok(Some(name)) } #[cfg(test)] diff --git a/crates/now-package-broker/src/command_builder/dotnet.rs b/crates/now-package-broker/src/command_builder/dotnet.rs index 23d1bb979..03f8f0860 100644 --- a/crates/now-package-broker/src/command_builder/dotnet.rs +++ b/crates/now-package-broker/src/command_builder/dotnet.rs @@ -8,7 +8,7 @@ use anyhow::bail; use now_policy_api::{Architecture, Operation, PackageRequest, Scope}; -use super::{set_if_specified, set_if_true, uses_default_source, validate_package_version}; +use super::{SourceChoice, set_if_specified, set_if_true, uses_default_source, validate_package_version}; const NUGET_ORG_V3_SOURCE: &str = "https://api.nuget.org/v3/index.json"; /// NuGet version range syntax, such as `[1.0,2.0)` or `1.*`. @@ -18,7 +18,12 @@ const DOTNET_VERSION_RANGE_CHARACTERS: &[char] = &['[', ']', '(', ')', ',', '*'] /// /// Returns the command as a list of arguments (first element is the executable). pub fn build_dotnet_command(request: &PackageRequest) -> anyhow::Result> { - validate_dotnet_request(request)?; + build_dotnet_command_with(request, SourceChoice::Request) +} + +/// Build the .NET tool command line of a request, on the source that `source` chooses. +pub(crate) fn build_dotnet_command_with(request: &PackageRequest, source: SourceChoice) -> anyhow::Result> { + validate_dotnet_request(request, source)?; let operation = match request.operation { Operation::Install => "install", @@ -44,7 +49,7 @@ pub fn build_dotnet_command(request: &PackageRequest) -> anyhow::Result anyhow::Result anyhow::Result<()> { +fn validate_dotnet_request(request: &PackageRequest, source: SourceChoice) -> anyhow::Result<()> { // `dotnet tool` reads an element starting with `-` as an option, so such an id names no package. if request.package.id.0.starts_with('-') { bail!(".NET package id cannot start with a hyphen"); @@ -93,7 +98,7 @@ fn validate_dotnet_request(request: &PackageRequest) -> anyhow::Result<()> { bail!(".NET prerelease selection is not supported for uninstall operations"); } if matches!(request.operation, Operation::Install | Operation::Update) { - dotnet_source(request)?; + dotnet_source(request, source)?; if let Some(version) = request.package.version.as_deref() { validate_package_version(".NET", version, DOTNET_VERSION_RANGE_CHARACTERS)?; } @@ -102,8 +107,8 @@ fn validate_dotnet_request(request: &PackageRequest) -> anyhow::Result<()> { Ok(()) } -fn append_source(command: &mut Vec, request: &PackageRequest) -> anyhow::Result<()> { - if let Some(source) = dotnet_source(request)? { +fn append_source(command: &mut Vec, request: &PackageRequest, source: SourceChoice) -> anyhow::Result<()> { + if let Some(source) = dotnet_source(request, source)? { command.push("--source".to_owned()); command.push(source.to_owned()); } @@ -111,8 +116,15 @@ fn append_source(command: &mut Vec, request: &PackageRequest) -> anyhow: } /// The canonical feed to pass as `--source`, or `None` to use the NuGet configuration's default feeds. -fn dotnet_source(request: &PackageRequest) -> anyhow::Result> { - if uses_default_source(".NET", request)? { +fn dotnet_source(request: &PackageRequest, source: SourceChoice) -> anyhow::Result> { + // A request without a source is read with `nuget.org`, the only source name of an install or update + // ([§bypass-reading]), so its command is the one of that name. + // + // [§bypass-reading]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#bypass-reading + if source == SourceChoice::Manager { + return Ok(Some(NUGET_ORG_V3_SOURCE)); + } + if uses_default_source(".NET", request, source)? { return Ok(None); } diff --git a/crates/now-package-broker/src/command_builder/mod.rs b/crates/now-package-broker/src/command_builder/mod.rs index cb0fb0cfe..49a332ef6 100644 --- a/crates/now-package-broker/src/command_builder/mod.rs +++ b/crates/now-package-broker/src/command_builder/mod.rs @@ -15,7 +15,7 @@ pub mod vcpkg; pub mod winget; use anyhow::bail; -use now_policy_api::{ManagerName, Operation, PackageRequest}; +use now_policy_api::{Elevation, ManagerName, Operation, PackageRequest}; /// Build a command line from a validated request, dispatching to the appropriate /// package manager builder. @@ -51,6 +51,34 @@ fn build_manager_command(request: &PackageRequest) -> anyhow::Result } } +/// Build the command line of a run whose token elevation the caller states, with the installer arguments it carries. +/// +/// [`build_command`] derives the elevation from the request's requested elevation and scope, and passes no installer +/// arguments; this serves a request that states its run elevation itself, and may have no source. +/// Unlike [`build_command`], it names the scope of the request on a PowerShell 7 uninstall, and has every option of +/// a WinGet command before the custom parameters. +pub(crate) fn build_command_as( + request: &PackageRequest, + source: SourceChoice, + elevation: Elevation, + installer_arguments: Option>, +) -> anyhow::Result> { + match request.manager { + ManagerName::Bun => bun::build_bun_command_as(request, source, elevation), + ManagerName::Cargo => cargo::build_cargo_command_as(request, source, elevation), + ManagerName::Dotnet => dotnet::build_dotnet_command_with(request, source), + ManagerName::Npm => npm::build_npm_command_as(request, source, elevation), + ManagerName::Winget => winget::build_winget_command_with(request, source, installer_arguments), + ManagerName::PowerShell => powershell::build_powershell5_command_as(request, source, elevation), + ManagerName::PowerShell7 => powershell::build_powershell7_command_as(request, source, elevation), + ManagerName::Chocolatey => chocolatey::build_chocolatey_command_with(request, source), + ManagerName::Pip => pip::build_pip_command_as(request, source, elevation), + ManagerName::Scoop => scoop::build_scoop_command_as(request, source, elevation), + ManagerName::Vcpkg => vcpkg::build_vcpkg_command_as(request, source, elevation), + unsupported => bail!("package manager is not supported by the broker: {unsupported}"), + } +} + /// Build a command line for a remote grant. /// /// Unlike [`build_command`], this allows a PowerShell 7 update with an empty source and scopes its uninstalls. @@ -129,11 +157,34 @@ pub(crate) fn validate_source_name(manager: &str, name: &str) -> anyhow::Result< Ok(()) } +/// Who chooses the source that the command of a request acts on. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum SourceChoice { + /// The request, by its source name. + /// + /// An empty name builds no install, and leaves an update or an uninstall to the sources its manager is + /// configured with. + Request, + /// The manager, for a request that has no source ([§bypass-reading]). + /// + /// The source name of the request is not read. + /// + /// [§bypass-reading]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#bypass-reading + Manager, +} + /// Report whether the request leaves the source to the manager's ordinary default. /// -/// Only update and uninstall may carry an empty source name, and never with a URL. -/// An install must always name its source. -pub(crate) fn uses_default_source(manager: &str, request: &PackageRequest) -> anyhow::Result { +/// A request that chooses its source may carry an empty source name only for update and uninstall, and never with a +/// URL: its install must always name its source. +pub(crate) fn uses_default_source( + manager: &str, + request: &PackageRequest, + source: SourceChoice, +) -> anyhow::Result { + if source == SourceChoice::Manager { + return Ok(true); + } if !request.source.name.is_empty() { return Ok(false); } diff --git a/crates/now-package-broker/src/command_builder/npm.rs b/crates/now-package-broker/src/command_builder/npm.rs index 169c32b7c..d73ef13f9 100644 --- a/crates/now-package-broker/src/command_builder/npm.rs +++ b/crates/now-package-broker/src/command_builder/npm.rs @@ -13,7 +13,9 @@ use anyhow::bail; use now_policy_api::{Architecture, Elevation, Operation, PackageRequest, Scope}; -use super::{quote_powershell_literal, uses_default_source, validate_npm_package_name, validate_package_version}; +use super::{ + SourceChoice, quote_powershell_literal, uses_default_source, validate_npm_package_name, validate_package_version, +}; /// npm version selectors that are inert when passed through the `npm.cmd` shim, such as `~1.2` or `1.x`. const NPM_VERSION_EXTRA_CHARACTERS: &[char] = &['~', '*']; @@ -28,7 +30,20 @@ const SCRIPT_PREFIX: &str = "$ErrorActionPreference = 'Stop'; \ /// Build an npm command from a validated request. pub fn build_npm_command(request: &PackageRequest) -> anyhow::Result> { - validate_npm_request(request)?; + build_npm_command_as( + request, + SourceChoice::Request, + crate::evaluator::effective_execution_elevation(request), + ) +} + +/// Build the command of a run whose token has the elevation `elevation`, on the source that `source` chooses. +pub(crate) fn build_npm_command_as( + request: &PackageRequest, + source: SourceChoice, + elevation: Elevation, +) -> anyhow::Result> { + validate_npm_request(request, source, elevation)?; let mut script = String::from(SCRIPT_PREFIX); @@ -55,17 +70,17 @@ pub fn build_npm_command(request: &PackageRequest) -> anyhow::Result ]) } -fn validate_npm_request(request: &PackageRequest) -> anyhow::Result<()> { +fn validate_npm_request(request: &PackageRequest, source: SourceChoice, elevation: Elevation) -> anyhow::Result<()> { if request.options.scope == Some(Scope::Machine) { bail!("npm machine-scope operations are not supported by the broker"); } - if crate::evaluator::effective_execution_elevation(request) == Elevation::Elevated { + if elevation == Elevation::Elevated { bail!("npm elevated operations are not supported by the broker"); } if request.source.url.is_some() { bail!("npm package sources with URLs are not supported by the broker"); } - if !uses_default_source("npm", request)? && !request.source.name.eq_ignore_ascii_case("npm") { + if !uses_default_source("npm", request, source)? && !request.source.name.eq_ignore_ascii_case("npm") { bail!("npm package source must be 'npm'"); } match request.package.architecture { diff --git a/crates/now-package-broker/src/command_builder/pip.rs b/crates/now-package-broker/src/command_builder/pip.rs index ab575214f..cb6af45a6 100644 --- a/crates/now-package-broker/src/command_builder/pip.rs +++ b/crates/now-package-broker/src/command_builder/pip.rs @@ -3,7 +3,7 @@ use anyhow::bail; use now_policy_api::{Architecture, Elevation, Operation, PackageRequest, Scope}; -use super::uses_default_source; +use super::{SourceChoice, uses_default_source}; /// Build the Pip command line from a validated request. /// @@ -12,7 +12,20 @@ use super::uses_default_source; /// a batch script, which cannot carry `!`; a version with an epoch such as `1!2.0` then fails /// before Pip runs, while the same request runs through any other `python.exe`. pub fn build_pip_command(request: &PackageRequest) -> anyhow::Result> { - validate_pip_request(request)?; + build_pip_command_as( + request, + SourceChoice::Request, + crate::evaluator::effective_execution_elevation(request), + ) +} + +/// Build the command of a run whose token has the elevation `elevation`, on the source that `source` chooses. +pub(crate) fn build_pip_command_as( + request: &PackageRequest, + source: SourceChoice, + elevation: Elevation, +) -> anyhow::Result> { + validate_pip_request(request, source, elevation)?; let mut command = vec![ "python.exe".to_owned(), @@ -56,17 +69,17 @@ pub fn build_pip_command(request: &PackageRequest) -> anyhow::Result Ok(command) } -fn validate_pip_request(request: &PackageRequest) -> anyhow::Result<()> { +fn validate_pip_request(request: &PackageRequest, source: SourceChoice, elevation: Elevation) -> anyhow::Result<()> { if request.options.scope == Some(Scope::Machine) { bail!("pip machine-scope operations are not supported by the broker"); } - if crate::evaluator::effective_execution_elevation(request) == Elevation::Elevated { + if elevation == Elevation::Elevated { bail!("pip elevated operations are not supported by the broker"); } if request.source.url.is_some() { bail!("pip package sources with urls are not supported by the broker"); } - if !uses_default_source("pip", request)? && !request.source.name.eq_ignore_ascii_case("pip") { + if !uses_default_source("pip", request, source)? && !request.source.name.eq_ignore_ascii_case("pip") { bail!("pip package source must be pip"); } validate_distribution_name(&request.package.id.0)?; diff --git a/crates/now-package-broker/src/command_builder/powershell.rs b/crates/now-package-broker/src/command_builder/powershell.rs index cde044621..042d964b4 100644 --- a/crates/now-package-broker/src/command_builder/powershell.rs +++ b/crates/now-package-broker/src/command_builder/powershell.rs @@ -14,6 +14,7 @@ //! Uninstall and `Update-Module` take no `-Repository`: they act on installed modules, and //! `Update-Module` updates from the repository a module was installed from. Those commands //! first check that every installed version came from the requested source instead. +//! A request that leaves the source to the manager gets neither `-Repository` nor that check. //! Options that don't apply to PowerShell modules (interactive, custom install //! location, skip hash check, winget's no-upgrade / uninstall-previous) are intentionally omitted. //! PowerShellGet has no installer hash check to skip: its `-SkipPublisherCheck` skips the @@ -22,7 +23,9 @@ use anyhow::bail; use now_policy_api::{Elevation, ManagerName, Operation, PackageRequest, Scope}; -use super::{quote_powershell_literal, uses_default_source, validate_package_version, validate_source_name}; +use super::{ + SourceChoice, quote_powershell_literal, uses_default_source, validate_package_version, validate_source_name, +}; /// The repository PowerShellGet registers by default, with a URL built into the module. const POWERSHELL_GALLERY: &str = "PSGallery"; @@ -44,18 +47,28 @@ const SCRIPT_SUFFIX: &str = "; exit 0"; /// Build a Windows PowerShell 5.x (PowerShellGet) command from a validated request. pub fn build_powershell5_command(request: &PackageRequest) -> anyhow::Result> { - build_powershell5(request, crate::evaluator::effective_execution_elevation(request)) + build_powershell5_command_as( + request, + SourceChoice::Request, + crate::evaluator::effective_execution_elevation(request), + ) } /// Build a Windows PowerShell 5.x command for a remote grant, which runs with the requested elevation. /// /// The caller must enforce the grant's target-user token and requested elevation. pub(super) fn build_powershell5_remote_grant_command(request: &PackageRequest) -> anyhow::Result> { - build_powershell5(request, request.client.requested_elevation) + build_powershell5_command_as(request, SourceChoice::Request, request.client.requested_elevation) } -fn build_powershell5(request: &PackageRequest, elevation: Elevation) -> anyhow::Result> { - validate_powershell_request(request, false, elevation)?; +/// Build the Windows PowerShell command of a run whose token has the elevation `elevation`, on the source that +/// `source` chooses. +pub(crate) fn build_powershell5_command_as( + request: &PackageRequest, + source: SourceChoice, + elevation: Elevation, +) -> anyhow::Result> { + validate_powershell_request(request, source, false, elevation)?; let mut script = SCRIPT_PREFIX.to_owned(); @@ -67,7 +80,12 @@ fn build_powershell5(request: &PackageRequest, elevation: Elevation) -> anyhow:: &mut script, "; AllVersions = $true; ErrorAction = 'Stop' }; if ((Get-Command Get-InstalledModule).Parameters.ContainsKey('AllowPrerelease')) { $installedModuleQuery.AllowPrerelease = $true };", ); - append_installed_repository_check(&mut script, "Get-InstalledModule @installedModuleQuery", request)?; + append_installed_repository_check( + &mut script, + "Get-InstalledModule @installedModuleQuery", + request, + source, + )?; } let verb = match request.operation { @@ -78,8 +96,11 @@ fn build_powershell5(request: &PackageRequest, elevation: Elevation) -> anyhow:: append_raw(&mut script, verb); append_flag_value(&mut script, "-Name", &request.package.id.0); - if request.operation == Operation::Install { - append_repository(&mut script, request)?; + // Without `-Repository`, `Install-Module` searches every repository registered for the user. + if request.operation == Operation::Install + && let Some(repository) = repository(request, source)? + { + append_flag_value(&mut script, "-Repository", repository); } append_raw(&mut script, "-Confirm:$false"); append_raw(&mut script, "-Force"); @@ -113,7 +134,32 @@ fn build_powershell5(request: &PackageRequest, elevation: Elevation) -> anyhow:: /// Build a PowerShell 7.x (PSResourceGet) command from a validated request. pub fn build_powershell7_command(request: &PackageRequest) -> anyhow::Result> { - build_powershell7(request, false) + build_powershell7( + request, + SourceChoice::Request, + false, + UninstallScope::Unnamed, + crate::evaluator::effective_execution_elevation(request), + ) +} + +/// Whether `Uninstall-PSResource` is told the scope it removes a resource from. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum UninstallScope { + /// The command names no scope, so PSResourceGet removes the resource from where it finds it. + Unnamed, + /// The command names the scope of the request, when the request has one. + OfRequest, +} + +/// Build the PowerShell 7 command of a run whose token has the elevation `elevation`, on the source that `source` +/// chooses, with an uninstall that names the scope of the request when the request has one. +pub(crate) fn build_powershell7_command_as( + request: &PackageRequest, + source: SourceChoice, + elevation: Elevation, +) -> anyhow::Result> { + build_powershell7(request, source, false, UninstallScope::OfRequest, elevation) } /// Build a PowerShell 7.x command for a remote grant. @@ -122,17 +168,26 @@ pub fn build_powershell7_command(request: &PackageRequest) -> anyhow::Result anyhow::Result> { - build_powershell7(request, true) + build_powershell7( + request, + SourceChoice::Request, + true, + UninstallScope::OfRequest, + // A remote grant runs with the requested elevation, even with a machine scope. + request.client.requested_elevation, + ) } -fn build_powershell7(request: &PackageRequest, remote_grant: bool) -> anyhow::Result> { - // A remote grant runs with the requested elevation, even with a machine scope. - let elevation = if remote_grant { - request.client.requested_elevation - } else { - crate::evaluator::effective_execution_elevation(request) - }; - validate_powershell_request(request, remote_grant, elevation)?; +fn build_powershell7( + request: &PackageRequest, + source: SourceChoice, + remote_grant: bool, + uninstall_scope: UninstallScope, + elevation: Elevation, +) -> anyhow::Result> { + // A request that has no source leaves the repositories of its update to the manager, as a remote grant does. + let allow_default_update_source = remote_grant || source == SourceChoice::Manager; + validate_powershell_request(request, source, allow_default_update_source, elevation)?; let mut script = SCRIPT_PREFIX.to_owned(); @@ -141,7 +196,7 @@ fn build_powershell7(request: &PackageRequest, remote_grant: bool) -> anyhow::Re "Get-InstalledPSResource -Name {} -ErrorAction Stop", quote_powershell_literal(&request.package.id.0) ); - append_installed_repository_check(&mut script, &lookup, request)?; + append_installed_repository_check(&mut script, &lookup, request, source)?; } let verb = match request.operation { @@ -153,7 +208,7 @@ fn build_powershell7(request: &PackageRequest, remote_grant: bool) -> anyhow::Re append_raw(&mut script, verb); append_flag_value(&mut script, "-Name", &request.package.id.0); if request.operation != Operation::Uninstall - && let Some(repository) = repository(request)? + && let Some(repository) = repository(request, source)? { append_flag_value(&mut script, "-Repository", repository); } @@ -184,7 +239,7 @@ fn build_powershell7(request: &PackageRequest, remote_grant: bool) -> anyhow::Re Some(Scope::Machine) => append_raw(&mut script, "-Scope AllUsers"), Some(Scope::User) | None => append_raw(&mut script, "-Scope CurrentUser"), } - } else if remote_grant { + } else if uninstall_scope == UninstallScope::OfRequest { match request.options.scope { Some(Scope::Machine) => append_raw(&mut script, "-Scope AllUsers"), Some(Scope::User) => append_raw(&mut script, "-Scope CurrentUser"), @@ -202,16 +257,17 @@ fn build_powershell7(request: &PackageRequest, remote_grant: bool) -> anyhow::Re ]) } -/// Validate a request that runs with `elevation`. +/// Validate a request that runs with `elevation`, on the source that `source` chooses. fn validate_powershell_request( request: &PackageRequest, + source: SourceChoice, allow_default_update_source: bool, elevation: Elevation, ) -> anyhow::Result<()> { if request.source.url.is_some() { bail!("PowerShell package sources with URLs are not supported by the broker"); } - let repository = repository(request)?; + let repository = repository(request, source)?; // Update-PSResource without -Repository searches every registered repository and the script trusts them. if repository.is_none() && !allow_default_update_source @@ -270,9 +326,9 @@ fn validate_powershell_request( Ok(()) } -/// The repository name, or `None` when update or uninstall leaves the source to the manager. -fn repository(request: &PackageRequest) -> anyhow::Result> { - if uses_default_source("PowerShell", request)? { +/// The repository name, or `None` when the request leaves the source to the manager. +fn repository(request: &PackageRequest, source: SourceChoice) -> anyhow::Result> { + if uses_default_source("PowerShell", request, source)? { return Ok(None); } let repository = request.source.name.trim(); @@ -282,14 +338,6 @@ fn repository(request: &PackageRequest) -> anyhow::Result> { Ok(Some(repository)) } -fn append_repository(script: &mut String, request: &PackageRequest) -> anyhow::Result<()> { - let Some(repository) = repository(request)? else { - bail!("PowerShell package source name is required"); - }; - append_flag_value(script, "-Repository", repository); - Ok(()) -} - /// Fail the script unless every installed version that `lookup` lists was installed from /// the requested source, so a command without `-Repository` only acts on modules from the /// source that policy evaluation matched. @@ -303,8 +351,9 @@ fn append_installed_repository_check( script: &mut String, lookup: &str, request: &PackageRequest, + source: SourceChoice, ) -> anyhow::Result<()> { - let Some(repository) = repository(request)? else { + let Some(repository) = repository(request, source)? else { return Ok(()); }; append_raw( diff --git a/crates/now-package-broker/src/command_builder/scoop.rs b/crates/now-package-broker/src/command_builder/scoop.rs index 665687403..264cf4aef 100644 --- a/crates/now-package-broker/src/command_builder/scoop.rs +++ b/crates/now-package-broker/src/command_builder/scoop.rs @@ -7,7 +7,7 @@ use anyhow::bail; use now_policy_api::{Architecture, Elevation, Operation, PackageRequest, Scope}; -use super::{quote_powershell_literal, uses_default_source}; +use super::{SourceChoice, quote_powershell_literal, uses_default_source}; /// Build a Scoop command from a validated request. /// @@ -15,7 +15,12 @@ use super::{quote_powershell_literal, uses_default_source}; /// can materialize it in a protected temporary `.ps1` file and replace the /// PowerShell host with a trusted system path. pub fn build_scoop_command(request: &PackageRequest) -> anyhow::Result> { - build_scoop(request, false) + build_scoop( + request, + SourceChoice::Request, + crate::evaluator::effective_execution_elevation(request), + false, + ) } /// Build a Scoop command for a remote grant. @@ -25,11 +30,30 @@ pub fn build_scoop_command(request: &PackageRequest) -> anyhow::Result anyhow::Result> { - build_scoop(request, true) + build_scoop( + request, + SourceChoice::Request, + crate::evaluator::effective_execution_elevation(request), + true, + ) } -fn build_scoop(request: &PackageRequest, remote_grant: bool) -> anyhow::Result> { - validate_scoop_request(request, remote_grant)?; +/// Build the command of a run whose token has the elevation `elevation`, on the source that `source` chooses. +pub(crate) fn build_scoop_command_as( + request: &PackageRequest, + source: SourceChoice, + elevation: Elevation, +) -> anyhow::Result> { + build_scoop(request, source, elevation, false) +} + +fn build_scoop( + request: &PackageRequest, + source: SourceChoice, + elevation: Elevation, + remote_grant: bool, +) -> anyhow::Result> { + validate_scoop_request(request, source, elevation, remote_grant)?; let operation = match request.operation { Operation::Install => "install", @@ -37,7 +61,7 @@ fn build_scoop(request: &PackageRequest, remote_grant: bool) -> anyhow::Result "uninstall", }; - let mut scoop_args = vec![operation.to_owned(), scoop_package_ref(request)?]; + let mut scoop_args = vec![operation.to_owned(), scoop_package_ref(request, source)?]; if matches!(request.operation, Operation::Install | Operation::Update) && request.options.skip_hash_check { scoop_args.push("--skip-hash-check".to_owned()); @@ -89,13 +113,19 @@ fn build_scoop(request: &PackageRequest, remote_grant: bool) -> anyhow::Result anyhow::Result<()> { - // UNTESTED: refusing every local update keeps Scoop from updating an app from a bucket other than the one - // the request names, until the broker reads the bucket recorded at install (`scoop-install.json` or - // `install.json` in the app's current version directory). +fn validate_scoop_request( + request: &PackageRequest, + source: SourceChoice, + elevation: Elevation, + remote_grant: bool, +) -> anyhow::Result<()> { + // UNTESTED: refusing every local update of a request that chooses its source keeps Scoop from updating an app + // from a bucket other than the one the request names, until the broker reads the bucket recorded at install + // (`scoop-install.json` or `install.json` in the app's current version directory). // Scoop resolves that directory from `SCOOP`, its `root_path` setting or its own location, so such a check // must resolve it the way the `scoop.ps1` the broker runs does. - if request.operation == Operation::Update && !remote_grant { + // A request that leaves the source to Scoop names no bucket for the recorded one to differ from. + if request.operation == Operation::Update && source == SourceChoice::Request && !remote_grant { bail!( "Scoop updates are not supported by the broker because Scoop updates an app from the bucket recorded at install, not from the requested bucket" ); @@ -103,12 +133,12 @@ fn validate_scoop_request(request: &PackageRequest, remote_grant: bool) -> anyho if request.options.scope == Some(Scope::Machine) { bail!("Scoop machine/global scope is not supported by the broker"); } - if crate::evaluator::effective_execution_elevation(request) == Elevation::Elevated { + if elevation == Elevation::Elevated { bail!( "Scoop elevated execution is not supported by the broker because scoop.ps1 is resolved from the target user profile" ); } - if !uses_default_source("Scoop", request)? && request.source.name.trim().is_empty() { + if !uses_default_source("Scoop", request, source)? && request.source.name.trim().is_empty() { bail!("Scoop package source name is required"); } if request.package.version.is_some() { @@ -149,8 +179,12 @@ fn validate_scoop_request(request: &PackageRequest, remote_grant: bool) -> anyho Ok(()) } -fn scoop_package_ref(request: &PackageRequest) -> anyhow::Result { - let source = request.source.name.as_str(); +fn scoop_package_ref(request: &PackageRequest, source: SourceChoice) -> anyhow::Result { + // A request that leaves the source to Scoop names no bucket, and Scoop looks its package id up in its buckets. + let source = match source { + SourceChoice::Request => request.source.name.as_str(), + SourceChoice::Manager => "", + }; let id = request.package.id.0.as_str(); validate_script_argument(source)?; validate_script_argument(id)?; @@ -172,7 +206,7 @@ fn scoop_package_ref(request: &PackageRequest) -> anyhow::Result { return Ok(id.to_owned()); } - // An update or uninstall without a bucket acts on the installed app by name. + // A command without a bucket names the app alone. if !source.is_empty() { validate_scoop_name("bucket name", source)?; } @@ -428,6 +462,40 @@ mod tests { } } + /// The command of `operation` on `id` for a request that leaves the bucket to Scoop. + fn build_without_bucket(operation: Operation, id: &str) -> anyhow::Result> { + let mut request = make_request(); + request.operation = operation; + request.source = RequestSource { + name: String::new(), + url: None, + }; + request.package.id = PackageIdentifier::from(id.to_owned()); + build_scoop_command_as(&request, SourceChoice::Manager, Elevation::Standard) + } + + // oracle: contract Devolutions/now-libraries@3014fcbb899d:policies/CONTRACT.wire.md §bypass-reading + #[test] + fn a_request_that_leaves_the_bucket_to_scoop_names_one_app_by_its_package_id() { + for operation in [Operation::Install, Operation::Update, Operation::Uninstall] { + for id in ["7zip", "git-with_openssh", "python3.12"] { + build_without_bucket(operation, id).unwrap_or_else(|error| panic!("{operation:?} {id}: {error:#}")); + } + for id in [ + "", + "extras/7zip", + "7zip@24.09", + "7zip.json", + "7zip.JSON", + "7zip.", + "a...b", + "https://example.test/app.json", + ] { + assert!(build_without_bucket(operation, id).is_err(), "{operation:?} {id}"); + } + } + } + // oracle: contract crates/agent-channel-proto/CONTRACT.package-management.md §operations #[test] fn remote_grant_update_runs_scoop_update() { diff --git a/crates/now-package-broker/src/command_builder/vcpkg.rs b/crates/now-package-broker/src/command_builder/vcpkg.rs index 1260e6977..ac8f7b972 100644 --- a/crates/now-package-broker/src/command_builder/vcpkg.rs +++ b/crates/now-package-broker/src/command_builder/vcpkg.rs @@ -12,11 +12,24 @@ use anyhow::bail; use now_policy_api::{Elevation, Operation, PackageRequest, Scope}; -use super::uses_default_source; +use super::{SourceChoice, uses_default_source}; /// Build the vcpkg command line from a validated request. pub fn build_vcpkg_command(request: &PackageRequest) -> anyhow::Result> { - validate_vcpkg_request(request)?; + build_vcpkg_command_as( + request, + SourceChoice::Request, + crate::evaluator::effective_execution_elevation(request), + ) +} + +/// Build the command of a run whose token has the elevation `elevation`, on the source that `source` chooses. +pub(crate) fn build_vcpkg_command_as( + request: &PackageRequest, + source: SourceChoice, + elevation: Elevation, +) -> anyhow::Result> { + validate_vcpkg_request(request, source, elevation)?; let operation = match request.operation { Operation::Install => "install", @@ -24,7 +37,11 @@ pub fn build_vcpkg_command(request: &PackageRequest) -> anyhow::Result "remove", }; - let mut command = vec!["vcpkg.exe".to_owned(), operation.to_owned(), package_spec(request)?]; + let mut command = vec![ + "vcpkg.exe".to_owned(), + operation.to_owned(), + package_spec(request, source)?, + ]; match request.operation { Operation::Install => {} @@ -35,17 +52,17 @@ pub fn build_vcpkg_command(request: &PackageRequest) -> anyhow::Result anyhow::Result<()> { +fn validate_vcpkg_request(request: &PackageRequest, source: SourceChoice, elevation: Elevation) -> anyhow::Result<()> { if request.options.scope == Some(Scope::Machine) { bail!("vcpkg machine-scope operations are not supported by the broker"); } - if crate::evaluator::effective_execution_elevation(request) == Elevation::Elevated { + if elevation == Elevation::Elevated { bail!("vcpkg elevated operations are not supported by the broker"); } if request.source.url.is_some() { bail!("vcpkg package sources with URLs are not supported by the broker"); } - if !uses_default_source("vcpkg", request)? && !is_valid_triplet(&request.source.name) { + if !uses_default_source("vcpkg", request, source)? && !is_valid_triplet(&request.source.name) { bail!("vcpkg package source name must be a triplet"); } if request.package.version.is_some() { @@ -82,8 +99,11 @@ fn validate_vcpkg_request(request: &PackageRequest) -> anyhow::Result<()> { Ok(()) } -fn package_spec(request: &PackageRequest) -> anyhow::Result { - let triplet = request.source.name.trim(); +fn package_spec(request: &PackageRequest, source: SourceChoice) -> anyhow::Result { + let triplet = match source { + SourceChoice::Request => request.source.name.trim(), + SourceChoice::Manager => "", + }; let package_id = request.package.id.0.trim(); if package_id.is_empty() { @@ -103,8 +123,14 @@ fn package_spec(request: &PackageRequest) -> anyhow::Result { } Ok(package_id.to_owned()) } else if triplet.is_empty() { - // vcpkg would otherwise act on the default triplet, which may not be the installed one. - bail!("vcpkg package id must carry a triplet when the request has no source"); + match source { + // vcpkg would otherwise act on the default triplet, which may not be the installed one. + SourceChoice::Request => { + bail!("vcpkg package id must carry a triplet when the request has no source") + } + // The request leaves the triplet to vcpkg, which acts on its default one. + SourceChoice::Manager => Ok(package_id.to_owned()), + } } else { Ok(format!("{package_id}:{triplet}")) } @@ -242,6 +268,36 @@ mod tests { // oracle: contract crates/agent-channel-proto/CONTRACT.package-management.md §operations build_vcpkg_command(&request).expect_err("install requires a source"); } + + // The package id of a request that leaves the triplet to vcpkg is still a port spec. + // oracle: contract Devolutions/now-libraries@3014fcbb899d:policies/CONTRACT.wire.md §bypass-reading + // oracle: contract Devolutions/now-libraries@3014fcbb899d:policies/CONTRACT.policy.md §manager-vcpkg + #[test] + fn a_request_that_leaves_the_triplet_to_vcpkg_must_name_a_port_spec() { + for operation in [Operation::Install, Operation::Update, Operation::Uninstall] { + for id in [ + "", + "Zlib", + "-zlib", + "zlib:", + "zlib:x64:windows", + "zlib[]", + "zlib[core", + "zlib --overlay-ports=ports", + ] { + let mut request = make_request(); + request.operation = operation; + request.source.name = String::new(); + request.package.id = PackageIdentifier::from(id.to_owned()); + + assert!( + build_vcpkg_command_as(&request, SourceChoice::Manager, Elevation::Standard).is_err(), + "{operation:?} {id}" + ); + } + } + } + #[test] fn install_appends_source_triplet() { let request = make_request(); diff --git a/crates/now-package-broker/src/command_builder/winget.rs b/crates/now-package-broker/src/command_builder/winget.rs index 8c7eb0b77..196e65057 100644 --- a/crates/now-package-broker/src/command_builder/winget.rs +++ b/crates/now-package-broker/src/command_builder/winget.rs @@ -4,15 +4,64 @@ use anyhow::bail; use now_policy_api::{Architecture, ManagerName, Operation, PackageRequest, Scope}; use super::{ - set_if_specified, set_if_true, uses_default_source, validate_batch_arguments, validate_package_version, - validate_source_name, + SourceChoice, set_if_specified, set_if_true, uses_default_source, validate_batch_arguments, + validate_package_version, validate_source_name, }; /// Build the WinGet command line from a validated request. /// /// Returns the command as a list of arguments (first element is the executable). pub fn build_winget_command(request: &PackageRequest) -> anyhow::Result> { - let source = if uses_default_source("WinGet", request)? { + build( + request, + SourceChoice::Request, + None, + PackageAgreements::AfterCustomParameters, + ) +} + +/// Where a WinGet command has `--accept-package-agreements`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum PackageAgreements { + /// After the custom parameters, where one of them can take the option as its value or move it after a `--`. + AfterCustomParameters, + /// Before the custom parameters, as every other option the broker builds. + BeforeCustomParameters, +} + +/// Arguments WinGet hands to the installer it runs. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum InstallerArguments<'a> { + /// Arguments added to the ones WinGet passes to the installer. + Append(&'a str), + /// Arguments replacing the ones WinGet passes to the installer. + Replace(&'a str), +} + +/// Build the WinGet command line of a request that may carry installer arguments, on the source that `source` chooses. +/// +/// Every option the broker builds comes before the custom parameters, so that no custom parameter takes one of them +/// as its value or moves it after a `--`. +pub(crate) fn build_winget_command_with( + request: &PackageRequest, + source: SourceChoice, + installer_arguments: Option>, +) -> anyhow::Result> { + build( + request, + source, + installer_arguments, + PackageAgreements::BeforeCustomParameters, + ) +} + +fn build( + request: &PackageRequest, + source: SourceChoice, + installer_arguments: Option>, + package_agreements: PackageAgreements, +) -> anyhow::Result> { + let source = if uses_default_source("WinGet", request, source)? { None } else { validate_source_name("WinGet", &request.source.name)?; @@ -104,6 +153,28 @@ pub fn build_winget_command(request: &PackageRequest) -> anyhow::Result { + command.push("--custom".to_owned()); + command.push(arguments.to_owned()); + } + Some(InstallerArguments::Replace(arguments)) => { + command.push("--override".to_owned()); + command.push(arguments.to_owned()); + } + None => {} + } + } + + let accepts_package_agreements = matches!(request.operation, Operation::Install | Operation::Update); + if accepts_package_agreements && package_agreements == PackageAgreements::BeforeCustomParameters { + command.push("--accept-package-agreements".to_owned()); + } + // Append any custom parameters. for param in &request.options.custom_parameters { if !param.is_empty() { @@ -111,7 +182,7 @@ pub fn build_winget_command(request: &PackageRequest) -> anyhow::Result Cow<'_, str> { if name.is_empty() || name.contains('.') { Cow::Borrowed(name) @@ -86,7 +86,20 @@ pub(crate) fn is_acceptable_kill_process_name(name: &str) -> bool { .get(name.len() - EXTENSION.len()..) .is_some_and(|extension| extension.eq_ignore_ascii_case(EXTENSION)); - has_executable_extension + has_executable_extension && has_only_literal_characters(name) +} + +/// Whether `name` is an image name that `taskkill /IM` matches literally, whatever its extension. +/// +/// It is [`is_acceptable_kill_process_name`] without the `.exe` requirement, and it refuses a name that starts with +/// `-`, which `taskkill` reads as one of its switches. +pub(crate) fn is_literal_kill_process_name(name: &str) -> bool { + has_only_literal_characters(name) && !name.starts_with('-') +} + +/// Whether `name` is not empty and has no wildcard, path, drive or stream separator, quote or control character. +fn has_only_literal_characters(name: &str) -> bool { + !name.is_empty() && !name .chars() .any(|character| character.is_control() || matches!(character, '*' | '?' | '\\' | '/' | ':' | '"' | '\'')) @@ -132,6 +145,54 @@ mod tests { } } + #[test] + fn literal_kill_targets_need_no_executable_extension() { + // oracle: mutant Requiring the `.exe` extension of a literal kill target. + for name in ["Mystify.scr", "helper.com", "notepad", "Code.exe", "chrome."] { + assert!(is_literal_kill_process_name(name), "{name}"); + } + } + + #[test] + fn wildcard_path_and_malformed_names_are_no_literal_kill_targets() { + // oracle: mutant Allowing wildcard, path or quoted names as literal kill targets. + for name in [ + "", + "*", + "*.scr", + "a?.scr", + r"C:\Windows\Mystify.scr", + "dir/Mystify.scr", + "C:Mystify.scr", + "\"Mystify.scr\"", + "Mysti'fy.scr", + "Mystify\n.scr", + "Mystify\u{0}.scr", + ] { + assert!(!is_literal_kill_process_name(name), "{name:?}"); + } + } + + #[test] + fn a_name_that_starts_with_a_hyphen_is_no_literal_kill_target() { + // oracle: mutant Allowing as a literal kill target a name that `taskkill` reads as one of its switches. + for name in ["-T", "-t", "-IM", "-tool.exe", "-"] { + assert!(!is_literal_kill_process_name(name), "{name}"); + } + } + + #[test] + fn a_hyphen_after_the_first_character_keeps_a_literal_kill_target() { + // oracle: mutant Refusing a literal kill target for a hyphen after its first character. + assert!(is_literal_kill_process_name("my-tool.exe")); + } + + #[test] + fn a_name_that_starts_with_a_hyphen_stays_acceptable_where_only_executables_are_stopped() { + // oracle: mutant Changing which names that end in `.exe` are acceptable where only executables are stopped. + assert!(is_acceptable_kill_process_name("-tool.exe")); + } + #[test] fn names_without_an_extension_get_exe_appended() { // oracle: mutant Leaving extensionless kill targets unnormalized. diff --git a/crates/now-package-broker/src/evaluator/mod.rs b/crates/now-package-broker/src/evaluator/mod.rs index 32bb989b7..4874de527 100644 --- a/crates/now-package-broker/src/evaluator/mod.rs +++ b/crates/now-package-broker/src/evaluator/mod.rs @@ -83,7 +83,9 @@ mod matching; mod version; mod wildcard; -pub(crate) use builtin_rules::{is_acceptable_kill_process_name, normalize_kill_process_name}; +pub(crate) use builtin_rules::{ + is_acceptable_kill_process_name, is_literal_kill_process_name, normalize_kill_process_name, +}; pub(crate) use custom_options::{custom_options, has_non_ascii_option_name}; pub(crate) use wildcard::has_powershell_wildcard_syntax; diff --git a/crates/now-package-broker/src/event_channel.rs b/crates/now-package-broker/src/event_channel.rs index 1c2c09689..a438f9c9b 100644 --- a/crates/now-package-broker/src/event_channel.rs +++ b/crates/now-package-broker/src/event_channel.rs @@ -263,8 +263,11 @@ impl OperationEventSink { } /// Queue a `StatusUpdated` notification frame. + /// + /// Never panics: an operation may be ended while a panic unwinds, where a second panic aborts the process. + /// A queue whose lock is poisoned is used as it is. pub fn status_updated(&self) { - let mut state = self.queue.state.lock().expect("event queue lock poisoned"); + let mut state = self.queue.state.lock().unwrap_or_else(PoisonError::into_inner); if state.closed { return; } @@ -277,8 +280,10 @@ impl OperationEventSink { /// /// Flushes buffered incomplete UTF-8 sequences first, so `Finish` is always /// the last frame. + /// + /// Never panics, for the reason [`Self::status_updated`] does not. pub fn finish(&self) { - let mut state = self.queue.state.lock().expect("event queue lock poisoned"); + let mut state = self.queue.state.lock().unwrap_or_else(PoisonError::into_inner); if state.closed { return; } @@ -508,15 +513,39 @@ fn overflow_frame(stream: OutputStream, bytes_skipped: u32) -> EventFrame { } } +/// The protocol version an event channel announces in its `Hello` frame. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ChannelVersion { + /// The version of the channel of an operation started on a 1.x route. + V1_0, + /// The version of the channel of an operation started by a 2.0 request ([§frames]). + /// + /// [§frames]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#frames + V2_0, +} + +impl ChannelVersion { + /// The major and minor numbers of the version. + #[cfg(windows)] + fn numbers(self) -> (u16, u16) { + use now_policy_api::event_channel::{EVENT_CHANNEL_VERSION_MAJOR, EVENT_CHANNEL_VERSION_MINOR}; + + match self { + Self::V1_0 => (EVENT_CHANNEL_VERSION_MAJOR, EVENT_CHANNEL_VERSION_MINOR), + Self::V2_0 => (2, 0), + } + } +} + #[cfg(windows)] -pub use windows_channel::open_operation_channel; +pub use windows_channel::{open_operation_channel, open_operation_channel_announcing}; #[cfg(windows)] mod windows_channel { use std::time::Duration; use anyhow::Context as _; - use now_policy_api::event_channel::{EVENT_CHANNEL_VERSION_MAJOR, EVENT_CHANNEL_VERSION_MINOR, EventFrame}; + use now_policy_api::event_channel::EventFrame; use now_policy_api::{EventChannel, EventChannelKind}; use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _}; use tokio::net::windows::named_pipe::{NamedPipeServer, ServerOptions}; @@ -529,7 +558,7 @@ mod windows_channel { use windows::Win32::Security::Authorization::SET_ACCESS; use windows::Win32::Storage::FileSystem::FILE_GENERIC_READ; - use super::{OperationEventSink, operation_pipe_name}; + use super::{ChannelVersion, OperationEventSink, operation_pipe_name}; /// How long the channel stays available for a late client connection after the /// operation finished without any client having connected. @@ -555,12 +584,24 @@ mod windows_channel { pub fn open_operation_channel( operation_id: &str, client_sid: &Sid, + ) -> anyhow::Result<(OperationEventSink, EventChannel)> { + open_operation_channel_announcing(ChannelVersion::V1_0, operation_id, client_sid) + } + + /// Create the event channel for an operation, whose `Hello` frame announces `version`. + /// + /// It is otherwise [`open_operation_channel`], except that SYSTEM and Administrators open the pipe of a channel + /// announcing 2.0 for reading only, as the client user does. + pub fn open_operation_channel_announcing( + version: ChannelVersion, + operation_id: &str, + client_sid: &Sid, ) -> anyhow::Result<(OperationEventSink, EventChannel)> { let sink = OperationEventSink::new(); let pipe_name = operation_pipe_name(operation_id); let pipe_path = format!(r"\\.\pipe\{pipe_name}"); - let security_attributes = build_channel_security_attributes(client_sid) + let security_attributes = build_channel_security_attributes(version, client_sid) .context("failed to build event channel security attributes")?; // SAFETY: `create_with_security_attributes_raw` requires a pointer to a valid @@ -588,14 +629,19 @@ mod windows_channel { let writer_sink = sink.clone(); let operation_id = operation_id.to_owned(); tokio::spawn(async move { - run_channel(server, writer_sink, &operation_id).await; + run_channel(version, server, writer_sink, &operation_id).await; }); Ok((sink, descriptor)) } /// Serve one client connection on the operation's event pipe, best-effort. - async fn run_channel(server: NamedPipeServer, sink: OperationEventSink, operation_id: &str) { + async fn run_channel( + version: ChannelVersion, + server: NamedPipeServer, + sink: OperationEventSink, + operation_id: &str, + ) { // Wait for a client; once the operation finishes without one, linger only // for a bounded grace period so late clients can still fetch the frames. let connected = tokio::select! { @@ -615,9 +661,10 @@ mod windows_channel { debug!(operation_id, "Client connected to the event channel"); let mut server = server; + let (version_major, version_minor) = version.numbers(); let hello = EventFrame::Hello { - version_major: EVENT_CHANNEL_VERSION_MAJOR, - version_minor: EVENT_CHANNEL_VERSION_MINOR, + version_major, + version_minor, }; if let Err(error) = write_frame(&mut server, &hello).await { sink.abandon(); @@ -678,27 +725,48 @@ mod windows_channel { Ok(()) } - /// Security descriptor for a per-operation event pipe: - /// - SYSTEM: full control - /// - Administrators: full control + /// The access the event pipe of an operation grants, when its channel announces `version`: + /// - SYSTEM and Administrators: read on a channel that announces 2.0 ([§event-channel]), and full control on + /// one that announces 1.0, which 1.x clients may depend on /// - requesting client user: read (the channel is one-way, server to client) - fn build_channel_security_attributes( + /// + /// The broker's own end is the handle that created the pipe, whose access these entries do not decide. + /// + /// [§event-channel]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#event-channel + pub(super) fn channel_access_entries( + version: ChannelVersion, client_sid: &Sid, - ) -> anyhow::Result { + ) -> anyhow::Result<[ExplicitAccess; 3]> { let system_sid = Sid::from_well_known(Security::WinLocalSystemSid, None).context("failed to create SYSTEM SID")?; let admins_sid = Sid::from_well_known(Security::WinBuiltinAdministratorsSid, None) .context("failed to create Administrators SID")?; - let entries = [ + // UNTESTED: A process of the local system or of an elevated member of the Administrators group opens the pipe + // of a 2.0 operation for reading, and no entry grants it write access to the data of the pipe. + // Full control would let those two principals write to the channel. + // The entries do not decide what the owner of the pipe can do: it keeps the right to read and to change the + // DACL. + // The tests read these entries and open the pipe as the user that runs them only; when changing the entries + // or how the descriptor is built from them, open such a pipe for reading and for writing from a process of + // each of the two principals. + // + // Full control is for the version existing 1.x clients use, and no other: a version added to the type gets + // its access decided here. + let privileged_access = match version { + ChannelVersion::V1_0 => GENERIC_ALL.0, + ChannelVersion::V2_0 => FILE_GENERIC_READ.0, + }; + + Ok([ ExplicitAccess { - access_permissions: GENERIC_ALL.0, + access_permissions: privileged_access, access_mode: SET_ACCESS, inheritance: Security::ACE_FLAGS(0), trustee: Trustee::Sid(system_sid), }, ExplicitAccess { - access_permissions: GENERIC_ALL.0, + access_permissions: privileged_access, access_mode: SET_ACCESS, inheritance: Security::ACE_FLAGS(0), trustee: Trustee::Sid(admins_sid), @@ -709,7 +777,16 @@ mod windows_channel { inheritance: Security::ACE_FLAGS(0), trustee: Trustee::Sid(client_sid.clone()), }, - ]; + ]) + } + + /// Security descriptor for a per-operation event pipe, whose DACL is protected and has the entries of + /// [`channel_access_entries`] only. + fn build_channel_security_attributes( + version: ChannelVersion, + client_sid: &Sid, + ) -> anyhow::Result { + let entries = channel_access_entries(version, client_sid)?; let empty_acl = Acl::new().context("failed to create empty ACL")?; let dacl = empty_acl.set_entries(&entries).context("failed to set ACL entries")?; @@ -1057,6 +1134,25 @@ mod tests { assert_eq!(sink.next_frame().await, None); } + + // oracle: mutant panicking in a status update or a finish on a poisoned queue lock, which aborts the broker when an operation is ended while a panic unwinds + #[test] + fn a_status_update_and_a_finish_close_a_queue_whose_lock_is_poisoned() { + let sink = OperationEventSink::new(); + let poisoner = sink.clone(); + std::thread::spawn(move || { + let _state = poisoner.queue.state.lock().expect("lock the queue"); + panic!("poison the queue lock"); + }) + .join() + .expect_err("the thread panics"); + assert!(sink.queue.state.is_poisoned()); + + sink.status_updated(); + sink.finish(); + + assert!(sink.queue.finished.is_cancelled()); + } } #[cfg(all(test, windows))] @@ -1126,6 +1222,134 @@ mod pipe_tests { ); } + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §frames + #[tokio::test] + async fn the_channel_of_a_2_0_operation_announces_version_2_0() { + let operation_id = test_operation_id("hello-2-0"); + let (sink, descriptor) = + open_operation_channel_announcing(ChannelVersion::V2_0, &operation_id, ¤t_user_sid()) + .expect("open channel"); + + let mut client = tokio::net::windows::named_pipe::ClientOptions::new() + .write(false) + .open(format!(r"\\.\pipe\{}", descriptor.path)) + .expect("connect to event channel pipe"); + let mut frame = [0u8; 10]; + client.read_exact(&mut frame).await.expect("first frame"); + sink.finish(); + + assert_eq!( + frame, + [ + 0x04, 0x00, 0x00, 0x00, // Body size. + 0x00, 0x00, // HELLO. + 0x02, 0x00, // Major version. + 0x00, 0x00, // Minor version. + ] + ); + } + + /// Checks that the pipe of a channel announcing `version` grants the local system and Administrators the access + /// `privileged_access`, the client user read access, and nobody else anything. + fn assert_channel_access(version: ChannelVersion, privileged_access: u32) { + use win_api_wrappers::security::acl::Trustee; + use windows::Win32::Security::Authorization::SET_ACCESS; + use windows::Win32::Security::{WinBuiltinAdministratorsSid, WinLocalSystemSid}; + use windows::Win32::Storage::FileSystem::FILE_GENERIC_READ; + + let client = current_user_sid(); + + let entries = windows_channel::channel_access_entries(version, &client).expect("entries"); + + assert!( + entries.iter().all(|entry| entry.access_mode == SET_ACCESS), + "{entries:?}" + ); + let granted: Vec<(Sid, u32)> = entries + .into_iter() + .map(|entry| { + let Trustee::Sid(sid) = entry.trustee; + (sid, entry.access_permissions) + }) + .collect(); + let expected = [ + ( + Sid::from_well_known(WinLocalSystemSid, None).expect("local system"), + privileged_access, + ), + ( + Sid::from_well_known(WinBuiltinAdministratorsSid, None).expect("Administrators"), + privileged_access, + ), + (client, FILE_GENERIC_READ.0), + ]; + assert_eq!(granted.len(), expected.len(), "{granted:?}"); + for principal in &expected { + assert!(granted.contains(principal), "{principal:?} is not in {granted:?}"); + } + } + + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §event-channel + #[test] + fn the_pipe_of_a_2_0_operation_grants_its_three_principals_read_access_and_no_other() { + assert_channel_access( + ChannelVersion::V2_0, + windows::Win32::Storage::FileSystem::FILE_GENERIC_READ.0, + ); + } + + // oracle: mutant narrowing the access to the pipe of a 1.x operation, which 1.x clients may depend on + #[test] + fn the_pipe_of_a_1_x_operation_grants_the_local_system_and_administrators_full_control() { + assert_channel_access(ChannelVersion::V1_0, windows::Win32::Foundation::GENERIC_ALL.0); + } + + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §event-channel + #[tokio::test] + async fn the_user_of_a_2_0_operation_opens_its_pipe_for_reading_and_never_for_writing() { + use tokio::net::windows::named_pipe::ClientOptions; + + let operation_id = test_operation_id("read-only-2-0"); + let (sink, descriptor) = + open_operation_channel_announcing(ChannelVersion::V2_0, &operation_id, ¤t_user_sid()) + .expect("open channel"); + let path = format!(r"\\.\pipe\{}", descriptor.path); + + for (read, write) in [(true, true), (false, true)] { + let error = ClientOptions::new() + .read(read) + .write(write) + .open(&path) + .expect_err("the pipe opened for writing"); + + assert_eq!( + error.kind(), + std::io::ErrorKind::PermissionDenied, + "read {read}, write {write}: {error}" + ); + } + ClientOptions::new().write(false).open(&path).expect("open for reading"); + sink.finish(); + } + + // oracle: reference now-policy-api 0.7.1 EVENT_CHANNEL_VERSION_MAJOR and EVENT_CHANNEL_VERSION_MINOR + #[tokio::test] + async fn the_channel_of_a_1_x_operation_announces_version_1_0() { + let operation_id = test_operation_id("hello-1-0"); + let (sink, descriptor) = open_operation_channel(&operation_id, ¤t_user_sid()).expect("open channel"); + sink.finish(); + + let frames = read_all_frames(&descriptor.path).await; + + assert_eq!( + frames.first(), + Some(&EventFrame::Hello { + version_major: 1, + version_minor: 0, + }) + ); + } + #[tokio::test] async fn channel_streams_hello_data_status_and_finish() { let operation_id = test_operation_id("stream"); diff --git a/crates/now-package-broker/src/executor/mod.rs b/crates/now-package-broker/src/executor/mod.rs index ddbf6463c..7d00c2af0 100644 --- a/crates/now-package-broker/src/executor/mod.rs +++ b/crates/now-package-broker/src/executor/mod.rs @@ -39,6 +39,29 @@ pub enum TokenElevationCheck { Exact, } +/// Which image names the executor accepts for the kill-before-operation step of a plan. +/// +/// The empty name, and a name with a wildcard, a path, drive or stream separator, a quote or a control character, +/// are never accepted. +/// `taskkill /IM` would not match such a name as one literal image name. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum KillProcessNames { + /// Names that end in `.exe`. + Executables, + /// Names with any extension, or none, that do not start with `-`, which `taskkill` reads as one of its switches. + Literal, +} + +impl KillProcessNames { + /// Whether a plan may name `name` in its kill-before-operation step. + pub fn accepts(self, name: &str) -> bool { + match self { + Self::Executables => crate::evaluator::is_acceptable_kill_process_name(name), + Self::Literal => crate::evaluator::is_literal_kill_process_name(name), + } + } +} + /// Execution context passed from the server to the executor. /// /// Describes the full ordered plan the broker runs on the user's behalf: @@ -48,6 +71,8 @@ pub enum TokenElevationCheck { pub struct ExecutionContext { /// Process image names to terminate before the operation (best-effort). pub kill_processes: Vec, + /// The image names `kill_processes` may hold; the executor refuses a plan that holds another. + pub kill_process_names: KillProcessNames, /// Optional shell command to run before the main command (`cmd.exe /S /C`). /// /// SECURITY: this is a raw command string whose content is not governed by the diff --git a/crates/now-package-broker/src/executor/windows/mod.rs b/crates/now-package-broker/src/executor/windows/mod.rs index 9d73a347b..cf52f80f2 100644 --- a/crates/now-package-broker/src/executor/windows/mod.rs +++ b/crates/now-package-broker/src/executor/windows/mod.rs @@ -385,14 +385,7 @@ fn run_plan( .context("failed to query execution token elevation")?; check_execution_token_elevation(ctx, token_is_elevated)?; - // Defense in depth: the server rejects these names before policy evaluation. - if let Some(process_name) = ctx - .kill_processes - .iter() - .find(|name| !crate::evaluator::is_acceptable_kill_process_name(name)) - { - bail!("unacceptable kill-before-operation process name '{process_name}'"); - } + check_kill_process_names(ctx)?; let vars = win_api_wrappers::utils::environment_block(Some(token), false) .context("failed to load user environment block")?; @@ -619,6 +612,21 @@ fn prepare_main_command_in( Ok(PreparedCommand::raw(command)) } +/// Refuses a plan whose kill-before-operation step holds a name the plan may not hold. +/// +/// Defense in depth: the server rejects, or leaves out of the plan, these names before the plan reaches the executor. +fn check_kill_process_names(ctx: &ExecutionContext) -> anyhow::Result<()> { + if let Some(process_name) = ctx + .kill_processes + .iter() + .find(|name| !ctx.kill_process_names.accepts(name)) + { + bail!("unacceptable kill-before-operation process name '{process_name}'"); + } + + Ok(()) +} + /// `taskkill` command line terminating `process_name` in `session_id`, owned by `user` when given. /// /// `/IM` alone matches processes of every session and user the execution token can reach. @@ -1774,7 +1782,7 @@ mod tests { reject_unsupported_vcpkg_elevation, resolve_trusted_chocolatey_executable, resolve_winget_executable, run_plan, trusted_system32_executable, verify_token_elevation, }; - use crate::executor::{CommandExecutor as _, ExecutionContext, TokenElevationCheck}; + use crate::executor::{CommandExecutor as _, ExecutionContext, KillProcessNames, TokenElevationCheck}; fn grant(permissions: u32, sid: Sid) -> ExplicitAccess { ExplicitAccess { @@ -2933,6 +2941,7 @@ mod tests { // oracle: mutant Running an elevated vcpkg plan or rejecting its demoted user-scope plan. let mut ctx = ExecutionContext { kill_processes: Vec::new(), + kill_process_names: KillProcessNames::Executables, pre_command: None, command: vec![ "vcpkg.exe".to_owned(), @@ -3004,6 +3013,7 @@ mod tests { // oracle: regression Devolutions/devolutions-gateway#1903 let ctx = ExecutionContext { kill_processes: Vec::new(), + kill_process_names: KillProcessNames::Executables, pre_command: Some("echo before".to_owned()), command: vec!["winget.exe".to_owned(), "install".to_owned()], post_command: None, @@ -3032,6 +3042,7 @@ mod tests { // oracle: regression Devolutions/devolutions-gateway#1892 let ctx = ExecutionContext { kill_processes: Vec::new(), + kill_process_names: KillProcessNames::Executables, pre_command: None, command: vec![ r"C:\Windows\System32\cmd.exe".to_owned(), @@ -3071,6 +3082,7 @@ mod tests { fn grant_elevation_is_independent_of_the_manager_scope() { let mut ctx = ExecutionContext { kill_processes: Vec::new(), + kill_process_names: KillProcessNames::Executables, pre_command: None, command: vec!["pwsh.exe".to_owned()], post_command: None, @@ -3107,6 +3119,7 @@ mod tests { // Require the opposite of what the token is: the plan must fail before any process starts. let ctx = ExecutionContext { kill_processes: vec!["now-package-broker-test-never-running.exe".to_owned()], + kill_process_names: KillProcessNames::Executables, pre_command: None, command: vec![ r"C:\Windows\System32\cmd.exe".to_owned(), @@ -3142,6 +3155,7 @@ mod tests { .expect("open current process token"); let ctx = ExecutionContext { kill_processes: vec!["notepad.exe".to_owned()], + kill_process_names: KillProcessNames::Executables, pre_command: None, command: vec![ r"C:\Windows\System32\cmd.exe".to_owned(), @@ -3173,6 +3187,7 @@ mod tests { // oracle: regression Devolutions/devolutions-gateway#2036 discussion_r4192110367 let mut ctx = ExecutionContext { kill_processes: vec!["notepad.exe".to_owned()], + kill_process_names: KillProcessNames::Executables, pre_command: None, command: vec!["winget.exe".to_owned(), "install".to_owned()], post_command: None, @@ -3208,6 +3223,45 @@ mod tests { assert!(error.to_string().contains("non-elevated"), "{error:#}"); } + #[test] + fn a_plan_is_refused_for_a_kill_name_it_may_not_hold() { + // oracle: mutant Checking the kill names of every plan against one rule, whatever rule the plan names. + let mut ctx = ExecutionContext { + kill_processes: vec!["notepad.exe".to_owned(), "Mystify.scr".to_owned()], + kill_process_names: KillProcessNames::Executables, + pre_command: None, + command: vec!["winget.exe".to_owned(), "install".to_owned()], + post_command: None, + effective_user: "DOMAIN\\user".to_owned(), + user_sid: Sid::from_well_known(WinWorldSid, None).expect("well-known Everyone SID"), + session_id: 1, + elevation: Elevation::Standard, + scope: None, + token_elevation_check: TokenElevationCheck::Unchecked, + custom_install_location: None, + capture_output: false, + cancel_token: tokio_util::sync::CancellationToken::new(), + event_sink: None, + }; + + let error = super::check_kill_process_names(&ctx).expect_err("a name without `.exe` among executables"); + assert!(error.to_string().contains("'Mystify.scr'"), "{error:#}"); + + ctx.kill_process_names = KillProcessNames::Literal; + super::check_kill_process_names(&ctx).expect("a literal name without `.exe`"); + + ctx.kill_processes.push("*.scr".to_owned()); + let error = super::check_kill_process_names(&ctx).expect_err("a wildcard among literal names"); + assert!(error.to_string().contains("'*.scr'"), "{error:#}"); + + ctx.kill_processes = vec!["-tool.exe".to_owned()]; + let error = super::check_kill_process_names(&ctx).expect_err("a name that starts with `-` among literal names"); + assert!(error.to_string().contains("'-tool.exe'"), "{error:#}"); + + ctx.kill_process_names = KillProcessNames::Executables; + super::check_kill_process_names(&ctx).expect("a name that starts with `-` among executables"); + } + #[test] fn session_zero_is_never_used_for_execution() { // oracle: mutant Using the service process token for a session-zero request. diff --git a/crates/now-package-broker/src/server/grant.rs b/crates/now-package-broker/src/server/grant.rs index 774931453..da78a7aed 100644 --- a/crates/now-package-broker/src/server/grant.rs +++ b/crates/now-package-broker/src/server/grant.rs @@ -27,7 +27,7 @@ use super::{ use crate::auth::PipeClient; use crate::command_builder::build_remote_grant_command; use crate::evaluator; -use crate::executor::{ExecutionContext, TokenElevationCheck}; +use crate::executor::{ExecutionContext, KillProcessNames, TokenElevationCheck}; use crate::remote_grant::VerifiedCaller; pub(super) const GRANT_ROUTE: &str = "/v1/package-operations/execute-grant"; @@ -137,6 +137,7 @@ pub(super) async fn execute_grant( let mut context = ExecutionContext { kill_processes: Vec::new(), + kill_process_names: KillProcessNames::Executables, pre_command: None, command, post_command: None, diff --git a/crates/now-package-broker/src/server/mod.rs b/crates/now-package-broker/src/server/mod.rs index be82912dc..1f08e06ee 100644 --- a/crates/now-package-broker/src/server/mod.rs +++ b/crates/now-package-broker/src/server/mod.rs @@ -33,7 +33,7 @@ use win_api_wrappers::identity::sid::Sid; use crate::auth::PipeClient; use crate::command_builder::build_command; use crate::evaluator; -use crate::executor::{CommandExecutor, ExecutionContext, TokenElevationCheck}; +use crate::executor::{CommandExecutor, ExecutionContext, KillProcessNames, TokenElevationCheck}; use crate::operation_tracker::OperationTracker; use crate::policy_store::PolicyStore; use crate::remote_grant::RemoteGrantStore; @@ -807,6 +807,7 @@ impl BrokerState { .iter() .map(|process| process.0.clone()) .collect(), + kill_process_names: KillProcessNames::Executables, pre_command: request.options.pre_operation_command.clone(), command: evaluated.command.clone(), post_command: request.options.post_operation_command.clone(), diff --git a/crates/now-package-broker/src/v2/execution.rs b/crates/now-package-broker/src/v2/execution.rs deleted file mode 100644 index 8a5350750..000000000 --- a/crates/now-package-broker/src/v2/execution.rs +++ /dev/null @@ -1 +0,0 @@ -//! Operations started by a 2.0 request. diff --git a/crates/now-package-broker/src/v2/execution/mod.rs b/crates/now-package-broker/src/v2/execution/mod.rs new file mode 100644 index 000000000..22892b6b0 --- /dev/null +++ b/crates/now-package-broker/src/v2/execution/mod.rs @@ -0,0 +1,8 @@ +//! Operations started by a 2.0 request. + +mod operations; +mod owner; +mod plan; + +pub use self::operations::{Caller, Existing, OperationState, Operations, RETENTION, Start, StartedOperation, Status}; +pub use self::owner::Owner; diff --git a/crates/now-package-broker/src/v2/execution/operations.rs b/crates/now-package-broker/src/v2/execution/operations.rs new file mode 100644 index 000000000..d2b02965c --- /dev/null +++ b/crates/now-package-broker/src/v2/execution/operations.rs @@ -0,0 +1,1357 @@ +//! The operations the broker holds for 2.0 requests. + +use std::collections::HashMap; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use chrono::{DateTime, Utc}; +use now_policy_api::v2; +use now_policy_eval::Request; +use parking_lot::Mutex; +use tokio_util::sync::CancellationToken; +use tracing::{info, warn}; +use uuid::Uuid; + +use super::owner::Owner; +use super::plan::plan; +use crate::event_channel::{ChannelVersion, OperationEventSink, open_operation_channel_announcing}; +use crate::executor::{ + CommandExecutor, ExecutionContext, KillProcessNames, ProcessStartedCallback, TokenElevationCheck, is_canceled_error, +}; + +/// How long the broker holds an operation after it ended ([§operations]). +/// +/// [§operations]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#operations +pub const RETENTION: Duration = Duration::from_secs(300); + +/// The status of an operation ([§operations]). +/// +/// [§operations]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#operations +pub type Status = v2::OperationStatus; + +/// What a status response says about an operation ([§status]). +/// +/// [§status]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#status +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct OperationState { + pub status: Status, + /// When the manager process was launched. + pub started_at: Option>, + /// When the operation ended. + pub completed_at: Option>, + /// The exit code of the manager process, when it exited on its own. + pub exit_code: Option, + /// Text for a person. + pub message: Option, +} + +/// The authenticated client process a request came from. +#[derive(Debug, Clone)] +pub struct Caller { + pub owner: Owner, + /// The session of the caller's token, in which the operation runs. + pub session_id: u32, + /// The account name of the caller, for logs. + pub display_name: String, +} + +/// What an execution response says about the operation of its request ([§execute]). +/// +/// [§execute]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#execute +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct StartedOperation { + pub operation_id: String, + /// The status of the operation when this value was made. + pub status: Status, + /// The name of the event channel pipe, absent when the broker could not create it. + pub event_pipe: Option, + /// What the caller of [`Operations::start`] stored with the operation. + pub context: C, +} + +/// The operation the broker already holds for a request id of an owner. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Existing { + /// The request is equal to the one that started the operation. + Replayed(StartedOperation), + /// The request is not equal to the one that started the operation. + Conflict, +} + +/// The outcome of [`Operations::start`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Start { + /// The request started this operation. + Started(StartedOperation), + /// The broker already held an operation for the request id, and started nothing. + Existing(Existing), +} + +/// The operations started by 2.0 requests that the broker holds. +/// +/// `K` is what decides whether two package requests are equal ([§equal-requests]); the caller supplies it because it +/// reads the request's encoding. +/// `C` is what the caller needs to write the response of the request that started an operation again. +/// +/// An operation started on a 1.x route is not held here, so no request served from here names it. +/// +/// [§equal-requests]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#equal-requests +pub struct Operations { + inner: Arc>, +} + +struct Inner { + executor: Arc, + state: Mutex>, +} + +struct State { + /// The operations by their id. + operations: HashMap>, + /// The id of the operation each request id of an owner started. + /// + /// INVARIANT: Every value is a key of `operations`, and every operation has exactly one entry here. + request_ids: HashMap<(Owner, String), String>, +} + +impl State { + /// Returns the operation held for `request_id` and `owner`, and how a request with `request_key` relates to it. + fn existing(&self, owner: &Owner, request_id: &str, request_key: &K) -> Option> { + let operation_id = self.request_ids.get(&(owner.clone(), request_id.to_owned()))?; + let record = self.operations.get(operation_id)?; + + Some(if record.request_key == *request_key { + Existing::Replayed(StartedOperation { + operation_id: operation_id.clone(), + status: record.state.status, + event_pipe: record.event_pipe.clone(), + context: record.context.clone(), + }) + } else { + Existing::Conflict + }) + } +} + +struct Record { + owner: Owner, + request_key: K, + context: C, + event_pipe: Option, + /// The sender of the event channel, absent when the broker could not create it and once the operation ended. + events: Option, + /// Asks the steps of the operation to stop. + cancel: CancellationToken, + state: OperationState, + /// When the operation ended. + ended: Option, +} + +impl Record { + /// Gives the operation the status `status` and tells the event channel. + fn set_status(&mut self, status: Status) { + self.state.status = status; + if let Some(events) = &self.events { + events.status_updated(); + } + } + + /// Ends the operation, unless it has ended: a terminal status never changes. + fn end(&mut self, status: Status, exit_code: Option, message: Option) { + if self.state.status.is_terminal() { + return; + } + + self.state.completed_at = Some(Utc::now()); + self.state.exit_code = exit_code; + self.state.message = message.map(|message| crate::v2::wire::message(&message)); + self.ended = Some(Instant::now()); + self.set_status(status); + // `FINISH` is the last frame, after the frame for the terminal status and the output read before it. + // A terminal status never changes, so the sender has nothing left to send and is given up here. + // The frames it queued then live only as long as the task that writes them to the pipe, where a sender kept + // until the broker stops holding the operation would keep the output no client came to read for that long. + if let Some(events) = self.events.take() { + events.finish(); + } + } +} + +/// Ends its operation `Failed` when dropped while the operation has not ended. +/// +/// The task that runs the steps of an operation holds one. +/// An operation whose task ended without recording an end, as when a step panics, would otherwise keep a status that +/// is not terminal: the broker would hold it for ever, its request id would never be unused again, and its event +/// channel would never get `FINISH`. +struct EndOnDrop { + operations: Operations, + operation_id: String, +} + +impl Drop for EndOnDrop { + fn drop(&mut self) { + // Nothing here may panic: this runs while a panic of the task unwinds, where a second panic aborts the broker. + // The registry lock is never poisoned, and the event sink takes a status update and a finish without + // panicking, even on a queue whose lock a panic poisoned. + // The message is cut to a length that every text has as a message, so the cut does not panic either. + let mut state = self.operations.inner.state.lock(); + if let Some(record) = state.operations.get_mut(&self.operation_id) + && !record.state.status.is_terminal() + { + warn!(operation_id = %self.operation_id, "Operation stopped before its steps reported how it ended"); + let message = "the broker stopped running the operation before it ended".to_owned(); + record.end(Status::Failed, None, Some(message)); + } + } +} + +impl Clone for Operations { + fn clone(&self) -> Self { + Self { + inner: Arc::clone(&self.inner), + } + } +} + +impl Operations +where + K: PartialEq + Send + 'static, + C: Clone + Send + 'static, +{ + /// Returns an empty registry whose operations run on `executor`. + pub fn new(executor: Arc) -> Self { + Self { + inner: Arc::new(Inner { + executor, + state: Mutex::new(State { + operations: HashMap::new(), + request_ids: HashMap::new(), + }), + }), + } + } + + /// Starts the operation of the allowed package request `request` for `caller`. + /// + /// `request_key` decides whether a later request with `request_id` is equal to this one, and `context` comes back + /// with every replay of it. + /// Nothing starts when the broker already holds an operation for `request_id` and the caller's owner. + /// + /// The caller must answer a request that is `NotRunnable` ([§not-runnable]) without calling this. + /// A call takes the request id for the operation it starts, so such a request would get an operation, which ends + /// `Failed` without running a step, where the contract has it start none and leave its id unused. + /// + /// Must be called from a Tokio runtime, on which the operation runs. + /// + /// [§not-runnable]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#not-runnable + pub fn start(&self, caller: &Caller, request_id: &str, request_key: K, request: &Request, context: C) -> Start { + // The plan depends on the request only, so no other request waits for it. + let planned = plan(request); + + // UNTESTED: Requests of one owner with one request id that arrive together start one operation. + // A second operation would run the same package request twice. + // The lookup and the insertion happen under one acquisition of the lock, and no test runs two calls at once; + // when changing this function, keep both under the same acquisition. + let mut state = self.inner.state.lock(); + if let Some(existing) = state.existing(&caller.owner, request_id, &request_key) { + return Start::Existing(existing); + } + + // UNTESTED: No two operations ever get the same id. + // A status or cancel request names an operation by its id alone, so a repeated id would hand one operation's + // state to the owner of another. + // The id is a version 4 UUID, whose 122 random bits make a repeat improbable rather than impossible; when + // changing how ids are made, keep them unique for the life of the broker process at least. + let operation_id = format!("op-{}", Uuid::new_v4()); + let user_sid = caller.owner.user_sid(); + + // The pipe is created while the registry is locked, once the request is known to start an operation. + // A channel opened before the lookup, for a request that then has an operation, could only be closed by + // finishing it, and a finished channel keeps its pipe open for the 60 seconds it gives a late client. + // Creating the pipe waits for no other process. + let (events, event_pipe, channel_error) = + match open_operation_channel_announcing(ChannelVersion::V2_0, &operation_id, user_sid) { + Ok((sink, channel)) => (Some(sink), Some(channel.path), None), + // The operation runs without a channel, and its response names no pipe. + Err(error) => (None, None, Some(error)), + }; + + let cancel = CancellationToken::new(); + let (execution, skipped_kill_processes, failure) = match planned { + Ok(plan) => { + let execution = ExecutionContext { + kill_processes: plan.kill_processes, + kill_process_names: KillProcessNames::Literal, + pre_command: plan.pre_command, + command: plan.command, + post_command: plan.post_command, + effective_user: caller.display_name.clone(), + user_sid: user_sid.clone(), + session_id: caller.session_id, + elevation: plan.elevation, + scope: plan.scope, + // The request states the elevation of its run, which the scope never lowers. + token_elevation_check: TokenElevationCheck::Exact, + custom_install_location: plan.custom_install_location, + capture_output: true, + cancel_token: cancel.clone(), + event_sink: events.clone(), + }; + (Some(execution), plan.skipped_kill_processes, None) + } + Err(error) => (None, Vec::new(), Some(format!("{error:#}"))), + }; + + let mut record = Record { + owner: caller.owner.clone(), + request_key, + context: context.clone(), + event_pipe: event_pipe.clone(), + events, + cancel, + state: OperationState { + status: Status::Starting, + started_at: None, + completed_at: None, + exit_code: None, + message: None, + }, + ended: None, + }; + if let Some(reason) = &failure { + record.end(Status::Failed, None, Some(reason.clone())); + } + + let started = StartedOperation { + operation_id: operation_id.clone(), + status: record.state.status, + event_pipe, + context, + }; + state + .request_ids + .insert((caller.owner.clone(), request_id.to_owned()), operation_id.clone()); + state.operations.insert(operation_id.clone(), record); + drop(state); + + if let Some(error) = channel_error { + warn!(%operation_id, error = format!("{error:#}"), "Failed to create the event channel"); + } + for process in &skipped_kill_processes { + warn!( + %operation_id, + %user_sid, + // UNTESTED: The log holds the name with its control characters escaped. + // The name is the request's and may hold line breaks, which would otherwise forge a log record. + // When changing this field, keep the `?` form or escape the name another way. + ?process, + "Left a process to stop out of the operation, because taskkill cannot take its name as one image name" + ); + } + match &failure { + Some(reason) => { + // The reason may quote a member of the request, so it is logged escaped like the names above. + warn!(%operation_id, %user_sid, error = ?reason, "Operation failed before its first step"); + } + None => info!( + %operation_id, + %user_sid, + effective_user = %caller.display_name, + manager = request.manager.as_str(), + operation = request.operation.as_str(), + "Started an operation" + ), + } + + // The steps run once the broker holds the operation, so that every report of theirs finds it. + if let Some(execution) = execution { + let operations = self.clone(); + let unfinished = EndOnDrop { + operations: self.clone(), + operation_id: operation_id.clone(), + }; + tokio::spawn(async move { + // Dropped after the steps, however the task ends. + let _unfinished = unfinished; + operations.run(operation_id, execution).await; + }); + } + + Start::Started(started) + } + + /// Runs the steps of the operation `operation_id` and records how it ends. + async fn run(self, operation_id: String, execution: ExecutionContext) { + let manager = execution.command.first().cloned().unwrap_or_default(); + + let launched: ProcessStartedCallback = Arc::new({ + let operations = self.clone(); + let operation_id = operation_id.clone(); + move |at| operations.launched(&operation_id, at) + }); + + let (status, exit_code, message) = match self.inner.executor.execute(&execution, Some(launched)).await { + Ok(output) => { + // The executor reports the launch of a process that then exited, even when its callback was not called. + if let Some(at) = output.started_at { + self.launched(&operation_id, at); + } + info!(%operation_id, exit_code = output.exit_code, "Manager process exited"); + if output.exit_code == 0 { + (Status::Completed, Some(0), None) + } else { + let description = crate::executor::describe_exit_code(output.exit_code) + .map(|description| format!(": {description}")) + .unwrap_or_default(); + let message = format!("{manager} exited with code {}{description}", output.exit_code); + (Status::Failed, Some(output.exit_code), Some(message)) + } + } + Err(error) if is_canceled_error(&error) => { + info!(%operation_id, "Operation canceled"); + (Status::Canceled, None, None) + } + Err(error) => { + let reason = format!("{error:#}"); + warn!(%operation_id, error = ?reason, "Operation failed"); + (Status::Failed, None, Some(reason)) + } + }; + + let mut state = self.inner.state.lock(); + if let Some(record) = state.operations.get_mut(&operation_id) { + record.end(status, exit_code, message); + } + } + + /// Records that the manager process of the operation `operation_id` was launched at `at`. + fn launched(&self, operation_id: &str, at: DateTime) { + let mut state = self.inner.state.lock(); + let Some(record) = state.operations.get_mut(operation_id) else { + return; + }; + if record.state.status.is_terminal() || record.state.started_at.is_some() { + return; + } + + record.state.started_at = Some(at); + // An operation asked to cancel stays `Canceling` until it ends. + if record.state.status == Status::Starting { + record.set_status(Status::Running); + } + } + + /// Returns the operation the broker holds for `request_id` and `owner`, if any, and how a request with the key + /// `request_key` relates to it. + /// + /// A request for which this returns a value is answered from it, and is neither evaluated nor started. + /// This reserves nothing: a request that starts no operation leaves its id unused. + pub fn existing(&self, owner: &Owner, request_id: &str, request_key: &K) -> Option> { + self.inner.state.lock().existing(owner, request_id, request_key) + } + + /// Stops holding every operation that ended at least [`RETENTION`] before `now`. + /// + /// The request id of such an operation is unused again. + pub fn evict_expired(&self, now: Instant) { + let mut state = self.inner.state.lock(); + let State { + operations, + request_ids, + } = &mut *state; + operations.retain(|_, record| { + record + .ended + .is_none_or(|ended| now.saturating_duration_since(ended) < RETENTION) + }); + request_ids.retain(|_, operation_id| operations.contains_key(operation_id)); + } + + /// Spawns the task that stops holding ended operations, until `shutdown` is canceled. + /// + /// Must be called from a Tokio runtime. + pub fn spawn_eviction_task(self, shutdown: CancellationToken) { + const INTERVAL: Duration = Duration::from_secs(30); + + tokio::spawn(async move { + loop { + tokio::select! { + () = shutdown.cancelled() => break, + () = tokio::time::sleep(INTERVAL) => self.evict_expired(Instant::now()), + } + } + }); + } + + /// Returns what the broker holds for the operation `operation_id` of `owner`. + /// + /// The operation of another owner is one the broker does not hold. + pub fn status(&self, owner: &Owner, operation_id: &str) -> Option { + let state = self.inner.state.lock(); + state + .operations + .get(operation_id) + .filter(|record| record.owner == *owner) + .map(|record| record.state.clone()) + } + + /// Asks the operation `operation_id` of `owner` to cancel, and returns its status after that ([§cancel]). + /// + /// The operation of another owner is one the broker does not hold. + /// + /// [§cancel]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#cancel + pub fn cancel(&self, owner: &Owner, operation_id: &str) -> Option { + let mut state = self.inner.state.lock(); + let record = state + .operations + .get_mut(operation_id) + .filter(|record| record.owner == *owner)?; + + if !record.state.status.is_terminal() { + if record.state.status != Status::Canceling { + info!(%operation_id, "Operation asked to cancel"); + record.set_status(Status::Canceling); + } + // The executor runs no later step once the token is canceled, and stops the process that is running. + record.cancel.cancel(); + } + + Some(record.state.status) + } +} + +#[cfg(test)] +mod tests { + use anyhow::anyhow; + use async_trait::async_trait; + use tokio::sync::mpsc; + + use super::super::owner::tests::{everyone_sid, system_sid}; + use super::super::plan::tests::winget_install; + use super::*; + use crate::executor::{ExecutionOutput, OperationCanceled}; + + /// What the executor of a test does next for the operation it runs. + enum Step { + /// Reports that the manager process was launched. + Launch(DateTime), + /// The manager process exits on its own. + Exit(i32), + /// A step fails before the manager process exits on its own. + Fail(String), + /// Runs until the operation is canceled. + RunUntilCanceled, + /// The task running the steps panics. + Panic, + } + + /// An executor that records what it was asked to run and does what the test tells it. + struct ScriptedExecutor { + contexts: Mutex>, + steps: tokio::sync::Mutex>, + } + + #[async_trait] + impl CommandExecutor for ScriptedExecutor { + async fn execute( + &self, + ctx: &ExecutionContext, + process_started: Option, + ) -> anyhow::Result { + self.contexts.lock().push(ctx.clone()); + let mut steps = self.steps.lock().await; + loop { + match steps.recv().await.expect("the test dropped its steps") { + Step::Launch(at) => process_started.as_ref().expect("launch callback")(at), + Step::Exit(exit_code) => { + return Ok(ExecutionOutput { + exit_code, + ..ExecutionOutput::default() + }); + } + Step::Fail(message) => return Err(anyhow!(message)), + Step::RunUntilCanceled => { + ctx.cancel_token.cancelled().await; + return Err(OperationCanceled.into()); + } + Step::Panic => panic!("a step panicked, as the test asked"), + } + } + } + } + + struct Fixture { + operations: Operations<&'static str, &'static str>, + executor: Arc, + steps: mpsc::UnboundedSender, + } + + impl Fixture { + fn new() -> Self { + let (steps, receiver) = mpsc::unbounded_channel(); + let executor = Arc::new(ScriptedExecutor { + contexts: Mutex::new(Vec::new()), + steps: tokio::sync::Mutex::new(receiver), + }); + let operations = Operations::new(Arc::clone(&executor) as Arc); + Self { + operations, + executor, + steps, + } + } + + /// Starts an operation for `request`, which the registry must not hold yet. + fn start(&self, caller: &Caller, request_id: &str, request: &Request) -> StartedOperation<&'static str> { + match self.operations.start(caller, request_id, "request", request, "context") { + Start::Started(started) => started, + Start::Existing(existing) => panic!("the broker already held {existing:?}"), + } + } + + fn step(&self, step: Step) { + self.steps.send(step).expect("the executor is gone"); + } + + /// Waits until the operation `operation_id` of `owner` has the status `status`, and returns its state. + async fn wait_for(&self, owner: &Owner, operation_id: &str, status: Status) -> OperationState { + self.wait_until(owner, operation_id, &format!("{status:?}"), |state| { + state.status == status + }) + .await + } + + /// Waits until the state of the operation `operation_id` of `owner` is `expected`, and returns it. + async fn wait_until( + &self, + owner: &Owner, + operation_id: &str, + description: &str, + expected: impl Fn(&OperationState) -> bool, + ) -> OperationState { + let reached = async { + loop { + let state = self.operations.status(owner, operation_id).expect("held operation"); + if expected(&state) { + return state; + } + tokio::task::yield_now().await; + } + }; + tokio::time::timeout(Duration::from_secs(10), reached) + .await + .unwrap_or_else(|_| panic!("the operation never became {description}")) + } + + /// The number of plans the executor was asked to run, once every task that can run has run. + async fn executed_plans(&self) -> usize { + for _ in 0..16 { + tokio::task::yield_now().await; + } + self.executor.contexts.lock().len() + } + } + + fn caller(owner: Owner) -> Caller { + Caller { + owner, + session_id: 3, + display_name: r"CONTOSO\alice".to_owned(), + } + } + + fn alice() -> Caller { + caller(Owner::new(&system_sid(), std::path::Path::new(r"C:\Tools\client.exe"))) + } + + fn at(seconds: i64) -> DateTime { + DateTime::from_timestamp(1_800_000_000 + seconds, 0).expect("timestamp") + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §operations + #[tokio::test] + async fn an_operation_starts_then_runs_then_completes_when_its_manager_exits_with_code_0() { + let fixture = Fixture::new(); + let alice = alice(); + + let started = fixture.start(&alice, "request-1", &winget_install()); + + assert_eq!(started.status, Status::Starting); + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §status + assert_eq!( + fixture.operations.status(&alice.owner, &started.operation_id), + Some(OperationState { + status: Status::Starting, + started_at: None, + completed_at: None, + exit_code: None, + message: None, + }) + ); + + fixture.step(Step::Launch(at(5))); + let running = fixture + .wait_for(&alice.owner, &started.operation_id, Status::Running) + .await; + assert_eq!(running.started_at, Some(at(5))); + assert_eq!((running.completed_at, running.exit_code), (None, None)); + + let before_exit = Utc::now(); + fixture.step(Step::Exit(0)); + let completed = fixture + .wait_for(&alice.owner, &started.operation_id, Status::Completed) + .await; + assert_eq!(completed.started_at, Some(at(5))); + assert_eq!(completed.exit_code, Some(0)); + let completed_at = completed.completed_at.expect("completion time"); + assert!( + before_exit <= completed_at && completed_at <= Utc::now(), + "{completed_at}" + ); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §operations + #[tokio::test] + async fn an_operation_fails_when_its_manager_exits_with_another_code() { + let fixture = Fixture::new(); + let alice = alice(); + let started = fixture.start(&alice, "request-1", &winget_install()); + + fixture.step(Step::Launch(at(5))); + fixture.step(Step::Exit(-1978335212)); + + let failed = fixture + .wait_for(&alice.owner, &started.operation_id, Status::Failed) + .await; + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §status + assert_eq!(failed.exit_code, Some(-1978335212)); + assert_eq!(failed.started_at, Some(at(5))); + assert!(failed.completed_at.is_some()); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §operations + #[tokio::test] + async fn an_operation_whose_manager_never_exits_on_its_own_fails_without_an_exit_code() { + let fixture = Fixture::new(); + let alice = alice(); + let started = fixture.start(&alice, "request-1", &winget_install()); + + fixture.step(Step::Fail("pre-operation command exited with code 1".to_owned())); + + let failed = fixture + .wait_for(&alice.owner, &started.operation_id, Status::Failed) + .await; + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §status + assert_eq!((failed.started_at, failed.exit_code), (None, None)); + assert!(failed.completed_at.is_some()); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §status + #[tokio::test] + async fn a_message_is_at_most_2048_bytes() { + let fixture = Fixture::new(); + let alice = alice(); + let started = fixture.start(&alice, "request-1", &winget_install()); + + // 1500 characters of two bytes each. + fixture.step(Step::Fail("é".repeat(1500))); + + let failed = fixture + .wait_for(&alice.owner, &started.operation_id, Status::Failed) + .await; + let message = failed.message.expect("message"); + assert!(message.as_str().len() <= 2048, "{} bytes", message.as_str().len()); + // oracle: mutant an operation that ends with a long failure keeps no text, or a text that is not its start + assert!( + !message.as_str().is_empty() && "é".repeat(1500).starts_with(message.as_str()), + "{}", + message.as_str() + ); + } + + // oracle: mutant running the plan as another user, in another session, or with a token the request did not ask for + #[tokio::test] + async fn the_executor_runs_the_plan_of_the_request_as_the_caller() { + let fixture = Fixture::new(); + let caller = caller(Owner::new( + &everyone_sid(), + std::path::Path::new(r"C:\Tools\client.exe"), + )); + let mut request = winget_install(); + request.elevation = now_policy_eval::Elevation::Elevated; + request.scope = Some(now_policy_eval::Scope::Machine); + + let started = fixture.start(&caller, "request-1", &request); + fixture.step(Step::Exit(0)); + fixture + .wait_for(&caller.owner, &started.operation_id, Status::Completed) + .await; + + let contexts = fixture.executor.contexts.lock(); + let [context] = contexts.as_slice() else { + panic!("the executor ran {} plans", contexts.len()); + }; + assert_eq!(context.command[..2], ["winget.exe", "install"]); + assert_eq!(context.user_sid, everyone_sid()); + assert_eq!(context.session_id, 3); + assert_eq!(context.elevation, now_policy_api::Elevation::Elevated); + assert_eq!(context.token_elevation_check, TokenElevationCheck::Exact); + // oracle: mutant giving the executor the rule of the 1.x routes, under which it refuses a name the plan kept + assert_eq!(context.kill_process_names, KillProcessNames::Literal); + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §frame-order + assert!(context.capture_output && context.event_sink.is_some()); + } + + /// The response to a request the broker already holds an operation for. + fn replayed(start: Start<&'static str>) -> StartedOperation<&'static str> { + match start { + Start::Existing(Existing::Replayed(replayed)) => replayed, + other => panic!("not a replay: {other:?}"), + } + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §execute + #[tokio::test] + async fn an_equal_request_with_the_same_id_replays_the_first_response_with_the_current_status() { + let fixture = Fixture::new(); + let alice = alice(); + let first = match fixture + .operations + .start(&alice, "request-1", "request", &winget_install(), "first context") + { + Start::Started(started) => started, + Start::Existing(existing) => panic!("the broker already held {existing:?}"), + }; + fixture.step(Step::Launch(at(5))); + fixture + .wait_for(&alice.owner, &first.operation_id, Status::Running) + .await; + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §def-owner + let same_owner = caller(Owner::new(&system_sid(), std::path::Path::new(r"c:\tools\CLIENT.EXE"))); + let expected = StartedOperation { + status: Status::Running, + ..first.clone() + }; + assert_eq!( + fixture.operations.existing(&same_owner.owner, "request-1", &"request"), + Some(Existing::Replayed(expected.clone())) + ); + assert_eq!( + replayed(fixture.operations.start( + &same_owner, + "request-1", + "request", + &winget_install(), + "second context" + )), + expected + ); + + // The broker starts nothing for a replay. + fixture.step(Step::Exit(0)); + fixture + .wait_for(&alice.owner, &first.operation_id, Status::Completed) + .await; + assert_eq!(fixture.executor.contexts.lock().len(), 1); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §execute + #[tokio::test] + async fn an_unequal_request_with_the_same_id_conflicts_and_starts_nothing() { + let fixture = Fixture::new(); + let alice = alice(); + let first = fixture.start(&alice, "request-1", &winget_install()); + + assert_eq!( + fixture + .operations + .existing(&alice.owner, "request-1", &"another request"), + Some(Existing::Conflict) + ); + assert_eq!( + fixture + .operations + .start(&alice, "request-1", "another request", &winget_install(), "context"), + Start::Existing(Existing::Conflict) + ); + + // The conflicting request left the operation and its request as they were. + assert_eq!( + replayed( + fixture + .operations + .start(&alice, "request-1", "request", &winget_install(), "context") + ) + .operation_id, + first.operation_id + ); + fixture.step(Step::Exit(0)); + fixture + .wait_for(&alice.owner, &first.operation_id, Status::Completed) + .await; + assert_eq!(fixture.executor.contexts.lock().len(), 1); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §execute + #[tokio::test] + async fn a_request_that_starts_no_operation_leaves_its_id_unused() { + let fixture = Fixture::new(); + let alice = alice(); + + // A request that ends before an operation starts, as a denied one does, only asks what the broker holds. + assert_eq!( + fixture + .operations + .existing(&alice.owner, "request-1", &"denied request"), + None + ); + + let started = fixture + .operations + .start(&alice, "request-1", "allowed request", &winget_install(), "context"); + assert!(matches!(started, Start::Started(_)), "{started:?}"); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §execute + #[tokio::test] + async fn a_request_id_belongs_to_its_owner() { + let fixture = Fixture::new(); + let alice = alice(); + let other_user = caller(Owner::new( + &everyone_sid(), + std::path::Path::new(r"C:\Tools\client.exe"), + )); + let other_program = caller(Owner::new(&system_sid(), std::path::Path::new(r"C:\Tools\other.exe"))); + + let first = fixture.start(&alice, "request-1", &winget_install()); + + for other in [&other_user, &other_program] { + assert_eq!( + fixture + .operations + .existing(&other.owner, "request-1", &"another request"), + None + ); + let second = fixture.start(other, "request-1", &winget_install()); + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §operations + assert_ne!(second.operation_id, first.operation_id); + } + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §operations + #[tokio::test] + async fn the_operation_of_another_owner_is_one_the_broker_does_not_hold() { + let fixture = Fixture::new(); + let alice = alice(); + let started = fixture.start(&alice, "request-1", &winget_install()); + + for other in [ + Owner::new(&everyone_sid(), std::path::Path::new(r"C:\Tools\client.exe")), + Owner::new(&system_sid(), std::path::Path::new(r"C:\Tools\other.exe")), + ] { + assert_eq!(fixture.operations.status(&other, &started.operation_id), None); + assert_eq!(fixture.operations.cancel(&other, &started.operation_id), None); + } + assert_eq!(fixture.operations.status(&alice.owner, "op-unknown"), None); + assert_eq!(fixture.operations.cancel(&alice.owner, "op-unknown"), None); + + // The cancel requests of the other owners did nothing to the operation. + let state = fixture.operations.status(&alice.owner, &started.operation_id); + assert_eq!(state.map(|state| state.status), Some(Status::Starting)); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §cancel + #[tokio::test] + async fn a_cancel_request_makes_an_operation_canceling_until_the_broker_has_stopped_it() { + let fixture = Fixture::new(); + let alice = alice(); + let started = fixture.start(&alice, "request-1", &winget_install()); + fixture.step(Step::Launch(at(5))); + fixture + .wait_for(&alice.owner, &started.operation_id, Status::Running) + .await; + fixture.step(Step::RunUntilCanceled); + + assert_eq!( + fixture.operations.cancel(&alice.owner, &started.operation_id), + Some(Status::Canceling) + ); + let canceling = fixture.operations.status(&alice.owner, &started.operation_id); + assert_eq!(canceling.map(|state| state.status), Some(Status::Canceling)); + // Sending the cancel request again has no other effect. + assert_eq!( + fixture.operations.cancel(&alice.owner, &started.operation_id), + Some(Status::Canceling) + ); + + let canceled = fixture + .wait_for(&alice.owner, &started.operation_id, Status::Canceled) + .await; + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §status + assert_eq!((canceled.started_at, canceled.exit_code), (Some(at(5)), None)); + assert!(canceled.completed_at.is_some()); + assert_eq!( + fixture.operations.cancel(&alice.owner, &started.operation_id), + Some(Status::Canceled) + ); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §operations + #[tokio::test] + async fn a_canceling_operation_never_becomes_running_and_ends_as_the_exit_of_its_manager_decides() { + let fixture = Fixture::new(); + let alice = alice(); + let started = fixture.start(&alice, "request-1", &winget_install()); + + assert_eq!( + fixture.operations.cancel(&alice.owner, &started.operation_id), + Some(Status::Canceling) + ); + // The manager process was launched before the broker could stop the operation. + fixture.step(Step::Launch(at(5))); + let launched = fixture + .wait_until(&alice.owner, &started.operation_id, "launched", |state| { + state.started_at.is_some() + }) + .await; + assert_eq!(launched.status, Status::Canceling); + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §cancel + fixture.step(Step::Exit(3)); + let failed = fixture + .wait_for(&alice.owner, &started.operation_id, Status::Failed) + .await; + assert_eq!(failed.exit_code, Some(3)); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §cancel + #[tokio::test] + async fn a_cancel_request_for_an_ended_operation_returns_its_terminal_status_and_changes_nothing() { + let fixture = Fixture::new(); + let alice = alice(); + let started = fixture.start(&alice, "request-1", &winget_install()); + fixture.step(Step::Exit(0)); + let completed = fixture + .wait_for(&alice.owner, &started.operation_id, Status::Completed) + .await; + + assert_eq!( + fixture.operations.cancel(&alice.owner, &started.operation_id), + Some(Status::Completed) + ); + assert_eq!( + fixture.operations.status(&alice.owner, &started.operation_id), + Some(completed) + ); + } + + /// Checks that the operation `started` of `caller` ended `Failed` without running a step. + async fn assert_failed_without_a_step( + fixture: &Fixture, + caller: &Caller, + started: &StartedOperation<&'static str>, + ) { + assert_eq!(started.status, Status::Failed); + let state = fixture + .operations + .status(&caller.owner, &started.operation_id) + .expect("held operation"); + assert_eq!(state.status, Status::Failed); + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §status + assert_eq!((state.started_at, state.exit_code), (None, None)); + assert!(state.completed_at.is_some()); + assert_eq!(fixture.executed_plans().await, 0); + } + + // Such a request is `NotRunnable`, and "the broker runs nothing for the request" even when one gets an operation. + // An operation with `PrePostCommands` whose token would be elevated "runs no step and ends `Failed`". + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §not-runnable + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §operations + #[tokio::test] + async fn pre_post_commands_for_an_elevated_run_end_the_operation_failed_without_a_step() { + use now_policy_eval::{Elevation, PrePostCommands}; + + for (name, commands) in [ + ( + "pre", + PrePostCommands { + pre: Some("echo before".to_owned()), + post: None, + }, + ), + ( + "post", + PrePostCommands { + pre: None, + post: Some("echo after".to_owned()), + }, + ), + ] { + let fixture = Fixture::new(); + let alice = alice(); + let mut request = winget_install(); + request.elevation = Elevation::Elevated; + request.opt_ins.pre_post_commands = Some(commands); + + let started = fixture.start(&alice, name, &request); + + assert_failed_without_a_step(&fixture, &alice, &started).await; + } + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §operations + #[tokio::test] + async fn an_update_from_a_recorded_source_the_broker_has_not_read_ends_failed_without_a_step() { + for request in super::super::plan::tests::updates_from_a_recorded_source() { + let fixture = Fixture::new(); + let alice = alice(); + + let started = fixture.start(&alice, request.manager.as_str(), &request); + + assert_failed_without_a_step(&fixture, &alice, &started).await; + } + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §execute + #[tokio::test] + async fn an_operation_that_ended_without_a_step_is_an_operation_its_request_replays() { + let fixture = Fixture::new(); + let alice = alice(); + let [request, _] = super::super::plan::tests::updates_from_a_recorded_source(); + let started = fixture.start(&alice, "request-1", &request); + + assert_eq!( + replayed( + fixture + .operations + .start(&alice, "request-1", "request", &request, "context") + ), + started + ); + assert_eq!( + fixture.operations.cancel(&alice.owner, &started.operation_id), + Some(Status::Failed) + ); + } + + /// A caller whose user is the one running the tests, which is the only one they can open an event pipe as. + fn current_user() -> Caller { + use win_api_wrappers::process::Process; + use windows::Win32::Security::TOKEN_QUERY; + + let current_user = Process::current_process() + .token(TOKEN_QUERY) + .expect("open current process token") + .sid_and_attributes() + .expect("query token user SID") + .sid; + caller(Owner::new(¤t_user, std::path::Path::new(r"C:\Tools\client.exe"))) + } + + /// Reads the next `N` bytes of the event channel `client` is connected to. + async fn read_frames(client: &mut tokio::net::windows::named_pipe::NamedPipeClient) -> [u8; N] { + use tokio::io::AsyncReadExt as _; + + let mut frames = [0u8; N]; + tokio::time::timeout(Duration::from_secs(10), client.read_exact(&mut frames)) + .await + .expect("the frames in time") + .expect("the frames"); + frames + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §frames + #[tokio::test] + async fn the_event_channel_of_an_operation_announces_version_2_0_and_tells_each_status_change() { + let fixture = Fixture::new(); + let caller = current_user(); + + let started = fixture.start(&caller, "request-1", &winget_install()); + + let pipe = started.event_pipe.expect("event pipe"); + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §execute + assert!( + (1..=256).contains(&pipe.len()) + && pipe + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-')), + "{pipe}" + ); + let mut client = tokio::net::windows::named_pipe::ClientOptions::new() + .write(false) + .open(format!(r"\\.\pipe\{pipe}")) + .expect("connect to the event channel pipe"); + fixture.step(Step::Launch(at(5))); + fixture.step(Step::Exit(0)); + let frames: [u8; 28] = read_frames(&mut client).await; + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §frame-order + assert_eq!( + frames, + [ + 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, // HELLO, version 2.0. + 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, // STATUS_UPDATED, for `Running`. + 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, // STATUS_UPDATED, for `Completed`. + 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, // FINISH. + ] + ); + } + + // The channel closes "when no connection it serves has opened 60 seconds after the operation's status became + // terminal", so a connection that opens sooner is served. + // oracle: contract Devolutions/now-libraries@09d6488736cf:policies/CONTRACT.wire.md §event-channel + #[tokio::test] + async fn a_client_that_connects_after_its_operation_ended_reads_the_frames_of_the_operation() { + let fixture = Fixture::new(); + let caller = current_user(); + let started = fixture.start(&caller, "request-1", &winget_install()); + let pipe = started.event_pipe.as_deref().expect("event pipe"); + + fixture.step(Step::Exit(0)); + fixture + .wait_for(&caller.owner, &started.operation_id, Status::Completed) + .await; + let mut client = tokio::net::windows::named_pipe::ClientOptions::new() + .write(false) + .open(format!(r"\\.\pipe\{pipe}")) + .expect("connect to the event channel pipe"); + + // oracle: contract Devolutions/now-libraries@09d6488736cf:policies/CONTRACT.wire.md §frame-order + assert_eq!( + read_frames(&mut client).await, + [ + 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, // HELLO, version 2.0. + 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, // STATUS_UPDATED, for `Completed`. + 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, // FINISH. + ] + ); + } + + // An operation whose manager process did not exit with code 0 and that no cancel request ended "ended otherwise". + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §operations + #[tokio::test] + async fn an_operation_whose_steps_stop_without_an_end_fails_and_is_held_no_longer_than_another() { + let fixture = Fixture::new(); + let caller = current_user(); + let started = fixture.start(&caller, "request-1", &winget_install()); + let pipe = started.event_pipe.as_deref().expect("event pipe"); + let mut client = tokio::net::windows::named_pipe::ClientOptions::new() + .write(false) + .open(format!(r"\\.\pipe\{pipe}")) + .expect("connect to the event channel pipe"); + + fixture.step(Step::Panic); + + let failed = fixture + .wait_for(&caller.owner, &started.operation_id, Status::Failed) + .await; + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §status + assert_eq!((failed.started_at, failed.exit_code), (None, None)); + assert!(failed.completed_at.is_some()); + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §frame-order + assert_eq!( + read_frames(&mut client).await, + [ + 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, // HELLO, version 2.0. + 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, // STATUS_UPDATED, for `Failed`. + 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, // FINISH. + ] + ); + + // The contract states only the least time an ended operation is held, so the time itself is the broker's. + let after = Instant::now(); + fixture.operations.evict_expired(after + RETENTION); + assert_eq!(fixture.operations.status(&caller.owner, &started.operation_id), None); + assert_eq!( + fixture.operations.existing(&caller.owner, "request-1", &"request"), + None + ); + } + + /// Whether the registry of `fixture` holds the sender of the event channel of the operation `operation_id`. + fn holds_event_sender(fixture: &Fixture, operation_id: &str) -> bool { + let state = fixture.operations.inner.state.lock(); + let record = state.operations.get(operation_id).expect("held operation"); + record.events.is_some() + } + + // oracle: mutant keeping the sender of the event channel of an ended operation for as long as the broker holds the operation + #[tokio::test] + async fn an_ended_operation_releases_the_sender_of_its_event_channel() { + let fixture = Fixture::new(); + let alice = alice(); + let started = fixture.start(&alice, "request-1", &winget_install()); + // The operation has a channel, whose sender the registry holds while the operation may still change. + assert!(started.event_pipe.is_some()); + assert!(holds_event_sender(&fixture, &started.operation_id)); + + fixture.step(Step::Exit(0)); + fixture + .wait_for(&alice.owner, &started.operation_id, Status::Completed) + .await; + + assert!(!holds_event_sender(&fixture, &started.operation_id)); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §operations + #[tokio::test] + async fn an_ended_operation_is_held_for_300_seconds() { + let fixture = Fixture::new(); + let alice = alice(); + let before = Instant::now(); + let ended = fixture.start(&alice, "request-1", &winget_install()); + fixture.step(Step::Exit(0)); + fixture + .wait_for(&alice.owner, &ended.operation_id, Status::Completed) + .await; + let running = fixture.start(&alice, "request-2", &winget_install()); + let after = Instant::now(); + + // The operation ended after `before`, so less than 300 seconds have passed since. + fixture + .operations + .evict_expired(before + Duration::from_secs(300) - Duration::from_nanos(1)); + assert!(fixture.operations.status(&alice.owner, &ended.operation_id).is_some()); + assert_eq!( + replayed( + fixture + .operations + .start(&alice, "request-1", "request", &winget_install(), "context") + ) + .operation_id, + ended.operation_id + ); + + // An operation that has not ended is held however long it runs. + fixture.operations.evict_expired(after + Duration::from_secs(86_400)); + assert!(fixture.operations.status(&alice.owner, &running.operation_id).is_some()); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §operations + #[tokio::test] + async fn an_operation_the_broker_no_longer_holds_frees_its_request_id() { + let fixture = Fixture::new(); + let alice = alice(); + let first = fixture.start(&alice, "request-1", &winget_install()); + fixture.step(Step::Exit(0)); + fixture + .wait_for(&alice.owner, &first.operation_id, Status::Completed) + .await; + let after = Instant::now(); + + // The contract states only the least time an ended operation is held, so the time itself is the broker's. + fixture.operations.evict_expired(after + RETENTION); + + assert_eq!(fixture.operations.status(&alice.owner, &first.operation_id), None); + assert_eq!(fixture.operations.existing(&alice.owner, "request-1", &"request"), None); + // An unequal request with the id starts an operation instead of conflicting. + let second = fixture + .operations + .start(&alice, "request-1", "another request", &winget_install(), "context"); + assert!( + matches!(&second, Start::Started(started) if started.operation_id != first.operation_id), + "{second:?}" + ); + } +} diff --git a/crates/now-package-broker/src/v2/execution/owner.rs b/crates/now-package-broker/src/v2/execution/owner.rs new file mode 100644 index 000000000..4e260e71d --- /dev/null +++ b/crates/now-package-broker/src/v2/execution/owner.rs @@ -0,0 +1,196 @@ +//! Who an operation belongs to. + +use std::hash::{Hash, Hasher}; +use std::os::windows::ffi::OsStrExt as _; +use std::path::Path; + +use win_api_wrappers::identity::sid::Sid; + +/// The owner of an operation ([§def-owner]): the user and the executable of the caller that started it. +/// +/// Two owners are equal when their SIDs are equal and their paths are equal ignoring case ([§text-comparison]). +/// +/// [§def-owner]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#def-owner +/// [§text-comparison]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.policy.md#text-comparison +#[derive(Debug, Clone)] +pub struct Owner { + user_sid: Sid, + /// The code points of the executable path. + /// + /// A path is a sequence of 16-bit units that need not be valid UTF-16; an unpaired surrogate stands for itself. + path: Box<[u32]>, +} + +impl Owner { + /// Returns the owner made of the user `user_sid` and the executable at `executable_path`. + pub fn new(user_sid: &Sid, executable_path: &Path) -> Self { + let path = char::decode_utf16(executable_path.as_os_str().encode_wide()) + .map(|unit| match unit { + Ok(character) => u32::from(character), + Err(unpaired) => u32::from(unpaired.unpaired_surrogate()), + }) + .collect(); + + Self { + user_sid: user_sid.clone(), + path, + } + } + + /// The SID of the user. + pub fn user_sid(&self) -> &Sid { + &self.user_sid + } +} + +impl PartialEq for Owner { + fn eq(&self, other: &Self) -> bool { + // The comparison of two characters is the policy evaluator's, which has the uppercase mappings the contract + // names: the broker has no table of its own, and the mappings of the toolchain are those of another Unicode + // version. + // It replaces each code point on its own, so comparing two paths one code point at a time gives what + // comparing them whole does. + self.user_sid == other.user_sid + && self.path.len() == other.path.len() + && self.path.iter().zip(&other.path).all(|(&left, &right)| { + match (char::from_u32(left), char::from_u32(right)) { + (Some(left), Some(right)) => { + now_policy_eval::eq_ignore_case(left.encode_utf8(&mut [0; 4]), right.encode_utf8(&mut [0; 4])) + } + // An unpaired surrogate is no character: it has no mapping, and is equal to itself only. + _ => left == right, + } + }) + } +} + +impl Eq for Owner {} + +impl Hash for Owner { + fn hash(&self, state: &mut H) { + // Equal owners must hash alike, so the hash covers only what the comparison keeps whatever the case of a + // path: the SID and the number of code points. + // The evaluator exports its comparison and not its mappings, and no mapping made here would agree with it: + // it takes some characters outside ASCII to ASCII letters, as U+0131 to `I` and U+017F to `S`. + // The paths of one user that have one length therefore share a hash, which costs little among the few + // operations that the broker holds for a user. + self.user_sid.hash(state); + self.path.len().hash(state); + } +} + +#[cfg(test)] +pub(super) mod tests { + use windows::Win32::Security::{WinLocalSystemSid, WinWorldSid}; + + use super::*; + + pub(in crate::v2::execution) fn system_sid() -> Sid { + Sid::from_well_known(WinLocalSystemSid, None).expect("local system SID") + } + + pub(in crate::v2::execution) fn everyone_sid() -> Sid { + Sid::from_well_known(WinWorldSid, None).expect("world SID") + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §def-owner + #[test] + fn owners_with_one_sid_and_paths_differing_only_in_case_are_the_same() { + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.policy.md §text-comparison + // `UnicodeData.txt` gives U+0061..U+007A the uppercase mappings U+0041..U+005A, and U+00E9 the mapping U+00C9. + for (left, right) in [ + (r"C:\Program Files\Tool\tool.exe", r"c:\PROGRAM FILES\tool\Tool.EXE"), + (r"C:\Outils\café.exe", r"C:\Outils\CAFÉ.exe"), + ] { + assert_eq!( + Owner::new(&system_sid(), Path::new(left)), + Owner::new(&system_sid(), Path::new(right)), + "{left} and {right}" + ); + } + } + + fn hash_of(owner: &Owner) -> u64 { + use std::hash::{DefaultHasher, Hash as _, Hasher as _}; + + let mut hasher = DefaultHasher::new(); + owner.hash(&mut hasher); + hasher.finish() + } + + // oracle: contract Devolutions/now-libraries@09d6488736cf:policies/CONTRACT.wire.md §def-owner + // oracle: contract Devolutions/now-libraries@09d6488736cf:policies/CONTRACT.policy.md §text-comparison + #[test] + fn owners_whose_paths_are_equal_by_the_simple_uppercase_mappings_of_unicode_16_are_the_same_and_hash_alike() { + for (name, left, right) in [ + // oracle: reference `UnicodeData.txt` of Unicode 16.0.0, the line of 1F80, whose simple uppercase field is 1F88 + ("U+1F80 and U+1F88", "C:\\Tool\\\u{1f80}.exe", "C:\\Tool\\\u{1f88}.exe"), + // oracle: reference `UnicodeData.txt` of Unicode 16.0.0, the line of 0131, whose simple uppercase field is 0049 + ("U+0131 and U+0049", "C:\\Tool\\\u{131}.exe", "C:\\Tool\\I.exe"), + // A character outside the Basic Multilingual Plane, which a path holds as two 16-bit units. + // oracle: reference `UnicodeData.txt` of Unicode 16.0.0, the line of 10428, whose simple uppercase field is 10400 + ( + "U+10428 and U+10400", + "C:\\Tool\\\u{10428}.exe", + "C:\\Tool\\\u{10400}.exe", + ), + ] { + let left = Owner::new(&system_sid(), Path::new(left)); + let right = Owner::new(&system_sid(), Path::new(right)); + + assert_eq!(left, right, "{name}"); + // oracle: reference Rust standard library, the trait `Hash`: "k1 == k2 -> hash(k1) == hash(k2)" + assert_eq!(hash_of(&left), hash_of(&right), "{name}"); + } + } + + // oracle: mutant comparing an unpaired surrogate of a path as equal to another code point + #[test] + fn an_unpaired_surrogate_of_a_path_is_equal_to_itself_only() { + use std::ffi::OsString; + use std::os::windows::ffi::OsStringExt as _; + + let owner = |unit: u16| { + let path: Vec = r"C:\Tool\" + .encode_utf16() + .chain([unit]) + .chain(".exe".encode_utf16()) + .collect(); + Owner::new(&system_sid(), Path::new(&OsString::from_wide(&path))) + }; + + assert_eq!(owner(0xD800), owner(0xD800)); + // Another unpaired surrogate, and the character that a lossy conversion puts in the place of each. + for other in [0xD801, 0xDC00, 0xFFFD] { + assert_ne!(owner(0xD800), owner(other), "{other:#06X}"); + } + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §def-owner + #[test] + fn owners_with_different_sids_are_different() { + let path = Path::new(r"C:\Program Files\Tool\tool.exe"); + + assert_ne!(Owner::new(&system_sid(), path), Owner::new(&everyone_sid(), path)); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.policy.md §text-comparison + #[test] + fn owners_whose_paths_differ_beyond_simple_uppercase_mappings_are_different() { + // U+00DF has no simple uppercase mapping in `UnicodeData.txt`, and no other normalization applies. + // The paths of the second row have as many code points as each other, and U+006F and U+0069 have the + // mappings U+004F and U+0049. + for (left, right) in [ + (r"C:\Tool\tool.exe", r"C:\Tool\other.exe"), + (r"C:\Tool\tool.exe", r"C:\Tool\toil.exe"), + (r"C:\Tool\straße.exe", r"C:\Tool\STRASSE.exe"), + ("C:\\Tool\\caf\u{e9}.exe", "C:\\Tool\\cafe\u{301}.exe"), + ] { + assert_ne!( + Owner::new(&system_sid(), Path::new(left)), + Owner::new(&system_sid(), Path::new(right)), + "{left} and {right}" + ); + } + } +} diff --git a/crates/now-package-broker/src/v2/execution/plan.rs b/crates/now-package-broker/src/v2/execution/plan.rs new file mode 100644 index 000000000..72d5ac93a --- /dev/null +++ b/crates/now-package-broker/src/v2/execution/plan.rs @@ -0,0 +1,1455 @@ +//! What an operation runs for a 2.0 package request. +//! +//! The command builders take a 1.x request, so a 2.0 request is rewritten as one. +//! The run's elevation, the WinGet installer arguments and the absence of a source, which a 1.x request does not +//! state, are passed beside it. + +use std::path::PathBuf; + +use anyhow::bail; +use chrono::Utc; +use now_policy_api as v1; +use now_policy_eval::{Architecture, Elevation, InstallerArgumentsMode, Manager, Operation, Request, Scope}; + +use crate::command_builder::winget::InstallerArguments; +use crate::command_builder::{SourceChoice, build_command_as}; +use crate::executor::KillProcessNames; + +/// The steps of an operation ([§operations]) and the token they run with. +/// +/// [§operations]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#operations +#[derive(Debug, Clone, PartialEq, Eq)] +pub(super) struct Plan { + /// Image names of the processes to stop first. + pub(super) kill_processes: Vec, + /// The names of `KillBeforeOperation` for which the operation attempts nothing. + pub(super) skipped_kill_processes: Vec, + pub(super) pre_command: Option, + /// The manager command, the executable first. + pub(super) command: Vec, + pub(super) post_command: Option, + /// The elevation of the token every process of the operation runs with. + pub(super) elevation: v1::Elevation, + pub(super) scope: Option, + pub(super) custom_install_location: Option, +} + +/// Returns what the operation of `request` runs. +/// +/// An error means the operation runs no step and ends `Failed` ([§operations]); its text is the reason. +/// It is not a decision: the request was allowed before it got here. +/// +/// [§operations]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#operations +pub(super) fn plan(request: &Request) -> anyhow::Result { + let opt_ins = &request.opt_ins; + + // SECURITY: A `Pre` or `Post` command is a raw command line that no policy rule describes, so it never runs + // with administrator rights, whatever allowed the request. + // Such a request is `NotRunnable` ([§not-runnable]) and is answered so before an operation starts; this refusal + // keeps the broker from running anything for one that gets here all the same. + // + // [§not-runnable]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#not-runnable + // + // UNTESTED: A `NonElevated` request with `PrePostCommands` also runs no step when the token the executor obtains + // is elevated, as when User Account Control is disabled. + // That refusal is the executor's, which compares the token with the plan before the first step, and the tests of + // this module replace the executor. + // When changing the executor or the context it is given, check that it still refuses before it stops a process. + if opt_ins.pre_post_commands.is_some() && request.elevation == Elevation::Elevated { + bail!("pre-operation and post-operation commands never run with an elevated token"); + } + + // The manager updates from the source recorded at install, whatever source the request names. + // The broker reads no such record before the first step, so it cannot tell that each names `Source.Name`. + // A request without a source names none for a record to differ from. + if request.operation == Operation::Update + && request.source.is_some() + && updates_from_recorded_source(request.manager) + { + bail!( + "{} updates a package from the source recorded when it was installed, which the broker has not read", + request.manager.as_str() + ); + } + + let elevation = match request.elevation { + Elevation::NonElevated => v1::Elevation::Standard, + Elevation::Elevated => v1::Elevation::Elevated, + }; + let mut builder_request = builder_request(request, elevation); + // SECURITY: A run as administrator that works for the user alone would write with administrator rights into + // folders that the user's non-elevated processes can change. + // Leaving `Scope` out must not get such a run, so the command of an elevated request without `Scope` is made + // machine-wide where its manager takes a scope, and the request is read with the scope `Machine` ([§reading]). + // + // [§reading]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.policy.md#reading + // + // UNTESTED: An elevated request whose command the broker cannot make machine-wide runs no step, because such a + // request is unreadable: an Uninstall through Windows PowerShell whatever its `Scope`, and a request without + // `Scope` under a manager whose commands work for the user unless they are told otherwise. + // Nothing here refuses it: an Uninstall through Windows PowerShell, for one, gets a plan whose command names no + // scope. + // The refusal is the caller's, which has to read a request before it plans the operation, and the tests of this + // module make no such reading. + // When changing how a request gets here, check that it was read first. + if is_made_machine_wide(request, &builder_request) { + builder_request.options.scope = Some(v1::Scope::Machine); + } + // SECURITY: An elevated install writes with administrator rights into the folder the request names, and the + // executor verifies that folder only when the plan carries it. + // The plan has no location for a path the broker cannot normalize, as one with a segment that ends with `.`, + // while the command would keep that path as written. + // A request with such a location fails the install location check ([§install-location]) and is denied before an + // operation starts; this refusal keeps the broker from running anything for one that gets here all the same. + // + // [§install-location]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.policy.md#install-location + if crate::evaluator::has_unacceptable_install_location(&builder_request) { + bail!("the request does not name exactly one plain local install location"); + } + let installer_arguments = opt_ins + .installer_arguments + .as_ref() + .map(|arguments| match arguments.mode { + InstallerArgumentsMode::Append => InstallerArguments::Append(&arguments.arguments), + InstallerArgumentsMode::Replace => InstallerArguments::Replace(&arguments.arguments), + }); + // A request without a source leaves the choice of source to its manager ([§bypass-reading]). + // + // [§bypass-reading]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#bypass-reading + // + // UNTESTED: An Install or Update without a source runs no step for an elevated run under a manager other than + // WinGet and Chocolatey, because such a request is unreadable. + // Nothing here refuses it: the builders refuse most of these requests, and a .NET tool one gets a plan. + // The refusal is the caller's, which has to read a request without a source as a bypass request before it plans + // the operation, and the tests of this module make no such reading. + // When changing how a request gets here, check that one without a source was read that way first. + let source = match request.source { + Some(_) => SourceChoice::Request, + None => SourceChoice::Manager, + }; + let command = build_command_as(&builder_request, source, elevation, installer_arguments)?; + // "No command the broker builds limits an uninstall to packages installed from `Source.Name`" ([§managers]). + // The script that the PowerShell builders make for an uninstall that names its source fails unless the module + // was installed from that source, so the command of such an uninstall is the one of a request that leaves the + // source to its manager. + // Neither cmdlet takes a repository, so that choice changes nothing else in the script. + // The command above is built first all the same, so that the plan refuses the source names the builders refuse. + // + // [§managers]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.policy.md#managers + let command = if source == SourceChoice::Request + && request.operation == Operation::Uninstall + && matches!(request.manager, Manager::PowerShell | Manager::PowerShell7) + { + build_command_as(&builder_request, SourceChoice::Manager, elevation, installer_arguments)? + } else { + command + }; + + // The executor refuses a whole plan for one name it cannot hand to `taskkill /IM` as one literal image name. + // Such a name has a path, drive or stream separator, a quote or a control character, or starts with `-`, which + // `taskkill` reads as one of its switches. + // Nothing is attempted for it: it is left out of the plan, so the other steps still run, as they do after a + // process could not be stopped, and it is returned beside the plan, as the request spells it, for the caller to + // log. + let (kill_processes, skipped_kill_processes): (Vec, Vec) = opt_ins + .kill_before_operation + .iter() + .flat_map(|kill| &kill.processes) + .cloned() + .partition(|name| KillProcessNames::Literal.accepts(name)); + // A name without `.` stands for the executable of that name, so it is stopped as that name with `.exe`. + let kill_processes = kill_processes + .into_iter() + .map(|name| crate::evaluator::normalize_kill_process_name(&name).into_owned()) + .collect(); + + Ok(Plan { + kill_processes, + skipped_kill_processes, + pre_command: builder_request.options.pre_operation_command.clone(), + command, + post_command: builder_request.options.post_operation_command.clone(), + elevation, + scope: builder_request.options.scope, + custom_install_location: crate::evaluator::custom_install_location(&builder_request).map(PathBuf::from), + }) +} + +/// Whether the broker makes the command of `request` machine-wide ([§manager-winget], [§manager-powershell]). +/// +/// It does so for an elevated request without `Scope`, by naming the machine scope among the options it builds. +/// WinGet takes `--scope` once, so the broker passes none of its own when a custom parameter names that option. +/// `Uninstall-Module` takes no scope. +/// +/// [§manager-winget]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.policy.md#manager-winget +/// [§manager-powershell]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.policy.md#manager-powershell +fn is_made_machine_wide(request: &Request, builder_request: &v1::PackageRequest) -> bool { + if request.elevation != Elevation::Elevated || request.scope.is_some() { + return false; + } + + match request.manager { + Manager::Winget => { + // "An element that is exactly `--` ends the options: no later element names an option" + // ([§manager-winget]), so a request whose only `--scope` comes after one was read with the scope + // `Machine`. + // The reader below follows WinGet instead, which may take a `--` as the value of the option before it and + // read on, so it gets only the custom parameters before the first `--`. + // The two readings are the same for those: a 2.0 custom parameter is never empty, and the builder refuses + // one that starts with `---`. + // A `--` that the contract reads as the value of an option ends this reading too, so the broker may pass + // its own scope although a later custom parameter names one. + // + // [§manager-winget]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.policy.md#manager-winget + // + // UNTESTED: An elevated run never works for the user alone because of a `--scope` that WinGet reads after + // a `--` among the custom parameters. + // Such a request was read with the scope `Machine`, so the rules that allowed it are those of a + // machine-wide run. + // Its command names `--scope` twice, and it matters that WinGet refuses such a command, which only a run + // of WinGet shows. + // When changing which custom parameters are read here, check that a `--scope` that WinGet may read and + // the contract does not is never the only one of a command. + let parameters = &builder_request.options.custom_parameters; + let end_of_options = parameters + .iter() + .position(|parameter| parameter.0 == "--") + .unwrap_or(parameters.len()); + + crate::evaluator::custom_options(v1::ManagerName::Winget, ¶meters[..end_of_options]) + .scopes + .is_empty() + } + Manager::PowerShell => request.operation != Operation::Uninstall, + Manager::PowerShell7 => true, + _ => false, + } +} + +/// Whether `manager` updates a package from the source recorded when it was installed ([§managers]). +/// +/// [§managers]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.policy.md#managers +fn updates_from_recorded_source(manager: Manager) -> bool { + matches!(manager, Manager::Scoop | Manager::PowerShell) +} + +/// Whether the command of `request` must tell its manager that the version it names is a pre-release. +/// +/// A 2.0 request has no member that asks for pre-release versions: it names its version, and that version is the one +/// its command installs. +/// PowerShellGet and PSResourceGet leave pre-releases out of what they find unless told to include them, so a command +/// that names one needs the option to find it. +/// The option is set for these two managers only, because the builders of several others refuse a request that has +/// it. +fn names_pre_release(request: &Request) -> bool { + matches!(request.manager, Manager::PowerShell | Manager::PowerShell7) + && request.package.version.as_deref().is_some_and(is_pre_release) +} + +/// Whether `version` is a version that has a pre-release ([§version-scheme]). +/// +/// [§version-scheme]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.policy.md#version-scheme +fn is_pre_release(version: &str) -> bool { + let version = version.strip_prefix(['v', 'V']).unwrap_or(version); + // The build metadata may have a `-`, which starts no pre-release. + let (version, build_metadata) = version.split_once('+').unwrap_or((version, "")); + let Some((release, pre_release)) = version.split_once('-') else { + return false; + }; + + return release + .split('.') + .all(|component| !component.is_empty() && is_numeric(component)) + && pre_release.split('.').all(|identifier| { + !identifier.is_empty() + && identifier + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-') + && !(is_numeric(identifier) && 1 < identifier.len() && identifier.starts_with('0')) + }) + && build_metadata + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-' || byte == b'.'); + + fn is_numeric(text: &str) -> bool { + text.bytes().all(|byte| byte.is_ascii_digit()) + } +} + +/// Rewrites `request` as the 1.x request the command builders read. +/// +/// The builders read the operation, manager, source, package and options only. +/// The other members describe a 1.x client and its message, and get placeholders. +fn builder_request(request: &Request, elevation: v1::Elevation) -> v1::PackageRequest { + let opt_ins = &request.opt_ins; + let pre_post = opt_ins.pre_post_commands.as_ref(); + + v1::PackageRequest { + request_kind: v1::PackageRequestKind, + request_version: v1::API_VERSION_STR.into(), + request_id: v1::ResourceId::from("2.0"), + created_at: Utc::now(), + operation: match request.operation { + Operation::Install => v1::Operation::Install, + Operation::Update => v1::Operation::Update, + Operation::Uninstall => v1::Operation::Uninstall, + }, + manager: match request.manager { + Manager::Winget => v1::ManagerName::Winget, + Manager::PowerShell => v1::ManagerName::PowerShell, + Manager::PowerShell7 => v1::ManagerName::PowerShell7, + Manager::Apt => v1::ManagerName::Apt, + Manager::Bun => v1::ManagerName::Bun, + Manager::Cargo => v1::ManagerName::Cargo, + Manager::Chocolatey => v1::ManagerName::Chocolatey, + Manager::Dnf => v1::ManagerName::Dnf, + Manager::Dotnet => v1::ManagerName::Dotnet, + Manager::Flatpak => v1::ManagerName::Flatpak, + Manager::Homebrew => v1::ManagerName::Homebrew, + Manager::Npm => v1::ManagerName::Npm, + Manager::Pacman => v1::ManagerName::Pacman, + Manager::Pip => v1::ManagerName::Pip, + Manager::Scoop => v1::ManagerName::Scoop, + Manager::Snap => v1::ManagerName::Snap, + Manager::Vcpkg => v1::ManagerName::Vcpkg, + }, + source: v1::RequestSource { + // The builders do not read the name of a request without a source. + name: request + .source + .as_ref() + .map(|source| source.name.clone()) + .unwrap_or_default(), + url: None, + }, + package: v1::RequestPackage { + id: v1::PackageIdentifier(request.package.id.clone()), + version: request.package.version.clone().map(v1::VersionString), + architecture: request.package.architecture.map(|architecture| match architecture { + Architecture::X86 => v1::Architecture::X86, + Architecture::X64 => v1::Architecture::X64, + Architecture::Arm64 => v1::Architecture::Arm64, + Architecture::Neutral => v1::Architecture::Neutral, + }), + channel: None, + }, + options: v1::RequestOptions { + scope: request.scope.map(|scope| match scope { + Scope::User => v1::Scope::User, + Scope::Machine => v1::Scope::Machine, + }), + interactive: opt_ins.interactive, + skip_hash_check: opt_ins.skip_hash_check, + pre_release: names_pre_release(request), + custom_install_location: opt_ins + .custom_install_location + .as_ref() + .map(|location| location.path.clone()), + custom_parameters: opt_ins + .custom_parameters + .iter() + .flat_map(|parameters| ¶meters.values) + .cloned() + .map(v1::CustomParameterString) + .collect(), + pre_operation_command: pre_post.and_then(|commands| commands.pre.clone()), + post_operation_command: pre_post.and_then(|commands| commands.post.clone()), + kill_before_operation: opt_ins + .kill_before_operation + .iter() + .flat_map(|kill| &kill.processes) + .cloned() + .map(v1::ProcessName) + .collect(), + uninstall_previous: opt_ins.uninstall_previous, + no_upgrade: opt_ins.no_upgrade, + }, + client: v1::ClientContext { + transport: v1::Transport::HttpNamedPipe, + requested_elevation: elevation, + effective_user: String::new(), + client_executable_path: String::new(), + client_version: String::new(), + }, + include_command_preview: false, + capture_output: true, + } +} + +#[cfg(test)] +pub(super) mod tests { + use now_policy_eval::{ + CustomInstallLocation, CustomParameters, InstallerArguments as RequestInstallerArguments, KillBeforeOperation, + OptIns, Package, PrePostCommands, Source, + }; + + use super::*; + + /// A plain WinGet install that asks for nothing beyond the package. + pub(in crate::v2::execution) fn winget_install() -> Request { + Request { + operation: Operation::Install, + manager: Manager::Winget, + source: Some(Source { + name: "winget".to_owned(), + }), + package: Package { + id: "Contoso.Tool".to_owned(), + version: Some("1.2.3".to_owned()), + architecture: None, + }, + scope: None, + elevation: Elevation::NonElevated, + opt_ins: OptIns::default(), + } + } + + fn with_installer_arguments(operation: Operation, mode: InstallerArgumentsMode) -> Request { + let mut request = winget_install(); + request.operation = operation; + request.opt_ins.installer_arguments = Some(RequestInstallerArguments { + arguments: "/quiet /norestart".to_owned(), + mode, + }); + request.opt_ins.custom_parameters = Some(CustomParameters { + values: vec!["--locale".to_owned(), "en-US".to_owned()], + }); + request + } + + /// The index of the only element of `command` equal to `element`. + fn position(command: &[String], element: &str) -> usize { + let mut positions = command + .iter() + .enumerate() + .filter(|(_, candidate)| *candidate == element) + .map(|(index, _)| index); + let position = positions + .next() + .unwrap_or_else(|| panic!("{element} is absent from {command:?}")); + assert_eq!(positions.next(), None, "{element} is repeated in {command:?}"); + position + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.policy.md §manager-winget + #[test] + fn winget_install_and_update_pass_installer_arguments_before_custom_parameters() { + for (operation, mode, option, other_option) in [ + ( + Operation::Install, + InstallerArgumentsMode::Append, + "--custom", + "--override", + ), + ( + Operation::Install, + InstallerArgumentsMode::Replace, + "--override", + "--custom", + ), + ( + Operation::Update, + InstallerArgumentsMode::Append, + "--custom", + "--override", + ), + ( + Operation::Update, + InstallerArgumentsMode::Replace, + "--override", + "--custom", + ), + ] { + let case = format!("{} {}", operation.as_str(), mode.as_str()); + let command = plan(&with_installer_arguments(operation, mode)).expect(&case).command; + + let option_at = position(&command, option); + assert_eq!(command[option_at + 1], "/quiet /norestart", "{case}: {command:?}"); + let parameters_at = position(&command, "--locale"); + assert!(option_at + 1 < parameters_at, "{case}: {command:?}"); + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.policy.md §reading + assert_eq!( + command[parameters_at..parameters_at + 2], + ["--locale", "en-US"], + "{case}: {command:?}" + ); + + assert!( + !command.iter().any(|element| element == other_option), + "{case}: {command:?}" + ); + } + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.policy.md §manager-winget + #[test] + fn winget_uninstall_passes_no_installer_arguments() { + for mode in [InstallerArgumentsMode::Append, InstallerArgumentsMode::Replace] { + let command = plan(&with_installer_arguments(Operation::Uninstall, mode)) + .unwrap_or_else(|error| panic!("{}: {error:#}", mode.as_str())) + .command; + + assert!( + !command + .iter() + .any(|element| ["--custom", "--override", "/quiet /norestart"].contains(&element.as_str())), + "{}: {command:?}", + mode.as_str() + ); + } + } + + /// An elevated WinGet request without `Scope` that carries the custom parameters `parameters`. + fn elevated_winget_without_scope(operation: Operation, parameters: &[&str]) -> Request { + let mut request = winget_install(); + request.operation = operation; + request.elevation = Elevation::Elevated; + if !parameters.is_empty() { + request.opt_ins.custom_parameters = Some(CustomParameters { + values: parameters.iter().map(|¶meter| parameter.to_owned()).collect(), + }); + } + request + } + + /// The number of elements of `command` that are `--scope` ignoring ASCII case, with or without a value after `=`. + fn scope_options(command: &[String]) -> usize { + command + .iter() + .filter(|element| { + let name = element.split('=').next().unwrap_or(element); + name.eq_ignore_ascii_case("--scope") + }) + .count() + } + + // oracle: contract Devolutions/now-libraries@09d6488736cf:policies/CONTRACT.policy.md §manager-winget + #[test] + fn winget_without_scope_passes_no_scope_option_when_the_run_is_not_elevated() { + for operation in [Operation::Install, Operation::Update, Operation::Uninstall] { + let mut request = winget_install(); + request.operation = operation; + + let command = command_of(&request); + + assert_eq!(scope_options(&command), 0, "{}: {command:?}", operation.as_str()); + } + } + + // oracle: contract Devolutions/now-libraries@09d6488736cf:policies/CONTRACT.policy.md §manager-winget + #[test] + fn an_elevated_winget_command_without_scope_names_the_machine_scope_before_the_custom_parameters() { + let no_custom_parameter_names_the_scope_option: [&[&str]; 9] = [ + &[], + &["--locale", "en-US"], + // "An element that is exactly `--` ends the options: no later element names an option." + &["--", "--scope", "user"], + // `--log` and `-o` are not options that the table lists with a value, so the `--` after one ends the + // options. + &["--log", "--", "--scope", "user"], + &["-o", "--", "--scope=user"], + &["--locale", "en-US", "--", "--SCOPE", "user"], + // The option takes "the next element, which is then only that value, even when it is `--` or starts with + // `-`". + &["--version", "--scope"], + &["-v", "--scope"], + &["--architecture", "--scope", "--locale", "en-US"], + ]; + + for operation in [Operation::Install, Operation::Update, Operation::Uninstall] { + for parameters in no_custom_parameter_names_the_scope_option { + let case = format!("{} {parameters:?}", operation.as_str()); + let command = command_of(&elevated_winget_without_scope(operation, parameters)); + + let scope_at = command + .iter() + .position(|element| element == "--scope") + .unwrap_or_else(|| panic!("{case}: {command:?}")); + assert_eq!(command[scope_at + 1], "machine", "{case}: {command:?}"); + // The custom parameters are the last elements of the command. + let own_options = &command[..command.len() - parameters.len()]; + assert!(scope_at + 1 < own_options.len(), "{case}: {command:?}"); + // "The broker passes `--scope` and `machine` as two elements", so its own options name the scope once. + assert_eq!(scope_options(own_options), 1, "{case}: {command:?}"); + } + } + } + + // oracle: contract Devolutions/now-libraries@09d6488736cf:policies/CONTRACT.policy.md §manager-winget + #[test] + fn an_elevated_winget_command_gets_no_scope_of_the_broker_when_a_custom_parameter_names_the_scope_option() { + let one_custom_parameter_names_the_scope_option: [&[&str]; 6] = [ + &["--scope", "machine"], + &["--scope=machine"], + // "A long option matches a name in the table ignoring ASCII case." + &["--SCOPE", "machine"], + &["--locale", "en-US", "--Scope=Machine"], + // An option that takes no value "still has its effect". + &["--locale", "en-US", "--scope"], + // `--locale` is not an option that the table lists with a value, so the next element names an option. + &["--locale", "--scope", "machine"], + ]; + + for operation in [Operation::Install, Operation::Update, Operation::Uninstall] { + for parameters in one_custom_parameter_names_the_scope_option { + let command = command_of(&elevated_winget_without_scope(operation, parameters)); + + assert_eq!( + scope_options(&command), + 1, + "{} {parameters:?}: {command:?}", + operation.as_str() + ); + } + } + } + + // "The broker passes every option it builds, and the value of each that takes one, before the custom parameters". + // oracle: contract Devolutions/now-libraries@09d6488736cf:policies/CONTRACT.policy.md §manager-winget + #[test] + fn a_winget_command_has_every_option_of_the_broker_before_the_custom_parameters() { + let custom_parameters: [&[&str]; 3] = [&["--locale", "en-US"], &["--log"], &["--", "--locale"]]; + + for operation in [Operation::Install, Operation::Update, Operation::Uninstall] { + for elevation in [Elevation::NonElevated, Elevation::Elevated] { + for parameters in custom_parameters { + let mut request = elevated_winget_without_scope(operation, parameters); + request.elevation = elevation; + + let command = command_of(&request); + + assert_eq!( + &command[command.len() - parameters.len()..], + parameters, + "{} {}: {command:?}", + operation.as_str(), + elevation.as_str() + ); + } + } + } + } + + // oracle: contract Devolutions/now-libraries@09d6488736cf:policies/CONTRACT.policy.md §manager-winget + #[test] + fn a_winget_command_names_the_scope_of_the_request_once() { + let mut machine_wide = winget_install(); + machine_wide.elevation = Elevation::Elevated; + machine_wide.scope = Some(Scope::Machine); + let for_the_user = Request { + scope: Some(Scope::User), + ..winget_install() + }; + + for (request, scope) in [(machine_wide, "machine"), (for_the_user, "user")] { + let command = command_of(&request); + + let scope_at = position(&command, "--scope"); + assert_eq!(command[scope_at + 1], scope, "{command:?}"); + assert_eq!(scope_options(&command), 1, "{command:?}"); + } + } + + /// The words after each `-Scope` of the script that the PowerShell command of `request` runs. + fn powershell_scopes(request: &Request) -> Vec { + let words = script_words(request); + words + .iter() + .enumerate() + .filter(|(_, word)| *word == "-Scope") + .map(|(index, _)| words.get(index + 1).cloned().unwrap_or_default()) + .collect() + } + + // oracle: contract Devolutions/now-libraries@09d6488736cf:policies/CONTRACT.policy.md §manager-powershell + #[test] + fn an_elevated_powershell_command_without_scope_names_the_scope_of_all_users() { + for request in [ + from_source( + without_source(Operation::Install, Manager::PowerShell, "Pester"), + "PSGallery", + ), + without_source(Operation::Uninstall, Manager::PowerShell7, "Pester"), + ] { + let request = Request { + elevation: Elevation::Elevated, + ..request + }; + + assert_eq!( + powershell_scopes(&request), + ["AllUsers"], + "{} {}", + request.manager.as_str(), + request.operation.as_str() + ); + } + } + + // An elevated Update under `PowerShell` gets no plan: without `Source` it is unreadable, and with one the broker + // has not read the recorded source. + // So this checks only that the broker would make its command machine-wide, as it does the one of an Install. + // oracle: contract Devolutions/now-libraries@09d6488736cf:policies/CONTRACT.policy.md §manager-powershell + #[test] + fn an_elevated_windows_powershell_update_without_scope_is_made_machine_wide() { + let mut request = from_source( + without_source(Operation::Update, Manager::PowerShell, "Pester"), + "PSGallery", + ); + request.elevation = Elevation::Elevated; + + let builder_request = builder_request(&request, v1::Elevation::Elevated); + + assert!(is_made_machine_wide(&request, &builder_request)); + } + + // "Under `PowerShell7`, when `Scope` is present, the broker passes `-Scope AllUsers` for `Machine` or + // `-Scope CurrentUser` for `User` to `Uninstall-PSResource`". + // oracle: contract Devolutions/now-libraries@09d6488736cf:policies/CONTRACT.policy.md §manager-powershell + #[test] + fn a_powershell7_uninstall_names_the_scope_of_the_request() { + for (scope, elevation, expected) in [ + (Scope::Machine, Elevation::Elevated, "AllUsers"), + (Scope::User, Elevation::NonElevated, "CurrentUser"), + ] { + let mut request = without_source(Operation::Uninstall, Manager::PowerShell7, "Pester"); + request.scope = Some(scope); + request.elevation = elevation; + + assert_eq!(powershell_scopes(&request), [expected], "{scope:?}"); + } + } + + // "Under `PowerShell7`, when `Scope` is absent and `Elevation` is `NonElevated`, the broker passes no `-Scope`", + // and under `PowerShell` "`Uninstall-Module` takes no scope". + // An elevated Uninstall under `PowerShell` is unreadable, so it gets no command. + // oracle: contract Devolutions/now-libraries@09d6488736cf:policies/CONTRACT.policy.md §manager-powershell + #[test] + fn a_powershell_uninstall_that_is_not_elevated_names_no_scope_where_its_command_takes_or_gets_none() { + for (manager, scope) in [ + (Manager::PowerShell7, None), + (Manager::PowerShell, None), + (Manager::PowerShell, Some(Scope::User)), + ] { + let mut request = without_source(Operation::Uninstall, manager, "Pester"); + request.scope = scope; + + assert_eq!(powershell_scopes(&request), [""; 0], "{} {scope:?}", manager.as_str()); + } + } + + // "The scope is `Scope`, and `User` when it is absent." + // oracle: contract Devolutions/now-libraries@09d6488736cf:policies/CONTRACT.policy.md §managers + #[test] + fn a_powershell_install_or_update_that_is_not_elevated_keeps_the_scope_of_the_current_user_without_scope() { + for (manager, operation) in [ + (Manager::PowerShell, Operation::Install), + (Manager::PowerShell, Operation::Update), + (Manager::PowerShell7, Operation::Install), + (Manager::PowerShell7, Operation::Update), + ] { + let request = without_source(operation, manager, "Pester"); + + assert_eq!( + powershell_scopes(&request), + ["CurrentUser"], + "{} {}", + manager.as_str(), + operation.as_str() + ); + } + } + + // oracle: contract Devolutions/now-libraries@09d6488736cf:policies/CONTRACT.policy.md §def-elevation + #[test] + fn the_run_has_the_elevation_the_request_asks_for() { + for (elevation, scope, expected) in [ + (Elevation::Elevated, Some(Scope::Machine), v1::Elevation::Elevated), + (Elevation::Elevated, None, v1::Elevation::Elevated), + (Elevation::NonElevated, Some(Scope::User), v1::Elevation::Standard), + (Elevation::NonElevated, None, v1::Elevation::Standard), + ] { + let mut request = winget_install(); + request.elevation = elevation; + request.scope = scope; + + assert_eq!( + plan(&request).expect("plan").elevation, + expected, + "{} {scope:?}", + elevation.as_str() + ); + } + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.policy.md §manager-npm + #[test] + fn no_npm_command_is_built_for_an_elevated_request_whatever_its_scope() { + for scope in [None, Some(Scope::Machine)] { + let mut request = winget_install(); + request.manager = Manager::Npm; + request.source = Some(Source { name: "npm".to_owned() }); + request.package.id = "left-pad".to_owned(); + request.elevation = Elevation::Elevated; + request.scope = scope; + + assert!(plan(&request).is_err(), "{scope:?}"); + } + } + + // Such a request is `NotRunnable`, and "the broker runs nothing for the request". + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §not-runnable + #[test] + fn pre_post_commands_never_get_a_plan_for_an_elevated_run() { + for commands in [ + PrePostCommands { + pre: Some("echo before".to_owned()), + post: None, + }, + PrePostCommands { + pre: None, + post: Some("echo after".to_owned()), + }, + ] { + let mut request = winget_install(); + request.elevation = Elevation::Elevated; + request.opt_ins.pre_post_commands = Some(commands.clone()); + + assert!(plan(&request).is_err(), "{commands:?}"); + } + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §operations + #[test] + fn the_plan_carries_the_pre_and_post_commands_of_a_run_that_is_not_elevated() { + let mut request = winget_install(); + request.opt_ins.pre_post_commands = Some(PrePostCommands { + pre: Some("echo before".to_owned()), + post: Some("echo after".to_owned()), + }); + + let plan = plan(&request).expect("plan"); + + assert_eq!(plan.pre_command.as_deref(), Some("echo before")); + assert_eq!(plan.post_command.as_deref(), Some("echo after")); + } + + /// An update under each manager that updates a package from the source recorded when it was installed. + pub(in crate::v2::execution) fn updates_from_a_recorded_source() -> [Request; 2] { + let scoop = Request { + operation: Operation::Update, + manager: Manager::Scoop, + source: Some(Source { + name: "main".to_owned(), + }), + package: Package { + id: "7zip".to_owned(), + version: None, + architecture: None, + }, + scope: None, + elevation: Elevation::NonElevated, + opt_ins: OptIns::default(), + }; + let windows_powershell = Request { + operation: Operation::Update, + manager: Manager::PowerShell, + source: Some(Source { + name: "PSGallery".to_owned(), + }), + package: Package { + id: "Pester".to_owned(), + version: Some("5.5.0".to_owned()), + architecture: None, + }, + scope: None, + elevation: Elevation::NonElevated, + opt_ins: OptIns::default(), + }; + + [scoop, windows_powershell] + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.policy.md §managers + #[test] + fn an_update_from_a_recorded_source_gets_no_plan_while_the_record_is_not_read() { + for request in updates_from_a_recorded_source() { + assert!(plan(&request).is_err(), "{}", request.manager.as_str()); + } + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §operations + #[test] + fn only_an_update_waits_for_the_record_of_its_source() { + for mut request in updates_from_a_recorded_source() { + request.operation = Operation::Install; + + plan(&request).unwrap_or_else(|error| panic!("{}: {error:#}", request.manager.as_str())); + } + } + + // The broker reads the record for "an Update that has `Source`". + // oracle: contract Devolutions/now-libraries@3014fcbb899d:policies/CONTRACT.wire.md §operations + #[test] + fn an_update_without_a_source_waits_for_no_record() { + for mut request in updates_from_a_recorded_source() { + request.source = None; + + plan(&request).unwrap_or_else(|error| panic!("{}: {error:#}", request.manager.as_str())); + } + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.policy.md §manager-powershell + #[test] + fn a_powershell_7_update_names_its_repository_instead_of_reading_a_record() { + let request = Request { + operation: Operation::Update, + manager: Manager::PowerShell7, + source: Some(Source { + name: "PSGallery".to_owned(), + }), + package: Package { + id: "Pester".to_owned(), + version: Some("5.5.0".to_owned()), + architecture: None, + }, + scope: None, + elevation: Elevation::NonElevated, + opt_ins: OptIns::default(), + }; + + let command = plan(&request).expect("plan").command; + + let script = command.last().expect("script"); + assert!(script.contains("Update-PSResource"), "{script}"); + assert!(script.contains("-Repository 'PSGallery'"), "{script}"); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §opt-ins + #[test] + fn the_plan_stops_processes_by_the_image_names_of_the_request() { + let mut request = winget_install(); + request.opt_ins.kill_before_operation = Some(KillBeforeOperation { + processes: vec!["Contoso Tool.exe".to_owned(), "helper.EXE".to_owned()], + }); + + let plan = plan(&request).expect("plan"); + + assert_eq!(plan.kill_processes, ["Contoso Tool.exe", "helper.EXE"]); + assert_eq!(plan.skipped_kill_processes, [""; 0]); + } + + // oracle: contract Devolutions/now-libraries@09d6488736cf:policies/CONTRACT.wire.md §opt-ins + #[test] + fn the_plan_stops_processes_whose_image_name_does_not_end_in_exe() { + let mut request = winget_install(); + request.opt_ins.kill_before_operation = Some(KillBeforeOperation { + processes: vec!["Mystify.scr".to_owned(), "helper.com".to_owned(), "chrome.".to_owned()], + }); + + let plan = plan(&request).expect("plan"); + + assert_eq!(plan.kill_processes, ["Mystify.scr", "helper.com", "chrome."]); + assert_eq!(plan.skipped_kill_processes, [""; 0]); + } + + // oracle: mutant handing `taskkill /IM` a name without `.` as the request spells it, which stops no process of the executable it stands for + #[test] + fn the_plan_stops_a_name_without_a_dot_as_that_name_with_the_exe_extension() { + let mut request = winget_install(); + request.opt_ins.kill_before_operation = Some(KillBeforeOperation { + processes: vec![ + "notepad".to_owned(), + "Contoso Tool".to_owned(), + "notepad.exe".to_owned(), + ], + }); + + let plan = plan(&request).expect("plan"); + + assert_eq!(plan.kill_processes, ["notepad.exe", "Contoso Tool.exe", "notepad.exe"]); + assert_eq!(plan.skipped_kill_processes, [""; 0]); + } + + // oracle: mutant handing the executor a name it refuses, which fails the plan before its first step + #[test] + fn a_name_the_executor_cannot_stop_is_left_out_of_the_plan() { + let unstoppable = [ + r"C:\tool.exe", + "bin/tool.scr", + "tool.exe:stream", + "\"tool.exe\"", + "to'ol.exe", + "tool\n.exe", + // `taskkill` reads an argument that starts with `-` as one of its switches. + "-T", + "-tool.exe", + "-tool", + ]; + let mut request = winget_install(); + request.opt_ins.kill_before_operation = Some(KillBeforeOperation { + processes: std::iter::once("tool.exe") + .chain(unstoppable) + .map(str::to_owned) + .collect(), + }); + + let plan = plan(&request).expect("plan"); + + assert_eq!(plan.kill_processes, ["tool.exe"]); + assert_eq!(plan.skipped_kill_processes, unstoppable); + } + + /// An operation on the version `version` of a module of the PowerShell Gallery. + fn gallery_module(operation: Operation, manager: Manager, version: &str) -> Request { + Request { + operation, + manager, + source: Some(Source { + name: "PSGallery".to_owned(), + }), + package: Package { + id: "Pester".to_owned(), + version: Some(version.to_owned()), + architecture: None, + }, + scope: None, + elevation: Elevation::NonElevated, + opt_ins: OptIns::default(), + } + } + + /// The words of the script that the PowerShell command of `request` runs, without the `;` that ends a statement. + fn script_words(request: &Request) -> Vec { + let command = plan(request) + .unwrap_or_else(|error| panic!("{} {:?}: {error:#}", request.manager.as_str(), request.package.version)) + .command; + let script = command.last().expect("script"); + script + .split_whitespace() + .map(|word| word.trim_end_matches(';').to_owned()) + .collect() + } + + // oracle: reference PowerShellGet, "Prerelease module versions" on Microsoft Learn: "To install a prerelease, always specify -AllowPrerelease. Specifying a prerelease version string is not sufficient." + #[test] + fn a_windows_powershell_install_pinned_to_a_pre_release_allows_pre_releases() { + let words = script_words(&gallery_module(Operation::Install, Manager::PowerShell, "2.0.0-beta1")); + + assert_eq!( + position(&words, "-RequiredVersion") + 1, + position(&words, "'2.0.0-beta1'") + ); + position(&words, "-AllowPrerelease"); + } + + // oracle: reference PSResourceGet on Microsoft Learn, `-Prerelease` of Install-PSResource: "When specified, includes prerelease versions in search results returned."; of Update-PSResource: "When specified, allows updating to a prerelease version." + #[test] + fn a_powershell_7_install_or_update_pinned_to_a_pre_release_includes_pre_releases() { + for operation in [Operation::Install, Operation::Update] { + let words = script_words(&gallery_module(operation, Manager::PowerShell7, "2.0.0-beta1")); + + assert_eq!( + position(&words, "-Version") + 1, + position(&words, "'2.0.0-beta1'"), + "{}", + operation.as_str() + ); + position(&words, "-Prerelease"); + } + } + + // oracle: mutant telling PowerShellGet or PSResourceGet to include pre-releases for a version that has none + #[test] + fn a_powershell_command_pinned_to_a_version_that_is_no_pre_release_asks_for_none() { + for (manager, option) in [ + (Manager::PowerShell, "-AllowPrerelease"), + (Manager::PowerShell7, "-Prerelease"), + ] { + // The build metadata of the second version has a `-`, and the version has no pre-release. + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.policy.md §version-scheme + for version in ["2.0.0", "2.0.0+build-1"] { + let words = script_words(&gallery_module(Operation::Install, manager, version)); + + assert!( + !words.iter().any(|word| word == option), + "{} {version}: {words:?}", + manager.as_str() + ); + } + } + } + + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.policy.md §version-scheme + #[test] + fn a_version_is_a_pre_release_when_it_is_a_version_that_has_a_pre_release() { + for (version, expected) in [ + ("2.0.0-beta1", true), + ("v1.0-rc.1", true), + ("V3-alpha", true), + ("1.2.3.4-x-y.0", true), + ("1.0.0-beta+exp.sha-1", true), + ("2.0.0", false), + ("v2.0", false), + // The `-` is in the build metadata. + ("2.0.0+build-1", false), + // No version: a pre-release identifier is empty, has a leading zero, or has another character. + ("2.0.0-", false), + ("2.0.0-a..b", false), + ("2.0.0-01", false), + ("2.0.0-beta_1", false), + // No version: a release component is empty or is not made of digits. + ("-beta", false), + ("2..0-beta", false), + ("2.x-beta", false), + ("vv2-beta", false), + // No version: the build metadata has another character. + ("2.0.0-beta+a_b", false), + // No version: a range of PowerShell 7. + ("[1.0.0-beta, 2.0.0)", false), + ] { + assert_eq!(is_pre_release(version), expected, "{version}"); + } + } + + // No case in which "the broker builds no Npm command" is a version that has a pre-release, and no other case of + // an unreadable request is one. + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.policy.md §manager-npm + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.policy.md §reading + #[test] + fn a_version_with_a_pre_release_gets_a_plan_under_a_manager_that_is_told_nothing_about_it() { + let mut request = winget_install(); + request.manager = Manager::Npm; + request.source = Some(Source { name: "npm".to_owned() }); + request.package.id = "left-pad".to_owned(); + request.package.version = Some("2.0.0-beta.1".to_owned()); + + plan(&request).expect("plan"); + } + + const OPERATIONS: [Operation; 3] = [Operation::Install, Operation::Update, Operation::Uninstall]; + + /// A request for `id` through `manager` that names no source and asks for nothing beyond the package. + fn without_source(operation: Operation, manager: Manager, id: &str) -> Request { + Request { + operation, + manager, + source: None, + package: Package { + id: id.to_owned(), + version: None, + architecture: None, + }, + scope: None, + elevation: Elevation::NonElevated, + opt_ins: OptIns::default(), + } + } + + /// `request` with the source name `name`. + fn from_source(mut request: Request, name: &str) -> Request { + request.source = Some(Source { name: name.to_owned() }); + request + } + + /// The command of the operation of `request`. + fn command_of(request: &Request) -> Vec { + plan(request) + .unwrap_or_else(|error| { + panic!( + "{} {} from {:?}: {error:#}", + request.manager.as_str(), + request.operation.as_str(), + request.source + ) + }) + .command + } + + // Without a source, the request is read with the only source name of its manager, "and the broker runs the + // command for it". + // oracle: contract Devolutions/now-libraries@3014fcbb899d:policies/CONTRACT.wire.md §bypass-reading + #[test] + fn a_request_without_a_source_gets_the_command_of_the_only_source_name_of_its_manager() { + for (manager, only_source_name, id, operations) in [ + // oracle: contract Devolutions/now-libraries@3014fcbb899d:policies/CONTRACT.policy.md §manager-npm + (Manager::Npm, "npm", "left-pad", &OPERATIONS[..]), + // oracle: contract Devolutions/now-libraries@3014fcbb899d:policies/CONTRACT.policy.md §manager-bun + (Manager::Bun, "Bun", "left-pad", &OPERATIONS[..]), + // oracle: contract Devolutions/now-libraries@3014fcbb899d:policies/CONTRACT.policy.md §manager-cargo + (Manager::Cargo, "crates.io", "ripgrep", &OPERATIONS[..]), + // oracle: contract Devolutions/now-libraries@3014fcbb899d:policies/CONTRACT.policy.md §manager-pip + (Manager::Pip, "pip", "requests", &OPERATIONS[..]), + // `nuget.org` is the only source name of an Install or Update. + // oracle: contract Devolutions/now-libraries@3014fcbb899d:policies/CONTRACT.policy.md §manager-dotnet + ( + Manager::Dotnet, + "nuget.org", + "dotnetsay", + &[Operation::Install, Operation::Update][..], + ), + ] { + for operation in operations { + let request = without_source(*operation, manager, id); + + assert_eq!( + command_of(&request), + command_of(&from_source(request.clone(), only_source_name)), + "{} {}", + manager.as_str(), + operation.as_str() + ); + } + } + } + + // Without a source, "the broker passes no source to the manager", and the request is read in the same way. + // oracle: contract Devolutions/now-libraries@3014fcbb899d:policies/CONTRACT.wire.md §bypass-reading + #[test] + fn a_command_without_a_source_is_the_one_of_a_source_without_its_source_option() { + for (manager, name, id, operations) in [ + // WinGet takes `Source.Name` as `--source`. + // oracle: contract Devolutions/now-libraries@3014fcbb899d:policies/CONTRACT.policy.md §managers + (Manager::Winget, "winget", "Contoso.Tool", &OPERATIONS[..]), + // oracle: reference Chocolatey, "Install Command (choco install)" and "Upgrade Command (choco upgrade)" on docs.chocolatey.org, the option "-s, --source=VALUE": "Defaults to default feeds." + ( + Manager::Chocolatey, + "community", + "git", + &[Operation::Install, Operation::Update][..], + ), + ] { + for operation in operations { + let case = format!("{} {}", manager.as_str(), operation.as_str()); + let request = without_source(*operation, manager, id); + let mut expected = command_of(&from_source(request.clone(), name)); + let option_at = position(&expected, "--source"); + assert_eq!(expected[option_at + 1], name, "{case}: {expected:?}"); + expected.drain(option_at..option_at + 2); + + assert_eq!(command_of(&request), expected, "{case}"); + } + } + } + + // oracle: contract Devolutions/now-libraries@3014fcbb899d:policies/CONTRACT.wire.md §bypass-reading + #[test] + fn an_uninstall_without_a_source_passes_no_source_option() { + for (manager, id) in [ + // oracle: reference Chocolatey, "Install Command (choco install)" on docs.chocolatey.org, whose source option is "-s, --source=VALUE" + (Manager::Chocolatey, "git"), + // oracle: reference .NET CLI, "dotnet tool install" on Microsoft Learn, whose source options are "[--add-source ]" and "[--source ]" + (Manager::Dotnet, "dotnetsay"), + ] { + let command = command_of(&without_source(Operation::Uninstall, manager, id)); + + assert!( + !command.iter().any(|element| { + ["-s", "--source", "--add-source"].contains(&element.as_str()) + || element.starts_with("--source=") + || element.starts_with("--add-source=") + }), + "{}: {command:?}", + manager.as_str() + ); + } + } + + /// An elevated Install and an elevated Update of `id` through `manager` that name no source. + fn elevated_without_source(manager: Manager, id: &str) -> [Request; 2] { + [Operation::Install, Operation::Update].map(|operation| { + let mut request = without_source(operation, manager, id); + request.elevation = Elevation::Elevated; + request + }) + } + + // Such a request is unreadable "unless its manager is `Winget` or `Chocolatey`". + // oracle: contract Devolutions/now-libraries@3014fcbb899d:policies/CONTRACT.wire.md §bypass-reading + #[test] + fn an_elevated_install_or_update_without_a_source_gets_a_plan_under_winget_and_chocolatey() { + for (manager, id) in [(Manager::Winget, "Contoso.Tool"), (Manager::Chocolatey, "git")] { + for request in elevated_without_source(manager, id) { + command_of(&request); + } + } + } + + // oracle: mutant building, for a request without a source, the elevated command that the builder of its manager refuses for a request with one + #[test] + fn an_elevated_install_or_update_without_a_source_gets_no_plan_where_no_elevated_command_is_built() { + for (manager, id) in [ + (Manager::PowerShell7, "Pester"), + (Manager::Npm, "left-pad"), + (Manager::Bun, "left-pad"), + (Manager::Cargo, "ripgrep"), + (Manager::Pip, "requests"), + (Manager::Scoop, "7zip"), + (Manager::Vcpkg, "zlib:x64-windows"), + ] { + for request in elevated_without_source(manager, id) { + assert!( + plan(&request).is_err(), + "{} {}", + manager.as_str(), + request.operation.as_str() + ); + } + } + } + + // oracle: mutant building an elevated Windows PowerShell command that names no repository, which leaves the choice among the registered repositories to PowerShellGet + #[test] + fn an_elevated_windows_powershell_install_or_update_without_a_source_gets_no_plan() { + for request in elevated_without_source(Manager::PowerShell, "Pester") { + assert!(plan(&request).is_err(), "{}", request.operation.as_str()); + } + } + + // Without a source, "the broker passes no source to the manager", which PowerShell takes as `-Repository`. + // oracle: contract Devolutions/now-libraries@3014fcbb899d:policies/CONTRACT.wire.md §bypass-reading + // oracle: contract Devolutions/now-libraries@3014fcbb899d:policies/CONTRACT.policy.md §managers + #[test] + fn a_powershell_command_without_a_source_names_its_module_and_no_repository() { + for (manager, operation, cmdlet) in [ + // oracle: reference PowerShellGet on Microsoft Learn, the cmdlets Install-Module, Update-Module and Uninstall-Module + (Manager::PowerShell, Operation::Install, "Install-Module"), + (Manager::PowerShell, Operation::Update, "Update-Module"), + (Manager::PowerShell, Operation::Uninstall, "Uninstall-Module"), + // oracle: reference PSResourceGet on Microsoft Learn, the cmdlets Install-PSResource, Update-PSResource and Uninstall-PSResource + (Manager::PowerShell7, Operation::Install, "Install-PSResource"), + (Manager::PowerShell7, Operation::Update, "Update-PSResource"), + (Manager::PowerShell7, Operation::Uninstall, "Uninstall-PSResource"), + ] { + let case = format!("{} {}", manager.as_str(), operation.as_str()); + let words = script_words(&without_source(operation, manager, "Pester")); + + // The broker passes the identifier "whole as the value of `-Name`". + // oracle: contract Devolutions/now-libraries@3014fcbb899d:policies/CONTRACT.policy.md §manager-powershell + let cmdlet_at = position(&words, cmdlet); + assert_eq!( + words[cmdlet_at + 1..cmdlet_at + 3], + ["-Name", "'Pester'"], + "{case}: {words:?}" + ); + assert!(!words.iter().any(|word| word == "-Repository"), "{case}: {words:?}"); + } + } + + // "No command the broker builds limits an uninstall to packages installed from `Source.Name`". + // oracle: contract Devolutions/now-libraries@09d6488736cf:policies/CONTRACT.policy.md §managers + #[test] + fn a_powershell_uninstall_from_a_source_does_not_check_the_repository_recorded_for_its_module() { + for manager in [Manager::PowerShell, Manager::PowerShell7] { + let request = from_source(without_source(Operation::Uninstall, manager, "Pester"), "PSGallery"); + + let command = command_of(&request); + + // PowerShell reads names ignoring case. + let script = command.last().expect("script").to_ascii_lowercase(); + // oracle: reference PowerShellGet and PSResourceGet on Microsoft Learn, the objects that Get-InstalledModule and Get-InstalledPSResource return, whose property `Repository` is the repository a module was installed from + assert!(!script.contains(".repository"), "{}: {script}", manager.as_str()); + assert!(!script.contains("throw"), "{}: {script}", manager.as_str()); + } + } + + // oracle: mutant building the command of an uninstall for a source name that the PowerShell builders refuse + #[test] + fn a_powershell_uninstall_from_a_source_name_that_its_builder_refuses_gets_no_plan() { + for manager in [Manager::PowerShell, Manager::PowerShell7] { + let request = from_source(without_source(Operation::Uninstall, manager, "Pester"), "PS;Gallery"); + + assert!(plan(&request).is_err(), "{}", manager.as_str()); + } + } + + /// An elevated WinGet install into the folder `path`. + fn elevated_winget_install_into(path: &str) -> Request { + let mut request = winget_install(); + request.elevation = Elevation::Elevated; + request.opt_ins.custom_install_location = Some(CustomInstallLocation { path: path.to_owned() }); + request + } + + // A plain local path starts with "an ASCII letter followed by `:` and a separator", and a segment of it "is not + // `.` or `..`, does not start with a space (U+0020), does not end with `.` or a space". + // oracle: contract Devolutions/now-libraries@09d6488736cf:policies/CONTRACT.policy.md §install-location + #[test] + fn an_install_location_that_is_not_a_plain_local_path_gets_no_plan() { + let planned: Vec<&str> = [ + r"C:\Users\Public\Tools.", + r"C:\Users\Public\Tools ", + r"C:\Users\Public\ Tools", + r"C:\Users\Public\..\Tools", + r"\\server\share\Tools", + r"Public\Tools", + ] + .into_iter() + .filter(|path| plan(&elevated_winget_install_into(path)).is_ok()) + .collect(); + + assert_eq!(planned, [] as [&str; 0]); + } + + // A plain local path passes the install location check. + // oracle: contract Devolutions/now-libraries@09d6488736cf:policies/CONTRACT.policy.md §install-location + // oracle: mutant leaving the install location of a request out of its plan, so that the executor verifies no folder + #[test] + fn a_plan_carries_an_install_location_that_is_a_plain_local_path() { + let plan = plan(&elevated_winget_install_into(r"C:\Users\Public\Tools")).expect("plan"); + + assert_eq!( + plan.custom_install_location, + Some(PathBuf::from(r"C:\Users\Public\Tools")) + ); + } + + // Under Scoop, "the broker passes `Package.Id` alone". + // oracle: contract Devolutions/now-libraries@3014fcbb899d:policies/CONTRACT.wire.md §bypass-reading + #[test] + fn a_scoop_command_without_a_source_passes_the_package_id_alone() { + for (operation, subcommand) in [ + // oracle: reference Scoop, `libexec/scoop-install.ps1`: "# Usage: scoop install [options]" + (Operation::Install, "'install'"), + // oracle: reference Scoop, `libexec/scoop-update.ps1`: "# Usage: scoop update [options]" + (Operation::Update, "'update'"), + // oracle: reference Scoop, `libexec/scoop-uninstall.ps1`: "# Usage: scoop uninstall [options]" + (Operation::Uninstall, "'uninstall'"), + ] { + let words = script_words(&without_source(operation, Manager::Scoop, "7zip")); + + assert_eq!( + position(&words, subcommand) + 1, + position(&words, "'7zip'"), + "{}: {words:?}", + operation.as_str() + ); + } + } + + // Under Vcpkg, "the broker passes `Package.Id` as it is", where it passes `:` for a source. + // oracle: contract Devolutions/now-libraries@3014fcbb899d:policies/CONTRACT.wire.md §bypass-reading + // oracle: contract Devolutions/now-libraries@3014fcbb899d:policies/CONTRACT.policy.md §managers + #[test] + fn a_vcpkg_command_without_a_source_passes_the_package_id_as_it_is() { + for operation in OPERATIONS { + let named = command_of(&from_source( + without_source(operation, Manager::Vcpkg, "zlib"), + "x64-windows", + )); + let spec_at = position(&named, "zlib:x64-windows"); + + for id in ["zlib", "zlib:x64-windows", "curl[ssl]", "curl[ssl,http2]:arm64-windows"] { + let mut expected = named.clone(); + expected[spec_at] = id.to_owned(); + + assert_eq!( + command_of(&without_source(operation, Manager::Vcpkg, id)), + expected, + "{} {id}", + operation.as_str() + ); + } + } + } +} diff --git a/crates/now-package-broker/src/v2/wire/convert.rs b/crates/now-package-broker/src/v2/wire/convert.rs new file mode 100644 index 000000000..9f8a20906 --- /dev/null +++ b/crates/now-package-broker/src/v2/wire/convert.rs @@ -0,0 +1,1016 @@ +//! Conversions between the message types and the evaluator's types. +//! +//! Each closed set is mapped by a `match` without a wildcard arm, so a value added to the message types or to the +//! evaluator does not compile until it is mapped. + +use chrono::{DateTime, Utc}; +use now_policy_api::v2; +use now_policy_eval as eval; + +/// Returns the evaluator's input for a package request ([§request-input]). +/// +/// [§request-input]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.policy.md#request-input +pub fn evaluator_request(request: &v2::PackageRequest) -> eval::Request { + eval::Request { + operation: operation(request.operation), + manager: manager(request.manager), + source: Some(eval::Source { + name: request.source.name.as_str().to_owned(), + }), + package: eval::Package { + id: request.package.id.as_str().to_owned(), + version: request + .package + .version + .as_ref() + .map(|version| version.as_str().to_owned()), + architecture: request.package.architecture.map(architecture), + }, + scope: request.scope.map(scope), + elevation: elevation(request.elevation), + opt_ins: request.opt_ins.as_ref().map(evaluator_opt_ins).unwrap_or_default(), + } +} + +fn evaluator_opt_ins(opt_ins: &v2::OptIns) -> eval::OptIns { + eval::OptIns { + interactive: opt_ins.interactive.is_some(), + skip_hash_check: opt_ins.skip_hash_check.is_some(), + custom_install_location: opt_ins + .custom_install_location + .as_ref() + .map(|location| eval::CustomInstallLocation { + path: location.path.as_str().to_owned(), + }), + custom_parameters: opt_ins + .custom_parameters + .as_ref() + .map(|parameters| eval::CustomParameters { + values: parameters + .values + .iter() + .map(|value| value.as_str().to_owned()) + .collect(), + }), + installer_arguments: opt_ins + .installer_arguments + .as_ref() + .map(|arguments| eval::InstallerArguments { + arguments: arguments.arguments.as_str().to_owned(), + mode: installer_arguments_mode(arguments.mode), + }), + pre_post_commands: opt_ins + .pre_post_commands + .as_ref() + .map(|commands| eval::PrePostCommands { + pre: commands.pre.as_ref().map(|command| command.as_str().to_owned()), + post: commands.post.as_ref().map(|command| command.as_str().to_owned()), + }), + kill_before_operation: opt_ins + .kill_before_operation + .as_ref() + .map(|kill| eval::KillBeforeOperation { + processes: kill + .processes + .iter() + .map(|process| process.as_str().to_owned()) + .collect(), + }), + uninstall_previous: opt_ins.uninstall_previous.is_some(), + no_upgrade: opt_ins.no_upgrade.is_some(), + } +} + +/// Returns the package request a bypass request is read as ([§bypass-reading]), or `None` when the request has no +/// `Source.Name`. +/// +/// `listed_source` is the `Source.Name` that the list of that section gives a request without `Source`, when it gives +/// one. +/// +/// [§bypass-reading]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#bypass-reading +pub fn bypass_package_request( + request: &v2::BypassRequest, + listed_source: Option<&v2::SourceName>, +) -> Option { + let source = match (&request.source, listed_source) { + (Some(source), _) => source.clone(), + (None, Some(name)) => v2::Source { name: name.clone() }, + (None, None) => return None, + }; + + Some(v2::PackageRequest { + operation: request.operation, + manager: request.manager, + source, + package: v2::Package { + id: request.package.id.clone(), + version: request.package.version.clone(), + architecture: None, + }, + scope: request.scope, + elevation: request.elevation, + opt_ins: request.opt_ins.as_ref().map(|opt_ins| v2::OptIns { + interactive: None, + skip_hash_check: None, + custom_install_location: None, + custom_parameters: None, + installer_arguments: None, + pre_post_commands: None, + kill_before_operation: None, + uninstall_previous: None, + no_upgrade: opt_ins.no_upgrade.clone(), + }), + }) +} + +/// Returns the decision as a response carries it ([§decision]). +/// +/// Fails when a rule id is not one a policy document can hold, which no decision of the evaluator has. +/// +/// [§decision]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#decision +pub fn decision(decision: &eval::Decision) -> Result { + let rules = decision + .rules + .iter() + .map(|rule| { + Ok(v2::Rule { + id: v2::RuleId::parse(&rule.id)?, + reason: rule.reason.clone(), + }) + }) + .collect::>()?; + + Ok(v2::Decision { + outcome: outcome(decision.outcome), + check: check(decision.check), + rules, + opt_ins: decision.opt_ins.iter().copied().map(opt_in_name).collect(), + audited: decision.audited, + }) +} + +/// Returns the validation error as a response carries it ([§policy-errors]). +/// +/// [§policy-errors]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#policy-errors +pub fn policy_error(error: &eval::ValidationError) -> v2::PolicyError { + v2::PolicyError { + code: policy_error_code(error.code), + pointer: error.pointer.clone(), + } +} + +/// Returns the timestamp the broker writes for an instant, with the offset `Z` ([§values]). +/// +/// Fails when the year of the instant is outside 0001 to 9999, or when the instant is a leap second, neither of which +/// a timestamp names ([§timestamps]). +/// +/// [§values]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#values +/// [§timestamps]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.policy.md#timestamps +pub fn timestamp(instant: DateTime) -> Result { + v2::Timestamp::from_datetime(instant) +} + +fn operation(operation: v2::Operation) -> eval::Operation { + match operation { + v2::Operation::Install => eval::Operation::Install, + v2::Operation::Update => eval::Operation::Update, + v2::Operation::Uninstall => eval::Operation::Uninstall, + } +} + +fn manager(manager: v2::Manager) -> eval::Manager { + match manager { + v2::Manager::Winget => eval::Manager::Winget, + v2::Manager::PowerShell => eval::Manager::PowerShell, + v2::Manager::PowerShell7 => eval::Manager::PowerShell7, + v2::Manager::Apt => eval::Manager::Apt, + v2::Manager::Bun => eval::Manager::Bun, + v2::Manager::Cargo => eval::Manager::Cargo, + v2::Manager::Chocolatey => eval::Manager::Chocolatey, + v2::Manager::Dnf => eval::Manager::Dnf, + v2::Manager::Dotnet => eval::Manager::Dotnet, + v2::Manager::Flatpak => eval::Manager::Flatpak, + v2::Manager::Homebrew => eval::Manager::Homebrew, + v2::Manager::Npm => eval::Manager::Npm, + v2::Manager::Pacman => eval::Manager::Pacman, + v2::Manager::Pip => eval::Manager::Pip, + v2::Manager::Scoop => eval::Manager::Scoop, + v2::Manager::Snap => eval::Manager::Snap, + v2::Manager::Vcpkg => eval::Manager::Vcpkg, + } +} + +fn scope(scope: v2::Scope) -> eval::Scope { + match scope { + v2::Scope::User => eval::Scope::User, + v2::Scope::Machine => eval::Scope::Machine, + } +} + +fn architecture(architecture: v2::Architecture) -> eval::Architecture { + match architecture { + v2::Architecture::X86 => eval::Architecture::X86, + v2::Architecture::X64 => eval::Architecture::X64, + v2::Architecture::Arm64 => eval::Architecture::Arm64, + v2::Architecture::Neutral => eval::Architecture::Neutral, + } +} + +fn elevation(elevation: v2::Elevation) -> eval::Elevation { + match elevation { + v2::Elevation::NonElevated => eval::Elevation::NonElevated, + v2::Elevation::Elevated => eval::Elevation::Elevated, + } +} + +fn installer_arguments_mode(mode: v2::InstallerArgumentsMode) -> eval::InstallerArgumentsMode { + match mode { + v2::InstallerArgumentsMode::Append => eval::InstallerArgumentsMode::Append, + v2::InstallerArgumentsMode::Replace => eval::InstallerArgumentsMode::Replace, + } +} + +fn outcome(outcome: eval::Outcome) -> v2::Outcome { + match outcome { + eval::Outcome::Allow => v2::Outcome::Allow, + eval::Outcome::Deny => v2::Outcome::Deny, + } +} + +fn check(check: eval::Check) -> v2::Check { + match check { + eval::Check::UnreadableRequest => v2::Check::UnreadableRequest, + eval::Check::ValidityWindow => v2::Check::ValidityWindow, + eval::Check::InstallLocation => v2::Check::InstallLocation, + eval::Check::MissingVersion => v2::Check::MissingVersion, + eval::Check::UntrustedSource => v2::Check::UntrustedSource, + eval::Check::DenyRule => v2::Check::DenyRule, + eval::Check::UngrantedOptIn => v2::Check::UngrantedOptIn, + eval::Check::DefaultDeny => v2::Check::DefaultDeny, + eval::Check::AllowRules => v2::Check::AllowRules, + } +} + +fn opt_in_name(opt_in: eval::OptIn) -> v2::OptInName { + match opt_in { + eval::OptIn::Interactive => v2::OptInName::Interactive, + eval::OptIn::SkipHashCheck => v2::OptInName::SkipHashCheck, + eval::OptIn::CustomInstallLocation => v2::OptInName::CustomInstallLocation, + eval::OptIn::CustomParameters => v2::OptInName::CustomParameters, + eval::OptIn::InstallerArguments => v2::OptInName::InstallerArguments, + eval::OptIn::PrePostCommands => v2::OptInName::PrePostCommands, + eval::OptIn::KillBeforeOperation => v2::OptInName::KillBeforeOperation, + eval::OptIn::UninstallPrevious => v2::OptInName::UninstallPrevious, + eval::OptIn::NoUpgrade => v2::OptInName::NoUpgrade, + } +} + +fn policy_error_code(code: eval::ErrorCode) -> v2::PolicyErrorCode { + match code { + eval::ErrorCode::DocumentTooLarge => v2::PolicyErrorCode::DocumentTooLarge, + eval::ErrorCode::MalformedDocument => v2::PolicyErrorCode::MalformedDocument, + eval::ErrorCode::DuplicateKey => v2::PolicyErrorCode::DuplicateKey, + eval::ErrorCode::UnsupportedFormatVersion => v2::PolicyErrorCode::UnsupportedFormatVersion, + eval::ErrorCode::MissingKey => v2::PolicyErrorCode::MissingKey, + eval::ErrorCode::UnknownKey => v2::PolicyErrorCode::UnknownKey, + eval::ErrorCode::ConflictingKeys => v2::PolicyErrorCode::ConflictingKeys, + eval::ErrorCode::WrongType => v2::PolicyErrorCode::WrongType, + eval::ErrorCode::InvalidValue => v2::PolicyErrorCode::InvalidValue, + eval::ErrorCode::DuplicateRuleId => v2::PolicyErrorCode::DuplicateRuleId, + } +} + +#[cfg(test)] +mod tests { + use chrono::{TimeZone as _, Timelike as _}; + use serde::Serialize; + use serde::de::DeserializeOwned; + use serde_json::{Value, json}; + + use super::*; + use crate::v2::wire::{read_bypass_request, read_evaluation_request, read_execution_request}; + + const NONE: &[&str] = &[]; + + /// The operations of the policy contract's "Request properties". + const OPERATIONS: [&str; 3] = ["Install", "Update", "Uninstall"]; + + /// The manager identifiers of the policy contract's "Managers". + const MANAGERS: [&str; 17] = [ + "Winget", + "PowerShell", + "PowerShell7", + "Apt", + "Bun", + "Cargo", + "Chocolatey", + "Dnf", + "Dotnet", + "Flatpak", + "Homebrew", + "Npm", + "Pacman", + "Pip", + "Scoop", + "Snap", + "Vcpkg", + ]; + + /// The scopes of the policy contract's "Request properties". + const SCOPES: [&str; 2] = ["User", "Machine"]; + + /// The architectures of the policy contract's "Request properties". + const ARCHITECTURES: [&str; 4] = ["X86", "X64", "Arm64", "Neutral"]; + + /// The elevations of the policy contract's "Request properties". + const ELEVATIONS: [&str; 2] = ["NonElevated", "Elevated"]; + + /// The values of `Mode` in the wire contract's "Opt-ins". + const INSTALLER_ARGUMENTS_MODES: [&str; 2] = ["Append", "Replace"]; + + /// The opt-ins of the policy contract's "Opt-ins", in the order of its table. + const OPT_INS: [&str; 9] = [ + "Interactive", + "SkipHashCheck", + "CustomInstallLocation", + "CustomParameters", + "InstallerArguments", + "PrePostCommands", + "KillBeforeOperation", + "UninstallPrevious", + "NoUpgrade", + ]; + + /// A value of the message types' closed set `T`, from its name in the contract. + fn named(name: &str) -> T { + serde_json::from_value(json!(name)).expect("a value of the closed set") + } + + /// The name a message carries for a value of a closed set. + fn name_of(value: T) -> String { + serde_json::to_value(value) + .expect("a value of a closed set") + .as_str() + .expect("a closed-set value written as a string") + .to_owned() + } + + /// Returns the names that `mapped` changes. + fn changed_names<'a>(names: &[&'a str], mapped: impl Fn(&str) -> String) -> Vec<&'a str> { + names.iter().copied().filter(|name| mapped(name) != *name).collect() + } + + fn names>(values: &[T], name: impl Fn(T) -> N) -> Vec { + values.iter().map(|value| name(*value).as_ref().to_owned()).collect() + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.policy.md §request-properties + #[test] + fn every_operation_keeps_its_name() { + assert_eq!( + changed_names(&OPERATIONS, |name| operation(named(name)).as_str().to_owned()), + NONE + ); + assert_eq!(names(eval::Operation::ALL, eval::Operation::as_str), OPERATIONS); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.policy.md §managers + #[test] + fn every_manager_keeps_its_name() { + assert_eq!( + changed_names(&MANAGERS, |name| manager(named(name)).as_str().to_owned()), + NONE + ); + assert_eq!(names(eval::Manager::ALL, eval::Manager::as_str), MANAGERS); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.policy.md §request-properties + #[test] + fn every_scope_keeps_its_name() { + assert_eq!( + changed_names(&SCOPES, |name| scope(named(name)).as_str().to_owned()), + NONE + ); + assert_eq!(names(eval::Scope::ALL, eval::Scope::as_str), SCOPES); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.policy.md §request-properties + #[test] + fn every_architecture_keeps_its_name() { + assert_eq!( + changed_names(&ARCHITECTURES, |name| architecture(named(name)).as_str().to_owned()), + NONE + ); + assert_eq!( + names(eval::Architecture::ALL, eval::Architecture::as_str), + ARCHITECTURES + ); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.policy.md §request-properties + #[test] + fn every_elevation_keeps_its_name() { + assert_eq!( + changed_names(&ELEVATIONS, |name| elevation(named(name)).as_str().to_owned()), + NONE + ); + assert_eq!(names(eval::Elevation::ALL, eval::Elevation::as_str), ELEVATIONS); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §opt-ins + #[test] + fn every_installer_arguments_mode_keeps_its_name() { + assert_eq!( + changed_names(&INSTALLER_ARGUMENTS_MODES, |name| { + installer_arguments_mode(named(name)).as_str().to_owned() + }), + NONE + ); + assert_eq!( + names(eval::InstallerArgumentsMode::ALL, eval::InstallerArgumentsMode::as_str), + INSTALLER_ARGUMENTS_MODES + ); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.policy.md §opt-ins + #[test] + fn every_opt_in_keeps_its_name() { + assert_eq!( + changed_names(&OPT_INS, |name| { + name_of(opt_in_name(eval::OptIn::from_name(name).expect("an opt-in"))) + }), + NONE + ); + assert_eq!(names(eval::OptIn::ALL, eval::OptIn::as_str), OPT_INS); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §decision + #[test] + fn every_outcome_keeps_its_name() { + let outcomes = [eval::Outcome::Allow, eval::Outcome::Deny]; + + assert_eq!(names(&outcomes, eval::Outcome::as_str), ["Allow", "Deny"]); + assert_eq!(names(&outcomes, |value| name_of(outcome(value))), ["Allow", "Deny"]); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.policy.md §precedence + #[test] + fn every_check_keeps_its_name() { + const CHECKS: [&str; 9] = [ + "UnreadableRequest", + "ValidityWindow", + "InstallLocation", + "MissingVersion", + "UntrustedSource", + "DenyRule", + "UngrantedOptIn", + "DefaultDeny", + "AllowRules", + ]; + let checks = [ + eval::Check::UnreadableRequest, + eval::Check::ValidityWindow, + eval::Check::InstallLocation, + eval::Check::MissingVersion, + eval::Check::UntrustedSource, + eval::Check::DenyRule, + eval::Check::UngrantedOptIn, + eval::Check::DefaultDeny, + eval::Check::AllowRules, + ]; + + assert_eq!(names(&checks, eval::Check::as_str), CHECKS); + assert_eq!(names(&checks, |value| name_of(check(value))), CHECKS); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.policy.md §errors + #[test] + fn every_validation_error_code_keeps_its_name() { + const CODES: [&str; 10] = [ + "DocumentTooLarge", + "MalformedDocument", + "DuplicateKey", + "UnsupportedFormatVersion", + "MissingKey", + "UnknownKey", + "ConflictingKeys", + "WrongType", + "InvalidValue", + "DuplicateRuleId", + ]; + let codes = [ + eval::ErrorCode::DocumentTooLarge, + eval::ErrorCode::MalformedDocument, + eval::ErrorCode::DuplicateKey, + eval::ErrorCode::UnsupportedFormatVersion, + eval::ErrorCode::MissingKey, + eval::ErrorCode::UnknownKey, + eval::ErrorCode::ConflictingKeys, + eval::ErrorCode::WrongType, + eval::ErrorCode::InvalidValue, + eval::ErrorCode::DuplicateRuleId, + ]; + + assert_eq!(names(&codes, eval::ErrorCode::as_str), CODES); + assert_eq!(names(&codes, |value| name_of(policy_error_code(value))), CODES); + } + + /// A body with every member of a package request, each with a value of its own. + fn full_package_request() -> Value { + json!({ + "Operation": "Update", + "Manager": "Chocolatey", + "Source": { "Name": "community" }, + "Package": { "Id": "git.install", "Version": "2.45.1", "Architecture": "Arm64" }, + "Scope": "Machine", + "Elevation": "Elevated", + "OptIns": { + "Interactive": {}, + "SkipHashCheck": {}, + "CustomInstallLocation": { "Path": "D:\\Tools\\Git" }, + "CustomParameters": { "Values": ["--params", "/NoShellIntegration"] }, + "InstallerArguments": { "Arguments": "/VERYSILENT", "Mode": "Replace" }, + "PrePostCommands": { "Pre": "echo before", "Post": "echo after" }, + "KillBeforeOperation": { "Processes": ["git.exe", "bash.exe"] }, + "UninstallPrevious": {}, + "NoUpgrade": {}, + }, + }) + } + + /// The evaluator's request with the members of `full_package_request`. + fn full_evaluator_request() -> eval::Request { + eval::Request { + operation: eval::Operation::Update, + manager: eval::Manager::Chocolatey, + source: Some(eval::Source { + name: "community".to_owned(), + }), + package: eval::Package { + id: "git.install".to_owned(), + version: Some("2.45.1".to_owned()), + architecture: Some(eval::Architecture::Arm64), + }, + scope: Some(eval::Scope::Machine), + elevation: eval::Elevation::Elevated, + opt_ins: eval::OptIns { + interactive: true, + skip_hash_check: true, + custom_install_location: Some(eval::CustomInstallLocation { + path: "D:\\Tools\\Git".to_owned(), + }), + custom_parameters: Some(eval::CustomParameters { + values: vec!["--params".to_owned(), "/NoShellIntegration".to_owned()], + }), + installer_arguments: Some(eval::InstallerArguments { + arguments: "/VERYSILENT".to_owned(), + mode: eval::InstallerArgumentsMode::Replace, + }), + pre_post_commands: Some(eval::PrePostCommands { + pre: Some("echo before".to_owned()), + post: Some("echo after".to_owned()), + }), + kill_before_operation: Some(eval::KillBeforeOperation { + processes: vec!["git.exe".to_owned(), "bash.exe".to_owned()], + }), + uninstall_previous: true, + no_upgrade: true, + }, + } + } + + fn evaluation_request(body: &Value) -> v2::PackageRequest { + read_evaluation_request(body.to_string().as_bytes()).expect("package request") + } + + fn with(mut body: Value, pointer: &str, value: Value) -> Value { + *body.pointer_mut(pointer).expect("a member of the body") = value; + body + } + + fn without(mut body: Value, parent: &str, key: &str) -> Value { + body.pointer_mut(parent) + .and_then(Value::as_object_mut) + .expect("an object of the body") + .remove(key) + .expect("a member of the object"); + body + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.policy.md §request-input + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §package-request + #[test] + fn evaluator_request_has_every_member_of_the_package_request() { + let request = evaluation_request(&full_package_request()); + + assert_eq!(evaluator_request(&request), full_evaluator_request()); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §package-request + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §opt-ins + #[test] + fn evaluator_request_lacks_what_the_package_request_lacks() { + let body = json!({ + "Operation": "Install", + "Manager": "Winget", + "Source": { "Name": "winget" }, + "Package": { "Id": "Git.Git" }, + "Elevation": "NonElevated", + }); + let expected = eval::Request { + operation: eval::Operation::Install, + manager: eval::Manager::Winget, + source: Some(eval::Source { + name: "winget".to_owned(), + }), + package: eval::Package { + id: "Git.Git".to_owned(), + version: None, + architecture: None, + }, + scope: None, + elevation: eval::Elevation::NonElevated, + opt_ins: eval::OptIns { + interactive: false, + skip_hash_check: false, + custom_install_location: None, + custom_parameters: None, + installer_arguments: None, + pre_post_commands: None, + kill_before_operation: None, + uninstall_previous: false, + no_upgrade: false, + }, + }; + + let with_empty_opt_ins = evaluation_request(&with(full_package_request(), "/OptIns", json!({}))); + + assert_eq!(evaluator_request(&evaluation_request(&body)), expected); + assert_eq!( + evaluator_request(&with_empty_opt_ins).opt_ins, + expected.opt_ins, + "OptIns set to {{}} asks for no opt-in" + ); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §opt-ins + #[test] + fn evaluator_request_asks_for_exactly_the_opt_ins_of_the_package_request() { + let full = full_package_request(); + let all = full_evaluator_request().opt_ins; + let asked = |opt_ins: &eval::OptIns| { + [ + opt_ins.interactive, + opt_ins.skip_hash_check, + opt_ins.custom_install_location.is_some(), + opt_ins.custom_parameters.is_some(), + opt_ins.installer_arguments.is_some(), + opt_ins.pre_post_commands.is_some(), + opt_ins.kill_before_operation.is_some(), + opt_ins.uninstall_previous, + opt_ins.no_upgrade, + ] + }; + assert_eq!(asked(&all), [true; 9]); + + let wrong: Vec<&str> = OPT_INS + .iter() + .copied() + .enumerate() + .filter(|(index, name)| { + let only = with(full.clone(), "/OptIns", json!({ *name: full["OptIns"][*name] })); + let mut expected = [false; 9]; + expected[*index] = true; + + asked(&evaluator_request(&evaluation_request(&only)).opt_ins) != expected + }) + .map(|(_, name)| name) + .collect(); + + assert_eq!(wrong, NONE); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §opt-ins + #[test] + fn evaluator_request_keeps_a_lone_pre_or_post_command() { + let pre = with( + full_package_request(), + "/OptIns/PrePostCommands", + json!({ "Pre": "echo before" }), + ); + let post = with( + full_package_request(), + "/OptIns/PrePostCommands", + json!({ "Post": "echo after" }), + ); + + assert_eq!( + evaluator_request(&evaluation_request(&pre)).opt_ins.pre_post_commands, + Some(eval::PrePostCommands { + pre: Some("echo before".to_owned()), + post: None, + }) + ); + assert_eq!( + evaluator_request(&evaluation_request(&post)).opt_ins.pre_post_commands, + Some(eval::PrePostCommands { + pre: None, + post: Some("echo after".to_owned()), + }) + ); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §execute + #[test] + fn execution_request_gives_the_evaluator_request_of_its_package_request() { + let mut body = full_package_request(); + body["RequestId"] = json!("request-1"); + + let request = read_execution_request(body.to_string().as_bytes()).expect("execution request"); + + assert_eq!(evaluator_request(&request.package_request()), full_evaluator_request()); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.policy.md §def-decision + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §package-request + #[test] + fn evaluator_decides_the_request_of_a_package_request_at_its_limits() { + const POLICY: &[u8] = br#"{"PolicyFormatVersion":"2.0.0","Metadata":{"Id":"policy","Publisher":"publisher","Revision":1,"PublishedAt":"2026-01-01T00:00:00Z"},"TrustedSources":[],"Rules":[]}"#; + let policy = eval::parse_policy(POLICY).expect("valid policy"); + let time: eval::Timestamp = "2026-06-01T00:00:00Z".parse().expect("timestamp"); + let at_its_limits = json!({ + "Operation": "Install", + "Manager": "Winget", + "Source": { "Name": "é".repeat(64) }, + "Package": { "Id": format!("{}abcdefghi", "Az09._+@/:[],#$%{}-".repeat(13)), "Version": "é".repeat(64) }, + "Scope": "User", + "Elevation": "NonElevated", + "OptIns": { + "CustomInstallLocation": { "Path": "é".repeat(1024) }, + "CustomParameters": { "Values": vec!["é".repeat(256); 64] }, + "InstallerArguments": { "Arguments": "é".repeat(1024), "Mode": "Append" }, + "PrePostCommands": { "Pre": "é".repeat(1024), "Post": "é".repeat(1024) }, + "KillBeforeOperation": { "Processes": vec!["é".repeat(64); 64] }, + }, + }); + assert_eq!(at_its_limits["Package"]["Id"].as_str().map(str::len), Some(256)); + + let decided = [full_package_request(), at_its_limits] + .iter() + .map(|body| eval::evaluate(&policy, &evaluator_request(&evaluation_request(body)), time).is_ok()) + .collect::>(); + + assert_eq!(decided, [true, true]); + } + + fn bypass_request(body: &Value) -> v2::BypassRequest { + read_bypass_request(body.to_string().as_bytes()).expect("bypass request") + } + + /// A body with every member of a bypass request. + fn full_bypass_request() -> Value { + json!({ + "RequestId": "request-1", + "Operation": "Update", + "Manager": "Chocolatey", + "Source": { "Name": "community" }, + "Package": { "Id": "git.install", "Version": "2.45.1" }, + "Scope": "Machine", + "Elevation": "Elevated", + "OptIns": { "NoUpgrade": {} }, + }) + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §bypass-reading + #[test] + fn bypass_request_with_source_is_read_as_the_package_request_with_its_members() { + let body = full_bypass_request(); + let listed = v2::SourceName::parse("listed").expect("source name"); + + let read = bypass_package_request(&bypass_request(&body), Some(&listed)); + + assert_eq!(read, Some(evaluation_request(&without(body, "", "RequestId")))); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §bypass-reading + #[test] + fn bypass_request_with_only_required_members_is_read_as_the_package_request_with_its_members() { + let body = json!({ + "RequestId": "request-1", + "Operation": "Install", + "Manager": "Winget", + "Source": { "Name": "winget" }, + "Package": { "Id": "Git.Git" }, + "Elevation": "NonElevated", + }); + + let read = bypass_package_request(&bypass_request(&body), None); + + assert_eq!(read, Some(evaluation_request(&without(body, "", "RequestId")))); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §bypass-reading + #[test] + fn bypass_request_without_source_is_read_with_the_source_name_its_list_gives() { + let body = without(full_bypass_request(), "", "Source"); + let listed = v2::SourceName::parse("listed").expect("source name"); + let mut expected = without(full_bypass_request(), "", "RequestId"); + expected["Source"] = json!({ "Name": "listed" }); + + let read = bypass_package_request(&bypass_request(&body), Some(&listed)); + + assert_eq!(read, Some(evaluation_request(&expected))); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §bypass-reading + #[test] + fn bypass_request_without_any_source_name_is_no_package_request() { + let body = without(full_bypass_request(), "", "Source"); + + assert_eq!(bypass_package_request(&bypass_request(&body), None), None); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §decision + #[test] + fn decision_is_written_with_the_members_of_its_table() { + let evaluated = eval::Decision { + outcome: eval::Outcome::Deny, + check: eval::Check::DenyRule, + rules: vec![ + eval::DecisionRule { + id: "block-games".to_owned(), + reason: Some("Games are not allowed.".to_owned()), + }, + eval::DecisionRule { + id: "0.second_rule:b".to_owned(), + reason: None, + }, + ], + opt_ins: vec![eval::OptIn::SkipHashCheck, eval::OptIn::NoUpgrade], + audited: false, + }; + + let written = serde_json::to_value(decision(&evaluated).expect("decision")).expect("decision"); + + assert_eq!( + written, + json!({ + "Outcome": "Deny", + "Check": "DenyRule", + "Rules": [ + { "Id": "block-games", "Reason": "Games are not allowed." }, + { "Id": "0.second_rule:b" }, + ], + "OptIns": ["SkipHashCheck", "NoUpgrade"], + "Audited": false, + }) + ); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §decision + #[test] + fn audited_decision_without_rules_is_written_with_empty_lists() { + let evaluated = eval::Decision { + outcome: eval::Outcome::Allow, + check: eval::Check::DefaultDeny, + rules: Vec::new(), + opt_ins: Vec::new(), + audited: true, + }; + + let written = serde_json::to_value(decision(&evaluated).expect("decision")).expect("decision"); + + assert_eq!( + written, + json!({ "Outcome": "Allow", "Check": "DefaultDeny", "Rules": [], "OptIns": [], "Audited": true }) + ); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.policy.md §rules + #[test] + fn decision_naming_a_rule_id_no_policy_holds_is_an_error() { + let ids: Vec<&str> = ["", "-rule", "rule id", "règle"] + .into_iter() + .filter(|id| { + let evaluated = eval::Decision { + outcome: eval::Outcome::Deny, + check: eval::Check::DenyRule, + rules: vec![eval::DecisionRule { + id: (*id).to_owned(), + reason: None, + }], + opt_ins: Vec::new(), + audited: false, + }; + + decision(&evaluated).is_ok() + }) + .collect(); + + assert_eq!(ids, NONE); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §policy-errors + #[test] + fn policy_error_is_written_with_its_code_and_pointer() { + let located = eval::ValidationError { + code: eval::ErrorCode::MissingKey, + pointer: "/Rules/0/Select".to_owned(), + }; + let whole_document = eval::ValidationError { + code: eval::ErrorCode::MalformedDocument, + pointer: String::new(), + }; + + assert_eq!( + serde_json::to_value(policy_error(&located)).expect("policy error"), + json!({ "Code": "MissingKey", "Pointer": "/Rules/0/Select" }) + ); + assert_eq!( + serde_json::to_value(policy_error(&whole_document)).expect("policy error"), + json!({ "Code": "MalformedDocument", "Pointer": "" }) + ); + } + + fn instant(year: i32, month: u32, day: u32, hour: u32, minute: u32, second: u32, nanosecond: u32) -> DateTime { + Utc.with_ymd_and_hms(year, month, day, hour, minute, second) + .single() + .and_then(|instant| instant.with_nanosecond(nanosecond)) + .expect("an instant") + } + + /// Returns whether `text` is a timestamp with the offset `Z` that names `instant`. + /// + /// The evaluator decides whether the text is a timestamp, and `chrono` which instant it names. + fn names_instant_with_offset_z(text: &str, instant: DateTime) -> bool { + text.ends_with('Z') + && text.parse::().is_ok() + && DateTime::parse_from_rfc3339(text).is_ok_and(|named| named == instant) + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §values + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.policy.md §timestamps + // oracle: reference now-policy-eval `Timestamp` and chrono `parse_from_rfc3339` + #[test] + fn timestamp_names_its_instant_with_the_offset_z() { + let instants = [ + ("whole second", instant(2026, 12, 1, 13, 5, 9, 0)), + ("half a second", instant(2026, 12, 1, 13, 5, 9, 500_000_000)), + ("one nanosecond", instant(2026, 12, 1, 13, 5, 9, 1)), + ( + "last nanosecond of a second", + instant(2026, 12, 1, 13, 5, 9, 999_999_999), + ), + ("leap day", instant(2024, 2, 29, 0, 0, 0, 0)), + ("first instant of year 0001", instant(1, 1, 1, 0, 0, 0, 0)), + ( + "last instant of year 9999", + instant(9999, 12, 31, 23, 59, 59, 999_999_999), + ), + ]; + + let wrong: Vec<&str> = instants + .iter() + .filter(|(_, instant)| { + !timestamp(*instant).is_ok_and(|written| names_instant_with_offset_z(written.as_str(), *instant)) + }) + .map(|(name, _)| *name) + .collect(); + + assert_eq!(wrong, NONE); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.policy.md §timestamps + #[test] + fn instant_in_a_year_no_timestamp_names_is_an_error() { + let instants = [ + ("year 0000", instant(0, 12, 31, 23, 59, 59, 0)), + ("year 10000", instant(10000, 1, 1, 0, 0, 0, 0)), + ("year before 0000", instant(-1, 6, 1, 0, 0, 0, 0)), + ]; + + let written: Vec<&str> = instants + .iter() + .filter(|(_, instant)| timestamp(*instant).is_ok()) + .map(|(name, _)| *name) + .collect(); + + assert_eq!(written, NONE); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.policy.md §timestamps + #[test] + fn timestamp_of_a_leap_second_has_seconds_up_to_59() { + // `chrono` holds a leap second as the second 59 with a nanosecond of 1_000_000_000 or more. + let leap_second = instant(2016, 12, 31, 23, 59, 59, 1_500_000_000); + + let seconds = timestamp(leap_second).ok().and_then(|written| { + written + .as_str() + .get(17..19) + .and_then(|seconds| seconds.parse::().ok()) + }); + + assert!(seconds.is_none_or(|seconds| seconds <= 59), "seconds are {seconds:?}"); + } +} diff --git a/crates/now-package-broker/src/v2/wire/error.rs b/crates/now-package-broker/src/v2/wire/error.rs new file mode 100644 index 000000000..27bbde780 --- /dev/null +++ b/crates/now-package-broker/src/v2/wire/error.rs @@ -0,0 +1,375 @@ +//! Building error responses ([§errors]). +//! +//! A response built here is always one the contract allows. +//! A member is written only with a code whose row has it, and a response whose code needs a member it was not given +//! becomes `InternalError`, which may replace every code that has such a member. +//! +//! [§errors]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#errors + +use now_policy_api::v2; + +/// The most bytes a `Message` has. +const MESSAGE_MAX_LEN: usize = 2048; + +/// Returns the error response for a code whose response has no member besides `Code` and `Message`. +pub fn error_response(code: v2::ErrorCode, text: &str) -> v2::ErrorResponse { + build(code, text, None, None, None) +} + +/// Returns the `NotRunnable` response for a request that `decision` allows ([§not-runnable]). +/// +/// [§not-runnable]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#not-runnable +pub fn not_runnable(decision: v2::Decision, text: &str) -> v2::ErrorResponse { + build(v2::ErrorCode::NotRunnable, text, Some(decision), None, None) +} + +/// Returns the error response for a code whose response carries the policy management state after the request. +pub fn policy_state_error(code: v2::ErrorCode, management: v2::PolicyManagement, text: &str) -> v2::ErrorResponse { + build(code, text, None, Some(management), None) +} + +/// Returns the `InvalidPolicy` response for a document with these validation errors. +pub fn invalid_policy(errors: Vec, text: &str) -> v2::ErrorResponse { + build(v2::ErrorCode::InvalidPolicy, text, None, None, Some(errors)) +} + +/// Returns the longest start of `text` that a `Message` holds. +pub fn message(text: &str) -> v2::Message { + let mut len = text.len().min(MESSAGE_MAX_LEN); + + while !text.is_char_boundary(len) { + len -= 1; + } + + // INVARIANT: `len` is at most `MESSAGE_MAX_LEN`, the only limit of a message, and a character boundary of `text`. + v2::Message::parse(&text[..len]).expect("text of at most 2048 bytes is a message") +} + +/// The member that the response of a code has besides `Code` and `Message`. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Member { + None, + Decision, + Management, + Errors, +} + +fn member_of(code: v2::ErrorCode) -> Member { + use v2::ErrorCode as Code; + + match code { + Code::NotRunnable => Member::Decision, + Code::StaleStoreToken | Code::PolicyNotWritable | Code::RevisionNotHigher | Code::ActivationFailed => { + Member::Management + } + Code::InvalidPolicy => Member::Errors, + Code::BrokerBusy + | Code::UnknownEndpoint + | Code::UnsupportedMediaType + | Code::Unauthenticated + | Code::AdministratorRequired + | Code::RequestTooLarge + | Code::BadRequest + | Code::PolicyUnavailable + | Code::RequestIdConflict + | Code::BypassTokenRejected + | Code::ProtectedPackage + | Code::BypassRequestUnreadable + | Code::OperationNotFound + | Code::PersistenceFailed + | Code::InternalError => Member::None, + } +} + +fn build( + code: v2::ErrorCode, + text: &str, + decision: Option, + management: Option, + errors: Option>, +) -> v2::ErrorResponse { + let member = member_of(code); + + // A not-runnable request was allowed, and an invalid document has an error. + let decision = decision.filter(|decision| member == Member::Decision && decision.outcome == v2::Outcome::Allow); + let management = management.filter(|_| member == Member::Management); + let errors = errors.filter(|errors| member == Member::Errors && !errors.is_empty()); + + let has_its_member = match member { + Member::None => true, + Member::Decision => decision.is_some(), + Member::Management => management.is_some(), + Member::Errors => errors.is_some(), + }; + + if has_its_member { + v2::ErrorResponse { + code, + message: message(text), + decision, + management, + errors, + } + } else { + v2::ErrorResponse { + code: v2::ErrorCode::InternalError, + message: message(text), + decision: None, + management: None, + errors: None, + } + } +} +#[cfg(test)] +mod tests { + use serde_json::{Value, json}; + + use super::*; + + const NONE: &[&str] = &[]; + + /// The table of error codes of "Errors": each code and its HTTP status. + const CODES: [(&str, u16); 21] = [ + ("BrokerBusy", 503), + ("UnknownEndpoint", 404), + ("UnsupportedMediaType", 415), + ("Unauthenticated", 401), + ("AdministratorRequired", 403), + ("RequestTooLarge", 413), + ("BadRequest", 400), + ("PolicyUnavailable", 503), + ("RequestIdConflict", 409), + ("NotRunnable", 422), + ("BypassTokenRejected", 403), + ("ProtectedPackage", 422), + ("BypassRequestUnreadable", 422), + ("OperationNotFound", 404), + ("StaleStoreToken", 409), + ("PolicyNotWritable", 409), + ("InvalidPolicy", 422), + ("RevisionNotHigher", 409), + ("PersistenceFailed", 500), + ("ActivationFailed", 500), + ("InternalError", 500), + ]; + + /// The codes whose response has `Management`. + const MANAGEMENT_CODES: [&str; 4] = [ + "StaleStoreToken", + "PolicyNotWritable", + "RevisionNotHigher", + "ActivationFailed", + ]; + + /// The codes whose response has a member besides `Code` and `Message`. + const CODES_WITH_A_MEMBER: [&str; 6] = [ + "NotRunnable", + "StaleStoreToken", + "PolicyNotWritable", + "InvalidPolicy", + "RevisionNotHigher", + "ActivationFailed", + ]; + + fn code(name: &str) -> v2::ErrorCode { + serde_json::from_value(json!(name)).expect("error code") + } + + fn written(response: v2::ErrorResponse) -> Value { + serde_json::to_value(response).expect("error response") + } + + fn decision(outcome: &str) -> Value { + json!({ + "Outcome": outcome, + "Check": if outcome == "Allow" { "AllowRules" } else { "DefaultDeny" }, + "Rules": [], + "OptIns": [], + "Audited": false, + }) + } + + fn management() -> Value { + json!({ + "State": "Missing", + "Path": "C:\\ProgramData\\Devolutions\\Agent\\policy.json", + "StoreToken": "token-1", + }) + } + + fn policy_errors() -> Value { + json!([{ "Code": "MissingKey", "Pointer": "/Rules" }]) + } + + fn read(value: Value) -> T { + serde_json::from_value(value).expect("a member of an error response") + } + + fn internal_error() -> Value { + json!({ "Code": "InternalError", "Message": "text" }) + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §errors + #[test] + fn every_code_has_the_http_status_of_the_table() { + let statuses: Vec<(&str, u16)> = CODES + .iter() + .map(|(name, _)| (*name, code(name).http_status())) + .collect(); + + assert_eq!(statuses, CODES); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §errors + #[test] + fn response_of_a_code_without_other_members_has_code_and_message() { + let wrong: Vec<&str> = CODES + .iter() + .map(|(name, _)| *name) + .filter(|name| !CODES_WITH_A_MEMBER.contains(name)) + .filter(|name| written(error_response(code(name), "text")) != json!({ "Code": name, "Message": "text" })) + .collect(); + + assert_eq!(wrong, NONE); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §errors + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §not-runnable + #[test] + fn not_runnable_response_carries_the_decision() { + assert_eq!( + written(not_runnable(read(decision("Allow")), "text")), + json!({ "Code": "NotRunnable", "Message": "text", "Decision": decision("Allow") }) + ); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §errors + #[test] + fn response_of_a_code_with_management_carries_it() { + let wrong: Vec<&str> = MANAGEMENT_CODES + .into_iter() + .filter(|name| { + written(policy_state_error(code(name), read(management()), "text")) + != json!({ "Code": name, "Message": "text", "Management": management() }) + }) + .collect(); + + assert_eq!(wrong, NONE); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §errors + #[test] + fn invalid_policy_response_carries_the_errors() { + assert_eq!( + written(invalid_policy(read(policy_errors()), "text")), + json!({ "Code": "InvalidPolicy", "Message": "text", "Errors": policy_errors() }) + ); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §errors + #[test] + fn management_is_left_out_of_a_response_whose_code_has_none() { + let wrong: Vec<&str> = CODES + .iter() + .map(|(name, _)| *name) + .filter(|name| !CODES_WITH_A_MEMBER.contains(name)) + .filter(|name| { + written(policy_state_error(code(name), read(management()), "text")) + != json!({ "Code": name, "Message": "text" }) + }) + .collect(); + + assert_eq!(wrong, NONE); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §errors + #[test] + fn response_without_the_member_of_its_code_is_internal_error() { + let wrong: Vec<&str> = CODES_WITH_A_MEMBER + .into_iter() + .filter(|name| written(error_response(code(name), "text")) != internal_error()) + .collect(); + + assert_eq!(wrong, NONE); + assert_eq!( + written(policy_state_error(code("NotRunnable"), read(management()), "text")), + internal_error() + ); + assert_eq!( + written(policy_state_error(code("InvalidPolicy"), read(management()), "text")), + internal_error() + ); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §not-runnable + #[test] + fn not_runnable_response_with_a_denying_decision_is_internal_error() { + assert_eq!(written(not_runnable(read(decision("Deny")), "text")), internal_error()); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §errors + #[test] + fn invalid_policy_response_without_an_error_is_internal_error() { + assert_eq!(written(invalid_policy(Vec::new(), "text")), internal_error()); + } + + /// Texts around the limit of a message, each with a name. + fn texts() -> Vec<(&'static str, String)> { + vec![ + ("empty", String::new()), + ("short", "operation not found".to_owned()), + ("2048 bytes", "m".repeat(2048)), + ("2049 bytes", "m".repeat(2049)), + ("far over the limit", "m".repeat(100_000)), + ("2048 bytes in 1024 characters", "é".repeat(1024)), + ("2050 bytes in 1025 characters", "é".repeat(1025)), + ("limit inside a character of 2 bytes", format!("m{}", "é".repeat(1024))), + ("limit inside a character of 3 bytes", format!("m{}", "€".repeat(683))), + ( + "limit inside a character of 4 bytes", + format!("mmm{}", "😀".repeat(512)), + ), + ] + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §errors + #[test] + fn message_has_at_most_2048_bytes() { + let too_long: Vec<&str> = texts() + .iter() + .filter(|(_, text)| { + let response = written(error_response(code("InternalError"), text)); + !response["Message"] + .as_str() + .is_some_and(|message| message.len() <= 2048) + }) + .map(|(name, _)| *name) + .collect(); + + assert_eq!(too_long, NONE); + } + + // oracle: mutant a message cut shorter than the limit requires, or not a start of its text + #[test] + fn message_is_the_longest_start_of_its_text_within_the_limit() { + let expected = [ + String::new(), + "operation not found".to_owned(), + "m".repeat(2048), + "m".repeat(2048), + "m".repeat(2048), + "é".repeat(1024), + "é".repeat(1024), + format!("m{}", "é".repeat(1023)), + format!("m{}", "€".repeat(682)), + format!("mmm{}", "😀".repeat(511)), + ]; + + let messages: Vec = texts() + .iter() + .map(|(_, text)| message(text).as_str().to_owned()) + .collect(); + + assert_eq!(messages, expected); + } +} diff --git a/crates/now-package-broker/src/v2/wire/mod.rs b/crates/now-package-broker/src/v2/wire/mod.rs index 048598d95..727a90ee5 100644 --- a/crates/now-package-broker/src/v2/wire/mod.rs +++ b/crates/now-package-broker/src/v2/wire/mod.rs @@ -1 +1,18 @@ //! Requests and responses of the 2.0 encoding. +//! +//! The message types are those of [`now_policy_api::v2`]. +//! This module matches a request to its endpoint, reads request bodies into those types, converts between them and the +//! evaluator's types, and builds error responses, so the routes only move values. + +mod convert; +mod error; +mod read; +mod route; + +pub use convert::{bypass_package_request, decision, evaluator_request, policy_error, timestamp}; +pub use error::{error_response, invalid_policy, message, not_runnable, policy_state_error}; +pub use read::{ + BadRequest, read_bypass_request, read_evaluation_request, read_execution_request, read_replacement_request, + read_validation_request, +}; +pub use route::{OperationNotFound, Route, UnknownEndpoint, route}; diff --git a/crates/now-package-broker/src/v2/wire/read.rs b/crates/now-package-broker/src/v2/wire/read.rs new file mode 100644 index 000000000..20ac78989 --- /dev/null +++ b/crates/now-package-broker/src/v2/wire/read.rs @@ -0,0 +1,1395 @@ +//! Reading request bodies ([§json]). +//! +//! [§json]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#json + +use core::fmt; + +use now_policy_api::v2; +use serde::de::DeserializeOwned; + +/// The request has a malformed body, or a request object the contract does not allow ([§errors]). +/// +/// [§errors]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#errors +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct BadRequest; + +impl fmt::Display for BadRequest { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("request body is malformed or is not a request the endpoint allows") + } +} + +impl core::error::Error for BadRequest {} + +/// Reads the body of an evaluation request ([§evaluate]). +/// +/// [§evaluate]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#evaluate +pub fn read_evaluation_request(body: &[u8]) -> Result { + read(body) +} + +/// Reads the body of an execution request ([§execute]). +/// +/// [§execute]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#execute +pub fn read_execution_request(body: &[u8]) -> Result { + read(body) +} + +/// Reads the body of a bypass request ([§bypass]). +/// +/// [§bypass]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#bypass +pub fn read_bypass_request(body: &[u8]) -> Result { + read(body) +} + +/// Reads the body of a policy validation request ([§validation]). +/// +/// [§validation]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#validation +pub fn read_validation_request(body: &[u8]) -> Result { + read(body) +} + +/// Reads the body of a policy replacement request ([§replacement]). +/// +/// [§replacement]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#replacement +pub fn read_replacement_request(body: &[u8]) -> Result { + read(body) +} + +fn read(body: &[u8]) -> Result { + serde_json::from_slice(body).map_err(|_| BadRequest) +} + +#[cfg(test)] +mod tests { + use serde_json::{Value, json}; + + use super::*; + + const NONE: &[&str] = &[]; + + /// The manager identifiers of the policy contract's "Managers". + const MANAGERS: [&str; 17] = [ + "Winget", + "PowerShell", + "PowerShell7", + "Apt", + "Bun", + "Cargo", + "Chocolatey", + "Dnf", + "Dotnet", + "Flatpak", + "Homebrew", + "Npm", + "Pacman", + "Pip", + "Scoop", + "Snap", + "Vcpkg", + ]; + + /// The opt-ins whose value is `{}`. + const FLAG_OPT_INS: [&str; 4] = ["Interactive", "SkipHashCheck", "UninstallPrevious", "NoUpgrade"]; + + /// Values that are no string, each with a name. + fn non_strings() -> Vec<(&'static str, Value)> { + vec![ + ("null", json!(null)), + ("a number", json!(1)), + ("a boolean", json!(true)), + ("a list", json!(["x"])), + ("an object", json!({})), + ] + } + + /// Values that are no object, each with a name. + fn non_objects() -> Vec<(&'static str, Value)> { + vec![ + ("null", json!(null)), + ("a number", json!(1)), + ("a boolean", json!(true)), + ("a string", json!("x")), + ("a list", json!([])), + ] + } + + /// Request bodies that each differ from one base by the change their name tells. + struct Cases { + base: Value, + cases: Vec<(String, Value)>, + } + + impl Cases { + fn new(base: Value) -> Self { + Self { + base, + cases: Vec::new(), + } + } + + /// Adds the base with the member at `pointer` set to `value`. + fn set(self, name: &str, pointer: &str, value: Value) -> Self { + self.set_all(name, &[(pointer, value)]) + } + + /// Adds the base with each member of `changes` set. + fn set_all(mut self, name: &str, changes: &[(&str, Value)]) -> Self { + let mut body = self.base.clone(); + for (pointer, value) in changes { + *slot(&mut body, pointer) = value.clone(); + } + self.cases.push((name.to_owned(), body)); + self + } + + /// Adds the base without the member at `pointer`. + fn unset(mut self, name: &str, pointer: &str) -> Self { + self.cases.push((name.to_owned(), without(&self.base, pointer))); + self + } + + /// Returns the names of the cases whose body `holds` is false for. + fn failing(&self, holds: impl Fn(&[u8]) -> bool) -> Vec<&str> { + self.cases + .iter() + .filter(|(_, body)| !holds(body.to_string().as_bytes())) + .map(|(name, _)| name.as_str()) + .collect() + } + } + + /// Returns the value at `pointer`, creating the objects on the way. + fn slot<'a>(body: &'a mut Value, pointer: &str) -> &'a mut Value { + pointer.split('/').skip(1).fold(body, |value, key| { + value + .as_object_mut() + .expect("an object on the way") + .entry(key) + .or_insert_with(|| json!({})) + }) + } + + fn with(base: &Value, pointer: &str, value: Value) -> Value { + let mut body = base.clone(); + *slot(&mut body, pointer) = value; + body + } + + fn without(base: &Value, pointer: &str) -> Value { + let (parent, key) = pointer.rsplit_once('/').expect("a pointer to a member"); + let mut body = base.clone(); + slot(&mut body, parent) + .as_object_mut() + .expect("an object holding the member") + .remove(key) + .expect("the member to remove"); + body + } + + fn bytes(body: &Value) -> Vec { + body.to_string().into_bytes() + } + + /// Returns the names of the bodies `holds` is false for. + fn failing_bodies<'a>(bodies: &'a [(&'a str, Vec)], holds: impl Fn(&[u8]) -> bool) -> Vec<&'a str> { + bodies + .iter() + .filter(|(_, body)| !holds(body)) + .map(|(name, _)| *name) + .collect() + } + + fn package_request() -> Value { + json!({ + "Operation": "Install", + "Manager": "Winget", + "Source": { "Name": "winget" }, + "Package": { "Id": "Git.Git" }, + "Elevation": "NonElevated", + }) + } + + fn execution_request() -> Value { + with(&package_request(), "/RequestId", json!("request-1")) + } + + /// A value of each opt-in key, taken from the table of "Opt-ins". + fn opt_ins() -> Value { + json!({ + "Interactive": {}, + "SkipHashCheck": {}, + "CustomInstallLocation": { "Path": "D:\\Tools\\Git" }, + "CustomParameters": { "Values": ["--params", "/NoShellIntegration"] }, + "InstallerArguments": { "Arguments": "/VERYSILENT", "Mode": "Append" }, + "PrePostCommands": { "Pre": "echo before", "Post": "echo after" }, + "KillBeforeOperation": { "Processes": ["git.exe", "bash.exe"] }, + "UninstallPrevious": {}, + "NoUpgrade": {}, + }) + } + + fn evaluation_is_ok(body: &[u8]) -> bool { + read_evaluation_request(body).is_ok() + } + + fn evaluation_is_bad(body: &[u8]) -> bool { + read_evaluation_request(body) == Err(BadRequest) + } + + fn execution_is_ok(body: &[u8]) -> bool { + read_execution_request(body).is_ok() + } + + fn execution_is_bad(body: &[u8]) -> bool { + read_execution_request(body) == Err(BadRequest) + } + + fn bypass_is_ok(body: &[u8]) -> bool { + read_bypass_request(body).is_ok() + } + + fn bypass_is_bad(body: &[u8]) -> bool { + read_bypass_request(body) == Err(BadRequest) + } + + fn validation_is_ok(body: &[u8]) -> bool { + read_validation_request(body).is_ok() + } + + fn validation_is_bad(body: &[u8]) -> bool { + read_validation_request(body) == Err(BadRequest) + } + + fn replacement_is_ok(body: &[u8]) -> bool { + read_replacement_request(body).is_ok() + } + + fn replacement_is_bad(body: &[u8]) -> bool { + read_replacement_request(body) == Err(BadRequest) + } + + /// Changes that keep a package request, an execution request and a bypass request with `Source` well-formed. + fn accepted_in_every_package_request(mut cases: Cases) -> Cases { + for manager in MANAGERS { + cases = cases.set(&format!("manager {manager}"), "/Manager", json!(manager)); + } + + cases + .set("operation Update", "/Operation", json!("Update")) + .set("scope User", "/Scope", json!("User")) + .set_all( + "scope Machine, elevated", + &[("/Scope", json!("Machine")), ("/Elevation", json!("Elevated"))], + ) + .set("no scope, elevated", "/Elevation", json!("Elevated")) + .set("source name of 1 byte", "/Source/Name", json!("w")) + .set("source name of 128 bytes", "/Source/Name", json!("s".repeat(128))) + .set( + "source name of 128 bytes in 64 characters", + "/Source/Name", + json!("é".repeat(64)), + ) + .set("package id of 1 character", "/Package/Id", json!("g")) + .set("package id of 256 characters", "/Package/Id", json!("g".repeat(256))) + .set( + "package id with every allowed character", + "/Package/Id", + json!("Az09._+@/:[],#$%{}-"), + ) + .set("package id starting with a hyphen", "/Package/Id", json!("-g")) + .set("version of 1 byte", "/Package/Version", json!("2")) + .set("version of 128 bytes", "/Package/Version", json!("2".repeat(128))) + .set( + "version of 128 bytes in 64 characters", + "/Package/Version", + json!("é".repeat(64)), + ) + .set("empty OptIns", "/OptIns", json!({})) + .set("NoUpgrade", "/OptIns/NoUpgrade", json!({})) + } + + /// Changes that keep a package request and an execution request well-formed, and that a bypass request does not + /// allow. + fn accepted_in_a_full_package_request(mut cases: Cases) -> Cases { + for architecture in ["X86", "X64", "Arm64", "Neutral"] { + cases = cases.set( + &format!("architecture {architecture}"), + "/Package/Architecture", + json!(architecture), + ); + } + + for opt_in in FLAG_OPT_INS { + cases = cases.set(&format!("opt-in {opt_in}"), &format!("/OptIns/{opt_in}"), json!({})); + } + + cases + .set("operation Uninstall", "/Operation", json!("Uninstall")) + .set( + "install location of 1 byte", + "/OptIns/CustomInstallLocation/Path", + json!("C"), + ) + .set( + "install location of 2048 bytes", + "/OptIns/CustomInstallLocation/Path", + json!("C".repeat(2048)), + ) + .set("1 custom parameter", "/OptIns/CustomParameters/Values", json!(["-q"])) + .set( + "64 custom parameters", + "/OptIns/CustomParameters/Values", + json!(vec!["-q"; 64]), + ) + .set( + "custom parameter of 512 bytes", + "/OptIns/CustomParameters/Values", + json!(["q".repeat(512)]), + ) + .set( + "installer arguments appended", + "/OptIns/InstallerArguments", + json!({ "Arguments": "/S", "Mode": "Append" }), + ) + .set( + "installer arguments replacing", + "/OptIns/InstallerArguments", + json!({ "Arguments": "/S", "Mode": "Replace" }), + ) + .set( + "installer arguments of 2048 bytes", + "/OptIns/InstallerArguments", + json!({ "Arguments": "S".repeat(2048), "Mode": "Append" }), + ) + .set("Pre alone", "/OptIns/PrePostCommands", json!({ "Pre": "echo" })) + .set("Post alone", "/OptIns/PrePostCommands", json!({ "Post": "echo" })) + .set( + "Pre and Post", + "/OptIns/PrePostCommands", + json!({ "Pre": "echo", "Post": "echo" }), + ) + .set( + "commands of 2048 bytes", + "/OptIns/PrePostCommands", + json!({ "Pre": "e".repeat(2048), "Post": "e".repeat(2048) }), + ) + .set( + "1 process", + "/OptIns/KillBeforeOperation/Processes", + json!(["notepad.exe"]), + ) + .set( + "64 processes", + "/OptIns/KillBeforeOperation/Processes", + json!(vec!["notepad.exe"; 64]), + ) + .set( + "image name of 128 bytes", + "/OptIns/KillBeforeOperation/Processes", + json!(["n".repeat(128)]), + ) + .set_all( + "every opt-in through a manager the broker builds no command for", + &[("/Manager", json!("Apt")), ("/OptIns", opt_ins())], + ) + } + + /// Changes that make a package request, an execution request and a bypass request with `Source` `BadRequest`. + fn rejected_in_every_package_request(mut cases: Cases) -> Cases { + for member in [ + "/Operation", + "/Manager", + "/Source/Name", + "/Package/Id", + "/Package/Version", + "/Scope", + "/Elevation", + ] { + for (kind, value) in non_strings() { + cases = cases.set(&format!("{member} is {kind}"), member, value); + } + } + + for member in ["/Source", "/Package", "/OptIns"] { + for (kind, value) in non_objects() { + cases = cases.set(&format!("{member} is {kind}"), member, value); + } + } + + for character in [ + ' ', '*', '?', '\\', '"', '\'', '!', '(', ')', '&', '=', '~', ';', '<', '>', '|', '^', '`', 'é', '\n', '\0', + ] { + cases = cases.set( + &format!("package id with {character:?}"), + "/Package/Id", + json!(format!("Git{character}Git")), + ); + } + + for (member, values) in [ + ("/Operation", ["install", "INSTALL", "Remove", ""]), + ("/Manager", ["winget", "WinGet", "Brew", ""]), + ("/Scope", ["user", "MACHINE", "System", ""]), + ("/Elevation", ["elevated", "nonElevated", "Admin", ""]), + ] { + for value in values { + cases = cases.set(&format!("{member} is {value:?}"), member, json!(value)); + } + } + + cases + .unset("Operation is absent", "/Operation") + .unset("Manager is absent", "/Manager") + .unset("Package is absent", "/Package") + .unset("Elevation is absent", "/Elevation") + .unset("Source.Name is absent", "/Source/Name") + .unset("Package.Id is absent", "/Package/Id") + .set("Source is the list of its members", "/Source", json!(["winget"])) + .set("Package is the list of its members", "/Package", json!(["Git.Git"])) + .set("OptIns is the list of its members", "/OptIns", json!([{}])) + .set("NoUpgrade is a list", "/OptIns/NoUpgrade", json!([])) + .set("unknown member", "/Extra", json!("x")) + .set("member spelled in lower case", "/scope", json!("User")) + .set("unknown member of Source", "/Source/Url", json!("https://example.test")) + .set("unknown member of Package", "/Package/Channel", json!("beta")) + .set("unknown opt-in", "/OptIns/Unknown", json!({})) + .set("opt-in spelled in lower case", "/OptIns/noUpgrade", json!({})) + .set("empty source name", "/Source/Name", json!("")) + .set("source name of 129 bytes", "/Source/Name", json!("s".repeat(129))) + .set( + "source name of 130 bytes in 65 characters", + "/Source/Name", + json!("é".repeat(65)), + ) + .set("empty package id", "/Package/Id", json!("")) + .set("package id of 257 characters", "/Package/Id", json!("g".repeat(257))) + .set("empty version", "/Package/Version", json!("")) + .set("version of 129 bytes", "/Package/Version", json!("2".repeat(129))) + .set( + "version of 130 bytes in 65 characters", + "/Package/Version", + json!("é".repeat(65)), + ) + .set("scope Machine, non-elevated", "/Scope", json!("Machine")) + // oracle: contract Devolutions/now-libraries@09d6488736cf:policies/CONTRACT.wire.md §package-request + .set_all( + "scope User, elevated", + &[("/Scope", json!("User")), ("/Elevation", json!("Elevated"))], + ) + .set("NoUpgrade with a member", "/OptIns/NoUpgrade", json!({ "Extra": {} })) + } + + /// Changes that make a package request and an execution request `BadRequest`. + fn rejected_in_a_full_package_request(mut cases: Cases) -> Cases { + for (kind, value) in non_strings() { + for member in [ + "/Package/Architecture", + "/OptIns/CustomInstallLocation/Path", + "/OptIns/InstallerArguments/Arguments", + "/OptIns/InstallerArguments/Mode", + "/OptIns/PrePostCommands/Pre", + "/OptIns/PrePostCommands/Post", + ] { + let base_opt_ins = [("/OptIns", opt_ins()), (member, value.clone())]; + cases = cases.set_all(&format!("{member} is {kind}"), &base_opt_ins); + } + + cases = cases + .set( + &format!("a custom parameter is {kind}"), + "/OptIns/CustomParameters/Values", + json!([value]), + ) + .set( + &format!("an image name is {kind}"), + "/OptIns/KillBeforeOperation/Processes", + json!([value]), + ); + } + + for (kind, value) in non_objects() { + for opt_in in [ + "Interactive", + "SkipHashCheck", + "CustomInstallLocation", + "CustomParameters", + "InstallerArguments", + "PrePostCommands", + "KillBeforeOperation", + "UninstallPrevious", + "NoUpgrade", + ] { + cases = cases.set( + &format!("{opt_in} is {kind}"), + &format!("/OptIns/{opt_in}"), + value.clone(), + ); + } + } + + for opt_in in FLAG_OPT_INS { + cases = cases.set( + &format!("{opt_in} with a member"), + &format!("/OptIns/{opt_in}"), + json!({ "Extra": {} }), + ); + } + + for (name, list) in [ + ("is a string", json!("x")), + ("is an object", json!({})), + ("is null", json!(null)), + ("is empty", json!([])), + ("has an empty string", json!([""])), + ("has 65 entries", json!(vec!["x"; 65])), + ] { + cases = cases + .set( + &format!("CustomParameters.Values {name}"), + "/OptIns/CustomParameters/Values", + list.clone(), + ) + .set( + &format!("KillBeforeOperation.Processes {name}"), + "/OptIns/KillBeforeOperation/Processes", + list, + ); + } + + for architecture in ["x64", "ARM64", "Arm", ""] { + cases = cases.set( + &format!("architecture {architecture:?}"), + "/Package/Architecture", + json!(architecture), + ); + } + + cases + .unset("Source is absent", "/Source") + .set( + "CustomInstallLocation is the list of its members", + "/OptIns/CustomInstallLocation", + json!(["C:\\Apps"]), + ) + .set( + "CustomParameters is the list of its members", + "/OptIns/CustomParameters", + json!([["-q"]]), + ) + .set( + "InstallerArguments is the list of its members", + "/OptIns/InstallerArguments", + json!(["/S", "Append"]), + ) + .set( + "PrePostCommands is the list of its members", + "/OptIns/PrePostCommands", + json!(["echo", "echo"]), + ) + .set( + "KillBeforeOperation is the list of its members", + "/OptIns/KillBeforeOperation", + json!([["notepad.exe"]]), + ) + .set( + "CustomInstallLocation without Path", + "/OptIns/CustomInstallLocation", + json!({}), + ) + .set( + "empty install location", + "/OptIns/CustomInstallLocation/Path", + json!(""), + ) + .set( + "install location of 2049 bytes", + "/OptIns/CustomInstallLocation/Path", + json!("C".repeat(2049)), + ) + .set( + "unknown member of CustomInstallLocation", + "/OptIns/CustomInstallLocation", + json!({ "Path": "C:\\Apps", "Create": true }), + ) + .set("CustomParameters without Values", "/OptIns/CustomParameters", json!({})) + .set( + "custom parameter of 513 bytes", + "/OptIns/CustomParameters/Values", + json!(["q".repeat(513)]), + ) + .set( + "unknown member of CustomParameters", + "/OptIns/CustomParameters", + json!({ "Values": ["-q"], "Separator": " " }), + ) + .set( + "InstallerArguments without members", + "/OptIns/InstallerArguments", + json!({}), + ) + .set( + "InstallerArguments without Mode", + "/OptIns/InstallerArguments", + json!({ "Arguments": "/S" }), + ) + .set( + "InstallerArguments without Arguments", + "/OptIns/InstallerArguments", + json!({ "Mode": "Append" }), + ) + .set( + "empty installer arguments", + "/OptIns/InstallerArguments", + json!({ "Arguments": "", "Mode": "Append" }), + ) + .set( + "installer arguments of 2049 bytes", + "/OptIns/InstallerArguments", + json!({ "Arguments": "S".repeat(2049), "Mode": "Append" }), + ) + .set( + "installer arguments mode in lower case", + "/OptIns/InstallerArguments", + json!({ "Arguments": "/S", "Mode": "append" }), + ) + .set( + "installer arguments mode outside its set", + "/OptIns/InstallerArguments", + json!({ "Arguments": "/S", "Mode": "Override" }), + ) + .set( + "unknown member of InstallerArguments", + "/OptIns/InstallerArguments", + json!({ "Arguments": "/S", "Mode": "Append", "Quiet": true }), + ) + .set( + "PrePostCommands with neither command", + "/OptIns/PrePostCommands", + json!({}), + ) + .set( + "empty Pre", + "/OptIns/PrePostCommands", + json!({ "Pre": "", "Post": "echo" }), + ) + .set( + "empty Post", + "/OptIns/PrePostCommands", + json!({ "Pre": "echo", "Post": "" }), + ) + .set( + "Pre of 2049 bytes", + "/OptIns/PrePostCommands", + json!({ "Pre": "e".repeat(2049) }), + ) + .set( + "Post of 2049 bytes", + "/OptIns/PrePostCommands", + json!({ "Post": "e".repeat(2049) }), + ) + .set( + "unknown member of PrePostCommands", + "/OptIns/PrePostCommands", + json!({ "Pre": "echo", "Shell": "cmd" }), + ) + .set( + "KillBeforeOperation without Processes", + "/OptIns/KillBeforeOperation", + json!({}), + ) + .set( + "image name of 129 bytes", + "/OptIns/KillBeforeOperation/Processes", + json!(["n".repeat(129)]), + ) + .set( + "image name with an asterisk", + "/OptIns/KillBeforeOperation/Processes", + json!(["note*.exe"]), + ) + .set( + "image name with a question mark", + "/OptIns/KillBeforeOperation/Processes", + json!(["notepa?.exe"]), + ) + .set( + "unknown member of KillBeforeOperation", + "/OptIns/KillBeforeOperation", + json!({ "Processes": ["notepad.exe"], "Force": true }), + ) + } + + /// Changes of `RequestId` that keep an execution request and a bypass request well-formed. + fn accepted_request_ids(cases: Cases) -> Cases { + cases + .set("request id of 1 letter", "/RequestId", json!("a")) + .set("request id of 1 digit", "/RequestId", json!("0")) + .set("request id of 128 characters", "/RequestId", json!("r".repeat(128))) + .set( + "request id with every allowed character", + "/RequestId", + json!("Az09._:-"), + ) + } + + /// Changes of `RequestId` that make an execution request and a bypass request `BadRequest`. + fn rejected_request_ids(mut cases: Cases) -> Cases { + for (kind, value) in non_strings() { + cases = cases.set(&format!("request id is {kind}"), "/RequestId", value); + } + + for request_id in [ + "", "-a", ".a", "_a", ":a", "a b", "a/b", "a~b", "a+b", "a%20b", "é", "a\n", + ] { + cases = cases.set(&format!("request id {request_id:?}"), "/RequestId", json!(request_id)); + } + + cases.unset("request id is absent", "/RequestId").set( + "request id of 129 characters", + "/RequestId", + json!("r".repeat(129)), + ) + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §json + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §validation + #[test] + fn well_formed_body_is_read() { + assert_eq!( + read_validation_request(br#"{"Document":"text"}"#), + Ok(v2::ValidationRequest { + document: "text".to_owned() + }) + ); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §json + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.policy.md §json + #[test] + fn malformed_body_is_bad_request() { + let utf16: Vec = r#"{"Document":"text"}"#.encode_utf16().flat_map(u16::to_le_bytes).collect(); + let bodies: Vec<(&str, Vec)> = vec![ + ("empty", b"".to_vec()), + ("whitespace only", b" \n".to_vec()), + ("truncated", br#"{"Document":"text""#.to_vec()), + ("trailing comma", br#"{"Document":"text",}"#.to_vec()), + ("line comment", b"{// note\n\"Document\":\"text\"}".to_vec()), + ("block comment", br#"{/* note */"Document":"text"}"#.to_vec()), + ("single quotes", br#"{'Document':'text'}"#.to_vec()), + ("unquoted key", br#"{Document:"text"}"#.to_vec()), + ("second value", br#"{"Document":"text"}{"Document":"text"}"#.to_vec()), + ("text after the value", br#"{"Document":"text"}x"#.to_vec()), + ("form feed as whitespace", b"\x0c{\"Document\":\"text\"}".to_vec()), + ("control character in a string", b"{\"Document\":\"te\nxt\"}".to_vec()), + ("escape RFC 8259 does not define", br#"{"Document":"\x41"}"#.to_vec()), + ("top-level list", br#"["text"]"#.to_vec()), + ("top-level string", br#""text""#.to_vec()), + ("top-level number", b"1".to_vec()), + ("top-level boolean", b"true".to_vec()), + ("top-level null", b"null".to_vec()), + ("byte that is not UTF-8", b"{\"Document\":\"\xff\"}".to_vec()), + ("truncated UTF-8 sequence", b"{\"Document\":\"\xc3\"}".to_vec()), + ( + "surrogate encoded in UTF-8", + b"{\"Document\":\"\xed\xa0\x80\"}".to_vec(), + ), + ("UTF-16", utf16), + ("unpaired leading surrogate", br#"{"Document":"\ud800"}"#.to_vec()), + ("unpaired trailing surrogate", br#"{"Document":"\udc00"}"#.to_vec()), + ( + "leading surrogate before a character", + br#"{"Document":"\ud800x"}"#.to_vec(), + ), + ( + "surrogates in reverse order", + br#"{"Document":"\udc00\ud800"}"#.to_vec(), + ), + ( + "unpaired surrogate in a key", + br#"{"Document":"text","\ud800":"x"}"#.to_vec(), + ), + ]; + + assert_eq!(failing_bodies(&bodies, validation_is_bad), NONE); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §json + #[test] + fn body_with_byte_order_mark_is_bad_request() { + assert_eq!( + read_validation_request(b"\xEF\xBB\xBF{\"Document\":\"text\"}"), + Err(BadRequest) + ); + } + + // A body is JSON as RFC 8259 defines it, which gives each escape its character. + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §json + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §validation + // oracle: spec RFC 8259 §7 + #[test] + fn escapes_of_a_string_are_decoded() { + assert_eq!( + read_validation_request(br#"{"Document":"\ud83d\ude00\u0041\n\"\\\/"}"#), + Ok(v2::ValidationRequest { + document: "\u{1F600}A\n\"\\/".to_owned() + }) + ); + } + + // The keys of a request are read as the keys of a policy document are. + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §json + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.policy.md §json + #[test] + fn key_is_matched_after_its_escapes_are_decoded() { + assert_eq!( + read_validation_request(br#"{"\u0044ocument":"text"}"#), + Ok(v2::ValidationRequest { + document: "text".to_owned() + }) + ); + } + + // A key with other characters is a member the table does not list, and leaves the required member absent. + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §json + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.policy.md §json + #[test] + fn key_with_other_characters_is_bad_request() { + let bodies: Vec<(&str, Vec)> = vec![ + ("lower case", br#"{"document":"text"}"#.to_vec()), + ("upper case", br#"{"DOCUMENT":"text"}"#.to_vec()), + ("trailing space", br#"{"Document ":"text"}"#.to_vec()), + ("leading space", br#"{" Document":"text"}"#.to_vec()), + ]; + + assert_eq!(failing_bodies(&bodies, validation_is_bad), NONE); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §json + #[test] + fn repeated_key_is_bad_request() { + const BODY: &str = r#"{"Operation":"Install","Manager":"Winget","Source":{"Name":"winget"},"Package":{"Id":"Git.Git"},"Elevation":"NonElevated","Scope":"User","OptIns":{"Interactive":{},"CustomInstallLocation":{"Path":"C:\\Apps"}}}"#; + let repeated = |member: &str, twice: &str| { + assert!(BODY.contains(member), "{member} is in the body"); + BODY.replacen(member, twice, 1).into_bytes() + }; + let bodies: Vec<(&str, Vec)> = vec![ + ( + "required member", + repeated( + r#""Operation":"Install""#, + r#""Operation":"Install","Operation":"Install""#, + ), + ), + ( + "required member with another value", + repeated( + r#""Operation":"Install""#, + r#""Operation":"Install","Operation":"Update""#, + ), + ), + ( + "key spelled with an escape", + repeated( + r#""Operation":"Install""#, + r#""Operation":"Install","\u004fperation":"Install""#, + ), + ), + ( + "optional member", + repeated(r#""Scope":"User""#, r#""Scope":"User","Scope":"User""#), + ), + ( + "member of Source", + repeated(r#""Name":"winget""#, r#""Name":"winget","Name":"winget""#), + ), + ( + "member of Package", + repeated(r#""Id":"Git.Git""#, r#""Id":"Git.Git","Id":"Git.Git""#), + ), + ( + "member of Package spelled with an escape", + repeated(r#""Id":"Git.Git""#, r#""Id":"Git.Git","\u0049d":"Git.Git""#), + ), + ( + "opt-in", + repeated(r#""Interactive":{}"#, r#""Interactive":{},"Interactive":{}"#), + ), + ( + "member of an opt-in", + repeated(r#""Path":"C:\\Apps""#, r#""Path":"C:\\Apps","Path":"C:\\Apps""#), + ), + ]; + + assert!(evaluation_is_ok(BODY.as_bytes())); + assert_eq!(failing_bodies(&bodies, evaluation_is_bad), NONE); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §json + #[test] + fn repeated_key_is_bad_request_in_every_request() { + const EXECUTION: &str = r#"{"RequestId":"request-1","Operation":"Install","Manager":"Winget","Source":{"Name":"winget"},"Package":{"Id":"Git.Git"},"Elevation":"NonElevated","OptIns":{"NoUpgrade":{}}}"#; + const VALIDATION: &str = r#"{"Document":"{}"}"#; + const REPLACEMENT: &str = r#"{"ExpectedStoreToken":"token-1","Document":"{}"}"#; + let request_id_twice = EXECUTION.replacen( + r#""RequestId":"request-1""#, + r#""RequestId":"request-1","RequestId":"request-1""#, + 1, + ); + let no_upgrade_twice = EXECUTION.replacen(r#""NoUpgrade":{}"#, r#""NoUpgrade":{},"NoUpgrade":{}"#, 1); + let document_twice = VALIDATION.replacen(r#""Document":"{}""#, r#""Document":"{}","Document":"{}""#, 1); + let store_token_twice = REPLACEMENT.replacen( + r#""ExpectedStoreToken":"token-1""#, + r#""ExpectedStoreToken":"token-1","ExpectedStoreToken":"token-1""#, + 1, + ); + + assert!(execution_is_ok(EXECUTION.as_bytes())); + assert!(bypass_is_ok(EXECUTION.as_bytes())); + assert!(validation_is_ok(VALIDATION.as_bytes())); + assert!(replacement_is_ok(REPLACEMENT.as_bytes())); + assert_ne!(request_id_twice, EXECUTION); + assert_ne!(no_upgrade_twice, EXECUTION); + assert_ne!(document_twice, VALIDATION); + assert_ne!(store_token_twice, REPLACEMENT); + + assert!(execution_is_bad(request_id_twice.as_bytes())); + assert!(execution_is_bad(no_upgrade_twice.as_bytes())); + assert!(bypass_is_bad(request_id_twice.as_bytes())); + assert!(bypass_is_bad(no_upgrade_twice.as_bytes())); + assert!(validation_is_bad(document_twice.as_bytes())); + assert!(replacement_is_bad(store_token_twice.as_bytes())); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §json + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.policy.md §json + #[test] + fn key_order_and_whitespace_carry_no_meaning() { + let spaced = b" \t\r\n{ \"Elevation\" : \"Elevated\" ,\r\n\t\"Package\" : { \"Version\" : \"2.45.1\" , \"Id\" : \"Git.Git\" } ,\n \"Source\" : { \"Name\" : \"winget\" } , \"Manager\" : \"Winget\" , \"Operation\" : \"Install\" } \n"; + let compact = br#"{"Operation":"Install","Manager":"Winget","Source":{"Name":"winget"},"Package":{"Id":"Git.Git","Version":"2.45.1"},"Elevation":"Elevated"}"#; + + let spaced = read_evaluation_request(spaced).expect("body with other key order and whitespace"); + + assert_eq!(Ok(spaced), read_evaluation_request(compact)); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §package-request + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §opt-ins + #[test] + fn every_member_of_a_package_request_is_read() { + let request = read_evaluation_request(&bytes(&full_package_request_body())).expect("package request"); + + assert_eq!(request, full_package_request()); + } + + /// A body with every member of a package request. + fn full_package_request_body() -> Value { + json!({ + "Operation": "Update", + "Manager": "Chocolatey", + "Source": { "Name": "community" }, + "Package": { "Id": "git.install", "Version": "2.45.1", "Architecture": "X64" }, + "Scope": "Machine", + "Elevation": "Elevated", + "OptIns": opt_ins(), + }) + } + + /// The package request whose members are those of `full_package_request_body`. + fn full_package_request() -> v2::PackageRequest { + v2::PackageRequest { + operation: v2::Operation::Update, + manager: v2::Manager::Chocolatey, + source: v2::Source { + name: v2::SourceName::parse("community").expect("source name"), + }, + package: v2::Package { + id: v2::PackageId::parse("git.install").expect("package id"), + version: Some(v2::PackageVersion::parse("2.45.1").expect("version")), + architecture: Some(v2::Architecture::X64), + }, + scope: Some(v2::Scope::Machine), + elevation: v2::Elevation::Elevated, + opt_ins: Some(v2::OptIns { + interactive: Some(v2::Empty {}), + skip_hash_check: Some(v2::Empty {}), + custom_install_location: Some(v2::CustomInstallLocation { + path: v2::InstallPath::parse("D:\\Tools\\Git").expect("path"), + }), + custom_parameters: Some(v2::CustomParameters { + values: vec![ + v2::CustomParameter::parse("--params").expect("custom parameter"), + v2::CustomParameter::parse("/NoShellIntegration").expect("custom parameter"), + ], + }), + installer_arguments: Some(v2::InstallerArguments { + arguments: v2::InstallerArgumentsText::parse("/VERYSILENT").expect("arguments"), + mode: v2::InstallerArgumentsMode::Append, + }), + pre_post_commands: Some(v2::PrePostCommands { + pre: Some(v2::CommandText::parse("echo before").expect("command")), + post: Some(v2::CommandText::parse("echo after").expect("command")), + }), + kill_before_operation: Some(v2::KillBeforeOperation { + processes: vec![ + v2::ImageName::parse("git.exe").expect("image name"), + v2::ImageName::parse("bash.exe").expect("image name"), + ], + }), + uninstall_previous: Some(v2::Empty {}), + no_upgrade: Some(v2::Empty {}), + }), + } + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §package-request + #[test] + fn package_request_without_optional_members_is_read() { + let request = read_evaluation_request(&bytes(&package_request())).expect("package request"); + + assert_eq!( + request, + v2::PackageRequest { + operation: v2::Operation::Install, + manager: v2::Manager::Winget, + source: v2::Source { + name: v2::SourceName::parse("winget").expect("source name"), + }, + package: v2::Package { + id: v2::PackageId::parse("Git.Git").expect("package id"), + version: None, + architecture: None, + }, + scope: None, + elevation: v2::Elevation::NonElevated, + opt_ins: None, + } + ); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §package-request + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §opt-ins + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.policy.md §request-properties + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.policy.md §managers + #[test] + fn evaluation_request_within_its_tables_is_read() { + let cases = Cases::new(package_request()); + let cases = accepted_in_a_full_package_request(accepted_in_every_package_request(cases)); + + assert_eq!(cases.failing(evaluation_is_ok), NONE); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §json + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §package-request + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §opt-ins + #[test] + fn evaluation_request_outside_its_tables_is_bad_request() { + let cases = Cases::new(package_request()); + let cases = rejected_in_a_full_package_request(rejected_in_every_package_request(cases)); + + assert!(evaluation_is_ok(&bytes(&cases.base))); + assert_eq!(cases.failing(evaluation_is_bad), NONE); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §json + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §values + #[test] + fn closed_set_value_written_as_an_object_is_bad_request() { + let cases = Cases::new(with(&package_request(), "/OptIns", opt_ins())) + .set("Operation", "/Operation", json!({ "Install": null })) + .set("Manager", "/Manager", json!({ "Winget": null })) + .set("Scope", "/Scope", json!({ "User": null })) + .set("Elevation", "/Elevation", json!({ "NonElevated": null })) + .set("Package.Architecture", "/Package/Architecture", json!({ "X64": null })) + .set( + "InstallerArguments.Mode", + "/OptIns/InstallerArguments/Mode", + json!({ "Append": null }), + ); + + assert!(evaluation_is_ok(&bytes(&cases.base))); + assert_eq!(cases.failing(evaluation_is_bad), NONE); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §evaluate + #[test] + fn evaluation_request_with_request_id_is_bad_request() { + assert_eq!(read_evaluation_request(&bytes(&execution_request())), Err(BadRequest)); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §execute + #[test] + fn execution_request_is_a_package_request_with_a_request_id() { + let body = with(&full_package_request_body(), "/RequestId", json!("request-1")); + + let request = read_execution_request(&bytes(&body)).expect("execution request"); + + assert_eq!(request.request_id.as_str(), "request-1"); + assert_eq!(request.package_request(), full_package_request()); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §execute + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §values + #[test] + fn execution_request_within_its_tables_is_read() { + let cases = Cases::new(execution_request()); + let cases = accepted_in_a_full_package_request(accepted_in_every_package_request(cases)); + let cases = accepted_request_ids(cases); + + assert_eq!(cases.failing(execution_is_ok), NONE); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §execute + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §values + #[test] + fn execution_request_outside_its_tables_is_bad_request() { + let cases = Cases::new(execution_request()); + let cases = rejected_in_a_full_package_request(rejected_in_every_package_request(cases)); + let cases = rejected_request_ids(cases); + + assert!(execution_is_ok(&bytes(&cases.base))); + assert_eq!(cases.failing(execution_is_bad), NONE); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §bypass + #[test] + fn every_member_of_a_bypass_request_is_read() { + let body = json!({ + "RequestId": "request-1", + "Operation": "Update", + "Manager": "Chocolatey", + "Source": { "Name": "community" }, + "Package": { "Id": "git.install", "Version": "2.45.1" }, + "Scope": "Machine", + "Elevation": "Elevated", + "OptIns": { "NoUpgrade": {} }, + }); + + let request = read_bypass_request(&bytes(&body)).expect("bypass request"); + + assert_eq!( + request, + v2::BypassRequest { + request_id: v2::Identifier::parse("request-1").expect("identifier"), + operation: v2::Operation::Update, + manager: v2::Manager::Chocolatey, + source: Some(v2::Source { + name: v2::SourceName::parse("community").expect("source name"), + }), + package: v2::BypassPackage { + id: v2::PackageId::parse("git.install").expect("package id"), + version: Some(v2::PackageVersion::parse("2.45.1").expect("version")), + }, + scope: Some(v2::Scope::Machine), + elevation: v2::Elevation::Elevated, + opt_ins: Some(v2::BypassOptIns { + no_upgrade: Some(v2::Empty {}), + }), + } + ); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §bypass + #[test] + fn bypass_request_within_its_tables_is_read() { + let cases = Cases::new(execution_request()); + let cases = accepted_request_ids(accepted_in_every_package_request(cases)); + let without_source = Cases::new(without(&execution_request(), "/Source")) + .set("install without Source", "/Operation", json!("Install")) + .set("update without Source", "/Operation", json!("Update")) + .set("uninstall without Source", "/Operation", json!("Uninstall")); + + assert_eq!(cases.failing(bypass_is_ok), NONE); + assert_eq!(without_source.failing(bypass_is_ok), NONE); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §bypass + #[test] + fn bypass_request_outside_its_tables_is_bad_request() { + let mut cases = rejected_request_ids(rejected_in_every_package_request(Cases::new(execution_request()))); + + let other_opt_ins = opt_ins(); + for (opt_in, value) in other_opt_ins.as_object().expect("opt-ins") { + if opt_in != "NoUpgrade" { + cases = cases.set(&format!("opt-in {opt_in}"), &format!("/OptIns/{opt_in}"), value.clone()); + } + } + + for architecture in ["X86", "X64", "Arm64", "Neutral"] { + cases = cases.set( + &format!("architecture {architecture}"), + "/Package/Architecture", + json!(architecture), + ); + } + + let cases = cases + .set("uninstall with Source", "/Operation", json!("Uninstall")) + .set("Source without Name", "/Source", json!({})); + + assert!(bypass_is_ok(&bytes(&cases.base))); + assert_eq!(cases.failing(bypass_is_bad), NONE); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §validation + #[test] + fn validation_request_within_its_table_is_read() { + let cases = Cases::new(json!({ "Document": "{}" })) + .set("empty document", "/Document", json!("")) + .set("document that is no JSON", "/Document", json!("not a policy")) + .set("document starting with U+FEFF", "/Document", json!("\u{FEFF}{}")); + + assert_eq!(cases.failing(validation_is_ok), NONE); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §validation + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §json + #[test] + fn validation_request_outside_its_table_is_bad_request() { + let mut cases = Cases::new(json!({ "Document": "{}" })); + for (kind, value) in non_strings() { + cases = cases.set(&format!("Document is {kind}"), "/Document", value); + } + let cases = cases.unset("Document is absent", "/Document").set( + "unknown member", + "/ExpectedStoreToken", + json!("token-1"), + ); + + assert!(validation_is_ok(&bytes(&cases.base))); + assert_eq!(cases.failing(validation_is_bad), NONE); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §replacement + #[test] + fn every_member_of_a_replacement_request_is_read() { + assert_eq!( + read_replacement_request(br#"{"ExpectedStoreToken":"token-1","Document":"{}"}"#), + Ok(v2::ReplacementRequest { + expected_store_token: v2::StoreToken::parse("token-1").expect("store token"), + document: "{}".to_owned(), + }) + ); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §replacement + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §management-state + #[test] + fn replacement_request_within_its_table_is_read() { + let cases = Cases::new(json!({ "ExpectedStoreToken": "token-1", "Document": "{}" })) + .set("store token of 1 letter", "/ExpectedStoreToken", json!("a")) + .set("store token of 1 digit", "/ExpectedStoreToken", json!("0")) + .set( + "store token of 512 characters", + "/ExpectedStoreToken", + json!("t".repeat(512)), + ) + .set( + "store token with every allowed character", + "/ExpectedStoreToken", + json!("Az09._~:-"), + ) + .set("empty document", "/Document", json!("")); + + assert_eq!(cases.failing(replacement_is_ok), NONE); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §replacement + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §management-state + #[test] + fn replacement_request_outside_its_table_is_bad_request() { + let mut cases = Cases::new(json!({ "ExpectedStoreToken": "token-1", "Document": "{}" })); + for (kind, value) in non_strings() { + cases = cases + .set(&format!("Document is {kind}"), "/Document", value.clone()) + .set(&format!("store token is {kind}"), "/ExpectedStoreToken", value); + } + for token in ["", "~a", "-a", ".a", "_a", ":a", "a b", "a/b", "a+b", "a=", "é"] { + cases = cases.set(&format!("store token {token:?}"), "/ExpectedStoreToken", json!(token)); + } + let cases = cases + .unset("Document is absent", "/Document") + .unset("store token is absent", "/ExpectedStoreToken") + .set( + "store token of 513 characters", + "/ExpectedStoreToken", + json!("t".repeat(513)), + ) + .set("unknown member", "/Force", json!(true)); + + assert!(replacement_is_ok(&bytes(&cases.base))); + assert_eq!(cases.failing(replacement_is_bad), NONE); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §equal-requests + #[test] + fn package_requests_with_equal_members_are_equal() { + let request = with(&package_request(), "/OptIns", opt_ins()); + let reordered = br#"{"OptIns":{"NoUpgrade":{},"UninstallPrevious":{},"KillBeforeOperation":{"Processes":["git.exe","bash.exe"]},"PrePostCommands":{"Post":"echo after","Pre":"echo before"},"InstallerArguments":{"Mode":"Append","Arguments":"/VERYSILENT"},"CustomParameters":{"Values":["--params","/NoShellIntegration"]},"CustomInstallLocation":{"Path":"D:\\Tools\\Git"},"SkipHashCheck":{},"Interactive":{}},"Elevation":"NonElevated","Package":{"Id":"Git.Git"},"Source":{"Name":"\u0077inget"},"Manager":"Winget","Operation":"Install"}"#; + + let request = read_evaluation_request(&bytes(&request)).expect("package request"); + + assert_eq!(Ok(&request), read_evaluation_request(reordered).as_ref()); + assert_eq!( + Ok(request), + read_execution_request(&bytes(&with( + &with(&package_request(), "/OptIns", opt_ins()), + "/RequestId", + json!("request-2") + ))) + .map(|request| request.package_request()) + ); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §equal-requests + #[test] + fn package_requests_with_other_members_are_not_equal() { + let base = with( + &with( + &package_request(), + "/OptIns/CustomParameters/Values", + json!(["-a", "-b"]), + ), + "/Package/Version", + json!("1.0"), + ); + let cases = Cases::new(base) + .set( + "list in another order", + "/OptIns/CustomParameters/Values", + json!(["-b", "-a"]), + ) + .set( + "list with a repeated entry", + "/OptIns/CustomParameters/Values", + json!(["-a", "-b", "-b"]), + ) + .set("string in another case", "/Source/Name", json!("Winget")) + .set( + "string in another normalization form", + "/Package/Version", + json!("1.0\u{0301}"), + ) + .set("another value of a closed set", "/Elevation", json!("Elevated")) + .set("member added", "/Scope", json!("User")) + .unset("member removed", "/Package/Version") + .set("opt-in added", "/OptIns/NoUpgrade", json!({})) + .unset("opt-in removed", "/OptIns/CustomParameters"); + let base = read_evaluation_request(&bytes(&cases.base)).expect("package request"); + + assert_eq!( + cases.failing(|body| read_evaluation_request(body).is_ok_and(|request| request != base)), + NONE + ); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §equal-requests + #[test] + fn package_request_with_empty_opt_ins_is_not_equal_to_one_without_opt_ins() { + let without_opt_ins = read_evaluation_request(&bytes(&package_request())).expect("package request"); + let with_empty_opt_ins = + read_evaluation_request(&bytes(&with(&package_request(), "/OptIns", json!({})))).expect("package request"); + + assert_ne!(without_opt_ins, with_empty_opt_ins); + } +} diff --git a/crates/now-package-broker/src/v2/wire/route.rs b/crates/now-package-broker/src/v2/wire/route.rs new file mode 100644 index 000000000..47e625df3 --- /dev/null +++ b/crates/now-package-broker/src/v2/wire/route.rs @@ -0,0 +1,397 @@ +//! Matching a request to its endpoint ([§endpoints]). +//! +//! [§endpoints]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#endpoints + +use core::fmt; + +use now_policy_api::v2; + +/// The row of the endpoint table a request matches. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Route { + pub endpoint: v2::Endpoint, + /// What the `{OperationId}` of the path names, for a row whose path has one. + pub operation: Option>, +} + +/// The method and path of the request match no row of the endpoint table. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct UnknownEndpoint; + +impl fmt::Display for UnknownEndpoint { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("method and path match no endpoint") + } +} + +impl core::error::Error for UnknownEndpoint {} + +/// The path names no operation, because the characters at its `{OperationId}` are not an identifier ([§endpoints]). +/// +/// The broker holds no operation with such an id, so the request is `OperationNotFound` ([§status], [§cancel]) unless +/// an earlier outcome of [§errors] applies to it. +/// +/// [§endpoints]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#endpoints +/// [§status]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#status +/// [§cancel]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#cancel +/// [§errors]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#errors +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct OperationNotFound; + +impl fmt::Display for OperationNotFound { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("path names no operation") + } +} + +impl core::error::Error for OperationNotFound {} + +/// Returns the row of the endpoint table that a request line's method and target match ([§endpoints]). +/// +/// The target is the path, optionally followed by a query, which is ignored ([§transport]). +/// Neither is decoded or normalized. +/// +/// [§endpoints]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#endpoints +/// [§transport]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#transport +pub fn route(method: &str, target: &str) -> Result { + let path = target.split_once('?').map_or(target, |(path, _query)| path); + + v2::Endpoint::ALL + .into_iter() + .filter(|endpoint| endpoint.method().as_str() == method) + .find_map(|endpoint| { + let operation_id = match_path(endpoint.path(), path)?; + + Some(Route { + endpoint, + operation: operation_id.map(|id| v2::Identifier::parse(id).map_err(|_| OperationNotFound)), + }) + }) + .ok_or(UnknownEndpoint) +} + +/// Returns the characters of `path` at the `{OperationId}` of `template`, or `Some(None)` for a template without one, +/// when the path matches the template. +fn match_path<'a>(template: &str, path: &'a str) -> Option> { + let Some((before, after)) = template.split_once("{OperationId}") else { + return (template == path).then_some(None); + }; + + let operation_id = path.strip_prefix(before)?.strip_suffix(after)?; + + (!operation_id.is_empty() && !operation_id.contains('/')).then_some(Some(operation_id)) +} + +#[cfg(test)] +mod tests { + use now_policy_api::v2::ClientRequirement::{Any, Authenticated, ElevatedAdministrator}; + use now_policy_api::v2::Endpoint; + + use super::*; + + const NONE: &[&str] = &[]; + + /// A row of the table of "Endpoints". + struct Row { + method: &'static str, + path: &'static str, + body_limit: usize, + client: v2::ClientRequirement, + endpoint: Endpoint, + /// The characters of `path` at `{OperationId}`, for a row whose path has one. + operation_id: Option<&'static str>, + } + + /// A row whose path has no `{OperationId}`. + const fn row( + method: &'static str, + path: &'static str, + body_limit: usize, + client: v2::ClientRequirement, + endpoint: Endpoint, + ) -> Row { + Row { + method, + path, + body_limit, + client, + endpoint, + operation_id: None, + } + } + + /// The table of "Endpoints", with `op-1` at `{OperationId}`. + const ROWS: [Row; 10] = [ + row("GET", "/v2/health", 0, Any, Endpoint::Health), + row("GET", "/v2/capabilities", 0, Authenticated, Endpoint::Capabilities), + row( + "POST", + "/v2/package-requests/evaluate", + 262_144, + Authenticated, + Endpoint::Evaluate, + ), + row( + "POST", + "/v2/package-requests/execute", + 262_144, + Authenticated, + Endpoint::Execute, + ), + row( + "POST", + "/v2/package-requests/execute-bypass", + 262_144, + Authenticated, + Endpoint::ExecuteBypass, + ), + Row { + operation_id: Some("op-1"), + ..row("GET", "/v2/operations/op-1", 0, Authenticated, Endpoint::Status) + }, + Row { + operation_id: Some("op-1"), + ..row("POST", "/v2/operations/op-1/cancel", 0, Authenticated, Endpoint::Cancel) + }, + row("GET", "/v2/policy/management", 0, Authenticated, Endpoint::Management), + row( + "POST", + "/v2/policy/validate", + 33_554_432, + Authenticated, + Endpoint::Validate, + ), + row( + "POST", + "/v2/policy", + 33_554_432, + ElevatedAdministrator, + Endpoint::Replace, + ), + ]; + + fn named(endpoint: Endpoint, operation_id: &str) -> Result { + Ok(Route { + endpoint, + operation: Some(Ok(v2::Identifier::parse(operation_id).expect("identifier"))), + }) + } + + fn plain(endpoint: Endpoint) -> Result { + Ok(Route { + endpoint, + operation: None, + }) + } + + fn expected(row: &Row) -> Result { + Ok(Route { + endpoint: row.endpoint, + operation: row + .operation_id + .map(|id| Ok(v2::Identifier::parse(id).expect("identifier"))), + }) + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §endpoints + #[test] + fn every_row_is_matched_by_its_method_and_path() { + let unmatched: Vec<&str> = ROWS + .iter() + .filter(|row| route(row.method, row.path) != expected(row)) + .map(|row| row.path) + .collect(); + + assert_eq!(unmatched, NONE); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §endpoints + #[test] + fn every_row_has_the_body_limit_of_the_table() { + let limits: Vec<(&str, usize)> = ROWS.iter().map(|row| (row.path, row.endpoint.body_limit())).collect(); + let table: Vec<(&str, usize)> = ROWS.iter().map(|row| (row.path, row.body_limit)).collect(); + + assert_eq!(limits, table); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §endpoints + #[test] + fn every_row_has_the_client_of_the_table() { + let clients: Vec<(&str, v2::ClientRequirement)> = + ROWS.iter().map(|row| (row.path, row.endpoint.client())).collect(); + let table: Vec<(&str, v2::ClientRequirement)> = ROWS.iter().map(|row| (row.path, row.client)).collect(); + + assert_eq!(clients, table); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §endpoints + #[test] + fn table_has_every_endpoint() { + let endpoints: Vec = ROWS.iter().map(|row| row.endpoint).collect(); + + assert_eq!(endpoints, Endpoint::ALL); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §endpoints + #[test] + fn path_of_a_row_with_another_method_is_unknown_endpoint() { + let matched: Vec = ROWS + .iter() + .flat_map(|row| { + [ + "GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS", "get", "post", "Get", "Post", "", + ] + .into_iter() + .filter(move |method| *method != row.method) + .map(move |method| (method, row.path)) + }) + .filter(|(method, path)| route(method, path) != Err(UnknownEndpoint)) + .map(|(method, path)| format!("{method} {path}")) + .collect(); + + assert_eq!(matched, NONE); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §endpoints + #[test] + fn path_with_other_characters_is_unknown_endpoint() { + let paths = [ + "", + "/", + "/v2", + "/v2/", + "v2/health", + " /v2/health", + "/v2/health ", + "/v2/health/", + "/v2//health", + "//v2/health", + "/v2/Health", + "/V2/health", + "/v1/health", + "/v2/healt", + "/v2/healthy", + "/v2/%68ealth", + "/v2/health%20", + "/v2/./health", + "/v2/policy/../health", + "/v2/health#top", + "/v2/health;x=1", + "/v2/package-requests", + "/v2/package-requests/", + "/v2/package-requests/evaluate/", + "/v2/package-requests/execute_bypass", + "/v2/package-requests/execute%2Dbypass", + "/v2/operations", + "/v2/operations/", + "/v2/operations//cancel", + "/v2/operations/op-1/", + "/v2/operations/op-1/status", + "/v2/operations/op-1/Cancel", + "/v2/operations/op-1/cancel/", + "/v2/operations/op-1/cancel/cancel", + "/v2/operations/op-1%2Fcancel/x", + "/v2/policy/", + "/v2/policy/management/", + "/v2/policy/validate/", + ]; + + let matched: Vec = paths + .into_iter() + .flat_map(|path| [("GET", path), ("POST", path)]) + .filter(|(method, path)| route(method, path) != Err(UnknownEndpoint)) + .map(|(method, path)| format!("{method} {path}")) + .collect(); + + assert_eq!(matched, NONE); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §transport + #[test] + fn query_is_ignored() { + let unmatched: Vec = ROWS + .iter() + .flat_map(|row| ["?", "?x=1", "?x=1?y=2", "?/cancel", "?/../health", "?%"].map(|query| (row, query))) + .filter(|(row, query)| route(row.method, &format!("{}{query}", row.path)) != expected(row)) + .map(|(row, query)| format!("{}{query}", row.path)) + .collect(); + + assert_eq!(unmatched, NONE); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §transport + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §endpoints + #[test] + fn path_ends_where_the_query_starts() { + assert_eq!( + route("GET", "/v2/operations/op-1?/cancel"), + named(Endpoint::Status, "op-1") + ); + assert_eq!(route("POST", "/v2/operations/op-1?/cancel"), Err(UnknownEndpoint)); + assert_eq!(route("POST", "/v2/policy?/validate"), plain(Endpoint::Replace)); + assert_eq!(route("GET", "/v2/healt?h"), Err(UnknownEndpoint)); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §endpoints + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §values + #[test] + fn operation_id_is_the_characters_of_its_segment() { + let longest = "o".repeat(128); + let ids = ["a", "0", "Az09._:-", "cancel", "operations", "OP-1", longest.as_str()]; + + let wrong: Vec<&str> = ids + .into_iter() + .filter(|id| { + route("GET", &format!("/v2/operations/{id}")) != named(Endpoint::Status, id) + || route("POST", &format!("/v2/operations/{id}/cancel")) != named(Endpoint::Cancel, id) + }) + .collect(); + + assert_eq!(wrong, NONE); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §endpoints + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §values + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §status + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §cancel + #[test] + fn segment_that_is_no_identifier_names_no_operation() { + let too_long = "o".repeat(129); + let segments = [ + "%6Fp-1", + "op%2D1", + "op-1%20", + "op 1", + "-op", + ".op", + "_op", + ":op", + ".", + "..", + "op~1", + "op+1", + "op,1", + "op;1", + "op#1", + "opé", + "{OperationId}", + too_long.as_str(), + ]; + let no_operation = |endpoint| { + Ok(Route { + endpoint, + operation: Some(Err(OperationNotFound)), + }) + }; + + let wrong: Vec<&str> = segments + .into_iter() + .filter(|segment| { + route("GET", &format!("/v2/operations/{segment}")) != no_operation(Endpoint::Status) + || route("POST", &format!("/v2/operations/{segment}/cancel")) != no_operation(Endpoint::Cancel) + }) + .collect(); + + assert_eq!(wrong, NONE); + } +}