返回 CodeWhale
account.rs
根目录 / crates / secrets / src / account.rs
1 //! Shared secure-storage contract for Codewhale account sessions.
2 //!
3 //! The CLI owns device authorization and refresh traffic. This module owns the
4 //! durable record written by that flow so the TUI and Runtime API can recognize
5 //! the same account without copying tokens or inventing another login protocol.
6
7 use std::collections::BTreeMap;
8
9 use chrono::{DateTime, Utc};
10 use serde::{Deserialize, Serialize};
11 use sha2::{Digest, Sha256};
12 use thiserror::Error;
13
14 use crate::{Secrets, SecretsError};
15
16 /// Production account API origin used when no override is configured.
17 pub const DEFAULT_ACCOUNT_API_BASE: &str = "https://api.codewhale.net";
18 /// Environment variable that selects the account API origin.
19 pub const ACCOUNT_API_BASE_ENV: &str = "CODEWHALE_CLOUD_API_BASE";
20 /// Current serialized account-session record version.
21 pub const ACCOUNT_SESSION_SCHEMA_VERSION: u8 = 1;
22
23 const MAX_TOKEN_BYTES: usize = 64 * 1024;
24 const MAX_SCOPES: usize = 64;
25 const MAX_SCOPE_BYTES: usize = 128;
26
27 /// A short-lived access credential and its durable refresh/session metadata.
28 ///
29 /// This type intentionally does not implement `Debug`, preventing accidental
30 /// token disclosure through ordinary diagnostic formatting.
31 #[derive(Clone, Deserialize, Serialize)]
32 #[serde(rename_all = "camelCase")]
33 pub struct AccountAuthBundle {
34 /// Authentication scheme returned by the account service.
35 pub token_type: String,
36 /// Short-lived bearer credential. Never serialize this outside secure storage.
37 pub access_token: String,
38 /// Refresh credential. Never serialize this outside secure storage.
39 pub refresh_token: String,
40 /// Durable server session metadata, when returned by the service.
41 #[serde(default)]
42 pub session: Option<AccountSession>,
43 /// Cached non-secret account record, when returned by the service.
44 #[serde(default)]
45 pub user: Option<AccountUser>,
46 }
47
48 /// Durable account-session metadata supplied by the account service.
49 #[derive(Clone, Default, Deserialize, Serialize)]
50 #[serde(rename_all = "camelCase")]
51 pub struct AccountSession {
52 /// Durable session identifier shared across Codewhale surfaces.
53 pub id: String,
54 /// Authorization provider used to establish the session.
55 #[serde(default)]
56 pub provider: String,
57 /// Linked authorization providers recorded by the account service.
58 #[serde(default)]
59 pub providers: Vec<String>,
60 /// Explicit bounded scopes granted to this session.
61 #[serde(default)]
62 pub scopes: Vec<String>,
63 /// Access-credential expiration in RFC 3339 format.
64 #[serde(default)]
65 pub expires_at: String,
66 /// Refresh/session expiration in RFC 3339 format.
67 #[serde(default)]
68 pub refresh_expires_at: String,
69 /// Explicit server session state when supplied.
70 #[serde(default)]
71 pub status: String,
72 /// Explicit revocation timestamp when supplied.
73 #[serde(default)]
74 pub revoked_at: String,
75 }
76
77 /// Cached account identity and non-secret presentation fields.
78 #[derive(Clone, Default, Deserialize, Serialize)]
79 #[serde(rename_all = "camelCase")]
80 pub struct AccountUser {
81 /// Stable Codewhale account identifier.
82 #[serde(default)]
83 pub id: String,
84 /// User-facing account name.
85 #[serde(default)]
86 pub display_name: String,
87 /// Account email returned by the service. Runtime metadata never exposes it.
88 #[serde(default)]
89 pub email: String,
90 /// Account residency region returned by the service.
91 #[serde(default)]
92 pub region: String,
93 /// Account plan returned by the service.
94 #[serde(default)]
95 pub plan: String,
96 /// Provider-key presence metadata; values never contain provider credentials.
97 #[serde(default)]
98 pub model_keys: BTreeMap<String, AccountModelKeyState>,
99 }
100
101 /// Non-secret provider-key presence metadata returned by the account service.
102 #[derive(Clone, Default, Deserialize, Serialize)]
103 #[serde(rename_all = "camelCase")]
104 pub struct AccountModelKeyState {
105 /// Whether the account service reports a credential for this provider.
106 #[serde(default)]
107 pub configured: bool,
108 /// Service-reported credential state (for example `active`, `invalid`).
109 ///
110 /// Non-secret presentation metadata: it says whether a stored key is
111 /// usable without ever revealing the key. Absent when the service did not
112 /// state one.
113 #[serde(default)]
114 pub state: Option<String>,
115 /// Non-secret label the account holder gave the stored credential.
116 #[serde(default)]
117 pub label: Option<String>,
118 }
119
120 /// Versioned secure-storage envelope shared by every local Codewhale surface.
121 ///
122 /// This type intentionally does not implement `Debug` because `bundle`
123 /// contains access and refresh credentials.
124 #[derive(Clone, Deserialize, Serialize)]
125 #[serde(rename_all = "camelCase")]
126 pub struct StoredAccountAuth {
127 /// Serialized record version.
128 pub schema_version: u8,
129 /// Exact canonical API origin that owns this session.
130 pub api_base: String,
131 /// Secret account bundle held in the secret store.
132 pub bundle: AccountAuthBundle,
133 }
134
135 #[derive(Clone, Deserialize, Serialize)]
136 #[serde(rename_all = "camelCase", deny_unknown_fields)]
137 #[doc = "A session-bound device key held inside the shared private account record."]
138 pub struct AccountDeviceAccess {
139 #[doc = "Stable device UUID scoped to the account profile and API origin."]
140 pub device_id: String,
141 #[doc = "Secret device credential; never include it in runtime receipts or diagnostics."]
142 pub credential: String,
143 #[doc = "Server identifier used to revoke this device key."]
144 pub api_key_id: String,
145 #[doc = "Account that owns the device key."]
146 pub account_id: String,
147 #[doc = "Parent authentication session that authorizes this key."]
148 pub session_id: String,
149 #[doc = "Device-key expiry as Unix seconds, bounded by the parent refresh lifetime."]
150 pub expires_at: i64,
151 }
152
153 /// Normalized account states exposed by the token-free Runtime API contract.
154 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
155 #[serde(rename_all = "snake_case")]
156 pub enum AccountSessionState {
157 /// No valid secure-store session was found for the selected profile/origin.
158 SignedOut,
159 /// The cached session and access credential are within their recorded lifetime.
160 Authenticated,
161 /// Durable identity remains cached, but the access credential has expired.
162 OfflineCached,
163 /// The durable refresh/session lifetime has ended.
164 Expired,
165 /// The stored session carries an explicit revocation receipt.
166 Revoked,
167 }
168
169 /// Token-free account receipt returned by `GET /v1/runtime/info`.
170 #[derive(Debug, Clone, PartialEq, Eq, Serialize)]
171 pub struct RuntimeAccountInfo {
172 /// Runtime account receipt schema version.
173 pub schema_version: u8,
174 /// Current account-session state.
175 pub state: AccountSessionState,
176 /// Exact account API origin used to locate the secure session.
177 pub api_base: String,
178 /// Stable account identifier, present only when read from secure storage.
179 #[serde(skip_serializing_if = "Option::is_none")]
180 pub account_id: Option<String>,
181 /// Durable session identifier, present only when read from secure storage.
182 #[serde(skip_serializing_if = "Option::is_none")]
183 pub session_id: Option<String>,
184 /// Explicit session scopes from secure storage; never inferred from identity.
185 pub scopes: Vec<String>,
186 /// Access-credential expiration, when the stored value is valid RFC 3339.
187 #[serde(skip_serializing_if = "Option::is_none")]
188 pub expires_at: Option<String>,
189 }
190
191 impl RuntimeAccountInfo {
192 /// Build the fail-closed signed-out receipt for an API origin.
193 #[must_use]
194 pub fn signed_out(api_base: impl Into<String>) -> Self {
195 Self {
196 schema_version: ACCOUNT_SESSION_SCHEMA_VERSION,
197 state: AccountSessionState::SignedOut,
198 api_base: api_base.into(),
199 account_id: None,
200 session_id: None,
201 scopes: Vec::new(),
202 expires_at: None,
203 }
204 }
205 }
206
207 /// Failures while selecting, decoding, or validating account session storage.
208 #[derive(Debug, Error)]
209 pub enum AccountSessionError {
210 /// Underlying credential-store failure.
211 #[error(transparent)]
212 Secrets(#[from] SecretsError),
213 /// Stored session JSON could not be decoded.
214 #[error("the local Codewhale account session is unreadable")]
215 UnreadableRecord(#[source] serde_json::Error),
216 /// Stored or newly returned authentication credentials are malformed.
217 #[error("the Codewhale account session contains invalid credentials")]
218 InvalidCredentials,
219 /// No approved secure session backend is available.
220 #[error(
221 "Codewhale account sessions could not open a secret store; check that HOME is writable or set CODEWHALE_HOME to an absolute path"
222 )]
223 SecureStoreUnavailable,
224 }
225
226 /// Profile- and origin-scoped view of the shared account credential record.
227 #[derive(Clone)]
228 pub struct AccountSessionStore {
229 secrets: Secrets,
230 auth_slot: String,
231 api_base: String,
232 }
233
234 /// Opaque account-store revision. Contains credentials; deliberately no Debug.
235 #[derive(Clone)]
236 pub struct AccountSessionSnapshot {
237 raw: Option<String>,
238 slot: String,
239 api_base: String,
240 }
241
242 impl AccountSessionSnapshot {
243 #[doc = "Read validated device custody from this snapshot; the caller checks key expiry."]
244 pub fn device_access(&self) -> Result<Option<AccountDeviceAccess>, AccountSessionError> {
245 let Some(stored) = self.load()? else {
246 return Ok(None);
247 };
248 let value: serde_json::Value =
249 serde_json::from_str(self.raw.as_deref().unwrap_or_default())
250 .map_err(AccountSessionError::UnreadableRecord)?;
251 let Some(access) = value.get("deviceAccess") else {
252 return Ok(None);
253 };
254 let access: AccountDeviceAccess = serde_json::from_value(access.clone())
255 .map_err(AccountSessionError::UnreadableRecord)?;
256 validate_device_access(&stored.bundle, &access)?;
257 Ok(Some(access))
258 }
259
260 #[doc = "Whether the captured slot contains no record, including no logout tombstone."]
261 pub fn is_pristine(&self) -> bool {
262 self.raw.is_none()
263 }
264
265 #[doc = "Project this exact captured revision into token-free account state."]
266 pub fn runtime_info_at(
267 &self,
268 now: DateTime<Utc>,
269 ) -> Result<RuntimeAccountInfo, AccountSessionError> {
270 Ok(match self.load()? {
271 Some(stored) => runtime_account_info_from_stored(stored, now),
272 None => RuntimeAccountInfo::signed_out(self.api_base.clone()),
273 })
274 }
275
276 #[doc = "Hash the slot, API origin and exact record bytes into an opaque revision."]
277 pub fn fingerprint(&self) -> String {
278 let mut digest = Sha256::new();
279 digest.update(b"codewhale-account-revision-v1\0");
280 digest.update(self.slot.as_bytes());
281 digest.update([0]);
282 digest.update(self.api_base.as_bytes());
283 digest.update([0]);
284 if let Some(raw) = &self.raw {
285 digest.update([1]);
286 digest.update(raw.as_bytes());
287 } else {
288 digest.update([0]);
289 }
290 digest
291 .finalize()
292 .iter()
293 .map(|byte| format!("{byte:02x}"))
294 .collect()
295 }
296
297 /// Decode and validate the captured record without re-reading storage.
298 pub fn load(&self) -> Result<Option<StoredAccountAuth>, AccountSessionError> {
299 let Some(raw) = &self.raw else {
300 return Ok(None);
301 };
302 let value: serde_json::Value =
303 serde_json::from_str(raw).map_err(AccountSessionError::UnreadableRecord)?;
304 if value.get("signedOut").is_some() {
305 let signed_out: SignedOutAccount =
306 serde_json::from_value(value).map_err(AccountSessionError::UnreadableRecord)?;
307 if signed_out.schema_version != ACCOUNT_SESSION_SCHEMA_VERSION
308 || signed_out.api_base != self.api_base
309 || !signed_out.signed_out
310 || uuid::Uuid::parse_str(&signed_out.revision).is_err()
311 {
312 return Err(AccountSessionError::InvalidCredentials);
313 }
314 return Ok(None);
315 }
316 let stored: StoredAccountAuth =
317 serde_json::from_value(value).map_err(AccountSessionError::UnreadableRecord)?;
318 if stored.schema_version != ACCOUNT_SESSION_SCHEMA_VERSION
319 || stored.api_base != self.api_base
320 {
321 return Ok(None);
322 }
323 validate_account_auth_bundle(&stored.bundle)?;
324 Ok(Some(stored))
325 }
326 }
327
328 #[derive(Deserialize)]
329 #[serde(rename_all = "camelCase", deny_unknown_fields)]
330 struct SignedOutAccount {
331 schema_version: u8,
332 api_base: String,
333 signed_out: bool,
334 revision: String,
335 }
336
337 fn signed_out_record(api_base: &str) -> String {
338 serde_json::json!({
339 "schemaVersion": ACCOUNT_SESSION_SCHEMA_VERSION,
340 "apiBase": api_base,
341 "signedOut": true,
342 "revision": uuid::Uuid::new_v4().to_string(),
343 })
344 .to_string()
345 }
346
347 fn validate_device_access(
348 bundle: &AccountAuthBundle,
349 access: &AccountDeviceAccess,
350 ) -> Result<(), AccountSessionError> {
351 let now = Utc::now();
352 let parent_expiry = bundle.session.as_ref().and_then(|session| {
353 (!matches!(
354 classify_session_state(session, now),
355 AccountSessionState::Expired | AccountSessionState::Revoked
356 ))
357 .then(|| parse_rfc3339(&session.refresh_expires_at))
358 .flatten()
359 });
360 let credential_valid = access
361 .credential
362 .strip_prefix(&format!("cwc_key_{}_", access.api_key_id))
363 .is_some_and(|suffix| {
364 suffix.len() == 43
365 && suffix
366 .bytes()
367 .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-'))
368 });
369 if access.account_id.is_empty()
370 || access.session_id.is_empty()
371 || bundle.user.as_ref().map(|user| user.id.as_str()) != Some(access.account_id.as_str())
372 || bundle.session.as_ref().map(|session| session.id.as_str())
373 != Some(access.session_id.as_str())
374 || uuid::Uuid::parse_str(&access.device_id).is_err()
375 || access.expires_at <= 0
376 || parent_expiry
377 .is_none_or(|expiry| expiry <= now || access.expires_at > expiry.timestamp())
378 || !credential_valid
379 || access.api_key_id.len() != 24
380 || !access
381 .api_key_id
382 .bytes()
383 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
384 {
385 return Err(AccountSessionError::InvalidCredentials);
386 }
387 Ok(())
388 }
389
390 fn auth_record(
391 api_base: &str,
392 bundle: AccountAuthBundle,
393 previous: Option<&str>,
394 ) -> Result<String, AccountSessionError> {
395 let access = previous
396 .and_then(|raw| serde_json::from_str::<serde_json::Value>(raw).ok())
397 .and_then(|value| value.get("deviceAccess").cloned())
398 .and_then(|value| serde_json::from_value::<AccountDeviceAccess>(value).ok())
399 .filter(|access| validate_device_access(&bundle, access).is_ok());
400 let mut value = serde_json::to_value(StoredAccountAuth {
401 schema_version: ACCOUNT_SESSION_SCHEMA_VERSION,
402 api_base: api_base.into(),
403 bundle,
404 })
405 .map_err(AccountSessionError::UnreadableRecord)?;
406 value["revision"] = uuid::Uuid::new_v4().to_string().into();
407 if let Some(access) = access {
408 value["deviceAccess"] =
409 serde_json::to_value(access).map_err(AccountSessionError::UnreadableRecord)?;
410 }
411 serde_json::to_string(&value).map_err(AccountSessionError::UnreadableRecord)
412 }
413
414 /// Locked account entry. Never reacquire its store lock from a callback.
415 pub struct AccountSessionTransaction<'a> {
416 raw: &'a mut Option<String>,
417 slot: &'a str,
418 api_base: &'a str,
419 }
420 impl AccountSessionTransaction<'_> {
421 #[doc = "Renew the revision while preserving the current authentication state."]
422 pub fn renew_revision(&mut self) -> Result<AccountSessionSnapshot, AccountSessionError> {
423 match self.load()? {
424 Some(stored) => self.replace(stored.bundle)?,
425 None => self.clear(),
426 }
427 Ok(self.snapshot())
428 }
429
430 #[doc = "Store a validated device credential inside this locked account record."]
431 pub fn set_device_access(
432 &mut self,
433 access: AccountDeviceAccess,
434 ) -> Result<(), AccountSessionError> {
435 let Some(stored) = self.load()? else {
436 return Err(AccountSessionError::InvalidCredentials);
437 };
438 validate_device_access(&stored.bundle, &access)?;
439 let raw = auth_record(self.api_base, stored.bundle, None)?;
440 let mut value: serde_json::Value =
441 serde_json::from_str(&raw).map_err(AccountSessionError::UnreadableRecord)?;
442 value["deviceAccess"] =
443 serde_json::to_value(access).map_err(AccountSessionError::UnreadableRecord)?;
444 *self.raw = Some(value.to_string());
445 Ok(())
446 }
447
448 /// Capture the exact current revision without unlocking.
449 pub fn snapshot(&self) -> AccountSessionSnapshot {
450 AccountSessionSnapshot {
451 raw: self.raw.clone(),
452 slot: self.slot.into(),
453 api_base: self.api_base.into(),
454 }
455 }
456 /// Decode the current record; errors may be recovered by explicit logout.
457 pub fn load(&self) -> Result<Option<StoredAccountAuth>, AccountSessionError> {
458 self.snapshot().load()
459 }
460 /// Compare an admitted snapshot without reacquiring the lock.
461 pub fn matches(&self, snapshot: &AccountSessionSnapshot) -> bool {
462 self.slot == snapshot.slot
463 && self.api_base == snapshot.api_base
464 && *self.raw == snapshot.raw
465 }
466 /// Replace this entry on successful transaction completion.
467 pub fn replace(&mut self, bundle: AccountAuthBundle) -> Result<(), AccountSessionError> {
468 validate_account_auth_bundle(&bundle)?;
469 *self.raw = Some(auth_record(self.api_base, bundle, self.raw.as_deref())?);
470 Ok(())
471 }
472 /// Remove this entry on successful transaction completion.
473 pub fn clear(&mut self) {
474 *self.raw = Some(signed_out_record(self.api_base));
475 }
476 }
477
478 impl AccountSessionStore {
479 /// Create a store view for one local profile and one validated API origin.
480 #[must_use]
481 pub fn new(secrets: Secrets, profile: Option<&str>, api_base: &str) -> Self {
482 let profile = normalize_account_profile(profile);
483 let api_base = api_base.trim().trim_end_matches('/').to_string();
484 Self {
485 auth_slot: account_auth_slot(&profile, &api_base),
486 secrets,
487 api_base,
488 }
489 }
490
491 /// Load and validate the selected account session from secure storage.
492 pub fn load(&self) -> Result<Option<StoredAccountAuth>, AccountSessionError> {
493 self.snapshot()?.load()
494 }
495
496 /// Capture exact account-store bytes, including malformed/obsolete records
497 /// so logout can clear only the revision it inspected.
498 pub fn snapshot(&self) -> Result<AccountSessionSnapshot, AccountSessionError> {
499 Ok(AccountSessionSnapshot {
500 raw: self.secrets.get(&self.auth_slot)?,
501 slot: self.auth_slot.clone(),
502 api_base: self.api_base.clone(),
503 })
504 }
505
506 #[doc = "Renew the shared revision to fence older login completions."]
507 pub fn begin_login(&self) -> Result<AccountSessionSnapshot, AccountSessionError> {
508 self.with_transaction(|transaction| transaction.renew_revision())
509 }
510
511 #[doc = "Read or create this profile and API origin's stable device UUID."]
512 pub fn device_id(&self) -> Result<String, AccountSessionError> {
513 let slot =
514 self.auth_slot
515 .replacen("codewhale-cloud-auth-v1-", "codewhale-device-id-v1-", 1);
516 self.secrets
517 .with_entry_transaction(&slot, |raw| {
518 let id = match raw {
519 Some(id) if uuid::Uuid::parse_str(id).is_ok() => id.clone(),
520 Some(_) => {
521 return Err(SecretsError::Keyring(
522 "Invalid Codewhale device identity".into(),
523 ));
524 }
525 None => uuid::Uuid::new_v4().to_string(),
526 };
527 *raw = Some(id.clone());
528 Ok(id)
529 })
530 .map_err(AccountSessionError::from)
531 }
532
533 /// Save a renewed bundle only if the captured session has not changed.
534 /// Returns the exact committed revision, or None on a concurrent change.
535 pub fn save_if_unchanged(
536 &self,
537 expected: &AccountSessionSnapshot,
538 bundle: AccountAuthBundle,
539 ) -> Result<Option<AccountSessionSnapshot>, AccountSessionError> {
540 validate_account_auth_bundle(&bundle)?;
541 if expected.slot != self.auth_slot || expected.api_base != self.api_base {
542 return Err(AccountSessionError::InvalidCredentials);
543 }
544 let raw = auth_record(&self.api_base, bundle, expected.raw.as_deref())?;
545 if !self
546 .secrets
547 .compare_exchange(&self.auth_slot, expected.raw.as_deref(), Some(&raw))?
548 {
549 return Ok(None);
550 }
551 Ok(Some(AccountSessionSnapshot {
552 raw: Some(raw),
553 slot: self.auth_slot.clone(),
554 api_base: self.api_base.clone(),
555 }))
556 }
557
558 /// Remove exactly the captured revision; never erase a newer sign-in.
559 pub fn clear_if_unchanged(
560 &self,
561 expected: &AccountSessionSnapshot,
562 ) -> Result<bool, AccountSessionError> {
563 if expected.slot != self.auth_slot || expected.api_base != self.api_base {
564 return Err(AccountSessionError::InvalidCredentials);
565 }
566 Ok(self.secrets.compare_exchange(
567 &self.auth_slot,
568 expected.raw.as_deref(),
569 Some(&signed_out_record(&self.api_base)),
570 )?)
571 }
572
573 /// Serialize an account lifecycle operation with every backend writer.
574 /// Return errors roll back local changes; no nested store operations allowed.
575 pub fn with_transaction<T, E>(
576 &self,
577 operation: impl FnOnce(&mut AccountSessionTransaction<'_>) -> Result<T, E>,
578 ) -> Result<T, E>
579 where
580 E: From<AccountSessionError>,
581 {
582 let mut outcome = None;
583 let result = self.secrets.with_entry_transaction(&self.auth_slot, |raw| {
584 let mut transaction = AccountSessionTransaction {
585 raw,
586 slot: &self.auth_slot,
587 api_base: &self.api_base,
588 };
589 match operation(&mut transaction) {
590 Ok(value) => {
591 outcome = Some(Ok(value));
592 Ok(())
593 }
594 Err(error) => {
595 outcome = Some(Err(error));
596 Err(SecretsError::Keyring("Account transaction aborted".into()))
597 }
598 }
599 });
600 match outcome {
601 Some(Err(error)) => Err(error),
602 Some(Ok(value)) => {
603 result.map_err(AccountSessionError::from).map_err(E::from)?;
604 Ok(value)
605 }
606 None => {
607 result.map_err(AccountSessionError::from).map_err(E::from)?;
608 Err(E::from(AccountSessionError::InvalidCredentials))
609 }
610 }
611 }
612
613 /// Validate and save an account bundle in the selected secure-store slot.
614 pub fn save(&self, bundle: AccountAuthBundle) -> Result<(), AccountSessionError> {
615 validate_account_auth_bundle(&bundle)?;
616 self.with_transaction(|transaction| transaction.replace(bundle))
617 }
618
619 /// Remove only the selected profile/origin account session.
620 pub fn clear(&self) -> Result<(), AccountSessionError> {
621 self.with_transaction(|transaction| {
622 transaction.clear();
623 Ok(())
624 })
625 }
626
627 /// Read a token-free runtime receipt at a caller-supplied clock instant.
628 pub fn runtime_info_at(
629 &self,
630 now: DateTime<Utc>,
631 ) -> Result<RuntimeAccountInfo, AccountSessionError> {
632 self.snapshot()?.runtime_info_at(now)
633 }
634 }
635
636 /// Select the approved account-session backend shared by CLI, TUI, and Runtime.
637 ///
638 /// Account sessions live in the private `0600` Codewhale secrets file. The OS
639 /// keyring is not used: on macOS every unsigned or rebuilt `codewhale` binary
640 /// is a new Keychain ACL principal, so reading `codewhale-cloud-auth-v1-*`
641 /// under the legacy `deepseek` service pops a password dialog on every start.
642 pub fn secure_account_session_secrets() -> Result<Secrets, AccountSessionError> {
643 Ok(Secrets::file_backed())
644 }
645
646 /// Normalize an optional CLI/TUI profile to the durable account slot label.
647 #[must_use]
648 pub fn normalize_account_profile(profile: Option<&str>) -> String {
649 profile
650 .map(str::trim)
651 .filter(|value| !value.is_empty())
652 .unwrap_or("default")
653 .to_string()
654 }
655
656 /// Derive the opaque secure-store slot for a profile and account API origin.
657 #[must_use]
658 pub fn account_auth_slot(profile: &str, api_base: &str) -> String {
659 let mut digest = Sha256::new();
660 digest.update(profile.as_bytes());
661 digest.update([0]);
662 digest.update(api_base.as_bytes());
663 let digest = digest.finalize();
664 const HEX: &[u8; 16] = b"0123456789abcdef";
665 let mut encoded = String::with_capacity(digest.len() * 2);
666 for byte in digest {
667 encoded.push(HEX[(byte >> 4) as usize] as char);
668 encoded.push(HEX[(byte & 0x0f) as usize] as char);
669 }
670 format!("codewhale-cloud-auth-v1-{encoded}")
671 }
672
673 /// Validate the credential-bearing portion of an account response or record.
674 pub fn validate_account_auth_bundle(bundle: &AccountAuthBundle) -> Result<(), AccountSessionError> {
675 if !bundle.token_type.eq_ignore_ascii_case("bearer")
676 || bundle.access_token.trim().is_empty()
677 || bundle.refresh_token.trim().is_empty()
678 || bundle.access_token.len() > MAX_TOKEN_BYTES
679 || bundle.refresh_token.len() > MAX_TOKEN_BYTES
680 || bundle
681 .access_token
682 .chars()
683 .any(|character| character.is_control() || character.is_whitespace())
684 || bundle
685 .refresh_token
686 .chars()
687 .any(|character| character.is_control() || character.is_whitespace())
688 {
689 return Err(AccountSessionError::InvalidCredentials);
690 }
691 Ok(())
692 }
693
694 fn runtime_account_info_from_stored(
695 stored: StoredAccountAuth,
696 now: DateTime<Utc>,
697 ) -> RuntimeAccountInfo {
698 let account_id = stored
699 .bundle
700 .user
701 .as_ref()
702 .map(|user| user.id.trim())
703 .filter(|value| !value.is_empty())
704 .map(str::to_string);
705 let session = stored.bundle.session.as_ref();
706 let session_id = session
707 .map(|session| session.id.trim())
708 .filter(|value| !value.is_empty())
709 .map(str::to_string);
710 let expires_at = session
711 .map(|session| session.expires_at.trim())
712 .filter(|value| parse_rfc3339(value).is_some())
713 .map(str::to_string);
714 let scopes = normalized_scopes(session.map_or(&[], |session| &session.scopes));
715 let state = session.map_or(AccountSessionState::OfflineCached, |session| {
716 classify_session_state(session, now)
717 });
718 RuntimeAccountInfo {
719 schema_version: ACCOUNT_SESSION_SCHEMA_VERSION,
720 state,
721 api_base: stored.api_base,
722 account_id,
723 session_id,
724 scopes,
725 expires_at,
726 }
727 }
728
729 fn classify_session_state(session: &AccountSession, now: DateTime<Utc>) -> AccountSessionState {
730 let explicit = session.status.trim().to_ascii_lowercase();
731 if explicit == "revoked" || !session.revoked_at.trim().is_empty() {
732 return AccountSessionState::Revoked;
733 }
734 if explicit == "expired"
735 || parse_rfc3339(&session.refresh_expires_at).is_some_and(|expiry| expiry <= now)
736 {
737 return AccountSessionState::Expired;
738 }
739 if explicit == "offline_cached"
740 || parse_rfc3339(&session.expires_at).is_some_and(|expiry| expiry <= now)
741 {
742 return AccountSessionState::OfflineCached;
743 }
744 AccountSessionState::Authenticated
745 }
746
747 fn parse_rfc3339(value: &str) -> Option<DateTime<Utc>> {
748 DateTime::parse_from_rfc3339(value.trim())
749 .ok()
750 .map(|value| value.with_timezone(&Utc))
751 }
752
753 fn normalized_scopes(scopes: &[String]) -> Vec<String> {
754 let mut scopes = scopes
755 .iter()
756 .map(|scope| scope.trim())
757 .filter(|scope| {
758 !scope.is_empty()
759 && scope.len() <= MAX_SCOPE_BYTES
760 && scope.bytes().all(|byte| {
761 byte.is_ascii_alphanumeric() || matches!(byte, b':' | b'.' | b'_' | b'-' | b'/')
762 })
763 })
764 .map(str::to_string)
765 .collect::<Vec<_>>();
766 scopes.sort();
767 scopes.dedup();
768 scopes.truncate(MAX_SCOPES);
769 scopes
770 }
771
772 #[cfg(test)]
773 mod tests {
774 use super::*;
775 use std::sync::Arc;
776
777 use crate::InMemoryKeyringStore;
778
779 /// Account sessions must never touch the OS keyring. Unsigned rebuilds
780 /// on macOS otherwise prompt on every `codewhale web` / TUI start.
781 #[test]
782 fn session_secrets_use_the_file_store_not_keychain() {
783 let _lock = crate::tests::env_lock();
784 let dir = tempfile::TempDir::new().expect("tempdir");
785 let home = dir.path().join("codewhale-home");
786 std::fs::create_dir_all(&home).expect("home");
787 unsafe { std::env::set_var("CODEWHALE_HOME", &home) };
788 unsafe { std::env::remove_var("CODEWHALE_SECRET_BACKEND") };
789 unsafe { std::env::remove_var("DEEPSEEK_SECRET_BACKEND") };
790 let secrets =
791 secure_account_session_secrets().expect("session secrets must resolve without opt-in");
792 let name = secrets.backend_name();
793 assert!(
794 name.to_lowercase().contains("file"),
795 "account sessions must not use Keychain: {name}"
796 );
797 assert!(!name.to_lowercase().contains("keychain"));
798 assert!(!name.to_lowercase().contains("keyring"));
799 }
800
801 fn auth(
802 account_id: &str,
803 session_id: &str,
804 expires_at: &str,
805 refresh_expires_at: &str,
806 ) -> AccountAuthBundle {
807 AccountAuthBundle {
808 token_type: "Bearer".to_string(),
809 access_token: "access-never-serialize".to_string(),
810 refresh_token: "refresh-never-serialize".to_string(),
811 session: Some(AccountSession {
812 id: session_id.to_string(),
813 scopes: vec!["identity:read".to_string(), "session:sync".to_string()],
814 expires_at: expires_at.to_string(),
815 refresh_expires_at: refresh_expires_at.to_string(),
816 ..AccountSession::default()
817 }),
818 user: Some(AccountUser {
819 id: account_id.to_string(),
820 email: "private@example.test".to_string(),
821 ..AccountUser::default()
822 }),
823 }
824 }
825
826 fn test_store() -> (Secrets, Arc<InMemoryKeyringStore>) {
827 let store = Arc::new(InMemoryKeyringStore::new());
828 (Secrets::new(store.clone()), store)
829 }
830
831 #[test]
832 fn runtime_receipt_is_token_free_and_preserves_only_explicit_scopes() {
833 let (secrets, _) = test_store();
834 let store = AccountSessionStore::new(secrets, Some("work"), "https://api.codewhale.net");
835 store
836 .save(auth(
837 "acct-1",
838 "session-1",
839 "2030-01-01T00:00:00Z",
840 "2031-01-01T00:00:00Z",
841 ))
842 .unwrap();
843
844 let info = store.runtime_info_at(Utc::now()).unwrap();
845 assert_eq!(info.state, AccountSessionState::Authenticated);
846 assert_eq!(info.account_id.as_deref(), Some("acct-1"));
847 assert_eq!(info.session_id.as_deref(), Some("session-1"));
848 assert_eq!(info.scopes, ["identity:read", "session:sync"]);
849 let json = serde_json::to_string(&info).unwrap();
850 for secret in [
851 "access-never-serialize",
852 "refresh-never-serialize",
853 "private@example.test",
854 ] {
855 assert!(!json.contains(secret));
856 }
857 }
858
859 #[test]
860 fn profiles_and_origins_preserve_same_account_and_cross_account_isolation() {
861 let (secrets, _) = test_store();
862 let default = AccountSessionStore::new(secrets.clone(), None, "https://api.codewhale.net");
863 let work =
864 AccountSessionStore::new(secrets.clone(), Some("work"), "https://api.codewhale.net");
865 let local = AccountSessionStore::new(secrets, None, "http://127.0.0.1:8787");
866 default.save(auth("acct-a", "session-a", "", "")).unwrap();
867 work.save(auth("acct-a", "session-b", "", "")).unwrap();
868 local.save(auth("acct-b", "session-c", "", "")).unwrap();
869
870 let now = Utc::now();
871 assert_eq!(
872 default.runtime_info_at(now).unwrap().account_id.as_deref(),
873 Some("acct-a")
874 );
875 assert_eq!(
876 work.runtime_info_at(now).unwrap().account_id.as_deref(),
877 Some("acct-a")
878 );
879 assert_eq!(
880 local.runtime_info_at(now).unwrap().account_id.as_deref(),
881 Some("acct-b")
882 );
883 default.clear().unwrap();
884 assert_eq!(
885 default.runtime_info_at(now).unwrap().state,
886 AccountSessionState::SignedOut
887 );
888 assert_eq!(
889 work.runtime_info_at(now).unwrap().state,
890 AccountSessionState::Authenticated
891 );
892 }
893
894 #[test]
895 fn signed_out_expired_offline_and_revoked_states_are_distinct() {
896 let (secrets, _) = test_store();
897 let store = AccountSessionStore::new(secrets, None, DEFAULT_ACCOUNT_API_BASE);
898 let now = DateTime::parse_from_rfc3339("2029-01-01T00:00:00Z")
899 .unwrap()
900 .with_timezone(&Utc);
901 assert_eq!(
902 store.runtime_info_at(now).unwrap().state,
903 AccountSessionState::SignedOut
904 );
905
906 store
907 .save(auth(
908 "acct",
909 "offline",
910 "2028-12-31T23:59:59Z",
911 "2029-12-31T23:59:59Z",
912 ))
913 .unwrap();
914 assert_eq!(
915 store.runtime_info_at(now).unwrap().state,
916 AccountSessionState::OfflineCached
917 );
918
919 store
920 .save(auth(
921 "acct",
922 "expired",
923 "2028-12-31T23:59:59Z",
924 "2028-12-31T23:59:59Z",
925 ))
926 .unwrap();
927 assert_eq!(
928 store.runtime_info_at(now).unwrap().state,
929 AccountSessionState::Expired
930 );
931
932 let mut revoked = auth("acct", "revoked", "2030-01-01T00:00:00Z", "");
933 revoked.session.as_mut().unwrap().status = "revoked".to_string();
934 store.save(revoked).unwrap();
935 assert_eq!(
936 store.runtime_info_at(now).unwrap().state,
937 AccountSessionState::Revoked
938 );
939 }
940 }
941
942 /// Keep device custody tied to the account session, inside the file store's
943 /// existing transaction. Refreshing access tokens within that owner preserves it.
944 pub(crate) fn invalidate_device_companion(
945 entries: &mut std::collections::HashMap<String, String>,
946 slot: &str,
947 replacement: Option<&str>,
948 ) {
949 let Some(suffix) = slot.strip_prefix("codewhale-cloud-auth-v1-") else {
950 return;
951 };
952 if suffix.len() != 64 || !suffix.bytes().all(|c| c.is_ascii_hexdigit()) {
953 return;
954 }
955 fn identity(raw: &str) -> Option<(String, String, String)> {
956 let stored: StoredAccountAuth = serde_json::from_str(raw).ok()?;
957 if stored.schema_version != ACCOUNT_SESSION_SCHEMA_VERSION {
958 return None;
959 }
960 let account = stored.bundle.user?.id;
961 let session = stored.bundle.session?.id;
962 if stored.api_base.is_empty() || account.is_empty() || session.is_empty() {
963 return None;
964 }
965 Some((stored.api_base, account, session))
966 }
967 let old = entries.get(slot).and_then(|raw| identity(raw));
968 let next = replacement.and_then(identity);
969 if old.is_none() || old != next {
970 entries.remove(&format!("codewhale-cloud-device-v1-{suffix}"));
971 }
972 }
973
974 #[cfg(test)]
975 mod snapshot_tests {
976 use super::*;
977 use std::sync::Arc;
978 fn bundle(id: &str) -> AccountAuthBundle {
979 AccountAuthBundle {
980 token_type: "Bearer".into(),
981 access_token: format!("access-{id}"),
982 refresh_token: format!("refresh-{id}"),
983 session: Some(AccountSession {
984 id: id.into(),
985 expires_at: "2099-01-01T00:00:00Z".into(),
986 refresh_expires_at: "2100-01-01T00:00:00Z".into(),
987 ..Default::default()
988 }),
989 user: Some(AccountUser {
990 id: id.into(),
991 ..Default::default()
992 }),
993 }
994 }
995 #[test]
996 fn exact_revision_cas_rejects_late_replace_and_clear_on_file_and_memory() {
997 let dir = tempfile::tempdir().unwrap();
998 for secrets in [
999 Secrets::new(Arc::new(crate::InMemoryKeyringStore::new())),
1000 Secrets::new(Arc::new(crate::FileKeyringStore::new(
1001 dir.path().join("secrets.json"),
1002 ))),
1003 ] {
1004 let store = AccountSessionStore::new(secrets, None, DEFAULT_ACCOUNT_API_BASE);
1005 let pristine = store.snapshot().unwrap();
1006 assert!(pristine.is_pristine());
1007 let first_login = store.begin_login().unwrap();
1008 assert!(first_login.load().unwrap().is_none());
1009 store.clear().unwrap();
1010 let signed_out = store.snapshot().unwrap();
1011 assert!(!signed_out.is_pristine());
1012 assert_ne!(pristine.fingerprint(), signed_out.fingerprint());
1013 assert_ne!(first_login.fingerprint(), signed_out.fingerprint());
1014 assert!(
1015 store
1016 .save_if_unchanged(&pristine, bundle("late-pristine-login"))
1017 .unwrap()
1018 .is_none()
1019 );
1020 assert!(
1021 store
1022 .save_if_unchanged(&first_login, bundle("late-claimed-login"))
1023 .unwrap()
1024 .is_none()
1025 );
1026 store.save(bundle("old")).unwrap();
1027 store
1028 .with_transaction(|transaction| {
1029 transaction.set_device_access(AccountDeviceAccess {
1030 device_id: uuid::Uuid::new_v4().to_string(),
1031 credential: format!("cwc_key_{}_{}", "b".repeat(24), "A".repeat(43)),
1032 api_key_id: "b".repeat(24),
1033 account_id: "old".into(),
1034 session_id: "old".into(),
1035 expires_at: Utc::now().timestamp() + 3600,
1036 })
1037 })
1038 .unwrap();
1039 store.save(bundle("old")).unwrap();
1040 assert!(store.snapshot().unwrap().device_access().unwrap().is_some());
1041 let old = store.snapshot().unwrap();
1042 let other = store.clone();
1043 std::thread::spawn(move || other.save(bundle("new")))
1044 .join()
1045 .unwrap()
1046 .unwrap();
1047 assert!(
1048 store
1049 .save_if_unchanged(&old, bundle("stale-refresh"))
1050 .unwrap()
1051 .is_none()
1052 );
1053 assert!(!store.clear_if_unchanged(&old).unwrap());
1054 assert_eq!(
1055 store.load().unwrap().unwrap().bundle.user.unwrap().id,
1056 "new"
1057 );
1058 assert!(store.snapshot().unwrap().device_access().unwrap().is_none());
1059 let latest = store.snapshot().unwrap();
1060 assert!(store.clear_if_unchanged(&latest).unwrap());
1061 assert!(store.load().unwrap().is_none());
1062 assert!(store.snapshot().unwrap().device_access().unwrap().is_none());
1063 }
1064 }
1065 #[test]
1066 fn snapshot_compares_original_unknown_fields_and_scopes_store_identity() {
1067 let secrets = Secrets::new(Arc::new(crate::InMemoryKeyringStore::new()));
1068 let store = AccountSessionStore::new(secrets.clone(), None, DEFAULT_ACCOUNT_API_BASE);
1069 store.save(bundle("account")).unwrap();
1070 let slot = account_auth_slot("default", DEFAULT_ACCOUNT_API_BASE);
1071 let mut value: serde_json::Value =
1072 serde_json::from_str(&secrets.get(&slot).unwrap().unwrap()).unwrap();
1073 value["futureField"] = true.into();
1074 secrets.set(&slot, &value.to_string()).unwrap();
1075 let snapshot = store.snapshot().unwrap();
1076 let other =
1077 AccountSessionStore::new(secrets.clone(), Some("other"), DEFAULT_ACCOUNT_API_BASE);
1078 assert!(other.clear_if_unchanged(&snapshot).is_err());
1079 assert!(
1080 store
1081 .save_if_unchanged(&snapshot, bundle("account"))
1082 .unwrap()
1083 .is_some()
1084 );
1085 secrets.set(&slot, "malformed").unwrap();
1086 let corrupt = store.snapshot().unwrap();
1087 assert!(corrupt.load().is_err());
1088 assert!(store.clear_if_unchanged(&corrupt).unwrap());
1089 }
1090 }
1091
1091 lines RUST