| 1 | use std::sync::Arc; |
| 2 | use std::sync::atomic::{AtomicBool, Ordering}; |
| 3 | use std::time::{Duration, Instant}; |
| 4 | |
| 5 | use chrono::{DateTime, Utc}; |
| 6 | use codewhale_secrets::account::{AccountDeviceAccess, AccountSessionState, RuntimeAccountInfo}; |
| 7 | |
| 8 | use super::*; |
| 9 | |
| 10 | pub fn account_api_base(api_base: Option<&str>) -> Result<String> { |
| 11 | let requested_base = machine::resolve_api_base( |
| 12 | api_base, |
| 13 | std::env::var(machine::MACHINE_API_BASE_ENV).ok().as_deref(), |
| 14 | std::env::var(CLOUD_API_BASE_ENV).ok().as_deref(), |
| 15 | DEFAULT_API_BASE, |
| 16 | ); |
| 17 | Ok(validate_api_base(&requested_base)?.display) |
| 18 | } |
| 19 | |
| 20 | #[derive(Clone, Serialize)] |
| 21 | #[serde(rename_all = "camelCase")] |
| 22 | pub struct AccountStatus { |
| 23 | pub profile: String, |
| 24 | pub api_base: String, |
| 25 | pub account: RuntimeAccountInfo, |
| 26 | pub user: Option<CloudUser>, |
| 27 | pub revision: String, |
| 28 | pub import_allowed: bool, |
| 29 | } |
| 30 | |
| 31 | pub struct AccountAuthLease { |
| 32 | pub bundle: AuthBundle, |
| 33 | pub snapshot: AccountSessionSnapshot, |
| 34 | } |
| 35 | |
| 36 | #[derive(Clone, Serialize)] |
| 37 | #[serde(rename_all = "camelCase")] |
| 38 | pub struct AccountModel { |
| 39 | pub id: String, |
| 40 | pub label: String, |
| 41 | pub provider: String, |
| 42 | pub model: String, |
| 43 | pub protocol: String, |
| 44 | pub billing_mode: String, |
| 45 | pub is_default: bool, |
| 46 | } |
| 47 | |
| 48 | pub struct AccountModels { |
| 49 | pub api_base: String, |
| 50 | pub account_id: String, |
| 51 | pub session_id: String, |
| 52 | pub expires_at: i64, |
| 53 | pub default_model: Option<String>, |
| 54 | pub models: Vec<AccountModel>, |
| 55 | pub credential: Option<String>, |
| 56 | pub snapshot: AccountSessionSnapshot, |
| 57 | } |
| 58 | |
| 59 | #[derive(Clone)] |
| 60 | pub struct AccountClient { |
| 61 | pub(crate) transport: ReqwestTransport, |
| 62 | store: AccountSessionStore, |
| 63 | profile: String, |
| 64 | pub(crate) api_base: String, |
| 65 | } |
| 66 | |
| 67 | impl AccountClient { |
| 68 | pub fn new(profile: Option<&str>, api_base: Option<&str>) -> Result<Self> { |
| 69 | let requested_base = account_api_base(api_base)?; |
| 70 | let base = validate_api_base(&requested_base)?; |
| 71 | let profile = normalized_profile(profile); |
| 72 | let secrets = cloud_session_secrets()?; |
| 73 | Ok(Self { |
| 74 | transport: ReqwestTransport::new(base.url)?, |
| 75 | store: AccountSessionStore::new(secrets, Some(&profile), &base.display), |
| 76 | profile, |
| 77 | api_base: base.display, |
| 78 | }) |
| 79 | } |
| 80 | |
| 81 | pub(crate) fn client(&self) -> CloudClient<'_, ReqwestTransport> { |
| 82 | CloudClient { |
| 83 | transport: &self.transport, |
| 84 | account_store: self.store.clone(), |
| 85 | } |
| 86 | } |
| 87 | |
| 88 | fn revoke_session_later(&self, previous: Option<AccountSessionSnapshot>, bundle: AuthBundle) { |
| 89 | let client = self.clone(); |
| 90 | if let Err(error) = std::thread::Builder::new() |
| 91 | .name("cw-account-revoke".into()) |
| 92 | .spawn(move || { |
| 93 | let _ = match previous { |
| 94 | Some(previous) => client.client().revoke_previous_session(&previous, &bundle), |
| 95 | None => client.client().revoke_session_bundle(&bundle), |
| 96 | }; |
| 97 | }) |
| 98 | { |
| 99 | codewhale_runtime::logging::info(format!( |
| 100 | "failed to spawn account session revoke thread: {error}" |
| 101 | )); |
| 102 | } |
| 103 | } |
| 104 | |
| 105 | pub fn snapshot(&self) -> Result<AccountSessionSnapshot> { |
| 106 | Ok(self.store.snapshot()?) |
| 107 | } |
| 108 | |
| 109 | pub fn status(&self) -> Result<AccountStatus> { |
| 110 | let snapshot = self.snapshot()?; |
| 111 | let user = snapshot.load()?.and_then(|stored| stored.bundle.user); |
| 112 | Ok(AccountStatus { |
| 113 | profile: self.profile.clone(), |
| 114 | api_base: self.api_base.clone(), |
| 115 | account: snapshot.runtime_info_at(Utc::now())?, |
| 116 | user, |
| 117 | revision: snapshot.fingerprint(), |
| 118 | import_allowed: snapshot.is_pristine(), |
| 119 | }) |
| 120 | } |
| 121 | |
| 122 | pub fn claim(&self) -> Result<AccountSessionSnapshot> { |
| 123 | Ok(self.store.begin_login()?) |
| 124 | } |
| 125 | |
| 126 | pub fn claim_if_unchanged( |
| 127 | &self, |
| 128 | expected_revision: &str, |
| 129 | ) -> Result<Option<AccountSessionSnapshot>> { |
| 130 | self.store.with_transaction(|transaction| { |
| 131 | if transaction.snapshot().fingerprint() != expected_revision { |
| 132 | return Ok(None); |
| 133 | } |
| 134 | Ok(Some(transaction.renew_revision()?)) |
| 135 | }) |
| 136 | } |
| 137 | |
| 138 | pub fn cancel_claim(&self, expected_revision: &str) -> Result<bool> { |
| 139 | self.store.with_transaction(|transaction| { |
| 140 | if transaction.snapshot().fingerprint() != expected_revision { |
| 141 | return Ok(false); |
| 142 | } |
| 143 | transaction.renew_revision()?; |
| 144 | Ok(true) |
| 145 | }) |
| 146 | } |
| 147 | |
| 148 | pub fn import( |
| 149 | &self, |
| 150 | bundle: AuthBundle, |
| 151 | expected_revision: &str, |
| 152 | replace_existing: bool, |
| 153 | ) -> Result<bool> { |
| 154 | self.import_with_receipt(bundle, expected_revision, replace_existing) |
| 155 | .map(|receipt| receipt.is_some()) |
| 156 | } |
| 157 | |
| 158 | pub fn import_with_receipt( |
| 159 | &self, |
| 160 | bundle: AuthBundle, |
| 161 | expected_revision: &str, |
| 162 | replace_existing: bool, |
| 163 | ) -> Result<Option<AccountSessionSnapshot>> { |
| 164 | validate_auth_bundle(&bundle)?; |
| 165 | let expected = self.snapshot()?; |
| 166 | if expected.fingerprint() != expected_revision { |
| 167 | return Ok(None); |
| 168 | } |
| 169 | if !replace_existing && !expected.is_pristine() { |
| 170 | return Ok(None); |
| 171 | } |
| 172 | let Some(committed) = self.store.save_if_unchanged(&expected, bundle.clone())? else { |
| 173 | return Ok(None); |
| 174 | }; |
| 175 | self.revoke_session_later(Some(expected), bundle); |
| 176 | Ok(Some(committed)) |
| 177 | } |
| 178 | |
| 179 | pub fn fresh_auth(&self, rejected_token: Option<&str>) -> Result<Option<AccountAuthLease>> { |
| 180 | let snapshot = self.snapshot()?; |
| 181 | let Some(stored) = snapshot.load()? else { |
| 182 | return Ok(None); |
| 183 | }; |
| 184 | if matches!( |
| 185 | snapshot.runtime_info_at(Utc::now())?.state, |
| 186 | AccountSessionState::Expired | AccountSessionState::Revoked |
| 187 | ) { |
| 188 | return Ok(None); |
| 189 | } |
| 190 | let refresh = rejected_token == Some(stored.bundle.access_token.as_str()) |
| 191 | || !stored |
| 192 | .bundle |
| 193 | .session |
| 194 | .as_ref() |
| 195 | .and_then(|session| DateTime::parse_from_rfc3339(&session.expires_at).ok()) |
| 196 | .is_some_and(|expires| expires.timestamp() > Utc::now().timestamp() + 120); |
| 197 | let (bundle, snapshot) = if refresh { |
| 198 | let Some(renewed) = self.client().refresh_snapshot(&snapshot)? else { |
| 199 | return Ok(None); |
| 200 | }; |
| 201 | renewed |
| 202 | } else { |
| 203 | (stored.bundle, snapshot) |
| 204 | }; |
| 205 | let current = self.store.with_transaction(|transaction| { |
| 206 | Ok::<_, anyhow::Error>(transaction.matches(&snapshot)) |
| 207 | })?; |
| 208 | Ok(current.then_some(AccountAuthLease { bundle, snapshot })) |
| 209 | } |
| 210 | |
| 211 | pub fn logout(&self) -> Result<bool> { |
| 212 | self.client().logout() |
| 213 | } |
| 214 | |
| 215 | pub fn logout_if_unchanged(&self, snapshot: &AccountSessionSnapshot) -> Result<bool> { |
| 216 | self.client().logout_from_snapshot(snapshot) |
| 217 | } |
| 218 | |
| 219 | pub fn connect_models(&self) -> Result<AccountModels> { |
| 220 | self.connect_models_with_cancel(&AtomicBool::new(false)) |
| 221 | } |
| 222 | |
| 223 | pub fn connect_models_with_cancel(&self, cancelled: &AtomicBool) -> Result<AccountModels> { |
| 224 | if cancelled.load(Ordering::Acquire) { |
| 225 | bail!("Codewhale account model connection cancelled"); |
| 226 | } |
| 227 | let lease = self |
| 228 | .fresh_auth(None)? |
| 229 | .ok_or_else(|| anyhow!("Sign in to Codewhale before connecting account models"))?; |
| 230 | let (response, snapshot) = self.client().execute_from_snapshot( |
| 231 | HttpMethod::Get, |
| 232 | "/api/account/model-api", |
| 233 | None, |
| 234 | lease.snapshot, |
| 235 | )?; |
| 236 | let catalog: serde_json::Value = expect_json(response, &[200])?; |
| 237 | let data = catalog |
| 238 | .get("data") |
| 239 | .and_then(serde_json::Value::as_array) |
| 240 | .filter(|rows| rows.len() <= 8192) |
| 241 | .ok_or_else(|| anyhow!("The Codewhale account model catalog was invalid"))?; |
| 242 | let mut models = Vec::new(); |
| 243 | for row in data { |
| 244 | let facts = &row["codewhale"]; |
| 245 | if facts["usable"].as_bool() != Some(true) { |
| 246 | continue; |
| 247 | } |
| 248 | if facts["protocol"].as_str() != Some("chat-completions") |
| 249 | || facts["billingMode"].as_str() != Some("byok_external") |
| 250 | { |
| 251 | continue; |
| 252 | } |
| 253 | let id = model_text(row, "id")?; |
| 254 | let provider = model_text(facts, "provider")?; |
| 255 | let model = model_text(facts, "model")?; |
| 256 | if id != format!("{provider}/{model}") { |
| 257 | bail!("The Codewhale account model catalog was invalid"); |
| 258 | } |
| 259 | models.push(AccountModel { |
| 260 | id, |
| 261 | label: facts["label"] |
| 262 | .as_str() |
| 263 | .map(|label| printable_max(label, 200)) |
| 264 | .filter(|label| !label.is_empty()) |
| 265 | .unwrap_or_else(|| model.clone()), |
| 266 | provider, |
| 267 | model, |
| 268 | protocol: model_text(facts, "protocol")?, |
| 269 | billing_mode: model_text(facts, "billingMode")?, |
| 270 | is_default: facts["default"].as_bool() == Some(true), |
| 271 | }); |
| 272 | } |
| 273 | let stored = snapshot |
| 274 | .load()? |
| 275 | .ok_or_else(|| anyhow!("The signed-in account changed. Refresh and try again."))?; |
| 276 | let account_id = stored |
| 277 | .bundle |
| 278 | .user |
| 279 | .as_ref() |
| 280 | .map(|user| user.id.clone()) |
| 281 | .filter(|id| !id.is_empty()) |
| 282 | .ok_or_else(|| anyhow!("Sign in again before connecting account models"))?; |
| 283 | let session = stored |
| 284 | .bundle |
| 285 | .session |
| 286 | .as_ref() |
| 287 | .filter(|session| !session.id.is_empty()) |
| 288 | .ok_or_else(|| anyhow!("Sign in again before connecting account models"))?; |
| 289 | let session_id = session.id.clone(); |
| 290 | let access_expires = DateTime::parse_from_rfc3339(&session.expires_at) |
| 291 | .context("The account session expiry was invalid")? |
| 292 | .timestamp(); |
| 293 | let refresh_expires = DateTime::parse_from_rfc3339(&session.refresh_expires_at) |
| 294 | .context("The account session expiry was invalid")? |
| 295 | .timestamp(); |
| 296 | let default_model = catalog["codewhale"]["defaultModel"] |
| 297 | .as_str() |
| 298 | .filter(|id| models.iter().any(|model| model.id == *id)) |
| 299 | .map(str::to_string) |
| 300 | .or_else(|| { |
| 301 | models |
| 302 | .iter() |
| 303 | .find(|model| model.is_default) |
| 304 | .map(|model| model.id.clone()) |
| 305 | }); |
| 306 | let mut result = AccountModels { |
| 307 | api_base: format!("{}/v1", self.api_base), |
| 308 | account_id: account_id.clone(), |
| 309 | session_id: session_id.clone(), |
| 310 | expires_at: 0, |
| 311 | default_model, |
| 312 | models, |
| 313 | credential: None, |
| 314 | snapshot, |
| 315 | }; |
| 316 | if result.models.is_empty() { |
| 317 | let current = self.store.with_transaction(|transaction| { |
| 318 | Ok::<_, anyhow::Error>(transaction.matches(&result.snapshot)) |
| 319 | })?; |
| 320 | if !current { |
| 321 | bail!("The signed-in account changed. Refresh and try again."); |
| 322 | } |
| 323 | return Ok(result); |
| 324 | } |
| 325 | if cancelled.load(Ordering::Acquire) { |
| 326 | bail!("Codewhale account model connection cancelled"); |
| 327 | } |
| 328 | let device_id = self.store.device_id()?; |
| 329 | let mut issued_id: Option<String> = None; |
| 330 | let connected = self.store.with_transaction(|transaction| { |
| 331 | if !transaction.matches(&result.snapshot) || access_expires <= Utc::now().timestamp() { |
| 332 | bail!("The signed-in account changed. Refresh and try again."); |
| 333 | } |
| 334 | if cancelled.load(Ordering::Acquire) { |
| 335 | bail!("Codewhale account model connection cancelled"); |
| 336 | } |
| 337 | let current = transaction.snapshot(); |
| 338 | if let Some(access) = current.device_access()? { |
| 339 | if access.device_id != device_id { |
| 340 | bail!("The Codewhale device connection changed. Reconnect your account."); |
| 341 | } |
| 342 | machine::MachineKey::parse(&access.credential)?; |
| 343 | if access.expires_at > Utc::now().timestamp() { |
| 344 | let checked = self.transport.execute(CloudRequest { |
| 345 | method: HttpMethod::Get, |
| 346 | path: "/v1/models".into(), |
| 347 | bearer: Some(access.credential.clone()), |
| 348 | body: None, |
| 349 | })?; |
| 350 | match checked.status { |
| 351 | 200 => return Ok((access, current)), |
| 352 | 401 => {} |
| 353 | _ => return Err(response_error(&checked)), |
| 354 | } |
| 355 | } |
| 356 | } |
| 357 | if cancelled.load(Ordering::Acquire) { |
| 358 | bail!("Codewhale account model connection cancelled"); |
| 359 | } |
| 360 | let response = self.transport.execute(CloudRequest { |
| 361 | method: HttpMethod::Post, |
| 362 | path: "/api/account/device-link".into(), |
| 363 | bearer: Some(stored.bundle.access_token.clone()), |
| 364 | body: Some(serde_json::to_vec(&serde_json::json!({ |
| 365 | "deviceId": device_id, |
| 366 | "deviceName": "Codewhale", |
| 367 | "expectedAccountId": account_id, |
| 368 | }))?), |
| 369 | })?; |
| 370 | let linked: LinkedDevice = expect_json(response, &[201])?; |
| 371 | if linked.api_key.id.len() == 24 |
| 372 | && linked |
| 373 | .api_key |
| 374 | .id |
| 375 | .bytes() |
| 376 | .all(|byte| byte.is_ascii_hexdigit()) |
| 377 | { |
| 378 | issued_id = Some(linked.api_key.id.clone()); |
| 379 | } |
| 380 | let key = machine::MachineKey::parse(&linked.secret)?; |
| 381 | let expires_at = DateTime::parse_from_rfc3339(&linked.api_key.expires_at) |
| 382 | .context("The account device expiry was invalid")? |
| 383 | .timestamp(); |
| 384 | if !linked.session_bound |
| 385 | || linked.api_key.scopes.len() != 1 |
| 386 | || linked.api_key.scopes[0] != "models:infer" |
| 387 | || linked.api_key.revoked_at.is_some() |
| 388 | || linked.api_key.context.kind != "device" |
| 389 | || linked.api_key.context.device_id != device_id |
| 390 | || linked.api_key.context.session_id != session_id |
| 391 | || key.head().strip_prefix("cwc_key_") != Some(linked.api_key.id.as_str()) |
| 392 | || expires_at <= Utc::now().timestamp() |
| 393 | || expires_at > refresh_expires |
| 394 | { |
| 395 | bail!("The Codewhale device connection could not be verified"); |
| 396 | } |
| 397 | let access = AccountDeviceAccess { |
| 398 | device_id: device_id.clone(), |
| 399 | credential: linked.secret, |
| 400 | api_key_id: linked.api_key.id, |
| 401 | account_id: account_id.clone(), |
| 402 | session_id: session_id.clone(), |
| 403 | expires_at, |
| 404 | }; |
| 405 | transaction.set_device_access(access.clone())?; |
| 406 | Ok((access, transaction.snapshot())) |
| 407 | }); |
| 408 | let (access, snapshot) = match connected { |
| 409 | Ok(connected) => connected, |
| 410 | Err(error) => { |
| 411 | if let Some(id) = issued_id { |
| 412 | let _ = self.transport.execute(CloudRequest { |
| 413 | method: HttpMethod::Delete, |
| 414 | path: format!("/api/account/api-keys/{id}"), |
| 415 | bearer: Some(stored.bundle.access_token), |
| 416 | body: None, |
| 417 | }); |
| 418 | } |
| 419 | return Err(error); |
| 420 | } |
| 421 | }; |
| 422 | result.expires_at = access.expires_at.min(access_expires); |
| 423 | result.credential = Some(access.credential); |
| 424 | result.snapshot = snapshot; |
| 425 | Ok(result) |
| 426 | } |
| 427 | |
| 428 | pub fn start_login(&self, timeout: Duration) -> Result<AccountLogin> { |
| 429 | self.start_login_with_cancel(timeout, Arc::new(AtomicBool::new(false))) |
| 430 | } |
| 431 | |
| 432 | pub fn start_login_with_cancel( |
| 433 | &self, |
| 434 | timeout: Duration, |
| 435 | cancelled: Arc<AtomicBool>, |
| 436 | ) -> Result<AccountLogin> { |
| 437 | if timeout.is_zero() || timeout > Duration::from_secs(MAX_LOGIN_TIMEOUT_SECONDS) { |
| 438 | bail!("Invalid Codewhale account login timeout"); |
| 439 | } |
| 440 | let expected = self.store.with_transaction(|transaction| { |
| 441 | if cancelled.load(Ordering::Acquire) { |
| 442 | bail!("Codewhale account login cancelled"); |
| 443 | } |
| 444 | Ok::<_, anyhow::Error>(transaction.renew_revision()?) |
| 445 | })?; |
| 446 | let started = Instant::now(); |
| 447 | if cancelled.load(Ordering::Acquire) { |
| 448 | bail!("Codewhale account login cancelled"); |
| 449 | } |
| 450 | let device = self.client().start_device()?; |
| 451 | validate_device_code(&device.device_code)?; |
| 452 | validate_user_code(&device.user_code)?; |
| 453 | let verification_uri = validate_verification_url( |
| 454 | &device.verification_uri, |
| 455 | &self.api_base, |
| 456 | &device.user_code, |
| 457 | false, |
| 458 | )?; |
| 459 | let verification_uri_complete = validate_verification_url( |
| 460 | &device.verification_uri_complete, |
| 461 | &self.api_base, |
| 462 | &device.user_code, |
| 463 | true, |
| 464 | )?; |
| 465 | let lifetime = timeout.min(Duration::from_secs( |
| 466 | device.expires_in.clamp(1, MAX_LOGIN_TIMEOUT_SECONDS), |
| 467 | )); |
| 468 | let interval = if device.interval == 0 { |
| 469 | codewhale_config::device_code::DEFAULT_POLL_INTERVAL_SECS |
| 470 | } else { |
| 471 | device.interval.min(10) |
| 472 | }; |
| 473 | Ok(AccountLogin { |
| 474 | client: self.clone(), |
| 475 | expected, |
| 476 | prompt: AccountLoginPrompt { |
| 477 | user_code: device.user_code.clone(), |
| 478 | verification_uri, |
| 479 | verification_uri_complete, |
| 480 | expires_in: lifetime.as_secs(), |
| 481 | interval, |
| 482 | }, |
| 483 | device, |
| 484 | cancelled: AccountLoginCancellation(cancelled), |
| 485 | deadline: started + lifetime, |
| 486 | next_poll: started, |
| 487 | pending_bundle: None, |
| 488 | finished: false, |
| 489 | }) |
| 490 | } |
| 491 | } |
| 492 | |
| 493 | fn model_text(value: &serde_json::Value, key: &str) -> Result<String> { |
| 494 | value[key] |
| 495 | .as_str() |
| 496 | .filter(|text| { |
| 497 | !text.is_empty() |
| 498 | && text.len() <= 512 |
| 499 | && !text.chars().any(char::is_control) |
| 500 | && !text.chars().any(char::is_whitespace) |
| 501 | }) |
| 502 | .map(str::to_string) |
| 503 | .ok_or_else(|| anyhow!("The Codewhale account model catalog was invalid")) |
| 504 | } |
| 505 | |
| 506 | #[derive(Deserialize)] |
| 507 | #[serde(rename_all = "camelCase")] |
| 508 | struct LinkedDevice { |
| 509 | secret: String, |
| 510 | api_key: LinkedDeviceKey, |
| 511 | session_bound: bool, |
| 512 | } |
| 513 | |
| 514 | #[derive(Deserialize)] |
| 515 | #[serde(rename_all = "camelCase")] |
| 516 | struct LinkedDeviceKey { |
| 517 | id: String, |
| 518 | scopes: Vec<String>, |
| 519 | expires_at: String, |
| 520 | revoked_at: Option<String>, |
| 521 | context: LinkedDeviceContext, |
| 522 | } |
| 523 | |
| 524 | #[derive(Deserialize)] |
| 525 | #[serde(rename_all = "camelCase")] |
| 526 | struct LinkedDeviceContext { |
| 527 | kind: String, |
| 528 | device_id: String, |
| 529 | session_id: String, |
| 530 | } |
| 531 | |
| 532 | #[derive(Clone, Serialize)] |
| 533 | #[serde(rename_all = "camelCase")] |
| 534 | pub struct AccountLoginPrompt { |
| 535 | pub user_code: String, |
| 536 | pub verification_uri: String, |
| 537 | pub verification_uri_complete: String, |
| 538 | pub expires_in: u64, |
| 539 | pub interval: u64, |
| 540 | } |
| 541 | |
| 542 | #[derive(Clone)] |
| 543 | pub struct AccountLoginCancellation(Arc<AtomicBool>); |
| 544 | |
| 545 | impl AccountLoginCancellation { |
| 546 | pub fn cancel(&self) { |
| 547 | self.0.store(true, Ordering::Release); |
| 548 | } |
| 549 | } |
| 550 | |
| 551 | pub enum AccountLoginPoll { |
| 552 | Pending { retry_after: Duration }, |
| 553 | Complete { user: CloudUser }, |
| 554 | Cancelled, |
| 555 | Expired, |
| 556 | } |
| 557 | |
| 558 | pub struct AccountLogin { |
| 559 | client: AccountClient, |
| 560 | expected: AccountSessionSnapshot, |
| 561 | device: DeviceStart, |
| 562 | prompt: AccountLoginPrompt, |
| 563 | cancelled: AccountLoginCancellation, |
| 564 | deadline: Instant, |
| 565 | next_poll: Instant, |
| 566 | pending_bundle: Option<AuthBundle>, |
| 567 | finished: bool, |
| 568 | } |
| 569 | |
| 570 | impl AccountLogin { |
| 571 | pub fn prompt(&self) -> &AccountLoginPrompt { |
| 572 | &self.prompt |
| 573 | } |
| 574 | |
| 575 | pub fn cancellation(&self) -> AccountLoginCancellation { |
| 576 | self.cancelled.clone() |
| 577 | } |
| 578 | |
| 579 | pub fn poll(&mut self) -> Result<AccountLoginPoll> { |
| 580 | let result = self.poll_once(); |
| 581 | if !matches!(result, Ok(AccountLoginPoll::Pending { .. })) { |
| 582 | self.finished = true; |
| 583 | } |
| 584 | if matches!( |
| 585 | result, |
| 586 | Ok(AccountLoginPoll::Cancelled | AccountLoginPoll::Expired) |
| 587 | ) { |
| 588 | self.revoke_pending(); |
| 589 | } |
| 590 | result |
| 591 | } |
| 592 | |
| 593 | fn revoke_pending(&mut self) { |
| 594 | if let Some(bundle) = self.pending_bundle.take() { |
| 595 | self.client.revoke_session_later(None, bundle); |
| 596 | } |
| 597 | } |
| 598 | |
| 599 | fn poll_once(&mut self) -> Result<AccountLoginPoll> { |
| 600 | if self.finished || self.cancelled.0.load(Ordering::Acquire) { |
| 601 | return Ok(AccountLoginPoll::Cancelled); |
| 602 | } |
| 603 | let now = Instant::now(); |
| 604 | if now >= self.deadline { |
| 605 | return Ok(AccountLoginPoll::Expired); |
| 606 | } |
| 607 | if now < self.next_poll { |
| 608 | return Ok(AccountLoginPoll::Pending { |
| 609 | retry_after: (self.next_poll - now).min(self.deadline - now), |
| 610 | }); |
| 611 | } |
| 612 | if !self.client.store.with_transaction(|transaction| { |
| 613 | Ok::<_, anyhow::Error>(transaction.matches(&self.expected)) |
| 614 | })? { |
| 615 | return Ok(AccountLoginPoll::Cancelled); |
| 616 | } |
| 617 | if let Some(bundle) = self.pending_bundle.as_mut() { |
| 618 | if bundle.user.is_none() { |
| 619 | let response = self.client.transport.execute(CloudRequest { |
| 620 | method: HttpMethod::Get, |
| 621 | path: "/api/me".into(), |
| 622 | bearer: Some(bundle.access_token.clone()), |
| 623 | body: None, |
| 624 | })?; |
| 625 | bundle.user = Some(expect_json::<MeResponse>(response, &[200])?.user); |
| 626 | } |
| 627 | } else { |
| 628 | match self.client.client().poll_device_once(&self.device)? { |
| 629 | DevicePollOutcome::Complete(bundle) => self.pending_bundle = Some(bundle), |
| 630 | DevicePollOutcome::Pending | DevicePollOutcome::SlowDown { .. } => { |
| 631 | self.next_poll = Instant::now() + Duration::from_secs(self.prompt.interval); |
| 632 | return Ok(AccountLoginPoll::Pending { |
| 633 | retry_after: self |
| 634 | .next_poll |
| 635 | .min(self.deadline) |
| 636 | .saturating_duration_since(Instant::now()), |
| 637 | }); |
| 638 | } |
| 639 | } |
| 640 | } |
| 641 | let bundle = self |
| 642 | .pending_bundle |
| 643 | .as_ref() |
| 644 | .ok_or_else(|| anyhow!("The Codewhale account authorization was unavailable"))?; |
| 645 | if bundle.user.is_none() { |
| 646 | return Ok(AccountLoginPoll::Pending { |
| 647 | retry_after: Duration::ZERO, |
| 648 | }); |
| 649 | } |
| 650 | let Some(user) = bundle |
| 651 | .user |
| 652 | .as_ref() |
| 653 | .filter(|user| !user.id.trim().is_empty()) |
| 654 | else { |
| 655 | bail!("The Codewhale service returned an account without an ID"); |
| 656 | }; |
| 657 | let user = user.clone(); |
| 658 | validate_auth_bundle(bundle)?; |
| 659 | if Instant::now() >= self.deadline { |
| 660 | return Ok(AccountLoginPoll::Expired); |
| 661 | } |
| 662 | let bundle = self |
| 663 | .pending_bundle |
| 664 | .take() |
| 665 | .ok_or_else(|| anyhow!("The Codewhale account authorization was unavailable"))?; |
| 666 | let committed = self.client.store.with_transaction(|transaction| { |
| 667 | if self.cancelled.0.load(Ordering::Acquire) |
| 668 | || !transaction.matches(&self.expected) |
| 669 | || Instant::now() >= self.deadline |
| 670 | { |
| 671 | return Ok::<_, anyhow::Error>(false); |
| 672 | } |
| 673 | transaction.replace(bundle.clone())?; |
| 674 | Ok(true) |
| 675 | })?; |
| 676 | if !committed { |
| 677 | self.client.revoke_session_later(None, bundle); |
| 678 | return Ok(AccountLoginPoll::Cancelled); |
| 679 | } |
| 680 | self.client |
| 681 | .revoke_session_later(Some(self.expected.clone()), bundle); |
| 682 | Ok(AccountLoginPoll::Complete { user }) |
| 683 | } |
| 684 | } |
| 685 | |
| 686 | impl Drop for AccountLogin { |
| 687 | fn drop(&mut self) { |
| 688 | if !self.finished { |
| 689 | self.cancelled.cancel(); |
| 690 | } |
| 691 | self.revoke_pending(); |
| 692 | } |
| 693 | } |
| 694 |