返回 CodeWhale
auth.rs
1 use axum::Json;
2 use axum::extract::{Request, State};
3 use axum::http::{Method, StatusCode, header};
4 use axum::middleware::Next;
5 use axum::response::{IntoResponse, Response};
6 use codewhale_core::secret_eq::constant_time_eq;
7 use serde_json::json;
8
9 use super::{RuntimeApiState, mobile, remote_pairings, web};
10
11 #[derive(Debug, Clone, PartialEq, Eq)]
12 pub(super) struct ResolvedRuntimeAuth {
13 pub(super) token: Option<String>,
14 pub(super) generated: bool,
15 }
16
17 pub(super) fn resolve_runtime_auth(
18 cli_token: Option<String>,
19 env_token: Option<String>,
20 insecure_no_auth: bool,
21 ) -> ResolvedRuntimeAuth {
22 if let Some(token) = first_nonblank_token(cli_token).or_else(|| first_nonblank_token(env_token))
23 {
24 return ResolvedRuntimeAuth {
25 token: Some(token),
26 generated: false,
27 };
28 }
29 if insecure_no_auth {
30 return ResolvedRuntimeAuth {
31 token: None,
32 generated: false,
33 };
34 }
35 ResolvedRuntimeAuth {
36 token: Some(generate_runtime_token()),
37 generated: true,
38 }
39 }
40
41 pub(super) fn runtime_auth_status_lines(auth: &ResolvedRuntimeAuth) -> Vec<String> {
42 if auth.generated {
43 return vec![
44 "Runtime API auth: generated bearer token for this process (not printed).".to_string(),
45 " Set CODEWHALE_RUNTIME_TOKEN (or DEEPSEEK_RUNTIME_TOKEN as an alias) when another client needs to connect.".to_string(),
46 ];
47 }
48 if auth.token.is_some() {
49 return vec!["Runtime API auth: bearer token required for /v1/* routes.".to_string()];
50 }
51 vec!["Runtime API auth: disabled by explicit insecure mode.".to_string()]
52 }
53
54 fn first_nonblank_token(token: Option<String>) -> Option<String> {
55 token
56 .map(|token| token.trim().to_string())
57 .filter(|token| !token.is_empty())
58 }
59
60 fn generate_runtime_token() -> String {
61 format!(
62 "cwrt_{}{}",
63 uuid::Uuid::new_v4().simple(),
64 uuid::Uuid::new_v4().simple()
65 )
66 }
67
68 pub(super) async fn require_host_token(
69 State(state): State<RuntimeApiState>,
70 req: Request,
71 next: Next,
72 ) -> Response {
73 if state
74 .runtime_token
75 .as_deref()
76 .is_some_and(|master| request_has_header_runtime_token(&req, master))
77 {
78 next.run(req).await
79 } else {
80 runtime_token_required_response()
81 }
82 }
83
84 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
85 pub(super) enum RuntimeAuthCaller {
86 MasterOrLocal,
87 DeviceClient,
88 WebSession,
89 MobileSession,
90 }
91
92 pub(super) enum RuntimeAuthDecision {
93 Allow(Option<remote_pairings::RemoteSessionScope>),
94 Forbidden(&'static str),
95 Unauthorized,
96 }
97
98 enum RuntimeAuthOutcome {
99 Allow {
100 caller: RuntimeAuthCaller,
101 scope: Option<remote_pairings::RemoteSessionScope>,
102 },
103 Forbidden(&'static str),
104 Unauthorized,
105 }
106
107 pub(super) async fn require_runtime_token(
108 State(state): State<RuntimeApiState>,
109 mut req: Request,
110 next: Next,
111 ) -> Response {
112 match authorize_runtime_request(&req, &state) {
113 RuntimeAuthOutcome::Allow { caller, scope } => {
114 req.extensions_mut().insert(caller);
115 if let Some(scope) = scope {
116 req.extensions_mut().insert(scope);
117 }
118 next.run(req).await
119 }
120 RuntimeAuthOutcome::Forbidden(message) => {
121 (StatusCode::FORBIDDEN, Json(json!({"error": message}))).into_response()
122 }
123 RuntimeAuthOutcome::Unauthorized => runtime_token_required_response(),
124 }
125 }
126
127 pub(super) fn runtime_request_is_authorized(req: &Request, state: &RuntimeApiState) -> bool {
128 matches!(
129 authorize_runtime_request(req, state),
130 RuntimeAuthOutcome::Allow { .. }
131 )
132 }
133
134 fn authorize_runtime_request(req: &Request, state: &RuntimeApiState) -> RuntimeAuthOutcome {
135 if let Some(expected) = state.runtime_token.as_deref()
136 && request_has_header_runtime_token(req, expected)
137 {
138 return RuntimeAuthOutcome::Allow {
139 caller: RuntimeAuthCaller::MasterOrLocal,
140 scope: None,
141 };
142 }
143 // Device tokens carry their immutable mint intent. Watch permits HTTP
144 // reads only; an upgraded GET could otherwise become a write channel.
145 // Computer display/control routes enforce intent in their own handlers.
146 if let Some(principal) =
147 request_bearer(req).and_then(|token| state.computer.client_principal(token))
148 {
149 return if client_request_is_authorized(&principal, req) {
150 RuntimeAuthOutcome::Allow {
151 caller: RuntimeAuthCaller::DeviceClient,
152 scope: None,
153 }
154 } else {
155 RuntimeAuthOutcome::Forbidden("watch client tokens cannot change Runtime state")
156 };
157 }
158 if state
159 .web
160 .as_ref()
161 .is_some_and(|web| web_session_request_is_authorized(req, state, web))
162 {
163 return RuntimeAuthOutcome::Allow {
164 caller: RuntimeAuthCaller::WebSession,
165 scope: None,
166 };
167 }
168 if let Some(mobile) = state.mobile.as_ref() {
169 match mobile_session_request_is_authorized(req, state, mobile) {
170 RuntimeAuthDecision::Allow(scope) => {
171 return RuntimeAuthOutcome::Allow {
172 caller: RuntimeAuthCaller::MobileSession,
173 scope,
174 };
175 }
176 RuntimeAuthDecision::Forbidden(message) => {
177 return RuntimeAuthOutcome::Forbidden(message);
178 }
179 RuntimeAuthDecision::Unauthorized => {}
180 }
181 }
182 if state.runtime_token.is_none() && !request_has_any_credential(req) {
183 RuntimeAuthOutcome::Allow {
184 caller: RuntimeAuthCaller::MasterOrLocal,
185 scope: None,
186 }
187 } else {
188 RuntimeAuthOutcome::Unauthorized
189 }
190 }
191
192 fn request_has_any_credential(req: &Request) -> bool {
193 let has_header_token = req.headers().contains_key(header::AUTHORIZATION)
194 || req.headers().contains_key("x-codewhale-runtime-token")
195 || req.headers().contains_key("x-deepseek-runtime-token");
196 let has_session_cookie = req.headers().get_all(header::COOKIE).iter().any(|value| {
197 let Ok(cookie) = value.to_str() else {
198 return true;
199 };
200 mobile::cookie_value(Some(cookie), web::WEB_SESSION_COOKIE_NAME).is_some()
201 || mobile::cookie_value(Some(cookie), mobile::MOBILE_SESSION_COOKIE_NAME).is_some()
202 });
203 let has_web = req.headers().contains_key(web::WEB_REQUEST_HEADER)
204 || request_has_query_key(req, web::WEB_STREAM_TICKET_QUERY);
205 let has_mobile = req.headers().contains_key(mobile::MOBILE_REQUEST_HEADER)
206 || request_has_query_key(req, mobile::MOBILE_STREAM_TICKET_QUERY);
207 has_header_token || has_session_cookie || has_web || has_mobile
208 }
209
210 fn request_has_query_key(req: &Request, query_key: &str) -> bool {
211 req.uri().query().is_some_and(|query| {
212 query
213 .split('&')
214 .any(|pair| pair.split_once('=').map_or(pair, |(key, _)| key) == query_key)
215 })
216 }
217
218 fn client_request_is_authorized(
219 principal: &super::computer_display::Principal,
220 req: &Request,
221 ) -> bool {
222 principal.can_drive()
223 || (matches!(*req.method(), Method::GET | Method::HEAD)
224 && !req.headers().contains_key(header::UPGRADE)
225 && !req.headers().contains_key("sec-websocket-key"))
226 }
227
228 fn request_bearer(req: &Request) -> Option<&str> {
229 req.headers()
230 .get(header::AUTHORIZATION)
231 .and_then(|value| value.to_str().ok())
232 .and_then(|raw| raw.strip_prefix("Bearer "))
233 .or_else(|| {
234 req.headers()
235 .get("x-codewhale-runtime-token")
236 .and_then(|value| value.to_str().ok())
237 })
238 }
239
240 pub(super) fn request_has_header_runtime_token(req: &Request, expected: &str) -> bool {
241 headers_have_runtime_token(req.headers(), expected)
242 }
243
244 pub(super) fn headers_have_runtime_token(headers: &axum::http::HeaderMap, expected: &str) -> bool {
245 headers
246 .get(header::AUTHORIZATION)
247 .and_then(|value| value.to_str().ok())
248 .and_then(|raw| raw.strip_prefix("Bearer "))
249 .is_some_and(|token| constant_time_eq(token.as_bytes(), expected.as_bytes()))
250 || headers
251 .get("x-codewhale-runtime-token")
252 .and_then(|value| value.to_str().ok())
253 .is_some_and(|token| constant_time_eq(token.as_bytes(), expected.as_bytes()))
254 || headers
255 .get("x-deepseek-runtime-token")
256 .and_then(|value| value.to_str().ok())
257 .is_some_and(|token| constant_time_eq(token.as_bytes(), expected.as_bytes()))
258 }
259
260 /// Web fetches require a cookie and an origin-scoped proof; streams consume
261 /// a single-use ticket instead. Origin metadata is an additional check only.
262 pub(super) fn web_session_request_is_authorized(
263 req: &Request,
264 state: &RuntimeApiState,
265 web: &web::RuntimeWebState,
266 ) -> bool {
267 web_request_is_authorized(req, &runtime_http_origin(state), web)
268 }
269
270 fn web_request_is_authorized(
271 req: &Request,
272 expected_origin: &str,
273 web: &web::RuntimeWebState,
274 ) -> bool {
275 if req
276 .headers()
277 .get("sec-fetch-site")
278 .is_some_and(|value| value != "same-origin")
279 || req
280 .headers()
281 .get(header::ORIGIN)
282 .is_some_and(|value| value != expected_origin)
283 {
284 return false;
285 }
286 let cookie = req
287 .headers()
288 .get(header::COOKIE)
289 .and_then(|value| value.to_str().ok());
290 if is_thread_stream_request(req) {
291 return web.consume_stream_ticket(cookie, stream_ticket(req, web::WEB_STREAM_TICKET_QUERY));
292 }
293 web.matches_request(
294 cookie,
295 req.headers()
296 .get(web::WEB_REQUEST_HEADER)
297 .and_then(|value| value.to_str().ok()),
298 )
299 }
300
301 /// Mobile cookies are host-scoped and can be attached to a sibling loopback
302 /// port. A cookie alone is therefore never Runtime authority: normal fetches
303 /// must also present an origin-scoped proof and EventSource requests must
304 /// consume a short-lived stream ticket. The origin/Fetch Metadata check keeps
305 /// a sibling port from replaying a captured value.
306 pub(super) fn mobile_session_request_is_authorized(
307 req: &Request,
308 state: &RuntimeApiState,
309 mobile_state: &mobile::RuntimeMobileState,
310 ) -> RuntimeAuthDecision {
311 if !mobile_cookie_request_is_same_origin(req, state) {
312 return RuntimeAuthDecision::Unauthorized;
313 }
314 let cookie_header = req
315 .headers()
316 .get(header::COOKIE)
317 .and_then(|value| value.to_str().ok());
318 if is_thread_stream_request(req) {
319 let ticket = stream_ticket(req, mobile::MOBILE_STREAM_TICKET_QUERY);
320 let Some(grant_binding) = mobile_state.peek_stream_ticket(cookie_header, ticket) else {
321 return RuntimeAuthDecision::Unauthorized;
322 };
323 if let Some(binding) = grant_binding {
324 let route = remote_pairings::classify_mobile_route(req.method(), req.uri().path());
325 return match remote_pairings::authorize_grant_binding(&binding, route) {
326 remote_pairings::GrantAuthOutcome::Allow(scope) => {
327 if mobile_state.consume_stream_ticket(cookie_header, ticket) {
328 RuntimeAuthDecision::Allow(Some(scope))
329 } else {
330 RuntimeAuthDecision::Unauthorized
331 }
332 }
333 remote_pairings::GrantAuthOutcome::Forbidden => {
334 RuntimeAuthDecision::Forbidden("paired device cannot access this route")
335 }
336 remote_pairings::GrantAuthOutcome::DropAndUnauthorized => {
337 mobile_state.remove_session_by_cookie(cookie_header);
338 RuntimeAuthDecision::Unauthorized
339 }
340 };
341 }
342 return if mobile_state.consume_stream_ticket(cookie_header, ticket) {
343 RuntimeAuthDecision::Allow(None)
344 } else {
345 RuntimeAuthDecision::Unauthorized
346 };
347 }
348 let request_proof = req
349 .headers()
350 .get(mobile::MOBILE_REQUEST_HEADER)
351 .and_then(|value| value.to_str().ok());
352 let Some(grant_binding) = mobile_state.authorize_proof(cookie_header, request_proof) else {
353 return RuntimeAuthDecision::Unauthorized;
354 };
355 if let Some(binding) = grant_binding {
356 let route = remote_pairings::classify_mobile_route(req.method(), req.uri().path());
357 return match remote_pairings::authorize_grant_binding(&binding, route) {
358 remote_pairings::GrantAuthOutcome::Allow(scope) => {
359 RuntimeAuthDecision::Allow(Some(scope))
360 }
361 remote_pairings::GrantAuthOutcome::Forbidden => {
362 RuntimeAuthDecision::Forbidden("paired device cannot access this route")
363 }
364 remote_pairings::GrantAuthOutcome::DropAndUnauthorized => {
365 mobile_state.remove_session_by_cookie(cookie_header);
366 RuntimeAuthDecision::Unauthorized
367 }
368 };
369 }
370 RuntimeAuthDecision::Allow(None)
371 }
372
373 fn mobile_cookie_request_is_same_origin(req: &Request, state: &RuntimeApiState) -> bool {
374 let fetch_metadata_is_same_origin = req
375 .headers()
376 .get("sec-fetch-site")
377 .and_then(|value| value.to_str().ok())
378 .is_some_and(|site| site.eq_ignore_ascii_case("same-origin"));
379 if req
380 .headers()
381 .get("sec-fetch-site")
382 .and_then(|value| value.to_str().ok())
383 .is_some_and(|site| !site.eq_ignore_ascii_case("same-origin"))
384 {
385 return false;
386 }
387
388 match req
389 .headers()
390 .get(header::ORIGIN)
391 .and_then(|value| value.to_str().ok())
392 {
393 Some(origin) => origin == runtime_http_origin(state),
394 None => fetch_metadata_is_same_origin,
395 }
396 }
397
398 pub(super) fn runtime_http_origin(state: &RuntimeApiState) -> String {
399 runtime_http_origin_for_bind(&state.bind_host, state.bind_port)
400 }
401
402 fn runtime_http_origin_for_bind(bind_host: &str, bind_port: u16) -> String {
403 let host = match bind_host.parse::<std::net::IpAddr>() {
404 Ok(std::net::IpAddr::V4(address)) => address.to_string(),
405 Ok(std::net::IpAddr::V6(address)) => format!("[{address}]"),
406 Err(_) => bind_host.to_string(),
407 };
408 if bind_port == 80 {
409 format!("http://{host}")
410 } else {
411 format!("http://{host}:{bind_port}")
412 }
413 }
414
415 fn is_thread_stream_request(req: &Request) -> bool {
416 req.method() == Method::GET
417 && req.uri().path().starts_with("/v1/threads/")
418 && req.uri().path().ends_with("/events")
419 }
420
421 fn stream_ticket<'a>(req: &'a Request, query_key: &str) -> Option<&'a str> {
422 let mut tickets = req
423 .uri()
424 .query()?
425 .split('&')
426 .filter_map(|pair| pair.split_once('='))
427 .filter_map(|(key, value)| (key == query_key).then_some(value));
428 let ticket = tickets.next()?;
429 tickets.next().is_none().then_some(ticket)
430 }
431
432 pub(super) fn runtime_token_required_response() -> Response {
433 (
434 StatusCode::UNAUTHORIZED,
435 Json(json!({
436 "error": {
437 "message": "runtime API bearer token required",
438 "status": StatusCode::UNAUTHORIZED.as_u16(),
439 }
440 })),
441 )
442 .into_response()
443 }
444
445 pub(super) async fn require_runtime_master_bearer(
446 State(state): State<RuntimeApiState>,
447 req: Request,
448 next: Next,
449 ) -> Response {
450 let Some(expected) = state.runtime_token.as_deref() else {
451 return (
452 StatusCode::CONFLICT,
453 Json(json!({"error": "Master bearer routes require configured Runtime bearer authentication"})),
454 )
455 .into_response();
456 };
457 let authorized = req
458 .headers()
459 .get(header::AUTHORIZATION)
460 .and_then(|value| value.to_str().ok())
461 .and_then(|value| value.strip_prefix("Bearer "))
462 .is_some_and(|presented| constant_time_eq(presented.as_bytes(), expected.as_bytes()));
463 if authorized {
464 next.run(req).await
465 } else {
466 (
467 StatusCode::FORBIDDEN,
468 Json(json!({"error": "This route requires the master Authorization bearer"})),
469 )
470 .into_response()
471 }
472 }
473
474 #[cfg(test)]
475 mod tests {
476 use super::runtime_http_origin_for_bind;
477
478 #[test]
479 fn runtime_surface_hardening_web_requests_require_proof() {
480 use super::*;
481 use axum::body::Body;
482 let (web, nonce) = web::RuntimeWebState::new();
483 let (token, proof) = web.consume(&nonce, "127.0.0.1".parse().unwrap()).unwrap();
484 let cookie = format!("codewhale_web_session={token}");
485 let origin = "http://127.0.0.1:7878";
486 let request = |method: Method, path: &str, proof: Option<&str>, metadata: bool| {
487 let mut builder = Request::builder()
488 .method(method)
489 .uri(path)
490 .header(header::COOKIE, &cookie);
491 if metadata {
492 builder = builder
493 .header(header::ORIGIN, origin)
494 .header("sec-fetch-site", "same-origin");
495 }
496 if let Some(proof) = proof {
497 builder = builder.header(web::WEB_REQUEST_HEADER, proof);
498 }
499 builder.body(Body::empty()).unwrap()
500 };
501 for method in [Method::GET, Method::POST, Method::HEAD, Method::OPTIONS] {
502 for metadata in [false, true] {
503 for presented in [None, Some("wrong-proof")] {
504 assert!(!web_request_is_authorized(
505 &request(method.clone(), "/v1/threads", presented, metadata),
506 origin,
507 &web
508 ));
509 }
510 assert!(web_request_is_authorized(
511 &request(method.clone(), "/v1/threads", Some(&proof), metadata),
512 origin,
513 &web
514 ));
515 }
516 }
517 let mut wrong_origin = request(Method::POST, "/v1/threads", Some(&proof), true);
518 wrong_origin
519 .headers_mut()
520 .insert(header::ORIGIN, "http://127.0.0.1:3000".parse().unwrap());
521 assert!(!web_request_is_authorized(&wrong_origin, origin, &web));
522 let mut cross_site = request(Method::GET, "/v1/threads", Some(&proof), true);
523 cross_site
524 .headers_mut()
525 .insert("sec-fetch-site", "same-site".parse().unwrap());
526 assert!(!web_request_is_authorized(&cross_site, origin, &web));
527
528 assert!(web.refresh_stream_ticket(Some(&cookie), None).is_none());
529 let ticket = web
530 .refresh_stream_ticket(Some(&cookie), Some(&proof))
531 .unwrap();
532 let path = format!("/v1/threads/thread-1/events?web_stream_ticket={ticket}");
533 assert!(!web_request_is_authorized(
534 &request(
535 Method::GET,
536 "/v1/threads/thread-1/events",
537 Some(&proof),
538 true
539 ),
540 origin,
541 &web
542 ));
543 assert!(!web_request_is_authorized(
544 &request(
545 Method::GET,
546 &format!("{path}&web_stream_ticket=extra"),
547 None,
548 true
549 ),
550 origin,
551 &web
552 ));
553 assert!(web_request_is_authorized(
554 &request(Method::GET, &path, None, true),
555 origin,
556 &web
557 ));
558 assert!(!web_request_is_authorized(
559 &request(Method::GET, &path, None, true),
560 origin,
561 &web
562 ));
563 }
564
565 #[test]
566 fn expected_origin_canonicalizes_ipv6_loopback_literals() {
567 assert_eq!(
568 runtime_http_origin_for_bind("0:0:0:0:0:0:0:1", 7878),
569 "http://[::1]:7878"
570 );
571 assert_eq!(runtime_http_origin_for_bind("::1", 80), "http://[::1]");
572 }
573 }
574
574 lines RUST