Skip to main content

vtcode_auth/openai_chatgpt_oauth/
refresh.rs

1//! Token exchange, refresh, storage wrappers, and refresh-lock helpers.
2
3use anyhow::{Context, Result, anyhow, bail};
4use fs2::FileExt;
5use serde::Deserialize;
6use std::fs;
7use std::fs::OpenOptions;
8
9use crate::openai_refresh_policy::{RefreshFailureAction, classify_refresh_failure};
10use crate::openai_session_storage::OpenAiSessionStorage;
11use crate::storage_paths::auth_storage_dir;
12
13pub use super::super::credentials::AuthCredentialsStoreMode;
14use super::super::pkce::PkceChallenge;
15use super::jwt::{parse_jwt_claims, parse_jwt_exp};
16use super::session::{OpenAIChatGptAuthStatus, OpenAIChatGptSession, active_api_bearer_token};
17use super::{
18    MAX_ERROR_BODY_BYTES, OPENAI_CALLBACK_PATH, OPENAI_REFRESH_LOCK_FILE, OPENAI_TOKEN_URL, now_secs,
19    resolve_oauth_client_identity,
20};
21
22/// Exchange an authorization code for OAuth tokens.
23pub async fn exchange_openai_chatgpt_code_for_tokens(
24    code: &str,
25    challenge: &PkceChallenge,
26    callback_port: u16,
27) -> Result<OpenAIChatGptSession> {
28    let redirect_uri = format!("http://localhost:{callback_port}{OPENAI_CALLBACK_PATH}");
29    let identity = resolve_oauth_client_identity()?;
30    let body = format!(
31        "grant_type=authorization_code&code={}&redirect_uri={}&client_id={}&code_verifier={}",
32        urlencoding::encode(code),
33        urlencoding::encode(&redirect_uri),
34        urlencoding::encode(&identity.client_id),
35        urlencoding::encode(&challenge.code_verifier),
36    );
37
38    let token_client = vtcode_commons::http::create_default_client_without_redirects()
39        .context("failed to build openai token client")?;
40    let token_response: OpenAITokenResponse =
41        vtcode_commons::http::send_with_retry_transport_only(&crate::oauth_token_retry_policy(), || {
42            token_client
43                .post(OPENAI_TOKEN_URL)
44                .header("Content-Type", "application/x-www-form-urlencoded")
45                .body(body.clone())
46                .send()
47        })
48        .await
49        .context("failed to exchange openai authorization code")?
50        .error_for_status()
51        .context("openai authorization-code exchange failed")?
52        .json()
53        .await
54        .context("failed to parse openai authorization-code response")?;
55
56    build_session_from_token_response(token_response).await
57}
58pub fn save_openai_chatgpt_session(session: &OpenAIChatGptSession) -> Result<()> {
59    save_openai_chatgpt_session_with_mode(session, AuthCredentialsStoreMode::default())
60}
61
62pub fn save_openai_chatgpt_session_with_mode(
63    session: &OpenAIChatGptSession,
64    mode: AuthCredentialsStoreMode,
65) -> Result<()> {
66    OpenAiSessionStorage::new().save(session, mode)
67}
68
69pub fn load_openai_chatgpt_session() -> Result<Option<OpenAIChatGptSession>> {
70    OpenAiSessionStorage::new().load(AuthCredentialsStoreMode::Keyring)
71}
72
73pub fn load_openai_chatgpt_session_with_mode(mode: AuthCredentialsStoreMode) -> Result<Option<OpenAIChatGptSession>> {
74    OpenAiSessionStorage::new().load(mode)
75}
76
77pub fn clear_openai_chatgpt_session() -> Result<()> {
78    OpenAiSessionStorage::new().clear_all()
79}
80
81pub fn clear_openai_chatgpt_session_with_mode(mode: AuthCredentialsStoreMode) -> Result<()> {
82    OpenAiSessionStorage::new().clear(mode)
83}
84
85pub fn get_openai_chatgpt_auth_status() -> Result<OpenAIChatGptAuthStatus> {
86    get_openai_chatgpt_auth_status_with_mode(AuthCredentialsStoreMode::default())
87}
88
89pub fn get_openai_chatgpt_auth_status_with_mode(mode: AuthCredentialsStoreMode) -> Result<OpenAIChatGptAuthStatus> {
90    let Some(session) = load_openai_chatgpt_session_with_mode(mode)? else {
91        return Ok(OpenAIChatGptAuthStatus::NotAuthenticated);
92    };
93    let now = now_secs();
94    Ok(OpenAIChatGptAuthStatus::Authenticated {
95        label: session
96            .email
97            .clone()
98            .or_else(|| session.plan.clone())
99            .or_else(|| session.account_id.clone()),
100        age_seconds: now.saturating_sub(session.obtained_at),
101        expires_in: session.expires_at.map(|expires_at| expires_at.saturating_sub(now)),
102    })
103}
104
105pub async fn refresh_openai_chatgpt_session_with_mode(mode: AuthCredentialsStoreMode) -> Result<OpenAIChatGptSession> {
106    let session = load_openai_chatgpt_session_with_mode(mode)?.ok_or_else(|| anyhow!("Run vtcode login openai"))?;
107    refresh_openai_chatgpt_session_from_snapshot(&session, mode).await
108}
109
110pub(super) async fn refresh_openai_chatgpt_session_from_snapshot(
111    session: &OpenAIChatGptSession,
112    storage_mode: AuthCredentialsStoreMode,
113) -> Result<OpenAIChatGptSession> {
114    let _lock = acquire_refresh_lock().await?;
115    if let Some(current) = load_openai_chatgpt_session_with_mode(storage_mode)?
116        && session_has_newer_refresh_state(&current, session)
117    {
118        return Ok(current);
119    }
120    refresh_openai_chatgpt_session_without_lock(session, storage_mode).await
121}
122
123/// Refresh the ChatGPT session using the stored refresh token.
124///
125/// The response is parsed as [`OpenAIRefreshResponse`] with independently
126/// optional fields — OpenAI's token endpoint may omit unchanged fields.
127/// Omitted fields preserve the current session's values. This matches the
128/// behavior of `openai/codex`'s `RefreshResponse` + `persist_tokens`.
129async fn refresh_openai_chatgpt_session_without_lock(
130    current: &OpenAIChatGptSession,
131    storage_mode: AuthCredentialsStoreMode,
132) -> Result<OpenAIChatGptSession> {
133    let identity = resolve_oauth_client_identity()?;
134    let token_client = vtcode_commons::http::create_default_client_without_redirects()
135        .context("failed to build openai token client")?;
136    let response = vtcode_commons::http::send_with_retry_transport_only(&crate::oauth_token_retry_policy(), || {
137        token_client
138            .post(OPENAI_TOKEN_URL)
139            .header("Content-Type", "application/x-www-form-urlencoded")
140            .body(format!(
141                "grant_type=refresh_token&client_id={}&refresh_token={}",
142                urlencoding::encode(&identity.client_id),
143                urlencoding::encode(&current.refresh_token),
144            ))
145            .send()
146    })
147    .await
148    .context("failed to refresh openai chatgpt token")?;
149
150    // Check for HTTP errors. Unlike error_for_status_ref(), we capture the
151    // response body to classify token-endpoint errors (e.g. invalid_grant,
152    // refresh_token_expired) that reqwest's status-only error would miss.
153    if !response.status().is_success() {
154        let status = response.status();
155        // Read a bounded body for error classification — never log it raw.
156        let body_text = read_bounded_text(response, MAX_ERROR_BODY_BYTES).await;
157        return Err(classify_refresh_status_error(status, &body_text));
158    }
159
160    let refresh_response: OpenAIRefreshResponse =
161        vtcode_commons::http_body::read_json_limited(response, vtcode_commons::http_body::CONTROL_BODY_LIMIT_BYTES)
162            .await
163            .context("failed to parse openai refresh response")?;
164
165    let session = merge_refresh_response(current, refresh_response).await?;
166    // Guard against a blank access_token — the primary bearer credential.
167    // This protects the minimal-session refresh helper (which starts with
168    // blank token fields) from persisting a session with blank tokens when
169    // the token endpoint returns a partial response that omits access_token.
170    if session.access_token.trim().is_empty() {
171        bail!("openai token refresh returned no access token — the session cannot be used");
172    }
173    save_openai_chatgpt_session_with_mode(&session, storage_mode)?;
174    Ok(session)
175}
176
177/// Merge a partial refresh response into the current session, preserving
178/// omitted fields. Only re-exchanges the API key when a new `id_token` is
179/// present; otherwise keeps the previous exchanged key.
180pub(crate) async fn merge_refresh_response(
181    current: &OpenAIChatGptSession,
182    resp: OpenAIRefreshResponse,
183) -> Result<OpenAIChatGptSession> {
184    let now = now_secs();
185    // Track which fields were present before moving them out of resp.
186    // Treat blank-string values as absent — some token endpoints return
187    // empty strings for omitted fields rather than leaving them out.
188    let has_new_id_token = resp.id_token.as_deref().is_some_and(|v| !v.trim().is_empty());
189    let has_new_access_token = resp.access_token.as_deref().is_some_and(|v| !v.trim().is_empty());
190    let new_id_token = resp
191        .id_token
192        .filter(|v| !v.trim().is_empty())
193        .unwrap_or_else(|| current.id_token.clone());
194    let new_access_token = resp
195        .access_token
196        .filter(|v| !v.trim().is_empty())
197        .unwrap_or_else(|| current.access_token.clone());
198    let new_refresh_token = resp
199        .refresh_token
200        .filter(|v| !v.trim().is_empty())
201        .unwrap_or_else(|| current.refresh_token.clone());
202
203    // Re-exchange the API key only when a new id_token was provided.
204    let openai_api_key = if has_new_id_token {
205        match exchange_openai_chatgpt_api_key(&new_id_token).await {
206            Ok(api_key) => api_key,
207            Err(err) => {
208                tracing::warn!("openai api-key exchange unavailable, falling back to previous key: {err}");
209                current.openai_api_key.clone()
210            }
211        }
212    } else {
213        current.openai_api_key.clone()
214    };
215
216    // Recompute expiry: prefer expires_in from the response, then try to parse
217    // exp from the new access_token JWT. For a **changed** access token without
218    // expires_in or a parseable exp, set None — do NOT inherit the previous
219    // token's expiry, which belongs to a different token.
220    //
221    // Key distinction: `has_new_access_token` means the field was present and
222    // non-blank, NOT that the token value changed. If the endpoint repeats the
223    // same opaque access token without expires_in, the old expiry is still
224    // valid and must be preserved.
225    let access_token_changed = has_new_access_token && new_access_token != current.access_token;
226    let expires_at = if let Some(secs) = resp.expires_in {
227        Some(now.saturating_add(secs))
228    } else if access_token_changed {
229        parse_jwt_exp(&new_access_token)
230    } else {
231        current.expires_at
232    };
233
234    // Update email/plan/account_id only when a new id_token was provided.
235    let (email, plan, account_id) = if has_new_id_token {
236        let id_claims = parse_jwt_claims(&new_id_token)?;
237        let access_claims = parse_jwt_claims(&new_access_token).ok();
238        let email = id_claims.email.clone();
239        let plan = access_claims.as_ref().and_then(|c| c.plan.clone()).or(id_claims.plan);
240        let account_id = access_claims
241            .as_ref()
242            .and_then(|c| c.account_id.clone())
243            .or(id_claims.account_id);
244        (email, plan, account_id)
245    } else {
246        (current.email.clone(), current.plan.clone(), current.account_id.clone())
247    };
248
249    Ok(OpenAIChatGptSession {
250        openai_api_key,
251        id_token: new_id_token,
252        access_token: new_access_token,
253        refresh_token: new_refresh_token,
254        account_id,
255        email,
256        plan,
257        // Preserve the original obtained_at — only refreshed_at advances.
258        obtained_at: current.obtained_at,
259        refreshed_at: now,
260        expires_at,
261    })
262}
263
264async fn build_session_from_token_response(token_response: OpenAITokenResponse) -> Result<OpenAIChatGptSession> {
265    // Validate that the token response contains usable credentials.
266    if token_response.access_token.trim().is_empty() {
267        bail!("openai authorization-code response did not include a usable access token");
268    }
269    if token_response.refresh_token.trim().is_empty() {
270        bail!("openai authorization-code response did not include a usable refresh token");
271    }
272    let id_claims = parse_jwt_claims(&token_response.id_token)?;
273    let access_claims = parse_jwt_claims(&token_response.access_token).ok();
274    let api_key = match exchange_openai_chatgpt_api_key(&token_response.id_token).await {
275        Ok(api_key) => api_key,
276        Err(err) => {
277            tracing::warn!("openai api-key exchange unavailable, falling back to oauth access token: {err}");
278            String::new()
279        }
280    };
281    let now = now_secs();
282    Ok(OpenAIChatGptSession {
283        openai_api_key: api_key,
284        id_token: token_response.id_token,
285        access_token: token_response.access_token,
286        refresh_token: token_response.refresh_token,
287        account_id: access_claims
288            .as_ref()
289            .and_then(|claims| claims.account_id.clone())
290            .or(id_claims.account_id),
291        email: id_claims
292            .email
293            .or_else(|| access_claims.as_ref().and_then(|claims| claims.email.clone())),
294        plan: access_claims.as_ref().and_then(|claims| claims.plan.clone()).or(id_claims.plan),
295        obtained_at: now,
296        refreshed_at: now,
297        expires_at: token_response.expires_in.map(|secs| now.saturating_add(secs)),
298    })
299}
300
301async fn exchange_openai_chatgpt_api_key(id_token: &str) -> Result<String> {
302    #[derive(Deserialize)]
303    struct ExchangeResponse {
304        access_token: String,
305    }
306
307    let identity = resolve_oauth_client_identity()?;
308    let token_client = vtcode_commons::http::create_default_client_without_redirects()
309        .context("failed to build openai token client")?;
310    let exchange: ExchangeResponse =
311        vtcode_commons::http::send_with_retry_transport_only(&crate::oauth_token_retry_policy(), || {
312            token_client
313                .post(OPENAI_TOKEN_URL)
314                .header("Content-Type", "application/x-www-form-urlencoded")
315                .body(format!(
316                    "grant_type={}&client_id={}&requested_token={}&subject_token={}&subject_token_type={}",
317                    urlencoding::encode("urn:ietf:params:oauth:grant-type:token-exchange"),
318                    urlencoding::encode(&identity.client_id),
319                    urlencoding::encode("openai-api-key"),
320                    urlencoding::encode(id_token),
321                    urlencoding::encode("urn:ietf:params:oauth:token-type:id_token"),
322                ))
323                .send()
324        })
325        .await
326        .context("failed to exchange openai id token for api key")?
327        .error_for_status()
328        .context("openai api-key exchange failed")?
329        .json()
330        .await
331        .context("failed to parse openai api-key exchange response")?;
332
333    Ok(exchange.access_token)
334}
335#[derive(Deserialize)]
336struct OpenAITokenResponse {
337    id_token: String,
338    access_token: String,
339    refresh_token: String,
340    #[serde(default)]
341    expires_in: Option<u64>,
342}
343
344/// Refresh-token grant response — all token fields are independently optional
345/// because OpenAI's token endpoint may omit unchanged fields (matching the
346/// behavior observed in `openai/codex`'s `RefreshResponse`). Omitted fields
347/// preserve the previous session's values during merge.
348#[derive(Deserialize)]
349pub(crate) struct OpenAIRefreshResponse {
350    #[serde(default)]
351    pub(crate) id_token: Option<String>,
352    #[serde(default)]
353    pub(crate) access_token: Option<String>,
354    #[serde(default)]
355    pub(crate) refresh_token: Option<String>,
356    #[serde(default)]
357    pub(crate) expires_in: Option<u64>,
358}
359fn session_has_newer_refresh_state(current: &OpenAIChatGptSession, previous: &OpenAIChatGptSession) -> bool {
360    current.refresh_token != previous.refresh_token
361        || current.refreshed_at > previous.refreshed_at
362        || current.obtained_at > previous.obtained_at
363}
364
365pub(crate) struct RefreshLockGuard {
366    file: fs::File,
367}
368
369impl Drop for RefreshLockGuard {
370    fn drop(&mut self) {
371        drop(FileExt::unlock(&self.file));
372    }
373}
374
375pub(crate) async fn acquire_refresh_lock() -> Result<RefreshLockGuard> {
376    let path = auth_storage_dir()?.join(OPENAI_REFRESH_LOCK_FILE);
377    let file = OpenOptions::new()
378        .create(true)
379        .read(true)
380        .write(true)
381        .truncate(false)
382        .open(&path)
383        .context("failed to open openai refresh lock")?;
384    let file = tokio::task::spawn_blocking(move || {
385        file.lock_exclusive().context("failed to acquire openai refresh lock")?;
386        Ok::<_, anyhow::Error>(file)
387    })
388    .await
389    .context("openai refresh lock task failed")??;
390    Ok(RefreshLockGuard { file })
391}
392
393/// Read at most `max_bytes` from an HTTP response body as a string.
394///
395/// Reads the response in chunks and stops once `max_bytes` have been
396/// accumulated, preventing unbounded memory allocation from a misbehaving or
397/// hostile endpoint. Invalid UTF-8 sequences are replaced (lossy) since we
398/// only use the text for best-effort error classification, never for display
399/// or logging.
400async fn read_bounded_text(mut response: reqwest::Response, max_bytes: usize) -> String {
401    let mut buf = Vec::with_capacity(max_bytes.min(8 * 1024));
402    while buf.len() < max_bytes {
403        match response.chunk().await {
404            Ok(Some(chunk)) => {
405                let remaining = max_bytes - buf.len();
406                if chunk.len() <= remaining {
407                    buf.extend_from_slice(&chunk);
408                } else {
409                    buf.extend_from_slice(chunk.get(..remaining).unwrap_or_default());
410                    break;
411                }
412            }
413            Ok(None) => break,
414            Err(_) => break,
415        }
416    }
417    String::from_utf8_lossy(&buf).into_owned()
418}
419
420pub(crate) fn classify_refresh_status_error(status: reqwest::StatusCode, body: &str) -> anyhow::Error {
421    let failure = classify_refresh_failure(status, body);
422    if failure.action() == RefreshFailureAction::ClearStoredSession {
423        if let Err(clear_err) = clear_session_from_all_stores() {
424            tracing::warn!("failed to clear expired openai chatgpt session across all stores: {clear_err}");
425        }
426    }
427    failure.into_error()
428}
429
430fn clear_session_from_all_stores() -> Result<()> {
431    OpenAiSessionStorage::new().clear_all()
432}