```
feat(core): 添加API认证主体配置和安全验证 - 在Settings中添加api_actor字段,用于标识API调用方身份 - 创建ApiPrincipal数据类来表示服务主体 - 修改require_api_key函数返回认证的服务主体信息 - 更新配置文件引入ActorValue常量 feat(ai_agent): 增强OpenClaw工具调用的安全性检查 - 实现_openclaw_allowed_tools和openclaw_allowed_actions配置项 - 添加CSV列表解析验证器 - 实现工具和操作权限检查方法_ensure_tool_allowed - 在工具调用前验证允许的工具和操作类型 feat(security): 强化API密钥认证和审计安全性 - 更新require_api_key函数在缺少API_KEY时抛出异常 - 在AI代理、审批、飞书等模块的路由中统一使用ApiPrincipal获取调用方信息 - 替换硬编码的ActorValue.API为动态的principal.actor feat(audit): 实现安全审计负载脱敏处理 - 添加敏感键名集合AI_AUDIT_SENSITIVE_KEYS - 实现审计安全负载处理函数_audit_safe_payload - 支持深度遍历、文本截断、序列限制和敏感信息脱敏 - 在AI服务的审计日志中应用安全负载处理 feat(approval): 完善审批流程的申请人身份验证 - 更新审批创建接口使用认证主体作为申请人 - 使用utc_now替换datetime.utcnow确保时间一致性 - 修复审批逻辑中的条件判断问题 feat(business): 加强业务领域高风险操作的审批控制 - 为高风险域创建统一的审批验证方法_ensure_approved - 在创建和更新操作中强制要求审批票证 - 为项目同步功能添加认证主体参数 feat(config): 统一时间处理使用UTC时间函数 - 创建并使用utc_now函数替代datetime.utcnow - 在审批、审计、业务、遗留数据等模块中更新时间戳处理 feat(constants): 扩展风险事件类型和报告指标 - 添加新风险事件类型到GENERATED_RISK_EVENT_TYPES - 为报告模块添加外部开放和高风险事件指标 refactor(feishu): 增强飞书验证令牌安全检查 - 确保飞书验证令牌配置存在时才接受请求 - 修正令牌验证逻辑以提高安全性 ```
This commit is contained in:
@@ -101,6 +101,8 @@ class MetricKey(StrEnum):
|
||||
OVER_BUDGET_PROJECTS = "over_budget_projects"
|
||||
OPEN_EVENTS = "open_events"
|
||||
HIGH_EVENTS = "high_events"
|
||||
EXTERNAL_OPEN_EVENTS = "external_open_events"
|
||||
EXTERNAL_HIGH_EVENTS = "external_high_events"
|
||||
EVENTS_BY_TYPE = "events_by_type"
|
||||
EVENTS_BY_LEVEL = "events_by_level"
|
||||
SCORE = "score"
|
||||
|
||||
@@ -3,9 +3,8 @@ from datetime import date
|
||||
from fastapi import APIRouter, Depends
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.core.constants import ActorValue
|
||||
from app.core.database import get_db
|
||||
from app.core.security import require_api_key
|
||||
from app.core.security import ApiPrincipal, require_api_key
|
||||
from app.modules.reports.schemas import (
|
||||
PushReportRequest,
|
||||
ReportResponse,
|
||||
@@ -33,8 +32,8 @@ def project_lifecycle_report(
|
||||
period_start: date | None = None,
|
||||
period_end: date | None = None,
|
||||
include_ai: bool = False,
|
||||
actor: str = ActorValue.API,
|
||||
db: Session = Depends(get_db),
|
||||
principal: ApiPrincipal = Depends(require_api_key),
|
||||
) -> dict:
|
||||
return ReportService(db).project_lifecycle_report(
|
||||
project_code=project_code,
|
||||
@@ -42,7 +41,7 @@ def project_lifecycle_report(
|
||||
period_start=period_start,
|
||||
period_end=period_end,
|
||||
include_ai=include_ai,
|
||||
actor=actor,
|
||||
actor=principal.actor,
|
||||
)
|
||||
|
||||
|
||||
@@ -58,6 +57,7 @@ def attendance_summary(
|
||||
def generate_work_report(
|
||||
payload: WorkReportGenerateRequest,
|
||||
db: Session = Depends(get_db),
|
||||
principal: ApiPrincipal = Depends(require_api_key),
|
||||
) -> dict:
|
||||
return ReportService(db).generate_work_report(
|
||||
report_type=payload.report_type,
|
||||
@@ -67,27 +67,35 @@ def generate_work_report(
|
||||
period_start=payload.period_start,
|
||||
period_end=payload.period_end,
|
||||
persist=payload.persist,
|
||||
actor=payload.actor,
|
||||
actor=principal.actor,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/daily-brief/push")
|
||||
def push_daily_brief(payload: PushReportRequest, db: Session = Depends(get_db)) -> dict:
|
||||
def push_daily_brief(
|
||||
payload: PushReportRequest,
|
||||
db: Session = Depends(get_db),
|
||||
principal: ApiPrincipal = Depends(require_api_key),
|
||||
) -> dict:
|
||||
report = ReportService(db).daily_brief()
|
||||
return ReportService(db).push_report(
|
||||
report,
|
||||
payload.receive_id,
|
||||
payload.receive_id_type,
|
||||
payload.actor,
|
||||
principal.actor,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/project-weekly/push")
|
||||
def push_project_weekly(payload: PushReportRequest, db: Session = Depends(get_db)) -> dict:
|
||||
def push_project_weekly(
|
||||
payload: PushReportRequest,
|
||||
db: Session = Depends(get_db),
|
||||
principal: ApiPrincipal = Depends(require_api_key),
|
||||
) -> dict:
|
||||
report = ReportService(db).project_weekly()
|
||||
return ReportService(db).push_report(
|
||||
report,
|
||||
payload.receive_id,
|
||||
payload.receive_id_type,
|
||||
payload.actor,
|
||||
principal.actor,
|
||||
)
|
||||
|
||||
@@ -6,11 +6,14 @@ from sqlalchemy import func, or_, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.core.constants import ActorValue
|
||||
from app.core.time import utc_now
|
||||
from app.modules.audit.constants import AuditSource, AuditTargetType
|
||||
from app.modules.audit.schemas import AuditLogCreate
|
||||
from app.modules.audit.service import AuditService
|
||||
from app.modules.business.constants import (
|
||||
ATTENDANCE_ABNORMAL_STATUSES,
|
||||
DONE_STATUSES,
|
||||
GENERATED_RISK_EVENT_TYPES,
|
||||
PROJECT_CLOSED_STATUSES,
|
||||
PENDING_APPROVAL_STATUSES,
|
||||
SUPPLIER_RISK_LEVELS,
|
||||
@@ -69,7 +72,7 @@ def _json_safe(value: Any) -> Any:
|
||||
def _next_code(prefix: str) -> str:
|
||||
"""Build a compact unique code for generated report records."""
|
||||
|
||||
return f"{prefix}-{datetime.utcnow():%Y%m%d%H%M%S%f}"
|
||||
return f"{prefix}-{utc_now():%Y%m%d%H%M%S%f}"
|
||||
|
||||
|
||||
def _rate(numerator: int | Decimal, denominator: int | Decimal) -> float:
|
||||
@@ -228,7 +231,14 @@ class ReportService:
|
||||
task_conditions,
|
||||
risk_conditions,
|
||||
)
|
||||
health = self._lifecycle_health(project_stats, task_stats, risk_stats, supplier_stats)
|
||||
include_global_risk = not (project_code or owner)
|
||||
health = self._lifecycle_health(
|
||||
project_stats,
|
||||
task_stats,
|
||||
risk_stats,
|
||||
supplier_stats,
|
||||
include_global_risk,
|
||||
)
|
||||
attention = self._lifecycle_attention(project_conditions, task_conditions)
|
||||
recommendations = self._lifecycle_recommendations(
|
||||
project_stats,
|
||||
@@ -238,6 +248,7 @@ class ReportService:
|
||||
fund_stats,
|
||||
supplier_stats,
|
||||
risk_stats,
|
||||
include_global_risk,
|
||||
)
|
||||
|
||||
metrics = {
|
||||
@@ -533,12 +544,25 @@ class ReportService:
|
||||
RiskEvent.risk_level == RiskLevel.HIGH,
|
||||
*risk_conditions,
|
||||
)
|
||||
external_open_events = self._count(
|
||||
RiskEvent,
|
||||
RiskEvent.status == StatusValue.OPEN,
|
||||
RiskEvent.risk_type.notin_(GENERATED_RISK_EVENT_TYPES),
|
||||
*risk_conditions,
|
||||
)
|
||||
external_high_events = self._count(
|
||||
RiskEvent,
|
||||
RiskEvent.status == StatusValue.OPEN,
|
||||
RiskEvent.risk_level == RiskLevel.HIGH,
|
||||
RiskEvent.risk_type.notin_(GENERATED_RISK_EVENT_TYPES),
|
||||
*risk_conditions,
|
||||
)
|
||||
risk_score = (
|
||||
overdue_tasks * 1
|
||||
+ delayed_projects * 3
|
||||
+ over_budget_projects * 4
|
||||
+ open_events * 2
|
||||
+ high_events * 3
|
||||
+ external_open_events * 2
|
||||
+ external_high_events * 3
|
||||
)
|
||||
if risk_score >= 15:
|
||||
level = RiskLevel.HIGH
|
||||
@@ -554,6 +578,8 @@ class ReportService:
|
||||
MetricKey.OVER_BUDGET_PROJECTS: over_budget_projects,
|
||||
MetricKey.OPEN_EVENTS: open_events,
|
||||
MetricKey.HIGH_EVENTS: high_events,
|
||||
MetricKey.EXTERNAL_OPEN_EVENTS: external_open_events,
|
||||
MetricKey.EXTERNAL_HIGH_EVENTS: external_high_events,
|
||||
MetricKey.EVENTS_BY_TYPE: self._group_counts(
|
||||
RiskEvent,
|
||||
RiskEvent.risk_type,
|
||||
@@ -572,16 +598,18 @@ class ReportService:
|
||||
tasks: dict[str, Any],
|
||||
risks: dict[str, Any],
|
||||
suppliers: dict[str, Any],
|
||||
include_global_risk: bool,
|
||||
) -> dict[str, Any]:
|
||||
penalty = (
|
||||
risks[MetricKey.OVERDUE_TASKS] * 3
|
||||
+ risks[MetricKey.DELAYED_PROJECTS] * 8
|
||||
+ risks[MetricKey.OVER_BUDGET_PROJECTS] * 10
|
||||
+ risks[MetricKey.HIGH_EVENTS] * 8
|
||||
+ suppliers[MetricKey.BLACKLISTED] * 10
|
||||
+ risks[MetricKey.EXTERNAL_HIGH_EVENTS] * 8
|
||||
+ max(0, projects[MetricKey.BUDGET_USAGE_RATE] - 100) * 0.4
|
||||
+ (100 - tasks[MetricKey.COMPLETION_RATE]) * 0.1
|
||||
)
|
||||
if include_global_risk:
|
||||
penalty += suppliers[MetricKey.BLACKLISTED] * 10
|
||||
score = max(0, min(100, round(100 - penalty, 2)))
|
||||
if score >= 80:
|
||||
level = HealthLevel.HEALTHY
|
||||
@@ -641,6 +669,7 @@ class ReportService:
|
||||
funds: dict[str, Any],
|
||||
suppliers: dict[str, Any],
|
||||
risks: dict[str, Any],
|
||||
include_global_risk: bool,
|
||||
) -> list[str]:
|
||||
recommendations: list[str] = []
|
||||
if risks[MetricKey.DELAYED_PROJECTS]:
|
||||
@@ -654,9 +683,9 @@ class ReportService:
|
||||
or expenses[MetricKey.PENDING_APPROVAL]
|
||||
):
|
||||
recommendations.append(ReportText.RECOMMEND_APPROVALS)
|
||||
if funds[MetricKey.RISK_ACCOUNTS]:
|
||||
if include_global_risk and funds[MetricKey.RISK_ACCOUNTS]:
|
||||
recommendations.append(ReportText.RECOMMEND_FUNDS)
|
||||
if suppliers[MetricKey.RISKY]:
|
||||
if include_global_risk and suppliers[MetricKey.RISKY]:
|
||||
recommendations.append(ReportText.RECOMMEND_SUPPLIERS)
|
||||
if not recommendations:
|
||||
recommendations.append(ReportText.RECOMMEND_STABLE)
|
||||
@@ -835,9 +864,9 @@ class ReportService:
|
||||
AuditService(self.db).log(
|
||||
AuditLogCreate(
|
||||
actor=actor,
|
||||
source="reports",
|
||||
source=AuditSource.REPORTS,
|
||||
action=f"generate_{report_type}_report",
|
||||
target_type="work-reports",
|
||||
target_type=AuditTargetType.WORK_REPORTS,
|
||||
target_id=str(record.id),
|
||||
response_payload=record_data,
|
||||
)
|
||||
@@ -871,17 +900,31 @@ class ReportService:
|
||||
WorkTask.due_date >= start,
|
||||
WorkTask.due_date <= end,
|
||||
]
|
||||
procurement_filters = [Procurement.approval_status.in_(PENDING_APPROVAL_STATUSES)]
|
||||
expense_filters = [Expense.approval_status.in_(PENDING_APPROVAL_STATUSES)]
|
||||
start_at = datetime.combine(start, datetime.min.time())
|
||||
end_at = datetime.combine(end, datetime.max.time())
|
||||
project_filters = []
|
||||
risk_filters = [RiskEvent.status == StatusValue.OPEN]
|
||||
procurement_filters = [
|
||||
Procurement.approval_status.in_(PENDING_APPROVAL_STATUSES),
|
||||
Procurement.created_at >= start_at,
|
||||
Procurement.created_at <= end_at,
|
||||
]
|
||||
expense_filters = [
|
||||
Expense.approval_status.in_(PENDING_APPROVAL_STATUSES),
|
||||
Expense.created_at >= start_at,
|
||||
Expense.created_at <= end_at,
|
||||
]
|
||||
attendance_filters = [
|
||||
AttendanceRecord.work_date >= start,
|
||||
AttendanceRecord.work_date <= end,
|
||||
]
|
||||
if project_code:
|
||||
project_filters.append(Project.code == project_code)
|
||||
task_filters.append(WorkTask.project_code == project_code)
|
||||
procurement_filters.append(Procurement.project_code == project_code)
|
||||
expense_filters.append(Expense.project_code == project_code)
|
||||
attendance_filters.append(AttendanceRecord.project_code == project_code)
|
||||
risk_filters.append(RiskEvent.project_code == project_code)
|
||||
if department:
|
||||
expense_filters.append(Expense.department == department)
|
||||
attendance_filters.append(AttendanceRecord.department == department)
|
||||
@@ -894,10 +937,11 @@ class ReportService:
|
||||
*task_filters,
|
||||
)
|
||||
return {
|
||||
"projects_total": self._count(Project),
|
||||
"projects_total": self._count(Project, *project_filters),
|
||||
"active_projects": self._count(
|
||||
Project,
|
||||
Project.status.notin_(PROJECT_CLOSED_STATUSES),
|
||||
*project_filters,
|
||||
),
|
||||
"tasks_total": self._count(WorkTask, *task_filters),
|
||||
"tasks_completed": completed_tasks,
|
||||
@@ -905,10 +949,7 @@ class ReportService:
|
||||
"procurements_pending": self._count(Procurement, *procurement_filters),
|
||||
"expenses_pending": self._count(Expense, *expense_filters),
|
||||
"attendance_total": self._count(AttendanceRecord, *attendance_filters),
|
||||
"open_risk_events": self._count(
|
||||
RiskEvent,
|
||||
RiskEvent.status == StatusValue.OPEN,
|
||||
),
|
||||
"open_risk_events": self._count(RiskEvent, *risk_filters),
|
||||
}
|
||||
|
||||
def _work_report_lines(
|
||||
|
||||
Reference in New Issue
Block a user