From 17567c6a2c2fc9441d8844c519d319ebb626a3c6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Tue, 1 Dec 2026 04:05:30 +0900 Subject: [PATCH 01/16] build(agent): depend on the 2.x policy evaluator The package broker reads 2.x policies and evaluates requests with `now-policy-eval`. The crate is not published yet, so the dependency is pinned to a git revision until it is. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- Cargo.lock | 6 ++++++ crates/now-package-broker/Cargo.toml | 3 +++ crates/now-package-broker/src/lib.rs | 2 ++ crates/now-package-broker/src/v2/mod.rs | 7 +++++++ crates/now-package-broker/src/v2/policy.rs | 1 + crates/now-package-broker/src/v2/wire/mod.rs | 1 + 6 files changed, 20 insertions(+) create mode 100644 crates/now-package-broker/src/v2/mod.rs create mode 100644 crates/now-package-broker/src/v2/policy.rs create mode 100644 crates/now-package-broker/src/v2/wire/mod.rs diff --git a/Cargo.lock b/Cargo.lock index e00186e11..1dee1d2b1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5209,6 +5209,7 @@ dependencies = [ "notify 7.0.0", "now-policy", "now-policy-api", + "now-policy-eval", "now-policy-server-template", "parking_lot", "regex", @@ -5262,6 +5263,11 @@ dependencies = [ "thiserror 2.0.20", ] +[[package]] +name = "now-policy-eval" +version = "0.0.0" +source = "git+https://github.com/Devolutions/now-libraries?rev=bd8760e4664835d3b420aa481ed00c753848a115#bd8760e4664835d3b420aa481ed00c753848a115" + [[package]] name = "now-policy-server-template" version = "0.7.1" diff --git a/crates/now-package-broker/Cargo.toml b/crates/now-package-broker/Cargo.toml index 50041123a..724ca02d5 100644 --- a/crates/now-package-broker/Cargo.toml +++ b/crates/now-package-broker/Cargo.toml @@ -28,6 +28,9 @@ http-body-util = "0.1" mime = "0.3" now-policy = "0.5" now-policy-api = "0.7.1" +# TEMPORARY: `now-policy-eval` is not published yet. +# This git dependency must become a crates.io version before this change merges. +now-policy-eval = { git = "https://github.com/Devolutions/now-libraries", rev = "bd8760e4664835d3b420aa481ed00c753848a115" } now-policy-server-template = "0.7.1" parking_lot = "0.12" regex = "1" diff --git a/crates/now-package-broker/src/lib.rs b/crates/now-package-broker/src/lib.rs index f8db50786..5f1b61ea4 100644 --- a/crates/now-package-broker/src/lib.rs +++ b/crates/now-package-broker/src/lib.rs @@ -39,6 +39,8 @@ pub mod remote_grant; pub mod server; #[cfg(windows)] pub mod task; +#[cfg(windows)] +pub mod v2; #[cfg(all(test, windows))] mod scenario_tests; diff --git a/crates/now-package-broker/src/v2/mod.rs b/crates/now-package-broker/src/v2/mod.rs new file mode 100644 index 000000000..e9f373d28 --- /dev/null +++ b/crates/now-package-broker/src/v2/mod.rs @@ -0,0 +1,7 @@ +//! The 2.0 request encoding and the 2.x policy format. +//! +//! Everything the `/v2/` endpoints need lives here, apart from the policy store, the executor and the command builders, +//! which the 1.x routes share until they are removed. + +pub mod policy; +pub mod wire; diff --git a/crates/now-package-broker/src/v2/policy.rs b/crates/now-package-broker/src/v2/policy.rs new file mode 100644 index 000000000..4af098657 --- /dev/null +++ b/crates/now-package-broker/src/v2/policy.rs @@ -0,0 +1 @@ +//! Accepted 2.x policies and their evaluation. diff --git a/crates/now-package-broker/src/v2/wire/mod.rs b/crates/now-package-broker/src/v2/wire/mod.rs new file mode 100644 index 000000000..048598d95 --- /dev/null +++ b/crates/now-package-broker/src/v2/wire/mod.rs @@ -0,0 +1 @@ +//! Requests and responses of the 2.0 encoding. From ee357d0cecbda78697c7631c2ccd13bd37a0d899 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Tue, 1 Dec 2026 04:06:12 +0900 Subject: [PATCH 02/16] refactor(agent): add the module for the 2.0 request encoding Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- crates/now-package-broker/src/v2/execution.rs | 1 + crates/now-package-broker/src/v2/mod.rs | 1 + 2 files changed, 2 insertions(+) create mode 100644 crates/now-package-broker/src/v2/execution.rs diff --git a/crates/now-package-broker/src/v2/execution.rs b/crates/now-package-broker/src/v2/execution.rs new file mode 100644 index 000000000..8a5350750 --- /dev/null +++ b/crates/now-package-broker/src/v2/execution.rs @@ -0,0 +1 @@ +//! Operations started by a 2.0 request. diff --git a/crates/now-package-broker/src/v2/mod.rs b/crates/now-package-broker/src/v2/mod.rs index e9f373d28..b75f79586 100644 --- a/crates/now-package-broker/src/v2/mod.rs +++ b/crates/now-package-broker/src/v2/mod.rs @@ -3,5 +3,6 @@ //! Everything the `/v2/` endpoints need lives here, apart from the policy store, the executor and the command builders, //! which the 1.x routes share until they are removed. +pub mod execution; pub mod policy; pub mod wire; From ee900c2f37ee426b696ecab1628679390e45c7b5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Tue, 1 Dec 2026 04:16:31 +0900 Subject: [PATCH 03/16] build(agent): take the 2.0 package broker API types The 2.0 request and response types live in `now_policy_api::v2`, which no published version carries yet. The now-policy crates are patched to one git revision until they are published, so the Agent and the package broker keep sharing one copy of the 1.x types. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- Cargo.lock | 11 ++++------- Cargo.toml | 5 +++++ crates/now-package-broker/Cargo.toml | 2 +- 3 files changed, 10 insertions(+), 8 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 1dee1d2b1..11f819110 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5234,8 +5234,7 @@ dependencies = [ [[package]] name = "now-policy" version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "14bf619b405ffb47839ee24baebe1866009d1aea49b112afe0da1465fda7e700" +source = "git+https://github.com/Devolutions/now-libraries?rev=77307f5106d9764d03a420d22fd8377c99432af5#77307f5106d9764d03a420d22fd8377c99432af5" dependencies = [ "chrono", "schemars 0.9.0", @@ -5249,8 +5248,7 @@ dependencies = [ [[package]] name = "now-policy-api" version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d72b70c897187df0bb789335d51b709113eb9f0784e0f69f05fc501d8919b05" +source = "git+https://github.com/Devolutions/now-libraries?rev=77307f5106d9764d03a420d22fd8377c99432af5#77307f5106d9764d03a420d22fd8377c99432af5" dependencies = [ "chrono", "derive_more", @@ -5266,13 +5264,12 @@ dependencies = [ [[package]] name = "now-policy-eval" version = "0.0.0" -source = "git+https://github.com/Devolutions/now-libraries?rev=bd8760e4664835d3b420aa481ed00c753848a115#bd8760e4664835d3b420aa481ed00c753848a115" +source = "git+https://github.com/Devolutions/now-libraries?rev=77307f5106d9764d03a420d22fd8377c99432af5#77307f5106d9764d03a420d22fd8377c99432af5" [[package]] name = "now-policy-server-template" version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4cb17df500bcc9d9a5909eee68e5bfd66c6b15dae56ca7b1473f2c6d6fd537a9" +source = "git+https://github.com/Devolutions/now-libraries?rev=77307f5106d9764d03a420d22fd8377c99432af5#77307f5106d9764d03a420d22fd8377c99432af5" dependencies = [ "aide 0.15.1", "async-trait", diff --git a/Cargo.toml b/Cargo.toml index f4a377a7e..15ba797a6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -33,6 +33,11 @@ lto = true [patch.crates-io] tracing-appender = { git = "https://github.com/CBenoit/tracing.git", rev = "42097daf92e683cf18da7639ddccb056721a796c" } +# TEMPORARY: the 2.0 package broker API types are not published yet. +# These three patches must go, and the crates.io versions that carry the types must be required instead, before this change merges. +now-policy = { git = "https://github.com/Devolutions/now-libraries", rev = "77307f5106d9764d03a420d22fd8377c99432af5" } +now-policy-api = { git = "https://github.com/Devolutions/now-libraries", rev = "77307f5106d9764d03a420d22fd8377c99432af5" } +now-policy-server-template = { git = "https://github.com/Devolutions/now-libraries", rev = "77307f5106d9764d03a420d22fd8377c99432af5" } [workspace.lints.rust] # Declare the custom cfgs. diff --git a/crates/now-package-broker/Cargo.toml b/crates/now-package-broker/Cargo.toml index 724ca02d5..5af0c2098 100644 --- a/crates/now-package-broker/Cargo.toml +++ b/crates/now-package-broker/Cargo.toml @@ -30,7 +30,7 @@ now-policy = "0.5" now-policy-api = "0.7.1" # TEMPORARY: `now-policy-eval` is not published yet. # This git dependency must become a crates.io version before this change merges. -now-policy-eval = { git = "https://github.com/Devolutions/now-libraries", rev = "bd8760e4664835d3b420aa481ed00c753848a115" } +now-policy-eval = { git = "https://github.com/Devolutions/now-libraries", rev = "77307f5106d9764d03a420d22fd8377c99432af5" } now-policy-server-template = "0.7.1" parking_lot = "0.12" regex = "1" From 31c24f0e0452e6819b9acfafc7a5754676bc4d23 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Tue, 1 Dec 2026 04:23:23 +0900 Subject: [PATCH 04/16] feat(agent): read and evaluate 2.x policies for the 2.0 endpoints An accepted policy keeps the text it was read from next to the parsed document, because the management state reports that text and a replacement compares identities without reading the file again. `Metadata.Id` and `Metadata.Revision` are read from the valid document, since the evaluator does not expose them. The evaluation time goes through the timestamp the broker writes in its responses, because the evaluator reads its time from text only. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- crates/now-package-broker/src/v2/policy.rs | 448 +++++++++++++++++++++ 1 file changed, 448 insertions(+) diff --git a/crates/now-package-broker/src/v2/policy.rs b/crates/now-package-broker/src/v2/policy.rs index 4af098657..288a17541 100644 --- a/crates/now-package-broker/src/v2/policy.rs +++ b/crates/now-package-broker/src/v2/policy.rs @@ -1 +1,449 @@ //! Accepted 2.x policies and their evaluation. + +use core::fmt; + +use chrono::{DateTime, Utc}; +use now_policy_api::v2::{PolicyError, PolicyErrorCode, PolicyIdentity, Revision, Timestamp}; +use now_policy_eval::{Decision, Elevation, Outcome, Policy, Request}; + +/// The UTF-8 byte order mark, one of which a reader ignores at the start of a document. +const BYTE_ORDER_MARK: char = '\u{FEFF}'; + +/// A valid 2.x policy document, as the broker holds it once it accepted it. +/// +/// The policy keeps the text it was read from, so the broker can evaluate requests against the document and report its identity without reading it again. +#[derive(Debug, Clone)] +pub struct AcceptedPolicy { + document: String, + policy: Policy, + id: String, + revision: Revision, +} + +impl AcceptedPolicy { + /// Reads a policy document from its bytes, which are those of a policy file or the UTF-8 encoding of a submitted document. + /// + /// The errors are those the policy contract has a reader report for the document, and there is at least one. + pub fn from_bytes(bytes: &[u8]) -> Result> { + let policy = now_policy_eval::parse_policy(bytes) + .map_err(|errors| errors.into_iter().map(policy_error).collect::>())?; + + // A valid document is UTF-8 and carries its identity, so neither step fails after the reader accepted the bytes. + // Reporting the whole document as malformed keeps an unexpected disagreement between the two readers from + // being held as an accepted policy without an identity. + let unreadable = || { + vec![PolicyError { + code: PolicyErrorCode::MalformedDocument, + pointer: String::new(), + }] + }; + let document = core::str::from_utf8(bytes).map_err(|_| unreadable())?; + let (id, revision) = read_identity(document).ok_or_else(unreadable)?; + + Ok(Self { + document: document.to_owned(), + policy, + id, + revision, + }) + } + + /// Returns the text the policy was read from, with a leading byte order mark as a leading U+FEFF. + pub fn document(&self) -> &str { + &self.document + } + + /// Returns the policy's `Metadata.Id`. + pub fn id(&self) -> &str { + &self.id + } + + /// Returns the policy's `Metadata.Revision`. + pub fn revision(&self) -> Revision { + self.revision + } + + /// Returns the identity a response names the deciding policy by. + pub fn identity(&self) -> PolicyIdentity { + PolicyIdentity { + id: self.id.clone(), + revision: self.revision, + } + } + + /// Evaluates `request` against this policy at the evaluation time `time`. + pub fn evaluate(&self, request: &Request, time: DateTime) -> Result { + // The evaluator reads its evaluation time from text only, so the instant goes through the timestamp the broker + // writes in its responses, which keeps every nanosecond. + let time = Timestamp::from_datetime(time) + .ok() + .and_then(|timestamp| timestamp.as_str().parse::().ok()) + .ok_or(EvaluationError::TimeOutOfRange)?; + + now_policy_eval::evaluate(&self.policy, request, time).map_err(|_| EvaluationError::BadRequest) + } + + /// Returns whether replacing this policy with `candidate` is `RevisionNotHigher`. + /// + /// A document with another `Id` may have any `Revision`. + pub fn refuses_revision_of(&self, candidate: &AcceptedPolicy) -> bool { + self.id == candidate.id && candidate.revision <= self.revision + } +} + +/// Why a request got no decision. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum EvaluationError { + /// The request is not well-formed. + BadRequest, + /// The evaluation time is not an instant a timestamp of the policy contract can express. + TimeOutOfRange, +} + +impl fmt::Display for EvaluationError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::BadRequest => f.write_str("request is not well-formed"), + Self::TimeOutOfRange => f.write_str("evaluation time is outside the years 0001 to 9999"), + } + } +} + +impl core::error::Error for EvaluationError {} + +/// Returns the policy errors of a document, given as its bytes, which are none exactly when the document is valid. +pub fn validate(bytes: &[u8]) -> Vec { + match AcceptedPolicy::from_bytes(bytes) { + Ok(_) => Vec::new(), + Err(errors) => errors, + } +} + +/// Returns whether the broker refuses to run `request` although `decision`, its decision, allows it. +/// +/// The broker never runs a `Pre` or `Post` command with administrator rights. +/// A decision that audit mode turned into `Allow` is refused like any other, and a denied request is not, because it is +/// answered with its denial. +pub fn is_not_runnable(request: &Request, decision: &Decision) -> bool { + decision.outcome == Outcome::Allow + && request.opt_ins.pre_post_commands.is_some() + && request.elevation == Elevation::Elevated +} + +fn policy_error(error: now_policy_eval::ValidationError) -> PolicyError { + use now_policy_eval::ErrorCode; + + let code = match error.code { + ErrorCode::DocumentTooLarge => PolicyErrorCode::DocumentTooLarge, + ErrorCode::MalformedDocument => PolicyErrorCode::MalformedDocument, + ErrorCode::DuplicateKey => PolicyErrorCode::DuplicateKey, + ErrorCode::UnsupportedFormatVersion => PolicyErrorCode::UnsupportedFormatVersion, + ErrorCode::MissingKey => PolicyErrorCode::MissingKey, + ErrorCode::UnknownKey => PolicyErrorCode::UnknownKey, + ErrorCode::ConflictingKeys => PolicyErrorCode::ConflictingKeys, + ErrorCode::WrongType => PolicyErrorCode::WrongType, + ErrorCode::InvalidValue => PolicyErrorCode::InvalidValue, + ErrorCode::DuplicateRuleId => PolicyErrorCode::DuplicateRuleId, + }; + + PolicyError { + code, + pointer: error.pointer, + } +} + +/// Reads `Metadata.Id` and `Metadata.Revision` from the text of a valid document. +fn read_identity(document: &str) -> Option<(String, Revision)> { + let json = document.strip_prefix(BYTE_ORDER_MARK).unwrap_or(document); + let value: serde_json::Value = serde_json::from_str(json).ok()?; + let metadata = value.get("Metadata")?; + let id = metadata.get("Id")?.as_str()?.to_owned(); + let revision = u32::try_from(metadata.get("Revision")?.as_u64()?).ok()?; + + Some((id, Revision::new(revision).ok()?)) +} + +#[cfg(test)] +pub(crate) mod tests { + use chrono::TimeZone as _; + use now_policy_eval::{Check, Manager, Operation, OptIns, Package, PrePostCommands, Source}; + + use super::*; + + /// A valid policy document that allows nothing. + pub(crate) fn document(id: &str, revision: u32) -> String { + document_with(id, revision, "[]", "") + } + + /// A valid policy document with `rules` as its `Rules` and `enforcement` as extra top-level members. + fn document_with(id: &str, revision: u32, rules: &str, enforcement: &str) -> String { + format!( + r#"{{ + "PolicyFormatVersion": "2.0.0", + "Metadata": {{ "Id": "{id}", "Publisher": "Test", "Revision": {revision}, "PublishedAt": "2026-01-01T00:00:00Z" }}, + {enforcement} + "TrustedSources": [{{ "Manager": "Winget", "AnySource": true }}], + "Rules": {rules} +}}"# + ) + } + + const ALLOW_PRE_POST_COMMANDS: &str = + r#"[{ "Id": "allow-commands", "Decision": "Allow", "Select": {}, "Grants": { "PrePostCommands": {} } }]"#; + + const AUDIT_MODE: &str = r#""Enforcement": { "AuditMode": true },"#; + + fn accepted(document: &str) -> AcceptedPolicy { + AcceptedPolicy::from_bytes(document.as_bytes()).expect("document is valid") + } + + fn request(elevation: Elevation, pre_post_commands: bool) -> Request { + Request { + operation: Operation::Install, + manager: Manager::Winget, + source: Source { + name: "winget".to_owned(), + }, + package: Package { + id: "Git.Git".to_owned(), + // An install through WinGet without a concrete version is denied whatever the policy says. + version: Some("2.45.1".to_owned()), + architecture: None, + }, + scope: None, + elevation, + opt_ins: OptIns { + pre_post_commands: pre_post_commands.then(|| PrePostCommands { + pre: Some("echo before".to_owned()), + post: None, + }), + ..OptIns::default() + }, + } + } + + fn evaluation_time() -> DateTime { + Utc.with_ymd_and_hms(2026, 6, 1, 12, 0, 0).single().expect("valid time") + } + + fn error(code: PolicyErrorCode, pointer: &str) -> PolicyError { + PolicyError { + code, + pointer: pointer.to_owned(), + } + } + + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §policy-identity + #[test] + fn accepted_policy_keeps_its_text_and_identity() { + let text = document("corp-baseline", 7); + + let policy = accepted(&text); + + assert_eq!(policy.document(), text); + assert_eq!(policy.id(), "corp-baseline"); + assert_eq!(policy.revision().get(), 7); + assert_eq!(policy.identity().id, "corp-baseline"); + assert_eq!(policy.identity().revision.get(), 7); + } + + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §management-state + #[test] + fn leading_byte_order_mark_stays_in_the_document_text() { + let text = format!("\u{FEFF}{}", document("corp-baseline", 2)); + + let policy = accepted(&text); + + assert!(policy.document().starts_with('\u{FEFF}')); + assert_eq!(policy.document(), text); + assert_eq!(policy.id(), "corp-baseline"); + assert_eq!(policy.revision().get(), 2); + } + + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §validation + #[test] + fn valid_document_has_no_errors() { + assert_eq!(validate(document("corp-baseline", 1).as_bytes()), []); + } + + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.policy.md §errors + #[test] + fn document_with_one_defect_reports_that_error() { + let cases = [ + ( + "not JSON", + b"{".to_vec(), + error(PolicyErrorCode::MalformedDocument, ""), + ), + ( + "not UTF-8", + vec![0xFF], + error(PolicyErrorCode::MalformedDocument, ""), + ), + ( + "earlier format version", + document("corp-baseline", 1).replace("2.0.0", "1.0.0").into_bytes(), + error(PolicyErrorCode::UnsupportedFormatVersion, "/PolicyFormatVersion"), + ), + ( + "revision zero", + document("corp-baseline", 0).into_bytes(), + error(PolicyErrorCode::InvalidValue, "/Metadata/Revision"), + ), + ( + "unknown top-level key", + document_with("corp-baseline", 1, "[]", r#""Extra": 1,"#).into_bytes(), + error(PolicyErrorCode::UnknownKey, "/Extra"), + ), + ]; + + for (name, bytes, expected) in cases { + assert_eq!(validate(&bytes), [expected.clone()], "{name}"); + assert_eq!( + AcceptedPolicy::from_bytes(&bytes).expect_err(name), + [expected], + "{name}" + ); + } + } + + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §decision + #[test] + fn evaluation_decides_against_the_document() { + let policy = accepted(&document_with("corp-baseline", 1, ALLOW_PRE_POST_COMMANDS, "")); + + let allowed = policy + .evaluate(&request(Elevation::NonElevated, true), evaluation_time()) + .expect("well-formed request"); + let denied = accepted(&document("corp-baseline", 1)) + .evaluate(&request(Elevation::NonElevated, false), evaluation_time()) + .expect("well-formed request"); + + assert_eq!(allowed.outcome, Outcome::Allow); + assert_eq!(allowed.check, Check::AllowRules); + assert_eq!(denied.outcome, Outcome::Deny); + assert!(!denied.audited); + } + + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.policy.md §validity-window + #[test] + fn evaluation_uses_the_given_time() { + let text = document_with("corp-baseline", 1, ALLOW_PRE_POST_COMMANDS, "").replace( + r#""PublishedAt": "2026-01-01T00:00:00Z""#, + r#""PublishedAt": "2026-01-01T00:00:00Z", "ValidUntil": "2026-06-01T12:00:00.5Z""#, + ); + let policy = accepted(&text); + let request = request(Elevation::NonElevated, false); + let last_instant = evaluation_time() + chrono::Duration::milliseconds(500); + + let in_force = policy.evaluate(&request, last_instant).expect("well-formed request"); + let expired = policy + .evaluate(&request, last_instant + chrono::Duration::nanoseconds(1)) + .expect("well-formed request"); + + assert_eq!(in_force.outcome, Outcome::Allow); + assert_eq!(expired.outcome, Outcome::Deny); + } + + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §package-request + #[test] + fn request_that_is_not_well_formed_gets_no_decision() { + let mut request = request(Elevation::NonElevated, false); + request.package.id = String::new(); + + let result = accepted(&document("corp-baseline", 1)).evaluate(&request, evaluation_time()); + + assert_eq!(result, Err(EvaluationError::BadRequest)); + } + + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.policy.md §timestamps + #[test] + fn evaluation_time_after_year_9999_gets_no_decision() { + let time = Utc.with_ymd_and_hms(10000, 1, 1, 0, 0, 0).single().expect("valid time"); + + let result = + accepted(&document("corp-baseline", 1)).evaluate(&request(Elevation::NonElevated, false), time); + + assert_eq!(result, Err(EvaluationError::TimeOutOfRange)); + } + + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §not-runnable + #[test] + fn allowed_elevated_request_with_commands_is_not_runnable() { + let policy = accepted(&document_with("corp-baseline", 1, ALLOW_PRE_POST_COMMANDS, "")); + let request = request(Elevation::Elevated, true); + + let decision = policy.evaluate(&request, evaluation_time()).expect("well-formed request"); + + assert_eq!(decision.outcome, Outcome::Allow, "the policy grants the opt-in"); + assert!(!decision.audited); + assert!(is_not_runnable(&request, &decision)); + } + + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §not-runnable + #[test] + fn request_allowed_by_audit_mode_is_not_runnable_either() { + let policy = accepted(&document_with("corp-baseline", 1, "[]", AUDIT_MODE)); + let request = request(Elevation::Elevated, true); + + let decision = policy.evaluate(&request, evaluation_time()).expect("well-formed request"); + + assert_eq!(decision.outcome, Outcome::Allow, "audit mode lets the denied request run"); + assert!(decision.audited); + assert!(is_not_runnable(&request, &decision)); + } + + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §evaluate + #[test] + fn denied_request_is_not_reported_as_not_runnable() { + let policy = accepted(&document("corp-baseline", 1)); + let request = request(Elevation::Elevated, true); + + let decision = policy.evaluate(&request, evaluation_time()).expect("well-formed request"); + + assert_eq!(decision.outcome, Outcome::Deny, "no rule allows the request"); + assert!(!is_not_runnable(&request, &decision)); + } + + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §not-runnable + #[test] + fn allowed_request_without_both_conditions_is_runnable() { + let policy = accepted(&document_with("corp-baseline", 1, ALLOW_PRE_POST_COMMANDS, "")); + + for (elevation, pre_post_commands) in [ + (Elevation::NonElevated, true), + (Elevation::Elevated, false), + (Elevation::NonElevated, false), + ] { + let request = request(elevation, pre_post_commands); + let decision = policy.evaluate(&request, evaluation_time()).expect("well-formed request"); + + assert_eq!(decision.outcome, Outcome::Allow, "{elevation:?} {pre_post_commands}"); + assert!( + !is_not_runnable(&request, &decision), + "{elevation:?} {pre_post_commands}" + ); + } + } + + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §replacement + #[test] + fn revision_is_refused_only_for_the_same_id_and_no_higher_revision() { + let held = accepted(&document("corp-baseline", 5)); + + let cases = [ + ("same id, lower revision", "corp-baseline", 4, true), + ("same id, equal revision", "corp-baseline", 5, true), + ("same id, higher revision", "corp-baseline", 6, false), + ("other id, lower revision", "other", 1, false), + ("other id, equal revision", "other", 5, false), + ("other id, higher revision", "other", 9, false), + ]; + + for (name, id, revision, refused) in cases { + let candidate = accepted(&document(id, revision)); + + assert_eq!(held.refuses_revision_of(&candidate), refused, "{name}"); + } + } +} From 6c7395be64b6af4ce8a102ee3f9aa00017e12194 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Tue, 1 Dec 2026 04:55:12 +0900 Subject: [PATCH 05/16] feat(agent): hold and replace 2.x policies in the policy store The policy store now reads the policy file once for both request encodings. Beside the 1.x snapshot it holds what the 2.0 endpoints report: the policy management state of the wire contract, and the accepted policy when the file is a valid 2.x document. A replacement of the 2.0 encoding writes the document text unchanged as the whole file through the transactions the 1.x writes use, decides its outcome in the order the wire contract gives, and succeeds only when the file read back holds exactly the document that was sent. A file in format 2.x is read-only for the 1.x management endpoints, because their reader reports it as invalid and a repair would overwrite it. A file the 1.x reader accepts stays exactly as it was for those endpoints, and is `Unconvertible` for the 2.0 endpoints: no conversion is defined, so the one function a conversion would live in refuses every policy. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- crates/now-package-broker/src/audit.rs | 77 ++ .../src/policy_store/document.rs | 203 +++++ .../src/policy_store/document_tests.rs | 794 ++++++++++++++++++ .../src/policy_store/format_1.rs | 27 + .../src/policy_store/mod.rs | 330 +++++++- .../src/policy_store/windows.rs | 277 +++++- crates/now-package-broker/src/v2/policy.rs | 95 ++- 7 files changed, 1747 insertions(+), 56 deletions(-) create mode 100644 crates/now-package-broker/src/policy_store/document.rs create mode 100644 crates/now-package-broker/src/policy_store/document_tests.rs create mode 100644 crates/now-package-broker/src/policy_store/format_1.rs diff --git a/crates/now-package-broker/src/audit.rs b/crates/now-package-broker/src/audit.rs index 26b830a9e..7099ce653 100644 --- a/crates/now-package-broker/src/audit.rs +++ b/crates/now-package-broker/src/audit.rs @@ -187,6 +187,19 @@ impl FailureReason { } } +/// The request a policy replacement of the 2.0 encoding arrives as. +const DOCUMENT_INTENT: &str = "POST /v2/policy"; + +/// The operation recorded for a policy replacement of the 2.0 encoding, which has no operation of its own. +const DOCUMENT_OPERATION: &str = "replace"; + +/// Whether a policy replacement of the 2.0 encoding writes a policy file where none exists or changes one. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum DocumentWrite { + Create, + Change, +} + /// Which class an audit entry belongs to. /// /// Both classes share one queue, so entries reach the sink in the order they were recorded. The @@ -653,6 +666,70 @@ impl WriteAudit { }); } + /// Records that a policy replacement of the 2.0 encoding did not replace the policy. + pub(crate) fn document_failed_at(&self, path: &Path, write: DocumentWrite, reason: FailureReason) { + let path = bounded_path(path); + let outcome = if reason == FailureReason::StaleStoreToken { + "stale_conflict" + } else { + "failed" + }; + let (event_code, message) = match write { + DocumentWrite::Create => (policy_events::POLICY_CREATE_FAILED, "Policy creation failed"), + DocumentWrite::Change => (policy_events::POLICY_CHANGE_FAILED, "Policy change failed"), + }; + self.finish(EntryClass::Outcome, |state| { + policy_events::policy_write_failed( + event_code, + message, + &state.actor_sid, + &state.actor_exe, + DOCUMENT_INTENT, + path, + DOCUMENT_OPERATION, + outcome, + reason.as_str(), + ) + }); + } + + /// Records that a policy replacement of the 2.0 encoding replaced the policy. + /// + /// `old` is the id and revision of the accepted policy the replacement took the place of. + pub(crate) fn document_succeeded_at( + &self, + path: &Path, + old: Option<(&str, u32)>, + new_id: &str, + new_revision: u32, + write: DocumentWrite, + ) { + let path = bounded_path(path); + let old_id = bounded(old.map_or("", |(id, _)| id).to_owned(), MAX_POLICY_ID_BYTES); + let old_revision = old.map_or_else(|| "none".to_owned(), |(_, revision)| revision.to_string()); + let new_id = bounded(new_id.to_owned(), MAX_POLICY_ID_BYTES); + let (event_code, message) = match write { + DocumentWrite::Create => (policy_events::POLICY_CREATE_SUCCEEDED, "Policy creation succeeded"), + DocumentWrite::Change => (policy_events::POLICY_CHANGE_SUCCEEDED, "Policy change succeeded"), + }; + self.finish(EntryClass::Outcome, |state| { + policy_events::policy_write_succeeded( + event_code, + message, + &state.actor_sid, + &state.actor_exe, + path, + old_id, + old_revision, + new_id, + new_revision, + DOCUMENT_INTENT, + DOCUMENT_OPERATION, + "applied", + ) + }); + } + /// Records the terminal event of `class`, which decides whether a saturated sink may drop it. fn finish(&self, class: EntryClass, entry: impl FnOnce(&WriteAuditState) -> Entry) { if self diff --git a/crates/now-package-broker/src/policy_store/document.rs b/crates/now-package-broker/src/policy_store/document.rs new file mode 100644 index 000000000..28bd483f5 --- /dev/null +++ b/crates/now-package-broker/src/policy_store/document.rs @@ -0,0 +1,203 @@ +//! What the policy file holds for the 2.0 endpoints. +//! +//! The storage observes the file once for both request encodings. +//! [`DocumentObservation`] is the part of that observation the 2.0 endpoints read, and [`DocumentView`] is what the +//! store publishes from it. + +use std::sync::Arc; + +use now_policy::PolicyDocument; +use now_policy_api::PolicyReadOnlyReason; +use now_policy_api::v2::{ + InvalidReason, PolicyError, PolicyErrorCode, PolicyManagement, PolicyPath, PolicyState, ReadOnlyReason, StoreToken, +}; + +use super::format_1::{Conversion, Converter}; +use super::validation::DiskFailureReason; +use crate::v2::policy::AcceptedPolicy; + +/// The part of a storage observation the 2.0 endpoints read. +pub(super) struct DocumentObservation { + pub content: FileContent, + /// Why a replacement cannot write the file, as far as the storage decides it. + pub read_only_reason: Option, +} + +/// What the storage found at the policy path. +#[derive(Clone)] +pub(super) enum FileContent { + /// No file exists. + Missing, + /// The storage could not read the file or does not rely on it. + Unusable(InvalidReason), + /// A valid 2.x document. + Accepted(Arc), + /// A policy the 1.x reader accepted, with the text of the file. + Format1(String), + /// Neither, with the errors of the file read as a 2.x document. + Invalid(Vec), +} + +impl DocumentObservation { + /// The observation of a file the storage failed on for `reason`, before it read any content. + pub(super) fn of_storage_failure( + reason: DiskFailureReason, + read_only_reason: Option, + ) -> Self { + let content = match reason { + DiskFailureReason::Unreadable => FileContent::Unusable(InvalidReason::ReadFailed), + DiskFailureReason::InsecureStorage => FileContent::Unusable(InvalidReason::InsecureStorage), + DiskFailureReason::UnsupportedFormat => FileContent::Unusable(InvalidReason::UnsupportedPath), + DiskFailureReason::WatcherUnavailable => FileContent::Unusable(InvalidReason::MonitoringUnavailable), + // The 1.x reader gives these reasons for content it read, and content is classified where it is read. + // A storage failure that carries one anyway has no content to report errors for. + DiskFailureReason::MalformedContent | DiskFailureReason::FailedSemanticValidation => { + FileContent::Invalid(vec![PolicyError { + code: PolicyErrorCode::MalformedDocument, + pointer: String::new(), + }]) + } + }; + + Self { + content, + read_only_reason: self::read_only_reason(read_only_reason), + } + } +} + +/// Returns the reason a replacement cannot write the file for the reason the storage gives the 1.x endpoints. +pub(super) fn read_only_reason(reason: Option) -> Option { + Some(match reason? { + // The storage gives this reason only once it stopped watching the file. + PolicyReadOnlyReason::ManagementDisabled => ReadOnlyReason::MonitoringUnavailable, + // The storage never gives `PathNotConfigured`, because the broker always reads a path. + PolicyReadOnlyReason::PathNotConfigured | PolicyReadOnlyReason::UnsupportedFormat => { + ReadOnlyReason::UnsupportedPath + } + PolicyReadOnlyReason::UnsafePath => ReadOnlyReason::UnsafePath, + PolicyReadOnlyReason::InsufficientPermissions => ReadOnlyReason::InsufficientPermissions, + PolicyReadOnlyReason::UnsupportedFileSystem => ReadOnlyReason::UnsupportedFileSystem, + }) +} + +/// The state of the policy file as the 2.0 endpoints report it, with the accepted policy when there is one. +pub(super) struct DocumentView { + pub state: DocumentState, + /// Why a replacement cannot write the file, as far as the storage decides it. + pub read_only_reason: Option, +} + +pub(super) enum DocumentState { + Active { + policy: Arc, + /// The text of the policy file, which is not the text of `policy` when the policy was converted. + document: String, + }, + Missing, + /// The file is not a valid policy document, for these errors, of which there is at least one. + InvalidDocument(Vec), + /// The file is invalid for a reason other than `InvalidDocument`. + Unusable(InvalidReason), +} + +impl DocumentView { + /// Builds the view of an observation. + /// + /// `format_1` is the policy the 1.x reader accepted from the same file, which `convert` turns into the accepted + /// policy or refuses. + pub(super) fn from_observation( + observation: DocumentObservation, + format_1: Option<&PolicyDocument>, + convert: Converter, + ) -> Self { + let state = match observation.content { + FileContent::Missing => DocumentState::Missing, + FileContent::Unusable(reason) => DocumentState::Unusable(reason), + FileContent::Accepted(policy) => DocumentState::Active { + document: policy.document().to_owned(), + policy, + }, + FileContent::Invalid(errors) => DocumentState::InvalidDocument(errors), + FileContent::Format1(text) => match format_1.and_then(|policy| converted(policy, convert)) { + Some(policy) => DocumentState::Active { + policy: Arc::new(policy), + document: text, + }, + None => DocumentState::Unusable(InvalidReason::Unconvertible), + }, + }; + + Self { + state, + read_only_reason: observation.read_only_reason, + } + } + + /// Returns the accepted policy, which the broker holds exactly when the state is `Active`. + pub(super) fn accepted(&self) -> Option<&Arc> { + match &self.state { + DocumentState::Active { policy, .. } => Some(policy), + DocumentState::Missing | DocumentState::InvalidDocument(_) | DocumentState::Unusable(_) => None, + } + } + + /// Returns the policy management state of this view. + /// + /// `watched` is whether the broker watches the file for changes, without which no replacement writes it. + pub(super) fn management(&self, path: PolicyPath, store_token: StoreToken, watched: bool) -> PolicyManagement { + let mut management = PolicyManagement { + state: PolicyState::Missing, + path, + store_token, + read_only_reason: if watched { + self.read_only_reason + } else { + Some(ReadOnlyReason::MonitoringUnavailable) + }, + document: None, + invalid_reason: None, + errors: None, + }; + + match &self.state { + DocumentState::Active { document, .. } => { + management.state = PolicyState::Active; + management.document = Some(document.clone()); + } + DocumentState::Missing => {} + DocumentState::InvalidDocument(errors) => { + management.state = PolicyState::Invalid; + management.invalid_reason = Some(InvalidReason::InvalidDocument); + management.errors = Some(errors.clone()); + } + DocumentState::Unusable(reason) => { + management.state = PolicyState::Invalid; + management.invalid_reason = Some(*reason); + } + } + + management + } +} + +/// Converts a 1.x policy and reads the result as the text of a 2.x policy file. +/// +/// A conversion whose document is not valid is no exact conversion, so it is refused like any other. +fn converted(policy: &PolicyDocument, convert: Converter) -> Option { + let Conversion { document, differences } = convert(policy).ok()?; + + let accepted = match AcceptedPolicy::from_bytes(document.as_bytes()) { + Ok(accepted) => accepted, + Err(errors) => { + tracing::warn!(?errors, "Converted 1.x policy is not a valid policy document"); + return None; + } + }; + + for difference in differences { + tracing::warn!(%difference, "Converted policy differs from the 1.x policy file"); + } + + Some(accepted) +} diff --git a/crates/now-package-broker/src/policy_store/document_tests.rs b/crates/now-package-broker/src/policy_store/document_tests.rs new file mode 100644 index 000000000..2c8794e4f --- /dev/null +++ b/crates/now-package-broker/src/policy_store/document_tests.rs @@ -0,0 +1,794 @@ +//! The policy store as the 2.0 endpoints use it, over a storage double that holds the bytes of one policy file. + +use std::sync::atomic::{AtomicUsize, Ordering}; + +use now_policy::PolicyDraftDocument; +use now_policy_api::v2::{InvalidReason, PolicyError, PolicyErrorCode, PolicyManagement, PolicyState, ReadOnlyReason}; +use now_policy_api::{PolicyConflictHandling, PolicyReplacementRequestKind}; +use win_api_wrappers::identity::sid::Sid; + +use super::*; +use crate::v2::policy::tests::document; + +const POLICY_PATH: &str = r"C:\policy.json"; + +/// What a document write into the storage double does besides, or instead of, publishing the document. +enum Fault { + /// The write fails before anything is published. + WriteFails, + /// Someone else writes this content first, which the conditional publication does not write over. + ChangedBeforeWrite(Vec), + /// The document is published, and someone else writes this content before the file is read again. + ChangedAfterWrite(Vec), + /// The document is published, and what the storage does after the publication fails. + FailsAfterWrite, +} + +struct FakeFile { + content: Option>, + /// Stands in for the identity of the file, which every write changes. + generation: u32, +} + +/// A storage that holds the bytes of one policy file and reads them exactly as the content of a real file is read. +struct FileDouble { + file: parking_lot::Mutex, + read_only: Option<(PolicyWriteCapability, PolicyReadOnlyReason)>, + fault: parking_lot::Mutex>, + writes: AtomicUsize, +} + +impl FileDouble { + fn holding(content: Option<&str>) -> Arc { + Self::new(content, None) + } + + fn read_only(content: &str, capability: PolicyWriteCapability, reason: PolicyReadOnlyReason) -> Arc { + Self::new(Some(content), Some((capability, reason))) + } + + fn new(content: Option<&str>, read_only: Option<(PolicyWriteCapability, PolicyReadOnlyReason)>) -> Arc { + Arc::new(Self { + file: parking_lot::Mutex::new(FakeFile { + content: content.map(|content| content.as_bytes().to_vec()), + generation: 1, + }), + read_only, + fault: parking_lot::Mutex::new(None), + writes: AtomicUsize::new(0), + }) + } + + fn content(&self) -> Option> { + self.file.lock().content.clone() + } + + /// Writes the file as someone other than the store does. + fn set_content(&self, content: &[u8]) { + let mut file = self.file.lock(); + file.content = Some(content.to_vec()); + file.generation += 1; + } + + fn fail_next_write(&self, fault: Fault) { + *self.fault.lock() = Some(fault); + } + + /// How many times the store wrote the file. + fn writes(&self) -> usize { + self.writes.load(Ordering::SeqCst) + } + + fn publish(&self, bytes: &[u8]) { + self.set_content(bytes); + self.writes.fetch_add(1, Ordering::SeqCst); + } + + fn observation(&self) -> Observation { + let file = self.file.lock(); + match &file.content { + Some(content) => windows::test_file_observation(content, file.generation, self.read_only), + None => windows::test_missing_file_observation(self.read_only), + } + } + + fn write_format_1(&self, bytes: &[u8]) -> Result { + self.publish(bytes); + let observation = self.observation(); + let policy = observation + .policy + .ok_or_else(|| WriteFailure::PostPublication(anyhow::anyhow!("published bytes are no 1.x policy")))?; + Ok(PersistedPolicy { + policy, + fingerprint: observation.fingerprint, + write_capability: observation.write_capability, + read_only_reason: observation.read_only_reason, + canonical_path: observation.canonical_path, + }) + } +} + +impl PolicyStorage for FileDouble { + fn observe(&self, _source: PolicyConfigurationSource, _path: &Path) -> Observation { + self.observation() + } + + fn observe_for_write(&self, source: PolicyConfigurationSource, path: &Path) -> Observation { + let mut observation = self.observe(source, path); + if observation.state != PolicyManagementState::Missing { + observation.retained_target = Some(windows::RetainedPolicyFile::for_fake(observation.fingerprint.clone())); + } + observation + } + + fn create( + &self, + _source: PolicyConfigurationSource, + _configured_path: &Path, + _observation: &Observation, + bytes: &[u8], + ) -> Result { + self.write_format_1(bytes) + } + + fn replace( + &self, + _source: PolicyConfigurationSource, + _configured_path: &Path, + _observation: &mut Observation, + bytes: &[u8], + ) -> Result { + self.write_format_1(bytes) + } + + fn write_document( + &self, + _configured_path: &Path, + observation: &mut Observation, + bytes: &[u8], + ) -> Result { + let fault = self.fault.lock().take(); + match &fault { + Some(Fault::WriteFails) => { + return Err(WriteFailure::PrePublication(anyhow::anyhow!( + "injected failure before publication" + ))); + } + Some(Fault::ChangedBeforeWrite(content)) => self.set_content(content), + Some(Fault::ChangedAfterWrite(_) | Fault::FailsAfterWrite) | None => {} + } + if self.observation().fingerprint != observation.fingerprint { + return Err(WriteFailure::ConcurrentChange(anyhow::anyhow!( + "the file is not the one the observation saw" + ))); + } + self.publish(bytes); + match &fault { + Some(Fault::ChangedAfterWrite(content)) => self.set_content(content), + Some(Fault::FailsAfterWrite) => { + return Err(WriteFailure::PostPublication(anyhow::anyhow!( + "injected failure after publication" + ))); + } + Some(Fault::WriteFails | Fault::ChangedBeforeWrite(_)) | None => {} + } + Ok(self.observation()) + } +} + +fn store(storage: &Arc) -> Arc { + PolicyStore::load_with_storage( + Some(PathBuf::from(POLICY_PATH)), + Arc::clone(storage) as Arc, + Monitoring::Available, + ) +} + +fn store_converting(storage: &Arc, converter: format_1::Converter) -> Arc { + PolicyStore::load_with_converter( + Some(PathBuf::from(POLICY_PATH)), + Arc::clone(storage) as Arc, + Monitoring::Available, + converter, + ) +} + +fn management(store: &PolicyStore) -> PolicyManagement { + store + .policy_management() + .expect("the policy path is one a state carries") +} + +async fn replace(store: &PolicyStore, expected: &v2::StoreToken, document: &str) -> DocumentReplacement { + store + .replace_document(expected, document, crate::audit::tests::noop()) + .await + .expect("the policy path is one a state carries") +} + +/// The error code a replacement outcome is answered with, or `Replaced`. +fn code(outcome: &DocumentReplacement) -> &'static str { + match outcome { + DocumentReplacement::StaleStoreToken(_) => "StaleStoreToken", + DocumentReplacement::PolicyNotWritable(_) => "PolicyNotWritable", + DocumentReplacement::InvalidPolicy(_) => "InvalidPolicy", + DocumentReplacement::RevisionNotHigher(_) => "RevisionNotHigher", + DocumentReplacement::PersistenceFailed => "PersistenceFailed", + DocumentReplacement::ActivationFailed(_) => "ActivationFailed", + DocumentReplacement::Replaced(_) => "Replaced", + } +} + +/// The policy management state a replacement outcome carries. +fn state_after(outcome: DocumentReplacement) -> Option { + match outcome { + DocumentReplacement::StaleStoreToken(management) + | DocumentReplacement::PolicyNotWritable(management) + | DocumentReplacement::RevisionNotHigher(management) + | DocumentReplacement::ActivationFailed(management) + | DocumentReplacement::Replaced(management) => Some(management), + DocumentReplacement::InvalidPolicy(_) | DocumentReplacement::PersistenceFailed => None, + } +} + +/// The identity of the accepted policy the store holds. +fn held(store: &PolicyStore) -> Option<(String, u32)> { + store + .accepted_policy() + .map(|policy| (policy.id().to_owned(), policy.revision().get())) +} + +/// A 2.x document whose only defect is the unknown top-level key `Extra`. +fn document_with_unknown_key(id: &str, revision: u32) -> String { + document(id, revision).replacen(r#""Rules""#, "\"Extra\": 1,\n \"Rules\"", 1) +} + +/// The error a reader reports for [`document_with_unknown_key`]. +fn unknown_key_error() -> PolicyError { + PolicyError { + code: PolicyErrorCode::UnknownKey, + pointer: "/Extra".to_owned(), + } +} + +fn format_1_draft(id: &str) -> serde_json::Value { + serde_json::json!({ + "PolicyFormatVersion": "1.0.0", + "Metadata": { "Id": id, "Publisher": "Test" }, + "Enforcement": { "DefaultDecision": "Deny" }, + "Rules": [] + }) +} + +/// The text of a policy file the 1.x reader accepts. +fn format_1_text(id: &str, revision: u32) -> String { + let draft: PolicyDraftDocument = serde_json::from_value(format_1_draft(id)).expect("valid draft"); + let policy = draft + .into_policy_document(revision, Utc::now()) + .expect("valid committed policy"); + serde_json::to_string_pretty(&policy).expect("policy serializes") +} + +fn format_1_request(store: &PolicyStore, operation: PolicyReplacementOperation) -> PolicyReplacementRequest { + let raw = format_1_draft("legacy"); + let validation = store.validate_draft(&raw); + PolicyReplacementRequest { + request_kind: PolicyReplacementRequestKind, + request_version: API_VERSION_STR.into(), + expected_store_token: store.management_snapshot().store_token, + operation, + conflict_handling: PolicyConflictHandling::Reject, + draft: raw, + validation_receipt: validation.validation_receipt.expect("valid receipt"), + } +} + +/// Converts a 1.x policy to a 2.x document that keeps its identity, and reports one difference. +fn convert_keeping_identity(policy: &PolicyDocument) -> Result { + Ok(format_1::Conversion { + document: document(&policy.metadata.id.0, policy.metadata.revision), + differences: vec!["rule priorities are not kept".to_owned()], + }) +} + +/// Converts every 1.x policy to text that is not a policy document. +fn convert_to_invalid_document(_policy: &PolicyDocument) -> Result { + Ok(format_1::Conversion { + document: "{".to_owned(), + differences: Vec::new(), + }) +} + +fn recording_audit() -> (crate::audit::WriteAudit, Arc) { + let sid = Sid::from_well_known(::windows::Win32::Security::WinLocalSystemSid, None).expect("resolve SYSTEM SID"); + crate::audit::tests::begin(&sid, Path::new(r"C:\client.exe"), Path::new(POLICY_PATH)) +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §management-state +#[test] +fn valid_document_file_is_active_with_its_text() { + let text = document("corp-baseline", 3); + let store = store(&FileDouble::holding(Some(&text))); + + let management = management(&store); + + assert_eq!(management.state, PolicyState::Active); + assert_eq!(management.path.as_str(), POLICY_PATH); + assert_eq!(management.document.as_deref(), Some(text.as_str())); + assert_eq!(management.invalid_reason, None); + assert_eq!(management.errors, None); + assert_eq!(management.read_only_reason, None); + assert_eq!(held(&store), Some(("corp-baseline".to_owned(), 3))); +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §management-state +#[test] +fn invalid_document_file_is_invalid_with_its_errors() { + let store = store(&FileDouble::holding(Some(&document_with_unknown_key( + "corp-baseline", + 3, + )))); + + let management = management(&store); + + assert_eq!(management.state, PolicyState::Invalid); + assert_eq!(management.invalid_reason, Some(InvalidReason::InvalidDocument)); + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.policy.md §errors + assert_eq!(management.errors, Some(vec![unknown_key_error()])); + assert_eq!(management.document, None); + assert_eq!(held(&store), None); +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §management-state +#[test] +fn format_1_file_is_unconvertible_while_the_earlier_endpoints_still_read_it() { + let store = store(&FileDouble::holding(Some(&format_1_text("legacy", 2)))); + + let management = management(&store); + + assert_eq!(management.state, PolicyState::Invalid); + assert_eq!(management.invalid_reason, Some(InvalidReason::Unconvertible)); + assert_eq!(management.errors, None); + assert_eq!(management.document, None); + assert_eq!(held(&store), None); + // oracle: intent Devolutions/now-libraries@77307f5106d9:policies/INTENT.legacy.md §wire-1 + assert_eq!(store.management_snapshot().state, PolicyManagementState::Active); + assert_eq!( + store + .active_policy() + .map(|policy| (policy.metadata.id.0.clone(), policy.metadata.revision)), + Some(("legacy".to_owned(), 2)) + ); +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §management-state +#[test] +fn missing_file_is_missing() { + let store = store(&FileDouble::holding(None)); + + let management = management(&store); + + assert_eq!(management.state, PolicyState::Missing); + assert_eq!(management.document, None); + assert_eq!(management.invalid_reason, None); + assert_eq!(management.errors, None); + assert_eq!(held(&store), None); +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §management-state +#[test] +fn converted_format_1_policy_is_active_with_the_text_of_its_file() { + let text = format_1_text("legacy", 2); + let store = store_converting(&FileDouble::holding(Some(&text)), convert_keeping_identity); + + let management = management(&store); + + assert_eq!(management.state, PolicyState::Active); + assert_eq!(management.document.as_deref(), Some(text.as_str())); + assert_eq!(management.invalid_reason, None); + assert_eq!(held(&store), Some(("legacy".to_owned(), 2))); +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §management-state +#[test] +fn conversion_that_is_no_valid_document_is_unconvertible() { + let store = store_converting( + &FileDouble::holding(Some(&format_1_text("legacy", 2))), + convert_to_invalid_document, + ); + + let management = management(&store); + + assert_eq!(management.state, PolicyState::Invalid); + assert_eq!(management.invalid_reason, Some(InvalidReason::Unconvertible)); + assert_eq!(management.document, None); + assert_eq!(held(&store), None); +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §management-state +#[tokio::test] +async fn file_that_cannot_be_watched_is_invalid_and_read_only() { + let store = store(&FileDouble::holding(Some(&document("corp-baseline", 3)))); + + store.mark_watcher_unavailable().await; + let management = management(&store); + + assert_eq!(management.state, PolicyState::Invalid); + assert_eq!(management.invalid_reason, Some(InvalidReason::MonitoringUnavailable)); + assert_eq!(management.read_only_reason, Some(ReadOnlyReason::MonitoringUnavailable)); + assert_eq!(management.document, None); + assert_eq!(held(&store), None); +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §management-state +#[tokio::test] +async fn file_changed_by_someone_else_is_the_accepted_policy_after_a_reload() { + let storage = FileDouble::holding(Some(&document("corp-baseline", 3))); + let store = store(&storage); + let before = management(&store); + let changed = document("corp-baseline", 4); + + storage.set_content(changed.as_bytes()); + store.reload_from_disk(ReloadCause::ExternalChange).await; + let after = management(&store); + + assert_eq!(after.state, PolicyState::Active); + assert_eq!(after.document.as_deref(), Some(changed.as_str())); + assert_ne!(after.store_token, before.store_token); + assert_eq!(held(&store), Some(("corp-baseline".to_owned(), 4))); +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §replacement +#[tokio::test] +async fn replacement_with_another_store_token_is_stale() { + let text = document("corp-baseline", 3); + let storage = FileDouble::holding(Some(&text)); + let store = store(&storage); + let expected = v2::StoreToken::parse("not-the-current-token").expect("valid store token"); + + let outcome = replace(&store, &expected, &document("corp-baseline", 4)).await; + + assert_eq!(code(&outcome), "StaleStoreToken"); + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §errors + assert_eq!(state_after(outcome), Some(management(&store))); + assert_eq!(management(&store).document.as_deref(), Some(text.as_str())); + assert_eq!(storage.content(), Some(text.into_bytes())); + assert_eq!(storage.writes(), 0); +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §replacement +#[tokio::test] +async fn replacement_after_the_file_changed_is_stale_and_reports_the_changed_file() { + let storage = FileDouble::holding(Some(&document("corp-baseline", 3))); + let store = store(&storage); + let expected = management(&store).store_token; + let changed = document("corp-baseline", 4); + + storage.set_content(changed.as_bytes()); + let outcome = replace(&store, &expected, &document("corp-baseline", 5)).await; + + assert_eq!(code(&outcome), "StaleStoreToken"); + let after = state_after(outcome).expect("a stale replacement carries the state after the request"); + assert_eq!(after.document.as_deref(), Some(changed.as_str())); + assert_ne!(after.store_token, expected); + assert_eq!(storage.content(), Some(changed.into_bytes())); + assert_eq!(storage.writes(), 0); +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §replacement +#[tokio::test] +async fn stale_store_token_is_decided_before_writability() { + let storage = FileDouble::read_only( + &document("corp-baseline", 3), + PolicyWriteCapability::ReadOnly, + PolicyReadOnlyReason::UnsafePath, + ); + let store = store(&storage); + let expected = v2::StoreToken::parse("not-the-current-token").expect("valid store token"); + + let outcome = replace(&store, &expected, &document("corp-baseline", 4)).await; + + assert_eq!(code(&outcome), "StaleStoreToken"); +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §replacement +#[tokio::test] +async fn read_only_policy_is_not_writable_whatever_the_document() { + let text = document("corp-baseline", 3); + let storage = FileDouble::read_only(&text, PolicyWriteCapability::ReadOnly, PolicyReadOnlyReason::UnsafePath); + let store = store(&storage); + let expected = management(&store).store_token; + + let outcome = replace(&store, &expected, &document_with_unknown_key("corp-baseline", 4)).await; + + assert_eq!(code(&outcome), "PolicyNotWritable"); + let after = state_after(outcome).expect("an unwritable replacement carries the state after the request"); + assert!(after.read_only_reason.is_some()); + assert_eq!(after.document.as_deref(), Some(text.as_str())); + assert_eq!(storage.writes(), 0); +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §replacement +#[tokio::test] +async fn policy_that_cannot_be_watched_is_not_writable() { + let storage = FileDouble::holding(Some(&document("corp-baseline", 3))); + let store = store(&storage); + store.mark_watcher_unavailable().await; + let expected = management(&store).store_token; + + let outcome = replace(&store, &expected, &document("corp-baseline", 4)).await; + + assert_eq!(code(&outcome), "PolicyNotWritable"); + let after = state_after(outcome).expect("an unwritable replacement carries the state after the request"); + assert_eq!(after.read_only_reason, Some(ReadOnlyReason::MonitoringUnavailable)); + assert_eq!(storage.writes(), 0); +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §replacement +#[tokio::test] +async fn invalid_document_is_refused_with_its_errors_before_its_revision_is_compared() { + let text = document("corp-baseline", 3); + let storage = FileDouble::holding(Some(&text)); + let store = store(&storage); + let expected = management(&store).store_token; + + let outcome = replace(&store, &expected, &document_with_unknown_key("corp-baseline", 2)).await; + + assert!( + matches!(&outcome, DocumentReplacement::InvalidPolicy(errors) if *errors == [unknown_key_error()]), + "{outcome:?}" + ); + assert_eq!(storage.content(), Some(text.into_bytes())); + assert_eq!(held(&store), Some(("corp-baseline".to_owned(), 3))); +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §replacement +#[tokio::test] +async fn revision_that_is_not_higher_for_the_same_id_is_refused_before_writing() { + for (name, revision) in [("equal revision", 3), ("lower revision", 2)] { + let text = document("corp-baseline", 3); + let storage = FileDouble::holding(Some(&text)); + let store = store(&storage); + let expected = management(&store).store_token; + storage.fail_next_write(Fault::WriteFails); + + let outcome = replace(&store, &expected, &document("corp-baseline", revision)).await; + + assert_eq!(code(&outcome), "RevisionNotHigher", "{name}"); + let after = state_after(outcome).expect("a refused revision carries the state after the request"); + assert_eq!(after.document.as_deref(), Some(text.as_str()), "{name}"); + assert_eq!(storage.content(), Some(text.into_bytes()), "{name}"); + assert_eq!(storage.writes(), 0, "{name}"); + } +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §replacement +#[tokio::test] +async fn accepted_replacement_holds_the_document_exactly_as_sent() { + let cases = [ + ( + "same id and a higher revision", + Some(document("corp-baseline", 3)), + document("corp-baseline", 4), + ("corp-baseline", 4), + ), + ( + "another id and a lower revision", + Some(document("corp-baseline", 3)), + document("other", 1), + ("other", 1), + ), + ("no file", None, document("corp-baseline", 1), ("corp-baseline", 1)), + ( + "invalid file with a higher revision", + Some(document_with_unknown_key("corp-baseline", 9)), + document("corp-baseline", 1), + ("corp-baseline", 1), + ), + ( + "file in an earlier format", + Some(format_1_text("corp-baseline", 9)), + document("corp-baseline", 1), + ("corp-baseline", 1), + ), + ( + "document with a byte order mark", + Some(document("corp-baseline", 3)), + format!("\u{FEFF}{}", document("corp-baseline", 4)), + ("corp-baseline", 4), + ), + ]; + + for (name, file, sent, (id, revision)) in cases { + let storage = FileDouble::holding(file.as_deref()); + let store = store(&storage); + let expected = management(&store).store_token; + + let outcome = replace(&store, &expected, &sent).await; + + assert_eq!(code(&outcome), "Replaced", "{name}"); + let after = state_after(outcome).expect("a replacement response carries the state"); + assert_eq!(after.state, PolicyState::Active, "{name}"); + assert_eq!(after.document.as_deref(), Some(sent.as_str()), "{name}"); + assert_ne!(after.store_token, expected, "{name}"); + assert_eq!(management(&store), after, "{name}"); + assert_eq!(held(&store), Some((id.to_owned(), revision)), "{name}"); + assert_eq!(storage.content(), Some(sent.into_bytes()), "{name}"); + } +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §replacement +#[tokio::test] +async fn write_that_fails_leaves_the_policy_as_it_was() { + let text = document("corp-baseline", 3); + let storage = FileDouble::holding(Some(&text)); + let store = store(&storage); + let expected = management(&store).store_token; + storage.fail_next_write(Fault::WriteFails); + + let outcome = replace(&store, &expected, &document("corp-baseline", 4)).await; + + assert_eq!(code(&outcome), "PersistenceFailed"); + assert_eq!(storage.content(), Some(text.into_bytes())); + assert_eq!(held(&store), Some(("corp-baseline".to_owned(), 3))); +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §replacement +#[tokio::test] +async fn file_that_changes_before_the_write_is_never_written_over() { + let storage = FileDouble::holding(Some(&document("corp-baseline", 3))); + let store = store(&storage); + let expected = management(&store).store_token; + let changed = document("corp-baseline", 7); + storage.fail_next_write(Fault::ChangedBeforeWrite(changed.clone().into_bytes())); + + let outcome = replace(&store, &expected, &document("corp-baseline", 4)).await; + + assert_eq!(code(&outcome), "StaleStoreToken"); + let after = state_after(outcome).expect("a stale replacement carries the state after the request"); + assert_eq!(after.document.as_deref(), Some(changed.as_str())); + assert_eq!(storage.content(), Some(changed.into_bytes())); + assert_eq!(storage.writes(), 0); +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §replacement +#[tokio::test] +async fn written_document_the_broker_does_not_hold_is_an_activation_failure() { + let storage = FileDouble::holding(Some(&document("corp-baseline", 3))); + let store = store(&storage); + let expected = management(&store).store_token; + let sent = document("corp-baseline", 4); + storage.fail_next_write(Fault::ChangedAfterWrite(b"{".to_vec())); + + let outcome = replace(&store, &expected, &sent).await; + + assert_eq!(code(&outcome), "ActivationFailed"); + let after = state_after(outcome).expect("an activation failure carries the state after the request"); + assert_eq!(after.state, PolicyState::Invalid); + assert_eq!(after, management(&store)); + assert_eq!(held(&store), None); + assert_eq!(storage.writes(), 1); +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §replacement +#[tokio::test] +async fn written_document_the_broker_holds_is_replaced_whatever_failed_after_the_write() { + let storage = FileDouble::holding(Some(&document("corp-baseline", 3))); + let store = store(&storage); + let expected = management(&store).store_token; + let sent = document("corp-baseline", 4); + storage.fail_next_write(Fault::FailsAfterWrite); + + let outcome = replace(&store, &expected, &sent).await; + + assert_eq!(code(&outcome), "Replaced"); + assert_eq!(management(&store).document.as_deref(), Some(sent.as_str())); + assert_eq!(held(&store), Some(("corp-baseline".to_owned(), 4))); +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §replacement +#[tokio::test] +async fn only_one_of_two_replacements_with_the_same_store_token_succeeds() { + let storage = FileDouble::holding(Some(&document("corp-baseline", 3))); + let store = store(&storage); + let expected = management(&store).store_token; + let first = document("corp-baseline", 4); + let second = document("corp-baseline", 5); + + let (first_outcome, second_outcome) = + tokio::join!(replace(&store, &expected, &first), replace(&store, &expected, &second)); + + let mut codes = [code(&first_outcome), code(&second_outcome)]; + codes.sort_unstable(); + assert_eq!(codes, ["Replaced", "StaleStoreToken"]); + assert_eq!(storage.writes(), 1); +} + +// oracle: mutant a 1.x management write replaces a policy file in format 2.x +#[tokio::test] +async fn format_1_write_never_replaces_a_format_2_file() { + let files = [ + ("valid document", document("corp-baseline", 3)), + ("invalid document", document_with_unknown_key("corp-baseline", 3)), + ]; + let operations = [ + PolicyReplacementOperation::Repair, + PolicyReplacementOperation::Create, + PolicyReplacementOperation::Update, + PolicyReplacementOperation::ReplaceIdentity, + ]; + + for (name, text) in files { + for operation in operations { + let storage = FileDouble::holding(Some(&text)); + let store = store(&storage); + + let result = store.replace_for_tests(format_1_request(&store, operation)).await; + + assert!(result.is_err(), "{name}, {operation:?}"); + assert_eq!( + storage.content(), + Some(text.clone().into_bytes()), + "{name}, {operation:?}" + ); + } + } +} + +// oracle: mutant a replacement of the 2.0 encoding leaves no terminal event, or one of another kind +#[tokio::test] +async fn replacement_outcome_is_audited_once() { + let storage = FileDouble::holding(Some(&document("corp-baseline", 3))); + let store = store(&storage); + let expected = management(&store).store_token; + + let (refused_audit, refused) = recording_audit(); + store + .replace_document(&expected, &document("corp-baseline", 3), refused_audit) + .await + .expect("the policy path is one a state carries"); + let (accepted_audit, accepted) = recording_audit(); + store + .replace_document(&expected, &document("corp-baseline", 4), accepted_audit) + .await + .expect("the policy path is one a state carries"); + + let codes = |recorder: &crate::audit::tests::Recorder| { + recorder + .events() + .iter() + .map(|entry| entry.event_code) + .collect::>() + }; + assert_eq!( + codes(&refused), + [ + Some(agent_sysevent_codes::POLICY_WRITE_ATTEMPTED), + Some(agent_sysevent_codes::POLICY_CHANGE_FAILED) + ] + ); + assert_eq!( + codes(&accepted), + [ + Some(agent_sysevent_codes::POLICY_WRITE_ATTEMPTED), + Some(agent_sysevent_codes::POLICY_CHANGE_SUCCEEDED) + ] + ); +} + +// oracle: mutant a 2.x policy an administrator wrote and the broker accepted is audited as a rejected change +#[tokio::test(flavor = "current_thread")] +async fn accepted_document_written_by_someone_else_is_audited_as_applied() { + let storage = FileDouble::holding(Some(&document("corp-baseline", 3))); + let store = store(&storage); + crate::audit::tests::take_events(); + + storage.set_content(document("corp-baseline", 4).as_bytes()); + store.reload_from_disk(ReloadCause::ExternalChange).await; + + let codes = crate::audit::tests::take_events() + .iter() + .map(|entry| entry.event_code) + .collect::>(); + assert_eq!(codes, [Some(agent_sysevent_codes::POLICY_EXTERNAL_CHANGE_APPLIED)]); +} diff --git a/crates/now-package-broker/src/policy_store/format_1.rs b/crates/now-package-broker/src/policy_store/format_1.rs new file mode 100644 index 000000000..df1429d2f --- /dev/null +++ b/crates/now-package-broker/src/policy_store/format_1.rs @@ -0,0 +1,27 @@ +//! Where a policy in format 1.x becomes a 2.x document. +//! +//! The store reads a converted document exactly as it reads the text of a 2.x policy file, so a conversion only has to +//! produce that text. + +use now_policy::PolicyDocument; + +/// A 2.x document that gives every request the outcome the 1.x policy it was converted from gives it. +pub(super) struct Conversion { + /// The text of the 2.x document. + pub document: String, + /// What the conversion reports about how the document differs from the 1.x policy without changing an outcome. + pub differences: Vec, +} + +/// The refusal of a 1.x policy that has no exact 2.x equivalent. +pub(super) struct Refused; + +/// Converts a 1.x policy to a 2.x document, or refuses it. +pub(super) type Converter = fn(&PolicyDocument) -> Result; + +/// Converts a 1.x policy to a 2.x document. +/// +/// No conversion is defined, so every 1.x policy is refused. +pub(super) fn convert(_policy: &PolicyDocument) -> Result { + Err(Refused) +} diff --git a/crates/now-package-broker/src/policy_store/mod.rs b/crates/now-package-broker/src/policy_store/mod.rs index eae85bbe1..3a2758b89 100644 --- a/crates/now-package-broker/src/policy_store/mod.rs +++ b/crates/now-package-broker/src/policy_store/mod.rs @@ -5,15 +5,23 @@ use std::path::{Path, PathBuf}; use std::sync::{Arc, RwLock}; +use anyhow::Context as _; use chrono::Utc; use now_policy::PolicyDocument; use now_policy_api::{ API_VERSION_STR, ErrorCode, ErrorResponse, ErrorResponseKind, InvalidPolicyDiagnostics, PolicyConfigurationSource, PolicyConflictHandling, PolicyManagementSnapshot, PolicyManagementState, PolicyReadOnlyReason, PolicyReplacementOperation, PolicyReplacementRequest, PolicyStoreToken, PolicyValidationResult, - PolicyWriteCapability, ServerContext, Transport, + PolicyWriteCapability, ServerContext, Transport, v2, }; +use self::document::{DocumentObservation, DocumentState, DocumentView, FileContent}; +use crate::v2::policy::AcceptedPolicy; + +mod document; +#[cfg(test)] +mod document_tests; +mod format_1; mod receipt; mod validation; mod windows; @@ -47,6 +55,14 @@ trait PolicyStorage: Send + Sync { observation: &mut Observation, bytes: &[u8], ) -> Result; + /// Writes `bytes`, the text of a 2.x policy document, as the whole policy file, only while the file is as + /// `observation` saw it, and returns the observation of what the file then holds. + fn write_document( + &self, + configured_path: &Path, + observation: &mut Observation, + bytes: &[u8], + ) -> Result; } struct FilePolicyStorage { @@ -110,6 +126,44 @@ impl PolicyStorage for FilePolicyStorage { )?; self.authoritative_reobserve(configured_path, bytes) } + + // UNTESTED: a missing file is created without ever replacing one that appeared since, any other file is replaced + // through the handle its observation retained, and the returned observation is read after the write. + // No test runs it, because writing needs a directory secured for the broker. + // When changing it, check the three against how `create` and `replace` write a 1.x policy. + fn write_document( + &self, + configured_path: &Path, + observation: &mut Observation, + bytes: &[u8], + ) -> Result { + let hosting_dir = observation + .hosting_dir + .as_ref() + .context("observation retained no hosting directory") + .map_err(WriteFailure::PrePublication)?; + if matches!(observation.document.content, FileContent::Missing) { + windows::atomic_create_document( + hosting_dir, + &observation.fingerprint, + &observation.canonical_path, + bytes, + )?; + } else { + windows::atomic_replace_document( + hosting_dir, + observation.retained_target.take(), + &observation.fingerprint, + &observation.canonical_path, + bytes, + )?; + } + Ok(windows::observe( + PolicyConfigurationSource::ConfiguredPath, + configured_path, + &self.probe_cache, + )) + } } impl FilePolicyStorage { @@ -152,6 +206,8 @@ struct Snapshot { configured_path: PathBuf, store_token: PolicyStoreToken, fingerprint: DiskFingerprint, + /// What the same observation holds for the 2.0 endpoints. + document: DocumentView, } #[derive(Clone, Copy, PartialEq, Eq)] @@ -168,13 +224,35 @@ pub struct ReplaceSuccess { pub management: PolicyManagementSnapshot, } +/// The outcome of a policy replacement of the 2.0 encoding, in the order the wire contract decides them. +/// +/// An outcome carries the policy management state after the request when its response does. +#[derive(Debug)] +pub enum DocumentReplacement { + StaleStoreToken(v2::PolicyManagement), + PolicyNotWritable(v2::PolicyManagement), + /// The document is not valid, for these errors, of which there is at least one. + InvalidPolicy(Vec), + RevisionNotHigher(v2::PolicyManagement), + PersistenceFailed, + ActivationFailed(v2::PolicyManagement), + Replaced(v2::PolicyManagement), +} + pub struct PolicyStore { configured_path: PathBuf, source: PolicyConfigurationSource, snapshot: RwLock>, writer: tokio::sync::Mutex, + /// Whether the store watches the policy file for changes, which is when `writer` holds [`Monitoring::Available`]. + /// + /// Written only while `writer` is locked, and kept apart from it so reading the management state never waits for + /// a write. + watched: std::sync::atomic::AtomicBool, storage: Arc, receipt_key: receipt::ReceiptKey, + /// Converts the policy of a 1.x policy file for the 2.0 endpoints. + converter: format_1::Converter, } impl PolicyStore { @@ -190,6 +268,15 @@ impl PolicyStore { configured_path: Option, storage: Arc, monitoring: Monitoring, + ) -> Arc { + Self::load_with_converter(configured_path, storage, monitoring, format_1::convert) + } + + fn load_with_converter( + configured_path: Option, + storage: Arc, + monitoring: Monitoring, + converter: format_1::Converter, ) -> Arc { let (configured_path, source) = match configured_path { Some(path) => (path, PolicyConfigurationSource::ConfiguredPath), @@ -199,14 +286,16 @@ impl PolicyStore { ), }; let observation = storage.observe(source, &configured_path); - let snapshot = Arc::new(snapshot_from_observation(observation, random_store_token())); + let snapshot = Arc::new(snapshot_from_observation(observation, random_store_token(), converter)); Arc::new(Self { configured_path, source, snapshot: RwLock::new(snapshot), writer: tokio::sync::Mutex::new(monitoring), + watched: std::sync::atomic::AtomicBool::new(monitoring == Monitoring::Available), storage, receipt_key: receipt::ReceiptKey::generate(), + converter, }) } @@ -223,6 +312,30 @@ impl PolicyStore { management_from_snapshot(&snapshot, self.source) } + /// Returns the accepted policy the 2.0 endpoints evaluate requests against, which the store holds exactly when + /// the state of [`Self::policy_management`] is `Active`. + pub fn accepted_policy(&self) -> Option> { + self.snapshot().document.accepted().cloned() + } + + /// Returns the policy management state the 2.0 endpoints report. + /// + /// Fails when the path of the policy file is empty or longer than the wire contract lets a path be, because no + /// policy management state can carry it. + pub fn policy_management(&self) -> Result { + self.management_of(&self.snapshot()) + } + + fn management_of(&self, snapshot: &Snapshot) -> Result { + let path = v2::PolicyPath::parse(&snapshot.configured_path.display().to_string())?; + let store_token = v2::StoreToken::parse(snapshot.store_token.as_ref())?; + Ok(snapshot.document.management( + path, + store_token, + self.watched.load(std::sync::atomic::Ordering::Acquire), + )) + } + fn observe_storage(&self, retain_for_write: bool) -> (PathBuf, Observation) { let path = self.configured_path.clone(); let observation = if retain_for_write { @@ -270,12 +383,14 @@ impl PolicyStore { let (_, observation) = self.observe_storage(false); let management = self.publish_external_observation(observation); *monitoring = Monitoring::Available; + self.watched.store(true, std::sync::atomic::Ordering::Release); management } pub(crate) async fn mark_watcher_unavailable(&self) { let mut monitoring = self.writer.lock().await; *monitoring = Monitoring::Unavailable; + self.watched.store(false, std::sync::atomic::Ordering::Release); let previous = self.snapshot(); let observation = Observation { state: PolicyManagementState::Invalid, @@ -292,6 +407,10 @@ impl PolicyStore { fingerprint: windows::unavailable_fingerprint(previous.configured_path.clone()), hosting_dir: None, retained_target: None, + document: DocumentObservation::of_storage_failure( + validation::DiskFailureReason::WatcherUnavailable, + Some(PolicyReadOnlyReason::ManagementDisabled), + ), }; self.publish_observation(observation); } @@ -521,6 +640,7 @@ impl PolicyStore { configured_path: persisted.canonical_path, store_token: token, fingerprint: persisted.fingerprint, + document: self.format_1_view(&persisted.policy, &bytes, persisted.read_only_reason), }); *self.snapshot.write().expect("policy store snapshot lock poisoned") = snapshot; @@ -541,16 +661,172 @@ impl PolicyStore { }) } + /// Replaces the policy file with `document`, the text of a 2.x policy document, when `expected_store_token` is the + /// current store token. + /// + /// Fails when the outcome carries a policy management state and [`Self::policy_management`] fails. + #[cfg_attr( + not(test), + expect(dead_code, reason = "no endpoint of the 2.0 encoding replaces the policy yet") + )] + pub(crate) async fn replace_document( + &self, + expected_store_token: &v2::StoreToken, + document: &str, + audit: crate::audit::WriteAudit, + ) -> Result { + use crate::audit::{DocumentWrite, FailureReason}; + + let monitoring = self.writer.lock().await; + let previous = self.snapshot(); + + if *monitoring != Monitoring::Available { + // The store does not rely on a file it does not watch, so the published state is the current one. + let management = self.management_of(&previous)?; + let write = if matches!(previous.document.state, DocumentState::Missing) { + DocumentWrite::Create + } else { + DocumentWrite::Change + }; + if management.store_token != *expected_store_token { + audit.document_failed_at(&previous.configured_path, write, FailureReason::StaleStoreToken); + return Ok(DocumentReplacement::StaleStoreToken(management)); + } + audit.document_failed_at(&previous.configured_path, write, FailureReason::MonitoringUnavailable); + return Ok(DocumentReplacement::PolicyNotWritable(management)); + } + + let (write_configured_path, mut observation) = self.observe_storage(true); + let write = if matches!(observation.document.content, FileContent::Missing) { + DocumentWrite::Create + } else { + DocumentWrite::Change + }; + let path = observation.canonical_path.clone(); + + if token_for(&previous, &observation.fingerprint).as_ref() != expected_store_token.as_str() { + self.publish_external_observation(observation); + audit.document_failed_at(&path, write, FailureReason::StaleStoreToken); + return Ok(DocumentReplacement::StaleStoreToken(self.policy_management()?)); + } + + if observation.document.read_only_reason.is_some() { + self.publish_observation(observation); + audit.document_failed_at(&path, write, FailureReason::PathNotWritable); + return Ok(DocumentReplacement::PolicyNotWritable(self.policy_management()?)); + } + + let candidate = match AcceptedPolicy::from_bytes(document.as_bytes()) { + Ok(candidate) => candidate, + Err(errors) => { + audit.document_failed_at(&path, write, FailureReason::InvalidPolicy); + return Ok(DocumentReplacement::InvalidPolicy(errors)); + } + }; + + // The observation has the fingerprint of the published state, so the policy that state holds is the one the + // file holds now. + let held = previous.document.accepted(); + if held.is_some_and(|held| held.refuses_revision_of(&candidate)) { + audit.document_failed_at(&path, write, FailureReason::RevisionConflict); + return Ok(DocumentReplacement::RevisionNotHigher(self.management_of(&previous)?)); + } + + let written = self + .storage + .write_document(&write_configured_path, &mut observation, document.as_bytes()); + let reobserved = match written { + Ok(reobserved) => reobserved, + Err(failure @ (WriteFailure::PrePublication(_) | WriteFailure::ConcurrentChange(_))) => { + let (error, unchanged_reason) = match failure { + WriteFailure::ConcurrentChange(error) => (error, FailureReason::ConditionalPublicationFailed), + WriteFailure::PrePublication(error) | WriteFailure::PostPublication(error) => { + (error, FailureReason::PersistenceFailed) + } + }; + tracing::warn!(error = format!("{error:#}"), "Policy document persistence failed"); + // Nothing was published, so a file that differs from the observation was changed by someone else, + // and the store token the request expected is no longer the current one. + let (_, current) = self.observe_storage(false); + if current.fingerprint != observation.fingerprint { + let path = current.canonical_path.clone(); + self.publish_external_observation(current); + audit.document_failed_at(&path, write, FailureReason::StaleStoreToken); + return Ok(DocumentReplacement::StaleStoreToken(self.policy_management()?)); + } + audit.document_failed_at(&path, write, unchanged_reason); + return Ok(DocumentReplacement::PersistenceFailed); + } + Err(WriteFailure::PostPublication(error)) => { + tracing::warn!( + error = format!("{error:#}"), + "Published policy document failed verification" + ); + // What the file holds now decides the outcome, whatever failed after the publication. + self.observe_storage(false).1 + } + }; + + let path = reobserved.canonical_path.clone(); + let holds_document = matches!( + &reobserved.document.content, + FileContent::Accepted(accepted) if accepted.document() == document + ); + if !holds_document { + // The file no longer holds the document this request published, or the store cannot rely on it, so what it + // holds instead is published as any other change of the file. + self.publish_external_observation(reobserved); + audit.document_failed_at(&path, write, FailureReason::ActivationFailed); + return Ok(DocumentReplacement::ActivationFailed(self.policy_management()?)); + } + + // The file changed, so its store token does, even when a storage gives the new file the fingerprint of the old. + let snapshot = Arc::new(snapshot_from_observation( + reobserved, + random_store_token(), + self.converter, + )); + *self.snapshot.write().expect("policy store snapshot lock poisoned") = snapshot; + + audit.document_succeeded_at( + &path, + held.map(|held| (held.id(), held.revision().get())), + candidate.id(), + candidate.revision().get(), + write, + ); + + Ok(DocumentReplacement::Replaced(self.policy_management()?)) + } + + /// Builds the 2.0 view of a 1.x policy the store holds, from the bytes of its file. + fn format_1_view( + &self, + policy: &PolicyDocument, + bytes: &[u8], + read_only_reason: Option, + ) -> DocumentView { + DocumentView::from_observation( + DocumentObservation { + content: FileContent::Format1(String::from_utf8_lossy(bytes).into_owned()), + read_only_reason: document::read_only_reason(read_only_reason), + }, + Some(policy), + self.converter, + ) + } + fn publish_observation(&self, observation: Observation) -> PolicyManagementSnapshot { let previous = self.snapshot(); if previous.fingerprint == observation.fingerprint && previous.write_capability == observation.write_capability && previous.read_only_reason == observation.read_only_reason + && previous.document.read_only_reason == observation.document.read_only_reason { return management_from_snapshot(&previous, self.source); } let token = token_for(&previous, &observation.fingerprint); - let snapshot = Arc::new(snapshot_from_observation(observation, token)); + let snapshot = Arc::new(snapshot_from_observation(observation, token, self.converter)); let management = management_from_snapshot(&snapshot, self.source); *self.snapshot.write().expect("policy store snapshot lock poisoned") = snapshot; management @@ -566,7 +842,14 @@ impl PolicyStore { crate::audit::external_change_applied(path, &policy.metadata.id.0, policy.metadata.revision); } (PolicyManagementState::Missing | PolicyManagementState::Invalid, _) => { - crate::audit::external_change_rejected(path, management.state); + // A file the 1.x reader refuses is still an applied change when it holds the accepted policy of + // the 2.0 endpoints. + match self.accepted_policy() { + Some(accepted) => { + crate::audit::external_change_applied(path, accepted.id(), accepted.revision().get()); + } + None => crate::audit::external_change_rejected(path, management.state), + } } (PolicyManagementState::Active, None) => { crate::audit::external_change_rejected(path, PolicyManagementState::Invalid); @@ -597,13 +880,14 @@ impl PolicyStore { let fingerprint = DiskFingerprint::test_active(&bytes, 1, 1, 1, 1); let snapshot = Arc::new(Snapshot { state: PolicyManagementState::Active, - policy: Some(policy), invalid_diagnostics: None, write_capability: PolicyWriteCapability::Writable, read_only_reason: None, configured_path: previous.configured_path.clone(), store_token: token_for(&previous, &fingerprint), fingerprint, + document: self.format_1_view(&policy, &bytes, None), + policy: Some(policy), }); *self.snapshot.write().expect("policy store snapshot lock poisoned") = snapshot; } @@ -642,8 +926,13 @@ fn plan_revision( } } -fn snapshot_from_observation(observation: Observation, store_token: PolicyStoreToken) -> Snapshot { +fn snapshot_from_observation( + observation: Observation, + store_token: PolicyStoreToken, + converter: format_1::Converter, +) -> Snapshot { Snapshot { + document: DocumentView::from_observation(observation.document, observation.policy.as_ref(), converter), state: observation.state, policy: observation.policy.map(Arc::new), invalid_diagnostics: observation.invalid_diagnostics, @@ -848,6 +1137,17 @@ impl PolicyStorage for TestStorage { .map_err(WriteFailure::ConcurrentChange)?; self.persist(observation, bytes) } + + fn write_document( + &self, + _configured_path: &Path, + _observation: &mut Observation, + _bytes: &[u8], + ) -> Result { + Err(WriteFailure::PrePublication(anyhow::anyhow!( + "this storage double only holds 1.x policies" + ))) + } } #[cfg(test)] @@ -922,6 +1222,19 @@ fn test_observation(policy: Option, invalid: bool, marker: u8) - .as_ref() .map(|policy| serde_json::to_vec(policy).expect("test policy serializes")) .unwrap_or_default(); + let document = match state { + PolicyManagementState::Active => DocumentObservation { + content: FileContent::Format1(String::from_utf8_lossy(&bytes).into_owned()), + read_only_reason: None, + }, + PolicyManagementState::Missing => DocumentObservation { + content: FileContent::Missing, + read_only_reason: None, + }, + PolicyManagementState::Invalid => { + DocumentObservation::of_storage_failure(validation::DiskFailureReason::MalformedContent, None) + } + }; let fingerprint = match state { PolicyManagementState::Active => DiskFingerprint::test_active(&bytes, marker.into(), 1, 1, 1), PolicyManagementState::Missing => DiskFingerprint::test_missing(marker.into(), 1), @@ -946,6 +1259,7 @@ fn test_observation(policy: Option, invalid: bool, marker: u8) - windows::test_security_digest(1), )), retained_target: None, + document, } } @@ -965,6 +1279,10 @@ fn clone_observation(observation: &Observation) -> Observation { windows::test_security_digest(1), )), retained_target: None, + document: DocumentObservation { + content: observation.document.content.clone(), + read_only_reason: observation.document.read_only_reason, + }, } } diff --git a/crates/now-package-broker/src/policy_store/windows.rs b/crates/now-package-broker/src/policy_store/windows.rs index a7b9d2a90..ed4535614 100644 --- a/crates/now-package-broker/src/policy_store/windows.rs +++ b/crates/now-package-broker/src/policy_store/windows.rs @@ -44,7 +44,9 @@ use windows::Win32::Storage::FileSystem::{ use windows::Win32::Storage::FileSystem::{MOVEFILE_REPLACE_EXISTING, MoveFileExW}; use crate::policy_security::{self, FileIdentity}; +use crate::policy_store::document::{self, DocumentObservation, FileContent}; use crate::policy_store::validation; +use crate::v2::policy::{self as policy_2, AcceptedPolicy}; /// Base file name for the policy file (a fixed name inside its dedicated directory). pub(super) const POLICY_FILE_NAME: &str = "package-broker-policy.json"; @@ -1053,6 +1055,67 @@ pub(super) fn test_security_digest(generation: u32) -> [u8; 32] { sha256_digest(&generation.to_le_bytes()) } +/// Observes `content` as the policy file of a fake storage, exactly as the content of a real file is read. +/// +/// `target_generation` stands in for the identity of the file, and `read_only` makes the storage refuse writes. +#[cfg(test)] +pub(super) fn test_file_observation( + content: &[u8], + target_generation: u32, + read_only: Option<(PolicyWriteCapability, PolicyReadOnlyReason)>, +) -> DiskObservation { + let (write_capability, read_only_reason) = match read_only { + Some((capability, reason)) => (capability, Some(reason)), + None => (PolicyWriteCapability::Writable, None), + }; + observation_from_parts( + Path::new(r"C:\policy.json"), + content, + VerifiedIdentity { + parent: test_identity(1), + dir_security_digest: test_security_digest(1), + ancestor_security_digest: test_security_digest(1), + target: test_identity(target_generation), + security_digest: test_security_digest(1), + }, + write_capability, + read_only_reason, + read_only.is_none().then(test_hosting_directory), + None, + ) +} + +/// Observes a fake storage that holds no policy file. +#[cfg(test)] +pub(super) fn test_missing_file_observation( + read_only: Option<(PolicyWriteCapability, PolicyReadOnlyReason)>, +) -> DiskObservation { + let (write_capability, read_only_reason) = match read_only { + Some((capability, reason)) => (capability, Some(reason)), + None => (PolicyWriteCapability::Writable, None), + }; + DiskObservation { + state: PolicyManagementState::Missing, + policy: None, + invalid_diagnostics: None, + fingerprint: DiskFingerprint::test_missing(1, 1), + write_capability, + read_only_reason, + canonical_path: PathBuf::from(r"C:\policy.json"), + hosting_dir: read_only.is_none().then(test_hosting_directory), + retained_target: None, + document: DocumentObservation { + content: FileContent::Missing, + read_only_reason: document::read_only_reason(read_only_reason), + }, + } +} + +#[cfg(test)] +fn test_hosting_directory() -> VerifiedHostingDirectory { + VerifiedHostingDirectory::for_fake_storage(PathBuf::from(r"C:\"), test_identity(1), test_security_digest(1)) +} + pub(super) fn sha256_digest(bytes: &[u8]) -> [u8; 32] { let mut hasher = Sha256::new(); hasher.update(bytes); @@ -1167,6 +1230,8 @@ pub(super) struct DiskObservation { pub hosting_dir: Option, /// Exact target handle retained by write observations. pub retained_target: Option, + /// What the same file holds for the 2.0 endpoints. + pub document: DocumentObservation, } /// Context accumulated while observation fails partway through, for building the most @@ -1536,6 +1601,10 @@ fn observe_impl( canonical_path, hosting_dir, retained_target: None, + document: DocumentObservation { + content: FileContent::Missing, + read_only_reason: document::read_only_reason(base_read_only_reason), + }, }; } Err(error) => { @@ -1801,8 +1870,29 @@ fn observation_from_parts( let content_digest = sha256_digest(content); + let document_read_only_reason = document::read_only_reason(read_only_reason); + let (accepted, is_format_2) = match AcceptedPolicy::from_bytes(content) { + Ok(policy) => (FileContent::Accepted(std::sync::Arc::new(policy)), true), + Err(errors) => (FileContent::Invalid(errors), policy_2::is_format_2(content)), + }; + // What the 2.0 endpoints read from a file the 1.x reader does not accept. + let unread_by_format_1 = DocumentObservation { + content: accepted, + read_only_reason: document_read_only_reason, + }; + // A file in format 2.x belongs to the 2.0 endpoints, whether or not it is valid. + // The 1.x reader reports it as invalid, and a 1.x write would otherwise repair it by overwriting it. + let (write_capability, read_only_reason) = if is_format_2 && write_capability == PolicyWriteCapability::Writable { + ( + PolicyWriteCapability::Unsupported, + Some(PolicyReadOnlyReason::UnsupportedFormat), + ) + } else { + (write_capability, read_only_reason) + }; + let mut retained_target = retained_target; - let mut invalid_with = |reason: validation::DiskFailureReason, hosting_dir| DiskObservation { + let mut invalid_with = |reason: validation::DiskFailureReason, hosting_dir, document| DiskObservation { state: PolicyManagementState::Invalid, policy: None, invalid_diagnostics: Some(InvalidPolicyDiagnostics { @@ -1824,6 +1914,7 @@ fn observation_from_parts( canonical_path: path.to_owned(), hosting_dir, retained_target: retained_target.take(), + document, }; let policy = match serde_json::from_slice::(content) { @@ -1834,7 +1925,11 @@ fn observation_from_parts( // and could otherwise leak content fragments to any authenticated (but not // necessarily elevated) caller of `GET /v1/policy/management`. tracing::warn!(%parse_error, "Configured policy file content failed to parse"); - return invalid_with(validation::DiskFailureReason::MalformedContent, hosting_dir); + return invalid_with( + validation::DiskFailureReason::MalformedContent, + hosting_dir, + unread_by_format_1, + ); } }; @@ -1848,7 +1943,11 @@ fn observation_from_parts( findings = ?committed_validation.findings, "Configured policy file failed authoritative semantic validation" ); - return invalid_with(validation::DiskFailureReason::FailedSemanticValidation, hosting_dir); + return invalid_with( + validation::DiskFailureReason::FailedSemanticValidation, + hosting_dir, + unread_by_format_1, + ); } DiskObservation { @@ -1868,6 +1967,11 @@ fn observation_from_parts( canonical_path: path.to_owned(), hosting_dir, retained_target, + document: DocumentObservation { + // The 1.x reader accepted the bytes, so they are UTF-8 and the text is theirs exactly. + content: FileContent::Format1(String::from_utf8_lossy(content).into_owned()), + read_only_reason: document_read_only_reason, + }, } } @@ -1894,6 +1998,10 @@ fn observe_leaf_under_unverifiable_directory( canonical_path: configured_path.to_owned(), hosting_dir: None, retained_target: None, + document: DocumentObservation { + content: FileContent::Missing, + read_only_reason: document::read_only_reason(Some(read_only_reason)), + }, }, Ok(_) | Err(_) => invalid_observation( configured_path, @@ -1937,6 +2045,7 @@ fn invalid_observation( canonical_path: path.to_owned(), hosting_dir: None, retained_target: None, + document: DocumentObservation::of_storage_failure(reason, read_only_reason), } } @@ -1984,13 +2093,64 @@ pub(super) fn atomic_replace( final_path: &Path, bytes: &[u8], ) -> Result { + replace_verified( + hosting_dir, + observed_target, + expected_fingerprint, + final_path, + bytes, + |published| verify_persisted_handle(hosting_dir, published, final_path, bytes), + ) +} + +/// Conditionally persists `bytes`, the text of a 2.x policy document, as [`atomic_replace`] persists a 1.x policy. +/// +/// The published file is verified to hold exactly `bytes`. +/// Whether they are a valid document is for the caller's next observation to tell. +// +// UNTESTED: this publication goes through the same transaction as `atomic_replace`, so a file that changed since the +// observation is never written over and an interruption stays recoverable. +// No test runs it, because it needs a directory secured for the broker. +// When changing it, check that it still differs from `atomic_replace` only in how the published file is verified. +pub(super) fn atomic_replace_document( + hosting_dir: &VerifiedHostingDirectory, + observed_target: Option, + expected_fingerprint: &DiskFingerprint, + final_path: &Path, + bytes: &[u8], +) -> Result<(), WriteFailure> { + replace_verified( + hosting_dir, + observed_target, + expected_fingerprint, + final_path, + bytes, + |published| verify_published_bytes(hosting_dir, published, final_path, bytes).map(drop), + ) +} + +fn replace_verified( + hosting_dir: &VerifiedHostingDirectory, + observed_target: Option, + expected_fingerprint: &DiskFingerprint, + final_path: &Path, + bytes: &[u8], + verify_published: impl FnOnce(&File) -> anyhow::Result, +) -> Result { let observed_target = observed_target .context("replacement observation did not retain the target handle") .map_err(WriteFailure::ConcurrentChange)?; verify_replacement_evidence(hosting_dir, &observed_target, expected_fingerprint) .map_err(WriteFailure::ConcurrentChange)?; - conditional_replace(hosting_dir, observed_target, expected_fingerprint, final_path, bytes) + conditional_replace( + hosting_dir, + observed_target, + expected_fingerprint, + final_path, + bytes, + verify_published, + ) } fn verify_replacement_evidence( @@ -2161,13 +2321,14 @@ impl TransactionMarker { } } -fn conditional_replace( +fn conditional_replace( hosting_dir: &VerifiedHostingDirectory, observed_target: RetainedPolicyFile, expected_fingerprint: &DiskFingerprint, final_path: &Path, bytes: &[u8], -) -> Result { + verify_published: impl FnOnce(&File) -> anyhow::Result, +) -> Result { use std::io::Write as _; let dir_handle = hosting_dir @@ -2262,8 +2423,7 @@ fn conditional_replace( || Ok(()), )?; - let persisted = - verify_persisted_handle(hosting_dir, &temp_file, final_path, bytes).map_err(WriteFailure::PostPublication)?; + let persisted = verify_published(&temp_file).map_err(WriteFailure::PostPublication)?; delete_file_handle(observed_target.handle()).map_err(WriteFailure::PostPublication)?; drop(observed_target); delete_file_handle(&marker_file).map_err(WriteFailure::PostPublication)?; @@ -2963,6 +3123,14 @@ fn verify_recovery_final( ) .context("transaction final policy is not the prepared replacement")?; let content = read_file_from_start(file)?; + // UNTESTED: a replacement that is a valid 2.x document is recovered like one that is a valid 1.x policy. + // Otherwise an interruption between publishing a 2.x document and deleting the transaction marker leaves remnants + // that fail every later observation. + // No test runs it, because preparing the transaction needs a directory secured for the broker. + // When changing it, check that both formats still end the recovery as a published replacement. + if policy_2::validate(&content).is_empty() { + return Ok(RecoveryFinalState::PublishedReplacement); + } let policy = serde_json::from_slice::(&content) .context("transaction final replacement is not a policy document")?; let validation = validation::validate_committed_policy(&policy); @@ -3072,6 +3240,37 @@ pub(super) fn atomic_create( final_path: &Path, bytes: &[u8], ) -> Result { + create_verified(hosting_dir, expected_fingerprint, final_path, bytes, |published| { + verify_persisted_handle(hosting_dir, published, final_path, bytes) + }) +} + +/// Atomically persists `bytes`, the text of a 2.x policy document, as [`atomic_create`] persists a 1.x policy. +/// +/// The published file is verified to hold exactly `bytes`. +/// Whether they are a valid document is for the caller's next observation to tell. +// +// UNTESTED: this publication never overwrites an existing destination, exactly as `atomic_create`. +// No test runs it, because it needs a directory secured for the broker. +// When changing it, check that it still differs from `atomic_create` only in how the published file is verified. +pub(super) fn atomic_create_document( + hosting_dir: &VerifiedHostingDirectory, + expected_fingerprint: &DiskFingerprint, + final_path: &Path, + bytes: &[u8], +) -> Result<(), WriteFailure> { + create_verified(hosting_dir, expected_fingerprint, final_path, bytes, |published| { + verify_published_bytes(hosting_dir, published, final_path, bytes).map(drop) + }) +} + +fn create_verified( + hosting_dir: &VerifiedHostingDirectory, + expected_fingerprint: &DiskFingerprint, + final_path: &Path, + bytes: &[u8], + verify_published: impl FnOnce(&File) -> anyhow::Result, +) -> Result { use std::io::Write as _; verify_directory_evidence(hosting_dir, expected_fingerprint).map_err(WriteFailure::ConcurrentChange)?; @@ -3116,7 +3315,7 @@ pub(super) fn atomic_create( (failure, _) => failure, }); } - verify_persisted_handle(hosting_dir, &temp_file, final_path, bytes).map_err(WriteFailure::PostPublication) + verify_published(&temp_file).map_err(WriteFailure::PostPublication) } fn publish_created_file( @@ -3148,6 +3347,36 @@ fn verify_persisted_handle( final_path: &Path, expected_bytes: &[u8], ) -> anyhow::Result { + let fingerprint = verify_published_bytes(hosting_dir, final_file, final_path, expected_bytes)?; + + let policy = serde_json::from_slice::(expected_bytes) + .context("failed to reparse the freshly persisted policy file")?; + + let committed_validation = validation::validate_committed_policy(&policy); + ensure!( + committed_validation.is_valid, + "freshly persisted policy file failed authoritative semantic validation: {:?}", + committed_validation.findings + ); + + Ok(PersistedPolicy { + policy, + fingerprint, + write_capability: PolicyWriteCapability::Writable, + read_only_reason: None, + canonical_path: final_path.to_owned(), + }) +} + +/// Verifies the published handle, directory, ancestor chain and exact bytes, whatever policy format the bytes are in. +/// +/// Returns the fingerprint an observation gives the file when it holds a policy the 1.x reader accepts. +fn verify_published_bytes( + hosting_dir: &VerifiedHostingDirectory, + final_file: &File, + final_path: &Path, + expected_bytes: &[u8], +) -> anyhow::Result { let dir_security_digest = hosting_dir .verify_unchanged() .context("held policy directory changed during replacement")?; @@ -3176,31 +3405,15 @@ fn verify_persisted_handle( bail!("persisted policy file content does not match what was written"); } - let policy = serde_json::from_slice::(&persisted) - .context("failed to reparse the freshly persisted policy file")?; - - let committed_validation = validation::validate_committed_policy(&policy); - ensure!( - committed_validation.is_valid, - "freshly persisted policy file failed authoritative semantic validation: {:?}", - committed_validation.findings - ); - let content_digest = sha256_digest(&persisted); - Ok(PersistedPolicy { - policy, - fingerprint: DiskFingerprint::Active { - parent, - target, - content_digest, - security_digest, - dir_security_digest, - ancestor_security_digest, - }, - write_capability: PolicyWriteCapability::Writable, - read_only_reason: None, - canonical_path: final_path.to_owned(), + Ok(DiskFingerprint::Active { + parent, + target, + content_digest, + security_digest, + dir_security_digest, + ancestor_security_digest, }) } diff --git a/crates/now-package-broker/src/v2/policy.rs b/crates/now-package-broker/src/v2/policy.rs index 288a17541..c956dc6a8 100644 --- a/crates/now-package-broker/src/v2/policy.rs +++ b/crates/now-package-broker/src/v2/policy.rs @@ -9,6 +9,9 @@ use now_policy_eval::{Decision, Elevation, Outcome, Policy, Request}; /// The UTF-8 byte order mark, one of which a reader ignores at the start of a document. const BYTE_ORDER_MARK: char = '\u{FEFF}'; +/// The `PolicyFormatVersion` of a document in format 2.x. +const FORMAT_2_VERSION: &str = "2.0.0"; + /// A valid 2.x policy document, as the broker holds it once it accepted it. /// /// The policy keeps the text it was read from, so the broker can evaluate requests against the document and report its identity without reading it again. @@ -119,6 +122,21 @@ pub fn validate(bytes: &[u8]) -> Vec { } } +/// Returns whether `bytes` hold a document in format 2.x, valid or not. +/// +/// A document is in format 2.x when its `PolicyFormatVersion` is `"2.0.0"`, so bytes that are not a JSON object with +/// that member are not, whatever else they hold. +pub fn is_format_2(bytes: &[u8]) -> bool { + let json = bytes + .strip_prefix(BYTE_ORDER_MARK.encode_utf8(&mut [0; 4]).as_bytes()) + .unwrap_or(bytes); + + serde_json::from_slice::(json) + .ok() + .and_then(|value| Some(value.get("PolicyFormatVersion")?.as_str()? == FORMAT_2_VERSION)) + .unwrap_or(false) +} + /// Returns whether the broker refuses to run `request` although `decision`, its decision, allows it. /// /// The broker never runs a `Pre` or `Post` command with administrator rights. @@ -260,6 +278,44 @@ pub(crate) mod tests { assert_eq!(policy.revision().get(), 2); } + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.policy.md §format-version + #[test] + fn document_is_in_format_2_exactly_when_its_format_version_says_so() { + let cases = [ + ("valid document", document("corp-baseline", 1), true), + ( + "document with a defect elsewhere", + document_with("corp-baseline", 1, "[]", r#""Extra": 1,"#), + true, + ), + ( + "document after a byte order mark", + format!("\u{FEFF}{}", document("corp-baseline", 1)), + true, + ), + ( + "earlier format version", + document("corp-baseline", 1).replace("2.0.0", "1.0.0"), + false, + ), + ( + "format version that is not a string", + document("corp-baseline", 1).replace(r#""2.0.0""#, "2"), + false, + ), + ( + "no format version", + r#"{ "Metadata": { "Id": "corp-baseline" } }"#.to_owned(), + false, + ), + ("not JSON", "{".to_owned(), false), + ]; + + for (name, text, expected) in cases { + assert_eq!(is_format_2(text.as_bytes()), expected, "{name}"); + } + } + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §validation #[test] fn valid_document_has_no_errors() { @@ -270,16 +326,8 @@ pub(crate) mod tests { #[test] fn document_with_one_defect_reports_that_error() { let cases = [ - ( - "not JSON", - b"{".to_vec(), - error(PolicyErrorCode::MalformedDocument, ""), - ), - ( - "not UTF-8", - vec![0xFF], - error(PolicyErrorCode::MalformedDocument, ""), - ), + ("not JSON", b"{".to_vec(), error(PolicyErrorCode::MalformedDocument, "")), + ("not UTF-8", vec![0xFF], error(PolicyErrorCode::MalformedDocument, "")), ( "earlier format version", document("corp-baseline", 1).replace("2.0.0", "1.0.0").into_bytes(), @@ -298,7 +346,7 @@ pub(crate) mod tests { ]; for (name, bytes, expected) in cases { - assert_eq!(validate(&bytes), [expected.clone()], "{name}"); + assert_eq!(validate(&bytes), std::slice::from_ref(&expected), "{name}"); assert_eq!( AcceptedPolicy::from_bytes(&bytes).expect_err(name), [expected], @@ -361,8 +409,7 @@ pub(crate) mod tests { fn evaluation_time_after_year_9999_gets_no_decision() { let time = Utc.with_ymd_and_hms(10000, 1, 1, 0, 0, 0).single().expect("valid time"); - let result = - accepted(&document("corp-baseline", 1)).evaluate(&request(Elevation::NonElevated, false), time); + let result = accepted(&document("corp-baseline", 1)).evaluate(&request(Elevation::NonElevated, false), time); assert_eq!(result, Err(EvaluationError::TimeOutOfRange)); } @@ -373,7 +420,9 @@ pub(crate) mod tests { let policy = accepted(&document_with("corp-baseline", 1, ALLOW_PRE_POST_COMMANDS, "")); let request = request(Elevation::Elevated, true); - let decision = policy.evaluate(&request, evaluation_time()).expect("well-formed request"); + let decision = policy + .evaluate(&request, evaluation_time()) + .expect("well-formed request"); assert_eq!(decision.outcome, Outcome::Allow, "the policy grants the opt-in"); assert!(!decision.audited); @@ -386,9 +435,15 @@ pub(crate) mod tests { let policy = accepted(&document_with("corp-baseline", 1, "[]", AUDIT_MODE)); let request = request(Elevation::Elevated, true); - let decision = policy.evaluate(&request, evaluation_time()).expect("well-formed request"); + let decision = policy + .evaluate(&request, evaluation_time()) + .expect("well-formed request"); - assert_eq!(decision.outcome, Outcome::Allow, "audit mode lets the denied request run"); + assert_eq!( + decision.outcome, + Outcome::Allow, + "audit mode lets the denied request run" + ); assert!(decision.audited); assert!(is_not_runnable(&request, &decision)); } @@ -399,7 +454,9 @@ pub(crate) mod tests { let policy = accepted(&document("corp-baseline", 1)); let request = request(Elevation::Elevated, true); - let decision = policy.evaluate(&request, evaluation_time()).expect("well-formed request"); + let decision = policy + .evaluate(&request, evaluation_time()) + .expect("well-formed request"); assert_eq!(decision.outcome, Outcome::Deny, "no rule allows the request"); assert!(!is_not_runnable(&request, &decision)); @@ -416,7 +473,9 @@ pub(crate) mod tests { (Elevation::NonElevated, false), ] { let request = request(elevation, pre_post_commands); - let decision = policy.evaluate(&request, evaluation_time()).expect("well-formed request"); + let decision = policy + .evaluate(&request, evaluation_time()) + .expect("well-formed request"); assert_eq!(decision.outcome, Outcome::Allow, "{elevation:?} {pre_post_commands}"); assert!( From 35b2a6ac8ec75d1968c0a3628eba1be08006454d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Tue, 1 Dec 2026 05:45:58 +0900 Subject: [PATCH 06/16] fix(agent): tell a 2.x policy file by the errors of its own reader A second, lenient JSON parser decided whether the policy file is in format 2.x, and it disagreed with the reader of that format. A 2.x document holding a number that parser refuses was not told as 2.x, so a 1.x repair could overwrite it, and a document repeating `PolicyFormatVersion` was told as 2.x although the reader calls it malformed. The store now tells the format from the errors the reader reports, in the code that exists only for the 1.x endpoints. A replacement of the 2.0 encoding fails before it records an attempt or touches the file when no policy management state can carry the policy path, so nothing can fail once the outcome is decided. Its success audit record names the 1.x policy it replaced when the file held one, because the 1.x endpoints enforced that policy. The storage observes the written file with the source the store reads the path from. A 1.x policy refused for the 2.0 endpoints is logged once for each change of the file, so the refusal is reported beyond the policy management state. Tests now pin how each storage failure and read-only reason maps to the `InvalidReason` and `ReadOnlyReason` of the wire contract, and that recovery accepts a published replacement that is a 2.x document. The content check of a recovered replacement is its own function, so a test reaches it without a file secured for the broker, which only an elevated process can create. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- .../src/policy_store/document.rs | 26 +- .../src/policy_store/document_tests.rs | 330 +++++++++++++++++- .../src/policy_store/format_1.rs | 27 +- .../src/policy_store/mod.rs | 75 ++-- .../src/policy_store/windows.rs | 113 +++++- crates/now-package-broker/src/v2/policy.rs | 56 --- 6 files changed, 518 insertions(+), 109 deletions(-) diff --git a/crates/now-package-broker/src/policy_store/document.rs b/crates/now-package-broker/src/policy_store/document.rs index 28bd483f5..91347469c 100644 --- a/crates/now-package-broker/src/policy_store/document.rs +++ b/crates/now-package-broker/src/policy_store/document.rs @@ -51,6 +51,11 @@ impl DocumentObservation { DiskFailureReason::WatcherUnavailable => FileContent::Unusable(InvalidReason::MonitoringUnavailable), // The 1.x reader gives these reasons for content it read, and content is classified where it is read. // A storage failure that carries one anyway has no content to report errors for. + // + // UNTESTED: the storage never fails with these reasons before it read the content, so no test decides what + // this arm reports, and the wire contract has no `InvalidReason` for it. + // A state from this arm would tell a client the file is an invalid document without having read it. + // When the storage starts failing with one of these reasons, give it its own arm and a contract value. DiskFailureReason::MalformedContent | DiskFailureReason::FailedSemanticValidation => { FileContent::Invalid(vec![PolicyError { code: PolicyErrorCode::MalformedDocument, @@ -71,10 +76,12 @@ pub(super) fn read_only_reason(reason: Option) -> Option ReadOnlyReason::MonitoringUnavailable, - // The storage never gives `PathNotConfigured`, because the broker always reads a path. - PolicyReadOnlyReason::PathNotConfigured | PolicyReadOnlyReason::UnsupportedFormat => { - ReadOnlyReason::UnsupportedPath - } + PolicyReadOnlyReason::UnsupportedFormat => ReadOnlyReason::UnsupportedPath, + // UNTESTED: the storage never gives `PathNotConfigured`, because the broker always reads a path, so no test + // decides what this arm reports, and the wire contract has no `ReadOnlyReason` for a broker without a path. + // A state from this arm would name a reason that is not why the file cannot be written. + // When the storage starts giving this reason, decide its contract value before relying on this arm. + PolicyReadOnlyReason::PathNotConfigured => ReadOnlyReason::UnsupportedPath, PolicyReadOnlyReason::UnsafePath => ReadOnlyReason::UnsafePath, PolicyReadOnlyReason::InsufficientPermissions => ReadOnlyReason::InsufficientPermissions, PolicyReadOnlyReason::UnsupportedFileSystem => ReadOnlyReason::UnsupportedFileSystem, @@ -184,8 +191,17 @@ impl DocumentView { /// Converts a 1.x policy and reads the result as the text of a 2.x policy file. /// /// A conversion whose document is not valid is no exact conversion, so it is refused like any other. +/// A refusal is reported here, where the store builds the view of a file it observed anew, so it is logged once for +/// each change of the file and never when the state is only read. fn converted(policy: &PolicyDocument, convert: Converter) -> Option { - let Conversion { document, differences } = convert(policy).ok()?; + let Ok(Conversion { document, differences }) = convert(policy) else { + tracing::warn!( + policy_id = %policy.metadata.id.0, + revision = policy.metadata.revision, + "Refused the 1.x policy file for the 2.0 endpoints, because it has no exact conversion" + ); + return None; + }; let accepted = match AcceptedPolicy::from_bytes(document.as_bytes()) { Ok(accepted) => accepted, diff --git a/crates/now-package-broker/src/policy_store/document_tests.rs b/crates/now-package-broker/src/policy_store/document_tests.rs index 2c8794e4f..b899ec53d 100644 --- a/crates/now-package-broker/src/policy_store/document_tests.rs +++ b/crates/now-package-broker/src/policy_store/document_tests.rs @@ -7,6 +7,7 @@ use now_policy_api::v2::{InvalidReason, PolicyError, PolicyErrorCode, PolicyMana use now_policy_api::{PolicyConflictHandling, PolicyReplacementRequestKind}; use win_api_wrappers::identity::sid::Sid; +use super::validation::DiskFailureReason; use super::*; use crate::v2::policy::tests::document; @@ -34,26 +35,42 @@ struct FakeFile { struct FileDouble { file: parking_lot::Mutex, read_only: Option<(PolicyWriteCapability, PolicyReadOnlyReason)>, + /// Why the storage fails on the file before it reads any content, when it does. + failure: Option, fault: parking_lot::Mutex>, writes: AtomicUsize, } impl FileDouble { fn holding(content: Option<&str>) -> Arc { - Self::new(content, None) + Self::new(content, None, None) } fn read_only(content: &str, capability: PolicyWriteCapability, reason: PolicyReadOnlyReason) -> Arc { - Self::new(Some(content), Some((capability, reason))) + Self::new(Some(content), Some((capability, reason)), None) } - fn new(content: Option<&str>, read_only: Option<(PolicyWriteCapability, PolicyReadOnlyReason)>) -> Arc { + /// A storage that fails on its file for `failure` and gives `reason` for not writing it. + fn failing( + failure: DiskFailureReason, + capability: PolicyWriteCapability, + reason: PolicyReadOnlyReason, + ) -> Arc { + Self::new(None, Some((capability, reason)), Some(failure)) + } + + fn new( + content: Option<&str>, + read_only: Option<(PolicyWriteCapability, PolicyReadOnlyReason)>, + failure: Option, + ) -> Arc { Arc::new(Self { file: parking_lot::Mutex::new(FakeFile { content: content.map(|content| content.as_bytes().to_vec()), generation: 1, }), read_only, + failure, fault: parking_lot::Mutex::new(None), writes: AtomicUsize::new(0), }) @@ -85,6 +102,9 @@ impl FileDouble { } fn observation(&self) -> Observation { + if let Some(failure) = self.failure { + return windows::test_failed_observation(failure, self.read_only); + } let file = self.file.lock(); match &file.content { Some(content) => windows::test_file_observation(content, file.generation, self.read_only), @@ -143,6 +163,7 @@ impl PolicyStorage for FileDouble { fn write_document( &self, + _source: PolicyConfigurationSource, _configured_path: &Path, observation: &mut Observation, bytes: &[u8], @@ -201,7 +222,7 @@ fn management(store: &PolicyStore) -> PolicyManagement { async fn replace(store: &PolicyStore, expected: &v2::StoreToken, document: &str) -> DocumentReplacement { store - .replace_document(expected, document, crate::audit::tests::noop()) + .replace_document(expected, document, crate::audit::tests::noop) .await .expect("the policy path is one a state carries") } @@ -283,6 +304,20 @@ fn format_1_request(store: &PolicyStore, operation: PolicyReplacementOperation) } } +/// The text of a document in format 2.x whose `Revision` is a number larger than any a JSON library need represent. +fn document_with_huge_revision() -> String { + document("corp-baseline", 3).replacen(r#""Revision": 3"#, r#""Revision": 1e999"#, 1) +} + +/// The text of a file that repeats `PolicyFormatVersion`, first as format 1.x and then as format 2.x. +fn document_with_two_format_versions() -> String { + document("corp-baseline", 3).replacen( + r#""PolicyFormatVersion""#, + "\"PolicyFormatVersion\": \"1.0.0\",\n \"PolicyFormatVersion\"", + 1, + ) +} + /// Converts a 1.x policy to a 2.x document that keeps its identity, and reports one difference. fn convert_keeping_identity(policy: &PolicyDocument) -> Result { Ok(format_1::Conversion { @@ -299,6 +334,47 @@ fn convert_to_invalid_document(_policy: &PolicyDocument) -> Result); + +impl tracing::Subscriber for ViewWarnings { + fn enabled(&self, _metadata: &tracing::Metadata<'_>) -> bool { + true + } + + fn new_span(&self, _attributes: &tracing::span::Attributes<'_>) -> tracing::span::Id { + tracing::span::Id::from_u64(1) + } + + fn record(&self, _span: &tracing::span::Id, _values: &tracing::span::Record<'_>) {} + + fn record_follows_from(&self, _span: &tracing::span::Id, _follows: &tracing::span::Id) {} + + fn event(&self, event: &tracing::Event<'_>) { + let metadata = event.metadata(); + if *metadata.level() == tracing::Level::WARN && metadata.target().ends_with("policy_store::document") { + self.0.fetch_add(1, Ordering::SeqCst); + } + } + + fn enter(&self, _span: &tracing::span::Id) {} + + fn exit(&self, _span: &tracing::span::Id) {} +} + +/// Counts, until the returned guard drops, the warnings the current thread logs while it builds the 2.0 view. +/// +/// While the process has a single subscriber, `tracing` asks only the thread that first reaches a log statement +/// whether its subscriber listens to it, and keeps the answer for every thread. +/// Tests on other threads reach the same statements without a subscriber, so the guard holds a second one: with more +/// than one, `tracing` asks each of them. +fn count_view_warnings() -> (Arc, impl Sized) { + let warnings = Arc::new(AtomicUsize::new(0)); + let counting = tracing::subscriber::set_default(ViewWarnings(Arc::clone(&warnings))); + let second = tracing::Dispatch::new(tracing::subscriber::NoSubscriber::default()); + (warnings, (counting, second)) +} + fn recording_audit() -> (crate::audit::WriteAudit, Arc) { let sid = Sid::from_well_known(::windows::Win32::Security::WinLocalSystemSid, None).expect("resolve SYSTEM SID"); crate::audit::tests::begin(&sid, Path::new(r"C:\client.exe"), Path::new(POLICY_PATH)) @@ -375,6 +451,128 @@ fn missing_file_is_missing() { assert_eq!(held(&store), None); } +#[tokio::test] +async fn refused_format_1_policy_is_reported_when_the_file_is_read_and_when_it_changes() { + let (warnings, _counting) = count_view_warnings(); + let storage = FileDouble::holding(Some(&format_1_text("legacy", 2))); + + let store = store(&storage); + // oracle: intent Devolutions/now-libraries@77307f5106d9:policies/INTENT.legacy.md §format-1 + assert_eq!(warnings.load(Ordering::SeqCst), 1); + + management(&store); + store.accepted_policy(); + store.reload_from_disk(ReloadCause::ExternalChange).await; + // oracle: mutant the refusal is reported again each time the state is read or the unchanged file is observed + assert_eq!(warnings.load(Ordering::SeqCst), 1); + + storage.set_content(format_1_text("legacy", 3).as_bytes()); + store.reload_from_disk(ReloadCause::ExternalChange).await; + // oracle: intent Devolutions/now-libraries@77307f5106d9:policies/INTENT.legacy.md §format-1 + assert_eq!(warnings.load(Ordering::SeqCst), 2); +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §management-state +#[test] +fn file_the_storage_fails_on_is_invalid_for_the_reason_of_the_failure() { + let cases = [ + ( + "file that cannot be opened or read", + DiskFailureReason::Unreadable, + (PolicyWriteCapability::ReadOnly, PolicyReadOnlyReason::UnsafePath), + InvalidReason::ReadFailed, + ), + ( + "location that fails the storage security checks", + DiskFailureReason::InsecureStorage, + (PolicyWriteCapability::ReadOnly, PolicyReadOnlyReason::UnsafePath), + InvalidReason::InsecureStorage, + ), + ( + "path with an extension the broker does not read", + DiskFailureReason::UnsupportedFormat, + ( + PolicyWriteCapability::Unsupported, + PolicyReadOnlyReason::UnsupportedFormat, + ), + InvalidReason::UnsupportedPath, + ), + ]; + + for (name, failure, (capability, read_only_reason), expected) in cases { + let store = store(&FileDouble::failing(failure, capability, read_only_reason)); + + let management = management(&store); + + assert_eq!(management.state, PolicyState::Invalid, "{name}"); + assert_eq!(management.invalid_reason, Some(expected), "{name}"); + assert_eq!(management.errors, None, "{name}"); + assert_eq!(management.document, None, "{name}"); + assert_eq!(held(&store), None, "{name}"); + } +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §management-state +#[test] +fn file_the_storage_does_not_write_is_read_only_for_the_reason_of_the_storage() { + let cases = [ + ( + "path with an extension the broker does not write", + ( + PolicyWriteCapability::Unsupported, + PolicyReadOnlyReason::UnsupportedFormat, + ), + ReadOnlyReason::UnsupportedPath, + ), + ( + "location that fails the storage security checks", + (PolicyWriteCapability::ReadOnly, PolicyReadOnlyReason::UnsafePath), + ReadOnlyReason::UnsafePath, + ), + ( + "directory the broker lacks the permissions to write", + ( + PolicyWriteCapability::ReadOnly, + PolicyReadOnlyReason::InsufficientPermissions, + ), + ReadOnlyReason::InsufficientPermissions, + ), + ( + "file system that cannot replace a file atomically", + ( + PolicyWriteCapability::Unsupported, + PolicyReadOnlyReason::UnsupportedFileSystem, + ), + ReadOnlyReason::UnsupportedFileSystem, + ), + ]; + + for (name, (capability, read_only_reason), expected) in cases { + let text = document("corp-baseline", 3); + let store = store(&FileDouble::read_only(&text, capability, read_only_reason)); + + let management = management(&store); + + assert_eq!(management.read_only_reason, Some(expected), "{name}"); + assert_eq!(management.state, PolicyState::Active, "{name}"); + } +} + +// oracle: mutant a storage that stopped managing the file gives the 2.0 endpoints no reason, or another one +#[test] +fn file_the_storage_stopped_managing_is_read_only_as_unwatched() { + let store = store(&FileDouble::read_only( + &document("corp-baseline", 3), + PolicyWriteCapability::ReadOnly, + PolicyReadOnlyReason::ManagementDisabled, + )); + + assert_eq!( + management(&store).read_only_reason, + Some(ReadOnlyReason::MonitoringUnavailable) + ); +} + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §management-state #[test] fn converted_format_1_policy_is_active_with_the_text_of_its_file() { @@ -503,7 +701,7 @@ async fn read_only_policy_is_not_writable_whatever_the_document() { assert_eq!(code(&outcome), "PolicyNotWritable"); let after = state_after(outcome).expect("an unwritable replacement carries the state after the request"); - assert!(after.read_only_reason.is_some()); + assert_eq!(after.read_only_reason, Some(ReadOnlyReason::UnsafePath)); assert_eq!(after.document.as_deref(), Some(text.as_str())); assert_eq!(storage.writes(), 0); } @@ -704,12 +902,75 @@ async fn only_one_of_two_replacements_with_the_same_store_token_succeeds() { assert_eq!(storage.writes(), 1); } +// oracle: mutant the earlier endpoints may write a file in format 2.x, or lose a file whose format cannot be told +#[test] +fn earlier_endpoints_write_no_file_the_reader_tells_is_in_format_2() { + let unwritable = ( + PolicyWriteCapability::Unsupported, + Some(PolicyReadOnlyReason::UnsupportedFormat), + ); + let writable = (PolicyWriteCapability::Writable, None); + let cases = [ + ("valid document", document("corp-baseline", 3), unwritable), + ( + "valid document after a byte order mark", + format!("\u{FEFF}{}", document("corp-baseline", 3)), + unwritable, + ), + ( + "document with an unknown key", + document_with_unknown_key("corp-baseline", 3), + unwritable, + ), + ( + "document with a number of any magnitude", + document_with_huge_revision(), + unwritable, + ), + ( + "file that repeats its format version", + document_with_two_format_versions(), + writable, + ), + ( + "file with another format version", + document("corp-baseline", 3).replace("2.0.0", "1.0.0"), + writable, + ), + ( + "file with a format version that is no string", + document("corp-baseline", 3).replace(r#""2.0.0""#, "2"), + writable, + ), + ( + "file without a format version", + r#"{ "Metadata": {} }"#.to_owned(), + writable, + ), + ("file that is not JSON", "{".to_owned(), writable), + ("file that is no object", r#"["2.0.0"]"#.to_owned(), writable), + ]; + + for (name, text, expected) in cases { + let store = store(&FileDouble::holding(Some(&text))); + + let management = store.management_snapshot(); + + assert_eq!( + (management.write_capability, management.read_only_reason), + expected, + "{name}" + ); + } +} + // oracle: mutant a 1.x management write replaces a policy file in format 2.x #[tokio::test] async fn format_1_write_never_replaces_a_format_2_file() { let files = [ ("valid document", document("corp-baseline", 3)), ("invalid document", document_with_unknown_key("corp-baseline", 3)), + ("document with a number of any magnitude", document_with_huge_revision()), ]; let operations = [ PolicyReplacementOperation::Repair, @@ -744,12 +1005,12 @@ async fn replacement_outcome_is_audited_once() { let (refused_audit, refused) = recording_audit(); store - .replace_document(&expected, &document("corp-baseline", 3), refused_audit) + .replace_document(&expected, &document("corp-baseline", 3), || refused_audit) .await .expect("the policy path is one a state carries"); let (accepted_audit, accepted) = recording_audit(); store - .replace_document(&expected, &document("corp-baseline", 4), accepted_audit) + .replace_document(&expected, &document("corp-baseline", 4), || accepted_audit) .await .expect("the policy path is one a state carries"); @@ -776,6 +1037,61 @@ async fn replacement_outcome_is_audited_once() { ); } +#[tokio::test] +async fn replacement_for_a_path_no_state_carries_fails_before_it_is_audited() { + let storage = FileDouble::holding(Some(&document("corp-baseline", 3))); + let store = PolicyStore::load_with_storage( + Some(PathBuf::new()), + Arc::clone(&storage) as Arc, + Monitoring::Available, + ); + let expected = v2::StoreToken::parse("any-token").expect("valid store token"); + let audited = std::cell::Cell::new(false); + + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §management-state + assert!(store.policy_management().is_err()); + + let outcome = store + .replace_document(&expected, &document("corp-baseline", 4), || { + audited.set(true); + crate::audit::tests::noop() + }) + .await; + + // oracle: mutant a replacement no response can report the outcome of is audited as attempted, or writes the file + assert!(outcome.is_err()); + assert!(!audited.get()); + assert_eq!(storage.writes(), 0); +} + +// oracle: mutant a replacement of a policy the earlier endpoints enforce records no replaced policy +#[tokio::test] +async fn replacement_of_a_format_1_policy_is_audited_with_the_identity_it_replaced() { + let storage = FileDouble::holding(Some(&format_1_text("legacy", 2))); + let store = store(&storage); + let expected = management(&store).store_token; + + let (audit, recorder) = recording_audit(); + let outcome = store + .replace_document(&expected, &document("corp-baseline", 1), || audit) + .await + .expect("the policy path is one a state carries"); + + assert_eq!(code(&outcome), "Replaced"); + let events = recorder.events(); + let field = |name: &str| { + events[1] + .fields + .iter() + .find(|(field, _)| field == name) + .map(|(_, value)| value.as_str()) + }; + assert_eq!(field("old_id"), Some("legacy")); + assert_eq!(field("old_revision"), Some("2")); + assert_eq!(field("new_id"), Some("corp-baseline")); + assert_eq!(field("new_revision"), Some("1")); +} + // oracle: mutant a 2.x policy an administrator wrote and the broker accepted is audited as a rejected change #[tokio::test(flavor = "current_thread")] async fn accepted_document_written_by_someone_else_is_audited_as_applied() { diff --git a/crates/now-package-broker/src/policy_store/format_1.rs b/crates/now-package-broker/src/policy_store/format_1.rs index df1429d2f..eead4caa4 100644 --- a/crates/now-package-broker/src/policy_store/format_1.rs +++ b/crates/now-package-broker/src/policy_store/format_1.rs @@ -1,9 +1,10 @@ -//! Where a policy in format 1.x becomes a 2.x document. +//! What the store does only because policies in format 1.x and their endpoints exist. //! //! The store reads a converted document exactly as it reads the text of a 2.x policy file, so a conversion only has to //! produce that text. use now_policy::PolicyDocument; +use now_policy_api::v2::{PolicyError, PolicyErrorCode}; /// A 2.x document that gives every request the outcome the 1.x policy it was converted from gives it. pub(super) struct Conversion { @@ -25,3 +26,27 @@ pub(super) type Converter = fn(&PolicyDocument) -> Result; pub(super) fn convert(_policy: &PolicyDocument) -> Result { Err(Refused) } + +/// Returns whether a policy file is in format 2.x, valid or not, from the errors the 2.x reader reports for it. +/// +/// The 1.x management endpoints never write such a file: their reader reports it as invalid, and repairing it would +/// overwrite a policy that belongs to the 2.0 endpoints. +/// +/// A file is in format 2.x when its `PolicyFormatVersion` is `"2.0.0"`. +/// The reader reports nothing else when the document is too large, is malformed, repeats a key, or has no or another +/// format version, so a file with none of these errors has that format version. +/// A file with one of them stays writable for the 1.x endpoints, because the reader does not tell its format. +pub(super) fn is_format_2(errors: &[PolicyError]) -> bool { + !errors.iter().any(|error| match error.code { + PolicyErrorCode::DocumentTooLarge + | PolicyErrorCode::MalformedDocument + | PolicyErrorCode::DuplicateKey + | PolicyErrorCode::UnsupportedFormatVersion => true, + PolicyErrorCode::MissingKey => error.pointer == "/PolicyFormatVersion", + PolicyErrorCode::UnknownKey + | PolicyErrorCode::ConflictingKeys + | PolicyErrorCode::WrongType + | PolicyErrorCode::InvalidValue + | PolicyErrorCode::DuplicateRuleId => false, + }) +} diff --git a/crates/now-package-broker/src/policy_store/mod.rs b/crates/now-package-broker/src/policy_store/mod.rs index 3a2758b89..6670c7306 100644 --- a/crates/now-package-broker/src/policy_store/mod.rs +++ b/crates/now-package-broker/src/policy_store/mod.rs @@ -59,6 +59,7 @@ trait PolicyStorage: Send + Sync { /// `observation` saw it, and returns the observation of what the file then holds. fn write_document( &self, + source: PolicyConfigurationSource, configured_path: &Path, observation: &mut Observation, bytes: &[u8], @@ -133,6 +134,7 @@ impl PolicyStorage for FilePolicyStorage { // When changing it, check the three against how `create` and `replace` write a 1.x policy. fn write_document( &self, + source: PolicyConfigurationSource, configured_path: &Path, observation: &mut Observation, bytes: &[u8], @@ -158,11 +160,7 @@ impl PolicyStorage for FilePolicyStorage { bytes, )?; } - Ok(windows::observe( - PolicyConfigurationSource::ConfiguredPath, - configured_path, - &self.probe_cache, - )) + Ok(windows::observe(source, configured_path, &self.probe_cache)) } } @@ -251,6 +249,8 @@ pub struct PolicyStore { watched: std::sync::atomic::AtomicBool, storage: Arc, receipt_key: receipt::ReceiptKey, + /// The path of the policy file as a policy management state carries it, or why no state can carry it. + document_path: Result, /// Converts the policy of a 1.x policy file for the 2.0 endpoints. converter: format_1::Converter, } @@ -288,6 +288,7 @@ impl PolicyStore { let observation = storage.observe(source, &configured_path); let snapshot = Arc::new(snapshot_from_observation(observation, random_store_token(), converter)); Arc::new(Self { + document_path: v2::PolicyPath::parse(&configured_path.display().to_string()), configured_path, source, snapshot: RwLock::new(snapshot), @@ -323,17 +324,19 @@ impl PolicyStore { /// Fails when the path of the policy file is empty or longer than the wire contract lets a path be, because no /// policy management state can carry it. pub fn policy_management(&self) -> Result { - self.management_of(&self.snapshot()) + Ok(self.management_of(&self.snapshot(), self.document_path.clone()?)) } - fn management_of(&self, snapshot: &Snapshot) -> Result { - let path = v2::PolicyPath::parse(&snapshot.configured_path.display().to_string())?; - let store_token = v2::StoreToken::parse(snapshot.store_token.as_ref())?; - Ok(snapshot.document.management( + fn management_of(&self, snapshot: &Snapshot, path: v2::PolicyPath) -> v2::PolicyManagement { + // The store mints every store token as a hyphenated UUID: 36 ASCII hexadecimal digits and hyphens, the first + // of them a digit. + let store_token = + v2::StoreToken::parse(snapshot.store_token.as_ref()).expect("a hyphenated UUID is a store token"); + snapshot.document.management( path, store_token, self.watched.load(std::sync::atomic::Ordering::Acquire), - )) + ) } fn observe_storage(&self, retain_for_write: bool) -> (PathBuf, Observation) { @@ -664,7 +667,10 @@ impl PolicyStore { /// Replaces the policy file with `document`, the text of a 2.x policy document, when `expected_store_token` is the /// current store token. /// - /// Fails when the outcome carries a policy management state and [`Self::policy_management`] fails. + /// `begin_audit` records the attempt and returns the audit that the outcome is recorded in. + /// + /// Fails when [`Self::policy_management`] does, before it calls `begin_audit` and before it reads or writes the + /// policy file, because most outcomes carry a policy management state. #[cfg_attr( not(test), expect(dead_code, reason = "no endpoint of the 2.0 encoding replaces the policy yet") @@ -673,16 +679,20 @@ impl PolicyStore { &self, expected_store_token: &v2::StoreToken, document: &str, - audit: crate::audit::WriteAudit, + begin_audit: impl FnOnce() -> crate::audit::WriteAudit, ) -> Result { use crate::audit::{DocumentWrite, FailureReason}; + let document_path = self.document_path.clone()?; + let management_of = |snapshot: &Snapshot| self.management_of(snapshot, document_path.clone()); + let audit = begin_audit(); + let monitoring = self.writer.lock().await; let previous = self.snapshot(); if *monitoring != Monitoring::Available { // The store does not rely on a file it does not watch, so the published state is the current one. - let management = self.management_of(&previous)?; + let management = management_of(&previous); let write = if matches!(previous.document.state, DocumentState::Missing) { DocumentWrite::Create } else { @@ -707,13 +717,13 @@ impl PolicyStore { if token_for(&previous, &observation.fingerprint).as_ref() != expected_store_token.as_str() { self.publish_external_observation(observation); audit.document_failed_at(&path, write, FailureReason::StaleStoreToken); - return Ok(DocumentReplacement::StaleStoreToken(self.policy_management()?)); + return Ok(DocumentReplacement::StaleStoreToken(management_of(&self.snapshot()))); } if observation.document.read_only_reason.is_some() { self.publish_observation(observation); audit.document_failed_at(&path, write, FailureReason::PathNotWritable); - return Ok(DocumentReplacement::PolicyNotWritable(self.policy_management()?)); + return Ok(DocumentReplacement::PolicyNotWritable(management_of(&self.snapshot()))); } let candidate = match AcceptedPolicy::from_bytes(document.as_bytes()) { @@ -729,12 +739,15 @@ impl PolicyStore { let held = previous.document.accepted(); if held.is_some_and(|held| held.refuses_revision_of(&candidate)) { audit.document_failed_at(&path, write, FailureReason::RevisionConflict); - return Ok(DocumentReplacement::RevisionNotHigher(self.management_of(&previous)?)); + return Ok(DocumentReplacement::RevisionNotHigher(management_of(&previous))); } - let written = self - .storage - .write_document(&write_configured_path, &mut observation, document.as_bytes()); + let written = self.storage.write_document( + self.source, + &write_configured_path, + &mut observation, + document.as_bytes(), + ); let reobserved = match written { Ok(reobserved) => reobserved, Err(failure @ (WriteFailure::PrePublication(_) | WriteFailure::ConcurrentChange(_))) => { @@ -752,7 +765,7 @@ impl PolicyStore { let path = current.canonical_path.clone(); self.publish_external_observation(current); audit.document_failed_at(&path, write, FailureReason::StaleStoreToken); - return Ok(DocumentReplacement::StaleStoreToken(self.policy_management()?)); + return Ok(DocumentReplacement::StaleStoreToken(management_of(&self.snapshot()))); } audit.document_failed_at(&path, write, unchanged_reason); return Ok(DocumentReplacement::PersistenceFailed); @@ -777,7 +790,7 @@ impl PolicyStore { // holds instead is published as any other change of the file. self.publish_external_observation(reobserved); audit.document_failed_at(&path, write, FailureReason::ActivationFailed); - return Ok(DocumentReplacement::ActivationFailed(self.policy_management()?)); + return Ok(DocumentReplacement::ActivationFailed(management_of(&self.snapshot()))); } // The file changed, so its store token does, even when a storage gives the new file the fingerprint of the old. @@ -788,15 +801,16 @@ impl PolicyStore { )); *self.snapshot.write().expect("policy store snapshot lock poisoned") = snapshot; - audit.document_succeeded_at( - &path, - held.map(|held| (held.id(), held.revision().get())), - candidate.id(), - candidate.revision().get(), - write, - ); + // A file the 1.x reader accepted held a policy the 1.x endpoints enforced, even when the 2.0 endpoints held none. + let replaced = held.map(|held| (held.id(), held.revision().get())).or_else(|| { + previous + .policy + .as_deref() + .map(|policy| (policy.metadata.id.0.as_str(), policy.metadata.revision)) + }); + audit.document_succeeded_at(&path, replaced, candidate.id(), candidate.revision().get(), write); - Ok(DocumentReplacement::Replaced(self.policy_management()?)) + Ok(DocumentReplacement::Replaced(management_of(&self.snapshot()))) } /// Builds the 2.0 view of a 1.x policy the store holds, from the bytes of its file. @@ -1140,6 +1154,7 @@ impl PolicyStorage for TestStorage { fn write_document( &self, + _source: PolicyConfigurationSource, _configured_path: &Path, _observation: &mut Observation, _bytes: &[u8], diff --git a/crates/now-package-broker/src/policy_store/windows.rs b/crates/now-package-broker/src/policy_store/windows.rs index ed4535614..b5cea9cc1 100644 --- a/crates/now-package-broker/src/policy_store/windows.rs +++ b/crates/now-package-broker/src/policy_store/windows.rs @@ -45,7 +45,7 @@ use windows::Win32::Storage::FileSystem::{MOVEFILE_REPLACE_EXISTING, MoveFileExW use crate::policy_security::{self, FileIdentity}; use crate::policy_store::document::{self, DocumentObservation, FileContent}; -use crate::policy_store::validation; +use crate::policy_store::{format_1, validation}; use crate::v2::policy::{self as policy_2, AcceptedPolicy}; /// Base file name for the policy file (a fixed name inside its dedicated directory). @@ -1111,6 +1111,25 @@ pub(super) fn test_missing_file_observation( } } +/// Observes a fake storage that fails on its policy file for `reason`, before it reads any content. +#[cfg(test)] +pub(super) fn test_failed_observation( + reason: validation::DiskFailureReason, + read_only: Option<(PolicyWriteCapability, PolicyReadOnlyReason)>, +) -> DiskObservation { + let (write_capability, read_only_reason) = match read_only { + Some((capability, reason)) => (capability, Some(reason)), + None => (PolicyWriteCapability::Writable, None), + }; + invalid_observation( + Path::new(r"C:\policy.json"), + reason, + InvalidContext::default(), + write_capability, + read_only_reason, + ) +} + #[cfg(test)] fn test_hosting_directory() -> VerifiedHostingDirectory { VerifiedHostingDirectory::for_fake_storage(PathBuf::from(r"C:\"), test_identity(1), test_security_digest(1)) @@ -1873,7 +1892,10 @@ fn observation_from_parts( let document_read_only_reason = document::read_only_reason(read_only_reason); let (accepted, is_format_2) = match AcceptedPolicy::from_bytes(content) { Ok(policy) => (FileContent::Accepted(std::sync::Arc::new(policy)), true), - Err(errors) => (FileContent::Invalid(errors), policy_2::is_format_2(content)), + Err(errors) => { + let is_format_2 = format_1::is_format_2(&errors); + (FileContent::Invalid(errors), is_format_2) + } }; // What the 2.0 endpoints read from a file the 1.x reader does not accept. let unread_by_format_1 = DocumentObservation { @@ -3122,23 +3144,27 @@ fn verify_recovery_final( marker.new_security_digest, ) .context("transaction final policy is not the prepared replacement")?; - let content = read_file_from_start(file)?; - // UNTESTED: a replacement that is a valid 2.x document is recovered like one that is a valid 1.x policy. + verify_replacement_content(&read_file_from_start(file)?)?; + Ok(RecoveryFinalState::PublishedReplacement) +} + +/// Checks that `content`, the bytes of a published replacement, is what a transaction publishes: a valid 2.x document +/// or a valid 1.x policy. +fn verify_replacement_content(content: &[u8]) -> anyhow::Result<()> { + // A replacement that is a valid 2.x document is recovered like one that is a valid 1.x policy. // Otherwise an interruption between publishing a 2.x document and deleting the transaction marker leaves remnants // that fail every later observation. - // No test runs it, because preparing the transaction needs a directory secured for the broker. - // When changing it, check that both formats still end the recovery as a published replacement. - if policy_2::validate(&content).is_empty() { - return Ok(RecoveryFinalState::PublishedReplacement); + if policy_2::validate(content).is_empty() { + return Ok(()); } - let policy = serde_json::from_slice::(&content) + let policy = serde_json::from_slice::(content) .context("transaction final replacement is not a policy document")?; let validation = validation::validate_committed_policy(&policy); ensure!( validation.is_valid, "transaction final replacement failed committed-policy validation" ); - Ok(RecoveryFinalState::PublishedReplacement) + Ok(()) } fn open_optional_final_policy(path: &Path) -> anyhow::Result> { @@ -4268,6 +4294,73 @@ mod tests { assert!(!marker_path.exists()); } + // oracle: mutant recovery refuses a published replacement in one of the two formats, or accepts one that is no policy + #[test] + fn published_replacement_is_a_valid_policy_of_either_format() { + let cases = [ + ( + "2.x document", + crate::v2::policy::tests::document("corp-baseline", 3).into_bytes(), + true, + ), + ("1.x policy", valid_committed_policy_bytes(), true), + ("JSON object that is no policy", b"{}".to_vec(), false), + ]; + + for (name, content, expected) in cases { + assert_eq!(verify_replacement_content(&content).is_ok(), expected, "{name}"); + } + } + + // oracle: mutant recovery refuses a published replacement that is a valid 2.x document, and keeps its remnants + #[test] + fn recovery_accepts_the_exact_prepared_document_after_genuine_rename() { + use std::io::Write as _; + + let dir = temp_dir(); + let dir_file = open_directory_no_reparse(dir.path()).unwrap(); + let final_path = dir.path().join("policy.json"); + let prepared_path = dir.path().join("prepared"); + let marker_path = dir.path().join("marker"); + let old_path = dir.path().join("old"); + let mut prepared = match create_secure_transaction_file(&prepared_path) { + Ok(file) => file, + Err(_) => return, + }; + let bytes = crate::v2::policy::tests::document("corp-baseline", 3).into_bytes(); + prepared.write_all(&bytes).unwrap(); + prepared.sync_all().unwrap(); + let marker = TransactionMarker { + id: uuid::Uuid::new_v4(), + final_leaf: "policy.json".to_owned(), + old_identity: test_identity(1), + old_content_digest: sha256_digest(b"verified-old"), + old_security_digest: test_security_digest(1), + new_identity: policy_security::file_identity(&prepared).unwrap(), + new_content_digest: sha256_digest(&bytes), + new_security_digest: policy_security::security_state_digest(&prepared).unwrap(), + }; + rename_file_handle(&prepared, &dir_file, final_path.file_name().unwrap()).unwrap(); + drop(prepared); + let marker_file = open_deletable_test_file(&marker_path, b"marker"); + let old_file = open_deletable_test_file(&old_path, b"verified-old"); + + recover_verified_transaction_with_evidence( + &dir_file, + dir.path(), + final_path.file_name().unwrap(), + &marker, + marker_file, + Some(old_file), + None, + ) + .unwrap(); + + assert_eq!(std::fs::read(&final_path).unwrap(), bytes); + assert!(!old_path.exists()); + assert!(!marker_path.exists()); + } + #[test] fn recovery_accepts_exact_warning_bearing_replacement() { use std::io::Write as _; diff --git a/crates/now-package-broker/src/v2/policy.rs b/crates/now-package-broker/src/v2/policy.rs index c956dc6a8..9b8906282 100644 --- a/crates/now-package-broker/src/v2/policy.rs +++ b/crates/now-package-broker/src/v2/policy.rs @@ -9,9 +9,6 @@ use now_policy_eval::{Decision, Elevation, Outcome, Policy, Request}; /// The UTF-8 byte order mark, one of which a reader ignores at the start of a document. const BYTE_ORDER_MARK: char = '\u{FEFF}'; -/// The `PolicyFormatVersion` of a document in format 2.x. -const FORMAT_2_VERSION: &str = "2.0.0"; - /// A valid 2.x policy document, as the broker holds it once it accepted it. /// /// The policy keeps the text it was read from, so the broker can evaluate requests against the document and report its identity without reading it again. @@ -122,21 +119,6 @@ pub fn validate(bytes: &[u8]) -> Vec { } } -/// Returns whether `bytes` hold a document in format 2.x, valid or not. -/// -/// A document is in format 2.x when its `PolicyFormatVersion` is `"2.0.0"`, so bytes that are not a JSON object with -/// that member are not, whatever else they hold. -pub fn is_format_2(bytes: &[u8]) -> bool { - let json = bytes - .strip_prefix(BYTE_ORDER_MARK.encode_utf8(&mut [0; 4]).as_bytes()) - .unwrap_or(bytes); - - serde_json::from_slice::(json) - .ok() - .and_then(|value| Some(value.get("PolicyFormatVersion")?.as_str()? == FORMAT_2_VERSION)) - .unwrap_or(false) -} - /// Returns whether the broker refuses to run `request` although `decision`, its decision, allows it. /// /// The broker never runs a `Pre` or `Post` command with administrator rights. @@ -278,44 +260,6 @@ pub(crate) mod tests { assert_eq!(policy.revision().get(), 2); } - // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.policy.md §format-version - #[test] - fn document_is_in_format_2_exactly_when_its_format_version_says_so() { - let cases = [ - ("valid document", document("corp-baseline", 1), true), - ( - "document with a defect elsewhere", - document_with("corp-baseline", 1, "[]", r#""Extra": 1,"#), - true, - ), - ( - "document after a byte order mark", - format!("\u{FEFF}{}", document("corp-baseline", 1)), - true, - ), - ( - "earlier format version", - document("corp-baseline", 1).replace("2.0.0", "1.0.0"), - false, - ), - ( - "format version that is not a string", - document("corp-baseline", 1).replace(r#""2.0.0""#, "2"), - false, - ), - ( - "no format version", - r#"{ "Metadata": { "Id": "corp-baseline" } }"#.to_owned(), - false, - ), - ("not JSON", "{".to_owned(), false), - ]; - - for (name, text, expected) in cases { - assert_eq!(is_format_2(text.as_bytes()), expected, "{name}"); - } - } - // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §validation #[test] fn valid_document_has_no_errors() { From f44f10118ba98a5361423b3376e14a9b3e79e036 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Tue, 1 Dec 2026 06:16:47 +0900 Subject: [PATCH 07/16] fix(agent): tell a 2.x policy file that repeats a key by its format version The 2.x reader reports a repeated key before it reads the format version, and reports nothing else. A file whose only `PolicyFormatVersion` is `"2.0.0"` and that repeats a key elsewhere is a 2.x file the errors of the reader cannot tell from a 1.x file that repeats a key, so a 1.x repair could overwrite a policy that belongs to the 2.0 endpoints. The rule that tells a 2.x file changes for that one case. When the reader reports a repeated key other than the format version, the top-level `PolicyFormatVersion` members of the document decide: the file is in format 2.x when there is at least one and each of them is the string `"2.0.0"`. They are read without interpreting any other value, so a number of any magnitude does not prevent it. A 1.x file that repeats a key stays repairable, and so does a file that gives its format version twice, whatever the two values. Every other case is still decided from the errors of the reader. A malformed or too large 2.x file stays writable for the 1.x endpoints, because nothing reads a format version from it. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- .../src/policy_store/document_tests.rs | 81 +++++++++++++- .../src/policy_store/format_1.rs | 104 +++++++++++++++--- .../src/policy_store/windows.rs | 2 +- 3 files changed, 162 insertions(+), 25 deletions(-) diff --git a/crates/now-package-broker/src/policy_store/document_tests.rs b/crates/now-package-broker/src/policy_store/document_tests.rs index b899ec53d..fa1d22e36 100644 --- a/crates/now-package-broker/src/policy_store/document_tests.rs +++ b/crates/now-package-broker/src/policy_store/document_tests.rs @@ -309,15 +309,30 @@ fn document_with_huge_revision() -> String { document("corp-baseline", 3).replacen(r#""Revision": 3"#, r#""Revision": 1e999"#, 1) } -/// The text of a file that repeats `PolicyFormatVersion`, first as format 1.x and then as format 2.x. -fn document_with_two_format_versions() -> String { +/// The text of a file that gives `first` and then `second` as its `PolicyFormatVersion`. +fn document_with_format_versions(first: &str, second: &str) -> String { document("corp-baseline", 3).replacen( - r#""PolicyFormatVersion""#, - "\"PolicyFormatVersion\": \"1.0.0\",\n \"PolicyFormatVersion\"", + r#""PolicyFormatVersion": "2.0.0""#, + &format!(r#""PolicyFormatVersion": "{first}", "PolicyFormatVersion": "{second}""#), 1, ) } +/// `text` with the `Publisher` of its `Metadata` written twice, so an object other than the document repeats a key. +fn repeating_its_publisher(text: &str) -> String { + text.replacen( + r#""Publisher": "Test""#, + r#""Publisher": "Test", "Publisher": "Test""#, + 1, + ) +} + +/// `text` with one more `PolicyFormatVersion`, of value `version`, as the last member of the document. +fn ending_with_format_version(text: &str, version: &str) -> String { + let end = text.rfind('}').expect("text of an object"); + format!(r#"{}, "PolicyFormatVersion": "{version}" }}"#, text[..end].trim_end()) +} + /// Converts a 1.x policy to a 2.x document that keeps its identity, and reports one difference. fn convert_keeping_identity(policy: &PolicyDocument) -> Result { Ok(format_1::Conversion { @@ -928,8 +943,58 @@ fn earlier_endpoints_write_no_file_the_reader_tells_is_in_format_2() { unwritable, ), ( - "file that repeats its format version", - document_with_two_format_versions(), + "document that repeats a key of another object", + repeating_its_publisher(&document("corp-baseline", 3)), + unwritable, + ), + ( + "document that repeats a key of another object, after a byte order mark", + format!("\u{FEFF}{}", repeating_its_publisher(&document("corp-baseline", 3))), + unwritable, + ), + ( + "document that repeats a key of another object and holds a number of any magnitude", + repeating_its_publisher(&document_with_huge_revision()), + unwritable, + ), + ( + "1.x file that repeats a key of another object", + repeating_its_publisher(&format_1_text("legacy", 2)), + writable, + ), + ( + "file that repeats a key of another object, with a format version that is no string", + repeating_its_publisher(&document("corp-baseline", 3).replace(r#""2.0.0""#, "2")), + writable, + ), + ( + "file that repeats a key of another object, without a format version", + r#"{ "Metadata": { "Publisher": "Test", "Publisher": "Test" } }"#.to_owned(), + writable, + ), + ( + "file that repeats a key of another object, then gives an earlier format version", + ending_with_format_version(&repeating_its_publisher(&document("corp-baseline", 3)), "1.0.0"), + writable, + ), + ( + "file that gives an earlier format version, then repeats a key of another object", + ending_with_format_version(&repeating_its_publisher(&format_1_text("legacy", 2)), "2.0.0"), + writable, + ), + ( + "file that gives format version 1.0.0 and then 2.0.0", + document_with_format_versions("1.0.0", "2.0.0"), + writable, + ), + ( + "file that gives format version 2.0.0 and then 1.0.0", + document_with_format_versions("2.0.0", "1.0.0"), + writable, + ), + ( + "file that gives format version 2.0.0 twice", + document_with_format_versions("2.0.0", "2.0.0"), writable, ), ( @@ -971,6 +1036,10 @@ async fn format_1_write_never_replaces_a_format_2_file() { ("valid document", document("corp-baseline", 3)), ("invalid document", document_with_unknown_key("corp-baseline", 3)), ("document with a number of any magnitude", document_with_huge_revision()), + ( + "document that repeats a key of another object", + repeating_its_publisher(&document("corp-baseline", 3)), + ), ]; let operations = [ PolicyReplacementOperation::Repair, diff --git a/crates/now-package-broker/src/policy_store/format_1.rs b/crates/now-package-broker/src/policy_store/format_1.rs index eead4caa4..4c7402d5d 100644 --- a/crates/now-package-broker/src/policy_store/format_1.rs +++ b/crates/now-package-broker/src/policy_store/format_1.rs @@ -3,8 +3,12 @@ //! The store reads a converted document exactly as it reads the text of a 2.x policy file, so a conversion only has to //! produce that text. +use std::fmt; + use now_policy::PolicyDocument; use now_policy_api::v2::{PolicyError, PolicyErrorCode}; +use serde::Deserializer as _; +use serde::de::{IgnoredAny, MapAccess, Visitor}; /// A 2.x document that gives every request the outcome the 1.x policy it was converted from gives it. pub(super) struct Conversion { @@ -27,26 +31,90 @@ pub(super) fn convert(_policy: &PolicyDocument) -> Result { Err(Refused) } -/// Returns whether a policy file is in format 2.x, valid or not, from the errors the 2.x reader reports for it. +/// The JSON Pointer of the `PolicyFormatVersion` member of a document. +const FORMAT_VERSION_POINTER: &str = "/PolicyFormatVersion"; + +/// Returns whether the policy file holding `content` is in format 2.x, valid or not, given the `errors` the 2.x reader +/// reports for it. /// /// The 1.x management endpoints never write such a file: their reader reports it as invalid, and repairing it would /// overwrite a policy that belongs to the 2.0 endpoints. /// -/// A file is in format 2.x when its `PolicyFormatVersion` is `"2.0.0"`. -/// The reader reports nothing else when the document is too large, is malformed, repeats a key, or has no or another -/// format version, so a file with none of these errors has that format version. -/// A file with one of them stays writable for the 1.x endpoints, because the reader does not tell its format. -pub(super) fn is_format_2(errors: &[PolicyError]) -> bool { - !errors.iter().any(|error| match error.code { - PolicyErrorCode::DocumentTooLarge - | PolicyErrorCode::MalformedDocument - | PolicyErrorCode::DuplicateKey - | PolicyErrorCode::UnsupportedFormatVersion => true, - PolicyErrorCode::MissingKey => error.pointer == "/PolicyFormatVersion", - PolicyErrorCode::UnknownKey - | PolicyErrorCode::ConflictingKeys - | PolicyErrorCode::WrongType - | PolicyErrorCode::InvalidValue - | PolicyErrorCode::DuplicateRuleId => false, - }) +/// A file is in format 2.x when its `PolicyFormatVersion` is `"2.0.0"`, which the reader's errors tell in every case but +/// one: +/// +/// - No error, or only errors the reader reports once it read that format version: the file is in format 2.x. +/// - `UnsupportedFormatVersion`, or `MissingKey` for the format version: it is not. +/// - `DuplicateKey` for the format version: it is not, whatever the values, so a file that gives its format version +/// twice stays repairable. +/// - `DuplicateKey` for another key: the reader stops there without reading the format version, so the top-level +/// `PolicyFormatVersion` members decide. +/// The file is in format 2.x when there is at least one and each of them is the string `"2.0.0"`. +/// A 1.x file that repeats a key therefore stays repairable. +/// - `MalformedDocument` or `DocumentTooLarge`: it is not, because nothing reads a format version from such a file. +/// A 2.x file damaged that way stays writable for the 1.x endpoints. +pub(super) fn is_format_2(content: &[u8], errors: &[PolicyError]) -> bool { + let mut repeats_another_key = false; + + for error in errors { + match error.code { + PolicyErrorCode::DocumentTooLarge + | PolicyErrorCode::MalformedDocument + | PolicyErrorCode::UnsupportedFormatVersion => return false, + PolicyErrorCode::MissingKey | PolicyErrorCode::DuplicateKey if error.pointer == FORMAT_VERSION_POINTER => { + return false; + } + PolicyErrorCode::DuplicateKey => repeats_another_key = true, + PolicyErrorCode::MissingKey + | PolicyErrorCode::UnknownKey + | PolicyErrorCode::ConflictingKeys + | PolicyErrorCode::WrongType + | PolicyErrorCode::InvalidValue + | PolicyErrorCode::DuplicateRuleId => {} + } + } + + !repeats_another_key || every_format_version_is_2(content) +} + +/// Returns whether the document in `content` has `PolicyFormatVersion` members and each of them is the string +/// `"2.0.0"`. +/// +/// Every other value is skipped without being interpreted, so a number of any magnitude does not fail the read. +/// Content that cannot be read as a JSON object has no such member. +/// What follows the object is not read, because the reader reports a repeated key only for a well-formed document. +fn every_format_version_is_2(content: &[u8]) -> bool { + // The reader ignores one leading byte order mark, so a document that has one can repeat a key. + let json = content.strip_prefix("\u{FEFF}".as_bytes()).unwrap_or(content); + + serde_json::Deserializer::from_slice(json) + .deserialize_map(FormatVersions) + .unwrap_or(false) +} + +/// Reads the `PolicyFormatVersion` members of a JSON object, repeated or not. +struct FormatVersions; + +impl<'de> Visitor<'de> for FormatVersions { + /// Whether the object has such members and each of them is the string `"2.0.0"`. + type Value = bool; + + fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str("a JSON object") + } + + fn visit_map>(self, mut map: A) -> Result { + let mut every_version_is_2 = None; + + while let Some(key) = map.next_key::()? { + if key == "PolicyFormatVersion" { + let is_2 = map.next_value::()? == "2.0.0"; + every_version_is_2 = Some(every_version_is_2.unwrap_or(true) && is_2); + } else { + map.next_value::()?; + } + } + + Ok(every_version_is_2 == Some(true)) + } } diff --git a/crates/now-package-broker/src/policy_store/windows.rs b/crates/now-package-broker/src/policy_store/windows.rs index b5cea9cc1..8498b41b0 100644 --- a/crates/now-package-broker/src/policy_store/windows.rs +++ b/crates/now-package-broker/src/policy_store/windows.rs @@ -1893,7 +1893,7 @@ fn observation_from_parts( let (accepted, is_format_2) = match AcceptedPolicy::from_bytes(content) { Ok(policy) => (FileContent::Accepted(std::sync::Arc::new(policy)), true), Err(errors) => { - let is_format_2 = format_1::is_format_2(&errors); + let is_format_2 = format_1::is_format_2(content, &errors); (FileContent::Invalid(errors), is_format_2) } }; From 907ea6bf96feb85ba4fdcac19906a9fe9f93dd02 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Tue, 1 Dec 2026 06:17:10 +0900 Subject: [PATCH 08/16] fix(agent): report a policy path of unsupported form as an unsupported path The policy management state of the 2.0 endpoints has one reason for a path whose form or extension the broker does not read or write, and keeps `InsecureStorage` and `UnsafePath` for a path or location that fails the storage security checks. A relative path, a path ending with a separator, a path with a `.` or `..` component and a path that names no file were reported with the security reasons, as the 1.x management state reports them. The 2.0 state now gives `UnsupportedPath` for both the invalid reason and the read-only reason of such a path, like a path with an extension the broker does not read. The 1.x management state is unchanged. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- .../src/policy_store/windows.rs | 46 ++++++++++++++++++- 1 file changed, 45 insertions(+), 1 deletion(-) diff --git a/crates/now-package-broker/src/policy_store/windows.rs b/crates/now-package-broker/src/policy_store/windows.rs index 8498b41b0..3575cca31 100644 --- a/crates/now-package-broker/src/policy_store/windows.rs +++ b/crates/now-package-broker/src/policy_store/windows.rs @@ -18,6 +18,7 @@ use std::path::{Path, PathBuf}; use anyhow::{Context as _, bail, ensure}; use now_policy::PolicyDocument; +use now_policy_api::v2::{InvalidReason, ReadOnlyReason}; use now_policy_api::{ API_VERSION_STR, InvalidPolicyDiagnostics, PolicyConfigurationSource, PolicyManagementState, PolicyReadOnlyReason, PolicyStoreToken, PolicyWriteCapability, @@ -1412,13 +1413,21 @@ fn observe_impl( PolicyReadOnlyReason::UnsupportedFormat, ), }; - return invalid_observation( + let mut observation = invalid_observation( configured_path, failure, InvalidContext::default(), PolicyWriteCapability::Unsupported, Some(read_only_reason), ); + // The 1.x management state reports a path of unsupported form as failing the storage security checks. + // The 2.0 management state keeps those reasons for a path or location that fails the checks, and has one + // reason for a path whose form or extension the broker does not read or write. + observation.document = DocumentObservation { + content: FileContent::Unusable(InvalidReason::UnsupportedPath), + read_only_reason: Some(ReadOnlyReason::UnsupportedPath), + }; + return observation; } let dir = configured_path.parent().unwrap_or_else(|| Path::new(".")); @@ -5004,6 +5013,41 @@ mod tests { assert_unsupported_format_is_reported_invalid_end_to_end("policy.txt"); } + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §management-state + #[test] + fn path_of_a_form_or_extension_the_broker_does_not_read_is_an_unsupported_path_for_the_2_0_endpoints() { + let paths = [ + ("relative path", r"relative\policy.json"), + ("path ending with a separator", r"C:\ProgramData\Devolutions\"), + ("path with a `.` component", r"C:\ProgramData\.\policy.json"), + ("path with a `..` component", r"C:\ProgramData\..\policy.json"), + ("path that names no file", r"C:\"), + ("path with another extension", r"C:\ProgramData\Devolutions\policy.yaml"), + ("path without an extension", r"C:\ProgramData\Devolutions\policy"), + ]; + + for (case, path) in paths { + let observation = observe( + PolicyConfigurationSource::ConfiguredPath, + Path::new(path), + &AtomicityProbeCache::new(), + ); + + assert!( + matches!( + observation.document.content, + FileContent::Unusable(InvalidReason::UnsupportedPath) + ), + "{case}" + ); + assert_eq!( + observation.document.read_only_reason, + Some(ReadOnlyReason::UnsupportedPath), + "{case}" + ); + } + } + // ─── Strict policy ancestor walk: reparse rejection (item 16) ───────────── // // Directory junctions (unlike symlinks) require no special privilege to create, so From 74ae1e82474a3ca1bff68ba91a948101acaadf3d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Tue, 1 Dec 2026 06:17:10 +0900 Subject: [PATCH 09/16] docs(agent): say what the policy store does for the 2.0 endpoints The `Path` of the 2.0 policy management state is the configured path, not the canonical path of the observation, which the 1.x management state shows. The success audit record of a replacement can name the 1.x policy the replacement took the place of. A 1.x policy refused for the 2.0 endpoints is logged each time the store builds a view, which a change of the security or the write capability of unchanged bytes also causes. The observation a document write returns is read with the configuration source of the store, a property no test checks. The test of the content check of a recovered replacement gains a 1.x policy that parses and fails validation, and compares the refusal, so each case reaches the branch it is meant for. The observation doubles of the storage tests move next to the test module, out of the production items. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- crates/now-package-broker/src/audit.rs | 3 +- .../src/policy_store/document.rs | 6 +- .../src/policy_store/mod.rs | 9 +- .../src/policy_store/windows.rs | 192 ++++++++++-------- 4 files changed, 117 insertions(+), 93 deletions(-) diff --git a/crates/now-package-broker/src/audit.rs b/crates/now-package-broker/src/audit.rs index 7099ce653..3df0b4d96 100644 --- a/crates/now-package-broker/src/audit.rs +++ b/crates/now-package-broker/src/audit.rs @@ -695,7 +695,8 @@ impl WriteAudit { /// Records that a policy replacement of the 2.0 encoding replaced the policy. /// - /// `old` is the id and revision of the accepted policy the replacement took the place of. + /// `old` is the id and revision of the policy the replacement took the place of: the accepted policy, or the 1.x + /// policy the 1.x endpoints enforced from a file the 2.0 endpoints held no accepted policy for. pub(crate) fn document_succeeded_at( &self, path: &Path, diff --git a/crates/now-package-broker/src/policy_store/document.rs b/crates/now-package-broker/src/policy_store/document.rs index 91347469c..f37a3a935 100644 --- a/crates/now-package-broker/src/policy_store/document.rs +++ b/crates/now-package-broker/src/policy_store/document.rs @@ -191,8 +191,10 @@ impl DocumentView { /// Converts a 1.x policy and reads the result as the text of a 2.x policy file. /// /// A conversion whose document is not valid is no exact conversion, so it is refused like any other. -/// A refusal is reported here, where the store builds the view of a file it observed anew, so it is logged once for -/// each change of the file and never when the state is only read. +/// A refusal is logged here, where the store builds a view: when it loads the file, and each time what it observes of +/// the file differs from what it last published, in content, identity, security, or whether the file can be written. +/// A change of security or of write capability therefore logs the refusal of unchanged bytes again. +/// Reading the state builds no view, so it logs nothing. fn converted(policy: &PolicyDocument, convert: Converter) -> Option { let Ok(Conversion { document, differences }) = convert(policy) else { tracing::warn!( diff --git a/crates/now-package-broker/src/policy_store/mod.rs b/crates/now-package-broker/src/policy_store/mod.rs index 6670c7306..b6bd1c5e9 100644 --- a/crates/now-package-broker/src/policy_store/mod.rs +++ b/crates/now-package-broker/src/policy_store/mod.rs @@ -129,9 +129,12 @@ impl PolicyStorage for FilePolicyStorage { } // UNTESTED: a missing file is created without ever replacing one that appeared since, any other file is replaced - // through the handle its observation retained, and the returned observation is read after the write. - // No test runs it, because writing needs a directory secured for the broker. - // When changing it, check the three against how `create` and `replace` write a 1.x policy. + // through the handle its observation retained, and the returned observation is read after the write, with the + // configuration source of the store, which decides how the directory of the file is verified. + // No test runs it, because writing needs a directory secured for the broker, and the storage doubles ignore the + // source. + // When changing it, check the first three against how `create` and `replace` write a 1.x policy, and that the + // source reaches `windows::observe` unchanged. fn write_document( &self, source: PolicyConfigurationSource, diff --git a/crates/now-package-broker/src/policy_store/windows.rs b/crates/now-package-broker/src/policy_store/windows.rs index 3575cca31..dabffaa5e 100644 --- a/crates/now-package-broker/src/policy_store/windows.rs +++ b/crates/now-package-broker/src/policy_store/windows.rs @@ -1056,86 +1056,6 @@ pub(super) fn test_security_digest(generation: u32) -> [u8; 32] { sha256_digest(&generation.to_le_bytes()) } -/// Observes `content` as the policy file of a fake storage, exactly as the content of a real file is read. -/// -/// `target_generation` stands in for the identity of the file, and `read_only` makes the storage refuse writes. -#[cfg(test)] -pub(super) fn test_file_observation( - content: &[u8], - target_generation: u32, - read_only: Option<(PolicyWriteCapability, PolicyReadOnlyReason)>, -) -> DiskObservation { - let (write_capability, read_only_reason) = match read_only { - Some((capability, reason)) => (capability, Some(reason)), - None => (PolicyWriteCapability::Writable, None), - }; - observation_from_parts( - Path::new(r"C:\policy.json"), - content, - VerifiedIdentity { - parent: test_identity(1), - dir_security_digest: test_security_digest(1), - ancestor_security_digest: test_security_digest(1), - target: test_identity(target_generation), - security_digest: test_security_digest(1), - }, - write_capability, - read_only_reason, - read_only.is_none().then(test_hosting_directory), - None, - ) -} - -/// Observes a fake storage that holds no policy file. -#[cfg(test)] -pub(super) fn test_missing_file_observation( - read_only: Option<(PolicyWriteCapability, PolicyReadOnlyReason)>, -) -> DiskObservation { - let (write_capability, read_only_reason) = match read_only { - Some((capability, reason)) => (capability, Some(reason)), - None => (PolicyWriteCapability::Writable, None), - }; - DiskObservation { - state: PolicyManagementState::Missing, - policy: None, - invalid_diagnostics: None, - fingerprint: DiskFingerprint::test_missing(1, 1), - write_capability, - read_only_reason, - canonical_path: PathBuf::from(r"C:\policy.json"), - hosting_dir: read_only.is_none().then(test_hosting_directory), - retained_target: None, - document: DocumentObservation { - content: FileContent::Missing, - read_only_reason: document::read_only_reason(read_only_reason), - }, - } -} - -/// Observes a fake storage that fails on its policy file for `reason`, before it reads any content. -#[cfg(test)] -pub(super) fn test_failed_observation( - reason: validation::DiskFailureReason, - read_only: Option<(PolicyWriteCapability, PolicyReadOnlyReason)>, -) -> DiskObservation { - let (write_capability, read_only_reason) = match read_only { - Some((capability, reason)) => (capability, Some(reason)), - None => (PolicyWriteCapability::Writable, None), - }; - invalid_observation( - Path::new(r"C:\policy.json"), - reason, - InvalidContext::default(), - write_capability, - read_only_reason, - ) -} - -#[cfg(test)] -fn test_hosting_directory() -> VerifiedHostingDirectory { - VerifiedHostingDirectory::for_fake_storage(PathBuf::from(r"C:\"), test_identity(1), test_security_digest(1)) -} - pub(super) fn sha256_digest(bytes: &[u8]) -> [u8; 32] { let mut hasher = Sha256::new(); hasher.update(bytes); @@ -1242,7 +1162,9 @@ pub(super) struct DiskObservation { pub read_only_reason: Option, /// Canonical path formed from the verified parent handle and exact configured `.json` leaf name; see item 22. /// Falls back to the literal configured path when the path cannot be canonicalized. - /// Trusted target access, publication, display, and watching use this path as applicable. + /// Trusted target access, publication, watching, and the path the 1.x management state shows use this path as + /// applicable. + /// The policy management state of the 2.0 endpoints carries the configured path instead. /// `PolicyStore` retains the original configured path for authoritative re-observation and security-chain validation. pub canonical_path: PathBuf, /// The hosting directory verified during this observation. @@ -3461,6 +3383,86 @@ fn move_replace(from: &Path, to: &Path) -> anyhow::Result<()> { .context("MoveFileExW replacement failed") } +/// Observes `content` as the policy file of a fake storage, exactly as the content of a real file is read. +/// +/// `target_generation` stands in for the identity of the file, and `read_only` makes the storage refuse writes. +#[cfg(test)] +pub(super) fn test_file_observation( + content: &[u8], + target_generation: u32, + read_only: Option<(PolicyWriteCapability, PolicyReadOnlyReason)>, +) -> DiskObservation { + let (write_capability, read_only_reason) = match read_only { + Some((capability, reason)) => (capability, Some(reason)), + None => (PolicyWriteCapability::Writable, None), + }; + observation_from_parts( + Path::new(r"C:\policy.json"), + content, + VerifiedIdentity { + parent: test_identity(1), + dir_security_digest: test_security_digest(1), + ancestor_security_digest: test_security_digest(1), + target: test_identity(target_generation), + security_digest: test_security_digest(1), + }, + write_capability, + read_only_reason, + read_only.is_none().then(test_hosting_directory), + None, + ) +} + +/// Observes a fake storage that holds no policy file. +#[cfg(test)] +pub(super) fn test_missing_file_observation( + read_only: Option<(PolicyWriteCapability, PolicyReadOnlyReason)>, +) -> DiskObservation { + let (write_capability, read_only_reason) = match read_only { + Some((capability, reason)) => (capability, Some(reason)), + None => (PolicyWriteCapability::Writable, None), + }; + DiskObservation { + state: PolicyManagementState::Missing, + policy: None, + invalid_diagnostics: None, + fingerprint: DiskFingerprint::test_missing(1, 1), + write_capability, + read_only_reason, + canonical_path: PathBuf::from(r"C:\policy.json"), + hosting_dir: read_only.is_none().then(test_hosting_directory), + retained_target: None, + document: DocumentObservation { + content: FileContent::Missing, + read_only_reason: document::read_only_reason(read_only_reason), + }, + } +} + +/// Observes a fake storage that fails on its policy file for `reason`, before it reads any content. +#[cfg(test)] +pub(super) fn test_failed_observation( + reason: validation::DiskFailureReason, + read_only: Option<(PolicyWriteCapability, PolicyReadOnlyReason)>, +) -> DiskObservation { + let (write_capability, read_only_reason) = match read_only { + Some((capability, reason)) => (capability, Some(reason)), + None => (PolicyWriteCapability::Writable, None), + }; + invalid_observation( + Path::new(r"C:\policy.json"), + reason, + InvalidContext::default(), + write_capability, + read_only_reason, + ) +} + +#[cfg(test)] +fn test_hosting_directory() -> VerifiedHostingDirectory { + VerifiedHostingDirectory::for_fake_storage(PathBuf::from(r"C:\"), test_identity(1), test_security_digest(1)) +} + #[cfg(test)] mod tests { #![allow(clippy::unwrap_used)] @@ -4303,21 +4305,37 @@ mod tests { assert!(!marker_path.exists()); } - // oracle: mutant recovery refuses a published replacement in one of the two formats, or accepts one that is no policy + // oracle: mutant recovery refuses a published replacement in one of the two formats, or accepts an invalid one #[test] fn published_replacement_is_a_valid_policy_of_either_format() { + let mut without_publisher: serde_json::Value = serde_json::from_slice(&valid_committed_policy_bytes()).unwrap(); + without_publisher["Metadata"]["Publisher"] = serde_json::json!(""); + let cases = [ ( "2.x document", crate::v2::policy::tests::document("corp-baseline", 3).into_bytes(), - true, + None, + ), + ("1.x policy", valid_committed_policy_bytes(), None), + ( + "1.x policy with an empty publisher", + serde_json::to_vec(&without_publisher).unwrap(), + Some("transaction final replacement failed committed-policy validation"), + ), + ( + "JSON object that is no policy", + b"{}".to_vec(), + Some("transaction final replacement is not a policy document"), ), - ("1.x policy", valid_committed_policy_bytes(), true), - ("JSON object that is no policy", b"{}".to_vec(), false), ]; - for (name, content, expected) in cases { - assert_eq!(verify_replacement_content(&content).is_ok(), expected, "{name}"); + for (name, content, refusal) in cases { + let refused = verify_replacement_content(&content) + .err() + .map(|error| error.to_string()); + + assert_eq!(refused.as_deref(), refusal, "{name}"); } } From e6093c06c2712cef728322ae76dd2a9f546a5a90 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Tue, 1 Dec 2026 06:23:42 +0900 Subject: [PATCH 10/16] fix(agent): tell a 2.x policy file that repeats any key by its format version Whether a file that repeats a key is in format 2.x depended on which key the 2.x reader reports first. A file giving `"2.0.0"` twice as its `PolicyFormatVersion` was not told as a 2.x file, while the same file with a repeated key of another object between the two was. The rule is now the same for every repeated key. When the reader reports a repeated key, whatever the key, the top-level `PolicyFormatVersion` members of the document decide: the file is in format 2.x when there is at least one and each of them is the string `"2.0.0"`. A file that gives that format version twice is in format 2.x, so the 1.x management endpoints do not write it. A file that gives two different format versions is not, and a 1.x file that repeats a key stays repairable. Every other case is still decided from the errors of the reader. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- .../src/policy_store/document_tests.rs | 13 +++++++++++-- .../src/policy_store/format_1.rs | 17 +++++++---------- 2 files changed, 18 insertions(+), 12 deletions(-) diff --git a/crates/now-package-broker/src/policy_store/document_tests.rs b/crates/now-package-broker/src/policy_store/document_tests.rs index fa1d22e36..67346651b 100644 --- a/crates/now-package-broker/src/policy_store/document_tests.rs +++ b/crates/now-package-broker/src/policy_store/document_tests.rs @@ -993,9 +993,14 @@ fn earlier_endpoints_write_no_file_the_reader_tells_is_in_format_2() { writable, ), ( - "file that gives format version 2.0.0 twice", + "document that gives format version 2.0.0 twice", document_with_format_versions("2.0.0", "2.0.0"), - writable, + unwritable, + ), + ( + "document that repeats a key of another object, then gives format version 2.0.0 again", + ending_with_format_version(&repeating_its_publisher(&document("corp-baseline", 3)), "2.0.0"), + unwritable, ), ( "file with another format version", @@ -1040,6 +1045,10 @@ async fn format_1_write_never_replaces_a_format_2_file() { "document that repeats a key of another object", repeating_its_publisher(&document("corp-baseline", 3)), ), + ( + "document that gives format version 2.0.0 twice", + document_with_format_versions("2.0.0", "2.0.0"), + ), ]; let operations = [ PolicyReplacementOperation::Repair, diff --git a/crates/now-package-broker/src/policy_store/format_1.rs b/crates/now-package-broker/src/policy_store/format_1.rs index 4c7402d5d..c435a4cd7 100644 --- a/crates/now-package-broker/src/policy_store/format_1.rs +++ b/crates/now-package-broker/src/policy_store/format_1.rs @@ -45,26 +45,23 @@ const FORMAT_VERSION_POINTER: &str = "/PolicyFormatVersion"; /// /// - No error, or only errors the reader reports once it read that format version: the file is in format 2.x. /// - `UnsupportedFormatVersion`, or `MissingKey` for the format version: it is not. -/// - `DuplicateKey` for the format version: it is not, whatever the values, so a file that gives its format version -/// twice stays repairable. -/// - `DuplicateKey` for another key: the reader stops there without reading the format version, so the top-level +/// - `DuplicateKey`, whatever the key: the reader reports it without reading the format version, so the top-level /// `PolicyFormatVersion` members decide. /// The file is in format 2.x when there is at least one and each of them is the string `"2.0.0"`. -/// A 1.x file that repeats a key therefore stays repairable. +/// A file that gives that format version twice is therefore in format 2.x, a file that gives two different format +/// versions is not, and a 1.x file that repeats a key stays repairable. /// - `MalformedDocument` or `DocumentTooLarge`: it is not, because nothing reads a format version from such a file. /// A 2.x file damaged that way stays writable for the 1.x endpoints. pub(super) fn is_format_2(content: &[u8], errors: &[PolicyError]) -> bool { - let mut repeats_another_key = false; + let mut repeats_a_key = false; for error in errors { match error.code { PolicyErrorCode::DocumentTooLarge | PolicyErrorCode::MalformedDocument | PolicyErrorCode::UnsupportedFormatVersion => return false, - PolicyErrorCode::MissingKey | PolicyErrorCode::DuplicateKey if error.pointer == FORMAT_VERSION_POINTER => { - return false; - } - PolicyErrorCode::DuplicateKey => repeats_another_key = true, + PolicyErrorCode::MissingKey if error.pointer == FORMAT_VERSION_POINTER => return false, + PolicyErrorCode::DuplicateKey => repeats_a_key = true, PolicyErrorCode::MissingKey | PolicyErrorCode::UnknownKey | PolicyErrorCode::ConflictingKeys @@ -74,7 +71,7 @@ pub(super) fn is_format_2(content: &[u8], errors: &[PolicyError]) -> bool { } } - !repeats_another_key || every_format_version_is_2(content) + !repeats_a_key || every_format_version_is_2(content) } /// Returns whether the document in `content` has `PolicyFormatVersion` members and each of them is the string From 3da6ae2d4eaa99828d53814a9ca51d030de55a99 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Tue, 1 Dec 2026 07:02:30 +0900 Subject: [PATCH 11/16] test(agent): cover the replacement outcomes and policy errors no test decided The wire contract decides each of these cases, and a broker that got them wrong passed every test: - A stale store token sent while the file is not watched is `StaleStoreToken`, not `PolicyNotWritable`. - A file that became read-only after its state was read is `PolicyNotWritable`, decided from the file as it is now. - A file someone else changed before a write that then fails for another reason is `StaleStoreToken`, and the change is reported. - A file that holds another valid document after the write is `ActivationFailed`, not a successful replacement. - A file the broker starts watching is no longer read-only for `MonitoringUnavailable`. The table of documents with one defect compared the code and pointer of four of the ten errors the policy contract has a reader report. It now has a document too large, a repeated key, a missing key, conflicting keys, a value of the wrong type and a repeated rule id. The table of files the 1.x endpoints do not write gains a 2.x document that misses a required key other than its format version, which a reader taking any missing key for a missing format version would hand to the 1.x endpoints. The storage double can refuse writes after it was built, and can fail a write over a file someone else changed without telling of the change. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- .../src/policy_store/document_tests.rs | 157 ++++++++++++++---- crates/now-package-broker/src/v2/policy.rs | 45 +++++ 2 files changed, 173 insertions(+), 29 deletions(-) diff --git a/crates/now-package-broker/src/policy_store/document_tests.rs b/crates/now-package-broker/src/policy_store/document_tests.rs index 67346651b..55065325e 100644 --- a/crates/now-package-broker/src/policy_store/document_tests.rs +++ b/crates/now-package-broker/src/policy_store/document_tests.rs @@ -19,6 +19,8 @@ enum Fault { WriteFails, /// Someone else writes this content first, which the conditional publication does not write over. ChangedBeforeWrite(Vec), + /// Someone else writes this content first, and the write then fails without telling that the file changed. + ChangedBeforeFailedWrite(Vec), /// The document is published, and someone else writes this content before the file is read again. ChangedAfterWrite(Vec), /// The document is published, and what the storage does after the publication fails. @@ -34,7 +36,7 @@ struct FakeFile { /// A storage that holds the bytes of one policy file and reads them exactly as the content of a real file is read. struct FileDouble { file: parking_lot::Mutex, - read_only: Option<(PolicyWriteCapability, PolicyReadOnlyReason)>, + read_only: parking_lot::Mutex>, /// Why the storage fails on the file before it reads any content, when it does. failure: Option, fault: parking_lot::Mutex>, @@ -69,7 +71,7 @@ impl FileDouble { content: content.map(|content| content.as_bytes().to_vec()), generation: 1, }), - read_only, + read_only: parking_lot::Mutex::new(read_only), failure, fault: parking_lot::Mutex::new(None), writes: AtomicUsize::new(0), @@ -87,6 +89,11 @@ impl FileDouble { file.generation += 1; } + /// Makes the storage refuse writes from now on, without changing the file. + fn refuse_writes(&self, capability: PolicyWriteCapability, reason: PolicyReadOnlyReason) { + *self.read_only.lock() = Some((capability, reason)); + } + fn fail_next_write(&self, fault: Fault) { *self.fault.lock() = Some(fault); } @@ -102,13 +109,14 @@ impl FileDouble { } fn observation(&self) -> Observation { + let read_only = *self.read_only.lock(); if let Some(failure) = self.failure { - return windows::test_failed_observation(failure, self.read_only); + return windows::test_failed_observation(failure, read_only); } let file = self.file.lock(); match &file.content { - Some(content) => windows::test_file_observation(content, file.generation, self.read_only), - None => windows::test_missing_file_observation(self.read_only), + Some(content) => windows::test_file_observation(content, file.generation, read_only), + None => windows::test_missing_file_observation(read_only), } } @@ -176,6 +184,12 @@ impl PolicyStorage for FileDouble { ))); } Some(Fault::ChangedBeforeWrite(content)) => self.set_content(content), + Some(Fault::ChangedBeforeFailedWrite(content)) => { + self.set_content(content); + return Err(WriteFailure::PrePublication(anyhow::anyhow!( + "injected failure before publication" + ))); + } Some(Fault::ChangedAfterWrite(_) | Fault::FailsAfterWrite) | None => {} } if self.observation().fingerprint != observation.fingerprint { @@ -191,7 +205,7 @@ impl PolicyStorage for FileDouble { "injected failure after publication" ))); } - Some(Fault::WriteFails | Fault::ChangedBeforeWrite(_)) | None => {} + Some(Fault::WriteFails | Fault::ChangedBeforeWrite(_) | Fault::ChangedBeforeFailedWrite(_)) | None => {} } Ok(self.observation()) } @@ -633,6 +647,24 @@ async fn file_that_cannot_be_watched_is_invalid_and_read_only() { assert_eq!(held(&store), None); } +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §management-state +#[tokio::test] +async fn file_is_read_only_as_unwatched_until_the_broker_watches_it() { + let storage = FileDouble::holding(Some(&document("corp-baseline", 3))); + let store = PolicyStore::load_with_storage( + Some(PathBuf::from(POLICY_PATH)), + Arc::clone(&storage) as Arc, + Monitoring::Initializing, + ); + + let before = management(&store); + store.mark_monitoring_ready().await; + let after = management(&store); + + assert_eq!(before.read_only_reason, Some(ReadOnlyReason::MonitoringUnavailable)); + assert_eq!(after.read_only_reason, None); +} + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §management-state #[tokio::test] async fn file_changed_by_someone_else_is_the_accepted_policy_after_a_reload() { @@ -704,6 +736,38 @@ async fn stale_store_token_is_decided_before_writability() { assert_eq!(code(&outcome), "StaleStoreToken"); } +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §replacement +#[tokio::test] +async fn stale_store_token_is_decided_before_an_unwatched_file_is_refused() { + let storage = FileDouble::holding(Some(&document("corp-baseline", 3))); + let store = store(&storage); + store.mark_watcher_unavailable().await; + let expected = v2::StoreToken::parse("not-the-current-token").expect("valid store token"); + + let outcome = replace(&store, &expected, &document("corp-baseline", 4)).await; + + assert_eq!(code(&outcome), "StaleStoreToken"); +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §replacement +#[tokio::test] +async fn policy_that_became_read_only_after_its_state_was_read_is_not_writable() { + let storage = FileDouble::holding(Some(&document("corp-baseline", 3))); + let store = store(&storage); + let expected = management(&store).store_token; + + storage.refuse_writes( + PolicyWriteCapability::ReadOnly, + PolicyReadOnlyReason::InsufficientPermissions, + ); + let outcome = replace(&store, &expected, &document("corp-baseline", 4)).await; + + assert_eq!(code(&outcome), "PolicyNotWritable"); + let after = state_after(outcome).expect("an unwritable replacement carries the state after the request"); + assert_eq!(after.read_only_reason, Some(ReadOnlyReason::InsufficientPermissions)); + assert_eq!(storage.writes(), 0); +} + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §replacement #[tokio::test] async fn read_only_policy_is_not_writable_whatever_the_document() { @@ -849,38 +913,68 @@ async fn write_that_fails_leaves_the_policy_as_it_was() { // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §replacement #[tokio::test] async fn file_that_changes_before_the_write_is_never_written_over() { - let storage = FileDouble::holding(Some(&document("corp-baseline", 3))); - let store = store(&storage); - let expected = management(&store).store_token; - let changed = document("corp-baseline", 7); - storage.fail_next_write(Fault::ChangedBeforeWrite(changed.clone().into_bytes())); + let cases = [ + ( + "write that the change makes fail", + Fault::ChangedBeforeWrite as fn(Vec) -> Fault, + ), + ( + "write that fails without telling that the file changed", + Fault::ChangedBeforeFailedWrite, + ), + ]; - let outcome = replace(&store, &expected, &document("corp-baseline", 4)).await; + for (name, fault) in cases { + let storage = FileDouble::holding(Some(&document("corp-baseline", 3))); + let store = store(&storage); + let expected = management(&store).store_token; + let changed = document("corp-baseline", 7); + storage.fail_next_write(fault(changed.clone().into_bytes())); - assert_eq!(code(&outcome), "StaleStoreToken"); - let after = state_after(outcome).expect("a stale replacement carries the state after the request"); - assert_eq!(after.document.as_deref(), Some(changed.as_str())); - assert_eq!(storage.content(), Some(changed.into_bytes())); - assert_eq!(storage.writes(), 0); + let outcome = replace(&store, &expected, &document("corp-baseline", 4)).await; + + assert_eq!(code(&outcome), "StaleStoreToken", "{name}"); + let after = state_after(outcome).expect("a stale replacement carries the state after the request"); + assert_eq!(after.document.as_deref(), Some(changed.as_str()), "{name}"); + assert_eq!(storage.content(), Some(changed.into_bytes()), "{name}"); + assert_eq!(storage.writes(), 0, "{name}"); + } } // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §replacement #[tokio::test] async fn written_document_the_broker_does_not_hold_is_an_activation_failure() { - let storage = FileDouble::holding(Some(&document("corp-baseline", 3))); - let store = store(&storage); - let expected = management(&store).store_token; - let sent = document("corp-baseline", 4); - storage.fail_next_write(Fault::ChangedAfterWrite(b"{".to_vec())); + let cases = [ + ( + "file that then holds no document", + "{".to_owned(), + PolicyState::Invalid, + None, + ), + ( + "file that then holds another valid document", + document("corp-baseline", 9), + PolicyState::Active, + Some(("corp-baseline".to_owned(), 9)), + ), + ]; - let outcome = replace(&store, &expected, &sent).await; + for (name, changed, state, policy) in cases { + let storage = FileDouble::holding(Some(&document("corp-baseline", 3))); + let store = store(&storage); + let expected = management(&store).store_token; + let sent = document("corp-baseline", 4); + storage.fail_next_write(Fault::ChangedAfterWrite(changed.into_bytes())); - assert_eq!(code(&outcome), "ActivationFailed"); - let after = state_after(outcome).expect("an activation failure carries the state after the request"); - assert_eq!(after.state, PolicyState::Invalid); - assert_eq!(after, management(&store)); - assert_eq!(held(&store), None); - assert_eq!(storage.writes(), 1); + let outcome = replace(&store, &expected, &sent).await; + + assert_eq!(code(&outcome), "ActivationFailed", "{name}"); + let after = state_after(outcome).expect("an activation failure carries the state after the request"); + assert_eq!(after.state, state, "{name}"); + assert_eq!(after, management(&store), "{name}"); + assert_eq!(held(&store), policy, "{name}"); + assert_eq!(storage.writes(), 1, "{name}"); + } } // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §replacement @@ -937,6 +1031,11 @@ fn earlier_endpoints_write_no_file_the_reader_tells_is_in_format_2() { document_with_unknown_key("corp-baseline", 3), unwritable, ), + ( + "document without a required key that is not the format version", + document("corp-baseline", 3).replace(r#""Publisher": "Test", "#, ""), + unwritable, + ), ( "document with a number of any magnitude", document_with_huge_revision(), diff --git a/crates/now-package-broker/src/v2/policy.rs b/crates/now-package-broker/src/v2/policy.rs index 9b8906282..a51366eb6 100644 --- a/crates/now-package-broker/src/v2/policy.rs +++ b/crates/now-package-broker/src/v2/policy.rs @@ -269,9 +269,54 @@ pub(crate) mod tests { // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.policy.md §errors #[test] fn document_with_one_defect_reports_that_error() { + let mut larger_than_4_mib = document("corp-baseline", 1).into_bytes(); + larger_than_4_mib.resize(4 * 1024 * 1024 + 1, b' '); + let cases = [ + ( + "larger than 4 MiB", + larger_than_4_mib, + error(PolicyErrorCode::DocumentTooLarge, ""), + ), ("not JSON", b"{".to_vec(), error(PolicyErrorCode::MalformedDocument, "")), ("not UTF-8", vec![0xFF], error(PolicyErrorCode::MalformedDocument, "")), + ( + "repeated key", + document("corp-baseline", 1) + .replace(r#""Publisher": "Test""#, r#""Publisher": "Test", "Publisher": "Test""#) + .into_bytes(), + error(PolicyErrorCode::DuplicateKey, "/Metadata/Publisher"), + ), + ( + "missing required key", + document("corp-baseline", 1) + .replace(r#""Publisher": "Test", "#, "") + .into_bytes(), + error(PolicyErrorCode::MissingKey, "/Metadata/Publisher"), + ), + ( + "source selector with both of its exclusive keys", + document("corp-baseline", 1) + .replace(r#""AnySource": true"#, r#""Source": "winget", "AnySource": true"#) + .into_bytes(), + error(PolicyErrorCode::ConflictingKeys, "/TrustedSources/0/AnySource"), + ), + ( + "rules that are no list", + document_with("corp-baseline", 1, "{}", "").into_bytes(), + error(PolicyErrorCode::WrongType, "/Rules"), + ), + ( + "two rules with the same id", + document_with( + "corp-baseline", + 1, + r#"[{ "Id": "rule", "Decision": "Allow", "Select": {} }, { "Id": "rule", "Decision": "Deny", "Select": {} }]"#, + "", + ) + .into_bytes(), + error(PolicyErrorCode::DuplicateRuleId, "/Rules/1/Id"), + ), ( "earlier format version", document("corp-baseline", 1).replace("2.0.0", "1.0.0").into_bytes(), From 297717f10a1f43185e7dcdca370f38ce761b0d6d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Tue, 1 Dec 2026 07:13:32 +0900 Subject: [PATCH 12/16] test(agent): pin the 1.x view of a policy path of unsupported form The 2.0 view of a path of unsupported form is set right beside the code that builds the 1.x view of it, and no test of the storage decided what the 1.x endpoints report for such a path. A test now pins the state, the write capability and the read-only reason they get for each rule that refuses a form. The path meant to name no file ended with a separator, so the rule for a trailing separator refused it and the rule for a missing file name was never reached. A share root reaches that rule, which its own test now shows. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- .../src/policy_store/windows.rs | 54 ++++++++++++++++--- 1 file changed, 47 insertions(+), 7 deletions(-) diff --git a/crates/now-package-broker/src/policy_store/windows.rs b/crates/now-package-broker/src/policy_store/windows.rs index dabffaa5e..1b710d348 100644 --- a/crates/now-package-broker/src/policy_store/windows.rs +++ b/crates/now-package-broker/src/policy_store/windows.rs @@ -4951,6 +4951,13 @@ mod tests { assert!(error.to_string().contains("'..'"), "{error}"); } + // oracle: mutant a path that names no file is accepted, or refused by the rule for another form + #[test] + fn path_that_names_no_file_is_rejected() { + let error = validate_configured_path_shape(Path::new(r"\\server\share")).unwrap_err(); + assert!(error.to_string().contains("name a file"), "{error}"); + } + #[test] fn yaml_extension_is_rejected() { let error = validate_configured_path_shape(Path::new(r"C:\ProgramData\Devolutions\policy.yaml")).unwrap_err(); @@ -5031,20 +5038,27 @@ mod tests { assert_unsupported_format_is_reported_invalid_end_to_end("policy.txt"); } + /// Paths of a form the broker does not read, one for each rule that refuses a form. + const PATHS_OF_UNSUPPORTED_FORM: [(&str, &str); 5] = [ + ("relative path", r"relative\policy.json"), + ("path ending with a separator", r"C:\ProgramData\Devolutions\"), + ("path with a `.` component", r"C:\ProgramData\.\policy.json"), + ("path with a `..` component", r"C:\ProgramData\..\policy.json"), + ("path that names no file", r"\\server\share"), + ]; + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §management-state #[test] fn path_of_a_form_or_extension_the_broker_does_not_read_is_an_unsupported_path_for_the_2_0_endpoints() { - let paths = [ - ("relative path", r"relative\policy.json"), - ("path ending with a separator", r"C:\ProgramData\Devolutions\"), - ("path with a `.` component", r"C:\ProgramData\.\policy.json"), - ("path with a `..` component", r"C:\ProgramData\..\policy.json"), - ("path that names no file", r"C:\"), + let paths_of_unsupported_extension = [ ("path with another extension", r"C:\ProgramData\Devolutions\policy.yaml"), ("path without an extension", r"C:\ProgramData\Devolutions\policy"), ]; - for (case, path) in paths { + for (case, path) in PATHS_OF_UNSUPPORTED_FORM + .into_iter() + .chain(paths_of_unsupported_extension) + { let observation = observe( PolicyConfigurationSource::ConfiguredPath, Path::new(path), @@ -5066,6 +5080,32 @@ mod tests { } } + // oracle: mutant the 1.x endpoints report a path of unsupported form with another state, capability or reason + #[test] + fn path_of_a_form_the_broker_does_not_read_is_an_unsafe_path_for_the_1_x_endpoints() { + for (case, path) in PATHS_OF_UNSUPPORTED_FORM { + let observation = observe( + PolicyConfigurationSource::ConfiguredPath, + Path::new(path), + &AtomicityProbeCache::new(), + ); + + assert_eq!( + ( + observation.state, + observation.write_capability, + observation.read_only_reason + ), + ( + PolicyManagementState::Invalid, + PolicyWriteCapability::Unsupported, + Some(PolicyReadOnlyReason::UnsafePath) + ), + "{case}" + ); + } + } + // ─── Strict policy ancestor walk: reparse rejection (item 16) ───────────── // // Directory junctions (unlike symlinks) require no special privilege to create, so From 01cd992073728e82b9751bc25f58352a45e78e77 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Tue, 1 Dec 2026 07:13:32 +0900 Subject: [PATCH 13/16] test(agent): compare the format 2.x rule with the reader on escapes and nesting The members that decide the format of a file that repeats a key are read by another parser than the 2.x reader, so the two must read a key, a value and a nested value alike. The table now holds a format version key and a format version value spelled with a JSON escape, and a value nested to the deepest level the reader accepts, each alone and beside a repeated key, and a value nested one level deeper. The two agree on every row, so the rule is unchanged. The fixtures that rewrite the text of a document now fail when the text they look for is not there exactly once. A fixture that returns its input unchanged leaves a row that no longer tests its case, and the row still passes where a valid document is expected. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- .../src/policy_store/document_tests.rs | 106 ++++++++++++++++-- 1 file changed, 97 insertions(+), 9 deletions(-) diff --git a/crates/now-package-broker/src/policy_store/document_tests.rs b/crates/now-package-broker/src/policy_store/document_tests.rs index 55065325e..d81131f41 100644 --- a/crates/now-package-broker/src/policy_store/document_tests.rs +++ b/crates/now-package-broker/src/policy_store/document_tests.rs @@ -318,29 +318,59 @@ fn format_1_request(store: &PolicyStore, operation: PolicyReplacementOperation) } } +/// `text` with its one occurrence of `pattern` replaced by `replacement`. +/// +/// Panics when `text` does not hold `pattern` exactly once, so a fixture never returns its input unchanged. +fn replacing(text: &str, pattern: &str, replacement: &str) -> String { + assert_eq!( + text.matches(pattern).count(), + 1, + "the text holds `{pattern}` once: {text}" + ); + text.replacen(pattern, replacement, 1) +} + +/// The JSON escape that spells `character`, a character of the Basic Multilingual Plane, by its code unit. +fn json_escape(character: char) -> String { + format!(r"\u{:04x}", u32::from(character)) +} + /// The text of a document in format 2.x whose `Revision` is a number larger than any a JSON library need represent. fn document_with_huge_revision() -> String { - document("corp-baseline", 3).replacen(r#""Revision": 3"#, r#""Revision": 1e999"#, 1) + replacing( + &document("corp-baseline", 3), + r#""Revision": 3"#, + r#""Revision": 1e999"#, + ) } /// The text of a file that gives `first` and then `second` as its `PolicyFormatVersion`. fn document_with_format_versions(first: &str, second: &str) -> String { - document("corp-baseline", 3).replacen( + replacing( + &document("corp-baseline", 3), r#""PolicyFormatVersion": "2.0.0""#, &format!(r#""PolicyFormatVersion": "{first}", "PolicyFormatVersion": "{second}""#), - 1, ) } /// `text` with the `Publisher` of its `Metadata` written twice, so an object other than the document repeats a key. fn repeating_its_publisher(text: &str) -> String { - text.replacen( + replacing( + text, r#""Publisher": "Test""#, r#""Publisher": "Test", "Publisher": "Test""#, - 1, ) } +/// `text` with one more member of the document, whose value nests arrays down to `level`. +/// +/// The document is level 1, so the value is `level - 1` arrays, each inside the one before. +fn with_value_nested_to_level(text: &str, level: usize) -> String { + let arrays = level - 1; + let value = format!("{}{}", "[".repeat(arrays), "]".repeat(arrays)); + replacing(text, r#""Metadata""#, &format!(r#""Nested": {value}, "Metadata""#)) +} + /// `text` with one more `PolicyFormatVersion`, of value `version`, as the last member of the document. fn ending_with_format_version(text: &str, version: &str) -> String { let end = text.rfind('}').expect("text of an object"); @@ -1019,6 +1049,16 @@ fn earlier_endpoints_write_no_file_the_reader_tells_is_in_format_2() { Some(PolicyReadOnlyReason::UnsupportedFormat), ); let writable = (PolicyWriteCapability::Writable, None); + let with_escaped_key = replacing( + &document("corp-baseline", 3), + r#""PolicyFormatVersion""#, + &format!(r#""PolicyFormat{}ersion""#, json_escape('V')), + ); + let with_escaped_version = replacing( + &document("corp-baseline", 3), + r#""2.0.0""#, + &format!(r#""2.0.{}""#, json_escape('0')), + ); let cases = [ ("valid document", document("corp-baseline", 3), unwritable), ( @@ -1033,7 +1073,7 @@ fn earlier_endpoints_write_no_file_the_reader_tells_is_in_format_2() { ), ( "document without a required key that is not the format version", - document("corp-baseline", 3).replace(r#""Publisher": "Test", "#, ""), + replacing(&document("corp-baseline", 3), r#""Publisher": "Test", "#, ""), unwritable, ), ( @@ -1063,7 +1103,7 @@ fn earlier_endpoints_write_no_file_the_reader_tells_is_in_format_2() { ), ( "file that repeats a key of another object, with a format version that is no string", - repeating_its_publisher(&document("corp-baseline", 3).replace(r#""2.0.0""#, "2")), + repeating_its_publisher(&replacing(&document("corp-baseline", 3), r#""2.0.0""#, "2")), writable, ), ( @@ -1101,14 +1141,62 @@ fn earlier_endpoints_write_no_file_the_reader_tells_is_in_format_2() { ending_with_format_version(&repeating_its_publisher(&document("corp-baseline", 3)), "2.0.0"), unwritable, ), + // CONTRACT.policy.md §json: "Keys match only with their exact characters, after JSON escapes are decoded." + // The reader reads the key as `PolicyFormatVersion` and accepts the document. + ( + "document that spells its format version key with an escape", + with_escaped_key.clone(), + unwritable, + ), + // The reader reports the repeated key alone, and the member decides, read with its escape decoded. + ( + "document that spells its format version key with an escape and repeats a key of another object", + repeating_its_publisher(&with_escaped_key), + unwritable, + ), + // CONTRACT.policy.md §json: "A policy document is one JSON value as RFC 8259 defines it", where an escape + // spells the character it names. + // The reader reads the value as `2.0.0` and accepts the document. + ( + "document that spells its format version with an escape", + with_escaped_version.clone(), + unwritable, + ), + // The reader reports the repeated key alone, and the member decides, read with its escape decoded. + ( + "document that spells its format version with an escape and repeats a key of another object", + repeating_its_publisher(&with_escaped_version), + unwritable, + ), + // CONTRACT.policy.md §json: a document is malformed when it "nests arrays and objects more than 64 levels + // deep, counting the top-level object as level 1". + // The reader reads a value nested to level 64 and reports the key of that value as unknown. + ( + "document with a value nested to level 64", + with_value_nested_to_level(&document("corp-baseline", 3), 64), + unwritable, + ), + // The reader reports the repeated key alone, and the member decides, the nested value skipped. + ( + "document with a value nested to level 64 that repeats a key of another object", + repeating_its_publisher(&with_value_nested_to_level(&document("corp-baseline", 3), 64)), + unwritable, + ), + // The reader reports a value nested to level 65 as a malformed document, repeated key or not, so nothing + // tells the format of the file. + ( + "file with a value nested to level 65 that repeats a key of another object", + repeating_its_publisher(&with_value_nested_to_level(&document("corp-baseline", 3), 65)), + writable, + ), ( "file with another format version", - document("corp-baseline", 3).replace("2.0.0", "1.0.0"), + replacing(&document("corp-baseline", 3), "2.0.0", "1.0.0"), writable, ), ( "file with a format version that is no string", - document("corp-baseline", 3).replace(r#""2.0.0""#, "2"), + replacing(&document("corp-baseline", 3), r#""2.0.0""#, "2"), writable, ), ( From 47fec3e51f3e438cf099fb9a0eaa0db233d60300 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Tue, 1 Dec 2026 07:13:33 +0900 Subject: [PATCH 14/16] docs(agent): correct what the storage says of an unsupported policy path The documentation of `observe` gave `UnsupportedFormat` as the read-only reason of every path of unsupported form or extension. The 1.x endpoints get `UnsafePath` for a form and `UnsupportedFormat` for an extension, and the 2.0 endpoints get `UnsupportedPath` for both. The read-only reason of a file the store stopped watching is marked as a value no test decides in a flow the broker has: the state of an unwatched file gets its reason elsewhere, and the test of the mapping uses a storage that gives the reason for a watched file. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- crates/now-package-broker/src/policy_store/document.rs | 8 +++++++- crates/now-package-broker/src/policy_store/windows.rs | 9 +++++---- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/crates/now-package-broker/src/policy_store/document.rs b/crates/now-package-broker/src/policy_store/document.rs index f37a3a935..cf34e5418 100644 --- a/crates/now-package-broker/src/policy_store/document.rs +++ b/crates/now-package-broker/src/policy_store/document.rs @@ -74,7 +74,13 @@ impl DocumentObservation { /// Returns the reason a replacement cannot write the file for the reason the storage gives the 1.x endpoints. pub(super) fn read_only_reason(reason: Option) -> Option { Some(match reason? { - // The storage gives this reason only once it stopped watching the file. + // UNTESTED: only the store gives `ManagementDisabled`, once it stopped watching the file, and the state of an + // unwatched file already gets `MonitoringUnavailable` from `DocumentView::management`, whatever this arm + // returns. + // The one test of this arm uses a storage that gives the reason for a watched file, which no storage does, so + // no test decides what a client reads through this arm in a flow the broker has. + // When a storage starts giving this reason for a watched file, check its contract value before relying on + // this arm. PolicyReadOnlyReason::ManagementDisabled => ReadOnlyReason::MonitoringUnavailable, PolicyReadOnlyReason::UnsupportedFormat => ReadOnlyReason::UnsupportedPath, // UNTESTED: the storage never gives `PathNotConfigured`, because the broker always reads a path, so no test diff --git a/crates/now-package-broker/src/policy_store/windows.rs b/crates/now-package-broker/src/policy_store/windows.rs index 1b710d348..2df304224 100644 --- a/crates/now-package-broker/src/policy_store/windows.rs +++ b/crates/now-package-broker/src/policy_store/windows.rs @@ -1294,10 +1294,11 @@ fn paths_component_matches_case_insensitive(a: &OsStr, b: &OsStr) -> bool { /// deterministic way a submitted draft is (item 30): a committed file is never activated /// on structural parseability alone. /// -/// A configured path whose shape/extension is unsupported (item 18/22) -- relative, -/// empty/non-file leaf, trailing separator, `.`/`..` component, or an extension other -/// than `.json` -- is reported with the shared contract's dedicated -/// [`PolicyReadOnlyReason::UnsupportedFormat`]. +/// A configured path of unsupported form -- relative, empty/non-file leaf, trailing +/// separator, or `.`/`..` component -- is reported to the 1.x endpoints with +/// [`PolicyReadOnlyReason::UnsafePath`], and a path with an extension other than `.json` +/// with [`PolicyReadOnlyReason::UnsupportedFormat`]. +/// The 2.0 endpoints get [`ReadOnlyReason::UnsupportedPath`] for both. pub(super) fn observe( source: PolicyConfigurationSource, configured_path: &Path, From d3cd6103d8f0aa0f5dbaa0340fa55ac0eb8ba23b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Tue, 1 Dec 2026 12:28:35 +0900 Subject: [PATCH 15/16] test(agent): keep the policy store test fixtures and comments to what a test decides The arm that maps `ManagementDisabled` has a test, so its comment no longer marks it as untested and says instead why no client reads its value. The fixture that adds an unknown key now fails when the text it replaces is not there exactly once, like the other fixtures that rewrite a document. The rows that quote the policy contract cite the revision the quotes come from. Issue: DGW-499 Changelog: ignore Co-Authored-By: Claude Fable 5.2 --- .../now-package-broker/src/policy_store/document.rs | 10 +++------- .../src/policy_store/document_tests.rs | 11 +++++++---- 2 files changed, 10 insertions(+), 11 deletions(-) diff --git a/crates/now-package-broker/src/policy_store/document.rs b/crates/now-package-broker/src/policy_store/document.rs index cf34e5418..41cca63e8 100644 --- a/crates/now-package-broker/src/policy_store/document.rs +++ b/crates/now-package-broker/src/policy_store/document.rs @@ -74,13 +74,9 @@ impl DocumentObservation { /// Returns the reason a replacement cannot write the file for the reason the storage gives the 1.x endpoints. pub(super) fn read_only_reason(reason: Option) -> Option { Some(match reason? { - // UNTESTED: only the store gives `ManagementDisabled`, once it stopped watching the file, and the state of an - // unwatched file already gets `MonitoringUnavailable` from `DocumentView::management`, whatever this arm - // returns. - // The one test of this arm uses a storage that gives the reason for a watched file, which no storage does, so - // no test decides what a client reads through this arm in a flow the broker has. - // When a storage starts giving this reason for a watched file, check its contract value before relying on - // this arm. + // Only the store gives `ManagementDisabled`, once it stopped watching the file, and `DocumentView::management` + // reports `MonitoringUnavailable` for an unwatched file without reading this reason. + // No client therefore reads the value of this arm unless a storage gives the reason for a watched file. PolicyReadOnlyReason::ManagementDisabled => ReadOnlyReason::MonitoringUnavailable, PolicyReadOnlyReason::UnsupportedFormat => ReadOnlyReason::UnsupportedPath, // UNTESTED: the storage never gives `PathNotConfigured`, because the broker always reads a path, so no test diff --git a/crates/now-package-broker/src/policy_store/document_tests.rs b/crates/now-package-broker/src/policy_store/document_tests.rs index d81131f41..00cecf6cf 100644 --- a/crates/now-package-broker/src/policy_store/document_tests.rs +++ b/crates/now-package-broker/src/policy_store/document_tests.rs @@ -275,7 +275,7 @@ fn held(store: &PolicyStore) -> Option<(String, u32)> { /// A 2.x document whose only defect is the unknown top-level key `Extra`. fn document_with_unknown_key(id: &str, revision: u32) -> String { - document(id, revision).replacen(r#""Rules""#, "\"Extra\": 1,\n \"Rules\"", 1) + replacing(&document(id, revision), r#""Rules""#, "\"Extra\": 1,\n \"Rules\"") } /// The error a reader reports for [`document_with_unknown_key`]. @@ -1141,7 +1141,8 @@ fn earlier_endpoints_write_no_file_the_reader_tells_is_in_format_2() { ending_with_format_version(&repeating_its_publisher(&document("corp-baseline", 3)), "2.0.0"), unwritable, ), - // CONTRACT.policy.md §json: "Keys match only with their exact characters, after JSON escapes are decoded." + // Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.policy.md §json: + // "Keys match only with their exact characters, after JSON escapes are decoded." // The reader reads the key as `PolicyFormatVersion` and accepts the document. ( "document that spells its format version key with an escape", @@ -1154,7 +1155,8 @@ fn earlier_endpoints_write_no_file_the_reader_tells_is_in_format_2() { repeating_its_publisher(&with_escaped_key), unwritable, ), - // CONTRACT.policy.md §json: "A policy document is one JSON value as RFC 8259 defines it", where an escape + // Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.policy.md §json: + // "A policy document is one JSON value as RFC 8259 defines it", where an escape // spells the character it names. // The reader reads the value as `2.0.0` and accepts the document. ( @@ -1168,7 +1170,8 @@ fn earlier_endpoints_write_no_file_the_reader_tells_is_in_format_2() { repeating_its_publisher(&with_escaped_version), unwritable, ), - // CONTRACT.policy.md §json: a document is malformed when it "nests arrays and objects more than 64 levels + // Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.policy.md §json: + // a document is malformed when it "nests arrays and objects more than 64 levels // deep, counting the top-level object as level 1". // The reader reads a value nested to level 64 and reports the key of that value as unknown. ( From 41b5e66206561103122528a0ceb51cf783d05581 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Wed, 2 Dec 2026 03:09:48 +0900 Subject: [PATCH 16/16] build(agent): pin the 2.0 policy crates to revisions that read a request without a source The API types at the new revision read a closed-set value from a string only, refuse a timestamp of a leap second, and check the members of a status response, a policy identity and a policy error. The evaluator at its new revision takes a request whose source is optional, which a bypass request may leave out, and reads such a request the way the broker executes it. The two pins differ because the two crates are changed on separate branches of the repository; the evaluator has no dependency of its own, so no type exists twice. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- Cargo.lock | 8 ++++---- Cargo.toml | 6 +++--- crates/now-package-broker/Cargo.toml | 2 +- crates/now-package-broker/src/v2/policy.rs | 4 ++-- 4 files changed, 10 insertions(+), 10 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 11f819110..88f10f0c2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5234,7 +5234,7 @@ dependencies = [ [[package]] name = "now-policy" version = "0.5.0" -source = "git+https://github.com/Devolutions/now-libraries?rev=77307f5106d9764d03a420d22fd8377c99432af5#77307f5106d9764d03a420d22fd8377c99432af5" +source = "git+https://github.com/Devolutions/now-libraries?rev=5b23b1a616ca97590d4d6b9e610cd07772d30453#5b23b1a616ca97590d4d6b9e610cd07772d30453" dependencies = [ "chrono", "schemars 0.9.0", @@ -5248,7 +5248,7 @@ dependencies = [ [[package]] name = "now-policy-api" version = "0.7.1" -source = "git+https://github.com/Devolutions/now-libraries?rev=77307f5106d9764d03a420d22fd8377c99432af5#77307f5106d9764d03a420d22fd8377c99432af5" +source = "git+https://github.com/Devolutions/now-libraries?rev=5b23b1a616ca97590d4d6b9e610cd07772d30453#5b23b1a616ca97590d4d6b9e610cd07772d30453" dependencies = [ "chrono", "derive_more", @@ -5264,12 +5264,12 @@ dependencies = [ [[package]] name = "now-policy-eval" version = "0.0.0" -source = "git+https://github.com/Devolutions/now-libraries?rev=77307f5106d9764d03a420d22fd8377c99432af5#77307f5106d9764d03a420d22fd8377c99432af5" +source = "git+https://github.com/Devolutions/now-libraries?rev=25e75110c067239e44e42f005abbf566f32f803a#25e75110c067239e44e42f005abbf566f32f803a" [[package]] name = "now-policy-server-template" version = "0.7.1" -source = "git+https://github.com/Devolutions/now-libraries?rev=77307f5106d9764d03a420d22fd8377c99432af5#77307f5106d9764d03a420d22fd8377c99432af5" +source = "git+https://github.com/Devolutions/now-libraries?rev=5b23b1a616ca97590d4d6b9e610cd07772d30453#5b23b1a616ca97590d4d6b9e610cd07772d30453" dependencies = [ "aide 0.15.1", "async-trait", diff --git a/Cargo.toml b/Cargo.toml index 15ba797a6..a08f60a2d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -35,9 +35,9 @@ lto = true tracing-appender = { git = "https://github.com/CBenoit/tracing.git", rev = "42097daf92e683cf18da7639ddccb056721a796c" } # TEMPORARY: the 2.0 package broker API types are not published yet. # These three patches must go, and the crates.io versions that carry the types must be required instead, before this change merges. -now-policy = { git = "https://github.com/Devolutions/now-libraries", rev = "77307f5106d9764d03a420d22fd8377c99432af5" } -now-policy-api = { git = "https://github.com/Devolutions/now-libraries", rev = "77307f5106d9764d03a420d22fd8377c99432af5" } -now-policy-server-template = { git = "https://github.com/Devolutions/now-libraries", rev = "77307f5106d9764d03a420d22fd8377c99432af5" } +now-policy = { git = "https://github.com/Devolutions/now-libraries", rev = "5b23b1a616ca97590d4d6b9e610cd07772d30453" } +now-policy-api = { git = "https://github.com/Devolutions/now-libraries", rev = "5b23b1a616ca97590d4d6b9e610cd07772d30453" } +now-policy-server-template = { git = "https://github.com/Devolutions/now-libraries", rev = "5b23b1a616ca97590d4d6b9e610cd07772d30453" } [workspace.lints.rust] # Declare the custom cfgs. diff --git a/crates/now-package-broker/Cargo.toml b/crates/now-package-broker/Cargo.toml index 5af0c2098..a2e826aaa 100644 --- a/crates/now-package-broker/Cargo.toml +++ b/crates/now-package-broker/Cargo.toml @@ -30,7 +30,7 @@ now-policy = "0.5" now-policy-api = "0.7.1" # TEMPORARY: `now-policy-eval` is not published yet. # This git dependency must become a crates.io version before this change merges. -now-policy-eval = { git = "https://github.com/Devolutions/now-libraries", rev = "77307f5106d9764d03a420d22fd8377c99432af5" } +now-policy-eval = { git = "https://github.com/Devolutions/now-libraries", rev = "25e75110c067239e44e42f005abbf566f32f803a" } now-policy-server-template = "0.7.1" parking_lot = "0.12" regex = "1" diff --git a/crates/now-package-broker/src/v2/policy.rs b/crates/now-package-broker/src/v2/policy.rs index a51366eb6..cbcfe411d 100644 --- a/crates/now-package-broker/src/v2/policy.rs +++ b/crates/now-package-broker/src/v2/policy.rs @@ -201,9 +201,9 @@ pub(crate) mod tests { Request { operation: Operation::Install, manager: Manager::Winget, - source: Source { + source: Some(Source { name: "winget".to_owned(), - }, + }), package: Package { id: "Git.Git".to_owned(), // An install through WinGet without a concrete version is denied whatever the policy says.