From 654862bfa15fe1d42f57285bb8d2f6bcdfd87629 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Tue, 1 Dec 2026 05:12:53 +0900 Subject: [PATCH 01/38] feat(agent): answer requests under /v2/ in the 2.0 encoding A request whose path starts with `/v2/` no longer reaches the 1.x router. It gets the outcome the wire contract ranks first: `BrokerBusy`, `UnknownEndpoint`, `UnsupportedMediaType`, `Unauthenticated` and `AdministratorRequired` are answered without reading the body, then `RequestTooLarge` and `BadRequest`. An endpoint that passes these checks answers `InternalError`, because none is served yet, and a panic while answering does too, so such a request never gets a 1.x body. A refused policy replacement leaves a denial record naming `POST /v2/policy`, counted apart from the denials of the 1.x route, whose records do not change. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- crates/now-package-broker/src/audit.rs | 65 +- crates/now-package-broker/src/server/mod.rs | 15 +- crates/now-package-broker/src/v2/mod.rs | 1 + .../now-package-broker/src/v2/routes/mod.rs | 332 ++++++++++ .../now-package-broker/src/v2/routes/tests.rs | 592 ++++++++++++++++++ 5 files changed, 991 insertions(+), 14 deletions(-) create mode 100644 crates/now-package-broker/src/v2/routes/mod.rs create mode 100644 crates/now-package-broker/src/v2/routes/tests.rs diff --git a/crates/now-package-broker/src/audit.rs b/crates/now-package-broker/src/audit.rs index 3df0b4d96..a57b68b70 100644 --- a/crates/now-package-broker/src/audit.rs +++ b/crates/now-package-broker/src/audit.rs @@ -517,6 +517,8 @@ fn wait_for_emission(pending: &AtomicUsize, grace: std::time::Duration) { struct WriteAuditState { actor_sid: String, actor_exe: String, + /// The request the write arrived as. + intent: &'static str, path: PathBuf, terminal_recorded: AtomicBool, recorder: Arc, @@ -529,7 +531,7 @@ impl Drop for WriteAuditState { policy_events::policy_write_denied( &self.actor_sid, &self.actor_exe, - INTENT, + self.intent, &self.path, DenialReason::RequestRejected.as_str(), ), @@ -552,15 +554,26 @@ impl WriteAudit { } fn begin_with_recorder(actor_sid: &Sid, actor_exe: &Path, path: &Path, recorder: Arc) -> Self { + Self::begin_as(INTENT, actor_sid, actor_exe, path, recorder) + } + + fn begin_as( + intent: &'static str, + actor_sid: &Sid, + actor_exe: &Path, + path: &Path, + recorder: Arc, + ) -> Self { let state = Arc::new(WriteAuditState { actor_sid: bounded(actor_sid.to_string(), MAX_SID_BYTES), actor_exe: bounded(actor_exe.display().to_string(), MAX_PATH_BYTES), + intent, path: bounded_path(path), terminal_recorded: AtomicBool::new(false), recorder, }); state.record( - policy_events::policy_write_attempted(&state.actor_sid, &state.actor_exe, INTENT, &state.path), + policy_events::policy_write_attempted(&state.actor_sid, &state.actor_exe, intent, &state.path), EntryClass::Admission, ); Self(state) @@ -756,11 +769,22 @@ impl WriteAuditState { /// logged. The denials that follow within [`DENIAL_SUMMARY_INTERVAL`] are counted and logged as /// one summary once the interval elapses or the broker stops. pub(crate) fn write_denied(actor_sid: &Sid, actor_exe: &Path, path: &Path, reason: DenialReason) { + write_denied_as(INTENT, actor_sid, actor_exe, path, reason); +} + +/// Records that a caller was refused a policy replacement of the 2.0 encoding before its attempt was recorded. +/// +/// Its denials are logged and counted as [`write_denied`] does, apart from those of the 1.x route. +pub(crate) fn document_write_denied(actor_sid: &Sid, actor_exe: &Path, path: &Path, reason: DenialReason) { + write_denied_as(DOCUMENT_INTENT, actor_sid, actor_exe, path, reason); +} + +fn write_denied_as(intent: &'static str, actor_sid: &Sid, actor_exe: &Path, path: &Path, reason: DenialReason) { let actor_sid = bounded(actor_sid.to_string(), MAX_SID_BYTES); let actor_exe = bounded(actor_exe.display().to_string(), MAX_PATH_BYTES); let path = bounded_path(path); record_denials(with_denials(|denials| { - denials.deny(actor_sid, &actor_exe, &path, reason, std::time::Instant::now()) + denials.deny_as(intent, actor_sid, &actor_exe, &path, reason, std::time::Instant::now()) })); } @@ -813,6 +837,8 @@ fn with_denials(f: impl FnOnce(&DenialThrottle) -> R) -> R { #[derive(Clone, Debug, PartialEq, Eq, Hash)] struct DenialKey { + /// The request the denied write arrived as. + intent: &'static str, actor_sid: String, reason: DenialReason, } @@ -825,17 +851,31 @@ struct DenialWindow { /// Collapses the repeated denials of each caller into its first denial and a periodic summary. /// -/// INVARIANT: at most [`MAX_DENIAL_WINDOWS`] windows plus one overflow window per reason are open. +/// INVARIANT: at most [`MAX_DENIAL_WINDOWS`] windows plus one overflow window per intent and reason are open. #[derive(Default)] struct DenialThrottle(parking_lot::Mutex>); impl DenialThrottle { - /// Counts one denial, and returns the entries to log for it. + /// Counts one denial of a write through the 1.x route, as [`Self::deny_as`] does. + #[cfg(test)] + fn deny( + &self, + actor_sid: String, + actor_exe: &str, + path: &Path, + reason: DenialReason, + now: std::time::Instant, + ) -> Vec { + self.deny_as(INTENT, actor_sid, actor_exe, path, reason, now) + } + + /// Counts one denial of a write that arrived as `intent`, and returns the entries to log for it. /// - /// The denial is logged when it opens a window for its caller and reason. The summaries of the + /// The denial is logged when it opens a window for its intent, caller and reason. The summaries of the /// windows that elapsed are returned first. - fn deny( + fn deny_as( &self, + intent: &'static str, actor_sid: String, actor_exe: &str, path: &Path, @@ -844,14 +884,18 @@ impl DenialThrottle { ) -> Vec { let mut windows = self.0.lock(); let mut entries = summarize(&mut windows, now, false); - let key = DenialKey { actor_sid, reason }; + let key = DenialKey { + intent, + actor_sid, + reason, + }; if let Some(window) = windows.get_mut(&key) { window.suppressed = window.suppressed.saturating_add(1); } else if windows.len() < MAX_DENIAL_WINDOWS { entries.push(policy_events::policy_write_denied( &key.actor_sid, actor_exe, - INTENT, + intent, path, reason.as_str(), )); @@ -866,6 +910,7 @@ impl DenialThrottle { // The overflow window never logs a denial individually, so it counts this one as well. let window = windows .entry(DenialKey { + intent, actor_sid: OVERFLOW_ACTOR_SID.to_owned(), reason, }) @@ -900,7 +945,7 @@ fn summarize(windows: &mut HashMap, now: std::time::Ins if window.suppressed > 0 { entries.push(policy_events::policy_write_denied_summary( &key.actor_sid, - INTENT, + key.intent, key.reason.as_str(), window.suppressed, elapsed.as_secs(), diff --git a/crates/now-package-broker/src/server/mod.rs b/crates/now-package-broker/src/server/mod.rs index 9e47fa0ed..98e34b6da 100644 --- a/crates/now-package-broker/src/server/mod.rs +++ b/crates/now-package-broker/src/server/mod.rs @@ -224,8 +224,10 @@ struct EvaluatedRequest { const BUSY_RETRY_AFTER_SECONDS: &str = "1"; /// Build a router that answers every request with a busy error, for clients over a connection limit. +/// +/// A request of the 2.0 encoding is answered in that encoding. pub(crate) fn build_busy_router() -> axum::Router { - axum::Router::new().fallback(|| async { + let busy = axum::Router::new().fallback(|| async { ( StatusCode::SERVICE_UNAVAILABLE, [(axum::http::header::RETRY_AFTER, BUSY_RETRY_AFTER_SECONDS)], @@ -234,7 +236,9 @@ pub(crate) fn build_busy_router() -> axum::Router { "package broker is busy; retry later", )), ) - }) + }); + + crate::v2::routes::route_busy(busy) } /// Build the axum router for a single authenticated pipe client. @@ -260,14 +264,17 @@ fn build_router(state: Arc, client: PipeClient, identity: Option Response { diff --git a/crates/now-package-broker/src/v2/mod.rs b/crates/now-package-broker/src/v2/mod.rs index b75f79586..f34e5a600 100644 --- a/crates/now-package-broker/src/v2/mod.rs +++ b/crates/now-package-broker/src/v2/mod.rs @@ -5,4 +5,5 @@ pub mod execution; pub mod policy; +pub(crate) mod routes; pub mod wire; diff --git a/crates/now-package-broker/src/v2/routes/mod.rs b/crates/now-package-broker/src/v2/routes/mod.rs new file mode 100644 index 000000000..55bc2ca69 --- /dev/null +++ b/crates/now-package-broker/src/v2/routes/mod.rs @@ -0,0 +1,332 @@ +//! The endpoints of the 2.0 encoding ([§endpoints]). +//! +//! A request whose path starts with `/v2/` is answered here, with a response of the 2.0 encoding whatever happens to it, and a request with another path never reaches this module ([§transport]). +//! +//! [§endpoints]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#endpoints +//! [§transport]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#transport + +use std::future::Future; +use std::panic::AssertUnwindSafe; +use std::path::PathBuf; +use std::pin::Pin; +use std::sync::Arc; +use std::task::{Context, Poll}; + +use axum::body::{Body, Bytes, HttpBody as _, to_bytes}; +use axum::extract::Request; +use axum::http::{HeaderMap, HeaderValue, StatusCode, header}; +use axum::response::Response; +use now_policy_api::v2; +use tower_service::Service as _; +use tracing::{error, warn}; + +use super::wire; +use crate::audit::DenialReason; +use crate::auth::PipeClient; +use crate::server::BrokerState; + +/// What the path of every request of the 2.0 encoding starts with ([§transport]). +/// +/// [§transport]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#transport +const PATH_PREFIX: &str = "/v2/"; + +/// The body of the response sent when no other response can be written. +const INTERNAL_ERROR_BODY: &str = r#"{"Code":"InternalError","Message":"the broker failed to write its response"}"#; + +/// Returns a router that answers the requests of the 2.0 encoding of one connected client, and sends every other request to `other`. +pub(crate) fn route_connection(state: Arc, client: PipeClient, other: axum::Router) -> axum::Router { + let connection = Arc::new(Connection { state, client }); + + axum::Router::new().fallback(move |request: Request| { + let connection = Arc::clone(&connection); + let other = other.clone(); + + async move { + if is_v2(&request) { + CatchPanic(Box::pin(connection.respond(request))).await + } else { + forward(other, request).await + } + } + }) +} + +/// Returns a router that answers every request of the 2.0 encoding with `BrokerBusy`, and sends every other request to `other` ([§errors]). +/// +/// The response is sent without reading the request body, and nothing is started or changed. +/// +/// [§errors]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#errors +pub(crate) fn route_busy(other: axum::Router) -> axum::Router { + axum::Router::new().fallback(move |request: Request| { + let other = other.clone(); + + async move { + if is_v2(&request) { + error_response(v2::ErrorCode::BrokerBusy, "the broker is busy; send the request again") + } else { + forward(other, request).await + } + } + }) +} + +fn is_v2(request: &Request) -> bool { + request.uri().path().starts_with(PATH_PREFIX) +} + +async fn forward(mut other: axum::Router, request: Request) -> Response { + match other.call(request).await { + Ok(response) => response, + Err(infallible) => match infallible {}, + } +} + +/// One connected client and the broker it reached. +struct Connection { + state: Arc, + client: PipeClient, +} + +impl Connection { + /// Answers one request whose path starts with [`PATH_PREFIX`]. + /// + /// The checks run in the order of the outcomes of [§errors], so the earliest outcome that applies is the response. + /// Nothing reads the body before the client is known to be allowed to send one. + /// + /// [§errors]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#errors + async fn respond(self: Arc, request: Request) -> Response { + let (parts, body) = request.into_parts(); + + let Ok(route) = wire::route(parts.method.as_str(), parts.uri.path()) else { + return error_response(v2::ErrorCode::UnknownEndpoint, "the method and path match no endpoint"); + }; + let endpoint = route.endpoint; + let body_limit = endpoint.body_limit(); + + if 0 < body_limit && !has_json_media_type(&parts.headers) { + return error_response( + v2::ErrorCode::UnsupportedMediaType, + "the content type of the request is not application/json", + ); + } + + if let Some(response) = self.refuse_client(endpoint) { + return response; + } + + let body = match read_body(body, body_limit).await { + Ok(body) => body, + Err(BodyError::TooLarge) => { + return error_response( + v2::ErrorCode::RequestTooLarge, + "the request body is larger than the limit of its endpoint", + ); + } + Err(BodyError::Unreadable) => { + return error_response(v2::ErrorCode::BadRequest, "the request body could not be read"); + } + }; + + self.serve(&route, &body).await + } + + /// Returns the response to a client that `endpoint` does not answer ([§authentication]). + /// + /// A client refused the policy replacement leaves a denial record. + /// + /// [§authentication]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#authentication + fn refuse_client(&self, endpoint: v2::Endpoint) -> Option { + let must_be_administrator = match endpoint.client() { + v2::ClientRequirement::Any => return None, + v2::ClientRequirement::Authenticated => false, + v2::ClientRequirement::ElevatedAdministrator => true, + }; + + if let Err(error) = self.client.validate_connection(self.state.skip_signature_validation) { + warn!(error = format!("{error:#}"), "Rejected package broker request"); + if must_be_administrator { + self.record_replacement_denial(DenialReason::AuthenticationFailed); + } + return Some(error_response( + v2::ErrorCode::Unauthenticated, + "the client process is not authenticated", + )); + } + + if must_be_administrator && !self.client.is_elevated_administrator() { + self.record_replacement_denial(DenialReason::AdministratorRequired); + return Some(error_response( + v2::ErrorCode::AdministratorRequired, + "replacing the policy requires an elevated administrator", + )); + } + + None + } + + fn record_replacement_denial(&self, reason: DenialReason) { + crate::audit::document_write_denied( + self.client.user_sid(), + self.client.executable_path(), + &self.configured_policy_path(), + reason, + ); + } + + fn configured_policy_path(&self) -> PathBuf { + PathBuf::from(self.state.policy_store.management_snapshot().configured_path) + } + + /// Answers a request that passed every check made before its body is read. + async fn serve(&self, route: &wire::Route, body: &[u8]) -> Response { + match route.endpoint { + v2::Endpoint::Health + | v2::Endpoint::Capabilities + | v2::Endpoint::Status + | v2::Endpoint::Cancel + | v2::Endpoint::Management => not_served(), + v2::Endpoint::Evaluate => match wire::read_evaluation_request(body) { + Ok(_request) => not_served(), + Err(error) => bad_request(&error), + }, + v2::Endpoint::Execute => match wire::read_execution_request(body) { + Ok(_request) => not_served(), + Err(error) => bad_request(&error), + }, + v2::Endpoint::ExecuteBypass => match wire::read_bypass_request(body) { + Ok(_request) => not_served(), + Err(error) => bad_request(&error), + }, + v2::Endpoint::Validate => match wire::read_validation_request(body) { + Ok(_request) => not_served(), + Err(error) => bad_request(&error), + }, + v2::Endpoint::Replace => match wire::read_replacement_request(body) { + Ok(_request) => not_served(), + Err(error) => bad_request(&error), + }, + } + } +} + +/// Why a request body was not read. +enum BodyError { + /// The body is larger than the limit of its endpoint. + TooLarge, + /// The client stopped sending the body, or framed it wrongly. + Unreadable, +} + +/// Reads a request body of at most `limit` bytes, counted after the transfer coding is decoded ([§endpoints]). +/// +/// A body whose declared length is over the limit is refused without waiting for its bytes. +/// +/// [§endpoints]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#endpoints +async fn read_body(body: Body, limit: usize) -> Result { + let declared = body.size_hint().lower(); + if !usize::try_from(declared).is_ok_and(|declared| declared <= limit) { + return Err(BodyError::TooLarge); + } + + to_bytes(body, limit).await.map_err(|error| { + let too_large = + std::error::Error::source(&error).is_some_and(|source| source.is::()); + if too_large { + BodyError::TooLarge + } else { + BodyError::Unreadable + } + }) +} + +/// Tells whether the request has the media type `application/json`, whatever its parameters ([§transport]). +/// +/// [§transport]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#transport +fn has_json_media_type(headers: &HeaderMap) -> bool { + headers + .get(header::CONTENT_TYPE) + .and_then(|value| value.to_str().ok()) + .is_some_and(|value| { + let media_type = value + .split_once(';') + .map_or(value, |(media_type, _parameters)| media_type); + media_type + .trim_matches([' ', '\t']) + .eq_ignore_ascii_case("application/json") + }) +} + +fn bad_request(error: &wire::BadRequest) -> Response { + error_response(v2::ErrorCode::BadRequest, &error.to_string()) +} + +/// The response of an endpoint the broker does not answer yet. +fn not_served() -> Response { + error_response(v2::ErrorCode::InternalError, "the broker does not serve this endpoint") +} + +/// Returns the error response for a code whose response has no member besides `Code` and `Message`. +fn error_response(code: v2::ErrorCode, text: &str) -> Response { + error_body(&wire::error_response(code, text)) +} + +/// Returns the response that carries `error`, with the HTTP status its code gives ([§errors]). +/// +/// [§errors]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#errors +fn error_body(error: &v2::ErrorResponse) -> Response { + match StatusCode::from_u16(error.code.http_status()) { + Ok(status) => json(status, error), + Err(_) => unwritable_response(), + } +} + +/// Returns a response whose body is `value` as JSON ([§transport]). +/// +/// [§transport]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#transport +fn json(status: StatusCode, value: &T) -> Response { + match serde_json::to_vec(value) { + Ok(body) => with_json_media_type(status, Body::from(body)), + Err(error) => { + error!(%error, "Failed to write a package broker response"); + unwritable_response() + } + } +} + +fn unwritable_response() -> Response { + with_json_media_type(StatusCode::INTERNAL_SERVER_ERROR, Body::from(INTERNAL_ERROR_BODY)) +} + +fn with_json_media_type(status: StatusCode, body: Body) -> Response { + let mut response = Response::new(body); + *response.status_mut() = status; + response + .headers_mut() + .insert(header::CONTENT_TYPE, HeaderValue::from_static("application/json")); + response +} + +/// Answers `InternalError` when answering a request panics, so that a `/v2/` request never goes without a response of the 2.0 encoding. +struct CatchPanic(Pin>); + +impl> Future for CatchPanic { + type Output = Response; + + fn poll(mut self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll { + let future = self.0.as_mut(); + + match std::panic::catch_unwind(AssertUnwindSafe(|| future.poll(context))) { + Ok(poll) => poll, + Err(_) => { + error!("Answering a package broker request panicked"); + Poll::Ready(error_response( + v2::ErrorCode::InternalError, + "the broker failed to answer the request", + )) + } + } + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/now-package-broker/src/v2/routes/tests.rs b/crates/now-package-broker/src/v2/routes/tests.rs new file mode 100644 index 000000000..026d774dc --- /dev/null +++ b/crates/now-package-broker/src/v2/routes/tests.rs @@ -0,0 +1,592 @@ +use std::sync::Arc; +use std::time::Duration; + +use async_trait::async_trait; +use axum::body::{Body, to_bytes}; +use axum::http::{Method, Request}; +use axum::response::Response; +use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _}; +use tower_service::Service as _; + +use crate::auth::PipeClient; +use crate::executor::{CommandExecutor, ExecutionContext, ExecutionOutput, ProcessStartedCallback}; +use crate::operation_tracker::OperationTracker; +use crate::policy_store::PolicyStore; +use crate::remote_grant::RemoteGrantStore; +use crate::server::{BrokerState, build_busy_router, build_router_for_client, serve_connection}; + +const EVALUATE: &str = "/v2/package-requests/evaluate"; +const EXECUTE: &str = "/v2/package-requests/execute"; +const EXECUTE_BYPASS: &str = "/v2/package-requests/execute-bypass"; +const VALIDATE: &str = "/v2/policy/validate"; +const REPLACE: &str = "/v2/policy"; + +/// The body limit of the endpoints that take a package request. +const PACKAGE_REQUEST_LIMIT: usize = 262_144; + +/// The body limit of the endpoints that take a policy document. +const DOCUMENT_LIMIT: usize = 33_554_432; + +/// An executor for the requests that start nothing. +struct IdleExecutor; + +#[async_trait] +impl CommandExecutor for IdleExecutor { + async fn execute( + &self, + _context: &ExecutionContext, + _process_started: Option, + ) -> anyhow::Result { + anyhow::bail!("this test starts no operation") + } +} + +/// A broker without a policy file that authenticates the test process. +fn state() -> BrokerState { + BrokerState { + policy_store: PolicyStore::for_tests(None), + executor: Arc::new(IdleExecutor), + pipe_name: "test-pipe".to_owned(), + tracker: OperationTracker::new(), + skip_signature_validation: true, + manager_probe_cache: Default::default(), + remote_grants: RemoteGrantStore::new(), + agent_product_code: || Ok(None), + } +} + +/// A broker that authenticates no test client, because the test process has no Devolutions signature. +fn unauthenticating_state() -> BrokerState { + BrokerState { + skip_signature_validation: false, + ..state() + } +} + +fn client() -> PipeClient { + PipeClient::from_current_process().expect("capture the test process") +} + +fn administrator() -> PipeClient { + PipeClient::test_with_authority(true, true).expect("capture the test process") +} + +fn standard_user() -> PipeClient { + PipeClient::test_with_authority(false, false).expect("capture the test process") +} + +/// What the broker answered. +#[derive(Debug)] +struct Reply { + status: u16, + content_type: Option, + body: serde_json::Value, +} + +impl Reply { + /// The members of the response body, sorted. + fn members(&self) -> Vec<&str> { + let mut members: Vec<&str> = self + .body + .as_object() + .expect("the response body is a JSON object") + .keys() + .map(String::as_str) + .collect(); + members.sort_unstable(); + members + } + + /// Checks an error response whose code gives it no member besides `Code` and `Message`. + #[track_caller] + fn assert_error(&self, status: u16, code: &str) { + assert_eq!( + (self.status, &self.body["Code"]), + (status, &serde_json::json!(code)), + "{self:?}" + ); + assert_eq!(self.members(), ["Code", "Message"], "{self:?}"); + assert_eq!(self.content_type.as_deref(), Some("application/json"), "{self:?}"); + let message = self.body["Message"].as_str().expect("Message is a string"); + assert!(message.len() <= 2048, "{self:?}"); + } +} + +async fn reply(response: Response) -> Reply { + let status = response.status().as_u16(); + let content_type = response + .headers() + .get("content-type") + .map(|value| value.to_str().expect("ASCII content type").to_owned()); + let body = to_bytes(response.into_body(), usize::MAX) + .await + .expect("read the response body"); + + Reply { + status, + content_type, + body: serde_json::from_slice(&body).unwrap_or(serde_json::Value::Null), + } +} + +/// Sends one request through the router of a connected client. +async fn send(state: &Arc, client: &PipeClient, request: Request) -> Reply { + let mut router = build_router_for_client(Arc::clone(state), client.clone()); + let response = router.call(request).await.expect("the router is infallible"); + + reply(response).await +} + +fn request(method: Method, path: &str, content_type: Option<&str>, body: impl Into) -> Request { + let mut builder = Request::builder().method(method).uri(path); + if let Some(content_type) = content_type { + builder = builder.header("content-type", content_type); + } + builder.body(body.into()).expect("a valid test request") +} + +fn get(path: &str) -> Request { + request(Method::GET, path, None, Body::empty()) +} + +fn post(path: &str) -> Request { + request(Method::POST, path, None, Body::empty()) +} + +fn post_json(path: &str, body: impl Into) -> Request { + request(Method::POST, path, Some("application/json"), body) +} + +/// Serves `router` on one connection, writes `request` to it and reads the response to the end. +/// +/// The client keeps its end open without writing anything more. +async fn exchange(router: axum::Router, request: &[u8]) -> Reply { + let (mut client, server) = tokio::io::duplex(1 << 16); + let serving = tokio::spawn(serve_connection(server, router)); + + // The broker may answer and close before it has read everything. + let _ = client.write_all(request).await; + let mut response = Vec::new(); + tokio::time::timeout(Duration::from_secs(10), client.read_to_end(&mut response)) + .await + .expect("the broker answers and closes the connection") + .expect("read the response"); + serving.await.expect("the connection is served without a panic"); + + let response = String::from_utf8(response).expect("a UTF-8 response"); + let (head, body) = response.split_once("\r\n\r\n").expect("a response with a body"); + let status = head + .strip_prefix("HTTP/1.1 ") + .and_then(|rest| rest.get(..3)) + .and_then(|status| status.parse().ok()) + .expect("an HTTP/1.1 status line"); + let content_type = head.lines().find_map(|line| { + let (name, value) = line.split_once(':')?; + name.eq_ignore_ascii_case("content-type") + .then(|| value.trim().to_owned()) + }); + + Reply { + status, + content_type, + body: serde_json::from_str(body).unwrap_or(serde_json::Value::Null), + } +} + +/// The header of a request that announces a body of 16 bytes, which the test never sends. +fn header_announcing_a_body(path: &str, content_type: &str) -> Vec { + format!("POST {path} HTTP/1.1\r\nHost: broker\r\nContent-Type: {content_type}\r\nContent-Length: 16\r\n\r\n") + .into_bytes() +} + +/// A request to `path` whose body is `chunks`, sent with the chunked transfer coding. +fn chunked(path: &str, chunks: &[&[u8]]) -> Vec { + let mut request = format!( + "POST {path} HTTP/1.1\r\nHost: broker\r\nContent-Type: application/json\r\nTransfer-Encoding: chunked\r\n\r\n" + ) + .into_bytes(); + for chunk in chunks { + request.extend_from_slice(format!("{:x}\r\n", chunk.len()).as_bytes()); + request.extend_from_slice(chunk); + request.extend_from_slice(b"\r\n"); + } + request.extend_from_slice(b"0\r\n\r\n"); + request +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §endpoints +#[tokio::test] +async fn a_method_and_path_that_match_no_endpoint_are_unknown_endpoint() { + let state = Arc::new(state()); + + for (method, path) in [ + (Method::GET, "/v2/"), + (Method::GET, "/v2/unknown"), + (Method::POST, "/v2/health"), + (Method::GET, "/v2/health/"), + (Method::GET, "/v2/Health"), + (Method::GET, "/v2/policy"), + (Method::PUT, "/v2/policy"), + (Method::GET, "/v2/operations/"), + ] { + let reply = send(&state, &client(), request(method, path, None, Body::empty())).await; + + reply.assert_error(404, "UnknownEndpoint"); + } +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §errors +#[tokio::test] +async fn unknown_endpoint_wins_over_the_media_type_and_the_client() { + let state = Arc::new(unauthenticating_state()); + + let reply = send( + &state, + &client(), + request(Method::POST, "/v2/unknown", Some("text/plain"), "{"), + ) + .await; + + reply.assert_error(404, "UnknownEndpoint"); +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §transport +#[tokio::test] +async fn a_body_endpoint_without_the_json_media_type_is_unsupported_media_type() { + let state = Arc::new(state()); + + for content_type in [ + None, + Some("text/plain"), + Some("application/jsonx"), + Some("application/problem+json"), + Some("application"), + Some("; application/json"), + ] { + let reply = send(&state, &client(), request(Method::POST, EVALUATE, content_type, "{}")).await; + + assert_eq!( + (reply.status, &reply.body["Code"]), + (415, &serde_json::json!("UnsupportedMediaType")), + "{content_type:?}" + ); + } +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §transport +#[tokio::test] +async fn the_json_media_type_matches_in_any_case_and_with_any_parameters() { + let state = Arc::new(state()); + + for content_type in [ + "application/json", + "APPLICATION/Json", + "application/json; charset=utf-16", + "application/json;charset=utf-8;version=1", + ] { + // The body is malformed, so the first outcome after the media type is `BadRequest`. + let reply = send( + &state, + &client(), + request(Method::POST, EVALUATE, Some(content_type), "{"), + ) + .await; + + assert_eq!( + (reply.status, &reply.body["Code"]), + (400, &serde_json::json!("BadRequest")), + "{content_type}" + ); + } +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §errors +#[tokio::test] +async fn unsupported_media_type_wins_over_the_client() { + let state = Arc::new(unauthenticating_state()); + + let reply = send( + &state, + &client(), + request(Method::POST, EVALUATE, Some("text/plain"), "{"), + ) + .await; + + reply.assert_error(415, "UnsupportedMediaType"); +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §authentication +#[tokio::test] +async fn an_endpoint_for_authenticated_clients_is_unauthenticated_for_any_other() { + let state = Arc::new(unauthenticating_state()); + + for request in [ + get("/v2/capabilities"), + post_json(EVALUATE, "{}"), + post_json(EXECUTE, "{}"), + post_json(EXECUTE_BYPASS, "{}"), + get("/v2/operations/op-1"), + post("/v2/operations/op-1/cancel"), + get("/v2/policy/management"), + post_json(VALIDATE, "{}"), + post_json(REPLACE, "{}"), + ] { + let target = format!("{} {}", request.method(), request.uri()); + + let reply = send(&state, &administrator(), request).await; + + assert_eq!( + (reply.status, &reply.body["Code"]), + (401, &serde_json::json!("Unauthenticated")), + "{target}" + ); + assert_eq!(reply.members(), ["Code", "Message"], "{target}"); + } +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §errors +#[tokio::test] +async fn unauthenticated_wins_over_an_oversized_body() { + let state = Arc::new(unauthenticating_state()); + + let reply = send( + &state, + &client(), + post_json(EVALUATE, vec![b'x'; PACKAGE_REQUEST_LIMIT + 1]), + ) + .await; + + reply.assert_error(401, "Unauthenticated"); +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §authentication +#[tokio::test] +async fn replacing_the_policy_is_administrator_required_unless_elevated_and_an_administrator() { + let state = Arc::new(state()); + + for (elevated, administrator) in [(false, false), (true, false), (false, true)] { + let client = PipeClient::test_with_authority(elevated, administrator).expect("capture the test process"); + + let reply = send(&state, &client, post_json(REPLACE, "{}")).await; + + reply.assert_error(403, "AdministratorRequired"); + } +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §errors +#[tokio::test] +async fn administrator_required_wins_over_an_oversized_body() { + let state = Arc::new(state()); + + let reply = send( + &state, + &standard_user(), + post_json(REPLACE, vec![b'x'; DOCUMENT_LIMIT + 1]), + ) + .await; + + reply.assert_error(403, "AdministratorRequired"); +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §endpoints +#[tokio::test] +async fn a_body_over_the_limit_of_its_endpoint_is_request_too_large() { + let state = Arc::new(state()); + + for (path, limit) in [ + (EVALUATE, PACKAGE_REQUEST_LIMIT), + (EXECUTE, PACKAGE_REQUEST_LIMIT), + (EXECUTE_BYPASS, PACKAGE_REQUEST_LIMIT), + (VALIDATE, DOCUMENT_LIMIT), + (REPLACE, DOCUMENT_LIMIT), + ] { + // The body is malformed as well, and `RequestTooLarge` wins over `BadRequest`. + let reply = send(&state, &administrator(), post_json(path, vec![b'x'; limit + 1])).await; + + assert_eq!( + (reply.status, &reply.body["Code"]), + (413, &serde_json::json!("RequestTooLarge")), + "{path}" + ); + assert_eq!(reply.members(), ["Code", "Message"], "{path}"); + } +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §endpoints +#[tokio::test] +async fn a_body_of_exactly_the_limit_of_its_endpoint_is_read() { + let state = Arc::new(state()); + + let reply = send( + &state, + &client(), + post_json(EVALUATE, vec![b'x'; PACKAGE_REQUEST_LIMIT]), + ) + .await; + + reply.assert_error(400, "BadRequest"); +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §endpoints +#[tokio::test] +async fn any_body_sent_to_an_endpoint_without_a_request_body_is_request_too_large() { + let state = Arc::new(state()); + + for (method, path) in [ + (Method::GET, "/v2/health"), + (Method::GET, "/v2/capabilities"), + (Method::GET, "/v2/operations/op-1"), + (Method::POST, "/v2/operations/op-1/cancel"), + (Method::GET, "/v2/policy/management"), + ] { + let reply = send(&state, &client(), request(method, path, None, "x")).await; + + assert_eq!( + (reply.status, &reply.body["Code"]), + (413, &serde_json::json!("RequestTooLarge")), + "{path}" + ); + } +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §endpoints +#[tokio::test] +async fn a_chunked_body_is_counted_after_the_transfer_coding_is_decoded() { + let half = vec![b'x'; PACKAGE_REQUEST_LIMIT / 2]; + let router = || build_router_for_client(Arc::new(state()), client()); + + // The decoded body is exactly the limit, although the chunked message is longer. + let at_the_limit = exchange(router(), &chunked(EVALUATE, &[&half, &half])).await; + let over_the_limit = exchange(router(), &chunked(EVALUATE, &[&half, &half, b"x"])).await; + + at_the_limit.assert_error(400, "BadRequest"); + over_the_limit.assert_error(413, "RequestTooLarge"); +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §json +#[tokio::test] +async fn a_malformed_body_is_bad_request() { + let state = Arc::new(state()); + + for path in [EVALUATE, EXECUTE, EXECUTE_BYPASS, VALIDATE, REPLACE] { + let reply = send(&state, &administrator(), post_json(path, "{")).await; + + assert_eq!( + (reply.status, &reply.body["Code"]), + (400, &serde_json::json!("BadRequest")), + "{path}" + ); + assert_eq!(reply.members(), ["Code", "Message"], "{path}"); + } +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §errors +#[tokio::test] +async fn the_first_five_outcomes_are_answered_without_any_byte_of_the_body() { + let router = |state: BrokerState, client: PipeClient| build_router_for_client(Arc::new(state), client); + + for (router, path, content_type, status, code) in [ + (build_busy_router(), EVALUATE, "application/json", 503, "BrokerBusy"), + ( + router(state(), client()), + "/v2/unknown", + "application/json", + 404, + "UnknownEndpoint", + ), + ( + router(state(), client()), + EVALUATE, + "text/plain", + 415, + "UnsupportedMediaType", + ), + ( + router(unauthenticating_state(), client()), + EVALUATE, + "application/json", + 401, + "Unauthenticated", + ), + ( + router(state(), standard_user()), + REPLACE, + "application/json", + 403, + "AdministratorRequired", + ), + ] { + let reply = exchange(router, &header_announcing_a_body(path, content_type)).await; + + reply.assert_error(status, code); + } +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §errors +#[tokio::test] +async fn a_busy_broker_answers_broker_busy_whatever_the_request() { + for request in [get("/v2/health"), get("/v2/unknown"), post(EVALUATE)] { + let mut router = build_busy_router(); + + let reply = reply(router.call(request).await.expect("the router is infallible")).await; + + reply.assert_error(503, "BrokerBusy"); + } +} + +// oracle: mutant answering a request whose path does not start with `/v2/` with a response of the 2.0 encoding +#[tokio::test] +async fn a_path_outside_the_prefix_reaches_the_other_router() { + let state = Arc::new(state()); + + for path in ["/v1/health", "/v2", "/v20/health", "/V2/health", "/"] { + let served = send(&state, &client(), get(path)).await; + let mut busy = build_busy_router(); + let busy = reply(busy.call(get(path)).await.expect("the router is infallible")).await; + + assert_ne!(served.body["Code"], "UnknownEndpoint", "{path}"); + assert_eq!(busy.body["Code"], "BrokerPaused", "{path}"); + } +} + +// oracle: mutant recording the refusal of a 2.0 policy replacement as the 1.x request, under the wrong reason, or not at all +#[tokio::test] +async fn a_refused_policy_replacement_leaves_a_denial_record() { + crate::audit::tests::take_events(); + + let unauthenticated = send( + &Arc::new(unauthenticating_state()), + &administrator(), + post_json(REPLACE, "{}"), + ) + .await; + let not_administrator = send(&Arc::new(state()), &standard_user(), post_json(REPLACE, "{}")).await; + + unauthenticated.assert_error(401, "Unauthenticated"); + not_administrator.assert_error(403, "AdministratorRequired"); + let records: Vec<_> = crate::audit::tests::take_events() + .into_iter() + .map(|entry| { + let field = |name: &str| { + entry + .fields + .iter() + .find_map(|(field, value)| (field == name).then(|| value.clone())) + .expect("a denial field") + }; + (entry.event_code, field("intent"), field("reason")) + }) + .collect(); + let denied = Some(agent_sysevent_codes::POLICY_WRITE_DENIED); + assert_eq!( + records, + [ + (denied, "POST /v2/policy".to_owned(), "authentication_failed".to_owned()), + ( + denied, + "POST /v2/policy".to_owned(), + "administrator_required".to_owned() + ), + ] + ); +} From 28f738a6a2df89aa40fb6bc85157b3ceccee479d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Tue, 1 Dec 2026 05:21:52 +0900 Subject: [PATCH 02/38] feat(agent): answer the 2.0 health and capabilities requests `GET /v2/health` says `Ready` only while the broker holds an accepted 2.x policy, so a policy file in format 1.x leaves the 2.0 endpoints paused while the 1.x routes keep their policy. `GET /v2/capabilities` names the managers found for the client's user and the timeout the executor stops a process after. A manager capability lists the opt-ins the broker handles itself, and the custom parameters and install location where the manager takes them. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- .../src/policy_store/mod.rs | 97 +++++++ crates/now-package-broker/src/server/mod.rs | 2 +- .../src/v2/routes/capabilities.rs | 91 ++++++ .../now-package-broker/src/v2/routes/mod.rs | 45 ++- .../now-package-broker/src/v2/routes/tests.rs | 259 +++++++++++++++++- 5 files changed, 487 insertions(+), 7 deletions(-) create mode 100644 crates/now-package-broker/src/v2/routes/capabilities.rs diff --git a/crates/now-package-broker/src/policy_store/mod.rs b/crates/now-package-broker/src/policy_store/mod.rs index b6bd1c5e9..a39b03f2e 100644 --- a/crates/now-package-broker/src/policy_store/mod.rs +++ b/crates/now-package-broker/src/policy_store/mod.rs @@ -1304,6 +1304,103 @@ fn clone_observation(observation: &Observation) -> Observation { } } +/// A policy file for the tests of the 2.0 endpoints, whose bytes a store reads as it reads those of a real file. +#[cfg(test)] +pub(crate) struct TestPolicyFile { + content: parking_lot::Mutex>>, + /// Stands in for the identity of the file, which every write changes. + generation: std::sync::atomic::AtomicU32, + read_only: Option<(PolicyWriteCapability, PolicyReadOnlyReason)>, +} + +#[cfg(test)] +impl TestPolicyFile { + /// A file with `content` that the store may replace, or no file where the store may create one. + pub(crate) fn holding(content: Option<&str>) -> Arc { + Self::new(content, None) + } + + fn new(content: Option<&str>, read_only: Option<(PolicyWriteCapability, PolicyReadOnlyReason)>) -> Arc { + Arc::new(Self { + content: parking_lot::Mutex::new(content.map(|content| content.as_bytes().to_vec())), + generation: std::sync::atomic::AtomicU32::new(1), + read_only, + }) + } + + /// Returns a store that watches this file. + pub(crate) fn store(self: &Arc) -> Arc { + PolicyStore::load_with_storage( + Some(PathBuf::from(r"C:\policy.json")), + Arc::clone(self) as Arc, + Monitoring::Available, + ) + } + + fn observation(&self) -> Observation { + let generation = self.generation.load(std::sync::atomic::Ordering::SeqCst); + match self.content.lock().as_deref() { + Some(content) => windows::test_file_observation(content, generation, self.read_only), + None => windows::test_missing_file_observation(self.read_only), + } + } +} + +#[cfg(test)] +impl PolicyStorage for TestPolicyFile { + 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 { + Err(WriteFailure::PrePublication(anyhow::anyhow!( + "this storage double takes no 1.x policy" + ))) + } + + fn replace( + &self, + _source: PolicyConfigurationSource, + _configured_path: &Path, + _observation: &mut Observation, + _bytes: &[u8], + ) -> Result { + Err(WriteFailure::PrePublication(anyhow::anyhow!( + "this storage double takes no 1.x policy" + ))) + } + + fn write_document( + &self, + _configured_path: &Path, + observation: &mut Observation, + bytes: &[u8], + ) -> Result { + if self.observation().fingerprint != observation.fingerprint { + return Err(WriteFailure::ConcurrentChange(anyhow::anyhow!( + "the file is not the one the observation saw" + ))); + } + *self.content.lock() = Some(bytes.to_vec()); + self.generation.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + Ok(self.observation()) + } +} + #[cfg(test)] mod storage_tests { use now_policy::PolicyDraftDocument; diff --git a/crates/now-package-broker/src/server/mod.rs b/crates/now-package-broker/src/server/mod.rs index 98e34b6da..50b1e88f9 100644 --- a/crates/now-package-broker/src/server/mod.rs +++ b/crates/now-package-broker/src/server/mod.rs @@ -740,7 +740,7 @@ impl BrokerState { /// /// Availability is probed through the executor (mirroring execution-time resolution) /// and cached per user for [`MANAGER_PROBE_TTL`]. - async fn probed_manager_capabilities(&self, user_sid: &Sid) -> Vec { + pub(crate) async fn probed_manager_capabilities(&self, user_sid: &Sid) -> Vec { let user_key = user_sid.to_string(); let available = match self.manager_probe_cache.get_fresh(&user_key) { diff --git a/crates/now-package-broker/src/v2/routes/capabilities.rs b/crates/now-package-broker/src/v2/routes/capabilities.rs new file mode 100644 index 000000000..9380ca133 --- /dev/null +++ b/crates/now-package-broker/src/v2/routes/capabilities.rs @@ -0,0 +1,91 @@ +//! What the broker offers a client ([§capabilities]). +//! +//! [§capabilities]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#capabilities + +use now_policy_api as v1; +use now_policy_api::v2; + +use crate::operation_tracker::OperationTracker; + +/// Returns the capabilities response for a user who has `managers`. +/// +/// The timeout is the one the executor stops a process after. +pub(super) fn response(managers: Vec) -> Result { + let timeout = u32::try_from(OperationTracker::operation_timeout().as_secs()).unwrap_or(u32::MAX); + + Ok(v2::CapabilitiesResponse { + server_version: v2::ServerVersion::parse(env!("CARGO_PKG_VERSION"))?, + operation_timeout_seconds: v2::OperationTimeoutSeconds::new(timeout)?, + managers: managers + .into_iter() + // A capability names at least one operation. + .filter(|capability| !capability.operations.is_empty()) + .map(manager_capability) + .collect(), + }) +} + +fn manager_capability(capability: v1::ManagerCapability) -> v2::ManagerCapability { + // The broker runs the commands and stops the processes itself, whatever the manager. + let mut opt_ins = vec![v2::OptInName::PrePostCommands, v2::OptInName::KillBeforeOperation]; + if capability.supports_custom_parameters { + opt_ins.push(v2::OptInName::CustomParameters); + } + if capability.supports_custom_install_location { + opt_ins.push(v2::OptInName::CustomInstallLocation); + } + + v2::ManagerCapability { + manager: manager(capability.manager), + operations: capability.operations.into_iter().map(operation).collect(), + scopes: capability.scopes.into_iter().map(scope).collect(), + architectures: capability.architectures.into_iter().map(architecture).collect(), + opt_ins, + } +} + +fn manager(manager: v1::ManagerName) -> v2::Manager { + match manager { + v1::ManagerName::Winget => v2::Manager::Winget, + v1::ManagerName::PowerShell => v2::Manager::PowerShell, + v1::ManagerName::PowerShell7 => v2::Manager::PowerShell7, + v1::ManagerName::Apt => v2::Manager::Apt, + v1::ManagerName::Bun => v2::Manager::Bun, + v1::ManagerName::Cargo => v2::Manager::Cargo, + v1::ManagerName::Chocolatey => v2::Manager::Chocolatey, + v1::ManagerName::Dnf => v2::Manager::Dnf, + v1::ManagerName::Dotnet => v2::Manager::Dotnet, + v1::ManagerName::Flatpak => v2::Manager::Flatpak, + v1::ManagerName::Homebrew => v2::Manager::Homebrew, + v1::ManagerName::Npm => v2::Manager::Npm, + v1::ManagerName::Pacman => v2::Manager::Pacman, + v1::ManagerName::Pip => v2::Manager::Pip, + v1::ManagerName::Scoop => v2::Manager::Scoop, + v1::ManagerName::Snap => v2::Manager::Snap, + v1::ManagerName::Vcpkg => v2::Manager::Vcpkg, + } +} + +fn operation(operation: v1::Operation) -> v2::Operation { + match operation { + v1::Operation::Install => v2::Operation::Install, + v1::Operation::Update => v2::Operation::Update, + v1::Operation::Uninstall => v2::Operation::Uninstall, + } +} + +fn scope(scope: v1::Scope) -> v2::Scope { + match scope { + v1::Scope::User => v2::Scope::User, + v1::Scope::Machine => v2::Scope::Machine, + } +} + +fn architecture(architecture: v1::Architecture) -> v2::Architecture { + match architecture { + v1::Architecture::X86 => v2::Architecture::X86, + v1::Architecture::X64 => v2::Architecture::X64, + v1::Architecture::Arm64 => v2::Architecture::Arm64, + v1::Architecture::Neutral => v2::Architecture::Neutral, + } +} diff --git a/crates/now-package-broker/src/v2/routes/mod.rs b/crates/now-package-broker/src/v2/routes/mod.rs index 55bc2ca69..6ecb85df7 100644 --- a/crates/now-package-broker/src/v2/routes/mod.rs +++ b/crates/now-package-broker/src/v2/routes/mod.rs @@ -5,6 +5,8 @@ //! [§endpoints]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#endpoints //! [§transport]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#transport +mod capabilities; + use std::future::Future; use std::panic::AssertUnwindSafe; use std::path::PathBuf; @@ -177,14 +179,37 @@ impl Connection { PathBuf::from(self.state.policy_store.management_snapshot().configured_path) } + /// Tells whether the broker holds an accepted policy ([§health]). + /// + /// [§health]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#health + fn health(&self) -> Response { + let status = if self.state.policy_store.accepted_policy().is_some() { + v2::HealthStatus::Ready + } else { + v2::HealthStatus::Paused + }; + + json(StatusCode::OK, &v2::HealthResponse { status }) + } + + /// Names the managers the broker finds for the client's user ([§capabilities]). + /// + /// [§capabilities]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#capabilities + async fn capabilities(&self) -> Response { + let managers = self.state.probed_manager_capabilities(self.client.user_sid()).await; + + match capabilities::response(managers) { + Ok(response) => json(StatusCode::OK, &response), + Err(error) => internal_error(&error), + } + } + /// Answers a request that passed every check made before its body is read. async fn serve(&self, route: &wire::Route, body: &[u8]) -> Response { match route.endpoint { - v2::Endpoint::Health - | v2::Endpoint::Capabilities - | v2::Endpoint::Status - | v2::Endpoint::Cancel - | v2::Endpoint::Management => not_served(), + v2::Endpoint::Health => self.health(), + v2::Endpoint::Capabilities => self.capabilities().await, + v2::Endpoint::Status | v2::Endpoint::Cancel | v2::Endpoint::Management => not_served(), v2::Endpoint::Evaluate => match wire::read_evaluation_request(body) { Ok(_request) => not_served(), Err(error) => bad_request(&error), @@ -260,6 +285,16 @@ fn bad_request(error: &wire::BadRequest) -> Response { error_response(v2::ErrorCode::BadRequest, &error.to_string()) } +/// The response to a request the broker failed to answer for a reason no other code names ([§errors]). +/// +/// The reason goes to the log only, because a message carries no meaning a client may depend on. +/// +/// [§errors]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#errors +fn internal_error(error: &dyn std::fmt::Display) -> Response { + error!(%error, "Failed to answer a package broker request"); + error_response(v2::ErrorCode::InternalError, "the broker failed to answer the request") +} + /// The response of an endpoint the broker does not answer yet. fn not_served() -> Response { error_response(v2::ErrorCode::InternalError, "the broker does not serve this endpoint") diff --git a/crates/now-package-broker/src/v2/routes/tests.rs b/crates/now-package-broker/src/v2/routes/tests.rs index 026d774dc..68f5ee42f 100644 --- a/crates/now-package-broker/src/v2/routes/tests.rs +++ b/crates/now-package-broker/src/v2/routes/tests.rs @@ -7,11 +7,12 @@ use axum::http::{Method, Request}; use axum::response::Response; use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _}; use tower_service::Service as _; +use win_api_wrappers::identity::sid::Sid; use crate::auth::PipeClient; use crate::executor::{CommandExecutor, ExecutionContext, ExecutionOutput, ProcessStartedCallback}; use crate::operation_tracker::OperationTracker; -use crate::policy_store::PolicyStore; +use crate::policy_store::{PolicyStore, TestPolicyFile}; use crate::remote_grant::RemoteGrantStore; use crate::server::{BrokerState, build_busy_router, build_router_for_client, serve_connection}; @@ -590,3 +591,259 @@ async fn a_refused_policy_replacement_leaves_a_denial_record() { ] ); } + +/// A valid 2.x 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} +}}"# + ) +} + +/// A valid 2.x policy document that allows nothing. +fn document(id: &str, revision: u32) -> String { + document_with(id, revision, "[]", "") +} + +/// The text of a policy file in format 1.x. +fn format_1_document(id: &str, revision: u32) -> String { + let draft: now_policy::PolicyDraftDocument = serde_json::from_value(serde_json::json!({ + "PolicyFormatVersion": "1.0.0", + "Metadata": { "Id": id, "Publisher": "Test" }, + "Enforcement": { "DefaultDecision": "Deny" }, + "Rules": [] + })) + .expect("a valid 1.x draft"); + let policy = draft + .into_policy_document(revision, chrono::Utc::now()) + .expect("a valid 1.x policy"); + + serde_json::to_string_pretty(&policy).expect("the policy serializes") +} + +/// A broker whose policy file holds `content`, or that has no policy file. +fn state_with_policy_file(content: Option<&str>) -> BrokerState { + BrokerState { + policy_store: TestPolicyFile::holding(content).store(), + ..state() + } +} + +/// An executor that finds the given managers for every user, and starts nothing. +struct ProbingExecutor(Vec); + +#[async_trait] +impl CommandExecutor for ProbingExecutor { + async fn execute( + &self, + _context: &ExecutionContext, + _process_started: Option, + ) -> anyhow::Result { + anyhow::bail!("this test starts no operation") + } + + async fn probe_managers(&self, _user_sid: &Sid) -> Vec { + self.0.clone() + } +} + +/// An executor that panics when asked which managers a user has. +struct PanickingExecutor; + +#[async_trait] +impl CommandExecutor for PanickingExecutor { + async fn execute( + &self, + _context: &ExecutionContext, + _process_started: Option, + ) -> anyhow::Result { + anyhow::bail!("this test starts no operation") + } + + async fn probe_managers(&self, _user_sid: &Sid) -> Vec { + panic!("the probe fails") + } +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §health +#[tokio::test] +async fn health_is_ready_exactly_when_the_broker_holds_an_accepted_policy() { + for (policy_file, status) in [ + (Some(document("corp-baseline", 3)), "Ready"), + (None, "Paused"), + (Some(format_1_document("legacy", 3)), "Paused"), + (Some("{".to_owned()), "Paused"), + ] { + let state = Arc::new(state_with_policy_file(policy_file.as_deref())); + + let reply = send(&state, &client(), get("/v2/health")).await; + + assert_eq!(reply.status, 200, "{reply:?}"); + assert_eq!(reply.content_type.as_deref(), Some("application/json"), "{reply:?}"); + assert_eq!(reply.body, serde_json::json!({ "Status": status }), "{policy_file:?}"); + } +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §authentication +#[tokio::test] +async fn health_answers_a_client_the_broker_does_not_authenticate() { + let state = Arc::new(unauthenticating_state()); + + let reply = send(&state, &standard_user(), get("/v2/health")).await; + + assert_eq!(reply.status, 200, "{reply:?}"); + assert_eq!(reply.members(), ["Status"]); +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §transport +#[tokio::test] +async fn an_endpoint_without_a_body_ignores_the_content_type() { + let state = Arc::new(state()); + + for content_type in [None, Some("text/plain"), Some("application/json")] { + let reply = send( + &state, + &client(), + request(Method::GET, "/v2/health", content_type, Body::empty()), + ) + .await; + + assert_eq!(reply.status, 200, "{content_type:?}: {reply:?}"); + } +} + +/// The strings of a list member of a JSON object. +fn strings<'a>(object: &'a serde_json::Value, member: &str) -> Vec<&'a str> { + object[member] + .as_array() + .expect("the member is a list") + .iter() + .map(|value| value.as_str().expect("the list holds strings")) + .collect() +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §capabilities +#[tokio::test] +async fn capabilities_name_the_version_the_timeout_and_each_manager_once() { + use now_policy_api::ManagerName; + + const OPT_INS: [&str; 9] = [ + "Interactive", + "SkipHashCheck", + "CustomInstallLocation", + "CustomParameters", + "InstallerArguments", + "PrePostCommands", + "KillBeforeOperation", + "UninstallPrevious", + "NoUpgrade", + ]; + + let state = Arc::new(BrokerState { + executor: Arc::new(ProbingExecutor(vec![ManagerName::Winget, ManagerName::Npm])), + ..state() + }); + + let reply = send(&state, &client(), get("/v2/capabilities")).await; + + assert_eq!(reply.status, 200, "{reply:?}"); + assert_eq!(reply.content_type.as_deref(), Some("application/json"), "{reply:?}"); + assert_eq!( + reply.members(), + ["Managers", "OperationTimeoutSeconds", "ServerVersion"], + "{reply:?}" + ); + let version = reply.body["ServerVersion"].as_str().expect("ServerVersion is a string"); + assert!((1..=128).contains(&version.len()), "{reply:?}"); + let timeout = reply.body["OperationTimeoutSeconds"] + .as_u64() + .expect("OperationTimeoutSeconds is an integer"); + assert!((1..=2_147_483_647).contains(&timeout), "{reply:?}"); + + let mut names = Vec::new(); + for manager in reply.body["Managers"].as_array().expect("Managers is a list") { + let mut members: Vec<&str> = manager + .as_object() + .expect("a manager capability is an object") + .keys() + .map(String::as_str) + .collect(); + members.sort_unstable(); + assert_eq!( + members, + ["Architectures", "Manager", "Operations", "OptIns", "Scopes"], + "{manager}" + ); + let operations = strings(manager, "Operations"); + assert!(!operations.is_empty(), "{manager}"); + assert!( + operations + .iter() + .all(|operation| ["Install", "Update", "Uninstall"].contains(operation)), + "{manager}" + ); + assert!( + strings(manager, "Scopes") + .iter() + .all(|scope| ["User", "Machine"].contains(scope)), + "{manager}" + ); + assert!( + strings(manager, "Architectures") + .iter() + .all(|architecture| ["X86", "X64", "Arm64", "Neutral"].contains(architecture)), + "{manager}" + ); + assert!( + strings(manager, "OptIns").iter().all(|opt_in| OPT_INS.contains(opt_in)), + "{manager}" + ); + names.push(manager["Manager"].as_str().expect("Manager is a string")); + } + names.sort_unstable(); + // The managers are those the test made the broker find for the client's user. + assert_eq!(names, ["Npm", "Winget"], "{reply:?}"); +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §authentication +#[tokio::test] +async fn capabilities_refuse_a_client_the_broker_does_not_authenticate() { + let state = Arc::new(unauthenticating_state()); + + let reply = send(&state, &client(), get("/v2/capabilities")).await; + + reply.assert_error(401, "Unauthenticated"); +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §errors +#[tokio::test] +async fn a_request_whose_answer_panics_is_internal_error() { + let state = Arc::new(BrokerState { + executor: Arc::new(PanickingExecutor), + ..state() + }); + + let reply = send(&state, &client(), get("/v2/capabilities")).await; + + reply.assert_error(500, "InternalError"); +} + +// oracle: mutant a policy file in format 1.x stops the 1.x routes from answering, or one in format 2.x gives them a policy +#[tokio::test] +async fn the_1_x_routes_hold_a_policy_exactly_when_the_file_is_in_format_1() { + for (policy_file, status) in [ + (format_1_document("legacy", 3), "Ready"), + (document("corp-baseline", 3), "Paused"), + ] { + let state = Arc::new(state_with_policy_file(Some(&policy_file))); + + let reply = send(&state, &client(), get("/v1/health")).await; + + assert_eq!((reply.status, &reply.body["Status"]), (200, &serde_json::json!(status))); + } +} From 7e6385d69e1e2bbf780e0102436bb90a67005e9f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Tue, 1 Dec 2026 05:27:41 +0900 Subject: [PATCH 03/38] feat(agent): evaluate 2.0 package requests against the accepted policy `POST /v2/package-requests/evaluate` answers the decision of the 2.x evaluator, the identity of the policy that decided and the evaluation time, and starts nothing. A denial is a decision in a 200 response, not an error. Without an accepted 2.x policy the request is `PolicyUnavailable`, which is also the answer while the policy file is in format 1.x. An allowed request that would run a command with an elevated token is `NotRunnable` with its decision, in audit mode too. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- .../now-package-broker/src/v2/routes/mod.rs | 76 ++++- .../now-package-broker/src/v2/routes/tests.rs | 272 ++++++++++++++++++ 2 files changed, 347 insertions(+), 1 deletion(-) diff --git a/crates/now-package-broker/src/v2/routes/mod.rs b/crates/now-package-broker/src/v2/routes/mod.rs index 6ecb85df7..b9d822315 100644 --- a/crates/now-package-broker/src/v2/routes/mod.rs +++ b/crates/now-package-broker/src/v2/routes/mod.rs @@ -18,10 +18,12 @@ use axum::body::{Body, Bytes, HttpBody as _, to_bytes}; use axum::extract::Request; use axum::http::{HeaderMap, HeaderValue, StatusCode, header}; use axum::response::Response; +use chrono::Utc; use now_policy_api::v2; use tower_service::Service as _; use tracing::{error, warn}; +use super::policy::{EvaluationError, is_not_runnable}; use super::wire; use crate::audit::DenialReason; use crate::auth::PipeClient; @@ -204,6 +206,70 @@ impl Connection { } } + /// Evaluates a package request, and starts and changes nothing ([§evaluate]). + /// + /// [§evaluate]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#evaluate + fn evaluate(&self, request: &v2::EvaluationRequest) -> Response { + match self.decide(request) { + Ok(evaluated) => json( + StatusCode::OK, + &v2::EvaluationResponse { + decision: evaluated.decision, + policy: evaluated.policy, + evaluated_at: evaluated.evaluated_at, + }, + ), + Err(response) => *response, + } + } + + /// Evaluates `request` against the accepted policy at the current time. + /// + /// The error is the response of a request that gets no evaluation response: `PolicyUnavailable` and `NotRunnable`, + /// in that order, are the outcomes an evaluation and an execution request share ([§evaluate], [§execute]). + /// + /// [§evaluate]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#evaluate + /// [§execute]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#execute + fn decide(&self, request: &v2::PackageRequest) -> Result> { + let Some(policy) = self.state.policy_store.accepted_policy() else { + return Err(Box::new(error_response( + v2::ErrorCode::PolicyUnavailable, + "the broker holds no accepted policy", + ))); + }; + + let evaluated_at = Utc::now(); + let request = wire::evaluator_request(request); + let decision = match policy.evaluate(&request, evaluated_at) { + Ok(decision) => decision, + // The evaluator reads a package request as the wire contract defines it, so it refuses only a request + // the contract does not allow. + Err(EvaluationError::BadRequest) => { + return Err(Box::new(error_response( + v2::ErrorCode::BadRequest, + "the package request is not well-formed", + ))); + } + Err(error @ EvaluationError::TimeOutOfRange) => return Err(Box::new(internal_error(&error))), + }; + let not_runnable = is_not_runnable(&request, &decision); + let decision = wire::decision(&decision).map_err(|error| Box::new(internal_error(&error)))?; + let evaluated_at = wire::timestamp(evaluated_at).map_err(|error| Box::new(internal_error(&error)))?; + + if not_runnable { + return Err(Box::new(error_body(&wire::not_runnable( + decision, + "the broker never runs a pre-operation or post-operation command with administrator rights", + )))); + } + + Ok(Evaluated { + decision, + policy: policy.identity(), + evaluated_at, + }) + } + /// Answers a request that passed every check made before its body is read. async fn serve(&self, route: &wire::Route, body: &[u8]) -> Response { match route.endpoint { @@ -211,7 +277,7 @@ impl Connection { v2::Endpoint::Capabilities => self.capabilities().await, v2::Endpoint::Status | v2::Endpoint::Cancel | v2::Endpoint::Management => not_served(), v2::Endpoint::Evaluate => match wire::read_evaluation_request(body) { - Ok(_request) => not_served(), + Ok(request) => self.evaluate(&request), Err(error) => bad_request(&error), }, v2::Endpoint::Execute => match wire::read_execution_request(body) { @@ -234,6 +300,14 @@ impl Connection { } } +/// A package request and the decision the accepted policy gave it. +struct Evaluated { + decision: v2::Decision, + /// The identity of the policy that decided. + policy: v2::PolicyIdentity, + evaluated_at: v2::Timestamp, +} + /// Why a request body was not read. enum BodyError { /// The body is larger than the limit of its endpoint. diff --git a/crates/now-package-broker/src/v2/routes/tests.rs b/crates/now-package-broker/src/v2/routes/tests.rs index 68f5ee42f..cbc1a6e01 100644 --- a/crates/now-package-broker/src/v2/routes/tests.rs +++ b/crates/now-package-broker/src/v2/routes/tests.rs @@ -847,3 +847,275 @@ async fn the_1_x_routes_hold_a_policy_exactly_when_the_file_is_in_format_1() { assert_eq!((reply.status, &reply.body["Status"]), (200, &serde_json::json!(status))); } } + +/// A rule that allows every plain request. +const ALLOW_ALL: &str = r#"[{ "Id": "allow-all", "Decision": "Allow", "Reason": "anything goes", "Select": {} }]"#; + +/// A rule that allows every request and grants the opt-ins the tests use. +const ALLOW_WITH_OPT_INS: &str = r#"[{ + "Id": "allow-opt-ins", + "Decision": "Allow", + "Select": {}, + "Grants": { "PrePostCommands": {}, "KillBeforeOperation": {}, "CustomInstallLocation": { "Patterns": ["*"] } } +}]"#; + +const AUDIT_MODE: &str = r#""Enforcement": { "AuditMode": true },"#; + +/// A package request to install one version of a package through WinGet, with `members` added or replaced. +fn package_request(members: serde_json::Value) -> serde_json::Value { + let mut request = serde_json::json!({ + "Operation": "Install", + "Manager": "Winget", + "Source": { "Name": "winget" }, + "Package": { "Id": "Git.Git", "Version": "2.45.1" }, + "Elevation": "NonElevated", + }); + let members = members.as_object().expect("the members are an object").clone(); + request + .as_object_mut() + .expect("the request is an object") + .extend(members); + request +} + +fn post_value(path: &str, body: &serde_json::Value) -> Request { + post_json(path, body.to_string()) +} + +/// A broker whose accepted policy has `rules`, and `enforcement` as extra top-level members. +fn state_with_policy(rules: &str, enforcement: &str) -> BrokerState { + state_with_policy_file(Some(&document_with("corp-baseline", 3, rules, enforcement))) +} + +fn decision(outcome: &str, check: &str, opt_ins: &[&str], audited: bool) -> serde_json::Value { + serde_json::json!({ "Outcome": outcome, "Check": check, "Rules": [], "OptIns": opt_ins, "Audited": audited }) +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §evaluate +#[tokio::test] +async fn an_evaluation_without_an_accepted_policy_is_policy_unavailable() { + for policy_file in [None, Some(format_1_document("legacy", 3)), Some("{".to_owned())] { + let state = Arc::new(state_with_policy_file(policy_file.as_deref())); + + let reply = send( + &state, + &client(), + post_value(EVALUATE, &package_request(serde_json::json!({}))), + ) + .await; + + reply.assert_error(503, "PolicyUnavailable"); + } +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §evaluate +#[tokio::test] +async fn an_evaluation_names_the_decision_the_policy_and_the_evaluation_time() { + let state = Arc::new(state_with_policy(ALLOW_ALL, "")); + let before = chrono::Utc::now(); + + let reply = send( + &state, + &client(), + post_value(EVALUATE, &package_request(serde_json::json!({}))), + ) + .await; + + let after = chrono::Utc::now(); + assert_eq!(reply.status, 200, "{reply:?}"); + assert_eq!(reply.content_type.as_deref(), Some("application/json"), "{reply:?}"); + assert_eq!(reply.members(), ["Decision", "EvaluatedAt", "Policy"], "{reply:?}"); + assert_eq!( + reply.body["Decision"], + serde_json::json!({ + "Outcome": "Allow", + "Check": "AllowRules", + "Rules": [{ "Id": "allow-all", "Reason": "anything goes" }], + "OptIns": [], + "Audited": false, + }) + ); + assert_eq!( + reply.body["Policy"], + serde_json::json!({ "Id": "corp-baseline", "Revision": 3 }) + ); + let evaluated_at = reply.body["EvaluatedAt"].as_str().expect("EvaluatedAt is a string"); + let evaluated_at = chrono::DateTime::parse_from_rfc3339(evaluated_at).expect("EvaluatedAt is a timestamp"); + assert!((before..=after).contains(&evaluated_at.to_utc()), "{reply:?}"); +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §evaluate +#[tokio::test] +async fn a_denied_evaluation_is_answered_with_its_decision() { + let state = Arc::new(state_with_policy("[]", "")); + + let reply = send( + &state, + &client(), + post_value(EVALUATE, &package_request(serde_json::json!({}))), + ) + .await; + + assert_eq!(reply.status, 200, "{reply:?}"); + assert_eq!(reply.members(), ["Decision", "EvaluatedAt", "Policy"], "{reply:?}"); + assert_eq!(reply.body["Decision"], decision("Deny", "DefaultDeny", &[], false)); +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §evaluate +#[tokio::test] +async fn an_evaluation_request_with_a_request_id_is_bad_request() { + let state = Arc::new(state_with_policy(ALLOW_ALL, "")); + + let reply = send( + &state, + &client(), + post_value( + EVALUATE, + &package_request(serde_json::json!({ "RequestId": "request-1" })), + ), + ) + .await; + + reply.assert_error(400, "BadRequest"); +} + +/// The members a request has when it asks to run a command before the manager with an elevated token. +fn elevated_with_a_command() -> serde_json::Value { + serde_json::json!({ "Elevation": "Elevated", "OptIns": { "PrePostCommands": { "Pre": "echo before" } } }) +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §not-runnable +#[tokio::test] +async fn an_allowed_request_with_commands_for_an_elevated_run_is_not_runnable() { + for (rules, enforcement, expected) in [ + ( + ALLOW_WITH_OPT_INS, + "", + serde_json::json!({ + "Outcome": "Allow", + "Check": "AllowRules", + "Rules": [{ "Id": "allow-opt-ins" }], + "OptIns": [], + "Audited": false, + }), + ), + // Audit mode lets the denial of the default decision through, and the request is refused all the same. + ( + "[]", + AUDIT_MODE, + decision("Allow", "DefaultDeny", &["PrePostCommands"], true), + ), + ] { + let state = Arc::new(state_with_policy(rules, enforcement)); + + let request = package_request(elevated_with_a_command()); + + let reply = send(&state, &client(), post_value(EVALUATE, &request)).await; + + assert_eq!( + (reply.status, &reply.body["Code"]), + (422, &serde_json::json!("NotRunnable")), + "{reply:?}" + ); + assert_eq!(reply.members(), ["Code", "Decision", "Message"], "{reply:?}"); + assert_eq!(reply.body["Decision"], expected); + } +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §not-runnable +#[tokio::test] +async fn only_an_allowed_request_with_commands_for_an_elevated_run_is_not_runnable() { + // A denied request is answered with its denial. + let denying = Arc::new(state_with_policy("[]", "")); + let denied = send( + &denying, + &client(), + post_value(EVALUATE, &package_request(elevated_with_a_command())), + ) + .await; + assert_eq!(denied.status, 200, "{denied:?}"); + assert_eq!( + denied.body["Decision"], + decision("Deny", "DefaultDeny", &["PrePostCommands"], false) + ); + + // The commands of a run that is not elevated are not refused. + let allowing = Arc::new(state_with_policy(ALLOW_WITH_OPT_INS, "")); + let allowed = send( + &allowing, + &client(), + post_value( + EVALUATE, + &package_request(serde_json::json!({ "OptIns": { "PrePostCommands": { "Pre": "echo before" } } })), + ), + ) + .await; + assert_eq!(allowed.status, 200, "{allowed:?}"); + assert_eq!(allowed.body["Decision"]["Outcome"], "Allow"); +} + +// What the 2.0 encoding does with the requests the 1.x routes refuse before they read the policy. +// Audit mode is on and the policy grants every opt-in the requests use, so nothing but the rule under test refuses them. +#[tokio::test] +async fn a_request_the_contract_refuses_whatever_the_policy_is_refused_in_audit_mode_too() { + let state = Arc::new(state_with_policy(ALLOW_WITH_OPT_INS, AUDIT_MODE)); + + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.policy.md §reading + // A source name that starts with a white space character looks like another, so the request is unreadable. + let ambiguous_source = send( + &state, + &client(), + post_value( + EVALUATE, + &package_request(serde_json::json!({ "Source": { "Name": " winget" } })), + ), + ) + .await; + assert_eq!(ambiguous_source.status, 200, "{ambiguous_source:?}"); + assert_eq!( + ambiguous_source.body["Decision"], + decision("Deny", "UnreadableRequest", &[], false) + ); + + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.policy.md §install-location + // A network path is not a plain local path. + let install_location = send( + &state, + &client(), + post_value( + EVALUATE, + &package_request(serde_json::json!({ + "OptIns": { "CustomInstallLocation": { "Path": r"\\server\share\git" } }, + })), + ), + ) + .await; + assert_eq!(install_location.status, 200, "{install_location:?}"); + assert_eq!( + install_location.body["Decision"], + decision("Deny", "InstallLocation", &[], false) + ); + + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §package-request + let machine_scope = send( + &state, + &client(), + post_value(EVALUATE, &package_request(serde_json::json!({ "Scope": "Machine" }))), + ) + .await; + machine_scope.assert_error(400, "BadRequest"); + + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §opt-ins + let wildcard_image_name = send( + &state, + &client(), + post_value( + EVALUATE, + &package_request(serde_json::json!({ + "OptIns": { "KillBeforeOperation": { "Processes": ["git*"] } }, + })), + ), + ) + .await; + wildcard_image_name.assert_error(400, "BadRequest"); +} From d3da6d3c2e48789ff2c16c8b241cd7fb1aea9e1d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Tue, 1 Dec 2026 05:39:47 +0900 Subject: [PATCH 04/38] feat(agent): start, report and cancel operations for 2.0 requests An execution request under /v2/ is evaluated against the accepted policy and, when allowed, starts an operation held apart from those of the 1.x routes, so neither encoding names, replays or conflicts with an operation of the other. The status and cancel requests answer for the owner of an operation only, with the same response for another owner's operation as for one the broker does not hold. An allowed request that would uninstall the Devolutions Agent, or any uninstall while the product code of the installed Agent cannot be read, starts an operation that runs no step and ends Failed, because the broker never removes the Agent it runs in. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- crates/now-package-broker/src/server/grant.rs | 1 + crates/now-package-broker/src/server/mod.rs | 5 + crates/now-package-broker/src/task.rs | 6 + .../src/v2/execution/operations.rs | 24 +- .../src/v2/execution/plan.rs | 28 +- crates/now-package-broker/src/v2/mod.rs | 2 + .../now-package-broker/src/v2/routes/held.rs | 62 ++ .../now-package-broker/src/v2/routes/mod.rs | 16 +- .../src/v2/routes/operations.rs | 193 +++++ .../now-package-broker/src/v2/routes/tests.rs | 666 +++++++++++++++++- 10 files changed, 983 insertions(+), 20 deletions(-) create mode 100644 crates/now-package-broker/src/v2/routes/held.rs create mode 100644 crates/now-package-broker/src/v2/routes/operations.rs diff --git a/crates/now-package-broker/src/server/grant.rs b/crates/now-package-broker/src/server/grant.rs index 017c7dc3e..980f32190 100644 --- a/crates/now-package-broker/src/server/grant.rs +++ b/crates/now-package-broker/src/server/grant.rs @@ -326,6 +326,7 @@ mod tests { manager_probe_cache: Default::default(), remote_grants: RemoteGrantStore::new(), agent_product_code: || Ok(None), + operations: Default::default(), }) } diff --git a/crates/now-package-broker/src/server/mod.rs b/crates/now-package-broker/src/server/mod.rs index 50b1e88f9..0d8b1830b 100644 --- a/crates/now-package-broker/src/server/mod.rs +++ b/crates/now-package-broker/src/server/mod.rs @@ -192,6 +192,8 @@ pub struct BrokerState { /// `Ok(None)` means that no Agent MSI is installed. /// An error rejects every request that removes a package. pub agent_product_code: fn() -> anyhow::Result>, + /// The operations started by the requests of the 2.0 encoding; `tracker` holds those of the 1.x routes. + pub operations: crate::v2::HeldOperations, } /// Reads the MSI product code of the installed Devolutions Agent from the registry. @@ -1286,6 +1288,7 @@ mod tests { manager_probe_cache: Default::default(), remote_grants: RemoteGrantStore::new(), agent_product_code: || Ok(None), + operations: Default::default(), } } @@ -2185,6 +2188,7 @@ mod tests { manager_probe_cache, remote_grants: RemoteGrantStore::new(), agent_product_code: || Ok(None), + operations: Default::default(), }); (state, executor) } @@ -2369,6 +2373,7 @@ mod tests { manager_probe_cache: Default::default(), remote_grants: RemoteGrantStore::new(), agent_product_code: || Ok(None), + operations: Default::default(), } } diff --git a/crates/now-package-broker/src/task.rs b/crates/now-package-broker/src/task.rs index 8b8de7070..7195eb8ad 100644 --- a/crates/now-package-broker/src/task.rs +++ b/crates/now-package-broker/src/task.rs @@ -57,6 +57,7 @@ impl BrokerTask { remote_grants: RemoteGrantStore::new(), // UNTESTED: The broker runs with the registry lookup; see `read_agent_product_code`. agent_product_code: crate::server::read_agent_product_code, + operations: Default::default(), }); Self { state, @@ -89,6 +90,11 @@ impl Task for BrokerTask { // Bridge the agent's ShutdownSignal to the cancellation token used by subsystems. let shutdown = CancellationToken::new(); state.tracker.clone().spawn_eviction_task(shutdown.clone()); + // UNTESTED: The broker stops holding the operations of the 2.0 encoding once they ended long enough ago. + // Without this task every ended operation stays in memory, and its request id stays taken, until the broker + // restarts. + // No test runs the broker task, so check that this call remains when changing how the task starts. + state.operations.spawn_eviction_task(&state, shutdown.clone()); let denial_summary_handle = crate::audit::spawn_denial_summary_task(shutdown.clone()); // Spawn policy watcher task. diff --git a/crates/now-package-broker/src/v2/execution/operations.rs b/crates/now-package-broker/src/v2/execution/operations.rs index 52dd9764f..581954cea 100644 --- a/crates/now-package-broker/src/v2/execution/operations.rs +++ b/crates/now-package-broker/src/v2/execution/operations.rs @@ -12,7 +12,7 @@ use tracing::{info, warn}; use uuid::Uuid; use super::owner::Owner; -use super::plan::plan; +use super::plan::plan_protecting_agent; use crate::event_channel::{ChannelVersion, OperationEventSink, open_operation_channel_announcing}; use crate::executor::{ CommandExecutor, ExecutionContext, ProcessStartedCallback, TokenElevationCheck, is_canceled_error, @@ -139,6 +139,8 @@ pub struct Operations { struct Inner { executor: Arc, + /// Reads the MSI product code of the installed Devolutions Agent. + agent_product_code: fn() -> anyhow::Result>, state: Mutex>, } @@ -263,11 +265,25 @@ where K: PartialEq + Send + 'static, C: Clone + Send + 'static, { - /// Returns an empty registry whose operations run on `executor`. + /// Returns an empty registry whose operations run on `executor`, on a machine without Devolutions Agent. + #[cfg(test)] pub fn new(executor: Arc) -> Self { + Self::protecting_agent(executor, || Ok(None)) + } + + /// Returns an empty registry whose operations run on `executor` and never remove the Devolutions Agent. + /// + /// `agent_product_code` reads the MSI product code of the installed Agent, `Ok(None)` when none is installed. + /// An operation that removes a package runs no step and ends `Failed` when its request names the Agent, or when + /// the product code cannot be read. + pub fn protecting_agent( + executor: Arc, + agent_product_code: fn() -> anyhow::Result>, + ) -> Self { Self { inner: Arc::new(Inner { executor, + agent_product_code, state: Mutex::new(State { operations: HashMap::new(), request_ids: HashMap::new(), @@ -290,8 +306,8 @@ where /// /// [§not-runnable]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#not-runnable pub fn start(&self, caller: &Caller, request_id: &str, request_key: K, request: &Request, context: C) -> Start { - // The plan depends on the request only, so no other request waits for it. - let planned = plan(request); + // The plan depends on the request and the installed Agent only, so no other request waits for it. + let planned = plan_protecting_agent(request, self.inner.agent_product_code); // UNTESTED: Requests of one owner with one request id that arrive together start one operation. // A second operation would run the same package request twice. diff --git a/crates/now-package-broker/src/v2/execution/plan.rs b/crates/now-package-broker/src/v2/execution/plan.rs index a828ac193..25d6d7a2f 100644 --- a/crates/now-package-broker/src/v2/execution/plan.rs +++ b/crates/now-package-broker/src/v2/execution/plan.rs @@ -5,7 +5,7 @@ use std::path::PathBuf; -use anyhow::bail; +use anyhow::{Context as _, bail}; use chrono::Utc; use now_policy_api as v1; use now_policy_eval::{Architecture, Elevation, InstallerArgumentsMode, Manager, Operation, Request, Scope}; @@ -102,6 +102,32 @@ pub(super) fn plan(request: &Request) -> anyhow::Result { }) } +/// Reads the MSI product code of the installed Devolutions Agent, `Ok(None)` when no Agent MSI is installed. +pub(super) type AgentProductCode = fn() -> anyhow::Result>; + +/// Returns what the operation of `request` runs, which never removes the Devolutions Agent. +/// +/// It is [`plan`] for every other request. +pub(super) fn plan_protecting_agent(request: &Request, agent_product_code: AgentProductCode) -> anyhow::Result { + // SECURITY: The broker never removes the Devolutions Agent, which hosts it, whatever allowed the request. + // A request that removes a package runs no step either when the product code of the installed Agent cannot be + // read, because an identifier that holds that code would then go unnoticed. + let elevation = match request.elevation { + Elevation::NonElevated => v1::Elevation::Standard, + Elevation::Elevated => v1::Elevation::Elevated, + }; + let builder_request = builder_request(request, elevation); + if crate::evaluator::removes_package(&builder_request) { + let agent_product_code = agent_product_code() + .context("the broker cannot verify that the request does not uninstall the Devolutions Agent")?; + if crate::evaluator::uninstalls_protected_package(&builder_request, agent_product_code) { + bail!("the broker does not uninstall the Devolutions Agent"); + } + } + + plan(request) +} + /// Whether `manager` updates a package from the source recorded when it was installed ([§managers]). /// /// [§managers]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.policy.md#managers diff --git a/crates/now-package-broker/src/v2/mod.rs b/crates/now-package-broker/src/v2/mod.rs index f34e5a600..ac7e09832 100644 --- a/crates/now-package-broker/src/v2/mod.rs +++ b/crates/now-package-broker/src/v2/mod.rs @@ -7,3 +7,5 @@ pub mod execution; pub mod policy; pub(crate) mod routes; pub mod wire; + +pub use self::routes::HeldOperations; diff --git a/crates/now-package-broker/src/v2/routes/held.rs b/crates/now-package-broker/src/v2/routes/held.rs new file mode 100644 index 000000000..f008cc8c4 --- /dev/null +++ b/crates/now-package-broker/src/v2/routes/held.rs @@ -0,0 +1,62 @@ +//! The operations the broker holds for the requests of the 2.0 encoding ([§operations]). +//! +//! [§operations]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#operations + +use std::sync::{Arc, OnceLock}; + +use now_policy_api::v2; +use tokio_util::sync::CancellationToken; + +use crate::server::BrokerState; +use crate::v2::execution::Operations; + +/// What the response to the execution request that started an operation says besides the operation ([§execute]). +/// +/// A replayed response repeats it. +/// +/// [§execute]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#execute +#[derive(Debug, Clone)] +pub(super) struct Decided { + pub(super) decision: v2::Decision, + /// The identity of the policy that decided. + pub(super) policy: v2::PolicyIdentity, + pub(super) evaluated_at: v2::Timestamp, +} + +/// The operations started by execution requests, in which two requests are equal when their package requests are +/// ([§equal-requests]). +/// +/// [§equal-requests]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#equal-requests +pub(super) type Executions = Operations; + +/// The operations started by the requests of the 2.0 encoding, which a broker state creates empty. +/// +/// The operations of the 1.x routes are not held here, so no request of the 2.0 encoding names one. +/// A clone holds the same operations. +#[derive(Clone, Default)] +pub struct HeldOperations { + /// Made when first needed, because the operations run on the executor of the state that holds this value. + registries: Arc>, +} + +pub(super) struct Registries { + pub(super) executions: Executions, +} + +impl HeldOperations { + /// Returns the registries, whose operations run on the executor of `state` and never remove the Devolutions + /// Agent that `state` finds installed. + pub(super) fn of(&self, state: &BrokerState) -> &Registries { + self.registries.get_or_init(|| Registries { + executions: Operations::protecting_agent(Arc::clone(&state.executor), state.agent_product_code), + }) + } + + /// Spawns the task that stops holding ended operations, until `shutdown` is canceled. + /// + /// `state` is the broker state that holds this value. + /// Must be called from a Tokio runtime. + pub fn spawn_eviction_task(&self, state: &BrokerState, shutdown: CancellationToken) { + self.of(state).executions.clone().spawn_eviction_task(shutdown); + } +} diff --git a/crates/now-package-broker/src/v2/routes/mod.rs b/crates/now-package-broker/src/v2/routes/mod.rs index b9d822315..e752e5874 100644 --- a/crates/now-package-broker/src/v2/routes/mod.rs +++ b/crates/now-package-broker/src/v2/routes/mod.rs @@ -6,6 +6,8 @@ //! [§transport]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#transport mod capabilities; +mod held; +mod operations; use std::future::Future; use std::panic::AssertUnwindSafe; @@ -23,6 +25,7 @@ use now_policy_api::v2; use tower_service::Service as _; use tracing::{error, warn}; +pub use self::held::HeldOperations; use super::policy::{EvaluationError, is_not_runnable}; use super::wire; use crate::audit::DenialReason; @@ -253,6 +256,7 @@ impl Connection { Err(error @ EvaluationError::TimeOutOfRange) => return Err(Box::new(internal_error(&error))), }; let not_runnable = is_not_runnable(&request, &decision); + let allowed = decision.outcome == now_policy_eval::Outcome::Allow; let decision = wire::decision(&decision).map_err(|error| Box::new(internal_error(&error)))?; let evaluated_at = wire::timestamp(evaluated_at).map_err(|error| Box::new(internal_error(&error)))?; @@ -264,6 +268,8 @@ impl Connection { } Ok(Evaluated { + request, + allowed, decision, policy: policy.identity(), evaluated_at, @@ -275,13 +281,15 @@ impl Connection { match route.endpoint { v2::Endpoint::Health => self.health(), v2::Endpoint::Capabilities => self.capabilities().await, - v2::Endpoint::Status | v2::Endpoint::Cancel | v2::Endpoint::Management => not_served(), + v2::Endpoint::Status => self.status(route), + v2::Endpoint::Cancel => self.cancel(route), + v2::Endpoint::Management => not_served(), v2::Endpoint::Evaluate => match wire::read_evaluation_request(body) { Ok(request) => self.evaluate(&request), Err(error) => bad_request(&error), }, v2::Endpoint::Execute => match wire::read_execution_request(body) { - Ok(_request) => not_served(), + Ok(request) => self.execute(&request), Err(error) => bad_request(&error), }, v2::Endpoint::ExecuteBypass => match wire::read_bypass_request(body) { @@ -302,6 +310,10 @@ impl Connection { /// A package request and the decision the accepted policy gave it. struct Evaluated { + /// The request as the evaluator read it, which is what an operation runs. + request: now_policy_eval::Request, + /// Whether the outcome of the decision is `Allow`. + allowed: bool, decision: v2::Decision, /// The identity of the policy that decided. policy: v2::PolicyIdentity, diff --git a/crates/now-package-broker/src/v2/routes/operations.rs b/crates/now-package-broker/src/v2/routes/operations.rs new file mode 100644 index 000000000..34339f083 --- /dev/null +++ b/crates/now-package-broker/src/v2/routes/operations.rs @@ -0,0 +1,193 @@ +//! The endpoints that start, report and cancel operations ([§execute], [§status], [§cancel]). +//! +//! [§execute]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#execute +//! [§status]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#status +//! [§cancel]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#cancel + +use axum::http::StatusCode; +use axum::response::Response; +use now_policy_api::v2; + +use super::held::Decided; +use super::{Connection, error_response, internal_error, json}; +use crate::v2::execution::{Caller, Existing, OperationState, Owner, Start, StartedOperation, Status}; +use crate::v2::wire; + +impl Connection { + /// The client as the one its requests start operations for. + /// + /// The user and the executable are those of the process on the pipe, never values of a request body. + pub(super) fn caller(&self) -> Caller { + let user_sid = self.client.user_sid(); + + Caller { + owner: Owner::new(user_sid, self.client.executable_path()), + session_id: self.client.session_id(), + // The name is for logs only, and resolving the account name may wait for a domain controller. + display_name: user_sid.to_string(), + } + } + + /// Starts the operation of an allowed package request, unless the broker holds one for its `RequestId` ([§execute]). + /// + /// [§execute]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#execute + pub(super) fn execute(&self, request: &v2::ExecutionRequest) -> Response { + let executions = &self.state.operations.of(&self.state).executions; + let caller = self.caller(); + let request_id = request.request_id.as_str(); + let package_request = request.package_request(); + + // A request the broker holds an operation for is neither evaluated nor started. + if let Some(existing) = executions.existing(&caller.owner, request_id, &package_request) { + return existing_execution(existing); + } + + let evaluated = match self.decide(&package_request) { + Ok(evaluated) => evaluated, + Err(response) => return *response, + }; + let decided = Decided { + decision: evaluated.decision, + policy: evaluated.policy, + evaluated_at: evaluated.evaluated_at, + }; + if !evaluated.allowed { + // A denied request starts nothing, and its `RequestId` stays unused. + return execution_response(decided, None); + } + + match executions.start(&caller, request_id, package_request, &evaluated.request, decided) { + Start::Started(started) => started_execution(started), + // A request with the same `RequestId` arrived in the meantime and started the operation. + Start::Existing(existing) => existing_execution(existing), + } + } + + /// Reports the operation the path names, when the broker holds it for the client ([§status]). + /// + /// [§status]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#status + pub(super) fn status(&self, route: &wire::Route) -> Response { + let Some(state) = self.held_operation(route, |owner, operation_id| { + self.state + .operations + .of(&self.state) + .executions + .status(owner, operation_id) + }) else { + return operation_not_found(); + }; + + match status_response(state) { + Ok(response) => json(StatusCode::OK, &response), + Err(error) => internal_error(&error), + } + } + + /// Asks the operation the path names to cancel, when the broker holds it for the client ([§cancel]). + /// + /// [§cancel]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#cancel + pub(super) fn cancel(&self, route: &wire::Route) -> Response { + let Some(status) = self.held_operation(route, |owner, operation_id| { + self.state + .operations + .of(&self.state) + .executions + .cancel(owner, operation_id) + }) else { + return operation_not_found(); + }; + + json( + StatusCode::OK, + &v2::CancelResponse { + status: operation_status(status), + }, + ) + } + + /// Looks up the operation that the path of `route` names among those the broker holds for the client. + /// + /// A path whose operation id is not an identifier names no operation. + fn held_operation(&self, route: &wire::Route, lookup: impl FnOnce(&Owner, &str) -> Option) -> Option { + let operation_id = route.operation.as_ref()?.as_ref().ok()?; + + lookup(&self.caller().owner, operation_id.as_str()) + } +} + +fn existing_execution(existing: Existing) -> Response { + match existing { + Existing::Replayed(started) => started_execution(started), + Existing::Conflict => error_response( + v2::ErrorCode::RequestIdConflict, + "the broker holds an operation started with this request id for a different package request", + ), + } +} + +/// The response to a request the broker holds `started` for, with the status the operation has now. +fn started_execution(started: StartedOperation) -> Response { + let StartedOperation { + operation_id, + status, + event_pipe, + context, + } = started; + + execution_response(context, Some((operation_id, status, event_pipe))) +} + +fn execution_response(decided: Decided, operation: Option<(String, Status, Option)>) -> Response { + let named = operation.map(|(operation_id, status, event_pipe)| { + Ok::<_, v2::ValueError>(( + v2::Identifier::parse(&operation_id)?, + operation_status(status), + event_pipe.as_deref().map(v2::EventPipe::parse).transpose()?, + )) + }); + let (operation_id, status, event_pipe) = match named.transpose() { + Ok(Some((operation_id, status, event_pipe))) => (Some(operation_id), Some(status), event_pipe), + Ok(None) => (None, None, None), + Err(error) => return internal_error(&error), + }; + + json( + StatusCode::OK, + &v2::ExecutionResponse { + decision: decided.decision, + policy: decided.policy, + evaluated_at: decided.evaluated_at, + operation_id, + status, + event_pipe, + }, + ) +} + +fn status_response(state: OperationState) -> Result { + Ok(v2::StatusResponse { + status: operation_status(state.status), + started_at: state.started_at.map(wire::timestamp).transpose()?, + completed_at: state.completed_at.map(wire::timestamp).transpose()?, + exit_code: state.exit_code, + message: state.message.as_deref().map(wire::message), + }) +} + +pub(super) fn operation_status(status: Status) -> v2::OperationStatus { + match status { + Status::Starting => v2::OperationStatus::Starting, + Status::Running => v2::OperationStatus::Running, + Status::Canceling => v2::OperationStatus::Canceling, + Status::Completed => v2::OperationStatus::Completed, + Status::Failed => v2::OperationStatus::Failed, + Status::Canceled => v2::OperationStatus::Canceled, + } +} + +fn operation_not_found() -> Response { + error_response( + v2::ErrorCode::OperationNotFound, + "the broker holds no such operation for the client", + ) +} diff --git a/crates/now-package-broker/src/v2/routes/tests.rs b/crates/now-package-broker/src/v2/routes/tests.rs index cbc1a6e01..ebf7ff8c6 100644 --- a/crates/now-package-broker/src/v2/routes/tests.rs +++ b/crates/now-package-broker/src/v2/routes/tests.rs @@ -53,6 +53,7 @@ fn state() -> BrokerState { manager_probe_cache: Default::default(), remote_grants: RemoteGrantStore::new(), agent_product_code: || Ok(None), + operations: Default::default(), } } @@ -1006,19 +1007,23 @@ async fn an_allowed_request_with_commands_for_an_elevated_run_is_not_runnable() decision("Allow", "DefaultDeny", &["PrePostCommands"], true), ), ] { - let state = Arc::new(state_with_policy(rules, enforcement)); - - let request = package_request(elevated_with_a_command()); - - let reply = send(&state, &client(), post_value(EVALUATE, &request)).await; - - assert_eq!( - (reply.status, &reply.body["Code"]), - (422, &serde_json::json!("NotRunnable")), - "{reply:?}" - ); - assert_eq!(reply.members(), ["Code", "Decision", "Message"], "{reply:?}"); - assert_eq!(reply.body["Decision"], expected); + for (path, request) in [ + (EVALUATE, package_request(elevated_with_a_command())), + (EXECUTE, execution_request("request-1", elevated_with_a_command())), + ] { + let broker = Broker::with_policy(rules, enforcement); + + let reply = send(&broker.state, &client(), post_value(path, &request)).await; + + assert_eq!( + (reply.status, &reply.body["Code"]), + (422, &serde_json::json!("NotRunnable")), + "{reply:?}" + ); + assert_eq!(reply.members(), ["Code", "Decision", "Message"], "{reply:?}"); + assert_eq!(reply.body["Decision"], expected); + assert_eq!(broker.runs().await, 0); + } } } @@ -1119,3 +1124,638 @@ async fn a_request_the_contract_refuses_whatever_the_policy_is_refused_in_audit_ .await; wildcard_image_name.assert_error(400, "BadRequest"); } + +/// What the executor of a test does next for the operation it runs. +enum Step { + /// Reports that the manager process was launched at the given time. + Launch(chrono::DateTime), + /// The manager process exits on its own with the given code. + Exit(i32), + /// Runs until the operation is canceled. + RunUntilCanceled, +} + +/// An executor that counts what it was asked to run and does what the test tells it. +struct ScriptedExecutor { + runs: std::sync::atomic::AtomicUsize, + steps: tokio::sync::Mutex>, +} + +#[async_trait] +impl CommandExecutor for ScriptedExecutor { + async fn execute( + &self, + context: &ExecutionContext, + process_started: Option, + ) -> anyhow::Result { + self.runs.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + let mut steps = self.steps.lock().await; + loop { + match steps.recv().await.expect("the test dropped its steps") { + Step::Launch(at) => process_started.as_ref().expect("launch callback")(at), + Step::Exit(exit_code) => { + return Ok(ExecutionOutput { + exit_code, + ..ExecutionOutput::default() + }); + } + Step::RunUntilCanceled => { + context.cancel_token.cancelled().await; + return Err(crate::executor::OperationCanceled.into()); + } + } + } + } +} + +/// A broker whose operations do what the test tells them. +struct Broker { + state: Arc, + executor: Arc, + steps: tokio::sync::mpsc::UnboundedSender, +} + +impl Broker { + /// A broker whose accepted policy has `rules`, and `enforcement` as extra top-level members. + fn with_policy(rules: &str, enforcement: &str) -> Self { + Self::from_state(state_with_policy(rules, enforcement)) + } + + /// The broker `state` describes, with the executor of the test in place of its own. + fn from_state(state: BrokerState) -> Self { + let (steps, receiver) = tokio::sync::mpsc::unbounded_channel(); + let executor = Arc::new(ScriptedExecutor { + runs: std::sync::atomic::AtomicUsize::new(0), + steps: tokio::sync::Mutex::new(receiver), + }); + let state = Arc::new(BrokerState { + executor: Arc::clone(&executor) as Arc, + ..state + }); + + Self { state, executor, steps } + } + + fn step(&self, step: Step) { + self.steps.send(step).expect("the executor is gone"); + } + + /// The number of operations the executor was asked to run, once every task that can run has run. + async fn runs(&self) -> usize { + for _ in 0..16 { + tokio::task::yield_now().await; + } + self.executor.runs.load(std::sync::atomic::Ordering::SeqCst) + } + + /// Sends an execution request for `request` that must start an operation, and returns the response. + async fn start(&self, request: &serde_json::Value) -> Reply { + let reply = send(&self.state, &client(), post_value(EXECUTE, request)).await; + assert_eq!(reply.status, 200, "{reply:?}"); + assert!(reply.body["OperationId"].is_string(), "{reply:?}"); + reply + } + + /// Asks for the status of the operation until it is `status`, and returns that response. + async fn wait_for(&self, operation_id: &str, status: &str) -> Reply { + let reached = async { + loop { + let reply = send(&self.state, &client(), get(&status_path(operation_id))).await; + assert_eq!(reply.status, 200, "{reply:?}"); + if reply.body["Status"] == status { + return reply; + } + tokio::task::yield_now().await; + } + }; + tokio::time::timeout(Duration::from_secs(10), reached) + .await + .unwrap_or_else(|_| panic!("the operation never became {status}")) + } +} + +/// An execution request for [`package_request`] with `members` added or replaced. +fn execution_request(request_id: &str, members: serde_json::Value) -> serde_json::Value { + let mut request = package_request(members); + request["RequestId"] = serde_json::json!(request_id); + request +} + +fn operation_id(reply: &Reply) -> &str { + reply.body["OperationId"].as_str().expect("OperationId is a string") +} + +fn status_path(operation_id: &str) -> String { + format!("/v2/operations/{operation_id}") +} + +fn cancel_path(operation_id: &str) -> String { + format!("/v2/operations/{operation_id}/cancel") +} + +/// The members of a response without `absent`, which the contract lets the broker leave out. +fn members_without<'a>(reply: &'a Reply, absent: &str) -> Vec<&'a str> { + let mut members = reply.members(); + members.retain(|member| *member != absent); + members +} + +fn timestamp(reply: &Reply, member: &str) -> chrono::DateTime { + let text = reply.body[member] + .as_str() + .unwrap_or_else(|| panic!("{member} is a string")); + assert!(text.ends_with('Z'), "{member} is written with the offset Z: {text}"); + chrono::DateTime::parse_from_rfc3339(text) + .unwrap_or_else(|_| panic!("{member} is a timestamp")) + .to_utc() +} + +fn at(seconds: i64) -> chrono::DateTime { + chrono::DateTime::from_timestamp(1_800_000_000 + seconds, 0).expect("timestamp") +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §execute +#[tokio::test] +async fn an_allowed_execution_starts_an_operation_and_names_it() { + let broker = Broker::with_policy(ALLOW_ALL, ""); + let before = chrono::Utc::now(); + + let reply = broker + .start(&execution_request("request-1", serde_json::json!({}))) + .await; + + let after = chrono::Utc::now(); + assert_eq!(reply.content_type.as_deref(), Some("application/json"), "{reply:?}"); + assert_eq!( + members_without(&reply, "EventPipe"), + ["Decision", "EvaluatedAt", "OperationId", "Policy", "Status"], + "{reply:?}" + ); + assert_eq!( + reply.body["Decision"], + serde_json::json!({ + "Outcome": "Allow", + "Check": "AllowRules", + "Rules": [{ "Id": "allow-all", "Reason": "anything goes" }], + "OptIns": [], + "Audited": false, + }) + ); + assert_eq!( + reply.body["Policy"], + serde_json::json!({ "Id": "corp-baseline", "Revision": 3 }) + ); + assert!( + (before..=after).contains(×tamp(&reply, "EvaluatedAt")), + "{reply:?}" + ); + // The manager process has not been launched. + assert_eq!(reply.body["Status"], "Starting"); + // An identifier is 1 to 128 ASCII letters, digits, `.`, `_`, `:` and `-`, and starts with a letter or digit. + let operation_id = operation_id(&reply); + assert!((1..=128).contains(&operation_id.len()), "{reply:?}"); + assert!( + operation_id + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || b"._:-".contains(&byte)), + "{reply:?}" + ); + assert!(operation_id.as_bytes()[0].is_ascii_alphanumeric(), "{reply:?}"); + if let Some(event_pipe) = reply.body.get("EventPipe") { + let event_pipe = event_pipe.as_str().expect("EventPipe is a string"); + assert!((1..=256).contains(&event_pipe.len()), "{reply:?}"); + assert!( + event_pipe + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || b"._-".contains(&byte)), + "{reply:?}" + ); + } + assert_eq!(broker.runs().await, 1); +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §execute +#[tokio::test] +async fn a_denied_execution_starts_no_operation_and_leaves_its_request_id_unused() { + let broker = Broker::with_policy("[]", ""); + + let denied = send( + &broker.state, + &client(), + post_value(EXECUTE, &execution_request("request-1", serde_json::json!({}))), + ) + .await; + + assert_eq!(denied.status, 200, "{denied:?}"); + assert_eq!(denied.members(), ["Decision", "EvaluatedAt", "Policy"], "{denied:?}"); + assert_eq!(denied.body["Decision"], decision("Deny", "DefaultDeny", &[], false)); + + // The request id is unused, so another package request with it does not conflict. + let other = execution_request( + "request-1", + serde_json::json!({ "Package": { "Id": "Git.Git", "Version": "2.46.0" } }), + ); + let reply = send(&broker.state, &client(), post_value(EXECUTE, &other)).await; + assert_eq!(reply.status, 200, "{reply:?}"); + assert_eq!(reply.members(), ["Decision", "EvaluatedAt", "Policy"], "{reply:?}"); + assert_eq!(broker.runs().await, 0); +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §execute +#[tokio::test] +async fn an_execution_without_an_accepted_policy_is_policy_unavailable() { + for policy_file in [None, Some(format_1_document("legacy", 3))] { + let broker = Broker::from_state(state_with_policy_file(policy_file.as_deref())); + + let reply = send( + &broker.state, + &client(), + post_value(EXECUTE, &execution_request("request-1", serde_json::json!({}))), + ) + .await; + + reply.assert_error(503, "PolicyUnavailable"); + assert_eq!(broker.runs().await, 0); + } +} + +/// The broker of `broker` once it holds no accepted policy, with the operations it held. +fn without_policy(broker: &Broker) -> Arc { + Arc::new(BrokerState { + operations: broker.state.operations.clone(), + ..state() + }) +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §execute +#[tokio::test] +async fn an_equal_execution_request_with_a_used_request_id_replays_the_response_with_the_current_status() { + let broker = Broker::with_policy(ALLOW_ALL, ""); + let first = broker + .start(&execution_request("request-1", serde_json::json!({}))) + .await; + broker.step(Step::Launch(at(0))); + broker.wait_for(operation_id(&first), "Running").await; + + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §equal-requests + // The same members with equal values in another key order are an equal request. + let reordered = r#"{ + "Elevation": "NonElevated", + "Package": { "Version": "2.45.1", "Id": "Git.Git" }, + "RequestId": "request-1", + "Source": { "Name": "winget" }, + "Manager": "Winget", + "Operation": "Install" + }"#; + let replay = send(&broker.state, &client(), post_json(EXECUTE, reordered)).await; + + assert_eq!(replay.status, 200, "{replay:?}"); + assert_eq!(replay.members(), first.members(), "{replay:?}"); + for member in ["Decision", "Policy", "EvaluatedAt", "OperationId"] { + assert_eq!(replay.body[member], first.body[member], "{member}"); + } + assert_eq!(replay.body.get("EventPipe"), first.body.get("EventPipe")); + assert_eq!(replay.body["Status"], "Running"); + assert_eq!(broker.runs().await, 1); + + // The replay comes before the outcome of a broker that holds no accepted policy. + let replay = send(&without_policy(&broker), &client(), post_json(EXECUTE, reordered)).await; + assert_eq!(replay.status, 200, "{replay:?}"); + assert_eq!(replay.body["OperationId"], first.body["OperationId"]); +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §execute +#[tokio::test] +async fn an_unequal_execution_request_with_a_used_request_id_is_request_id_conflict() { + let broker = Broker::with_policy(ALLOW_ALL, ""); + broker + .start(&execution_request("request-1", serde_json::json!({}))) + .await; + + for unequal in [ + serde_json::json!({ "Package": { "Id": "Git.Git", "Version": "2.46.0" } }), + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §equal-requests + // A request with `OptIns` does not have the same members as one without it. + serde_json::json!({ "OptIns": {} }), + ] { + let request = execution_request("request-1", unequal); + + let reply = send(&broker.state, &client(), post_value(EXECUTE, &request)).await; + reply.assert_error(409, "RequestIdConflict"); + + // The conflict comes before the outcome of a broker that holds no accepted policy. + let reply = send(&without_policy(&broker), &client(), post_value(EXECUTE, &request)).await; + reply.assert_error(409, "RequestIdConflict"); + } + assert_eq!(broker.runs().await, 1); +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §status +#[tokio::test] +async fn a_status_response_follows_an_operation_to_its_end() { + for (exit_code, terminal) in [(0, "Completed"), (3, "Failed")] { + let broker = Broker::with_policy(ALLOW_ALL, ""); + let started = broker + .start(&execution_request("request-1", serde_json::json!({}))) + .await; + let operation_id = operation_id(&started); + + let starting = broker.wait_for(operation_id, "Starting").await; + assert_eq!(starting.content_type.as_deref(), Some("application/json")); + assert_eq!(members_without(&starting, "Message"), ["Status"], "{starting:?}"); + + broker.step(Step::Launch(at(5))); + let running = broker.wait_for(operation_id, "Running").await; + assert_eq!( + members_without(&running, "Message"), + ["StartedAt", "Status"], + "{running:?}" + ); + assert_eq!(timestamp(&running, "StartedAt"), at(5)); + + let before = chrono::Utc::now(); + broker.step(Step::Exit(exit_code)); + let ended = broker.wait_for(operation_id, terminal).await; + let after = chrono::Utc::now(); + assert_eq!( + members_without(&ended, "Message"), + ["CompletedAt", "ExitCode", "StartedAt", "Status"], + "{ended:?}" + ); + assert_eq!(timestamp(&ended, "StartedAt"), at(5)); + assert_eq!(ended.body["ExitCode"], exit_code); + assert!( + (before - chrono::TimeDelta::seconds(1)..=after).contains(×tamp(&ended, "CompletedAt")), + "{ended:?}" + ); + } +} + +/// A client that runs as the user of the test process from another executable. +struct OtherExecutable { + process: std::process::Child, + client: PipeClient, +} + +impl OtherExecutable { + fn start() -> Self { + // The command interpreter waits for the input the test never writes. + let process = std::process::Command::new("cmd.exe") + .stdin(std::process::Stdio::piped()) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .spawn() + .expect("start another process"); + let client = PipeClient::from_process_id_for_identity(process.id()).expect("capture the other process"); + + Self { process, client } + } +} + +impl Drop for OtherExecutable { + fn drop(&mut self) { + let _ = self.process.kill(); + let _ = self.process.wait(); + } +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §operations +#[tokio::test] +async fn a_status_or_cancel_request_for_an_operation_the_broker_does_not_hold_for_its_owner_is_operation_not_found() { + let broker = Broker::with_policy(ALLOW_ALL, ""); + let started = broker + .start(&execution_request("request-1", serde_json::json!({}))) + .await; + let operation_id = operation_id(&started); + let other = OtherExecutable::start(); + assert_ne!(other.client.executable_path(), client().executable_path()); + + // An operation of another owner. + for request in [get(&status_path(operation_id)), post(&cancel_path(operation_id))] { + let reply = send(&broker.state, &other.client, request).await; + reply.assert_error(404, "OperationNotFound"); + } + // The cancel request of another owner left the operation as it was. + broker.wait_for(operation_id, "Starting").await; + + // An operation the broker never started, and a path segment that is not an identifier. + for unknown in ["op-unknown", "-op"] { + for request in [get(&status_path(unknown)), post(&cancel_path(unknown))] { + let reply = send(&broker.state, &client(), request).await; + reply.assert_error(404, "OperationNotFound"); + } + } +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §operations +#[tokio::test] +async fn a_request_id_belongs_to_its_owner() { + let broker = Broker::with_policy(ALLOW_ALL, ""); + let started = broker + .start(&execution_request("request-1", serde_json::json!({}))) + .await; + let other = OtherExecutable::start(); + + // Another package request with the same id from another owner neither conflicts nor replays. + let request = execution_request( + "request-1", + serde_json::json!({ "Package": { "Id": "Git.Git", "Version": "2.46.0" } }), + ); + let reply = send(&broker.state, &other.client, post_value(EXECUTE, &request)).await; + + assert_eq!(reply.status, 200, "{reply:?}"); + assert!(reply.body["OperationId"].is_string(), "{reply:?}"); + assert_ne!(reply.body["OperationId"], started.body["OperationId"]); +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §cancel +#[tokio::test] +async fn a_cancel_request_makes_an_operation_canceling_and_changes_nothing_once_it_ended() { + let broker = Broker::with_policy(ALLOW_ALL, ""); + let started = broker + .start(&execution_request("request-1", serde_json::json!({}))) + .await; + let operation_id = operation_id(&started); + broker.step(Step::Launch(at(0))); + broker.wait_for(operation_id, "Running").await; + + let canceling = send(&broker.state, &client(), post(&cancel_path(operation_id))).await; + + assert_eq!(canceling.status, 200, "{canceling:?}"); + assert_eq!(canceling.content_type.as_deref(), Some("application/json")); + assert_eq!(canceling.body, serde_json::json!({ "Status": "Canceling" })); + assert_eq!( + send(&broker.state, &client(), get(&status_path(operation_id))) + .await + .body["Status"], + "Canceling" + ); + + // The broker ends the operation, which the manager process did not do on its own. + broker.step(Step::RunUntilCanceled); + let canceled = broker.wait_for(operation_id, "Canceled").await; + assert_eq!( + members_without(&canceled, "Message"), + ["CompletedAt", "StartedAt", "Status"], + "{canceled:?}" + ); + + let again = send(&broker.state, &client(), post(&cancel_path(operation_id))).await; + assert_eq!(again.status, 200, "{again:?}"); + assert_eq!(again.body, serde_json::json!({ "Status": "Canceled" })); +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §cancel +#[tokio::test] +async fn a_cancel_request_for_an_ended_operation_answers_its_terminal_status() { + let broker = Broker::with_policy(ALLOW_ALL, ""); + let started = broker + .start(&execution_request("request-1", serde_json::json!({}))) + .await; + let operation_id = operation_id(&started); + broker.step(Step::Launch(at(0))); + broker.step(Step::Exit(0)); + broker.wait_for(operation_id, "Completed").await; + + let reply = send(&broker.state, &client(), post(&cancel_path(operation_id))).await; + + assert_eq!(reply.status, 200, "{reply:?}"); + assert_eq!(reply.body, serde_json::json!({ "Status": "Completed" })); + broker.wait_for(operation_id, "Completed").await; +} + +/// A 1.x request with the id `request_id`. +fn request_1_x(request_id: &str) -> now_policy_api::PackageRequest { + use now_policy_api as api; + + api::PackageRequest { + request_kind: api::PackageRequestKind, + request_version: api::API_VERSION_STR.into(), + request_id: api::ResourceId::from(request_id), + created_at: chrono::Utc::now(), + operation: api::Operation::Install, + manager: api::ManagerName::Winget, + source: api::RequestSource { + name: "winget".to_owned(), + url: None, + }, + package: api::RequestPackage { + id: api::PackageIdentifier("Git.Git".to_owned()), + version: None, + architecture: None, + channel: None, + }, + options: api::RequestOptions { + scope: None, + interactive: false, + skip_hash_check: false, + pre_release: false, + custom_install_location: None, + custom_parameters: Vec::new(), + pre_operation_command: None, + post_operation_command: None, + kill_before_operation: Vec::new(), + uninstall_previous: false, + no_upgrade: false, + }, + client: api::ClientContext { + transport: api::Transport::HttpNamedPipe, + requested_elevation: api::Elevation::Standard, + effective_user: client().user_sid().to_string(), + client_executable_path: client().executable_path().display().to_string(), + client_version: "1.0.0".to_owned(), + }, + include_command_preview: false, + capture_output: false, + } +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §operations +#[tokio::test] +async fn an_operation_of_the_1_x_routes_is_not_one_a_2_0_request_names_or_replays() { + let broker = Broker::with_policy(ALLOW_ALL, ""); + let request = request_1_x("request-1"); + let owner_key = format!( + "{}|{}", + request.client.effective_user.to_lowercase(), + request.client.client_executable_path.to_lowercase() + ); + let (operation_1_x, _) = broker + .state + .tracker + .register(&owner_key, &request, now_policy_api::ResourceId::from("op-1-x")) + .expect("register the 1.x operation"); + + for request in [ + get(&status_path(operation_1_x.as_ref())), + post(&cancel_path(operation_1_x.as_ref())), + ] { + let reply = send(&broker.state, &client(), request).await; + reply.assert_error(404, "OperationNotFound"); + } + + // The id of the 1.x request neither conflicts with nor replays an execution request. + let started = broker + .start(&execution_request("request-1", serde_json::json!({}))) + .await; + assert_ne!(operation_id(&started), operation_1_x.as_ref()); + + // oracle: mutant holding the operations of both encodings in the tracker of the 1.x routes + assert!(broker.state.tracker.get(operation_id(&started)).is_none()); + assert!( + broker + .state + .tracker + .get_for_owner(operation_id(&started), &owner_key) + .is_none() + ); +} + +/// An execution request to uninstall the package `id` through WinGet. +fn uninstall(id: &str) -> serde_json::Value { + execution_request( + "request-1", + serde_json::json!({ "Operation": "Uninstall", "Package": { "Id": id } }), + ) +} + +/// Checks that the operation `started` names ended `Failed` without running a step. +async fn assert_failed_without_a_step(broker: &Broker, started: &Reply) { + let failed = broker.wait_for(operation_id(started), "Failed").await; + + assert_eq!( + members_without(&failed, "Message"), + ["CompletedAt", "Status"], + "{failed:?}" + ); + assert_eq!(broker.runs().await, 0); +} + +// oracle: mutant running an allowed uninstall of the Devolutions Agent, or any uninstall when the product code of the +// installed Agent cannot be read +#[tokio::test] +async fn an_allowed_uninstall_of_the_devolutions_agent_ends_failed_without_a_step() { + let broker = Broker::with_policy(ALLOW_ALL, ""); + let started = broker.start(&uninstall("Devolutions.Agent")).await; + assert_eq!(started.body["Decision"]["Outcome"], "Allow"); + assert_failed_without_a_step(&broker, &started).await; + + let broker = Broker::from_state(BrokerState { + agent_product_code: || anyhow::bail!("the registry cannot be read"), + ..state_with_policy(ALLOW_ALL, "") + }); + let started = broker.start(&uninstall("Git.Git")).await; + assert_failed_without_a_step(&broker, &started).await; +} + +// oracle: mutant refusing every uninstall as one of the Devolutions Agent +#[tokio::test] +async fn an_allowed_uninstall_of_another_package_runs() { + let broker = Broker::with_policy(ALLOW_ALL, ""); + + let started = broker.start(&uninstall("Git.Git")).await; + + broker.step(Step::Launch(at(0))); + broker.wait_for(operation_id(&started), "Running").await; + assert_eq!(broker.runs().await, 1); +} From 16d0ee0895478236005d26b2134d887f32ba8559 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Tue, 1 Dec 2026 05:46:35 +0900 Subject: [PATCH 05/38] feat(agent): read, check and replace the policy through 2.0 requests The policy management, validation and replacement requests under /v2/ answer from the 2.0 view of the policy store, so a client of the 2.0 encoding manages a 2.x policy file without the 1.x routes. A replacement is recorded under its own request, from the attempt of an administrator to its result, and a request refused for its body leaves a result too. The store and the wire model each mapped the validation errors of the evaluator; the wire model's mapping is the one that remains. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- crates/now-package-broker/src/audit.rs | 7 + .../src/policy_store/mod.rs | 46 +- crates/now-package-broker/src/v2/policy.rs | 24 +- .../now-package-broker/src/v2/routes/mod.rs | 7 +- .../src/v2/routes/policy.rs | 93 +++++ .../now-package-broker/src/v2/routes/tests.rs | 392 +++++++++++++++++- 6 files changed, 537 insertions(+), 32 deletions(-) create mode 100644 crates/now-package-broker/src/v2/routes/policy.rs diff --git a/crates/now-package-broker/src/audit.rs b/crates/now-package-broker/src/audit.rs index a57b68b70..0af40dccd 100644 --- a/crates/now-package-broker/src/audit.rs +++ b/crates/now-package-broker/src/audit.rs @@ -553,6 +553,13 @@ impl WriteAudit { Self::begin_with_recorder(actor_sid, actor_exe, path, Arc::clone(recorder())) } + /// Records the attempt of a caller authorized to replace the policy through the 2.0 encoding. + /// + /// The returned audit pairs the attempt with a result as [`Self::begin`] does. + pub(crate) fn begin_document(actor_sid: &Sid, actor_exe: &Path, path: &Path) -> Self { + Self::begin_as(DOCUMENT_INTENT, actor_sid, actor_exe, path, Arc::clone(recorder())) + } + fn begin_with_recorder(actor_sid: &Sid, actor_exe: &Path, path: &Path, recorder: Arc) -> Self { Self::begin_as(INTENT, actor_sid, actor_exe, path, recorder) } diff --git a/crates/now-package-broker/src/policy_store/mod.rs b/crates/now-package-broker/src/policy_store/mod.rs index a39b03f2e..a8bdd125c 100644 --- a/crates/now-package-broker/src/policy_store/mod.rs +++ b/crates/now-package-broker/src/policy_store/mod.rs @@ -674,10 +674,6 @@ impl PolicyStore { /// /// 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, @@ -1311,6 +1307,17 @@ pub(crate) struct TestPolicyFile { /// Stands in for the identity of the file, which every write changes. generation: std::sync::atomic::AtomicU32, read_only: Option<(PolicyWriteCapability, PolicyReadOnlyReason)>, + next_write: parking_lot::Mutex>, +} + +/// What goes wrong with a write to a [`TestPolicyFile`]. +#[cfg(test)] +#[derive(Debug, Clone, Copy)] +pub(crate) enum TestWriteFault { + /// The write fails and leaves the file as it was. + Refused, + /// The write leaves the file with other bytes than the ones to write. + Garbled, } #[cfg(test)] @@ -1320,11 +1327,30 @@ impl TestPolicyFile { Self::new(content, None) } + /// A file with `content` at a path the store does not write to. + pub(crate) fn read_only(content: &str) -> Arc { + Self::new( + Some(content), + Some((PolicyWriteCapability::ReadOnly, PolicyReadOnlyReason::UnsafePath)), + ) + } + + /// The bytes the file holds, when it exists. + pub(crate) fn content(&self) -> Option> { + self.content.lock().clone() + } + + /// Makes the next write to the file go wrong as `fault` says. + pub(crate) fn fail_next_write(&self, fault: TestWriteFault) { + *self.next_write.lock() = Some(fault); + } + fn new(content: Option<&str>, read_only: Option<(PolicyWriteCapability, PolicyReadOnlyReason)>) -> Arc { Arc::new(Self { content: parking_lot::Mutex::new(content.map(|content| content.as_bytes().to_vec())), generation: std::sync::atomic::AtomicU32::new(1), read_only, + next_write: parking_lot::Mutex::new(None), }) } @@ -1386,6 +1412,7 @@ impl PolicyStorage for TestPolicyFile { fn write_document( &self, + _source: PolicyConfigurationSource, _configured_path: &Path, observation: &mut Observation, bytes: &[u8], @@ -1395,7 +1422,16 @@ impl PolicyStorage for TestPolicyFile { "the file is not the one the observation saw" ))); } - *self.content.lock() = Some(bytes.to_vec()); + let written = match self.next_write.lock().take() { + Some(TestWriteFault::Refused) => { + return Err(WriteFailure::PrePublication(anyhow::anyhow!( + "the file cannot be written" + ))); + } + Some(TestWriteFault::Garbled) => b"{".to_vec(), + None => bytes.to_vec(), + }; + *self.content.lock() = Some(written); self.generation.fetch_add(1, std::sync::atomic::Ordering::SeqCst); Ok(self.observation()) } diff --git a/crates/now-package-broker/src/v2/policy.rs b/crates/now-package-broker/src/v2/policy.rs index a51366eb6..d644ed51d 100644 --- a/crates/now-package-broker/src/v2/policy.rs +++ b/crates/now-package-broker/src/v2/policy.rs @@ -26,7 +26,7 @@ impl AcceptedPolicy { /// 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::>())?; + .map_err(|errors| errors.iter().map(super::wire::policy_error).collect::>())?; // A valid document is UTF-8 and carries its identity, so neither step fails after the reader accepted the bytes. // Reporting the whole document as malformed keeps an unexpected disagreement between the two readers from @@ -130,28 +130,6 @@ pub fn is_not_runnable(request: &Request, decision: &Decision) -> bool { && request.elevation == Elevation::Elevated } -fn policy_error(error: now_policy_eval::ValidationError) -> PolicyError { - use now_policy_eval::ErrorCode; - - let code = match error.code { - ErrorCode::DocumentTooLarge => PolicyErrorCode::DocumentTooLarge, - ErrorCode::MalformedDocument => PolicyErrorCode::MalformedDocument, - ErrorCode::DuplicateKey => PolicyErrorCode::DuplicateKey, - ErrorCode::UnsupportedFormatVersion => PolicyErrorCode::UnsupportedFormatVersion, - ErrorCode::MissingKey => PolicyErrorCode::MissingKey, - ErrorCode::UnknownKey => PolicyErrorCode::UnknownKey, - ErrorCode::ConflictingKeys => PolicyErrorCode::ConflictingKeys, - ErrorCode::WrongType => PolicyErrorCode::WrongType, - ErrorCode::InvalidValue => PolicyErrorCode::InvalidValue, - ErrorCode::DuplicateRuleId => PolicyErrorCode::DuplicateRuleId, - }; - - PolicyError { - code, - pointer: error.pointer, - } -} - /// Reads `Metadata.Id` and `Metadata.Revision` from the text of a valid document. fn read_identity(document: &str) -> Option<(String, Revision)> { let json = document.strip_prefix(BYTE_ORDER_MARK).unwrap_or(document); diff --git a/crates/now-package-broker/src/v2/routes/mod.rs b/crates/now-package-broker/src/v2/routes/mod.rs index e752e5874..a49cffa69 100644 --- a/crates/now-package-broker/src/v2/routes/mod.rs +++ b/crates/now-package-broker/src/v2/routes/mod.rs @@ -8,6 +8,7 @@ mod capabilities; mod held; mod operations; +mod policy; use std::future::Future; use std::panic::AssertUnwindSafe; @@ -283,7 +284,7 @@ impl Connection { v2::Endpoint::Capabilities => self.capabilities().await, v2::Endpoint::Status => self.status(route), v2::Endpoint::Cancel => self.cancel(route), - v2::Endpoint::Management => not_served(), + v2::Endpoint::Management => self.management(), v2::Endpoint::Evaluate => match wire::read_evaluation_request(body) { Ok(request) => self.evaluate(&request), Err(error) => bad_request(&error), @@ -297,11 +298,11 @@ impl Connection { Err(error) => bad_request(&error), }, v2::Endpoint::Validate => match wire::read_validation_request(body) { - Ok(_request) => not_served(), + Ok(request) => policy::validate(&request), Err(error) => bad_request(&error), }, v2::Endpoint::Replace => match wire::read_replacement_request(body) { - Ok(_request) => not_served(), + Ok(request) => self.replace(&request).await, Err(error) => bad_request(&error), }, } diff --git a/crates/now-package-broker/src/v2/routes/policy.rs b/crates/now-package-broker/src/v2/routes/policy.rs new file mode 100644 index 000000000..b70fffe37 --- /dev/null +++ b/crates/now-package-broker/src/v2/routes/policy.rs @@ -0,0 +1,93 @@ +//! The endpoints that read, check and replace the policy file ([§management], [§validation], [§replacement]). +//! +//! [§management]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#management +//! [§validation]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#validation +//! [§replacement]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#replacement + +use axum::http::StatusCode; +use axum::response::Response; +use now_policy_api::v2; + +use super::{Connection, error_body, error_response, internal_error, json}; +use crate::audit::WriteAudit; +use crate::policy_store::DocumentReplacement; +use crate::v2::wire; + +impl Connection { + /// Reports the policy management state of the broker ([§management]). + /// + /// [§management]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#management + pub(super) fn management(&self) -> Response { + match self.state.policy_store.policy_management() { + Ok(management) => json(StatusCode::OK, &v2::ManagementResponse { management }), + Err(error) => internal_error(&error), + } + } + + /// Replaces the policy file with the document of `request`, when nothing refuses it ([§replacement]). + /// + /// [§replacement]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#replacement + /// + /// The attempt is recorded once the store can decide the request, and the store records its result. + pub(super) async fn replace(&self, request: &v2::ReplacementRequest) -> Response { + let begin_audit = || { + WriteAudit::begin_document( + self.client.user_sid(), + self.client.executable_path(), + &self.configured_policy_path(), + ) + }; + let replacement = self + .state + .policy_store + .replace_document(&request.expected_store_token, &request.document, begin_audit) + .await; + + match replacement { + Ok(DocumentReplacement::StaleStoreToken(management)) => policy_state_error( + v2::ErrorCode::StaleStoreToken, + management, + "the expected store token is not the current store token", + ), + Ok(DocumentReplacement::PolicyNotWritable(management)) => policy_state_error( + v2::ErrorCode::PolicyNotWritable, + management, + "the broker cannot write the policy file", + ), + Ok(DocumentReplacement::InvalidPolicy(errors)) => { + error_body(&wire::invalid_policy(errors, "the document is not a valid policy")) + } + Ok(DocumentReplacement::RevisionNotHigher(management)) => policy_state_error( + v2::ErrorCode::RevisionNotHigher, + management, + "the revision of the document is not higher than that of the accepted policy with the same id", + ), + Ok(DocumentReplacement::PersistenceFailed) => error_response( + v2::ErrorCode::PersistenceFailed, + "the broker failed to write the policy file", + ), + Ok(DocumentReplacement::ActivationFailed(management)) => policy_state_error( + v2::ErrorCode::ActivationFailed, + management, + "the broker wrote the policy file and does not hold the document as its accepted policy", + ), + Ok(DocumentReplacement::Replaced(management)) => { + json(StatusCode::OK, &v2::ReplacementResponse { management }) + } + Err(error) => internal_error(&error), + } + } +} + +/// Reports the policy errors of a document, and reads and changes nothing the broker stores ([§validation]). +/// +/// [§validation]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#validation +pub(super) fn validate(request: &v2::ValidationRequest) -> Response { + let errors = crate::v2::policy::validate(request.document.as_bytes()); + + json(StatusCode::OK, &v2::ValidationResponse { errors }) +} + +fn policy_state_error(code: v2::ErrorCode, management: v2::PolicyManagement, text: &str) -> Response { + error_body(&wire::policy_state_error(code, management, text)) +} diff --git a/crates/now-package-broker/src/v2/routes/tests.rs b/crates/now-package-broker/src/v2/routes/tests.rs index ebf7ff8c6..180508356 100644 --- a/crates/now-package-broker/src/v2/routes/tests.rs +++ b/crates/now-package-broker/src/v2/routes/tests.rs @@ -12,7 +12,7 @@ use win_api_wrappers::identity::sid::Sid; use crate::auth::PipeClient; use crate::executor::{CommandExecutor, ExecutionContext, ExecutionOutput, ProcessStartedCallback}; use crate::operation_tracker::OperationTracker; -use crate::policy_store::{PolicyStore, TestPolicyFile}; +use crate::policy_store::{PolicyStore, TestPolicyFile, TestWriteFault}; use crate::remote_grant::RemoteGrantStore; use crate::server::{BrokerState, build_busy_router, build_router_for_client, serve_connection}; @@ -1759,3 +1759,393 @@ async fn an_allowed_uninstall_of_another_package_runs() { broker.wait_for(operation_id(&started), "Running").await; assert_eq!(broker.runs().await, 1); } + +const MANAGEMENT: &str = "/v2/policy/management"; + +/// A broker that reads `file` as its policy file. +fn broker_reading(file: &Arc) -> Arc { + Arc::new(BrokerState { + policy_store: file.store(), + ..state() + }) +} + +/// The policy management state the broker reports, checked to be alone in its response. +async fn management(state: &Arc) -> serde_json::Value { + let reply = send(state, &client(), get(MANAGEMENT)).await; + + assert_eq!(reply.status, 200, "{reply:?}"); + assert_eq!(reply.content_type.as_deref(), Some("application/json"), "{reply:?}"); + assert_eq!(reply.members(), ["Management"], "{reply:?}"); + reply.body["Management"].clone() +} + +fn members_of(object: &serde_json::Value) -> Vec<&str> { + let mut members: Vec<&str> = object + .as_object() + .expect("a JSON object") + .keys() + .map(String::as_str) + .collect(); + members.sort_unstable(); + members +} + +/// The store token of a policy management state, checked against the domain of store tokens. +fn store_token(management: &serde_json::Value) -> &str { + let token = management["StoreToken"].as_str().expect("StoreToken is a string"); + assert!((1..=512).contains(&token.len()), "{token}"); + assert!( + token + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || b"._~:-".contains(&byte)), + "{token}" + ); + assert!(token.as_bytes()[0].is_ascii_alphanumeric(), "{token}"); + token +} + +/// A document that has the one defect of a key the policy contract does not define, at `/Extra`. +fn document_with_an_unknown_key(id: &str, revision: u32) -> String { + document_with(id, revision, "[]", r#""Extra": 1,"#) +} + +fn unknown_key_errors() -> serde_json::Value { + serde_json::json!([{ "Code": "UnknownKey", "Pointer": "/Extra" }]) +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §management-state +#[tokio::test] +async fn the_management_state_of_an_accepted_policy_is_active_with_the_text_of_the_file() { + let text = document("corp-baseline", 3); + let state = broker_reading(&TestPolicyFile::holding(Some(&text))); + + let management = management(&state).await; + + assert_eq!( + members_of(&management), + ["Document", "Path", "State", "StoreToken"], + "{management}" + ); + assert_eq!(management["State"], "Active"); + assert_eq!(management["Document"], text); + assert!(!management["Path"].as_str().expect("Path is a string").is_empty()); + store_token(&management); +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §management-state +#[tokio::test] +async fn the_management_state_without_a_policy_file_is_missing() { + let state = broker_reading(&TestPolicyFile::holding(None)); + + let management = management(&state).await; + + assert_eq!(members_of(&management), ["Path", "State", "StoreToken"], "{management}"); + assert_eq!(management["State"], "Missing"); + store_token(&management); +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §management-state +#[tokio::test] +async fn the_management_state_of_a_file_that_is_not_a_valid_document_is_invalid_with_its_errors() { + let state = broker_reading(&TestPolicyFile::holding(Some(&document_with_an_unknown_key( + "corp-baseline", + 3, + )))); + + let management = management(&state).await; + + assert_eq!( + members_of(&management), + ["Errors", "InvalidReason", "Path", "State", "StoreToken"], + "{management}" + ); + assert_eq!(management["State"], "Invalid"); + assert_eq!(management["InvalidReason"], "InvalidDocument"); + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.policy.md §errors + assert_eq!(management["Errors"], unknown_key_errors()); +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §management-state +#[tokio::test] +async fn the_management_state_of_a_file_the_broker_cannot_write_has_a_read_only_reason() { + let state = broker_reading(&TestPolicyFile::read_only(&document("corp-baseline", 3))); + + let management = management(&state).await; + + assert_eq!( + members_of(&management), + ["Document", "Path", "ReadOnlyReason", "State", "StoreToken"], + "{management}" + ); + assert_eq!(management["ReadOnlyReason"], "UnsafePath"); +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §validation +#[tokio::test] +async fn a_validation_reports_the_policy_errors_of_the_document_and_changes_nothing() { + let held = document("corp-baseline", 3); + let file = TestPolicyFile::holding(Some(&held)); + let state = broker_reading(&file); + let before = management(&state).await; + + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.policy.md §errors + for (text, errors) in [ + (document("other", 1), serde_json::json!([])), + // A document is valid whatever the accepted policy is, so a lower revision of it has no error. + (document("corp-baseline", 2), serde_json::json!([])), + ( + "{".to_owned(), + serde_json::json!([{ "Code": "MalformedDocument", "Pointer": "" }]), + ), + (document_with_an_unknown_key("other", 1), unknown_key_errors()), + ] { + let reply = send( + &state, + &client(), + post_value(VALIDATE, &serde_json::json!({ "Document": text })), + ) + .await; + + assert_eq!(reply.status, 200, "{reply:?}"); + assert_eq!(reply.content_type.as_deref(), Some("application/json"), "{reply:?}"); + assert_eq!(reply.body, serde_json::json!({ "Errors": errors }), "{text}"); + } + + assert_eq!(file.content().as_deref(), Some(held.as_bytes())); + assert_eq!(management(&state).await, before); +} + +/// Sends a policy replacement from an elevated administrator. +async fn replace(state: &Arc, expected_store_token: &str, text: &str) -> Reply { + send( + state, + &administrator(), + post_value( + REPLACE, + &serde_json::json!({ "ExpectedStoreToken": expected_store_token, "Document": text }), + ), + ) + .await +} + +/// Checks an error response that carries the policy management state after the request, and returns that state. +#[track_caller] +fn assert_policy_state_error(reply: &Reply, status: u16, code: &str) -> serde_json::Value { + assert_eq!( + (reply.status, &reply.body["Code"]), + (status, &serde_json::json!(code)), + "{reply:?}" + ); + assert_eq!(reply.content_type.as_deref(), Some("application/json"), "{reply:?}"); + assert_eq!(reply.members(), ["Code", "Management", "Message"], "{reply:?}"); + reply.body["Management"].clone() +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §replacement +#[tokio::test] +async fn a_replacement_writes_the_document_and_holds_it_as_the_accepted_policy() { + for (held, text) in [ + ( + Some(document("corp-baseline", 3)), + document_with("corp-baseline", 4, ALLOW_ALL, ""), + ), + // A document whose id differs from the accepted policy's may have any revision. + ( + Some(document("corp-baseline", 3)), + document_with("other", 1, ALLOW_ALL, ""), + ), + // So may any document while the broker holds no accepted policy. + (None, document_with("corp-baseline", 1, ALLOW_ALL, "")), + (Some("{".to_owned()), document_with("corp-baseline", 1, ALLOW_ALL, "")), + ] { + let file = TestPolicyFile::holding(held.as_deref()); + let state = broker_reading(&file); + let before = management(&state).await; + let expected_store_token = store_token(&before); + + let reply = replace(&state, expected_store_token, &text).await; + + assert_eq!(reply.status, 200, "{reply:?}"); + assert_eq!(reply.content_type.as_deref(), Some("application/json"), "{reply:?}"); + assert_eq!(reply.members(), ["Management"], "{reply:?}"); + let after = &reply.body["Management"]; + assert_eq!(after["State"], "Active"); + assert_eq!(after["Document"], text); + assert_ne!(store_token(after), expected_store_token); + assert_eq!(file.content().as_deref(), Some(text.as_bytes())); + assert_eq!(&management(&state).await, after); + + // A package request evaluated after the response is evaluated against the new policy. + let evaluation = send( + &state, + &client(), + post_value(EVALUATE, &package_request(serde_json::json!({}))), + ) + .await; + assert_eq!(evaluation.body["Decision"]["Outcome"], "Allow", "{evaluation:?}"); + } +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §replacement +#[tokio::test] +async fn a_replacement_with_another_store_token_than_the_current_one_is_stale_store_token() { + let held = document("corp-baseline", 3); + // The outcome comes before those of a file the broker cannot write and of a document that is not valid. + for (file, text) in [ + (TestPolicyFile::holding(Some(&held)), document("corp-baseline", 4)), + (TestPolicyFile::read_only(&held), "{".to_owned()), + ] { + let state = broker_reading(&file); + let before = management(&state).await; + + let reply = replace(&state, "not-the-current-token", &text).await; + + let after = assert_policy_state_error(&reply, 409, "StaleStoreToken"); + assert_eq!(after, before); + assert_eq!(file.content().as_deref(), Some(held.as_bytes())); + } +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §replacement +#[tokio::test] +async fn a_replacement_of_a_file_the_broker_cannot_write_is_policy_not_writable() { + let held = document("corp-baseline", 3); + // The outcome comes before that of a document that is not valid. + for text in [document("corp-baseline", 4), "{".to_owned()] { + let file = TestPolicyFile::read_only(&held); + let state = broker_reading(&file); + let before = management(&state).await; + + let reply = replace(&state, store_token(&before), &text).await; + + let after = assert_policy_state_error(&reply, 409, "PolicyNotWritable"); + assert_eq!(after["ReadOnlyReason"], "UnsafePath"); + assert_eq!(after["Document"], held); + assert_eq!(file.content().as_deref(), Some(held.as_bytes())); + } +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §replacement +#[tokio::test] +async fn a_replacement_with_a_document_that_is_not_valid_is_invalid_policy() { + let held = document("corp-baseline", 3); + let file = TestPolicyFile::holding(Some(&held)); + let state = broker_reading(&file); + let before = management(&state).await; + + // The outcome comes before that of a revision that is not higher. + let reply = replace( + &state, + store_token(&before), + &document_with_an_unknown_key("corp-baseline", 2), + ) + .await; + + assert_eq!( + (reply.status, &reply.body["Code"]), + (422, &serde_json::json!("InvalidPolicy")), + "{reply:?}" + ); + assert_eq!(reply.members(), ["Code", "Errors", "Message"], "{reply:?}"); + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.policy.md §errors + assert_eq!(reply.body["Errors"], unknown_key_errors()); + assert_eq!(file.content().as_deref(), Some(held.as_bytes())); + assert_eq!(management(&state).await, before); +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §replacement +#[tokio::test] +async fn a_replacement_with_the_id_of_the_accepted_policy_and_no_higher_revision_is_revision_not_higher() { + let held = document("corp-baseline", 3); + for revision in [3, 2] { + let file = TestPolicyFile::holding(Some(&held)); + let state = broker_reading(&file); + let before = management(&state).await; + + let reply = replace( + &state, + store_token(&before), + &document_with("corp-baseline", revision, ALLOW_ALL, ""), + ) + .await; + + let after = assert_policy_state_error(&reply, 409, "RevisionNotHigher"); + assert_eq!(after, before); + assert_eq!(file.content().as_deref(), Some(held.as_bytes())); + } +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §replacement +#[tokio::test] +async fn a_replacement_the_broker_fails_to_write_is_persistence_failed() { + let held = document("corp-baseline", 3); + let file = TestPolicyFile::holding(Some(&held)); + let state = broker_reading(&file); + let before = management(&state).await; + file.fail_next_write(TestWriteFault::Refused); + + let reply = replace(&state, store_token(&before), &document("corp-baseline", 4)).await; + + reply.assert_error(500, "PersistenceFailed"); + assert_eq!(file.content().as_deref(), Some(held.as_bytes())); + assert_eq!(management(&state).await, before); +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §replacement +#[tokio::test] +async fn a_replacement_whose_written_file_does_not_hold_the_document_is_activation_failed() { + let file = TestPolicyFile::holding(Some(&document("corp-baseline", 3))); + let state = broker_reading(&file); + let before = management(&state).await; + file.fail_next_write(TestWriteFault::Garbled); + + let reply = replace(&state, store_token(&before), &document("corp-baseline", 4)).await; + + let after = assert_policy_state_error(&reply, 500, "ActivationFailed"); + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §management-state + // The file holds bytes that are not a valid document, so the broker holds no accepted policy. + assert_eq!(after["State"], "Invalid"); + assert_eq!(after, management(&state).await); + let health = send(&state, &client(), get("/v2/health")).await; + assert_eq!(health.body, serde_json::json!({ "Status": "Paused" })); +} + +// oracle: mutant recording the attempt or the result of a 2.0 policy replacement as the 1.x request, or recording an +// attempt without its result, or one for a request whose body the broker refused +#[tokio::test] +async fn a_policy_replacement_leaves_its_attempt_and_its_result_under_its_own_request() { + let file = TestPolicyFile::holding(Some(&document("corp-baseline", 3))); + let state = broker_reading(&file); + let before = management(&state).await; + crate::audit::tests::take_events(); + + let replaced = replace(&state, store_token(&before), &document("corp-baseline", 4)).await; + let outdated = replace(&state, store_token(&before), &document("corp-baseline", 5)).await; + let malformed = send(&state, &administrator(), post_json(REPLACE, "{")).await; + + assert_eq!(replaced.status, 200, "{replaced:?}"); + assert_policy_state_error(&outdated, 409, "StaleStoreToken"); + malformed.assert_error(400, "BadRequest"); + let records: Vec<_> = crate::audit::tests::take_events() + .into_iter() + .map(|entry| { + let intent = entry + .fields + .iter() + .find_map(|(field, value)| (field == "intent").then(|| value.clone())) + .expect("an intent field"); + (entry.event_code, intent) + }) + .collect(); + let intent = "POST /v2/policy".to_owned(); + assert_eq!( + records, + [ + (Some(agent_sysevent_codes::POLICY_WRITE_ATTEMPTED), intent.clone()), + (Some(agent_sysevent_codes::POLICY_CHANGE_SUCCEEDED), intent.clone()), + (Some(agent_sysevent_codes::POLICY_WRITE_ATTEMPTED), intent.clone()), + (Some(agent_sysevent_codes::POLICY_CHANGE_FAILED), intent), + ] + ); +} From 524d8a40227bcb969373dbd7cf05021d1d463732 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Tue, 1 Dec 2026 05:57:13 +0900 Subject: [PATCH 06/38] feat(agent): answer a 2.0 bypass request with InternalError The broker binds a bypass token to a 1.x request and uses the token up when it checks it, so it can neither compare a 2.0 bypass request with the bound request nor refuse one without using up its token. A well-formed bypass request is therefore answered with InternalError, which lets the client treat its outcome as unknown, and no command runs for it. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- .../now-package-broker/src/v2/routes/mod.rs | 9 +++++++- .../now-package-broker/src/v2/routes/tests.rs | 21 +++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/crates/now-package-broker/src/v2/routes/mod.rs b/crates/now-package-broker/src/v2/routes/mod.rs index a49cffa69..637e37363 100644 --- a/crates/now-package-broker/src/v2/routes/mod.rs +++ b/crates/now-package-broker/src/v2/routes/mod.rs @@ -382,7 +382,14 @@ fn internal_error(error: &dyn std::fmt::Display) -> Response { error_response(v2::ErrorCode::InternalError, "the broker failed to answer the request") } -/// The response of an endpoint the broker does not answer yet. +/// The response to a bypass request ([§bypass]), whose outcome `InternalError` replaces ([§errors]). +/// +/// The broker binds a bypass token to a 1.x request and uses the token up when it checks it. +/// It can therefore neither compare a 2.0 request with the bound one, nor refuse one without using up its token. +/// A client treats the outcome of such a request as unknown, and no command runs for it. +/// +/// [§bypass]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#bypass +/// [§errors]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#errors fn not_served() -> Response { error_response(v2::ErrorCode::InternalError, "the broker does not serve this endpoint") } diff --git a/crates/now-package-broker/src/v2/routes/tests.rs b/crates/now-package-broker/src/v2/routes/tests.rs index 180508356..fe7cfefe6 100644 --- a/crates/now-package-broker/src/v2/routes/tests.rs +++ b/crates/now-package-broker/src/v2/routes/tests.rs @@ -2149,3 +2149,24 @@ async fn a_policy_replacement_leaves_its_attempt_and_its_result_under_its_own_re ] ); } + +// oracle: mutant answering a bypass request the broker cannot serve with a body of the 1.x encoding, or running a +// command for it +#[tokio::test] +async fn a_bypass_request_is_internal_error_and_runs_nothing() { + let broker = Broker::with_policy(ALLOW_ALL, ""); + let request = Request::builder() + .method(Method::POST) + .uri(EXECUTE_BYPASS) + .header("content-type", "application/json") + .header("x-devolutions-bypass-token", "0123456789abcdef") + .body(Body::from( + execution_request("request-1", serde_json::json!({})).to_string(), + )) + .expect("a valid test request"); + + let reply = send(&broker.state, &client(), request).await; + + reply.assert_error(500, "InternalError"); + assert_eq!(broker.runs().await, 0); +} From 2f715301bc652c840901bbe6ef2cea4ffa071473 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Tue, 1 Dec 2026 06:25:26 +0900 Subject: [PATCH 07/38] feat(agent): serve a 2.0 bypass request its token authorizes The 2.0 bypass route answered InternalError to every request, because the tokens of the 1.x remote operations bind a 1.x request and are used up when checked. The broker now holds the bypass tokens of the 2.0 encoding in a store of their own, which binds each one to a 2.0 bypass request and to a user, and tells whether a token authorizes a request without using it up. The route uses a token up and starts its operation while the tokens are locked, so requests with one token that arrive together start one operation and each equal one gets it. Bypass operations have a registry of their own, so a RequestId of a bypass request neither conflicts with nor replays an execution request. A request without Source is read under the only source name of its manager when it has one. Any other request without Source that is not unreadable by its elevation is answered InternalError and keeps its token, because the reading and the command builders take a package request, which always names a source. Devolutions Agent does not give the broker a token of this encoding yet, so no request is authorized outside tests. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- .../now-package-broker/src/v2/bypass/mod.rs | 11 + .../src/v2/bypass/reading.rs | 422 ++++++++++++++ .../src/v2/bypass/tokens.rs | 351 ++++++++++++ crates/now-package-broker/src/v2/mod.rs | 1 + .../src/v2/routes/bypass.rs | 145 +++++ .../now-package-broker/src/v2/routes/held.rs | 29 +- .../now-package-broker/src/v2/routes/mod.rs | 19 +- .../src/v2/routes/operations.rs | 13 +- .../now-package-broker/src/v2/routes/tests.rs | 515 +++++++++++++++++- 9 files changed, 1466 insertions(+), 40 deletions(-) create mode 100644 crates/now-package-broker/src/v2/bypass/mod.rs create mode 100644 crates/now-package-broker/src/v2/bypass/reading.rs create mode 100644 crates/now-package-broker/src/v2/bypass/tokens.rs create mode 100644 crates/now-package-broker/src/v2/routes/bypass.rs diff --git a/crates/now-package-broker/src/v2/bypass/mod.rs b/crates/now-package-broker/src/v2/bypass/mod.rs new file mode 100644 index 000000000..b828df1b3 --- /dev/null +++ b/crates/now-package-broker/src/v2/bypass/mod.rs @@ -0,0 +1,11 @@ +//! Bypass tokens, and how the broker reads the requests they authorize ([§bypass]). +//! +//! The tokens of the 1.x remote operations are held elsewhere and authorize no request read here. +//! +//! [§bypass]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#bypass + +mod reading; +mod tokens; + +pub(crate) use self::reading::{Reading, read, uninstall_names_agent}; +pub(crate) use self::tokens::{BypassTokens, TokenDigest}; diff --git a/crates/now-package-broker/src/v2/bypass/reading.rs b/crates/now-package-broker/src/v2/bypass/reading.rs new file mode 100644 index 000000000..5b740f0bd --- /dev/null +++ b/crates/now-package-broker/src/v2/bypass/reading.rs @@ -0,0 +1,422 @@ +//! How the broker reads a bypass request ([§bypass-reading]), and which one names Devolutions Agent ([§bypass]). +//! +//! [§bypass]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#bypass +//! [§bypass-reading]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#bypass-reading + +use std::sync::LazyLock; + +use now_policy_api::v2; +use now_policy_eval as eval; +use uuid::Uuid; + +use crate::v2::wire; + +/// How the broker reads a bypass request ([§bypass-reading]). +/// +/// [§bypass-reading]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#bypass-reading +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) enum Reading { + /// The request is readable, and its operation runs the command of this package request. + Readable(Box), + /// The request is unreadable. + Unreadable, + /// The broker cannot tell whether the request is readable, for the reason given, and runs nothing for it. + NotRead(&'static str), +} + +/// Reads a bypass request ([§bypass-reading]). +/// +/// A request with a `Source.Name`, its own or the only one of its manager, is read as the package request with the +/// same members. +/// A request without one is not read, apart from the elevated ones that are unreadable whatever their other members: +/// the reading the broker has takes a package request, which always has a `Source.Name`, and reading such a request +/// under a name it does not have would apply the cases that test `Source.Name` to it. +/// +/// [§bypass-reading]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#bypass-reading +pub(crate) fn read(request: &v2::BypassRequest) -> Reading { + let listed_source = if request.source.is_none() { + // A run as administrator uses only sources from machine-wide configuration, and only an administrator can + // change the sources these two managers are configured with. + if request.operation != v2::Operation::Uninstall + && request.elevation == v2::Elevation::Elevated + && !matches!(request.manager, v2::Manager::Winget | v2::Manager::Chocolatey) + { + return Reading::Unreadable; + } + + match only_source_name(request.manager, request.operation).map(v2::SourceName::parse) { + Some(Ok(name)) => Some(name), + Some(Err(_)) => return Reading::NotRead("the only source name of the manager is not a source name"), + None => None, + } + } else { + None + }; + + let Some(package_request) = wire::bypass_package_request(request, listed_source.as_ref()) else { + return Reading::NotRead("the broker does not read a request that has no source name"); + }; + let package_request = wire::evaluator_request(&package_request); + + match is_unreadable(&package_request) { + Some(true) => Reading::Unreadable, + Some(false) => Reading::Readable(Box::new(package_request)), + None => Reading::NotRead("the evaluator did not read the package request"), + } +} + +/// Returns the only source name the reading of `manager` names for `operation`, if it names one ([§managers]). +/// +/// [§managers]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.policy.md#managers +fn only_source_name(manager: v2::Manager, operation: v2::Operation) -> Option<&'static str> { + match manager { + v2::Manager::Npm => Some("npm"), + v2::Manager::Bun => Some("Bun"), + v2::Manager::Cargo => Some("crates.io"), + v2::Manager::Pip => Some("pip"), + // An Uninstall through Dotnet has no only source name. + v2::Manager::Dotnet => (operation != v2::Operation::Uninstall).then_some("nuget.org"), + v2::Manager::Winget + | v2::Manager::PowerShell + | v2::Manager::PowerShell7 + | v2::Manager::Apt + | v2::Manager::Chocolatey + | v2::Manager::Dnf + | v2::Manager::Flatpak + | v2::Manager::Homebrew + | v2::Manager::Pacman + | v2::Manager::Scoop + | v2::Manager::Snap + | v2::Manager::Vcpkg => None, + } +} + +/// A valid policy, which plays no part in what [`is_unreadable`] returns. +const ANY_POLICY: &str = r#"{ + "PolicyFormatVersion": "2.0.0", + "Metadata": { "Id": "bypass-reading", "Publisher": "Devolutions", "Revision": 1, "PublishedAt": "2026-01-01T00:00:00Z" }, + "TrustedSources": [], + "Rules": [] +}"#; + +/// A time at which [`ANY_POLICY`] is evaluated, which plays no part in what [`is_unreadable`] returns either. +const ANY_TIME: &str = "2026-01-01T00:00:00Z"; + +/// Tells whether `request` is unreadable ([CONTRACT.policy.md §reading]), or `None` when the evaluator does not say. +/// +/// This stands in for a reading function, which the evaluator does not export: the only way to ask it whether a +/// request is unreadable is to evaluate the request and look at the check of the decision. +/// A bypass request is not evaluated against any policy, and this does not make it so: `UnreadableRequest` is the +/// first check of every evaluation ([§precedence]), decided from the request alone, so the policy and the time given +/// here change nothing of the answer, and nothing else of the decision is looked at. +/// +/// [CONTRACT.policy.md §reading]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.policy.md#reading +/// [§precedence]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.policy.md#precedence +fn is_unreadable(request: &eval::Request) -> Option { + static POLICY: LazyLock> = + LazyLock::new(|| Some((eval::parse_policy(ANY_POLICY.as_bytes()).ok()?, ANY_TIME.parse().ok()?))); + + let (policy, time) = POLICY.as_ref()?; + let decision = eval::evaluate(policy, request, *time).ok()?; + + Some(decision.check == eval::Check::UnreadableRequest) +} + +/// Tells whether an Uninstall through `manager` of `package_id` names Devolutions Agent ([§bypass]). +/// +/// `agent_product_code` is the product code of the installed Devolutions Agent, when one is installed. +/// +/// [§bypass]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#bypass +pub(crate) fn uninstall_names_agent(manager: v2::Manager, package_id: &str, agent_product_code: Option) -> bool { + let name = package_id.split_once('#').map_or(package_id, |(name, _)| name); + let name = name.rsplit_once('@').map_or(name, |(name, _)| name); + + match manager { + v2::Manager::Winget => { + name.eq_ignore_ascii_case("Devolutions.Agent") + || agent_product_code + .is_some_and(|code| package_id.to_ascii_lowercase().contains(&code.hyphenated().to_string())) + } + v2::Manager::Chocolatey => name.eq_ignore_ascii_case("devo-agent"), + v2::Manager::PowerShell + | v2::Manager::PowerShell7 + | v2::Manager::Apt + | v2::Manager::Bun + | v2::Manager::Cargo + | v2::Manager::Dnf + | v2::Manager::Dotnet + | v2::Manager::Flatpak + | v2::Manager::Homebrew + | v2::Manager::Npm + | v2::Manager::Pacman + | v2::Manager::Pip + | v2::Manager::Scoop + | v2::Manager::Snap + | v2::Manager::Vcpkg => false, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn request(members: serde_json::Value) -> v2::BypassRequest { + let mut body = serde_json::json!({ + "RequestId": "request-1", + "Operation": "Install", + "Manager": "Winget", + "Package": { "Id": "Git.Git" }, + "Elevation": "NonElevated", + }); + body.as_object_mut() + .expect("an object") + .extend(members.as_object().expect("an object").clone()); + wire::read_bypass_request(body.to_string().as_bytes()).expect("a bypass request") + } + + /// The `Source.Name` of the package request that `request` is read as. + fn read_source_name(request: &v2::BypassRequest) -> String { + match read(request) { + Reading::Readable(package_request) => package_request.source.name, + other => panic!("the request is not readable: {other:?}"), + } + } + + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §bypass-reading + #[test] + fn a_request_with_source_is_read_as_the_package_request_with_the_same_members() { + let request = request(serde_json::json!({ + "Operation": "Update", + "Manager": "Chocolatey", + "Source": { "Name": "chocolatey" }, + "Package": { "Id": "git", "Version": "2.45.1" }, + "Scope": "Machine", + "Elevation": "Elevated", + })); + + let Reading::Readable(read) = read(&request) else { + panic!("the request is not readable"); + }; + + assert_eq!(read.operation, eval::Operation::Update); + assert_eq!(read.manager, eval::Manager::Chocolatey); + assert_eq!(read.source.name, "chocolatey"); + assert_eq!(read.package.id, "git"); + assert_eq!(read.package.version.as_deref(), Some("2.45.1")); + assert_eq!(read.package.architecture, None); + assert_eq!(read.scope, Some(eval::Scope::Machine)); + assert_eq!(read.elevation, eval::Elevation::Elevated); + assert_eq!(read.opt_ins, eval::OptIns::default()); + } + + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.policy.md §reading + #[test] + fn a_request_with_source_that_is_unreadable_as_a_package_request_is_unreadable() { + let cases = [ + ( + "a source name that ends with white space", + serde_json::json!({ "Source": { "Name": "winget " } }), + ), + ( + "a WinGet source name that is not plain", + serde_json::json!({ "Source": { "Name": "win/get" } }), + ), + ( + "a WinGet id that starts with a hyphen", + serde_json::json!({ "Source": { "Name": "winget" }, "Package": { "Id": "-Git.Git" } }), + ), + ( + "a manager the broker builds no command for", + serde_json::json!({ "Manager": "Apt", "Source": { "Name": "main" } }), + ), + ( + "NoUpgrade through Scoop", + serde_json::json!({ "Manager": "Scoop", "Source": { "Name": "main" }, "OptIns": { "NoUpgrade": {} } }), + ), + ]; + + for (case, members) in cases { + assert_eq!(read(&request(members)), Reading::Unreadable, "{case}"); + } + } + + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §bypass-reading + // The only source names are those of CONTRACT.policy.md §manager-npm, §manager-bun, §manager-cargo, §manager-pip + // and §manager-dotnet. + #[test] + fn a_request_without_source_is_read_with_the_only_source_name_of_its_manager() { + let cases = [ + ("Npm", "Install", "left-pad", "npm"), + ("Npm", "Uninstall", "left-pad", "npm"), + ("Bun", "Update", "left-pad", "Bun"), + ("Bun", "Uninstall", "left-pad", "Bun"), + ("Cargo", "Install", "ripgrep", "crates.io"), + ("Cargo", "Uninstall", "ripgrep", "crates.io"), + ("Pip", "Update", "requests", "pip"), + ("Pip", "Uninstall", "requests", "pip"), + ("Dotnet", "Install", "dotnet-ef", "nuget.org"), + ("Dotnet", "Update", "dotnet-ef", "nuget.org"), + ]; + + for (manager, operation, package_id, source_name) in cases { + let request = request(serde_json::json!({ + "Manager": manager, + "Operation": operation, + "Package": { "Id": package_id }, + })); + + assert_eq!(read_source_name(&request), source_name, "{manager} {operation}"); + } + } + + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.policy.md §manager-npm + #[test] + fn a_request_without_source_is_unreadable_when_a_case_that_tests_other_members_makes_it_so() { + // The identifier is neither a registry name nor an alias. + let request = request(serde_json::json!({ "Manager": "Npm", "Package": { "Id": "-left-pad" } })); + + assert_eq!(read(&request), Reading::Unreadable); + } + + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §bypass-reading + #[test] + fn an_elevated_install_or_update_without_source_is_unreadable_unless_through_winget_or_chocolatey() { + let managers = [ + "PowerShell", + "PowerShell7", + "Apt", + "Bun", + "Cargo", + "Dnf", + "Dotnet", + "Flatpak", + "Homebrew", + "Npm", + "Pacman", + "Pip", + "Scoop", + "Snap", + "Vcpkg", + ]; + + for manager in managers { + for operation in ["Install", "Update"] { + let request = request(serde_json::json!({ + "Manager": manager, + "Operation": operation, + "Package": { "Id": "package" }, + "Elevation": "Elevated", + })); + + assert_eq!(read(&request), Reading::Unreadable, "{manager} {operation}"); + } + } + } + + // oracle: mutant reading a request that has no source name under a name it does not have, or as unreadable + #[test] + fn a_request_that_has_no_source_name_is_not_read() { + let cases = [ + ("Winget", "Install", "NonElevated"), + ("Winget", "Update", "Elevated"), + ("Winget", "Uninstall", "NonElevated"), + ("Chocolatey", "Install", "Elevated"), + ("Chocolatey", "Uninstall", "Elevated"), + ("PowerShell", "Install", "NonElevated"), + ("PowerShell", "Uninstall", "Elevated"), + ("PowerShell7", "Update", "NonElevated"), + ("Dotnet", "Uninstall", "NonElevated"), + ("Scoop", "Install", "NonElevated"), + ("Scoop", "Uninstall", "NonElevated"), + ("Vcpkg", "Install", "NonElevated"), + ("Vcpkg", "Uninstall", "NonElevated"), + ]; + + for (manager, operation, elevation) in cases { + let request = request(serde_json::json!({ + "Manager": manager, + "Operation": operation, + "Package": { "Id": "package" }, + "Elevation": elevation, + })); + + let reading = read(&request); + + assert!( + matches!(reading, Reading::NotRead(_)), + "{manager} {operation}: {reading:?}" + ); + } + } + + const PRODUCT_CODE: &str = "0f2a6b3c-4d5e-4f60-8a9b-0c1d2e3f4a5b"; + + fn product_code() -> Option { + Some(PRODUCT_CODE.parse().expect("a UUID")) + } + + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §bypass + #[test] + fn an_uninstall_names_devolutions_agent_by_its_id_or_by_its_product_code() { + let cases = [ + (v2::Manager::Winget, "Devolutions.Agent"), + (v2::Manager::Winget, "devolutions.AGENT"), + // The text from the first `#` is removed, then the text from the last `@`. + (v2::Manager::Winget, "Devolutions.Agent#main"), + (v2::Manager::Winget, "Devolutions.Agent@2026.1.0"), + (v2::Manager::Winget, "Devolutions.Agent@1#a@b#c"), + (v2::Manager::Chocolatey, "devo-agent"), + (v2::Manager::Chocolatey, "Devo-Agent"), + (v2::Manager::Chocolatey, "devo-agent@2026.1.0"), + (v2::Manager::Winget, "{0f2a6b3c-4d5e-4f60-8a9b-0c1d2e3f4a5b}"), + (v2::Manager::Winget, "{0F2A6B3C-4D5E-4F60-8A9B-0C1D2E3F4A5B}"), + ( + v2::Manager::Winget, + "ARP/Machine/X64/{0f2a6b3c-4d5e-4f60-8a9b-0c1d2e3f4a5b}@1", + ), + ]; + + for (manager, package_id) in cases { + assert!( + uninstall_names_agent(manager, package_id, product_code()), + "{manager:?} {package_id}" + ); + } + } + + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §bypass + #[test] + fn an_uninstall_of_anything_else_does_not_name_devolutions_agent() { + let cases = [ + (v2::Manager::Winget, "Devolutions.Agent2"), + (v2::Manager::Winget, "Devolutions.Agent.Tools"), + (v2::Manager::Winget, "devo-agent"), + (v2::Manager::Chocolatey, "Devolutions.Agent"), + (v2::Manager::Scoop, "Devolutions.Agent"), + (v2::Manager::Winget, "scope@Devolutions.Agent"), + (v2::Manager::Winget, "other#Devolutions.Agent"), + // The product code names the Agent through WinGet only, and in hyphenated form. + (v2::Manager::Chocolatey, "{0f2a6b3c-4d5e-4f60-8a9b-0c1d2e3f4a5b}"), + (v2::Manager::Winget, "{0f2a6b3c4d5e4f608a9b0c1d2e3f4a5b}"), + (v2::Manager::Winget, "{1f2a6b3c-4d5e-4f60-8a9b-0c1d2e3f4a5b}"), + ]; + + for (manager, package_id) in cases { + assert!( + !uninstall_names_agent(manager, package_id, product_code()), + "{manager:?} {package_id}" + ); + } + } + + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §bypass + #[test] + fn without_an_installed_agent_no_product_code_names_it() { + assert!(!uninstall_names_agent( + v2::Manager::Winget, + "{0f2a6b3c-4d5e-4f60-8a9b-0c1d2e3f4a5b}", + None + )); + assert!(uninstall_names_agent(v2::Manager::Winget, "Devolutions.Agent", None)); + } +} diff --git a/crates/now-package-broker/src/v2/bypass/tokens.rs b/crates/now-package-broker/src/v2/bypass/tokens.rs new file mode 100644 index 000000000..4bdb2019b --- /dev/null +++ b/crates/now-package-broker/src/v2/bypass/tokens.rs @@ -0,0 +1,351 @@ +//! The bypass tokens the broker holds ([§bypass]). +//! +//! [§bypass]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#bypass + +use std::collections::HashMap; +use std::time::{Duration, Instant}; + +use now_policy_api::v2; +use parking_lot::{Mutex, MutexGuard}; +use sha2::{Digest as _, Sha256}; +use win_api_wrappers::identity::sid::Sid; + +/// How long the broker holds a token that no request used up, after which it discards it. +/// +/// A token authorizes one request that the Agent expects at once, so a short life bounds how long a token that +/// reached another process stays useful. +const TOKEN_LIFETIME: Duration = Duration::from_secs(60); + +/// The most tokens the broker holds at once, so that the tokens it is given never grow its memory without bound. +const MAX_HELD_TOKENS: usize = 256; + +/// The SHA-256 digest of a bypass token. +/// +/// The broker keeps and compares digests, never tokens: two digests are equal exactly when their tokens have the +/// same characters, and a digest that leaves the broker, such as in a memory dump, authorizes nothing. +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +pub(crate) struct TokenDigest([u8; 32]); + +impl TokenDigest { + /// Returns the digest of the token whose characters are `token`. + /// + /// `token` may be any bytes, such as the field value of a request header: bytes that are no token have the + /// digest of no token the broker holds. + pub(crate) fn of(token: &[u8]) -> Self { + Self(Sha256::digest(token).into()) + } + + /// Returns the digest as text, which names the token where a name is needed and gives nothing of the token away. + pub(crate) fn to_hex(self) -> String { + hex::encode(self.0) + } +} + +/// Why the broker does not hold a token it was given. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum HoldError { + /// The text is not a bypass token. + NotAToken, + /// The broker already holds this token. + AlreadyHeld, + /// The broker holds [`MAX_HELD_TOKENS`] tokens. + TooManyTokens, +} + +impl core::fmt::Display for HoldError { + fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + formatter.write_str(match self { + Self::NotAToken => "the text is not a bypass token", + Self::AlreadyHeld => "the broker already holds this bypass token", + Self::TooManyTokens => "the broker holds as many bypass tokens as it allows", + }) + } +} + +impl core::error::Error for HoldError {} + +/// What a token binds. +struct Bound { + /// The bypass request, `RequestId` included. + request: v2::BypassRequest, + /// The SID of the Windows user. + user_sid: Sid, + /// When the broker discards the token. + expires_at: Instant, +} + +/// The bypass tokens the broker holds, which a restart of the broker discards. +#[derive(Default)] +pub(crate) struct BypassTokens { + held: Mutex>, +} + +impl BypassTokens { + /// Holds `token`, which then authorizes the bypass request `request` of the user `user_sid` once, within + /// [`TOKEN_LIFETIME`]. + /// + /// This is how Devolutions Agent gives the broker a token. + /// The Agent gives each token once: the broker does not remember a token it no longer holds, so a token given + /// again after it was used up is held as a new one. + #[cfg_attr( + not(test), + expect( + dead_code, + reason = "Devolutions Agent does not give the broker a token of the 2.0 encoding yet" + ) + )] + pub(crate) fn hold(&self, token: &str, request: v2::BypassRequest, user_sid: Sid) -> Result<(), HoldError> { + self.hold_at(Instant::now(), token, request, user_sid) + } + + fn hold_at(&self, now: Instant, token: &str, request: v2::BypassRequest, user_sid: Sid) -> Result<(), HoldError> { + let token = v2::BypassToken::parse(token).map_err(|_| HoldError::NotAToken)?; + let digest = TokenDigest::of(token.as_str().as_bytes()); + + let mut held = self.lock_at(now).held; + if held.contains_key(&digest) { + return Err(HoldError::AlreadyHeld); + } + if !(held.len() < MAX_HELD_TOKENS) { + return Err(HoldError::TooManyTokens); + } + held.insert( + digest, + Bound { + request, + user_sid, + expires_at: now + TOKEN_LIFETIME, + }, + ); + + Ok(()) + } + + /// Locks the tokens the broker holds now. + /// + /// No other request finds a token held or used up while the returned value lives. + /// A request keeps it from the moment it looks for the operation of its token until it has started one, so that + /// requests with one token that arrive together start one operation, and each of them finds either the token + /// held or the operation it started ([§bypass]). + /// + /// [§bypass]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#bypass + pub(crate) fn lock(&self) -> HeldTokens<'_> { + self.lock_at(Instant::now()) + } + + fn lock_at(&self, now: Instant) -> HeldTokens<'_> { + let mut held = self.held.lock(); + held.retain(|_, bound| now < bound.expires_at); + + HeldTokens { held } + } +} + +/// The tokens the broker holds, locked ([`BypassTokens::lock`]). +pub(crate) struct HeldTokens<'a> { + held: MutexGuard<'a, HashMap>, +} + +impl HeldTokens<'_> { + /// Tells whether the token `token` authorizes the bypass request `request` from an owner whose user is + /// `owner_sid` ([§bypass]). + /// + /// The broker holds the token after this, whatever the answer. + /// + /// [§bypass]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#bypass + pub(crate) fn authorizes(&self, token: &TokenDigest, owner_sid: &Sid, request: &v2::BypassRequest) -> bool { + self.held + .get(token) + .is_some_and(|bound| bound.user_sid == *owner_sid && bound.request == *request) + } + + /// Uses up the token `token`, which never authorizes a request again. + pub(crate) fn use_up(&mut self, token: &TokenDigest) { + self.held.remove(token); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const TOKEN: &str = "0123456789abcdef"; + + fn request(body: &serde_json::Value) -> v2::BypassRequest { + crate::v2::wire::read_bypass_request(body.to_string().as_bytes()).expect("a bypass request") + } + + fn install() -> serde_json::Value { + serde_json::json!({ + "RequestId": "request-1", + "Operation": "Install", + "Manager": "Winget", + "Source": { "Name": "winget" }, + "Package": { "Id": "Git.Git" }, + "Elevation": "NonElevated", + }) + } + + fn with(mut body: serde_json::Value, member: &str, value: serde_json::Value) -> serde_json::Value { + body[member] = value; + body + } + + fn user() -> Sid { + Sid::from_well_known(windows::Win32::Security::WinLocalSystemSid, None).expect("a SID") + } + + fn other_user() -> Sid { + Sid::from_well_known(windows::Win32::Security::WinLocalServiceSid, None).expect("a SID") + } + + fn digest(token: &str) -> TokenDigest { + TokenDigest::of(token.as_bytes()) + } + + /// Tokens that hold [`TOKEN`] for [`install`] and [`user`]. + fn holding() -> BypassTokens { + let tokens = BypassTokens::default(); + tokens.hold(TOKEN, request(&install()), user()).expect("hold the token"); + tokens + } + + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §bypass + #[test] + fn a_token_is_1_to_2048_characters_of_its_set_that_start_with_a_letter_or_digit() { + let longest = "a".repeat(2048); + let accepted = ["a", "Z", "0", "aZ09._~:-", longest.as_str()]; + let too_long = "a".repeat(2049); + let refused = [ + "", + too_long.as_str(), + ".a", + "_a", + "~a", + ":a", + "-a", + "a b", + "a,b", + "a/b", + "a+b", + "a=b", + "a\u{e9}", + " a", + "a\t", + ]; + + for token in accepted { + let held = BypassTokens::default().hold(token, request(&install()), user()); + assert_eq!(held, Ok(()), "{} characters", token.len()); + } + for token in refused { + let held = BypassTokens::default().hold(token, request(&install()), user()); + assert_eq!(held, Err(HoldError::NotAToken), "{token:?}"); + } + } + + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §bypass + #[test] + fn a_held_token_authorizes_the_request_it_binds_from_the_user_it_binds() { + let tokens = holding(); + // Two objects are equal whatever the order of their keys. + let reordered: serde_json::Value = serde_json::from_str( + r#"{ "Elevation": "NonElevated", "Package": { "Id": "Git.Git" }, "Source": { "Name": "winget" }, + "Manager": "Winget", "Operation": "Install", "RequestId": "request-1" }"#, + ) + .expect("JSON"); + + assert!(tokens.lock().authorizes(&digest(TOKEN), &user(), &request(&install()))); + assert!(tokens.lock().authorizes(&digest(TOKEN), &user(), &request(&reordered))); + } + + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §bypass + #[test] + fn a_token_authorizes_no_request_that_differs_from_what_it_binds() { + let tokens = holding(); + let held = tokens.lock(); + let bound = request(&install()); + + // Another token, and the token with other characters. + assert!(!held.authorizes(&digest("0123456789abcdee"), &user(), &bound)); + assert!(!held.authorizes(&digest("0123456789ABCDEF"), &user(), &bound)); + assert!(!held.authorizes(&digest("0123456789abcdef "), &user(), &bound)); + // Another user. + assert!(!held.authorizes(&digest(TOKEN), &other_user(), &bound)); + // Another `RequestId`. + let other_id = request(&with(install(), "RequestId", serde_json::json!("request-2"))); + assert!(!held.authorizes(&digest(TOKEN), &user(), &other_id)); + // Another body: a member with another value, a member more, and a member less. + let other_package = request(&with(install(), "Package", serde_json::json!({ "Id": "Git.Git2" }))); + assert!(!held.authorizes(&digest(TOKEN), &user(), &other_package)); + let with_opt_ins = request(&with(install(), "OptIns", serde_json::json!({}))); + assert!(!held.authorizes(&digest(TOKEN), &user(), &with_opt_ins)); + let mut without_source = install(); + without_source.as_object_mut().expect("an object").remove("Source"); + assert!(!held.authorizes(&digest(TOKEN), &user(), &request(&without_source))); + } + + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §bypass + #[test] + fn a_token_is_held_until_it_is_used_up_and_never_authorizes_again() { + let tokens = holding(); + let bound = request(&install()); + + // Asking whether the token authorizes a request does not use it up. + assert!(tokens.lock().authorizes(&digest(TOKEN), &user(), &bound)); + assert!(!tokens.lock().authorizes(&digest(TOKEN), &other_user(), &bound)); + assert!(tokens.lock().authorizes(&digest(TOKEN), &user(), &bound)); + + tokens.lock().use_up(&digest(TOKEN)); + + assert!(!tokens.lock().authorizes(&digest(TOKEN), &user(), &bound)); + } + + // oracle: mutant holding a token past its lifetime, or discarding it before + #[test] + fn a_token_is_discarded_when_its_lifetime_ends() { + let tokens = BypassTokens::default(); + let given = Instant::now(); + tokens + .hold_at(given, TOKEN, request(&install()), user()) + .expect("hold the token"); + let bound = request(&install()); + + let just_before = given + TOKEN_LIFETIME - Duration::from_millis(1); + assert!(tokens.lock_at(just_before).authorizes(&digest(TOKEN), &user(), &bound)); + assert!( + !tokens + .lock_at(given + TOKEN_LIFETIME) + .authorizes(&digest(TOKEN), &user(), &bound) + ); + } + + // oracle: mutant holding a token twice, or more tokens than the bound, or counting discarded tokens in the bound + #[test] + fn the_broker_holds_each_token_once_and_a_bounded_number_of_them() { + let tokens = BypassTokens::default(); + let given = Instant::now(); + for index in 0..MAX_HELD_TOKENS { + tokens + .hold_at(given, &format!("token-{index}"), request(&install()), user()) + .expect("hold the token"); + } + + let again = tokens.hold_at(given, "token-0", request(&install()), other_user()); + let one_more = tokens.hold_at(given, "one-more", request(&install()), user()); + // The first binding of a token stands. + let rebound = tokens + .lock_at(given) + .authorizes(&digest("token-0"), &other_user(), &request(&install())); + let still_bound = tokens + .lock_at(given) + .authorizes(&digest("token-0"), &user(), &request(&install())); + let after_they_expired = tokens.hold_at(given + TOKEN_LIFETIME, "one-more", request(&install()), user()); + + assert_eq!(again, Err(HoldError::AlreadyHeld)); + assert_eq!(one_more, Err(HoldError::TooManyTokens)); + assert!(!rebound); + assert!(still_bound); + assert_eq!(after_they_expired, Ok(())); + } +} diff --git a/crates/now-package-broker/src/v2/mod.rs b/crates/now-package-broker/src/v2/mod.rs index ac7e09832..2ad251882 100644 --- a/crates/now-package-broker/src/v2/mod.rs +++ b/crates/now-package-broker/src/v2/mod.rs @@ -3,6 +3,7 @@ //! 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(crate) mod bypass; pub mod execution; pub mod policy; pub(crate) mod routes; diff --git a/crates/now-package-broker/src/v2/routes/bypass.rs b/crates/now-package-broker/src/v2/routes/bypass.rs new file mode 100644 index 000000000..3e5be2c8c --- /dev/null +++ b/crates/now-package-broker/src/v2/routes/bypass.rs @@ -0,0 +1,145 @@ +//! The endpoint that runs the package request a bypass token authorizes ([§bypass]). +//! +//! [§bypass]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#bypass + +use axum::http::{HeaderMap, StatusCode}; +use axum::response::Response; +use now_policy_api::v2; +use tracing::warn; + +use super::operations::operation_status; +use super::{Connection, error_response, internal_error, json}; +use crate::v2::bypass::{Reading, TokenDigest, read, uninstall_names_agent}; +use crate::v2::execution::{Existing, Start, StartedOperation}; + +impl Connection { + /// Starts the operation of the bypass request `request`, when the token in `headers` authorizes it and nothing + /// refuses it, unless the broker holds the operation that request started ([§bypass]). + /// + /// No policy is evaluated, so this answers the same whether or not the broker holds an accepted policy. + /// + /// [§bypass]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#bypass + pub(super) fn execute_bypass(&self, headers: &HeaderMap, request: &v2::BypassRequest) -> Response { + // No token authorizes a request that has no such header, or several. + let Some(token) = token_of(headers) else { + return token_rejected(); + }; + let registries = self.state.operations.of(&self.state); + let caller = self.caller(); + // A token starts one operation at most, so its digest names that operation among those of its owner. + let token_name = token.to_hex(); + + // UNTESTED: A request never finds a token used up before the operation it started is held. + // Otherwise, of two equal requests that arrive together, the second could be answered `BypassTokenRejected` + // while the first starts the operation, where the contract has it get that operation. + // Everything from the lookup of the operation to its start happens while the tokens are locked, and a test + // that sends requests together passes most of the time without that; when changing this function, keep the + // lock from the lookup until the operation is held. + let mut tokens = registries.bypass_tokens.lock(); + + match registries.bypasses.existing(&caller.owner, &token_name, request) { + Some(Existing::Replayed(started)) => return bypass_response(started), + // The token was used up for another request, and never authorizes a request again, even when the broker + // was given it once more. + Some(Existing::Conflict) => return token_rejected(), + None => {} + } + + if !tokens.authorizes(&token, caller.owner.user_sid(), request) { + return token_rejected(); + } + + if request.operation == v2::Operation::Uninstall { + let names_agent = match (self.state.agent_product_code)() { + Ok(product_code) => uninstall_names_agent(request.manager, request.package.id.as_str(), product_code), + Err(error) => { + warn!( + error = format!("{error:#}"), + "Failed to read the product code of the installed Devolutions Agent" + ); + // The broker cannot verify that the request does not uninstall the Agent. + true + } + }; + if names_agent { + return error_response( + v2::ErrorCode::ProtectedPackage, + "the broker does not uninstall Devolutions Agent", + ); + } + } + + let package_request = match read(request) { + Reading::Readable(package_request) => package_request, + Reading::Unreadable => { + return error_response( + v2::ErrorCode::BypassRequestUnreadable, + "the bypass request is unreadable", + ); + } + // Nothing starts, so the token is not used up. + Reading::NotRead(reason) => return internal_error(&reason), + }; + + tokens.use_up(&token); + match registries + .bypasses + .start(&caller, &token_name, request.clone(), &package_request, ()) + { + Start::Started(started) | Start::Existing(Existing::Replayed(started)) => bypass_response(started), + // Not reached while every operation of this registry starts with the tokens locked, as above. + Start::Existing(Existing::Conflict) => token_rejected(), + } + } +} + +/// Returns the digest of the bypass token of a request, when the request has exactly one header that carries one +/// ([§bypass]). +/// +/// The token is the field value of the header, which has no space or tab at either end ([RFC 9110 §5.5]). +/// +/// [§bypass]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#bypass +/// [RFC 9110 §5.5]: https://www.rfc-editor.org/rfc/rfc9110#section-5.5 +fn token_of(headers: &HeaderMap) -> Option { + let mut values = headers.get_all(v2::BYPASS_TOKEN_HEADER).iter(); + let value = values.next()?; + if values.next().is_some() { + return None; + } + + let mut value = value.as_bytes(); + while let [b' ' | b'\t', rest @ ..] = value { + value = rest; + } + while let [rest @ .., b' ' | b'\t'] = value { + value = rest; + } + + Some(TokenDigest::of(value)) +} + +/// The response to a request the broker holds `started` for, with the status the operation has now. +fn bypass_response(started: StartedOperation<()>) -> Response { + let response = (|| { + Ok::<_, v2::ValueError>(v2::BypassResponse { + operation_id: v2::Identifier::parse(&started.operation_id)?, + status: operation_status(started.status), + event_pipe: started.event_pipe.as_deref().map(v2::EventPipe::parse).transpose()?, + }) + })(); + + match response { + Ok(response) => json(StatusCode::OK, &response), + Err(error) => internal_error(&error), + } +} + +/// The response to a request that no bypass token authorizes. +/// +/// It is the same whatever the reason, so it tells nothing about any token. +fn token_rejected() -> Response { + error_response( + v2::ErrorCode::BypassTokenRejected, + "no bypass token authorizes the request", + ) +} diff --git a/crates/now-package-broker/src/v2/routes/held.rs b/crates/now-package-broker/src/v2/routes/held.rs index f008cc8c4..db3188eed 100644 --- a/crates/now-package-broker/src/v2/routes/held.rs +++ b/crates/now-package-broker/src/v2/routes/held.rs @@ -1,5 +1,7 @@ -//! The operations the broker holds for the requests of the 2.0 encoding ([§operations]). +//! The operations the broker holds for the requests of the 2.0 encoding ([§operations]), and its bypass tokens +//! ([§bypass]). //! +//! [§bypass]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#bypass //! [§operations]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#operations use std::sync::{Arc, OnceLock}; @@ -8,6 +10,7 @@ use now_policy_api::v2; use tokio_util::sync::CancellationToken; use crate::server::BrokerState; +use crate::v2::bypass::BypassTokens; use crate::v2::execution::Operations; /// What the response to the execution request that started an operation says besides the operation ([§execute]). @@ -29,10 +32,22 @@ pub(super) struct Decided { /// [§equal-requests]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#equal-requests pub(super) type Executions = Operations; -/// The operations started by the requests of the 2.0 encoding, which a broker state creates empty. +/// The operations started by bypass requests ([§bypass]). +/// +/// The request id of an operation here is the digest of the token whose request started it, as text, because a token +/// starts one operation at most, while the Agent may bind two tokens of one user to one `RequestId`. +/// Two requests are equal when their bodies are, `RequestId` included. +/// Execution requests have a registry of their own, so the `RequestId` of a request of one kind neither conflicts +/// with nor replays a request of the other. +/// +/// [§bypass]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#bypass +pub(super) type Bypasses = Operations; + +/// The operations started by the requests of the 2.0 encoding and the bypass tokens the broker holds, which a broker +/// state creates empty. /// /// The operations of the 1.x routes are not held here, so no request of the 2.0 encoding names one. -/// A clone holds the same operations. +/// A clone holds the same operations and tokens. #[derive(Clone, Default)] pub struct HeldOperations { /// Made when first needed, because the operations run on the executor of the state that holds this value. @@ -41,6 +56,8 @@ pub struct HeldOperations { pub(super) struct Registries { pub(super) executions: Executions, + pub(super) bypasses: Bypasses, + pub(super) bypass_tokens: BypassTokens, } impl HeldOperations { @@ -49,6 +66,8 @@ impl HeldOperations { pub(super) fn of(&self, state: &BrokerState) -> &Registries { self.registries.get_or_init(|| Registries { executions: Operations::protecting_agent(Arc::clone(&state.executor), state.agent_product_code), + bypasses: Operations::protecting_agent(Arc::clone(&state.executor), state.agent_product_code), + bypass_tokens: BypassTokens::default(), }) } @@ -57,6 +76,8 @@ impl HeldOperations { /// `state` is the broker state that holds this value. /// Must be called from a Tokio runtime. pub fn spawn_eviction_task(&self, state: &BrokerState, shutdown: CancellationToken) { - self.of(state).executions.clone().spawn_eviction_task(shutdown); + let registries = self.of(state); + registries.executions.clone().spawn_eviction_task(shutdown.clone()); + registries.bypasses.clone().spawn_eviction_task(shutdown); } } diff --git a/crates/now-package-broker/src/v2/routes/mod.rs b/crates/now-package-broker/src/v2/routes/mod.rs index 637e37363..3481119a6 100644 --- a/crates/now-package-broker/src/v2/routes/mod.rs +++ b/crates/now-package-broker/src/v2/routes/mod.rs @@ -5,6 +5,7 @@ //! [§endpoints]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#endpoints //! [§transport]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#transport +mod bypass; mod capabilities; mod held; mod operations; @@ -135,7 +136,7 @@ impl Connection { } }; - self.serve(&route, &body).await + self.serve(&route, &parts.headers, &body).await } /// Returns the response to a client that `endpoint` does not answer ([§authentication]). @@ -278,7 +279,7 @@ impl Connection { } /// Answers a request that passed every check made before its body is read. - async fn serve(&self, route: &wire::Route, body: &[u8]) -> Response { + async fn serve(&self, route: &wire::Route, headers: &HeaderMap, body: &[u8]) -> Response { match route.endpoint { v2::Endpoint::Health => self.health(), v2::Endpoint::Capabilities => self.capabilities().await, @@ -294,7 +295,7 @@ impl Connection { Err(error) => bad_request(&error), }, v2::Endpoint::ExecuteBypass => match wire::read_bypass_request(body) { - Ok(_request) => not_served(), + Ok(request) => self.execute_bypass(headers, &request), Err(error) => bad_request(&error), }, v2::Endpoint::Validate => match wire::read_validation_request(body) { @@ -382,18 +383,6 @@ fn internal_error(error: &dyn std::fmt::Display) -> Response { error_response(v2::ErrorCode::InternalError, "the broker failed to answer the request") } -/// The response to a bypass request ([§bypass]), whose outcome `InternalError` replaces ([§errors]). -/// -/// The broker binds a bypass token to a 1.x request and uses the token up when it checks it. -/// It can therefore neither compare a 2.0 request with the bound one, nor refuse one without using up its token. -/// A client treats the outcome of such a request as unknown, and no command runs for it. -/// -/// [§bypass]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#bypass -/// [§errors]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#errors -fn not_served() -> Response { - error_response(v2::ErrorCode::InternalError, "the broker does not serve this endpoint") -} - /// Returns the error response for a code whose response has no member besides `Code` and `Message`. fn error_response(code: v2::ErrorCode, text: &str) -> Response { error_body(&wire::error_response(code, text)) diff --git a/crates/now-package-broker/src/v2/routes/operations.rs b/crates/now-package-broker/src/v2/routes/operations.rs index 34339f083..3d746bba0 100644 --- a/crates/now-package-broker/src/v2/routes/operations.rs +++ b/crates/now-package-broker/src/v2/routes/operations.rs @@ -67,12 +67,12 @@ impl Connection { /// /// [§status]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#status pub(super) fn status(&self, route: &wire::Route) -> Response { + let registries = self.state.operations.of(&self.state); let Some(state) = self.held_operation(route, |owner, operation_id| { - self.state - .operations - .of(&self.state) + registries .executions .status(owner, operation_id) + .or_else(|| registries.bypasses.status(owner, operation_id)) }) else { return operation_not_found(); }; @@ -87,12 +87,12 @@ impl Connection { /// /// [§cancel]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#cancel pub(super) fn cancel(&self, route: &wire::Route) -> Response { + let registries = self.state.operations.of(&self.state); let Some(status) = self.held_operation(route, |owner, operation_id| { - self.state - .operations - .of(&self.state) + registries .executions .cancel(owner, operation_id) + .or_else(|| registries.bypasses.cancel(owner, operation_id)) }) else { return operation_not_found(); }; @@ -107,6 +107,7 @@ impl Connection { /// Looks up the operation that the path of `route` names among those the broker holds for the client. /// + /// An operation is one that an execution request or a bypass request started, and no two of them share an id. /// A path whose operation id is not an identifier names no operation. fn held_operation(&self, route: &wire::Route, lookup: impl FnOnce(&Owner, &str) -> Option) -> Option { let operation_id = route.operation.as_ref()?.as_ref().ok()?; diff --git a/crates/now-package-broker/src/v2/routes/tests.rs b/crates/now-package-broker/src/v2/routes/tests.rs index fe7cfefe6..1502a1db4 100644 --- a/crates/now-package-broker/src/v2/routes/tests.rs +++ b/crates/now-package-broker/src/v2/routes/tests.rs @@ -1138,6 +1138,8 @@ enum Step { /// An executor that counts what it was asked to run and does what the test tells it. struct ScriptedExecutor { runs: std::sync::atomic::AtomicUsize, + /// What it was asked to run, in the order it was asked. + ran: std::sync::Mutex>, steps: tokio::sync::Mutex>, } @@ -1148,6 +1150,10 @@ impl CommandExecutor for ScriptedExecutor { context: &ExecutionContext, process_started: Option, ) -> anyhow::Result { + self.ran + .lock() + .expect("no test panics with the lock") + .push(context.clone()); self.runs.fetch_add(1, std::sync::atomic::Ordering::SeqCst); let mut steps = self.steps.lock().await; loop { @@ -1186,6 +1192,7 @@ impl Broker { let (steps, receiver) = tokio::sync::mpsc::unbounded_channel(); let executor = Arc::new(ScriptedExecutor { runs: std::sync::atomic::AtomicUsize::new(0), + ran: std::sync::Mutex::new(Vec::new()), steps: tokio::sync::Mutex::new(receiver), }); let state = Arc::new(BrokerState { @@ -2150,23 +2157,501 @@ async fn a_policy_replacement_leaves_its_attempt_and_its_result_under_its_own_re ); } -// oracle: mutant answering a bypass request the broker cannot serve with a body of the 1.x encoding, or running a -// command for it +const BYPASS_TOKEN_HEADER: &str = "x-devolutions-bypass-token"; + +/// A bypass token that has each kind of character a token may have. +const TOKEN: &str = "t0ken.A_b~c:d-e"; + +/// A bypass request for [`package_request`] with `members` added or replaced. +fn bypass_request(request_id: &str, members: serde_json::Value) -> serde_json::Value { + execution_request(request_id, members) +} + +fn without_source(mut request: serde_json::Value) -> serde_json::Value { + request + .as_object_mut() + .expect("the request is an object") + .remove("Source"); + request +} + +/// A bypass request to uninstall the package `id` through `manager`. +fn bypass_uninstall(manager: &str, id: &str) -> serde_json::Value { + without_source(bypass_request( + "request-1", + serde_json::json!({ "Operation": "Uninstall", "Manager": manager, "Package": { "Id": id } }), + )) +} + +/// A bypass request with the body `body` and one bypass token header for each of `tokens`. +fn post_bypass(tokens: &[&str], body: &serde_json::Value) -> Request { + let mut request = post_value(EXECUTE_BYPASS, body); + for token in tokens { + let token = axum::http::HeaderValue::from_str(token).expect("a field value"); + request.headers_mut().append(BYPASS_TOKEN_HEADER, token); + } + request +} + +/// Gives the broker `token` with the request it binds and the SID of the user it binds, as Devolutions Agent does. +fn hold_for(state: &BrokerState, token: &str, request: &serde_json::Value, user_sid: Sid) { + let request = crate::v2::wire::read_bypass_request(request.to_string().as_bytes()).expect("a bypass request"); + state + .operations + .of(state) + .bypass_tokens + .hold(token, request, user_sid) + .expect("the broker holds the token"); +} + +/// Gives the broker `token` bound to `request` and to the user of the test process. +fn hold(state: &BrokerState, token: &str, request: &serde_json::Value) { + hold_for(state, token, request, client().user_sid().clone()); +} + +/// Sends the bypass request `request`, which `token` authorizes and which must start an operation, and returns the +/// response. +async fn start_bypass(broker: &Broker, token: &str, request: &serde_json::Value) -> Reply { + hold(&broker.state, token, request); + let reply = send(&broker.state, &client(), post_bypass(&[token], request)).await; + assert_eq!(reply.status, 200, "{reply:?}"); + assert!(reply.body["OperationId"].is_string(), "{reply:?}"); + reply +} + +/// What the executor of `broker` was asked to run, in the order it was asked. +fn ran(broker: &Broker) -> Vec { + broker + .executor + .ran + .lock() + .expect("no test panics with the lock") + .clone() +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §bypass +#[tokio::test] +async fn a_bypass_request_its_token_authorizes_starts_an_operation_without_any_policy() { + // The broker holds no accepted policy. + let broker = Broker::from_state(state()); + let request = bypass_request("request-1", serde_json::json!({})); + hold(&broker.state, TOKEN, &request); + + let reply = send(&broker.state, &client(), post_bypass(&[TOKEN], &request)).await; + + assert_eq!(reply.status, 200, "{reply:?}"); + assert_eq!(reply.content_type.as_deref(), Some("application/json")); + assert_eq!( + members_without(&reply, "EventPipe"), + ["OperationId", "Status"], + "{reply:?}" + ); + assert_eq!(reply.body["Status"], "Starting"); + assert!(!reply.body.to_string().contains(TOKEN), "{reply:?}"); + assert_eq!(broker.runs().await, 1); +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §bypass +// The field value of a header has no space or tab at either end (RFC 9110 §5.5). +#[tokio::test] +async fn the_token_of_a_bypass_request_is_the_field_value_of_its_header() { + let broker = Broker::from_state(state()); + let request = bypass_request("request-1", serde_json::json!({})); + hold(&broker.state, TOKEN, &request); + + let padded = format!(" \t{TOKEN}\t "); + let reply = send(&broker.state, &client(), post_bypass(&[&padded], &request)).await; + + assert_eq!(reply.status, 200, "{reply:?}"); +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §operations +#[tokio::test] +async fn the_owner_of_a_bypass_operation_reads_its_status_and_cancels_it() { + let broker = Broker::from_state(state()); + let started = start_bypass(&broker, TOKEN, &bypass_request("request-1", serde_json::json!({}))).await; + let operation_id = operation_id(&started); + + broker.step(Step::Launch(at(5))); + let running = broker.wait_for(operation_id, "Running").await; + assert_eq!(timestamp(&running, "StartedAt"), at(5)); + + // The operation is not one of another owner. + let other = OtherExecutable::start(); + for request in [get(&status_path(operation_id)), post(&cancel_path(operation_id))] { + let reply = send(&broker.state, &other.client, request).await; + reply.assert_error(404, "OperationNotFound"); + } + + let canceling = send(&broker.state, &client(), post(&cancel_path(operation_id))).await; + assert_eq!(canceling.status, 200, "{canceling:?}"); + assert_eq!(canceling.body, serde_json::json!({ "Status": "Canceling" })); + broker.step(Step::RunUntilCanceled); + broker.wait_for(operation_id, "Canceled").await; +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §bypass +#[tokio::test] +async fn an_equal_bypass_request_with_the_token_of_a_held_operation_replays_the_response() { + let broker = Broker::from_state(state()); + let first = start_bypass(&broker, TOKEN, &bypass_request("request-1", serde_json::json!({}))).await; + broker.step(Step::Launch(at(0))); + broker.wait_for(operation_id(&first), "Running").await; + + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §equal-requests + // The same members with equal values in another key order are an equal request. + let reordered = serde_json::from_str( + r#"{ + "Elevation": "NonElevated", + "Package": { "Version": "2.45.1", "Id": "Git.Git" }, + "RequestId": "request-1", + "Source": { "Name": "winget" }, + "Manager": "Winget", + "Operation": "Install" + }"#, + ) + .expect("a JSON object"); + let replay = send(&broker.state, &client(), post_bypass(&[TOKEN], &reordered)).await; + + assert_eq!(replay.status, 200, "{replay:?}"); + assert_eq!(replay.members(), first.members(), "{replay:?}"); + assert_eq!(replay.body["OperationId"], first.body["OperationId"]); + assert_eq!(replay.body.get("EventPipe"), first.body.get("EventPipe")); + assert_eq!(replay.body["Status"], "Running"); + assert!(!replay.body.to_string().contains(TOKEN), "{replay:?}"); + + // The request gets its operation after the operation failed as well. + broker.step(Step::Exit(3)); + broker.wait_for(operation_id(&first), "Failed").await; + let replay = send(&broker.state, &client(), post_bypass(&[TOKEN], &reordered)).await; + assert_eq!(replay.status, 200, "{replay:?}"); + assert_eq!(replay.body["OperationId"], first.body["OperationId"]); + assert_eq!(replay.body["Status"], "Failed"); + + assert_eq!(broker.runs().await, 1); +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §bypass +#[tokio::test] +async fn a_bypass_request_no_held_token_authorizes_is_bypass_token_rejected_and_uses_up_no_token() { + let broker = Broker::from_state(state()); + let bound = bypass_request("request-1", serde_json::json!({})); + hold(&broker.state, TOKEN, &bound); + // The same request bound to a user that no client is. + let everyone = Sid::from_well_known(windows::Win32::Security::WinWorldSid, None).expect("a SID"); + hold_for(&broker.state, "token-of-another-user", &bound, everyone); + + let other_case = TOKEN.to_ascii_uppercase(); + let other_request_id = bypass_request("request-2", serde_json::json!({})); + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §equal-requests + // A request with `OptIns` does not have the same members as one without it. + let other_body = bypass_request("request-1", serde_json::json!({ "OptIns": {} })); + let cases = [ + ("no header", post_bypass(&[], &bound)), + ("two headers with the token", post_bypass(&[TOKEN, TOKEN], &bound)), + ( + "a header with the token and one with another", + post_bypass(&[TOKEN, "another"], &bound), + ), + ("a token the broker does not hold", post_bypass(&["unknown"], &bound)), + ("the token in another case", post_bypass(&[&other_case], &bound)), + ("another RequestId", post_bypass(&[TOKEN], &other_request_id)), + ("another body", post_bypass(&[TOKEN], &other_body)), + ( + "a token bound to another user", + post_bypass(&["token-of-another-user"], &bound), + ), + ]; + + for (case, request) in cases { + let reply = send(&broker.state, &client(), request).await; + + assert_eq!(reply.body["Code"], "BypassTokenRejected", "{case}: {reply:?}"); + reply.assert_error(403, "BypassTokenRejected"); + assert!(!reply.body.to_string().contains(TOKEN), "{case}: {reply:?}"); + } + assert_eq!(broker.runs().await, 0); + + // None of these requests used up the token. + let reply = send(&broker.state, &client(), post_bypass(&[TOKEN], &bound)).await; + assert_eq!(reply.status, 200, "{reply:?}"); +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §bypass #[tokio::test] -async fn a_bypass_request_is_internal_error_and_runs_nothing() { +async fn a_used_up_token_authorizes_no_other_request() { + let broker = Broker::from_state(state()); + let bound = bypass_request("request-1", serde_json::json!({})); + start_bypass(&broker, TOKEN, &bound).await; + // The same user, who is another owner from another executable. + let other = OtherExecutable::start(); + + let other_body = bypass_request("request-1", serde_json::json!({ "OptIns": {} })); + let unequal = send(&broker.state, &client(), post_bypass(&[TOKEN], &other_body)).await; + let from_another_owner = send(&broker.state, &other.client, post_bypass(&[TOKEN], &bound)).await; + + unequal.assert_error(403, "BypassTokenRejected"); + from_another_owner.assert_error(403, "BypassTokenRejected"); + assert_eq!(broker.runs().await, 1); +} + +/// How a broker of a test reads the product code of the installed Devolutions Agent. +type AgentProductCode = fn() -> anyhow::Result>; + +const AGENT_PRODUCT_CODE: AgentProductCode = || Ok(Some("0f2a6b3c-4d5e-4f60-8a9b-0c1d2e3f4a5b".parse()?)); + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §bypass +#[tokio::test] +async fn a_bypass_request_to_uninstall_devolutions_agent_is_protected_package() { + let cases: [(&str, AgentProductCode, &str, &str); 4] = [ + ("its WinGet id", || Ok(None), "Winget", "devolutions.AGENT"), + ("its Chocolatey id", || Ok(None), "Chocolatey", "Devo-Agent"), + ( + "its product code", + AGENT_PRODUCT_CODE, + "Winget", + "{0F2A6B3C-4D5E-4F60-8A9B-0C1D2E3F4A5B}", + ), + ( + "a product code the broker cannot read", + || anyhow::bail!("the registry cannot be read"), + "Npm", + "left-pad", + ), + ]; + + for (case, agent_product_code, manager, id) in cases { + let broker = Broker::from_state(BrokerState { + agent_product_code, + ..state() + }); + let request = bypass_uninstall(manager, id); + hold(&broker.state, TOKEN, &request); + + // The second request shows that the first one did not use up the token. + for _ in 0..2 { + let reply = send(&broker.state, &client(), post_bypass(&[TOKEN], &request)).await; + + assert_eq!(reply.body["Code"], "ProtectedPackage", "{case}: {reply:?}"); + reply.assert_error(422, "ProtectedPackage"); + } + assert_eq!(broker.runs().await, 0, "{case}"); + } +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §bypass +#[tokio::test] +async fn only_an_uninstall_that_may_be_of_devolutions_agent_is_protected_package() { + // An uninstall of another package, when the broker can tell that it is another one. + let broker = Broker::from_state(BrokerState { + agent_product_code: AGENT_PRODUCT_CODE, + ..state() + }); + start_bypass(&broker, TOKEN, &bypass_uninstall("Npm", "left-pad")).await; + + // An install and an update of Devolutions Agent, even when the broker cannot read its product code. + for operation in ["Install", "Update"] { + let broker = Broker::from_state(BrokerState { + agent_product_code: || anyhow::bail!("the registry cannot be read"), + ..state() + }); + let request = bypass_request( + "request-1", + serde_json::json!({ "Operation": operation, "Package": { "Id": "Devolutions.Agent" } }), + ); + start_bypass(&broker, TOKEN, &request).await; + } +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §bypass-reading +#[tokio::test] +async fn an_unreadable_bypass_request_is_bypass_request_unreadable() { + let cases = [ + ( + // CONTRACT.policy.md §manager-winget + "a WinGet source name that is not a plain source name", + bypass_request("request-1", serde_json::json!({ "Source": { "Name": "win/get" } })), + ), + ( + "an elevated install without Source through a manager other than WinGet and Chocolatey", + without_source(bypass_request( + "request-1", + serde_json::json!({ "Manager": "Npm", "Package": { "Id": "left-pad" }, "Elevation": "Elevated" }), + )), + ), + ( + // CONTRACT.policy.md §manager-npm: a case that tests no `Source.Name` applies without `Source` too. + "an Npm id that is neither a registry name nor an alias, without Source", + without_source(bypass_request( + "request-1", + serde_json::json!({ "Manager": "Npm", "Package": { "Id": "-left-pad" } }), + )), + ), + ]; + + for (case, request) in cases { + let broker = Broker::from_state(state()); + hold(&broker.state, TOKEN, &request); + + // The second request shows that the first one did not use up the token. + for _ in 0..2 { + let reply = send(&broker.state, &client(), post_bypass(&[TOKEN], &request)).await; + + assert_eq!(reply.body["Code"], "BypassRequestUnreadable", "{case}: {reply:?}"); + reply.assert_error(422, "BypassRequestUnreadable"); + } + assert_eq!(broker.runs().await, 0, "{case}"); + } +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §bypass +#[tokio::test] +async fn the_outcomes_of_a_bypass_request_come_in_their_order() { + let broker = Broker::from_state(state()); + // An uninstall of Devolutions Agent that is unreadable as well: the broker builds no Chocolatey command for the + // scope `User` (CONTRACT.policy.md §manager-chocolatey). + let mut request = bypass_uninstall("Chocolatey", "devo-agent"); + request["Scope"] = serde_json::json!("User"); + + let without_a_held_token = send(&broker.state, &client(), post_bypass(&[TOKEN], &request)).await; + hold(&broker.state, TOKEN, &request); + let with_its_token = send(&broker.state, &client(), post_bypass(&[TOKEN], &request)).await; + + without_a_held_token.assert_error(403, "BypassTokenRejected"); + with_its_token.assert_error(422, "ProtectedPackage"); +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §bypass-reading +#[tokio::test] +async fn a_bypass_request_without_source_runs_the_command_for_the_only_source_name_of_its_manager() { + let broker = Broker::from_state(state()); + // The only source name of Npm is `npm` (CONTRACT.policy.md §manager-npm). + let named = bypass_request( + "request-1", + serde_json::json!({ "Manager": "Npm", "Source": { "Name": "npm" }, "Package": { "Id": "left-pad" } }), + ); + let unnamed = without_source(named.clone()); + + for (token, request) in [("token-1", &named), ("token-2", &unnamed)] { + let started = start_bypass(&broker, token, request).await; + broker.step(Step::Launch(at(0))); + broker.step(Step::Exit(0)); + broker.wait_for(operation_id(&started), "Completed").await; + } + + let ran = ran(&broker); + let [named, unnamed] = ran.as_slice() else { + panic!("the broker ran {} operations", ran.len()); + }; + assert!( + named.command.iter().any(|argument| argument.contains("left-pad")), + "{:?}", + named.command + ); + assert_eq!(unnamed.command, named.command); +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §bypass +#[tokio::test] +async fn a_bypass_operation_runs_as_the_bound_user_with_the_elevation_of_the_request() { + for (elevation, expected) in [ + ("NonElevated", now_policy_api::Elevation::Standard), + ("Elevated", now_policy_api::Elevation::Elevated), + ] { + let broker = Broker::from_state(state()); + let request = bypass_request("request-1", serde_json::json!({ "Elevation": elevation })); + + let started = start_bypass(&broker, TOKEN, &request).await; + broker.step(Step::Launch(at(0))); + broker.step(Step::Exit(0)); + broker.wait_for(operation_id(&started), "Completed").await; + + let ran = ran(&broker); + let [run] = ran.as_slice() else { + panic!("the broker ran {} operations", ran.len()); + }; + assert_eq!(&run.user_sid, client().user_sid(), "{elevation}"); + assert_eq!(run.elevation, expected); + // The executor runs nothing with a token whose elevation is not the one the request names. + assert_eq!( + run.token_elevation_check, + crate::executor::TokenElevationCheck::Exact, + "{elevation}" + ); + } +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §bypass +#[tokio::test] +async fn the_request_id_of_a_bypass_request_and_that_of_an_execution_request_are_apart() { let broker = Broker::with_policy(ALLOW_ALL, ""); - let request = Request::builder() - .method(Method::POST) - .uri(EXECUTE_BYPASS) - .header("content-type", "application/json") - .header("x-devolutions-bypass-token", "0123456789abcdef") - .body(Body::from( - execution_request("request-1", serde_json::json!({})).to_string(), - )) - .expect("a valid test request"); - - let reply = send(&broker.state, &client(), request).await; + let same = serde_json::json!({}); + let other = serde_json::json!({ "Package": { "Id": "Git.Git", "Version": "2.46.0" } }); + let mut operation_ids = std::collections::HashSet::new(); + + // An execution request, then a bypass request with its `RequestId` and an equal or an unequal body. + for (request_id, token, members) in [("request-1", "token-1", &same), ("request-2", "token-2", &other)] { + let execution = broker + .start(&execution_request(request_id, serde_json::json!({}))) + .await; + let bypass = start_bypass(&broker, token, &bypass_request(request_id, members.clone())).await; - reply.assert_error(500, "InternalError"); + assert!(bypass.body.get("Decision").is_none(), "{bypass:?}"); + operation_ids.insert(operation_id(&execution).to_owned()); + operation_ids.insert(operation_id(&bypass).to_owned()); + } + + // A bypass request, then an execution request with its `RequestId` and an equal or an unequal body. + for (request_id, token, members) in [("request-3", "token-3", &same), ("request-4", "token-4", &other)] { + let bypass = start_bypass(&broker, token, &bypass_request(request_id, serde_json::json!({}))).await; + let execution = broker.start(&execution_request(request_id, members.clone())).await; + + assert!(execution.body.get("Decision").is_some(), "{execution:?}"); + operation_ids.insert(operation_id(&bypass).to_owned()); + operation_ids.insert(operation_id(&execution).to_owned()); + } + + // Each request started an operation of its own. + assert_eq!(operation_ids.len(), 8, "{operation_ids:?}"); +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §bypass +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn bypass_requests_with_one_token_that_arrive_together_start_one_operation() { + let broker = Broker::from_state(state()); + let request = bypass_request("request-1", serde_json::json!({})); + hold(&broker.state, TOKEN, &request); + + let mut requests = tokio::task::JoinSet::new(); + for _ in 0..16 { + let state = Arc::clone(&broker.state); + let request = post_bypass(&[TOKEN], &request); + requests.spawn(async move { send(&state, &client(), request).await }); + } + let replies = requests.join_all().await; + + let started = operation_id(&replies[0]).to_owned(); + for reply in &replies { + assert_eq!(reply.status, 200, "{reply:?}"); + assert_eq!(operation_id(reply), started); + } + broker.step(Step::Launch(at(0))); + broker.wait_for(&started, "Running").await; + assert_eq!(broker.runs().await, 1); +} + +// oracle: mutant using up the token of a request without a source name that the broker does not read, or running a +// command for it +#[tokio::test] +async fn a_bypass_request_the_broker_does_not_read_is_internal_error_and_keeps_its_token() { + let broker = Broker::from_state(state()); + let request = without_source(bypass_request("request-1", serde_json::json!({}))); + hold(&broker.state, TOKEN, &request); + + // The second request is answered as the first one, so the first one did not use up the token. + for _ in 0..2 { + let reply = send(&broker.state, &client(), post_bypass(&[TOKEN], &request)).await; + reply.assert_error(500, "InternalError"); + } assert_eq!(broker.runs().await, 0); } From 4e803a9dee03935bbd343fbcad90377a27290d8d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Tue, 1 Dec 2026 06:37:03 +0900 Subject: [PATCH 08/38] fix(agent): record a 2.0 policy replacement the broker refuses for its body A client that may replace the policy and whose request is refused as too large, as not well-formed, or because its body could not be read left no trace, while the same request on the 1.x route leaves its attempt and a rejection. An administrator who looks for who tried to change the policy has to find these requests as well, so they now leave the attempt and a request_rejected denial under the request of the 2.0 encoding. A replacement the policy store fails to decide is answered before any attempt is recorded, so its log line now names the client. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- .../now-package-broker/src/v2/routes/mod.rs | 48 +++++++++--- .../src/v2/routes/policy.rs | 26 ++++--- .../now-package-broker/src/v2/routes/tests.rs | 77 ++++++++++++++++++- 3 files changed, 129 insertions(+), 22 deletions(-) diff --git a/crates/now-package-broker/src/v2/routes/mod.rs b/crates/now-package-broker/src/v2/routes/mod.rs index 3481119a6..ee8ad3d4d 100644 --- a/crates/now-package-broker/src/v2/routes/mod.rs +++ b/crates/now-package-broker/src/v2/routes/mod.rs @@ -30,7 +30,7 @@ use tracing::{error, warn}; pub use self::held::HeldOperations; use super::policy::{EvaluationError, is_not_runnable}; use super::wire; -use crate::audit::DenialReason; +use crate::audit::{DenialReason, WriteAudit}; use crate::auth::PipeClient; use crate::server::BrokerState; @@ -125,14 +125,19 @@ impl Connection { let body = match read_body(body, body_limit).await { Ok(body) => body, - Err(BodyError::TooLarge) => { - return error_response( - v2::ErrorCode::RequestTooLarge, - "the request body is larger than the limit of its endpoint", - ); - } - Err(BodyError::Unreadable) => { - return error_response(v2::ErrorCode::BadRequest, "the request body could not be read"); + Err(error) => { + if endpoint == v2::Endpoint::Replace { + self.record_rejected_replacement(); + } + return match error { + BodyError::TooLarge => error_response( + v2::ErrorCode::RequestTooLarge, + "the request body is larger than the limit of its endpoint", + ), + BodyError::Unreadable => { + error_response(v2::ErrorCode::BadRequest, "the request body could not be read") + } + }; } }; @@ -182,6 +187,26 @@ impl Connection { ); } + /// Records the attempt of a client that may replace the policy. + /// + /// The returned audit records the rejection of the request when it is dropped before the policy store records a + /// result in it. + fn begin_replacement_audit(&self) -> WriteAudit { + WriteAudit::begin_document( + self.client.user_sid(), + self.client.executable_path(), + &self.configured_policy_path(), + ) + } + + /// Records the attempt and the rejection of a policy replacement refused for its body. + /// + /// The request is one of a client that may replace the policy, so it leaves the records a replacement the policy + /// store refuses does. + fn record_rejected_replacement(&self) { + drop(self.begin_replacement_audit()); + } + fn configured_policy_path(&self) -> PathBuf { PathBuf::from(self.state.policy_store.management_snapshot().configured_path) } @@ -304,7 +329,10 @@ impl Connection { }, v2::Endpoint::Replace => match wire::read_replacement_request(body) { Ok(request) => self.replace(&request).await, - Err(error) => bad_request(&error), + Err(error) => { + self.record_rejected_replacement(); + bad_request(&error) + } }, } } diff --git a/crates/now-package-broker/src/v2/routes/policy.rs b/crates/now-package-broker/src/v2/routes/policy.rs index b70fffe37..c4a2b37a5 100644 --- a/crates/now-package-broker/src/v2/routes/policy.rs +++ b/crates/now-package-broker/src/v2/routes/policy.rs @@ -7,9 +7,9 @@ use axum::http::StatusCode; use axum::response::Response; use now_policy_api::v2; +use tracing::error; use super::{Connection, error_body, error_response, internal_error, json}; -use crate::audit::WriteAudit; use crate::policy_store::DocumentReplacement; use crate::v2::wire; @@ -30,17 +30,12 @@ impl Connection { /// /// The attempt is recorded once the store can decide the request, and the store records its result. pub(super) async fn replace(&self, request: &v2::ReplacementRequest) -> Response { - let begin_audit = || { - WriteAudit::begin_document( - self.client.user_sid(), - self.client.executable_path(), - &self.configured_policy_path(), - ) - }; let replacement = self .state .policy_store - .replace_document(&request.expected_store_token, &request.document, begin_audit) + .replace_document(&request.expected_store_token, &request.document, || { + self.begin_replacement_audit() + }) .await; match replacement { @@ -74,7 +69,18 @@ impl Connection { Ok(DocumentReplacement::Replaced(management)) => { json(StatusCode::OK, &v2::ReplacementResponse { management }) } - Err(error) => internal_error(&error), + Err(error) => { + // UNTESTED: A replacement the policy store fails to decide names its client in the log. + // The store fails before the attempt is recorded, so this line is the only trace of who asked. + // When this changes, check that every failure of `replace_document` still comes before its attempt is + // recorded, and that the line keeps the SID and the executable of the client. + error!( + user_sid = %self.client.user_sid(), + executable = %self.client.executable_path().display(), + "Failed to decide a policy replacement" + ); + internal_error(&error) + } } } } diff --git a/crates/now-package-broker/src/v2/routes/tests.rs b/crates/now-package-broker/src/v2/routes/tests.rs index 1502a1db4..b2720b31a 100644 --- a/crates/now-package-broker/src/v2/routes/tests.rs +++ b/crates/now-package-broker/src/v2/routes/tests.rs @@ -2119,7 +2119,7 @@ async fn a_replacement_whose_written_file_does_not_hold_the_document_is_activati } // oracle: mutant recording the attempt or the result of a 2.0 policy replacement as the 1.x request, or recording an -// attempt without its result, or one for a request whose body the broker refused +// attempt without its result, or nothing for a request whose body the broker refused #[tokio::test] async fn a_policy_replacement_leaves_its_attempt_and_its_result_under_its_own_request() { let file = TestPolicyFile::holding(Some(&document("corp-baseline", 3))); @@ -2152,11 +2152,84 @@ async fn a_policy_replacement_leaves_its_attempt_and_its_result_under_its_own_re (Some(agent_sysevent_codes::POLICY_WRITE_ATTEMPTED), intent.clone()), (Some(agent_sysevent_codes::POLICY_CHANGE_SUCCEEDED), intent.clone()), (Some(agent_sysevent_codes::POLICY_WRITE_ATTEMPTED), intent.clone()), - (Some(agent_sysevent_codes::POLICY_CHANGE_FAILED), intent), + (Some(agent_sysevent_codes::POLICY_CHANGE_FAILED), intent.clone()), + (Some(agent_sysevent_codes::POLICY_WRITE_ATTEMPTED), intent.clone()), + (Some(agent_sysevent_codes::POLICY_WRITE_DENIED), intent), ] ); } +/// A request body the broker fails to read, as that of a client that stops sending it. +struct BrokenBody; + +impl hyper::body::Body for BrokenBody { + type Data = axum::body::Bytes; + type Error = std::io::Error; + + fn poll_frame( + self: std::pin::Pin<&mut Self>, + _context: &mut std::task::Context<'_>, + ) -> std::task::Poll, Self::Error>>> { + std::task::Poll::Ready(Some(Err(std::io::ErrorKind::UnexpectedEof.into()))) + } +} + +// oracle: mutant leaving no record of a 2.0 policy replacement refused for its body, or recording it as the 1.x +// request, without its attempt or under another reason, or recording a request to another endpoint +#[tokio::test] +async fn a_policy_replacement_refused_for_its_body_leaves_its_attempt_and_its_rejection() { + let state = Arc::new(state()); + let records = || -> Vec<_> { + crate::audit::tests::take_events() + .into_iter() + .map(|entry| { + let field = |name: &str| { + entry + .fields + .iter() + .find_map(|(field, value)| (field == name).then(|| value.clone())) + }; + (entry.event_code, field("intent"), field("reason")) + }) + .collect() + }; + let intent = Some("POST /v2/policy".to_owned()); + + for (case, body, status, code) in [ + ( + "too large", + Body::from(vec![b'x'; DOCUMENT_LIMIT + 1]), + 413, + "RequestTooLarge", + ), + ("not read", Body::new(BrokenBody), 400, "BadRequest"), + ("malformed", Body::from("{"), 400, "BadRequest"), + ] { + records(); + + let reply = send(&state, &administrator(), post_json(REPLACE, body)).await; + + reply.assert_error(status, code); + assert_eq!( + records(), + [ + (Some(agent_sysevent_codes::POLICY_WRITE_ATTEMPTED), intent.clone(), None), + ( + Some(agent_sysevent_codes::POLICY_WRITE_DENIED), + intent.clone(), + Some("request_rejected".to_owned()) + ), + ], + "{case}" + ); + } + + let validation = send(&state, &administrator(), post_json(VALIDATE, "{")).await; + + validation.assert_error(400, "BadRequest"); + assert_eq!(records(), []); +} + const BYPASS_TOKEN_HEADER: &str = "x-devolutions-bypass-token"; /// A bypass token that has each kind of character a token may have. From 61a32633f9caec36ad73ca4160643ead84f477d2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Tue, 1 Dec 2026 06:39:23 +0900 Subject: [PATCH 09/38] fix(agent): answer InternalError when the evaluator refuses a request the broker read The broker reads a package request as the wire contract defines it before it asks the evaluator for a decision, so a refusal by the evaluator means the two read the contract differently. BadRequest was the answer, yet that code wins over PolicyUnavailable and over a replayed response, which the broker has decided by then, so a client could be told its request is malformed when the contract gives it another outcome. The failure is the broker's and no other code names it: it is now logged and answered as InternalError. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- .../now-package-broker/src/v2/routes/mod.rs | 20 +++++++++-------- .../now-package-broker/src/v2/routes/tests.rs | 22 +++++++++++++++++++ 2 files changed, 33 insertions(+), 9 deletions(-) diff --git a/crates/now-package-broker/src/v2/routes/mod.rs b/crates/now-package-broker/src/v2/routes/mod.rs index ee8ad3d4d..05c3c3685 100644 --- a/crates/now-package-broker/src/v2/routes/mod.rs +++ b/crates/now-package-broker/src/v2/routes/mod.rs @@ -261,6 +261,11 @@ impl Connection { /// [§evaluate]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#evaluate /// [§execute]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#execute fn decide(&self, request: &v2::PackageRequest) -> Result> { + self.decide_read(wire::evaluator_request(request)) + } + + /// Evaluates a package request the broker read, given as the evaluator's input for it. + fn decide_read(&self, request: now_policy_eval::Request) -> Result> { let Some(policy) = self.state.policy_store.accepted_policy() else { return Err(Box::new(error_response( v2::ErrorCode::PolicyUnavailable, @@ -269,18 +274,15 @@ impl Connection { }; let evaluated_at = Utc::now(); - let request = wire::evaluator_request(request); let decision = match policy.evaluate(&request, evaluated_at) { Ok(decision) => decision, - // The evaluator reads a package request as the wire contract defines it, so it refuses only a request - // the contract does not allow. - Err(EvaluationError::BadRequest) => { - return Err(Box::new(error_response( - v2::ErrorCode::BadRequest, - "the package request is not well-formed", - ))); + // The broker read the request as well-formed, so the evaluator that refuses it reads the contract another + // way than the broker does. + // `BadRequest` wins over `PolicyUnavailable` and over a replayed response, both decided already, so it + // is no answer here. + Err(error @ (EvaluationError::BadRequest | EvaluationError::TimeOutOfRange)) => { + return Err(Box::new(internal_error(&error))); } - Err(error @ EvaluationError::TimeOutOfRange) => return Err(Box::new(internal_error(&error))), }; let not_runnable = is_not_runnable(&request, &decision); let allowed = decision.outcome == now_policy_eval::Outcome::Allow; diff --git a/crates/now-package-broker/src/v2/routes/tests.rs b/crates/now-package-broker/src/v2/routes/tests.rs index b2720b31a..f07521d79 100644 --- a/crates/now-package-broker/src/v2/routes/tests.rs +++ b/crates/now-package-broker/src/v2/routes/tests.rs @@ -1125,6 +1125,28 @@ async fn a_request_the_contract_refuses_whatever_the_policy_is_refused_in_audit_ wildcard_image_name.assert_error(400, "BadRequest"); } +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §errors +// `BadRequest` wins over every outcome of the section of an endpoint, so a request the broker read as well-formed and +// the evaluator refuses all the same met a broker failure that no other code names. +#[tokio::test] +async fn a_request_the_evaluator_refuses_once_the_broker_read_it_is_internal_error() { + let connection = super::Connection { + state: Arc::new(state_with_policy(ALLOW_ALL, "")), + client: client(), + }; + let body = serde_json::to_vec(&package_request(serde_json::json!({}))).expect("the request serializes"); + let read = crate::v2::wire::read_evaluation_request(&body).expect("a well-formed package request"); + let mut request = crate::v2::wire::evaluator_request(&read); + // No package request the broker reads has an empty package id. + request.package.id = String::new(); + + let Err(refused) = connection.decide_read(request) else { + panic!("the evaluator decides no request with an empty package id"); + }; + + reply(*refused).await.assert_error(500, "InternalError"); +} + /// What the executor of a test does next for the operation it runs. enum Step { /// Reports that the manager process was launched at the given time. From dde046ebcabc84dcb859e0ef2b441a105db6e981 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Tue, 1 Dec 2026 06:43:41 +0900 Subject: [PATCH 10/38] fix(agent): name in the 2.0 capabilities every opt-in the broker acts on for a manager The capability of a manager named the commands and the processes the broker runs itself, custom parameters and a custom install location, and nothing else. A client that offers what the capabilities name never offered Interactive, SkipHashCheck, InstallerArguments, UninstallPrevious or NoUpgrade, which the WinGet, Chocolatey and Scoop commands carry, and offered Cargo pre and post commands and processes to stop, which make a Cargo request unreadable. Each manager now gets the opt-ins that change what the broker runs for it: the keys its reading accepts, less those its command carries nothing for, as the PowerShell commands do for every key of the manager itself. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- .../src/v2/routes/capabilities.rs | 80 ++++++++++-- .../now-package-broker/src/v2/routes/tests.rs | 116 ++++++++++++++++++ 2 files changed, 186 insertions(+), 10 deletions(-) diff --git a/crates/now-package-broker/src/v2/routes/capabilities.rs b/crates/now-package-broker/src/v2/routes/capabilities.rs index 9380ca133..f84e77cfd 100644 --- a/crates/now-package-broker/src/v2/routes/capabilities.rs +++ b/crates/now-package-broker/src/v2/routes/capabilities.rs @@ -26,21 +26,81 @@ pub(super) fn response(managers: Vec) -> Result v2::ManagerCapability { - // The broker runs the commands and stops the processes itself, whatever the manager. - let mut opt_ins = vec![v2::OptInName::PrePostCommands, v2::OptInName::KillBeforeOperation]; - if capability.supports_custom_parameters { - opt_ins.push(v2::OptInName::CustomParameters); - } - if capability.supports_custom_install_location { - opt_ins.push(v2::OptInName::CustomInstallLocation); - } + let manager = manager(capability.manager); v2::ManagerCapability { - manager: manager(capability.manager), + manager, operations: capability.operations.into_iter().map(operation).collect(), scopes: capability.scopes.into_iter().map(scope).collect(), architectures: capability.architectures.into_iter().map(architecture).collect(), - opt_ins, + opt_ins: opt_ins(manager).to_vec(), + } +} + +/// Returns the opt-ins that change what the broker runs for a request through `manager`, in the order of [§opt-ins]. +/// +/// An opt-in is left out where the reading of the manager makes a request that has its key unreadable ([§managers]). +/// It is left out as well where the reading accepts the key and the command carries nothing for it, as the commands +/// of `PowerShell` and `PowerShell7` do for `Interactive`, so that a client offers nothing that has no effect. +/// A manager is listed with an opt-in that only some of its operations carry, as `Winget` is with `NoUpgrade`. +/// +/// [§opt-ins]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.policy.md#opt-ins +/// [§managers]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.policy.md#managers +// +// UNTESTED: An opt-in listed for a manager is one the command builder of that manager acts on, or one the broker runs +// itself for it, and no other opt-in is. +// The tests compare the list with the keys the reading of each manager accepts, not with what the builders do, so a +// builder that starts or stops carrying an opt-in leaves them passing while a client is told the wrong thing. +// When a command builder or the plan of an operation changes what it does with an opt-in, change this list with it. +fn opt_ins(manager: v2::Manager) -> &'static [v2::OptInName] { + use v2::OptInName as OptIn; + + // The broker runs the commands and stops the processes itself, for every manager whose builder lets it. + const BROKER_RUN: &[OptIn] = &[OptIn::PrePostCommands, OptIn::KillBeforeOperation]; + + match manager { + v2::Manager::Winget => &[ + OptIn::Interactive, + OptIn::SkipHashCheck, + OptIn::CustomInstallLocation, + OptIn::CustomParameters, + OptIn::InstallerArguments, + OptIn::PrePostCommands, + OptIn::KillBeforeOperation, + OptIn::UninstallPrevious, + OptIn::NoUpgrade, + ], + v2::Manager::Chocolatey => &[ + OptIn::Interactive, + OptIn::SkipHashCheck, + OptIn::PrePostCommands, + OptIn::KillBeforeOperation, + ], + v2::Manager::Scoop => &[ + OptIn::SkipHashCheck, + OptIn::CustomParameters, + OptIn::PrePostCommands, + OptIn::KillBeforeOperation, + ], + v2::Manager::Cargo => &[OptIn::CustomInstallLocation], + v2::Manager::Dotnet => &[ + OptIn::CustomInstallLocation, + OptIn::PrePostCommands, + OptIn::KillBeforeOperation, + ], + v2::Manager::PowerShell + | v2::Manager::PowerShell7 + | v2::Manager::Bun + | v2::Manager::Npm + | v2::Manager::Pip + | v2::Manager::Vcpkg => BROKER_RUN, + // The broker builds no command for these managers. + v2::Manager::Apt + | v2::Manager::Dnf + | v2::Manager::Flatpak + | v2::Manager::Homebrew + | v2::Manager::Pacman + | v2::Manager::Snap => &[], } } diff --git a/crates/now-package-broker/src/v2/routes/tests.rs b/crates/now-package-broker/src/v2/routes/tests.rs index f07521d79..8c69d6b09 100644 --- a/crates/now-package-broker/src/v2/routes/tests.rs +++ b/crates/now-package-broker/src/v2/routes/tests.rs @@ -811,6 +811,122 @@ async fn capabilities_name_the_version_the_timeout_and_each_manager_once() { assert_eq!(names, ["Npm", "Winget"], "{reply:?}"); } +/// The opt-ins the capabilities name for each of `managers`, sorted, by the name of the manager. +async fn capability_opt_ins( + managers: Vec, +) -> std::collections::BTreeMap> { + let state = Arc::new(BrokerState { + executor: Arc::new(ProbingExecutor(managers)), + ..state() + }); + + let reply = send(&state, &client(), get("/v2/capabilities")).await; + + assert_eq!(reply.status, 200, "{reply:?}"); + reply.body["Managers"] + .as_array() + .expect("Managers is a list") + .iter() + .map(|manager| { + let mut opt_ins: Vec = strings(manager, "OptIns").into_iter().map(str::to_owned).collect(); + opt_ins.sort_unstable(); + let name = manager["Manager"].as_str().expect("Manager is a string"); + (name.to_owned(), opt_ins) + }) + .collect() +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.policy.md §managers +// The opt-ins of a manager are the keys that do not make every request through it unreadable: the reading of the +// manager names the keys the broker builds no command with, and accepts custom parameters and installer arguments +// only where it says so. +#[tokio::test] +async fn the_capability_of_a_manager_names_the_opt_ins_its_reading_accepts() { + use now_policy_api::ManagerName; + + const BROKER_RUN: [&str; 2] = ["KillBeforeOperation", "PrePostCommands"]; + + let opt_ins = capability_opt_ins(vec![ + ManagerName::Winget, + ManagerName::Scoop, + ManagerName::Vcpkg, + ManagerName::Npm, + ManagerName::Bun, + ManagerName::Cargo, + ManagerName::Pip, + ManagerName::Dotnet, + ManagerName::Chocolatey, + ]) + .await; + + let expected: [(&str, &[&str]); 9] = [ + ( + "Winget", + &[ + "CustomInstallLocation", + "CustomParameters", + "InstallerArguments", + "Interactive", + "KillBeforeOperation", + "NoUpgrade", + "PrePostCommands", + "SkipHashCheck", + "UninstallPrevious", + ], + ), + ( + "Scoop", + &[ + "CustomParameters", + "KillBeforeOperation", + "PrePostCommands", + "SkipHashCheck", + ], + ), + ("Vcpkg", &BROKER_RUN), + ("Npm", &BROKER_RUN), + ("Bun", &BROKER_RUN), + ("Cargo", &["CustomInstallLocation"]), + ("Pip", &BROKER_RUN), + ( + "Dotnet", + &["CustomInstallLocation", "KillBeforeOperation", "PrePostCommands"], + ), + ( + "Chocolatey", + &["Interactive", "KillBeforeOperation", "PrePostCommands", "SkipHashCheck"], + ), + ]; + let expected: std::collections::BTreeMap> = expected + .into_iter() + .map(|(manager, opt_ins)| { + ( + manager.to_owned(), + opt_ins.iter().map(|&opt_in| opt_in.to_owned()).collect(), + ) + }) + .collect(); + assert_eq!(opt_ins, expected); +} + +// oracle: mutant naming for PowerShell or PowerShell7 an opt-in its reading accepts although its command carries +// nothing for it, or leaving out one the broker runs itself +#[tokio::test] +async fn the_capability_of_a_powershell_manager_names_only_the_opt_ins_the_broker_runs_itself() { + use now_policy_api::ManagerName; + + let opt_ins = capability_opt_ins(vec![ManagerName::PowerShell, ManagerName::PowerShell7]).await; + + let broker_run = vec!["KillBeforeOperation".to_owned(), "PrePostCommands".to_owned()]; + assert_eq!( + opt_ins, + std::collections::BTreeMap::from([ + ("PowerShell".to_owned(), broker_run.clone()), + ("PowerShell7".to_owned(), broker_run), + ]) + ); +} + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §authentication #[tokio::test] async fn capabilities_refuse_a_client_the_broker_does_not_authenticate() { From c2003884ac68e8a504f6fb7e1b9649a1a4d4b72b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Tue, 1 Dec 2026 06:59:30 +0900 Subject: [PATCH 11/38] fix(agent): answer the 2.0 requests of a client whose process the broker cannot identify The pipe server closed the connection of a client whose process it failed to identify, for example one whose executable is on a network share, before reading any request. The 2.0 encoding answers every request of a connected client: the health endpoint answers any client, a request to any other endpoint is `Unauthenticated` when the broker does not authenticate the client process, and a connection closes without a response only on a timeout. Such a client now stays connected as an unidentified one. Its 2.0 requests get `UnknownEndpoint` and `UnsupportedMediaType` first, then the health response or `Unauthenticated`, without the broker reading a body it does not need, and a refused policy replacement leaves a denial record that names the user the process seemed to run as. That user reaches nothing else: the client owns nothing, starts nothing, and is never named to the policy store. The 1.x routes still serve no such client. The connection closes without a response once the header of a request outside the 2.0 encoding is read. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- crates/now-package-broker/src/pipe.rs | 210 +++++++++++++++++- .../src/server/connection.rs | 36 +++ crates/now-package-broker/src/server/mod.rs | 1 + .../now-package-broker/src/v2/routes/mod.rs | 195 ++++++++++++---- .../now-package-broker/src/v2/routes/tests.rs | 173 ++++++++++++++- 5 files changed, 560 insertions(+), 55 deletions(-) diff --git a/crates/now-package-broker/src/pipe.rs b/crates/now-package-broker/src/pipe.rs index 6f04c86a8..db55011b9 100644 --- a/crates/now-package-broker/src/pipe.rs +++ b/crates/now-package-broker/src/pipe.rs @@ -20,7 +20,10 @@ use windows::Win32::Security::Authorization::SET_ACCESS; use windows::Win32::Storage::FileSystem::{FILE_GENERIC_READ, FILE_WRITE_ATTRIBUTES, FILE_WRITE_DATA}; use crate::auth::{PipeClient, connected_pipe_client_user_sid}; -use crate::server::{BrokerState, PipeIdentity, build_busy_router, build_router_for_pipe, serve_connection}; +use crate::server::{ + BrokerState, PipeIdentity, build_busy_router, build_router_for_pipe, serve_connection, + serve_unidentified_connection, +}; /// Default pipe name for the package broker. pub const DEFAULT_PIPE_NAME: &str = r"\\.\pipe\Devolutions.Now.PackageBroker.v1"; @@ -147,14 +150,9 @@ async fn accept_connections( let serve = admission.serve( server, permit, - PipeClient::from_connected_pipe, - PipeClient::user_sid, - |server, client| async move { - info!("Client connected to named pipe"); - let router = build_router_for_pipe(state, client, PipeIdentity::of(&server)); - serve_connection(server, router).await; - info!("Client disconnected from named pipe"); - }, + capture_connected_client, + ConnectedClient::user_sid, + |server, client| serve_client(state, server, client), ); // Enforce a deadline so idle or slow clients cannot pin @@ -172,6 +170,76 @@ async fn accept_connections( Ok(()) } +/// A connected client, as far as the broker identified its process. +enum ConnectedClient { + Identified(Box), + /// A client whose process the broker failed to identify, and which it therefore never authenticates. + Unidentified { + /// The user the client process seemed to run as when it connected. + user_sid: Sid, + }, +} + +impl ConnectedClient { + /// Identifies the process on the other end of `server` with `identify`. + /// + /// A client whose process is not identified stays connected, because the broker answers some requests whoever + /// sends them. + /// It is refused when its user cannot be looked up either, since the limit of connections per user needs one. + fn capture( + server: &NamedPipeServer, + identify: fn(&NamedPipeServer) -> anyhow::Result, + ) -> anyhow::Result { + let error = match identify(server) { + Ok(client) => return Ok(Self::Identified(Box::new(client))), + Err(error) => error, + }; + + match connected_pipe_client_user_sid(server) { + Ok(user_sid) => { + warn!( + error = format!("{error:#}"), + %user_sid, + "Failed to identify named pipe client; none of its requests is authenticated" + ); + Ok(Self::Unidentified { user_sid }) + } + Err(_) => Err(error), + } + } + + fn user_sid(&self) -> &Sid { + match self { + Self::Identified(client) => client.user_sid(), + Self::Unidentified { user_sid } => user_sid, + } + } +} + +// UNTESTED: The pipe server identifies a client process with `PipeClient::from_connected_pipe`, and a process that +// capture refuses, such as one whose executable is on a network share, is served as an unidentified client. +// A weaker capture here would let the routes trust a process the broker did not verify. +// The tests pass their own capture to `ConnectedClient::capture`, so none runs this function or a capture that fails +// on a real process. +// When changing this, check that the accept loop still captures with this function, and that it passes the full +// identity capture. +fn capture_connected_client(server: &NamedPipeServer) -> anyhow::Result { + ConnectedClient::capture(server, PipeClient::from_connected_pipe) +} + +/// Serve the requests of an admitted client until its connection ends. +async fn serve_client(state: Arc, server: NamedPipeServer, client: ConnectedClient) { + info!("Client connected to named pipe"); + match client { + ConnectedClient::Identified(client) => { + let router = build_router_for_pipe(state, *client, PipeIdentity::of(&server)); + serve_connection(server, router).await; + } + ConnectedClient::Unidentified { user_sid } => serve_unidentified_connection(server, state, user_sid).await, + } + info!("Client disconnected from named pipe"); +} + /// Concurrency limits applied by [`accept_loop`]. struct AcceptLimits { /// Connections served concurrently. @@ -1628,6 +1696,130 @@ mod tests { assert!(user_sid == current_user_sid()); } + /// A broker without a policy that authenticates the test process. + fn broker_state() -> Arc { + Arc::new(BrokerState { + policy_store: crate::policy_store::PolicyStore::for_tests(None), + executor: Arc::new(crate::executor::DryRunExecutor), + pipe_name: "test-pipe".to_owned(), + tracker: crate::operation_tracker::OperationTracker::new(), + skip_signature_validation: true, + manager_probe_cache: Default::default(), + remote_grants: crate::remote_grant::RemoteGrantStore::new(), + agent_product_code: || Ok(None), + operations: Default::default(), + }) + } + + fn capture_the_test_process(server: &NamedPipeServer) -> anyhow::Result { + ConnectedClient::capture(server, |_server| PipeClient::from_current_process()) + } + + fn capture_no_process(server: &NamedPipeServer) -> anyhow::Result { + ConnectedClient::capture(server, |_server| anyhow::bail!("the test identifies no client process")) + } + + /// Connects a client, admits and serves it like the pipe server does with `capture` as the identity capture, + /// and returns what the client reads once it wrote `request`, up to the end of the connection. + async fn exchange_captured( + tag: &str, + capture: fn(&NamedPipeServer) -> anyhow::Result, + request: &str, + ) -> String { + use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _}; + + let pipe_name = unique_pipe_name(tag); + let connection_permits = Arc::new(Semaphore::new(1)); + let admission = UserAdmission::new(1, Arc::new(Semaphore::new(1))); + let server = create_owned_test_instance(&pipe_name, true).expect("create pipe instance"); + let mut client = open_client(&pipe_name).expect("open client"); + server.connect().await.expect("accept client"); + let permit = Arc::clone(&connection_permits) + .try_acquire_owned() + .expect("connection slot"); + let state = broker_state(); + let serving = tokio::spawn(async move { + admission + .serve(server, permit, capture, ConnectedClient::user_sid, |server, client| { + serve_client(state, server, client) + }) + .await; + }); + + client.write_all(request.as_bytes()).await.expect("write request"); + let mut response = Vec::new(); + // The end of a pipe whose server closed reads as an error or as the end of the stream. + let _ = tokio::time::timeout(Duration::from_secs(10), client.read_to_end(&mut response)) + .await + .expect("the connection is closed promptly"); + tokio::time::timeout(Duration::from_secs(10), serving) + .await + .expect("the serving task ends") + .expect("the serving task does not panic"); + + String::from_utf8(response).expect("UTF-8 response") + } + + fn json_body(response: &str) -> serde_json::Value { + let body = response.split_once("\r\n\r\n").expect("response body").1; + serde_json::from_str(body).expect("JSON response body") + } + + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §authentication + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn a_client_whose_process_is_not_identified_is_answered_as_one_the_broker_does_not_authenticate() { + let health = exchange_captured( + "unidentified-health", + capture_no_process, + "GET /v2/health HTTP/1.1\r\nHost: broker\r\n\r\n", + ) + .await; + let capabilities = exchange_captured( + "unidentified-capabilities", + capture_no_process, + "GET /v2/capabilities HTTP/1.1\r\nHost: broker\r\n\r\n", + ) + .await; + + assert!(health.starts_with("HTTP/1.1 200"), "{health}"); + assert_eq!(json_body(&health), serde_json::json!({ "Status": "Paused" })); + assert!(capabilities.starts_with("HTTP/1.1 401"), "{capabilities}"); + assert_eq!(json_body(&capabilities)["Code"], "Unauthenticated", "{capabilities}"); + } + + // oracle: mutant sending a response to a 1.x request of a client whose process is not identified, which no 1.x route serves + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn a_client_whose_process_is_not_identified_gets_no_response_to_a_1_x_request() { + let response = exchange_captured( + "unidentified-v1", + capture_no_process, + "GET /v1/health HTTP/1.1\r\nHost: localhost\r\n\r\n", + ) + .await; + + assert_eq!(response, ""); + } + + // oracle: mutant serving a client whose process is identified as one whose process is not, so that no request of its is authenticated + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn a_client_whose_process_is_identified_is_served_as_that_process() { + let v1_health = exchange_captured( + "identified-v1", + capture_the_test_process, + "GET /v1/health HTTP/1.1\r\nHost: localhost\r\n\r\n", + ) + .await; + let capabilities = exchange_captured( + "identified-capabilities", + capture_the_test_process, + "GET /v2/capabilities HTTP/1.1\r\nHost: broker\r\n\r\n", + ) + .await; + + assert!(v1_health.starts_with("HTTP/1.1 200"), "{v1_health}"); + assert!(capabilities.starts_with("HTTP/1.1 200"), "{capabilities}"); + } + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn idle_connections_are_closed_after_the_header_timeout() { use tokio::io::AsyncReadExt as _; diff --git a/crates/now-package-broker/src/server/connection.rs b/crates/now-package-broker/src/server/connection.rs index e84f546cf..051f9b8fa 100644 --- a/crates/now-package-broker/src/server/connection.rs +++ b/crates/now-package-broker/src/server/connection.rs @@ -1,10 +1,16 @@ //! Router and connection serving helpers. +use std::sync::Arc; use std::time::Duration; +use axum::response::Response; use hyper_util::rt::{TokioIo, TokioTimer}; use tokio::io::{AsyncRead, AsyncWrite}; +use tokio::sync::Notify; use tracing::warn; +use win_api_wrappers::identity::sid::Sid; + +use super::BrokerState; /// How long a client may take to send a complete request header before the connection is closed. const REQUEST_HEADER_TIMEOUT: Duration = Duration::from_secs(5); @@ -17,6 +23,36 @@ where serve_connection_with_header_timeout(stream, router, REQUEST_HEADER_TIMEOUT).await; } +/// Serve the connection of a client whose process the broker did not identify. +/// +/// A request of the 2.0 encoding gets the answer of a client the broker does not authenticate. +/// The 1.x routes serve no client the broker did not identify, so the connection is closed without a response once +/// the header of any other request is read. +/// `user_sid` is the user the client process seemed to run as. +pub(crate) async fn serve_unidentified_connection(stream: S, state: Arc, user_sid: Sid) +where + S: AsyncRead + AsyncWrite + Unpin + Send + 'static, +{ + let unanswered = Arc::new(Notify::new()); + let never_answered = axum::Router::new().fallback({ + let unanswered = Arc::clone(&unanswered); + move || { + let unanswered = Arc::clone(&unanswered); + async move { + unanswered.notify_one(); + // The connection is dropped while this request waits, so nothing is ever written for it. + std::future::pending::().await + } + } + }); + let router = crate::v2::routes::route_unidentified(state, user_sid, never_answered); + + tokio::select! { + () = serve_connection(stream, router) => {} + () = unanswered.notified() => {} + } +} + /// Serve one HTTP/1 connection, closing it when the request header is not received within `header_timeout`. pub(crate) async fn serve_connection_with_header_timeout(stream: S, router: axum::Router, header_timeout: Duration) where diff --git a/crates/now-package-broker/src/server/mod.rs b/crates/now-package-broker/src/server/mod.rs index 0d8b1830b..4d4b06616 100644 --- a/crates/now-package-broker/src/server/mod.rs +++ b/crates/now-package-broker/src/server/mod.rs @@ -47,6 +47,7 @@ mod responses; pub use connection::serve_connection; #[cfg(test)] pub(crate) use connection::serve_connection_with_header_timeout; +pub(crate) use connection::serve_unidentified_connection; pub(crate) use pipe_identity::PipeIdentity; use responses::{ api_version, diagnostics, error_response, filter_manager_capabilities, new_operation_id, parse_rule_id, diff --git a/crates/now-package-broker/src/v2/routes/mod.rs b/crates/now-package-broker/src/v2/routes/mod.rs index 05c3c3685..42c6cf7cc 100644 --- a/crates/now-package-broker/src/v2/routes/mod.rs +++ b/crates/now-package-broker/src/v2/routes/mod.rs @@ -13,19 +13,21 @@ mod policy; use std::future::Future; use std::panic::AssertUnwindSafe; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use std::pin::Pin; use std::sync::Arc; use std::task::{Context, Poll}; use axum::body::{Body, Bytes, HttpBody as _, to_bytes}; use axum::extract::Request; +use axum::http::request::Parts; use axum::http::{HeaderMap, HeaderValue, StatusCode, header}; use axum::response::Response; use chrono::Utc; use now_policy_api::v2; use tower_service::Service as _; use tracing::{error, warn}; +use win_api_wrappers::identity::sid::Sid; pub use self::held::HeldOperations; use super::policy::{EvaluationError, is_not_runnable}; @@ -60,6 +62,29 @@ pub(crate) fn route_connection(state: Arc, client: PipeClient, othe }) } +/// Returns a router that answers the requests of the 2.0 encoding of one connected client whose process the broker did not identify, and sends every other request to `other`. +/// +/// The broker authenticates no such client, so the client gets the answers of one it does not authenticate ([§authentication]). +/// `user_sid` is the user the client process seemed to run as; it names the client in a denial record, and nothing else uses it. +/// +/// [§authentication]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#authentication +pub(crate) fn route_unidentified(state: Arc, user_sid: Sid, other: axum::Router) -> axum::Router { + let client = Arc::new(UnidentifiedClient { state, user_sid }); + + axum::Router::new().fallback(move |request: Request| { + let client = Arc::clone(&client); + let other = other.clone(); + + async move { + if is_v2(&request) { + CatchPanic(Box::pin(client.respond(request))).await + } else { + forward(other, request).await + } + } + }) +} + /// Returns a router that answers every request of the 2.0 encoding with `BrokerBusy`, and sends every other request to `other` ([§errors]). /// /// The response is sent without reading the request body, and nothing is started or changed. @@ -106,38 +131,23 @@ impl Connection { async fn respond(self: Arc, request: Request) -> Response { let (parts, body) = request.into_parts(); - let Ok(route) = wire::route(parts.method.as_str(), parts.uri.path()) else { - return error_response(v2::ErrorCode::UnknownEndpoint, "the method and path match no endpoint"); + let route = match find_endpoint(&parts) { + Ok(route) => route, + Err(response) => return *response, }; let endpoint = route.endpoint; - let body_limit = endpoint.body_limit(); - - if 0 < body_limit && !has_json_media_type(&parts.headers) { - return error_response( - v2::ErrorCode::UnsupportedMediaType, - "the content type of the request is not application/json", - ); - } if let Some(response) = self.refuse_client(endpoint) { return response; } - let body = match read_body(body, body_limit).await { + let body = match read_body(body, endpoint.body_limit()).await { Ok(body) => body, Err(error) => { if endpoint == v2::Endpoint::Replace { self.record_rejected_replacement(); } - return match error { - BodyError::TooLarge => error_response( - v2::ErrorCode::RequestTooLarge, - "the request body is larger than the limit of its endpoint", - ), - BodyError::Unreadable => { - error_response(v2::ErrorCode::BadRequest, "the request body could not be read") - } - }; + return unread_body(&error); } }; @@ -161,10 +171,7 @@ impl Connection { if must_be_administrator { self.record_replacement_denial(DenialReason::AuthenticationFailed); } - return Some(error_response( - v2::ErrorCode::Unauthenticated, - "the client process is not authenticated", - )); + return Some(unauthenticated()); } if must_be_administrator && !self.client.is_elevated_administrator() { @@ -182,7 +189,7 @@ impl Connection { crate::audit::document_write_denied( self.client.user_sid(), self.client.executable_path(), - &self.configured_policy_path(), + &configured_policy_path(&self.state), reason, ); } @@ -195,7 +202,7 @@ impl Connection { WriteAudit::begin_document( self.client.user_sid(), self.client.executable_path(), - &self.configured_policy_path(), + &configured_policy_path(&self.state), ) } @@ -207,23 +214,6 @@ impl Connection { drop(self.begin_replacement_audit()); } - fn configured_policy_path(&self) -> PathBuf { - PathBuf::from(self.state.policy_store.management_snapshot().configured_path) - } - - /// Tells whether the broker holds an accepted policy ([§health]). - /// - /// [§health]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#health - fn health(&self) -> Response { - let status = if self.state.policy_store.accepted_policy().is_some() { - v2::HealthStatus::Ready - } else { - v2::HealthStatus::Paused - }; - - json(StatusCode::OK, &v2::HealthResponse { status }) - } - /// Names the managers the broker finds for the client's user ([§capabilities]). /// /// [§capabilities]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#capabilities @@ -308,7 +298,7 @@ impl Connection { /// Answers a request that passed every check made before its body is read. async fn serve(&self, route: &wire::Route, headers: &HeaderMap, body: &[u8]) -> Response { match route.endpoint { - v2::Endpoint::Health => self.health(), + v2::Endpoint::Health => health(&self.state), v2::Endpoint::Capabilities => self.capabilities().await, v2::Endpoint::Status => self.status(route), v2::Endpoint::Cancel => self.cancel(route), @@ -340,6 +330,110 @@ impl Connection { } } +/// One connected client whose process the broker did not identify, and the broker it reached. +/// +/// Nothing the broker read about such a client is confirmed, so this client owns nothing, starts nothing, and is +/// never named to the policy store. +struct UnidentifiedClient { + state: Arc, + /// The user the client process seemed to run as when it connected. + user_sid: Sid, +} + +impl UnidentifiedClient { + /// Answers one request whose path starts with [`PATH_PREFIX`]. + /// + /// The checks run in the order of the outcomes of [§errors]. + /// The broker does not authenticate the client, so a request to an endpoint whose client must be authenticated + /// is `Unauthenticated`, and its body is never read ([§authentication]). + /// + /// [§errors]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#errors + /// [§authentication]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#authentication + async fn respond(self: Arc, request: Request) -> Response { + let (parts, body) = request.into_parts(); + + let endpoint = match find_endpoint(&parts) { + Ok(route) => route.endpoint, + Err(response) => return *response, + }; + + match endpoint { + // The only endpoint that answers any client. + v2::Endpoint::Health => match read_body(body, endpoint.body_limit()).await { + Ok(_empty) => health(&self.state), + Err(error) => unread_body(&error), + }, + v2::Endpoint::Replace => { + // The executable of the client is not known, so the record names none. + crate::audit::document_write_denied( + &self.user_sid, + Path::new(""), + &configured_policy_path(&self.state), + DenialReason::AuthenticationFailed, + ); + unauthenticated() + } + v2::Endpoint::Capabilities + | v2::Endpoint::Evaluate + | v2::Endpoint::Execute + | v2::Endpoint::ExecuteBypass + | v2::Endpoint::Status + | v2::Endpoint::Cancel + | v2::Endpoint::Management + | v2::Endpoint::Validate => unauthenticated(), + } + } +} + +/// Finds the endpoint of a request, and checks that a request to an endpoint that takes a body gives its media type +/// as JSON. +/// +/// The error is the response of a request that meets `UnknownEndpoint` or `UnsupportedMediaType`, the outcomes of +/// [§errors] that come before any about the client. +/// +/// [§errors]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#errors +fn find_endpoint(parts: &Parts) -> Result> { + let Ok(route) = wire::route(parts.method.as_str(), parts.uri.path()) else { + return Err(Box::new(error_response( + v2::ErrorCode::UnknownEndpoint, + "the method and path match no endpoint", + ))); + }; + + if 0 < route.endpoint.body_limit() && !has_json_media_type(&parts.headers) { + return Err(Box::new(error_response( + v2::ErrorCode::UnsupportedMediaType, + "the content type of the request is not application/json", + ))); + } + + Ok(route) +} + +fn unauthenticated() -> Response { + error_response( + v2::ErrorCode::Unauthenticated, + "the client process is not authenticated", + ) +} + +fn configured_policy_path(state: &BrokerState) -> PathBuf { + PathBuf::from(state.policy_store.management_snapshot().configured_path) +} + +/// Tells whether the broker holds an accepted policy ([§health]). +/// +/// [§health]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#health +fn health(state: &BrokerState) -> Response { + let status = if state.policy_store.accepted_policy().is_some() { + v2::HealthStatus::Ready + } else { + v2::HealthStatus::Paused + }; + + json(StatusCode::OK, &v2::HealthResponse { status }) +} + /// A package request and the decision the accepted policy gave it. struct Evaluated { /// The request as the evaluator read it, which is what an operation runs. @@ -382,6 +476,17 @@ async fn read_body(body: Body, limit: usize) -> Result { }) } +/// Returns the response to a request whose body was not read. +fn unread_body(error: &BodyError) -> Response { + match error { + BodyError::TooLarge => error_response( + v2::ErrorCode::RequestTooLarge, + "the request body is larger than the limit of its endpoint", + ), + BodyError::Unreadable => error_response(v2::ErrorCode::BadRequest, "the request body could not be read"), + } +} + /// Tells whether the request has the media type `application/json`, whatever its parameters ([§transport]). /// /// [§transport]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#transport diff --git a/crates/now-package-broker/src/v2/routes/tests.rs b/crates/now-package-broker/src/v2/routes/tests.rs index 8c69d6b09..400a42e1c 100644 --- a/crates/now-package-broker/src/v2/routes/tests.rs +++ b/crates/now-package-broker/src/v2/routes/tests.rs @@ -14,7 +14,9 @@ use crate::executor::{CommandExecutor, ExecutionContext, ExecutionOutput, Proces use crate::operation_tracker::OperationTracker; use crate::policy_store::{PolicyStore, TestPolicyFile, TestWriteFault}; use crate::remote_grant::RemoteGrantStore; -use crate::server::{BrokerState, build_busy_router, build_router_for_client, serve_connection}; +use crate::server::{ + BrokerState, build_busy_router, build_router_for_client, serve_connection, serve_unidentified_connection, +}; const EVALUATE: &str = "/v2/package-requests/evaluate"; const EXECUTE: &str = "/v2/package-requests/execute"; @@ -593,6 +595,175 @@ async fn a_refused_policy_replacement_leaves_a_denial_record() { ); } +/// The user of a client whose process the broker did not identify. +/// +/// The test process runs as no such user, so a record that names it is one of that client. +fn unidentified_user() -> Sid { + Sid::from_well_known(windows::Win32::Security::WinWorldSid, None).expect("a SID") +} + +/// Returns the router of a connected client whose process the broker did not identify. +/// +/// The broker authenticates the test process, so it refuses nothing because of that process. +fn unidentified_router(state: BrokerState) -> axum::Router { + let other = axum::Router::new().fallback(|| async { axum::Json(serde_json::json!({ "Router": "other" })) }); + + super::route_unidentified(Arc::new(state), unidentified_user(), other) +} + +async fn send_unidentified(state: BrokerState, request: Request) -> Reply { + let mut router = unidentified_router(state); + + reply(router.call(request).await.expect("the router is infallible")).await +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §health +#[tokio::test] +async fn health_answers_a_client_whose_process_the_broker_did_not_identify() { + for (policy_file, status) in [(Some(document("corp-baseline", 3)), "Ready"), (None, "Paused")] { + let state = state_with_policy_file(policy_file.as_deref()); + + let reply = send_unidentified(state, get("/v2/health")).await; + + assert_eq!(reply.status, 200, "{reply:?}"); + assert_eq!(reply.content_type.as_deref(), Some("application/json"), "{reply:?}"); + assert_eq!(reply.body, serde_json::json!({ "Status": status }), "{policy_file:?}"); + } +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §endpoints +#[tokio::test] +async fn a_body_sent_to_health_by_a_client_the_broker_did_not_identify_is_request_too_large() { + let reply = send_unidentified(state(), request(Method::GET, "/v2/health", None, "x")).await; + + reply.assert_error(413, "RequestTooLarge"); +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §authentication +#[tokio::test] +async fn an_endpoint_for_authenticated_clients_is_unauthenticated_for_a_client_the_broker_did_not_identify() { + for request in [ + get("/v2/capabilities"), + post_json(EVALUATE, "{}"), + post_json(EXECUTE, "{}"), + post_json(EXECUTE_BYPASS, "{}"), + get("/v2/operations/op-1"), + post("/v2/operations/op-1/cancel"), + get("/v2/policy/management"), + post_json(VALIDATE, "{}"), + post_json(REPLACE, "{}"), + ] { + let target = format!("{} {}", request.method(), request.uri()); + + let reply = send_unidentified(state(), request).await; + + assert_eq!( + (reply.status, &reply.body["Code"]), + (401, &serde_json::json!("Unauthenticated")), + "{target}" + ); + assert_eq!(reply.members(), ["Code", "Message"], "{target}"); + } +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §errors +#[tokio::test] +async fn a_client_the_broker_did_not_identify_is_answered_in_order_without_any_byte_of_the_body() { + for (path, content_type, status, code) in [ + ("/v2/unknown", "text/plain", 404, "UnknownEndpoint"), + (EVALUATE, "text/plain", 415, "UnsupportedMediaType"), + (REPLACE, "text/plain", 415, "UnsupportedMediaType"), + (EVALUATE, "application/json", 401, "Unauthenticated"), + (REPLACE, "application/json", 401, "Unauthenticated"), + ] { + let reply = exchange( + unidentified_router(state()), + &header_announcing_a_body(path, content_type), + ) + .await; + + reply.assert_error(status, code); + } +} + +// oracle: mutant leaving no denial record of a policy replacement by a client the broker did not identify, or naming in the record a caller the broker does not know +#[tokio::test] +async fn a_policy_replacement_by_a_client_the_broker_did_not_identify_leaves_a_denial_record() { + crate::audit::tests::take_events(); + + let evaluation = send_unidentified(state(), post_json(EVALUATE, "{}")).await; + let replacement = send_unidentified(state(), post_json(REPLACE, "{}")).await; + + evaluation.assert_error(401, "Unauthenticated"); + replacement.assert_error(401, "Unauthenticated"); + let records: Vec<_> = crate::audit::tests::take_events() + .into_iter() + .map(|entry| { + let field = |name: &str| { + entry + .fields + .iter() + .find_map(|(field, value)| (field == name).then(|| value.clone())) + .expect("a denial field") + }; + ( + entry.event_code, + field("intent"), + field("reason"), + field("actor_sid"), + field("actor_exe"), + ) + }) + .collect(); + assert_eq!( + records, + [( + Some(agent_sysevent_codes::POLICY_WRITE_DENIED), + "POST /v2/policy".to_owned(), + "authentication_failed".to_owned(), + "S-1-1-0".to_owned(), + String::new(), + )] + ); +} + +// oracle: mutant answering in the 2.0 encoding a request whose path does not start with `/v2/`, sent by a client the broker did not identify +#[tokio::test] +async fn a_path_outside_the_prefix_from_a_client_the_broker_did_not_identify_reaches_the_other_router() { + for path in ["/v1/health", "/v2", "/v20/health", "/V2/health", "/"] { + let reply = send_unidentified(state(), get(path)).await; + + assert_eq!(reply.body, serde_json::json!({ "Router": "other" }), "{path}"); + } +} + +// oracle: mutant sending a response to a request whose path does not start with `/v2/` on the connection of a client the broker did not identify, which no 1.x route serves +#[tokio::test] +async fn a_request_outside_the_prefix_from_a_client_the_broker_did_not_identify_gets_no_response() { + for request in [ + "GET /v1/health HTTP/1.1\r\nHost: broker\r\n\r\n", + "GET /v2 HTTP/1.1\r\nHost: broker\r\n\r\n", + "PUT /v1/policy HTTP/1.1\r\nHost: broker\r\nContent-Type: application/json\r\nContent-Length: 2\r\n\r\n{}", + ] { + let (mut client, server) = tokio::io::duplex(1 << 16); + let serving = tokio::spawn(serve_unidentified_connection( + server, + Arc::new(state()), + unidentified_user(), + )); + + client.write_all(request.as_bytes()).await.expect("write the request"); + let mut response = Vec::new(); + tokio::time::timeout(Duration::from_secs(10), client.read_to_end(&mut response)) + .await + .expect("the broker closes the connection") + .expect("read to the end of the connection"); + serving.await.expect("the connection is served without a panic"); + + assert_eq!(String::from_utf8_lossy(&response), "", "{request}"); + } +} + /// A valid 2.x 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!( From 48c543936ac5768e4de96184e7d714c29f465617 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Tue, 1 Dec 2026 12:42:10 +0900 Subject: [PATCH 12/38] fix(agent): send the frames of a 2.0 bypass operation to its owner only The event channel of a bypass operation was the channel of an execution: it served the first connection to its pipe, so any process of the user could read the output of an operation the policy did not decide, and the owner connecting after it got nothing. The 2.0 encoding sends the frames of such an operation only on a connection from a process the broker authenticates as the owner, and closes any other connection without a frame. The channel of a bypass operation now identifies the process of a connection the way the request pipe identifies a client, before the hello frame, and compares it with the owner of the operation. A connection it refuses is disconnected and the same pipe instance listens again, for as long as the channel would have waited for a first connection: until 60 seconds after the status became terminal. Identifying a process costs the broker much more than connecting costs a client, so after a refusal the channel waits one second before it identifies another client, with the pipe listening meanwhile. A process of the user that connects in a loop therefore keeps no thread busy, but can still hold the single instance of the pipe against the owner, who keeps the status endpoint. The channel of an execution and the 1.x channel serve the first connection as before. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- .../now-package-broker/src/event_channel.rs | 300 +++++++++++++++++- .../src/v2/execution/mod.rs | 3 +- .../src/v2/execution/operations.rs | 142 ++++++++- .../now-package-broker/src/v2/routes/held.rs | 37 ++- .../src/v2/routes/operations.rs | 10 +- .../now-package-broker/src/v2/routes/tests.rs | 58 ++++ 6 files changed, 526 insertions(+), 24 deletions(-) diff --git a/crates/now-package-broker/src/event_channel.rs b/crates/now-package-broker/src/event_channel.rs index a438f9c9b..e5a3f5db9 100644 --- a/crates/now-package-broker/src/event_channel.rs +++ b/crates/now-package-broker/src/event_channel.rs @@ -538,10 +538,13 @@ impl ChannelVersion { } #[cfg(windows)] -pub use windows_channel::{open_operation_channel, open_operation_channel_announcing}; +pub use windows_channel::{ + AdmitClient, Audience, open_operation_channel, open_operation_channel_announcing, open_operation_channel_serving, +}; #[cfg(windows)] mod windows_channel { + use std::sync::Arc; use std::time::Duration; use anyhow::Context as _; @@ -573,6 +576,37 @@ mod windows_channel { /// the kernel pipe buffer is full, i.e. the client stopped reading. const WRITE_STALL_TIMEOUT: Duration = Duration::from_secs(30); + /// After the channel refused a connection, how long it waits before it asks whether the client of another one is + /// admitted. + /// + /// Telling who a client is costs the broker far more than connecting costs a client, so a process that connects in + /// a loop would otherwise keep a thread of the broker busy. + /// The pipe listens during the wait: a client that connects then gets its first frame late, not a busy pipe. + const REFUSAL_PAUSE: Duration = Duration::from_secs(1); + + /// How long the channel waits for the read of a refused connection to end once it closed the connection, after + /// which it gives the pipe up. + const REFUSED_READ_TIMEOUT: Duration = Duration::from_secs(5); + + /// Tells whether the client of a connected event pipe is one the channel sends its frames to. + /// + /// The channel calls it off the async runtime, so it may block. + pub type AdmitClient = Arc bool + Send + Sync>; + + /// The connections an event channel sends its frames on ([§event-channel]). + /// + /// [§event-channel]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#event-channel + #[derive(Clone)] + pub enum Audience { + /// The first connection, whatever process it is from. + FirstConnection, + /// The first connection whose client the function admits. + /// + /// The channel closes a connection whose client is not admitted without sending a frame on it, and then + /// listens again on the same pipe instance. + Admitted(AdmitClient), + } + /// Create the event channel for an operation. /// /// The named pipe instance is created (with its security descriptor) before this @@ -596,6 +630,18 @@ mod windows_channel { version: ChannelVersion, operation_id: &str, client_sid: &Sid, + ) -> anyhow::Result<(OperationEventSink, EventChannel)> { + open_operation_channel_serving(Audience::FirstConnection, version, operation_id, client_sid) + } + + /// Create the event channel for an operation, which sends its frames on a connection of `audience`. + /// + /// It is otherwise [`open_operation_channel_announcing`]. + pub fn open_operation_channel_serving( + audience: Audience, + version: ChannelVersion, + operation_id: &str, + client_sid: &Sid, ) -> anyhow::Result<(OperationEventSink, EventChannel)> { let sink = OperationEventSink::new(); let pipe_name = operation_pipe_name(operation_id); @@ -629,7 +675,7 @@ mod windows_channel { let writer_sink = sink.clone(); let operation_id = operation_id.to_owned(); tokio::spawn(async move { - run_channel(version, server, writer_sink, &operation_id).await; + run_channel(audience, version, server, writer_sink, &operation_id).await; }); Ok((sink, descriptor)) @@ -637,29 +683,22 @@ mod windows_channel { /// Serve one client connection on the operation's event pipe, best-effort. async fn run_channel( + audience: Audience, version: ChannelVersion, server: NamedPipeServer, sink: OperationEventSink, operation_id: &str, ) { - // Wait for a client; once the operation finishes without one, linger only - // for a bounded grace period so late clients can still fetch the frames. - let connected = tokio::select! { - result = server.connect() => result.is_ok(), - () = sink.finished() => { - matches!( - tokio::time::timeout(NEVER_CONNECTED_LINGER, server.connect()).await, - Ok(Ok(())) - ) - } + let connected = match audience { + Audience::FirstConnection => accept_first(server, &sink).await, + Audience::Admitted(admit) => accept_admitted(server, &sink, &admit, operation_id).await, }; - if !connected { + let Some(mut server) = connected else { debug!(operation_id, "No client connected to the event channel"); return; - } + }; debug!(operation_id, "Client connected to the event channel"); - let mut server = server; let (version_major, version_minor) = version.numbers(); let hello = EventFrame::Hello { @@ -709,6 +748,111 @@ mod windows_channel { debug!(operation_id, "Event channel closed"); } + /// Waits for the first connection on `server`, and returns the pipe once a client is connected. + /// + /// Returns `None` when no client connects before the channel stops waiting for one. + async fn accept_first(server: NamedPipeServer, sink: &OperationEventSink) -> Option { + // Wait for a client; once the operation finishes without one, linger only + // for a bounded grace period so late clients can still fetch the frames. + let connected = tokio::select! { + result = server.connect() => result.is_ok(), + () = sink.finished() => { + matches!( + tokio::time::timeout(NEVER_CONNECTED_LINGER, server.connect()).await, + Ok(Ok(())) + ) + } + }; + + connected.then_some(server) + } + + /// Waits for the first connection on `server` whose client `admit` admits, and returns the pipe connected to it. + /// + /// Returns `None` when no such client connects before the channel stops waiting for one. + async fn accept_admitted( + server: NamedPipeServer, + sink: &OperationEventSink, + admit: &AdmitClient, + operation_id: &str, + ) -> Option { + // UNTESTED: The channel closes 60 seconds after the status became terminal when no admitted client connected, + // however many connections it refused in that time, and no refused connection closes it earlier. + // A wait that started again with each refused connection would let a process that connects in a loop keep the + // pipe and the queued output for as long as it likes. + // No test waits 60 seconds; when changing this function, keep one wait for the whole loop, and keep it out of + // the admission of a client that is already connected. + let linger = async { + sink.finished().await; + tokio::time::sleep(NEVER_CONNECTED_LINGER).await; + }; + tokio::pin!(linger); + + let mut server = server; + let mut refused_before = false; + let mut admit_from = tokio::time::Instant::now(); + + loop { + let connected = tokio::select! { + // A client that connects in a loop is always there, and must not keep the wait from ending. + biased; + () = &mut linger => false, + result = server.connect() => result.is_ok(), + }; + if !connected { + return None; + } + if refused_before { + // The pipe still holds what its read for the refused connection ended with. + // Taking it makes the pipe read for this connection, which the wait for the served client to close + // its end relies on. + let _ = server.try_read(&mut [0u8; 1]); + } + + tokio::time::sleep_until(admit_from).await; + + let admission = tokio::task::spawn_blocking({ + let admit = Arc::clone(admit); + move || { + let admitted = admit(&server); + (server, admitted) + } + }); + let admitted; + (server, admitted) = match admission.await { + Ok(admission) => admission, + Err(error) => { + debug!(operation_id, %error, "Failed to tell whether the event channel admits a client"); + return None; + } + }; + if admitted { + return Some(server); + } + + debug!(operation_id, "Refused a connection to the event channel"); + // The same instance listens again: the pipe never has a second one. + if let Err(error) = server.disconnect() { + debug!(operation_id, %error, "Failed to close a refused connection to the event channel"); + return None; + } + // The pipe started a read when the client connected, which the disconnection ends. + // Its end is awaited here, so that it is not taken for something the next client did. + let read = tokio::time::timeout(REFUSED_READ_TIMEOUT, server.read(&mut [0u8; 1])).await; + if !matches!(read, Ok(Ok(0) | Err(_))) { + // A client has no write access to the pipe, and a disconnection ends a read at once. + debug!( + operation_id, + ?read, + "Failed to end the read of a refused connection to the event channel" + ); + return None; + } + refused_before = true; + admit_from = tokio::time::Instant::now() + REFUSAL_PAUSE; + } + } + /// Write one frame with a bounded deadline. /// /// A connected client that stops reading would otherwise leave the write @@ -1156,7 +1300,7 @@ mod tests { } #[cfg(all(test, windows))] -mod pipe_tests { +pub(crate) mod pipe_tests { use std::time::Duration; use now_policy_api::EventChannelKind; @@ -1190,6 +1334,11 @@ mod pipe_tests { .open(&path) .expect("connect to event channel pipe"); + read_frames(&mut client).await + } + + /// Reads the frames `client` receives, up to `Finish` or to the end of the stream. + async fn read_frames(client: &mut tokio::net::windows::named_pipe::NamedPipeClient) -> Vec { let mut decoder = EventFrameDecoder::new(); let mut frames = Vec::new(); let mut buffer = [0u8; 4096]; @@ -1501,4 +1650,123 @@ mod pipe_tests { assert!(skipped > 0, "slow reader must observe overflow"); assert_eq!(received + skipped, (chunk.len() * pushes) as u64); } + + /// An audience that admits the client of each connection as `answers` says, in the order of the connections. + fn admitting(answers: &'static [bool]) -> Audience { + let asked = std::sync::atomic::AtomicUsize::new(0); + + Audience::Admitted(Arc::new(move |_pipe| { + let connection = asked.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + *answers.get(connection).expect("the test opens no other connection") + })) + } + + /// Opens the channel of a 2.0 operation that sends its frames on a connection of `audience`. + fn open_serving(audience: Audience, tag: &str) -> (OperationEventSink, String) { + let (sink, descriptor) = open_operation_channel_serving( + audience, + ChannelVersion::V2_0, + &test_operation_id(tag), + ¤t_user_sid(), + ) + .expect("open channel"); + + (sink, descriptor.path) + } + + /// Opens the event pipe `pipe_name` for reading, once the pipe listens. + pub(crate) async fn connect(pipe_name: &str) -> tokio::net::windows::named_pipe::NamedPipeClient { + const ERROR_PIPE_BUSY: i32 = 231; + + let path = format!(r"\\.\pipe\{pipe_name}"); + let connected = async { + loop { + match tokio::net::windows::named_pipe::ClientOptions::new() + .write(false) + .open(&path) + { + Ok(client) => return client, + // The pipe has one instance, which is taking its previous client off. + Err(error) if error.raw_os_error() == Some(ERROR_PIPE_BUSY) => { + tokio::time::sleep(Duration::from_millis(10)).await; + } + Err(error) => panic!("connect to event channel pipe: {error}"), + } + } + }; + + tokio::time::timeout(Duration::from_secs(10), connected) + .await + .expect("the pipe listens again") + } + + /// Connects to the event pipe `pipe_name`, and returns the bytes the channel sent before it closed the connection. + pub(crate) async fn bytes_of_a_closed_connection(pipe_name: &str) -> Vec { + let mut client = connect(pipe_name).await; + let mut received = Vec::new(); + // The read ends with an error when the channel closes the connection, and keeps what it read before. + let _ = tokio::time::timeout(Duration::from_secs(10), client.read_to_end(&mut received)) + .await + .expect("the channel closes the connection"); + + received + } + + const HELLO_2_0: EventFrame = EventFrame::Hello { + version_major: 2, + version_minor: 0, + }; + + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §event-channel + #[tokio::test] + async fn a_channel_for_admitted_clients_sends_its_frames_on_the_connection_of_one() { + let (sink, pipe_name) = open_serving(admitting(&[true]), "admitted"); + sink.stdout(b"output"); + sink.finish(); + + let frames = read_frames(&mut connect(&pipe_name).await).await; + + assert_eq!( + frames, + [HELLO_2_0, EventFrame::Stdout("output".to_owned()), EventFrame::Finish] + ); + } + + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §event-channel + #[tokio::test] + async fn a_refused_connection_gets_no_frame_and_the_next_admitted_one_gets_them_all() { + let (sink, pipe_name) = open_serving(admitting(&[false, false, true]), "refused"); + sink.stdout(b"output"); + sink.finish(); + + for _ in 0..2 { + let received = bytes_of_a_closed_connection(&pipe_name).await; + assert_eq!(received, [0u8; 0]); + // The pipe of the channel allows no other instance. + tokio::net::windows::named_pipe::ServerOptions::new() + .create(format!(r"\\.\pipe\{pipe_name}")) + .expect_err("the pipe got a second instance"); + } + let frames = read_frames(&mut connect(&pipe_name).await).await; + + assert_eq!( + frames, + [HELLO_2_0, EventFrame::Stdout("output".to_owned()), EventFrame::Finish] + ); + } + + // oracle: mutant leaving in the pipe the result of the read it started for a refused connection, which ends the wait for the served client to read its last frames as soon as FINISH is written + #[tokio::test] + async fn the_channel_waits_for_the_client_it_serves_to_close_after_it_refused_a_connection() { + let (sink, pipe_name) = open_serving(admitting(&[false, true]), "refused-drain"); + sink.finish(); + bytes_of_a_closed_connection(&pipe_name).await; + + let mut client = connect(&pipe_name).await; + let frames = read_frames(&mut client).await; + let closed = tokio::time::timeout(Duration::from_millis(500), client.read(&mut [0u8; 1])).await; + + assert_eq!(frames, [HELLO_2_0, EventFrame::Finish]); + assert!(closed.is_err(), "the channel closed its end first: {closed:?}"); + } } diff --git a/crates/now-package-broker/src/v2/execution/mod.rs b/crates/now-package-broker/src/v2/execution/mod.rs index b9ae501c1..71ff46fc0 100644 --- a/crates/now-package-broker/src/v2/execution/mod.rs +++ b/crates/now-package-broker/src/v2/execution/mod.rs @@ -5,6 +5,7 @@ mod owner; mod plan; pub use self::operations::{ - Caller, Existing, MAX_MESSAGE_BYTES, OperationState, Operations, RETENTION, Start, StartedOperation, Status, + Caller, Existing, IdentifyPipeClient, MAX_MESSAGE_BYTES, OperationState, Operations, RETENTION, Start, + StartedOperation, Status, }; pub use self::owner::Owner; diff --git a/crates/now-package-broker/src/v2/execution/operations.rs b/crates/now-package-broker/src/v2/execution/operations.rs index 581954cea..a1f859f57 100644 --- a/crates/now-package-broker/src/v2/execution/operations.rs +++ b/crates/now-package-broker/src/v2/execution/operations.rs @@ -7,13 +7,14 @@ use std::time::{Duration, Instant}; use chrono::{DateTime, Utc}; use now_policy_eval::Request; use parking_lot::Mutex; +use tokio::net::windows::named_pipe::NamedPipeServer; use tokio_util::sync::CancellationToken; -use tracing::{info, warn}; +use tracing::{debug, info, warn}; use uuid::Uuid; use super::owner::Owner; use super::plan::plan_protecting_agent; -use crate::event_channel::{ChannelVersion, OperationEventSink, open_operation_channel_announcing}; +use crate::event_channel::{Audience, ChannelVersion, OperationEventSink, open_operation_channel_serving}; use crate::executor::{ CommandExecutor, ExecutionContext, ProcessStartedCallback, TokenElevationCheck, is_canceled_error, }; @@ -137,10 +138,53 @@ pub struct Operations { inner: Arc>, } +/// Returns the owner that the client process of a connected pipe is, when the broker authenticates that process +/// ([§authentication]). +/// +/// It may block. +/// +/// [§authentication]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#authentication +pub type IdentifyPipeClient = Arc anyhow::Result + Send + Sync>; + +/// The connections on which the event channels of a registry send their frames ([§event-channel]). +/// +/// [§event-channel]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#event-channel +enum EventAudience { + /// The first connection to the pipe of an operation, whatever process it is from. + FirstConnection, + /// The first connection from a process that the function identifies as the owner of the operation. + Owner(IdentifyPipeClient), +} + +impl EventAudience { + /// Returns the connections on which the channel of the operation `operation_id` of `owner` sends its frames. + fn of(&self, owner: &Owner, operation_id: &str) -> Audience { + let Self::Owner(identify) = self else { + return Audience::FirstConnection; + }; + + let identify = Arc::clone(identify); + let owner = owner.clone(); + let operation_id = operation_id.to_owned(); + Audience::Admitted(Arc::new(move |pipe| match identify(pipe) { + Ok(client) => client == owner, + Err(error) => { + debug!( + %operation_id, + error = format!("{error:#}"), + "Failed to identify the client of an event channel" + ); + false + } + })) + } +} + struct Inner { executor: Arc, /// Reads the MSI product code of the installed Devolutions Agent. agent_product_code: fn() -> anyhow::Result>, + event_audience: EventAudience, state: Mutex>, } @@ -276,14 +320,41 @@ where /// `agent_product_code` reads the MSI product code of the installed Agent, `Ok(None)` when none is installed. /// An operation that removes a package runs no step and ends `Failed` when its request names the Agent, or when /// the product code cannot be read. + /// + /// The event channel of an operation sends its frames on the first connection to its pipe, whatever process it + /// is from. pub fn protecting_agent( executor: Arc, agent_product_code: fn() -> anyhow::Result>, + ) -> Self { + Self::with_event_audience(executor, agent_product_code, EventAudience::FirstConnection) + } + + /// Returns a registry like that of [`Self::protecting_agent`], except that the event channel of an operation + /// sends frames only on a connection from a process that `identify` identifies as the owner of the operation + /// ([§event-channel]). + /// + /// The channel closes any other connection, and one whose client `identify` fails on, without sending a frame. + /// + /// [§event-channel]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#event-channel + pub fn protecting_agent_with_events_for_owner( + executor: Arc, + agent_product_code: fn() -> anyhow::Result>, + identify: IdentifyPipeClient, + ) -> Self { + Self::with_event_audience(executor, agent_product_code, EventAudience::Owner(identify)) + } + + fn with_event_audience( + executor: Arc, + agent_product_code: fn() -> anyhow::Result>, + event_audience: EventAudience, ) -> Self { Self { inner: Arc::new(Inner { executor, agent_product_code, + event_audience, state: Mutex::new(State { operations: HashMap::new(), request_ids: HashMap::new(), @@ -330,8 +401,9 @@ where // A channel opened before the lookup, for a request that then has an operation, could only be closed by // finishing it, and a finished channel keeps its pipe open for the 60 seconds it gives a late client. // Creating the pipe waits for no other process. + let audience = self.inner.event_audience.of(&caller.owner, &operation_id); let (events, event_pipe, channel_error) = - match open_operation_channel_announcing(ChannelVersion::V2_0, &operation_id, user_sid) { + match open_operation_channel_serving(audience, ChannelVersion::V2_0, &operation_id, user_sid) { Ok((sink, channel)) => (Some(sink), Some(channel.path), None), // The operation runs without a channel, and its response names no pipe. Err(error) => (None, None, Some(error)), @@ -648,12 +720,30 @@ mod tests { impl Fixture { fn new() -> Self { + Self::with_registry(Operations::new) + } + + /// A fixture whose registry sends the frames of an operation to its owner only, and identifies the client of + /// each connection to an event pipe as `identified` says, in the order of the connections. + fn identifying(identified: Vec>) -> Self { + let identified = Mutex::new(identified.into_iter()); + let identify: IdentifyPipeClient = + Arc::new(move |_pipe| identified.lock().next().expect("the test opens no other connection")); + + Self::with_registry(|executor| { + Operations::protecting_agent_with_events_for_owner(executor, || Ok(None), identify) + }) + } + + fn with_registry( + registry: impl FnOnce(Arc) -> Operations<&'static str, &'static str>, + ) -> Self { let (steps, receiver) = mpsc::unbounded_channel(); let executor = Arc::new(ScriptedExecutor { contexts: Mutex::new(Vec::new()), steps: tokio::sync::Mutex::new(receiver), }); - let operations = Operations::new(Arc::clone(&executor) as Arc); + let operations = registry(Arc::clone(&executor) as Arc); Self { operations, executor, @@ -1349,4 +1439,48 @@ mod tests { "{second:?}" ); } + + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §event-channel + #[tokio::test] + async fn a_channel_for_the_owner_sends_its_frames_to_the_process_identified_as_the_owner_and_to_no_other() { + use crate::event_channel::pipe_tests::{bytes_of_a_closed_connection, connect}; + + let caller = current_user(); + let user = caller.owner.user_sid(); + let fixture = Fixture::identifying(vec![ + // Another executable run by the user of the owner. + Ok(Owner::new(user, std::path::Path::new(r"C:\Tools\other.exe"))), + // The executable of the owner run by another user. + Ok(Owner::new( + &everyone_sid(), + std::path::Path::new(r"C:\Tools\client.exe"), + )), + // A process the broker does not authenticate. + Err(anyhow!("the process has no signature the broker accepts")), + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §def-owner + // The owner, whose path is equal ignoring case. + Ok(Owner::new(user, std::path::Path::new(r"c:\tools\CLIENT.EXE"))), + ]); + let started = fixture.start(&caller, "request-1", &winget_install()); + let pipe = started.event_pipe.as_deref().expect("event pipe"); + fixture.step(Step::Exit(0)); + fixture + .wait_for(&caller.owner, &started.operation_id, Status::Completed) + .await; + + for refused in ["another executable", "another user", "an unauthenticated process"] { + assert_eq!(bytes_of_a_closed_connection(pipe).await, [0u8; 0], "{refused}"); + } + let mut owner = connect(pipe).await; + + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §frame-order + assert_eq!( + read_frames(&mut owner).await, + [ + 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, // HELLO, version 2.0. + 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, // STATUS_UPDATED, for `Completed`. + 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, // FINISH. + ] + ); + } } diff --git a/crates/now-package-broker/src/v2/routes/held.rs b/crates/now-package-broker/src/v2/routes/held.rs index db3188eed..8a47116b6 100644 --- a/crates/now-package-broker/src/v2/routes/held.rs +++ b/crates/now-package-broker/src/v2/routes/held.rs @@ -9,9 +9,11 @@ use std::sync::{Arc, OnceLock}; use now_policy_api::v2; use tokio_util::sync::CancellationToken; +use super::operations::owner_of; +use crate::auth::PipeClient; use crate::server::BrokerState; use crate::v2::bypass::BypassTokens; -use crate::v2::execution::Operations; +use crate::v2::execution::{IdentifyPipeClient, Operations}; /// What the response to the execution request that started an operation says besides the operation ([§execute]). /// @@ -40,7 +42,10 @@ pub(super) type Executions = Operations; /// Execution requests have a registry of their own, so the `RequestId` of a request of one kind neither conflicts /// with nor replays a request of the other. /// +/// The event channel of an operation here sends its frames to the owner of the operation only ([§event-channel]). +/// /// [§bypass]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#bypass +/// [§event-channel]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#event-channel pub(super) type Bypasses = Operations; /// The operations started by the requests of the 2.0 encoding and the bypass tokens the broker holds, which a broker @@ -66,7 +71,11 @@ impl HeldOperations { pub(super) fn of(&self, state: &BrokerState) -> &Registries { self.registries.get_or_init(|| Registries { executions: Operations::protecting_agent(Arc::clone(&state.executor), state.agent_product_code), - bypasses: Operations::protecting_agent(Arc::clone(&state.executor), state.agent_product_code), + bypasses: Operations::protecting_agent_with_events_for_owner( + Arc::clone(&state.executor), + state.agent_product_code, + identify_event_client(state.skip_signature_validation), + ), bypass_tokens: BypassTokens::default(), }) } @@ -81,3 +90,27 @@ impl HeldOperations { registries.bypasses.clone().spawn_eviction_task(shutdown); } } + +/// Returns how the event channel of a bypass operation identifies the process of a connection. +/// +/// `skip_signature_validation` is the setting of the broker state for the clients of requests. +// UNTESTED: The event channel of a bypass operation identifies the process of a connection the way the request pipe +// identifies the client of a request: `PipeClient::from_connected_pipe`, then `validate_connection` with the setting +// of the broker state, and the owner that `Connection::caller` makes of such a client. +// A weaker identification would send the output of a bypassed operation to a process the broker does not +// authenticate as its owner, and an owner made another way would be refused its own frames. +// The tests of the channel identify with a function of their own, and the one test that runs this function connects +// another executable, which gets no frame; none connects a process that this function identifies as the owner, +// because capture does not accept the test process on every machine. +// When changing this, check with a signed client that the process that sent a bypass request reads the frames of its +// operation, and that an unsigned copy of it and another executable of the same user read none. +// The process identified is the one that opened the connection: a handle that process gives to another one is used +// without the broker seeing it. +fn identify_event_client(skip_signature_validation: bool) -> IdentifyPipeClient { + Arc::new(move |pipe| { + let client = PipeClient::from_connected_pipe(pipe)?; + client.validate_connection(skip_signature_validation)?; + + Ok(owner_of(&client)) + }) +} diff --git a/crates/now-package-broker/src/v2/routes/operations.rs b/crates/now-package-broker/src/v2/routes/operations.rs index 3d746bba0..c32c5fa59 100644 --- a/crates/now-package-broker/src/v2/routes/operations.rs +++ b/crates/now-package-broker/src/v2/routes/operations.rs @@ -10,9 +10,17 @@ use now_policy_api::v2; use super::held::Decided; use super::{Connection, error_response, internal_error, json}; +use crate::auth::PipeClient; use crate::v2::execution::{Caller, Existing, OperationState, Owner, Start, StartedOperation, Status}; use crate::v2::wire; +/// Returns the owner that the client process `client` is ([§def-owner]). +/// +/// [§def-owner]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#def-owner +pub(super) fn owner_of(client: &PipeClient) -> Owner { + Owner::new(client.user_sid(), client.executable_path()) +} + impl Connection { /// The client as the one its requests start operations for. /// @@ -21,7 +29,7 @@ impl Connection { let user_sid = self.client.user_sid(); Caller { - owner: Owner::new(user_sid, self.client.executable_path()), + owner: owner_of(&self.client), session_id: self.client.session_id(), // The name is for logs only, and resolving the account name may wait for a domain controller. display_name: user_sid.to_string(), diff --git a/crates/now-package-broker/src/v2/routes/tests.rs b/crates/now-package-broker/src/v2/routes/tests.rs index 400a42e1c..fa4ec2b37 100644 --- a/crates/now-package-broker/src/v2/routes/tests.rs +++ b/crates/now-package-broker/src/v2/routes/tests.rs @@ -3037,3 +3037,61 @@ async fn a_bypass_request_the_broker_does_not_read_is_internal_error_and_keeps_i } assert_eq!(broker.runs().await, 0); } + +/// Runs another executable as the user of the test process, which opens the event pipe `pipe` for reading, and +/// returns how many of the first ten bytes of the channel it read before the channel closed the connection. +async fn bytes_another_executable_reads(pipe: &str) -> usize { + // The name of an event pipe has letters, digits, `.`, `_` and `-` only. + let script = format!( + "$pipe = New-Object System.IO.Pipes.NamedPipeClientStream('.', '{pipe}', [System.IO.Pipes.PipeDirection]::In); \ + $pipe.Connect(10000); \ + $bytes = New-Object byte[] 10; \ + $total = 0; \ + try {{ \ + while ($total -lt 10) {{ \ + $read = $pipe.Read($bytes, $total, 10 - $total); \ + if ($read -eq 0) {{ break }}; \ + $total += $read \ + }} \ + }} catch [System.IO.IOException] {{ }}; \ + [Console]::Out.Write(\"read $total\")" + ); + let output = tokio::task::spawn_blocking(move || { + std::process::Command::new("powershell.exe") + .args(["-NoProfile", "-NonInteractive", "-Command", &script]) + .stdin(std::process::Stdio::null()) + .output() + .expect("run another executable") + }) + .await + .expect("the other executable ran"); + + let said = String::from_utf8_lossy(&output.stdout); + said.strip_prefix("read ") + .and_then(|count| count.parse().ok()) + .unwrap_or_else(|| panic!("the other executable did not connect to the pipe: {output:?}")) +} + +fn event_pipe(reply: &Reply) -> &str { + reply.body["EventPipe"] + .as_str() + .expect("the broker created the event pipe") +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §event-channel +#[tokio::test] +async fn another_process_of_the_user_reads_the_frames_of_an_execution_and_none_of_a_bypass() { + let broker = Broker::with_policy(ALLOW_ALL, ""); + let execution = broker + .start(&execution_request("request-1", serde_json::json!({}))) + .await; + let bypass = start_bypass(&broker, TOKEN, &bypass_request("request-2", serde_json::json!({}))).await; + + let of_the_execution = bytes_another_executable_reads(event_pipe(&execution)).await; + let of_the_bypass = bytes_another_executable_reads(event_pipe(&bypass)).await; + + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §frames + // The first frame is `HELLO`, which has ten bytes. + assert_eq!(of_the_execution, 10); + assert_eq!(of_the_bypass, 0); +} From 15f5c59a936d778f26aee13cb3128153960a8c8f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Tue, 1 Dec 2026 12:47:32 +0900 Subject: [PATCH 13/38] fix(agent): refuse to hold again a 2.0 bypass token a request used up The broker forgot a bypass token as soon as a request used it up, so the same token given once more was held as a new one and authorized a request again: for another owner of the same user at once, and for the owner once its operation was no longer held. A used-up token never authorizes a request again. The broker now remembers a used-up token until the lifetime it was held with ends. During that time it refuses to hold the token again, the token authorizes nothing, and it counts toward the bound on held tokens, so remembering it costs no more memory than holding it did. Past that time nothing tells the token from a new one, which is why whoever gives the broker tokens must give each one once; `hold` says so. A test also covers the equal request that arrives once the broker no longer holds the operation its token started, which is refused. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- .../src/v2/bypass/tokens.rs | 103 ++++++++++++++---- .../src/v2/routes/bypass.rs | 7 +- .../now-package-broker/src/v2/routes/tests.rs | 48 +++++++- 3 files changed, 134 insertions(+), 24 deletions(-) diff --git a/crates/now-package-broker/src/v2/bypass/tokens.rs b/crates/now-package-broker/src/v2/bypass/tokens.rs index 4bdb2019b..8b09333a7 100644 --- a/crates/now-package-broker/src/v2/bypass/tokens.rs +++ b/crates/now-package-broker/src/v2/bypass/tokens.rs @@ -14,9 +14,12 @@ use win_api_wrappers::identity::sid::Sid; /// /// A token authorizes one request that the Agent expects at once, so a short life bounds how long a token that /// reached another process stays useful. +/// The broker remembers a token that a request used up until the same moment. const TOKEN_LIFETIME: Duration = Duration::from_secs(60); /// The most tokens the broker holds at once, so that the tokens it is given never grow its memory without bound. +/// +/// A used-up token the broker still remembers counts as one it holds. const MAX_HELD_TOKENS: usize = 256; /// The SHA-256 digest of a bypass token. @@ -46,7 +49,7 @@ impl TokenDigest { pub(crate) enum HoldError { /// The text is not a bypass token. NotAToken, - /// The broker already holds this token. + /// The broker already holds this token, or remembers that a request used it up. AlreadyHeld, /// The broker holds [`MAX_HELD_TOKENS`] tokens. TooManyTokens, @@ -56,7 +59,7 @@ impl core::fmt::Display for HoldError { fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { formatter.write_str(match self { Self::NotAToken => "the text is not a bypass token", - Self::AlreadyHeld => "the broker already holds this bypass token", + Self::AlreadyHeld => "the broker was already given this bypass token", Self::TooManyTokens => "the broker holds as many bypass tokens as it allows", }) } @@ -64,20 +67,26 @@ impl core::fmt::Display for HoldError { impl core::error::Error for HoldError {} +/// A token the broker was given, until the lifetime it was held with ends. +struct Given { + /// What the token binds while the broker holds it, or `None` once a request used the token up. + bound: Option, + /// When the lifetime ends, and the broker remembers nothing of the token. + expires_at: Instant, +} + /// What a token binds. struct Bound { /// The bypass request, `RequestId` included. request: v2::BypassRequest, /// The SID of the Windows user. user_sid: Sid, - /// When the broker discards the token. - expires_at: Instant, } /// The bypass tokens the broker holds, which a restart of the broker discards. #[derive(Default)] pub(crate) struct BypassTokens { - held: Mutex>, + given: Mutex>, } impl BypassTokens { @@ -85,8 +94,15 @@ impl BypassTokens { /// [`TOKEN_LIFETIME`]. /// /// This is how Devolutions Agent gives the broker a token. - /// The Agent gives each token once: the broker does not remember a token it no longer holds, so a token given - /// again after it was used up is held as a new one. + /// + /// The broker remembers a token that a request used up until the lifetime it was held with ends, and refuses to + /// hold it until then, so a used-up token authorizes nothing when it is given again ([§bypass]). + /// + /// The caller never gives a token twice. + /// The broker cannot check this: once the lifetime of a token has ended it remembers nothing of the token, so a + /// used-up token given again after that is held as a new one. + /// + /// [§bypass]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#bypass #[cfg_attr( not(test), expect( @@ -102,18 +118,17 @@ impl BypassTokens { let token = v2::BypassToken::parse(token).map_err(|_| HoldError::NotAToken)?; let digest = TokenDigest::of(token.as_str().as_bytes()); - let mut held = self.lock_at(now).held; - if held.contains_key(&digest) { + let mut given = self.lock_at(now).given; + if given.contains_key(&digest) { return Err(HoldError::AlreadyHeld); } - if !(held.len() < MAX_HELD_TOKENS) { + if !(given.len() < MAX_HELD_TOKENS) { return Err(HoldError::TooManyTokens); } - held.insert( + given.insert( digest, - Bound { - request, - user_sid, + Given { + bound: Some(Bound { request, user_sid }), expires_at: now + TOKEN_LIFETIME, }, ); @@ -128,22 +143,24 @@ impl BypassTokens { /// requests with one token that arrive together start one operation, and each of them finds either the token /// held or the operation it started ([§bypass]). /// + /// A token whose lifetime has ended is forgotten here, used up or not. + /// /// [§bypass]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#bypass pub(crate) fn lock(&self) -> HeldTokens<'_> { self.lock_at(Instant::now()) } fn lock_at(&self, now: Instant) -> HeldTokens<'_> { - let mut held = self.held.lock(); - held.retain(|_, bound| now < bound.expires_at); + let mut given = self.given.lock(); + given.retain(|_, token| now < token.expires_at); - HeldTokens { held } + HeldTokens { given } } } -/// The tokens the broker holds, locked ([`BypassTokens::lock`]). +/// The tokens the broker holds and the used-up ones it remembers, locked ([`BypassTokens::lock`]). pub(crate) struct HeldTokens<'a> { - held: MutexGuard<'a, HashMap>, + given: MutexGuard<'a, HashMap>, } impl HeldTokens<'_> { @@ -154,14 +171,19 @@ impl HeldTokens<'_> { /// /// [§bypass]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#bypass pub(crate) fn authorizes(&self, token: &TokenDigest, owner_sid: &Sid, request: &v2::BypassRequest) -> bool { - self.held + self.given .get(token) + .and_then(|given| given.bound.as_ref()) .is_some_and(|bound| bound.user_sid == *owner_sid && bound.request == *request) } /// Uses up the token `token`, which never authorizes a request again. + /// + /// The broker remembers the token until the lifetime it was held with ends ([`BypassTokens::hold`]). pub(crate) fn use_up(&mut self, token: &TokenDigest) { - self.held.remove(token); + if let Some(given) = self.given.get_mut(token) { + given.bound = None; + } } } @@ -348,4 +370,43 @@ mod tests { assert!(still_bound); assert_eq!(after_they_expired, Ok(())); } + + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §bypass + #[test] + fn a_used_up_token_given_again_is_not_held_and_authorizes_no_request() { + let tokens = holding(); + let bound = request(&install()); + let other = request(&with(install(), "RequestId", serde_json::json!("request-2"))); + tokens.lock().use_up(&digest(TOKEN)); + + let again = tokens.hold(TOKEN, bound.clone(), user()); + let rebound = tokens.hold(TOKEN, other.clone(), other_user()); + + assert_eq!(again, Err(HoldError::AlreadyHeld)); + assert_eq!(rebound, Err(HoldError::AlreadyHeld)); + assert!(!tokens.lock().authorizes(&digest(TOKEN), &user(), &bound)); + assert!(!tokens.lock().authorizes(&digest(TOKEN), &other_user(), &other)); + } + + // oracle: mutant forgetting a used-up token before the lifetime it was held with ends, or leaving it out of the bound on held tokens, or remembering it once that lifetime has ended + #[test] + fn a_used_up_token_is_remembered_and_counted_until_the_lifetime_it_was_held_with_ends() { + let tokens = BypassTokens::default(); + let given = Instant::now(); + for index in 0..MAX_HELD_TOKENS { + tokens + .hold_at(given, &format!("token-{index}"), request(&install()), user()) + .expect("hold the token"); + } + tokens.lock_at(given + TOKEN_LIFETIME / 2).use_up(&digest("token-0")); + + let just_before = given + TOKEN_LIFETIME - Duration::from_millis(1); + let again = tokens.hold_at(just_before, "token-0", request(&install()), user()); + let one_more = tokens.hold_at(just_before, "one-more", request(&install()), user()); + let after_its_lifetime = tokens.hold_at(given + TOKEN_LIFETIME, "token-0", request(&install()), user()); + + assert_eq!(again, Err(HoldError::AlreadyHeld)); + assert_eq!(one_more, Err(HoldError::TooManyTokens)); + assert_eq!(after_its_lifetime, Ok(())); + } } diff --git a/crates/now-package-broker/src/v2/routes/bypass.rs b/crates/now-package-broker/src/v2/routes/bypass.rs index 3e5be2c8c..35b753ead 100644 --- a/crates/now-package-broker/src/v2/routes/bypass.rs +++ b/crates/now-package-broker/src/v2/routes/bypass.rs @@ -39,8 +39,11 @@ impl Connection { match registries.bypasses.existing(&caller.owner, &token_name, request) { Some(Existing::Replayed(started)) => return bypass_response(started), - // The token was used up for another request, and never authorizes a request again, even when the broker - // was given it once more. + // The token started the operation of another request of this owner, so it is used up, and the request is + // refused without asking what the token authorizes. + // For a request of another owner, and once the broker no longer holds that operation, the tokens answer: + // a used-up token authorizes nothing, and is not held again within the lifetime it was held with, but + // nothing tells one given again after that from a new token (`BypassTokens::hold`). Some(Existing::Conflict) => return token_rejected(), None => {} } diff --git a/crates/now-package-broker/src/v2/routes/tests.rs b/crates/now-package-broker/src/v2/routes/tests.rs index fa4ec2b37..65e52344f 100644 --- a/crates/now-package-broker/src/v2/routes/tests.rs +++ b/crates/now-package-broker/src/v2/routes/tests.rs @@ -2577,13 +2577,18 @@ fn post_bypass(tokens: &[&str], body: &serde_json::Value) -> Request { /// Gives the broker `token` with the request it binds and the SID of the user it binds, as Devolutions Agent does. fn hold_for(state: &BrokerState, token: &str, request: &serde_json::Value, user_sid: Sid) { + assert!(give(state, token, request, user_sid), "the broker holds the token"); +} + +/// Gives the broker `token` like [`hold_for`], and returns whether the broker holds it for `request` after that. +fn give(state: &BrokerState, token: &str, request: &serde_json::Value, user_sid: Sid) -> bool { let request = crate::v2::wire::read_bypass_request(request.to_string().as_bytes()).expect("a bypass request"); state .operations .of(state) .bypass_tokens .hold(token, request, user_sid) - .expect("the broker holds the token"); + .is_ok() } /// Gives the broker `token` bound to `request` and to the user of the test process. @@ -2777,6 +2782,47 @@ async fn a_used_up_token_authorizes_no_other_request() { assert_eq!(broker.runs().await, 1); } +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §bypass +#[tokio::test] +async fn a_used_up_token_the_broker_is_given_again_authorizes_no_request() { + let broker = Broker::from_state(state()); + start_bypass(&broker, TOKEN, &bypass_request("request-1", serde_json::json!({}))).await; + // The same user, who is another owner from another executable and so has no operation the token names. + let other = OtherExecutable::start(); + let rebound = bypass_request("request-2", serde_json::json!({})); + + let held_again = give(&broker.state, TOKEN, &rebound, client().user_sid().clone()); + let reply = send(&broker.state, &other.client, post_bypass(&[TOKEN], &rebound)).await; + + assert!(!held_again); + reply.assert_error(403, "BypassTokenRejected"); + assert_eq!(broker.runs().await, 1); +} + +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §bypass +#[tokio::test] +async fn an_equal_bypass_request_with_the_token_of_an_operation_the_broker_no_longer_holds_is_bypass_token_rejected() { + let broker = Broker::from_state(state()); + let request = bypass_request("request-1", serde_json::json!({})); + let started = start_bypass(&broker, TOKEN, &request).await; + broker.step(Step::Exit(0)); + broker.wait_for(operation_id(&started), "Completed").await; + + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §operations + // The broker holds an operation for at least 300 seconds after it ended, and may stop holding it then. + let registries = broker.state.operations.of(&broker.state); + registries + .bypasses + .evict_expired(std::time::Instant::now() + Duration::from_secs(300)); + let status = send(&broker.state, &client(), get(&status_path(operation_id(&started)))).await; + status.assert_error(404, "OperationNotFound"); + + let reply = send(&broker.state, &client(), post_bypass(&[TOKEN], &request)).await; + + reply.assert_error(403, "BypassTokenRejected"); + assert_eq!(broker.runs().await, 1); +} + /// How a broker of a test reads the product code of the installed Devolutions Agent. type AgentProductCode = fn() -> anyhow::Result>; From 1577e570482a5f84d830678f1ca0bcd0d4652a47 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Tue, 1 Dec 2026 12:52:18 +0900 Subject: [PATCH 14/38] fix(agent): use a 2.0 bypass token up once the broker holds its operation The broker used a bypass token up before it started the operation of the request. When starting the operation failed, the token was gone and no operation was held, so the request the token authorized could never run: a bypass request that starts no operation does not use up its token. The token is now used up after the start returned, with the tokens still locked, so no other request sees the operation without the token used up, nor the token used up without the operation. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- .../src/v2/bypass/tokens.rs | 6 ++-- .../src/v2/routes/bypass.rs | 27 ++++++++++------- .../now-package-broker/src/v2/routes/tests.rs | 30 +++++++++++++++++++ 3 files changed, 50 insertions(+), 13 deletions(-) diff --git a/crates/now-package-broker/src/v2/bypass/tokens.rs b/crates/now-package-broker/src/v2/bypass/tokens.rs index 8b09333a7..02902facb 100644 --- a/crates/now-package-broker/src/v2/bypass/tokens.rs +++ b/crates/now-package-broker/src/v2/bypass/tokens.rs @@ -139,9 +139,9 @@ impl BypassTokens { /// Locks the tokens the broker holds now. /// /// No other request finds a token held or used up while the returned value lives. - /// A request keeps it from the moment it looks for the operation of its token until it has started one, so that - /// requests with one token that arrive together start one operation, and each of them finds either the token - /// held or the operation it started ([§bypass]). + /// A request keeps it from the moment it looks for the operation of its token until it has started one and used + /// the token up, so that requests with one token that arrive together start one operation, and each of them + /// finds either the token held or the operation it started ([§bypass]). /// /// A token whose lifetime has ended is forgotten here, used up or not. /// diff --git a/crates/now-package-broker/src/v2/routes/bypass.rs b/crates/now-package-broker/src/v2/routes/bypass.rs index 35b753ead..441cfb8ce 100644 --- a/crates/now-package-broker/src/v2/routes/bypass.rs +++ b/crates/now-package-broker/src/v2/routes/bypass.rs @@ -29,12 +29,16 @@ impl Connection { // A token starts one operation at most, so its digest names that operation among those of its owner. let token_name = token.to_hex(); - // UNTESTED: A request never finds a token used up before the operation it started is held. - // Otherwise, of two equal requests that arrive together, the second could be answered `BypassTokenRejected` - // while the first starts the operation, where the contract has it get that operation. - // Everything from the lookup of the operation to its start happens while the tokens are locked, and a test - // that sends requests together passes most of the time without that; when changing this function, keep the - // lock from the lookup until the operation is held. + // UNTESTED: Another request finds either the token held and no operation started with it, or the token used + // up and the operation it started held, and never anything in between. + // Were the token used up before the operation is held, of two equal requests that arrive together, the second + // could be answered `BypassTokenRejected` while the first starts the operation, where the contract has it get + // that operation. + // Were the operation held before the token is used up, the same request from another executable of the user + // could start a second operation with the token. + // Everything from the lookup of the operation to the use of the token happens while the tokens are locked, + // and a test that sends requests together passes most of the time without that; when changing this function, + // keep the lock from the lookup until the token is used up. let mut tokens = registries.bypass_tokens.lock(); match registries.bypasses.existing(&caller.owner, &token_name, request) { @@ -84,11 +88,14 @@ impl Connection { Reading::NotRead(reason) => return internal_error(&reason), }; - tokens.use_up(&token); - match registries + let start = registries .bypasses - .start(&caller, &token_name, request.clone(), &package_request, ()) - { + .start(&caller, &token_name, request.clone(), &package_request, ()); + // The broker holds the operation of the token now, so the token is used up. + // A start that panics holds no operation and never gets here: the token then still authorizes the request. + tokens.use_up(&token); + + match start { Start::Started(started) | Start::Existing(Existing::Replayed(started)) => bypass_response(started), // Not reached while every operation of this registry starts with the tokens locked, as above. Start::Existing(Existing::Conflict) => token_rejected(), diff --git a/crates/now-package-broker/src/v2/routes/tests.rs b/crates/now-package-broker/src/v2/routes/tests.rs index 65e52344f..0451e6189 100644 --- a/crates/now-package-broker/src/v2/routes/tests.rs +++ b/crates/now-package-broker/src/v2/routes/tests.rs @@ -3084,6 +3084,36 @@ async fn a_bypass_request_the_broker_does_not_read_is_internal_error_and_keeps_i assert_eq!(broker.runs().await, 0); } +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §bypass +#[tokio::test] +async fn a_bypass_request_that_fails_before_the_broker_holds_its_operation_keeps_its_token() { + thread_local! { + /// How many times the broker of this test read the product code of the installed Devolutions Agent. + static READS: std::cell::Cell = const { std::cell::Cell::new(0) }; + } + // The first read answers: it tells the broker that the request does not uninstall the Agent. + // The second one, which starting the operation of that request makes, panics, and every later one answers. + let agent_product_code: AgentProductCode = || { + let earlier_reads = READS.replace(READS.get() + 1); + assert_ne!(earlier_reads, 1, "the product code cannot be read"); + Ok(None) + }; + let broker = Broker::from_state(BrokerState { + agent_product_code, + ..state() + }); + let request = bypass_uninstall("Npm", "left-pad"); + hold(&broker.state, TOKEN, &request); + + let failed = send(&broker.state, &client(), post_bypass(&[TOKEN], &request)).await; + let reply = send(&broker.state, &client(), post_bypass(&[TOKEN], &request)).await; + + failed.assert_error(500, "InternalError"); + // The first request started no operation, so the token still authorizes the request. + assert_eq!(reply.status, 200, "{reply:?}"); + assert_eq!(broker.runs().await, 1); +} + /// Runs another executable as the user of the test process, which opens the event pipe `pipe` for reading, and /// returns how many of the first ten bytes of the channel it read before the channel closed the connection. async fn bytes_another_executable_reads(pipe: &str) -> usize { From 619ec65821452715d5f3d80b4138615dd77c03f2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Tue, 1 Dec 2026 13:20:43 +0900 Subject: [PATCH 15/38] test(agent): check the capabilities refusal with the other authenticated endpoints The table of endpoints for authenticated clients already sends the capabilities request of a client the broker does not authenticate. It now checks each refusal as a whole error response, content type and message length included, so the separate capabilities test repeated one of its rows. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- crates/now-package-broker/src/v2/routes/tests.rs | 12 +----------- 1 file changed, 1 insertion(+), 11 deletions(-) diff --git a/crates/now-package-broker/src/v2/routes/tests.rs b/crates/now-package-broker/src/v2/routes/tests.rs index 0451e6189..9ecbed210 100644 --- a/crates/now-package-broker/src/v2/routes/tests.rs +++ b/crates/now-package-broker/src/v2/routes/tests.rs @@ -344,7 +344,7 @@ async fn an_endpoint_for_authenticated_clients_is_unauthenticated_for_any_other( (401, &serde_json::json!("Unauthenticated")), "{target}" ); - assert_eq!(reply.members(), ["Code", "Message"], "{target}"); + reply.assert_error(401, "Unauthenticated"); } } @@ -1098,16 +1098,6 @@ async fn the_capability_of_a_powershell_manager_names_only_the_opt_ins_the_broke ); } -// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §authentication -#[tokio::test] -async fn capabilities_refuse_a_client_the_broker_does_not_authenticate() { - let state = Arc::new(unauthenticating_state()); - - let reply = send(&state, &client(), get("/v2/capabilities")).await; - - reply.assert_error(401, "Unauthenticated"); -} - // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §errors #[tokio::test] async fn a_request_whose_answer_panics_is_internal_error() { From 3f89b3ee390cfefe01833aebe8c83cabf7f6a528 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Tue, 1 Dec 2026 13:25:17 +0900 Subject: [PATCH 16/38] test(agent): check that authentication is decided before the administrator requirement A request that meets both `Unauthenticated` and `AdministratorRequired` is answered with the first. No test sent the policy replacement of a client that is neither authenticated nor an administrator, so a broker that checked the administrator requirement first passed every test. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- crates/now-package-broker/src/v2/routes/tests.rs | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/crates/now-package-broker/src/v2/routes/tests.rs b/crates/now-package-broker/src/v2/routes/tests.rs index 9ecbed210..4954093b9 100644 --- a/crates/now-package-broker/src/v2/routes/tests.rs +++ b/crates/now-package-broker/src/v2/routes/tests.rs @@ -363,6 +363,16 @@ async fn unauthenticated_wins_over_an_oversized_body() { reply.assert_error(401, "Unauthenticated"); } +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §errors +#[tokio::test] +async fn unauthenticated_wins_over_administrator_required() { + let state = Arc::new(unauthenticating_state()); + + let reply = send(&state, &standard_user(), post_json(REPLACE, "{}")).await; + + reply.assert_error(401, "Unauthenticated"); +} + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §authentication #[tokio::test] async fn replacing_the_policy_is_administrator_required_unless_elevated_and_an_administrator() { From 45f2f9fe3bcaa63034fc0fb4bfcfc56a289bc20b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Tue, 1 Dec 2026 13:25:17 +0900 Subject: [PATCH 17/38] test(agent): check the managers the elevated bypass rule leaves out An elevated Install or Update without `Source` is unreadable unless its manager is `Winget` or `Chocolatey`. The only test that told apart a broker that refused those two as well expected the answer the broker gives today for a request without a source name, so it would follow a change of that answer. The new test states what the contract does: such a request is not unreadable. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- .../now-package-broker/src/v2/bypass/reading.rs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/crates/now-package-broker/src/v2/bypass/reading.rs b/crates/now-package-broker/src/v2/bypass/reading.rs index 5b740f0bd..97bff7c6a 100644 --- a/crates/now-package-broker/src/v2/bypass/reading.rs +++ b/crates/now-package-broker/src/v2/bypass/reading.rs @@ -313,6 +313,23 @@ mod tests { } } + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §bypass-reading + #[test] + fn an_elevated_install_or_update_without_source_through_winget_or_chocolatey_is_not_unreadable() { + for manager in ["Winget", "Chocolatey"] { + for operation in ["Install", "Update"] { + let request = request(serde_json::json!({ + "Manager": manager, + "Operation": operation, + "Package": { "Id": "package" }, + "Elevation": "Elevated", + })); + + assert_ne!(read(&request), Reading::Unreadable, "{manager} {operation}"); + } + } + } + // oracle: mutant reading a request that has no source name under a name it does not have, or as unreadable #[test] fn a_request_that_has_no_source_name_is_not_read() { From d7936a9cdf64bb0e9f7d62932e52b88de4f3d01c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Tue, 1 Dec 2026 13:30:35 +0900 Subject: [PATCH 18/38] test(agent): check that a manager capability names at least one operation `Operations` is a non-empty list. Every manager the broker drives has an operation, so no request shows what the capabilities do with one that has none, and a response that listed such a manager with an empty list passed every test. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- .../now-package-broker/src/v2/routes/tests.rs | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/crates/now-package-broker/src/v2/routes/tests.rs b/crates/now-package-broker/src/v2/routes/tests.rs index 4954093b9..2b8eb9539 100644 --- a/crates/now-package-broker/src/v2/routes/tests.rs +++ b/crates/now-package-broker/src/v2/routes/tests.rs @@ -992,6 +992,36 @@ async fn capabilities_name_the_version_the_timeout_and_each_manager_once() { assert_eq!(names, ["Npm", "Winget"], "{reply:?}"); } +// oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §capabilities +#[test] +fn every_manager_capability_names_at_least_one_operation() { + use now_policy_api as v1; + + let capability = |manager, operations| v1::ManagerCapability { + manager, + operations, + scopes: vec![v1::Scope::User], + architectures: vec![v1::Architecture::Neutral], + supports_custom_parameters: false, + supports_custom_install_location: false, + supports_capture_output: true, + supports_details: false, + max_operation_timeout_seconds: None, + }; + + // No manager the broker drives is without an operation today, so no request reaches this case. + let response = super::capabilities::response(vec![ + capability(v1::ManagerName::Npm, vec![v1::Operation::Install]), + capability(v1::ManagerName::Bun, Vec::new()), + ]) + .expect("a capabilities response"); + + let body = serde_json::to_value(&response).expect("a JSON response"); + for manager in body["Managers"].as_array().expect("Managers is a list") { + assert!(!strings(manager, "Operations").is_empty(), "{manager}"); + } +} + /// The opt-ins the capabilities name for each of `managers`, sorted, by the name of the manager. async fn capability_opt_ins( managers: Vec, From 57f0ef21e819478252fed3554827c3ccff933e60 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Tue, 1 Dec 2026 14:02:21 +0900 Subject: [PATCH 19/38] fix(agent): identify the client of a 2.0 bypass event channel as soon as it connects After the channel of a bypass operation refused a connection, its pipe listened during the pause that follows, and a client that connected then was identified only once the pause ended. The process that connected had up to one second to exit and let another process take its id before the broker read that id and opened the process. The channel now identifies a client at once whenever one connects, and after a refusal its pipe listens again only once the pause has passed. A client that opens the pipe during the pause gets a busy pipe. The wait for the end of the channel still wins over the pause and over the listening, and is still one wait for the whole loop. The pause is a parameter of the channel so that tests choose it. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- .../now-package-broker/src/event_channel.rs | 137 +++++++++++++++--- 1 file changed, 116 insertions(+), 21 deletions(-) diff --git a/crates/now-package-broker/src/event_channel.rs b/crates/now-package-broker/src/event_channel.rs index e5a3f5db9..f693a2fd6 100644 --- a/crates/now-package-broker/src/event_channel.rs +++ b/crates/now-package-broker/src/event_channel.rs @@ -576,12 +576,13 @@ mod windows_channel { /// the kernel pipe buffer is full, i.e. the client stopped reading. const WRITE_STALL_TIMEOUT: Duration = Duration::from_secs(30); - /// After the channel refused a connection, how long it waits before it asks whether the client of another one is - /// admitted. + /// After the channel refused a connection, how long it waits before its pipe listens again. /// /// Telling who a client is costs the broker far more than connecting costs a client, so a process that connects in /// a loop would otherwise keep a thread of the broker busy. - /// The pipe listens during the wait: a client that connects then gets its first frame late, not a busy pipe. + /// The pipe does not listen during the wait: a client that opens it then gets a busy pipe, not a late first frame. + /// A pipe that listened would let a client connect up to this long before the channel tells who it is, and the + /// process that connected could be gone by then, with its id given to another process. const REFUSAL_PAUSE: Duration = Duration::from_secs(1); /// How long the channel waits for the read of a refused connection to end once it closed the connection, after @@ -602,8 +603,8 @@ mod windows_channel { FirstConnection, /// The first connection whose client the function admits. /// - /// The channel closes a connection whose client is not admitted without sending a frame on it, and then - /// listens again on the same pipe instance. + /// The channel closes a connection whose client is not admitted without sending a frame on it, and after a + /// pause listens again on the same pipe instance. Admitted(AdmitClient), } @@ -642,6 +643,19 @@ mod windows_channel { version: ChannelVersion, operation_id: &str, client_sid: &Sid, + ) -> anyhow::Result<(OperationEventSink, EventChannel)> { + open_operation_channel_pausing(audience, REFUSAL_PAUSE, version, operation_id, client_sid) + } + + /// Create the event channel for an operation, which waits `refusal_pause` after it refused a connection. + /// + /// It is otherwise [`open_operation_channel_serving`], whose channels wait [`REFUSAL_PAUSE`]. + pub(super) fn open_operation_channel_pausing( + audience: Audience, + refusal_pause: Duration, + version: ChannelVersion, + operation_id: &str, + client_sid: &Sid, ) -> anyhow::Result<(OperationEventSink, EventChannel)> { let sink = OperationEventSink::new(); let pipe_name = operation_pipe_name(operation_id); @@ -675,7 +689,7 @@ mod windows_channel { let writer_sink = sink.clone(); let operation_id = operation_id.to_owned(); tokio::spawn(async move { - run_channel(audience, version, server, writer_sink, &operation_id).await; + run_channel(audience, refusal_pause, version, server, writer_sink, &operation_id).await; }); Ok((sink, descriptor)) @@ -684,6 +698,7 @@ mod windows_channel { /// Serve one client connection on the operation's event pipe, best-effort. async fn run_channel( audience: Audience, + refusal_pause: Duration, version: ChannelVersion, server: NamedPipeServer, sink: OperationEventSink, @@ -691,7 +706,7 @@ mod windows_channel { ) { let connected = match audience { Audience::FirstConnection => accept_first(server, &sink).await, - Audience::Admitted(admit) => accept_admitted(server, &sink, &admit, operation_id).await, + Audience::Admitted(admit) => accept_admitted(server, &sink, &admit, refusal_pause, operation_id).await, }; let Some(mut server) = connected else { debug!(operation_id, "No client connected to the event channel"); @@ -769,19 +784,26 @@ mod windows_channel { /// Waits for the first connection on `server` whose client `admit` admits, and returns the pipe connected to it. /// + /// The channel asks `admit` about a client as soon as that client is connected. + /// After it refused a connection, its pipe listens again once `refusal_pause` has passed. + /// /// Returns `None` when no such client connects before the channel stops waiting for one. async fn accept_admitted( server: NamedPipeServer, sink: &OperationEventSink, admit: &AdmitClient, + refusal_pause: Duration, operation_id: &str, ) -> Option { - // UNTESTED: The channel closes 60 seconds after the status became terminal when no admitted client connected, - // however many connections it refused in that time, and no refused connection closes it earlier. + // UNTESTED: The wait for the end of the channel is one wait for the whole loop: it starts when the status + // becomes terminal, lasts 60 seconds, and no refused connection starts it again. // A wait that started again with each refused connection would let a process that connects in a loop keep the // pipe and the queued output for as long as it likes. - // No test waits 60 seconds; when changing this function, keep one wait for the whole loop, and keep it out of - // the admission of a client that is already connected. + // The loop looks at the wait only where it pauses and where it listens, so a channel whose wait ends while a + // client is being identified closes later, by what is left of that identification and of closing the + // connection it refuses. + // No test waits 60 seconds; when changing this function, keep one wait for the whole loop, and let it win over + // the pause and over the listening. let linger = async { sink.finished().await; tokio::time::sleep(NEVER_CONNECTED_LINGER).await; @@ -789,10 +811,19 @@ mod windows_channel { tokio::pin!(linger); let mut server = server; - let mut refused_before = false; - let mut admit_from = tokio::time::Instant::now(); + // When the pipe listens again, once the channel refused a connection. + let mut listens_from = None; loop { + if let Some(listens_from) = listens_from { + // The pipe accepts no client until it listens. + tokio::select! { + biased; + () = &mut linger => return None, + () = tokio::time::sleep_until(listens_from) => {} + } + } + let connected = tokio::select! { // A client that connects in a loop is always there, and must not keep the wait from ending. biased; @@ -802,15 +833,15 @@ mod windows_channel { if !connected { return None; } - if refused_before { + if listens_from.is_some() { // The pipe still holds what its read for the refused connection ended with. // Taking it makes the pipe read for this connection, which the wait for the served client to close // its end relies on. let _ = server.try_read(&mut [0u8; 1]); } - tokio::time::sleep_until(admit_from).await; - + // The client is identified now: the process that connected may exit, and its id go to another process, + // in any time left between its connection and its identification. let admission = tokio::task::spawn_blocking({ let admit = Arc::clone(admit); move || { @@ -848,8 +879,7 @@ mod windows_channel { ); return None; } - refused_before = true; - admit_from = tokio::time::Instant::now() + REFUSAL_PAUSE; + listens_from = Some(tokio::time::Instant::now() + refusal_pause); } } @@ -1674,10 +1704,26 @@ pub(crate) mod pipe_tests { (sink, descriptor.path) } + /// Opens the channel of a 2.0 operation like [`open_serving`], which waits `refusal_pause` after it refused a + /// connection. + fn open_pausing(audience: Audience, refusal_pause: Duration, tag: &str) -> (OperationEventSink, String) { + let (sink, descriptor) = windows_channel::open_operation_channel_pausing( + audience, + refusal_pause, + ChannelVersion::V2_0, + &test_operation_id(tag), + ¤t_user_sid(), + ) + .expect("open channel"); + + (sink, descriptor.path) + } + + /// What opening a pipe fails with when the pipe has no instance that listens. + const ERROR_PIPE_BUSY: i32 = 231; + /// Opens the event pipe `pipe_name` for reading, once the pipe listens. pub(crate) async fn connect(pipe_name: &str) -> tokio::net::windows::named_pipe::NamedPipeClient { - const ERROR_PIPE_BUSY: i32 = 231; - let path = format!(r"\\.\pipe\{pipe_name}"); let connected = async { loop { @@ -1686,7 +1732,7 @@ pub(crate) mod pipe_tests { .open(&path) { Ok(client) => return client, - // The pipe has one instance, which is taking its previous client off. + // The pipe has one instance, which serves another client or does not listen yet. Err(error) if error.raw_os_error() == Some(ERROR_PIPE_BUSY) => { tokio::time::sleep(Duration::from_millis(10)).await; } @@ -1769,4 +1815,53 @@ pub(crate) mod pipe_tests { assert_eq!(frames, [HELLO_2_0, EventFrame::Finish]); assert!(closed.is_err(), "the channel closed its end first: {closed:?}"); } + + // oracle: mutant listening on the pipe during the pause after a refusal, so that a client connects long before the channel identifies it + #[tokio::test] + async fn the_pipe_of_a_channel_is_busy_during_the_pause_after_a_refusal() { + // The pause does not end while the test runs. + let (_sink, pipe_name) = open_pausing(admitting(&[false]), Duration::from_secs(600), "busy"); + bytes_of_a_closed_connection(&pipe_name).await; + + let path = format!(r"\\.\pipe\{pipe_name}"); + for _ in 0..20 { + let error = tokio::net::windows::named_pipe::ClientOptions::new() + .write(false) + .open(&path) + .expect_err("the pipe listens during the pause"); + assert_eq!(error.raw_os_error(), Some(ERROR_PIPE_BUSY), "{error}"); + tokio::time::sleep(Duration::from_millis(10)).await; + } + } + + // oracle: mutant identifying the client of a connection less than one pause after it refused another + #[tokio::test] + async fn the_channel_identifies_no_client_within_one_pause_of_a_refusal() { + const PAUSE: Duration = Duration::from_millis(300); + + let identified = Arc::new(Mutex::new(Vec::new())); + let audience = Audience::Admitted(Arc::new({ + let identified = Arc::clone(&identified); + move |_pipe| { + let mut identified = identified.lock().expect("no identification panics"); + identified.push(std::time::Instant::now()); + // The first client is refused, and the second one admitted. + identified.len() == 2 + } + })); + let (sink, pipe_name) = open_pausing(audience, PAUSE, "pause"); + sink.finish(); + + bytes_of_a_closed_connection(&pipe_name).await; + let frames = read_frames(&mut connect(&pipe_name).await).await; + + let identified = identified.lock().expect("no identification panics"); + assert_eq!(frames, [HELLO_2_0, EventFrame::Finish]); + let [first, second] = identified[..] else { + panic!("the channel identified {} clients", identified.len()); + }; + // The channel refused the first client after it identified it. + let apart = second.duration_since(first); + assert!(PAUSE <= apart, "the identifications are {apart:?} apart"); + } } From cb0e49e8842abeecffe184b2cc5fa9053a570b54 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Tue, 1 Dec 2026 14:04:51 +0900 Subject: [PATCH 20/38] fix(agent): close the queue of a 2.0 bypass event channel that gives its pipe up A channel that could no longer tell who its pipe was connected to (the identification of a client panicked, the pipe failed to listen or to close a refused connection, or the read of that connection did not end) closed its pipe, logged that no client connected, and left its queue open. The queue then went on taking output that nobody would read. Such a channel now closes its queue, and the broker logs the failure for what it is, as a warning that names its cause. A channel to which no admitted client connected before its end keeps its behaviour and its log line. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- .../now-package-broker/src/event_channel.rs | 125 +++++++++++++----- 1 file changed, 91 insertions(+), 34 deletions(-) diff --git a/crates/now-package-broker/src/event_channel.rs b/crates/now-package-broker/src/event_channel.rs index f693a2fd6..251979afb 100644 --- a/crates/now-package-broker/src/event_channel.rs +++ b/crates/now-package-broker/src/event_channel.rs @@ -552,7 +552,7 @@ mod windows_channel { use now_policy_api::{EventChannel, EventChannelKind}; use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _}; use tokio::net::windows::named_pipe::{NamedPipeServer, ServerOptions}; - use tracing::debug; + use tracing::{debug, warn}; use win_api_wrappers::identity::sid::Sid; use win_api_wrappers::security::acl::{Acl, ExplicitAccess, InheritableAcl, InheritableAclKind, Trustee}; use win_api_wrappers::security::attributes::SecurityAttributesInit; @@ -592,6 +592,7 @@ mod windows_channel { /// Tells whether the client of a connected event pipe is one the channel sends its frames to. /// /// The channel calls it off the async runtime, so it may block. + /// A channel in which it panics serves nobody. pub type AdmitClient = Arc bool + Send + Sync>; /// The connections an event channel sends its frames on ([§event-channel]). @@ -705,12 +706,25 @@ mod windows_channel { operation_id: &str, ) { let connected = match audience { - Audience::FirstConnection => accept_first(server, &sink).await, + Audience::FirstConnection => Ok(accept_first(server, &sink).await), Audience::Admitted(admit) => accept_admitted(server, &sink, &admit, refusal_pause, operation_id).await, }; - let Some(mut server) = connected else { - debug!(operation_id, "No client connected to the event channel"); - return; + let mut server = match connected { + Ok(Some(server)) => server, + Ok(None) => { + debug!(operation_id, "No client connected to the event channel"); + return; + } + Err(error) => { + // Nobody will read the queue, so it takes no more output. + sink.abandon(); + warn!( + operation_id, + error = format!("{error:#}"), + "Event channel failed before it served a client, continuing without streaming" + ); + return; + } }; debug!(operation_id, "Client connected to the event channel"); @@ -787,14 +801,16 @@ mod windows_channel { /// The channel asks `admit` about a client as soon as that client is connected. /// After it refused a connection, its pipe listens again once `refusal_pause` has passed. /// - /// Returns `None` when no such client connects before the channel stops waiting for one. + /// Returns `Ok(None)` when no such client connects before the channel stops waiting for one. + /// Returns an error when the channel can no longer tell who its pipe is connected to: the pipe is then closed, + /// and the channel serves nobody. async fn accept_admitted( server: NamedPipeServer, sink: &OperationEventSink, admit: &AdmitClient, refusal_pause: Duration, operation_id: &str, - ) -> Option { + ) -> anyhow::Result> { // UNTESTED: The wait for the end of the channel is one wait for the whole loop: it starts when the status // becomes terminal, lasts 60 seconds, and no refused connection starts it again. // A wait that started again with each refused connection would let a process that connects in a loop keep the @@ -819,7 +835,7 @@ mod windows_channel { // The pipe accepts no client until it listens. tokio::select! { biased; - () = &mut linger => return None, + () = &mut linger => return Ok(None), () = tokio::time::sleep_until(listens_from) => {} } } @@ -827,12 +843,17 @@ mod windows_channel { let connected = tokio::select! { // A client that connects in a loop is always there, and must not keep the wait from ending. biased; - () = &mut linger => false, - result = server.connect() => result.is_ok(), + () = &mut linger => return Ok(None), + connected = server.connect() => connected, }; - if !connected { - return None; - } + // UNTESTED: A channel that fails to listen, to close a connection it refused, or to see the read of that + // connection end, serves nobody and gives its pipe up: each of the three returns its error at once, which + // drops the pipe, and the caller closes the queue. + // After any of them the channel no longer knows who its pipe is connected to, and the frames it would + // write next could reach a client it refused. + // No test makes a pipe fail in these ways; when changing this function, check that none of the three + // exits listens again or returns the pipe. + connected.context("failed to listen on the event pipe")?; if listens_from.is_some() { // The pipe still holds what its read for the refused connection ended with. // Taking it makes the pipe read for this connection, which the wait for the served client to close @@ -850,34 +871,28 @@ mod windows_channel { } }); let admitted; - (server, admitted) = match admission.await { - Ok(admission) => admission, - Err(error) => { - debug!(operation_id, %error, "Failed to tell whether the event channel admits a client"); - return None; - } - }; + // An identification that panics drops the pipe with its task, so the channel serves nobody. + (server, admitted) = admission + .await + .context("failed to tell whether the event channel admits a client")?; if admitted { - return Some(server); + return Ok(Some(server)); } debug!(operation_id, "Refused a connection to the event channel"); // The same instance listens again: the pipe never has a second one. - if let Err(error) = server.disconnect() { - debug!(operation_id, %error, "Failed to close a refused connection to the event channel"); - return None; - } + server + .disconnect() + .context("failed to close a refused connection to the event channel")?; // The pipe started a read when the client connected, which the disconnection ends. // Its end is awaited here, so that it is not taken for something the next client did. - let read = tokio::time::timeout(REFUSED_READ_TIMEOUT, server.read(&mut [0u8; 1])).await; - if !matches!(read, Ok(Ok(0) | Err(_))) { - // A client has no write access to the pipe, and a disconnection ends a read at once. - debug!( - operation_id, - ?read, - "Failed to end the read of a refused connection to the event channel" - ); - return None; + // A client has no write access to the pipe, and a disconnection ends a read at once. + match tokio::time::timeout(REFUSED_READ_TIMEOUT, server.read(&mut [0u8; 1])).await { + Ok(Ok(0) | Err(_)) => {} + Ok(Ok(_)) => anyhow::bail!("a refused connection to the event channel sent bytes"), + Err(_) => anyhow::bail!( + "the read of a refused connection to the event channel did not end within {REFUSED_READ_TIMEOUT:?}" + ), } listens_from = Some(tokio::time::Instant::now() + refusal_pause); } @@ -1864,4 +1879,46 @@ pub(crate) mod pipe_tests { let apart = second.duration_since(first); assert!(PAUSE <= apart, "the identifications are {apart:?} apart"); } + + /// Waits until the event pipe `pipe_name` no longer exists. + async fn pipe_is_gone(pipe_name: &str) { + const ERROR_FILE_NOT_FOUND: i32 = 2; + + let path = format!(r"\\.\pipe\{pipe_name}"); + let gone = async { + loop { + match tokio::net::windows::named_pipe::ClientOptions::new() + .write(false) + .open(&path) + { + Ok(_) => panic!("the pipe listens"), + Err(error) if error.raw_os_error() == Some(ERROR_FILE_NOT_FOUND) => return, + // The last handle of the pipe is not closed yet. + Err(_) => tokio::time::sleep(Duration::from_millis(10)).await, + } + } + }; + + tokio::time::timeout(Duration::from_secs(10), gone) + .await + .expect("the channel gives its pipe up"); + } + + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §event-channel + #[tokio::test] + async fn a_channel_whose_identification_of_a_client_panics_sends_no_frame_and_gives_its_pipe_up() { + let audience = Audience::Admitted(Arc::new(|_pipe| panic!("the identification fails"))); + let (sink, pipe_name) = open_serving(audience, "panic"); + sink.stdout(b"output"); + + let received = bytes_of_a_closed_connection(&pipe_name).await; + pipe_is_gone(&pipe_name).await; + let queue_closed = tokio::time::timeout(Duration::from_secs(10), sink.finished()).await; + sink.stdout(b"more output"); + + assert_eq!(received, [0u8; 0]); + // oracle: mutant leaving open the queue of a channel that serves nobody, which goes on taking output that nobody reads + queue_closed.expect("the channel left its queue open"); + assert_eq!(sink.next_frame().await, None); + } } From 3eed0962090a6dcafc51c088f087c2a4e4ad9edf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Tue, 1 Dec 2026 14:05:21 +0900 Subject: [PATCH 21/38] docs(agent): say what two comments on a 2.0 bypass operation can claim The test of a refused connection said that the pipe allows no other instance. Creating an instance fails there because the access control of the pipe gives the user of the test no right to create one, whatever the number of instances the pipe allows: the probe shows that the channel kept its pipe, which its comment and its message now say. The bypass route said that a start that panics holds no operation. That holds for a panic before the registry takes the operation only; after it, the registry holds an operation whose token is not used up. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- crates/now-package-broker/src/event_channel.rs | 7 +++++-- crates/now-package-broker/src/v2/routes/bypass.rs | 4 +++- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/crates/now-package-broker/src/event_channel.rs b/crates/now-package-broker/src/event_channel.rs index 251979afb..b1db732a9 100644 --- a/crates/now-package-broker/src/event_channel.rs +++ b/crates/now-package-broker/src/event_channel.rs @@ -1803,10 +1803,13 @@ pub(crate) mod pipe_tests { for _ in 0..2 { let received = bytes_of_a_closed_connection(&pipe_name).await; assert_eq!(received, [0u8; 0]); - // The pipe of the channel allows no other instance. + // The channel kept its pipe to refuse the connection: the access control of the pipe gives the user of + // the test no right to create an instance of it, however many instances it allows, so creating one + // fails for as long as the pipe exists. + // It would succeed after a channel closed its pipe, until that channel created another. tokio::net::windows::named_pipe::ServerOptions::new() .create(format!(r"\\.\pipe\{pipe_name}")) - .expect_err("the pipe got a second instance"); + .expect_err("the channel closed its pipe to refuse the connection"); } let frames = read_frames(&mut connect(&pipe_name).await).await; diff --git a/crates/now-package-broker/src/v2/routes/bypass.rs b/crates/now-package-broker/src/v2/routes/bypass.rs index 441cfb8ce..ee0dbdad1 100644 --- a/crates/now-package-broker/src/v2/routes/bypass.rs +++ b/crates/now-package-broker/src/v2/routes/bypass.rs @@ -92,7 +92,9 @@ impl Connection { .bypasses .start(&caller, &token_name, request.clone(), &package_request, ()); // The broker holds the operation of the token now, so the token is used up. - // A start that panics holds no operation and never gets here: the token then still authorizes the request. + // A start that panics never gets here, so its token still authorizes the request. + // It holds no operation when it panics before its registry takes the operation. + // When it panics after that, the registry holds an operation whose token is not used up. tokens.use_up(&token); match start { From bb80ec74cb846b21b91da439e8df050661fcdb28 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Tue, 1 Dec 2026 14:49:22 +0900 Subject: [PATCH 22/38] docs(agent): state the untested properties of a 2.0 bypass event channel as the code keeps them The comment on the wait for the end of the channel said its 60 seconds start when the status becomes terminal. They start the first time the loop looks at the wait after that, which is later when a client is being identified or refused at that moment. That a client is handed to its identification as soon as it connects is the reason the pause comes before the listening, and no test bounds the time between the two, so the comment there now says what to keep when the function changes. The exit for a refused connection that sent bytes was missing from the comment on the exits no test reaches, and the comment on the token lock did not name the start that panics once its registry took the operation. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- .../now-package-broker/src/event_channel.rs | 31 ++++++++++++------- .../src/v2/routes/bypass.rs | 3 +- 2 files changed, 21 insertions(+), 13 deletions(-) diff --git a/crates/now-package-broker/src/event_channel.rs b/crates/now-package-broker/src/event_channel.rs index b1db732a9..fc431a415 100644 --- a/crates/now-package-broker/src/event_channel.rs +++ b/crates/now-package-broker/src/event_channel.rs @@ -811,13 +811,15 @@ mod windows_channel { refusal_pause: Duration, operation_id: &str, ) -> anyhow::Result> { - // UNTESTED: The wait for the end of the channel is one wait for the whole loop: it starts when the status - // becomes terminal, lasts 60 seconds, and no refused connection starts it again. + // UNTESTED: The wait for the end of the channel is one wait for the whole loop: its 60 seconds start the first + // time the loop looks at the wait once the status is terminal, and no refused connection starts them again. // A wait that started again with each refused connection would let a process that connects in a loop keep the // pipe and the queued output for as long as it likes. - // The loop looks at the wait only where it pauses and where it listens, so a channel whose wait ends while a - // client is being identified closes later, by what is left of that identification and of closing the - // connection it refuses. + // The loop looks at the wait only where it pauses and where it listens. + // A status that becomes terminal while the channel identifies a client it then refuses, or closes the + // connection of that client, therefore starts the 60 seconds once that is over, and a wait that ends at such + // a time closes the channel once that is over. + // The start is late once at most, and the end is late once at most, whatever the clients do. // No test waits 60 seconds; when changing this function, keep one wait for the whole loop, and let it win over // the pause and over the listening. let linger = async { @@ -847,22 +849,27 @@ mod windows_channel { connected = server.connect() => connected, }; // UNTESTED: A channel that fails to listen, to close a connection it refused, or to see the read of that - // connection end, serves nobody and gives its pipe up: each of the three returns its error at once, which - // drops the pipe, and the caller closes the queue. + // connection end with nothing read, serves nobody and gives its pipe up: each of these exits returns its + // error at once, which drops the pipe, and the caller closes the queue. // After any of them the channel no longer knows who its pipe is connected to, and the frames it would // write next could reach a client it refused. - // No test makes a pipe fail in these ways; when changing this function, check that none of the three - // exits listens again or returns the pipe. + // No test makes a pipe fail in these ways; when changing this function, check that none of these exits + // listens again or returns the pipe. connected.context("failed to listen on the event pipe")?; if listens_from.is_some() { - // The pipe still holds what its read for the refused connection ended with. + // The pipe still holds the result of a read it started while no client was connected. // Taking it makes the pipe read for this connection, which the wait for the served client to close // its end relies on. let _ = server.try_read(&mut [0u8; 1]); } - // The client is identified now: the process that connected may exit, and its id go to another process, - // in any time left between its connection and its identification. + // UNTESTED: The channel hands a client to its identification as soon as the client is connected: this + // function awaits nothing between the two, and the identification starts when a thread of the blocking + // pool takes it. + // In any time left between them, the process that connected may exit and its id go to another process, + // which the channel would then identify in its place. + // No test bounds that time; when changing this function, keep every wait, the pause after a refusal + // included, out of the lines between the connection and this call. let admission = tokio::task::spawn_blocking({ let admit = Arc::clone(admit); move || { diff --git a/crates/now-package-broker/src/v2/routes/bypass.rs b/crates/now-package-broker/src/v2/routes/bypass.rs index ee0dbdad1..aa1f7f508 100644 --- a/crates/now-package-broker/src/v2/routes/bypass.rs +++ b/crates/now-package-broker/src/v2/routes/bypass.rs @@ -30,7 +30,8 @@ impl Connection { let token_name = token.to_hex(); // UNTESTED: Another request finds either the token held and no operation started with it, or the token used - // up and the operation it started held, and never anything in between. + // up and the operation it started held, and nothing in between unless the start panics once its registry + // took the operation. // Were the token used up before the operation is held, of two equal requests that arrive together, the second // could be answered `BypassTokenRejected` while the first starts the operation, where the contract has it get // that operation. From 653829620cdb7fd75831a7ea5d51a738b62d95df Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Wed, 2 Dec 2026 04:01:20 +0900 Subject: [PATCH 23/38] feat(agent): read a 2.0 bypass request without a source as the contract reads it A bypass request that names no source is read by the evaluator, which gives it the only source name of its manager where the manager has one and leaves it without a source elsewhere. Its operation runs for the request with that source, so a request that leaves the choice of source to its manager is no longer answered with an internal error. The broker keeps no reading of its own: the cases that make a request unreadable are the evaluator's, including those that test members other than the source name. A request the evaluator refuses once the broker read it is answered with an internal error before anything starts, so its token stays unused. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- .../src/v2/bypass/reading.rs | 309 ++++++++++-------- .../src/v2/routes/bypass.rs | 9 +- .../now-package-broker/src/v2/routes/tests.rs | 127 ++++++- .../now-package-broker/src/v2/wire/convert.rs | 147 +++++---- crates/now-package-broker/src/v2/wire/mod.rs | 2 +- 5 files changed, 378 insertions(+), 216 deletions(-) diff --git a/crates/now-package-broker/src/v2/bypass/reading.rs b/crates/now-package-broker/src/v2/bypass/reading.rs index 2cd975272..30a7580eb 100644 --- a/crates/now-package-broker/src/v2/bypass/reading.rs +++ b/crates/now-package-broker/src/v2/bypass/reading.rs @@ -3,8 +3,6 @@ //! [§bypass]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#bypass //! [§bypass-reading]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#bypass-reading -use std::sync::LazyLock; - use now_policy_api::v2; use now_policy_eval as eval; use uuid::Uuid; @@ -16,112 +14,34 @@ use crate::v2::wire; /// [§bypass-reading]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#bypass-reading #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) enum Reading { - /// The request is readable, and its operation runs the command of this package request. + /// The request is readable, and its operation runs for this request. + /// + /// It has the members of the bypass request and the `Source.Name` the reading gives it, which is none where the + /// request leaves the choice of source to its manager. Readable(Box), /// The request is unreadable. Unreadable, - /// The broker cannot tell whether the request is readable, for the reason given, and runs nothing for it. - NotRead(&'static str), } /// Reads a bypass request ([§bypass-reading]). /// -/// A request with a `Source.Name`, its own or the only one of its manager, is read as the package request with the -/// same members. -/// A request without one is not read, apart from the elevated ones that are unreadable whatever their other members: -/// the reading the broker has takes a package request, which always has a `Source.Name`, and reading such a request -/// under a name it does not have would apply the cases that test `Source.Name` to it. +/// Fails for a request that is not a well-formed bypass request ([§bypass]), which no body the broker reads as a +/// bypass request is. /// +/// [§bypass]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#bypass /// [§bypass-reading]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#bypass-reading -pub(crate) fn read(request: &v2::BypassRequest) -> Reading { - let listed_source = if request.source.is_none() { - // A run as administrator uses only sources from machine-wide configuration, and only an administrator can - // change the sources these two managers are configured with. - if request.operation != v2::Operation::Uninstall - && request.elevation == v2::Elevation::Elevated - && !matches!(request.manager, v2::Manager::Winget | v2::Manager::Chocolatey) - { - return Reading::Unreadable; - } +pub(crate) fn read(request: &v2::BypassRequest) -> Result { + let mut read_as = wire::evaluator_bypass_request(request); - match only_source_name(request.manager, request.operation).map(v2::SourceName::parse) { - Some(Ok(name)) => Some(name), - Some(Err(_)) => return Reading::NotRead("the only source name of the manager is not a source name"), - None => None, + match eval::read_bypass(&read_as)? { + eval::BypassReading::Readable { source } => { + read_as.source = source; + Ok(Reading::Readable(Box::new(read_as))) } - } else { - None - }; - - let Some(package_request) = wire::bypass_package_request(request, listed_source.as_ref()) else { - return Reading::NotRead("the broker does not read a request that has no source name"); - }; - let package_request = wire::evaluator_request(&package_request); - - match is_unreadable(&package_request) { - Some(true) => Reading::Unreadable, - Some(false) => Reading::Readable(Box::new(package_request)), - None => Reading::NotRead("the evaluator did not read the package request"), - } -} - -/// Returns the only source name the reading of `manager` names for `operation`, if it names one ([§managers]). -/// -/// [§managers]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.policy.md#managers -fn only_source_name(manager: v2::Manager, operation: v2::Operation) -> Option<&'static str> { - match manager { - v2::Manager::Npm => Some("npm"), - v2::Manager::Bun => Some("Bun"), - v2::Manager::Cargo => Some("crates.io"), - v2::Manager::Pip => Some("pip"), - // An Uninstall through Dotnet has no only source name. - v2::Manager::Dotnet => (operation != v2::Operation::Uninstall).then_some("nuget.org"), - v2::Manager::Winget - | v2::Manager::PowerShell - | v2::Manager::PowerShell7 - | v2::Manager::Apt - | v2::Manager::Chocolatey - | v2::Manager::Dnf - | v2::Manager::Flatpak - | v2::Manager::Homebrew - | v2::Manager::Pacman - | v2::Manager::Scoop - | v2::Manager::Snap - | v2::Manager::Vcpkg => None, + eval::BypassReading::Unreadable => Ok(Reading::Unreadable), } } -/// A valid policy, which plays no part in what [`is_unreadable`] returns. -const ANY_POLICY: &str = r#"{ - "PolicyFormatVersion": "2.0.0", - "Metadata": { "Id": "bypass-reading", "Publisher": "Devolutions", "Revision": 1, "PublishedAt": "2026-01-01T00:00:00Z" }, - "TrustedSources": [], - "Rules": [] -}"#; - -/// A time at which [`ANY_POLICY`] is evaluated, which plays no part in what [`is_unreadable`] returns either. -const ANY_TIME: &str = "2026-01-01T00:00:00Z"; - -/// Tells whether `request` is unreadable ([CONTRACT.policy.md §reading]), or `None` when the evaluator does not say. -/// -/// This stands in for a reading function, which the evaluator does not export: the only way to ask it whether a -/// request is unreadable is to evaluate the request and look at the check of the decision. -/// A bypass request is not evaluated against any policy, and this does not make it so: `UnreadableRequest` is the -/// first check of every evaluation ([§precedence]), decided from the request alone, so the policy and the time given -/// here change nothing of the answer, and nothing else of the decision is looked at. -/// -/// [CONTRACT.policy.md §reading]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.policy.md#reading -/// [§precedence]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.policy.md#precedence -fn is_unreadable(request: &eval::Request) -> Option { - static POLICY: LazyLock> = - LazyLock::new(|| Some((eval::parse_policy(ANY_POLICY.as_bytes()).ok()?, ANY_TIME.parse().ok()?))); - - let (policy, time) = POLICY.as_ref()?; - let decision = eval::evaluate(policy, request, *time).ok()?; - - Some(decision.check == eval::Check::UnreadableRequest) -} - /// Tells whether an Uninstall through `manager` of `package_id` names Devolutions Agent ([§bypass]). /// /// `agent_product_code` is the product code of the installed Devolutions Agent, when one is installed. @@ -174,16 +94,19 @@ mod tests { wire::read_bypass_request(body.to_string().as_bytes()).expect("a bypass request") } - /// The `Source.Name` of the package request that `request` is read as. - fn read_source_name(request: &v2::BypassRequest) -> String { + /// The request the operation of `request` runs for. + fn readable(request: &v2::BypassRequest) -> eval::Request { match read(request) { - Reading::Readable(package_request) => { - package_request.source.map(|source| source.name).expect("a source name") - } + Ok(Reading::Readable(read)) => *read, other => panic!("the request is not readable: {other:?}"), } } + /// The `Source.Name` the reading of `request` gives it, if it gives one. + fn read_source_name(request: &v2::BypassRequest) -> Option { + readable(request).source.map(|source| source.name) + } + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §bypass-reading #[test] fn a_request_with_source_is_read_as_the_package_request_with_the_same_members() { @@ -196,9 +119,7 @@ mod tests { "Elevation": "Elevated", })); - let Reading::Readable(read) = read(&request) else { - panic!("the request is not readable"); - }; + let read = readable(&request); assert_eq!(read.operation, eval::Operation::Update); assert_eq!(read.manager, eval::Manager::Chocolatey); @@ -238,7 +159,7 @@ mod tests { ]; for (case, members) in cases { - assert_eq!(read(&request(members)), Reading::Unreadable, "{case}"); + assert_eq!(read(&request(members)), Ok(Reading::Unreadable), "{case}"); } } @@ -267,7 +188,123 @@ mod tests { "Package": { "Id": package_id }, })); - assert_eq!(read_source_name(&request), source_name, "{manager} {operation}"); + assert_eq!( + read_source_name(&request).as_deref(), + Some(source_name), + "{manager} {operation}" + ); + } + } + + // oracle: contract Devolutions/now-libraries@3014fcbb899d:policies/CONTRACT.wire.md §bypass-reading + // An Uninstall through Dotnet has no only source name (CONTRACT.policy.md §manager-dotnet). + #[test] + fn a_request_without_source_whose_manager_names_no_only_source_name_is_read_without_one() { + let cases = [ + ("Winget", "Install", "Git.Git", "NonElevated"), + ("Winget", "Update", "Git.Git", "Elevated"), + ("Winget", "Uninstall", "Git.Git", "NonElevated"), + ("Chocolatey", "Install", "git", "Elevated"), + ("Chocolatey", "Uninstall", "git", "Elevated"), + ("PowerShell", "Install", "Pester", "NonElevated"), + ("PowerShell", "Uninstall", "Pester", "Elevated"), + ("PowerShell7", "Update", "Pester", "NonElevated"), + ("Dotnet", "Uninstall", "dotnet-ef", "NonElevated"), + ("Scoop", "Install", "git", "NonElevated"), + ("Scoop", "Uninstall", "git", "NonElevated"), + ("Vcpkg", "Install", "zlib", "NonElevated"), + ("Vcpkg", "Uninstall", "zlib:x64-windows", "NonElevated"), + ]; + + for (manager, operation, package_id, elevation) in cases { + let request = request(serde_json::json!({ + "Manager": manager, + "Operation": operation, + "Package": { "Id": package_id }, + "Elevation": elevation, + })); + + assert_eq!(read_source_name(&request), None, "{manager} {operation}"); + } + } + + // oracle: contract Devolutions/now-libraries@3014fcbb899d:policies/CONTRACT.wire.md §bypass-reading + #[test] + fn a_request_without_source_runs_for_its_own_members() { + let request = request(serde_json::json!({ + "Operation": "Update", + "Manager": "Winget", + "Package": { "Id": "Git.Git", "Version": "2.45.1" }, + "Scope": "Machine", + "Elevation": "Elevated", + "OptIns": { "NoUpgrade": {} }, + })); + + assert_eq!( + readable(&request), + eval::Request { + operation: eval::Operation::Update, + manager: eval::Manager::Winget, + source: None, + package: eval::Package { + id: "Git.Git".to_owned(), + version: Some("2.45.1".to_owned()), + architecture: None, + }, + scope: Some(eval::Scope::Machine), + elevation: eval::Elevation::Elevated, + opt_ins: eval::OptIns { + no_upgrade: true, + ..eval::OptIns::default() + }, + } + ); + } + + // oracle: contract Devolutions/now-libraries@3014fcbb899d:policies/CONTRACT.wire.md §bypass-reading + #[test] + fn a_scoop_request_without_source_whose_id_names_one_app_is_readable() { + // Two `.` in a row are not three, and `.jsonl` is not `.json`. + for package_id in ["git", "7zip", "My_App-2", "a.b", "a..b", "app.jsonl"] { + let request = request(serde_json::json!({ "Manager": "Scoop", "Package": { "Id": package_id } })); + + assert_eq!(read_source_name(&request), None, "{package_id}"); + } + } + + // oracle: contract Devolutions/now-libraries@3014fcbb899d:policies/CONTRACT.wire.md §bypass-reading + #[test] + fn a_scoop_request_without_source_whose_id_may_name_anything_else_is_unreadable() { + let cases = [ + ("Install", "main/git"), + ("Install", "git@2.45.1"), + ("Install", "a...b"), + ("Install", "git."), + ("Install", "app.json"), + ("Install", "App.JSON"), + ("Update", "main/git"), + ("Uninstall", "app.json"), + ]; + + for (operation, package_id) in cases { + let request = request(serde_json::json!({ + "Manager": "Scoop", + "Operation": operation, + "Package": { "Id": package_id }, + })); + + assert_eq!(read(&request), Ok(Reading::Unreadable), "{operation} {package_id}"); + } + } + + // oracle: contract Devolutions/now-libraries@3014fcbb899d:policies/CONTRACT.wire.md §bypass-reading + // A port spec is that of CONTRACT.policy.md §manager-vcpkg. + #[test] + fn a_vcpkg_request_without_source_is_read_by_its_port_spec_alone() { + for package_id in ["zlib", "zlib:x64-windows", "zlib[core,tools]:arm64-windows"] { + let request = request(serde_json::json!({ "Manager": "Vcpkg", "Package": { "Id": package_id } })); + + assert_eq!(read_source_name(&request), None, "{package_id}"); } } @@ -277,7 +314,27 @@ mod tests { // The identifier is neither a registry name nor an alias. let request = request(serde_json::json!({ "Manager": "Npm", "Package": { "Id": "-left-pad" } })); - assert_eq!(read(&request), Reading::Unreadable); + assert_eq!(read(&request), Ok(Reading::Unreadable)); + } + + // oracle: contract Devolutions/now-libraries@3014fcbb899d:policies/CONTRACT.wire.md §bypass-reading + // Each case of a reading named here joins a test of `Source.Name` and a test of `Package.Id` with "or". + #[test] + fn a_request_without_source_is_unreadable_by_the_other_members_of_a_case_that_also_tests_the_source_name() { + let cases = [ + // CONTRACT.policy.md §manager-vcpkg: the id is not a port spec, or its triplet differs from `Source.Name`. + ("Vcpkg", "Zlib"), + ("Vcpkg", "zlib:"), + // CONTRACT.policy.md §manager-powershell: the source name is not plain, or the id contains `[` or `]`. + ("PowerShell", "Pester[1]"), + ("PowerShell7", "Pester]"), + ]; + + for (manager, package_id) in cases { + let request = request(serde_json::json!({ "Manager": manager, "Package": { "Id": package_id } })); + + assert_eq!(read(&request), Ok(Reading::Unreadable), "{manager} {package_id}"); + } } // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §bypass-reading @@ -310,7 +367,7 @@ mod tests { "Elevation": "Elevated", })); - assert_eq!(read(&request), Reading::Unreadable, "{manager} {operation}"); + assert_eq!(read(&request), Ok(Reading::Unreadable), "{manager} {operation}"); } } } @@ -327,45 +384,19 @@ mod tests { "Elevation": "Elevated", })); - assert_ne!(read(&request), Reading::Unreadable, "{manager} {operation}"); + assert_ne!(read(&request), Ok(Reading::Unreadable), "{manager} {operation}"); } } } - // oracle: mutant reading a request that has no source name under a name it does not have, or as unreadable + // oracle: contract Devolutions/now-libraries@3014fcbb899d:policies/CONTRACT.wire.md §bypass #[test] - fn a_request_that_has_no_source_name_is_not_read() { - let cases = [ - ("Winget", "Install", "NonElevated"), - ("Winget", "Update", "Elevated"), - ("Winget", "Uninstall", "NonElevated"), - ("Chocolatey", "Install", "Elevated"), - ("Chocolatey", "Uninstall", "Elevated"), - ("PowerShell", "Install", "NonElevated"), - ("PowerShell", "Uninstall", "Elevated"), - ("PowerShell7", "Update", "NonElevated"), - ("Dotnet", "Uninstall", "NonElevated"), - ("Scoop", "Install", "NonElevated"), - ("Scoop", "Uninstall", "NonElevated"), - ("Vcpkg", "Install", "NonElevated"), - ("Vcpkg", "Uninstall", "NonElevated"), - ]; - - for (manager, operation, elevation) in cases { - let request = request(serde_json::json!({ - "Manager": manager, - "Operation": operation, - "Package": { "Id": "package" }, - "Elevation": elevation, - })); - - let reading = read(&request); + fn a_request_that_is_not_a_well_formed_bypass_request_is_not_read() { + // No body is read as an Uninstall with `Source`. + let mut uninstall_with_source = request(serde_json::json!({ "Source": { "Name": "winget" } })); + uninstall_with_source.operation = v2::Operation::Uninstall; - assert!( - matches!(reading, Reading::NotRead(_)), - "{manager} {operation}: {reading:?}" - ); - } + assert_eq!(read(&uninstall_with_source), Err(eval::BadRequest)); } const PRODUCT_CODE: &str = "0f2a6b3c-4d5e-4f60-8a9b-0c1d2e3f4a5b"; diff --git a/crates/now-package-broker/src/v2/routes/bypass.rs b/crates/now-package-broker/src/v2/routes/bypass.rs index aa1f7f508..5a2f896a5 100644 --- a/crates/now-package-broker/src/v2/routes/bypass.rs +++ b/crates/now-package-broker/src/v2/routes/bypass.rs @@ -78,15 +78,18 @@ impl Connection { } let package_request = match read(request) { - Reading::Readable(package_request) => package_request, - Reading::Unreadable => { + Ok(Reading::Readable(package_request)) => package_request, + Ok(Reading::Unreadable) => { return error_response( v2::ErrorCode::BypassRequestUnreadable, "the bypass request is unreadable", ); } + // The broker read the request as well-formed, so the evaluator that refuses it reads the contract another + // way than the broker does. + // `BadRequest` wins over every outcome decided above, so it is no answer here. // Nothing starts, so the token is not used up. - Reading::NotRead(reason) => return internal_error(&reason), + Err(error) => return internal_error(&error), }; let start = registries diff --git a/crates/now-package-broker/src/v2/routes/tests.rs b/crates/now-package-broker/src/v2/routes/tests.rs index 2b8eb9539..bf0f8728d 100644 --- a/crates/now-package-broker/src/v2/routes/tests.rs +++ b/crates/now-package-broker/src/v2/routes/tests.rs @@ -3098,18 +3098,131 @@ async fn bypass_requests_with_one_token_that_arrive_together_start_one_operation assert_eq!(broker.runs().await, 1); } -// oracle: mutant using up the token of a request without a source name that the broker does not read, or running a -// command for it +// oracle: contract Devolutions/now-libraries@3014fcbb899d:policies/CONTRACT.wire.md §bypass-reading #[tokio::test] -async fn a_bypass_request_the_broker_does_not_read_is_internal_error_and_keeps_its_token() { +async fn a_readable_bypass_request_without_source_starts_an_operation() { + let cases = [ + ( + "an install through WinGet", + serde_json::json!({ "Manager": "Winget", "Package": { "Id": "Git.Git" } }), + ), + ( + "an elevated update through WinGet", + serde_json::json!({ "Operation": "Update", "Manager": "Winget", "Elevation": "Elevated" }), + ), + ( + "an elevated install through Chocolatey", + serde_json::json!({ "Manager": "Chocolatey", "Package": { "Id": "git" }, "Elevation": "Elevated" }), + ), + ( + "an install through PowerShell", + serde_json::json!({ "Manager": "PowerShell", "Package": { "Id": "Pester" } }), + ), + ( + "an elevated uninstall through PowerShell7", + serde_json::json!({ + "Operation": "Uninstall", + "Manager": "PowerShell7", + "Package": { "Id": "Pester" }, + "Elevation": "Elevated", + }), + ), + ( + "an install through Scoop of an id that names one app", + serde_json::json!({ "Manager": "Scoop", "Package": { "Id": "git" } }), + ), + ( + "an install through Vcpkg of a port with a triplet", + serde_json::json!({ "Manager": "Vcpkg", "Package": { "Id": "zlib:x64-windows" } }), + ), + ( + "an uninstall through Dotnet", + serde_json::json!({ "Operation": "Uninstall", "Manager": "Dotnet", "Package": { "Id": "dotnet-ef" } }), + ), + ]; + + for (case, members) in cases { + let broker = Broker::from_state(state()); + let request = without_source(bypass_request("request-1", members)); + hold(&broker.state, TOKEN, &request); + + let reply = send(&broker.state, &client(), post_bypass(&[TOKEN], &request)).await; + + assert_eq!(reply.status, 200, "{case}: {reply:?}"); + assert!(reply.body["OperationId"].is_string(), "{case}: {reply:?}"); + } +} + +// oracle: contract Devolutions/now-libraries@3014fcbb899d:policies/CONTRACT.wire.md §bypass-reading +#[tokio::test] +async fn a_bypass_request_without_source_that_its_other_members_make_unreadable_is_bypass_request_unreadable() { + let cases = [ + ( + "a Scoop id that ends with .json", + serde_json::json!({ "Manager": "Scoop", "Package": { "Id": "app.json" } }), + ), + ( + "a Scoop id with a bucket", + serde_json::json!({ "Manager": "Scoop", "Package": { "Id": "main/git" } }), + ), + ( + // CONTRACT.policy.md §manager-vcpkg joins this test to one of `Source.Name` with "or". + "a Vcpkg id that is not a port spec", + serde_json::json!({ "Manager": "Vcpkg", "Package": { "Id": "Zlib" } }), + ), + ( + // CONTRACT.policy.md §manager-powershell joins this test to one of `Source.Name` with "or". + "a PowerShell id with a bracket", + serde_json::json!({ "Manager": "PowerShell", "Package": { "Id": "Pester[1]" } }), + ), + ]; + + for (case, members) in cases { + let broker = Broker::from_state(state()); + let request = without_source(bypass_request("request-1", members)); + hold(&broker.state, TOKEN, &request); + + // The second request shows that the first one did not use up the token. + for _ in 0..2 { + let reply = send(&broker.state, &client(), post_bypass(&[TOKEN], &request)).await; + + assert_eq!(reply.body["Code"], "BypassRequestUnreadable", "{case}: {reply:?}"); + reply.assert_error(422, "BypassRequestUnreadable"); + } + assert_eq!(broker.runs().await, 0, "{case}"); + } +} + +// oracle: contract Devolutions/now-libraries@3014fcbb899d:policies/CONTRACT.wire.md §errors +// `BadRequest` wins over every outcome of the section of an endpoint, so a request the broker read as well-formed and +// the evaluator refuses to read all the same met a broker failure that no other code names. +// oracle: contract Devolutions/now-libraries@3014fcbb899d:policies/CONTRACT.wire.md §bypass +// A bypass request that starts no operation does not use up its token. +#[tokio::test] +async fn a_bypass_request_the_evaluator_refuses_once_the_broker_read_it_is_internal_error_and_keeps_its_token() { let broker = Broker::from_state(state()); - let request = without_source(bypass_request("request-1", serde_json::json!({}))); - hold(&broker.state, TOKEN, &request); + let connection = super::Connection { + state: Arc::clone(&broker.state), + client: client(), + }; + let body = bypass_request("request-1", serde_json::json!({})); + let mut request = crate::v2::wire::read_bypass_request(body.to_string().as_bytes()).expect("a bypass request"); + // No body the broker reads as a bypass request has the scope `Machine` for a run that is not elevated. + request.scope = Some(now_policy_api::v2::Scope::Machine); + let held = broker.state.operations.of(&broker.state).bypass_tokens.hold( + TOKEN, + request.clone(), + client().user_sid().clone(), + ); + assert!(held.is_ok(), "the broker holds the token"); + let mut headers = axum::http::HeaderMap::new(); + headers.insert(BYPASS_TOKEN_HEADER, axum::http::HeaderValue::from_static(TOKEN)); // The second request is answered as the first one, so the first one did not use up the token. for _ in 0..2 { - let reply = send(&broker.state, &client(), post_bypass(&[TOKEN], &request)).await; - reply.assert_error(500, "InternalError"); + let refused = connection.execute_bypass(&headers, &request); + + reply(refused).await.assert_error(500, "InternalError"); } assert_eq!(broker.runs().await, 0); } diff --git a/crates/now-package-broker/src/v2/wire/convert.rs b/crates/now-package-broker/src/v2/wire/convert.rs index c09cdaf5c..ccf5fd326 100644 --- a/crates/now-package-broker/src/v2/wire/convert.rs +++ b/crates/now-package-broker/src/v2/wire/convert.rs @@ -80,44 +80,37 @@ fn evaluator_opt_ins(opt_ins: &v2::OptIns) -> eval::OptIns { } } -/// Returns the package request a bypass request is read as ([§bypass-reading]), or `None` when the request has no `Source.Name`. +/// Returns the body of a bypass request without its `RequestId`, as the evaluator reads it ([§bypass-reading]). /// -/// `listed_source` is the `Source.Name` that the list of that section gives a request without `Source`, when it gives one. +/// The request the evaluator reads has a source exactly when the bypass request has `Source`. /// /// [§bypass-reading]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#bypass-reading -pub fn bypass_package_request( - request: &v2::BypassRequest, - listed_source: Option<&v2::SourceName>, -) -> Option { - let source = match (&request.source, listed_source) { - (Some(source), _) => source.clone(), - (None, Some(name)) => v2::Source { name: name.clone() }, - (None, None) => return None, - }; - - Some(v2::PackageRequest { - operation: request.operation, - manager: request.manager, - source, - package: v2::Package { - id: request.package.id.clone(), - version: request.package.version.clone(), +pub fn evaluator_bypass_request(request: &v2::BypassRequest) -> eval::Request { + eval::Request { + operation: operation(request.operation), + manager: manager(request.manager), + source: request.source.as_ref().map(|source| eval::Source { + name: source.name.as_str().to_owned(), + }), + package: eval::Package { + id: request.package.id.as_str().to_owned(), + version: request + .package + .version + .as_ref() + .map(|version| version.as_str().to_owned()), architecture: None, }, - scope: request.scope, - elevation: request.elevation, - opt_ins: request.opt_ins.as_ref().map(|opt_ins| v2::OptIns { - interactive: None, - skip_hash_check: None, - custom_install_location: None, - custom_parameters: None, - installer_arguments: None, - pre_post_commands: None, - kill_before_operation: None, - uninstall_previous: None, - no_upgrade: opt_ins.no_upgrade.clone(), - }), - }) + scope: request.scope.map(scope), + elevation: elevation(request.elevation), + opt_ins: eval::OptIns { + no_upgrade: request + .opt_ins + .as_ref() + .is_some_and(|opt_ins| opt_ins.no_upgrade.is_some()), + ..eval::OptIns::default() + }, + } } /// Returns the decision as a response carries it ([§decision]). @@ -777,53 +770,75 @@ mod tests { }) } - // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §bypass-reading + // oracle: contract Devolutions/now-libraries@3014fcbb899d:policies/CONTRACT.wire.md §bypass-reading #[test] - fn bypass_request_with_source_is_read_as_the_package_request_with_its_members() { + fn evaluator_bypass_request_of_a_request_with_source_is_that_of_the_package_request_with_the_same_members() { let body = full_bypass_request(); - let listed = v2::SourceName::parse("listed").expect("source name"); - let read = bypass_package_request(&bypass_request(&body), Some(&listed)); + let read = evaluator_bypass_request(&bypass_request(&body)); + + assert_eq!( + read, + evaluator_request(&evaluation_request(&without(body, "", "RequestId"))) + ); + assert_eq!(read.source.map(|source| source.name).as_deref(), Some("community")); + } + + // oracle: contract Devolutions/now-libraries@3014fcbb899d:policies/CONTRACT.wire.md §bypass-reading + #[test] + fn evaluator_bypass_request_of_a_request_without_source_has_no_source() { + let body = without(full_bypass_request(), "", "Source"); + let expected = eval::Request { + operation: eval::Operation::Update, + manager: eval::Manager::Chocolatey, + source: None, + package: eval::Package { + id: "git.install".to_owned(), + version: Some("2.45.1".to_owned()), + architecture: None, + }, + scope: Some(eval::Scope::Machine), + elevation: eval::Elevation::Elevated, + opt_ins: eval::OptIns { + no_upgrade: true, + ..eval::OptIns::default() + }, + }; - assert_eq!(read, Some(evaluation_request(&without(body, "", "RequestId")))); + assert_eq!(evaluator_bypass_request(&bypass_request(&body)), expected); } - // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §bypass-reading + // oracle: contract Devolutions/now-libraries@3014fcbb899d:policies/CONTRACT.wire.md §bypass #[test] - fn bypass_request_with_only_required_members_is_read_as_the_package_request_with_its_members() { + fn evaluator_bypass_request_lacks_what_the_bypass_request_lacks() { let body = json!({ "RequestId": "request-1", - "Operation": "Install", + "Operation": "Uninstall", "Manager": "Winget", - "Source": { "Name": "winget" }, "Package": { "Id": "Git.Git" }, "Elevation": "NonElevated", }); + let expected = eval::Request { + operation: eval::Operation::Uninstall, + manager: eval::Manager::Winget, + source: None, + package: eval::Package { + id: "Git.Git".to_owned(), + version: None, + architecture: None, + }, + scope: None, + elevation: eval::Elevation::NonElevated, + opt_ins: eval::OptIns::default(), + }; + let with_empty_opt_ins = with(full_bypass_request(), "/OptIns", json!({})); - let read = bypass_package_request(&bypass_request(&body), None); - - assert_eq!(read, Some(evaluation_request(&without(body, "", "RequestId")))); - } - - // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §bypass-reading - #[test] - fn bypass_request_without_source_is_read_with_the_source_name_its_list_gives() { - let body = without(full_bypass_request(), "", "Source"); - let listed = v2::SourceName::parse("listed").expect("source name"); - let mut expected = without(full_bypass_request(), "", "RequestId"); - expected["Source"] = json!({ "Name": "listed" }); - - let read = bypass_package_request(&bypass_request(&body), Some(&listed)); - - assert_eq!(read, Some(evaluation_request(&expected))); - } - - // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §bypass-reading - #[test] - fn bypass_request_without_any_source_name_is_no_package_request() { - let body = without(full_bypass_request(), "", "Source"); - - assert_eq!(bypass_package_request(&bypass_request(&body), None), None); + assert_eq!(evaluator_bypass_request(&bypass_request(&body)), expected); + assert_eq!( + evaluator_bypass_request(&bypass_request(&with_empty_opt_ins)).opt_ins, + eval::OptIns::default(), + "OptIns set to {{}} asks for no opt-in" + ); } // oracle: contract Devolutions/now-libraries@bd8760e46648:policies/CONTRACT.wire.md §decision diff --git a/crates/now-package-broker/src/v2/wire/mod.rs b/crates/now-package-broker/src/v2/wire/mod.rs index 2c4569a23..19851c283 100644 --- a/crates/now-package-broker/src/v2/wire/mod.rs +++ b/crates/now-package-broker/src/v2/wire/mod.rs @@ -8,7 +8,7 @@ mod error; mod read; mod route; -pub use convert::{bypass_package_request, decision, evaluator_request, policy_error, timestamp}; +pub use convert::{decision, evaluator_bypass_request, evaluator_request, policy_error, timestamp}; pub use error::{error_response, invalid_policy, message, not_runnable, policy_state_error}; pub use read::{ BadRequest, read_bypass_request, read_evaluation_request, read_execution_request, read_replacement_request, From 8d3b8f6a64e1b69996c51813af38007ad70c085b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Wed, 2 Dec 2026 04:19:09 +0900 Subject: [PATCH 24/38] feat(agent): name the version of the hosting Agent in the 2.0 capabilities The 2.0 capabilities carry the version of the Devolutions Agent that hosts the broker, and the broker named the version of its own crate, which is not one any Agent is released with. The Agent now gives its package version to the broker task. A version the capabilities cannot carry, empty or longer than 128 bytes, is refused when the task is created, so the service fails to start with the cause instead of answering every capabilities request with an internal error. The 1.x routes keep reporting the version they reported. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- crates/now-package-broker/src/pipe.rs | 1 + crates/now-package-broker/src/server/grant.rs | 1 + crates/now-package-broker/src/server/mod.rs | 9 +++ crates/now-package-broker/src/task.rs | 64 ++++++++++++++++++- .../src/v2/routes/capabilities.rs | 10 ++- .../now-package-broker/src/v2/routes/mod.rs | 2 +- .../now-package-broker/src/v2/routes/tests.rs | 31 +++++++-- .../src/device_management/context.rs | 2 +- devolutions-agent/src/service.rs | 8 ++- 9 files changed, 115 insertions(+), 13 deletions(-) diff --git a/crates/now-package-broker/src/pipe.rs b/crates/now-package-broker/src/pipe.rs index db55011b9..0630a6f31 100644 --- a/crates/now-package-broker/src/pipe.rs +++ b/crates/now-package-broker/src/pipe.rs @@ -1707,6 +1707,7 @@ mod tests { manager_probe_cache: Default::default(), remote_grants: crate::remote_grant::RemoteGrantStore::new(), agent_product_code: || Ok(None), + agent_version: now_policy_api::v2::ServerVersion::parse("1.2.3").expect("a server version"), operations: Default::default(), }) } diff --git a/crates/now-package-broker/src/server/grant.rs b/crates/now-package-broker/src/server/grant.rs index 980f32190..9a06ec8e9 100644 --- a/crates/now-package-broker/src/server/grant.rs +++ b/crates/now-package-broker/src/server/grant.rs @@ -326,6 +326,7 @@ mod tests { manager_probe_cache: Default::default(), remote_grants: RemoteGrantStore::new(), agent_product_code: || Ok(None), + agent_version: now_policy_api::v2::ServerVersion::parse("1.2.3").expect("a server version"), operations: Default::default(), }) } diff --git a/crates/now-package-broker/src/server/mod.rs b/crates/now-package-broker/src/server/mod.rs index 4d4b06616..7dc0ebb60 100644 --- a/crates/now-package-broker/src/server/mod.rs +++ b/crates/now-package-broker/src/server/mod.rs @@ -193,6 +193,12 @@ pub struct BrokerState { /// `Ok(None)` means that no Agent MSI is installed. /// An error rejects every request that removes a package. pub agent_product_code: fn() -> anyhow::Result>, + /// The version of the Devolutions Agent that hosts the broker, which the 2.0 capabilities name ([§capabilities]). + /// + /// The 1.x routes report the version of this crate. + /// + /// [§capabilities]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#capabilities + pub agent_version: now_policy_api::v2::ServerVersion, /// The operations started by the requests of the 2.0 encoding; `tracker` holds those of the 1.x routes. pub operations: crate::v2::HeldOperations, } @@ -1289,6 +1295,7 @@ mod tests { manager_probe_cache: Default::default(), remote_grants: RemoteGrantStore::new(), agent_product_code: || Ok(None), + agent_version: now_policy_api::v2::ServerVersion::parse("1.2.3").expect("a server version"), operations: Default::default(), } } @@ -2189,6 +2196,7 @@ mod tests { manager_probe_cache, remote_grants: RemoteGrantStore::new(), agent_product_code: || Ok(None), + agent_version: now_policy_api::v2::ServerVersion::parse("1.2.3").expect("a server version"), operations: Default::default(), }); (state, executor) @@ -2374,6 +2382,7 @@ mod tests { manager_probe_cache: Default::default(), remote_grants: RemoteGrantStore::new(), agent_product_code: || Ok(None), + agent_version: now_policy_api::v2::ServerVersion::parse("1.2.3").expect("a server version"), operations: Default::default(), } } diff --git a/crates/now-package-broker/src/task.rs b/crates/now-package-broker/src/task.rs index 7195eb8ad..c126b9021 100644 --- a/crates/now-package-broker/src/task.rs +++ b/crates/now-package-broker/src/task.rs @@ -26,6 +26,12 @@ pub struct BrokerTaskConfig { pub policy_path: Option, /// Skip Authenticode signature validation for the broker client executable. pub skip_signature_validation: bool, + /// The version of the Devolutions Agent that hosts the broker, which the 2.0 capabilities name ([§capabilities]). + /// + /// The capabilities carry a version of 1 to 128 bytes, and [`BrokerTask::new`] refuses any other. + /// + /// [§capabilities]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#capabilities + pub agent_version: String, } impl Default for BrokerTaskConfig { @@ -34,6 +40,8 @@ impl Default for BrokerTaskConfig { pipe_name: DEFAULT_PIPE_NAME.to_owned(), policy_path: None, skip_signature_validation: false, + // No Agent hosts a broker that is given no version, which names the version of this crate. + agent_version: env!("CARGO_PKG_VERSION").to_owned(), } } } @@ -44,7 +52,16 @@ pub struct BrokerTask { } impl BrokerTask { - pub fn new(config: BrokerTaskConfig) -> Self { + /// Creates the task of the broker `config` describes. + /// + /// Fails when the version of the hosting Agent is not one the 2.0 capabilities can carry ([§capabilities]). + /// A broker that ran with such a version would answer every capabilities request with an error, and nothing + /// would tell why before a client asks. + /// + /// [§capabilities]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#capabilities + pub fn new(config: BrokerTaskConfig) -> anyhow::Result { + let agent_version = now_policy_api::v2::ServerVersion::parse(&config.agent_version) + .context("the version of the hosting Devolutions Agent is not one the broker can name")?; let policy_store = PolicyStore::load(config.policy_path.map(std::path::PathBuf::from)); let executor: Arc = executor::create_platform_executor().into(); let state = Arc::new(BrokerState { @@ -57,12 +74,13 @@ impl BrokerTask { remote_grants: RemoteGrantStore::new(), // UNTESTED: The broker runs with the registry lookup; see `read_agent_product_code`. agent_product_code: crate::server::read_agent_product_code, + agent_version, operations: Default::default(), }); - Self { + Ok(Self { state, registration: RegistrationHandle::new(), - } + }) } /// Returns the handle that snapshots the live UniGetUI registrations while the task runs. @@ -157,3 +175,43 @@ impl Task for BrokerTask { result } } + +#[cfg(test)] +mod tests { + use super::*; + + /// The configuration of a broker hosted by an Agent of version `agent_version`, whose policy file is in `folder`. + fn config(folder: &tempfile::TempDir, agent_version: &str) -> BrokerTaskConfig { + BrokerTaskConfig { + policy_path: Some(folder.path().join("policy.json").to_string_lossy().into_owned()), + agent_version: agent_version.to_owned(), + ..Default::default() + } + } + + // oracle: mutant giving the state of the task another version than the one of its configuration, such as the version of this crate + #[tokio::test] + async fn the_state_of_a_task_has_the_agent_version_of_its_configuration() { + let folder = tempfile::tempdir().expect("a folder"); + let longest = "9".repeat(128); + + for version in ["2026.3.1", "1", longest.as_str()] { + let task = BrokerTask::new(config(&folder, version)).expect("a task"); + + assert_eq!(task.state().agent_version.as_str(), version); + } + } + + // oracle: mutant creating the task of a broker whose capabilities cannot carry the version it was given + #[tokio::test] + async fn a_task_is_not_created_with_an_agent_version_the_capabilities_cannot_carry() { + let folder = tempfile::tempdir().expect("a folder"); + let too_long = "9".repeat(129); + + for (case, version) in [("empty", ""), ("129 bytes", too_long.as_str())] { + let task = BrokerTask::new(config(&folder, version)); + + assert!(task.is_err(), "{case}"); + } + } +} diff --git a/crates/now-package-broker/src/v2/routes/capabilities.rs b/crates/now-package-broker/src/v2/routes/capabilities.rs index f84e77cfd..e9825507b 100644 --- a/crates/now-package-broker/src/v2/routes/capabilities.rs +++ b/crates/now-package-broker/src/v2/routes/capabilities.rs @@ -7,14 +7,18 @@ use now_policy_api::v2; use crate::operation_tracker::OperationTracker; -/// Returns the capabilities response for a user who has `managers`. +/// Returns the capabilities response of a broker hosted by an Agent of version `agent_version`, for a user who has +/// `managers`. /// /// The timeout is the one the executor stops a process after. -pub(super) fn response(managers: Vec) -> Result { +pub(super) fn response( + agent_version: &v2::ServerVersion, + managers: Vec, +) -> Result { let timeout = u32::try_from(OperationTracker::operation_timeout().as_secs()).unwrap_or(u32::MAX); Ok(v2::CapabilitiesResponse { - server_version: v2::ServerVersion::parse(env!("CARGO_PKG_VERSION"))?, + server_version: agent_version.clone(), operation_timeout_seconds: v2::OperationTimeoutSeconds::new(timeout)?, managers: managers .into_iter() diff --git a/crates/now-package-broker/src/v2/routes/mod.rs b/crates/now-package-broker/src/v2/routes/mod.rs index 42c6cf7cc..79efd168c 100644 --- a/crates/now-package-broker/src/v2/routes/mod.rs +++ b/crates/now-package-broker/src/v2/routes/mod.rs @@ -220,7 +220,7 @@ impl Connection { async fn capabilities(&self) -> Response { let managers = self.state.probed_manager_capabilities(self.client.user_sid()).await; - match capabilities::response(managers) { + match capabilities::response(&self.state.agent_version, managers) { Ok(response) => json(StatusCode::OK, &response), Err(error) => internal_error(&error), } diff --git a/crates/now-package-broker/src/v2/routes/tests.rs b/crates/now-package-broker/src/v2/routes/tests.rs index bf0f8728d..c0820cc7f 100644 --- a/crates/now-package-broker/src/v2/routes/tests.rs +++ b/crates/now-package-broker/src/v2/routes/tests.rs @@ -55,6 +55,7 @@ fn state() -> BrokerState { manager_probe_cache: Default::default(), remote_grants: RemoteGrantStore::new(), agent_product_code: || Ok(None), + agent_version: now_policy_api::v2::ServerVersion::parse("1.2.3").expect("a server version"), operations: Default::default(), } } @@ -992,6 +993,25 @@ async fn capabilities_name_the_version_the_timeout_and_each_manager_once() { assert_eq!(names, ["Npm", "Winget"], "{reply:?}"); } +// oracle: contract Devolutions/now-libraries@3014fcbb899d:policies/CONTRACT.wire.md §capabilities +#[tokio::test] +async fn capabilities_name_the_version_of_the_agent_that_hosts_the_broker() { + let longest = "9".repeat(128); + + for version in ["2026.3.1", "1", longest.as_str()] { + let state = Arc::new(BrokerState { + executor: Arc::new(ProbingExecutor(Vec::new())), + agent_version: now_policy_api::v2::ServerVersion::parse(version).expect("a server version"), + ..state() + }); + + let reply = send(&state, &client(), get("/v2/capabilities")).await; + + assert_eq!(reply.status, 200, "{version}: {reply:?}"); + assert_eq!(reply.body["ServerVersion"], version, "{reply:?}"); + } +} + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §capabilities #[test] fn every_manager_capability_names_at_least_one_operation() { @@ -1010,10 +1030,13 @@ fn every_manager_capability_names_at_least_one_operation() { }; // No manager the broker drives is without an operation today, so no request reaches this case. - let response = super::capabilities::response(vec![ - capability(v1::ManagerName::Npm, vec![v1::Operation::Install]), - capability(v1::ManagerName::Bun, Vec::new()), - ]) + let response = super::capabilities::response( + &state().agent_version, + vec![ + capability(v1::ManagerName::Npm, vec![v1::Operation::Install]), + capability(v1::ManagerName::Bun, Vec::new()), + ], + ) .expect("a capabilities response"); let body = serde_json::to_value(&response).expect("a JSON response"); diff --git a/devolutions-agent/src/device_management/context.rs b/devolutions-agent/src/device_management/context.rs index e6caf11d2..cbf0b1105 100644 --- a/devolutions-agent/src/device_management/context.rs +++ b/devolutions-agent/src/device_management/context.rs @@ -260,7 +260,7 @@ mod tests { let broker = BrokerTask::new(BrokerTaskConfig { policy_path: Some(data.join("missing-policy.json").to_string()), ..Default::default() - }); + })?; let registration = broker.registration(); let pipe = format!(r"\\.\pipe\agent-journal-test-{}", Uuid::new_v4().simple()); let server_registration = registration.clone(); diff --git a/devolutions-agent/src/service.rs b/devolutions-agent/src/service.rs index e1c88f966..c1db02838 100644 --- a/devolutions-agent/src/service.rs +++ b/devolutions-agent/src/service.rs @@ -239,8 +239,14 @@ async fn spawn_tasks(conf_handle: ConfHandle) -> anyhow::Result { .unwrap_or_else(|| DEFAULT_PIPE_NAME.to_owned()), policy_path: conf.package_broker.policy_path.clone(), skip_signature_validation: conf.debug.skip_broker_signature_validation, + // UNTESTED: The broker is given the version of this Agent, which hosts it. + // A client reads that version in the capabilities of the broker, and would read another one as the + // version of the Agent it talks to. + // No test starts the tasks of the service; when changing how the broker is configured, check that + // this member is still the package version of the Agent. + agent_version: env!("CARGO_PKG_VERSION").to_owned(), }; - let broker = BrokerTask::new(broker_config); + let broker = BrokerTask::new(broker_config).context("failed to create the package broker task")?; identity = identity.map(|task| task.with_package_broker(broker.registration(), broker.state())); tasks.register(broker); } From ba1bde37d1ef470b0d60794bd1ba59eb68efbb1a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Wed, 2 Dec 2026 04:42:32 +0900 Subject: [PATCH 25/38] feat(agent): answer a protected uninstall of the 2.0 routes ProtectedPackage The wire contract has no request start an operation that would uninstall the Devolutions Agent, which hosts the broker, and names where `ProtectedPackage` falls among the outcomes of an evaluation, an execution and a bypass request. The broker answered it for a bypass request only: an evaluation said such a request was allowed, and an execution started an operation that ended `Failed` and kept its `RequestId`. One function now decides a protected uninstall for the three requests. A request that removes a package, by its operation or by `UninstallPrevious`, is refused when it names the Agent or when the product code of the installed Agent cannot be read; the product code is read for no other request. An evaluation answers it before anything else, and an execution after a used `RequestId` and before the policy is looked at, so it starts nothing and leaves its `RequestId` unused. The plan of an operation still refuses to remove the Agent, for a request the Agent turns out to be named by once the operation starts. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- .../now-package-broker/src/v2/bypass/mod.rs | 2 +- .../src/v2/bypass/reading.rs | 109 +---- .../src/v2/routes/bypass.rs | 25 +- .../now-package-broker/src/v2/routes/mod.rs | 8 +- .../src/v2/routes/operations.rs | 6 + .../src/v2/routes/protection.rs | 196 +++++++++ .../now-package-broker/src/v2/routes/tests.rs | 372 +++++++++++++++++- 7 files changed, 575 insertions(+), 143 deletions(-) create mode 100644 crates/now-package-broker/src/v2/routes/protection.rs diff --git a/crates/now-package-broker/src/v2/bypass/mod.rs b/crates/now-package-broker/src/v2/bypass/mod.rs index b828df1b3..ea01e07af 100644 --- a/crates/now-package-broker/src/v2/bypass/mod.rs +++ b/crates/now-package-broker/src/v2/bypass/mod.rs @@ -7,5 +7,5 @@ mod reading; mod tokens; -pub(crate) use self::reading::{Reading, read, uninstall_names_agent}; +pub(crate) use self::reading::{Reading, read}; pub(crate) use self::tokens::{BypassTokens, TokenDigest}; diff --git a/crates/now-package-broker/src/v2/bypass/reading.rs b/crates/now-package-broker/src/v2/bypass/reading.rs index 30a7580eb..ee6131e7e 100644 --- a/crates/now-package-broker/src/v2/bypass/reading.rs +++ b/crates/now-package-broker/src/v2/bypass/reading.rs @@ -1,11 +1,9 @@ -//! How the broker reads a bypass request ([§bypass-reading]), and which one names Devolutions Agent ([§bypass]). +//! How the broker reads a bypass request ([§bypass-reading]). //! -//! [§bypass]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#bypass //! [§bypass-reading]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#bypass-reading use now_policy_api::v2; use now_policy_eval as eval; -use uuid::Uuid; use crate::v2::wire; @@ -42,40 +40,6 @@ pub(crate) fn read(request: &v2::BypassRequest) -> Result) -> bool { - let name = package_id.split_once('#').map_or(package_id, |(name, _)| name); - let name = name.rsplit_once('@').map_or(name, |(name, _)| name); - - match manager { - v2::Manager::Winget => { - name.eq_ignore_ascii_case("Devolutions.Agent") - || agent_product_code - .is_some_and(|code| package_id.to_ascii_lowercase().contains(&code.hyphenated().to_string())) - } - v2::Manager::Chocolatey => name.eq_ignore_ascii_case("devo-agent"), - v2::Manager::PowerShell - | v2::Manager::PowerShell7 - | v2::Manager::Apt - | v2::Manager::Bun - | v2::Manager::Cargo - | v2::Manager::Dnf - | v2::Manager::Dotnet - | v2::Manager::Flatpak - | v2::Manager::Homebrew - | v2::Manager::Npm - | v2::Manager::Pacman - | v2::Manager::Pip - | v2::Manager::Scoop - | v2::Manager::Snap - | v2::Manager::Vcpkg => false, - } -} - #[cfg(test)] mod tests { use super::*; @@ -398,75 +362,4 @@ mod tests { assert_eq!(read(&uninstall_with_source), Err(eval::BadRequest)); } - - const PRODUCT_CODE: &str = "0f2a6b3c-4d5e-4f60-8a9b-0c1d2e3f4a5b"; - - fn product_code() -> Option { - Some(PRODUCT_CODE.parse().expect("a UUID")) - } - - // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §bypass - #[test] - fn an_uninstall_names_devolutions_agent_by_its_id_or_by_its_product_code() { - let cases = [ - (v2::Manager::Winget, "Devolutions.Agent"), - (v2::Manager::Winget, "devolutions.AGENT"), - // The text from the first `#` is removed, then the text from the last `@`. - (v2::Manager::Winget, "Devolutions.Agent#main"), - (v2::Manager::Winget, "Devolutions.Agent@2026.1.0"), - (v2::Manager::Winget, "Devolutions.Agent@1#a@b#c"), - (v2::Manager::Chocolatey, "devo-agent"), - (v2::Manager::Chocolatey, "Devo-Agent"), - (v2::Manager::Chocolatey, "devo-agent@2026.1.0"), - (v2::Manager::Winget, "{0f2a6b3c-4d5e-4f60-8a9b-0c1d2e3f4a5b}"), - (v2::Manager::Winget, "{0F2A6B3C-4D5E-4F60-8A9B-0C1D2E3F4A5B}"), - ( - v2::Manager::Winget, - "ARP/Machine/X64/{0f2a6b3c-4d5e-4f60-8a9b-0c1d2e3f4a5b}@1", - ), - ]; - - for (manager, package_id) in cases { - assert!( - uninstall_names_agent(manager, package_id, product_code()), - "{manager:?} {package_id}" - ); - } - } - - // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §bypass - #[test] - fn an_uninstall_of_anything_else_does_not_name_devolutions_agent() { - let cases = [ - (v2::Manager::Winget, "Devolutions.Agent2"), - (v2::Manager::Winget, "Devolutions.Agent.Tools"), - (v2::Manager::Winget, "devo-agent"), - (v2::Manager::Chocolatey, "Devolutions.Agent"), - (v2::Manager::Scoop, "Devolutions.Agent"), - (v2::Manager::Winget, "scope@Devolutions.Agent"), - (v2::Manager::Winget, "other#Devolutions.Agent"), - // The product code names the Agent through WinGet only, and in hyphenated form. - (v2::Manager::Chocolatey, "{0f2a6b3c-4d5e-4f60-8a9b-0c1d2e3f4a5b}"), - (v2::Manager::Winget, "{0f2a6b3c4d5e4f608a9b0c1d2e3f4a5b}"), - (v2::Manager::Winget, "{1f2a6b3c-4d5e-4f60-8a9b-0c1d2e3f4a5b}"), - ]; - - for (manager, package_id) in cases { - assert!( - !uninstall_names_agent(manager, package_id, product_code()), - "{manager:?} {package_id}" - ); - } - } - - // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §bypass - #[test] - fn without_an_installed_agent_no_product_code_names_it() { - assert!(!uninstall_names_agent( - v2::Manager::Winget, - "{0f2a6b3c-4d5e-4f60-8a9b-0c1d2e3f4a5b}", - None - )); - assert!(uninstall_names_agent(v2::Manager::Winget, "Devolutions.Agent", None)); - } } diff --git a/crates/now-package-broker/src/v2/routes/bypass.rs b/crates/now-package-broker/src/v2/routes/bypass.rs index 5a2f896a5..0d112d019 100644 --- a/crates/now-package-broker/src/v2/routes/bypass.rs +++ b/crates/now-package-broker/src/v2/routes/bypass.rs @@ -5,11 +5,11 @@ use axum::http::{HeaderMap, StatusCode}; use axum::response::Response; use now_policy_api::v2; -use tracing::warn; use super::operations::operation_status; +use super::protection::protected_package; use super::{Connection, error_response, internal_error, json}; -use crate::v2::bypass::{Reading, TokenDigest, read, uninstall_names_agent}; +use crate::v2::bypass::{Reading, TokenDigest, read}; use crate::v2::execution::{Existing, Start, StartedOperation}; impl Connection { @@ -57,24 +57,9 @@ impl Connection { return token_rejected(); } - if request.operation == v2::Operation::Uninstall { - let names_agent = match (self.state.agent_product_code)() { - Ok(product_code) => uninstall_names_agent(request.manager, request.package.id.as_str(), product_code), - Err(error) => { - warn!( - error = format!("{error:#}"), - "Failed to read the product code of the installed Devolutions Agent" - ); - // The broker cannot verify that the request does not uninstall the Agent. - true - } - }; - if names_agent { - return error_response( - v2::ErrorCode::ProtectedPackage, - "the broker does not uninstall Devolutions Agent", - ); - } + // Nothing starts, so the token is not used up. + if self.is_protected_uninstall(request.into()) { + return protected_package(); } let package_request = match read(request) { diff --git a/crates/now-package-broker/src/v2/routes/mod.rs b/crates/now-package-broker/src/v2/routes/mod.rs index 79efd168c..698ee2791 100644 --- a/crates/now-package-broker/src/v2/routes/mod.rs +++ b/crates/now-package-broker/src/v2/routes/mod.rs @@ -10,6 +10,7 @@ mod capabilities; mod held; mod operations; mod policy; +mod protection; use std::future::Future; use std::panic::AssertUnwindSafe; @@ -230,6 +231,10 @@ impl Connection { /// /// [§evaluate]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#evaluate fn evaluate(&self, request: &v2::EvaluationRequest) -> Response { + if self.is_protected_uninstall(request.into()) { + return protection::protected_package(); + } + match self.decide(request) { Ok(evaluated) => json( StatusCode::OK, @@ -246,7 +251,8 @@ impl Connection { /// Evaluates `request` against the accepted policy at the current time. /// /// The error is the response of a request that gets no evaluation response: `PolicyUnavailable` and `NotRunnable`, - /// in that order, are the outcomes an evaluation and an execution request share ([§evaluate], [§execute]). + /// in that order, are the outcomes an evaluation and an execution request share once neither is a protected + /// uninstall, which the caller answers before it calls this ([§evaluate], [§execute]). /// /// [§evaluate]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#evaluate /// [§execute]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#execute diff --git a/crates/now-package-broker/src/v2/routes/operations.rs b/crates/now-package-broker/src/v2/routes/operations.rs index c32c5fa59..cb5ac7f6a 100644 --- a/crates/now-package-broker/src/v2/routes/operations.rs +++ b/crates/now-package-broker/src/v2/routes/operations.rs @@ -9,6 +9,7 @@ use axum::response::Response; use now_policy_api::v2; use super::held::Decided; +use super::protection::protected_package; use super::{Connection, error_response, internal_error, json}; use crate::auth::PipeClient; use crate::v2::execution::{Caller, Existing, OperationState, Owner, Start, StartedOperation, Status}; @@ -50,6 +51,11 @@ impl Connection { return existing_execution(existing); } + // A protected uninstall starts nothing, and its `RequestId` stays unused. + if self.is_protected_uninstall((&package_request).into()) { + return protected_package(); + } + let evaluated = match self.decide(&package_request) { Ok(evaluated) => evaluated, Err(response) => return *response, diff --git a/crates/now-package-broker/src/v2/routes/protection.rs b/crates/now-package-broker/src/v2/routes/protection.rs new file mode 100644 index 000000000..1dc0fa8db --- /dev/null +++ b/crates/now-package-broker/src/v2/routes/protection.rs @@ -0,0 +1,196 @@ +//! The requests that would uninstall Devolutions Agent, for which the broker starts no operation +//! ([§protected-package]). +//! +//! [§protected-package]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#protected-package + +use axum::response::Response; +use now_policy_api::v2; +use tracing::warn; +use uuid::Uuid; + +use super::{Connection, error_response}; + +/// The members of a request that tell whether it is a protected uninstall ([§protected-package]). +/// +/// [§protected-package]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#protected-package +pub(super) struct Target<'a> { + /// Whether the request removes a package. + removes_package: bool, + manager: v2::Manager, + package_id: &'a str, +} + +impl<'a> From<&'a v2::PackageRequest> for Target<'a> { + fn from(request: &'a v2::PackageRequest) -> Self { + Self { + removes_package: request.operation == v2::Operation::Uninstall + || request + .opt_ins + .as_ref() + .is_some_and(|opt_ins| opt_ins.uninstall_previous.is_some()), + manager: request.manager, + package_id: request.package.id.as_str(), + } + } +} + +impl<'a> From<&'a v2::BypassRequest> for Target<'a> { + fn from(request: &'a v2::BypassRequest) -> Self { + Self { + // The `OptIns` of a bypass request never has `UninstallPrevious`. + removes_package: request.operation == v2::Operation::Uninstall, + manager: request.manager, + package_id: request.package.id.as_str(), + } + } +} + +impl Connection { + /// Tells whether `request` is a protected uninstall ([§protected-package]). + /// + /// The broker reads the product code of the installed Devolutions Agent for a request that removes a package, and + /// for no other. + /// + /// [§protected-package]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#protected-package + pub(super) fn is_protected_uninstall(&self, request: Target<'_>) -> bool { + let Target { + removes_package, + manager, + package_id, + } = request; + + if !removes_package { + return false; + } + + match (self.state.agent_product_code)() { + Ok(agent_product_code) => names_agent(manager, package_id, agent_product_code), + Err(error) => { + warn!( + error = format!("{error:#}"), + "Failed to read the product code of the installed Devolutions Agent" + ); + // The broker cannot verify that the request does not name the Agent. + true + } + } + } +} + +/// Returns the response to a protected uninstall. +pub(super) fn protected_package() -> Response { + error_response( + v2::ErrorCode::ProtectedPackage, + "the broker does not uninstall Devolutions Agent", + ) +} + +/// Tells whether a request through `manager` for `package_id` names Devolutions Agent ([§protected-package]). +/// +/// `agent_product_code` is the product code of the installed Devolutions Agent, when one is installed. +/// +/// [§protected-package]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#protected-package +fn names_agent(manager: v2::Manager, package_id: &str, agent_product_code: Option) -> bool { + let name = package_id.split_once('#').map_or(package_id, |(name, _)| name); + let name = name.rsplit_once('@').map_or(name, |(name, _)| name); + + match manager { + v2::Manager::Winget => { + name.eq_ignore_ascii_case("Devolutions.Agent") + || agent_product_code + .is_some_and(|code| package_id.to_ascii_lowercase().contains(&code.hyphenated().to_string())) + } + v2::Manager::Chocolatey => name.eq_ignore_ascii_case("devo-agent"), + v2::Manager::PowerShell + | v2::Manager::PowerShell7 + | v2::Manager::Apt + | v2::Manager::Bun + | v2::Manager::Cargo + | v2::Manager::Dnf + | v2::Manager::Dotnet + | v2::Manager::Flatpak + | v2::Manager::Homebrew + | v2::Manager::Npm + | v2::Manager::Pacman + | v2::Manager::Pip + | v2::Manager::Scoop + | v2::Manager::Snap + | v2::Manager::Vcpkg => false, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const PRODUCT_CODE: &str = "0f2a6b3c-4d5e-4f60-8a9b-0c1d2e3f4a5b"; + + fn product_code() -> Option { + Some(PRODUCT_CODE.parse().expect("a UUID")) + } + + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §bypass + #[test] + fn a_request_names_devolutions_agent_by_its_id_or_by_its_product_code() { + let cases = [ + (v2::Manager::Winget, "Devolutions.Agent"), + (v2::Manager::Winget, "devolutions.AGENT"), + // The text from the first `#` is removed, then the text from the last `@`. + (v2::Manager::Winget, "Devolutions.Agent#main"), + (v2::Manager::Winget, "Devolutions.Agent@2026.1.0"), + (v2::Manager::Winget, "Devolutions.Agent@1#a@b#c"), + (v2::Manager::Chocolatey, "devo-agent"), + (v2::Manager::Chocolatey, "Devo-Agent"), + (v2::Manager::Chocolatey, "devo-agent@2026.1.0"), + (v2::Manager::Winget, "{0f2a6b3c-4d5e-4f60-8a9b-0c1d2e3f4a5b}"), + (v2::Manager::Winget, "{0F2A6B3C-4D5E-4F60-8A9B-0C1D2E3F4A5B}"), + ( + v2::Manager::Winget, + "ARP/Machine/X64/{0f2a6b3c-4d5e-4f60-8a9b-0c1d2e3f4a5b}@1", + ), + ]; + + for (manager, package_id) in cases { + assert!( + names_agent(manager, package_id, product_code()), + "{manager:?} {package_id}" + ); + } + } + + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §bypass + #[test] + fn a_request_for_anything_else_does_not_name_devolutions_agent() { + let cases = [ + (v2::Manager::Winget, "Devolutions.Agent2"), + (v2::Manager::Winget, "Devolutions.Agent.Tools"), + (v2::Manager::Winget, "devo-agent"), + (v2::Manager::Chocolatey, "Devolutions.Agent"), + (v2::Manager::Scoop, "Devolutions.Agent"), + (v2::Manager::Winget, "scope@Devolutions.Agent"), + (v2::Manager::Winget, "other#Devolutions.Agent"), + // The product code names the Agent through WinGet only, and in hyphenated form. + (v2::Manager::Chocolatey, "{0f2a6b3c-4d5e-4f60-8a9b-0c1d2e3f4a5b}"), + (v2::Manager::Winget, "{0f2a6b3c4d5e4f608a9b0c1d2e3f4a5b}"), + (v2::Manager::Winget, "{1f2a6b3c-4d5e-4f60-8a9b-0c1d2e3f4a5b}"), + ]; + + for (manager, package_id) in cases { + assert!( + !names_agent(manager, package_id, product_code()), + "{manager:?} {package_id}" + ); + } + } + + // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §bypass + #[test] + fn without_an_installed_agent_no_product_code_names_it() { + assert!(!names_agent( + v2::Manager::Winget, + "{0f2a6b3c-4d5e-4f60-8a9b-0c1d2e3f4a5b}", + None + )); + assert!(names_agent(v2::Manager::Winget, "Devolutions.Agent", None)); + } +} diff --git a/crates/now-package-broker/src/v2/routes/tests.rs b/crates/now-package-broker/src/v2/routes/tests.rs index c0820cc7f..898b7e195 100644 --- a/crates/now-package-broker/src/v2/routes/tests.rs +++ b/crates/now-package-broker/src/v2/routes/tests.rs @@ -2100,21 +2100,48 @@ async fn assert_failed_without_a_step(broker: &Broker, started: &Reply) { assert_eq!(broker.runs().await, 0); } -// oracle: mutant running an allowed uninstall of the Devolutions Agent, or any uninstall when the product code of the -// installed Agent cannot be read +// oracle: mutant running an allowed uninstall that names the Devolutions Agent found installed when its operation +// starts, or any allowed uninstall when the product code of the installed Agent cannot be read by then #[tokio::test] -async fn an_allowed_uninstall_of_the_devolutions_agent_ends_failed_without_a_step() { - let broker = Broker::with_policy(ALLOW_ALL, ""); - let started = broker.start(&uninstall("Devolutions.Agent")).await; - assert_eq!(started.body["Decision"]["Outcome"], "Allow"); - assert_failed_without_a_step(&broker, &started).await; +async fn an_allowed_uninstall_found_protected_when_its_operation_starts_ends_failed_without_a_step() { + thread_local! { + /// How many times the broker of a case read the product code of the installed Devolutions Agent. + static READS: std::cell::Cell = const { std::cell::Cell::new(0) }; + } + // The first read of a broker, which answering the request makes, finds no installed Agent, so the request is no + // protected uninstall. + // The next one, which starting the operation makes, finds what the case says. + let cases: [(&str, AgentProductCode, &str); 2] = [ + ( + "an Agent installed in the meantime", + || match READS.replace(READS.get() + 1) { + 0 => Ok(None), + _ => AGENT_PRODUCT_CODE(), + }, + "{0f2a6b3c-4d5e-4f60-8a9b-0c1d2e3f4a5b}", + ), + ( + "a product code the broker cannot read any more", + || match READS.replace(READS.get() + 1) { + 0 => Ok(None), + _ => anyhow::bail!("the registry cannot be read"), + }, + "Git.Git", + ), + ]; - let broker = Broker::from_state(BrokerState { - agent_product_code: || anyhow::bail!("the registry cannot be read"), - ..state_with_policy(ALLOW_ALL, "") - }); - let started = broker.start(&uninstall("Git.Git")).await; - assert_failed_without_a_step(&broker, &started).await; + for (case, agent_product_code, id) in cases { + READS.set(0); + let broker = Broker::from_state(BrokerState { + agent_product_code, + ..state_with_policy(ALLOW_ALL, "") + }); + + let started = broker.start(&uninstall(id)).await; + + assert_eq!(started.body["Decision"]["Outcome"], "Allow", "{case}"); + assert_failed_without_a_step(&broker, &started).await; + } } // oracle: mutant refusing every uninstall as one of the Devolutions Agent @@ -2129,6 +2156,325 @@ async fn an_allowed_uninstall_of_another_package_runs() { assert_eq!(broker.runs().await, 1); } +/// A read of the product code of the installed Devolutions Agent that finds no installed Agent. +const NO_PRODUCT_CODE: AgentProductCode = || Ok(None); + +/// A read of the product code of the installed Devolutions Agent that fails. +const UNREADABLE_PRODUCT_CODE: AgentProductCode = || anyhow::bail!("the registry cannot be read"); + +/// The members of a package request for the package `id` of Chocolatey. +fn chocolatey(operation: &str, id: &str) -> serde_json::Value { + serde_json::json!({ + "Operation": operation, + "Manager": "Chocolatey", + "Source": { "Name": "chocolatey" }, + "Package": { "Id": id }, + }) +} + +/// The members of a package request to uninstall the package `id` of WinGet. +fn winget_uninstall(id: &str) -> serde_json::Value { + serde_json::json!({ "Operation": "Uninstall", "Package": { "Id": id } }) +} + +fn with_uninstall_previous(mut members: serde_json::Value) -> serde_json::Value { + members["OptIns"] = serde_json::json!({ "UninstallPrevious": {} }); + members +} + +// oracle: contract Devolutions/now-libraries@3014fcbb899d:policies/CONTRACT.wire.md §protected-package +#[tokio::test] +async fn an_evaluation_or_execution_request_that_is_a_protected_uninstall_is_protected_package() { + let cases: [(&str, AgentProductCode, serde_json::Value); 12] = [ + ( + "an uninstall of the WinGet id of the Agent", + NO_PRODUCT_CODE, + winget_uninstall("Devolutions.Agent"), + ), + ( + "the WinGet id in another case", + NO_PRODUCT_CODE, + winget_uninstall("devolutions.AGENT"), + ), + ( + "the WinGet id before the first `#`", + NO_PRODUCT_CODE, + winget_uninstall("Devolutions.Agent#main"), + ), + ( + "the WinGet id before the last `@`", + NO_PRODUCT_CODE, + winget_uninstall("Devolutions.Agent@2026.1.0"), + ), + ( + "the WinGet id before the last `@` of what the first `#` leaves", + NO_PRODUCT_CODE, + winget_uninstall("Devolutions.Agent@1#a@b#c"), + ), + ( + "an uninstall of the Chocolatey id of the Agent", + NO_PRODUCT_CODE, + chocolatey("Uninstall", "devo-agent"), + ), + ( + "the Chocolatey id in another case before an `@`", + NO_PRODUCT_CODE, + chocolatey("Uninstall", "Devo-Agent@2026.1.0"), + ), + ( + "a WinGet id that contains the product code in another case", + AGENT_PRODUCT_CODE, + winget_uninstall("ARP/Machine/X64/{0F2A6B3C-4D5E-4F60-8A9B-0C1D2E3F4A5B}"), + ), + ( + "an install of the Agent with UninstallPrevious", + NO_PRODUCT_CODE, + with_uninstall_previous(serde_json::json!({ "Package": { "Id": "Devolutions.Agent" } })), + ), + ( + "an update of the Agent with UninstallPrevious", + NO_PRODUCT_CODE, + with_uninstall_previous(chocolatey("Update", "devo-agent")), + ), + ( + "an uninstall of another package through any manager while the product code cannot be read", + UNREADABLE_PRODUCT_CODE, + serde_json::json!({ + "Operation": "Uninstall", + "Manager": "Npm", + "Source": { "Name": "npm" }, + "Package": { "Id": "left-pad" }, + }), + ), + ( + "an install of another package with UninstallPrevious while the product code cannot be read", + UNREADABLE_PRODUCT_CODE, + with_uninstall_previous(serde_json::json!({})), + ), + ]; + + for (case, agent_product_code, members) in cases { + for (path, request) in [ + (EVALUATE, package_request(members.clone())), + (EXECUTE, execution_request("request-1", members.clone())), + ] { + // In audit mode, the policy denies no request that the broker reads. + let broker = Broker::from_state(BrokerState { + agent_product_code, + ..state_with_policy("[]", AUDIT_MODE) + }); + + let reply = send(&broker.state, &client(), post_value(path, &request)).await; + + assert_eq!(reply.body["Code"], "ProtectedPackage", "{case} at {path}: {reply:?}"); + reply.assert_error(422, "ProtectedPackage"); + assert_eq!(broker.runs().await, 0, "{case} at {path}"); + } + } +} + +// oracle: contract Devolutions/now-libraries@3014fcbb899d:policies/CONTRACT.wire.md §protected-package +#[tokio::test] +async fn a_request_that_is_no_protected_uninstall_is_evaluated() { + let cases: [(&str, AgentProductCode, serde_json::Value); 10] = [ + ( + "an install of the Agent while the product code cannot be read", + UNREADABLE_PRODUCT_CODE, + serde_json::json!({ "Package": { "Id": "Devolutions.Agent" } }), + ), + ( + "an update of the Agent while the product code cannot be read", + UNREADABLE_PRODUCT_CODE, + chocolatey("Update", "devo-agent"), + ), + ( + "an uninstall of another package", + AGENT_PRODUCT_CODE, + winget_uninstall("Git.Git"), + ), + ( + "an uninstall of the WinGet id of the Agent through Chocolatey", + NO_PRODUCT_CODE, + chocolatey("Uninstall", "Devolutions.Agent"), + ), + ( + "an uninstall of the Chocolatey id of the Agent through WinGet", + NO_PRODUCT_CODE, + winget_uninstall("devo-agent"), + ), + ( + "an uninstall of an id that goes on after the WinGet id of the Agent", + NO_PRODUCT_CODE, + winget_uninstall("Devolutions.Agent.Tools"), + ), + ( + "an uninstall of an id that has the WinGet id of the Agent after a `#`", + NO_PRODUCT_CODE, + winget_uninstall("other#Devolutions.Agent"), + ), + ( + "an uninstall through Chocolatey of an id that contains the product code", + AGENT_PRODUCT_CODE, + chocolatey("Uninstall", "{0f2a6b3c-4d5e-4f60-8a9b-0c1d2e3f4a5b}"), + ), + ( + "an uninstall of a WinGet id that contains the product code without its hyphens", + AGENT_PRODUCT_CODE, + winget_uninstall("{0f2a6b3c4d5e4f608a9b0c1d2e3f4a5b}"), + ), + ( + "an uninstall of a WinGet id that contains a product code while no Agent is installed", + NO_PRODUCT_CODE, + winget_uninstall("{0f2a6b3c-4d5e-4f60-8a9b-0c1d2e3f4a5b}"), + ), + ]; + + for (case, agent_product_code, members) in cases { + let state = Arc::new(BrokerState { + agent_product_code, + ..state_with_policy("[]", AUDIT_MODE) + }); + + let reply = send(&state, &client(), post_value(EVALUATE, &package_request(members))).await; + + assert_eq!(reply.status, 200, "{case}: {reply:?}"); + assert_eq!( + reply.members(), + ["Decision", "EvaluatedAt", "Policy"], + "{case}: {reply:?}" + ); + } +} + +// oracle: mutant reading the product code of the installed Devolutions Agent for a request that removes no package +#[tokio::test] +async fn a_request_that_removes_no_package_reads_no_product_code() { + let broker = Broker::from_state(BrokerState { + agent_product_code: || panic!("the broker read the product code"), + ..state_with_policy(ALLOW_ALL, "") + }); + + let evaluated = send( + &broker.state, + &client(), + post_value(EVALUATE, &package_request(serde_json::json!({}))), + ) + .await; + assert_eq!(evaluated.status, 200, "{evaluated:?}"); + broker + .start(&execution_request("request-1", serde_json::json!({}))) + .await; + start_bypass(&broker, TOKEN, &bypass_request("request-1", serde_json::json!({}))).await; +} + +// oracle: contract Devolutions/now-libraries@3014fcbb899d:policies/CONTRACT.wire.md §evaluate +#[tokio::test] +async fn protected_package_comes_before_the_other_outcomes_of_an_evaluation() { + // A broker without an accepted policy answers a request that is no protected uninstall `PolicyUnavailable`. + let without_policy = Arc::new(state()); + let reply = send( + &without_policy, + &client(), + post_value(EVALUATE, &package_request(winget_uninstall("Devolutions.Agent"))), + ) + .await; + reply.assert_error(422, "ProtectedPackage"); + + // An allowed request with a command for an elevated run is `NotRunnable` when it is no protected uninstall. + let allowing = Arc::new(state_with_policy(ALLOW_WITH_OPT_INS, "")); + let uninstall_with_a_command = |id: &str| { + let mut members = elevated_with_a_command(); + members["Operation"] = serde_json::json!("Uninstall"); + members["Package"] = serde_json::json!({ "Id": id }); + post_value(EVALUATE, &package_request(members)) + }; + let other = send(&allowing, &client(), uninstall_with_a_command("Git.Git")).await; + let agent = send(&allowing, &client(), uninstall_with_a_command("Devolutions.Agent")).await; + assert_eq!(other.body["Code"], "NotRunnable", "{other:?}"); + agent.assert_error(422, "ProtectedPackage"); +} + +// oracle: contract Devolutions/now-libraries@3014fcbb899d:policies/CONTRACT.wire.md §execute +#[tokio::test] +async fn protected_package_comes_after_a_used_request_id_and_before_the_other_outcomes_of_an_execution() { + let broker = Broker::with_policy(ALLOW_ALL, ""); + let first = broker.start(&uninstall("Git.Git")).await; + // The same broker once it cannot read the product code of the installed Agent: every request that removes a + // package is a protected uninstall then. + let unreadable = Arc::new(BrokerState { + operations: broker.state.operations.clone(), + agent_product_code: UNREADABLE_PRODUCT_CODE, + ..state_with_policy(ALLOW_ALL, "") + }); + + let replay = send(&unreadable, &client(), post_value(EXECUTE, &uninstall("Git.Git"))).await; + let conflict = send( + &unreadable, + &client(), + post_value(EXECUTE, &uninstall("Devolutions.Agent")), + ) + .await; + let mut with_an_unused_id = uninstall("Git.Git"); + with_an_unused_id["RequestId"] = serde_json::json!("request-2"); + let protected = send(&unreadable, &client(), post_value(EXECUTE, &with_an_unused_id)).await; + + assert_eq!(replay.status, 200, "{replay:?}"); + assert_eq!(replay.body["OperationId"], first.body["OperationId"]); + conflict.assert_error(409, "RequestIdConflict"); + protected.assert_error(422, "ProtectedPackage"); + assert_eq!(broker.runs().await, 1); + + // A broker without an accepted policy answers a request that is no protected uninstall `PolicyUnavailable`. + let without_policy = Broker::from_state(state()); + let reply = send( + &without_policy.state, + &client(), + post_value(EXECUTE, &uninstall("Devolutions.Agent")), + ) + .await; + reply.assert_error(422, "ProtectedPackage"); + + // An allowed request with a command for an elevated run is `NotRunnable` when it is no protected uninstall. + let allowing = Broker::with_policy(ALLOW_WITH_OPT_INS, ""); + let uninstall_with_a_command = |id: &str| { + let mut members = elevated_with_a_command(); + members["Operation"] = serde_json::json!("Uninstall"); + members["Package"] = serde_json::json!({ "Id": id }); + post_value(EXECUTE, &execution_request("request-1", members)) + }; + let other = send(&allowing.state, &client(), uninstall_with_a_command("Git.Git")).await; + let agent = send( + &allowing.state, + &client(), + uninstall_with_a_command("Devolutions.Agent"), + ) + .await; + assert_eq!(other.body["Code"], "NotRunnable", "{other:?}"); + agent.assert_error(422, "ProtectedPackage"); + assert_eq!(allowing.runs().await, 0); +} + +// oracle: contract Devolutions/now-libraries@3014fcbb899d:policies/CONTRACT.wire.md §execute +#[tokio::test] +async fn a_protected_uninstall_starts_no_operation_and_leaves_its_request_id_unused() { + let broker = Broker::with_policy(ALLOW_ALL, ""); + + let protected = send( + &broker.state, + &client(), + post_value(EXECUTE, &uninstall("Devolutions.Agent")), + ) + .await; + + protected.assert_error(422, "ProtectedPackage"); + assert_eq!(broker.runs().await, 0); + // The request id is unused, so another package request with it starts an operation and does not conflict. + broker + .start(&execution_request("request-1", serde_json::json!({}))) + .await; + assert_eq!(broker.runs().await, 1); +} + const MANAGEMENT: &str = "/v2/policy/management"; /// A broker that reads `file` as its policy file. From 50c4dc8736ccf45ef14cdc893389f8ec153f435a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Wed, 2 Dec 2026 04:48:48 +0900 Subject: [PATCH 26/38] test(agent): cite the wire contract for the 60 seconds of a bypass token The wire contract now states how long the broker holds a bypass token: it discards one no later than 60 seconds after the Agent gave it, remembers a used-up one until then, and takes a token with the same characters given after that for a new token. The token store already does this, so its tests now name the contract as the source of these instants instead of pinning them as the broker's own choice, and one test follows a used-up token across the 60 seconds. What the contract leaves to the broker, the exact instant a lifetime ends and how a remembered token counts against the bound, stays pinned as such. The comments of the store and of the bypass route say the same, and the route names what a token digest cannot tell apart while the broker holds the operation an earlier token started. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- .../src/v2/bypass/tokens.rs | 66 +++++++++++++++---- .../src/v2/routes/bypass.rs | 7 +- 2 files changed, 57 insertions(+), 16 deletions(-) diff --git a/crates/now-package-broker/src/v2/bypass/tokens.rs b/crates/now-package-broker/src/v2/bypass/tokens.rs index 02902facb..b74964f1b 100644 --- a/crates/now-package-broker/src/v2/bypass/tokens.rs +++ b/crates/now-package-broker/src/v2/bypass/tokens.rs @@ -10,11 +10,12 @@ use parking_lot::{Mutex, MutexGuard}; use sha2::{Digest as _, Sha256}; use win_api_wrappers::identity::sid::Sid; -/// How long the broker holds a token that no request used up, after which it discards it. +/// How long after the Agent gave it the broker discards a token that no request used up, and forgets one that a +/// request used up ([§bypass]). /// -/// A token authorizes one request that the Agent expects at once, so a short life bounds how long a token that -/// reached another process stays useful. -/// The broker remembers a token that a request used up until the same moment. +/// The contract lets the broker discard an unused token earlier, and the broker holds it for the whole of this time. +/// +/// [§bypass]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#bypass const TOKEN_LIFETIME: Duration = Duration::from_secs(60); /// The most tokens the broker holds at once, so that the tokens it is given never grow its memory without bound. @@ -96,11 +97,11 @@ impl BypassTokens { /// This is how Devolutions Agent gives the broker a token. /// /// The broker remembers a token that a request used up until the lifetime it was held with ends, and refuses to - /// hold it until then, so a used-up token authorizes nothing when it is given again ([§bypass]). + /// hold it until then, so a used-up token authorizes nothing when it is given again. + /// Once that lifetime has ended the broker remembers nothing of the token, and a token with the same characters + /// is a new token, which it holds ([§bypass]). /// - /// The caller never gives a token twice. - /// The broker cannot check this: once the lifetime of a token has ended it remembers nothing of the token, so a - /// used-up token given again after that is held as a new one. + /// A token the broker still holds is not held again either, and keeps what it binds. /// /// [§bypass]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#bypass #[cfg_attr( @@ -323,7 +324,6 @@ mod tests { assert!(!tokens.lock().authorizes(&digest(TOKEN), &user(), &bound)); } - // oracle: mutant holding a token past its lifetime, or discarding it before #[test] fn a_token_is_discarded_when_its_lifetime_ends() { let tokens = BypassTokens::default(); @@ -333,11 +333,14 @@ mod tests { .expect("hold the token"); let bound = request(&install()); + // oracle: mutant discarding a token before its lifetime ends let just_before = given + TOKEN_LIFETIME - Duration::from_millis(1); assert!(tokens.lock_at(just_before).authorizes(&digest(TOKEN), &user(), &bound)); + // oracle: contract Devolutions/now-libraries@3014fcbb899d:policies/CONTRACT.wire.md §bypass + let sixty_seconds_after = given + Duration::from_secs(60); assert!( !tokens - .lock_at(given + TOKEN_LIFETIME) + .lock_at(sixty_seconds_after) .authorizes(&digest(TOKEN), &user(), &bound) ); } @@ -388,9 +391,46 @@ mod tests { assert!(!tokens.lock().authorizes(&digest(TOKEN), &other_user(), &other)); } - // oracle: mutant forgetting a used-up token before the lifetime it was held with ends, or leaving it out of the bound on held tokens, or remembering it once that lifetime has ended + // oracle: contract Devolutions/now-libraries@3014fcbb899d:policies/CONTRACT.wire.md §bypass #[test] - fn a_used_up_token_is_remembered_and_counted_until_the_lifetime_it_was_held_with_ends() { + fn a_used_up_token_is_remembered_until_60_seconds_after_it_was_given_and_is_a_new_token_after_that() { + let tokens = BypassTokens::default(); + let given = Instant::now(); + tokens + .hold_at(given, TOKEN, request(&install()), user()) + .expect("hold the token"); + // The 60 seconds run from when the token was given, not from when it was used up. + tokens.lock_at(given + Duration::from_secs(45)).use_up(&digest(TOKEN)); + let other = request(&with(install(), "RequestId", serde_json::json!("request-2"))); + + let while_remembered = given + Duration::from_secs(60) - Duration::from_millis(1); + let again = tokens.hold_at(while_remembered, TOKEN, other.clone(), other_user()); + let authorizes_while_remembered = + tokens + .lock_at(while_remembered) + .authorizes(&digest(TOKEN), &other_user(), &other); + let after_that = given + Duration::from_secs(61); + let as_a_new_token = tokens.hold_at(after_that, TOKEN, other.clone(), other_user()); + + assert!(again.is_err(), "the broker held a used-up token it remembers"); + assert!(!authorizes_while_remembered); + assert_eq!(as_a_new_token, Ok(())); + // The new token authorizes the request it binds, and not the one the used-up token bound. + assert!( + tokens + .lock_at(after_that) + .authorizes(&digest(TOKEN), &other_user(), &other) + ); + assert!( + !tokens + .lock_at(after_that) + .authorizes(&digest(TOKEN), &user(), &request(&install())) + ); + } + + // oracle: mutant leaving a used-up token the broker remembers out of the bound on held tokens, or remembering it at the instant the lifetime it was held with ends + #[test] + fn a_used_up_token_is_counted_until_the_lifetime_it_was_held_with_ends() { let tokens = BypassTokens::default(); let given = Instant::now(); for index in 0..MAX_HELD_TOKENS { @@ -401,11 +441,9 @@ mod tests { tokens.lock_at(given + TOKEN_LIFETIME / 2).use_up(&digest("token-0")); let just_before = given + TOKEN_LIFETIME - Duration::from_millis(1); - let again = tokens.hold_at(just_before, "token-0", request(&install()), user()); let one_more = tokens.hold_at(just_before, "one-more", request(&install()), user()); let after_its_lifetime = tokens.hold_at(given + TOKEN_LIFETIME, "token-0", request(&install()), user()); - assert_eq!(again, Err(HoldError::AlreadyHeld)); assert_eq!(one_more, Err(HoldError::TooManyTokens)); assert_eq!(after_its_lifetime, Ok(())); } diff --git a/crates/now-package-broker/src/v2/routes/bypass.rs b/crates/now-package-broker/src/v2/routes/bypass.rs index 0d112d019..04e7a7100 100644 --- a/crates/now-package-broker/src/v2/routes/bypass.rs +++ b/crates/now-package-broker/src/v2/routes/bypass.rs @@ -47,8 +47,11 @@ impl Connection { // The token started the operation of another request of this owner, so it is used up, and the request is // refused without asking what the token authorizes. // For a request of another owner, and once the broker no longer holds that operation, the tokens answer: - // a used-up token authorizes nothing, and is not held again within the lifetime it was held with, but - // nothing tells one given again after that from a new token (`BypassTokens::hold`). + // a used-up token authorizes nothing, and is not held again while the broker remembers it + // (`BypassTokens::hold`). + // A token with the same characters that the Agent gives after that is a new token, which its digest does + // not tell from this one: while the broker holds this operation, a request of this owner with the new + // token is answered here and above, as one with the token that started the operation. Some(Existing::Conflict) => return token_rejected(), None => {} } From 16871b631c5390207920fa26528e3b2101db27b4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Wed, 2 Dec 2026 04:49:22 +0900 Subject: [PATCH 27/38] docs(agent): mark what keeps a Completed status of the 2.0 routes readable A client refuses the status of a `Completed` operation that has no `StartedAt`, since a manager process that exited on its own was launched. The status route copies what the registry recorded, and the registry records a launch only when the executor reports one, so the response depends on a property of the executor that no test checks. The comment names that property where the response is built. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- crates/now-package-broker/src/v2/routes/operations.rs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/crates/now-package-broker/src/v2/routes/operations.rs b/crates/now-package-broker/src/v2/routes/operations.rs index cb5ac7f6a..d17f54109 100644 --- a/crates/now-package-broker/src/v2/routes/operations.rs +++ b/crates/now-package-broker/src/v2/routes/operations.rs @@ -179,6 +179,15 @@ fn execution_response(decided: Decided, operation: Option<(String, Status, Optio ) } +// UNTESTED: The response of a `Completed` operation has `StartedAt`. +// A manager process that exited on its own was launched, so a client refuses a `Completed` status without the time +// of its launch ([§status]), and then knows nothing of how the operation ended. +// The registry records a launch only when the executor reports one, and the executor of the broker reports the +// launch of every process whose exit it returns. +// No test checks this of that executor; when changing an executor, or how the registry records a launch, check that +// no exit comes without a launch. +// +// [§status]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#status fn status_response(state: OperationState) -> Result { Ok(v2::StatusResponse { status: operation_status(state.status), From 31160652099cec9a41b2426b9bdb23a8a0b01f47 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Wed, 2 Dec 2026 04:50:36 +0900 Subject: [PATCH 28/38] docs(agent): cite the wire contract for the pause and the closing of the event channel The wire contract now states that the broker does not listen on the event pipe for one second after it closes a connection it does not serve, that opening the pipe fails with a busy pipe meanwhile, and that the broker closes the channel when a failure leaves it unable to tell which process is connected. The channel already behaves so, and its tests pinned the pause and the busy pipe as the broker's own choice: they now name the contract as their source, and the comments at the pause and at the exits that give the pipe up name the section that decides them. No test of the pause runs with the value the broker uses, which a comment at that value now says. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- crates/now-package-broker/src/event_channel.rs | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/crates/now-package-broker/src/event_channel.rs b/crates/now-package-broker/src/event_channel.rs index fc431a415..438d2fc67 100644 --- a/crates/now-package-broker/src/event_channel.rs +++ b/crates/now-package-broker/src/event_channel.rs @@ -576,13 +576,19 @@ mod windows_channel { /// the kernel pipe buffer is full, i.e. the client stopped reading. const WRITE_STALL_TIMEOUT: Duration = Duration::from_secs(30); - /// After the channel refused a connection, how long it waits before its pipe listens again. + /// After the channel refused a connection, how long its pipe does not listen ([§event-channel]). /// /// Telling who a client is costs the broker far more than connecting costs a client, so a process that connects in /// a loop would otherwise keep a thread of the broker busy. /// The pipe does not listen during the wait: a client that opens it then gets a busy pipe, not a late first frame. /// A pipe that listened would let a client connect up to this long before the channel tells who it is, and the /// process that connected could be gone by then, with its id given to another process. + /// + /// [§event-channel]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#event-channel + // UNTESTED: The pause of a channel of the broker is the one second the contract states. + // A shorter one lets a process that keeps connecting make the broker identify it more often than the contract + // allows, and a longer one keeps the pipe busy for the owner longer than the contract says. + // Every test of the pause gives its channel another one; when changing this value, check it against the contract. const REFUSAL_PAUSE: Duration = Duration::from_secs(1); /// How long the channel waits for the read of a refused connection to end once it closed the connection, after @@ -853,6 +859,8 @@ mod windows_channel { // error at once, which drops the pipe, and the caller closes the queue. // After any of them the channel no longer knows who its pipe is connected to, and the frames it would // write next could reach a client it refused. + // These are the failures for which the contract has the broker close the channel (CONTRACT.wire.md + // §event-channel). // No test makes a pipe fail in these ways; when changing this function, check that none of these exits // listens again or returns the pipe. connected.context("failed to listen on the event pipe")?; @@ -1841,7 +1849,7 @@ pub(crate) mod pipe_tests { assert!(closed.is_err(), "the channel closed its end first: {closed:?}"); } - // oracle: mutant listening on the pipe during the pause after a refusal, so that a client connects long before the channel identifies it + // oracle: contract Devolutions/now-libraries@3014fcbb899d:policies/CONTRACT.wire.md §event-channel #[tokio::test] async fn the_pipe_of_a_channel_is_busy_during_the_pause_after_a_refusal() { // The pause does not end while the test runs. @@ -1859,7 +1867,8 @@ pub(crate) mod pipe_tests { } } - // oracle: mutant identifying the client of a connection less than one pause after it refused another + // oracle: contract Devolutions/now-libraries@3014fcbb899d:policies/CONTRACT.wire.md §event-channel + // The pipe does not listen for the pause, so no client connects, and none is identified, before the pause ends. #[tokio::test] async fn the_channel_identifies_no_client_within_one_pause_of_a_refusal() { const PAUSE: Duration = Duration::from_millis(300); @@ -1922,6 +1931,8 @@ pub(crate) mod pipe_tests { sink.stdout(b"output"); let received = bytes_of_a_closed_connection(&pipe_name).await; + // oracle: contract Devolutions/now-libraries@3014fcbb899d:policies/CONTRACT.wire.md §event-channel + // The broker closes the channel of an identification that does not complete. pipe_is_gone(&pipe_name).await; let queue_closed = tokio::time::timeout(Duration::from_secs(10), sink.finished()).await; sink.stdout(b"more output"); From c973be552fe51a0b22dbfdd77912212804f142c6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Wed, 2 Dec 2026 05:05:26 +0900 Subject: [PATCH 29/38] test(agent): name the reply of a protected execution without a policy for what it shows The test of where `ProtectedPackage` falls among the outcomes of an execution named two replies `replay` and `reply`, which clippy refuses as too similar and which told a reader nothing of the second. It is the reply that comes before the policy is looked at, and is named so. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- crates/now-package-broker/src/v2/routes/tests.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/now-package-broker/src/v2/routes/tests.rs b/crates/now-package-broker/src/v2/routes/tests.rs index 898b7e195..10b789c0e 100644 --- a/crates/now-package-broker/src/v2/routes/tests.rs +++ b/crates/now-package-broker/src/v2/routes/tests.rs @@ -2426,13 +2426,13 @@ async fn protected_package_comes_after_a_used_request_id_and_before_the_other_ou // A broker without an accepted policy answers a request that is no protected uninstall `PolicyUnavailable`. let without_policy = Broker::from_state(state()); - let reply = send( + let before_the_policy = send( &without_policy.state, &client(), post_value(EXECUTE, &uninstall("Devolutions.Agent")), ) .await; - reply.assert_error(422, "ProtectedPackage"); + before_the_policy.assert_error(422, "ProtectedPackage"); // An allowed request with a command for an elevated run is `NotRunnable` when it is no protected uninstall. let allowing = Broker::with_policy(ALLOW_WITH_OPT_INS, ""); From 1c64dd4dda8ef04ea1ab4bbc64ac45497d4c9d05 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Wed, 2 Dec 2026 05:25:35 +0900 Subject: [PATCH 30/38] refactor(agent): lend the pipe of an event channel to the identification of its client The identification of the client connected to an event channel owned the pipe for as long as it ran, so the channel could do nothing with its pipe until the identification returned. The channel now keeps the pipe and lends it: the identification reaches it through the channel each time it asks the pipe something, and the channel takes it back once the identification is over. What the channel sends, and how a client is identified, do not change. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- .../now-package-broker/src/event_channel.rs | 50 +++++++++++++++---- .../src/v2/execution/operations.rs | 5 +- .../now-package-broker/src/v2/routes/held.rs | 5 +- 3 files changed, 47 insertions(+), 13 deletions(-) diff --git a/crates/now-package-broker/src/event_channel.rs b/crates/now-package-broker/src/event_channel.rs index 438d2fc67..95c15de2c 100644 --- a/crates/now-package-broker/src/event_channel.rs +++ b/crates/now-package-broker/src/event_channel.rs @@ -539,7 +539,8 @@ impl ChannelVersion { #[cfg(windows)] pub use windows_channel::{ - AdmitClient, Audience, open_operation_channel, open_operation_channel_announcing, open_operation_channel_serving, + AdmitClient, Audience, ChannelPipe, open_operation_channel, open_operation_channel_announcing, + open_operation_channel_serving, }; #[cfg(windows)] @@ -595,11 +596,40 @@ mod windows_channel { /// which it gives the pipe up. const REFUSED_READ_TIMEOUT: Duration = Duration::from_secs(5); + /// The pipe of a channel, for the identification of the client connected to it. + /// + /// The identification reaches the pipe through [`ChannelPipe::with`] only, so the pipe is the channel's to take + /// back whenever the identification asks it nothing. + pub struct ChannelPipe { + /// The pipe, until the channel takes it back. + server: parking_lot::Mutex>, + } + + impl ChannelPipe { + fn holding(server: NamedPipeServer) -> Self { + Self { + server: parking_lot::Mutex::new(Some(server)), + } + } + + /// Returns what `query` returns for the pipe, or `None` once the channel took the pipe back. + /// + /// The channel cannot take the pipe back while `query` runs, so `query` asks the pipe one thing and returns. + pub fn with(&self, query: impl FnOnce(&NamedPipeServer) -> T) -> Option { + self.server.lock().as_ref().map(query) + } + + /// Takes the pipe back. + fn take(&self) -> Option { + self.server.lock().take() + } + } + /// Tells whether the client of a connected event pipe is one the channel sends its frames to. /// /// The channel calls it off the async runtime, so it may block. /// A channel in which it panics serves nobody. - pub type AdmitClient = Arc bool + Send + Sync>; + pub type AdmitClient = Arc bool + Send + Sync>; /// The connections an event channel sends its frames on ([§event-channel]). /// @@ -878,18 +908,20 @@ mod windows_channel { // which the channel would then identify in its place. // No test bounds that time; when changing this function, keep every wait, the pause after a refusal // included, out of the lines between the connection and this call. + let pipe = Arc::new(ChannelPipe::holding(server)); let admission = tokio::task::spawn_blocking({ let admit = Arc::clone(admit); - move || { - let admitted = admit(&server); - (server, admitted) - } + let pipe = Arc::clone(&pipe); + move || admit(&pipe) }); - let admitted; - // An identification that panics drops the pipe with its task, so the channel serves nobody. - (server, admitted) = admission + // An identification that panics leaves the pipe to this function, which drops it with the error it + // returns, so the channel serves nobody. + let admitted = admission .await .context("failed to tell whether the event channel admits a client")?; + server = pipe + .take() + .context("the event channel no longer holds the pipe of the client it identified")?; if admitted { return Ok(Some(server)); } diff --git a/crates/now-package-broker/src/v2/execution/operations.rs b/crates/now-package-broker/src/v2/execution/operations.rs index a1f859f57..151401a46 100644 --- a/crates/now-package-broker/src/v2/execution/operations.rs +++ b/crates/now-package-broker/src/v2/execution/operations.rs @@ -7,14 +7,13 @@ use std::time::{Duration, Instant}; use chrono::{DateTime, Utc}; use now_policy_eval::Request; use parking_lot::Mutex; -use tokio::net::windows::named_pipe::NamedPipeServer; use tokio_util::sync::CancellationToken; use tracing::{debug, info, warn}; use uuid::Uuid; use super::owner::Owner; use super::plan::plan_protecting_agent; -use crate::event_channel::{Audience, ChannelVersion, OperationEventSink, open_operation_channel_serving}; +use crate::event_channel::{Audience, ChannelPipe, ChannelVersion, OperationEventSink, open_operation_channel_serving}; use crate::executor::{ CommandExecutor, ExecutionContext, ProcessStartedCallback, TokenElevationCheck, is_canceled_error, }; @@ -144,7 +143,7 @@ pub struct Operations { /// It may block. /// /// [§authentication]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#authentication -pub type IdentifyPipeClient = Arc anyhow::Result + Send + Sync>; +pub type IdentifyPipeClient = Arc anyhow::Result + Send + Sync>; /// The connections on which the event channels of a registry send their frames ([§event-channel]). /// diff --git a/crates/now-package-broker/src/v2/routes/held.rs b/crates/now-package-broker/src/v2/routes/held.rs index 8a47116b6..7d3913ca3 100644 --- a/crates/now-package-broker/src/v2/routes/held.rs +++ b/crates/now-package-broker/src/v2/routes/held.rs @@ -6,6 +6,7 @@ use std::sync::{Arc, OnceLock}; +use anyhow::Context as _; use now_policy_api::v2; use tokio_util::sync::CancellationToken; @@ -108,7 +109,9 @@ impl HeldOperations { // without the broker seeing it. fn identify_event_client(skip_signature_validation: bool) -> IdentifyPipeClient { Arc::new(move |pipe| { - let client = PipeClient::from_connected_pipe(pipe)?; + let client = pipe + .with(PipeClient::from_connected_pipe) + .context("the event channel took its pipe back")??; client.validate_connection(skip_signature_validation)?; Ok(owner_of(&client)) From 91088ed45a481c515396bb1b8d311955b0064d67 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Wed, 2 Dec 2026 05:32:23 +0900 Subject: [PATCH 31/38] feat(agent): close an event channel whose identification of a client does not complete The wire contract has the broker close an event channel when the identification of a process connected to its pipe does not complete, since the broker then cannot tell which process is connected. The channel waited for the identification for as long as it ran, so one that never returned left the pipe connected to a client the channel knew nothing of, and busy for every other client, for as long as the broker ran. The channel now waits 30 seconds for the identification of a client. When they pass it closes its pipe at once, sends no frame and closes its queue, as it does when the identification panics. It does not wait for the identification, which reaches the pipe through the channel and finds none from then on; a pipe that the identification is asking something at that instant closes as soon as it has answered. The channels that identify no client are unchanged. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- .../now-package-broker/src/event_channel.rs | 196 ++++++++++++++++-- 1 file changed, 179 insertions(+), 17 deletions(-) diff --git a/crates/now-package-broker/src/event_channel.rs b/crates/now-package-broker/src/event_channel.rs index 95c15de2c..a3dc3704f 100644 --- a/crates/now-package-broker/src/event_channel.rs +++ b/crates/now-package-broker/src/event_channel.rs @@ -546,6 +546,7 @@ pub use windows_channel::{ #[cfg(windows)] mod windows_channel { use std::sync::Arc; + use std::sync::atomic::{AtomicBool, Ordering}; use std::time::Duration; use anyhow::Context as _; @@ -596,39 +597,83 @@ mod windows_channel { /// which it gives the pipe up. const REFUSED_READ_TIMEOUT: Duration = Duration::from_secs(5); + /// How long the channel waits for the identification of a client connected to its pipe to complete, after which + /// it gives the pipe up ([§event-channel]). + /// + /// An identification that does not complete would otherwise leave the pipe connected to a client the channel + /// knows nothing of, and busy for every other client, for as long as the broker runs. + /// An identification reads the executable of the client and validates its signature, which can take seconds, so + /// the deadline is well above that. + /// It is below the 60 seconds that the channel of an ended operation lives without a client it serves, which an + /// identification makes later by its length at most. + /// + /// [§event-channel]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#event-channel + // UNTESTED: The deadline of a channel of the broker is longer than an identification that completes takes, and + // shorter than the 60 seconds the channel of an ended operation lives. + // A shorter one closes the channel of an owner whose identification is slow, who then reads no output of the + // operation; a longer one keeps a pipe that serves nobody busy for longer than a channel without a client lives. + // Every test of the deadline gives its channel another one; when changing this value, check it against the time + // the identification of a signed client takes on a loaded machine. + const IDENTIFICATION_DEADLINE: Duration = Duration::from_secs(30); + /// The pipe of a channel, for the identification of the client connected to it. /// /// The identification reaches the pipe through [`ChannelPipe::with`] only, so the pipe is the channel's to take - /// back whenever the identification asks it nothing. + /// back or to close whenever the identification asks it nothing, whether or not the identification ever returns. pub struct ChannelPipe { - /// The pipe, until the channel takes it back. + /// The pipe, until the channel takes it back or gives it up. server: parking_lot::Mutex>, + /// Whether the channel gave the pipe up. + given_up: AtomicBool, } impl ChannelPipe { fn holding(server: NamedPipeServer) -> Self { Self { server: parking_lot::Mutex::new(Some(server)), + given_up: AtomicBool::new(false), } } - /// Returns what `query` returns for the pipe, or `None` once the channel took the pipe back. + /// Returns what `query` returns for the pipe, or `None` once the channel took the pipe back or gave it up. /// - /// The channel cannot take the pipe back while `query` runs, so `query` asks the pipe one thing and returns. + /// The pipe stays open while `query` runs, so `query` asks the pipe one thing and returns. pub fn with(&self, query: impl FnOnce(&NamedPipeServer) -> T) -> Option { - self.server.lock().as_ref().map(query) + let answer = self.server.lock().as_ref().map(query); + // A channel that gave the pipe up while `query` ran could not close it, so it is closed here. + // + // UNTESTED: Once the channel gave the pipe up, the pipe is closed whenever no query of it runs. + // A pipe left open then stays connected and busy until the identification returns, which it may never do. + // The pipe is unlocked before this looks at the mark, and the channel sets the mark before it tries the + // lock, so one of the two closes the pipe however they interleave. + // The test of a pipe given up during a query does not make them race; when changing this function or + // `give_up`, keep these two orders. + if self.given_up.load(Ordering::SeqCst) { + self.server.lock().take(); + } + + answer } /// Takes the pipe back. fn take(&self) -> Option { self.server.lock().take() } + + /// Closes the pipe without waiting for the identification: now, or as soon as the query of the pipe that + /// runs now returns. + fn give_up(&self) { + self.given_up.store(true, Ordering::SeqCst); + if let Some(mut server) = self.server.try_lock() { + server.take(); + } + } } /// Tells whether the client of a connected event pipe is one the channel sends its frames to. /// /// The channel calls it off the async runtime, so it may block. - /// A channel in which it panics serves nobody. + /// A channel in which it panics, or does not return before the deadline of the channel, serves nobody. pub type AdmitClient = Arc bool + Send + Sync>; /// The connections an event channel sends its frames on ([§event-channel]). @@ -681,15 +726,25 @@ mod windows_channel { operation_id: &str, client_sid: &Sid, ) -> anyhow::Result<(OperationEventSink, EventChannel)> { - open_operation_channel_pausing(audience, REFUSAL_PAUSE, version, operation_id, client_sid) + open_operation_channel_pausing( + audience, + REFUSAL_PAUSE, + IDENTIFICATION_DEADLINE, + version, + operation_id, + client_sid, + ) } - /// Create the event channel for an operation, which waits `refusal_pause` after it refused a connection. + /// Create the event channel for an operation, which waits `refusal_pause` after it refused a connection, and + /// `identification_deadline` for the identification of a client to complete. /// - /// It is otherwise [`open_operation_channel_serving`], whose channels wait [`REFUSAL_PAUSE`]. + /// It is otherwise [`open_operation_channel_serving`], whose channels wait [`REFUSAL_PAUSE`] and + /// [`IDENTIFICATION_DEADLINE`]. pub(super) fn open_operation_channel_pausing( audience: Audience, refusal_pause: Duration, + identification_deadline: Duration, version: ChannelVersion, operation_id: &str, client_sid: &Sid, @@ -726,7 +781,16 @@ mod windows_channel { let writer_sink = sink.clone(); let operation_id = operation_id.to_owned(); tokio::spawn(async move { - run_channel(audience, refusal_pause, version, server, writer_sink, &operation_id).await; + run_channel( + audience, + refusal_pause, + identification_deadline, + version, + server, + writer_sink, + &operation_id, + ) + .await; }); Ok((sink, descriptor)) @@ -736,6 +800,7 @@ mod windows_channel { async fn run_channel( audience: Audience, refusal_pause: Duration, + identification_deadline: Duration, version: ChannelVersion, server: NamedPipeServer, sink: OperationEventSink, @@ -743,7 +808,17 @@ mod windows_channel { ) { let connected = match audience { Audience::FirstConnection => Ok(accept_first(server, &sink).await), - Audience::Admitted(admit) => accept_admitted(server, &sink, &admit, refusal_pause, operation_id).await, + Audience::Admitted(admit) => { + accept_admitted( + server, + &sink, + &admit, + refusal_pause, + identification_deadline, + operation_id, + ) + .await + } }; let mut server = match connected { Ok(Some(server)) => server, @@ -834,7 +909,8 @@ mod windows_channel { /// Waits for the first connection on `server` whose client `admit` admits, and returns the pipe connected to it. /// - /// The channel asks `admit` about a client as soon as that client is connected. + /// The channel asks `admit` about a client as soon as that client is connected, and waits + /// `identification_deadline` for the answer. /// After it refused a connection, its pipe listens again once `refusal_pause` has passed. /// /// Returns `Ok(None)` when no such client connects before the channel stops waiting for one. @@ -845,6 +921,7 @@ mod windows_channel { sink: &OperationEventSink, admit: &AdmitClient, refusal_pause: Duration, + identification_deadline: Duration, operation_id: &str, ) -> anyhow::Result> { // UNTESTED: The wait for the end of the channel is one wait for the whole loop: its 60 seconds start the first @@ -914,11 +991,19 @@ mod windows_channel { let pipe = Arc::clone(&pipe); move || admit(&pipe) }); - // An identification that panics leaves the pipe to this function, which drops it with the error it - // returns, so the channel serves nobody. - let admitted = admission - .await - .context("failed to tell whether the event channel admits a client")?; + let admitted = match tokio::time::timeout(identification_deadline, admission).await { + // An identification that panics leaves the pipe to this function, which drops it with the error it + // returns, so the channel serves nobody. + Ok(admitted) => admitted.context("failed to tell whether the event channel admits a client")?, + Err(_) => { + // The identification goes on, and nothing here waits for it to end. + pipe.give_up(); + anyhow::bail!( + "the identification of a client of the event channel did not complete within {identification_deadline:?}" + ); + } + }; + // Only a channel that gave its pipe up finds none, and it returned above. server = pipe .take() .context("the event channel no longer holds the pipe of the client it identified")?; @@ -1769,9 +1854,22 @@ pub(crate) mod pipe_tests { /// Opens the channel of a 2.0 operation like [`open_serving`], which waits `refusal_pause` after it refused a /// connection. fn open_pausing(audience: Audience, refusal_pause: Duration, tag: &str) -> (OperationEventSink, String) { + // The deadline does not pass while the test runs. + open_waiting(audience, refusal_pause, Duration::from_secs(600), tag) + } + + /// Opens the channel of a 2.0 operation like [`open_pausing`], which waits `identification_deadline` for the + /// identification of a client to complete. + fn open_waiting( + audience: Audience, + refusal_pause: Duration, + identification_deadline: Duration, + tag: &str, + ) -> (OperationEventSink, String) { let (sink, descriptor) = windows_channel::open_operation_channel_pausing( audience, refusal_pause, + identification_deadline, ChannelVersion::V2_0, &test_operation_id(tag), ¤t_user_sid(), @@ -1974,4 +2072,68 @@ pub(crate) mod pipe_tests { queue_closed.expect("the channel left its queue open"); assert_eq!(sink.next_frame().await, None); } + + /// An audience whose identification of a client returns once the sender it comes with is dropped, and not before. + fn never_identifying() -> (Audience, std::sync::mpsc::Sender<()>) { + let (until_dropped, dropped) = std::sync::mpsc::channel::<()>(); + let dropped = Mutex::new(dropped); + let audience = Audience::Admitted(Arc::new(move |_pipe| { + let _ = dropped.lock().expect("no identification panics").recv(); + true + })); + + (audience, until_dropped) + } + + // oracle: contract Devolutions/now-libraries@3014fcbb899d:policies/CONTRACT.wire.md §event-channel + #[tokio::test] + async fn a_channel_whose_identification_of_a_client_does_not_complete_sends_no_frame_and_gives_its_pipe_up() { + const DEADLINE: Duration = Duration::from_millis(300); + + // The identification runs until the test ends, so the channel never sees it complete. + let (audience, _until_the_test_ends) = never_identifying(); + let (sink, pipe_name) = open_waiting(audience, Duration::from_secs(600), DEADLINE, "no-identification"); + sink.stdout(b"output"); + + // Each of these waits ends within 10 seconds of the connection, while the identification still runs. + let received = bytes_of_a_closed_connection(&pipe_name).await; + pipe_is_gone(&pipe_name).await; + let queue_closed = tokio::time::timeout(Duration::from_secs(10), sink.finished()).await; + sink.stdout(b"more output"); + + assert_eq!(received, [0u8; 0]); + // oracle: mutant leaving open the queue of a channel that serves nobody, which goes on taking output that nobody reads + queue_closed.expect("the channel left its queue open"); + assert_eq!(sink.next_frame().await, None); + } + + // oracle: mutant keeping, until its identification returns, a pipe that the channel gave up while the identification asked the pipe something + #[tokio::test] + async fn a_pipe_given_up_while_the_identification_asks_it_something_closes_once_it_has_answered() { + const DEADLINE: Duration = Duration::from_millis(300); + + let (until_the_pipe_answers, answered) = std::sync::mpsc::channel::<()>(); + let (_until_the_test_ends, ended) = std::sync::mpsc::channel::<()>(); + let waits = Mutex::new((answered, ended)); + let audience = Audience::Admitted(Arc::new(move |pipe| { + let waits = waits.lock().expect("no identification panics"); + let (answered, ended) = &*waits; + pipe.with(|_pipe| { + let _ = answered.recv(); + }); + // The identification runs until the test ends, so the channel never sees it complete. + let _ = ended.recv(); + true + })); + let (sink, pipe_name) = open_waiting(audience, Duration::from_secs(600), DEADLINE, "asked"); + let _client = connect(&pipe_name).await; + + // The channel closes its queue as it gives its pipe up. + tokio::time::timeout(Duration::from_secs(10), sink.finished()) + .await + .expect("the deadline passes"); + drop(until_the_pipe_answers); + + pipe_is_gone(&pipe_name).await; + } } From 7e7b7e8a580a6398fb43203be5780765bc6a915c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Wed, 2 Dec 2026 05:34:05 +0900 Subject: [PATCH 32/38] fix(agent): keep the pipe of an event channel only to read the id of its client An event channel closes its pipe when the identification of a client does not complete in time, and cannot close it while the identification keeps it. The identification of the broker kept the pipe for the whole capture of the client process, which opens the executable of the client and checks who can write it, so a capture that never returned still left the pipe connected and busy. The capture asks the pipe one thing, the id of the client process, as it starts and once more before it returns. It now takes that question as a function, and the identification of an event channel answers it through the channel, which keeps the pipe only for the length of each answer. The capture of the client of a request is the same function with the pipe it is given, and does what it did. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- crates/now-package-broker/src/auth.rs | 19 +++++++++++++++---- .../now-package-broker/src/v2/routes/held.rs | 19 +++++++++++++------ 2 files changed, 28 insertions(+), 10 deletions(-) diff --git a/crates/now-package-broker/src/auth.rs b/crates/now-package-broker/src/auth.rs index 18bc894c3..cb770723e 100644 --- a/crates/now-package-broker/src/auth.rs +++ b/crates/now-package-broker/src/auth.rs @@ -95,7 +95,18 @@ impl PipeClient { /// must keep it off the accept loop and bound it with a connection permit. /// Account-name resolution remains deferred because it may contact a domain controller. pub(crate) fn from_connected_pipe(server: &NamedPipeServer) -> anyhow::Result { - let process_id = connected_pipe_client_process_id(server).context("failed to query pipe client process id")?; + Self::from_pipe_client_process(&|| connected_pipe_client_process_id(server)) + } + + /// Captures the identity of the process on the other end of a connected pipe instance, as + /// [`PipeClient::from_connected_pipe`] does, for a caller that does not lend the pipe for the whole capture. + /// + /// `client_process_id` reads the id of that process from the pipe, with [`connected_pipe_client_process_id`]. + /// The capture asks the pipe nothing else, and calls it once as it starts and once more before it returns. + pub(crate) fn from_pipe_client_process( + client_process_id: &dyn Fn() -> anyhow::Result, + ) -> anyhow::Result { + let process_id = client_process_id().context("failed to query pipe client process id")?; let process = Arc::new( Process::get_by_pid(process_id, PROCESS_IDENTITY_ACCESS) .with_context(|| format!("failed to open pipe client process {process_id}"))?, @@ -103,8 +114,7 @@ impl PipeClient { Self::ensure_process_active(process_id, &process)?; let process_instance = process_instance_identity(process_id, &process)?; let client = Self::from_process(process_instance, Arc::clone(&process), ExecutableSecurityMode::Enforce)?; - let confirmed_process_id = - connected_pipe_client_process_id(server).context("failed to confirm pipe client process id")?; + let confirmed_process_id = client_process_id().context("failed to confirm pipe client process id")?; if confirmed_process_id != process_id { bail!("pipe client process changed while its identity was captured"); } @@ -475,7 +485,8 @@ pub(crate) fn connected_pipe_client_user_sid(server: &NamedPipeServer) -> anyhow Ok(user_sid) } -fn connected_pipe_client_process_id(server: &NamedPipeServer) -> anyhow::Result { +/// Reads the id of the process on the other end of a connected pipe instance. +pub(crate) fn connected_pipe_client_process_id(server: &NamedPipeServer) -> anyhow::Result { use std::os::windows::io::AsRawHandle as _; use windows::Win32::Foundation::HANDLE; diff --git a/crates/now-package-broker/src/v2/routes/held.rs b/crates/now-package-broker/src/v2/routes/held.rs index 7d3913ca3..c078f0deb 100644 --- a/crates/now-package-broker/src/v2/routes/held.rs +++ b/crates/now-package-broker/src/v2/routes/held.rs @@ -11,7 +11,7 @@ use now_policy_api::v2; use tokio_util::sync::CancellationToken; use super::operations::owner_of; -use crate::auth::PipeClient; +use crate::auth::{PipeClient, connected_pipe_client_process_id}; use crate::server::BrokerState; use crate::v2::bypass::BypassTokens; use crate::v2::execution::{IdentifyPipeClient, Operations}; @@ -96,8 +96,8 @@ impl HeldOperations { /// /// `skip_signature_validation` is the setting of the broker state for the clients of requests. // UNTESTED: The event channel of a bypass operation identifies the process of a connection the way the request pipe -// identifies the client of a request: `PipeClient::from_connected_pipe`, then `validate_connection` with the setting -// of the broker state, and the owner that `Connection::caller` makes of such a client. +// identifies the client of a request: the capture of `PipeClient::from_connected_pipe`, then `validate_connection` +// with the setting of the broker state, and the owner that `Connection::caller` makes of such a client. // A weaker identification would send the output of a bypassed operation to a process the broker does not // authenticate as its owner, and an owner made another way would be refused its own frames. // The tests of the channel identify with a function of their own, and the one test that runs this function connects @@ -107,11 +107,18 @@ impl HeldOperations { // operation, and that an unsigned copy of it and another executable of the same user read none. // The process identified is the one that opened the connection: a handle that process gives to another one is used // without the broker seeing it. +// +// UNTESTED: The identification keeps the pipe of the channel only while it reads the id of the client process. +// A channel closes its pipe when the identification does not complete in time, and cannot close it while the +// identification keeps it, so an identification that kept the pipe while it reads the executable of the client, or +// validates its signature, and never returned would leave the pipe connected and busy for as long as the broker runs. +// No test makes this identification wait; when changing it, ask the pipe one thing at a time, through the channel. fn identify_event_client(skip_signature_validation: bool) -> IdentifyPipeClient { Arc::new(move |pipe| { - let client = pipe - .with(PipeClient::from_connected_pipe) - .context("the event channel took its pipe back")??; + let client = PipeClient::from_pipe_client_process(&|| { + pipe.with(connected_pipe_client_process_id) + .context("the event channel closed its pipe")? + })?; client.validate_connection(skip_signature_validation)?; Ok(owner_of(&client)) From b944c0699154c893cdb936965321f2a49e310994 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Wed, 2 Dec 2026 05:51:26 +0900 Subject: [PATCH 33/38] test(agent): check the command a bypass request without a source runs A request without a source that got a plan with a source option, or no plan at all, was still answered with an operation id, so the test of the route passed either way. It now waits for the run and reads its command. An elevated Install or Update without a source through Windows PowerShell or .NET tool gets a command from its builder, so only the reading of the bypass request refuses it: both are now cases of the unreadable requests. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- .../src/v2/routes/protection.rs | 6 +-- .../now-package-broker/src/v2/routes/tests.rs | 39 ++++++++++++++++++- 2 files changed, 40 insertions(+), 5 deletions(-) diff --git a/crates/now-package-broker/src/v2/routes/protection.rs b/crates/now-package-broker/src/v2/routes/protection.rs index 1dc0fa8db..004d32328 100644 --- a/crates/now-package-broker/src/v2/routes/protection.rs +++ b/crates/now-package-broker/src/v2/routes/protection.rs @@ -129,7 +129,7 @@ mod tests { Some(PRODUCT_CODE.parse().expect("a UUID")) } - // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §bypass + // oracle: contract Devolutions/now-libraries@3014fcbb899d:policies/CONTRACT.wire.md §protected-package #[test] fn a_request_names_devolutions_agent_by_its_id_or_by_its_product_code() { let cases = [ @@ -158,7 +158,7 @@ mod tests { } } - // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §bypass + // oracle: contract Devolutions/now-libraries@3014fcbb899d:policies/CONTRACT.wire.md §protected-package #[test] fn a_request_for_anything_else_does_not_name_devolutions_agent() { let cases = [ @@ -183,7 +183,7 @@ mod tests { } } - // oracle: contract Devolutions/now-libraries@77307f5106d9:policies/CONTRACT.wire.md §bypass + // oracle: contract Devolutions/now-libraries@3014fcbb899d:policies/CONTRACT.wire.md §protected-package #[test] fn without_an_installed_agent_no_product_code_names_it() { assert!(!names_agent( diff --git a/crates/now-package-broker/src/v2/routes/tests.rs b/crates/now-package-broker/src/v2/routes/tests.rs index 10b789c0e..bc0b2a34e 100644 --- a/crates/now-package-broker/src/v2/routes/tests.rs +++ b/crates/now-package-broker/src/v2/routes/tests.rs @@ -3306,6 +3306,26 @@ async fn an_unreadable_bypass_request_is_bypass_request_unreadable() { serde_json::json!({ "Manager": "Npm", "Package": { "Id": "left-pad" }, "Elevation": "Elevated" }), )), ), + ( + // The builders of these two managers build an elevated command, so only the reading refuses the request. + "an elevated install without Source through PowerShell", + without_source(bypass_request( + "request-1", + serde_json::json!({ "Manager": "PowerShell", "Package": { "Id": "Pester" }, "Elevation": "Elevated" }), + )), + ), + ( + "an elevated update without Source through Dotnet", + without_source(bypass_request( + "request-1", + serde_json::json!({ + "Operation": "Update", + "Manager": "Dotnet", + "Package": { "Id": "dotnet-ef" }, + "Elevation": "Elevated", + }), + )), + ), ( // CONTRACT.policy.md §manager-npm: a case that tests no `Source.Name` applies without `Source` too. "an Npm id that is neither a registry name nor an alias, without Source", @@ -3469,7 +3489,7 @@ async fn bypass_requests_with_one_token_that_arrive_together_start_one_operation // oracle: contract Devolutions/now-libraries@3014fcbb899d:policies/CONTRACT.wire.md §bypass-reading #[tokio::test] -async fn a_readable_bypass_request_without_source_starts_an_operation() { +async fn a_readable_bypass_request_without_source_runs_its_command_without_a_source() { let cases = [ ( "an install through WinGet", @@ -3518,7 +3538,22 @@ async fn a_readable_bypass_request_without_source_starts_an_operation() { let reply = send(&broker.state, &client(), post_bypass(&[TOKEN], &request)).await; assert_eq!(reply.status, 200, "{case}: {reply:?}"); - assert!(reply.body["OperationId"].is_string(), "{case}: {reply:?}"); + // An operation whose command the broker cannot build ends `Failed` without a run. + broker.step(Step::Launch(at(0))); + broker.step(Step::Exit(0)); + broker.wait_for(operation_id(&reply), "Completed").await; + let ran = ran(&broker); + let [run] = ran.as_slice() else { + panic!("{case}: the broker ran {} operations", ran.len()); + }; + // WinGet, Chocolatey and .NET tool take a source as `--source`, and the PowerShell managers as `-Repository`. + assert!( + !run.command + .iter() + .any(|argument| argument == "--source" || argument.contains("-Repository")), + "{case}: {:?}", + run.command + ); } } From e61af5067237c7d5961c8fb0266722a4a7c0071e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Wed, 2 Dec 2026 06:31:17 +0900 Subject: [PATCH 34/38] fix(agent): keep the state of an event channel's pipe under one lock The channel marked a pipe as given up with an atomic flag and then tried the lock a query of the pipe held, while the query unlocked and then read the flag. Each of the two could read the other's earlier value on a processor that lets a load run ahead of a store, as ARM64 does, and then neither closed the pipe: it stayed connected until the identification returned, which the deadline exists not to wait for. A query now takes the pipe out of the lock for as long as it runs and puts it back, or closes it when the channel gave it up meanwhile, so every change of the state happens under the lock and none waits for a query. The test of a pipe given up during a query drives the pipe itself, so it no longer depends on the identification reaching its query before the deadline passes. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- .../now-package-broker/src/event_channel.rs | 97 ++++++++++--------- 1 file changed, 52 insertions(+), 45 deletions(-) diff --git a/crates/now-package-broker/src/event_channel.rs b/crates/now-package-broker/src/event_channel.rs index a3dc3704f..866ef4bb0 100644 --- a/crates/now-package-broker/src/event_channel.rs +++ b/crates/now-package-broker/src/event_channel.rs @@ -546,7 +546,6 @@ pub use windows_channel::{ #[cfg(windows)] mod windows_channel { use std::sync::Arc; - use std::sync::atomic::{AtomicBool, Ordering}; use std::time::Duration; use anyhow::Context as _; @@ -621,52 +620,57 @@ mod windows_channel { /// The identification reaches the pipe through [`ChannelPipe::with`] only, so the pipe is the channel's to take /// back or to close whenever the identification asks it nothing, whether or not the identification ever returns. pub struct ChannelPipe { - /// The pipe, until the channel takes it back or gives it up. - server: parking_lot::Mutex>, + /// Where the pipe is, locked for each change and never while a query of the pipe runs. + state: parking_lot::Mutex, + } + + struct PipeState { + /// The pipe, unless a query of it runs, or the channel took it back or gave it up. + server: Option, /// Whether the channel gave the pipe up. - given_up: AtomicBool, + given_up: bool, } impl ChannelPipe { - fn holding(server: NamedPipeServer) -> Self { + pub(super) fn holding(server: NamedPipeServer) -> Self { Self { - server: parking_lot::Mutex::new(Some(server)), - given_up: AtomicBool::new(false), + state: parking_lot::Mutex::new(PipeState { + server: Some(server), + given_up: false, + }), } } /// Returns what `query` returns for the pipe, or `None` once the channel took the pipe back or gave it up. /// /// The pipe stays open while `query` runs, so `query` asks the pipe one thing and returns. + /// One query runs at a time: a query made while another one runs finds no pipe. pub fn with(&self, query: impl FnOnce(&NamedPipeServer) -> T) -> Option { - let answer = self.server.lock().as_ref().map(query); - // A channel that gave the pipe up while `query` ran could not close it, so it is closed here. - // - // UNTESTED: Once the channel gave the pipe up, the pipe is closed whenever no query of it runs. - // A pipe left open then stays connected and busy until the identification returns, which it may never do. - // The pipe is unlocked before this looks at the mark, and the channel sets the mark before it tries the - // lock, so one of the two closes the pipe however they interleave. - // The test of a pipe given up during a query does not make them race; when changing this function or - // `give_up`, keep these two orders. - if self.given_up.load(Ordering::SeqCst) { - self.server.lock().take(); + // The query has the pipe, and the lock is free while it runs, so the channel gives the pipe up without + // waiting for the query. + let server = self.state.lock().server.take()?; + let answer = query(&server); + + let mut state = self.state.lock(); + if !state.given_up { + state.server = Some(server); } + // Otherwise the pipe closes here: the channel gave it up while `query` ran. - answer + Some(answer) } /// Takes the pipe back. fn take(&self) -> Option { - self.server.lock().take() + self.state.lock().server.take() } /// Closes the pipe without waiting for the identification: now, or as soon as the query of the pipe that /// runs now returns. - fn give_up(&self) { - self.given_up.store(true, Ordering::SeqCst); - if let Some(mut server) = self.server.try_lock() { - server.take(); - } + pub(super) fn give_up(&self) { + let mut state = self.state.lock(); + state.given_up = true; + state.server.take(); } } @@ -2110,30 +2114,33 @@ pub(crate) mod pipe_tests { // oracle: mutant keeping, until its identification returns, a pipe that the channel gave up while the identification asked the pipe something #[tokio::test] async fn a_pipe_given_up_while_the_identification_asks_it_something_closes_once_it_has_answered() { - const DEADLINE: Duration = Duration::from_millis(300); - + let pipe_name = format!("now-package-broker-{}", test_operation_id("asked")); + let server = tokio::net::windows::named_pipe::ServerOptions::new() + .create(format!(r"\\.\pipe\{pipe_name}")) + .expect("create the pipe"); + let pipe = Arc::new(ChannelPipe::holding(server)); + let (asked, is_asked) = std::sync::mpsc::channel::<()>(); let (until_the_pipe_answers, answered) = std::sync::mpsc::channel::<()>(); - let (_until_the_test_ends, ended) = std::sync::mpsc::channel::<()>(); - let waits = Mutex::new((answered, ended)); - let audience = Audience::Admitted(Arc::new(move |pipe| { - let waits = waits.lock().expect("no identification panics"); - let (answered, ended) = &*waits; - pipe.with(|_pipe| { - let _ = answered.recv(); - }); - // The identification runs until the test ends, so the channel never sees it complete. - let _ = ended.recv(); - true - })); - let (sink, pipe_name) = open_waiting(audience, Duration::from_secs(600), DEADLINE, "asked"); - let _client = connect(&pipe_name).await; + let query = std::thread::spawn({ + let pipe = Arc::clone(&pipe); + move || { + pipe.with(|_pipe| { + asked.send(()).expect("the test waits for the query"); + let _ = answered.recv(); + }) + } + }); + is_asked + .recv_timeout(Duration::from_secs(10)) + .expect("the query of the pipe runs"); - // The channel closes its queue as it gives its pipe up. - tokio::time::timeout(Duration::from_secs(10), sink.finished()) - .await - .expect("the deadline passes"); + // The query runs until the test lets the pipe answer, so the pipe is given up during it. + pipe.give_up(); drop(until_the_pipe_answers); + let answer = query.join().expect("the query does not panic"); + assert_eq!(answer, Some(())); pipe_is_gone(&pipe_name).await; + assert_eq!(pipe.with(|_pipe| ()), None); } } From 2ca479568b89ee45886f9013058cde72fd38598d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Wed, 2 Dec 2026 06:31:18 +0900 Subject: [PATCH 35/38] test(agent): look for the source option each manager of a bypass request takes The assertion that a bypass request without a source runs a command without one looked for two spellings in every case, though half of the cases build a command that has neither spelling with a source as well. Each case now names the option its manager takes a source with, or none, and a case whose operation does not run fails under its name. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- .../now-package-broker/src/v2/routes/tests.rs | 37 +++++++++++++------ 1 file changed, 25 insertions(+), 12 deletions(-) diff --git a/crates/now-package-broker/src/v2/routes/tests.rs b/crates/now-package-broker/src/v2/routes/tests.rs index bc0b2a34e..24b65326d 100644 --- a/crates/now-package-broker/src/v2/routes/tests.rs +++ b/crates/now-package-broker/src/v2/routes/tests.rs @@ -3490,22 +3490,28 @@ async fn bypass_requests_with_one_token_that_arrive_together_start_one_operation // oracle: contract Devolutions/now-libraries@3014fcbb899d:policies/CONTRACT.wire.md §bypass-reading #[tokio::test] async fn a_readable_bypass_request_without_source_runs_its_command_without_a_source() { + // Each case names the option its manager takes a source with, when the command of its operation has one. + // Scoop and Vcpkg take a source inside the package they are given, which the tests of the plan read. let cases = [ ( "an install through WinGet", serde_json::json!({ "Manager": "Winget", "Package": { "Id": "Git.Git" } }), + Some("--source"), ), ( "an elevated update through WinGet", serde_json::json!({ "Operation": "Update", "Manager": "Winget", "Elevation": "Elevated" }), + Some("--source"), ), ( "an elevated install through Chocolatey", serde_json::json!({ "Manager": "Chocolatey", "Package": { "Id": "git" }, "Elevation": "Elevated" }), + Some("--source"), ), ( "an install through PowerShell", serde_json::json!({ "Manager": "PowerShell", "Package": { "Id": "Pester" } }), + Some("-Repository"), ), ( "an elevated uninstall through PowerShell7", @@ -3515,22 +3521,26 @@ async fn a_readable_bypass_request_without_source_runs_its_command_without_a_sou "Package": { "Id": "Pester" }, "Elevation": "Elevated", }), + None, ), ( "an install through Scoop of an id that names one app", serde_json::json!({ "Manager": "Scoop", "Package": { "Id": "git" } }), + None, ), ( "an install through Vcpkg of a port with a triplet", serde_json::json!({ "Manager": "Vcpkg", "Package": { "Id": "zlib:x64-windows" } }), + None, ), ( "an uninstall through Dotnet", serde_json::json!({ "Operation": "Uninstall", "Manager": "Dotnet", "Package": { "Id": "dotnet-ef" } }), + None, ), ]; - for (case, members) in cases { + for (case, members, source_option) in cases { let broker = Broker::from_state(state()); let request = without_source(bypass_request("request-1", members)); hold(&broker.state, TOKEN, &request); @@ -3540,23 +3550,26 @@ async fn a_readable_bypass_request_without_source_runs_its_command_without_a_sou assert_eq!(reply.status, 200, "{case}: {reply:?}"); // An operation whose command the broker cannot build ends `Failed` without a run. broker.step(Step::Launch(at(0))); - broker.step(Step::Exit(0)); - broker.wait_for(operation_id(&reply), "Completed").await; + tokio::time::timeout(Duration::from_secs(5), broker.wait_for(operation_id(&reply), "Running")) + .await + .unwrap_or_else(|_| panic!("{case}: the operation never ran")); let ran = ran(&broker); let [run] = ran.as_slice() else { panic!("{case}: the broker ran {} operations", ran.len()); }; - // WinGet, Chocolatey and .NET tool take a source as `--source`, and the PowerShell managers as `-Repository`. - assert!( - !run.command - .iter() - .any(|argument| argument == "--source" || argument.contains("-Repository")), - "{case}: {:?}", - run.command - ); + if let Some(source_option) = source_option { + // A PowerShell manager gets its options inside one argument, after a space. + let inside = format!(" {source_option} "); + assert!( + !run.command + .iter() + .any(|argument| argument == source_option || argument.contains(&inside)), + "{case}: {:?}", + run.command + ); + } } } - // oracle: contract Devolutions/now-libraries@3014fcbb899d:policies/CONTRACT.wire.md §bypass-reading #[tokio::test] async fn a_bypass_request_without_source_that_its_other_members_make_unreadable_is_bypass_request_unreadable() { From a3c5d99392e5b8e44f8e632ffc08cb4fc6a7398c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Wed, 2 Dec 2026 07:03:26 +0900 Subject: [PATCH 36/38] test(agent): cover what the pipe of an event channel does around a query No test asked the pipe of a channel anything and then expected the channel to serve its client, so a pipe that a query did not give back left every test passing while no owner could read a frame. The audience of the pipe tests now asks the pipe twice, as an identification does. A test through the channel makes the deadline pass while a query of the pipe runs: a channel that only took its pipe back then would leave it connected once the query returned. The test of a pipe given up during a query bounds the time giving up takes, so a pipe that waited for the query fails it. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- .../now-package-broker/src/event_channel.rs | 64 +++++++++++++++++-- 1 file changed, 58 insertions(+), 6 deletions(-) diff --git a/crates/now-package-broker/src/event_channel.rs b/crates/now-package-broker/src/event_channel.rs index 866ef4bb0..6157c838f 100644 --- a/crates/now-package-broker/src/event_channel.rs +++ b/crates/now-package-broker/src/event_channel.rs @@ -661,6 +661,9 @@ mod windows_channel { } /// Takes the pipe back. + /// + /// The channel takes the pipe once the identification returned, when no query of it runs: a query that ran + /// would put the pipe back afterwards, where nothing takes it. fn take(&self) -> Option { self.state.lock().server.take() } @@ -1007,7 +1010,8 @@ mod windows_channel { ); } }; - // Only a channel that gave its pipe up finds none, and it returned above. + // A channel that gave its pipe up returned above, so none is found here only when a query of the pipe + // panicked, which closed the pipe, and the identification returned all the same. server = pipe .take() .context("the event channel no longer holds the pipe of the client it identified")?; @@ -1836,7 +1840,11 @@ pub(crate) mod pipe_tests { fn admitting(answers: &'static [bool]) -> Audience { let asked = std::sync::atomic::AtomicUsize::new(0); - Audience::Admitted(Arc::new(move |_pipe| { + Audience::Admitted(Arc::new(move |pipe| { + // An identification asks the pipe for its client more than once, and the channel has the pipe after each. + for _ in 0..2 { + pipe.with(|_pipe| ()).expect("the channel holds its pipe"); + } let connection = asked.fetch_add(1, std::sync::atomic::Ordering::SeqCst); *answers.get(connection).expect("the test opens no other connection") })) @@ -2111,10 +2119,46 @@ pub(crate) mod pipe_tests { assert_eq!(sink.next_frame().await, None); } - // oracle: mutant keeping, until its identification returns, a pipe that the channel gave up while the identification asked the pipe something + // oracle: mutant taking the pipe back when the deadline passes, which leaves the pipe connected when a query of it runs then #[tokio::test] - async fn a_pipe_given_up_while_the_identification_asks_it_something_closes_once_it_has_answered() { - let pipe_name = format!("now-package-broker-{}", test_operation_id("asked")); + async fn a_channel_whose_deadline_passes_while_the_identification_asks_its_pipe_something_gives_its_pipe_up() { + // Long enough for the identification to reach its query on a loaded machine. + const DEADLINE: Duration = Duration::from_secs(1); + + let (asked, is_asked) = std::sync::mpsc::channel::<()>(); + let (until_the_pipe_answers, answered) = std::sync::mpsc::channel::<()>(); + let (_until_the_test_ends, ended) = std::sync::mpsc::channel::<()>(); + let waits = Mutex::new((asked, answered, ended)); + let audience = Audience::Admitted(Arc::new(move |pipe| { + let waits = waits.lock().expect("no identification panics"); + let (asked, answered, ended) = &*waits; + pipe.with(|_pipe| { + let _ = asked.send(()); + let _ = answered.recv(); + }); + // The identification runs until the test ends, so the channel never sees it complete. + let _ = ended.recv(); + true + })); + let (sink, pipe_name) = open_waiting(audience, Duration::from_secs(600), DEADLINE, "asked"); + let _client = connect(&pipe_name).await; + + // The channel closes its queue as it gives its pipe up. + tokio::time::timeout(Duration::from_secs(10), sink.finished()) + .await + .expect("the deadline passes"); + is_asked + .try_recv() + .expect("the identification asked the pipe something before the deadline passed"); + drop(until_the_pipe_answers); + + pipe_is_gone(&pipe_name).await; + } + + // oracle: mutant putting back, when the query of it returns, a pipe that the channel gave up while that query ran + #[tokio::test] + async fn a_pipe_given_up_while_it_is_asked_something_closes_once_it_has_answered() { + let pipe_name = format!("now-package-broker-{}", test_operation_id("given-up")); let server = tokio::net::windows::named_pipe::ServerOptions::new() .create(format!(r"\\.\pipe\{pipe_name}")) .expect("create the pipe"); @@ -2135,7 +2179,15 @@ pub(crate) mod pipe_tests { .expect("the query of the pipe runs"); // The query runs until the test lets the pipe answer, so the pipe is given up during it. - pipe.give_up(); + // oracle: mutant waiting, to give a pipe up, for the query of it that runs, which may never return + let given_up = tokio::task::spawn_blocking({ + let pipe = Arc::clone(&pipe); + move || pipe.give_up() + }); + tokio::time::timeout(Duration::from_secs(10), given_up) + .await + .expect("the channel waits for no query to give its pipe up") + .expect("giving a pipe up does not panic"); drop(until_the_pipe_answers); let answer = query.join().expect("the query does not panic"); From 1f4c8e97f48297871efe67e61b2933a1e04a0564 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Wed, 2 Dec 2026 07:03:27 +0900 Subject: [PATCH 37/38] test(agent): split the bypass requests without a source by what their command shows Half of the cases had no source option to look for and took another path through the body of the test. They are a test of their own, which checks that their operation runs, and both tests let the operation end, so no executor outlives its case. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- .../now-package-broker/src/v2/routes/tests.rs | 102 +++++++++++------- 1 file changed, 63 insertions(+), 39 deletions(-) diff --git a/crates/now-package-broker/src/v2/routes/tests.rs b/crates/now-package-broker/src/v2/routes/tests.rs index 24b65326d..a91efb51b 100644 --- a/crates/now-package-broker/src/v2/routes/tests.rs +++ b/crates/now-package-broker/src/v2/routes/tests.rs @@ -3487,32 +3487,86 @@ async fn bypass_requests_with_one_token_that_arrive_together_start_one_operation assert_eq!(broker.runs().await, 1); } +/// Sends the bypass request without `Source` that `members` make, whose operation must run and end `Completed`, and +/// returns what the broker ran for it. +async fn run_of_a_bypass_request_without_source(case: &str, members: serde_json::Value) -> ExecutionContext { + let broker = Broker::from_state(state()); + let request = without_source(bypass_request("request-1", members)); + hold(&broker.state, TOKEN, &request); + + let reply = send(&broker.state, &client(), post_bypass(&[TOKEN], &request)).await; + + assert_eq!(reply.status, 200, "{case}: {reply:?}"); + broker.step(Step::Launch(at(0))); + broker.step(Step::Exit(0)); + let ended = async { + loop { + let reply = send(&broker.state, &client(), get(&status_path(operation_id(&reply)))).await; + if reply.body["Status"] == "Completed" || reply.body["Status"] == "Failed" { + return reply; + } + tokio::task::yield_now().await; + } + }; + let ended = tokio::time::timeout(Duration::from_secs(10), ended) + .await + .unwrap_or_else(|_| panic!("{case}: the operation never ended")); + // An operation whose command the broker cannot build ends `Failed` without a run. + assert_eq!(ended.body["Status"], "Completed", "{case}: {ended:?}"); + let [run] = <[ExecutionContext; 1]>::try_from(ran(&broker)) + .unwrap_or_else(|ran| panic!("{case}: the broker ran {} operations", ran.len())); + + run +} + // oracle: contract Devolutions/now-libraries@3014fcbb899d:policies/CONTRACT.wire.md §bypass-reading #[tokio::test] -async fn a_readable_bypass_request_without_source_runs_its_command_without_a_source() { - // Each case names the option its manager takes a source with, when the command of its operation has one. - // Scoop and Vcpkg take a source inside the package they are given, which the tests of the plan read. +async fn a_readable_bypass_request_without_source_runs_its_command_without_the_source_option_of_its_manager() { + // Each case names the option its manager takes a source with for the operation of the case. let cases = [ ( "an install through WinGet", serde_json::json!({ "Manager": "Winget", "Package": { "Id": "Git.Git" } }), - Some("--source"), + "--source", ), ( "an elevated update through WinGet", serde_json::json!({ "Operation": "Update", "Manager": "Winget", "Elevation": "Elevated" }), - Some("--source"), + "--source", ), ( "an elevated install through Chocolatey", serde_json::json!({ "Manager": "Chocolatey", "Package": { "Id": "git" }, "Elevation": "Elevated" }), - Some("--source"), + "--source", ), ( "an install through PowerShell", serde_json::json!({ "Manager": "PowerShell", "Package": { "Id": "Pester" } }), - Some("-Repository"), + "-Repository", ), + ]; + + for (case, members, source_option) in cases { + let run = run_of_a_bypass_request_without_source(case, members).await; + + // A PowerShell manager gets its options inside one argument, after a space. + let inside = format!(" {source_option} "); + assert!( + !run.command + .iter() + .any(|argument| argument == source_option || argument.contains(&inside)), + "{case}: {:?}", + run.command + ); + } +} + +// oracle: contract Devolutions/now-libraries@3014fcbb899d:policies/CONTRACT.wire.md §bypass-reading +// The commands of these cases have no option for a source: Scoop and Vcpkg take one inside the package they are given, +// which the tests of `v2::execution::plan` read, and the two uninstalls take none. +#[tokio::test] +async fn a_readable_bypass_request_without_source_whose_command_has_no_source_option_runs() { + let cases = [ ( "an elevated uninstall through PowerShell7", serde_json::json!({ @@ -3521,53 +3575,23 @@ async fn a_readable_bypass_request_without_source_runs_its_command_without_a_sou "Package": { "Id": "Pester" }, "Elevation": "Elevated", }), - None, ), ( "an install through Scoop of an id that names one app", serde_json::json!({ "Manager": "Scoop", "Package": { "Id": "git" } }), - None, ), ( "an install through Vcpkg of a port with a triplet", serde_json::json!({ "Manager": "Vcpkg", "Package": { "Id": "zlib:x64-windows" } }), - None, ), ( "an uninstall through Dotnet", serde_json::json!({ "Operation": "Uninstall", "Manager": "Dotnet", "Package": { "Id": "dotnet-ef" } }), - None, ), ]; - for (case, members, source_option) in cases { - let broker = Broker::from_state(state()); - let request = without_source(bypass_request("request-1", members)); - hold(&broker.state, TOKEN, &request); - - let reply = send(&broker.state, &client(), post_bypass(&[TOKEN], &request)).await; - - assert_eq!(reply.status, 200, "{case}: {reply:?}"); - // An operation whose command the broker cannot build ends `Failed` without a run. - broker.step(Step::Launch(at(0))); - tokio::time::timeout(Duration::from_secs(5), broker.wait_for(operation_id(&reply), "Running")) - .await - .unwrap_or_else(|_| panic!("{case}: the operation never ran")); - let ran = ran(&broker); - let [run] = ran.as_slice() else { - panic!("{case}: the broker ran {} operations", ran.len()); - }; - if let Some(source_option) = source_option { - // A PowerShell manager gets its options inside one argument, after a space. - let inside = format!(" {source_option} "); - assert!( - !run.command - .iter() - .any(|argument| argument == source_option || argument.contains(&inside)), - "{case}: {:?}", - run.command - ); - } + for (case, members) in cases { + run_of_a_bypass_request_without_source(case, members).await; } } // oracle: contract Devolutions/now-libraries@3014fcbb899d:policies/CONTRACT.wire.md §bypass-reading From 7fecff236f1cad417a0bb898c5e8541ea4f9bc3c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Wed, 2 Dec 2026 07:32:12 +0900 Subject: [PATCH 38/38] test(agent): end the waits of the event channel and bypass tests on their own The query of the test that lets the deadline pass during it waited for the test to release it. A channel that waited for that query would do so on the thread the test runs on, and the test would never end instead of failing, so the query now ends after a bounded time. The test of bypass requests that arrive together lets its operation end, so its executor does not outlive it, and the wait for the operation of a bypass request without a source shows a status request that fails. Issue: DGW-499 Co-Authored-By: Claude Fable 5.2 --- crates/now-package-broker/src/event_channel.rs | 4 +++- crates/now-package-broker/src/v2/routes/tests.rs | 4 ++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/crates/now-package-broker/src/event_channel.rs b/crates/now-package-broker/src/event_channel.rs index 6157c838f..f89786412 100644 --- a/crates/now-package-broker/src/event_channel.rs +++ b/crates/now-package-broker/src/event_channel.rs @@ -2134,7 +2134,9 @@ pub(crate) mod pipe_tests { let (asked, answered, ended) = &*waits; pipe.with(|_pipe| { let _ = asked.send(()); - let _ = answered.recv(); + // A channel that waited for this query would wait on the thread that lets the pipe answer, so the query + // ends on its own, well after the deadline. + let _ = answered.recv_timeout(Duration::from_secs(20)); }); // The identification runs until the test ends, so the channel never sees it complete. let _ = ended.recv(); diff --git a/crates/now-package-broker/src/v2/routes/tests.rs b/crates/now-package-broker/src/v2/routes/tests.rs index a91efb51b..b339ba73a 100644 --- a/crates/now-package-broker/src/v2/routes/tests.rs +++ b/crates/now-package-broker/src/v2/routes/tests.rs @@ -3485,6 +3485,9 @@ async fn bypass_requests_with_one_token_that_arrive_together_start_one_operation broker.step(Step::Launch(at(0))); broker.wait_for(&started, "Running").await; assert_eq!(broker.runs().await, 1); + // The operation ends before the test does, so its executor waits for no step the test never sends. + broker.step(Step::Exit(0)); + broker.wait_for(&started, "Completed").await; } /// Sends the bypass request without `Source` that `members` make, whose operation must run and end `Completed`, and @@ -3502,6 +3505,7 @@ async fn run_of_a_bypass_request_without_source(case: &str, members: serde_json: let ended = async { loop { let reply = send(&broker.state, &client(), get(&status_path(operation_id(&reply)))).await; + assert_eq!(reply.status, 200, "{case}: {reply:?}"); if reply.body["Status"] == "Completed" || reply.body["Status"] == "Failed" { return reply; }