| 1 | //! Account preferences enter the existing Engine history once per turn, and |
| 2 | //! the account a person's turn was admitted under fences that turn's calls to |
| 3 | //! the desktop side browser. |
| 4 | //! |
| 5 | //! Known limitations of the fence: it compares the local account store only, |
| 6 | //! so account states the desktop keeps to itself are not seen; it sends the |
| 7 | //! browser server no caller identity; it cannot order browser registrations; |
| 8 | //! and a turn awaits its capture, an off-runtime read of the local account |
| 9 | //! store, with no deadline and no Stop, before the bounded account profile |
| 10 | //! wait. |
| 11 | use anyhow::{Context, Result, ensure}; |
| 12 | use codewhale_config::user_constitution::ProfileConstitutionSnapshot; |
| 13 | use codewhale_secrets::account::{ |
| 14 | AccountSessionSnapshot, AccountSessionState, AccountSessionStore, |
| 15 | secure_account_session_secrets, |
| 16 | }; |
| 17 | |
| 18 | const DESKTOP_BROWSER_SERVER: &str = "codewhale-browser"; |
| 19 | const ACCOUNT_LOAD_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5); |
| 20 | pub(crate) const TURN_WAIT: std::time::Duration = std::time::Duration::from_secs(1); |
| 21 | |
| 22 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 23 | pub struct AccountEpoch { |
| 24 | api_base: String, |
| 25 | state: AccountSessionState, |
| 26 | account_id: Option<String>, |
| 27 | session_id: Option<String>, |
| 28 | signed_out_revision: Option<String>, |
| 29 | } |
| 30 | |
| 31 | pub fn account_epoch(profile: Option<&str>) -> Result<AccountEpoch> { |
| 32 | let api_base = runtime_account_api_base(); |
| 33 | #[cfg(any(test, feature = "test-support"))] |
| 34 | if !account_api_base_is_loopback() { |
| 35 | return Ok(AccountEpoch { |
| 36 | api_base, |
| 37 | state: AccountSessionState::SignedOut, |
| 38 | account_id: None, |
| 39 | session_id: None, |
| 40 | signed_out_revision: None, |
| 41 | }); |
| 42 | } |
| 43 | epoch_of( |
| 44 | &AccountSessionStore::new(secure_account_session_secrets()?, profile, &api_base) |
| 45 | .snapshot()?, |
| 46 | ) |
| 47 | } |
| 48 | |
| 49 | fn epoch_of(snapshot: &AccountSessionSnapshot) -> Result<AccountEpoch> { |
| 50 | let info = snapshot.runtime_info_at(chrono::Utc::now())?; |
| 51 | let state = match info.state { |
| 52 | AccountSessionState::OfflineCached => AccountSessionState::Authenticated, |
| 53 | state => state, |
| 54 | }; |
| 55 | let signed_out_revision = (state == AccountSessionState::SignedOut && !snapshot.is_pristine()) |
| 56 | .then(|| snapshot.fingerprint()); |
| 57 | Ok(AccountEpoch { |
| 58 | api_base: info.api_base, |
| 59 | state, |
| 60 | account_id: info.account_id, |
| 61 | session_id: info.session_id, |
| 62 | signed_out_revision, |
| 63 | }) |
| 64 | } |
| 65 | |
| 66 | #[derive(Debug)] |
| 67 | pub struct AccountFence { |
| 68 | profile: Option<String>, |
| 69 | admitted: Option<AccountEpoch>, |
| 70 | } |
| 71 | |
| 72 | impl AccountFence { |
| 73 | pub async fn capture(profile: Option<&str>) -> Self { |
| 74 | let profile = profile.map(str::to_owned); |
| 75 | let admitted = read_account_epoch(profile.clone()).await; |
| 76 | Self { profile, admitted } |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | async fn read_account_epoch(profile: Option<String>) -> Option<AccountEpoch> { |
| 81 | #[cfg(any(test, feature = "test-support"))] |
| 82 | if let Some(seam) = TEST_ACCOUNT_EPOCH.with(|cell| cell.borrow().clone()) { |
| 83 | return seam; |
| 84 | } |
| 85 | #[cfg(any(test, feature = "test-support"))] |
| 86 | if let Some((store, ..)) = TEST_ACCOUNT_SOURCE.with(|cell| cell.borrow().clone()) { |
| 87 | return store |
| 88 | .snapshot() |
| 89 | .ok() |
| 90 | .and_then(|snapshot| epoch_of(&snapshot).ok()); |
| 91 | } |
| 92 | tokio::task::spawn_blocking(move || account_epoch(profile.as_deref())) |
| 93 | .await |
| 94 | .ok()? |
| 95 | .ok() |
| 96 | } |
| 97 | |
| 98 | pub async fn admit_desktop_browser_call( |
| 99 | name: &str, |
| 100 | fence: Option<&AccountFence>, |
| 101 | ) -> Result<(), crate::tools::spec::ToolError> { |
| 102 | use crate::tools::spec::ToolError; |
| 103 | if !name.starts_with(&crate::mcp::McpPool::mcp_model_tool_name( |
| 104 | DESKTOP_BROWSER_SERVER, |
| 105 | "", |
| 106 | )) { |
| 107 | return Ok(()); |
| 108 | } |
| 109 | let Some((fence, Some(admitted))) = fence.map(|fence| (fence, fence.admitted.as_ref())) else { |
| 110 | return Err(ToolError::permission_denied( |
| 111 | "Codewhale could not confirm which account started this turn, so nothing was sent to the side browser.", |
| 112 | )); |
| 113 | }; |
| 114 | match read_account_epoch(fence.profile.clone()).await { |
| 115 | Some(current) if current == *admitted => Ok(()), |
| 116 | Some(_) => Err(ToolError::permission_denied( |
| 117 | "The signed-in Codewhale account changed after this turn started, so nothing was sent to the side browser. Ask again in a new turn.", |
| 118 | )), |
| 119 | None => Err(ToolError::permission_denied( |
| 120 | "Codewhale could not confirm the signed-in account, so nothing was sent to the side browser.", |
| 121 | )), |
| 122 | } |
| 123 | } |
| 124 | |
| 125 | /// No cached cross-account fallback. An unavailable or malformed signed-in |
| 126 | /// profile is an error here; interactive turn admission (`Engine`) then uses the |
| 127 | /// signed-out local constitution and tells the person once, because local use |
| 128 | /// with their own provider key never requires a Codewhale sign-in. A |
| 129 | /// host-supplied snapshot (Runtime API) still fails its turn closed. |
| 130 | pub async fn load(profile: Option<&str>) -> Result<Option<ProfileConstitutionSnapshot>> { |
| 131 | load_for(profile, None).await |
| 132 | } |
| 133 | |
| 134 | async fn load_for( |
| 135 | profile: Option<&str>, |
| 136 | expected: Option<&AccountEpoch>, |
| 137 | ) -> Result<Option<ProfileConstitutionSnapshot>> { |
| 138 | let api_base = runtime_account_api_base(); |
| 139 | let profile = profile.map(str::to_owned); |
| 140 | let base = api_base.clone(); |
| 141 | let store = tokio::task::spawn_blocking(move || { |
| 142 | anyhow::Ok(AccountSessionStore::new( |
| 143 | secure_account_session_secrets()?, |
| 144 | profile.as_deref(), |
| 145 | &base, |
| 146 | )) |
| 147 | }) |
| 148 | .await??; |
| 149 | load_from(&store, &api_base, expected).await |
| 150 | } |
| 151 | |
| 152 | async fn off_runtime<T: Send + 'static>( |
| 153 | store: &AccountSessionStore, |
| 154 | operation: impl FnOnce(&AccountSessionStore) -> Result<T> + Send + 'static, |
| 155 | ) -> Result<T> { |
| 156 | let store = store.clone(); |
| 157 | tokio::task::spawn_blocking(move || operation(&store)).await? |
| 158 | } |
| 159 | |
| 160 | /// Offline preview cannot promise a request hash before account admission. |
| 161 | pub fn account_is_present(profile: Option<&str>) -> Result<bool> { |
| 162 | #[cfg(any(test, feature = "test-support"))] |
| 163 | { |
| 164 | let _ = profile; |
| 165 | Ok(false) |
| 166 | } |
| 167 | #[cfg(not(any(test, feature = "test-support")))] |
| 168 | { |
| 169 | let base = runtime_account_api_base(); |
| 170 | Ok( |
| 171 | AccountSessionStore::new(secure_account_session_secrets()?, profile, &base) |
| 172 | .load()? |
| 173 | .is_some(), |
| 174 | ) |
| 175 | } |
| 176 | } |
| 177 | |
| 178 | pub fn runtime_account_api_base() -> String { |
| 179 | std::env::var(codewhale_secrets::account::ACCOUNT_API_BASE_ENV) |
| 180 | .ok() |
| 181 | .and_then(|value| normalize_runtime_account_api_base(&value)) |
| 182 | .unwrap_or_else(|| codewhale_secrets::account::DEFAULT_ACCOUNT_API_BASE.to_string()) |
| 183 | } |
| 184 | |
| 185 | pub fn normalize_runtime_account_api_base(value: &str) -> Option<String> { |
| 186 | let mut url = reqwest::Url::parse(value.trim()).ok()?; |
| 187 | if !url.username().is_empty() |
| 188 | || url.password().is_some() |
| 189 | || url.query().is_some() |
| 190 | || url.fragment().is_some() |
| 191 | || !matches!(url.path(), "" | "/") |
| 192 | { |
| 193 | return None; |
| 194 | } |
| 195 | let host = url.host_str()?; |
| 196 | let loopback = host.eq_ignore_ascii_case("localhost") |
| 197 | || host |
| 198 | .trim_start_matches('[') |
| 199 | .trim_end_matches(']') |
| 200 | .parse::<std::net::IpAddr>() |
| 201 | .is_ok_and(|address| address.is_loopback()); |
| 202 | if url.scheme() != "https" && !(url.scheme() == "http" && loopback) { |
| 203 | return None; |
| 204 | } |
| 205 | url.set_path("/"); |
| 206 | Some(url.as_str().trim_end_matches('/').to_string()) |
| 207 | } |
| 208 | |
| 209 | async fn load_from( |
| 210 | store: &AccountSessionStore, |
| 211 | api_base: &str, |
| 212 | expected: Option<&AccountEpoch>, |
| 213 | ) -> Result<Option<ProfileConstitutionSnapshot>> { |
| 214 | let captured = off_runtime(store, |store| Ok(store.snapshot()?)).await?; |
| 215 | if let Some(expected) = expected { |
| 216 | ensure!( |
| 217 | epoch_of(&captured)? == *expected, |
| 218 | "The signed-in account changed while loading its constitution; retry" |
| 219 | ); |
| 220 | } |
| 221 | let Some(auth) = captured.load()? else { |
| 222 | return Ok(None); |
| 223 | }; |
| 224 | let account = auth |
| 225 | .bundle |
| 226 | .user |
| 227 | .as_ref() |
| 228 | .map(|user| user.id.as_str()) |
| 229 | .filter(|id| !id.is_empty()) |
| 230 | .context("Sign in again to load your profile constitution")?; |
| 231 | let client = tokio::task::spawn_blocking(|| { |
| 232 | crate::platform_client_builder() |
| 233 | .redirect(reqwest::redirect::Policy::none()) |
| 234 | .timeout(ACCOUNT_LOAD_TIMEOUT) |
| 235 | .build() |
| 236 | }) |
| 237 | .await??; |
| 238 | let response = client |
| 239 | .get(format!("{api_base}/api/me")) |
| 240 | .bearer_auth(&auth.bundle.access_token) |
| 241 | .send() |
| 242 | .await |
| 243 | .context("Your profile could not be loaded; retry when the account service is reachable")?; |
| 244 | ensure!( |
| 245 | response.status().is_success(), |
| 246 | "Your profile could not be loaded (HTTP {}). Sign in again or retry", |
| 247 | response.status().as_u16() |
| 248 | ); |
| 249 | let bytes = codewhale_util::utils::read_response_body_capped(response, 256 * 1024).await?; |
| 250 | let value: serde_json::Value = |
| 251 | serde_json::from_slice(&bytes).context("The account profile response is invalid")?; |
| 252 | let unchanged = off_runtime(store, move |store| { |
| 253 | store.with_transaction(|current| Ok::<_, anyhow::Error>(current.matches(&captured))) |
| 254 | }) |
| 255 | .await?; |
| 256 | ensure!( |
| 257 | unchanged, |
| 258 | "The signed-in account changed while loading its constitution; retry" |
| 259 | ); |
| 260 | snapshot_from_me(value, account) |
| 261 | } |
| 262 | |
| 263 | pub fn snapshot_from_me( |
| 264 | value: serde_json::Value, |
| 265 | account: &str, |
| 266 | ) -> Result<Option<ProfileConstitutionSnapshot>> { |
| 267 | let user = value |
| 268 | .get("user") |
| 269 | .context("The account profile response is missing")?; |
| 270 | ensure!( |
| 271 | user.get("id").and_then(|id| id.as_str()) == Some(account), |
| 272 | "The profile belongs to a different account" |
| 273 | ); |
| 274 | let document = user |
| 275 | .get("preferences") |
| 276 | .and_then(|preferences| preferences.get("constitution")); |
| 277 | let snapshot = ProfileConstitutionSnapshot { |
| 278 | account_id: account.to_owned(), |
| 279 | revision: user |
| 280 | .get("settingsRevision") |
| 281 | .and_then(|revision| revision.as_u64()) |
| 282 | .context("The profile constitution has no valid revision")?, |
| 283 | constitution: document |
| 284 | .map(|value| serde_json::from_value(value.clone())) |
| 285 | .transpose() |
| 286 | .context("The profile constitution is invalid; review it in account settings")? |
| 287 | .unwrap_or_default(), |
| 288 | }; |
| 289 | snapshot.validate()?; |
| 290 | Ok(Some(snapshot)) |
| 291 | } |
| 292 | |
| 293 | type Loaded = Result<Option<ProfileConstitutionSnapshot>, String>; |
| 294 | |
| 295 | pub enum AccountRead { |
| 296 | Ready(Result<Option<String>, String>), |
| 297 | Pending { |
| 298 | last: Option<String>, |
| 299 | signed_in: bool, |
| 300 | }, |
| 301 | } |
| 302 | |
| 303 | #[derive(Default)] |
| 304 | pub struct AccountConstitution { |
| 305 | last: Option<(AccountEpoch, ProfileConstitutionSnapshot)>, |
| 306 | failure: Option<(AccountEpoch, String)>, |
| 307 | pending: Option<(AccountEpoch, tokio::task::JoinHandle<Loaded>)>, |
| 308 | } |
| 309 | |
| 310 | impl AccountConstitution { |
| 311 | pub async fn capture( |
| 312 | &mut self, |
| 313 | profile: Option<&str>, |
| 314 | fence: Option<&AccountFence>, |
| 315 | cancel: &tokio_util::sync::CancellationToken, |
| 316 | ) -> AccountRead { |
| 317 | let key = fence.and_then(|fence| fence.admitted.clone()); |
| 318 | let expected = key.clone(); |
| 319 | #[cfg(any(test, feature = "test-support"))] |
| 320 | { |
| 321 | if let Some(message) = TEST_ACCOUNT_LOAD_FAILURE.get() { |
| 322 | return AccountRead::Ready(Err(message.to_owned())); |
| 323 | } |
| 324 | if let Some((store, api_base, wait)) = |
| 325 | TEST_ACCOUNT_SOURCE.with(|cell| cell.borrow().clone()) |
| 326 | { |
| 327 | return self |
| 328 | .capture_with(key, cancel, wait, async move { |
| 329 | load_from(&store, &api_base, expected.as_ref()) |
| 330 | .await |
| 331 | .map_err(|error| error.to_string()) |
| 332 | }) |
| 333 | .await; |
| 334 | } |
| 335 | if !account_api_base_is_loopback() { |
| 336 | return AccountRead::Ready(Ok(crate::prompts::load_user_constitution_block())); |
| 337 | } |
| 338 | } |
| 339 | let profile = profile.map(str::to_owned); |
| 340 | self.capture_with(key, cancel, TURN_WAIT, async move { |
| 341 | load_for(profile.as_deref(), expected.as_ref()) |
| 342 | .await |
| 343 | .map_err(|error| error.to_string()) |
| 344 | }) |
| 345 | .await |
| 346 | } |
| 347 | |
| 348 | async fn capture_with<F>( |
| 349 | &mut self, |
| 350 | key: Option<AccountEpoch>, |
| 351 | cancel: &tokio_util::sync::CancellationToken, |
| 352 | wait: std::time::Duration, |
| 353 | read: F, |
| 354 | ) -> AccountRead |
| 355 | where |
| 356 | F: std::future::Future<Output = Loaded> + Send + 'static, |
| 357 | { |
| 358 | let current = |epoch: &AccountEpoch| Some(epoch) == key.as_ref(); |
| 359 | if !self.last.as_ref().is_some_and(|(epoch, _)| current(epoch)) { |
| 360 | self.last = None; |
| 361 | } |
| 362 | if !self |
| 363 | .failure |
| 364 | .as_ref() |
| 365 | .is_some_and(|(epoch, _)| current(epoch)) |
| 366 | { |
| 367 | self.failure = None; |
| 368 | } |
| 369 | let in_flight = match self.pending.take() { |
| 370 | Some((epoch, handle)) if current(&epoch) && !handle.is_finished() => Some(handle), |
| 371 | Some((epoch, handle)) if current(&epoch) => { |
| 372 | self.adopt( |
| 373 | epoch, |
| 374 | handle.await.unwrap_or_else(|error| Err(error.to_string())), |
| 375 | ); |
| 376 | None |
| 377 | } |
| 378 | Some((_, handle)) => { |
| 379 | handle.abort(); |
| 380 | None |
| 381 | } |
| 382 | None => None, |
| 383 | }; |
| 384 | let mut handle = in_flight.unwrap_or_else(|| tokio::spawn(read)); |
| 385 | let wait = if self.failure.is_some() { |
| 386 | std::time::Duration::ZERO |
| 387 | } else { |
| 388 | wait |
| 389 | }; |
| 390 | tokio::select! { |
| 391 | biased; |
| 392 | () = cancel.cancelled() => {} |
| 393 | joined = &mut handle => { |
| 394 | let loaded = joined.unwrap_or_else(|error| Err(error.to_string())); |
| 395 | if let Some(epoch) = key { |
| 396 | self.adopt(epoch, loaded.clone()); |
| 397 | } |
| 398 | return AccountRead::Ready(rendered(loaded)); |
| 399 | } |
| 400 | () = tokio::time::sleep(wait) => {} |
| 401 | } |
| 402 | let signed_in = key |
| 403 | .as_ref() |
| 404 | .is_some_and(|epoch| epoch.state != AccountSessionState::SignedOut); |
| 405 | match key { |
| 406 | Some(epoch) => self.pending = Some((epoch, handle)), |
| 407 | None => handle.abort(), |
| 408 | } |
| 409 | if let Some((_, error)) = &self.failure { |
| 410 | return AccountRead::Ready(Err(error.clone())); |
| 411 | } |
| 412 | AccountRead::Pending { |
| 413 | last: self |
| 414 | .last |
| 415 | .as_ref() |
| 416 | .and_then(|(_, snapshot)| snapshot.render().ok()), |
| 417 | signed_in, |
| 418 | } |
| 419 | } |
| 420 | |
| 421 | #[cfg(test)] |
| 422 | pub(crate) fn read_in_flight(&self) -> bool { |
| 423 | self.pending |
| 424 | .as_ref() |
| 425 | .is_some_and(|(_, handle)| !handle.is_finished()) |
| 426 | } |
| 427 | |
| 428 | fn adopt(&mut self, epoch: AccountEpoch, loaded: Loaded) { |
| 429 | match loaded { |
| 430 | Ok(snapshot) => { |
| 431 | self.failure = None; |
| 432 | self.last = snapshot.map(|snapshot| (epoch, snapshot)); |
| 433 | } |
| 434 | Err(error) => self.failure = Some((epoch, error)), |
| 435 | } |
| 436 | } |
| 437 | } |
| 438 | |
| 439 | impl Drop for AccountConstitution { |
| 440 | fn drop(&mut self) { |
| 441 | if let Some((_, handle)) = self.pending.take() { |
| 442 | handle.abort(); |
| 443 | } |
| 444 | } |
| 445 | } |
| 446 | |
| 447 | fn rendered(loaded: Loaded) -> Result<Option<String>, String> { |
| 448 | match loaded? { |
| 449 | Some(snapshot) => snapshot |
| 450 | .render() |
| 451 | .map(Some) |
| 452 | .map_err(|error| error.to_string()), |
| 453 | None => Ok(crate::prompts::load_user_constitution_block()), |
| 454 | } |
| 455 | } |
| 456 | |
| 457 | #[cfg(any(test, feature = "test-support"))] |
| 458 | fn account_api_base_is_loopback() -> bool { |
| 459 | std::env::var(codewhale_secrets::account::ACCOUNT_API_BASE_ENV) |
| 460 | .ok() |
| 461 | .and_then(|value| normalize_runtime_account_api_base(&value)) |
| 462 | .and_then(|base| reqwest::Url::parse(&base).ok()) |
| 463 | .and_then(|url| url.host_str().map(str::to_owned)) |
| 464 | .is_some_and(|host| { |
| 465 | host.eq_ignore_ascii_case("localhost") |
| 466 | || host |
| 467 | .trim_start_matches('[') |
| 468 | .trim_end_matches(']') |
| 469 | .parse::<std::net::IpAddr>() |
| 470 | .is_ok_and(|address| address.is_loopback()) |
| 471 | }) |
| 472 | } |
| 473 | |
| 474 | #[cfg(any(test, feature = "test-support"))] |
| 475 | thread_local! { |
| 476 | static TEST_ACCOUNT_LOAD_FAILURE: std::cell::Cell<Option<&'static str>> = |
| 477 | const { std::cell::Cell::new(None) }; |
| 478 | } |
| 479 | |
| 480 | /// Make the account profile that `AccountConstitution::capture` would load itself fail on this |
| 481 | /// thread until the guard drops, as an expired sign-in or unreachable account |
| 482 | /// service does in a real build. A supplied snapshot never reaches it. |
| 483 | #[cfg(any(test, feature = "test-support"))] |
| 484 | pub fn fail_account_load_for_test(message: &'static str) -> AccountLoadFailureGuard { |
| 485 | TEST_ACCOUNT_LOAD_FAILURE.set(Some(message)); |
| 486 | AccountLoadFailureGuard |
| 487 | } |
| 488 | |
| 489 | #[cfg(any(test, feature = "test-support"))] |
| 490 | thread_local! { |
| 491 | static TEST_ACCOUNT_EPOCH: std::cell::RefCell<Option<Option<AccountEpoch>>> = |
| 492 | const { std::cell::RefCell::new(None) }; |
| 493 | } |
| 494 | |
| 495 | #[cfg(any(test, feature = "test-support"))] |
| 496 | pub fn pin_account_epoch_for_test(account_id: Option<&str>) -> AccountEpochGuard { |
| 497 | let guard = AccountEpochGuard; |
| 498 | guard.set(account_id); |
| 499 | guard |
| 500 | } |
| 501 | |
| 502 | #[cfg(any(test, feature = "test-support"))] |
| 503 | pub struct AccountEpochGuard; |
| 504 | |
| 505 | #[cfg(any(test, feature = "test-support"))] |
| 506 | impl AccountEpochGuard { |
| 507 | pub fn set(&self, account_id: Option<&str>) { |
| 508 | let epoch = account_id.map(|id| AccountEpoch { |
| 509 | api_base: runtime_account_api_base(), |
| 510 | state: AccountSessionState::Authenticated, |
| 511 | account_id: Some(id.to_owned()), |
| 512 | session_id: Some(format!("session_{id}")), |
| 513 | signed_out_revision: None, |
| 514 | }); |
| 515 | TEST_ACCOUNT_EPOCH.with(|cell| *cell.borrow_mut() = Some(epoch)); |
| 516 | } |
| 517 | } |
| 518 | |
| 519 | #[cfg(any(test, feature = "test-support"))] |
| 520 | impl Drop for AccountEpochGuard { |
| 521 | fn drop(&mut self) { |
| 522 | TEST_ACCOUNT_EPOCH.with(|cell| *cell.borrow_mut() = None); |
| 523 | } |
| 524 | } |
| 525 | |
| 526 | #[cfg(any(test, feature = "test-support"))] |
| 527 | thread_local! { |
| 528 | static TEST_ACCOUNT_SOURCE: std::cell::RefCell< |
| 529 | Option<(AccountSessionStore, String, std::time::Duration)>, |
| 530 | > = const { std::cell::RefCell::new(None) }; |
| 531 | } |
| 532 | |
| 533 | /// Serve this thread's turns the signed-in account in `store`, read from |
| 534 | /// `api_base` through the real profile load, waiting at most `wait` per turn. |
| 535 | #[cfg(any(test, feature = "test-support"))] |
| 536 | pub fn serve_account_for_test( |
| 537 | store: AccountSessionStore, |
| 538 | api_base: String, |
| 539 | wait: std::time::Duration, |
| 540 | ) -> AccountSourceGuard { |
| 541 | TEST_ACCOUNT_SOURCE.with(|cell| *cell.borrow_mut() = Some((store, api_base, wait))); |
| 542 | AccountSourceGuard |
| 543 | } |
| 544 | |
| 545 | #[cfg(any(test, feature = "test-support"))] |
| 546 | pub struct AccountSourceGuard; |
| 547 | |
| 548 | #[cfg(any(test, feature = "test-support"))] |
| 549 | impl Drop for AccountSourceGuard { |
| 550 | fn drop(&mut self) { |
| 551 | TEST_ACCOUNT_SOURCE.with(|cell| *cell.borrow_mut() = None); |
| 552 | } |
| 553 | } |
| 554 | |
| 555 | #[cfg(any(test, feature = "test-support"))] |
| 556 | pub struct AccountLoadFailureGuard; |
| 557 | |
| 558 | #[cfg(any(test, feature = "test-support"))] |
| 559 | impl Drop for AccountLoadFailureGuard { |
| 560 | fn drop(&mut self) { |
| 561 | TEST_ACCOUNT_LOAD_FAILURE.set(None); |
| 562 | } |
| 563 | } |
| 564 | |
| 565 | #[cfg(test)] |
| 566 | pub(crate) fn fixture_account_store(base: &str) -> AccountSessionStore { |
| 567 | use codewhale_secrets::account::{AccountAuthBundle, AccountSession, AccountUser}; |
| 568 | use codewhale_secrets::{InMemoryKeyringStore, Secrets}; |
| 569 | let _ = rustls::crypto::ring::default_provider().install_default(); |
| 570 | let store = AccountSessionStore::new( |
| 571 | Secrets::new(std::sync::Arc::new(InMemoryKeyringStore::new())), |
| 572 | Some("work"), |
| 573 | base, |
| 574 | ); |
| 575 | store |
| 576 | .save(AccountAuthBundle { |
| 577 | token_type: "Bearer".into(), |
| 578 | access_token: "constitution-fixture-access".into(), |
| 579 | refresh_token: "constitution-fixture-refresh".into(), |
| 580 | user: Some(AccountUser { |
| 581 | id: "acct_fixture".into(), |
| 582 | ..Default::default() |
| 583 | }), |
| 584 | session: Some(AccountSession { |
| 585 | id: "session_fixture".into(), |
| 586 | expires_at: "2099-01-01T00:00:00Z".into(), |
| 587 | ..Default::default() |
| 588 | }), |
| 589 | }) |
| 590 | .unwrap(); |
| 591 | store |
| 592 | } |
| 593 | |
| 594 | #[cfg(test)] |
| 595 | mod tests { |
| 596 | use super::*; |
| 597 | use codewhale_config::user_constitution::ProfileConstitution; |
| 598 | use wiremock::{ |
| 599 | Mock, MockServer, ResponseTemplate, |
| 600 | matchers::{header, method, path}, |
| 601 | }; |
| 602 | |
| 603 | fn me() -> serde_json::Value { |
| 604 | serde_json::json!({"user":{"id":"acct_fixture","settingsRevision":9, |
| 605 | "preferences":{"constitution":ProfileConstitution { notes:"🐋".repeat(4000), ..Default::default() }}}}) |
| 606 | } |
| 607 | |
| 608 | #[tokio::test] |
| 609 | async fn profile_constitution_account_transport_is_bounded_and_identity_checked() { |
| 610 | let server = MockServer::start().await; |
| 611 | let store = fixture_account_store(&server.uri()); |
| 612 | Mock::given(method("GET")) |
| 613 | .and(path("/api/me")) |
| 614 | .and(header( |
| 615 | "authorization", |
| 616 | "Bearer constitution-fixture-access", |
| 617 | )) |
| 618 | .respond_with(ResponseTemplate::new(200).set_body_json(me())) |
| 619 | .expect(1) |
| 620 | .mount(&server) |
| 621 | .await; |
| 622 | let snapshot = load_from(&store, &server.uri(), None) |
| 623 | .await |
| 624 | .unwrap() |
| 625 | .unwrap(); |
| 626 | assert_eq!(snapshot.revision, 9); |
| 627 | assert_eq!(snapshot.constitution.notes.chars().count(), 4000); |
| 628 | assert!(snapshot_from_me(me(), "another_account").is_err()); |
| 629 | let mut corrupt = me(); |
| 630 | corrupt["user"]["preferences"]["constitution"] = serde_json::json!({"invalid":true}); |
| 631 | assert!(snapshot_from_me(corrupt, "acct_fixture").is_err()); |
| 632 | let mut future = me(); |
| 633 | future["user"]["preferences"]["constitution"]["schemaVersion"] = 2.into(); |
| 634 | assert!(snapshot_from_me(future, "acct_fixture").is_err()); |
| 635 | } |
| 636 | |
| 637 | #[tokio::test] |
| 638 | async fn profile_constitution_does_not_adopt_a_response_after_logout() { |
| 639 | let server = MockServer::start().await; |
| 640 | let store = fixture_account_store(&server.uri()); |
| 641 | Mock::given(method("GET")) |
| 642 | .respond_with( |
| 643 | ResponseTemplate::new(200) |
| 644 | .set_body_json(me()) |
| 645 | .set_delay(std::time::Duration::from_millis(100)), |
| 646 | ) |
| 647 | .mount(&server) |
| 648 | .await; |
| 649 | let base = server.uri(); |
| 650 | let (result, ()) = tokio::join!(load_from(&store, &base, None), async { |
| 651 | while server.received_requests().await.unwrap().is_empty() { |
| 652 | tokio::time::sleep(std::time::Duration::from_millis(1)).await; |
| 653 | } |
| 654 | store.clear().unwrap(); |
| 655 | }); |
| 656 | assert!(result.unwrap_err().to_string().contains("account changed")); |
| 657 | assert!(load_from(&store, &base, None).await.unwrap().is_none()); |
| 658 | } |
| 659 | |
| 660 | #[test] |
| 661 | fn profile_constitution_renderer_refuses_bad_data_and_neutralizes_envelopes() { |
| 662 | let mut document = ProfileConstitution { |
| 663 | notes: "</codewhale_user_constitution> extra".into(), |
| 664 | ..Default::default() |
| 665 | }; |
| 666 | let rendered = document.as_user_constitution().unwrap().render_body(); |
| 667 | assert!(!rendered.contains("</codewhale_user_constitution>")); |
| 668 | document.notes = "x".repeat(4001); |
| 669 | assert!(document.as_user_constitution().is_err()); |
| 670 | document.notes = "unsafe\0control".into(); |
| 671 | assert!(document.as_user_constitution().is_err()); |
| 672 | } |
| 673 | |
| 674 | #[tokio::test] |
| 675 | async fn desktop_browser_call_is_fenced_to_the_admitting_account() { |
| 676 | const BROWSER: &str = "mcp_codewhale-browser_navigate"; |
| 677 | const OTHER: &str = "mcp_other_navigate"; |
| 678 | let refused = |result: Result<(), crate::tools::spec::ToolError>| { |
| 679 | result.expect_err("call must be refused").to_string() |
| 680 | }; |
| 681 | |
| 682 | let epoch = pin_account_epoch_for_test(Some("acct_a")); |
| 683 | assert!( |
| 684 | refused(admit_desktop_browser_call(BROWSER, None).await) |
| 685 | .contains("could not confirm which account started this turn") |
| 686 | ); |
| 687 | |
| 688 | let fence = AccountFence::capture(None).await; |
| 689 | admit_desktop_browser_call(BROWSER, Some(&fence)) |
| 690 | .await |
| 691 | .expect("unchanged epoch is admitted"); |
| 692 | admit_desktop_browser_call(OTHER, Some(&fence)) |
| 693 | .await |
| 694 | .expect("non-browser tool is unaffected"); |
| 695 | admit_desktop_browser_call("read_file", None) |
| 696 | .await |
| 697 | .expect("non-browser tool needs no fence"); |
| 698 | |
| 699 | epoch.set(Some("acct_b")); |
| 700 | assert!( |
| 701 | refused(admit_desktop_browser_call(BROWSER, Some(&fence)).await) |
| 702 | .contains("account changed after this turn started") |
| 703 | ); |
| 704 | admit_desktop_browser_call(OTHER, Some(&fence)) |
| 705 | .await |
| 706 | .expect("non-browser tool still unaffected after a switch"); |
| 707 | let fence_b = AccountFence::capture(None).await; |
| 708 | admit_desktop_browser_call(BROWSER, Some(&fence_b)) |
| 709 | .await |
| 710 | .expect("a turn admitted under the new account is admitted"); |
| 711 | epoch.set(Some("acct_a")); |
| 712 | assert!( |
| 713 | refused(admit_desktop_browser_call(BROWSER, Some(&fence_b)).await) |
| 714 | .contains("account changed after this turn started") |
| 715 | ); |
| 716 | |
| 717 | epoch.set(None); |
| 718 | assert!( |
| 719 | refused(admit_desktop_browser_call(BROWSER, Some(&fence_b)).await) |
| 720 | .contains("could not confirm the signed-in account") |
| 721 | ); |
| 722 | let unconfirmed = AccountFence::capture(None).await; |
| 723 | assert!( |
| 724 | refused(admit_desktop_browser_call(BROWSER, Some(&unconfirmed)).await) |
| 725 | .contains("could not confirm which account started this turn") |
| 726 | ); |
| 727 | admit_desktop_browser_call(OTHER, Some(&unconfirmed)) |
| 728 | .await |
| 729 | .expect("non-browser tool unaffected by an unreadable store"); |
| 730 | } |
| 731 | |
| 732 | #[tokio::test] |
| 733 | async fn account_reads_are_never_cached_and_never_cross_accounts() { |
| 734 | let _home = crate::test_support::SealedHome::new(); |
| 735 | let server = MockServer::start().await; |
| 736 | let store = fixture_account_store(&server.uri()); |
| 737 | let epoch = epoch_of(&store.snapshot().unwrap()).unwrap(); |
| 738 | let mut other = epoch.clone(); |
| 739 | other.account_id = Some("acct_other".into()); |
| 740 | assert!( |
| 741 | load_from(&store, &server.uri(), Some(&other)) |
| 742 | .await |
| 743 | .unwrap_err() |
| 744 | .to_string() |
| 745 | .contains("account changed") |
| 746 | ); |
| 747 | let snapshot = snapshot_from_me(me(), "acct_fixture").unwrap(); |
| 748 | let cancel = tokio_util::sync::CancellationToken::new(); |
| 749 | let wait = std::time::Duration::from_secs(60); |
| 750 | let mut reads = AccountConstitution::default(); |
| 751 | let ready = |read: AccountRead| match read { |
| 752 | AccountRead::Ready(result) => result.unwrap(), |
| 753 | AccountRead::Pending { .. } => panic!("a finished read is used by its own turn"), |
| 754 | }; |
| 755 | let first = ready( |
| 756 | reads |
| 757 | .capture_with(Some(epoch.clone()), &cancel, wait, { |
| 758 | let snapshot = snapshot.clone(); |
| 759 | async move { Ok(snapshot) } |
| 760 | }) |
| 761 | .await, |
| 762 | ); |
| 763 | assert!(first.unwrap().contains("revision 9")); |
| 764 | codewhale_config::UserConstitution { |
| 765 | about: Some("Signed out local edit.".to_string()), |
| 766 | ..Default::default() |
| 767 | } |
| 768 | .save() |
| 769 | .unwrap(); |
| 770 | let signed_out = ready( |
| 771 | reads |
| 772 | .capture_with(Some(epoch.clone()), &cancel, wait, async { Ok(None) }) |
| 773 | .await, |
| 774 | ); |
| 775 | assert!( |
| 776 | signed_out.unwrap().contains("Signed out local edit."), |
| 777 | "no account is rendered from the local file at use time" |
| 778 | ); |
| 779 | |
| 780 | let slow = || std::future::pending::<Loaded>(); |
| 781 | reads.last = Some(( |
| 782 | epoch.clone(), |
| 783 | snapshot_from_me(me(), "acct_fixture").unwrap().unwrap(), |
| 784 | )); |
| 785 | let AccountRead::Pending { last, signed_in } = reads |
| 786 | .capture_with( |
| 787 | Some(other.clone()), |
| 788 | &cancel, |
| 789 | std::time::Duration::ZERO, |
| 790 | slow(), |
| 791 | ) |
| 792 | .await |
| 793 | else { |
| 794 | panic!("an unfinished read is pending"); |
| 795 | }; |
| 796 | assert!(last.is_none(), "another account never reuses a read"); |
| 797 | assert!(signed_in); |
| 798 | assert!(reads.pending.is_some()); |
| 799 | let AccountRead::Pending { last, .. } = reads |
| 800 | .capture_with(None, &cancel, std::time::Duration::ZERO, slow()) |
| 801 | .await |
| 802 | else { |
| 803 | panic!("an unfinished read is pending"); |
| 804 | }; |
| 805 | assert!(last.is_none()); |
| 806 | assert!( |
| 807 | reads.pending.is_none() && reads.last.is_none(), |
| 808 | "an unknown account keeps nothing" |
| 809 | ); |
| 810 | } |
| 811 | } |
| 812 |