fix: replace device flow with loopback ip redirect flow (RFC 8252)

- Device Flow only works with 'TV and Limited Input devices' OAuth client type
- Desktop app type requires Authorization Code flow with localhost redirect
- New flow: start local TCP server on random port, open browser with auth URL,
  catch redirect containing authorization code, exchange for tokens
- Uses webbrowser crate to auto-open the browser
- Self-contained: no separate HTTP server framework needed, uses std::net
- Popup shows auth URL and waits for browser authorization
- Support for refresh_token for long-lived access
This commit is contained in:
Ruben Rosario
2026-06-20 20:55:08 +01:00
parent 64993b127c
commit 0cbf9262c7
5 changed files with 471 additions and 173 deletions
+177 -120
View File
@@ -1,3 +1,5 @@
use std::io::{BufRead, BufReader, Write};
use std::net::TcpListener;
use std::path::PathBuf;
use std::sync::Arc;
@@ -5,7 +7,8 @@ use chrono::{DateTime, Utc};
use reqwest::Client;
use serde::{Deserialize, Serialize};
use tokio::sync::Mutex;
use tokio::time::{sleep, Duration};
use url::Url;
use crate::domain::models::*;
@@ -32,6 +35,8 @@ pub struct ApiClient {
token_path: PathBuf,
}
const SCOPES: &str = "https://www.googleapis.com/auth/tasks";
impl ApiClient {
pub fn new(client_id: String, client_secret: String) -> Self {
let token_path = dirs::config_dir()
@@ -49,10 +54,11 @@ impl ApiClient {
}
pub fn token_file_exists(&self) -> bool {
self.token_path.exists() && std::fs::read_to_string(&self.token_path)
.ok()
.and_then(|s| serde_json::from_str::<OAuthToken>(&s).ok())
.is_some()
self.token_path.exists()
&& std::fs::read_to_string(&self.token_path)
.ok()
.and_then(|s| serde_json::from_str::<OAuthToken>(&s).ok())
.is_some()
}
pub async fn load_token(&self) -> Option<OAuthToken> {
@@ -69,123 +75,65 @@ impl ApiClient {
}
}
pub async fn authenticate(&self) -> Result<(String, String), ApiError> {
/// Starts the Loopback IP Redirect OAuth flow (RFC 8252).
/// Returns (auth_url, callback_port) so the app can tell the user
/// to open the URL or open it automatically.
pub async fn start_auth_flow(&self) -> Result<(String, u16), ApiError> {
if self.client_id.is_empty() {
return Err(ApiError::Auth(
"GOOGLE_CLIENT_ID not set. Set both GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET".to_string(),
));
}
if self.client_secret.is_empty() {
return Err(ApiError::Auth(
"GOOGLE_CLIENT_SECRET not set. Set both GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET".to_string(),
"GOOGLE_CLIENT_ID not set".to_string(),
));
}
let params = serde_json::json!({
"client_id": self.client_id,
"scope": "https://www.googleapis.com/auth/tasks",
});
// Find a free port
let listener = TcpListener::bind("127.0.0.1:0")
.map_err(|e| ApiError::Network(format!("Failed to bind port: {}", e)))?;
let port = listener.local_addr().unwrap().port();
let redirect_uri = format!("http://127.0.0.1:{}/", port);
let resp = self
.client
.post("https://oauth2.googleapis.com/device/code")
.json(&params)
.send()
.await
.map_err(|e| ApiError::Network(format!("HTTP request failed: {}", e)))?;
// Build Google auth URL
let auth_url = format!(
"https://accounts.google.com/o/oauth2/v2/auth?\
response_type=code&\
client_id={}&\
redirect_uri={}&\
scope={}&\
access_type=offline&\
prompt=consent",
urlencoding(&self.client_id),
urlencoding(&redirect_uri),
urlencoding(SCOPES),
);
let status = resp.status();
let data: serde_json::Value = resp
.json()
.await
.map_err(|e| ApiError::Api(format!("Invalid response (status {}): {}", status, e)))?;
// Spawn a thread that accepts one connection and parses the code
let client_id = self.client_id.clone();
let client_secret = self.client_secret.clone();
let token = self.token.clone();
let token_path = self.token_path.clone();
if !status.is_success() {
let err_code = data["error"].as_str().unwrap_or("unknown_error");
let err_desc = data["error_description"]
.as_str()
.unwrap_or("no description");
let mut msg = format!("OAuth error ({}): {} - {}", status, err_code, err_desc);
if err_code == "invalid_client" || err_desc.contains("Invalid client") {
msg.push_str(
"\n\nPossible fixes (Google Cloud Console):\n\
1. APIs & Services > Library -> Enable 'Google Tasks API'.\n\
2. APIs & Services > OAuth consent screen:\n\
- Set 'Publishing status' to 'Testing'\n\
- Add 'https://www.googleapis.com/auth/tasks' to Scopes\n\
- Add your email under 'Test users'\n\
3. APIs & Services > Credentials:\n\
- Create new OAuth 2.0 Client ID of type 'Desktop app'\n\
- Copy the Client ID and Client Secret exactly (no extra spaces)",
);
}
return Err(ApiError::Api(msg));
}
let url = data["verification_url"]
.as_str()
.or_else(|| data["verification_uri"].as_str())
.unwrap_or("https://www.google.com/device")
.to_string();
let code = data["user_code"]
.as_str()
.unwrap_or("")
.to_string();
let device_code = data["device_code"].as_str().unwrap_or("").to_string();
let interval = data["interval"].as_u64().unwrap_or(5);
tokio::spawn({
let client = self.client.clone();
let client_id = self.client_id.clone();
let client_secret = self.client_secret.clone();
let device_code = device_code.clone();
let token = self.token.clone();
let token_path = self.token_path.clone();
async move {
loop {
sleep(Duration::from_secs(interval)).await;
let poll = serde_json::json!({
"client_id": client_id,
"client_secret": client_secret,
"device_code": device_code,
"grant_type": "urn:ietf:params:oauth:grant_type:device_code",
});
if let Ok(resp) = client
.post("https://oauth2.googleapis.com/token")
.json(&poll)
.send()
.await
{
if let Ok(data) = resp.json::<serde_json::Value>().await {
if let Some(access_token) = data["access_token"].as_str() {
let expires_in = data["expires_in"].as_i64().unwrap_or(3600);
let oauth_token = OAuthToken {
access_token: access_token.to_string(),
refresh_token: data["refresh_token"].as_str().map(|s| s.to_string()),
expires_at: Some(Utc::now() + chrono::Duration::seconds(expires_in)),
};
if let Ok(content) = serde_json::to_string_pretty(&oauth_token) {
std::fs::write(&token_path, content).ok();
}
let mut t = token.lock().await;
*t = Some(oauth_token);
break;
}
}
}
}
std::thread::spawn(move || {
if let Err(e) = handle_oauth_callback(
listener,
&client_id,
&client_secret,
&token,
&token_path,
) {
eprintln!("OAuth callback error: {}", e);
}
});
Ok((url, code))
Ok((auth_url, port))
}
/// Opens the browser or returns the URL for manual opening
pub fn open_browser(auth_url: &str) -> bool {
webbrowser::open(auth_url).is_ok()
}
/// Polls the in-memory token to see if auth completed
pub async fn token_is_ready(&self) -> bool {
self.token.lock().await.is_some()
}
pub async fn refresh_access_token(&self, refresh_token: &str) -> Result<(), ApiError> {
@@ -202,12 +150,20 @@ impl ApiClient {
.json(&params)
.send()
.await
.map_err(|e| ApiError::Network(e.to_string()))?;
.map_err(|e| ApiError::Network(format!("HTTP request failed: {}", e)))?;
let status = resp.status();
let data: serde_json::Value = resp
.json()
.await
.map_err(|e| ApiError::Network(e.to_string()))?;
.map_err(|e| ApiError::Api(format!("Invalid response (status {}): {}", status, e)))?;
if !status.is_success() {
return Err(ApiError::Api(format!(
"Token refresh failed ({}): {:?}",
status, data
)));
}
if let Some(access_token) = data["access_token"].as_str() {
let expires_in = data["expires_in"].as_i64().unwrap_or(3600);
@@ -243,7 +199,9 @@ impl ApiClient {
return Ok(t.access_token.clone());
}
}
Err(ApiError::Auth("Token expired and no refresh token".to_string()))
Err(ApiError::Auth(
"Token expired and no refresh token".to_string(),
))
} else if let Some(saved) = self.load_token().await {
*token = Some(saved);
if let Some(ref t) = *token {
@@ -314,7 +272,11 @@ impl ApiClient {
.map(|(i, item)| {
let due_str = item["due"].as_str().and_then(|s| {
chrono::NaiveDateTime::parse_from_str(
&s.replace("T", " ").replace("Z", "").chars().take(16).collect::<String>(),
&s.replace("T", " ")
.replace("Z", "")
.chars()
.take(16)
.collect::<String>(),
"%Y-%m-%d %H:%M",
)
.ok()
@@ -350,7 +312,8 @@ impl ApiClient {
body["notes"] = serde_json::Value::String(notes.clone());
}
if let Some(due) = task.due {
body["due"] = serde_json::Value::String(due.format("%Y-%m-%dT%H:%M:00.000Z").to_string());
body["due"] =
serde_json::Value::String(due.format("%Y-%m-%dT%H:%M:00.000Z").to_string());
}
if task.status == TaskStatus::Completed {
body["status"] = serde_json::Value::String("completed".to_string());
@@ -371,7 +334,10 @@ impl ApiClient {
.map_err(|e| ApiError::Network(e.to_string()))?;
if !resp.status().is_success() {
return Err(ApiError::Api(format!("Create failed: {}", resp.status())));
return Err(ApiError::Api(format!(
"Create failed: {}",
resp.status()
)));
}
Ok(())
@@ -388,7 +354,8 @@ impl ApiClient {
body["notes"] = serde_json::Value::String(notes.clone());
}
if let Some(due) = task.due {
body["due"] = serde_json::Value::String(due.format("%Y-%m-%dT%H:%M:00.000Z").to_string());
body["due"] =
serde_json::Value::String(due.format("%Y-%m-%dT%H:%M:00.000Z").to_string());
}
body["status"] = serde_json::Value::String(match task.status {
TaskStatus::Completed => "completed".to_string(),
@@ -410,7 +377,10 @@ impl ApiClient {
.map_err(|e| ApiError::Network(e.to_string()))?;
if !resp.status().is_success() {
return Err(ApiError::Api(format!("Update failed: {}", resp.status())));
return Err(ApiError::Api(format!(
"Update failed: {}",
resp.status()
)));
}
Ok(())
@@ -433,7 +403,10 @@ impl ApiClient {
.map_err(|e| ApiError::Network(e.to_string()))?;
if !resp.status().is_success() {
return Err(ApiError::Api(format!("Delete failed: {}", resp.status())));
return Err(ApiError::Api(format!(
"Delete failed: {}",
resp.status()
)));
}
Ok(())
@@ -475,3 +448,87 @@ impl ApiClient {
Ok(())
}
}
fn urlencoding(s: &str) -> String {
s.chars()
.map(|c| match c {
'A'..='Z' | 'a'..='z' | '0'..='9' | '-' | '_' | '.' | '~' => c.to_string(),
_ => format!("%{:02X}", c as u8),
})
.collect()
}
fn handle_oauth_callback(
listener: TcpListener,
client_id: &str,
client_secret: &str,
token_storage: &Arc<Mutex<Option<OAuthToken>>>,
token_path: &PathBuf,
) -> Result<(), Box<dyn std::error::Error>> {
let (stream, _) = listener.accept()?;
let mut reader = BufReader::new(&stream);
let mut request_line = String::new();
reader.read_line(&mut request_line)?;
// Parse the GET request to extract the code
let code = request_line
.split_whitespace()
.nth(1)
.and_then(|path| {
let parsed = Url::parse(&format!("http://localhost{}", path)).ok()?;
parsed.query_pairs().find(|(k, _)| k == "code")?.1.to_string().into()
});
let reply = if let Some(ref _code) = code {
// Send success response to browser
"HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<html><body><h1>Authorized!</h1><p>You can close this tab and return to the terminal.</p></body></html>"
} else {
"HTTP/1.1 400 Bad Request\r\nContent-Type: text/html\r\n\r\n<html><body><h1>Authorization failed</h1><p>No code received.</p></body></html>"
};
let mut response = stream.try_clone()?;
response.write_all(reply.as_bytes())?;
response.flush()?;
if let Some(auth_code) = code {
// Exchange code for token
let rt = tokio::runtime::Runtime::new()?;
rt.block_on(async move {
let client = Client::new();
let params = serde_json::json!({
"client_id": client_id,
"client_secret": client_secret,
"code": auth_code,
"redirect_uri": format!("http://127.0.0.1:{}/", listener.local_addr().unwrap().port()),
"grant_type": "authorization_code",
});
if let Ok(resp) = client
.post("https://oauth2.googleapis.com/token")
.json(&params)
.send()
.await
{
if let Ok(data) = resp.json::<serde_json::Value>().await {
if let Some(access_token) = data["access_token"].as_str() {
let expires_in = data["expires_in"].as_i64().unwrap_or(3600);
let oauth_token = OAuthToken {
access_token: access_token.to_string(),
refresh_token: data["refresh_token"].as_str().map(|s| s.to_string()),
expires_at: Some(Utc::now() + chrono::Duration::seconds(expires_in)),
};
if let Ok(content) = serde_json::to_string_pretty(&oauth_token) {
std::fs::write(token_path, content).ok();
}
let mut t = token_storage.lock().await;
*t = Some(oauth_token);
}
}
}
});
}
Ok(())
}