diff --git a/crates/now-package-broker/src/audit.rs b/crates/now-package-broker/src/audit.rs index 3df0b4d96..0af40dccd 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(), ), @@ -551,16 +553,34 @@ 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) + } + + 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 +776,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 +844,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 +858,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 +891,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 +917,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 +952,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/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/event_channel.rs b/crates/now-package-broker/src/event_channel.rs index a438f9c9b..08209dff7 100644 --- a/crates/now-package-broker/src/event_channel.rs +++ b/crates/now-package-broker/src/event_channel.rs @@ -538,10 +538,14 @@ impl ChannelVersion { } #[cfg(windows)] -pub use windows_channel::{open_operation_channel, open_operation_channel_announcing}; +pub use windows_channel::{ + AdmitClient, Audience, ChannelPipe, 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 _; @@ -549,7 +553,8 @@ 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 tokio_util::sync::CancellationToken; + use tracing::{debug, trace, 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; @@ -573,6 +578,141 @@ 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 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 + /// 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); + + /// How long after the deadline of its channel an identification that the channel still waited for would be + /// interrupted. + /// + /// The channel abandons an identification at its deadline, and interrupts it then. + /// An identification interrupted while its channel waits for it could answer like one that refuses its client, and + /// the channel would listen again where it must close, so this is a time that never comes. + // + // UNTESTED: No identification is interrupted while its channel waits for it. + // One interrupted at the deadline of the channel, by a deadline of its own, races the channel closing, and the + // channel listens again when the interruption wins. + // No test tells that race from the channel closing first; when changing this value or the deadline given to the + // identification, check that the deadline comes long after the channel abandoned the identification. + const UNABANDONED_INTERRUPTION_DELAY: Duration = Duration::from_secs(365 * 24 * 60 * 60); + + /// 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 or to close whenever the identification asks it nothing, whether or not the identification ever returns. + pub struct ChannelPipe { + /// 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: bool, + } + + impl ChannelPipe { + pub(super) fn holding(server: NamedPipeServer) -> Self { + Self { + 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 { + // 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. + + Some(answer) + } + + /// 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() + } + + /// Closes the pipe without waiting for the identification: now, or as soon as the query of the pipe that + /// runs now returns. + pub(super) fn give_up(&self) { + let mut state = self.state.lock(); + state.given_up = true; + state.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, or does not return before the deadline of the channel, serves nobody. + /// From that deadline on, the synchronous I/O it waits on is cancelled until it returns. + 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 after a + /// pause 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 +736,41 @@ 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)> { + 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, and + /// `identification_deadline` for the identification of a client to complete. + /// + /// 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, ) -> anyhow::Result<(OperationEventSink, EventChannel)> { let sink = OperationEventSink::new(); let pipe_name = operation_pipe_name(operation_id); @@ -629,7 +804,16 @@ 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, + refusal_pause, + identification_deadline, + version, + server, + writer_sink, + &operation_id, + ) + .await; }); Ok((sink, descriptor)) @@ -637,29 +821,47 @@ mod windows_channel { /// Serve one client connection on the operation's event pipe, best-effort. async fn run_channel( + audience: Audience, + refusal_pause: Duration, + identification_deadline: Duration, 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 => Ok(accept_first(server, &sink).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, + 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; } }; - if !connected { - 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 +911,168 @@ 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. + /// + /// 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. + /// 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, + 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 + // 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. + // 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 { + sink.finished().await; + tokio::time::sleep(NEVER_CONNECTED_LINGER).await; + }; + tokio::pin!(linger); + + let mut server = server; + // 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 Ok(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; + () = &mut linger => return Ok(None), + 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 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. + // 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")?; + if listens_from.is_some() { + // 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]); + } + + // 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 pipe = Arc::new(ChannelPipe::holding(server)); + // Cancelled once the channel no longer waits for the identification, however this function ends. + let abandoned = CancellationToken::new(); + let _abandoned = abandoned.clone().drop_guard(); + // The identification is interrupted once the channel abandoned it, and not at a deadline of its own. + let admission = crate::pipe::spawn_cancellable_capture( + std::time::Instant::now() + identification_deadline + UNABANDONED_INTERRUPTION_DELAY, + abandoned.clone(), + { + let admit = Arc::clone(admit); + let pipe = Arc::clone(&pipe); + move || Ok(admit(&pipe)) + }, + ); + let admitted = match tokio::time::timeout(identification_deadline, admission).await { + // An identification that panics, or that no thread could run, 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")? + .context("failed to run the identification of a client of the event channel")?, + Err(_) => { + // UNTESTED: The identification that the broker gives its channels waits for other processes in + // synchronous file I/O only, which this cancellation interrupts until the identification returns. + // One that also waited for something else, such as a lock or an event, would keep its thread of + // the blocking pool for as long as that wait lasts, and a client that makes it wait on every + // channel would leave the pool without a thread. + // The test of this cancellation blocks its identification in a read; when changing what + // identifies the clients of a channel, check what it waits for. + abandoned.cancel(); + // Nothing here waits for the identification to end. + pipe.give_up(); + anyhow::bail!( + "the identification of a client of the event channel did not complete within {identification_deadline:?}" + ); + } + }; + // 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")?; + if admitted { + return Ok(Some(server)); + } + + // A process that is refused may connect again after every pause, for as long as the operation runs. + trace!(operation_id, "Refused a connection to the event channel"); + // The same instance listens again: the pipe never has a second one. + 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. + // 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); + } + } + /// Write one frame with a bounded deadline. /// /// A connected client that stops reading would otherwise leave the write @@ -1156,7 +1520,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 +1554,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 +1870,401 @@ 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| { + // 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") + })) + } + + /// 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 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(), + ) + .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 { + 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 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; + } + 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 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 channel closed its pipe to refuse the connection"); + } + 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:?}"); + } + + // 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. + 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: 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); + + 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"); + } + + /// 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; + // 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"); + + 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); + } + + /// 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 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_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(()); + // 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(); + 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 leaving an identification that its channel abandoned at the deadline blocked in synchronous I/O, which keeps its thread for as long as another process holds that I/O up + #[tokio::test] + async fn an_identification_blocked_in_synchronous_io_ends_once_its_channel_closed_at_the_deadline() { + use std::io::Read as _; + + const DEADLINE: Duration = Duration::from_millis(300); + + // Nothing is ever written to this pipe, so a read of it blocks for as long as the test holds its server end. + let unanswered_path = format!(r"\\.\pipe\now-package-broker-{}", test_operation_id("unanswered")); + let _unanswering = tokio::net::windows::named_pipe::ServerOptions::new() + .create(&unanswered_path) + .expect("create the pipe"); + let unanswered = std::fs::File::open(&unanswered_path).expect("open the pipe"); + let (ended, mut has_ended) = tokio::sync::mpsc::unbounded_channel(); + let audience = Audience::Admitted(Arc::new(move |_pipe| { + let read = (&unanswered).read(&mut [0u8; 1]); + let _ = ended.send(read); + false + })); + let (sink, pipe_name) = open_waiting(audience, Duration::from_secs(600), DEADLINE, "blocked"); + 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"); + let read = tokio::time::timeout(Duration::from_secs(5), has_ended.recv()) + .await + .expect("the identification ends once its channel closed"); + + // The identification read nothing: its read was cancelled, or the channel closed before a thread took the + // identification, which then never ran. + assert!(!matches!(read, Some(Ok(_))), "{read:?}"); + } + + // 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"); + 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 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 query runs until the test lets the pipe answer, so the pipe is given up during it. + // 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"); + + assert_eq!(answer, Some(())); + pipe_is_gone(&pipe_name).await; + assert_eq!(pipe.with(|_pipe| ()), None); + } } diff --git a/crates/now-package-broker/src/pipe.rs b/crates/now-package-broker/src/pipe.rs index 4776179ef..d6542de95 100644 --- a/crates/now-package-broker/src/pipe.rs +++ b/crates/now-package-broker/src/pipe.rs @@ -31,8 +31,9 @@ use crate::auth::{PipeClient, connected_pipe_client_user_sid}; use crate::remote_grant::PendingGrant; use crate::server::{ BrokerState, PipeIdentity, build_router_for_pipe, busy_response, presented_grant, serve_connection, - unauthenticated_client_response, + serve_unidentified_connection, unauthenticated_client_response, }; +use crate::v2::bypass::TokenDigest; /// Default pipe name for the package broker. pub const DEFAULT_PIPE_NAME: &str = r"\\.\pipe\Devolutions.Now.PackageBroker.v1"; @@ -59,9 +60,11 @@ pub const MAX_CONCURRENT_GRANT_CONNECTIONS: usize = 8; /// Maximum number of clients over the connection limits whose request is being read or answered busy. /// /// Beyond this, further clients are disconnected without a reply. +/// A client served in a grant slot or in the slot of a bypass token is not counted. const MAX_CONCURRENT_BUSY_REPLIES: usize = 16; -/// Deadline for sending a busy reply, from accept to response completion, unless the request presents a pending grant. +/// Deadline for sending a busy reply, from accept to response completion, unless the request takes a grant slot or the +/// slot of a bypass token. const BUSY_REPLY_DEADLINE: std::time::Duration = std::time::Duration::from_secs(5); /// Consecutive connect failures tolerated before the accept loop backs off. @@ -129,10 +132,17 @@ async fn accept_connections( Arc::clone(state), PipeClient::from_connected_pipe, )); + let unidentified = Arc::new(UnidentifiedClientLog::default()); + let bypasses = Arc::new(BypassAdmission::for_broker( + Arc::clone(state), + capture_connected_client, + Arc::clone(&unidentified), + )); let admission = Arc::new(UserAdmission::new( MAX_CONCURRENT_CONNECTIONS_PER_USER, Arc::clone(&busy_replies), Arc::clone(&grants), + Arc::clone(&bypasses), )); accept_loop( @@ -152,13 +162,19 @@ async fn accept_connections( let permit = match accepted { Admission::Serve(permit) => permit, Admission::Busy(permit) => { - connections.spawn(reply_over_limit(server, permit, Arc::clone(&grants))); + connections.spawn(reply_over_limit( + server, + permit, + Arc::clone(&grants), + Arc::clone(&bypasses), + )); return; } }; let state = Arc::clone(state); let admission = Arc::clone(&admission); + let unidentified = Arc::clone(&unidentified); let connection_deadline = tokio::time::Instant::now() + CONNECTION_DEADLINE; connections.spawn(async move { // Serving this connection can commit a policy and record its terminal @@ -170,14 +186,9 @@ async fn accept_connections( server, permit, connected_pipe_client_user_sid, - 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, &unidentified), ); // Enforce a deadline so idle or slow clients cannot pin @@ -195,6 +206,114 @@ 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, + /// Why the broker failed to identify the process. + error: anyhow::Error, + }, +} + +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. + /// + /// Nothing is logged here: whoever serves the client reports why its process was not identified, through an + /// [`UnidentifiedClientLog`]. + 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) => Ok(Self::Unidentified { user_sid, error }), + Err(_) => Err(error), + } + } + + fn user_sid(&self) -> &Sid { + match self { + Self::Identified(client) => client.user_sid(), + Self::Unidentified { user_sid, .. } => user_sid, + } + } +} + +/// Reports the clients whose process the broker failed to identify, which any local process can be. +/// +/// It logs one of them at most in each [`REPEATED_LOG_REPORT_INTERVAL`], with the number of those it left out, so +/// that the failure to identify such clients cannot fill the log. +/// A connection that fails or outlives its deadline is logged like that of any other client. +#[derive(Default)] +struct UnidentifiedClientLog(parking_lot::Mutex); + +impl UnidentifiedClientLog { + fn report(&self, user_sid: &Sid, error: &anyhow::Error) { + let report = self.0.lock().record(std::time::Instant::now()); + if let Some(suppressed) = report { + warn!( + error = format!("{error:#}"), + %user_sid, + suppressed, + "Failed to identify named pipe client; none of its requests is authenticated" + ); + } + } +} + +// 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, for the clients it admits and +// for those it serves over a limit for a bypass token, 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. +/// +/// A client whose process the broker failed to identify is reported to `unidentified`. +async fn serve_client( + state: Arc, + server: NamedPipeServer, + client: ConnectedClient, + unidentified: &UnidentifiedClientLog, +) { + match client { + ConnectedClient::Identified(client) => { + 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"); + } + ConnectedClient::Unidentified { user_sid, error } => { + unidentified.report(&user_sid, &error); + // Any local process can connect as such a client as often as it likes, so the lines of each connection + // are below `INFO`. + debug!( + error = format!("{error:#}"), + %user_sid, + "Unidentified client connected to named pipe" + ); + serve_unidentified_connection(server, state, user_sid).await; + debug!("Unidentified client disconnected from named pipe"); + } + } +} + /// Concurrency limits applied by [`accept_loop`]. struct AcceptLimits { /// Connections served concurrently. @@ -208,30 +327,64 @@ struct AcceptLimits { /// The client's request is classified before routing. /// A request presenting a pending grant is served in a grant slot, which replaces the busy reply slot, until the connection deadline. /// It gets a busy reply instead when every grant slot is taken or another connection holds one for the same grant. -/// Any other request gets a busy reply, which never consumes a grant, since the grant route is never reached. -async fn reply_over_limit(server: NamedPipeServer, busy_permit: OwnedSemaphorePermit, grants: Arc) { - reply_over_limit_within(server, busy_permit, grants, BUSY_REPLY_DEADLINE, CONNECTION_DEADLINE).await; +/// A bypass request of the 2.0 encoding that carries a bypass token the broker holds is served in the slot of that +/// token, which replaces the busy reply slot, until the connection deadline. +/// It gets a busy reply instead while another connection holds the slot of the same token. +/// A connection holds that slot until the broker answers its request or finds the connection ended. +/// The broker finds that a client left before it sent its whole body only when it reads that body, which it does once +/// it has captured the client, or at the connection deadline. +/// Any other request gets a busy reply, which never consumes a grant or uses up a token, since no route is reached. +/// A request of the 2.0 encoding gets that reply in the 2.0 encoding. +async fn reply_over_limit( + server: NamedPipeServer, + busy_permit: OwnedSemaphorePermit, + grants: Arc, + bypasses: Arc, +) { + reply_over_limit_within( + server, + busy_permit, + grants, + bypasses, + BUSY_REPLY_DEADLINE, + CONNECTION_DEADLINE, + ) + .await; } /// Answer a client over a connection limit as [`reply_over_limit`] does, with the given deadlines. /// -/// The connection closes `busy_deadline` after accept unless it holds a grant slot, and `connection_deadline` after accept otherwise. +/// The connection closes `busy_deadline` after accept unless it holds a grant slot or the slot of a bypass token, and +/// `connection_deadline` after accept otherwise. /// A connection cut short is disconnected, so its client sees it end even while the capture of its identity still holds the pipe. async fn reply_over_limit_within( server: NamedPipeServer, busy_permit: OwnedSemaphorePermit, grants: Arc, + bypasses: Arc, busy_deadline: std::time::Duration, connection_deadline: std::time::Duration, ) { let accepted_at = tokio::time::Instant::now(); + // The capture of a client served in the slot of a bypass token is cancelled when its connection ends, so this + // deadline only bounds a capture whose connection lasts until its own. + let bypass_capture_deadline = std::time::Instant::now() + connection_deadline; let pipe = Arc::new(server); let mut cut_short = DisconnectOnDrop(Some(Arc::clone(&pipe))); let slot = Arc::new(parking_lot::Mutex::new(OverLimitSlot::Busy { _permit: busy_permit })); let router = axum::Router::new().fallback({ let pipe = Arc::clone(&pipe); let slot = Arc::clone(&slot); - move |request: Request| serve_over_limit(request, Arc::clone(&grants), Arc::clone(&pipe), Arc::clone(&slot)) + move |request: Request| { + serve_over_limit( + request, + Arc::clone(&grants), + Arc::clone(&bypasses), + Arc::clone(&pipe), + Arc::clone(&slot), + bypass_capture_deadline, + ) + } }); let serve = serve_connection(SharedPipe(pipe), router); @@ -282,9 +435,16 @@ impl Drop for DisconnectOnDrop { async fn serve_over_limit( request: Request, grants: Arc, + bypasses: Arc, pipe: Arc, slot: Arc>, + bypass_capture_deadline: std::time::Instant, ) -> Response { + // No request of the 2.0 encoding presents a grant, and each gets the answers of its own encoding. + if crate::v2::routes::is_v2(&request) { + return serve_v2_over_limit(request, bypasses, pipe, slot, bypass_capture_deadline).await; + } + let Some(grant_slot) = grants.try_claim(&request) else { return busy_response(); }; @@ -335,6 +495,61 @@ async fn serve_over_limit( } } +/// Serve the request of the 2.0 encoding of a client over a connection limit, or answer it busy; see +/// [`reply_over_limit`]. +async fn serve_v2_over_limit( + request: Request, + bypasses: Arc, + pipe: Arc, + slot: Arc>, + capture_deadline: std::time::Instant, +) -> Response { + let Some(token_slot) = bypasses.try_claim(&request) else { + return crate::v2::routes::busy(); + }; + *slot.lock() = OverLimitSlot::BypassToken { + _slot: token_slot, + // A connection served for a token holds what any served connection holds. + _audit_lease: crate::audit::AuditLease::acquire(), + }; + debug!("Client whose bypass request carries a held token connected to named pipe over the connection limit"); + + // Cancelled when this request is answered or its connection ends, whichever comes first. + let ended = CancellationToken::new(); + let _ended = ended.clone().drop_guard(); + // The blocking capture holds the pipe, so that its handle stays valid even when the connection is dropped first. + // It does not hold the slot: the connection alone does, so the slot is free as soon as the broker stops serving + // the request, and the capture is cancelled then, so that it does not keep its thread. + let capture = { + let bypasses = Arc::clone(&bypasses); + spawn_cancellable_capture(capture_deadline, ended, move || (bypasses.router)(&pipe)) + }; + let mut router = match capture.await { + Ok(Ok(router)) => router, + Ok(Err(error)) => { + if let Some(suppressed) = bypasses.rejections.lock().record(std::time::Instant::now()) { + warn!( + error = format!("{error:#}"), + suppressed, "Failed to capture the named pipe client of a bypass request that carries a held token" + ); + } + return crate::v2::routes::refuse_unknown_client(request); + } + Err(error) => { + error!( + error = format!("{error:#}"), + "Named pipe client identity capture task failed" + ); + return crate::v2::routes::refuse_unknown_client(request); + } + }; + + match router.call(request).await { + Ok(response) => response, + Err(infallible) => match infallible {}, + } +} + /// How long before its grant expires the identity capture of a client presenting that grant is interrupted. /// /// The Agent dispatches an operation after issuing its grant, and waits for its start until 60 seconds after dispatch. @@ -360,16 +575,30 @@ impl Drop for CaptureFinished { } } -/// Run blocking `capture` work that ends by `deadline`. +/// Run blocking `capture` work that ends by `deadline`; see [`spawn_cancellable_capture`]. +fn spawn_interruptible_capture( + deadline: std::time::Instant, + capture: impl FnOnce() -> anyhow::Result + Send + 'static, +) -> JoinHandle> +where + T: Send + 'static, +{ + spawn_cancellable_capture(deadline, CancellationToken::new(), capture) +} + +/// Run blocking `capture` work that ends by `deadline`, or once `cancelled` is cancelled when that comes first. /// -/// From the deadline on, the synchronous I/O the capture's thread waits on is cancelled until the capture returns. +/// From then on, the synchronous I/O the capture's thread waits on is cancelled until the capture returns. /// A file open that another process holds up, for example with an oplock, then fails instead of waiting. /// -/// UNTESTED: the identity capture of a pipe client waits on other processes only in synchronous file I/O, which this interrupts. -/// A capture that also waited on something else, such as an event or a lock, would not end at its deadline and would keep its grant slot. +/// UNTESTED: the identity capture of a pipe client waits on other processes only in synchronous file I/O, which this +/// interrupts. +/// A capture that also waited on something else, such as an event or a lock, would not end when it must: it would keep +/// its thread, and its grant slot when it holds one. /// Check the waits of `PipeClient::from_connected_pipe` when changing it. -fn spawn_interruptible_capture( +pub(crate) fn spawn_cancellable_capture( deadline: std::time::Instant, + cancelled: CancellationToken, capture: impl FnOnce() -> anyhow::Result + Send + 'static, ) -> JoinHandle> where @@ -381,8 +610,12 @@ where let state = Arc::new(parking_lot::Mutex::new(CaptureThread::NotStarted)); let watched = Arc::clone(&state); + let watched_cancellation = cancelled.clone(); tokio::spawn(async move { - tokio::time::sleep_until(deadline.into()).await; + tokio::select! { + () = tokio::time::sleep_until(deadline.into()) => {} + () = watched_cancellation.cancelled() => {} + } loop { { let state = watched.lock(); @@ -406,6 +639,9 @@ where if deadline <= std::time::Instant::now() { anyhow::bail!("identity capture deadline exceeded before it started"); } + if cancelled.is_cancelled() { + anyhow::bail!("identity capture cancelled before it started"); + } // SAFETY: No preconditions. let thread_id = unsafe { GetCurrentThreadId() }; let thread = Thread::get_by_id(thread_id, THREAD_TERMINATE).context("failed to open the capture thread")?; @@ -417,20 +653,26 @@ where /// What a client over a connection limit holds while it is answered. enum OverLimitSlot { - /// A busy reply slot, until the client's request presents a pending grant. + /// A busy reply slot, until the client's request presents a pending grant or carries a bypass token the broker + /// holds. Busy { _permit: OwnedSemaphorePermit }, /// A grant slot, for the rest of the connection. Grant { _slot: GrantSlot, _audit_lease: crate::audit::AuditLease, }, + /// The slot of a bypass token, for the rest of the connection. + BypassToken { + _slot: BypassTokenSlot, + _audit_lease: crate::audit::AuditLease, + }, } /// Looks up a pending grant from the value a request presents. type PendingGrantLookup = Box Option + Send + Sync>; /// Captures the connected client and builds the router that serves its request; blocking. -type GrantRouterBuilder = Box anyhow::Result + Send + Sync>; +type ClientRouterBuilder = Box anyhow::Result + Send + Sync>; /// Serves the clients over a connection limit whose request presents a pending grant. /// @@ -440,7 +682,7 @@ struct GrantAdmission { max_connections: usize, claimed: parking_lot::Mutex>, pending: PendingGrantLookup, - router: GrantRouterBuilder, + router: ClientRouterBuilder, /// Clients presenting a pending grant whose identity could not be captured. rejections: parking_lot::Mutex, } @@ -506,6 +748,99 @@ impl Drop for GrantSlot { } } +/// Looks up the bypass token a request carries, when the request is a bypass request and the broker holds the token. +type HeldBypassTokenLookup = Box Option + Send + Sync>; + +/// Serves the clients over a connection limit whose bypass request carries a bypass token the broker holds. +/// +/// Only the Agent gives the broker tokens, so connections carrying none of them cannot take these slots. +/// Every token has a slot, and holds it for at most one connection at a time, so such a request is answered busy only +/// while the broker serves another one with the same token. +/// A connection takes a slot only for a token the broker holds then, and keeps it until the connection deadline at +/// most, so the tokens the Agent gives the broker bound the slots taken at once. +struct BypassAdmission { + claimed: parking_lot::Mutex>, + held: HeldBypassTokenLookup, + router: ClientRouterBuilder, + /// Clients whose bypass request carries a held token, and of which neither the identity nor the user was captured. + rejections: parking_lot::Mutex, +} + +impl BypassAdmission { + fn new( + held: impl Fn(&Request) -> Option + Send + Sync + 'static, + router: impl Fn(&NamedPipeServer) -> anyhow::Result + Send + Sync + 'static, + ) -> Self { + Self { + claimed: parking_lot::Mutex::new(HashSet::new()), + held: Box::new(held), + router: Box::new(router), + rejections: parking_lot::Mutex::new(LogRateLimit::default()), + } + } + + fn for_broker( + state: Arc, + capture: fn(&NamedPipeServer) -> anyhow::Result, + unidentified: Arc, + ) -> Self { + let tokens = Arc::clone(&state); + + Self::new( + move |request| crate::v2::routes::held_bypass_token(&tokens, request), + move |server| { + // Only a request of the 2.0 encoding reaches this router, so it needs no route of another encoding. + let other = axum::Router::new(); + let router = match capture(server)? { + ConnectedClient::Identified(client) => { + crate::v2::routes::route_connection(Arc::clone(&state), *client, other) + } + // UNTESTED: A client whose process is not identified, and which is served over a connection limit + // for the bypass token it carries, is reported to the same log as the clients served within the + // limits, and this arm logs nothing else for it above `DEBUG`. + // A line for each such connection would let a process that has a held token fill the log for as + // long as the broker holds the token. + // The test of that log serves its clients within the limits; when changing this arm, check that + // it still reports to `unidentified` and logs nothing else for each client. + ConnectedClient::Unidentified { user_sid, error } => { + unidentified.report(&user_sid, &error); + crate::v2::routes::route_unidentified(Arc::clone(&state), user_sid, other) + } + }; + + Ok(router) + }, + ) + } + + /// Take the slot of the bypass token that `request` carries, when the broker holds that token. + /// + /// Returns `None` when another connection holds that slot. + fn try_claim(self: &Arc, request: &Request) -> Option { + let token = (self.held)(request)?; + if !self.claimed.lock().insert(token) { + return None; + } + + Some(BypassTokenSlot { + admission: Arc::clone(self), + token, + }) + } +} + +/// The slot of a bypass token, released on drop. +struct BypassTokenSlot { + admission: Arc, + token: TokenDigest, +} + +impl Drop for BypassTokenSlot { + fn drop(&mut self) { + self.admission.claimed.lock().remove(&self.token); + } +} + /// A connected pipe instance that its connection and the blocking capture of its client both hold. struct SharedPipe(Arc); @@ -676,7 +1011,7 @@ async fn accept_loop( if let Some(suppressed) = busy_log.record(std::time::Instant::now()) { warn!( suppressed, - "Named pipe client over the connection limit: replying busy unless it presents a pending grant" + "Named pipe client over the connection limit: replying busy unless it presents a pending grant or a held bypass token" ); } Admission::Busy(permit) @@ -899,17 +1234,24 @@ struct UserAdmission { /// Slots for clients over a connection limit, shared with the connection limit of the accept loop. busy_replies: Arc, grants: Arc, + bypasses: Arc, rejections: parking_lot::Mutex, /// Clients whose user or identity could not be established, which any local process can cause. unauthenticated_rejections: parking_lot::Mutex, } impl UserAdmission { - fn new(max_per_user: usize, busy_replies: Arc, grants: Arc) -> Self { + fn new( + max_per_user: usize, + busy_replies: Arc, + grants: Arc, + bypasses: Arc, + ) -> Self { Self { user_slots: Arc::new(UserConnectionSlots::new(max_per_user)), busy_replies, grants, + bypasses, rejections: parking_lot::Mutex::new(LogRateLimit::default()), unauthenticated_rejections: parking_lot::Mutex::new(LogRateLimit::default()), } @@ -969,7 +1311,7 @@ impl UserAdmission { warn!( %user_sid, suppressed, - "Named pipe client over the per-user connection limit: replying busy unless it presents a pending grant" + "Named pipe client over the per-user connection limit: replying busy unless it presents a pending grant or a held bypass token" ); } else { warn!( @@ -980,7 +1322,13 @@ impl UserAdmission { } } if let Some(busy_permit) = busy_permit { - reply_over_limit(server, busy_permit, Arc::clone(&self.grants)).await; + reply_over_limit( + server, + busy_permit, + Arc::clone(&self.grants), + Arc::clone(&self.bypasses), + ) + .await; } return; }; @@ -1777,7 +2125,7 @@ mod tests { let pipe_name = unique_pipe_name("user-change"); let connection_permits = Arc::new(Semaphore::new(1)); - let admission = UserAdmission::new(1, Arc::new(Semaphore::new(1)), no_grants()); + let admission = UserAdmission::new(1, Arc::new(Semaphore::new(1)), no_grants(), no_bypasses()); 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"); @@ -1875,6 +2223,7 @@ mod tests { MAX_PER_USER, Arc::new(Semaphore::new(1)), no_grants(), + no_bypasses(), )); let (served_tx, mut served_rx) = tokio::sync::mpsc::unbounded_channel(); let release = Arc::new(Semaphore::new(0)); @@ -1964,7 +2313,7 @@ mod tests { let permit = Arc::new(Semaphore::new(1)) .try_acquire_owned() .expect("busy reply slot"); - let serving = tokio::spawn(reply_over_limit(server, permit, no_grants())); + let serving = tokio::spawn(reply_over_limit(server, permit, no_grants(), no_bypasses())); let response = exchange(&mut client, HEALTH_REQUEST).await; @@ -1980,6 +2329,560 @@ mod tests { serving.await.expect("serving task"); } + const BYPASS_TOKEN: &str = "t0ken.A_b~c:d-e"; + + /// The members of a bypass request of the 2.0 encoding. + fn bypass_body(request_id: &str) -> serde_json::Value { + serde_json::json!({ + "RequestId": request_id, + "Operation": "Install", + "Manager": "Winget", + "Source": { "Name": "winget" }, + "Package": { "Id": "Git.Git", "Version": "2.45.1" }, + "Elevation": "NonElevated", + }) + } + + /// The header section of a request of the 2.0 encoding that announces `body`, with one bypass token header for + /// each of `tokens`. + fn v2_header(method: &str, path: &str, content_type: &str, tokens: &[&str], body: &str) -> String { + let token_headers: String = tokens + .iter() + .map(|token| format!("X-Devolutions-Bypass-Token: {token}\r\n")) + .collect(); + + format!( + "{method} {path} HTTP/1.1\r\nHost: broker\r\nConnection: close\r\nContent-Type: {content_type}\r\n{token_headers}Content-Length: {}\r\n\r\n", + body.len() + ) + } + + /// The header section of a bypass request whose body is `body`. + fn bypass_header(tokens: &[&str], body: &str) -> String { + v2_header( + "POST", + "/v2/package-requests/execute-bypass", + "application/json", + tokens, + body, + ) + } + + fn bypass_request(tokens: &[&str], body: &str) -> String { + format!("{}{body}", bypass_header(tokens, body)) + } + + /// Gives the broker `token` bound to the bypass request `body` and to the user of the test process, as + /// Devolutions Agent does. + fn give_bypass_token(state: &Arc, token: &str, body: &serde_json::Value) { + assert!( + state + .operations + .give_bypass_token(state, token, body, current_user_sid()), + "the broker holds the token" + ); + } + + /// A broker that answers every client as one over a connection limit. + struct OverLimit { + pipe_name: String, + bypasses: Arc, + } + + impl OverLimit { + fn of( + tag: &str, + state: &Arc, + capture: fn(&NamedPipeServer) -> anyhow::Result, + ) -> Self { + Self { + pipe_name: unique_pipe_name(tag), + bypasses: Arc::new(BypassAdmission::for_broker(Arc::clone(state), capture, Arc::default())), + } + } + + /// Connects a client, which the broker answers with the deadlines of the pipe server. + async fn connect(&self) -> (tokio::net::windows::named_pipe::NamedPipeClient, JoinHandle<()>) { + self.connect_within(BUSY_REPLY_DEADLINE, CONNECTION_DEADLINE).await + } + + async fn connect_within( + &self, + busy_deadline: Duration, + connection_deadline: Duration, + ) -> (tokio::net::windows::named_pipe::NamedPipeClient, JoinHandle<()>) { + let server = create_owned_test_instance(&self.pipe_name, false).expect("create pipe instance"); + let client = open_client(&self.pipe_name).expect("open client"); + server.connect().await.expect("accept client"); + let permit = Arc::new(Semaphore::new(1)) + .try_acquire_owned() + .expect("busy reply slot"); + let serving = tokio::spawn(reply_over_limit_within( + server, + permit, + no_grants(), + Arc::clone(&self.bypasses), + busy_deadline, + connection_deadline, + )); + + (client, serving) + } + + /// Sends `request` on a connection of its own, and returns the whole response. + async fn exchange(&self, request: &str) -> String { + let (mut client, serving) = self.connect().await; + let response = exchange(&mut client, request).await; + serving.await.expect("serving task"); + + response + } + + /// Waits until the broker serves a connection for each of `count` bypass tokens. + async fn serves(&self, count: usize) { + wait_for_bypass_slots(&self.bypasses, count).await; + } + } + + async fn wait_for_bypass_slots(bypasses: &BypassAdmission, count: usize) { + let deadline = Instant::now() + Duration::from_secs(10); + while bypasses.claimed.lock().len() != count { + assert!( + Instant::now() < deadline, + "the broker serves a connection for {count} bypass tokens" + ); + tokio::time::sleep(Duration::from_millis(10)).await; + } + } + + fn assert_error(response: &str, status: u16, code: &str, case: &str) { + assert!( + response.starts_with(&format!("HTTP/1.1 {status}")), + "{case}: {response}" + ); + let body = json_body(response); + let mut members: Vec<&String> = body.as_object().expect("a JSON object").keys().collect(); + members.sort_unstable(); + assert_eq!(members, ["Code", "Message"], "{case}: {response}"); + assert_eq!(body["Code"], code, "{case}: {response}"); + } + + fn assert_started(response: &str) { + assert!(response.starts_with("HTTP/1.1 200"), "{response}"); + assert!(json_body(response)["OperationId"].is_string(), "{response}"); + } + + // oracle: contract Devolutions/now-libraries@5ca59890e65f:policies/CONTRACT.wire.md §bypass + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn a_request_of_the_2_0_encoding_over_the_limit_is_broker_busy_unless_it_is_a_bypass_request_with_a_held_token() + { + let state = broker_state(); + let body = bypass_body("request-1"); + give_bypass_token(&state, BYPASS_TOKEN, &body); + let body = body.to_string(); + let broker = OverLimit::of("busy-v2", &state, capture_the_test_process); + + for (case, request) in [ + ( + "an endpoint that answers any client", + "GET /v2/health HTTP/1.1\r\nHost: broker\r\nConnection: close\r\n\r\n".to_owned(), + ), + ( + "no endpoint", + "GET /v2/unknown HTTP/1.1\r\nHost: broker\r\nConnection: close\r\n\r\n".to_owned(), + ), + ( + "a request that announces a body and sends none", + v2_header( + "POST", + "/v2/package-requests/evaluate", + "application/json", + &[], + "sixteen bytes...", + ), + ), + ("a bypass request without a token", bypass_request(&[], &body)), + ( + "a bypass request with the held token in two headers", + bypass_request(&[BYPASS_TOKEN, BYPASS_TOKEN], &body), + ), + ( + "a bypass request with a token the broker does not hold", + bypass_request(&["t0ken.never-given"], &body), + ), + ( + "an execution request with the held token", + format!( + "{}{body}", + v2_header( + "POST", + "/v2/package-requests/execute", + "application/json", + &[BYPASS_TOKEN], + &body + ) + ), + ), + ( + "another method on the path of a bypass request, with the held token", + v2_header( + "GET", + "/v2/package-requests/execute-bypass", + "application/json", + &[BYPASS_TOKEN], + "", + ), + ), + ] { + let response = broker.exchange(&request).await; + + assert_error(&response, 503, "BrokerBusy", case); + } + + // None of these replies used up the token, which still authorizes its request. + let response = broker.exchange(&bypass_request(&[BYPASS_TOKEN], &body)).await; + assert_started(&response); + } + + // oracle: mutant answering in the 2.0 encoding a request over the limit whose path does not start with `/v2/` + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn a_request_over_the_limit_whose_path_is_outside_the_2_0_prefix_gets_the_1_x_busy_reply() { + let broker = OverLimit::of("busy-prefix", &broker_state(), capture_the_test_process); + + for path in ["/v1/health", "/v2", "/v20/health", "/V2/health", "/"] { + let response = broker + .exchange(&format!( + "GET {path} HTTP/1.1\r\nHost: broker\r\nConnection: close\r\n\r\n" + )) + .await; + + assert!(response.starts_with("HTTP/1.1 503"), "{path}: {response}"); + // Every 1.x error names its kind, and no response of the 2.0 encoding has this member. + assert_eq!(json_body(&response)["ResponseKind"], "ErrorResponse", "{path}"); + } + } + + // oracle: contract Devolutions/now-libraries@5ca59890e65f:policies/CONTRACT.wire.md §bypass + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn a_bypass_request_over_the_limit_with_a_held_token_is_broker_busy_only_while_another_one_with_that_token_is_served() + { + const OTHER_TOKEN: &str = "another-t0ken"; + + let state = broker_state(); + let body = bypass_body("request-1"); + let other_body = bypass_body("request-2"); + give_bypass_token(&state, BYPASS_TOKEN, &body); + give_bypass_token(&state, OTHER_TOKEN, &other_body); + let body = body.to_string(); + let other_body = other_body.to_string(); + let broker = OverLimit::of("bypass-token", &state, capture_the_test_process); + + // The broker serves the first request from its header on, and until its body has arrived. + let (mut first, first_serving) = broker.connect().await; + write_request(&mut first, &bypass_header(&[BYPASS_TOKEN], &body)).await; + broker.serves(1).await; + + let busy = broker.exchange(&bypass_request(&[BYPASS_TOKEN], &body)).await; + assert_error(&busy, 503, "BrokerBusy", "the same token"); + + // A request with another token the broker holds is served meanwhile. + let other = broker.exchange(&bypass_request(&[OTHER_TOKEN], &other_body)).await; + assert_started(&other); + + // The busy reply left the token to the request the broker was serving. + let served = exchange(&mut first, &body).await; + assert_started(&served); + first_serving.await.expect("serving task"); + } + + // oracle: contract Devolutions/now-libraries@5ca59890e65f:policies/CONTRACT.wire.md §bypass + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn a_bypass_request_over_the_limit_is_served_once_the_broker_serves_no_other_one_with_its_token() { + let state = broker_state(); + let body = bypass_body("request-1"); + give_bypass_token(&state, BYPASS_TOKEN, &body); + let body = body.to_string(); + let broker = OverLimit::of("bypass-token-again", &state, capture_the_test_process); + + // A request that starts no operation does not use up its token. + let refused = broker + .exchange(&format!( + "{}{body}", + v2_header( + "POST", + "/v2/package-requests/execute-bypass", + "text/plain", + &[BYPASS_TOKEN], + &body + ) + )) + .await; + assert_error(&refused, 415, "UnsupportedMediaType", "another media type"); + + let served = broker.exchange(&bypass_request(&[BYPASS_TOKEN], &body)).await; + assert_started(&served); + } + + // oracle: contract Devolutions/now-libraries@5ca59890e65f:policies/CONTRACT.wire.md §bypass + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn every_held_bypass_token_gets_a_connection_beyond_those_the_broker_allows() { + let state = broker_state(); + let bypasses = Arc::new(BypassAdmission::for_broker( + Arc::clone(&state), + capture_the_test_process, + Arc::default(), + )); + let pipe_name = unique_pipe_name("bypass-slots"); + // The broker reads the request of one client over the connection limit at a time. + let (shutdown, mut dispatched, task) = spawn_accept_loop(&pipe_name, limits(1, 1)); + let admitted = open_client_when_listening(&pipe_name).await; + let (admitted_server, admission) = next_dispatched(&mut dispatched).await; + assert!(matches!(admission, Admission::Serve(_))); + + let mut clients = Vec::new(); + for index in 0..3 { + let token = format!("t0ken-{index}"); + let body = bypass_body(&format!("request-{index}")); + give_bypass_token(&state, &token, &body); + let body = body.to_string(); + let mut client = open_client_when_listening(&pipe_name).await; + let (server, admission) = next_dispatched(&mut dispatched).await; + let Admission::Busy(permit) = admission else { + panic!("a client over the connection limit is handed off as over the limit"); + }; + let serving = tokio::spawn(reply_over_limit(server, permit, no_grants(), Arc::clone(&bypasses))); + // The broker serves the request until its body has arrived. + write_request(&mut client, &bypass_header(&[&token], &body)).await; + wait_for_bypass_slots(&bypasses, index + 1).await; + clients.push((client, serving, body)); + } + + for (mut client, serving, body) in clients { + let response = exchange(&mut client, &body).await; + assert_started(&response); + serving.await.expect("serving task"); + } + drop((admitted, admitted_server, admission)); + shutdown.cancel(); + task.await.expect("accept loop task"); + } + + // oracle: mutant closing at the busy deadline a connection the broker serves for a bypass token + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn a_connection_served_for_a_bypass_token_outlives_the_busy_deadline() { + const BUSY_DEADLINE: Duration = Duration::from_millis(200); + + let state = broker_state(); + let body = bypass_body("request-1"); + give_bypass_token(&state, BYPASS_TOKEN, &body); + let body = body.to_string(); + let broker = OverLimit::of("bypass-deadline", &state, capture_the_test_process); + + let (mut client, serving) = broker.connect_within(BUSY_DEADLINE, Duration::from_secs(10)).await; + write_request(&mut client, &bypass_header(&[BYPASS_TOKEN], &body)).await; + broker.serves(1).await; + + // A client that connects later and sends nothing is closed at the busy deadline. + let (_idle, idle_serving) = broker.connect_within(BUSY_DEADLINE, Duration::from_secs(10)).await; + tokio::time::timeout(Duration::from_secs(3), idle_serving) + .await + .expect("the idle connection is closed at the busy deadline") + .expect("serving task"); + + let response = exchange(&mut client, &body).await; + assert_started(&response); + serving.await.expect("serving task"); + } + + fn capture_no_client(_server: &NamedPipeServer) -> anyhow::Result { + anyhow::bail!("the test looks up neither the client process nor its user") + } + + // oracle: contract Devolutions/now-libraries@5ca59890e65f:policies/CONTRACT.wire.md §authentication + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn a_bypass_request_over_the_limit_from_a_client_the_broker_does_not_authenticate_is_unauthenticated() { + type Capture = fn(&NamedPipeServer) -> anyhow::Result; + + let captures: [(&str, Capture); 2] = [ + ( + "a client whose process the broker does not identify", + capture_no_process, + ), + ("a client the broker can look up nothing of", capture_no_client), + ]; + + for (case, capture) in captures { + let state = broker_state(); + let body = bypass_body("request-1"); + give_bypass_token(&state, BYPASS_TOKEN, &body); + let body = body.to_string(); + let broker = OverLimit::of("bypass-unauthenticated", &state, capture); + + let response = broker.exchange(&bypass_request(&[BYPASS_TOKEN], &body)).await; + assert_error(&response, 401, "Unauthenticated", case); + + // `UnsupportedMediaType` comes before `Unauthenticated` in the order of the outcomes. + let response = broker + .exchange(&format!( + "{}{body}", + v2_header( + "POST", + "/v2/package-requests/execute-bypass", + "text/plain", + &[BYPASS_TOKEN], + &body + ) + )) + .await; + assert_error(&response, 415, "UnsupportedMediaType", case); + } + } + + static FIRST_CAPTURE_STARTED: AtomicBool = AtomicBool::new(false); + static FIRST_CAPTURE_RELEASED: AtomicBool = AtomicBool::new(false); + static FIRST_CAPTURE_RETURNED: AtomicBool = AtomicBool::new(false); + + /// Captures the test process, the first time only once `FIRST_CAPTURE_RELEASED` is set. + fn capture_the_first_client_late(server: &NamedPipeServer) -> anyhow::Result { + if !FIRST_CAPTURE_STARTED.swap(true, Ordering::SeqCst) { + let deadline = Instant::now() + Duration::from_secs(30); + while !FIRST_CAPTURE_RELEASED.load(Ordering::SeqCst) && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(10)); + } + FIRST_CAPTURE_RETURNED.store(true, Ordering::SeqCst); + } + + capture_the_test_process(server) + } + + // oracle: contract Devolutions/now-libraries@5ca59890e65f:policies/CONTRACT.wire.md §bypass + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn a_bypass_request_over_the_limit_is_served_once_the_connection_that_carried_its_token_has_ended() { + let state = broker_state(); + let body = bypass_body("request-1"); + give_bypass_token(&state, BYPASS_TOKEN, &body); + let body = body.to_string(); + let broker = OverLimit::of("bypass-left", &state, capture_the_first_client_late); + + // The first client leaves while the broker still looks up who it is. + let (mut first, first_serving) = broker.connect().await; + write_request(&mut first, &bypass_request(&[BYPASS_TOKEN], &body)).await; + let deadline = Instant::now() + Duration::from_secs(10); + while !FIRST_CAPTURE_STARTED.load(Ordering::SeqCst) { + assert!(Instant::now() < deadline, "the broker looks up the first client"); + tokio::time::sleep(Duration::from_millis(10)).await; + } + drop(first); + tokio::time::timeout(Duration::from_secs(10), first_serving) + .await + .expect("the connection ends once its client has left") + .expect("serving task"); + + // The broker serves no request with the token now, although that lookup has not returned. + let response = broker.exchange(&bypass_request(&[BYPASS_TOKEN], &body)).await; + let lookup_had_returned = FIRST_CAPTURE_RETURNED.load(Ordering::SeqCst); + FIRST_CAPTURE_RELEASED.store(true, Ordering::SeqCst); + + assert_started(&response); + assert!(!lookup_had_returned, "the lookup of the first client was still pending"); + } + + // oracle: mutant leaving the capture of a client served for a bypass token blocked after its connection ended, which keeps its thread until the connection deadline + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn the_capture_of_a_client_served_for_a_bypass_token_ends_when_its_connection_does() { + use std::io::Read as _; + + let state = broker_state(); + let body = bypass_body("request-1"); + give_bypass_token(&state, BYPASS_TOKEN, &body); + let body = body.to_string(); + let (reader, _writer) = anonymous_pipe(); + let (capturing_tx, mut capturing) = tokio::sync::mpsc::unbounded_channel(); + let (returned_tx, mut returned) = tokio::sync::mpsc::unbounded_channel(); + let broker = OverLimit { + pipe_name: unique_pipe_name("bypass-capture-cancelled"), + bypasses: Arc::new(BypassAdmission::new( + move |request| crate::v2::routes::held_bypass_token(&state, request), + // A capture that waits in synchronous I/O for as long as nothing cancels it. + move |_server| { + capturing_tx.send(()).expect("the test holds the receiver"); + let mut byte = [0u8; 1]; + let read = (&reader).read(&mut byte).context("read the pipe"); + returned_tx.send(()).expect("the test holds the receiver"); + read.map(|_read| axum::Router::new()) + }, + )), + }; + + let (mut client, serving) = broker.connect().await; + write_request(&mut client, &bypass_request(&[BYPASS_TOKEN], &body)).await; + recv_within(&mut capturing, "the broker captures the client").await; + drop(client); + + // The wait is shorter than the connection deadline, at which any capture ends. + recv_within(&mut returned, "the capture ends once its connection has").await; + serving.await.expect("serving task"); + } + + // oracle: contract Devolutions/now-libraries@5ca59890e65f:policies/CONTRACT.wire.md §bypass + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn a_bypass_request_over_the_per_user_limit_with_a_held_token_is_served() { + let state = broker_state(); + let body = bypass_body("request-1"); + give_bypass_token(&state, BYPASS_TOKEN, &body); + let body = body.to_string(); + let pipe_name = unique_pipe_name("bypass-per-user"); + let bypasses = Arc::new(BypassAdmission::for_broker( + Arc::clone(&state), + capture_the_test_process, + Arc::default(), + )); + let busy_replies = Arc::new(Semaphore::new(1)); + let connection_permits = Arc::new(Semaphore::new(8)); + // The user of the test process may have one connection. + let admission = Arc::new(UserAdmission::new( + 1, + Arc::clone(&busy_replies), + no_grants(), + Arc::clone(&bypasses), + )); + let (served_tx, mut served) = tokio::sync::mpsc::unbounded_channel(); + let release = Arc::new(Semaphore::new(0)); + let connect = async || { + connect_admitted( + &pipe_name, + &admission, + &connection_permits, + served_tx.clone(), + Arc::clone(&release), + ) + .await + }; + let (_admitted, admitted_task) = connect().await; + recv_within(&mut served, "the first client of the user is served").await; + + // The broker serves the bypass request from its header on, and until its body has arrived. + let (mut held, held_task) = connect().await; + write_request(&mut held, &bypass_header(&[BYPASS_TOKEN], &body)).await; + wait_for_bypass_slots(&bypasses, 1).await; + // Its connection left the only busy reply slot to the next client over the limit. + let (mut other, other_task) = connect().await; + let busy = exchange( + &mut other, + "GET /v2/health HTTP/1.1\r\nHost: broker\r\nConnection: close\r\n\r\n", + ) + .await; + let response = exchange(&mut held, &body).await; + + assert_error(&busy, 503, "BrokerBusy", "another request over the per-user limit"); + assert_started(&response); + + other_task.await.expect("serving task"); + held_task.await.expect("serving task"); + release.add_permits(1); + admitted_task.await.expect("serving task"); + } + const HEALTH_REQUEST: &str = "GET /v1/health HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"; fn grant_request(grant: &str) -> String { @@ -2011,6 +2914,13 @@ mod tests { )) } + fn no_bypasses() -> Arc { + Arc::new(BypassAdmission::new( + |_| None, + |_| anyhow::bail!("the broker holds no bypass token"), + )) + } + fn issue_grant(store: &crate::remote_grant::RemoteGrantStore) -> String { let spec = crate::remote_grant::GrantSpec { operation: now_policy_api::Operation::Uninstall, @@ -2091,6 +3001,7 @@ mod tests { MAX_CONCURRENT_CONNECTIONS_PER_USER, Arc::new(Semaphore::new(MAX_CONCURRENT_BUSY_REPLIES)), grant_admission, + no_bypasses(), )); let (served_tx, mut served) = tokio::sync::mpsc::unbounded_channel(); let release_local = Arc::new(Semaphore::new(0)); @@ -2165,7 +3076,12 @@ mod tests { let Admission::Busy(permit) = admission else { panic!("a client over the connection limit is handed off as over the limit"); }; - let serving = tokio::spawn(reply_over_limit(server, permit, Arc::clone(&grant_admission))); + let serving = tokio::spawn(reply_over_limit( + server, + permit, + Arc::clone(&grant_admission), + no_bypasses(), + )); write_request(&mut client, &grant_request(grant)).await; recv_within(&mut grant_served, "a client presenting a pending grant is served").await; grant_clients.push((client, serving)); @@ -2203,7 +3119,12 @@ mod tests { let (admission, mut grant_served, release_grant) = held_grant_admission(MAX_GRANT_CONNECTIONS, store); let busy_replies = Arc::new(Semaphore::new(1)); let connection_permits = Arc::new(Semaphore::new(8)); - let admission = Arc::new(UserAdmission::new(1, Arc::clone(&busy_replies), admission)); + let admission = Arc::new(UserAdmission::new( + 1, + Arc::clone(&busy_replies), + admission, + no_bypasses(), + )); let (served_tx, mut served) = tokio::sync::mpsc::unbounded_channel(); let release_local = Arc::new(Semaphore::new(0)); let connect = async || { @@ -2293,6 +3214,8 @@ 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(), }); // The test process is the client, and its executable is not signed. let client = PipeClient::from_current_process().expect("capture the test process"); @@ -2369,7 +3292,7 @@ mod tests { let permit = Arc::new(Semaphore::new(1)) .try_acquire_owned() .expect("busy reply slot"); - let serving = tokio::spawn(reply_over_limit(server, permit, Arc::clone(&grants))); + let serving = tokio::spawn(reply_over_limit(server, permit, Arc::clone(&grants), no_bypasses())); responses.push(exchange(&mut client, &request).await); serving.await.expect("serving task"); } @@ -2411,7 +3334,7 @@ mod tests { .expect("busy reply slot"); ( client, - tokio::spawn(reply_over_limit(server, permit, Arc::clone(&grants))), + tokio::spawn(reply_over_limit(server, permit, Arc::clone(&grants), no_bypasses())), ) }; @@ -2441,17 +3364,8 @@ mod tests { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn a_capture_blocked_in_synchronous_io_ends_at_its_deadline() { use std::io::Read as _; - use std::os::windows::io::FromRawHandle as _; - let mut read = windows::Win32::Foundation::HANDLE::default(); - let mut write = windows::Win32::Foundation::HANDLE::default(); - // SAFETY: Both output pointers are valid, and no security attributes are passed. - unsafe { windows::Win32::System::Pipes::CreatePipe(&mut read, &mut write, None, 0) } - .expect("create an anonymous pipe"); - // SAFETY: `CreatePipe` returned this new handle, which nothing else owns. - let mut reader = unsafe { std::fs::File::from_raw_handle(read.0) }; - // SAFETY: `CreatePipe` returned this new handle, which nothing else owns. - let _writer = unsafe { std::fs::File::from_raw_handle(write.0) }; + let (mut reader, _writer) = anonymous_pipe(); let deadline = Instant::now() + Duration::from_millis(200); let capture = spawn_interruptible_capture(deadline, move || { let mut byte = [0u8; 1]; @@ -2466,6 +3380,47 @@ mod tests { assert!(deadline <= Instant::now()); } + // oracle: mutant leaving the capture of a client whose connection ended blocked in synchronous I/O until its deadline, which keeps its thread + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn a_capture_blocked_in_synchronous_io_ends_when_it_is_cancelled() { + use std::io::Read as _; + + let (mut reader, _writer) = anonymous_pipe(); + let deadline = Instant::now() + Duration::from_secs(60); + let cancelled = CancellationToken::new(); + let capture = spawn_cancellable_capture(deadline, cancelled.clone(), move || { + let mut byte = [0u8; 1]; + reader.read(&mut byte).context("read the pipe") + }); + + cancelled.cancel(); + let result = tokio::time::timeout(Duration::from_secs(5), capture) + .await + .expect("the blocked capture ends once it is cancelled") + .expect("the capture does not panic"); + + assert!(result.is_err(), "the blocked read is cancelled: {result:?}"); + assert!(Instant::now() < deadline); + } + + /// The two ends of an anonymous pipe: one to read from, which blocks while the other one is open and writes + /// nothing. + fn anonymous_pipe() -> (std::fs::File, std::fs::File) { + use std::os::windows::io::FromRawHandle as _; + + let mut read = windows::Win32::Foundation::HANDLE::default(); + let mut write = windows::Win32::Foundation::HANDLE::default(); + // SAFETY: Both output pointers are valid, and no security attributes are passed. + unsafe { windows::Win32::System::Pipes::CreatePipe(&mut read, &mut write, None, 0) } + .expect("create an anonymous pipe"); + // SAFETY: `CreatePipe` returned this new handle, which nothing else owns. + let reader = unsafe { std::fs::File::from_raw_handle(read.0) }; + // SAFETY: `CreatePipe` returned this new handle, which nothing else owns. + let writer = unsafe { std::fs::File::from_raw_handle(write.0) }; + + (reader, writer) + } + // oracle: mutant leaving the client of a connection cut short connected until the capture of its identity ends #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn a_connection_cut_short_during_capture_is_disconnected_before_the_capture_ends() { @@ -2494,6 +3449,7 @@ mod tests { server, permit, Arc::clone(&grants), + no_bypasses(), Duration::from_millis(100), Duration::from_millis(300), )); @@ -2537,6 +3493,7 @@ mod tests { server, permit, Arc::clone(&grants), + no_bypasses(), BUSY_DEADLINE, Duration::from_secs(10), )); @@ -2578,10 +3535,30 @@ mod tests { anyhow::bail!("injected capture failure") } - /// Counts the warnings emitted on the thread it is the default subscriber of. - struct WarningCounter(Arc); + /// Counts the events at least as severe as a level that are emitted on the thread it is the default subscriber of. + struct EventCounter { + events: Arc, + least_severe: tracing::Level, + } - impl tracing::Subscriber for WarningCounter { + impl EventCounter { + fn of_warnings(events: Arc) -> Self { + Self { + events, + least_severe: tracing::Level::WARN, + } + } + + /// Counts every event that a log at the level `INFO` holds. + fn above_debug(events: Arc) -> Self { + Self { + events, + least_severe: tracing::Level::INFO, + } + } + } + + impl tracing::Subscriber for EventCounter { fn enabled(&self, _metadata: &tracing::Metadata<'_>) -> bool { true } @@ -2595,8 +3572,9 @@ mod tests { fn record_follows_from(&self, _span: &tracing::span::Id, _follows: &tracing::span::Id) {} fn event(&self, event: &tracing::Event<'_>) { - if *event.metadata().level() == tracing::Level::WARN { - self.0.fetch_add(1, Ordering::SeqCst); + // A more severe level compares as the lesser one. + if *event.metadata().level() <= self.least_severe { + self.events.fetch_add(1, Ordering::SeqCst); } } @@ -2609,10 +3587,10 @@ mod tests { #[tokio::test] async fn rejections_of_clients_whose_user_or_identity_cannot_be_captured_are_rate_limited_in_the_log() { let warnings = Arc::new(std::sync::atomic::AtomicUsize::new(0)); - let _subscriber = tracing::subscriber::set_default(WarningCounter(Arc::clone(&warnings))); + let _subscriber = tracing::subscriber::set_default(EventCounter::of_warnings(Arc::clone(&warnings))); let pipe_name = unique_pipe_name("unauthenticated"); let connection_permits = Arc::new(Semaphore::new(1)); - let admission = UserAdmission::new(1, Arc::new(Semaphore::new(1)), no_grants()); + let admission = UserAdmission::new(1, Arc::new(Semaphore::new(1)), no_grants(), no_bypasses()); let was_served = AtomicBool::new(false); type Lookup = fn(&NamedPipeServer) -> anyhow::Result; @@ -2651,6 +3629,43 @@ mod tests { ); } + // oracle: mutant logging every client whose process the broker fails to identify, where it identifies them or where it serves them, or logging its connection and its disconnection at `INFO`, which lets a local flood of such connections fill the log + #[tokio::test] + async fn clients_whose_process_is_not_identified_are_rate_limited_in_the_log() { + static EVENTS: std::sync::LazyLock> = + std::sync::LazyLock::new(Arc::default); + + /// Identifies no client process, like [`capture_no_process`], and counts the events of the capture. + /// + /// The capture runs on another thread than the test, where the subscriber of the test counts nothing. + fn capture(server: &NamedPipeServer) -> anyhow::Result { + let _subscriber = tracing::subscriber::set_default(EventCounter::above_debug(Arc::clone(&EVENTS))); + capture_no_process(server) + } + + let _subscriber = tracing::subscriber::set_default(EventCounter::above_debug(Arc::clone(&EVENTS))); + let unidentified = Arc::new(UnidentifiedClientLog::default()); + + for tag in ["unidentified-first", "unidentified-second"] { + let health = exchange_reporting( + tag, + capture, + "GET /v2/health HTTP/1.1\r\nHost: broker\r\n\r\n", + Arc::clone(&unidentified), + ) + .await; + + assert!(health.starts_with("HTTP/1.1 200"), "the client is served: {health}"); + } + + // The lines of each connection are below `INFO`, so the warning for the first client is the only event counted. + assert_eq!( + EVENTS.load(Ordering::SeqCst), + 1, + "only the first of the clients is logged" + ); + } + // oracle: regression #2029 #[tokio::test] async fn connected_client_user_is_looked_up_from_the_pipe() { @@ -2664,6 +3679,147 @@ 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), + agent_version: now_policy_api::v2::ServerVersion::parse("1.2.3").expect("a server version"), + 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 { + exchange_reporting(tag, capture, request, Arc::default()).await + } + + /// Exchanges `request` like [`exchange_captured`], with a broker that reports to `unidentified` the clients + /// whose process it fails to identify. + async fn exchange_reporting( + tag: &str, + capture: fn(&NamedPipeServer) -> anyhow::Result, + request: &str, + unidentified: Arc, + ) -> 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)), no_grants(), no_bypasses()); + 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, + connected_pipe_client_user_sid, + capture, + ConnectedClient::user_sid, + |server, client| serve_client(state, server, client, &unidentified), + ) + .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/policy_store/mod.rs b/crates/now-package-broker/src/policy_store/mod.rs index b050b0c22..093863bd0 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, @@ -1312,6 +1308,143 @@ 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)>, + 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)] +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) + } + + /// 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), + }) + } + + /// 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, + _source: PolicyConfigurationSource, + _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" + ))); + } + 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()) + } +} + #[cfg(test)] mod storage_tests { use now_policy::PolicyDraftDocument; 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/grant.rs b/crates/now-package-broker/src/server/grant.rs index da78a7aed..886f4b01c 100644 --- a/crates/now-package-broker/src/server/grant.rs +++ b/crates/now-package-broker/src/server/grant.rs @@ -341,6 +341,8 @@ 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 1f08e06ee..95f66df76 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 grant::presented_grant; pub(crate) use pipe_identity::PipeIdentity; use responses::{ @@ -191,8 +192,17 @@ pub struct BrokerState { /// Reads the MSI product code of the installed Devolutions Agent, which no route uninstalls. /// /// `Ok(None)` means that no Agent MSI is installed. - /// An error rejects every request that removes a package. + /// An error rejects every request of the 1.x routes that removes a package, and every request of the 2.0 encoding + /// that removes one through WinGet. 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, } /// Reads the MSI product code of the installed Devolutions Agent from the registry. @@ -272,14 +282,17 @@ fn build_router(state: Arc, client: PipeClient, identity: Option Response { @@ -745,7 +758,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) { @@ -1295,6 +1308,8 @@ 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(), } } @@ -2194,6 +2209,8 @@ 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) } @@ -2378,6 +2395,8 @@ 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 8b8de7070..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,11 +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. @@ -89,6 +108,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. @@ -151,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/bypass/mod.rs b/crates/now-package-broker/src/v2/bypass/mod.rs new file mode 100644 index 000000000..ea01e07af --- /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}; +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..d1b78db75 --- /dev/null +++ b/crates/now-package-broker/src/v2/bypass/reading.rs @@ -0,0 +1,365 @@ +//! 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 + +use now_policy_api::v2; +use now_policy_eval as eval; + +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 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, +} + +/// Reads a bypass request ([§bypass-reading]). +/// +/// 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) -> Result { + let mut read_as = wire::evaluator_bypass_request(request); + + match eval::read_bypass(&read_as)? { + eval::BypassReading::Readable { source } => { + read_as.source = source; + Ok(Reading::Readable(Box::new(read_as))) + } + eval::BypassReading::Unreadable => Ok(Reading::Unreadable), + } +} + +#[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 request the operation of `request` runs for. + fn readable(request: &v2::BypassRequest) -> eval::Request { + match read(request) { + 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() { + 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 read = readable(&request); + + assert_eq!(read.operation, eval::Operation::Update); + assert_eq!(read.manager, eval::Manager::Chocolatey); + assert_eq!(read.source.map(|source| source.name).as_deref(), Some("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)), Ok(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).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", "NonElevated"), + ("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}"); + } + } + + // 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), 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 + #[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), Ok(Reading::Unreadable), "{manager} {operation}"); + } + } + } + + // 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), Ok(Reading::Unreadable), "{manager} {operation}"); + } + } + } + + // oracle: contract Devolutions/now-libraries@3014fcbb899d:policies/CONTRACT.wire.md §bypass + #[test] + 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_eq!(read(&uninstall_with_source), Err(eval::BadRequest)); + } +} 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..f75ae2b05 --- /dev/null +++ b/crates/now-package-broker/src/v2/bypass/tokens.rs @@ -0,0 +1,539 @@ +//! 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 after the Agent gave it the broker discards a token that no request used up, and forgets one that a +/// request used up ([§bypass]). +/// +/// 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. +/// +/// 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. +/// +/// 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, or remembers that a request used it up. + 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 was already given this bypass token", + Self::TooManyTokens => "the broker holds as many bypass tokens as it allows", + }) + } +} + +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, +} + +/// The bypass tokens the broker holds, which a restart of the broker discards. +#[derive(Default)] +pub(crate) struct BypassTokens { + given: 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 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. + /// 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]). + /// + /// 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( + 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) + } + + /// Holds `token` like [`BypassTokens::hold`], as a token the Agent gave at `now`. + pub(crate) 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()); + + // `now` may be earlier than the time the tokens are locked at, so the lifetime of the token ends no later. + // A token whose lifetime ended in between still counts here, and is forgotten when the tokens are next locked. + let mut given = self.lock_at(now).given; + if given.contains_key(&digest) { + return Err(HoldError::AlreadyHeld); + } + if !(given.len() < MAX_HELD_TOKENS) { + return Err(HoldError::TooManyTokens); + } + given.insert( + digest, + Given { + bound: Some(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 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. + /// + /// [§bypass]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#bypass + pub(crate) fn lock(&self) -> HeldTokens<'_> { + // UNTESTED: The time is read by `lock_with`, once the tokens are locked, and never before this call waits for + // them. + // A time read before the wait lets a token authorize a request that waited for the tokens past the end of its + // 60 seconds. + // The test of `lock_with` gives it a clock of its own; when changing this function, check that it passes a + // function that reads the time, and not a time. + self.lock_with(Instant::now) + } + + fn lock_at(&self, now: Instant) -> HeldTokens<'_> { + self.lock_with(|| now) + } + + /// Locks the tokens like [`BypassTokens::lock`], and reads the time from `clock` once they are locked. + fn lock_with(&self, clock: impl FnOnce() -> Instant) -> HeldTokens<'_> { + let mut held = HeldTokens { + given: self.given.lock(), + }; + // The time is read once the tokens are locked, however long that took: a request that waited for them past + // the end of the lifetime of its token finds no token. + held.discard_expired_at(clock()); + + held + } +} + +/// The tokens the broker holds and the used-up ones it remembers, locked ([`BypassTokens::lock`]). +pub(crate) struct HeldTokens<'a> { + given: MutexGuard<'a, HashMap>, +} + +impl HeldTokens<'_> { + /// Tells whether the broker holds the token `token`, which it does until the token is used up or discarded + /// ([§bypass]). + /// + /// [§bypass]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#bypass + pub(crate) fn holds(&self, token: &TokenDigest) -> bool { + self.given.get(token).is_some_and(|given| given.bound.is_some()) + } + + /// 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.given + .get(token) + .and_then(|given| given.bound.as_ref()) + .is_some_and(|bound| bound.user_sid == *owner_sid && bound.request == *request) + } + + /// Forgets the tokens whose lifetime has ended since the tokens were locked, used up or not. + /// + /// A request that kept the tokens locked while it did something that takes time calls this before it lets a token + /// start an operation ([§bypass]). + /// + /// [§bypass]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#bypass + pub(crate) fn discard_expired(&mut self) { + self.discard_expired_at(Instant::now()); + } + + fn discard_expired_at(&mut self, now: Instant) { + self.given.retain(|_, token| now < token.expires_at); + } + + /// 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) { + if let Some(given) = self.given.get_mut(token) { + given.bound = None; + } + } +} + +#[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: contract Devolutions/now-libraries@5ca59890e65f:policies/CONTRACT.wire.md §bypass + #[test] + fn the_broker_holds_a_token_from_when_it_is_given_until_it_is_used_up_or_discarded() { + let tokens = BypassTokens::default(); + let given = Instant::now(); + + assert!(!tokens.lock_at(given).holds(&digest(TOKEN))); + + tokens + .hold_at(given, TOKEN, request(&install()), user()) + .expect("hold the token"); + tokens + .hold_at(given, "another-token", request(&install()), user()) + .expect("hold the other token"); + assert!(tokens.lock_at(given).holds(&digest(TOKEN))); + assert!(!tokens.lock_at(given).holds(&digest("a-token-never-given"))); + + tokens.lock_at(given).use_up(&digest(TOKEN)); + assert!(!tokens.lock_at(given).holds(&digest(TOKEN))); + assert!(tokens.lock_at(given).holds(&digest("another-token"))); + + let sixty_seconds_after = given + Duration::from_secs(60); + assert!(!tokens.lock_at(sixty_seconds_after).holds(&digest("another-token"))); + } + + #[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()); + + // 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(sixty_seconds_after) + .authorizes(&digest(TOKEN), &user(), &bound) + ); + } + + // oracle: mutant reading the time before it waits for the tokens, which lets a token authorize a request that waited for them past the end of its lifetime + #[test] + fn the_time_that_ends_the_lifetime_of_a_token_is_read_once_the_tokens_are_locked() { + let tokens = holding(); + let locked_when_read = std::cell::Cell::new(false); + + let held = tokens.lock_with(|| { + locked_when_read.set(tokens.given.is_locked()); + Instant::now() + }); + drop(held); + + assert!( + locked_when_read.get(), + "the time was read before the tokens were locked" + ); + } + + // 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(())); + } + + // 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: contract Devolutions/now-libraries@3014fcbb899d:policies/CONTRACT.wire.md §bypass + #[test] + 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 { + 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 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!(one_more, Err(HoldError::TooManyTokens)); + assert_eq!(after_its_lifetime, Ok(())); + } +} diff --git a/crates/now-package-broker/src/v2/execution/mod.rs b/crates/now-package-broker/src/v2/execution/mod.rs index 22892b6b0..418349f44 100644 --- a/crates/now-package-broker/src/v2/execution/mod.rs +++ b/crates/now-package-broker/src/v2/execution/mod.rs @@ -4,5 +4,7 @@ mod operations; mod owner; mod plan; -pub use self::operations::{Caller, Existing, OperationState, Operations, RETENTION, Start, StartedOperation, Status}; +pub use self::operations::{ + Caller, Existing, IdentifyPipeClient, 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 d2b02965c..1928c97b4 100644 --- a/crates/now-package-broker/src/v2/execution/operations.rs +++ b/crates/now-package-broker/src/v2/execution/operations.rs @@ -9,12 +9,12 @@ use now_policy_api::v2; use now_policy_eval::Request; use parking_lot::Mutex; use tokio_util::sync::CancellationToken; -use tracing::{info, warn}; +use tracing::{info, trace, warn}; use uuid::Uuid; use super::owner::Owner; -use super::plan::plan; -use crate::event_channel::{ChannelVersion, OperationEventSink, open_operation_channel_announcing}; +use super::plan::plan_protecting_agent; +use crate::event_channel::{Audience, ChannelPipe, ChannelVersion, OperationEventSink, open_operation_channel_serving}; use crate::executor::{ CommandExecutor, ExecutionContext, KillProcessNames, ProcessStartedCallback, TokenElevationCheck, is_canceled_error, }; @@ -100,8 +100,54 @@ 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) => { + // This failure may repeat with every connection the channel refuses for it. + trace!( + %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>, } @@ -218,11 +264,52 @@ 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 + /// it removes the package through WinGet and 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(), @@ -245,8 +332,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. @@ -269,8 +356,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)), @@ -588,12 +676,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, @@ -1354,4 +1460,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/execution/plan.rs b/crates/now-package-broker/src/v2/execution/plan.rs index 72d5ac93a..36de9f37d 100644 --- a/crates/now-package-broker/src/v2/execution/plan.rs +++ b/crates/now-package-broker/src/v2/execution/plan.rs @@ -6,7 +6,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}; @@ -72,10 +72,7 @@ pub(super) fn plan(request: &Request) -> anyhow::Result { ); } - let elevation = match request.elevation { - Elevation::NonElevated => v1::Elevation::Standard, - Elevation::Elevated => v1::Elevation::Elevated, - }; + let elevation = builder_elevation(request); let mut builder_request = builder_request(request, elevation); // SECURITY: A run as administrator that works for the user alone would write with administrator rights into // folders that the user's non-elevated processes can change. @@ -175,6 +172,43 @@ 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 through WinGet 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. + // No identifier of another manager holds it, so the code is read for WinGet only ([§protected-package]). + // + // [§protected-package]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#protected-package + let builder_request = builder_request(request, builder_elevation(request)); + if crate::evaluator::removes_package(&builder_request) { + let agent_product_code = if request.manager == Manager::Winget { + agent_product_code() + .context("the broker cannot verify that the request does not uninstall the Devolutions Agent")? + } else { + None + }; + if crate::evaluator::uninstalls_protected_package(&builder_request, agent_product_code) { + bail!("the broker does not uninstall the Devolutions Agent"); + } + } + + plan(request) +} + +/// Returns the elevation that the command builders know the one of `request` as. +fn builder_elevation(request: &Request) -> v1::Elevation { + match request.elevation { + Elevation::NonElevated => v1::Elevation::Standard, + Elevation::Elevated => v1::Elevation::Elevated, + } +} + /// Whether the broker makes the command of `request` machine-wide ([§manager-winget], [§manager-powershell]). /// /// It does so for an elevated request without `Scope`, by naming the machine scope among the options it builds. diff --git a/crates/now-package-broker/src/v2/mod.rs b/crates/now-package-broker/src/v2/mod.rs index b75f79586..2ad251882 100644 --- a/crates/now-package-broker/src/v2/mod.rs +++ b/crates/now-package-broker/src/v2/mod.rs @@ -3,6 +3,10 @@ //! 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; pub mod wire; + +pub use self::routes::HeldOperations; diff --git a/crates/now-package-broker/src/v2/policy.rs b/crates/now-package-broker/src/v2/policy.rs index 03b62a23d..05481d16a 100644 --- a/crates/now-package-broker/src/v2/policy.rs +++ b/crates/now-package-broker/src/v2/policy.rs @@ -25,7 +25,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::>())?; // Two conversions stay fallible by their types: the bytes to text, and the revision to the range a response // carries. @@ -135,28 +135,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, - } -} - #[cfg(test)] pub(crate) mod tests { use chrono::TimeZone as _; 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..ae751aff0 --- /dev/null +++ b/crates/now-package-broker/src/v2/routes/bypass.rs @@ -0,0 +1,184 @@ +//! 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 super::{Connection, error_response, internal_error, json}; +use crate::server::BrokerState; +use crate::v2::bypass::{Reading, TokenDigest, read}; +use crate::v2::execution::{Existing, Start, StartedOperation}; +use crate::v2::wire; + +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: 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 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. + // 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) { + Some(Existing::Replayed(started)) => return bypass_response(started), + // 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 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 => {} + } + + if !tokens.authorizes(&token, caller.owner.user_sid(), request) { + return token_rejected(); + } + + // Nothing starts, so the token is not used up. + if let Some(protected) = self.protected_uninstall(request.into()) { + return protected; + } + + let package_request = match read(request) { + 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. + Err(error) => return internal_error(&error), + }; + + // The lifetime of the token may have ended since the tokens were locked: reading the product code of the + // installed Agent and reading the request take time. + // A token authorizes no request from 60 seconds after the Agent gave it, so the time is read again here, + // as late as this function can read it. + // + // UNTESTED: Once a token passed this check, its operation is held without a wait: the start plans the + // operation, which reads the product code of the installed Agent once more, locks its registry, and creates + // the event pipe, and does nothing else before its registry holds the operation. + // A token whose 60 seconds end during those steps starts an operation all the same, where the contract has an + // unused token start none, so every step added there lets a token start an operation later. + // No test makes those steps take time; when changing the start or this function, keep what waits for another + // process, or reads what another process can hold, before this check, and nothing between the check and the + // start. + tokens.discard_expired(); + if !tokens.holds(&token) { + return token_rejected(); + } + + let start = registries + .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 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 { + 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 `request`, when `request` is a bypass request with exactly one header +/// that carries a token and the broker of `state` holds that token ([§bypass]). +/// +/// The broker serves such a request beyond its connection limits, unless it already serves one with the same token. +/// Nothing of the body is read, and the token authorizes nothing here: what the request gets is for its endpoint to +/// say. +/// +/// [§bypass]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#bypass +pub(crate) fn held_bypass_token(state: &BrokerState, request: &axum::http::Request) -> Option { + let route = wire::route(request.method().as_str(), request.uri().path()).ok()?; + if route.endpoint != v2::Endpoint::ExecuteBypass { + return None; + } + let token = token_of(request.headers())?; + + state + .operations + .of(state) + .bypass_tokens + .lock() + .holds(&token) + .then_some(token) +} + +/// 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; + } + + // Space and tab are the only ASCII whitespace a header value holds. + Some(TokenDigest::of(value.as_bytes().trim_ascii())) +} + +/// 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: 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/capabilities.rs b/crates/now-package-broker/src/v2/routes/capabilities.rs new file mode 100644 index 000000000..6dbdef374 --- /dev/null +++ b/crates/now-package-broker/src/v2/routes/capabilities.rs @@ -0,0 +1,164 @@ +//! 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 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( + 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: agent_version.clone(), + 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 { + let manager = manager(capability.manager); + // A Vcpkg request that has `Package.Architecture` is unreadable ([§manager-vcpkg]), so its capability offers a + // client no architecture to name. + // + // [§manager-vcpkg]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.policy.md#manager-vcpkg + let architectures = if manager == v2::Manager::Vcpkg { + Vec::new() + } else { + capability.architectures.into_iter().map(architecture).collect() + }; + + v2::ManagerCapability { + manager, + operations: capability.operations.into_iter().map(operation).collect(), + scopes: capability.scopes.into_iter().map(scope).collect(), + architectures, + 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 => &[], + } +} + +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/held.rs b/crates/now-package-broker/src/v2/routes/held.rs new file mode 100644 index 000000000..f9242a623 --- /dev/null +++ b/crates/now-package-broker/src/v2/routes/held.rs @@ -0,0 +1,159 @@ +//! 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}; + +use anyhow::Context as _; +use now_policy_api::v2; +use tokio_util::sync::CancellationToken; + +use super::operations::owner_of; +use crate::auth::{PipeClient, connected_pipe_client_process_id}; +use crate::server::BrokerState; +use crate::v2::bypass::BypassTokens; +use crate::v2::execution::{IdentifyPipeClient, 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 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. +/// +/// 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 +/// 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 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. + registries: Arc>, +} + +pub(super) struct Registries { + pub(super) executions: Executions, + pub(super) bypasses: Bypasses, + pub(super) bypass_tokens: BypassTokens, +} + +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), + 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(), + }) + } + + /// 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) { + let registries = self.of(state); + registries.executions.clone().spawn_eviction_task(shutdown.clone()); + 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: 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 +// 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. +// +// 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 = 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)) + }) +} + +#[cfg(test)] +impl HeldOperations { + /// Gives the broker of `state` the bypass token `token` with the request and the user it binds, as Devolutions + /// Agent does, and returns whether the broker holds it for them after that. + pub(crate) fn give_bypass_token( + &self, + state: &BrokerState, + token: &str, + request: &serde_json::Value, + user_sid: win_api_wrappers::identity::sid::Sid, + ) -> bool { + self.give_bypass_token_at(state, token, request, user_sid, std::time::Instant::now()) + } + + /// Gives the broker of `state` a bypass token like [`HeldOperations::give_bypass_token`], as Devolutions Agent + /// did at `given`. + pub(crate) fn give_bypass_token_at( + &self, + state: &BrokerState, + token: &str, + request: &serde_json::Value, + user_sid: win_api_wrappers::identity::sid::Sid, + given: std::time::Instant, + ) -> bool { + let request = crate::v2::wire::read_bypass_request(request.to_string().as_bytes()).expect("a bypass request"); + + self.of(state) + .bypass_tokens + .hold_at(given, token, request, user_sid) + .is_ok() + } +} 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..1a79b4598 --- /dev/null +++ b/crates/now-package-broker/src/v2/routes/mod.rs @@ -0,0 +1,611 @@ +//! 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 + +mod bypass; +mod capabilities; +mod held; +mod operations; +mod policy; +mod protection; + +use std::future::Future; +use std::panic::AssertUnwindSafe; +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(crate) use self::bypass::held_bypass_token; +pub use self::held::HeldOperations; +use super::policy::{EvaluationError, is_not_runnable}; +use super::wire; +use crate::audit::{DenialReason, WriteAudit}; +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 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 the response to a request of the 2.0 encoding that is `BrokerBusy` ([§errors]). +/// +/// The broker sends it without reading the request body, and starts and changes nothing for the request. +/// +/// [§errors]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#errors +pub(crate) fn busy() -> Response { + error_response(v2::ErrorCode::BrokerBusy, "the broker is busy; send the request again") +} + +/// Returns the response to a request of the 2.0 encoding whose endpoint needs an authenticated client, from a client +/// the broker could neither identify nor name the user of ([§authentication]). +/// +/// The body of the request is not read. +/// +/// [§authentication]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#authentication +pub(crate) fn refuse_unknown_client(request: Request) -> Response { + let (parts, _body) = request.into_parts(); + + match find_endpoint(&parts) { + Ok(_route) => unauthenticated(), + Err(response) => *response, + } +} + +/// Tells whether `request` is one of the 2.0 encoding ([§transport]). +/// +/// [§transport]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#transport +pub(crate) fn is_v2(request: &axum::http::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 route = match find_endpoint(&parts) { + Ok(route) => route, + Err(response) => return *response, + }; + let endpoint = route.endpoint; + + if let Some(response) = self.refuse_client(endpoint) { + return response; + } + + 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 unread_body(&error); + } + }; + + self.serve(&route, &parts.headers, &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(unauthenticated()); + } + + 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(), + &configured_policy_path(&self.state), + reason, + ); + } + + /// 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(), + &configured_policy_path(&self.state), + ) + } + + /// 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()); + } + + /// 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(&self.state.agent_version, managers) { + Ok(response) => json(StatusCode::OK, &response), + Err(error) => internal_error(&error), + } + } + + /// 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 { + if let Some(protected) = self.protected_uninstall(request.into()) { + return protected; + } + + 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 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 + 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, + "the broker holds no accepted policy", + ))); + }; + + let evaluated_at = Utc::now(); + let decision = match policy.evaluate(&request, evaluated_at) { + Ok(decision) => decision, + // 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))); + } + }; + 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)))?; + + 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 { + request, + allowed, + 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, headers: &HeaderMap, body: &[u8]) -> Response { + match route.endpoint { + v2::Endpoint::Health => health(&self.state), + v2::Endpoint::Capabilities => self.capabilities().await, + v2::Endpoint::Status => self.status(route), + v2::Endpoint::Cancel => self.cancel(route), + v2::Endpoint::Management => self.management(), + 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) => self.execute(&request), + Err(error) => bad_request(&error), + }, + v2::Endpoint::ExecuteBypass => match wire::read_bypass_request(body) { + Ok(request) => self.execute_bypass(headers, &request), + Err(error) => bad_request(&error), + }, + v2::Endpoint::Validate => match wire::read_validation_request(body) { + Ok(request) => policy::validate(&request), + Err(error) => bad_request(&error), + }, + v2::Endpoint::Replace => match wire::read_replacement_request(body) { + Ok(request) => self.replace(&request).await, + Err(error) => { + self.record_rejected_replacement(); + bad_request(&error) + } + }, + } + } +} + +/// 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. + 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, + evaluated_at: v2::Timestamp, +} + +/// 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 + } + }) +} + +/// 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 +fn has_json_media_type(headers: &HeaderMap) -> bool { + headers.get(header::CONTENT_TYPE).is_some_and(|value| { + // The field value is compared as bytes: a parameter may hold bytes from 0x80 to 0xFF, which are no text + // ([RFC 9110 §5.5]), and no parameter changes the media type. + // + // [RFC 9110 §5.5]: https://www.rfc-editor.org/rfc/rfc9110#section-5.5 + let value = value.as_bytes(); + let media_type = value.split(|byte| *byte == b';').next().unwrap_or(value); + + // Space and tab are the only ASCII whitespace a header value holds. + media_type.trim_ascii().eq_ignore_ascii_case(b"application/json") + }) +} + +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"); + internal_error_response() +} + +/// The response of [`internal_error`], for a failure that its caller logs itself. +fn internal_error_response() -> Response { + error_response(v2::ErrorCode::InternalError, "the broker failed to answer the request") +} + +/// 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/operations.rs b/crates/now-package-broker/src/v2/routes/operations.rs new file mode 100644 index 000000000..36208ac55 --- /dev/null +++ b/crates/now-package-broker/src/v2/routes/operations.rs @@ -0,0 +1,201 @@ +//! 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::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. + /// + /// 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_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(), + } + } + + /// 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); + } + + // A protected uninstall starts nothing, and its `RequestId` stays unused. + if let Some(protected) = self.protected_uninstall((&package_request).into()) { + return protected; + } + + 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 registries = self.state.operations.of(&self.state); + let Some(state) = self.held_operation(route, |owner, operation_id| { + registries + .executions + .status(owner, operation_id) + .or_else(|| registries.bypasses.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 registries = self.state.operations.of(&self.state); + let Some(status) = self.held_operation(route, |owner, operation_id| { + registries + .executions + .cancel(owner, operation_id) + .or_else(|| registries.bypasses.cancel(owner, operation_id)) + }) else { + return operation_not_found(); + }; + + json(StatusCode::OK, &v2::CancelResponse { status }) + } + + /// 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()?; + + 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)?, + 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, + }, + ) +} + +// 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: 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, + }) +} + +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/policy.rs b/crates/now-package-broker/src/v2/routes/policy.rs new file mode 100644 index 000000000..0e36a3c0c --- /dev/null +++ b/crates/now-package-broker/src/v2/routes/policy.rs @@ -0,0 +1,102 @@ +//! 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 tracing::error; + +use super::{Connection, error_body, error_response, internal_error, internal_error_response, json}; +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 replacement = self + .state + .policy_store + .replace_document(&request.expected_store_token, &request.document, || { + self.begin_replacement_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) => { + // UNTESTED: A replacement the policy store fails to decide names its client and the failure in the log. + // The store fails before the attempt is recorded, so this line is the only trace of who asked, and + // nothing else logs the error. + // 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 and the error of the + // store. + error!( + user_sid = %self.client.user_sid(), + executable = %self.client.executable_path().display(), + error = format!("{error:#}"), + "Failed to decide a policy replacement" + ); + internal_error_response() + } + } + } +} + +/// 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/protection.rs b/crates/now-package-broker/src/v2/routes/protection.rs new file mode 100644 index 000000000..5f0ab59ce --- /dev/null +++ b/crates/now-package-broker/src/v2/routes/protection.rs @@ -0,0 +1,209 @@ +//! 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 { + /// Returns the response to `request` when it is a protected uninstall, and nothing when it is not one + /// ([§protected-package]). + /// + /// The broker reads the product code of the installed Devolutions Agent for a request that removes a package + /// through WinGet, and for no other: no id of another manager contains it. + /// A request for which it fails to read that product code is answered like a protected uninstall, with a message + /// of its own unless its id names the Agent without the product code. + /// + /// [§protected-package]: https://github.com/Devolutions/now-libraries/blob/master/policies/CONTRACT.wire.md#protected-package + pub(super) fn protected_uninstall(&self, request: Target<'_>) -> Option { + let Target { + removes_package, + manager, + package_id, + } = request; + + if !removes_package { + return None; + } + if manager != v2::Manager::Winget { + return names_agent(manager, package_id, None).then(protected_package); + } + + match (self.state.agent_product_code)() { + Ok(agent_product_code) => names_agent(manager, package_id, agent_product_code).then(protected_package), + Err(error) => { + warn!( + error = format!("{error:#}"), + "Failed to read the product code of the installed Devolutions Agent" + ); + if names_agent(manager, package_id, None) { + return Some(protected_package()); + } + // The broker cannot verify that the id of the request does not contain the product code. + Some(error_response( + v2::ErrorCode::ProtectedPackage, + "the broker cannot verify that the request does not uninstall Devolutions Agent", + )) + } + } + } +} + +/// Returns the response to a request that names Devolutions Agent as the package it removes. +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 from its MSI +/// package. +/// +/// [§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@5ca59890e65f:policies/CONTRACT.wire.md §protected-package + #[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@5ca59890e65f:policies/CONTRACT.wire.md §protected-package + #[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@5ca59890e65f:policies/CONTRACT.wire.md §protected-package + #[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 new file mode 100644 index 000000000..053db6872 --- /dev/null +++ b/crates/now-package-broker/src/v2/routes/tests.rs @@ -0,0 +1,4172 @@ +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 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, TestWriteFault}; +use crate::remote_grant::RemoteGrantStore; +use crate::server::{BrokerState, build_router_for_client, serve_connection, serve_unidentified_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), + agent_version: now_policy_api::v2::ServerVersion::parse("1.2.3").expect("a server version"), + operations: Default::default(), + } +} + +/// 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 [ + b"application/json".as_slice(), + b"APPLICATION/Json", + b"application/json; charset=utf-16", + b"application/json;charset=utf-8;version=1", + // A field value may hold bytes from 0x80 to 0xFF, also inside a quoted string (RFC 9110 §5.5). + b"application/json; charset=\"\xE9\"", + ] { + // The body is malformed, so the first outcome after the media type is `BadRequest`. + let mut request = request(Method::POST, EVALUATE, None, "{"); + let field_value = axum::http::HeaderValue::from_bytes(content_type).expect("a field value"); + request.headers_mut().insert("content-type", field_value); + let reply = send(&state, &client(), request).await; + + assert_eq!( + (reply.status, &reply.body["Code"]), + (400, &serde_json::json!("BadRequest")), + "{}", + content_type.escape_ascii() + ); + } +} + +// 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}" + ); + reply.assert_error(401, "Unauthenticated"); + } +} + +// 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 §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() { + 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}"); + } +} + +// `BrokerBusy`, the first outcome, is the answer to a client over a connection limit, which the tests of `pipe` cover. +// oracle: contract Devolutions/now-libraries@5ca59890e65f:policies/CONTRACT.wire.md §errors +#[tokio::test] +async fn the_outcomes_from_unknown_endpoint_to_administrator_required_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 [ + ( + 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: 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; + + assert_ne!(served.body["Code"], "UnknownEndpoint", "{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() + ), + ] + ); +} + +/// 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!( + 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@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() { + 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( + &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"); + 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, +) -> 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: contract Devolutions/now-libraries@09d6488736cf:policies/CONTRACT.policy.md §manager-vcpkg +// A Vcpkg request that has `Package.Architecture` is unreadable, whatever architecture it names. +#[tokio::test] +async fn the_capability_of_vcpkg_names_no_architecture() { + let state = Arc::new(BrokerState { + executor: Arc::new(ProbingExecutor(vec![now_policy_api::ManagerName::Vcpkg])), + ..state() + }); + + let reply = send(&state, &client(), get("/v2/capabilities")).await; + + assert_eq!(reply.status, 200, "{reply:?}"); + let managers = reply.body["Managers"].as_array().expect("Managers is a list"); + let [vcpkg] = managers.as_slice() else { + panic!("the broker found one manager: {reply:?}"); + }; + assert_eq!(vcpkg["Manager"], "Vcpkg"); + assert_eq!(strings(vcpkg, "Architectures"), [""; 0]); +} + +// 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 §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))); + } +} + +/// 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), + ), + ] { + 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); + } + } +} + +// 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@09d6488736cf:policies/CONTRACT.wire.md §package-request + let elevated_user_scope = send( + &state, + &client(), + post_value( + EVALUATE, + &package_request(serde_json::json!({ "Scope": "User", "Elevation": "Elevated" })), + ), + ) + .await; + elevated_user_scope.assert_error(400, "BadRequest"); + + // oracle: contract Devolutions/now-libraries@09d6488736cf:policies/CONTRACT.policy.md §reading + let requests_with_an_unreadable_scope = [ + ( + // CONTRACT.policy.md §managers: "the scope is `Scope`, and `User` when it is absent". + "the scope is User through the default of the manager", + serde_json::json!({ + "Manager": "Dotnet", + "Source": { "Name": "nuget.org" }, + "Package": { "Id": "dotnet-ef", "Version": "8.0.0" }, + "Elevation": "Elevated", + }), + ), + ( + "the scope is User through a custom parameter", + serde_json::json!({ + "Elevation": "Elevated", + "OptIns": { "CustomParameters": { "Values": ["--scope", "user"] } }, + }), + ), + ( + // CONTRACT.policy.md §manager-powershell: "`Uninstall-Module` takes no scope". + "the scope is unknown and the request has no Scope", + serde_json::json!({ + "Operation": "Uninstall", + "Manager": "PowerShell", + "Source": { "Name": "PSGallery" }, + "Package": { "Id": "Pester" }, + "Elevation": "Elevated", + }), + ), + ( + // CONTRACT.policy.md §manager-powershell: "every `Elevated` Uninstall under `PowerShell` is unreadable". + "the scope is unknown and the command cannot name one, whatever the Scope", + serde_json::json!({ + "Operation": "Uninstall", + "Manager": "PowerShell", + "Source": { "Name": "PSGallery" }, + "Package": { "Id": "Pester" }, + "Scope": "Machine", + "Elevation": "Elevated", + }), + ), + ( + "a custom parameter makes the scope unknown, whatever the elevation", + serde_json::json!({ "OptIns": { "CustomParameters": { "Values": ["--scope", "everyone"] } } }), + ), + ]; + for (case, members) in requests_with_an_unreadable_scope { + let reply = send(&state, &client(), post_value(EVALUATE, &package_request(members))).await; + + assert_eq!(reply.status, 200, "{case}: {reply:?}"); + assert_eq!( + reply.body["Decision"], + decision("Deny", "UnreadableRequest", &[], false), + "{case}" + ); + } + + // 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"); +} + +// 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. + 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, + /// What it was asked to run, in the order it was asked. + ran: std::sync::Mutex>, + steps: tokio::sync::Mutex>, +} + +#[async_trait] +impl CommandExecutor for ScriptedExecutor { + async fn execute( + &self, + 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 { + 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), + ran: std::sync::Mutex::new(Vec::new()), + 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 that names the Devolutions Agent found installed when its operation +// starts, or an allowed uninstall through WinGet when the product code of the installed Agent cannot be read by then +#[tokio::test] +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", + ), + ]; + + 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 +#[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); +} + +// oracle: contract Devolutions/now-libraries@5ca59890e65f:policies/CONTRACT.wire.md §protected-package +#[tokio::test] +async fn an_allowed_uninstall_through_another_manager_than_winget_runs_while_the_product_code_cannot_be_read() { + let broker = Broker::from_state(BrokerState { + agent_product_code: UNREADABLE_PRODUCT_CODE, + ..state_with_policy(ALLOW_ALL, "") + }); + + let started = broker + .start(&execution_request("request-1", npm_uninstall("left-pad"))) + .await; + + broker.step(Step::Launch(at(0))); + broker.wait_for(operation_id(&started), "Running").await; + assert_eq!(broker.runs().await, 1); +} + +/// A read of the product code of the installed Devolutions Agent that finds no Agent installed from its MSI package. +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 } }) +} + +/// The members of a package request to uninstall the package `id` of npm. +fn npm_uninstall(id: &str) -> serde_json::Value { + serde_json::json!({ + "Operation": "Uninstall", + "Manager": "Npm", + "Source": { "Name": "npm" }, + "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@5ca59890e65f: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); 13] = [ + ( + "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 WinGet while the product code cannot be read", + UNREADABLE_PRODUCT_CODE, + winget_uninstall("Git.Git"), + ), + ( + "an install of another package through WinGet with UninstallPrevious while the product code cannot be read", + UNREADABLE_PRODUCT_CODE, + with_uninstall_previous(serde_json::json!({})), + ), + ( + "an uninstall of the Chocolatey id of the Agent while the product code cannot be read", + UNREADABLE_PRODUCT_CODE, + chocolatey("Uninstall", "devo-agent"), + ), + ]; + + 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@5ca59890e65f: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); 13] = [ + ( + "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}"), + ), + ( + "an uninstall of another package through WinGet while no Agent is installed", + NO_PRODUCT_CODE, + winget_uninstall("Git.Git"), + ), + ( + "an uninstall of another package through npm while the product code cannot be read", + UNREADABLE_PRODUCT_CODE, + npm_uninstall("left-pad"), + ), + ( + "an uninstall of another package through Chocolatey while the product code cannot be read", + UNREADABLE_PRODUCT_CODE, + chocolatey("Uninstall", "git"), + ), + ]; + + 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 through WinGet 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 before_the_policy = send( + &without_policy.state, + &client(), + post_value(EXECUTE, &uninstall("Devolutions.Agent")), + ) + .await; + 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, ""); + 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. +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 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))); + 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.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. +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) { + 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 { + state.operations.give_bypass_token(state, token, request, user_sid) +} + +/// 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_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); +} + +// 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>; + +const AGENT_PRODUCT_CODE: AgentProductCode = || Ok(Some("0f2a6b3c-4d5e-4f60-8a9b-0c1d2e3f4a5b".parse()?)); + +// oracle: contract Devolutions/now-libraries@5ca59890e65f:policies/CONTRACT.wire.md §protected-package +#[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"), + "Winget", + "Git.Git", + ), + ]; + + 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@5ca59890e65f:policies/CONTRACT.wire.md §protected-package +#[tokio::test] +async fn only_an_uninstall_that_may_be_of_devolutions_agent_is_protected_package() { + // An uninstall of another package through WinGet, when the broker can tell that it is another one: with the + // product code of the installed Agent, and with no Agent installed from its MSI package. + for agent_product_code in [AGENT_PRODUCT_CODE, NO_PRODUCT_CODE] { + let broker = Broker::from_state(BrokerState { + agent_product_code, + ..state() + }); + start_bypass(&broker, TOKEN, &bypass_uninstall("Winget", "Git.Git")).await; + } + + // An uninstall through another manager, whose ids never hold the product code, even when the broker cannot read it. + let broker = Broker::from_state(BrokerState { + agent_product_code: UNREADABLE_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" }), + )), + ), + ( + // 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-powershell: "`Uninstall-Module` takes no scope", so the broker cannot make + // the command of this run as administrator machine-wide. + // oracle: contract Devolutions/now-libraries@09d6488736cf:policies/CONTRACT.policy.md §reading + "an elevated uninstall without Scope through PowerShell", + without_source(bypass_request( + "request-1", + serde_json::json!({ + "Operation": "Uninstall", + "Manager": "PowerShell", + "Package": { "Id": "Pester" }, + "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}"); + } +} + +/// The members of a request for a version of the module `Pester` from the repository `source` through `manager`. +fn powershell_module(manager: &str, operation: &str, source: &str, elevation: &str) -> serde_json::Value { + serde_json::json!({ + "Operation": operation, + "Manager": manager, + "Source": { "Name": source }, + "Package": { "Id": "Pester", "Version": "5.5.0" }, + "Elevation": elevation, + }) +} + +/// The elevated Install and Update requests that name a repository whose registration the user's own processes can +/// change: every one under `PowerShell7`, and under `PowerShell` one whose "`Source.Name` does not equal `PSGallery` +/// ignoring ASCII case". +const ELEVATED_FROM_A_REPOSITORY_OF_THE_USER: [(&str, &str, &str); 4] = [ + ("PowerShell7", "Install", "PSGallery"), + ("PowerShell7", "Update", "PSGallery"), + ("PowerShell", "Install", "Internal"), + ("PowerShell", "Update", "Internal"), +]; + +// oracle: contract Devolutions/now-libraries@1763e9655b91:policies/CONTRACT.policy.md §manager-powershell +#[tokio::test] +async fn an_elevated_powershell_install_or_update_from_a_repository_of_the_user_is_unreadable() { + let broker = Broker::with_policy(ALLOW_ALL, ""); + + for (manager, operation, source) in ELEVATED_FROM_A_REPOSITORY_OF_THE_USER { + let members = powershell_module(manager, operation, source, "Elevated"); + + let evaluated = send( + &broker.state, + &client(), + post_value(EVALUATE, &package_request(members.clone())), + ) + .await; + let executed = send( + &broker.state, + &client(), + post_value(EXECUTE, &execution_request("request-1", members)), + ) + .await; + + for reply in [evaluated, executed] { + assert_eq!(reply.status, 200, "{manager} {operation} {source}: {reply:?}"); + assert_eq!( + reply.body["Decision"], + decision("Deny", "UnreadableRequest", &[], false), + "{manager} {operation} {source}" + ); + } + } + assert_eq!(broker.runs().await, 0); + + // The same requests are readable from `PSGallery` under `PowerShell`, and from any repository when not elevated. + let readable = [ + ("PowerShell", "Install", "psgallery", "Elevated"), + ("PowerShell7", "Install", "PSGallery", "NonElevated"), + ("PowerShell", "Install", "Internal", "NonElevated"), + ]; + for (manager, operation, source, elevation) in readable { + let members = powershell_module(manager, operation, source, elevation); + + let evaluated = send( + &broker.state, + &client(), + post_value(EVALUATE, &package_request(members)), + ) + .await; + + // A request the broker reads is decided by a later check of the policy, whatever that check answers. + assert_eq!( + evaluated.status, 200, + "{manager} {operation} {source} {elevation}: {evaluated:?}" + ); + assert!(evaluated.body["Decision"]["Check"].is_string(), "{evaluated:?}"); + assert_ne!( + evaluated.body["Decision"]["Check"], "UnreadableRequest", + "{manager} {operation} {source} {elevation}" + ); + } +} + +// An unreadable bypass request is the fourth outcome of its section, and starts nothing. +// oracle: contract Devolutions/now-libraries@1763e9655b91:policies/CONTRACT.policy.md §manager-powershell +#[tokio::test] +async fn an_elevated_powershell_bypass_install_or_update_from_a_repository_of_the_user_is_bypass_request_unreadable() { + for (manager, operation, source) in ELEVATED_FROM_A_REPOSITORY_OF_THE_USER { + let broker = Broker::from_state(state()); + let request = bypass_request("request-1", powershell_module(manager, operation, source, "Elevated")); + hold(&broker.state, TOKEN, &request); + + let reply = send(&broker.state, &client(), post_bypass(&[TOKEN], &request)).await; + + assert_eq!( + reply.body["Code"], "BypassRequestUnreadable", + "{manager} {operation} {source}: {reply:?}" + ); + reply.assert_error(422, "BypassRequestUnreadable"); + assert_eq!(broker.runs().await, 0, "{manager} {operation} {source}"); + } + + // The same Install from `PSGallery` under `PowerShell` is readable, and starts its operation. + let broker = Broker::from_state(state()); + let request = bypass_request( + "request-1", + powershell_module("PowerShell", "Install", "PSGallery", "Elevated"), + ); + start_bypass(&broker, TOKEN, &request).await; +} + +// 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"); +} + +// "`OptIns` has no key other than `NoUpgrade`, and any other key is `BadRequest`", so no bypass request carries an +// install location, a command or a process to stop. +// oracle: contract Devolutions/now-libraries@09d6488736cf:policies/CONTRACT.wire.md §bypass +#[tokio::test] +async fn a_bypass_request_with_an_opt_in_other_than_no_upgrade_is_bad_request() { + let broker = Broker::from_state(state()); + // Each value is well-formed for its key (CONTRACT.wire.md §opt-ins), so only the key makes the request malformed. + let other_opt_ins = [ + ("Interactive", serde_json::json!({})), + ("SkipHashCheck", serde_json::json!({})), + ("CustomInstallLocation", serde_json::json!({ "Path": r"C:\Tools\Git" })), + ("CustomParameters", serde_json::json!({ "Values": ["--silent"] })), + ( + "InstallerArguments", + serde_json::json!({ "Arguments": "/S", "Mode": "Append" }), + ), + ("PrePostCommands", serde_json::json!({ "Pre": "whoami" })), + ("KillBeforeOperation", serde_json::json!({ "Processes": ["git.exe"] })), + ("UninstallPrevious", serde_json::json!({})), + ]; + + for (key, value) in other_opt_ins { + let request = bypass_request("request-1", serde_json::json!({ "OptIns": { key: value } })); + + let reply = send(&broker.state, &client(), post_bypass(&[TOKEN], &request)).await; + + assert_eq!(reply.body["Code"], "BadRequest", "{key}: {reply:?}"); + reply.assert_error(400, "BadRequest"); + } + + // The broker holds no token, so a well-formed request is the second outcome of the section. + let no_upgrade = bypass_request("request-1", serde_json::json!({ "OptIns": { "NoUpgrade": {} } })); + let reply = send(&broker.state, &client(), post_bypass(&[TOKEN], &no_upgrade)).await; + reply.assert_error(403, "BypassTokenRejected"); + assert_eq!(broker.runs().await, 0); +} + +// 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 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; + + 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); + // 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 +/// 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; + assert_eq!(reply.status, 200, "{case}: {reply:?}"); + 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_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" } }), + "--source", + ), + ( + "an elevated update through WinGet", + serde_json::json!({ "Operation": "Update", "Manager": "Winget", "Elevation": "Elevated" }), + "--source", + ), + ( + "an elevated install through Chocolatey", + serde_json::json!({ "Manager": "Chocolatey", "Package": { "Id": "git" }, "Elevation": "Elevated" }), + "--source", + ), + ( + "an install through PowerShell", + serde_json::json!({ "Manager": "PowerShell", "Package": { "Id": "Pester" } }), + "-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 + ); + } +} + +/// A rule that allows the requests whose scope is `Machine`, and no other rule. +const ALLOW_MACHINE_WIDE: &str = + r#"[{ "Id": "allow-machine-wide", "Decision": "Allow", "Select": { "Scopes": ["Machine"] } }]"#; + +// An elevated WinGet request without `Scope` is read with the scope `Machine`, which its command names. +// oracle: contract Devolutions/now-libraries@09d6488736cf:policies/CONTRACT.policy.md §manager-winget +#[tokio::test] +async fn an_elevated_request_without_scope_is_decided_and_run_as_a_machine_wide_one() { + let broker = Broker::with_policy(ALLOW_MACHINE_WIDE, ""); + + // The scope of the same request is unknown when it is not elevated, so the rule does not allow it. + let not_elevated = send( + &broker.state, + &client(), + post_value(EVALUATE, &package_request(serde_json::json!({}))), + ) + .await; + let started = broker + .start(&execution_request( + "request-1", + serde_json::json!({ "Elevation": "Elevated" }), + )) + .await; + broker.step(Step::Launch(at(0))); + broker.step(Step::Exit(0)); + broker.wait_for(operation_id(&started), "Completed").await; + + assert_eq!(not_elevated.body["Decision"]["Outcome"], "Deny", "{not_elevated:?}"); + assert_eq!(started.body["Decision"]["Outcome"], "Allow", "{started:?}"); + let [run] = <[ExecutionContext; 1]>::try_from(ran(&broker)) + .unwrap_or_else(|ran| panic!("the broker ran {} operations", ran.len())); + assert!( + run.command.windows(2).any(|pair| pair == ["--scope", "machine"]), + "{:?}", + run.command + ); +} + +// oracle: contract Devolutions/now-libraries@09d6488736cf:policies/CONTRACT.policy.md §manager-winget +// oracle: contract Devolutions/now-libraries@09d6488736cf:policies/CONTRACT.policy.md §manager-powershell +#[tokio::test] +async fn an_elevated_bypass_request_without_scope_runs_a_machine_wide_command() { + let winget = run_of_a_bypass_request_without_source( + "an elevated update through WinGet", + serde_json::json!({ "Operation": "Update", "Manager": "Winget", "Elevation": "Elevated" }), + ) + .await; + let powershell = run_of_a_bypass_request_without_source( + "an elevated uninstall through PowerShell7", + serde_json::json!({ + "Operation": "Uninstall", + "Manager": "PowerShell7", + "Package": { "Id": "Pester" }, + "Elevation": "Elevated", + }), + ) + .await; + + assert!( + winget.command.windows(2).any(|pair| pair == ["--scope", "machine"]), + "{:?}", + winget.command + ); + // A PowerShell manager gets its options inside one argument. + assert!( + powershell + .command + .iter() + .any(|argument| argument.contains(" -Scope AllUsers")), + "{:?}", + powershell.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!({ + "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 { + run_of_a_bypass_request_without_source(case, members).await; + } +} +// 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 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 refused = connection.execute_bypass(&headers, &request); + + reply(refused).await.assert_error(500, "InternalError"); + } + 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() + }); + // The broker reads the product code for a request that removes a package through WinGet. + let request = bypass_uninstall("Winget", "Git.Git"); + 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); +} + +// oracle: contract Devolutions/now-libraries@09d6488736cf:policies/CONTRACT.wire.md §bypass +// A token authorizes no request from 60 seconds after the Agent gave it, and an unused one starts no operation later. +#[tokio::test] +async fn a_bypass_request_whose_token_becomes_60_seconds_old_before_its_operation_starts_is_bypass_token_rejected() { + /// How long before the end of its 60 seconds the request finds the token. + const REMAINING: Duration = Duration::from_millis(300); + + thread_local! { + /// The time 60 seconds after the token of this test was given. + static SIXTY_SECONDS_AFTER: std::cell::Cell> = const { std::cell::Cell::new(None) }; + } + // The broker reads the product code once it found that the token authorizes the request, and before it starts + // the operation. + // The read returns once the 60 seconds have passed, however long the test took to get there. + let agent_product_code: AgentProductCode = || { + let sixty_seconds_after = SIXTY_SECONDS_AFTER.get().expect("the test gave the token"); + loop { + let remaining = sixty_seconds_after.saturating_duration_since(std::time::Instant::now()); + if remaining.is_zero() { + return Ok(None); + } + std::thread::sleep(remaining); + } + }; + let broker = Broker::from_state(BrokerState { + agent_product_code, + ..state() + }); + let client = client(); + // The broker reads the product code for a request that removes a package through WinGet. + let request = bypass_uninstall("Winget", "Git.Git"); + let given = std::time::Instant::now() + .checked_sub(Duration::from_secs(60) - REMAINING) + .expect("the machine started more than a minute ago"); + SIXTY_SECONDS_AFTER.set(Some(given + Duration::from_secs(60))); + let held = + broker + .state + .operations + .give_bypass_token_at(&broker.state, TOKEN, &request, client.user_sid().clone(), given); + assert!(held, "the broker holds the token"); + + // On a machine that takes longer than `REMAINING` to get from the gift of the token to the request, the broker + // finds no token at all, and the test passes without the check that precedes the start. + let reply = send(&broker.state, &client, post_bypass(&[TOKEN], &request)).await; + // The broker replays the response of an operation it holds, so it holds none when it answers this. + let again = send(&broker.state, &client, post_bypass(&[TOKEN], &request)).await; + + reply.assert_error(403, "BypassTokenRejected"); + again.assert_error(403, "BypassTokenRejected"); + 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); +} diff --git a/crates/now-package-broker/src/v2/wire/convert.rs b/crates/now-package-broker/src/v2/wire/convert.rs index 9f8a20906..302b8049b 100644 --- a/crates/now-package-broker/src/v2/wire/convert.rs +++ b/crates/now-package-broker/src/v2/wire/convert.rs @@ -81,46 +81,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]). @@ -781,53 +772,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 727a90ee5..8ff868ec7 100644 --- a/crates/now-package-broker/src/v2/wire/mod.rs +++ b/crates/now-package-broker/src/v2/wire/mod.rs @@ -9,7 +9,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, 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); }