Line data Source code
1 : mod classic;
2 : mod console_redirect;
3 : mod hacks;
4 : pub mod jwt;
5 : pub mod local;
6 :
7 : use std::net::IpAddr;
8 : use std::sync::Arc;
9 :
10 : pub use console_redirect::ConsoleRedirectBackend;
11 : pub(crate) use console_redirect::ConsoleRedirectError;
12 : use ipnet::{Ipv4Net, Ipv6Net};
13 : use local::LocalBackend;
14 : use postgres_client::config::AuthKeys;
15 : use serde::{Deserialize, Serialize};
16 : use tokio::io::{AsyncRead, AsyncWrite};
17 : use tracing::{debug, info, warn};
18 :
19 : use crate::auth::credentials::check_peer_addr_is_in_list;
20 : use crate::auth::{
21 : self, validate_password_and_exchange, AuthError, ComputeUserInfoMaybeEndpoint, IpPattern,
22 : };
23 : use crate::cache::Cached;
24 : use crate::config::AuthenticationConfig;
25 : use crate::context::RequestContext;
26 : use crate::control_plane::client::ControlPlaneClient;
27 : use crate::control_plane::errors::GetAuthInfoError;
28 : use crate::control_plane::{
29 : self, AccessBlockerFlags, AuthSecret, CachedAccessBlockerFlags, CachedAllowedIps,
30 : CachedAllowedVpcEndpointIds, CachedNodeInfo, CachedRoleSecret, ControlPlaneApi,
31 : };
32 : use crate::intern::EndpointIdInt;
33 : use crate::metrics::Metrics;
34 : use crate::protocol2::ConnectionInfoExtra;
35 : use crate::proxy::connect_compute::ComputeConnectBackend;
36 : use crate::proxy::NeonOptions;
37 : use crate::rate_limiter::{BucketRateLimiter, EndpointRateLimiter};
38 : use crate::stream::Stream;
39 : use crate::types::{EndpointCacheKey, EndpointId, RoleName};
40 : use crate::{scram, stream};
41 :
42 : /// Alternative to [`std::borrow::Cow`] but doesn't need `T: ToOwned` as we don't need that functionality
43 : pub enum MaybeOwned<'a, T> {
44 : Owned(T),
45 : Borrowed(&'a T),
46 : }
47 :
48 : impl<T> std::ops::Deref for MaybeOwned<'_, T> {
49 : type Target = T;
50 :
51 13 : fn deref(&self) -> &Self::Target {
52 13 : match self {
53 13 : MaybeOwned::Owned(t) => t,
54 0 : MaybeOwned::Borrowed(t) => t,
55 : }
56 13 : }
57 : }
58 :
59 : /// This type serves two purposes:
60 : ///
61 : /// * When `T` is `()`, it's just a regular auth backend selector
62 : /// which we use in [`crate::config::ProxyConfig`].
63 : ///
64 : /// * However, when we substitute `T` with [`ComputeUserInfoMaybeEndpoint`],
65 : /// this helps us provide the credentials only to those auth
66 : /// backends which require them for the authentication process.
67 : pub enum Backend<'a, T> {
68 : /// Cloud API (V2).
69 : ControlPlane(MaybeOwned<'a, ControlPlaneClient>, T),
70 : /// Local proxy uses configured auth credentials and does not wake compute
71 : Local(MaybeOwned<'a, LocalBackend>),
72 : }
73 :
74 : impl std::fmt::Display for Backend<'_, ()> {
75 0 : fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
76 0 : match self {
77 0 : Self::ControlPlane(api, ()) => match &**api {
78 0 : ControlPlaneClient::ProxyV1(endpoint) => fmt
79 0 : .debug_tuple("ControlPlane::ProxyV1")
80 0 : .field(&endpoint.url())
81 0 : .finish(),
82 : #[cfg(any(test, feature = "testing"))]
83 0 : ControlPlaneClient::PostgresMock(endpoint) => fmt
84 0 : .debug_tuple("ControlPlane::PostgresMock")
85 0 : .field(&endpoint.url())
86 0 : .finish(),
87 : #[cfg(test)]
88 0 : ControlPlaneClient::Test(_) => fmt.debug_tuple("ControlPlane::Test").finish(),
89 : },
90 0 : Self::Local(_) => fmt.debug_tuple("Local").finish(),
91 : }
92 0 : }
93 : }
94 :
95 : impl<T> Backend<'_, T> {
96 : /// Very similar to [`std::option::Option::as_ref`].
97 : /// This helps us pass structured config to async tasks.
98 0 : pub(crate) fn as_ref(&self) -> Backend<'_, &T> {
99 0 : match self {
100 0 : Self::ControlPlane(c, x) => Backend::ControlPlane(MaybeOwned::Borrowed(c), x),
101 0 : Self::Local(l) => Backend::Local(MaybeOwned::Borrowed(l)),
102 : }
103 0 : }
104 :
105 0 : pub(crate) fn get_api(&self) -> &ControlPlaneClient {
106 0 : match self {
107 0 : Self::ControlPlane(api, _) => api,
108 0 : Self::Local(_) => panic!("Local backend has no API"),
109 : }
110 0 : }
111 :
112 0 : pub(crate) fn is_local_proxy(&self) -> bool {
113 0 : matches!(self, Self::Local(_))
114 0 : }
115 : }
116 :
117 : impl<'a, T> Backend<'a, T> {
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> {
122 0 : match self {
123 0 : Self::ControlPlane(c, x) => Backend::ControlPlane(c, f(x)),
124 0 : Self::Local(l) => Backend::Local(l),
125 : }
126 0 : }
127 : }
128 : impl<'a, T, E> Backend<'a, Result<T, E>> {
129 : /// Very similar to [`std::option::Option::transpose`].
130 : /// This is most useful for error handling.
131 0 : pub(crate) fn transpose(self) -> Result<Backend<'a, T>, E> {
132 0 : match self {
133 0 : Self::ControlPlane(c, x) => x.map(|x| Backend::ControlPlane(c, x)),
134 0 : Self::Local(l) => Ok(Backend::Local(l)),
135 : }
136 0 : }
137 : }
138 :
139 : pub(crate) struct ComputeCredentials {
140 : pub(crate) info: ComputeUserInfo,
141 : pub(crate) keys: ComputeCredentialKeys,
142 : }
143 :
144 : #[derive(Debug, Clone)]
145 : pub(crate) struct ComputeUserInfoNoEndpoint {
146 : pub(crate) user: RoleName,
147 : pub(crate) options: NeonOptions,
148 : }
149 :
150 0 : #[derive(Debug, Clone, Default, Serialize, Deserialize)]
151 : pub(crate) struct ComputeUserInfo {
152 : pub(crate) endpoint: EndpointId,
153 : pub(crate) user: RoleName,
154 : pub(crate) options: NeonOptions,
155 : }
156 :
157 : impl ComputeUserInfo {
158 2 : pub(crate) fn endpoint_cache_key(&self) -> EndpointCacheKey {
159 2 : self.options.get_cache_key(&self.endpoint)
160 2 : }
161 : }
162 :
163 : #[cfg_attr(test, derive(Debug))]
164 : pub(crate) enum ComputeCredentialKeys {
165 : #[cfg(any(test, feature = "testing"))]
166 : Password(Vec<u8>),
167 : AuthKeys(AuthKeys),
168 : JwtPayload(Vec<u8>),
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 AuthenticationConfig {
211 3 : pub(crate) fn check_rate_limit(
212 3 : &self,
213 3 : ctx: &RequestContext,
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: &RequestContext,
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, Option<Vec<IpPattern>>)> {
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 : debug!("fetching authentication info and allowlists");
290 :
291 : // check allowed list
292 3 : let allowed_ips = if config.ip_allowlist_check_enabled {
293 3 : let allowed_ips = api.get_allowed_ips(ctx, &info).await?;
294 3 : if !check_peer_addr_is_in_list(&ctx.peer_addr(), &allowed_ips) {
295 0 : return Err(auth::AuthError::ip_address_not_allowed(ctx.peer_addr()));
296 3 : }
297 3 : allowed_ips
298 : } else {
299 0 : Cached::new_uncached(Arc::new(vec![]))
300 : };
301 :
302 : // check if a VPC endpoint ID is coming in and if yes, if it's allowed
303 3 : let access_blocks = api.get_block_public_or_vpc_access(ctx, &info).await?;
304 3 : if config.is_vpc_acccess_proxy {
305 0 : if access_blocks.vpc_access_blocked {
306 0 : return Err(AuthError::NetworkNotAllowed);
307 0 : }
308 :
309 0 : let incoming_vpc_endpoint_id = match ctx.extra() {
310 0 : None => return Err(AuthError::MissingEndpointName),
311 0 : Some(ConnectionInfoExtra::Aws { vpce_id }) => {
312 0 : // Convert the vcpe_id to a string
313 0 : String::from_utf8(vpce_id.to_vec()).unwrap_or_default()
314 : }
315 0 : Some(ConnectionInfoExtra::Azure { link_id }) => link_id.to_string(),
316 : };
317 0 : let allowed_vpc_endpoint_ids = api.get_allowed_vpc_endpoint_ids(ctx, &info).await?;
318 : // TODO: For now an empty VPC endpoint ID list means all are allowed. We should replace that.
319 0 : if !allowed_vpc_endpoint_ids.is_empty()
320 0 : && !allowed_vpc_endpoint_ids.contains(&incoming_vpc_endpoint_id)
321 : {
322 0 : return Err(AuthError::vpc_endpoint_id_not_allowed(
323 0 : incoming_vpc_endpoint_id,
324 0 : ));
325 0 : }
326 3 : } else if access_blocks.public_access_blocked {
327 0 : return Err(AuthError::NetworkNotAllowed);
328 3 : }
329 :
330 3 : if !endpoint_rate_limiter.check(info.endpoint.clone().into(), 1) {
331 0 : return Err(AuthError::too_many_connections());
332 3 : }
333 3 : let cached_secret = api.get_role_secret(ctx, &info).await?;
334 3 : let (cached_entry, secret) = cached_secret.take_value();
335 :
336 3 : let secret = if let Some(secret) = secret {
337 3 : config.check_rate_limit(
338 3 : ctx,
339 3 : secret,
340 3 : &info.endpoint,
341 3 : unauthenticated_password.is_some() || allow_cleartext,
342 0 : )?
343 : } else {
344 : // If we don't have an authentication secret, we mock one to
345 : // prevent malicious probing (possible due to missing protocol steps).
346 : // This mocked secret will never lead to successful authentication.
347 0 : info!("authentication info not found, mocking it");
348 0 : AuthSecret::Scram(scram::ServerSecret::mock(rand::random()))
349 : };
350 :
351 3 : match authenticate_with_secret(
352 3 : ctx,
353 3 : secret,
354 3 : info,
355 3 : client,
356 3 : unauthenticated_password,
357 3 : allow_cleartext,
358 3 : config,
359 3 : )
360 3 : .await
361 : {
362 3 : Ok(keys) => Ok((keys, Some(allowed_ips.as_ref().clone()))),
363 0 : Err(e) => {
364 0 : if e.is_password_failed() {
365 0 : // The password could have been changed, so we invalidate the cache.
366 0 : cached_entry.invalidate();
367 0 : }
368 0 : Err(e)
369 : }
370 : }
371 3 : }
372 :
373 3 : async fn authenticate_with_secret(
374 3 : ctx: &RequestContext,
375 3 : secret: AuthSecret,
376 3 : info: ComputeUserInfo,
377 3 : client: &mut stream::PqStream<Stream<impl AsyncRead + AsyncWrite + Unpin>>,
378 3 : unauthenticated_password: Option<Vec<u8>>,
379 3 : allow_cleartext: bool,
380 3 : config: &'static AuthenticationConfig,
381 3 : ) -> auth::Result<ComputeCredentials> {
382 3 : if let Some(password) = unauthenticated_password {
383 1 : let ep = EndpointIdInt::from(&info.endpoint);
384 :
385 1 : let auth_outcome =
386 1 : validate_password_and_exchange(&config.thread_pool, ep, &password, secret).await?;
387 1 : let keys = match auth_outcome {
388 1 : crate::sasl::Outcome::Success(key) => key,
389 0 : crate::sasl::Outcome::Failure(reason) => {
390 0 : info!("auth backend failed with an error: {reason}");
391 0 : return Err(auth::AuthError::password_failed(&*info.user));
392 : }
393 : };
394 :
395 : // we have authenticated the password
396 1 : client.write_message_noflush(&pq_proto::BeMessage::AuthenticationOk)?;
397 :
398 1 : return Ok(ComputeCredentials { info, keys });
399 2 : }
400 2 :
401 2 : // -- the remaining flows are self-authenticating --
402 2 :
403 2 : // Perform cleartext auth if we're allowed to do that.
404 2 : // Currently, we use it for websocket connections (latency).
405 2 : if allow_cleartext {
406 1 : ctx.set_auth_method(crate::context::AuthMethod::Cleartext);
407 1 : return hacks::authenticate_cleartext(ctx, info, client, secret, config).await;
408 1 : }
409 1 :
410 1 : // Finally, proceed with the main auth flow (SCRAM-based).
411 1 : classic::authenticate(ctx, info, client, config, secret).await
412 3 : }
413 :
414 : impl<'a> Backend<'a, ComputeUserInfoMaybeEndpoint> {
415 : /// Get username from the credentials.
416 0 : pub(crate) fn get_user(&self) -> &str {
417 0 : match self {
418 0 : Self::ControlPlane(_, user_info) => &user_info.user,
419 0 : Self::Local(_) => "local",
420 : }
421 0 : }
422 :
423 : /// Authenticate the client via the requested backend, possibly using credentials.
424 : #[tracing::instrument(fields(allow_cleartext = allow_cleartext), skip_all)]
425 : pub(crate) async fn authenticate(
426 : self,
427 : ctx: &RequestContext,
428 : client: &mut stream::PqStream<Stream<impl AsyncRead + AsyncWrite + Unpin>>,
429 : allow_cleartext: bool,
430 : config: &'static AuthenticationConfig,
431 : endpoint_rate_limiter: Arc<EndpointRateLimiter>,
432 : ) -> auth::Result<(Backend<'a, ComputeCredentials>, Option<Vec<IpPattern>>)> {
433 : let res = match self {
434 : Self::ControlPlane(api, user_info) => {
435 : debug!(
436 : user = &*user_info.user,
437 : project = user_info.endpoint(),
438 : "performing authentication using the console"
439 : );
440 :
441 : let (credentials, ip_allowlist) = auth_quirks(
442 : ctx,
443 : &*api,
444 : user_info,
445 : client,
446 : allow_cleartext,
447 : config,
448 : endpoint_rate_limiter,
449 : )
450 : .await?;
451 : Ok((Backend::ControlPlane(api, credentials), ip_allowlist))
452 : }
453 : Self::Local(_) => {
454 : return Err(auth::AuthError::bad_auth_method("invalid for local proxy"))
455 : }
456 : };
457 :
458 : // TODO: replace with some metric
459 : info!("user successfully authenticated");
460 : res
461 : }
462 : }
463 :
464 : impl Backend<'_, ComputeUserInfo> {
465 0 : pub(crate) async fn get_role_secret(
466 0 : &self,
467 0 : ctx: &RequestContext,
468 0 : ) -> Result<CachedRoleSecret, GetAuthInfoError> {
469 0 : match self {
470 0 : Self::ControlPlane(api, user_info) => api.get_role_secret(ctx, user_info).await,
471 0 : Self::Local(_) => Ok(Cached::new_uncached(None)),
472 : }
473 0 : }
474 :
475 0 : pub(crate) async fn get_allowed_ips(
476 0 : &self,
477 0 : ctx: &RequestContext,
478 0 : ) -> Result<CachedAllowedIps, GetAuthInfoError> {
479 0 : match self {
480 0 : Self::ControlPlane(api, user_info) => api.get_allowed_ips(ctx, user_info).await,
481 0 : Self::Local(_) => Ok(Cached::new_uncached(Arc::new(vec![]))),
482 : }
483 0 : }
484 :
485 0 : pub(crate) async fn get_allowed_vpc_endpoint_ids(
486 0 : &self,
487 0 : ctx: &RequestContext,
488 0 : ) -> Result<CachedAllowedVpcEndpointIds, GetAuthInfoError> {
489 0 : match self {
490 0 : Self::ControlPlane(api, user_info) => {
491 0 : api.get_allowed_vpc_endpoint_ids(ctx, user_info).await
492 : }
493 0 : Self::Local(_) => Ok(Cached::new_uncached(Arc::new(vec![]))),
494 : }
495 0 : }
496 :
497 0 : pub(crate) async fn get_block_public_or_vpc_access(
498 0 : &self,
499 0 : ctx: &RequestContext,
500 0 : ) -> Result<CachedAccessBlockerFlags, GetAuthInfoError> {
501 0 : match self {
502 0 : Self::ControlPlane(api, user_info) => {
503 0 : api.get_block_public_or_vpc_access(ctx, user_info).await
504 : }
505 0 : Self::Local(_) => Ok(Cached::new_uncached(AccessBlockerFlags::default())),
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: &RequestContext,
515 13 : ) -> Result<CachedNodeInfo, control_plane::errors::WakeComputeError> {
516 13 : match self {
517 13 : Self::ControlPlane(api, creds) => api.wake_compute(ctx, &creds.info).await,
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::ControlPlane(_, creds) => &creds.keys,
525 0 : Self::Local(_) => &ComputeCredentialKeys::None,
526 : }
527 6 : }
528 : }
529 :
530 : #[cfg(test)]
531 : mod tests {
532 : #![allow(clippy::unimplemented, clippy::unwrap_used)]
533 :
534 : use std::net::IpAddr;
535 : use std::sync::Arc;
536 : use std::time::Duration;
537 :
538 : use bytes::BytesMut;
539 : use control_plane::AuthSecret;
540 : use fallible_iterator::FallibleIterator;
541 : use once_cell::sync::Lazy;
542 : use postgres_protocol::authentication::sasl::{ChannelBinding, ScramSha256};
543 : use postgres_protocol::message::backend::Message as PgMessage;
544 : use postgres_protocol::message::frontend;
545 : use tokio::io::{AsyncRead, AsyncReadExt, AsyncWriteExt};
546 :
547 : use super::jwt::JwkCache;
548 : use super::{auth_quirks, AuthRateLimiter};
549 : use crate::auth::backend::MaskedIp;
550 : use crate::auth::{ComputeUserInfoMaybeEndpoint, IpPattern};
551 : use crate::config::AuthenticationConfig;
552 : use crate::context::RequestContext;
553 : use crate::control_plane::{
554 : self, AccessBlockerFlags, CachedAccessBlockerFlags, CachedAllowedIps,
555 : CachedAllowedVpcEndpointIds, CachedNodeInfo, CachedRoleSecret,
556 : };
557 : use crate::proxy::NeonOptions;
558 : use crate::rate_limiter::{EndpointRateLimiter, RateBucketInfo};
559 : use crate::scram::threadpool::ThreadPool;
560 : use crate::scram::ServerSecret;
561 : use crate::stream::{PqStream, Stream};
562 :
563 : struct Auth {
564 : ips: Vec<IpPattern>,
565 : vpc_endpoint_ids: Vec<String>,
566 : access_blocker_flags: AccessBlockerFlags,
567 : secret: AuthSecret,
568 : }
569 :
570 : impl control_plane::ControlPlaneApi for Auth {
571 3 : async fn get_role_secret(
572 3 : &self,
573 3 : _ctx: &RequestContext,
574 3 : _user_info: &super::ComputeUserInfo,
575 3 : ) -> Result<CachedRoleSecret, control_plane::errors::GetAuthInfoError> {
576 3 : Ok(CachedRoleSecret::new_uncached(Some(self.secret.clone())))
577 3 : }
578 :
579 3 : async fn get_allowed_ips(
580 3 : &self,
581 3 : _ctx: &RequestContext,
582 3 : _user_info: &super::ComputeUserInfo,
583 3 : ) -> Result<CachedAllowedIps, control_plane::errors::GetAuthInfoError> {
584 3 : Ok(CachedAllowedIps::new_uncached(Arc::new(self.ips.clone())))
585 3 : }
586 :
587 0 : async fn get_allowed_vpc_endpoint_ids(
588 0 : &self,
589 0 : _ctx: &RequestContext,
590 0 : _user_info: &super::ComputeUserInfo,
591 0 : ) -> Result<CachedAllowedVpcEndpointIds, control_plane::errors::GetAuthInfoError> {
592 0 : Ok(CachedAllowedVpcEndpointIds::new_uncached(Arc::new(
593 0 : self.vpc_endpoint_ids.clone(),
594 0 : )))
595 0 : }
596 :
597 3 : async fn get_block_public_or_vpc_access(
598 3 : &self,
599 3 : _ctx: &RequestContext,
600 3 : _user_info: &super::ComputeUserInfo,
601 3 : ) -> Result<CachedAccessBlockerFlags, control_plane::errors::GetAuthInfoError> {
602 3 : Ok(CachedAccessBlockerFlags::new_uncached(
603 3 : self.access_blocker_flags.clone(),
604 3 : ))
605 3 : }
606 :
607 0 : async fn get_endpoint_jwks(
608 0 : &self,
609 0 : _ctx: &RequestContext,
610 0 : _endpoint: crate::types::EndpointId,
611 0 : ) -> Result<Vec<super::jwt::AuthRule>, control_plane::errors::GetEndpointJwksError>
612 0 : {
613 0 : unimplemented!()
614 : }
615 :
616 0 : async fn wake_compute(
617 0 : &self,
618 0 : _ctx: &RequestContext,
619 0 : _user_info: &super::ComputeUserInfo,
620 0 : ) -> Result<CachedNodeInfo, control_plane::errors::WakeComputeError> {
621 0 : unimplemented!()
622 : }
623 : }
624 :
625 3 : static CONFIG: Lazy<AuthenticationConfig> = Lazy::new(|| AuthenticationConfig {
626 3 : jwks_cache: JwkCache::default(),
627 3 : thread_pool: ThreadPool::new(1),
628 3 : scram_protocol_timeout: std::time::Duration::from_secs(5),
629 3 : rate_limiter_enabled: true,
630 3 : rate_limiter: AuthRateLimiter::new(&RateBucketInfo::DEFAULT_AUTH_SET),
631 3 : rate_limit_ip_subnet: 64,
632 3 : ip_allowlist_check_enabled: true,
633 3 : is_vpc_acccess_proxy: false,
634 3 : is_auth_broker: false,
635 3 : accept_jwts: false,
636 3 : console_redirect_confirmation_timeout: std::time::Duration::from_secs(5),
637 3 : });
638 :
639 5 : async fn read_message(r: &mut (impl AsyncRead + Unpin), b: &mut BytesMut) -> PgMessage {
640 : loop {
641 7 : r.read_buf(&mut *b).await.unwrap();
642 7 : if let Some(m) = PgMessage::parse(&mut *b).unwrap() {
643 5 : break m;
644 2 : }
645 : }
646 5 : }
647 :
648 : #[test]
649 1 : fn masked_ip() {
650 1 : let ip_a = IpAddr::V4([127, 0, 0, 1].into());
651 1 : let ip_b = IpAddr::V4([127, 0, 0, 2].into());
652 1 : let ip_c = IpAddr::V4([192, 168, 1, 101].into());
653 1 : let ip_d = IpAddr::V4([192, 168, 1, 102].into());
654 1 : let ip_e = IpAddr::V6("abcd:abcd:abcd:abcd:abcd:abcd:abcd:abcd".parse().unwrap());
655 1 : let ip_f = IpAddr::V6("abcd:abcd:abcd:abcd:1234:abcd:abcd:abcd".parse().unwrap());
656 1 :
657 1 : assert_ne!(MaskedIp::new(ip_a, 64), MaskedIp::new(ip_b, 64));
658 1 : assert_ne!(MaskedIp::new(ip_a, 32), MaskedIp::new(ip_b, 32));
659 1 : assert_eq!(MaskedIp::new(ip_a, 30), MaskedIp::new(ip_b, 30));
660 1 : assert_eq!(MaskedIp::new(ip_c, 30), MaskedIp::new(ip_d, 30));
661 :
662 1 : assert_ne!(MaskedIp::new(ip_e, 128), MaskedIp::new(ip_f, 128));
663 1 : assert_eq!(MaskedIp::new(ip_e, 64), MaskedIp::new(ip_f, 64));
664 1 : }
665 :
666 : #[test]
667 1 : fn test_default_auth_rate_limit_set() {
668 1 : // these values used to exceed u32::MAX
669 1 : assert_eq!(
670 1 : RateBucketInfo::DEFAULT_AUTH_SET,
671 1 : [
672 1 : RateBucketInfo {
673 1 : interval: Duration::from_secs(1),
674 1 : max_rpi: 1000 * 4096,
675 1 : },
676 1 : RateBucketInfo {
677 1 : interval: Duration::from_secs(60),
678 1 : max_rpi: 600 * 4096 * 60,
679 1 : },
680 1 : RateBucketInfo {
681 1 : interval: Duration::from_secs(600),
682 1 : max_rpi: 300 * 4096 * 600,
683 1 : }
684 1 : ]
685 1 : );
686 :
687 4 : for x in RateBucketInfo::DEFAULT_AUTH_SET {
688 3 : let y = x.to_string().parse().unwrap();
689 3 : assert_eq!(x, y);
690 : }
691 1 : }
692 :
693 : #[tokio::test]
694 1 : async fn auth_quirks_scram() {
695 1 : let (mut client, server) = tokio::io::duplex(1024);
696 1 : let mut stream = PqStream::new(Stream::from_raw(server));
697 1 :
698 1 : let ctx = RequestContext::test();
699 1 : let api = Auth {
700 1 : ips: vec![],
701 1 : vpc_endpoint_ids: vec![],
702 1 : access_blocker_flags: AccessBlockerFlags::default(),
703 1 : secret: AuthSecret::Scram(ServerSecret::build("my-secret-password").await.unwrap()),
704 1 : };
705 1 :
706 1 : let user_info = ComputeUserInfoMaybeEndpoint {
707 1 : user: "conrad".into(),
708 1 : endpoint_id: Some("endpoint".into()),
709 1 : options: NeonOptions::default(),
710 1 : };
711 1 :
712 1 : let handle = tokio::spawn(async move {
713 1 : let mut scram = ScramSha256::new(b"my-secret-password", ChannelBinding::unsupported());
714 1 :
715 1 : let mut read = BytesMut::new();
716 1 :
717 1 : // server should offer scram
718 1 : match read_message(&mut client, &mut read).await {
719 1 : PgMessage::AuthenticationSasl(a) => {
720 1 : let options: Vec<&str> = a.mechanisms().collect().unwrap();
721 1 : assert_eq!(options, ["SCRAM-SHA-256"]);
722 1 : }
723 1 : _ => panic!("wrong message"),
724 1 : }
725 1 :
726 1 : // client sends client-first-message
727 1 : let mut write = BytesMut::new();
728 1 : frontend::sasl_initial_response("SCRAM-SHA-256", scram.message(), &mut write).unwrap();
729 1 : client.write_all(&write).await.unwrap();
730 1 :
731 1 : // server response with server-first-message
732 1 : match read_message(&mut client, &mut read).await {
733 1 : PgMessage::AuthenticationSaslContinue(a) => {
734 1 : scram.update(a.data()).await.unwrap();
735 1 : }
736 1 : _ => panic!("wrong message"),
737 1 : }
738 1 :
739 1 : // client response with client-final-message
740 1 : write.clear();
741 1 : frontend::sasl_response(scram.message(), &mut write).unwrap();
742 1 : client.write_all(&write).await.unwrap();
743 1 :
744 1 : // server response with server-final-message
745 1 : match read_message(&mut client, &mut read).await {
746 1 : PgMessage::AuthenticationSaslFinal(a) => {
747 1 : scram.finish(a.data()).unwrap();
748 1 : }
749 1 : _ => panic!("wrong message"),
750 1 : }
751 1 : });
752 1 : let endpoint_rate_limiter = Arc::new(EndpointRateLimiter::new_with_shards(
753 1 : EndpointRateLimiter::DEFAULT,
754 1 : 64,
755 1 : ));
756 1 :
757 1 : let _creds = auth_quirks(
758 1 : &ctx,
759 1 : &api,
760 1 : user_info,
761 1 : &mut stream,
762 1 : false,
763 1 : &CONFIG,
764 1 : endpoint_rate_limiter,
765 1 : )
766 1 : .await
767 1 : .unwrap();
768 1 :
769 1 : // flush the final server message
770 1 : stream.flush().await.unwrap();
771 1 :
772 1 : handle.await.unwrap();
773 1 : }
774 :
775 : #[tokio::test]
776 1 : async fn auth_quirks_cleartext() {
777 1 : let (mut client, server) = tokio::io::duplex(1024);
778 1 : let mut stream = PqStream::new(Stream::from_raw(server));
779 1 :
780 1 : let ctx = RequestContext::test();
781 1 : let api = Auth {
782 1 : ips: vec![],
783 1 : vpc_endpoint_ids: vec![],
784 1 : access_blocker_flags: AccessBlockerFlags::default(),
785 1 : secret: AuthSecret::Scram(ServerSecret::build("my-secret-password").await.unwrap()),
786 1 : };
787 1 :
788 1 : let user_info = ComputeUserInfoMaybeEndpoint {
789 1 : user: "conrad".into(),
790 1 : endpoint_id: Some("endpoint".into()),
791 1 : options: NeonOptions::default(),
792 1 : };
793 1 :
794 1 : let handle = tokio::spawn(async move {
795 1 : let mut read = BytesMut::new();
796 1 : let mut write = BytesMut::new();
797 1 :
798 1 : // server should offer cleartext
799 1 : match read_message(&mut client, &mut read).await {
800 1 : PgMessage::AuthenticationCleartextPassword => {}
801 1 : _ => panic!("wrong message"),
802 1 : }
803 1 :
804 1 : // client responds with password
805 1 : write.clear();
806 1 : frontend::password_message(b"my-secret-password", &mut write).unwrap();
807 1 : client.write_all(&write).await.unwrap();
808 1 : });
809 1 : let endpoint_rate_limiter = Arc::new(EndpointRateLimiter::new_with_shards(
810 1 : EndpointRateLimiter::DEFAULT,
811 1 : 64,
812 1 : ));
813 1 :
814 1 : let _creds = auth_quirks(
815 1 : &ctx,
816 1 : &api,
817 1 : user_info,
818 1 : &mut stream,
819 1 : true,
820 1 : &CONFIG,
821 1 : endpoint_rate_limiter,
822 1 : )
823 1 : .await
824 1 : .unwrap();
825 1 :
826 1 : handle.await.unwrap();
827 1 : }
828 :
829 : #[tokio::test]
830 1 : async fn auth_quirks_password_hack() {
831 1 : let (mut client, server) = tokio::io::duplex(1024);
832 1 : let mut stream = PqStream::new(Stream::from_raw(server));
833 1 :
834 1 : let ctx = RequestContext::test();
835 1 : let api = Auth {
836 1 : ips: vec![],
837 1 : vpc_endpoint_ids: vec![],
838 1 : access_blocker_flags: AccessBlockerFlags::default(),
839 1 : secret: AuthSecret::Scram(ServerSecret::build("my-secret-password").await.unwrap()),
840 1 : };
841 1 :
842 1 : let user_info = ComputeUserInfoMaybeEndpoint {
843 1 : user: "conrad".into(),
844 1 : endpoint_id: None,
845 1 : options: NeonOptions::default(),
846 1 : };
847 1 :
848 1 : let handle = tokio::spawn(async move {
849 1 : let mut read = BytesMut::new();
850 1 :
851 1 : // server should offer cleartext
852 1 : match read_message(&mut client, &mut read).await {
853 1 : PgMessage::AuthenticationCleartextPassword => {}
854 1 : _ => panic!("wrong message"),
855 1 : }
856 1 :
857 1 : // client responds with password
858 1 : let mut write = BytesMut::new();
859 1 : frontend::password_message(b"endpoint=my-endpoint;my-secret-password", &mut write)
860 1 : .unwrap();
861 1 : client.write_all(&write).await.unwrap();
862 1 : });
863 1 :
864 1 : let endpoint_rate_limiter = Arc::new(EndpointRateLimiter::new_with_shards(
865 1 : EndpointRateLimiter::DEFAULT,
866 1 : 64,
867 1 : ));
868 1 :
869 1 : let creds = auth_quirks(
870 1 : &ctx,
871 1 : &api,
872 1 : user_info,
873 1 : &mut stream,
874 1 : true,
875 1 : &CONFIG,
876 1 : endpoint_rate_limiter,
877 1 : )
878 1 : .await
879 1 : .unwrap();
880 1 :
881 1 : assert_eq!(creds.0.info.endpoint, "my-endpoint");
882 1 :
883 1 : handle.await.unwrap();
884 1 : }
885 : }
|