Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion backend/app/api/routes/users.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -104,7 +104,8 @@ def update_password_me(
"""
Update own password.
"""
if not verify_password(body.current_password, current_user.hashed_password):
verified, _ = verify_password(body.current_password, current_user.hashed_password)
if not verified:
raise HTTPException(status_code=400, detail="Incorrect password")
if body.current_password == body.new_password:
raise HTTPException(
Expand Down
19 changes: 14 additions & 5 deletions backend/app/core/security.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,11 +2,18 @@
from typing import Any

import jwt
from passlib.context import CryptContext
from pwdlib import PasswordHash
from pwdlib.hashers.argon2 import Argon2Hasher
from pwdlib.hashers.bcrypt import BcryptHasher

from app.core.config import settings

pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
password_hash = PasswordHash(
(
Argon2Hasher(),
BcryptHasher(),
)
)


ALGORITHM = "HS256"
Expand All@@ -19,9 +26,11 @@ def create_access_token(subject: str | Any, expires_delta: timedelta) -> str:
return encoded_jwt


def verify_password(plain_password: str, hashed_password: str) -> bool:
return pwd_context.verify(plain_password, hashed_password)
def verify_password(
plain_password: str, hashed_password: str
) -> tuple[bool, str | None]:
return password_hash.verify_and_update(plain_password, hashed_password)


def get_password_hash(password: str) -> str:
return pwd_context.hash(password)
return password_hash.hash(password)
8 changes: 7 additions & 1 deletion backend/app/crud.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -41,8 +41,14 @@ def authenticate(*, session: Session, email: str, password: str) -> User | None:
db_user = get_user_by_email(session=session, email=email)
if not db_user:
return None
if not verify_password(password, db_user.hashed_password):
verified, updated_password_hash = verify_password(password, db_user.hashed_password)
if not verified:
return None
if updated_password_hash:
db_user.hashed_password = updated_password_hash
session.add(db_user)
session.commit()
session.refresh(db_user)
return db_user


Expand Down
5 changes: 1 addition & 4 deletions backend/pyproject.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,7 +7,6 @@ dependencies = [
"fastapi[standard]<1.0.0,>=0.114.2",
"python-multipart<1.0.0,>=0.0.7",
"email-validator<3.0.0.0,>=2.1.0.post1",
"passlib[bcrypt]<2.0.0,>=1.7.4",
"tenacity<9.0.0,>=8.2.3",
"pydantic>2.0",
"emails<1.0,>=0.6",
Expand All@@ -16,11 +15,10 @@ dependencies = [
"httpx<1.0.0,>=0.25.1",
"psycopg[binary]<4.0.0,>=3.1.13",
"sqlmodel<1.0.0,>=0.0.21",
# Pin bcrypt until passlib supports the latest
"bcrypt==4.3.0",
"pydantic-settings<3.0.0,>=2.2.1",
"sentry-sdk[fastapi]<2.0.0,>=1.40.6",
"pyjwt<3.0.0,>=2.8.0",
"pwdlib[argon2,bcrypt]>=0.3.0",
]

[dependency-groups]
Expand All@@ -29,7 +27,6 @@ dev = [
"mypy<2.0.0,>=1.8.0",
"ruff<1.0.0,>=0.2.2",
"prek>=0.2.24,<1.0.0",
"types-passlib<2.0.0.0,>=1.7.7.20240106",
"coverage<8.0.0,>=7.4.3",
]

Expand Down
73 changes: 70 additions & 3 deletions backend/tests/api/routes/test_login.py
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,13 @@
from unittest.mock import patch

from fastapi.testclient import TestClient
from pwdlib.hashers.bcrypt import BcryptHasher
from sqlmodel import Session

from app.core.config import settings
from app.core.security import verify_password
from app.core.security import get_password_hash, verify_password
from app.crud import create_user
from app.models import UserCreate
from app.models import User, UserCreate
from app.utils import generate_password_reset_token
from tests.utils.user import user_authentication_headers
from tests.utils.utils import random_email, random_lower_string
Expand DownExpand Up@@ -99,7 +100,8 @@ def test_reset_password(client: TestClient, db: Session) -> None:
assert r.json() == {"message": "Password updated successfully"}

db.refresh(user)
assert verify_password(new_password, user.hashed_password)
verified, _ = verify_password(new_password, user.hashed_password)
assert verified


def test_reset_password_invalid_token(
Expand All@@ -116,3 +118,68 @@ def test_reset_password_invalid_token(
assert "detail" in response
assert r.status_code == 400
assert response["detail"] == "Invalid token"


def test_login_with_bcrypt_password_upgrades_to_argon2(
client: TestClient, db: Session
) -> None:
"""Test that logging in with a bcrypt password hash upgrades it to argon2."""
email = random_email()
password = random_lower_string()

# Create a bcrypt hash directly (simulating legacy password)
bcrypt_hasher = BcryptHasher()
bcrypt_hash = bcrypt_hasher.hash(password)
assert bcrypt_hash.startswith("$2") # bcrypt hashes start with $2

user = User(email=email, hashed_password=bcrypt_hash, is_active=True)
db.add(user)
db.commit()
db.refresh(user)

assert user.hashed_password.startswith("$2")

login_data = {"username": email, "password": password}
r = client.post(f"{settings.API_V1_STR}/login/access-token", data=login_data)
assert r.status_code == 200
tokens = r.json()
assert "access_token" in tokens

db.refresh(user)

# Verify the hash was upgraded to argon2
assert user.hashed_password.startswith("$argon2")

verified, updated_hash = verify_password(password, user.hashed_password)
assert verified
# Should not need another update since it's already argon2
assert updated_hash is None


def test_login_with_argon2_password_keeps_hash(client: TestClient, db: Session) -> None:
"""Test that logging in with an argon2 password hash does not update it."""
email = random_email()
password = random_lower_string()

# Create an argon2 hash (current default)
argon2_hash = get_password_hash(password)
assert argon2_hash.startswith("$argon2")

# Create user with argon2 hash
user = User(email=email, hashed_password=argon2_hash, is_active=True)
db.add(user)
db.commit()
db.refresh(user)

original_hash = user.hashed_password

login_data = {"username": email, "password": password}
r = client.post(f"{settings.API_V1_STR}/login/access-token", data=login_data)
assert r.status_code == 200
tokens = r.json()
assert "access_token" in tokens

db.refresh(user)

assert user.hashed_password == original_hash
assert user.hashed_password.startswith("$argon2")
11 changes: 8 additions & 3 deletions backend/tests/api/routes/test_users.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -242,7 +242,8 @@ def test_update_password_me(
user_db = db.exec(user_query).first()
assert user_db
assert user_db.email == settings.FIRST_SUPERUSER
assert verify_password(new_password, user_db.hashed_password)
verified, _ = verify_password(new_password, user_db.hashed_password)
assert verified

# Revert to the old password to keep consistency in test
old_data = {
Expand All@@ -257,7 +258,10 @@ def test_update_password_me(
db.refresh(user_db)

assert r.status_code == 200
assert verify_password(settings.FIRST_SUPERUSER_PASSWORD, user_db.hashed_password)
verified, _ = verify_password(
settings.FIRST_SUPERUSER_PASSWORD, user_db.hashed_password
)
assert verified


def test_update_password_me_incorrect_password(
Expand DownExpand Up@@ -331,7 +335,8 @@ def test_register_user(client: TestClient, db: Session) -> None:
assert user_db
assert user_db.email == username
assert user_db.full_name == full_name
assert verify_password(password, user_db.hashed_password)
verified, _ = verify_password(password, user_db.hashed_password)
assert verified


def test_register_user_already_exists_error(client: TestClient) -> None:
Expand Down
41 changes: 40 additions & 1 deletion backend/tests/crud/test_user.py
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
from fastapi.encoders import jsonable_encoder
from pwdlib.hashers.bcrypt import BcryptHasher
from sqlmodel import Session

from app import crud
Expand DownExpand Up@@ -88,4 +89,42 @@ def test_update_user(db: Session) -> None:
user_2 = db.get(User, user.id)
assert user_2
assert user.email == user_2.email
assert verify_password(new_password, user_2.hashed_password)
verified, _ = verify_password(new_password, user_2.hashed_password)
assert verified


def test_authenticate_user_with_bcrypt_upgrades_to_argon2(db: Session) -> None:
"""Test that a user with bcrypt password hash gets upgraded to argon2 on login."""
email = random_email()
password = random_lower_string()

# Create a bcrypt hash directly (simulating legacy password)
bcrypt_hasher = BcryptHasher()
bcrypt_hash = bcrypt_hasher.hash(password)
assert bcrypt_hash.startswith("$2") # bcrypt hashes start with $2

# Create user with bcrypt hash directly in the database
user = User(email=email, hashed_password=bcrypt_hash)
db.add(user)
db.commit()
db.refresh(user)

# Verify the hash is bcrypt before authentication
assert user.hashed_password.startswith("$2")

# Authenticate - this should upgrade the hash to argon2
authenticated_user = crud.authenticate(session=db, email=email, password=password)
assert authenticated_user
assert authenticated_user.email == email

db.refresh(authenticated_user)

# Verify the hash was upgraded to argon2
assert authenticated_user.hashed_password.startswith("$argon2")

verified, updated_hash = verify_password(
password, authenticated_user.hashed_password
)
assert verified
# Should not need another update since it's already argon2
assert updated_hash is None
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion backend/app/api/routes/users.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -104,7 +104,8 @@ def update_password_me(
"""
Update own password.
"""
if not verify_password(body.current_password, current_user.hashed_password):
verified, _ = verify_password(body.current_password, current_user.hashed_password)
if not verified:
raise HTTPException(status_code=400, detail="Incorrect password")
if body.current_password == body.new_password:
raise HTTPException(
Expand Down
19 changes: 14 additions & 5 deletions backend/app/core/security.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,11 +2,18 @@
from typing import Any

import jwt
from passlib.context import CryptContext
from pwdlib import PasswordHash
from pwdlib.hashers.argon2 import Argon2Hasher
from pwdlib.hashers.bcrypt import BcryptHasher

from app.core.config import settings

pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
password_hash = PasswordHash(
(
Argon2Hasher(),
BcryptHasher(),
)
)


ALGORITHM = "HS256"
Expand All@@ -19,9 +26,11 @@ def create_access_token(subject: str | Any, expires_delta: timedelta) -> str:
return encoded_jwt


def verify_password(plain_password: str, hashed_password: str) -> bool:
return pwd_context.verify(plain_password, hashed_password)
def verify_password(
plain_password: str, hashed_password: str
) -> tuple[bool, str | None]:
return password_hash.verify_and_update(plain_password, hashed_password)


def get_password_hash(password: str) -> str:
return pwd_context.hash(password)
return password_hash.hash(password)
8 changes: 7 additions & 1 deletion backend/app/crud.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -41,8 +41,14 @@ def authenticate(*, session: Session, email: str, password: str) -> User | None:
db_user = get_user_by_email(session=session, email=email)
if not db_user:
return None
if not verify_password(password, db_user.hashed_password):
verified, updated_password_hash = verify_password(password, db_user.hashed_password)
if not verified:
return None
if updated_password_hash:
db_user.hashed_password = updated_password_hash
session.add(db_user)
session.commit()
session.refresh(db_user)
return db_user


Expand Down
5 changes: 1 addition & 4 deletions backend/pyproject.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,7 +7,6 @@ dependencies = [
"fastapi[standard]<1.0.0,>=0.114.2",
"python-multipart<1.0.0,>=0.0.7",
"email-validator<3.0.0.0,>=2.1.0.post1",
"passlib[bcrypt]<2.0.0,>=1.7.4",
"tenacity<9.0.0,>=8.2.3",
"pydantic>2.0",
"emails<1.0,>=0.6",
Expand All@@ -16,11 +15,10 @@ dependencies = [
"httpx<1.0.0,>=0.25.1",
"psycopg[binary]<4.0.0,>=3.1.13",
"sqlmodel<1.0.0,>=0.0.21",
# Pin bcrypt until passlib supports the latest
"bcrypt==4.3.0",
"pydantic-settings<3.0.0,>=2.2.1",
"sentry-sdk[fastapi]<2.0.0,>=1.40.6",
"pyjwt<3.0.0,>=2.8.0",
"pwdlib[argon2,bcrypt]>=0.3.0",
]

[dependency-groups]
Expand All@@ -29,7 +27,6 @@ dev = [
"mypy<2.0.0,>=1.8.0",
"ruff<1.0.0,>=0.2.2",
"prek>=0.2.24,<1.0.0",
"types-passlib<2.0.0.0,>=1.7.7.20240106",
"coverage<8.0.0,>=7.4.3",
]

Expand Down
73 changes: 70 additions & 3 deletions backend/tests/api/routes/test_login.py
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,13 @@
from unittest.mock import patch

from fastapi.testclient import TestClient
from pwdlib.hashers.bcrypt import BcryptHasher
from sqlmodel import Session

from app.core.config import settings
from app.core.security import verify_password
from app.core.security import get_password_hash, verify_password
from app.crud import create_user
from app.models import UserCreate
from app.models import User, UserCreate
from app.utils import generate_password_reset_token
from tests.utils.user import user_authentication_headers
from tests.utils.utils import random_email, random_lower_string
Expand DownExpand Up@@ -99,7 +100,8 @@ def test_reset_password(client: TestClient, db: Session) -> None:
assert r.json() == {"message": "Password updated successfully"}

db.refresh(user)
assert verify_password(new_password, user.hashed_password)
verified, _ = verify_password(new_password, user.hashed_password)
assert verified


def test_reset_password_invalid_token(
Expand All@@ -116,3 +118,68 @@ def test_reset_password_invalid_token(
assert "detail" in response
assert r.status_code == 400
assert response["detail"] == "Invalid token"


def test_login_with_bcrypt_password_upgrades_to_argon2(
client: TestClient, db: Session
) -> None:
"""Test that logging in with a bcrypt password hash upgrades it to argon2."""
email = random_email()
password = random_lower_string()

# Create a bcrypt hash directly (simulating legacy password)
bcrypt_hasher = BcryptHasher()
bcrypt_hash = bcrypt_hasher.hash(password)
assert bcrypt_hash.startswith("$2") # bcrypt hashes start with $2

user = User(email=email, hashed_password=bcrypt_hash, is_active=True)
db.add(user)
db.commit()
db.refresh(user)

assert user.hashed_password.startswith("$2")

login_data = {"username": email, "password": password}
r = client.post(f"{settings.API_V1_STR}/login/access-token", data=login_data)
assert r.status_code == 200
tokens = r.json()
assert "access_token" in tokens

db.refresh(user)

# Verify the hash was upgraded to argon2
assert user.hashed_password.startswith("$argon2")

verified, updated_hash = verify_password(password, user.hashed_password)
assert verified
# Should not need another update since it's already argon2
assert updated_hash is None


def test_login_with_argon2_password_keeps_hash(client: TestClient, db: Session) -> None:
"""Test that logging in with an argon2 password hash does not update it."""
email = random_email()
password = random_lower_string()

# Create an argon2 hash (current default)
argon2_hash = get_password_hash(password)
assert argon2_hash.startswith("$argon2")

# Create user with argon2 hash
user = User(email=email, hashed_password=argon2_hash, is_active=True)
db.add(user)
db.commit()
db.refresh(user)

original_hash = user.hashed_password

login_data = {"username": email, "password": password}
r = client.post(f"{settings.API_V1_STR}/login/access-token", data=login_data)
assert r.status_code == 200
tokens = r.json()
assert "access_token" in tokens

db.refresh(user)

assert user.hashed_password == original_hash
assert user.hashed_password.startswith("$argon2")
11 changes: 8 additions & 3 deletions backend/tests/api/routes/test_users.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -242,7 +242,8 @@ def test_update_password_me(
user_db = db.exec(user_query).first()
assert user_db
assert user_db.email == settings.FIRST_SUPERUSER
assert verify_password(new_password, user_db.hashed_password)
verified, _ = verify_password(new_password, user_db.hashed_password)
assert verified

# Revert to the old password to keep consistency in test
old_data = {
Expand All@@ -257,7 +258,10 @@ def test_update_password_me(
db.refresh(user_db)

assert r.status_code == 200
assert verify_password(settings.FIRST_SUPERUSER_PASSWORD, user_db.hashed_password)
verified, _ = verify_password(
settings.FIRST_SUPERUSER_PASSWORD, user_db.hashed_password
)
assert verified


def test_update_password_me_incorrect_password(
Expand DownExpand Up@@ -331,7 +335,8 @@ def test_register_user(client: TestClient, db: Session) -> None:
assert user_db
assert user_db.email == username
assert user_db.full_name == full_name
assert verify_password(password, user_db.hashed_password)
verified, _ = verify_password(password, user_db.hashed_password)
assert verified


def test_register_user_already_exists_error(client: TestClient) -> None:
Expand Down
41 changes: 40 additions & 1 deletion backend/tests/crud/test_user.py
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
from fastapi.encoders import jsonable_encoder
from pwdlib.hashers.bcrypt import BcryptHasher
from sqlmodel import Session

from app import crud
Expand DownExpand Up@@ -88,4 +89,42 @@ def test_update_user(db: Session) -> None:
user_2 = db.get(User, user.id)
assert user_2
assert user.email == user_2.email
assert verify_password(new_password, user_2.hashed_password)
verified, _ = verify_password(new_password, user_2.hashed_password)
assert verified


def test_authenticate_user_with_bcrypt_upgrades_to_argon2(db: Session) -> None:
"""Test that a user with bcrypt password hash gets upgraded to argon2 on login."""
email = random_email()
password = random_lower_string()

# Create a bcrypt hash directly (simulating legacy password)
bcrypt_hasher = BcryptHasher()
bcrypt_hash = bcrypt_hasher.hash(password)
assert bcrypt_hash.startswith("$2") # bcrypt hashes start with $2

# Create user with bcrypt hash directly in the database
user = User(email=email, hashed_password=bcrypt_hash)
db.add(user)
db.commit()
db.refresh(user)

# Verify the hash is bcrypt before authentication
assert user.hashed_password.startswith("$2")

# Authenticate - this should upgrade the hash to argon2
authenticated_user = crud.authenticate(session=db, email=email, password=password)
assert authenticated_user
assert authenticated_user.email == email

db.refresh(authenticated_user)

# Verify the hash was upgraded to argon2
assert authenticated_user.hashed_password.startswith("$argon2")

verified, updated_hash = verify_password(
password, authenticated_user.hashed_password
)
assert verified
# Should not need another update since it's already argon2
assert updated_hash is None
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion backend/app/api/routes/users.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -104,7 +104,8 @@ def update_password_me(
"""
Update own password.
"""
if not verify_password(body.current_password, current_user.hashed_password):
verified, _ = verify_password(body.current_password, current_user.hashed_password)
if not verified:
raise HTTPException(status_code=400, detail="Incorrect password")
if body.current_password == body.new_password:
raise HTTPException(
Expand Down
19 changes: 14 additions & 5 deletions backend/app/core/security.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,11 +2,18 @@
from typing import Any

import jwt
from passlib.context import CryptContext
from pwdlib import PasswordHash
from pwdlib.hashers.argon2 import Argon2Hasher
from pwdlib.hashers.bcrypt import BcryptHasher

from app.core.config import settings

pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
password_hash = PasswordHash(
(
Argon2Hasher(),
BcryptHasher(),
)
)


ALGORITHM = "HS256"
Expand All@@ -19,9 +26,11 @@ def create_access_token(subject: str | Any, expires_delta: timedelta) -> str:
return encoded_jwt


def verify_password(plain_password: str, hashed_password: str) -> bool:
return pwd_context.verify(plain_password, hashed_password)
def verify_password(
plain_password: str, hashed_password: str
) -> tuple[bool, str | None]:
return password_hash.verify_and_update(plain_password, hashed_password)


def get_password_hash(password: str) -> str:
return pwd_context.hash(password)
return password_hash.hash(password)
8 changes: 7 additions & 1 deletion backend/app/crud.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -41,8 +41,14 @@ def authenticate(*, session: Session, email: str, password: str) -> User | None:
db_user = get_user_by_email(session=session, email=email)
if not db_user:
return None
if not verify_password(password, db_user.hashed_password):
verified, updated_password_hash = verify_password(password, db_user.hashed_password)
if not verified:
return None
if updated_password_hash:
db_user.hashed_password = updated_password_hash
session.add(db_user)
session.commit()
session.refresh(db_user)
return db_user


Expand Down
5 changes: 1 addition & 4 deletions backend/pyproject.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,7 +7,6 @@ dependencies = [
"fastapi[standard]<1.0.0,>=0.114.2",
"python-multipart<1.0.0,>=0.0.7",
"email-validator<3.0.0.0,>=2.1.0.post1",
"passlib[bcrypt]<2.0.0,>=1.7.4",
"tenacity<9.0.0,>=8.2.3",
"pydantic>2.0",
"emails<1.0,>=0.6",
Expand All@@ -16,11 +15,10 @@ dependencies = [
"httpx<1.0.0,>=0.25.1",
"psycopg[binary]<4.0.0,>=3.1.13",
"sqlmodel<1.0.0,>=0.0.21",
# Pin bcrypt until passlib supports the latest
"bcrypt==4.3.0",
"pydantic-settings<3.0.0,>=2.2.1",
"sentry-sdk[fastapi]<2.0.0,>=1.40.6",
"pyjwt<3.0.0,>=2.8.0",
"pwdlib[argon2,bcrypt]>=0.3.0",
]

[dependency-groups]
Expand All@@ -29,7 +27,6 @@ dev = [
"mypy<2.0.0,>=1.8.0",
"ruff<1.0.0,>=0.2.2",
"prek>=0.2.24,<1.0.0",
"types-passlib<2.0.0.0,>=1.7.7.20240106",
"coverage<8.0.0,>=7.4.3",
]

Expand Down
73 changes: 70 additions & 3 deletions backend/tests/api/routes/test_login.py
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,13 @@
from unittest.mock import patch

from fastapi.testclient import TestClient
from pwdlib.hashers.bcrypt import BcryptHasher
from sqlmodel import Session

from app.core.config import settings
from app.core.security import verify_password
from app.core.security import get_password_hash, verify_password
from app.crud import create_user
from app.models import UserCreate
from app.models import User, UserCreate
from app.utils import generate_password_reset_token
from tests.utils.user import user_authentication_headers
from tests.utils.utils import random_email, random_lower_string
Expand DownExpand Up@@ -99,7 +100,8 @@ def test_reset_password(client: TestClient, db: Session) -> None:
assert r.json() == {"message": "Password updated successfully"}

db.refresh(user)
assert verify_password(new_password, user.hashed_password)
verified, _ = verify_password(new_password, user.hashed_password)
assert verified


def test_reset_password_invalid_token(
Expand All@@ -116,3 +118,68 @@ def test_reset_password_invalid_token(
assert "detail" in response
assert r.status_code == 400
assert response["detail"] == "Invalid token"


def test_login_with_bcrypt_password_upgrades_to_argon2(
client: TestClient, db: Session
) -> None:
"""Test that logging in with a bcrypt password hash upgrades it to argon2."""
email = random_email()
password = random_lower_string()

# Create a bcrypt hash directly (simulating legacy password)
bcrypt_hasher = BcryptHasher()
bcrypt_hash = bcrypt_hasher.hash(password)
assert bcrypt_hash.startswith("$2") # bcrypt hashes start with $2

user = User(email=email, hashed_password=bcrypt_hash, is_active=True)
db.add(user)
db.commit()
db.refresh(user)

assert user.hashed_password.startswith("$2")

login_data = {"username": email, "password": password}
r = client.post(f"{settings.API_V1_STR}/login/access-token", data=login_data)
assert r.status_code == 200
tokens = r.json()
assert "access_token" in tokens

db.refresh(user)

# Verify the hash was upgraded to argon2
assert user.hashed_password.startswith("$argon2")

verified, updated_hash = verify_password(password, user.hashed_password)
assert verified
# Should not need another update since it's already argon2
assert updated_hash is None


def test_login_with_argon2_password_keeps_hash(client: TestClient, db: Session) -> None:
"""Test that logging in with an argon2 password hash does not update it."""
email = random_email()
password = random_lower_string()

# Create an argon2 hash (current default)
argon2_hash = get_password_hash(password)
assert argon2_hash.startswith("$argon2")

# Create user with argon2 hash
user = User(email=email, hashed_password=argon2_hash, is_active=True)
db.add(user)
db.commit()
db.refresh(user)

original_hash = user.hashed_password

login_data = {"username": email, "password": password}
r = client.post(f"{settings.API_V1_STR}/login/access-token", data=login_data)
assert r.status_code == 200
tokens = r.json()
assert "access_token" in tokens

db.refresh(user)

assert user.hashed_password == original_hash
assert user.hashed_password.startswith("$argon2")
11 changes: 8 additions & 3 deletions backend/tests/api/routes/test_users.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -242,7 +242,8 @@ def test_update_password_me(
user_db = db.exec(user_query).first()
assert user_db
assert user_db.email == settings.FIRST_SUPERUSER
assert verify_password(new_password, user_db.hashed_password)
verified, _ = verify_password(new_password, user_db.hashed_password)
assert verified

# Revert to the old password to keep consistency in test
old_data = {
Expand All@@ -257,7 +258,10 @@ def test_update_password_me(
db.refresh(user_db)

assert r.status_code == 200
assert verify_password(settings.FIRST_SUPERUSER_PASSWORD, user_db.hashed_password)
verified, _ = verify_password(
settings.FIRST_SUPERUSER_PASSWORD, user_db.hashed_password
)
assert verified


def test_update_password_me_incorrect_password(
Expand DownExpand Up@@ -331,7 +335,8 @@ def test_register_user(client: TestClient, db: Session) -> None:
assert user_db
assert user_db.email == username
assert user_db.full_name == full_name
assert verify_password(password, user_db.hashed_password)
verified, _ = verify_password(password, user_db.hashed_password)
assert verified


def test_register_user_already_exists_error(client: TestClient) -> None:
Expand Down
41 changes: 40 additions & 1 deletion backend/tests/crud/test_user.py
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
from fastapi.encoders import jsonable_encoder
from pwdlib.hashers.bcrypt import BcryptHasher
from sqlmodel import Session

from app import crud
Expand DownExpand Up@@ -88,4 +89,42 @@ def test_update_user(db: Session) -> None:
user_2 = db.get(User, user.id)
assert user_2
assert user.email == user_2.email
assert verify_password(new_password, user_2.hashed_password)
verified, _ = verify_password(new_password, user_2.hashed_password)
assert verified


def test_authenticate_user_with_bcrypt_upgrades_to_argon2(db: Session) -> None:
"""Test that a user with bcrypt password hash gets upgraded to argon2 on login."""
email = random_email()
password = random_lower_string()

# Create a bcrypt hash directly (simulating legacy password)
bcrypt_hasher = BcryptHasher()
bcrypt_hash = bcrypt_hasher.hash(password)
assert bcrypt_hash.startswith("$2") # bcrypt hashes start with $2

# Create user with bcrypt hash directly in the database
user = User(email=email, hashed_password=bcrypt_hash)
db.add(user)
db.commit()
db.refresh(user)

# Verify the hash is bcrypt before authentication
assert user.hashed_password.startswith("$2")

# Authenticate - this should upgrade the hash to argon2
authenticated_user = crud.authenticate(session=db, email=email, password=password)
assert authenticated_user
assert authenticated_user.email == email

db.refresh(authenticated_user)

# Verify the hash was upgraded to argon2
assert authenticated_user.hashed_password.startswith("$argon2")

verified, updated_hash = verify_password(
password, authenticated_user.hashed_password
)
assert verified
# Should not need another update since it's already argon2
assert updated_hash is None
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion backend/app/api/routes/users.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -104,7 +104,8 @@ def update_password_me(
"""
Update own password.
"""
if not verify_password(body.current_password, current_user.hashed_password):
verified, _ = verify_password(body.current_password, current_user.hashed_password)
if not verified:
raise HTTPException(status_code=400, detail="Incorrect password")
if body.current_password == body.new_password:
raise HTTPException(
Expand Down
19 changes: 14 additions & 5 deletions backend/app/core/security.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,11 +2,18 @@
from typing import Any

import jwt
from passlib.context import CryptContext
from pwdlib import PasswordHash
from pwdlib.hashers.argon2 import Argon2Hasher
from pwdlib.hashers.bcrypt import BcryptHasher

from app.core.config import settings

pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
password_hash = PasswordHash(
(
Argon2Hasher(),
BcryptHasher(),
)
)


ALGORITHM = "HS256"
Expand All@@ -19,9 +26,11 @@ def create_access_token(subject: str | Any, expires_delta: timedelta) -> str:
return encoded_jwt


def verify_password(plain_password: str, hashed_password: str) -> bool:
return pwd_context.verify(plain_password, hashed_password)
def verify_password(
plain_password: str, hashed_password: str
) -> tuple[bool, str | None]:
return password_hash.verify_and_update(plain_password, hashed_password)


def get_password_hash(password: str) -> str:
return pwd_context.hash(password)
return password_hash.hash(password)
8 changes: 7 additions & 1 deletion backend/app/crud.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -41,8 +41,14 @@ def authenticate(*, session: Session, email: str, password: str) -> User | None:
db_user = get_user_by_email(session=session, email=email)
if not db_user:
return None
if not verify_password(password, db_user.hashed_password):
verified, updated_password_hash = verify_password(password, db_user.hashed_password)
if not verified:
return None
if updated_password_hash:
db_user.hashed_password = updated_password_hash
session.add(db_user)
session.commit()
session.refresh(db_user)
return db_user


Expand Down
5 changes: 1 addition & 4 deletions backend/pyproject.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,7 +7,6 @@ dependencies = [
"fastapi[standard]<1.0.0,>=0.114.2",
"python-multipart<1.0.0,>=0.0.7",
"email-validator<3.0.0.0,>=2.1.0.post1",
"passlib[bcrypt]<2.0.0,>=1.7.4",
"tenacity<9.0.0,>=8.2.3",
"pydantic>2.0",
"emails<1.0,>=0.6",
Expand All@@ -16,11 +15,10 @@ dependencies = [
"httpx<1.0.0,>=0.25.1",
"psycopg[binary]<4.0.0,>=3.1.13",
"sqlmodel<1.0.0,>=0.0.21",
# Pin bcrypt until passlib supports the latest
"bcrypt==4.3.0",
"pydantic-settings<3.0.0,>=2.2.1",
"sentry-sdk[fastapi]<2.0.0,>=1.40.6",
"pyjwt<3.0.0,>=2.8.0",
"pwdlib[argon2,bcrypt]>=0.3.0",
]

[dependency-groups]
Expand All@@ -29,7 +27,6 @@ dev = [
"mypy<2.0.0,>=1.8.0",
"ruff<1.0.0,>=0.2.2",
"prek>=0.2.24,<1.0.0",
"types-passlib<2.0.0.0,>=1.7.7.20240106",
"coverage<8.0.0,>=7.4.3",
]

Expand Down
73 changes: 70 additions & 3 deletions backend/tests/api/routes/test_login.py
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,13 @@
from unittest.mock import patch

from fastapi.testclient import TestClient
from pwdlib.hashers.bcrypt import BcryptHasher
from sqlmodel import Session

from app.core.config import settings
from app.core.security import verify_password
from app.core.security import get_password_hash, verify_password
from app.crud import create_user
from app.models import UserCreate
from app.models import User, UserCreate
from app.utils import generate_password_reset_token
from tests.utils.user import user_authentication_headers
from tests.utils.utils import random_email, random_lower_string
Expand DownExpand Up@@ -99,7 +100,8 @@ def test_reset_password(client: TestClient, db: Session) -> None:
assert r.json() == {"message": "Password updated successfully"}

db.refresh(user)
assert verify_password(new_password, user.hashed_password)
verified, _ = verify_password(new_password, user.hashed_password)
assert verified


def test_reset_password_invalid_token(
Expand All@@ -116,3 +118,68 @@ def test_reset_password_invalid_token(
assert "detail" in response
assert r.status_code == 400
assert response["detail"] == "Invalid token"


def test_login_with_bcrypt_password_upgrades_to_argon2(
client: TestClient, db: Session
) -> None:
"""Test that logging in with a bcrypt password hash upgrades it to argon2."""
email = random_email()
password = random_lower_string()

# Create a bcrypt hash directly (simulating legacy password)
bcrypt_hasher = BcryptHasher()
bcrypt_hash = bcrypt_hasher.hash(password)
assert bcrypt_hash.startswith("$2") # bcrypt hashes start with $2

user = User(email=email, hashed_password=bcrypt_hash, is_active=True)
db.add(user)
db.commit()
db.refresh(user)

assert user.hashed_password.startswith("$2")

login_data = {"username": email, "password": password}
r = client.post(f"{settings.API_V1_STR}/login/access-token", data=login_data)
assert r.status_code == 200
tokens = r.json()
assert "access_token" in tokens

db.refresh(user)

# Verify the hash was upgraded to argon2
assert user.hashed_password.startswith("$argon2")

verified, updated_hash = verify_password(password, user.hashed_password)
assert verified
# Should not need another update since it's already argon2
assert updated_hash is None


def test_login_with_argon2_password_keeps_hash(client: TestClient, db: Session) -> None:
"""Test that logging in with an argon2 password hash does not update it."""
email = random_email()
password = random_lower_string()

# Create an argon2 hash (current default)
argon2_hash = get_password_hash(password)
assert argon2_hash.startswith("$argon2")

# Create user with argon2 hash
user = User(email=email, hashed_password=argon2_hash, is_active=True)
db.add(user)
db.commit()
db.refresh(user)

original_hash = user.hashed_password

login_data = {"username": email, "password": password}
r = client.post(f"{settings.API_V1_STR}/login/access-token", data=login_data)
assert r.status_code == 200
tokens = r.json()
assert "access_token" in tokens

db.refresh(user)

assert user.hashed_password == original_hash
assert user.hashed_password.startswith("$argon2")
11 changes: 8 additions & 3 deletions backend/tests/api/routes/test_users.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -242,7 +242,8 @@ def test_update_password_me(
user_db = db.exec(user_query).first()
assert user_db
assert user_db.email == settings.FIRST_SUPERUSER
assert verify_password(new_password, user_db.hashed_password)
verified, _ = verify_password(new_password, user_db.hashed_password)
assert verified

# Revert to the old password to keep consistency in test
old_data = {
Expand All@@ -257,7 +258,10 @@ def test_update_password_me(
db.refresh(user_db)

assert r.status_code == 200
assert verify_password(settings.FIRST_SUPERUSER_PASSWORD, user_db.hashed_password)
verified, _ = verify_password(
settings.FIRST_SUPERUSER_PASSWORD, user_db.hashed_password
)
assert verified


def test_update_password_me_incorrect_password(
Expand DownExpand Up@@ -331,7 +335,8 @@ def test_register_user(client: TestClient, db: Session) -> None:
assert user_db
assert user_db.email == username
assert user_db.full_name == full_name
assert verify_password(password, user_db.hashed_password)
verified, _ = verify_password(password, user_db.hashed_password)
assert verified


def test_register_user_already_exists_error(client: TestClient) -> None:
Expand Down
41 changes: 40 additions & 1 deletion backend/tests/crud/test_user.py
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
from fastapi.encoders import jsonable_encoder
from pwdlib.hashers.bcrypt import BcryptHasher
from sqlmodel import Session

from app import crud
Expand DownExpand Up@@ -88,4 +89,42 @@ def test_update_user(db: Session) -> None:
user_2 = db.get(User, user.id)
assert user_2
assert user.email == user_2.email
assert verify_password(new_password, user_2.hashed_password)
verified, _ = verify_password(new_password, user_2.hashed_password)
assert verified


def test_authenticate_user_with_bcrypt_upgrades_to_argon2(db: Session) -> None:
"""Test that a user with bcrypt password hash gets upgraded to argon2 on login."""
email = random_email()
password = random_lower_string()

# Create a bcrypt hash directly (simulating legacy password)
bcrypt_hasher = BcryptHasher()
bcrypt_hash = bcrypt_hasher.hash(password)
assert bcrypt_hash.startswith("$2") # bcrypt hashes start with $2

# Create user with bcrypt hash directly in the database
user = User(email=email, hashed_password=bcrypt_hash)
db.add(user)
db.commit()
db.refresh(user)

# Verify the hash is bcrypt before authentication
assert user.hashed_password.startswith("$2")

# Authenticate - this should upgrade the hash to argon2
authenticated_user = crud.authenticate(session=db, email=email, password=password)
assert authenticated_user
assert authenticated_user.email == email

db.refresh(authenticated_user)

# Verify the hash was upgraded to argon2
assert authenticated_user.hashed_password.startswith("$argon2")

verified, updated_hash = verify_password(
password, authenticated_user.hashed_password
)
assert verified
# Should not need another update since it's already argon2
assert updated_hash is None
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion backend/app/api/routes/users.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -104,7 +104,8 @@ def update_password_me(
"""
Update own password.
"""
if not verify_password(body.current_password, current_user.hashed_password):
verified, _ = verify_password(body.current_password, current_user.hashed_password)
if not verified:
raise HTTPException(status_code=400, detail="Incorrect password")
if body.current_password == body.new_password:
raise HTTPException(
Expand Down
19 changes: 14 additions & 5 deletions backend/app/core/security.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,11 +2,18 @@
from typing import Any

import jwt
from passlib.context import CryptContext
from pwdlib import PasswordHash
from pwdlib.hashers.argon2 import Argon2Hasher
from pwdlib.hashers.bcrypt import BcryptHasher

from app.core.config import settings

pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
password_hash = PasswordHash(
(
Argon2Hasher(),
BcryptHasher(),
)
)


ALGORITHM = "HS256"
Expand All@@ -19,9 +26,11 @@ def create_access_token(subject: str | Any, expires_delta: timedelta) -> str:
return encoded_jwt


def verify_password(plain_password: str, hashed_password: str) -> bool:
return pwd_context.verify(plain_password, hashed_password)
def verify_password(
plain_password: str, hashed_password: str
) -> tuple[bool, str | None]:
return password_hash.verify_and_update(plain_password, hashed_password)


def get_password_hash(password: str) -> str:
return pwd_context.hash(password)
return password_hash.hash(password)
8 changes: 7 additions & 1 deletion backend/app/crud.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -41,8 +41,14 @@ def authenticate(*, session: Session, email: str, password: str) -> User | None:
db_user = get_user_by_email(session=session, email=email)
if not db_user:
return None
if not verify_password(password, db_user.hashed_password):
verified, updated_password_hash = verify_password(password, db_user.hashed_password)
if not verified:
return None
if updated_password_hash:
db_user.hashed_password = updated_password_hash
session.add(db_user)
session.commit()
session.refresh(db_user)
return db_user


Expand Down
5 changes: 1 addition & 4 deletions backend/pyproject.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,7 +7,6 @@ dependencies = [
"fastapi[standard]<1.0.0,>=0.114.2",
"python-multipart<1.0.0,>=0.0.7",
"email-validator<3.0.0.0,>=2.1.0.post1",
"passlib[bcrypt]<2.0.0,>=1.7.4",
"tenacity<9.0.0,>=8.2.3",
"pydantic>2.0",
"emails<1.0,>=0.6",
Expand All@@ -16,11 +15,10 @@ dependencies = [
"httpx<1.0.0,>=0.25.1",
"psycopg[binary]<4.0.0,>=3.1.13",
"sqlmodel<1.0.0,>=0.0.21",
# Pin bcrypt until passlib supports the latest
"bcrypt==4.3.0",
"pydantic-settings<3.0.0,>=2.2.1",
"sentry-sdk[fastapi]<2.0.0,>=1.40.6",
"pyjwt<3.0.0,>=2.8.0",
"pwdlib[argon2,bcrypt]>=0.3.0",
]

[dependency-groups]
Expand All@@ -29,7 +27,6 @@ dev = [
"mypy<2.0.0,>=1.8.0",
"ruff<1.0.0,>=0.2.2",
"prek>=0.2.24,<1.0.0",
"types-passlib<2.0.0.0,>=1.7.7.20240106",
"coverage<8.0.0,>=7.4.3",
]

Expand Down
73 changes: 70 additions & 3 deletions backend/tests/api/routes/test_login.py
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,13 @@
from unittest.mock import patch

from fastapi.testclient import TestClient
from pwdlib.hashers.bcrypt import BcryptHasher
from sqlmodel import Session

from app.core.config import settings
from app.core.security import verify_password
from app.core.security import get_password_hash, verify_password
from app.crud import create_user
from app.models import UserCreate
from app.models import User, UserCreate
from app.utils import generate_password_reset_token
from tests.utils.user import user_authentication_headers
from tests.utils.utils import random_email, random_lower_string
Expand DownExpand Up@@ -99,7 +100,8 @@ def test_reset_password(client: TestClient, db: Session) -> None:
assert r.json() == {"message": "Password updated successfully"}

db.refresh(user)
assert verify_password(new_password, user.hashed_password)
verified, _ = verify_password(new_password, user.hashed_password)
assert verified


def test_reset_password_invalid_token(
Expand All@@ -116,3 +118,68 @@ def test_reset_password_invalid_token(
assert "detail" in response
assert r.status_code == 400
assert response["detail"] == "Invalid token"


def test_login_with_bcrypt_password_upgrades_to_argon2(
client: TestClient, db: Session
) -> None:
"""Test that logging in with a bcrypt password hash upgrades it to argon2."""
email = random_email()
password = random_lower_string()

# Create a bcrypt hash directly (simulating legacy password)
bcrypt_hasher = BcryptHasher()
bcrypt_hash = bcrypt_hasher.hash(password)
assert bcrypt_hash.startswith("$2") # bcrypt hashes start with $2

user = User(email=email, hashed_password=bcrypt_hash, is_active=True)
db.add(user)
db.commit()
db.refresh(user)

assert user.hashed_password.startswith("$2")

login_data = {"username": email, "password": password}
r = client.post(f"{settings.API_V1_STR}/login/access-token", data=login_data)
assert r.status_code == 200
tokens = r.json()
assert "access_token" in tokens

db.refresh(user)

# Verify the hash was upgraded to argon2
assert user.hashed_password.startswith("$argon2")

verified, updated_hash = verify_password(password, user.hashed_password)
assert verified
# Should not need another update since it's already argon2
assert updated_hash is None


def test_login_with_argon2_password_keeps_hash(client: TestClient, db: Session) -> None:
"""Test that logging in with an argon2 password hash does not update it."""
email = random_email()
password = random_lower_string()

# Create an argon2 hash (current default)
argon2_hash = get_password_hash(password)
assert argon2_hash.startswith("$argon2")

# Create user with argon2 hash
user = User(email=email, hashed_password=argon2_hash, is_active=True)
db.add(user)
db.commit()
db.refresh(user)

original_hash = user.hashed_password

login_data = {"username": email, "password": password}
r = client.post(f"{settings.API_V1_STR}/login/access-token", data=login_data)
assert r.status_code == 200
tokens = r.json()
assert "access_token" in tokens

db.refresh(user)

assert user.hashed_password == original_hash
assert user.hashed_password.startswith("$argon2")
11 changes: 8 additions & 3 deletions backend/tests/api/routes/test_users.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -242,7 +242,8 @@ def test_update_password_me(
user_db = db.exec(user_query).first()
assert user_db
assert user_db.email == settings.FIRST_SUPERUSER
assert verify_password(new_password, user_db.hashed_password)
verified, _ = verify_password(new_password, user_db.hashed_password)
assert verified

# Revert to the old password to keep consistency in test
old_data = {
Expand All@@ -257,7 +258,10 @@ def test_update_password_me(
db.refresh(user_db)

assert r.status_code == 200
assert verify_password(settings.FIRST_SUPERUSER_PASSWORD, user_db.hashed_password)
verified, _ = verify_password(
settings.FIRST_SUPERUSER_PASSWORD, user_db.hashed_password
)
assert verified


def test_update_password_me_incorrect_password(
Expand DownExpand Up@@ -331,7 +335,8 @@ def test_register_user(client: TestClient, db: Session) -> None:
assert user_db
assert user_db.email == username
assert user_db.full_name == full_name
assert verify_password(password, user_db.hashed_password)
verified, _ = verify_password(password, user_db.hashed_password)
assert verified


def test_register_user_already_exists_error(client: TestClient) -> None:
Expand Down
41 changes: 40 additions & 1 deletion backend/tests/crud/test_user.py
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
from fastapi.encoders import jsonable_encoder
from pwdlib.hashers.bcrypt import BcryptHasher
from sqlmodel import Session

from app import crud
Expand DownExpand Up@@ -88,4 +89,42 @@ def test_update_user(db: Session) -> None:
user_2 = db.get(User, user.id)
assert user_2
assert user.email == user_2.email
assert verify_password(new_password, user_2.hashed_password)
verified, _ = verify_password(new_password, user_2.hashed_password)
assert verified


def test_authenticate_user_with_bcrypt_upgrades_to_argon2(db: Session) -> None:
"""Test that a user with bcrypt password hash gets upgraded to argon2 on login."""
email = random_email()
password = random_lower_string()

# Create a bcrypt hash directly (simulating legacy password)
bcrypt_hasher = BcryptHasher()
bcrypt_hash = bcrypt_hasher.hash(password)
assert bcrypt_hash.startswith("$2") # bcrypt hashes start with $2

# Create user with bcrypt hash directly in the database
user = User(email=email, hashed_password=bcrypt_hash)
db.add(user)
db.commit()
db.refresh(user)

# Verify the hash is bcrypt before authentication
assert user.hashed_password.startswith("$2")

# Authenticate - this should upgrade the hash to argon2
authenticated_user = crud.authenticate(session=db, email=email, password=password)
assert authenticated_user
assert authenticated_user.email == email

db.refresh(authenticated_user)

# Verify the hash was upgraded to argon2
assert authenticated_user.hashed_password.startswith("$argon2")

verified, updated_hash = verify_password(
password, authenticated_user.hashed_password
)
assert verified
# Should not need another update since it's already argon2
assert updated_hash is None
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion backend/app/api/routes/users.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -104,7 +104,8 @@ def update_password_me(
"""
Update own password.
"""
if not verify_password(body.current_password, current_user.hashed_password):
verified, _ = verify_password(body.current_password, current_user.hashed_password)
if not verified:
raise HTTPException(status_code=400, detail="Incorrect password")
if body.current_password == body.new_password:
raise HTTPException(
Expand Down
19 changes: 14 additions & 5 deletions backend/app/core/security.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,11 +2,18 @@
from typing import Any

import jwt
from passlib.context import CryptContext
from pwdlib import PasswordHash
from pwdlib.hashers.argon2 import Argon2Hasher
from pwdlib.hashers.bcrypt import BcryptHasher

from app.core.config import settings

pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
password_hash = PasswordHash(
(
Argon2Hasher(),
BcryptHasher(),
)
)


ALGORITHM = "HS256"
Expand All@@ -19,9 +26,11 @@ def create_access_token(subject: str | Any, expires_delta: timedelta) -> str:
return encoded_jwt


def verify_password(plain_password: str, hashed_password: str) -> bool:
return pwd_context.verify(plain_password, hashed_password)
def verify_password(
plain_password: str, hashed_password: str
) -> tuple[bool, str | None]:
return password_hash.verify_and_update(plain_password, hashed_password)


def get_password_hash(password: str) -> str:
return pwd_context.hash(password)
return password_hash.hash(password)
8 changes: 7 additions & 1 deletion backend/app/crud.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -41,8 +41,14 @@ def authenticate(*, session: Session, email: str, password: str) -> User | None:
db_user = get_user_by_email(session=session, email=email)
if not db_user:
return None
if not verify_password(password, db_user.hashed_password):
verified, updated_password_hash = verify_password(password, db_user.hashed_password)
if not verified:
return None
if updated_password_hash:
db_user.hashed_password = updated_password_hash
session.add(db_user)
session.commit()
session.refresh(db_user)
return db_user


Expand Down
5 changes: 1 addition & 4 deletions backend/pyproject.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,7 +7,6 @@ dependencies = [
"fastapi[standard]<1.0.0,>=0.114.2",
"python-multipart<1.0.0,>=0.0.7",
"email-validator<3.0.0.0,>=2.1.0.post1",
"passlib[bcrypt]<2.0.0,>=1.7.4",
"tenacity<9.0.0,>=8.2.3",
"pydantic>2.0",
"emails<1.0,>=0.6",
Expand All@@ -16,11 +15,10 @@ dependencies = [
"httpx<1.0.0,>=0.25.1",
"psycopg[binary]<4.0.0,>=3.1.13",
"sqlmodel<1.0.0,>=0.0.21",
# Pin bcrypt until passlib supports the latest
"bcrypt==4.3.0",
"pydantic-settings<3.0.0,>=2.2.1",
"sentry-sdk[fastapi]<2.0.0,>=1.40.6",
"pyjwt<3.0.0,>=2.8.0",
"pwdlib[argon2,bcrypt]>=0.3.0",
]

[dependency-groups]
Expand All@@ -29,7 +27,6 @@ dev = [
"mypy<2.0.0,>=1.8.0",
"ruff<1.0.0,>=0.2.2",
"prek>=0.2.24,<1.0.0",
"types-passlib<2.0.0.0,>=1.7.7.20240106",
"coverage<8.0.0,>=7.4.3",
]

Expand Down
73 changes: 70 additions & 3 deletions backend/tests/api/routes/test_login.py
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,13 @@
from unittest.mock import patch

from fastapi.testclient import TestClient
from pwdlib.hashers.bcrypt import BcryptHasher
from sqlmodel import Session

from app.core.config import settings
from app.core.security import verify_password
from app.core.security import get_password_hash, verify_password
from app.crud import create_user
from app.models import UserCreate
from app.models import User, UserCreate
from app.utils import generate_password_reset_token
from tests.utils.user import user_authentication_headers
from tests.utils.utils import random_email, random_lower_string
Expand DownExpand Up@@ -99,7 +100,8 @@ def test_reset_password(client: TestClient, db: Session) -> None:
assert r.json() == {"message": "Password updated successfully"}

db.refresh(user)
assert verify_password(new_password, user.hashed_password)
verified, _ = verify_password(new_password, user.hashed_password)
assert verified


def test_reset_password_invalid_token(
Expand All@@ -116,3 +118,68 @@ def test_reset_password_invalid_token(
assert "detail" in response
assert r.status_code == 400
assert response["detail"] == "Invalid token"


def test_login_with_bcrypt_password_upgrades_to_argon2(
client: TestClient, db: Session
) -> None:
"""Test that logging in with a bcrypt password hash upgrades it to argon2."""
email = random_email()
password = random_lower_string()

# Create a bcrypt hash directly (simulating legacy password)
bcrypt_hasher = BcryptHasher()
bcrypt_hash = bcrypt_hasher.hash(password)
assert bcrypt_hash.startswith("$2") # bcrypt hashes start with $2

user = User(email=email, hashed_password=bcrypt_hash, is_active=True)
db.add(user)
db.commit()
db.refresh(user)

assert user.hashed_password.startswith("$2")

login_data = {"username": email, "password": password}
r = client.post(f"{settings.API_V1_STR}/login/access-token", data=login_data)
assert r.status_code == 200
tokens = r.json()
assert "access_token" in tokens

db.refresh(user)

# Verify the hash was upgraded to argon2
assert user.hashed_password.startswith("$argon2")

verified, updated_hash = verify_password(password, user.hashed_password)
assert verified
# Should not need another update since it's already argon2
assert updated_hash is None


def test_login_with_argon2_password_keeps_hash(client: TestClient, db: Session) -> None:
"""Test that logging in with an argon2 password hash does not update it."""
email = random_email()
password = random_lower_string()

# Create an argon2 hash (current default)
argon2_hash = get_password_hash(password)
assert argon2_hash.startswith("$argon2")

# Create user with argon2 hash
user = User(email=email, hashed_password=argon2_hash, is_active=True)
db.add(user)
db.commit()
db.refresh(user)

original_hash = user.hashed_password

login_data = {"username": email, "password": password}
r = client.post(f"{settings.API_V1_STR}/login/access-token", data=login_data)
assert r.status_code == 200
tokens = r.json()
assert "access_token" in tokens

db.refresh(user)

assert user.hashed_password == original_hash
assert user.hashed_password.startswith("$argon2")
11 changes: 8 additions & 3 deletions backend/tests/api/routes/test_users.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -242,7 +242,8 @@ def test_update_password_me(
user_db = db.exec(user_query).first()
assert user_db
assert user_db.email == settings.FIRST_SUPERUSER
assert verify_password(new_password, user_db.hashed_password)
verified, _ = verify_password(new_password, user_db.hashed_password)
assert verified

# Revert to the old password to keep consistency in test
old_data = {
Expand All@@ -257,7 +258,10 @@ def test_update_password_me(
db.refresh(user_db)

assert r.status_code == 200
assert verify_password(settings.FIRST_SUPERUSER_PASSWORD, user_db.hashed_password)
verified, _ = verify_password(
settings.FIRST_SUPERUSER_PASSWORD, user_db.hashed_password
)
assert verified


def test_update_password_me_incorrect_password(
Expand DownExpand Up@@ -331,7 +335,8 @@ def test_register_user(client: TestClient, db: Session) -> None:
assert user_db
assert user_db.email == username
assert user_db.full_name == full_name
assert verify_password(password, user_db.hashed_password)
verified, _ = verify_password(password, user_db.hashed_password)
assert verified


def test_register_user_already_exists_error(client: TestClient) -> None:
Expand Down
41 changes: 40 additions & 1 deletion backend/tests/crud/test_user.py
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
from fastapi.encoders import jsonable_encoder
from pwdlib.hashers.bcrypt import BcryptHasher
from sqlmodel import Session

from app import crud
Expand DownExpand Up@@ -88,4 +89,42 @@ def test_update_user(db: Session) -> None:
user_2 = db.get(User, user.id)
assert user_2
assert user.email == user_2.email
assert verify_password(new_password, user_2.hashed_password)
verified, _ = verify_password(new_password, user_2.hashed_password)
assert verified


def test_authenticate_user_with_bcrypt_upgrades_to_argon2(db: Session) -> None:
"""Test that a user with bcrypt password hash gets upgraded to argon2 on login."""
email = random_email()
password = random_lower_string()

# Create a bcrypt hash directly (simulating legacy password)
bcrypt_hasher = BcryptHasher()
bcrypt_hash = bcrypt_hasher.hash(password)
assert bcrypt_hash.startswith("$2") # bcrypt hashes start with $2

# Create user with bcrypt hash directly in the database
user = User(email=email, hashed_password=bcrypt_hash)
db.add(user)
db.commit()
db.refresh(user)

# Verify the hash is bcrypt before authentication
assert user.hashed_password.startswith("$2")

# Authenticate - this should upgrade the hash to argon2
authenticated_user = crud.authenticate(session=db, email=email, password=password)
assert authenticated_user
assert authenticated_user.email == email

db.refresh(authenticated_user)

# Verify the hash was upgraded to argon2
assert authenticated_user.hashed_password.startswith("$argon2")

verified, updated_hash = verify_password(
password, authenticated_user.hashed_password
)
assert verified
# Should not need another update since it's already argon2
assert updated_hash is None
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion backend/app/api/routes/users.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -104,7 +104,8 @@ def update_password_me(
"""
Update own password.
"""
if not verify_password(body.current_password, current_user.hashed_password):
verified, _ = verify_password(body.current_password, current_user.hashed_password)
if not verified:
raise HTTPException(status_code=400, detail="Incorrect password")
if body.current_password == body.new_password:
raise HTTPException(
Expand Down
19 changes: 14 additions & 5 deletions backend/app/core/security.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,11 +2,18 @@
from typing import Any

import jwt
from passlib.context import CryptContext
from pwdlib import PasswordHash
from pwdlib.hashers.argon2 import Argon2Hasher
from pwdlib.hashers.bcrypt import BcryptHasher

from app.core.config import settings

pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
password_hash = PasswordHash(
(
Argon2Hasher(),
BcryptHasher(),
)
)


ALGORITHM = "HS256"
Expand All@@ -19,9 +26,11 @@ def create_access_token(subject: str | Any, expires_delta: timedelta) -> str:
return encoded_jwt


def verify_password(plain_password: str, hashed_password: str) -> bool:
return pwd_context.verify(plain_password, hashed_password)
def verify_password(
plain_password: str, hashed_password: str
) -> tuple[bool, str | None]:
return password_hash.verify_and_update(plain_password, hashed_password)


def get_password_hash(password: str) -> str:
return pwd_context.hash(password)
return password_hash.hash(password)
8 changes: 7 additions & 1 deletion backend/app/crud.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -41,8 +41,14 @@ def authenticate(*, session: Session, email: str, password: str) -> User | None:
db_user = get_user_by_email(session=session, email=email)
if not db_user:
return None
if not verify_password(password, db_user.hashed_password):
verified, updated_password_hash = verify_password(password, db_user.hashed_password)
if not verified:
return None
if updated_password_hash:
db_user.hashed_password = updated_password_hash
session.add(db_user)
session.commit()
session.refresh(db_user)
return db_user


Expand Down
5 changes: 1 addition & 4 deletions backend/pyproject.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,7 +7,6 @@ dependencies = [
"fastapi[standard]<1.0.0,>=0.114.2",
"python-multipart<1.0.0,>=0.0.7",
"email-validator<3.0.0.0,>=2.1.0.post1",
"passlib[bcrypt]<2.0.0,>=1.7.4",
"tenacity<9.0.0,>=8.2.3",
"pydantic>2.0",
"emails<1.0,>=0.6",
Expand All@@ -16,11 +15,10 @@ dependencies = [
"httpx<1.0.0,>=0.25.1",
"psycopg[binary]<4.0.0,>=3.1.13",
"sqlmodel<1.0.0,>=0.0.21",
# Pin bcrypt until passlib supports the latest
"bcrypt==4.3.0",
"pydantic-settings<3.0.0,>=2.2.1",
"sentry-sdk[fastapi]<2.0.0,>=1.40.6",
"pyjwt<3.0.0,>=2.8.0",
"pwdlib[argon2,bcrypt]>=0.3.0",
]

[dependency-groups]
Expand All@@ -29,7 +27,6 @@ dev = [
"mypy<2.0.0,>=1.8.0",
"ruff<1.0.0,>=0.2.2",
"prek>=0.2.24,<1.0.0",
"types-passlib<2.0.0.0,>=1.7.7.20240106",
"coverage<8.0.0,>=7.4.3",
]

Expand Down
73 changes: 70 additions & 3 deletions backend/tests/api/routes/test_login.py
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,13 @@
from unittest.mock import patch

from fastapi.testclient import TestClient
from pwdlib.hashers.bcrypt import BcryptHasher
from sqlmodel import Session

from app.core.config import settings
from app.core.security import verify_password
from app.core.security import get_password_hash, verify_password
from app.crud import create_user
from app.models import UserCreate
from app.models import User, UserCreate
from app.utils import generate_password_reset_token
from tests.utils.user import user_authentication_headers
from tests.utils.utils import random_email, random_lower_string
Expand DownExpand Up@@ -99,7 +100,8 @@ def test_reset_password(client: TestClient, db: Session) -> None:
assert r.json() == {"message": "Password updated successfully"}

db.refresh(user)
assert verify_password(new_password, user.hashed_password)
verified, _ = verify_password(new_password, user.hashed_password)
assert verified


def test_reset_password_invalid_token(
Expand All@@ -116,3 +118,68 @@ def test_reset_password_invalid_token(
assert "detail" in response
assert r.status_code == 400
assert response["detail"] == "Invalid token"


def test_login_with_bcrypt_password_upgrades_to_argon2(
client: TestClient, db: Session
) -> None:
"""Test that logging in with a bcrypt password hash upgrades it to argon2."""
email = random_email()
password = random_lower_string()

# Create a bcrypt hash directly (simulating legacy password)
bcrypt_hasher = BcryptHasher()
bcrypt_hash = bcrypt_hasher.hash(password)
assert bcrypt_hash.startswith("$2") # bcrypt hashes start with $2

user = User(email=email, hashed_password=bcrypt_hash, is_active=True)
db.add(user)
db.commit()
db.refresh(user)

assert user.hashed_password.startswith("$2")

login_data = {"username": email, "password": password}
r = client.post(f"{settings.API_V1_STR}/login/access-token", data=login_data)
assert r.status_code == 200
tokens = r.json()
assert "access_token" in tokens

db.refresh(user)

# Verify the hash was upgraded to argon2
assert user.hashed_password.startswith("$argon2")

verified, updated_hash = verify_password(password, user.hashed_password)
assert verified
# Should not need another update since it's already argon2
assert updated_hash is None


def test_login_with_argon2_password_keeps_hash(client: TestClient, db: Session) -> None:
"""Test that logging in with an argon2 password hash does not update it."""
email = random_email()
password = random_lower_string()

# Create an argon2 hash (current default)
argon2_hash = get_password_hash(password)
assert argon2_hash.startswith("$argon2")

# Create user with argon2 hash
user = User(email=email, hashed_password=argon2_hash, is_active=True)
db.add(user)
db.commit()
db.refresh(user)

original_hash = user.hashed_password

login_data = {"username": email, "password": password}
r = client.post(f"{settings.API_V1_STR}/login/access-token", data=login_data)
assert r.status_code == 200
tokens = r.json()
assert "access_token" in tokens

db.refresh(user)

assert user.hashed_password == original_hash
assert user.hashed_password.startswith("$argon2")
11 changes: 8 additions & 3 deletions backend/tests/api/routes/test_users.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -242,7 +242,8 @@ def test_update_password_me(
user_db = db.exec(user_query).first()
assert user_db
assert user_db.email == settings.FIRST_SUPERUSER
assert verify_password(new_password, user_db.hashed_password)
verified, _ = verify_password(new_password, user_db.hashed_password)
assert verified

# Revert to the old password to keep consistency in test
old_data = {
Expand All@@ -257,7 +258,10 @@ def test_update_password_me(
db.refresh(user_db)

assert r.status_code == 200
assert verify_password(settings.FIRST_SUPERUSER_PASSWORD, user_db.hashed_password)
verified, _ = verify_password(
settings.FIRST_SUPERUSER_PASSWORD, user_db.hashed_password
)
assert verified


def test_update_password_me_incorrect_password(
Expand DownExpand Up@@ -331,7 +335,8 @@ def test_register_user(client: TestClient, db: Session) -> None:
assert user_db
assert user_db.email == username
assert user_db.full_name == full_name
assert verify_password(password, user_db.hashed_password)
verified, _ = verify_password(password, user_db.hashed_password)
assert verified


def test_register_user_already_exists_error(client: TestClient) -> None:
Expand Down
41 changes: 40 additions & 1 deletion backend/tests/crud/test_user.py
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
from fastapi.encoders import jsonable_encoder
from pwdlib.hashers.bcrypt import BcryptHasher
from sqlmodel import Session

from app import crud
Expand DownExpand Up@@ -88,4 +89,42 @@ def test_update_user(db: Session) -> None:
user_2 = db.get(User, user.id)
assert user_2
assert user.email == user_2.email
assert verify_password(new_password, user_2.hashed_password)
verified, _ = verify_password(new_password, user_2.hashed_password)
assert verified


def test_authenticate_user_with_bcrypt_upgrades_to_argon2(db: Session) -> None:
"""Test that a user with bcrypt password hash gets upgraded to argon2 on login."""
email = random_email()
password = random_lower_string()

# Create a bcrypt hash directly (simulating legacy password)
bcrypt_hasher = BcryptHasher()
bcrypt_hash = bcrypt_hasher.hash(password)
assert bcrypt_hash.startswith("$2") # bcrypt hashes start with $2

# Create user with bcrypt hash directly in the database
user = User(email=email, hashed_password=bcrypt_hash)
db.add(user)
db.commit()
db.refresh(user)

# Verify the hash is bcrypt before authentication
assert user.hashed_password.startswith("$2")

# Authenticate - this should upgrade the hash to argon2
authenticated_user = crud.authenticate(session=db, email=email, password=password)
assert authenticated_user
assert authenticated_user.email == email

db.refresh(authenticated_user)

# Verify the hash was upgraded to argon2
assert authenticated_user.hashed_password.startswith("$argon2")

verified, updated_hash = verify_password(
password, authenticated_user.hashed_password
)
assert verified
# Should not need another update since it's already argon2
assert updated_hash is None
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion backend/app/api/routes/users.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -104,7 +104,8 @@ def update_password_me(
"""
Update own password.
"""
if not verify_password(body.current_password, current_user.hashed_password):
verified, _ = verify_password(body.current_password, current_user.hashed_password)
if not verified:
raise HTTPException(status_code=400, detail="Incorrect password")
if body.current_password == body.new_password:
raise HTTPException(
Expand Down
19 changes: 14 additions & 5 deletions backend/app/core/security.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,11 +2,18 @@
from typing import Any

import jwt
from passlib.context import CryptContext
from pwdlib import PasswordHash
from pwdlib.hashers.argon2 import Argon2Hasher
from pwdlib.hashers.bcrypt import BcryptHasher

from app.core.config import settings

pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
password_hash = PasswordHash(
(
Argon2Hasher(),
BcryptHasher(),
)
)


ALGORITHM = "HS256"
Expand All@@ -19,9 +26,11 @@ def create_access_token(subject: str | Any, expires_delta: timedelta) -> str:
return encoded_jwt


def verify_password(plain_password: str, hashed_password: str) -> bool:
return pwd_context.verify(plain_password, hashed_password)
def verify_password(
plain_password: str, hashed_password: str
) -> tuple[bool, str | None]:
return password_hash.verify_and_update(plain_password, hashed_password)


def get_password_hash(password: str) -> str:
return pwd_context.hash(password)
return password_hash.hash(password)
8 changes: 7 additions & 1 deletion backend/app/crud.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -41,8 +41,14 @@ def authenticate(*, session: Session, email: str, password: str) -> User | None:
db_user = get_user_by_email(session=session, email=email)
if not db_user:
return None
if not verify_password(password, db_user.hashed_password):
verified, updated_password_hash = verify_password(password, db_user.hashed_password)
if not verified:
return None
if updated_password_hash:
db_user.hashed_password = updated_password_hash
session.add(db_user)
session.commit()
session.refresh(db_user)
return db_user


Expand Down
5 changes: 1 addition & 4 deletions backend/pyproject.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,7 +7,6 @@ dependencies = [
"fastapi[standard]<1.0.0,>=0.114.2",
"python-multipart<1.0.0,>=0.0.7",
"email-validator<3.0.0.0,>=2.1.0.post1",
"passlib[bcrypt]<2.0.0,>=1.7.4",
"tenacity<9.0.0,>=8.2.3",
"pydantic>2.0",
"emails<1.0,>=0.6",
Expand All@@ -16,11 +15,10 @@ dependencies = [
"httpx<1.0.0,>=0.25.1",
"psycopg[binary]<4.0.0,>=3.1.13",
"sqlmodel<1.0.0,>=0.0.21",
# Pin bcrypt until passlib supports the latest
"bcrypt==4.3.0",
"pydantic-settings<3.0.0,>=2.2.1",
"sentry-sdk[fastapi]<2.0.0,>=1.40.6",
"pyjwt<3.0.0,>=2.8.0",
"pwdlib[argon2,bcrypt]>=0.3.0",
]

[dependency-groups]
Expand All@@ -29,7 +27,6 @@ dev = [
"mypy<2.0.0,>=1.8.0",
"ruff<1.0.0,>=0.2.2",
"prek>=0.2.24,<1.0.0",
"types-passlib<2.0.0.0,>=1.7.7.20240106",
"coverage<8.0.0,>=7.4.3",
]

Expand Down
73 changes: 70 additions & 3 deletions backend/tests/api/routes/test_login.py
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,13 @@
from unittest.mock import patch

from fastapi.testclient import TestClient
from pwdlib.hashers.bcrypt import BcryptHasher
from sqlmodel import Session

from app.core.config import settings
from app.core.security import verify_password
from app.core.security import get_password_hash, verify_password
from app.crud import create_user
from app.models import UserCreate
from app.models import User, UserCreate
from app.utils import generate_password_reset_token
from tests.utils.user import user_authentication_headers
from tests.utils.utils import random_email, random_lower_string
Expand DownExpand Up@@ -99,7 +100,8 @@ def test_reset_password(client: TestClient, db: Session) -> None:
assert r.json() == {"message": "Password updated successfully"}

db.refresh(user)
assert verify_password(new_password, user.hashed_password)
verified, _ = verify_password(new_password, user.hashed_password)
assert verified


def test_reset_password_invalid_token(
Expand All@@ -116,3 +118,68 @@ def test_reset_password_invalid_token(
assert "detail" in response
assert r.status_code == 400
assert response["detail"] == "Invalid token"


def test_login_with_bcrypt_password_upgrades_to_argon2(
client: TestClient, db: Session
) -> None:
"""Test that logging in with a bcrypt password hash upgrades it to argon2."""
email = random_email()
password = random_lower_string()

# Create a bcrypt hash directly (simulating legacy password)
bcrypt_hasher = BcryptHasher()
bcrypt_hash = bcrypt_hasher.hash(password)
assert bcrypt_hash.startswith("$2") # bcrypt hashes start with $2

user = User(email=email, hashed_password=bcrypt_hash, is_active=True)
db.add(user)
db.commit()
db.refresh(user)

assert user.hashed_password.startswith("$2")

login_data = {"username": email, "password": password}
r = client.post(f"{settings.API_V1_STR}/login/access-token", data=login_data)
assert r.status_code == 200
tokens = r.json()
assert "access_token" in tokens

db.refresh(user)

# Verify the hash was upgraded to argon2
assert user.hashed_password.startswith("$argon2")

verified, updated_hash = verify_password(password, user.hashed_password)
assert verified
# Should not need another update since it's already argon2
assert updated_hash is None


def test_login_with_argon2_password_keeps_hash(client: TestClient, db: Session) -> None:
"""Test that logging in with an argon2 password hash does not update it."""
email = random_email()
password = random_lower_string()

# Create an argon2 hash (current default)
argon2_hash = get_password_hash(password)
assert argon2_hash.startswith("$argon2")

# Create user with argon2 hash
user = User(email=email, hashed_password=argon2_hash, is_active=True)
db.add(user)
db.commit()
db.refresh(user)

original_hash = user.hashed_password

login_data = {"username": email, "password": password}
r = client.post(f"{settings.API_V1_STR}/login/access-token", data=login_data)
assert r.status_code == 200
tokens = r.json()
assert "access_token" in tokens

db.refresh(user)

assert user.hashed_password == original_hash
assert user.hashed_password.startswith("$argon2")
11 changes: 8 additions & 3 deletions backend/tests/api/routes/test_users.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -242,7 +242,8 @@ def test_update_password_me(
user_db = db.exec(user_query).first()
assert user_db
assert user_db.email == settings.FIRST_SUPERUSER
assert verify_password(new_password, user_db.hashed_password)
verified, _ = verify_password(new_password, user_db.hashed_password)
assert verified

# Revert to the old password to keep consistency in test
old_data = {
Expand All@@ -257,7 +258,10 @@ def test_update_password_me(
db.refresh(user_db)

assert r.status_code == 200
assert verify_password(settings.FIRST_SUPERUSER_PASSWORD, user_db.hashed_password)
verified, _ = verify_password(
settings.FIRST_SUPERUSER_PASSWORD, user_db.hashed_password
)
assert verified


def test_update_password_me_incorrect_password(
Expand DownExpand Up@@ -331,7 +335,8 @@ def test_register_user(client: TestClient, db: Session) -> None:
assert user_db
assert user_db.email == username
assert user_db.full_name == full_name
assert verify_password(password, user_db.hashed_password)
verified, _ = verify_password(password, user_db.hashed_password)
assert verified


def test_register_user_already_exists_error(client: TestClient) -> None:
Expand Down
41 changes: 40 additions & 1 deletion backend/tests/crud/test_user.py
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
from fastapi.encoders import jsonable_encoder
from pwdlib.hashers.bcrypt import BcryptHasher
from sqlmodel import Session

from app import crud
Expand DownExpand Up@@ -88,4 +89,42 @@ def test_update_user(db: Session) -> None:
user_2 = db.get(User, user.id)
assert user_2
assert user.email == user_2.email
assert verify_password(new_password, user_2.hashed_password)
verified, _ = verify_password(new_password, user_2.hashed_password)
assert verified


def test_authenticate_user_with_bcrypt_upgrades_to_argon2(db: Session) -> None:
"""Test that a user with bcrypt password hash gets upgraded to argon2 on login."""
email = random_email()
password = random_lower_string()

# Create a bcrypt hash directly (simulating legacy password)
bcrypt_hasher = BcryptHasher()
bcrypt_hash = bcrypt_hasher.hash(password)
assert bcrypt_hash.startswith("$2") # bcrypt hashes start with $2

# Create user with bcrypt hash directly in the database
user = User(email=email, hashed_password=bcrypt_hash)
db.add(user)
db.commit()
db.refresh(user)

# Verify the hash is bcrypt before authentication
assert user.hashed_password.startswith("$2")

# Authenticate - this should upgrade the hash to argon2
authenticated_user = crud.authenticate(session=db, email=email, password=password)
assert authenticated_user
assert authenticated_user.email == email

db.refresh(authenticated_user)

# Verify the hash was upgraded to argon2
assert authenticated_user.hashed_password.startswith("$argon2")

verified, updated_hash = verify_password(
password, authenticated_user.hashed_password
)
assert verified
# Should not need another update since it's already argon2
assert updated_hash is None
Loading
Loading