Skip to main content

pgwire/
pg_server.rs

1// Copyright 2022 RisingWave Labs
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::collections::HashMap;
16use std::future::Future;
17use std::str::FromStr;
18use std::sync::Arc;
19use std::time::Instant;
20
21use bytes::Bytes;
22use jsonwebtoken::{Algorithm, DecodingKey, Validation, decode, decode_header};
23use parking_lot::Mutex;
24use risingwave_common::config::HbaEntry;
25use risingwave_common::id::DatabaseId;
26use risingwave_common::types::DataType;
27use risingwave_common::util::runtime::BackgroundShutdownRuntime;
28use risingwave_common::util::tokio_util::sync::CancellationToken;
29use risingwave_sqlparser::ast::Statement;
30use serde::Deserialize;
31use thiserror_ext::AsReport;
32
33use crate::error::{PsqlError, PsqlResult};
34use crate::ldap_auth::LdapAuthenticator;
35use crate::net::{AddressRef, Listener, TcpKeepalive};
36use crate::pg_field_descriptor::PgFieldDescriptor;
37use crate::pg_message::TransactionStatus;
38use crate::pg_protocol::{ConnectionContext, PgByteStream, PgProtocol};
39use crate::pg_response::{PgResponse, ValuesStream};
40use crate::types::Format;
41
42pub type BoxedError = Box<dyn std::error::Error + Send + Sync>;
43type ProcessId = i32;
44type SecretKey = i32;
45pub type SessionId = (ProcessId, SecretKey);
46
47/// The interface for a database system behind pgwire protocol.
48/// We can mock it for testing purpose.
49pub trait SessionManager: Send + Sync + 'static {
50    type Error: Into<BoxedError>;
51    type Session: Session<Error = Self::Error>;
52
53    /// In the process of auto schema change, we need a dummy session to access
54    /// catalog information in frontend and build a replace plan for the table.
55    fn create_dummy_session(
56        &self,
57        database_id: DatabaseId,
58    ) -> Result<Arc<Self::Session>, Self::Error>;
59
60    fn connect(
61        &self,
62        database: &str,
63        user_name: &str,
64        peer_addr: AddressRef,
65    ) -> Result<Arc<Self::Session>, Self::Error>;
66
67    fn cancel_queries_in_session(&self, session_id: SessionId);
68
69    fn cancel_creating_jobs_in_session(&self, session_id: SessionId);
70
71    fn end_session(&self, session: &Self::Session);
72
73    /// Run some cleanup tasks before the server shutdown.
74    fn shutdown(&self) -> impl Future<Output = ()> + Send {
75        async {}
76    }
77}
78
79/// A psql connection. Each connection binds with a database. Switching database will need to
80/// recreate another connection.
81pub trait Session: Send + Sync {
82    type Error: Into<BoxedError>;
83    type ValuesStream: ValuesStream;
84    type PreparedStatement: Send + Clone + 'static;
85    type Portal: Send + Clone + std::fmt::Display + 'static;
86
87    /// The str sql can not use the unparse from AST: There is some problem when dealing with create
88    /// view, see <https://github.com/risingwavelabs/risingwave/issues/6801>.
89    fn run_one_query(
90        self: Arc<Self>,
91        stmt: Statement,
92        format: Format,
93    ) -> impl Future<Output = Result<PgResponse<Self::ValuesStream>, Self::Error>> + Send;
94
95    fn parse(
96        self: Arc<Self>,
97        sql: Option<Statement>,
98        params_types: Vec<Option<DataType>>,
99    ) -> impl Future<Output = Result<Self::PreparedStatement, Self::Error>> + Send;
100
101    /// Receive the next notice message to send to the client.
102    ///
103    /// This function should be cancellation-safe.
104    fn next_notice(self: &Arc<Self>) -> impl Future<Output = String> + Send;
105
106    fn bind(
107        self: Arc<Self>,
108        prepare_statement: Self::PreparedStatement,
109        params: Vec<Option<Bytes>>,
110        param_formats: Vec<Format>,
111        result_formats: Vec<Format>,
112    ) -> Result<Self::Portal, Self::Error>;
113
114    fn execute(
115        self: Arc<Self>,
116        portal: Self::Portal,
117    ) -> impl Future<Output = Result<PgResponse<Self::ValuesStream>, Self::Error>> + Send;
118
119    fn describe_statement(
120        self: Arc<Self>,
121        prepare_statement: Self::PreparedStatement,
122    ) -> Result<(Vec<DataType>, Vec<PgFieldDescriptor>), Self::Error>;
123
124    fn describe_portal(
125        self: Arc<Self>,
126        portal: Self::Portal,
127    ) -> Result<Vec<PgFieldDescriptor>, Self::Error>;
128
129    fn user_authenticator(&self) -> &UserAuthenticator;
130
131    fn id(&self) -> SessionId;
132
133    fn get_config(&self, key: &str) -> Result<String, Self::Error>;
134
135    fn set_config(&self, key: &str, value: String) -> Result<String, Self::Error>;
136
137    fn transaction_status(&self) -> TransactionStatus;
138
139    fn init_exec_context(&self, sql: Arc<str>) -> ExecContextGuard;
140
141    fn check_idle_in_transaction_timeout(&self) -> PsqlResult<()>;
142
143    fn user(&self) -> String;
144}
145
146/// Each session could run different SQLs multiple times.
147/// `ExecContext` represents the lifetime of a running SQL in the current session.
148pub struct ExecContext {
149    pub running_sql: Arc<str>,
150    /// The instant of the running sql
151    pub last_instant: Instant,
152    /// A reference used to update when `ExecContext` is dropped
153    pub last_idle_instant: Arc<Mutex<Option<Instant>>>,
154}
155
156/// `ExecContextGuard` holds a `Arc` pointer. Once `ExecContextGuard` is dropped,
157/// the inner `Arc<ExecContext>` should not be referred anymore, so that its `Weak` reference (used in `SessionImpl`) will be the same lifecycle of the running sql execution context.
158pub struct ExecContextGuard(#[expect(dead_code)] Arc<ExecContext>);
159
160impl ExecContextGuard {
161    pub fn new(exec_context: Arc<ExecContext>) -> Self {
162        Self(exec_context)
163    }
164}
165
166impl Drop for ExecContext {
167    fn drop(&mut self) {
168        *self.last_idle_instant.lock() = Some(Instant::now());
169    }
170}
171
172#[derive(Debug, Clone)]
173pub enum UserAuthenticator {
174    // No need to authenticate.
175    None,
176    // raw password in clear-text form.
177    ClearText(Vec<u8>),
178    // password encrypted with random salt.
179    Md5WithSalt {
180        encrypted_password: Vec<u8>,
181        salt: [u8; 4],
182    },
183    OAuth {
184        metadata: HashMap<String, String>,
185        cluster_id: String,
186    },
187    Ldap(String, HbaEntry),
188}
189
190/// A JWK Set is a JSON object that represents a set of JWKs.
191/// The JSON object MUST have a "keys" member, with its value being an array of JWKs.
192/// See <https://www.rfc-editor.org/rfc/rfc7517.html#section-5> for more details.
193#[derive(Debug, Deserialize)]
194struct Jwks {
195    keys: Vec<Jwk>,
196}
197
198/// A JSON Web Key (JWK) is a JSON object that represents a cryptographic key.
199/// See <https://www.rfc-editor.org/rfc/rfc7517.html#section-4> for more details.
200#[derive(Debug, Deserialize)]
201struct Jwk {
202    kty: Option<String>, // Key Type
203    kid: Option<String>, // Key ID (OPTIONAL per RFC 7517 section 4.5)
204    alg: Option<String>, // Algorithm (OPTIONAL per RFC 7517 section 4.4)
205    n: Option<String>,   // RSA modulus
206    e: Option<String>,   // RSA exponent
207}
208
209/// Algorithms we accept for JWT signature verification.
210///
211/// Restricted to RSA-family algorithms because the only `DecodingKey` we build
212/// is from RSA components (`n`, `e`). Pinning the algorithm to a server-side
213/// allow-list also prevents the classic alg-confusion attack: a token with
214/// `alg: "none"` (no signature) or `alg: "HS256"` forged using the RSA public
215/// key as the HMAC secret cannot select a verification algorithm outside this
216/// set.
217const ALLOWED_JWT_ALGORITHMS: &[Algorithm] = &[
218    Algorithm::RS256,
219    Algorithm::RS384,
220    Algorithm::RS512,
221    Algorithm::PS256,
222    Algorithm::PS384,
223    Algorithm::PS512,
224];
225const RSA_JWK_KEY_TYPE: &str = "RSA";
226/// Optional OAuth user option overriding the expected JWT `aud`.
227const OAUTH_AUDIENCE_KEY: &str = "audience";
228
229async fn validate_jwt(
230    jwt: &str,
231    jwks_url: &str,
232    issuer: &str,
233    audience: &str,
234    metadata: &HashMap<String, String>,
235) -> Result<bool, BoxedError> {
236    let jwks: Jwks = reqwest::get(jwks_url).await?.json().await?;
237    validate_jwt_with_jwks(jwt, &jwks, issuer, audience, metadata)
238}
239
240fn audience_from_cluster_id(cluster_id: &str) -> String {
241    format!("urn:risingwave:cluster:{}", cluster_id)
242}
243
244fn resolve_oauth_audience(
245    configured: Option<String>,
246    cluster_id: &str,
247) -> Result<String, BoxedError> {
248    let Some(configured_audience) = configured else {
249        return Ok(audience_from_cluster_id(cluster_id));
250    };
251
252    let audience = configured_audience.trim();
253    if audience.is_empty() {
254        return Err(format!("OAuth option `{OAUTH_AUDIENCE_KEY}` cannot be empty").into());
255    }
256    Ok(audience.to_owned())
257}
258
259fn validate_jwt_with_jwks(
260    jwt: &str,
261    jwks: &Jwks,
262    issuer: &str,
263    audience: &str,
264    metadata: &HashMap<String, String>,
265) -> Result<bool, BoxedError> {
266    let header = decode_header(jwt)?;
267
268    // 1. Retrieve the kid from the header to find compatible JWKs in the JWK Set.
269    let kid = header.kid.ok_or("JWT header missing 'kid' field")?;
270
271    // 2. Decide which algorithm to use.
272    //
273    // Per RFC 7517 §4.4 the JWK `alg` member is OPTIONAL. When the JWK pins an
274    // `alg`, the JWT header MUST match it; when it doesn't, we fall back to
275    // the header's `alg` but only after checking it against a server-side
276    // allow-list. The allow-list is what ultimately blocks alg-confusion: an
277    // attacker-chosen `alg` from the token header alone must never be trusted
278    // to select the verification algorithm.
279    if !ALLOWED_JWT_ALGORITHMS.contains(&header.alg) {
280        return Err(format!("JWT alg {:?} is not allowed", header.alg).into());
281    }
282
283    // A JWK Set can contain unrelated key types, keys without an optional `kid`,
284    // and equivalent keys of different types that share a `kid`. Scan all
285    // candidates instead of letting the first same-`kid` key shadow a usable
286    // RSA key later in the set.
287    let jwk = jwks
288        .keys
289        .iter()
290        .filter(|jwk| jwk.kid.as_deref() == Some(kid.as_str()))
291        .find(|jwk| {
292            jwk.kty.as_deref() == Some(RSA_JWK_KEY_TYPE)
293                && jwk.n.is_some()
294                && jwk.e.is_some()
295                && match jwk.alg.as_deref() {
296                    Some(alg) => Algorithm::from_str(alg).is_ok_and(|alg| alg == header.alg),
297                    None => true,
298                }
299        })
300        .ok_or_else(|| format!("No compatible RSA key found in JWKS for kid: '{}'", kid))?;
301
302    // 3. Decode the JWT and validate the claims.
303    let n = jwk.n.as_deref().expect("RSA candidate must have a modulus");
304    let e = jwk
305        .e
306        .as_deref()
307        .expect("RSA candidate must have an exponent");
308    let decoding_key = DecodingKey::from_rsa_components(n, e)?;
309    let mut validation = Validation::new(header.alg);
310    validation.set_issuer(&[issuer]);
311    validation.set_audience(&[audience]);
312    validation.set_required_spec_claims(&["exp", "iss", "aud"]);
313    let token_data = decode::<HashMap<String, serde_json::Value>>(jwt, &decoding_key, &validation)?;
314
315    // 4. Check if the metadata in the token matches.
316    if !metadata.iter().all(
317        |(k, v)| matches!(token_data.claims.get(k), Some(serde_json::Value::String(s)) if s == v),
318    ) {
319        return Err("metadata in jwt does not match with metadata declared with user".into());
320    }
321    Ok(true)
322}
323
324impl UserAuthenticator {
325    pub async fn authenticate(&self, password: &[u8]) -> PsqlResult<()> {
326        let success = match self {
327            UserAuthenticator::None => true,
328            UserAuthenticator::ClearText(text) => password == text,
329            UserAuthenticator::Md5WithSalt {
330                encrypted_password, ..
331            } => encrypted_password == password,
332            UserAuthenticator::OAuth {
333                metadata,
334                cluster_id,
335            } => {
336                let mut metadata = metadata.clone();
337                let jwks_url = metadata.remove("jwks_url").unwrap();
338                let issuer = metadata.remove("issuer").unwrap();
339                let audience =
340                    resolve_oauth_audience(metadata.remove(OAUTH_AUDIENCE_KEY), cluster_id)
341                        .map_err(PsqlError::StartupError)?;
342                validate_jwt(
343                    &String::from_utf8_lossy(password),
344                    &jwks_url,
345                    &issuer,
346                    &audience,
347                    &metadata,
348                )
349                .await
350                .map_err(PsqlError::StartupError)?
351            }
352            UserAuthenticator::Ldap(user_name, hba_entry) => {
353                let ldap_auth = LdapAuthenticator::new(hba_entry)?;
354                // Convert password to string, defaulting to empty if not valid UTF-8
355                let password_str = String::from_utf8_lossy(password).into_owned();
356                ldap_auth.authenticate(user_name, &password_str).await?
357            }
358        };
359        if !success {
360            return Err(PsqlError::PasswordError);
361        }
362        Ok(())
363    }
364}
365
366/// Binds a Tcp or Unix listener at `addr`. Spawn a coroutine to serve every new connection.
367///
368/// Returns when the `shutdown` token is triggered.
369pub async fn pg_serve(
370    addr: &str,
371    tcp_keepalive: TcpKeepalive,
372    session_mgr: Arc<impl SessionManager>,
373    context: ConnectionContext,
374    shutdown: CancellationToken,
375) -> Result<(), BoxedError> {
376    let listener = Listener::bind(addr).await?;
377    tracing::info!(addr, "server started");
378
379    let acceptor_runtime = BackgroundShutdownRuntime::from({
380        let mut builder = tokio::runtime::Builder::new_multi_thread();
381        builder.worker_threads(1);
382        builder
383            .thread_name("rw-acceptor")
384            .enable_all()
385            .build()
386            .unwrap()
387    });
388
389    #[cfg(not(madsim))]
390    let worker_runtime = tokio::runtime::Handle::current();
391    #[cfg(madsim)]
392    let worker_runtime = tokio::runtime::Builder::new_multi_thread().build().unwrap();
393    let session_mgr_clone = session_mgr.clone();
394    let f = async move {
395        loop {
396            let conn_ret = listener.accept(&tcp_keepalive).await;
397            match conn_ret {
398                Ok((stream, peer_addr)) => {
399                    tracing::info!(%peer_addr, "accept connection");
400                    worker_runtime.spawn(handle_connection(
401                        stream,
402                        session_mgr_clone.clone(),
403                        Arc::new(peer_addr),
404                        context.clone(),
405                    ));
406                }
407
408                Err(e) => {
409                    tracing::error!(error = %e.as_report(), "failed to accept connection",);
410                }
411            }
412        }
413    };
414    acceptor_runtime.spawn(f);
415
416    // Wait for the shutdown signal.
417    shutdown.cancelled().await;
418
419    // Stop accepting new connections.
420    drop(acceptor_runtime);
421    // Shutdown session manager, typically close all existing sessions.
422    session_mgr.shutdown().await;
423
424    Ok(())
425}
426
427pub async fn handle_connection<S, SM>(
428    stream: S,
429    session_mgr: Arc<SM>,
430    peer_addr: AddressRef,
431    context: ConnectionContext,
432) where
433    S: PgByteStream,
434    SM: SessionManager,
435{
436    PgProtocol::new(stream, session_mgr, peer_addr, context)
437        .run()
438        .await;
439}
440#[cfg(test)]
441mod tests {
442    use std::sync::{Arc, Mutex};
443    use std::time::{Duration, Instant};
444
445    use bytes::Bytes;
446    use futures::StreamExt;
447    use futures::stream::BoxStream;
448    use risingwave_common::id::DatabaseId;
449    use risingwave_common::types::DataType;
450    use risingwave_common::util::tokio_util::sync::CancellationToken;
451    use risingwave_sqlparser::ast::Statement;
452    use tokio_postgres::NoTls;
453
454    use crate::error::PsqlResult;
455    use crate::memory_manager::MessageMemoryManager;
456    use crate::pg_field_descriptor::PgFieldDescriptor;
457    use crate::pg_message::TransactionStatus;
458    use crate::pg_protocol::ConnectionContext;
459    use crate::pg_response::{PgResponse, RowSetResult, StatementType};
460    use crate::pg_server::{
461        BoxedError, ExecContext, ExecContextGuard, Session, SessionId, SessionManager,
462        UserAuthenticator, pg_serve,
463    };
464    use crate::types;
465    use crate::types::Row;
466
467    struct MockSessionManager {
468        authenticator: UserAuthenticator,
469        session_id: SessionId,
470        cancelled: Arc<Mutex<Vec<SessionId>>>,
471    }
472
473    impl Default for MockSessionManager {
474        fn default() -> Self {
475            Self {
476                authenticator: UserAuthenticator::None,
477                session_id: (0, 0),
478                cancelled: Arc::new(Mutex::new(Vec::new())),
479            }
480        }
481    }
482
483    struct MockSession {
484        authenticator: UserAuthenticator,
485        id: SessionId,
486    }
487
488    const STREAMING_TEST_QUERY: &str = "SELECT 'pgwire_streaming_test'";
489
490    impl SessionManager for MockSessionManager {
491        type Error = BoxedError;
492        type Session = MockSession;
493
494        fn create_dummy_session(
495            &self,
496            _database_id: DatabaseId,
497        ) -> Result<Arc<Self::Session>, Self::Error> {
498            unimplemented!()
499        }
500
501        fn connect(
502            &self,
503            _database: &str,
504            _user_name: &str,
505            _peer_addr: crate::net::AddressRef,
506        ) -> Result<Arc<Self::Session>, Self::Error> {
507            Ok(Arc::new(MockSession {
508                authenticator: self.authenticator.clone(),
509                id: self.session_id,
510            }))
511        }
512
513        fn cancel_queries_in_session(&self, session_id: SessionId) {
514            self.cancelled.lock().unwrap().push(session_id);
515        }
516
517        fn cancel_creating_jobs_in_session(&self, _session_id: SessionId) {}
518
519        fn end_session(&self, _session: &Self::Session) {}
520    }
521
522    impl Session for MockSession {
523        type Error = BoxedError;
524        type Portal = String;
525        type PreparedStatement = String;
526        type ValuesStream = BoxStream<'static, RowSetResult>;
527
528        async fn run_one_query(
529            self: Arc<Self>,
530            _stmt: Statement,
531            _format: types::Format,
532        ) -> Result<PgResponse<BoxStream<'static, RowSetResult>>, Self::Error> {
533            Ok(PgResponse::builder(StatementType::SELECT)
534                .values(
535                    futures::stream::iter(vec![Ok(vec![Row::new(vec![Some(Bytes::new())])])])
536                        .boxed(),
537                    vec![
538                        // 1043 is the oid of varchar type.
539                        // -1 is the type len of varchar type.
540                        PgFieldDescriptor::new("".to_owned(), 1043, -1);
541                        1
542                    ],
543                )
544                .into())
545        }
546
547        async fn parse(
548            self: Arc<Self>,
549            sql: Option<Statement>,
550            _params_types: Vec<Option<DataType>>,
551        ) -> Result<String, Self::Error> {
552            Ok(sql.map(|stmt| stmt.to_string()).unwrap_or_default())
553        }
554
555        fn bind(
556            self: Arc<Self>,
557            prepare_statement: String,
558            _params: Vec<Option<Bytes>>,
559            _param_formats: Vec<types::Format>,
560            _result_formats: Vec<types::Format>,
561        ) -> Result<String, Self::Error> {
562            Ok(prepare_statement)
563        }
564
565        async fn execute(
566            self: Arc<Self>,
567            portal: String,
568        ) -> Result<PgResponse<BoxStream<'static, RowSetResult>>, Self::Error> {
569            if portal == STREAMING_TEST_QUERY {
570                let first_row = futures::stream::once(async {
571                    Ok(vec![Row::new(vec![Some(Bytes::from(vec![
572                        b'x';
573                        128 * 1024
574                    ]))])])
575                });
576                let remaining_rows = futures::stream::pending();
577                return Ok(PgResponse::builder(StatementType::SELECT)
578                    .values(
579                        first_row.chain(remaining_rows).boxed(),
580                        vec![PgFieldDescriptor::new("".to_owned(), 1043, -1)],
581                    )
582                    .into());
583            }
584
585            Ok(PgResponse::builder(StatementType::SELECT)
586                .values(
587                    futures::stream::iter(vec![Ok(vec![Row::new(vec![Some(Bytes::new())])])])
588                        .boxed(),
589                    vec![
590                    // 1043 is the oid of varchar type.
591                    // -1 is the type len of varchar type.
592                    PgFieldDescriptor::new("".to_owned(), 1043, -1);
593                    1
594                ],
595                )
596                .into())
597        }
598
599        fn describe_statement(
600            self: Arc<Self>,
601            _statement: String,
602        ) -> Result<(Vec<DataType>, Vec<PgFieldDescriptor>), Self::Error> {
603            Ok((
604                vec![],
605                vec![PgFieldDescriptor::new("".to_owned(), 1043, -1)],
606            ))
607        }
608
609        fn describe_portal(
610            self: Arc<Self>,
611            _portal: String,
612        ) -> Result<Vec<PgFieldDescriptor>, Self::Error> {
613            Ok(vec![PgFieldDescriptor::new("".to_owned(), 1043, -1)])
614        }
615
616        fn user_authenticator(&self) -> &UserAuthenticator {
617            &self.authenticator
618        }
619
620        fn id(&self) -> SessionId {
621            self.id
622        }
623
624        fn get_config(&self, key: &str) -> Result<String, Self::Error> {
625            match key {
626                "timezone" => Ok("UTC".to_owned()),
627                _ => Err(format!("Unknown config key: {key}").into()),
628            }
629        }
630
631        fn set_config(&self, _key: &str, _value: String) -> Result<String, Self::Error> {
632            Ok("".to_owned())
633        }
634
635        async fn next_notice(self: &Arc<Self>) -> String {
636            std::future::pending().await
637        }
638
639        fn transaction_status(&self) -> TransactionStatus {
640            TransactionStatus::Idle
641        }
642
643        fn init_exec_context(&self, sql: Arc<str>) -> ExecContextGuard {
644            let exec_context = Arc::new(ExecContext {
645                running_sql: sql,
646                last_instant: Instant::now(),
647                last_idle_instant: Default::default(),
648            });
649            ExecContextGuard::new(exec_context)
650        }
651
652        fn check_idle_in_transaction_timeout(&self) -> PsqlResult<()> {
653            Ok(())
654        }
655
656        fn user(&self) -> String {
657            "mock".to_owned()
658        }
659    }
660
661    async fn do_test_query(bind_addr: impl Into<String>, pg_config: impl Into<String>) {
662        let bind_addr = bind_addr.into();
663        let pg_config = pg_config.into();
664
665        let session_mgr = MockSessionManager::default();
666        tokio::spawn(async move {
667            pg_serve(
668                &bind_addr,
669                socket2::TcpKeepalive::new(),
670                Arc::new(session_mgr),
671                ConnectionContext {
672                    tls_config: None,
673                    sql_option_redaction: None,
674                    message_memory_manager: MessageMemoryManager::new(u64::MAX, u64::MAX, u64::MAX)
675                        .into(),
676                    stream_flush_threshold_bytes: 64 * 1024,
677                },
678                CancellationToken::new(), // dummy
679            )
680            .await
681        });
682        // wait for server to start
683        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
684
685        // Connect to the database.
686        let (client, connection) = tokio_postgres::connect(&pg_config, NoTls).await.unwrap();
687
688        // The connection object performs the actual communication with the database,
689        // so spawn it off to run on its own.
690        tokio::spawn(async move {
691            if let Err(e) = connection.await {
692                eprintln!("connection error: {}", e);
693            }
694        });
695
696        let rows = client
697            .simple_query("SELECT ''")
698            .await
699            .expect("Error executing query");
700        // Row + CommandComplete
701        assert_eq!(rows.len(), 2);
702
703        let rows = client
704            .query("SELECT ''", &[])
705            .await
706            .expect("Error executing query");
707        assert_eq!(rows.len(), 1);
708    }
709
710    #[tokio::test]
711    async fn test_cancel_request_after_password_auth() {
712        let session_id = (42, 7);
713        let cancelled = Arc::new(Mutex::new(Vec::new()));
714        let session_mgr = MockSessionManager {
715            authenticator: UserAuthenticator::ClearText(b"pw".to_vec()),
716            session_id,
717            cancelled: cancelled.clone(),
718        };
719
720        tokio::spawn(async move {
721            pg_serve(
722                "127.0.0.1:10002",
723                socket2::TcpKeepalive::new(),
724                Arc::new(session_mgr),
725                ConnectionContext {
726                    tls_config: None,
727                    sql_option_redaction: None,
728                    message_memory_manager: MessageMemoryManager::new(u64::MAX, u64::MAX, u64::MAX)
729                        .into(),
730                    stream_flush_threshold_bytes: 64 * 1024,
731                },
732                CancellationToken::new(), // dummy
733            )
734            .await
735        });
736        // wait for server to start
737        tokio::time::sleep(Duration::from_millis(100)).await;
738
739        let (client, connection) = tokio_postgres::connect(
740            "host=localhost port=10002 user=mock password=pw application_name=cancel_test",
741            NoTls,
742        )
743        .await
744        .unwrap();
745        // Reported in the same `ParameterStatus` burst as `BackendKeyData`, so the
746        // password path must not skip it either.
747        assert_eq!(
748            connection.parameter("application_name"),
749            Some("cancel_test")
750        );
751        tokio::spawn(async move {
752            let _ = connection.await;
753        });
754
755        // The cancel token is built from the `BackendKeyData` the server sent after
756        // `AuthenticationOk`. Without it the client cancels with (0, 0) instead.
757        client.cancel_token().cancel_query(NoTls).await.unwrap();
758
759        for _ in 0..100 {
760            if !cancelled.lock().unwrap().is_empty() {
761                break;
762            }
763            tokio::time::sleep(Duration::from_millis(20)).await;
764        }
765        assert_eq!(cancelled.lock().unwrap().as_slice(), &[session_id]);
766    }
767
768    #[tokio::test]
769    async fn test_query_tcp() {
770        do_test_query("127.0.0.1:10000", "host=localhost port=10000").await;
771    }
772
773    #[cfg(not(madsim))]
774    #[tokio::test]
775    async fn test_query_unix() {
776        let port: i16 = 10000;
777        let dir = tempfile::TempDir::new().unwrap();
778        let sock = dir.path().join(format!(".s.PGSQL.{port}"));
779
780        do_test_query(
781            format!("unix:{}", sock.to_str().unwrap()),
782            format!("host={} port={}", dir.path().to_str().unwrap(), port),
783        )
784        .await;
785    }
786
787    #[cfg(not(madsim))]
788    #[tokio::test]
789    async fn test_large_query_row_is_streamed_before_query_finishes() {
790        let port: i16 = 10001;
791        let dir = tempfile::TempDir::new().unwrap();
792        let sock = dir.path().join(format!(".s.PGSQL.{port}"));
793        let bind_addr = format!("unix:{}", sock.to_str().unwrap());
794        let pg_config = format!("host={} port={port}", dir.path().to_str().unwrap());
795        let cancellation = CancellationToken::new();
796
797        let server_cancellation = cancellation.clone();
798        tokio::spawn(async move {
799            pg_serve(
800                &bind_addr,
801                socket2::TcpKeepalive::new(),
802                Arc::new(MockSessionManager::default()),
803                ConnectionContext {
804                    tls_config: None,
805                    sql_option_redaction: None,
806                    message_memory_manager: MessageMemoryManager::new(u64::MAX, u64::MAX, u64::MAX)
807                        .into(),
808                    stream_flush_threshold_bytes: 64 * 1024,
809                },
810                server_cancellation,
811            )
812            .await
813        });
814        tokio::time::sleep(Duration::from_millis(100)).await;
815
816        let (client, connection) = tokio_postgres::connect(&pg_config, NoTls).await.unwrap();
817        let connection_handle = tokio::spawn(connection);
818        let params: &[&str] = &[];
819        let rows = client
820            .query_raw(STREAMING_TEST_QUERY, params)
821            .await
822            .unwrap();
823        futures::pin_mut!(rows);
824
825        let first_row = tokio::time::timeout(Duration::from_secs(5), rows.next())
826            .await
827            .expect("first row should be sent before the result stream finishes")
828            .unwrap()
829            .unwrap();
830        assert_eq!(first_row.get::<_, &str>(0).len(), 128 * 1024);
831
832        drop(client);
833        cancellation.cancel();
834        connection_handle.abort();
835    }
836
837    mod jwt_validation_tests {
838        use std::collections::HashMap;
839        use std::time::{SystemTime, UNIX_EPOCH};
840
841        use base64::Engine;
842        use jsonwebtoken::{Algorithm, EncodingKey, Header};
843        use openssl::pkey::{Private, Public};
844        use openssl::rsa::Rsa;
845        use serde_json::json;
846
847        use crate::pg_server::{Jwk, Jwks, resolve_oauth_audience, validate_jwt_with_jwks};
848
849        fn create_test_rsa_keys() -> (Rsa<Private>, Rsa<Public>) {
850            let private_key = Rsa::generate(2048).expect("failed to generate a key");
851            let public_key = Rsa::from_public_components(
852                private_key.n().to_owned().unwrap(),
853                private_key.e().to_owned().unwrap(),
854            )
855            .unwrap();
856            (private_key, public_key)
857        }
858
859        fn create_test_jwks(public_key: &Rsa<Public>, kid: &str, alg: Option<&str>) -> Jwks {
860            let n =
861                base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(public_key.n().to_vec());
862            let e =
863                base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(public_key.e().to_vec());
864
865            Jwks {
866                keys: vec![Jwk {
867                    kty: Some("RSA".to_owned()),
868                    kid: Some(kid.to_owned()),
869                    alg: alg.map(ToOwned::to_owned),
870                    n: Some(n),
871                    e: Some(e),
872                }],
873            }
874        }
875
876        fn create_jwt_token(
877            private_key: &Rsa<Private>,
878            kid: &str,
879            algorithm: Algorithm,
880            issuer: &str,
881            audience: Option<&str>,
882            exp: u64,
883            additional_claims: HashMap<String, serde_json::Value>,
884        ) -> String {
885            let mut header = Header::new(algorithm);
886            header.kid = Some(kid.to_owned());
887
888            let mut claims = json!({
889                "iss": issuer,
890                "exp": exp,
891            });
892
893            if let Some(aud) = audience {
894                claims["aud"] = json!(aud);
895            }
896
897            for (key, value) in additional_claims {
898                claims[key] = value;
899            }
900
901            let encoding_key =
902                EncodingKey::from_rsa_pem(&private_key.private_key_to_pem().unwrap()).unwrap();
903
904            jsonwebtoken::encode(&header, &claims, &encoding_key).unwrap()
905        }
906
907        fn get_future_timestamp() -> u64 {
908            SystemTime::now()
909                .duration_since(UNIX_EPOCH)
910                .unwrap()
911                .as_secs()
912                + 3600 // 1 hour from now
913        }
914
915        fn get_past_timestamp() -> u64 {
916            SystemTime::now()
917                .duration_since(UNIX_EPOCH)
918                .unwrap()
919                .as_secs()
920                - 3600 // 1 hour ago
921        }
922
923        #[test]
924        fn test_jwt_with_invalid_audience() {
925            let (private_key, public_key) = create_test_rsa_keys();
926            let jwks = create_test_jwks(&public_key, "test-kid", Some("RS256"));
927
928            let metadata = HashMap::new();
929
930            let jwt = create_jwt_token(
931                &private_key,
932                "test-kid",
933                Algorithm::RS256,
934                "https://test-issuer.com",
935                Some("urn:risingwave:cluster:wrong-cluster-id"),
936                get_future_timestamp(),
937                HashMap::new(),
938            );
939
940            let result = validate_jwt_with_jwks(
941                &jwt,
942                &jwks,
943                "https://test-issuer.com",
944                "urn:risingwave:cluster:test-cluster-id",
945                &metadata,
946            );
947
948            let error = result.unwrap_err();
949            assert!(error.to_string().contains("InvalidAudience"));
950        }
951
952        #[test]
953        fn test_jwt_with_configured_audience() {
954            let (private_key, public_key) = create_test_rsa_keys();
955            let jwks = create_test_jwks(&public_key, "test-kid", Some("RS256"));
956
957            let mut additional_claims = HashMap::new();
958            additional_claims.insert("aud".to_owned(), json!(["urn:sn:cloud:o-for6u"]));
959            let jwt = create_jwt_token(
960                &private_key,
961                "test-kid",
962                Algorithm::RS256,
963                "https://test-issuer.com",
964                None,
965                get_future_timestamp(),
966                additional_claims,
967            );
968
969            let result = validate_jwt_with_jwks(
970                &jwt,
971                &jwks,
972                "https://test-issuer.com",
973                "urn:sn:cloud:o-for6u",
974                &HashMap::new(),
975            );
976
977            assert!(result.unwrap());
978        }
979
980        #[test]
981        fn test_empty_configured_audience() {
982            let error =
983                resolve_oauth_audience(Some("  ".to_owned()), "test-cluster-id").unwrap_err();
984            assert!(error.to_string().contains("cannot be empty"));
985        }
986
987        #[test]
988        fn test_default_audience_from_cluster_id() {
989            let audience = resolve_oauth_audience(None, "test-cluster-id").unwrap();
990            assert_eq!(audience, "urn:risingwave:cluster:test-cluster-id");
991        }
992
993        #[test]
994        fn test_jwt_with_missing_audience() {
995            let (private_key, public_key) = create_test_rsa_keys();
996            let jwks = create_test_jwks(&public_key, "test-kid", Some("RS256"));
997
998            let metadata = HashMap::new();
999
1000            let jwt = create_jwt_token(
1001                &private_key,
1002                "test-kid",
1003                Algorithm::RS256,
1004                "https://test-issuer.com",
1005                None, // No audience claim
1006                get_future_timestamp(),
1007                HashMap::new(),
1008            );
1009
1010            let result = validate_jwt_with_jwks(
1011                &jwt,
1012                &jwks,
1013                "https://test-issuer.com",
1014                "urn:risingwave:cluster:test-cluster-id",
1015                &metadata,
1016            );
1017
1018            let error = result.unwrap_err();
1019            assert!(error.to_string().contains("Missing required claim: aud"));
1020        }
1021
1022        #[test]
1023        fn test_jwt_with_invalid_issuer() {
1024            let (private_key, public_key) = create_test_rsa_keys();
1025            let jwks = create_test_jwks(&public_key, "test-kid", Some("RS256"));
1026
1027            let metadata = HashMap::new();
1028
1029            let jwt = create_jwt_token(
1030                &private_key,
1031                "test-kid",
1032                Algorithm::RS256,
1033                "https://wrong-issuer.com",
1034                Some("urn:risingwave:cluster:test-cluster-id"),
1035                get_future_timestamp(),
1036                HashMap::new(),
1037            );
1038
1039            let result = validate_jwt_with_jwks(
1040                &jwt,
1041                &jwks,
1042                "https://test-issuer.com",
1043                "urn:risingwave:cluster:test-cluster-id",
1044                &metadata,
1045            );
1046
1047            let error = result.unwrap_err();
1048            assert!(error.to_string().contains("InvalidIssuer"));
1049        }
1050
1051        #[test]
1052        fn test_jwt_with_kid_not_found_in_jwks() {
1053            let (private_key, public_key) = create_test_rsa_keys();
1054            let jwks = create_test_jwks(&public_key, "different-kid", Some("RS256"));
1055
1056            let metadata = HashMap::new();
1057
1058            let jwt = create_jwt_token(
1059                &private_key,
1060                "missing-kid",
1061                Algorithm::RS256,
1062                "https://test-issuer.com",
1063                Some("urn:risingwave:cluster:test-cluster-id"),
1064                get_future_timestamp(),
1065                HashMap::new(),
1066            );
1067
1068            let result = validate_jwt_with_jwks(
1069                &jwt,
1070                &jwks,
1071                "https://test-issuer.com",
1072                "urn:risingwave:cluster:test-cluster-id",
1073                &metadata,
1074            );
1075
1076            let error = result.unwrap_err();
1077            assert!(
1078                error
1079                    .to_string()
1080                    .contains("No compatible RSA key found in JWKS for kid: 'missing-kid'")
1081            );
1082        }
1083
1084        #[test]
1085        fn test_jwt_with_empty_jwks_reports_no_matching_key() {
1086            let (private_key, _) = create_test_rsa_keys();
1087            let jwks = Jwks { keys: vec![] };
1088
1089            let jwt = create_jwt_token(
1090                &private_key,
1091                "missing-kid",
1092                Algorithm::RS256,
1093                "https://test-issuer.com",
1094                Some("urn:risingwave:cluster:test-cluster-id"),
1095                get_future_timestamp(),
1096                HashMap::new(),
1097            );
1098
1099            let result = validate_jwt_with_jwks(
1100                &jwt,
1101                &jwks,
1102                "https://test-issuer.com",
1103                "urn:risingwave:cluster:test-cluster-id",
1104                &HashMap::new(),
1105            );
1106
1107            let error = result.unwrap_err();
1108            assert!(
1109                error
1110                    .to_string()
1111                    .contains("No compatible RSA key found in JWKS for kid: 'missing-kid'")
1112            );
1113        }
1114
1115        #[test]
1116        fn test_jwt_with_expired_token() {
1117            let (private_key, public_key) = create_test_rsa_keys();
1118            let jwks = create_test_jwks(&public_key, "test-kid", Some("RS256"));
1119
1120            let metadata = HashMap::new();
1121
1122            let jwt = create_jwt_token(
1123                &private_key,
1124                "test-kid",
1125                Algorithm::RS256,
1126                "https://test-issuer.com",
1127                Some("urn:risingwave:cluster:test-cluster-id"),
1128                get_past_timestamp(), // Expired token
1129                HashMap::new(),
1130            );
1131
1132            let result = validate_jwt_with_jwks(
1133                &jwt,
1134                &jwks,
1135                "https://test-issuer.com",
1136                "urn:risingwave:cluster:test-cluster-id",
1137                &metadata,
1138            );
1139
1140            let error = result.unwrap_err();
1141            assert!(error.to_string().contains("ExpiredSignature"));
1142        }
1143
1144        #[test]
1145        fn test_jwt_with_invalid_signature() {
1146            let (_, public_key) = create_test_rsa_keys();
1147            let (wrong_private_key, _) = create_test_rsa_keys(); // Different key pair
1148            let jwks = create_test_jwks(&public_key, "test-kid", Some("RS256"));
1149
1150            let metadata = HashMap::new();
1151
1152            // Sign with wrong private key
1153            let jwt = create_jwt_token(
1154                &wrong_private_key,
1155                "test-kid",
1156                Algorithm::RS256,
1157                "https://test-issuer.com",
1158                Some("urn:risingwave:cluster:test-cluster-id"),
1159                get_future_timestamp(),
1160                HashMap::new(),
1161            );
1162
1163            let result = validate_jwt_with_jwks(
1164                &jwt,
1165                &jwks,
1166                "https://test-issuer.com",
1167                "urn:risingwave:cluster:test-cluster-id",
1168                &metadata,
1169            );
1170
1171            let error = result.unwrap_err();
1172            assert!(error.to_string().contains("InvalidSignature"));
1173        }
1174
1175        #[test]
1176        fn test_metadata_validation_success() {
1177            let (private_key, public_key) = create_test_rsa_keys();
1178            let jwks = create_test_jwks(&public_key, "test-kid", Some("RS256"));
1179
1180            let mut metadata = HashMap::new();
1181            metadata.insert("role".to_owned(), "admin".to_owned());
1182            metadata.insert("department".to_owned(), "security".to_owned());
1183
1184            let mut claims = HashMap::new();
1185            claims.insert("role".to_owned(), json!("admin"));
1186            claims.insert("department".to_owned(), json!("security"));
1187            claims.insert("extra_claim".to_owned(), json!("ignored")); // Extra claims are fine
1188
1189            let jwt = create_jwt_token(
1190                &private_key,
1191                "test-kid",
1192                Algorithm::RS256,
1193                "https://test-issuer.com",
1194                Some("urn:risingwave:cluster:test-cluster-id"),
1195                get_future_timestamp(),
1196                claims,
1197            );
1198
1199            let result = validate_jwt_with_jwks(
1200                &jwt,
1201                &jwks,
1202                "https://test-issuer.com",
1203                "urn:risingwave:cluster:test-cluster-id",
1204                &metadata,
1205            );
1206
1207            assert!(result.unwrap());
1208        }
1209
1210        #[test]
1211        fn test_metadata_validation_failure() {
1212            let (private_key, public_key) = create_test_rsa_keys();
1213            let jwks = create_test_jwks(&public_key, "test-kid", Some("RS256"));
1214
1215            let mut metadata = HashMap::new();
1216            metadata.insert("role".to_owned(), "admin".to_owned());
1217            metadata.insert("department".to_owned(), "security".to_owned());
1218
1219            let mut claims = HashMap::new();
1220            claims.insert("role".to_owned(), json!("user")); // Wrong role
1221            claims.insert("department".to_owned(), json!("security"));
1222
1223            let jwt = create_jwt_token(
1224                &private_key,
1225                "test-kid",
1226                Algorithm::RS256,
1227                "https://test-issuer.com",
1228                Some("urn:risingwave:cluster:test-cluster-id"),
1229                get_future_timestamp(),
1230                claims,
1231            );
1232
1233            let result = validate_jwt_with_jwks(
1234                &jwt,
1235                &jwks,
1236                "https://test-issuer.com",
1237                "urn:risingwave:cluster:test-cluster-id",
1238                &metadata,
1239            );
1240
1241            let error = result.unwrap_err();
1242            assert_eq!(
1243                error.to_string(),
1244                "metadata in jwt does not match with metadata declared with user"
1245            );
1246        }
1247
1248        #[test]
1249        fn test_jwt_with_jwk_missing_alg_succeeds() {
1250            let (private_key, public_key) = create_test_rsa_keys();
1251            let jwks = create_test_jwks(&public_key, "test-kid", None);
1252
1253            let jwt = create_jwt_token(
1254                &private_key,
1255                "test-kid",
1256                Algorithm::RS256,
1257                "https://test-issuer.com",
1258                Some("urn:risingwave:cluster:test-cluster-id"),
1259                get_future_timestamp(),
1260                HashMap::new(),
1261            );
1262
1263            let result = validate_jwt_with_jwks(
1264                &jwt,
1265                &jwks,
1266                "https://test-issuer.com",
1267                "urn:risingwave:cluster:test-cluster-id",
1268                &HashMap::new(),
1269            );
1270
1271            assert!(result.unwrap());
1272        }
1273
1274        #[test]
1275        fn test_jwt_with_mixed_jwks_ignores_non_matching_ec_key() {
1276            let (private_key, public_key) = create_test_rsa_keys();
1277            let mut jwks = create_test_jwks(&public_key, "rsa-kid", Some("RS256"));
1278            jwks.keys.push(Jwk {
1279                kty: Some("EC".to_owned()),
1280                kid: Some("ec-kid".to_owned()),
1281                alg: Some("ES256".to_owned()),
1282                n: None,
1283                e: None,
1284            });
1285
1286            let jwt = create_jwt_token(
1287                &private_key,
1288                "rsa-kid",
1289                Algorithm::RS256,
1290                "https://test-issuer.com",
1291                Some("urn:risingwave:cluster:test-cluster-id"),
1292                get_future_timestamp(),
1293                HashMap::new(),
1294            );
1295
1296            let result = validate_jwt_with_jwks(
1297                &jwt,
1298                &jwks,
1299                "https://test-issuer.com",
1300                "urn:risingwave:cluster:test-cluster-id",
1301                &HashMap::new(),
1302            );
1303
1304            assert!(result.unwrap());
1305        }
1306
1307        #[test]
1308        fn test_jwks_deserializes_ec_key_without_kid() {
1309            let jwks: Jwks = serde_json::from_value(json!({
1310                "keys": [
1311                    {
1312                        "alg": "ES256",
1313                        "kty": "EC",
1314                        "crv": "P-256",
1315                        "x": "x-coordinate",
1316                        "y": "y-coordinate"
1317                    },
1318                    {
1319                        "kid": "rsa-kid",
1320                        "alg": "RS256",
1321                        "kty": "RSA",
1322                        "n": "modulus",
1323                        "e": "AQAB"
1324                    }
1325                ]
1326            }))
1327            .unwrap();
1328
1329            assert_eq!(jwks.keys.len(), 2);
1330            assert!(jwks.keys[0].kid.is_none());
1331            assert_eq!(jwks.keys[1].kid.as_deref(), Some("rsa-kid"));
1332            assert_eq!(jwks.keys[1].n.as_deref(), Some("modulus"));
1333        }
1334
1335        #[test]
1336        fn test_jwt_uses_compatible_rsa_key_when_ec_key_has_same_kid() {
1337            let (private_key, public_key) = create_test_rsa_keys();
1338            let mut jwks = create_test_jwks(&public_key, "shared-kid", Some("RS256"));
1339            jwks.keys.insert(
1340                0,
1341                Jwk {
1342                    kty: Some("EC".to_owned()),
1343                    kid: Some("shared-kid".to_owned()),
1344                    alg: Some("ES256".to_owned()),
1345                    n: None,
1346                    e: None,
1347                },
1348            );
1349
1350            let jwt = create_jwt_token(
1351                &private_key,
1352                "shared-kid",
1353                Algorithm::RS256,
1354                "https://test-issuer.com",
1355                Some("urn:risingwave:cluster:test-cluster-id"),
1356                get_future_timestamp(),
1357                HashMap::new(),
1358            );
1359
1360            let result = validate_jwt_with_jwks(
1361                &jwt,
1362                &jwks,
1363                "https://test-issuer.com",
1364                "urn:risingwave:cluster:test-cluster-id",
1365                &HashMap::new(),
1366            );
1367
1368            assert!(result.unwrap());
1369        }
1370
1371        #[test]
1372        fn test_jwt_with_jwk_missing_alg_rejects_disallowed_header_alg() {
1373            let (_, public_key) = create_test_rsa_keys();
1374            let jwks = create_test_jwks(&public_key, "test-kid", None);
1375
1376            // Craft a token whose header claims HS256. The allow-list check
1377            // must reject it before the signature is ever verified — this is
1378            // the defence against the classic "alg=HS256 forged with the RSA
1379            // public key as the HMAC secret" confusion attack.
1380            let mut header = Header::new(Algorithm::HS256);
1381            header.kid = Some("test-kid".to_owned());
1382            let claims = json!({
1383                "iss": "https://test-issuer.com",
1384                "aud": "urn:risingwave:cluster:test-cluster-id",
1385                "exp": get_future_timestamp(),
1386            });
1387            let jwt = jsonwebtoken::encode(
1388                &header,
1389                &claims,
1390                &EncodingKey::from_secret(b"attacker-chosen"),
1391            )
1392            .unwrap();
1393
1394            let result = validate_jwt_with_jwks(
1395                &jwt,
1396                &jwks,
1397                "https://test-issuer.com",
1398                "urn:risingwave:cluster:test-cluster-id",
1399                &HashMap::new(),
1400            );
1401
1402            let error = result.unwrap_err();
1403            assert!(
1404                error.to_string().contains("is not allowed"),
1405                "unexpected error: {}",
1406                error
1407            );
1408        }
1409
1410        #[test]
1411        fn test_jwt_alg_mismatch_between_header_and_jwk() {
1412            let (private_key, public_key) = create_test_rsa_keys();
1413            // JWK pins RS384; token header declares RS256 — must be rejected.
1414            let jwks = create_test_jwks(&public_key, "test-kid", Some("RS384"));
1415
1416            let jwt = create_jwt_token(
1417                &private_key,
1418                "test-kid",
1419                Algorithm::RS256,
1420                "https://test-issuer.com",
1421                Some("urn:risingwave:cluster:test-cluster-id"),
1422                get_future_timestamp(),
1423                HashMap::new(),
1424            );
1425
1426            let result = validate_jwt_with_jwks(
1427                &jwt,
1428                &jwks,
1429                "https://test-issuer.com",
1430                "urn:risingwave:cluster:test-cluster-id",
1431                &HashMap::new(),
1432            );
1433
1434            let error = result.unwrap_err();
1435            assert_eq!(
1436                error.to_string(),
1437                "No compatible RSA key found in JWKS for kid: 'test-kid'"
1438            );
1439        }
1440    }
1441}