Skip to main content

rig_core/providers/copilot/auth/
mod.rs

1use crate::http_client::HttpClientExt;
2use crate::providers::auth::{
3    AuthContext, AuthError, DeviceCodeHandler, Shell, TokenStore, load_record, request,
4    save_record, send_json, token_expired,
5};
6use http::Method;
7use serde::{Deserialize, Serialize};
8use std::fmt;
9
10#[cfg(not(target_family = "wasm"))]
11mod native;
12
13/// The key the record is kept under in the store.
14const STORE_KEY: &str = super::PROVIDER_NAME;
15
16const GITHUB_API_KEY_URL: &str = "https://api.github.com/copilot_internal/v2/token";
17
18/// Derive the Copilot REST base URL from a chat token's `proxy-ep=` segment.
19///
20/// The endpoint is parsed from a credential string, not from explicit caller
21/// configuration. For that reason, token-derived routing is limited to GitHub
22/// Copilot service hosts and HTTPS. Callers that need a custom non-GitHub host
23/// can still opt in explicitly with [`OpenAIConfig::with_base_url`](crate::providers::openai::OpenAIConfig::with_base_url).
24pub(crate) fn base_url_from_token(token: &str) -> Option<String> {
25    let proxy_ep = token
26        .split(';')
27        .find_map(|part| part.trim().strip_prefix("proxy-ep="))?
28        .trim();
29
30    normalize_copilot_proxy_endpoint(proxy_ep)
31}
32
33fn normalize_copilot_proxy_endpoint(proxy_ep: &str) -> Option<String> {
34    if proxy_ep.is_empty() {
35        return None;
36    }
37
38    let candidate = if proxy_ep.starts_with("http://") || proxy_ep.starts_with("https://") {
39        proxy_ep.to_string()
40    } else {
41        format!("https://{proxy_ep}")
42    };
43
44    let mut url = url::Url::parse(&candidate).ok()?;
45    if url.scheme() != "https" || !url.username().is_empty() || url.password().is_some() {
46        return None;
47    }
48    if url.path() != "/" || url.query().is_some() || url.fragment().is_some() {
49        return None;
50    }
51
52    let host = url.host_str()?.to_ascii_lowercase();
53    if !is_allowed_token_derived_copilot_host(&host) {
54        return None;
55    }
56
57    let api_host = host
58        .strip_prefix("proxy.")
59        .map(|suffix| format!("api.{suffix}"))
60        .unwrap_or(host);
61    url.set_host(Some(&api_host)).ok()?;
62
63    Some(url.to_string().trim_end_matches('/').to_string())
64}
65
66fn is_allowed_token_derived_copilot_host(host: &str) -> bool {
67    host == "githubcopilot.com" || host.ends_with(".githubcopilot.com")
68}
69
70#[derive(Clone)]
71pub enum AuthSource {
72    ApiKey(String),
73    GitHubAccessToken(String),
74    OAuth,
75}
76
77impl fmt::Debug for AuthSource {
78    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
79        match self {
80            Self::ApiKey(_) => f.write_str("ApiKey(<redacted>)"),
81            Self::GitHubAccessToken(_) => f.write_str("GitHubAccessToken(<redacted>)"),
82            Self::OAuth => f.write_str("OAuth"),
83        }
84    }
85}
86
87/// Signs in to GitHub, exchanges the GitHub token for a Copilot session, and
88/// keeps both in its [`TokenStore`]. Clones share the store and the refresh
89/// lock.
90#[derive(Clone)]
91pub struct Authenticator(Shell<AuthSource>);
92
93impl fmt::Debug for Authenticator {
94    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
95        self.0.fmt(f)
96    }
97}
98
99impl Authenticator {
100    /// An authenticator over `source`, keeping the GitHub token and the
101    /// session it exchanges for in `store` under
102    /// [`PROVIDER_NAME`](super::PROVIDER_NAME), `copilot`;
103    /// `device_code_handler` shows a device code when the device flow is
104    /// allowed.
105    pub fn new(
106        source: AuthSource,
107        store: impl TokenStore + 'static,
108        device_code_handler: DeviceCodeHandler,
109        allow_device_flow: bool,
110    ) -> Self {
111        Self(Shell::new(
112            source,
113            store,
114            device_code_handler,
115            allow_device_flow,
116        ))
117    }
118
119    /// Resolve the API key and optional API base, refreshing through `http` as needed.
120    /// Return store, transport, or authorization errors. OAuth device login is
121    /// unsupported on WASM; the GitHub token exchange remains available.
122    pub async fn auth_context<H>(&self, http: &H) -> Result<AuthContext, AuthError>
123    where
124        H: HttpClientExt,
125    {
126        match &self.0.source {
127            AuthSource::ApiKey(api_key) => Ok(AuthContext {
128                api_key: api_key.clone().into(),
129                account_id: None,
130                api_base: None,
131            }),
132            AuthSource::GitHubAccessToken(access_token) => {
133                self.auth_context_with_github_access_token(http, access_token)
134                    .await
135            }
136            #[cfg(not(target_family = "wasm"))]
137            AuthSource::OAuth => self.auth_context_oauth(http).await,
138            #[cfg(target_family = "wasm")]
139            AuthSource::OAuth => Err(AuthError::Message(
140                "GitHub Copilot OAuth is not supported on wasm targets".into(),
141            )),
142        }
143    }
144
145    async fn auth_context_with_github_access_token<H>(
146        &self,
147        http: &H,
148        access_token: &str,
149    ) -> Result<AuthContext, AuthError>
150    where
151        H: HttpClientExt,
152    {
153        if let Some(context) = self.0.remembered.live(0) {
154            return Ok(context);
155        }
156        let _held = self.0.hold(STORE_KEY).await?;
157        let record: ApiKeyRecord = load_record(&*self.0.store, STORE_KEY).await?;
158        if record.reusable_for(Some(access_token)) {
159            return Ok(self.remember(record));
160        }
161
162        // A GitHub token an OAuth sign-in kept stays for that sign-in.
163        let session = refresh_api_key(http, access_token)
164            .await?
165            .bound_to(access_token, record.github_token);
166        save_record(&*self.0.store, STORE_KEY, &session).await?;
167        Ok(self.remember(session))
168    }
169
170    /// `session`'s context, remembered until the session expires.
171    fn remember(&self, session: ApiKeyRecord) -> AuthContext {
172        let context = AuthContext {
173            api_base: session.api_base(),
174            api_key: session.token.unwrap_or_default().into(),
175            account_id: None,
176        };
177        self.0.remembered.keep(&context, session.expires_at);
178        context
179    }
180}
181
182/// Copilot API key exchanged for a GitHub access token, and the record kept
183/// under the provider's name.
184#[derive(Debug, Clone, Deserialize, Serialize, Default)]
185struct ApiKeyRecord {
186    /// The GitHub token an OAuth sign-in got, which the exchange takes.
187    #[serde(default, skip_serializing_if = "Option::is_none")]
188    github_token: Option<String>,
189    token: Option<String>,
190    expires_at: Option<i64>,
191    endpoints: Option<ApiKeyEndpoints>,
192    bootstrap_token_fingerprint: Option<String>,
193}
194
195#[derive(Debug, Clone, Deserialize, Serialize, Default)]
196struct ApiKeyEndpoints {
197    api: Option<String>,
198}
199
200impl ApiKeyRecord {
201    fn api_base(&self) -> Option<String> {
202        self.endpoints
203            .as_ref()
204            .and_then(|endpoints| endpoints.api.as_ref())
205            .cloned()
206    }
207
208    /// Whether the key is live and, when `bootstrap_token` is known, was
209    /// exchanged for it.
210    fn reusable_for(&self, bootstrap_token: Option<&str>) -> bool {
211        self.has_live_api_key()
212            && bootstrap_token.is_none_or(|token| {
213                self.bootstrap_token_fingerprint.as_deref()
214                    == Some(bootstrap_token_fingerprint(token).as_str())
215            })
216    }
217
218    /// This session, exchanged for `bootstrap_token`, kept with
219    /// `github_token`.
220    fn bound_to(mut self, bootstrap_token: &str, github_token: Option<String>) -> Self {
221        self.bootstrap_token_fingerprint = Some(bootstrap_token_fingerprint(bootstrap_token));
222        self.github_token = github_token;
223        self
224    }
225
226    fn has_live_api_key(&self) -> bool {
227        self.token
228            .as_ref()
229            .is_some_and(|token| !token.trim().is_empty())
230            && !token_expired(self.expires_at, 0)
231    }
232}
233
234/// The first 16 hex digits of the token's SHA-256, stable across builds.
235fn bootstrap_token_fingerprint(bootstrap_token: &str) -> String {
236    let digest = <sha2::Sha256 as sha2::Digest>::digest(bootstrap_token);
237    digest
238        .iter()
239        .take(8)
240        .map(|byte| format!("{byte:02x}"))
241        .collect()
242}
243
244/// Exchange a GitHub access token for a Copilot API key.
245/// Return transport errors, or an error when the response has no non-blank token.
246async fn refresh_api_key<H>(http: &H, access_token: &str) -> Result<ApiKeyRecord, AuthError>
247where
248    H: HttpClientExt,
249{
250    let response: ApiKeyRecord = send_json(
251        http,
252        request(Method::GET, GITHUB_API_KEY_URL)
253            .header(http::header::ACCEPT, "application/json")
254            .header("editor-version", super::EDITOR_VERSION)
255            .header("editor-plugin-version", super::EDITOR_PLUGIN_VERSION)
256            .header("user-agent", super::USER_AGENT)
257            .header(http::header::AUTHORIZATION, format!("token {access_token}"))
258            .body(bytes::Bytes::new()),
259    )
260    .await?;
261
262    if response
263        .token
264        .as_ref()
265        .is_none_or(|token| token.trim().is_empty())
266    {
267        return Err(AuthError::Message(
268            "GitHub Copilot API key response did not include a token".into(),
269        ));
270    }
271
272    Ok(response)
273}