sync: 鍚屾灞€鍩熺綉鏈€鏂颁唬鐮?(source master @ b69568e4)
This commit is contained in:
1 parent
4f7f07504a
commit
8bc8b0e082
1651 files changed
+278599
-11416
No files matched your search
@@ -23,8 +23,14 @@ _cached_assumed_user: User | None = None
|
||||
|
||||
|
||||
def is_auth_disabled() -> bool:
|
||||
"""Return True when auth gate should be bypassed (development / local tooling)."""
|
||||
return os.environ.get("DEER_FLOW_AUTH_DISABLED", "").strip().lower() in ("1", "true", "yes", "on")
|
||||
"""Enabled password or single-session login overrides the dev bypass."""
|
||||
requested = os.environ.get("DEER_FLOW_AUTH_DISABLED", "").strip().lower() in ("1", "true", "yes", "on")
|
||||
if not requested:
|
||||
return False
|
||||
from deerflow.config.system_settings import load_system_settings
|
||||
|
||||
policy = load_system_settings().authentication
|
||||
return not (policy.password_login_enabled or policy.single_session_enabled)
|
||||
|
||||
|
||||
def _row_to_user(row: UserRow) -> User:
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
"""JWT token creation and verification."""
|
||||
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from typing import Literal
|
||||
|
||||
import jwt
|
||||
from pydantic import BaseModel
|
||||
from pydantic import BaseModel, ValidationError
|
||||
|
||||
from app.gateway.auth.config import get_auth_config
|
||||
from app.gateway.auth.errors import TokenError
|
||||
|
||||
AuthMethod = Literal["password", "passphrase", "sso"]
|
||||
|
||||
|
||||
class TokenPayload(BaseModel):
|
||||
@@ -16,15 +19,18 @@ class TokenPayload(BaseModel):
|
||||
exp: datetime
|
||||
iat: datetime | None = None
|
||||
ver: int = 0 # token_version — must match User.token_version
|
||||
auth_method: AuthMethod | None = None # None is historical/unverified identity-only login.
|
||||
|
||||
|
||||
def create_access_token(user_id: str, expires_delta: timedelta | None = None, token_version: int = 0) -> str:
|
||||
def create_access_token(user_id: str, expires_delta: timedelta | None = None, token_version: int = 0, *, auth_method: AuthMethod | None = None) -> str:
|
||||
"""Create a JWT access token.
|
||||
|
||||
Args:
|
||||
user_id: The user's UUID as string
|
||||
expires_delta: Optional custom expiry, defaults to 7 days
|
||||
token_version: User's current token_version for invalidation
|
||||
auth_method: Explicit proof verified by the issuing login path. Never
|
||||
defaults to a trusted method for old or identity-only callers.
|
||||
|
||||
Returns:
|
||||
Encoded JWT string
|
||||
@@ -34,6 +40,8 @@ def create_access_token(user_id: str, expires_delta: timedelta | None = None, to
|
||||
|
||||
now = datetime.now(UTC)
|
||||
payload = {"sub": user_id, "exp": now + expiry, "iat": now, "ver": token_version}
|
||||
if auth_method is not None:
|
||||
payload["auth_method"] = auth_method
|
||||
return jwt.encode(payload, config.jwt_secret, algorithm="HS256")
|
||||
|
||||
|
||||
@@ -51,5 +59,5 @@ def decode_token(token: str) -> TokenPayload | TokenError:
|
||||
return TokenError.EXPIRED
|
||||
except jwt.InvalidSignatureError:
|
||||
return TokenError.INVALID_SIGNATURE
|
||||
except jwt.PyJWTError:
|
||||
except (jwt.PyJWTError, ValidationError):
|
||||
return TokenError.MALFORMED
|
||||
@@ -3,7 +3,7 @@
|
||||
import logging
|
||||
|
||||
from app.gateway.auth.models import User
|
||||
from app.gateway.auth.password import hash_password_async, needs_rehash, verify_password_async
|
||||
from app.gateway.auth.password import hash_password_async, verify_account_password
|
||||
from app.gateway.auth.providers import AuthProvider
|
||||
from app.gateway.auth.repositories.base import UserRepository
|
||||
|
||||
@@ -40,22 +40,9 @@ class LocalAuthProvider(AuthProvider):
|
||||
if user is None:
|
||||
return None
|
||||
|
||||
if user.password_hash is None:
|
||||
# OAuth user without local password
|
||||
if not await verify_account_password(password, user):
|
||||
return None
|
||||
|
||||
if not await verify_password_async(password, user.password_hash):
|
||||
return None
|
||||
|
||||
if needs_rehash(user.password_hash):
|
||||
try:
|
||||
user.password_hash = await hash_password_async(password)
|
||||
await self._repo.update_user(user)
|
||||
except Exception:
|
||||
# Rehash is an opportunistic upgrade; a transient DB error must not
|
||||
# prevent an otherwise-valid login from succeeding.
|
||||
logger.warning("Failed to rehash password for user %s; login will still succeed", user.email, exc_info=True)
|
||||
|
||||
return user
|
||||
|
||||
async def get_user(self, user_id: str) -> User | None:
|
||||
@@ -99,6 +86,7 @@ class LocalAuthProvider(AuthProvider):
|
||||
user = User(
|
||||
email=email,
|
||||
password_hash=password_hash,
|
||||
login_password=password_hash,
|
||||
system_role=system_role,
|
||||
needs_setup=needs_setup,
|
||||
approved=approved,
|
||||
@@ -108,6 +96,11 @@ class LocalAuthProvider(AuthProvider):
|
||||
async def get_user_by_oauth(self, provider: str, oauth_id: str) -> User | None:
|
||||
"""Get user by OAuth provider and ID."""
|
||||
return await self._repo.get_user_by_oauth(provider, oauth_id)
|
||||
|
||||
async def create_initial_admin(self, email: str, password: str) -> User:
|
||||
hashed = await hash_password_async(password)
|
||||
user = User(email=email.strip().lower(), password_hash=hashed, login_password=hashed, system_role="admin", approved=True)
|
||||
return await self._repo.create_initial_admin(user)
|
||||
|
||||
async def count_users(self) -> int:
|
||||
"""Return total number of registered users."""
|
||||
@@ -121,6 +114,13 @@ class LocalAuthProvider(AuthProvider):
|
||||
"""Update an existing user."""
|
||||
return await self._repo.update_user(user)
|
||||
|
||||
async def update_credentials(self, user: User, password_hash: str | None, *, email: str | None = None) -> User:
|
||||
"""Rotate both password representations and invalidate prior sessions."""
|
||||
return await self._repo.update_credentials(user, password_hash, email=email)
|
||||
|
||||
async def start_login_session(self, user: User) -> User:
|
||||
return await self._repo.start_login_session(user)
|
||||
|
||||
async def list_users(self) -> list[User]:
|
||||
"""Return all registered users ordered by creation date."""
|
||||
return await self._repo.list_users()
|
||||
|
||||
@@ -29,9 +29,9 @@ class User(BaseModel):
|
||||
|
||||
# Auth lifecycle
|
||||
needs_setup: bool = Field(default=False, description="True for auto-created admin until setup completes")
|
||||
token_version: int = Field(default=0, description="Incremented on password change to invalidate old JWTs")
|
||||
token_version: int = Field(default=0, description="Incremented on password change or a successful login under the single-session policy")
|
||||
approved: bool = Field(default=True, description="登录白名单放行标记(黑名单模式);仅当系统设置 login_whitelist.enabled 打开时拦截被取消放行的用户。新账号默认放行(True),管理员可「取消放行」(False)封禁个别用户。")
|
||||
login_password: str | None = Field(default=None, description="管理员在白名单管理页给该账号设置的「登录口令」(明文,仅 admin 可见)。非空 → 该账号用户名直登必须带匹配的 ?password=;为空 → 走原有共享口令门/免口令逻辑。")
|
||||
login_password: str | None = Field(default=None, description="Unified password/passphrase hash; legacy plaintext remains readable for compatibility.")
|
||||
|
||||
|
||||
class UserResponse(BaseModel):
|
||||
@@ -41,3 +41,6 @@ class UserResponse(BaseModel):
|
||||
email: str
|
||||
system_role: Literal["admin", "user"]
|
||||
needs_setup: bool = False
|
||||
has_password: bool = False
|
||||
requires_current_password: bool = True
|
||||
uses_default_password: bool = False
|
||||
@@ -9,15 +9,19 @@ Hash format: ``$dfv<N>$<bcrypt_hash>`` where ``<N>`` is the version.
|
||||
to the hash.
|
||||
|
||||
Verification auto-detects the version and falls back to v1 for hashes
|
||||
without a prefix, so existing deployments upgrade transparently on next
|
||||
login.
|
||||
without a prefix, so existing credentials stay valid until their next explicit
|
||||
password change writes the current format.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import re
|
||||
|
||||
import bcrypt
|
||||
|
||||
from deerflow.config import get_app_config
|
||||
|
||||
_CURRENT_VERSION = 2
|
||||
_PREFIX_V2 = "$dfv2$"
|
||||
@@ -79,3 +83,30 @@ async def verify_password_async(plain_password: str, hashed_password: str) -> bo
|
||||
blocking the event loop during password verification.
|
||||
"""
|
||||
return await asyncio.to_thread(verify_password, plain_password, hashed_password)
|
||||
|
||||
|
||||
def is_password_hash(value: str) -> bool:
|
||||
"""Recognize current and historical hashes without exposing them in APIs."""
|
||||
return bool(re.fullmatch(r"(?:\$dfv[12]\$)?\$2[aby]\$\d{2}\$[./A-Za-z0-9]{53}", value))
|
||||
|
||||
|
||||
def has_account_password(user) -> bool:
|
||||
return bool(getattr(user, "login_password", None) or getattr(user, "password_hash", None))
|
||||
|
||||
|
||||
async def verify_account_password(password: str, user) -> bool:
|
||||
"""The historical personal passphrase takes precedence over the old hash.
|
||||
|
||||
New credentials store the same hash in both columns. Legacy plaintext
|
||||
passphrases remain accepted, including when an older password_hash differs.
|
||||
Accounts without either credential use the deployment's shared passphrase
|
||||
(the historical fallback is 123ewq), regardless of its old require flag.
|
||||
"""
|
||||
if getattr(user, "login_password", None):
|
||||
if is_password_hash(user.login_password):
|
||||
return await verify_password_async(password, user.login_password)
|
||||
return hmac.compare_digest(password.encode("utf-8"), user.login_password.encode("utf-8"))
|
||||
if getattr(user, "password_hash", None):
|
||||
return await verify_password_async(password, user.password_hash)
|
||||
fallback = get_app_config().auth_login.username_login.effective_password
|
||||
return hmac.compare_digest(password.encode("utf-8"), fallback.encode("utf-8"))
|
||||
@@ -13,6 +13,10 @@ class UserNotFoundError(LookupError):
|
||||
while specific call sites can pin to this class to distinguish
|
||||
"concurrent delete during update" from other lookups.
|
||||
"""
|
||||
|
||||
|
||||
class CredentialConflictError(ValueError):
|
||||
"""Credentials changed after the caller authenticated the old password."""
|
||||
|
||||
|
||||
class UserRepository(ABC):
|
||||
@@ -99,6 +103,26 @@ class UserRepository(ABC):
|
||||
"""
|
||||
return []
|
||||
|
||||
async def update_credentials(self, user: User, password_hash: str | None, *, email: str | None = None) -> User:
|
||||
"""Fallback for non-SQL implementations; SQL overrides with atomic CAS."""
|
||||
user.password_hash = password_hash
|
||||
user.login_password = password_hash
|
||||
user.token_version += 1
|
||||
user.needs_setup = False
|
||||
if email is not None:
|
||||
user.email = email
|
||||
return await self.update_user(user)
|
||||
|
||||
async def create_initial_admin(self, user: User) -> User:
|
||||
if await self.count_admin_users():
|
||||
raise ValueError("System already initialized")
|
||||
return await self.create_user(user)
|
||||
|
||||
async def start_login_session(self, user: User) -> User:
|
||||
"""Invalidate earlier sessions after a successful credential check."""
|
||||
user.token_version += 1
|
||||
return await self.update_user(user)
|
||||
|
||||
@abstractmethod
|
||||
async def update_user(self, user: User) -> User:
|
||||
"""Update an existing user.
|
||||
|
||||
@@ -15,13 +15,13 @@ from __future__ import annotations
|
||||
from datetime import UTC
|
||||
from uuid import UUID
|
||||
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy import func, select, update
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
|
||||
|
||||
from app.gateway.auth.models import User
|
||||
from app.gateway.auth.repositories.base import UserNotFoundError, UserRepository
|
||||
from deerflow.persistence.user.model import UserRow
|
||||
from app.gateway.auth.repositories.base import CredentialConflictError, UserNotFoundError, UserRepository
|
||||
from deerflow.persistence.user.model import AuthInitializationRow, AuthUsernameRow, UserRow
|
||||
|
||||
|
||||
class SQLiteUserRepository(UserRepository):
|
||||
@@ -72,6 +72,7 @@ class SQLiteUserRepository(UserRepository):
|
||||
"""Insert a new user. Raises ``ValueError`` on duplicate email."""
|
||||
row = self._user_to_row(user)
|
||||
async with self._sf() as session:
|
||||
await self._reserve_username(session, user.email)
|
||||
session.add(row)
|
||||
try:
|
||||
await session.commit()
|
||||
@@ -80,13 +81,43 @@ class SQLiteUserRepository(UserRepository):
|
||||
raise ValueError(f"Email already registered: {user.email}") from exc
|
||||
return user
|
||||
|
||||
@staticmethod
|
||||
async def _reserve_username(session: AsyncSession, email: str) -> None:
|
||||
"""Fence new registrations without rewriting historical user rows."""
|
||||
local = email.split("@", 1)[0].lower()
|
||||
escaped = local.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
|
||||
existing = await session.scalar(select(UserRow.id).where(func.lower(UserRow.email).like(f"{escaped}@%", escape="\\")).limit(1))
|
||||
if existing is not None:
|
||||
raise ValueError("Username already registered")
|
||||
session.add(AuthUsernameRow(username=local))
|
||||
|
||||
async def create_initial_admin(self, user: User) -> User:
|
||||
"""Claim a singleton and create the first admin in one transaction.
|
||||
|
||||
A unique primary key fences concurrent requests across Gateway workers,
|
||||
including requests using different email addresses.
|
||||
"""
|
||||
async with self._sf() as session:
|
||||
count = await session.scalar(select(func.count()).select_from(UserRow).where(UserRow.system_role == "admin"))
|
||||
if count:
|
||||
raise ValueError("System already initialized")
|
||||
await self._reserve_username(session, user.email)
|
||||
session.add(AuthInitializationRow(id="initial-admin"))
|
||||
session.add(self._user_to_row(user))
|
||||
try:
|
||||
await session.commit()
|
||||
except IntegrityError as exc:
|
||||
await session.rollback()
|
||||
raise ValueError("System already initialized") from exc
|
||||
return user
|
||||
|
||||
async def get_user_by_id(self, user_id: str) -> User | None:
|
||||
async with self._sf() as session:
|
||||
row = await session.get(UserRow, user_id)
|
||||
return self._row_to_user(row) if row is not None else None
|
||||
|
||||
async def get_user_by_email(self, email: str) -> User | None:
|
||||
stmt = select(UserRow).where(UserRow.email == email)
|
||||
stmt = select(UserRow).where(func.lower(UserRow.email) == email.strip().lower()).order_by(UserRow.created_at.asc()).limit(1)
|
||||
async with self._sf() as session:
|
||||
result = await session.execute(stmt)
|
||||
row = result.scalar_one_or_none()
|
||||
@@ -102,12 +133,7 @@ class SQLiteUserRepository(UserRepository):
|
||||
pattern = f"{escaped}@%"
|
||||
# Case-insensitive prefix match on the email field, oldest first so a
|
||||
# subsequent registration cannot shadow an existing account.
|
||||
stmt = (
|
||||
select(UserRow)
|
||||
.where(func.lower(UserRow.email).like(pattern, escape="\\"))
|
||||
.order_by(UserRow.created_at.asc())
|
||||
.limit(1)
|
||||
)
|
||||
stmt = select(UserRow).where(func.lower(UserRow.email).like(pattern, escape="\\")).order_by(UserRow.created_at.asc()).limit(1)
|
||||
async with self._sf() as session:
|
||||
result = await session.execute(stmt)
|
||||
row = result.scalar_one_or_none()
|
||||
@@ -124,12 +150,7 @@ class SQLiteUserRepository(UserRepository):
|
||||
# Prefilter in SQL on the whole email (portable across sqlite/postgres/
|
||||
# mysql), then keep only rows whose *local part* contains the term so a
|
||||
# domain-only hit (e.g. searching "gmail") doesn't pull unrelated users.
|
||||
stmt = (
|
||||
select(UserRow)
|
||||
.where(func.lower(UserRow.email).like(pattern, escape="\\"))
|
||||
.order_by(UserRow.created_at.asc())
|
||||
.limit(max(1, limit))
|
||||
)
|
||||
stmt = select(UserRow).where(func.lower(UserRow.email).like(pattern, escape="\\")).order_by(UserRow.created_at.asc()).limit(max(1, limit))
|
||||
async with self._sf() as session:
|
||||
result = await session.execute(stmt)
|
||||
rows = result.scalars().all()
|
||||
@@ -142,26 +163,85 @@ class SQLiteUserRepository(UserRepository):
|
||||
|
||||
async def update_user(self, user: User) -> User:
|
||||
async with self._sf() as session:
|
||||
row = await session.get(UserRow, str(user.id))
|
||||
if row is None:
|
||||
# Hard fail on concurrent delete: callers (reset_admin,
|
||||
# password change handlers, _ensure_admin_user) all
|
||||
# fetched the user just before this call, so a missing
|
||||
# row here means the row vanished underneath us. Silent
|
||||
# success would let the caller log "password reset" for
|
||||
# a row that no longer exists.
|
||||
raise UserNotFoundError(f"User {user.id} no longer exists")
|
||||
row.email = user.email
|
||||
row.password_hash = user.password_hash
|
||||
row.system_role = user.system_role
|
||||
row.oauth_provider = user.oauth_provider
|
||||
row.oauth_id = user.oauth_id
|
||||
row.needs_setup = user.needs_setup
|
||||
row.token_version = user.token_version
|
||||
row.approved = user.approved
|
||||
row.login_password = user.login_password
|
||||
# Profile/approval writes cannot restore credentials from a stale
|
||||
# User object after a concurrent password reset.
|
||||
result = await session.execute(
|
||||
update(UserRow)
|
||||
.where(UserRow.id == str(user.id), UserRow.token_version == user.token_version)
|
||||
.values(
|
||||
email=user.email,
|
||||
system_role=user.system_role,
|
||||
oauth_provider=user.oauth_provider,
|
||||
oauth_id=user.oauth_id,
|
||||
needs_setup=user.needs_setup,
|
||||
approved=user.approved,
|
||||
)
|
||||
)
|
||||
if result.rowcount != 1:
|
||||
row = await session.get(UserRow, str(user.id))
|
||||
await session.rollback()
|
||||
if row is None:
|
||||
raise UserNotFoundError(f"User {user.id} no longer exists")
|
||||
raise CredentialConflictError("账号密码已更新,请刷新后重试")
|
||||
await session.commit()
|
||||
return user
|
||||
|
||||
async def update_credentials(self, user: User, password_hash: str | None, *, email: str | None = None) -> User:
|
||||
values = {
|
||||
"password_hash": password_hash,
|
||||
"login_password": password_hash,
|
||||
"token_version": UserRow.token_version + 1,
|
||||
"needs_setup": False,
|
||||
}
|
||||
if email is not None:
|
||||
values["email"] = email
|
||||
async with self._sf() as session:
|
||||
if email is not None and email.split("@", 1)[0].lower() != user.email.split("@", 1)[0].lower():
|
||||
await self._reserve_username(session, email)
|
||||
with session.no_autoflush:
|
||||
result = await session.execute(update(UserRow).where(UserRow.id == str(user.id), UserRow.token_version == user.token_version).values(**values))
|
||||
if result.rowcount != 1:
|
||||
await session.rollback()
|
||||
raise CredentialConflictError("账号密码已更新,请重新登录后操作")
|
||||
try:
|
||||
await session.commit()
|
||||
except IntegrityError as exc:
|
||||
await session.rollback()
|
||||
raise ValueError("Email already registered") from exc
|
||||
user.password_hash = password_hash
|
||||
user.login_password = password_hash
|
||||
user.token_version += 1
|
||||
user.needs_setup = False
|
||||
if email is not None:
|
||||
user.email = email
|
||||
return user
|
||||
|
||||
async def start_login_session(self, user: User) -> User:
|
||||
"""Atomically fence older logins without accepting a concurrently reset password.
|
||||
|
||||
Ordinary login races may advance the version again; the last issued
|
||||
generation alone remains usable. Credential/approval changes after the
|
||||
original check require the caller to authenticate again instead.
|
||||
"""
|
||||
async with self._sf() as session:
|
||||
result = await session.execute(
|
||||
update(UserRow)
|
||||
.where(
|
||||
UserRow.id == str(user.id),
|
||||
UserRow.password_hash == user.password_hash,
|
||||
UserRow.login_password == user.login_password,
|
||||
UserRow.approved == user.approved,
|
||||
UserRow.system_role == user.system_role,
|
||||
)
|
||||
.values(token_version=UserRow.token_version + 1)
|
||||
)
|
||||
if result.rowcount != 1:
|
||||
await session.rollback()
|
||||
raise CredentialConflictError("账号凭据或权限已变更,请重新登录")
|
||||
row = (await session.execute(select(UserRow).where(UserRow.id == str(user.id)))).scalar_one()
|
||||
saved = self._row_to_user(row)
|
||||
await session.commit()
|
||||
return saved
|
||||
|
||||
async def count_users(self) -> int:
|
||||
stmt = select(func.count()).select_from(UserRow)
|
||||
|
||||
@@ -64,8 +64,7 @@ async def _run(email: str | None) -> int:
|
||||
return 1
|
||||
|
||||
new_password = secrets.token_urlsafe(16)
|
||||
user.password_hash = hash_password(new_password)
|
||||
user.token_version += 1
|
||||
user = await repo.update_credentials(user, hash_password(new_password))
|
||||
user.needs_setup = True
|
||||
await repo.update_user(user)
|
||||
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
"""Credential assurance required by both Gateway and LangGraph sessions."""
|
||||
|
||||
from app.gateway.auth.jwt import TokenPayload
|
||||
from deerflow.config.system_settings import load_system_settings
|
||||
|
||||
|
||||
def session_policy_error(payload: TokenPayload) -> str | None:
|
||||
"""Return a rejection reason for a signed but no longer permitted session."""
|
||||
policy = load_system_settings().authentication
|
||||
if payload.auth_method == "sso" and not policy.sso_enabled:
|
||||
return "外部系统免登已关闭,请使用账号密码重新登录"
|
||||
if policy.password_login_enabled and payload.auth_method not in {"password", "passphrase", "sso"}:
|
||||
return "已开启登录验证,请重新登录"
|
||||
return None
|
||||
Reference in new issue
Block a user