sync: 鍚屾灞€鍩熺綉鏈€鏂颁唬鐮?(source master @ b69568e4)
This commit is contained in:
1 parent
4f7f07504a
commit
8bc8b0e082
1651 files changed
+278599
-11416
No files matched your search
@@ -0,0 +1,538 @@
|
||||
"""Authentication policy, password/passphrase parity and session revocation."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
import pytest_asyncio
|
||||
from fastapi import FastAPI
|
||||
from sqlalchemy import update
|
||||
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
|
||||
|
||||
from app.gateway import deps, langgraph_auth
|
||||
from app.gateway.auth import config as auth_config
|
||||
from app.gateway.auth import password as password_utils
|
||||
from app.gateway.auth.disabled_mode import is_auth_disabled
|
||||
from app.gateway.auth.jwt import create_access_token, decode_token
|
||||
from app.gateway.auth.local_provider import LocalAuthProvider
|
||||
from app.gateway.auth.models import User
|
||||
from app.gateway.auth.password import hash_password, verify_password
|
||||
from app.gateway.auth.repositories.base import CredentialConflictError
|
||||
from app.gateway.auth.repositories.sqlite import SQLiteUserRepository
|
||||
from app.gateway.auth_middleware import AuthMiddleware
|
||||
from app.gateway.csrf_middleware import CSRFMiddleware
|
||||
from app.gateway.routers import auth, parallel_agents, system_settings
|
||||
from deerflow.config import system_settings as settings
|
||||
from deerflow.config.login_config import AuthLoginConfig
|
||||
from deerflow.persistence.user.model import AuthInitializationRow, AuthUsernameRow, UserRow
|
||||
|
||||
PASSWORD = "Account-s3cret!"
|
||||
NEW_PASSWORD = "Changed-s3cret!"
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def ctx(monkeypatch, tmp_path):
|
||||
engine = create_async_engine(f"sqlite+aiosqlite:///{tmp_path / 'users.db'}")
|
||||
async with engine.begin() as connection:
|
||||
await connection.run_sync(lambda conn: UserRow.metadata.create_all(conn, tables=[UserRow.__table__, AuthInitializationRow.__table__, AuthUsernameRow.__table__]))
|
||||
sf = async_sessionmaker(engine, expire_on_commit=False)
|
||||
repository = SQLiteUserRepository(sf)
|
||||
provider = LocalAuthProvider(repository)
|
||||
monkeypatch.setattr(settings, "runtime_home", lambda: tmp_path)
|
||||
monkeypatch.setattr(auth, "get_local_provider", lambda: provider)
|
||||
monkeypatch.setattr(deps, "get_local_provider", lambda: provider)
|
||||
monkeypatch.setattr(langgraph_auth, "get_local_provider", lambda: provider)
|
||||
monkeypatch.setattr(auth_config, "_auth_config", auth_config.AuthConfig(jwt_secret="test-auth-key-with-sufficient-entropy-0123456789"))
|
||||
login_config = AuthLoginConfig()
|
||||
monkeypatch.setattr(auth, "get_app_config", lambda: SimpleNamespace(auth_login=login_config))
|
||||
monkeypatch.setattr(password_utils, "get_app_config", lambda: SimpleNamespace(auth_login=login_config))
|
||||
settings.save_system_settings(settings.SystemSettings(authentication=settings.AuthenticationSettings(password_login_enabled=True)))
|
||||
monkeypatch.delenv("DEER_FLOW_AUTH_DISABLED", raising=False)
|
||||
monkeypatch.delenv("DEER_FLOW_USERNAME_LOGIN_DOMAIN", raising=False)
|
||||
monkeypatch.setattr(auth, "_login_attempts", {})
|
||||
monkeypatch.setattr(auth, "_SETUP_STATUS_COOLDOWN", {})
|
||||
app = FastAPI()
|
||||
app.include_router(auth.router)
|
||||
app.include_router(system_settings.router)
|
||||
app.include_router(parallel_agents.router)
|
||||
app.add_middleware(CSRFMiddleware)
|
||||
app.add_middleware(AuthMiddleware)
|
||||
counter = SimpleNamespace(count_owned=AsyncMock(return_value=0))
|
||||
app.dependency_overrides[deps.get_skill_store] = lambda: counter
|
||||
app.dependency_overrides[deps.get_agent_store] = lambda: counter
|
||||
monkeypatch.setattr(auth, "get_run_store", lambda _: SimpleNamespace(count_by_user=AsyncMock(return_value={})))
|
||||
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client:
|
||||
yield SimpleNamespace(client=client, provider=provider, repository=repository, sf=sf, login_config=login_config)
|
||||
await engine.dispose()
|
||||
|
||||
|
||||
def enable_registration():
|
||||
current = settings.load_system_settings()
|
||||
settings.save_system_settings(current.model_copy(update={"authentication": settings.AuthenticationSettings(password_login_enabled=True, registration_enabled=True)}))
|
||||
|
||||
|
||||
def bearer(user, *, auth_method="password"):
|
||||
return {"Authorization": f"Bearer {create_access_token(str(user.id), token_version=user.token_version, auth_method=auth_method)}"}
|
||||
|
||||
|
||||
async def make_admin(ctx, *, password=PASSWORD):
|
||||
return await ctx.provider.create_user("operator@cm.com", password=password, system_role="admin")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_anonymous_options_defaults_and_closed_registration(ctx):
|
||||
settings.save_system_settings(settings.SystemSettings())
|
||||
options = await ctx.client.get("/api/v1/auth/options")
|
||||
assert options.status_code == 200
|
||||
assert options.json() == {"password_login_enabled": False, "registration_enabled": False, "sso_enabled": True, "single_session_enabled": False, "needs_setup": True}
|
||||
assert options.headers["cache-control"] == "no-store"
|
||||
response = await ctx.client.post("/api/v1/auth/register", json={"username": "alice", "password": PASSWORD})
|
||||
assert response.status_code == 403
|
||||
assert await ctx.provider.count_users() == 0
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_register_login_and_sso_share_password_and_user_role(ctx):
|
||||
enable_registration()
|
||||
response = await ctx.client.post("/api/v1/auth/register", json={"username": "b1admin", "password": PASSWORD})
|
||||
assert response.status_code == 201, response.text
|
||||
assert response.json()["system_role"] == "user"
|
||||
assert response.json()["access_token"]
|
||||
assert decode_token(response.json()["access_token"]).auth_method == "password"
|
||||
user = await ctx.provider.get_user(response.json()["user_id"])
|
||||
assert user.password_hash == user.login_password
|
||||
assert user.login_password != PASSWORD
|
||||
assert verify_password(PASSWORD, user.password_hash)
|
||||
for username in ("b1admin", "B1ADMIN@CM.COM"):
|
||||
login = await ctx.client.post("/api/v1/auth/login/local", data={"username": username, "password": PASSWORD})
|
||||
assert login.status_code == 200
|
||||
assert login.json()["user_id"] == str(user.id)
|
||||
denied = await ctx.client.post("/api/v1/auth/login/username", json={"username": "b1admin"})
|
||||
assert denied.status_code == 401
|
||||
sso = await ctx.client.post("/api/v1/auth/login/username", params={"password": PASSWORD}, json={"username": "b1admin"})
|
||||
assert sso.status_code == 200
|
||||
assert decode_token(sso.json()["access_token"]).auth_method == "passphrase"
|
||||
assert sso.json()["system_role"] == "user"
|
||||
me = await ctx.client.get("/api/v1/auth/me", headers=bearer(user))
|
||||
assert me.json()["has_password"] is True
|
||||
assert "password_hash" not in me.json()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("username", ["alice", "ALICE", "alice@other.org"])
|
||||
async def test_registration_rejects_legacy_username_collisions(ctx, username):
|
||||
enable_registration()
|
||||
legacy = await ctx.provider.create_user("alice@legacy.com", password=PASSWORD)
|
||||
response = await ctx.client.post("/api/v1/auth/register", json={"username": username, "password": NEW_PASSWORD})
|
||||
assert response.status_code == 409
|
||||
assert await ctx.provider.count_users() == 1
|
||||
assert verify_password(PASSWORD, (await ctx.provider.get_user(str(legacy.id))).password_hash)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(
|
||||
"body",
|
||||
[
|
||||
{"username": "alice", "password": "password123"},
|
||||
{"username": "alice", "password": "short"},
|
||||
{"username": "alice", "password": "x" * 256},
|
||||
{"username": "alice", "password": " Account-s3cret!"},
|
||||
{"username": "bad name", "password": PASSWORD},
|
||||
{"username": "alice", "password": PASSWORD, "system_role": "admin"},
|
||||
{"username": "alice", "password": PASSWORD, "email": "different@example.com"},
|
||||
],
|
||||
)
|
||||
async def test_register_validates_credentials_and_rejects_role_injection(ctx, body):
|
||||
enable_registration()
|
||||
response = await ctx.client.post("/api/v1/auth/register", json=body)
|
||||
assert response.status_code == 422
|
||||
assert await ctx.provider.count_users() == 0
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_policy_admin_only_and_lockout_protection(ctx):
|
||||
user = await ctx.provider.create_user("alice@cm.com", password=PASSWORD)
|
||||
policy = {"password_login_enabled": True, "registration_enabled": True, "sso_enabled": False}
|
||||
assert (await ctx.client.get("/api/system-settings/authentication")).status_code == 401
|
||||
assert (await ctx.client.put("/api/system-settings/authentication", headers=bearer(user), json=policy)).status_code == 403
|
||||
admin = await make_admin(ctx, password=None)
|
||||
# The existing shared/default passphrase remains usable without a personal password.
|
||||
assert (await ctx.client.put("/api/system-settings/authentication", headers=bearer(admin), json=policy)).status_code == 200
|
||||
for invalid in [dict(policy, password_login_enabled=False), dict(policy, registration_enabled=False, password_login_enabled=False)]:
|
||||
assert (await ctx.client.put("/api/system-settings/authentication", headers=bearer(admin), json=invalid)).status_code == 400
|
||||
changed = await ctx.client.post("/api/v1/auth/change-password", headers=bearer(admin), json={"current_password": "123ewq", "new_password": PASSWORD})
|
||||
assert changed.status_code == 200
|
||||
assert decode_token(changed.json()["access_token"]).auth_method == "password"
|
||||
admin = await ctx.provider.get_user(str(admin.id))
|
||||
assert (await ctx.client.put("/api/system-settings/authentication", headers=bearer(admin), json=policy)).status_code == 200
|
||||
for path, kwargs in [
|
||||
("/api/v1/auth/login/username", {"json": {"username": "newbie"}}),
|
||||
("/api/v1/auth/login/token", {"params": {"token": "upstream"}}),
|
||||
("/api/parallel-agents/auth/token", {"json": {"username": "newbie"}}),
|
||||
]:
|
||||
assert (await ctx.client.post(path, **kwargs)).status_code == 403
|
||||
assert await ctx.provider.count_users() == 2
|
||||
assert (await ctx.client.get("/api/v1/auth/oauth/github", headers=bearer(admin))).status_code == 403
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_disabling_password_login_blocks_login_and_registration(ctx):
|
||||
admin = await make_admin(ctx)
|
||||
response = await ctx.client.put("/api/system-settings/authentication", headers=bearer(admin), json={"password_login_enabled": False, "registration_enabled": False, "sso_enabled": True})
|
||||
assert response.status_code == 200
|
||||
assert (await ctx.client.post("/api/v1/auth/login/local", data={"username": "operator", "password": PASSWORD})).status_code == 403
|
||||
assert (await ctx.client.post("/api/v1/auth/register", json={"username": "alice", "password": PASSWORD})).status_code == 403
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_change_password_revokes_old_sessions_and_keeps_current_bearer(ctx):
|
||||
user = await ctx.provider.create_user("alice@cm.com", password=PASSWORD)
|
||||
old_headers = bearer(user)
|
||||
wrong = await ctx.client.post("/api/v1/auth/change-password", headers=old_headers, json={"current_password": "wrong", "new_password": NEW_PASSWORD})
|
||||
assert wrong.status_code == 400
|
||||
changed = await ctx.client.post("/api/v1/auth/change-password", headers=old_headers, json={"current_password": PASSWORD, "new_password": NEW_PASSWORD})
|
||||
assert changed.status_code == 200
|
||||
assert (await ctx.client.get("/api/v1/auth/me", headers=old_headers)).status_code == 401
|
||||
assert (await ctx.client.get("/api/v1/auth/me", headers={"Authorization": "Bearer " + changed.json()["access_token"]})).status_code == 200
|
||||
saved = await ctx.provider.get_user(str(user.id))
|
||||
assert saved.token_version == 1
|
||||
assert saved.login_password == saved.password_hash
|
||||
for password, expected in [(PASSWORD, 401), (NEW_PASSWORD, 200)]:
|
||||
assert (await ctx.client.post("/api/v1/auth/login/local", data={"username": "alice", "password": password})).status_code == expected
|
||||
assert (await ctx.client.post("/api/v1/auth/login/username", params={"password": password}, json={"username": "alice"})).status_code == expected
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_admin_reset_unified_password_no_hash_leak_and_self_session(ctx):
|
||||
admin = await make_admin(ctx)
|
||||
user = await ctx.provider.create_user("alice@cm.com", password=PASSWORD)
|
||||
old_headers = bearer(user)
|
||||
endpoint = f"/api/v1/auth/users/{user.id}/reset-password"
|
||||
assert (await ctx.client.put(endpoint, headers=old_headers, json={"password": NEW_PASSWORD})).status_code == 403
|
||||
response = await ctx.client.put(endpoint, headers=bearer(admin), json={"password": NEW_PASSWORD})
|
||||
assert response.status_code == 200
|
||||
assert response.json()["login_password"] is None
|
||||
assert response.json()["has_login_password"] is True
|
||||
assert (await ctx.client.get("/api/v1/auth/me", headers=old_headers)).status_code == 401
|
||||
listing = await ctx.client.get("/api/v1/auth/users", headers=bearer(admin))
|
||||
assert listing.status_code == 200
|
||||
assert "$dfv" not in listing.text and NEW_PASSWORD not in listing.text
|
||||
assert (await ctx.client.put(endpoint, headers=bearer(admin), json={"password": None})).status_code == 400
|
||||
old_admin = bearer(admin)
|
||||
self_reset = await ctx.client.put(f"/api/v1/auth/users/{admin.id}/login-password", headers=old_admin, json={"password": NEW_PASSWORD})
|
||||
assert self_reset.status_code == 200
|
||||
assert self_reset.json()["access_token"]
|
||||
assert decode_token(self_reset.json()["access_token"]).auth_method == "password"
|
||||
assert (await ctx.client.get("/api/v1/auth/me", headers=old_admin)).status_code == 401
|
||||
assert (await ctx.client.get("/api/v1/auth/me", headers={"Authorization": "Bearer " + self_reset.json()["access_token"]})).status_code == 200
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("legacy_password", ["old-code", "$dfv-legacy-plaintext"])
|
||||
async def test_historical_plaintext_passphrase_wins_and_changes_without_old_hash(ctx, legacy_password):
|
||||
user = User(email="legacy@cm.com", password_hash=hash_password("different-old-password"), login_password=legacy_password)
|
||||
await ctx.repository.create_user(user)
|
||||
login = await ctx.client.post("/api/v1/auth/login/local", data={"username": "legacy", "password": legacy_password})
|
||||
assert login.status_code == 200
|
||||
assert (await ctx.client.post("/api/v1/auth/login/local", data={"username": "legacy", "password": "different-old-password"})).status_code == 401
|
||||
change = await ctx.client.post("/api/v1/auth/change-password", headers=bearer(user), json={"current_password": legacy_password, "new_password": NEW_PASSWORD})
|
||||
assert change.status_code == 200
|
||||
saved = await ctx.provider.get_user(str(user.id))
|
||||
assert saved.login_password == saved.password_hash
|
||||
assert verify_password(NEW_PASSWORD, saved.login_password)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_parallel_token_endpoint_cannot_bypass_personal_password(ctx):
|
||||
await ctx.provider.create_user("alice@cm.com", password=PASSWORD)
|
||||
endpoint = "/api/parallel-agents/auth/token"
|
||||
assert (await ctx.client.post(endpoint, json={"username": "alice"})).status_code == 401
|
||||
assert (await ctx.client.post(endpoint, params={"password": PASSWORD}, json={"username": "alice"})).status_code == 200
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_approval_gate_applies_to_password_login(ctx):
|
||||
await ctx.provider.create_user("blocked@cm.com", password=PASSWORD, approved=False)
|
||||
current = settings.load_system_settings()
|
||||
settings.save_system_settings(current.model_copy(update={"login_whitelist": settings.LoginWhitelistSettings(enabled=True)}))
|
||||
response = await ctx.client.post("/api/v1/auth/login/local", data={"username": "blocked", "password": PASSWORD})
|
||||
assert response.status_code == 403
|
||||
assert response.json()["detail"]["code"] == "PENDING_APPROVAL"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_stale_profile_and_concurrent_password_updates_cannot_resurrect_credentials(ctx):
|
||||
user = await ctx.provider.create_user("alice@cm.com", password=PASSWORD)
|
||||
stale = user.model_copy(deep=True)
|
||||
await ctx.repository.update_credentials(user, hash_password(NEW_PASSWORD))
|
||||
stale.approved = False
|
||||
with pytest.raises(CredentialConflictError):
|
||||
await ctx.repository.update_user(stale)
|
||||
with pytest.raises(CredentialConflictError):
|
||||
await ctx.repository.update_credentials(stale, hash_password("Concurrent-s3cret!"))
|
||||
saved = await ctx.provider.get_user(str(user.id))
|
||||
assert saved.token_version == 1
|
||||
assert verify_password(NEW_PASSWORD, saved.login_password)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_initialize_first_admin_is_atomic_and_returns_login_credentials(ctx):
|
||||
results = await asyncio.gather(*[ctx.client.post("/api/v1/auth/initialize", json={"email": f"initial{index}@cm.com", "password": PASSWORD}) for index in range(2)])
|
||||
assert sorted(response.status_code for response in results) == [201, 409]
|
||||
assert await ctx.provider.count_admin_users() == 1
|
||||
success = next(response for response in results if response.status_code == 201)
|
||||
assert success.json()["access_token"]
|
||||
assert decode_token(success.json()["access_token"]).auth_method == "password"
|
||||
assert success.json()["system_role"] == "admin"
|
||||
options = await ctx.client.get("/api/v1/auth/options")
|
||||
assert options.json()["needs_setup"] is False
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_sql_credential_rotation_updates_both_columns_without_touching_approval(ctx):
|
||||
user = await ctx.provider.create_user("alice@cm.com", password=PASSWORD)
|
||||
async with ctx.sf() as session:
|
||||
await session.execute(update(UserRow).where(UserRow.id == str(user.id)).values(approved=False))
|
||||
await session.commit()
|
||||
saved = await ctx.provider.update_credentials(user, hash_password(NEW_PASSWORD))
|
||||
persisted = await ctx.provider.get_user(str(saved.id))
|
||||
assert persisted.approved is False
|
||||
assert persisted.password_hash == persisted.login_password
|
||||
assert persisted.token_version == 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_concurrent_registration_email_domains_cannot_claim_same_username(ctx):
|
||||
enable_registration()
|
||||
results = await asyncio.gather(*[ctx.client.post("/api/v1/auth/register", json={"email": f"alice@domain{index}.com", "password": PASSWORD}) for index in range(2)])
|
||||
assert sorted(response.status_code for response in results) == [201, 409]
|
||||
assert await ctx.provider.count_users() == 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_username_sso_rechecks_password_if_registration_won_a_race(ctx, monkeypatch):
|
||||
await ctx.provider.create_user("alice@cm.com", password=PASSWORD)
|
||||
monkeypatch.setattr(auth, "_lookup_user_by_username", AsyncMock(return_value=None))
|
||||
response = await ctx.client.post("/api/v1/auth/login/username", json={"username": "alice"})
|
||||
assert response.status_code == 401
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("configured,expected_password", [("", "123ewq"), ("Original-shared-code", "Original-shared-code")])
|
||||
async def test_accounts_without_personal_password_use_existing_passphrase(ctx, configured, expected_password):
|
||||
ctx.login_config.username_login.password = configured
|
||||
user = await ctx.provider.create_user("legacy@cm.com")
|
||||
assert not ctx.login_config.username_login.require_password
|
||||
assert await ctx.provider.authenticate({"email": user.email, "password": "wrong"}) is None
|
||||
assert (await ctx.provider.authenticate({"email": user.email, "password": expected_password})).id == user.id
|
||||
for path, kwargs in [
|
||||
("/api/v1/auth/login/local", {"data": {"username": "legacy", "password": expected_password}}),
|
||||
("/api/v1/auth/login/username", {"json": {"username": "legacy"}, "params": {"password": expected_password}}),
|
||||
("/api/parallel-agents/auth/token", {"json": {"username": "legacy"}, "params": {"password": expected_password}}),
|
||||
]:
|
||||
response = await ctx.client.post(path, **kwargs)
|
||||
assert response.status_code == 200, response.text
|
||||
assert decode_token(response.json()["access_token"]).auth_method in {"password", "passphrase"}
|
||||
me = await ctx.client.get("/api/v1/auth/me", headers=bearer(user))
|
||||
assert me.json()["has_password"] is False
|
||||
assert me.json()["uses_default_password"] is True
|
||||
assert me.json()["requires_current_password"] is True
|
||||
if configured:
|
||||
denied = await ctx.client.post("/api/v1/auth/login/local", data={"username": "legacy", "password": "123ewq"})
|
||||
assert denied.status_code == 401
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_first_personal_password_requires_current_shared_passphrase(ctx):
|
||||
user = await ctx.provider.create_user("legacy@cm.com")
|
||||
old_headers = bearer(user)
|
||||
for wrong in ("", "incorrect"):
|
||||
response = await ctx.client.post("/api/v1/auth/change-password", headers=old_headers, json={"current_password": wrong, "new_password": NEW_PASSWORD})
|
||||
assert response.status_code == 400
|
||||
changed = await ctx.client.post("/api/v1/auth/change-password", headers=old_headers, json={"current_password": "123ewq", "new_password": NEW_PASSWORD})
|
||||
assert changed.status_code == 200
|
||||
for path, kwargs in [
|
||||
("/api/v1/auth/login/local", {"data": {"username": "legacy", "password": "123ewq"}}),
|
||||
("/api/v1/auth/login/username", {"json": {"username": "legacy"}, "params": {"password": "123ewq"}}),
|
||||
]:
|
||||
assert (await ctx.client.post(path, **kwargs)).status_code == 401
|
||||
updated = await ctx.provider.get_user(str(user.id))
|
||||
assert await ctx.provider.authenticate({"email": user.email, "password": "123ewq"}) is None
|
||||
me = await ctx.client.get("/api/v1/auth/me", headers=bearer(updated))
|
||||
assert me.json()["has_password"] is True
|
||||
assert me.json()["uses_default_password"] is False
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_enabled_password_login_blocks_bare_username_and_parallel_logins(ctx):
|
||||
await ctx.provider.create_user("legacy@cm.com")
|
||||
for username in ("legacy", "not-created"):
|
||||
for endpoint in ("/api/v1/auth/login/username", "/api/parallel-agents/auth/token"):
|
||||
assert (await ctx.client.post(endpoint, json={"username": username})).status_code == 401
|
||||
assert await ctx.provider.count_users() == 1
|
||||
|
||||
|
||||
def langgraph_request(token):
|
||||
return SimpleNamespace(method="GET", headers={"authorization": f"Bearer {token}"}, cookies={})
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_gateway_and_langgraph_reject_legacy_session_after_login_enabled(ctx):
|
||||
user = await ctx.provider.create_user("legacy@cm.com")
|
||||
legacy = create_access_token(str(user.id), token_version=user.token_version)
|
||||
assert decode_token(legacy).auth_method is None
|
||||
for cookie_only in (False, True):
|
||||
ctx.client.cookies.clear()
|
||||
if cookie_only:
|
||||
ctx.client.cookies.set("access_token", legacy)
|
||||
headers = {} if cookie_only else {"Authorization": f"Bearer {legacy}"}
|
||||
assert (await ctx.client.get("/api/v1/auth/me", headers=headers)).status_code == 401
|
||||
with pytest.raises(Exception) as rejected:
|
||||
await langgraph_auth.authenticate(langgraph_request(legacy))
|
||||
assert rejected.value.status_code == 401
|
||||
login = await ctx.client.post("/api/v1/auth/login/local", data={"username": "legacy", "password": "123ewq"})
|
||||
assert login.status_code == 200
|
||||
fresh = login.json()["access_token"]
|
||||
assert (await ctx.client.get("/api/v1/auth/me", headers={"Authorization": f"Bearer {fresh}"})).status_code == 200
|
||||
assert await langgraph_auth.authenticate(langgraph_request(fresh)) == str(user.id)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_passwordless_compatibility_token_cannot_survive_enabling_password_login(ctx):
|
||||
settings.save_system_settings(settings.SystemSettings())
|
||||
response = await ctx.client.post("/api/v1/auth/login/username", json={"username": "legacy"})
|
||||
assert response.status_code == 200
|
||||
token = response.json()["access_token"]
|
||||
assert decode_token(token).auth_method is None
|
||||
assert (await ctx.client.get("/api/v1/auth/me", headers={"Authorization": f"Bearer {token}"})).status_code == 200
|
||||
assert await langgraph_auth.authenticate(langgraph_request(token)) == response.json()["user_id"]
|
||||
settings.save_system_settings(settings.SystemSettings(authentication=settings.AuthenticationSettings(password_login_enabled=True)))
|
||||
assert (await ctx.client.get("/api/v1/auth/me", headers={"Authorization": f"Bearer {token}"})).status_code == 401
|
||||
with pytest.raises(Exception) as rejected:
|
||||
await langgraph_auth.authenticate(langgraph_request(token))
|
||||
assert rejected.value.status_code == 401
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_verified_upstream_sso_remains_independently_controlled(ctx):
|
||||
ctx.login_config.token_login.enabled = True
|
||||
ctx.login_config.token_login.mock_tokens = {"trusted-upstream-token": "sso-user"}
|
||||
response = await ctx.client.post("/api/v1/auth/login/token", params={"token": "trusted-upstream-token"})
|
||||
assert response.status_code == 200
|
||||
token = response.json()["access_token"]
|
||||
assert decode_token(token).auth_method == "sso"
|
||||
assert (await ctx.client.get("/api/v1/auth/me", headers={"Authorization": f"Bearer {token}"})).status_code == 200
|
||||
assert await langgraph_auth.authenticate(langgraph_request(token)) == response.json()["user_id"]
|
||||
settings.save_system_settings(settings.SystemSettings(authentication=settings.AuthenticationSettings(password_login_enabled=True, sso_enabled=False)))
|
||||
assert (await ctx.client.get("/api/v1/auth/me", headers={"Authorization": f"Bearer {token}"})).status_code == 401
|
||||
with pytest.raises(Exception) as rejected:
|
||||
await langgraph_auth.authenticate(langgraph_request(token))
|
||||
assert rejected.value.status_code == 401
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("policy_field", ["password_login_enabled", "single_session_enabled"])
|
||||
async def test_development_bypass_does_not_override_enabled_login(ctx, monkeypatch, policy_field):
|
||||
settings.save_system_settings(settings.SystemSettings(authentication=settings.AuthenticationSettings(**{policy_field: True})))
|
||||
monkeypatch.setenv("DEER_FLOW_AUTH_DISABLED", "true")
|
||||
assert is_auth_disabled() is False
|
||||
assert (await ctx.client.get("/api/v1/auth/me")).status_code == 401
|
||||
with pytest.raises(Exception) as rejected:
|
||||
await langgraph_auth.authenticate(langgraph_request(""))
|
||||
assert rejected.value.status_code == 401
|
||||
settings.save_system_settings(settings.SystemSettings())
|
||||
assert is_auth_disabled() is True
|
||||
|
||||
|
||||
def set_single_session(enabled):
|
||||
current = settings.load_system_settings()
|
||||
policy = current.authentication.model_copy(update={"single_session_enabled": enabled})
|
||||
settings.save_system_settings(current.model_copy(update={"authentication": policy}))
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("enabled", [False, True])
|
||||
@pytest.mark.parametrize("method", ["local", "username", "token", "parallel"])
|
||||
async def test_login_single_session_policy_across_all_entry_points(ctx, enabled, method):
|
||||
user = await ctx.provider.create_user("alice@cm.com", password=PASSWORD)
|
||||
set_single_session(enabled)
|
||||
ctx.login_config.token_login.enabled = True
|
||||
ctx.login_config.token_login.mock_tokens = {"upstream-alice": "alice"}
|
||||
|
||||
async def login():
|
||||
if method == "local":
|
||||
return await ctx.client.post("/api/v1/auth/login/local", data={"username": "alice", "password": PASSWORD})
|
||||
if method == "token":
|
||||
return await ctx.client.post("/api/v1/auth/login/token", params={"token": "upstream-alice"})
|
||||
endpoint = "/api/parallel-agents/auth/token" if method == "parallel" else "/api/v1/auth/login/username"
|
||||
return await ctx.client.post(endpoint, json={"username": "alice"}, params={"password": PASSWORD})
|
||||
|
||||
first, second = await login(), await login()
|
||||
assert first.status_code == second.status_code == 200
|
||||
first_token, second_token = first.json()["access_token"], second.json()["access_token"]
|
||||
assert (await ctx.client.get("/api/v1/auth/me", headers={"Authorization": f"Bearer {first_token}"})).status_code == (401 if enabled else 200)
|
||||
assert (await ctx.client.get("/api/v1/auth/me", headers={"Authorization": f"Bearer {second_token}"})).status_code == 200
|
||||
if enabled:
|
||||
assert decode_token(second_token).ver == decode_token(first_token).ver + 1
|
||||
with pytest.raises(Exception) as rejected:
|
||||
await langgraph_auth.authenticate(langgraph_request(first_token))
|
||||
assert rejected.value.status_code == 401
|
||||
else:
|
||||
assert decode_token(first_token).ver == decode_token(second_token).ver == 0
|
||||
assert await langgraph_auth.authenticate(langgraph_request(first_token)) == str(user.id)
|
||||
assert await langgraph_auth.authenticate(langgraph_request(second_token)) == str(user.id)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_failed_login_does_not_kick_out_existing_session(ctx):
|
||||
await ctx.provider.create_user("alice@cm.com", password=PASSWORD)
|
||||
set_single_session(True)
|
||||
first = await ctx.client.post("/api/v1/auth/login/local", data={"username": "alice", "password": PASSWORD})
|
||||
token = first.json()["access_token"]
|
||||
failed = await ctx.client.post("/api/v1/auth/login/local", data={"username": "alice", "password": "incorrect"})
|
||||
assert failed.status_code == 401
|
||||
assert (await ctx.client.get("/api/v1/auth/me", headers={"Authorization": f"Bearer {token}"})).status_code == 200
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_concurrent_logins_have_exactly_one_surviving_session(ctx):
|
||||
await ctx.provider.create_user("alice@cm.com", password=PASSWORD)
|
||||
set_single_session(True)
|
||||
responses = await asyncio.gather(*[ctx.client.post("/api/v1/auth/login/local", data={"username": "alice", "password": PASSWORD}) for _ in range(2)])
|
||||
assert all(response.status_code == 200 for response in responses)
|
||||
tokens = [response.json()["access_token"] for response in responses]
|
||||
assert sorted(decode_token(token).ver for token in tokens) == [1, 2]
|
||||
checks = [await ctx.client.get("/api/v1/auth/me", headers={"Authorization": f"Bearer {token}"}) for token in tokens]
|
||||
assert sorted(response.status_code for response in checks) == [200, 401]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_single_session_cannot_reissue_after_concurrent_password_reset(ctx):
|
||||
user = await ctx.provider.create_user("alice@cm.com", password=PASSWORD)
|
||||
stale = user.model_copy(deep=True)
|
||||
await ctx.repository.update_credentials(user, hash_password(NEW_PASSWORD))
|
||||
with pytest.raises(CredentialConflictError):
|
||||
await ctx.repository.start_login_session(stale)
|
||||
persisted = await ctx.provider.get_user(str(user.id))
|
||||
assert persisted.token_version == 1
|
||||
assert verify_password(NEW_PASSWORD, persisted.password_hash)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("method", ["register", "initialize"])
|
||||
async def test_first_account_login_obeys_single_session_setting(ctx, method):
|
||||
enable_registration()
|
||||
set_single_session(True)
|
||||
body = {"password": PASSWORD, "username" if method == "register" else "email": "first" if method == "register" else "first@cm.com"}
|
||||
first = await ctx.client.post(f"/api/v1/auth/{method}", json=body)
|
||||
assert first.status_code == 201
|
||||
old_token = first.json()["access_token"]
|
||||
assert decode_token(old_token).ver == 1
|
||||
second = await ctx.client.post("/api/v1/auth/login/local", data={"username": "first", "password": PASSWORD})
|
||||
assert second.status_code == 200
|
||||
assert decode_token(second.json()["access_token"]).ver == 2
|
||||
assert (await ctx.client.get("/api/v1/auth/me", headers={"Authorization": f"Bearer {old_token}"})).status_code == 401
|
||||
Reference in new issue
Block a user