Line data Source code
1 : //! User credentials used in authentication.
2 :
3 : use std::collections::HashSet;
4 : use std::net::IpAddr;
5 : use std::str::FromStr;
6 :
7 : use itertools::Itertools;
8 : use pq_proto::StartupMessageParams;
9 : use thiserror::Error;
10 : use tracing::{debug, warn};
11 :
12 : use crate::auth::password_hack::parse_endpoint_param;
13 : use crate::context::RequestContext;
14 : use crate::error::{ReportableError, UserFacingError};
15 : use crate::metrics::{Metrics, SniKind};
16 : use crate::proxy::NeonOptions;
17 : use crate::serverless::SERVERLESS_DRIVER_SNI;
18 : use crate::types::{EndpointId, RoleName};
19 :
20 : #[derive(Debug, Error, PartialEq, Eq, Clone)]
21 : pub(crate) enum ComputeUserInfoParseError {
22 : #[error("Parameter '{0}' is missing in startup packet.")]
23 : MissingKey(&'static str),
24 :
25 : #[error(
26 : "Inconsistent project name inferred from \
27 : SNI ('{}') and project option ('{}').",
28 : .domain, .option,
29 : )]
30 : InconsistentProjectNames {
31 : domain: EndpointId,
32 : option: EndpointId,
33 : },
34 :
35 : #[error(
36 : "Common name inferred from SNI ('{}') is not known",
37 : .cn,
38 : )]
39 : UnknownCommonName { cn: String },
40 :
41 : #[error("Project name ('{0}') must contain only alphanumeric characters and hyphen.")]
42 : MalformedProjectName(EndpointId),
43 : }
44 :
45 : impl UserFacingError for ComputeUserInfoParseError {}
46 :
47 : impl ReportableError for ComputeUserInfoParseError {
48 0 : fn get_error_kind(&self) -> crate::error::ErrorKind {
49 0 : crate::error::ErrorKind::User
50 0 : }
51 : }
52 :
53 : /// Various client credentials which we use for authentication.
54 : /// Note that we don't store any kind of client key or password here.
55 : #[derive(Debug, Clone, PartialEq, Eq)]
56 : pub(crate) struct ComputeUserInfoMaybeEndpoint {
57 : pub(crate) user: RoleName,
58 : pub(crate) endpoint_id: Option<EndpointId>,
59 : pub(crate) options: NeonOptions,
60 : }
61 :
62 : impl ComputeUserInfoMaybeEndpoint {
63 : #[inline]
64 0 : pub(crate) fn endpoint(&self) -> Option<&str> {
65 0 : self.endpoint_id.as_deref()
66 0 : }
67 : }
68 :
69 27 : pub(crate) fn endpoint_sni(
70 27 : sni: &str,
71 27 : common_names: &HashSet<String>,
72 27 : ) -> Result<Option<EndpointId>, ComputeUserInfoParseError> {
73 27 : let Some((subdomain, common_name)) = sni.split_once('.') else {
74 0 : return Err(ComputeUserInfoParseError::UnknownCommonName { cn: sni.into() });
75 : };
76 27 : if !common_names.contains(common_name) {
77 1 : return Err(ComputeUserInfoParseError::UnknownCommonName {
78 1 : cn: common_name.into(),
79 1 : });
80 26 : }
81 26 : if subdomain == SERVERLESS_DRIVER_SNI {
82 0 : return Ok(None);
83 26 : }
84 26 : Ok(Some(EndpointId::from(subdomain)))
85 27 : }
86 :
87 : impl ComputeUserInfoMaybeEndpoint {
88 13 : pub(crate) fn parse(
89 13 : ctx: &RequestContext,
90 13 : params: &StartupMessageParams,
91 13 : sni: Option<&str>,
92 13 : common_names: Option<&HashSet<String>>,
93 13 : ) -> Result<Self, ComputeUserInfoParseError> {
94 13 : // Some parameters are stored in the startup message.
95 13 : let get_param = |key| {
96 13 : params
97 13 : .get(key)
98 13 : .ok_or(ComputeUserInfoParseError::MissingKey(key))
99 13 : };
100 13 : let user: RoleName = get_param("user")?.into();
101 13 :
102 13 : // Project name might be passed via PG's command-line options.
103 13 : let endpoint_option = params
104 13 : .options_raw()
105 13 : .and_then(|options| {
106 7 : // We support both `project` (deprecated) and `endpoint` options for backward compatibility.
107 7 : // However, if both are present, we don't exactly know which one to use.
108 7 : // Therefore we require that only one of them is present.
109 7 : options
110 7 : .filter_map(parse_endpoint_param)
111 7 : .at_most_one()
112 7 : .ok()?
113 13 : })
114 13 : .map(|name| name.into());
115 :
116 13 : let endpoint_from_domain = if let Some(sni_str) = sni {
117 7 : if let Some(cn) = common_names {
118 7 : endpoint_sni(sni_str, cn)?
119 : } else {
120 0 : None
121 : }
122 : } else {
123 6 : None
124 : };
125 :
126 12 : let endpoint = match (endpoint_option, endpoint_from_domain) {
127 : // Invariant: if we have both project name variants, they should match.
128 2 : (Some(option), Some(domain)) if option != domain => {
129 1 : Some(Err(ComputeUserInfoParseError::InconsistentProjectNames {
130 1 : domain,
131 1 : option,
132 1 : }))
133 : }
134 : // Invariant: project name may not contain certain characters.
135 11 : (a, b) => a.or(b).map(|name| {
136 7 : if project_name_valid(name.as_ref()) {
137 7 : Ok(name)
138 : } else {
139 0 : Err(ComputeUserInfoParseError::MalformedProjectName(name))
140 : }
141 11 : }),
142 : }
143 12 : .transpose()?;
144 :
145 11 : if let Some(ep) = &endpoint {
146 7 : ctx.set_endpoint_id(ep.clone());
147 7 : }
148 :
149 11 : let metrics = Metrics::get();
150 11 : debug!(%user, "credentials");
151 11 : if sni.is_some() {
152 5 : debug!("Connection with sni");
153 5 : metrics.proxy.accepted_connections_by_sni.inc(SniKind::Sni);
154 6 : } else if endpoint.is_some() {
155 2 : metrics
156 2 : .proxy
157 2 : .accepted_connections_by_sni
158 2 : .inc(SniKind::NoSni);
159 2 : debug!("Connection without sni");
160 : } else {
161 4 : metrics
162 4 : .proxy
163 4 : .accepted_connections_by_sni
164 4 : .inc(SniKind::PasswordHack);
165 4 : debug!("Connection with password hack");
166 : }
167 :
168 11 : let options = NeonOptions::parse_params(params);
169 11 :
170 11 : Ok(Self {
171 11 : user,
172 11 : endpoint_id: endpoint,
173 11 : options,
174 11 : })
175 13 : }
176 : }
177 :
178 10 : pub(crate) fn check_peer_addr_is_in_list(peer_addr: &IpAddr, ip_list: &[IpPattern]) -> bool {
179 10 : ip_list.is_empty() || ip_list.iter().any(|pattern| check_ip(peer_addr, pattern))
180 10 : }
181 :
182 : #[derive(Debug, Clone, Eq, PartialEq)]
183 : pub(crate) enum IpPattern {
184 : Subnet(ipnet::IpNet),
185 : Range(IpAddr, IpAddr),
186 : Single(IpAddr),
187 : None,
188 : }
189 :
190 : impl<'de> serde::de::Deserialize<'de> for IpPattern {
191 10 : fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
192 10 : where
193 10 : D: serde::Deserializer<'de>,
194 10 : {
195 : struct StrVisitor;
196 : impl serde::de::Visitor<'_> for StrVisitor {
197 : type Value = IpPattern;
198 :
199 0 : fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
200 0 : write!(
201 0 : formatter,
202 0 : "comma separated list with ip address, ip address range, or ip address subnet mask"
203 0 : )
204 0 : }
205 :
206 10 : fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
207 10 : where
208 10 : E: serde::de::Error,
209 10 : {
210 10 : Ok(parse_ip_pattern(v).unwrap_or_else(|e| {
211 1 : warn!("Cannot parse ip pattern {v}: {e}");
212 1 : IpPattern::None
213 10 : }))
214 10 : }
215 : }
216 10 : deserializer.deserialize_str(StrVisitor)
217 10 : }
218 : }
219 :
220 : impl FromStr for IpPattern {
221 : type Err = anyhow::Error;
222 :
223 6 : fn from_str(s: &str) -> Result<Self, Self::Err> {
224 6 : parse_ip_pattern(s)
225 6 : }
226 : }
227 :
228 24 : fn parse_ip_pattern(pattern: &str) -> anyhow::Result<IpPattern> {
229 24 : if pattern.contains('/') {
230 2 : let subnet: ipnet::IpNet = pattern.parse()?;
231 1 : return Ok(IpPattern::Subnet(subnet));
232 22 : }
233 22 : if let Some((start, end)) = pattern.split_once('-') {
234 3 : let start: IpAddr = start.parse()?;
235 2 : let end: IpAddr = end.parse()?;
236 1 : return Ok(IpPattern::Range(start, end));
237 19 : }
238 19 : let addr: IpAddr = pattern.parse()?;
239 16 : Ok(IpPattern::Single(addr))
240 24 : }
241 :
242 16 : fn check_ip(ip: &IpAddr, pattern: &IpPattern) -> bool {
243 16 : match pattern {
244 3 : IpPattern::Subnet(subnet) => subnet.contains(ip),
245 5 : IpPattern::Range(start, end) => start <= ip && ip <= end,
246 7 : IpPattern::Single(addr) => addr == ip,
247 1 : IpPattern::None => false,
248 : }
249 16 : }
250 :
251 7 : fn project_name_valid(name: &str) -> bool {
252 23 : name.chars().all(|c| c.is_alphanumeric() || c == '-')
253 7 : }
254 :
255 : #[cfg(test)]
256 : mod tests {
257 : use ComputeUserInfoParseError::*;
258 : use serde_json::json;
259 :
260 : use super::*;
261 :
262 : #[test]
263 1 : fn parse_bare_minimum() -> anyhow::Result<()> {
264 1 : // According to postgresql, only `user` should be required.
265 1 : let options = StartupMessageParams::new([("user", "john_doe")]);
266 1 : let ctx = RequestContext::test();
267 1 : let user_info = ComputeUserInfoMaybeEndpoint::parse(&ctx, &options, None, None)?;
268 1 : assert_eq!(user_info.user, "john_doe");
269 1 : assert_eq!(user_info.endpoint_id, None);
270 :
271 1 : Ok(())
272 1 : }
273 :
274 : #[test]
275 1 : fn parse_excessive() -> anyhow::Result<()> {
276 1 : let options = StartupMessageParams::new([
277 1 : ("user", "john_doe"),
278 1 : ("database", "world"), // should be ignored
279 1 : ("foo", "bar"), // should be ignored
280 1 : ]);
281 1 : let ctx = RequestContext::test();
282 1 : let user_info = ComputeUserInfoMaybeEndpoint::parse(&ctx, &options, None, None)?;
283 1 : assert_eq!(user_info.user, "john_doe");
284 1 : assert_eq!(user_info.endpoint_id, None);
285 :
286 1 : Ok(())
287 1 : }
288 :
289 : #[test]
290 1 : fn parse_project_from_sni() -> anyhow::Result<()> {
291 1 : let options = StartupMessageParams::new([("user", "john_doe")]);
292 1 :
293 1 : let sni = Some("foo.localhost");
294 1 : let common_names = Some(["localhost".into()].into());
295 1 :
296 1 : let ctx = RequestContext::test();
297 1 : let user_info =
298 1 : ComputeUserInfoMaybeEndpoint::parse(&ctx, &options, sni, common_names.as_ref())?;
299 1 : assert_eq!(user_info.user, "john_doe");
300 1 : assert_eq!(user_info.endpoint_id.as_deref(), Some("foo"));
301 1 : assert_eq!(user_info.options.get_cache_key("foo"), "foo");
302 :
303 1 : Ok(())
304 1 : }
305 :
306 : #[test]
307 1 : fn parse_project_from_options() -> anyhow::Result<()> {
308 1 : let options = StartupMessageParams::new([
309 1 : ("user", "john_doe"),
310 1 : ("options", "-ckey=1 project=bar -c geqo=off"),
311 1 : ]);
312 1 :
313 1 : let ctx = RequestContext::test();
314 1 : let user_info = ComputeUserInfoMaybeEndpoint::parse(&ctx, &options, None, None)?;
315 1 : assert_eq!(user_info.user, "john_doe");
316 1 : assert_eq!(user_info.endpoint_id.as_deref(), Some("bar"));
317 :
318 1 : Ok(())
319 1 : }
320 :
321 : #[test]
322 1 : fn parse_endpoint_from_options() -> anyhow::Result<()> {
323 1 : let options = StartupMessageParams::new([
324 1 : ("user", "john_doe"),
325 1 : ("options", "-ckey=1 endpoint=bar -c geqo=off"),
326 1 : ]);
327 1 :
328 1 : let ctx = RequestContext::test();
329 1 : let user_info = ComputeUserInfoMaybeEndpoint::parse(&ctx, &options, None, None)?;
330 1 : assert_eq!(user_info.user, "john_doe");
331 1 : assert_eq!(user_info.endpoint_id.as_deref(), Some("bar"));
332 :
333 1 : Ok(())
334 1 : }
335 :
336 : #[test]
337 1 : fn parse_three_endpoints_from_options() -> anyhow::Result<()> {
338 1 : let options = StartupMessageParams::new([
339 1 : ("user", "john_doe"),
340 1 : (
341 1 : "options",
342 1 : "-ckey=1 endpoint=one endpoint=two endpoint=three -c geqo=off",
343 1 : ),
344 1 : ]);
345 1 :
346 1 : let ctx = RequestContext::test();
347 1 : let user_info = ComputeUserInfoMaybeEndpoint::parse(&ctx, &options, None, None)?;
348 1 : assert_eq!(user_info.user, "john_doe");
349 1 : assert!(user_info.endpoint_id.is_none());
350 :
351 1 : Ok(())
352 1 : }
353 :
354 : #[test]
355 1 : fn parse_when_endpoint_and_project_are_in_options() -> anyhow::Result<()> {
356 1 : let options = StartupMessageParams::new([
357 1 : ("user", "john_doe"),
358 1 : ("options", "-ckey=1 endpoint=bar project=foo -c geqo=off"),
359 1 : ]);
360 1 :
361 1 : let ctx = RequestContext::test();
362 1 : let user_info = ComputeUserInfoMaybeEndpoint::parse(&ctx, &options, None, None)?;
363 1 : assert_eq!(user_info.user, "john_doe");
364 1 : assert!(user_info.endpoint_id.is_none());
365 :
366 1 : Ok(())
367 1 : }
368 :
369 : #[test]
370 1 : fn parse_projects_identical() -> anyhow::Result<()> {
371 1 : let options = StartupMessageParams::new([("user", "john_doe"), ("options", "project=baz")]);
372 1 :
373 1 : let sni = Some("baz.localhost");
374 1 : let common_names = Some(["localhost".into()].into());
375 1 :
376 1 : let ctx = RequestContext::test();
377 1 : let user_info =
378 1 : ComputeUserInfoMaybeEndpoint::parse(&ctx, &options, sni, common_names.as_ref())?;
379 1 : assert_eq!(user_info.user, "john_doe");
380 1 : assert_eq!(user_info.endpoint_id.as_deref(), Some("baz"));
381 :
382 1 : Ok(())
383 1 : }
384 :
385 : #[test]
386 1 : fn parse_multi_common_names() -> anyhow::Result<()> {
387 1 : let options = StartupMessageParams::new([("user", "john_doe")]);
388 1 :
389 1 : let common_names = Some(["a.com".into(), "b.com".into()].into());
390 1 : let sni = Some("p1.a.com");
391 1 : let ctx = RequestContext::test();
392 1 : let user_info =
393 1 : ComputeUserInfoMaybeEndpoint::parse(&ctx, &options, sni, common_names.as_ref())?;
394 1 : assert_eq!(user_info.endpoint_id.as_deref(), Some("p1"));
395 :
396 1 : let common_names = Some(["a.com".into(), "b.com".into()].into());
397 1 : let sni = Some("p1.b.com");
398 1 : let ctx = RequestContext::test();
399 1 : let user_info =
400 1 : ComputeUserInfoMaybeEndpoint::parse(&ctx, &options, sni, common_names.as_ref())?;
401 1 : assert_eq!(user_info.endpoint_id.as_deref(), Some("p1"));
402 :
403 1 : Ok(())
404 1 : }
405 :
406 : #[test]
407 1 : fn parse_projects_different() {
408 1 : let options =
409 1 : StartupMessageParams::new([("user", "john_doe"), ("options", "project=first")]);
410 1 :
411 1 : let sni = Some("second.localhost");
412 1 : let common_names = Some(["localhost".into()].into());
413 1 :
414 1 : let ctx = RequestContext::test();
415 1 : let err = ComputeUserInfoMaybeEndpoint::parse(&ctx, &options, sni, common_names.as_ref())
416 1 : .expect_err("should fail");
417 1 : match err {
418 1 : InconsistentProjectNames { domain, option } => {
419 1 : assert_eq!(option, "first");
420 1 : assert_eq!(domain, "second");
421 : }
422 0 : _ => panic!("bad error: {err:?}"),
423 : }
424 1 : }
425 :
426 : #[test]
427 1 : fn parse_inconsistent_sni() {
428 1 : let options = StartupMessageParams::new([("user", "john_doe")]);
429 1 :
430 1 : let sni = Some("project.localhost");
431 1 : let common_names = Some(["example.com".into()].into());
432 1 :
433 1 : let ctx = RequestContext::test();
434 1 : let err = ComputeUserInfoMaybeEndpoint::parse(&ctx, &options, sni, common_names.as_ref())
435 1 : .expect_err("should fail");
436 1 : match err {
437 1 : UnknownCommonName { cn } => {
438 1 : assert_eq!(cn, "localhost");
439 : }
440 0 : _ => panic!("bad error: {err:?}"),
441 : }
442 1 : }
443 :
444 : #[test]
445 1 : fn parse_neon_options() -> anyhow::Result<()> {
446 1 : let options = StartupMessageParams::new([
447 1 : ("user", "john_doe"),
448 1 : ("options", "neon_lsn:0/2 neon_endpoint_type:read_write"),
449 1 : ]);
450 1 :
451 1 : let sni = Some("project.localhost");
452 1 : let common_names = Some(["localhost".into()].into());
453 1 : let ctx = RequestContext::test();
454 1 : let user_info =
455 1 : ComputeUserInfoMaybeEndpoint::parse(&ctx, &options, sni, common_names.as_ref())?;
456 1 : assert_eq!(user_info.endpoint_id.as_deref(), Some("project"));
457 1 : assert_eq!(
458 1 : user_info.options.get_cache_key("project"),
459 1 : "project endpoint_type:read_write lsn:0/2"
460 1 : );
461 :
462 1 : Ok(())
463 1 : }
464 :
465 : #[test]
466 1 : fn test_check_peer_addr_is_in_list() {
467 4 : fn check(v: serde_json::Value) -> bool {
468 4 : let peer_addr = IpAddr::from([127, 0, 0, 1]);
469 4 : let ip_list: Vec<IpPattern> = serde_json::from_value(v).unwrap();
470 4 : check_peer_addr_is_in_list(&peer_addr, &ip_list)
471 4 : }
472 :
473 1 : assert!(check(json!([])));
474 1 : assert!(check(json!(["127.0.0.1"])));
475 1 : assert!(!check(json!(["8.8.8.8"])));
476 : // If there is an incorrect address, it will be skipped.
477 1 : assert!(check(json!(["88.8.8", "127.0.0.1"])));
478 1 : }
479 : #[test]
480 1 : fn test_parse_ip_v4() -> anyhow::Result<()> {
481 1 : let peer_addr = IpAddr::from([127, 0, 0, 1]);
482 : // Ok
483 1 : assert_eq!(parse_ip_pattern("127.0.0.1")?, IpPattern::Single(peer_addr));
484 1 : assert_eq!(
485 1 : parse_ip_pattern("127.0.0.1/31")?,
486 1 : IpPattern::Subnet(ipnet::IpNet::new(peer_addr, 31)?)
487 : );
488 1 : assert_eq!(
489 1 : parse_ip_pattern("0.0.0.0-200.0.1.2")?,
490 1 : IpPattern::Range(IpAddr::from([0, 0, 0, 0]), IpAddr::from([200, 0, 1, 2]))
491 : );
492 :
493 : // Error
494 1 : assert!(parse_ip_pattern("300.0.1.2").is_err());
495 1 : assert!(parse_ip_pattern("30.1.2").is_err());
496 1 : assert!(parse_ip_pattern("127.0.0.1/33").is_err());
497 1 : assert!(parse_ip_pattern("127.0.0.1-127.0.3").is_err());
498 1 : assert!(parse_ip_pattern("1234.0.0.1-127.0.3.0").is_err());
499 1 : Ok(())
500 1 : }
501 :
502 : #[test]
503 1 : fn test_check_ipv4() -> anyhow::Result<()> {
504 1 : let peer_addr = IpAddr::from([127, 0, 0, 1]);
505 1 : let peer_addr_next = IpAddr::from([127, 0, 0, 2]);
506 1 : let peer_addr_prev = IpAddr::from([127, 0, 0, 0]);
507 1 : // Success
508 1 : assert!(check_ip(&peer_addr, &IpPattern::Single(peer_addr)));
509 1 : assert!(check_ip(
510 1 : &peer_addr,
511 1 : &IpPattern::Subnet(ipnet::IpNet::new(peer_addr_prev, 31)?)
512 : ));
513 1 : assert!(check_ip(
514 1 : &peer_addr,
515 1 : &IpPattern::Subnet(ipnet::IpNet::new(peer_addr_next, 30)?)
516 : ));
517 1 : assert!(check_ip(
518 1 : &peer_addr,
519 1 : &IpPattern::Range(IpAddr::from([0, 0, 0, 0]), IpAddr::from([200, 0, 1, 2]))
520 1 : ));
521 1 : assert!(check_ip(
522 1 : &peer_addr,
523 1 : &IpPattern::Range(peer_addr, peer_addr)
524 1 : ));
525 :
526 : // Not success
527 1 : assert!(!check_ip(&peer_addr, &IpPattern::Single(peer_addr_prev)));
528 1 : assert!(!check_ip(
529 1 : &peer_addr,
530 1 : &IpPattern::Subnet(ipnet::IpNet::new(peer_addr_next, 31)?)
531 : ));
532 1 : assert!(!check_ip(
533 1 : &peer_addr,
534 1 : &IpPattern::Range(IpAddr::from([0, 0, 0, 0]), peer_addr_prev)
535 1 : ));
536 1 : assert!(!check_ip(
537 1 : &peer_addr,
538 1 : &IpPattern::Range(peer_addr_next, IpAddr::from([128, 0, 0, 0]))
539 1 : ));
540 : // There is no check that for range start <= end. But it's fine as long as for all this cases the result is false.
541 1 : assert!(!check_ip(
542 1 : &peer_addr,
543 1 : &IpPattern::Range(peer_addr, peer_addr_prev)
544 1 : ));
545 1 : Ok(())
546 1 : }
547 :
548 : #[test]
549 1 : fn test_connection_blocker() {
550 3 : fn check(v: serde_json::Value) -> bool {
551 3 : let peer_addr = IpAddr::from([127, 0, 0, 1]);
552 3 : let ip_list: Vec<IpPattern> = serde_json::from_value(v).unwrap();
553 3 : check_peer_addr_is_in_list(&peer_addr, &ip_list)
554 3 : }
555 :
556 1 : assert!(check(json!([])));
557 1 : assert!(check(json!(["127.0.0.1"])));
558 1 : assert!(!check(json!(["255.255.255.255"])));
559 1 : }
560 : }
|