feat: Phase 3 - AES encryption, SQL audit engine, audit logs (85 tests)
Phase 3.1: Instance password AES-256-GCM encryption Phase 3.2: SQL audit rule engine (10 rules) Phase 3.3: Auto-audit on ticket creation Phase 3.4: Operation audit logs + GET /audit/logs Tests: 44 -> 85 (41 new), Frontend: AuditLogsPage
This commit is contained in:
1 parent
27989274f5
commit
66b09e4d85
16 files changed
+1146
-6
No files matched your search
@@ -0,0 +1,27 @@
|
||||
"""Audit log endpoints."""
|
||||
from typing import Optional
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.database import get_db
|
||||
from app.core.security import require_role
|
||||
from app.models.user import User
|
||||
from app.services.audit_log_service import AuditLogService
|
||||
|
||||
router = APIRouter(prefix="/audit", tags=["审计日志"])
|
||||
|
||||
|
||||
@router.get("/logs")
|
||||
async def list_audit_logs(
|
||||
page: int = Query(1, ge=1),
|
||||
page_size: int = Query(20, ge=1, le=100),
|
||||
user_id: Optional[int] = None,
|
||||
action: Optional[str] = None,
|
||||
target_type: Optional[str] = None,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
current_user: User = Depends(require_role("admin", "dba")),
|
||||
):
|
||||
return await AuditLogService.list_logs(
|
||||
db, page=page, page_size=page_size,
|
||||
user_id=user_id, action=action, target_type=target_type,
|
||||
)
|
||||
@@ -10,6 +10,8 @@ from app.models.user import User
|
||||
from app.models.instance import Instance
|
||||
from app.schemas.instance import InstanceCreate, InstanceUpdate, InstanceResponse, ConnectionTestResult
|
||||
from app.services.instance_service import InstanceService
|
||||
from app.core.crypto import encrypt_password, decrypt_password
|
||||
from app.services.audit_log_service import AuditLogService
|
||||
|
||||
router = APIRouter(prefix="/instances", tags=["数据源管理"])
|
||||
|
||||
@@ -42,12 +44,18 @@ async def create_instance(
|
||||
host=data.host,
|
||||
port=data.port,
|
||||
username=data.username,
|
||||
password=data.password,
|
||||
password=encrypt_password(data.password),
|
||||
database=data.database,
|
||||
env=data.env,
|
||||
description=data.description,
|
||||
)
|
||||
db.add(instance)
|
||||
await db.flush()
|
||||
await AuditLogService.log(
|
||||
db, user_id=current_user.id, action="CREATE_INSTANCE",
|
||||
target_type="instance", target_id=instance.id,
|
||||
detail=f"创建数据源: {data.name} ({data.db_type}@{data.host}:{data.port})",
|
||||
)
|
||||
await db.commit()
|
||||
await db.refresh(instance)
|
||||
return instance
|
||||
@@ -79,6 +87,8 @@ async def update_instance(
|
||||
raise HTTPException(status_code=404, detail="数据源不存在")
|
||||
|
||||
update_data = data.model_dump(exclude_unset=True)
|
||||
if "password" in update_data:
|
||||
update_data["password"] = encrypt_password(update_data["password"])
|
||||
for key, value in update_data.items():
|
||||
setattr(instance, key, value)
|
||||
await db.commit()
|
||||
@@ -97,6 +107,11 @@ async def delete_instance(
|
||||
if not instance:
|
||||
raise HTTPException(status_code=404, detail="数据源不存在")
|
||||
|
||||
await AuditLogService.log(
|
||||
db, user_id=current_user.id, action="DELETE_INSTANCE",
|
||||
target_type="instance", target_id=instance.id,
|
||||
detail=f"删除数据源: {instance.name}",
|
||||
)
|
||||
await db.delete(instance)
|
||||
await db.commit()
|
||||
return {"message": "数据源已删除"}
|
||||
@@ -113,7 +128,18 @@ async def test_connection(
|
||||
if not instance:
|
||||
raise HTTPException(status_code=404, detail="数据源不存在")
|
||||
|
||||
return await InstanceService.test_connection(instance)
|
||||
# Decrypt password for connection test
|
||||
from app.models.instance import Instance as InstModel
|
||||
decrypted = instance.__class__(
|
||||
name=instance.name, db_type=instance.db_type, host=instance.host,
|
||||
port=instance.port, username=instance.username,
|
||||
password=decrypt_password(instance.password),
|
||||
database=instance.database, env=instance.env,
|
||||
description=instance.description, status=instance.status,
|
||||
version=instance.version,
|
||||
)
|
||||
decrypted.id = instance.id
|
||||
return await InstanceService.test_connection(decrypted)
|
||||
|
||||
|
||||
@router.get("/{instance_id}/databases")
|
||||
|
||||
@@ -9,6 +9,7 @@ from app.models.instance import Instance
|
||||
from app.models.audit_log import AuditLog
|
||||
from app.schemas.query import QueryRequest, QueryResult
|
||||
from app.services.query_service import QueryService
|
||||
from app.core.crypto import decrypt_password
|
||||
|
||||
router = APIRouter(prefix="/query", tags=["SQL 查询"])
|
||||
|
||||
@@ -27,6 +28,9 @@ async def execute_query(
|
||||
if not instance:
|
||||
raise HTTPException(status_code=404, detail="数据源不存在")
|
||||
|
||||
# Decrypt password for query execution
|
||||
instance.password = decrypt_password(instance.password)
|
||||
|
||||
try:
|
||||
query_result = await QueryService.execute_query(instance, req.database, req.sql, current_user.id)
|
||||
except ValueError as e:
|
||||
|
||||
@@ -11,6 +11,10 @@ from app.models.user import User
|
||||
from app.models.ticket import Ticket
|
||||
from app.models.instance import Instance
|
||||
from app.schemas.ticket import TicketCreate, TicketReview, TicketResponse
|
||||
from app.core.crypto import decrypt_password
|
||||
from app.services.audit_engine import SQLAuditEngine
|
||||
from app.services.audit_log_service import AuditLogService
|
||||
import json
|
||||
|
||||
router = APIRouter(prefix="/tickets", tags=["工单管理"])
|
||||
|
||||
@@ -104,6 +108,10 @@ async def create_ticket(
|
||||
if not inst.scalar_one_or_none():
|
||||
raise HTTPException(status_code=400, detail="数据源不存在")
|
||||
|
||||
# Auto-audit SQL before creating ticket
|
||||
engine = SQLAuditEngine(env="production" if data.db_type == "mysql" else "development")
|
||||
report = engine.audit(data.sql_content)
|
||||
|
||||
ticket = Ticket(
|
||||
title=data.title,
|
||||
db_type=data.db_type,
|
||||
@@ -115,11 +123,23 @@ async def create_ticket(
|
||||
priority=data.priority,
|
||||
applicant_id=current_user.id,
|
||||
status="pending",
|
||||
audit_result=json.dumps(report.to_dict(), ensure_ascii=False) if report.findings else None,
|
||||
)
|
||||
db.add(ticket)
|
||||
await db.flush() # flush to get ticket.id for audit log
|
||||
|
||||
# Log ticket creation
|
||||
await AuditLogService.log(
|
||||
db, user_id=current_user.id, action="CREATE_TICKET",
|
||||
target_type="ticket", target_id=ticket.id,
|
||||
detail=f"SQL审核评分: {report.score}, 通过: {report.passed}",
|
||||
)
|
||||
|
||||
await db.commit()
|
||||
await db.refresh(ticket)
|
||||
return await _enrich_ticket(ticket, db)
|
||||
result = await _enrich_ticket(ticket, db)
|
||||
result["audit_report"] = report.to_dict()
|
||||
return result
|
||||
|
||||
|
||||
@router.get("/statistics")
|
||||
@@ -184,6 +204,13 @@ async def review_ticket(
|
||||
ticket.approver_id = current_user.id
|
||||
ticket.review_time = datetime.now(timezone.utc)
|
||||
ticket.audit_result = data.comment
|
||||
|
||||
await AuditLogService.log(
|
||||
db, user_id=current_user.id, action="REVIEW_TICKET",
|
||||
target_type="ticket", target_id=ticket.id,
|
||||
detail=f"审核动作: {data.action}, 备注: {data.comment}",
|
||||
)
|
||||
|
||||
await db.commit()
|
||||
await db.refresh(ticket)
|
||||
return await _enrich_ticket(ticket, db)
|
||||
@@ -213,6 +240,7 @@ async def execute_ticket(
|
||||
raise HTTPException(status_code=400, detail="数据源不存在")
|
||||
|
||||
from app.services.query_service import QueryService
|
||||
instance.password = decrypt_password(instance.password)
|
||||
exec_result = await QueryService.execute_dml(instance, ticket.target_database, ticket.sql_content)
|
||||
|
||||
ticket.status = "success"
|
||||
|
||||
@@ -8,6 +8,7 @@ from app.core.database import get_db
|
||||
from app.core.security import get_current_user, hash_password, require_role
|
||||
from app.models.user import User
|
||||
from app.schemas.user import UserCreate, UserUpdate, UserResponse
|
||||
from app.services.audit_log_service import AuditLogService
|
||||
|
||||
router = APIRouter(prefix="/users", tags=["用户管理"])
|
||||
|
||||
@@ -47,6 +48,12 @@ async def create_user(
|
||||
hashed_password=hash_password(data.password),
|
||||
)
|
||||
db.add(user)
|
||||
await db.flush()
|
||||
await AuditLogService.log(
|
||||
db, user_id=current_user.id, action="CREATE_USER",
|
||||
target_type="user", target_id=user.id,
|
||||
detail=f"创建用户: {data.username} ({data.role})",
|
||||
)
|
||||
await db.commit()
|
||||
await db.refresh(user)
|
||||
return user
|
||||
@@ -99,6 +106,11 @@ async def delete_user(
|
||||
if not user:
|
||||
raise HTTPException(status_code=404, detail="用户不存在")
|
||||
|
||||
await AuditLogService.log(
|
||||
db, user_id=current_user.id, action="DELETE_USER",
|
||||
target_type="user", target_id=user.id,
|
||||
detail=f"删除用户: {user.username}",
|
||||
)
|
||||
await db.delete(user)
|
||||
await db.commit()
|
||||
return {"message": "用户已删除"}
|
||||
@@ -1,6 +1,6 @@
|
||||
from fastapi import APIRouter
|
||||
|
||||
from app.api.v1.endpoints import auth, user, instance, ticket, query, dashboard
|
||||
from app.api.v1.endpoints import auth, user, instance, ticket, query, dashboard, audit
|
||||
|
||||
api_router = APIRouter(prefix="/api/v1")
|
||||
|
||||
@@ -10,3 +10,4 @@ api_router.include_router(instance.router)
|
||||
api_router.include_router(ticket.router)
|
||||
api_router.include_router(query.router)
|
||||
api_router.include_router(dashboard.router)
|
||||
api_router.include_router(audit.router)
|
||||
Reference in new issue
Block a user