Skip to main content

vtcode_auth/
oauth_server.rs

1use anyhow::{Context, Result};
2use axum::{
3    Router,
4    extract::{Query, State},
5    response::Html,
6    routing::get,
7};
8use serde::{Deserialize, Serialize};
9use std::fmt;
10use std::net::SocketAddr;
11use std::str::FromStr;
12use std::sync::Arc;
13use std::time::Duration;
14use tokio::sync::{mpsc, oneshot};
15
16const DEFAULT_CALLBACK_TIMEOUT_SECS: u64 = 300;
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
19#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
20#[serde(rename_all = "snake_case")]
21pub enum OAuthProvider {
22    OpenAi,
23    OpenRouter,
24}
25
26impl OAuthProvider {
27    #[must_use]
28    fn slug(self) -> &'static str {
29        match self {
30            Self::OpenAi => "openai",
31            Self::OpenRouter => "openrouter",
32        }
33    }
34
35    #[must_use]
36    pub fn display_name(self) -> &'static str {
37        match self {
38            Self::OpenAi => "OpenAI",
39            Self::OpenRouter => "OpenRouter",
40        }
41    }
42
43    #[must_use]
44    pub fn subtitle(self) -> &'static str {
45        match self {
46            Self::OpenAi => "Your ChatGPT subscription is now connected.",
47            Self::OpenRouter => "Your OpenRouter account is now connected.",
48        }
49    }
50
51    #[must_use]
52    pub fn failure_subtitle(self) -> &'static str {
53        match self {
54            Self::OpenAi => "Unable to connect your ChatGPT subscription.",
55            Self::OpenRouter => "Unable to connect your OpenRouter account.",
56        }
57    }
58
59    #[must_use]
60    pub fn retry_hint(self) -> String {
61        format!("You can try again anytime using /login {}", self.slug())
62    }
63
64    #[must_use]
65    pub fn supports_manual_refresh(self) -> bool {
66        matches!(self, Self::OpenAi)
67    }
68}
69
70impl fmt::Display for OAuthProvider {
71    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72        f.write_str(self.slug())
73    }
74}
75
76impl FromStr for OAuthProvider {
77    type Err = ();
78
79    fn from_str(value: &str) -> std::result::Result<Self, Self::Err> {
80        match value.trim().to_ascii_lowercase().as_str() {
81            "openai" => Ok(Self::OpenAi),
82            "openrouter" => Ok(Self::OpenRouter),
83            _ => Err(()),
84        }
85    }
86}
87
88#[derive(Debug, Clone, Copy)]
89pub struct OAuthCallbackPage {
90    provider_slug: &'static str,
91    success_subtitle: &'static str,
92    failure_subtitle: &'static str,
93    retry_hint: &'static str,
94}
95
96impl OAuthCallbackPage {
97    #[must_use]
98    pub fn new(provider: OAuthProvider) -> Self {
99        match provider {
100            OAuthProvider::OpenAi => Self {
101                provider_slug: "openai",
102                success_subtitle: "Your ChatGPT subscription is now connected.",
103                failure_subtitle: "Unable to connect your ChatGPT subscription.",
104                retry_hint: "You can try again anytime using /login openai",
105            },
106            OAuthProvider::OpenRouter => Self {
107                provider_slug: "openrouter",
108                success_subtitle: "Your OpenRouter account is now connected.",
109                failure_subtitle: "Unable to connect your OpenRouter account.",
110                retry_hint: "You can try again anytime using /login openrouter",
111            },
112        }
113    }
114
115    #[must_use]
116    pub fn custom(
117        provider_slug: &'static str,
118        success_subtitle: &'static str,
119        failure_subtitle: &'static str,
120        retry_hint: &'static str,
121    ) -> Self {
122        Self {
123            provider_slug,
124            success_subtitle,
125            failure_subtitle,
126            retry_hint,
127        }
128    }
129
130    #[must_use]
131    fn provider_slug(&self) -> &'static str {
132        self.provider_slug
133    }
134
135    #[must_use]
136    fn success_subtitle(&self) -> &'static str {
137        self.success_subtitle
138    }
139
140    #[must_use]
141    fn failure_subtitle(&self) -> &'static str {
142        self.failure_subtitle
143    }
144
145    #[must_use]
146    fn retry_hint(&self) -> &'static str {
147        self.retry_hint
148    }
149}
150
151/// OAuth callback result from the local HTTP server.
152///
153/// Custom `Debug` redacts the authorization `Code` and `Error` payloads —
154/// the code is a short-lived secret exchangeable for tokens, and error
155/// strings come from untrusted callback query parameters that may contain
156/// tenant identifiers, URLs, or other sensitive values.
157#[derive(Clone)]
158pub enum AuthCallbackOutcome {
159    Code(String),
160    Cancelled,
161    Error(String),
162}
163
164impl fmt::Debug for AuthCallbackOutcome {
165    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
166        match self {
167            Self::Code(_) => f.debug_tuple("Code").field(&"<redacted>").finish(),
168            Self::Cancelled => f.debug_struct("Cancelled").finish(),
169            Self::Error(_) => f.debug_tuple("Error").field(&"<redacted>").finish(),
170        }
171    }
172}
173
174pub struct AuthCodeCallbackServer {
175    timeout: Duration,
176    result_rx: mpsc::Receiver<AuthCallbackOutcome>,
177    shutdown_tx: Option<oneshot::Sender<()>>,
178    server_handle: Option<tokio::task::JoinHandle<()>>,
179}
180
181impl AuthCodeCallbackServer {
182    async fn start(
183        port: u16,
184        timeout_secs: u64,
185        page: OAuthCallbackPage,
186        expected_state: Option<String>,
187    ) -> Result<Self> {
188        let (result_tx, result_rx) = mpsc::channel::<AuthCallbackOutcome>(1);
189        let (shutdown_tx, shutdown_rx) = oneshot::channel::<()>();
190        let state = Arc::new(AuthCallbackState { page, expected_state, result_tx });
191
192        let app = Router::new()
193            .route("/callback", get(handle_callback))
194            .route("/auth/callback", get(handle_callback))
195            .route("/cancel", get(handle_cancel))
196            .route("/health", get(|| async { "OK" }))
197            .with_state(state);
198
199        let addr = SocketAddr::from(([127, 0, 0, 1], port));
200        let listener = tokio::net::TcpListener::bind(addr)
201            .await
202            .with_context(|| format!("failed to bind localhost callback server on port {port}"))?;
203
204        let server = axum::serve(listener, app).with_graceful_shutdown(async move {
205            drop(shutdown_rx.await);
206        });
207        let server_handle = tokio::spawn(async move {
208            if let Err(err) = server.await {
209                tracing::error!("OAuth callback server error: {}", err);
210            }
211        });
212
213        Ok(Self {
214            timeout: callback_timeout(timeout_secs),
215            result_rx,
216            shutdown_tx: Some(shutdown_tx),
217            server_handle: Some(server_handle),
218        })
219    }
220
221    pub async fn wait(mut self) -> Result<AuthCallbackOutcome> {
222        let result = tokio::select! {
223            Some(result) = self.result_rx.recv() => result,
224            _ = tokio::time::sleep(self.timeout) => {
225                AuthCallbackOutcome::Error(format!(
226                    "OAuth flow timed out after {} seconds",
227                    self.timeout.as_secs()
228                ))
229            }
230        };
231
232        // No callback after the selected outcome can be consumed; close the
233        // receiver before yielding to graceful shutdown.
234        self.result_rx.close();
235        self.shutdown().await;
236        Ok(result)
237    }
238
239    async fn shutdown(&mut self) {
240        if let Some(shutdown_tx) = self.shutdown_tx.take() {
241            let _ignored = shutdown_tx.send(());
242        }
243        if let Some(server_handle) = self.server_handle.take() {
244            drop(server_handle.await);
245        }
246    }
247}
248
249impl Drop for AuthCodeCallbackServer {
250    fn drop(&mut self) {
251        if let Some(shutdown_tx) = self.shutdown_tx.take() {
252            let _ignored = shutdown_tx.send(());
253        }
254        if let Some(server_handle) = self.server_handle.take() {
255            server_handle.abort();
256        }
257    }
258}
259
260#[derive(Deserialize)]
261struct AuthCallbackParams {
262    code: Option<String>,
263    error: Option<String>,
264    error_description: Option<String>,
265    state: Option<String>,
266}
267
268struct AuthCallbackState {
269    page: OAuthCallbackPage,
270    expected_state: Option<String>,
271    result_tx: mpsc::Sender<AuthCallbackOutcome>,
272}
273
274pub async fn start_auth_code_callback_server(
275    port: u16,
276    timeout_secs: u64,
277    page: OAuthCallbackPage,
278    expected_state: Option<String>,
279) -> Result<AuthCodeCallbackServer> {
280    AuthCodeCallbackServer::start(port, timeout_secs, page, expected_state).await
281}
282
283pub async fn run_auth_code_callback_server(
284    port: u16,
285    timeout_secs: u64,
286    page: OAuthCallbackPage,
287    expected_state: Option<String>,
288) -> Result<AuthCallbackOutcome> {
289    start_auth_code_callback_server(port, timeout_secs, page, expected_state)
290        .await?
291        .wait()
292        .await
293}
294
295async fn handle_callback(
296    State(state): State<Arc<AuthCallbackState>>,
297    Query(params): Query<AuthCallbackParams>,
298) -> Html<String> {
299    tracing::info!(
300        provider = state.page.provider_slug(),
301        has_code = params.code.is_some(),
302        has_error = params.error.is_some(),
303        "received oauth callback"
304    );
305    if let Some(expected_state) = state.expected_state.as_deref() {
306        match params.state.as_deref() {
307            Some(actual_state) if actual_state == expected_state => {}
308            _ => {
309                return Html(error_html(state.page, "OAuth error: state mismatch"));
310            }
311        }
312    }
313
314    if let Some(error) = params.error {
315        let message = match params.error_description {
316            Some(description) if !description.trim().is_empty() => {
317                format!("OAuth error: {error} - {description}")
318            }
319            _ => format!("OAuth error: {error}"),
320        };
321        return finish_callback(&state, AuthCallbackOutcome::Error(message.clone()), error_html(state.page, &message));
322    }
323
324    let Some(code) = params.code else {
325        let message = "Missing authorization code".to_string();
326        return finish_callback(&state, AuthCallbackOutcome::Error(message.clone()), error_html(state.page, &message));
327    };
328
329    finish_callback(&state, AuthCallbackOutcome::Code(code), success_html(state.page))
330}
331
332async fn handle_cancel(State(state): State<Arc<AuthCallbackState>>) -> Html<String> {
333    finish_callback(&state, AuthCallbackOutcome::Cancelled, cancelled_html(state.page))
334}
335
336fn finish_callback(state: &AuthCallbackState, outcome: AuthCallbackOutcome, page: String) -> Html<String> {
337    if state.result_tx.try_send(outcome).is_ok() {
338        Html(page)
339    } else {
340        Html(error_html(state.page, "OAuth callback is no longer accepting results"))
341    }
342}
343
344fn success_html(page: OAuthCallbackPage) -> String {
345    base_html(
346        "Authentication Successful",
347        page.success_subtitle(),
348        Some("You may now close this window and return to VT Code."),
349        "✓",
350        "#22c55e",
351        None,
352    )
353}
354
355fn error_html(page: OAuthCallbackPage, error: &str) -> String {
356    base_html("Authentication Failed", page.failure_subtitle(), None, "✕", "#ef4444", Some(error))
357}
358
359fn cancelled_html(page: OAuthCallbackPage) -> String {
360    base_html("Authentication Cancelled", page.retry_hint(), None, "—", "#71717a", None)
361}
362
363fn base_html(
364    title: &str,
365    subtitle: &str,
366    close_note: Option<&str>,
367    icon: &str,
368    accent: &str,
369    error: Option<&str>,
370) -> String {
371    let close_note_html = close_note
372        .map(|value| format!(r#"<p class="close-note">{}</p>"#, html_escape(value)))
373        .unwrap_or_default();
374    let error_html = error
375        .map(|value| format!(r#"<div class="error">{}</div>"#, html_escape(value)))
376        .unwrap_or_default();
377    let auto_close = if close_note.is_some() {
378        r#"<script>setTimeout(() => window.close(), 3000);</script>"#
379    } else {
380        ""
381    };
382
383    format!(
384        r##"<!DOCTYPE html>
385<html>
386<head>
387    <title>VT Code - {title}</title>
388    <style>
389        @font-face {{
390            font-family: 'SF Pro Display';
391            src: local('SF Pro Display'), local('.SF NS Display'), local('Helvetica Neue');
392        }}
393        @font-face {{
394            font-family: 'SF Mono';
395            src: local('SF Mono'), local('Menlo'), local('Monaco');
396        }}
397        :root {{
398            color-scheme: dark;
399            --bg: #0a0a0a;
400            --panel: #111111;
401            --panel-border: #262626;
402            --text: #fafafa;
403            --muted: #a1a1aa;
404            --subtle: #52525b;
405            --code-bg: #18181b;
406            --code-border: #27272a;
407            --accent: {accent};
408        }}
409        * {{ box-sizing: border-box; }}
410        body {{
411            font-family: 'SF Pro Display', -apple-system, BlinkMacSystemFont, system-ui, sans-serif;
412            display: flex;
413            justify-content: center;
414            align-items: center;
415            min-height: 100vh;
416            margin: 0;
417            background:
418                radial-gradient(circle at top, rgba(255,255,255,0.04), transparent 32%),
419                linear-gradient(180deg, var(--bg), #050505);
420            color: var(--text);
421            padding: 24px;
422        }}
423        .container {{
424            text-align: center;
425            padding: 2.75rem 3rem;
426            border: 1px solid var(--panel-border);
427            border-radius: 14px;
428            background: rgba(17, 17, 17, 0.92);
429            max-width: 460px;
430            width: 100%;
431            box-shadow: 0 30px 90px rgba(0, 0, 0, 0.35);
432        }}
433        .logo {{
434            margin-bottom: 1.5rem;
435        }}
436        .logo-mark {{
437            display: inline-flex;
438            align-items: center;
439            justify-content: center;
440            font-size: 0.95rem;
441            letter-spacing: 0.24em;
442            text-transform: uppercase;
443            color: var(--muted);
444        }}
445        .status-icon {{
446            width: 52px;
447            height: 52px;
448            margin: 0 auto 1.25rem;
449            border: 2px solid var(--accent);
450            border-radius: 50%;
451            display: flex;
452            align-items: center;
453            justify-content: center;
454            font-size: 1.25rem;
455            color: var(--accent);
456        }}
457        h1 {{
458            margin: 0 0 0.75rem 0;
459            font-size: 1.25rem;
460            font-weight: 600;
461            letter-spacing: -0.02em;
462        }}
463        p {{
464            color: var(--muted);
465            margin: 0;
466            font-size: 0.92rem;
467            line-height: 1.55;
468        }}
469        .close-note {{
470            margin-top: 1.25rem;
471            font-size: 0.78rem;
472            color: var(--subtle);
473        }}
474        .error {{
475            margin-top: 1.35rem;
476            padding: 0.95rem 1rem;
477            background: var(--code-bg);
478            border: 1px solid var(--code-border);
479            border-radius: 10px;
480            font-family: 'SF Mono', Menlo, Monaco, monospace;
481            font-size: 0.75rem;
482            color: #d4d4d8;
483            word-break: break-word;
484            text-align: left;
485        }}
486    </style>
487</head>
488<body>
489    <div class="container">
490        <div class="logo">
491            <div class="logo-mark">&gt; VT Code</div>
492        </div>
493        <div class="status-icon">{icon}</div>
494        <h1>{title}</h1>
495        <p>{subtitle}</p>
496        {close_note_html}
497        {error_html}
498    </div>
499    {auto_close}
500</body>
501</html>"##,
502        title = html_escape(title),
503        subtitle = html_escape(subtitle),
504        icon = icon,
505        accent = accent,
506        close_note_html = close_note_html,
507        error_html = error_html,
508        auto_close = auto_close,
509    )
510}
511
512fn html_escape(value: &str) -> String {
513    value.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;")
514}
515
516fn callback_timeout(timeout_secs: u64) -> Duration {
517    Duration::from_secs(if timeout_secs == 0 {
518        DEFAULT_CALLBACK_TIMEOUT_SECS
519    } else {
520        timeout_secs
521    })
522}
523
524#[cfg(test)]
525mod tests {
526    use super::*;
527    use axum::extract::{Query, State};
528    use reqwest::Client;
529
530    #[test]
531    fn oauth_provider_parses_known_providers() {
532        assert_eq!("openai".parse::<OAuthProvider>(), Ok(OAuthProvider::OpenAi));
533        assert_eq!("openrouter".parse::<OAuthProvider>(), Ok(OAuthProvider::OpenRouter));
534        assert!("other".parse::<OAuthProvider>().is_err());
535    }
536
537    #[test]
538    fn success_html_mentions_vtcode_and_autoclose() {
539        let html = success_html(OAuthCallbackPage::new(OAuthProvider::OpenAi));
540        assert!(html.contains("VT Code"));
541        assert!(html.contains("Authentication Successful"));
542        assert!(html.contains("window.close"));
543    }
544
545    #[tokio::test]
546    async fn callback_rejects_state_mismatch() {
547        let (result_tx, mut result_rx) = mpsc::channel(1);
548        let state = Arc::new(AuthCallbackState {
549            page: OAuthCallbackPage::new(OAuthProvider::OpenAi),
550            expected_state: Some("expected-state".to_string()),
551            result_tx,
552        });
553
554        for rejected_state in [None, Some("wrong-state".to_string())] {
555            let html = handle_callback(
556                State(Arc::clone(&state)),
557                Query(AuthCallbackParams {
558                    code: Some("auth-code".to_string()),
559                    error: None,
560                    error_description: None,
561                    state: rejected_state,
562                }),
563            )
564            .await;
565            assert!(html.0.contains("Authentication Failed"));
566            assert!(matches!(result_rx.try_recv(), Err(mpsc::error::TryRecvError::Empty)));
567        }
568        let valid = handle_callback(
569            State(state),
570            Query(AuthCallbackParams {
571                code: Some("valid-code".to_string()),
572                error: None,
573                error_description: None,
574                state: Some("expected-state".to_string()),
575            }),
576        )
577        .await;
578        assert!(valid.0.contains("Authentication Successful"));
579        assert!(matches!(result_rx.recv().await, Some(AuthCallbackOutcome::Code(code)) if code == "valid-code"));
580    }
581
582    #[tokio::test]
583    async fn callbacks_do_not_block_when_result_channel_is_full() {
584        let (result_tx, mut result_rx) = mpsc::channel(1);
585        result_tx
586            .try_send(AuthCallbackOutcome::Code("first".into()))
587            .expect("fill channel");
588        let state = Arc::new(AuthCallbackState {
589            page: OAuthCallbackPage::new(OAuthProvider::OpenAi),
590            expected_state: Some("expected".into()),
591            result_tx,
592        });
593        let callback = handle_callback(
594            State(Arc::clone(&state)),
595            Query(AuthCallbackParams {
596                code: Some("second".into()),
597                error: None,
598                error_description: None,
599                state: Some("expected".into()),
600            }),
601        );
602        let page = tokio::time::timeout(Duration::from_secs(1), callback)
603            .await
604            .expect("callback must not block");
605        assert!(page.0.contains("no longer accepting results"));
606        let page = tokio::time::timeout(Duration::from_secs(1), handle_cancel(State(state)))
607            .await
608            .expect("cancel must not block");
609        assert!(page.0.contains("no longer accepting results"));
610        assert!(matches!(result_rx.recv().await, Some(AuthCallbackOutcome::Code(code)) if code == "first"));
611        assert!(result_rx.try_recv().is_err());
612    }
613
614    #[tokio::test]
615    async fn wait_closes_result_channel_before_server_shutdown() {
616        let (result_tx, result_rx) = mpsc::channel(1);
617        result_tx
618            .try_send(AuthCallbackOutcome::Code("first".into()))
619            .expect("queue result");
620        let (shutdown_tx, shutdown_rx) = oneshot::channel();
621        let (observed_tx, observed_rx) = oneshot::channel();
622        let server_handle = tokio::spawn(async move {
623            shutdown_rx.await.expect("shutdown signal");
624            observed_tx.send(result_tx.is_closed()).expect("shutdown observer");
625        });
626        let server = AuthCodeCallbackServer {
627            timeout: Duration::from_secs(1),
628            result_rx,
629            shutdown_tx: Some(shutdown_tx),
630            server_handle: Some(server_handle),
631        };
632        assert!(matches!(server.wait().await.expect("wait"), AuthCallbackOutcome::Code(code) if code == "first"));
633        assert!(observed_rx.await.expect("shutdown observation"));
634    }
635
636    #[tokio::test]
637    async fn callback_server_starts_listening_before_wait() {
638        let listener = match std::net::TcpListener::bind(("127.0.0.1", 0)) {
639            Ok(listener) => listener,
640            Err(err) if err.kind() == std::io::ErrorKind::PermissionDenied => return,
641            Err(err) => panic!("bind temp port: {err}"),
642        };
643        let port = listener.local_addr().expect("local addr").port();
644        drop(listener);
645
646        let server = start_auth_code_callback_server(port, 5, OAuthCallbackPage::new(OAuthProvider::OpenAi), None)
647            .await
648            .expect("start callback server");
649        let client = Client::builder().no_proxy().build().expect("build http client");
650
651        let health = client
652            .get(format!("http://127.0.0.1:{port}/health"))
653            .send()
654            .await
655            .expect("health request should succeed");
656        assert!(health.status().is_success());
657
658        let cancel = client
659            .get(format!("http://127.0.0.1:{port}/cancel"))
660            .send()
661            .await
662            .expect("cancel request should succeed");
663        assert!(cancel.status().is_success());
664
665        assert!(matches!(server.wait().await.expect("wait for callback outcome"), AuthCallbackOutcome::Cancelled));
666    }
667}