You've already forked authentication-service
mirror of
https://github.com/matrix-org/matrix-authentication-service.git
synced 2025-11-21 23:00:50 +03:00
Use the new password manager
This commit is contained in:
@@ -41,6 +41,7 @@ use mas_keystore::{Encrypter, Keystore};
|
||||
use mas_policy::PolicyFactory;
|
||||
use mas_router::{Route, UrlBuilder};
|
||||
use mas_templates::{ErrorContext, Templates};
|
||||
use passwords::PasswordManager;
|
||||
use rand::SeedableRng;
|
||||
use sqlx::PgPool;
|
||||
use tower::util::AndThenLayer;
|
||||
@@ -253,6 +254,7 @@ where
|
||||
Mailer: FromRef<S>,
|
||||
Keystore: FromRef<S>,
|
||||
HttpClientFactory: FromRef<S>,
|
||||
PasswordManager: FromRef<S>,
|
||||
{
|
||||
Router::new()
|
||||
.route(
|
||||
@@ -351,7 +353,7 @@ where
|
||||
async fn test_state(pool: PgPool) -> Result<AppState, anyhow::Error> {
|
||||
use mas_email::MailTransport;
|
||||
|
||||
use crate::passwords::{Hasher, PasswordManager};
|
||||
use crate::passwords::Hasher;
|
||||
|
||||
let workspace_root = camino::Utf8Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("..")
|
||||
|
||||
@@ -71,6 +71,7 @@ impl PasswordManager {
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns an error if the hashing failed
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn hash<R: CryptoRng + RngCore + Send>(
|
||||
&self,
|
||||
rng: R,
|
||||
@@ -78,7 +79,7 @@ impl PasswordManager {
|
||||
) -> Result<(SchemeVersion, String), anyhow::Error> {
|
||||
// Seed a future-local RNG so the RNG passed in parameters doesn't have to be
|
||||
// 'static
|
||||
let mut rng = rand_chacha::ChaChaRng::from_rng(rng)?;
|
||||
let rng = rand_chacha::ChaChaRng::from_rng(rng)?;
|
||||
let hashers = self.hashers.clone();
|
||||
let default_hasher_version = self.default_hasher;
|
||||
|
||||
@@ -87,7 +88,7 @@ impl PasswordManager {
|
||||
.get(&default_hasher_version)
|
||||
.context("Default hasher not found")?;
|
||||
|
||||
default_hasher.hash_blocking(&mut rng, &password)
|
||||
default_hasher.hash_blocking(rng, &password)
|
||||
})
|
||||
.await??;
|
||||
|
||||
@@ -95,7 +96,12 @@ impl PasswordManager {
|
||||
}
|
||||
|
||||
/// Verify a password hash for the given hashing scheme.
|
||||
async fn verify(
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns an error if the password hash verification failed
|
||||
#[tracing::instrument(skip_all, fields(%scheme))]
|
||||
pub async fn verify(
|
||||
&self,
|
||||
scheme: SchemeVersion,
|
||||
password: Zeroizing<Vec<u8>>,
|
||||
@@ -118,6 +124,7 @@ impl PasswordManager {
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns an error if the password hash verification failed
|
||||
#[tracing::instrument(skip_all, fields(%scheme))]
|
||||
pub async fn verify_and_upgrade<R: CryptoRng + RngCore + Send>(
|
||||
&self,
|
||||
rng: R,
|
||||
@@ -172,7 +179,7 @@ impl Hasher {
|
||||
|
||||
fn hash_blocking<R: CryptoRng + RngCore>(
|
||||
&self,
|
||||
rng: &mut R,
|
||||
rng: R,
|
||||
password: &[u8],
|
||||
) -> Result<String, anyhow::Error> {
|
||||
self.algorithm
|
||||
@@ -195,7 +202,7 @@ enum Algorithm {
|
||||
impl Algorithm {
|
||||
fn hash_blocking<R: CryptoRng + RngCore>(
|
||||
self,
|
||||
rng: &mut R,
|
||||
mut rng: R,
|
||||
password: &[u8],
|
||||
pepper: Option<&[u8]>,
|
||||
) -> Result<String, anyhow::Error> {
|
||||
|
||||
@@ -28,9 +28,7 @@ use mas_storage::{
|
||||
upstream_oauth2::{
|
||||
associate_link_to_user, consume_session, lookup_link, lookup_session_on_link,
|
||||
},
|
||||
user::{
|
||||
authenticate_session_with_upstream, lookup_user, register_passwordless_user, start_session,
|
||||
},
|
||||
user::{add_user, authenticate_session_with_upstream, lookup_user, start_session},
|
||||
};
|
||||
use mas_templates::{
|
||||
EmptyContext, TemplateContext, Templates, UpstreamExistingLinkContext, UpstreamRegister,
|
||||
@@ -236,7 +234,7 @@ pub(crate) async fn post(
|
||||
}
|
||||
|
||||
(None, None, FormData::Register { username }) => {
|
||||
let user = register_passwordless_user(&mut txn, &mut rng, &clock, &username).await?;
|
||||
let user = add_user(&mut txn, &mut rng, &clock, &username).await?;
|
||||
associate_link_to_user(&mut txn, &link, &user).await?;
|
||||
|
||||
start_session(&mut txn, &mut rng, &clock, user).await?
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
use argon2::Argon2;
|
||||
use anyhow::Context;
|
||||
use axum::{
|
||||
extract::{Form, State},
|
||||
response::{Html, IntoResponse, Response},
|
||||
@@ -26,13 +26,16 @@ use mas_data_model::BrowserSession;
|
||||
use mas_keystore::Encrypter;
|
||||
use mas_router::Route;
|
||||
use mas_storage::{
|
||||
user::{authenticate_session, set_password},
|
||||
user::{add_user_password, authenticate_session_with_password, lookup_user_password},
|
||||
Clock,
|
||||
};
|
||||
use mas_templates::{EmptyContext, TemplateContext, Templates};
|
||||
use rand::Rng;
|
||||
use serde::Deserialize;
|
||||
use sqlx::PgPool;
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
use crate::passwords::PasswordManager;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct ChangeForm {
|
||||
@@ -80,6 +83,7 @@ async fn render(
|
||||
}
|
||||
|
||||
pub(crate) async fn post(
|
||||
State(password_manager): State<PasswordManager>,
|
||||
State(templates): State<Templates>,
|
||||
State(pool): State<PgPool>,
|
||||
cookie_jar: PrivateCookieJar<Encrypter>,
|
||||
@@ -101,31 +105,42 @@ pub(crate) async fn post(
|
||||
return Ok((cookie_jar, login.go()).into_response());
|
||||
};
|
||||
|
||||
authenticate_session(
|
||||
&mut txn,
|
||||
&mut rng,
|
||||
&clock,
|
||||
&mut session,
|
||||
&form.current_password,
|
||||
)
|
||||
.await?;
|
||||
let user_password = lookup_user_password(&mut txn, &session.user)
|
||||
.await?
|
||||
.context("user has no password")?;
|
||||
|
||||
let password = Zeroizing::new(form.current_password.into_bytes());
|
||||
let new_password = Zeroizing::new(form.new_password.into_bytes());
|
||||
let new_password_confirm = Zeroizing::new(form.new_password_confirm.into_bytes());
|
||||
|
||||
password_manager
|
||||
.verify(
|
||||
user_password.version,
|
||||
password,
|
||||
user_password.hashed_password,
|
||||
)
|
||||
.await?;
|
||||
|
||||
// TODO: display nice form errors
|
||||
if form.new_password != form.new_password_confirm {
|
||||
if new_password != new_password_confirm {
|
||||
return Err(anyhow::anyhow!("password mismatch").into());
|
||||
}
|
||||
|
||||
let phf = Argon2::default();
|
||||
set_password(
|
||||
let (version, hashed_password) = password_manager.hash(&mut rng, new_password).await?;
|
||||
let user_password = add_user_password(
|
||||
&mut txn,
|
||||
&mut rng,
|
||||
&clock,
|
||||
phf,
|
||||
&session.user,
|
||||
&form.new_password,
|
||||
version,
|
||||
hashed_password,
|
||||
None,
|
||||
)
|
||||
.await?;
|
||||
|
||||
authenticate_session_with_password(&mut txn, &mut rng, &clock, &mut session, &user_password)
|
||||
.await?;
|
||||
|
||||
let reply = render(&mut rng, &clock, templates.clone(), session, cookie_jar).await?;
|
||||
|
||||
txn.commit().await?;
|
||||
|
||||
@@ -21,15 +21,25 @@ use mas_axum_utils::{
|
||||
csrf::{CsrfExt, CsrfToken, ProtectedForm},
|
||||
FancyError, SessionInfoExt,
|
||||
};
|
||||
use mas_data_model::BrowserSession;
|
||||
use mas_keystore::Encrypter;
|
||||
use mas_storage::user::{login, LoginError};
|
||||
use mas_storage::{
|
||||
user::{
|
||||
add_user_password, authenticate_session_with_password, lookup_user_by_username,
|
||||
lookup_user_password, start_session,
|
||||
},
|
||||
Clock,
|
||||
};
|
||||
use mas_templates::{
|
||||
FieldError, FormError, LoginContext, LoginFormField, TemplateContext, Templates, ToFormState,
|
||||
};
|
||||
use rand::{CryptoRng, Rng};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sqlx::{PgConnection, PgPool};
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
use super::shared::OptionalPostAuthAction;
|
||||
use crate::passwords::PasswordManager;
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
pub(crate) struct LoginForm {
|
||||
@@ -74,6 +84,7 @@ pub(crate) async fn get(
|
||||
}
|
||||
|
||||
pub(crate) async fn post(
|
||||
State(password_manager): State<PasswordManager>,
|
||||
State(templates): State<Templates>,
|
||||
State(pool): State<PgPool>,
|
||||
Query(query): Query<OptionalPostAuthAction>,
|
||||
@@ -118,19 +129,25 @@ pub(crate) async fn post(
|
||||
return Ok((cookie_jar, Html(content)).into_response());
|
||||
}
|
||||
|
||||
match login(&mut conn, &mut rng, &clock, &form.username, &form.password).await {
|
||||
lookup_user_by_username(&mut conn, &form.username).await?;
|
||||
|
||||
match login(
|
||||
password_manager,
|
||||
&mut conn,
|
||||
rng,
|
||||
&clock,
|
||||
&form.username,
|
||||
&form.password,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(session_info) => {
|
||||
let cookie_jar = cookie_jar.set_session(&session_info);
|
||||
let reply = query.go_next();
|
||||
Ok((cookie_jar, reply).into_response())
|
||||
}
|
||||
Err(e) => {
|
||||
let state = match e {
|
||||
LoginError::NotFound { .. } | LoginError::Authentication { .. } => {
|
||||
state.with_error_on_form(FormError::InvalidCredentials)
|
||||
}
|
||||
LoginError::Other(_) => state.with_error_on_form(FormError::Internal),
|
||||
};
|
||||
let state = state.with_error_on_form(e);
|
||||
|
||||
let content = render(
|
||||
LoginContext::default().with_form_state(state),
|
||||
@@ -146,6 +163,71 @@ pub(crate) async fn post(
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: move that logic elsewhere?
|
||||
async fn login(
|
||||
password_manager: PasswordManager,
|
||||
conn: &mut PgConnection,
|
||||
mut rng: impl Rng + CryptoRng + Send,
|
||||
clock: &Clock,
|
||||
username: &str,
|
||||
password: &str,
|
||||
) -> Result<BrowserSession, FormError> {
|
||||
// XXX: we're loosing the error context here
|
||||
// First, lookup the user
|
||||
let user = lookup_user_by_username(&mut *conn, username)
|
||||
.await
|
||||
.map_err(|_e| FormError::Internal)?
|
||||
.ok_or(FormError::InvalidCredentials)?;
|
||||
|
||||
// And its password
|
||||
let user_password = lookup_user_password(&mut *conn, &user)
|
||||
.await
|
||||
.map_err(|_e| FormError::Internal)?
|
||||
.ok_or(FormError::InvalidCredentials)?;
|
||||
|
||||
let password = Zeroizing::new(password.as_bytes().to_vec());
|
||||
|
||||
// Verify the password, and upgrade it on-the-fly if needed
|
||||
let new_password_hash = password_manager
|
||||
.verify_and_upgrade(
|
||||
&mut rng,
|
||||
user_password.version,
|
||||
password,
|
||||
user_password.hashed_password.clone(),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| FormError::InvalidCredentials)?;
|
||||
|
||||
let user_password = if let Some((version, new_password_hash)) = new_password_hash {
|
||||
// Save the upgraded password
|
||||
add_user_password(
|
||||
&mut *conn,
|
||||
&mut rng,
|
||||
clock,
|
||||
&user,
|
||||
version,
|
||||
new_password_hash,
|
||||
Some(user_password),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| FormError::Internal)?
|
||||
} else {
|
||||
user_password
|
||||
};
|
||||
|
||||
// Start a new session
|
||||
let mut user_session = start_session(&mut *conn, &mut rng, clock, user)
|
||||
.await
|
||||
.map_err(|_| FormError::Internal)?;
|
||||
|
||||
// And mark it as authenticated by the password
|
||||
authenticate_session_with_password(&mut *conn, rng, clock, &mut user_session, &user_password)
|
||||
.await
|
||||
.map_err(|_| FormError::Internal)?;
|
||||
|
||||
Ok(user_session)
|
||||
}
|
||||
|
||||
async fn render(
|
||||
ctx: LoginContext,
|
||||
action: OptionalPostAuthAction,
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
use anyhow::Context;
|
||||
use axum::{
|
||||
extract::{Form, Query, State},
|
||||
response::{Html, IntoResponse, Response},
|
||||
@@ -23,12 +24,16 @@ use mas_axum_utils::{
|
||||
};
|
||||
use mas_keystore::Encrypter;
|
||||
use mas_router::Route;
|
||||
use mas_storage::user::authenticate_session;
|
||||
use mas_storage::user::{
|
||||
add_user_password, authenticate_session_with_password, lookup_user_password,
|
||||
};
|
||||
use mas_templates::{ReauthContext, TemplateContext, Templates};
|
||||
use serde::Deserialize;
|
||||
use sqlx::PgPool;
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
use super::shared::OptionalPostAuthAction;
|
||||
use crate::passwords::PasswordManager;
|
||||
|
||||
#[derive(Deserialize, Debug)]
|
||||
pub(crate) struct ReauthForm {
|
||||
@@ -73,6 +78,7 @@ pub(crate) async fn get(
|
||||
}
|
||||
|
||||
pub(crate) async fn post(
|
||||
State(password_manager): State<PasswordManager>,
|
||||
State(pool): State<PgPool>,
|
||||
Query(query): Query<OptionalPostAuthAction>,
|
||||
cookie_jar: PrivateCookieJar<Encrypter>,
|
||||
@@ -96,8 +102,43 @@ pub(crate) async fn post(
|
||||
return Ok((cookie_jar, login.go()).into_response());
|
||||
};
|
||||
|
||||
// TODO: recover from errors here
|
||||
authenticate_session(&mut txn, &mut rng, &clock, &mut session, &form.password).await?;
|
||||
// Load the user password
|
||||
let user_password = lookup_user_password(&mut txn, &session.user)
|
||||
.await?
|
||||
.context("User has no password")?;
|
||||
|
||||
let password = Zeroizing::new(form.password.as_bytes().to_vec());
|
||||
|
||||
// TODO: recover from errors
|
||||
// Verify the password, and upgrade it on-the-fly if needed
|
||||
let new_password_hash = password_manager
|
||||
.verify_and_upgrade(
|
||||
&mut rng,
|
||||
user_password.version,
|
||||
password,
|
||||
user_password.hashed_password.clone(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
let user_password = if let Some((version, new_password_hash)) = new_password_hash {
|
||||
// Save the upgraded password
|
||||
add_user_password(
|
||||
&mut *txn,
|
||||
&mut rng,
|
||||
&clock,
|
||||
&session.user,
|
||||
version,
|
||||
new_password_hash,
|
||||
Some(user_password),
|
||||
)
|
||||
.await?
|
||||
} else {
|
||||
user_password
|
||||
};
|
||||
|
||||
// Mark the session as authenticated by the password
|
||||
authenticate_session_with_password(&mut txn, rng, &clock, &mut session, &user_password).await?;
|
||||
|
||||
let cookie_jar = cookie_jar.set_session(&session);
|
||||
txn.commit().await?;
|
||||
|
||||
|
||||
@@ -16,7 +16,6 @@
|
||||
|
||||
use std::{str::FromStr, sync::Arc};
|
||||
|
||||
use argon2::Argon2;
|
||||
use axum::{
|
||||
extract::{Form, Query, State},
|
||||
response::{Html, IntoResponse, Response},
|
||||
@@ -33,7 +32,8 @@ use mas_keystore::Encrypter;
|
||||
use mas_policy::PolicyFactory;
|
||||
use mas_router::Route;
|
||||
use mas_storage::user::{
|
||||
add_user_email, add_user_email_verification_code, register_user, start_session, username_exists,
|
||||
add_user, add_user_email, add_user_email_verification_code, add_user_password,
|
||||
authenticate_session_with_password, start_session, username_exists,
|
||||
};
|
||||
use mas_templates::{
|
||||
EmailVerificationContext, FieldError, FormError, RegisterContext, RegisterFormField,
|
||||
@@ -42,8 +42,10 @@ use mas_templates::{
|
||||
use rand::{distributions::Uniform, Rng};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sqlx::{PgConnection, PgPool};
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
use super::shared::OptionalPostAuthAction;
|
||||
use crate::passwords::PasswordManager;
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
pub(crate) struct RegisterForm {
|
||||
@@ -88,8 +90,9 @@ pub(crate) async fn get(
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_lines)]
|
||||
#[allow(clippy::too_many_lines, clippy::too_many_arguments)]
|
||||
pub(crate) async fn post(
|
||||
State(password_manager): State<PasswordManager>,
|
||||
State(mailer): State<Mailer>,
|
||||
State(policy_factory): State<Arc<PolicyFactory>>,
|
||||
State(templates): State<Templates>,
|
||||
@@ -182,14 +185,17 @@ pub(crate) async fn post(
|
||||
return Ok((cookie_jar, Html(content)).into_response());
|
||||
}
|
||||
|
||||
let pfh = Argon2::default();
|
||||
let user = register_user(
|
||||
let user = add_user(&mut txn, &mut rng, &clock, &form.username).await?;
|
||||
let password = Zeroizing::new(form.password.into_bytes());
|
||||
let (version, hashed_password) = password_manager.hash(&mut rng, password).await?;
|
||||
let user_password = add_user_password(
|
||||
&mut txn,
|
||||
&mut rng,
|
||||
&clock,
|
||||
pfh,
|
||||
&form.username,
|
||||
&form.password,
|
||||
&user,
|
||||
version,
|
||||
hashed_password,
|
||||
None,
|
||||
)
|
||||
.await?;
|
||||
|
||||
@@ -222,7 +228,9 @@ pub(crate) async fn post(
|
||||
let next = mas_router::AccountVerifyEmail::new(verification.email.id)
|
||||
.and_maybe(query.post_auth_action);
|
||||
|
||||
let session = start_session(&mut txn, &mut rng, &clock, user).await?;
|
||||
let mut session = start_session(&mut txn, &mut rng, &clock, user).await?;
|
||||
authenticate_session_with_password(&mut txn, &mut rng, &clock, &mut session, &user_password)
|
||||
.await?;
|
||||
|
||||
txn.commit().await?;
|
||||
|
||||
|
||||
Reference in New Issue
Block a user