mirror of
https://github.com/neondatabase/neon.git
synced 2026-01-14 08:52:56 +00:00
This patch attempts to fix some of the technical debt we had to introduce in previous patches.
91 lines
2.5 KiB
Rust
91 lines
2.5 KiB
Rust
//! User credentials used in authentication.
|
|
|
|
use crate::compute;
|
|
use crate::config::ProxyConfig;
|
|
use crate::error::UserFacingError;
|
|
use crate::stream::PqStream;
|
|
use std::collections::HashMap;
|
|
use thiserror::Error;
|
|
use tokio::io::{AsyncRead, AsyncWrite};
|
|
|
|
#[derive(Debug, Error)]
|
|
pub enum ClientCredsParseError {
|
|
#[error("Parameter `{0}` is missing in startup packet")]
|
|
MissingKey(&'static str),
|
|
}
|
|
|
|
impl UserFacingError for ClientCredsParseError {}
|
|
|
|
/// Various client credentials which we use for authentication.
|
|
/// Note that we don't store any kind of client key or password here.
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub struct ClientCredentials {
|
|
pub user: String,
|
|
pub dbname: String,
|
|
|
|
// New console API requires SNI info to determine the cluster name.
|
|
// Other Auth backends don't need it.
|
|
pub sni_data: Option<String>,
|
|
}
|
|
|
|
impl ClientCredentials {
|
|
pub fn is_existing_user(&self) -> bool {
|
|
// This logic will likely change in the future.
|
|
self.user.ends_with("@zenith")
|
|
}
|
|
}
|
|
|
|
#[derive(Debug, Error)]
|
|
pub enum ProjectNameError {
|
|
#[error("SNI is missing, please upgrade the postgres client library")]
|
|
Missing,
|
|
|
|
#[error("SNI is malformed")]
|
|
Bad,
|
|
}
|
|
|
|
impl UserFacingError for ProjectNameError {}
|
|
|
|
impl ClientCredentials {
|
|
/// Determine project name from SNI.
|
|
pub fn project_name(&self) -> Result<&str, ProjectNameError> {
|
|
// Currently project name is passed as a top level domain
|
|
let sni = self.sni_data.as_ref().ok_or(ProjectNameError::Missing)?;
|
|
let (first, _) = sni.split_once('.').ok_or(ProjectNameError::Bad)?;
|
|
Ok(first)
|
|
}
|
|
}
|
|
|
|
impl TryFrom<HashMap<String, String>> for ClientCredentials {
|
|
type Error = ClientCredsParseError;
|
|
|
|
fn try_from(mut value: HashMap<String, String>) -> Result<Self, Self::Error> {
|
|
let mut get_param = |key| {
|
|
value
|
|
.remove(key)
|
|
.ok_or(ClientCredsParseError::MissingKey(key))
|
|
};
|
|
|
|
let user = get_param("user")?;
|
|
let dbname = get_param("database")?;
|
|
|
|
Ok(Self {
|
|
user,
|
|
dbname,
|
|
sni_data: None,
|
|
})
|
|
}
|
|
}
|
|
|
|
impl ClientCredentials {
|
|
/// Use credentials to authenticate the user.
|
|
pub async fn authenticate(
|
|
self,
|
|
config: &ProxyConfig,
|
|
client: &mut PqStream<impl AsyncRead + AsyncWrite + Unpin + Send>,
|
|
) -> super::Result<compute::NodeInfo> {
|
|
// This method is just a convenient facade for `handle_user`
|
|
super::backend::handle_user(config, client, self).await
|
|
}
|
|
}
|