diff --git a/Cargo.lock b/Cargo.lock index 9ec6dee3b..787c55571 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", @@ -5233,7 +5234,7 @@ dependencies = [ [[package]] name = "now-policy" version = "0.5.0" -source = "git+https://github.com/Devolutions/now-libraries?rev=4b672ee9c7c04aa913dc7a739bd941b49e1ee9f6#4b672ee9c7c04aa913dc7a739bd941b49e1ee9f6" +source = "git+https://github.com/Devolutions/now-libraries?rev=af4ff9e01d3a5c6ad64f07eaa03bf92d05549b67#af4ff9e01d3a5c6ad64f07eaa03bf92d05549b67" dependencies = [ "chrono", "schemars 0.9.0", @@ -5247,7 +5248,7 @@ dependencies = [ [[package]] name = "now-policy-api" version = "0.7.1" -source = "git+https://github.com/Devolutions/now-libraries?rev=4b672ee9c7c04aa913dc7a739bd941b49e1ee9f6#4b672ee9c7c04aa913dc7a739bd941b49e1ee9f6" +source = "git+https://github.com/Devolutions/now-libraries?rev=af4ff9e01d3a5c6ad64f07eaa03bf92d05549b67#af4ff9e01d3a5c6ad64f07eaa03bf92d05549b67" dependencies = [ "chrono", "derive_more", @@ -5260,10 +5261,15 @@ dependencies = [ "thiserror 2.0.20", ] +[[package]] +name = "now-policy-eval" +version = "0.0.0" +source = "git+https://github.com/Devolutions/now-libraries?rev=1763e9655b912f754481c6e6ab424ed89299c0cb#1763e9655b912f754481c6e6ab424ed89299c0cb" + [[package]] name = "now-policy-server-template" version = "0.7.1" -source = "git+https://github.com/Devolutions/now-libraries?rev=4b672ee9c7c04aa913dc7a739bd941b49e1ee9f6#4b672ee9c7c04aa913dc7a739bd941b49e1ee9f6" +source = "git+https://github.com/Devolutions/now-libraries?rev=af4ff9e01d3a5c6ad64f07eaa03bf92d05549b67#af4ff9e01d3a5c6ad64f07eaa03bf92d05549b67" dependencies = [ "aide 0.15.1", "async-trait", diff --git a/Cargo.toml b/Cargo.toml index b43394a09..2c8f299f1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -33,10 +33,11 @@ lto = true [patch.crates-io] tracing-appender = { git = "https://github.com/CBenoit/tracing.git", rev = "42097daf92e683cf18da7639ddccb056721a796c" } -# `ErrorCode::BrokerBusy` is merged in now-libraries but not released yet; move to now-policy-api 0.8.0 once it is published. -now-policy = { git = "https://github.com/Devolutions/now-libraries", rev = "4b672ee9c7c04aa913dc7a739bd941b49e1ee9f6" } -now-policy-api = { git = "https://github.com/Devolutions/now-libraries", rev = "4b672ee9c7c04aa913dc7a739bd941b49e1ee9f6" } -now-policy-server-template = { git = "https://github.com/Devolutions/now-libraries", rev = "4b672ee9c7c04aa913dc7a739bd941b49e1ee9f6" } +# TEMPORARY: the 2.0 package broker API types and `ErrorCode::BrokerBusy` are not published yet. +# These three patches must go, and the crates.io versions that carry both must be required instead, before this change merges. +now-policy = { git = "https://github.com/Devolutions/now-libraries", rev = "af4ff9e01d3a5c6ad64f07eaa03bf92d05549b67" } +now-policy-api = { git = "https://github.com/Devolutions/now-libraries", rev = "af4ff9e01d3a5c6ad64f07eaa03bf92d05549b67" } +now-policy-server-template = { git = "https://github.com/Devolutions/now-libraries", rev = "af4ff9e01d3a5c6ad64f07eaa03bf92d05549b67" } [workspace.lints.rust] # Declare the custom cfgs. diff --git a/crates/now-package-broker/Cargo.toml b/crates/now-package-broker/Cargo.toml index 50041123a..11d1a33d1 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 = "1763e9655b912f754481c6e6ab424ed89299c0cb" } now-policy-server-template = "0.7.1" parking_lot = "0.12" regex = "1" diff --git a/crates/now-package-broker/src/audit.rs b/crates/now-package-broker/src/audit.rs index 26b830a9e..3df0b4d96 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,71 @@ 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 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, + 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/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/policy_store/document.rs b/crates/now-package-broker/src/policy_store/document.rs new file mode 100644 index 000000000..41cca63e8 --- /dev/null +++ b/crates/now-package-broker/src/policy_store/document.rs @@ -0,0 +1,223 @@ +//! 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. + // + // 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, + 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? { + // 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 + // 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, + }) +} + +/// 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. +/// 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!( + 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, + 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..56e760d40 --- /dev/null +++ b/crates/now-package-broker/src/policy_store/document_tests.rs @@ -0,0 +1,1526 @@ +//! 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 std::task::Poll; + +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::validation::DiskFailureReason; +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), + /// 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. + FailsAfterWrite, +} + +struct FakeFile { + content: Option>, + /// Stands in for the identity of the file, which every write changes. + generation: u32, +} + +/// Holds a document write between its entry into the storage and anything it does there. +struct WriteGate { + /// Tells the test that the write entered the storage. + entered: tokio::sync::oneshot::Sender<()>, + /// Ends the wait when the test sends on it or drops its sender. + release: std::sync::mpsc::Receiver<()>, +} + +/// 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: parking_lot::Mutex>, + /// Why the storage fails on the file before it reads any content, when it does. + failure: Option, + fault: parking_lot::Mutex>, + gate: parking_lot::Mutex>, + writes: AtomicUsize, +} + +impl FileDouble { + fn holding(content: Option<&str>) -> Arc { + Self::new(content, None, None) + } + + fn read_only(content: &str, capability: PolicyWriteCapability, reason: PolicyReadOnlyReason) -> Arc { + Self::new(Some(content), Some((capability, reason)), None) + } + + /// 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: parking_lot::Mutex::new(read_only), + failure, + fault: parking_lot::Mutex::new(None), + gate: 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; + } + + /// 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)); + } + + /// Makes the storage accept writes from now on, without changing the file. + fn allow_writes(&self) { + *self.read_only.lock() = None; + } + + fn fail_next_write(&self, fault: Fault) { + *self.fault.lock() = Some(fault); + } + + /// Makes the next document write wait once it entered the storage, until the returned sender sends or drops. + /// + /// The returned receiver resolves when that write entered the storage. + fn hold_next_write(&self) -> (tokio::sync::oneshot::Receiver<()>, std::sync::mpsc::Sender<()>) { + let (entered, entry) = tokio::sync::oneshot::channel(); + let (opener, release) = std::sync::mpsc::channel(); + *self.gate.lock() = Some(WriteGate { entered, release }); + (entry, opener) + } + + /// 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 read_only = *self.read_only.lock(); + if let Some(failure) = self.failure { + 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, read_only), + None => windows::test_missing_file_observation(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, + _source: PolicyConfigurationSource, + _configured_path: &Path, + observation: &mut Observation, + bytes: &[u8], + ) -> Result { + let gate = self.gate.lock().take(); + if let Some(gate) = gate { + // The write is synchronous, so it waits on a channel of the standard library, which parks the thread that + // runs it and no other. + // A dropped sender ends the wait too, so a test that fails before it releases the write still ends. + let _ = gate.entered.send(()); + let _ = gate.release.recv(); + } + 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::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 { + 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(_) | Fault::ChangedBeforeFailedWrite(_)) | 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 { + replacing(&document(id, revision), r#""Rules""#, "\"Extra\": 1,\n \"Rules\"") +} + +/// 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"), + } +} + +/// `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 { + 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 { + replacing( + &document("corp-baseline", 3), + r#""PolicyFormatVersion": "2.0.0""#, + &format!(r#""PolicyFormatVersion": "{first}", "PolicyFormatVersion": "{second}""#), + ) +} + +/// `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 { + replacing( + text, + r#""Publisher": "Test""#, + r#""Publisher": "Test", "Publisher": "Test""#, + ) +} + +/// `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"); + 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 { + 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(), + }) +} + +/// Counts the warnings logged by one module of the policy store. +struct ModuleWarnings { + /// The end of the target of the module, which starts with the name of the crate. + module: &'static str, + count: Arc, +} + +impl tracing::Subscriber for ModuleWarnings { + 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(self.module) { + self.count.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. +fn count_view_warnings() -> (Arc, impl Sized) { + count_warnings_of("policy_store::document") +} + +/// Counts, until the returned guard drops, the warnings the current thread logs while it observes the policy file. +fn count_observation_warnings() -> (Arc, impl Sized) { + count_warnings_of("policy_store::windows") +} + +/// Counts, until the returned guard drops, the warnings the current thread logs from the module whose target ends with +/// `module`. +/// +/// 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_warnings_of(module: &'static str) -> (Arc, impl Sized) { + let warnings = Arc::new(AtomicUsize::new(0)); + let counting = tracing::subscriber::set_default(ModuleWarnings { + module, + count: 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)) +} + +// 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); +} + +#[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: mutant a valid 2.x policy file logs a failure of the 1.x reader, or a file that reader refuses logs none +#[test] +fn failure_of_the_1x_reader_is_logged_only_for_a_file_that_is_no_valid_document() { + let cases = [ + ("valid 2.x document", document("corp-baseline", 3), 0), + ( + "2.x document that is not valid", + document_with_unknown_key("corp-baseline", 3), + 1, + ), + ("file that is not JSON", "{".to_owned(), 1), + ( + "1.x file with an empty publisher", + replacing( + &format_1_text("legacy", 2), + r#""Publisher": "Test""#, + r#""Publisher": """#, + ), + 1, + ), + ]; + let (warnings, _counting) = count_observation_warnings(); + + for (name, text, expected) in cases { + let before = warnings.load(Ordering::SeqCst); + + store(&FileDouble::holding(Some(&text))); + + assert_eq!(warnings.load(Ordering::SeqCst) - before, expected, "{name}"); + } +} + +// 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() { + 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_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() { + 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 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() { + 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_eq!(after.read_only_reason, Some(ReadOnlyReason::UnsafePath)); + 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@09d6488736cf:policies/CONTRACT.wire.md §errors +#[tokio::test] +async fn refused_revision_is_answered_with_the_state_after_the_request() { + let storage = FileDouble::read_only( + &document("corp-baseline", 3), + PolicyWriteCapability::ReadOnly, + PolicyReadOnlyReason::InsufficientPermissions, + ); + let store = store(&storage); + let before = management(&store); + + storage.allow_writes(); + let outcome = replace(&store, &before.store_token, &document("corp-baseline", 3)).await; + + assert_eq!(code(&outcome), "RevisionNotHigher"); + let after = state_after(outcome).expect("a refused revision carries the state after the request"); + // oracle: contract Devolutions/now-libraries@09d6488736cf:policies/CONTRACT.wire.md §replacement + assert_eq!(after.read_only_reason, None); + assert_eq!(after, management(&store)); + // oracle: mutant a refused replacement gives the unchanged file another store token + assert_eq!(after.store_token, before.store_token); +} + +// oracle: contract Devolutions/now-libraries@09d6488736cf:policies/CONTRACT.wire.md §replacement +#[tokio::test] +async fn state_read_after_an_invalid_document_is_the_one_the_request_was_decided_on() { + let storage = FileDouble::read_only( + &document("corp-baseline", 3), + PolicyWriteCapability::ReadOnly, + PolicyReadOnlyReason::InsufficientPermissions, + ); + let store = store(&storage); + let expected = management(&store).store_token; + + storage.allow_writes(); + let outcome = replace(&store, &expected, &document_with_unknown_key("corp-baseline", 4)).await; + + assert_eq!(code(&outcome), "InvalidPolicy"); + let after = management(&store); + assert_eq!(after.read_only_reason, None); + // oracle: mutant a refused replacement gives the unchanged file another store token + assert_eq!(after.store_token, expected); +} + +// 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 cases = [ + ( + "write that the change makes fail", + Fault::ChangedBeforeWrite as fn(Vec) -> Fault, + ), + ( + "write that fails without telling that the file changed", + Fault::ChangedBeforeFailedWrite, + ), + ]; + + 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())); + + 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 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)), + ), + ]; + + 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())); + + 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 +#[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@09d6488736cf:policies/CONTRACT.wire.md §replacement +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +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 (entered, release) = storage.hold_next_write(); + + // The first replacement runs on a worker thread, which its write parks while the test body goes on here. + let mut first = tokio::spawn({ + let store = Arc::clone(&store); + let expected = expected.clone(); + async move { replace(&store, &expected, &document("corp-baseline", 4)).await } + }); + tokio::select! { + entered = entered => entered.expect("the storage keeps the gate until a write enters it"), + outcome = &mut first => panic!("the first replacement ended before it wrote: {outcome:?}"), + } + + // The second replacement arrives while the first is writing, and gets no further than the first lets it. + let sent_second = document("corp-baseline", 5); + let mut second = std::pin::pin!(replace(&store, &expected, &sent_second)); + let arrived = std::future::poll_fn(|context| Poll::Ready(second.as_mut().poll(context))).await; + // oracle: mutant the store lets a second replacement observe the storage while the first one is writing + assert!( + arrived.is_pending(), + "the second replacement ended while the first was writing: {arrived:?}" + ); + assert_eq!(storage.writes(), 0); + + release.send(()).expect("the first replacement waits in its write"); + let first_outcome = first.await.expect("the first replacement ends without a panic"); + let second_outcome = second.await; + + assert_eq!(code(&first_outcome), "Replaced"); + assert_eq!(code(&second_outcome), "StaleStoreToken"); + 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 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), + ( + "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 without a required key that is not the format version", + replacing(&document("corp-baseline", 3), r#""Publisher": "Test", "#, ""), + unwritable, + ), + ( + "document with a number of any magnitude", + document_with_huge_revision(), + unwritable, + ), + ( + "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(&replacing(&document("corp-baseline", 3), 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, + ), + ( + "document that gives format version 2.0.0 twice", + document_with_format_versions("2.0.0", "2.0.0"), + 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, + ), + // 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", + 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, + ), + // 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. + ( + "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, + ), + // 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. + ( + "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", + replacing(&document("corp-baseline", 3), "2.0.0", "1.0.0"), + writable, + ), + ( + "file with a format version that is no string", + replacing(&document("corp-baseline", 3), 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()), + ( + "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, + 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) + ] + ); +} + +#[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() { + 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..255e31384 --- /dev/null +++ b/crates/now-package-broker/src/policy_store/format_1.rs @@ -0,0 +1,117 @@ +//! 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 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 { + /// 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) +} + +/// 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"`, 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`, 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 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_a_key = false; + + for error in errors { + match error.code { + PolicyErrorCode::DocumentTooLarge + | PolicyErrorCode::MalformedDocument + | PolicyErrorCode::UnsupportedFormatVersion => return false, + PolicyErrorCode::MissingKey if error.pointer == FORMAT_VERSION_POINTER => return false, + PolicyErrorCode::DuplicateKey => repeats_a_key = true, + PolicyErrorCode::MissingKey + | PolicyErrorCode::UnknownKey + | PolicyErrorCode::ConflictingKeys + | PolicyErrorCode::WrongType + | PolicyErrorCode::InvalidValue + | PolicyErrorCode::DuplicateRuleId => {} + } + } + + !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 +/// `"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/mod.rs b/crates/now-package-broker/src/policy_store/mod.rs index eae85bbe1..b050b0c22 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,15 @@ 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, + source: PolicyConfigurationSource, + configured_path: &Path, + observation: &mut Observation, + bytes: &[u8], + ) -> Result; } struct FilePolicyStorage { @@ -110,6 +127,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, 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, + 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(source, configured_path, &self.probe_cache)) + } } impl FilePolicyStorage { @@ -150,8 +205,11 @@ struct Snapshot { write_capability: PolicyWriteCapability, read_only_reason: Option, configured_path: PathBuf, + /// INVARIANT: A hyphenated UUID: 36 ASCII hexadecimal digits and hyphens, the first of them a hexadecimal digit. store_token: PolicyStoreToken, fingerprint: DiskFingerprint, + /// What the same observation holds for the 2.0 endpoints. + document: DocumentView, } #[derive(Clone, Copy, PartialEq, Eq)] @@ -168,13 +226,37 @@ 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, + /// 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, } impl PolicyStore { @@ -190,6 +272,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 +290,17 @@ 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 { + document_path: v2::PolicyPath::parse(&configured_path.display().to_string()), 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 +317,31 @@ 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 { + Ok(self.management_of(&self.snapshot(), self.document_path.clone()?)) + } + + fn management_of(&self, snapshot: &Snapshot, path: v2::PolicyPath) -> v2::PolicyManagement { + // The store token of a snapshot is a hyphenated UUID, which has the length and the characters of a store token. + 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) { let path = self.configured_path.clone(); let observation = if retain_for_write { @@ -270,12 +389,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 +413,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 +646,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 +667,191 @@ 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. + /// + /// `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") + )] + pub(crate) async fn replace_document( + &self, + expected_store_token: &v2::StoreToken, + document: &str, + 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 = 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(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(management_of(&self.snapshot()))); + } + + let candidate = match AcceptedPolicy::from_bytes(document.as_bytes()) { + Ok(candidate) => candidate, + Err(errors) => { + // Whether the file can be written is no part of its fingerprint, so the published state may still give + // a reason the storage no longer has, although the store token matched. + // Publishing the observation makes the state read after this request the one it was decided on. + self.publish_observation(observation); + 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)) { + // The answer carries the state after the request, which is that of the observation, as for an invalid + // document. + self.publish_observation(observation); + audit.document_failed_at(&path, write, FailureReason::RevisionConflict); + return Ok(DocumentReplacement::RevisionNotHigher(management_of(&self.snapshot()))); + } + + 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(_))) => { + 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(management_of(&self.snapshot()))); + } + 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(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. + let snapshot = Arc::new(snapshot_from_observation( + reobserved, + random_store_token(), + self.converter, + )); + *self.snapshot.write().expect("policy store snapshot lock poisoned") = snapshot; + + // 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(management_of(&self.snapshot()))) + } + + /// 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 +867,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 +905,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 +951,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 +1162,18 @@ impl PolicyStorage for TestStorage { .map_err(WriteFailure::ConcurrentChange)?; self.persist(observation, bytes) } + + fn write_document( + &self, + _source: PolicyConfigurationSource, + _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 +1248,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 +1285,7 @@ fn test_observation(policy: Option, invalid: bool, marker: u8) - windows::test_security_digest(1), )), retained_target: None, + document, } } @@ -965,6 +1305,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..4512d4999 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, @@ -44,7 +45,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::validation; +use crate::policy_store::document::{self, DocumentObservation, FileContent}; +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). pub(super) const POLICY_FILE_NAME: &str = "package-broker-policy.json"; @@ -1159,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. @@ -1167,6 +1172,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 @@ -1287,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, @@ -1328,13 +1336,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(".")); @@ -1536,6 +1552,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 +1821,35 @@ 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) => { + let is_format_2 = format_1::is_format_2(content, &errors); + (FileContent::Invalid(errors), is_format_2) + } + }; + // A valid 2.x document is not a file that failed, so the refusal of its bytes by the 1.x reader is not logged. + // The refusal of any other file is, because nothing else logs that the file was refused. + let log_format_1_refusal = !matches!(accepted, FileContent::Accepted(_)); + // 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 +1871,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) { @@ -1833,8 +1881,14 @@ fn observation_from_parts( // API: it is heuristically derived from attacker/corruption-controlled bytes // 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); + if log_format_1_refusal { + tracing::warn!(%parse_error, "Configured policy file content failed to parse"); + } + return invalid_with( + validation::DiskFailureReason::MalformedContent, + hosting_dir, + unread_by_format_1, + ); } }; @@ -1844,11 +1898,17 @@ fn observation_from_parts( // not exposed: they are derived from the committed file's own content, which // `GET /v1/policy/management` exposes to any authenticated (but not necessarily // elevated/Administrator, and not necessarily the file's author) caller. - tracing::warn!( - findings = ?committed_validation.findings, - "Configured policy file failed authoritative semantic validation" + if log_format_1_refusal { + tracing::warn!( + findings = ?committed_validation.findings, + "Configured policy file failed authoritative semantic validation" + ); + } + return invalid_with( + validation::DiskFailureReason::FailedSemanticValidation, + hosting_dir, + unread_by_format_1, ); - return invalid_with(validation::DiskFailureReason::FailedSemanticValidation, hosting_dir); } DiskObservation { @@ -1868,6 +1928,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,14 +1959,25 @@ 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, - validation::DiskFailureReason::Unreadable, - InvalidContext::default(), - write_capability, - Some(read_only_reason), - ), + Ok(_) | Err(_) => { + let mut observation = invalid_observation( + configured_path, + validation::DiskFailureReason::Unreadable, + InvalidContext::default(), + write_capability, + Some(read_only_reason), + ); + // The 1.x management state reports an entry under a directory that failed verification as unreadable. + // The storage never tried to open it, so the 2.0 management state reports its location as failing the + // storage security checks. + observation.document.content = FileContent::Unusable(InvalidReason::InsecureStorage); + observation + } } } @@ -1937,6 +2013,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 +2061,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 +2289,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 +2391,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)?; @@ -2962,15 +3090,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)?; - let policy = serde_json::from_slice::(&content) + 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. + if policy_2::validate(content).is_empty() { + return Ok(()); + } + 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> { @@ -3072,6 +3212,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 +3287,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 +3319,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 +3377,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, }) } @@ -3213,6 +3398,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)] @@ -4055,6 +4320,89 @@ mod tests { assert!(!marker_path.exists()); } + // 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(), + 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"), + ), + ]; + + 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}"); + } + } + + // 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 _; @@ -4618,6 +4966,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(); @@ -4698,6 +5053,74 @@ 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_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_OF_UNSUPPORTED_FORM + .into_iter() + .chain(paths_of_unsupported_extension) + { + 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}" + ); + } + } + + // 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 @@ -4854,6 +5277,14 @@ mod tests { assert!(format!("{error:#}").contains("reparse point")); } + /// The reason the 2.0 state gives for a file the storage does not rely on. + fn unusable_reason(observation: &DiskObservation) -> Option { + match observation.document.content { + FileContent::Unusable(reason) => Some(reason), + FileContent::Missing | FileContent::Accepted(_) | FileContent::Format1(_) | FileContent::Invalid(_) => None, + } + } + #[test] fn unverifiable_directory_classifies_dangling_reparse_as_invalid() { let dir = temp_dir(); @@ -4869,6 +5300,13 @@ mod tests { assert_eq!(observation.state, PolicyManagementState::Invalid); assert_eq!(observation.write_capability, PolicyWriteCapability::ReadOnly); assert_eq!(observation.read_only_reason, Some(PolicyReadOnlyReason::UnsafePath)); + // oracle: contract Devolutions/now-libraries@09d6488736cf:policies/CONTRACT.wire.md §management-state + assert_eq!(unusable_reason(&observation), Some(InvalidReason::InsecureStorage)); + // oracle: mutant the finding the 1.x endpoints report changes with the reason of the 2.0 state + assert_eq!( + observation.invalid_diagnostics.expect("invalid diagnostics").findings[0].message, + "the configured policy file could not be opened or read" + ); } #[test] @@ -4886,6 +5324,13 @@ mod tests { assert_eq!(observation.state, PolicyManagementState::Invalid); assert_eq!(observation.write_capability, PolicyWriteCapability::ReadOnly); assert_eq!(observation.read_only_reason, Some(PolicyReadOnlyReason::UnsafePath)); + // oracle: contract Devolutions/now-libraries@09d6488736cf:policies/CONTRACT.wire.md §management-state + assert_eq!(unusable_reason(&observation), Some(InvalidReason::InsecureStorage)); + // oracle: mutant the finding the 1.x endpoints report changes with the reason of the 2.0 state + assert_eq!( + observation.invalid_diagnostics.expect("invalid diagnostics").findings[0].message, + "the configured policy file could not be opened or read" + ); } #[test] 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 new file mode 100644 index 000000000..b75f79586 --- /dev/null +++ b/crates/now-package-broker/src/v2/mod.rs @@ -0,0 +1,8 @@ +//! 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 execution; +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..03b62a23d --- /dev/null +++ b/crates/now-package-broker/src/v2/policy.rs @@ -0,0 +1,491 @@ +//! 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}; + +/// 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::>())?; + + // Two conversions stay fallible by their types: the bytes to text, and the revision to the range a response + // carries. + // Neither fails for bytes the evaluator accepted, which are UTF-8 and give a revision from 1 to 2147483647, + // the range of `Revision`. + // + // UNTESTED: a document the evaluator accepts and one of the two conversions refuses is reported as malformed. + // No test reaches it, because the evaluator accepts no such document, and the broker could report neither the + // text nor the identity of a policy it held from one. + // When the evaluator changes what it accepts, check that both conversions still cover it. + let unreadable = || { + vec![PolicyError { + code: PolicyErrorCode::MalformedDocument, + pointer: String::new(), + }] + }; + let document = core::str::from_utf8(bytes).map_err(|_| unreadable())?; + let revision = Revision::new(policy.revision()).map_err(|_| unreadable())?; + + Ok(Self { + document: document.to_owned(), + id: policy.id().to_owned(), + revision, + policy, + }) + } + + /// 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, + } +} + +#[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: 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. + 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 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(), + 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), std::slice::from_ref(&expected), "{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}"); + } + } +} 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.