LCOV - code coverage report
Current view: top level - proxy/src/auth/backend - mod.rs (source / functions) Coverage Total Hit
Test: 20b6afc7b7f34578dcaab2b3acdaecfe91cd8bf1.info Lines: 79.0 % 490 387
Test Date: 2024-11-25 17:48:16 Functions: 42.9 % 70 30

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

Generated by: LCOV version 2.1-beta