Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

stop the Anthropic login tests from binding the registered callback port (#3323)

Sebastian Müllere8951e5079ed
diff --git a/crates/pa-ai/src/oauth/anthropic.rs b/crates/pa-ai/src/oauth/anthropic.rs
index 7a2399d236..cde1c6dd1b 100644
--- a/crates/pa-ai/src/oauth/anthropic.rs
+++ b/crates/pa-ai/src/oauth/anthropic.rs
@@ -92,17 +92,29 @@ pub async fn login_anthropic(
}
let (verifier, challenge) = generate_pkce();
let server = AnthropicCallbackServer::start(&verifier)?;
+ login_with_server(http, ui, &server, &verifier, &challenge).await
+}
+
+/// The flow after the bind: present the URL, race the callback against
+/// the paste, exchange the code. `server` listens with `verifier` as
+/// its state.
+async fn login_with_server(
+ http: &dyn ProviderHttp,
+ ui: &dyn OAuthLoginUi,
+ server: &AnthropicCallbackServer,
+ verifier: &str,
+ challenge: &str,
+) -> Result<AnthropicCredentials, String> {
ui.on_auth(
- &authorization_url(&challenge, &verifier),
+ &authorization_url(challenge, verifier),
Some(AUTH_INSTRUCTIONS),
);
-
- let code = wait_for_code(&server, ui, &verifier).await?;
+ let code = wait_for_code(server, ui, verifier).await?;
if ui.is_cancelled() {
return Err(LOGIN_CANCELLED.to_string());
}
ui.on_progress("Exchanging authorization code for tokens...");
- exchange_authorization_code(http, &code, &verifier).await
+ exchange_authorization_code(http, &code, verifier).await
}
/// Refresh an expired credential (TS `refreshAnthropicToken`).
@@ -441,7 +453,6 @@ async fn post_json(
#[cfg(test)]
mod tests {
use super::*;
- use crate::oauth::anthropic_callback::CALLBACK_PORT;
use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;
@@ -449,8 +460,6 @@ mod tests {
use std::sync::{Arc, Mutex};
use tokio::io::AsyncWriteExt as _;
- use super::super::anthropic_callback::{registered_port_stages, CALLBACK_PORT_LOCK};
-
/// A scripted transport: url -> response, recording every posted
/// body. Unknown urls fail the request (the TS suite throws on
/// unexpected fetches).
@@ -629,6 +638,18 @@ mod tests {
)])
}
+ /// The flow on a free loopback port (the registered port is `start`'s
+ /// production bind; `a_bound_port_fails_the_start_clearly` pins it).
+ async fn login_on_a_free_port(
+ http: &ScriptedHttp,
+ ui: &ScriptedUi,
+ ) -> Result<AnthropicCredentials, String> {
+ let (verifier, challenge) = generate_pkce();
+ let server = AnthropicCallbackServer::bind("127.0.0.1", 0, &verifier)
+ .expect("a free loopback port binds");
+ login_with_server(http, ui, &server, &verifier, &challenge).await
+ }
+
#[tokio::test]
async fn the_authorization_url_carries_the_ts_parameters() {
let url = authorization_url("the-challenge", "the-verifier");
@@ -655,13 +676,9 @@ mod tests {
#[tokio::test]
async fn the_exchange_body_matches_the_ts_grant() {
- let _port = CALLBACK_PORT_LOCK.lock().await;
- if !registered_port_stages() {
- return; // the registered port is busy: this run cannot stage it.
- }
let http = token_http();
let ui = ScriptedUi::new(Some(ScriptedAnswer::value("the-code")), None);
- let credentials = login_anthropic(&http, &ui).await.unwrap();
+ let credentials = login_on_a_free_port(&http, &ui).await.unwrap();
assert_eq!(credentials.access, "the-access");
assert_eq!(credentials.refresh, "the-refresh");
// TS: expires = now + expires_in * 1000 - 5 minutes.
@@ -693,13 +710,9 @@ mod tests {
#[tokio::test]
async fn a_failed_exchange_surfaces_the_ts_message() {
- let _port = CALLBACK_PORT_LOCK.lock().await;
- if !registered_port_stages() {
- return; // the registered port is busy: this run cannot stage it.
- }
let http = ScriptedHttp::new(vec![(TOKEN_URL, 400, "no grant")]);
let ui = ScriptedUi::new(Some(ScriptedAnswer::value("the-code")), None);
- let error = login_anthropic(&http, &ui).await.unwrap_err();
+ let error = login_on_a_free_port(&http, &ui).await.unwrap_err();
assert_eq!(
error,
format!(
@@ -710,13 +723,9 @@ mod tests {
#[tokio::test]
async fn a_missing_field_exchange_names_the_response() {
- let _port = CALLBACK_PORT_LOCK.lock().await;
- if !registered_port_stages() {
- return; // the registered port is busy: this run cannot stage it.
- }
let http = ScriptedHttp::new(vec![(TOKEN_URL, 200, r#"{"access_token":"a"}"#)]);
let ui = ScriptedUi::new(Some(ScriptedAnswer::value("the-code")), None);
- let error = login_anthropic(&http, &ui).await.unwrap_err();
+ let error = login_on_a_free_port(&http, &ui).await.unwrap_err();
assert!(
error.starts_with("Token exchange response missing fields"),
"{error}"
@@ -748,10 +757,6 @@ mod tests {
#[tokio::test]
async fn a_state_mismatch_fails_the_paste() {
- let _port = CALLBACK_PORT_LOCK.lock().await;
- if !registered_port_stages() {
- return; // the registered port is busy: this run cannot stage it.
- }
let http = token_http();
let ui = ScriptedUi::new(
Some(ScriptedAnswer::value(
@@ -759,23 +764,19 @@ mod tests {
)),
None,
);
- let error = login_anthropic(&http, &ui).await.unwrap_err();
+ let error = login_on_a_free_port(&http, &ui).await.unwrap_err();
assert_eq!(error, "OAuth state mismatch");
assert!(http.requests.lock().unwrap().is_empty());
}
#[tokio::test]
async fn a_paste_without_a_code_falls_back_to_the_prompt() {
- let _port = CALLBACK_PORT_LOCK.lock().await;
- if !registered_port_stages() {
- return; // the registered port is busy: this run cannot stage it.
- }
let http = token_http();
let ui = ScriptedUi::new(
Some(ScriptedAnswer::value(" ")),
Some(ScriptedAnswer::value("the-prompted-code")),
);
- login_anthropic(&http, &ui).await.unwrap();
+ login_on_a_free_port(&http, &ui).await.unwrap();
let body = http.first_body(TOKEN_URL);
let json: serde_json::Value = serde_json::from_str(&body).unwrap();
assert_eq!(json["code"], "the-prompted-code");
@@ -783,43 +784,31 @@ mod tests {
#[tokio::test]
async fn a_cancelled_paste_ends_the_login() {
- let _port = CALLBACK_PORT_LOCK.lock().await;
- if !registered_port_stages() {
- return; // the registered port is busy: this run cannot stage it.
- }
let http = token_http();
let ui = ScriptedUi::new(Some(ScriptedAnswer::ready()), None);
- let error = login_anthropic(&http, &ui).await.unwrap_err();
+ let error = login_on_a_free_port(&http, &ui).await.unwrap_err();
assert_eq!(error, LOGIN_CANCELLED);
}
#[tokio::test]
async fn a_cancelled_prompt_ends_the_login() {
- let _port = CALLBACK_PORT_LOCK.lock().await;
- if !registered_port_stages() {
- return; // the registered port is busy: this run cannot stage it.
- }
let http = token_http();
let ui = ScriptedUi::new(
Some(ScriptedAnswer::value(" ")),
Some(ScriptedAnswer::ready()),
);
- let error = login_anthropic(&http, &ui).await.unwrap_err();
+ let error = login_on_a_free_port(&http, &ui).await.unwrap_err();
assert_eq!(error, LOGIN_CANCELLED);
}
#[tokio::test]
async fn a_cancelled_surface_ends_the_login_between_polls() {
- let _port = CALLBACK_PORT_LOCK.lock().await;
- if !registered_port_stages() {
- return; // the registered port is busy: this run cannot stage it.
- }
// The flag flips when the url lands: the race loop's first
// poll-step check ends the flow before any code arrives.
let http = token_http();
let mut ui = ScriptedUi::new(Some(ScriptedAnswer::Pending), None);
ui.cancel_on_auth = true;
- let error = login_anthropic(&http, &ui).await.unwrap_err();
+ let error = login_on_a_free_port(&http, &ui).await.unwrap_err();
assert_eq!(error, LOGIN_CANCELLED);
// No token request ever posted.
assert!(http.requests.lock().unwrap().is_empty());
@@ -827,20 +816,25 @@ mod tests {
#[tokio::test]
async fn the_browser_callback_wins_the_race() {
- let _port = CALLBACK_PORT_LOCK.lock().await;
- // The real registered port: the flow binds its callback server
- // and the browser redirect settles the code. Skip when another
- // process holds the port — the bind-failure path is its own
- // invariant.
- if !registered_port_stages() {
- return; // the registered port is busy: this run cannot stage it.
- }
let http = Arc::new(token_http());
let ui = Arc::new(ScriptedUi::new(Some(ScriptedAnswer::Pending), None));
+ let (verifier, challenge) = generate_pkce();
+ let server = AnthropicCallbackServer::bind("127.0.0.1", 0, &verifier)
+ .expect("a free loopback port binds");
+ let port = server.port();
let flow_ui = Arc::clone(&ui);
let flow = {
let flow_http = Arc::clone(&http);
- tokio::spawn(async move { login_anthropic(flow_http.as_ref(), flow_ui.as_ref()).await })
+ tokio::spawn(async move {
+ login_with_server(
+ flow_http.as_ref(),
+ flow_ui.as_ref(),
+ &server,
+ &verifier,
+ &challenge,
+ )
+ .await
+ })
};
let url = ui.captured_url().await;
let state = url::Url::parse(&url)
@@ -849,7 +843,7 @@ mod tests {
.find(|(key, _)| key == "state")
.map(|(_, value)| value.to_string())
.expect("the authorization url carries the state");
- let mut stream = tokio::net::TcpStream::connect(("127.0.0.1", CALLBACK_PORT))
+ let mut stream = tokio::net::TcpStream::connect(("127.0.0.1", port))
.await
.expect("the flow's callback server accepts the redirect");
stream
diff --git a/crates/pa-ai/src/oauth/anthropic_callback.rs b/crates/pa-ai/src/oauth/anthropic_callback.rs
index 6e3949ebcc..029fc076f9 100644
--- a/crates/pa-ai/src/oauth/anthropic_callback.rs
+++ b/crates/pa-ai/src/oauth/anthropic_callback.rs
@@ -55,26 +55,6 @@ impl CallbackShared {
}
}
-/// The tests that bind the registered callback port (`53_692`)
-/// serialize on this lock across the oauth test modules: parallel
-/// test threads never collide on the one port (the OS answers the
-/// bind with `address already in use` otherwise).
-#[cfg(test)]
-pub(crate) static CALLBACK_PORT_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
-
-/// The registered port's staging probe: `true` when this run can bind
-/// it. The lock above serializes the port's binders inside one test
-/// binary; a holder outside it — an ephemeral-range collision on the
-/// runner (`53692` sits inside the kernel's 32768-60999 allocation
-/// range) — is invisible to the lock, so a test that stages the real
-/// flow probes first and skips when the port is busy: the
-/// bind-failure path is its own invariant
-/// (`tests::a_bound_port_fails_the_start_clearly`).
-#[cfg(test)]
-pub(crate) fn registered_port_stages() -> bool {
- std::net::TcpListener::bind(("127.0.0.1", CALLBACK_PORT)).is_ok()
-}
-
/// A running callback server.
///
/// Dropping the server aborts its accept loop, releasing the
@@ -495,7 +475,6 @@ mod tests {
#[tokio::test]
async fn a_bound_port_fails_the_start_clearly() {
- let _port = CALLBACK_PORT_LOCK.lock().await;
// The registered port is occupied, so the login fails (TS
// rejects the server promise with the bind error). Skip when
// the port was already busy before this test — the blocker
diff --git a/crates/pa-cli/src/subscription_login.rs b/crates/pa-cli/src/subscription_login.rs
index a3273bcba9..0508c85bae 100644
--- a/crates/pa-cli/src/subscription_login.rs
+++ b/crates/pa-cli/src/subscription_login.rs
@@ -19,8 +19,9 @@ use std::path::Path;
use std::pin::Pin;
use pa_ai::oauth::{
- login_anthropic, login_github_copilot, login_xai, OAuthLoginUi, OAuthPrompt, ProviderHttp,
- ANTHROPIC_LOGIN_CANCELLED, COPILOT_LOGIN_CANCELLED, XAI_LOGIN_CANCELLED,
+ login_anthropic, login_github_copilot, login_xai, AnthropicCredentials, OAuthLoginUi,
+ OAuthPrompt, ProviderHttp, ANTHROPIC_LOGIN_CANCELLED, COPILOT_LOGIN_CANCELLED,
+ XAI_LOGIN_CANCELLED,
};
use pa_core::auth::{
AuthCredential, AuthStorage, ANTHROPIC_PROVIDER_ID, GITHUB_COPILOT_PROVIDER_ID, XAI_PROVIDER_ID,
@@ -147,6 +148,16 @@ pub(crate) async fn run_anthropic_login(
if ui.is_cancelled() {
return ProviderAuthOutcome::Cancelled;
}
+ store_anthropic_login(agent_dir, provider_name, credentials)
+}
+
+/// TS `completeProviderAuthentication` for Anthropic: store the
+/// credential under the provider id and report the TS status.
+fn store_anthropic_login(
+ agent_dir: &Path,
+ provider_name: &str,
+ credentials: AnthropicCredentials,
+) -> ProviderAuthOutcome {
let mut auth = AuthStorage::create(agent_dir);
auth.set(
ANTHROPIC_PROVIDER_ID,
@@ -329,37 +340,22 @@ mod tests {
}
}
- /// One scripted prompt answer: a value (blank included — TS
- /// `allowEmpty`'s blank entry) or a cancel.
- enum Answer {
- Value(String),
- Cancel,
- }
-
- /// A scripted surface: the prompt answer, the manual paste, and a
- /// shared cancel flag.
+ /// A scripted surface: the prompt answer and a shared cancel flag.
struct ScriptedUi {
- prompt: Answer,
- manual: Option<String>,
+ prompt: String,
cancelled: Arc<AtomicBool>,
}
impl ScriptedUi {
fn new() -> Self {
ScriptedUi {
- prompt: Answer::Value(String::new()),
- manual: None,
+ prompt: String::new(),
cancelled: Arc::new(AtomicBool::new(false)),
}
}
fn prompt(mut self, answer: &str) -> Self {
- self.prompt = Answer::Value(answer.to_string());
- self
- }
-
- fn cancelled_prompt(mut self) -> Self {
- self.prompt = Answer::Cancel;
+ self.prompt = answer.to_string();
self
}
@@ -375,11 +371,7 @@ mod tests {
&self,
_prompt: &OAuthPrompt,
) -> Pin<Box<dyn Future<Output = Option<String>> + Send + '_>> {
- let answer = match &self.prompt {
- Answer::Value(value) => Some(value.clone()),
- Answer::Cancel => None,
- };
- Box::pin(std::future::ready(answer))
+ Box::pin(std::future::ready(Some(self.prompt.clone())))
}
fn on_progress(&self, _message: &str) {}
@@ -387,9 +379,7 @@ mod tests {
fn on_manual_code_input(
&self,
) -> Option<Pin<Box<dyn Future<Output = Option<String>> + Send + '_>>> {
- self.manual
- .as_ref()
- .map(|answer| Box::pin(std::future::ready(Some(answer.clone()))) as _)
+ None
}
fn is_cancelled(&self) -> bool {
@@ -524,27 +514,18 @@ mod tests {
assert_eq!(auth.get_api_key("xai"), Some("grok-access".to_string()));
}
- /// The Anthropic login's run: the flow binds its registered callback
- /// port. Skip when another process holds the port — the flow-level
- /// tests cover the race; this test covers the store's wire shape.
- #[tokio::test]
- async fn the_anthropic_login_stores_the_credential_and_reports_the_ts_status() {
- let Ok(probe) = std::net::TcpListener::bind(("127.0.0.1", 53_692)) else {
- return; // the registered port is busy: this run cannot stage it.
- };
- drop(probe);
+ /// The Anthropic login's store step: the credential's wire shape
+ /// under the provider id (the flow is covered in pa-ai).
+ #[test]
+ fn the_anthropic_login_stores_the_credential_and_reports_the_ts_status() {
let dir = tempfile::tempdir().expect("temp dir");
let agent = agent_dir(&dir);
- let http = ScriptedHttp::new().queue(
- "https://platform.claude.com/v1/oauth/token",
- vec![ScriptedHttp::entry(
- 200,
- r#"{"access_token":"anthropic-access","refresh_token":"anthropic-refresh","expires_in":3600}"#,
- )],
- );
- let mut ui = ScriptedUi::new().cancelled_prompt();
- ui.manual = Some("http://localhost:53692/callback?code=anthropic-code".to_string());
- match run_anthropic_login(&agent, "Anthropic (Claude Pro/Max)", &http, &ui).await {
+ let credentials = AnthropicCredentials {
+ access: "anthropic-access".to_string(),
+ refresh: "anthropic-refresh".to_string(),
+ expires: 4_000_000_000_000,
+ };
+ match store_anthropic_login(&agent, "Anthropic (Claude Pro/Max)", credentials) {
ProviderAuthOutcome::Status(message) => {
assert_eq!(
message,