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