Init Project Flexly Estimator
This commit is contained in:
@@ -0,0 +1,166 @@
|
||||
from datetime import UTC, datetime
|
||||
|
||||
import pytest
|
||||
from pydantic import ValidationError
|
||||
|
||||
from estimator.config.settings import Settings
|
||||
from estimator.passwords import hash_password, is_valid_hash, verify_password
|
||||
from estimator.web import format as fmt
|
||||
from estimator.web.client import ApiError
|
||||
from estimator.web.routes.estimates import parse_hours
|
||||
from estimator.web.security import LoginLimiter, safe_next
|
||||
|
||||
FAST = {"iterations": 1000}
|
||||
|
||||
|
||||
def test_password_roundtrip_and_wrong_password():
|
||||
h = hash_password("correct horse battery", **FAST)
|
||||
assert verify_password("correct horse battery", h)
|
||||
assert not verify_password("wrong", h) and not verify_password("", h)
|
||||
assert h.startswith("pbkdf2_sha256$1000$") and "correct" not in h
|
||||
|
||||
|
||||
def test_hashes_are_salted():
|
||||
assert hash_password("same", **FAST) != hash_password("same", **FAST)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("bad", ["", "plain", "md5$1$a$b", "pbkdf2_sha256$x$a$b", "pbkdf2_sha256$0$a$b", "a$b$c"])
|
||||
def test_malformed_hash_never_verifies(bad):
|
||||
assert not is_valid_hash(bad) and not verify_password("x", bad)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("target", [
|
||||
"/ui/estimates/abc", "/ui/estimates?status=done", "/ui/market",
|
||||
])
|
||||
def test_safe_next_allows_local_ui_paths(target):
|
||||
assert safe_next(target) == target
|
||||
|
||||
|
||||
@pytest.mark.parametrize("target", [
|
||||
None, "", "https://evil.example/ui/x", "//evil.example/ui/x", "/api/estimates", "javascript:alert(1)",
|
||||
"/ui/..\\evil", "/ui/x\nSet-Cookie: a=b", "ui/relative", "///ui/x",
|
||||
])
|
||||
def test_safe_next_rejects_everything_else(target):
|
||||
assert safe_next(target) == "/ui/estimates/new"
|
||||
|
||||
|
||||
def test_limiter_blocks_after_max_and_expires():
|
||||
now = [0.0]
|
||||
lim = LoginLimiter(3, 60, clock=lambda: now[0])
|
||||
for _ in range(3):
|
||||
assert lim.retry_after("1.1.1.1", "bob") == 0
|
||||
lim.record_failure("1.1.1.1", "bob")
|
||||
assert 0 < lim.retry_after("1.1.1.1", "bob") <= 61
|
||||
assert lim.retry_after("1.1.1.1", "alice") == 0 # another user from the same address is fine
|
||||
assert lim.retry_after("2.2.2.2", "bob") == 0 # same user from another address too
|
||||
now[0] = 61
|
||||
assert lim.retry_after("1.1.1.1", "bob") == 0
|
||||
|
||||
|
||||
def test_limiter_blocks_an_address_spraying_many_users():
|
||||
lim = LoginLimiter(2, 60, clock=lambda: 0.0)
|
||||
for i in range(8):
|
||||
lim.record_failure("9.9.9.9", f"user{i}")
|
||||
assert lim.retry_after("9.9.9.9", "someone-new") > 0
|
||||
|
||||
|
||||
def test_limiter_success_resets_the_user_counter():
|
||||
lim = LoginLimiter(2, 60, clock=lambda: 0.0)
|
||||
lim.record_failure("1.1.1.1", "bob")
|
||||
lim.reset("1.1.1.1", "bob")
|
||||
assert lim.retry_after("1.1.1.1", "bob") == 0
|
||||
|
||||
|
||||
def test_limiter_memory_is_bounded():
|
||||
lim = LoginLimiter(3, 60, clock=lambda: 0.0)
|
||||
for i in range(12_000):
|
||||
lim.record_failure(f"ip{i}", "u")
|
||||
assert len(lim._fails) <= 20_000
|
||||
|
||||
|
||||
def test_money_hours_num_formatting():
|
||||
assert fmt.money(370000, "RUB") == "370\u202f000\u00a0₽"
|
||||
assert fmt.money(17730.4, "EUR") == "17\u202f730\u00a0€"
|
||||
assert fmt.money(None, "RUB") == "—" and fmt.money(5, "XYZ") == "5\u00a0XYZ"
|
||||
assert fmt.hours(144.7) == "144,7\u00a0ч" and fmt.hours(12.0) == "12\u00a0ч"
|
||||
assert fmt.num(25.3333) == "25,33" and fmt.num(8.0) == "8" and fmt.num(1.5) == "1,5"
|
||||
|
||||
|
||||
def test_datetime_filter_uses_the_configured_zone():
|
||||
dt = fmt.make_datetime_filter("Europe/Helsinki")
|
||||
assert dt("2026-10-30T12:00:00+00:00") == "30.10.2026 14:00" # EET, UTC+2 in late October
|
||||
assert dt(datetime(2026, 7, 1, 12, 0, tzinfo=UTC)) == "01.07.2026 15:00" # EEST, UTC+3
|
||||
assert dt("2026-10-30T12:00:00") == "30.10.2026 14:00" # naive is taken as UTC
|
||||
assert dt(None) == "—"
|
||||
|
||||
|
||||
def test_labels_fall_back_to_the_raw_key():
|
||||
assert fmt.label(fmt.ROLES)("backend") == "Backend"
|
||||
assert fmt.label(fmt.ROLES)("wizard") == "wizard" and fmt.label(fmt.ROLES)(None) == "—"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("raw,expected", [("12", 12.0), (" 1,5 ", 1.5), ("0", 0.0), ("2.25", 2.25)])
|
||||
def test_parse_hours_accepts_comma_and_dot(raw, expected):
|
||||
assert parse_hours(raw, "x") == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize("raw", ["", "abc", "-1", "nan", "inf", "1e999"])
|
||||
def test_parse_hours_rejects_garbage(raw):
|
||||
with pytest.raises(ApiError) as e:
|
||||
parse_hours(raw, "Вероятно")
|
||||
assert e.value.status == 422 and "Вероятно" in e.value.detail
|
||||
|
||||
|
||||
# ----------------------------------------------------------- settings validation
|
||||
|
||||
|
||||
def _env(monkeypatch, **extra):
|
||||
base = {"EST_DATABASE__DSN": "sqlite:///x.db", "EST_LLM__ANTHROPIC__API_KEY": "sk-test"}
|
||||
for k, v in {**base, **extra}.items():
|
||||
monkeypatch.setenv(k, v)
|
||||
|
||||
|
||||
def test_web_disabled_needs_nothing(monkeypatch):
|
||||
_env(monkeypatch)
|
||||
assert Settings().web.enabled is False
|
||||
|
||||
|
||||
def test_enabled_web_without_secrets_refuses_to_start(monkeypatch):
|
||||
_env(monkeypatch, EST_WEB__ENABLED="true")
|
||||
with pytest.raises(ValidationError) as e:
|
||||
Settings()
|
||||
text = str(e.value)
|
||||
assert "session_secret" in text and "web.users" in text
|
||||
|
||||
|
||||
def test_enabled_web_rejects_short_secret_and_bad_hash(monkeypatch):
|
||||
_env(monkeypatch, EST_WEB__ENABLED="true", EST_WEB__SESSION_SECRET="short", EST_WEB__USERS="alex:plaintext")
|
||||
with pytest.raises(ValidationError) as e:
|
||||
Settings()
|
||||
assert "at least 32" in str(e.value) and "valid password hash" in str(e.value)
|
||||
|
||||
|
||||
def test_enabled_web_rejects_unknown_timezone_and_odd_user_names(monkeypatch):
|
||||
h = hash_password("x" * 12, **FAST)
|
||||
_env(monkeypatch, EST_WEB__ENABLED="true", EST_WEB__SESSION_SECRET="s" * 40,
|
||||
EST_WEB__USERS=f"bad name:{h}", EST_WEB__TIMEZONE="Mars/Base") # fmt: skip
|
||||
with pytest.raises(ValidationError) as e:
|
||||
Settings()
|
||||
assert "timezone" in str(e.value) and "not valid" in str(e.value)
|
||||
|
||||
|
||||
def test_external_api_mode_needs_a_key(monkeypatch):
|
||||
h = hash_password("x" * 12, **FAST)
|
||||
_env(monkeypatch, EST_WEB__ENABLED="true", EST_WEB__SESSION_SECRET="s" * 40,
|
||||
EST_WEB__USERS=f"alex:{h}", EST_WEB__API_BASE_URL="https://api.example") # fmt: skip
|
||||
with pytest.raises(ValidationError, match="INTERNAL_API_KEY"):
|
||||
Settings()
|
||||
|
||||
|
||||
def test_valid_web_settings_load_and_hide_secrets(monkeypatch):
|
||||
h = hash_password("x" * 12, **FAST)
|
||||
_env(monkeypatch, EST_WEB__ENABLED="true", EST_WEB__SESSION_SECRET="s" * 40,
|
||||
EST_WEB__USERS=f"alex:{h},bob:{h}") # fmt: skip
|
||||
s = Settings()
|
||||
assert set(s.web.user_hashes) == {"alex", "bob"}
|
||||
assert "s" * 40 not in repr(s) and h not in repr(s)
|
||||
Reference in New Issue
Block a user