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