1use std::fmt::Debug;
16use std::sync::Arc;
17use std::sync::atomic::Ordering;
18
19use ::auth::{
20 BEARER_TOKEN_USER, Identity, Password, PgAuthInfo, PgScramSha256Verifier, UserInfoRef,
21 UserProviderRef, userinfo_by_name,
22};
23use async_trait::async_trait;
24use common_catalog::parse_catalog_and_schema_from_db_string;
25use common_error::ext::ErrorExt;
26use common_error::status_code::StatusCode;
27use common_telemetry::{debug, error, warn};
28use common_time::Timezone;
29use futures::{Sink, SinkExt};
30use pgwire::api::auth::StartupHandler;
31use pgwire::api::auth::cleartext::CleartextPasswordAuth;
32use pgwire::api::auth::mechanism::AuthMechanismFactory;
33use pgwire::api::auth::sasl::scram::{ScramAuth, ScramSecret};
34use pgwire::api::auth::{AuthOutcome, AuthSource, LoginInfo as WireLoginInfo};
35use pgwire::api::{ClientInfo, PidSecretKeyGenerator, auth};
36use pgwire::error::{ErrorInfo, PgWireError, PgWireResult};
37use pgwire::messages::response::ErrorResponse;
38use pgwire::messages::startup::SecretKey;
39use pgwire::messages::{PgWireBackendMessage, PgWireFrontendMessage};
40use session::Session;
41use snafu::IntoError;
42
43use crate::error::{AuthSnafu, Result};
44use crate::metrics::METRIC_AUTH_FAILURE;
45use crate::postgres::PostgresServerHandlerInner;
46use crate::postgres::types::PgErrorCode;
47use crate::postgres::utils::convert_err;
48use crate::query_handler::sql::ServerSqlQueryHandlerRef;
49
50pub(crate) struct ZeroPidSecretKeyGenerator;
53
54impl PidSecretKeyGenerator for ZeroPidSecretKeyGenerator {
55 fn generate(&self, _client: &dyn ClientInfo) -> (i32, SecretKey) {
56 (0, SecretKey::I32(0))
57 }
58}
59
60fn record_auth_failure(status_code: StatusCode) {
61 METRIC_AUTH_FAILURE
62 .with_label_values(&[status_code.as_ref()])
63 .inc();
64}
65
66pub(crate) struct PgUserProviderSource {
76 user_provider: UserProviderRef,
77}
78
79impl Debug for PgUserProviderSource {
80 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
81 f.debug_struct("PgUserProviderSource")
82 .finish_non_exhaustive()
83 }
84}
85
86impl PgUserProviderSource {
87 pub(crate) fn new(user_provider: UserProviderRef) -> Self {
88 Self { user_provider }
89 }
90
91 pub(crate) async fn authorize_database(
98 &self,
99 catalog: &str,
100 schema: &str,
101 user_info: &UserInfoRef,
102 ) -> PgWireResult<()> {
103 match self
104 .user_provider
105 .authorize(catalog, schema, user_info)
106 .await
107 {
108 Err(e) => {
109 record_auth_failure(e.status_code());
110 if e.status_code().should_log_error() {
111 error!(e; user = user_info.username(), protocol = "postgres", catalog = %catalog,
112 schema = %schema, reason = %e.status_code(), "COPY target authorization failed");
113 } else {
114 warn!(user = user_info.username(), protocol = "postgres", catalog = %catalog,
115 schema = %schema, reason = %e.status_code(), "COPY target authorization denied");
116 }
117 Err(convert_err(AuthSnafu.into_error(e)))
118 }
119 Ok(()) => Ok(()),
120 }
121 }
122
123 fn resolve(login: &WireLoginInfo<'_>) -> Option<(String, String, String)> {
126 let user = login.user()?.to_string();
127 let (catalog, schema) = parse_catalog_and_schema_from_db_string(login.database()?);
128 Some((user, catalog, schema))
129 }
130
131 async fn postgres_auth_info(&self, login: &WireLoginInfo<'_>) -> Result<PgAuthInfo> {
135 let Some((user, catalog, _)) = Self::resolve(login) else {
136 return Ok(PgAuthInfo::Cleartext);
137 };
138
139 match self
140 .user_provider
141 .postgres_auth_info(Identity::UserId(&user, None), &catalog)
142 .await
143 {
144 Err(e) => {
145 record_auth_failure(e.status_code());
146 Err(AuthSnafu.into_error(e))
147 }
148 Ok(auth_info) => Ok(auth_info),
149 }
150 }
151
152 async fn authorize(
156 &self,
157 login: &WireLoginInfo<'_>,
158 user_info: &UserInfoRef,
159 ) -> PgWireResult<()> {
160 let Some((_, catalog, schema)) = Self::resolve(login) else {
161 return Err(PgWireError::UserNameRequired);
162 };
163
164 match self
165 .user_provider
166 .authorize(&catalog, &schema, user_info)
167 .await
168 {
169 Err(e) => {
170 record_auth_failure(e.status_code());
171 if e.status_code().should_log_error() {
172 error!(e; user = user_info.username(), protocol = "postgres", catalog = %catalog,
173 schema = %schema, client_addr = login.host(), reason = %e.status_code(), "Startup database authorization failed");
174 } else {
175 warn!(user = user_info.username(), protocol = "postgres", catalog = %catalog,
176 schema = %schema, client_addr = login.host(), reason = %e.status_code(), "Startup database authorization denied");
177 }
178 Err(PgWireError::ApiError(Box::new(AuthSnafu.into_error(e))))
179 }
180 Ok(()) => Ok(()),
181 }
182 }
183}
184
185#[async_trait]
186impl AuthSource<UserInfoRef> for PgUserProviderSource {
187 async fn get_password(
188 &self,
189 _login: &WireLoginInfo,
190 ) -> PgWireResult<pgwire::api::auth::Password> {
191 Err(PgWireError::ApiError(
192 "no cleartext password available from the user provider".into(),
193 ))
194 }
195
196 async fn verify_password(
199 &self,
200 login: &WireLoginInfo,
201 presented_password: &[u8],
202 ) -> PgWireResult<Option<UserInfoRef>> {
203 let Some((user, catalog, _schema)) = Self::resolve(login) else {
204 return Err(PgWireError::UserNameRequired);
205 };
206 let password = String::from_utf8_lossy(presented_password).into_owned();
207
208 let result = if user == BEARER_TOKEN_USER {
209 self.user_provider
210 .authenticate_bearer_token(&password, &catalog)
211 .await
212 } else {
213 self.user_provider
214 .authenticate(
215 Identity::UserId(&user, None),
216 Password::PlainText(password.into()),
217 )
218 .await
219 };
220 match result {
221 Err(e) => {
222 record_auth_failure(e.status_code());
223 Err(PgWireError::ApiError(Box::new(AuthSnafu.into_error(e))))
224 }
225 Ok(user_info) => Ok(Some(user_info)),
226 }
227 }
228
229 async fn get_scram_secret(
230 &self,
231 login: &WireLoginInfo,
232 ) -> PgWireResult<(ScramSecret, Option<UserInfoRef>)> {
233 match self.postgres_auth_info(login).await {
234 Ok(PgAuthInfo::ScramSha256 {
238 verifier,
239 user_info,
240 }) => Ok((to_scram_secret(&verifier), user_info)),
241 _ => {
244 let user = login.user().unwrap_or_default();
245 Ok((
246 to_scram_secret(&PgScramSha256Verifier::mock_for_unknown_user(
247 user.as_bytes(),
248 )),
249 None,
250 ))
251 }
252 }
253 }
254}
255
256fn to_scram_secret(verifier: &PgScramSha256Verifier) -> ScramSecret {
257 ScramSecret::Verifier {
258 salt: verifier.salt().to_vec(),
259 iterations: verifier.iterations() as usize,
260 stored_key: verifier.stored_key().to_vec(),
261 server_key: verifier.server_key().to_vec(),
262 }
263}
264
265fn set_client_info<C>(client: &mut C, session: &Session)
266where
267 C: ClientInfo,
268{
269 if let Some(current_catalog) = client.metadata().get(super::METADATA_CATALOG) {
270 session.set_catalog(current_catalog.clone());
271 }
272 if let Some(current_schema) = client.metadata().get(super::METADATA_SCHEMA) {
273 session.set_schema(current_schema.clone());
274 }
275 debug!(user = session.user_info().username(), protocol = "postgres",
276 catalog = %session.catalog(), schema = %session.schema(),
277 client_addr = ?session.conn_info().client_addr, "Handshake database selected");
278}
279
280enum MechanismSelection {
281 NoAuth,
283 Cleartext(Arc<PgUserProviderSource>),
284 Scram(Arc<PgUserProviderSource>),
285 Failed,
287}
288
289impl PostgresServerHandlerInner {
290 async fn select_mechanism<C>(&self, client: &C) -> MechanismSelection
291 where
292 C: ClientInfo + Sync,
293 {
294 let Some(source) = self.auth_source.clone() else {
295 return MechanismSelection::NoAuth;
296 };
297 let login = WireLoginInfo::from_client_info(client);
298 if login.user() == Some(BEARER_TOKEN_USER) {
299 return MechanismSelection::Cleartext(source);
300 }
301 match source.postgres_auth_info(&login).await {
302 Err(_) => MechanismSelection::Failed,
303 Ok(PgAuthInfo::Cleartext) => MechanismSelection::Cleartext(source),
304 Ok(PgAuthInfo::ScramSha256 { .. }) => MechanismSelection::Scram(source),
305 }
306 }
307}
308
309#[async_trait]
310impl StartupHandler for PostgresServerHandlerInner {
311 async fn on_startup<C>(
312 &self,
313 client: &mut C,
314 message: PgWireFrontendMessage,
315 ) -> PgWireResult<()>
316 where
317 C: ClientInfo + Sink<PgWireBackendMessage> + Unpin + Send + Sync,
318 C::Error: Debug,
319 PgWireError: From<<C as Sink<PgWireBackendMessage>>::Error>,
320 {
321 match message {
322 PgWireFrontendMessage::Startup(ref startup) => {
323 if !client.is_secure() && self.force_tls {
325 send_error(
326 client,
327 PgErrorCode::Ec28000.to_err_info("No encryption".to_string()),
328 )
329 .await?;
330 return Ok(());
331 }
332
333 auth::protocol_negotiation(client, startup).await?;
334 auth::save_startup_parameters_to_metadata(client, startup);
335
336 let Some(db) = client.metadata().get(super::METADATA_DATABASE) else {
337 send_error(
338 client,
339 PgErrorCode::Ec3D000.to_err_info("Database not specified".to_owned()),
340 )
341 .await?;
342 return Ok(());
343 };
344 let (catalog, schema) = parse_catalog_and_schema_from_db_string(db);
345 let metadata = client.metadata_mut();
346 let _ = metadata.insert(super::METADATA_CATALOG.to_owned(), catalog);
347 let _ = metadata.insert(super::METADATA_SCHEMA.to_owned(), schema);
348
349 if let Some(tz) = client.metadata().get("TimeZone") {
351 match Timezone::from_tz_string(tz) {
352 Ok(tz) => self.session.set_timezone(tz),
353 Err(_) => {
354 send_error(
355 client,
356 PgErrorCode::Ec22023
357 .to_err_info(format!("Invalid TimeZone: {}", tz)),
358 )
359 .await?;
360
361 return Ok(());
362 }
363 }
364 }
365
366 match self.select_mechanism(client).await {
367 MechanismSelection::NoAuth => {
368 if !check_database_exists(client, &self.query_handler).await? {
369 return Ok(());
370 }
371 self.session.set_user_info(userinfo_by_name(
372 client.metadata().get(super::METADATA_USER).cloned(),
373 ));
374 set_client_info(client, &self.session);
375 self.auth_driver
376 .complete_authentication(client, None)
377 .await?;
378 }
379 MechanismSelection::Cleartext(source) => {
380 if self
381 .auth_driver
382 .begin_authentication(
383 client,
384 CleartextPasswordAuth::new(source).create(),
385 )
386 .await
387 .is_err()
388 {
389 return send_password_authentication_failed(client).await;
390 }
391 }
392 MechanismSelection::Scram(source) => {
393 self.is_scram_auth.store(true, Ordering::Relaxed);
394 if self
395 .auth_driver
396 .begin_authentication(client, ScramAuth::new(source).create())
397 .await
398 .is_err()
399 {
400 return send_password_authentication_failed(client).await;
401 }
402 }
403 MechanismSelection::Failed => {
404 return send_password_authentication_failed(client).await;
405 }
406 }
407 }
408 PgWireFrontendMessage::PasswordMessageFamily(pwd) => {
409 match self.auth_driver.advance_authentication(client, pwd).await {
410 Ok(AuthOutcome::InProgress) => {}
411 Ok(AuthOutcome::Authenticated {
412 identity,
413 final_message,
414 }) => {
415 self.is_scram_auth.store(false, Ordering::Relaxed);
416 let Some(user_info) = identity else {
417 return send_password_authentication_failed(client).await;
418 };
419
420 let authorized = {
425 let login = WireLoginInfo::from_client_info(client);
426 match &self.auth_source {
427 Some(source) => source.authorize(&login, &user_info).await.is_ok(),
428 None => false,
429 }
430 };
431 if !authorized {
432 return send_password_authentication_failed(client).await;
433 }
434
435 if !check_database_exists(client, &self.query_handler).await? {
436 return Ok(());
437 }
438 self.session.set_user_info(user_info);
439 set_client_info(client, &self.session);
440 self.auth_driver
441 .complete_authentication(client, final_message)
442 .await?;
443 }
444 Err(_e) => {
445 if self.is_scram_auth.swap(false, Ordering::Relaxed) {
449 record_auth_failure(StatusCode::UserPasswordMismatch);
450 }
451 return send_password_authentication_failed(client).await;
452 }
453 }
454 }
455 _ => {}
456 }
457 Ok(())
458 }
459}
460
461async fn send_error<C>(client: &mut C, err_info: ErrorInfo) -> PgWireResult<()>
462where
463 C: ClientInfo + Sink<PgWireBackendMessage> + Unpin + Send,
464 C::Error: Debug,
465 PgWireError: From<<C as Sink<PgWireBackendMessage>>::Error>,
466{
467 let error = ErrorResponse::from(err_info);
468 client
469 .feed(PgWireBackendMessage::ErrorResponse(error))
470 .await?;
471 client.close().await?;
472 Ok(())
473}
474
475async fn send_password_authentication_failed<C>(client: &mut C) -> PgWireResult<()>
476where
477 C: ClientInfo + Sink<PgWireBackendMessage> + Unpin + Send,
478 C::Error: Debug,
479 PgWireError: From<<C as Sink<PgWireBackendMessage>>::Error>,
480{
481 send_error(
482 client,
483 PgErrorCode::Ec28P01.to_err_info("password authentication failed".to_string()),
484 )
485 .await
486}
487
488async fn check_database_exists<C>(
489 client: &mut C,
490 query_handler: &ServerSqlQueryHandlerRef,
491) -> PgWireResult<bool>
492where
493 C: ClientInfo + Sink<PgWireBackendMessage> + Unpin + Send,
494 C::Error: Debug,
495 PgWireError: From<<C as Sink<PgWireBackendMessage>>::Error>,
496{
497 let db = client.metadata().get(super::METADATA_DATABASE);
498 let error = if let Some(db) = db {
499 let (catalog, schema) = parse_catalog_and_schema_from_db_string(db);
500 match query_handler.is_valid_schema(&catalog, &schema).await {
501 Ok(true) => return Ok(true),
502 Ok(false) => {}
503 Err(error) => {
504 let mut error_info: ErrorInfo = convert_err(error).into();
505 error_info.severity = "FATAL".to_string();
506 send_error(client, error_info).await?;
507 return Ok(false);
508 }
509 }
510 debug!(protocol = "postgres", user = ?client.metadata().get(super::METADATA_USER),
511 catalog = %catalog, schema = %schema, reason = "schema_not_found",
512 "Startup database validation failed");
513 format!("Database not found: {db}")
514 } else {
515 "Database not specified".to_owned()
516 };
517 send_error(client, PgErrorCode::Ec3D000.to_err_info(error)).await?;
518 Ok(false)
519}
520
521#[cfg(test)]
522mod tests {
523 use super::*;
524
525 #[tokio::test]
526 async fn test_authorize_database() {
527 let source = PgUserProviderSource::new(Arc::new(::auth::tests::MockUserProvider {
528 catalog: "greptime".to_string(),
529 schema: "allowed".to_string(),
530 username: "greptime".to_string(),
531 }));
532 let user = userinfo_by_name(Some("greptime".to_string()));
533 source
534 .authorize_database("greptime", "allowed", &user)
535 .await
536 .unwrap();
537 for (catalog, schema) in [("greptime", "denied"), ("other", "allowed")] {
538 assert!(
539 source
540 .authorize_database(catalog, schema, &user)
541 .await
542 .is_err()
543 );
544 }
545 }
546}