Skip to content

🛡️ Warracker is an open source, self-hostable warranty tracker to monitor expirations, store receipts, files. You own the data, your rules!

Security: require the current password for email changes, notify the old address (AUTH-09)

Omega (QA)0e4b820acc51
diff --git a/backend/auth_routes.py b/backend/auth_routes.py
index cf25702..1057af6 100644
--- a/backend/auth_routes.py
+++ b/backend/auth_routes.py
@@ -517,6 +517,8 @@ def update_profile():
try:
update_fields = ["first_name = %s", "last_name = %s"]
update_params = [first_name, last_name]
+ email_changed = False
+ old_email = None
# Handle email change
if new_email:
@@ -525,14 +527,31 @@ def update_profile():
return jsonify({'message': 'Invalid email format!'}), 400
# Check if the new email is different from the current one
- cursor.execute("SELECT email FROM users WHERE id = %s", (user_id,))
- current_email_tuple = cursor.fetchone()
- if not current_email_tuple:
+ cursor.execute(
+ "SELECT email, password_hash, oidc_sub FROM users "
+ "WHERE id = %s", (user_id,))
+ current_row = cursor.fetchone()
+ if not current_row:
conn.rollback()
return jsonify({'message': 'User not found while fetching current email.'}), 404
- current_email = current_email_tuple[0]
+ current_email = current_row[0]
if new_email.lower() != current_email.lower():
+ # AUTH-09: an email change is a credential change. It
+ # needs the current password, so a stolen session
+ # alone cannot convert the account and then take it
+ # over with a reset to the new address. Accounts
+ # without a local password (single sign-on) cannot
+ # confirm one; their email is changed by an admin.
+ if current_row[1] is None:
+ conn.rollback()
+ return jsonify({'message': 'Email changes for single sign-on accounts must be made by an administrator.'}), 403
+ current_password = data.get('current_password', '')
+ if not current_password or not bcrypt.check_password_hash(
+ current_row[1], current_password):
+ conn.rollback()
+ return jsonify({'message': 'Incorrect current password!'}), 401
+
# Check if the new email is already in use by another user
cursor.execute("SELECT id FROM users WHERE LOWER(email) = LOWER(%s) AND id != %s", (new_email, user_id))
if cursor.fetchone():
@@ -540,6 +559,8 @@ def update_profile():
return jsonify({'message': 'This email address is already in use by another account.'}), 409
update_fields.append("email = %s")
update_params.append(new_email)
+ email_changed = True
+ old_email = current_email
update_query_string = ", ".join(update_fields)
final_query = f"""
@@ -558,6 +579,18 @@ def update_profile():
conn.commit()
+ if email_changed and old_email:
+ # AUTH-09: tell the old address the account email
+ # changed, so a takeover via a stolen session is visible
+ # to the legitimate owner. Best effort; a mail failure
+ # must not fail the profile update itself.
+ try:
+ send_email_change_notice(old_email, new_email)
+ except Exception as notice_err:
+ current_app.logger.error(
+ f"Failed to send email-change notice to "
+ f"{old_email}: {notice_err}")
+
user = {
'id': user_data[0],
'username': user_data[1],
@@ -929,6 +962,63 @@ def send_password_reset_email(recipient_email, reset_link):
current_app.logger.error(f"Error sending password reset email: {e}")
return False
+
+def send_email_change_notice(old_email, new_email):
+ """Tell the previous address that the account email changed (AUTH-09).
+
+ Best effort: returns True on delivery, False otherwise, and never
+ raises. The profile update that calls it must not fail on mail.
+ """
+ try:
+ smtp_host = os.environ.get('SMTP_HOST', 'localhost')
+ smtp_port = int(os.environ.get('SMTP_PORT', 1025))
+ smtp_username = os.environ.get('SMTP_USERNAME')
+ smtp_password = os.environ.get('SMTP_PASSWORD')
+ if os.environ.get('SMTP_PASSWORD_FILE'):
+ smtp_password = open(os.environ.get('SMTP_PASSWORD_FILE'), 'r').read().strip()
+ smtp_use_tls = os.environ.get('SMTP_USE_TLS', 'true').lower() == 'true'
+ try:
+ from .utils import get_smtp_from_address
+ except ImportError:
+ from utils import get_smtp_from_address
+ sender_email = get_smtp_from_address()
+
+ html_content = f"""
+ <html>
+ <body>
+ <p>Hello,</p>
+ <p>The email address on your Warracker account was changed to {new_email}.</p>
+ <p>If you did not make this change, please contact your administrator right away: someone with access to your account may have changed it.</p>
+ <p>Thanks,<br>The Warracker Team</p>
+ </body>
+ </html>
+ """
+
+ msg = MIMEMultipart('alternative')
+ msg['Subject'] = "Email Changed - Warracker"
+ msg['From'] = sender_email
+ msg['To'] = old_email
+ msg.attach(MIMEText(html_content, 'html'))
+
+ server = None
+ if smtp_port == 465:
+ server = smtplib.SMTP_SSL(smtp_host, smtp_port, timeout=10)
+ else:
+ server = smtplib.SMTP(smtp_host, smtp_port, timeout=10)
+ if smtp_use_tls:
+ server.starttls()
+ if smtp_username and smtp_password:
+ server.login(smtp_username, smtp_password)
+ server.sendmail(sender_email, old_email, msg.as_string())
+ server.quit()
+ current_app.logger.info(
+ f"Email-change notice sent to {old_email}")
+ return True
+ except Exception as e:
+ current_app.logger.error(f"Error sending email-change notice: {e}")
+ return False
+
+
@auth_bp.route('/preferences', methods=['GET'])
@token_required
def get_preferences():
diff --git a/frontend/settings-new.html b/frontend/settings-new.html
index cf63dc4..9a436d3 100644
--- a/frontend/settings-new.html
+++ b/frontend/settings-new.html
@@ -183,6 +183,12 @@
<label for="email" data-i18n="settings.email">Email</label>
<input type="email" id="email" name="email" class="form-control">
</div>
+
+ <div class="form-group" id="profilePasswordGroup" style="display: none;">
+ <label for="profileCurrentPassword">Current Password</label>
+ <input type="password" id="profileCurrentPassword" name="profileCurrentPassword" class="form-control" autocomplete="current-password">
+ <p class="text-muted">Required to change your email address.</p>
+ </div>
<button type="button" id="saveProfileBtn" class="btn btn-primary" data-i18n="settings.save_profile">Save Changes</button>
</form>
diff --git a/frontend/settings-new.js b/frontend/settings-new.js
index f610ca3..4f6276a 100644
--- a/frontend/settings-new.js
+++ b/frontend/settings-new.js
@@ -41,6 +41,8 @@ const editUserAdmin = document.getElementById('editUserAdmin');
const firstNameInput = document.getElementById('firstName');
const lastNameInput = document.getElementById('lastName');
const emailInput = document.getElementById('email');
+const profilePasswordGroup = document.getElementById('profilePasswordGroup');
+const profileCurrentPasswordInput = document.getElementById('profileCurrentPassword');
const currentPasswordInput = document.getElementById('currentPassword');
const newPasswordInput = document.getElementById('newPassword');
const confirmPasswordInput = document.getElementById('confirmPassword');
@@ -1251,6 +1253,20 @@ function setupEventListeners() {
if (saveProfileBtn) {
saveProfileBtn.addEventListener('click', saveProfile);
}
+
+ // AUTH-09: reveal the current-password field as soon as the email
+ // differs from the signed-in address, so the requirement is visible
+ // before the user saves.
+ if (emailInput && profilePasswordGroup) {
+ emailInput.addEventListener('input', function() {
+ const currentUser = window.auth && window.auth.getCurrentUser
+ ? window.auth.getCurrentUser() : null;
+ const changed = currentUser && currentUser.email
+ && emailInput.value.trim().toLowerCase()
+ !== currentUser.email.toLowerCase();
+ profilePasswordGroup.style.display = changed ? 'block' : 'none';
+ });
+ }
// Save preferences button
if (savePreferencesBtn) {
@@ -1615,6 +1631,22 @@ async function saveProfile() {
return;
}
+ // AUTH-09: changing the email address needs the current password,
+ // so a stolen session alone cannot convert the account.
+ const currentUser = window.auth.getCurrentUser();
+ const emailChanged = currentUser && currentUser.email
+ && newEmail.toLowerCase() !== currentUser.email.toLowerCase();
+ let currentPassword = '';
+ if (emailChanged) {
+ currentPassword = profileCurrentPasswordInput
+ ? profileCurrentPasswordInput.value : '';
+ if (!currentPassword) {
+ if (profilePasswordGroup) profilePasswordGroup.style.display = 'block';
+ showToast('Enter your current password to change your email address.', 'error');
+ return;
+ }
+ }
+
showLoading();
const userNameDisplay = document.getElementById('currentUserNameDisplay');
@@ -1628,7 +1660,8 @@ async function saveProfile() {
body: JSON.stringify({
first_name: firstNameInput.value.trim(),
last_name: lastNameInput.value.trim(),
- email: newEmail
+ email: newEmail,
+ current_password: currentPassword || undefined
})
});
@@ -1670,6 +1703,10 @@ async function saveProfile() {
}
showToast('Profile updated successfully', 'success');
+
+ // Clear the password field now that the change is saved.
+ if (profileCurrentPasswordInput) profileCurrentPasswordInput.value = '';
+ if (profilePasswordGroup) profilePasswordGroup.style.display = 'none';
} else {
const errorData = await response.json().catch(() => ({ message: 'Failed to parse error response' }));
throw new Error(errorData.message || 'Failed to update profile');
diff --git a/tests/test_profile_email_change.py b/tests/test_profile_email_change.py
new file mode 100644
index 0000000..90bcee7
--- /dev/null
+++ b/tests/test_profile_email_change.py
@@ -0,0 +1,108 @@
+"""Email change confirmation (AUTH-09).
+
+Changing the account email needs the current password, so a stolen
+session alone cannot convert the account and then take it over with
+a reset to the new address. A notice goes to the old address. An
+account with no local password (single sign-on) cannot change its
+email here; an admin changes it instead.
+"""
+import uuid
+from datetime import datetime, UTC, timedelta
+
+import jwt
+
+from backend.auth_utils import generate_token
+
+
+def _change_email(client, headers, email, **extra):
+ body = {"first_name": "Test", "last_name": "User", "email": email}
+ body.update(extra)
+ return client.put("/api/auth/profile", headers=headers, json=body)
+
+
+def test_email_change_requires_current_password(client, user_factory):
+ user = user_factory()
+ headers = user["headers"]
+ new_email = f"moved-{user['username']}@test.local"
+
+ r = _change_email(client, headers, new_email)
+ assert r.status_code == 401
+ assert r.get_json()["message"] == "Incorrect current password!"
+
+ r = _change_email(client, headers, new_email,
+ current_password="WrongPass123!")
+ assert r.status_code == 401
+
+ r = _change_email(client, headers, new_email,
+ current_password="TestPass123!")
+ assert r.status_code == 200, r.get_data(as_text=True)
+ assert r.get_json()["email"] == new_email
+
+
+def test_email_change_notifies_old_address(
+ client, user_factory, monkeypatch):
+ calls = []
+ monkeypatch.setattr(
+ "backend.auth_routes.send_email_change_notice",
+ lambda old, new: calls.append((old, new)) or True)
+ user = user_factory()
+ headers = user["headers"]
+ old_email = f"{user['username']}@test.local"
+ new_email = f"moved-{user['username']}@test.local"
+ r = _change_email(client, headers, new_email,
+ current_password="TestPass123!")
+ assert r.status_code == 200, r.get_data(as_text=True)
+ assert calls == [(old_email, new_email)]
+
+
+def test_name_only_change_needs_no_password_and_sends_no_notice(
+ client, user_factory, monkeypatch):
+ calls = []
+ monkeypatch.setattr(
+ "backend.auth_routes.send_email_change_notice",
+ lambda old, new: calls.append((old, new)) or True)
+ user = user_factory()
+ r = client.put("/api/auth/profile", headers=user["headers"], json={
+ "first_name": "Renamed", "last_name": "User",
+ "email": f"{user['username']}@test.local",
+ })
+ assert r.status_code == 200, r.get_data(as_text=True)
+ assert r.get_json()["first_name"] == "Renamed"
+ assert calls == []
+
+
+def test_oidc_only_account_cannot_change_email(
+ app, client, db_connection):
+ username = f"oidconly_{uuid.uuid4().hex[:8]}"
+ with db_connection, db_connection.cursor() as cur:
+ cur.execute(
+ "INSERT INTO users (username, email, password_hash, oidc_sub, "
+ "oidc_issuer, is_active) VALUES (%s, %s, NULL, %s, %s, TRUE) "
+ "RETURNING id",
+ (username, f"{username}@test.local",
+ f"sub-{uuid.uuid4().hex[:12]}", "https://idp.test"),
+ )
+ user_id = cur.fetchone()[0]
+ with app.app_context():
+ token, jti = generate_token(user_id)
+ with db_connection, db_connection.cursor() as cur:
+ cur.execute(
+ "INSERT INTO user_sessions (user_id, session_token, expires_at, "
+ "ip_address, user_agent, login_method) VALUES (%s, %s, %s, %s, "
+ "%s, %s)",
+ (user_id, jti, datetime.now(UTC) + timedelta(hours=24),
+ "127.0.0.1", "pytest", "oidc"),
+ )
+ r = _change_email(client, {"Authorization": f"Bearer {token}"},
+ f"moved-{username}@test.local",
+ current_password="Whatever123!")
+ assert r.status_code == 403
+ assert "administrator" in r.get_json()["message"]
+
+
+def test_email_change_notice_sender_returns_false_without_smtp(app):
+ """The notice is best effort: with no SMTP server it fails quietly."""
+ from backend.auth_routes import send_email_change_notice
+ with app.app_context():
+ assert send_email_change_notice(