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
38 changes: 31 additions & 7 deletions app/auth_core.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,47 @@
from passlib.context import CryptContext
import bcrypt

pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
# Work factor for new hashes. Read at call time so tests can lower it
# (tests/conftest.py); existing hashes carry their own cost and verify as-is.
BCRYPT_ROUNDS = 12

# passlib refuses to hash beyond 4096 chars (PasswordSizeError), and bcrypt
# itself silently truncates at 72 bytes. Cap well below the first limit so an
# oversized field is a validation error at the caller, never a 500.
# bcrypt only ever looks at the first 72 bytes. passlib (which hashed every
# stored password and backup code before this module called bcrypt directly)
# truncated silently; bcrypt>=5 raises instead. Truncate the same way so
# existing hashes of long passwords still verify.
_BCRYPT_MAX_BYTES = 72

# Cap well below any library limit so an oversized field is a validation
# error at the caller, never a 500.
MAX_PASSWORD_LEN = 128


def _secret_bytes(secret: str) -> bytes:
return secret.encode("utf-8")[:_BCRYPT_MAX_BYTES]


def hash_secret(secret: str) -> str:
"""Salted bcrypt hash of a password or backup code ($2b$ format)."""
return bcrypt.hashpw(_secret_bytes(secret), bcrypt.gensalt(BCRYPT_ROUNDS)).decode("ascii")


def verify_secret(secret: str, hashed: str) -> bool:
"""Check a secret against a bcrypt hash; a malformed hash is a mismatch."""
try:
return bcrypt.checkpw(_secret_bytes(secret), hashed.encode("ascii"))
except (ValueError, UnicodeEncodeError):
return False


def hash_password(pw: str) -> str:
if len(pw or "") > MAX_PASSWORD_LEN:
raise ValueError(f"password must be {MAX_PASSWORD_LEN} characters or fewer")
return pwd_context.hash(pw)
return hash_secret(pw)


def verify_password(pw: str, hashed: str | None) -> bool:
if not hashed:
return False
try:
return pwd_context.verify(pw, hashed)
return verify_secret(pw, hashed)
except Exception:
return False
21 changes: 12 additions & 9 deletions app/main.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import ipaddress
import logging
import os
from contextlib import asynccontextmanager

from fastapi import FastAPI
from fastapi.responses import FileResponse, PlainTextResponse, RedirectResponse, Response
Expand Down Expand Up @@ -89,13 +90,23 @@ def _acquire_single_instance_lock(app) -> None:
app.state.instance_lock = lock # keep the fd alive for the process lifetime


@asynccontextmanager
async def _lifespan(app: FastAPI):
yield
# Stop APScheduler on SIGTERM (docker restart/redeploy) so a running
# backup or mailer flush finishes instead of being killed mid-write.
sched = getattr(app.state, "scheduler", None)
if sched is not None:
sched.shutdown(wait=True)


def create_app(engine=None) -> FastAPI:
# First thing, so anything below (migrations, seeding, scheduler wiring)
# that fails during boot fails somewhere an operator can read.
observability.configure_logging()
log.info("OpenPoolPro %s starting (tz=%s, scheduler=%s)",
config.APP_VERSION, config.TIMEZONE, config.RUN_SCHEDULER)
app = FastAPI(title="OpenPoolPro")
app = FastAPI(title="OpenPoolPro", lifespan=_lifespan)
# A real boot builds its own file-backed engine; the test suite always
# injects an in-memory engine. Enforce secure secrets only on the former,
# so a deployment can never run on the shipped placeholder SECRET_KEY.
Expand Down Expand Up @@ -498,12 +509,4 @@ def sw():
# last_backup_error rather than stopping the app from starting.
backup_if_stale(app.state.engine)

@app.on_event("shutdown")
def _stop_scheduler():
# Stop APScheduler on SIGTERM (docker restart/redeploy) so a running
# backup or mailer flush finishes instead of being killed mid-write.
sched = getattr(app.state, "scheduler", None)
if sched is not None:
sched.shutdown(wait=True)

return app
8 changes: 4 additions & 4 deletions app/security.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
import segno

from app import config
from app.auth_core import pwd_context
from app.auth_core import hash_secret, verify_secret

ISSUER = "OpenPoolPro"
_PENDING_2FA_SALT = "cpp-2fa-pending"
Expand Down Expand Up @@ -76,12 +76,12 @@ def make_backup_codes() -> list[str]:
def hash_code(code: str) -> str:
"""Bcrypt hash of a normalized (lowercased, stripped) code.

Reuses the app's configured passlib CryptContext (see app.auth_core) so
Reuses the app's password hashing (see app.auth_core) so
backup codes get the same salted, slow-to-brute-force treatment as
passwords rather than a bare, unsalted digest.
"""
normalized = code.strip().lower()
return pwd_context.hash(normalized)
return hash_secret(normalized)


def verify_code(code: str | None, code_hash: str | None) -> bool:
Expand All @@ -95,7 +95,7 @@ def verify_code(code: str | None, code_hash: str | None) -> bool:
return False
normalized = code.strip().lower()
try:
return pwd_context.verify(normalized, code_hash)
return verify_secret(normalized, code_hash)
except Exception:
return False

Expand Down
30 changes: 14 additions & 16 deletions requirements-dev.lock
Original file line number Diff line number Diff line change
Expand Up @@ -6,24 +6,19 @@ annotated-types==0.8.0
# via pydantic
anyio==4.14.2
# via
# httpx
# httpx2
# starlette
# watchfiles
apscheduler==3.11.3
# via -r requirements.txt
bcrypt==4.0.1
# via
# -r requirements.txt
# passlib
bcrypt==5.0.0
# via -r requirements.txt
boolean-py==5.0
# via license-expression
cachecontrol==0.14.4
# via pip-audit
certifi==2026.7.22
# via
# httpcore
# httpx
# requests
# via requests
cffi==2.1.1
# via cryptography
charset-normalizer==3.5.1
Expand Down Expand Up @@ -52,18 +47,18 @@ greenlet==3.5.5
# via sqlalchemy
h11==0.16.0
# via
# httpcore
# httpcore2
# uvicorn
httpcore==1.0.9
# via httpx
httpcore2==2.13.1
# via httpx2
httptools==0.8.0
# via uvicorn
httpx==0.28.1
httpx2==2.13.1
# via -r requirements-dev.txt
idna==3.19
# via
# anyio
# httpx
# httpx2
# requests
iniconfig==2.3.0
# via pytest
Expand All @@ -90,8 +85,6 @@ packaging==26.3
# pip-audit
# pip-requirements-parser
# pytest
passlib==1.7.4
# via -r requirements.txt
pillow==13.0.0
# via
# -r requirements.txt
Expand Down Expand Up @@ -167,11 +160,16 @@ tomli==2.4.1
# via pip-audit
tomli-w==1.2.0
# via pip-audit
truststore==0.10.4
# via
# httpcore2
# httpx2
typing-extensions==4.16.0
# via
# anyio
# cyclonedx-python-lib
# fastapi
# httpx2
# pydantic
# pydantic-core
# sqlalchemy
Expand Down
2 changes: 1 addition & 1 deletion requirements-dev.txt
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,5 @@ pytest-cov>=5.0
pytest-xdist>=3.5
ruff>=0.6
pip-audit>=2.7
httpx>=0.27
httpx2>=2.13
pytailwindcss>=0.2
8 changes: 2 additions & 6 deletions requirements.lock
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,8 @@ anyio==4.14.2
# watchfiles
apscheduler==3.11.3
# via -r requirements.txt
bcrypt==4.0.1
# via
# -r requirements.txt
# passlib
bcrypt==5.0.0
# via -r requirements.txt
cffi==2.1.1
# via cryptography
charset-normalizer==3.5.1
Expand Down Expand Up @@ -42,8 +40,6 @@ markupsafe==3.0.3
# via jinja2
openpyxl==3.1.5
# via -r requirements.txt
passlib==1.7.4
# via -r requirements.txt
pillow==13.0.0
# via
# -r requirements.txt
Expand Down
3 changes: 1 addition & 2 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,7 @@ sqlalchemy>=2.0
itsdangerous>=2.1
apscheduler>=3.10
pillow>=13.0.0
passlib[bcrypt]>=1.7
bcrypt<4.1
bcrypt>=4.2
pyotp>=2.9
segno>=1.6
reportlab>=4.0
Expand Down
9 changes: 4 additions & 5 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,10 @@
# every `client` fixture rebuilds the app (seeds.run hashes APP_PASSWORD) and
# then logs in (a verify), so 500+ tests each paid ~0.5 s of pure KDF.
#
# Mutate the shared CryptContext IN PLACE rather than rebinding it: app/security.py
# does `from app.auth_core import pwd_context`, so a rebind would leave backup-code
# hashing on the old context. The scheme stays bcrypt — only the work factor moves,
# so every code path under test behaves identically.
auth_core.pwd_context.update(bcrypt__rounds=4)
# auth_core reads BCRYPT_ROUNDS at call time, so passwords and backup codes
# (app/security.py) both pick this up. The scheme stays bcrypt — only the work
# factor moves, so every code path under test behaves identically.
auth_core.BCRYPT_ROUNDS = 4

# The TestClient speaks plain http://testserver, and httpx's cookie jar rightly
# refuses to store Secure cookies from an insecure origin — under the
Expand Down
26 changes: 24 additions & 2 deletions tests/test_auth_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
from sqlalchemy.orm import Session

import app.config as config
from app import models, seeds
from app.auth_core import hash_password, verify_password
from app import models, security, seeds
from app.auth_core import MAX_PASSWORD_LEN, hash_password, verify_password


def test_hash_and_verify_roundtrip():
Expand All @@ -15,6 +15,28 @@ def test_hash_and_verify_roundtrip():
assert verify_password("x", "not-a-hash") is False


# Produced by passlib 1.7.4 (CryptContext(schemes=["bcrypt"]), bcrypt 4.0.1),
# which hashed every password and backup code stored before auth_core called
# bcrypt directly. Those rows must keep verifying after the switch.
_PASSLIB_HASH = "$2b$04$uo/GLXyUBcNionKvjGXJKuM62vh0nOqH1zYYP8xGWJWqNb1C.8kgq"
_PASSLIB_LONG_PW = "é" * 50 + "tail" # 104 UTF-8 bytes: past bcrypt's 72
_PASSLIB_LONG_HASH = "$2b$04$7A3K7jHD5QZYIK9hRatwh.wDEYVpTurgye5UflJCKj0nE3pBQQJYO"


def test_passlib_era_hashes_still_verify():
assert verify_password("correct horse", _PASSLIB_HASH) is True
assert verify_password("correct horsE", _PASSLIB_HASH) is False
assert security.verify_code("Correct Horse ", _PASSLIB_HASH) is True


def test_long_password_truncates_like_passlib_instead_of_raising():
# passlib silently used the first 72 bytes; bcrypt>=5 raises on longer
# input. A long password must hash (no 500) and old long hashes verify.
assert verify_password(_PASSLIB_LONG_PW, _PASSLIB_LONG_HASH) is True
pw = "x" * MAX_PASSWORD_LEN
assert verify_password(pw, hash_password(pw)) is True


def _prep(engine, monkeypatch, password):
monkeypatch.setattr(config, "APP_PASSWORD", password)
from app.db import Base
Expand Down
71 changes: 71 additions & 0 deletions tests/test_backup.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,3 +58,74 @@ def test_start_scheduler_wiring(engine):
assert "hour='1'" in trigger and "minute='0'" in trigger
finally:
sched.shutdown(wait=False)


# --- off-box sync (BACKUP_SYNC_CMD) ---------------------------------------------

def _sync_setup(engine, monkeypatch, tmp_path, cmd):
monkeypatch.setattr(config, "DATA_DIR", str(tmp_path))
monkeypatch.setattr(config, "BACKUP_SYNC_CMD", cmd)
from app.db import Base
Base.metadata.create_all(engine)
(tmp_path / "photos").mkdir()
(tmp_path / "photos" / "p.jpg").write_bytes(b"jpg")


def _all_settings(engine):
with Session(engine) as s:
return {r.key: r.value for r in s.query(models.Setting).all()}


def test_offbox_sync_gets_snapshot_paths_and_clears_prior_error(engine, monkeypatch, tmp_path):
seen = tmp_path / "seen.txt"
_sync_setup(engine, monkeypatch, tmp_path,
f'printf "%s\\n%s\\n%s\\n" "$BACKUP_DIR" "$BACKUP_FILE" "$BACKUP_ASSETS_FILE" > {seen}')
with Session(engine) as s:
models.set_setting(s, "last_backup_sync_error", "CalledProcessError (exit 1)")
s.commit()
path = run_backup(engine)
bdir, db_file, assets_file = seen.read_text().splitlines()
assert bdir == str(tmp_path / "backups")
assert db_file == path
assert os.path.basename(assets_file).startswith("assets-") and os.path.exists(assets_file)
assert _all_settings(engine)["last_backup_sync_error"] == ""


def test_offbox_sync_failure_never_persists_the_command_line(engine, monkeypatch, tmp_path):
# A sync command routinely carries a credential (rclone --sftp-pass=...).
# Its failure must record only the error type and exit code: the settings
# table lands in every nightly snapshot, which is exactly what gets shipped.
secret = "hunter2-offbox-secret"
_sync_setup(engine, monkeypatch, tmp_path, f"echo --pass={secret} >&2; exit 3")
path = run_backup(engine)
settings = _all_settings(engine)
assert settings["last_backup_sync_error"] == "CalledProcessError (exit 3)"
assert not any(secret in (v or "") for v in settings.values())
# The local snapshot still counts as a good backup.
assert os.path.exists(path)
assert settings["last_backup_ok"] == "1" and settings["last_backup_error"] == ""


def test_offbox_sync_timeout_records_type_without_command(engine, monkeypatch, tmp_path):
import subprocess

secret = "hunter2-offbox-secret"
_sync_setup(engine, monkeypatch, tmp_path, f"rclone copy --pass={secret} remote:")

def hang(cmd, **kw):
raise subprocess.TimeoutExpired(cmd, kw.get("timeout"))

monkeypatch.setattr(subprocess, "run", hang)
run_backup(engine)
settings = _all_settings(engine)
assert settings["last_backup_sync_error"] == "TimeoutExpired"
assert not any(secret in (v or "") for v in settings.values())


def test_offbox_sync_skipped_when_unconfigured(engine, monkeypatch, tmp_path):
import subprocess

_sync_setup(engine, monkeypatch, tmp_path, "")
monkeypatch.setattr(subprocess, "run", lambda *a, **k: (_ for _ in ()).throw(AssertionError("ran")))
run_backup(engine)
assert "last_backup_sync_error" not in _all_settings(engine)
10 changes: 10 additions & 0 deletions tests/test_improvements.py
Original file line number Diff line number Diff line change
Expand Up @@ -361,3 +361,13 @@ def test_an_invalid_portal_link_is_a_finished_page(client, engine):
assert "Customer portal" in r.text
# No route back into the app: a customer holding a dead link has no account.
assert 'href="/"' not in r.text


def test_failed_offbox_sync_is_surfaced_in_settings_and_operations(client, engine, monkeypatch):
monkeypatch.setattr(config, 'BACKUP_SYNC_CMD', 'rclone copy "$BACKUP_FILE" remote:')
assert 'Configured; verify copies at destination' in client.get('/operations').text
with Session(engine) as s:
models.set_setting(s, 'last_backup_sync_error', 'CalledProcessError (exit 3)')
s.commit()
assert 'Off-box copy: Last attempt failed' in client.get('/operations').text
assert 'Off-box backup sync failed (CalledProcessError (exit 3))' in client.get('/settings').text
Loading
Loading