LINE1 10 20 30 40 50 60 70 80 90 100 110 120 130 140 150 160 170 1801use std::time::{Duration, Instant};23use anyhow::{Context, bail};4use reqwest::Url;5#[cfg(not(feature = "testing"))]6use reqwest::{Client, redirect::Policy};7use serde::Deserialize;8#[cfg(not(feature = "testing"))]9use serde::Serialize;1011use crate::{credential_store::CredentialStore, git_config::GitConfigurator, server_url::TwigUrl};1213#[derive(Deserialize)]14pub struct DeviceAuthorizationStart {15 pub device_code: String,16 pub user_code: String,17 pub verification_uri: String,18 pub expires_in: u64,19 pub interval: u64,20}2122#[derive(Deserialize)]23#[serde(tag = "status", rename_all = "snake_case")]24pub enum DevicePollResponse {25 Pending { interval: u64 },26 SlowDown { interval: u64 },27 Denied,28 Expired,29 Authorized { access_token: String },30}3132#[derive(Serialize)]33#[cfg(not(feature = "testing"))]34struct DeviceTokenRequest<'a> {35 device_code: &'a str,36}3738#[cfg(not(feature = "testing"))]39pub struct DeviceClient {40 http: Client,41 base_url: TwigUrl,42}4344#[cfg(not(feature = "testing"))]45impl DeviceClient {46 pub fn new(base_url: TwigUrl) -> anyhow::Result<Self> {47 let http = Client::builder()48 .timeout(Duration::from_secs(15))49 .redirect(Policy::none())50 .build()51 .context("Failed to initialize Twig HTTP client")?;52 Ok(Self { http, base_url })53 }5455 pub async fn start(&self) -> anyhow::Result<DeviceAuthorizationStart> {56 let endpoint = self.base_url.as_url().join("api/auth/device")?;57 let response = self58 .http59 .post(endpoint)60 .send()61 .await62 .context("Could not start Twig device authorization")?63 .error_for_status()64 .context("Twig rejected the device authorization request")?;65 let challenge = response66 .json::<DeviceAuthorizationStart>()67 .await68 .context("Twig returned an invalid device authorization response")?;69 if challenge.device_code.is_empty() || challenge.user_code.is_empty() {70 bail!("Twig returned an empty device or user code");71 }72 if challenge.device_code.len() != 6473 || !challenge74 .device_code75 .bytes()76 .all(|byte| byte.is_ascii_hexdigit())77 {78 bail!("Twig returned an invalid polling code");79 }80 if !is_formatted_user_code(&challenge.user_code) {81 bail!("Twig returned an invalid human verification code");82 }83 if challenge.expires_in == 0 {84 bail!("Twig returned an already-expired device authorization");85 }86 Ok(challenge)87 }8889 pub async fn poll(&self, device_code: &str) -> anyhow::Result<DevicePollResponse> {90 let endpoint = self.base_url.as_url().join("api/auth/device/token")?;91 let response = self92 .http93 .post(endpoint)94 .json(&DeviceTokenRequest { device_code })95 .send()96 .await97 .context("Could not check Twig device authorization")?98 .error_for_status()99 .context("Twig rejected the device authorization poll")?;100 response101 .json::<DevicePollResponse>()102 .await103 .context("Twig returned an invalid device authorization status")104 }105}106107pub trait DeviceAuthorization {108 async fn start(&self) -> anyhow::Result<DeviceAuthorizationStart>;109 async fn poll(&self, device_code: &str) -> anyhow::Result<DevicePollResponse>;110111 fn is_simulation(&self) -> bool {112 false113 }114}115116#[cfg(not(feature = "testing"))]117impl DeviceAuthorization for DeviceClient {118 async fn start(&self) -> anyhow::Result<DeviceAuthorizationStart> {119 DeviceClient::start(self).await120 }121122 async fn poll(&self, device_code: &str) -> anyhow::Result<DevicePollResponse> {123 DeviceClient::poll(self, device_code).await124 }125}126127pub trait BrowserOpener {128 fn open(&self, url: &Url) -> anyhow::Result<()>;129}130131#[cfg(not(feature = "testing"))]132pub struct DefaultBrowserOpener;133134#[cfg(not(feature = "testing"))]135impl BrowserOpener for DefaultBrowserOpener {136 fn open(&self, url: &Url) -> anyhow::Result<()> {137 webbrowser::open(url.as_str()).context("Could not open the default browser")138 }139}140141pub async fn connect(142 server: TwigUrl,143 authorization: &impl DeviceAuthorization,144 browser: &impl BrowserOpener,145 credentials: &impl CredentialStore,146 git: &impl GitConfigurator,147) -> anyhow::Result<()> {148 credentials.check_available()?;149 git.check_git_available()?;150151 let challenge = authorization.start().await?;152 let mut verification_url = server.as_url().join(&challenge.verification_uri)?;153 if verification_url.origin() != server.as_url().origin() {154 bail!("Twig returned a verification URL on a different origin");155 }156 if verification_url.path() != "/auth/device"157 || verification_url.query().is_some()158 || verification_url.fragment().is_some()159 {160 bail!("Twig returned an invalid device verification path");161 }162 verification_url163 .query_pairs_mut()164 .append_pair("user_code", &challenge.user_code);165166 if authorization.is_simulation() {167 eprintln!("Simulation only — verification URL: {verification_url}");168 eprintln!("Simulation user code: {}", challenge.user_code);169 } else {170 eprintln!("Authorize Tree in your browser: {verification_url}");171 eprintln!("If asked, enter this code: {}", challenge.user_code);172 }173 if let Err(error) = browser.open(&verification_url) {174 eprintln!("Could not open a browser ({error}); open the URL above manually.");175 }176177 let deadline = Instant::now()178 .checked_add(Duration::from_secs(challenge.expires_in))179 .context("Twig returned an invalid authorization lifetime")?;180 let mut interval = poll_interval(challenge.interval, challenge.expires_in);181 loop {182 if Instant::now() >= deadline {183 bail!("Twig device authorization expired");184 }185 if !authorization.is_simulation() {186 tokio::time::sleep(interval.min(deadline.saturating_duration_since(Instant::now())))187 .await;188 }189 if Instant::now() >= deadline {190 bail!("Twig device authorization expired");191 }192193 match authorization.poll(&challenge.device_code).await? {194 DevicePollResponse::Pending {195 interval: next_interval,196 }197 | DevicePollResponse::SlowDown {198 interval: next_interval,199 } => interval = poll_interval(next_interval, challenge.expires_in),200 DevicePollResponse::Denied => bail!("Twig device authorization was denied"),201 DevicePollResponse::Expired => bail!("Twig device authorization expired"),202 DevicePollResponse::Authorized { access_token } => {203 if let Err(error) = credentials.put(&server, &access_token) {204 bail!(205 "Twig created a Tree CLI token, but Tree could not save it securely. Revoke that token in Twig Account Settings before retrying: {error:#}"206 );207 }208 if let Err(error) = git.ensure_tree_helper(&server) {209 bail!(210 "The token is stored in the OS keyring, but Git helper setup failed. Fix global Git configuration and retry; revoke any unused Tree CLI tokens in Twig: {error:#}"211 );212 }213 if authorization.is_simulation() {214 eprintln!(215 "Simulation complete for {}; no real services were used.",216 server.as_url()217 );218 } else {219 eprintln!(220 "Tree is connected to {} and Git is configured.",221 server.as_url()222 );223 }224 return Ok(());225 }226 }227 }228}229230#[cfg(not(feature = "testing"))]231fn is_formatted_user_code(value: &str) -> bool {232 const ALPHABET: &[u8; 32] = b"23456789ABCDEFGHJKLMNPQRSTUVWXYZ";233 let bytes = value.as_bytes();234 bytes.len() == 9235 && bytes[4] == b'-'236 && bytes[..4]237 .iter()238 .chain(bytes[5..].iter())239 .all(|byte| ALPHABET.contains(byte))240}241242fn poll_interval(interval: u64, expires_in: u64) -> Duration {243 Duration::from_secs(interval.max(1).min(expires_in.max(1)))244}245246#[cfg(all(test, not(feature = "testing")))]247mod tests {248 use std::{249 collections::HashMap,250 fs,251 path::PathBuf,252 sync::Mutex,253 time::{SystemTime, UNIX_EPOCH},254 };255256 use reqwest::Url;257 use wiremock::{258 Mock, MockServer, ResponseTemplate, matchers::method, matchers::path, matchers::query_param,259 };260261 use super::*;262 use crate::credential_store::CredentialStore;263 use crate::git_config::GitConfig;264265 const STUB_APPROVAL_HTML: &str = r#"<!doctype html>266<html lang="en" data-theme="light">267 <head>268 <meta charset="utf-8" />269 <meta name="viewport" content="width=device-width, initial-scale=1" />270 <title>Authorize Tree — Twig test stub</title>271 <link href="https://cdn.jsdelivr.net/npm/daisyui@5" rel="stylesheet" type="text/css" />272 <script src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"></script>273 </head>274 <body class="min-h-screen bg-base-200 text-base-content">275 <main class="mx-auto flex min-h-screen max-w-xl items-center px-4 py-8">276 <section class="card w-full border border-base-300 bg-base-100 shadow-sm">277 <div class="card-body">278 <h1 class="card-title">Authorize Tree</h1>279 <p>Stub approval page for the device authorization tracer test.</p>280 <code>WQJH-8K2M</code>281 <button class="btn" type="button">Approve and connect</button>282 </div>283 </section>284 </main>285 </body>286</html>"#;287 const MOCK_DEVICE_CODE: &str =288 "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";289290 #[derive(Default)]291 struct FakeBrowser {292 opened: Mutex<Option<Url>>,293 fail: bool,294 }295296 impl BrowserOpener for FakeBrowser {297 fn open(&self, url: &Url) -> anyhow::Result<()> {298 if self.fail {299 bail!("simulated browser launch failure");300 }301 *self.opened.lock().expect("browser lock") = Some(url.clone());302 Ok(())303 }304 }305306 #[derive(Default)]307 struct FakeCredentialStore {308 tokens: Mutex<HashMap<String, String>>,309 fail_check: bool,310 fail_put: bool,311 }312313 impl CredentialStore for FakeCredentialStore {314 fn check_available(&self) -> anyhow::Result<()> {315 if self.fail_check {316 bail!("simulated secure-store failure");317 }318 Ok(())319 }320321 fn get(&self, server: &TwigUrl) -> anyhow::Result<Option<String>> {322 Ok(self323 .tokens324 .lock()325 .expect("credential lock")326 .get(server.as_url().as_str())327 .cloned())328 }329330 fn put(&self, server: &TwigUrl, token: &str) -> anyhow::Result<()> {331 if self.fail_put {332 bail!("simulated keyring write failure");333 }334 self.tokens335 .lock()336 .expect("credential lock")337 .insert(server.as_url().as_str().to_owned(), token.to_owned());338 Ok(())339 }340341 fn erase(&self, server: &TwigUrl) -> anyhow::Result<()> {342 self.tokens343 .lock()344 .expect("credential lock")345 .remove(server.as_url().as_str());346 Ok(())347 }348 }349350 fn temp_config_path() -> PathBuf {351 let unique = SystemTime::now()352 .duration_since(UNIX_EPOCH)353 .expect("clock after epoch")354 .as_nanos();355 std::env::temp_dir().join(format!(356 "tree-auth-git-config-{}-{unique}",357 std::process::id()358 ))359 }360361 async fn mount_authorized_flow(server: &MockServer, verification_uri: &str) {362 Mock::given(method("POST"))363 .and(path("/api/auth/device"))364 .respond_with(ResponseTemplate::new(200).set_body_raw(365 format!(366 r#"{{"device_code":"{MOCK_DEVICE_CODE}","user_code":"WQJH-8K2M","verification_uri":"{verification_uri}","expires_in":600,"interval":0}}"#367 ),368 "application/json",369 ))370 .mount(server)371 .await;372 Mock::given(method("POST"))373 .and(path("/api/auth/device/token"))374 .respond_with(ResponseTemplate::new(200).set_body_raw(375 r#"{"status":"authorized","access_token":"twigt_stub_only"}"#,376 "application/json",377 ))378 .mount(server)379 .await;380 Mock::given(method("GET"))381 .and(path("/auth/device"))382 .and(query_param("user_code", "WQJH-8K2M"))383 .respond_with(ResponseTemplate::new(200).set_body_raw(STUB_APPROVAL_HTML, "text/html"))384 .mount(server)385 .await;386 }387388 #[tokio::test]389 async fn mock_server_wires_code_browser_page_poll_token_and_git_setup() {390 let server = MockServer::start().await;391 Mock::given(method("POST"))392 .and(path("/api/auth/device"))393 .respond_with(ResponseTemplate::new(200).set_body_raw(394 format!(r#"{{"device_code":"{MOCK_DEVICE_CODE}","user_code":"WQJH-8K2M","verification_uri":"/auth/device","expires_in":600,"interval":0}}"#),395 "application/json",396 ))397 .mount(&server)398 .await;399 Mock::given(method("POST"))400 .and(path("/api/auth/device/token"))401 .respond_with(ResponseTemplate::new(200).set_body_raw(402 r#"{"status":"authorized","access_token":"twigt_stub_only"}"#,403 "application/json",404 ))405 .mount(&server)406 .await;407 Mock::given(method("GET"))408 .and(path("/auth/device"))409 .and(query_param("user_code", "WQJH-8K2M"))410 .respond_with(ResponseTemplate::new(200).set_body_raw(STUB_APPROVAL_HTML, "text/html"))411 .mount(&server)412 .await;413414 let server_url = TwigUrl::parse(&server.uri()).expect("mock Twig URL");415 let authorization = DeviceClient::new(server_url.clone()).expect("HTTP client");416 let browser = FakeBrowser::default();417 let credentials = FakeCredentialStore::default();418 let config_path = temp_config_path();419 let git = GitConfig::with_global_file(config_path.clone());420421 connect(422 server_url.clone(),423 &authorization,424 &browser,425 &credentials,426 &git,427 )428 .await429 .expect("complete mocked Tree authorization");430431 assert_eq!(432 credentials.get(&server_url).expect("read fake token"),433 Some("twigt_stub_only".to_owned())434 );435 let verification_url = browser436 .opened437 .lock()438 .expect("browser lock")439 .clone()440 .expect("browser was opened");441 assert_eq!(442 verification_url443 .query_pairs()444 .find(|(key, _)| key == "user_code"),445 Some(("user_code".into(), "WQJH-8K2M".into()))446 );447 let page = reqwest::get(verification_url)448 .await449 .expect("load stub approval page")450 .text()451 .await452 .expect("read stub page");453 assert!(page.contains("Authorize Tree"));454 assert!(page.contains("Approve and connect"));455456 let config = fs::read_to_string(&config_path).expect("read isolated Git config");457 assert!(config.contains("!tree credential --url"));458 assert!(config.contains("useHttpPath = true"));459 credentials460 .erase(&server_url)461 .expect("erase only the matching test credential");462 assert_eq!(credentials.get(&server_url).unwrap(), None);463 let _ = fs::remove_file(config_path);464 }465466 #[tokio::test]467 async fn client_rejects_a_cross_origin_verification_url() {468 let server = MockServer::start().await;469 Mock::given(method("POST"))470 .and(path("/api/auth/device"))471 .respond_with(ResponseTemplate::new(200).set_body_raw(472 format!(r#"{{"device_code":"{MOCK_DEVICE_CODE}","user_code":"WQJH-8K2M","verification_uri":"https://attacker.example/auth/device","expires_in":600,"interval":0}}"#),473 "application/json",474 ))475 .mount(&server)476 .await;477478 let server_url = TwigUrl::parse(&server.uri()).expect("mock Twig URL");479 let authorization = DeviceClient::new(server_url.clone()).expect("HTTP client");480 let browser = FakeBrowser::default();481 let credentials = FakeCredentialStore::default();482 let git = GitConfig::with_global_file(temp_config_path());483484 let result = connect(server_url, &authorization, &browser, &credentials, &git).await;485486 assert!(result.is_err());487 assert!(browser.opened.lock().expect("browser lock").is_none());488 assert!(489 credentials490 .tokens491 .lock()492 .expect("credential lock")493 .is_empty()494 );495 }496497 #[tokio::test]498 async fn secure_store_failure_stops_before_contacting_twig() {499 let server = MockServer::start().await;500 let server_url = TwigUrl::parse(&server.uri()).expect("mock Twig URL");501 let authorization = DeviceClient::new(server_url.clone()).expect("HTTP client");502 let browser = FakeBrowser::default();503 let credentials = FakeCredentialStore {504 fail_check: true,505 ..FakeCredentialStore::default()506 };507 let git = GitConfig::global();508509 let error = connect(server_url, &authorization, &browser, &credentials, &git)510 .await511 .expect_err("missing keyring must fail before authorization");512513 assert!(error.to_string().contains("simulated secure-store failure"));514 assert!(515 server516 .received_requests()517 .await518 .unwrap_or_default()519 .is_empty()520 );521 assert!(browser.opened.lock().expect("browser lock").is_none());522 }523524 #[tokio::test]525 async fn keyring_write_failure_does_not_expose_the_issued_secret() {526 let server = MockServer::start().await;527 mount_authorized_flow(&server, "/auth/device").await;528 let server_url = TwigUrl::parse(&server.uri()).expect("mock Twig URL");529 let authorization = DeviceClient::new(server_url.clone()).expect("HTTP client");530 let browser = FakeBrowser::default();531 let credentials = FakeCredentialStore {532 fail_put: true,533 ..FakeCredentialStore::default()534 };535 let git = GitConfig::global();536537 let error = connect(server_url, &authorization, &browser, &credentials, &git)538 .await539 .expect_err("keyring failure must be reported");540 let message = format!("{error:#}");541 assert!(message.contains("Revoke that token in Twig Account Settings"));542 assert!(!message.contains("twigt_stub_only"));543 assert!(544 credentials545 .tokens546 .lock()547 .expect("credential lock")548 .is_empty()549 );550 }551552 #[tokio::test]553 async fn git_config_failure_reports_that_the_token_is_stored() {554 let server = MockServer::start().await;555 mount_authorized_flow(&server, "/auth/device").await;556 let server_url = TwigUrl::parse(&server.uri()).expect("mock Twig URL");557 let authorization = DeviceClient::new(server_url.clone()).expect("HTTP client");558 let browser = FakeBrowser::default();559 let credentials = FakeCredentialStore::default();560 let config_path = temp_config_path();561 fs::create_dir_all(&config_path).expect("create invalid config path");562 let git = GitConfig::with_global_file(config_path.clone());563564 let error = connect(565 server_url.clone(),566 &authorization,567 &browser,568 &credentials,569 &git,570 )571 .await572 .expect_err("Git config failure must be reported");573 let message = format!("{error:#}");574 assert!(message.contains("token is stored in the OS keyring"));575 assert!(!message.contains("twigt_stub_only"));576 assert_eq!(577 credentials578 .get(&server_url)579 .expect("read stored test token"),580 Some("twigt_stub_only".to_owned())581 );582 let _ = fs::remove_dir_all(config_path);583 }584585 #[test]586 fn polling_interval_is_never_zero_or_longer_than_the_challenge() {587 assert_eq!(poll_interval(0, 600), Duration::from_secs(1));588 assert_eq!(poll_interval(30, 10), Duration::from_secs(10));589 assert_eq!(poll_interval(u64::MAX, 10), Duration::from_secs(10));590 }591592 #[tokio::test]593 async fn same_origin_but_unexpected_verification_paths_are_rejected() {594 let server = MockServer::start().await;595 mount_authorized_flow(&server, "/auth/not-device").await;596 let server_url = TwigUrl::parse(&server.uri()).expect("mock Twig URL");597 let authorization = DeviceClient::new(server_url.clone()).expect("HTTP client");598 let browser = FakeBrowser::default();599 let credentials = FakeCredentialStore::default();600 let git = GitConfig::global();601602 assert!(603 connect(server_url, &authorization, &browser, &credentials, &git)604 .await605 .is_err()606 );607 assert!(browser.opened.lock().expect("browser lock").is_none());608 }609}