278 行
9.1 KiB
Rust
278 行
9.1 KiB
Rust
use std::{
|
|
net::{IpAddr, Ipv4Addr, SocketAddr},
|
|
time::Duration,
|
|
};
|
|
|
|
use desktop_protocol::{
|
|
ActiveSlotKind, AuthLoginRequest, AuthLoginResponse, BoundGatewayEvent, ClientCapabilities,
|
|
EventMetadata, GatewayEvent, GatewayEventBody, HealthResponse, HeartbeatPayload,
|
|
PROTOCOL_VERSION, RawProtocolEnvelope,
|
|
};
|
|
use mock_gateway::{MockGatewayConfig, MockGatewayError, MockInstanceKind, spawn_mock_gateway};
|
|
use reqwest::{Client, Response, StatusCode};
|
|
use serde_json::Value;
|
|
use tokio::time::timeout;
|
|
use uuid::Uuid;
|
|
|
|
#[tokio::test]
|
|
async fn refuses_non_loopback_bind_addresses() {
|
|
let mut config = MockGatewayConfig::for_test(MockInstanceKind::Companion);
|
|
config.bind_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 0);
|
|
let result = spawn_mock_gateway(config).await;
|
|
assert!(matches!(result, Err(MockGatewayError::NonLoopbackBind(_))));
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn companion_and_operations_streams_are_independent_and_replay_by_cursor() {
|
|
let companion = spawn_mock_gateway(MockGatewayConfig::for_test(MockInstanceKind::Companion))
|
|
.await
|
|
.unwrap();
|
|
let operations = spawn_mock_gateway(MockGatewayConfig::for_test(MockInstanceKind::Operations))
|
|
.await
|
|
.unwrap();
|
|
let client = Client::new();
|
|
|
|
let companion_health: HealthResponse = client
|
|
.get(format!("{}/desktop/v1/health", companion.base_url()))
|
|
.send()
|
|
.await
|
|
.unwrap()
|
|
.error_for_status()
|
|
.unwrap()
|
|
.json()
|
|
.await
|
|
.unwrap();
|
|
let operations_health: HealthResponse = client
|
|
.get(format!("{}/desktop/v1/health", operations.base_url()))
|
|
.send()
|
|
.await
|
|
.unwrap()
|
|
.error_for_status()
|
|
.unwrap()
|
|
.json()
|
|
.await
|
|
.unwrap();
|
|
assert_ne!(
|
|
companion_health.server_instance_id,
|
|
operations_health.server_instance_id
|
|
);
|
|
|
|
let companion_token = login(&client, &companion.base_url()).await;
|
|
let operations_token = login(&client, &operations.base_url()).await;
|
|
let mut companion_stream =
|
|
open_stream(&client, &companion.base_url(), &companion_token, None).await;
|
|
let mut operations_stream =
|
|
open_stream(&client, &operations.base_url(), &operations_token, None).await;
|
|
let mut companion_buffer = String::new();
|
|
let mut operations_buffer = String::new();
|
|
|
|
let shared_event_id = "same-event-id";
|
|
companion
|
|
.emit_event(event_for(
|
|
shared_event_id,
|
|
companion.server_instance_id(),
|
|
1,
|
|
))
|
|
.await
|
|
.unwrap();
|
|
operations
|
|
.emit_event(event_for(
|
|
shared_event_id,
|
|
operations.server_instance_id(),
|
|
1,
|
|
))
|
|
.await
|
|
.unwrap();
|
|
|
|
let companion_wire = next_sse_data(&mut companion_stream, &mut companion_buffer).await;
|
|
let operations_wire = next_sse_data(&mut operations_stream, &mut operations_buffer).await;
|
|
assert_eq!(companion_wire["eventId"], shared_event_id);
|
|
assert_eq!(operations_wire["eventId"], shared_event_id);
|
|
assert_ne!(
|
|
companion_wire["serverInstanceId"],
|
|
operations_wire["serverInstanceId"]
|
|
);
|
|
|
|
let companion_bound = bind_wire(
|
|
companion_wire,
|
|
"local-companion",
|
|
ActiveSlotKind::Companion,
|
|
companion.server_instance_id(),
|
|
);
|
|
let operations_bound = bind_wire(
|
|
operations_wire,
|
|
"local-operations",
|
|
ActiveSlotKind::Operations,
|
|
operations.server_instance_id(),
|
|
);
|
|
assert_eq!(companion_bound.profile_id, "local-companion");
|
|
assert_eq!(operations_bound.profile_id, "local-operations");
|
|
|
|
companion.disconnect_streams();
|
|
let operations_second = operations
|
|
.emit_body(GatewayEventBody::Heartbeat(HeartbeatPayload {
|
|
interval_ms: 1_000,
|
|
}))
|
|
.await;
|
|
let operations_wire = next_sse_data(&mut operations_stream, &mut operations_buffer).await;
|
|
assert_eq!(
|
|
operations_wire["eventId"],
|
|
operations_second.metadata.event_id
|
|
);
|
|
|
|
let companion_second = companion
|
|
.emit_body(GatewayEventBody::Heartbeat(HeartbeatPayload {
|
|
interval_ms: 1_000,
|
|
}))
|
|
.await;
|
|
drop(companion_stream);
|
|
let mut resumed = open_stream(
|
|
&client,
|
|
&companion.base_url(),
|
|
&companion_token,
|
|
Some(shared_event_id),
|
|
)
|
|
.await;
|
|
let mut resumed_buffer = String::new();
|
|
let replayed = next_sse_data(&mut resumed, &mut resumed_buffer).await;
|
|
assert_eq!(replayed["eventId"], companion_second.metadata.event_id);
|
|
drop(resumed);
|
|
drop(operations_stream);
|
|
|
|
companion.shutdown().await.unwrap();
|
|
operations.shutdown().await.unwrap();
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn duplicate_events_are_emitted_with_the_original_event_id() {
|
|
let gateway = spawn_mock_gateway(MockGatewayConfig::for_test(MockInstanceKind::Companion))
|
|
.await
|
|
.unwrap();
|
|
let client = Client::new();
|
|
let token = login(&client, &gateway.base_url()).await;
|
|
let mut stream = open_stream(&client, &gateway.base_url(), &token, None).await;
|
|
let mut buffer = String::new();
|
|
|
|
let event = gateway
|
|
.emit_body(GatewayEventBody::Heartbeat(HeartbeatPayload {
|
|
interval_ms: 1_000,
|
|
}))
|
|
.await;
|
|
let first = next_sse_data(&mut stream, &mut buffer).await;
|
|
assert!(gateway.replay_event(&event.metadata.event_id).await);
|
|
let duplicate = next_sse_data(&mut stream, &mut buffer).await;
|
|
assert_eq!(first["eventId"], duplicate["eventId"]);
|
|
drop(stream);
|
|
|
|
gateway.shutdown().await.unwrap();
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn rejected_authentication_is_scoped_to_one_instance() {
|
|
let companion = spawn_mock_gateway(MockGatewayConfig::for_test(MockInstanceKind::Companion))
|
|
.await
|
|
.unwrap();
|
|
let operations = spawn_mock_gateway(MockGatewayConfig::for_test(MockInstanceKind::Operations))
|
|
.await
|
|
.unwrap();
|
|
operations.set_auth_mode(mock_gateway::AuthMode::Reject);
|
|
let client = Client::new();
|
|
|
|
let companion_response = login_response(&client, &companion.base_url()).await;
|
|
let operations_response = login_response(&client, &operations.base_url()).await;
|
|
assert!(companion_response.status().is_success());
|
|
assert_eq!(operations_response.status(), StatusCode::UNAUTHORIZED);
|
|
|
|
companion.shutdown().await.unwrap();
|
|
operations.shutdown().await.unwrap();
|
|
}
|
|
|
|
fn event_for(event_id: &str, server_instance_id: &str, sequence: u64) -> GatewayEvent {
|
|
GatewayEvent::new(
|
|
EventMetadata::new(
|
|
event_id,
|
|
server_instance_id,
|
|
"2026-01-01T00:00:00Z",
|
|
sequence,
|
|
),
|
|
GatewayEventBody::Heartbeat(HeartbeatPayload { interval_ms: 1_000 }),
|
|
)
|
|
}
|
|
|
|
fn bind_wire(
|
|
value: Value,
|
|
profile_id: &str,
|
|
slot: ActiveSlotKind,
|
|
expected_server: &str,
|
|
) -> BoundGatewayEvent {
|
|
let raw: RawProtocolEnvelope = serde_json::from_value(value).unwrap();
|
|
BoundGatewayEvent::bind(raw, profile_id, slot, expected_server).unwrap()
|
|
}
|
|
|
|
async fn login(client: &Client, base_url: &str) -> String {
|
|
let response = login_response(client, base_url)
|
|
.await
|
|
.error_for_status()
|
|
.unwrap();
|
|
response
|
|
.json::<AuthLoginResponse>()
|
|
.await
|
|
.unwrap()
|
|
.access_token
|
|
}
|
|
|
|
async fn login_response(client: &Client, base_url: &str) -> Response {
|
|
client
|
|
.post(format!("{base_url}/desktop/v1/auth/login"))
|
|
.json(&AuthLoginRequest {
|
|
client_id: "integration-client".to_owned(),
|
|
device_id: "integration-device".to_owned(),
|
|
credential: Uuid::new_v4().to_string(),
|
|
capabilities: ClientCapabilities {
|
|
protocol_version: PROTOCOL_VERSION.to_owned(),
|
|
app_version: "0.1.0-test".to_owned(),
|
|
platform: "windows".to_owned(),
|
|
features: vec!["events.sse".to_owned()],
|
|
},
|
|
})
|
|
.send()
|
|
.await
|
|
.unwrap()
|
|
}
|
|
|
|
async fn open_stream(
|
|
client: &Client,
|
|
base_url: &str,
|
|
token: &str,
|
|
last_event_id: Option<&str>,
|
|
) -> Response {
|
|
let mut request = client
|
|
.get(format!("{base_url}/desktop/v1/events/stream"))
|
|
.bearer_auth(token);
|
|
if let Some(last_event_id) = last_event_id {
|
|
request = request.header("Last-Event-ID", last_event_id);
|
|
}
|
|
request.send().await.unwrap().error_for_status().unwrap()
|
|
}
|
|
|
|
async fn next_sse_data(response: &mut Response, buffer: &mut String) -> Value {
|
|
timeout(Duration::from_secs(3), async {
|
|
loop {
|
|
while let Some(frame_end) = buffer.find("\n\n") {
|
|
let frame = buffer[..frame_end].to_owned();
|
|
buffer.drain(..frame_end + 2);
|
|
if let Some(data) = frame.lines().find_map(|line| line.strip_prefix("data: ")) {
|
|
return serde_json::from_str(data).unwrap();
|
|
}
|
|
}
|
|
let chunk = response
|
|
.chunk()
|
|
.await
|
|
.unwrap()
|
|
.expect("SSE stream closed before an event arrived");
|
|
buffer.push_str(std::str::from_utf8(&chunk).unwrap());
|
|
}
|
|
})
|
|
.await
|
|
.expect("timed out waiting for SSE data")
|
|
}
|