Skip to content

YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context

fix(connections): propagate OAuth error callbacks instead of hanging until timeout (#5122)

Ansh Grover8fdbe86f5906
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/oauth.rs b/apps/screenpipe-app-tauri/src-tauri/src/oauth.rs
index b33f5a20e..120607702 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/oauth.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/oauth.rs
@@ -11,7 +11,9 @@
use crate::store::SettingsStore;
use base64::Engine;
use screenpipe_connect::connections::all_integrations;
-use screenpipe_connect::oauth::{self, PendingOAuth, OAUTH_REDIRECT_URI, PENDING_OAUTH};
+use screenpipe_connect::oauth::{
+ self, OAuthCallbackResult, PendingOAuth, OAUTH_REDIRECT_URI, PENDING_OAUTH,
+};
use serde::{Deserialize, Serialize};
use tauri::AppHandle;
use tauri_plugin_opener::OpenerExt;
@@ -132,7 +134,7 @@ pub async fn oauth_connect(
};
let state = uuid::Uuid::new_v4().simple().to_string();
- let (tx, rx) = oneshot::channel::<String>();
+ let (tx, rx) = oneshot::channel::<OAuthCallbackResult>();
{
let mut map = PENDING_OAUTH.lock().unwrap();
map.insert(
@@ -180,7 +182,7 @@ pub async fn oauth_connect(
integration_id, instance, variant
);
- let raw = tokio::time::timeout(std::time::Duration::from_secs(120), rx)
+ let result = tokio::time::timeout(std::time::Duration::from_secs(120), rx)
.await
.map_err(|_| {
let mut map = PENDING_OAUTH.lock().unwrap();
@@ -189,19 +191,30 @@ pub async fn oauth_connect(
})?
.map_err(|_| "OAuth channel closed before code was received".to_string())?;
- // Some providers (e.g. QuickBooks) send extra callback params alongside the code.
- // The callback handler encodes them as JSON: {"code":"...","realmId":"..."}.
- // Plain strings are treated as a bare authorization code for backward compatibility.
- let (code, callback_extras): (String, Option<serde_json::Value>) = if raw.starts_with('{') {
- match serde_json::from_str::<serde_json::Value>(&raw) {
- Ok(v) => {
- let c = v["code"].as_str().unwrap_or(&raw).to_string();
- (c, Some(v))
- }
- Err(_) => (raw, None),
+ let (code, callback_extras): (String, Option<serde_json::Value>) = match result {
+ OAuthCallbackResult::Success { code, realm_id } => {
+ let extras = realm_id.map(|rid| serde_json::json!({ "realmId": rid }));
+ (code, extras)
+ }
+ OAuthCallbackResult::ProviderError {
+ error,
+ error_description,
+ } => {
+ info!(
+ "oauth callback for {} rejected by provider: {}",
+ integration_id, error
+ );
+ return Err(match error.as_str() {
+ "access_denied" => {
+ "authorization was denied or cancelled in the browser — try connecting again"
+ .to_string()
+ }
+ _ => match error_description {
+ Some(desc) => format!("provider returned error: {} ({})", error, desc),
+ None => format!("provider returned error: {}", error),
+ },
+ });
}
- } else {
- (raw, None)
};
let client = reqwest::Client::builder()
@@ -666,7 +679,8 @@ fn derive_effective_instance(
#[cfg(test)]
mod tests {
- use super::derive_effective_instance;
+ use super::{derive_effective_instance, oauth_cancel};
+ use screenpipe_connect::oauth::{OAuthCallbackResult, PendingOAuth, PENDING_OAUTH};
use serde_json::json;
#[test]
@@ -691,6 +705,51 @@ mod tests {
assert_eq!(derive_effective_instance(None, &token_data), None);
}
+
+ /// Canceled flow (#5092): oauth_cancel drops the pending sender, which
+ /// must close the channel so the awaiting oauth_connect fails fast
+ /// instead of hanging for the full 120s timeout.
+ #[tokio::test]
+ async fn oauth_cancel_drops_pending_flow_and_closes_channel() {
+ let state = "test-cancel-state";
+ let (tx, rx) = tokio::sync::oneshot::channel::<OAuthCallbackResult>();
+ PENDING_OAUTH.lock().unwrap().insert(
+ state.to_string(),
+ PendingOAuth {
+ integration_id: "test-cancel-integration".to_string(),
+ sender: tx,
+ },
+ );
+
+ oauth_cancel("test-cancel-integration".to_string()).unwrap();
+
+ assert!(!PENDING_OAUTH.lock().unwrap().contains_key(state));
+ // Dropped sender closes the channel — the waiter unblocks immediately.
+ assert!(rx.await.is_err());
+ }
+
+ /// oauth_cancel must only drop flows for the given integration.
+ #[tokio::test]
+ async fn oauth_cancel_leaves_other_integrations_pending() {
+ let state = "test-cancel-other-state";
+ let (tx, mut rx) = tokio::sync::oneshot::channel::<OAuthCallbackResult>();
+ PENDING_OAUTH.lock().unwrap().insert(
+ state.to_string(),
+ PendingOAuth {
+ integration_id: "test-cancel-other-integration".to_string(),
+ sender: tx,
+ },
+ );
+
+ oauth_cancel("some-unrelated-integration".to_string()).unwrap();
+
+ assert!(PENDING_OAUTH.lock().unwrap().contains_key(state));
+ assert!(matches!(
+ rx.try_recv(),
+ Err(tokio::sync::oneshot::error::TryRecvError::Empty)
+ ));
+ PENDING_OAUTH.lock().unwrap().remove(state);
+ }
}
/// Microsoft's well-known tenant ID for **personal** Microsoft accounts
diff --git a/crates/screenpipe-connect/src/oauth.rs b/crates/screenpipe-connect/src/oauth.rs
index 0dcda2a28..172f76513 100644
--- a/crates/screenpipe-connect/src/oauth.rs
+++ b/crates/screenpipe-connect/src/oauth.rs
@@ -35,9 +35,11 @@
//! 2. The browser opens the provider's authorization URL with
//! `redirect_uri=http://localhost:3030/connections/oauth/callback&state=<uuid>`.
//! 3. The provider redirects back; the screenpipe server handles
-//! `GET /connections/oauth/callback?code=X&state=<uuid>`, looks up the
-//! sender by `state`, and delivers the code.
-//! 4. `oauth_connect` receives the code and calls `exchange_code`.
+//! `GET /connections/oauth/callback?code=X&state=<uuid>` (or
+//! `?error=...&state=<uuid>` when the user denies), looks up the sender
+//! by `state`, and delivers a typed `OAuthCallbackResult`.
+//! 4. `oauth_connect` receives the result and calls `exchange_code`, or
+//! fails immediately with the provider error.
//!
//! ## Adding a new OAuth integration
//! 1. Fill in a `static OAUTH: OAuthConfig` in the integration file.
@@ -67,11 +69,29 @@ pub const OAUTH_REDIRECT_URI: &str = "http://localhost:3030/connections/oauth/ca
// /connections/oauth/callback HTTP handler (screenpipe-engine)
// ---------------------------------------------------------------------------
+/// Outcome of a provider redirect to the OAuth callback, delivered through
+/// the pending oneshot channel. Errors carry only the provider's error code
+/// and optional description (RFC 6749 §4.1.2.1) — never codes, tokens, or
+/// state values.
+#[derive(Debug)]
+pub enum OAuthCallbackResult {
+ Success {
+ code: String,
+ /// Extra callback param some providers return alongside the code
+ /// (e.g. QuickBooks `realmId`).
+ realm_id: Option<String>,
+ },
+ ProviderError {
+ error: String,
+ error_description: Option<String>,
+ },
+}
+
/// A pending OAuth flow: the sender that delivers the callback payload,
/// tagged with its `integration_id` so `oauth_cancel` can find and drop it.
pub struct PendingOAuth {
pub integration_id: String,
- pub sender: oneshot::Sender<String>,
+ pub sender: oneshot::Sender<OAuthCallbackResult>,
}
pub static PENDING_OAUTH: Lazy<Mutex<HashMap<String, PendingOAuth>>> =
diff --git a/crates/screenpipe-engine/src/connections_api.rs b/crates/screenpipe-engine/src/connections_api.rs
index bcd8f9798..7d1575392 100644
--- a/crates/screenpipe-engine/src/connections_api.rs
+++ b/crates/screenpipe-engine/src/connections_api.rs
@@ -10,7 +10,7 @@ use axum::response::Html;
use axum::routing::{get, post};
use axum::{Json, Router};
use screenpipe_connect::connections::{bee, ConnectionManager};
-use screenpipe_connect::oauth::{self as oauth_store, PENDING_OAUTH};
+use screenpipe_connect::oauth::{self as oauth_store, OAuthCallbackResult, PENDING_OAUTH};
use screenpipe_connect::whatsapp::WhatsAppGateway;
use screenpipe_secrets::SecretStore;
use serde::{Deserialize, Serialize};
@@ -1441,17 +1441,49 @@ pub struct OAuthCallbackQuery {
pub code: Option<String>,
pub state: Option<String>,
pub error: Option<String>,
+ // Optional human-readable error detail (RFC 6749 §4.1.2.1).
+ pub error_description: Option<String>,
// QuickBooks Online returns realmId (company ID) as a callback param alongside the code.
#[serde(rename = "realmId")]
pub realm_id: Option<String>,
}
-/// GET /connections/oauth/callback — receives the provider redirect after user approves.
+/// GET /connections/oauth/callback — receives the provider redirect.
///
/// The `state` parameter is used to look up the waiting `oauth_connect` Tauri command
-/// via the `PENDING_OAUTH` channel map, then delivers the `code` through the channel.
+/// via the `PENDING_OAUTH` channel map, then delivers the outcome — success with the
+/// authorization `code`, or the provider's error — as a typed `OAuthCallbackResult`.
+/// Logs never include codes, tokens, state values, or the callback query string.
async fn oauth_callback(Query(params): Query<OAuthCallbackQuery>) -> (StatusCode, Html<String>) {
if let Some(err) = params.error {
+ // Provider rejection (e.g. access_denied on cancel). Resolve the waiting
+ // flow immediately instead of leaving it to hit the 120s timeout.
+ let pending = params.state.as_ref().and_then(|state| {
+ let mut map = PENDING_OAUTH.lock().unwrap();
+ map.remove(state)
+ });
+ match pending {
+ Some(pending) => {
+ tracing::warn!(
+ "oauth callback: provider returned error '{}' for {} — resolving pending flow",
+ err,
+ pending.integration_id
+ );
+ let _ = pending.sender.send(OAuthCallbackResult::ProviderError {
+ error: err.clone(),
+ error_description: params.error_description,
+ });
+ }
+ None => tracing::warn!(
+ "oauth callback: provider returned error '{}' with {} state — no pending flow to resolve",
+ err,
+ if params.state.is_some() {
+ "an unknown or stale"
+ } else {
+ "a missing"
+ }
+ ),
+ }
return oauth_callback_page(
StatusCode::BAD_REQUEST,
"Connection failed",
@@ -1463,6 +1495,7 @@ async fn oauth_callback(Query(params): Query<OAuthCallbackQuery>) -> (StatusCode
let (code, state) = match (params.code, params.state) {
(Some(c), Some(s)) => (c, s),
_ => {
+ tracing::warn!("oauth callback: missing code or state parameter");
return oauth_callback_page(
StatusCode::BAD_REQUEST,
"Invalid callback",
@@ -1479,13 +1512,14 @@ async fn oauth_callback(Query(params): Query<OAuthCallbackQuery>) -> (StatusCode
match sender {
Some(pending) => {
- // For providers that return extra callback params (e.g. QuickBooks realmId),
- // encode them alongside the code as JSON so the Tauri command can extract both.
- let payload = match params.realm_id {
- Some(ref rid) => serde_json::json!({"code": code, "realmId": rid}).to_string(),
- None => code,
- };
- let _ = pending.sender.send(payload);
+ tracing::info!(
+ "oauth callback: authorization received for {}",
+ pending.integration_id
+ );
+ let _ = pending.sender.send(OAuthCallbackResult::Success {
+ code,
+ realm_id: params.realm_id,
+ });
oauth_callback_page(
StatusCode::OK,
"Connected",
@@ -1493,12 +1527,15 @@ async fn oauth_callback(Query(params): Query<OAuthCallbackQuery>) -> (StatusCode
"You can close this tab and return to screenpipe.",
)
}
- None => oauth_callback_page(
- StatusCode::BAD_REQUEST,
- "Session expired",
- "screenpipe could not find the waiting app session.",
- "The authorization session was not found or already completed. Please try again.",
- ),
+ None => {
+ tracing::warn!("oauth callback: unknown or stale state — no pending flow");
+ oauth_callback_page(
+ StatusCode::BAD_REQUEST,
+ "Session expired",
+ "screenpipe could not find the waiting app session.",
+ "The authorization session was not found or already completed. Please try again.",
+ )
+ }
}
}
@@ -4310,4 +4347,176 @@ mod tests {
Some("pipe:reddit-poster".to_string())
);
}
+
+ // -----------------------------------------------------------------------
+ // OAuth callback — success and provider-error delivery (#5092)
+ // -----------------------------------------------------------------------
+
+ use screenpipe_connect::oauth::PendingOAuth;
+ use tokio::sync::oneshot;
+
+ /// Register a pending flow under `state` and return the receiving end.
+ /// `PENDING_OAUTH` is a process-global map, so every test uses a unique
+ /// state key to stay independent under parallel test execution.
+ fn register_pending(state: &str) -> oneshot::Receiver<OAuthCallbackResult> {
+ let (tx, rx) = oneshot::channel();
+ PENDING_OAUTH.lock().unwrap().insert(
+ state.to_string(),
+ PendingOAuth {
+ integration_id: "test-integration".to_string(),
+ sender: tx,
+ },
+ );
+ rx
+ }
+
+ fn pending_contains(state: &str) -> bool {
+ PENDING_OAUTH.lock().unwrap().contains_key(state)
+ }
+
+ fn callback_query(
+ code: Option<&str>,
+ state: Option<&str>,
+ error: Option<&str>,
+ error_description: Option<&str>,
+ realm_id: Option<&str>,
+ ) -> Query<OAuthCallbackQuery> {
+ Query(OAuthCallbackQuery {
+ code: code.map(String::from),
+ state: state.map(String::from),
+ error: error.map(String::from),
+ error_description: error_description.map(String::from),
+ realm_id: realm_id.map(String::from),
+ })
+ }
+
+ #[tokio::test]
+ async fn oauth_callback_success_delivers_code_and_removes_entry() {
+ let state = "test-cb-success-state";
+ let rx = register_pending(state);
+
+ let (status, _) = oauth_callback(callback_query(
+ Some("auth-code-1"),
+ Some(state),
+ None,
+ None,
+ None,
+ ))
+ .await;
+
+ assert_eq!(status, StatusCode::OK);
+ assert!(!pending_contains(state));
+ match rx.await.unwrap() {
+ OAuthCallbackResult::Success { code, realm_id } => {
+ assert_eq!(code, "auth-code-1");
+ assert_eq!(realm_id, None);
+ }
+ other => panic!("expected Success, got {:?}", other),
+ }
+ }
+
+ #[tokio::test]
+ async fn oauth_callback_success_carries_realm_id() {
+ let state = "test-cb-realmid-state";
+ let rx = register_pending(state);
+
+ let (status, _) = oauth_callback(callback_query(
+ Some("qb-code"),
+ Some(state),
+ None,
+ None,
+ Some("realm-42"),
+ ))
+ .await;
+
+ assert_eq!(status, StatusCode::OK);
+ match rx.await.unwrap() {
+ OAuthCallbackResult::Success { code, realm_id } => {
+ assert_eq!(code, "qb-code");
+ assert_eq!(realm_id.as_deref(), Some("realm-42"));
+ }
+ other => panic!("expected Success, got {:?}", other),
+ }
+ }
+
+ #[tokio::test]
+ async fn oauth_callback_provider_error_wakes_pending_flow() {
+ let state = "test-cb-error-state";
+ let rx = register_pending(state);
+
+ let (status, body) = oauth_callback(callback_query(
+ None,
+ Some(state),
+ Some("access_denied"),
+ Some("User denied access"),
+ None,
+ ))
+ .await;
+
+ assert_eq!(status, StatusCode::BAD_REQUEST);
+ assert!(body.0.contains("access_denied"));
+ assert!(!pending_contains(state));
+ match rx.await.unwrap() {
+ OAuthCallbackResult::ProviderError {
+ error,
+ error_description,
+ } => {
+ assert_eq!(error, "access_denied");
+ assert_eq!(error_description.as_deref(), Some("User denied access"));
+ }
+ other => panic!("expected ProviderError, got {:?}", other),
+ }
+ }
+
+ #[tokio::test]
+ async fn oauth_callback_error_with_missing_state_leaves_pending_untouched() {
+ let state = "test-cb-error-nostate-state";
+ let mut rx = register_pending(state);
+
+ let (status, _) =
+ oauth_callback(callback_query(None, None, Some("server_error"), None, None)).await;
+
+ assert_eq!(status, StatusCode::BAD_REQUEST);
+ // Unrelated pending flow must survive an error callback without state.
+ assert!(pending_contains(state));
+ assert!(rx.try_recv().is_err());
+ PENDING_OAUTH.lock().unwrap().remove(state);
+ }
+
+ #[tokio::test]
+ async fn oauth_callback_error_with_unknown_state_returns_error_page() {
+ let (status, _) = oauth_callback(callback_query(
+ None,
+ Some("test-cb-unknown-state"),
+ Some("temporarily_unavailable"),
+ None,
+ None,
+ ))
+ .await;
+
+ assert_eq!(status, StatusCode::BAD_REQUEST);
+ }
+
+ #[tokio::test]
+ async fn oauth_callback_missing_code_and_state_is_invalid() {
+ let (status, body) = oauth_callback(callback_query(None, None, None, None, None)).await;
+
+ assert_eq!(status, StatusCode::BAD_REQUEST);
+ assert!(body.0.contains("Missing code or state"));
+ }
+
+ #[tokio::test]
+ async fn oauth_callback_success_with_stale_state_reports_session_expired() {
+ let (status, body) = oauth_callback(callback_query(
+ Some("auth-code-2"),
+ Some("test-cb-stale-state"),
+ None,
+ None,
+ None,
+ ))
+ .await;
+
+ assert_eq!(status, StatusCode::BAD_REQUEST);
+ assert!(body.0.contains("Session expired"));
+ }
}