diff --git a/crates/apache-pulsar-testkit/tests/connection.rs b/crates/apache-pulsar-testkit/tests/connection.rs index 35dd4ab..e5072cc 100644 --- a/crates/apache-pulsar-testkit/tests/connection.rs +++ b/crates/apache-pulsar-testkit/tests/connection.rs @@ -24,7 +24,9 @@ use apache_pulsar_protocol::connection::{ State, }; use apache_pulsar_protocol::proto::base_command::Type; -use apache_pulsar_protocol::proto::{BaseCommand, CommandScalableTopicLookup, FeatureFlags, ServerError}; +use apache_pulsar_protocol::proto::{ + AuthData, BaseCommand, CommandAuthChallenge, CommandScalableTopicLookup, FeatureFlags, ServerError, +}; use apache_pulsar_testkit::{Link, SimBroker, reply}; use buffa::EnumValue; @@ -170,6 +172,58 @@ fn auth_refresh_and_challenge_rounds() { assert_eq!(closed_with(&events), Some(&ConnectionError::TooManyAuthRounds)); } +/// Ten challenge rounds, a refresh, then ten more: the refresh starts the count over, so a connection the broker +/// refreshes now and then is never failed by the cap. Java's +/// `ClientCnxAsyncAuthTest.refreshResetsChallengeRoundCounter`. +#[test] +fn a_refresh_starts_the_challenge_rounds_over() { + let mut link = connected(); + let answer_rounds = |link: &mut Link| { + for round in 1..=MAX_AUTH_CHALLENGE_ROUNDS { + let events = link.push(&reply::auth_challenge(b"again")); + assert!( + matches!(events.as_slice(), [Event::AuthChallenge { refresh: false, .. }]), + "round {round}: {events:?}" + ); + link.client.auth_response(b"answer".to_vec()); + } + }; + answer_rounds(&mut link); + let events = link.push(&reply::auth_challenge(AUTH_REFRESH_SENTINEL)); + assert!(matches!(events.as_slice(), [Event::AuthChallenge { refresh: true, .. }]), "{events:?}"); + link.client.auth_response(b"new-token".to_vec()); + answer_rounds(&mut link); + assert_eq!(link.client.state(), State::Ready); +} + +/// Only `PulsarAuthRefresh` asks for fresh credentials. `PulsarAuthInit`, an empty payload, an absent one and any +/// other are challenges, handed to the driver as they came. Java's +/// `BinaryAuthenticationExchangeTest.isRefreshSentinelMatchesOnlyTheRefreshPayload`. +#[test] +fn only_the_refresh_sentinel_asks_for_fresh_credentials() { + let classify = |command: &BaseCommand| { + let mut link = connected(); + match link.push(command).as_slice() { + [Event::AuthChallenge { refresh, challenge }] => (*refresh, challenge.to_vec()), + events => panic!("one challenge expected: {events:?}"), + } + }; + let challenge = |challenge: CommandAuthChallenge| BaseCommand { + r#type: Type::AUTH_CHALLENGE.into(), + authChallenge: challenge.into(), + ..Default::default() + }; + assert_eq!(classify(&reply::auth_challenge(AUTH_REFRESH_SENTINEL)), (true, AUTH_REFRESH_SENTINEL.to_vec())); + // Java's `AuthData.INIT_AUTH_DATA`. + assert_eq!(classify(&reply::auth_challenge(b"PulsarAuthInit")), (false, b"PulsarAuthInit".to_vec())); + assert_eq!(classify(&reply::auth_challenge(b"")), (false, vec![])); + assert_eq!(classify(&reply::auth_challenge(b"challenge")), (false, b"challenge".to_vec())); + // Auth data without its bytes, and no auth data at all. + let without_bytes = CommandAuthChallenge { challenge: AuthData::default().into(), ..Default::default() }; + assert_eq!(classify(&challenge(without_bytes)), (false, vec![])); + assert_eq!(classify(&challenge(CommandAuthChallenge::default())), (false, vec![])); +} + #[test] fn scalable_commands_need_the_broker_feature() { let mut link = Link::new(ConnectOptions::default(), SimBroker::with_features(FeatureFlags::default())); diff --git a/crates/apache-pulsar-testkit/tests/lookup.rs b/crates/apache-pulsar-testkit/tests/lookup.rs index 5c3c256..a6c898e 100644 --- a/crates/apache-pulsar-testkit/tests/lookup.rs +++ b/crates/apache-pulsar-testkit/tests/lookup.rs @@ -103,6 +103,10 @@ fn service_urls() { vec![hp("a:6651"), hp("b:7000"), apache_pulsar_protocol::lookup::HostPort { host: "::1".into(), port: 6000 }] ); assert!(ServiceUrl::parse("http://a:8080").is_err()); + // A web service URL over TLS is refused, the reason naming the scheme to use. Java's + // `PulsarClientBuilderV5Test.testRejectsHttpsWithGuidance`. + let error = ServiceUrl::parse("https://a:8443").unwrap_err(); + assert!(error.reason.contains("pulsar+ssl://"), "{error}"); assert!(ServiceUrl::parse("pulsar://a:x").is_err()); assert!(ServiceUrl::parse("pulsar://").is_err()); } diff --git a/crates/apache-pulsar/src/tests.rs b/crates/apache-pulsar/src/tests.rs index 183bb77..fe69136 100644 --- a/crates/apache-pulsar/src/tests.rs +++ b/crates/apache-pulsar/src/tests.rs @@ -105,6 +105,15 @@ impl SimServer { fn received(&self, kind: Type) -> Vec { self.log.borrow().iter().filter(|c| c.r#type == EnumValue::Known(kind)).cloned().collect() } + + /// What the client answered to the broker's challenges, in order. + fn auth_responses(&self) -> Vec { + let answer = |command: &BaseCommand| { + let data = command.authResponse.as_option().unwrap().response.as_option().unwrap().auth_data.clone(); + String::from_utf8(data.unwrap()).unwrap() + }; + self.received(Type::AUTH_RESPONSE).iter().map(answer).collect() + } } async fn serve(mut stream: S, mut behavior: Behavior, log: Rc>>) { @@ -146,6 +155,17 @@ fn self_serving(address: &HostPort) -> Behavior { Behavior { broker, close_after: None, push_after_connect: vec![] } } +/// A self-serving broker that challenges the client: with the first of `challenges` once it is connected, and with +/// each next one once it answered the one before. +fn challenging(address: &HostPort, challenges: Vec) -> Behavior { + let mut challenges = challenges.into_iter(); + let mut behavior = + Behavior { push_after_connect: challenges.next().into_iter().collect(), ..self_serving(address) }; + // The client's answers are the only commands the simulated broker leaves to its responder. + behavior.broker.on_command = Some(Box::new(move |_| challenges.next().into_iter().collect())); + behavior +} + /// Waits for `condition`, polling, for up to 10 s: CI machines stall, so tests wait for states, not for times. async fn wait_until(what: &str, condition: impl Fn() -> bool) { let deadline = std::time::Instant::now() + Duration::from_secs(10); @@ -294,15 +314,15 @@ fn keepalive_keeps_an_answering_connection() { }); } +/// A token fetched for `CONNECT`, and again for each refresh the broker asks for: each refresh is answered in band +/// with the next token, over the one connection, which stays open. Java's +/// `ClientCnxAsyncAuthTest.refreshRepublishesCredentialWithoutDisconnect`. #[test] fn token_authentication_and_refresh() { run(async { let refresh = reply::auth_challenge(AUTH_REFRESH_SENTINEL); - let server = SimServer::start(None, move |address| Behavior { - push_after_connect: vec![refresh.clone()], - ..self_serving(address) - }) - .await; + let server = + SimServer::start(None, move |address| challenging(address, vec![refresh.clone(), refresh.clone()])).await; let fetched = Arc::new(AtomicUsize::new(0)); let counter = fetched.clone(); let token = Token::from_fn(move || { @@ -316,15 +336,15 @@ fn token_authentication_and_refresh() { .await .unwrap(); client.lookup(TOPIC).await.unwrap(); - wait_until("the refresh is answered", || !server.received(Type::AUTH_RESPONSE).is_empty()).await; + wait_until("both refreshes are answered", || server.auth_responses().len() >= 2).await; let connect = server.received(Type::CONNECT)[0].connect.as_option().unwrap().clone(); assert_eq!(connect.auth_method_name.as_deref(), Some("token")); assert_eq!(connect.auth_data.as_deref(), Some(&b"token-0"[..])); - let response = server.received(Type::AUTH_RESPONSE); - assert_eq!(response.len(), 1, "the refresh challenge is answered"); - let data = response[0].authResponse.as_option().unwrap().response.as_option().unwrap().auth_data.clone(); - assert_eq!(data.as_deref(), Some(&b"token-1"[..])); - assert_eq!(fetched.load(Ordering::SeqCst), 2); + assert_eq!(server.auth_responses(), ["token-1", "token-2"]); + assert_eq!(fetched.load(Ordering::SeqCst), 3); + // The connection still serves, so no new one sent a second CONNECT. + client.lookup(TOPIC).await.unwrap(); + assert_eq!(server.received(Type::CONNECT).len(), 1); client.close().await.unwrap(); }); } @@ -435,6 +455,51 @@ fn dropping_the_last_client_handle_stops_its_loops() { } } +/// Closing the client releases its authentication provider, whose close is its drop: once the thread-safe client's +/// `close` has stopped its loops, nothing holds the provider, though a handle to the client remains. The local +/// client's goes with its last handle, once `close` has ended the connections that used it. Java's +/// `ClientAuthenticationLifecycleTest.closingTheClientClosesAV5NativePlugin`. +#[test] +fn closing_the_client_releases_its_authentication_provider() { + /// Counts its drops. + struct Counted(Arc); + impl crate::Authentication for Counted { + fn method_name(&self) -> &str { + "counted" + } + fn auth_data(&self) -> crate::auth::AuthFuture { + Box::pin(async { Ok(Vec::new()) }) + } + } + impl Drop for Counted { + fn drop(&mut self) { + self.0.fetch_add(1, Ordering::SeqCst); + } + } + + let drops = Arc::new(AtomicUsize::new(0)); + let builder = PulsarClient::builder().service_url("pulsar://127.0.0.1:1").event_loops(2); + let client = futures_executor::block_on(builder.authentication(Counted(drops.clone())).build()).unwrap(); + assert_eq!(drops.load(Ordering::SeqCst), 0); + futures_executor::block_on(client.close()).unwrap(); + assert_eq!(drops.load(Ordering::SeqCst), 1); + + let drops = Arc::new(AtomicUsize::new(0)); + run(async { + let server = SimServer::start(None, self_serving).await; + let local = local::PulsarClient::builder() + .service_url(server.service_url("pulsar")) + .authentication(Counted(drops.clone())) + .build() + .await + .unwrap(); + local.lookup(TOPIC).await.unwrap(); + local.close().await.unwrap(); + drop(local); + assert_eq!(drops.load(Ordering::SeqCst), 1); + }); +} + #[test] fn lookup_moves_to_the_next_service_host() { run(async { diff --git a/crates/apache-pulsar/src/tests/driver.rs b/crates/apache-pulsar/src/tests/driver.rs index 40691f7..8d46023 100644 --- a/crates/apache-pulsar/src/tests/driver.rs +++ b/crates/apache-pulsar/src/tests/driver.rs @@ -223,6 +223,57 @@ fn challenges_are_answered_by_the_provider() { }); } +/// A refresh is answered by the provider's `auth_data`, and any other challenge by its `challenge`: an empty +/// payload, an absent one and `PulsarAuthInit` too. Java's `BinaryAuthenticationExchangeTest`'s +/// `refreshSentinelRoutesToCredentialProviderNotChallengeHandler`, +/// `emptyChallengeRoutesToChallengeHandlerNotCredentialProvider` and +/// `initPayloadRoutesToChallengeHandlerNotCredentialProvider`. +#[test] +fn only_a_refresh_is_answered_with_fresh_auth_data() { + /// Answers `CONNECT` and refreshes with its credential, and a challenge with what it asked. + struct TwoAnswers; + impl crate::Authentication for TwoAnswers { + fn method_name(&self) -> &str { + "two-answers" + } + fn auth_data(&self) -> crate::auth::AuthFuture { + Box::pin(async { Ok(b"credential".to_vec()) }) + } + fn challenge(&self, challenge: &[u8]) -> crate::auth::AuthFuture { + let answer = [&b"response-to:"[..], challenge].concat(); + Box::pin(async move { Ok(answer) }) + } + } + + run(async { + let absent = BaseCommand { + r#type: Type::AUTH_CHALLENGE.into(), + authChallenge: apache_pulsar_protocol::proto::CommandAuthChallenge::default().into(), + ..Default::default() + }; + let challenges = vec![ + reply::auth_challenge(AUTH_REFRESH_SENTINEL), + reply::auth_challenge(b""), + absent, + // Java's `AuthData.INIT_AUTH_DATA`. + reply::auth_challenge(b"PulsarAuthInit"), + ]; + let server = SimServer::start(None, move |address| challenging(address, challenges.clone())).await; + let client = local::PulsarClient::builder() + .service_url(server.service_url("pulsar")) + .authentication(TwoAnswers) + .build() + .await + .unwrap(); + let connection = client.connection(&connect_to(&server)).await.unwrap(); + wait_until("every challenge is answered", || server.auth_responses().len() >= 4).await; + let answers = ["credential", "response-to:", "response-to:", "response-to:PulsarAuthInit"]; + assert_eq!(server.auth_responses(), answers); + assert!(!connection.is_closed()); + client.close().await.unwrap(); + }); +} + #[test] fn a_provider_failing_a_refresh_closes_the_connection() { run(async { @@ -254,6 +305,134 @@ fn a_provider_failing_a_refresh_closes_the_connection() { }); } +/// A second refresh comes while the provider's answer to the first is still pending: only the second's answer goes +/// out, and the first's, when it comes, is dropped. Java's `ClientCnxAsyncAuthTest.staleRoundCompletionIsIgnored`. +#[test] +fn a_refresh_supersedes_one_still_pending() { + /// Answers its call `n` with `token-n`, but call 1, the first refresh's, only once `gate` opens. It counts its + /// calls as they are made, whether or not their futures ever run. + struct Gated { + calls: Arc, + gate: std::sync::Mutex>>, + } + impl crate::Authentication for Gated { + fn method_name(&self) -> &str { + "token" + } + fn auth_data(&self) -> crate::auth::AuthFuture { + let n = self.calls.fetch_add(1, Ordering::SeqCst); + let gate = if n == 1 { self.gate.lock().unwrap().take() } else { None }; + Box::pin(async move { + if let Some(gate) = gate { + let _ = gate.await; + } + Ok(format!("token-{n}").into_bytes()) + }) + } + } + + run(async { + let refresh = reply::auth_challenge(AUTH_REFRESH_SENTINEL); + let server = SimServer::start(None, move |address| Behavior { + push_after_connect: vec![refresh.clone(), refresh.clone()], + ..self_serving(address) + }) + .await; + let calls = Arc::new(AtomicUsize::new(0)); + let (release, gate) = futures_channel::oneshot::channel(); + let client = local::PulsarClient::builder() + .service_url(server.service_url("pulsar")) + .authentication(Gated { calls: calls.clone(), gate: std::sync::Mutex::new(Some(gate)) }) + .build() + .await + .unwrap(); + let connection = client.connection(&connect_to(&server)).await.unwrap(); + wait_until("a refresh is answered", || !server.auth_responses().is_empty()).await; + // The first refresh's answer comes late. A late answer would go out before the lookup's comes back. + let _ = release.send(()); + connection.request(lookup_request(&server)).await.unwrap(); + assert_eq!(server.auth_responses(), ["token-2"]); + assert_eq!(calls.load(Ordering::SeqCst), 3); + assert!(!connection.is_closed()); + client.close().await.unwrap(); + }); +} + +/// A provider whose first answer fails is asked again for the next connection, which it then answers: a failed +/// attempt leaves nothing behind. Java's +/// `AuthInitializationRetryTest.anImmediatelyFailedInitializationIsRetriedOnTheNextConnection`. +#[test] +fn a_provider_that_failed_is_asked_again_for_the_next_connection() { + run(async { + let server = SimServer::start(None, self_serving).await; + let calls = Arc::new(AtomicUsize::new(0)); + let counter = calls.clone(); + let token = Token::from_fn(move || { + let n = counter.fetch_add(1, Ordering::SeqCst); + async move { + if n == 0 { + Err(crate::Error::new(ErrorKind::Authentication, "the identity provider is not reachable yet")) + } else { + Ok(format!("token-{n}")) + } + } + }); + let client = local::PulsarClient::builder() + .service_url(server.service_url("pulsar")) + .authentication(token) + .build() + .await + .unwrap(); + assert!(client.connection(&connect_to(&server)).await.is_err()); + let connection = client.connection(&connect_to(&server)).await.unwrap(); + assert!(!connection.is_closed()); + assert_eq!(calls.load(Ordering::SeqCst), 2); + let connect = server.received(Type::CONNECT); + assert_eq!(connect.len(), 1, "the failed attempt sent no CONNECT"); + assert_eq!(connect[0].connect.as_option().unwrap().auth_data.as_deref(), Some(&b"token-1"[..])); + client.close().await.unwrap(); + }); +} + +/// The broker closes the socket while the provider is still fetching the credential for `CONNECT`: once it comes, +/// the connection fails on the closed socket, rather than waiting out the handshake. Java's +/// `ClientCnxAsyncAuthTest.continuationAfterChannelCloseDoesNotWrite`; Rust learns of the close from the socket, and +/// may still write the `CONNECT`, which goes nowhere. +#[test] +fn a_socket_closed_while_the_credential_is_fetched_fails_the_connection() { + run(async { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let (closed, on_close) = futures_channel::oneshot::channel(); + // The broker takes the connection and closes it at once. + let broker = compio::runtime::spawn(async move { + let (tcp, _) = listener.accept().await.unwrap(); + tcp.close().await.unwrap(); + closed.send(()).unwrap(); + }); + let on_close = std::sync::Mutex::new(Some(on_close)); + let token = Token::from_fn(move || { + let on_close = on_close.lock().unwrap().take().unwrap(); + async move { + let _ = on_close.await; + Ok("token".to_string()) + } + }); + let client = local::PulsarClient::builder() + .service_url(format!("pulsar://127.0.0.1:{port}")) + .authentication(token) + .build() + .await + .unwrap(); + let address = BrokerAddress::direct(HostPort { host: "127.0.0.1".into(), port }); + let error = client.connection(&address).await.unwrap_err(); + // A connection that missed the close would wait out the connect timeout, and fail with `Timeout`. + assert_eq!(error.kind(), ErrorKind::Connect, "{error}"); + broker.await.unwrap(); + client.close().await.unwrap(); + }); +} + #[test] fn a_challenge_without_a_provider_closes_the_connection() { run(async { diff --git a/crates/apache-pulsar/src/tests/options.rs b/crates/apache-pulsar/src/tests/options.rs index 416f741..ea5b88b 100644 --- a/crates/apache-pulsar/src/tests/options.rs +++ b/crates/apache-pulsar/src/tests/options.rs @@ -90,6 +90,11 @@ fn the_builder_refuses_incomplete_or_contradictory_options() { let error = error_of(local::PulsarClient::builder().service_url("http://broker:8080").into_config()); assert_eq!(error.kind(), ErrorKind::InvalidServiceUrl, "{error}"); + // An empty or blank URL fails the build too. Java's `PulsarClientBuilderV5Test.testRejectsNullAndBlank`. + for url in ["", " "] { + let error = error_of(futures_executor::block_on(local::PulsarClient::builder().service_url(url).build())); + assert_eq!(error.kind(), ErrorKind::InvalidServiceUrl, "{url:?}: {error}"); + } let tls = TlsAuthentication::from_pem(Vec::new(), Vec::new()); let error =