diff --git a/crates/openlogi-agent/src/autostart.rs b/crates/openlogi-agent/src/autostart.rs index 40af4d92d1..37a7865226 100644 --- a/crates/openlogi-agent/src/autostart.rs +++ b/crates/openlogi-agent/src/autostart.rs @@ -12,7 +12,9 @@ //! `config.toml` therefore takes effect the next time the GUI runs. //! - **Linux** ([`linux`]): a systemd **user** unit, written/removed and //! `systemctl --user` enabled/disabled. `Restart=on-failure` mirrors the -//! macOS service's `KeepAlive = {SuccessfulExit: false}` semantics. +//! macOS service's `KeepAlive = {SuccessfulExit: false}` semantics. Inside a +//! Flatpak, which can reach neither, the XDG Background portal's `autostart` +//! request instead — login launch only, as on Windows. //! - **Windows** ([`windows`]): an `HKCU\…\Run` registry value — login launch //! only, no crash respawn. //! diff --git a/crates/openlogi-agent/src/autostart/linux.rs b/crates/openlogi-agent/src/autostart/linux.rs index c5cfd103c8..8b5c45b322 100644 --- a/crates/openlogi-agent/src/autostart/linux.rs +++ b/crates/openlogi-agent/src/autostart/linux.rs @@ -1,5 +1,9 @@ //! Linux systemd user-unit ownership and autostart reconciliation. //! +//! Inside a Flatpak none of this applies: the sandbox has no `systemctl`, and +//! the host's systemd never reads the sandbox's `$XDG_DATA_HOME`. [`portal`] +//! takes over there, sharing only the enablement claim described below. +//! //! When a packaged unit already launches this exact binary — installed by a //! distribution package, `install.sh`, or an administrator — it is simply //! enabled. Generating a second copy would duplicate its directives one tier @@ -36,13 +40,37 @@ use std::path::{Path, PathBuf}; use tracing::{debug, info, warn}; +mod portal; + /// Reconcile the agent's autostart state with `enabled`. /// /// Idempotent; failures are logged, not propagated — startup must not abort /// because an autostart directory is read-only or systemd is unavailable. pub(super) fn reconcile(enabled: bool) { - if let Err(e) = apply(enabled) { - warn!(error = %e, enabled, "agent systemd unit reconcile failed"); + reconcile_in( + openlogi_core::sandbox::is_flatpak(), + enabled, + portal::reconcile, + |enabled| { + if let Err(e) = apply(enabled) { + warn!(error = %e, enabled, "agent systemd unit reconcile failed"); + } + }, + ); +} + +/// [`reconcile`] over an injectable sandbox answer and the two routes, so the +/// choice between them can be tested without a sandbox, a bus, or systemd. +fn reconcile_in( + in_flatpak: bool, + enabled: bool, + portal: impl FnOnce(bool), + systemd: impl FnOnce(bool), +) { + if in_flatpak { + portal(enabled); + } else { + systemd(enabled); } } @@ -220,6 +248,16 @@ fn enablement_marker_path() -> io::Result { } /// Enable the unit and record that this app is the one that did. +fn enable_unit() { + let Ok(marker) = enablement_marker_path() else { + return; + }; + claim_enablement_at(&marker, || run_systemctl(&["enable", UNIT_NAME])); +} + +/// Run `enable`, the step that turns autostart on, under this app's claim on +/// the enablement at `marker`. Shared with [`portal`], so both routes keep +/// the same ownership rules. /// /// The claim is recorded *before* enabling. An enablement this app cannot /// record is one a later reconcile could never withdraw, leaving autostart @@ -232,21 +270,12 @@ fn enablement_marker_path() -> io::Result { /// Claiming an enablement the user made by hand is deliberate: reaching the /// toggle at all is an explicit request for this app to manage autostart, and /// the setting has to mean what it says when it is switched back off. -fn enable_unit() { - let Ok(marker) = enablement_marker_path() else { - return; - }; - enable_unit_with(&marker, || run_systemctl(&["enable", UNIT_NAME])); -} - -/// The ordering and rollback rules of [`enable_unit`], over an injectable -/// marker path and enable step so the state transitions can be tested. /// /// A claim that already existed is left alone when `enable` fails: the failure /// may be transient (no session bus yet at login), and dropping a claim made by /// an earlier reconcile would leave an enablement this app owns with nothing /// able to withdraw it. Only a claim *this* call created is rolled back. -fn enable_unit_with(marker: &Path, enable: impl FnOnce() -> bool) { +fn claim_enablement_at(marker: &Path, enable: impl FnOnce() -> bool) { let claimed_now = match record_enablement_at(marker) { Ok(claimed_now) => claimed_now, Err(e) => { @@ -279,7 +308,7 @@ fn clear_marker_at(marker: &Path) { /// Created exclusively, so the answer is decided by the filesystem and not by /// a check made a moment earlier: of any number of callers racing for a /// missing marker, exactly one is told it made the claim. The rollback in -/// [`enable_unit_with`] trusts that answer, and a second "yes" there would let +/// [`claim_enablement_at`] trusts that answer, and a second "yes" there would let /// one caller's failure withdraw a claim another caller still holds. fn record_enablement_at(path: &Path) -> io::Result { if let Some(parent) = path.parent() { @@ -296,26 +325,53 @@ fn record_enablement_at(path: &Path) -> io::Result { } } -/// Withdraw the enablement only when this app recorded making it. -/// -/// A missing marker means the enablement came from somewhere else — the -/// install instructions, another tool, the user — and is not ours to remove. -/// Losing the marker therefore fails safe: autostart keeps working, and the -/// user can still turn it off the way they turned it on. +/// Disable the unit, if this app is the one that enabled it. fn disable_unit_if_ours() { let Ok(marker) = enablement_marker_path() else { return; }; + withdraw_enablement_at(&marker, || { + if run_systemctl(&["disable", UNIT_NAME]) { + Withdrawal::Done + } else { + Withdrawal::Failed + } + }); +} + +/// What a disable step did with the enablement it was asked to withdraw. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Withdrawal { + /// Autostart is off: the claim is dropped. + Done, + /// Autostart may still be on: the claim stays, so the next reconcile + /// retries rather than stranding an enablement this app is still + /// responsible for. + Failed, + /// Asked for, and not yet confirmed: the claim stays, and whatever + /// confirms the removal drops it. + Pending, +} + +/// Run `disable`, the step that turns autostart off, only when this app +/// recorded making the enablement at `marker`. Shared with [`portal`], so both +/// routes keep the same ownership rules. +/// +/// A missing marker means the enablement came from somewhere else — the +/// install instructions, another tool, the user — and is not ours to remove. +/// Losing the marker therefore fails safe: autostart keeps working, and the +/// user can still turn it off the way they turned it on. For the same reason +/// the marker goes only once autostart is known to be off, never when the +/// removal has merely been asked for. +fn withdraw_enablement_at(marker: &Path, disable: impl FnOnce() -> Withdrawal) { if !marker.exists() { debug!("autostart enablement was not made by OpenLogi; leaving it alone"); return; } - if !run_systemctl(&["disable", UNIT_NAME]) { - // Keep the marker so the next reconcile retries rather than stranding - // an enablement this app is still responsible for. - return; + match disable() { + Withdrawal::Done => clear_marker_at(marker), + Withdrawal::Failed | Withdrawal::Pending => {} } - clear_marker_at(&marker); } /// Path to the generated unit: diff --git a/crates/openlogi-agent/src/autostart/linux/portal.rs b/crates/openlogi-agent/src/autostart/linux/portal.rs new file mode 100644 index 0000000000..e630575360 --- /dev/null +++ b/crates/openlogi-agent/src/autostart/linux/portal.rs @@ -0,0 +1,546 @@ +//! Autostart from inside a Flatpak, through the XDG Background portal. +//! +//! The systemd arm cannot work in the sandbox: there is no `systemctl` to +//! enable a unit with, and the unit it writes lands in the sandbox's +//! `$XDG_DATA_HOME` (`~/.var/app//data`), which the host's systemd never +//! reads. The portal is the sandbox's own route instead. `RequestBackground` +//! with `autostart` set has the host write `~/.config/autostart/.desktop`, +//! which launches `commandline` inside this app's sandbox at login; with +//! `autostart` cleared, it removes that file again. It is login launch only, +//! with no crash respawn — the same as on Windows. +//! +//! Enablement goes through the claim the systemd arm keeps, so a disabled +//! setting reaches the portal only to withdraw an autostart this app asked +//! for. That keeps more than tidiness: a desktop may ask the user whether the +//! app may run in the background the first time it requests anything, and a +//! user who never turned the setting on must not be asked. +//! +//! Only the request is awaited, not the user's answer. Reconcile runs at agent +//! startup and inside the `reload_config` RPC, and neither may wait on a +//! person. The answer arrives on a helper thread, and only the answer settles +//! the request: a withdrawn claim is dropped once the portal confirms the +//! removal, so a removal that is refused or never answered is asked for again. +//! A refusal is the portal's to remember, so asking again later does not ask +//! the user again. + +use std::collections::HashMap; +use std::path::{Path, PathBuf}; +use std::sync::{Mutex, MutexGuard, PoisonError}; +use std::thread; + +use tracing::{debug, info, warn}; +use zbus::blocking::Connection; +use zbus::proxy; +use zbus::zvariant::{ObjectPath, OwnedObjectPath, OwnedValue, Value}; + +use super::Withdrawal; + +/// Shown by desktops that ask the user before granting the request. +const REASON: &str = + "Start the OpenLogi agent at login so your device settings apply without opening the app."; + +#[proxy( + interface = "org.freedesktop.portal.Background", + default_service = "org.freedesktop.portal.Desktop", + default_path = "/org/freedesktop/portal/desktop", + gen_blocking = true +)] +trait Background { + fn request_background( + &self, + parent_window: &str, + options: HashMap<&str, Value<'_>>, + ) -> zbus::Result; +} + +#[proxy( + interface = "org.freedesktop.portal.Request", + default_service = "org.freedesktop.portal.Desktop", + gen_blocking = true +)] +trait Request { + #[zbus(signal)] + fn response(&self, response: u32, results: HashMap) -> zbus::Result<()>; +} + +/// This process's portal requests. Held across a whole reconcile — claim, +/// request, and marker — and by the response thread while it settles one, so +/// an answer cannot land between a reconcile's claim and its request. +static REQUESTS: Mutex = Mutex::new(Requests::new()); + +fn requests() -> MutexGuard<'static, Requests> { + REQUESTS.lock().unwrap_or_else(PoisonError::into_inner) +} + +/// Reconcile the portal autostart with `enabled`. +pub(super) fn reconcile(enabled: bool) { + let Ok(marker) = super::enablement_marker_path() else { + return; + }; + let exe = if enabled { + match std::env::current_exe() { + Ok(exe) => Some(exe), + Err(error) => { + warn!(%error, "cannot resolve the agent executable; leaving autostart unchanged"); + return; + } + } + } else { + None + }; + reconcile_with(&mut requests(), &marker, exe.as_deref(), |autostart, id| { + request(autostart, id, &marker) + }); +} + +/// [`reconcile`] over an injectable claim marker and request sender, so the +/// ownership rules can be tested without a session bus. +/// +/// `send` asks the portal for `autostart` as request `id` and reports whether +/// the portal accepted it; the answer is for [`settle`]. +fn reconcile_with( + requests: &mut Requests, + marker: &Path, + autostart: Option<&Path>, + send: impl FnOnce(Option<&Path>, RequestId) -> bool, +) { + let wanted = autostart.is_some(); + if wanted { + super::claim_enablement_at(marker, || { + requests.ask(wanted, |id| send(autostart, id)) != Asked::Failed + }); + } else { + super::withdraw_enablement_at(marker, || { + match requests.ask(wanted, |id| send(autostart, id)) { + Asked::Sent | Asked::InFlight => Withdrawal::Pending, + Asked::Confirmed => Withdrawal::Done, + Asked::Failed => Withdrawal::Failed, + } + }); + } +} + +/// Apply the portal's `answer` to request `id`, and drop the withdrawn claim +/// at `marker` once the removal it asked for is confirmed. +fn settle(requests: &mut Requests, id: RequestId, answer: Answer, marker: &Path) { + if requests.answer(id, answer) { + super::clear_marker_at(marker); + } +} + +/// A request's identity within this process. It also names the request's +/// `handle_token`, which the portal needs unique per connection. +type RequestId = u64; + +/// What [`Requests::ask`] did. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Asked { + /// A new request went out. + Sent, + /// A request for the same state is still waiting for its answer. + InFlight, + /// The portal already confirmed the same state to this process. + Confirmed, + /// The request could not be sent. + Failed, +} + +/// How the portal answered a request. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Answer { + /// Completed, with a result that does not contradict the request. + Granted, + /// Declined, failed, contradicted, or never answered. + Refused, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum State { + /// Nothing asked yet, or the last request was refused: the next reconcile + /// asks again. + Idle, + /// Request `id` asked for `wanted` and has not been answered. + Pending { id: RequestId, wanted: bool }, + /// The portal confirmed `enabled`. + Confirmed { enabled: bool }, +} + +/// The portal requests of this process: the one owner of what was last asked +/// and what the portal has confirmed, and the only place either changes. +#[derive(Debug)] +struct Requests { + next: RequestId, + state: State, +} + +impl Requests { + const fn new() -> Self { + Self { + next: 0, + state: State::Idle, + } + } + + /// Ask for `wanted` through `send`, which gets the new request's id — + /// unless that state is already pending or confirmed. + /// + /// Every settings save reloads the config and reconciles again. A pending + /// request may still have a dialog in front of the user, and repeating it + /// would stack a second one behind it. A new process asks again, which is + /// what restores an autostart file the user deleted by hand. + /// + /// A request that cannot be sent changes nothing: one still pending keeps + /// its claim on the answer. + fn ask(&mut self, wanted: bool, send: impl FnOnce(RequestId) -> bool) -> Asked { + match self.state { + State::Pending { + wanted: pending, .. + } if pending == wanted => return Asked::InFlight, + State::Confirmed { enabled } if enabled == wanted => return Asked::Confirmed, + _ => {} + } + let id = self.next; + self.next += 1; + if !send(id) { + return Asked::Failed; + } + self.state = State::Pending { id, wanted }; + Asked::Sent + } + + /// Settle request `id` with `answer`, reporting whether a withdrawn claim + /// may now be dropped: only when `id` is the latest request, it asked to + /// stop, and the portal confirmed it. + /// + /// The answer to any earlier request is stale. A later request has + /// replaced it, and the stale answer must neither settle that one nor + /// drop the claim it relies on. + #[must_use] + fn answer(&mut self, id: RequestId, answer: Answer) -> bool { + match self.state { + State::Pending { + id: pending, + wanted, + } if pending == id => match answer { + Answer::Granted => { + self.state = State::Confirmed { enabled: wanted }; + !wanted + } + Answer::Refused => { + self.state = State::Idle; + false + } + }, + _ => { + debug!( + id, + "ignoring the answer to a superseded Background portal request" + ); + false + } + } + } +} + +/// Ask the portal to launch `autostart` at login, or with `None` to stop, as +/// request `id`. +/// +/// `true` once the portal has accepted the request; its answer is settled from +/// a helper thread when the portal sends it. +fn request(autostart: Option<&Path>, id: RequestId, marker: &Path) -> bool { + match send(autostart, id, marker.to_path_buf()) { + Ok(()) => true, + Err(error) => { + warn!(%error, autostart = autostart.is_some(), "Background portal request failed"); + false + } + } +} + +fn send(autostart: Option<&Path>, id: RequestId, marker: PathBuf) -> zbus::Result<()> { + let connection = Connection::session()?; + let token = handle_token(id); + let handle = request_path(&connection, &token)?; + // Subscribe before asking, or a portal that answers at once (no dialog) + // could send the response before anything is listening for it. + let mut responses = RequestProxyBlocking::builder(&connection) + .path(handle)? + .build()? + .receive_response()?; + + let mut options = HashMap::from([ + ("handle_token", Value::from(token.as_str())), + ("reason", Value::from(REASON)), + ("autostart", Value::from(autostart.is_some())), + ]); + if let Some(exe) = autostart { + options.insert( + "commandline", + Value::from(vec![exe.to_string_lossy().into_owned()]), + ); + } + BackgroundProxyBlocking::new(&connection)?.request_background("", options)?; + debug!( + id, + autostart = autostart.is_some(), + "Background portal request sent" + ); + + // The portal cancels a request whose sender leaves the bus, so the + // connection stays open, held by the iterator, until the answer arrives. + let wanted = autostart.is_some(); + let spawned = thread::Builder::new() + .name("openlogi-autostart-portal".into()) + .spawn(move || { + let answer = match responses.next() { + None => { + warn!( + requested = wanted, + "Background portal response stream ended without an answer" + ); + Answer::Refused + } + Some(signal) => match signal.args() { + Ok(args) => answer_of(wanted, *args.response(), args.results()), + Err(error) => { + warn!(%error, "unreadable Background portal response"); + Answer::Refused + } + }, + }; + settle(&mut requests(), id, answer, &marker); + }); + if let Err(error) = spawned { + // The request is out already, and nothing will settle it: it stays + // pending for the rest of this process. A withdrawn claim is kept, + // and the next process asks again. + warn!(%error, "could not wait for the Background portal response"); + } + Ok(()) +} + +/// A token unique within this connection, as the portal's `handle_token` +/// requires: object-path-element characters only. +fn handle_token(id: RequestId) -> String { + format!("openlogi_autostart_{id}") +} + +/// The object path the portal will give the request with `token`, known in +/// advance so the response can be subscribed to before the call is made. +fn request_path(connection: &Connection, token: &str) -> zbus::Result> { + let unique = connection + .unique_name() + .ok_or_else(|| zbus::Error::Failure("session bus connection has no unique name".into()))?; + let sender = sender_path_element(unique.as_str()); + Ok(ObjectPath::try_from(format!( + "/org/freedesktop/portal/desktop/request/{sender}/{token}" + ))?) +} + +/// A unique bus name as the portal spells it in a request path: `:1.42` +/// becomes `1_42`. +fn sender_path_element(unique: &str) -> String { + unique.trim_start_matches(':').replace('.', "_") +} + +/// Log the portal's response to a request for `wanted`, and classify it. +/// +/// Granted only for a completed request whose `autostart` result does not +/// contradict what was asked. A portal that leaves the result out is taken at +/// its word. +fn answer_of(wanted: bool, response: u32, results: &HashMap) -> Answer { + let flag = |key: &str| { + results + .get(key) + .and_then(|value| bool::try_from(value).ok()) + }; + let autostart = flag("autostart"); + match response { + 0 => info!( + requested = wanted, + autostart = ?autostart, + background = ?flag("background"), + "Background portal answered", + ), + 1 => warn!( + requested = wanted, + "the user declined the Background portal request" + ), + _ => warn!( + requested = wanted, + response, "the Background portal request did not complete" + ), + } + if response == 0 && autostart != Some(!wanted) { + Answer::Granted + } else { + Answer::Refused + } +} + +#[cfg(test)] +mod tests { + use std::cell::RefCell; + use std::path::{Path, PathBuf}; + + use super::super::tests::TempDir; + use super::{ + Answer, OwnedValue, RequestId, Requests, answer_of, reconcile_with, sender_path_element, + settle, + }; + + #[test] + fn sender_path_element_matches_the_portal_spelling() { + assert_eq!(sender_path_element(":1.42"), "1_42"); + assert_eq!(sender_path_element(":1.1024"), "1_1024"); + } + + /// Requests the fake portal accepted, as `(autostart, id)`. + type Sent = RefCell, RequestId)>>; + + fn reconcile(requests: &mut Requests, marker: &Path, enabled: bool, sent: &Sent) { + let exe = Path::new("/app/bin/openlogi-agent"); + reconcile_with(requests, marker, enabled.then_some(exe), |autostart, id| { + sent.borrow_mut() + .push((autostart.map(Path::to_path_buf), id)); + true + }); + } + + fn last_id(sent: &Sent) -> RequestId { + sent.borrow().last().expect("a request was sent").1 + } + + /// A user who never turned the setting on must never meet the portal: a + /// desktop may ask them about background permission the first time this + /// app requests anything. + #[test] + fn disabling_without_a_claim_sends_nothing() { + let dir = TempDir::new("portal-unclaimed"); + let marker = dir.path("autostart.enabled"); + let sent = Sent::default(); + + reconcile(&mut Requests::new(), &marker, false, &sent); + + assert!(sent.borrow().is_empty(), "no claim, so nothing to withdraw"); + assert!(!marker.exists()); + } + + #[test] + fn enabling_claims_and_asks_for_the_agent_at_login() { + let dir = TempDir::new("portal-enable"); + let marker = dir.path("autostart.enabled"); + let sent = Sent::default(); + + reconcile(&mut Requests::new(), &marker, true, &sent); + + assert!(marker.exists(), "the enablement is claimed before asking"); + let sent = sent.borrow(); + assert_eq!(sent.len(), 1); + assert_eq!( + sent[0].0.as_deref(), + Some(Path::new("/app/bin/openlogi-agent")), + "the request launches the agent" + ); + } + + /// The claim must outlive the request to remove autostart: until the + /// portal confirms, autostart may still be on, and only the claim lets a + /// later reconcile withdraw it. + #[test] + fn a_withdrawn_claim_is_dropped_only_once_the_portal_confirms() { + let dir = TempDir::new("portal-confirm"); + let marker = dir.path("autostart.enabled"); + let mut requests = Requests::new(); + let sent = Sent::default(); + reconcile(&mut requests, &marker, true, &sent); + settle(&mut requests, last_id(&sent), Answer::Granted, &marker); + + reconcile(&mut requests, &marker, false, &sent); + assert_eq!(sent.borrow().last().expect("removal sent").0, None); + assert!(marker.exists(), "an unanswered removal keeps the claim"); + + settle(&mut requests, last_id(&sent), Answer::Granted, &marker); + assert!(!marker.exists(), "a confirmed removal drops the claim"); + } + + /// A removal the portal refuses, or never answers, leaves autostart on; + /// the claim stays and the next reconcile asks again. + #[test] + fn a_refused_removal_is_asked_for_again() { + let dir = TempDir::new("portal-refused"); + let marker = dir.path("autostart.enabled"); + std::fs::write(&marker, b"").expect("claim from an earlier run"); + let mut requests = Requests::new(); + let sent = Sent::default(); + + reconcile(&mut requests, &marker, false, &sent); + settle(&mut requests, last_id(&sent), Answer::Refused, &marker); + assert!(marker.exists(), "a refused removal keeps the claim"); + + reconcile(&mut requests, &marker, false, &sent); + assert_eq!(sent.borrow().len(), 2, "the removal is asked for again"); + } + + /// Repeated settings saves must not stack dialogs: while a request for + /// the same state is pending, nothing more is sent. + #[test] + fn a_pending_request_is_not_repeated() { + let dir = TempDir::new("portal-pending"); + let marker = dir.path("autostart.enabled"); + let mut requests = Requests::new(); + let sent = Sent::default(); + + reconcile(&mut requests, &marker, true, &sent); + reconcile(&mut requests, &marker, true, &sent); + assert_eq!(sent.borrow().len(), 1); + + settle(&mut requests, last_id(&sent), Answer::Granted, &marker); + reconcile(&mut requests, &marker, true, &sent); + assert_eq!( + sent.borrow().len(), + 1, + "a confirmed state is not asked again" + ); + } + + /// Off, then on again before the removal is answered: the removal's + /// answer is stale and must not drop the claim the new enablement holds. + #[test] + fn a_stale_removal_answer_keeps_the_newer_claim() { + let dir = TempDir::new("portal-stale"); + let marker = dir.path("autostart.enabled"); + std::fs::write(&marker, b"").expect("claim from an earlier run"); + let mut requests = Requests::new(); + let sent = Sent::default(); + + reconcile(&mut requests, &marker, false, &sent); + let removal = last_id(&sent); + reconcile(&mut requests, &marker, true, &sent); + let enable = last_id(&sent); + + settle(&mut requests, removal, Answer::Granted, &marker); + assert!(marker.exists(), "a stale answer keeps the newer claim"); + + settle(&mut requests, enable, Answer::Granted, &marker); + reconcile(&mut requests, &marker, true, &sent); + assert_eq!(sent.borrow().len(), 2, "the newer request still settled"); + } + + #[test] + fn only_a_completed_uncontradicted_response_is_granted() { + let results = |autostart: Option| { + autostart + .map(|value| ("autostart".to_owned(), OwnedValue::from(value))) + .into_iter() + .collect() + }; + + assert_eq!(answer_of(false, 0, &results(Some(false))), Answer::Granted); + assert_eq!(answer_of(true, 0, &results(Some(true))), Answer::Granted); + assert_eq!(answer_of(false, 0, &results(None)), Answer::Granted); + assert_eq!(answer_of(false, 0, &results(Some(true))), Answer::Refused); + assert_eq!(answer_of(true, 1, &results(Some(true))), Answer::Refused); + assert_eq!(answer_of(false, 2, &results(None)), Answer::Refused); + } +} diff --git a/crates/openlogi-agent/src/autostart/linux/tests.rs b/crates/openlogi-agent/src/autostart/linux/tests.rs index 709be6535c..e9c298b4af 100644 --- a/crates/openlogi-agent/src/autostart/linux/tests.rs +++ b/crates/openlogi-agent/src/autostart/linux/tests.rs @@ -279,10 +279,10 @@ fn the_enablement_marker_sits_outside_the_unit_directories() { /// Scratch directory for tests that need real files. Removed on drop so a /// failing assertion cannot leave state behind for the next run. -struct TempDir(PathBuf); +pub(super) struct TempDir(PathBuf); impl TempDir { - fn new(tag: &str) -> Self { + pub(super) fn new(tag: &str) -> Self { let dir = std::env::temp_dir().join(format!( "openlogi-launch-agent-{tag}-{}-{:?}", std::process::id(), @@ -293,7 +293,7 @@ impl TempDir { Self(dir) } - fn path(&self, name: &str) -> PathBuf { + pub(super) fn path(&self, name: &str) -> PathBuf { self.0.join(name) } } @@ -314,7 +314,7 @@ fn a_held_claim_survives_a_failed_re_enable() { let marker = dir.path("autostart.enabled"); std::fs::write(&marker, b"").expect("pre-existing claim"); - enable_unit_with(&marker, || false); + claim_enablement_at(&marker, || false); assert!( marker.exists(), @@ -329,7 +329,7 @@ fn a_claim_made_now_is_rolled_back_when_enable_fails() { let dir = TempDir::new("fresh-claim"); let marker = dir.path("autostart.enabled"); - enable_unit_with(&marker, || false); + claim_enablement_at(&marker, || false); assert!( !marker.exists(), @@ -342,14 +342,67 @@ fn a_claim_is_kept_when_enable_succeeds() { let dir = TempDir::new("ok-claim"); let marker = dir.path("autostart.enabled"); - enable_unit_with(&marker, || true); + claim_enablement_at(&marker, || true); assert!(marker.exists(), "a successful enable is recorded"); // A second reconcile finds the claim already held and keeps it. - enable_unit_with(&marker, || true); + claim_enablement_at(&marker, || true); assert!(marker.exists()); } +/// Inside a Flatpak the systemd route cannot work — no `systemctl`, and a +/// unit written to the sandbox's data dir the host never reads — so the +/// setting must reach the portal, and only the portal. +#[test] +fn a_flatpak_reconciles_through_the_portal_and_not_systemd() { + for in_flatpak in [true, false] { + for enabled in [true, false] { + let mut portal = None; + let mut systemd = None; + reconcile_in( + in_flatpak, + enabled, + |enabled| portal = Some(enabled), + |enabled| systemd = Some(enabled), + ); + let (taken, skipped) = if in_flatpak { + (portal, systemd) + } else { + (systemd, portal) + }; + assert_eq!(taken, Some(enabled), "in_flatpak={in_flatpak}"); + assert_eq!(skipped, None, "in_flatpak={in_flatpak}"); + } + } +} + +#[test] +fn withdrawing_without_a_claim_runs_nothing() { + let dir = TempDir::new("withdraw-unclaimed"); + let marker = dir.path("autostart.enabled"); + + withdraw_enablement_at(&marker, || panic!("not ours to disable")); +} + +/// The claim goes only once autostart is known to be off. A failed disable, +/// or one still waiting for confirmation, leaves autostart possibly on, and +/// dropping the claim then would leave nothing able to turn it off. +#[test] +fn a_claim_is_dropped_only_by_a_completed_withdrawal() { + let dir = TempDir::new("withdraw-claimed"); + let marker = dir.path("autostart.enabled"); + std::fs::write(&marker, b"").expect("claim"); + + withdraw_enablement_at(&marker, || Withdrawal::Failed); + assert!(marker.exists(), "a failed disable keeps the claim"); + + withdraw_enablement_at(&marker, || Withdrawal::Pending); + assert!(marker.exists(), "an unconfirmed disable keeps the claim"); + + withdraw_enablement_at(&marker, || Withdrawal::Done); + assert!(!marker.exists(), "a completed disable drops the claim"); +} + #[test] fn recording_reports_whether_the_claim_is_new() { let dir = TempDir::new("record"); diff --git a/crates/openlogi-core/.ast-grep/rules/core-flatpak-sandbox-owner.yml b/crates/openlogi-core/.ast-grep/rules/core-flatpak-sandbox-owner.yml new file mode 100644 index 0000000000..5389669a0c --- /dev/null +++ b/crates/openlogi-core/.ast-grep/rules/core-flatpak-sandbox-owner.yml @@ -0,0 +1,15 @@ +# Owner: openlogi_core::sandbox — whether this process runs inside a Flatpak. +id: core-flatpak-sandbox-owner +language: rust +severity: error +message: Whether this process runs inside a Flatpak is openlogi_core::sandbox::is_flatpak's to answer; call it instead of probing /.flatpak-info here. +note: | + The udev remedy and the agent's autostart both branch on the sandbox. See + "Single source of truth" in AGENTS.md. +files: + - crates/**/*.rs + - xtask/**/*.rs +ignores: + - crates/openlogi-core/** +rule: + pattern: '"/.flatpak-info"' diff --git a/crates/openlogi-core/src/lib.rs b/crates/openlogi-core/src/lib.rs index 59db54c102..1e4ee51df4 100644 --- a/crates/openlogi-core/src/lib.rs +++ b/crates/openlogi-core/src/lib.rs @@ -5,12 +5,13 @@ //! `hidpp`, `async-hid`, or any platform-specific event/window API; those live //! in sibling crates. //! -//! The exceptions are feature-gated: reading and writing that config file -//! (`fs`) and locale negotiation (`locale`), which reads the host's language -//! preference, both on by default; and, off by default, the dedicated tokio -//! worker thread the host crates run async work on (`worker`) and the `tracing` -//! filter every process installs (`logging`). Without them this crate touches -//! no host at all, which is what the `wasm (portable crates)` CI job checks. +//! The exceptions are feature-gated: reading and writing that config file and +//! probing the sandbox this process runs in (`fs`), and locale negotiation +//! (`locale`), which reads the host's language preference, both on by default; +//! and, off by default, the dedicated tokio worker thread the host crates run +//! async work on (`worker`) and the `tracing` filter every process installs +//! (`logging`). Without them this crate touches no host at all, which is what +//! the `wasm (portable crates)` CI job checks. #![deny(missing_docs)] @@ -32,6 +33,8 @@ pub mod locale; pub mod logging; #[cfg(feature = "fs")] pub mod paths; +#[cfg(feature = "fs")] +pub mod sandbox; pub mod scroll; #[cfg(feature = "fs")] pub mod single_instance; diff --git a/crates/openlogi-core/src/sandbox.rs b/crates/openlogi-core/src/sandbox.rs new file mode 100644 index 0000000000..8207ff3d09 --- /dev/null +++ b/crates/openlogi-core/src/sandbox.rs @@ -0,0 +1,18 @@ +//! Whether this process runs inside an application sandbox. +//! +//! Several Linux integrations take a different route from inside a Flatpak: +//! the sandbox has no host `/etc`, no `pkexec`, no `systemctl`, and its +//! `$XDG_*_HOME` point into `~/.var/app//`, which the host never reads. +//! The check is answered here once so every such integration asks the same +//! question the same way. + +use std::path::Path; + +/// Whether this process runs inside a Flatpak sandbox. +/// +/// `flatpak run` mounts `/.flatpak-info` into every sandbox it creates, and +/// nothing else does, which makes it the documented test. +#[must_use] +pub fn is_flatpak() -> bool { + Path::new("/.flatpak-info").exists() +} diff --git a/crates/openlogi-permissions/src/udev.rs b/crates/openlogi-permissions/src/udev.rs index 46b2d1c595..d7b9c85361 100644 --- a/crates/openlogi-permissions/src/udev.rs +++ b/crates/openlogi-permissions/src/udev.rs @@ -98,7 +98,7 @@ impl fmt::Display for RulesManager { /// [`install_rules`] may write to. #[must_use] pub fn rules_manager() -> Option { - if Path::new("/.flatpak-info").exists() { + if openlogi_core::sandbox::is_flatpak() { Some(RulesManager::Flatpak) } else if Path::new("/etc/NIXOS").exists() { Some(RulesManager::NixOs) diff --git a/docs/INSTALL-linux.md b/docs/INSTALL-linux.md index e1d0b21839..b5dee22174 100644 --- a/docs/INSTALL-linux.md +++ b/docs/INSTALL-linux.md @@ -191,7 +191,9 @@ flatpak kill org.openlogi.OpenLogi ``` Then launch it again. There is no user service to enable — unlike the packages, -the application launches its own agent. +the application launches its own agent. **Settings → General → Launch at +login** starts that agent at login through the desktop's Background portal; see +[Autostart](#autostart-launch-at-login). ## Build from source @@ -326,6 +328,13 @@ OpenLogi never overwrites or deletes a unit it did not generate, at either location, and it only turns off an autostart it turned on. Enabling the service yourself with the command above keeps working regardless of the GUI toggle. +The Flatpak has no systemd unit. The toggle asks the desktop's Background +portal instead, which writes `~/.config/autostart/org.openlogi.OpenLogi.desktop` +to start the agent inside the sandbox at login, and removes it when the toggle +is turned off. Some desktops ask once whether OpenLogi may run in the +background; if that was declined, allow it again in the desktop's app +permissions (GNOME: Settings → Apps → OpenLogi). + ## Verify the installation ```sh