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