diff --git a/backend/app/core/security.py b/backend/app/core/security.py index dcfe5d7..5e4acf3 100644 --- a/backend/app/core/security.py +++ b/backend/app/core/security.py @@ -1,9 +1,77 @@ from datetime import timedelta import bcrypt +from fastapi import HTTPException, status from jose import JWTError, jwt from .config import settings from .time_utils import utc_now +BLOCKLIST_PASSWORDS = { + "123456", + "12345678", + "password", + "password1", + "qwerty123", + "admin123", + "welcome1", +} + + +def validate_password(password: str, email: str | None = None) -> None: + """Validate password rules: + - Length: at least 8, at most 128 characters. + - Characters: at least one letter and at least one digit. (Special characters allowed, not required. Case insensitive.) + - Must NOT start or end with a space (reject with a clear message, do not silently strip). + - Blocklist (case-insensitive): '123456', '12345678', 'password', 'password1', 'qwerty123', 'admin123', 'welcome1'. + (NOTE: demo password 'demo@123' must remain allowed) + - Must not contain the user's username/email local-part if length >= 4 (case-insensitive). + """ + if not isinstance(password, str): + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, + detail="Password must be a string.", + ) + + if password.startswith(" ") or password.endswith(" "): + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, + detail="Password must not start or end with a space.", + ) + + if len(password) < 8: + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, + detail="Password must be at least 8 characters long.", + ) + + if len(password) > 128: + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, + detail="Password must be at most 128 characters long.", + ) + + has_letter = any(c.isalpha() for c in password) + has_digit = any(c.isdigit() for c in password) + if not has_letter or not has_digit: + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, + detail="Password must contain at least one letter and at least one digit.", + ) + + lower_pass = password.lower() + if lower_pass in BLOCKLIST_PASSWORDS: + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, + detail="Password is too common or easily guessable.", + ) + + if email: + local_part = email.split("@")[0].strip().lower() + if len(local_part) >= 4 and local_part in lower_pass: + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, + detail="Password must not contain your email username.", + ) + def verify_password(plain: str, hashed: str) -> bool: if not plain or not hashed: diff --git a/backend/app/routers/auth.py b/backend/app/routers/auth.py index 29e3c75..f8f06d5 100644 --- a/backend/app/routers/auth.py +++ b/backend/app/routers/auth.py @@ -6,7 +6,7 @@ from sqlalchemy.orm import Session, joinedload from ..core.db import get_db from ..core.deps import get_current_user from ..core.exceptions import CodedHTTPException -from ..core.security import create_access_token, hash_password, verify_password +from ..core.security import create_access_token, hash_password, validate_password, verify_password from ..models.masters import User from ..schemas.auth import LoginRequest, TokenResponse, UserOut from ..services.settings_service import get_demo_as_of_date @@ -17,7 +17,7 @@ router = APIRouter(prefix="/auth", tags=["auth"]) class ChangePasswordRequest(BaseModel): current_password: str - new_password: str = Field(..., min_length=6) + new_password: str = Field(..., max_length=128) MAX_LOGIN_ATTEMPTS = 15 LOGIN_WINDOW_SECONDS = 60.0 @@ -110,12 +110,12 @@ def change_password( status_code=status.HTTP_400_BAD_REQUEST, detail="Current password is incorrect.", ) - new_pass = payload.new_password.strip() - if len(new_pass) < 6: + if payload.new_password == payload.current_password: raise HTTPException( status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, - detail="New password must be at least 6 characters.", + detail="New password must be different.", ) - current_user.password_hash = hash_password(new_pass) + validate_password(payload.new_password, email=current_user.email) + current_user.password_hash = hash_password(payload.new_password) db.commit() return {"message": "Password changed successfully."} diff --git a/backend/app/routers/users.py b/backend/app/routers/users.py index e65558a..783162e 100644 --- a/backend/app/routers/users.py +++ b/backend/app/routers/users.py @@ -6,7 +6,7 @@ from sqlalchemy.exc import IntegrityError from sqlalchemy.orm import Session, joinedload from ..core.db import get_db from ..core.deps import get_current_user, require_roles -from ..core.security import hash_password +from ..core.security import hash_password, validate_password from ..models.masters import Department, User from ..schemas.masters import ( PaginatedOut, @@ -21,7 +21,7 @@ router = APIRouter(prefix="/users", tags=["users"]) class ResetPasswordRequest(BaseModel): - new_password: str = Field(..., min_length=6) + new_password: str = Field(..., max_length=128) def _user_list_out(user: User) -> UserListOut: @@ -93,6 +93,8 @@ def create_user( if dept is None: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Department not found.") + validate_password(payload.password, email=payload.email) + user = User( name=payload.name.strip(), email=payload.email.strip().lower(), @@ -175,12 +177,8 @@ def update_user( data["email"] = data["email"].strip().lower() password = data.pop("password", None) - if password is not None and password.strip(): - if len(password) < 4: - raise HTTPException( - status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, - detail="Password must be at least 4 characters.", - ) + if password is not None and password != "": + validate_password(password, email=data.get("email", user.email)) user.password_hash = hash_password(password) for k, v in data.items(): @@ -243,12 +241,7 @@ def reset_user_password( user = db.query(User).filter(User.id == user_id).first() if user is None: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found.") - new_pass = payload.new_password.strip() - if len(new_pass) < 6: - raise HTTPException( - status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, - detail="Password must be at least 6 characters.", - ) - user.password_hash = hash_password(new_pass) + validate_password(payload.new_password, email=user.email) + user.password_hash = hash_password(payload.new_password) db.commit() return {"message": f"Password for {user.name} has been reset successfully."} diff --git a/backend/app/schemas/masters.py b/backend/app/schemas/masters.py index 25f9460..4b5559c 100644 --- a/backend/app/schemas/masters.py +++ b/backend/app/schemas/masters.py @@ -123,7 +123,7 @@ class VendorOut(BaseModel): class UserCreate(BaseModel): name: str = Field(..., min_length=1, max_length=150) email: str = Field(..., min_length=3, max_length=200) - password: str = Field(..., min_length=4, max_length=128) + password: str = Field(..., max_length=128) role: UserRole department_id: Optional[int] = None is_active: bool = True diff --git a/backend/tests/test_task4_passwords.py b/backend/tests/test_task4_passwords.py new file mode 100644 index 0000000..563dc66 --- /dev/null +++ b/backend/tests/test_task4_passwords.py @@ -0,0 +1,165 @@ +import pytest +from fastapi.testclient import TestClient +from app.core.security import validate_password +from app.models.masters import User +from app.seed.seed import seed_database + + +@pytest.fixture(scope="module", autouse=True) +def seeded_task4_db(db, tmp_path_factory): + upload_dir = tmp_path_factory.mktemp("task4_test_uploads") + seed_database(db, upload_dir=upload_dir) + return upload_dir + + +def _auth_headers(client, email: str = "admin@poona.demo") -> dict[str, str]: + res = client.post("/api/auth/login", json={"email": email, "password": "Demo@123"}) + assert res.status_code == 200, res.text + return {"Authorization": f"Bearer {res.json()['access_token']}"} + + +def test_validate_password_unit(): + # 1. Short password (< 8) + with pytest.raises(Exception) as exc1: + validate_password("Short1", email="user@hospital.com") + assert "at least 8 characters" in str(exc1.value) + + # 2. No digits + with pytest.raises(Exception) as exc2: + validate_password("NoDigitsHere", email="user@hospital.com") + assert "at least one letter and at least one digit" in str(exc2.value) + + # 3. No letters + with pytest.raises(Exception) as exc3: + validate_password("1234567890", email="user@hospital.com") + assert "at least one letter and at least one digit" in str(exc3.value) + + # 4. Leading / trailing space + with pytest.raises(Exception) as exc4a: + validate_password(" Secret123", email="user@hospital.com") + assert "space" in str(exc4a.value) + + with pytest.raises(Exception) as exc4b: + validate_password("Secret123 ", email="user@hospital.com") + assert "space" in str(exc4b.value) + + # 5. Blocklisted passwords + for bad in ("12345678", "password", "password1", "qwerty123", "admin123", "welcome1"): + with pytest.raises(Exception) as exc5: + validate_password(bad, email="user@hospital.com") + assert "easily guessable" in str(exc5.value) or "at least 8" in str(exc5.value) or "at least one" in str(exc5.value) + + # 6. Demo password MUST be allowed + validate_password("demo@123", email="admin@poona.demo") + validate_password("Demo@123", email="admin@poona.demo") + + # 7. Contains email local part (>= 4 chars) + with pytest.raises(Exception) as exc7: + validate_password("Secureadmin123", email="admin@poona.demo") + assert "username" in str(exc7.value).lower() + + # Short local part (< 4 chars) does NOT trigger username check + validate_password("Securebio123", email="bio@poona.demo") + + +def test_api_create_user_password_validation(client, db): + headers = _auth_headers(client, "admin@poona.demo") + + # Rejected: no digit + res_bad = client.post( + "/api/users", + headers=headers, + json={ + "name": "Test User", + "email": "test_pw_rule@poona.demo", + "password": "NoDigitsPassword", + "role": "biomedical", + }, + ) + assert res_bad.status_code == 422 + assert "letter and at least one digit" in res_bad.json()["detail"] + + # Rejected: contains email username "tester123" + res_username = client.post( + "/api/users", + headers=headers, + json={ + "name": "Test User 2", + "email": "tester123@poona.demo", + "password": "tester123Password1", + "role": "biomedical", + }, + ) + assert res_username.status_code == 422 + assert "username" in res_username.json()["detail"].lower() + + # Accepted: valid password with letters and numbers + res_ok = client.post( + "/api/users", + headers=headers, + json={ + "name": "Test User 3", + "email": "validuser@poona.demo", + "password": "ValidPassword123", + "role": "biomedical", + }, + ) + assert res_ok.status_code == 201 + user_id = res_ok.json()["id"] + + # Reset password with leading space rejected + res_reset_bad = client.post( + f"/api/users/{user_id}/reset-password", + headers=headers, + json={"new_password": " LeadingSpace123"}, + ) + assert res_reset_bad.status_code == 422 + assert "space" in res_reset_bad.json()["detail"] + + # Reset password with valid password succeeds + res_reset_ok = client.post( + f"/api/users/{user_id}/reset-password", + headers=headers, + json={"new_password": "NewValidSecret456"}, + ) + assert res_reset_ok.status_code == 200 + + +def test_api_change_password_validation(client, db): + # Log in as bio user + bio_headers = _auth_headers(client, "bio@poona.demo") + + # Reject new == current + res_same = client.post( + "/api/auth/change-password", + headers=bio_headers, + json={"current_password": "Demo@123", "new_password": "Demo@123"}, + ) + assert res_same.status_code == 422 + assert res_same.json()["detail"] == "New password must be different." + + # Reject trailing space + res_space = client.post( + "/api/auth/change-password", + headers=bio_headers, + json={"current_password": "Demo@123", "new_password": "NewSecretPass1 "}, + ) + assert res_space.status_code == 422 + assert "space" in res_space.json()["detail"] + + # Reject blocklisted password + res_block = client.post( + "/api/auth/change-password", + headers=bio_headers, + json={"current_password": "Demo@123", "new_password": "password1"}, + ) + assert res_block.status_code == 422 + + # Accept valid change + res_ok = client.post( + "/api/auth/change-password", + headers=bio_headers, + json={"current_password": "Demo@123", "new_password": "BrandNewSecret789"}, + ) + assert res_ok.status_code == 200 + assert res_ok.json()["message"] == "Password changed successfully." diff --git a/docs/ASSUMPTIONS.md b/docs/ASSUMPTIONS.md index 74dd044..ada29a5 100644 --- a/docs/ASSUMPTIONS.md +++ b/docs/ASSUMPTIONS.md @@ -42,3 +42,10 @@ Items marked "to be confirmed" or left flexible in the proposal are recorded her - **Calibration Plans**: Each asset can have at most one calibration plan. In bulk import, rows for assets that already have a calibration plan in the database receive `Asset already has a calibration plan.`, while rows repeating an earlier row for the same asset in the same upload file receive `Duplicate of row N in this file.`. Dry run previews surface these validation errors identically. 25. **Import Template Multi-Sheet Structure (Task 2)**: All four bulk-import templates (Assets, Contracts, Calibration Plans, Insurance Policies) feature an empty data template on Sheet 1 (containing only styled headers), an 'Example' reference on Sheet 2 (with warning banner 'Example only - this sheet is ignored on import' in Row 1 and sample values in Row 2), and 'Master Reference' lookup tables on Sheet 3. All four importers read strictly the first worksheet (`wb.worksheets[0]`), ensuring sample rows and reference sheets are never accidentally imported. 26. **Backup Script Path Resolution & Dual Archive Packaging (Task 3)**: `backend/scripts/backup.py` exposes `get_db_path(db_url, backend_dir)` to accurately resolve SQLite file paths from `DATABASE_URL` across relative paths (`sqlite:///./data/ams.db`, `sqlite:///data/ams.db`), absolute POSIX/Windows paths (`sqlite:////app/data/ams.db`, `sqlite:////tmp/x/custom.db`), and in-memory or fallback scenarios. `create_backup()` supports both `.tar.gz` and `.zip` archives and packages SQLite database files under both `db.sqlite3` and `ams.db` member names for cross-environment compatibility. +27. **Universal Password Policy (Task 4)**: A unified validation rule (`validate_password`) is enforced across user registration, profile updates, self-service password changes, and administrator resets: + - Length: 8 to 128 characters. + - Character composition: at least one letter and at least one digit (case-insensitive; special characters permitted). + - Whitespace: leading and trailing spaces are strictly prohibited and rejected with HTTP 422 (never silently trimmed). + - Prohibited passwords: blocklist of common passwords (`123456`, `12345678`, `password`, `password1`, `qwerty123`, `admin123`, `welcome1`), while preserving `demo@123` for seeded testing environments. + - Username containment: cannot contain the user's email username (local part before `@`) if 4 or more characters. + - Password changes additionally require that the new password is not identical to the current password. diff --git a/frontend/src/components/ChangePasswordModal.tsx b/frontend/src/components/ChangePasswordModal.tsx index b053c36..fd700f9 100644 --- a/frontend/src/components/ChangePasswordModal.tsx +++ b/frontend/src/components/ChangePasswordModal.tsx @@ -43,8 +43,8 @@ export function ChangePasswordModal({ open, onClose }: ChangePasswordModalProps) setErrorMsg("Please enter your current password."); return; } - if (!newPassword || newPassword.length < 6) { - setErrorMsg("New password must be at least 6 characters."); + if (!newPassword || newPassword.length < 8) { + setErrorMsg("New password must be at least 8 characters."); return; } if (newPassword !== confirmPassword) { @@ -73,7 +73,7 @@ export function ChangePasswordModal({ open, onClose }: ChangePasswordModalProps) if (!next) handleClose(); }} title="Change Password" - description="Update your account login password. Password must be at least 6 characters long." + description="Update your account login password." className="max-w-md" >
@@ -122,9 +122,9 @@ export function ChangePasswordModal({ open, onClose }: ChangePasswordModalProps) value={newPassword} onChange={(e) => setNewPassword(e.target.value)} required - minLength={6} + minLength={8} autoComplete="new-password" - placeholder="At least 6 characters" + placeholder="At least 8 characters" className="w-full px-3 py-2 text-sm border border-gray-300 rounded-md pr-10 focus:outline-none focus:ring-2 focus:ring-blue-500" /> +

At least 8 characters, with a letter and a number.

diff --git a/frontend/src/pages/MastersPage.tsx b/frontend/src/pages/MastersPage.tsx index afafc5a..524212e 100644 --- a/frontend/src/pages/MastersPage.tsx +++ b/frontend/src/pages/MastersPage.tsx @@ -425,8 +425,8 @@ function buildUserSchema(isEdit: boolean) { role: z.enum(["system_admin", "biomedical", "department_user", "management", "coordinator"]), department_id: z.string().optional(), password: isEdit - ? z.string().refine((v) => v === "" || v.length >= 6, "Password must be at least 6 characters") - : z.string().min(6, "Password must be at least 6 characters"), + ? z.string().refine((v) => v === "" || v.length >= 8, "Password must be at least 8 characters") + : z.string().min(8, "Password must be at least 8 characters"), }); } @@ -530,6 +530,7 @@ function UserModal({ {editing ? "New Password (leave blank to keep current)" : "Password *"} +

At least 8 characters, with a letter and a number.

{errors.password &&

{errors.password.message}

}