LCOV - code coverage report
Current view: top level - proxy/src/auth - backend.rs (source / functions) Coverage Total Hit
Test: ccf45ed1c149555259baec52d6229a81013dcd6a.info Lines: 77.7 % 494 384
Test Date: 2024-08-21 17:32:46 Functions: 40.5 % 74 30

            Line data    Source code
       1              : mod classic;
       2              : mod hacks;
       3              : pub mod jwt;
       4              : mod link;
       5              : 
       6              : use std::net::IpAddr;
       7              : use std::sync::Arc;
       8              : use std::time::Duration;
       9              : 
      10              : use ipnet::{Ipv4Net, Ipv6Net};
      11              : pub use link::LinkAuthError;
      12              : use tokio::io::{AsyncRead, AsyncWrite};
      13              : use tokio_postgres::config::AuthKeys;
      14              : use tracing::{info, warn};
      15              : 
      16              : use crate::auth::credentials::check_peer_addr_is_in_list;
      17              : use crate::auth::{validate_password_and_exchange, AuthError};
      18              : use crate::cache::Cached;
      19              : use crate::console::errors::GetAuthInfoError;
      20              : use crate::console::provider::{CachedRoleSecret, ConsoleBackend};
      21              : use crate::console::{AuthSecret, NodeInfo};
      22              : use crate::context::RequestMonitoring;
      23              : use crate::intern::EndpointIdInt;
      24              : use crate::metrics::Metrics;
      25              : use crate::proxy::connect_compute::ComputeConnectBackend;
      26              : use crate::proxy::NeonOptions;
      27              : use crate::rate_limiter::{BucketRateLimiter, EndpointRateLimiter, RateBucketInfo};
      28              : use crate::stream::Stream;
      29              : use crate::{
      30              :     auth::{self, ComputeUserInfoMaybeEndpoint},
      31              :     config::AuthenticationConfig,
      32              :     console::{
      33              :         self,
      34              :         provider::{CachedAllowedIps, CachedNodeInfo},
      35              :         Api,
      36              :     },
      37              :     stream, url,
      38              : };
      39              : use crate::{scram, EndpointCacheKey, EndpointId, RoleName};
      40              : 
      41              : /// Alternative to [`std::borrow::Cow`] but doesn't need `T: ToOwned` as we don't need that functionality
      42              : pub enum MaybeOwned<'a, T> {
      43              :     Owned(T),
      44              :     Borrowed(&'a T),
      45              : }
      46              : 
      47              : impl<T> std::ops::Deref for MaybeOwned<'_, T> {
      48              :     type Target = T;
      49              : 
      50           26 :     fn deref(&self) -> &Self::Target {
      51           26 :         match self {
      52           26 :             MaybeOwned::Owned(t) => t,
      53            0 :             MaybeOwned::Borrowed(t) => t,
      54              :         }
      55           26 :     }
      56              : }
      57              : 
      58              : /// This type serves two purposes:
      59              : ///
      60              : /// * When `T` is `()`, it's just a regular auth backend selector
      61              : ///   which we use in [`crate::config::ProxyConfig`].
      62              : ///
      63              : /// * However, when we substitute `T` with [`ComputeUserInfoMaybeEndpoint`],
      64              : ///   this helps us provide the credentials only to those auth
      65              : ///   backends which require them for the authentication process.
      66              : pub enum BackendType<'a, T, D> {
      67              :     /// Cloud API (V2).
      68              :     Console(MaybeOwned<'a, ConsoleBackend>, T),
      69              :     /// Authentication via a web browser.
      70              :     Link(MaybeOwned<'a, url::ApiUrl>, D),
      71              : }
      72              : 
      73              : pub trait TestBackend: Send + Sync + 'static {
      74              :     fn wake_compute(&self) -> Result<CachedNodeInfo, console::errors::WakeComputeError>;
      75              :     fn get_allowed_ips_and_secret(
      76              :         &self,
      77              :     ) -> Result<(CachedAllowedIps, Option<CachedRoleSecret>), console::errors::GetAuthInfoError>;
      78              :     fn get_role_secret(&self) -> Result<CachedRoleSecret, console::errors::GetAuthInfoError>;
      79              : }
      80              : 
      81              : impl std::fmt::Display for BackendType<'_, (), ()> {
      82            0 :     fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
      83            0 :         match self {
      84            0 :             Self::Console(api, _) => match &**api {
      85            0 :                 ConsoleBackend::Console(endpoint) => {
      86            0 :                     fmt.debug_tuple("Console").field(&endpoint.url()).finish()
      87              :                 }
      88              :                 #[cfg(any(test, feature = "testing"))]
      89            0 :                 ConsoleBackend::Postgres(endpoint) => {
      90            0 :                     fmt.debug_tuple("Postgres").field(&endpoint.url()).finish()
      91              :                 }
      92              :                 #[cfg(test)]
      93            0 :                 ConsoleBackend::Test(_) => fmt.debug_tuple("Test").finish(),
      94              :             },
      95            0 :             Self::Link(url, _) => fmt.debug_tuple("Link").field(&url.as_str()).finish(),
      96              :         }
      97            0 :     }
      98              : }
      99              : 
     100              : impl<T, D> BackendType<'_, T, D> {
     101              :     /// Very similar to [`std::option::Option::as_ref`].
     102              :     /// This helps us pass structured config to async tasks.
     103            0 :     pub fn as_ref(&self) -> BackendType<'_, &T, &D> {
     104            0 :         match self {
     105            0 :             Self::Console(c, x) => BackendType::Console(MaybeOwned::Borrowed(c), x),
     106            0 :             Self::Link(c, x) => BackendType::Link(MaybeOwned::Borrowed(c), x),
     107              :         }
     108            0 :     }
     109              : }
     110              : 
     111              : impl<'a, T, D> BackendType<'a, T, D> {
     112              :     /// Very similar to [`std::option::Option::map`].
     113              :     /// Maps [`BackendType<T>`] to [`BackendType<R>`] by applying
     114              :     /// a function to a contained value.
     115            0 :     pub fn map<R>(self, f: impl FnOnce(T) -> R) -> BackendType<'a, R, D> {
     116            0 :         match self {
     117            0 :             Self::Console(c, x) => BackendType::Console(c, f(x)),
     118            0 :             Self::Link(c, x) => BackendType::Link(c, x),
     119              :         }
     120            0 :     }
     121              : }
     122              : impl<'a, T, D, E> BackendType<'a, Result<T, E>, D> {
     123              :     /// Very similar to [`std::option::Option::transpose`].
     124              :     /// This is most useful for error handling.
     125            0 :     pub fn transpose(self) -> Result<BackendType<'a, T, D>, E> {
     126            0 :         match self {
     127            0 :             Self::Console(c, x) => x.map(|x| BackendType::Console(c, x)),
     128            0 :             Self::Link(c, x) => Ok(BackendType::Link(c, x)),
     129              :         }
     130            0 :     }
     131              : }
     132              : 
     133              : pub struct ComputeCredentials {
     134              :     pub info: ComputeUserInfo,
     135              :     pub keys: ComputeCredentialKeys,
     136              : }
     137              : 
     138              : #[derive(Debug, Clone)]
     139              : pub struct ComputeUserInfoNoEndpoint {
     140              :     pub user: RoleName,
     141              :     pub options: NeonOptions,
     142              : }
     143              : 
     144              : #[derive(Debug, Clone)]
     145              : pub struct ComputeUserInfo {
     146              :     pub endpoint: EndpointId,
     147              :     pub user: RoleName,
     148              :     pub options: NeonOptions,
     149              : }
     150              : 
     151              : impl ComputeUserInfo {
     152            4 :     pub fn endpoint_cache_key(&self) -> EndpointCacheKey {
     153            4 :         self.options.get_cache_key(&self.endpoint)
     154            4 :     }
     155              : }
     156              : 
     157              : pub enum ComputeCredentialKeys {
     158              :     Password(Vec<u8>),
     159              :     AuthKeys(AuthKeys),
     160              : }
     161              : 
     162              : impl TryFrom<ComputeUserInfoMaybeEndpoint> for ComputeUserInfo {
     163              :     // user name
     164              :     type Error = ComputeUserInfoNoEndpoint;
     165              : 
     166            6 :     fn try_from(user_info: ComputeUserInfoMaybeEndpoint) -> Result<Self, Self::Error> {
     167            6 :         match user_info.endpoint_id {
     168            2 :             None => Err(ComputeUserInfoNoEndpoint {
     169            2 :                 user: user_info.user,
     170            2 :                 options: user_info.options,
     171            2 :             }),
     172            4 :             Some(endpoint) => Ok(ComputeUserInfo {
     173            4 :                 endpoint,
     174            4 :                 user: user_info.user,
     175            4 :                 options: user_info.options,
     176            4 :             }),
     177              :         }
     178            6 :     }
     179              : }
     180              : 
     181              : #[derive(PartialEq, PartialOrd, Hash, Eq, Ord, Debug, Copy, Clone)]
     182              : pub struct MaskedIp(IpAddr);
     183              : 
     184              : impl MaskedIp {
     185           30 :     fn new(value: IpAddr, prefix: u8) -> Self {
     186           30 :         match value {
     187           22 :             IpAddr::V4(v4) => Self(IpAddr::V4(
     188           22 :                 Ipv4Net::new(v4, prefix).map_or(v4, |x| x.trunc().addr()),
     189           22 :             )),
     190            8 :             IpAddr::V6(v6) => Self(IpAddr::V6(
     191            8 :                 Ipv6Net::new(v6, prefix).map_or(v6, |x| x.trunc().addr()),
     192            8 :             )),
     193              :         }
     194           30 :     }
     195              : }
     196              : 
     197              : // This can't be just per IP because that would limit some PaaS that share IP addresses
     198              : pub type AuthRateLimiter = BucketRateLimiter<(EndpointIdInt, MaskedIp)>;
     199              : 
     200              : impl RateBucketInfo {
     201              :     /// All of these are per endpoint-maskedip pair.
     202              :     /// Context: 4096 rounds of pbkdf2 take about 1ms of cpu time to execute (1 milli-cpu-second or 1mcpus).
     203              :     ///
     204              :     /// First bucket: 1000mcpus total per endpoint-ip pair
     205              :     /// * 4096000 requests per second with 1 hash rounds.
     206              :     /// * 1000 requests per second with 4096 hash rounds.
     207              :     /// * 6.8 requests per second with 600000 hash rounds.
     208              :     pub const DEFAULT_AUTH_SET: [Self; 3] = [
     209              :         Self::new(1000 * 4096, Duration::from_secs(1)),
     210              :         Self::new(600 * 4096, Duration::from_secs(60)),
     211              :         Self::new(300 * 4096, Duration::from_secs(600)),
     212              :     ];
     213              : }
     214              : 
     215              : impl AuthenticationConfig {
     216            6 :     pub fn check_rate_limit(
     217            6 :         &self,
     218            6 :         ctx: &RequestMonitoring,
     219            6 :         config: &AuthenticationConfig,
     220            6 :         secret: AuthSecret,
     221            6 :         endpoint: &EndpointId,
     222            6 :         is_cleartext: bool,
     223            6 :     ) -> auth::Result<AuthSecret> {
     224            6 :         // we have validated the endpoint exists, so let's intern it.
     225            6 :         let endpoint_int = EndpointIdInt::from(endpoint.normalize());
     226              : 
     227              :         // only count the full hash count if password hack or websocket flow.
     228              :         // in other words, if proxy needs to run the hashing
     229            6 :         let password_weight = if is_cleartext {
     230            4 :             match &secret {
     231              :                 #[cfg(any(test, feature = "testing"))]
     232            0 :                 AuthSecret::Md5(_) => 1,
     233            4 :                 AuthSecret::Scram(s) => s.iterations + 1,
     234              :             }
     235              :         } else {
     236              :             // validating scram takes just 1 hmac_sha_256 operation.
     237            2 :             1
     238              :         };
     239              : 
     240            6 :         let limit_not_exceeded = self.rate_limiter.check(
     241            6 :             (
     242            6 :                 endpoint_int,
     243            6 :                 MaskedIp::new(ctx.peer_addr(), config.rate_limit_ip_subnet),
     244            6 :             ),
     245            6 :             password_weight,
     246            6 :         );
     247            6 : 
     248            6 :         if !limit_not_exceeded {
     249            0 :             warn!(
     250              :                 enabled = self.rate_limiter_enabled,
     251            0 :                 "rate limiting authentication"
     252              :             );
     253            0 :             Metrics::get().proxy.requests_auth_rate_limits_total.inc();
     254            0 :             Metrics::get()
     255            0 :                 .proxy
     256            0 :                 .endpoints_auth_rate_limits
     257            0 :                 .get_metric()
     258            0 :                 .measure(endpoint);
     259            0 : 
     260            0 :             if self.rate_limiter_enabled {
     261            0 :                 return Err(auth::AuthError::too_many_connections());
     262            0 :             }
     263            6 :         }
     264              : 
     265            6 :         Ok(secret)
     266            6 :     }
     267              : }
     268              : 
     269              : /// True to its name, this function encapsulates our current auth trade-offs.
     270              : /// Here, we choose the appropriate auth flow based on circumstances.
     271              : ///
     272              : /// All authentication flows will emit an AuthenticationOk message if successful.
     273            6 : async fn auth_quirks(
     274            6 :     ctx: &RequestMonitoring,
     275            6 :     api: &impl console::Api,
     276            6 :     user_info: ComputeUserInfoMaybeEndpoint,
     277            6 :     client: &mut stream::PqStream<Stream<impl AsyncRead + AsyncWrite + Unpin>>,
     278            6 :     allow_cleartext: bool,
     279            6 :     config: &'static AuthenticationConfig,
     280            6 :     endpoint_rate_limiter: Arc<EndpointRateLimiter>,
     281            6 : ) -> auth::Result<ComputeCredentials> {
     282              :     // If there's no project so far, that entails that client doesn't
     283              :     // support SNI or other means of passing the endpoint (project) name.
     284              :     // We now expect to see a very specific payload in the place of password.
     285            6 :     let (info, unauthenticated_password) = match user_info.try_into() {
     286            2 :         Err(info) => {
     287            2 :             let res = hacks::password_hack_no_authentication(ctx, info, client).await?;
     288              : 
     289            2 :             ctx.set_endpoint_id(res.info.endpoint.clone());
     290            2 :             let password = match res.keys {
     291            2 :                 ComputeCredentialKeys::Password(p) => p,
     292              :                 ComputeCredentialKeys::AuthKeys(_) => {
     293            0 :                     unreachable!("password hack should return a password")
     294              :                 }
     295              :             };
     296            2 :             (res.info, Some(password))
     297              :         }
     298            4 :         Ok(info) => (info, None),
     299              :     };
     300              : 
     301            6 :     info!("fetching user's authentication info");
     302            6 :     let (allowed_ips, maybe_secret) = api.get_allowed_ips_and_secret(ctx, &info).await?;
     303              : 
     304              :     // check allowed list
     305            6 :     if !check_peer_addr_is_in_list(&ctx.peer_addr(), &allowed_ips) {
     306            0 :         return Err(auth::AuthError::ip_address_not_allowed(ctx.peer_addr()));
     307            6 :     }
     308            6 : 
     309            6 :     if !endpoint_rate_limiter.check(info.endpoint.clone().into(), 1) {
     310            0 :         return Err(AuthError::too_many_connections());
     311            6 :     }
     312            6 :     let cached_secret = match maybe_secret {
     313            6 :         Some(secret) => secret,
     314            0 :         None => api.get_role_secret(ctx, &info).await?,
     315              :     };
     316            6 :     let (cached_entry, secret) = cached_secret.take_value();
     317              : 
     318            6 :     let secret = match secret {
     319            6 :         Some(secret) => config.check_rate_limit(
     320            6 :             ctx,
     321            6 :             config,
     322            6 :             secret,
     323            6 :             &info.endpoint,
     324            6 :             unauthenticated_password.is_some() || allow_cleartext,
     325            0 :         )?,
     326              :         None => {
     327              :             // If we don't have an authentication secret, we mock one to
     328              :             // prevent malicious probing (possible due to missing protocol steps).
     329              :             // This mocked secret will never lead to successful authentication.
     330            0 :             info!("authentication info not found, mocking it");
     331            0 :             AuthSecret::Scram(scram::ServerSecret::mock(rand::random()))
     332              :         }
     333              :     };
     334              : 
     335            6 :     match authenticate_with_secret(
     336            6 :         ctx,
     337            6 :         secret,
     338            6 :         info,
     339            6 :         client,
     340            6 :         unauthenticated_password,
     341            6 :         allow_cleartext,
     342            6 :         config,
     343            6 :     )
     344           10 :     .await
     345              :     {
     346            6 :         Ok(keys) => Ok(keys),
     347            0 :         Err(e) => {
     348            0 :             if e.is_auth_failed() {
     349            0 :                 // The password could have been changed, so we invalidate the cache.
     350            0 :                 cached_entry.invalidate();
     351            0 :             }
     352            0 :             Err(e)
     353              :         }
     354              :     }
     355            6 : }
     356              : 
     357            6 : async fn authenticate_with_secret(
     358            6 :     ctx: &RequestMonitoring,
     359            6 :     secret: AuthSecret,
     360            6 :     info: ComputeUserInfo,
     361            6 :     client: &mut stream::PqStream<Stream<impl AsyncRead + AsyncWrite + Unpin>>,
     362            6 :     unauthenticated_password: Option<Vec<u8>>,
     363            6 :     allow_cleartext: bool,
     364            6 :     config: &'static AuthenticationConfig,
     365            6 : ) -> auth::Result<ComputeCredentials> {
     366            6 :     if let Some(password) = unauthenticated_password {
     367            2 :         let ep = EndpointIdInt::from(&info.endpoint);
     368              : 
     369            2 :         let auth_outcome =
     370            2 :             validate_password_and_exchange(&config.thread_pool, ep, &password, secret).await?;
     371            2 :         let keys = match auth_outcome {
     372            2 :             crate::sasl::Outcome::Success(key) => key,
     373            0 :             crate::sasl::Outcome::Failure(reason) => {
     374            0 :                 info!("auth backend failed with an error: {reason}");
     375            0 :                 return Err(auth::AuthError::auth_failed(&*info.user));
     376              :             }
     377              :         };
     378              : 
     379              :         // we have authenticated the password
     380            2 :         client.write_message_noflush(&pq_proto::BeMessage::AuthenticationOk)?;
     381              : 
     382            2 :         return Ok(ComputeCredentials { info, keys });
     383            4 :     }
     384            4 : 
     385            4 :     // -- the remaining flows are self-authenticating --
     386            4 : 
     387            4 :     // Perform cleartext auth if we're allowed to do that.
     388            4 :     // Currently, we use it for websocket connections (latency).
     389            4 :     if allow_cleartext {
     390            2 :         ctx.set_auth_method(crate::context::AuthMethod::Cleartext);
     391            4 :         return hacks::authenticate_cleartext(ctx, info, client, secret, config).await;
     392            2 :     }
     393            2 : 
     394            2 :     // Finally, proceed with the main auth flow (SCRAM-based).
     395            4 :     classic::authenticate(ctx, info, client, config, secret).await
     396            6 : }
     397              : 
     398              : impl<'a> BackendType<'a, ComputeUserInfoMaybeEndpoint, &()> {
     399              :     /// Get compute endpoint name from the credentials.
     400            0 :     pub fn get_endpoint(&self) -> Option<EndpointId> {
     401            0 :         match self {
     402            0 :             Self::Console(_, user_info) => user_info.endpoint_id.clone(),
     403            0 :             Self::Link(_, _) => Some("link".into()),
     404              :         }
     405            0 :     }
     406              : 
     407              :     /// Get username from the credentials.
     408            0 :     pub fn get_user(&self) -> &str {
     409            0 :         match self {
     410            0 :             Self::Console(_, user_info) => &user_info.user,
     411            0 :             Self::Link(_, _) => "link",
     412              :         }
     413            0 :     }
     414              : 
     415              :     /// Authenticate the client via the requested backend, possibly using credentials.
     416            0 :     #[tracing::instrument(fields(allow_cleartext = allow_cleartext), skip_all)]
     417              :     pub async fn authenticate(
     418              :         self,
     419              :         ctx: &RequestMonitoring,
     420              :         client: &mut stream::PqStream<Stream<impl AsyncRead + AsyncWrite + Unpin>>,
     421              :         allow_cleartext: bool,
     422              :         config: &'static AuthenticationConfig,
     423              :         endpoint_rate_limiter: Arc<EndpointRateLimiter>,
     424              :     ) -> auth::Result<BackendType<'a, ComputeCredentials, NodeInfo>> {
     425              :         let res = match self {
     426              :             Self::Console(api, user_info) => {
     427              :                 info!(
     428              :                     user = &*user_info.user,
     429              :                     project = user_info.endpoint(),
     430              :                     "performing authentication using the console"
     431              :                 );
     432              : 
     433              :                 let credentials = auth_quirks(
     434              :                     ctx,
     435              :                     &*api,
     436              :                     user_info,
     437              :                     client,
     438              :                     allow_cleartext,
     439              :                     config,
     440              :                     endpoint_rate_limiter,
     441              :                 )
     442              :                 .await?;
     443              :                 BackendType::Console(api, credentials)
     444              :             }
     445              :             // NOTE: this auth backend doesn't use client credentials.
     446              :             Self::Link(url, _) => {
     447              :                 info!("performing link authentication");
     448              : 
     449              :                 let info = link::authenticate(ctx, &url, client).await?;
     450              : 
     451              :                 BackendType::Link(url, info)
     452              :             }
     453              :         };
     454              : 
     455              :         info!("user successfully authenticated");
     456              :         Ok(res)
     457              :     }
     458              : }
     459              : 
     460              : impl BackendType<'_, ComputeUserInfo, &()> {
     461            0 :     pub async fn get_role_secret(
     462            0 :         &self,
     463            0 :         ctx: &RequestMonitoring,
     464            0 :     ) -> Result<CachedRoleSecret, GetAuthInfoError> {
     465            0 :         match self {
     466            0 :             Self::Console(api, user_info) => api.get_role_secret(ctx, user_info).await,
     467            0 :             Self::Link(_, _) => Ok(Cached::new_uncached(None)),
     468              :         }
     469            0 :     }
     470              : 
     471            0 :     pub async fn get_allowed_ips_and_secret(
     472            0 :         &self,
     473            0 :         ctx: &RequestMonitoring,
     474            0 :     ) -> Result<(CachedAllowedIps, Option<CachedRoleSecret>), GetAuthInfoError> {
     475            0 :         match self {
     476            0 :             Self::Console(api, user_info) => api.get_allowed_ips_and_secret(ctx, user_info).await,
     477            0 :             Self::Link(_, _) => Ok((Cached::new_uncached(Arc::new(vec![])), None)),
     478              :         }
     479            0 :     }
     480              : }
     481              : 
     482              : #[async_trait::async_trait]
     483              : impl ComputeConnectBackend for BackendType<'_, ComputeCredentials, NodeInfo> {
     484            0 :     async fn wake_compute(
     485            0 :         &self,
     486            0 :         ctx: &RequestMonitoring,
     487            0 :     ) -> Result<CachedNodeInfo, console::errors::WakeComputeError> {
     488            0 :         match self {
     489            0 :             Self::Console(api, creds) => api.wake_compute(ctx, &creds.info).await,
     490            0 :             Self::Link(_, info) => Ok(Cached::new_uncached(info.clone())),
     491            0 :         }
     492            0 :     }
     493              : 
     494            0 :     fn get_keys(&self) -> Option<&ComputeCredentialKeys> {
     495            0 :         match self {
     496            0 :             Self::Console(_, creds) => Some(&creds.keys),
     497            0 :             Self::Link(_, _) => None,
     498              :         }
     499            0 :     }
     500              : }
     501              : 
     502              : #[async_trait::async_trait]
     503              : impl ComputeConnectBackend for BackendType<'_, ComputeCredentials, &()> {
     504           26 :     async fn wake_compute(
     505           26 :         &self,
     506           26 :         ctx: &RequestMonitoring,
     507           26 :     ) -> Result<CachedNodeInfo, console::errors::WakeComputeError> {
     508           26 :         match self {
     509           26 :             Self::Console(api, creds) => api.wake_compute(ctx, &creds.info).await,
     510           26 :             Self::Link(_, _) => unreachable!("link auth flow doesn't support waking the compute"),
     511           26 :         }
     512           26 :     }
     513              : 
     514           12 :     fn get_keys(&self) -> Option<&ComputeCredentialKeys> {
     515           12 :         match self {
     516           12 :             Self::Console(_, creds) => Some(&creds.keys),
     517            0 :             Self::Link(_, _) => None,
     518              :         }
     519           12 :     }
     520              : }
     521              : 
     522              : #[cfg(test)]
     523              : mod tests {
     524              :     use std::{net::IpAddr, sync::Arc, time::Duration};
     525              : 
     526              :     use bytes::BytesMut;
     527              :     use fallible_iterator::FallibleIterator;
     528              :     use once_cell::sync::Lazy;
     529              :     use postgres_protocol::{
     530              :         authentication::sasl::{ChannelBinding, ScramSha256},
     531              :         message::{backend::Message as PgMessage, frontend},
     532              :     };
     533              :     use provider::AuthSecret;
     534              :     use tokio::io::{AsyncRead, AsyncReadExt, AsyncWriteExt};
     535              : 
     536              :     use crate::{
     537              :         auth::{backend::MaskedIp, ComputeUserInfoMaybeEndpoint, IpPattern},
     538              :         config::AuthenticationConfig,
     539              :         console::{
     540              :             self,
     541              :             provider::{self, CachedAllowedIps, CachedRoleSecret},
     542              :             CachedNodeInfo,
     543              :         },
     544              :         context::RequestMonitoring,
     545              :         proxy::NeonOptions,
     546              :         rate_limiter::{EndpointRateLimiter, RateBucketInfo},
     547              :         scram::{threadpool::ThreadPool, ServerSecret},
     548              :         stream::{PqStream, Stream},
     549              :     };
     550              : 
     551              :     use super::{auth_quirks, AuthRateLimiter};
     552              : 
     553              :     struct Auth {
     554              :         ips: Vec<IpPattern>,
     555              :         secret: AuthSecret,
     556              :     }
     557              : 
     558              :     impl console::Api for Auth {
     559            0 :         async fn get_role_secret(
     560            0 :             &self,
     561            0 :             _ctx: &RequestMonitoring,
     562            0 :             _user_info: &super::ComputeUserInfo,
     563            0 :         ) -> Result<CachedRoleSecret, console::errors::GetAuthInfoError> {
     564            0 :             Ok(CachedRoleSecret::new_uncached(Some(self.secret.clone())))
     565            0 :         }
     566              : 
     567            6 :         async fn get_allowed_ips_and_secret(
     568            6 :             &self,
     569            6 :             _ctx: &RequestMonitoring,
     570            6 :             _user_info: &super::ComputeUserInfo,
     571            6 :         ) -> Result<(CachedAllowedIps, Option<CachedRoleSecret>), console::errors::GetAuthInfoError>
     572            6 :         {
     573            6 :             Ok((
     574            6 :                 CachedAllowedIps::new_uncached(Arc::new(self.ips.clone())),
     575            6 :                 Some(CachedRoleSecret::new_uncached(Some(self.secret.clone()))),
     576            6 :             ))
     577            6 :         }
     578              : 
     579            0 :         async fn wake_compute(
     580            0 :             &self,
     581            0 :             _ctx: &RequestMonitoring,
     582            0 :             _user_info: &super::ComputeUserInfo,
     583            0 :         ) -> Result<CachedNodeInfo, console::errors::WakeComputeError> {
     584            0 :             unimplemented!()
     585              :         }
     586              :     }
     587              : 
     588            6 :     static CONFIG: Lazy<AuthenticationConfig> = Lazy::new(|| AuthenticationConfig {
     589            6 :         thread_pool: ThreadPool::new(1),
     590            6 :         scram_protocol_timeout: std::time::Duration::from_secs(5),
     591            6 :         rate_limiter_enabled: true,
     592            6 :         rate_limiter: AuthRateLimiter::new(&RateBucketInfo::DEFAULT_AUTH_SET),
     593            6 :         rate_limit_ip_subnet: 64,
     594            6 :     });
     595              : 
     596           10 :     async fn read_message(r: &mut (impl AsyncRead + Unpin), b: &mut BytesMut) -> PgMessage {
     597              :         loop {
     598           14 :             r.read_buf(&mut *b).await.unwrap();
     599           14 :             if let Some(m) = PgMessage::parse(&mut *b).unwrap() {
     600           10 :                 break m;
     601            4 :             }
     602              :         }
     603           10 :     }
     604              : 
     605              :     #[test]
     606            2 :     fn masked_ip() {
     607            2 :         let ip_a = IpAddr::V4([127, 0, 0, 1].into());
     608            2 :         let ip_b = IpAddr::V4([127, 0, 0, 2].into());
     609            2 :         let ip_c = IpAddr::V4([192, 168, 1, 101].into());
     610            2 :         let ip_d = IpAddr::V4([192, 168, 1, 102].into());
     611            2 :         let ip_e = IpAddr::V6("abcd:abcd:abcd:abcd:abcd:abcd:abcd:abcd".parse().unwrap());
     612            2 :         let ip_f = IpAddr::V6("abcd:abcd:abcd:abcd:1234:abcd:abcd:abcd".parse().unwrap());
     613            2 : 
     614            2 :         assert_ne!(MaskedIp::new(ip_a, 64), MaskedIp::new(ip_b, 64));
     615            2 :         assert_ne!(MaskedIp::new(ip_a, 32), MaskedIp::new(ip_b, 32));
     616            2 :         assert_eq!(MaskedIp::new(ip_a, 30), MaskedIp::new(ip_b, 30));
     617            2 :         assert_eq!(MaskedIp::new(ip_c, 30), MaskedIp::new(ip_d, 30));
     618              : 
     619            2 :         assert_ne!(MaskedIp::new(ip_e, 128), MaskedIp::new(ip_f, 128));
     620            2 :         assert_eq!(MaskedIp::new(ip_e, 64), MaskedIp::new(ip_f, 64));
     621            2 :     }
     622              : 
     623              :     #[test]
     624            2 :     fn test_default_auth_rate_limit_set() {
     625            2 :         // these values used to exceed u32::MAX
     626            2 :         assert_eq!(
     627            2 :             RateBucketInfo::DEFAULT_AUTH_SET,
     628            2 :             [
     629            2 :                 RateBucketInfo {
     630            2 :                     interval: Duration::from_secs(1),
     631            2 :                     max_rpi: 1000 * 4096,
     632            2 :                 },
     633            2 :                 RateBucketInfo {
     634            2 :                     interval: Duration::from_secs(60),
     635            2 :                     max_rpi: 600 * 4096 * 60,
     636            2 :                 },
     637            2 :                 RateBucketInfo {
     638            2 :                     interval: Duration::from_secs(600),
     639            2 :                     max_rpi: 300 * 4096 * 600,
     640            2 :                 }
     641            2 :             ]
     642            2 :         );
     643              : 
     644            8 :         for x in RateBucketInfo::DEFAULT_AUTH_SET {
     645            6 :             let y = x.to_string().parse().unwrap();
     646            6 :             assert_eq!(x, y);
     647              :         }
     648            2 :     }
     649              : 
     650              :     #[tokio::test]
     651            2 :     async fn auth_quirks_scram() {
     652            2 :         let (mut client, server) = tokio::io::duplex(1024);
     653            2 :         let mut stream = PqStream::new(Stream::from_raw(server));
     654            2 : 
     655            2 :         let ctx = RequestMonitoring::test();
     656            2 :         let api = Auth {
     657            2 :             ips: vec![],
     658            6 :             secret: AuthSecret::Scram(ServerSecret::build("my-secret-password").await.unwrap()),
     659            2 :         };
     660            2 : 
     661            2 :         let user_info = ComputeUserInfoMaybeEndpoint {
     662            2 :             user: "conrad".into(),
     663            2 :             endpoint_id: Some("endpoint".into()),
     664            2 :             options: NeonOptions::default(),
     665            2 :         };
     666            2 : 
     667            2 :         let handle = tokio::spawn(async move {
     668            2 :             let mut scram = ScramSha256::new(b"my-secret-password", ChannelBinding::unsupported());
     669            2 : 
     670            2 :             let mut read = BytesMut::new();
     671            2 : 
     672            2 :             // server should offer scram
     673            2 :             match read_message(&mut client, &mut read).await {
     674            2 :                 PgMessage::AuthenticationSasl(a) => {
     675            2 :                     let options: Vec<&str> = a.mechanisms().collect().unwrap();
     676            2 :                     assert_eq!(options, ["SCRAM-SHA-256"]);
     677            2 :                 }
     678            2 :                 _ => panic!("wrong message"),
     679            2 :             }
     680            2 : 
     681            2 :             // client sends client-first-message
     682            2 :             let mut write = BytesMut::new();
     683            2 :             frontend::sasl_initial_response("SCRAM-SHA-256", scram.message(), &mut write).unwrap();
     684            2 :             client.write_all(&write).await.unwrap();
     685            2 : 
     686            2 :             // server response with server-first-message
     687            2 :             match read_message(&mut client, &mut read).await {
     688            2 :                 PgMessage::AuthenticationSaslContinue(a) => {
     689            6 :                     scram.update(a.data()).await.unwrap();
     690            2 :                 }
     691            2 :                 _ => panic!("wrong message"),
     692            2 :             }
     693            2 : 
     694            2 :             // client response with client-final-message
     695            2 :             write.clear();
     696            2 :             frontend::sasl_response(scram.message(), &mut write).unwrap();
     697            2 :             client.write_all(&write).await.unwrap();
     698            2 : 
     699            2 :             // server response with server-final-message
     700            2 :             match read_message(&mut client, &mut read).await {
     701            2 :                 PgMessage::AuthenticationSaslFinal(a) => {
     702            2 :                     scram.finish(a.data()).unwrap();
     703            2 :                 }
     704            2 :                 _ => panic!("wrong message"),
     705            2 :             }
     706            2 :         });
     707            2 :         let endpoint_rate_limiter = Arc::new(EndpointRateLimiter::new_with_shards(
     708            2 :             EndpointRateLimiter::DEFAULT,
     709            2 :             64,
     710            2 :         ));
     711            2 : 
     712            2 :         let _creds = auth_quirks(
     713            2 :             &ctx,
     714            2 :             &api,
     715            2 :             user_info,
     716            2 :             &mut stream,
     717            2 :             false,
     718            2 :             &CONFIG,
     719            2 :             endpoint_rate_limiter,
     720            2 :         )
     721            4 :         .await
     722            2 :         .unwrap();
     723            2 : 
     724            2 :         handle.await.unwrap();
     725            2 :     }
     726              : 
     727              :     #[tokio::test]
     728            2 :     async fn auth_quirks_cleartext() {
     729            2 :         let (mut client, server) = tokio::io::duplex(1024);
     730            2 :         let mut stream = PqStream::new(Stream::from_raw(server));
     731            2 : 
     732            2 :         let ctx = RequestMonitoring::test();
     733            2 :         let api = Auth {
     734            2 :             ips: vec![],
     735            6 :             secret: AuthSecret::Scram(ServerSecret::build("my-secret-password").await.unwrap()),
     736            2 :         };
     737            2 : 
     738            2 :         let user_info = ComputeUserInfoMaybeEndpoint {
     739            2 :             user: "conrad".into(),
     740            2 :             endpoint_id: Some("endpoint".into()),
     741            2 :             options: NeonOptions::default(),
     742            2 :         };
     743            2 : 
     744            2 :         let handle = tokio::spawn(async move {
     745            2 :             let mut read = BytesMut::new();
     746            2 :             let mut write = BytesMut::new();
     747            2 : 
     748            2 :             // server should offer cleartext
     749            2 :             match read_message(&mut client, &mut read).await {
     750            2 :                 PgMessage::AuthenticationCleartextPassword => {}
     751            2 :                 _ => panic!("wrong message"),
     752            2 :             }
     753            2 : 
     754            2 :             // client responds with password
     755            2 :             write.clear();
     756            2 :             frontend::password_message(b"my-secret-password", &mut write).unwrap();
     757            2 :             client.write_all(&write).await.unwrap();
     758            2 :         });
     759            2 :         let endpoint_rate_limiter = Arc::new(EndpointRateLimiter::new_with_shards(
     760            2 :             EndpointRateLimiter::DEFAULT,
     761            2 :             64,
     762            2 :         ));
     763            2 : 
     764            2 :         let _creds = auth_quirks(
     765            2 :             &ctx,
     766            2 :             &api,
     767            2 :             user_info,
     768            2 :             &mut stream,
     769            2 :             true,
     770            2 :             &CONFIG,
     771            2 :             endpoint_rate_limiter,
     772            2 :         )
     773            4 :         .await
     774            2 :         .unwrap();
     775            2 : 
     776            2 :         handle.await.unwrap();
     777            2 :     }
     778              : 
     779              :     #[tokio::test]
     780            2 :     async fn auth_quirks_password_hack() {
     781            2 :         let (mut client, server) = tokio::io::duplex(1024);
     782            2 :         let mut stream = PqStream::new(Stream::from_raw(server));
     783            2 : 
     784            2 :         let ctx = RequestMonitoring::test();
     785            2 :         let api = Auth {
     786            2 :             ips: vec![],
     787            6 :             secret: AuthSecret::Scram(ServerSecret::build("my-secret-password").await.unwrap()),
     788            2 :         };
     789            2 : 
     790            2 :         let user_info = ComputeUserInfoMaybeEndpoint {
     791            2 :             user: "conrad".into(),
     792            2 :             endpoint_id: None,
     793            2 :             options: NeonOptions::default(),
     794            2 :         };
     795            2 : 
     796            2 :         let handle = tokio::spawn(async move {
     797            2 :             let mut read = BytesMut::new();
     798            2 : 
     799            2 :             // server should offer cleartext
     800            2 :             match read_message(&mut client, &mut read).await {
     801            2 :                 PgMessage::AuthenticationCleartextPassword => {}
     802            2 :                 _ => panic!("wrong message"),
     803            2 :             }
     804            2 : 
     805            2 :             // client responds with password
     806            2 :             let mut write = BytesMut::new();
     807            2 :             frontend::password_message(b"endpoint=my-endpoint;my-secret-password", &mut write)
     808            2 :                 .unwrap();
     809            2 :             client.write_all(&write).await.unwrap();
     810            2 :         });
     811            2 : 
     812            2 :         let endpoint_rate_limiter = Arc::new(EndpointRateLimiter::new_with_shards(
     813            2 :             EndpointRateLimiter::DEFAULT,
     814            2 :             64,
     815            2 :         ));
     816            2 : 
     817            2 :         let creds = auth_quirks(
     818            2 :             &ctx,
     819            2 :             &api,
     820            2 :             user_info,
     821            2 :             &mut stream,
     822            2 :             true,
     823            2 :             &CONFIG,
     824            2 :             endpoint_rate_limiter,
     825            2 :         )
     826            4 :         .await
     827            2 :         .unwrap();
     828            2 : 
     829            2 :         assert_eq!(creds.info.endpoint, "my-endpoint");
     830            2 : 
     831            2 :         handle.await.unwrap();
     832            2 :     }
     833              : }
        

Generated by: LCOV version 2.1-beta