docs(comments): rewrite comments across all crates to the guidelines
Sweep every first-party crate source (1956 .rs files) to the project comment guidelines: delete redundant restatements, decorative banners, change narration, and end-of-line comments; keep and tighten the crucial ones (invariants, bug rationale, SAFETY blocks, ported-source attribution). No functional code changed. Every edit is proven comment-only against the prior tree by a comment-stripping lexer (string/char/raw-string aware) plus a separate doctest-fence check. Where removing a comment made rustfmt or clippy want to re-lay-out adjacent code, the minimal triggering comment is restored so code tokens stay byte-identical. Gates green: cargo fmt --all --check (0 diffs), cargo check and cargo clippy --workspace --all-targets (0 warnings). Adds scripts/check_codegen_comment_guidelines.py — the enforcement gate for these guidelines (flags banners, end-of-line comments, change narration, and commented-out code).
This commit is contained in:
1 parent
ff0fb56c67
commit
a02b555e66
1458 files changed
+10729
-21750
No files matched your search
@@ -58,7 +58,6 @@ use crate::auth::{AuthManager, TOKEN_TTL, token_suffix};
|
||||
#[cfg(test)]
|
||||
static EMIT_COUNT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
|
||||
/// Read the test-only emit counter.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn test_emit_count() -> u64 {
|
||||
EMIT_COUNT.load(std::sync::atomic::Ordering::SeqCst)
|
||||
@@ -341,7 +340,7 @@ pub(crate) fn record_auth_401(
|
||||
EMIT_COUNT.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
|
||||
}
|
||||
|
||||
/// Pure (no I/O) computation of the attribution payload. Extracted
|
||||
/// Pure (no I/O) computation of the attribution payload, kept separate
|
||||
/// from [`record_auth_401`] so unit tests can assert each field
|
||||
/// directly without reaching into `unified_log`'s file writer or the
|
||||
/// tracing layer.
|
||||
@@ -467,8 +466,6 @@ mod tests {
|
||||
payload_field(&payload, "current_key_prefix"),
|
||||
"567890abcdef"
|
||||
);
|
||||
// mint_age_seconds: should be small and non-negative for a
|
||||
// freshly-created auth.
|
||||
let mint = payload_field(&payload, "mint_age_seconds")
|
||||
.as_i64()
|
||||
.unwrap();
|
||||
@@ -476,8 +473,6 @@ mod tests {
|
||||
(0..5).contains(&mint),
|
||||
"mint_age_seconds should be 0-5 sec for a freshly-created auth, got {mint}"
|
||||
);
|
||||
// expires_at_seconds_from_now: should be just under 1 hour
|
||||
// (3600s), with a tolerance for elapsed time during the test.
|
||||
let expires = payload_field(&payload, "expires_at_seconds_from_now")
|
||||
.as_i64()
|
||||
.unwrap();
|
||||
@@ -543,7 +538,6 @@ mod tests {
|
||||
|
||||
let payload = compute_attribution_payload(&am, "Test.legacy", Some("k"));
|
||||
|
||||
// mint_age_seconds: ~60.
|
||||
let mint = payload_field(&payload, "mint_age_seconds")
|
||||
.as_i64()
|
||||
.unwrap();
|
||||
@@ -551,8 +545,6 @@ mod tests {
|
||||
(60..=70).contains(&mint),
|
||||
"mint_age_seconds should be ~60 for a 60s-old auth, got {mint}"
|
||||
);
|
||||
// expires_at_seconds_from_now: TOKEN_TTL minus 60s = roughly
|
||||
// 30 * 86400 - 60 = 2_591_940. Tolerate ~10s drift.
|
||||
let expires = payload_field(&payload, "expires_at_seconds_from_now")
|
||||
.as_i64()
|
||||
.unwrap();
|
||||
|
||||
@@ -13,14 +13,11 @@ use serde::{Deserialize, Serialize};
|
||||
pub const KIMI_CODE_OAUTH_SCOPE: &str = "oauth/kimi-code";
|
||||
|
||||
/// Auth configuration block (`[kimi_code_config]` in the agent config).
|
||||
/// Currently empty: the OAuth host and client id are fixed by the
|
||||
/// environment crate.
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct KimiCodeConfig {}
|
||||
|
||||
impl KimiCodeConfig {
|
||||
/// The persisted-credential scope key for this configuration.
|
||||
pub fn auth_scope(&self) -> String {
|
||||
KIMI_CODE_OAUTH_SCOPE.to_owned()
|
||||
}
|
||||
|
||||
@@ -2,10 +2,10 @@
|
||||
//!
|
||||
//! One authority answers, for every outgoing inference request, the only
|
||||
//! question that matters: **which credential — if any — may ride it?**
|
||||
//! ([`CredentialAuthority::credential_class`]). Before this module the answer was
|
||||
//! re-derived — differently — at every call site (`ModelsManager`, `MvpAgent`,
|
||||
//! `SessionActor`, the aux/summary/subagent paths), and three separate rounds
|
||||
//! of fixes each closed some sites and missed others.
|
||||
//! ([`CredentialAuthority::credential_class`]). Every credential sink
|
||||
//! (`ModelsManager`, `MvpAgent`, `SessionActor`, the aux/summary/subagent
|
||||
//! paths) funnels through this one rule, so none can derive the answer
|
||||
//! differently and leak a bearer.
|
||||
//!
|
||||
//! # How omission is structurally prevented
|
||||
//!
|
||||
@@ -27,9 +27,8 @@
|
||||
//! through the identical rule as the `api_key` sink.
|
||||
//! 4. A guard asks [`CredentialAuthority::credential_class`] and MATCHES on the
|
||||
//! answer. There is no second, similarly-named boolean to pick by mistake:
|
||||
//! the round-3 defect (C1) was `takes_session_credential` — *may **a**
|
||||
//! session credential ride?* — paired with a hand-carried PRIMARY bearer,
|
||||
//! and the two predicates that made that pairing expressible are gone.
|
||||
//! C1 was `takes_session_credential` — *may **a** session credential
|
||||
//! ride?* — misread as license to hand-carry the PRIMARY bearer.
|
||||
//!
|
||||
//! SECURITY: no token is ever logged, `Debug`-printed or `Display`ed here.
|
||||
|
||||
@@ -67,12 +66,12 @@ impl SessionCredential {
|
||||
/// WHICH credential — if any — may ride a request routed to a given
|
||||
/// `(platform, base_url)` pair.
|
||||
///
|
||||
/// ONE question with three answers, replacing the two look-alike booleans
|
||||
/// `takes_session_credential` / `takes_primary_credential` (identical
|
||||
/// ONE question with three answers, not two look-alike booleans
|
||||
/// (`takes_session_credential` / `takes_primary_credential`: identical
|
||||
/// signatures, near-identical names, opposite answers on a subscription host).
|
||||
/// C1 was caused by asking the first and stamping the credential the second
|
||||
/// describes; with a single classifier a call site must MATCH on the answer, so
|
||||
/// that mistake is no longer expressible.
|
||||
/// that mistake is not expressible.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum CredentialClass {
|
||||
/// `platform`'s OWN pooled subscription-OAuth token, at its own registry
|
||||
@@ -135,7 +134,8 @@ impl CredentialAuthority {
|
||||
/// github-copilot, xai-grok) rides ITS OWN pooled manager — never the
|
||||
/// primary — and only to its own registry host (L10: a
|
||||
/// `[model."claude-pro-max/x"]` override keeps `info.id` but can point
|
||||
/// `base_url` anywhere, and used to ship the Claude OAuth bearer there);
|
||||
/// `base_url` anywhere, and would otherwise ship the Claude OAuth bearer
|
||||
/// there);
|
||||
/// - `kimi-code` — the one `uses_oauth` platform with no `OAuthConfig` —
|
||||
/// rides the PRIMARY session, and only at the session's own effective
|
||||
/// coding endpoint;
|
||||
@@ -273,15 +273,12 @@ impl CredentialAuthority {
|
||||
/// M5: a slug that is NOT in the catalog resolves through the SAME endpoint
|
||||
/// rule against the aux fallback endpoint
|
||||
/// (`EndpointsConfig::resolve_inference_base_url`, which is exactly where
|
||||
/// `resolve_aux_model_sampling_config`'s Tier-2 entry routes) instead of
|
||||
/// being handed the primary unconditionally — the old "first-party by
|
||||
/// construction" justification was false once `models_base_url` could point
|
||||
/// anywhere.
|
||||
/// `resolve_aux_model_sampling_config`'s Tier-2 entry routes), not handed
|
||||
/// the primary unconditionally: `models_base_url` can point anywhere, so an
|
||||
/// off-catalog slug is not first-party by construction.
|
||||
///
|
||||
/// M6: the platform and the base URL come from ONE
|
||||
/// [`crate::agent::models::entry_for_slug`] lookup, so they can no longer
|
||||
/// disagree (the aux path used to resolve the platform with `current_key`
|
||||
/// and the credential with a separate `find_model_by_id`).
|
||||
/// [`crate::agent::models::entry_for_slug`] lookup, so they cannot disagree.
|
||||
pub(crate) fn credential_for_slug(
|
||||
&self,
|
||||
models: &indexmap::IndexMap<String, ModelEntry>,
|
||||
@@ -491,9 +488,6 @@ mod tests {
|
||||
|
||||
/// C1 — a subscription platform's own host DOES take a session credential,
|
||||
/// but it is that platform's POOLED token, never the primary / house key.
|
||||
/// Two look-alike booleans used to encode this, and picking the wrong one is
|
||||
/// the whole defect; one classifier makes the distinction impossible to
|
||||
/// mis-read.
|
||||
#[test]
|
||||
fn a_subscription_host_classifies_pooled_never_primary() {
|
||||
let (_d, kimi) = primary("kimi-tok");
|
||||
|
||||
@@ -200,8 +200,7 @@ mod tests {
|
||||
);
|
||||
assert!(snap.user_id.is_none());
|
||||
}
|
||||
/// 401 recovery routes through `unauthorized_recovery` (pre-fix
|
||||
/// it no-oped because the refresher arg was hardcoded `None`).
|
||||
/// 401 recovery routes through `unauthorized_recovery`.
|
||||
#[tokio::test]
|
||||
async fn refresh_after_unauthorized_drives_recovery_state_machine() {
|
||||
let _guard = EarlyInvalidationGuard::pin_to_default();
|
||||
@@ -304,8 +303,6 @@ mod tests {
|
||||
.snapshot();
|
||||
assert!(oidc.deployment_id.is_none() && oidc.api_key_id.is_none());
|
||||
}
|
||||
/// Bootstrap mode: `snapshot()` re-reads disk so sibling-rotated
|
||||
/// tokens are picked up without a live AuthManager.
|
||||
#[test]
|
||||
fn deployment_key_wins_over_resolved_user_token() {
|
||||
let _guard = EarlyInvalidationGuard::pin_to_default();
|
||||
|
||||
@@ -260,7 +260,6 @@ mod tests {
|
||||
let created = load_or_create_device_id(&path).unwrap();
|
||||
assert_eq!(created.len(), 32, "uuid4 hex is 32 chars: {created:?}");
|
||||
assert!(created.chars().all(|c| c.is_ascii_hexdigit()));
|
||||
// Second call reads the same id back.
|
||||
let reread = load_or_create_device_id(&path).unwrap();
|
||||
assert_eq!(created, reread);
|
||||
#[cfg(unix)]
|
||||
|
||||
@@ -23,9 +23,9 @@ use crate::auth::{AuthChannels, AuthManager, AuthUrlInfo, AuthUrlMode, KimiAuth}
|
||||
const SLOW_DOWN_INCREMENT_SECS: u64 = 5;
|
||||
|
||||
/// The wire behind a device-code login. The `Kimi` arm calls the bespoke Kimi
|
||||
/// Code wire (X-Msh headers, `/api/oauth/*`) verbatim — byte-identical to the
|
||||
/// pre-generalization path; the `Generic` arm drives a registry
|
||||
/// [`OAuthConfig`] provider (xai-grok) through [`crate::auth::oauth_device`].
|
||||
/// Code wire (X-Msh headers, `/api/oauth/*`) verbatim; the `Generic` arm
|
||||
/// drives a registry [`OAuthConfig`] provider (xai-grok) through
|
||||
/// [`crate::auth::oauth_device`].
|
||||
enum DeviceFlowBackend<'a> {
|
||||
Kimi {
|
||||
host: &'a str,
|
||||
@@ -280,7 +280,8 @@ mod tests {
|
||||
"verification_uri": "https://www.kimi.com/code/authorize_device",
|
||||
"verification_uri_complete": "https://www.kimi.com/code/authorize_device?user_code=WXYZ-6789",
|
||||
"expires_in": 1800,
|
||||
"interval": 0, // floored to 1s by the poll loop
|
||||
// floored to 1s by the poll loop
|
||||
"interval": 0,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -6,7 +6,6 @@ pub enum AuthError {
|
||||
#[error("Not logged in. Run `kigi login`.")]
|
||||
NotLoggedIn,
|
||||
|
||||
/// Token expired and no refresh authority available.
|
||||
#[error("Token expired. Run `kigi login` to re-authenticate.")]
|
||||
TokenExpiredNoRefresh,
|
||||
|
||||
@@ -14,7 +13,6 @@ pub enum AuthError {
|
||||
#[error("Authentication rejected by server. Run `kigi login` to re-authenticate.")]
|
||||
ServerRejectedNoRecovery,
|
||||
|
||||
/// All recovery strategies exhausted.
|
||||
#[error("Auth recovery exhausted; re-authentication required.")]
|
||||
RecoveryExhausted,
|
||||
|
||||
|
||||
@@ -405,7 +405,6 @@ pub async fn ensure_authenticated(
|
||||
let kigi_home = kigi_home::kigi_home();
|
||||
let auth_manager = Arc::new(AuthManager::new(&kigi_home, kimi_code_config.clone()));
|
||||
|
||||
// If not re-authing, accept any valid cached credential.
|
||||
if !reauth && let Some(auth) = auth_manager.current() {
|
||||
return Ok(auth);
|
||||
}
|
||||
@@ -587,8 +586,6 @@ mod tests {
|
||||
assert!(expired_refreshable_session(&mgr).is_none());
|
||||
}
|
||||
|
||||
// ── run_auth_flow: expired path with persisted token ─────────────
|
||||
|
||||
/// When the in-memory token is expired but the store has a valid token,
|
||||
/// run_auth_flow should return the stored token without interactive login.
|
||||
#[tokio::test]
|
||||
|
||||
@@ -119,7 +119,6 @@ fn oauth_url(host: &str, path: &str) -> String {
|
||||
format!("{}{path}", host.trim_end_matches('/'))
|
||||
}
|
||||
|
||||
/// Attach the device-identity headers to a request.
|
||||
fn with_device_headers(
|
||||
mut builder: reqwest::RequestBuilder,
|
||||
) -> anyhow::Result<reqwest::RequestBuilder> {
|
||||
|
||||
@@ -105,14 +105,6 @@ struct ScopedRefreshFailure {
|
||||
/// minutes" (a suspend doesn't extend it).
|
||||
const PERMANENT_FAILURE_TTL: StdDuration = StdDuration::from_secs(300);
|
||||
|
||||
/// Single source of truth for `auth.json` + the in-memory bearer.
|
||||
///
|
||||
/// Lock order: `refresh_lock` (async) -> the sync locks (`inner` / `refresher`
|
||||
/// / `permanent_failure`), never co-held; `permanent_failure()`
|
||||
/// reads `permanent_failure` first and only then `inner` (via
|
||||
/// `attempted_tombstone_key`, when a tombstone is stored), never co-held. Never hold
|
||||
/// a `parking_lot` guard across `.await`. Refreshers return [`RefreshOutcome`]
|
||||
/// for `refresh_chain` to apply.
|
||||
/// Whether a manager rooted at `path` may use the OS keyring for `scope`.
|
||||
///
|
||||
/// The keyring entry (`service kigi / oauth/kimi-code`) is global per OS
|
||||
@@ -144,6 +136,14 @@ pub(crate) fn set_test_force_keyring_path_scope(on: bool) {
|
||||
TEST_FORCE_KEYRING_PATH_SCOPE.with(|flag| flag.set(on));
|
||||
}
|
||||
|
||||
/// Single source of truth for `auth.json` + the in-memory bearer.
|
||||
///
|
||||
/// Lock order: `refresh_lock` (async) -> the sync locks (`inner` / `refresher`
|
||||
/// / `permanent_failure`), never co-held; `permanent_failure()`
|
||||
/// reads `permanent_failure` first and only then `inner` (via
|
||||
/// `attempted_tombstone_key`, when a tombstone is stored), never co-held. Never hold
|
||||
/// a `parking_lot` guard across `.await`. Refreshers return [`RefreshOutcome`]
|
||||
/// for `refresh_chain` to apply.
|
||||
pub struct AuthManager {
|
||||
/// In-memory bearer. Mutate via [`Self::with_inner_write`] or
|
||||
/// [`Self::refresh_chain`]; the closure helpers' sync return type
|
||||
@@ -274,8 +274,6 @@ enum LockOutcome {
|
||||
Adopted(Box<KimiAuth>),
|
||||
}
|
||||
|
||||
// ── Construction + builders ──────────────────────────────────────────
|
||||
|
||||
impl AuthManager {
|
||||
pub fn new(kigi_home: &Path, kimi_code_config: KimiCodeConfig) -> Self {
|
||||
let scope = kimi_code_config.auth_scope();
|
||||
@@ -478,8 +476,6 @@ impl AuthManager {
|
||||
}
|
||||
}
|
||||
|
||||
// ── State mutation (clear, hot_swap, update) ──────────────────────
|
||||
|
||||
pub(crate) fn clear(&self) -> std::io::Result<()> {
|
||||
self.remove_scope(&self.scope)
|
||||
}
|
||||
@@ -508,7 +504,7 @@ impl AuthManager {
|
||||
tracing::warn!(error = %e, "auth: failed to remove session credential from keyring");
|
||||
}
|
||||
let disk_mutation = if let Some(_lock) = lock::try_lock_auth_file_nonblocking(&self.path) {
|
||||
self.write_scope_removal(scope)? // lock released on drop
|
||||
self.write_scope_removal(scope)?
|
||||
} else {
|
||||
ScopeRemoval::SkippedLockUnavailable
|
||||
};
|
||||
@@ -651,8 +647,6 @@ impl AuthManager {
|
||||
self.clear_inner();
|
||||
}
|
||||
|
||||
// ── Read methods ─────────────────────────────────────────────────
|
||||
//
|
||||
// | wire-bound bearer | `auth().await` / `get_valid_token().await` |
|
||||
// | cached, no refresh | `current()` (5-min buffer) |
|
||||
// | any in-memory bearer | `current_or_expired()` |
|
||||
@@ -723,8 +717,6 @@ impl AuthManager {
|
||||
is_expired_with_buffer(auth, Duration::zero())
|
||||
}
|
||||
|
||||
// ── Persistence ───────────────────────────────────────────────────
|
||||
|
||||
/// Persist rotated tokens (keyring → file fallback) + cache.
|
||||
///
|
||||
/// Invariants:
|
||||
@@ -781,7 +773,6 @@ impl AuthManager {
|
||||
}
|
||||
};
|
||||
let mut map = map;
|
||||
// One entry per scope.
|
||||
tracing::debug!(scope = %self.scope, "auth: storing token");
|
||||
map.insert(self.scope.clone(), auth.clone());
|
||||
let write_result = write_auth_json(&self.path, &map);
|
||||
@@ -821,7 +812,8 @@ impl AuthManager {
|
||||
/// the auth-file lock on the mutation paths that matter.
|
||||
fn strip_scope_from_file_best_effort(&self) {
|
||||
let Ok(mut map) = read_auth_json(&self.path) else {
|
||||
return; // missing/corrupt file: nothing to strip
|
||||
// missing/corrupt file: nothing to strip
|
||||
return;
|
||||
};
|
||||
if map.remove(&self.scope).is_none() {
|
||||
return;
|
||||
@@ -888,8 +880,6 @@ impl AuthManager {
|
||||
self.clear_inner();
|
||||
}
|
||||
|
||||
// ── Disk I/O helpers ──────────────────────────────────────────────
|
||||
|
||||
/// Accept a sibling-rotated disk token. On `ServerRejected`, the
|
||||
/// disk key must differ from in-memory (else no one refreshed).
|
||||
pub(crate) fn try_use_disk_token(
|
||||
@@ -915,8 +905,7 @@ impl AuthManager {
|
||||
|
||||
/// Re-read disk and try to adopt a sibling-written token, emitting
|
||||
/// telemetry on success. Combines `read_disk_auth` +
|
||||
/// `try_use_disk_token` + the structured log that was previously
|
||||
/// duplicated at each callsite in `refresh_chain`.
|
||||
/// `try_use_disk_token` + the structured adoption log.
|
||||
fn try_adopt_disk_token(&self, reason: RefreshReason, msg: &str) -> Option<KimiAuth> {
|
||||
let disk_auth = self.read_disk_auth();
|
||||
let refreshed = self.try_use_disk_token(disk_auth.as_ref(), reason)?;
|
||||
@@ -1105,8 +1094,6 @@ impl AuthManager {
|
||||
try_lock_auth_file_async(&self.path, timeout).await
|
||||
}
|
||||
|
||||
// ── Refresher setup ─────────────────────────────────────────────
|
||||
|
||||
/// Set up refresh capability. Call once per `Arc<AuthManager>` at
|
||||
/// startup; subsequent calls are no-op via an atomic guard (so
|
||||
/// per-session call sites don't reset refresher-internal state).
|
||||
@@ -1155,8 +1142,6 @@ impl AuthManager {
|
||||
TokenType::from_auth(self.inner.read().as_ref())
|
||||
}
|
||||
|
||||
// ── Pre-request dispatch ──────────────────────────────────────────
|
||||
|
||||
/// Pre-request entry point: per-`TokenType` dispatch. For just the key:
|
||||
/// [`Self::get_valid_token`].
|
||||
#[tracing::instrument(skip(self), fields(token_type = tracing::field::Empty))]
|
||||
@@ -1259,8 +1244,6 @@ impl AuthManager {
|
||||
self.auth().await.map(|a| a.key)
|
||||
}
|
||||
|
||||
// ── Refresh chain (single mutation point) ─────────────────────────
|
||||
|
||||
/// Acquire lock, double-check, try disk, then active refresh via injected refresher.
|
||||
///
|
||||
/// This is the single place where auth state is mutated during refresh.
|
||||
@@ -1779,8 +1762,6 @@ impl AuthManager {
|
||||
}
|
||||
}
|
||||
|
||||
// ── 401 recovery entry point ──────────────────────────────────────
|
||||
|
||||
/// 401 recovery state machine driven by the `rejected` credential. For
|
||||
/// one-shot recovery off the live bearer, use `try_recover_unauthorized()`.
|
||||
pub(crate) fn unauthorized_recovery(
|
||||
@@ -1797,8 +1778,6 @@ impl AuthManager {
|
||||
self.unauthorized_recovery(cached).next().await.is_ok()
|
||||
}
|
||||
|
||||
// ── Proactive refresh ─────────────────────────────────────────────
|
||||
|
||||
/// Spawn the background refresh task (PRD F1): a fixed
|
||||
/// [`PROACTIVE_REFRESH_INTERVAL`] (60s) tick that refreshes when the
|
||||
/// remaining lifetime drops below `max(300, expires_in × 0.5)` seconds
|
||||
|
||||
@@ -23,8 +23,6 @@ use crate::unified_log;
|
||||
/// Maximum age (seconds) of a lock holder before it is considered stuck.
|
||||
const STALE_LOCK_TIMEOUT_SECS: u64 = 60;
|
||||
|
||||
// ── Holder-info helpers ──────────────────────────────────────────────
|
||||
|
||||
/// Write `PID:UNIX_TIMESTAMP` into the lock file so waiters can detect
|
||||
/// staleness.
|
||||
fn write_holder_info(file: &mut File) -> io::Result<()> {
|
||||
@@ -46,8 +44,6 @@ fn parse_holder_info(content: &str) -> Option<(u32, u64)> {
|
||||
Some((pid_str.parse().ok()?, ts_str.parse().ok()?))
|
||||
}
|
||||
|
||||
// ── Platform-specific helpers ────────────────────────────────────────
|
||||
|
||||
/// Check whether the process that wrote the lock file is still running.
|
||||
#[cfg(unix)]
|
||||
fn is_process_alive(pid: u32) -> bool {
|
||||
@@ -77,7 +73,8 @@ fn is_process_alive(pid: u32) -> bool {
|
||||
|
||||
#[cfg(not(unix))]
|
||||
fn is_process_alive(_pid: u32) -> bool {
|
||||
true // conservative fallback — skip liveness check on non-Unix
|
||||
// conservative fallback — skip liveness check on non-Unix
|
||||
true
|
||||
}
|
||||
|
||||
/// `fstat(fd)` vs `stat(path)` inode comparison. Detects a concurrent
|
||||
@@ -92,11 +89,10 @@ fn inodes_match(file: &File, path: &Path) -> io::Result<bool> {
|
||||
|
||||
#[cfg(not(unix))]
|
||||
fn inodes_match(_file: &File, _path: &Path) -> io::Result<bool> {
|
||||
Ok(true) // no inode concept; skip the check
|
||||
// no inode concept; skip the check
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
// ── Staleness check ──────────────────────────────────────────────────
|
||||
|
||||
/// Decide staleness when the lock file carries no usable `PID:TS` holder
|
||||
/// info — it is empty, was truncated mid-write, or holds non-UTF-8
|
||||
/// garbage. We have no PID to liveness-probe, so we fall back to the lock
|
||||
@@ -106,9 +102,9 @@ fn inodes_match(_file: &File, _path: &Path) -> io::Result<bool> {
|
||||
/// break. A lock caught in the sub-millisecond `set_len(0)`→write window
|
||||
/// keeps a fresh mtime and is therefore never broken by this path.
|
||||
///
|
||||
/// Returning `false` here used to be unconditional ("assume alive"), which
|
||||
/// turned a single empty/garbage lock file into an unbreakable lock and
|
||||
/// wedged every refresh behind it.
|
||||
/// Without this mtime arm, an unconditional "assume alive" turns a single
|
||||
/// empty/garbage lock file into an unbreakable lock that wedges every refresh
|
||||
/// behind it.
|
||||
fn unidentified_holder_is_stale(file: &File, why: &str) -> bool {
|
||||
let Ok(modified) = file.metadata().and_then(|m| m.modified()) else {
|
||||
unified_log::debug(
|
||||
@@ -154,7 +150,6 @@ fn is_holder_stale(file: &mut File) -> bool {
|
||||
);
|
||||
};
|
||||
|
||||
// Process dead?
|
||||
if !is_process_alive(holder_pid) {
|
||||
unified_log::info(
|
||||
&format!("auth lock: holder pid={holder_pid} is dead, breaking stale lock"),
|
||||
@@ -164,7 +159,6 @@ fn is_holder_stale(file: &mut File) -> bool {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Process stuck (holding > STALE_LOCK_TIMEOUT_SECS)?
|
||||
let now = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
@@ -186,8 +180,6 @@ fn is_holder_stale(file: &mut File) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
// ── Single-iteration acquire logic ───────────────────────────────────
|
||||
|
||||
/// Outcome of one lock attempt.
|
||||
enum LockAttempt {
|
||||
/// Lock acquired; inner file holds the flock.
|
||||
@@ -205,7 +197,6 @@ enum LockAttempt {
|
||||
/// `lock_path` is the resolved path to `auth.json.lock` — computed once
|
||||
/// by the caller to avoid re-deriving it on every poll iteration.
|
||||
fn try_acquire_once(lock_path: &Path) -> LockAttempt {
|
||||
// Step 1: open (create if missing) auth.json.lock
|
||||
let mut file = match OpenOptions::new()
|
||||
.read(true)
|
||||
.write(true)
|
||||
@@ -224,11 +215,9 @@ fn try_acquire_once(lock_path: &Path) -> LockAttempt {
|
||||
}
|
||||
};
|
||||
|
||||
// Step 2: flock(LOCK_EX | LOCK_NB)
|
||||
match file.try_lock_exclusive() {
|
||||
Ok(()) => {
|
||||
let pid = std::process::id();
|
||||
// Step 3: write holder info, then verify same inode.
|
||||
if let Err(e) = write_holder_info(&mut file) {
|
||||
unified_log::warn(
|
||||
&format!("auth lock: failed to write holder info: {e}"),
|
||||
@@ -271,7 +260,7 @@ fn try_acquire_once(lock_path: &Path) -> LockAttempt {
|
||||
}
|
||||
}
|
||||
|
||||
// Step 4: EWOULDBLOCK — lock is held by someone else.
|
||||
// WouldBlock: another process holds the flock.
|
||||
Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
|
||||
if is_holder_stale(&mut file) {
|
||||
match std::fs::remove_file(lock_path) {
|
||||
@@ -300,8 +289,6 @@ fn try_acquire_once(lock_path: &Path) -> LockAttempt {
|
||||
}
|
||||
}
|
||||
|
||||
// ── Blocking acquire (kernel FIFO wait queue) ────────────────────────
|
||||
|
||||
/// Attempt a blocking `flock(LOCK_EX)` on the lock file. Returns the
|
||||
/// locked file on success, or an error on I/O failure / inode mismatch.
|
||||
///
|
||||
@@ -315,7 +302,6 @@ fn blocking_acquire(lock_path: &Path) -> io::Result<File> {
|
||||
.truncate(false)
|
||||
.open(lock_path)?;
|
||||
|
||||
// Blocking flock — waits in kernel until the lock is available.
|
||||
file.lock_exclusive().map_err(|e| {
|
||||
unified_log::warn(
|
||||
&format!("auth lock: blocking flock failed: {e}"),
|
||||
@@ -355,8 +341,6 @@ fn blocking_acquire(lock_path: &Path) -> io::Result<File> {
|
||||
}
|
||||
}
|
||||
|
||||
// ── Public API ───────────────────────────────────────────────────────
|
||||
|
||||
/// Best-effort **non-blocking** acquire for advisory cleanup call sites
|
||||
/// (`AuthManager::new` WebLogin cleanup, `remove_scope`).
|
||||
///
|
||||
@@ -365,8 +349,8 @@ fn blocking_acquire(lock_path: &Path) -> io::Result<File> {
|
||||
/// returns `None` so the caller simply skips its best-effort write.
|
||||
/// Crucially it records `PID:TS` holder info after locking, so a waiter
|
||||
/// that observes the flock can identify the holder (and break it once
|
||||
/// stale). Taking the flock *without* writing holder info is what used to
|
||||
/// leave an empty `auth.json.lock` that defeated stale-lock recovery.
|
||||
/// stale). Taking the flock *without* writing holder info would leave an
|
||||
/// empty `auth.json.lock` that defeats stale-lock recovery.
|
||||
pub(crate) fn try_lock_auth_file_nonblocking(auth_json_path: &Path) -> Option<AuthFileLock> {
|
||||
let lock_path = auth_json_path.with_file_name("auth.json.lock");
|
||||
let mut file = OpenOptions::new()
|
||||
@@ -433,7 +417,8 @@ pub(crate) async fn try_lock_auth_file_async(
|
||||
loop {
|
||||
let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
|
||||
if remaining == StdDuration::ZERO {
|
||||
break; // fall through to Phase 3
|
||||
// fall through to Phase 3
|
||||
break;
|
||||
}
|
||||
|
||||
let lp = lock_path.clone();
|
||||
@@ -471,7 +456,7 @@ pub(crate) async fn try_lock_auth_file_async(
|
||||
for _ in 0..2 {
|
||||
match try_acquire_once(&lock_path) {
|
||||
LockAttempt::Acquired(file) => return Some(AuthFileLock { _file: file }),
|
||||
LockAttempt::StaleUnlinked => continue, // unlinked stale lock, retry once
|
||||
LockAttempt::StaleUnlinked => continue,
|
||||
LockAttempt::Busy | LockAttempt::Failed => break,
|
||||
}
|
||||
}
|
||||
@@ -498,8 +483,6 @@ mod tests {
|
||||
dir.path().join("auth.json")
|
||||
}
|
||||
|
||||
// ── Pure-function unit tests (no runtime needed) ─────────────────
|
||||
|
||||
#[test]
|
||||
fn test_write_and_parse_holder_info() {
|
||||
let dir = TempDir::new().unwrap();
|
||||
@@ -551,7 +534,7 @@ mod tests {
|
||||
// an empty `auth.json.lock` was treated as alive forever.
|
||||
let dir = TempDir::new().unwrap();
|
||||
let lock_path = dir.path().join("test.lock");
|
||||
std::fs::write(&lock_path, b"").unwrap(); // empty → unparseable
|
||||
std::fs::write(&lock_path, b"").unwrap();
|
||||
|
||||
let file = OpenOptions::new()
|
||||
.read(true)
|
||||
@@ -758,8 +741,6 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
// ── Async tests against the production code path ─────────────────
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_async_acquire_release_basic() {
|
||||
let dir = TempDir::new().unwrap();
|
||||
@@ -768,16 +749,13 @@ mod tests {
|
||||
let lock = try_lock_auth_file_async(&path, StdDuration::from_secs(1)).await;
|
||||
assert!(lock.is_some(), "should acquire lock");
|
||||
|
||||
// Verify lock file has holder info.
|
||||
let lock_path = path.with_file_name("auth.json.lock");
|
||||
let content = std::fs::read_to_string(&lock_path).unwrap();
|
||||
let (pid, _ts) = parse_holder_info(&content).unwrap();
|
||||
assert_eq!(pid, std::process::id());
|
||||
|
||||
// Release.
|
||||
drop(lock);
|
||||
|
||||
// Re-acquire should succeed.
|
||||
let lock2 = try_lock_auth_file_async(&path, StdDuration::from_secs(1)).await;
|
||||
assert!(lock2.is_some(), "should re-acquire after release");
|
||||
}
|
||||
@@ -816,8 +794,6 @@ mod tests {
|
||||
assert_eq!(pid, std::process::id());
|
||||
}
|
||||
|
||||
// ── Real cross-process integration tests (async) ─────────────────
|
||||
//
|
||||
// These spawn a genuine second process so we exercise OS-level flock
|
||||
// semantics that threads/extra FDs cannot model: a *dead* holder PID
|
||||
// (flock auto-released on process death) and `is_process_alive()`
|
||||
@@ -847,7 +823,8 @@ mod tests {
|
||||
#[ignore = "spawned as a subprocess by the cross-process lock tests"]
|
||||
fn subprocess_lock_holder() {
|
||||
let Ok(spec) = std::env::var("KIGI_TEST_LOCK_HOLDER") else {
|
||||
return; // normal test run — not a subprocess invocation
|
||||
// normal test run — not a subprocess invocation
|
||||
return;
|
||||
};
|
||||
let mut parts = spec.splitn(3, '|');
|
||||
let lock_path = parts.next().expect("spec lock_path");
|
||||
@@ -982,10 +959,10 @@ mod tests {
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn test_async_breaks_old_empty_lock_held_by_live_holder() {
|
||||
// Regression: a LIVE process holding the flock on an EMPTY lock
|
||||
// file (no `PID:TS`) used to be "alive forever", wedging refresh.
|
||||
// With the mtime fallback an old empty lock is broken even though
|
||||
// the holder process is still running.
|
||||
// Regression: without the mtime fallback a LIVE process holding the
|
||||
// flock on an EMPTY lock file (no `PID:TS`) reads as "alive forever"
|
||||
// and wedges refresh. The fallback breaks an old empty lock even
|
||||
// though the holder process is still running.
|
||||
let dir = TempDir::new().unwrap();
|
||||
let path = auth_json_path(&dir);
|
||||
let lock_path = path.with_file_name("auth.json.lock");
|
||||
@@ -1022,7 +999,7 @@ mod tests {
|
||||
let path = auth_json_path(&dir);
|
||||
let lock_path = path.with_file_name("auth.json.lock");
|
||||
|
||||
let mut child = spawn_lock_holder_subprocess(&lock_path, "empty", 0); // fresh mtime
|
||||
let mut child = spawn_lock_holder_subprocess(&lock_path, "empty", 0);
|
||||
|
||||
let lock = try_lock_auth_file_async(&path, StdDuration::from_millis(800)).await;
|
||||
assert!(
|
||||
@@ -1046,22 +1023,20 @@ mod tests {
|
||||
let mut child = spawn_lock_holder_subprocess(&lock_path, "pid", 0);
|
||||
let child_pid = child.id();
|
||||
|
||||
// Verify child's PID in the lock file.
|
||||
let content_before = std::fs::read_to_string(&lock_path).unwrap();
|
||||
let (written_pid, _) = parse_holder_info(&content_before).unwrap();
|
||||
assert_eq!(written_pid, child_pid);
|
||||
|
||||
// Kill the child.
|
||||
child.kill().unwrap();
|
||||
child.wait().unwrap();
|
||||
assert!(!is_process_alive(child_pid));
|
||||
|
||||
// Lock file still has the dead child's PID.
|
||||
// The killed child's flock is released, but its stale `PID:TS` is
|
||||
// still on disk — recovery must break it.
|
||||
let content_after = std::fs::read_to_string(&lock_path).unwrap();
|
||||
let (dead_pid, _) = parse_holder_info(&content_after).unwrap();
|
||||
assert_eq!(dead_pid, child_pid);
|
||||
|
||||
// Acquire should succeed immediately.
|
||||
let start = tokio::time::Instant::now();
|
||||
let lock = try_lock_auth_file_async(&path, StdDuration::from_secs(2)).await;
|
||||
let elapsed = start.elapsed();
|
||||
@@ -1131,8 +1106,6 @@ mod tests {
|
||||
assert!(!is_process_alive(pid), "child should be dead after kill");
|
||||
}
|
||||
|
||||
// ── Blocking acquire unit tests ──────────────────────────────────
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn test_blocking_acquire_uncontended() {
|
||||
|
||||
@@ -156,8 +156,8 @@ impl SleepGate {
|
||||
// Stale gate (missed/late wake). `sleep_straddle` = the monotonic clock
|
||||
// is still under the bound but real (wall-clock) time is not: the
|
||||
// machine slept through the gate without delivering a wake event. This
|
||||
// is precisely the case the wall-clock arm was added to catch, so
|
||||
// surface it explicitly to confirm the fix firing in the field.
|
||||
// is precisely the case the wall-clock arm exists to catch, so surface
|
||||
// it explicitly to confirm it fires in the field.
|
||||
let sleep_straddle = mono < SLEEP_GATE_MAX;
|
||||
*self.raised_at.write() = None;
|
||||
kigi_log::unified_log::info(
|
||||
|
||||
@@ -67,8 +67,6 @@ fn install_ok_refresher(m: &Arc<AuthManager>) -> Arc<AtomicU32> {
|
||||
calls
|
||||
}
|
||||
|
||||
// ── Dynamic refresh threshold (PRD: max(300, expires_in × 0.5)) ─────────
|
||||
|
||||
/// A 7200s-lifetime token with 3000s left is inside the 3600s threshold:
|
||||
/// `current()` hides it (refresh due) while `expired_auth()` still exposes
|
||||
/// it (wire-valid bearer for senders).
|
||||
@@ -87,7 +85,6 @@ fn threshold_hides_current_but_keeps_expired_auth() {
|
||||
assert!(!m.is_expired());
|
||||
}
|
||||
|
||||
/// Hard expiry: a genuinely past-expiry token is not usable.
|
||||
#[test]
|
||||
fn hard_expired_token_is_not_usable() {
|
||||
let (_d, m) = mgr();
|
||||
@@ -97,8 +94,6 @@ fn hard_expired_token_is_not_usable() {
|
||||
assert!(!m.has_usable_token());
|
||||
}
|
||||
|
||||
// ── auth() dispatch ─────────────────────────────────────────────────────
|
||||
|
||||
#[tokio::test]
|
||||
async fn auth_returns_not_logged_in_when_empty() {
|
||||
let (_d, m) = mgr();
|
||||
@@ -135,7 +130,6 @@ async fn auth_expired_session_refreshes_via_chain() {
|
||||
let auth = m.auth().await.unwrap();
|
||||
assert_eq!(auth.key, "at-refreshed");
|
||||
assert_eq!(calls.load(AtomicOrdering::SeqCst), 1);
|
||||
// Refresh persisted: a fresh manager on the same home adopts it.
|
||||
assert_eq!(m.current().map(|a| a.key), Some("at-refreshed".into()));
|
||||
}
|
||||
|
||||
@@ -176,8 +170,6 @@ async fn refresh_notifies_waiters() {
|
||||
);
|
||||
}
|
||||
|
||||
// ── Tombstone semantics (PRD F1) ────────────────────────────────────────
|
||||
|
||||
/// A 401-rejected refresh sets a tombstone keyed by the rejected refresh
|
||||
/// token; subsequent auth() calls short-circuit without hitting the wire.
|
||||
#[tokio::test]
|
||||
@@ -294,8 +286,6 @@ async fn tombstone_does_not_block_wire_valid_bearer() {
|
||||
assert_eq!(auth.key, "at-usable");
|
||||
}
|
||||
|
||||
// ── Persistence: file fallback + keyring ────────────────────────────────
|
||||
|
||||
#[tokio::test]
|
||||
async fn update_persists_to_file_when_keyring_disabled() {
|
||||
let (dir, m) = mgr();
|
||||
@@ -457,8 +447,6 @@ mod keyring_integration {
|
||||
}
|
||||
}
|
||||
|
||||
// ── Sibling adoption + disk reload ──────────────────────────────────────
|
||||
|
||||
#[tokio::test]
|
||||
async fn pick_up_sibling_token_adopts_different_valid_token() {
|
||||
let (dir, m) = mgr();
|
||||
@@ -481,7 +469,6 @@ fn force_reload_drops_credentials_on_readable_entry_missing() {
|
||||
// A readable auth.json without our scope = trustworthy logout signal.
|
||||
let store = AuthStore::new();
|
||||
crate::auth::storage::write_auth_json(&dir.path().join("auth.json"), &store).unwrap();
|
||||
// Non-empty map required for EntryMissing (empty map is still readable).
|
||||
m.force_reload_from_disk();
|
||||
assert!(
|
||||
m.current_or_expired().is_none(),
|
||||
@@ -504,8 +491,6 @@ fn force_reload_retains_refresh_token_on_disk_anomaly() {
|
||||
);
|
||||
}
|
||||
|
||||
// ── Proactive tick (loop body) ──────────────────────────────────────────
|
||||
|
||||
#[tokio::test]
|
||||
async fn proactive_tick_skips_above_threshold() {
|
||||
let (_d, m) = mgr();
|
||||
@@ -576,8 +561,6 @@ async fn proactive_tick_respects_tombstone_cooldown() {
|
||||
);
|
||||
}
|
||||
|
||||
// ── Sleep gate integration ──────────────────────────────────────────────
|
||||
|
||||
#[tokio::test]
|
||||
async fn refresh_chain_defers_when_sleep_imminent() {
|
||||
let (_d, m) = mgr();
|
||||
@@ -605,8 +588,6 @@ async fn refresh_chain_defers_when_sleep_imminent() {
|
||||
);
|
||||
}
|
||||
|
||||
// ── Idempotency guards ──────────────────────────────────────────────────
|
||||
|
||||
#[tokio::test]
|
||||
async fn start_proactive_refresh_is_idempotent_per_arc() {
|
||||
let (_d, m) = mgr();
|
||||
|
||||
@@ -137,7 +137,6 @@ pub(crate) fn token_suffix(t: &str) -> &str {
|
||||
if len > 12 { &t[len - 12..] } else { t }
|
||||
}
|
||||
|
||||
/// Look up auth from the store by scope key.
|
||||
pub fn lookup_auth(map: &AuthStore, scope: &str) -> Option<KimiAuth> {
|
||||
map.get(scope).cloned()
|
||||
}
|
||||
|
||||
@@ -25,7 +25,6 @@ use super::kimi_oauth::{
|
||||
|
||||
const DEVICE_GRANT_TYPE: &str = "urn:ietf:params:oauth:grant-type:device_code";
|
||||
const REFRESH_GRANT_TYPE: &str = "refresh_token";
|
||||
/// Refresh retry budget over the retryable statuses / network blips.
|
||||
const MAX_REFRESH_RETRIES: u32 = 3;
|
||||
/// HTTP statuses worth retrying a refresh for (kimi-cli parity).
|
||||
const RETRYABLE_REFRESH_STATUSES: [u16; 5] = [429, 500, 502, 503, 504];
|
||||
@@ -58,8 +57,6 @@ fn oauth_url(host: &str, path: &str) -> String {
|
||||
format!("{}{path}", host.trim_end_matches('/'))
|
||||
}
|
||||
|
||||
/// The device-authorization form fields: `client_id`, `scope`, and the
|
||||
/// optional non-standard `extra_device_field`.
|
||||
fn device_form(cfg: &OAuthConfig) -> Vec<(&'static str, &'static str)> {
|
||||
let mut form = vec![("client_id", cfg.client_id), ("scope", cfg.scope)];
|
||||
if let Some((name, value)) = cfg.extra_device_field {
|
||||
@@ -257,8 +254,6 @@ mod tests {
|
||||
use wiremock::matchers::{body_string_contains, method, path};
|
||||
use wiremock::{Mock, MockServer, ResponseTemplate};
|
||||
|
||||
/// An OAuthConfig pointed at a mock server (copies XAI's client_id/scope/
|
||||
/// paths but overrides the host).
|
||||
fn mock_cfg(host: &'static str) -> OAuthConfig {
|
||||
OAuthConfig {
|
||||
auth_host: host,
|
||||
@@ -308,8 +303,6 @@ mod tests {
|
||||
assert_eq!(auth.expires_in, Some(900));
|
||||
}
|
||||
|
||||
/// A response with only `verification_uri` (no `_complete`) still yields a
|
||||
/// valid display URI.
|
||||
#[tokio::test]
|
||||
async fn device_authorization_falls_back_to_verification_uri() {
|
||||
let server = MockServer::start().await;
|
||||
|
||||
@@ -35,7 +35,6 @@ use super::model::KimiAuth;
|
||||
|
||||
const CODE_GRANT_TYPE: &str = "authorization_code";
|
||||
const REFRESH_GRANT_TYPE: &str = "refresh_token";
|
||||
/// Refresh retry budget over the retryable statuses / network blips.
|
||||
const MAX_REFRESH_RETRIES: u32 = 3;
|
||||
/// HTTP statuses worth retrying a refresh for (parity with the device wire).
|
||||
const RETRYABLE_REFRESH_STATUSES: [u16; 5] = [429, 500, 502, 503, 504];
|
||||
@@ -87,8 +86,6 @@ pub(crate) fn generate_pkce_random_state() -> PkceCodes {
|
||||
}
|
||||
}
|
||||
|
||||
/// The loopback redirect URI for a PKCE-localhost provider (claude `/callback`,
|
||||
/// codex `/auth/callback`).
|
||||
pub(crate) fn redirect_uri(redirect_port: u16, redirect_path: &str) -> String {
|
||||
format!("http://localhost:{redirect_port}{redirect_path}")
|
||||
}
|
||||
@@ -159,12 +156,10 @@ pub(crate) fn parse_manual_paste(input: &str) -> anyhow::Result<CallbackParams>
|
||||
if trimmed.is_empty() {
|
||||
anyhow::bail!("empty paste");
|
||||
}
|
||||
// Full redirect URL.
|
||||
if trimmed.starts_with("http://") || trimmed.starts_with("https://") {
|
||||
let url = url::Url::parse(trimmed).context("pasted value is not a valid URL")?;
|
||||
return parse_callback_query(url.query().unwrap_or_default());
|
||||
}
|
||||
// `code#state`.
|
||||
if let Some((code, state)) = trimmed.split_once('#') {
|
||||
if code.is_empty() {
|
||||
anyhow::bail!("pasted code was empty");
|
||||
@@ -174,7 +169,6 @@ pub(crate) fn parse_manual_paste(input: &str) -> anyhow::Result<CallbackParams>
|
||||
state: (!state.is_empty()).then(|| state.to_owned()),
|
||||
});
|
||||
}
|
||||
// Bare code.
|
||||
Ok(CallbackParams {
|
||||
code: trimmed.to_owned(),
|
||||
state: None,
|
||||
@@ -208,7 +202,6 @@ pub(crate) fn validate_pasted_state(
|
||||
}
|
||||
}
|
||||
|
||||
/// The token-endpoint URL (`{token_host}{token_path}`).
|
||||
fn token_url(cfg: &OAuthConfig) -> String {
|
||||
format!("{}{}", cfg.token_host.trim_end_matches('/'), cfg.token_path)
|
||||
}
|
||||
@@ -486,7 +479,6 @@ async fn handle_loopback_conn(
|
||||
}
|
||||
}
|
||||
|
||||
/// Write a minimal HTTP/1.1 response with an HTML body.
|
||||
async fn write_http(
|
||||
stream: &mut tokio::net::TcpStream,
|
||||
status: u16,
|
||||
@@ -516,8 +508,6 @@ mod tests {
|
||||
use wiremock::matchers::{body_string_contains, method, path};
|
||||
use wiremock::{Mock, MockServer, ResponseTemplate};
|
||||
|
||||
/// A config pointed at a mock token host (copies Claude's client_id/scope/
|
||||
/// paths but overrides the token host).
|
||||
fn mock_cfg(token_host: &'static str) -> OAuthConfig {
|
||||
OAuthConfig {
|
||||
token_host,
|
||||
@@ -525,8 +515,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// PKCE codes: verifier/challenge are non-empty base64url (no padding), the
|
||||
/// challenge is the base64url SHA-256 of the verifier, and state == verifier.
|
||||
#[test]
|
||||
fn generate_pkce_produces_valid_s256_codes() {
|
||||
let pkce = generate_pkce();
|
||||
@@ -540,16 +528,12 @@ mod tests {
|
||||
);
|
||||
assert!(!s.contains('='), "no padding: {s}");
|
||||
}
|
||||
// challenge == base64url(SHA-256(verifier)).
|
||||
let expect = base64::engine::general_purpose::URL_SAFE_NO_PAD
|
||||
.encode(Sha256::digest(pkce.verifier.as_bytes()));
|
||||
assert_eq!(pkce.challenge, expect);
|
||||
// Fresh entropy each call.
|
||||
assert_ne!(pkce.verifier, generate_pkce().verifier);
|
||||
}
|
||||
|
||||
/// The authorize URL carries the fixed params + the PKCE state and S256
|
||||
/// challenge, and targets `claude.ai/oauth/authorize`.
|
||||
#[test]
|
||||
fn authorize_url_has_state_and_s256_challenge() {
|
||||
let pkce = generate_pkce();
|
||||
@@ -580,15 +564,12 @@ mod tests {
|
||||
q.get("redirect_uri").map(String::as_str),
|
||||
Some(redirect.as_str())
|
||||
);
|
||||
// The verifier itself must NEVER appear in the browser URL.
|
||||
assert!(
|
||||
!url.contains("code_verifier"),
|
||||
"the verifier must not ride the authorize URL"
|
||||
);
|
||||
}
|
||||
|
||||
/// STRICT state validation: an exact match passes; a mismatch or an absent
|
||||
/// state is REJECTED (CSRF guard — the flow must never proceed).
|
||||
#[test]
|
||||
fn state_validation_is_strict() {
|
||||
let ok = CallbackParams {
|
||||
@@ -614,8 +595,6 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// A loopback `/callback` with the WRONG state is rejected end-to-end (the
|
||||
/// listener returns an error, never a code) — the CSRF guard on the wire.
|
||||
#[tokio::test]
|
||||
async fn loopback_rejects_state_mismatch() {
|
||||
// Ephemeral port: bind, learn the port, then drive a client at it.
|
||||
@@ -631,7 +610,6 @@ mod tests {
|
||||
);
|
||||
// Give the listener a moment to bind.
|
||||
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
|
||||
// Attacker callback: valid code, WRONG state.
|
||||
let _ = reqwest::get(format!(
|
||||
"http://127.0.0.1:{port}/callback?code=stolen&state=wrong-state"
|
||||
))
|
||||
@@ -641,7 +619,6 @@ mod tests {
|
||||
assert!(err.to_string().contains("state mismatch"), "{err}");
|
||||
}
|
||||
|
||||
/// A loopback `/callback` with the MATCHING state yields the code.
|
||||
#[tokio::test]
|
||||
async fn loopback_returns_code_on_valid_state() {
|
||||
let probe = tokio::net::TcpListener::bind(("127.0.0.1", 0))
|
||||
@@ -661,7 +638,6 @@ mod tests {
|
||||
assert_eq!(code, "auth-code-123");
|
||||
}
|
||||
|
||||
/// Manual-paste parsing: full redirect URL, `code#state`, and bare code.
|
||||
#[test]
|
||||
fn manual_paste_parses_all_three_forms() {
|
||||
let from_url =
|
||||
@@ -678,12 +654,9 @@ mod tests {
|
||||
assert_eq!(bare.state, None);
|
||||
|
||||
assert!(parse_manual_paste("").is_err());
|
||||
// A pasted redirect that carries an error param surfaces the error.
|
||||
assert!(parse_manual_paste("http://localhost/callback?error=access_denied").is_err());
|
||||
}
|
||||
|
||||
/// Code → token exchange: JSON body carries the grant + verifier, response
|
||||
/// materializes a `KimiAuth` with the rotating refresh token.
|
||||
#[tokio::test]
|
||||
async fn exchange_code_posts_json_and_returns_auth() {
|
||||
let server = MockServer::start().await;
|
||||
@@ -719,7 +692,6 @@ mod tests {
|
||||
assert_eq!(auth.expires_in, Some(3600));
|
||||
}
|
||||
|
||||
/// Refresh rotates the refresh token (JSON body, refresh grant).
|
||||
#[tokio::test]
|
||||
async fn refresh_rotates_refresh_token() {
|
||||
let server = MockServer::start().await;
|
||||
@@ -745,7 +717,6 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// A 401 on refresh maps to Unauthorized (drives the permanent-failure path).
|
||||
#[tokio::test]
|
||||
async fn refresh_401_maps_to_unauthorized() {
|
||||
let server = MockServer::start().await;
|
||||
@@ -774,10 +745,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
// ── ChatGPT/Codex PKCE (openai-codex) ────────────────────────────────────
|
||||
|
||||
/// Codex PKCE uses an INDEPENDENT fresh-random state (NOT `state ==
|
||||
/// verifier`) so the verifier never rides the callback.
|
||||
#[test]
|
||||
fn codex_pkce_state_is_independent_of_the_verifier() {
|
||||
let pkce = generate_pkce_random_state();
|
||||
@@ -786,7 +753,6 @@ mod tests {
|
||||
"codex state must be fresh-random, not the verifier"
|
||||
);
|
||||
assert!(!pkce.state.is_empty() && !pkce.verifier.is_empty());
|
||||
// Challenge is still the S256 of the verifier.
|
||||
let expect = base64::engine::general_purpose::URL_SAFE_NO_PAD
|
||||
.encode(Sha256::digest(pkce.verifier.as_bytes()));
|
||||
assert_eq!(pkce.challenge, expect);
|
||||
@@ -797,9 +763,6 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// The codex authorize URL carries the PKCE state + S256 challenge AND the
|
||||
/// three codex-only extra params, and targets `auth.openai.com/oauth/
|
||||
/// authorize` with the `/auth/callback` redirect. The verifier never rides it.
|
||||
#[test]
|
||||
fn codex_authorize_url_has_state_challenge_and_three_extra_params() {
|
||||
use kigi_models::CODEX_OAUTH_CONFIG;
|
||||
@@ -823,7 +786,6 @@ mod tests {
|
||||
q.get("code_challenge_method").map(String::as_str),
|
||||
Some("S256")
|
||||
);
|
||||
// The three codex-only extra params.
|
||||
assert_eq!(
|
||||
q.get("id_token_add_organizations").map(String::as_str),
|
||||
Some("true")
|
||||
@@ -842,8 +804,6 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// The claude authorize URL is UNCHANGED (no extra params) — its empty
|
||||
/// `authorize_extra` keeps it byte-identical.
|
||||
#[test]
|
||||
fn claude_authorize_url_carries_no_extra_params() {
|
||||
let pkce = generate_pkce();
|
||||
@@ -864,9 +824,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// Codex code→token exchange posts a FORM body carrying the grant + code +
|
||||
/// verifier + redirect_uri, and NOTABLY NO `state` field (the codex token
|
||||
/// endpoint does not expect it). Response materializes a `KimiAuth`.
|
||||
#[tokio::test]
|
||||
async fn codex_exchange_code_posts_form_without_state() {
|
||||
use wiremock::matchers::{body_string_contains, header, method, path};
|
||||
|
||||
@@ -72,17 +72,17 @@ fn oauth_manager_pool() -> &'static Mutex<HashMap<&'static str, Arc<AuthManager>
|
||||
/// production-readable env override is added here on purpose: a knob that
|
||||
/// redirects where OAuth tokens are read from is not worth a test convenience.
|
||||
///
|
||||
/// M8: this used to be a `static OnceLock<TempDir>`. Statics are never dropped,
|
||||
/// so that leaked one temp directory per test binary — against the project's
|
||||
/// "tests are TempDir self-cleaning" discipline. Nothing is created here
|
||||
/// instead, and nothing in the lib-test suite creates it: a manager reads a
|
||||
/// missing `auth.json` as "no session", and the only two paths that WRITE one
|
||||
/// are a successful token refresh (which needs a stored refresh token that by
|
||||
/// Nothing is created here, and a `static OnceLock<TempDir>` would be wrong: a
|
||||
/// static is never dropped, so it would leak one temp directory per test binary,
|
||||
/// against the project's "tests are TempDir self-cleaning" discipline. Nothing
|
||||
/// in the lib-test suite creates the directory either: a manager reads a missing
|
||||
/// `auth.json` as "no session", and the only two paths that WRITE one are a
|
||||
/// successful token refresh (which needs a stored refresh token that by
|
||||
/// construction does not exist here) and a completed device login
|
||||
/// ([`crate::agent::mvp_agent::MvpAgent::authenticate_oauth_platform`], which
|
||||
/// M4 repointed at this same home). Both require the network, so no lib test
|
||||
/// performs either. That is an observation about the suite, not an invariant of
|
||||
/// this function — [`tests::test_pool_home_is_disposable_and_never_the_real_home`]
|
||||
/// targets this same home). Both require the network, so no lib test performs
|
||||
/// either. That is an observation about the suite, not an invariant of this
|
||||
/// function — [`tests::test_pool_home_is_disposable_and_never_the_real_home`]
|
||||
/// asserts the directory does not exist and is the tripwire if one ever does
|
||||
/// (the path is per-PROCESS under the system temp dir, so the blast radius of a
|
||||
/// future login-driving test is one disposable directory, never `~/.kigi`).
|
||||
@@ -132,10 +132,6 @@ mod tests {
|
||||
.expect("subscription-OAuth platform carries an OAuthConfig")
|
||||
}
|
||||
|
||||
/// Each subscription-OAuth platform gets its OWN process-global pooled
|
||||
/// manager, and no two share one. (Which credential governs a REQUEST is
|
||||
/// not decided here — see
|
||||
/// [`crate::auth::credential_authority::CredentialAuthority`].)
|
||||
#[tokio::test]
|
||||
async fn every_oauth_scope_gets_its_own_pooled_manager() {
|
||||
let home = tempfile::tempdir().unwrap();
|
||||
@@ -168,7 +164,7 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// M8: the test pool home is a per-process path that is never created, so a
|
||||
/// The test pool home is a per-process path that is never created, so a
|
||||
/// test binary leaves nothing behind (and never resolves the developer's
|
||||
/// real `~/.kigi`, whose stored OAuth tokens the pool would otherwise read
|
||||
/// and proactively refresh over the network).
|
||||
|
||||
@@ -58,9 +58,7 @@ enum RecoveryStep {
|
||||
/// State machine that walks through recovery strategies after a 401.
|
||||
pub struct UnauthorizedRecovery {
|
||||
auth_manager: Arc<AuthManager>,
|
||||
/// The token that was rejected by the server.
|
||||
rejected_token: String,
|
||||
/// Current step in the recovery sequence.
|
||||
step: RecoveryStep,
|
||||
/// Error from `RefreshFromAuthority`, propagated on exhaustion.
|
||||
authority_error: Option<AuthError>,
|
||||
@@ -298,7 +296,6 @@ impl UnauthorizedRecovery {
|
||||
}
|
||||
}
|
||||
|
||||
/// Check if a candidate token is different from the rejected one.
|
||||
fn is_different_token(&self, candidate: &KimiAuth) -> bool {
|
||||
candidate.key != self.rejected_token
|
||||
}
|
||||
@@ -383,8 +380,6 @@ mod tests {
|
||||
mgr.hot_swap(auth);
|
||||
}
|
||||
|
||||
// -- TokenType dispatch matrix ----------------------------------------
|
||||
|
||||
#[tokio::test]
|
||||
async fn dispatch_oauth_session_uses_refresh_chain() {
|
||||
let (_d, m) = mgr();
|
||||
@@ -401,8 +396,6 @@ mod tests {
|
||||
assert_eq!(calls.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
// -- Fresh-mint guard --------------------------------------------------
|
||||
|
||||
/// Seed a *valid* (unexpired) in-memory token whose `create_time` lies
|
||||
/// `mint_age` in the past (negative = clock stepped back since mint).
|
||||
fn seed_valid(mgr: &AuthManager, mint_age: Duration) {
|
||||
@@ -542,8 +535,6 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
// -- ReloadFromDisk matrix --------------------------------------------
|
||||
|
||||
#[tokio::test]
|
||||
async fn reload_from_disk_picks_up_different_token() {
|
||||
let (dir, m) = mgr();
|
||||
@@ -605,8 +596,6 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
// -- Done state -------------------------------------------------------
|
||||
|
||||
/// With no stored authority error (the first `next()` succeeded), driving
|
||||
/// past `Done` surfaces `RecoveryExhausted`. The transient-failure case is
|
||||
/// pinned by `exhaustion_after_transient_failure_stays_transient`.
|
||||
@@ -677,8 +666,6 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
// -- Tombstone short-circuit (cross-check) ------------
|
||||
|
||||
#[tokio::test]
|
||||
async fn refresh_authority_short_circuits_on_cached_tombstone() {
|
||||
let (_d, m) = mgr();
|
||||
@@ -707,8 +694,6 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
// -- ReloadFromDisk rejects expired disk tokens -------------------------
|
||||
|
||||
/// Regression: disk holds a different but expired token. Recovery
|
||||
/// must skip it and fall through to RefreshFromAuthority, not
|
||||
/// return it for the caller to send on the wire (instant 401).
|
||||
|
||||
@@ -253,7 +253,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// A successful refresh rotates the token via the generic wire.
|
||||
#[tokio::test]
|
||||
async fn refresh_success_returns_rotated_token() {
|
||||
let server = MockServer::start().await;
|
||||
|
||||
@@ -4,7 +4,7 @@ use std::path::{Path, PathBuf};
|
||||
|
||||
use super::model::{API_KEY_SCOPE, AuthMode, AuthStore, KimiAuth, lookup_auth};
|
||||
|
||||
// ── System-keyring storage for the Kimi Code OAuth session ─────────────
|
||||
// System-keyring storage for the Kimi Code OAuth session.
|
||||
//
|
||||
// PRD F1: the OAuth token set lives in the system keyring (service `kigi`,
|
||||
// entry `oauth/kimi-code`); when the keyring is unavailable we fall back to
|
||||
@@ -111,7 +111,6 @@ fn keyring_entry() -> Result<&'static keyring::Entry, keyring::Error> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Read the session credential from the system keyring.
|
||||
#[cfg(any(target_os = "macos", windows))]
|
||||
pub(crate) fn keyring_read_session() -> KeyringRead {
|
||||
if !keyring_enabled() {
|
||||
@@ -145,7 +144,6 @@ pub(crate) fn keyring_read_session() -> KeyringRead {
|
||||
KeyringRead::Unavailable
|
||||
}
|
||||
|
||||
/// Write the session credential to the system keyring.
|
||||
#[cfg(any(target_os = "macos", windows))]
|
||||
pub(crate) fn keyring_write_session(auth: &KimiAuth) -> anyhow::Result<()> {
|
||||
anyhow::ensure!(keyring_enabled(), "keyring storage disabled");
|
||||
@@ -386,8 +384,8 @@ fn write_auth_json_with(
|
||||
"auth: disk full during atomic write, falling back to in-place write"
|
||||
);
|
||||
// Must reach unified.jsonl: a silent in-memory-only credential
|
||||
// (the prior behavior) leaves sibling processes with a stale
|
||||
// refresh token and no record of why. Surface it loudly.
|
||||
// leaves sibling processes with a stale refresh token and no
|
||||
// record of why. Surface it loudly.
|
||||
kigi_log::unified_log::warn(
|
||||
"auth: disk full, falling back to non-atomic in-place write",
|
||||
None,
|
||||
@@ -430,8 +428,7 @@ fn write_store_to(path: &Path, auth_store: &AuthStore) -> std::io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Atomic write: tmp + Windows-safe replace (see `util::fs::replace_file`,
|
||||
/// which this site's inline delete-first pattern graduated into).
|
||||
/// Atomic write: tmp + Windows-safe replace (see `util::fs::replace_file`).
|
||||
fn write_auth_json_atomic(auth_file: &Path, auth_store: &AuthStore) -> std::io::Result<()> {
|
||||
let tmp = auth_file.with_extension(format!("json.{}.tmp", std::process::id()));
|
||||
write_store_to(&tmp, auth_store)?;
|
||||
@@ -447,8 +444,8 @@ fn write_auth_json_atomic(auth_file: &Path, auth_store: &AuthStore) -> std::io::
|
||||
///
|
||||
/// Truncation is destructive, so the prior bytes are snapshotted first and
|
||||
/// restored best-effort if the rewrite fails partway — a failed fallback
|
||||
/// must not leave an empty/torn file where a parseable (if stale) credential
|
||||
/// used to be. A partial file that survives (because even the restore failed)
|
||||
/// must not leave an empty/torn file in place of a parseable (if stale)
|
||||
/// credential. A partial file that survives (because even the restore failed)
|
||||
/// is healed on the next read via [`read_auth_json_or_empty_recovering_corrupt`].
|
||||
fn write_auth_json_in_place(auth_file: &Path, auth_store: &AuthStore) -> std::io::Result<()> {
|
||||
write_auth_json_in_place_with(auth_file, auth_store, write_store_to)
|
||||
@@ -719,7 +716,8 @@ mod write_fallback_tests {
|
||||
/// old content, as `open_secure_file` does) and then fails partway — the
|
||||
/// torn-write case the rollback must recover from.
|
||||
fn fake_truncate_then_fail(path: &Path, _: &AuthStore) -> std::io::Result<()> {
|
||||
crate::util::secure_file::open_secure_file(path)?; // truncates to 0 bytes
|
||||
// `open_secure_file` truncates to 0 bytes.
|
||||
crate::util::secure_file::open_secure_file(path)?;
|
||||
Err(std::io::Error::from(std::io::ErrorKind::StorageFull))
|
||||
}
|
||||
|
||||
@@ -778,7 +776,7 @@ mod write_fallback_tests {
|
||||
|
||||
/// A fallback write that truncates then fails must roll back to the prior
|
||||
/// bytes instead of leaving an empty/torn file — otherwise a second
|
||||
/// disk-full failure would destroy a previously-valid credential.
|
||||
/// disk-full failure would destroy the still-valid credential.
|
||||
#[test]
|
||||
fn in_place_restores_prior_bytes_on_failure() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
||||
Reference in new issue
Block a user