From b3ea0f517340f63c54838e6ca46ed82b72f02890 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Tue, 1 Dec 2026 04:30:31 +0900 Subject: [PATCH 01/29] feat(agent): read 2.0 request bodies into the published request types A route gets one function per request body, from the body bytes to the request type of the 2.0 API or a `BadRequest` marker, so no route parses JSON on its own and every body is held to the same rules. The tests take each rule from the wire contract: the JSON rules, the member tables of the five request objects, and request equality. One of them is ignored because the API types read a closed-set value written as an object, which the contract makes `BadRequest`. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- crates/now-package-broker/src/v2/wire/mod.rs | 10 + crates/now-package-broker/src/v2/wire/read.rs | 1322 +++++++++++++++++ 2 files changed, 1332 insertions(+) create mode 100644 crates/now-package-broker/src/v2/wire/read.rs diff --git a/crates/now-package-broker/src/v2/wire/mod.rs b/crates/now-package-broker/src/v2/wire/mod.rs index 048598d95..1e52ced9c 100644 --- a/crates/now-package-broker/src/v2/wire/mod.rs +++ b/crates/now-package-broker/src/v2/wire/mod.rs @@ -1 +1,11 @@ //! Requests and responses of the 2.0 encoding. +//! +//! The message types are those of [`now_policy_api::v2`]. +//! This module reads request bodies into them, converts between them and the evaluator's types, and matches a request to its endpoint, so the routes only move values. + +mod read; + +pub use read::{ + BadRequest, read_bypass_request, read_evaluation_request, read_execution_request, read_replacement_request, + read_validation_request, +}; 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..ac3473d5e --- /dev/null +++ b/crates/now-package-broker/src/v2/wire/read.rs @@ -0,0 +1,1322 @@ +//! 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 User, elevated", + &[("/Scope", json!("User")), ("/Elevation", json!("Elevated"))], + ) + .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("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")) + .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 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 + #[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) + ); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §json + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §validation + #[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() + }) + ); + } + + // 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() + }) + ); + } + + // 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.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 body = 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(), + }); + + let request = read_evaluation_request(&bytes(&body)).expect("package request"); + + assert_eq!(request, full_package_request()); + } + + /// The package request whose members are those of the body in `every_member_of_a_package_request_is_read`. + 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] + #[ignore = "now-policy-api reads a closed-set value written as an object, such as {\"Install\": null}"] + 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( + &serde_json::to_value(full_package_request()).expect("package request"), + "/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); + } +} From 719326292f013ab07fa396a8d2f8e78d52bf84f0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Tue, 1 Dec 2026 04:37:58 +0900 Subject: [PATCH 02/29] feat(agent): convert between the 2.0 request types and the policy evaluator A package request read from a 2.0 body becomes the evaluator's input, and the evaluator's decision and validation errors become the members a 2.0 response carries, so a route never maps a member by hand. Each closed set is mapped by a match without a wildcard arm, and tested name by name against the contract's list, so a value added on either side cannot be dropped or renamed unnoticed. A bypass request becomes the package request the contract reads it as, with its own source name or the one the caller found for it. One timestamp test is ignored because the API types write the leap second chrono can hold with the seconds 60, which no timestamp has. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- .../now-package-broker/src/v2/wire/convert.rs | 1013 +++++++++++++++++ crates/now-package-broker/src/v2/wire/mod.rs | 2 + 2 files changed, 1015 insertions(+) create mode 100644 crates/now-package-broker/src/v2/wire/convert.rs 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..9d7f190c6 --- /dev/null +++ b/crates/now-package-broker/src/v2/wire/convert.rs @@ -0,0 +1,1013 @@ +//! 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: 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, which no 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: 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: 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] + #[ignore = "now-policy-api writes the leap second that chrono holds with the seconds 60"] + 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/mod.rs b/crates/now-package-broker/src/v2/wire/mod.rs index 1e52ced9c..a01883ef8 100644 --- a/crates/now-package-broker/src/v2/wire/mod.rs +++ b/crates/now-package-broker/src/v2/wire/mod.rs @@ -3,8 +3,10 @@ //! The message types are those of [`now_policy_api::v2`]. //! This module reads request bodies into them, converts between them and the evaluator's types, and matches a request to its endpoint, so the routes only move values. +mod convert; mod read; +pub use convert::{bypass_package_request, decision, evaluator_request, policy_error, timestamp}; pub use read::{ BadRequest, read_bypass_request, read_evaluation_request, read_execution_request, read_replacement_request, read_validation_request, From 4e321a21c33c8798051942bca2550ca6453899f0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Tue, 1 Dec 2026 04:41:03 +0900 Subject: [PATCH 03/29] feat(agent): match a 2.0 request to its endpoint A request line's method and target give the row of the endpoint table they match, with the operation id of the path where the row has one, so every route applies the same matching: exact characters, no decoding, and a query that is ignored. A path whose operation id is not an identifier still matches its row, because the checks that come before `OperationNotFound`, such as authentication, depend on the row. The tests go through the contract's table row by row, body limits and client requirements included. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- crates/now-package-broker/src/v2/wire/mod.rs | 2 + .../now-package-broker/src/v2/wire/route.rs | 384 ++++++++++++++++++ 2 files changed, 386 insertions(+) create mode 100644 crates/now-package-broker/src/v2/wire/route.rs diff --git a/crates/now-package-broker/src/v2/wire/mod.rs b/crates/now-package-broker/src/v2/wire/mod.rs index a01883ef8..98b7e418a 100644 --- a/crates/now-package-broker/src/v2/wire/mod.rs +++ b/crates/now-package-broker/src/v2/wire/mod.rs @@ -5,9 +5,11 @@ mod convert; mod read; +mod route; pub use convert::{bypass_package_request, decision, evaluator_request, policy_error, timestamp}; 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/route.rs b/crates/now-package-broker/src/v2/wire/route.rs new file mode 100644 index 000000000..f3e3fff86 --- /dev/null +++ b/crates/now-package-broker/src/v2/wire/route.rs @@ -0,0 +1,384 @@ +//! 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, + } + + 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, + } + } + + /// 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("GET", "/v2/operations/op-1", 0, Authenticated, Endpoint::Status), + 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 { + if row.path.contains("op-1") { + named(row.endpoint, "op-1") + } else { + plain(row.endpoint) + } + } + + // 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); + } +} From b118056ff5b7d28997df61a772a277ad6ddbffd9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Tue, 1 Dec 2026 04:47:55 +0900 Subject: [PATCH 04/29] test(agent): check a repeated key in every 2.0 request body The rule was checked through the evaluation request only, and each request type has its own reader. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- crates/now-package-broker/src/v2/wire/read.rs | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/crates/now-package-broker/src/v2/wire/read.rs b/crates/now-package-broker/src/v2/wire/read.rs index ac3473d5e..259a3a339 100644 --- a/crates/now-package-broker/src/v2/wire/read.rs +++ b/crates/now-package-broker/src/v2/wire/read.rs @@ -887,6 +887,42 @@ mod tests { 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.policy.md §json #[test] fn key_order_and_whitespace_carry_no_meaning() { From 43873c8dd2c493229c683243f0ef964a0ebf6c09 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Tue, 1 Dec 2026 04:47:55 +0900 Subject: [PATCH 05/29] feat(agent): build 2.0 error responses the contract allows A route gets a constructor per kind of error response, so the message limit and the member each code carries are decided in one place. A message is cut to the 2048 bytes a response may carry, at a character boundary. 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 the contract lets replace each such code, rather than a response the contract does not allow. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- .../now-package-broker/src/v2/wire/error.rs | 374 ++++++++++++++++++ crates/now-package-broker/src/v2/wire/mod.rs | 4 +- 2 files changed, 377 insertions(+), 1 deletion(-) create mode 100644 crates/now-package-broker/src/v2/wire/error.rs 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..8e5975371 --- /dev/null +++ b/crates/now-package-broker/src/v2/wire/error.rs @@ -0,0 +1,374 @@ +//! 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 98b7e418a..2c4569a23 100644 --- a/crates/now-package-broker/src/v2/wire/mod.rs +++ b/crates/now-package-broker/src/v2/wire/mod.rs @@ -1,13 +1,15 @@ //! Requests and responses of the 2.0 encoding. //! //! The message types are those of [`now_policy_api::v2`]. -//! This module reads request bodies into them, converts between them and the evaluator's types, and matches a request to its endpoint, so the routes only move values. +//! 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, From 3a44d67e741a87331356d873c52819ee85829234 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Tue, 1 Dec 2026 04:49:38 +0900 Subject: [PATCH 06/29] test(agent): check an object written as the list of its members A derived reader takes a list in place of an object, member by member, and the list with no entry does not tell such a reader apart. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- crates/now-package-broker/src/v2/wire/read.rs | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/crates/now-package-broker/src/v2/wire/read.rs b/crates/now-package-broker/src/v2/wire/read.rs index 259a3a339..70641b5bf 100644 --- a/crates/now-package-broker/src/v2/wire/read.rs +++ b/crates/now-package-broker/src/v2/wire/read.rs @@ -448,6 +448,10 @@ mod tests { .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")) @@ -561,6 +565,31 @@ mod tests { 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", From 85b4c86c5290435165e30204043d800e10217d0d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Tue, 1 Dec 2026 04:28:40 +0900 Subject: [PATCH 07/29] refactor(agent): let command builders take the elevation of the run Each builder that refuses an elevated run derived the elevation from the request, where a user-scope request lowers it to a standard run. A 2.0 request states the elevation of its run on its own, so the builders now take it as a parameter, and the existing entry points keep deriving it the same way. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- .../src/command_builder/bun.rs | 11 +++-- .../src/command_builder/cargo.rs | 11 +++-- .../src/command_builder/npm.rs | 11 +++-- .../src/command_builder/pip.rs | 11 +++-- .../src/command_builder/powershell.rs | 40 ++++++++++++++----- .../src/command_builder/scoop.rs | 11 +++-- .../src/command_builder/vcpkg.rs | 11 +++-- 7 files changed, 79 insertions(+), 27 deletions(-) diff --git a/crates/now-package-broker/src/command_builder/bun.rs b/crates/now-package-broker/src/command_builder/bun.rs index db65d8368..a8cc059b9 100644 --- a/crates/now-package-broker/src/command_builder/bun.rs +++ b/crates/now-package-broker/src/command_builder/bun.rs @@ -22,7 +22,12 @@ 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, crate::evaluator::effective_execution_elevation(request)) +} + +/// Build the command of a run whose token has the elevation `elevation`. +pub(crate) fn build_bun_command_as(request: &PackageRequest, elevation: Elevation) -> anyhow::Result> { + validate_bun_request(request, elevation)?; let operation = match request.operation { Operation::Install | Operation::Update => "add", @@ -44,12 +49,12 @@ pub fn build_bun_command(request: &PackageRequest) -> anyhow::Result ]) } -fn validate_bun_request(request: &PackageRequest) -> anyhow::Result<()> { +fn validate_bun_request(request: &PackageRequest, 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"); } diff --git a/crates/now-package-broker/src/command_builder/cargo.rs b/crates/now-package-broker/src/command_builder/cargo.rs index cdf7cb536..72555d665 100644 --- a/crates/now-package-broker/src/command_builder/cargo.rs +++ b/crates/now-package-broker/src/command_builder/cargo.rs @@ -14,7 +14,12 @@ 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, crate::evaluator::effective_execution_elevation(request)) +} + +/// Build the command of a run whose token has the elevation `elevation`. +pub(crate) fn build_cargo_command_as(request: &PackageRequest, elevation: Elevation) -> anyhow::Result> { + validate_cargo_request(request, elevation)?; let operation = match request.operation { Operation::Install | Operation::Update => "install", @@ -60,11 +65,11 @@ pub fn build_cargo_command(request: &PackageRequest) -> anyhow::Result anyhow::Result<()> { +fn validate_cargo_request(request: &PackageRequest, 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)? { diff --git a/crates/now-package-broker/src/command_builder/npm.rs b/crates/now-package-broker/src/command_builder/npm.rs index 169c32b7c..e8ff15c19 100644 --- a/crates/now-package-broker/src/command_builder/npm.rs +++ b/crates/now-package-broker/src/command_builder/npm.rs @@ -28,7 +28,12 @@ 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, crate::evaluator::effective_execution_elevation(request)) +} + +/// Build the command of a run whose token has the elevation `elevation`. +pub(crate) fn build_npm_command_as(request: &PackageRequest, elevation: Elevation) -> anyhow::Result> { + validate_npm_request(request, elevation)?; let mut script = String::from(SCRIPT_PREFIX); @@ -55,11 +60,11 @@ pub fn build_npm_command(request: &PackageRequest) -> anyhow::Result ]) } -fn validate_npm_request(request: &PackageRequest) -> anyhow::Result<()> { +fn validate_npm_request(request: &PackageRequest, 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() { diff --git a/crates/now-package-broker/src/command_builder/pip.rs b/crates/now-package-broker/src/command_builder/pip.rs index ab575214f..cbac7d00f 100644 --- a/crates/now-package-broker/src/command_builder/pip.rs +++ b/crates/now-package-broker/src/command_builder/pip.rs @@ -12,7 +12,12 @@ 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, crate::evaluator::effective_execution_elevation(request)) +} + +/// Build the command of a run whose token has the elevation `elevation`. +pub(crate) fn build_pip_command_as(request: &PackageRequest, elevation: Elevation) -> anyhow::Result> { + validate_pip_request(request, elevation)?; let mut command = vec![ "python.exe".to_owned(), @@ -56,11 +61,11 @@ 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, 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() { diff --git a/crates/now-package-broker/src/command_builder/powershell.rs b/crates/now-package-broker/src/command_builder/powershell.rs index ccf2cb523..6878b6c35 100644 --- a/crates/now-package-broker/src/command_builder/powershell.rs +++ b/crates/now-package-broker/src/command_builder/powershell.rs @@ -44,7 +44,15 @@ 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> { - validate_powershell_request(request, false)?; + build_powershell5_command_as(request, crate::evaluator::effective_execution_elevation(request)) +} + +/// Build the Windows PowerShell command of a run whose token has the elevation `elevation`. +pub(crate) fn build_powershell5_command_as( + request: &PackageRequest, + elevation: Elevation, +) -> anyhow::Result> { + validate_powershell_request(request, false, elevation)?; let mut script = SCRIPT_PREFIX.to_owned(); @@ -102,7 +110,15 @@ pub fn build_powershell5_command(request: &PackageRequest) -> anyhow::Result anyhow::Result> { - build_powershell7(request, false) + build_powershell7_command_as(request, crate::evaluator::effective_execution_elevation(request)) +} + +/// Build the PowerShell 7 command of a run whose token has the elevation `elevation`. +pub(crate) fn build_powershell7_command_as( + request: &PackageRequest, + elevation: Elevation, +) -> anyhow::Result> { + build_powershell7(request, false, elevation) } /// Build a PowerShell 7.x command for a remote grant. @@ -111,11 +127,15 @@ pub fn build_powershell7_command(request: &PackageRequest) -> anyhow::Result anyhow::Result> { - build_powershell7(request, true) + build_powershell7(request, true, crate::evaluator::effective_execution_elevation(request)) } -fn build_powershell7(request: &PackageRequest, remote_grant: bool) -> anyhow::Result> { - validate_powershell_request(request, remote_grant)?; +fn build_powershell7( + request: &PackageRequest, + remote_grant: bool, + elevation: Elevation, +) -> anyhow::Result> { + validate_powershell_request(request, remote_grant, elevation)?; let mut script = SCRIPT_PREFIX.to_owned(); @@ -185,7 +205,11 @@ fn build_powershell7(request: &PackageRequest, remote_grant: bool) -> anyhow::Re ]) } -fn validate_powershell_request(request: &PackageRequest, allow_default_update_source: bool) -> anyhow::Result<()> { +fn validate_powershell_request( + request: &PackageRequest, + 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"); } @@ -203,9 +227,7 @@ fn validate_powershell_request(request: &PackageRequest, allow_default_update_so // The executor points an elevated Windows PowerShell run at an empty store, where PowerShellGet registers // only its built-in PSGallery; PSResourceGet's store can't be moved. // Uninstall downloads nothing, so it resolves no repository. - if request.operation != Operation::Uninstall - && crate::evaluator::effective_execution_elevation(request) == Elevation::Elevated - { + if request.operation != Operation::Uninstall && elevation == Elevation::Elevated { if request.manager == ManagerName::PowerShell7 { bail!( "elevated PowerShell 7 installs and updates are not supported by the broker, \ diff --git a/crates/now-package-broker/src/command_builder/scoop.rs b/crates/now-package-broker/src/command_builder/scoop.rs index bfa05e086..cec16e5c9 100644 --- a/crates/now-package-broker/src/command_builder/scoop.rs +++ b/crates/now-package-broker/src/command_builder/scoop.rs @@ -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> { - validate_scoop_request(request)?; + build_scoop_command_as(request, crate::evaluator::effective_execution_elevation(request)) +} + +/// Build the command of a run whose token has the elevation `elevation`. +pub(crate) fn build_scoop_command_as(request: &PackageRequest, elevation: Elevation) -> anyhow::Result> { + validate_scoop_request(request, elevation)?; let operation = match request.operation { Operation::Install => "install", @@ -75,7 +80,7 @@ pub fn build_scoop_command(request: &PackageRequest) -> anyhow::Result anyhow::Result<()> { +fn validate_scoop_request(request: &PackageRequest, elevation: Elevation) -> anyhow::Result<()> { // UNTESTED: refusing every 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). @@ -89,7 +94,7 @@ fn validate_scoop_request(request: &PackageRequest) -> anyhow::Result<()> { 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" ); diff --git a/crates/now-package-broker/src/command_builder/vcpkg.rs b/crates/now-package-broker/src/command_builder/vcpkg.rs index 1260e6977..0bb37aa07 100644 --- a/crates/now-package-broker/src/command_builder/vcpkg.rs +++ b/crates/now-package-broker/src/command_builder/vcpkg.rs @@ -16,7 +16,12 @@ use super::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, crate::evaluator::effective_execution_elevation(request)) +} + +/// Build the command of a run whose token has the elevation `elevation`. +pub(crate) fn build_vcpkg_command_as(request: &PackageRequest, elevation: Elevation) -> anyhow::Result> { + validate_vcpkg_request(request, elevation)?; let operation = match request.operation { Operation::Install => "install", @@ -35,11 +40,11 @@ pub fn build_vcpkg_command(request: &PackageRequest) -> anyhow::Result anyhow::Result<()> { +fn validate_vcpkg_request(request: &PackageRequest, 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() { From 52cebfe951fabb6dc2d17a40b4f3cf0a2c9da675 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Tue, 1 Dec 2026 04:48:55 +0900 Subject: [PATCH 08/29] feat(agent): let an event channel announce the version of its protocol The first frame of an event channel states the protocol version, which was fixed at 1.0. A channel opened for an operation of the 2.0 protocol announces 2.0, the version its clients require, while the channels of the 1.x routes keep announcing 1.0. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- .../now-package-broker/src/event_channel.rs | 95 +++++++++++++++++-- 1 file changed, 88 insertions(+), 7 deletions(-) diff --git a/crates/now-package-broker/src/event_channel.rs b/crates/now-package-broker/src/event_channel.rs index 1c2c09689..fe0b7169f 100644 --- a/crates/now-package-broker/src/event_channel.rs +++ b/crates/now-package-broker/src/event_channel.rs @@ -508,15 +508,35 @@ 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 struct ChannelVersion { + major: u16, + minor: u16, +} + +impl ChannelVersion { + /// The version of the channel of an operation started on a 1.x route. + pub const V1_0: Self = Self { + major: now_policy_api::event_channel::EVENT_CHANNEL_VERSION_MAJOR, + minor: now_policy_api::event_channel::EVENT_CHANNEL_VERSION_MINOR, + }; + + /// 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 + pub const V2_0: Self = Self { major: 2, minor: 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 +549,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,6 +575,17 @@ 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`]. + 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); @@ -588,14 +619,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! { @@ -616,8 +652,8 @@ mod windows_channel { let mut server = server; let hello = EventFrame::Hello { - version_major: EVENT_CHANNEL_VERSION_MAJOR, - version_minor: EVENT_CHANNEL_VERSION_MINOR, + version_major: version.major, + version_minor: version.minor, }; if let Err(error) = write_frame(&mut server, &hello).await { sink.abandon(); @@ -1126,6 +1162,51 @@ 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. + ] + ); + } + + // 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"); From 431ee5f2d638b758a9b95c42c359d4084fdf8060 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Tue, 1 Dec 2026 04:48:56 +0900 Subject: [PATCH 09/29] feat(agent): hold the operations started by 2.0 requests An allowed 2.0 package request becomes an operation the broker starts on the executor the 1.x routes use, tracks, reports and cancels as the 2.0 protocol states. These operations live in their own registry, so a 1.x request never names one and a 2.0 request never names an operation of a 1.x route. An operation belongs to the user and the executable of its caller, and a request id is unique per owner: an equal request with the same id gets the operation it started, and an unequal one conflicts. The caller supplies what decides that two requests are equal, because that depends on their encoding. The command comes from the existing builders, which now take the elevation of the run and the WinGet installer arguments beside the 1.x request they read. The run has the elevation the request states, whatever its scope. An operation ends `Failed` without running a step when it has a pre or post command and an elevated run, when it updates under a manager that updates from the source recorded at install, which the broker does not read yet, and when no command can be built for it. The module root moves to `execution/mod.rs` because the crate's lints require that form for a module with sub-modules. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- .../src/command_builder/mod.rs | 27 +- .../src/command_builder/winget.rs | 34 + crates/now-package-broker/src/v2/execution.rs | 1 - .../src/v2/execution/mod.rs | 10 + .../src/v2/execution/operations.rs | 1234 +++++++++++++++++ .../src/v2/execution/owner.rs | 123 ++ .../src/v2/execution/plan.rs | 503 +++++++ 7 files changed, 1930 insertions(+), 2 deletions(-) delete mode 100644 crates/now-package-broker/src/v2/execution.rs create mode 100644 crates/now-package-broker/src/v2/execution/mod.rs create mode 100644 crates/now-package-broker/src/v2/execution/operations.rs create mode 100644 crates/now-package-broker/src/v2/execution/owner.rs create mode 100644 crates/now-package-broker/src/v2/execution/plan.rs diff --git a/crates/now-package-broker/src/command_builder/mod.rs b/crates/now-package-broker/src/command_builder/mod.rs index a33263134..b56808380 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,31 @@ 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. +pub(crate) fn build_command_as( + request: &PackageRequest, + elevation: Elevation, + installer_arguments: Option>, +) -> anyhow::Result> { + match request.manager { + ManagerName::Bun => bun::build_bun_command_as(request, elevation), + ManagerName::Cargo => cargo::build_cargo_command_as(request, elevation), + ManagerName::Dotnet => dotnet::build_dotnet_command(request), + ManagerName::Npm => npm::build_npm_command_as(request, elevation), + ManagerName::Winget => winget::build_winget_command_with(request, installer_arguments), + ManagerName::PowerShell => powershell::build_powershell5_command_as(request, elevation), + ManagerName::PowerShell7 => powershell::build_powershell7_command_as(request, elevation), + ManagerName::Chocolatey => chocolatey::build_chocolatey_command(request), + ManagerName::Pip => pip::build_pip_command_as(request, elevation), + ManagerName::Scoop => scoop::build_scoop_command_as(request, elevation), + ManagerName::Vcpkg => vcpkg::build_vcpkg_command_as(request, 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. diff --git a/crates/now-package-broker/src/command_builder/winget.rs b/crates/now-package-broker/src/command_builder/winget.rs index d054088eb..671107cd8 100644 --- a/crates/now-package-broker/src/command_builder/winget.rs +++ b/crates/now-package-broker/src/command_builder/winget.rs @@ -12,6 +12,23 @@ use super::{ /// /// Returns the command as a list of arguments (first element is the executable). pub fn build_winget_command(request: &PackageRequest) -> anyhow::Result> { + build_winget_command_with(request, None) +} + +/// 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. +pub(crate) fn build_winget_command_with( + request: &PackageRequest, + installer_arguments: Option>, +) -> anyhow::Result> { let source = if uses_default_source("WinGet", request)? { None } else { @@ -103,6 +120,23 @@ 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 => {} + } + } + // Append any custom parameters. for param in &request.options.custom_parameters { if !param.is_empty() { 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..b9ae501c1 --- /dev/null +++ b/crates/now-package-broker/src/v2/execution/mod.rs @@ -0,0 +1,10 @@ +//! Operations started by a 2.0 request. + +mod operations; +mod owner; +mod plan; + +pub use self::operations::{ + Caller, Existing, MAX_MESSAGE_BYTES, 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..85015d243 --- /dev/null +++ b/crates/now-package-broker/src/v2/execution/operations.rs @@ -0,0 +1,1234 @@ +//! 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_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, 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 most bytes the message of an operation has ([§status]). +/// +/// [§status]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#status +pub const MAX_MESSAGE_BYTES: usize = 2048; + +/// The status of an operation ([§operations]). +/// +/// [§operations]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#operations +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Status { + /// The operation was started, and its manager process has not been launched. + Starting, + /// The operation has launched its manager process. + Running, + /// The operation was asked to cancel and has not ended. + Canceling, + /// The operation ended after its manager process exited on its own with code 0. + Completed, + /// The operation ended otherwise. + Failed, + /// The broker ended the operation on a cancel request. + Canceled, +} + +impl Status { + /// Whether an operation with this status has ended. + pub fn is_terminal(self) -> bool { + matches!(self, Self::Completed | Self::Failed | Self::Canceled) + } + + /// The name of the status in a response. + pub fn as_str(self) -> &'static str { + match self { + Self::Starting => "Starting", + Self::Running => "Running", + Self::Canceling => "Canceling", + Self::Completed => "Completed", + Self::Failed => "Failed", + Self::Canceled => "Canceled", + } + } +} + +/// 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, of at most [`MAX_MESSAGE_BYTES`] bytes. + 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. + 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| truncated(message, MAX_MESSAGE_BYTES)); + 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. + if let Some(events) = &self.events { + events.finish(); + } + } +} + +/// Returns `text` without the characters that do not fit in `max_bytes` bytes. +fn truncated(mut text: String, max_bytes: usize) -> String { + if max_bytes < text.len() { + let mut end = max_bytes; + while !text.is_char_boundary(end) { + end -= 1; + } + text.truncate(end); + } + text +} + +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. + /// + /// Must be called from a Tokio runtime, on which the operation runs. + pub fn start(&self, caller: &Caller, request_id: &str, request_key: K, request: &Request, context: C) -> Start { + // 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(); + + let (events, event_pipe) = + match open_operation_channel_announcing(ChannelVersion::V2_0, &operation_id, user_sid) { + Ok((sink, channel)) => (Some(sink), Some(channel.path)), + Err(error) => { + // The operation runs without a channel, and its response names no pipe. + warn!(%operation_id, error = format!("{error:#}"), "Failed to create the event channel"); + (None, None) + } + }; + + let mut record = Record { + owner: caller.owner.clone(), + request_key, + context: context.clone(), + event_pipe: event_pipe.clone(), + events: events.clone(), + cancel: CancellationToken::new(), + state: OperationState { + status: Status::Starting, + started_at: None, + completed_at: None, + exit_code: None, + message: None, + }, + ended: None, + }; + + let execution = match plan(request) { + Ok(plan) => { + info!( + %operation_id, + %user_sid, + effective_user = %caller.display_name, + manager = request.manager.as_str(), + operation = request.operation.as_str(), + "Started an operation" + ); + Some(ExecutionContext { + kill_processes: plan.kill_processes, + 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: record.cancel.clone(), + event_sink: events, + }) + } + Err(error) => { + let reason = format!("{error:#}"); + warn!(%operation_id, %user_sid, error = %reason, "Operation failed before its first step"); + record.end(Status::Failed, None, Some(reason)); + None + } + }; + + 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); + + // The steps run once the broker holds the operation, so that every report of theirs finds it. + if let Some(execution) = execution { + tokio::spawn(self.clone().run(operation_id, execution)); + } + + 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, + } + + /// 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()); + } + } + } + } + } + + 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, status.as_str(), |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.len() <= 2048, "{} bytes", message.len()); + } + + // 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::User); + + 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: 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); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648: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) + ); + } + + // 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() { + use tokio::io::AsyncReadExt as _; + use win_api_wrappers::process::Process; + use windows::Win32::Security::TOKEN_QUERY; + + let fixture = Fixture::new(); + // The pipe only lets the user of the operation's owner read it. + let current_user = Process::current_process() + .token(TOKEN_QUERY) + .expect("open current process token") + .sid_and_attributes() + .expect("query token user SID") + .sid; + let caller = caller(Owner::new(¤t_user, std::path::Path::new(r"C:\Tools\client.exe"))); + + 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 mut frames = [0u8; 28]; + tokio::time::timeout(Duration::from_secs(10), client.read_exact(&mut frames)) + .await + .expect("the frames in time") + .expect("the frames"); + + // 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. + ] + ); + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §operations + #[tokio::test] + async fn operations_started_on_1_x_routes_and_by_2_0_requests_do_not_see_each_other() { + let fixture = Fixture::new(); + let alice = alice(); + let tracker = crate::operation_tracker::OperationTracker::new(); + let owner_key = "S-1-5-18"; + + let mut request_1_x = super::super::plan::tests::request_1_x(&winget_install()); + request_1_x.request_id = now_policy_api::ResourceId::from("request-1"); + let (operation_1_x, _) = tracker + .register(owner_key, &request_1_x, now_policy_api::ResourceId::from("op-1-x")) + .expect("register"); + + // The 1.x operation neither answers a 2.0 status request nor replays or conflicts with a 2.0 request. + assert_eq!(fixture.operations.status(&alice.owner, operation_1_x.as_ref()), None); + assert_eq!(fixture.operations.existing(&alice.owner, "request-1", &"request"), None); + let started = fixture.start(&alice, "request-1", &winget_install()); + + // The 2.0 operation is not one the 1.x routes find. + assert!(tracker.get(&started.operation_id).is_none()); + assert!(tracker.get_for_owner(&started.operation_id, owner_key).is_none()); + } + + // 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(); + + fixture.operations.evict_expired(after + Duration::from_secs(300)); + + 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..141051023 --- /dev/null +++ b/crates/now-package-broker/src/v2/execution/owner.rs @@ -0,0 +1,123 @@ +//! Who an operation belongs to. + +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. +/// +/// [§def-owner]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#def-owner +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct Owner { + user_sid: Sid, + /// The code points of the executable path, each replaced by its uppercase mapping. + folded_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 { + Self { + user_sid: user_sid.clone(), + folded_path: fold(executable_path), + } + } + + /// The SID of the user. + pub fn user_sid(&self) -> &Sid { + &self.user_sid + } +} + +/// Returns the code points of `path` after the replacement that makes equal paths compare equal ignoring case +/// ([§text-comparison]). +/// +/// A path is a sequence of 16-bit units that need not be valid UTF-16; an unpaired surrogate stands for itself. +/// +/// [§text-comparison]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.policy.md#text-comparison +fn fold(path: &Path) -> Box<[u32]> { + char::decode_utf16(path.as_os_str().encode_wide()) + .map(|unit| match unit { + Ok(character) => u32::from(simple_uppercase(character)), + Err(unpaired) => u32::from(unpaired.unpaired_surrogate()), + }) + .collect() +} + +/// Returns the simple uppercase mapping of `character`, or `character` when it has none. +/// +/// UNTESTED: The result is the simple uppercase mapping of `UnicodeData.txt` of Unicode 16.0.0 for every code point. +/// The standard library gives the full mapping of the Unicode version of the toolchain, and no simple mapping. +/// A full mapping of one character is the simple one, so this differs from the contract for a code point whose full +/// mapping is several characters while `UnicodeData.txt` gives it a simple one, such as U+1F80, which stays itself +/// here instead of becoming U+1F88, and for a code point whose mapping changed between the two Unicode versions. +/// Two callers whose paths differ only by such a code point are then two owners where the contract has one, or one +/// owner where it has two, and an owner is what decides who sees, replays and cancels an operation. +/// The policy evaluator has the pinned table but does not export it; use its comparison once it does. +fn simple_uppercase(character: char) -> char { + let mut mapping = character.to_uppercase(); + match (mapping.next(), mapping.next()) { + (Some(upper), None) => upper, + _ => character, + } +} + +#[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}" + ); + } + } + + // 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. + for (left, right) in [ + (r"C:\Tool\tool.exe", r"C:\Tool\other.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..b7639a11f --- /dev/null +++ b/crates/now-package-broker/src/v2/execution/plan.rs @@ -0,0 +1,503 @@ +//! 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 and the WinGet installer arguments, 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::build_command_as; +use crate::command_builder::winget::InstallerArguments; + +/// 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, + 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. + // 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`. + if request.operation == Operation::Update && 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 builder_request = builder_request(request, elevation); + 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), + }); + let command = build_command_as(&builder_request, elevation, installer_arguments)?; + + // The executor refuses a whole plan for one name it cannot hand to `taskkill /IM` as one literal image name. + // A failure to stop a process is ignored, so such a name is left out and the other steps still run. + let kill_processes = opt_ins + .kill_before_operation + .iter() + .flat_map(|kill| &kill.processes) + .filter(|name| crate::evaluator::is_acceptable_kill_process_name(name)) + .cloned() + .collect(); + + Ok(Plan { + 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 `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) +} + +/// 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 { + name: request.source.name.clone(), + 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, + // A 2.0 request has no member that asks for pre-release versions. + pre_release: false, + 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::{ + 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: 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(), + } + } + + /// The 1.x request that asks for what `request` asks for. + pub(in crate::v2::execution) fn request_1_x(request: &Request) -> v1::PackageRequest { + builder_request(request, v1::Elevation::Standard) + } + + 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) in [ + (Operation::Install, InstallerArgumentsMode::Append, "--custom"), + (Operation::Install, InstallerArgumentsMode::Replace, "--override"), + (Operation::Update, InstallerArgumentsMode::Append, "--custom"), + (Operation::Update, InstallerArgumentsMode::Replace, "--override"), + ] { + 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:?}" + ); + + let other_option = if option == "--custom" { "--override" } else { "--custom" }; + 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() + ); + } + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.policy.md §manager-winget + #[test] + fn winget_without_scope_passes_no_scope_option() { + for elevation in [Elevation::NonElevated, Elevation::Elevated] { + let mut request = winget_install(); + request.elevation = elevation; + + let command = plan(&request) + .unwrap_or_else(|error| panic!("{}: {error:#}", elevation.as_str())) + .command; + + assert!( + !command.iter().any(|element| element.starts_with("--scope")), + "{}: {command:?}", + elevation.as_str() + ); + } + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.policy.md §def-elevation + #[test] + fn the_run_has_the_elevation_the_request_asks_for_whatever_its_scope() { + let mut request = winget_install(); + request.elevation = Elevation::Elevated; + request.scope = Some(Scope::User); + assert_eq!( + plan(&request).expect("elevated user scope").elevation, + v1::Elevation::Elevated + ); + + let mut request = winget_install(); + request.elevation = Elevation::NonElevated; + request.scope = Some(Scope::User); + assert_eq!( + plan(&request).expect("standard user scope").elevation, + v1::Elevation::Standard + ); + } + + // 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::User)] { + let mut request = winget_install(); + request.manager = Manager::Npm; + request.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:?}"); + } + } + + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §operations + #[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: 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: 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())); + } + } + + // 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: 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()], + }); + + assert_eq!( + plan(&request).expect("plan").kill_processes, + ["Contoso Tool.exe", "helper.EXE"] + ); + } + + // 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 mut request = winget_install(); + request.opt_ins.kill_before_operation = Some(KillBeforeOperation { + processes: vec!["notepad".to_owned(), "tool.exe".to_owned(), r"C:\tool.exe".to_owned()], + }); + + assert_eq!(plan(&request).expect("plan").kill_processes, ["tool.exe"]); + } +} From 42482f13ff5c77e85674beb1c3f5258734458246 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Tue, 1 Dec 2026 05:41:12 +0900 Subject: [PATCH 10/29] fix(agent): let nobody open the event pipe of a 2.0 operation for writing The pipe of an operation's event channel granted the local system and Administrators full control, which lets them write to a one-way channel and change who can open the pipe. A channel that announces 2.0 now grants them read access, as it grants the operation owner's user. The channel of a 1.x operation keeps its access, which 1.x clients may depend on. The broker's own end is the handle that created the pipe, so its writes do not depend on these entries. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- .../now-package-broker/src/event_channel.rs | 132 ++++++++++++++++-- 1 file changed, 121 insertions(+), 11 deletions(-) diff --git a/crates/now-package-broker/src/event_channel.rs b/crates/now-package-broker/src/event_channel.rs index fe0b7169f..3901df037 100644 --- a/crates/now-package-broker/src/event_channel.rs +++ b/crates/now-package-broker/src/event_channel.rs @@ -581,7 +581,8 @@ mod windows_channel { /// Create the event channel for an operation, whose `Hello` frame announces `version`. /// - /// It is otherwise [`open_operation_channel`]. + /// 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, @@ -591,7 +592,7 @@ mod windows_channel { 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 @@ -714,27 +715,44 @@ 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 cannot open it for writing. + // Full control would let them write to the channel and change who can open the pipe. + // 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. + let privileged_access = if version == ChannelVersion::V2_0 { + FILE_GENERIC_READ.0 + } else { + GENERIC_ALL.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), @@ -745,7 +763,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")?; @@ -1189,6 +1216,89 @@ mod pipe_tests { ); } + /// 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() { From 4397c6d8fa44d69c9b5ef9ff1b6dafde687f086c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Tue, 1 Dec 2026 05:43:22 +0900 Subject: [PATCH 11/29] test(agent): cite the rule behind refusing elevated pre and post commands A request with `PrePostCommands` whose `Elevation` is `Elevated` is `NotRunnable`, for which the broker runs nothing. The two tests of the refusal behind that answer cited the rule about a `NonElevated` request whose token turns out elevated, which says nothing about this request. `Operations::start` now states that its caller answers `NotRunnable` without calling it, because a call takes the request id. The test that built a 1.x tracker and a 2.0 registry sharing nothing, and checked that neither finds the other's operation, is removed: no change to either could make it fail, since the routes choose which one a request reaches. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- .../src/v2/execution/operations.rs | 33 +++++-------------- .../src/v2/execution/plan.rs | 13 ++++---- 2 files changed, 15 insertions(+), 31 deletions(-) diff --git a/crates/now-package-broker/src/v2/execution/operations.rs b/crates/now-package-broker/src/v2/execution/operations.rs index 85015d243..2b08ca7e1 100644 --- a/crates/now-package-broker/src/v2/execution/operations.rs +++ b/crates/now-package-broker/src/v2/execution/operations.rs @@ -255,7 +255,13 @@ where /// 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 { // 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. @@ -1028,7 +1034,8 @@ mod tests { assert_eq!(fixture.executed_plans().await, 0); } - // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §operations + // Such a request is `NotRunnable`, and "the broker runs nothing for the request" even when one gets an operation. + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §not-runnable #[tokio::test] async fn pre_post_commands_for_an_elevated_run_end_the_operation_failed_without_a_step() { use now_policy_eval::{Elevation, PrePostCommands}; @@ -1148,30 +1155,6 @@ mod tests { ); } - // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §operations - #[tokio::test] - async fn operations_started_on_1_x_routes_and_by_2_0_requests_do_not_see_each_other() { - let fixture = Fixture::new(); - let alice = alice(); - let tracker = crate::operation_tracker::OperationTracker::new(); - let owner_key = "S-1-5-18"; - - let mut request_1_x = super::super::plan::tests::request_1_x(&winget_install()); - request_1_x.request_id = now_policy_api::ResourceId::from("request-1"); - let (operation_1_x, _) = tracker - .register(owner_key, &request_1_x, now_policy_api::ResourceId::from("op-1-x")) - .expect("register"); - - // The 1.x operation neither answers a 2.0 status request nor replays or conflicts with a 2.0 request. - assert_eq!(fixture.operations.status(&alice.owner, operation_1_x.as_ref()), None); - assert_eq!(fixture.operations.existing(&alice.owner, "request-1", &"request"), None); - let started = fixture.start(&alice, "request-1", &winget_install()); - - // The 2.0 operation is not one the 1.x routes find. - assert!(tracker.get(&started.operation_id).is_none()); - assert!(tracker.get_for_owner(&started.operation_id, owner_key).is_none()); - } - // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §operations #[tokio::test] async fn an_ended_operation_is_held_for_300_seconds() { diff --git a/crates/now-package-broker/src/v2/execution/plan.rs b/crates/now-package-broker/src/v2/execution/plan.rs index b7639a11f..ea922bbf5 100644 --- a/crates/now-package-broker/src/v2/execution/plan.rs +++ b/crates/now-package-broker/src/v2/execution/plan.rs @@ -41,6 +41,11 @@ pub(super) fn plan(request: &Request) -> anyhow::Result { // 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 @@ -225,11 +230,6 @@ pub(super) mod tests { } } - /// The 1.x request that asks for what `request` asks for. - pub(in crate::v2::execution) fn request_1_x(request: &Request) -> v1::PackageRequest { - builder_request(request, v1::Elevation::Standard) - } - fn with_installer_arguments(operation: Operation, mode: InstallerArgumentsMode) -> Request { let mut request = winget_install(); request.operation = operation; @@ -360,7 +360,8 @@ pub(super) mod tests { } } - // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §operations + // 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 [ From ffe8bd626afb55483c789285f487330e56c167b6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Tue, 1 Dec 2026 05:44:53 +0900 Subject: [PATCH 12/29] fix(agent): plan a 2.0 operation before locking the registry `Operations::start` built the plan of a request while it held the lock of the registry, so every status, cancel and execution request waited for the command builders. The plan depends on the request only and is now made first. The lookup and the insertion stay under one acquisition of the lock, and so does the creation of the event pipe: a channel opened for a request that turns out to have an operation could only be closed by finishing it, which keeps its pipe open for 60 seconds. The names of `KillBeforeOperation` that the executor cannot hand to `taskkill` as one image name were left out of the plan without a trace. They are still left out, since nothing can be attempted for them, and each is now logged with the id of its operation. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- .../src/v2/execution/operations.rs | 107 +++++++++++------- .../src/v2/execution/plan.rs | 24 ++-- 2 files changed, 79 insertions(+), 52 deletions(-) diff --git a/crates/now-package-broker/src/v2/execution/operations.rs b/crates/now-package-broker/src/v2/execution/operations.rs index 2b08ca7e1..7117bcf31 100644 --- a/crates/now-package-broker/src/v2/execution/operations.rs +++ b/crates/now-package-broker/src/v2/execution/operations.rs @@ -263,6 +263,9 @@ where /// /// [§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; @@ -280,44 +283,21 @@ where let operation_id = format!("op-{}", Uuid::new_v4()); let user_sid = caller.owner.user_sid(); - let (events, event_pipe) = + // 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)), - Err(error) => { - // The operation runs without a channel, and its response names no pipe. - warn!(%operation_id, error = format!("{error:#}"), "Failed to create the event channel"); - (None, None) - } + 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 mut record = Record { - owner: caller.owner.clone(), - request_key, - context: context.clone(), - event_pipe: event_pipe.clone(), - events: events.clone(), - cancel: CancellationToken::new(), - state: OperationState { - status: Status::Starting, - started_at: None, - completed_at: None, - exit_code: None, - message: None, - }, - ended: None, - }; - - let execution = match plan(request) { + let cancel = CancellationToken::new(); + let (execution, skipped_kill_processes, failure) = match planned { Ok(plan) => { - info!( - %operation_id, - %user_sid, - effective_user = %caller.display_name, - manager = request.manager.as_str(), - operation = request.operation.as_str(), - "Started an operation" - ); - Some(ExecutionContext { + let execution = ExecutionContext { kill_processes: plan.kill_processes, pre_command: plan.pre_command, command: plan.command, @@ -331,17 +311,33 @@ where token_elevation_check: TokenElevationCheck::Exact, custom_install_location: plan.custom_install_location, capture_output: true, - cancel_token: record.cancel.clone(), - event_sink: events, - }) - } - Err(error) => { - let reason = format!("{error:#}"); - warn!(%operation_id, %user_sid, error = %reason, "Operation failed before its first step"); - record.end(Status::Failed, None, Some(reason)); - None + 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(), @@ -355,6 +351,31 @@ where 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, + %process, + "Left a process to stop out of the operation, because its name is not one image name" + ); + } + match &failure { + Some(reason) => { + 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 { tokio::spawn(self.clone().run(operation_id, execution)); diff --git a/crates/now-package-broker/src/v2/execution/plan.rs b/crates/now-package-broker/src/v2/execution/plan.rs index ea922bbf5..052db150b 100644 --- a/crates/now-package-broker/src/v2/execution/plan.rs +++ b/crates/now-package-broker/src/v2/execution/plan.rs @@ -20,6 +20,8 @@ use crate::command_builder::winget::InstallerArguments; 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, @@ -79,17 +81,18 @@ pub(super) fn plan(request: &Request) -> anyhow::Result { let command = build_command_as(&builder_request, elevation, installer_arguments)?; // The executor refuses a whole plan for one name it cannot hand to `taskkill /IM` as one literal image name. - // A failure to stop a process is ignored, so such a name is left out and the other steps still run. - let kill_processes = opt_ins + // Nothing is attempted for such a name: 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 for the caller to log. + let (kill_processes, skipped_kill_processes) = opt_ins .kill_before_operation .iter() .flat_map(|kill| &kill.processes) - .filter(|name| crate::evaluator::is_acceptable_kill_process_name(name)) .cloned() - .collect(); + .partition(|name| crate::evaluator::is_acceptable_kill_process_name(name)); 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(), @@ -485,10 +488,10 @@ pub(super) mod tests { processes: vec!["Contoso Tool.exe".to_owned(), "helper.EXE".to_owned()], }); - assert_eq!( - plan(&request).expect("plan").kill_processes, - ["Contoso Tool.exe", "helper.EXE"] - ); + let plan = plan(&request).expect("plan"); + + assert_eq!(plan.kill_processes, ["Contoso Tool.exe", "helper.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 @@ -499,6 +502,9 @@ pub(super) mod tests { processes: vec!["notepad".to_owned(), "tool.exe".to_owned(), r"C:\tool.exe".to_owned()], }); - assert_eq!(plan(&request).expect("plan").kill_processes, ["tool.exe"]); + let plan = plan(&request).expect("plan"); + + assert_eq!(plan.kill_processes, ["tool.exe"]); + assert_eq!(plan.skipped_kill_processes, ["notepad", r"C:\tool.exe"]); } } From 0f701ba9430bf1b4e4e770d656e10bf2e64d40e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Tue, 1 Dec 2026 05:45:00 +0900 Subject: [PATCH 13/29] fix(agent): include pre-releases when a PowerShell command names one A 2.0 request names the version its command installs and has no member that asks for pre-release versions, so the command never had the option that makes PowerShellGet and PSResourceGet include pre-releases in what they find. PowerShellGet documents that naming a pre-release version is not enough to install it, so an allowed request for one ran a command its manager refused. The command of a `PowerShell` or `PowerShell7` request now has `-AllowPrerelease` or `-Prerelease` exactly when `Package.Version` is a version with a pre-release under the contract's version scheme. The evaluator does not export its reading of that scheme, so the plan reads the version itself. No other manager gets the option, because the builders of several refuse a request that has it. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- .../src/v2/execution/plan.rs | 169 +++++++++++++++++- 1 file changed, 167 insertions(+), 2 deletions(-) diff --git a/crates/now-package-broker/src/v2/execution/plan.rs b/crates/now-package-broker/src/v2/execution/plan.rs index 052db150b..60ce8e4d6 100644 --- a/crates/now-package-broker/src/v2/execution/plan.rs +++ b/crates/now-package-broker/src/v2/execution/plan.rs @@ -109,6 +109,49 @@ 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 { + fn is_numeric(text: &str) -> bool { + text.bytes().all(|byte| byte.is_ascii_digit()) + } + + 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; + }; + + 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'.') +} + /// Rewrites `request` as the 1.x request the command builders read. /// /// The builders read the operation, manager, source, package and options only. @@ -168,8 +211,7 @@ fn builder_request(request: &Request, elevation: v1::Elevation) -> v1::PackageRe }), interactive: opt_ins.interactive, skip_hash_check: opt_ins.skip_hash_check, - // A 2.0 request has no member that asks for pre-release versions. - pre_release: false, + pre_release: names_pre_release(request), custom_install_location: opt_ins .custom_install_location .as_ref() @@ -507,4 +549,127 @@ pub(super) mod tests { assert_eq!(plan.kill_processes, ["tool.exe"]); assert_eq!(plan.skipped_kill_processes, ["notepad", r"C:\tool.exe"]); } + + /// 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: 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: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.policy.md §version-scheme + #[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. + 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}"); + } + } + + // oracle: mutant asking for pre-releases under every manager, whose builders refuse a request that asks for them + #[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.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"); + } } From ad8f657e1f7fbbf3f2b5d782e6e9f7815f3ef61e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Tue, 1 Dec 2026 05:45:16 +0900 Subject: [PATCH 14/29] fix(agent): end a 2.0 operation whose task stops without an end The steps of an operation run on a detached task, which alone records how the operation ends. When that task ended without doing so, as when a step panics, the operation kept a status that is not terminal: the broker held it for ever, its request id replayed it for ever, and its event channel never got `FINISH`. The task now holds a guard that ends the operation `Failed` when it is dropped while the operation has not ended. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- .../src/v2/execution/operations.rs | 113 ++++++++++++++++-- 1 file changed, 100 insertions(+), 13 deletions(-) diff --git a/crates/now-package-broker/src/v2/execution/operations.rs b/crates/now-package-broker/src/v2/execution/operations.rs index 7117bcf31..0c9675edf 100644 --- a/crates/now-package-broker/src/v2/execution/operations.rs +++ b/crates/now-package-broker/src/v2/execution/operations.rs @@ -223,6 +223,30 @@ fn truncated(mut text: String, max_bytes: usize) -> String { text } +/// 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) { + 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 { @@ -378,7 +402,16 @@ where // The steps run once the broker holds the operation, so that every report of theirs finds it. if let Some(execution) = execution { - tokio::spawn(self.clone().run(operation_id, 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) @@ -545,6 +578,8 @@ mod tests { 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. @@ -576,6 +611,7 @@ mod tests { ctx.cancel_token.cancelled().await; return Err(OperationCanceled.into()); } + Step::Panic => panic!("a step panicked, as the test asked"), } } } @@ -1124,22 +1160,37 @@ mod tests { ); } - // 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() { - use tokio::io::AsyncReadExt as _; + /// 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 fixture = Fixture::new(); - // The pipe only lets the user of the operation's owner read it. let current_user = Process::current_process() .token(TOKEN_QUERY) .expect("open current process token") .sid_and_attributes() .expect("query token user SID") .sid; - let caller = caller(Owner::new(¤t_user, std::path::Path::new(r"C:\Tools\client.exe"))); + 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()); @@ -1158,11 +1209,7 @@ mod tests { .expect("connect to the event channel pipe"); fixture.step(Step::Launch(at(5))); fixture.step(Step::Exit(0)); - let mut frames = [0u8; 28]; - tokio::time::timeout(Duration::from_secs(10), client.read_exact(&mut frames)) - .await - .expect("the frames in time") - .expect("the frames"); + let frames: [u8; 28] = read_frames(&mut client).await; // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §frame-order assert_eq!( @@ -1176,6 +1223,46 @@ mod tests { ); } + // 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. + ] + ); + + let after = Instant::now(); + fixture.operations.evict_expired(after + Duration::from_secs(300)); + assert_eq!(fixture.operations.status(&caller.owner, &started.operation_id), None); + assert_eq!( + fixture.operations.existing(&caller.owner, "request-1", &"request"), + None + ); + } + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §operations #[tokio::test] async fn an_ended_operation_is_held_for_300_seconds() { From b00c382083b184e70ac6c1bb7de4ff858a093874 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Tue, 1 Dec 2026 06:09:40 +0900 Subject: [PATCH 15/29] fix(agent): decide the access to an event pipe for each channel version The local system and Administrators got full control of the pipe of every channel but one announcing 2.0, so a version added later would have got full control without anyone deciding it. The channel version is now an enumeration, and the access is a match on it with no default: full control is for 1.0, which existing 1.x clients may depend on, and a new version does not compile until its access is chosen. The comment on the access entries claimed that the two principals cannot change who can open the pipe. The entries only withhold write access to the data of the pipe; the owner of the pipe keeps the right to read and to change its DACL. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- .../now-package-broker/src/event_channel.rs | 49 +++++++++++-------- 1 file changed, 29 insertions(+), 20 deletions(-) diff --git a/crates/now-package-broker/src/event_channel.rs b/crates/now-package-broker/src/event_channel.rs index 3901df037..04451b508 100644 --- a/crates/now-package-broker/src/event_channel.rs +++ b/crates/now-package-broker/src/event_channel.rs @@ -510,22 +510,26 @@ 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 struct ChannelVersion { - major: u16, - minor: u16, -} - -impl ChannelVersion { +pub enum ChannelVersion { /// The version of the channel of an operation started on a 1.x route. - pub const V1_0: Self = Self { - major: now_policy_api::event_channel::EVENT_CHANNEL_VERSION_MAJOR, - minor: now_policy_api::event_channel::EVENT_CHANNEL_VERSION_MINOR, - }; - + 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 - pub const V2_0: Self = Self { major: 2, minor: 0 }; + 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)] @@ -652,9 +656,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: version.major, - version_minor: version.minor, + version_major, + version_minor, }; if let Err(error) = write_frame(&mut server, &hello).await { sink.abandon(); @@ -733,15 +738,19 @@ mod windows_channel { .context("failed to create Administrators SID")?; // 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 cannot open it for writing. - // Full control would let them write to the channel and change who can open 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. - let privileged_access = if version == ChannelVersion::V2_0 { - FILE_GENERIC_READ.0 - } else { - GENERIC_ALL.0 + // + // 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([ From a6393c6e75de59a6b63d3017ffe6ddf12233a556 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Tue, 1 Dec 2026 06:09:40 +0900 Subject: [PATCH 16/29] fix(agent): end an operation without a panic on a poisoned event queue An operation whose task panics is ended `Failed` while the panic unwinds. Ending it queues a status update and a finish on the event channel, and both panicked when the lock of the queue was poisoned; a panic during unwinding aborts the broker. Both now take a poisoned queue as it is, as marking the output incomplete already does, so the record ends `Failed` and the queue is closed. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- .../now-package-broker/src/event_channel.rs | 28 +++++++++++++++++-- .../src/v2/execution/operations.rs | 3 ++ 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/crates/now-package-broker/src/event_channel.rs b/crates/now-package-broker/src/event_channel.rs index 04451b508..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; } @@ -1129,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))] diff --git a/crates/now-package-broker/src/v2/execution/operations.rs b/crates/now-package-broker/src/v2/execution/operations.rs index 0c9675edf..f2af10593 100644 --- a/crates/now-package-broker/src/v2/execution/operations.rs +++ b/crates/now-package-broker/src/v2/execution/operations.rs @@ -236,6 +236,9 @@ struct EndOnDrop { 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. let mut state = self.operations.inner.state.lock(); if let Some(record) = state.operations.get_mut(&self.operation_id) && !record.state.status.is_terminal() From 8699a82b5de65b903ef0011365b33200f246b46b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Tue, 1 Dec 2026 06:09:40 +0900 Subject: [PATCH 17/29] fix(agent): escape a process name left out of a 2.0 operation in the log The name comes from the request and may hold control characters, so logging it as it is let a request write a line break and text of its choice into a text log. It is logged escaped, as the executor logs the names it stops. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- crates/now-package-broker/src/v2/execution/operations.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/now-package-broker/src/v2/execution/operations.rs b/crates/now-package-broker/src/v2/execution/operations.rs index f2af10593..a84271b12 100644 --- a/crates/now-package-broker/src/v2/execution/operations.rs +++ b/crates/now-package-broker/src/v2/execution/operations.rs @@ -385,7 +385,8 @@ where warn!( %operation_id, %user_sid, - %process, + // The name is the request's, and may hold line breaks and other control characters. + ?process, "Left a process to stop out of the operation, because its name is not one image name" ); } From 2d15c030b8fa71a301c2bb9f33d3f75dfae395a3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Tue, 1 Dec 2026 07:04:47 +0900 Subject: [PATCH 18/29] test(agent): give each row of a test table its own expected value The rows for the installer arguments of winget now name the option that must be absent, and the rows of the endpoint table name the operation identifier their path holds. Both were computed in the test from another column of the row, so a row could not state anything else and a mistake in that computation would have been part of the expectation. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- .../src/v2/execution/plan.rs | 31 +++++++++++++++---- .../now-package-broker/src/v2/wire/route.rs | 25 ++++++++++----- 2 files changed, 43 insertions(+), 13 deletions(-) diff --git a/crates/now-package-broker/src/v2/execution/plan.rs b/crates/now-package-broker/src/v2/execution/plan.rs index 60ce8e4d6..a11f073be 100644 --- a/crates/now-package-broker/src/v2/execution/plan.rs +++ b/crates/now-package-broker/src/v2/execution/plan.rs @@ -305,11 +305,31 @@ pub(super) mod tests { // 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) in [ - (Operation::Install, InstallerArgumentsMode::Append, "--custom"), - (Operation::Install, InstallerArgumentsMode::Replace, "--override"), - (Operation::Update, InstallerArgumentsMode::Append, "--custom"), - (Operation::Update, InstallerArgumentsMode::Replace, "--override"), + 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; @@ -325,7 +345,6 @@ pub(super) mod tests { "{case}: {command:?}" ); - let other_option = if option == "--custom" { "--override" } else { "--custom" }; assert!( !command.iter().any(|element| element == other_option), "{case}: {command:?}" diff --git a/crates/now-package-broker/src/v2/wire/route.rs b/crates/now-package-broker/src/v2/wire/route.rs index f3e3fff86..4c41891c8 100644 --- a/crates/now-package-broker/src/v2/wire/route.rs +++ b/crates/now-package-broker/src/v2/wire/route.rs @@ -96,8 +96,11 @@ mod tests { 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, @@ -111,6 +114,7 @@ mod tests { body_limit, client, endpoint, + operation_id: None, } } @@ -139,8 +143,14 @@ mod tests { Authenticated, Endpoint::ExecuteBypass, ), - row("GET", "/v2/operations/op-1", 0, Authenticated, Endpoint::Status), - row("POST", "/v2/operations/op-1/cancel", 0, Authenticated, Endpoint::Cancel), + 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", @@ -173,11 +183,12 @@ mod tests { } fn expected(row: &Row) -> Result { - if row.path.contains("op-1") { - named(row.endpoint, "op-1") - } else { - plain(row.endpoint) - } + 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 From 452dea308a5b8147c28f41864c1b2528cacb0583 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Tue, 1 Dec 2026 07:04:47 +0900 Subject: [PATCH 19/29] test(agent): read an execution request from a literal body The body of the execution request was the serialization of the package request the test then expects back, so a member written and read under the same wrong name would have passed. The body is now the literal one the test of the package request reads, with a request id. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- crates/now-package-broker/src/v2/wire/read.rs | 23 +++++++++---------- 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/crates/now-package-broker/src/v2/wire/read.rs b/crates/now-package-broker/src/v2/wire/read.rs index 70641b5bf..5667128b5 100644 --- a/crates/now-package-broker/src/v2/wire/read.rs +++ b/crates/now-package-broker/src/v2/wire/read.rs @@ -967,7 +967,14 @@ mod tests { // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §opt-ins #[test] fn every_member_of_a_package_request_is_read() { - let body = json!({ + 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" }, @@ -975,14 +982,10 @@ mod tests { "Scope": "Machine", "Elevation": "Elevated", "OptIns": opt_ins(), - }); - - let request = read_evaluation_request(&bytes(&body)).expect("package request"); - - assert_eq!(request, full_package_request()); + }) } - /// The package request whose members are those of the body in `every_member_of_a_package_request_is_read`. + /// The package request whose members are those of `full_package_request_body`. fn full_package_request() -> v2::PackageRequest { v2::PackageRequest { operation: v2::Operation::Update, @@ -1108,11 +1111,7 @@ mod tests { // 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( - &serde_json::to_value(full_package_request()).expect("package request"), - "/RequestId", - json!("request-1"), - ); + let body = with(&full_package_request_body(), "/RequestId", json!("request-1")); let request = read_execution_request(&bytes(&body)).expect("execution request"); From e928d5cdab10559bee77cea82af00faf72a08888 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Tue, 1 Dec 2026 07:04:48 +0900 Subject: [PATCH 20/29] test(agent): expect an ended operation gone only once the broker drops it The contract gives the least time an ended operation is held, not the time it is dropped. Two tests that need an operation to be gone expected it gone at that least time, so a broker holding operations longer, as the contract allows, would have failed them. They now pass the time the broker holds an operation, and the 300 seconds stay in the test of the bound. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- crates/now-package-broker/src/v2/execution/operations.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/crates/now-package-broker/src/v2/execution/operations.rs b/crates/now-package-broker/src/v2/execution/operations.rs index a84271b12..df56f9ace 100644 --- a/crates/now-package-broker/src/v2/execution/operations.rs +++ b/crates/now-package-broker/src/v2/execution/operations.rs @@ -1258,8 +1258,9 @@ mod tests { ] ); + // 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 + Duration::from_secs(300)); + 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"), @@ -1313,7 +1314,8 @@ mod tests { .await; let after = Instant::now(); - fixture.operations.evict_expired(after + Duration::from_secs(300)); + // 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); From 9fad4fdf93dbd3be156c656515d13d42527471cb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Tue, 1 Dec 2026 07:04:49 +0900 Subject: [PATCH 21/29] test(agent): tell two owners apart by a letter in paths of one length Every pair of paths expected to give two owners differed in its number of code points, so a comparison that only counted them, or that mapped every code point to the same one, made each pair two owners as well. One pair now has paths of one length that differ by a letter. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- crates/now-package-broker/src/v2/execution/owner.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/now-package-broker/src/v2/execution/owner.rs b/crates/now-package-broker/src/v2/execution/owner.rs index 141051023..7c625d14e 100644 --- a/crates/now-package-broker/src/v2/execution/owner.rs +++ b/crates/now-package-broker/src/v2/execution/owner.rs @@ -108,8 +108,11 @@ pub(super) mod tests { #[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"), ] { From ee58b28af62c3adf09135aa440bf80bad25f5dfe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Tue, 1 Dec 2026 07:04:49 +0900 Subject: [PATCH 22/29] test(agent): cite the source that decides each expected value Some tests of the 2.0 requests named a source that does not decide what they expect, or named only part of it: - an operation with `PrePostCommands` and an elevated token ending `Failed` without a step is a rule of the operations, not only of `NotRunnable`; - the reading of keys and escapes of a request body rests on the wire contract and RFC 8259, where only the policy contract was cited; - a plan for a version with a pre-release under a manager with no pre-release option follows from the cases in which no command is built, and was marked as a guard against a fault; - no pre-release switch for a version without a pre-release is such a guard, since the contract only says which versions have none, and that is cited where the versions are listed. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- crates/now-package-broker/src/v2/execution/operations.rs | 2 ++ crates/now-package-broker/src/v2/execution/plan.rs | 6 ++++-- crates/now-package-broker/src/v2/wire/read.rs | 8 ++++++++ 3 files changed, 14 insertions(+), 2 deletions(-) diff --git a/crates/now-package-broker/src/v2/execution/operations.rs b/crates/now-package-broker/src/v2/execution/operations.rs index df56f9ace..3583f36d6 100644 --- a/crates/now-package-broker/src/v2/execution/operations.rs +++ b/crates/now-package-broker/src/v2/execution/operations.rs @@ -1096,7 +1096,9 @@ mod tests { } // 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}; diff --git a/crates/now-package-broker/src/v2/execution/plan.rs b/crates/now-package-broker/src/v2/execution/plan.rs index a11f073be..fad61ec67 100644 --- a/crates/now-package-broker/src/v2/execution/plan.rs +++ b/crates/now-package-broker/src/v2/execution/plan.rs @@ -628,7 +628,7 @@ pub(super) mod tests { } } - // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.policy.md §version-scheme + // 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 [ @@ -636,6 +636,7 @@ pub(super) mod tests { (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)); @@ -680,7 +681,8 @@ pub(super) mod tests { } } - // oracle: mutant asking for pre-releases under every manager, whose builders refuse a request that asks for them + // No case in which "the broker builds no Npm command" is a version that has a pre-release. + // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.policy.md §manager-npm #[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(); diff --git a/crates/now-package-broker/src/v2/wire/read.rs b/crates/now-package-broker/src/v2/wire/read.rs index 5667128b5..15bcf3f59 100644 --- a/crates/now-package-broker/src/v2/wire/read.rs +++ b/crates/now-package-broker/src/v2/wire/read.rs @@ -751,6 +751,7 @@ mod tests { } // 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!( @@ -820,8 +821,10 @@ mod tests { ); } + // 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!( @@ -832,6 +835,8 @@ mod tests { ); } + // 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() { @@ -843,6 +848,8 @@ mod tests { ); } + // 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() { @@ -952,6 +959,7 @@ mod tests { 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() { From ef12c02a389fd011e0bf8bc56d99a3475a5b2552 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Tue, 1 Dec 2026 12:32:16 +0900 Subject: [PATCH 23/29] fix(agent): escape in the log the reason a 2.0 operation failed The reason comes from the plan or the executor, whose errors quote members of the request, so a control character in one of them reached the log as it was. The reason is now logged escaped, like the process names left out of an operation. Issue: DGW-499 Changelog: ignore Co-Authored-By: Claude Fable 5.2 --- crates/now-package-broker/src/v2/execution/operations.rs | 9 ++++++--- crates/now-package-broker/src/v2/execution/plan.rs | 4 +++- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/crates/now-package-broker/src/v2/execution/operations.rs b/crates/now-package-broker/src/v2/execution/operations.rs index 3583f36d6..52dd9764f 100644 --- a/crates/now-package-broker/src/v2/execution/operations.rs +++ b/crates/now-package-broker/src/v2/execution/operations.rs @@ -385,14 +385,17 @@ where warn!( %operation_id, %user_sid, - // The name is the request's, and may hold line breaks and other control characters. + // 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 its name is not one image name" ); } match &failure { Some(reason) => { - warn!(%operation_id, %user_sid, error = %reason, "Operation failed before its first step"); + // 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, @@ -454,7 +457,7 @@ where } Err(error) => { let reason = format!("{error:#}"); - warn!(%operation_id, error = %reason, "Operation failed"); + warn!(%operation_id, error = ?reason, "Operation failed"); (Status::Failed, None, Some(reason)) } }; diff --git a/crates/now-package-broker/src/v2/execution/plan.rs b/crates/now-package-broker/src/v2/execution/plan.rs index fad61ec67..a828ac193 100644 --- a/crates/now-package-broker/src/v2/execution/plan.rs +++ b/crates/now-package-broker/src/v2/execution/plan.rs @@ -681,8 +681,10 @@ pub(super) mod tests { } } - // No case in which "the broker builds no Npm command" is a version that has a pre-release. + // 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(); From 6c948aa07322829cc976e7a93d8d76f9b2c0ba2d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Wed, 2 Dec 2026 04:04:24 +0900 Subject: [PATCH 24/29] fix(agent): refuse a 2.0 update over its source record only when it names a source The contract has an Update end Failed for an unread record of its source only when the Update has a source. An Update without one names no source that a record could differ from, so the plan no longer refuses it for that reason. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- .../now-package-broker/src/v2/execution/plan.rs | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/crates/now-package-broker/src/v2/execution/plan.rs b/crates/now-package-broker/src/v2/execution/plan.rs index 1be967a28..c8bc4f3c4 100644 --- a/crates/now-package-broker/src/v2/execution/plan.rs +++ b/crates/now-package-broker/src/v2/execution/plan.rs @@ -59,7 +59,11 @@ pub(super) fn plan(request: &Request) -> anyhow::Result { // 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`. - if request.operation == Operation::Update && updates_from_recorded_source(request.manager) { + // 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() @@ -520,6 +524,16 @@ pub(super) mod tests { } } + // 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() { + let [_, mut windows_powershell] = updates_from_a_recorded_source(); + windows_powershell.source = None; + + plan(&windows_powershell).expect("Windows PowerShell"); + } + // 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() { From 63ef2e00b8f5eebdfd415d597f96e78d13e8553d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Wed, 2 Dec 2026 04:21:31 +0900 Subject: [PATCH 25/29] feat(agent): build the command of a 2.0 request that names no source A request without a source leaves the choice of source to its manager. The builders read a 1.x request, where an empty source name builds no install, so the plan now tells them that the request has no source instead of handing them an empty name. Such a request gets the command of the only source name of its manager where the manager has one, and otherwise a command that passes no source: no `--source` for WinGet and Chocolatey, no `-Repository` for PowerShell. A request that names its source builds the command it built before. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- .../src/command_builder/bun.rs | 22 +- .../src/command_builder/cargo.rs | 22 +- .../src/command_builder/chocolatey.rs | 35 ++- .../src/command_builder/dotnet.rs | 30 ++- .../src/command_builder/mod.rs | 54 +++-- .../src/command_builder/npm.rs | 24 +- .../src/command_builder/pip.rs | 22 +- .../src/command_builder/powershell.rs | 79 +++--- .../src/command_builder/scoop.rs | 34 ++- .../src/command_builder/vcpkg.rs | 35 ++- .../src/command_builder/winget.rs | 11 +- .../src/v2/execution/plan.rs | 225 +++++++++++++++++- 12 files changed, 471 insertions(+), 122 deletions(-) diff --git a/crates/now-package-broker/src/command_builder/bun.rs b/crates/now-package-broker/src/command_builder/bun.rs index a8cc059b9..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,12 +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> { - build_bun_command_as(request, crate::evaluator::effective_execution_elevation(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`. -pub(crate) fn build_bun_command_as(request: &PackageRequest, elevation: Elevation) -> anyhow::Result> { - validate_bun_request(request, elevation)?; +/// 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", @@ -49,7 +57,7 @@ pub(crate) fn build_bun_command_as(request: &PackageRequest, elevation: Elevatio ]) } -fn validate_bun_request(request: &PackageRequest, elevation: Elevation) -> 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"); } @@ -58,7 +66,7 @@ fn validate_bun_request(request: &PackageRequest, elevation: Elevation) -> anyho 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 72555d665..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,12 +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> { - build_cargo_command_as(request, crate::evaluator::effective_execution_elevation(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`. -pub(crate) fn build_cargo_command_as(request: &PackageRequest, elevation: Elevation) -> anyhow::Result> { - validate_cargo_request(request, elevation)?; +/// 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", @@ -65,14 +73,14 @@ pub(crate) fn build_cargo_command_as(request: &PackageRequest, elevation: Elevat Ok(command) } -fn validate_cargo_request(request: &PackageRequest, elevation: Elevation) -> 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 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 eb0e1eb60..09ee45039 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, &[])?; } @@ -163,22 +172,22 @@ fn validate_chocolatey_package_id(id: &str) -> anyhow::Result<()> { const CHOCOLATEY_SOURCE_TYPES: [&str; 5] = ["cygwin", "python", "ruby", "windowsfeature", "windowsfeatures"]; /// 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)?; + validate_source_name("Chocolatey", name)?; if CHOCOLATEY_SOURCE_TYPES .iter() - .any(|source_type| source_type.eq_ignore_ascii_case(source)) + .any(|source_type| source_type.eq_ignore_ascii_case(name)) { - bail!("Chocolatey package source name '{source}' selects a Chocolatey source type, not a configured source"); + 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 b56808380..5eccf4459 100644 --- a/crates/now-package-broker/src/command_builder/mod.rs +++ b/crates/now-package-broker/src/command_builder/mod.rs @@ -54,24 +54,25 @@ 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. +/// arguments; this serves a request that states its run elevation itself, and may have no source. 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, elevation), - ManagerName::Cargo => cargo::build_cargo_command_as(request, elevation), - ManagerName::Dotnet => dotnet::build_dotnet_command(request), - ManagerName::Npm => npm::build_npm_command_as(request, elevation), - ManagerName::Winget => winget::build_winget_command_with(request, installer_arguments), - ManagerName::PowerShell => powershell::build_powershell5_command_as(request, elevation), - ManagerName::PowerShell7 => powershell::build_powershell7_command_as(request, elevation), - ManagerName::Chocolatey => chocolatey::build_chocolatey_command(request), - ManagerName::Pip => pip::build_pip_command_as(request, elevation), - ManagerName::Scoop => scoop::build_scoop_command_as(request, elevation), - ManagerName::Vcpkg => vcpkg::build_vcpkg_command_as(request, elevation), + 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}"), } } @@ -151,11 +152,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 e8ff15c19..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,12 +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> { - build_npm_command_as(request, crate::evaluator::effective_execution_elevation(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`. -pub(crate) fn build_npm_command_as(request: &PackageRequest, elevation: Elevation) -> anyhow::Result> { - validate_npm_request(request, elevation)?; +/// 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); @@ -60,7 +70,7 @@ pub(crate) fn build_npm_command_as(request: &PackageRequest, elevation: Elevatio ]) } -fn validate_npm_request(request: &PackageRequest, elevation: Elevation) -> 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"); } @@ -70,7 +80,7 @@ fn validate_npm_request(request: &PackageRequest, elevation: Elevation) -> anyho 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 cbac7d00f..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,12 +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> { - build_pip_command_as(request, crate::evaluator::effective_execution_elevation(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`. -pub(crate) fn build_pip_command_as(request: &PackageRequest, elevation: Elevation) -> anyhow::Result> { - validate_pip_request(request, elevation)?; +/// 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(), @@ -61,7 +69,7 @@ pub(crate) fn build_pip_command_as(request: &PackageRequest, elevation: Elevatio Ok(command) } -fn validate_pip_request(request: &PackageRequest, elevation: Elevation) -> 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"); } @@ -71,7 +79,7 @@ fn validate_pip_request(request: &PackageRequest, elevation: Elevation) -> anyho 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 6878b6c35..999e74f77 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,15 +47,21 @@ 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_command_as(request, crate::evaluator::effective_execution_elevation(request)) + build_powershell5_command_as( + request, + SourceChoice::Request, + crate::evaluator::effective_execution_elevation(request), + ) } -/// Build the Windows PowerShell command of a run whose token has the elevation `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, false, elevation)?; + validate_powershell_request(request, source, false, elevation)?; let mut script = SCRIPT_PREFIX.to_owned(); @@ -64,7 +73,12 @@ pub(crate) fn build_powershell5_command_as( &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 { @@ -75,8 +89,11 @@ pub(crate) fn build_powershell5_command_as( 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"); @@ -110,15 +127,21 @@ pub(crate) fn build_powershell5_command_as( /// Build a PowerShell 7.x (PSResourceGet) command from a validated request. pub fn build_powershell7_command(request: &PackageRequest) -> anyhow::Result> { - build_powershell7_command_as(request, crate::evaluator::effective_execution_elevation(request)) + build_powershell7_command_as( + request, + SourceChoice::Request, + crate::evaluator::effective_execution_elevation(request), + ) } -/// Build the PowerShell 7 command of a run whose token has the elevation `elevation`. +/// Build the PowerShell 7 command of a run whose token has the elevation `elevation`, on the source that `source` +/// chooses. pub(crate) fn build_powershell7_command_as( request: &PackageRequest, + source: SourceChoice, elevation: Elevation, ) -> anyhow::Result> { - build_powershell7(request, false, elevation) + build_powershell7(request, source, false, elevation) } /// Build a PowerShell 7.x command for a remote grant. @@ -127,15 +150,23 @@ pub(crate) fn build_powershell7_command_as( /// passes an authorized installed scope to uninstall. /// The caller must enforce the grant's target-user token and requested elevation. pub(super) fn build_powershell7_remote_grant_command(request: &PackageRequest) -> anyhow::Result> { - build_powershell7(request, true, crate::evaluator::effective_execution_elevation(request)) + build_powershell7( + request, + SourceChoice::Request, + true, + crate::evaluator::effective_execution_elevation(request), + ) } fn build_powershell7( request: &PackageRequest, + source: SourceChoice, remote_grant: bool, elevation: Elevation, ) -> anyhow::Result> { - validate_powershell_request(request, remote_grant, elevation)?; + // 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(); @@ -144,7 +175,7 @@ fn build_powershell7( "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 { @@ -156,7 +187,7 @@ fn build_powershell7( 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); } @@ -207,13 +238,14 @@ fn build_powershell7( 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 @@ -272,9 +304,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(); @@ -284,14 +316,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. @@ -305,8 +329,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 cec16e5c9..76ae82132 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,12 +15,20 @@ 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_command_as(request, crate::evaluator::effective_execution_elevation(request)) + build_scoop_command_as( + request, + SourceChoice::Request, + crate::evaluator::effective_execution_elevation(request), + ) } -/// Build the command of a run whose token has the elevation `elevation`. -pub(crate) fn build_scoop_command_as(request: &PackageRequest, elevation: Elevation) -> anyhow::Result> { - validate_scoop_request(request, elevation)?; +/// 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> { + validate_scoop_request(request, source, elevation)?; let operation = match request.operation { Operation::Install => "install", @@ -28,7 +36,7 @@ pub(crate) fn build_scoop_command_as(request: &PackageRequest, elevation: Elevat Operation::Uninstall => "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()); @@ -80,7 +88,7 @@ pub(crate) fn build_scoop_command_as(request: &PackageRequest, elevation: Elevat ]) } -fn validate_scoop_request(request: &PackageRequest, elevation: Elevation) -> anyhow::Result<()> { +fn validate_scoop_request(request: &PackageRequest, source: SourceChoice, elevation: Elevation) -> anyhow::Result<()> { // UNTESTED: refusing every 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). @@ -99,7 +107,7 @@ fn validate_scoop_request(request: &PackageRequest, elevation: Elevation) -> any "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() { @@ -140,8 +148,12 @@ fn validate_scoop_request(request: &PackageRequest, elevation: Elevation) -> any 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)?; @@ -163,7 +175,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)?; } diff --git a/crates/now-package-broker/src/command_builder/vcpkg.rs b/crates/now-package-broker/src/command_builder/vcpkg.rs index 0bb37aa07..35a732fc6 100644 --- a/crates/now-package-broker/src/command_builder/vcpkg.rs +++ b/crates/now-package-broker/src/command_builder/vcpkg.rs @@ -12,16 +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> { - build_vcpkg_command_as(request, crate::evaluator::effective_execution_elevation(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`. -pub(crate) fn build_vcpkg_command_as(request: &PackageRequest, elevation: Elevation) -> anyhow::Result> { - validate_vcpkg_request(request, elevation)?; +/// 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", @@ -29,7 +37,11 @@ pub(crate) fn build_vcpkg_command_as(request: &PackageRequest, elevation: Elevat Operation::Uninstall => "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 => {} @@ -40,7 +52,7 @@ pub(crate) fn build_vcpkg_command_as(request: &PackageRequest, elevation: Elevat Ok(command) } -fn validate_vcpkg_request(request: &PackageRequest, elevation: Elevation) -> 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"); } @@ -50,7 +62,7 @@ fn validate_vcpkg_request(request: &PackageRequest, elevation: Elevation) -> any 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() { @@ -87,8 +99,11 @@ fn validate_vcpkg_request(request: &PackageRequest, elevation: Elevation) -> any 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() { diff --git a/crates/now-package-broker/src/command_builder/winget.rs b/crates/now-package-broker/src/command_builder/winget.rs index 671107cd8..f2146017b 100644 --- a/crates/now-package-broker/src/command_builder/winget.rs +++ b/crates/now-package-broker/src/command_builder/winget.rs @@ -4,15 +4,15 @@ 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> { - build_winget_command_with(request, None) + build_winget_command_with(request, SourceChoice::Request, None) } /// Arguments WinGet hands to the installer it runs. @@ -24,12 +24,13 @@ pub(crate) enum InstallerArguments<'a> { Replace(&'a str), } -/// Build the WinGet command line of a request that may carry installer arguments. +/// Build the WinGet command line of a request that may carry installer arguments, on the source that `source` chooses. pub(crate) fn build_winget_command_with( request: &PackageRequest, + source: SourceChoice, installer_arguments: Option>, ) -> anyhow::Result> { - let source = if uses_default_source("WinGet", request)? { + let source = if uses_default_source("WinGet", request, source)? { None } else { validate_source_name("WinGet", &request.source.name)?; diff --git a/crates/now-package-broker/src/v2/execution/plan.rs b/crates/now-package-broker/src/v2/execution/plan.rs index c8bc4f3c4..0b6c76d08 100644 --- a/crates/now-package-broker/src/v2/execution/plan.rs +++ b/crates/now-package-broker/src/v2/execution/plan.rs @@ -1,7 +1,8 @@ //! 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 and the WinGet installer arguments, which a 1.x request does not state, are passed beside it. +//! 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; @@ -10,8 +11,8 @@ use chrono::Utc; use now_policy_api as v1; use now_policy_eval::{Architecture, Elevation, InstallerArgumentsMode, Manager, Operation, Request, Scope}; -use crate::command_builder::build_command_as; use crate::command_builder::winget::InstallerArguments; +use crate::command_builder::{SourceChoice, build_command_as}; /// The steps of an operation ([§operations]) and the token they run with. /// @@ -82,7 +83,22 @@ pub(super) fn plan(request: &Request) -> anyhow::Result { InstallerArgumentsMode::Append => InstallerArguments::Append(&arguments.arguments), InstallerArgumentsMode::Replace => InstallerArguments::Replace(&arguments.arguments), }); - let command = build_command_as(&builder_request, elevation, installer_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 some of these requests, and a Windows PowerShell or .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)?; // The executor refuses a whole plan for one name it cannot hand to `taskkill /IM` as one literal image name. // Nothing is attempted for such a name: it is left out of the plan, so the other steps still run, as they do @@ -194,7 +210,7 @@ fn builder_request(request: &Request, elevation: v1::Elevation) -> v1::PackageRe Manager::Vcpkg => v1::ManagerName::Vcpkg, }, source: v1::RequestSource { - // The builders read an empty name as a request that leaves the choice of source to its manager. + // The builders do not read the name of a request without a source. name: request .source .as_ref() @@ -714,4 +730,205 @@ pub(super) mod tests { 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: contract Devolutions/now-libraries@3014fcbb899d:policies/CONTRACT.wire.md §bypass-reading + #[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() + ); + } + } + } + + // 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:?}"); + } + } } From acd0045f0cb93dfdd25f2bfbd9fb725bf2f9e438 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Wed, 2 Dec 2026 04:42:16 +0900 Subject: [PATCH 26/29] feat(agent): build the Scoop command of a 2.0 request that names no source Without a source the request names no bucket, so the command passes the package id alone and Scoop looks it up in its buckets. An update is built too: the builder refuses the update of a request that names a bucket because Scoop updates from the bucket recorded at install, and a request without a source names no bucket for that record to differ from. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- .../src/command_builder/scoop.rs | 43 +++++++++++++++++-- .../src/v2/execution/plan.rs | 30 +++++++++++-- 2 files changed, 66 insertions(+), 7 deletions(-) diff --git a/crates/now-package-broker/src/command_builder/scoop.rs b/crates/now-package-broker/src/command_builder/scoop.rs index 76ae82132..84a33040a 100644 --- a/crates/now-package-broker/src/command_builder/scoop.rs +++ b/crates/now-package-broker/src/command_builder/scoop.rs @@ -89,12 +89,13 @@ pub(crate) fn build_scoop_command_as( } fn validate_scoop_request(request: &PackageRequest, source: SourceChoice, elevation: Elevation) -> anyhow::Result<()> { - // UNTESTED: refusing every 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). + // UNTESTED: refusing every 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 { + // 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 { 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" ); @@ -424,6 +425,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 Devolutions/now-libraries@469ce8575463:policies/CONTRACT.policy.md §manager-scoop #[test] fn manifest_install_must_name_one_unambiguous_https_url() { diff --git a/crates/now-package-broker/src/v2/execution/plan.rs b/crates/now-package-broker/src/v2/execution/plan.rs index 0b6c76d08..06f3f2458 100644 --- a/crates/now-package-broker/src/v2/execution/plan.rs +++ b/crates/now-package-broker/src/v2/execution/plan.rs @@ -544,10 +544,11 @@ pub(super) mod tests { // oracle: contract Devolutions/now-libraries@3014fcbb899d:policies/CONTRACT.wire.md §operations #[test] fn an_update_without_a_source_waits_for_no_record() { - let [_, mut windows_powershell] = updates_from_a_recorded_source(); - windows_powershell.source = None; + for mut request in updates_from_a_recorded_source() { + request.source = None; - plan(&windows_powershell).expect("Windows PowerShell"); + plan(&request).unwrap_or_else(|error| panic!("{}: {error:#}", request.manager.as_str())); + } } // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.policy.md §manager-powershell @@ -931,4 +932,27 @@ pub(super) mod tests { assert!(!words.iter().any(|word| word == "-Repository"), "{case}: {words:?}"); } } + + // 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() + ); + } + } } From ae3da3d95f2ddcdcce4e01cd31c60ae9ac0002b0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Wed, 2 Dec 2026 04:47:51 +0900 Subject: [PATCH 27/29] feat(agent): build the Vcpkg command of a 2.0 request that names no source Without a source the request names no triplet, so the command passes the package id as it is: Vcpkg acts on the triplet the id carries, or on its default triplet when the id carries none. A request that names its source with an empty name still needs a triplet in its package id. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- .../src/command_builder/vcpkg.rs | 40 ++++++++++++++++++- .../src/v2/execution/plan.rs | 26 ++++++++++++ 2 files changed, 64 insertions(+), 2 deletions(-) diff --git a/crates/now-package-broker/src/command_builder/vcpkg.rs b/crates/now-package-broker/src/command_builder/vcpkg.rs index 35a732fc6..ac8f7b972 100644 --- a/crates/now-package-broker/src/command_builder/vcpkg.rs +++ b/crates/now-package-broker/src/command_builder/vcpkg.rs @@ -123,8 +123,14 @@ fn package_spec(request: &PackageRequest, source: SourceChoice) -> anyhow::Resul } 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}")) } @@ -262,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/v2/execution/plan.rs b/crates/now-package-broker/src/v2/execution/plan.rs index 06f3f2458..717aa7786 100644 --- a/crates/now-package-broker/src/v2/execution/plan.rs +++ b/crates/now-package-broker/src/v2/execution/plan.rs @@ -955,4 +955,30 @@ pub(super) mod tests { ); } } + + // 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() + ); + } + } + } } From 9d2d757f1a30b0e28b7f40ca80a1d3370a6b5825 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Wed, 2 Dec 2026 05:47:01 +0900 Subject: [PATCH 28/29] test(agent): mark the refusal of an elevated plan without a source for what decides it The builders decide which managers get no elevated command, so the test guards their refusal against a change that would lift it for a request that names no source. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- crates/now-package-broker/src/v2/execution/plan.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/now-package-broker/src/v2/execution/plan.rs b/crates/now-package-broker/src/v2/execution/plan.rs index 717aa7786..f7165873a 100644 --- a/crates/now-package-broker/src/v2/execution/plan.rs +++ b/crates/now-package-broker/src/v2/execution/plan.rs @@ -880,7 +880,7 @@ pub(super) mod tests { } } - // oracle: contract Devolutions/now-libraries@3014fcbb899d:policies/CONTRACT.wire.md §bypass-reading + // 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 [ From 0c1e8a885c220b762f72b0d9802360ef1aaab672 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Wed, 2 Dec 2026 05:47:02 +0900 Subject: [PATCH 29/29] docs(agent): name the leap second among the instants no 2.0 timestamp is written for Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- crates/now-package-broker/src/v2/wire/convert.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/now-package-broker/src/v2/wire/convert.rs b/crates/now-package-broker/src/v2/wire/convert.rs index c09cdaf5c..4a52c1963 100644 --- a/crates/now-package-broker/src/v2/wire/convert.rs +++ b/crates/now-package-broker/src/v2/wire/convert.rs @@ -158,7 +158,8 @@ pub fn policy_error(error: &eval::ValidationError) -> v2::PolicyError { /// 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, which no timestamp names ([§timestamps]). +/// 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