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
88 changes: 69 additions & 19 deletions desktop/ox-host-web/src/push.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use crate::{
admin::DeviceClass,
bridge,
push_relay::{self, EventRef, Notification, QueueStatus},
push_relay::{self, EventRef, Notification, QueueStatus, session_alert},
server::App,
state::now,
};
Expand Down Expand Up @@ -477,6 +477,8 @@ async fn deliveries(
struct NativeAsk {
scope: Scope,
reference: String,
/// Only finished, failed and goal alerts open a session without an ask.
session: Option<String>,
/// What happened. A phone is sent it only if its preferences allow it.
event: Event,
/// A finished session that also reached its goal. A phone that asked for
Expand Down Expand Up @@ -727,6 +729,25 @@ async fn native_notifications<F>(
else {
continue;
};
// Record the exact recipient before queueing: a fast tap can reach
// the host before the relay returns.
if let Some(thread) = &ask.session
&& let Some(reference) = session_alert::reference_suffix(&ask.reference)
{
service.session_alerts.lock().unwrap().remember(
target.device,
reference.to_owned(),
session_alert::Sent {
target: session_alert::Target {
scope: ask.scope.clone(),
thread: thread.clone(),
},
installation: target.installation_id,
expires_at,
},
epoch_ms(),
);
}
// Only a stateless worker is sent the route; a relay with a
// credential already holds it and the client leaves it out.
let notification = notification.with_route(
Expand Down Expand Up @@ -887,16 +908,52 @@ fn phone_access(bytes: &[u8]) -> io::Result<bridge::Access> {
}

async fn native_scope_reachable(app: App, scope: Scope) -> bool {
let result = tokio::time::timeout(Duration::from_secs(2), async {
check_native_scope(&app, &scope).await.unwrap_or(false)
}

async fn check_native_scope(app: &App, scope: &Scope) -> io::Result<bool> {
tokio::time::timeout(Duration::from_secs(2), async {
let host = bridge::connect(&app.host).await?;
let (reader, mut writer) = host.into_split();
let mut reader = BufReader::new(reader);
bridge::write(&mut writer, &Client::Hello { version: VERSION }).await?;
let hello = bridge::line(&mut reader, &mut Vec::new()).await?;
Ok::<_, io::Error>(phone_access(&hello)?.reachable(&app, &scope))
Ok(phone_access(&hello)?.reachable(app, scope))
})
.await;
matches!(result, Ok(Ok(true)))
.await
.map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "Host scope check timed out"))?
}

pub(crate) async fn lookup_session_alert(
app: &App,
device: &str,
reference: &str,
) -> io::Result<Option<session_alert::Target>> {
let Some(service) = &app.push_relay else {
return Ok(None);
};
let Some(scope) = service
.session_alerts
.lock()
.unwrap()
.get(device, reference, epoch_ms())
.map(|sent| sent.target.scope.clone())
else {
return Ok(None);
};
if !check_native_scope(app, &scope).await? {
return Ok(None);
}
let Some(delivery) = service.current_delivery(device).await else {
return Ok(None);
};
Ok(service
.session_alerts
.lock()
.unwrap()
.get(device, reference, epoch_ms())
.filter(|sent| sent.installation == *delivery.installation_id())
.map(|sent| sent.target.clone()))
}

enum Notices {
Expand Down Expand Up @@ -1022,6 +1079,7 @@ where
Some(NativeAsk {
scope: scope.clone(),
reference: ask.reference.clone()?,
session: None,
event: Event::Session(ask.kind),
goal: false,
done: Some(ask.done.clone()),
Expand All @@ -1033,8 +1091,7 @@ where
};
let mut native: Vec<NativeAsk> = native;
if reachable_scope {
// A finished or failed session. Its reference only tells two alerts
// apart: nothing is looked up by it.
// A finished or failed session can be opened by its own opaque reference.
for change in &changes {
let (Some(thread), Some(kind)) = (&change.thread, change.event) else {
continue;
Expand All @@ -1044,9 +1101,13 @@ where
{
continue;
}
let Some(reference) = session_alert::new_reference() else {
continue;
};
native.push(NativeAsk {
scope: scope.clone(),
reference: session_event_ref(thread, &c),
reference,
session: Some(thread.clone()),
event: Event::Session(kind),
goal: change.goal_reached && kind == NotificationKind::Finished,
done: None,
Expand Down Expand Up @@ -1114,17 +1175,6 @@ where
Ok((Notices::Delta(c, payloads), native))
}

/// An opaque reference for a session event: a digest of the thread and the
/// feed position that reported it.
fn session_event_ref(thread: &str, cursor: &Cursor) -> String {
let mut context = ring::digest::Context::new(&ring::digest::SHA256);
context.update(b"ox.push_session_event.v1\0");
context.update(thread.as_bytes());
context.update(b"\0");
context.update(format!("{}:{}", cursor.epoch, cursor.seq).as_bytes());
B64.encode(context.finish())
}

// Push never materializes transcript bodies or tool output from a global subscription.
#[derive(Deserialize)]
struct NoticeFrame {
Expand Down
99 changes: 98 additions & 1 deletion desktop/ox-host-web/src/push/native_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -507,6 +507,7 @@ async fn native_sender_queues_one_generic_alert_for_each_live_phone_only() {
tx.send(NativeAsk {
scope: fixture_scope(),
reference: reference.clone(),
session: None,
event: Event::Session(NotificationKind::Approval),
goal: false,
done: Some(done),
Expand Down Expand Up @@ -610,6 +611,7 @@ async fn native_sender_rechecks_the_pairing_immediately_before_each_send() {
tx.send(NativeAsk {
scope: fixture_scope(),
reference: reference(),
session: None,
event: Event::Session(NotificationKind::Approval),
goal: false,
done: Some(done),
Expand Down Expand Up @@ -651,6 +653,7 @@ async fn cancelled_asks_are_not_sent_and_a_failed_enqueue_is_not_retried() {
tx.send(NativeAsk {
scope: fixture_scope(),
reference: reference(),
session: None,
event: Event::Session(NotificationKind::Approval),
goal: false,
done: Some(done),
Expand All @@ -676,6 +679,7 @@ async fn cancelled_asks_are_not_sent_and_a_failed_enqueue_is_not_retried() {
tx.send(NativeAsk {
scope: fixture_scope(),
reference: reference(),
session: None,
event: Event::Session(NotificationKind::Approval),
goal: false,
done: Some(done),
Expand Down Expand Up @@ -735,6 +739,7 @@ async fn an_answered_ask_cancels_an_in_flight_enqueue() {
tx.send(NativeAsk {
scope: fixture_scope(),
reference: reference(),
session: None,
event: Event::Session(NotificationKind::Approval),
goal: false,
done: Some(done),
Expand Down Expand Up @@ -820,7 +825,8 @@ fn a_finished_or_failed_session_is_a_native_event_that_nothing_answers() {
assert!(event.done.is_none());
assert!(event.live());
assert!(EventRef::new(&event.reference).is_ok());
// The reference is a digest, never the thread or the title.
// The reference is random, never the thread or the title.
assert!(session_alert::reference_suffix(&event.reference).is_some());
assert!(!event.reference.contains("Fix"));
}
// The same thread at another feed position is another event.
Expand All @@ -832,6 +838,96 @@ fn a_finished_or_failed_session_is_a_native_event_that_nothing_answers() {
assert!(native.is_empty());
}

#[tokio::test]
async fn a_sent_session_alert_resolves_for_its_recipient_on_the_exact_live_route() {
let dir = state_dir();
let mut state = State::load(dir.path()).unwrap();
state
.set_origin(Some("https://test.tail.ts.net".into()), 0)
.unwrap();
let phone = paired_phone(&mut state, "Phone");
let other = paired_phone(&mut state, "Other phone");
enroll_active(dir.path(), &phone, "routing-token-phone");
let service = Arc::new(Service::new(dir.path().to_path_buf()));
let app = app(dir.path(), state, service.clone());
let listener = tokio::net::UnixListener::bind(&*app.host).unwrap();
let scope = fixture_scope();
let reply_scope = scope.clone();
let host = tokio::spawn(async move {
let (stream, _) = listener.accept().await.unwrap();
let (reader, mut writer) = stream.into_split();
let mut reader = BufReader::new(reader);
let hello = bridge::line(&mut reader, &mut Vec::new()).await.unwrap();
assert!(matches!(
serde_json::from_slice::<Client>(&hello).unwrap(),
Client::Hello { .. }
));
bridge::write(
&mut writer,
&Server::Hello {
version: VERSION,
capabilities: vec![],
projects: vec![reply_scope.project],
routes: vec![reply_scope.route],
host: None,
},
)
.await
.unwrap();
});
let reference = session_alert::new_reference().unwrap();
let suffix = session_alert::reference_suffix(&reference)
.unwrap()
.to_owned();
let queue = Arc::new(Queue::stateless());
queue.on_call({
let service = service.clone();
let phone = phone.clone();
let suffix = suffix.clone();
move |_| {
assert!(
service
.session_alerts
.lock()
.unwrap()
.get(&phone, &suffix, epoch_ms())
.is_some(),
"an alert can be tapped before the relay responds"
);
}
});
let (tx, rx) = mpsc::channel(1);
tx.send(NativeAsk {
scope: scope.clone(),
reference,
session: Some("thread-with-exact-route".into()),
event: Event::Session(NotificationKind::Finished),
goal: false,
done: None,
})
.await
.unwrap();
drop(tx);
native_notifications(app.clone(), service, queue.clone(), rx, |_, _| {
std::future::ready(true)
})
.await;
assert_eq!(queue.calls().len(), 1);
assert!(
lookup_session_alert(&app, &other, &suffix)
.await
.unwrap()
.is_none()
);
let target = lookup_session_alert(&app, &phone, &suffix)
.await
.unwrap()
.unwrap();
assert_eq!(target.scope, scope);
assert_eq!(target.thread, "thread-with-exact-route");
host.await.unwrap();
}

async fn kinds_sent(
edits: &[(Preference, bool)],
queue: Queue,
Expand Down Expand Up @@ -880,6 +976,7 @@ async fn kinds_sent(
tx.send(NativeAsk {
scope: fixture_scope(),
reference: format!("session-event-reference-{index}"),
session: None,
event,
goal,
done,
Expand Down
2 changes: 2 additions & 0 deletions desktop/ox-host-web/src/push_relay.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1041,3 +1041,5 @@ pub(crate) mod enrollment;
pub(crate) mod host_config;
#[cfg(feature = "server")]
pub(crate) mod service;
#[cfg(feature = "server")]
pub(crate) mod session_alert;
4 changes: 3 additions & 1 deletion desktop/ox-host-web/src/push_relay/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ use super::{
self, DeviceId, Enrollment, Error as StateError, PendingRegistration, PendingRevocation,
Store,
},
host_config,
host_config, session_alert,
};
use crate::admin::DeviceClass;
use std::{
Expand Down Expand Up @@ -144,6 +144,7 @@ pub(crate) struct Service {
store: Arc<Mutex<Option<Store>>>,
/// Wakes the background task after a local mutation.
notify: Notify,
pub(crate) session_alerts: Mutex<session_alert::Cache>,
}

/// One durable, active enrollment a native alert may target.
Expand All @@ -160,6 +161,7 @@ impl Service {
dir,
store: Arc::new(Mutex::new(None)),
notify: Notify::new(),
session_alerts: Mutex::default(),
}
}

Expand Down
Loading
Loading