Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 55 additions & 1 deletion crates/apache-pulsar-testkit/tests/connection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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()));
Expand Down
4 changes: 4 additions & 0 deletions crates/apache-pulsar-testkit/tests/lookup.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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());
}
Expand Down
87 changes: 76 additions & 11 deletions crates/apache-pulsar/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,15 @@ impl SimServer {
fn received(&self, kind: Type) -> Vec<BaseCommand> {
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<String> {
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<S: AsyncRead + AsyncWrite>(mut stream: S, mut behavior: Behavior, log: Rc<RefCell<Vec<BaseCommand>>>) {
Expand Down Expand Up @@ -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<BaseCommand>) -> 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);
Expand Down Expand Up @@ -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 || {
Expand All @@ -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();
});
}
Expand Down Expand Up @@ -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<AtomicUsize>);
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 {
Expand Down
Loading
Loading