feat: add Windows DNS integration and LDAP/AD authentication
Windows DNS (WinRM): - New dns_service.py: create/delete A-records via PowerShell over WinRM (NTLM) - Idempotent create (removes existing record first), graceful delete - DNS failures are non-fatal — deployment continues, error logged - test-dns endpoint: GET /api/settings/test-dns - Integrated into deploy_customer() and undeploy_customer() LDAP / Active Directory auth: - New ldap_service.py: service-account bind + user search + user bind (ldap3) - Optional AD group restriction via ldap_group_dn - Login flow: LDAP first → local fallback (prevents admin lockout) - LDAP users auto-created with auth_provider="ldap" and role="viewer" - test-ldap endpoint: GET /api/settings/test-ldap - reset-password/reset-mfa guards extended to block LDAP users All credentials (dns_password, ldap_bind_password) encrypted with Fernet. New DB columns added via backwards-compatible migrations. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -13,6 +13,8 @@ from sqlalchemy.orm import Session
|
||||
from app.database import get_db
|
||||
from app.dependencies import create_access_token, create_mfa_token, get_current_user, verify_mfa_token
|
||||
from app.models import SystemConfig, User
|
||||
from app.services import ldap_service
|
||||
from app.utils.config import get_system_config
|
||||
from app.utils.security import (
|
||||
decrypt_value,
|
||||
encrypt_value,
|
||||
@@ -35,24 +37,94 @@ from app.limiter import limiter
|
||||
async def login(request: Request, payload: LoginRequest, db: Session = Depends(get_db)):
|
||||
"""Authenticate with username/password. May require MFA as a second step.
|
||||
|
||||
Auth flow:
|
||||
1. If LDAP is enabled: try LDAP authentication first.
|
||||
- Success → find or auto-create local User with auth_provider="ldap"
|
||||
- Wrong password (user found in LDAP) → HTTP 401
|
||||
- User not found in LDAP → fall through to local auth
|
||||
2. Local auth: verify bcrypt hash for users with auth_provider="local"
|
||||
3. On success: check MFA requirement (local users only) then issue JWT
|
||||
|
||||
Rate-limited to 10 attempts per minute per IP address.
|
||||
"""
|
||||
user = db.query(User).filter(User.username == payload.username).first()
|
||||
if not user or not verify_password(payload.password, user.password_hash):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid username or password.",
|
||||
)
|
||||
config = get_system_config(db)
|
||||
user: User | None = None
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Step 1: LDAP authentication (if enabled)
|
||||
# ------------------------------------------------------------------
|
||||
if config and config.ldap_enabled and config.ldap_server:
|
||||
try:
|
||||
ldap_info = await ldap_service.authenticate_ldap(
|
||||
payload.username, payload.password, config
|
||||
)
|
||||
if ldap_info is not None:
|
||||
# User authenticated via LDAP — find or create local record
|
||||
user = db.query(User).filter(User.username == ldap_info["username"]).first()
|
||||
if not user:
|
||||
user = User(
|
||||
username=ldap_info["username"],
|
||||
password_hash=hash_password(secrets.token_urlsafe(32)),
|
||||
email=ldap_info.get("email", ""),
|
||||
is_active=True,
|
||||
role="viewer",
|
||||
auth_provider="ldap",
|
||||
)
|
||||
db.add(user)
|
||||
db.commit()
|
||||
db.refresh(user)
|
||||
logger.info("LDAP user '%s' auto-created with role 'viewer'.", ldap_info["username"])
|
||||
elif not user.is_active:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Account is disabled.",
|
||||
)
|
||||
else:
|
||||
# Keep auth_provider in sync in case it was changed
|
||||
if user.auth_provider != "ldap":
|
||||
user.auth_provider = "ldap"
|
||||
db.commit()
|
||||
except ValueError as exc:
|
||||
# User found in LDAP but wrong password or group denied
|
||||
logger.warning("LDAP login failed for '%s': %s", payload.username, exc)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid username or password.",
|
||||
)
|
||||
except RuntimeError as exc:
|
||||
# LDAP server unreachable — log and fall through to local auth
|
||||
logger.error("LDAP server error, falling back to local auth: %s", exc)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Step 2: Local authentication (if LDAP didn't produce a user)
|
||||
# ------------------------------------------------------------------
|
||||
if user is None:
|
||||
local_user = db.query(User).filter(User.username == payload.username).first()
|
||||
if local_user and local_user.auth_provider == "local":
|
||||
if not verify_password(payload.password, local_user.password_hash):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid username or password.",
|
||||
)
|
||||
user = local_user
|
||||
else:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid username or password.",
|
||||
)
|
||||
|
||||
if not user.is_active:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Account is disabled.",
|
||||
)
|
||||
|
||||
# Check if MFA is required (only for local users)
|
||||
# ------------------------------------------------------------------
|
||||
# Step 3: MFA check (local users only)
|
||||
# ------------------------------------------------------------------
|
||||
if user.auth_provider == "local":
|
||||
config = db.query(SystemConfig).filter(SystemConfig.id == 1).first()
|
||||
if config and getattr(config, "mfa_enabled", False):
|
||||
sys_config = db.query(SystemConfig).filter(SystemConfig.id == 1).first()
|
||||
if sys_config and getattr(sys_config, "mfa_enabled", False):
|
||||
mfa_token = create_mfa_token(user.username)
|
||||
return {
|
||||
"mfa_required": True,
|
||||
@@ -61,7 +133,7 @@ async def login(request: Request, payload: LoginRequest, db: Session = Depends(g
|
||||
}
|
||||
|
||||
token = create_access_token(user.username)
|
||||
logger.info("User %s logged in.", user.username)
|
||||
logger.info("User %s logged in (provider: %s).", user.username, user.auth_provider)
|
||||
return {
|
||||
"access_token": token,
|
||||
"token_type": "bearer",
|
||||
|
||||
@@ -15,7 +15,7 @@ from sqlalchemy.orm import Session
|
||||
from app.database import get_db
|
||||
from app.dependencies import get_current_user
|
||||
from app.models import SystemConfig, User
|
||||
from app.services import npm_service
|
||||
from app.services import dns_service, ldap_service, npm_service
|
||||
from app.utils.config import get_system_config
|
||||
from app.utils.security import encrypt_value
|
||||
from app.utils.validators import SystemConfigUpdate
|
||||
@@ -86,6 +86,14 @@ async def update_settings(
|
||||
raw_secret = update_data.pop("azure_client_secret")
|
||||
row.azure_client_secret_encrypted = encrypt_value(raw_secret)
|
||||
|
||||
# Handle DNS password encryption
|
||||
if "dns_password" in update_data:
|
||||
row.dns_password_encrypted = encrypt_value(update_data.pop("dns_password"))
|
||||
|
||||
# Handle LDAP bind password encryption
|
||||
if "ldap_bind_password" in update_data:
|
||||
row.ldap_bind_password_encrypted = encrypt_value(update_data.pop("ldap_bind_password"))
|
||||
|
||||
for field, value in update_data.items():
|
||||
if hasattr(row, field):
|
||||
setattr(row, field, value)
|
||||
@@ -164,6 +172,64 @@ async def list_npm_certificates(
|
||||
return result["certificates"]
|
||||
|
||||
|
||||
@router.get("/test-dns")
|
||||
async def test_dns(
|
||||
current_user: User = Depends(get_current_user),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""Test connectivity to the Windows DNS server via WinRM.
|
||||
|
||||
Returns:
|
||||
Dict with ``ok`` and ``message``.
|
||||
"""
|
||||
config = get_system_config(db)
|
||||
if not config:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="System configuration not initialized.",
|
||||
)
|
||||
if not config.dns_enabled:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Windows DNS integration is not enabled.",
|
||||
)
|
||||
if not config.dns_server or not config.dns_username or not config.dns_password:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="DNS server, username, or password not configured.",
|
||||
)
|
||||
return await dns_service.test_dns_connection(config)
|
||||
|
||||
|
||||
@router.get("/test-ldap")
|
||||
async def test_ldap(
|
||||
current_user: User = Depends(get_current_user),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""Test connectivity to the LDAP / Active Directory server.
|
||||
|
||||
Returns:
|
||||
Dict with ``ok`` and ``message``.
|
||||
"""
|
||||
config = get_system_config(db)
|
||||
if not config:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="System configuration not initialized.",
|
||||
)
|
||||
if not config.ldap_enabled:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="LDAP authentication is not enabled.",
|
||||
)
|
||||
if not config.ldap_server or not config.ldap_bind_dn or not config.ldap_bind_password:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="LDAP server, bind DN, or bind password not configured.",
|
||||
)
|
||||
return await ldap_service.test_ldap_connection(config)
|
||||
|
||||
|
||||
@router.get("/branding")
|
||||
async def get_branding(db: Session = Depends(get_db)):
|
||||
"""Public endpoint — returns branding info for the login page (no auth required)."""
|
||||
|
||||
@@ -126,7 +126,7 @@ async def reset_password(
|
||||
if user.auth_provider != "local":
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Cannot reset password for Azure AD users.",
|
||||
detail="Cannot reset password for external auth users (Azure AD / LDAP).",
|
||||
)
|
||||
|
||||
new_password = secrets.token_urlsafe(16)
|
||||
@@ -151,7 +151,7 @@ async def reset_mfa(
|
||||
if user.auth_provider != "local":
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Cannot reset MFA for Azure AD users.",
|
||||
detail="Cannot reset MFA for external auth users (Azure AD / LDAP).",
|
||||
)
|
||||
|
||||
user.totp_enabled = False
|
||||
|
||||
Reference in New Issue
Block a user