Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions desktop/ox-host-web/src/push.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,13 @@ impl Preferences {
pub(crate) fn fcm_session_alerts(&self) -> bool {
self.enabled && self.fcm_session_alerts
}

/// The stored per-phone opt-in itself, without the master switch. The
/// dedicated setting reports what it saved, not whether the master switch
/// currently silences it.
pub(crate) fn stored_fcm_session_alerts(&self) -> bool {
self.fcm_session_alerts
}
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
Expand Down
11 changes: 11 additions & 0 deletions desktop/ox-host-web/src/push_relay.rs
Original file line number Diff line number Diff line change
Expand Up @@ -945,6 +945,17 @@ impl Client {
self.enqueue(body).await
}

/// Whether this relay advertises the exact typed session-alert capability
/// the send path requires. This is the same request, bearer credential,
/// timeout and parser as [`Self::queue_session`], so a settings surface
/// that reveals the opt-in cannot promise more than an actual send checks.
/// A stateless worker has no capability endpoint and answers `false`
/// without a request.
#[cfg(any(test, feature = "server"))]
pub(crate) async fn supports_session_alerts(&self) -> bool {
!self.is_stateless() && self.require_session_alerts().await.is_ok()
}

async fn enqueue(&self, body: Vec<u8>) -> Result<QueueStatus, Error> {
match self
.exchange(
Expand Down
35 changes: 35 additions & 0 deletions desktop/ox-host-web/src/push_relay/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -336,6 +336,41 @@ impl Service {
.flatten()
}

/// Whether this phone could turn on typed session alerts right now: a
/// confirmed, current FCM enrollment on the configured relay, and that
/// credentialed relay's exact session-alert capability. The enrollment
/// and configuration are read fresh for the question; a stateless worker
/// is refused before any request. A failure to reach the relay, or any
/// answer other than the exact capability, is `false`.
///
/// The capability request is an await. Afterwards the enrollment must
/// still be the same confirmed FCM delivery for the same installation and
/// generation, and the relay client must still match the current
/// configuration, or the answer is `false`. This keeps a phone from
/// showing a control the send path would refuse after a rotation,
/// revocation or relay change.
pub(crate) async fn supports_fcm_session_alerts(&self, device: &str) -> bool {
let Some(delivery) = self.current_delivery(device).await else {
return false;
};
if delivery.provider() != Provider::Fcm {
return false;
}
let Some(relay) = self.relay().await else {
return false;
};
if !relay.supports_session_alerts().await {
return false;
}
let Some(current) = self.current_delivery(device).await else {
return false;
};
current.provider() == Provider::Fcm
&& current.installation_id() == delivery.installation_id()
&& current.generation() == delivery.generation()
&& self.still_configured_for(&relay).await
}

/// Reconcile one device once.
///
/// `member` is the current pairing registry: it must answer whether the
Expand Down
48 changes: 48 additions & 0 deletions desktop/ox-host-web/src/push_relay/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -621,6 +621,54 @@ async fn typed_send_fails_closed_without_the_exact_capability_body() {
}
}

#[tokio::test]
async fn session_alert_support_reuses_the_exact_capability_request() {
let cases = [
(capability_enabled(), true),
(json!({"status": 200, "body": {"sessionAlerts": 0}}), false),
(
json!({"status": 404, "body": {"error": "not_found"}}),
false,
),
(
json!({"status": 200, "body": {"sessionAlerts": 1, "extra": true}}),
false,
),
(json!({"status": 200, "body": [1]}), false),
(json!({"status": 200, "raw": "not json"}), false),
];
for (index, (step, expected)) in cases.into_iter().enumerate() {
let dir = tempfile::tempdir().unwrap();
let (mut server, port) = spawn_server(dir.path(), &json!([step]));
let client = client_with("https://relay.fixture.test", fixture_http(dir.path(), port));
assert_eq!(
client.supports_session_alerts().await,
expected,
"capability case {index}"
);
assert!(server.wait().unwrap().success());
let records = records(dir.path());
assert_eq!(records.len(), 1, "capability case {index}");
assert_eq!(records[0]["method"], "GET", "capability case {index}");
assert_eq!(
records[0]["path"], "/v1/capabilities",
"capability case {index}"
);
assert_eq!(
records[0]["authorization"],
format!("Bearer {}", credential()),
"capability case {index}"
);
}
}

#[tokio::test]
async fn a_stateless_worker_has_no_session_alert_capability_probe() {
let config = Config::stateless("https://relay.fixture.test").unwrap();
let client = Client::with_http(config, None, reqwest::Client::new());
assert!(!client.supports_session_alerts().await);
}

#[tokio::test]
async fn typed_capability_and_enqueue_stop_on_authentication_failure() {
let dir = tempfile::tempdir().unwrap();
Expand Down
98 changes: 96 additions & 2 deletions desktop/ox-host-web/src/remote_settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,11 @@ enum DeviceAction {
},
/// Disable this caller's own paired phone and revoke it at the relay.
NativePushDisable,
/// Read or change the authenticated phone's typed session-alert opt-in.
/// The reply is the capability the host can promise and the stored value.
NativeFcmSessionAlerts {
enabled: Option<bool>,
},
/// Read or change the authenticated phone's notification-action opt-in.
NativePushApprovalActions {
enabled: Option<bool>,
Expand All @@ -112,6 +117,9 @@ enum NativePush {
routing_token: String,
},
Disable,
SessionAlerts {
enabled: Option<bool>,
},
}

impl NativePush {
Expand All @@ -130,6 +138,9 @@ impl NativePush {
routing_token: routing_token.clone(),
}),
DeviceAction::NativePushDisable => Some(Self::Disable),
DeviceAction::NativeFcmSessionAlerts { enabled } => {
Some(Self::SessionAlerts { enabled: *enabled })
}
_ => None,
}
}
Expand Down Expand Up @@ -400,15 +411,23 @@ pub(super) async fn settings(
// Handled after this lock is released.
DeviceAction::NativePushStatus { .. }
| DeviceAction::NativePushEnable { .. }
| DeviceAction::NativePushDisable => unreachable!("native push after proof"),
| DeviceAction::NativePushDisable
| DeviceAction::NativeFcmSessionAlerts { .. } => {
unreachable!("native push after proof")
}
};
if let Some(data) = data {
return Ok(Json(data));
}
}
}
if let Some(action) = native_push {
return apply_native_push(&app, &id, action).await;
return match action {
NativePush::SessionAlerts { enabled } => {
apply_native_fcm_session_alerts(&app, &id, enabled).await
}
action => apply_native_push(&app, &id, action).await,
};
}
if let Some(DeviceAction::LookupApproval { reference }) = &device_action {
// Bound the global-snapshot work before opening the host socket. The
Expand Down Expand Up @@ -675,6 +694,9 @@ async fn apply_native_push(
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
(status, None)
}
NativePush::SessionAlerts { .. } => {
unreachable!("session alerts have their own settings action")
}
};
// The pairing may have expired or been removed while the file work or
// status read ran. Do not confirm anything to a device that is no longer
Expand All @@ -692,6 +714,78 @@ async fn apply_native_push(
Ok(Json(reply))
}

/// Read or change one authenticated phone's typed session-alert opt-in.
///
/// The stored `enabled` value is the only thing saved. The `support` value is
/// whether this phone could enable it right now: a confirmed, current FCM
/// enrollment and the configured credentialed relay's exact session-alert
/// capability, read with the same request and parser as a real send. No reply
/// ever carries a provider identifier, relay origin or error text, and a
/// stateless worker is never probed.
///
/// An explicit disable is a local opt-out and is saved before any relay
/// question, so it stands even when the relay is unreachable. The reply still
/// carries the freshly checked capability, so a healthy relay keeps the
/// control visible and off. An enable is refused while unsupported. Every
/// reply reads the stored value after the asynchronous capability read and
/// the live-pairing check, and every write rechecks the pairing under its own
/// lock.
async fn apply_native_fcm_session_alerts(
app: &App,
id: &str,
enabled: Option<bool>,
) -> Result<Json<Value>, ErrCode> {
// The dispatch above has already refused a caller that is not a live
// paired phone.
let service = app.push_relay.clone();
// Persist an explicit opt-out before asking the relay, so the local
// opt-out stands however the probe turns out.
if enabled == Some(false) {
fcm_session_alerts(app, id, Some(false))?;
}
let support = match service {
Some(service) => service.supports_fcm_session_alerts(id).await,
None => false,
};
// Read the stored value after the probe and the pairing check, so the
// reply cannot carry a snapshot from before either. This helper rechecks
// that the caller is still a live paired phone under its own lock, so a
// pairing removed during the await is never written or answered.
let stored = fcm_session_alerts(app, id, None)?;
if enabled == Some(true) {
if !support {
return Ok(Json(json!({"support": false, "enabled": stored})));
}
let stored = fcm_session_alerts(app, id, Some(true))?;
return Ok(Json(json!({"support": true, "enabled": stored})));
}
Ok(Json(json!({"support": support, "enabled": stored})))
}

/// Read or change one live phone's stored session-alert opt-in under one
/// lock. `None` reads, and `Some` edits and returns the stored value. The
/// pairing is checked under the same lock as the read or write.
fn fcm_session_alerts(app: &App, id: &str, enabled: Option<bool>) -> Result<bool, ErrCode> {
let mut state = app.state.lock().unwrap();
if !state.alive(id) || state.device_class(id) != Some(crate::admin::DeviceClass::Phone) {
return Err(DENY);
}
let change = enabled.map(|value| crate::push::PreferenceEdit {
event: crate::push::Preference::FcmSessionAlerts,
value,
});
state
.push_preferences(id, change)
.map(|state| state.preferences.stored_fcm_session_alerts())
.map_err(|error| {
if error.kind() == std::io::ErrorKind::PermissionDenied {
DENY
} else {
StatusCode::INTERNAL_SERVER_ERROR
}
})
}

#[cfg(test)]
mod memory_tests {
use super::*;
Expand Down
Loading
Loading