Skip to main content

halephant_core/auth/
mod.rs

1pub mod pgpass;
2pub mod query;
3pub mod scram;
4
5use tokio::net::TcpStream;
6use tokio_util::codec::Framed;
7use tracing::{debug, trace, warn};
8
9use crate::config::Config;
10use crate::errors;
11use crate::messages;
12use crate::proto::codec::FrontendCodec;
13
14use query::VerifierCache;
15
16// ---------------------------------------------------------------------------
17// Admin upstream connection parameters
18// ---------------------------------------------------------------------------
19
20/// Resolved parameters for the upstream admin connection halephant uses
21/// to run `auth_query`. Built by [`resolve_admin_conn`] from a config
22/// snapshot plus the topology-resolved primary address and pgpass
23/// lookup, then passed down to [`VerifierCache::get`] as a single unit
24/// instead of six scalar arguments.
25pub(crate) struct AdminConn<'a> {
26    pub(crate) addr: &'a str,
27    pub(crate) admin_user: &'a str,
28    pub(crate) admin_database: &'a str,
29    pub(crate) password: Option<&'a str>,
30    pub(crate) auth_query: &'a str,
31    pub(crate) cache_ttl: std::time::Duration,
32    pub(crate) connect_timeout: std::time::Duration,
33}
34
35/// Resolve the admin connection details for the cluster serving `database`.
36/// The `addr` and `password` are supplied by the caller (topology + pgpass
37/// lookups); every other field comes from the cluster config.
38fn resolve_admin_conn<'a>(
39    config: &'a Config,
40    database: &str,
41    addr: &'a str,
42    password: Option<&'a str>,
43) -> Result<AdminConn<'a>, errors::AuthError> {
44    let (_, cluster, _) = config.find_pool(database).ok_or_else(|| {
45        errors::AuthError::VerifierFetch(format!("no pool configured for {database:?}"))
46    })?;
47
48    Ok(AdminConn {
49        addr,
50        admin_user: &cluster.admin_user,
51        admin_database: &cluster.admin_database,
52        password,
53        auth_query: &cluster.auth.query,
54        cache_ttl: cluster.auth.cache_ttl,
55        connect_timeout: cluster.connect_timeout,
56    })
57}
58
59// ---------------------------------------------------------------------------
60// Authenticator — caches verifiers and drives the auth exchange
61// ---------------------------------------------------------------------------
62
63/// Handles client authentication using pool-based user access control and
64/// SCRAM-SHA-256.
65#[derive(Default)]
66pub struct Authenticator {
67    cache: VerifierCache,
68}
69
70impl Authenticator {
71    pub fn new() -> Self {
72        Self::default()
73    }
74
75    /// Authenticate a client connection. On success, the client has received
76    /// `AuthenticationOk`. On failure, the client has received an
77    /// `ErrorResponse` and the connection should be closed.
78    ///
79    /// Responsibilities at this layer:
80    /// - Pool-user policy check (is this `(database, user)` pair allowed?)
81    /// - Verifier resolution: alias the user to its upstream name and
82    ///   fetch the SCRAM verifier from the cache (or via auth query)
83    /// - Error classification into PostgreSQL SQLSTATE codes
84    /// - Tracing span and error reporting
85    ///
86    /// The pure SCRAM wire exchange is delegated to
87    /// [`scram::server::authenticate`].
88    #[tracing::instrument(name = "auth", skip_all, err(Display), fields(
89        db.namespace = %database,
90        user = %user,
91        otel.status_code,
92        otel.status_description,
93    ))]
94    pub async fn authenticate(
95        &self,
96        client: &mut Framed<TcpStream, FrontendCodec>,
97        database: &str,
98        user: &str,
99        config: &Config,
100        admin_addr: &str,
101        admin_password: Option<&str>,
102    ) -> Result<(), errors::AuthError> {
103        async {
104            // Policy: reject unknown `(database, user)` pairs before
105            // performing any upstream work.
106            if !config.is_user_allowed(database, user) {
107                debug!(%database, %user, "rejected: not in pool users list");
108                messages::error::send_fatal(client, "28000", "authentication failed").await;
109                return Err(errors::AuthError::Rejected {
110                    database: database.into(),
111                    user: user.into(),
112                });
113            }
114
115            // Resolve the upstream identity and fetch the verifier.
116            // `find_user` may map the client-facing name to a
117            // different upstream role when `alias` is configured.
118            let admin_conn = resolve_admin_conn(config, database, admin_addr, admin_password)?;
119            let upstream_user = config
120                .find_user(database, user)
121                .map_or(user, |u| u.upstream_name(user));
122
123            let verifier = match tokio::time::timeout(
124                admin_conn.connect_timeout,
125                self.cache.get(upstream_user, &admin_conn),
126            )
127            .await
128            {
129                Ok(Ok(v)) => v,
130                Ok(Err(e)) => {
131                    messages::error::send_fatal(client, "28000", "authentication failed").await;
132                    return Err(e);
133                }
134                Err(_) => {
135                    messages::error::send_fatal(client, "28000", "authentication failed").await;
136                    return Err(errors::AuthError::VerifierFetch(
137                        "verifier fetch timed out".into(),
138                    ));
139                }
140            };
141
142            // Delegate the pure wire exchange. The driver has no
143            // knowledge of `Config` or halephant-level policy.
144            if let Err(e) = scram::server::authenticate(client, verifier).await {
145                if matches!(e, errors::AuthError::InvalidCredentials) {
146                    warn!(%user, %database, "SCRAM authentication failed");
147                }
148                let code = match &e {
149                    errors::AuthError::InvalidCredentials => "28P01",
150                    _ => "28000",
151                };
152                messages::error::send_fatal(client, code, "authentication failed").await;
153                return Err(e);
154            }
155
156            trace!(%user, %database, "SCRAM authentication succeeded");
157            Ok(())
158        }
159        .await
160        .inspect(|()| {
161            tracing::Span::current().record("otel.status_code", "OK");
162        })
163        .inspect_err(|e| {
164            let span = tracing::Span::current();
165            span.record("otel.status_code", "ERROR");
166            span.record("otel.status_description", e.to_string().as_str());
167        })
168    }
169}