LCOV - code coverage report
Current view: top level - proxy/src/auth - flow.rs (source / functions) Coverage Total Hit
Test: 691a4c28fe7169edd60b367c52d448a0a6605f1f.info Lines: 92.6 % 108 100
Test Date: 2024-05-10 13:18:37 Functions: 39.7 % 58 23

            Line data    Source code
       1              : //! Main authentication flow.
       2              : 
       3              : use super::{backend::ComputeCredentialKeys, AuthErrorImpl, PasswordHackPayload};
       4              : use crate::{
       5              :     config::TlsServerEndPoint,
       6              :     console::AuthSecret,
       7              :     context::RequestMonitoring,
       8              :     sasl, scram,
       9              :     stream::{PqStream, Stream},
      10              : };
      11              : use postgres_protocol::authentication::sasl::{SCRAM_SHA_256, SCRAM_SHA_256_PLUS};
      12              : use pq_proto::{BeAuthenticationSaslMessage, BeMessage, BeMessage as Be};
      13              : use std::io;
      14              : use tokio::io::{AsyncRead, AsyncWrite};
      15              : use tracing::info;
      16              : 
      17              : /// Every authentication selector is supposed to implement this trait.
      18              : pub trait AuthMethod {
      19              :     /// Any authentication selector should provide initial backend message
      20              :     /// containing auth method name and parameters, e.g. md5 salt.
      21              :     fn first_message(&self, channel_binding: bool) -> BeMessage<'_>;
      22              : }
      23              : 
      24              : /// Initial state of [`AuthFlow`].
      25              : pub struct Begin;
      26              : 
      27              : /// Use [SCRAM](crate::scram)-based auth in [`AuthFlow`].
      28              : pub struct Scram<'a>(pub &'a scram::ServerSecret, pub &'a mut RequestMonitoring);
      29              : 
      30              : impl AuthMethod for Scram<'_> {
      31              :     #[inline(always)]
      32           26 :     fn first_message(&self, channel_binding: bool) -> BeMessage<'_> {
      33           26 :         if channel_binding {
      34           24 :             Be::AuthenticationSasl(BeAuthenticationSaslMessage::Methods(scram::METHODS))
      35              :         } else {
      36            2 :             Be::AuthenticationSasl(BeAuthenticationSaslMessage::Methods(
      37            2 :                 scram::METHODS_WITHOUT_PLUS,
      38            2 :             ))
      39              :         }
      40           26 :     }
      41              : }
      42              : 
      43              : /// Use an ad hoc auth flow (for clients which don't support SNI) proposed in
      44              : /// <https://github.com/neondatabase/cloud/issues/1620#issuecomment-1165332290>.
      45              : pub struct PasswordHack;
      46              : 
      47              : impl AuthMethod for PasswordHack {
      48              :     #[inline(always)]
      49            2 :     fn first_message(&self, _channel_binding: bool) -> BeMessage<'_> {
      50            2 :         Be::AuthenticationCleartextPassword
      51            2 :     }
      52              : }
      53              : 
      54              : /// Use clear-text password auth called `password` in docs
      55              : /// <https://www.postgresql.org/docs/current/auth-password.html>
      56              : pub struct CleartextPassword(pub AuthSecret);
      57              : 
      58              : impl AuthMethod for CleartextPassword {
      59              :     #[inline(always)]
      60            2 :     fn first_message(&self, _channel_binding: bool) -> BeMessage<'_> {
      61            2 :         Be::AuthenticationCleartextPassword
      62            2 :     }
      63              : }
      64              : 
      65              : /// This wrapper for [`PqStream`] performs client authentication.
      66              : #[must_use]
      67              : pub struct AuthFlow<'a, S, State> {
      68              :     /// The underlying stream which implements libpq's protocol.
      69              :     stream: &'a mut PqStream<Stream<S>>,
      70              :     /// State might contain ancillary data (see [`Self::begin`]).
      71              :     state: State,
      72              :     tls_server_end_point: TlsServerEndPoint,
      73              : }
      74              : 
      75              : /// Initial state of the stream wrapper.
      76              : impl<'a, S: AsyncRead + AsyncWrite + Unpin> AuthFlow<'a, S, Begin> {
      77              :     /// Create a new wrapper for client authentication.
      78           30 :     pub fn new(stream: &'a mut PqStream<Stream<S>>) -> Self {
      79           30 :         let tls_server_end_point = stream.get_ref().tls_server_end_point();
      80           30 : 
      81           30 :         Self {
      82           30 :             stream,
      83           30 :             state: Begin,
      84           30 :             tls_server_end_point,
      85           30 :         }
      86           30 :     }
      87              : 
      88              :     /// Move to the next step by sending auth method's name & params to client.
      89           30 :     pub async fn begin<M: AuthMethod>(self, method: M) -> io::Result<AuthFlow<'a, S, M>> {
      90           30 :         self.stream
      91           30 :             .write_message(&method.first_message(self.tls_server_end_point.supported()))
      92            0 :             .await?;
      93              : 
      94           30 :         Ok(AuthFlow {
      95           30 :             stream: self.stream,
      96           30 :             state: method,
      97           30 :             tls_server_end_point: self.tls_server_end_point,
      98           30 :         })
      99           30 :     }
     100              : }
     101              : 
     102              : impl<S: AsyncRead + AsyncWrite + Unpin> AuthFlow<'_, S, PasswordHack> {
     103              :     /// Perform user authentication. Raise an error in case authentication failed.
     104            2 :     pub async fn get_password(self) -> super::Result<PasswordHackPayload> {
     105            2 :         let msg = self.stream.read_password_message().await?;
     106            2 :         let password = msg
     107            2 :             .strip_suffix(&[0])
     108            2 :             .ok_or(AuthErrorImpl::MalformedPassword("missing terminator"))?;
     109              : 
     110            2 :         let payload = PasswordHackPayload::parse(password)
     111            2 :             // If we ended up here and the payload is malformed, it means that
     112            2 :             // the user neither enabled SNI nor resorted to any other method
     113            2 :             // for passing the project name we rely on. We should show them
     114            2 :             // the most helpful error message and point to the documentation.
     115            2 :             .ok_or(AuthErrorImpl::MissingEndpointName)?;
     116              : 
     117            2 :         Ok(payload)
     118            2 :     }
     119              : }
     120              : 
     121              : impl<S: AsyncRead + AsyncWrite + Unpin> AuthFlow<'_, S, CleartextPassword> {
     122              :     /// Perform user authentication. Raise an error in case authentication failed.
     123            2 :     pub async fn authenticate(self) -> super::Result<sasl::Outcome<ComputeCredentialKeys>> {
     124            2 :         let msg = self.stream.read_password_message().await?;
     125            2 :         let password = msg
     126            2 :             .strip_suffix(&[0])
     127            2 :             .ok_or(AuthErrorImpl::MalformedPassword("missing terminator"))?;
     128              : 
     129            6 :         let outcome = validate_password_and_exchange(password, self.state.0).await?;
     130              : 
     131            2 :         if let sasl::Outcome::Success(_) = &outcome {
     132            2 :             self.stream.write_message_noflush(&Be::AuthenticationOk)?;
     133            0 :         }
     134              : 
     135            2 :         Ok(outcome)
     136            2 :     }
     137              : }
     138              : 
     139              : /// Stream wrapper for handling [SCRAM](crate::scram) auth.
     140              : impl<S: AsyncRead + AsyncWrite + Unpin> AuthFlow<'_, S, Scram<'_>> {
     141              :     /// Perform user authentication. Raise an error in case authentication failed.
     142           26 :     pub async fn authenticate(self) -> super::Result<sasl::Outcome<scram::ScramKey>> {
     143           26 :         let Scram(secret, ctx) = self.state;
     144           26 : 
     145           26 :         // pause the timer while we communicate with the client
     146           26 :         let _paused = ctx.latency_timer.pause(crate::metrics::Waiting::Client);
     147              : 
     148              :         // Initial client message contains the chosen auth method's name.
     149           26 :         let msg = self.stream.read_password_message().await?;
     150           24 :         let sasl = sasl::FirstMessage::parse(&msg)
     151           24 :             .ok_or(AuthErrorImpl::MalformedPassword("bad sasl message"))?;
     152              : 
     153              :         // Currently, the only supported SASL method is SCRAM.
     154           24 :         if !scram::METHODS.contains(&sasl.method) {
     155            0 :             return Err(super::AuthError::bad_auth_method(sasl.method));
     156           24 :         }
     157           24 : 
     158           24 :         match sasl.method {
     159           24 :             SCRAM_SHA_256 => ctx.auth_method = Some(crate::context::AuthMethod::ScramSha256),
     160           12 :             SCRAM_SHA_256_PLUS => {
     161           12 :                 ctx.auth_method = Some(crate::context::AuthMethod::ScramSha256Plus)
     162              :             }
     163            0 :             _ => {}
     164              :         }
     165           24 :         info!("client chooses {}", sasl.method);
     166              : 
     167           24 :         let outcome = sasl::SaslStream::new(self.stream, sasl.message)
     168           24 :             .authenticate(scram::Exchange::new(
     169           24 :                 secret,
     170           24 :                 rand::random,
     171           24 :                 self.tls_server_end_point,
     172           24 :             ))
     173           22 :             .await?;
     174              : 
     175           14 :         if let sasl::Outcome::Success(_) = &outcome {
     176           12 :             self.stream.write_message_noflush(&Be::AuthenticationOk)?;
     177            2 :         }
     178              : 
     179           14 :         Ok(outcome)
     180           26 :     }
     181              : }
     182              : 
     183            4 : pub(crate) async fn validate_password_and_exchange(
     184            4 :     password: &[u8],
     185            4 :     secret: AuthSecret,
     186            4 : ) -> super::Result<sasl::Outcome<ComputeCredentialKeys>> {
     187            4 :     match secret {
     188              :         #[cfg(any(test, feature = "testing"))]
     189              :         AuthSecret::Md5(_) => {
     190              :             // test only
     191            0 :             Ok(sasl::Outcome::Success(ComputeCredentialKeys::Password(
     192            0 :                 password.to_owned(),
     193            0 :             )))
     194              :         }
     195              :         // perform scram authentication as both client and server to validate the keys
     196            4 :         AuthSecret::Scram(scram_secret) => {
     197           12 :             let outcome = crate::scram::exchange(&scram_secret, password).await?;
     198              : 
     199            4 :             let client_key = match outcome {
     200            4 :                 sasl::Outcome::Success(client_key) => client_key,
     201            0 :                 sasl::Outcome::Failure(reason) => return Ok(sasl::Outcome::Failure(reason)),
     202              :             };
     203              : 
     204            4 :             let keys = crate::compute::ScramKeys {
     205            4 :                 client_key: client_key.as_bytes(),
     206            4 :                 server_key: scram_secret.server_key.as_bytes(),
     207            4 :             };
     208            4 : 
     209            4 :             Ok(sasl::Outcome::Success(ComputeCredentialKeys::AuthKeys(
     210            4 :                 tokio_postgres::config::AuthKeys::ScramSha256(keys),
     211            4 :             )))
     212              :         }
     213              :     }
     214            4 : }
        

Generated by: LCOV version 2.1-beta