Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
17567c6
build(agent): depend on the 2.x policy evaluator
CBenoit Nov 30, 2026
ee357d0
refactor(agent): add the module for the 2.0 request encoding
CBenoit Nov 30, 2026
ee900c2
build(agent): take the 2.0 package broker API types
CBenoit Nov 30, 2026
31c24f0
feat(agent): read and evaluate 2.x policies for the 2.0 endpoints
CBenoit Nov 30, 2026
6c7395b
feat(agent): hold and replace 2.x policies in the policy store
CBenoit Nov 30, 2026
35b2a6a
fix(agent): tell a 2.x policy file by the errors of its own reader
CBenoit Nov 30, 2026
f44f101
fix(agent): tell a 2.x policy file that repeats a key by its format v…
CBenoit Nov 30, 2026
907ea6b
fix(agent): report a policy path of unsupported form as an unsupporte…
CBenoit Nov 30, 2026
74ae1e8
docs(agent): say what the policy store does for the 2.0 endpoints
CBenoit Nov 30, 2026
e6093c0
fix(agent): tell a 2.x policy file that repeats any key by its format…
CBenoit Nov 30, 2026
3da6ae2
test(agent): cover the replacement outcomes and policy errors no test…
CBenoit Nov 30, 2026
297717f
test(agent): pin the 1.x view of a policy path of unsupported form
CBenoit Nov 30, 2026
01cd992
test(agent): compare the format 2.x rule with the reader on escapes a…
CBenoit Nov 30, 2026
47fec3e
docs(agent): correct what the storage says of an unsupported policy path
CBenoit Nov 30, 2026
d3cd610
test(agent): keep the policy store test fixtures and comments to what…
CBenoit Dec 1, 2026
41b5e66
build(agent): pin the 2.0 policy crates to revisions that read a requ…
CBenoit Dec 1, 2026
89e0bd4
Merge branch 'claude/broker-v2-base-7702d2' into claude/broker-v2-pol…
CBenoit Dec 2, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 9 additions & 3 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 5 additions & 4 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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 = "5b23b1a616ca97590d4d6b9e610cd07772d30453" }
now-policy-api = { git = "https://github.com/Devolutions/now-libraries", rev = "5b23b1a616ca97590d4d6b9e610cd07772d30453" }
now-policy-server-template = { git = "https://github.com/Devolutions/now-libraries", rev = "5b23b1a616ca97590d4d6b9e610cd07772d30453" }

[workspace.lints.rust]
# Declare the custom cfgs.
Expand Down
3 changes: 3 additions & 0 deletions crates/now-package-broker/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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 = "25e75110c067239e44e42f005abbf566f32f803a" }
now-policy-server-template = "0.7.1"
parking_lot = "0.12"
regex = "1"
Expand Down
78 changes: 78 additions & 0 deletions crates/now-package-broker/src/audit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Comment on lines +190 to +191

/// 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
Expand Down Expand Up @@ -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("<none>", |(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
Expand Down
2 changes: 2 additions & 0 deletions crates/now-package-broker/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
223 changes: 223 additions & 0 deletions crates/now-package-broker/src/policy_store/document.rs
Original file line number Diff line number Diff line change
@@ -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<ReadOnlyReason>,
}

/// 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<AcceptedPolicy>),
/// 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<PolicyError>),
}

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<PolicyReadOnlyReason>,
) -> 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<PolicyReadOnlyReason>) -> Option<ReadOnlyReason> {
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<ReadOnlyReason>,
}

pub(super) enum DocumentState {
Active {
policy: Arc<AcceptedPolicy>,
/// 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<PolicyError>),
/// 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<AcceptedPolicy>> {
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<AcceptedPolicy> {
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)
}
Loading
Loading