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