返回 CodeWhale
remote_pairings.rs
根目录 / crates / app-server / src / runtime_api / remote_pairings.rs
1 use std::net::SocketAddr;
2 use std::time::Instant;
3
4 use axum::Json;
5 use axum::extract::{ConnectInfo, Path, Query, State};
6 use axum::http::{HeaderMap, HeaderValue, Method, StatusCode, header};
7 use axum::response::{IntoResponse, Response};
8 use codewhale_engine::extension_host::{RemoteDenial, RemoteSecret, RemoteState, manager};
9 use serde::{Deserialize, Serialize};
10 use serde_json::json;
11 use tokio_util::sync::CancellationToken;
12
13 use super::mobile::RemoteGrantBinding;
14 use super::{ApiError, RuntimeApiState, auth};
15
16 #[derive(Clone)]
17 pub(super) struct RemoteSessionScope {
18 pub(super) grant: String,
19 pub(super) session_id: String,
20 pub(super) token: RemoteSecret,
21 pub(super) cancel: CancellationToken,
22 pub(super) expires_at: Instant,
23 }
24
25 impl std::fmt::Debug for RemoteSessionScope {
26 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
27 f.debug_struct("RemoteSessionScope")
28 .field("grant", &self.grant)
29 .field("session_id", &self.session_id)
30 .field("token", &"[redacted]")
31 .field("cancelled", &self.cancel.is_cancelled())
32 .field("expires_at", &self.expires_at)
33 .finish()
34 }
35 }
36
37 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
38 pub(super) enum MobileRoute<'a> {
39 StreamTicketRefresh,
40 ThreadsList,
41 ThreadsSummary,
42 ThreadGet(&'a str),
43 ThreadEvents(&'a str),
44 TurnCreate(&'a str),
45 TurnSteer(&'a str),
46 TurnInterrupt(&'a str),
47 Disallowed,
48 }
49
50 impl<'a> MobileRoute<'a> {
51 pub(super) fn thread_id(self) -> Option<&'a str> {
52 match self {
53 Self::ThreadGet(id)
54 | Self::ThreadEvents(id)
55 | Self::TurnCreate(id)
56 | Self::TurnSteer(id)
57 | Self::TurnInterrupt(id) => Some(id),
58 Self::StreamTicketRefresh
59 | Self::ThreadsList
60 | Self::ThreadsSummary
61 | Self::Disallowed => None,
62 }
63 }
64
65 pub(super) fn is_allowed(self) -> bool {
66 !matches!(self, Self::Disallowed)
67 }
68 }
69
70 fn valid_segment(segment: &str) -> bool {
71 let lower = segment.to_ascii_lowercase();
72 !segment.is_empty()
73 && segment != "."
74 && segment != ".."
75 && !segment.contains('\\')
76 && !lower.contains("%2f")
77 && !lower.contains("%5c")
78 }
79
80 pub(super) fn classify_mobile_route<'a>(method: &Method, path: &'a str) -> MobileRoute<'a> {
81 let segments: Vec<&str> = path.split('/').collect();
82 match (method, segments.as_slice()) {
83 (&Method::POST, ["", "__codewhale", "mobile", "stream-ticket"]) => {
84 MobileRoute::StreamTicketRefresh
85 }
86 (&Method::GET, ["", "v1", "threads"]) => MobileRoute::ThreadsList,
87 (&Method::GET, ["", "v1", "threads", "summary"]) => MobileRoute::ThreadsSummary,
88 (&Method::GET, ["", "v1", "threads", id]) if valid_segment(id) => {
89 MobileRoute::ThreadGet(id)
90 }
91 (&Method::GET, ["", "v1", "threads", id, "events"]) if valid_segment(id) => {
92 MobileRoute::ThreadEvents(id)
93 }
94 (&Method::POST, ["", "v1", "threads", id, "turns"]) if valid_segment(id) => {
95 MobileRoute::TurnCreate(id)
96 }
97 (&Method::POST, ["", "v1", "threads", id, "turns", turn_id, "steer"])
98 if valid_segment(id) && valid_segment(turn_id) =>
99 {
100 MobileRoute::TurnSteer(id)
101 }
102 (&Method::POST, ["", "v1", "threads", id, "turns", turn_id, "interrupt"])
103 if valid_segment(id) && valid_segment(turn_id) =>
104 {
105 MobileRoute::TurnInterrupt(id)
106 }
107 _ => MobileRoute::Disallowed,
108 }
109 }
110
111 pub(super) enum GrantAuthOutcome {
112 Allow(RemoteSessionScope),
113 Forbidden,
114 DropAndUnauthorized,
115 }
116
117 pub(super) fn authorize_grant_binding(
118 binding: &RemoteGrantBinding,
119 route: MobileRoute<'_>,
120 ) -> GrantAuthOutcome {
121 if binding.cancel.is_cancelled() || Instant::now() >= binding.expires_at {
122 return GrantAuthOutcome::DropAndUnauthorized;
123 }
124 let target_session = route.thread_id().unwrap_or(&binding.session_id);
125 match manager().authorize_remote_client(binding.token.expose(), target_session) {
126 Ok(_grant) => {
127 if route.is_allowed() {
128 GrantAuthOutcome::Allow(RemoteSessionScope {
129 grant: binding.grant.clone(),
130 session_id: binding.session_id.clone(),
131 token: binding.token.clone(),
132 cancel: binding.cancel.clone(),
133 expires_at: binding.expires_at,
134 })
135 } else {
136 GrantAuthOutcome::Forbidden
137 }
138 }
139 Err(RemoteDenial::ForeignSession) => GrantAuthOutcome::Forbidden,
140 Err(RemoteDenial::Unknown | RemoteDenial::NonLoopback) => {
141 GrantAuthOutcome::DropAndUnauthorized
142 }
143 }
144 }
145
146 pub(super) fn scope_is_live_sync(scope: &RemoteSessionScope) -> bool {
147 !scope.cancel.is_cancelled()
148 && Instant::now() < scope.expires_at
149 && manager()
150 .authorize_remote_client(scope.token.expose(), &scope.session_id)
151 .is_ok()
152 }
153
154 pub(super) async fn scope_is_live(state: &RuntimeApiState, scope: &RemoteSessionScope) -> bool {
155 scope_is_live_sync(scope)
156 && state
157 .runtime_threads
158 .get_thread(&scope.session_id)
159 .await
160 .is_ok_and(|thread| !thread.archived)
161 }
162
163 pub(super) async fn scope_is_live_for_frame(
164 state: &RuntimeApiState,
165 scope: &RemoteSessionScope,
166 frame: &crate::RuntimeOwnerEventFrame,
167 ) -> bool {
168 if !scope_is_live_sync(scope) {
169 return false;
170 }
171 if matches!(
172 frame.event.as_str(),
173 "approval.grant_revoked" | "thread.updated" | "thread.deleted"
174 ) {
175 return state
176 .runtime_threads
177 .get_thread(&scope.session_id)
178 .await
179 .is_ok_and(|thread| !thread.archived);
180 }
181 true
182 }
183
184 pub(super) fn evict_scope(state: &RuntimeApiState, scope: &RemoteSessionScope) {
185 scope.cancel.cancel();
186 if let Some(mobile) = state.mobile.as_ref() {
187 mobile.revoke_grant(&scope.grant);
188 }
189 }
190
191 #[derive(Serialize)]
192 pub(super) struct RemotePairingItem {
193 grant: String,
194 plugin_id: String,
195 plugin_name: String,
196 session_id: String,
197 state: &'static str,
198 plugin_label: String,
199 client_label: Option<String>,
200 expires_in_seconds: u64,
201 }
202
203 fn pairing_state_name(state: RemoteState) -> &'static str {
204 match state {
205 RemoteState::AwaitingHost => "awaiting_host",
206 RemoteState::Paired => "paired",
207 }
208 }
209
210 fn unknown_grant_response() -> Response {
211 (
212 StatusCode::NOT_FOUND,
213 Json(json!({
214 "error": {
215 "message": "not found",
216 "status": StatusCode::NOT_FOUND.as_u16(),
217 }
218 })),
219 )
220 .into_response()
221 }
222
223 pub(super) async fn list_pairings() -> Response {
224 let items: Vec<RemotePairingItem> = manager()
225 .remote_pairings()
226 .into_iter()
227 .map(|row| RemotePairingItem {
228 grant: row.grant,
229 plugin_id: row.plugin_id,
230 plugin_name: row.plugin_name,
231 session_id: row.session_id,
232 state: pairing_state_name(row.state),
233 plugin_label: row.plugin_label,
234 client_label: row.client_label,
235 expires_in_seconds: row.expires_in_seconds,
236 })
237 .collect();
238 (
239 StatusCode::OK,
240 [(header::CACHE_CONTROL, HeaderValue::from_static("no-store"))],
241 Json(items),
242 )
243 .into_response()
244 }
245
246 pub(super) async fn present_pairing(
247 State(state): State<RuntimeApiState>,
248 Path(grant): Path<String>,
249 ) -> Response {
250 if state.mobile.is_none() {
251 return ApiError::conflict("mobile control is disabled").into_response();
252 }
253 let Some(row) = manager()
254 .remote_pairings()
255 .into_iter()
256 .find(|item| item.grant == grant)
257 else {
258 return unknown_grant_response();
259 };
260 if row.state != RemoteState::AwaitingHost {
261 return unknown_grant_response();
262 }
263 match state.runtime_threads.get_thread(&row.session_id).await {
264 Ok(thread) if !thread.archived => {}
265 Ok(_) | Err(_) => {
266 return ApiError::conflict("pairing conversation is not available over Runtime HTTP")
267 .into_response();
268 }
269 }
270 let Ok(secret) = manager().present_remote_pairing(&grant) else {
271 return unknown_grant_response();
272 };
273 let origin = auth::runtime_http_origin(&state);
274 let url = format!("{origin}/__codewhale/mobile/pair/{}", secret.expose());
275 (
276 StatusCode::OK,
277 [(header::CACHE_CONTROL, HeaderValue::from_static("no-store"))],
278 Json(json!({
279 "grant": grant,
280 "url": url,
281 "expires_in_seconds": row.expires_in_seconds,
282 })),
283 )
284 .into_response()
285 }
286
287 pub(super) async fn withdraw_pairing(
288 State(state): State<RuntimeApiState>,
289 Path(grant): Path<String>,
290 ) -> Response {
291 let _ = manager().withdraw_remote_grant(&grant);
292 if let Some(mobile) = state.mobile.as_ref() {
293 mobile.revoke_grant(&grant);
294 }
295 StatusCode::NO_CONTENT.into_response()
296 }
297
298 #[derive(Deserialize)]
299 pub(super) struct RedeemPairingQuery {
300 label: Option<String>,
301 }
302
303 pub(super) async fn redeem_pairing(
304 State(state): State<RuntimeApiState>,
305 ConnectInfo(peer): ConnectInfo<SocketAddr>,
306 Path(secret): Path<String>,
307 headers: HeaderMap,
308 Query(query): Query<RedeemPairingQuery>,
309 ) -> Response {
310 let Some(mobile_state) = state.mobile.as_ref() else {
311 return super::mobile_not_found();
312 };
313 let header_label = headers
314 .get(header::USER_AGENT)
315 .and_then(|value| value.to_str().ok())
316 .map(str::trim)
317 .filter(|value| !value.is_empty());
318 let client_label = query
319 .label
320 .as_deref()
321 .map(str::trim)
322 .filter(|value| !value.is_empty())
323 .or(header_label)
324 .unwrap_or("Mobile browser");
325
326 let client = match manager().redeem_remote_pairing(&secret, client_label, peer.ip()) {
327 Ok(client) => client,
328 Err(RemoteDenial::NonLoopback) => {
329 return super::secured_mobile_text(StatusCode::FORBIDDEN, "bootstrap unavailable");
330 }
331 Err(RemoteDenial::Unknown | RemoteDenial::ForeignSession) => {
332 return super::secured_mobile_text(StatusCode::UNAUTHORIZED, "bootstrap unavailable");
333 }
334 };
335
336 let session = mobile_state.issue_grant_session(
337 client.grant,
338 client.session_id,
339 client.token,
340 client.expires_in_seconds,
341 );
342 super::mobile_redirect_response(session)
343 }
344
344 lines RUST