Skip to main content

auth/
user_provider.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15pub(crate) mod static_user_provider;
16pub(crate) mod watch_file_user_provider;
17
18use std::collections::HashMap;
19use std::fs::File;
20use std::io::BufRead;
21use std::path::Path;
22use std::{fmt, io};
23
24use common_base::secrets::ExposeSecret;
25use common_telemetry::warn;
26use pbkdf2::pbkdf2_hmac;
27use sha2::Sha256;
28use snafu::{OptionExt, ResultExt, ensure};
29use subtle::ConstantTimeEq;
30
31use crate::common::{
32    DEFAULT_PBKDF2_SHA256_SALT_LEN, Identity, MAX_PBKDF2_SHA256_ITERATIONS,
33    MAX_PBKDF2_SHA256_SALT_LEN, PBKDF2_SHA256_HASH_LEN, PG_SCRAM_SHA256_KEY_LEN, Password,
34    PgScramSha256Verifier, auth_mysql_with_hash_stage_2,
35};
36use crate::error::{
37    IllegalParamSnafu, InvalidConfigSnafu, IoSnafu, Result, UnsupportedAuthMethodSnafu,
38    UnsupportedPasswordTypeSnafu, UserNotFoundSnafu, UserPasswordMismatchSnafu,
39};
40use crate::user_info::{DefaultUserInfo, PermissionMode};
41use crate::{UserInfoRef, auth_mysql};
42
43#[async_trait::async_trait]
44pub trait UserProvider: Send + Sync {
45    fn name(&self) -> &str;
46
47    /// Checks whether a user is valid and allowed to access the database.
48    async fn authenticate(&self, id: Identity<'_>, password: Password<'_>) -> Result<UserInfoRef>;
49
50    /// Checks whether a connection request
51    /// from a certain user to a certain catalog/schema is legal.
52    /// This method should be called after [authenticate()](UserProvider::authenticate()).
53    async fn authorize(&self, catalog: &str, schema: &str, user_info: &UserInfoRef) -> Result<()>;
54
55    /// Combination of [authenticate()](UserProvider::authenticate()) and [authorize()](UserProvider::authorize()).
56    /// In most cases it's preferred for both convenience and performance.
57    async fn auth(
58        &self,
59        id: Identity<'_>,
60        password: Password<'_>,
61        catalog: &str,
62        schema: &str,
63    ) -> Result<UserInfoRef> {
64        let user_info = self.authenticate(id, password).await?;
65        self.authorize(catalog, schema, &user_info).await?;
66        Ok(user_info)
67    }
68
69    /// Authenticates and authorizes an opaque bearer token (e.g. a JWT or an
70    /// OAuth2 access token).
71    ///
72    /// Unlike [auth()](Self::auth), the caller has no `Identity`/`Password` —
73    /// the provider validates the token and *derives* the identity from it.
74    /// The token is opaque to the server, so JWT/JWKS/OIDC validation policy
75    /// stays pluggable and out of core.
76    ///
77    /// The default rejects token auth with
78    /// [`Error::UnsupportedAuthMethod`], so password-only providers keep
79    /// today's behavior. Providers that support token auth override this to
80    /// validate the token, resolve it to a user, and
81    /// [`authorize`](Self::authorize) the connection.
82    async fn auth_bearer_token(
83        &self,
84        _token: &str,
85        _catalog: &str,
86        _schema: &str,
87    ) -> Result<UserInfoRef> {
88        UnsupportedAuthMethodSnafu {
89            method: "bearer token",
90        }
91        .fail()
92    }
93
94    async fn postgres_auth_info(&self, _id: Identity<'_>) -> Result<PgAuthInfo> {
95        Ok(PgAuthInfo::Cleartext)
96    }
97
98    /// Returns whether this user provider implementation is backed by an external system.
99    fn external(&self) -> bool {
100        false
101    }
102}
103
104pub enum PgAuthInfo {
105    ScramSha256 {
106        verifier: PgScramSha256Verifier,
107        user_info: Option<UserInfoRef>,
108    },
109    Cleartext,
110}
111
112#[derive(Clone)]
113pub(crate) enum PasswordVerifier {
114    PlainText {
115        password: String,
116        /// SCRAM verifier derived once at load time. Precomputing it keeps the
117        /// Postgres SCRAM `server-first-message` (stable salt, fixed iterations)
118        /// and per-connection cost indistinguishable from stored-hash and
119        /// unknown users, instead of running PBKDF2 with a fresh salt on every
120        /// connection.
121        scram: PgScramSha256Verifier,
122    },
123    Pbkdf2Sha256 {
124        iterations: u32,
125        salt: Vec<u8>,
126        hash: Vec<u8>,
127    },
128    MysqlNativePassword {
129        hash_stage_2: Vec<u8>,
130    },
131    PgScramSha256(PgScramSha256Verifier),
132}
133
134impl PartialEq for PasswordVerifier {
135    fn eq(&self, other: &Self) -> bool {
136        // The precomputed SCRAM verifier is a cache derived from the password, so
137        // two plaintext verifiers are equal iff their passwords match.
138        match (self, other) {
139            (
140                PasswordVerifier::PlainText { password: a, .. },
141                PasswordVerifier::PlainText { password: b, .. },
142            ) => a == b,
143            (
144                PasswordVerifier::Pbkdf2Sha256 {
145                    iterations: i1,
146                    salt: s1,
147                    hash: h1,
148                },
149                PasswordVerifier::Pbkdf2Sha256 {
150                    iterations: i2,
151                    salt: s2,
152                    hash: h2,
153                },
154            ) => i1 == i2 && s1 == s2 && h1 == h2,
155            (
156                PasswordVerifier::MysqlNativePassword { hash_stage_2: a },
157                PasswordVerifier::MysqlNativePassword { hash_stage_2: b },
158            ) => a == b,
159            (PasswordVerifier::PgScramSha256(a), PasswordVerifier::PgScramSha256(b)) => a == b,
160            _ => false,
161        }
162    }
163}
164
165impl Eq for PasswordVerifier {}
166
167impl fmt::Debug for PasswordVerifier {
168    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
169        match self {
170            PasswordVerifier::PlainText { .. } => {
171                f.debug_tuple("PlainText").field(&"<REDACTED>").finish()
172            }
173            PasswordVerifier::Pbkdf2Sha256 { iterations, .. } => f
174                .debug_struct("Pbkdf2Sha256")
175                .field("iterations", iterations)
176                .field("salt", &"<REDACTED>")
177                .field("hash", &"<REDACTED>")
178                .finish(),
179            PasswordVerifier::MysqlNativePassword { .. } => f
180                .debug_struct("MysqlNativePassword")
181                .field("hash_stage_2", &"<REDACTED>")
182                .finish(),
183            PasswordVerifier::PgScramSha256(_) => f
184                .debug_struct("PgScramSha256")
185                .field("verifier", &"<REDACTED>")
186                .finish(),
187        }
188    }
189}
190
191impl PasswordVerifier {
192    /// Builds a plaintext verifier, precomputing a stable SCRAM verifier so the
193    /// Postgres SCRAM handshake for this user carries a stable salt and runs no
194    /// per-connection PBKDF2. Uses [`DEFAULT_PBKDF2_SHA256_ITERATIONS`] to match
195    /// the mock verifier handed to unknown users.
196    fn plain_text(password: String) -> Option<Self> {
197        let salt = rand::random::<[u8; DEFAULT_PBKDF2_SHA256_SALT_LEN]>();
198        let scram = PgScramSha256Verifier::from_password(
199            password.as_bytes(),
200            &salt,
201            crate::DEFAULT_PBKDF2_SHA256_ITERATIONS,
202        )
203        .ok()?;
204        Some(Self::PlainText { password, scram })
205    }
206
207    fn parse(input: &str) -> Option<Self> {
208        if let Some(password) = input.strip_prefix("plain:") {
209            return Self::plain_text(password.to_string());
210        }
211
212        if let Some(verifier) = input.strip_prefix("pbkdf2_sha256:") {
213            let mut parts = verifier.split(':');
214            let iterations = parts.next()?.parse::<u32>().ok()?;
215            let salt = hex::decode(parts.next()?).ok()?;
216            let hash = hex::decode(parts.next()?).ok()?;
217            if parts.next().is_some()
218                || iterations == 0
219                || iterations > MAX_PBKDF2_SHA256_ITERATIONS
220                || salt.is_empty()
221                || salt.len() > MAX_PBKDF2_SHA256_SALT_LEN
222                || hash.len() != PBKDF2_SHA256_HASH_LEN
223            {
224                return None;
225            }
226
227            return Some(Self::Pbkdf2Sha256 {
228                iterations,
229                salt,
230                hash,
231            });
232        }
233
234        if let Some(verifier) = input.strip_prefix("mysql_native_password:") {
235            let hash_stage_2 = hex::decode(verifier).ok()?;
236            if hash_stage_2.len() != 20 {
237                return None;
238            }
239
240            return Some(Self::MysqlNativePassword { hash_stage_2 });
241        }
242
243        if let Some(verifier) = input.strip_prefix("pg_scram_sha256:") {
244            let mut parts = verifier.split(':');
245            let iterations = parts.next()?.parse::<u32>().ok()?;
246            let salt = hex::decode(parts.next()?).ok()?;
247            let stored_key = hex::decode(parts.next()?).ok()?;
248            let server_key = hex::decode(parts.next()?).ok()?;
249            if parts.next().is_some()
250                || stored_key.len() != PG_SCRAM_SHA256_KEY_LEN
251                || server_key.len() != PG_SCRAM_SHA256_KEY_LEN
252            {
253                return None;
254            }
255
256            return PgScramSha256Verifier::new(iterations, salt, stored_key, server_key)
257                .ok()
258                .map(Self::PgScramSha256);
259        }
260
261        Self::plain_text(input.to_string())
262    }
263
264    fn supports_pg_scram_sha256(&self) -> bool {
265        matches!(
266            self,
267            PasswordVerifier::PlainText { .. } | PasswordVerifier::PgScramSha256(_)
268        )
269    }
270
271    fn to_pg_scram_sha256_verifier(&self) -> Option<PgScramSha256Verifier> {
272        match self {
273            PasswordVerifier::PlainText { scram, .. } => Some(scram.clone()),
274            // Legacy PBKDF2 verifiers were derived without SASLprep, and the
275            // original password is unavailable to normalize them safely.
276            PasswordVerifier::Pbkdf2Sha256 { .. } => None,
277            PasswordVerifier::PgScramSha256(verifier) => Some(verifier.clone()),
278            PasswordVerifier::MysqlNativePassword { .. } => None,
279        }
280    }
281
282    fn verify_plain_text(&self, password: &str) -> bool {
283        match self {
284            PasswordVerifier::PlainText {
285                password: expected, ..
286            } => expected.as_bytes().ct_eq(password.as_bytes()).into(),
287            PasswordVerifier::Pbkdf2Sha256 {
288                iterations,
289                salt,
290                hash,
291            } => {
292                if hash.len() != PBKDF2_SHA256_HASH_LEN {
293                    return false;
294                }
295                let mut actual = [0u8; PBKDF2_SHA256_HASH_LEN];
296                pbkdf2_hmac::<Sha256>(password.as_bytes(), salt, *iterations, &mut actual);
297                hash.as_slice().ct_eq(&actual[..]).into()
298            }
299            PasswordVerifier::MysqlNativePassword { .. } => false,
300            PasswordVerifier::PgScramSha256(verifier) => verifier
301                .verify_plain_password(password.as_bytes())
302                .unwrap_or(false),
303        }
304    }
305
306    fn verify_mysql_native_password(
307        &self,
308        auth_data: &[u8],
309        salt: &[u8],
310        username: &str,
311    ) -> Result<()> {
312        match self {
313            PasswordVerifier::PlainText { password, .. } => {
314                auth_mysql(auth_data, salt, username, password.as_bytes())
315            }
316            PasswordVerifier::MysqlNativePassword { hash_stage_2 } => {
317                auth_mysql_with_hash_stage_2(auth_data, salt, username, hash_stage_2)
318            }
319            PasswordVerifier::Pbkdf2Sha256 { .. } => UnsupportedPasswordTypeSnafu {
320                password_type: "mysql_native_password_with_pbkdf2_sha256_verifier",
321            }
322            .fail(),
323            PasswordVerifier::PgScramSha256(_) => UnsupportedPasswordTypeSnafu {
324                password_type: "mysql_native_password_with_pg_scram_sha256_verifier",
325            }
326            .fail(),
327        }
328    }
329}
330
331/// Type alias for user info map.
332/// Key is username, value is (password verifier, permission_mode).
333pub type UserInfoMap = HashMap<String, (PasswordVerifier, PermissionMode)>;
334
335fn load_credential_from_file(filepath: &str) -> Result<UserInfoMap> {
336    // check valid path
337    let path = Path::new(filepath);
338    if !path.exists() {
339        return InvalidConfigSnafu {
340            value: filepath.to_string(),
341            msg: "UserProvider file must exist",
342        }
343        .fail();
344    }
345
346    ensure!(
347        path.is_file(),
348        InvalidConfigSnafu {
349            value: filepath,
350            msg: "UserProvider file must be a file",
351        }
352    );
353    let file = File::open(path).context(IoSnafu)?;
354    let credential = io::BufReader::new(file)
355        .lines()
356        .enumerate()
357        .map_while(|(idx, line)| match line {
358            Ok(line) => Some((idx, line)),
359            Err(err) => {
360                // A read error (I/O failure or invalid UTF-8) ends the iterator,
361                // so every remaining credential is dropped. Warn instead of
362                // vanishing silently, matching the malformed-line handling below.
363                warn!(
364                    "Failed to read line {} of user provider file {}: {}; \
365                     all remaining credentials are ignored",
366                    idx + 1,
367                    filepath,
368                    err
369                );
370                None
371            }
372        })
373        .filter_map(|(idx, line)| {
374            // The line format is:
375            // - `username=password` - Basic user with default permissions
376            // - `username:permission_mode=password` - User with specific permission mode
377            // - Lines starting with '#' are treated as comments and ignored
378            // - Empty lines are ignored
379            let line = line.trim();
380            if line.is_empty() || line.starts_with('#') {
381                return None;
382            }
383
384            let parsed = parse_credential_line(line);
385            if parsed.is_none() {
386                // Don't log the line: it carries the password/verifier. A common
387                // cause is a plaintext password containing `=`, which splits the
388                // line into more than two parts.
389                warn!(
390                    "Ignoring malformed credential at line {} of user provider file {}: \
391                     expected `username[:permission]=verifier` with exactly one `=` \
392                     (passwords containing `=` are not supported)",
393                    idx + 1,
394                    filepath
395                );
396            }
397            parsed
398        })
399        .collect::<HashMap<String, _>>();
400
401    ensure!(
402        !credential.is_empty(),
403        InvalidConfigSnafu {
404            value: filepath,
405            msg: "UserProvider's file must contains at least one valid credential",
406        }
407    );
408
409    warn_if_pg_scram_disabled(&credential);
410
411    Ok(credential)
412}
413
414/// Returns the users whose verifier cannot back a Postgres SCRAM handshake.
415///
416/// Only [`PasswordVerifier::PlainText`] and [`PasswordVerifier::PgScramSha256`]
417/// support SCRAM. A `mysql_native_password` verifier is a double-SHA1 digest
418/// unrelated to PBKDF2, and a `pbkdf2_sha256` verifier was derived without
419/// SASLprep and cannot be safely reused as a SCRAM secret without the original
420/// password. Either kind forces the whole Postgres endpoint to fall back to
421/// cleartext (see [`postgres_auth_info_with_credential`]).
422fn pg_scram_unsupported_users(users: &UserInfoMap) -> Vec<&str> {
423    users
424        .iter()
425        .filter(|(_, (verifier, _))| !verifier.supports_pg_scram_sha256())
426        .map(|(username, _)| username.as_str())
427        .collect()
428}
429
430/// Warns once per credential load when the set disables Postgres SCRAM, so
431/// operators don't unknowingly serve cleartext passwords over Postgres while
432/// believing SCRAM is in effect.
433pub(crate) fn warn_if_pg_scram_disabled(users: &UserInfoMap) {
434    let unsupported = pg_scram_unsupported_users(users);
435    if !unsupported.is_empty() {
436        warn!(
437            "Postgres SCRAM authentication is disabled: {} of {} user(s) use a \
438             non-SCRAM password verifier {:?}, so all Postgres password \
439             authentication falls back to cleartext. Ensure TLS is enabled; if you \
440             rely on Postgres SCRAM, generate every user's verifier with the \
441             pg_scram_sha256 format.",
442            unsupported.len(),
443            users.len(),
444            unsupported
445        );
446    }
447}
448
449/// Parse a line of credential in the format of `username=password` or `username:permission_mode=password`.
450///
451/// The password part accepts legacy plain text and explicit verifier formats:
452/// - `plain:<password>`
453/// - `pbkdf2_sha256:<iterations>:<hex-encoded-salt>:<hex-encoded-hash>`
454/// - `mysql_native_password:<hex-encoded-sha1-sha1-password>`
455/// - `pg_scram_sha256:<iterations>:<hex-encoded-salt>:<hex-encoded-stored-key>:<hex-encoded-server-key>`
456pub(crate) fn parse_credential_line(
457    line: &str,
458) -> Option<(String, (PasswordVerifier, PermissionMode))> {
459    let parts = line.split('=').collect::<Vec<&str>>();
460    if parts.len() != 2 {
461        return None;
462    }
463
464    let (username_part, password) = (parts[0], parts[1]);
465    let (username, permission_mode) = if let Some((user, perm)) = username_part.split_once(':') {
466        (user, PermissionMode::from_str(perm)?)
467    } else {
468        (username_part, PermissionMode::default())
469    };
470
471    let verifier = PasswordVerifier::parse(password)?;
472
473    Some((username.to_string(), (verifier, permission_mode)))
474}
475
476pub(crate) fn postgres_auth_info_with_credential(
477    users: &UserInfoMap,
478    input_id: Identity<'_>,
479) -> Result<PgAuthInfo> {
480    match input_id {
481        Identity::UserId(username, _) => {
482            ensure!(
483                !username.is_empty(),
484                IllegalParamSnafu {
485                    msg: "blank username"
486                }
487            );
488
489            if !users
490                .values()
491                .all(|(verifier, _)| verifier.supports_pg_scram_sha256())
492            {
493                // PostgreSQL chooses one auth method during startup. Selecting it
494                // per username would expose user or verifier existence.
495                return Ok(PgAuthInfo::Cleartext);
496            }
497
498            if let Some((verifier, permission_mode)) = users.get(username) {
499                if let Some(verifier) = verifier.to_pg_scram_sha256_verifier() {
500                    return Ok(PgAuthInfo::ScramSha256 {
501                        verifier,
502                        user_info: Some(DefaultUserInfo::with_name_and_permission(
503                            username,
504                            *permission_mode,
505                        )),
506                    });
507                }
508
509                return Ok(PgAuthInfo::Cleartext);
510            }
511
512            // Unknown user: hand back a deterministic mock verifier so the SCRAM
513            // handshake is indistinguishable from a real user, without running
514            // PBKDF2 or leaking existence through an unstable salt.
515            Ok(PgAuthInfo::ScramSha256 {
516                verifier: PgScramSha256Verifier::mock_for_unknown_user(username.as_bytes()),
517                user_info: None,
518            })
519        }
520    }
521}
522
523fn authenticate_with_credential(
524    users: &UserInfoMap,
525    input_id: Identity<'_>,
526    input_pwd: Password<'_>,
527) -> Result<UserInfoRef> {
528    match input_id {
529        Identity::UserId(username, _) => {
530            ensure!(
531                !username.is_empty(),
532                IllegalParamSnafu {
533                    msg: "blank username"
534                }
535            );
536            let (verifier, permission_mode) = users.get(username).context(UserNotFoundSnafu {
537                username: username.to_string(),
538            })?;
539
540            match input_pwd {
541                Password::PlainText(pwd) => {
542                    ensure!(
543                        !pwd.expose_secret().is_empty(),
544                        IllegalParamSnafu {
545                            msg: "blank password"
546                        }
547                    );
548                    if verifier.verify_plain_text(pwd.expose_secret()) {
549                        Ok(DefaultUserInfo::with_name_and_permission(
550                            username,
551                            *permission_mode,
552                        ))
553                    } else {
554                        UserPasswordMismatchSnafu {
555                            username: username.to_string(),
556                        }
557                        .fail()
558                    }
559                }
560                Password::MysqlNativePassword(auth_data, salt) => verifier
561                    .verify_mysql_native_password(auth_data, salt, username)
562                    .map(|_| DefaultUserInfo::with_name_and_permission(username, *permission_mode)),
563                Password::PgMD5(_, _) => UnsupportedPasswordTypeSnafu {
564                    password_type: "pg_md5",
565                }
566                .fail(),
567            }
568        }
569    }
570}
571#[cfg(test)]
572mod tests {
573    use digest::Digest;
574    use sha1::Sha1;
575
576    use super::*;
577    use crate::common::{format_pg_scram_sha256_password_verifier, mysql_native_password_hash};
578
579    fn plain(password: &str) -> PasswordVerifier {
580        PasswordVerifier::plain_text(password.to_string()).unwrap()
581    }
582
583    fn sha1_one(data: &[u8]) -> Vec<u8> {
584        let mut hasher = Sha1::new();
585        hasher.update(data);
586        hasher.finalize().to_vec()
587    }
588
589    fn mysql_native_password_auth_data(password: &str, salt: &[u8]) -> Vec<u8> {
590        let hash_stage_1 = sha1_one(password.as_bytes());
591        let hash_stage_2 = mysql_native_password_hash(password.as_bytes());
592        let mut hasher = Sha1::new();
593        hasher.update(salt);
594        hasher.update(hash_stage_2);
595        let scramble = hasher.finalize();
596
597        hash_stage_1
598            .iter()
599            .zip(scramble.iter())
600            .map(|(lhs, rhs)| lhs ^ rhs)
601            .collect()
602    }
603
604    #[test]
605    fn test_parse_credential_line() {
606        // Basic username=password format
607        let result = parse_credential_line("admin=password123");
608        assert_eq!(
609            result,
610            Some((
611                "admin".to_string(),
612                (plain("password123"), PermissionMode::default())
613            ))
614        );
615
616        // Username with permission mode
617        let result = parse_credential_line("user:ReadOnly=secret");
618        assert_eq!(
619            result,
620            Some((
621                "user".to_string(),
622                (plain("secret"), PermissionMode::ReadOnly)
623            ))
624        );
625        let result = parse_credential_line("user:ro=secret");
626        assert_eq!(
627            result,
628            Some((
629                "user".to_string(),
630                (plain("secret"), PermissionMode::ReadOnly)
631            ))
632        );
633        // Username with WriteOnly permission mode
634        let result = parse_credential_line("writer:WriteOnly=mypass");
635        assert_eq!(
636            result,
637            Some((
638                "writer".to_string(),
639                (plain("mypass"), PermissionMode::WriteOnly)
640            ))
641        );
642
643        // Username with 'wo' as WriteOnly permission shorthand
644        let result = parse_credential_line("writer:wo=mypass");
645        assert_eq!(
646            result,
647            Some((
648                "writer".to_string(),
649                (plain("mypass"), PermissionMode::WriteOnly)
650            ))
651        );
652
653        // Username with complex password containing special characters
654        let result = parse_credential_line("admin:rw=p@ssw0rd!123");
655        assert_eq!(
656            result,
657            Some((
658                "admin".to_string(),
659                (plain("p@ssw0rd!123"), PermissionMode::ReadWrite)
660            ))
661        );
662
663        // Username with spaces should be preserved
664        let result = parse_credential_line("user name:WriteOnly=password");
665        assert_eq!(
666            result,
667            Some((
668                "user name".to_string(),
669                (plain("password"), PermissionMode::WriteOnly)
670            ))
671        );
672
673        let result = parse_credential_line("user=plain:password");
674        assert_eq!(
675            result,
676            Some((
677                "user".to_string(),
678                (plain("password"), PermissionMode::default())
679            ))
680        );
681
682        let iterations = 4096;
683        let salt = b"salt";
684        let mut hash = [0u8; 32];
685        pbkdf2_hmac::<Sha256>("password".as_bytes(), salt, iterations, &mut hash);
686        let result = parse_credential_line(&format!(
687            "user=pbkdf2_sha256:{iterations}:{}:{}",
688            hex::encode(salt),
689            hex::encode(hash)
690        ));
691        assert_eq!(
692            result,
693            Some((
694                "user".to_string(),
695                (
696                    PasswordVerifier::Pbkdf2Sha256 {
697                        iterations,
698                        salt: salt.to_vec(),
699                        hash: hash.to_vec(),
700                    },
701                    PermissionMode::default()
702                )
703            ))
704        );
705
706        let result = parse_credential_line("user=pbkdf2_sha256:4096:not-hex:abcd");
707        assert_eq!(result, None);
708
709        // A well-formed but truncated hash must be rejected: a short hash would let
710        // many wrong passwords pass by matching only a few derived bytes.
711        let result = parse_credential_line(&format!(
712            "user=pbkdf2_sha256:4096:{}:abcd",
713            hex::encode(salt)
714        ));
715        assert_eq!(result, None);
716
717        let result = parse_credential_line(&format!(
718            "user=pbkdf2_sha256:{}:{}:{}",
719            MAX_PBKDF2_SHA256_ITERATIONS + 1,
720            hex::encode(salt),
721            hex::encode(hash)
722        ));
723        assert_eq!(result, None);
724
725        let hash_stage_2 = mysql_native_password_hash("password".as_bytes());
726        let result = parse_credential_line(&format!(
727            "user=mysql_native_password:{}",
728            hex::encode(&hash_stage_2)
729        ));
730        assert_eq!(
731            result,
732            Some((
733                "user".to_string(),
734                (
735                    PasswordVerifier::MysqlNativePassword { hash_stage_2 },
736                    PermissionMode::default()
737                )
738            ))
739        );
740
741        let result = parse_credential_line("user=mysql_native_password:abcd");
742        assert_eq!(result, None);
743
744        let verifier =
745            format_pg_scram_sha256_password_verifier(b"password", b"salt", 4096).unwrap();
746        let result = parse_credential_line(&format!("user={verifier}"));
747        assert!(matches!(
748            result,
749            Some((
750                _,
751                (
752                    PasswordVerifier::PgScramSha256(PgScramSha256Verifier { .. }),
753                    PermissionMode::ReadWrite
754                )
755            ))
756        ));
757
758        let result = parse_credential_line("user=pg_scram_sha256:4096:73616c74:abcd:abcd");
759        assert_eq!(result, None);
760
761        // Invalid format - no equals sign
762        let result = parse_credential_line("invalid_line");
763        assert_eq!(result, None);
764
765        // Invalid format - multiple equals signs
766        let result = parse_credential_line("user=pass=word");
767        assert_eq!(result, None);
768
769        for line in [
770            "user:readonyl=password",
771            "user:=password",
772            "user:arbitrary=password",
773        ] {
774            assert_eq!(parse_credential_line(line), None);
775        }
776
777        // Empty password
778        let result = parse_credential_line("user=");
779        assert_eq!(
780            result,
781            Some(("user".to_string(), (plain(""), PermissionMode::default())))
782        );
783
784        // Empty username
785        let result = parse_credential_line("=password");
786        assert_eq!(
787            result,
788            Some((
789                "".to_string(),
790                (plain("password"), PermissionMode::default())
791            ))
792        );
793    }
794
795    #[test]
796    fn test_authenticate_with_mysql_native_password_verifier() {
797        let password = "password";
798        let salt = b"12345678901234567890";
799        let hash_stage_2 = mysql_native_password_hash(password.as_bytes());
800        let auth_data = mysql_native_password_auth_data(password, salt);
801        let users = HashMap::from([(
802            "user".to_string(),
803            (
804                PasswordVerifier::MysqlNativePassword { hash_stage_2 },
805                PermissionMode::default(),
806            ),
807        )]);
808
809        let result = authenticate_with_credential(
810            &users,
811            Identity::UserId("user", None),
812            Password::MysqlNativePassword(&auth_data, salt),
813        );
814
815        assert!(result.is_ok());
816    }
817
818    #[test]
819    fn test_authenticate_with_plain_text_mysql_native_password() {
820        let password = "password";
821        let salt = b"12345678901234567890";
822        let auth_data = mysql_native_password_auth_data(password, salt);
823        let users = HashMap::from([(
824            "user".to_string(),
825            (
826                PasswordVerifier::plain_text(password.to_string()).unwrap(),
827                PermissionMode::default(),
828            ),
829        )]);
830
831        let result = authenticate_with_credential(
832            &users,
833            Identity::UserId("user", None),
834            Password::MysqlNativePassword(&auth_data, salt),
835        );
836
837        assert!(result.is_ok());
838    }
839
840    #[test]
841    fn test_pbkdf2_sha256_rejects_mysql_native_password() {
842        let password = "password";
843        let salt = b"salt";
844        let iterations = 4096;
845        let mut hash = [0u8; 32];
846        pbkdf2_hmac::<Sha256>(password.as_bytes(), salt, iterations, &mut hash);
847        let users = HashMap::from([(
848            "user".to_string(),
849            (
850                PasswordVerifier::Pbkdf2Sha256 {
851                    iterations,
852                    salt: salt.to_vec(),
853                    hash: hash.to_vec(),
854                },
855                PermissionMode::default(),
856            ),
857        )]);
858        let mysql_salt = b"12345678901234567890";
859        let auth_data = mysql_native_password_auth_data(password, mysql_salt);
860
861        let result = authenticate_with_credential(
862            &users,
863            Identity::UserId("user", None),
864            Password::MysqlNativePassword(&auth_data, mysql_salt),
865        );
866
867        assert!(result.is_err());
868    }
869
870    #[test]
871    fn test_authenticate_with_pg_scram_sha256_verifier_plain_text() {
872        let verifier =
873            format_pg_scram_sha256_password_verifier(b"password", b"salt", 4096).unwrap();
874        let (_, user) = parse_credential_line(&format!("user={verifier}")).unwrap();
875        let users = HashMap::from([("user".to_string(), user)]);
876
877        let result = authenticate_with_credential(
878            &users,
879            Identity::UserId("user", None),
880            Password::PlainText("password".to_string().into()),
881        );
882        assert!(result.is_ok());
883
884        let result = authenticate_with_credential(
885            &users,
886            Identity::UserId("user", None),
887            Password::PlainText("wrong".to_string().into()),
888        );
889        assert!(result.is_err());
890    }
891
892    #[test]
893    fn test_plain_text_scram_verifier_is_stable() {
894        let verifier = PasswordVerifier::plain_text("password".to_string()).unwrap();
895        let first = verifier.to_pg_scram_sha256_verifier().unwrap();
896        let second = verifier.to_pg_scram_sha256_verifier().unwrap();
897
898        // A plaintext-backed user must present a stable salt and fixed iterations
899        // across connections without re-running PBKDF2, otherwise the SCRAM
900        // server-first message (and its timing) leaks that the user exists.
901        assert_eq!(first.salt(), second.salt());
902        assert_eq!(first.salt().len(), DEFAULT_PBKDF2_SHA256_SALT_LEN);
903        assert_eq!(first.iterations(), crate::DEFAULT_PBKDF2_SHA256_ITERATIONS);
904
905        // The derived verifier must still accept the real password.
906        assert!(first.verify_plain_password(b"password").unwrap());
907        assert!(!first.verify_plain_password(b"wrong").unwrap());
908    }
909
910    #[test]
911    fn test_postgres_auth_info_uses_scram_for_unknown_user() {
912        let verifier =
913            format_pg_scram_sha256_password_verifier(b"password", b"salt", 4096).unwrap();
914        let (_, user) = parse_credential_line(&format!("user={verifier}")).unwrap();
915        let users = HashMap::from([("user".to_string(), user)]);
916
917        let auth_info =
918            postgres_auth_info_with_credential(&users, Identity::UserId("unknown", None)).unwrap();
919        assert!(matches!(
920            auth_info,
921            PgAuthInfo::ScramSha256 {
922                user_info: None,
923                ..
924            }
925        ));
926    }
927
928    #[test]
929    fn test_postgres_auth_info_falls_back_to_cleartext() {
930        let hash_stage_2 = mysql_native_password_hash("password".as_bytes());
931        let users = HashMap::from([(
932            "user".to_string(),
933            (
934                PasswordVerifier::MysqlNativePassword { hash_stage_2 },
935                PermissionMode::default(),
936            ),
937        )]);
938
939        let auth_info =
940            postgres_auth_info_with_credential(&users, Identity::UserId("user", None)).unwrap();
941        assert!(matches!(auth_info, PgAuthInfo::Cleartext));
942
943        let auth_info =
944            postgres_auth_info_with_credential(&users, Identity::UserId("unknown", None)).unwrap();
945        assert!(matches!(auth_info, PgAuthInfo::Cleartext));
946    }
947
948    #[test]
949    fn test_postgres_auth_info_with_pbkdf2_falls_back_to_cleartext() {
950        let iterations = 4096;
951        let salt = b"salt";
952        let password = "pass\u{00a0}word";
953        let mut hash = [0u8; PBKDF2_SHA256_HASH_LEN];
954        pbkdf2_hmac::<Sha256>(password.as_bytes(), salt, iterations, &mut hash);
955        let users = HashMap::from([(
956            "user".to_string(),
957            (
958                PasswordVerifier::Pbkdf2Sha256 {
959                    iterations,
960                    salt: salt.to_vec(),
961                    hash: hash.to_vec(),
962                },
963                PermissionMode::default(),
964            ),
965        )]);
966
967        let auth_info =
968            postgres_auth_info_with_credential(&users, Identity::UserId("user", None)).unwrap();
969        assert!(matches!(auth_info, PgAuthInfo::Cleartext));
970
971        assert!(
972            authenticate_with_credential(
973                &users,
974                Identity::UserId("user", None),
975                Password::PlainText(password.to_string().into()),
976            )
977            .is_ok()
978        );
979    }
980
981    #[test]
982    fn test_postgres_auth_info_mixed_verifiers_fall_back_to_cleartext() {
983        let verifier =
984            format_pg_scram_sha256_password_verifier(b"password", b"salt", 4096).unwrap();
985        let (_, scram_user) = parse_credential_line(&format!("scram={verifier}")).unwrap();
986        let mysql_user = (
987            PasswordVerifier::MysqlNativePassword {
988                hash_stage_2: mysql_native_password_hash("password".as_bytes()),
989            },
990            PermissionMode::default(),
991        );
992        let users = HashMap::from([
993            ("scram".to_string(), scram_user),
994            ("mysql".to_string(), mysql_user),
995        ]);
996
997        let auth_info =
998            postgres_auth_info_with_credential(&users, Identity::UserId("scram", None)).unwrap();
999        assert!(matches!(auth_info, PgAuthInfo::Cleartext));
1000
1001        let auth_info =
1002            postgres_auth_info_with_credential(&users, Identity::UserId("unknown", None)).unwrap();
1003        assert!(matches!(auth_info, PgAuthInfo::Cleartext));
1004    }
1005
1006    #[test]
1007    fn test_pg_scram_unsupported_users() {
1008        let scram_verifier =
1009            format_pg_scram_sha256_password_verifier(b"password", b"salt", 4096).unwrap();
1010        let (_, scram_user) = parse_credential_line(&format!("scram={scram_verifier}")).unwrap();
1011
1012        let mut hash = [0u8; PBKDF2_SHA256_HASH_LEN];
1013        pbkdf2_hmac::<Sha256>(b"password", b"salt", 4096, &mut hash);
1014
1015        let users = HashMap::from([
1016            (
1017                "plain".to_string(),
1018                (plain("password"), PermissionMode::default()),
1019            ),
1020            ("scram".to_string(), scram_user),
1021            (
1022                "pbkdf2".to_string(),
1023                (
1024                    PasswordVerifier::Pbkdf2Sha256 {
1025                        iterations: 4096,
1026                        salt: b"salt".to_vec(),
1027                        hash: hash.to_vec(),
1028                    },
1029                    PermissionMode::default(),
1030                ),
1031            ),
1032            (
1033                "mysql".to_string(),
1034                (
1035                    PasswordVerifier::MysqlNativePassword {
1036                        hash_stage_2: mysql_native_password_hash(b"password"),
1037                    },
1038                    PermissionMode::default(),
1039                ),
1040            ),
1041        ]);
1042
1043        let mut unsupported = pg_scram_unsupported_users(&users);
1044        unsupported.sort();
1045        // A pbkdf2_sha256 verifier is flagged alongside mysql_native_password:
1046        // both force Postgres to fall back to cleartext, while plain and
1047        // pg_scram back SCRAM.
1048        assert_eq!(unsupported, vec!["mysql", "pbkdf2"]);
1049    }
1050
1051    #[test]
1052    fn test_password_verifier_debug_redacts_secrets() {
1053        let debug = format!(
1054            "{:?}",
1055            PasswordVerifier::plain_text("secret".to_string()).unwrap()
1056        );
1057        assert!(debug.contains("<REDACTED>"));
1058        assert!(!debug.contains("secret"));
1059
1060        let debug = format!(
1061            "{:?}",
1062            PasswordVerifier::Pbkdf2Sha256 {
1063                iterations: 4096,
1064                salt: b"super-secret-salt".to_vec(),
1065                hash: b"super-secret-hash".to_vec(),
1066            }
1067        );
1068        assert!(debug.contains("Pbkdf2Sha256"));
1069        assert!(debug.contains("4096"));
1070        assert!(!debug.contains("super-secret-salt"));
1071        assert!(!debug.contains("super-secret-hash"));
1072
1073        let debug = format!(
1074            "{:?}",
1075            PasswordVerifier::MysqlNativePassword {
1076                hash_stage_2: b"super-secret-hash".to_vec(),
1077            }
1078        );
1079        assert!(debug.contains("MysqlNativePassword"));
1080        assert!(!debug.contains("super-secret-hash"));
1081    }
1082}