fix: password_history.id → INTEGER monotonic (детерминированная обрезка)

Грабля: created_at в SQLite точен до секунды — 7 быстрых смен дают
равные метки, а secondary-сортировка по UUID-id случайна → «последние 5»
выбираются произвольно (флакущий тест + неверно хранимая история).
id теперь autoincrement (обрезка order_by id desc), UUID остаётся
как public_id. Миграция 010 обновлена (таблица только на CT108,
пересоздаётся миграцией заново — см. деплой).
This commit is contained in:
2026-09-25 10:46:18 +03:00
parent 50a261e05e
commit a1de5794e2
3 changed files with 16 additions and 8 deletions
+5 -3
View File
@@ -21,11 +21,13 @@ def upgrade() -> None:
sa.Column('password_changed_at', sa.DateTime(timezone=True), sa.Column('password_changed_at', sa.DateTime(timezone=True),
server_default=sa.text('NOW()'), nullable=True), server_default=sa.text('NOW()'), nullable=True),
) )
# История паролей (проверка переиспользования, password_history_count) # История паролей (проверка переиспользования, password_history_count).
# id — INTEGER monotonic (обрезка «последние N» детерминирована; created_at
# в SQLite точен до секунды, UUID-порядок случайный — см. модели).
op.create_table( op.create_table(
'password_history', 'password_history',
sa.Column('id', pg.UUID(as_uuid=True), primary_key=True, sa.Column('id', sa.Integer, primary_key=True, autoincrement=True),
server_default=sa.text('gen_random_uuid()')), sa.Column('public_id', pg.UUID(as_uuid=True), server_default=sa.text('gen_random_uuid()')),
sa.Column('user_id', pg.UUID(as_uuid=True), sa.Column('user_id', pg.UUID(as_uuid=True),
sa.ForeignKey('users.id', ondelete='CASCADE'), nullable=False), sa.ForeignKey('users.id', ondelete='CASCADE'), nullable=False),
sa.Column('hashed_password', sa.String(255), nullable=False), sa.Column('hashed_password', sa.String(255), nullable=False),
+8 -2
View File
@@ -345,10 +345,16 @@ class SecuritySetting(Base):
class PasswordHistoryEntry(Base): class PasswordHistoryEntry(Base):
"""B23: история паролей (bcrypt-хэши). Записывается при каждой смене, """B23: история паролей (bcrypt-хэши). Записывается при каждой смене,
проверяется против password_history_count последних записей.""" проверяется против password_history_count последних записей.
id — monotonic-последовательность (не UUID): обрезка «последние N» должна
быть детерминированной, а created_at в SQLite имеет точность до секунды
(несколько смен внутри одной секунды → равные метки → случайный порядок).
"""
__tablename__ = "password_history" __tablename__ = "password_history"
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) id = Column(Integer, primary_key=True, autoincrement=True)
public_id = Column(UUID(as_uuid=True), default=uuid.uuid4)
user_id = Column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), nullable=False) user_id = Column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), nullable=False)
hashed_password = Column(String(255), nullable=False) hashed_password = Column(String(255), nullable=False)
created_at = Column(DateTime(timezone=True), server_default=func.now()) created_at = Column(DateTime(timezone=True), server_default=func.now())
+3 -3
View File
@@ -83,7 +83,8 @@ def record_password_change(db: Session, user: User, new_hash: str,
В историю кладётся ПРЕДЫДУЩИЙ хэш (previous_hash — хэш, который заменяют), В историю кладётся ПРЕДЫДУЩИЙ хэш (previous_hash — хэш, который заменяют),
чтобы его нельзя было вернуть, пока он не выпал из password_history_count чтобы его нельзя было вернуть, пока он не выпал из password_history_count
последних записей. Обрезка хранит ровно password_history_count записей. последних записей. Обрезка хранит ровно password_history_count записей;
порядок — по monotonic id (created_at в SQLite точен до секунды).
""" """
history_count = int(get_setting(db, 'password_history_count', '5')) history_count = int(get_setting(db, 'password_history_count', '5'))
old_hash = previous_hash if previous_hash is not None else user.hashed_password old_hash = previous_hash if previous_hash is not None else user.hashed_password
@@ -93,8 +94,7 @@ def record_password_change(db: Session, user: User, new_hash: str,
if history_count > 0: if history_count > 0:
keep = (db.query(PasswordHistoryEntry.id) keep = (db.query(PasswordHistoryEntry.id)
.filter(PasswordHistoryEntry.user_id == user.id) .filter(PasswordHistoryEntry.user_id == user.id)
.order_by(PasswordHistoryEntry.created_at.desc(), .order_by(PasswordHistoryEntry.id.desc())
PasswordHistoryEntry.id.desc())
.limit(history_count).all()) .limit(history_count).all())
keep_ids = [row[0] for row in keep] keep_ids = [row[0] for row in keep]
if keep_ids: if keep_ids: