car-auth 0.24.0

Shared Parslee OAuth2 PKCE + token/keychain logic for the CAR CLI and daemon
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
//! Shared Parslee OAuth2 PKCE + token/keychain logic.
//!
//! Used by `car-cli` (`car auth login parslee`, loopback flow) and by
//! `car-server` (the `auth.*` JSON-RPC surface that CAR Host.app's
//! signup GUI drives). The keychain keys + default service exactly
//! match what `car-inference` reads at request time
//! (`PARSLEE_ACCESS_TOKEN`, default `"car"` service) — see
//! `car-inference` `remote.rs::lease_key`.

use base64::Engine;
use serde::Deserialize;
use sha2::{Digest, Sha256};

use car_secrets::{SecretRef, SecretStore};

pub const PARSLEE_ACCESS_TOKEN_KEY: &str = "PARSLEE_ACCESS_TOKEN";
pub const PARSLEE_REFRESH_TOKEN_KEY: &str = "PARSLEE_REFRESH_TOKEN";
pub const PARSLEE_EXPIRES_AT_KEY: &str = "PARSLEE_ACCESS_TOKEN_EXPIRES_AT";
pub const PARSLEE_API_BASE_KEY: &str = "PARSLEE_API_BASE";
pub const DEFAULT_API_BASE: &str = "https://api.parslee.ai";

/// `/connect/token` success body.
#[derive(Debug, Clone, Deserialize)]
pub struct TokenSet {
    pub access_token: String,
    pub refresh_token: String,
    pub expires_in: u64,
    pub token_type: String,
}

fn epoch_seconds() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0)
}

/// PKCE code verifier (URL-safe, no padding).
pub fn pkce_verifier() -> String {
    let raw = format!(
        "{}{}",
        uuid::Uuid::new_v4().simple(),
        uuid::Uuid::new_v4().simple()
    );
    base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(raw.as_bytes())
}

/// Opaque OAuth `state` value (CSRF guard).
pub fn new_state() -> String {
    uuid::Uuid::new_v4().simple().to_string()
}

/// PKCE S256 challenge for a verifier.
pub fn pkce_challenge(verifier: &str) -> String {
    let digest = Sha256::digest(verifier.as_bytes());
    base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(digest)
}

/// Build the `/connect/authorize` URL the user opens in a browser.
pub fn authorize_url(
    api_base: &str,
    client_id: &str,
    redirect_uri: &str,
    state: &str,
    challenge: &str,
    provider: Option<&str>,
) -> Result<String, String> {
    let mut url = reqwest::Url::parse(&format!(
        "{}/connect/authorize",
        api_base.trim_end_matches('/')
    ))
    .map_err(|e| format!("build authorize URL: {e}"))?;
    url.query_pairs_mut()
        .append_pair("client_id", client_id)
        .append_pair("redirect_uri", redirect_uri)
        .append_pair("response_type", "code")
        .append_pair("scope", "openid profile email")
        .append_pair("state", state)
        .append_pair("code_challenge", challenge)
        .append_pair("code_challenge_method", "S256");
    if let Some(provider) = provider {
        url.query_pairs_mut().append_pair("provider", provider);
    }
    Ok(url.to_string())
}

fn form_body(pairs: &[(&str, &str)]) -> String {
    let mut s = String::new();
    for (i, (k, v)) in pairs.iter().enumerate() {
        if i > 0 {
            s.push('&');
        }
        s.push_str(&urlencode(k));
        s.push('=');
        s.push_str(&urlencode(v));
    }
    s
}

fn urlencode(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for b in s.bytes() {
        match b {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
                out.push(b as char)
            }
            _ => out.push_str(&format!("%{b:02X}")),
        }
    }
    out
}

/// Exchange an authorization code + PKCE verifier for tokens.
pub async fn exchange_code(
    api_base: &str,
    client_id: &str,
    redirect_uri: &str,
    code: &str,
    verifier: &str,
) -> Result<TokenSet, String> {
    let body = form_body(&[
        ("grant_type", "authorization_code"),
        ("client_id", client_id),
        ("redirect_uri", redirect_uri),
        ("code", code),
        ("code_verifier", verifier),
    ]);
    let token_url = format!("{}/connect/token", api_base.trim_end_matches('/'));
    let response = reqwest::Client::new()
        .post(token_url)
        .header("content-type", "application/x-www-form-urlencoded")
        .body(body)
        .send()
        .await
        .map_err(|e| format!("exchange Parslee authorization code: {e}"))?;
    let status = response.status();
    let text = response
        .text()
        .await
        .map_err(|e| format!("read token response: {e}"))?;
    if !status.is_success() {
        return Err(format!("Parslee token exchange failed: HTTP {status}: {text}"));
    }
    let token: TokenSet =
        serde_json::from_str(&text).map_err(|e| format!("parse token response: {e}"))?;
    if !token.token_type.eq_ignore_ascii_case("bearer") {
        return Err(format!("unexpected Parslee token_type `{}`", token.token_type));
    }
    Ok(token)
}

fn put(key: &str, value: &str) -> Result<(), String> {
    SecretStore::new()
        .put(&SecretRef::with_default_service(key), value)
        .map_err(|e| format!("store {key}: {e}"))
}

/// Persist a token set + the API base into the OS keychain (default
/// `"car"` service — the same place `car-inference` reads from).
pub fn store_tokens(api_base: &str, token: &TokenSet) -> Result<(), String> {
    put(PARSLEE_ACCESS_TOKEN_KEY, &token.access_token)?;
    put(PARSLEE_REFRESH_TOKEN_KEY, &token.refresh_token)?;
    put(PARSLEE_API_BASE_KEY, api_base.trim_end_matches('/'))?;
    put(
        PARSLEE_EXPIRES_AT_KEY,
        &(epoch_seconds() + token.expires_in).to_string(),
    )?;
    Ok(())
}

/// Remove all stored Parslee credentials. Idempotent.
pub fn clear_tokens() -> Result<(), String> {
    let store = SecretStore::new();
    for key in [
        PARSLEE_ACCESS_TOKEN_KEY,
        PARSLEE_REFRESH_TOKEN_KEY,
        PARSLEE_EXPIRES_AT_KEY,
        PARSLEE_API_BASE_KEY,
    ] {
        let _ = store.delete(&SecretRef::with_default_service(key));
    }
    Ok(())
}

/// Current access token (env override first, then keychain).
pub fn access_token() -> Option<String> {
    car_secrets::resolve_env_or_keychain(PARSLEE_ACCESS_TOKEN_KEY)
}

/// Resolve the API base: explicit override → stored → default.
pub fn api_base(override_: Option<&str>) -> String {
    override_
        .map(|s| s.trim_end_matches('/').to_string())
        .or_else(|| car_secrets::resolve_env_or_keychain(PARSLEE_API_BASE_KEY))
        .unwrap_or_else(|| DEFAULT_API_BASE.to_string())
}

/// Fetch the Parslee session JSON for the stored token. Returns the
/// raw response body (the caller renders it). `Ok(None)` = not signed in.
pub async fn fetch_status(api_base_override: Option<&str>) -> Result<Option<String>, String> {
    let Some(access) = access_token() else {
        return Ok(None);
    };
    let base = api_base(api_base_override);
    let response = reqwest::Client::new()
        .get(format!("{}/connect/session", base.trim_end_matches('/')))
        .bearer_auth(access)
        .send()
        .await
        .map_err(|e| format!("fetch Parslee session: {e}"))?;
    let status = response.status();
    let text = response
        .text()
        .await
        .map_err(|e| format!("read Parslee session response: {e}"))?;
    if !status.is_success() {
        return Err(format!("Parslee session check failed: HTTP {status}: {text}"));
    }
    Ok(Some(text))
}

// First-login onboarding is intentionally NOT here. Brand-new users
// are routed through Parslee's existing hosted web consent/org page
// during the `/connect/authorize` browser hand-off (see m365dotnet
// `specs/draft/car-inference-gateway-auth.md` B6), so the token CAR
// redeems already carries `active_org`. CAR is a pure OAuth client and
// never touches consent — there is no `ensure_org`, by design.

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn pkce_challenge_is_s256_urlsafe_nopad() {
        let v = pkce_verifier();
        let c = pkce_challenge(&v);
        assert!(!c.contains('=') && !c.contains('+') && !c.contains('/'));
        assert_eq!(c, pkce_challenge(&v)); // deterministic
    }

    #[test]
    fn authorize_url_has_pkce_and_provider() {
        let u = authorize_url(
            "https://api.parslee.ai/",
            "parslee-car",
            "http://localhost:8765/auth/callback",
            "st8",
            "chal",
            Some("microsoft"),
        )
        .unwrap();
        assert!(u.starts_with("https://api.parslee.ai/connect/authorize?"));
        assert!(u.contains("code_challenge=chal"));
        assert!(u.contains("code_challenge_method=S256"));
        assert!(u.contains("client_id=parslee-car"));
        assert!(u.contains("provider=microsoft"));
    }

    #[test]
    fn api_base_precedence() {
        assert_eq!(api_base(Some("https://x.test/")), "https://x.test");
    }

    /// Hand-rolled loopback HTTP mock — no extra prod dep, no feature
    /// flags. Serves exactly `expected` one-shot requests, records
    /// what came in, and replies with whatever `respond` returns.
    /// Lets the networked auth fns be exercised end-to-end in CI
    /// without the real Parslee backend (or the OS keychain — the
    /// token is injected via the `PARSLEE_ACCESS_TOKEN` env override).
    mod mock {
        use std::io::{Read, Write};
        use std::net::TcpListener;
        use std::sync::{Arc, Mutex};
        use std::thread;

        pub struct Recorded {
            pub method: String,
            pub path: String,
            pub authorization: Option<String>,
            pub content_type: Option<String>,
            pub body: String,
        }

        pub struct Mock {
            pub base: String,
            pub recorded: Arc<Mutex<Vec<Recorded>>>,
            handle: Option<thread::JoinHandle<()>>,
        }

        impl Drop for Mock {
            fn drop(&mut self) {
                if let Some(h) = self.handle.take() {
                    let _ = h.join();
                }
            }
        }

        fn find(hay: &[u8], needle: &[u8]) -> Option<usize> {
            hay.windows(needle.len()).position(|w| w == needle)
        }

        pub fn start(
            expected: usize,
            respond: impl Fn(&Recorded) -> (u16, String) + Send + 'static,
        ) -> Mock {
            let listener = TcpListener::bind("127.0.0.1:0").unwrap();
            let port = listener.local_addr().unwrap().port();
            let recorded = Arc::new(Mutex::new(Vec::new()));
            let rec = recorded.clone();
            let handle = thread::spawn(move || {
                for _ in 0..expected {
                    let (mut stream, _) = listener.accept().unwrap();
                    let mut buf = Vec::new();
                    let mut tmp = [0u8; 1024];
                    loop {
                        let n = stream.read(&mut tmp).unwrap();
                        if n == 0 {
                            break;
                        }
                        buf.extend_from_slice(&tmp[..n]);
                        let Some(hdr_end) = find(&buf, b"\r\n\r\n") else {
                            continue;
                        };
                        let headers = String::from_utf8_lossy(&buf[..hdr_end]).into_owned();
                        let content_length = headers
                            .lines()
                            .find_map(|l| {
                                let (k, v) = l.split_once(':')?;
                                if k.eq_ignore_ascii_case("content-length") {
                                    v.trim().parse::<usize>().ok()
                                } else {
                                    None
                                }
                            })
                            .unwrap_or(0);
                        let body_start = hdr_end + 4;
                        while buf.len() < body_start + content_length {
                            let n = stream.read(&mut tmp).unwrap();
                            if n == 0 {
                                break;
                            }
                            buf.extend_from_slice(&tmp[..n]);
                        }
                        let mut header_lines = headers.lines();
                        let req_line = header_lines.next().unwrap_or("");
                        let mut rl = req_line.split_whitespace();
                        let method = rl.next().unwrap_or("").to_string();
                        let path = rl.next().unwrap_or("").to_string();
                        let mut authorization = None;
                        let mut content_type = None;
                        for l in header_lines {
                            if let Some((k, v)) = l.split_once(':') {
                                if k.eq_ignore_ascii_case("authorization") {
                                    authorization = Some(v.trim().to_string());
                                } else if k.eq_ignore_ascii_case("content-type") {
                                    content_type = Some(v.trim().to_string());
                                }
                            }
                        }
                        let body = String::from_utf8_lossy(
                            &buf[body_start..(body_start + content_length).min(buf.len())],
                        )
                        .into_owned();
                        let r = Recorded {
                            method,
                            path,
                            authorization,
                            content_type,
                            body,
                        };
                        let (code, resp_body) = respond(&r);
                        rec.lock().unwrap().push(r);
                        let resp = format!(
                            "HTTP/1.1 {code} OK\r\ncontent-type: application/json\r\n\
                             content-length: {}\r\nconnection: close\r\n\r\n{}",
                            resp_body.len(),
                            resp_body
                        );
                        stream.write_all(resp.as_bytes()).unwrap();
                        let _ = stream.flush();
                        break;
                    }
                }
            });
            Mock {
                base: format!("http://127.0.0.1:{port}"),
                recorded,
                handle: Some(handle),
            }
        }
    }

    #[tokio::test]
    async fn exchange_code_round_trips_token() {
        let mock = mock::start(1, |_r| {
            (
                200,
                r#"{"access_token":"a","refresh_token":"r","expires_in":3600,"token_type":"Bearer"}"#
                    .to_string(),
            )
        });
        let token = exchange_code(
            &mock.base,
            "parslee-car",
            "http://localhost:1/cb",
            "thecode",
            "theverifier",
        )
        .await
        .unwrap();
        assert_eq!(token.access_token, "a");
        assert_eq!(token.refresh_token, "r");
        assert_eq!(token.expires_in, 3600);

        let reqs = mock.recorded.lock().unwrap();
        assert_eq!(reqs.len(), 1);
        assert_eq!(reqs[0].method, "POST");
        assert_eq!(reqs[0].path, "/connect/token");
        assert!(reqs[0].body.contains("grant_type=authorization_code"));
        assert!(reqs[0].body.contains("code=thecode"));
        assert!(reqs[0].body.contains("code_verifier=theverifier"));
    }

    #[tokio::test]
    async fn fetch_status_sends_bearer() {
        // Inject the token via the env override so the keychain is
        // never touched. No other car-auth test reads this var.
        std::env::set_var(PARSLEE_ACCESS_TOKEN_KEY, "test-token");

        let mock = mock::start(1, |_r| (200, r#"{"authenticated":true}"#.to_string()));

        let session = fetch_status(Some(&mock.base)).await.unwrap();
        assert_eq!(session.as_deref(), Some(r#"{"authenticated":true}"#));

        let reqs = mock.recorded.lock().unwrap();
        assert_eq!(reqs.len(), 1);
        let sess = &reqs[0];
        assert_eq!(sess.method, "GET");
        assert_eq!(sess.path, "/connect/session");
        assert_eq!(sess.authorization.as_deref(), Some("Bearer test-token"));

        std::env::remove_var(PARSLEE_ACCESS_TOKEN_KEY);
    }
}