Lines
98.18 %
Functions
92.86 %
Branches
100 %
use super::*;
use crate::command::transaction_edit_tests::lock_wait::wait_for_blocked_on;
use crate::db::{get_connection, install_test_pool};
use argon2::{Argon2, PasswordHasher};
use sqlx::PgPool;
use supp_macro::local_db_sqlx_test;
use tokio::sync::OnceCell;
static CONTEXT: OnceCell<()> = OnceCell::const_new();
/// A hash the `argon2` CLI produced, with cost parameters deliberately
/// unlike `Argon2::default()`.
///
/// The break-glass admin is promoted by hand with a hash generated
/// out-of-band (doc/ops/0006, Phase 4a), and that runbook tells the operator
/// the cost settings need not match the seeded row. This is what makes that
/// true: verification reads the parameters out of the PHC string. If it ever
/// stops being true, the operator finds out during an outage, locked out of
/// the account they just promoted.
const CLI_GENERATED_HASH: &str = "$argon2id$v=19$m=4096,t=3,p=1$\
aTltTkFWR2paUHY5Y2pYbVNlR2Rsdz09$QKPc9TsnwNUm7fgdz/JqzHyrYyo4/x2pMvehw5upb8g";
#[test]
fn fold_email_trims_and_lowers_ascii_only() {
assert_eq!(
fold_email(" Ab\u{c4}@EXAMPLE.com\t"),
"ab\u{c4}@example.com"
);
}
fn a_hash_with_foreign_cost_parameters_still_verifies() {
let parsed = PasswordHash::new(CLI_GENERATED_HASH).expect("PHC string parses");
assert!(
Argon2::default()
.verify_password(b"correct horse", &parsed)
.is_ok(),
"the promotion runbook depends on a hash made with other parameters verifying"
.verify_password(b"wrong horse", &parsed)
.is_err()
async fn setup() {
CONTEXT
.get_or_init(|| async {
crate::telemetry::init_test_logging();
})
.await;
async fn insert_user_with_password(id: Uuid, email: &str, plaintext: &str) -> anyhow::Result<()> {
let hash = Argon2::default()
.hash_password(plaintext.as_bytes())
.unwrap()
.to_string();
let mut conn = get_connection().await.unwrap();
sqlx::query!(
"INSERT INTO users (
id, user_name, email, photo, verified,
user_password, user_role, database_name, created_at
) VALUES (
$1, 'Test', $2, 'default.png', TRUE,
$3, 'user', 'db', NOW()
)",
id,
email,
hash,
)
.execute(&mut *conn)
.await?;
Ok(())
#[local_db_sqlx_test]
async fn verify_returns_user_on_correct_password(pool: PgPool) -> anyhow::Result<()> {
let uid = Uuid::new_v4();
insert_user_with_password(uid, "good@example.com", "hunter2").await?;
let v = verify_user_password("good@example.com", "hunter2")
.await?
.expect("match");
assert_eq!(v.user_id, uid);
assert!(!v.ssh_enabled);
async fn verify_returns_none_on_wrong_password(pool: PgPool) -> anyhow::Result<()> {
insert_user_with_password(uid, "wrong@example.com", "hunter2").await?;
let v = verify_user_password("wrong@example.com", "nope").await?;
assert!(v.is_none());
async fn verify_returns_none_for_unknown_email(pool: PgPool) -> anyhow::Result<()> {
let _ = pool;
let v = verify_user_password("nobody@example.com", "whatever").await?;
/// Disable is `verified = FALSE`, and it must close the password path on
/// both surfaces at once: this function is shared by web login and the SSH
/// daemon's password auth.
async fn verify_returns_none_for_a_disabled_user(pool: PgPool) -> anyhow::Result<()> {
insert_user_with_password(uid, "off@example.com", "hunter2").await?;
verify_user_password("off@example.com", "hunter2")
.is_some()
sqlx::query("UPDATE users SET verified = FALSE WHERE id = $1")
.bind(uid)
.execute(&pool)
.is_none()
/// A password change must replace the hash and bump the generation in one
/// go: every token carrying the old value stops verifying the moment it
/// commits.
async fn change_password_bumps_the_generation(pool: PgPool) -> anyhow::Result<()> {
insert_user_with_password(uid, "bump@example.com", "hunter2").await?;
assert_eq!(generation_of(&pool, uid).await?, 0);
change_password(uid, "hunter2", "hunter3").await?;
assert_eq!(generation_of(&pool, uid).await?, 1);
verify_user_password("bump@example.com", "hunter3")
.is_some(),
"the new password must work"
verify_user_password("bump@example.com", "hunter2")
.is_none(),
"the old password must not"
/// A wrong current password must change nothing — in particular it must not
/// bump the generation, which would log the user out of every session.
async fn change_password_refuses_a_wrong_current(pool: PgPool) -> anyhow::Result<()> {
insert_user_with_password(uid, "wrongcur@example.com", "hunter2").await?;
assert!(change_password(uid, "not-it", "hunter3").await.is_err());
verify_user_password("wrongcur@example.com", "hunter2")
"the original password must still work"
/// A disabled account must not be able to change its own password: doing so
/// would let it mint a fresh session generation.
async fn change_password_refuses_a_disabled_user(pool: PgPool) -> anyhow::Result<()> {
insert_user_with_password(uid, "offpw@example.com", "hunter2").await?;
assert!(change_password(uid, "hunter2", "hunter3").await.is_err());
/// The current-password check authorises the write, so it must be part of
/// it. Two changes racing on the same old password would otherwise both
/// verify, and the loser's new password would be silently overwritten by a
/// caller that never knew it.
async fn change_password_serialises_a_concurrent_change(pool: PgPool) -> anyhow::Result<()> {
insert_user_with_password(uid, "race@example.com", "hunter2").await?;
// Hold the row, so the command blocks on the lock rather than racing it.
let mut blocker = pool.begin().await?;
sqlx::query("SELECT user_password FROM users WHERE id = $1 FOR UPDATE")
.fetch_one(&mut *blocker)
let racing = tokio::spawn(async move { change_password(uid, "hunter2", "loser").await });
let mut probe = pool.acquire().await?;
wait_for_blocked_on(&mut probe, 1).await?;
let winner = Argon2::default()
.hash_password(b"winner")
.expect("hash")
sqlx::query(
"UPDATE users SET user_password = $2, session_generation = session_generation + 1 \
WHERE id = $1",
.bind(&winner)
.execute(&mut *blocker)
blocker.commit().await?;
matches!(racing.await?, Err(CmdError::Args(_))),
"the old password must not authorise a write once another change has committed"
verify_user_password("race@example.com", "winner")
"the committed change must survive"
verify_user_password("race@example.com", "loser")
async fn generation_of(pool: &PgPool, user_id: Uuid) -> anyhow::Result<i32> {
Ok(
sqlx::query_scalar("SELECT session_generation FROM users WHERE id = $1")
.bind(user_id)
.fetch_one(pool)
.await?,
async fn verify_is_case_insensitive_on_email(pool: PgPool) -> anyhow::Result<()> {
insert_user_with_password(uid, "mixed@example.com", "pw").await?;
let v = verify_user_password("MIXED@EXAMPLE.COM", "pw")
async fn register(email: &str) -> Result<Account, CmdError> {
.hash_password(b"pw")
.map_err(|_| CmdError::Server(ServerError::PasswordHash))?
create_user(NewUser {
id: Uuid::new_v4(),
name: "Reg",
password_hash: &hash,
database_name: "db",
jwt_public_key: "key",
.await
async fn registration_stores_the_folded_email_and_finds_it_taken(
pool: PgPool,
) -> anyhow::Result<()> {
let account = register(" Mixed@EXAMPLE.com ").await?;
assert_eq!(account.email, "mixed@example.com");
assert!(email_taken("mixed@example.COM").await?);
assert!(email_taken(" MIXED@example.com ").await?);
assert!(!email_taken("other@example.com").await?);
/// Whether `lower()` folds non-ASCII letters depends on the database locale;
/// the taken check must give the verdict the unique index gives.
async fn email_taken_agrees_with_the_unique_index(pool: PgPool) -> anyhow::Result<()> {
register("\u{c4}@example.com").await?;
let taken = email_taken("\u{e4}@example.com").await?;
let second = register("\u{e4}@example.com").await;
taken,
matches!(second, Err(CmdError::Config(ConfigError::EmailTaken)))
assert!(taken || second.is_ok());
async fn a_padded_email_is_the_same_account(pool: PgPool) -> anyhow::Result<()> {
register("pad@example.com").await?;
assert!(matches!(
register(" pad@example.com ").await,
Err(CmdError::Config(ConfigError::EmailTaken))
));
async fn a_blank_email_is_refused_at_creation(pool: PgPool) -> anyhow::Result<()> {
register(" ").await,
Err(CmdError::Config(ConfigError::EmailBlank))
assert!(matches!(validate_email(""), Err(ConfigError::EmailBlank)));
assert_eq!(validate_email(" A@X ")?, "a@x");