返回 CodeWhale
mobile.rs
根目录 / crates / app-server / src / runtime_api / mobile.rs
1 //! Origin-bound browser session support for the loopback mobile control page.
2 //!
3 //! The Runtime bearer is deliberately never represented by these values. A
4 //! one-time terminal bootstrap (or an explicit bearer header at the session
5 //! endpoint) creates an opaque, process-local HttpOnly cookie plus browser
6 //! proofs held in origin-scoped session storage. The cookie is host scoped by
7 //! HTTP semantics and therefore can reach sibling ports; the proofs cannot.
8
9 use codewhale_core::secret_eq::constant_time_eq;
10 use std::collections::HashMap;
11 use std::net::{IpAddr, SocketAddr};
12 use std::sync::{Arc, Mutex};
13 use std::time::{Duration, Instant};
14
15 use tokio_util::sync::CancellationToken;
16 use uuid::Uuid;
17
18 pub(super) const MOBILE_SESSION_COOKIE_NAME: &str = "codewhale_mobile_session";
19 pub(super) const MOBILE_REQUEST_HEADER: &str = "x-codewhale-mobile-request";
20 pub(super) const MOBILE_STREAM_TICKET_QUERY: &str = "mobile_stream_ticket";
21 pub(super) const BOOTSTRAP_TTL: Duration = Duration::from_secs(10 * 60);
22 pub(super) const SESSION_TTL: Duration = Duration::from_secs(30 * 60);
23 pub(super) const STREAM_TICKET_TTL: Duration = Duration::from_secs(5 * 60);
24
25 const BOOTSTRAP_PREFIX: &str = "cwmb_";
26 const SESSION_PREFIX: &str = "cwms_";
27 const REQUEST_PREFIX: &str = "cwmr_";
28 const STREAM_PREFIX: &str = "cwmt_";
29 const STREAM_TICKET_PENDING_LIMIT: usize = 32;
30
31 #[derive(Clone)]
32 pub(super) struct RuntimeMobileState {
33 bootstrap: Arc<Mutex<Option<BootstrapCapability>>>,
34 sessions: Arc<Mutex<HashMap<String, MobileSession>>>,
35 session_ttl: Duration,
36 stream_ticket_ttl: Duration,
37 }
38
39 struct BootstrapCapability {
40 nonce: String,
41 expires_at: Instant,
42 }
43
44 #[derive(Clone)]
45 pub(super) struct RemoteGrantBinding {
46 pub(super) grant: String,
47 pub(super) session_id: String,
48 pub(super) token: codewhale_engine::extension_host::RemoteSecret,
49 pub(super) cancel: CancellationToken,
50 pub(super) expires_at: Instant,
51 }
52
53 impl std::fmt::Debug for RemoteGrantBinding {
54 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
55 f.debug_struct("RemoteGrantBinding")
56 .field("grant", &self.grant)
57 .field("session_id", &self.session_id)
58 .field("token", &"[redacted]")
59 .field("cancelled", &self.cancel.is_cancelled())
60 .field("expires_at", &self.expires_at)
61 .finish()
62 }
63 }
64
65 struct MobileSession {
66 request_proof: String,
67 stream_tickets: Vec<BootstrapCapability>,
68 expires_at: Instant,
69 cancel: CancellationToken,
70 remote_grant: Option<RemoteGrantBinding>,
71 }
72
73 impl std::fmt::Debug for MobileSession {
74 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
75 f.debug_struct("MobileSession")
76 .field("request_proof", &"[redacted]")
77 .field("stream_tickets", &self.stream_tickets.len())
78 .field("expires_at", &self.expires_at)
79 .field("cancelled", &self.cancel.is_cancelled())
80 .field("remote_grant", &self.remote_grant)
81 .finish()
82 }
83 }
84
85 #[derive(Clone)]
86 pub(super) struct MobileSessionBootstrap {
87 pub(super) session_cookie: String,
88 pub(super) request_proof: String,
89 pub(super) stream_ticket: String,
90 pub(super) session_ttl_seconds: u64,
91 pub(super) stream_ticket_ttl_seconds: u64,
92 }
93
94 impl std::fmt::Debug for MobileSessionBootstrap {
95 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
96 f.debug_struct("MobileSessionBootstrap")
97 .field("session_cookie", &"[redacted]")
98 .field("request_proof", &"[redacted]")
99 .field("stream_ticket", &"[redacted]")
100 .field("session_ttl_seconds", &self.session_ttl_seconds)
101 .field("stream_ticket_ttl_seconds", &self.stream_ticket_ttl_seconds)
102 .finish()
103 }
104 }
105
106 #[derive(Clone)]
107 pub(super) struct MobileStreamTicket {
108 pub(super) ticket: String,
109 pub(super) expires_in_seconds: u64,
110 }
111
112 impl std::fmt::Debug for MobileStreamTicket {
113 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
114 f.debug_struct("MobileStreamTicket")
115 .field("ticket", &"[redacted]")
116 .field("expires_in_seconds", &self.expires_in_seconds)
117 .finish()
118 }
119 }
120
121 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
122 pub(super) enum BootstrapError {
123 Invalid,
124 Expired,
125 NonLoopback,
126 }
127
128 impl RuntimeMobileState {
129 pub(super) fn new() -> (Self, String) {
130 Self::new_with_ttls(BOOTSTRAP_TTL, SESSION_TTL, STREAM_TICKET_TTL)
131 }
132
133 pub(super) fn new_with_ttls(
134 bootstrap_ttl: Duration,
135 session_ttl: Duration,
136 stream_ticket_ttl: Duration,
137 ) -> (Self, String) {
138 let nonce = random_capability(BOOTSTRAP_PREFIX);
139 let state = Self {
140 bootstrap: Arc::new(Mutex::new(Some(BootstrapCapability {
141 nonce: nonce.clone(),
142 expires_at: Instant::now() + bootstrap_ttl,
143 }))),
144 sessions: Arc::new(Mutex::new(HashMap::new())),
145 session_ttl,
146 stream_ticket_ttl,
147 };
148 (state, nonce)
149 }
150
151 /// Consume the terminal bootstrap once, only from a loopback peer.
152 pub(super) fn consume_bootstrap(
153 &self,
154 nonce: &str,
155 peer_ip: IpAddr,
156 ) -> Result<MobileSessionBootstrap, BootstrapError> {
157 if !peer_ip.is_loopback() {
158 return Err(BootstrapError::NonLoopback);
159 }
160 if !valid_bootstrap_nonce(nonce) {
161 return Err(BootstrapError::Invalid);
162 }
163
164 let mut slot = self
165 .bootstrap
166 .lock()
167 .unwrap_or_else(|poisoned| poisoned.into_inner());
168 let Some(capability) = slot.as_ref() else {
169 return Err(BootstrapError::Invalid);
170 };
171 if Instant::now() >= capability.expires_at {
172 *slot = None;
173 return Err(BootstrapError::Expired);
174 }
175 if !constant_time_eq(nonce.as_bytes(), capability.nonce.as_bytes()) {
176 return Err(BootstrapError::Invalid);
177 }
178 let _capability = slot.take().expect("bootstrap capability checked above");
179 drop(slot);
180
181 Ok(self.issue_session())
182 }
183
184 /// Create an opaque mobile browser session after explicit bearer proof.
185 pub(super) fn issue_session(&self) -> MobileSessionBootstrap {
186 self.issue_session_with(None, None)
187 }
188
189 pub(super) fn issue_grant_session(
190 &self,
191 grant: String,
192 session_id: String,
193 token: codewhale_engine::extension_host::RemoteSecret,
194 client_expires_in_seconds: u64,
195 ) -> MobileSessionBootstrap {
196 self.issue_session_with(
197 Some((grant, session_id, token)),
198 Some(Duration::from_secs(client_expires_in_seconds)),
199 )
200 }
201
202 fn issue_session_with(
203 &self,
204 remote_grant: Option<(
205 String,
206 String,
207 codewhale_engine::extension_host::RemoteSecret,
208 )>,
209 max_ttl: Option<Duration>,
210 ) -> MobileSessionBootstrap {
211 let session_cookie = random_capability(SESSION_PREFIX);
212 let request_proof = random_capability(REQUEST_PREFIX);
213 let stream_ticket = random_capability(STREAM_PREFIX);
214 let effective_session_ttl =
215 max_ttl.map_or(self.session_ttl, |limit| self.session_ttl.min(limit));
216 let effective_ticket_ttl = self.stream_ticket_ttl.min(effective_session_ttl);
217 let now = Instant::now();
218 let expires_at = now + effective_session_ttl;
219 let cancel = CancellationToken::new();
220 let remote_grant = remote_grant.map(|(grant, session_id, token)| RemoteGrantBinding {
221 grant,
222 session_id,
223 token,
224 cancel: cancel.clone(),
225 expires_at,
226 });
227 let mut sessions = self
228 .sessions
229 .lock()
230 .unwrap_or_else(|poisoned| poisoned.into_inner());
231 retain_live_sessions(&mut sessions, now);
232 if effective_session_ttl > Duration::ZERO {
233 sessions.insert(
234 session_cookie.clone(),
235 MobileSession {
236 request_proof: request_proof.clone(),
237 stream_tickets: vec![BootstrapCapability {
238 nonce: stream_ticket.clone(),
239 expires_at: now + effective_ticket_ttl,
240 }],
241 expires_at,
242 cancel,
243 remote_grant,
244 },
245 );
246 }
247 MobileSessionBootstrap {
248 session_cookie,
249 request_proof,
250 stream_ticket,
251 session_ttl_seconds: effective_session_ttl.as_secs(),
252 stream_ticket_ttl_seconds: effective_ticket_ttl.as_secs(),
253 }
254 }
255
256 pub(super) fn authorize_proof(
257 &self,
258 cookie_header: Option<&str>,
259 request_proof: Option<&str>,
260 ) -> Option<Option<RemoteGrantBinding>> {
261 let session_cookie = cookie_value(cookie_header, MOBILE_SESSION_COOKIE_NAME)?;
262 let request_proof = request_proof?;
263 let now = Instant::now();
264 let mut sessions = self
265 .sessions
266 .lock()
267 .unwrap_or_else(|poisoned| poisoned.into_inner());
268 retain_live_sessions(&mut sessions, now);
269 let session = sessions.get(session_cookie)?;
270 constant_time_eq(request_proof.as_bytes(), session.request_proof.as_bytes())
271 .then(|| session.remote_grant.clone())
272 }
273
274 #[cfg(test)]
275 pub(super) fn matches_request(
276 &self,
277 cookie_header: Option<&str>,
278 request_proof: Option<&str>,
279 ) -> bool {
280 self.authorize_proof(cookie_header, request_proof).is_some()
281 }
282
283 pub(super) fn peek_stream_ticket(
284 &self,
285 cookie_header: Option<&str>,
286 stream_ticket: Option<&str>,
287 ) -> Option<Option<RemoteGrantBinding>> {
288 let session_cookie = cookie_value(cookie_header, MOBILE_SESSION_COOKIE_NAME)?;
289 let stream_ticket = stream_ticket?;
290 let now = Instant::now();
291 let mut sessions = self
292 .sessions
293 .lock()
294 .unwrap_or_else(|poisoned| poisoned.into_inner());
295 retain_live_sessions(&mut sessions, now);
296 let session = sessions.get_mut(session_cookie)?;
297 session
298 .stream_tickets
299 .retain(|issued| now < issued.expires_at);
300 let matches = session
301 .stream_tickets
302 .iter()
303 .any(|issued| constant_time_eq(stream_ticket.as_bytes(), issued.nonce.as_bytes()));
304 matches.then(|| session.remote_grant.clone())
305 }
306
307 /// Consume a short-lived stream ticket. A reconnect must mint a fresh one
308 /// through the cookie-plus-request-proof endpoint.
309 pub(super) fn consume_stream_ticket(
310 &self,
311 cookie_header: Option<&str>,
312 stream_ticket: Option<&str>,
313 ) -> bool {
314 let Some(session_cookie) = cookie_value(cookie_header, MOBILE_SESSION_COOKIE_NAME) else {
315 return false;
316 };
317 let Some(stream_ticket) = stream_ticket else {
318 return false;
319 };
320 let now = Instant::now();
321 let mut sessions = self
322 .sessions
323 .lock()
324 .unwrap_or_else(|poisoned| poisoned.into_inner());
325 retain_live_sessions(&mut sessions, now);
326 let Some(session) = sessions.get_mut(session_cookie) else {
327 return false;
328 };
329 session
330 .stream_tickets
331 .retain(|issued| now < issued.expires_at);
332 let Some(index) = session
333 .stream_tickets
334 .iter()
335 .position(|issued| constant_time_eq(stream_ticket.as_bytes(), issued.nonce.as_bytes()))
336 else {
337 return false;
338 };
339 session.stream_tickets.remove(index);
340 true
341 }
342
343 pub(super) fn remove_session_by_cookie(&self, cookie_header: Option<&str>) -> bool {
344 let Some(session_cookie) = cookie_value(cookie_header, MOBILE_SESSION_COOKIE_NAME) else {
345 return false;
346 };
347 let mut sessions = self
348 .sessions
349 .lock()
350 .unwrap_or_else(|poisoned| poisoned.into_inner());
351 let Some(removed) = sessions.remove(session_cookie) else {
352 return false;
353 };
354 removed.cancel.cancel();
355 true
356 }
357
358 fn revoke_grant_sessions(&self, predicate: impl Fn(&RemoteGrantBinding) -> bool) -> usize {
359 let mut sessions = self
360 .sessions
361 .lock()
362 .unwrap_or_else(|poisoned| poisoned.into_inner());
363 let mut revoked = 0;
364 sessions.retain(|_, session| {
365 if session.remote_grant.as_ref().is_some_and(&predicate) {
366 session.cancel.cancel();
367 revoked += 1;
368 false
369 } else {
370 true
371 }
372 });
373 revoked
374 }
375
376 pub(super) fn revoke_grant(&self, grant: &str) -> usize {
377 self.revoke_grant_sessions(|binding| binding.grant == grant)
378 }
379
380 pub(super) fn revoke_remote_session(&self, session_id: &str) -> usize {
381 self.revoke_grant_sessions(|binding| binding.session_id == session_id)
382 }
383
384 /// Mint a new single-use stream ticket after a normal origin-bound request.
385 pub(super) fn refresh_stream_ticket(
386 &self,
387 cookie_header: Option<&str>,
388 request_proof: Option<&str>,
389 ) -> Option<MobileStreamTicket> {
390 let session_cookie = cookie_value(cookie_header, MOBILE_SESSION_COOKIE_NAME)?;
391 let request_proof = request_proof?;
392 let now = Instant::now();
393 let mut sessions = self
394 .sessions
395 .lock()
396 .unwrap_or_else(|poisoned| poisoned.into_inner());
397 retain_live_sessions(&mut sessions, now);
398 let session = sessions.get_mut(session_cookie)?;
399 if !constant_time_eq(request_proof.as_bytes(), session.request_proof.as_bytes()) {
400 return None;
401 }
402 let ticket = random_capability(STREAM_PREFIX);
403 let ticket_ttl = self
404 .stream_ticket_ttl
405 .min(session.expires_at.saturating_duration_since(now));
406 session
407 .stream_tickets
408 .retain(|issued| now < issued.expires_at);
409 if session.stream_tickets.len() == STREAM_TICKET_PENDING_LIMIT {
410 session.stream_tickets.remove(0);
411 }
412 session.stream_tickets.push(BootstrapCapability {
413 nonce: ticket.clone(),
414 expires_at: now + ticket_ttl,
415 });
416 Some(MobileStreamTicket {
417 ticket,
418 expires_in_seconds: ticket_ttl.as_secs(),
419 })
420 }
421 }
422
423 pub(super) fn bootstrap_url(addr: SocketAddr, nonce: &str) -> String {
424 format!("http://{addr}/__codewhale/mobile/bootstrap/{nonce}")
425 }
426
427 pub(super) fn mobile_session_cookie_with_max_age(
428 session_cookie: &str,
429 max_age_seconds: u64,
430 ) -> String {
431 format!(
432 "{MOBILE_SESSION_COOKIE_NAME}={session_cookie}; Max-Age={max_age_seconds}; HttpOnly; SameSite=Strict; Path=/"
433 )
434 }
435
436 #[cfg(test)]
437 pub(super) fn mobile_session_cookie(session_cookie: &str) -> String {
438 mobile_session_cookie_with_max_age(session_cookie, SESSION_TTL.as_secs())
439 }
440
441 fn retain_live_sessions(sessions: &mut HashMap<String, MobileSession>, now: Instant) {
442 sessions.retain(|_, session| {
443 if session.expires_at > now {
444 true
445 } else {
446 session.cancel.cancel();
447 false
448 }
449 });
450 }
451
452 fn random_capability(prefix: &str) -> String {
453 format!(
454 "{prefix}{}{}",
455 Uuid::new_v4().simple(),
456 Uuid::new_v4().simple()
457 )
458 }
459
460 pub(super) fn cookie_value<'a>(cookie_header: Option<&'a str>, name: &str) -> Option<&'a str> {
461 cookie_header.and_then(|cookie| {
462 cookie.split(';').find_map(|pair| {
463 let (key, value) = pair.trim().split_once('=')?;
464 (key == name).then_some(value.trim())
465 })
466 })
467 }
468
469 fn valid_bootstrap_nonce(value: &str) -> bool {
470 value.strip_prefix(BOOTSTRAP_PREFIX).is_some_and(|random| {
471 random.len() == 64 && random.bytes().all(|byte| byte.is_ascii_hexdigit())
472 })
473 }
474
475 #[cfg(test)]
476 mod tests {
477 use super::*;
478
479 #[test]
480 fn bootstrap_is_loopback_only_one_time_and_yields_no_runtime_bearer() {
481 let (state, nonce) = RuntimeMobileState::new_with_ttls(
482 Duration::from_secs(60),
483 Duration::from_secs(60),
484 Duration::from_secs(60),
485 );
486 assert!(matches!(
487 state.consume_bootstrap(&nonce, "192.0.2.4".parse().unwrap()),
488 Err(BootstrapError::NonLoopback)
489 ));
490 let session = state
491 .consume_bootstrap(&nonce, "127.0.0.1".parse().unwrap())
492 .expect("valid loopback bootstrap");
493 assert!(session.session_cookie.starts_with(SESSION_PREFIX));
494 assert!(session.request_proof.starts_with(REQUEST_PREFIX));
495 assert!(session.stream_ticket.starts_with(STREAM_PREFIX));
496 assert_ne!(session.session_cookie, session.request_proof);
497 assert!(matches!(
498 state.consume_bootstrap(&nonce, "127.0.0.1".parse().unwrap()),
499 Err(BootstrapError::Invalid)
500 ));
501 }
502
503 #[test]
504 fn session_requires_origin_scoped_proof_and_stream_tickets_are_single_use() {
505 let (state, _nonce) = RuntimeMobileState::new_with_ttls(
506 Duration::from_secs(60),
507 Duration::from_secs(60),
508 Duration::from_secs(60),
509 );
510 let session = state.issue_session();
511 let cookie = format!("{MOBILE_SESSION_COOKIE_NAME}={}", session.session_cookie);
512 assert!(!state.matches_request(Some(&cookie), None));
513 assert!(!state.matches_request(Some(&cookie), Some("wrong-proof")));
514 assert!(state.matches_request(Some(&cookie), Some(&session.request_proof)));
515 assert!(state.consume_stream_ticket(Some(&cookie), Some(&session.stream_ticket)));
516 assert!(
517 !state.consume_stream_ticket(Some(&cookie), Some(&session.stream_ticket)),
518 "a captured EventSource URL cannot be replayed"
519 );
520
521 let replacement = state
522 .refresh_stream_ticket(Some(&cookie), Some(&session.request_proof))
523 .expect("valid browser request can mint one replacement");
524 assert!(state.consume_stream_ticket(Some(&cookie), Some(&replacement.ticket)));
525 }
526
527 #[test]
528 fn refreshed_stream_tickets_coexist_within_one_session() {
529 let (state, _nonce) = RuntimeMobileState::new_with_ttls(
530 Duration::from_secs(60),
531 Duration::from_secs(60),
532 Duration::from_secs(60),
533 );
534 let session = state.issue_session();
535 let cookie = format!("{MOBILE_SESSION_COOKIE_NAME}={}", session.session_cookie);
536 let first = state
537 .refresh_stream_ticket(Some(&cookie), Some(&session.request_proof))
538 .expect("first refresh");
539 let second = state
540 .refresh_stream_ticket(Some(&cookie), Some(&session.request_proof))
541 .expect("second refresh");
542 assert_ne!(first.ticket, second.ticket);
543 assert!(
544 state.consume_stream_ticket(Some(&cookie), Some(&first.ticket)),
545 "a second refresh must not evict the ticket a reconnect already holds"
546 );
547 assert!(state.consume_stream_ticket(Some(&cookie), Some(&second.ticket)));
548 assert!(
549 !state.consume_stream_ticket(Some(&cookie), Some(&second.ticket)),
550 "each ticket stays single-use"
551 );
552 }
553
554 #[test]
555 fn cookie_has_exact_security_attributes_and_no_domain() {
556 let session_cookie = format!("{SESSION_PREFIX}{}", "01".repeat(32));
557 let cookie = mobile_session_cookie(&session_cookie);
558 assert_eq!(
559 cookie,
560 format!(
561 "{MOBILE_SESSION_COOKIE_NAME}={session_cookie}; Max-Age=1800; HttpOnly; SameSite=Strict; Path=/"
562 )
563 );
564 assert!(!cookie.contains("Domain="));
565 assert!(!cookie.contains("cwrt_"));
566 }
567
568 #[test]
569 fn launcher_url_contains_only_the_one_time_capability() {
570 let nonce = format!("{BOOTSTRAP_PREFIX}{}", "01".repeat(32));
571 let url = bootstrap_url("127.0.0.1:7878".parse().unwrap(), &nonce);
572 assert!(url.ends_with(&nonce));
573 assert!(!url.contains('?'));
574 assert!(!url.contains('#'));
575 assert!(!url.contains("cwrt_"));
576 }
577
578 #[test]
579 fn debug_formatting_redacts_session_secrets() {
580 let (state, _nonce) = RuntimeMobileState::new_with_ttls(
581 Duration::from_secs(60),
582 Duration::from_secs(60),
583 Duration::from_secs(30),
584 );
585 let bootstrap = state.issue_session();
586 let cookie = format!("{MOBILE_SESSION_COOKIE_NAME}={}", bootstrap.session_cookie);
587 let bootstrap_debug = format!("{bootstrap:?}");
588 assert!(!bootstrap_debug.contains(&bootstrap.session_cookie));
589 assert!(!bootstrap_debug.contains(&bootstrap.request_proof));
590 assert!(!bootstrap_debug.contains(&bootstrap.stream_ticket));
591
592 let ticket = state
593 .refresh_stream_ticket(Some(&cookie), Some(&bootstrap.request_proof))
594 .expect("refresh ticket");
595 let ticket_debug = format!("{ticket:?}");
596 assert!(!ticket_debug.contains(&ticket.ticket));
597
598 assert!(state.remove_session_by_cookie(Some(&cookie)));
599 assert!(!state.matches_request(Some(&cookie), Some(&bootstrap.request_proof)));
600 }
601 }
602
602 lines RUST