1use std::borrow::Cow;
4use std::env;
5use std::fs as std_fs;
6use std::fs::OpenOptions;
7use std::io::Write;
8use std::net;
9use std::os::unix::fs::OpenOptionsExt;
10use std::path::Path;
11use std::path::PathBuf;
12use std::process;
13
14use anyhow::Context;
15use futures::{SinkExt, StreamExt};
16use serde::{Deserialize, Serialize};
17use subtle::ConstantTimeEq;
18use tokio::fs;
19use tokio::net::TcpListener;
20use tokio::sync::broadcast;
21use tokio_tungstenite::tungstenite::Message;
22use tokio_tungstenite::tungstenite::handshake::server::ErrorResponse;
23use tokio_tungstenite::tungstenite::handshake::server::Request;
24use tokio_tungstenite::tungstenite::handshake::server::Response;
25use tokio_tungstenite::tungstenite::http::StatusCode;
26use tokio_tungstenite::tungstenite::http::header;
27
28use crate::home;
29
30#[derive(Clone, Debug, Default)]
32pub struct EventFilter {
33 pub task_id: Option<String>,
34 pub repo: Option<String>,
35}
36
37impl EventFilter {
38 fn from_request(request: &Request) -> Self {
40 let uri = request.uri();
41 let Some(query) = uri.query() else {
42 return Self::default();
43 };
44
45 let mut task_id = None;
46 let mut repo = None;
47
48 for pair in query.split('&') {
49 let Some((key, value)) = pair.split_once('=') else {
50 continue;
51 };
52 let decoded = urlencoding::decode(value).unwrap_or(Cow::Borrowed(value));
53 match key {
54 "task_id" => task_id = Some(decoded.into_owned()),
55 "repo" => repo = Some(decoded.into_owned()),
56 _ => {}
57 }
58 }
59
60 Self { task_id, repo }
61 }
62
63 fn matches(&self, event: &TaskEvent) -> bool {
65 if let Some(ref task_id) = self.task_id
66 && event.task_id != *task_id
67 {
68 return false;
69 }
70 if let Some(ref repo) = self.repo
71 && event.repo != *repo
72 {
73 return false;
74 }
75 true
76 }
77}
78
79fn query_value<'a>(request: &'a Request, key: &str) -> Option<Cow<'a, str>> {
80 let query = request.uri().query()?;
81 for pair in query.split('&') {
82 let Some((k, value)) = pair.split_once('=') else {
83 continue;
84 };
85 if k == key {
86 return Some(urlencoding::decode(value).unwrap_or(Cow::Borrowed(value)));
87 }
88 }
89 None
90}
91
92fn handshake_token(request: &Request) -> Cow<'_, str> {
93 if let Some(token) = query_value(request, "token") {
94 return token;
95 }
96 request
97 .headers()
98 .get(header::SEC_WEBSOCKET_PROTOCOL)
99 .and_then(|v| v.to_str().ok())
100 .map_or(Cow::Borrowed(""), |v| Cow::Borrowed(v.trim()))
101}
102
103fn authorize_handshake(request: &Request, token: &str, host: &str) -> Result<(), StatusCode> {
104 if request.headers().get(header::ORIGIN).is_some() {
106 return Err(StatusCode::FORBIDDEN);
107 }
108 let host_ok = request
110 .headers()
111 .get(header::HOST)
112 .is_some_and(|h| h.as_bytes() == host.as_bytes());
113 if !host_ok {
114 return Err(StatusCode::UNAUTHORIZED);
115 }
116 let given = handshake_token(request);
117 let token_ok: bool = given.as_bytes().ct_eq(token.as_bytes()).into();
118 if token_ok {
119 Ok(())
120 } else {
121 Err(StatusCode::UNAUTHORIZED)
122 }
123}
124
125fn handshake_error(status: StatusCode) -> ErrorResponse {
126 let mut resp = ErrorResponse::new(None);
127 *resp.status_mut() = status;
128 resp
129}
130
131#[derive(Clone, Debug, Serialize, Deserialize)]
137pub struct ControlMessage {
138 pub kind: String,
140 pub message: String,
142 pub missed: u64,
144}
145
146#[derive(Clone, Debug, Serialize, Deserialize)]
148pub struct TaskEvent {
149 pub task_id: String,
150 pub repo: String,
151 pub old_status: String,
152 pub new_status: String,
153 pub agent: Option<String>,
154 pub model: Option<String>,
155 pub pr_number: Option<String>,
156 pub branch: Option<String>,
157 pub review_context: Option<String>,
158 pub error: Option<String>,
159 pub timestamp: String,
160 pub title: Option<String>,
161 pub summary: Option<String>,
162 pub duration_seconds: Option<f64>,
163}
164
165#[derive(Debug)]
167pub struct EventBus {
168 tx: broadcast::Sender<TaskEvent>,
169}
170
171impl EventBus {
172 pub fn new(capacity: usize) -> Self {
173 let (tx, _) = broadcast::channel(capacity);
174 Self { tx }
175 }
176
177 pub fn sender(&self) -> broadcast::Sender<TaskEvent> {
179 self.tx.clone()
180 }
181
182 pub fn subscribe(&self) -> broadcast::Receiver<TaskEvent> {
184 self.tx.subscribe()
185 }
186
187 #[cfg(test)]
189 pub fn publish(&self, event: TaskEvent) -> usize {
190 self.tx.send(event).unwrap_or(0)
191 }
192
193 pub async fn start_ws_server(&self) -> anyhow::Result<(u16, String)> {
196 let (listener, port) = select_available_listener()?;
199 listener.set_nonblocking(true)?;
200 let listener = TcpListener::from_std(listener)?;
201
202 let token = format!(
203 "{}{}",
204 uuid::Uuid::new_v4().simple(),
205 uuid::Uuid::new_v4().simple()
206 );
207 let host = format!("127.0.0.1:{port}");
208 write_private(&ws_port_path()?, &format!("{port} {token}"))?;
209
210 if let Ok(path) = home::service_version_path() {
213 if let Some(parent) = path.parent() {
214 let _ = fs::create_dir_all(parent).await;
215 }
216 let pid = process::id();
217 let content = format!("{}\t{}", pid, env!("ORCH_VERSION"));
218 let _ = fs::write(path, content).await;
219 }
220
221 let tx = self.tx.clone();
222 let serve_token = token.clone();
223 let serve_host = host;
224 tokio::spawn(async move {
225 loop {
226 match listener.accept().await {
227 Ok((stream, _addr)) => {
228 let mut rx = tx.subscribe();
229 let token = serve_token.clone();
230 let host = serve_host.clone();
231 tokio::spawn(async move {
232 let mut filter = EventFilter::default();
233 #[expect(
234 clippy::result_large_err,
235 reason = "the tungstenite callback type fixes the error type"
236 )]
237 let callback = |req: &Request,
238 mut resp: Response|
239 -> Result<Response, ErrorResponse> {
240 if let Err(status) = authorize_handshake(req, &token, &host) {
241 return Err(handshake_error(status));
242 }
243 if let Some(proto) =
244 req.headers().get(header::SEC_WEBSOCKET_PROTOCOL)
245 {
246 let proto_ok: bool =
247 proto.as_bytes().ct_eq(token.as_bytes()).into();
248 if proto_ok {
249 resp.headers_mut()
250 .insert(header::SEC_WEBSOCKET_PROTOCOL, proto.clone());
251 }
252 }
253 filter = EventFilter::from_request(req);
254 tracing::debug!(?filter, "ws client connected with filter");
255 Ok(resp)
256 };
257 let Ok(ws) =
258 tokio_tungstenite::accept_hdr_async(stream, callback).await
259 else {
260 return;
261 };
262 let (mut write, mut read) = ws.split();
263 loop {
264 tokio::select! {
265 event = rx.recv() => {
266 match event {
267 Ok(e) => {
268 if !filter.matches(&e) {
269 continue;
270 }
271 let json = serde_json::to_string(&e)
272 .unwrap_or_default();
273 let msg = Message::Text(json);
274 if write.send(msg).await.is_err() {
275 break;
276 }
277 }
278 Err(broadcast::error::RecvError::Lagged(n)) => {
279 tracing::warn!(
280 missed = n,
281 "event bus ws client lagged — {n} events dropped"
282 );
283 let ctrl = ControlMessage {
284 kind: "lagged".to_string(),
285 message: format!(
286 "event bus lagged: {n} events were dropped — resync from store"
287 ),
288 missed: n,
289 };
290 if let Ok(json) = serde_json::to_string(&ctrl) {
291 let msg = Message::Text(json);
292 if write.send(msg).await.is_err() {
293 break;
294 }
295 }
296 }
297 Err(_) => break,
298 }
299 }
300 msg = read.next() => {
301 if msg.is_none() {
303 break;
304 }
305 }
306 }
307 }
308 });
309 }
310 Err(e) => {
311 tracing::warn!(?e, "ws accept failed");
312 }
313 }
314 }
315 });
316
317 tracing::info!(port, "event bus websocket server started on 127.0.0.1");
318 Ok((port, token))
319 }
320}
321
322pub fn select_available_listener() -> anyhow::Result<(net::TcpListener, u16)> {
326 let hostname = env::var("HOSTNAME").unwrap_or_else(|_| "orch".to_string());
327 let hash = hostname
328 .bytes()
329 .fold(0u32, |acc, b| acc.wrapping_add(u32::from(b)));
330 let range = 65535u32 - 49152;
331 let start = 49152u16 + u16::try_from(hash % range).unwrap_or(0);
332
333 for offset in 0..1000u16 {
334 let port = start.wrapping_add(offset);
335 if port < 49152 {
336 continue;
337 }
338 if let Ok(listener) = net::TcpListener::bind(("127.0.0.1", port)) {
339 return Ok((listener, port));
340 }
341 }
342 anyhow::bail!("no available port found in range 49152-65535")
343}
344
345pub async fn cleanup_port_file() {
347 if let Ok(path) = ws_port_path() {
348 let _ = fs::remove_file(path).await;
349 }
350}
351
352pub fn cleanup_version_file() {
354 if let Ok(path) = home::service_version_path() {
355 let owned = std_fs::read_to_string(&path)
356 .ok()
357 .and_then(|s| s.split('\t').next()?.parse::<u32>().ok())
358 .is_none_or(|pid| pid == process::id()); if owned {
360 let _ = std_fs::remove_file(path);
361 }
362 }
363}
364
365fn ws_port_path() -> anyhow::Result<PathBuf> {
366 if cfg!(test) {
367 Ok(env::temp_dir().join("orch-test-state").join("ws.port"))
368 } else {
369 Ok(home::state_dir()?.join("ws.port"))
370 }
371}
372
373fn write_private(path: &Path, body: &str) -> anyhow::Result<()> {
375 if let Some(parent) = path.parent() {
376 std_fs::create_dir_all(parent)?;
377 }
378
379 let tmp = path.with_extension(format!("tmp.{}", process::id()));
380 let mut file = OpenOptions::new()
381 .write(true)
382 .create(true)
383 .truncate(true)
384 .mode(0o600)
385 .open(&tmp)?;
386 file.write_all(body.as_bytes())?;
387 std_fs::rename(&tmp, path)?;
388 Ok(())
389}
390
391fn parse_ws_credentials(body: &str) -> anyhow::Result<(u16, String)> {
392 let mut parts = body.split_whitespace();
393 let port = parts
394 .next()
395 .ok_or_else(|| anyhow::anyhow!("empty ws.port"))?
396 .parse()
397 .context("invalid port number in ws.port")?;
398 let token = parts
399 .next()
400 .ok_or_else(|| anyhow::anyhow!("ws.port missing token"))?
401 .to_string();
402 Ok((port, token))
403}
404
405pub fn read_ws_credentials() -> anyhow::Result<(u16, String)> {
407 let body = std_fs::read_to_string(ws_port_path()?)
408 .context("event bus not running — is the service started? (ws.port not found)")?;
409 parse_ws_credentials(&body)
410}
411
412#[cfg(test)]
413mod tests {
414 use std::os::unix::fs::PermissionsExt;
415 use std::time::Duration;
416
417 use tokio::time;
418 use tokio_tungstenite::tungstenite::Error;
419 use tokio_tungstenite::tungstenite::client::IntoClientRequest;
420
421 use super::*;
422
423 #[test]
424 fn control_message_serializes_to_json() {
425 let ctrl = ControlMessage {
426 kind: "lagged".to_string(),
427 message: "event bus lagged: 5 events were dropped".to_string(),
428 missed: 5,
429 };
430 let json = serde_json::to_string(&ctrl).unwrap();
431 assert!(json.contains("\"kind\":\"lagged\""));
432 assert!(json.contains("\"missed\":5"));
433 }
434
435 #[test]
436 fn control_message_round_trips() {
437 let ctrl = ControlMessage {
438 kind: "lagged".to_string(),
439 message: "test".to_string(),
440 missed: 42,
441 };
442 let json = serde_json::to_string(&ctrl).unwrap();
443 let decoded: ControlMessage = serde_json::from_str(&json).unwrap();
444 assert_eq!(decoded.kind, "lagged");
445 assert_eq!(decoded.missed, 42);
446 }
447
448 #[test]
449 fn task_event_serializes_to_json() {
450 let event = TaskEvent {
451 task_id: "123".to_string(),
452 repo: "owner/repo".to_string(),
453 old_status: "new".to_string(),
454 new_status: "routed".to_string(),
455 agent: Some("claude".to_string()),
456 model: None,
457 pr_number: None,
458 branch: None,
459 review_context: None,
460 error: None,
461 timestamp: "2026-03-23T12:00:00Z".to_string(),
462 title: None,
463 summary: None,
464 duration_seconds: None,
465 };
466 let json = serde_json::to_string(&event).unwrap();
467 assert!(json.contains("\"task_id\":\"123\""));
468 assert!(json.contains("\"new_status\":\"routed\""));
469 }
470
471 #[test]
472 fn event_bus_send_receive() {
473 let bus = EventBus::new(256);
474 let mut rx = bus.subscribe();
475 let event = TaskEvent {
476 task_id: "1".to_string(),
477 repo: "r".to_string(),
478 old_status: "new".to_string(),
479 new_status: "routed".to_string(),
480 agent: None,
481 model: None,
482 pr_number: None,
483 branch: None,
484 review_context: None,
485 error: None,
486 timestamp: "2026-03-23T12:00:00Z".to_string(),
487 title: None,
488 summary: None,
489 duration_seconds: None,
490 };
491 bus.publish(event);
492 let received = rx.try_recv().unwrap();
493 assert_eq!(received.task_id, "1");
494 assert_eq!(received.new_status, "routed");
495 }
496
497 #[test]
498 fn select_port_finds_available_port() {
499 let (listener, port) = select_available_listener().unwrap();
500 assert!(port >= 49152);
501 let second_bind = net::TcpListener::bind(("127.0.0.1", port));
503 assert!(second_bind.is_err());
504 drop(listener);
505 }
506
507 fn make_event(task_id: &str, repo: &str) -> TaskEvent {
508 TaskEvent {
509 task_id: task_id.to_string(),
510 repo: repo.to_string(),
511 old_status: "new".to_string(),
512 new_status: "routed".to_string(),
513 agent: None,
514 model: None,
515 pr_number: None,
516 branch: None,
517 review_context: None,
518 error: None,
519 timestamp: "2026-03-23T12:00:00Z".to_string(),
520 title: None,
521 summary: None,
522 duration_seconds: None,
523 }
524 }
525
526 fn authed_url(port: u16, token: &str, extra: &str) -> String {
527 let mut url = format!("ws://127.0.0.1:{port}/events?token={token}");
528 if !extra.is_empty() {
529 url.push('&');
530 url.push_str(extra);
531 }
532 url
533 }
534
535 async fn handshake_status(req: impl IntoClientRequest + Unpin) -> u16 {
536 match tokio_tungstenite::connect_async(req).await {
537 Ok(_) => 101,
538 Err(Error::Http(resp)) => resp.status().as_u16(),
539 Err(e) => panic!("expected HTTP handshake status, got {e}"),
540 }
541 }
542
543 #[test]
544 fn event_filter_empty_matches_all() {
545 let filter = EventFilter::default();
546 assert!(filter.matches(&make_event("1", "a/b")));
547 assert!(filter.matches(&make_event("999", "x/y")));
548 }
549
550 #[test]
551 fn event_filter_task_id_filters() {
552 let filter = EventFilter {
553 task_id: Some("42".to_string()),
554 repo: None,
555 };
556 assert!(filter.matches(&make_event("42", "a/b")));
557 assert!(!filter.matches(&make_event("43", "a/b")));
558 }
559
560 #[test]
561 fn event_filter_repo_filters() {
562 let filter = EventFilter {
563 task_id: None,
564 repo: Some("owner/repo".to_string()),
565 };
566 assert!(filter.matches(&make_event("1", "owner/repo")));
567 assert!(!filter.matches(&make_event("1", "other/repo")));
568 }
569
570 #[test]
571 fn event_filter_repo_exact_match() {
572 let filter = EventFilter {
573 task_id: None,
574 repo: Some("owner".to_string()),
575 };
576 assert!(filter.matches(&make_event("1", "owner")));
577 assert!(!filter.matches(&make_event("1", "owner/repo")));
578 assert!(!filter.matches(&make_event("1", "someone/else")));
579 }
580
581 #[test]
582 fn event_filter_combined() {
583 let filter = EventFilter {
584 task_id: Some("5".to_string()),
585 repo: Some("a/b".to_string()),
586 };
587 assert!(filter.matches(&make_event("5", "a/b")));
588 assert!(!filter.matches(&make_event("6", "a/b")));
589 assert!(!filter.matches(&make_event("5", "c/d")));
590 }
591
592 #[tokio::test]
593 async fn ws_server_broadcasts_events() {
594 let bus = EventBus::new(256);
595 let (port, token) = bus.start_ws_server().await.unwrap();
596
597 let url = authed_url(port, &token, "");
599 let (ws, _) = tokio_tungstenite::connect_async(&url).await.unwrap();
600 let (_write, mut read) = ws.split();
601
602 time::sleep(Duration::from_millis(50)).await;
604
605 let mut event_with_agent = make_event("test-1", "owner/repo");
607 event_with_agent.agent = Some("claude".to_string());
608 bus.publish(event_with_agent);
609
610 let msg = time::timeout(Duration::from_secs(2), StreamExt::next(&mut read))
612 .await
613 .unwrap()
614 .unwrap()
615 .unwrap();
616
617 if let Message::Text(text) = msg {
618 let received: TaskEvent = serde_json::from_str(&text).unwrap();
619 assert_eq!(received.task_id, "test-1");
620 assert_eq!(received.new_status, "routed");
621 assert_eq!(received.agent, Some("claude".to_string()));
622 } else {
623 panic!("expected text message");
624 }
625
626 cleanup_port_file().await;
628 }
629
630 #[tokio::test]
631 async fn ws_filter_by_task_id() {
632 let bus = EventBus::new(256);
633 let (port, token) = bus.start_ws_server().await.unwrap();
634
635 let url = authed_url(port, &token, "task_id=42");
637 let (ws, _) = tokio_tungstenite::connect_async(&url).await.unwrap();
638 let (_write, mut read) = ws.split();
639
640 time::sleep(Duration::from_millis(50)).await;
641
642 bus.publish(make_event("42", "owner/repo"));
644 bus.publish(make_event("99", "owner/repo"));
646
647 let msg = time::timeout(Duration::from_secs(2), StreamExt::next(&mut read))
648 .await
649 .unwrap()
650 .unwrap()
651 .unwrap();
652
653 if let Message::Text(text) = msg {
654 let received: TaskEvent = serde_json::from_str(&text).unwrap();
655 assert_eq!(received.task_id, "42");
656 } else {
657 panic!("expected text message");
658 }
659
660 let result = time::timeout(Duration::from_millis(300), StreamExt::next(&mut read)).await;
662 assert!(result.is_err(), "expected no more messages (filtered)");
663
664 cleanup_port_file().await;
665 }
666
667 #[tokio::test]
668 async fn ws_filter_by_repo() {
669 let bus = EventBus::new(256);
670 let (port, token) = bus.start_ws_server().await.unwrap();
671
672 let url = authed_url(
673 port,
674 &token,
675 &format!("repo={}", urlencoding::encode("gabrielkoerich/orch")),
676 );
677 let (ws, _) = tokio_tungstenite::connect_async(&url).await.unwrap();
678 let (_write, mut read) = ws.split();
679
680 time::sleep(Duration::from_millis(50)).await;
681
682 bus.publish(make_event("1", "gabrielkoerich/orch"));
684 bus.publish(make_event("2", "other/repo"));
686
687 let msg = time::timeout(Duration::from_secs(2), StreamExt::next(&mut read))
688 .await
689 .unwrap()
690 .unwrap()
691 .unwrap();
692
693 if let Message::Text(text) = msg {
694 let received: TaskEvent = serde_json::from_str(&text).unwrap();
695 assert_eq!(received.task_id, "1");
696 assert_eq!(received.repo, "gabrielkoerich/orch");
697 } else {
698 panic!("expected text message");
699 }
700
701 let result = time::timeout(Duration::from_millis(300), StreamExt::next(&mut read)).await;
703 assert!(result.is_err(), "expected no more messages (filtered)");
704
705 cleanup_port_file().await;
706 }
707
708 #[tokio::test]
709 async fn ws_unfiltered_client_receives_all() {
710 let bus = EventBus::new(256);
711 let (port, token) = bus.start_ws_server().await.unwrap();
712
713 let url = authed_url(port, &token, "");
714 let (ws, _) = tokio_tungstenite::connect_async(&url).await.unwrap();
715 let (_write, mut read) = ws.split();
716
717 time::sleep(Duration::from_millis(50)).await;
718
719 bus.publish(make_event("1", "a/b"));
720 bus.publish(make_event("2", "c/d"));
721 bus.publish(make_event("3", "e/f"));
722
723 let mut received_ids = Vec::new();
724 for _ in 0..3 {
725 let msg = time::timeout(Duration::from_secs(2), StreamExt::next(&mut read))
726 .await
727 .unwrap()
728 .unwrap()
729 .unwrap();
730
731 if let Message::Text(text) = msg {
732 let event: TaskEvent = serde_json::from_str(&text).unwrap();
733 received_ids.push(event.task_id);
734 }
735 }
736
737 assert_eq!(received_ids, vec!["1", "2", "3"]);
738
739 cleanup_port_file().await;
740 }
741
742 #[tokio::test]
745 async fn ws_server_sends_lag_control_message() {
746 let bus = EventBus::new(1);
749 let Ok((port, token)) = bus.start_ws_server().await else {
750 return;
752 };
753
754 let url = authed_url(port, &token, "");
756 let (ws, _) = tokio_tungstenite::connect_async(&url).await.unwrap();
757 let (_write, mut read) = ws.split();
758
759 time::sleep(Duration::from_millis(50)).await;
761
762 for i in 0..20 {
765 bus.publish(make_event(&i.to_string(), "owner/repo"));
766 }
767
768 let mut got_lag = false;
770 for _ in 0..30 {
771 let result = time::timeout(Duration::from_secs(2), StreamExt::next(&mut read)).await;
772
773 let Ok(Some(Ok(msg))) = result else { break };
774
775 if let Message::Text(text) = msg
776 && let Ok(ctrl) = serde_json::from_str::<ControlMessage>(&text)
777 && ctrl.kind == "lagged"
778 {
779 got_lag = true;
780 assert!(ctrl.missed > 0, "missed count must be > 0");
781 break;
782 }
783 }
784
785 assert!(
786 got_lag,
787 "expected a lagged ControlMessage when bus capacity is exceeded"
788 );
789
790 cleanup_port_file().await;
791 }
792
793 #[test]
794 fn parse_ws_credentials_reads_port_and_token() {
795 let (port, token) = parse_ws_credentials("51234 abcdef\n").unwrap();
796 assert_eq!(port, 51234);
797 assert_eq!(token, "abcdef");
798 }
799
800 #[test]
801 fn parse_ws_credentials_rejects_port_only() {
802 assert!(
803 parse_ws_credentials("51234\n").is_err(),
804 "a port file without a token is refused"
805 );
806 }
807
808 #[test]
809 fn write_private_creates_owner_only_file() {
810 let dir = tempfile::tempdir().unwrap();
811 let path = dir.path().join("ws.port");
812 write_private(&path, "9 tok").unwrap();
813 let mode = std_fs::metadata(&path).unwrap().permissions().mode();
814 assert_eq!(mode & 0o777, 0o600, "ws.port must be owner-only");
815 }
816
817 #[tokio::test]
818 async fn ws_port_file_is_owner_only() {
819 let bus = EventBus::new(16);
820 let (port, token) = bus.start_ws_server().await.unwrap();
821 let path = ws_port_path().unwrap();
822 let body = std_fs::read_to_string(&path).unwrap_or_default();
823 if body.contains(&token) {
824 let mode = std_fs::metadata(&path).unwrap().permissions().mode();
825 assert_eq!(mode & 0o777, 0o600, "ws.port must be owner-only");
826 assert!(
827 body.starts_with(&format!("{port} ")),
828 "port is first in the file, got {body:?}"
829 );
830 }
831 cleanup_port_file().await;
832 }
833
834 #[tokio::test]
835 async fn ws_handshake_rejects_a_missing_token() {
836 let bus = EventBus::new(16);
837 let (port, _token) = bus.start_ws_server().await.unwrap();
838 let url = format!("ws://127.0.0.1:{port}/events");
839 assert_eq!(
840 handshake_status(&url).await,
841 401,
842 "a handshake with no token is unauthorized"
843 );
844 cleanup_port_file().await;
845 }
846
847 #[tokio::test]
848 async fn ws_handshake_rejects_a_wrong_token() {
849 let bus = EventBus::new(16);
850 let (port, _token) = bus.start_ws_server().await.unwrap();
851 let url = format!("ws://127.0.0.1:{port}/events?token=nope");
852 assert_eq!(
853 handshake_status(&url).await,
854 401,
855 "a handshake with a wrong token is unauthorized"
856 );
857 cleanup_port_file().await;
858 }
859
860 #[tokio::test]
861 async fn ws_handshake_rejects_another_host() {
862 let bus = EventBus::new(16);
863 let (port, token) = bus.start_ws_server().await.unwrap();
864 let url = format!("ws://localhost:{port}/events?token={token}");
865 assert_eq!(
866 handshake_status(&url).await,
867 401,
868 "a Host other than 127.0.0.1 is refused"
869 );
870 cleanup_port_file().await;
871 }
872
873 #[tokio::test]
874 async fn ws_handshake_rejects_any_origin() {
875 let bus = EventBus::new(16);
876 let (port, token) = bus.start_ws_server().await.unwrap();
877 let mut req = authed_url(port, &token, "").into_client_request().unwrap();
878 req.headers_mut()
879 .insert("origin", "http://evil.test".parse().unwrap());
880 assert_eq!(
881 handshake_status(req).await,
882 403,
883 "a handshake with an Origin header is forbidden"
884 );
885 cleanup_port_file().await;
886 }
887
888 #[tokio::test]
889 async fn ws_handshake_accepts_sec_websocket_protocol() {
890 let bus = EventBus::new(16);
891 let (port, token) = bus.start_ws_server().await.unwrap();
892 let mut req = format!("ws://127.0.0.1:{port}/events")
893 .into_client_request()
894 .unwrap();
895 req.headers_mut()
896 .insert("sec-websocket-protocol", token.parse().unwrap());
897 assert_eq!(
898 handshake_status(req).await,
899 101,
900 "the token may be sent as Sec-WebSocket-Protocol"
901 );
902 cleanup_port_file().await;
903 }
904}