Skip to main content

arrow_integration_testing/flight_client_scenarios/
auth_basic_proto.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! Scenario for testing basic auth.
6
7use crate::{AUTH_PASSWORD, AUTH_USERNAME};
8
9use arrow_flight::{BasicAuth, HandshakeRequest, flight_service_client::FlightServiceClient};
10use futures::{StreamExt, stream};
11use prost::Message;
12use tonic::{Request, Status, metadata::MetadataValue, transport::Endpoint};
13
14type Error = Box<dyn std::error::Error + Send + Sync + 'static>;
15type Result<T = (), E = Error> = std::result::Result<T, E>;
16
17type Client = FlightServiceClient<tonic::transport::Channel>;
18
19/// Run a scenario that tests basic auth.
20pub async fn run_scenario(host: &str, port: u16) -> Result {
21    let url = format!("http://{host}:{port}");
22    let endpoint = Endpoint::new(url)?;
23    let channel = endpoint.connect().await?;
24    let mut client = FlightServiceClient::new(channel);
25
26    let action = arrow_flight::Action::default();
27
28    let resp = client.do_action(Request::new(action.clone())).await;
29    // This client is unauthenticated and should fail.
30    match resp {
31        Err(e) => {
32            if e.code() != tonic::Code::Unauthenticated {
33                return Err(Box::new(Status::internal(format!(
34                    "Expected UNAUTHENTICATED but got {e:?}"
35                ))));
36            }
37        }
38        Ok(other) => {
39            return Err(Box::new(Status::internal(format!(
40                "Expected UNAUTHENTICATED but got {other:?}"
41            ))));
42        }
43    }
44
45    let token = authenticate(&mut client, AUTH_USERNAME, AUTH_PASSWORD)
46        .await
47        .expect("must respond successfully from handshake");
48
49    let mut request = Request::new(action);
50    let metadata = request.metadata_mut();
51    metadata.insert_bin(
52        "auth-token-bin",
53        MetadataValue::from_bytes(token.as_bytes()),
54    );
55
56    let resp = client.do_action(request).await?;
57    let mut resp = resp.into_inner();
58
59    let r = resp
60        .next()
61        .await
62        .expect("No response received")
63        .expect("Invalid response received");
64
65    let body = std::str::from_utf8(&r.body).unwrap();
66    assert_eq!(body, AUTH_USERNAME);
67
68    Ok(())
69}
70
71async fn authenticate(client: &mut Client, username: &str, password: &str) -> Result<String> {
72    let auth = BasicAuth {
73        username: username.into(),
74        password: password.into(),
75    };
76    let mut payload = vec![];
77    auth.encode(&mut payload)?;
78
79    let req = stream::once(async {
80        HandshakeRequest {
81            payload: payload.into(),
82            ..HandshakeRequest::default()
83        }
84    });
85
86    let rx = client.handshake(Request::new(req)).await?;
87    let mut rx = rx.into_inner();
88
89    let r = rx.next().await.expect("must respond from handshake")?;
90    assert!(rx.next().await.is_none(), "must not respond a second time");
91
92    Ok(std::str::from_utf8(&r.payload).unwrap().into())
93}