Line data Source code
1 : //! Various stuff for dealing with the Neon Console.
2 : //! Later we might move some API wrappers here.
3 :
4 : /// Payloads used in the console's APIs.
5 : pub mod messages;
6 :
7 : /// Wrappers for console APIs and their mocks.
8 : pub mod client;
9 :
10 : pub(crate) mod errors;
11 :
12 : use std::sync::Arc;
13 :
14 : use messages::EndpointRateLimitConfig;
15 :
16 : use crate::auth::backend::ComputeUserInfo;
17 : use crate::auth::backend::jwt::AuthRule;
18 : use crate::auth::{AuthError, IpPattern, check_peer_addr_is_in_list};
19 : use crate::cache::{Cached, TimedLru};
20 : use crate::context::RequestContext;
21 : use crate::control_plane::messages::{ControlPlaneErrorMessage, MetricsAuxInfo};
22 : use crate::intern::{AccountIdInt, EndpointIdInt, ProjectIdInt};
23 : use crate::protocol2::ConnectionInfoExtra;
24 : use crate::rate_limiter::{EndpointRateLimiter, LeakyBucketConfig};
25 : use crate::types::{EndpointCacheKey, EndpointId, RoleName};
26 : use crate::{compute, scram};
27 :
28 : /// Various cache-related types.
29 : pub mod caches {
30 : pub use super::client::ApiCaches;
31 : }
32 :
33 : /// Various cache-related types.
34 : pub mod locks {
35 : pub use super::client::ApiLocks;
36 : }
37 :
38 : /// Console's management API.
39 : pub mod mgmt;
40 :
41 : /// Auth secret which is managed by the cloud.
42 : #[derive(Clone, Eq, PartialEq, Debug)]
43 : pub(crate) enum AuthSecret {
44 : /// [SCRAM](crate::scram) authentication info.
45 : Scram(scram::ServerSecret),
46 : }
47 :
48 : #[derive(Default)]
49 : pub(crate) struct AuthInfo {
50 : pub(crate) secret: Option<AuthSecret>,
51 : /// List of IP addresses allowed for the autorization.
52 : pub(crate) allowed_ips: Vec<IpPattern>,
53 : /// List of VPC endpoints allowed for the autorization.
54 : pub(crate) allowed_vpc_endpoint_ids: Vec<String>,
55 : /// Project ID. This is used for cache invalidation.
56 : pub(crate) project_id: Option<ProjectIdInt>,
57 : /// Account ID. This is used for cache invalidation.
58 : pub(crate) account_id: Option<AccountIdInt>,
59 : /// Are public connections or VPC connections blocked?
60 : pub(crate) access_blocker_flags: AccessBlockerFlags,
61 : /// The rate limits for this endpoint.
62 : pub(crate) rate_limits: EndpointRateLimitConfig,
63 : }
64 :
65 : /// Info for establishing a connection to a compute node.
66 : #[derive(Clone)]
67 : pub(crate) struct NodeInfo {
68 : pub(crate) conn_info: compute::ConnectInfo,
69 :
70 : /// Labels for proxy's metrics.
71 : pub(crate) aux: MetricsAuxInfo,
72 : }
73 :
74 : #[derive(Copy, Clone, Default, Debug)]
75 : pub(crate) struct AccessBlockerFlags {
76 : pub public_access_blocked: bool,
77 : pub vpc_access_blocked: bool,
78 : }
79 :
80 : pub(crate) type NodeInfoCache =
81 : TimedLru<EndpointCacheKey, Result<NodeInfo, Box<ControlPlaneErrorMessage>>>;
82 : pub(crate) type CachedNodeInfo = Cached<&'static NodeInfoCache, NodeInfo>;
83 :
84 : #[derive(Clone, Debug)]
85 : pub struct RoleAccessControl {
86 : pub secret: Option<AuthSecret>,
87 : }
88 :
89 : #[derive(Clone, Debug)]
90 : pub struct EndpointAccessControl {
91 : pub allowed_ips: Arc<Vec<IpPattern>>,
92 : pub allowed_vpce: Arc<Vec<String>>,
93 : pub flags: AccessBlockerFlags,
94 :
95 : pub rate_limits: EndpointRateLimitConfig,
96 : }
97 :
98 : impl EndpointAccessControl {
99 3 : pub fn check(
100 3 : &self,
101 3 : ctx: &RequestContext,
102 3 : check_ip_allowed: bool,
103 3 : check_vpc_allowed: bool,
104 3 : ) -> Result<(), AuthError> {
105 3 : if check_ip_allowed && !check_peer_addr_is_in_list(&ctx.peer_addr(), &self.allowed_ips) {
106 0 : return Err(AuthError::IpAddressNotAllowed(ctx.peer_addr()));
107 3 : }
108 :
109 : // check if a VPC endpoint ID is coming in and if yes, if it's allowed
110 3 : if check_vpc_allowed {
111 0 : if self.flags.vpc_access_blocked {
112 0 : return Err(AuthError::NetworkNotAllowed);
113 0 : }
114 :
115 0 : let incoming_vpc_endpoint_id = match ctx.extra() {
116 0 : None => return Err(AuthError::MissingVPCEndpointId),
117 0 : Some(ConnectionInfoExtra::Aws { vpce_id }) => vpce_id.to_string(),
118 0 : Some(ConnectionInfoExtra::Azure { link_id }) => link_id.to_string(),
119 : };
120 :
121 0 : let vpce = &self.allowed_vpce;
122 : // TODO: For now an empty VPC endpoint ID list means all are allowed. We should replace that.
123 0 : if !vpce.is_empty() && !vpce.contains(&incoming_vpc_endpoint_id) {
124 0 : return Err(AuthError::vpc_endpoint_id_not_allowed(
125 0 : incoming_vpc_endpoint_id,
126 0 : ));
127 0 : }
128 3 : } else if self.flags.public_access_blocked {
129 0 : return Err(AuthError::NetworkNotAllowed);
130 3 : }
131 :
132 3 : Ok(())
133 3 : }
134 :
135 3 : pub fn connection_attempt_rate_limit(
136 3 : &self,
137 3 : ctx: &RequestContext,
138 3 : endpoint: &EndpointId,
139 3 : rate_limiter: &EndpointRateLimiter,
140 3 : ) -> Result<(), AuthError> {
141 3 : let endpoint = EndpointIdInt::from(endpoint);
142 :
143 3 : let limits = &self.rate_limits.connection_attempts;
144 3 : let config = match ctx.protocol() {
145 0 : crate::metrics::Protocol::Http => limits.http,
146 0 : crate::metrics::Protocol::Ws => limits.ws,
147 3 : crate::metrics::Protocol::Tcp => limits.tcp,
148 0 : crate::metrics::Protocol::SniRouter => return Ok(()),
149 : };
150 3 : let config = config.and_then(|config| {
151 0 : if config.rps <= 0.0 || config.burst <= 0.0 {
152 0 : return None;
153 0 : }
154 :
155 0 : Some(LeakyBucketConfig::new(config.rps, config.burst))
156 0 : });
157 :
158 3 : if !rate_limiter.check(endpoint, config, 1) {
159 0 : return Err(AuthError::too_many_connections());
160 3 : }
161 :
162 3 : Ok(())
163 3 : }
164 : }
165 :
166 : /// This will allocate per each call, but the http requests alone
167 : /// already require a few allocations, so it should be fine.
168 : pub(crate) trait ControlPlaneApi {
169 : async fn get_role_access_control(
170 : &self,
171 : ctx: &RequestContext,
172 : endpoint: &EndpointId,
173 : role: &RoleName,
174 : ) -> Result<RoleAccessControl, errors::GetAuthInfoError>;
175 :
176 : async fn get_endpoint_access_control(
177 : &self,
178 : ctx: &RequestContext,
179 : endpoint: &EndpointId,
180 : role: &RoleName,
181 : ) -> Result<EndpointAccessControl, errors::GetAuthInfoError>;
182 :
183 : async fn get_endpoint_jwks(
184 : &self,
185 : ctx: &RequestContext,
186 : endpoint: &EndpointId,
187 : ) -> Result<Vec<AuthRule>, errors::GetEndpointJwksError>;
188 :
189 : /// Wake up the compute node and return the corresponding connection info.
190 : async fn wake_compute(
191 : &self,
192 : ctx: &RequestContext,
193 : user_info: &ComputeUserInfo,
194 : ) -> Result<CachedNodeInfo, errors::WakeComputeError>;
195 : }
|