diff --git a/.flocks/flockshub/index.json b/.flocks/flockshub/index.json index 78c527a33..ef33f5ca4 100644 --- a/.flocks/flockshub/index.json +++ b/.flocks/flockshub/index.json @@ -14689,7 +14689,7 @@ "name": "SOC Workspace WebUI", "description": "SOC workspace pages for posture, overview, and alert investigation.", "descriptionCn": "SOC 工作区页面,包含态势、SOC 总览和告警调查。", - "version": "1.1.12.1", + "version": "1.1.13", "category": "workflow-automation", "tags": [ "siem", @@ -14711,7 +14711,7 @@ "name": "Flocks SOC Workspace Query", "description": "Query information from Flocks own SOC workspace pages, including dashboard, overview, alert lists, alert details, triage reports, and workflow status.", "descriptionCn": "查询 Flocks 自身 SOC 工作区里的信息,包括 dashboard、overview、告警调查列表、告警详情、研判报告和工作流状态。", - "version": "1.1.9.1", + "version": "1.2.0", "category": "integration", "tags": [ "siem", @@ -14757,7 +14757,7 @@ "nameCn": "HTTP研判工作流", "description": "Downstream alert triage workflow that writes triage results to SOC DB by default with optional JSONL output.", "descriptionCn": "下游告警研判工作流,默认写入 SOC DB,并保留 JSONL 输出配置。", - "version": "1.1.2.1", + "version": "1.2.0", "category": "workflow-automation", "tags": [ "siem", @@ -14780,7 +14780,7 @@ "nameCn": "告警运营套件", "description": "Installer for Flocks alert operations: pages, tools, denoise workflow, and triage workflow.", "descriptionCn": "Flocks 告警运营套件安装器:包含页面、工具、降噪工作流和研判工作流。", - "version": "1.0.2", + "version": "1.0.3", "category": "workflow-automation", "tags": [ "siem", diff --git a/.flocks/flockshub/plugins/components/soc-workspace/manifest.json b/.flocks/flockshub/plugins/components/soc-workspace/manifest.json index 58424f691..7190d97a9 100644 --- a/.flocks/flockshub/plugins/components/soc-workspace/manifest.json +++ b/.flocks/flockshub/plugins/components/soc-workspace/manifest.json @@ -6,7 +6,7 @@ "nameCn": "告警运营套件", "description": "Installer for Flocks alert operations: pages, tools, denoise workflow, and triage workflow.", "descriptionCn": "Flocks 告警运营套件安装器:包含页面、工具、降噪工作流和研判工作流。", - "version": "1.0.2", + "version": "1.0.3", "author": "Flocks Team", "license": "MIT", "homepage": "", diff --git a/.flocks/flockshub/plugins/tools/python/soc_workspace_query/manifest.json b/.flocks/flockshub/plugins/tools/python/soc_workspace_query/manifest.json index 45736ae1b..fb45093b1 100644 --- a/.flocks/flockshub/plugins/tools/python/soc_workspace_query/manifest.json +++ b/.flocks/flockshub/plugins/tools/python/soc_workspace_query/manifest.json @@ -5,7 +5,7 @@ "name": "Flocks SOC Workspace Query", "description": "Query information from Flocks own SOC workspace pages, including dashboard, overview, alert lists, alert details, triage reports, and workflow status.", "descriptionCn": "查询 Flocks 自身 SOC 工作区里的信息,包括 dashboard、overview、告警调查列表、告警详情、研判报告和工作流状态。", - "version": "1.1.9.1", + "version": "1.2.0", "author": "Flocks Team", "license": "MIT", "homepage": "", diff --git a/.flocks/flockshub/plugins/tools/python/soc_workspace_query/soc_workspace_query.py b/.flocks/flockshub/plugins/tools/python/soc_workspace_query/soc_workspace_query.py index 402e2e3c1..c7edd3537 100644 --- a/.flocks/flockshub/plugins/tools/python/soc_workspace_query/soc_workspace_query.py +++ b/.flocks/flockshub/plugins/tools/python/soc_workspace_query/soc_workspace_query.py @@ -1,3 +1,10 @@ +"""Query tool over Flocks' own SOC workspace. + +flocks-soc-store-client: this file holds no database code. Alerts and workflow +runs come from the platform's SOC data service (``flocks.workflow.soc_store``, +the one of the database backend in use), so the same file serves every backend. +""" + from __future__ import annotations import asyncio @@ -5,12 +12,11 @@ import inspect import json import re -import sqlite3 import sys import threading -from collections import Counter from datetime import datetime, time as dt_time from pathlib import Path +from types import SimpleNamespace from typing import Any, Optional from zoneinfo import ZoneInfo @@ -24,54 +30,57 @@ ) -SOC_DB = Path.home() / ".flocks" / "data" / "soc.db" -WORKFLOW_DB = Path.home() / ".flocks" / "data" / "workflow.db" -SOC_UI_ROOT = Path.home() / ".flocks" / "plugins" / "contracts" / "webui" / "soc_ui" +# Where the SOC pages are installed; None for the installation's own. +SOC_UI_ROOT: Optional[Path] = None SOC_TZ = ZoneInfo("Asia/Shanghai") -# The triage workflow stores its verdict in triage_attack_verdict / -# triage_attack_success; the SOC overview and alert pages read those first. -# Older records only carry the NDR fields (attach_result, threat_result, -# attack_verdict). triage_status is the triage run's own status ("ok"), not a -# verdict about the attack. -_TRIAGE_VERDICT_SQL = "lower(trim(CAST(json_extract(record_json, '$.triage_attack_verdict') AS TEXT)))" -_TRIAGE_SUCCESS_SQL = "lower(trim(CAST(json_extract(record_json, '$.triage_attack_success') AS TEXT)))" -ATTACK_VERDICT_SQL = ( - f"CASE WHEN COALESCE({_TRIAGE_VERDICT_SQL}, '') <> '' THEN " - f"CASE WHEN {_TRIAGE_VERDICT_SQL} IN ('attack', 'attack_success', 'attack_failed') THEN 'attack' " - f"WHEN {_TRIAGE_VERDICT_SQL} IN ('non_attack', 'benign') THEN 'non_attack' ELSE 'unknown' END " - "ELSE json_extract(record_json, '$.attack_verdict') END" -) -ATTACK_RESULT_SQL = ( - f"CASE WHEN COALESCE({_TRIAGE_VERDICT_SQL}, '') <> '' THEN " - f"CASE WHEN {_TRIAGE_VERDICT_SQL} NOT IN ('attack', 'attack_success', 'attack_failed') THEN 'unknown' " - f"WHEN {_TRIAGE_SUCCESS_SQL} IN ('success', 'failed', 'unknown') THEN {_TRIAGE_SUCCESS_SQL} " - f"WHEN {_TRIAGE_VERDICT_SQL} = 'attack_success' THEN 'success' " - f"WHEN {_TRIAGE_VERDICT_SQL} = 'attack_failed' THEN 'failed' " - f"WHEN {_TRIAGE_SUCCESS_SQL} IN ('1', 'true') THEN 'success' ELSE 'unknown' END " - "ELSE COALESCE(json_extract(record_json, '$.attach_result'), json_extract(record_json, '$.threat_result'), " - "json_extract(record_json, '$.attack_verdict')) END" +# The fields an alert search can match exactly. +ALERT_FILTER_FIELDS = ( + "row_id", + "record_id", + "source_type", + "threat_name", + "threat_type", + "threat_phase", + "attack_result", + "attack_verdict", + "direction", + "sip", + "dip", + "sport", + "dport", + "req_host", + "req_http_url", + "rsp_status_code", + "threat_rule_id", ) -ALERT_FIELDS = { - "row_id": "row_id", - "record_id": "record_id", - "source_type": "COALESCE(source_type, json_extract(record_json, '$._source_type'), json_extract(record_json, '$.source_type'))", - "threat_name": "COALESCE(threat_name, json_extract(record_json, '$.threat_name'))", - "threat_type": "json_extract(record_json, '$.threat_type')", - "threat_phase": "json_extract(record_json, '$.threat_phase')", - "attack_result": ATTACK_RESULT_SQL, - "attack_verdict": ATTACK_VERDICT_SQL, - "direction": "json_extract(record_json, '$.direction')", - "sip": "json_extract(record_json, '$.sip')", - "dip": "json_extract(record_json, '$.dip')", - "sport": "json_extract(record_json, '$.sport')", - "dport": "json_extract(record_json, '$.dport')", - "req_host": "json_extract(record_json, '$.req_host')", - "req_http_url": "json_extract(record_json, '$.req_http_url')", - "rsp_status_code": "json_extract(record_json, '$.rsp_status_code')", - "threat_rule_id": "json_extract(record_json, '$.threat_rule_id')", -} + +def _soc_store() -> Any: + """The platform's SOC data service.""" + try: + from flocks.workflow import soc_store + except ImportError as exc: + raise RuntimeError( + "soc_workspace_query needs the SOC data service of the platform; update Flocks to a version that has it" + ) from exc + return soc_store + + +def _alert_store() -> Any: + _soc_store() + from flocks.workflow.soc_store import alerts + + return alerts + + +def _soc_ui_root() -> Path: + if SOC_UI_ROOT is not None: + return Path(SOC_UI_ROOT) + from flocks.contracts.webui.store import get_webui_pages_root + + return get_webui_pages_root() / "soc_ui" + PAGE_VALUES = ["all", "dashboard", "overview", "alerts", "alert_detail", "workflow", "schema"] @@ -155,18 +164,18 @@ def _parameters() -> list[ToolParameter]: "Query information rendered by Flocks' own SOC workspace pages: dashboard, overview, " "alert investigation list, alert detail/triage report, and workflow status. This tool " "is for inspecting the local Flocks SOC workspace itself, not for querying an external " - "SOC product. It reads only local Flocks databases: ~/.flocks/data/soc.db and " - "~/.flocks/data/workflow.db." + "SOC product. It reads only this Flocks installation's own alert store and " + "workflow records." ), description_cn=( "查询 Flocks 自身 SOC 工作区页面信息,包括 dashboard、overview、告警调查列表、" "单条告警详情、研判报告和工作流状态。这个工具用于查看本机 Flocks 自身的 SOC " - "工作区数据,不是查询外部 SOC 系统;只读取 ~/.flocks/data/soc.db 和 " - "~/.flocks/data/workflow.db。" + "工作区数据,不是查询外部 SOC 系统;只读取本机 Flocks 自己的告警库和" + "工作流执行记录。" ), category=ToolCategory.CUSTOM, parameters=_parameters(), - tags=["soc", "flocks", "workspace", "dashboard", "overview", "alerts", "sqlite"], + tags=["soc", "flocks", "workspace", "dashboard", "overview", "alerts"], ) async def soc_workspace_query( ctx: ToolContext, @@ -188,7 +197,7 @@ async def soc_workspace_query( safe_order = "asc" if str(order).lower() == "asc" else "desc" try: - # Off the event loop: the pages read SQLite and scan alert records. + # Off the event loop: the pages read the alert store and scan its records. output = await asyncio.to_thread( _query_page, page=page, @@ -199,6 +208,8 @@ async def soc_workspace_query( include_raw=bool(include_raw), include_reports=bool(include_reports), ) + # Asked on the worker thread too: a store may be a database that is not read on the event loop. + source = await asyncio.to_thread(_source_info) except Exception as exc: return ToolResult( success=False, @@ -213,8 +224,8 @@ async def soc_workspace_query( metadata={ "session_id": ctx.session_id, "page": page, - "soc_db": _display_path(SOC_DB), - "workflow_db": _display_path(WORKFLOW_DB), + "soc_db": source["socDb"], + "workflow_db": source["workflowDb"], }, ) @@ -260,12 +271,12 @@ def _schema() -> dict[str, Any]: "generatedAt": _now(), "source": _source_info(), "pages": PAGE_VALUES, - "alertFilterFields": sorted(ALERT_FIELDS), + "alertFilterFields": sorted(ALERT_FILTER_FIELDS), "alertRecordFields": _record_field_sample(), "notes": [ "dashboard and overview reuse the installed SOC WebUI API handlers.", - "alerts and alert_detail read alert_records from ~/.flocks/data/soc.db.", - "workflow reads workflow_stats and workflow_executions from ~/.flocks/data/workflow.db.", + "alerts and alert_detail read the alert store of this Flocks installation.", + "workflow reads the workflow statistics and executions of this Flocks installation.", ], } @@ -280,7 +291,7 @@ def _page_module(page_dir_name: str) -> Any: Loading them again for every query would also start their caches and schema checks over. """ - handler_path = SOC_UI_ROOT / page_dir_name / "api" / "handlers.py" + handler_path = _soc_ui_root() / page_dir_name / "api" / "handlers.py" if not handler_path.is_file(): raise FileNotFoundError(f"SOC page handler not found: {handler_path}") version = handler_path.stat().st_mtime_ns @@ -299,10 +310,20 @@ def _page_module(page_dir_name: str) -> Any: return module +def _page_context() -> Any: + """What the page runtime hands a page's handlers, as far as the SOC pages use it. + + ``database`` is there for the pages of an earlier suite, which read through it. + """ + from flocks.coordination import page_api_database + + return SimpleNamespace(services=SimpleNamespace(soc=_soc_store().page_service()), database=page_api_database()) + + def _page_stats(page_dir_name: str, filters: dict[str, Any]) -> dict[str, Any]: - stats = _page_module(page_dir_name).get_stats(None, _Request(_page_query_params(filters))) + stats = _page_module(page_dir_name).get_stats(_page_context(), _Request(_page_query_params(filters))) if inspect.isawaitable(stats): - # The dashboard's handler is a coroutine function. Pages are queried + # A page's handler may be a coroutine function. Pages are queried # on a worker thread (soc_workspace_query), which has no loop of its own. stats = asyncio.run(stats) return stats @@ -355,31 +376,15 @@ def _query_alerts( include_raw: bool, include_reports: bool, ) -> dict[str, Any]: - _require_db(SOC_DB, "SOC alert database") - where, params, applied = _alert_where(filters) - order_sql = "ASC" if order == "asc" else "DESC" - query = f""" - SELECT row_id, record_id, asset_date, source_file, line_number, event_time, - source_type, threat_name, is_duplicate, record_json - FROM alert_records - WHERE {where} - ORDER BY event_time {order_sql}, row_id {order_sql} - LIMIT ? OFFSET ? - """ - count_query = f"SELECT COUNT(*) FROM alert_records WHERE {where}" - - with sqlite3.connect(SOC_DB) as conn: - conn.row_factory = sqlite3.Row - total = int(conn.execute(count_query, params).fetchone()[0]) - rows = conn.execute(query, [*params, limit, offset]).fetchall() - - items = [_normalize_alert_row(row, include_raw, include_reports) for row in rows] + criteria, applied = _alert_criteria(filters) + found = _alert_store().search(criteria, limit=limit, offset=offset, order=order) + items = [_normalize_alert_row(row, include_raw, include_reports) for row in found["rows"]] return { "page": "alerts", "generatedAt": _now(), "source": _source_info(), "summary": { - "total": total, + "total": found["total"], "limit": limit, "offset": offset, "returned": len(items), @@ -387,7 +392,7 @@ def _query_alerts( "latestDate": _latest_asset_date(), }, "filtersApplied": applied, - "facets": _alert_facets(where, params), + "facets": found["facets"], "items": items, } @@ -429,54 +434,11 @@ def _query_alert_detail(filters: dict[str, Any], include_raw: bool, include_repo def _query_workflow(filters: dict[str, Any], limit: int) -> dict[str, Any]: - _require_db(WORKFLOW_DB, "workflow database") workflow_id = _clean(filters.get("workflow_id") or "") limit = max(1, min(limit, 100)) - stats_params: list[Any] = [] - stats_where = "" - if workflow_id: - stats_where = "WHERE workflow_id = ?" - stats_params.append(workflow_id) - - exec_where = [] - exec_params: list[Any] = [] - if workflow_id: - exec_where.append("workflow_id = ?") - exec_params.append(workflow_id) start_ms, end_ms = _workflow_time_range(filters) - if start_ms is not None: - exec_where.append("started_at >= ?") - exec_params.append(start_ms) - if end_ms is not None: - exec_where.append("started_at <= ?") - exec_params.append(end_ms) - exec_where_sql = " AND ".join(exec_where) if exec_where else "1=1" - - with sqlite3.connect(WORKFLOW_DB) as conn: - conn.row_factory = sqlite3.Row - stats_rows = conn.execute( - f""" - SELECT workflow_id, call_count, success_count, error_count, total_runtime, - avg_runtime, thumbs_up, thumbs_down, updated_at - FROM workflow_stats - {stats_where} - ORDER BY updated_at DESC - """, - stats_params, - ).fetchall() - execution_rows = conn.execute( - f""" - SELECT id, workflow_id, status, current_phase, current_node_id, - current_node_type, current_step_index, step_count, - error_message, trigger_id, trigger_type, started_at, - finished_at, duration, updated_at - FROM workflow_executions - WHERE {exec_where_sql} - ORDER BY started_at DESC - LIMIT ? - """, - [*exec_params, limit], - ).fetchall() + runs = _alert_store().workflow_runs(workflow_id, start_ms=start_ms, end_ms=end_ms, limit=limit) + stats_rows, execution_rows = runs["stats"], runs["executions"] return { "page": "workflow", @@ -492,13 +454,12 @@ def _query_workflow(filters: dict[str, Any], limit: int) -> dict[str, Any]: } -def _alert_where(filters: dict[str, Any]) -> tuple[str, list[Any], list[dict[str, Any]]]: - clauses = [] - params: list[Any] = [] +def _alert_criteria(filters: dict[str, Any]) -> tuple[dict[str, Any], list[dict[str, Any]]]: + """What an alert search matches (for the data service), and the filters applied (for the answer).""" + criteria: dict[str, Any] = {"include_duplicates": _truthy(filters.get("include_duplicates"))} applied: list[dict[str, Any]] = [] - if not _truthy(filters.get("include_duplicates")): - clauses.append("is_duplicate = 0") + if not criteria["include_duplicates"]: applied.append({"field": "include_duplicates", "value": False}) date_value = filters.get("date") @@ -507,90 +468,46 @@ def _alert_where(filters: dict[str, Any]) -> tuple[str, list[Any], list[dict[str if date_value and not start_date and not end_date: start_date = end_date = date_value if start_date: - clauses.append("asset_date >= ?") - params.append(str(start_date)) + criteria["start_date"] = str(start_date) applied.append({"field": "startDate", "value": str(start_date)}) if end_date: - clauses.append("asset_date <= ?") - params.append(str(end_date)) + criteria["end_date"] = str(end_date) applied.append({"field": "endDate", "value": str(end_date)}) start_time = _required_epoch_seconds("startTime", filters.get("startTime", filters.get("start_time"))) end_time = _required_epoch_seconds("endTime", filters.get("endTime", filters.get("end_time"))) if start_time is not None: - clauses.append("event_time >= ?") - params.append(start_time) + criteria["start_time"] = start_time applied.append({"field": "startTime", "value": start_time}) if end_time is not None: - clauses.append("event_time <= ?") - params.append(end_time) + criteria["end_time"] = end_time applied.append({"field": "endTime", "value": end_time}) keyword = _clean(filters.get("keyword")) if keyword: - clauses.append("(record_json LIKE ? OR threat_name LIKE ? OR record_id LIKE ? OR row_id LIKE ?)") - like = f"%{keyword}%" - params.extend([like, like, like, like]) + criteria["keyword"] = keyword applied.append({"field": "keyword", "value": keyword}) - for key, expression in ALERT_FIELDS.items(): - if key in {"row_id", "record_id"}: - value = filters.get(key) - else: - value = filters.get(key) + fields: dict[str, Any] = {} + for key in ALERT_FILTER_FIELDS: + value = filters.get(key) if value in (None, "", []): continue - # Compared as text: a JSON number (dport 443) comes back from - # json_extract as an integer and would never equal the text "443". - compared = expression if key in {"row_id", "record_id"} else f"CAST(({expression}) AS TEXT)" if isinstance(value, (list, tuple, set)): cleaned = [_clean(item) for item in value if _clean(item)] if not cleaned: continue - placeholders = ", ".join("?" for _ in cleaned) - clauses.append(f"{compared} IN ({placeholders})") - params.extend(cleaned) + fields[key] = cleaned applied.append({"field": key, "value": cleaned}) else: - clauses.append(f"{compared} = ?") - params.append(_clean(value)) + fields[key] = _clean(value) applied.append({"field": key, "value": _clean(value)}) + criteria["fields"] = fields - return " AND ".join(clauses) if clauses else "1=1", params, applied + return criteria, applied -def _alert_facets(where: str, params: list[Any]) -> dict[str, list[dict[str, Any]]]: - facets: dict[str, list[dict[str, Any]]] = {} - facet_fields = { - "source_type": "COALESCE(source_type, json_extract(record_json, '$._source_type'), json_extract(record_json, '$.source_type'))", - "threat_name": "COALESCE(threat_name, json_extract(record_json, '$.threat_name'))", - "threat_type": "json_extract(record_json, '$.threat_type')", - "threat_phase": "json_extract(record_json, '$.threat_phase')", - "attack_result": ATTACK_RESULT_SQL, - "direction": "json_extract(record_json, '$.direction')", - } - with sqlite3.connect(SOC_DB) as conn: - for key, expression in facet_fields.items(): - rows = conn.execute( - f""" - SELECT {expression} AS value, COUNT(*) AS count - FROM alert_records - WHERE {where} - GROUP BY value - ORDER BY count DESC - LIMIT 20 - """, - params, - ).fetchall() - facets[key] = [ - {"value": _clean(value) or "unknown", "count": int(count or 0)} - for value, count in rows - if value not in (None, "") - ] - return facets - - -def _normalize_alert_row(row: sqlite3.Row, include_raw: bool, include_reports: bool) -> dict[str, Any]: +def _normalize_alert_row(row: Any, include_raw: bool, include_reports: bool) -> dict[str, Any]: record = _loads(row["record_json"]) # event_time is stored in seconds; the raw "time" may be milliseconds. event_time = _epoch_seconds(_safe_int(row["event_time"])) or _epoch_seconds(_safe_int(record.get("time"))) @@ -646,7 +563,7 @@ def _normalize_alert_row(row: sqlite3.Row, include_raw: bool, include_reports: b return normalized -def _normalize_workflow_stat(row: sqlite3.Row) -> dict[str, Any]: +def _normalize_workflow_stat(row: Any) -> dict[str, Any]: updated_at = _safe_int(row["updated_at"]) return { "workflowId": row["workflow_id"], @@ -662,7 +579,7 @@ def _normalize_workflow_stat(row: sqlite3.Row) -> dict[str, Any]: } -def _normalize_workflow_execution(row: sqlite3.Row) -> dict[str, Any]: +def _normalize_workflow_execution(row: Any) -> dict[str, Any]: started_at = _safe_int(row["started_at"]) finished_at = _safe_int(row["finished_at"]) return { @@ -687,37 +604,22 @@ def _normalize_workflow_execution(row: sqlite3.Row) -> dict[str, Any]: def _record_field_sample() -> list[str]: - if not SOC_DB.is_file(): - return [] - try: - with sqlite3.connect(SOC_DB) as conn: - row = conn.execute("SELECT record_json FROM alert_records LIMIT 1").fetchone() - if not row: - return [] - value = _loads(row[0]) - return sorted(str(key) for key in value.keys()) - except Exception: - return [] + return _alert_store().record_fields() def _latest_asset_date() -> str: - if not SOC_DB.is_file(): - return "" - try: - with sqlite3.connect(SOC_DB) as conn: - row = conn.execute("SELECT MAX(asset_date) FROM alert_records").fetchone() - return str(row[0] or "") - except Exception: - return "" + return _alert_store().latest_date() def _source_info() -> dict[str, Any]: + info = _alert_store().source_info() return { "type": "flocks-local-soc-workspace", - "socDb": _display_path(SOC_DB), - "socDbExists": SOC_DB.is_file(), - "workflowDb": _display_path(WORKFLOW_DB), - "workflowDbExists": WORKFLOW_DB.is_file(), + "dataSource": info["dataSource"], + "socDb": _display_path(info["socDb"]), + "socDbExists": info["socDbExists"], + "workflowDb": _display_path(info["workflowDb"]), + "workflowDbExists": info["workflowDbExists"], "jsonlEnabled": False, "externalSoc": False, } @@ -884,13 +786,8 @@ def _now() -> str: return datetime.now(SOC_TZ).isoformat(timespec="seconds") -def _display_path(path: Path) -> str: +def _display_path(path: Any) -> str: try: - return str(path.expanduser()) + return str(Path(path).expanduser()) except Exception: return str(path) - - -def _require_db(path: Path, label: str) -> None: - if not path.is_file(): - raise FileNotFoundError(f"{label} does not exist: {path}") diff --git a/.flocks/flockshub/plugins/webuis/soc_ui/access/soc_alerts_operations.py b/.flocks/flockshub/plugins/webuis/soc_ui/access/soc_alerts_operations.py index bc23f4beb..b9eb79425 100644 --- a/.flocks/flockshub/plugins/webuis/soc_ui/access/soc_alerts_operations.py +++ b/.flocks/flockshub/plugins/webuis/soc_ui/access/soc_alerts_operations.py @@ -1,4 +1,10 @@ -"""SOC alert investigation WebUI access contract.""" +"""SOC alert investigation WebUI access contract. + +flocks-soc-store-client: this file holds no database code. The contract names +the platform's SOC alert store as its source (the ``builtin-soc-alerts`` +adapter kind), which ``flocks.contracts.access.driver`` reads from whatever the +database backend in use keeps it in, so the same file serves every backend. +""" from __future__ import annotations @@ -26,12 +32,9 @@ CONTRACT_ID = "soc.alerts.operations" CONTRACT_VERSION = "1.0" SOURCE_PAGE_ID = "soc-alerts" -DEFAULT_SQLITE_DB = Path.home() / ".flocks" / "data" / "soc.db" -DEFAULT_SQLITE_TABLE = "alert_records" -DEFAULT_SQLITE_RECORD_COLUMN = "record_json" -DEFAULT_SQLITE_DATE_COLUMN = "asset_date" -DEFAULT_SQLITE_EVENT_TIME_COLUMN = "event_time" -SQL_IDENTIFIER_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$") +# The SOC suite's alert store, wherever the platform's database backend keeps it. +SOC_ALERTS_ADAPTER_KIND = "builtin-soc-alerts" +SOC_ALERTS_SOURCE = Path("soc-alerts") DISPLAY_FIELDS = ( "id", @@ -78,7 +81,7 @@ "is_duplicate", "_syslog_meta", ) -DRIVER_FIELDS = frozenset((*DISPLAY_FIELDS, "triage_attack_verdict", "triage_attack_success")) +DRIVER_FIELDS = frozenset((*DISPLAY_FIELDS, "triage_attack_verdict", "triage_attack_success", "__flocks_source_row_id")) FILTER_FIELDS = frozenset( { "_source_type", @@ -140,25 +143,23 @@ def _contract() -> Contract: class _BindingResolver: def resolve(self, *, page_id: str, slot_id: str, contract_id: str, contract_version: str) -> Binding: - settings = _sqlite_settings() - db_path = settings["db_path"] return Binding( - binding_id="soc-alerts-sqlite", + binding_id="soc-alerts-store", binding_version=1, page_id=page_id, slot_id=slot_id, contract_id=contract_id, contract_version=contract_version, - adapter_kind="builtin-sqlite-json", + adapter_kind=SOC_ALERTS_ADAPTER_KIND, source_page_id=SOURCE_PAGE_ID, - source_root=db_path, + source_root=SOC_ALERTS_SOURCE, driver_available_fields=DRIVER_FIELDS, - driver_allowlist_roots=(db_path.parent,), + driver_allowlist_roots=(), driver_options={ - "table": settings["table"], - "recordColumn": settings["record_column"], - "dateColumn": settings["date_column"], - "eventTimeColumn": settings["event_time_column"], + # The suite's settings file as it is: the driver reads the part + # meant for its store, and where a relative path in it starts. + "settings": _load_config(), + "settingsDir": str(_config_path().parent), "facetFields": sorted(FILTER_FIELDS), }, predicate_value_resolver=_filter_value, @@ -204,10 +205,10 @@ def run_query( "schemaVersion": "soc.alerts.v1", "generatedAt": datetime.now().isoformat(timespec="seconds"), "source": { - "label": "SOC Contract SQLite", + "label": f"SOC Contract {_store_label()}".strip(), "pageId": binding_source_page_id, "sampleMode": False, - "dataSource": "sqlite", + "dataSource": _store_name(), }, "summary": { "sourcePageId": binding_source_page_id, @@ -247,6 +248,7 @@ def _incident_from_row(row: InternalDataRow) -> dict[str, Any]: return { "id": record_id, "sourceRecordId": record_id, + "sourceRowId": _text(record.get("__flocks_source_row_id")), "observedAt": observed_at, "rawAlerts": 1, "priority": "P1" if verdict == "success" else "P2", @@ -319,20 +321,20 @@ def _display_value(value: Any, key: str) -> str: return str(value) -def _sqlite_settings() -> dict[str, Any]: - config = _load_config().get("sqlite", {}) - if not isinstance(config, dict): - config = {} - return { - "db_path": _resolve_config_path( - _read_config_string(os.environ.get("FLOCKS_SOC_ALERTS_SQLITE_DB"), config.get("dbPath")), - DEFAULT_SQLITE_DB, - ), - "table": _sql_identifier(config.get("table"), DEFAULT_SQLITE_TABLE), - "record_column": _sql_identifier(config.get("recordColumn"), DEFAULT_SQLITE_RECORD_COLUMN), - "date_column": _sql_identifier(config.get("dateColumn"), DEFAULT_SQLITE_DATE_COLUMN), - "event_time_column": _sql_identifier(config.get("eventTimeColumn"), DEFAULT_SQLITE_EVENT_TIME_COLUMN), - } +def _alert_store() -> Any: + try: + from flocks.workflow.soc_store import alerts + except ImportError: + return None + return alerts + + +def _store_name() -> str: + return str(getattr(_alert_store(), "DATA_SOURCE", "") or "") + + +def _store_label() -> str: + return str(getattr(_alert_store(), "DATA_SOURCE_LABEL", "") or "") def _load_config() -> dict[str, Any]: @@ -364,19 +366,6 @@ def _read_config_string(*values: Any) -> str: return "" -def _resolve_config_path(value: str, fallback: Path) -> Path: - text = _read_config_string(value, str(fallback)) - path = Path(text).expanduser() - if path.is_absolute(): - return path - return (_config_path().parent / path).resolve() - - -def _sql_identifier(value: Any, fallback: str) -> str: - text = _read_config_string(value, fallback) - return text if SQL_IDENTIFIER_RE.fullmatch(text) else fallback - - def _record_id(record: dict[str, Any]) -> str: value = _first_text(record, "id", "record_id", "dedup_key") if value: diff --git a/.flocks/flockshub/plugins/webuis/soc_ui/manifest.json b/.flocks/flockshub/plugins/webuis/soc_ui/manifest.json index 7a9e76380..1b7394d4f 100644 --- a/.flocks/flockshub/plugins/webuis/soc_ui/manifest.json +++ b/.flocks/flockshub/plugins/webuis/soc_ui/manifest.json @@ -5,7 +5,7 @@ "name": "SOC Workspace WebUI", "description": "SOC workspace pages for posture, overview, and alert investigation.", "descriptionCn": "SOC 工作区页面,包含态势、SOC 总览和告警调查。", - "version": "1.1.12.1", + "version": "1.1.13", "author": "Flocks Team", "license": "MIT", "homepage": "", diff --git a/.flocks/flockshub/plugins/webuis/soc_ui/soc_alerts/src/index.tsx b/.flocks/flockshub/plugins/webuis/soc_ui/soc_alerts/src/index.tsx index 477dc0efe..100b4e887 100644 --- a/.flocks/flockshub/plugins/webuis/soc_ui/soc_alerts/src/index.tsx +++ b/.flocks/flockshub/plugins/webuis/soc_ui/soc_alerts/src/index.tsx @@ -181,7 +181,7 @@ const MARKDOWN_STEP_ORDER = [ ]; const EMPTY_DATA: Required> = { - source: { label: 'SOC Contract SQLite', pageId: 'soc-alerts', sampleMode: false, dataSource: 'sqlite' }, + source: { label: 'SOC Contract', pageId: 'soc-alerts', sampleMode: false, dataSource: '' }, summary: { sourcePageId: 'soc-alerts', sourceAssetDate: '-', diff --git a/.flocks/flockshub/plugins/webuis/soc_ui/soc_dashboard/api/handlers.py b/.flocks/flockshub/plugins/webuis/soc_ui/soc_dashboard/api/handlers.py index c329a88d8..bb070ee7c 100644 --- a/.flocks/flockshub/plugins/webuis/soc_ui/soc_dashboard/api/handlers.py +++ b/.flocks/flockshub/plugins/webuis/soc_ui/soc_dashboard/api/handlers.py @@ -1,1312 +1,57 @@ -import asyncio -import base64 -import json -import math +"""SOC dashboard page API. + +flocks-soc-store-client: this file holds no database code. The figures come +from the platform's SOC data service (``ctx.services.soc.dashboard``, the +``flocks.workflow.soc_store`` of the database backend in use), so the same +file serves every backend. +""" + import re -import sqlite3 import time from collections import Counter, OrderedDict -from contextlib import closing -from dataclasses import dataclass -from datetime import datetime, timedelta, timezone +from datetime import datetime, timedelta from pathlib import Path -from threading import Lock, RLock +from threading import RLock DATE_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$") -DEFAULT_SQLITE_DB = Path.home() / ".flocks" / "data" / "soc.db" -DEFAULT_SQLITE_TABLE = "alert_records" -DEFAULT_SQLITE_RECORD_COLUMN = "record_json" -DEFAULT_SQLITE_DATE_COLUMN = "asset_date" -DEFAULT_SQLITE_EVENT_TIME_COLUMN = "event_time" -FACTS_TABLE = "soc_dashboard_alert_facts" -ACTIVITY_TABLE = "soc_dashboard_activity" -META_TABLE = "soc_dashboard_meta" -SCHEMA_VERSION = "4" -ACTIVITY_DEFAULT_LIMIT = 20 -ACTIVITY_MAX_LIMIT = 50 -ACTIVITY_WINDOW_MS = 3000 -ACTIVITY_NORMAL_LIMIT = 5 -ACTIVITY_SURGE_LIMIT = 100 -ACTIVITY_RETENTION_ROWS = 100_000 -ACTIVITY_PRUNE_INTERVAL = 3600.0 - -WORKFLOW_DB = Path.home() / ".flocks" / "data" / "workflow.db" -WORKFLOW_SNAPSHOT_TABLE = "soc_dashboard_workflow_stats_samples" -TASK_DB = Path.home() / ".flocks" / "data" / "tasks.db" -USAGE_DB = Path.home() / ".flocks" / "data" / "flocks.db" -SOC_PINNED_WORKFLOW_NAMES = { - "stream_alert_denoise": "告警降噪工作流", - "stream_alert_triage": "告警研判工作流", -} -TRIAGE_WORKFLOW_IDS = { - "stream_alert_triage", - "onesec_kafka_investigation", - "tdp_alert_triage", - "sec_alert_unified_ops", -} -WORKFLOW_DISPLAY_NAMES = { - **SOC_PINNED_WORKFLOW_NAMES, - "onesec_kafka_investigation": "OneSEC Kafka 告警研判工作流", - "tdp_alert_triage": "TDP 告警研判工作流", - "sec_alert_unified_ops": "统一告警运营工作流", -} -WORKFLOW_RUNNING_STATUSES = {"running", "queued", "pending"} -WORKFLOW_SUCCESS_STATUSES = {"success", "completed"} -WORKFLOW_TRIGGER_CONFIG_KINDS = { - "workflow_kafka_config", - "workflow_poller_config", - "workflow_syslog_config", -} -WORKFLOW_DEFAULT_ACTIVE_TIMEOUT_SECONDS = 7200 -WORKFLOW_MIN_ACTIVE_TIMEOUT_SECONDS = 60 -UUID_RE = re.compile( - r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$", - re.IGNORECASE, -) - -_workflow_stats_cache: OrderedDict = OrderedDict() -_CACHE_TTL: float = 30.0 -_WORKFLOW_CACHE_MAX = 64 -_denoise_detail_cache: OrderedDict = OrderedDict() -_DENOISE_DETAIL_CACHE_TTL = 300.0 -_DENOISE_DETAIL_CACHE_MAX = 64 -_stats_response_cache: OrderedDict = OrderedDict() -_STATS_RESPONSE_CACHE_TTL = 300.0 -_STATS_RESPONSE_CACHE_MAX = 32 -_token_usage_cache = {"updatedAt": 0.0, "mtimeNs": 0, "value": None} -_TOKEN_USAGE_CACHE_TTL = 30.0 -_cache_lock = RLock() -_workflow_activity_read_lock = Lock() -_schema_lock = RLock() -_schema_ready: set = set() -_activity_pruned_at: float = 0 - - -@dataclass(frozen=True) -class _RecordSource: - path: Path - role: str - date: str - data_source: str - record_count: int = 0 - start_time: int = 0 - end_time: int = 0 - - -_FACT_COLUMNS = ( - "alert_row_id", - "row_key", - "asset_date", - "event_time", - "source_type", - "threat_name", - "threat_type", - "is_duplicate", - "phase", - "direction", - "result", - "protocol", - "severity", - "response_code", - "port", - "has_triage", - "triage_persisted_at", - "triage_status", - "triage_source", - "triage_attack_verdict", - "risk_level", - "triage_ms", - "triage_attack_success", -) -# How a fact column an older layout lacks is added; any other is TEXT. A facts -# table of an older schema version is brought up to date in place and -# recomputed from alert_records rather than dropped and made again. -_FACT_COLUMN_DEFINITIONS = { - "row_key": "TEXT NOT NULL DEFAULT ''", - "asset_date": "TEXT NOT NULL DEFAULT ''", - "event_time": "INTEGER", - "is_duplicate": "INTEGER NOT NULL DEFAULT 0", - "has_triage": "INTEGER NOT NULL DEFAULT 0", - "triage_ms": "INTEGER NOT NULL DEFAULT 0", - "triage_attack_success": "TEXT NOT NULL DEFAULT 'unknown'", -} - - -def _json_value(prefix, path): - return ( - f"CASE WHEN json_valid({prefix}.record_json) " - f"THEN json_extract({prefix}.record_json, '$.{path}') END" - ) - - -def _fact_expressions(prefix): - source_type = _json_value(prefix, "_source_type") - source_type_fallback = _json_value(prefix, "source_type") - threat_name = _json_value(prefix, "threat_name") - threat_type = _json_value(prefix, "_threat_type") - threat_type_fallback = _json_value(prefix, "threat_type") - phase = _json_value(prefix, "threat_phase") - attack_phase = _json_value(prefix, "attack_phase") - kill_chain = _json_value(prefix, "kill_chain_phase") - direction = _json_value(prefix, "direction") - traffic_direction = _json_value(prefix, "traffic_direction") - raw_result = _json_value(prefix, "threat_result") - raw_verdict = _json_value(prefix, "attack_verdict") - triage_attack_verdict = _json_value(prefix, "triage_attack_verdict") - triage_attack_success = _json_value(prefix, "triage_attack_success") - normalized_triage_verdict = ( - f"CASE WHEN LOWER(COALESCE({triage_attack_verdict}, '')) " - "IN ('attack', 'non_attack', 'unknown') " - f"THEN LOWER({triage_attack_verdict}) " - f"WHEN LOWER(COALESCE({triage_attack_verdict}, '')) " - "IN ('attack_success', 'attack_failed') THEN 'attack' " - f"WHEN LOWER(COALESCE({triage_attack_verdict}, '')) = 'benign' " - "THEN 'non_attack' ELSE 'unknown' END" - ) - normalized_triage_success = ( - f"CASE WHEN {normalized_triage_verdict} != 'attack' THEN 'unknown' " - f"WHEN LOWER(COALESCE({triage_attack_success}, '')) " - "IN ('success', 'failed', 'unknown') " - f"THEN LOWER({triage_attack_success}) " - f"WHEN LOWER(COALESCE({triage_attack_verdict}, '')) = 'attack_success' " - "THEN 'success' " - f"WHEN LOWER(COALESCE({triage_attack_verdict}, '')) = 'attack_failed' " - "THEN 'failed' " - f"WHEN LOWER(COALESCE({triage_attack_success}, '')) IN ('1', 'true') " - "THEN 'success' ELSE 'unknown' END" - ) - protocol = _json_value(prefix, "net_type") - app_protocol = _json_value(prefix, "net_app_proto") - protocol_fallback = _json_value(prefix, "protocol") - severity = _json_value(prefix, "threat_severity") - risk_level = _json_value(prefix, "risk_level") - response = _json_value(prefix, "rsp_status_code") - status_code = _json_value(prefix, "status_code") - destination_port = _json_value(prefix, "dport") - destination_port_fallback = _json_value(prefix, "dst_port") - destination_port_legacy = _json_value(prefix, "destination_port") - triage_persisted_at = _json_value(prefix, "_triage_persisted_at") - triage_status = _json_value(prefix, "triage_status") - triage_source = _json_value(prefix, "triage_source") - triage_report = _json_value(prefix, "triage_report") - triage_ms = _json_value(prefix, "triage_ms") - has_triage = ( - "CASE WHEN " - f"NULLIF({triage_status}, '') IS NOT NULL " - f"OR NULLIF({triage_persisted_at}, '') IS NOT NULL " - f"OR {triage_report} IS NOT NULL THEN 1 ELSE 0 END" - ) - return ( - f"{prefix}.rowid", - f"COALESCE(NULLIF({prefix}.row_id, ''), CAST({prefix}.rowid AS TEXT))", - f"{prefix}.asset_date", - f"{prefix}.event_time", - f"COALESCE(NULLIF({prefix}.source_type, ''), NULLIF({source_type}, ''), " - f"NULLIF({source_type_fallback}, ''), 'unknown')", - f"COALESCE(NULLIF({prefix}.threat_name, ''), NULLIF({threat_name}, ''), 'unknown')", - f"COALESCE(NULLIF({threat_type}, ''), NULLIF({threat_type_fallback}, ''), 'unknown')", - f"COALESCE({prefix}.is_duplicate, 0)", - f"COALESCE(NULLIF({phase}, ''), NULLIF({attack_phase}, ''), NULLIF({kill_chain}, ''), 'unknown')", - f"COALESCE(NULLIF({direction}, ''), NULLIF({traffic_direction}, ''), 'unknown')", - f"CASE WHEN {has_triage} = 1 " - f"THEN {normalized_triage_success} " - f"ELSE COALESCE(NULLIF({raw_result}, ''), NULLIF({raw_verdict}, ''), 'unknown') END", - f"COALESCE(NULLIF({protocol}, ''), NULLIF({app_protocol}, ''), " - f"NULLIF({protocol_fallback}, ''), 'unknown')", - f"COALESCE(NULLIF({severity}, ''), 'unknown')", - f"COALESCE(NULLIF({response}, ''), NULLIF({status_code}, ''), 'unknown')", - f"COALESCE(NULLIF({destination_port}, ''), NULLIF({destination_port_fallback}, ''), " - f"NULLIF({destination_port_legacy}, ''), 'unknown')", - has_triage, - f"COALESCE({triage_persisted_at}, '')", - f"COALESCE({triage_status}, '')", - f"COALESCE({triage_source}, '')", - normalized_triage_verdict, - f"COALESCE(NULLIF({risk_level}, ''), 'unknown')", - f"COALESCE(CAST({triage_ms} AS INTEGER), 0)", - normalized_triage_success, - ) - - -def _fact_upsert_sql(prefix): - columns = ", ".join(_FACT_COLUMNS) - values = ", ".join(_fact_expressions(prefix)) - return f"INSERT OR REPLACE INTO {FACTS_TABLE} ({columns}) VALUES ({values})" - - -def _fact_backfill_sql(): - columns = ", ".join(_FACT_COLUMNS) - values = ", ".join(_fact_expressions("source")) - return ( - f"INSERT OR REPLACE INTO {FACTS_TABLE} ({columns}) " - f"SELECT {values} FROM {DEFAULT_SQLITE_TABLE} AS source" - ) +# The platform's SOC dashboard data service, bound by each request. +_store = None -def _triage_marker(prefix): - status_value = _json_value(prefix, "triage_status") - persisted_value = _json_value(prefix, "_triage_persisted_at") - report_value = _json_value(prefix, "triage_report") - return ( - f"(NULLIF({status_value}, '') IS NOT NULL " - f"OR NULLIF({persisted_value}, '') IS NOT NULL " - f"OR {report_value} IS NOT NULL)" - ) - - -def _column_exists(conn, table_name, column_name): - return any( - str(row[1]) == column_name - for row in conn.execute(f"PRAGMA table_info({table_name})").fetchall() - ) - - -def _add_column_if_missing(conn, table_name, column_name, column_definition): - if not _column_exists(conn, table_name, column_name): - conn.execute( - f"ALTER TABLE {table_name} ADD COLUMN {column_name} {column_definition}" - ) - -def _drop_dashboard_triggers(conn): - for trigger_name in ( - "soc_dashboard_fact_insert", - "soc_dashboard_fact_update", - "soc_dashboard_fact_delete", - ): - conn.execute(f"DROP TRIGGER IF EXISTS {trigger_name}") - - -def _ensure_alert_record_columns(conn): - for column_name, column_definition in ( - ("row_id", "TEXT"), - ("record_id", "TEXT"), - ("source_file", "TEXT"), - ("line_number", "INTEGER"), - ("source_type", "TEXT"), - ("threat_name", "TEXT"), - ("is_duplicate", "INTEGER DEFAULT 0"), - ): - _add_column_if_missing( - conn, - DEFAULT_SQLITE_TABLE, - column_name, - column_definition, - ) - conn.execute( - f"UPDATE {DEFAULT_SQLITE_TABLE} " - f"SET row_id = CAST(rowid AS TEXT) " - f"WHERE row_id IS NULL OR row_id = ''" - ) - - -def _create_dashboard_triggers(conn): - insert_fact = _fact_upsert_sql("NEW") - new_row_key = _fact_expressions("NEW")[1] - new_persisted = _json_value("NEW", "_triage_persisted_at") - old_persisted = _json_value("OLD", "_triage_persisted_at") - new_status = _json_value("NEW", "triage_status") - old_status = _json_value("OLD", "triage_status") - new_report = _json_value("NEW", "triage_report") - old_report = _json_value("OLD", "triage_report") - conn.execute( - f""" - CREATE TRIGGER IF NOT EXISTS soc_dashboard_fact_insert - AFTER INSERT ON {DEFAULT_SQLITE_TABLE} - BEGIN - {insert_fact}; - INSERT OR IGNORE INTO {ACTIVITY_TABLE} ( - event_key, alert_row_id, record_row_id, asset_date, event_time, record_json - ) - SELECT COALESCE(NULLIF(NEW.row_id, ''), CAST(NEW.rowid AS TEXT)) || - ':insert:' || COALESCE({new_persisted}, {new_status}, CAST(NEW.rowid AS TEXT)), - NEW.rowid, COALESCE(NULLIF(NEW.row_id, ''), CAST(NEW.rowid AS TEXT)), - NEW.asset_date, NEW.event_time, NEW.record_json - WHERE {_triage_marker('NEW')}; - END - """ - ) - conn.execute( - f""" - CREATE TRIGGER IF NOT EXISTS soc_dashboard_fact_update - AFTER UPDATE OF row_id, asset_date, event_time, source_type, threat_name, is_duplicate, record_json - ON {DEFAULT_SQLITE_TABLE} - BEGIN - DELETE FROM {FACTS_TABLE} - WHERE alert_row_id = NEW.rowid OR row_key = {new_row_key}; - {insert_fact}; - INSERT OR IGNORE INTO {ACTIVITY_TABLE} ( - event_key, alert_row_id, record_row_id, asset_date, event_time, record_json - ) - SELECT COALESCE(NULLIF(NEW.row_id, ''), CAST(NEW.rowid AS TEXT)) || - ':update:' || strftime('%s', 'now') || ':' || lower(hex(randomblob(6))), - NEW.rowid, COALESCE(NULLIF(NEW.row_id, ''), CAST(NEW.rowid AS TEXT)), - NEW.asset_date, NEW.event_time, NEW.record_json - WHERE {_triage_marker('NEW')} - AND NEW.record_json <> OLD.record_json - AND ( - COALESCE({new_persisted}, '') <> COALESCE({old_persisted}, '') - OR COALESCE({new_status}, '') <> COALESCE({old_status}, '') - OR COALESCE({new_report}, '') <> COALESCE({old_report}, '') - ); - END - """ - ) - conn.execute( - f""" - CREATE TRIGGER IF NOT EXISTS soc_dashboard_fact_delete - AFTER DELETE ON {DEFAULT_SQLITE_TABLE} - BEGIN - DELETE FROM {FACTS_TABLE} WHERE alert_row_id = OLD.rowid; - END - """ - ) - - -def _ensure_sqlite_schema(): - db_path = DEFAULT_SQLITE_DB - if not db_path.is_file(): - return False - stat = db_path.stat() - identity = (str(db_path), getattr(stat, "st_ino", 0)) - if identity in _schema_ready: - return True - with _schema_lock: - if identity in _schema_ready: - return True - with sqlite3.connect(db_path, timeout=30) as conn: - conn.execute("PRAGMA busy_timeout = 5000") - exists = conn.execute( - "SELECT 1 FROM sqlite_master WHERE type='table' AND name=?", - (DEFAULT_SQLITE_TABLE,), - ).fetchone() - if not exists: - return False - # One write transaction from dropping the projection triggers to - # creating them again: a writer that slipped in between would add - # an alert no trigger projects into the facts. - conn.execute("BEGIN IMMEDIATE") - _drop_dashboard_triggers(conn) - _ensure_alert_record_columns(conn) - conn.execute( - f"CREATE INDEX IF NOT EXISTS idx_alert_records_asset_event " - f"ON {DEFAULT_SQLITE_TABLE}(asset_date, event_time)" - ) - conn.execute( - f"CREATE INDEX IF NOT EXISTS idx_alert_records_event_time " - f"ON {DEFAULT_SQLITE_TABLE}(event_time)" - ) - conn.execute( - f"CREATE INDEX IF NOT EXISTS idx_alert_records_asset_date " - f"ON {DEFAULT_SQLITE_TABLE}(asset_date)" - ) - conn.execute( - f"CREATE INDEX IF NOT EXISTS idx_alert_records_source_type " - f"ON {DEFAULT_SQLITE_TABLE}(source_type)" - ) - conn.execute( - f"CREATE INDEX IF NOT EXISTS idx_alert_records_threat_name " - f"ON {DEFAULT_SQLITE_TABLE}(threat_name)" - ) - conn.execute( - f"CREATE UNIQUE INDEX IF NOT EXISTS idx_alert_records_row_id " - f"ON {DEFAULT_SQLITE_TABLE}(row_id)" - ) - conn.execute( - f""" - CREATE TABLE IF NOT EXISTS {META_TABLE} ( - meta_key TEXT PRIMARY KEY, - meta_value TEXT NOT NULL - ) - """ - ) - version_row = conn.execute( - f"SELECT meta_value FROM {META_TABLE} WHERE meta_key='schema_version'" - ).fetchone() - needs_rebuild = not version_row or str(version_row[0]) != SCHEMA_VERSION - conn.execute( - f""" - CREATE TABLE IF NOT EXISTS {FACTS_TABLE} ( - alert_row_id INTEGER PRIMARY KEY, - row_key TEXT NOT NULL UNIQUE, - asset_date TEXT NOT NULL, - event_time INTEGER, - source_type TEXT, - threat_name TEXT, - threat_type TEXT, - is_duplicate INTEGER NOT NULL DEFAULT 0, - phase TEXT, - direction TEXT, - result TEXT, - protocol TEXT, - severity TEXT, - response_code TEXT, - port TEXT, - has_triage INTEGER NOT NULL DEFAULT 0, - triage_persisted_at TEXT, - triage_status TEXT, - triage_source TEXT, - triage_attack_verdict TEXT, - risk_level TEXT, - triage_ms INTEGER NOT NULL DEFAULT 0, - triage_attack_success TEXT NOT NULL DEFAULT 'unknown' - ) - """ - ) - if needs_rebuild: - for column_name in _FACT_COLUMNS[1:]: - _add_column_if_missing( - conn, - FACTS_TABLE, - column_name, - _FACT_COLUMN_DEFINITIONS.get(column_name, "TEXT"), - ) - conn.execute( - f"CREATE INDEX IF NOT EXISTS idx_soc_dashboard_facts_asset_event " - f"ON {FACTS_TABLE}(asset_date, event_time)" - ) - conn.execute( - f"CREATE INDEX IF NOT EXISTS idx_soc_dashboard_facts_event " - f"ON {FACTS_TABLE}(event_time, asset_date)" - ) - conn.execute( - f"CREATE INDEX IF NOT EXISTS idx_soc_dashboard_facts_triage_event " - f"ON {FACTS_TABLE}(has_triage, asset_date, event_time)" - ) - conn.execute( - f"CREATE INDEX IF NOT EXISTS idx_soc_dashboard_facts_triage_time " - f"ON {FACTS_TABLE}(has_triage, event_time, asset_date)" - ) - conn.execute( - f""" - CREATE TABLE IF NOT EXISTS {ACTIVITY_TABLE} ( - activity_id INTEGER PRIMARY KEY AUTOINCREMENT, - event_key TEXT NOT NULL UNIQUE, - alert_row_id INTEGER NOT NULL, - record_row_id TEXT NOT NULL, - asset_date TEXT NOT NULL, - event_time INTEGER, - record_json TEXT NOT NULL - ) - """ - ) - conn.execute( - f"CREATE INDEX IF NOT EXISTS idx_soc_dashboard_activity_event " - f"ON {ACTIVITY_TABLE}(asset_date, event_time, activity_id)" - ) - conn.execute( - f"CREATE INDEX IF NOT EXISTS idx_soc_dashboard_activity_time " - f"ON {ACTIVITY_TABLE}(event_time, activity_id)" - ) - if needs_rebuild: - conn.execute(_fact_backfill_sql()) - # Facts of alert rows that are gone (the rest were just recomputed). - conn.execute( - f"DELETE FROM {FACTS_TABLE} WHERE NOT EXISTS (" - f"SELECT 1 FROM {DEFAULT_SQLITE_TABLE} AS source " - f"WHERE source.rowid = {FACTS_TABLE}.alert_row_id)" - ) - persisted = _json_value("source", "_triage_persisted_at") - status_value = _json_value("source", "triage_status") - conn.execute( - f""" - INSERT OR IGNORE INTO {ACTIVITY_TABLE} ( - event_key, alert_row_id, record_row_id, asset_date, event_time, record_json - ) - SELECT COALESCE(NULLIF(source.row_id, ''), CAST(source.rowid AS TEXT)) || ':bootstrap:' || - COALESCE({persisted}, {status_value}, CAST(source.rowid AS TEXT)), - source.rowid, - COALESCE(NULLIF(source.row_id, ''), CAST(source.rowid AS TEXT)), - source.asset_date, - source.event_time, source.record_json - FROM {DEFAULT_SQLITE_TABLE} AS source - WHERE {_triage_marker('source')} - """ - ) - conn.execute( - f"INSERT OR REPLACE INTO {META_TABLE}(meta_key, meta_value) " - f"VALUES('schema_version', ?)", - (SCHEMA_VERSION,), - ) - _create_dashboard_triggers(conn) - conn.commit() - _schema_ready.add(identity) - return True - - -def _maybe_prune_activity(): - global _activity_pruned_at - now = time.monotonic() - if now - _activity_pruned_at < ACTIVITY_PRUNE_INTERVAL: - return - with _schema_lock: - if now - _activity_pruned_at < ACTIVITY_PRUNE_INTERVAL: - return +def _bind(ctx): + """Take the SOC data service the platform hands this page.""" + global _store + soc = getattr(getattr(ctx, "services", None), "soc", None) + if soc is None: + # Not called by the page runtime: the SOC query tool loads this file itself. try: - with sqlite3.connect(DEFAULT_SQLITE_DB, timeout=5) as conn: - conn.execute( - f"DELETE FROM {ACTIVITY_TABLE} WHERE activity_id <= " - f"(SELECT COALESCE(MAX(activity_id), 0) - ? FROM {ACTIVITY_TABLE})", - (ACTIVITY_RETENTION_ROWS,), - ) - conn.commit() - except Exception: - pass - _activity_pruned_at = now - - -def _safe_json_object(value): - try: - parsed = json.loads(value or "{}") - except Exception: - return {} - return parsed if isinstance(parsed, dict) else {} - - -def _usage_iso(dt): - return dt.astimezone(timezone.utc).isoformat() - - -def _read_token_usage(): - empty = { - "totalTokens": 0, - "todayTokens": 0, - "todayRequests": 0, - "dailySeries": [], - "dailyLabels": [], - "source": "usage_records", - } - if not USAGE_DB.is_file(): - return empty + from flocks.workflow import soc_store + except ImportError as exc: + raise RuntimeError( + "The SOC dashboard needs the SOC data service of the platform; update Flocks to a version that has it" + ) from exc + soc = soc_store.page_service() + _store = soc.dashboard + return _store - try: - mtime_ns = USAGE_DB.stat().st_mtime_ns - except Exception: - mtime_ns = 0 - now_monotonic = time.monotonic() - with _cache_lock: - cached_value = _token_usage_cache.get("value") - if ( - cached_value is not None - and _token_usage_cache.get("mtimeNs") == mtime_ns - and now_monotonic - float(_token_usage_cache.get("updatedAt") or 0) < _TOKEN_USAGE_CACHE_TTL - ): - return cached_value - - now_local = datetime.now().astimezone() - today_start = now_local.replace(hour=0, minute=0, second=0, microsecond=0) - tomorrow_start = today_start + timedelta(days=1) - first_day = today_start - timedelta(days=6) - labels = [(first_day + timedelta(days=index)).strftime("%m/%d") for index in range(7)] - series_by_date = { - (first_day + timedelta(days=index)).date().isoformat(): 0 - for index in range(7) - } - - try: - with sqlite3.connect(f"file:{USAGE_DB}?mode=ro", uri=True, timeout=1.0) as conn: - conn.execute("PRAGMA query_only = ON") - if not _table_exists(conn, "usage_records"): - return {**empty, "dailyLabels": labels, "dailySeries": [0] * 7} - total_tokens = _safe_int( - conn.execute( - "SELECT COALESCE(SUM(total_tokens), 0) FROM usage_records" - ).fetchone()[0] - ) - today_row = conn.execute( - "SELECT COALESCE(SUM(total_tokens), 0), COUNT(*) " - "FROM usage_records WHERE created_at >= ? AND created_at < ?", - (_usage_iso(today_start), _usage_iso(tomorrow_start)), - ).fetchone() - series_rows = conn.execute( - "SELECT date(created_at, 'localtime') AS usage_day, " - "COALESCE(SUM(total_tokens), 0) AS token_count " - "FROM usage_records WHERE created_at >= ? AND created_at < ? " - "GROUP BY usage_day", - (_usage_iso(first_day), _usage_iso(tomorrow_start)), - ).fetchall() - except Exception: - return {**empty, "dailyLabels": labels, "dailySeries": [0] * 7} - - for usage_day, total in series_rows: - key = str(usage_day or "") - if key in series_by_date: - series_by_date[key] += max(_safe_int(total), 0) - - result = { - **empty, - "totalTokens": max(total_tokens, 0), - "todayTokens": max(_safe_int(today_row[0]), 0) if today_row else 0, - "todayRequests": max(_safe_int(today_row[1]), 0) if today_row else 0, - "dailySeries": list(series_by_date.values()), - "dailyLabels": labels, - } - with _cache_lock: - _token_usage_cache.update({"updatedAt": now_monotonic, "mtimeNs": mtime_ns, "value": result}) - return result - - -def _workflow_stats_sample_deltas(conn, workflow_name, start_time=0, end_time=0): - stats_exists = conn.execute( - "SELECT 1 FROM sqlite_master WHERE type='table' AND name='workflow_stats'" - ).fetchone() - if not stats_exists: - return None - columns = { - row[1] for row in conn.execute("PRAGMA table_info(workflow_stats)").fetchall() - } - success_expr = "success_count" if "success_count" in columns else "0" - error_expr = "error_count" if "error_count" in columns else "0" - updated_expr = "updated_at" if "updated_at" in columns else "0" - current = conn.execute( - f"SELECT call_count, {success_expr}, {error_expr}, {updated_expr} " - "FROM workflow_stats WHERE workflow_id = ?", - (workflow_name,), - ).fetchone() - if current is None: - return None - - conn.execute( - f""" - CREATE TABLE IF NOT EXISTS {WORKFLOW_SNAPSHOT_TABLE} ( - workflow_id TEXT NOT NULL, - sampled_at INTEGER NOT NULL, - call_count INTEGER NOT NULL, - success_count INTEGER NOT NULL DEFAULT 0, - error_count INTEGER NOT NULL DEFAULT 0, - PRIMARY KEY (workflow_id, sampled_at) - ) - """ - ) - last = conn.execute( - f"SELECT sampled_at, call_count, success_count, error_count " - f"FROM {WORKFLOW_SNAPSHOT_TABLE} WHERE workflow_id = ? " - "ORDER BY sampled_at DESC LIMIT 1", - (workflow_name,), - ).fetchone() - current_count = max(_safe_int(current[0]), 0) - success_count = max(_safe_int(current[1]), 0) - error_count = max(_safe_int(current[2]), 0) - if last is None or (current_count, success_count, error_count) != tuple(last[1:4]): - stats_updated_at = _safe_int(current[3]) or int(time.time() * 1000) - sampled_at = stats_updated_at - (stats_updated_at % 60000) - if last is not None and sampled_at <= _safe_int(last[0]): - sampled_at = _safe_int(last[0]) - conn.execute( - f"UPDATE {WORKFLOW_SNAPSHOT_TABLE} " - "SET call_count = ?, success_count = ?, error_count = ? " - "WHERE workflow_id = ? AND sampled_at = ?", - (current_count, success_count, error_count, workflow_name, sampled_at), - ) - else: - conn.execute( - f"INSERT INTO {WORKFLOW_SNAPSHOT_TABLE} " - "(workflow_id, sampled_at, call_count, success_count, error_count) " - "VALUES (?, ?, ?, ?, ?)", - (workflow_name, sampled_at, current_count, success_count, error_count), - ) - conn.commit() - last = (sampled_at, current_count, success_count, error_count) - - if not (start_time > 0 and end_time > 0): - sampled_at = max(_safe_int(current[3]), _safe_int(last[0] if last else 0)) - return [(current_count, success_count, error_count, sampled_at)] if current_count else [] - - start_ms = int(start_time * 1000) - end_ms = int(end_time * 1000) - previous = conn.execute( - f"SELECT call_count, success_count, error_count " - f"FROM {WORKFLOW_SNAPSHOT_TABLE} " - "WHERE workflow_id = ? AND sampled_at < ? " - "ORDER BY sampled_at DESC LIMIT 1", - (workflow_name, start_ms), - ).fetchone() - rows = conn.execute( - f"SELECT sampled_at, call_count, success_count, error_count " - f"FROM {WORKFLOW_SNAPSHOT_TABLE} " - "WHERE workflow_id = ? AND sampled_at >= ? AND sampled_at <= ? " - "ORDER BY sampled_at", - (workflow_name, start_ms, end_ms), - ).fetchall() - previous_counts = tuple(previous) if previous is not None else (0, 0, 0) - deltas = [] - for sampled_at, call_count, sample_success, sample_error in rows: - current_counts = ( - max(_safe_int(call_count), 0), - max(_safe_int(sample_success), 0), - max(_safe_int(sample_error), 0), - ) - delta_counts = tuple( - current_value - previous_value - if current_value >= previous_value - else current_value - for current_value, previous_value in zip(current_counts, previous_counts) - ) - if delta_counts[0] > 0: - deltas.append((*delta_counts, _safe_int(sampled_at))) - previous_counts = current_counts - return deltas - - -def _workflow_stats_call_delta_from_samples(conn, workflow_name, start_ms, end_ms): - if not _table_exists(conn, WORKFLOW_SNAPSHOT_TABLE): - return None - previous = conn.execute( - f"SELECT call_count FROM {WORKFLOW_SNAPSHOT_TABLE} " - "WHERE workflow_id = ? AND sampled_at < ? " - "ORDER BY sampled_at DESC LIMIT 1", - (workflow_name, start_ms), - ).fetchone() - if previous is None: - return None - rows = conn.execute( - f"SELECT sampled_at, call_count FROM {WORKFLOW_SNAPSHOT_TABLE} " - "WHERE workflow_id = ? AND sampled_at >= ? AND sampled_at < ? " - "ORDER BY sampled_at", - (workflow_name, start_ms, end_ms), - ).fetchall() - if not rows: - return None - total = 0 - previous_count = max(_safe_int(previous[0]), 0) - for _, call_count in rows: - current_count = max(_safe_int(call_count), 0) - total += ( - current_count - previous_count - if current_count >= previous_count - else current_count - ) - previous_count = current_count - return max(total, 0) - - -def _workflow_metric_value(stats, key, fallback=0): - value = stats.get(key) - return max(_safe_int(fallback if value is None else value), 0) - - -def _workflow_alert_preview(output): - for key in ("unique_alerts", "enriched_alerts"): - value = output.get(key) - if isinstance(value, dict): - value = value.get("preview") - if isinstance(value, list): - return next( - ( - item - for item in value - if isinstance(item, dict) and item.get("_type") != "dict" - ), - {}, - ) - return {} - - -def _workflow_input_preview(inputs): - syslog_message = inputs.get("syslog_message") or inputs.get("syslog") - if isinstance(syslog_message, dict): - message = syslog_message.get("message") - if isinstance(message, str): - parsed = _safe_json_object(message) - if parsed: - return parsed - alerts = inputs.get("alerts") or inputs.get("alert_list") - if isinstance(alerts, dict): - alerts = alerts.get("data") - if isinstance(alerts, list): - return next((item for item in alerts if isinstance(item, dict)), {}) - return {} - - -def _workflow_execution_metrics(output_text, input_text=""): - output = _safe_json_object(output_text) - inputs = _safe_json_object(input_text) - stats = output.get("stats") if isinstance(output.get("stats"), dict) else {} - duplicate_flag_available = isinstance(output.get("is_duplicate"), bool) - metrics_available = duplicate_flag_available or any( - stats.get(key) is not None - for key in ( - "raw_count", - "normalized_count", - "after_filter_count", - "after_dedup_count", - ) - ) - raw_count = _workflow_metric_value(stats, "raw_count", 1) - normalized_count = _workflow_metric_value(stats, "normalized_count", raw_count) - after_filter_count = _workflow_metric_value( - stats, - "after_filter_count", - normalized_count, - ) - unique_count = _workflow_metric_value( - stats, - "after_dedup_count", - after_filter_count, - ) - filter_removed_count = _workflow_metric_value( - stats, - "filter_removed_count", - max(normalized_count - after_filter_count, 0), - ) - duplicate_count = _workflow_metric_value( - stats, - "dedup_removed_count", - max(after_filter_count - unique_count, 0), - ) - is_duplicate = output.get("is_duplicate") is True - if ( - is_duplicate - and raw_count == 1 - and after_filter_count == 1 - and unique_count == 1 - and duplicate_count == 0 - ): - # Older streaming executions only counted duplicates within the current - # one-alert batch, even when cross-batch state marked it as duplicate. - unique_count = 0 - duplicate_count = 1 - reduced_count = ( - max(raw_count - unique_count, filter_removed_count + duplicate_count, 0) - if metrics_available - else 0 - ) - source_counts = {} - raw_source_counts = stats.get("normalize_type_counts") - if isinstance(raw_source_counts, dict) and raw_source_counts.get("_type") != "dict": - source_counts = { - _norm(key): max(_safe_int(value), 0) - for key, value in raw_source_counts.items() - if max(_safe_int(value), 0) > 0 - } - preview = _workflow_alert_preview(output) or _workflow_input_preview(inputs) - syslog_message = inputs.get("syslog_message") or inputs.get("syslog") - syslog_app = syslog_message.get("app_name") if isinstance(syslog_message, dict) else "" - source_type = _norm( - preview.get("_source_type") - or inputs.get("source_log_type") - or output.get("source_log_type") - or output.get("input_mode") - or syslog_app - ) - if not source_counts and normalized_count > 0: - source_counts[source_type] = normalized_count +def _data(): + if _store is None: + return _bind(None) + return _store - return { - "metricsAvailable": metrics_available, - "rawCount": raw_count, - "normalizedCount": normalized_count, - "afterFilterCount": after_filter_count, - "uniqueCount": unique_count, - "filterRemovedCount": filter_removed_count, - "duplicateCount": duplicate_count, - "reducedCount": reduced_count, - "reductionRate": _ratio(reduced_count, raw_count) if metrics_available else 0, - "dedupRate": _ratio(duplicate_count, after_filter_count) if metrics_available else 0, - "clusterCount": _workflow_metric_value(stats, "lsh_total_clusters"), - "isDuplicate": is_duplicate, - "sourceCounts": source_counts, - "sourceType": source_type, - "preview": preview, - } - - -def _empty_workflow_denoise_stats(): - return { - "callCount": 0, - "successCount": 0, - "errorCount": 0, - "earliestStartedAt": 0, - "latestStartedAt": 0, - "rawCount": 0, - "normalizedCount": 0, - "afterFilterCount": 0, - "uniqueCount": 0, - "filterRemovedCount": 0, - "duplicateCount": 0, - "reducedCount": 0, - "reductionRate": 0, - "dedupRate": 0, - "sourceCounts": {}, - "seriesRaw": [], - "seriesUnique": [], - "timelineLabels": [], - "timelineWindow": "", - } +def _is_store_source(path): + """Whether *path* is a set of records in the alert store (what find_sources lists), not a file.""" + return hasattr(path, "data_source") -def _get_workflow_denoise_stats( - workflow_name: str, - start_time: int = 0, - end_time: int = 0, - *, - force: bool = False, -) -> dict: - now = time.time() - cache_key = f"denoise:{workflow_name}:{start_time or 0}:{end_time or 0}" - with _cache_lock: - cached = _workflow_stats_cache.get(cache_key) - if not force and cached and now - float(cached.get("updatedAt") or 0) < _CACHE_TTL: - _workflow_stats_cache.move_to_end(cache_key) - return cached["value"] - - empty = _empty_workflow_denoise_stats() - if not WORKFLOW_DB.is_file(): - return empty - - try: - with sqlite3.connect(WORKFLOW_DB) as conn: - sample_deltas = _workflow_stats_sample_deltas( - conn, - workflow_name, - start_time, - end_time, - ) - if sample_deltas is None: - query = ( - "SELECT status, started_at FROM workflow_executions " - "WHERE workflow_id = ?" - ) - query_params = [workflow_name] - if start_time > 0 and end_time > 0: - query += " AND started_at >= ? AND started_at <= ?" - query_params.extend((int(start_time * 1000), int(end_time * 1000))) - query += " ORDER BY started_at" - execution_rows = conn.execute(query, query_params).fetchall() - samples = [ - ( - 1, - 1 if str(status).lower() == "success" else 0, - 0 if str(status).lower() == "success" else 1, - _safe_int(started_at), - ) - for status, started_at in execution_rows - ] - else: - samples = sample_deltas - - result_dict = _empty_workflow_denoise_stats() - processed_total = sum(call_count for call_count, _, _, _ in samples) - if processed_total: - result_dict.update( - { - "callCount": processed_total, - "successCount": sum(success_count for _, success_count, _, _ in samples), - "errorCount": sum(error_count for _, _, error_count, _ in samples), - "earliestStartedAt": samples[0][3], - "latestStartedAt": samples[-1][3], - "rawCount": processed_total, - "normalizedCount": processed_total, - "afterFilterCount": processed_total, - "sourceCounts": {"ndr": processed_total}, - } - ) - first_started = samples[0][3] // 1000 - last_started = samples[-1][3] // 1000 - bucket_start, bucket_seconds, bucket_count, labels, window = _timeline_spec( - [], - start_time or first_started, - end_time or max(last_started, first_started), - ) - series_raw = [0] * bucket_count - for call_count, _, _, started_at in samples: - index = int(((started_at // 1000) - bucket_start) / bucket_seconds) - if 0 <= index < bucket_count: - series_raw[index] += call_count - result_dict["seriesRaw"] = series_raw - result_dict["timelineLabels"] = labels - result_dict["timelineWindow"] = window - - with _cache_lock: - _workflow_stats_cache[cache_key] = {"updatedAt": now, "value": result_dict} - _workflow_stats_cache.move_to_end(cache_key) - while len(_workflow_stats_cache) > _WORKFLOW_CACHE_MAX: - _workflow_stats_cache.popitem(last=False) - return result_dict - except Exception: - with _cache_lock: - cached = _workflow_stats_cache.get(cache_key) - return cached["value"] if cached else empty - - -def _get_workflow_progress( - workflow_name: str, - start_time: int = 0, - end_time: int = 0, -) -> dict: - unavailable = {"callCount": None, "latestStartedAt": None} - if not WORKFLOW_DB.is_file(): - return unavailable - - try: - with sqlite3.connect(WORKFLOW_DB) as conn: - if start_time > 0 and end_time > 0: - sample_deltas = _workflow_stats_sample_deltas( - conn, - workflow_name, - start_time, - end_time, - ) - if sample_deltas is None: - row = conn.execute( - "SELECT COUNT(*), COALESCE(MAX(started_at), 0) " - "FROM workflow_executions " - "WHERE workflow_id = ? AND started_at >= ? AND started_at <= ?", - (workflow_name, int(start_time * 1000), int(end_time * 1000)), - ).fetchone() - else: - latest_row = conn.execute( - "SELECT COALESCE(MAX(started_at), 0) FROM workflow_executions " - "WHERE workflow_id = ? AND started_at >= ? AND started_at <= ?", - (workflow_name, int(start_time * 1000), int(end_time * 1000)), - ).fetchone() - latest_sample = sample_deltas[-1][3] if sample_deltas else 0 - row = ( - sum(max(_safe_int(item[0]), 0) for item in sample_deltas), - max(_safe_int(latest_row[0] if latest_row else 0), _safe_int(latest_sample)), - ) - else: - row = conn.execute( - "SELECT call_count FROM workflow_stats WHERE workflow_id = ?", - (workflow_name,), - ).fetchone() - except Exception: - return unavailable - - if row is None: - return {"callCount": 0, "latestStartedAt": 0} - return { - "callCount": max(_safe_int(row[0]), 0), - "latestStartedAt": max(_safe_int(row[1] if len(row) > 1 else 0), 0), - } - - -def _dashboard_execution_detail(output_text, input_text): - """Read a bounded preview for this execution only; never open result files. - - Kept separate from metric aggregation and task-center/workflow contracts. - A missing count is not zero (nor an assumed single-alert batch). - """ - output = _safe_json_object(output_text) - inputs = _safe_json_object(input_text) - def text(*values): - return _first_text(*(value[:512] for value in values if isinstance(value, str))) - - queue = [(value, 0) for value in ( - output.get("enriched_alerts_with_triage"), output.get("triage_results"), - output.get("unique_alerts"), output.get("enriched_alerts"), - inputs.get("_soc_alert_preview"), inputs.get("alerts"), - inputs.get("alert_list"), inputs.get("syslog_message"), inputs.get("syslog"), - ) if value is not None] - best, best_score = {}, 0 - for _ in range(48): - if not queue: - break - value, depth = queue.pop(0) - if depth > 6: - continue - if isinstance(value, str): - if len(value) > 65536: - continue - # Syslog prefixes can precede a vendor JSON envelope. - start = value.find("{") - parsed = _safe_json_object(value[start:] if start >= 0 else value) - if parsed: - queue.append((parsed, depth + 1)) - elif isinstance(value, list): - queue.extend((item, depth + 1) for item in value[:3]) - elif isinstance(value, dict): - if value.get("_type") == "dict": - continue # Persisted key-only summary, not an alert. - alert = { - "id": text(value.get("id"), value.get("alert_id"), value.get("uuid")), - "threatName": text(value.get("threat_name"), value.get("alert_name"), value.get("attack_name")), - "sourceType": text(value.get("_source_type"), value.get("source_type"), value.get("device_type")), - "srcIp": text(value.get("sip"), value.get("src_ip"), value.get("source_ip"), value.get("net_real_src_ip")), - "dstIp": text(value.get("dip"), value.get("dst_ip"), value.get("destination_ip"), value.get("net_dest_ip")), - } - score = sum(bool(alert[key]) for key in ("threatName", "srcIp", "dstIp")) - if score > best_score: - best, best_score = alert, score - for key in ("preview", "data", "alert", "alerts", "message", "msg", "log", "event", "payload"): - if key in value: - queue.append((value[key], depth + 1)) - stats = output.get("stats") if isinstance(output.get("stats"), dict) else {} - raw = stats.get("raw_count", inputs.get("_soc_alert_count")) - try: - count = int(raw) if raw is not None and not isinstance(raw, bool) else None - if count is not None and (count < 0 or str(raw).strip() != str(count)): - count = None - except (ValueError, TypeError, OverflowError): - count = None - if count is None: - alerts = inputs.get("alerts", inputs.get("alert_list")) - if isinstance(alerts, list): - count = len(alerts) - if best: - best["sourceType"] = best["sourceType"] or text( - inputs.get("source_log_type"), output.get("source_log_type") - ) - return best, count - - -def _get_workflow_recent_events( - workflow_name: str, - start_time: int = 0, - end_time: int = 0, - limit: int = 10, - snapshot=None, -) -> list: - # Polling must not multiply native SQLite allocations across dashboard tabs. - # The worker owns this lock until its reads/parsing actually finish, even if - # the HTTP request awaiting asyncio.to_thread is cancelled. - if not _workflow_activity_read_lock.acquire(blocking=False): - if snapshot is not None: - snapshot.update(complete=False, available=False) - return [] - try: - return _read_workflow_recent_events(workflow_name, start_time, end_time, limit, snapshot) - finally: - _workflow_activity_read_lock.release() - - -def _read_workflow_recent_events(workflow_name, start_time, end_time, limit, snapshot): - if not WORKFLOW_DB.is_file(): - if snapshot is not None: - snapshot.update(complete=False, available=False) - return [] - workflow_stage = "triage" if workflow_name in TRIAGE_WORKFLOW_IDS else "denoise" - try: - with closing(sqlite3.connect(f"{WORKFLOW_DB.resolve().as_uri()}?mode=ro", uri=True, timeout=0.2)) as conn: - deadline = time.monotonic() + 0.2 - conn.set_progress_handler(lambda: int(time.monotonic() > deadline), 100) - conn.row_factory = sqlite3.Row - conn.execute("BEGIN") - execution_columns = { - row[1] - for row in conn.execute("PRAGMA table_info(workflow_executions)").fetchall() - } - # octet_length(column) reads the record's byte-length metadata, not - # the entire TEXT. length(TEXT), including a cast-based fallback, - # is NOT a native-memory bound. Older SQLite must omit previews. - try: - conn.execute("SELECT octet_length('')").fetchone() - has_octet_length = True - except sqlite3.OperationalError: - has_octet_length = False - - def preview_column(name): - if name not in execution_columns or not has_octet_length: - return f"'{{}}' AS {name}" - return f"CASE WHEN octet_length({name}) <= 262144 THEN {name} ELSE '{{}}' END AS {name}" - - metadata_select = ", ".join([ - "id", "status", "started_at", - _workflow_execution_column_expr(execution_columns, "updated_at", "started_at"), - ]) - query = f"SELECT {metadata_select} FROM workflow_executions WHERE workflow_id = ?" - query_params = [workflow_name] - if start_time > 0 and end_time > 0: - query += " AND started_at >= ? AND started_at <= ?" - query_params.extend((int(start_time * 1000), int(end_time * 1000))) - row_limit = max(1, min(_safe_int(limit), 10)) - active_rows = conn.execute( - query + " AND status IN ('running', 'queued', 'pending') ORDER BY started_at DESC LIMIT ?", - [*query_params, row_limit], - ).fetchall() - recent_rows = conn.execute(query + " ORDER BY started_at DESC LIMIT ?", [*query_params, row_limit]).fetchall() - ids = list(dict.fromkeys(row["id"] for row in [*active_rows, *recent_rows])) - if time.monotonic() > deadline: - raise sqlite3.OperationalError("activity read budget exceeded") - # Select payloads only AFTER bounding IDs; a sorting query must not - # materialize previews for every matching execution before LIMIT. - rows = [] - if ids: - previews = ", ".join(preview_column(name) for name in ("output_results", "input_params", "payload")) - placeholders = ",".join("?" for _ in ids) - by_id = {row["id"]: row for row in conn.execute( - f"SELECT {metadata_select}, {previews} FROM workflow_executions WHERE id IN ({placeholders})", - ids, - ).fetchall()} - rows = [by_id[key] for key in ids] - if time.monotonic() > deadline: - raise sqlite3.OperationalError("activity read budget exceeded") - if snapshot is not None and len(active_rows) == row_limit: - snapshot["complete"] = False - except Exception: - if snapshot is not None: - snapshot.update(complete=False, available=False) - return [] - - events = [] - for row in rows: - execution_id = row["id"] - status = row["status"] - started_at = row["started_at"] - output_text = row["output_results"] - input_text = row["input_params"] - payload_text = row["payload"] - metrics = _workflow_execution_metrics(output_text, input_text) - alert, raw_count = _dashboard_execution_detail(output_text, input_text) - if workflow_stage == "denoise" and raw_count == 0 and not alert: - continue # No alert work; keep the execution itself untouched. - unique_count = metrics["uniqueCount"] - threat_name = alert.get("threatName", "") - if not threat_name and workflow_stage == "triage": - threat_name = _workflow_latest_alert_name(workflow_name, output_text, input_text) - if not threat_name: - threat_name = f"降噪批次 · 原始 {raw_count} 条" if raw_count and raw_count > 0 else "降噪批次 · 数量未提供" - normalized_status = str(status or "").lower() - event_status = ( - "completed" - if normalized_status in {"success", "completed"} - else normalized_status - if normalized_status in {"running", "queued", "pending"} - else "failed" - ) - session_id, message_id = _workflow_link_context( - { - "payload": payload_text, - "input_params": input_text, - } - ) - events.append( - { - "eventId": f"workflow-execution:{execution_id}", - "stage": workflow_stage, - "status": event_status, - "occurredAt": datetime.fromtimestamp( - _safe_int(started_at) / 1000 - ).astimezone().isoformat(timespec="seconds"), - "updatedAt": datetime.fromtimestamp( - _safe_int(row["updated_at"] or started_at) / 1000 - ).astimezone().isoformat(timespec="milliseconds"), - "triggerSource": "workflow_execution", - "workflowId": workflow_name, - "sessionId": session_id, - "messageId": message_id, - "sampleCount": max(unique_count, 1), - "alert": { - **alert, - "id": alert.get("id") or "", - "threatName": threat_name, - }, - "result": { - "isDuplicate": metrics["isDuplicate"], - "clusterId": str(metrics["clusterCount"] or "--"), - **{ - key: value - for key, value in metrics.items() - if key not in {"preview", "sourceCounts", "sourceType"} - }, - "rawCount": raw_count, - }, - } - ) - return events +_stats_response_cache: OrderedDict = OrderedDict() +_STATS_RESPONSE_CACHE_TTL = 300.0 +_STATS_RESPONSE_CACHE_MAX = 32 +_cache_lock = RLock() SOURCE_DEFS = [ @@ -1389,24 +134,17 @@ def _triage_attack_success_value(record): return "unknown" -async def get_activity(ctx, request): +def get_activity(ctx, request): + _bind(ctx) params = dict(request.query_params) - return await asyncio.to_thread(_get_activity, params) + return _data().activity(params) -async def get_task_center(ctx, request): +def get_task_center(ctx, request): + _bind(ctx) params = dict(request.query_params) include_mock = _truthy(params.get("mockActivity")) or _truthy(params.get("mockTaskCenter")) - return await asyncio.to_thread(_get_task_center, include_mock) - - -def _table_exists(conn, table_name): - return bool( - conn.execute( - "SELECT 1 FROM sqlite_master WHERE type='table' AND name=?", - (table_name,), - ).fetchone() - ) + return _get_task_center(include_mock) def _task_center_empty(): @@ -1418,617 +156,22 @@ def _task_center_empty(): "workflowActiveCount": 0, "scheduledTasks": [], "workflows": [], - "sourceStatus": { - "tasksDb": str(TASK_DB), - "workflowDb": str(WORKFLOW_DB), - "tasksAvailable": TASK_DB.is_file(), - "workflowAvailable": WORKFLOW_DB.is_file(), - }, + "sourceStatus": _task_center_source_status(), } -def _truthy(value): - return str(value or "").strip().lower() in {"1", "true", "yes", "on"} - - -def _task_trigger_value(trigger, key): - if not isinstance(trigger, dict): - return "" - return trigger.get(key) or trigger.get(key[0].lower() + key[1:]) or "" - - -def _today_bounds(): - now_local = datetime.now().astimezone() - today_start = now_local.replace(hour=0, minute=0, second=0, microsecond=0) - return today_start, today_start + timedelta(days=1) - - -def _task_center_task_rows(limit=12): - if not TASK_DB.is_file(): - return 0, [], 0, 0, 0 - try: - with sqlite3.connect(f"file:{TASK_DB}?mode=ro", uri=True, timeout=1.0) as conn: - conn.row_factory = sqlite3.Row - conn.execute("PRAGMA query_only = ON") - if not ( - _table_exists(conn, "task_schedulers") - and _table_exists(conn, "task_executions") - ): - return 0, [], 0, 0, 0 - today_start, tomorrow_start = _today_bounds() - today_start_iso = today_start.isoformat(timespec="seconds") - tomorrow_start_iso = tomorrow_start.isoformat(timespec="seconds") - session_count = _safe_int( - conn.execute( - "SELECT COUNT(DISTINCT session_id) FROM task_executions " - "WHERE session_id IS NOT NULL AND session_id <> ''" - ).fetchone()[0] - ) - scheduler_rows = conn.execute( - "SELECT id, title, mode, status, trigger, execution_mode, workflow_id, updated_at " - "FROM task_schedulers WHERE status <> 'archived' " - "ORDER BY updated_at DESC" - ).fetchall() - tasks = [] - for scheduler in scheduler_rows: - summary = conn.execute( - "SELECT COUNT(*) AS execution_count, " - "SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) AS success_count, " - "SUM(CASE WHEN status IN ('pending', 'queued', 'running') THEN 1 ELSE 0 END) AS active_count, " - "SUM(CASE WHEN " - "julianday(COALESCE(started_at, queued_at, created_at)) >= julianday(?) " - "AND julianday(COALESCE(started_at, queued_at, created_at)) < julianday(?) " - "THEN 1 ELSE 0 END) AS today_execution_count " - "FROM task_executions WHERE scheduler_id = ?", - (today_start_iso, tomorrow_start_iso, scheduler["id"]), - ).fetchone() - latest = conn.execute( - "SELECT status, queued_at, started_at, completed_at, updated_at " - "FROM task_executions WHERE scheduler_id = ? " - "ORDER BY julianday(COALESCE(completed_at, updated_at, started_at, queued_at, created_at)) DESC " - "LIMIT 1", - (scheduler["id"],), - ).fetchone() - trigger = _safe_json_object(scheduler["trigger"]) - execution_count = max(_safe_int(summary["execution_count"]), 0) - success_count = max(_safe_int(summary["success_count"]), 0) - active_count = max(_safe_int(summary["active_count"]), 0) - today_execution_count = max(_safe_int(summary["today_execution_count"]), 0) - last_run_at = "" - if latest: - last_run_at = latest["completed_at"] or latest["updated_at"] or latest["started_at"] or latest["queued_at"] or "" - tasks.append( - { - "id": scheduler["id"], - "name": scheduler["title"] or scheduler["id"], - "mode": scheduler["mode"] or "once", - "status": scheduler["status"] or "active", - "executionMode": scheduler["execution_mode"] or "agent", - "workflowId": scheduler["workflow_id"] or "", - "executionCount": execution_count, - "todayExecutionCount": today_execution_count, - "successCount": success_count, - "successRate": _ratio(success_count, execution_count), - "activeCount": active_count, - "lastStatus": latest["status"] if latest else "", - "lastRunAt": last_run_at, - "nextRunAt": _task_trigger_value(trigger, "nextRun"), - "cron": _task_trigger_value(trigger, "cron"), - "cronDescription": _task_trigger_value(trigger, "cronDescription"), - } - ) - tasks.sort( - key=lambda item: ( - item["activeCount"] > 0, - item["lastRunAt"] or "", - item["executionCount"], - ), - reverse=True, - ) - return ( - session_count, - tasks[:limit], - sum(task["executionCount"] for task in tasks), - sum(task["todayExecutionCount"] for task in tasks), - sum(task["activeCount"] for task in tasks), - ) - except Exception: - return 0, [], 0, 0, 0 - - -def _workflow_manifest_name_map(): - roots = [ - Path.home() / ".flocks" / "plugins" / "workflows", - Path.home() / ".flocks" / "workspace" / "workflows", - Path(__file__).resolve().parents[4] / "workflows", - ] - names = {} - for root in roots: - if not root.is_dir(): - continue - for manifest_path in root.glob("*/manifest.json"): - workflow_id = manifest_path.parent.name - try: - manifest = _safe_json_object(manifest_path.read_text(encoding="utf-8")) - except Exception: - manifest = {} - name = ( - manifest.get("nameCn") - or manifest.get("name") - or manifest.get("title") - or workflow_id - ) - name_i18n = manifest.get("nameI18n") - if isinstance(name_i18n, dict): - name = name_i18n.get("zh-CN") or name_i18n.get("zh") or name - names.setdefault(workflow_id, str(name)) - return names - - -def _workflow_config_name_map(conn): - if not _table_exists(conn, "workflow_configs"): - return {} - names = {} - for row in conn.execute( - "SELECT workflow_id, config FROM workflow_configs WHERE kind = ?", - ("workflow.integration-config",), - ).fetchall(): - workflow_id = row["workflow_id"] if isinstance(row, sqlite3.Row) else row[0] - config_raw = row["config"] if isinstance(row, sqlite3.Row) else row[1] - if not workflow_id: - continue - config = _safe_json_object(config_raw) - workflow = config.get("workflow") - if not isinstance(workflow, dict): - continue - name = workflow.get("name") or workflow.get("title") or workflow.get("id") - if name: - names.setdefault(str(workflow_id), str(name)) - return names - - -def _truthy_config_value(value): - if isinstance(value, bool): - return value - if isinstance(value, (int, float)): - return value != 0 - text = str(value or "").strip().lower() - if not text: - return False - return text in {"1", "true", "yes", "on", "enabled"} - - -def _workflow_trigger_state(conn, workflow_id): - state = { - "hasConfig": False, - "enabled": True, - "timeoutSeconds": WORKFLOW_DEFAULT_ACTIVE_TIMEOUT_SECONDS, +def _task_center_source_status(): + status = _data().source_status() + return { + "tasksDb": str(status["tasksDb"]), + "workflowDb": str(status["workflowDb"]), + "tasksAvailable": status["tasksAvailable"], + "workflowAvailable": status["workflowAvailable"], } - if not _table_exists(conn, "workflow_configs"): - return state - - placeholders = ",".join("?" for _ in WORKFLOW_TRIGGER_CONFIG_KINDS) - rows = conn.execute( - "SELECT kind, config FROM workflow_configs WHERE workflow_id = ? " - f"AND (kind IN ({placeholders}) OR kind LIKE ? OR kind LIKE ? OR kind LIKE ?)", - ( - workflow_id, - *WORKFLOW_TRIGGER_CONFIG_KINDS, - "workflow_kafka_config/%", - "workflow_poller_config/%", - "workflow_syslog_config/%", - ), - ).fetchall() - if not rows: - return state - - enabled = False - timeout_seconds = WORKFLOW_DEFAULT_ACTIVE_TIMEOUT_SECONDS - for row in rows: - config = _safe_json_object(row["config"] if isinstance(row, sqlite3.Row) else row[1]) - if "enabled" not in config or _truthy_config_value(config.get("enabled")): - enabled = True - timeout_seconds = max( - timeout_seconds, - _safe_int(config.get("timeoutSeconds") or config.get("timeout_seconds")), - ) - state["hasConfig"] = True - state["enabled"] = enabled - state["timeoutSeconds"] = max(timeout_seconds, WORKFLOW_MIN_ACTIVE_TIMEOUT_SECONDS) - return state - -def _workflow_effective_status(latest, active_count, trigger_state): - if not latest: - return "" - status = str(latest["status"] or "").lower() - if status not in WORKFLOW_RUNNING_STATUSES: - return status - if active_count > 0: - return status - if trigger_state.get("hasConfig") and not trigger_state.get("enabled"): - return "disabled" - return "stale" - - -def _workflow_execution_column_expr(columns, column_name, fallback): - return column_name if column_name in columns else f"{fallback} AS {column_name}" - - -def _workflow_node_count(workflow_id): - roots = [ - Path.home() / ".flocks" / "plugins" / "workflows", - Path.home() / ".flocks" / "workspace" / "workflows", - Path(__file__).resolve().parents[4] / "workflows", - ] - for root in roots: - workflow_path = root / str(workflow_id) / "workflow.json" - if not workflow_path.is_file(): - continue - try: - workflow_json = _safe_json_object(workflow_path.read_text(encoding="utf-8")) - nodes = workflow_json.get("nodes") - if isinstance(nodes, list): - return max(len(nodes), 0) - except Exception: - continue - return 0 - - -def _first_text(*values): - for value in values: - text = str(value or "").strip() - if text and text.lower() not in {"unknown", "none", "null", "--"}: - return text - return "" - - -def _alert_name_from_record(record): - if not isinstance(record, dict): - return "" - return _first_text( - record.get("threat_name"), - record.get("_threat_type"), - record.get("threat_type"), - record.get("alert_name"), - record.get("name"), - record.get("report_title"), - record.get("title"), - ) - -def _workflow_latest_alert_name(workflow_id, output_text="", input_text=""): - output = _safe_json_object(output_text) - inputs = _safe_json_object(input_text) - preview = _workflow_alert_preview(output) or _workflow_input_preview(inputs) - name = _alert_name_from_record(preview) - if name: - return name - for key in ( - "enriched_alerts_with_triage", - "triage_results", - "unique_alerts", - "enriched_alerts", - ): - value = output.get(key) - if isinstance(value, dict): - value = value.get("preview") - if isinstance(value, list): - for item in value: - name = _alert_name_from_record(item) - if name: - return name - name = _first_text( - output.get("top_report_title"), - output.get("report_title"), - output.get("title"), - ) - if name: - return name - if workflow_id in TRIAGE_WORKFLOW_IDS: - input_date = _first_text(inputs.get("input_date")) - return f"研判批次 {input_date}" if input_date else "研判批次" - if workflow_id == "stream_alert_denoise": - return "降噪批次" - return "" - - -def _workflow_progress(status, current_step_index, completed_steps, total_steps): - normalized = str(status or "").lower() - current = max(_safe_int(current_step_index), _safe_int(completed_steps), 0) - total = max(_safe_int(total_steps), current, 1) - if normalized == "disabled": - return 0, "已关闭" - if normalized == "stale": - return 0, "已停止" - if normalized in WORKFLOW_SUCCESS_STATUSES: - return 1, "已完成" - if normalized in {"error", "failed", "timeout"}: - percent = _ratio(current or total, total) - return percent, f"失败于 {current or total}/{total} 步" - if normalized == "cancelled": - percent = _ratio(current or total, total) - return percent, f"已取消 {current or total}/{total} 步" - if normalized in WORKFLOW_RUNNING_STATUSES: - visible_current = current if current > 0 else 1 - return max(_ratio(visible_current, total), 0.03), f"第 {visible_current}/{total} 步" - return 0, "待执行" - - -def _workflow_link_context(latest): - payload = _safe_json_object(latest["payload"] if latest and "payload" in latest.keys() else "") - input_params = _safe_json_object(latest["input_params"] if latest and "input_params" in latest.keys() else "") - session_id = _first_text( - payload.get("sessionId"), - payload.get("sessionID"), - payload.get("session_id"), - input_params.get("sessionId"), - input_params.get("sessionID"), - input_params.get("session_id"), - ) - message_id = _first_text( - payload.get("messageId"), - payload.get("messageID"), - payload.get("message_id"), - input_params.get("messageId"), - input_params.get("messageID"), - input_params.get("message_id"), - ) - return session_id, message_id - - -def _task_center_workflow_rows(limit=12, include_mock=False): - if not WORKFLOW_DB.is_file(): - return [], 0, 0, 0 - try: - with sqlite3.connect(f"file:{WORKFLOW_DB}?mode=ro", uri=True, timeout=1.0) as conn: - conn.row_factory = sqlite3.Row - conn.execute("PRAGMA query_only = ON") - if not ( - _table_exists(conn, "workflow_stats") - or _table_exists(conn, "workflow_executions") - ): - return [], 0, 0, 0 - today_start, tomorrow_start = _today_bounds() - today_start_ms = int(today_start.timestamp() * 1000) - tomorrow_start_ms = int(tomorrow_start.timestamp() * 1000) - workflow_ids = set() - if _table_exists(conn, "workflow_stats"): - workflow_ids.update( - row[0] - for row in conn.execute("SELECT workflow_id FROM workflow_stats").fetchall() - if row[0] - ) - if _table_exists(conn, "workflow_executions"): - workflow_ids.update( - row[0] - for row in conn.execute( - "SELECT DISTINCT workflow_id FROM workflow_executions" - ).fetchall() - if row[0] - ) - names = { - **_workflow_manifest_name_map(), - **_workflow_config_name_map(conn), - **WORKFLOW_DISPLAY_NAMES, - } - if include_mock: - workflow_ids.update(SOC_PINNED_WORKFLOW_NAMES) - stats_columns = ( - { - row[1] - for row in conn.execute("PRAGMA table_info(workflow_stats)").fetchall() - } - if _table_exists(conn, "workflow_stats") - else set() - ) - stats_success_expr = "success_count" if "success_count" in stats_columns else "0" - stats_error_expr = "error_count" if "error_count" in stats_columns else "0" - stats_updated_expr = "updated_at" if "updated_at" in stats_columns else "0" - execution_columns = ( - { - row[1] - for row in conn.execute("PRAGMA table_info(workflow_executions)").fetchall() - } - if _table_exists(conn, "workflow_executions") - else set() - ) - finished_at_expr = "finished_at" if "finished_at" in execution_columns else "NULL" - updated_at_expr = "updated_at" if "updated_at" in execution_columns else "NULL" - execution_time_expr = f"COALESCE({finished_at_expr}, {updated_at_expr}, started_at, 0)" - execution_start_expr = "started_at" - active_time_expr = f"COALESCE({updated_at_expr}, started_at, 0)" - latest_select = ", ".join( - [ - "id", - "status", - "started_at", - _workflow_execution_column_expr(execution_columns, "finished_at", "NULL"), - _workflow_execution_column_expr(execution_columns, "updated_at", "0"), - _workflow_execution_column_expr(execution_columns, "current_phase", "''"), - _workflow_execution_column_expr(execution_columns, "current_step_index", "0"), - _workflow_execution_column_expr(execution_columns, "step_count", "0"), - _workflow_execution_column_expr(execution_columns, "input_params", "'{}'"), - _workflow_execution_column_expr(execution_columns, "output_results", "'{}'"), - _workflow_execution_column_expr(execution_columns, "payload", "'{}'"), - _workflow_execution_column_expr(execution_columns, "error_message", "''"), - ] - ) - workflows = [] - total_execution_count = 0 - total_today_execution_count = 0 - total_active_count = 0 - now_ms = int(time.time() * 1000) - for workflow_id in workflow_ids: - workflow_name = names.get(workflow_id, workflow_id) - hidden_workflow = UUID_RE.match(str(workflow_id)) and workflow_name == workflow_id - trigger_state = _workflow_trigger_state(conn, workflow_id) - stats = None - if _table_exists(conn, "workflow_stats"): - stats = conn.execute( - f"SELECT call_count, {stats_success_expr}, {stats_error_expr}, {stats_updated_expr} " - "FROM workflow_stats WHERE workflow_id = ?", - (workflow_id,), - ).fetchone() - latest = None - exec_summary = None - if _table_exists(conn, "workflow_executions"): - exec_summary = conn.execute( - "SELECT COUNT(*) AS execution_count, " - "SUM(CASE WHEN status IN ('success', 'completed') THEN 1 ELSE 0 END) AS success_count, " - f"SUM(CASE WHEN {execution_start_expr} >= ? " - f"AND {execution_start_expr} < ? THEN 1 ELSE 0 END) " - "AS today_execution_count " - "FROM workflow_executions WHERE workflow_id = ?", - (today_start_ms, tomorrow_start_ms, workflow_id), - ).fetchone() - latest = conn.execute( - f"SELECT {latest_select} " - "FROM workflow_executions WHERE workflow_id = ? " - f"ORDER BY {execution_time_expr} DESC LIMIT 1", - (workflow_id,), - ).fetchone() - active_count = 0 - if _table_exists(conn, "workflow_executions"): - if trigger_state["hasConfig"] and trigger_state["enabled"]: - active_since_ms = now_ms - trigger_state["timeoutSeconds"] * 1000 - active_summary = conn.execute( - "SELECT COUNT(*) AS active_count " - "FROM workflow_executions WHERE workflow_id = ? " - "AND status IN ('running', 'queued', 'pending') " - f"AND {active_time_expr} >= ?", - (workflow_id, active_since_ms), - ).fetchone() - elif not trigger_state["hasConfig"] and "updated_at" in execution_columns: - active_since_ms = now_ms - WORKFLOW_DEFAULT_ACTIVE_TIMEOUT_SECONDS * 1000 - active_summary = conn.execute( - "SELECT COUNT(*) AS active_count " - "FROM workflow_executions WHERE workflow_id = ? " - "AND status IN ('running', 'queued', 'pending') " - f"AND {active_time_expr} >= ?", - (workflow_id, active_since_ms), - ).fetchone() - elif not trigger_state["hasConfig"]: - active_summary = conn.execute( - "SELECT COUNT(*) AS active_count " - "FROM workflow_executions WHERE workflow_id = ? " - "AND status IN ('running', 'queued', 'pending')", - (workflow_id,), - ).fetchone() - else: - active_summary = None - active_count = max( - _safe_int(active_summary["active_count"] if active_summary else 0), - 0, - ) - exec_execution_count = max( - _safe_int(exec_summary["execution_count"] if exec_summary else 0), - 0, - ) - exec_today_execution_count = max( - _safe_int(exec_summary["today_execution_count"] if exec_summary else 0), - 0, - ) - if stats is not None: - execution_count = max(_safe_int(stats["call_count"]), 0) - stats_today_count = _workflow_stats_call_delta_from_samples( - conn, - workflow_id, - today_start_ms, - tomorrow_start_ms, - ) - today_execution_count = ( - max(_safe_int(stats_today_count), 0) - if stats_today_count is not None - else exec_today_execution_count - ) - success_count = max(_safe_int(stats["success_count"]), 0) - else: - execution_count = exec_execution_count - today_execution_count = exec_today_execution_count - success_count = max( - _safe_int(exec_summary["success_count"] if exec_summary else 0), - 0, - ) - total_execution_count += execution_count - total_today_execution_count += today_execution_count - total_active_count += active_count - if hidden_workflow: - continue - last_run_at = 0 - if latest: - last_run_at = ( - _safe_int(latest["finished_at"]) - or _safe_int(latest["updated_at"]) - or _safe_int(latest["started_at"]) - ) - workflow_total_steps = _workflow_node_count(workflow_id) - latest_alert_name = "" - progress_percent = 0 - progress_label = "待执行" - current_phase = "" - session_id = "" - message_id = "" - effective_status = _workflow_effective_status(latest, active_count, trigger_state) - if latest: - workflow_total_steps = max(workflow_total_steps, _safe_int(latest["step_count"])) - latest_alert_name = _workflow_latest_alert_name( - workflow_id, - latest["output_results"], - latest["input_params"], - ) - progress_percent, progress_label = _workflow_progress( - effective_status, - latest["current_step_index"], - latest["step_count"], - workflow_total_steps, - ) - current_phase = str(latest["current_phase"] or "") - session_id, message_id = _workflow_link_context(latest) - workflows.append( - { - "id": workflow_id, - "name": workflow_name, - "executionCount": execution_count, - "todayExecutionCount": today_execution_count, - "successCount": success_count, - "successRate": _ratio(success_count, execution_count), - "activeCount": active_count, - "lastStatus": effective_status, - "lastRunAt": last_run_at, - "latestExecutionHash": str(latest["id"] if latest else ""), - "latestAlertName": latest_alert_name, - "progressPercent": progress_percent, - "progressLabel": progress_label, - "currentPhase": current_phase, - "sessionId": session_id, - "messageId": message_id, - } - ) - soc_order = { - "stream_alert_denoise": 3, - "stream_alert_triage": 2, - "onesec_kafka_investigation": 1, - "tdp_alert_triage": 1, - "sec_alert_unified_ops": 1, - } - workflows.sort( - key=lambda item: ( - item["activeCount"] > 0, - item["lastRunAt"], - item["executionCount"], - soc_order.get(item["id"], 0), - ), - reverse=True, - ) - return ( - workflows[:limit], - total_execution_count, - total_today_execution_count, - total_active_count, - ) - except Exception: - return [], 0, 0, 0 +def _truthy(value): + return str(value or "").strip().lower() in {"1", "true", "yes", "on"} def _get_task_center(include_mock=False): @@ -2038,13 +181,13 @@ def _get_task_center(include_mock=False): scheduled_execution_count, scheduled_today_execution_count, scheduled_active_count, - ) = _task_center_task_rows() + ) = _data().task_center_tasks() ( workflows, workflow_execution_count, workflow_today_execution_count, workflow_active_count, - ) = _task_center_workflow_rows( + ) = _data().task_center_workflows( include_mock=include_mock, ) return { @@ -2062,468 +205,6 @@ def _get_task_center(include_mock=False): } -def _get_activity(params): - _ensure_sqlite_schema() - _maybe_prune_activity() - settings = _sqlite_settings() - db_path = settings["db_path"] - time_window = _normalize_time_window( - params.get("startTime"), - params.get("endTime"), - ) - start_time, end_time = time_window or (0, 0) - workflow_stats = _get_workflow_progress( - "stream_alert_denoise", - start_time, - end_time, - ) - workflow_snapshot = {"complete": True, "available": True} - workflow_events = [ - *_get_workflow_recent_events("stream_alert_denoise", start_time, end_time, snapshot=workflow_snapshot), - *_get_workflow_recent_events("stream_alert_triage", start_time, end_time, snapshot=workflow_snapshot), - ] - raw_cursor = str(params.get("cursor") or "").strip() - bootstrap = str(params.get("bootstrap") or "").strip().lower() == "latest" - limit = max(1, min(_safe_int(params.get("limit") or ACTIVITY_DEFAULT_LIMIT), ACTIVITY_MAX_LIMIT)) - - if not db_path.is_file(): - return _activity_response( - [], - 0, - "", - cursor_reset=bool(raw_cursor), - workflow_stats=workflow_stats, - workflow_events=workflow_events, - workflow_snapshot=workflow_snapshot, - ) - - cursor = _decode_activity_cursor(raw_cursor) if raw_cursor else None - cursor_reset = bool(raw_cursor and cursor is None) - - try: - with sqlite3.connect(db_path) as conn: - conn.row_factory = sqlite3.Row - conn.execute("PRAGMA query_only = ON") - if not ( - _table_exists(conn, DEFAULT_SQLITE_TABLE) - and _table_exists(conn, ACTIVITY_TABLE) - ): - return _activity_response( - [], - 0, - 0, - cursor_reset=cursor_reset, - workflow_stats=workflow_stats, - workflow_events=workflow_events, - workflow_snapshot=workflow_snapshot, - ) - latest_row_id, latest_activity_id = _activity_latest_cursor(conn, settings) - - if bootstrap or cursor is None: - recent_events = _activity_recent_events( - conn, - settings, - limit=10, - start_time=start_time, - end_time=end_time, - ) - return _activity_response( - [], - latest_row_id, - latest_activity_id, - cursor_reset=cursor_reset, - recent_events=recent_events, - workflow_stats=workflow_stats, - workflow_events=workflow_events, - workflow_snapshot=workflow_snapshot, - ) - - last_row_id = max(_safe_int(cursor.get("lastRowId")), 0) - last_activity_id = max(_safe_int(cursor.get("lastActivityId")), 0) - if last_row_id > latest_row_id or last_activity_id > latest_activity_id: - last_row_id = 0 - last_activity_id = 0 - cursor_reset = True - rows, overflow_count, batch = _activity_rows( - conn, - settings, - last_row_id=last_row_id, - last_activity_id=last_activity_id, - latest_row_id=latest_row_id, - latest_activity_id=latest_activity_id, - limit=limit, - ) - except Exception as exc: - return { - **_activity_response( - [], - 0, - "", - workflow_stats=workflow_stats, - workflow_events=workflow_events, - workflow_snapshot=workflow_snapshot, - ), - "error": f"activity query failed: {exc}", - } - - events = [] - seen = set() - for row in rows: - event = _activity_event(row) - if event is None or event["eventId"] in seen: - continue - seen.add(event["eventId"]) - events.append(event) - - return { - **_activity_response( - events, - latest_row_id, - latest_activity_id, - cursor_reset=cursor_reset, - batch=batch, - workflow_stats=workflow_stats, - workflow_events=workflow_events, - workflow_snapshot=workflow_snapshot, - ), - "overflowCount": overflow_count, - } - - -def _activity_response( - events, - last_row_id, - last_activity_id, - *, - cursor_reset=False, - recent_events=None, - batch=None, - workflow_stats=None, - workflow_events=None, - workflow_snapshot=None, -): - return { - "cursor": _encode_activity_cursor(last_row_id, last_activity_id), - "generatedAt": datetime.now().astimezone().isoformat(timespec="seconds"), - "events": events, - "recentEvents": recent_events or [], - "overflowCount": 0, - "batch": batch or _empty_activity_batch(), - "cursorReset": cursor_reset, - "workflowStats": workflow_stats or {"callCount": None, "latestStartedAt": None}, - "workflowEvents": workflow_events or [], - "workflowSnapshotComplete": bool(workflow_snapshot and workflow_snapshot["complete"]), - "workflowSnapshotAvailable": bool(workflow_snapshot and workflow_snapshot.get("available", True)), - "tokenUsage": _read_token_usage(), - } - - -def _empty_activity_batch(): - return { - "mode": "normal", - "windowMs": ACTIVITY_WINDOW_MS, - "receivedCount": 0, - "duplicateCount": 0, - "uniqueCount": 0, - "clusterCount": 0, - "triageUpdatedCount": 0, - "sampledCount": 0, - "suppressedCount": 0, - "ratePerSecond": 0, - } - - -def _encode_activity_cursor(last_row_id, last_activity_id): - payload = json.dumps( - { - "lastRowId": max(_safe_int(last_row_id), 0), - "lastActivityId": max(_safe_int(last_activity_id), 0), - }, - separators=(",", ":"), - ).encode("utf-8") - return base64.urlsafe_b64encode(payload).decode("ascii").rstrip("=") - - -def _decode_activity_cursor(value): - try: - padding = "=" * (-len(value) % 4) - payload = json.loads(base64.urlsafe_b64decode((value + padding).encode("ascii"))) - except Exception: - return None - if not isinstance(payload, dict) or "lastRowId" not in payload: - return None - return payload - - -def _activity_latest_cursor(conn, settings): - latest_row_id = _safe_int( - conn.execute(f"SELECT COALESCE(MAX(rowid), 0) FROM {settings['table']}").fetchone()[0] - ) - latest_activity_id = _safe_int( - conn.execute( - f"SELECT COALESCE(MAX(activity_id), 0) FROM {settings['activity_table']}" - ).fetchone()[0] - ) - return latest_row_id, latest_activity_id - - -def _activity_rows( - conn, - settings, - *, - last_row_id, - last_activity_id, - latest_row_id, - latest_activity_id, - limit, -): - summary = _activity_insert_summary(conn, settings, last_row_id, latest_row_id) - new_count = summary["receivedCount"] - updated_count = _safe_int( - conn.execute( - f"SELECT COUNT(*) FROM {settings['activity_table']} " - f"WHERE alert_row_id <= ? AND activity_id > ? AND activity_id <= ?", - (last_row_id, last_activity_id, latest_activity_id), - ).fetchone()[0] - ) - - triage_reserve = min(updated_count, 3) - inserted = _activity_insert_samples( - conn, - settings, - last_row_id=last_row_id, - latest_row_id=latest_row_id, - received_count=new_count, - limit=max(limit - triage_reserve, 1), - ) - remaining = max(limit - len(inserted), 0) - updated = [] - if remaining and updated_count: - updated = conn.execute( - f"SELECT alert_row_id AS activity_row_id, activity_id AS activity_log_id, " - f"event_time AS activity_event_time, record_json, 1 AS sample_count " - f"FROM {settings['activity_table']} " - f"WHERE alert_row_id <= ? AND activity_id > ? AND activity_id <= ? " - f"ORDER BY activity_id DESC LIMIT ?", - (last_row_id, last_activity_id, latest_activity_id, remaining), - ).fetchall() - - rows = list(reversed(inserted)) + list(reversed(updated)) - sampled_count = len(inserted) - batch = { - **summary, - "mode": ( - "surge" - if new_count > ACTIVITY_SURGE_LIMIT - else "burst" if new_count > ACTIVITY_NORMAL_LIMIT else "normal" - ), - "windowMs": ACTIVITY_WINDOW_MS, - "triageUpdatedCount": updated_count, - "sampledCount": sampled_count, - "suppressedCount": max(new_count - sampled_count, 0), - "ratePerSecond": round(new_count / (ACTIVITY_WINDOW_MS / 1000), 1), - } - return rows, max(new_count + updated_count - len(rows), 0), batch - - -def _activity_table_columns(conn, settings): - return { - str(row[1]) - for row in conn.execute(f"PRAGMA table_info({settings['table']})").fetchall() - } - - -def _activity_insert_summary(conn, settings, last_row_id, latest_row_id): - columns = _activity_table_columns(conn, settings) - table = settings["table"] - if {"is_duplicate", "threat_name", "source_type"}.issubset(columns): - row = conn.execute( - f"SELECT COUNT(*) AS received_count, " - f"COALESCE(SUM(CASE WHEN \"is_duplicate\" = 1 THEN 1 ELSE 0 END), 0) AS duplicate_count, " - f"COUNT(DISTINCT COALESCE(NULLIF(\"source_type\", ''), 'unknown') || '|' || " - f"COALESCE(NULLIF(\"threat_name\", ''), 'unknown') || '|' || CAST(\"is_duplicate\" AS TEXT)) " - f"AS cluster_count FROM {table} WHERE rowid > ? AND rowid <= ?", - (last_row_id, latest_row_id), - ).fetchone() - received_count = _safe_int(row[0]) - duplicate_count = _safe_int(row[1]) - cluster_count = _safe_int(row[2]) - else: - received_count = _safe_int( - conn.execute( - f"SELECT COUNT(*) FROM {table} WHERE rowid > ? AND rowid <= ?", - (last_row_id, latest_row_id), - ).fetchone()[0] - ) - duplicate_count = 0 - cluster_count = received_count - return { - "receivedCount": received_count, - "duplicateCount": duplicate_count, - "uniqueCount": max(received_count - duplicate_count, 0), - "clusterCount": cluster_count, - } - - -def _activity_insert_samples(conn, settings, *, last_row_id, latest_row_id, received_count, limit): - if received_count <= 0: - return [] - table = settings["table"] - record_column = settings["record_column"] - if received_count <= limit: - return conn.execute( - f"SELECT rowid AS activity_row_id, {settings['event_time_column']} AS activity_event_time, " - f"{record_column} AS record_json, 1 AS sample_count " - f"FROM {table} WHERE rowid > ? AND rowid <= ? ORDER BY rowid DESC", - (last_row_id, latest_row_id), - ).fetchall() - - columns = _activity_table_columns(conn, settings) - if {"is_duplicate", "threat_name", "source_type"}.issubset(columns): - return conn.execute( - f"SELECT MAX(rowid) AS activity_row_id, MAX({settings['event_time_column']}) AS activity_event_time, " - f"{record_column} AS record_json, COUNT(*) AS sample_count " - f"FROM {table} WHERE rowid > ? AND rowid <= ? " - f"GROUP BY COALESCE(NULLIF(\"source_type\", ''), 'unknown'), " - f"COALESCE(NULLIF(\"threat_name\", ''), 'unknown'), \"is_duplicate\" " - f"ORDER BY sample_count DESC, activity_row_id DESC LIMIT ?", - (last_row_id, latest_row_id, limit), - ).fetchall() - return conn.execute( - f"SELECT rowid AS activity_row_id, {settings['event_time_column']} AS activity_event_time, " - f"{record_column} AS record_json, 1 AS sample_count " - f"FROM {table} WHERE rowid > ? AND rowid <= ? ORDER BY rowid DESC LIMIT ?", - (last_row_id, latest_row_id, limit), - ).fetchall() - - -def _activity_recent_events(conn, settings, *, limit, start_time=0, end_time=0): - raw_time_condition = "" - activity_time_condition = "" - time_params = [] - if start_time > 0 and end_time > 0: - start_date = datetime.fromtimestamp(start_time).strftime("%Y-%m-%d") - end_date = datetime.fromtimestamp(end_time).strftime("%Y-%m-%d") - raw_time_condition = ( - f"source.{settings['date_column']} BETWEEN ? AND ? " - f"AND source.{settings['event_time_column']} BETWEEN ? AND ?" - ) - activity_time_condition = ( - "asset_date BETWEEN ? AND ? AND event_time BETWEEN ? AND ?" - ) - time_params = [start_date, end_date, start_time, end_time] - recent_where = f" WHERE {raw_time_condition}" if raw_time_condition else "" - recent_rows = conn.execute( - f"SELECT source.rowid AS activity_row_id, " - f"source.{settings['event_time_column']} AS activity_event_time, " - f"source.{settings['record_column']} AS record_json, " - f"1 AS sample_count FROM {settings['table']} AS source{recent_where} " - f"ORDER BY source.{settings['event_time_column']} DESC, source.rowid DESC LIMIT ?", - (*time_params, limit), - ).fetchall() - triage_where = f" WHERE {activity_time_condition}" if activity_time_condition else "" - triage_rows = conn.execute( - f"SELECT alert_row_id AS activity_row_id, activity_id AS activity_log_id, " - f"event_time AS activity_event_time, record_json, 1 AS sample_count " - f"FROM {settings['activity_table']}{triage_where} " - f"ORDER BY event_time DESC, activity_id DESC LIMIT ?", - (*time_params, limit), - ).fetchall() - events = [] - seen = set() - for row in [*recent_rows, *triage_rows]: - event = _activity_event(row) - if event is None or event["eventId"] in seen: - continue - seen.add(event["eventId"]) - events.append(event) - return events - - -def _activity_event(row): - try: - record = json.loads(row["record_json"]) - except Exception: - return None - if not isinstance(record, dict): - return None - - row_id = str(row["activity_row_id"]) - triage_status = str(record.get("triage_status") or "").strip().lower() - triage_at = str(record.get("_triage_persisted_at") or "") - is_triage = bool(triage_status or triage_at or record.get("triage_report")) - stage = "triage" if is_triage else "denoise" - version = triage_at or row_id - event_time = _activity_event_time(record) - if not event_time and "activity_event_time" in row.keys(): - parsed_event_time = _parse_event_time(row["activity_event_time"]) - event_time = parsed_event_time.astimezone().isoformat(timespec="seconds") if parsed_event_time else "" - event = { - "eventId": f"{row_id}:{stage}:{version}", - "stage": stage, - "status": "failed" if triage_status in {"failed", "error"} else "completed", - "occurredAt": event_time, - "sampleCount": max(_safe_int(row["sample_count"]), 1) if "sample_count" in row.keys() else 1, - "alert": { - "id": _first_activity_text(record, "id", "record_id", "uuid", "event_id", "dedup_key"), - "sourceType": _first_activity_text(record, "_source_type", "source_type", "device_type"), - "threatName": _first_activity_text(record, "threat_name") or "未知告警", - "srcIp": _first_activity_text(record, "sip", "src_ip", "source_ip"), - "dstIp": _first_activity_text(record, "dip", "dst_ip", "destination_ip"), - "requestUri": _first_activity_text(record, "req_http_url", "uri", "url"), - "threatPhase": _first_activity_text(record, "threat_phase"), - "threatType": _first_activity_text(record, "_threat_type", "threat_type"), - }, - } - if stage == "denoise": - event["result"] = { - "isDuplicate": record.get("is_duplicate") is True, - "clusterId": _first_activity_text(record, "_lsh_cluster_id"), - "dedupKey": _first_activity_text(record, "dedup_key"), - } - else: - verdict = _triage_attack_verdict_value(record) - attack_success = _triage_attack_success_value(record) - outcome = _triage_outcome_key(record) - event["result"] = { - "triageStatus": triage_status or "completed", - "triageSource": str(record.get("triage_source") or "").strip().lower() or "triaged", - "durationMs": _safe_int(record.get("triage_ms")), - "verdict": verdict, - "attackSuccess": attack_success, - "verdictLabel": RESULT_LABELS.get(outcome, "待确认"), - "threatSeverity": _first_activity_text(record, "threat_severity"), - "riskLevel": _first_activity_text(record, "risk_level"), - "reportTitle": _first_activity_text(record, "report_title"), - "hasReport": bool(record.get("triage_report")), - } - return event - - -def _activity_event_time(record): - for key in ("time", "event_time", "timestamp", "timestamp_real", "occur_time", "created_at"): - value = _parse_event_time(record.get(key)) - if value is not None: - return value.astimezone().isoformat(timespec="seconds") - return "" - - -def _first_activity_text(record, *keys): - for key in keys: - value = record.get(key) - if value not in (None, "", "none", "None"): - return str(value) - return "" - - -def _file_revision(path): - try: - stat = path.stat() - return stat.st_size, stat.st_mtime_ns - except Exception: - return 0, 0 - - def _stats_cache_ttl(start_time, end_time): span = max(end_time - start_time, 0) if span <= 2 * 60 * 60: @@ -2559,13 +240,14 @@ def _stats_cache_put(cache_key, value): _stats_response_cache.popitem(last=False) -async def get_stats(ctx, request): +def get_stats(ctx, request): + _bind(ctx) params = dict(request.query_params) - return await asyncio.to_thread(_get_stats, params) + return _get_stats(params) def _get_stats(params): - _ensure_sqlite_schema() + _data().ensure_schema() time_window = _normalize_time_window( params.get("startTime"), params.get("endTime"), @@ -2602,7 +284,7 @@ def _get_stats(params): if cached is not None: return { **cached, - "tokenUsage": _read_token_usage(), + "tokenUsage": _data().token_usage(), "generatedAt": datetime.now().isoformat(timespec="seconds"), "latencyMs": round((time.time() - started) * 1000), "cacheHit": True, @@ -2619,7 +301,7 @@ def _get_stats(params): denoise_files = asset_denoise_files triage_files = asset_triage_files or asset_denoise_files - workflow_stats = _get_workflow_denoise_stats( + workflow_stats = _data().workflow_denoise_stats( "stream_alert_denoise", range_start_time, range_end_time, @@ -2655,7 +337,7 @@ def _get_stats(params): "_timelineLabels": timeline_labels, "_timelineWindow": timeline_window, "workflowCallCount": processed_total, - "dataSource": "workflow.db.workflow_stats.call_count + soc.db.unique", + "dataSource": "workflow call count + unique alerts", } ) triage = _read_triage(triage_files) @@ -2669,6 +351,7 @@ def _get_stats(params): date_range = _build_date_range(start_date, end_date, asset_files, available_dates) event_range = _build_event_range(date_range, denoise, triage) + source_status = _data().source_status() result = { "date": start_date, "dateRange": date_range, @@ -2677,22 +360,22 @@ def _get_stats(params): "latencyMs": round((time.time() - started) * 1000), "sourceStatus": { "dataPolicy": { - "mode": "sqlite-only", + "mode": source_status["mode"], "jsonlEnabled": False, "allowedDatabases": [ - _display_path(DEFAULT_SQLITE_DB), - _display_path(WORKFLOW_DB), - _display_path(USAGE_DB), + _display_path(source_status["alertsDb"]), + _display_path(source_status["workflowDb"]), + _display_path(source_status["usageDb"]), ], }, - "workflowStatsDb": _display_path(WORKFLOW_DB), + "workflowStatsDb": _display_path(source_status["workflowDb"]), "workflowStats": workflow_stats, "sampleMode": sample_mode, "sampleFile": ", ".join(_source_label(path) for path in asset_files) if sample_mode else "", "assets": { - "path": _display_path(_active_source_path()), - "exists": _active_source_exists(), - "dataSource": _active_data_source(), + "path": _display_path(source_status["alertsDb"]), + "exists": source_status["alertsAvailable"], + "dataSource": source_status["dataSource"], "locked": True, "fileCount": len(asset_files), "availableDates": available_dates, @@ -2731,7 +414,7 @@ def _get_stats(params): 8, ), "riskLevels": _counter_items(triage["riskCounter"], 5), - "tokenUsage": _read_token_usage(), + "tokenUsage": _data().token_usage(), "timeline": { "labels": denoise.get("_timelineLabels") or _series_labels(max(len(denoise["seriesRaw"]), len(triage["seriesTotal"]))), @@ -2782,11 +465,11 @@ def _date_span(start_date, end_date): def _find_asset_files(start_date, end_date, start_time=0, end_time=0): - return _find_sqlite_sources(start_date, end_date, start_time, end_time) + return _data().find_sources(start_date, end_date, start_time, end_time) def _asset_file_date(path): - if isinstance(path, _RecordSource): + if _is_store_source(path): return path.date return "" @@ -2797,94 +480,7 @@ def _latest_asset_date(): def _available_asset_dates(): - return _available_sqlite_dates() - - -def _active_data_source(): - return "sqlite" - - -def _sqlite_settings(): - return { - "db_path": DEFAULT_SQLITE_DB, - "table": f'"{DEFAULT_SQLITE_TABLE}"', - "facts_table": f'"{FACTS_TABLE}"', - "activity_table": f'"{ACTIVITY_TABLE}"', - "record_column": f'"{DEFAULT_SQLITE_RECORD_COLUMN}"', - "date_column": f'"{DEFAULT_SQLITE_DATE_COLUMN}"', - "event_time_column": f'"{DEFAULT_SQLITE_EVENT_TIME_COLUMN}"', - } - - -def _active_source_path(): - return _sqlite_settings()["db_path"] - - -def _active_source_exists(): - path = _active_source_path() - return path.is_file() - - -def _find_sqlite_sources(start_date, end_date, start_time=0, end_time=0): - settings = _sqlite_settings() - db_path = settings["db_path"] - if not db_path.is_file(): - return [] - - time_clause = "" - query_params = [start_date, end_date] - if start_time > 0 and end_time > 0: - time_clause = f" AND {settings['event_time_column']} BETWEEN ? AND ?" - query_params.extend((start_time, end_time)) - query = ( - f"SELECT {settings['date_column']} AS asset_date, COUNT(*) AS record_count " - f"FROM {settings['facts_table']} " - f"WHERE {settings['date_column']} BETWEEN ? AND ?{time_clause} " - f"GROUP BY {settings['date_column']} " - f"ORDER BY {settings['date_column']}" - ) - try: - with sqlite3.connect(db_path) as conn: - rows = conn.execute(query, query_params).fetchall() - except Exception: - return [] - - sources = [] - for asset_date, record_count in rows: - asset_date = str(asset_date or "") - if not DATE_RE.match(asset_date): - continue - sources.append( - _RecordSource( - path=db_path, - role="denoise", - date=asset_date, - data_source="sqlite", - record_count=int(record_count or 0), - start_time=start_time, - end_time=end_time, - ) - ) - return sources - - -def _available_sqlite_dates(): - settings = _sqlite_settings() - db_path = settings["db_path"] - if not db_path.is_file(): - return [] - query = ( - f"SELECT DISTINCT {settings['date_column']} AS asset_date " - f"FROM {settings['facts_table']} " - f"WHERE {settings['date_column']} IS NOT NULL " - f"ORDER BY {settings['date_column']}" - ) - try: - with sqlite3.connect(db_path) as conn: - rows = conn.execute(query).fetchall() - except Exception: - return [] - return [str(row[0]) for row in rows if DATE_RE.match(str(row[0]))] + return _data().available_dates() def _build_date_range(start_date, end_date, asset_files, available_dates=None): @@ -2932,7 +528,7 @@ def _timeline_window(start_date, end_date, series_length): def _asset_file_role(path): - if isinstance(path, _RecordSource): + if _is_store_source(path): return path.role name = path.name.lower() if "triage" in name or "研判" in name: @@ -2941,8 +537,8 @@ def _asset_file_role(path): def _read_denoise(paths, workflow_call_count: int = 0): - if paths and all(isinstance(path, _RecordSource) and path.data_source == "sqlite" for path in paths): - optimized = _read_sqlite_denoise(paths, workflow_call_count) + if paths and all(_is_store_source(path) for path in paths): + optimized = _data().read_denoise(paths, workflow_call_count) if optimized is not None: return optimized @@ -3004,377 +600,9 @@ def _read_denoise(paths, workflow_call_count: int = 0): } -def _read_sqlite_denoise(paths, workflow_call_count): - settings = _sqlite_settings() - dates = sorted({path.date for path in paths}) - if not dates: - return None - placeholders = ",".join("?" for _ in dates) - date_column = settings["date_column"] - event_time_column = settings["event_time_column"] - table = settings["facts_table"] - where_clause = f"{date_column} IN ({placeholders})" - query_params = list(dates) - start_time = min((path.start_time for path in paths if path.start_time > 0), default=0) - end_time = max((path.end_time for path in paths if path.end_time > 0), default=0) - if start_time > 0 and end_time > 0: - where_clause += f" AND {event_time_column} BETWEEN ? AND ?" - query_params.extend((start_time, end_time)) - try: - with sqlite3.connect(settings["db_path"]) as conn: - rows = conn.execute( - f"SELECT {date_column}, COUNT(*), " - f"COALESCE(SUM(CASE WHEN \"is_duplicate\" = 1 THEN 1 ELSE 0 END), 0), " - f"MIN({event_time_column}), MAX({event_time_column}) " - f"FROM {table} WHERE {where_clause} " - f"GROUP BY {date_column} ORDER BY {date_column}", - query_params, - ).fetchall() - source_rows = conn.execute( - f"SELECT \"source_type\", COUNT(*) FROM {table} " - f"WHERE {where_clause} GROUP BY \"source_type\"", - query_params, - ).fetchall() - profile_counters, threat_type_counter = _sqlite_detail_counters( - conn, - settings, - where_clause, - query_params, - ) - timeline = _sqlite_timeline( - conn, - settings, - where_clause, - query_params, - dates, - start_time, - end_time, - ) - except Exception: - return None - - total_raw = sum(_safe_int(row[1]) for row in rows) - duplicates = sum(_safe_int(row[2]) for row in rows) - total_unique = max(total_raw - duplicates, 0) - event_values = [ - _parse_event_time(value) - for row in rows - for value in (row[3], row[4]) - if value not in (None, "") - ] - series_raw = [_safe_int(row[1]) for row in rows] - series_unique = [max(_safe_int(row[1]) - _safe_int(row[2]), 0) for row in rows] - return { - "totalRaw": total_raw, - "totalUnique": total_unique, - "duplicates": duplicates, - "duplicateRate": _ratio(duplicates, total_raw), - "uniqueRate": _ratio(total_unique, total_raw), - "headers": 0, - "files": len(paths), - "parseErrors": 0, - "eventStart": _format_event_time(min(event_values) if event_values else None), - "eventEnd": _format_event_time(max(event_values) if event_values else None), - "sourceCounter": Counter({_norm(key): _safe_int(value) for key, value in source_rows}), - "threatTypeCounter": threat_type_counter, - **profile_counters, - "seriesRaw": timeline["raw"], - "seriesUnique": timeline["unique"], - "_seriesTriage": timeline["triage"], - "_seriesAttack": timeline["attack"], - "_timelineLabels": timeline["labels"], - "_timelineWindow": timeline["window"], - "workflowCallCount": workflow_call_count, - } - - -def _timeline_spec(dates, start_time, end_time): - if start_time > 0 and end_time > 0: - bucket_start = start_time - bucket_end = end_time - else: - bucket_start = int(datetime.strptime(min(dates), "%Y-%m-%d").timestamp()) - bucket_end = int( - (datetime.strptime(max(dates), "%Y-%m-%d") + timedelta(days=1)).timestamp() - ) - 1 - span = max(bucket_end - bucket_start + 1, 1) - if span <= 30 * 60: - bucket_seconds, window = 60, "按分钟真实分布" - elif span <= 2 * 60 * 60: - bucket_seconds, window = 5 * 60, "按 5 分钟真实分布" - elif span <= 24 * 60 * 60: - bucket_seconds, window = 60 * 60, "按小时真实分布" - elif span <= 7 * 24 * 60 * 60: - bucket_seconds, window = 6 * 60 * 60, "按 6 小时真实分布" - else: - bucket_seconds, window = 24 * 60 * 60, "按天真实分布" - bucket_count = max(1, min(math.ceil(span / bucket_seconds), 60)) - labels = [] - for index in range(bucket_count): - point = datetime.fromtimestamp(bucket_start + index * bucket_seconds) - if bucket_seconds >= 24 * 60 * 60: - labels.append(point.strftime("%m-%d")) - elif bucket_seconds >= 60 * 60: - labels.append(point.strftime("%m-%d %H:%M")) - else: - labels.append(point.strftime("%H:%M")) - return bucket_start, bucket_seconds, bucket_count, labels, window - - -def _sqlite_timeline(conn, settings, where_clause, query_params, dates, start_time, end_time): - bucket_start, bucket_seconds, bucket_count, labels, window = _timeline_spec( - dates, - start_time, - end_time, - ) - rows = conn.execute( - f"SELECT CAST((event_time - ?) / ? AS INTEGER) AS bucket_index, " - f"COUNT(*) AS raw_count, " - f"COALESCE(SUM(CASE WHEN is_duplicate = 0 THEN 1 ELSE 0 END), 0) AS unique_count, " - f"COALESCE(SUM(has_triage), 0) AS triage_count, " - f"COALESCE(SUM(CASE WHEN has_triage = 1 " - f"AND LOWER(triage_status) NOT IN ('failed', 'error') " - f"AND LOWER(triage_attack_verdict) = 'attack' " - f"THEN 1 ELSE 0 END), 0) AS attack_count " - f"FROM {settings['facts_table']} WHERE {where_clause} AND event_time IS NOT NULL " - f"GROUP BY bucket_index ORDER BY bucket_index", - (bucket_start, bucket_seconds, *query_params), - ).fetchall() - raw = [0] * bucket_count - unique = [0] * bucket_count - triage = [0] * bucket_count - attack = [0] * bucket_count - for row in rows: - index = _safe_int(row[0]) - if 0 <= index < bucket_count: - raw[index] = _safe_int(row[1]) - unique[index] = _safe_int(row[2]) - triage[index] = _safe_int(row[3]) - attack[index] = _safe_int(row[4]) - return { - "raw": raw, - "unique": unique, - "triage": triage, - "attack": attack, - "labels": labels, - "window": window, - } - - -def _sqlite_detail_counters(conn, settings, where_clause, query_params): - table = settings["facts_table"] - cache_key = ( - str(settings["db_path"]), - table, - tuple(query_params), - _file_revision(Path(f"{settings['db_path']}-wal")), - ) - revision = conn.execute( - f"SELECT COALESCE(MAX(alert_row_id), 0), COALESCE(MAX(triage_persisted_at), '') " - f"FROM {table} WHERE {where_clause}", - query_params, - ).fetchone() - latest_row_id = _safe_int(revision[0]) - latest_triage_at = str(revision[1] or "") - with _cache_lock: - cached = _denoise_detail_cache.get(cache_key) or {} - if cached: - _denoise_detail_cache.move_to_end(cache_key) - if ( - cached - and latest_row_id == _safe_int(cached.get("lastRowId")) - and latest_triage_at == str(cached.get("lastTriagePersistedAt") or "") - and time.monotonic() - float(cached.get("updatedAt") or 0) < _DENOISE_DETAIL_CACHE_TTL - ): - return ( - {key: Counter(value) for key, value in cached["profileCounters"].items()}, - Counter(cached["threatTypeCounter"]), - ) - - rows = conn.execute( - f"SELECT phase, direction, result, protocol, severity, response_code, " - f"port, threat_type, COUNT(*) AS profile_count FROM {table} " - f"WHERE {where_clause} " - f"GROUP BY 1, 2, 3, 4, 5, 6, 7, 8", - query_params, - ).fetchall() - profile_counters = _new_profile_counters() - profile_keys = ( - "phaseCounter", - "directionCounter", - "resultCounter", - "protocolCounter", - "severityCounter", - "responseCounter", - ) - threat_type_counter = Counter() - for row in rows: - count = _safe_int(row[8]) - for index, key in enumerate(profile_keys): - profile_counters[key][_norm(row[index])] += count - port_value = row[6] - port = str(_safe_int(port_value)) if _safe_int(port_value) > 0 else _norm(port_value) - profile_counters["portCounter"][port] += count - threat_type_counter[_norm(row[7])] += count - with _cache_lock: - _denoise_detail_cache[cache_key] = { - "lastRowId": latest_row_id, - "lastTriagePersistedAt": latest_triage_at, - "updatedAt": time.monotonic(), - "profileCounters": {key: Counter(value) for key, value in profile_counters.items()}, - "threatTypeCounter": Counter(threat_type_counter), - } - _denoise_detail_cache.move_to_end(cache_key) - while len(_denoise_detail_cache) > _DENOISE_DETAIL_CACHE_MAX: - _denoise_detail_cache.popitem(last=False) - return profile_counters, threat_type_counter - - -def _read_sqlite_triage(paths): - settings = _sqlite_settings() - dates = sorted({path.date for path in paths}) - if not dates: - return None - placeholders = ",".join("?" for _ in dates) - where_clause = f"asset_date IN ({placeholders})" - query_params = list(dates) - start_time = min((path.start_time for path in paths if path.start_time > 0), default=0) - end_time = max((path.end_time for path in paths if path.end_time > 0), default=0) - if start_time > 0 and end_time > 0: - where_clause += " AND event_time BETWEEN ? AND ?" - query_params.extend((start_time, end_time)) - triage_where = f"{where_clause} AND has_triage = 1" - cache_condition = "(LOWER(triage_source) = 'cache' OR LOWER(triage_status) = 'cached')" - follower_condition = ( - "(LOWER(triage_source) IN ('follower', 'followers', 'follower_reused') " - "OR LOWER(triage_status) = 'follower_reused')" - ) - failed_condition = "LOWER(triage_status) IN ('failed', 'error')" - new_triage_condition = ( - f"NOT {cache_condition} AND NOT {follower_condition} AND NOT ({failed_condition})" - ) - try: - with sqlite3.connect(settings["db_path"]) as conn: - row = conn.execute( - f"SELECT COUNT(*), " - f"COALESCE(SUM(CASE WHEN {cache_condition} THEN 1 ELSE 0 END), 0), " - f"COALESCE(SUM(CASE WHEN {follower_condition} THEN 1 ELSE 0 END), 0), " - f"COALESCE(SUM(CASE WHEN {failed_condition} " - f"THEN 1 ELSE 0 END), 0), " - f"COALESCE(SUM(CASE WHEN {new_triage_condition} " - f"THEN 1 ELSE 0 END), 0), " - f"COALESCE(SUM(CASE WHEN LOWER(triage_attack_verdict) = 'attack' " - f"AND LOWER(triage_attack_success) = 'success' THEN 1 ELSE 0 END), 0), " - f"COALESCE(SUM(CASE WHEN LOWER(triage_attack_verdict) = 'attack' " - f"AND LOWER(triage_attack_success) NOT IN ('success', 'failed') " - f"THEN 1 ELSE 0 END), 0), " - f"COALESCE(SUM(CASE WHEN LOWER(triage_attack_verdict) = 'attack' " - f"AND LOWER(triage_attack_success) = 'failed' " - f"THEN 1 ELSE 0 END), 0), " - f"COALESCE(SUM(CASE WHEN LOWER(triage_attack_verdict) = 'non_attack' " - f"THEN 1 ELSE 0 END), 0), " - f"COALESCE(SUM(CASE WHEN LOWER(triage_attack_verdict) " - f"NOT IN ('attack', 'non_attack') " - f"THEN 1 ELSE 0 END), 0), MIN(event_time), MAX(event_time), " - f"COALESCE(ROUND(AVG(CASE WHEN triage_ms > 0 THEN triage_ms END)), 0) " - f"FROM {settings['facts_table']} WHERE {triage_where}", - query_params, - ).fetchone() - source_rows = conn.execute( - f"SELECT source_type, COUNT(*) FROM {settings['facts_table']} " - f"WHERE {triage_where} GROUP BY source_type", - query_params, - ).fetchall() - threat_type_rows = conn.execute( - f"SELECT threat_type, COUNT(*) FROM {settings['facts_table']} " - f"WHERE {triage_where} GROUP BY threat_type", - query_params, - ).fetchall() - risk_rows = conn.execute( - f"SELECT risk_level, COUNT(*) FROM {settings['facts_table']} " - f"WHERE {triage_where} GROUP BY risk_level", - query_params, - ).fetchall() - status_rows = conn.execute( - f"SELECT COALESCE(NULLIF(triage_status, ''), triage_source), COUNT(*) " - f"FROM {settings['facts_table']} WHERE {triage_where} GROUP BY 1", - query_params, - ).fetchall() - profile_rows = conn.execute( - f"SELECT phase, direction, result, protocol, severity, response_code, port, COUNT(*) " - f"FROM {settings['facts_table']} WHERE {triage_where} " - f"GROUP BY 1, 2, 3, 4, 5, 6, 7", - query_params, - ).fetchall() - except Exception: - return None - - total_records = _safe_int(row[0]) - cache_hit = _safe_int(row[1]) - followers_reused = _safe_int(row[2]) - triage_failed = _safe_int(row[3]) - new_triaged = _safe_int(row[4]) - attack_success = _safe_int(row[5]) - attack = _safe_int(row[6]) - attack_failed = _safe_int(row[7]) - benign = _safe_int(row[8]) - unknown = _safe_int(row[9]) - attack_total = attack_success + attack + attack_failed - avg_triage_ms = _safe_int(row[12]) - profile_counters = _new_profile_counters() - profile_keys = ( - "phaseCounter", - "directionCounter", - "resultCounter", - "protocolCounter", - "severityCounter", - "responseCounter", - ) - for profile_row in profile_rows: - count = _safe_int(profile_row[7]) - for index, key in enumerate(profile_keys): - profile_counters[key][_norm(profile_row[index])] += count - port_value = profile_row[6] - port = str(_safe_int(port_value)) if _safe_int(port_value) > 0 else _norm(port_value) - profile_counters["portCounter"][port] += count - return { - "totalRecords": total_records, - "batchTotal": 0, - "newTriaged": new_triaged, - "cacheHit": cache_hit, - "triageFailed": triage_failed, - "followersReused": followers_reused, - "attackTotal": attack_total, - "attackSuccess": attack_success, - "attack": attack, - "attackFailed": attack_failed, - "benign": benign, - "unknown": unknown, - "attackRate": _ratio(attack_total, total_records), - "successRate": _ratio(attack_success, attack_total), - "cacheRate": _ratio(cache_hit + followers_reused, total_records), - "coverageRate": _ratio(total_records - triage_failed, total_records), - "avgTriageMs": avg_triage_ms, - "headers": 0, - "files": len(paths), - "parseErrors": 0, - "eventStart": _format_event_time(_parse_event_time(row[10])), - "eventEnd": _format_event_time(_parse_event_time(row[11])), - "sourceCounter": Counter({_norm(key): _safe_int(value) for key, value in source_rows}), - "threatTypeCounter": Counter( - {_norm(key): _safe_int(value) for key, value in threat_type_rows} - ), - "riskCounter": Counter({_norm(key): _safe_int(value) for key, value in risk_rows}), - "statusCounter": Counter({_norm(key): _safe_int(value) for key, value in status_rows}), - **profile_counters, - "seriesTotal": [], - "seriesAttack": [], - } - - def _read_triage(paths): - if paths and all(isinstance(path, _RecordSource) and path.data_source == "sqlite" for path in paths): - optimized = _read_sqlite_triage(paths) + if paths and all(_is_store_source(path) for path in paths): + optimized = _data().read_triage(paths) if optimized is not None: return optimized total_records = 0 @@ -3682,82 +910,11 @@ def _port_label(value): def _iter_source_records(path, *, triage_only=False): - if isinstance(path, _RecordSource) and path.data_source == "sqlite": - yield from _iter_sqlite_records(path, triage_only=triage_only) + if _is_store_source(path): + yield from _data().iter_records(path, triage_only=triage_only) return -def _iter_sqlite_records(source, *, triage_only=False): - settings = _sqlite_settings() - time_filter = "" - query_params = [source.date] - if source.start_time > 0 and source.end_time > 0: - time_filter = f" AND {settings['event_time_column']} BETWEEN ? AND ?" - query_params.extend((source.start_time, source.end_time)) - triage_filter = "" - if triage_only: - triage_filter = ( - f" AND (NULLIF(json_extract({settings['record_column']}, '$.triage_status'), '') IS NOT NULL " - f"OR NULLIF(json_extract({settings['record_column']}, '$._triage_persisted_at'), '') IS NOT NULL " - f"OR json_extract({settings['record_column']}, '$.triage_report') IS NOT NULL)" - ) - query = ( - f"SELECT {settings['record_column']} AS record_json " - f"FROM {settings['table']} " - f"WHERE {settings['date_column']} = ?{time_filter}{triage_filter} " - f"ORDER BY {settings['event_time_column']}, rowid" - ) - try: - with sqlite3.connect(settings["db_path"]) as conn: - cursor = conn.execute(query, query_params) - for row in cursor: - try: - payload = json.loads(row[0]) - except Exception: - yield None - continue - if isinstance(payload, dict): - yield payload - elif isinstance(payload, list): - yield from _iter_json_payload(payload) - else: - yield None - except Exception: - return - - -def _iter_json_payload(payload): - if isinstance(payload, list): - for item in payload: - yield item if isinstance(item, dict) else None - return - - if not isinstance(payload, dict): - yield None - return - - records = None - for key in ("records", "data", "items", "rows"): - value = payload.get(key) - if isinstance(value, list): - records = value - break - - if records is None: - yield payload - return - - header = { - key: value - for key, value in payload.items() - if key not in {"records", "data", "items", "rows"} - } - if header: - yield {"_type": "file_header", **header} - for item in records: - yield item if isinstance(item, dict) else None - - def _without_counters(payload): return { key: value @@ -3776,7 +933,7 @@ def _counter_items(counter, limit): def _file_brief(path): - if isinstance(path, _RecordSource): + if _is_store_source(path): stat = path.path.stat() if path.path.exists() else None return { "name": f"{path.path.name}:{path.date}", @@ -3798,6 +955,9 @@ def _file_brief(path): def _display_path(path): + if not Path(path).is_absolute(): + # A store that is not a file (a table of the platform's database) is named, not located. + return str(path) try: return "~/" + str(Path(path).resolve().relative_to(Path.home())).replace("\\", "/") except Exception: @@ -3805,7 +965,7 @@ def _display_path(path): def _source_label(path): - if isinstance(path, _RecordSource): + if _is_store_source(path): return f"{_display_path(path.path)}:{path.date}" return _display_path(path) diff --git a/.flocks/flockshub/plugins/webuis/soc_ui/soc_dashboard/src/Page.tsx b/.flocks/flockshub/plugins/webuis/soc_ui/soc_dashboard/src/Page.tsx index fd86a83ac..4a14f2561 100644 --- a/.flocks/flockshub/plugins/webuis/soc_ui/soc_dashboard/src/Page.tsx +++ b/.flocks/flockshub/plugins/webuis/soc_ui/soc_dashboard/src/Page.tsx @@ -1938,8 +1938,8 @@ function activitySourceBadge(event) { return { label: '告警记录', title: event.alert?.sourceType - ? `来源:soc.db 告警记录 · ${String(event.alert.sourceType).toUpperCase()}` - : '来源:soc.db 告警记录', + ? `来源:告警库记录 · ${String(event.alert.sourceType).toUpperCase()}` + : '来源:告警库记录', }; } diff --git a/.flocks/flockshub/plugins/webuis/soc_ui/soc_overview/api/handlers.py b/.flocks/flockshub/plugins/webuis/soc_ui/soc_overview/api/handlers.py index e9ce6c15c..1fe329733 100644 --- a/.flocks/flockshub/plugins/webuis/soc_ui/soc_overview/api/handlers.py +++ b/.flocks/flockshub/plugins/webuis/soc_ui/soc_overview/api/handlers.py @@ -1,101 +1,64 @@ +"""SOC overview page API. + +flocks-soc-store-client: this file holds no database code. The alert records +come from the platform's SOC data service (``ctx.services.soc.overview``, the +``flocks.workflow.soc_store`` of the database backend in use), so the same +file serves every backend. +""" + import json -import os import re -import sqlite3 +import threading import time from collections import Counter -from dataclasses import dataclass from datetime import datetime, timedelta from pathlib import Path DATE_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$") -SQL_IDENTIFIER_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$") CONTRACTS_ROOT = Path(__file__).resolve().parents[4] ACCESS_CONFIG_PATH = CONTRACTS_ROOT / "access" / "soc_alerts.json" -DEFAULT_DATA_SOURCE = "sqlite" -DEFAULT_SQLITE_DB = Path.home() / ".flocks" / "data" / "soc.db" -DEFAULT_SQLITE_TABLE = "alert_records" -DEFAULT_SQLITE_RECORD_COLUMN = "record_json" -DEFAULT_SQLITE_DATE_COLUMN = "asset_date" -DEFAULT_SQLITE_EVENT_TIME_COLUMN = "event_time" -WORKFLOW_DB = Path.home() / ".flocks" / "data" / "workflow.db" +# The platform's SOC overview data service, bound by each request. +_store = None +# What one request settled on, so its aggregates read the settings file once. +_request = threading.local() -_workflow_stats_cache: dict = {} -_cache_updated_at: float = 0 -_CACHE_TTL: float = 30.0 +def _bind(ctx): + """Take the SOC data service the platform hands this page.""" + global _store + soc = getattr(getattr(ctx, "services", None), "soc", None) + if soc is None: + # Not called by the page runtime: the SOC query tool loads this file itself. + try: + from flocks.workflow import soc_store + except ImportError as exc: + raise RuntimeError( + "The SOC overview needs the SOC data service of the platform; update Flocks to a version that has it" + ) from exc + soc = soc_store.page_service() + _store = soc.overview + return _store -@dataclass(frozen=True) -class _RecordSource: - path: Path - role: str - date: str - data_source: str - record_count: int = 0 - start_time: int | None = None - end_time: int | None = None +def _data(): + if _store is None: + return _bind(None) + return _store -def _get_workflow_call_count(workflow_name: str, date: str = None) -> int: - global _workflow_stats_cache, _cache_updated_at - now = time.time() - cache_key = f"{workflow_name}:{date or 'total'}" - if now - _cache_updated_at < _CACHE_TTL and cache_key in _workflow_stats_cache: - return _workflow_stats_cache[cache_key] +def _source_settings(): + """Where the alert records are, as the data service reads the suite's settings file.""" + settings = getattr(_request, "settings", None) + if settings is None: + settings = _data().settings(_load_alerts_config(), ACCESS_CONFIG_PATH.parent) + return settings - empty = {"callCount": 0, "dupCount": 0, "uniqueCount": 0} - if not WORKFLOW_DB.is_file(): - return empty - try: - if date: - start = int(datetime.strptime(date, "%Y-%m-%d").timestamp() * 1000) - end = start + 86400 * 1000 - with sqlite3.connect(WORKFLOW_DB) as conn: - rows = conn.execute( - """ - SELECT output_results - FROM workflow_executions - WHERE workflow_id = ? AND started_at >= ? AND started_at < ? - """, - (workflow_name, start, end), - ).fetchall() - dup_count = 0 - unique_count = 0 - for (output_text,) in rows: - try: - output = json.loads(output_text or "{}") - except Exception: - output = {} - stats = output.get("stats") if isinstance(output.get("stats"), dict) else {} - raw = _safe_int(stats.get("raw_count")) - if "after_dedup_count" in stats and stats.get("after_dedup_count") is not None: - unique_count += _safe_int(stats.get("after_dedup_count")) - else: - unique_count += raw - if output.get("is_duplicate") is True: - dup_count += 1 - result_dict = { - "callCount": len(rows), - "dupCount": dup_count, - "uniqueCount": unique_count, - } - else: - with sqlite3.connect(WORKFLOW_DB) as conn: - row = conn.execute( - "SELECT call_count FROM workflow_stats WHERE workflow_id = ?", - (workflow_name,), - ).fetchone() - result_dict = {"callCount": _safe_int(row[0] if row else 0), "dupCount": 0, "uniqueCount": 0} - - _workflow_stats_cache[cache_key] = result_dict - _cache_updated_at = now - return result_dict - except Exception: - return _workflow_stats_cache.get(cache_key, empty) +def _is_store_source(path): + """Whether *path* is a set of records in the alert store (what find_sources lists), not a file.""" + return hasattr(path, "data_source") SOURCE_DEFS = [ @@ -191,6 +154,16 @@ def _has_triage_result(record): def get_stats(ctx, request): + _bind(ctx) + _request.settings = None + _request.settings = _source_settings() + try: + return _get_stats(request) + finally: + _request.settings = None + + +def _get_stats(request): start_time, end_time = _normalize_time_range( request.query_params.get("startTime"), request.query_params.get("endTime"), @@ -222,12 +195,12 @@ def get_stats(ctx, request): sample_mode = bool(asset_denoise_files or asset_triage_files) if asset_denoise_files: denoise_files = asset_denoise_files - # alert_records holds the triaged first-seen alerts, so the same rows carry + # The alert store holds the triaged first-seen alerts, so the same rows carry # the model verdicts the triage statistics are built from (as on the # posture dashboard). Nothing is estimated when a field is missing. triage_files = asset_triage_files or asset_denoise_files - workflow_stats = _get_workflow_call_count("stream_alert_denoise", date=start_date) + workflow_stats = _data().workflow_call_count("stream_alert_denoise", date=start_date) denoise = _read_denoise(denoise_files) triage = _read_triage(triage_files) sources = _build_sources(denoise["sourceCounter"] or triage["sourceCounter"]) @@ -236,6 +209,7 @@ def get_stats(ctx, request): date_range = _build_date_range(start_date, end_date, asset_files) event_range = _build_event_range(date_range, denoise, triage) + source_status = _data().source_status(_source_settings()) return { "date": start_date, "dateRange": date_range, @@ -243,14 +217,14 @@ def get_stats(ctx, request): "generatedAt": datetime.now().isoformat(timespec="seconds"), "latencyMs": round((time.time() - started) * 1000), "sourceStatus": { - "workflowStatsDb": _display_path(WORKFLOW_DB), + "workflowStatsDb": _display_path(source_status["workflowStatsDb"]), "workflowStats": workflow_stats, "sampleMode": sample_mode, "sampleFile": ", ".join(_source_label(path) for path in asset_files) if sample_mode else "", "assets": { - "path": _display_path(_active_source_path()), - "exists": _active_source_exists(), - "dataSource": _active_data_source(), + "path": _display_path(source_status["path"]), + "exists": source_status["exists"], + "dataSource": source_status["dataSource"], "config": _display_path(ACCESS_CONFIG_PATH), "fileCount": len(asset_files), "availableDates": _available_asset_dates(), @@ -337,11 +311,11 @@ def _date_span(start_date, end_date): def _find_asset_files(start_date, end_date, start_time=None, end_time=None): - return _find_sqlite_sources(start_date, end_date, start_time, end_time) + return _data().find_sources(_source_settings(), start_date, end_date, start_time, end_time) def _asset_file_date(path): - if isinstance(path, _RecordSource): + if _is_store_source(path): return path.date return "" @@ -352,41 +326,19 @@ def _latest_asset_date(): def _available_asset_dates(): - return _available_sqlite_dates() + return _data().available_dates(_source_settings()) def _load_alerts_config(): - raw = {} + """The suite's alert settings file as it is; the data service reads the part meant for its store.""" if ACCESS_CONFIG_PATH.is_file(): try: value = json.loads(ACCESS_CONFIG_PATH.read_text(encoding="utf-8")) except Exception: value = {} if isinstance(value, dict): - raw = value - - sqlite_config = raw.get("sqlite") if isinstance(raw.get("sqlite"), dict) else {} - return { - "dataSource": DEFAULT_DATA_SOURCE, - "sqlite": { - "dbPath": _read_config_string( - os.environ.get("FLOCKS_SOC_ALERTS_SQLITE_DB"), - sqlite_config.get("dbPath"), - str(DEFAULT_SQLITE_DB), - ), - "table": _read_config_string(sqlite_config.get("table"), DEFAULT_SQLITE_TABLE), - "recordColumn": _read_config_string(sqlite_config.get("recordColumn"), DEFAULT_SQLITE_RECORD_COLUMN), - "dateColumn": _read_config_string(sqlite_config.get("dateColumn"), DEFAULT_SQLITE_DATE_COLUMN), - "eventTimeColumn": _read_config_string( - sqlite_config.get("eventTimeColumn"), - DEFAULT_SQLITE_EVENT_TIME_COLUMN, - ), - }, - } - - -def _active_data_source(): - return "sqlite" + return value + return {} def _read_config_string(*values): @@ -396,107 +348,6 @@ def _read_config_string(*values): return "" -def _resolve_config_path(value, fallback): - text = _read_config_string(value, str(fallback)) - path = Path(text).expanduser() - if path.is_absolute(): - return path - return (ACCESS_CONFIG_PATH.parent / path).resolve() - - -def _sqlite_settings(): - config = _load_alerts_config()["sqlite"] - return { - "db_path": _resolve_config_path(config.get("dbPath"), DEFAULT_SQLITE_DB), - "table": _sql_identifier(config.get("table"), DEFAULT_SQLITE_TABLE), - "record_column": _sql_identifier(config.get("recordColumn"), DEFAULT_SQLITE_RECORD_COLUMN), - "date_column": _sql_identifier(config.get("dateColumn"), DEFAULT_SQLITE_DATE_COLUMN), - "event_time_column": _sql_identifier( - config.get("eventTimeColumn"), - DEFAULT_SQLITE_EVENT_TIME_COLUMN, - ), - } - - -def _sql_identifier(value, fallback): - text = _read_config_string(value, fallback) - if not SQL_IDENTIFIER_RE.match(text): - text = fallback - return f'"{text}"' - - -def _active_source_path(): - return _sqlite_settings()["db_path"] - - -def _active_source_exists(): - path = _active_source_path() - return path.is_file() - - -def _find_sqlite_sources(start_date, end_date, start_time=None, end_time=None): - settings = _sqlite_settings() - db_path = settings["db_path"] - if not db_path.is_file(): - return [] - - where = [f"{settings['date_column']} BETWEEN ? AND ?"] - params = [start_date, end_date] - if start_time is not None and end_time is not None: - where.append(f"{settings['event_time_column']} BETWEEN ? AND ?") - params.extend([start_time, end_time]) - - query = ( - f"SELECT {settings['date_column']} AS asset_date, COUNT(*) AS record_count " - f"FROM {settings['table']} " - f"WHERE {' AND '.join(where)} " - f"GROUP BY {settings['date_column']} " - f"ORDER BY {settings['date_column']}" - ) - try: - with sqlite3.connect(db_path) as conn: - rows = conn.execute(query, params).fetchall() - except Exception: - return [] - - sources = [] - for asset_date, record_count in rows: - asset_date = str(asset_date or "") - if not DATE_RE.match(asset_date): - continue - sources.append( - _RecordSource( - path=db_path, - role="denoise", - date=asset_date, - data_source="sqlite", - record_count=int(record_count or 0), - start_time=start_time, - end_time=end_time, - ) - ) - return sources - - -def _available_sqlite_dates(): - settings = _sqlite_settings() - db_path = settings["db_path"] - if not db_path.is_file(): - return [] - query = ( - f"SELECT DISTINCT {settings['date_column']} AS asset_date " - f"FROM {settings['table']} " - f"WHERE {settings['date_column']} IS NOT NULL " - f"ORDER BY {settings['date_column']}" - ) - try: - with sqlite3.connect(db_path) as conn: - rows = conn.execute(query).fetchall() - except Exception: - return [] - return [str(row[0]) for row in rows if DATE_RE.match(str(row[0]))] - - def _build_date_range(start_date, end_date, asset_files): file_dates = sorted({date for date in (_asset_file_date(path) for path in asset_files) if date}) return { @@ -542,7 +393,7 @@ def _timeline_window(start_date, end_date): def _asset_file_role(path): - if isinstance(path, _RecordSource): + if _is_store_source(path): return path.role name = path.name.lower() if "triage" in name or "研判" in name: @@ -1011,76 +862,11 @@ def _port_label(value): def _iter_source_records(path): - if isinstance(path, _RecordSource) and path.data_source == "sqlite": - yield from _iter_sqlite_records(path) + if _is_store_source(path): + yield from _data().iter_records(_source_settings(), path) return -def _iter_sqlite_records(source): - settings = _sqlite_settings() - where = [f"{settings['date_column']} = ?"] - params = [source.date] - if source.start_time is not None and source.end_time is not None: - where.append(f"{settings['event_time_column']} BETWEEN ? AND ?") - params.extend([source.start_time, source.end_time]) - query = ( - f"SELECT {settings['record_column']} AS record_json " - f"FROM {settings['table']} " - f"WHERE {' AND '.join(where)} " - f"ORDER BY {settings['event_time_column']}, rowid" - ) - try: - with sqlite3.connect(settings["db_path"]) as conn: - rows = conn.execute(query, params).fetchall() - except Exception: - return - - for row in rows: - try: - payload = json.loads(row[0]) - except Exception: - yield None - continue - if isinstance(payload, dict): - yield payload - elif isinstance(payload, list): - yield from _iter_json_payload(payload) - else: - yield None - - -def _iter_json_payload(payload): - if isinstance(payload, list): - for item in payload: - yield item if isinstance(item, dict) else None - return - - if not isinstance(payload, dict): - yield None - return - - records = None - for key in ("records", "data", "items", "rows"): - value = payload.get(key) - if isinstance(value, list): - records = value - break - - if records is None: - yield payload - return - - header = { - key: value - for key, value in payload.items() - if key not in {"records", "data", "items", "rows"} - } - if header: - yield {"_type": "file_header", **header} - for item in records: - yield item if isinstance(item, dict) else None - - def _without_counters(payload): return { key: value @@ -1099,7 +885,7 @@ def _counter_items(counter, limit): def _file_brief(path): - if isinstance(path, _RecordSource): + if _is_store_source(path): stat = path.path.stat() if path.path.exists() else None return { "name": f"{path.path.name}:{path.date}", @@ -1121,6 +907,9 @@ def _file_brief(path): def _display_path(path): + if not Path(path).is_absolute(): + # A store that is not a file (a table of the platform's database) is named, not located. + return str(path) try: return "~/" + str(Path(path).resolve().relative_to(Path.home())).replace("\\", "/") except Exception: @@ -1128,7 +917,7 @@ def _display_path(path): def _source_label(path): - if isinstance(path, _RecordSource): + if _is_store_source(path): return f"{_display_path(path.path)}:{path.date}" return _display_path(path) diff --git a/.flocks/flockshub/plugins/webuis/soc_ui/workspace.json b/.flocks/flockshub/plugins/webuis/soc_ui/workspace.json index ba52621ff..e3240b325 100644 --- a/.flocks/flockshub/plugins/webuis/soc_ui/workspace.json +++ b/.flocks/flockshub/plugins/webuis/soc_ui/workspace.json @@ -1,6 +1,6 @@ { "id": "soc_ui", - "version": "1.1.12.1", + "version": "1.1.13", "title": "SOC 工作区", "titleEn": "SOC Workspace", "icon": "ShieldCheck", diff --git a/.flocks/flockshub/plugins/workflows/stream_alert_triage/config.json b/.flocks/flockshub/plugins/workflows/stream_alert_triage/config.json index 328952bb7..afc7fe263 100644 --- a/.flocks/flockshub/plugins/workflows/stream_alert_triage/config.json +++ b/.flocks/flockshub/plugins/workflows/stream_alert_triage/config.json @@ -1,7 +1,6 @@ { - "_comment": "stream_alert_triage runtime defaults. Workflow inputs override these values.", + "_comment": "stream_alert_triage runtime defaults. Workflow inputs override these values. SOC persistence goes through the platform's alert store, in the database Flocks is configured for; no database location is set here.", "triage_output_mode": "soc_db", - "soc_db_path": "~/.flocks/data/soc.db", "persist_triage_output": false, "jsonl_output_dir": "" } diff --git a/.flocks/flockshub/plugins/workflows/stream_alert_triage/guide.md b/.flocks/flockshub/plugins/workflows/stream_alert_triage/guide.md index 687b49c57..ab2673267 100644 --- a/.flocks/flockshub/plugins/workflows/stream_alert_triage/guide.md +++ b/.flocks/flockshub/plugins/workflows/stream_alert_triage/guide.md @@ -145,10 +145,11 @@ ## 6. 输出与副作用 -默认 SOC DB: +默认 SOC DB:平台的告警库,由 Flocks 的数据库设置决定,工作流里不配置库地址。 ```text -~/.flocks/data/soc.db +SQLite:数据目录下的 soc.db(默认 ~/.flocks/data/soc.db) +PostgreSQL:共享库里的 alert_records 表 ``` 可选 JSONL: diff --git a/.flocks/flockshub/plugins/workflows/stream_alert_triage/manifest.json b/.flocks/flockshub/plugins/workflows/stream_alert_triage/manifest.json index 406602d6d..69d02929e 100644 --- a/.flocks/flockshub/plugins/workflows/stream_alert_triage/manifest.json +++ b/.flocks/flockshub/plugins/workflows/stream_alert_triage/manifest.json @@ -6,7 +6,7 @@ "nameCn": "HTTP研判工作流", "description": "Downstream alert triage workflow that writes triage results to SOC DB by default with optional JSONL output.", "descriptionCn": "下游告警研判工作流,默认写入 SOC DB,并保留 JSONL 输出配置。", - "version": "1.1.2.1", + "version": "1.2.0", "author": "Flocks Team", "license": "MIT", "homepage": "", diff --git a/.flocks/flockshub/plugins/workflows/stream_alert_triage/meta.json b/.flocks/flockshub/plugins/workflows/stream_alert_triage/meta.json index 08b32d2d2..55828cbbb 100644 --- a/.flocks/flockshub/plugins/workflows/stream_alert_triage/meta.json +++ b/.flocks/flockshub/plugins/workflows/stream_alert_triage/meta.json @@ -1,7 +1,7 @@ { "name": "stream_alert_triage", "nameCn": "HTTP研判工作流", - "description": "Self-contained downstream pipeline for stream_alert_denoise. Loads enriched_alerts from JSONL files written by stream_alert_denoise, then runs leader/follower concurrent triage with the tdp_alert_triage logic INLINED (no sub-workflow invocation). Alerts sharing the same dedup_key in a batch form groups; only the LEADER (first occurrence) is triaged, FOLLOWERS reuse the leader result with no extra LLM calls. Each alert keeps the 4 LLM analysis branches (survey / cve_related / cve_info / payload_analysis), while every llm.ask call shares the run-wide concurrency budget so nested executors cannot multiply provider load. The semantic-tagged markdown verdict report is attached to each alert via the `triage_report` field — NO per-alert markdown file is written to disk. Persistent cache (triage_cache.pkl, FIFO LRU, file-locked, atomic write): historic dedup_key hits reuse the cached verdict/title/triage_report instantly; misses run the full inline triage and persist new results. Default persistence writes enriched triage alerts into ~/.flocks/data/soc.db alert_records; optional JSONL output is controlled by config.json or triage_output_mode=jsonl/both.", + "description": "Self-contained downstream pipeline for stream_alert_denoise. Loads enriched_alerts from JSONL files written by stream_alert_denoise, then runs leader/follower concurrent triage with the tdp_alert_triage logic INLINED (no sub-workflow invocation). Alerts sharing the same dedup_key in a batch form groups; only the LEADER (first occurrence) is triaged, FOLLOWERS reuse the leader result with no extra LLM calls. Each alert keeps the 4 LLM analysis branches (survey / cve_related / cve_info / payload_analysis), while every llm.ask call shares the run-wide concurrency budget so nested executors cannot multiply provider load. The semantic-tagged markdown verdict report is attached to each alert via the `triage_report` field — NO per-alert markdown file is written to disk. Persistent cache (triage_cache.pkl, FIFO LRU, file-locked, atomic write): historic dedup_key hits reuse the cached verdict/title/triage_report instantly; misses run the full inline triage and persist new results. Default persistence writes enriched triage alerts through the platform's SOC alert store (alert_records, in the database Flocks is configured for); optional JSONL output is controlled by config.json or triage_output_mode=jsonl/both.", "category": "default", "status": "active", "createdBy": null, diff --git a/.flocks/flockshub/plugins/workflows/stream_alert_triage/workflow.json b/.flocks/flockshub/plugins/workflows/stream_alert_triage/workflow.json index e4b47c12f..e44bee331 100644 --- a/.flocks/flockshub/plugins/workflows/stream_alert_triage/workflow.json +++ b/.flocks/flockshub/plugins/workflows/stream_alert_triage/workflow.json @@ -15,7 +15,7 @@ "id": "concurrent_triage", "type": "python", "description": "Leader/follower 分组并发研判节点(自包含,内联 tdp_alert_triage 逻辑)。先按 dedup_key 把 alerts 分组:每组只对 leader 研判,follower 复用 leader 结果。外层 ThreadPoolExecutor(concurrency) 处理 unique work units(concurrency 取值 1–5,默认 1),单条告警仍执行 survey / cve_related / cve_info / payload_analysis 4 个分支,但所有 llm.ask() 共享运行级 concurrency 预算,总 LLM 峰值不超过 1–5。dedup_key 在 triage_cache.pkl 命中时直接复用历史 verdict/title/triage_report;未命中则 leader 执行完整研判(情报查询 + 4 个 LLM + attack_analysis + verdict + title + 聚合 markdown),完整研判 markdown 仅写入 alert 的 `triage_report` 字段,**不生成任何独立报告文件**。新结果合并写回 cache(FIFO LRU + 文件锁 + 原子落盘)。SOC DB 只接受明确 `is_duplicate=false`、包含 `dedup_key` 且批内首次出现的告警,并通过数据库唯一索引保证跨执行全局唯一;重复 key 只更新研判字段并保留首次事件元数据,持久化失败会使工作流失败。可通过工作流目录 `config.json` 或运行输入将 `triage_output_mode` 切换为 `jsonl` / `both` / `none`,保留 `triage_result_NNN.jsonl` 可选输出。 该节点在短生命周期宿主子进程中执行,结束后由操作系统回收解释器堆。", - "code": "\"\"\"\nconcurrent_triage: leader/follower 分组并发研判 + dedup_key 缓存复用(自包含)。\n\n去重模式:\n 1. 输入 alerts 先按 dedup_key 分组 → unique dedup_keys 列表\n 2. 每个 group 只对 leader(首条)做研判;followers 复用 leader 结果,不重复调 LLM\n 3. 无 dedup_key 的 alert 各自独立成 work unit(防御性研判,无法复用)\n\n并发结构:\n 外层按 3 个 work unit 分批创建 ThreadPoolExecutor,避免整批 future/上下文同时驻留\n (concurrency 取值 1–5,默认 1,由 inputs.concurrency 控制,每批实际 worker 不超过 3)\n 单条 alert 包含 4 个并行分支以及攻击分析、结论、标题、报告 4 个汇总调用\n (survey / cve_related / cve_info / payload_analysis — 保留 tdp_alert_triage\n 的 4 分支研判结构)\n 所有 llm.ask 调用共享运行级信号量,稳态 LLM 峰值不超过 concurrency\n\n模型攻击结论以两个正交维度附加到每条 alert:triage_attack_verdict 表示\n是否攻击(attack / non_attack / unknown),triage_attack_success 表示攻击\n结果(success / failed / unknown)。原始同名字段保持不变;其他研判产物包括 risk_level /\nreport_title / triage_report 等。**不生成任何独立的 per-alert markdown 报告\n文件**,避免冗余落盘与跨日期路径失效。\n\ndedup_key 缓存(与 stream_alert_denoise 的 LSH 状态文件同根目录,逻辑独立):\n ~/.flocks/workspace/workflows/stream_alert_triage/triage_cache.pkl\n - cache 命中:直接复用历史 verdict/title/triage_report,**不调用 LLM**\n - cache 未命中:leader 执行完整内联研判(情报 + 4 个 LLM 分支 + verdict + title + report);\n follower 直接广播 leader 结果\n - 新结果合并写回 cache,FIFO LRU 淘汰,文件锁 + 原子落盘\n\"\"\"\n\nimport ipaddress\nimport json\nimport os\nimport pickle\nimport re\nimport sys\nimport threading\nimport time\nfrom concurrent.futures import ThreadPoolExecutor, as_completed\n\nIS_WINDOWS = sys.platform == 'win32'\nif IS_WINDOWS:\n import msvcrt # noqa: F401\nelse:\n import fcntl # noqa: F401\n\nWORKFLOW_NAME = 'stream_alert_triage'\n\n# Per-call LLM timeout and retry budget for every analysis branch in this\n# node. Workflow LLM calls share the dedicated ``flocks-workflow-llm-loop``;\n# a single hung call (e.g. provider 504, slow TLS handshake) without a\n# timeout would otherwise pin one of the (already concurrency-limited)\n# worker threads for up to httpx's DEFAULT read timeout (10 min), serially\n# blocking the rest of the alert pipeline. 120s + 1 retry covers normal\n# slow-but-alive responses while still recovering from transient hangs.\nLLM_CALL_TIMEOUT_S = 120.0\nLLM_CALL_MAX_RETRIES = 1\n\n# Cache and work scheduling remain bounded without truncating alert or model content.\nMAX_TRIAGE_CACHE_BYTES = 128 * 1024 * 1024\nTRIAGE_SUB_BATCH_SIZE = 3\n\n# The user-facing concurrency setting is a run-wide LLM request budget. The\n# four logical branches still start together, but nested executors must not\n# multiply the actual provider load (5 outer workers used to become 20 calls).\n_llm_slots = None\n\nTRIAGE_FIELDS = (\n 'triage_attack_verdict',\n 'triage_attack_success',\n 'risk_level',\n 'report_title',\n 'triage_report',\n)\nATTACK_VERDICT_CN = {\n 'attack': '攻击',\n 'non_attack': '非攻击',\n 'unknown': '未知',\n}\nATTACK_SUCCESS_CN = {\n 'success': '攻击成功',\n 'failed': '攻击失败',\n 'unknown': '未知',\n}\nOUTCOME_RISK = {\n 'attack_success': 'High',\n 'attack_failed': 'Medium',\n 'attack': 'Medium',\n 'unknown': 'Medium',\n 'non_attack': 'Low',\n}\nOUTCOME_CN = {\n 'attack_success': '攻击成功',\n 'attack_failed': '攻击失败',\n 'attack': '攻击,结果未知',\n 'unknown': '未知',\n 'non_attack': '非攻击',\n}\nTRIAGE_REPORT_VERSION = 'soc.triage.markdown.v1'\nTRIAGE_REPORT_TAGS = (\n 'report_title',\n 'report_meta',\n 'analysis_steps',\n 'triage_conclusion',\n 'attack_payload',\n 'payload_explanation',\n 'response_evidence',\n 'key_evidence',\n 'disposal_recommendation',\n)\n\n\n# ── Cache persistence ─────────────────────────────────────────────────────────\n\ndef _cache_paths():\n configured_state_dir = inputs.get('_triage_state_dir')\n if configured_state_dir:\n from pathlib import Path\n state_dir = Path(os.path.expanduser(str(configured_state_dir)))\n else:\n from flocks.config import Config\n flocks_root = Config().get_global().data_dir.parent\n state_dir = flocks_root / 'workspace' / 'workflows' / WORKFLOW_NAME\n state_dir.mkdir(parents=True, exist_ok=True)\n return str(state_dir / 'triage_cache.pkl'), str(state_dir / 'triage_cache.lock')\n\n\ndef _acquire_lock(lock_path):\n fh = open(lock_path, 'w+')\n try:\n if IS_WINDOWS:\n fh.write('L'); fh.flush(); fh.seek(0)\n while True:\n try:\n msvcrt.locking(fh.fileno(), msvcrt.LK_LOCK, 1); break\n except OSError:\n continue\n else:\n fcntl.flock(fh.fileno(), fcntl.LOCK_EX)\n except BaseException:\n try:\n fh.close()\n except Exception:\n pass\n raise\n return fh\n\n\ndef _release_lock(fh):\n try:\n if IS_WINDOWS:\n try:\n fh.seek(0); msvcrt.locking(fh.fileno(), msvcrt.LK_UNLCK, 1)\n except OSError:\n pass\n else:\n fcntl.flock(fh.fileno(), fcntl.LOCK_UN)\n finally:\n fh.close()\n\n\ndef _batch_lease_path():\n cache_path, _ = _cache_paths()\n return os.path.join(os.path.dirname(cache_path), '.triage_batch.lock')\n\n\ndef _acquire_batch_lease():\n path = _batch_lease_path()\n fd = os.open(path, os.O_RDWR | os.O_CREAT, 0o600)\n try:\n if IS_WINDOWS:\n if os.fstat(fd).st_size == 0:\n os.write(fd, b'0')\n os.fsync(fd)\n os.lseek(fd, 0, os.SEEK_SET)\n msvcrt.locking(fd, msvcrt.LK_NBLCK, 1)\n else:\n fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)\n except OSError as exc:\n os.close(fd)\n raise RuntimeError('production_batch_lease_busy') from exc\n\n try:\n token = f'{os.getpid()}-{threading.get_ident()}-{time.time_ns()}'\n os.ftruncate(fd, 0)\n os.lseek(fd, 0, os.SEEK_SET)\n os.write(fd, token.encode('ascii'))\n os.fsync(fd)\n except BaseException:\n _release_batch_lease(fd)\n raise\n print(f'[triage] acquired production batch lease token={token}')\n return fd, token\n\n\ndef _release_batch_lease(fd):\n if type(fd) is not int or fd < 0:\n return\n try:\n if IS_WINDOWS:\n try:\n os.lseek(fd, 0, os.SEEK_SET)\n msvcrt.locking(fd, msvcrt.LK_UNLCK, 1)\n except OSError:\n pass\n else:\n fcntl.flock(fd, fcntl.LOCK_UN)\n finally:\n os.close(fd)\n\n\ndef _load_cache(cache_path):\n if not os.path.exists(cache_path):\n return {}\n cache_size = os.path.getsize(cache_path)\n if cache_size == 0:\n return {}\n if cache_size > MAX_TRIAGE_CACHE_BYTES:\n quarantine_path = f'{cache_path}.{time.time_ns()}.oversized'\n try:\n os.replace(cache_path, quarantine_path)\n print(f'[triage_cache] WARNING: skipped oversized cache '\n f'({cache_size} bytes > {MAX_TRIAGE_CACHE_BYTES}); '\n f'moved to {quarantine_path}')\n except OSError as e:\n print(f'[triage_cache] WARNING: skipped oversized cache '\n f'({cache_size} bytes > {MAX_TRIAGE_CACHE_BYTES}); '\n f'quarantine failed: {e}')\n return {}\n try:\n with open(cache_path, 'rb') as f:\n c = pickle.load(f)\n if not isinstance(c, dict):\n return {}\n print(f'[triage_cache] loaded {len(c)} entries from {cache_path}')\n return c\n except Exception as e:\n print(f'[triage_cache] WARNING: failed to load ({e}), starting fresh')\n return {}\n\n\n\ndef _save_cache_atomic(cache_path, cache):\n tmp = (\n f'{cache_path}.{os.getpid()}.{threading.get_ident()}.'\n f'{time.time_ns()}.tmp'\n )\n try:\n with open(tmp, 'wb') as f:\n pickle.dump(cache, f)\n f.flush()\n os.fsync(f.fileno())\n os.replace(tmp, cache_path)\n print(f'[triage_cache] saved {len(cache)} entries -> {cache_path}')\n except Exception as exc:\n try:\n if os.path.exists(tmp):\n os.remove(tmp)\n except OSError:\n pass\n raise RuntimeError(f'failed to save triage cache: {exc}') from exc\n\n\ndef _evict_lru(cache, max_keys, max_bytes=None):\n evicted = 0\n excess = len(cache) - max_keys\n if excess > 0:\n for k in list(cache.keys())[:excess]:\n del cache[k]\n evicted += 1\n\n if max_bytes is not None and max_bytes > 0 and cache:\n # Estimate one entry at a time so enforcing the cache budget never\n # creates a second serialized copy of the whole cache in memory.\n entry_sizes = {}\n estimated_bytes = 64\n for key, value in cache.items():\n size = len(pickle.dumps((key, value), protocol=pickle.HIGHEST_PROTOCOL)) + 16\n entry_sizes[key] = size\n estimated_bytes += size\n for key in list(cache.keys()):\n if estimated_bytes <= max_bytes:\n break\n estimated_bytes -= entry_sizes[key]\n del cache[key]\n evicted += 1\n return evicted\n\n\n# ── Runtime output config and persistence targets ──────────────────────────────\n#\n# Defaults are read from ~/.flocks/plugins/workflows/stream_alert_triage/config.json.\n# Runtime inputs override config values. The default mode is soc_db so SOC pages\n# read the same DB-backed dataset. JSONL remains available via config/input:\n# triage_output_mode = soc_db | jsonl | both | none\n# persist_triage_output = true (legacy alias that adds JSONL to soc_db)\n\nimport datetime as _datetime\n\nMAX_RECORDS_PER_FILE = 10000\n_TRIAGE_JSONL_PREFIX = 'triage_result'\n_TRIAGE_COUNTER_FILE = '.triage_counter.json'\n_WORKFLOW_CONFIG_PATH = os.path.expanduser('~/.flocks/plugins/workflows/stream_alert_triage/config.json')\n_DEFAULT_SOC_DB_PATH = os.path.expanduser('~/.flocks/data/soc.db')\n\n\ndef _load_workflow_config():\n try:\n with open(_WORKFLOW_CONFIG_PATH, 'r', encoding='utf-8') as f:\n cfg = json.load(f)\n if isinstance(cfg, dict):\n return cfg\n except FileNotFoundError:\n pass\n except Exception as e:\n print(f'[triage_config] WARNING: failed to read {_WORKFLOW_CONFIG_PATH}: {e}')\n return {}\n\n\ndef _configured_value(config, key, default=None):\n if key in inputs:\n value = inputs.get(key)\n if value is not None and not (isinstance(value, str) and not value.strip()):\n return value\n return config.get(key, default)\n\n\ndef _input_bool(value, default=False):\n if value is None:\n return default\n if isinstance(value, bool):\n return value\n if isinstance(value, (int, float)):\n return bool(value)\n text = str(value).strip().lower()\n if text in {'1', 'true', 'yes', 'y', 'on'}:\n return True\n if text in {'0', 'false', 'no', 'n', 'off'}:\n return False\n return default\n\n\ndef _select_first_seen_soc_alerts(alerts):\n selected = []\n seen_dedup_keys = set()\n stats = {\n 'input_rows': len(alerts),\n 'first_seen_rows': 0,\n 'skipped_not_first_seen_rows': 0,\n 'skipped_missing_dedup_key_rows': 0,\n 'skipped_repeated_dedup_key_rows': 0,\n }\n for alert in alerts:\n if not isinstance(alert, dict) or _input_bool(alert.get('is_duplicate'), True):\n stats['skipped_not_first_seen_rows'] += 1\n continue\n dedup_key = str(alert.get('dedup_key') or '').strip()\n if not dedup_key:\n stats['skipped_missing_dedup_key_rows'] += 1\n continue\n if dedup_key in seen_dedup_keys:\n stats['skipped_repeated_dedup_key_rows'] += 1\n continue\n seen_dedup_keys.add(dedup_key)\n selected.append(alert)\n stats['first_seen_rows'] = len(selected)\n return selected, stats\n\n\ndef _resolve_output_config():\n config = _load_workflow_config()\n raw_mode = str(_configured_value(config, 'triage_output_mode', 'soc_db') or 'soc_db').strip().lower()\n mode_alias = {\n 'db': 'soc_db',\n 'sqlite': 'soc_db',\n 'sqlite_db': 'soc_db',\n 'soc': 'soc_db',\n 'json': 'jsonl',\n 'file': 'jsonl',\n 'files': 'jsonl',\n 'off': 'none',\n 'disabled': 'none',\n }\n requested_mode = mode_alias.get(raw_mode, raw_mode)\n if requested_mode not in {'soc_db', 'jsonl', 'both', 'none'}:\n print(f'[triage_config] WARNING: invalid triage_output_mode={raw_mode!r}; using soc_db')\n requested_mode = 'soc_db'\n\n legacy_jsonl = _input_bool(_configured_value(config, 'persist_triage_output', False), False)\n write_soc_db = requested_mode in {'soc_db', 'both'}\n write_jsonl = requested_mode in {'jsonl', 'both'}\n effective_mode = requested_mode\n if requested_mode == 'soc_db' and legacy_jsonl:\n write_jsonl = True\n effective_mode = 'both'\n if requested_mode == 'none':\n write_soc_db = False\n write_jsonl = False\n effective_mode = 'none'\n\n soc_db_path = os.path.expanduser(str(\n _configured_value(config, 'soc_db_path', _DEFAULT_SOC_DB_PATH) or _DEFAULT_SOC_DB_PATH\n ))\n jsonl_output_dir = _configured_value(config, 'jsonl_output_dir', '') or ''\n jsonl_output_dir = os.path.expanduser(str(jsonl_output_dir)) if jsonl_output_dir else ''\n return {\n 'config_path': _WORKFLOW_CONFIG_PATH,\n 'requested_mode': requested_mode,\n 'mode': effective_mode,\n 'write_soc_db': write_soc_db,\n 'write_jsonl': write_jsonl,\n 'soc_db_path': soc_db_path,\n 'jsonl_output_dir': jsonl_output_dir,\n }\n\n\n# ── Persisted JSONL output (optional; mirrors stream_alert_denoise layout) ─────\n#\n# Directory : ~/.flocks/workspace/workflows/stream_alert_triage//\n# Filename : triage_result_NNN.jsonl (3-digit zero-padded seq)\n# Layout : line 1 = {\"_type\":\"file_header\", ...}, subsequent lines = one\n# enriched_with_triage alert per line.\n# Counter : .triage_counter.json sidecar tracks (seq, count) so we don't\n# rescan every existing file on each run; auto-rolls over to a\n# new file when reaching MAX_RECORDS_PER_FILE.\n\n\ndef _triage_output_dir(configured_dir=''):\n \"\"\"Return output directory for triage_result_*.jsonl.\"\"\"\n if configured_dir:\n out_dir = configured_dir\n os.makedirs(out_dir, exist_ok=True)\n return out_dir\n from flocks.config import Config\n flocks_root = Config().get_global().data_dir.parent\n date_str = _datetime.datetime.now().strftime('%Y-%m-%d')\n out_dir = flocks_root / 'workspace' / 'workflows' / WORKFLOW_NAME / date_str\n out_dir.mkdir(parents=True, exist_ok=True)\n return str(out_dir)\n\n\ndef _triage_get_counter(out_dir):\n path = os.path.join(out_dir, _TRIAGE_COUNTER_FILE)\n try:\n with open(path, 'r', encoding='utf-8') as f:\n d = json.load(f)\n return int(d.get('seq', 0)), int(d.get('count', 0))\n except Exception:\n return 0, 0\n\n\ndef _triage_set_counter(out_dir, seq, count):\n path = os.path.join(out_dir, _TRIAGE_COUNTER_FILE)\n tmp = path + '.tmp'\n with open(tmp, 'w', encoding='utf-8') as f:\n json.dump({'seq': seq, 'count': count}, f)\n os.replace(tmp, path)\n\n\ndef _triage_find_active_file(out_dir):\n \"\"\"Locate the active (latest, not-yet-full) jsonl file; create if none.\"\"\"\n seq, count = _triage_get_counter(out_dir)\n if seq > 0:\n path = os.path.join(out_dir, f'{_TRIAGE_JSONL_PREFIX}_{seq:03d}.jsonl')\n if os.path.exists(path):\n return path, count, seq\n import glob as _glob\n existing = sorted(_glob.glob(os.path.join(out_dir, _TRIAGE_JSONL_PREFIX + '_*.jsonl')))\n if not existing:\n return None, 0, 0\n latest = existing[-1]\n try:\n seq = int(os.path.basename(latest).replace(_TRIAGE_JSONL_PREFIX + '_', '').replace('.jsonl', ''))\n except ValueError:\n seq = len(existing)\n count = 0\n try:\n with open(latest, 'r', encoding='utf-8') as f:\n for line in f:\n if line.strip() and '\"_type\"' not in line:\n count += 1\n except Exception:\n pass\n return latest, count, seq\n\n\ndef _triage_write_jsonl(out_dir, alerts, run_id, run_stats):\n \"\"\"Append all alerts to today's triage_result_NNN.jsonl, rolling over at\n MAX_RECORDS_PER_FILE. Returns the list of files that were written to.\"\"\"\n now = _datetime.datetime.now()\n written = []\n active_path, active_count, seq = _triage_find_active_file(out_dir)\n remaining = list(alerts)\n while remaining:\n available = MAX_RECORDS_PER_FILE - active_count\n if available <= 0 or active_path is None:\n seq += 1\n active_path = os.path.join(out_dir, f'{_TRIAGE_JSONL_PREFIX}_{seq:03d}.jsonl')\n active_count = 0\n available = MAX_RECORDS_PER_FILE\n header = {\n '_type': 'file_header',\n 'created_at': now.isoformat(),\n 'date': now.strftime('%Y-%m-%d'),\n 'workflow': WORKFLOW_NAME,\n 'seq': seq,\n 'run_id': run_id,\n 'batch_total': run_stats.get('total'),\n 'batch_triaged': run_stats.get('triaged'),\n 'batch_followers_reused':run_stats.get('followers_reused'),\n 'batch_cache_hit': run_stats.get('cache_hit'),\n 'batch_triage_failed': run_stats.get('triage_failed'),\n }\n with open(active_path, 'w', encoding='utf-8') as hf:\n hf.write(json.dumps(header, ensure_ascii=False) + '\\n')\n batch = remaining[:available]\n remaining = remaining[available:]\n with open(active_path, 'a', encoding='utf-8') as af:\n for alert in batch:\n af.write(json.dumps(alert, ensure_ascii=False) + '\\n')\n active_count += len(batch)\n if active_path not in written:\n written.append(active_path)\n if remaining:\n active_path = None\n active_count = 0\n if written:\n _triage_set_counter(out_dir, seq, active_count)\n return written\n\n\n# ── SOC DB output (default) ───────────────────────────────────────────────────\n\ndef _ensure_soc_db_schema(conn):\n conn.execute(\"\"\"\n CREATE TABLE IF NOT EXISTS alert_records (\n row_id TEXT PRIMARY KEY,\n record_id TEXT,\n asset_date TEXT NOT NULL,\n source_file TEXT NOT NULL,\n line_number INTEGER NOT NULL,\n event_time INTEGER,\n source_type TEXT,\n threat_name TEXT,\n dedup_key TEXT,\n is_duplicate INTEGER NOT NULL DEFAULT 0,\n record_json TEXT NOT NULL\n )\n \"\"\")\n columns = {row[1] for row in conn.execute('PRAGMA table_info(alert_records)')}\n dedup_key_added = 'dedup_key' not in columns\n if dedup_key_added:\n conn.execute('ALTER TABLE alert_records ADD COLUMN dedup_key TEXT')\n\n # One row per dedup_key (its first-seen, non-duplicate row), held by a\n # partial unique index. An older non-unique index under that name stays;\n # the unique one then takes the next free name.\n unique_index_name = 'idx_alert_records_first_seen_dedup_key'\n indexes = list(conn.execute('PRAGMA index_list(alert_records)'))\n unique_index_ready = any(\n str(row[1]).startswith(unique_index_name) and bool(row[2]) for row in indexes\n )\n conn.execute('CREATE INDEX IF NOT EXISTS idx_alert_records_duplicate ON alert_records(is_duplicate)')\n has_persisted_duplicates = conn.execute(\"\"\"\n SELECT 1 FROM alert_records\n WHERE is_duplicate = 1\n AND dedup_key IS NOT NULL\n AND dedup_key <> ''\n LIMIT 1\n \"\"\").fetchone() is not None\n if not unique_index_ready or has_persisted_duplicates:\n row_key = \"\"\"NULLIF(TRIM(CASE\n WHEN dedup_key IS NOT NULL AND TRIM(dedup_key) <> '' THEN dedup_key\n WHEN json_valid(record_json) THEN CAST(json_extract(record_json, '$.dedup_key') AS TEXT)\n END), '')\"\"\"\n superseded = f\"\"\"\n WITH keyed AS (\n SELECT rowid AS rid, COALESCE(is_duplicate, 0) AS dup, {row_key} AS dedup\n FROM alert_records\n ),\n keepers AS (\n SELECT MIN(rid) AS rid FROM keyed WHERE dedup IS NOT NULL AND dup = 0 GROUP BY dedup\n ),\n superseded AS (\n SELECT rid FROM keyed WHERE dedup IS NOT NULL AND rid NOT IN (SELECT rid FROM keepers)\n )\n \"\"\"\n if conn.execute(f'{superseded} SELECT 1 FROM superseded LIMIT 1').fetchone() is not None:\n # Followers and duplicates an older version stored under a key are\n # moved to alert_records_superseded instead of being deleted.\n import uuid\n\n conn.execute('CREATE TABLE IF NOT EXISTS alert_records_superseded AS SELECT * FROM alert_records WHERE 0')\n kept = {row[1] for row in conn.execute('PRAGMA table_info(alert_records_superseded)')}\n record_columns = [row[1] for row in conn.execute('PRAGMA table_info(alert_records)')]\n for column, definition in [(column, '') for column in record_columns] + [\n ('source_rowid', ' INTEGER'), ('superseded_batch', ' TEXT'), ('superseded_at', ' TEXT'),\n ]:\n if column not in kept:\n conn.execute(f'ALTER TABLE alert_records_superseded ADD COLUMN \"{column}\"{definition}')\n column_list = ', '.join(f'\"{column}\"' for column in record_columns)\n batch = uuid.uuid4().hex\n conn.execute(f\"\"\"\n {superseded}\n INSERT INTO alert_records_superseded ({column_list}, source_rowid, superseded_batch, superseded_at)\n SELECT {column_list}, rowid, ?, ? FROM alert_records\n WHERE rowid IN (SELECT rid FROM superseded)\n \"\"\", (batch, _datetime.datetime.now().isoformat()))\n # Only the rows just copied, in the same transaction.\n conn.execute(\"\"\"\n DELETE FROM alert_records\n WHERE rowid IN (\n SELECT source_rowid FROM alert_records_superseded WHERE superseded_batch = ?\n )\n \"\"\", (batch,))\n # Every row still holding a key is its key's first-seen row, so the\n # trimmed key (or the one in record_json) cannot collide.\n conn.execute(f'UPDATE alert_records SET dedup_key = {row_key} WHERE dedup_key IS NOT {row_key}')\n if not unique_index_ready:\n taken = {row[1] for row in indexes}\n index_name, suffix = unique_index_name, 1\n while index_name in taken:\n suffix += 1\n index_name = f'{unique_index_name}_{suffix}'\n conn.execute(f\"\"\"\n CREATE UNIQUE INDEX {index_name}\n ON alert_records(dedup_key)\n WHERE dedup_key IS NOT NULL AND dedup_key <> ''\n \"\"\")\n\n conn.execute('CREATE INDEX IF NOT EXISTS idx_alert_records_asset_date ON alert_records(asset_date)')\n conn.execute('CREATE INDEX IF NOT EXISTS idx_alert_records_event_time ON alert_records(event_time)')\n conn.execute('CREATE INDEX IF NOT EXISTS idx_alert_records_source_type ON alert_records(source_type)')\n conn.execute('CREATE INDEX IF NOT EXISTS idx_alert_records_threat_name ON alert_records(threat_name)')\n\n\ndef _event_time_value(alert):\n for key in ('time', 'event_time', 'timestamp', 'timestamp_real', 'occur_time', 'created_at'):\n value = alert.get(key)\n if value in (None, ''):\n continue\n if isinstance(value, (int, float)):\n ts = float(value)\n if ts > 100000000000:\n ts = ts / 1000.0\n return int(ts)\n text = str(value).strip()\n if not text:\n continue\n try:\n ts = float(text)\n if ts > 100000000000:\n ts = ts / 1000.0\n return int(ts)\n except Exception:\n pass\n normalized = text.replace('Z', '+00:00')\n try:\n return int(_datetime.datetime.fromisoformat(normalized).timestamp())\n except Exception:\n pass\n for fmt in ('%Y-%m-%d %H:%M:%S', '%Y/%m/%d %H:%M:%S', '%Y-%m-%d %H:%M', '%Y/%m/%d %H:%M'):\n try:\n return int(_datetime.datetime.strptime(text, fmt).timestamp())\n except Exception:\n continue\n return int(time.time())\n\n\ndef _asset_date_value(alert, event_time):\n value = alert.get('asset_date') or alert.get('_asset_date') or alert.get('date')\n if value:\n text = str(value).strip()\n if re.match(r'^\\d{4}-\\d{2}-\\d{2}$', text):\n return text\n try:\n return _datetime.datetime.fromtimestamp(int(event_time)).strftime('%Y-%m-%d')\n except Exception:\n return _datetime.datetime.now().strftime('%Y-%m-%d')\n\n\ndef _source_type_value(alert):\n for key in ('source_type', '_source_type', 'data_source', 'log_type', 'vendor', 'device_type'):\n value = alert.get(key)\n if value not in (None, ''):\n return str(value)\n return ''\n\n\ndef _record_id_value(alert):\n for key in ('record_id', 'id', 'uuid', 'event_id', 'dedup_key'):\n value = alert.get(key)\n if value not in (None, ''):\n return str(value)\n return ''\n\n\ndef _stable_row_id(alert, source_file, line_number, event_time):\n existing = alert.get('row_id') or alert.get('_row_id')\n if existing:\n return str(existing)\n import hashlib as _hashlib\n basis = {\n 'record_id': _record_id_value(alert),\n 'dedup_key': alert.get('dedup_key', ''),\n 'time': event_time,\n 'source_file': source_file,\n 'line_number': line_number,\n 'sip': alert.get('sip', ''),\n 'sport': alert.get('sport', ''),\n 'dip': alert.get('dip', ''),\n 'dport': alert.get('dport', ''),\n 'threat_rule_id': alert.get('threat_rule_id') or alert.get('rule_id') or '',\n }\n raw = json.dumps(basis, sort_keys=True, ensure_ascii=False)\n return _hashlib.sha256(raw.encode('utf-8')).hexdigest()\n\n\ndef _load_existing_soc_rows(conn, dedup_keys):\n existing = {}\n unique_keys = list(dict.fromkeys(str(key).strip() for key in dedup_keys if str(key).strip()))\n for start in range(0, len(unique_keys), 500):\n chunk = unique_keys[start:start + 500]\n placeholders = ','.join('?' for _ in chunk)\n rows = conn.execute(f\"\"\"\n SELECT row_id, record_id, asset_date, source_file, line_number,\n event_time, source_type, threat_name, dedup_key,\n is_duplicate, record_json\n FROM alert_records\n WHERE dedup_key IN ({placeholders})\n \"\"\", chunk)\n for row in rows:\n try:\n record = json.loads(row[10])\n except Exception:\n record = {}\n if not isinstance(record, dict):\n record = {}\n existing[row[8]] = {\n 'row_id': row[0],\n 'record_id': row[1],\n 'asset_date': row[2],\n 'source_file': row[3],\n 'line_number': row[4],\n 'event_time': row[5],\n 'source_type': row[6],\n 'threat_name': row[7],\n 'record': record,\n }\n return existing\n\n\ndef _merge_triage_record(existing_record, incoming_record):\n merged = dict(existing_record) if isinstance(existing_record, dict) else {}\n triage_fields = (\n 'has_dedup_key',\n 'triage_source',\n 'triage_status',\n 'triage_attack_verdict',\n 'risk_level',\n 'report_title',\n 'triage_report',\n 'triage_attack_success',\n 'triage_ms',\n 'triage_error',\n '_triage_run_id',\n '_triage_persisted_at',\n )\n for key in triage_fields:\n if key in incoming_record:\n merged[key] = incoming_record[key]\n elif key in {'triage_ms', 'triage_error'}:\n merged.pop(key, None)\n return merged\n\n\ndef _triage_write_soc_db(db_path, alerts, run_id):\n import sqlite3\n\n db_dir = os.path.dirname(db_path)\n if db_dir:\n os.makedirs(db_dir, exist_ok=True)\n default_source_file = ''\n loaded_files = inputs.get('loaded_files') or []\n if isinstance(loaded_files, list) and len(loaded_files) == 1:\n default_source_file = str(loaded_files[0])\n\n persisted_at = _datetime.datetime.now().isoformat()\n candidates = []\n seen_dedup_keys = set()\n for idx, alert in enumerate(alerts, 1):\n if not isinstance(alert, dict):\n continue\n dedup_key = str(alert.get('dedup_key') or '').strip()\n if not dedup_key or dedup_key in seen_dedup_keys:\n continue\n seen_dedup_keys.add(dedup_key)\n record = dict(alert)\n record['dedup_key'] = dedup_key\n record['is_duplicate'] = False\n record['_triage_run_id'] = run_id\n record['_triage_persisted_at'] = persisted_at\n source_file = str(\n record.get('source_file')\n or record.get('_source_file')\n or record.get('file_path')\n or default_source_file\n or 'stream_alert_triage'\n )\n try:\n line_number = int(record.get('line_number') or record.get('_line_number') or idx)\n except Exception:\n line_number = idx\n event_time = _event_time_value(record)\n candidates.append({\n 'row_id': _stable_row_id(record, source_file, line_number, event_time),\n 'record_id': _record_id_value(record),\n 'asset_date': _asset_date_value(record, event_time),\n 'source_file': source_file,\n 'line_number': line_number,\n 'event_time': event_time,\n 'source_type': _source_type_value(record),\n 'threat_name': str(record.get('threat_name') or record.get('rule_name') or ''),\n 'dedup_key': dedup_key,\n 'record': record,\n })\n\n insert_rows = []\n update_rows = []\n with sqlite3.connect(db_path, timeout=30) as conn:\n conn.execute('BEGIN IMMEDIATE')\n _ensure_soc_db_schema(conn)\n existing_by_key = _load_existing_soc_rows(\n conn, [candidate['dedup_key'] for candidate in candidates],\n )\n for candidate in candidates:\n existing = existing_by_key.get(candidate['dedup_key'])\n if existing:\n merged_record = _merge_triage_record(existing['record'], candidate['record'])\n merged_record['dedup_key'] = candidate['dedup_key']\n merged_record['is_duplicate'] = False\n update_rows.append((\n candidate['dedup_key'],\n json.dumps(merged_record, ensure_ascii=False),\n existing['row_id'],\n ))\n continue\n insert_rows.append((\n candidate['row_id'],\n candidate['record_id'],\n candidate['asset_date'],\n candidate['source_file'],\n candidate['line_number'],\n candidate['event_time'],\n candidate['source_type'],\n candidate['threat_name'],\n candidate['dedup_key'],\n 0,\n json.dumps(candidate['record'], ensure_ascii=False),\n ))\n\n if insert_rows:\n conn.executemany(\"\"\"\n INSERT INTO alert_records (\n row_id, record_id, asset_date, source_file, line_number,\n event_time, source_type, threat_name, dedup_key,\n is_duplicate, record_json\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n \"\"\", insert_rows)\n if update_rows:\n conn.executemany(\"\"\"\n UPDATE alert_records\n SET dedup_key = ?, is_duplicate = 0, record_json = ?\n WHERE row_id = ?\n \"\"\", update_rows)\n conn.commit()\n\n persisted_rows = len(insert_rows) + len(update_rows)\n return {\n 'path': db_path,\n 'table': 'alert_records',\n 'rows': persisted_rows,\n 'inserted_rows': len(insert_rows),\n 'updated_rows': len(update_rows),\n }\n\n\n# ── LLM provider warm-up (avoid cold-start race in _parallel_4_branches) ──────\n#\n# Background: when this node starts, the LLM provider (e.g. threatbook-cn-llm)\n# is lazy-initialized on the first call. Inside `_parallel_4_branches` we\n# submit 4 LLM calls to a ThreadPoolExecutor simultaneously; whichever one\n# wins the race may race against provider registration and fail with\n# \"provider 'xxx' not exists\" while subsequent calls succeed. A single\n# synchronous warm-up call before any concurrent fan-out forces the provider\n# to finish registering on the main thread, eliminating the race entirely.\n#\n# Failure of the warm-up is non-fatal — we just log and continue. The first\n# real LLM call will still see the same error and surface it normally.\n\ndef _warmup_llm():\n \"\"\"Force LLM provider lazy-init on the main thread before any fan-out.\"\"\"\n t0 = time.time()\n try:\n _ask_llm('ping')\n print(f'[triage] LLM provider warm-up OK in {round((time.time()-t0)*1000)}ms')\n return True\n except Exception as e:\n print(f'[triage] WARNING: LLM warm-up failed ({type(e).__name__}: '\n f'{str(e)[:200]}); proceeding anyway')\n return False\n\n\n# ── Inline triage helpers (mirroring tdp_alert_triage docs version) ───────────\n\ndef _strip_think(text):\n return re.sub(r'[\\s\\S]*?', '', str(text or ''), flags=re.IGNORECASE).strip()\n\n\ndef _is_public_ip(value):\n try:\n ip_obj = ipaddress.ip_address(value)\n except Exception:\n return False\n return not (ip_obj.is_private or ip_obj.is_loopback or ip_obj.is_reserved\n or ip_obj.is_link_local or ip_obj.is_multicast or ip_obj.is_unspecified)\n\n\ndef _pick(*values):\n for v in values:\n if v not in (None, '', [], {}):\n return v\n return ''\n\n\ndef _parse_alert(alert_input):\n \"\"\"Mirrors tdp_alert_triage.receive_alert. Supports three input shapes:\n nested TDP (net.http.url), flat TDP (net_http_url), normalized (req_http_url).\n \"\"\"\n if isinstance(alert_input, str):\n try:\n alert_input = json.loads(alert_input)\n except Exception:\n alert_input = {}\n if isinstance(alert_input, list):\n alert_data = alert_input[0] if alert_input else {}\n elif isinstance(alert_input, dict) and isinstance(alert_input.get('data'), list):\n alert_data = alert_input.get('data', [])[0] if alert_input.get('data') else {}\n else:\n alert_data = alert_input if isinstance(alert_input, dict) else {}\n\n if alert_data.get('_source_type') == 'sangfor-sip':\n from flocks.ingest.syslog.sangfor import parse_sangfor_for_triage\n return parse_sangfor_for_triage(alert_data)\n\n net = alert_data.get('net', {}) or {}\n http = net.get('http', {}) or {}\n threat = alert_data.get('threat', {}) or {}\n assets = alert_data.get('assets', {}) or {}\n\n src_ip = _pick(\n alert_data.get('attacker'), alert_data.get('external_ip'),\n net.get('src_ip'), net.get('flow_src_ip'),\n alert_data.get('net_real_src_ip'),\n alert_data.get('sip'), alert_data.get('src_ip'), alert_data.get('src'),\n )\n dst_ip = _pick(\n alert_data.get('victim'), alert_data.get('machine'),\n alert_data.get('server_ip'), net.get('dest_ip'), net.get('flow_dest_ip'),\n alert_data.get('net_dest_ip'),\n alert_data.get('dip'), alert_data.get('dst_ip'), alert_data.get('dst'),\n )\n src_port = _pick(\n net.get('src_port'), net.get('flow_src_port'),\n alert_data.get('external_port'), alert_data.get('net_src_port'),\n alert_data.get('sport'), alert_data.get('src_port'), 0,\n )\n dst_port = _pick(\n net.get('dest_port'), net.get('flow_dest_port'),\n alert_data.get('server_port'), alert_data.get('machine_port'),\n alert_data.get('net_dest_port'),\n alert_data.get('dport'), alert_data.get('dst_port'), 0,\n )\n protocol = _pick(\n net.get('app_proto'), net.get('type'), net.get('proto'),\n alert_data.get('net_app_proto'), alert_data.get('protocol'),\n alert_data.get('event_type'), 'TCP',\n )\n alert_type = _pick(\n threat.get('name'), alert_data.get('threat_name'),\n alert_data.get('vuln_name'),\n alert_data.get('alert_type'), threat.get('topic'),\n alert_data.get('type'), 'unknown',\n )\n severity = _pick(\n threat.get('severity'), alert_data.get('threat_severity'),\n alert_data.get('severity'), threat.get('level'),\n alert_data.get('level'), 'medium',\n )\n\n req_line = _pick(http.get('reqs_line'), alert_data.get('req_line'), alert_data.get('net_http_reqs_line'))\n req_header = _pick(http.get('reqs_header'), alert_data.get('req_header'), alert_data.get('net_http_reqs_header'))\n req_body = _pick(http.get('req_body'), alert_data.get('req_body'), alert_data.get('net_http_reqs_body'))\n resp_line = _pick(http.get('resp_line'), alert_data.get('rsp_line'), alert_data.get('resp_line'),\n alert_data.get('net_http_resp_line'))\n resp_header = _pick(http.get('resp_header'), alert_data.get('rsp_header'), alert_data.get('resp_header'),\n alert_data.get('net_http_resp_header'))\n resp_body = _pick(http.get('resp_body'), alert_data.get('rsp_body'), alert_data.get('resp_body'),\n alert_data.get('net_http_resp_body'))\n status = _pick(http.get('status'), alert_data.get('http_status'),\n alert_data.get('net_http_status'), alert_data.get('rsp_status_code'), 0)\n\n host = _pick(http.get('reqs_host'), alert_data.get('url_host'), http.get('domain'),\n alert_data.get('req_host'), alert_data.get('net_http_reqs_host'), dst_ip)\n raw_url = _pick(http.get('raw_url'), http.get('url'),\n alert_data.get('url_path'),\n alert_data.get('net_http_url'), alert_data.get('req_http_url'),\n alert_data.get('uri'))\n url = ''\n if host and raw_url:\n scheme = 'https' if net.get('is_https') else 'http'\n url = raw_url if str(raw_url).startswith(('http://', 'https://')) else f'{scheme}://{host}{raw_url}'\n elif raw_url and str(raw_url).startswith(('http://', 'https://')):\n url = raw_url\n elif raw_url:\n url = raw_url\n\n payload = f'请求行: {req_line}\\n请求头: {req_header}\\n请求体: {req_body}'\n response = f'状态行: {resp_line}\\n响应头: {resp_header}\\n响应体: {resp_body}'\n threat_result = _pick(threat.get('result'), alert_data.get('threat_result'))\n threat_msg = _pick(threat.get('msg'), alert_data.get('threat_msg'))\n\n log_text = (\n f'[告警基本信息]\\n'\n f'告警类型: {alert_type}\\n严重级别: {severity}\\n'\n f'源地址: {src_ip}:{src_port}\\n目的地址: {dst_ip}:{dst_port}\\n'\n f'协议: {protocol}\\nURL: {url}\\nHTTP状态码: {status}\\n'\n f'TDP判定: {threat_result}\\nTDP消息: {threat_msg}\\n\\n'\n f'[HTTP请求内容]\\n{payload}\\n\\n'\n f'[HTTP响应内容]\\n{response}'\n )\n\n vuln_text = '\\n'.join(str(item) for item in [\n threat_msg, threat.get('topic', ''),\n alert_data.get('data', ''), url,\n json.dumps(threat.get('tag', []), ensure_ascii=False),\n ] if item)\n vuln_matches = sorted(set(re.findall(r'\\b(?:CVE|CNVD|CNNVD|XVE)-[A-Za-z0-9._-]+\\b', vuln_text, flags=re.I)))\n\n iocs = []\n for candidate in [src_ip, dst_ip]:\n if candidate:\n iocs.append({'type': 'ip', 'value': candidate})\n if url:\n iocs.append({'type': 'url', 'value': url})\n if host and not re.match(r'^\\d{1,3}(?:\\.\\d{1,3}){3}(?::\\d+)?$', str(host)):\n iocs.append({'type': 'domain', 'value': str(host).split(':')[0]})\n\n return {\n 'src_ip': src_ip, 'dst_ip': dst_ip, 'src_port': src_port, 'dst_port': dst_port,\n 'protocol': protocol, 'payload': payload, 'response': response,\n 'url': url, 'status': status,\n 'alert_type': alert_type, 'severity': severity,\n 'vuln_id': vuln_matches[0] if vuln_matches else '',\n 'vuln_candidates': vuln_matches,\n 'threat_result': threat_result, 'threat_msg': threat_msg,\n 'failed_by': threat.get('failed_by', []),\n 'asset_ip': assets.get('ip', ''), 'asset_name': assets.get('name', []),\n 'iocs': iocs, 'log_text': log_text,\n }\n\n\n# MCP tools register as \"_\". ThreatBook's server is named\n# threatbook_mcp by default and threatbook in older configurations. Workflow\n# code needs exact names: the \"__mcp_\" wildcard only works in agent tool lists.\nINTEL_TOOLS = {\n 'ip': ('threatbook_mcp_ip_query', 'threatbook_ip_query'),\n 'domain': ('threatbook_mcp_domain_query', 'threatbook_domain_query'),\n 'vuln': ('threatbook_mcp_vuln_query', 'threatbook_vuln_query'),\n # Not every ThreatBook configuration has a URL lookup. The URL host is\n # queried as a domain as well, so a missing URL tool is not reported.\n 'url': ('threatbook_mcp_url_query', 'threatbook_url_query'),\n}\n_intel_tool_names = {}\n_intel_tool_lock = threading.Lock()\n\n\ndef _run_intel_tool(kind, **kwargs):\n \"\"\"Run the first registered tool for ``kind``; None when none is registered.\n\n The tool found is reused for the rest of the run. A missing intel source is\n logged once instead of silently leaving every triage without intel.\n \"\"\"\n with _intel_tool_lock:\n resolved = _intel_tool_names.get(kind)\n if resolved == '':\n return None\n for name in ((resolved,) if resolved else INTEL_TOOLS[kind]):\n r = tool.run_safe(name, **kwargs)\n # Only the adapter's own message for this name means \"not registered\";\n # any other error, even one quoting it, is a failure of a registered tool.\n if not r['success'] and str(r.get('error') or '').strip() == f'Tool not found: {name!r}':\n continue\n with _intel_tool_lock:\n _intel_tool_names[kind] = name\n return r\n with _intel_tool_lock:\n first_miss = _intel_tool_names.get(kind) != ''\n _intel_tool_names[kind] = ''\n if first_miss and kind != 'url':\n print(f'[triage] WARNING: no {kind} intel tool is registered '\n f'(tried {\", \".join(INTEL_TOOLS[kind])}); triage continues without it')\n return None\n\n\ndef _prepare_intel(parsed):\n \"\"\"Mirrors tdp_alert_triage.prepare_intel. Pre-fetches IP/domain/URL threat intel\n and CVE info so the parallel LLM tasks have concrete context to consume.\n \"\"\"\n iocs = parsed.get('iocs', [])\n intel_results = []\n seen = set()\n for ioc in iocs:\n ioc_type = ioc.get('type', '')\n ioc_value = str(ioc.get('value', '')).strip()\n key = (ioc_type, ioc_value)\n if not ioc_value or key in seen:\n continue\n seen.add(key)\n if ioc_type == 'ip':\n if not _is_public_ip(ioc_value):\n continue\n r = _run_intel_tool('ip', ip=ioc_value)\n elif ioc_type == 'domain':\n r = _run_intel_tool('domain', domain=ioc_value)\n elif ioc_type == 'url':\n r = _run_intel_tool('url', url=ioc_value)\n else:\n continue\n if r and r['success']:\n intel_results.append({'source': 'threatbook', 'type': ioc_type,\n 'value': ioc_value, 'result': r['text']})\n\n vuln_info = {}\n vuln_id = parsed.get('vuln_id', '')\n if vuln_id:\n r = _run_intel_tool('vuln', vuln_id=vuln_id)\n if r and r['success']:\n try:\n obj = r.get('obj')\n if isinstance(obj, str):\n obj = json.loads(obj)\n vuln_info = obj if isinstance(obj, dict) else {'raw_result': r.get('text', '')}\n except Exception:\n vuln_info = {'raw_result': r.get('text', '')}\n\n intel_content = '\\n'.join(\n f\"[{i['source']}/{i['type']}] {i['value']}\\n{i['result']}\" for i in intel_results\n ) or '(无可用情报数据)'\n vuln_content = (\n json.dumps(vuln_info, ensure_ascii=False, indent=2)\n if vuln_info else '(无可用漏洞情报数据)'\n )\n return intel_results, intel_content, vuln_info, vuln_content\n\n\n# ── 4 LLM analysis branches (sharing one run-wide request budget) ───────────\n\ndef _ask_llm(prompt):\n \"\"\"Wrap ``llm.ask`` with the workflow-wide timeout + retry budget.\n\n Centralizing this avoids a hung provider request (no TCP timeout from\n upstream) from blocking a worker thread indefinitely. Any call that does\n not need bespoke parameters should go through here.\n \"\"\"\n kwargs = {\n 'timeout_s': LLM_CALL_TIMEOUT_S,\n 'max_retries': LLM_CALL_MAX_RETRIES,\n }\n if _llm_slots is None:\n return llm.ask(prompt, **kwargs)\n with _llm_slots:\n return llm.ask(prompt, **kwargs)\n\n\ndef _llm_survey(log_text, intel_content):\n prompt = f'''你是一个专业的Web日志分析专家。请总结以下IP的情报数据中的空间测绘信息。\n1. 如果该IP没有测绘信息,则不列出。\n2. 如果IP有测绘信息,则以简短的语言对该IP的测绘信息进行总结,关键说明ip的标签和测绘信息显示有哪些服务或者应用资产。\n3. 多个IP的测绘信息以无序列表显示,每个ip数据描述占一行数据。\n4. 不需要生成其他额外的补充信息。\n\n## 情报参考信息\n{intel_content}\n\n## 用户的原始输入日志\n{log_text}\n'''\n return _strip_think(_ask_llm(prompt))\n\n\ndef _llm_cve_related(log_text):\n prompt = f'''请从以下的日志数据中提取漏洞编号。\n要求:\n1. 仅从日志文本中识别漏洞编号,不要做任何推测。\n2. 如果日志中存在漏洞编号,则用简短语言描述,如:\"日志中存在漏洞编号:CVE-****-****\"。\n3. 如果日志中不存在漏洞编号,则输出:\"日志中无关联漏洞情报\"。\n\n日志数据如下:\n{log_text}\n'''\n return _strip_think(_ask_llm(prompt))\n\n\ndef _llm_cve_info(log_text, vuln_content):\n prompt = f'''你是一个专业的Web日志分析专家。参考情报信息中的漏洞数据,简要说明关联的CVE漏洞信息。\n1. 不要输出任何解释说明,只输出漏洞基本信息。不需要生成漏洞的处置建议或修复措施等。\n\n## 情报参考信息\n{vuln_content}\n\n## 用户的原始输入日志\n{log_text}\n'''\n return _strip_think(_ask_llm(prompt))\n\n\ndef _llm_payload_analysis(log_text):\n prompt = f'''你是一个专业的Web日志分析专家。根据用户输入的日志进行攻击负载分析。\n1. 首先分析日志中是否包含攻击负载,并给出判定依据。\n2. 不要进行攻击意图分析、攻击影响分析。\n3. 用简短的语言在一段话中进行描述。\n\n## 用户的原始输入日志:\n{log_text}\n'''\n return _strip_think(_ask_llm(prompt))\n\n\ndef _parallel_4_branches(parsed, intel_content, vuln_content):\n \"\"\"Submit 4 logical branches; _ask_llm enforces the run-wide provider budget.\"\"\"\n log_text = parsed.get('log_text', '')\n with ThreadPoolExecutor(max_workers=4, thread_name_prefix='triage_branch') as pool:\n futs = {\n 'survey_result': pool.submit(_llm_survey, log_text, intel_content),\n 'cve_related_result': pool.submit(_llm_cve_related, log_text),\n 'cve_info_result': pool.submit(_llm_cve_info, log_text, vuln_content),\n 'payload_analysis_result': pool.submit(_llm_payload_analysis, log_text),\n }\n out = {}\n for name, fut in futs.items():\n try:\n out[name] = fut.result()\n except Exception as e:\n print(f'[triage] WARNING: branch {name} failed: {e}')\n out[name] = ''\n return out\n\n\n# ── Join-point LLM analyses (attack_analysis_result -> verdict -> title) ──────\n\ndef _llm_attack_analysis(log_text):\n prompt = f'''你是一名专业且经验丰富的网络安全分析师和Web日志分析专家,你对HTTP协议以及Web攻击有着深入的理解,并且你能够快速识别和应对各种网络威胁。你的任务是对提供的HTTP请求与响应内容进行详细的专业分析,并判断日志请求的攻击状态。\n\n请严格遵循以下指令进行思考和分析:\n1. 分别判断是否为攻击(攻击/非攻击/未知)以及攻击结果(攻击成功/攻击失败/未知)。\n2. 从日志中提取出\"HTTP请求内容\"和\"HTTP响应内容\"。请注意,HTTP请求内容和HTTP响应内容是分开的,请不要混淆,有些日志中没有包含HTTP响应内容,请不要将HTTP请求内容和HTTP响应内容混淆。分析后请你记住哪些是HTTP请求内容,哪些是HTTP响应内容。\n3. 请检查HTTP响应状态码,2xx或者3xx状态码都代表本次HTTP请求成功,4xx或者5xx状态码大多数情况下都代表请求失败,只有在请求成功的情况下才能对攻击是否成功进行后续判断。\n\n各攻击状态的定义以及判定标准:\n1. 攻击成功:\n(1) 首先分析日志中是否含有清晰的\"HTTP响应内容\",如果日志中没有\"HTTP响应内容\",则肯定不属于攻击成功。\n(2) 如果日志中未提供\"HTTP响应内容\",即使HTTP请求内容中包含攻击者预期的结果,也不能判定为攻击成功。\n(3) 从日志中提取出\"HTTP请求内容\"和\"HTTP响应内容\"。请深入分析\"HTTP响应内容\",并判定其是否为\"HTTP请求内容\"攻击成功时的预期结果,这是判定攻击成功的强依据。请注意,HTTP响应码200仅表示网络连接成功,不代表攻击攻击成功。\n(4) 分析HTTP请求内容和HTTP响应内容,只有当HTTP响应内容中明确包含攻击载荷在目标机器上成功执行的证据,并且HTTP请求内容中包含攻击载荷的特征,则判定为\"攻击成功\"。\n(5) 请注意:攻击成功的判定必须包含HTTP响应内容。如果不包含HTTP响应内容,则肯定不属于攻击成功。\n(6) 请注意:如果不包含HTTP响应内容,即使HTTP请求内容是攻击,这也不属于攻击成功。\n2. 攻击失败:\n(1) 分析HTTP请求内容和HTTP响应内容,如果HTTP响应内容中明确包含攻击载荷在目标机器上执行失败或者被阻止的证据,并且HTTP请求内容中包含攻击载荷的特征,则判定为\"攻击失败\"。\n(2) 攻击失败的判定必须包含HTTP响应内容。如果不包含HTTP响应内容,则肯定不属于攻击失败。\n3. 攻击:\n(1) 在\"HTTP请求内容\"或\"HTTP响应内容\"中发现任何证明存在攻击意图的证据,即可判定为存在攻击行为。但如果不符合上述的攻击成功或者攻击失败的标准,则\"攻击状态\"为\"攻击\"。\n(2) 请注意:如果日志中只提供了\"HTTP请求内容\",且没有提供\"HTTP响应内容\",且HTTP的请求内容分析中是包含攻击行为的,则\"攻击状态\"为\"攻击\"。\n4. 未知:\n(1) 如果不能100%确定HTTP通信的攻击结果,那么请在\"攻击状态\"处给出\"未知\"。\n(2) 请注意:如果在你给的判定原因中存在\"可能\"等不确定词汇,都代表你不能对你的结论100%确定,那么请在\"攻击状态\"处给出\"未知\"。\n5. 安全:\n(1) 如果\"HTTP请求内容\"和\"HTTP响应内容\"中都没有任何攻击意图的证据,那么请在\"攻击状态\"处给出\"安全\"。\n\n## 日志内容\n{log_text}\n\n## 输出要求\n请按下列结构输出(中文):\n1. 是否攻击: [攻击/非攻击/未知]\n2. 攻击结果: [攻击成功/攻击失败/未知]\n3. 判定依据: 简要说明请求与响应的关键证据\n4. 详细分析: 不超过200字\n'''\n return _strip_think(_ask_llm(prompt))\n\n\ndef _normalize_triage_outcome(attack_verdict, attack_success):\n verdict = str(attack_verdict or '').strip().lower()\n result = str(attack_success or '').strip().lower()\n if verdict not in {'attack', 'non_attack', 'unknown'}:\n verdict = 'unknown'\n if result not in {'success', 'failed', 'unknown'}:\n result = 'unknown'\n if verdict != 'attack':\n result = 'unknown'\n return verdict, result\n\n\ndef _triage_outcome_key(attack_verdict, attack_success):\n verdict, result = _normalize_triage_outcome(attack_verdict, attack_success)\n if verdict == 'attack':\n if result == 'success':\n return 'attack_success'\n if result == 'failed':\n return 'attack_failed'\n return 'attack'\n if verdict == 'non_attack':\n return 'non_attack'\n return 'unknown'\n\n\ndef _llm_attack_outcome(attack_analysis_result):\n prompt = f'''你是一个专业的 Web 日志分析专家。根据参考信息,输出且仅输出一个 JSON 对象:\n{{\n \"triage_attack_verdict\": \"attack | non_attack | unknown\",\n \"triage_attack_success\": \"success | failed | unknown\"\n}}\n\n字段规则:\n1. triage_attack_verdict 只表示是否为攻击:attack=攻击,non_attack=非攻击,unknown=无法判断。\n2. triage_attack_success 只表示攻击结果:success=攻击成功,failed=攻击失败,unknown=无法判断结果。\n3. 只有 triage_attack_verdict=attack 时,攻击结果才允许为 success 或 failed。\n4. 当 triage_attack_verdict 为 non_attack 或 unknown 时,triage_attack_success 必须为 unknown。\n5. 不要输出解释、Markdown 或其他字段。\n\n## 日志分析结果\n{attack_analysis_result}\n'''\n raw = _strip_think(_ask_llm(prompt)).strip()\n match = re.search(r'\\{.*?\\}', raw, flags=re.S)\n try:\n parsed = json.loads(match.group(0)) if match else {}\n except Exception:\n parsed = {}\n verdict, result = _normalize_triage_outcome(\n parsed.get('triage_attack_verdict'),\n parsed.get('triage_attack_success'),\n )\n return {\n 'triage_attack_verdict': verdict,\n 'triage_attack_success': result,\n }\n\n\ndef _llm_report_title(alert_type, attack_verdict, attack_success, attack_analysis_result):\n prompt = f'''你是一个专业的Web日志分析专家。请基于以下分析结果,生成一份不超过 30 字的中文报告标题。\n要求:\n1. 标题必须能体现\"攻击类型\"或\"攻击结果分析的结论\"。\n2. 不要带书名号、引号或其他标点。\n3. 只输出标题本身,不要任何解释或说明。\n\n## 攻击类型\n{alert_type}\n\n## 是否攻击\n{attack_verdict}\n\n## 攻击结果\n{attack_success}\n\n## 攻击分析结果\n{attack_analysis_result}\n'''\n raw = _strip_think(_ask_llm(prompt)).strip()\n outcome_cn = OUTCOME_CN.get(\n _triage_outcome_key(attack_verdict, attack_success),\n '未知',\n )\n return raw.splitlines()[0].strip(' \"\\'《》[]【】') if raw else f'{alert_type} - {outcome_cn}'\n\n\ndef _clip_text(value, limit=3000):\n text = str(value or '').strip()\n if len(text) > limit:\n return text[:limit] + '\\n...(已截断)'\n return text or '未提供'\n\n\ndef _fence_text(value):\n text = _clip_text(value, 6000)\n return text.replace('```', '``\\\\u200b`')\n\n\ndef _extract_tagged_triage_report(text):\n text = _strip_think(text)\n m = re.search(r']*>[\\s\\S]*?', text, flags=re.I)\n return m.group(0).strip() if m else text.strip()\n\n\ndef _is_valid_triage_report(markdown):\n text = str(markdown or '')\n if not re.search(r']*version=[\"\\']soc\\.triage\\.markdown\\.v1[\"\\'][^>]*>', text, flags=re.I):\n return False\n if not re.search(r'', text, flags=re.I):\n return False\n for tag in TRIAGE_REPORT_TAGS:\n if not re.search(rf'<{tag}\\b[^>]*>', text, flags=re.I):\n return False\n if not re.search(rf'', text, flags=re.I):\n return False\n return True\n\n\ndef _is_current_triage_fields(fields):\n if not isinstance(fields, dict):\n return False\n verdict = fields.get('triage_attack_verdict')\n result = fields.get('triage_attack_success')\n normalized = _normalize_triage_outcome(verdict, result)\n return (\n (verdict, result) == normalized\n and all(key in fields for key in TRIAGE_FIELDS)\n and _is_valid_triage_report(fields.get('triage_report'))\n )\n\n\ndef _format_intel_brief(intel_results):\n if not intel_results:\n return '未查询到外部威胁情报。'\n lines = []\n for intel in intel_results[:6]:\n lines.append(f\"- {intel.get('source', 'intel')} / {intel.get('type', 'ioc')}: {intel.get('value', '')} => {_clip_text(intel.get('result'), 500)}\")\n return '\\n'.join(lines)\n\n\ndef _build_default_tagged_triage_report(parsed, intel_results, vuln_info, branches,\n attack_analysis_result, attack_verdict,\n attack_success, report_title, risk_level):\n outcome = _triage_outcome_key(attack_verdict, attack_success)\n verdict_cn = OUTCOME_CN.get(outcome, '未知')\n attack_verdict_cn = ATTACK_VERDICT_CN.get(attack_verdict, '未知')\n attack_success_cn = ATTACK_SUCCESS_CN.get(attack_success, '未知')\n title = report_title or f'{parsed.get(\"alert_type\", \"Web日志告警\")} - {verdict_cn}'\n payload = _fence_text(parsed.get('payload', ''))\n response = _fence_text(parsed.get('response', ''))\n url = parsed.get('url') or '未提供'\n threat_msg = parsed.get('threat_msg') or '未提供'\n status = parsed.get('status') or '未提供'\n survey = _clip_text(branches.get('survey_result'), 1500)\n cve_related = _clip_text(branches.get('cve_related_result'), 1500)\n cve_info = _clip_text(branches.get('cve_info_result'), 1500)\n payload_analysis = _clip_text(branches.get('payload_analysis_result'), 1500)\n attack_analysis = _clip_text(attack_analysis_result, 1500)\n intel_brief = _format_intel_brief(intel_results)\n vuln_brief = _clip_text(json.dumps(vuln_info, ensure_ascii=False, indent=2), 1800) if vuln_info else '未查询到漏洞详情。'\n\n if outcome == 'attack_success':\n recommendation = '立即核查目标资产是否产生异常文件、进程、账号或敏感数据访问记录,并按成功入侵事件升级处置。'\n elif outcome == 'attack_failed':\n recommendation = '保留拦截与响应证据,复核同源后续请求,并确认防护策略是否持续生效。'\n elif outcome == 'non_attack':\n recommendation = '作为低风险事件留痕,结合资产白名单或业务访问记录确认是否可降噪。'\n else:\n recommendation = '补齐目标 Web 日志、响应体、主机侧进程和文件证据后再确认攻击成功性。'\n\n return f'''\n\n\n# {title}\n\n\n\n- 是否攻击:{attack_verdict_cn}\n- 攻击结果:{attack_success_cn}\n- 研判结论:{verdict_cn}\n- 风险等级:{risk_level}\n- 告警类型:{parsed.get('alert_type', 'unknown')}\n- 源 IP:{parsed.get('src_ip', 'N/A')}:{parsed.get('src_port', 'N/A')}\n- 目标资产:{parsed.get('dst_ip', 'N/A')}:{parsed.get('dst_port', 'N/A')}\n- URL:{url}\n- 响应码:{status}\n\n\n\n## 分析步骤\n\n### 1. 日志类型分析\n该告警按 Web 日志处理,已提取 HTTP 请求、响应、源地址、目标资产、URL、响应码和 TDP 判定字段。\n\n### 2. 情报信息\n{intel_brief}\n\n### 3. 测绘信息\n{survey}\n\n### 4. 告警关联漏洞情报\n{cve_related}\n\n### 5. 攻击负载分析\n{payload_analysis}\n\n### 6. 攻击分析结果\n{attack_analysis}\n\n\n\n## 研判结论\n当前研判结论为 **{verdict_cn}**,风险等级为 **{risk_level}**。TDP 消息为:{threat_msg}\n\n\n\n## 攻击payload\n\n```http\n{payload}\n```\n\n\n\n## 具体含义解释\n\n1. 请求命中的告警类型为 {parsed.get('alert_type', 'unknown')}。\n2. 请求 URL 为 {url},需要结合参数、请求体和目标业务判断攻击意图。\n3. Payload 分析结果:{payload_analysis}\n\n\n\n## 响应证据\n\n```http\n{response}\n```\n\n响应码为 {status}。如果响应体未提供或没有执行成功证据,则不能仅凭请求侧 payload 判定攻击成功。\n\n\n\n## 重要证据\n\n1. 源地址:{parsed.get('src_ip', 'N/A')}:{parsed.get('src_port', 'N/A')}。\n2. 目标资产:{parsed.get('dst_ip', 'N/A')}:{parsed.get('dst_port', 'N/A')}。\n3. TDP 判定:{parsed.get('threat_result', '未提供')};TDP 消息:{threat_msg}。\n4. 漏洞详情:{vuln_brief}\n\n\n\n## 处置建议\n\n1. {recommendation}\n2. 检索同源 IP、同一 dedup_key、同一 URL 或同一漏洞特征的横向告警。\n3. 结合目标资产 Web 访问日志、主机审计、EDR 与 WAF 日志补齐证据链。\n\n\n'''\n\n\ndef _llm_triage_report_markdown(parsed, intel_results, vuln_info, branches,\n attack_analysis_result, attack_verdict,\n attack_success, report_title, risk_level):\n verdict_cn = OUTCOME_CN.get(\n _triage_outcome_key(attack_verdict, attack_success),\n '未知',\n )\n context = json.dumps({\n 'report_title': report_title,\n 'triage_attack_verdict': attack_verdict,\n 'triage_attack_success': attack_success,\n 'verdict_cn': verdict_cn,\n 'risk_level': risk_level,\n 'alert': {\n 'alert_type': parsed.get('alert_type'),\n 'severity': parsed.get('severity'),\n 'src_ip': parsed.get('src_ip'),\n 'src_port': parsed.get('src_port'),\n 'dst_ip': parsed.get('dst_ip'),\n 'dst_port': parsed.get('dst_port'),\n 'url': parsed.get('url'),\n 'status': parsed.get('status'),\n 'threat_result': parsed.get('threat_result'),\n 'threat_msg': parsed.get('threat_msg'),\n 'payload': parsed.get('payload'),\n 'response': parsed.get('response'),\n },\n 'survey_result': branches.get('survey_result'),\n 'cve_related_result': branches.get('cve_related_result'),\n 'cve_info_result': branches.get('cve_info_result'),\n 'payload_analysis_result': branches.get('payload_analysis_result'),\n 'attack_analysis_result': attack_analysis_result,\n 'intel_results': intel_results,\n 'vuln_info': vuln_info,\n }, ensure_ascii=False, indent=2)\n\n prompt = f'''你是一名资深 SOC 告警研判分析师。请根据输入上下文,生成一份供前端直接渲染的 SOC 告警研判报告 markdown。\n\n硬性要求:\n1. 只输出带语义标签的 markdown,不要输出 JSON,不要解释规则。\n2. 根标签必须是 。\n3. 必须按顺序输出并完整闭合这些标签:\n 、、、、、、、、。\n4. 标签外不得输出正文内容。标签内可以使用 markdown 标题、列表、引用、代码块。\n5. 段落标题必须贴近前端展示模板:分析步骤、研判结论、攻击payload、具体含义解释、响应证据、重要证据、处置建议。\n6. 如果没有 HTTP 响应体或没有明确响应证据,不得判定为攻击成功;需要写明“当前日志未提供有效响应证据”。\n7. 不要编造输入中不存在的 IP、域名、URL、CVE、账号、文件路径或响应内容。\n8. 攻击 payload 和响应证据必须分别放在对应标签中,不要混淆请求与响应。\n9. 研判结论必须严格遵循上下文中的 triage_attack_verdict 和 triage_attack_success,不得使用原始告警同名字段替代。\n\nFew-shot 示例 1:攻击成功\n\n\n\n# 敏感文件泄露攻击成功分析报告\n\n\n\n- 研判结论:攻击成功\n- 风险等级:High\n- 告警类型:敏感文件访问\n- 源 IP:203.0.113.10:42131\n- 目标资产:198.51.100.20:80\n- URL:http://example.com/api/.env\n- 响应码:200\n\n\n\n## 分析步骤\n\n### 1. 日志类型分析\n该日志包含 HTTP 请求路径、响应码和响应体,可用于判断敏感文件是否被返回。\n\n### 2. 情报信息\n源 IP 命中扫描源标签,风险高。\n\n### 3. 测绘信息\n目标为公网 Web 服务,存在敏感路径暴露风险。\n\n### 4. 告警关联漏洞情报\n该行为与环境变量文件泄露场景一致。\n\n### 5. 攻击负载分析\n攻击者直接请求 /api/.env,目标是读取环境变量配置。\n\n### 6. 攻击分析结果\n响应码为 200,响应体中出现 DB_PASSWORD,支持攻击成功。\n\n\n\n## 研判结论\n攻击者成功读取敏感配置文件,响应体中包含数据库密码字段,结论为攻击成功。\n\n\n\n## 攻击payload\n\n```http\nGET /api/.env HTTP/1.1\nHost: example.com\n```\n\n\n\n## 具体含义解释\n\n1. /api/.env 是常见环境变量文件路径。\n2. 攻击者通过 GET 请求尝试直接读取配置文件。\n3. 该路径若返回真实内容,通常意味着敏感文件暴露。\n\n\n\n## 响应证据\n\n```http\nHTTP/1.1 200 OK\n\nDB_PASSWORD=example-secret\n```\n\n响应体出现 DB_PASSWORD,证明敏感配置内容已被返回。\n\n\n\n## 重要证据\n\n1. 请求路径为 /api/.env。\n2. 响应码为 200。\n3. 响应体包含 DB_PASSWORD。\n\n\n\n## 处置建议\n\n1. 立即下线或限制敏感文件访问。\n2. 轮换可能泄露的密钥和数据库密码。\n3. 检索同源 IP 和同路径访问记录。\n\n\n\n\nFew-shot 示例 2:攻击失败\n\n\n\n# SQL注入攻击失败分析报告\n\n\n\n- 研判结论:攻击失败\n- 风险等级:Medium\n- 告警类型:SQL注入\n- 源 IP:203.0.113.44:51002\n- 目标资产:198.51.100.30:443\n- URL:https://shop.example.com/item?id=1\n- 响应码:403\n\n\n\n## 分析步骤\n\n### 1. 日志类型分析\n该日志包含请求参数和响应码,能够确认请求侧存在 SQL 注入尝试。\n\n### 2. 情报信息\n源 IP 暂无高置信恶意标签。\n\n### 3. 测绘信息\n目标为公网电商 Web 服务。\n\n### 4. 告警关联漏洞情报\n当前日志未提供可确认具体 CVE 的证据。\n\n### 5. 攻击负载分析\n请求参数中包含 union select,存在明显 SQL 注入意图。\n\n### 6. 攻击分析结果\n响应码为 403,响应体显示请求被阻断,不支持攻击成功。\n\n\n\n## 研判结论\n该请求存在 SQL 注入攻击意图,但响应显示被拒绝,当前判断为攻击失败。\n\n\n\n## 攻击payload\n\n```http\nGET /item?id=1 union select user HTTP/1.1\nHost: shop.example.com\n```\n\n\n\n## 具体含义解释\n\n1. union select 是典型 SQL 注入关键字组合。\n2. 攻击者尝试拼接查询以读取数据库用户信息。\n3. 该 payload 证明攻击意图,但不等同于成功执行。\n\n\n\n## 响应证据\n\n```http\nHTTP/1.1 403 Forbidden\n\nblocked by waf\n```\n\n响应状态和内容说明请求被拦截,未见数据泄露或执行成功证据。\n\n\n\n## 重要证据\n\n1. 请求参数包含 union select。\n2. 响应码为 403。\n3. 响应体显示 blocked by waf。\n\n\n\n## 处置建议\n\n1. 保留 WAF 拦截证据。\n2. 检查同源 IP 是否持续尝试其他注入 payload。\n3. 确认目标接口参数化查询和安全策略仍然有效。\n\n\n\n\n## 待研判上下文\n```json\n{context}\n```\n\n请输出最终报告:\n'''\n return _extract_tagged_triage_report(_ask_llm(prompt))\n\n\ndef _generate_triage_report(parsed, intel_results, vuln_info, branches,\n attack_analysis_result, attack_verdict,\n attack_success, report_title):\n # Aggregate everything into tagged markdown for frontend rendering.\n # The markdown is returned through `triage_report` and is not written as a\n # per-alert file; leader/follower/cache-hit paths reuse the same field.\n outcome = _triage_outcome_key(attack_verdict, attack_success)\n verdict_cn = OUTCOME_CN.get(outcome, '未知')\n risk_level = OUTCOME_RISK.get(outcome, 'Medium')\n\n if not report_title:\n report_title = f'{parsed.get(\"alert_type\", \"Web日志告警\")} - {verdict_cn}'\n\n try:\n triage_report = _llm_triage_report_markdown(\n parsed, intel_results, vuln_info, branches,\n attack_analysis_result, attack_verdict, attack_success,\n report_title, risk_level,\n )\n except Exception as e:\n print(f'[triage] WARNING: triage_report LLM generation failed: {e}')\n triage_report = ''\n\n if not _is_valid_triage_report(triage_report):\n print('[triage] WARNING: triage_report missing required semantic tags; using deterministic fallback')\n triage_report = _build_default_tagged_triage_report(\n parsed, intel_results, vuln_info, branches,\n attack_analysis_result, attack_verdict, attack_success,\n report_title, risk_level,\n )\n\n return triage_report, report_title, risk_level\n\n\ndef _triage_single_alert(alert):\n \"\"\"End-to-end inline triage for a single alert. Returns triage_fields dict.\n\n No file I/O — the full markdown report lives in the returned `triage_report` field\n and is broadcast to followers / persisted via `triage_cache.pkl`.\n \"\"\"\n parsed = _parse_alert(alert)\n intel_results, intel_content, vuln_info, vuln_content = _prepare_intel(parsed)\n\n branches = _parallel_4_branches(parsed, intel_content, vuln_content)\n\n attack_analysis_result = _llm_attack_analysis(parsed['log_text'])\n outcome = _llm_attack_outcome(attack_analysis_result)\n attack_verdict = outcome['triage_attack_verdict']\n attack_success = outcome['triage_attack_success']\n report_title = _llm_report_title(\n parsed.get('alert_type', 'unknown'),\n attack_verdict,\n attack_success,\n attack_analysis_result,\n )\n\n triage_report, report_title, risk_level = _generate_triage_report(\n parsed, intel_results, vuln_info, branches,\n attack_analysis_result, attack_verdict, attack_success, report_title,\n )\n\n return {\n 'triage_attack_verdict': attack_verdict,\n 'triage_attack_success': attack_success,\n 'risk_level': risk_level,\n 'report_title': report_title,\n 'triage_report': triage_report,\n }\n\n\n# ── Main: leader/follower batch deduplication ────────────────────────────────\n# When the input batch contains multiple alerts sharing the same dedup_key\n# (e.g. upstream emits is_duplicate=True alerts in the same batch, or LSH\n# clustering produces several alerts per cluster), we only triage the LEADER\n# (first occurrence of each dedup_key). All FOLLOWERS in the same group reuse\n# the leader's triage result without invoking the LLM again.\n#\n# Work unit types:\n# ('dk', dedup_key, leader_idx) — group of 1+ alerts sharing dedup_key\n# ('nokey', None, alert_idx) — single alert with no dedup_key\n# (cannot be deduplicated, always triaged)\n\ndef _bump_verdict(verdict):\n with results_lock:\n stats['verdict_counts'][verdict] = stats['verdict_counts'].get(verdict, 0) + 1\n\n\n_UNKNOWN_TRIAGE = {\n 'triage_attack_verdict': 'unknown',\n 'triage_attack_success': 'unknown',\n 'risk_level': 'Medium',\n 'report_title': '',\n 'triage_report': '',\n}\n\n\ndef _apply_triage_fields(record, triage_fields):\n verdict = triage_fields.get('triage_attack_verdict', 'unknown')\n result = triage_fields.get('triage_attack_success', 'unknown')\n if verdict not in {'attack', 'non_attack', 'unknown'}:\n verdict = 'unknown'\n if result not in {'success', 'failed', 'unknown'} or verdict != 'attack':\n result = 'unknown'\n record['triage_attack_verdict'] = verdict\n record['triage_attack_success'] = result\n for key in ('risk_level', 'report_title', 'triage_report'):\n if key in triage_fields:\n record[key] = triage_fields[key]\n\n\ndef _process_unit(unit_type, dedup_key, leader_idx):\n \"\"\"Triage one unique work unit. Returns (key, triage_fields, source, ms, error).\"\"\"\n leader_alert = enriched_alerts[leader_idx]\n t0 = time.time()\n\n # 1) cache lookup for dedup_key units\n if unit_type == 'dk':\n cached = triage_cache_snapshot.get(dedup_key)\n if cached:\n if _is_current_triage_fields(cached):\n with results_lock:\n stats['cache_hit'] += 1\n _bump_verdict(_triage_outcome_key(\n cached.get('triage_attack_verdict'),\n cached.get('triage_attack_success'),\n ))\n return dedup_key, cached, 'cache', 0, None\n print(f'[triage_cache] stale entry for dedup_key={dedup_key}: '\n 'missing current two-field triage schema/report; treating as cache miss')\n\n # 2) cache miss or no-key → run full inline triage on the leader\n try:\n triage_fields = _triage_single_alert(leader_alert)\n ms = round((time.time() - t0) * 1000)\n with results_lock:\n stats['triaged'] += 1\n if dedup_key:\n new_results[dedup_key] = triage_fields\n _bump_verdict(_triage_outcome_key(\n triage_fields.get('triage_attack_verdict'),\n triage_fields.get('triage_attack_success'),\n ))\n source = 'triaged' if unit_type == 'dk' else 'no_dedup_key_triaged'\n return (dedup_key if unit_type == 'dk' else leader_idx), triage_fields, source, ms, None\n except Exception as e:\n import traceback\n ms = round((time.time() - t0) * 1000)\n with results_lock:\n stats['triage_failed'] += 1\n _bump_verdict('unknown')\n err = str(e)[:500]\n print(f'[triage] leader_idx={leader_idx} FAILED: {e}\\n{traceback.format_exc()}')\n source = 'failed' if unit_type == 'dk' else 'no_dedup_key_failed'\n return (dedup_key if unit_type == 'dk' else leader_idx), dict(_UNKNOWN_TRIAGE), source, ms, err\n\n\n\n_batch_lease_fd = inputs.get('_batch_lease_fd')\nif type(_batch_lease_fd) is not int or _batch_lease_fd < 0:\n _batch_lease_fd = None\n_batch_lease_token = str(inputs.get('batch_lease_token') or '')\nif bool(inputs.get('cursor_enabled')) and _batch_lease_fd is None:\n _batch_lease_fd, _batch_lease_token = _acquire_batch_lease()\ntry:\n enriched_alerts = list(inputs.get('enriched_alerts', []) or [])\n concurrency = min(5, max(1, int(inputs.get('concurrency', 1))))\n _llm_slots = threading.BoundedSemaphore(concurrency)\n max_triage_cache_size = int(inputs.get('max_triage_cache_size', 100000))\n if max_triage_cache_size < 1:\n max_triage_cache_size = 100000\n\n # Group by dedup_key\n groups = {} # dedup_key -> [alert_index, ...]\n no_key_indices = [] # alerts with no dedup_key\n for i, a in enumerate(enriched_alerts):\n dk = a.get('dedup_key', '') if isinstance(a, dict) else ''\n if dk:\n groups.setdefault(dk, []).append(i)\n else:\n no_key_indices.append(i)\n\n work_units = (\n [('dk', dk, group_indices[0]) for dk, group_indices in groups.items()]\n + [('nokey', None, idx) for idx in no_key_indices]\n )\n follower_count = sum(len(v) - 1 for v in groups.values())\n\n print(f'[triage] alerts={len(enriched_alerts)} '\n f'→ {len(groups)} unique dedup_keys ({follower_count} followers) + '\n f'{len(no_key_indices)} no-key alerts '\n f'= {len(work_units)} work units; outer_concurrency={concurrency} '\n f'llm_concurrency_limit={concurrency} '\n f'sub_batch_size={TRIAGE_SUB_BATCH_SIZE} '\n f'(all LLM calls share the run-wide budget)')\n\n cache_path, lock_path = _cache_paths()\n cache_batch_lock = _acquire_lock(lock_path)\n try:\n triage_cache_snapshot = _load_cache(cache_path)\n\n # Only warm up the LLM when at least one work unit may actually need it.\n # A unit \"may need\" the LLM if it's a no-key alert OR a dedup_key unit whose\n # entry is not in the cache snapshot. Pure cache-hit batches skip warm-up.\n _needs_llm = any(\n unit_type == 'nokey' or not _is_current_triage_fields(triage_cache_snapshot.get(dk))\n for unit_type, dk, _ in work_units\n )\n if _needs_llm:\n _warmup_llm()\n\n results_lock = threading.Lock()\n new_results = {} # dedup_key -> triage_fields (only for freshly computed leaders)\n group_outcomes = {} # dedup_key -> (triage_fields, source) for broadcasting to followers\n nokey_outcomes = {} # alert_idx -> (triage_fields, source)\n stats = {\n 'total': len(enriched_alerts),\n 'unique_dedup_keys': len(groups),\n 'followers_reused': follower_count,\n 'no_dedup_key_alerts': len(no_key_indices),\n 'work_units': len(work_units),\n 'llm_concurrency_limit': concurrency,\n 'cache_hit': 0,\n 'triaged': 0,\n 'triage_failed': 0,\n 'verdict_counts': {},\n 'cache_size_before': len(triage_cache_snapshot),\n 'cache_size_after': 0,\n 'evicted': 0,\n }\n\n\n t_start = time.time()\n unit_completions = {} # key -> (triage_fields, source, ms, error)\n if work_units:\n completed_count = 0\n for batch_start in range(0, len(work_units), TRIAGE_SUB_BATCH_SIZE):\n work_batch = work_units[batch_start:batch_start + TRIAGE_SUB_BATCH_SIZE]\n worker_count = min(concurrency, len(work_batch))\n with ThreadPoolExecutor(\n max_workers=worker_count,\n thread_name_prefix='stream_triage',\n ) as pool:\n futures = [pool.submit(_process_unit, *u) for u in work_batch]\n for fut in as_completed(futures):\n completed_count += 1\n try:\n key, triage_fields, source, ms, err = fut.result()\n unit_completions[key] = (triage_fields, source, ms, err)\n if source == 'cache':\n group_outcomes[key] = (triage_fields, source)\n elif source.startswith('no_dedup_key'):\n nokey_outcomes[key] = (triage_fields, source)\n else:\n group_outcomes[key] = (triage_fields, source)\n except Exception as e:\n print(f'[triage] WARNING: unexpected worker exception: {e}')\n if completed_count % 5 == 0 or completed_count == len(work_units):\n print(f'[triage] progress {completed_count}/{len(work_units)} '\n f'(cache_hit={stats[\"cache_hit\"]} triaged={stats[\"triaged\"]} '\n f'failed={stats[\"triage_failed\"]})')\n del futures\n\n # ── Apply outcomes back to every alert (broadcast leader → followers) ─────────\n enriched_with_triage = [None] * len(enriched_alerts)\n for i, alert in enumerate(enriched_alerts):\n out = dict(alert) if isinstance(alert, dict) else {'_raw': alert}\n dk = alert.get('dedup_key', '') if isinstance(alert, dict) else ''\n out['has_dedup_key'] = bool(dk)\n\n if dk:\n triage_fields, source = group_outcomes.get(dk, (dict(_UNKNOWN_TRIAGE), 'failed'))\n is_leader = (groups.get(dk, [i])[0] == i)\n # All triage fields are pure data (no file-path references); broadcast as-is.\n _apply_triage_fields(out, triage_fields)\n if not is_leader and source != 'cache':\n out['triage_source'] = 'follower_reused'\n out['triage_status'] = 'reused_from_leader'\n else:\n out['triage_source'] = source\n out['triage_status'] = 'cached' if source == 'cache' else (\n 'ok' if source == 'triaged' else 'failed'\n )\n completion = unit_completions.get(dk)\n if completion and is_leader:\n _, _, ms, err = completion\n if ms:\n out['triage_ms'] = ms\n if err:\n out['triage_error'] = err\n else:\n # no-key alerts: each is its own unit, keyed by alert idx\n triage_fields, source = nokey_outcomes.get(i, (dict(_UNKNOWN_TRIAGE), 'no_dedup_key_failed'))\n _apply_triage_fields(out, triage_fields)\n out['triage_source'] = source\n out['triage_status'] = 'ok' if source == 'no_dedup_key_triaged' else 'failed'\n completion = unit_completions.get(i)\n if completion:\n _, _, ms, err = completion\n if ms:\n out['triage_ms'] = ms\n if err:\n out['triage_error'] = err\n\n enriched_with_triage[i] = out\n\n elapsed_ms = round((time.time() - t_start) * 1000)\n print(f'[triage] all done in {elapsed_ms}ms: cache_hit={stats[\"cache_hit\"]} '\n f'triaged={stats[\"triaged\"]} failed={stats[\"triage_failed\"]} '\n f'followers_reused={stats[\"followers_reused\"]} '\n f'no_dedup_key={stats[\"no_dedup_key_alerts\"]}')\n\n # The batch lock has remained held since the initial load, so reuse\n # that snapshot instead of temporarily retaining a second full cache.\n cache = triage_cache_snapshot\n for k, v in new_results.items():\n if k in cache:\n del cache[k] # LRU touch (move to end on rewrite)\n cache[k] = v\n evicted = _evict_lru(\n cache,\n max_triage_cache_size,\n MAX_TRIAGE_CACHE_BYTES if new_results else None,\n )\n if evicted:\n print(f'[triage_cache] LRU eviction: dropped {evicted} entries '\n f'(max_keys={max_triage_cache_size}, max_bytes={MAX_TRIAGE_CACHE_BYTES})')\n if new_results or evicted:\n _save_cache_atomic(cache_path, cache)\n stats['cache_size_after'] = len(cache)\n stats['evicted'] = evicted\n finally:\n _release_lock(cache_batch_lock)\n\n triage_results = []\n top_triage_result = {}\n top_outcome_rank = -1\n outcome_order = {\n 'attack_success': 5,\n 'attack': 4,\n 'attack_failed': 3,\n 'unknown': 2,\n 'non_attack': 1,\n }\n for a in enriched_with_triage:\n item = {\n 'dedup_key': a.get('dedup_key', ''),\n 'has_dedup_key': a.get('has_dedup_key', False),\n 'threat_name': a.get('threat_name', ''),\n 'sip': a.get('sip', ''),\n 'dip': a.get('dip', ''),\n 'is_duplicate': a.get('is_duplicate'),\n 'triage_source': a.get('triage_source', ''),\n 'triage_status': a.get('triage_status', ''),\n 'triage_attack_verdict': a.get('triage_attack_verdict', ''),\n 'triage_attack_success': a.get('triage_attack_success', 'unknown'),\n 'risk_level': a.get('risk_level', ''),\n 'report_title': a.get('report_title', ''),\n 'triage_ms': a.get('triage_ms'),\n 'triage_error': a.get('triage_error'),\n }\n triage_results.append(item)\n outcome = _triage_outcome_key(\n item['triage_attack_verdict'],\n item['triage_attack_success'],\n )\n rank = outcome_order.get(outcome, 0)\n if rank > top_outcome_rank:\n top_outcome_rank = rank\n top_triage_result = dict(item)\n # Keep the selected report intact; only the number of reports\n # crossing the process boundary is reduced.\n top_triage_result['triage_report'] = a.get('triage_report', '')\n\n stats['elapsed_ms'] = elapsed_ms\n stats['concurrency'] = concurrency\n stats['triage_sub_batch_size'] = TRIAGE_SUB_BATCH_SIZE\n stats['max_triage_cache_size'] = max_triage_cache_size\n stats['max_triage_cache_bytes'] = MAX_TRIAGE_CACHE_BYTES\n\n # Persist enriched_with_triage according to workflow config. Default is SOC DB;\n # JSONL is still available by config/input for downstream pipelines or archival.\n output_cfg = _resolve_output_config()\n run_id = (inputs.get('_run_id')\n or os.environ.get('FLOCKS_RUN_ID')\n or str(int(time.time() * 1000)))\n output_paths = []\n output_dir = ''\n first_seen_soc_alerts, soc_db_filter_stats = _select_first_seen_soc_alerts(\n enriched_with_triage,\n )\n soc_db_result = {\n 'path': output_cfg.get('soc_db_path', ''),\n 'table': 'alert_records',\n 'rows': 0,\n 'inserted_rows': 0,\n 'updated_rows': 0,\n }\n\n if output_cfg['write_soc_db'] and first_seen_soc_alerts:\n try:\n soc_db_result.update(_triage_write_soc_db(\n output_cfg['soc_db_path'], first_seen_soc_alerts, run_id,\n ))\n print(f'[triage] persisted {soc_db_result.get(\"rows\", 0)} globally unique alerts to '\n f'SOC DB {soc_db_result.get(\"path\")} '\n f'(inserted={soc_db_result.get(\"inserted_rows\", 0)}, '\n f'updated={soc_db_result.get(\"updated_rows\", 0)}); '\n f'filter={soc_db_filter_stats}')\n except Exception as e:\n import traceback\n print(f'[triage] ERROR: failed to persist triage results to SOC DB: {e}\\n{traceback.format_exc()}')\n raise\n elif output_cfg['write_soc_db']:\n print(f'[triage] no verified first-seen unique alerts to persist; filter={soc_db_filter_stats}')\n else:\n print(f'[triage] SOC DB output disabled by triage_output_mode={output_cfg[\"requested_mode\"]!r}')\n\n if output_cfg['write_jsonl'] and enriched_with_triage:\n try:\n output_dir = _triage_output_dir(output_cfg.get('jsonl_output_dir', ''))\n output_paths = _triage_write_jsonl(\n output_dir, enriched_with_triage, run_id, stats,\n )\n print(f'[triage] wrote {len(enriched_with_triage)} enriched alerts to '\n f'{len(output_paths)} JSONL file(s) under {output_dir}')\n for p in output_paths:\n print(f' → {p}')\n except Exception as e:\n import traceback\n print(f'[triage] ERROR: failed to persist triage_result JSONL: {e}\\n{traceback.format_exc()}')\n raise\n elif not output_cfg['write_jsonl']:\n print(f'[triage] JSONL output disabled by triage_output_mode={output_cfg[\"requested_mode\"]!r}')\n\n stats['output_mode'] = output_cfg['mode']\n stats['requested_output_mode'] = output_cfg['requested_mode']\n stats['output_config_path'] = output_cfg['config_path']\n stats['soc_db_path'] = soc_db_result.get('path', '')\n stats['soc_db_rows'] = soc_db_result.get('rows', 0)\n stats['soc_db_inserted_rows'] = soc_db_result.get('inserted_rows', 0)\n stats['soc_db_updated_rows'] = soc_db_result.get('updated_rows', 0)\n stats['soc_db_first_seen_rows'] = soc_db_filter_stats['first_seen_rows']\n stats['soc_db_skipped_rows'] = (\n soc_db_filter_stats['input_rows'] - soc_db_filter_stats['first_seen_rows']\n )\n stats['soc_db_filter_stats'] = soc_db_filter_stats\n stats['output_paths'] = output_paths\n stats['output_dir'] = output_dir\n\n print(f'[triage] stats={json.dumps(stats, ensure_ascii=False)}')\n\n outputs['top_triage_result'] = top_triage_result\n outputs['triage_results'] = triage_results\n outputs['triage_stats'] = stats\n outputs['load_stats'] = inputs.get('load_stats', {})\n outputs['loaded_files'] = inputs.get('loaded_files', [])\n outputs['input_date'] = inputs.get('input_date', '')\n outputs['cursor_enabled'] = bool(inputs.get('cursor_enabled'))\n outputs['cursor_before'] = inputs.get('cursor_before')\n outputs['cursor_revision'] = inputs.get('cursor_revision')\n outputs['cursor_invalidated'] = bool(inputs.get('cursor_invalidated'))\n outputs['pending_cursor'] = inputs.get('pending_cursor')\n outputs['next_cursor'] = inputs.get('next_cursor')\n outputs['has_more'] = bool(inputs.get('has_more'))\n outputs['batch_records'] = int(inputs.get('batch_records', 0) or 0)\n outputs['batch_bytes'] = int(inputs.get('batch_bytes', 0) or 0)\n outputs['triage_output_mode'] = output_cfg['mode']\n outputs['soc_db_result'] = soc_db_result\n outputs['soc_db_path'] = soc_db_result.get('path', '')\n outputs['output_config_path'] = output_cfg['config_path']\n outputs['output_paths'] = output_paths\n outputs['output_dir'] = output_dir\n outputs['_batch_lease_fd'] = _batch_lease_fd\n outputs['batch_lease_token'] = _batch_lease_token\n outputs['_triage_persistence_succeeded'] = True\nexcept BaseException:\n _release_batch_lease(_batch_lease_fd)\n raise\n", + "code": "\"\"\"\nconcurrent_triage: leader/follower 分组并发研判 + dedup_key 缓存复用(自包含)。\n\n去重模式:\n 1. 输入 alerts 先按 dedup_key 分组 → unique dedup_keys 列表\n 2. 每个 group 只对 leader(首条)做研判;followers 复用 leader 结果,不重复调 LLM\n 3. 无 dedup_key 的 alert 各自独立成 work unit(防御性研判,无法复用)\n\n并发结构:\n 外层按 3 个 work unit 分批创建 ThreadPoolExecutor,避免整批 future/上下文同时驻留\n (concurrency 取值 1–5,默认 1,由 inputs.concurrency 控制,每批实际 worker 不超过 3)\n 单条 alert 包含 4 个并行分支以及攻击分析、结论、标题、报告 4 个汇总调用\n (survey / cve_related / cve_info / payload_analysis — 保留 tdp_alert_triage\n 的 4 分支研判结构)\n 所有 llm.ask 调用共享运行级信号量,稳态 LLM 峰值不超过 concurrency\n\n模型攻击结论以两个正交维度附加到每条 alert:triage_attack_verdict 表示\n是否攻击(attack / non_attack / unknown),triage_attack_success 表示攻击\n结果(success / failed / unknown)。原始同名字段保持不变;其他研判产物包括 risk_level /\nreport_title / triage_report 等。**不生成任何独立的 per-alert markdown 报告\n文件**,避免冗余落盘与跨日期路径失效。\n\ndedup_key 缓存(与 stream_alert_denoise 的 LSH 状态文件同根目录,逻辑独立):\n ~/.flocks/workspace/workflows/stream_alert_triage/triage_cache.pkl\n - cache 命中:直接复用历史 verdict/title/triage_report,**不调用 LLM**\n - cache 未命中:leader 执行完整内联研判(情报 + 4 个 LLM 分支 + verdict + title + report);\n follower 直接广播 leader 结果\n - 新结果合并写回 cache,FIFO LRU 淘汰,文件锁 + 原子落盘\n\"\"\"\n\nimport ipaddress\nimport json\nimport os\nimport pickle\nimport re\nimport sys\nimport threading\nimport time\nfrom concurrent.futures import ThreadPoolExecutor, as_completed\n\nIS_WINDOWS = sys.platform == 'win32'\nif IS_WINDOWS:\n import msvcrt # noqa: F401\nelse:\n import fcntl # noqa: F401\n\nWORKFLOW_NAME = 'stream_alert_triage'\n\n# Per-call LLM timeout and retry budget for every analysis branch in this\n# node. Workflow LLM calls share the dedicated ``flocks-workflow-llm-loop``;\n# a single hung call (e.g. provider 504, slow TLS handshake) without a\n# timeout would otherwise pin one of the (already concurrency-limited)\n# worker threads for up to httpx's DEFAULT read timeout (10 min), serially\n# blocking the rest of the alert pipeline. 120s + 1 retry covers normal\n# slow-but-alive responses while still recovering from transient hangs.\nLLM_CALL_TIMEOUT_S = 120.0\nLLM_CALL_MAX_RETRIES = 1\n\n# Cache and work scheduling remain bounded without truncating alert or model content.\nMAX_TRIAGE_CACHE_BYTES = 128 * 1024 * 1024\nTRIAGE_SUB_BATCH_SIZE = 3\n\n# The user-facing concurrency setting is a run-wide LLM request budget. The\n# four logical branches still start together, but nested executors must not\n# multiply the actual provider load (5 outer workers used to become 20 calls).\n_llm_slots = None\n\nTRIAGE_FIELDS = (\n 'triage_attack_verdict',\n 'triage_attack_success',\n 'risk_level',\n 'report_title',\n 'triage_report',\n)\nATTACK_VERDICT_CN = {\n 'attack': '攻击',\n 'non_attack': '非攻击',\n 'unknown': '未知',\n}\nATTACK_SUCCESS_CN = {\n 'success': '攻击成功',\n 'failed': '攻击失败',\n 'unknown': '未知',\n}\nOUTCOME_RISK = {\n 'attack_success': 'High',\n 'attack_failed': 'Medium',\n 'attack': 'Medium',\n 'unknown': 'Medium',\n 'non_attack': 'Low',\n}\nOUTCOME_CN = {\n 'attack_success': '攻击成功',\n 'attack_failed': '攻击失败',\n 'attack': '攻击,结果未知',\n 'unknown': '未知',\n 'non_attack': '非攻击',\n}\nTRIAGE_REPORT_VERSION = 'soc.triage.markdown.v1'\nTRIAGE_REPORT_TAGS = (\n 'report_title',\n 'report_meta',\n 'analysis_steps',\n 'triage_conclusion',\n 'attack_payload',\n 'payload_explanation',\n 'response_evidence',\n 'key_evidence',\n 'disposal_recommendation',\n)\n\n\n# ── Cache persistence ─────────────────────────────────────────────────────────\n\ndef _cache_paths():\n configured_state_dir = inputs.get('_triage_state_dir')\n if configured_state_dir:\n from pathlib import Path\n state_dir = Path(os.path.expanduser(str(configured_state_dir)))\n else:\n from flocks.config import Config\n flocks_root = Config().get_global().data_dir.parent\n state_dir = flocks_root / 'workspace' / 'workflows' / WORKFLOW_NAME\n state_dir.mkdir(parents=True, exist_ok=True)\n return str(state_dir / 'triage_cache.pkl'), str(state_dir / 'triage_cache.lock')\n\n\ndef _acquire_lock(lock_path):\n fh = open(lock_path, 'w+')\n try:\n if IS_WINDOWS:\n fh.write('L'); fh.flush(); fh.seek(0)\n while True:\n try:\n msvcrt.locking(fh.fileno(), msvcrt.LK_LOCK, 1); break\n except OSError:\n continue\n else:\n fcntl.flock(fh.fileno(), fcntl.LOCK_EX)\n except BaseException:\n try:\n fh.close()\n except Exception:\n pass\n raise\n return fh\n\n\ndef _release_lock(fh):\n try:\n if IS_WINDOWS:\n try:\n fh.seek(0); msvcrt.locking(fh.fileno(), msvcrt.LK_UNLCK, 1)\n except OSError:\n pass\n else:\n fcntl.flock(fh.fileno(), fcntl.LOCK_UN)\n finally:\n fh.close()\n\n\ndef _batch_lease_path():\n cache_path, _ = _cache_paths()\n return os.path.join(os.path.dirname(cache_path), '.triage_batch.lock')\n\n\ndef _acquire_batch_lease():\n path = _batch_lease_path()\n fd = os.open(path, os.O_RDWR | os.O_CREAT, 0o600)\n try:\n if IS_WINDOWS:\n if os.fstat(fd).st_size == 0:\n os.write(fd, b'0')\n os.fsync(fd)\n os.lseek(fd, 0, os.SEEK_SET)\n msvcrt.locking(fd, msvcrt.LK_NBLCK, 1)\n else:\n fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)\n except OSError as exc:\n os.close(fd)\n raise RuntimeError('production_batch_lease_busy') from exc\n\n try:\n token = f'{os.getpid()}-{threading.get_ident()}-{time.time_ns()}'\n os.ftruncate(fd, 0)\n os.lseek(fd, 0, os.SEEK_SET)\n os.write(fd, token.encode('ascii'))\n os.fsync(fd)\n except BaseException:\n _release_batch_lease(fd)\n raise\n print(f'[triage] acquired production batch lease token={token}')\n return fd, token\n\n\ndef _release_batch_lease(fd):\n if type(fd) is not int or fd < 0:\n return\n try:\n if IS_WINDOWS:\n try:\n os.lseek(fd, 0, os.SEEK_SET)\n msvcrt.locking(fd, msvcrt.LK_UNLCK, 1)\n except OSError:\n pass\n else:\n fcntl.flock(fd, fcntl.LOCK_UN)\n finally:\n os.close(fd)\n\n\ndef _load_cache(cache_path):\n if not os.path.exists(cache_path):\n return {}\n cache_size = os.path.getsize(cache_path)\n if cache_size == 0:\n return {}\n if cache_size > MAX_TRIAGE_CACHE_BYTES:\n quarantine_path = f'{cache_path}.{time.time_ns()}.oversized'\n try:\n os.replace(cache_path, quarantine_path)\n print(f'[triage_cache] WARNING: skipped oversized cache '\n f'({cache_size} bytes > {MAX_TRIAGE_CACHE_BYTES}); '\n f'moved to {quarantine_path}')\n except OSError as e:\n print(f'[triage_cache] WARNING: skipped oversized cache '\n f'({cache_size} bytes > {MAX_TRIAGE_CACHE_BYTES}); '\n f'quarantine failed: {e}')\n return {}\n try:\n with open(cache_path, 'rb') as f:\n c = pickle.load(f)\n if not isinstance(c, dict):\n return {}\n print(f'[triage_cache] loaded {len(c)} entries from {cache_path}')\n return c\n except Exception as e:\n print(f'[triage_cache] WARNING: failed to load ({e}), starting fresh')\n return {}\n\n\n\ndef _save_cache_atomic(cache_path, cache):\n tmp = (\n f'{cache_path}.{os.getpid()}.{threading.get_ident()}.'\n f'{time.time_ns()}.tmp'\n )\n try:\n with open(tmp, 'wb') as f:\n pickle.dump(cache, f)\n f.flush()\n os.fsync(f.fileno())\n os.replace(tmp, cache_path)\n print(f'[triage_cache] saved {len(cache)} entries -> {cache_path}')\n except Exception as exc:\n try:\n if os.path.exists(tmp):\n os.remove(tmp)\n except OSError:\n pass\n raise RuntimeError(f'failed to save triage cache: {exc}') from exc\n\n\ndef _evict_lru(cache, max_keys, max_bytes=None):\n evicted = 0\n excess = len(cache) - max_keys\n if excess > 0:\n for k in list(cache.keys())[:excess]:\n del cache[k]\n evicted += 1\n\n if max_bytes is not None and max_bytes > 0 and cache:\n # Estimate one entry at a time so enforcing the cache budget never\n # creates a second serialized copy of the whole cache in memory.\n entry_sizes = {}\n estimated_bytes = 64\n for key, value in cache.items():\n size = len(pickle.dumps((key, value), protocol=pickle.HIGHEST_PROTOCOL)) + 16\n entry_sizes[key] = size\n estimated_bytes += size\n for key in list(cache.keys()):\n if estimated_bytes <= max_bytes:\n break\n estimated_bytes -= entry_sizes[key]\n del cache[key]\n evicted += 1\n return evicted\n\n\n# ── Runtime output config and persistence targets ──────────────────────────────\n#\n# Defaults are read from ~/.flocks/plugins/workflows/stream_alert_triage/config.json.\n# Runtime inputs override config values. The default mode is soc_db so SOC pages\n# read the same DB-backed dataset. JSONL remains available via config/input:\n# triage_output_mode = soc_db | jsonl | both | none\n# persist_triage_output = true (legacy alias that adds JSONL to soc_db)\n\nimport datetime as _datetime\n\nMAX_RECORDS_PER_FILE = 10000\n_TRIAGE_JSONL_PREFIX = 'triage_result'\n_TRIAGE_COUNTER_FILE = '.triage_counter.json'\n_WORKFLOW_CONFIG_PATH = os.path.join(os.environ.get('FLOCKS_ROOT') or os.path.expanduser('~/.flocks'), 'plugins', 'workflows', 'stream_alert_triage', 'config.json')\n\n\ndef _load_workflow_config():\n try:\n with open(_WORKFLOW_CONFIG_PATH, 'r', encoding='utf-8') as f:\n cfg = json.load(f)\n if isinstance(cfg, dict):\n return cfg\n except FileNotFoundError:\n pass\n except Exception as e:\n print(f'[triage_config] WARNING: failed to read {_WORKFLOW_CONFIG_PATH}: {e}')\n return {}\n\n\ndef _configured_value(config, key, default=None):\n if key in inputs:\n value = inputs.get(key)\n if value is not None and not (isinstance(value, str) and not value.strip()):\n return value\n return config.get(key, default)\n\n\ndef _input_bool(value, default=False):\n if value is None:\n return default\n if isinstance(value, bool):\n return value\n if isinstance(value, (int, float)):\n return bool(value)\n text = str(value).strip().lower()\n if text in {'1', 'true', 'yes', 'y', 'on'}:\n return True\n if text in {'0', 'false', 'no', 'n', 'off'}:\n return False\n return default\n\n\ndef _select_first_seen_soc_alerts(alerts):\n selected = []\n seen_dedup_keys = set()\n stats = {\n 'input_rows': len(alerts),\n 'first_seen_rows': 0,\n 'skipped_not_first_seen_rows': 0,\n 'skipped_missing_dedup_key_rows': 0,\n 'skipped_repeated_dedup_key_rows': 0,\n }\n for alert in alerts:\n if not isinstance(alert, dict) or _input_bool(alert.get('is_duplicate'), True):\n stats['skipped_not_first_seen_rows'] += 1\n continue\n dedup_key = str(alert.get('dedup_key') or '').strip()\n if not dedup_key:\n stats['skipped_missing_dedup_key_rows'] += 1\n continue\n if dedup_key in seen_dedup_keys:\n stats['skipped_repeated_dedup_key_rows'] += 1\n continue\n seen_dedup_keys.add(dedup_key)\n selected.append(alert)\n stats['first_seen_rows'] = len(selected)\n return selected, stats\n\n\ndef _resolve_output_config():\n config = _load_workflow_config()\n raw_mode = str(_configured_value(config, 'triage_output_mode', 'soc_db') or 'soc_db').strip().lower()\n mode_alias = {\n 'db': 'soc_db',\n 'soc': 'soc_db',\n 'json': 'jsonl',\n 'file': 'jsonl',\n 'files': 'jsonl',\n 'off': 'none',\n 'disabled': 'none',\n }\n requested_mode = mode_alias.get(raw_mode, raw_mode)\n if requested_mode not in {'soc_db', 'jsonl', 'both', 'none'}:\n print(f'[triage_config] WARNING: invalid triage_output_mode={raw_mode!r}; using soc_db')\n requested_mode = 'soc_db'\n\n legacy_jsonl = _input_bool(_configured_value(config, 'persist_triage_output', False), False)\n write_soc_db = requested_mode in {'soc_db', 'both'}\n write_jsonl = requested_mode in {'jsonl', 'both'}\n effective_mode = requested_mode\n if requested_mode == 'soc_db' and legacy_jsonl:\n write_jsonl = True\n effective_mode = 'both'\n if requested_mode == 'none':\n write_soc_db = False\n write_jsonl = False\n effective_mode = 'none'\n\n jsonl_output_dir = _configured_value(config, 'jsonl_output_dir', '') or ''\n jsonl_output_dir = os.path.expanduser(str(jsonl_output_dir)) if jsonl_output_dir else ''\n return {\n 'config_path': _WORKFLOW_CONFIG_PATH,\n 'requested_mode': requested_mode,\n 'mode': effective_mode,\n 'write_soc_db': write_soc_db,\n 'write_jsonl': write_jsonl,\n 'soc_db_path': '',\n 'jsonl_output_dir': jsonl_output_dir,\n }\n\n\n# ── Persisted JSONL output (optional; mirrors stream_alert_denoise layout) ─────\n#\n# Directory : ~/.flocks/workspace/workflows/stream_alert_triage//\n# Filename : triage_result_NNN.jsonl (3-digit zero-padded seq)\n# Layout : line 1 = {\"_type\":\"file_header\", ...}, subsequent lines = one\n# enriched_with_triage alert per line.\n# Counter : .triage_counter.json sidecar tracks (seq, count) so we don't\n# rescan every existing file on each run; auto-rolls over to a\n# new file when reaching MAX_RECORDS_PER_FILE.\n\n\ndef _triage_output_dir(configured_dir=''):\n \"\"\"Return output directory for triage_result_*.jsonl.\"\"\"\n if configured_dir:\n out_dir = configured_dir\n os.makedirs(out_dir, exist_ok=True)\n return out_dir\n from flocks.config import Config\n flocks_root = Config().get_global().data_dir.parent\n date_str = _datetime.datetime.now().strftime('%Y-%m-%d')\n out_dir = flocks_root / 'workspace' / 'workflows' / WORKFLOW_NAME / date_str\n out_dir.mkdir(parents=True, exist_ok=True)\n return str(out_dir)\n\n\ndef _triage_get_counter(out_dir):\n path = os.path.join(out_dir, _TRIAGE_COUNTER_FILE)\n try:\n with open(path, 'r', encoding='utf-8') as f:\n d = json.load(f)\n return int(d.get('seq', 0)), int(d.get('count', 0))\n except Exception:\n return 0, 0\n\n\ndef _triage_set_counter(out_dir, seq, count):\n path = os.path.join(out_dir, _TRIAGE_COUNTER_FILE)\n tmp = path + '.tmp'\n with open(tmp, 'w', encoding='utf-8') as f:\n json.dump({'seq': seq, 'count': count}, f)\n os.replace(tmp, path)\n\n\ndef _triage_find_active_file(out_dir):\n \"\"\"Locate the active (latest, not-yet-full) jsonl file; create if none.\"\"\"\n seq, count = _triage_get_counter(out_dir)\n if seq > 0:\n path = os.path.join(out_dir, f'{_TRIAGE_JSONL_PREFIX}_{seq:03d}.jsonl')\n if os.path.exists(path):\n return path, count, seq\n import glob as _glob\n existing = sorted(_glob.glob(os.path.join(out_dir, _TRIAGE_JSONL_PREFIX + '_*.jsonl')))\n if not existing:\n return None, 0, 0\n latest = existing[-1]\n try:\n seq = int(os.path.basename(latest).replace(_TRIAGE_JSONL_PREFIX + '_', '').replace('.jsonl', ''))\n except ValueError:\n seq = len(existing)\n count = 0\n try:\n with open(latest, 'r', encoding='utf-8') as f:\n for line in f:\n if line.strip() and '\"_type\"' not in line:\n count += 1\n except Exception:\n pass\n return latest, count, seq\n\n\ndef _triage_write_jsonl(out_dir, alerts, run_id, run_stats):\n \"\"\"Append all alerts to today's triage_result_NNN.jsonl, rolling over at\n MAX_RECORDS_PER_FILE. Returns the list of files that were written to.\"\"\"\n now = _datetime.datetime.now()\n written = []\n active_path, active_count, seq = _triage_find_active_file(out_dir)\n remaining = list(alerts)\n while remaining:\n available = MAX_RECORDS_PER_FILE - active_count\n if available <= 0 or active_path is None:\n seq += 1\n active_path = os.path.join(out_dir, f'{_TRIAGE_JSONL_PREFIX}_{seq:03d}.jsonl')\n active_count = 0\n available = MAX_RECORDS_PER_FILE\n header = {\n '_type': 'file_header',\n 'created_at': now.isoformat(),\n 'date': now.strftime('%Y-%m-%d'),\n 'workflow': WORKFLOW_NAME,\n 'seq': seq,\n 'run_id': run_id,\n 'batch_total': run_stats.get('total'),\n 'batch_triaged': run_stats.get('triaged'),\n 'batch_followers_reused':run_stats.get('followers_reused'),\n 'batch_cache_hit': run_stats.get('cache_hit'),\n 'batch_triage_failed': run_stats.get('triage_failed'),\n }\n with open(active_path, 'w', encoding='utf-8') as hf:\n hf.write(json.dumps(header, ensure_ascii=False) + '\\n')\n batch = remaining[:available]\n remaining = remaining[available:]\n with open(active_path, 'a', encoding='utf-8') as af:\n for alert in batch:\n af.write(json.dumps(alert, ensure_ascii=False) + '\\n')\n active_count += len(batch)\n if active_path not in written:\n written.append(active_path)\n if remaining:\n active_path = None\n active_count = 0\n if written:\n _triage_set_counter(out_dir, seq, active_count)\n return written\n\n\n# ── SOC DB output (default) ───────────────────────────────────────────────────\n\ndef _triage_write_soc_db(alerts, run_id):\n \"\"\"Hand the alerts to the platform's SOC alert store, in bounded batches.\n\n flocks-soc-store-client: this node opens no database of its own. The store\n is the host's (the `soc` service of the database backend in use), so the\n same code serves every backend.\n \"\"\"\n loaded_files = inputs.get('loaded_files') or []\n source_file = str(loaded_files[0]) if isinstance(loaded_files, list) and len(loaded_files) == 1 else ''\n result = {'backend': '', 'path': '', 'table': '',\n 'rows': 0, 'inserted_rows': 0, 'updated_rows': 0, 'unchanged_rows': 0}\n max_bytes = 2 * 1024 * 1024\n batch = []\n batch_bytes = 2\n\n def flush():\n persisted = soc.write_alerts(batch, str(run_id), source_file)\n for key in ('rows', 'inserted_rows', 'updated_rows', 'unchanged_rows'):\n result[key] += int(persisted.get(key, 0) or 0)\n for key in ('backend', 'path', 'table'):\n if persisted.get(key):\n result[key] = str(persisted[key])\n\n for alert in alerts:\n # An alert larger than a batch goes alone: the store says whether it takes it.\n size = len(json.dumps(alert, ensure_ascii=False, separators=(',', ':')).encode('utf-8'))\n if batch and (len(batch) >= 200 or batch_bytes + size + 1 > max_bytes):\n flush()\n batch = []\n batch_bytes = 2\n batch_bytes += size + (1 if batch else 0)\n batch.append(alert)\n if batch:\n flush()\n return result\n\n\n# ── LLM provider warm-up (avoid cold-start race in _parallel_4_branches) ──────\n#\n# Background: when this node starts, the LLM provider (e.g. threatbook-cn-llm)\n# is lazy-initialized on the first call. Inside `_parallel_4_branches` we\n# submit 4 LLM calls to a ThreadPoolExecutor simultaneously; whichever one\n# wins the race may race against provider registration and fail with\n# \"provider 'xxx' not exists\" while subsequent calls succeed. A single\n# synchronous warm-up call before any concurrent fan-out forces the provider\n# to finish registering on the main thread, eliminating the race entirely.\n#\n# Failure of the warm-up is non-fatal — we just log and continue. The first\n# real LLM call will still see the same error and surface it normally.\n\ndef _warmup_llm():\n \"\"\"Force LLM provider lazy-init on the main thread before any fan-out.\"\"\"\n t0 = time.time()\n try:\n _ask_llm('ping')\n print(f'[triage] LLM provider warm-up OK in {round((time.time()-t0)*1000)}ms')\n return True\n except Exception as e:\n print(f'[triage] WARNING: LLM warm-up failed ({type(e).__name__}: '\n f'{str(e)[:200]}); proceeding anyway')\n return False\n\n\n# ── Inline triage helpers (mirroring tdp_alert_triage docs version) ───────────\n\ndef _strip_think(text):\n return re.sub(r'[\\s\\S]*?', '', str(text or ''), flags=re.IGNORECASE).strip()\n\n\ndef _is_public_ip(value):\n try:\n ip_obj = ipaddress.ip_address(value)\n except Exception:\n return False\n return not (ip_obj.is_private or ip_obj.is_loopback or ip_obj.is_reserved\n or ip_obj.is_link_local or ip_obj.is_multicast or ip_obj.is_unspecified)\n\n\ndef _pick(*values):\n for v in values:\n if v not in (None, '', [], {}):\n return v\n return ''\n\n\ndef _parse_alert(alert_input):\n \"\"\"Mirrors tdp_alert_triage.receive_alert. Supports three input shapes:\n nested TDP (net.http.url), flat TDP (net_http_url), normalized (req_http_url).\n \"\"\"\n if isinstance(alert_input, str):\n try:\n alert_input = json.loads(alert_input)\n except Exception:\n alert_input = {}\n if isinstance(alert_input, list):\n alert_data = alert_input[0] if alert_input else {}\n elif isinstance(alert_input, dict) and isinstance(alert_input.get('data'), list):\n alert_data = alert_input.get('data', [])[0] if alert_input.get('data') else {}\n else:\n alert_data = alert_input if isinstance(alert_input, dict) else {}\n\n if alert_data.get('_source_type') == 'sangfor-sip':\n from flocks.ingest.syslog.sangfor import parse_sangfor_for_triage\n return parse_sangfor_for_triage(alert_data)\n\n net = alert_data.get('net', {}) or {}\n http = net.get('http', {}) or {}\n threat = alert_data.get('threat', {}) or {}\n assets = alert_data.get('assets', {}) or {}\n\n src_ip = _pick(\n alert_data.get('attacker'), alert_data.get('external_ip'),\n net.get('src_ip'), net.get('flow_src_ip'),\n alert_data.get('net_real_src_ip'),\n alert_data.get('sip'), alert_data.get('src_ip'), alert_data.get('src'),\n )\n dst_ip = _pick(\n alert_data.get('victim'), alert_data.get('machine'),\n alert_data.get('server_ip'), net.get('dest_ip'), net.get('flow_dest_ip'),\n alert_data.get('net_dest_ip'),\n alert_data.get('dip'), alert_data.get('dst_ip'), alert_data.get('dst'),\n )\n src_port = _pick(\n net.get('src_port'), net.get('flow_src_port'),\n alert_data.get('external_port'), alert_data.get('net_src_port'),\n alert_data.get('sport'), alert_data.get('src_port'), 0,\n )\n dst_port = _pick(\n net.get('dest_port'), net.get('flow_dest_port'),\n alert_data.get('server_port'), alert_data.get('machine_port'),\n alert_data.get('net_dest_port'),\n alert_data.get('dport'), alert_data.get('dst_port'), 0,\n )\n protocol = _pick(\n net.get('app_proto'), net.get('type'), net.get('proto'),\n alert_data.get('net_app_proto'), alert_data.get('protocol'),\n alert_data.get('event_type'), 'TCP',\n )\n alert_type = _pick(\n threat.get('name'), alert_data.get('threat_name'),\n alert_data.get('vuln_name'),\n alert_data.get('alert_type'), threat.get('topic'),\n alert_data.get('type'), 'unknown',\n )\n severity = _pick(\n threat.get('severity'), alert_data.get('threat_severity'),\n alert_data.get('severity'), threat.get('level'),\n alert_data.get('level'), 'medium',\n )\n\n req_line = _pick(http.get('reqs_line'), alert_data.get('req_line'), alert_data.get('net_http_reqs_line'))\n req_header = _pick(http.get('reqs_header'), alert_data.get('req_header'), alert_data.get('net_http_reqs_header'))\n req_body = _pick(http.get('req_body'), alert_data.get('req_body'), alert_data.get('net_http_reqs_body'))\n resp_line = _pick(http.get('resp_line'), alert_data.get('rsp_line'), alert_data.get('resp_line'),\n alert_data.get('net_http_resp_line'))\n resp_header = _pick(http.get('resp_header'), alert_data.get('rsp_header'), alert_data.get('resp_header'),\n alert_data.get('net_http_resp_header'))\n resp_body = _pick(http.get('resp_body'), alert_data.get('rsp_body'), alert_data.get('resp_body'),\n alert_data.get('net_http_resp_body'))\n status = _pick(http.get('status'), alert_data.get('http_status'),\n alert_data.get('net_http_status'), alert_data.get('rsp_status_code'), 0)\n\n host = _pick(http.get('reqs_host'), alert_data.get('url_host'), http.get('domain'),\n alert_data.get('req_host'), alert_data.get('net_http_reqs_host'), dst_ip)\n raw_url = _pick(http.get('raw_url'), http.get('url'),\n alert_data.get('url_path'),\n alert_data.get('net_http_url'), alert_data.get('req_http_url'),\n alert_data.get('uri'))\n url = ''\n if host and raw_url:\n scheme = 'https' if net.get('is_https') else 'http'\n url = raw_url if str(raw_url).startswith(('http://', 'https://')) else f'{scheme}://{host}{raw_url}'\n elif raw_url and str(raw_url).startswith(('http://', 'https://')):\n url = raw_url\n elif raw_url:\n url = raw_url\n\n payload = f'请求行: {req_line}\\n请求头: {req_header}\\n请求体: {req_body}'\n response = f'状态行: {resp_line}\\n响应头: {resp_header}\\n响应体: {resp_body}'\n threat_result = _pick(threat.get('result'), alert_data.get('threat_result'))\n threat_msg = _pick(threat.get('msg'), alert_data.get('threat_msg'))\n\n log_text = (\n f'[告警基本信息]\\n'\n f'告警类型: {alert_type}\\n严重级别: {severity}\\n'\n f'源地址: {src_ip}:{src_port}\\n目的地址: {dst_ip}:{dst_port}\\n'\n f'协议: {protocol}\\nURL: {url}\\nHTTP状态码: {status}\\n'\n f'TDP判定: {threat_result}\\nTDP消息: {threat_msg}\\n\\n'\n f'[HTTP请求内容]\\n{payload}\\n\\n'\n f'[HTTP响应内容]\\n{response}'\n )\n\n vuln_text = '\\n'.join(str(item) for item in [\n threat_msg, threat.get('topic', ''),\n alert_data.get('data', ''), url,\n json.dumps(threat.get('tag', []), ensure_ascii=False),\n ] if item)\n vuln_matches = sorted(set(re.findall(r'\\b(?:CVE|CNVD|CNNVD|XVE)-[A-Za-z0-9._-]+\\b', vuln_text, flags=re.I)))\n\n iocs = []\n for candidate in [src_ip, dst_ip]:\n if candidate:\n iocs.append({'type': 'ip', 'value': candidate})\n if url:\n iocs.append({'type': 'url', 'value': url})\n if host and not re.match(r'^\\d{1,3}(?:\\.\\d{1,3}){3}(?::\\d+)?$', str(host)):\n iocs.append({'type': 'domain', 'value': str(host).split(':')[0]})\n\n return {\n 'src_ip': src_ip, 'dst_ip': dst_ip, 'src_port': src_port, 'dst_port': dst_port,\n 'protocol': protocol, 'payload': payload, 'response': response,\n 'url': url, 'status': status,\n 'alert_type': alert_type, 'severity': severity,\n 'vuln_id': vuln_matches[0] if vuln_matches else '',\n 'vuln_candidates': vuln_matches,\n 'threat_result': threat_result, 'threat_msg': threat_msg,\n 'failed_by': threat.get('failed_by', []),\n 'asset_ip': assets.get('ip', ''), 'asset_name': assets.get('name', []),\n 'iocs': iocs, 'log_text': log_text,\n }\n\n\n# MCP tools register as \"_\". ThreatBook's server is named\n# threatbook_mcp by default and threatbook in older configurations. Workflow\n# code needs exact names: the \"__mcp_\" wildcard only works in agent tool lists.\nINTEL_TOOLS = {\n 'ip': ('threatbook_mcp_ip_query', 'threatbook_ip_query'),\n 'domain': ('threatbook_mcp_domain_query', 'threatbook_domain_query'),\n 'vuln': ('threatbook_mcp_vuln_query', 'threatbook_vuln_query'),\n # Not every ThreatBook configuration has a URL lookup. The URL host is\n # queried as a domain as well, so a missing URL tool is not reported.\n 'url': ('threatbook_mcp_url_query', 'threatbook_url_query'),\n}\n_intel_tool_names = {}\n_intel_tool_lock = threading.Lock()\n\n\ndef _run_intel_tool(kind, **kwargs):\n \"\"\"Run the first registered tool for ``kind``; None when none is registered.\n\n The tool found is reused for the rest of the run. A missing intel source is\n logged once instead of silently leaving every triage without intel.\n \"\"\"\n with _intel_tool_lock:\n resolved = _intel_tool_names.get(kind)\n if resolved == '':\n return None\n for name in ((resolved,) if resolved else INTEL_TOOLS[kind]):\n r = tool.run_safe(name, **kwargs)\n # Only the adapter's own message for this name means \"not registered\";\n # any other error, even one quoting it, is a failure of a registered tool.\n if not r['success'] and str(r.get('error') or '').strip() == f'Tool not found: {name!r}':\n continue\n with _intel_tool_lock:\n _intel_tool_names[kind] = name\n return r\n with _intel_tool_lock:\n first_miss = _intel_tool_names.get(kind) != ''\n _intel_tool_names[kind] = ''\n if first_miss and kind != 'url':\n print(f'[triage] WARNING: no {kind} intel tool is registered '\n f'(tried {\", \".join(INTEL_TOOLS[kind])}); triage continues without it')\n return None\n\n\ndef _prepare_intel(parsed):\n \"\"\"Mirrors tdp_alert_triage.prepare_intel. Pre-fetches IP/domain/URL threat intel\n and CVE info so the parallel LLM tasks have concrete context to consume.\n \"\"\"\n iocs = parsed.get('iocs', [])\n intel_results = []\n seen = set()\n for ioc in iocs:\n ioc_type = ioc.get('type', '')\n ioc_value = str(ioc.get('value', '')).strip()\n key = (ioc_type, ioc_value)\n if not ioc_value or key in seen:\n continue\n seen.add(key)\n if ioc_type == 'ip':\n if not _is_public_ip(ioc_value):\n continue\n r = _run_intel_tool('ip', ip=ioc_value)\n elif ioc_type == 'domain':\n r = _run_intel_tool('domain', domain=ioc_value)\n elif ioc_type == 'url':\n r = _run_intel_tool('url', url=ioc_value)\n else:\n continue\n if r and r['success']:\n intel_results.append({'source': 'threatbook', 'type': ioc_type,\n 'value': ioc_value, 'result': r['text']})\n\n vuln_info = {}\n vuln_id = parsed.get('vuln_id', '')\n if vuln_id:\n r = _run_intel_tool('vuln', vuln_id=vuln_id)\n if r and r['success']:\n try:\n obj = r.get('obj')\n if isinstance(obj, str):\n obj = json.loads(obj)\n vuln_info = obj if isinstance(obj, dict) else {'raw_result': r.get('text', '')}\n except Exception:\n vuln_info = {'raw_result': r.get('text', '')}\n\n intel_content = '\\n'.join(\n f\"[{i['source']}/{i['type']}] {i['value']}\\n{i['result']}\" for i in intel_results\n ) or '(无可用情报数据)'\n vuln_content = (\n json.dumps(vuln_info, ensure_ascii=False, indent=2)\n if vuln_info else '(无可用漏洞情报数据)'\n )\n return intel_results, intel_content, vuln_info, vuln_content\n\n\n# ── 4 LLM analysis branches (sharing one run-wide request budget) ───────────\n\ndef _ask_llm(prompt):\n \"\"\"Wrap ``llm.ask`` with the workflow-wide timeout + retry budget.\n\n Centralizing this avoids a hung provider request (no TCP timeout from\n upstream) from blocking a worker thread indefinitely. Any call that does\n not need bespoke parameters should go through here.\n \"\"\"\n kwargs = {\n 'timeout_s': LLM_CALL_TIMEOUT_S,\n 'max_retries': LLM_CALL_MAX_RETRIES,\n }\n if _llm_slots is None:\n return llm.ask(prompt, **kwargs)\n with _llm_slots:\n return llm.ask(prompt, **kwargs)\n\n\ndef _llm_survey(log_text, intel_content):\n prompt = f'''你是一个专业的Web日志分析专家。请总结以下IP的情报数据中的空间测绘信息。\n1. 如果该IP没有测绘信息,则不列出。\n2. 如果IP有测绘信息,则以简短的语言对该IP的测绘信息进行总结,关键说明ip的标签和测绘信息显示有哪些服务或者应用资产。\n3. 多个IP的测绘信息以无序列表显示,每个ip数据描述占一行数据。\n4. 不需要生成其他额外的补充信息。\n\n## 情报参考信息\n{intel_content}\n\n## 用户的原始输入日志\n{log_text}\n'''\n return _strip_think(_ask_llm(prompt))\n\n\ndef _llm_cve_related(log_text):\n prompt = f'''请从以下的日志数据中提取漏洞编号。\n要求:\n1. 仅从日志文本中识别漏洞编号,不要做任何推测。\n2. 如果日志中存在漏洞编号,则用简短语言描述,如:\"日志中存在漏洞编号:CVE-****-****\"。\n3. 如果日志中不存在漏洞编号,则输出:\"日志中无关联漏洞情报\"。\n\n日志数据如下:\n{log_text}\n'''\n return _strip_think(_ask_llm(prompt))\n\n\ndef _llm_cve_info(log_text, vuln_content):\n prompt = f'''你是一个专业的Web日志分析专家。参考情报信息中的漏洞数据,简要说明关联的CVE漏洞信息。\n1. 不要输出任何解释说明,只输出漏洞基本信息。不需要生成漏洞的处置建议或修复措施等。\n\n## 情报参考信息\n{vuln_content}\n\n## 用户的原始输入日志\n{log_text}\n'''\n return _strip_think(_ask_llm(prompt))\n\n\ndef _llm_payload_analysis(log_text):\n prompt = f'''你是一个专业的Web日志分析专家。根据用户输入的日志进行攻击负载分析。\n1. 首先分析日志中是否包含攻击负载,并给出判定依据。\n2. 不要进行攻击意图分析、攻击影响分析。\n3. 用简短的语言在一段话中进行描述。\n\n## 用户的原始输入日志:\n{log_text}\n'''\n return _strip_think(_ask_llm(prompt))\n\n\ndef _parallel_4_branches(parsed, intel_content, vuln_content):\n \"\"\"Submit 4 logical branches; _ask_llm enforces the run-wide provider budget.\"\"\"\n log_text = parsed.get('log_text', '')\n with ThreadPoolExecutor(max_workers=4, thread_name_prefix='triage_branch') as pool:\n futs = {\n 'survey_result': pool.submit(_llm_survey, log_text, intel_content),\n 'cve_related_result': pool.submit(_llm_cve_related, log_text),\n 'cve_info_result': pool.submit(_llm_cve_info, log_text, vuln_content),\n 'payload_analysis_result': pool.submit(_llm_payload_analysis, log_text),\n }\n out = {}\n for name, fut in futs.items():\n try:\n out[name] = fut.result()\n except Exception as e:\n print(f'[triage] WARNING: branch {name} failed: {e}')\n out[name] = ''\n return out\n\n\n# ── Join-point LLM analyses (attack_analysis_result -> verdict -> title) ──────\n\ndef _llm_attack_analysis(log_text):\n prompt = f'''你是一名专业且经验丰富的网络安全分析师和Web日志分析专家,你对HTTP协议以及Web攻击有着深入的理解,并且你能够快速识别和应对各种网络威胁。你的任务是对提供的HTTP请求与响应内容进行详细的专业分析,并判断日志请求的攻击状态。\n\n请严格遵循以下指令进行思考和分析:\n1. 分别判断是否为攻击(攻击/非攻击/未知)以及攻击结果(攻击成功/攻击失败/未知)。\n2. 从日志中提取出\"HTTP请求内容\"和\"HTTP响应内容\"。请注意,HTTP请求内容和HTTP响应内容是分开的,请不要混淆,有些日志中没有包含HTTP响应内容,请不要将HTTP请求内容和HTTP响应内容混淆。分析后请你记住哪些是HTTP请求内容,哪些是HTTP响应内容。\n3. 请检查HTTP响应状态码,2xx或者3xx状态码都代表本次HTTP请求成功,4xx或者5xx状态码大多数情况下都代表请求失败,只有在请求成功的情况下才能对攻击是否成功进行后续判断。\n\n各攻击状态的定义以及判定标准:\n1. 攻击成功:\n(1) 首先分析日志中是否含有清晰的\"HTTP响应内容\",如果日志中没有\"HTTP响应内容\",则肯定不属于攻击成功。\n(2) 如果日志中未提供\"HTTP响应内容\",即使HTTP请求内容中包含攻击者预期的结果,也不能判定为攻击成功。\n(3) 从日志中提取出\"HTTP请求内容\"和\"HTTP响应内容\"。请深入分析\"HTTP响应内容\",并判定其是否为\"HTTP请求内容\"攻击成功时的预期结果,这是判定攻击成功的强依据。请注意,HTTP响应码200仅表示网络连接成功,不代表攻击攻击成功。\n(4) 分析HTTP请求内容和HTTP响应内容,只有当HTTP响应内容中明确包含攻击载荷在目标机器上成功执行的证据,并且HTTP请求内容中包含攻击载荷的特征,则判定为\"攻击成功\"。\n(5) 请注意:攻击成功的判定必须包含HTTP响应内容。如果不包含HTTP响应内容,则肯定不属于攻击成功。\n(6) 请注意:如果不包含HTTP响应内容,即使HTTP请求内容是攻击,这也不属于攻击成功。\n2. 攻击失败:\n(1) 分析HTTP请求内容和HTTP响应内容,如果HTTP响应内容中明确包含攻击载荷在目标机器上执行失败或者被阻止的证据,并且HTTP请求内容中包含攻击载荷的特征,则判定为\"攻击失败\"。\n(2) 攻击失败的判定必须包含HTTP响应内容。如果不包含HTTP响应内容,则肯定不属于攻击失败。\n3. 攻击:\n(1) 在\"HTTP请求内容\"或\"HTTP响应内容\"中发现任何证明存在攻击意图的证据,即可判定为存在攻击行为。但如果不符合上述的攻击成功或者攻击失败的标准,则\"攻击状态\"为\"攻击\"。\n(2) 请注意:如果日志中只提供了\"HTTP请求内容\",且没有提供\"HTTP响应内容\",且HTTP的请求内容分析中是包含攻击行为的,则\"攻击状态\"为\"攻击\"。\n4. 未知:\n(1) 如果不能100%确定HTTP通信的攻击结果,那么请在\"攻击状态\"处给出\"未知\"。\n(2) 请注意:如果在你给的判定原因中存在\"可能\"等不确定词汇,都代表你不能对你的结论100%确定,那么请在\"攻击状态\"处给出\"未知\"。\n5. 安全:\n(1) 如果\"HTTP请求内容\"和\"HTTP响应内容\"中都没有任何攻击意图的证据,那么请在\"攻击状态\"处给出\"安全\"。\n\n## 日志内容\n{log_text}\n\n## 输出要求\n请按下列结构输出(中文):\n1. 是否攻击: [攻击/非攻击/未知]\n2. 攻击结果: [攻击成功/攻击失败/未知]\n3. 判定依据: 简要说明请求与响应的关键证据\n4. 详细分析: 不超过200字\n'''\n return _strip_think(_ask_llm(prompt))\n\n\ndef _normalize_triage_outcome(attack_verdict, attack_success):\n verdict = str(attack_verdict or '').strip().lower()\n result = str(attack_success or '').strip().lower()\n if verdict not in {'attack', 'non_attack', 'unknown'}:\n verdict = 'unknown'\n if result not in {'success', 'failed', 'unknown'}:\n result = 'unknown'\n if verdict != 'attack':\n result = 'unknown'\n return verdict, result\n\n\ndef _triage_outcome_key(attack_verdict, attack_success):\n verdict, result = _normalize_triage_outcome(attack_verdict, attack_success)\n if verdict == 'attack':\n if result == 'success':\n return 'attack_success'\n if result == 'failed':\n return 'attack_failed'\n return 'attack'\n if verdict == 'non_attack':\n return 'non_attack'\n return 'unknown'\n\n\ndef _llm_attack_outcome(attack_analysis_result):\n prompt = f'''你是一个专业的 Web 日志分析专家。根据参考信息,输出且仅输出一个 JSON 对象:\n{{\n \"triage_attack_verdict\": \"attack | non_attack | unknown\",\n \"triage_attack_success\": \"success | failed | unknown\"\n}}\n\n字段规则:\n1. triage_attack_verdict 只表示是否为攻击:attack=攻击,non_attack=非攻击,unknown=无法判断。\n2. triage_attack_success 只表示攻击结果:success=攻击成功,failed=攻击失败,unknown=无法判断结果。\n3. 只有 triage_attack_verdict=attack 时,攻击结果才允许为 success 或 failed。\n4. 当 triage_attack_verdict 为 non_attack 或 unknown 时,triage_attack_success 必须为 unknown。\n5. 不要输出解释、Markdown 或其他字段。\n\n## 日志分析结果\n{attack_analysis_result}\n'''\n raw = _strip_think(_ask_llm(prompt)).strip()\n match = re.search(r'\\{.*?\\}', raw, flags=re.S)\n try:\n parsed = json.loads(match.group(0)) if match else {}\n except Exception:\n parsed = {}\n verdict, result = _normalize_triage_outcome(\n parsed.get('triage_attack_verdict'),\n parsed.get('triage_attack_success'),\n )\n return {\n 'triage_attack_verdict': verdict,\n 'triage_attack_success': result,\n }\n\n\ndef _llm_report_title(alert_type, attack_verdict, attack_success, attack_analysis_result):\n prompt = f'''你是一个专业的Web日志分析专家。请基于以下分析结果,生成一份不超过 30 字的中文报告标题。\n要求:\n1. 标题必须能体现\"攻击类型\"或\"攻击结果分析的结论\"。\n2. 不要带书名号、引号或其他标点。\n3. 只输出标题本身,不要任何解释或说明。\n\n## 攻击类型\n{alert_type}\n\n## 是否攻击\n{attack_verdict}\n\n## 攻击结果\n{attack_success}\n\n## 攻击分析结果\n{attack_analysis_result}\n'''\n raw = _strip_think(_ask_llm(prompt)).strip()\n outcome_cn = OUTCOME_CN.get(\n _triage_outcome_key(attack_verdict, attack_success),\n '未知',\n )\n return raw.splitlines()[0].strip(' \"\\'《》[]【】') if raw else f'{alert_type} - {outcome_cn}'\n\n\ndef _clip_text(value, limit=3000):\n text = str(value or '').strip()\n if len(text) > limit:\n return text[:limit] + '\\n...(已截断)'\n return text or '未提供'\n\n\ndef _fence_text(value):\n text = _clip_text(value, 6000)\n return text.replace('```', '``\\\\u200b`')\n\n\ndef _extract_tagged_triage_report(text):\n text = _strip_think(text)\n m = re.search(r']*>[\\s\\S]*?', text, flags=re.I)\n return m.group(0).strip() if m else text.strip()\n\n\ndef _is_valid_triage_report(markdown):\n text = str(markdown or '')\n if not re.search(r']*version=[\"\\']soc\\.triage\\.markdown\\.v1[\"\\'][^>]*>', text, flags=re.I):\n return False\n if not re.search(r'', text, flags=re.I):\n return False\n for tag in TRIAGE_REPORT_TAGS:\n if not re.search(rf'<{tag}\\b[^>]*>', text, flags=re.I):\n return False\n if not re.search(rf'', text, flags=re.I):\n return False\n return True\n\n\ndef _is_current_triage_fields(fields):\n if not isinstance(fields, dict):\n return False\n verdict = fields.get('triage_attack_verdict')\n result = fields.get('triage_attack_success')\n normalized = _normalize_triage_outcome(verdict, result)\n return (\n (verdict, result) == normalized\n and all(key in fields for key in TRIAGE_FIELDS)\n and _is_valid_triage_report(fields.get('triage_report'))\n )\n\n\ndef _format_intel_brief(intel_results):\n if not intel_results:\n return '未查询到外部威胁情报。'\n lines = []\n for intel in intel_results[:6]:\n lines.append(f\"- {intel.get('source', 'intel')} / {intel.get('type', 'ioc')}: {intel.get('value', '')} => {_clip_text(intel.get('result'), 500)}\")\n return '\\n'.join(lines)\n\n\ndef _build_default_tagged_triage_report(parsed, intel_results, vuln_info, branches,\n attack_analysis_result, attack_verdict,\n attack_success, report_title, risk_level):\n outcome = _triage_outcome_key(attack_verdict, attack_success)\n verdict_cn = OUTCOME_CN.get(outcome, '未知')\n attack_verdict_cn = ATTACK_VERDICT_CN.get(attack_verdict, '未知')\n attack_success_cn = ATTACK_SUCCESS_CN.get(attack_success, '未知')\n title = report_title or f'{parsed.get(\"alert_type\", \"Web日志告警\")} - {verdict_cn}'\n payload = _fence_text(parsed.get('payload', ''))\n response = _fence_text(parsed.get('response', ''))\n url = parsed.get('url') or '未提供'\n threat_msg = parsed.get('threat_msg') or '未提供'\n status = parsed.get('status') or '未提供'\n survey = _clip_text(branches.get('survey_result'), 1500)\n cve_related = _clip_text(branches.get('cve_related_result'), 1500)\n cve_info = _clip_text(branches.get('cve_info_result'), 1500)\n payload_analysis = _clip_text(branches.get('payload_analysis_result'), 1500)\n attack_analysis = _clip_text(attack_analysis_result, 1500)\n intel_brief = _format_intel_brief(intel_results)\n vuln_brief = _clip_text(json.dumps(vuln_info, ensure_ascii=False, indent=2), 1800) if vuln_info else '未查询到漏洞详情。'\n\n if outcome == 'attack_success':\n recommendation = '立即核查目标资产是否产生异常文件、进程、账号或敏感数据访问记录,并按成功入侵事件升级处置。'\n elif outcome == 'attack_failed':\n recommendation = '保留拦截与响应证据,复核同源后续请求,并确认防护策略是否持续生效。'\n elif outcome == 'non_attack':\n recommendation = '作为低风险事件留痕,结合资产白名单或业务访问记录确认是否可降噪。'\n else:\n recommendation = '补齐目标 Web 日志、响应体、主机侧进程和文件证据后再确认攻击成功性。'\n\n return f'''\n\n\n# {title}\n\n\n\n- 是否攻击:{attack_verdict_cn}\n- 攻击结果:{attack_success_cn}\n- 研判结论:{verdict_cn}\n- 风险等级:{risk_level}\n- 告警类型:{parsed.get('alert_type', 'unknown')}\n- 源 IP:{parsed.get('src_ip', 'N/A')}:{parsed.get('src_port', 'N/A')}\n- 目标资产:{parsed.get('dst_ip', 'N/A')}:{parsed.get('dst_port', 'N/A')}\n- URL:{url}\n- 响应码:{status}\n\n\n\n## 分析步骤\n\n### 1. 日志类型分析\n该告警按 Web 日志处理,已提取 HTTP 请求、响应、源地址、目标资产、URL、响应码和 TDP 判定字段。\n\n### 2. 情报信息\n{intel_brief}\n\n### 3. 测绘信息\n{survey}\n\n### 4. 告警关联漏洞情报\n{cve_related}\n\n### 5. 攻击负载分析\n{payload_analysis}\n\n### 6. 攻击分析结果\n{attack_analysis}\n\n\n\n## 研判结论\n当前研判结论为 **{verdict_cn}**,风险等级为 **{risk_level}**。TDP 消息为:{threat_msg}\n\n\n\n## 攻击payload\n\n```http\n{payload}\n```\n\n\n\n## 具体含义解释\n\n1. 请求命中的告警类型为 {parsed.get('alert_type', 'unknown')}。\n2. 请求 URL 为 {url},需要结合参数、请求体和目标业务判断攻击意图。\n3. Payload 分析结果:{payload_analysis}\n\n\n\n## 响应证据\n\n```http\n{response}\n```\n\n响应码为 {status}。如果响应体未提供或没有执行成功证据,则不能仅凭请求侧 payload 判定攻击成功。\n\n\n\n## 重要证据\n\n1. 源地址:{parsed.get('src_ip', 'N/A')}:{parsed.get('src_port', 'N/A')}。\n2. 目标资产:{parsed.get('dst_ip', 'N/A')}:{parsed.get('dst_port', 'N/A')}。\n3. TDP 判定:{parsed.get('threat_result', '未提供')};TDP 消息:{threat_msg}。\n4. 漏洞详情:{vuln_brief}\n\n\n\n## 处置建议\n\n1. {recommendation}\n2. 检索同源 IP、同一 dedup_key、同一 URL 或同一漏洞特征的横向告警。\n3. 结合目标资产 Web 访问日志、主机审计、EDR 与 WAF 日志补齐证据链。\n\n\n'''\n\n\ndef _llm_triage_report_markdown(parsed, intel_results, vuln_info, branches,\n attack_analysis_result, attack_verdict,\n attack_success, report_title, risk_level):\n verdict_cn = OUTCOME_CN.get(\n _triage_outcome_key(attack_verdict, attack_success),\n '未知',\n )\n context = json.dumps({\n 'report_title': report_title,\n 'triage_attack_verdict': attack_verdict,\n 'triage_attack_success': attack_success,\n 'verdict_cn': verdict_cn,\n 'risk_level': risk_level,\n 'alert': {\n 'alert_type': parsed.get('alert_type'),\n 'severity': parsed.get('severity'),\n 'src_ip': parsed.get('src_ip'),\n 'src_port': parsed.get('src_port'),\n 'dst_ip': parsed.get('dst_ip'),\n 'dst_port': parsed.get('dst_port'),\n 'url': parsed.get('url'),\n 'status': parsed.get('status'),\n 'threat_result': parsed.get('threat_result'),\n 'threat_msg': parsed.get('threat_msg'),\n 'payload': parsed.get('payload'),\n 'response': parsed.get('response'),\n },\n 'survey_result': branches.get('survey_result'),\n 'cve_related_result': branches.get('cve_related_result'),\n 'cve_info_result': branches.get('cve_info_result'),\n 'payload_analysis_result': branches.get('payload_analysis_result'),\n 'attack_analysis_result': attack_analysis_result,\n 'intel_results': intel_results,\n 'vuln_info': vuln_info,\n }, ensure_ascii=False, indent=2)\n\n prompt = f'''你是一名资深 SOC 告警研判分析师。请根据输入上下文,生成一份供前端直接渲染的 SOC 告警研判报告 markdown。\n\n硬性要求:\n1. 只输出带语义标签的 markdown,不要输出 JSON,不要解释规则。\n2. 根标签必须是 。\n3. 必须按顺序输出并完整闭合这些标签:\n 、、、、、、、、。\n4. 标签外不得输出正文内容。标签内可以使用 markdown 标题、列表、引用、代码块。\n5. 段落标题必须贴近前端展示模板:分析步骤、研判结论、攻击payload、具体含义解释、响应证据、重要证据、处置建议。\n6. 如果没有 HTTP 响应体或没有明确响应证据,不得判定为攻击成功;需要写明“当前日志未提供有效响应证据”。\n7. 不要编造输入中不存在的 IP、域名、URL、CVE、账号、文件路径或响应内容。\n8. 攻击 payload 和响应证据必须分别放在对应标签中,不要混淆请求与响应。\n9. 研判结论必须严格遵循上下文中的 triage_attack_verdict 和 triage_attack_success,不得使用原始告警同名字段替代。\n\nFew-shot 示例 1:攻击成功\n\n\n\n# 敏感文件泄露攻击成功分析报告\n\n\n\n- 研判结论:攻击成功\n- 风险等级:High\n- 告警类型:敏感文件访问\n- 源 IP:203.0.113.10:42131\n- 目标资产:198.51.100.20:80\n- URL:http://example.com/api/.env\n- 响应码:200\n\n\n\n## 分析步骤\n\n### 1. 日志类型分析\n该日志包含 HTTP 请求路径、响应码和响应体,可用于判断敏感文件是否被返回。\n\n### 2. 情报信息\n源 IP 命中扫描源标签,风险高。\n\n### 3. 测绘信息\n目标为公网 Web 服务,存在敏感路径暴露风险。\n\n### 4. 告警关联漏洞情报\n该行为与环境变量文件泄露场景一致。\n\n### 5. 攻击负载分析\n攻击者直接请求 /api/.env,目标是读取环境变量配置。\n\n### 6. 攻击分析结果\n响应码为 200,响应体中出现 DB_PASSWORD,支持攻击成功。\n\n\n\n## 研判结论\n攻击者成功读取敏感配置文件,响应体中包含数据库密码字段,结论为攻击成功。\n\n\n\n## 攻击payload\n\n```http\nGET /api/.env HTTP/1.1\nHost: example.com\n```\n\n\n\n## 具体含义解释\n\n1. /api/.env 是常见环境变量文件路径。\n2. 攻击者通过 GET 请求尝试直接读取配置文件。\n3. 该路径若返回真实内容,通常意味着敏感文件暴露。\n\n\n\n## 响应证据\n\n```http\nHTTP/1.1 200 OK\n\nDB_PASSWORD=example-secret\n```\n\n响应体出现 DB_PASSWORD,证明敏感配置内容已被返回。\n\n\n\n## 重要证据\n\n1. 请求路径为 /api/.env。\n2. 响应码为 200。\n3. 响应体包含 DB_PASSWORD。\n\n\n\n## 处置建议\n\n1. 立即下线或限制敏感文件访问。\n2. 轮换可能泄露的密钥和数据库密码。\n3. 检索同源 IP 和同路径访问记录。\n\n\n\n\nFew-shot 示例 2:攻击失败\n\n\n\n# SQL注入攻击失败分析报告\n\n\n\n- 研判结论:攻击失败\n- 风险等级:Medium\n- 告警类型:SQL注入\n- 源 IP:203.0.113.44:51002\n- 目标资产:198.51.100.30:443\n- URL:https://shop.example.com/item?id=1\n- 响应码:403\n\n\n\n## 分析步骤\n\n### 1. 日志类型分析\n该日志包含请求参数和响应码,能够确认请求侧存在 SQL 注入尝试。\n\n### 2. 情报信息\n源 IP 暂无高置信恶意标签。\n\n### 3. 测绘信息\n目标为公网电商 Web 服务。\n\n### 4. 告警关联漏洞情报\n当前日志未提供可确认具体 CVE 的证据。\n\n### 5. 攻击负载分析\n请求参数中包含 union select,存在明显 SQL 注入意图。\n\n### 6. 攻击分析结果\n响应码为 403,响应体显示请求被阻断,不支持攻击成功。\n\n\n\n## 研判结论\n该请求存在 SQL 注入攻击意图,但响应显示被拒绝,当前判断为攻击失败。\n\n\n\n## 攻击payload\n\n```http\nGET /item?id=1 union select user HTTP/1.1\nHost: shop.example.com\n```\n\n\n\n## 具体含义解释\n\n1. union select 是典型 SQL 注入关键字组合。\n2. 攻击者尝试拼接查询以读取数据库用户信息。\n3. 该 payload 证明攻击意图,但不等同于成功执行。\n\n\n\n## 响应证据\n\n```http\nHTTP/1.1 403 Forbidden\n\nblocked by waf\n```\n\n响应状态和内容说明请求被拦截,未见数据泄露或执行成功证据。\n\n\n\n## 重要证据\n\n1. 请求参数包含 union select。\n2. 响应码为 403。\n3. 响应体显示 blocked by waf。\n\n\n\n## 处置建议\n\n1. 保留 WAF 拦截证据。\n2. 检查同源 IP 是否持续尝试其他注入 payload。\n3. 确认目标接口参数化查询和安全策略仍然有效。\n\n\n\n\n## 待研判上下文\n```json\n{context}\n```\n\n请输出最终报告:\n'''\n return _extract_tagged_triage_report(_ask_llm(prompt))\n\n\ndef _generate_triage_report(parsed, intel_results, vuln_info, branches,\n attack_analysis_result, attack_verdict,\n attack_success, report_title):\n # Aggregate everything into tagged markdown for frontend rendering.\n # The markdown is returned through `triage_report` and is not written as a\n # per-alert file; leader/follower/cache-hit paths reuse the same field.\n outcome = _triage_outcome_key(attack_verdict, attack_success)\n verdict_cn = OUTCOME_CN.get(outcome, '未知')\n risk_level = OUTCOME_RISK.get(outcome, 'Medium')\n\n if not report_title:\n report_title = f'{parsed.get(\"alert_type\", \"Web日志告警\")} - {verdict_cn}'\n\n try:\n triage_report = _llm_triage_report_markdown(\n parsed, intel_results, vuln_info, branches,\n attack_analysis_result, attack_verdict, attack_success,\n report_title, risk_level,\n )\n except Exception as e:\n print(f'[triage] WARNING: triage_report LLM generation failed: {e}')\n triage_report = ''\n\n if not _is_valid_triage_report(triage_report):\n print('[triage] WARNING: triage_report missing required semantic tags; using deterministic fallback')\n triage_report = _build_default_tagged_triage_report(\n parsed, intel_results, vuln_info, branches,\n attack_analysis_result, attack_verdict, attack_success,\n report_title, risk_level,\n )\n\n return triage_report, report_title, risk_level\n\n\ndef _triage_single_alert(alert):\n \"\"\"End-to-end inline triage for a single alert. Returns triage_fields dict.\n\n No file I/O — the full markdown report lives in the returned `triage_report` field\n and is broadcast to followers / persisted via `triage_cache.pkl`.\n \"\"\"\n parsed = _parse_alert(alert)\n intel_results, intel_content, vuln_info, vuln_content = _prepare_intel(parsed)\n\n branches = _parallel_4_branches(parsed, intel_content, vuln_content)\n\n attack_analysis_result = _llm_attack_analysis(parsed['log_text'])\n outcome = _llm_attack_outcome(attack_analysis_result)\n attack_verdict = outcome['triage_attack_verdict']\n attack_success = outcome['triage_attack_success']\n report_title = _llm_report_title(\n parsed.get('alert_type', 'unknown'),\n attack_verdict,\n attack_success,\n attack_analysis_result,\n )\n\n triage_report, report_title, risk_level = _generate_triage_report(\n parsed, intel_results, vuln_info, branches,\n attack_analysis_result, attack_verdict, attack_success, report_title,\n )\n\n return {\n 'triage_attack_verdict': attack_verdict,\n 'triage_attack_success': attack_success,\n 'risk_level': risk_level,\n 'report_title': report_title,\n 'triage_report': triage_report,\n }\n\n\n# ── Main: leader/follower batch deduplication ────────────────────────────────\n# When the input batch contains multiple alerts sharing the same dedup_key\n# (e.g. upstream emits is_duplicate=True alerts in the same batch, or LSH\n# clustering produces several alerts per cluster), we only triage the LEADER\n# (first occurrence of each dedup_key). All FOLLOWERS in the same group reuse\n# the leader's triage result without invoking the LLM again.\n#\n# Work unit types:\n# ('dk', dedup_key, leader_idx) — group of 1+ alerts sharing dedup_key\n# ('nokey', None, alert_idx) — single alert with no dedup_key\n# (cannot be deduplicated, always triaged)\n\ndef _bump_verdict(verdict):\n with results_lock:\n stats['verdict_counts'][verdict] = stats['verdict_counts'].get(verdict, 0) + 1\n\n\n_UNKNOWN_TRIAGE = {\n 'triage_attack_verdict': 'unknown',\n 'triage_attack_success': 'unknown',\n 'risk_level': 'Medium',\n 'report_title': '',\n 'triage_report': '',\n}\n\n\ndef _apply_triage_fields(record, triage_fields):\n verdict = triage_fields.get('triage_attack_verdict', 'unknown')\n result = triage_fields.get('triage_attack_success', 'unknown')\n if verdict not in {'attack', 'non_attack', 'unknown'}:\n verdict = 'unknown'\n if result not in {'success', 'failed', 'unknown'} or verdict != 'attack':\n result = 'unknown'\n record['triage_attack_verdict'] = verdict\n record['triage_attack_success'] = result\n for key in ('risk_level', 'report_title', 'triage_report'):\n if key in triage_fields:\n record[key] = triage_fields[key]\n\n\ndef _process_unit(unit_type, dedup_key, leader_idx):\n \"\"\"Triage one unique work unit. Returns (key, triage_fields, source, ms, error).\"\"\"\n leader_alert = enriched_alerts[leader_idx]\n t0 = time.time()\n\n # 1) cache lookup for dedup_key units\n if unit_type == 'dk':\n cached = triage_cache_snapshot.get(dedup_key)\n if cached:\n if _is_current_triage_fields(cached):\n with results_lock:\n stats['cache_hit'] += 1\n _bump_verdict(_triage_outcome_key(\n cached.get('triage_attack_verdict'),\n cached.get('triage_attack_success'),\n ))\n return dedup_key, cached, 'cache', 0, None\n print(f'[triage_cache] stale entry for dedup_key={dedup_key}: '\n 'missing current two-field triage schema/report; treating as cache miss')\n\n # 2) cache miss or no-key → run full inline triage on the leader\n try:\n triage_fields = _triage_single_alert(leader_alert)\n ms = round((time.time() - t0) * 1000)\n with results_lock:\n stats['triaged'] += 1\n if dedup_key:\n new_results[dedup_key] = triage_fields\n _bump_verdict(_triage_outcome_key(\n triage_fields.get('triage_attack_verdict'),\n triage_fields.get('triage_attack_success'),\n ))\n source = 'triaged' if unit_type == 'dk' else 'no_dedup_key_triaged'\n return (dedup_key if unit_type == 'dk' else leader_idx), triage_fields, source, ms, None\n except Exception as e:\n import traceback\n ms = round((time.time() - t0) * 1000)\n with results_lock:\n stats['triage_failed'] += 1\n _bump_verdict('unknown')\n err = str(e)[:500]\n print(f'[triage] leader_idx={leader_idx} FAILED: {e}\\n{traceback.format_exc()}')\n source = 'failed' if unit_type == 'dk' else 'no_dedup_key_failed'\n return (dedup_key if unit_type == 'dk' else leader_idx), dict(_UNKNOWN_TRIAGE), source, ms, err\n\n\n\n_batch_lease_fd = inputs.get('_batch_lease_fd')\nif type(_batch_lease_fd) is not int or _batch_lease_fd < 0:\n _batch_lease_fd = None\n_batch_lease_token = str(inputs.get('batch_lease_token') or '')\nif bool(inputs.get('cursor_enabled')) and _batch_lease_fd is None:\n _batch_lease_fd, _batch_lease_token = _acquire_batch_lease()\ntry:\n enriched_alerts = list(inputs.get('enriched_alerts', []) or [])\n concurrency = min(5, max(1, int(inputs.get('concurrency', 1))))\n _llm_slots = threading.BoundedSemaphore(concurrency)\n max_triage_cache_size = int(inputs.get('max_triage_cache_size', 100000))\n if max_triage_cache_size < 1:\n max_triage_cache_size = 100000\n\n # Group by dedup_key\n groups = {} # dedup_key -> [alert_index, ...]\n no_key_indices = [] # alerts with no dedup_key\n for i, a in enumerate(enriched_alerts):\n dk = a.get('dedup_key', '') if isinstance(a, dict) else ''\n if dk:\n groups.setdefault(dk, []).append(i)\n else:\n no_key_indices.append(i)\n\n work_units = (\n [('dk', dk, group_indices[0]) for dk, group_indices in groups.items()]\n + [('nokey', None, idx) for idx in no_key_indices]\n )\n follower_count = sum(len(v) - 1 for v in groups.values())\n\n print(f'[triage] alerts={len(enriched_alerts)} '\n f'→ {len(groups)} unique dedup_keys ({follower_count} followers) + '\n f'{len(no_key_indices)} no-key alerts '\n f'= {len(work_units)} work units; outer_concurrency={concurrency} '\n f'llm_concurrency_limit={concurrency} '\n f'sub_batch_size={TRIAGE_SUB_BATCH_SIZE} '\n f'(all LLM calls share the run-wide budget)')\n\n cache_path, lock_path = _cache_paths()\n cache_batch_lock = _acquire_lock(lock_path)\n try:\n triage_cache_snapshot = _load_cache(cache_path)\n\n # Only warm up the LLM when at least one work unit may actually need it.\n # A unit \"may need\" the LLM if it's a no-key alert OR a dedup_key unit whose\n # entry is not in the cache snapshot. Pure cache-hit batches skip warm-up.\n _needs_llm = any(\n unit_type == 'nokey' or not _is_current_triage_fields(triage_cache_snapshot.get(dk))\n for unit_type, dk, _ in work_units\n )\n if _needs_llm:\n _warmup_llm()\n\n results_lock = threading.Lock()\n new_results = {} # dedup_key -> triage_fields (only for freshly computed leaders)\n group_outcomes = {} # dedup_key -> (triage_fields, source) for broadcasting to followers\n nokey_outcomes = {} # alert_idx -> (triage_fields, source)\n stats = {\n 'total': len(enriched_alerts),\n 'unique_dedup_keys': len(groups),\n 'followers_reused': follower_count,\n 'no_dedup_key_alerts': len(no_key_indices),\n 'work_units': len(work_units),\n 'llm_concurrency_limit': concurrency,\n 'cache_hit': 0,\n 'triaged': 0,\n 'triage_failed': 0,\n 'verdict_counts': {},\n 'cache_size_before': len(triage_cache_snapshot),\n 'cache_size_after': 0,\n 'evicted': 0,\n }\n\n\n t_start = time.time()\n unit_completions = {} # key -> (triage_fields, source, ms, error)\n if work_units:\n completed_count = 0\n for batch_start in range(0, len(work_units), TRIAGE_SUB_BATCH_SIZE):\n work_batch = work_units[batch_start:batch_start + TRIAGE_SUB_BATCH_SIZE]\n worker_count = min(concurrency, len(work_batch))\n with ThreadPoolExecutor(\n max_workers=worker_count,\n thread_name_prefix='stream_triage',\n ) as pool:\n futures = [pool.submit(_process_unit, *u) for u in work_batch]\n for fut in as_completed(futures):\n completed_count += 1\n try:\n key, triage_fields, source, ms, err = fut.result()\n unit_completions[key] = (triage_fields, source, ms, err)\n if source == 'cache':\n group_outcomes[key] = (triage_fields, source)\n elif source.startswith('no_dedup_key'):\n nokey_outcomes[key] = (triage_fields, source)\n else:\n group_outcomes[key] = (triage_fields, source)\n except Exception as e:\n print(f'[triage] WARNING: unexpected worker exception: {e}')\n if completed_count % 5 == 0 or completed_count == len(work_units):\n print(f'[triage] progress {completed_count}/{len(work_units)} '\n f'(cache_hit={stats[\"cache_hit\"]} triaged={stats[\"triaged\"]} '\n f'failed={stats[\"triage_failed\"]})')\n del futures\n\n # ── Apply outcomes back to every alert (broadcast leader → followers) ─────────\n enriched_with_triage = [None] * len(enriched_alerts)\n for i, alert in enumerate(enriched_alerts):\n out = dict(alert) if isinstance(alert, dict) else {'_raw': alert}\n dk = alert.get('dedup_key', '') if isinstance(alert, dict) else ''\n out['has_dedup_key'] = bool(dk)\n\n if dk:\n triage_fields, source = group_outcomes.get(dk, (dict(_UNKNOWN_TRIAGE), 'failed'))\n is_leader = (groups.get(dk, [i])[0] == i)\n # All triage fields are pure data (no file-path references); broadcast as-is.\n _apply_triage_fields(out, triage_fields)\n if not is_leader and source != 'cache':\n out['triage_source'] = 'follower_reused'\n out['triage_status'] = 'reused_from_leader'\n else:\n out['triage_source'] = source\n out['triage_status'] = 'cached' if source == 'cache' else (\n 'ok' if source == 'triaged' else 'failed'\n )\n completion = unit_completions.get(dk)\n if completion and is_leader:\n _, _, ms, err = completion\n if ms:\n out['triage_ms'] = ms\n if err:\n out['triage_error'] = err\n else:\n # no-key alerts: each is its own unit, keyed by alert idx\n triage_fields, source = nokey_outcomes.get(i, (dict(_UNKNOWN_TRIAGE), 'no_dedup_key_failed'))\n _apply_triage_fields(out, triage_fields)\n out['triage_source'] = source\n out['triage_status'] = 'ok' if source == 'no_dedup_key_triaged' else 'failed'\n completion = unit_completions.get(i)\n if completion:\n _, _, ms, err = completion\n if ms:\n out['triage_ms'] = ms\n if err:\n out['triage_error'] = err\n\n enriched_with_triage[i] = out\n\n elapsed_ms = round((time.time() - t_start) * 1000)\n print(f'[triage] all done in {elapsed_ms}ms: cache_hit={stats[\"cache_hit\"]} '\n f'triaged={stats[\"triaged\"]} failed={stats[\"triage_failed\"]} '\n f'followers_reused={stats[\"followers_reused\"]} '\n f'no_dedup_key={stats[\"no_dedup_key_alerts\"]}')\n\n # The batch lock has remained held since the initial load, so reuse\n # that snapshot instead of temporarily retaining a second full cache.\n cache = triage_cache_snapshot\n for k, v in new_results.items():\n if k in cache:\n del cache[k] # LRU touch (move to end on rewrite)\n cache[k] = v\n evicted = _evict_lru(\n cache,\n max_triage_cache_size,\n MAX_TRIAGE_CACHE_BYTES if new_results else None,\n )\n if evicted:\n print(f'[triage_cache] LRU eviction: dropped {evicted} entries '\n f'(max_keys={max_triage_cache_size}, max_bytes={MAX_TRIAGE_CACHE_BYTES})')\n if new_results or evicted:\n _save_cache_atomic(cache_path, cache)\n stats['cache_size_after'] = len(cache)\n stats['evicted'] = evicted\n finally:\n _release_lock(cache_batch_lock)\n\n triage_results = []\n top_triage_result = {}\n top_outcome_rank = -1\n outcome_order = {\n 'attack_success': 5,\n 'attack': 4,\n 'attack_failed': 3,\n 'unknown': 2,\n 'non_attack': 1,\n }\n for a in enriched_with_triage:\n item = {\n 'dedup_key': a.get('dedup_key', ''),\n 'has_dedup_key': a.get('has_dedup_key', False),\n 'threat_name': a.get('threat_name', ''),\n 'sip': a.get('sip', ''),\n 'dip': a.get('dip', ''),\n 'is_duplicate': a.get('is_duplicate'),\n 'triage_source': a.get('triage_source', ''),\n 'triage_status': a.get('triage_status', ''),\n 'triage_attack_verdict': a.get('triage_attack_verdict', ''),\n 'triage_attack_success': a.get('triage_attack_success', 'unknown'),\n 'risk_level': a.get('risk_level', ''),\n 'report_title': a.get('report_title', ''),\n 'triage_ms': a.get('triage_ms'),\n 'triage_error': a.get('triage_error'),\n }\n triage_results.append(item)\n outcome = _triage_outcome_key(\n item['triage_attack_verdict'],\n item['triage_attack_success'],\n )\n rank = outcome_order.get(outcome, 0)\n if rank > top_outcome_rank:\n top_outcome_rank = rank\n top_triage_result = dict(item)\n # Keep the selected report intact; only the number of reports\n # crossing the process boundary is reduced.\n top_triage_result['triage_report'] = a.get('triage_report', '')\n\n stats['elapsed_ms'] = elapsed_ms\n stats['concurrency'] = concurrency\n stats['triage_sub_batch_size'] = TRIAGE_SUB_BATCH_SIZE\n stats['max_triage_cache_size'] = max_triage_cache_size\n stats['max_triage_cache_bytes'] = MAX_TRIAGE_CACHE_BYTES\n\n # Persist enriched_with_triage according to workflow config. Default is SOC DB;\n # JSONL is still available by config/input for downstream pipelines or archival.\n output_cfg = _resolve_output_config()\n run_id = (inputs.get('_run_id')\n or os.environ.get('FLOCKS_RUN_ID')\n or str(int(time.time() * 1000)))\n output_paths = []\n output_dir = ''\n first_seen_soc_alerts, soc_db_filter_stats = _select_first_seen_soc_alerts(\n enriched_with_triage,\n )\n soc_db_result = {\n 'path': output_cfg.get('soc_db_path', ''),\n 'table': '',\n 'rows': 0,\n 'inserted_rows': 0,\n 'updated_rows': 0,\n 'unchanged_rows': 0,\n }\n\n if output_cfg['write_soc_db'] and first_seen_soc_alerts:\n try:\n soc_db_result.update(_triage_write_soc_db(\n first_seen_soc_alerts, run_id,\n ))\n print(f'[triage] persisted {soc_db_result.get(\"rows\", 0)} globally unique alerts to '\n f'SOC DB {soc_db_result.get(\"path\")} '\n f'(inserted={soc_db_result.get(\"inserted_rows\", 0)}, '\n f'updated={soc_db_result.get(\"updated_rows\", 0)}); '\n f'filter={soc_db_filter_stats}')\n except Exception as e:\n import traceback\n print(f'[triage] ERROR: failed to persist triage results to SOC DB: {e}\\n{traceback.format_exc()}')\n raise\n elif output_cfg['write_soc_db']:\n print(f'[triage] no verified first-seen unique alerts to persist; filter={soc_db_filter_stats}')\n else:\n print(f'[triage] SOC DB output disabled by triage_output_mode={output_cfg[\"requested_mode\"]!r}')\n\n if output_cfg['write_jsonl'] and enriched_with_triage:\n try:\n output_dir = _triage_output_dir(output_cfg.get('jsonl_output_dir', ''))\n output_paths = _triage_write_jsonl(\n output_dir, enriched_with_triage, run_id, stats,\n )\n print(f'[triage] wrote {len(enriched_with_triage)} enriched alerts to '\n f'{len(output_paths)} JSONL file(s) under {output_dir}')\n for p in output_paths:\n print(f' → {p}')\n except Exception as e:\n import traceback\n print(f'[triage] ERROR: failed to persist triage_result JSONL: {e}\\n{traceback.format_exc()}')\n raise\n elif not output_cfg['write_jsonl']:\n print(f'[triage] JSONL output disabled by triage_output_mode={output_cfg[\"requested_mode\"]!r}')\n\n stats['output_mode'] = output_cfg['mode']\n stats['requested_output_mode'] = output_cfg['requested_mode']\n stats['output_config_path'] = output_cfg['config_path']\n stats['soc_db_path'] = soc_db_result.get('path', '')\n stats['soc_db_rows'] = soc_db_result.get('rows', 0)\n stats['soc_db_inserted_rows'] = soc_db_result.get('inserted_rows', 0)\n stats['soc_db_updated_rows'] = soc_db_result.get('updated_rows', 0)\n stats['soc_db_unchanged_rows'] = soc_db_result.get('unchanged_rows', 0)\n stats['soc_db_first_seen_rows'] = soc_db_filter_stats['first_seen_rows']\n stats['soc_db_skipped_rows'] = (\n soc_db_filter_stats['input_rows'] - soc_db_filter_stats['first_seen_rows']\n )\n stats['soc_db_filter_stats'] = soc_db_filter_stats\n stats['output_paths'] = output_paths\n stats['output_dir'] = output_dir\n\n print(f'[triage] stats={json.dumps(stats, ensure_ascii=False)}')\n\n outputs['top_triage_result'] = top_triage_result\n outputs['triage_results'] = triage_results\n outputs['triage_stats'] = stats\n outputs['load_stats'] = inputs.get('load_stats', {})\n outputs['loaded_files'] = inputs.get('loaded_files', [])\n outputs['input_date'] = inputs.get('input_date', '')\n outputs['cursor_enabled'] = bool(inputs.get('cursor_enabled'))\n outputs['cursor_before'] = inputs.get('cursor_before')\n outputs['cursor_revision'] = inputs.get('cursor_revision')\n outputs['cursor_invalidated'] = bool(inputs.get('cursor_invalidated'))\n outputs['pending_cursor'] = inputs.get('pending_cursor')\n outputs['next_cursor'] = inputs.get('next_cursor')\n outputs['has_more'] = bool(inputs.get('has_more'))\n outputs['batch_records'] = int(inputs.get('batch_records', 0) or 0)\n outputs['batch_bytes'] = int(inputs.get('batch_bytes', 0) or 0)\n outputs['triage_output_mode'] = output_cfg['mode']\n outputs['soc_db_result'] = soc_db_result\n outputs['soc_db_path'] = soc_db_result.get('path', '')\n outputs['output_config_path'] = output_cfg['config_path']\n outputs['output_paths'] = output_paths\n outputs['output_dir'] = output_dir\n outputs['_batch_lease_fd'] = _batch_lease_fd\n outputs['batch_lease_token'] = _batch_lease_token\n outputs['_triage_persistence_succeeded'] = True\nexcept BaseException:\n _release_batch_lease(_batch_lease_fd)\n raise\n", "processIsolated": true, "processRetainFdKeys": [ "_batch_lease_fd" @@ -136,7 +136,7 @@ "_comment_dedup": "同批次内多条 alert 共享 dedup_key 时只 LLM 研判 1 次(leader),其余 follower 直接复用结果;跨批次/跨进程的复用由 triage_cache.pkl 提供。", "_comment_cache": "研判缓存位于 ~/.flocks/workspace/workflows/stream_alert_triage/triage_cache.pkl,FIFO LRU,同时受 max_triage_cache_size 和 128 MiB 字节上限约束;文件锁 + 原子落盘,可跨进程/跨执行复用。dedup_key 即 stream_alert_denoise 生成的 MD5(strict_fields + lsh_cluster_id)。", "triage_output_mode": "soc_db", - "_comment_output": "默认只接受明确 is_duplicate=false、包含 dedup_key 且批内首次出现的告警,并由 soc.db 保证 dedup_key 跨执行全局唯一;如需 JSONL,设置 triage_output_mode=jsonl 或 both。", + "_comment_output": "默认只接受明确 is_duplicate=false、包含 dedup_key 且批内首次出现的告警,并由平台的告警库保证 dedup_key 跨执行全局唯一;如需 JSONL,设置 triage_output_mode=jsonl 或 both。", "batch_max_records": 10, "batch_max_bytes": 33554432 }, @@ -164,7 +164,7 @@ "_comment_dedup": "同批次内多条 alert 共享 dedup_key 时只 LLM 研判 1 次(leader),其余 follower 直接复用结果;跨批次/跨进程的复用由 triage_cache.pkl 提供。", "_comment_cache": "研判缓存位于 ~/.flocks/workspace/workflows/stream_alert_triage/triage_cache.pkl,FIFO LRU,同时受 max_triage_cache_size 和 128 MiB 字节上限约束;文件锁 + 原子落盘,可跨进程/跨执行复用。dedup_key 即 stream_alert_denoise 生成的 MD5(strict_fields + lsh_cluster_id)。", "triage_output_mode": "soc_db", - "_comment_output": "默认只接受明确 is_duplicate=false、包含 dedup_key 且批内首次出现的告警,并由 soc.db 保证 dedup_key 跨执行全局唯一;如需 JSONL,设置 triage_output_mode=jsonl 或 both。", + "_comment_output": "默认只接受明确 is_duplicate=false、包含 dedup_key 且批内首次出现的告警,并由平台的告警库保证 dedup_key 跨执行全局唯一;如需 JSONL,设置 triage_output_mode=jsonl 或 both。", "batch_max_records": 10, "batch_max_bytes": 33554432 }, @@ -188,7 +188,7 @@ "_comment_dedup": "同批次内多条 alert 共享 dedup_key 时只 LLM 研判 1 次(leader),其余 follower 直接复用结果;跨批次/跨进程的复用由 triage_cache.pkl 提供。", "_comment_cache": "研判缓存位于 ~/.flocks/workspace/workflows/stream_alert_triage/triage_cache.pkl,FIFO LRU,同时受 max_triage_cache_size 和 128 MiB 字节上限约束;文件锁 + 原子落盘,可跨进程/跨执行复用。dedup_key 即 stream_alert_denoise 生成的 MD5(strict_fields + lsh_cluster_id)。", "triage_output_mode": "soc_db", - "_comment_output": "默认只接受明确 is_duplicate=false、包含 dedup_key 且批内首次出现的告警,并由 soc.db 保证 dedup_key 跨执行全局唯一;如需 JSONL,设置 triage_output_mode=jsonl 或 both。", + "_comment_output": "默认只接受明确 is_duplicate=false、包含 dedup_key 且批内首次出现的告警,并由平台的告警库保证 dedup_key 跨执行全局唯一;如需 JSONL,设置 triage_output_mode=jsonl 或 both。", "batch_max_records": 10, "batch_max_bytes": 33554432 }, diff --git a/.flocks/flockshub/plugins/workflows/stream_alert_triage/workflow.md b/.flocks/flockshub/plugins/workflows/stream_alert_triage/workflow.md index 0a228636e..6e7d9ebc7 100644 --- a/.flocks/flockshub/plugins/workflows/stream_alert_triage/workflow.md +++ b/.flocks/flockshub/plugins/workflows/stream_alert_triage/workflow.md @@ -97,7 +97,9 @@ load_dedup_file -> concurrent_triage -> commit_cursor -> summarize - 同批相同 `dedup_key` 只研判 leader,followers 复用结果。 - 跨批命中 `triage_cache.pkl` 时直接复用,不调用 LLM;缓存锁覆盖 cache miss、LLM 研判和保存阶段,避免并发执行重复研判相同批次。 - 缓存使用 run 级唯一临时文件原子保存;保存失败会抛出异常并阻止生产游标提交。 +- 情报查询调用微步 MCP 的 `threatbook_mcp_ip_query`、`threatbook_mcp_domain_query`、`threatbook_mcp_vuln_query`;MCP 服务名是 `threatbook` 的旧配置自动改用 `threatbook_*` 这一组。IP、域名或漏洞情报工具没有注册时,每次执行打印一行 `[triage] WARNING`,研判照常进行。 - 默认 `triage_output_mode=soc_db`;也支持 `jsonl`、`both` 和 `none`。 +- SOC DB 是平台的告警库:工作流通过平台提供的 `soc` 服务写入,SQLite 还是 PostgreSQL 由 Flocks 的数据库设置决定,工作流和配置文件里都不写库地址。 - SOC DB 只接收明确 `is_duplicate=false`、有非空 `dedup_key` 且批内首次出现的告警。 - 研判正文只保存在 `triage_report` 字段,不生成逐告警 markdown 文件。 diff --git a/README.md b/README.md index 90b44329d..e96bb062c 100644 --- a/README.md +++ b/README.md @@ -125,8 +125,8 @@ flocks stop ``` The default service address is: -- Flocks WebUI: `http://127.0.0.1:5173` -- Remote access configurable via `flocks start --host ` +- Flocks WebUI: `http://127.0.0.1:5173` on this machine; the service listens on all interfaces (`0.0.0.0:5173`), so other machines open `http://:5173` +- Keep it on this machine with `flocks start --host 127.0.0.1` (or `FLOCKS_HOST=127.0.0.1`) Flocks CLI usage: `flocks --help` @@ -212,11 +212,19 @@ sudo chown -R : ~/.flocks ``` ### 4.3 Remote Access to Flocks Service +`flocks start` listens on all interfaces (`0.0.0.0`) by default, so other machines open +`http://:5173` (allow the port in the firewall if one is on). To listen +on one address only: ```bash -flocks start --host 0.0.0.0 +flocks start --host 127.0.0.1 # this machine only ``` If remote access from a virtual machine fails, please specify the host as the virtual machine's IP. +The first administrator can only be created from this machine: open +`http://127.0.0.1:5173` in a browser here, or run `flocks admin generate-one-time-password` +here and sign in from anywhere as `admin` with the password it prints (you are asked to +change it at first sign-in). + The WebUI and API share the same service address and port. API requests use the same-origin `/api` path, keeping browser cookies and SSE on a single origin for LAN access and reverse-proxy deployments. @@ -236,8 +244,10 @@ webhooks (`/api/channel/{channel_id}/webhook`) are public. Initial setup: -1. Open the WebUI and complete the **bootstrap-admin** flow to create the - single `admin` account. +1. Open the WebUI on the machine running Flocks and complete the + **bootstrap-admin** flow to create the single `admin` account. From another + machine, run `flocks admin generate-one-time-password` on the server instead and + sign in as `admin` with the printed password. 2. The browser session cookie (`flocks_session`) is enough for the WebUI; no extra steps are required. diff --git a/README_zh.md b/README_zh.md index f2ad396d8..aaea2ae36 100644 --- a/README_zh.md +++ b/README_zh.md @@ -124,8 +124,8 @@ flocks stop ``` 默认服务地址: -- Flocks WebUI:`http://127.0.0.1:5173` -- 远程访问可通过 `flocks start --host ` 配置 +- Flocks WebUI:本机 `http://127.0.0.1:5173`;服务默认监听所有网卡(`0.0.0.0:5173`),别的机器用 `http://<本机 IP>:5173` 打开 +- 只想本机访问:`flocks start --host 127.0.0.1`(或设 `FLOCKS_HOST=127.0.0.1`) 更多 CLI 命令使用 `flocks --help` @@ -209,11 +209,14 @@ sudo chown -R : ~/.flocks ``` ### 4.3 远程访问 Flocks 服务 +`flocks start` 默认监听所有网卡(`0.0.0.0`),别的机器直接用 `http://<本机 IP>:5173` 打开(开了防火墙的要放行这个端口)。只想听某一个地址: ```bash -flocks start --host 0.0.0.0 +flocks start --host 127.0.0.1 # 只允许本机访问 ``` 若从虚拟机远程访问失败,请将 host 指定为虚拟机的 IP。 +第一个管理员只能在这台机器上创建:在这台机器的浏览器里打开 `http://127.0.0.1:5173`,或者在这台机器上执行 `flocks admin generate-one-time-password`,再从任意机器用 `admin` 和输出的一次性密码登录(首次登录会要求改密码)。 + WebUI 与 API 共用同一个服务地址和端口,API 请求使用同源 `/api` 路径。这样浏览器 Cookie 与 SSE 保持在同一源,适用于局域网访问与反向代理场景。 仅在确实需要浏览器直连后端 URL 时,再显式启用: @@ -229,7 +232,7 @@ flocks start --server-host 0.0.0.0 --webui-host 0.0.0.0 初次部署: -1. 打开 WebUI,按提示完成 **bootstrap-admin**,创建唯一的 `admin` 账号。 +1. 在运行 Flocks 的这台机器上打开 WebUI,按提示完成 **bootstrap-admin**,创建唯一的 `admin` 账号;从别的机器访问时,先在服务器上执行 `flocks admin generate-one-time-password`,再用 `admin` 和输出的密码登录。 2. WebUI 会自动写入 `flocks_session` Cookie,浏览器侧无需额外配置。 非浏览器客户端(TUI / SDK / 脚本): diff --git a/flocks/__init__.py b/flocks/__init__.py index a6f26270f..55169daf3 100644 --- a/flocks/__init__.py +++ b/flocks/__init__.py @@ -9,9 +9,13 @@ # runtime modules, which has to be in place before the first of them is # imported (flocks/db_backend.py). from flocks import startup_env as _startup_env +from flocks import ca_certs as _ca_certs from flocks import db_backend as _db_backend _startup_env.load() +# Root certificates where OpenSSL's defaults find none (RHEL 8 and its kin, +# flocks/ca_certs.py); after the .env, which may name its own. +_ca_certs.ensure() _db_backend.install() from importlib.metadata import version, PackageNotFoundError diff --git a/flocks/agent/registry.py b/flocks/agent/registry.py index ecc786f50..532b075fc 100644 --- a/flocks/agent/registry.py +++ b/flocks/agent/registry.py @@ -23,7 +23,7 @@ import threading from collections import OrderedDict from pathlib import Path -from typing import Any, Dict, List, Optional, Set +from typing import Any, Dict, Iterable, List, Optional, Set from flocks.utils.log import Log from flocks.config.config import Config, ConfigInfo @@ -233,6 +233,29 @@ def _apply_enabled_agents( del agents[name] +def _delegation_candidates( + agents: Dict[str, AgentInfo], + registered: Dict[str, AgentInfo], + managed_names: Iterable[str], + enabled_agents: Optional[List[str]], +) -> Dict[str, AgentInfo]: + """The agents an orchestrator's prompt may offer for delegation. + + The loaded agents and the runtime-registered ones (Agent.register), merged + the way the registry merges them: not over a managed name, and within the + configured allowlist. ``delegate_task`` accepts a registered delegatable + agent, so the prompt that tells the orchestrator whom to delegate to has to + name it as well. + """ + reserved = set(managed_names) + candidates = dict(agents) + for name, info in registered.items(): + if name not in reserved: + candidates[name] = info + _apply_enabled_agents(candidates, enabled_agents) + return candidates + + # --------------------------------------------------------------------------- # Agent registry # --------------------------------------------------------------------------- @@ -477,7 +500,11 @@ def _permission_dict_to_tools(permission_cfg: Dict[str, Any]) -> List[str]: _apply_enabled_agents(result, cfg.enabled_agents) # ── ④ Phase-2 dynamic prompts ────────────────────────────────────── - available_agents = _build_available_agents(result) + # Runtime-registered agents are merged below, after the prompts are + # built; as delegation candidates they are counted already. + available_agents = _build_available_agents( + _delegation_candidates(result, Agent._custom_agents, managed_names, cfg.enabled_agents) + ) inject_dynamic_prompts( result, available_agents, diff --git a/flocks/auth/service.py b/flocks/auth/service.py index 07b089aa7..ae42ddd77 100644 --- a/flocks/auth/service.py +++ b/flocks/auth/service.py @@ -592,13 +592,31 @@ async def generate_admin_temp_password( username: str = "admin", ) -> str: user_info = await cls.get_user_by_username(username) + temp_password = secrets.token_urlsafe(12) + expires = (_utc_now() + timedelta(hours=cls._temp_password_ttl_hours)).isoformat() if not user_info: - raise ValueError("管理员账号不存在") + if await cls.has_users(): + raise ValueError("管理员账号不存在") + # No account at all yet: the first administrator, for a machine + # nobody opens the page on (the setup page only creates it for a + # browser on this machine, see routes/auth.bootstrap_admin). + user = await cls._create_user_internal( + username=username, + password=temp_password, + role="admin", + must_reset_password=True, + temp_expires_at=expires, + only_if_no_users=True, + ) + try: + await cls.migrate_legacy_sessions_to_admin(user.id) + except Exception as exc: + # The account stands; the server's startup migration retries. + log.warn("auth.temp_admin.migrate_legacy_sessions_failed", {"error": str(exc)}) + return temp_password user, _, _ = user_info if user.role != "admin": raise ValueError("目标账号不是管理员") - temp_password = secrets.token_urlsafe(12) - expires = (_utc_now() + timedelta(hours=cls._temp_password_ttl_hours)).isoformat() await cls.set_password( target_user_id=user.id, new_password=temp_password, diff --git a/flocks/ca_certs.py b/flocks/ca_certs.py new file mode 100644 index 000000000..ca39e9c42 --- /dev/null +++ b/flocks/ca_certs.py @@ -0,0 +1,123 @@ +""" +Root certificates for a Python whose OpenSSL looks for them elsewhere. + +The Linux packages ship a python-build-standalone interpreter, whose OpenSSL +looks for the system's root certificates in ``/etc/ssl/cert.pem`` and in the +hashed ``/etc/ssl/certs`` directory. RHEL 8 and the distributions built from +it (CentOS, Rocky and AlmaLinux 8, Anolis 8, Alibaba Cloud Linux 3) have +neither: their bundle is under ``/etc/pki``, and ``/etc/ssl/certs`` links to a +directory that holds it without the hashed names OpenSSL looks up. Every +client that trusts the defaults -- ``ssl.create_default_context()``: the WeCom +SDK's WebSocket, aiohttp, urllib -- then fails with CERTIFICATE_VERIFY_FAILED, +while httpx, which brings certifi's bundle, works. python-build-standalone +releases from 20260320 on fall back to ``/etc/pki/tls/cert.pem`` themselves, +but only in ``load_default_certs`` and only for that file. + +``ensure()``, run when ``flocks`` is imported, points ``SSL_CERT_FILE`` at the +system's bundle -- or at certifi's, when the system has none -- when the +environment names no certificates of its own and OpenSSL's default locations +hold none. OpenSSL reads the variable each time a context loads its default +locations, and the processes this one starts inherit it. httpx reads it too +and then uses that bundle instead of certifi's, which is the same trust the +rest of the machine has. Elsewhere (Debian, Ubuntu, RHEL 9 and later, macOS, +Windows) it changes nothing. +""" + +from __future__ import annotations + +import os +import re +import ssl +import sys +from typing import Iterable, MutableMapping, Optional + +# Where Linux distributions keep their bundle of root certificates, in the order +# truststore and Go's crypto/x509 look: the first one present is the system's. +SYSTEM_BUNDLES: tuple[str, ...] = ( + "/etc/ssl/cert.pem", # Alpine, Arch, Fedora 34+, RHEL 9+ + "/etc/pki/tls/cert.pem", # RHEL 8 and older, Fedora 33 and older + "/etc/pki/tls/certs/ca-bundle.crt", # the same bundle, as RHEL 6 named it + "/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem", # what both point to since RHEL 7 + "/etc/ssl/certs/ca-certificates.crt", # Debian, Ubuntu, Gentoo + "/etc/ssl/ca-bundle.pem", # SUSE +) + +# OpenSSL finds a certificate in a directory by the hash of its subject: +# ``<8 hex digits>.`` (c_rehash, update-ca-certificates). +_HASHED_NAME = re.compile(r"^[0-9a-fA-F]{8}\.\d+$") + +_ENV_NAMES = ("SSL_CERT_FILE", "SSL_CERT_DIR") + + +def _readable_file(path: str) -> bool: + try: + return os.path.isfile(path) and os.path.getsize(path) > 0 and os.access(path, os.R_OK) + except OSError: + return False + + +def _holds_hashed_certs(directory: str) -> bool: + """Whether *directory* has a certificate under a hashed name (a link that resolves to one counts).""" + try: + with os.scandir(directory) as entries: + return any( + _HASHED_NAME.match(entry.name) and _readable_file(entry.path) for entry in entries + ) + except OSError: + return False + + +def defaults_hold_certs() -> bool: + """Whether OpenSSL's default locations hold root certificates it can read. + + A file that is there but empty or unreadable, or a hashed name that is a + dangling link, holds none: OpenSSL would load nothing from it. + """ + paths = ssl.get_default_verify_paths() + if paths.cafile and _readable_file(paths.cafile): # cafile is None unless the file exists + return True + return bool(paths.capath) and _holds_hashed_certs(paths.capath) + + +def _certifi_bundle() -> Optional[str]: + try: + import certifi + except ImportError: + return None + try: + path = certifi.where() + except Exception: + return None + return path if _readable_file(path) else None + + +def find_bundle(candidates: Optional[Iterable[str]] = None) -> Optional[str]: + """The system's bundle of root certificates, else certifi's, else ``None``.""" + for path in SYSTEM_BUNDLES if candidates is None else candidates: + if _readable_file(path): + return path + return _certifi_bundle() + + +def ensure(environ: Optional[MutableMapping[str, str]] = None) -> Optional[str]: + """Point ``SSL_CERT_FILE`` at a bundle when OpenSSL's defaults hold no certificates. + + Returns the bundle it set, or ``None`` when it changed nothing: not Linux, + the environment already names certificates, the defaults hold some, or no + bundle was found. + """ + if not sys.platform.startswith("linux"): + return None + env = os.environ if environ is None else environ + if any(env.get(name) for name in _ENV_NAMES): + return None + if defaults_hold_certs(): + return None + bundle = find_bundle() + if bundle is None: + return None + env["SSL_CERT_FILE"] = bundle + return bundle + + +__all__ = ["SYSTEM_BUNDLES", "defaults_hold_certs", "ensure", "find_bundle"] diff --git a/flocks/channel/builtin/wecom/channel.py b/flocks/channel/builtin/wecom/channel.py index 486950190..37664a9a8 100644 --- a/flocks/channel/builtin/wecom/channel.py +++ b/flocks/channel/builtin/wecom/channel.py @@ -3,7 +3,10 @@ Uses the ``wecom-aibot-sdk`` package to maintain a WebSocket long-connection to ``wss://openws.work.weixin.qq.com``. The SDK handles authentication, -heartbeat keep-alive, and exponential-backoff reconnection internally. +heartbeat keep-alive, and exponential-backoff reconnection internally; what it +does not recover from (refused credentials, the server dropping the connection +for a newer one) ends start() with a readable reason, which the gateway shows +in the channel status and retries with backoff. Reference implementation: https://github.com/WecomTeam/wecom-openclaw-plugin @@ -14,8 +17,10 @@ import asyncio import math import re +import ssl from collections import OrderedDict from typing import Any, Awaitable, Callable, Optional +from urllib.parse import urlsplit from flocks.channel.base import ( ChannelCapabilities, @@ -33,6 +38,117 @@ _FRAME_CACHE_MAX = 500 _DEFAULT_RECONNECT_TIMEOUT_SECONDS = 60.0 _LEADING_MENTION_RE = re.compile(r"^\s*(?:@\S+(?:\s+|$))+") +# Shown in error messages when no websocketUrl is configured; the SDK's own default. +_FALLBACK_WS_URL = "wss://openws.work.weixin.qq.com" +# The SDK reports a refused subscribe frame as a plain Exception starting with +# this text (wecom_aibot_sdk.ws ``_handle_frame``), and raises +# WSAuthFailureError once it gives up retrying. +_AUTH_FAILURE_PREFIX = "Authentication failed" +# Reason the SDK passes to "disconnected" when the server drops this connection +# because the same bot opened another one (its ``disconnected_event``). +_REPLACED_BY_NEW_CONNECTION_PREFIX = "New connection established" + + +def _is_auth_failure(error: BaseException) -> bool: + return type(error).__name__ == "WSAuthFailureError" or str(error).startswith(_AUTH_FAILURE_PREFIX) + + +def _shown_ws_url(url: str) -> str: + """The WebSocket address as status messages show it: scheme, host and port only. + + A custom websocketUrl (or the {env:…}/{secret:…} it came from) may carry a + token in its user info, path or query, and the channel status is readable + by every signed-in user. + """ + try: + parts = urlsplit(url) + host = parts.hostname or "" + port = parts.port + except ValueError: + return "自定义地址" + if not parts.scheme or not host: + return "自定义地址" + if ":" in host: + host = f"[{host}]" + return f"{parts.scheme}://{host}" + (f":{port}" if port else "") + + +# The code the SDK appends to a refused subscribe ("… (code: 40058)"). +_AUTH_ERRCODE_RE = re.compile(r"\(code: (-?\d+)\)\s*$") +_SEE_SERVER_LOG = "详细报错见服务端日志 wecom.ws.error。" + + +def _error_facts(error: BaseException) -> str: + """What the status may say about an SDK error: its type and numeric codes, never its text. + + The text can quote an address (a redirect target, an invalid URI) with the + credentials it carries, or whatever a custom server sent back, and the + channel status is readable by every signed-in user. The full error is + logged on the server (``wecom.ws.error``) only. + """ + facts = [f"错误类型 {type(error).__name__}"] + errno = getattr(error, "errno", None) + if isinstance(errno, int): + facts.append(f"errno {errno}") + # websockets' InvalidStatus carries the response; older InvalidStatusCode the code itself. + status = getattr(getattr(error, "response", None), "status_code", None) + if status is None: + status = getattr(error, "status_code", None) + if isinstance(status, int): + facts.append(f"HTTP {status}") + return ",".join(facts) + + +def _cert_verification_error(error: BaseException) -> Optional[ssl.SSLCertVerificationError]: + """The failed certificate check behind *error* (itself, or what it was raised from), if any.""" + seen: set[int] = set() + current: Optional[BaseException] = error + while current is not None and id(current) not in seen: + if isinstance(current, ssl.SSLCertVerificationError): + return current + seen.add(id(current)) + current = current.__cause__ or current.__context__ + return None + + +def _describe_sdk_error(error: BaseException, ws_url: str) -> str: + """What the channel status shows for an SDK ``error`` event: the cause, then type and codes only.""" + if _is_auth_failure(error): + match = _AUTH_ERRCODE_RE.search(str(error)) + facts = f"企业微信错误码 {match.group(1)}" if match else _error_facts(error) + return ( + "企业微信机器人鉴权失败:请在企业微信管理后台核对智能机器人的 Bot ID 和 Secret," + "Secret 重置过的要在这里重新填写并保存。" + f"{facts},{_SEE_SERVER_LOG}" + ) + cert_error = _cert_verification_error(error) + if cert_error is not None: + # The address answered: the network and the proxy are not what to check. + facts = _error_facts(cert_error) + verify_code = getattr(cert_error, "verify_code", None) + if isinstance(verify_code, int): + facts += f",证书校验错误码 {verify_code}" + return ( + f"连接企业微信长连接服务({_shown_ws_url(ws_url)})时证书校验没通过:" + "这台服务器信任的根证书验证不了对方的证书。请确认系统装了根证书包(ca-certificates);" + "网络里有会替换 HTTPS 证书的代理或安全设备的,要把它的根证书加进系统信任。" + f"{facts},{_SEE_SERVER_LOG}" + ) + return ( + f"连接企业微信长连接服务({_shown_ws_url(ws_url)})出错:请确认服务器能访问这个地址," + "需要走代理的检查代理设置。" + f"{_error_facts(error)},{_SEE_SERVER_LOG}" + ) + + +def _describe_replaced_connection(reason: str) -> Optional[str]: + """The status message when the server dropped this connection for a newer one, else None.""" + if not reason.startswith(_REPLACED_BY_NEW_CONNECTION_PREFIX): + return None + return ( + "企业微信服务端断开了这个连接:同一个机器人在别处建立了新的长连接(一个 Bot ID 同时只能保持一个连接)。" + "请停掉其他正在使用这个机器人的服务(比如升级前的旧版本),再点「重启连接」。" + ) class _WeComSdkLogger: @@ -85,6 +201,13 @@ def __init__(self) -> None: self._reconnect_timeout_seconds = _DEFAULT_RECONNECT_TIMEOUT_SECONDS self._reconnect_timeout_event = asyncio.Event() self._reconnect_watchdog_task: asyncio.Task[None] | None = None + self._ws_url = _FALLBACK_WS_URL + # Set when the SDK will not recover on its own (refused credentials, a + # newer connection took over): start() fails with this message so the + # gateway shows it and retries with backoff. + self._failure_event = asyncio.Event() + self._failure_message = "" + self._last_error_message: Optional[str] = None def meta(self) -> ChannelMeta: return ChannelMeta( @@ -93,10 +216,13 @@ def meta(self) -> ChannelMeta: ) def capabilities(self) -> ChannelCapabilities: + # Connected only once WeCom accepts the bot's credentials + # (_handle_authenticated), not as soon as start() is running. return ChannelCapabilities( chat_types=[ChatType.DIRECT, ChatType.GROUP], media=True, threads=False, reactions=False, edit=False, rich_text=True, + self_managed_connection=True, ) def validate_config(self, config: dict) -> Optional[str]: @@ -130,6 +256,9 @@ async def start(self, config, on_message, abort_event=None): if error: raise ValueError(error) self._reconnect_timeout_event = asyncio.Event() + self._failure_event = asyncio.Event() + self._failure_message = "" + self._last_error_message = None self._cancel_reconnect_watchdog() try: @@ -141,7 +270,8 @@ async def start(self, config, on_message, abort_event=None): ) ws_url = config.get("websocketUrl", "") - self._ws_client = WSClient( + self._ws_url = ws_url or _FALLBACK_WS_URL + client = WSClient( bot_id=config["botId"], secret=config["secret"], **({"ws_url": ws_url} if ws_url else {}), @@ -151,22 +281,25 @@ async def start(self, config, on_message, abort_event=None): plug_version="1.0.0", # 企微服务端用于下发 MCP Server URL 时的版本校验 logger=_WeComSdkLogger(), ) + self._ws_client = client - self._ws_client.on("authenticated", self._handle_authenticated) - self._ws_client.on("disconnected", self._handle_disconnected) - self._ws_client.on("reconnecting", self._handle_reconnecting) - self._ws_client.on("error", self._handle_error) + # Each handler knows which client raised the event: one that has been + # replaced (a restart) must not change the status of the next one. + client.on("authenticated", lambda: self._handle_authenticated(client=client)) + client.on("disconnected", lambda reason="": self._handle_disconnected(reason, client=client)) + client.on("reconnecting", lambda attempt=0: self._handle_reconnecting(attempt, client=client)) + client.on("error", lambda error: self._handle_error(error, client=client)) handler = self._make_message_handler(on_message) # 监听通用 message 事件(SDK 对所有消息类型都会触发此事件) # 同时保留各类型事件作为备用,handler 内部有去重保护 - self._ws_client.on("message", handler) + client.on("message", handler) for event in ("message.text", "message.image", "message.mixed", "message.voice", "message.file"): - self._ws_client.on(event, handler) + client.on(event, handler) log.info("wecom.ws.connecting", {"bot_id": config["botId"]}) - await self._ws_client.connect() + await client.connect() try: await self._wait_until_stopped(abort_event) @@ -329,38 +462,84 @@ async def _wait_until_stopped( abort_event.wait() if abort_event else asyncio.Event().wait() ) reconnect_waiter = asyncio.create_task(self._reconnect_timeout_event.wait()) + failure_waiter = asyncio.create_task(self._failure_event.wait()) done, pending = await asyncio.wait( - {abort_waiter, reconnect_waiter}, + {abort_waiter, reconnect_waiter, failure_waiter}, return_when=asyncio.FIRST_COMPLETED, ) for task in pending: task.cancel() await asyncio.gather(*pending, return_exceptions=True) + if failure_waiter in done and self._failure_event.is_set(): + raise RuntimeError(self._failure_message) if reconnect_waiter in done and self._reconnect_timeout_event.is_set(): - raise RuntimeError( - "WeCom reconnect timed out after " - f"{self._reconnect_timeout_seconds:.1f}s" - ) + raise RuntimeError(self._reconnect_timeout_message()) + + def _reconnect_timeout_message(self) -> str: + head = f"WeCom reconnect timed out after {self._reconnect_timeout_seconds:.1f}s" + if self._last_error_message: + return f"{head}。最近一次错误:{self._last_error_message}" + return ( + f"{head}:断开后没能重新连上企业微信长连接服务({_shown_ws_url(self._ws_url)})," + "请确认服务器能访问这个地址,需要走代理的检查代理设置。" + ) + + def _is_stale(self, client: Any) -> bool: + """True for an event raised by a client this channel no longer runs.""" + return client is not None and client is not self._ws_client + + def _fail(self, message: str) -> None: + """End this connection attempt: start() raises *message*, which the status shows.""" + self.mark_disconnected(message) + self._failure_message = message + self._failure_event.set() - def _handle_authenticated(self) -> None: + def _handle_authenticated(self, client: Any = None) -> None: + if self._is_stale(client): + return self.mark_connected() + self._last_error_message = None self._reconnect_timeout_event.clear() self._cancel_reconnect_watchdog() log.info("wecom.ws.authenticated") - def _handle_disconnected(self, reason: str) -> None: + def _handle_disconnected(self, reason: str, client: Any = None) -> None: + if self._is_stale(client): + return + reason = str(reason) + replaced = None if self._intentional_disconnect else _describe_replaced_connection(reason) + if replaced: + # The SDK stops reconnecting after this: the server would drop a new + # connection again while the other one is up. + log.warning("wecom.ws.replaced", {"reason": reason}) + self._fail(replaced) + return self.mark_disconnected() log.warning("wecom.ws.disconnected", {"reason": reason}) self._start_reconnect_watchdog(reason=f"disconnected:{reason}") - def _handle_reconnecting(self, attempt: int) -> None: + def _handle_reconnecting(self, attempt: int, client: Any = None) -> None: + if self._is_stale(client): + return self.mark_disconnected() log.info("wecom.ws.reconnecting", {"attempt": attempt}) self._start_reconnect_watchdog(reason=f"reconnecting:{attempt}") - def _handle_error(self, error: Exception) -> None: + def _handle_error(self, error: Exception, client: Any = None) -> None: log.error("wecom.ws.error", {"error": str(error)}) + if self._is_stale(client) or self._intentional_disconnect: + return + message = _describe_sdk_error(error, self._ws_url) + self._last_error_message = message + if _is_auth_failure(error): + # After a refused subscribe frame the SDK closes the socket itself, + # and as a clean close ends its receive loop it never tries again. + self._fail(message) + return + # Connection-level errors: the SDK keeps reconnecting; the status says why + # until it is back (or the reconnect watchdog gives up). + self.mark_disconnected(message) def _start_reconnect_watchdog(self, reason: str) -> None: if self._intentional_disconnect or self._ws_client is None: diff --git a/flocks/channel/builtin/weixin/qr_login.py b/flocks/channel/builtin/weixin/qr_login.py index e364fca82..ba934b356 100644 --- a/flocks/channel/builtin/weixin/qr_login.py +++ b/flocks/channel/builtin/weixin/qr_login.py @@ -63,11 +63,17 @@ async def _api_get(base_url: str, endpoint: str) -> dict: """Simple GET against the iLink API with a short timeout.""" import aiohttp + from urllib.parse import urlparse + + from flocks.tool.web.webfetch import is_loopback_host + url = f"{base_url.rstrip('/')}/{endpoint}" timeout = aiohttp.ClientTimeout(total=QR_TIMEOUT_MS / 1000) connector = aiohttp.TCPConnector(ssl=_make_ssl_ctx()) + # An iLink relay on this machine's loopback is reached directly: through + # a proxy from the environment, 127.0.0.1 would be the proxy host's own. async with aiohttp.ClientSession( - trust_env=True, connector=connector + trust_env=not is_loopback_host(urlparse(url).hostname), connector=connector ) as session: async with session.get( url, headers=_login_headers(), timeout=timeout diff --git a/flocks/cli/commands/admin.py b/flocks/cli/commands/admin.py index 36cddd6b8..ac3bb7d6c 100644 --- a/flocks/cli/commands/admin.py +++ b/flocks/cli/commands/admin.py @@ -174,20 +174,24 @@ def generate_one_time_password( ): """ Generate a one-time admin password on this host - (must be changed on first login). + (must be changed on first login). With no account yet, this creates the + first administrator, for a machine nobody opens the setup page on. """ - async def _run() -> str: + async def _run() -> Tuple[str, bool]: await AuthService.use_installed_backend() await AuthService.init() - return await AuthService.generate_admin_temp_password(username=username) + first = not await AuthService.has_users() + return await AuthService.generate_admin_temp_password(username=username), first try: - temp_password = asyncio.run(_run()) + temp_password, created = asyncio.run(_run()) except Exception as exc: console.print(f"[red]Failed to generate one-time password: {exc}[/red]") raise typer.Exit(1) from exc + if created: + console.print(f"[green]Created the first administrator account: {username}[/green]") console.print( f"[yellow]One-time admin password generated " f"(valid for {TEMP_PASSWORD_TTL_HOURS} hours, password change required on first login)[/yellow]" diff --git a/flocks/cli/commands/enterprise.py b/flocks/cli/commands/enterprise.py index 459d44e87..60ddadbd7 100644 --- a/flocks/cli/commands/enterprise.py +++ b/flocks/cli/commands/enterprise.py @@ -135,7 +135,7 @@ async def progress(received: int, total: int | None) -> None: path = asyncio.run(enterprise.download(offer, progress)) console.print(f"[green]✓ 已下载并校验:{path}[/green]") if not enterprise.can_run_installer_here(): - console.print("[yellow]这台机器由 systemd 管(开源离线包),要以 root 运行安装包:[/yellow]") + console.print("[yellow]当前开源版由 systemd 管理(开源离线包),请使用 root 权限运行安装包:[/yellow]") console.print(f" [bold]{enterprise.installer_command(str(path))}[/bold]") return 1 console.print(f"运行 {path.name}(开源版会停下,企业版起来后照旧用 flocks start|stop|status|update)") diff --git a/flocks/cli/main.py b/flocks/cli/main.py index b05696166..7d16862ce 100644 --- a/flocks/cli/main.py +++ b/flocks/cli/main.py @@ -42,6 +42,7 @@ ) from flocks.cli.commands.update import update_command from flocks.cli.service_config import ( + DEFAULT_SERVICE_HOST, ServiceConfig, ServiceConfigError, build_service_config, @@ -353,7 +354,7 @@ def _service_config( webui_port=webui_port, default_server_host=default_server_host or global_config.server_host, default_server_port=default_server_port or global_config.server_port, - default_webui_host=default_webui_host or "127.0.0.1", + default_webui_host=default_webui_host or DEFAULT_SERVICE_HOST, default_webui_port=default_webui_port or 5173, ) @@ -418,7 +419,7 @@ def start( "--skip-webui-build", help="Skip WebUI static asset build before starting Flocks service", ), - host: Optional[str] = typer.Option(None, "--host", "-h", help="Public service host"), + host: Optional[str] = typer.Option(None, "--host", "-h", help="Public service host (default 0.0.0.0, all interfaces; 127.0.0.1 keeps it on this machine)"), port: Optional[int] = typer.Option(None, "--port", "-p", help="Public service port", **_PORT_OPTION_KWARGS), server_host: Optional[str] = typer.Option(None, "--server-host", help="Backend server host"), server_port: Optional[int] = typer.Option(None, "--server-port", help="Backend server port", **_PORT_OPTION_KWARGS), @@ -470,7 +471,7 @@ def restart( "--skip-webui-build", help="Skip WebUI static asset build before starting Flocks service", ), - host: Optional[str] = typer.Option(None, "--host", "-h", help="Public service host"), + host: Optional[str] = typer.Option(None, "--host", "-h", help="Public service host (default: where the running service listens, else 0.0.0.0)"), port: Optional[int] = typer.Option(None, "--port", "-p", help="Public service port", **_PORT_OPTION_KWARGS), server_host: Optional[str] = typer.Option(None, "--server-host", help="Backend server host"), server_port: Optional[int] = typer.Option(None, "--server-port", help="Backend server port", **_PORT_OPTION_KWARGS), @@ -561,6 +562,8 @@ def serve( import uvicorn os.environ["_FLOCKS_SERVER_PORT"] = str(port) + # Where it listens, for the first-administrator page (routes/auth._local_setup_url). + os.environ["_FLOCKS_SERVER_HOST"] = host # One id per service launch, inherited by all uvicorn workers/reload children. os.environ["_FLOCKS_SERVICE_BOOT_ID"] = secrets_lib.token_hex(16) apply_console_default() @@ -599,9 +602,9 @@ def serve( @app.command(name="service-daemon", hidden=True) def service_daemon( - server_host: str = typer.Option("127.0.0.1", "--server-host", help="Backend server host"), + server_host: str = typer.Option(DEFAULT_SERVICE_HOST, "--server-host", help="Backend server host"), server_port: int = typer.Option(5173, "--server-port", help="Public service port"), - webui_host: str = typer.Option("127.0.0.1", "--webui-host", help="WebUI host"), + webui_host: str = typer.Option(DEFAULT_SERVICE_HOST, "--webui-host", help="WebUI host"), webui_port: int = typer.Option(5173, "--webui-port", help="WebUI port"), legacy_server_host: Optional[str] = typer.Option(None, "--legacy-server-host", help="Legacy backend host"), legacy_server_port: Optional[int] = typer.Option(8000, "--legacy-server-port", help="Legacy backend port"), diff --git a/flocks/cli/service_config.py b/flocks/cli/service_config.py index f8a36844e..5d5efe98f 100644 --- a/flocks/cli/service_config.py +++ b/flocks/cli/service_config.py @@ -11,11 +11,19 @@ class ServiceConfigError(ValueError): """Raised when service configuration input is invalid.""" +# Where the WebUI/API listens when neither the command line nor the +# environment says: every IPv4 interface, so other machines reach the page at +# http://:5173. ``--host 127.0.0.1`` (or FLOCKS_HOST) +# keeps it on this machine. The first administrator can still only be created +# from this machine (flocks.server.auth.is_local_request). +DEFAULT_SERVICE_HOST = "0.0.0.0" + + @dataclass(frozen=True) class ServiceConfig: - backend_host: str = "127.0.0.1" + backend_host: str = DEFAULT_SERVICE_HOST backend_port: int = 5173 - frontend_host: str = "127.0.0.1" + frontend_host: str = DEFAULT_SERVICE_HOST frontend_port: int = 5173 legacy_backend_host: str | None = "127.0.0.1" legacy_backend_port: int | None = 8000 @@ -152,7 +160,7 @@ def build_service_config( webui_port: int | None = None, default_server_host: str, default_server_port: int, - default_webui_host: str = "127.0.0.1", + default_webui_host: str = DEFAULT_SERVICE_HOST, default_webui_port: int = 5173, ) -> ServiceConfig: """Build service config from CLI values, environment, and defaults. diff --git a/flocks/command/direct.py b/flocks/command/direct.py index 0fd874f04..aadc0f68f 100644 --- a/flocks/command/direct.py +++ b/flocks/command/direct.py @@ -4,6 +4,7 @@ from __future__ import annotations +import asyncio from collections import defaultdict from dataclasses import dataclass from typing import Any, Awaitable, Callable, Optional @@ -290,7 +291,7 @@ async def run_direct_command( return DirectCommandResult(handled=True, text=build_tools_catalog_summary()) if args == "refresh": - ToolRegistry.refresh_dynamic_tools() + await asyncio.to_thread(ToolRegistry.refresh_dynamic_tools) summary = build_tools_catalog_summary() text = "Dynamic tools refreshed. Current summary:\n\n" + summary.split("\n", 1)[1] return DirectCommandResult(handled=True, text=text) diff --git a/flocks/console/connectivity.py b/flocks/console/connectivity.py new file mode 100644 index 000000000..24659bcb1 --- /dev/null +++ b/flocks/console/connectivity.py @@ -0,0 +1,91 @@ +""" +Whether this install can reach Console now. + +The licence pages offer what works from here: signing in to a cloud account, applying online and syncing +with Console when Console answers; an application file to hand over and a licence file to import when it +does not (an install inside a network that does not reach Console, or one set up with no Console at all). + +Console answers ``GET /health``. Any answer from it counts (an older Console without that route answers +404, which still says the way there is open); no answer, a timeout, or a gateway's 5xx in its place does +not. The answer is kept for a short while, so a page that asks on every visit does not ask Console every +time; asking again with ``refresh`` checks now. +""" + +from __future__ import annotations + +import asyncio +import time +from datetime import UTC, datetime +from typing import Any +from urllib.parse import urlsplit + +import httpx + +from flocks.utils.log import Log + +log = Log.create(service="console.connectivity") + +#: How long an answer is kept. +CACHE_SECONDS = 30 +#: How long Console has to answer: long enough for a slow link, short enough for a page that waits. +TIMEOUT_SECONDS = 4 + +_lock = asyncio.Lock() +#: (base URL asked, monotonic time asked, answer) +_kept: tuple[str, float, dict[str, Any]] | None = None + + +def _base_url() -> str: + from flocks.console.login import ConsoleLoginService + + return ConsoleLoginService.console_base_url() + + +def _host(base: str) -> str: + try: + return urlsplit(base).hostname or "" + except ValueError: + return "" + + +async def _probe(base: str) -> tuple[bool, str | None]: + """Whether Console answers at *base*, and why not when it does not (for the log, not the page).""" + try: + async with httpx.AsyncClient(timeout=TIMEOUT_SECONDS, follow_redirects=False) as client: + resp = await client.get(f"{base}/health") + except httpx.HTTPError as exc: + return False, str(exc) or type(exc).__name__ + if resp.status_code >= 500: + return False, f"HTTP {resp.status_code}" + return True, None + + +async def console_connectivity(*, refresh: bool = False) -> dict[str, Any]: + """``configured``: a Console address is set; ``online``: Console answered just now (or within + CACHE_SECONDS); ``console_host``: the host asked; ``checked_at``: when it was asked.""" + global _kept + base = _base_url() + if not base: + return {"configured": False, "online": False, "console_host": "", "checked_at": datetime.now(UTC).isoformat()} + async with _lock: + if not refresh and _kept is not None: + kept_base, asked_at, answer = _kept + if kept_base == base and time.monotonic() - asked_at < CACHE_SECONDS: + return dict(answer) + online, why = await _probe(base) + if not online: + log.info("console.unreachable", {"host": _host(base), "reason": why}) + answer = { + "configured": True, + "online": online, + "console_host": _host(base), + "checked_at": datetime.now(UTC).isoformat(), + } + _kept = (base, time.monotonic(), answer) + return dict(answer) + + +def forget() -> None: + """Drop the kept answer (tests; a changed address is noticed by itself).""" + global _kept + _kept = None diff --git a/flocks/console/login.py b/flocks/console/login.py index cf5297bfe..6ea48d479 100644 --- a/flocks/console/login.py +++ b/flocks/console/login.py @@ -21,7 +21,7 @@ import httpx from flocks import __version__ -from flocks.console.previous_licence import find_licence_file, licence_id_of, licence_token +from flocks.console.previous_licence import LICENCE_FILE_LOCK, find_licence_file, licence_id_of, licence_token from flocks.storage.storage import Storage from flocks.utils.log import Log @@ -86,19 +86,22 @@ def keep_previous_licence_current(data: dict[str, Any]) -> None: patch in its answer) reaches the file whether the package is there or not: the Flocks Pro page reads it, and the enterprise core takes it when the machine moves. An extension that reports for itself has this among what it does, and a machine with no such licence has nothing here.""" - found = find_licence_file() - if found is None: - return - path, state = found - now = int(datetime.now(UTC).timestamp()) - state["last_sync_at"] = now - state["last_heartbeat_ok_at"] = now - patch = data.get("license_patch") or data.get("latest_patch") - if isinstance(patch, str) and patch: - patches = state.get("patches") if isinstance(state.get("patches"), list) else [] - if patch not in patches: - state["patches"] = [*patches, patch] - _write_private_json(path, state) + # Read and written back under the lock an import or a licence taken holds too: a copy read before + # their write would put back what they replaced, or drop the patches they added. + with LICENCE_FILE_LOCK: + found = find_licence_file() + if found is None: + return + path, state = found + now = int(datetime.now(UTC).timestamp()) + state["last_sync_at"] = now + state["last_heartbeat_ok_at"] = now + patch = data.get("license_patch") or data.get("latest_patch") + if isinstance(patch, str) and patch: + patches = state.get("patches") if isinstance(state.get("patches"), list) else [] + if patch not in patches: + state["patches"] = [*patches, patch] + _write_private_json(path, state) revoked = data.get("revoked_license_ids") if isinstance(revoked, list): _write_private_json(path.with_name("revocation.json"), {"revoked_license_ids": sorted({str(item) for item in revoked})}) diff --git a/flocks/console/previous_licence.py b/flocks/console/previous_licence.py index 1b224ed7a..104cbd5c6 100644 --- a/flocks/console/previous_licence.py +++ b/flocks/console/previous_licence.py @@ -15,6 +15,7 @@ import hashlib import json import os +import threading import time from datetime import UTC, datetime from pathlib import Path @@ -27,6 +28,13 @@ _TOKEN_FIELDS = ("key", "token", "activate_key") +#: Held around every read-modify-write of the licence file -- the heartbeat adding the patch Console sent, +#: a licence taken or imported -- so none writes back a copy read before another's write. Re-entrant: a +#: caller holding it may call one that takes it again. No await inside: it is held by threads and by the +#: event loop alike, for a file read and a file write. +LICENCE_FILE_LOCK = threading.RLock() + + def licence_files() -> list[Path]: """Where the Python enterprise package kept its licence: under FLOCKS_ROOT (its cloud checker), or under the home's .flocks whatever FLOCKS_ROOT says (its offline checker).""" @@ -46,16 +54,25 @@ def read_licence_file(path: Path) -> dict[str, Any] | None: return data if isinstance(data, dict) else None -def token_claims(token: Any) -> dict[str, Any] | None: - """What a signed token says of itself, None for what does not read as one.""" +def _token_part(token: Any, index: int) -> dict[str, Any] | None: parts = token.split(".") if isinstance(token, str) else [] if len(parts) != 3: return None try: - claims = json.loads(base64.urlsafe_b64decode(parts[1] + "=" * (-len(parts[1]) % 4))) + part = json.loads(base64.urlsafe_b64decode(parts[index] + "=" * (-len(parts[index]) % 4))) except (ValueError, UnicodeDecodeError, binascii.Error): return None - return claims if isinstance(claims, dict) else None + return part if isinstance(part, dict) else None + + +def token_claims(token: Any) -> dict[str, Any] | None: + """What a signed token says of itself, None for what does not read as one.""" + return _token_part(token, 1) + + +def token_header(token: Any) -> dict[str, Any] | None: + """A signed token's header (its alg and kid), None for what does not read as one.""" + return _token_part(token, 0) def licence_token(data: dict[str, Any]) -> tuple[str, dict[str, Any]]: diff --git a/flocks/contracts/access/driver.py b/flocks/contracts/access/driver.py index 69404f873..2c36a8aa0 100644 --- a/flocks/contracts/access/driver.py +++ b/flocks/contracts/access/driver.py @@ -2,6 +2,7 @@ from __future__ import annotations +import dataclasses import json import re import sqlite3 @@ -21,6 +22,10 @@ MAX_SCAN_BYTES = 32 * 1024 * 1024 MAX_SCAN_SECONDS = 30 SOURCE_ROW_ID_FIELD = "__flocks_source_row_id" +#: The SOC suite's alert store, wherever the database backend keeps it +#: (``flocks.workflow.soc_store``): the suite's contract names this kind and no +#: file, table or database of its own. +SOC_ALERTS_ADAPTER_KIND = "builtin-soc-alerts" class DriverProxy: @@ -34,12 +39,14 @@ def __init__( def execute(self, plan: QueryPlan) -> DriverResult: self._validate_plan(plan) + if plan.binding.adapter_kind == SOC_ALERTS_ADAPTER_KIND: + return self._sqlite_executor.execute(_soc_alerts_plan(plan)) if plan.binding.adapter_kind == "builtin-sqlite-json": return self._sqlite_executor.execute(plan) return self._jsonl_executor.execute(plan) def _validate_plan(self, plan: QueryPlan) -> None: - if plan.binding.adapter_kind not in {"builtin-jsonl", "builtin-sqlite-json"}: + if plan.binding.adapter_kind not in {"builtin-jsonl", "builtin-sqlite-json", SOC_ALERTS_ADAPTER_KIND}: raise ContractRuntimeError( "adapter_sandbox_unavailable", status_code=400, @@ -59,6 +66,25 @@ def _validate_plan(self, plan: QueryPlan) -> None: ) +def _soc_alerts_plan(plan: QueryPlan) -> QueryPlan: + """The plan against the SOC alert store: here, JSON records in a SQLite file.""" + from flocks.workflow.soc_store import alerts + + options = dict(plan.binding.driver_options) + source = alerts.contract_source(options) + for name in ("settings", "settingsDir"): + options.pop(name, None) + db_path = Path(source.pop("db_path")) + binding = dataclasses.replace( + plan.binding, + adapter_kind="builtin-sqlite-json", + source_root=db_path, + driver_allowlist_roots=(db_path.parent,), + driver_options={**options, **source}, + ) + return dataclasses.replace(plan, binding=binding) + + class SqliteJsonDriverExecutor: def execute(self, plan: QueryPlan) -> DriverResult: db_path = plan.binding.source_root diff --git a/flocks/contracts/webui/api_runtime.py b/flocks/contracts/webui/api_runtime.py index fcc3e76e9..b7704497a 100644 --- a/flocks/contracts/webui/api_runtime.py +++ b/flocks/contracts/webui/api_runtime.py @@ -641,9 +641,13 @@ def _normalize_response(self, result: Any) -> Response: return JSONResponse(content=result) def _create_context(self, page_id: str, user: Any, secrets: frozenset[str] = frozenset()) -> Any: + from flocks import coordination from flocks.coordination import page_api_database logger = Log.create(service=f"webui-page-api:{page_id}") + # A backend written before pages were handed services has none to give. + page_api_services = getattr(coordination, "page_api_services", None) + services = page_api_services() if page_api_services is not None else {} return SimpleNamespace( page_id=page_id, user=user, @@ -652,6 +656,11 @@ def _create_context(self, page_id: str, user: Any, secrets: frozenset[str] = fro cache=None, # A direct database handle, from a backend that offers pages one; None otherwise. database=page_api_database(), + # What the backend hands pages by name: ``ctx.services.soc`` is the SOC suite's data. + services=SimpleNamespace(**{ + name: service for name, service in services.items() + if isinstance(name, str) and name.isidentifier() + }), ) async def _mark_failed(self, page_id: str, error: str) -> None: diff --git a/flocks/coordination.py b/flocks/coordination.py index 3210169e0..7d011b13d 100644 --- a/flocks/coordination.py +++ b/flocks/coordination.py @@ -4,7 +4,9 @@ The runtime keeps its data in SQLite and runs in one process, so each question here has that answer: no other process is running a session, a shared value is simply the stored one, and a WebUI page or a workflow gets no direct database -handle. +handle. What they do get is the SOC suite's data service +(``flocks.workflow.soc_store``), which the suite's pages read and its triage +workflow writes through. Another database backend replaces this module as a whole (see ``flocks.db_backend``) with its own answers. Callers ask here instead of @@ -46,13 +48,26 @@ def page_api_database() -> Any: return None +def page_api_services() -> dict[str, Any]: + """``ctx.services`` for a WebUI page's API handlers, by name. + + ``soc``: what the SOC pages read their figures through. + """ + from flocks.workflow import soc_store + + return {"soc": soc_store.page_service()} + + def workflow_services(cancel_checker: Optional[Callable[[], bool]]) -> dict[str, Any]: - """Objects a backend hands workflow python nodes by name, next to ``tool`` and ``llm``: none here. + """Objects a backend hands workflow python nodes by name, next to ``tool`` and ``llm``. - Each lists the methods a node may call (``exposed_methods``) and may set a - time limit, in seconds, for a call from an isolated node (``rpc_timeout_s``). + ``soc``: what the triage workflow writes alerts through. Each lists the + methods a node may call (``exposed_methods``) and may set a time limit, in + seconds, for a call from an isolated node (``rpc_timeout_s``). """ - return {} + from flocks.workflow.soc_store import SOCWriteCapability + + return {"soc": SOCWriteCapability(cancel_checker)} def is_unique_violation(exc: BaseException) -> bool: @@ -67,6 +82,7 @@ def is_unique_violation(exc: BaseException) -> bool: __all__ = [ "is_unique_violation", "page_api_database", + "page_api_services", "sessions_running_elsewhere", "shared_setdefault", "workflow_services", diff --git a/flocks/db_backend.py b/flocks/db_backend.py index 39bd9a62a..c3d7b6eb4 100644 --- a/flocks/db_backend.py +++ b/flocks/db_backend.py @@ -98,6 +98,8 @@ "flocks.workflow.execution_store", "flocks.workflow.poller_manager", "flocks.workflow.ownership", + # What the alert operations suite writes and reads (its files hold no database code). + "flocks.workflow.soc_store", # Syslog listeners: one per workflow among the processes sharing the data. "flocks.ingest.syslog.manager", # Memory index and notes shared between nodes. diff --git a/flocks/hub/catalog.py b/flocks/hub/catalog.py index 416300274..0da2ec3db 100644 --- a/flocks/hub/catalog.py +++ b/flocks/hub/catalog.py @@ -103,6 +103,50 @@ def _read_yaml(path: Path) -> dict[str, Any]: return {} +@_once_per_build +def _read_plugin_json(path: Path) -> dict[str, Any]: + """A local plugin's JSON, ``{}`` when it is not a readable object. + + _read_yaml and _frontmatter already read a plugin's own broken file this + way: what someone wrote into their plugin directory decides how that plugin + is listed, not whether the catalog can be built. + """ + try: + data = json.loads(path.read_text(encoding="utf-8")) + except (OSError, ValueError) as exc: + log.warn("hub.plugin_file.invalid", {"path": str(path), "error": str(exc)}) + return {} + return data if isinstance(data, dict) else {} + + +def _string_items(value: Any) -> list[str]: + """The strings of a list field; ``tools:`` with nothing after it reads as null.""" + if isinstance(value, str): + return [value] + if isinstance(value, (list, tuple, set, dict)): + return [item for item in value if isinstance(item, str)] + return [] + + +def _read_local_plugin(reader, *args) -> Optional[HubPluginManifest]: + """``reader(*args)`` -- ending in the plugin's id and root -- or None when it fails. + + Scanning the plugin directories is how the whole catalog gets built, so a + plugin someone left half-written costs that plugin its place in the listing + and nothing else. + """ + try: + return reader(*args) + except tool_tree.Superseded: + raise + except Exception as exc: + log.warn( + "hub.local_plugin.unreadable", + {"id": str(args[-2]), "path": str(args[-1]), "type": type(exc).__name__, "error": str(exc)}, + ) + return None + + def _path_signature(path: Path) -> tuple[str, int, int]: try: stat = path.stat() @@ -448,7 +492,7 @@ def _agent_manifest(plugin_id: str, root: Path) -> Optional[HubPluginManifest]: if not agent_file.is_file(): return None data = _read_yaml(agent_file) - tools = [str(item) for item in data.get("tools", []) if isinstance(item, str)] + tools = _string_items(data.get("tools")) network = any(item in {"websearch", "webfetch"} or item.endswith("_query") for item in tools) shell = "bash" in tools filesystem = "write" if any(item in {"edit", "write"} for item in tools) else "read" @@ -459,7 +503,7 @@ def _agent_manifest(plugin_id: str, root: Path) -> Optional[HubPluginManifest]: description=str(data.get("description") or data.get("description_cn") or ""), description_cn=str(data.get("description_cn") or "") or None, category="detection", - tags=_safe_tags([str(item) for item in data.get("tags", []) if isinstance(item, str)]), + tags=_safe_tags(_string_items(data.get("tags"))), use_cases=["alert-triage"], capabilities=["llm-agent"], entrypoints=[item for item in ("agent.yaml", str(data.get("prompt_file") or "prompt.md")) if (root / item).exists()], @@ -477,7 +521,7 @@ def _workflow_manifest(plugin_id: str, root: Path) -> Optional[HubPluginManifest workflow_file = root / "workflow.json" if not workflow_file.is_file() and not (root / "workflow.md").is_file(): return None - data = _read_json(workflow_file) if workflow_file.is_file() else {} + data = _read_plugin_json(workflow_file) if workflow_file.is_file() else {} entrypoints = [name for name in ("workflow.json", "workflow.md") if (root / name).exists()] description_raw = str(data.get("description") or "") description_en = str(data.get("description_en") or "").strip() @@ -663,12 +707,12 @@ def _discover_system_plugin_roots() -> dict[tuple[PluginType, str], Path]: if not base.is_dir(): continue for child in sorted(base.iterdir(), key=lambda item: item.name): - if _is_plugin_dir(child) and detector(child.name, child): + if _is_plugin_dir(child) and _read_local_plugin(detector, child.name, child): roots[(plugin_type, child.name)] = child tools_root = local.install_root("tool", "project") for directory in _iter_tool_plugin_dirs(tools_root): - manifest = _tool_manifest(directory.name, directory) + manifest = _read_local_plugin(_tool_manifest, directory.name, directory) if manifest: # The manifest type already reflects ``integration_type: # device`` (see :func:`_tool_manifest`), so we just defer @@ -731,7 +775,7 @@ def _discover_bundled_tool_roots() -> dict[tuple[PluginType, str], Path]: for tools_root in bundled_tool_plugin_roots(): for directory in _iter_tool_plugin_dirs(tools_root): name = directory.name - manifest = _tool_manifest(name, directory) + manifest = _read_local_plugin(_tool_manifest, name, directory) if not manifest: continue # First-wins: keep the highest-priority bundled root entry @@ -827,7 +871,7 @@ def _build_catalog_entries( for (system_type, system_id), root in _system_plugin_roots().items(): if (system_type, system_id) in seen: continue - manifest = _manifest_for_system_root(system_type, system_id, root) + manifest = _read_local_plugin(_manifest_for_system_root, system_type, system_id, root) if manifest: entries.append(_entry_from_system_manifest(manifest, root)) seen.add((system_type, system_id)) @@ -842,7 +886,7 @@ def _build_catalog_entries( for (bundled_type, bundled_id), root in _bundled_tool_roots().items(): if (bundled_type, bundled_id) in seen: continue - manifest = _manifest_for_system_root(bundled_type, bundled_id, root) + manifest = _read_local_plugin(_manifest_for_system_root, bundled_type, bundled_id, root) if manifest: entries.append(_entry_from_bundled_tool(manifest, root, records, inferred_installs)) seen.add((bundled_type, bundled_id)) diff --git a/flocks/hub/installer.py b/flocks/hub/installer.py index 37f34d15c..5dc21844d 100644 --- a/flocks/hub/installer.py +++ b/flocks/hub/installer.py @@ -765,7 +765,23 @@ async def _rollback_component_ref_installs( raise RuntimeError("Dependency rollback incomplete; " + "; ".join(errors)) +def _project_root_is_user_root(plugin_type: PluginType) -> bool: + """The instance directory holds the flocks root (``~`` holding ``~/.flocks``). + + Its ``.flocks/plugins`` is then the user plugin root itself: what is installed + there was installed by the user, nothing in it shipped with a project. + """ + try: + return local.install_root(plugin_type, "project").resolve() == local.install_root(plugin_type, "global").resolve() + except OSError: + return False + + def _is_project_install_path(plugin_type: PluginType, install_path: Path) -> bool: + if _project_root_is_user_root(plugin_type): + # A server started from the home directory would otherwise refuse to + # uninstall anything ("Built-in project Hub plugins cannot be removed"). + return False try: project_root = local.install_root(plugin_type, "project").resolve() resolved_install_path = install_path.resolve() @@ -1296,6 +1312,11 @@ async def _uninstall_plugin( record = local.get_record(plugin_type, plugin_id) install_path = Path(record.installPath) if record and record.installPath else local.infer_local_install(plugin_type, plugin_id) scope = record.scope if record else "global" + if scope == "project" and _project_root_is_user_root(plugin_type): + # The project plugin root is the user plugin root: a "project" record there is + # a user install, checked and removed as one -- every target is validated + # (the access contracts included) before anything is deleted. + scope = "global" if install_path is not None: await asyncio.to_thread(_validate_uninstall_target, plugin_type, plugin_id, install_path, scope) if plugin_type == "webui" and scope != "project": @@ -1317,7 +1338,7 @@ async def _uninstall_plugin( # A missing page payload can still leave its access contracts behind. # Keep project-managed contracts protected even when their pages vanished. access_removed = False - if plugin_type == "webui" and (record is None or record.scope != "project"): + if plugin_type == "webui" and scope != "project": access_removed = await asyncio.to_thread( _remove_attached_access_contracts, plugin_type, plugin_id, "global", recovery_root=recovery_root, ) @@ -1346,7 +1367,7 @@ async def _uninstall_plugin( else: install_path.unlink() _remove_attached_access_contracts( - plugin_type, plugin_id, record.scope if record else "global", recovery_root=recovery_root, + plugin_type, plugin_id, scope, recovery_root=recovery_root, ) local.remove_installed_record(plugin_type, plugin_id) clear_catalog_caches() diff --git a/flocks/hub/local.py b/flocks/hub/local.py index 239911918..eaa60cec2 100644 --- a/flocks/hub/local.py +++ b/flocks/hub/local.py @@ -83,7 +83,7 @@ def load_installed_records() -> dict[str, InstalledPluginRecord]: raw = json.loads(path.read_text(encoding="utf-8")) except Exception: return {} - records = raw.get("plugins", raw) + records = raw.get("plugins", raw) if isinstance(raw, dict) else None if not isinstance(records, dict): return {} result: dict[str, InstalledPluginRecord] = {} diff --git a/flocks/ingest/kafka/manager.py b/flocks/ingest/kafka/manager.py index b9ef8afb8..13ff1e7b6 100644 --- a/flocks/ingest/kafka/manager.py +++ b/flocks/ingest/kafka/manager.py @@ -10,6 +10,13 @@ a UDP/TCP socket bind. "binding/listening" is replaced by "connecting/running"; a connection failure (broker unreachable, auth error) is surfaced the same way a bind failure is. +* Opt-in ``inputs._kafka_batching`` groups up to ``batchsize`` records into + one real workflow execution; ``maxparallel`` limits concurrent batch runs. + A partial batch flushes after ``batch_timeout_ms`` of input inactivity + (default 5000 ms). Even a batch of one has a list payload. Workflows receive + ``_kafka_delivery_ids`` aligned with that list for per-record idempotency; + batch IDs can change when replay regroups records after an idle flush. + Ordinary triggers keep one-record delivery. * Backpressure uses a *blocking* ``queue.put`` instead of ``put_nowait``+drop. Offsets are committed explicitly after successful workflow completion and persistence, never past an unfinished message in the same partition. A crash @@ -64,13 +71,9 @@ log = Log.create(service="kafka.manager") -# Maximum concurrent workflow executions per workflow to avoid FD exhaustion and -# database write contention. Kafka messages can carry large JSON payloads, so keep -# this bounded even when a trigger requests a larger worker pool. -_MAX_CONCURRENT_EXECUTIONS = 8 -# Maximum number of buffered Kafka messages per workflow. Unlike syslog we do -# not drop on overflow; a full queue applies backpressure to the consumer loop. -_MAX_QUEUE_SIZE = 1000 +# Per-workflow resource limits; a full queue applies backpressure to Kafka. +_MAX_CONCURRENT_EXECUTIONS = 20 +_MAX_QUEUE_SIZE = 5000 # Maximum time we wait for the consumer to either connect successfully or fail # during ``restart_workflow`` so the HTTP save endpoint can surface connection # errors instead of pretending the consumer is running. @@ -99,8 +102,19 @@ }) +def _kafka_batch_settings(inputs: Dict[str, Any]) -> tuple[int, int]: + """Batching is opt-in; ordinary Kafka triggers keep one-record delivery.""" + if not (inputs or {}).get("_kafka_batching"): + return 1, 0 + size = max(1, min(1000, int(inputs.get("batchsize") or 20))) + wait_ms = max(1, min(5000, int(inputs.get("batch_timeout_ms") or 5000))) + return size, wait_ms + + def _worker_count_for_trigger(trigger: TriggerDefinition) -> int: - return min(_MAX_CONCURRENT_EXECUTIONS, max(1, int(trigger.concurrency.maxParallel))) + inputs = trigger.inputs or {} + workers = inputs.get("maxparallel") if inputs.get("_kafka_batching") else None + return min(_MAX_CONCURRENT_EXECUTIONS, max(1, int(workers or trigger.concurrency.maxParallel))) def _queue_size_for_trigger(trigger: TriggerDefinition) -> int: @@ -128,6 +142,13 @@ class _QueuedKafkaMessage: delivery: Optional[_KafkaDelivery] = None +@dataclass(frozen=True) +class _QueuedKafkaBatch: + messages: tuple[_QueuedKafkaMessage, ...] + sequence: int + generation: str + + class _KafkaGenerationStopped(Exception): """The consumer generation no longer owns its queued deliveries.""" @@ -289,6 +310,34 @@ async def complete(self, delivery: _KafkaDelivery) -> None: self._slots.release() + async def complete_many(self, deliveries: Iterable[_KafkaDelivery]) -> None: + """Acknowledge a successful batch, committing one completed prefix per partition.""" + items = tuple(deliveries) + async with self._commit_lock: + for item in items: + self._check_partition_owner(item.partition, item.epoch) + for item in items: + item.completed = True + prefixes = {} + for partition in {item.partition for item in items}: + prefix = [] + for item in self._pending.get(partition, ()): + if not item.completed: + break + prefix.append(item) + if prefix: + prefixes[partition] = prefix + if not prefixes: + return + await self.consumer.commit({partition: prefix[-1].offset + 1 for partition, prefix in prefixes.items()}) + for item in items: + self._check_partition_owner(item.partition, item.epoch) + for partition, prefix in prefixes.items(): + for _ in prefix: + self._pending[partition].popleft() + self._slots.release() + + def _delivery_error_diagnostics(exc: BaseException) -> Dict[str, Any]: facts: Dict[str, Any] = {"error": str(exc), "error_type": type(exc).__name__} if isinstance(exc, _KafkaDeliveryError): @@ -812,6 +861,8 @@ def _create_generation( configured_inputs: Dict[str, Any], topic: str, ) -> tuple[asyncio.Queue, asyncio.Event]: queue: asyncio.Queue = asyncio.Queue(maxsize=_queue_size_for_trigger(trigger)) + queue._kafka_batch_settings = _kafka_batch_settings(configured_inputs) + queue._kafka_batch_generation = uuid.uuid4().hex abort = asyncio.Event() cancel = threading.Event() self._queues[workflow_id] = queue @@ -981,7 +1032,8 @@ async def _consumer_loop( tracker = _KafkaOffsetTracker( consumer, abort, - max_pending=queue.maxsize + max(1, len(self._worker_pools.get(workflow_id, ()))), + max_pending=(queue.maxsize + max(1, len(self._worker_pools.get(workflow_id, ())))) + * getattr(queue, "_kafka_batch_settings", (1, 0))[0], ) manager = self cancel_event = self._generation_cancel_events.get(workflow_id) or threading.Event() @@ -1138,12 +1190,43 @@ async def _fetch() -> Any: # before the message can wait for queue/acknowledgement capacity. return message, partition, tracker.epoch_for(partition) + async def _fetch_guarded() -> Any: + return await _until_aborted(_fetch(), abort) + + batch_size, batch_wait_ms = getattr(queue, "_kafka_batch_settings", (1, 0)) + batch_items = [] + batch_sequence = 0 + batch_deadline = None + batch_fetch = None + + async def flush_batch() -> None: + nonlocal batch_items, batch_sequence, batch_deadline + batch = _QueuedKafkaBatch(tuple(batch_items), batch_sequence, queue._kafka_batch_generation) + await _until_aborted(queue.put(batch), abort) + batch_items = [] + batch_sequence += 1 + batch_deadline = None + try: while not abort.is_set(): delivery = None try: - msg, partition, epoch = await _until_aborted(_fetch(), abort) + if batch_fetch is None: + batch_fetch = asyncio.create_task(_fetch_guarded()) + if batch_items: + remaining = max(0.001, batch_deadline - asyncio.get_running_loop().time()) + # An idle-tail flush must never cancel a fetch: getone may + # already have advanced the consumer's local position. + msg, partition, epoch = await asyncio.wait_for(asyncio.shield(batch_fetch), remaining) + else: + msg, partition, epoch = await batch_fetch + batch_fetch = None + except asyncio.TimeoutError: + if batch_items: + await flush_batch() + continue except _KafkaAssignmentChanged: + batch_fetch = None continue raw_value = msg.value await _until_aborted(tracker.wait_for_slot(), abort) @@ -1153,8 +1236,15 @@ async def _fetch() -> Any: size_bytes=len(raw_value) if raw_value is not None else 0, delivery=delivery, ) - # Blocking put applies backpressure instead of dropping messages. - await _until_aborted(queue.put(queued), abort) + # Aggregate in the single reader, so concurrent workers cannot split a batch. + if batch_wait_ms == 0: + await _until_aborted(queue.put(queued), abort) + else: + batch_items.append(queued) + # Flush an idle tail; capacity waits must not prematurely split a backlog. + batch_deadline = asyncio.get_running_loop().time() + batch_wait_ms / 1000 + if len(batch_items) >= batch_size: + await flush_batch() except _KafkaGenerationStopped: pass except asyncio.CancelledError: @@ -1166,6 +1256,9 @@ async def _fetch() -> Any: {"workflow_id": workflow_id, **_delivery_error_diagnostics(exc)}, ) finally: + if batch_fetch is not None: + batch_fetch.cancel() + await asyncio.gather(batch_fetch, return_exceptions=True) await _finish_cleanup(shutdown()) async def _worker_loop( @@ -1206,9 +1299,31 @@ def _unexpected_cancel(delivery: Optional[_KafkaDelivery] = None) -> None: except asyncio.CancelledError: _unexpected_cancel() return - delivery = msg.delivery if isinstance(msg, _QueuedKafkaMessage) else None + batch = msg if isinstance(msg, _QueuedKafkaBatch) else None + deliveries = [item.delivery for item in batch.messages if item.delivery is not None] if batch else [] + delivery = deliveries[0] if deliveries else (msg.delivery if isinstance(msg, _QueuedKafkaMessage) else None) + batch_inputs = dict(configured_inputs) + if batch: + # Batch membership can change on replay. Expose record identities + # directly to workflows so deduplication survives regrouping. + batch_inputs.update( + _kafka_batch_seq=batch.sequence, + _kafka_batch_generation=batch.generation, + _kafka_delivery_ids=[item.delivery_id for item in deliveries], + ) + message_diagnostics = { + **(delivery.diagnostics() if delivery is not None else {}), + "batchSize": len(batch.messages), + "batchOffsets": [item.diagnostics() for item in deliveries], + } + delivery_id = "kafka-batch:" + hashlib.sha256("|".join(item.delivery_id for item in deliveries).encode()).hexdigest() + else: + message_diagnostics = delivery.diagnostics() if delivery is not None else None + delivery_id = delivery.delivery_id if delivery is not None else None try: - if isinstance(msg, _QueuedKafkaMessage): + if batch: + msg = [_decode_message(item.raw_value) for item in batch.messages] + elif isinstance(msg, _QueuedKafkaMessage): msg = _decode_message(msg.raw_value) async def _dispatch() -> None: @@ -1217,12 +1332,12 @@ async def _dispatch() -> None: workflow_plan, msg, next(iter(trigger.mapping or {}), "kafka_message"), - configured_inputs, - trigger=trigger, + batch_inputs, + trigger=trigger.model_copy(update={"inputs": batch_inputs}) if batch else trigger, source=source, generation_cancel_event=run_cancel_event, - delivery_id=delivery.delivery_id if delivery is not None else None, - kafka_metadata=delivery.diagnostics() if delivery is not None else None, + delivery_id=delivery_id, + kafka_metadata=message_diagnostics, ) if isinstance(outcome, _KafkaDispatchOutcome) and not outcome.acknowledged: raise _KafkaDeliveryError( @@ -1242,7 +1357,7 @@ async def _dispatch() -> None: ) if delivery is not None: await self._retry_delivery( - lambda: delivery.tracker.complete(delivery), + lambda: delivery.tracker.complete_many(deliveries) if batch else delivery.tracker.complete(delivery), workflow_id=workflow_id, abort=abort, cancel=run_cancel_event, diff --git a/flocks/ingest/syslog/manager.py b/flocks/ingest/syslog/manager.py index 7aa17ff11..0f79ea525 100644 --- a/flocks/ingest/syslog/manager.py +++ b/flocks/ingest/syslog/manager.py @@ -42,11 +42,9 @@ log = Log.create(service="syslog.manager") -# Maximum concurrent workflow executions per workflow to avoid FD exhaustion and SQLite write contention -_MAX_CONCURRENT_EXECUTIONS = 8 -# Maximum number of buffered syslog messages per workflow; excess messages are dropped with a warning. -# Increased from 200 to 1000 to absorb larger inbound bursts before the worker pool catches up. -_MAX_QUEUE_SIZE = 1000 +# Per-workflow resource limits; excess syslog messages are dropped on overflow. +_MAX_CONCURRENT_EXECUTIONS = 20 +_MAX_QUEUE_SIZE = 5000 # Maximum time we wait for the listener to either bind successfully or fail # during ``restart_workflow``. Any value <0.5s makes the call too aggressive # under busy event-loops; anything >5s would make the HTTP save endpoint feel diff --git a/flocks/plugin/loader.py b/flocks/plugin/loader.py index 1ca617ba3..ca8e9cd94 100644 --- a/flocks/plugin/loader.py +++ b/flocks/plugin/loader.py @@ -714,7 +714,12 @@ def _load_yaml_source(cls, ext: ExtensionPoint, yaml_path: Path) -> None: return try: - raw = yaml.safe_load(yaml_path.read_text(encoding="utf-8")) + # Every plugin reload parses every tool file: use libyaml when it is + # there (the same SafeConstructor, several times faster). + raw = yaml.load( + yaml_path.read_text(encoding="utf-8"), + Loader=getattr(yaml, "CSafeLoader", yaml.SafeLoader), + ) except Exception as e: log.error("plugin.yaml_parse_failed", {"path": str(yaml_path), "error": str(e)}) cls._record_load_error(_error_source_path(str(yaml_path), yaml_path.parent), e) diff --git a/flocks/project/project.py b/flocks/project/project.py index 5992751c5..96c6d7662 100644 --- a/flocks/project/project.py +++ b/flocks/project/project.py @@ -359,8 +359,13 @@ def worktree_for_directory(cls, directory: str) -> str: return os.path.normcase(str(worktree)) @staticmethod - def _path_status(worktree: str) -> Literal["available", "missing", "unreadable"]: - path = Path(worktree) + def _directory_access(path: Path) -> Literal["available", "missing", "unreadable"]: + """Whether the account running Flocks can open ``path`` as a directory. + + ``missing`` means nothing reachable is a directory there; ``unreadable`` + that this account may not reach or list it, whether it exists or not. + """ + try: if not path.is_dir(): return "missing" @@ -371,8 +376,22 @@ def _path_status(worktree: str) -> Literal["available", "missing", "unreadable"] return "unreadable" if not os.access(path, os.R_OK | os.X_OK): return "unreadable" + # os.access only reads permission bits; on Windows it ignores the access + # list, so a service account left out of a folder's ACL passes it. Opening + # the folder for listing is the check the system itself makes. + try: + with os.scandir(path): + pass + except (FileNotFoundError, NotADirectoryError): + return "missing" + except OSError: + return "unreadable" return "available" + @classmethod + def _path_status(cls, worktree: str) -> Literal["available", "missing", "unreadable"]: + return cls._directory_access(Path(worktree)) + @staticmethod def _detect_vcs(worktree: str) -> Optional[str]: try: @@ -424,7 +443,13 @@ def validate_worktree( requested_path = Path(os.path.abspath(requested_path)) roots = cls.allowed_roots(default_worktree) - if create_if_missing and not requested_path.exists(): + try: + needs_creation = create_if_missing and not requested_path.exists() + except PermissionError: + # It may exist: this account cannot reach it. Reported below as + # such; creating it would fail the same way. + needs_creation = False + if needs_creation: ancestor = requested_path missing_parts: List[str] = [] while not ancestor.exists() and ancestor != ancestor.parent: @@ -444,15 +469,34 @@ def validate_worktree( try: path = requested_path.resolve(strict=True) + readable = True + except PermissionError: + # A parent denies search, or on Windows the folder's access list + # leaves this account out: the folder may well exist, so this is a + # permission to grant, not a path to correct. + readable = False + try: + path = requested_path.resolve(strict=False) + except (OSError, RuntimeError): + path = requested_path except (OSError, RuntimeError) as exc: raise ValueError("Project directory does not exist") from exc - if not path.is_dir(): - raise ValueError("Project path must be a directory") - if not os.access(path, os.R_OK | os.X_OK): - raise ValueError("Project directory is not readable") - - if roots and not any(path == root or path.is_relative_to(root) for root in roots): + if readable: + access = cls._directory_access(path) + if access == "missing": + raise ValueError("Project path must be a directory") + readable = access == "available" + + # The allowed roots and this account's access are separate settings + # (FLOCKS_PROJECT_ROOTS; the folder's permissions or ACL), each fixed + # by an administrator: name every one that is missing. + allowed = not roots or any(path == root or path.is_relative_to(root) for root in roots) + if not allowed and not readable: + raise ValueError("Project directory is outside the allowed roots and is not readable") + if not allowed: raise ValueError("Project directory is outside the allowed roots") + if not readable: + raise ValueError("Project directory is not readable") return os.path.normcase(str(path)) @classmethod diff --git a/flocks/provider/model_discovery.py b/flocks/provider/model_discovery.py index dd5d946c4..cbaf1ba1e 100644 --- a/flocks/provider/model_discovery.py +++ b/flocks/provider/model_discovery.py @@ -24,7 +24,16 @@ from flocks.provider.credential import UNSENDABLE_API_KEY_MESSAGE, api_key_is_sendable from flocks.provider.model_catalog import get_raw_catalog from flocks.provider.provider import Provider -from flocks.provider.sdk.openai_base import _coerce_bool, resolve_verify_ssl +from flocks.provider.sdk.openai_base import _coerce_bool +from flocks.provider.tls import ( + LEGACY_VERIFY_SSL_KEY, + TLS_ERROR_HINTS, + TLS_OPTION_KEYS, + VERIFY_SSL_KEY, + CACertError, + classify_tls_error, + httpx_verify, +) MAX_MODELS = 1000 MAX_PAGES = 10 @@ -157,23 +166,40 @@ def _resolve_option(value: Any, secrets: Any) -> str | None: return _usable(value) -def _transport_settings(options: dict, sdk_settings: Any) -> dict[str, bool]: +def _transport_settings(options: dict, sdk_settings: Any, tls_overrides: dict | None = None) -> dict[str, Any]: """TLS verification and proxy use, by the rules the provider's own client follows. - Same contract as sdk/openai_base.py: ``verify_ssl`` (or the older - ``ssl_verify``) in the provider options, and the ambient proxy settings - unless FLOCKS_HTTP_TRUST_ENV or the options' ``trust_env`` turn them off. + Same contract as the provider clients (flocks.provider.tls): ``verify_ssl`` + (or the older ``ssl_verify``) and ``ca_cert`` in the provider options, and + the ambient proxy settings unless FLOCKS_HTTP_TRUST_ENV or the options' + ``trust_env`` turn them off. *tls_overrides* are the TLS settings a + settings form has not saved yet; each one replaces the stored value of + that setting only, so a form that sends just the switch keeps the stored + CA certificate. """ - settings = options or (sdk_settings if isinstance(sdk_settings, dict) else {}) + settings = dict(options or (sdk_settings if isinstance(sdk_settings, dict) else {})) + overrides = {key: value for key, value in (tls_overrides or {}).items() if key in TLS_OPTION_KEYS} + if VERIFY_SSL_KEY in overrides: + settings.pop(LEGACY_VERIFY_SSL_KEY, None) # the older spelling must not outvote the new value + settings.update(overrides) trust_env = _coerce_bool(os.getenv("FLOCKS_HTTP_TRUST_ENV"), True) if "trust_env" in settings: trust_env = _coerce_bool(settings.get("trust_env"), trust_env) - return {"verify": resolve_verify_ssl(settings, default=True), "trust_env": trust_env} + try: + verify = httpx_verify(settings, trust_env=trust_env) + except CACertError as error: + raise DiscoveryError("invalid_ca_cert", str(error)) from error + return {"verify": verify, "trust_env": trust_env} async def _resolve_connection( - provider_id: str, raw: dict, catalog: dict, api_key: str | None, base_url: str | None -) -> tuple[str | None, str | None, dict[str, bool]]: + provider_id: str, + raw: dict, + catalog: dict, + api_key: str | None, + base_url: str | None, + tls_overrides: dict | None = None, +) -> tuple[str | None, str | None, dict[str, Any]]: resolved_options: dict = {} try: config = await Config.get() @@ -253,7 +279,9 @@ async def _resolve_connection( ) if provider_id in {"openai-compatible", "cherry"} and base_url is None and not (stored_url or env_url): effective_url = None - transport = _transport_settings(resolved_options or _dict(raw_options), getattr(sdk_config, "custom_settings", None)) + transport = _transport_settings( + resolved_options or _dict(raw_options), getattr(sdk_config, "custom_settings", None), tls_overrides + ) return effective_key, effective_url, transport @@ -328,6 +356,10 @@ async def _validate_resolved_addresses(url: str) -> None: # The HTTP transport owns connection error reporting; a test or custom # transport may also resolve names independently of the system resolver. return + except UnicodeError: + # The resolver encodes names with IDNA: an empty label ("a..b") or one + # longer than 63 characters is not a host name, not a server failure. + raise DiscoveryError("invalid_base_url", "The provider base URL does not name a valid host.") from None for address in addresses: target = ipaddress.ip_address(address[4][0].split("%", 1)[0]) if getattr(target, "ipv4_mapped", None): @@ -534,9 +566,17 @@ def _catalog_result(provider_id: str, raw: dict, protocol: str | None, already_a async def discover_models( - provider_id: str, *, api_key: str | None = None, base_url: str | None = None + provider_id: str, + *, + api_key: str | None = None, + base_url: str | None = None, + tls_overrides: dict | None = None, ) -> dict[str, Any]: - """Fetch models without saving configuration or mutating a provider client.""" + """Fetch models without saving configuration or mutating a provider client. + + *tls_overrides* (``verify_ssl`` / ``ca_cert``) stand in for the stored TLS + settings, so a form can check a gateway before its settings are saved. + """ raw = ConfigWriter.get_provider_raw(provider_id) or {} catalog = get_raw_catalog().get(provider_id, {}) protocol = _protocol(provider_id, raw, catalog) @@ -547,7 +587,9 @@ async def discover_models( result = _catalog_result(provider_id, raw, protocol, already_added) else: async with asyncio.timeout(DISCOVERY_TIMEOUT_SECONDS): - key, url, transport = await _resolve_connection(provider_id, raw, catalog, api_key, base_url) + key, url, transport = await _resolve_connection( + provider_id, raw, catalog, api_key, base_url, tls_overrides + ) url = _endpoint(_validate_base_url(url), protocol) if not key and not _no_auth_allowed(provider_id, raw, protocol): raise DiscoveryError("missing_credentials", "Configure credentials before fetching models.") @@ -673,12 +715,13 @@ async def discover_models( "truncated": False, "models": [], } - except httpx.TransportError: + except httpx.TransportError as error: + tls_code = classify_tls_error(error) result = { "source": "none", "status": "error", - "code": "connection_error", - "message": "Could not connect to the provider model listing endpoint.", + "code": tls_code or "connection_error", + "message": TLS_ERROR_HINTS[tls_code] if tls_code else "Could not connect to the provider model listing endpoint.", "truncated": False, "models": [], } diff --git a/flocks/provider/provider.py b/flocks/provider/provider.py index 1e8cfa078..d62afe014 100644 --- a/flocks/provider/provider.py +++ b/flocks/provider/provider.py @@ -201,6 +201,10 @@ class ChatResponse(BaseModel): usage: Dict[str, Any] tool_calls: Optional[List[Dict[str, Any]]] = None reasoning: Optional[str] = None + # Where the reasoning came from and its structured form, so a reply replayed + # into a stream keeps what the next tool round must send back. + reasoning_source: Optional[str] = None + reasoning_details: Optional[List[Dict[str, Any]]] = None class ToolCallInfo(BaseModel): @@ -1198,6 +1202,11 @@ class BaseProvider: # in get_model_definitions(). Leave empty for providers without a catalog entry. CATALOG_ID: str = "" + # True when the provider's HTTP client follows the ``verify_ssl`` and + # ``ca_cert`` options (flocks.provider.tls); the model settings page offers + # those settings only then. + SUPPORTS_TLS_SETTINGS: bool = False + # Per-event-loop SDK client cache; see LoopBoundClientSlot. _client = LoopBoundClientSlot() diff --git a/flocks/provider/sdk/anthropic.py b/flocks/provider/sdk/anthropic.py index fd5b80259..8cd6703b7 100644 --- a/flocks/provider/sdk/anthropic.py +++ b/flocks/provider/sdk/anthropic.py @@ -16,6 +16,7 @@ StreamChunk, ) from flocks.provider.sdk.openai_base import build_reasoning_metadata +from flocks.provider.tls import has_custom_tls, httpx_verify from flocks.provider.token_usage import normalize_usage from flocks.utils.log import Log @@ -38,6 +39,7 @@ class AnthropicProvider(BaseProvider): """Anthropic (Claude) provider with tool support.""" CATALOG_ID = "anthropic" + SUPPORTS_TLS_SETTINGS = True _INTERLEAVED_THINKING_BETA = "interleaved-thinking-2025-05-14" _FINE_GRAINED_TOOL_STREAMING_BETA = "fine-grained-tool-streaming-2025-05-14" _THINKING_BLOCK_TYPES = frozenset({"thinking", "redacted_thinking"}) @@ -67,15 +69,23 @@ def _get_client(self): # Support custom base URL from config base_url = self._config.base_url if self._config else None - + client_kwargs: Dict[str, Any] = {"api_key": api_key} + # verify_ssl / ca_cert from the provider options; without them + # the SDK keeps building its own default client. + settings = getattr(self._config, "custom_settings", None) or {} + if has_custom_tls(settings): + from anthropic import DefaultAsyncHttpxClient + + client_kwargs["http_client"] = DefaultAsyncHttpxClient(verify=httpx_verify(settings)) + if base_url: log.info("anthropic.client.init", { "base_url": base_url, "has_api_key": bool(api_key), + "custom_tls": "http_client" in client_kwargs, }) - self._client = AsyncAnthropic(api_key=api_key, base_url=base_url) - else: - self._client = AsyncAnthropic(api_key=api_key) + client_kwargs["base_url"] = base_url + self._client = AsyncAnthropic(**client_kwargs) except ImportError: raise ImportError("anthropic package not installed. Install with: pip install anthropic") return self._client diff --git a/flocks/provider/sdk/azure.py b/flocks/provider/sdk/azure.py index cbc3d6d13..5ca746908 100644 --- a/flocks/provider/sdk/azure.py +++ b/flocks/provider/sdk/azure.py @@ -14,6 +14,7 @@ StreamChunk, ) from flocks.provider.sdk.openai_base import format_openai_messages +from flocks.provider.tls import has_custom_tls, httpx_verify from flocks.utils.log import Log log = Log.create(service="provider.azure") @@ -22,6 +23,8 @@ class AzureProvider(BaseProvider): """Azure OpenAI provider""" + SUPPORTS_TLS_SETTINGS = True + def __init__(self): super().__init__(provider_id="azure", name="Azure OpenAI") self._api_key = os.getenv("AZURE_OPENAI_API_KEY") @@ -56,13 +59,23 @@ def _get_client(self): "AZURE_OPENAI_API_VERSION", "2025-04-01-preview" ) + client_kwargs: Dict[str, Any] = {} + # verify_ssl / ca_cert from the provider options; without them + # the SDK keeps building its own default client. + settings = (self._config.custom_settings if self._config else None) or {} + if has_custom_tls(settings): + from openai import DefaultAsyncHttpxClient + + client_kwargs["http_client"] = DefaultAsyncHttpxClient(verify=httpx_verify(settings)) + # Create client self._client = AsyncAzureOpenAI( api_key=api_key, azure_endpoint=endpoint, api_version=api_version, + **client_kwargs, ) - self.log.info("azure.client.created", {"endpoint": endpoint}) + self.log.info("azure.client.created", {"endpoint": endpoint, "custom_tls": bool(client_kwargs)}) except ImportError: raise ImportError("openai package not installed. Install with: pip install openai") diff --git a/flocks/provider/sdk/openai.py b/flocks/provider/sdk/openai.py index d7f514e48..367bf5658 100644 --- a/flocks/provider/sdk/openai.py +++ b/flocks/provider/sdk/openai.py @@ -30,6 +30,7 @@ raise_if_response_body_unsafe, resolve_verify_ssl, ) +from flocks.provider.tls import httpx_verify from flocks.utils.log import Log log = Log.create(service="provider.openai") @@ -58,6 +59,7 @@ class OpenAIProvider(BaseProvider): """OpenAI (GPT) provider with tool support.""" CATALOG_ID = "openai" + SUPPORTS_TLS_SETTINGS = True def __init__(self): super().__init__(provider_id="openai", name="OpenAI") @@ -100,7 +102,7 @@ def _get_client(self): verify_ssl = resolve_verify_ssl(cfg_settings, default=True) http_client = create_openai_http_client( trust_env=trust_env, - verify=verify_ssl, + verify=httpx_verify(cfg_settings, trust_env=trust_env), timeout=DEFAULT_HTTP_TIMEOUT, custom_settings=cfg_settings, ) diff --git a/flocks/provider/sdk/openai_base.py b/flocks/provider/sdk/openai_base.py index 336fedd8f..1e39a0aa4 100644 --- a/flocks/provider/sdk/openai_base.py +++ b/flocks/provider/sdk/openai_base.py @@ -8,10 +8,14 @@ """ import os -from typing import Any, AsyncIterator, Dict, List, Optional +import ssl +from typing import Any, AsyncIterator, Dict, List, Optional, Union import httpx +# ``_coerce_bool`` and ``resolve_verify_ssl`` keep being imported from here. +from flocks.provider.tls import coerce_bool as _coerce_bool +from flocks.provider.tls import httpx_verify, resolve_verify_ssl from flocks.provider.provider import ( BaseProvider, ChatMessage, @@ -132,11 +136,15 @@ async def _limit(response: httpx.Response) -> None: def create_openai_http_client( *, trust_env: bool, - verify: bool, + verify: Union[bool, ssl.SSLContext], timeout: httpx.Timeout = DEFAULT_HTTP_TIMEOUT, custom_settings: Any = None, ) -> httpx.AsyncClient: - """Build the shared OpenAI-compatible client with an ingress size cap.""" + """Build the shared OpenAI-compatible client with an ingress size cap. + + *verify* is what :func:`flocks.provider.tls.httpx_verify` gives for the + provider's options. + """ max_response_bytes = resolve_max_response_bytes(custom_settings) return httpx.AsyncClient( trust_env=trust_env, @@ -406,29 +414,6 @@ def format_openai_messages( return formatted -def _coerce_bool(value: Any, default: bool) -> bool: - """Coerce loosely-typed config values to bool.""" - if isinstance(value, bool): - return value - if isinstance(value, (int, float)): - return bool(value) - if isinstance(value, str): - return value.strip().lower() in {"1", "true", "yes", "on"} - return default - - -def resolve_verify_ssl(custom_settings: Any, default: bool = True) -> bool: - """Resolve the SSL verification flag from provider custom settings.""" - if not isinstance(custom_settings, dict): - return default - - if "verify_ssl" in custom_settings: - return _coerce_bool(custom_settings.get("verify_ssl"), default) - if "ssl_verify" in custom_settings: - return _coerce_bool(custom_settings.get("ssl_verify"), default) - return default - - def _normalize_stream_usage(raw_usage: Any, *, response_id: Any = None) -> Optional[Dict[str, Any]]: """Normalize provider usage objects to the shared usage schema. @@ -855,6 +840,87 @@ def extract_reasoning_details(delta) -> Optional[List[Dict[str, Any]]]: return None +def message_tool_call_chunks(message: Any) -> Optional[List[Dict[str, Any]]]: + """A non-streaming message's tool calls, shaped like streamed tool-call deltas.""" + calls: List[Dict[str, Any]] = [] + for call in getattr(message, "tool_calls", None) or []: + function = getattr(call, "function", None) + name = getattr(function, "name", None) + if not isinstance(name, str) or not name: + continue + arguments = getattr(function, "arguments", None) + call_id = getattr(call, "id", None) + calls.append({ + "index": len(calls), + # The tool-call accumulator mints an id when the provider gave none. + "id": call_id if isinstance(call_id, str) and call_id else None, + "type": "function", + # Kept as sent: an empty or partial string may be a cut-off call. + "function": {"name": name, "arguments": arguments if isinstance(arguments, str) else ""}, + }) + return calls or None + + +def message_reasoning( + message: Any, +) -> tuple[Optional[str], Optional[str], Optional[List[Dict[str, Any]]]]: + """Reasoning text, the field it came from, and structured reasoning details.""" + reasoning, source = extract_reasoning_content_with_source(message) + if not isinstance(reasoning, str) or not reasoning: + reasoning, source = None, None + details = [item for item in extract_reasoning_details(message) or [] if isinstance(item, dict)] + return reasoning, source if isinstance(source, str) else None, details or None + + +def chat_fallback_tool_call_chunks( + response: ChatResponse, + *, + provider_id: str, + model_id: str, +) -> List[StreamChunk]: + """Replay a non-streaming answer that made tool calls as stream chunks. + + The empty-stream fallback kept only ``content``: an answer made of tool + calls alone (content null) counted as empty, and the request was then sent + again without its tools, so the model reported it had none. + """ + chunks: List[StreamChunk] = [] + # As the streaming path does: details alone (e.g. encrypted reasoning) still + # make a reasoning chunk, since the next tool round has to send them back. + if response.reasoning is not None or response.reasoning_details: + chunks.append(StreamChunk( + event_type="reasoning", + reasoning=response.reasoning or "", + finish_reason=None, + metadata=build_reasoning_metadata( + provider_id=provider_id, + model_id=model_id, + reasoning_content=response.reasoning, + reasoning_source=response.reasoning_source, + reasoning_details=response.reasoning_details, + ), + )) + if response.content: + chunks.append(StreamChunk(delta=response.content, finish_reason=None)) + finish_reason = response.finish_reason or "tool_calls" + truncated = finish_reason in ("length", "max_tokens") + tool_calls = [] + for call in response.tool_calls or []: + function = dict(call.get("function") or {}) + if not truncated and not function.get("arguments"): + # A finished answer with no arguments is a call without parameters. + # A cut-off one stays empty so the accumulator refuses to run it. + function["arguments"] = "{}" + tool_calls.append({**call, "function": function}) + chunks.append(StreamChunk( + delta="", + finish_reason=finish_reason, + tool_calls=tool_calls, + usage=response.usage or None, + )) + return chunks + + def build_reasoning_metadata( *, provider_id: str, @@ -922,6 +988,7 @@ class OpenAIBaseProvider(BaseProvider): ALLOW_NO_API_KEY: bool = False PREFER_MAX_COMPLETION_TOKENS: bool = False NO_API_KEY_PLACEHOLDER: str = "not-needed" + SUPPORTS_TLS_SETTINGS = True def __init__(self, provider_id: str, name: str): super().__init__(provider_id=provider_id, name=name) @@ -987,7 +1054,7 @@ def _get_client(self): timeout = DEFAULT_HTTP_TIMEOUT http_client = create_openai_http_client( trust_env=trust_env, - verify=verify_ssl, + verify=httpx_verify(custom_settings, trust_env=trust_env), timeout=timeout, custom_settings=custom_settings, ) @@ -1115,12 +1182,17 @@ async def chat( f"{self.name} API returned choice with null message. " f"model={model_id}, detail={err_detail}" ) + reasoning, reasoning_source, reasoning_details = message_reasoning(msg) return ChatResponse( id=response.id, model=response.model, content=msg.content or "", finish_reason=choice.finish_reason or "stop", usage=normalize_usage(response.usage, response_id=response.id) or {}, + tool_calls=message_tool_call_chunks(msg), + reasoning=reasoning, + reasoning_source=reasoning_source, + reasoning_details=reasoning_details, ) async def chat_stream( @@ -1406,6 +1478,16 @@ async def chat_stream( fallback_error: Optional[Exception] = None try: fallback = await self.chat(model_id, messages, **kwargs) + if fallback.tool_calls: + log.warn("openai_base.stream.empty_response_recovered_tool_calls", { + "model": model_id, + "tool_calls": len(fallback.tool_calls), + }) + for chunk in chat_fallback_tool_call_chunks( + fallback, provider_id=self.id, model_id=model_id, + ): + yield chunk + return fallback_content = fallback.content or "" if fallback_content: yield StreamChunk( @@ -1417,30 +1499,12 @@ async def chat_stream( except Exception as exc: fallback_error = exc - if kwargs.get("tools"): - log.warn("openai_base.stream.retry_without_tools", { - "model": model_id, - "reason": str(fallback_error) if fallback_error else "empty_fallback_content", - }) - no_tool_kwargs = dict(kwargs) - no_tool_kwargs.pop("tools", None) - try: - fallback = await self.chat(model_id, messages, **no_tool_kwargs) - fallback_content = fallback.content or "" - if fallback_content: - yield StreamChunk( - delta=fallback_content, - finish_reason=fallback.finish_reason or "stop", - usage=fallback.usage or None, - ) - return - except Exception as exc: - if fallback_error is None: - fallback_error = exc - + # Not retried without the tools: a model asked to act with none + # writes its calls as text or says it has no tools. The empty + # response error is retryable, so the turn is retried with them. if fallback_error: raise fallback_error raise ValueError( f"{self.name} API returned an empty streaming response and empty fallback response. " - f"model={model_id}" + f"model={model_id}, tools_declared={bool(kwargs.get('tools'))}" ) diff --git a/flocks/provider/sdk/openai_compatible.py b/flocks/provider/sdk/openai_compatible.py index e77876ee5..affb2bab2 100644 --- a/flocks/provider/sdk/openai_compatible.py +++ b/flocks/provider/sdk/openai_compatible.py @@ -26,6 +26,7 @@ ThinkTagExtractor, apply_openai_token_limit, build_reasoning_metadata, + chat_fallback_tool_call_chunks, create_openai_http_client, create_chat_completion_with_fallbacks, _coerce_bool, @@ -35,9 +36,12 @@ extract_reasoning_details, format_openai_content, format_openai_messages, + message_reasoning, + message_tool_call_chunks, resolve_openai_token_limit, resolve_verify_ssl, ) +from flocks.provider.tls import httpx_verify from flocks.utils.log import Log log = Log.create(service="provider.openai_compatible") @@ -46,6 +50,7 @@ class OpenAICompatibleProvider(BaseProvider): """OpenAI Compatible API provider""" + SUPPORTS_TLS_SETTINGS = True _MINIMAX_EMPTY_RESPONSE_RETRY_DELAY_SECONDS = 3 def __init__(self): @@ -109,7 +114,7 @@ def _get_client(self): trust_env = _coerce_bool(custom_settings.get("trust_env"), trust_env) http_client = create_openai_http_client( trust_env=trust_env, - verify=verify_ssl, + verify=httpx_verify(custom_settings, trust_env=trust_env), timeout=DEFAULT_HTTP_TIMEOUT, custom_settings=custom_settings, ) @@ -230,18 +235,26 @@ async def chat( ) # Format response + if not response.choices: + # Worded like openai_base so the session retries it as transient. + raise ValueError(f"OpenAI-compatible API returned empty choices. model={model_id}") choice = response.choices[0] msg = getattr(choice, "message", None) if msg is None: raise ValueError( f"OpenAI-compatible API returned choice with null message. model={model_id}" ) + reasoning, reasoning_source, reasoning_details = message_reasoning(msg) return ChatResponse( id=response.id, model=response.model, content=msg.content or "", finish_reason=choice.finish_reason, usage=_normalize_stream_usage(response.usage, response_id=response.id) or {}, + tool_calls=message_tool_call_chunks(msg), + reasoning=reasoning, + reasoning_source=reasoning_source, + reasoning_details=reasoning_details, ) async def chat_stream( @@ -507,6 +520,16 @@ async def chat_stream( has_tools=bool(tools), ) fallback = await self.chat(model_id, messages, **kwargs) + if fallback.tool_calls: + self.log.warn("openai_compatible.stream.empty_response_recovered_tool_calls", { + "model": model_id, + "tool_calls": len(fallback.tool_calls), + }) + for chunk in chat_fallback_tool_call_chunks( + fallback, provider_id=self.id, model_id=model_id, + ): + yield chunk + return fallback_content = fallback.content or "" self.log.debug("openai_compatible.minimax_empty_response_fallback_result", { "model": model_id, @@ -553,7 +576,11 @@ async def chat_stream( "error": str(exc), }) - if tools: + # Only MiniMax keeps its tool-less last resort. Other models asked to + # act with no tools write their calls as text or say they have none; + # the empty-response error below is retryable, so the turn is + # retried with its tools instead. + if tools and minimax_empty_response_target: self.log.warn("openai_compatible.stream.retry_without_tools", { "model": model_id, "reason": str(fallback_error) if fallback_error else "empty_fallback_content", @@ -630,5 +657,5 @@ async def chat_stream( ) raise ValueError( f"OpenAI-compatible API returned an empty streaming response and empty fallback response. " - f"model={model_id}" + f"model={model_id}, tools_declared={bool(tools)}" ) diff --git a/flocks/provider/sdk/openrouter.py b/flocks/provider/sdk/openrouter.py index 64a4e2599..ca058e939 100644 --- a/flocks/provider/sdk/openrouter.py +++ b/flocks/provider/sdk/openrouter.py @@ -5,13 +5,14 @@ Multi-model routing provider """ -from typing import List +from typing import Any, Dict, List from flocks.provider.provider import ( ModelInfo, ModelCapabilities, ) from flocks.provider.sdk.openai_base import OpenAIBaseProvider +from flocks.provider.tls import has_custom_tls, httpx_verify class OpenRouterProvider(OpenAIBaseProvider): @@ -42,6 +43,15 @@ def _get_client(self): else self._base_url ) + client_kwargs: Dict[str, Any] = {} + # verify_ssl / ca_cert from the provider options (SUPPORTS_TLS_SETTINGS + # is inherited); without them the SDK keeps its own default client. + settings = getattr(self._config, "custom_settings", None) or {} + if has_custom_tls(settings): + from openai import DefaultAsyncHttpxClient + + client_kwargs["http_client"] = DefaultAsyncHttpxClient(verify=httpx_verify(settings)) + self._client = AsyncOpenAI( api_key=api_key, base_url=base_url, @@ -49,6 +59,7 @@ def _get_client(self): "HTTP-Referer": "https://opencode.ai/", "X-Title": "opencode", }, + **client_kwargs, ) return self._client diff --git a/flocks/provider/tls.py b/flocks/provider/tls.py new file mode 100644 index 000000000..4b102b0eb --- /dev/null +++ b/flocks/provider/tls.py @@ -0,0 +1,274 @@ +""" +TLS settings of the HTTP clients that talk to LLM providers. + +A provider's options in flocks.json (``provider..options``) may hold: + +``verify_ssl`` (bool, default true; ``ssl_verify`` is the older spelling) + False turns off the certificate and host name checks for that provider. + It also lets the client speak the older handshakes internal gateways often + still do: RSA key exchange and CBC-SHA1 suites, TLS 1.0 and 1.1, servers + without secure renegotiation. The packaged Python (python-build-standalone) + keeps CPython's own TLS defaults, stricter than the RHEL system Python that + older installs ran on, so such a gateway would fail the handshake with the + checks off unless the handshake is relaxed too. + +``ca_cert`` (string) + A CA certificate in PEM, or the path of a PEM file or of a hashed + certificate directory on the server. It is trusted besides the default + bundle and the checks stay on. Not used while ``verify_ssl`` is false. + +``httpx_verify()`` turns them into the ``verify`` argument of an httpx client. +With neither set it returns ``True``, which leaves the client exactly as httpx +builds it on its own. +""" + +from __future__ import annotations + +import os +import ssl +from typing import Any, Iterable, Mapping, Optional, Union + +VERIFY_SSL_KEY = "verify_ssl" +LEGACY_VERIFY_SSL_KEY = "ssl_verify" +CA_CERT_KEY = "ca_cert" +TLS_OPTION_KEYS = (VERIFY_SSL_KEY, LEGACY_VERIFY_SSL_KEY, CA_CERT_KEY) + +# PEM text pasted into the settings; a bundle of a few hundred CAs fits. +MAX_CA_CERT_CHARS = 1024 * 1024 + +# OpenSSL's own default list at security level 0: RSA key exchange, CBC and +# SHA-1 suites, small keys and TLS 1.0 / 1.1 signatures are allowed again. +_COMPAT_CIPHERS = "DEFAULT:@SECLEVEL=0" + +TLS_CERTIFICATE_FAILED = "tls_certificate_failed" +TLS_HANDSHAKE_FAILED = "tls_handshake_failed" + + +class CACertError(ValueError): + """A ``ca_cert`` value that cannot be loaded; the message is shown to the user.""" + + +def coerce_bool(value: Any, default: bool) -> bool: + """Coerce loosely-typed config values to bool.""" + if isinstance(value, bool): + return value + if isinstance(value, (int, float)): + return bool(value) + if isinstance(value, str): + return value.strip().lower() in {"1", "true", "yes", "on"} + return default + + +def resolve_verify_ssl(settings: Any, default: bool = True) -> bool: + """Whether certificates are checked, from provider options (``verify_ssl`` or ``ssl_verify``).""" + if not isinstance(settings, Mapping): + return default + if VERIFY_SSL_KEY in settings: + return coerce_bool(settings.get(VERIFY_SSL_KEY), default) + if LEGACY_VERIFY_SSL_KEY in settings: + return coerce_bool(settings.get(LEGACY_VERIFY_SSL_KEY), default) + return default + + +def resolve_ca_cert(settings: Any) -> Optional[str]: + """The configured ``ca_cert`` (PEM text or a path), or ``None``.""" + if not isinstance(settings, Mapping): + return None + value = settings.get(CA_CERT_KEY) + if not isinstance(value, str): + return None + value = value.strip() + return value or None + + +def has_custom_tls(settings: Any) -> bool: + """Whether the options change anything from the default checks.""" + return not resolve_verify_ssl(settings) or resolve_ca_cert(settings) is not None + + +def is_pem_text(value: str) -> bool: + return "-----BEGIN" in value + + +def _default_verify_locations(trust_env: bool) -> dict: + """The trust httpx gives ``verify=True``: SSL_CERT_FILE / SSL_CERT_DIR, else certifi.""" + if trust_env and os.environ.get("SSL_CERT_FILE"): + return {"cafile": os.environ["SSL_CERT_FILE"]} + if trust_env and os.environ.get("SSL_CERT_DIR"): + return {"capath": os.environ["SSL_CERT_DIR"]} + import certifi + + return {"cafile": certifi.where()} + + +def _load_ca(context: ssl.SSLContext, ca_cert: str) -> None: + if "PRIVATE KEY-----" in ca_cert: + raise CACertError("CA 证书里只填证书(-----BEGIN CERTIFICATE-----),不要粘贴私钥。") + if is_pem_text(ca_cert): + if len(ca_cert) > MAX_CA_CERT_CHARS: + raise CACertError("CA 证书内容太长,请只保留需要信任的 CA 证书。") + try: + context.load_verify_locations(cadata=ca_cert) + except (ssl.SSLError, ValueError) as exc: + raise CACertError(f"CA 证书无法解析,请粘贴完整的 PEM 格式证书:{exc}") from exc + return + path = os.path.expanduser(ca_cert) + if not os.path.isabs(path): + raise CACertError("CA 证书路径要写服务器上的绝对路径,或者直接粘贴 PEM 格式的证书内容。") + try: + if os.path.isdir(path): + context.load_verify_locations(capath=path) + else: + context.load_verify_locations(cafile=path) + except FileNotFoundError as exc: + raise CACertError(f"找不到 CA 证书文件:{path}") from exc + except PermissionError as exc: + raise CACertError(f"没有权限读取 CA 证书文件:{path}") from exc + except (OSError, ssl.SSLError, ValueError) as exc: + raise CACertError(f"CA 证书文件无法加载:{path}({exc})") from exc + + +def validate_ca_cert(value: Optional[str]) -> Optional[str]: + """Check that *value* loads at least one certificate; returns it stripped, or ``None`` when empty.""" + if value is None: + return None + value = value.strip() + if not value: + return None + probe = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + _load_ca(probe, value) + # A hashed directory is read lazily, certificate by certificate, so its + # count says nothing until a handshake looks a certificate up. + is_directory = not is_pem_text(value) and os.path.isdir(os.path.expanduser(value)) + if not is_directory and not probe.cert_store_stats().get("x509"): + raise CACertError("CA 证书里没有找到证书,请粘贴 -----BEGIN CERTIFICATE----- 开头的完整内容。") + return value + + +def verifying_context(ca_cert: str, *, trust_env: bool = True) -> ssl.SSLContext: + """Default trust plus *ca_cert*; certificate and host name checks stay on.""" + context = ssl.create_default_context(**_default_verify_locations(trust_env)) + _load_ca(context, ca_cert) + # The pasted certificate may be an intermediate, or the gateway's own + # self-signed certificate: let a chain end at any certificate trusted here. + partial_chain = getattr(ssl, "VERIFY_X509_PARTIAL_CHAIN", 0) + if partial_chain: + context.verify_flags |= partial_chain + return context + + +def compat_context() -> ssl.SSLContext: + """No certificate checks, and the older handshakes accepted (see the module docstring).""" + context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + context.check_hostname = False + context.verify_mode = ssl.CERT_NONE + try: + context.minimum_version = ssl.TLSVersion.MINIMUM_SUPPORTED + except (ValueError, ssl.SSLError): # pragma: no cover - build without the floor control + pass + try: + context.set_ciphers(_COMPAT_CIPHERS) + except ssl.SSLError: # pragma: no cover - OpenSSL without security levels + pass + context.options |= getattr(ssl, "OP_LEGACY_SERVER_CONNECT", 0) + return context + + +def httpx_verify(settings: Any, *, trust_env: bool = True) -> Union[bool, ssl.SSLContext]: + """The ``verify`` argument for an httpx client built from provider options. + + Raises :class:`CACertError` when ``ca_cert`` cannot be loaded, so a wrong + certificate fails loudly instead of quietly checking against the default + bundle only. + """ + if not resolve_verify_ssl(settings): + return compat_context() + ca_cert = resolve_ca_cert(settings) + if ca_cert is None: + return True + return verifying_context(ca_cert, trust_env=trust_env) + + +def _chain(exc: BaseException) -> Iterable[BaseException]: + seen = set() + current: Optional[BaseException] = exc + while current is not None and id(current) not in seen and len(seen) < 16: + seen.add(id(current)) + yield current + current = current.__cause__ or current.__context__ + + +_HANDSHAKE_MARKERS = ( + "HANDSHAKE_FAILURE", + "ALERT_PROTOCOL_VERSION", + "UNSUPPORTED_PROTOCOL", + "WRONG_VERSION_NUMBER", + "NO_PROTOCOLS_AVAILABLE", + "NO_CIPHERS_AVAILABLE", + "NO_SHARED_CIPHER", + "UNSAFE_LEGACY_RENEGOTIATION", + "DH_KEY_TOO_SMALL", + "EE_KEY_TOO_SMALL", + "CA_MD_TOO_WEAK", + "UNEXPECTED_EOF_WHILE_READING", +) + + +def classify_tls_error(exc: BaseException) -> Optional[str]: + """``tls_certificate_failed`` / ``tls_handshake_failed`` when TLS caused *exc*, else ``None``. + + Clients wrap the ``ssl`` error (httpcore -> httpx -> the provider SDK), so + the whole cause chain is read, and the message as well, since some + wrappers keep only the text. + """ + for error in _chain(exc): + if isinstance(error, CACertError): + return TLS_CERTIFICATE_FAILED + if isinstance(error, ssl.SSLCertVerificationError): + return TLS_CERTIFICATE_FAILED + text = str(error) + if "CERTIFICATE_VERIFY_FAILED" in text: + return TLS_CERTIFICATE_FAILED + if isinstance(error, ssl.SSLError) or any(marker in text for marker in _HANDSHAKE_MARKERS): + return TLS_HANDSHAKE_FAILED + return None + + +TLS_ERROR_HINTS = { + TLS_CERTIFICATE_FAILED: ( + "SSL 证书校验失败:网关用的是自签名或内部 CA 签发的证书。" + "可以在模型服务设置里填写 CA 证书,或关闭「校验 SSL 证书」。" + ), + TLS_HANDSHAKE_FAILED: ( + "TLS 握手失败:网关的 TLS 版本或加密套件较旧,或地址的 http/https 写错了。" + "确认地址无误后,可以在模型服务设置里关闭「校验 SSL 证书」,同时会兼容旧版 TLS。" + ), +} + + +def tls_error_hint(exc: BaseException) -> Optional[str]: + """A message telling the user what to change, when TLS caused *exc*.""" + code = classify_tls_error(exc) + return TLS_ERROR_HINTS.get(code) if code else None + + +__all__ = [ + "CA_CERT_KEY", + "CACertError", + "LEGACY_VERIFY_SSL_KEY", + "TLS_CERTIFICATE_FAILED", + "TLS_ERROR_HINTS", + "TLS_HANDSHAKE_FAILED", + "TLS_OPTION_KEYS", + "VERIFY_SSL_KEY", + "classify_tls_error", + "coerce_bool", + "compat_context", + "has_custom_tls", + "httpx_verify", + "resolve_ca_cert", + "resolve_verify_ssl", + "tls_error_hint", + "validate_ca_cert", + "verifying_context", +] diff --git a/flocks/server/app.py b/flocks/server/app.py index 5646bc053..663328792 100644 --- a/flocks/server/app.py +++ b/flocks/server/app.py @@ -845,10 +845,12 @@ def _should_log_request(path: str, status_code: int) -> bool: # ``_FLOCKS_WEBUI_*`` origin inferred from the current CLI launch. # 2. Explicit ``server.cors`` in flocks.json → append user-configured # origins without discarding the runtime ones. -# We deliberately do NOT auto-whitelist wildcard binds such as ``0.0.0.0``: -# matching ``[^/]+:`` would accept every host on that port, effectively -# disabling CORS. Remote deployments that bind to wildcard hosts must keep -# using explicit ``server.cors`` entries or start with a concrete IP/hostname. +# We deliberately do NOT auto-whitelist every host for wildcard binds such as +# ``0.0.0.0`` (the default): matching ``[^/]+:`` would accept every host +# on that port, effectively disabling CORS. A wildcard bind gets this +# machine's loopback origins, as a ``127.0.0.1`` bind does; remote deployments +# that need other origins keep using explicit ``server.cors`` entries or start +# with a concrete IP/hostname. # # Config is read lazily on the first request via # :class:`_DeferredCORSMiddleware` so that importing ``app`` in an async @@ -869,9 +871,12 @@ def _format_host_for_url(host: str) -> str: def _append_origin(origins: list[str], host: str, port: str) -> None: - if not host or not port or host in _WILDCARD_HOSTS: + if not host or not port: return - hosts = sorted(_LOOPBACK_ORIGIN_HOSTS) if host in _LOOPBACK_ORIGIN_HOSTS else [host] + # A wildcard bind serves this machine as well: its loopback origins, never + # "any host on the port". + local = host in _LOOPBACK_ORIGIN_HOSTS or host in _WILDCARD_HOSTS + hosts = sorted(_LOOPBACK_ORIGIN_HOSTS) if local else [host] for candidate_host in hosts: origin = f"http://{_format_host_for_url(candidate_host)}:{port}" if origin not in origins: diff --git a/flocks/server/auth.py b/flocks/server/auth.py index 0a37130e2..2aeab20cb 100644 --- a/flocks/server/auth.py +++ b/flocks/server/auth.py @@ -5,6 +5,7 @@ from __future__ import annotations import hmac +import ipaddress import os import re from collections.abc import Awaitable, Callable, Mapping @@ -168,6 +169,36 @@ def get_request_ip(request: Request) -> Optional[str]: return None +# A request that went through a proxy says so; a browser on this machine +# talking to the service sends none of these. +_PROXY_HEADERS = ("x-forwarded-for", "forwarded", "x-real-ip") + + +def is_local_request(request: HTTPConnection) -> bool: + """Whether the peer is a loopback address, i.e. a browser on this machine. + + The service listens on every interface by default, and until the first + administrator exists anyone who reaches the page could become it; that + first step is kept to this machine. A request carrying a forwarding header + is not local, whoever its peer: a reverse proxy on this machine connects + from loopback (127.0.0.1, ::1, ::ffff:127.0.0.1) for clients elsewhere, + and uvicorn resolves X-Forwarded-For only for the peers it trusts (by + default 127.0.0.1 alone). A proxy that sends no such header cannot be told + from a local browser. A name that is no IP address (the test client's + "testclient") is not local. + """ + if any(request.headers.get(name) is not None for name in _PROXY_HEADERS): + return False + host = request.client.host if request.client else "" + try: + address = ipaddress.ip_address(host or "") + except ValueError: + return False + if isinstance(address, ipaddress.IPv6Address) and address.ipv4_mapped is not None: + address = address.ipv4_mapped + return address.is_loopback + + def get_request_user_agent(request: Request) -> Optional[str]: return request.headers.get("user-agent") diff --git a/flocks/server/routes/auth.py b/flocks/server/routes/auth.py index 55cb30c51..e412407e6 100644 --- a/flocks/server/routes/auth.py +++ b/flocks/server/routes/auth.py @@ -4,6 +4,8 @@ from __future__ import annotations +import ipaddress +import os import threading import time from typing import Any @@ -15,8 +17,10 @@ from flocks.auth.service import AuthService, TEMP_PASSWORD_TTL_HOURS from flocks.console.login import ConsoleLoginService +from flocks.utils.log import Log from flocks.server.auth import ( clear_session_cookie, + is_local_request, require_admin, require_user, set_session_cookie, @@ -24,6 +28,7 @@ ) router = APIRouter() +log = Log.create(service="server.routes.auth") _LOGIN_FAILURE_WINDOW_SECONDS = 5 * 60 _LOGIN_LOCKOUT_SECONDS = 15 * 60 @@ -225,6 +230,13 @@ def _console_return_url(request: Request, value: str) -> str: class BootstrapStatusResponse(BaseModel): bootstrapped: bool + # Whether this browser may create the first administrator: only one on this + # machine may (bootstrap_admin). Others are told to use + # `flocks admin generate-one-time-password` on the machine. + setup_allowed: bool = True + # For those others: where a browser on the machine reaches the service, when + # loopback reaches it at all (_local_setup_url). + local_url: str | None = None class BootstrapAdminRequest(BaseModel): @@ -297,14 +309,69 @@ class ConsoleLoginSessionResponse(BaseModel): updated_at: str | None = None +def _local_setup_url() -> str | None: + """Where a browser on this machine reaches the service: loopback in the + family it listens on (``::`` takes no IPv4), from what ``flocks serve`` was + started with. None when loopback does not reach it (it listens on one + interface's address) or the address is unknown.""" + port = os.environ.get("_FLOCKS_SERVER_PORT", "").strip() + if not port.isdigit(): + return None + host = os.environ.get("_FLOCKS_SERVER_HOST", "").strip().strip("[]") + if host in {"0.0.0.0", "localhost"}: + return f"http://127.0.0.1:{port}" + try: + address = ipaddress.ip_address(host) + except ValueError: + return None + if address == ipaddress.ip_address("::"): + return f"http://[::1]:{port}" + if address.is_loopback: + # Bound to one loopback address (127.0.0.2 too): that one. + return f"http://{address}:{port}" if address.version == 4 else f"http://[{address}]:{port}" + return None + + +def _remote_bootstrap_refused() -> str: + local_url = _local_setup_url() + browser = f"在这台机器的浏览器里打开 {local_url},或者" if local_url else "" + return ( + "为了安全,第一个管理员只能在运行 Flocks 的这台机器上创建:" + f"{browser}在这台机器上执行 flocks admin generate-one-time-password," + "再用 admin 和输出的一次性密码登录" + ) + + +async def _adopt_legacy_sessions(admin_user_id: str) -> None: + """Sessions from before the first account go to the first administrator. + + The server does it at startup and the setup page right after creating the + administrator; one created by ``flocks admin generate-one-time-password`` + while the server runs (no account at startup) gets them at its first + sign-in. A marker makes it a no-op once done; it never stands in the way of + signing in. + """ + try: + await AuthService.migrate_legacy_sessions_to_admin(admin_user_id) + except Exception as exc: + log.warn("auth.login.adopt_legacy_sessions_failed", {"error": str(exc)}) + + @router.get("/bootstrap-status", response_model=BootstrapStatusResponse, summary="获取本地账号初始化状态") -async def bootstrap_status() -> BootstrapStatusResponse: - status_obj = await AuthService.get_bootstrap_status() +async def bootstrap_status(request: Request) -> BootstrapStatusResponse: + status_obj = dict(await AuthService.get_bootstrap_status()) + bootstrapped = bool(status_obj.get("bootstrapped")) + status_obj["setup_allowed"] = not bootstrapped and is_local_request(request) + status_obj["local_url"] = None if bootstrapped or status_obj["setup_allowed"] else _local_setup_url() return BootstrapStatusResponse(**status_obj) @router.post("/bootstrap-admin", response_model=MeResponse, summary="初始化管理员账号") async def bootstrap_admin(payload: BootstrapAdminRequest, response: Response, request: Request) -> MeResponse: + # The service listens on every interface by default: until an administrator + # exists, whoever reaches the page first would become it. + if not is_local_request(request): + raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=_remote_bootstrap_refused()) try: await AuthService.bootstrap_admin(payload.username, payload.password) user, session_id = await AuthService.login( @@ -353,6 +420,8 @@ async def login(payload: LoginRequest, response: Response, request: Request) -> raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)) from exc _login_rate_limiter.record_success(username=payload.username, ip=ip) + if user.role == "admin": + await _adopt_legacy_sessions(user.id) set_session_cookie(response, session_id, secure=should_use_secure_cookie(request)) await _emit_auth_audit( "account.login", @@ -464,6 +533,25 @@ async def console_login_session(request: Request) -> ConsoleLoginSessionResponse ) +class ConsoleConnectivityResponse(BaseModel): + configured: bool + online: bool + console_host: str = "" + checked_at: str + + +@router.get( + "/console-login/connectivity", + response_model=ConsoleConnectivityResponse, + summary="这台机器现在连不连得上 Console:授权页据此给在线或离线的授权方式", +) +async def console_login_connectivity(request: Request, refresh: bool = False) -> ConsoleConnectivityResponse: + require_admin(request) + from flocks.console.connectivity import console_connectivity + + return ConsoleConnectivityResponse(**await console_connectivity(refresh=refresh)) + + @router.post("/console-login/logout", summary="退出 console 云账号登录") async def console_login_logout(request: Request) -> dict: require_admin(request) diff --git a/flocks/server/routes/channel.py b/flocks/server/routes/channel.py index 4e020ac48..69919126b 100644 --- a/flocks/server/routes/channel.py +++ b/flocks/server/routes/channel.py @@ -447,22 +447,24 @@ class WeixinQrStartRequest(BaseModel): def _resolve_ilink_base_url(raw: Optional[str]) -> str: - """Accept only a public https iLink endpoint. + """Accept a public https iLink endpoint, or one on this machine's loopback. The value is fetched server-side; an arbitrary URL would turn this route - into a probe of the internal network. + into a probe of the internal network. Loopback (a local relay or mock of + iLink) is allowed, over plain http too since it never leaves the host. """ from flocks.channel.builtin.weixin.config import ILINK_BASE_URL + from flocks.tool.web.webfetch import is_loopback_host base_url = (raw or "").strip() if not base_url: return ILINK_BASE_URL parsed = urlparse(base_url) host = (parsed.hostname or "").strip().lower() + if parsed.scheme in ("http", "https") and host and is_loopback_host(host): + return base_url.rstrip("/") if parsed.scheme != "https" or not host: raise HTTPException(status_code=422, detail="baseUrl must be an https URL") - if host == "localhost" or host.endswith(".localhost"): - raise HTTPException(status_code=422, detail="baseUrl must not point at a local address") try: ip = ipaddress.ip_address(host) except ValueError: diff --git a/flocks/server/routes/custom_provider.py b/flocks/server/routes/custom_provider.py index bb5bd7f22..452373b46 100644 --- a/flocks/server/routes/custom_provider.py +++ b/flocks/server/routes/custom_provider.py @@ -32,6 +32,7 @@ ProviderConfig, ) from flocks.provider.sdk.openai_compatible import OpenAICompatibleProvider +from flocks.provider.tls import CA_CERT_KEY, MAX_CA_CERT_CHARS, VERIFY_SSL_KEY, CACertError, validate_ca_cert from flocks.server.auth import require_admin from flocks.server.config_mutation import serialized_config_mutation from flocks.server.routes.provider import _get_inline_provider_api_key @@ -121,6 +122,9 @@ class CreateProviderReq(BaseModel): api_key: Optional[str] = Field(None) description: Optional[str] = Field(None) skip_catalog_bootstrap: bool = False + # TLS settings of the gateway (flocks.provider.tls). + verify_ssl: StrictBool = True + ca_cert: Optional[str] = Field(None, max_length=MAX_CA_CERT_CHARS) class ProviderResp(BaseModel): @@ -209,6 +213,15 @@ async def create_provider(body: CreateProviderReq, _admin: object = Depends(requ supplied_key = (body.api_key or "").strip() or None if supplied_key and not api_key_is_sendable(supplied_key): raise HTTPException(422, UNSENDABLE_API_KEY_MESSAGE) + tls_options: dict[str, Any] = {} + if not body.verify_ssl: + tls_options[VERIFY_SSL_KEY] = False + try: + ca_cert = validate_ca_cert(body.ca_cert) + except CACertError as exc: + raise HTTPException(422, str(exc)) from exc + if ca_cert: + tls_options[CA_CERT_KEY] = ca_cert # Check if already exists if ConfigWriter.get_provider_raw(pid) is not None: @@ -221,6 +234,7 @@ async def create_provider(body: CreateProviderReq, _admin: object = Depends(requ pid, npm="@ai-sdk/openai-compatible", base_url=base_url, + extra_options=tls_options or None, ) config_dict["name"] = body.name if body.description: @@ -242,7 +256,7 @@ async def create_provider(body: CreateProviderReq, _admin: object = Depends(requ log.warning("custom_provider.secret_save_failed", {"id": pid, "error": str(e)}) # Register in runtime - _register_provider(pid, body.name, base_url, supplied_key) + _register_provider(pid, body.name, base_url, supplied_key, custom_settings=tls_options) log.info("custom_provider.created", {"id": pid}) return ProviderResp( @@ -675,7 +689,12 @@ async def _resolve_model_limits( def _register_provider( - pid: str, name: str, base_url: str, api_key: Optional[str] = None + pid: str, + name: str, + base_url: str, + api_key: Optional[str] = None, + *, + custom_settings: Optional[dict[str, Any]] = None, ): """Register a custom provider in the runtime Provider registry.""" if Provider.get(pid): @@ -687,6 +706,7 @@ def _register_provider( provider_id=pid, api_key=api_key or "not-needed", base_url=base_url, + custom_settings=dict(custom_settings or {}), )) Provider.register(p) diff --git a/flocks/server/routes/device.py b/flocks/server/routes/device.py index a3c18b8a1..8fa4340c1 100644 --- a/flocks/server/routes/device.py +++ b/flocks/server/routes/device.py @@ -165,7 +165,8 @@ async def route_create_custom_device_template(body: CustomDeviceTemplateCreate, # which is an admin-level change to what the agent can execute. require_admin(request) try: - return create_custom_device_template(body) + # Writing the template reloads every plugin tool: keep it off the event loop. + return await asyncio.to_thread(create_custom_device_template, body) except FileExistsError as exc: raise HTTPException(status_code=http_status.HTTP_409_CONFLICT, detail=str(exc)) except ValueError as exc: @@ -374,7 +375,8 @@ async def route_update_device_tool( if not tool.info.enabled: from flocks.server.routes.tool import _set_global_tool_enabled - _set_global_tool_enabled(tool, True) + async with ToolRegistry.write_lock(): + _set_global_tool_enabled(tool, True) await delete_device_tool_setting(device_id, tool_name) enabled_device = None else: diff --git a/flocks/server/routes/enterprise_upgrade.py b/flocks/server/routes/enterprise_upgrade.py index 0f98bff3c..e36f115fa 100644 --- a/flocks/server/routes/enterprise_upgrade.py +++ b/flocks/server/routes/enterprise_upgrade.py @@ -179,6 +179,29 @@ async def take_licence(request: Request, request_id: str = _REQUEST_ID) -> dict[ return {"application": application, "situation": await asyncio.to_thread(enterprise.situation)} +@router.post("/applications/offline", summary="离线申请:生成交给授权方的申请信息(表单和这台机器的标识),不发给 Console") +async def offline_application(form: ApplicationForm, user=Depends(_administrator)) -> dict[str, Any]: + try: + return {"application": await enterprise_application.offline_application(form.model_dump(), user.username)} + except enterprise.EnterpriseUpgradeError as exc: + raise _refused(exc) from exc + + +class LicenceFile(BaseModel): + """A licence file's text: the license.json Console's offline issue downloads, or the bare token.""" + + content: str = Field(min_length=1, max_length=enterprise_application.MAX_LICENCE_CHARS) + + +@router.post("/licence/import", summary="导入授权文件:写进这台机器,之后可以升级到企业版") +async def import_licence(payload: LicenceFile, _user=Depends(_administrator)) -> dict[str, Any]: + try: + licence = await enterprise_application.import_licence(payload.content) + except enterprise.EnterpriseUpgradeError as exc: + raise _refused(exc) from exc + return {"licence": licence, "situation": await asyncio.to_thread(enterprise.situation)} + + @router.post("/licence/sync", summary="向 Console 同步这台机器的授权:续期、额度变更落到本机") async def sync_licence(request: Request) -> dict[str, Any]: require_admin(request) diff --git a/flocks/server/routes/model_discovery.py b/flocks/server/routes/model_discovery.py index 52ffd717c..6a67a113a 100644 --- a/flocks/server/routes/model_discovery.py +++ b/flocks/server/routes/model_discovery.py @@ -13,6 +13,7 @@ from flocks.provider.model_catalog import get_raw_catalog from flocks.provider.model_discovery import THREATBOOK_MODEL_LIST_PROVIDERS, discover_models, is_known_non_chat_model from flocks.provider.provider import Provider +from flocks.provider.tls import MAX_CA_CERT_CHARS from flocks.server.auth import require_admin from flocks.server.config_mutation import serialized_config_mutation from flocks.server.routes.provider import _ensure_provider_initialized, _load_dynamic_providers @@ -24,6 +25,21 @@ class DiscoverModelsRequest(BaseModel): model_config = ConfigDict(extra="forbid") api_key: str | None = Field(None, max_length=16384) base_url: str | None = Field(None, max_length=4096) + # TLS settings a form has not saved yet (flocks.provider.tls); unset ones + # keep the stored values. + verify_ssl: bool | None = None + ca_cert: str | None = Field(None, max_length=MAX_CA_CERT_CHARS) + + def tls_overrides(self) -> dict | None: + """The TLS settings this request names, to put in place of the stored ones.""" + if self.verify_ssl is None and self.ca_cert is None: + return None + overrides: dict = {} + if self.verify_ssl is not None: + overrides["verify_ssl"] = self.verify_ssl + if self.ca_cert is not None: + overrides["ca_cert"] = self.ca_cert + return overrides ModelIdentifier = Annotated[str, StringConstraints(min_length=1, max_length=512)] @@ -83,7 +99,9 @@ async def discover_provider_models( ): raise HTTPException(404, "Provider not found") body = body or DiscoverModelsRequest() - return await discover_models(provider_id, api_key=body.api_key, base_url=body.base_url) + return await discover_models( + provider_id, api_key=body.api_key, base_url=body.base_url, tls_overrides=body.tls_overrides() + ) @router.post("/{provider_id}/import-models") @@ -245,7 +263,8 @@ async def check_provider_key(provider_id: str, body: DiscoverModelsRequest, _adm await _ensure_provider_initialized() if provider_id not in get_raw_catalog() and ConfigWriter.get_provider_raw(provider_id) is None and provider_id not in Provider._providers: raise HTTPException(404, "Provider not found") - result = await discover_models(provider_id, api_key=body.api_key, base_url=body.base_url) + tls_overrides = body.tls_overrides() + result = await discover_models(provider_id, api_key=body.api_key, base_url=body.base_url, tls_overrides=tls_overrides) if result["source"] != "api" or result["status"] != "success": return {"status": "invalid" if result["code"] in {"authentication_failed", "missing_credentials"} else "unverified", "code": result["code"]} # ThreatBook uses a successful live model-list response as its validation @@ -255,6 +274,11 @@ async def check_provider_key(provider_id: str, body: DiscoverModelsRequest, _adm # A public models endpoint does not prove that a key is valid. Require # rejection of an unrelated credential before reporting authentication. import secrets - control = await discover_models(provider_id, api_key="flocks-probe-" + secrets.token_urlsafe(24), base_url=body.base_url) + control = await discover_models( + provider_id, + api_key="flocks-probe-" + secrets.token_urlsafe(24), # secret-guard: allow (random probe key, not a credential) + base_url=body.base_url, + tls_overrides=tls_overrides, + ) verified = control["code"] in {"authentication_failed", "permission_denied"} return {"status": "valid" if verified else "unverified", "code": "key_valid" if verified else "key_check_unsupported"} diff --git a/flocks/server/routes/project.py b/flocks/server/routes/project.py index 9629e692c..fc05c0ba7 100644 --- a/flocks/server/routes/project.py +++ b/flocks/server/routes/project.py @@ -60,6 +60,22 @@ class FolderBrowserResponse(BaseModel): parent: Optional[str] roots: List[FolderEntry] entries: List[FolderEntry] + # The requested directory does not exist yet: ``path`` is its nearest + # existing ancestor, not the directory that was asked for. + missing: bool = False + + +# How many levels above a missing directory the folder picker looks for one +# that exists; one ``stat`` per level, so the request stays cheap for any path. +_NEAREST_ANCESTOR_LEVELS = 32 + + +def _nearest_existing_ancestor(path: Path) -> Path: + """Return the closest existing ancestor of *path*, or raise FileNotFoundError.""" + for candidate in (path, *path.parents[:_NEAREST_ANCESTOR_LEVELS]): + if candidate.exists(): + return candidate + raise FileNotFoundError(path) async def _list_project_summaries(user: AuthUser, search: Optional[str]) -> List[ProjectInfo]: @@ -198,7 +214,14 @@ async def get_current_project(request: Request, project_id: Optional[str] = Quer @router.get("/folders", response_model=FolderBrowserResponse, summary="Browse project folders") -async def browse_project_folders(request: Request, path: Optional[str] = Query(None)): +async def browse_project_folders( + request: Request, + path: Optional[str] = Query(None), + nearest: bool = Query( + False, + description="List the nearest existing ancestor when the directory does not exist yet", + ), +): """List directories under configured roots without exposing file contents.""" from flocks.utils.http_file_read_guard import http_private_path_is_blocked, require_http_private_path_access @@ -206,10 +229,24 @@ async def browse_project_folders(request: Request, path: Optional[str] = Query(N roots = Project.allowed_roots() if not roots: raise HTTPException(status_code=400, detail="No project roots are available") + if path and "\x00" in path: + # pathlib reports a NUL byte differently per platform (a ValueError, or + # an OSError that reads like a missing directory): refuse it up front. + raise HTTPException(status_code=400, detail="Directory does not exist") + missing = False try: if path: - current = Path(path).expanduser().resolve(strict=True) + requested = Path(path).expanduser() + try: + current = requested.resolve(strict=True) + except (OSError, RuntimeError): + # A project directory is created on save, so the picker can be + # opened on one that is not there yet: show what exists above it. + if not nearest or not requested.is_absolute(): + raise + current = _nearest_existing_ancestor(requested).resolve(strict=True) + missing = True else: home = Path.home().resolve(strict=True) current = ( @@ -261,6 +298,7 @@ async def browse_project_folders(request: Request, path: Optional[str] = Query(N parent=parent_value, roots=[FolderEntry(name=root.name or str(root), path=str(root)) for root in roots], entries=entries, + missing=missing, ) diff --git a/flocks/server/routes/provider.py b/flocks/server/routes/provider.py index 5a50bcf77..4af23ffb7 100644 --- a/flocks/server/routes/provider.py +++ b/flocks/server/routes/provider.py @@ -30,6 +30,17 @@ is_unsendable_header_error, ) from flocks.provider.provider import BaseProvider, Provider, ModelInfo as ProviderModelInfo +from flocks.provider.tls import ( + CA_CERT_KEY, + LEGACY_VERIFY_SSL_KEY, + MAX_CA_CERT_CHARS, + VERIFY_SSL_KEY, + CACertError, + classify_tls_error, + resolve_verify_ssl, + tls_error_hint, + validate_ca_cert, +) from flocks.security.secrets import SecretManager from flocks.server.auth import get_request_ip, get_request_user_agent, require_admin, require_user from flocks.server.config_mutation import serialized_config_mutation @@ -806,6 +817,8 @@ async def get_provider_catalog(): # Propagate allow_multiple flag (only openai-compatible has it) if raw.get("allow_multiple"): provider_data["allow_multiple"] = True + # Whether the add dialog offers the SSL certificate settings. + provider_data["tls_configurable"] = _provider_tls_configurable(provider_id, raw.get("npm")) providers.append(provider_data) @@ -1595,7 +1608,8 @@ async def update_api_service(provider_id: str, request: APIServiceUpdateRequest) statuses = await _read_api_service_status_cache() matched_count = 0 if request.enabled is not None: - matched_count = _set_api_service_tools_enabled(provider_id, request.enabled) + async with ToolRegistry.write_lock(): + matched_count = _set_api_service_tools_enabled(provider_id, request.enabled) if request.enabled: status_payload = statuses.get(provider_id, {}) if status_payload.get("status") == "disabled": @@ -1699,6 +1713,7 @@ async def delete_api_service(provider_id: str) -> Dict[str, Any]: """ from flocks.hub.installer import uninstall_plugin from flocks.security import get_secret_manager + from flocks.tool.registry import ToolRegistry try: if _is_api_service_builtin(provider_id): @@ -1736,7 +1751,8 @@ async def delete_api_service(provider_id: str) -> Dict[str, Any]: statuses.pop(provider_id, None) await _write_api_service_status_cache(statuses) - matched_count = _set_api_service_tools_enabled(provider_id, False) + async with ToolRegistry.write_lock(): + matched_count = _set_api_service_tools_enabled(provider_id, False) uninstalled_plugin = False if backing_plugin is not None: @@ -1861,6 +1877,18 @@ class ProviderCredentialRequest(BaseModel): fields: Optional[Dict[str, Optional[str]]] = Field(None, description="Dynamic service credential fields") provider_name: Optional[str] = Field(None, description="Display name for the provider") skip_catalog_bootstrap: bool = Field(False, description="Keep the model inventory explicitly managed instead of adding catalog defaults") + verify_ssl: Optional[bool] = Field( + None, + description=( + "LLM providers: check the server certificate (default). False turns the checks off " + "and accepts older TLS handshakes; omitted leaves the setting unchanged." + ), + ) + ca_cert: Optional[str] = Field( + None, + max_length=MAX_CA_CERT_CHARS, + description="LLM providers: CA certificate in PEM, or its absolute path on the server; empty removes it, omitted leaves it unchanged.", + ) class ProviderCredentialResponse(BaseModel): @@ -1875,6 +1903,11 @@ class ProviderCredentialResponse(BaseModel): fields: Optional[Dict[str, Optional[str]]] = None secret_ids: Optional[Dict[str, str]] = None has_credential: bool + # LLM providers only: the TLS settings (flocks.provider.tls) and whether + # this provider's client follows them. + verify_ssl: Optional[bool] = None + ca_cert: Optional[str] = None + tls_configurable: bool = False def _load_llm_provider_credentials( @@ -1895,15 +1928,18 @@ def _load_llm_provider_credentials( api_key = _get_inline_provider_api_key(provider_id) base_url = None + options: Dict[str, Any] = {} raw_provider = ConfigWriter.get_provider_raw(provider_id) if raw_provider: - options = raw_provider.get("options", {}) + raw_options = raw_provider.get("options") + options = raw_options if isinstance(raw_options, dict) else {} base_url = options.get("baseURL") or options.get("base_url") if not base_url: base_url = secrets.get(f"{provider_id}_base_url") is_placeholder = _is_placeholder_api_key(api_key) ui_api_key = None if is_placeholder else api_key + ca_cert = options.get(CA_CERT_KEY) return ProviderCredentialResponse( secret_id=secret_id if api_key else None, @@ -1911,9 +1947,69 @@ def _load_llm_provider_credentials( api_key_masked=SecretManager.mask(ui_api_key) if ui_api_key else None, base_url=base_url, has_credential=bool(api_key), + verify_ssl=resolve_verify_ssl(options), + ca_cert=(ca_cert.strip() or None) if isinstance(ca_cert, str) else None, + tls_configurable=_provider_tls_configurable(provider_id, (raw_provider or {}).get("npm")), ) +# npm packages whose providers are built on a client that follows the TLS +# settings (flocks.provider.tls), for providers not registered yet. +_TLS_CONFIGURABLE_NPMS = frozenset({ + "@ai-sdk/openai-compatible", + "@ai-sdk/cherry", + "@ai-sdk/openai", + "@ai-sdk/anthropic", + "@ai-sdk/azure", +}) + + +def _provider_tls_configurable(provider_id: str, npm: Optional[str] = None) -> bool: + """Whether ``verify_ssl`` / ``ca_cert`` reach this provider's HTTP client.""" + provider = Provider._providers.get(provider_id) + if provider is not None: + return bool(getattr(provider, "SUPPORTS_TLS_SETTINGS", False)) + if npm is None: + try: + from flocks.provider.model_catalog import get_raw_catalog + + npm = (get_raw_catalog().get(provider_id) or {}).get("npm") + except Exception: + npm = None + return npm in _TLS_CONFIGURABLE_NPMS + + +def _requested_tls_options(request: "ProviderCredentialRequest") -> Optional[Dict[str, Any]]: + """The TLS options a credentials request sets, checked; ``None`` when it sets none. + + ``verify_ssl`` true and an empty ``ca_cert`` remove the keys, so a provider + left at the defaults keeps no TLS options at all. + """ + if request.verify_ssl is None and request.ca_cert is None: + return None + updates: Dict[str, Any] = {} + if request.verify_ssl is not None: + updates[VERIFY_SSL_KEY] = None if request.verify_ssl else False + if request.ca_cert is not None: + try: + updates[CA_CERT_KEY] = validate_ca_cert(request.ca_cert) + except CACertError as exc: + raise HTTPException(status_code=400, detail=str(exc)) from exc + return updates + + +def _merge_tls_options(options: Dict[str, Any], updates: Dict[str, Any]) -> Dict[str, Any]: + merged = dict(options) + if VERIFY_SSL_KEY in updates: + merged.pop(LEGACY_VERIFY_SSL_KEY, None) + for key, value in updates.items(): + if value is None: + merged.pop(key, None) + else: + merged[key] = value + return merged + + @router.get( "/{provider_id}/credentials", response_model=ProviderCredentialResponse, @@ -2020,6 +2116,12 @@ async def set_provider_credentials( # Unknown id and nothing to update: refuse before touching # .secret.json / flocks.json so no bogus provider is persisted. raise HTTPException(status_code=404, detail=f"Unknown provider: {provider_id}") + tls_updates = _requested_tls_options(request) + if tls_updates is not None: + await _ensure_provider_initialized() + raw_for_npm = ConfigWriter.get_provider_raw(provider_id) or {} + if not _provider_tls_configurable(provider_id, raw_for_npm.get("npm")): + raise HTTPException(status_code=400, detail="该模型服务不支持 SSL 证书设置。") secrets = get_secret_manager() secret_id = request.secret_id or f"{provider_id}_llm_key" effective_api_key = (request.api_key or "").strip() @@ -2117,6 +2219,14 @@ async def set_provider_credentials( ) if request.skip_catalog_bootstrap: ConfigWriter.update_provider_field(provider_id, "model_sync", "manual") + if tls_updates is not None: + current = ConfigWriter.get_provider_raw(provider_id) or {} + current_options = current.get("options") + ConfigWriter.update_provider_field( + provider_id, + "options", + _merge_tls_options(current_options if isinstance(current_options, dict) else {}, tls_updates), + ) else: # Provider not yet in flocks.json — create a minimal entry, but only # for ids the system actually knows (catalog / registered SDK @@ -2171,6 +2281,8 @@ async def set_provider_credentials( config_dict["model_sync"] = "manual" if request.provider_name: config_dict["name"] = request.provider_name + if tls_updates is not None: + config_dict["options"] = _merge_tls_options(config_dict.get("options") or {}, tls_updates) ConfigWriter.add_provider(provider_id, config_dict) # Config.get() caches resolved secret values. Invalidate it after @@ -2190,6 +2302,8 @@ async def set_provider_credentials( effective_base_url = raw.get("options", {}).get("baseURL") custom_settings = _get_provider_custom_settings(provider) + if tls_updates is not None: + custom_settings = _merge_tls_options(custom_settings, tls_updates) provider.configure(ProviderConfig( provider_id=provider_id, api_key=effective_api_key, @@ -2730,6 +2844,9 @@ def _credential_test_error_code(error: Exception) -> str: return "authentication_failed" if isinstance(error, (APITimeoutError, httpx.TimeoutException, TimeoutError)): return "connection_timeout" + tls_code = classify_tls_error(error) + if tls_code: + return tls_code if isinstance(error, (APIConnectionError, httpx.TransportError)): return "connection_error" status_code = getattr(error, "status_code", None) @@ -2785,9 +2902,26 @@ def _without_credential(text: str, api_key: Optional[str]) -> str: def _credential_test_error_text(error: Exception, api_key: Optional[str]) -> str: if is_unsendable_header_error(error): return UNSENDABLE_HEADER_MESSAGE + hint = tls_error_hint(error) + if hint: + # The SDK says only "Connection error."; name the TLS cause and what to change. + return _without_credential(f"{hint}({_tls_root_text(error)})", api_key) return _without_credential(str(error), api_key) +def _tls_root_text(error: BaseException) -> str: + """The innermost message of *error*'s cause chain, e.g. the OpenSSL reason.""" + seen = set() + current: Optional[BaseException] = error + text = str(error) + while current is not None and id(current) not in seen and len(seen) < 16: + seen.add(id(current)) + if str(current): + text = str(current) + current = current.__cause__ or current.__context__ + return text[:300] + + async def _test_provider_credentials_impl( provider_id: str, body: Optional[TestCredentialRequest] = None, diff --git a/flocks/server/routes/tool.py b/flocks/server/routes/tool.py index 34ebbd271..deb99b80e 100644 --- a/flocks/server/routes/tool.py +++ b/flocks/server/routes/tool.py @@ -6,7 +6,7 @@ from dataclasses import dataclass import threading import time -from typing import Annotated, List, Optional, Dict, Any, Literal, Sequence +from typing import Annotated, List, NamedTuple, Optional, Dict, Any, Literal, Sequence from fastapi import APIRouter, Depends, HTTPException, Query, status from pydantic import BaseModel, Field, field_validator from pydantic_core import PydanticCustomError @@ -54,6 +54,21 @@ class ToolInfoResponse(BaseModel): group: Optional[str] = Field(None, description="Optional plugin group") group_readonly: bool = False enabled_customized: bool = Field(False, description="True if an enabled override is recorded in flocks.json tool_settings") + service_enabled: Optional[bool] = Field( + None, + description=( + "Enabled flag of the API service that gates this tool; null when no service gates it. " + "While it is false the tool stays disabled and a request to enable it is not applied." + ), + ) + service_integration_type: Optional[str] = Field( + None, + description=( + "integration_type of that service as the API service list reports it. " + "'device' means the service is managed on the Device Integration page, " + "not in the API service list, wherever the plugin is installed." + ), + ) requires_confirmation: bool = Field(False, description="Requires confirmation") @@ -199,6 +214,8 @@ class ToolListIndexItem: requires_confirmation: bool group: Optional[str] = None group_readonly: bool = False + service_enabled: Optional[bool] = None + service_integration_type: Optional[str] = None _TOOL_SUMMARY_CACHE_TTL_SECONDS = 5.0 @@ -242,8 +259,9 @@ def _get_tool_summary_items() -> List[ToolListIndexItem]: ): return list(_tool_summary_cache_items) + services = _ServiceLookup() items = tuple( - _build_tool_index_item(t) + _build_tool_index_item(t, services=services) for t in ToolRegistry.list_tools() if t.name not in _INTERNAL_TOOL_NAMES ) @@ -295,13 +313,22 @@ def _get_tool_source(tool_info: ToolInfo) -> tuple: return "custom", None -def _build_tool_response(t: ToolInfo, *, include_parameters: bool = True) -> ToolInfoResponse: - """Build ToolInfoResponse with source info and overlay metadata.""" +def _build_tool_response( + t: ToolInfo, + *, + include_parameters: bool = True, + services: Optional["_ServiceLookup"] = None, +) -> ToolInfoResponse: + """Build ToolInfoResponse with source info and overlay metadata. + + Pass one ``services`` lookup when building many rows for one response. + """ source, source_name = _get_tool_source(t) setting = ConfigWriter.get_tool_setting(t.name) or {} customized = "enabled" in setting enabled_default = _get_default_enabled(t) parameters = [p.model_dump() for p in t.parameters] if include_parameters else [] + state = _resolve_tool_enabled_state(t, source=source, source_name=source_name, services=services) return ToolInfoResponse( name=t.name, group=normalize_tool_group(t.group if t.group_readonly else setting.get("group", t.group)), @@ -314,17 +341,20 @@ def _build_tool_response(t: ToolInfo, *, include_parameters: bool = True) -> Too vendor=t.vendor, parameters=parameters, parameters_count=len(t.parameters), - enabled=_get_effective_tool_enabled(t, source=source, source_name=source_name), + enabled=state.enabled, enabled_default=enabled_default, enabled_customized=customized, + service_enabled=state.service_enabled, + service_integration_type=state.service_integration_type, requires_confirmation=t.requires_confirmation, ) -def _build_tool_index_item(t: ToolInfo) -> ToolListIndexItem: +def _build_tool_index_item(t: ToolInfo, *, services: Optional["_ServiceLookup"] = None) -> ToolListIndexItem: """Build the lightweight index row used by the paged list endpoint.""" source, source_name = _get_tool_source(t) setting = ConfigWriter.get_tool_setting(t.name) or {} + state = _resolve_tool_enabled_state(t, source=source, source_name=source_name, services=services) return ToolListIndexItem( name=t.name, group=normalize_tool_group(t.group if t.group_readonly else setting.get("group", t.group)), @@ -336,9 +366,11 @@ def _build_tool_index_item(t: ToolInfo) -> ToolListIndexItem: source_name=source_name, vendor=t.vendor, parameters_count=len(t.parameters), - enabled=_get_effective_tool_enabled(t, source=source, source_name=source_name), + enabled=state.enabled, enabled_default=_get_default_enabled(t), enabled_customized="enabled" in setting, + service_enabled=state.service_enabled, + service_integration_type=state.service_integration_type, requires_confirmation=t.requires_confirmation, ) @@ -359,6 +391,8 @@ def _tool_index_item_to_response(item: ToolListIndexItem) -> ToolInfoResponse: enabled=item.enabled, enabled_default=item.enabled_default, enabled_customized=item.enabled_customized, + service_enabled=item.service_enabled, + service_integration_type=item.service_integration_type, requires_confirmation=item.requires_confirmation, ) @@ -792,6 +826,87 @@ def _get_effective_tool_enabled( return tool_info.enabled and _get_api_service_enabled(source_name) +class _ServiceLookup: + """API service facts for the tool rows of one response, read once each. + + ``ConfigWriter.get_api_service_raw`` re-reads and parses ``flocks.json`` + on every call and a list response builds one row per tool, so a lookup + shared by those rows asks about each service once instead of once per + tool. It must not outlive the response it was created for. + """ + + def __init__(self) -> None: + self._enabled: Dict[str, bool] = {} + self._integration_type: Dict[str, Optional[str]] = {} + + def enabled(self, service_id: str) -> bool: + if service_id not in self._enabled: + from flocks.server.routes.provider import _get_api_service_enabled + + self._enabled[service_id] = _get_api_service_enabled(service_id) + return self._enabled[service_id] + + def integration_type(self, service_id: str) -> Optional[str]: + """Return the service's ``integration_type`` as the service list reports it. + + The API service list is the reference: a service it reports as + ``device`` is left out of the API tab and managed on the device + page. The tool's own ``source`` only says which plugin directory + it was loaded from, which can differ. + """ + if service_id not in self._integration_type: + value: Any = None + try: + from flocks.server.routes.provider import _load_api_service_summary_metadata_data + + value = (_load_api_service_summary_metadata_data(service_id) or {}).get("integration_type") + except Exception as exc: + # Unreadable metadata must not take the tool list down with it. + log.debug("tool.service_integration_type.failed", {"service": service_id, "error": str(exc)}) + normalized = value.strip().lower() if isinstance(value, str) else "" + self._integration_type[service_id] = normalized or None + return self._integration_type[service_id] + + +class _ToolEnabledState(NamedTuple): + enabled: bool + service_enabled: Optional[bool] + service_integration_type: Optional[str] + + +def _resolve_tool_enabled_state( + tool_info: ToolInfo, + *, + source: Optional[str], + source_name: Optional[str], + services: Optional[_ServiceLookup] = None, +) -> _ToolEnabledState: + """Return the enabled state of a tool and the facts about what gates it. + + ``enabled`` is exactly :func:`_get_effective_tool_enabled`. + ``service_enabled`` is the flag of the API service that gates the tool, + ``None`` when no service does. Two gates exist: PATCH refuses to open a + tool whose ``provider`` service is off (:func:`_service_allows_enable`), + and the effective state of api/device tools is ANDed with the service + named by ``source_name``; for YAML api/device tools they are the same + service. ``service_integration_type`` says where that service is + managed. Clients need both to explain why such a tool is off, cannot + be switched on, and where to go instead. + """ + effective_gate = source_name if source in ("api", "device") and source_name else None + gates = [gate for gate in dict.fromkeys((tool_info.provider, effective_gate)) if gate] + if not gates: + return _ToolEnabledState(tool_info.enabled, None, None) + services = services or _ServiceLookup() + flags = {gate: services.enabled(gate) for gate in gates} + enabled = tool_info.enabled + if effective_gate: + enabled = enabled and flags[effective_gate] + # The service to send the user to: the one that is off, else the owner. + blocking = next((gate for gate in gates if not flags[gate]), gates[0]) + return _ToolEnabledState(enabled, all(flags.values()), services.integration_type(blocking)) + + def _set_global_tool_enabled(tool: Any, desired: bool) -> bool: """Persist and apply the global enabled state for a registry tool.""" with ToolRegistry._refresh_lock: @@ -866,7 +981,8 @@ async def list_tools( ) tools = ToolRegistry.list_tools(category=cat_filter) - result = [_build_tool_response(t) for t in tools if t.name not in _INTERNAL_TOOL_NAMES] + services = _ServiceLookup() + result = [_build_tool_response(t, services=services) for t in tools if t.name not in _INTERNAL_TOOL_NAMES] # Apply source filter if specified if source: @@ -1088,7 +1204,8 @@ async def update_tool( if desired: if not tool.info.enabled: - _set_global_tool_enabled(tool, True) + async with ToolRegistry.write_lock(): + _set_global_tool_enabled(tool, True) removed = await delete_device_tool_setting(device_id, tool_name) log.info("tool.device.updated.reset_to_global", { "name": tool_name, @@ -1110,7 +1227,7 @@ async def update_tool( return _build_tool_response(tool.info) # --- Global mode (native settings, without rescanning plugin files) --- - with ToolRegistry._refresh_lock: + async with ToolRegistry.write_lock(): if desired is not None: _set_global_tool_enabled(tool, desired) if "group" in request.model_fields_set and not tool.info.group_readonly: @@ -1143,7 +1260,7 @@ async def reset_tool_setting(tool_name: str, _admin: object = Depends(require_ad detail=f"Tool not found: {tool_name}", ) - with ToolRegistry._refresh_lock: + async with ToolRegistry.write_lock(): removed = ConfigWriter.delete_tool_setting(tool_name, field="enabled") default = _get_default_enabled(tool.info) new_enabled = default and _service_allows_enable(tool.info) @@ -1349,7 +1466,9 @@ async def refresh_tools(_admin: object = Depends(require_admin)): ("plugin", ToolRegistry.refresh_plugin_tools), ): try: - refresh() + # Each reload re-reads every source and takes seconds: run it off + # the event loop so the rest of the server keeps answering. + await asyncio.to_thread(refresh) stages[stage] = "success" except ToolRefreshError as exc: stages[stage] = "error" @@ -1621,9 +1740,10 @@ async def create_tool(request: CreateToolRequest, _admin: object = Depends(requi tool.info.source = "plugin_yaml" if request.provider: tool.info.provider = request.provider - ToolRegistry.register(tool) - if tool.info.name not in ToolRegistry._plugin_tool_names: - ToolRegistry._plugin_tool_names.append(tool.info.name) + async with ToolRegistry.write_lock(): + ToolRegistry.register(tool) + if tool.info.name not in ToolRegistry._plugin_tool_names: + ToolRegistry._plugin_tool_names.append(tool.info.name) _invalidate_tool_summary_cache() except Exception as e: log.error("tool.create.register_error", {"error": str(e), "name": request.name}) @@ -1727,9 +1847,10 @@ async def update_plugin_tool(name: str, request: UpdateToolRequest, _admin: obje tool = yaml_to_tool(raw, yaml_path) if not tool.info.source: tool.info.source = "plugin_yaml" - ToolRegistry.register(tool) - ToolRegistry._sync_api_service_states() - ToolRegistry._apply_tool_settings() + async with ToolRegistry.write_lock(): + ToolRegistry.register(tool) + ToolRegistry._sync_api_service_states() + ToolRegistry._apply_tool_settings() _invalidate_tool_summary_cache() return _build_tool_response(tool.info) except Exception as e: @@ -1781,7 +1902,8 @@ async def delete_tool(name: str, _admin: object = Depends(require_admin)): # installation record consistent even when the in-memory refresh fails. cleanup_errors: List[str] = [] try: - ToolRegistry.refresh_plugin_tools() + # A full plugin reload takes seconds: never on the event loop. + await asyncio.to_thread(ToolRegistry.refresh_plugin_tools) except Exception as e: refresh_error = str(e) cleanup_errors.append(f"registry refresh: {refresh_error}") @@ -1846,7 +1968,8 @@ async def reload_tool(name: str, _admin: object = Depends(require_admin)): tool = yaml_to_tool(raw, yaml_path) if not tool.info.source: tool.info.source = "plugin_yaml" - ToolRegistry.register(tool) + async with ToolRegistry.write_lock(): + ToolRegistry.register(tool) _invalidate_tool_summary_cache() log.info("tool.reloaded", {"name": name}) return _build_tool_response(tool.info) diff --git a/flocks/server/routes/workflow.py b/flocks/server/routes/workflow.py index 1426e51fd..3319602d6 100644 --- a/flocks/server/routes/workflow.py +++ b/flocks/server/routes/workflow.py @@ -3493,6 +3493,30 @@ def _validate_trigger_definitions(triggers: List[TriggerDefinition]) -> None: _validate_schedule_trigger_source(trigger) +async def _save_trigger_definition( + workflow_id: str, + workflow_data: Dict[str, Any], + triggers: List[TriggerDefinition], + trigger: TriggerDefinition, +) -> tuple[TriggerDefinition, Dict[str, Any]]: + """Apply supplied fields to the stored definition, then validate and persist once. + + A form or API client that omits a trigger field must not reset it to a + model default. Explicit values (including empty mappings) still replace it. + """ + current = next((item for item in triggers if item.id == trigger.id), None) + if current is not None: + trigger = TriggerDefinition.model_validate({ + **current.model_dump(), + **trigger.model_dump(exclude_unset=True), + }) + trigger = _merge_trigger_secrets(trigger, current) + updated = _replace_or_append_trigger(triggers, trigger) + _validate_trigger_definitions(updated) + persisted = await _persist_workflow_triggers(workflow_id, workflow_data, updated) + return trigger, persisted + + @router.get("/workflow/{workflow_id}/triggers") async def list_workflow_triggers(workflow_id: str): """List unified triggers for a workflow with runtime status.""" @@ -3525,10 +3549,7 @@ async def create_workflow_trigger(workflow_id: str, trigger: TriggerDefinition): if not data: raise HTTPException(status_code=404, detail=f"Workflow not found: {workflow_id}") existing = await _get_workflow_trigger_defs(workflow_id, data) - trigger = _merge_trigger_secrets(trigger, next((item for item in existing if item.id == trigger.id), None)) - updated = _replace_or_append_trigger(existing, trigger) - _validate_trigger_definitions(updated) - persisted = await _persist_workflow_triggers(workflow_id, data, updated) + trigger, persisted = await _save_trigger_definition(workflow_id, data, existing, trigger) await default_trigger_runtime.restart_workflow(workflow_id, persisted.get("workflowJson") or {}) status = await default_trigger_runtime.get_trigger_status(workflow_id, trigger) return TriggerSaveResponse(trigger=_trigger_to_api_dict(trigger), status=status) @@ -3543,11 +3564,10 @@ async def update_workflow_trigger(workflow_id: str, trigger_id: str, trigger: Tr if not data: raise HTTPException(status_code=404, detail=f"Workflow not found: {workflow_id}") existing = await _get_workflow_trigger_defs(workflow_id, data) - current = _find_trigger_or_404(existing, trigger_id) - updated_trigger = _merge_trigger_secrets(trigger.model_copy(update={"id": trigger_id}), current) - updated = _replace_or_append_trigger(existing, updated_trigger) - _validate_trigger_definitions(updated) - persisted = await _persist_workflow_triggers(workflow_id, data, updated) + _find_trigger_or_404(existing, trigger_id) + updated_trigger, persisted = await _save_trigger_definition( + workflow_id, data, existing, trigger.model_copy(update={"id": trigger_id}), + ) await default_trigger_runtime.restart_workflow(workflow_id, persisted.get("workflowJson") or {}) status = await default_trigger_runtime.get_trigger_status(workflow_id, updated_trigger) return TriggerSaveResponse(trigger=_trigger_to_api_dict(updated_trigger), status=status) @@ -3920,53 +3940,14 @@ async def save_kafka_config(workflow_id: str, req: KafkaConfigRequest): if not data: raise HTTPException(status_code=404, detail=f"Workflow not found: {workflow_id}") - if req.enabled: - try: - validate_workflow_python(data.get("workflowJson") or {}) - except Exception as exc: - raise HTTPException(status_code=400, detail=str(exc)) from exc - config = { - "workflowId": workflow_id, - "enabled": req.enabled, - "inputBroker": req.inputBroker, - "inputTopic": req.inputTopic, - "inputGroupId": req.inputGroupId, - "inputKey": req.inputKey, - "autoOffsetReset": req.autoOffsetReset, - "inputs": _strip_execution_only_comments(req.inputs), - "updatedAt": int(time.time() * 1000), - } - await WorkflowStore.put_config(workflow_id, config, kind="workflow_kafka_config") + config = req.model_dump(by_alias=True) + config["inputs"] = _strip_execution_only_comments(req.inputs) + config["updatedAt"] = int(time.time() * 1000) triggers = await _get_workflow_trigger_defs(workflow_id, data) - unified_trigger = TriggerDefinition.model_validate( - { - "id": _legacy_singleton_trigger_id(triggers, "kafka"), - "type": "kafka", - "enabled": req.enabled, - "source": { - "inputBroker": req.inputBroker or "", - "inputTopic": req.inputTopic or "", - "inputGroupId": req.inputGroupId or "", - "autoOffsetReset": req.autoOffsetReset, - }, - "mapping": { - req.inputKey or "kafka_message": "$.body", - }, - "inputs": _strip_execution_only_comments(req.inputs), - "updatedAt": config["updatedAt"], - } - ) - updated_triggers = _replace_or_append_trigger(triggers, unified_trigger) - _validate_trigger_type_constraints(updated_triggers) - await _persist_workflow_triggers( - workflow_id, - data, - updated_triggers, - ) - - from flocks.ingest.kafka.manager import default_manager as _kafka_default_manager - - status = await _kafka_default_manager.restart_workflow(workflow_id) + trigger = legacy_kafka_trigger_from_config(config) + trigger = trigger.model_copy(update={"id": _legacy_singleton_trigger_id(triggers, "kafka")}) + trigger, _ = await _save_trigger_definition(workflow_id, data, triggers, trigger) + status = await _sync_trigger_legacy_state(workflow_id, trigger) state = (status or {}).get("state") if req.enabled and state == "failed": err = (status or {}).get("error") or "consumer_connect_failed" @@ -4029,66 +4010,13 @@ async def save_workflow_poller_config(workflow_id: str, req: WorkflowPollerConfi if not data: raise HTTPException(status_code=404, detail=f"Workflow not found: {workflow_id}") - if req.enabled: - try: - validate_workflow_python(data.get("workflowJson") or {}) - except Exception as exc: - raise HTTPException(status_code=400, detail=str(exc)) from exc - cron_expression = (req.cronExpression or "").strip() - if cron_expression: - # Validate before anything is persisted; a bad expression must not - # leave an enabled config behind that fails on every restart. - _validate_cron_expression(cron_expression) - trigger_source: Dict[str, Any] - if cron_expression: - trigger_source = { - "mode": "cron", - "intervalSeconds": req.intervalSeconds, - "cron": cron_expression, - } - else: - trigger_source = { - "mode": "interval", - "intervalSeconds": req.intervalSeconds, - } - - config = { - "workflowId": workflow_id, - "enabled": req.enabled, - "intervalSeconds": req.intervalSeconds, - "cronExpression": cron_expression or None, - "timeoutSeconds": req.timeoutSeconds, - "noOverlap": req.noOverlap, - "inputs": req.inputs, - "updatedAt": int(time.time() * 1000), - } - await WorkflowStore.put_config(workflow_id, config, kind="workflow_poller_config") + config = req.model_dump(by_alias=True) + config["updatedAt"] = int(time.time() * 1000) triggers = await _get_workflow_trigger_defs(workflow_id, data) - unified_trigger = TriggerDefinition.model_validate( - { - "id": _legacy_singleton_trigger_id(triggers, "schedule"), - "type": "schedule", - "enabled": req.enabled, - "source": trigger_source, - "runtime": { - "timeoutSeconds": req.timeoutSeconds, - "noOverlap": req.noOverlap, - }, - "inputs": req.inputs, - "updatedAt": config["updatedAt"], - } - ) - updated_triggers = _replace_or_append_trigger(triggers, unified_trigger) - _validate_trigger_type_constraints(updated_triggers) - await _persist_workflow_triggers( - workflow_id, - data, - updated_triggers, - ) - - from flocks.workflow.poller_manager import default_manager as _poller_default_manager - - poller_status = await _poller_default_manager.restart_workflow(workflow_id) + trigger = legacy_schedule_trigger_from_config(config) + trigger = trigger.model_copy(update={"id": _legacy_singleton_trigger_id(triggers, "schedule")}) + trigger, _ = await _save_trigger_definition(workflow_id, data, triggers, trigger) + poller_status = await _sync_trigger_legacy_state(workflow_id, trigger) if req.enabled and (poller_status or {}).get("state") == "failed": err = (poller_status or {}).get("error") or "poller_start_failed" raise HTTPException( @@ -4170,51 +4098,13 @@ async def save_syslog_config(workflow_id: str, req: SyslogConfigRequest): if not data: raise HTTPException(status_code=404, detail=f"Workflow not found: {workflow_id}") - if req.enabled: - try: - validate_workflow_python(data.get("workflowJson") or {}) - except Exception as exc: - raise HTTPException(status_code=400, detail=str(exc)) from exc - config = { - "workflowId": workflow_id, - "enabled": req.enabled, - "protocol": req.protocol, - "host": req.host, - "port": req.port, - "format": req.msg_format, - "inputKey": req.input_key, - "updatedAt": int(time.time() * 1000), - } - await WorkflowStore.put_config(workflow_id, config, kind="workflow_syslog_config") + config = req.model_dump(by_alias=True) + config["updatedAt"] = int(time.time() * 1000) triggers = await _get_workflow_trigger_defs(workflow_id, data) - unified_trigger = TriggerDefinition.model_validate( - { - "id": _legacy_singleton_trigger_id(triggers, "syslog"), - "type": "syslog", - "enabled": req.enabled, - "source": { - "protocol": req.protocol, - "host": req.host, - "port": req.port, - "format": req.msg_format, - }, - "mapping": { - req.input_key or "syslog_message": "$.body", - }, - "updatedAt": config["updatedAt"], - } - ) - updated_triggers = _replace_or_append_trigger(triggers, unified_trigger) - _validate_trigger_type_constraints(updated_triggers) - await _persist_workflow_triggers( - workflow_id, - data, - updated_triggers, - ) - - from flocks.ingest.syslog.manager import default_manager as _syslog_default_manager - - status = await _syslog_default_manager.restart_workflow(workflow_id) + trigger = legacy_syslog_trigger_from_config(config) + trigger = trigger.model_copy(update={"id": _legacy_singleton_trigger_id(triggers, "syslog")}) + trigger, _ = await _save_trigger_definition(workflow_id, data, triggers, trigger) + status = await _sync_trigger_legacy_state(workflow_id, trigger) state = (status or {}).get("state") if req.enabled and state == "failed": err = (status or {}).get("error") or "listener_bind_failed" diff --git a/flocks/session/agent_policy.py b/flocks/session/agent_policy.py index 535f7def4..3937aca0a 100644 --- a/flocks/session/agent_policy.py +++ b/flocks/session/agent_policy.py @@ -19,6 +19,21 @@ class AgentSessionPolicyError(ValueError): """Raised when an isolated agent is selected in a non-empty session.""" +async def _may_turn_memory_on(session: SessionInfo) -> bool: + """Whether an agent's Memory policy may turn Memory on for ``session``. + + Not for a child its parent keeps out of Memory (Session.create). When the + parent cannot be read, only for a session that keeps Memory already. + """ + parent_id = getattr(session, "parent_id", None) + if not parent_id: + return True + parent = await Session.get_by_id_unfiltered(parent_id) + if parent is None: + return bool(getattr(session, "memory_enabled", False)) + return parent.memory_enabled is not False + + async def prepare_session_for_agent( session: SessionInfo, agent: AgentInfo, @@ -85,7 +100,9 @@ async def prepare_session_for_agent( directory.chmod(0o700) updates["directory"] = str(directory.resolve()) if agent.memory_enabled is not None: - updates["memory_enabled"] = agent.memory_enabled + # The agent's policy, except that it never turns Memory back on + # for a child its parent keeps out of Memory (Session.create). + updates["memory_enabled"] = agent.memory_enabled and await _may_turn_memory_on(current) updated = await Session._update_locked( current.project_id, diff --git a/flocks/session/session.py b/flocks/session/session.py index d8049bf1e..43f8d686c 100644 --- a/flocks/session/session.py +++ b/flocks/session/session.py @@ -578,6 +578,11 @@ async def persist(parent: Optional[SessionInfo] = None) -> SessionInfo: kwargs["owner_user_id"] = parent.owner_user_id if child_owner_username is None: kwargs["owner_username"] = parent.owner_username + if parent.memory_enabled is False: + # A child works on its parent's conversation (a delegated + # subagent, a fork): when the parent keeps nothing in + # Memory, neither does the child, whatever its agent's default. + kwargs["memory_enabled"] = False created = SessionInfo( project_id=project_id, diff --git a/flocks/session/session_loop.py b/flocks/session/session_loop.py index eb915792e..c07557e40 100644 --- a/flocks/session/session_loop.py +++ b/flocks/session/session_loop.py @@ -791,6 +791,38 @@ async def _publish_session_status( "error": str(exc), }) + @classmethod + async def _mark_session_activity(cls, callbacks: "LoopCallbacks", session: SessionInfo) -> None: + """Record activity on *session* (``time.updated``, which session lists sort + by, newest first) and tell clients its record changed. + + Without the event a list already on screen kept its order: ``Session.touch`` + only writes storage, and the WebUI history refreshes on ``session.*`` + events. Announced only when the touch wrote (not for a session archived + meanwhile), and only for a session the session lists show: not a + sub-agent session, nor one they leave out (category ``test``, or + ``hideFromSessionManager`` -- an agent's test run), whose turns would + otherwise put it into lists that never had it. A failure is logged, + never raised: the run goes on either way. + """ + try: + # Session.touch, keeping what was written: the Pro edition's Session, + # which takes this one's place, has a touch that returns nothing. + touched = await Session.update(session.project_id, session.id) + except Exception as exc: + log.warn("loop.session_touch_failed", {"session_id": session.id, "error": str(exc)}) + return + if touched is None or not callbacks.event_publish_callback: + return + from flocks.server.routes.session import _is_hidden_from_session_manager + + if touched.parent_id or touched.category == "test" or _is_hidden_from_session_manager(touched): + return + try: + await callbacks.event_publish_callback("session.updated", {"id": session.id}) + except Exception as exc: + log.debug("loop.session_updated.publish_failed", {"session_id": session.id, "error": str(exc)}) + @classmethod async def _publish_session_notice( cls, @@ -1133,6 +1165,9 @@ async def _run_owned( }) await cls._publish_session_status(callbacks or LoopCallbacks(), session_id, "busy") + # A session continued from the history is the latest activity now: + # session lists (newest activity first) put it on top as it starts. + await cls._mark_session_activity(callbacks or LoopCallbacks(), session) # Run loop iteration from flocks.session.agent_inbox import AgentInbox while True: @@ -1193,8 +1228,8 @@ async def _run_owned( if can_publish_idle: await cls._publish_session_status(callbacks or LoopCallbacks(), session_id, "idle") - # Touch session (update timestamp) - await Session.touch(session.project_id, session_id) + # Touch session (update timestamp), and say so: lists re-sort. + await cls._mark_session_activity(callbacks or LoopCallbacks(), session) # Publish idle event try: diff --git a/flocks/skill/installer.py b/flocks/skill/installer.py index 9dfb9adb2..50e6f93e5 100644 --- a/flocks/skill/installer.py +++ b/flocks/skill/installer.py @@ -1162,13 +1162,17 @@ async def _install_from_url( error="httpx is required to download skills. Run: uv add httpx", ) - # Only https (plain http is allowed just for hosts explicitly allow-listed - # for local testing) and never internal / link-local / metadata targets. + # Only https -- plain http is allowed for this machine's loopback, which + # never leaves the host, and for hosts explicitly allow-listed for local + # testing -- and never internal / link-local / metadata targets. from urllib.parse import urlparse - from flocks.tool.web.webfetch import _internal_allowlist, _ssrf_error + from flocks.tool.web.webfetch import _internal_allowlist, _ssrf_error, is_loopback_host parsed = urlparse(url) - if parsed.scheme.lower() != "https" and (parsed.hostname or "").lower() not in _internal_allowlist(): + scheme = parsed.scheme.lower() + host = (parsed.hostname or "").lower() + plain_http_ok = scheme == "http" and (host in _internal_allowlist() or is_loopback_host(host)) + if scheme != "https" and not plain_http_ok: return SkillInstallResult( success=False, error=f"Skill source URL must use https:// (got {parsed.scheme}://): {url}", @@ -1178,7 +1182,16 @@ async def _install_from_url( return SkillInstallResult(success=False, error=ssrf_error) try: - async with httpx.AsyncClient(timeout=_NETWORK_TIMEOUT_SEC, follow_redirects=True) as client: + # This machine's loopback is reached directly: through a proxy from + # the environment, 127.0.0.1 would be the proxy host's own. A + # transport of our own leaves the environment's proxies out but + # still reads its CA settings (SSL_CERT_FILE / SSL_CERT_DIR). + direct = httpx.AsyncHTTPTransport() if is_loopback_host(host) else None + async with httpx.AsyncClient( + timeout=_NETWORK_TIMEOUT_SEC, + follow_redirects=True, + transport=direct, + ) as client: resp = await client.get(url) if resp.status_code != 200: return SkillInstallResult( diff --git a/flocks/tool/device/intake.py b/flocks/tool/device/intake.py index d0239a3ac..07a59f522 100644 --- a/flocks/tool/device/intake.py +++ b/flocks/tool/device/intake.py @@ -121,20 +121,23 @@ async def ensure_user_device_instances(*, refresh_templates: bool = False) -> in added an instance. Auto-provision one editable instance per user-level template when no instance for the same storage_key exists yet. """ + if refresh_templates: + from flocks.tool.device.plugin_index import list_device_templates + + # The forced rebuild reloads every plugin tool and is the slow part. + # Run it before taking the lock so overlapping syncs share one rebuild + # instead of each queuing a full reload behind the lock; the lock only + # has to cover the existence check and the inserts below. + await asyncio.to_thread(list_device_templates, refresh=True) async with _auto_instance_lock(): - return await _ensure_user_device_instances_unlocked( - refresh_templates=refresh_templates, - ) + return await _ensure_user_device_instances_unlocked() -async def _ensure_user_device_instances_unlocked(*, refresh_templates: bool = False) -> int: +async def _ensure_user_device_instances_unlocked() -> int: await ensure_default_group() existing_storage_keys = {device.storage_key for device in await list_devices()} ignored_storage_keys = await _load_auto_instance_ignored_storage_keys() - user_template_storage_keys = await asyncio.to_thread( - _user_device_template_storage_keys, - refresh_templates=refresh_templates, - ) + user_template_storage_keys = await asyncio.to_thread(_user_device_template_storage_keys) created = 0 from flocks.tool.device.plugin_index import list_device_templates diff --git a/flocks/tool/device/plugin_index.py b/flocks/tool/device/plugin_index.py index eee298374..c5540aa47 100644 --- a/flocks/tool/device/plugin_index.py +++ b/flocks/tool/device/plugin_index.py @@ -7,6 +7,7 @@ from __future__ import annotations import re +import threading from pathlib import Path from typing import Any, Dict, Iterable, Optional @@ -31,23 +32,48 @@ _SAFE_ID = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_-]*$") _SAFE_SERVICE_ID = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$") _template_cache: Optional[list[DeviceTemplate]] = None +# Bumped on every clear so a rebuild that started before the clear never +# stores its older result over it. +_template_cache_epoch = 0 +_template_cache_lock = threading.Lock() + +# Serializes create_custom_device_template's check-then-write. +_custom_template_lock = threading.Lock() + +# Forced runtime refreshes are coalesced, see _refresh_device_plugin_runtime. +_runtime_refresh_cond = threading.Condition() +_runtime_refresh_owner: Optional[int] = None +_runtime_refresh_started = 0 +_runtime_refresh_finished = 0 def clear_device_template_cache() -> None: """Clear the in-process device template cache after plugin changes.""" - global _template_cache - _template_cache = None + global _template_cache, _template_cache_epoch + with _template_cache_lock: + _template_cache = None + _template_cache_epoch += 1 def list_device_templates(*, refresh: bool = False) -> list[DeviceTemplate]: """Return device templates from Hub catalog plus local descriptor discovery.""" global _template_cache - if _template_cache is not None and not refresh: - return list(_template_cache) - if refresh: _refresh_device_plugin_runtime() + with _template_cache_lock: + if _template_cache is not None: + return list(_template_cache) + epoch = _template_cache_epoch + + templates = _build_device_templates() + with _template_cache_lock: + if _template_cache_epoch == epoch: + _template_cache = templates + return list(templates) + + +def _build_device_templates() -> list[DeviceTemplate]: by_key: dict[str, DeviceTemplate] = {} tool_counts = _device_tool_counts() for entry in hub_catalog.list_catalog(plugin_type="device"): @@ -112,9 +138,7 @@ def list_device_templates(*, refresh: bool = False) -> list[DeviceTemplate]: tool_counts=tool_counts, ) - templates = sorted(by_key.values(), key=_sort_key) - _template_cache = templates - return list(templates) + return sorted(by_key.values(), key=_sort_key) def create_custom_device_template(body: CustomDeviceTemplateCreate) -> DeviceTemplate: @@ -149,20 +173,26 @@ def create_custom_device_template(body: CustomDeviceTemplateCreate) -> DeviceTem validated_tools.append((tool_name, tool.model_dump(exclude_none=True))) provider_yaml = _custom_provider_yaml(body) - target.mkdir(parents=True, exist_ok=True) - _write_yaml(target / "_provider.yaml", provider_yaml) - for tool_name, tool_data in validated_tools: - _write_yaml(target / f"{tool_name}.yaml", _custom_tool_yaml(tool_data, service_id)) - - record = hub_local.make_record( - plugin_type="device", - plugin_id=plugin_id, - version=body.version or "0.0.0", - source="custom", - install_path=target, - scope="global", - ) - hub_local.save_installed_record(record) + # Requests run this on worker threads: the existence check, the files and + # the install record are one step, or two requests for the same id both + # pass the check and write over each other. + with _custom_template_lock: + if target.exists() and hub_local.has_install_payload("device", target): + raise FileExistsError(f"device plugin '{plugin_id}' already exists") + target.mkdir(parents=True, exist_ok=True) + _write_yaml(target / "_provider.yaml", provider_yaml) + for tool_name, tool_data in validated_tools: + _write_yaml(target / f"{tool_name}.yaml", _custom_tool_yaml(tool_data, service_id)) + + record = hub_local.make_record( + plugin_type="device", + plugin_id=plugin_id, + version=body.version or "0.0.0", + source="custom", + install_path=target, + scope="global", + ) + hub_local.save_installed_record(record) _refresh_device_plugin_runtime() @@ -173,13 +203,80 @@ def create_custom_device_template(body: CustomDeviceTemplateCreate) -> DeviceTem def _refresh_device_plugin_runtime() -> None: - """Refresh both device descriptors and runtime tool registrations.""" - clear_device_template_cache() + """Refresh both device descriptors and runtime tool registrations. + + A refresh reloads every plugin tool and can take many seconds, and the + device page, Hub actions and custom templates all ask for one. Overlapping + callers share the work instead of queuing a reload each: a caller returns + once a reload that started after it asked has finished (so a change it made + just before is picked up), and every caller arriving while a reload runs + shares the next one. Any number of overlapping requests costs at most two + reloads. + """ + global _runtime_refresh_owner, _runtime_refresh_started, _runtime_refresh_finished + me = threading.get_ident() + with _runtime_refresh_cond: + if _runtime_refresh_owner == me: + # Asked again from inside our own reload: waiting would deadlock. + run = None + else: + wanted = _runtime_refresh_started + 1 + while _runtime_refresh_finished < wanted and _runtime_refresh_owner is not None: + _runtime_refresh_cond.wait() + if _runtime_refresh_finished >= wanted: + return + _runtime_refresh_owner = me + _runtime_refresh_started += 1 + run = _runtime_refresh_started + if run is None: + _reload_device_plugin_runtime() + return + + reloaded = False + try: + reloaded = _reload_device_plugin_runtime() + finally: + with _runtime_refresh_cond: + _runtime_refresh_owner = None + if reloaded: + _runtime_refresh_finished = run + # A failed reload counts for nobody: the next waiter runs its own. + _runtime_refresh_cond.notify_all() + + +def _reload_device_plugin_runtime() -> bool: + """Reload descriptors and plugin tools, then swap in a rebuilt template index. + + Returns False when the tool reload failed. The index is rebuilt here, while + the caller still owns the reload: building it reads the tool registry, whose + lock the next queued reload would otherwise hold, keeping this reload's + callers waiting for that one too. Readers keep the previous index during the + reload instead of rebuilding from a half-reloaded registry. + """ + global _template_cache, _template_cache_epoch + with _template_cache_lock: + epoch = _template_cache_epoch discover_api_service_descriptors(refresh=True) + reloaded = True try: - ToolRegistry.refresh_plugin_tools() - except Exception as exc: # pragma: no cover - defensive runtime isolation + # The page asks on every return to the window; with no plugin file + # changed since the last clean load the registry is already current. + ToolRegistry.refresh_plugin_tools_if_changed() + except Exception as exc: # defensive runtime isolation: log, keep serving log.warn("device.templates.tool_refresh_failed", {"error": str(exc)}) + reloaded = False + try: + templates = _build_device_templates() + except Exception: + clear_device_template_cache() # the registry moved on; never keep the old index + raise + with _template_cache_lock: + # A clear during the reload (Hub install, file watcher) may postdate our + # scan: leave the index empty for the next reader to rebuild then. + _template_cache = templates if _template_cache_epoch == epoch else None + # Builds started before or during the reload must not overwrite this one. + _template_cache_epoch += 1 + return reloaded def _template_from_plugin_root( diff --git a/flocks/tool/registry.py b/flocks/tool/registry.py index ccf3b61c9..ace71899f 100644 --- a/flocks/tool/registry.py +++ b/flocks/tool/registry.py @@ -15,11 +15,25 @@ import threading import time from concurrent.futures import TimeoutError as FuturesTimeoutError +from contextlib import asynccontextmanager, contextmanager from dataclasses import dataclass from dataclasses import field as dataclass_field from enum import Enum from pathlib import Path -from typing import Any, Awaitable, Callable, Dict, List, Literal, Mapping, Optional, Set +from typing import ( + Any, + AsyncIterator, + Awaitable, + Callable, + Dict, + Iterator, + List, + Literal, + Mapping, + NamedTuple, + Optional, + Set, +) from pydantic import BaseModel, Field, field_validator from pydantic_core import PydanticCustomError @@ -1020,6 +1034,17 @@ async def execute(self, ctx: ToolContext, **kwargs) -> ToolResult: ) +class _RegistryState(NamedTuple): + """What a registry read needs: the live attributes, or a reload's copy of them.""" + + tools: Mapping[str, Tool] + enabled_defaults: Mapping[str, bool] + dynamic_tools_by_module: Mapping[str, List[str]] + revision: int + # Thread that published a reload copy; 0 for the live registry. + owner: int = 0 + + class ToolRegistry: """ Tool Registry - manages tool registration and execution @@ -1089,9 +1114,26 @@ class ToolRegistry: _config_state_token: Optional[tuple[str, int, int, int]] = None _failure_state: Dict[str, Dict[str, Any]] = {} _failure_disable_threshold: int = 3 + # Guards _failure_state only: tool calls touch it after every run, and + # they must not queue behind a reload holding _refresh_lock. + _failure_lock = threading.Lock() _init_lock = threading.Lock() _refresh_lock = threading.RLock() _initializing_thread_id: Optional[int] = None + # A plugin or dynamic tool reload holds _refresh_lock while it re-reads + # every source, which takes seconds (minutes on a slow machine). Reads on + # other threads use this copy of the registry as it was before the reload + # instead of waiting for it; see _reading. Set and cleared under the lock. + _reload_view: Optional[_RegistryState] = None + # How long a read waits on _refresh_lock before looking again for a + # reload's copy: a reload publishes it just after taking the lock. + _READ_WAIT_SLICE_SECONDS = 0.05 + # The plugin files the last plugin load read, when it reported no error + # (_plugin_sources_fingerprint); refresh_plugin_tools_if_changed skips a + # reload that would read the same files again. None after a failed or + # partial load, so asking again retries it. + _plugin_sources_stamp: Optional[tuple] = None + _PLUGIN_SOURCES_MAX_DEPTH = 8 # Snapshot of every tool's factory-default ``enabled`` flag — captured # in :meth:`register` at the moment the tool object is handed to the @@ -1111,6 +1153,107 @@ class ToolRegistry: # leaking across ``refresh_plugin_tools`` cycles). _enabled_defaults: Dict[str, bool] = {} + @classmethod + def _foreign_reload_view(cls) -> Optional[_RegistryState]: + """The copy published by a reload running on another thread, if any.""" + view = cls._reload_view + if view is not None and view.owner != threading.get_ident(): + return view + return None + + @classmethod + def _lock_or_reload_view(cls) -> Optional[_RegistryState]: + """Take ``_refresh_lock``, unless another thread's reload holds it. + + Returns None once the caller holds the lock, or the reload's copy of + the registry without taking it. Request handlers and tool calls read + the registry on the event loop: waiting out a reload there stops every + request on the server until it ends. + """ + lock = cls._refresh_lock + while True: + view = cls._foreign_reload_view() + if view is not None: + return view + if lock.acquire(timeout=cls._READ_WAIT_SLICE_SECONDS): + return None + + @classmethod + @contextmanager + def _reading(cls) -> Iterator[_RegistryState]: + """Read one consistent registry state without waiting for a reload. + + Outside a reload this is the live registry under ``_refresh_lock``, as + before. While another thread reloads, it is the registry as it was + before that reload began: a reload unregisters every plugin tool and + loads them again one by one, so the live dicts are incomplete until it + ends. The reloading thread itself reads the live registry. + """ + view = cls._lock_or_reload_view() + if view is not None: + yield view + return + try: + yield _RegistryState( + tools=cls._tools, + enabled_defaults=cls._enabled_defaults, + dynamic_tools_by_module=cls._dynamic_tools_by_module, + revision=cls._revision, + ) + finally: + cls._refresh_lock.release() + + @classmethod + @asynccontextmanager + async def write_lock(cls) -> AsyncIterator[None]: + """Hold ``_refresh_lock`` for a short write made on the event loop. + + A reload holds the lock for seconds, and blocking on it on the event + loop stops every request on the server; this waits for it + asynchronously instead. The body must not await: the lock then + belongs to the loop's thread, which every coroutine shares. + + The registry is initialized first: init() holds _init_lock and takes + this lock to register each tool, so initializing from inside the + block (get() does on first use) would wait on it the other way round. + """ + if not cls._initialized and cls._initializing_thread_id != threading.get_ident(): + await cls.init_async() + while not cls._refresh_lock.acquire(blocking=False): + await asyncio.sleep(cls._READ_WAIT_SLICE_SECONDS) + try: + yield + finally: + cls._refresh_lock.release() + + @classmethod + @contextmanager + def _publishing_reload_view(cls) -> Iterator[None]: + """Let other threads read the pre-reload registry while the caller reloads. + + The caller holds ``_refresh_lock`` for the whole reload. The copy is + shallow: tools keep their identity, so a tool's ``info`` is the same + object in the copy and in the live registry. + """ + if cls._reload_view is not None: + # A reload inside our own reload: the outer copy stays in force. + yield + return + cls._reload_view = _RegistryState( + tools=dict(cls._tools), + enabled_defaults=dict(cls._enabled_defaults), + dynamic_tools_by_module={ + module_name: list(tool_names) + for module_name, tool_names in cls._dynamic_tools_by_module.items() + }, + revision=cls._revision, + owner=threading.get_ident(), + ) + try: + yield + finally: + cls._reload_view = None + @classmethod def _core_definition_paths(cls) -> List[Path]: package_root = Path(__file__).resolve().parents[1] @@ -1223,8 +1366,8 @@ def revision(cls) -> int: """ cls._ensure_initialized() cls._sync_configured_enabled_states() - with cls._refresh_lock: - return cls._revision + with cls._reading() as state: + return state.revision @classmethod def _current_config_state_token(cls) -> tuple[str, int, int, int]: @@ -1253,7 +1396,13 @@ def _sync_configured_enabled_states(cls) -> None: except Exception: return - with cls._refresh_lock: + if token == cls._config_state_token: + return + if cls._lock_or_reload_view() is not None: + # Another thread is reloading and holds the lock until it ends; + # the first read after the reload applies the changed config. + return + try: if token == cls._config_state_token: return @@ -1279,6 +1428,8 @@ def _sync_configured_enabled_states(cls) -> None: cls._reset_failure_state(name) if changed_names: cls._bump_revision("config_enabled_state_sync") + finally: + cls._refresh_lock.release() @classmethod def _bump_revision(cls, reason: str) -> None: @@ -1367,16 +1518,16 @@ def get(cls, name: str) -> Optional[Tool]: """Get a tool by name""" cls._ensure_initialized() cls._sync_configured_enabled_states() - with cls._refresh_lock: - return cls._tools.get(name) + with cls._reading() as state: + return state.tools.get(name) @classmethod def list_tools(cls, category: Optional[ToolCategory] = None) -> List[ToolInfo]: """List all registered tools, optionally filtered by category""" cls._ensure_initialized() cls._sync_configured_enabled_states() - with cls._refresh_lock: - tools = list(cls._tools.values()) + with cls._reading() as state: + tools = list(state.tools.values()) if category: tools = [t for t in tools if t.info.category == category] return [t.info for t in tools] @@ -1437,7 +1588,13 @@ async def execute( error=denial_reason, ) - tool = cls.get(tool_name) + # Which tool runs, and whether it may, is decided on the registry as it + # stands with the config applied, as before: a running reload is waited + # out here, without blocking the event loop. Only listings read the + # pre-reload copy; a call must not run a tool the reload or a config + # change written meanwhile switched off. + async with cls.write_lock(): + tool = cls.get(tool_name) if not tool: return ToolResult( success=False, @@ -1520,7 +1677,6 @@ async def execute( success=False, error=f"Tool is disabled: {tool_name}" ) - if device_id: # Per-device tool enable gate: a device instance may carry a # disabled override independent of the shared global tool state. @@ -1570,7 +1726,12 @@ async def execute( # them would switch the tool off for everyone after three. disabled = False elif await cls._failure_auto_disable_enabled(): - disabled = cls._record_failure(tool, kwargs, result.error) + # Counted on the loop with the registry lock, as before, so + # the config write stays in line with the other config + # writers here; a running reload is waited out without + # blocking the loop, and the count sees what happened meanwhile. + async with cls.write_lock(): + disabled = cls._record_failure(tool, kwargs, result.error) else: cls._reset_failure_state(tool_name) disabled = False @@ -1694,25 +1855,25 @@ async def execute_batch( def all_tool_ids(cls) -> List[str]: """Get all registered tool IDs""" cls._ensure_initialized() - with cls._refresh_lock: - return list(cls._tools.keys()) + with cls._reading() as state: + return list(state.tools.keys()) @classmethod def snapshot_identity(cls) -> tuple[int, tuple[str, ...]]: """Return a revision/tool-id identity from one consistent registry state.""" cls._ensure_initialized() cls._sync_configured_enabled_states() - with cls._refresh_lock: - return cls._revision, tuple(cls._tools.keys()) + with cls._reading() as state: + return state.revision, tuple(state.tools.keys()) @classmethod def get_dynamic_tools_by_module(cls) -> Dict[str, List[str]]: """Return a copy of the dynamic-module → tool-names mapping.""" cls._ensure_initialized() - with cls._refresh_lock: + with cls._reading() as state: return { module_name: list(tool_names) - for module_name, tool_names in cls._dynamic_tools_by_module.items() + for module_name, tool_names in state.dynamic_tools_by_module.items() } @classmethod @@ -1751,7 +1912,9 @@ def init(cls) -> None: cls._register_builtin_tools() cls._register_dynamic_tools() cls._register_plugin_extension_point() + sources = cls._plugin_sources_fingerprint() cls._plugin_load_errors = cls._load_plugin_tools() + cls._plugin_sources_stamp = None if cls._plugin_load_errors else sources cls._initialized = True log.debug("tool_registry.initialized", {"count": len(cls._tools)}) finally: @@ -2013,8 +2176,8 @@ def get_default_enabled(cls, name: str) -> Optional[bool]: (e.g. dynamic tools registered after init). Callers should fall back to the live ``ToolInfo.enabled`` in that case. """ - with cls._refresh_lock: - return cls._enabled_defaults.get(name) + with cls._reading() as state: + return state.enabled_defaults.get(name) @classmethod def _apply_tool_settings(cls) -> None: @@ -2333,6 +2496,79 @@ def start_watcher(cls) -> None: cls._watcher = ToolFileWatcher() cls._watcher.start() + @classmethod + def _plugin_source_roots(cls) -> List[str]: + """The plugin roots a plugin load reads from (the ones the file watcher watches).""" + from flocks.config.config import get_user_plugins_root + from flocks.plugin.loader import PluginLoader + + return sorted({ + str(PluginLoader._plugin_root), + str(get_user_plugins_root()), + str(Path.cwd() / ".flocks" / "plugins"), + }) + + @classmethod + def _plugin_sources_fingerprint(cls) -> tuple: + """Path, size, mtime and inode of every file under the plugin roots. + + A plugin load reads tool files, the handler scripts and + ``_provider.yaml`` files beside them and Python plugin modules, all + under these roots. Directories are followed through symlinks, as the + loader does, to a bounded depth; ``__pycache__`` is left out. + + It also runs the ``flocks.plugins`` entry points of installed + packages: installing, removing or upgrading a package changes its + site-packages directory, whose mtime is part of the fingerprint. + """ + entries: list = [] + for path in sys.path: + if not path or os.path.basename(os.path.normpath(path)) not in ("site-packages", "dist-packages"): + continue + try: + stat = os.stat(path) + except OSError: + continue + entries.append((path, -1, stat.st_mtime_ns, stat.st_ino)) + for root in cls._plugin_source_roots(): + pending = [(root, 0)] + while pending: + directory, depth = pending.pop() + try: + with os.scandir(directory) as scan: + children = list(scan) + except OSError: + continue + for child in children: + try: + if child.is_dir(): + if child.name != "__pycache__" and depth < cls._PLUGIN_SOURCES_MAX_DEPTH: + pending.append((child.path, depth + 1)) + continue + stat = child.stat() + except OSError: + continue + entries.append((child.path, stat.st_size, stat.st_mtime_ns, stat.st_ino)) + entries.sort() + return tuple(entries) + + @classmethod + def refresh_plugin_tools_if_changed(cls) -> bool: + """Reload plugin tools unless no plugin file changed since the last clean load. + + For callers that reload only to pick up changes made elsewhere, such + as the device page each time the window comes back. A reload re-reads + every source and runs the plugin entry points again, which takes + seconds of CPU; with nothing changed it rebuilds what is there. A load + that reported an error is never current, so asking again retries it. + Returns whether a reload ran. + """ + stamp = cls._plugin_sources_stamp + if stamp is not None and stamp == cls._plugin_sources_fingerprint(): + return False + cls.refresh_plugin_tools() + return True + @classmethod def refresh_plugin_tools(cls, changed_path: Optional[Path] = None) -> List[str]: """Reload plugin tools (YAML + Python) from disk. @@ -2341,9 +2577,15 @@ def refresh_plugin_tools(cls, changed_path: Optional[Path] = None) -> List[str]: correctly removed from the registry. When a Hub operation supplies ``changed_path``, source failures outside that path are isolated and do not block the operation; failures inside it still roll back. + + Other threads keep reading the registry as it was before the reload + until it ends (``_publishing_reload_view``); only writers wait. """ cls._ensure_initialized() - with cls._refresh_lock: + with cls._refresh_lock, cls._publishing_reload_view(): + # Taken before reading, so a file changed during the load still + # counts as changed next time. + sources = cls._plugin_sources_fingerprint() tools_before = cls._tools.copy() defaults_before = cls._enabled_defaults.copy() plugin_names_before = list(cls._plugin_tool_names) @@ -2403,17 +2645,20 @@ def _restore_snapshot() -> None: cls._finalize_plugin_tools_load() cls._plugin_load_errors = load_errors + cls._plugin_sources_stamp = None if load_errors else sources cls._bump_revision("plugin_refresh") return cls.all_tool_ids() except Exception: _restore_snapshot() + # The files no longer match the restored registry. + cls._plugin_sources_stamp = None raise @classmethod def refresh_dynamic_tools(cls) -> List[str]: """Reload dynamically generated tools and return tool ids.""" cls._ensure_initialized() - with cls._refresh_lock: + with cls._refresh_lock, cls._publishing_reload_view(): tools_before = cls._tools.copy() defaults_before = cls._enabled_defaults.copy() dynamic_modules_before = cls._dynamic_modules.copy() @@ -2448,7 +2693,7 @@ def refresh_dynamic_tools(cls) -> List[str]: @classmethod def _reset_failure_state(cls, tool_name: str) -> None: """Reset failure tracking for a tool after success.""" - with cls._refresh_lock: + with cls._failure_lock: cls._failure_state.pop(tool_name, None) @classmethod @@ -2514,7 +2759,7 @@ def _record_failure(cls, tool: Tool, params: Dict[str, Any], error: Optional[str tool_name = tool.info.name key = cls._failure_key(tool_name, params, error) - with cls._refresh_lock: + with cls._failure_lock: state = cls._failure_state.get(tool_name, {"key": None, "count": 0}) if state.get("key") == key: @@ -2523,27 +2768,34 @@ def _record_failure(cls, tool: Tool, params: Dict[str, Any], error: Optional[str state = {"key": key, "count": 1} cls._failure_state[tool_name] = state + count = state["count"] - if state["count"] >= cls._failure_disable_threshold and tool.info.enabled: - tool.info.enabled = False - try: - from flocks.config.config_writer import ConfigWriter + if count < cls._failure_disable_threshold: + return False + # Switching the tool off is an enabled-state change like any other: + # under _refresh_lock, so it waits for a running reload rather than + # being undone by that reload's rollback. (_refresh_lock before + # _failure_lock, the order _sync_configured_enabled_states takes them.) + with cls._refresh_lock: + if not tool.info.enabled: + return False + tool.info.enabled = False + try: + from flocks.config.config_writer import ConfigWriter - ConfigWriter.set_tool_setting(tool_name, {"enabled": False}) - except Exception as exc: - log.warn("tool.disabled.repeated_error.persist_failed", { - "tool": tool_name, - "error": str(exc), - }) - cls._bump_revision("failure_auto_disable") - log.warn("tool.disabled.repeated_error", { + ConfigWriter.set_tool_setting(tool_name, {"enabled": False}) + except Exception as exc: + log.warn("tool.disabled.repeated_error.persist_failed", { "tool": tool_name, - "count": state["count"], - "error": error, + "error": str(exc), }) - return True - - return False + cls._bump_revision("failure_auto_disable") + log.warn("tool.disabled.repeated_error", { + "tool": tool_name, + "count": count, + "error": error, + }) + return True @classmethod def _generated_tools_dirs(cls) -> List[Path]: @@ -2730,7 +2982,6 @@ def __init__(self) -> None: self._observer: Optional[object] = None self._debounce_timer: Optional[threading.Timer] = None self._lock = threading.Lock() - self._loop: Optional[asyncio.AbstractEventLoop] = None # ---- public ---- @@ -2748,13 +2999,6 @@ def start(self) -> None: ) return - # Capture the running event loop so _do_refresh can safely schedule - # back onto it from the watchdog daemon thread. - try: - self._loop = asyncio.get_event_loop() - except RuntimeError: - self._loop = None - watch_dirs = self._collect_watch_dirs() if not watch_dirs: log.info("tool.watcher.no_dirs", {"msg": "no tool plugin directories to watch"}) @@ -2823,12 +3067,11 @@ def _schedule_refresh(self, *, device_changed: bool = False) -> None: self._debounce_timer.start() def _do_refresh(self) -> None: - # Schedule onto the asyncio event loop thread to avoid concurrent - # modification of _tools while request handlers may be reading it. - if self._loop is not None and self._loop.is_running(): - self._loop.call_soon_threadsafe(self._run_refresh) - else: - self._run_refresh() + # On the debounce timer's own thread. A reload takes seconds: run on + # the event loop it held up every request on the server until it + # ended. Readers meanwhile get the registry as it was before the + # reload (ToolRegistry._reading) and writers take the lock. + self._run_refresh() def _run_refresh(self) -> None: try: diff --git a/flocks/tool/tool_loader.py b/flocks/tool/tool_loader.py index 03d42a724..54d60c262 100644 --- a/flocks/tool/tool_loader.py +++ b/flocks/tool/tool_loader.py @@ -89,7 +89,11 @@ def _load_provider_config(yaml_path: Path) -> Optional[Dict[str, Any]]: if not provider_file.is_file(): return None try: - data = yaml.safe_load(provider_file.read_text(encoding="utf-8")) + # Read once per tool on every plugin reload: libyaml when available. + data = yaml.load( + provider_file.read_text(encoding="utf-8"), + Loader=getattr(yaml, "CSafeLoader", yaml.SafeLoader), + ) return data if isinstance(data, dict) else None except Exception as e: log.warn("tool.provider.load_failed", { diff --git a/flocks/tool/web/webfetch.py b/flocks/tool/web/webfetch.py index 6a4c43fea..597cb68a2 100644 --- a/flocks/tool/web/webfetch.py +++ b/flocks/tool/web/webfetch.py @@ -31,10 +31,11 @@ MAX_TIMEOUT = 120 # seconds MAX_REDIRECTS = 5 -# SSRF guard: webfetch must not reach loopback / private / link-local / reserved -# networks (including the cloud metadata endpoint 169.254.169.254). Operators can -# allow specific internal hosts/IPs for local testing via a comma-separated env -# list, e.g. FLOCKS_WEBFETCH_ALLOW_INTERNAL="127.0.0.1,localhost". +# SSRF guard: webfetch must not reach private / link-local / reserved networks +# (including the cloud metadata endpoint 169.254.169.254). This machine's own +# loopback (localhost, 127.0.0.0/8, ::1) stays reachable: local services and +# proxies listen there. Operators can allow specific internal hosts/IPs via a +# comma-separated env list, e.g. FLOCKS_WEBFETCH_ALLOW_INTERNAL="10.0.0.5,intranet.example". _ALLOW_INTERNAL_ENV = "FLOCKS_WEBFETCH_ALLOW_INTERNAL" @@ -43,14 +44,40 @@ def _internal_allowlist() -> set[str]: return {token.strip().lower() for token in raw.split(",") if token.strip()} +def _is_loopback_address(addr: ipaddress.IPv4Address | ipaddress.IPv6Address) -> bool: + """127.0.0.0/8 or ::1, also written as an IPv4-mapped IPv6 address.""" + if addr.is_loopback: + return True + mapped = getattr(addr, "ipv4_mapped", None) + return mapped is not None and mapped.is_loopback + + +def is_loopback_host(host: Optional[str]) -> bool: + """Whether *host* names this machine's loopback: ``localhost``, + ``*.localhost``, 127.0.0.0/8 or ``::1`` (bracketed or not, an IPv6 zone + included). Anything else with a ``%`` in it is a name, not an address + (``127.0.0.1%25.example.com``).""" + normalized = (host or "").strip().lower().rstrip(".") + if normalized.startswith("[") and normalized.endswith("]"): + normalized = normalized[1:-1] + if normalized == "localhost" or normalized.endswith(".localhost"): + return True + try: + addr = ipaddress.ip_address(normalized) + except ValueError: + return False + return _is_loopback_address(addr) + + def _ip_is_internal(ip: str) -> bool: try: addr = ipaddress.ip_address(ip) except ValueError: return False + if _is_loopback_address(addr): + return False return ( addr.is_private - or addr.is_loopback or addr.is_link_local or addr.is_reserved or addr.is_multicast @@ -62,9 +89,10 @@ def _ssrf_error(url: str) -> Optional[str]: """Return an error message if *url* resolves to an internal address. DNS-resolves the host and rejects the request when any resolved address is - loopback/private/link-local/reserved, so a public hostname that points at an - internal IP (DNS rebinding) is also caught. Returns None when the target is - allowed. Resolution failures return None so the request fails naturally with + private/link-local/reserved, so a public hostname that points at an internal + IP (DNS rebinding) is also caught; loopback addresses are allowed. Returns + None when the target is allowed. Resolution failures return None so the + request fails naturally with the normal "Request failed" path rather than being masked as an SSRF block. """ parsed = urlparse(url) @@ -91,7 +119,7 @@ def _ssrf_error(url: str) -> Optional[str]: if _ip_is_internal(ip): return ( f"Blocked request to internal or reserved address ({ip}). " - "webfetch does not allow access to loopback, private, link-local, " + "webfetch does not allow access to private, link-local, " "or metadata networks." ) return None diff --git a/flocks/updater/enterprise.py b/flocks/updater/enterprise.py index 344d9cdc6..37939559d 100644 --- a/flocks/updater/enterprise.py +++ b/flocks/updater/enterprise.py @@ -52,6 +52,7 @@ from flocks.updater.handoff_progress import summarize_error from flocks.updater.installation_status import ( installation_result_id, + installation_result_mark, installation_result_path, read_installation_result, scrub_credentials, @@ -616,6 +617,20 @@ def _installation_outcome(state: dict[str, Any]) -> dict[str, Any] | None: return read_installation_result() or {"recovery": "unknown"} +def _installer_recorded_done(state: dict[str, Any]) -> bool: + """The installer's own record of this run says done: it writes that once the release it put in + place serves, whatever becomes of its exit status after. Not said of a run that did not note + which record was there before it, nor from a record that cannot be read.""" + prior = state.get("prior_result", "unreadable") + if prior == "unreadable": + return False + try: + mark = installation_result_mark() + except (OSError, ValueError): + return False + return mark is not None and mark[0] != prior and mark[1] == "done" + + def _explain_failure(state: dict[str, Any]) -> None: """Where a failed upgrade stopped and why, for whoever reads it: the step, the reason in the installer's words, how the machine was left and the end of the log.""" @@ -793,6 +808,11 @@ def read_state() -> dict[str, Any] | None: if code is not None: state["phase"] = "finished" if code == 0 else "failed" state["exit_code"] = code + elif _installer_recorded_done(state): + # No exit status, and the machine is switched over: it did not come back. The Windows + # installer writes it last, from a console window that can hold it there for as long as + # its user selects text in it, or be closed on it. + state["phase"] = "finished" elif not _pid_alive(int(state.get("pid") or 0)): # Gone without saying how it ended (the machine restarted under it). state["phase"] = "failed" @@ -1027,7 +1047,7 @@ def start_installer(path: Path, offer: InstallerOffer, attempt: str | None = Non if _WINDOWS: return _start_windows_installer(path, offer, attempt) if run_by_systemd(): - raise EnterpriseUpgradeError(f"这台机器由 systemd 管,要以 root 执行:{installer_command(str(path))}") + raise EnterpriseUpgradeError(f"当前开源版由 systemd 管理,请使用 root 权限运行:{installer_command(str(path))}") if not install_root_ready(): raise EnterpriseUpgradeError(f"先用 root 执行一次:{prepare_command()}") prior_result = _prior_installation_result() diff --git a/flocks/updater/enterprise_application.py b/flocks/updater/enterprise_application.py index 2a758456d..44a71d5b5 100644 --- a/flocks/updater/enterprise_application.py +++ b/flocks/updater/enterprise_application.py @@ -22,6 +22,11 @@ A licence no longer valid is no licence here: the machine may apply again, and the licence taken replaces the old one. One Console renewed needs none of that: a sync with Console brings the renewal into the file (sync_licence), as the hourly heartbeat does. + +A machine that cannot reach Console applies offline: the page hands it an application to send to +whoever issues licences (offline_application: the form, and the machine the licence is to be bound to), +and imports the licence file they send back (import_licence: the license.json Console's offline issue +downloads, or the bare token), written where taking an approved application writes it. """ from __future__ import annotations @@ -29,6 +34,8 @@ import asyncio import json import os +import platform +import re import shutil import tempfile import time @@ -39,11 +46,18 @@ import httpx -from flocks.console.previous_licence import find_licence_file, licence_token +from flocks.console.previous_licence import ( + LICENCE_FILE_LOCK, + find_licence_file, + licence_token, + moment, + terms_in_force, + token_header, +) from flocks.storage.storage import Storage from flocks.updater import enterprise from flocks.updater.enterprise import EnterpriseUpgradeError -from flocks.updater.machine_fingerprint import MachineIdUnreadable, machine_fingerprint +from flocks.updater.machine_fingerprint import MachineIdUnreadable, machine_fingerprints, machine_names from flocks.utils.log import Log log = Log.create(service="updater.enterprise_application") @@ -275,7 +289,7 @@ async def _apply(form: dict[str, Any], applied_by: str) -> dict[str, Any]: raise EnterpriseUpgradeError("已经有一份申请在审核或等着启用,处理完再申请") base, session = _console_base(), await _console_session() try: - machine = await asyncio.to_thread(machine_fingerprint) + machine, machine_kind, devid = await asyncio.to_thread(machine_names) except MachineIdUnreadable as exc: # Sent without it, the licence would not be bound to this machine although it could be. raise EnterpriseUpgradeError(f"读不到这台机器的标识,先处理好再申请:{exc}") from exc @@ -304,8 +318,12 @@ async def _apply(form: dict[str, Any], applied_by: str) -> dict[str, Any]: "applied_by": applied_by, # The host as the enterprise core names it: Console binds the licence it issues to it, and the # core runs on that licence on this machine only. None for a host that keeps no identifier, - # which Console shows the operator. + # which Console shows the operator. machine_kind says which fingerprint it is, for whoever + # reviews: the machine-id digest, which every enterprise core reads, or the device id of a + # host that keeps no machine id. devid is the device id beside it, for Console's records. "machine": machine or None, + "machine_kind": machine_kind or None, + "devid": devid or None, } payload = { # The machine, as Console knows it from the sign-in: Console holds one open application @@ -454,18 +472,20 @@ async def _take(request_id: str) -> dict[str, Any]: # This very token on the machine already (taken twice, or a retry): the file stands, with the # patches it has gathered; Console still hears of it below. if token != held_token: - now = int(time.time()) - _keep_replaced_licence(licence_file(), now) - _write_licence(licence_file(), { - "license_id": issued, - "key": token, - "payload": {}, - "patches": [], - "activated_at": now, - "install_id": session.get("install_id"), - "fingerprint": session.get("fingerprint"), - "request_id": request_id, - }) + # Under the lock the heartbeat writes under: it must not put the file it read back over this one. + with LICENCE_FILE_LOCK: + now = int(time.time()) + _keep_replaced_licence(licence_file(), now) + _write_licence(licence_file(), { + "license_id": issued, + "key": token, + "payload": {}, + "patches": [], + "activated_at": now, + "install_id": session.get("install_id"), + "fingerprint": session.get("fingerprint"), + "request_id": request_id, + }) log.info("enterprise.licence_taken", {"request_id": request_id, "license_id": issued}) if _status(record) == "approved": try: @@ -525,3 +545,171 @@ async def _sync_licence() -> dict[str, bool]: changed = after is not None and any(before.get(term) != after.get(term) for term in terms) log.info("enterprise.licence_synced", {"license_id": before["license_id"], "changed": changed}) return {"changed": changed} + + +#: A licence file is a few kilobytes; anything far bigger is not one. +MAX_LICENCE_CHARS = 256 * 1024 +#: The bare token, as an operator may copy it out of Console instead of downloading the file. +_BARE_TOKEN = re.compile(r"^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*$") +#: What the application file says it is, for whoever reads it. +OFFLINE_APPLICATION_FORMAT = "flocks-licence-application/1" + + +def _licence_document(content: str) -> dict[str, Any]: + """The licence file as sent: the license.json Console's offline issue downloads, or its bare token.""" + text = content.strip().lstrip("\ufeff") + if not text: + raise EnterpriseUpgradeError("授权文件是空的") + if len(text) > MAX_LICENCE_CHARS: + raise EnterpriseUpgradeError("这不是授权文件:内容太大") + if _BARE_TOKEN.match(text): + return {"key": text} + try: + data = json.loads(text) + except ValueError as exc: + raise EnterpriseUpgradeError("这不是授权文件:内容既不是 JSON,也不是授权令牌") from exc + if not isinstance(data, dict): + raise EnterpriseUpgradeError("这不是授权文件:内容不是 JSON 对象") + return data + + +async def import_licence(content: str) -> dict[str, Any]: + """Write a licence file sent back for an offline application on this machine, after the checks that + can be made here; the enterprise core verifies its signature when the machine moves.""" + async with _lock: + return await _import_licence(content) + + +async def _import_licence(content: str) -> dict[str, Any]: + if not enterprise.available(): + raise EnterpriseUpgradeError("这台机器已经是企业版:授权在企业版的 Flocks Pro 页导入") + data = _licence_document(content) + token, claims = licence_token(data) + if not token: + raise EnterpriseUpgradeError("这个文件里没有授权令牌,不是 Console 签发的授权文件") + header = token_header(token) or {} + if str(header.get("alg") or "").upper() != "ES256": + raise EnterpriseUpgradeError("授权令牌不是 Console 签发的格式") + issued = str(claims.get("license_id") or "").strip() + if not issued: + raise EnterpriseUpgradeError("授权令牌里没有授权编号") + named = str(data.get("license_id") or "").strip() + if named and named != issued: + raise EnterpriseUpgradeError(f"文件写的授权编号 {named} 和令牌里的 {issued} 对不上") + payload = data.get("payload") if isinstance(data.get("payload"), dict) else {} + # The core takes the file's payload only as a copy of the token's own (go/internal/license/legacy.go). + if payload and payload != claims: + raise EnterpriseUpgradeError("文件里的 payload 和授权令牌对不上,文件可能被改过") + patches = [item for item in data.get("patches") or [] if isinstance(item, str)] if isinstance(data.get("patches"), list) else [] + record = {"license_id": issued, "key": token, "payload": payload, "patches": patches} # secret-guard: allow 误报:key 字段存的是上传文件里的令牌变量 + # A token bound to another machine is refused before anything is written, the same token already on + # this machine too (a data directory moved from that machine, say). + machine = str(claims.get("machine") or "").strip().lower() + if machine: + ours = await asyncio.to_thread(machine_fingerprints) + # A host whose fingerprints cannot be read now is not refused here: the core judges the binding. + if ours and machine not in ours: + raise EnterpriseUpgradeError("这份授权绑定的是另一台机器:请用这台机器的申请信息重新申请") + again = await asyncio.to_thread(_import_again, token, patches) + if again is not None: + # This very token is on the machine already (imported twice, or taken before): the file stands, with + # the patches it has gathered and the ones it lacked, and is judged as it now is -- a renewal it holds + # keeps an expired token good, a revocation it holds keeps it revoked. + _refuse_if_lapsed(again) + log.info("enterprise.licence_imported_again", {"license_id": issued}) + return _imported(again, issued) + _refuse_if_lapsed(record) + standing = await asyncio.to_thread(enterprise.standing_licence_id) + if standing and standing != issued: + raise EnterpriseUpgradeError(f"这台机器已经有授权 {standing},不覆盖;它失效后再导入新的") + with LICENCE_FILE_LOCK: + now = int(time.time()) + path = licence_file() + _keep_replaced_licence(path, now) + _write_licence(path, { + **record, + "activated_at": now, + "imported_at": now, + # What the file says of the install it was issued for; the core holds a bound token to it. + **{field: data[field] for field in ("install_id", "fingerprint", "request_id") if data.get(field)}, + }) + log.info("enterprise.licence_imported", {"license_id": issued}) + return _imported(record, issued) + + +def _import_again(token: str, patches: list[str]) -> dict[str, Any] | None: + """The file holding *token*, with the patches it lacked added (and written), read and written under the + lock the heartbeat writes under; None when the file on the machine holds another token, or none.""" + with LICENCE_FILE_LOCK: + found = find_licence_file() + if not found or licence_token(found[1])[0] != token: + return None + path, held = found + known = [item for item in held.get("patches") or [] if isinstance(item, str)] + fresh = [item for item in patches if item not in known] + merged = {**held, "patches": known + fresh} + if fresh: + _write_licence(path, merged) + return merged + + +def _licence_terms(record: dict[str, Any]) -> tuple[Any, Any]: + """A licence file's status and expiry as the core holds it to them: the token's, or the patch's in force.""" + claims = licence_token(record)[1] + terms = {**claims, **terms_in_force(record)} + return terms.get("status"), terms.get("expires_at") + + +def _refuse_if_lapsed(record: dict[str, Any]) -> None: + status, expires_at = _licence_terms(record) + state = str(status or "").strip().lower() + if state in enterprise.LAPSED_STATUSES: + said = {"revoked": "已吊销", "expired": "已过期", "superseded": "已被新的授权替换"}[state] + raise EnterpriseUpgradeError(f"这份授权{said},不能导入;请重新申请") + if enterprise.licence_lapsed(status, expires_at): + ended = datetime.fromtimestamp(moment(expires_at) or 0, UTC).astimezone().strftime("%Y-%m-%d") + raise EnterpriseUpgradeError(f"这份授权已在 {ended} 到期,不能导入;续期后重新下载授权文件,或者重新申请") + + +def _imported(record: dict[str, Any], issued: str) -> dict[str, Any]: + status, expires_at = _licence_terms(record) + return {"license_id": issued, "license_status": status, "expires_at": expires_at} + + +async def offline_application(form: dict[str, Any], applied_by: str) -> dict[str, Any]: + """The application to hand to whoever issues licences when Console cannot be reached from here: the + form, and the machine a licence issued for it is to be bound to. Nothing is sent or kept.""" + if not enterprise.available(): + raise EnterpriseUpgradeError("这台机器不能在这里申请:它已经是企业版,或者不是 Linux / macOS / Windows") + if await asyncio.to_thread(enterprise.standing_licence_id): + raise EnterpriseUpgradeError("这台机器已经有企业版授权,直接升级即可") + try: + machine, machine_kind, devid = await asyncio.to_thread(machine_names) + except MachineIdUnreadable as exc: + raise EnterpriseUpgradeError(f"读不到这台机器的标识,先处理好再申请:{exc}") from exc + from flocks import __version__ + from flocks.console.login import ConsoleLoginService + + return { + "format": OFFLINE_APPLICATION_FORMAT, + "product": "Flocks Pro", + "license_type": form["license_type"], + "company": form["company"], + "applicant_name": form["applicant_name"], + "applicant_email": form["applicant_email"], + "applicant_phone": form["applicant_phone"], + "sales_rep_name": form.get("sales_rep_name") or None, + "notes": form.get("notes") or None, + "replaces_license_id": enterprise.previous_licence_id() or None, + # Console's offline issue binds the licence to this fingerprint (32 hex digits), and keeps the + # device id beside it for its records. + "machine": machine or None, + "machine_kind": machine_kind or None, + "devid": devid or None, + "install_id": await ConsoleLoginService._get_install_id(), + "hostname": platform.node() or None, + "platform": enterprise.platform_id(), + "flocks_version": __version__, + "applied_by": applied_by, + "created_at": datetime.now(UTC).isoformat(), + } diff --git a/flocks/updater/installation_status.py b/flocks/updater/installation_status.py index f8d1cd189..1d4db49e7 100644 --- a/flocks/updater/installation_status.py +++ b/flocks/updater/installation_status.py @@ -39,8 +39,9 @@ def installation_result_path() -> Path: return root / "run" / "installation-result.json" -def installation_result_id() -> str | None: - """The id of the record there is, whatever it says (each one the installer writes has its own); +def installation_result_mark() -> tuple[str, str] | None: + """The id and the phase of the record there is, whatever else it says (each one the installer + writes has its own id: running as it starts to switch the machine over, then done or failed); None when there is none. Raises when there is one that cannot be read.""" path = installation_result_path() try: @@ -49,7 +50,16 @@ def installation_result_id() -> str | None: return None with os.fdopen(descriptor, "rb") as stream: record = json.loads(stream.read(MAX_RECORD_BYTES + 1)) - return str(record.get("id")) if isinstance(record, dict) else "" + if not isinstance(record, dict): + return "", "" + return str(record.get("id")), str(record.get("phase") or "") + + +def installation_result_id() -> str | None: + """The id of the record there is, whatever it says; None when there is none. Raises when there + is one that cannot be read.""" + mark = installation_result_mark() + return None if mark is None else mark[0] def source_upgrade_notice_path() -> Path: diff --git a/flocks/updater/machine_fingerprint.py b/flocks/updater/machine_fingerprint.py index 9dd75d489..ce488f54d 100644 --- a/flocks/updater/machine_fingerprint.py +++ b/flocks/updater/machine_fingerprint.py @@ -1,16 +1,29 @@ """ This machine, as the enterprise core names it. -The enterprise core (flockspro ``go/internal/activation/machine.go``) identifies the host by a digest -of the identifier the operating system keeps for it, and holds a licence Console bound to that digest -to this host. An application for a licence sends the same digest, so Console can bind the licence it -issues to the machine the application came from: a copy of the licence on another machine is then no -licence there. The raw identifier never leaves this module; Console sees only the digest. - -A host that keeps no identifier (a container without /etc/machine-id) has no digest, and Console shows -the operator that the licence cannot be bound. One whose identifier cannot be read now (a file it may -not read, ioreg failing) raises ``MachineIdUnreadable`` instead: an application then waits until it -can be read, rather than go out as one that cannot be bound by accident. +The enterprise core (flockspro ``go/internal/activation``) knows a host by two fingerprints, and holds a licence +bound to either to that host: + +- the digest of the identifier the operating system keeps for it (/etc/machine-id, the Mac's platform UUID), the + way every core has named it since licences were first bound to a machine; +- its device id, where it can be read: the fingerprint the company's other products license hosts by, computed + as the company's libdevid computes it on its default path -- the MD5 of the device type ``flocks`` and the + host's SMBIOS system UUID as dmidecode prints it, in lower case (on an AWS Xen host, its board asset tag or + hypervisor UUID), in hex (``flockspro go/internal/devid``). + +An application names the digest for the licence to be bound to wherever the host keeps an identifier, as the +core's own request does: an enterprise core from before the device id knows the host by the digest alone, and +so does one run by an account that cannot read the device id (on Linux only root may read the SMBIOS table, and +a core under an account of its own reads it only from a record root made). Bound to the device id, the licence +would be another host's to those. The device id goes beside it (``devid``), for Console's records. Only a host +that keeps no identifier (a container without /etc/machine-id) is named by its device id, where it has one. + +Both are 32 lower-case hex digits, the shape Console takes. The raw identifiers never leave this module. + +A host that keeps neither has no fingerprint, and Console shows the operator that the licence cannot be bound. +One whose identifier cannot be read now (a file it may not read, ioreg failing) raises ``MachineIdUnreadable`` +instead: an application then waits until it can be read, rather than go out as one that cannot be bound by +accident -- or bound to the device id, which the core may not read. """ from __future__ import annotations @@ -20,48 +33,32 @@ import subprocess import sys from pathlib import Path +from typing import NamedTuple #: Keeps this digest apart from any other hash of the same machine id (the core's machineDomain). _DOMAIN = b"flocks-machine/1\x00" _PLATFORM_UUID = re.compile(r'"IOPlatformUUID"\s*=\s*"([^"]+)"') #: Where Linux keeps the machine id; older distributions keep only the D-Bus copy. LINUX_MACHINE_ID_FILES = (Path("/etc/machine-id"), Path("/var/lib/dbus/machine-id")) +#: The device type Flocks hashes into its device id: each product has its own. +DEV_TYPE = "flocks" +#: What dmidecode prints for a UUID the firmware leaves all zeros or all ones: neither names a host. +_PLACEHOLDER_UUIDS = frozenset({"", "Not Settable", "Not Present"}) +#: Where Linux exposes the SMBIOS tables (root only) and an AWS Xen host its identifiers (anyone). +LINUX_SMBIOS_ENTRY_POINT = Path("/sys/firmware/dmi/tables/smbios_entry_point") +LINUX_SMBIOS_TABLE = Path("/sys/firmware/dmi/tables/DMI") +LINUX_HYPERVISOR_UUID = Path("/sys/hypervisor/uuid") +LINUX_BOARD_ASSET_TAG = Path("/sys/devices/virtual/dmi/id/board_asset_tag") + +#: What a fingerprint is (the core's activation.MachineKind*): the device id, or the machine-id digest. +KIND_DEVID = "devid" +KIND_MACHINE_ID = "machine-id" class MachineIdUnreadable(RuntimeError): """The host keeps an identifier, and it cannot be read now; ``str()`` says why.""" -def _machine_id() -> str: - if sys.platform.startswith("linux"): - for path in LINUX_MACHINE_ID_FILES: - try: - text = path.read_text(encoding="utf-8").strip() - except FileNotFoundError: - continue - except OSError as exc: - raise MachineIdUnreadable(f"读不了 {path}:{exc}") from exc - if text: - return text - return "" - if sys.platform == "darwin": - try: - # The absolute path keeps a PATH entry from standing in for it, as in the core. - result = subprocess.run( - ["/usr/sbin/ioreg", "-rd1", "-c", "IOPlatformExpertDevice"], - capture_output=True, text=True, timeout=10, check=False, - ) - except (OSError, subprocess.SubprocessError) as exc: - raise MachineIdUnreadable(f"ioreg 没有运行成功:{exc}") from exc - match = _PLATFORM_UUID.search(result.stdout or "") - if result.returncode != 0 or match is None: - # Every Mac has a platform UUID: not finding it is a failure, not a host without one. - raise MachineIdUnreadable(f"ioreg 没有给出 IOPlatformUUID(退出码 {result.returncode})") - return match.group(1) - # The enterprise edition runs on Linux and macOS only. - return "" - - def fingerprint_of(raw: str) -> str: """The digest of a machine id, as the core computes it; "" for none.""" text = raw.strip().lower() @@ -70,8 +67,176 @@ def fingerprint_of(raw: str) -> str: return hashlib.sha256(_DOMAIN + text.encode("utf-8")).hexdigest()[:32] -def machine_fingerprint() -> str: - """This host's digest; "" where it keeps no identifier (a container without /etc/machine-id). - Raises ``MachineIdUnreadable`` when it keeps one that cannot be read now. Blocking (ioreg runs up +def device_id_of(source: str) -> str: + """The device id of what it hashes (the SMBIOS UUID, or an AWS host's identifier), as the core computes + it, in lower case: libdevid prints the same digits in upper case.""" + return hashlib.md5((DEV_TYPE + source).encode("utf-8"), usedforsecurity=False).hexdigest() + + +def format_smbios_uuid(raw: bytes, major: int, minor: int) -> str: + """A 16-byte SMBIOS UUID as dmidecode prints it and libdevid hashes it: all ones "Not Present", all zeros + "Not Settable"; from SMBIOS 2.6 the first three fields little-endian; lower-case hex in 8-4-4-4-12 groups. + "" for too few.""" + if len(raw) < 16: + return "" + data = bytearray(raw[:16]) + if data == b"\xff" * 16: + return "Not Present" + if data == b"\x00" * 16: + return "Not Settable" + if major > 2 or (major == 2 and minor >= 6): + data[0:4] = data[0:4][::-1] + data[4:6] = data[4:6][::-1] + data[6:8] = data[6:8][::-1] + text = data.hex() + return f"{text[0:8]}-{text[8:12]}-{text[12:16]}-{text[16:20]}-{text[20:32]}" + + +def smbios_system_uuid(table: bytes, major: int, minor: int) -> str: + """The UUID of the System Information structure (type 1) in a raw SMBIOS structure table, as dmidecode + prints it; "" when there is none. Firmware's table is read defensively: a structure claiming more than + is there ends the walk.""" + uuid, p = "", 0 + while p + 4 <= len(table): + kind, length = table[p], table[p + 1] + if length < 4 or p + length > len(table): + break + # The UUID came with SMBIOS 2.1, which made the structure 0x19 long. + if kind == 1 and length >= 0x19: + uuid = format_smbios_uuid(table[p + 8 : p + 24], major, minor) + if kind == 127: # end of table + break + # The formatted area is followed by the structure's strings, which end with two NULs. + nxt = p + length + while nxt + 1 < len(table) and (table[nxt] != 0 or table[nxt + 1] != 0): + nxt += 1 + p = nxt + 2 + return uuid + + +def _first_line(path: Path) -> str: + try: + return path.read_text(encoding="utf-8", errors="replace").split("\n", 1)[0].strip() + except OSError: + return "" + + +def _linux_device_id() -> str: + """This Linux host's device id, "" where it cannot be read as the host's own: without root the SMBIOS + table is closed, and a UUID the firmware leaves unset names no host.""" + hypervisor = _first_line(LINUX_HYPERVISOR_UUID) + if hypervisor[:3].lower() == "ec2": + return device_id_of(_first_line(LINUX_BOARD_ASSET_TAG) or hypervisor) + major, minor = 2, 6 + try: + entry = LINUX_SMBIOS_ENTRY_POINT.read_bytes() + except OSError: + entry = b"" + if len(entry) >= 9 and entry[:5] == b"_SM3_": + major, minor = entry[7], entry[8] + elif len(entry) >= 8 and entry[:4] == b"_SM_": + major, minor = entry[6], entry[7] + try: + table = LINUX_SMBIOS_TABLE.read_bytes() + except OSError: + return "" + uuid = smbios_system_uuid(table, major, minor) + return "" if uuid in _PLACEHOLDER_UUIDS else device_id_of(uuid) + + +def _linux_machine_id() -> str: + for path in LINUX_MACHINE_ID_FILES: + try: + text = path.read_text(encoding="utf-8").strip() + except FileNotFoundError: + continue + except OSError as exc: + raise MachineIdUnreadable(f"读不了 {path}:{exc}") from exc + except UnicodeDecodeError as exc: + # A damaged file names no host this module can digest as the core does: it cannot be read. + raise MachineIdUnreadable(f"{path} 的内容不是文本,机器标识读不出来:{exc}") from exc + if text: + return text + return "" + + +def _platform_uuid() -> str: + try: + # The absolute path keeps a PATH entry from standing in for it, as in the core. + result = subprocess.run( + ["/usr/sbin/ioreg", "-rd1", "-c", "IOPlatformExpertDevice"], + capture_output=True, text=True, timeout=10, check=False, + ) + except (OSError, subprocess.SubprocessError) as exc: + raise MachineIdUnreadable(f"ioreg 没有运行成功:{exc}") from exc + match = _PLATFORM_UUID.search(result.stdout or "") + if result.returncode != 0 or match is None: + # Every Mac has a platform UUID: not finding it is a failure, not a host without one. + raise MachineIdUnreadable(f"ioreg 没有给出 IOPlatformUUID(退出码 {result.returncode})") + return match.group(1) + + +class MachineNames(NamedTuple): + """This host as an application names it: the fingerprint a licence is bound to and which one it is + (``KIND_MACHINE_ID`` or ``KIND_DEVID``), and the device id beside it where it can be read ("" where not).""" + + fingerprint: str + kind: str + devid: str + + +def _device_id_of_platform_uuid(uuid: str) -> str: + """A Mac's device id: its platform UUID stands in for the SMBIOS one, as in the core, in the lower case + libdevid hashes a UUID in (ioreg prints it in upper); "" for a placeholder.""" + return "" if uuid.strip() in _PLACEHOLDER_UUIDS else device_id_of(uuid.lower()) + + +def machine_names() -> MachineNames: + """This host's fingerprint for a licence, what it is, and its device id: the machine-id digest wherever the + host keeps an identifier, else the device id where it can be read; ("", "", "") where neither. Raises + ``MachineIdUnreadable`` when the host keeps an identifier that cannot be read now. Blocking (ioreg runs up to 10 seconds): call it off the event loop.""" - return fingerprint_of(_machine_id()) + if sys.platform.startswith("linux"): + device = _linux_device_id() + digest = fingerprint_of(_linux_machine_id()) + if digest: + return MachineNames(digest, KIND_MACHINE_ID, device) + return MachineNames(device, KIND_DEVID, device) if device else MachineNames("", "", "") + if sys.platform == "darwin": + uuid = _platform_uuid() + return MachineNames(fingerprint_of(uuid), KIND_MACHINE_ID, _device_id_of_platform_uuid(uuid)) + # Windows and the rest: applications from here go out unbound, as they always have. + return MachineNames("", "", "") + + +def machine_identity() -> tuple[str, str]: + """This host's fingerprint for a licence and what it is (``machine_names``).""" + names = machine_names() + return names.fingerprint, names.kind + + +def machine_fingerprints() -> set[str]: + """Every fingerprint this host goes by that can be read now -- its device id and the digest of its + identifier -- as the core holds a licence bound to either to this host; empty where none can be read. + Never raises: what cannot be read is left out. Blocking, as ``machine_identity`` is.""" + found: set[str] = set() + if sys.platform.startswith("linux"): + found.add(_linux_device_id()) + try: + found.add(fingerprint_of(_linux_machine_id())) + except MachineIdUnreadable: + pass + elif sys.platform == "darwin": + try: + uuid = _platform_uuid() + except MachineIdUnreadable: + uuid = "" + if uuid.strip(): + found.add(_device_id_of_platform_uuid(uuid)) + found.add(fingerprint_of(uuid)) + return {item for item in found if item} + + +def machine_fingerprint() -> str: + """This host's fingerprint (``machine_identity``); "" where it keeps no identifier.""" + return machine_identity()[0] diff --git a/flocks/workflow/soc_store/__init__.py b/flocks/workflow/soc_store/__init__.py new file mode 100644 index 000000000..a316a51c9 --- /dev/null +++ b/flocks/workflow/soc_store/__init__.py @@ -0,0 +1,69 @@ +""" +The SOC suite's data, on SQLite. + +The alert operations suite (the triage workflow, the SOC pages, the query +tool) keeps no database code of its own. It writes and reads through this +package: + +* the triage workflow writes alerts through the ``soc`` service a workflow's + python nodes get (:class:`SOCWriteCapability`, + ``flocks.coordination.workflow_services``); +* the dashboard and overview pages read through ``ctx.services.soc`` + (:func:`page_service`, ``flocks.coordination.page_api_services``); +* the query tool imports :mod:`.alerts`; +* the alert investigation page's contract names the ``builtin-soc-alerts`` + source, which ``flocks.contracts.access.driver`` reads from here. + +A database backend replaces this package as a whole (see +``flocks.db_backend``) and answers the same calls from its own tables, so the +suite's files are the same on every backend. +""" + +from __future__ import annotations + +from types import SimpleNamespace +from typing import Any, Callable, Optional + +from .triage import ensure_schema, persist_triage_alerts + +#: The database backend this implementation is for. +BACKEND = "sqlite" + +#: How a caller should batch alerts for one ``write_alerts`` call. A backend +#: may refuse a larger call; this one does not. +MAX_ALERT_ROWS = 500 +MAX_ALERT_BYTES = 2 * 1024 * 1024 + + +class SOCWriteCapability: + """What a workflow's python node writes triaged alerts through.""" + + #: What a node may call (flocks.coordination.workflow_services), and how long an isolated node waits. + exposed_methods = ("write_alerts",) + rpc_timeout_s = 60.0 + + def __init__(self, cancel_checker: Optional[Callable[[], bool]] = None) -> None: + self.cancel_checker = cancel_checker + + def write_alerts(self, alerts: list[dict[str, Any]], run_id: str, source_file: str = "") -> dict[str, Any]: + if self.cancel_checker and self.cancel_checker(): + raise RuntimeError("Workflow cancelled before SOC persistence") + return persist_triage_alerts(alerts, run_id, source_file) + + +def page_service() -> SimpleNamespace: + """``ctx.services.soc`` for a WebUI page's API handlers: what the SOC pages read.""" + from . import dashboard, overview + + return SimpleNamespace(backend=BACKEND, dashboard=dashboard, overview=overview) + + +__all__ = [ + "BACKEND", + "MAX_ALERT_BYTES", + "MAX_ALERT_ROWS", + "SOCWriteCapability", + "ensure_schema", + "page_service", + "persist_triage_alerts", +] diff --git a/flocks/workflow/soc_store/_paths.py b/flocks/workflow/soc_store/_paths.py new file mode 100644 index 000000000..26eb2f5cb --- /dev/null +++ b/flocks/workflow/soc_store/_paths.py @@ -0,0 +1,69 @@ +"""Where the SQLite files behind the SOC suite are, and the workflow packages its pages name. + +``soc.db`` is the suite's own: the triage workflow writes alerts to it and the +SOC pages read them back. The other three are the runtime's own databases, +read here for the dashboard's workflow, task and token figures. +""" + +from __future__ import annotations + +from pathlib import Path +from typing import Optional + +from flocks.db_backend import data_dir + +#: Another file to use instead of the installation's own; tests set these. +SOC_DB: Optional[Path] = None +WORKFLOW_DB: Optional[Path] = None +TASK_DB: Optional[Path] = None +USAGE_DB: Optional[Path] = None +WORKFLOW_ROOTS: Optional[list[Path]] = None + + +def historical_soc_db() -> Path: + """Where the suite kept its alerts before it asked the runtime for a place.""" + return Path.home() / ".flocks" / "data" / "soc.db" + + +def soc_db() -> Path: + """The alert store: in the data directory, or the historical file while only that one exists.""" + if SOC_DB is not None: + return Path(SOC_DB) + current = data_dir() / "soc.db" + if not current.exists(): + historical = historical_soc_db() + if historical.is_file(): + return historical + return current + + +def workflow_db() -> Path: + return Path(WORKFLOW_DB) if WORKFLOW_DB is not None else data_dir() / "workflow.db" + + +def task_db() -> Path: + return Path(TASK_DB) if TASK_DB is not None else data_dir() / "tasks.db" + + +def usage_db() -> Path: + return Path(USAGE_DB) if USAGE_DB is not None else data_dir() / "flocks.db" + + +def workflow_roots() -> list[Path]: + """Where workflow packages are read for their names and step counts, the installation's own first. + + The installation's plugins and workspace, then the workflows the release + bundles: a workflow that has run here but is not installed (any more) is + still named by the release's manifest. + """ + if WORKFLOW_ROOTS is not None: + return [Path(root) for root in WORKFLOW_ROOTS] + from flocks.config.config import get_user_plugins_root + from flocks.hub.paths import get_bundled_hub_root + from flocks.workspace.manager import _get_workspace_dir + + return [ + get_user_plugins_root() / "workflows", + _get_workspace_dir() / "workflows", + get_bundled_hub_root() / "plugins" / "workflows", + ] diff --git a/flocks/workflow/soc_store/alerts.py b/flocks/workflow/soc_store/alerts.py new file mode 100644 index 000000000..8b977de7d --- /dev/null +++ b/flocks/workflow/soc_store/alerts.py @@ -0,0 +1,302 @@ +""" +Alert records and workflow runs as the SOC query tool reads them, from SQLite. + +``soc_workspace_query`` holds no SQL: it turns its filters into the criteria +:func:`search` takes and lays the rows out. The alerts come from ``soc.db``, +the workflow figures from the runtime's ``workflow.db``. + +A database backend replaces ``flocks.workflow.soc_store`` as a whole (see +``flocks.db_backend``) and answers the same questions from its own tables. +""" + +from __future__ import annotations + +import json +import sqlite3 +from typing import Any, Optional + +from . import _paths + +#: What the tool and the alert page report as the kind of store they read. +DATA_SOURCE = "sqlite" +DATA_SOURCE_LABEL = "SQLite" + +# The triage workflow stores its verdict in triage_attack_verdict / +# triage_attack_success; the SOC overview and alert pages read those first. +# Older records only carry the NDR fields (attach_result, threat_result, +# attack_verdict). triage_status is the triage run's own status ("ok"), not a +# verdict about the attack. +_TRIAGE_VERDICT_SQL = "lower(trim(CAST(json_extract(record_json, '$.triage_attack_verdict') AS TEXT)))" +_TRIAGE_SUCCESS_SQL = "lower(trim(CAST(json_extract(record_json, '$.triage_attack_success') AS TEXT)))" +ATTACK_VERDICT_SQL = ( + f"CASE WHEN COALESCE({_TRIAGE_VERDICT_SQL}, '') <> '' THEN " + f"CASE WHEN {_TRIAGE_VERDICT_SQL} IN ('attack', 'attack_success', 'attack_failed') THEN 'attack' " + f"WHEN {_TRIAGE_VERDICT_SQL} IN ('non_attack', 'benign') THEN 'non_attack' ELSE 'unknown' END " + "ELSE json_extract(record_json, '$.attack_verdict') END" +) +ATTACK_RESULT_SQL = ( + f"CASE WHEN COALESCE({_TRIAGE_VERDICT_SQL}, '') <> '' THEN " + f"CASE WHEN {_TRIAGE_VERDICT_SQL} NOT IN ('attack', 'attack_success', 'attack_failed') THEN 'unknown' " + f"WHEN {_TRIAGE_SUCCESS_SQL} IN ('success', 'failed', 'unknown') THEN {_TRIAGE_SUCCESS_SQL} " + f"WHEN {_TRIAGE_VERDICT_SQL} = 'attack_success' THEN 'success' " + f"WHEN {_TRIAGE_VERDICT_SQL} = 'attack_failed' THEN 'failed' " + f"WHEN {_TRIAGE_SUCCESS_SQL} IN ('1', 'true') THEN 'success' ELSE 'unknown' END " + "ELSE COALESCE(json_extract(record_json, '$.attach_result'), json_extract(record_json, '$.threat_result'), " + "json_extract(record_json, '$.attack_verdict')) END" +) + +#: The fields an alert search can match exactly, and where each is read from. +ALERT_FIELDS = { + "row_id": "row_id", + "record_id": "record_id", + "source_type": "COALESCE(source_type, json_extract(record_json, '$._source_type'), json_extract(record_json, '$.source_type'))", + "threat_name": "COALESCE(threat_name, json_extract(record_json, '$.threat_name'))", + "threat_type": "json_extract(record_json, '$.threat_type')", + "threat_phase": "json_extract(record_json, '$.threat_phase')", + "attack_result": ATTACK_RESULT_SQL, + "attack_verdict": ATTACK_VERDICT_SQL, + "direction": "json_extract(record_json, '$.direction')", + "sip": "json_extract(record_json, '$.sip')", + "dip": "json_extract(record_json, '$.dip')", + "sport": "json_extract(record_json, '$.sport')", + "dport": "json_extract(record_json, '$.dport')", + "req_host": "json_extract(record_json, '$.req_host')", + "req_http_url": "json_extract(record_json, '$.req_http_url')", + "rsp_status_code": "json_extract(record_json, '$.rsp_status_code')", + "threat_rule_id": "json_extract(record_json, '$.threat_rule_id')", +} +FILTER_FIELDS = tuple(ALERT_FIELDS) + +_FACET_FIELDS = { + "source_type": ALERT_FIELDS["source_type"], + "threat_name": ALERT_FIELDS["threat_name"], + "threat_type": ALERT_FIELDS["threat_type"], + "threat_phase": ALERT_FIELDS["threat_phase"], + "attack_result": ATTACK_RESULT_SQL, + "direction": ALERT_FIELDS["direction"], +} + +_ALERT_COLUMNS = ( + "row_id", "record_id", "asset_date", "source_file", "line_number", "event_time", + "source_type", "threat_name", "is_duplicate", "record_json", +) +_WORKFLOW_STAT_COLUMNS = ( + "workflow_id", "call_count", "success_count", "error_count", "total_runtime", + "avg_runtime", "thumbs_up", "thumbs_down", "updated_at", +) +_WORKFLOW_EXECUTION_COLUMNS = ( + "id", "workflow_id", "status", "current_phase", "current_node_id", + "current_node_type", "current_step_index", "step_count", + "error_message", "trigger_id", "trigger_type", "started_at", + "finished_at", "duration", "updated_at", +) + + +def source_info() -> dict[str, Any]: + """Where the alerts and workflow runs are kept, and whether those stores are there.""" + soc_db, workflow_db = _paths.soc_db(), _paths.workflow_db() + return { + "dataSource": DATA_SOURCE, + "socDb": str(soc_db), + "socDbExists": soc_db.is_file(), + "workflowDb": str(workflow_db), + "workflowDbExists": workflow_db.is_file(), + } + + +def _require(path, label: str) -> None: + if not path.is_file(): + raise FileNotFoundError(f"{label} does not exist: {path}") + + +def _where(criteria: dict[str, Any]) -> tuple[str, list[Any]]: + clauses: list[str] = [] + params: list[Any] = [] + if not criteria.get("include_duplicates"): + clauses.append("is_duplicate = 0") + if criteria.get("start_date"): + clauses.append("asset_date >= ?") + params.append(str(criteria["start_date"])) + if criteria.get("end_date"): + clauses.append("asset_date <= ?") + params.append(str(criteria["end_date"])) + if criteria.get("start_time") is not None: + clauses.append("event_time >= ?") + params.append(criteria["start_time"]) + if criteria.get("end_time") is not None: + clauses.append("event_time <= ?") + params.append(criteria["end_time"]) + keyword = criteria.get("keyword") + if keyword: + clauses.append("(record_json LIKE ? OR threat_name LIKE ? OR record_id LIKE ? OR row_id LIKE ?)") + like = f"%{keyword}%" + params.extend([like, like, like, like]) + for key, value in (criteria.get("fields") or {}).items(): + expression = ALERT_FIELDS.get(key) + if expression is None: + raise ValueError(f"Unsupported alert filter field: {key}") + # Compared as text: a JSON number (dport 443) comes back from + # json_extract as an integer and would never equal the text "443". + compared = expression if key in {"row_id", "record_id"} else f"CAST(({expression}) AS TEXT)" + if isinstance(value, (list, tuple, set)): + values = list(value) + if not values: + continue + placeholders = ", ".join("?" for _ in values) + clauses.append(f"{compared} IN ({placeholders})") + params.extend(values) + else: + clauses.append(f"{compared} = ?") + params.append(value) + return " AND ".join(clauses) if clauses else "1=1", params + + +def search(criteria: dict[str, Any], *, limit: int, offset: int, order: str = "desc") -> dict[str, Any]: + """The alerts matching *criteria*, newest or oldest first: their count, one page of rows, and facets. + + *criteria* may hold ``include_duplicates``, ``start_date`` / ``end_date`` + (``YYYY-MM-DD``), ``start_time`` / ``end_time`` (epoch seconds), ``keyword`` + and ``fields`` (exact matches on :data:`FILTER_FIELDS`, a value or a list). + """ + soc_db = _paths.soc_db() + _require(soc_db, "SOC alert database") + where, params = _where(criteria) + order_sql = "ASC" if order == "asc" else "DESC" + query = f""" + SELECT {', '.join(_ALERT_COLUMNS)} + FROM alert_records + WHERE {where} + ORDER BY event_time {order_sql}, row_id {order_sql} + LIMIT ? OFFSET ? + """ + count_query = f"SELECT COUNT(*) FROM alert_records WHERE {where}" + + with sqlite3.connect(soc_db) as conn: + conn.row_factory = sqlite3.Row + total = int(conn.execute(count_query, params).fetchone()[0]) + rows = [dict(row) for row in conn.execute(query, [*params, limit, offset]).fetchall()] + facets: dict[str, list[dict[str, Any]]] = {} + for key, expression in _FACET_FIELDS.items(): + facet_rows = conn.execute( + f""" + SELECT {expression} AS value, COUNT(*) AS count + FROM alert_records + WHERE {where} + GROUP BY value + ORDER BY count DESC + LIMIT 20 + """, + params, + ).fetchall() + facets[key] = [ + {"value": str(value).strip() or "unknown", "count": int(count or 0)} + for value, count in facet_rows + if value not in (None, "") + ] + return {"total": total, "rows": rows, "facets": facets} + + +def record_fields() -> list[str]: + """The field names of one stored alert, as a sample of what a record holds.""" + soc_db = _paths.soc_db() + if not soc_db.is_file(): + return [] + try: + with sqlite3.connect(soc_db) as conn: + row = conn.execute("SELECT record_json FROM alert_records LIMIT 1").fetchone() + if not row: + return [] + value = json.loads(row[0]) if isinstance(row[0], str) and row[0].strip() else {} + return sorted(str(key) for key in value.keys()) if isinstance(value, dict) else [] + except Exception: + return [] + + +def latest_date() -> str: + """The latest date alerts are stored for; empty without any.""" + soc_db = _paths.soc_db() + if not soc_db.is_file(): + return "" + try: + with sqlite3.connect(soc_db) as conn: + row = conn.execute("SELECT MAX(asset_date) FROM alert_records").fetchone() + return str(row[0] or "") + except Exception: + return "" + + +def workflow_runs( + workflow_id: str = "", + *, + start_ms: Optional[int] = None, + end_ms: Optional[int] = None, + limit: int = 20, +) -> dict[str, list[dict[str, Any]]]: + """Workflow call statistics and the latest executions, of one workflow or all.""" + workflow_db = _paths.workflow_db() + _require(workflow_db, "workflow database") + stats_params: list[Any] = [] + stats_where = "" + if workflow_id: + stats_where = "WHERE workflow_id = ?" + stats_params.append(workflow_id) + + exec_where = [] + exec_params: list[Any] = [] + if workflow_id: + exec_where.append("workflow_id = ?") + exec_params.append(workflow_id) + if start_ms is not None: + exec_where.append("started_at >= ?") + exec_params.append(start_ms) + if end_ms is not None: + exec_where.append("started_at <= ?") + exec_params.append(end_ms) + exec_where_sql = " AND ".join(exec_where) if exec_where else "1=1" + + with sqlite3.connect(workflow_db) as conn: + conn.row_factory = sqlite3.Row + stats_rows = conn.execute( + f""" + SELECT {', '.join(_WORKFLOW_STAT_COLUMNS)} + FROM workflow_stats + {stats_where} + ORDER BY updated_at DESC + """, + stats_params, + ).fetchall() + execution_rows = conn.execute( + f""" + SELECT {', '.join(_WORKFLOW_EXECUTION_COLUMNS)} + FROM workflow_executions + WHERE {exec_where_sql} + ORDER BY started_at DESC + LIMIT ? + """, + [*exec_params, limit], + ).fetchall() + return { + "stats": [dict(row) for row in stats_rows], + "executions": [dict(row) for row in execution_rows], + } + + +def contract_source(options: Optional[dict[str, Any]] = None) -> dict[str, Any]: + """Where the alert contract's records are, for ``flocks.contracts.access.driver``. + + *options* are the binding's driver options. Their ``settings`` is the + content of ``access/soc_alerts.json`` (its ``sqlite`` part may name another + file, table or columns) and ``settingsDir`` the directory a relative path + in it starts from. + """ + from .overview import settings as source_settings + + options = options if isinstance(options, dict) else {} + resolved = source_settings(options.get("settings"), options.get("settingsDir")) + return { + "db_path": resolved["db_path"], + "table": resolved["table"].strip('"'), + "recordColumn": resolved["record_column"].strip('"'), + "dateColumn": resolved["date_column"].strip('"'), + "eventTimeColumn": resolved["event_time_column"].strip('"'), + } diff --git a/flocks/workflow/soc_store/dashboard.py b/flocks/workflow/soc_store/dashboard.py new file mode 100644 index 000000000..0296b06f5 --- /dev/null +++ b/flocks/workflow/soc_store/dashboard.py @@ -0,0 +1,3040 @@ +""" +What the SOC dashboard page reads, from SQLite. + +The page's handlers (``soc_ui/soc_dashboard/api/handlers.py``) hold no SQL: they +ask here for the alert figures, the activity feed, the workflow and task +summaries and the token usage, and lay the answers out. The alert figures come +from ``soc.db``, through a facts table kept up to date by triggers on +``alert_records``; the rest is read from the runtime's own databases. + +A database backend replaces ``flocks.workflow.soc_store`` as a whole (see +``flocks.db_backend``) and answers the same questions from its own tables. +""" + +from __future__ import annotations + +import base64 +import json +import math +import re +import sqlite3 +import time +from collections import Counter, OrderedDict +from contextlib import closing +from dataclasses import dataclass +from datetime import datetime, timedelta, timezone +from pathlib import Path +from threading import Lock, RLock + +from . import _paths + +#: What the page shows as the kind of store behind its figures. +DATA_SOURCE = "sqlite" + + +DATE_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$") +DEFAULT_SQLITE_TABLE = "alert_records" +DEFAULT_SQLITE_RECORD_COLUMN = "record_json" +DEFAULT_SQLITE_DATE_COLUMN = "asset_date" +DEFAULT_SQLITE_EVENT_TIME_COLUMN = "event_time" +FACTS_TABLE = "soc_dashboard_alert_facts" +ACTIVITY_TABLE = "soc_dashboard_activity" +META_TABLE = "soc_dashboard_meta" +SCHEMA_VERSION = "4" +ACTIVITY_DEFAULT_LIMIT = 20 +ACTIVITY_MAX_LIMIT = 50 +ACTIVITY_WINDOW_MS = 3000 +ACTIVITY_NORMAL_LIMIT = 5 +ACTIVITY_SURGE_LIMIT = 100 +ACTIVITY_RETENTION_ROWS = 100_000 +ACTIVITY_PRUNE_INTERVAL = 3600.0 +WORKFLOW_SNAPSHOT_TABLE = "soc_dashboard_workflow_stats_samples" +SOC_PINNED_WORKFLOW_NAMES = { + "stream_alert_denoise": "告警降噪工作流", + "stream_alert_triage": "告警研判工作流", +} +TRIAGE_WORKFLOW_IDS = { + "stream_alert_triage", + "onesec_kafka_investigation", + "tdp_alert_triage", + "sec_alert_unified_ops", +} +WORKFLOW_DISPLAY_NAMES = { + **SOC_PINNED_WORKFLOW_NAMES, + "onesec_kafka_investigation": "OneSEC Kafka 告警研判工作流", + "tdp_alert_triage": "TDP 告警研判工作流", + "sec_alert_unified_ops": "统一告警运营工作流", +} +WORKFLOW_RUNNING_STATUSES = {"running", "queued", "pending"} +WORKFLOW_SUCCESS_STATUSES = {"success", "completed"} +WORKFLOW_TRIGGER_CONFIG_KINDS = { + "workflow_kafka_config", + "workflow_poller_config", + "workflow_syslog_config", +} +WORKFLOW_DEFAULT_ACTIVE_TIMEOUT_SECONDS = 7200 +WORKFLOW_MIN_ACTIVE_TIMEOUT_SECONDS = 60 +UUID_RE = re.compile( + r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$", + re.IGNORECASE, +) + +_workflow_stats_cache: OrderedDict = OrderedDict() +_CACHE_TTL: float = 30.0 +_WORKFLOW_CACHE_MAX = 64 +_denoise_detail_cache: OrderedDict = OrderedDict() +_DENOISE_DETAIL_CACHE_TTL = 300.0 +_DENOISE_DETAIL_CACHE_MAX = 64 +_token_usage_cache = {"updatedAt": 0.0, "mtimeNs": 0, "value": None} +_TOKEN_USAGE_CACHE_TTL = 30.0 +_cache_lock = RLock() +_workflow_activity_read_lock = Lock() +_schema_lock = RLock() +_schema_ready: set = set() +_activity_pruned_at: float = 0 + + +@dataclass(frozen=True) +class RecordSource: + path: Path + role: str + date: str + data_source: str + record_count: int = 0 + start_time: int = 0 + end_time: int = 0 + + +_FACT_COLUMNS = ( + "alert_row_id", + "row_key", + "asset_date", + "event_time", + "source_type", + "threat_name", + "threat_type", + "is_duplicate", + "phase", + "direction", + "result", + "protocol", + "severity", + "response_code", + "port", + "has_triage", + "triage_persisted_at", + "triage_status", + "triage_source", + "triage_attack_verdict", + "risk_level", + "triage_ms", + "triage_attack_success", +) +# How a fact column an older layout lacks is added; any other is TEXT. A facts +# table of an older schema version is brought up to date in place and +# recomputed from alert_records rather than dropped and made again. +_FACT_COLUMN_DEFINITIONS = { + "row_key": "TEXT NOT NULL DEFAULT ''", + "asset_date": "TEXT NOT NULL DEFAULT ''", + "event_time": "INTEGER", + "is_duplicate": "INTEGER NOT NULL DEFAULT 0", + "has_triage": "INTEGER NOT NULL DEFAULT 0", + "triage_ms": "INTEGER NOT NULL DEFAULT 0", + "triage_attack_success": "TEXT NOT NULL DEFAULT 'unknown'", +} + + +def _json_value(prefix, path): + return ( + f"CASE WHEN json_valid({prefix}.record_json) " + f"THEN json_extract({prefix}.record_json, '$.{path}') END" + ) + + +def _fact_expressions(prefix): + source_type = _json_value(prefix, "_source_type") + source_type_fallback = _json_value(prefix, "source_type") + threat_name = _json_value(prefix, "threat_name") + threat_type = _json_value(prefix, "_threat_type") + threat_type_fallback = _json_value(prefix, "threat_type") + phase = _json_value(prefix, "threat_phase") + attack_phase = _json_value(prefix, "attack_phase") + kill_chain = _json_value(prefix, "kill_chain_phase") + direction = _json_value(prefix, "direction") + traffic_direction = _json_value(prefix, "traffic_direction") + raw_result = _json_value(prefix, "threat_result") + raw_verdict = _json_value(prefix, "attack_verdict") + triage_attack_verdict = _json_value(prefix, "triage_attack_verdict") + triage_attack_success = _json_value(prefix, "triage_attack_success") + normalized_triage_verdict = ( + f"CASE WHEN LOWER(COALESCE({triage_attack_verdict}, '')) " + "IN ('attack', 'non_attack', 'unknown') " + f"THEN LOWER({triage_attack_verdict}) " + f"WHEN LOWER(COALESCE({triage_attack_verdict}, '')) " + "IN ('attack_success', 'attack_failed') THEN 'attack' " + f"WHEN LOWER(COALESCE({triage_attack_verdict}, '')) = 'benign' " + "THEN 'non_attack' ELSE 'unknown' END" + ) + normalized_triage_success = ( + f"CASE WHEN {normalized_triage_verdict} != 'attack' THEN 'unknown' " + f"WHEN LOWER(COALESCE({triage_attack_success}, '')) " + "IN ('success', 'failed', 'unknown') " + f"THEN LOWER({triage_attack_success}) " + f"WHEN LOWER(COALESCE({triage_attack_verdict}, '')) = 'attack_success' " + "THEN 'success' " + f"WHEN LOWER(COALESCE({triage_attack_verdict}, '')) = 'attack_failed' " + "THEN 'failed' " + f"WHEN LOWER(COALESCE({triage_attack_success}, '')) IN ('1', 'true') " + "THEN 'success' ELSE 'unknown' END" + ) + protocol = _json_value(prefix, "net_type") + app_protocol = _json_value(prefix, "net_app_proto") + protocol_fallback = _json_value(prefix, "protocol") + severity = _json_value(prefix, "threat_severity") + risk_level = _json_value(prefix, "risk_level") + response = _json_value(prefix, "rsp_status_code") + status_code = _json_value(prefix, "status_code") + destination_port = _json_value(prefix, "dport") + destination_port_fallback = _json_value(prefix, "dst_port") + destination_port_legacy = _json_value(prefix, "destination_port") + triage_persisted_at = _json_value(prefix, "_triage_persisted_at") + triage_status = _json_value(prefix, "triage_status") + triage_source = _json_value(prefix, "triage_source") + triage_report = _json_value(prefix, "triage_report") + triage_ms = _json_value(prefix, "triage_ms") + has_triage = ( + "CASE WHEN " + f"NULLIF({triage_status}, '') IS NOT NULL " + f"OR NULLIF({triage_persisted_at}, '') IS NOT NULL " + f"OR {triage_report} IS NOT NULL THEN 1 ELSE 0 END" + ) + return ( + f"{prefix}.rowid", + f"COALESCE(NULLIF({prefix}.row_id, ''), CAST({prefix}.rowid AS TEXT))", + f"{prefix}.asset_date", + f"{prefix}.event_time", + f"COALESCE(NULLIF({prefix}.source_type, ''), NULLIF({source_type}, ''), " + f"NULLIF({source_type_fallback}, ''), 'unknown')", + f"COALESCE(NULLIF({prefix}.threat_name, ''), NULLIF({threat_name}, ''), 'unknown')", + f"COALESCE(NULLIF({threat_type}, ''), NULLIF({threat_type_fallback}, ''), 'unknown')", + f"COALESCE({prefix}.is_duplicate, 0)", + f"COALESCE(NULLIF({phase}, ''), NULLIF({attack_phase}, ''), NULLIF({kill_chain}, ''), 'unknown')", + f"COALESCE(NULLIF({direction}, ''), NULLIF({traffic_direction}, ''), 'unknown')", + f"CASE WHEN {has_triage} = 1 " + f"THEN {normalized_triage_success} " + f"ELSE COALESCE(NULLIF({raw_result}, ''), NULLIF({raw_verdict}, ''), 'unknown') END", + f"COALESCE(NULLIF({protocol}, ''), NULLIF({app_protocol}, ''), " + f"NULLIF({protocol_fallback}, ''), 'unknown')", + f"COALESCE(NULLIF({severity}, ''), 'unknown')", + f"COALESCE(NULLIF({response}, ''), NULLIF({status_code}, ''), 'unknown')", + f"COALESCE(NULLIF({destination_port}, ''), NULLIF({destination_port_fallback}, ''), " + f"NULLIF({destination_port_legacy}, ''), 'unknown')", + has_triage, + f"COALESCE({triage_persisted_at}, '')", + f"COALESCE({triage_status}, '')", + f"COALESCE({triage_source}, '')", + normalized_triage_verdict, + f"COALESCE(NULLIF({risk_level}, ''), 'unknown')", + f"COALESCE(CAST({triage_ms} AS INTEGER), 0)", + normalized_triage_success, + ) + + +def _fact_upsert_sql(prefix): + columns = ", ".join(_FACT_COLUMNS) + values = ", ".join(_fact_expressions(prefix)) + return f"INSERT OR REPLACE INTO {FACTS_TABLE} ({columns}) VALUES ({values})" + + +def _fact_backfill_sql(): + columns = ", ".join(_FACT_COLUMNS) + values = ", ".join(_fact_expressions("source")) + return ( + f"INSERT OR REPLACE INTO {FACTS_TABLE} ({columns}) " + f"SELECT {values} FROM {DEFAULT_SQLITE_TABLE} AS source" + ) + + +def _triage_marker(prefix): + status_value = _json_value(prefix, "triage_status") + persisted_value = _json_value(prefix, "_triage_persisted_at") + report_value = _json_value(prefix, "triage_report") + return ( + f"(NULLIF({status_value}, '') IS NOT NULL " + f"OR NULLIF({persisted_value}, '') IS NOT NULL " + f"OR {report_value} IS NOT NULL)" + ) + + +def _column_exists(conn, table_name, column_name): + return any( + str(row[1]) == column_name + for row in conn.execute(f"PRAGMA table_info({table_name})").fetchall() + ) + + +def _add_column_if_missing(conn, table_name, column_name, column_definition): + if not _column_exists(conn, table_name, column_name): + conn.execute( + f"ALTER TABLE {table_name} ADD COLUMN {column_name} {column_definition}" + ) + + +def _drop_dashboard_triggers(conn): + for trigger_name in ( + "soc_dashboard_fact_insert", + "soc_dashboard_fact_update", + "soc_dashboard_fact_delete", + ): + conn.execute(f"DROP TRIGGER IF EXISTS {trigger_name}") + + +def _ensure_alert_record_columns(conn): + for column_name, column_definition in ( + ("row_id", "TEXT"), + ("record_id", "TEXT"), + ("source_file", "TEXT"), + ("line_number", "INTEGER"), + ("source_type", "TEXT"), + ("threat_name", "TEXT"), + ("is_duplicate", "INTEGER DEFAULT 0"), + ): + _add_column_if_missing( + conn, + DEFAULT_SQLITE_TABLE, + column_name, + column_definition, + ) + conn.execute( + f"UPDATE {DEFAULT_SQLITE_TABLE} " + f"SET row_id = CAST(rowid AS TEXT) " + f"WHERE row_id IS NULL OR row_id = ''" + ) + + +def _create_dashboard_triggers(conn): + insert_fact = _fact_upsert_sql("NEW") + new_row_key = _fact_expressions("NEW")[1] + new_persisted = _json_value("NEW", "_triage_persisted_at") + old_persisted = _json_value("OLD", "_triage_persisted_at") + new_status = _json_value("NEW", "triage_status") + old_status = _json_value("OLD", "triage_status") + new_report = _json_value("NEW", "triage_report") + old_report = _json_value("OLD", "triage_report") + conn.execute( + f""" + CREATE TRIGGER IF NOT EXISTS soc_dashboard_fact_insert + AFTER INSERT ON {DEFAULT_SQLITE_TABLE} + BEGIN + {insert_fact}; + INSERT OR IGNORE INTO {ACTIVITY_TABLE} ( + event_key, alert_row_id, record_row_id, asset_date, event_time, record_json + ) + SELECT COALESCE(NULLIF(NEW.row_id, ''), CAST(NEW.rowid AS TEXT)) || + ':insert:' || COALESCE({new_persisted}, {new_status}, CAST(NEW.rowid AS TEXT)), + NEW.rowid, COALESCE(NULLIF(NEW.row_id, ''), CAST(NEW.rowid AS TEXT)), + NEW.asset_date, NEW.event_time, NEW.record_json + WHERE {_triage_marker('NEW')}; + END + """ + ) + conn.execute( + f""" + CREATE TRIGGER IF NOT EXISTS soc_dashboard_fact_update + AFTER UPDATE OF row_id, asset_date, event_time, source_type, threat_name, is_duplicate, record_json + ON {DEFAULT_SQLITE_TABLE} + BEGIN + DELETE FROM {FACTS_TABLE} + WHERE alert_row_id = NEW.rowid OR row_key = {new_row_key}; + {insert_fact}; + INSERT OR IGNORE INTO {ACTIVITY_TABLE} ( + event_key, alert_row_id, record_row_id, asset_date, event_time, record_json + ) + SELECT COALESCE(NULLIF(NEW.row_id, ''), CAST(NEW.rowid AS TEXT)) || + ':update:' || strftime('%s', 'now') || ':' || lower(hex(randomblob(6))), + NEW.rowid, COALESCE(NULLIF(NEW.row_id, ''), CAST(NEW.rowid AS TEXT)), + NEW.asset_date, NEW.event_time, NEW.record_json + WHERE {_triage_marker('NEW')} + AND NEW.record_json <> OLD.record_json + AND ( + COALESCE({new_persisted}, '') <> COALESCE({old_persisted}, '') + OR COALESCE({new_status}, '') <> COALESCE({old_status}, '') + OR COALESCE({new_report}, '') <> COALESCE({old_report}, '') + ); + END + """ + ) + conn.execute( + f""" + CREATE TRIGGER IF NOT EXISTS soc_dashboard_fact_delete + AFTER DELETE ON {DEFAULT_SQLITE_TABLE} + BEGIN + DELETE FROM {FACTS_TABLE} WHERE alert_row_id = OLD.rowid; + END + """ + ) + + +def ensure_schema(): + db_path = _paths.soc_db() + if not db_path.is_file(): + return False + stat = db_path.stat() + identity = (str(db_path), getattr(stat, "st_ino", 0)) + if identity in _schema_ready: + return True + with _schema_lock: + if identity in _schema_ready: + return True + with sqlite3.connect(db_path, timeout=30) as conn: + conn.execute("PRAGMA busy_timeout = 5000") + exists = conn.execute( + "SELECT 1 FROM sqlite_master WHERE type='table' AND name=?", + (DEFAULT_SQLITE_TABLE,), + ).fetchone() + if not exists: + return False + # One write transaction from dropping the projection triggers to + # creating them again: a writer that slipped in between would add + # an alert no trigger projects into the facts. + conn.execute("BEGIN IMMEDIATE") + _drop_dashboard_triggers(conn) + _ensure_alert_record_columns(conn) + conn.execute( + f"CREATE INDEX IF NOT EXISTS idx_alert_records_asset_event " + f"ON {DEFAULT_SQLITE_TABLE}(asset_date, event_time)" + ) + conn.execute( + f"CREATE INDEX IF NOT EXISTS idx_alert_records_event_time " + f"ON {DEFAULT_SQLITE_TABLE}(event_time)" + ) + conn.execute( + f"CREATE INDEX IF NOT EXISTS idx_alert_records_asset_date " + f"ON {DEFAULT_SQLITE_TABLE}(asset_date)" + ) + conn.execute( + f"CREATE INDEX IF NOT EXISTS idx_alert_records_source_type " + f"ON {DEFAULT_SQLITE_TABLE}(source_type)" + ) + conn.execute( + f"CREATE INDEX IF NOT EXISTS idx_alert_records_threat_name " + f"ON {DEFAULT_SQLITE_TABLE}(threat_name)" + ) + conn.execute( + f"CREATE UNIQUE INDEX IF NOT EXISTS idx_alert_records_row_id " + f"ON {DEFAULT_SQLITE_TABLE}(row_id)" + ) + conn.execute( + f""" + CREATE TABLE IF NOT EXISTS {META_TABLE} ( + meta_key TEXT PRIMARY KEY, + meta_value TEXT NOT NULL + ) + """ + ) + version_row = conn.execute( + f"SELECT meta_value FROM {META_TABLE} WHERE meta_key='schema_version'" + ).fetchone() + needs_rebuild = not version_row or str(version_row[0]) != SCHEMA_VERSION + conn.execute( + f""" + CREATE TABLE IF NOT EXISTS {FACTS_TABLE} ( + alert_row_id INTEGER PRIMARY KEY, + row_key TEXT NOT NULL UNIQUE, + asset_date TEXT NOT NULL, + event_time INTEGER, + source_type TEXT, + threat_name TEXT, + threat_type TEXT, + is_duplicate INTEGER NOT NULL DEFAULT 0, + phase TEXT, + direction TEXT, + result TEXT, + protocol TEXT, + severity TEXT, + response_code TEXT, + port TEXT, + has_triage INTEGER NOT NULL DEFAULT 0, + triage_persisted_at TEXT, + triage_status TEXT, + triage_source TEXT, + triage_attack_verdict TEXT, + risk_level TEXT, + triage_ms INTEGER NOT NULL DEFAULT 0, + triage_attack_success TEXT NOT NULL DEFAULT 'unknown' + ) + """ + ) + if needs_rebuild: + for column_name in _FACT_COLUMNS[1:]: + _add_column_if_missing( + conn, + FACTS_TABLE, + column_name, + _FACT_COLUMN_DEFINITIONS.get(column_name, "TEXT"), + ) + conn.execute( + f"CREATE INDEX IF NOT EXISTS idx_soc_dashboard_facts_asset_event " + f"ON {FACTS_TABLE}(asset_date, event_time)" + ) + conn.execute( + f"CREATE INDEX IF NOT EXISTS idx_soc_dashboard_facts_event " + f"ON {FACTS_TABLE}(event_time, asset_date)" + ) + conn.execute( + f"CREATE INDEX IF NOT EXISTS idx_soc_dashboard_facts_triage_event " + f"ON {FACTS_TABLE}(has_triage, asset_date, event_time)" + ) + conn.execute( + f"CREATE INDEX IF NOT EXISTS idx_soc_dashboard_facts_triage_time " + f"ON {FACTS_TABLE}(has_triage, event_time, asset_date)" + ) + conn.execute( + f""" + CREATE TABLE IF NOT EXISTS {ACTIVITY_TABLE} ( + activity_id INTEGER PRIMARY KEY AUTOINCREMENT, + event_key TEXT NOT NULL UNIQUE, + alert_row_id INTEGER NOT NULL, + record_row_id TEXT NOT NULL, + asset_date TEXT NOT NULL, + event_time INTEGER, + record_json TEXT NOT NULL + ) + """ + ) + conn.execute( + f"CREATE INDEX IF NOT EXISTS idx_soc_dashboard_activity_event " + f"ON {ACTIVITY_TABLE}(asset_date, event_time, activity_id)" + ) + conn.execute( + f"CREATE INDEX IF NOT EXISTS idx_soc_dashboard_activity_time " + f"ON {ACTIVITY_TABLE}(event_time, activity_id)" + ) + if needs_rebuild: + conn.execute(_fact_backfill_sql()) + # Facts of alert rows that are gone (the rest were just recomputed). + conn.execute( + f"DELETE FROM {FACTS_TABLE} WHERE NOT EXISTS (" + f"SELECT 1 FROM {DEFAULT_SQLITE_TABLE} AS source " + f"WHERE source.rowid = {FACTS_TABLE}.alert_row_id)" + ) + persisted = _json_value("source", "_triage_persisted_at") + status_value = _json_value("source", "triage_status") + conn.execute( + f""" + INSERT OR IGNORE INTO {ACTIVITY_TABLE} ( + event_key, alert_row_id, record_row_id, asset_date, event_time, record_json + ) + SELECT COALESCE(NULLIF(source.row_id, ''), CAST(source.rowid AS TEXT)) || ':bootstrap:' || + COALESCE({persisted}, {status_value}, CAST(source.rowid AS TEXT)), + source.rowid, + COALESCE(NULLIF(source.row_id, ''), CAST(source.rowid AS TEXT)), + source.asset_date, + source.event_time, source.record_json + FROM {DEFAULT_SQLITE_TABLE} AS source + WHERE {_triage_marker('source')} + """ + ) + conn.execute( + f"INSERT OR REPLACE INTO {META_TABLE}(meta_key, meta_value) " + f"VALUES('schema_version', ?)", + (SCHEMA_VERSION,), + ) + _create_dashboard_triggers(conn) + conn.commit() + _schema_ready.add(identity) + return True + + +def _maybe_prune_activity(): + global _activity_pruned_at + now = time.monotonic() + if now - _activity_pruned_at < ACTIVITY_PRUNE_INTERVAL: + return + with _schema_lock: + if now - _activity_pruned_at < ACTIVITY_PRUNE_INTERVAL: + return + try: + with sqlite3.connect(_paths.soc_db(), timeout=5) as conn: + conn.execute( + f"DELETE FROM {ACTIVITY_TABLE} WHERE activity_id <= " + f"(SELECT COALESCE(MAX(activity_id), 0) - ? FROM {ACTIVITY_TABLE})", + (ACTIVITY_RETENTION_ROWS,), + ) + conn.commit() + except Exception: + pass + _activity_pruned_at = now + + +def _safe_json_object(value): + try: + parsed = json.loads(value or "{}") + except Exception: + return {} + return parsed if isinstance(parsed, dict) else {} + + +def _usage_iso(dt): + return dt.astimezone(timezone.utc).isoformat() + + +def token_usage(): + empty = { + "totalTokens": 0, + "todayTokens": 0, + "todayRequests": 0, + "dailySeries": [], + "dailyLabels": [], + "source": "usage_records", + } + if not _paths.usage_db().is_file(): + return empty + + try: + mtime_ns = _paths.usage_db().stat().st_mtime_ns + except Exception: + mtime_ns = 0 + now_monotonic = time.monotonic() + with _cache_lock: + cached_value = _token_usage_cache.get("value") + if ( + cached_value is not None + and _token_usage_cache.get("mtimeNs") == mtime_ns + and now_monotonic - float(_token_usage_cache.get("updatedAt") or 0) < _TOKEN_USAGE_CACHE_TTL + ): + return cached_value + + now_local = datetime.now().astimezone() + today_start = now_local.replace(hour=0, minute=0, second=0, microsecond=0) + tomorrow_start = today_start + timedelta(days=1) + first_day = today_start - timedelta(days=6) + labels = [(first_day + timedelta(days=index)).strftime("%m/%d") for index in range(7)] + series_by_date = { + (first_day + timedelta(days=index)).date().isoformat(): 0 + for index in range(7) + } + + try: + with sqlite3.connect(f"file:{_paths.usage_db()}?mode=ro", uri=True, timeout=1.0) as conn: + conn.execute("PRAGMA query_only = ON") + if not _table_exists(conn, "usage_records"): + return {**empty, "dailyLabels": labels, "dailySeries": [0] * 7} + total_tokens = _safe_int( # secret-guard: allow (a count of model tokens, not a credential) + conn.execute( + "SELECT COALESCE(SUM(total_tokens), 0) FROM usage_records" + ).fetchone()[0] + ) + today_row = conn.execute( + "SELECT COALESCE(SUM(total_tokens), 0), COUNT(*) " + "FROM usage_records WHERE created_at >= ? AND created_at < ?", + (_usage_iso(today_start), _usage_iso(tomorrow_start)), + ).fetchone() + series_rows = conn.execute( + "SELECT date(created_at, 'localtime') AS usage_day, " + "COALESCE(SUM(total_tokens), 0) AS token_count " + "FROM usage_records WHERE created_at >= ? AND created_at < ? " + "GROUP BY usage_day", + (_usage_iso(first_day), _usage_iso(tomorrow_start)), + ).fetchall() + except Exception: + return {**empty, "dailyLabels": labels, "dailySeries": [0] * 7} + + for usage_day, total in series_rows: + key = str(usage_day or "") + if key in series_by_date: + series_by_date[key] += max(_safe_int(total), 0) + + result = { + **empty, + "totalTokens": max(total_tokens, 0), + "todayTokens": max(_safe_int(today_row[0]), 0) if today_row else 0, + "todayRequests": max(_safe_int(today_row[1]), 0) if today_row else 0, + "dailySeries": list(series_by_date.values()), + "dailyLabels": labels, + } + with _cache_lock: + _token_usage_cache.update({"updatedAt": now_monotonic, "mtimeNs": mtime_ns, "value": result}) + return result + + +def _workflow_stats_sample_deltas(conn, workflow_name, start_time=0, end_time=0): + stats_exists = conn.execute( + "SELECT 1 FROM sqlite_master WHERE type='table' AND name='workflow_stats'" + ).fetchone() + if not stats_exists: + return None + columns = { + row[1] for row in conn.execute("PRAGMA table_info(workflow_stats)").fetchall() + } + success_expr = "success_count" if "success_count" in columns else "0" + error_expr = "error_count" if "error_count" in columns else "0" + updated_expr = "updated_at" if "updated_at" in columns else "0" + current = conn.execute( + f"SELECT call_count, {success_expr}, {error_expr}, {updated_expr} " + "FROM workflow_stats WHERE workflow_id = ?", + (workflow_name,), + ).fetchone() + if current is None: + return None + + conn.execute( + f""" + CREATE TABLE IF NOT EXISTS {WORKFLOW_SNAPSHOT_TABLE} ( + workflow_id TEXT NOT NULL, + sampled_at INTEGER NOT NULL, + call_count INTEGER NOT NULL, + success_count INTEGER NOT NULL DEFAULT 0, + error_count INTEGER NOT NULL DEFAULT 0, + PRIMARY KEY (workflow_id, sampled_at) + ) + """ + ) + last = conn.execute( + f"SELECT sampled_at, call_count, success_count, error_count " + f"FROM {WORKFLOW_SNAPSHOT_TABLE} WHERE workflow_id = ? " + "ORDER BY sampled_at DESC LIMIT 1", + (workflow_name,), + ).fetchone() + current_count = max(_safe_int(current[0]), 0) + success_count = max(_safe_int(current[1]), 0) + error_count = max(_safe_int(current[2]), 0) + if last is None or (current_count, success_count, error_count) != tuple(last[1:4]): + stats_updated_at = _safe_int(current[3]) or int(time.time() * 1000) + sampled_at = stats_updated_at - (stats_updated_at % 60000) + if last is not None and sampled_at <= _safe_int(last[0]): + sampled_at = _safe_int(last[0]) + conn.execute( + f"UPDATE {WORKFLOW_SNAPSHOT_TABLE} " + "SET call_count = ?, success_count = ?, error_count = ? " + "WHERE workflow_id = ? AND sampled_at = ?", + (current_count, success_count, error_count, workflow_name, sampled_at), + ) + else: + conn.execute( + f"INSERT INTO {WORKFLOW_SNAPSHOT_TABLE} " + "(workflow_id, sampled_at, call_count, success_count, error_count) " + "VALUES (?, ?, ?, ?, ?)", + (workflow_name, sampled_at, current_count, success_count, error_count), + ) + conn.commit() + last = (sampled_at, current_count, success_count, error_count) + + if not (start_time > 0 and end_time > 0): + sampled_at = max(_safe_int(current[3]), _safe_int(last[0] if last else 0)) + return [(current_count, success_count, error_count, sampled_at)] if current_count else [] + + start_ms = int(start_time * 1000) + end_ms = int(end_time * 1000) + previous = conn.execute( + f"SELECT call_count, success_count, error_count " + f"FROM {WORKFLOW_SNAPSHOT_TABLE} " + "WHERE workflow_id = ? AND sampled_at < ? " + "ORDER BY sampled_at DESC LIMIT 1", + (workflow_name, start_ms), + ).fetchone() + rows = conn.execute( + f"SELECT sampled_at, call_count, success_count, error_count " + f"FROM {WORKFLOW_SNAPSHOT_TABLE} " + "WHERE workflow_id = ? AND sampled_at >= ? AND sampled_at <= ? " + "ORDER BY sampled_at", + (workflow_name, start_ms, end_ms), + ).fetchall() + previous_counts = tuple(previous) if previous is not None else (0, 0, 0) + deltas = [] + for sampled_at, call_count, sample_success, sample_error in rows: + current_counts = ( + max(_safe_int(call_count), 0), + max(_safe_int(sample_success), 0), + max(_safe_int(sample_error), 0), + ) + delta_counts = tuple( + current_value - previous_value + if current_value >= previous_value + else current_value + for current_value, previous_value in zip(current_counts, previous_counts) + ) + if delta_counts[0] > 0: + deltas.append((*delta_counts, _safe_int(sampled_at))) + previous_counts = current_counts + return deltas + + +def _workflow_stats_call_delta_from_samples(conn, workflow_name, start_ms, end_ms): + if not _table_exists(conn, WORKFLOW_SNAPSHOT_TABLE): + return None + previous = conn.execute( + f"SELECT call_count FROM {WORKFLOW_SNAPSHOT_TABLE} " + "WHERE workflow_id = ? AND sampled_at < ? " + "ORDER BY sampled_at DESC LIMIT 1", + (workflow_name, start_ms), + ).fetchone() + if previous is None: + return None + rows = conn.execute( + f"SELECT sampled_at, call_count FROM {WORKFLOW_SNAPSHOT_TABLE} " + "WHERE workflow_id = ? AND sampled_at >= ? AND sampled_at < ? " + "ORDER BY sampled_at", + (workflow_name, start_ms, end_ms), + ).fetchall() + if not rows: + return None + total = 0 + previous_count = max(_safe_int(previous[0]), 0) + for _, call_count in rows: + current_count = max(_safe_int(call_count), 0) + total += ( + current_count - previous_count + if current_count >= previous_count + else current_count + ) + previous_count = current_count + return max(total, 0) + + +def _workflow_metric_value(stats, key, fallback=0): + value = stats.get(key) + return max(_safe_int(fallback if value is None else value), 0) + + +def _workflow_alert_preview(output): + for key in ("unique_alerts", "enriched_alerts"): + value = output.get(key) + if isinstance(value, dict): + value = value.get("preview") + if isinstance(value, list): + return next( + ( + item + for item in value + if isinstance(item, dict) and item.get("_type") != "dict" + ), + {}, + ) + return {} + + +def _workflow_input_preview(inputs): + syslog_message = inputs.get("syslog_message") or inputs.get("syslog") + if isinstance(syslog_message, dict): + message = syslog_message.get("message") + if isinstance(message, str): + parsed = _safe_json_object(message) + if parsed: + return parsed + alerts = inputs.get("alerts") or inputs.get("alert_list") + if isinstance(alerts, dict): + alerts = alerts.get("data") + if isinstance(alerts, list): + return next((item for item in alerts if isinstance(item, dict)), {}) + return {} + + +def _workflow_execution_metrics(output_text, input_text=""): + output = _safe_json_object(output_text) + inputs = _safe_json_object(input_text) + stats = output.get("stats") if isinstance(output.get("stats"), dict) else {} + duplicate_flag_available = isinstance(output.get("is_duplicate"), bool) + metrics_available = duplicate_flag_available or any( + stats.get(key) is not None + for key in ( + "raw_count", + "normalized_count", + "after_filter_count", + "after_dedup_count", + ) + ) + raw_count = _workflow_metric_value(stats, "raw_count", 1) + normalized_count = _workflow_metric_value(stats, "normalized_count", raw_count) + after_filter_count = _workflow_metric_value( + stats, + "after_filter_count", + normalized_count, + ) + unique_count = _workflow_metric_value( + stats, + "after_dedup_count", + after_filter_count, + ) + filter_removed_count = _workflow_metric_value( + stats, + "filter_removed_count", + max(normalized_count - after_filter_count, 0), + ) + duplicate_count = _workflow_metric_value( + stats, + "dedup_removed_count", + max(after_filter_count - unique_count, 0), + ) + is_duplicate = output.get("is_duplicate") is True + if ( + is_duplicate + and raw_count == 1 + and after_filter_count == 1 + and unique_count == 1 + and duplicate_count == 0 + ): + # Older streaming executions only counted duplicates within the current + # one-alert batch, even when cross-batch state marked it as duplicate. + unique_count = 0 + duplicate_count = 1 + reduced_count = ( + max(raw_count - unique_count, filter_removed_count + duplicate_count, 0) + if metrics_available + else 0 + ) + + source_counts = {} + raw_source_counts = stats.get("normalize_type_counts") + if isinstance(raw_source_counts, dict) and raw_source_counts.get("_type") != "dict": + source_counts = { + _norm(key): max(_safe_int(value), 0) + for key, value in raw_source_counts.items() + if max(_safe_int(value), 0) > 0 + } + preview = _workflow_alert_preview(output) or _workflow_input_preview(inputs) + syslog_message = inputs.get("syslog_message") or inputs.get("syslog") + syslog_app = syslog_message.get("app_name") if isinstance(syslog_message, dict) else "" + source_type = _norm( + preview.get("_source_type") + or inputs.get("source_log_type") + or output.get("source_log_type") + or output.get("input_mode") + or syslog_app + ) + if not source_counts and normalized_count > 0: + source_counts[source_type] = normalized_count + + return { + "metricsAvailable": metrics_available, + "rawCount": raw_count, + "normalizedCount": normalized_count, + "afterFilterCount": after_filter_count, + "uniqueCount": unique_count, + "filterRemovedCount": filter_removed_count, + "duplicateCount": duplicate_count, + "reducedCount": reduced_count, + "reductionRate": _ratio(reduced_count, raw_count) if metrics_available else 0, + "dedupRate": _ratio(duplicate_count, after_filter_count) if metrics_available else 0, + "clusterCount": _workflow_metric_value(stats, "lsh_total_clusters"), + "isDuplicate": is_duplicate, + "sourceCounts": source_counts, + "sourceType": source_type, + "preview": preview, + } + + +def _empty_workflow_denoise_stats(): + return { + "callCount": 0, + "successCount": 0, + "errorCount": 0, + "earliestStartedAt": 0, + "latestStartedAt": 0, + "rawCount": 0, + "normalizedCount": 0, + "afterFilterCount": 0, + "uniqueCount": 0, + "filterRemovedCount": 0, + "duplicateCount": 0, + "reducedCount": 0, + "reductionRate": 0, + "dedupRate": 0, + "sourceCounts": {}, + "seriesRaw": [], + "seriesUnique": [], + "timelineLabels": [], + "timelineWindow": "", + } + + +def workflow_denoise_stats( + workflow_name: str, + start_time: int = 0, + end_time: int = 0, + *, + force: bool = False, +) -> dict: + now = time.time() + cache_key = f"denoise:{workflow_name}:{start_time or 0}:{end_time or 0}" + + with _cache_lock: + cached = _workflow_stats_cache.get(cache_key) + if not force and cached and now - float(cached.get("updatedAt") or 0) < _CACHE_TTL: + _workflow_stats_cache.move_to_end(cache_key) + return cached["value"] + + empty = _empty_workflow_denoise_stats() + if not _paths.workflow_db().is_file(): + return empty + + try: + with sqlite3.connect(_paths.workflow_db()) as conn: + sample_deltas = _workflow_stats_sample_deltas( + conn, + workflow_name, + start_time, + end_time, + ) + if sample_deltas is None: + query = ( + "SELECT status, started_at FROM workflow_executions " + "WHERE workflow_id = ?" + ) + query_params = [workflow_name] + if start_time > 0 and end_time > 0: + query += " AND started_at >= ? AND started_at <= ?" + query_params.extend((int(start_time * 1000), int(end_time * 1000))) + query += " ORDER BY started_at" + execution_rows = conn.execute(query, query_params).fetchall() + samples = [ + ( + 1, + 1 if str(status).lower() == "success" else 0, + 0 if str(status).lower() == "success" else 1, + _safe_int(started_at), + ) + for status, started_at in execution_rows + ] + else: + samples = sample_deltas + + result_dict = _empty_workflow_denoise_stats() + processed_total = sum(call_count for call_count, _, _, _ in samples) + if processed_total: + result_dict.update( + { + "callCount": processed_total, + "successCount": sum(success_count for _, success_count, _, _ in samples), + "errorCount": sum(error_count for _, _, error_count, _ in samples), + "earliestStartedAt": samples[0][3], + "latestStartedAt": samples[-1][3], + "rawCount": processed_total, + "normalizedCount": processed_total, + "afterFilterCount": processed_total, + "sourceCounts": {"ndr": processed_total}, + } + ) + first_started = samples[0][3] // 1000 + last_started = samples[-1][3] // 1000 + bucket_start, bucket_seconds, bucket_count, labels, window = _timeline_spec( + [], + start_time or first_started, + end_time or max(last_started, first_started), + ) + series_raw = [0] * bucket_count + for call_count, _, _, started_at in samples: + index = int(((started_at // 1000) - bucket_start) / bucket_seconds) + if 0 <= index < bucket_count: + series_raw[index] += call_count + result_dict["seriesRaw"] = series_raw + result_dict["timelineLabels"] = labels + result_dict["timelineWindow"] = window + + with _cache_lock: + _workflow_stats_cache[cache_key] = {"updatedAt": now, "value": result_dict} + _workflow_stats_cache.move_to_end(cache_key) + while len(_workflow_stats_cache) > _WORKFLOW_CACHE_MAX: + _workflow_stats_cache.popitem(last=False) + return result_dict + except Exception: + with _cache_lock: + cached = _workflow_stats_cache.get(cache_key) + return cached["value"] if cached else empty + + +def workflow_progress( + workflow_name: str, + start_time: int = 0, + end_time: int = 0, +) -> dict: + unavailable = {"callCount": None, "latestStartedAt": None} + if not _paths.workflow_db().is_file(): + return unavailable + + try: + with sqlite3.connect(_paths.workflow_db()) as conn: + if start_time > 0 and end_time > 0: + sample_deltas = _workflow_stats_sample_deltas( + conn, + workflow_name, + start_time, + end_time, + ) + if sample_deltas is None: + row = conn.execute( + "SELECT COUNT(*), COALESCE(MAX(started_at), 0) " + "FROM workflow_executions " + "WHERE workflow_id = ? AND started_at >= ? AND started_at <= ?", + (workflow_name, int(start_time * 1000), int(end_time * 1000)), + ).fetchone() + else: + latest_row = conn.execute( + "SELECT COALESCE(MAX(started_at), 0) FROM workflow_executions " + "WHERE workflow_id = ? AND started_at >= ? AND started_at <= ?", + (workflow_name, int(start_time * 1000), int(end_time * 1000)), + ).fetchone() + latest_sample = sample_deltas[-1][3] if sample_deltas else 0 + row = ( + sum(max(_safe_int(item[0]), 0) for item in sample_deltas), + max(_safe_int(latest_row[0] if latest_row else 0), _safe_int(latest_sample)), + ) + else: + row = conn.execute( + "SELECT call_count FROM workflow_stats WHERE workflow_id = ?", + (workflow_name,), + ).fetchone() + except Exception: + return unavailable + + if row is None: + return {"callCount": 0, "latestStartedAt": 0} + return { + "callCount": max(_safe_int(row[0]), 0), + "latestStartedAt": max(_safe_int(row[1] if len(row) > 1 else 0), 0), + } + + +def _dashboard_execution_detail(output_text, input_text): + """Read a bounded preview for this execution only; never open result files. + + Kept separate from metric aggregation and task-center/workflow contracts. + A missing count is not zero (nor an assumed single-alert batch). + """ + output = _safe_json_object(output_text) + inputs = _safe_json_object(input_text) + def text(*values): + return _first_text(*(value[:512] for value in values if isinstance(value, str))) + + queue = [(value, 0) for value in ( + output.get("enriched_alerts_with_triage"), output.get("triage_results"), + output.get("unique_alerts"), output.get("enriched_alerts"), + inputs.get("_soc_alert_preview"), inputs.get("alerts"), + inputs.get("alert_list"), inputs.get("syslog_message"), inputs.get("syslog"), + ) if value is not None] + best, best_score = {}, 0 + for _ in range(48): + if not queue: + break + value, depth = queue.pop(0) + if depth > 6: + continue + if isinstance(value, str): + if len(value) > 65536: + continue + # Syslog prefixes can precede a vendor JSON envelope. + start = value.find("{") + parsed = _safe_json_object(value[start:] if start >= 0 else value) + if parsed: + queue.append((parsed, depth + 1)) + elif isinstance(value, list): + queue.extend((item, depth + 1) for item in value[:3]) + elif isinstance(value, dict): + if value.get("_type") == "dict": + continue # Persisted key-only summary, not an alert. + alert = { + "id": text(value.get("id"), value.get("alert_id"), value.get("uuid")), + "threatName": text(value.get("threat_name"), value.get("alert_name"), value.get("attack_name")), + "sourceType": text(value.get("_source_type"), value.get("source_type"), value.get("device_type")), + "srcIp": text(value.get("sip"), value.get("src_ip"), value.get("source_ip"), value.get("net_real_src_ip")), + "dstIp": text(value.get("dip"), value.get("dst_ip"), value.get("destination_ip"), value.get("net_dest_ip")), + } + score = sum(bool(alert[key]) for key in ("threatName", "srcIp", "dstIp")) + if score > best_score: + best, best_score = alert, score + for key in ("preview", "data", "alert", "alerts", "message", "msg", "log", "event", "payload"): + if key in value: + queue.append((value[key], depth + 1)) + stats = output.get("stats") if isinstance(output.get("stats"), dict) else {} + raw = stats.get("raw_count", inputs.get("_soc_alert_count")) + try: + count = int(raw) if raw is not None and not isinstance(raw, bool) else None + if count is not None and (count < 0 or str(raw).strip() != str(count)): + count = None + except (ValueError, TypeError, OverflowError): + count = None + if count is None: + alerts = inputs.get("alerts", inputs.get("alert_list")) + if isinstance(alerts, list): + count = len(alerts) + if best: + best["sourceType"] = best["sourceType"] or text( + inputs.get("source_log_type"), output.get("source_log_type") + ) + return best, count + + +def workflow_recent_events( + workflow_name: str, + start_time: int = 0, + end_time: int = 0, + limit: int = 10, + snapshot=None, +) -> list: + # Polling must not multiply native SQLite allocations across dashboard tabs. + # The worker owns this lock until its reads/parsing actually finish, even if + # the HTTP request awaiting asyncio.to_thread is cancelled. + if not _workflow_activity_read_lock.acquire(blocking=False): + if snapshot is not None: + snapshot.update(complete=False, available=False) + return [] + try: + return _read_workflow_recent_events(workflow_name, start_time, end_time, limit, snapshot) + finally: + _workflow_activity_read_lock.release() + + +def _read_workflow_recent_events(workflow_name, start_time, end_time, limit, snapshot): + if not _paths.workflow_db().is_file(): + if snapshot is not None: + snapshot.update(complete=False, available=False) + return [] + workflow_stage = "triage" if workflow_name in TRIAGE_WORKFLOW_IDS else "denoise" + try: + with closing(sqlite3.connect(f"{_paths.workflow_db().resolve().as_uri()}?mode=ro", uri=True, timeout=0.2)) as conn: + deadline = time.monotonic() + 0.2 + conn.set_progress_handler(lambda: int(time.monotonic() > deadline), 100) + conn.row_factory = sqlite3.Row + conn.execute("BEGIN") + execution_columns = { + row[1] + for row in conn.execute("PRAGMA table_info(workflow_executions)").fetchall() + } + # octet_length(column) reads the record's byte-length metadata, not + # the entire TEXT. length(TEXT), including a cast-based fallback, + # is NOT a native-memory bound. Older SQLite must omit previews. + try: + conn.execute("SELECT octet_length('')").fetchone() + has_octet_length = True + except sqlite3.OperationalError: + has_octet_length = False + + def preview_column(name): + if name not in execution_columns or not has_octet_length: + return f"'{{}}' AS {name}" + return f"CASE WHEN octet_length({name}) <= 262144 THEN {name} ELSE '{{}}' END AS {name}" + + metadata_select = ", ".join([ + "id", "status", "started_at", + _workflow_execution_column_expr(execution_columns, "updated_at", "started_at"), + ]) + query = f"SELECT {metadata_select} FROM workflow_executions WHERE workflow_id = ?" + query_params = [workflow_name] + if start_time > 0 and end_time > 0: + query += " AND started_at >= ? AND started_at <= ?" + query_params.extend((int(start_time * 1000), int(end_time * 1000))) + row_limit = max(1, min(_safe_int(limit), 10)) + active_rows = conn.execute( + query + " AND status IN ('running', 'queued', 'pending') ORDER BY started_at DESC LIMIT ?", + [*query_params, row_limit], + ).fetchall() + recent_rows = conn.execute(query + " ORDER BY started_at DESC LIMIT ?", [*query_params, row_limit]).fetchall() + ids = list(dict.fromkeys(row["id"] for row in [*active_rows, *recent_rows])) + if time.monotonic() > deadline: + raise sqlite3.OperationalError("activity read budget exceeded") + # Select payloads only AFTER bounding IDs; a sorting query must not + # materialize previews for every matching execution before LIMIT. + rows = [] + if ids: + previews = ", ".join(preview_column(name) for name in ("output_results", "input_params", "payload")) + placeholders = ",".join("?" for _ in ids) + by_id = {row["id"]: row for row in conn.execute( + f"SELECT {metadata_select}, {previews} FROM workflow_executions WHERE id IN ({placeholders})", + ids, + ).fetchall()} + rows = [by_id[key] for key in ids] + if time.monotonic() > deadline: + raise sqlite3.OperationalError("activity read budget exceeded") + if snapshot is not None and len(active_rows) == row_limit: + snapshot["complete"] = False + except Exception: + if snapshot is not None: + snapshot.update(complete=False, available=False) + return [] + + events = [] + for row in rows: + execution_id = row["id"] + status = row["status"] + started_at = row["started_at"] + output_text = row["output_results"] + input_text = row["input_params"] + payload_text = row["payload"] + metrics = _workflow_execution_metrics(output_text, input_text) + alert, raw_count = _dashboard_execution_detail(output_text, input_text) + if workflow_stage == "denoise" and raw_count == 0 and not alert: + continue # No alert work; keep the execution itself untouched. + unique_count = metrics["uniqueCount"] + threat_name = alert.get("threatName", "") + if not threat_name and workflow_stage == "triage": + threat_name = _workflow_latest_alert_name(workflow_name, output_text, input_text) + if not threat_name: + threat_name = f"降噪批次 · 原始 {raw_count} 条" if raw_count and raw_count > 0 else "降噪批次 · 数量未提供" + normalized_status = str(status or "").lower() + event_status = ( + "completed" + if normalized_status in {"success", "completed"} + else normalized_status + if normalized_status in {"running", "queued", "pending"} + else "failed" + ) + session_id, message_id = _workflow_link_context( + { + "payload": payload_text, + "input_params": input_text, + } + ) + events.append( + { + "eventId": f"workflow-execution:{execution_id}", + "stage": workflow_stage, + "status": event_status, + "occurredAt": datetime.fromtimestamp( + _safe_int(started_at) / 1000 + ).astimezone().isoformat(timespec="seconds"), + "updatedAt": datetime.fromtimestamp( + _safe_int(row["updated_at"] or started_at) / 1000 + ).astimezone().isoformat(timespec="milliseconds"), + "triggerSource": "workflow_execution", + "workflowId": workflow_name, + "sessionId": session_id, + "messageId": message_id, + "sampleCount": max(unique_count, 1), + "alert": { + **alert, + "id": alert.get("id") or "", + "threatName": threat_name, + }, + "result": { + "isDuplicate": metrics["isDuplicate"], + "clusterId": str(metrics["clusterCount"] or "--"), + **{ + key: value + for key, value in metrics.items() + if key not in {"preview", "sourceCounts", "sourceType"} + }, + "rawCount": raw_count, + }, + } + ) + return events + +RESULT_LABELS = { + "attack_success": "攻击成功", + "attack": "攻击行为", + "attack_failed": "攻击失败", + "non_attack": "非攻击", + "unknown": "待确认", +} + + +def _triage_outcome_key(record): + verdict = _triage_attack_verdict_value(record) + result = _triage_attack_success_value(record) + if verdict == "attack": + if result == "success": + return "attack_success" + if result == "failed": + return "attack_failed" + return "attack" + if verdict == "non_attack": + return "non_attack" + return "unknown" + + +def _triage_attack_verdict_value(record): + verdict = _norm(record.get("triage_attack_verdict") or "unknown") + if verdict in {"attack", "non_attack", "unknown"}: + return verdict + if verdict in {"attack_success", "attack_failed"}: + return "attack" + if verdict == "benign": + return "non_attack" + return "unknown" + + +def _triage_attack_success_value(record): + # Same precedence as the SQL projection (normalized_triage_success): an + # explicit result string wins; older records carry the outcome in the + # verdict ("attack_success" / "attack_failed") or as a boolean result. + # A missing result is not an explicit "unknown". + if _triage_attack_verdict_value(record) != "attack": + return "unknown" + raw_result = record.get("triage_attack_success") + result = str(raw_result).strip().lower() if raw_result is not None else "" + if result in {"success", "failed", "unknown"}: + return result + raw_verdict = _norm(record.get("triage_attack_verdict")) + if raw_verdict == "attack_success": + return "success" + if raw_verdict == "attack_failed": + return "failed" + if result in {"1", "true"}: + return "success" + return "unknown" + + +def _table_exists(conn, table_name): + return bool( + conn.execute( + "SELECT 1 FROM sqlite_master WHERE type='table' AND name=?", + (table_name,), + ).fetchone() + ) + + +def _task_trigger_value(trigger, key): + if not isinstance(trigger, dict): + return "" + return trigger.get(key) or trigger.get(key[0].lower() + key[1:]) or "" + + +def _today_bounds(): + now_local = datetime.now().astimezone() + today_start = now_local.replace(hour=0, minute=0, second=0, microsecond=0) + return today_start, today_start + timedelta(days=1) + + +def task_center_tasks(limit=12): + if not _paths.task_db().is_file(): + return 0, [], 0, 0, 0 + try: + with sqlite3.connect(f"file:{_paths.task_db()}?mode=ro", uri=True, timeout=1.0) as conn: + conn.row_factory = sqlite3.Row + conn.execute("PRAGMA query_only = ON") + if not ( + _table_exists(conn, "task_schedulers") + and _table_exists(conn, "task_executions") + ): + return 0, [], 0, 0, 0 + today_start, tomorrow_start = _today_bounds() + today_start_iso = today_start.isoformat(timespec="seconds") + tomorrow_start_iso = tomorrow_start.isoformat(timespec="seconds") + session_count = _safe_int( + conn.execute( + "SELECT COUNT(DISTINCT session_id) FROM task_executions " + "WHERE session_id IS NOT NULL AND session_id <> ''" + ).fetchone()[0] + ) + scheduler_rows = conn.execute( + "SELECT id, title, mode, status, trigger, execution_mode, workflow_id, updated_at " + "FROM task_schedulers WHERE status <> 'archived' " + "ORDER BY updated_at DESC" + ).fetchall() + tasks = [] + for scheduler in scheduler_rows: + summary = conn.execute( + "SELECT COUNT(*) AS execution_count, " + "SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) AS success_count, " + "SUM(CASE WHEN status IN ('pending', 'queued', 'running') THEN 1 ELSE 0 END) AS active_count, " + "SUM(CASE WHEN " + "julianday(COALESCE(started_at, queued_at, created_at)) >= julianday(?) " + "AND julianday(COALESCE(started_at, queued_at, created_at)) < julianday(?) " + "THEN 1 ELSE 0 END) AS today_execution_count " + "FROM task_executions WHERE scheduler_id = ?", + (today_start_iso, tomorrow_start_iso, scheduler["id"]), + ).fetchone() + latest = conn.execute( + "SELECT status, queued_at, started_at, completed_at, updated_at " + "FROM task_executions WHERE scheduler_id = ? " + "ORDER BY julianday(COALESCE(completed_at, updated_at, started_at, queued_at, created_at)) DESC " + "LIMIT 1", + (scheduler["id"],), + ).fetchone() + trigger = _safe_json_object(scheduler["trigger"]) + execution_count = max(_safe_int(summary["execution_count"]), 0) + success_count = max(_safe_int(summary["success_count"]), 0) + active_count = max(_safe_int(summary["active_count"]), 0) + today_execution_count = max(_safe_int(summary["today_execution_count"]), 0) + last_run_at = "" + if latest: + last_run_at = latest["completed_at"] or latest["updated_at"] or latest["started_at"] or latest["queued_at"] or "" + tasks.append( + { + "id": scheduler["id"], + "name": scheduler["title"] or scheduler["id"], + "mode": scheduler["mode"] or "once", + "status": scheduler["status"] or "active", + "executionMode": scheduler["execution_mode"] or "agent", + "workflowId": scheduler["workflow_id"] or "", + "executionCount": execution_count, + "todayExecutionCount": today_execution_count, + "successCount": success_count, + "successRate": _ratio(success_count, execution_count), + "activeCount": active_count, + "lastStatus": latest["status"] if latest else "", + "lastRunAt": last_run_at, + "nextRunAt": _task_trigger_value(trigger, "nextRun"), + "cron": _task_trigger_value(trigger, "cron"), + "cronDescription": _task_trigger_value(trigger, "cronDescription"), + } + ) + tasks.sort( + key=lambda item: ( + item["activeCount"] > 0, + item["lastRunAt"] or "", + item["executionCount"], + ), + reverse=True, + ) + return ( + session_count, + tasks[:limit], + sum(task["executionCount"] for task in tasks), + sum(task["todayExecutionCount"] for task in tasks), + sum(task["activeCount"] for task in tasks), + ) + except Exception: + return 0, [], 0, 0, 0 + + +def _workflow_manifest_name_map(): + roots = _paths.workflow_roots() + names = {} + for root in roots: + if not root.is_dir(): + continue + for manifest_path in root.glob("*/manifest.json"): + workflow_id = manifest_path.parent.name + try: + manifest = _safe_json_object(manifest_path.read_text(encoding="utf-8")) + except Exception: + manifest = {} + name = ( + manifest.get("nameCn") + or manifest.get("name") + or manifest.get("title") + or workflow_id + ) + name_i18n = manifest.get("nameI18n") + if isinstance(name_i18n, dict): + name = name_i18n.get("zh-CN") or name_i18n.get("zh") or name + names.setdefault(workflow_id, str(name)) + return names + + +def _workflow_config_name_map(conn): + if not _table_exists(conn, "workflow_configs"): + return {} + names = {} + for row in conn.execute( + "SELECT workflow_id, config FROM workflow_configs WHERE kind = ?", + ("workflow.integration-config",), + ).fetchall(): + workflow_id = row["workflow_id"] if isinstance(row, sqlite3.Row) else row[0] + config_raw = row["config"] if isinstance(row, sqlite3.Row) else row[1] + if not workflow_id: + continue + config = _safe_json_object(config_raw) + workflow = config.get("workflow") + if not isinstance(workflow, dict): + continue + name = workflow.get("name") or workflow.get("title") or workflow.get("id") + if name: + names.setdefault(str(workflow_id), str(name)) + return names + + +def _truthy_config_value(value): + if isinstance(value, bool): + return value + if isinstance(value, (int, float)): + return value != 0 + text = str(value or "").strip().lower() + if not text: + return False + return text in {"1", "true", "yes", "on", "enabled"} + + +def _workflow_trigger_state(conn, workflow_id): + state = { + "hasConfig": False, + "enabled": True, + "timeoutSeconds": WORKFLOW_DEFAULT_ACTIVE_TIMEOUT_SECONDS, + } + if not _table_exists(conn, "workflow_configs"): + return state + + placeholders = ",".join("?" for _ in WORKFLOW_TRIGGER_CONFIG_KINDS) + rows = conn.execute( + "SELECT kind, config FROM workflow_configs WHERE workflow_id = ? " + f"AND (kind IN ({placeholders}) OR kind LIKE ? OR kind LIKE ? OR kind LIKE ?)", + ( + workflow_id, + *WORKFLOW_TRIGGER_CONFIG_KINDS, + "workflow_kafka_config/%", + "workflow_poller_config/%", + "workflow_syslog_config/%", + ), + ).fetchall() + if not rows: + return state + + enabled = False + timeout_seconds = WORKFLOW_DEFAULT_ACTIVE_TIMEOUT_SECONDS + for row in rows: + config = _safe_json_object(row["config"] if isinstance(row, sqlite3.Row) else row[1]) + if "enabled" not in config or _truthy_config_value(config.get("enabled")): + enabled = True + timeout_seconds = max( + timeout_seconds, + _safe_int(config.get("timeoutSeconds") or config.get("timeout_seconds")), + ) + state["hasConfig"] = True + state["enabled"] = enabled + state["timeoutSeconds"] = max(timeout_seconds, WORKFLOW_MIN_ACTIVE_TIMEOUT_SECONDS) + return state + + +def _workflow_effective_status(latest, active_count, trigger_state): + if not latest: + return "" + status = str(latest["status"] or "").lower() + if status not in WORKFLOW_RUNNING_STATUSES: + return status + if active_count > 0: + return status + if trigger_state.get("hasConfig") and not trigger_state.get("enabled"): + return "disabled" + return "stale" + + +def _workflow_execution_column_expr(columns, column_name, fallback): + return column_name if column_name in columns else f"{fallback} AS {column_name}" + + +def _workflow_node_count(workflow_id): + roots = _paths.workflow_roots() + for root in roots: + workflow_path = root / str(workflow_id) / "workflow.json" + if not workflow_path.is_file(): + continue + try: + workflow_json = _safe_json_object(workflow_path.read_text(encoding="utf-8")) + nodes = workflow_json.get("nodes") + if isinstance(nodes, list): + return max(len(nodes), 0) + except Exception: + continue + return 0 + + +def _first_text(*values): + for value in values: + text = str(value or "").strip() + if text and text.lower() not in {"unknown", "none", "null", "--"}: + return text + return "" + + +def _alert_name_from_record(record): + if not isinstance(record, dict): + return "" + return _first_text( + record.get("threat_name"), + record.get("_threat_type"), + record.get("threat_type"), + record.get("alert_name"), + record.get("name"), + record.get("report_title"), + record.get("title"), + ) + + +def _workflow_latest_alert_name(workflow_id, output_text="", input_text=""): + output = _safe_json_object(output_text) + inputs = _safe_json_object(input_text) + preview = _workflow_alert_preview(output) or _workflow_input_preview(inputs) + name = _alert_name_from_record(preview) + if name: + return name + for key in ( + "enriched_alerts_with_triage", + "triage_results", + "unique_alerts", + "enriched_alerts", + ): + value = output.get(key) + if isinstance(value, dict): + value = value.get("preview") + if isinstance(value, list): + for item in value: + name = _alert_name_from_record(item) + if name: + return name + name = _first_text( + output.get("top_report_title"), + output.get("report_title"), + output.get("title"), + ) + if name: + return name + if workflow_id in TRIAGE_WORKFLOW_IDS: + input_date = _first_text(inputs.get("input_date")) + return f"研判批次 {input_date}" if input_date else "研判批次" + if workflow_id == "stream_alert_denoise": + return "降噪批次" + return "" + + +def _workflow_progress(status, current_step_index, completed_steps, total_steps): + normalized = str(status or "").lower() + current = max(_safe_int(current_step_index), _safe_int(completed_steps), 0) + total = max(_safe_int(total_steps), current, 1) + if normalized == "disabled": + return 0, "已关闭" + if normalized == "stale": + return 0, "已停止" + if normalized in WORKFLOW_SUCCESS_STATUSES: + return 1, "已完成" + if normalized in {"error", "failed", "timeout"}: + percent = _ratio(current or total, total) + return percent, f"失败于 {current or total}/{total} 步" + if normalized == "cancelled": + percent = _ratio(current or total, total) + return percent, f"已取消 {current or total}/{total} 步" + if normalized in WORKFLOW_RUNNING_STATUSES: + visible_current = current if current > 0 else 1 + return max(_ratio(visible_current, total), 0.03), f"第 {visible_current}/{total} 步" + return 0, "待执行" + + +def _workflow_link_context(latest): + payload = _safe_json_object(latest["payload"] if latest and "payload" in latest.keys() else "") + input_params = _safe_json_object(latest["input_params"] if latest and "input_params" in latest.keys() else "") + session_id = _first_text( + payload.get("sessionId"), + payload.get("sessionID"), + payload.get("session_id"), + input_params.get("sessionId"), + input_params.get("sessionID"), + input_params.get("session_id"), + ) + message_id = _first_text( + payload.get("messageId"), + payload.get("messageID"), + payload.get("message_id"), + input_params.get("messageId"), + input_params.get("messageID"), + input_params.get("message_id"), + ) + return session_id, message_id + + +def task_center_workflows(limit=12, include_mock=False): + if not _paths.workflow_db().is_file(): + return [], 0, 0, 0 + try: + with sqlite3.connect(f"file:{_paths.workflow_db()}?mode=ro", uri=True, timeout=1.0) as conn: + conn.row_factory = sqlite3.Row + conn.execute("PRAGMA query_only = ON") + if not ( + _table_exists(conn, "workflow_stats") + or _table_exists(conn, "workflow_executions") + ): + return [], 0, 0, 0 + today_start, tomorrow_start = _today_bounds() + today_start_ms = int(today_start.timestamp() * 1000) + tomorrow_start_ms = int(tomorrow_start.timestamp() * 1000) + workflow_ids = set() + if _table_exists(conn, "workflow_stats"): + workflow_ids.update( + row[0] + for row in conn.execute("SELECT workflow_id FROM workflow_stats").fetchall() + if row[0] + ) + if _table_exists(conn, "workflow_executions"): + workflow_ids.update( + row[0] + for row in conn.execute( + "SELECT DISTINCT workflow_id FROM workflow_executions" + ).fetchall() + if row[0] + ) + names = { + **_workflow_manifest_name_map(), + **_workflow_config_name_map(conn), + **WORKFLOW_DISPLAY_NAMES, + } + if include_mock: + workflow_ids.update(SOC_PINNED_WORKFLOW_NAMES) + stats_columns = ( + { + row[1] + for row in conn.execute("PRAGMA table_info(workflow_stats)").fetchall() + } + if _table_exists(conn, "workflow_stats") + else set() + ) + stats_success_expr = "success_count" if "success_count" in stats_columns else "0" + stats_error_expr = "error_count" if "error_count" in stats_columns else "0" + stats_updated_expr = "updated_at" if "updated_at" in stats_columns else "0" + execution_columns = ( + { + row[1] + for row in conn.execute("PRAGMA table_info(workflow_executions)").fetchall() + } + if _table_exists(conn, "workflow_executions") + else set() + ) + finished_at_expr = "finished_at" if "finished_at" in execution_columns else "NULL" + updated_at_expr = "updated_at" if "updated_at" in execution_columns else "NULL" + execution_time_expr = f"COALESCE({finished_at_expr}, {updated_at_expr}, started_at, 0)" + execution_start_expr = "started_at" + active_time_expr = f"COALESCE({updated_at_expr}, started_at, 0)" + latest_select = ", ".join( + [ + "id", + "status", + "started_at", + _workflow_execution_column_expr(execution_columns, "finished_at", "NULL"), + _workflow_execution_column_expr(execution_columns, "updated_at", "0"), + _workflow_execution_column_expr(execution_columns, "current_phase", "''"), + _workflow_execution_column_expr(execution_columns, "current_step_index", "0"), + _workflow_execution_column_expr(execution_columns, "step_count", "0"), + _workflow_execution_column_expr(execution_columns, "input_params", "'{}'"), + _workflow_execution_column_expr(execution_columns, "output_results", "'{}'"), + _workflow_execution_column_expr(execution_columns, "payload", "'{}'"), + _workflow_execution_column_expr(execution_columns, "error_message", "''"), + ] + ) + workflows = [] + total_execution_count = 0 + total_today_execution_count = 0 + total_active_count = 0 + now_ms = int(time.time() * 1000) + for workflow_id in workflow_ids: + workflow_name = names.get(workflow_id, workflow_id) + hidden_workflow = UUID_RE.match(str(workflow_id)) and workflow_name == workflow_id + trigger_state = _workflow_trigger_state(conn, workflow_id) + stats = None + if _table_exists(conn, "workflow_stats"): + stats = conn.execute( + f"SELECT call_count, {stats_success_expr}, {stats_error_expr}, {stats_updated_expr} " + "FROM workflow_stats WHERE workflow_id = ?", + (workflow_id,), + ).fetchone() + latest = None + exec_summary = None + if _table_exists(conn, "workflow_executions"): + exec_summary = conn.execute( + "SELECT COUNT(*) AS execution_count, " + "SUM(CASE WHEN status IN ('success', 'completed') THEN 1 ELSE 0 END) AS success_count, " + f"SUM(CASE WHEN {execution_start_expr} >= ? " + f"AND {execution_start_expr} < ? THEN 1 ELSE 0 END) " + "AS today_execution_count " + "FROM workflow_executions WHERE workflow_id = ?", + (today_start_ms, tomorrow_start_ms, workflow_id), + ).fetchone() + latest = conn.execute( + f"SELECT {latest_select} " + "FROM workflow_executions WHERE workflow_id = ? " + f"ORDER BY {execution_time_expr} DESC LIMIT 1", + (workflow_id,), + ).fetchone() + active_count = 0 + if _table_exists(conn, "workflow_executions"): + if trigger_state["hasConfig"] and trigger_state["enabled"]: + active_since_ms = now_ms - trigger_state["timeoutSeconds"] * 1000 + active_summary = conn.execute( + "SELECT COUNT(*) AS active_count " + "FROM workflow_executions WHERE workflow_id = ? " + "AND status IN ('running', 'queued', 'pending') " + f"AND {active_time_expr} >= ?", + (workflow_id, active_since_ms), + ).fetchone() + elif not trigger_state["hasConfig"] and "updated_at" in execution_columns: + active_since_ms = now_ms - WORKFLOW_DEFAULT_ACTIVE_TIMEOUT_SECONDS * 1000 + active_summary = conn.execute( + "SELECT COUNT(*) AS active_count " + "FROM workflow_executions WHERE workflow_id = ? " + "AND status IN ('running', 'queued', 'pending') " + f"AND {active_time_expr} >= ?", + (workflow_id, active_since_ms), + ).fetchone() + elif not trigger_state["hasConfig"]: + active_summary = conn.execute( + "SELECT COUNT(*) AS active_count " + "FROM workflow_executions WHERE workflow_id = ? " + "AND status IN ('running', 'queued', 'pending')", + (workflow_id,), + ).fetchone() + else: + active_summary = None + active_count = max( + _safe_int(active_summary["active_count"] if active_summary else 0), + 0, + ) + exec_execution_count = max( + _safe_int(exec_summary["execution_count"] if exec_summary else 0), + 0, + ) + exec_today_execution_count = max( + _safe_int(exec_summary["today_execution_count"] if exec_summary else 0), + 0, + ) + if stats is not None: + execution_count = max(_safe_int(stats["call_count"]), 0) + stats_today_count = _workflow_stats_call_delta_from_samples( + conn, + workflow_id, + today_start_ms, + tomorrow_start_ms, + ) + today_execution_count = ( + max(_safe_int(stats_today_count), 0) + if stats_today_count is not None + else exec_today_execution_count + ) + success_count = max(_safe_int(stats["success_count"]), 0) + else: + execution_count = exec_execution_count + today_execution_count = exec_today_execution_count + success_count = max( + _safe_int(exec_summary["success_count"] if exec_summary else 0), + 0, + ) + total_execution_count += execution_count + total_today_execution_count += today_execution_count + total_active_count += active_count + if hidden_workflow: + continue + last_run_at = 0 + if latest: + last_run_at = ( + _safe_int(latest["finished_at"]) + or _safe_int(latest["updated_at"]) + or _safe_int(latest["started_at"]) + ) + workflow_total_steps = _workflow_node_count(workflow_id) + latest_alert_name = "" + progress_percent = 0 + progress_label = "待执行" + current_phase = "" + session_id = "" + message_id = "" + effective_status = _workflow_effective_status(latest, active_count, trigger_state) + if latest: + workflow_total_steps = max(workflow_total_steps, _safe_int(latest["step_count"])) + latest_alert_name = _workflow_latest_alert_name( + workflow_id, + latest["output_results"], + latest["input_params"], + ) + progress_percent, progress_label = _workflow_progress( + effective_status, + latest["current_step_index"], + latest["step_count"], + workflow_total_steps, + ) + current_phase = str(latest["current_phase"] or "") + session_id, message_id = _workflow_link_context(latest) + workflows.append( + { + "id": workflow_id, + "name": workflow_name, + "executionCount": execution_count, + "todayExecutionCount": today_execution_count, + "successCount": success_count, + "successRate": _ratio(success_count, execution_count), + "activeCount": active_count, + "lastStatus": effective_status, + "lastRunAt": last_run_at, + "latestExecutionHash": str(latest["id"] if latest else ""), + "latestAlertName": latest_alert_name, + "progressPercent": progress_percent, + "progressLabel": progress_label, + "currentPhase": current_phase, + "sessionId": session_id, + "messageId": message_id, + } + ) + soc_order = { + "stream_alert_denoise": 3, + "stream_alert_triage": 2, + "onesec_kafka_investigation": 1, + "tdp_alert_triage": 1, + "sec_alert_unified_ops": 1, + } + workflows.sort( + key=lambda item: ( + item["activeCount"] > 0, + item["lastRunAt"], + item["executionCount"], + soc_order.get(item["id"], 0), + ), + reverse=True, + ) + return ( + workflows[:limit], + total_execution_count, + total_today_execution_count, + total_active_count, + ) + except Exception: + return [], 0, 0, 0 + + +def activity(params): + ensure_schema() + _maybe_prune_activity() + settings = _settings() + db_path = settings["db_path"] + time_window = _normalize_time_window( + params.get("startTime"), + params.get("endTime"), + ) + start_time, end_time = time_window or (0, 0) + workflow_stats = workflow_progress( + "stream_alert_denoise", + start_time, + end_time, + ) + workflow_snapshot = {"complete": True, "available": True} + workflow_events = [ + *workflow_recent_events("stream_alert_denoise", start_time, end_time, snapshot=workflow_snapshot), + *workflow_recent_events("stream_alert_triage", start_time, end_time, snapshot=workflow_snapshot), + ] + raw_cursor = str(params.get("cursor") or "").strip() + bootstrap = str(params.get("bootstrap") or "").strip().lower() == "latest" + limit = max(1, min(_safe_int(params.get("limit") or ACTIVITY_DEFAULT_LIMIT), ACTIVITY_MAX_LIMIT)) + + if not db_path.is_file(): + return _activity_response( + [], + 0, + "", + cursor_reset=bool(raw_cursor), + workflow_stats=workflow_stats, + workflow_events=workflow_events, + workflow_snapshot=workflow_snapshot, + ) + + cursor = _decode_activity_cursor(raw_cursor) if raw_cursor else None + cursor_reset = bool(raw_cursor and cursor is None) + + try: + with sqlite3.connect(db_path) as conn: + conn.row_factory = sqlite3.Row + conn.execute("PRAGMA query_only = ON") + if not ( + _table_exists(conn, DEFAULT_SQLITE_TABLE) + and _table_exists(conn, ACTIVITY_TABLE) + ): + return _activity_response( + [], + 0, + 0, + cursor_reset=cursor_reset, + workflow_stats=workflow_stats, + workflow_events=workflow_events, + workflow_snapshot=workflow_snapshot, + ) + latest_row_id, latest_activity_id = _activity_latest_cursor(conn, settings) + + if bootstrap or cursor is None: + recent_events = _activity_recent_events( + conn, + settings, + limit=10, + start_time=start_time, + end_time=end_time, + ) + return _activity_response( + [], + latest_row_id, + latest_activity_id, + cursor_reset=cursor_reset, + recent_events=recent_events, + workflow_stats=workflow_stats, + workflow_events=workflow_events, + workflow_snapshot=workflow_snapshot, + ) + + last_row_id = max(_safe_int(cursor.get("lastRowId")), 0) + last_activity_id = max(_safe_int(cursor.get("lastActivityId")), 0) + if last_row_id > latest_row_id or last_activity_id > latest_activity_id: + last_row_id = 0 + last_activity_id = 0 + cursor_reset = True + rows, overflow_count, batch = _activity_rows( + conn, + settings, + last_row_id=last_row_id, + last_activity_id=last_activity_id, + latest_row_id=latest_row_id, + latest_activity_id=latest_activity_id, + limit=limit, + ) + except Exception as exc: + return { + **_activity_response( + [], + 0, + "", + workflow_stats=workflow_stats, + workflow_events=workflow_events, + workflow_snapshot=workflow_snapshot, + ), + "error": f"activity query failed: {exc}", + } + + events = [] + seen = set() + for row in rows: + event = _activity_event(row) + if event is None or event["eventId"] in seen: + continue + seen.add(event["eventId"]) + events.append(event) + + return { + **_activity_response( + events, + latest_row_id, + latest_activity_id, + cursor_reset=cursor_reset, + batch=batch, + workflow_stats=workflow_stats, + workflow_events=workflow_events, + workflow_snapshot=workflow_snapshot, + ), + "overflowCount": overflow_count, + } + + +def _activity_response( + events, + last_row_id, + last_activity_id, + *, + cursor_reset=False, + recent_events=None, + batch=None, + workflow_stats=None, + workflow_events=None, + workflow_snapshot=None, +): + return { + "cursor": _encode_activity_cursor(last_row_id, last_activity_id), + "generatedAt": datetime.now().astimezone().isoformat(timespec="seconds"), + "events": events, + "recentEvents": recent_events or [], + "overflowCount": 0, + "batch": batch or _empty_activity_batch(), + "cursorReset": cursor_reset, + "workflowStats": workflow_stats or {"callCount": None, "latestStartedAt": None}, + "workflowEvents": workflow_events or [], + "workflowSnapshotComplete": bool(workflow_snapshot and workflow_snapshot["complete"]), + "workflowSnapshotAvailable": bool(workflow_snapshot and workflow_snapshot.get("available", True)), + "tokenUsage": token_usage(), + } + + +def _empty_activity_batch(): + return { + "mode": "normal", + "windowMs": ACTIVITY_WINDOW_MS, + "receivedCount": 0, + "duplicateCount": 0, + "uniqueCount": 0, + "clusterCount": 0, + "triageUpdatedCount": 0, + "sampledCount": 0, + "suppressedCount": 0, + "ratePerSecond": 0, + } + + +def _encode_activity_cursor(last_row_id, last_activity_id): + payload = json.dumps( + { + "lastRowId": max(_safe_int(last_row_id), 0), + "lastActivityId": max(_safe_int(last_activity_id), 0), + }, + separators=(",", ":"), + ).encode("utf-8") + return base64.urlsafe_b64encode(payload).decode("ascii").rstrip("=") + + +def _decode_activity_cursor(value): + try: + padding = "=" * (-len(value) % 4) + payload = json.loads(base64.urlsafe_b64decode((value + padding).encode("ascii"))) + except Exception: + return None + if not isinstance(payload, dict) or "lastRowId" not in payload: + return None + return payload + + +def _activity_latest_cursor(conn, settings): + latest_row_id = _safe_int( + conn.execute(f"SELECT COALESCE(MAX(rowid), 0) FROM {settings['table']}").fetchone()[0] + ) + latest_activity_id = _safe_int( + conn.execute( + f"SELECT COALESCE(MAX(activity_id), 0) FROM {settings['activity_table']}" + ).fetchone()[0] + ) + return latest_row_id, latest_activity_id + + +def _activity_rows( + conn, + settings, + *, + last_row_id, + last_activity_id, + latest_row_id, + latest_activity_id, + limit, +): + summary = _activity_insert_summary(conn, settings, last_row_id, latest_row_id) + new_count = summary["receivedCount"] + updated_count = _safe_int( + conn.execute( + f"SELECT COUNT(*) FROM {settings['activity_table']} " + f"WHERE alert_row_id <= ? AND activity_id > ? AND activity_id <= ?", + (last_row_id, last_activity_id, latest_activity_id), + ).fetchone()[0] + ) + + triage_reserve = min(updated_count, 3) + inserted = _activity_insert_samples( + conn, + settings, + last_row_id=last_row_id, + latest_row_id=latest_row_id, + received_count=new_count, + limit=max(limit - triage_reserve, 1), + ) + remaining = max(limit - len(inserted), 0) + updated = [] + if remaining and updated_count: + updated = conn.execute( + f"SELECT alert_row_id AS activity_row_id, activity_id AS activity_log_id, " + f"event_time AS activity_event_time, record_json, 1 AS sample_count " + f"FROM {settings['activity_table']} " + f"WHERE alert_row_id <= ? AND activity_id > ? AND activity_id <= ? " + f"ORDER BY activity_id DESC LIMIT ?", + (last_row_id, last_activity_id, latest_activity_id, remaining), + ).fetchall() + + rows = list(reversed(inserted)) + list(reversed(updated)) + sampled_count = len(inserted) + batch = { + **summary, + "mode": ( + "surge" + if new_count > ACTIVITY_SURGE_LIMIT + else "burst" if new_count > ACTIVITY_NORMAL_LIMIT else "normal" + ), + "windowMs": ACTIVITY_WINDOW_MS, + "triageUpdatedCount": updated_count, + "sampledCount": sampled_count, + "suppressedCount": max(new_count - sampled_count, 0), + "ratePerSecond": round(new_count / (ACTIVITY_WINDOW_MS / 1000), 1), + } + return rows, max(new_count + updated_count - len(rows), 0), batch + + +def _activity_table_columns(conn, settings): + return { + str(row[1]) + for row in conn.execute(f"PRAGMA table_info({settings['table']})").fetchall() + } + + +def _activity_insert_summary(conn, settings, last_row_id, latest_row_id): + columns = _activity_table_columns(conn, settings) + table = settings["table"] + if {"is_duplicate", "threat_name", "source_type"}.issubset(columns): + row = conn.execute( + f"SELECT COUNT(*) AS received_count, " + f"COALESCE(SUM(CASE WHEN \"is_duplicate\" = 1 THEN 1 ELSE 0 END), 0) AS duplicate_count, " + f"COUNT(DISTINCT COALESCE(NULLIF(\"source_type\", ''), 'unknown') || '|' || " + f"COALESCE(NULLIF(\"threat_name\", ''), 'unknown') || '|' || CAST(\"is_duplicate\" AS TEXT)) " + f"AS cluster_count FROM {table} WHERE rowid > ? AND rowid <= ?", + (last_row_id, latest_row_id), + ).fetchone() + received_count = _safe_int(row[0]) + duplicate_count = _safe_int(row[1]) + cluster_count = _safe_int(row[2]) + else: + received_count = _safe_int( + conn.execute( + f"SELECT COUNT(*) FROM {table} WHERE rowid > ? AND rowid <= ?", + (last_row_id, latest_row_id), + ).fetchone()[0] + ) + duplicate_count = 0 + cluster_count = received_count + return { + "receivedCount": received_count, + "duplicateCount": duplicate_count, + "uniqueCount": max(received_count - duplicate_count, 0), + "clusterCount": cluster_count, + } + + +def _activity_insert_samples(conn, settings, *, last_row_id, latest_row_id, received_count, limit): + if received_count <= 0: + return [] + table = settings["table"] + record_column = settings["record_column"] + if received_count <= limit: + return conn.execute( + f"SELECT rowid AS activity_row_id, {settings['event_time_column']} AS activity_event_time, " + f"{record_column} AS record_json, 1 AS sample_count " + f"FROM {table} WHERE rowid > ? AND rowid <= ? ORDER BY rowid DESC", + (last_row_id, latest_row_id), + ).fetchall() + + columns = _activity_table_columns(conn, settings) + if {"is_duplicate", "threat_name", "source_type"}.issubset(columns): + return conn.execute( + f"SELECT MAX(rowid) AS activity_row_id, MAX({settings['event_time_column']}) AS activity_event_time, " + f"{record_column} AS record_json, COUNT(*) AS sample_count " + f"FROM {table} WHERE rowid > ? AND rowid <= ? " + f"GROUP BY COALESCE(NULLIF(\"source_type\", ''), 'unknown'), " + f"COALESCE(NULLIF(\"threat_name\", ''), 'unknown'), \"is_duplicate\" " + f"ORDER BY sample_count DESC, activity_row_id DESC LIMIT ?", + (last_row_id, latest_row_id, limit), + ).fetchall() + return conn.execute( + f"SELECT rowid AS activity_row_id, {settings['event_time_column']} AS activity_event_time, " + f"{record_column} AS record_json, 1 AS sample_count " + f"FROM {table} WHERE rowid > ? AND rowid <= ? ORDER BY rowid DESC LIMIT ?", + (last_row_id, latest_row_id, limit), + ).fetchall() + + +def _activity_recent_events(conn, settings, *, limit, start_time=0, end_time=0): + raw_time_condition = "" + activity_time_condition = "" + time_params = [] + if start_time > 0 and end_time > 0: + start_date = datetime.fromtimestamp(start_time).strftime("%Y-%m-%d") + end_date = datetime.fromtimestamp(end_time).strftime("%Y-%m-%d") + raw_time_condition = ( + f"source.{settings['date_column']} BETWEEN ? AND ? " + f"AND source.{settings['event_time_column']} BETWEEN ? AND ?" + ) + activity_time_condition = ( + "asset_date BETWEEN ? AND ? AND event_time BETWEEN ? AND ?" + ) + time_params = [start_date, end_date, start_time, end_time] + recent_where = f" WHERE {raw_time_condition}" if raw_time_condition else "" + recent_rows = conn.execute( + f"SELECT source.rowid AS activity_row_id, " + f"source.{settings['event_time_column']} AS activity_event_time, " + f"source.{settings['record_column']} AS record_json, " + f"1 AS sample_count FROM {settings['table']} AS source{recent_where} " + f"ORDER BY source.{settings['event_time_column']} DESC, source.rowid DESC LIMIT ?", + (*time_params, limit), + ).fetchall() + triage_where = f" WHERE {activity_time_condition}" if activity_time_condition else "" + triage_rows = conn.execute( + f"SELECT alert_row_id AS activity_row_id, activity_id AS activity_log_id, " + f"event_time AS activity_event_time, record_json, 1 AS sample_count " + f"FROM {settings['activity_table']}{triage_where} " + f"ORDER BY event_time DESC, activity_id DESC LIMIT ?", + (*time_params, limit), + ).fetchall() + events = [] + seen = set() + for row in [*recent_rows, *triage_rows]: + event = _activity_event(row) + if event is None or event["eventId"] in seen: + continue + seen.add(event["eventId"]) + events.append(event) + return events + + +def _activity_event(row): + try: + record = json.loads(row["record_json"]) + except Exception: + return None + if not isinstance(record, dict): + return None + + row_id = str(row["activity_row_id"]) + triage_status = str(record.get("triage_status") or "").strip().lower() + triage_at = str(record.get("_triage_persisted_at") or "") + is_triage = bool(triage_status or triage_at or record.get("triage_report")) + stage = "triage" if is_triage else "denoise" + version = triage_at or row_id + event_time = _activity_event_time(record) + if not event_time and "activity_event_time" in row.keys(): + parsed_event_time = _parse_event_time(row["activity_event_time"]) + event_time = parsed_event_time.astimezone().isoformat(timespec="seconds") if parsed_event_time else "" + event = { + "eventId": f"{row_id}:{stage}:{version}", + "stage": stage, + "status": "failed" if triage_status in {"failed", "error"} else "completed", + "occurredAt": event_time, + "sampleCount": max(_safe_int(row["sample_count"]), 1) if "sample_count" in row.keys() else 1, + "alert": { + "id": _first_activity_text(record, "id", "record_id", "uuid", "event_id", "dedup_key"), + "sourceType": _first_activity_text(record, "_source_type", "source_type", "device_type"), + "threatName": _first_activity_text(record, "threat_name") or "未知告警", + "srcIp": _first_activity_text(record, "sip", "src_ip", "source_ip"), + "dstIp": _first_activity_text(record, "dip", "dst_ip", "destination_ip"), + "requestUri": _first_activity_text(record, "req_http_url", "uri", "url"), + "threatPhase": _first_activity_text(record, "threat_phase"), + "threatType": _first_activity_text(record, "_threat_type", "threat_type"), + }, + } + if stage == "denoise": + event["result"] = { + "isDuplicate": record.get("is_duplicate") is True, + "clusterId": _first_activity_text(record, "_lsh_cluster_id"), + "dedupKey": _first_activity_text(record, "dedup_key"), + } + else: + verdict = _triage_attack_verdict_value(record) + attack_success = _triage_attack_success_value(record) + outcome = _triage_outcome_key(record) + event["result"] = { + "triageStatus": triage_status or "completed", + "triageSource": str(record.get("triage_source") or "").strip().lower() or "triaged", + "durationMs": _safe_int(record.get("triage_ms")), + "verdict": verdict, + "attackSuccess": attack_success, + "verdictLabel": RESULT_LABELS.get(outcome, "待确认"), + "threatSeverity": _first_activity_text(record, "threat_severity"), + "riskLevel": _first_activity_text(record, "risk_level"), + "reportTitle": _first_activity_text(record, "report_title"), + "hasReport": bool(record.get("triage_report")), + } + return event + + +def _activity_event_time(record): + for key in ("time", "event_time", "timestamp", "timestamp_real", "occur_time", "created_at"): + value = _parse_event_time(record.get(key)) + if value is not None: + return value.astimezone().isoformat(timespec="seconds") + return "" + + +def _first_activity_text(record, *keys): + for key in keys: + value = record.get(key) + if value not in (None, "", "none", "None"): + return str(value) + return "" + + +def _file_revision(path): + try: + stat = path.stat() + return stat.st_size, stat.st_mtime_ns + except Exception: + return 0, 0 + + +def _normalize_time_window(start_value, end_value): + start_time = _safe_int(start_value) + end_time = _safe_int(end_value) + if start_time <= 0 or end_time <= 0: + return None + if start_time > end_time: + start_time, end_time = end_time, start_time + return start_time, end_time + + +def _settings(): + return { + "db_path": _paths.soc_db(), + "table": f'"{DEFAULT_SQLITE_TABLE}"', + "facts_table": f'"{FACTS_TABLE}"', + "activity_table": f'"{ACTIVITY_TABLE}"', + "record_column": f'"{DEFAULT_SQLITE_RECORD_COLUMN}"', + "date_column": f'"{DEFAULT_SQLITE_DATE_COLUMN}"', + "event_time_column": f'"{DEFAULT_SQLITE_EVENT_TIME_COLUMN}"', + } + + +def find_sources(start_date, end_date, start_time=0, end_time=0): + settings = _settings() + db_path = settings["db_path"] + if not db_path.is_file(): + return [] + + time_clause = "" + query_params = [start_date, end_date] + if start_time > 0 and end_time > 0: + time_clause = f" AND {settings['event_time_column']} BETWEEN ? AND ?" + query_params.extend((start_time, end_time)) + query = ( + f"SELECT {settings['date_column']} AS asset_date, COUNT(*) AS record_count " + f"FROM {settings['facts_table']} " + f"WHERE {settings['date_column']} BETWEEN ? AND ?{time_clause} " + f"GROUP BY {settings['date_column']} " + f"ORDER BY {settings['date_column']}" + ) + try: + with sqlite3.connect(db_path) as conn: + rows = conn.execute(query, query_params).fetchall() + except Exception: + return [] + + sources = [] + for asset_date, record_count in rows: + asset_date = str(asset_date or "") + if not DATE_RE.match(asset_date): + continue + sources.append( + RecordSource( + path=db_path, + role="denoise", + date=asset_date, + data_source="sqlite", + record_count=int(record_count or 0), + start_time=start_time, + end_time=end_time, + ) + ) + return sources + + +def available_dates(): + settings = _settings() + db_path = settings["db_path"] + if not db_path.is_file(): + return [] + query = ( + f"SELECT DISTINCT {settings['date_column']} AS asset_date " + f"FROM {settings['facts_table']} " + f"WHERE {settings['date_column']} IS NOT NULL " + f"ORDER BY {settings['date_column']}" + ) + try: + with sqlite3.connect(db_path) as conn: + rows = conn.execute(query).fetchall() + except Exception: + return [] + return [str(row[0]) for row in rows if DATE_RE.match(str(row[0]))] + + +def read_denoise(paths, workflow_call_count): + settings = _settings() + dates = sorted({path.date for path in paths}) + if not dates: + return None + placeholders = ",".join("?" for _ in dates) + date_column = settings["date_column"] + event_time_column = settings["event_time_column"] + table = settings["facts_table"] + where_clause = f"{date_column} IN ({placeholders})" + query_params = list(dates) + start_time = min((path.start_time for path in paths if path.start_time > 0), default=0) + end_time = max((path.end_time for path in paths if path.end_time > 0), default=0) + if start_time > 0 and end_time > 0: + where_clause += f" AND {event_time_column} BETWEEN ? AND ?" + query_params.extend((start_time, end_time)) + try: + with sqlite3.connect(settings["db_path"]) as conn: + rows = conn.execute( + f"SELECT {date_column}, COUNT(*), " + f"COALESCE(SUM(CASE WHEN \"is_duplicate\" = 1 THEN 1 ELSE 0 END), 0), " + f"MIN({event_time_column}), MAX({event_time_column}) " + f"FROM {table} WHERE {where_clause} " + f"GROUP BY {date_column} ORDER BY {date_column}", + query_params, + ).fetchall() + source_rows = conn.execute( + f"SELECT \"source_type\", COUNT(*) FROM {table} " + f"WHERE {where_clause} GROUP BY \"source_type\"", + query_params, + ).fetchall() + profile_counters, threat_type_counter = _sqlite_detail_counters( + conn, + settings, + where_clause, + query_params, + ) + timeline = _sqlite_timeline( + conn, + settings, + where_clause, + query_params, + dates, + start_time, + end_time, + ) + except Exception: + return None + + total_raw = sum(_safe_int(row[1]) for row in rows) + duplicates = sum(_safe_int(row[2]) for row in rows) + total_unique = max(total_raw - duplicates, 0) + event_values = [ + _parse_event_time(value) + for row in rows + for value in (row[3], row[4]) + if value not in (None, "") + ] + series_raw = [_safe_int(row[1]) for row in rows] + series_unique = [max(_safe_int(row[1]) - _safe_int(row[2]), 0) for row in rows] + return { + "totalRaw": total_raw, + "totalUnique": total_unique, + "duplicates": duplicates, + "duplicateRate": _ratio(duplicates, total_raw), + "uniqueRate": _ratio(total_unique, total_raw), + "headers": 0, + "files": len(paths), + "parseErrors": 0, + "eventStart": _format_event_time(min(event_values) if event_values else None), + "eventEnd": _format_event_time(max(event_values) if event_values else None), + "sourceCounter": Counter({_norm(key): _safe_int(value) for key, value in source_rows}), + "threatTypeCounter": threat_type_counter, + **profile_counters, + "seriesRaw": timeline["raw"], + "seriesUnique": timeline["unique"], + "_seriesTriage": timeline["triage"], + "_seriesAttack": timeline["attack"], + "_timelineLabels": timeline["labels"], + "_timelineWindow": timeline["window"], + "workflowCallCount": workflow_call_count, + } + + +def _timeline_spec(dates, start_time, end_time): + if start_time > 0 and end_time > 0: + bucket_start = start_time + bucket_end = end_time + else: + bucket_start = int(datetime.strptime(min(dates), "%Y-%m-%d").timestamp()) + bucket_end = int( + (datetime.strptime(max(dates), "%Y-%m-%d") + timedelta(days=1)).timestamp() + ) - 1 + span = max(bucket_end - bucket_start + 1, 1) + if span <= 30 * 60: + bucket_seconds, window = 60, "按分钟真实分布" + elif span <= 2 * 60 * 60: + bucket_seconds, window = 5 * 60, "按 5 分钟真实分布" + elif span <= 24 * 60 * 60: + bucket_seconds, window = 60 * 60, "按小时真实分布" + elif span <= 7 * 24 * 60 * 60: + bucket_seconds, window = 6 * 60 * 60, "按 6 小时真实分布" + else: + bucket_seconds, window = 24 * 60 * 60, "按天真实分布" + bucket_count = max(1, min(math.ceil(span / bucket_seconds), 60)) + labels = [] + for index in range(bucket_count): + point = datetime.fromtimestamp(bucket_start + index * bucket_seconds) + if bucket_seconds >= 24 * 60 * 60: + labels.append(point.strftime("%m-%d")) + elif bucket_seconds >= 60 * 60: + labels.append(point.strftime("%m-%d %H:%M")) + else: + labels.append(point.strftime("%H:%M")) + return bucket_start, bucket_seconds, bucket_count, labels, window + + +def _sqlite_timeline(conn, settings, where_clause, query_params, dates, start_time, end_time): + bucket_start, bucket_seconds, bucket_count, labels, window = _timeline_spec( + dates, + start_time, + end_time, + ) + rows = conn.execute( + f"SELECT CAST((event_time - ?) / ? AS INTEGER) AS bucket_index, " + f"COUNT(*) AS raw_count, " + f"COALESCE(SUM(CASE WHEN is_duplicate = 0 THEN 1 ELSE 0 END), 0) AS unique_count, " + f"COALESCE(SUM(has_triage), 0) AS triage_count, " + f"COALESCE(SUM(CASE WHEN has_triage = 1 " + f"AND LOWER(triage_status) NOT IN ('failed', 'error') " + f"AND LOWER(triage_attack_verdict) = 'attack' " + f"THEN 1 ELSE 0 END), 0) AS attack_count " + f"FROM {settings['facts_table']} WHERE {where_clause} AND event_time IS NOT NULL " + f"GROUP BY bucket_index ORDER BY bucket_index", + (bucket_start, bucket_seconds, *query_params), + ).fetchall() + raw = [0] * bucket_count + unique = [0] * bucket_count + triage = [0] * bucket_count + attack = [0] * bucket_count + for row in rows: + index = _safe_int(row[0]) + if 0 <= index < bucket_count: + raw[index] = _safe_int(row[1]) + unique[index] = _safe_int(row[2]) + triage[index] = _safe_int(row[3]) + attack[index] = _safe_int(row[4]) + return { + "raw": raw, + "unique": unique, + "triage": triage, + "attack": attack, + "labels": labels, + "window": window, + } + + +def _sqlite_detail_counters(conn, settings, where_clause, query_params): + table = settings["facts_table"] + cache_key = ( + str(settings["db_path"]), + table, + tuple(query_params), + _file_revision(Path(f"{settings['db_path']}-wal")), + ) + revision = conn.execute( + f"SELECT COALESCE(MAX(alert_row_id), 0), COALESCE(MAX(triage_persisted_at), '') " + f"FROM {table} WHERE {where_clause}", + query_params, + ).fetchone() + latest_row_id = _safe_int(revision[0]) + latest_triage_at = str(revision[1] or "") + with _cache_lock: + cached = _denoise_detail_cache.get(cache_key) or {} + if cached: + _denoise_detail_cache.move_to_end(cache_key) + if ( + cached + and latest_row_id == _safe_int(cached.get("lastRowId")) + and latest_triage_at == str(cached.get("lastTriagePersistedAt") or "") + and time.monotonic() - float(cached.get("updatedAt") or 0) < _DENOISE_DETAIL_CACHE_TTL + ): + return ( + {key: Counter(value) for key, value in cached["profileCounters"].items()}, + Counter(cached["threatTypeCounter"]), + ) + + rows = conn.execute( + f"SELECT phase, direction, result, protocol, severity, response_code, " + f"port, threat_type, COUNT(*) AS profile_count FROM {table} " + f"WHERE {where_clause} " + f"GROUP BY 1, 2, 3, 4, 5, 6, 7, 8", + query_params, + ).fetchall() + profile_counters = _new_profile_counters() + profile_keys = ( + "phaseCounter", + "directionCounter", + "resultCounter", + "protocolCounter", + "severityCounter", + "responseCounter", + ) + threat_type_counter = Counter() + for row in rows: + count = _safe_int(row[8]) + for index, key in enumerate(profile_keys): + profile_counters[key][_norm(row[index])] += count + port_value = row[6] + port = str(_safe_int(port_value)) if _safe_int(port_value) > 0 else _norm(port_value) + profile_counters["portCounter"][port] += count + threat_type_counter[_norm(row[7])] += count + with _cache_lock: + _denoise_detail_cache[cache_key] = { + "lastRowId": latest_row_id, + "lastTriagePersistedAt": latest_triage_at, + "updatedAt": time.monotonic(), + "profileCounters": {key: Counter(value) for key, value in profile_counters.items()}, + "threatTypeCounter": Counter(threat_type_counter), + } + _denoise_detail_cache.move_to_end(cache_key) + while len(_denoise_detail_cache) > _DENOISE_DETAIL_CACHE_MAX: + _denoise_detail_cache.popitem(last=False) + return profile_counters, threat_type_counter + + +def read_triage(paths): + settings = _settings() + dates = sorted({path.date for path in paths}) + if not dates: + return None + placeholders = ",".join("?" for _ in dates) + where_clause = f"asset_date IN ({placeholders})" + query_params = list(dates) + start_time = min((path.start_time for path in paths if path.start_time > 0), default=0) + end_time = max((path.end_time for path in paths if path.end_time > 0), default=0) + if start_time > 0 and end_time > 0: + where_clause += " AND event_time BETWEEN ? AND ?" + query_params.extend((start_time, end_time)) + triage_where = f"{where_clause} AND has_triage = 1" + cache_condition = "(LOWER(triage_source) = 'cache' OR LOWER(triage_status) = 'cached')" + follower_condition = ( + "(LOWER(triage_source) IN ('follower', 'followers', 'follower_reused') " + "OR LOWER(triage_status) = 'follower_reused')" + ) + failed_condition = "LOWER(triage_status) IN ('failed', 'error')" + new_triage_condition = ( + f"NOT {cache_condition} AND NOT {follower_condition} AND NOT ({failed_condition})" + ) + try: + with sqlite3.connect(settings["db_path"]) as conn: + row = conn.execute( + f"SELECT COUNT(*), " + f"COALESCE(SUM(CASE WHEN {cache_condition} THEN 1 ELSE 0 END), 0), " + f"COALESCE(SUM(CASE WHEN {follower_condition} THEN 1 ELSE 0 END), 0), " + f"COALESCE(SUM(CASE WHEN {failed_condition} " + f"THEN 1 ELSE 0 END), 0), " + f"COALESCE(SUM(CASE WHEN {new_triage_condition} " + f"THEN 1 ELSE 0 END), 0), " + f"COALESCE(SUM(CASE WHEN LOWER(triage_attack_verdict) = 'attack' " + f"AND LOWER(triage_attack_success) = 'success' THEN 1 ELSE 0 END), 0), " + f"COALESCE(SUM(CASE WHEN LOWER(triage_attack_verdict) = 'attack' " + f"AND LOWER(triage_attack_success) NOT IN ('success', 'failed') " + f"THEN 1 ELSE 0 END), 0), " + f"COALESCE(SUM(CASE WHEN LOWER(triage_attack_verdict) = 'attack' " + f"AND LOWER(triage_attack_success) = 'failed' " + f"THEN 1 ELSE 0 END), 0), " + f"COALESCE(SUM(CASE WHEN LOWER(triage_attack_verdict) = 'non_attack' " + f"THEN 1 ELSE 0 END), 0), " + f"COALESCE(SUM(CASE WHEN LOWER(triage_attack_verdict) " + f"NOT IN ('attack', 'non_attack') " + f"THEN 1 ELSE 0 END), 0), MIN(event_time), MAX(event_time), " + f"COALESCE(ROUND(AVG(CASE WHEN triage_ms > 0 THEN triage_ms END)), 0) " + f"FROM {settings['facts_table']} WHERE {triage_where}", + query_params, + ).fetchone() + source_rows = conn.execute( + f"SELECT source_type, COUNT(*) FROM {settings['facts_table']} " + f"WHERE {triage_where} GROUP BY source_type", + query_params, + ).fetchall() + threat_type_rows = conn.execute( + f"SELECT threat_type, COUNT(*) FROM {settings['facts_table']} " + f"WHERE {triage_where} GROUP BY threat_type", + query_params, + ).fetchall() + risk_rows = conn.execute( + f"SELECT risk_level, COUNT(*) FROM {settings['facts_table']} " + f"WHERE {triage_where} GROUP BY risk_level", + query_params, + ).fetchall() + status_rows = conn.execute( + f"SELECT COALESCE(NULLIF(triage_status, ''), triage_source), COUNT(*) " + f"FROM {settings['facts_table']} WHERE {triage_where} GROUP BY 1", + query_params, + ).fetchall() + profile_rows = conn.execute( + f"SELECT phase, direction, result, protocol, severity, response_code, port, COUNT(*) " + f"FROM {settings['facts_table']} WHERE {triage_where} " + f"GROUP BY 1, 2, 3, 4, 5, 6, 7", + query_params, + ).fetchall() + except Exception: + return None + + total_records = _safe_int(row[0]) + cache_hit = _safe_int(row[1]) + followers_reused = _safe_int(row[2]) + triage_failed = _safe_int(row[3]) + new_triaged = _safe_int(row[4]) + attack_success = _safe_int(row[5]) + attack = _safe_int(row[6]) + attack_failed = _safe_int(row[7]) + benign = _safe_int(row[8]) + unknown = _safe_int(row[9]) + attack_total = attack_success + attack + attack_failed + avg_triage_ms = _safe_int(row[12]) + profile_counters = _new_profile_counters() + profile_keys = ( + "phaseCounter", + "directionCounter", + "resultCounter", + "protocolCounter", + "severityCounter", + "responseCounter", + ) + for profile_row in profile_rows: + count = _safe_int(profile_row[7]) + for index, key in enumerate(profile_keys): + profile_counters[key][_norm(profile_row[index])] += count + port_value = profile_row[6] + port = str(_safe_int(port_value)) if _safe_int(port_value) > 0 else _norm(port_value) + profile_counters["portCounter"][port] += count + return { + "totalRecords": total_records, + "batchTotal": 0, + "newTriaged": new_triaged, + "cacheHit": cache_hit, + "triageFailed": triage_failed, + "followersReused": followers_reused, + "attackTotal": attack_total, + "attackSuccess": attack_success, + "attack": attack, + "attackFailed": attack_failed, + "benign": benign, + "unknown": unknown, + "attackRate": _ratio(attack_total, total_records), + "successRate": _ratio(attack_success, attack_total), + "cacheRate": _ratio(cache_hit + followers_reused, total_records), + "coverageRate": _ratio(total_records - triage_failed, total_records), + "avgTriageMs": avg_triage_ms, + "headers": 0, + "files": len(paths), + "parseErrors": 0, + "eventStart": _format_event_time(_parse_event_time(row[10])), + "eventEnd": _format_event_time(_parse_event_time(row[11])), + "sourceCounter": Counter({_norm(key): _safe_int(value) for key, value in source_rows}), + "threatTypeCounter": Counter( + {_norm(key): _safe_int(value) for key, value in threat_type_rows} + ), + "riskCounter": Counter({_norm(key): _safe_int(value) for key, value in risk_rows}), + "statusCounter": Counter({_norm(key): _safe_int(value) for key, value in status_rows}), + **profile_counters, + "seriesTotal": [], + "seriesAttack": [], + } + + +def _new_profile_counters(): + return { + "phaseCounter": Counter(), + "directionCounter": Counter(), + "resultCounter": Counter(), + "portCounter": Counter(), + "protocolCounter": Counter(), + "severityCounter": Counter(), + "responseCounter": Counter(), + } + + +def iter_records(source, *, triage_only=False): + settings = _settings() + time_filter = "" + query_params = [source.date] + if source.start_time > 0 and source.end_time > 0: + time_filter = f" AND {settings['event_time_column']} BETWEEN ? AND ?" + query_params.extend((source.start_time, source.end_time)) + triage_filter = "" + if triage_only: + triage_filter = ( + f" AND (NULLIF(json_extract({settings['record_column']}, '$.triage_status'), '') IS NOT NULL " + f"OR NULLIF(json_extract({settings['record_column']}, '$._triage_persisted_at'), '') IS NOT NULL " + f"OR json_extract({settings['record_column']}, '$.triage_report') IS NOT NULL)" + ) + query = ( + f"SELECT {settings['record_column']} AS record_json " + f"FROM {settings['table']} " + f"WHERE {settings['date_column']} = ?{time_filter}{triage_filter} " + f"ORDER BY {settings['event_time_column']}, rowid" + ) + try: + with sqlite3.connect(settings["db_path"]) as conn: + cursor = conn.execute(query, query_params) + for row in cursor: + try: + payload = json.loads(row[0]) + except Exception: + yield None + continue + if isinstance(payload, dict): + yield payload + elif isinstance(payload, list): + yield from _iter_json_payload(payload) + else: + yield None + except Exception: + return + + +def _iter_json_payload(payload): + if isinstance(payload, list): + for item in payload: + yield item if isinstance(item, dict) else None + return + + if not isinstance(payload, dict): + yield None + return + + records = None + for key in ("records", "data", "items", "rows"): + value = payload.get(key) + if isinstance(value, list): + records = value + break + + if records is None: + yield payload + return + + header = { + key: value + for key, value in payload.items() + if key not in {"records", "data", "items", "rows"} + } + if header: + yield {"_type": "file_header", **header} + for item in records: + yield item if isinstance(item, dict) else None + + +def _parse_event_time(value): + if value is None or value == "": + return None + if isinstance(value, datetime): + return value.replace(tzinfo=None) + try: + number = float(value) + if number > 1_000_000_000_000: + number = number / 1000 + if number > 10_000_000: + return datetime.fromtimestamp(number).replace(tzinfo=None) + except Exception: + pass + try: + text = str(value).strip().replace("Z", "+00:00") + return datetime.fromisoformat(text).replace(tzinfo=None) + except Exception: + return None + + +def _format_event_time(value): + if not value: + return "" + return value.isoformat(sep=" ", timespec="seconds") + + +def _safe_int(value): + try: + if value is None or value == "": + return 0 + return int(value) + except Exception: + return 0 + + +def _ratio(part, total): + part = _safe_int(part) + total = _safe_int(total) + if total <= 0: + return 0 + return round(part / total, 4) + + +def _norm(value): + if value is None: + return "unknown" + text = str(value).strip() + if not text: + return "unknown" + return text.lower() + + +def source_status(): + """Where the dashboard's figures come from and which of those stores are there.""" + alerts, workflow, tasks, usage = _paths.soc_db(), _paths.workflow_db(), _paths.task_db(), _paths.usage_db() + return { + "dataSource": DATA_SOURCE, + "mode": "sqlite-only", + "alertsDb": alerts, + "workflowDb": workflow, + "tasksDb": tasks, + "usageDb": usage, + "alertsAvailable": alerts.is_file(), + "workflowAvailable": workflow.is_file(), + "tasksAvailable": tasks.is_file(), + } diff --git a/flocks/workflow/soc_store/overview.py b/flocks/workflow/soc_store/overview.py new file mode 100644 index 000000000..d32d6f9be --- /dev/null +++ b/flocks/workflow/soc_store/overview.py @@ -0,0 +1,301 @@ +""" +What the SOC overview page reads, from SQLite. + +The page's handlers (``soc_ui/soc_overview/api/handlers.py``) hold no SQL: they +ask here for the alert records of a date range and for a workflow's call +counts, and work the overview out of them. + +The alert records come from ``soc.db``. ``access/soc_alerts.json`` beside the +suite's pages may name another file, table or columns under ``sqlite``; the +page hands that file's content to :func:`settings` as it read it. + +A database backend replaces ``flocks.workflow.soc_store`` as a whole (see +``flocks.db_backend``) and answers the same questions from its own tables. +""" + +from __future__ import annotations + +import json +import os +import re +import sqlite3 +import time +from dataclasses import dataclass +from datetime import datetime +from pathlib import Path +from typing import Any, Optional + +from . import _paths + +#: What the page shows as the kind of store behind its figures. +DATA_SOURCE = "sqlite" + +DATE_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$") +SQL_IDENTIFIER_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$") +DEFAULT_SQLITE_TABLE = "alert_records" +DEFAULT_SQLITE_RECORD_COLUMN = "record_json" +DEFAULT_SQLITE_DATE_COLUMN = "asset_date" +DEFAULT_SQLITE_EVENT_TIME_COLUMN = "event_time" + +_workflow_stats_cache: dict = {} +_cache_updated_at: float = 0 +_CACHE_TTL: float = 30.0 + + +@dataclass(frozen=True) +class RecordSource: + path: Path + role: str + date: str + data_source: str + record_count: int = 0 + start_time: int | None = None + end_time: int | None = None + + +def workflow_call_count(workflow_name: str, date: str = None) -> dict: + global _workflow_stats_cache, _cache_updated_at + now = time.time() + cache_key = f"{workflow_name}:{date or 'total'}" + + if now - _cache_updated_at < _CACHE_TTL and cache_key in _workflow_stats_cache: + return _workflow_stats_cache[cache_key] + + empty = {"callCount": 0, "dupCount": 0, "uniqueCount": 0} + workflow_db = _paths.workflow_db() + if not workflow_db.is_file(): + return empty + + try: + if date: + start = int(datetime.strptime(date, "%Y-%m-%d").timestamp() * 1000) + end = start + 86400 * 1000 + with sqlite3.connect(workflow_db) as conn: + rows = conn.execute( + """ + SELECT output_results + FROM workflow_executions + WHERE workflow_id = ? AND started_at >= ? AND started_at < ? + """, + (workflow_name, start, end), + ).fetchall() + dup_count = 0 + unique_count = 0 + for (output_text,) in rows: + try: + output = json.loads(output_text or "{}") + except Exception: + output = {} + stats = output.get("stats") if isinstance(output.get("stats"), dict) else {} + raw = _safe_int(stats.get("raw_count")) + if "after_dedup_count" in stats and stats.get("after_dedup_count") is not None: + unique_count += _safe_int(stats.get("after_dedup_count")) + else: + unique_count += raw + if output.get("is_duplicate") is True: + dup_count += 1 + result_dict = { + "callCount": len(rows), + "dupCount": dup_count, + "uniqueCount": unique_count, + } + else: + with sqlite3.connect(workflow_db) as conn: + row = conn.execute( + "SELECT call_count FROM workflow_stats WHERE workflow_id = ?", + (workflow_name,), + ).fetchone() + result_dict = {"callCount": _safe_int(row[0] if row else 0), "dupCount": 0, "uniqueCount": 0} + + _workflow_stats_cache[cache_key] = result_dict + _cache_updated_at = now + return result_dict + except Exception: + return _workflow_stats_cache.get(cache_key, empty) + + +def _read_config_string(*values): + for value in values: + if isinstance(value, str) and value.strip(): + return value.strip() + return "" + + +def _resolve_config_path(value, fallback, config_dir): + text = _read_config_string(value, str(fallback)) + path = Path(text).expanduser() + if path.is_absolute(): + return path + return (Path(config_dir) / path).resolve() if config_dir is not None else path.resolve() + + +def settings(config: Optional[dict[str, Any]] = None, config_dir: Optional[Path] = None) -> dict[str, Any]: + """Which file, table and columns hold the alert records. + + *config* is the content of ``access/soc_alerts.json`` (its ``sqlite`` part + is read here), *config_dir* the directory a relative path in it starts from. + """ + raw = config.get("sqlite") if isinstance(config, dict) else None + section = raw if isinstance(raw, dict) else {} + configured = _read_config_string(os.environ.get("FLOCKS_SOC_ALERTS_SQLITE_DB"), section.get("dbPath")) + return { + "db_path": _resolve_config_path(configured, _paths.soc_db(), config_dir) if configured else _paths.soc_db(), + "table": _sql_identifier(section.get("table"), DEFAULT_SQLITE_TABLE), + "record_column": _sql_identifier(section.get("recordColumn"), DEFAULT_SQLITE_RECORD_COLUMN), + "date_column": _sql_identifier(section.get("dateColumn"), DEFAULT_SQLITE_DATE_COLUMN), + "event_time_column": _sql_identifier( + section.get("eventTimeColumn"), + DEFAULT_SQLITE_EVENT_TIME_COLUMN, + ), + } + + +def _sql_identifier(value, fallback): + text = _read_config_string(value, fallback) + if not SQL_IDENTIFIER_RE.match(text): + text = fallback + return f'"{text}"' + + +def source_status(settings: dict[str, Any]) -> dict[str, Any]: + """Where the overview's figures come from and whether the alert store is there.""" + return { + "dataSource": DATA_SOURCE, + "path": settings["db_path"], + "exists": settings["db_path"].is_file(), + "workflowStatsDb": str(_paths.workflow_db()), + } + + +def find_sources(settings, start_date, end_date, start_time=None, end_time=None): + db_path = settings["db_path"] + if not db_path.is_file(): + return [] + + where = [f"{settings['date_column']} BETWEEN ? AND ?"] + params = [start_date, end_date] + if start_time is not None and end_time is not None: + where.append(f"{settings['event_time_column']} BETWEEN ? AND ?") + params.extend([start_time, end_time]) + + query = ( + f"SELECT {settings['date_column']} AS asset_date, COUNT(*) AS record_count " + f"FROM {settings['table']} " + f"WHERE {' AND '.join(where)} " + f"GROUP BY {settings['date_column']} " + f"ORDER BY {settings['date_column']}" + ) + try: + with sqlite3.connect(db_path) as conn: + rows = conn.execute(query, params).fetchall() + except Exception: + return [] + + sources = [] + for asset_date, record_count in rows: + asset_date = str(asset_date or "") + if not DATE_RE.match(asset_date): + continue + sources.append( + RecordSource( + path=db_path, + role="denoise", + date=asset_date, + data_source=DATA_SOURCE, + record_count=int(record_count or 0), + start_time=start_time, + end_time=end_time, + ) + ) + return sources + + +def available_dates(settings): + db_path = settings["db_path"] + if not db_path.is_file(): + return [] + query = ( + f"SELECT DISTINCT {settings['date_column']} AS asset_date " + f"FROM {settings['table']} " + f"WHERE {settings['date_column']} IS NOT NULL " + f"ORDER BY {settings['date_column']}" + ) + try: + with sqlite3.connect(db_path) as conn: + rows = conn.execute(query).fetchall() + except Exception: + return [] + return [str(row[0]) for row in rows if DATE_RE.match(str(row[0]))] + + +def iter_records(settings, source): + where = [f"{settings['date_column']} = ?"] + params = [source.date] + if source.start_time is not None and source.end_time is not None: + where.append(f"{settings['event_time_column']} BETWEEN ? AND ?") + params.extend([source.start_time, source.end_time]) + query = ( + f"SELECT {settings['record_column']} AS record_json " + f"FROM {settings['table']} " + f"WHERE {' AND '.join(where)} " + f"ORDER BY {settings['event_time_column']}, rowid" + ) + try: + with sqlite3.connect(settings["db_path"]) as conn: + rows = conn.execute(query, params).fetchall() + except Exception: + return + + for row in rows: + try: + payload = json.loads(row[0]) + except Exception: + yield None + continue + if isinstance(payload, dict): + yield payload + elif isinstance(payload, list): + yield from _iter_json_payload(payload) + else: + yield None + + +def _iter_json_payload(payload): + if isinstance(payload, list): + for item in payload: + yield item if isinstance(item, dict) else None + return + + if not isinstance(payload, dict): + yield None + return + + records = None + for key in ("records", "data", "items", "rows"): + value = payload.get(key) + if isinstance(value, list): + records = value + break + + if records is None: + yield payload + return + + header = { + key: value + for key, value in payload.items() + if key not in {"records", "data", "items", "rows"} + } + if header: + yield {"_type": "file_header", **header} + for item in records: + yield item if isinstance(item, dict) else None + + +def _safe_int(value): + try: + if value is None or value == "": + return 0 + return int(value) + except Exception: + return 0 diff --git a/flocks/workflow/soc_store/triage.py b/flocks/workflow/soc_store/triage.py new file mode 100644 index 000000000..ec81f88dc --- /dev/null +++ b/flocks/workflow/soc_store/triage.py @@ -0,0 +1,403 @@ +""" +Writing triaged alerts to the SOC alert store, on SQLite. + +The triage workflow hands its first-seen alerts to ``persist_triage_alerts`` +(through the ``soc`` service a workflow's python nodes get, see +``flocks.coordination.workflow_services``). One row is kept per ``dedup_key``: +a key seen again updates the triage fields of the row it already has and leaves +the original alert fields alone. + +``_ensure_soc_db_schema`` also brings a store written by an older suite up to +date: rows an older version stored as followers or duplicates of a key move to +``alert_records_superseded`` rather than being deleted. +""" + +from __future__ import annotations + +import datetime as _datetime +import json +import os +import re +import sqlite3 +import time + +from . import _paths + +def _ensure_soc_db_schema(conn): + conn.execute(""" + CREATE TABLE IF NOT EXISTS alert_records ( + row_id TEXT PRIMARY KEY, + record_id TEXT, + asset_date TEXT NOT NULL, + source_file TEXT NOT NULL, + line_number INTEGER NOT NULL, + event_time INTEGER, + source_type TEXT, + threat_name TEXT, + dedup_key TEXT, + is_duplicate INTEGER NOT NULL DEFAULT 0, + record_json TEXT NOT NULL + ) + """) + columns = {row[1] for row in conn.execute('PRAGMA table_info(alert_records)')} + dedup_key_added = 'dedup_key' not in columns + if dedup_key_added: + conn.execute('ALTER TABLE alert_records ADD COLUMN dedup_key TEXT') + + # One row per dedup_key (its first-seen, non-duplicate row), held by a + # partial unique index. An older non-unique index under that name stays; + # the unique one then takes the next free name. + unique_index_name = 'idx_alert_records_first_seen_dedup_key' + indexes = list(conn.execute('PRAGMA index_list(alert_records)')) + unique_index_ready = any( + str(row[1]).startswith(unique_index_name) and bool(row[2]) for row in indexes + ) + conn.execute('CREATE INDEX IF NOT EXISTS idx_alert_records_duplicate ON alert_records(is_duplicate)') + has_persisted_duplicates = conn.execute(""" + SELECT 1 FROM alert_records + WHERE is_duplicate = 1 + AND dedup_key IS NOT NULL + AND dedup_key <> '' + LIMIT 1 + """).fetchone() is not None + if not unique_index_ready or has_persisted_duplicates: + row_key = """NULLIF(TRIM(CASE + WHEN dedup_key IS NOT NULL AND TRIM(dedup_key) <> '' THEN dedup_key + WHEN json_valid(record_json) THEN CAST(json_extract(record_json, '$.dedup_key') AS TEXT) + END), '')""" + superseded = f""" + WITH keyed AS ( + SELECT rowid AS rid, COALESCE(is_duplicate, 0) AS dup, {row_key} AS dedup + FROM alert_records + ), + keepers AS ( + SELECT MIN(rid) AS rid FROM keyed WHERE dedup IS NOT NULL AND dup = 0 GROUP BY dedup + ), + superseded AS ( + SELECT rid FROM keyed WHERE dedup IS NOT NULL AND rid NOT IN (SELECT rid FROM keepers) + ) + """ + if conn.execute(f'{superseded} SELECT 1 FROM superseded LIMIT 1').fetchone() is not None: + # Followers and duplicates an older version stored under a key are + # moved to alert_records_superseded instead of being deleted. + import uuid + + conn.execute('CREATE TABLE IF NOT EXISTS alert_records_superseded AS SELECT * FROM alert_records WHERE 0') + kept = {row[1] for row in conn.execute('PRAGMA table_info(alert_records_superseded)')} + record_columns = [row[1] for row in conn.execute('PRAGMA table_info(alert_records)')] + for column, definition in [(column, '') for column in record_columns] + [ + ('source_rowid', ' INTEGER'), ('superseded_batch', ' TEXT'), ('superseded_at', ' TEXT'), + ]: + if column not in kept: + conn.execute(f'ALTER TABLE alert_records_superseded ADD COLUMN "{column}"{definition}') + column_list = ', '.join(f'"{column}"' for column in record_columns) + batch = uuid.uuid4().hex + conn.execute(f""" + {superseded} + INSERT INTO alert_records_superseded ({column_list}, source_rowid, superseded_batch, superseded_at) + SELECT {column_list}, rowid, ?, ? FROM alert_records + WHERE rowid IN (SELECT rid FROM superseded) + """, (batch, _datetime.datetime.now().isoformat())) + # Only the rows just copied, in the same transaction. + conn.execute(""" + DELETE FROM alert_records + WHERE rowid IN ( + SELECT source_rowid FROM alert_records_superseded WHERE superseded_batch = ? + ) + """, (batch,)) + # Every row still holding a key is its key's first-seen row, so the + # trimmed key (or the one in record_json) cannot collide. + conn.execute(f'UPDATE alert_records SET dedup_key = {row_key} WHERE dedup_key IS NOT {row_key}') + if not unique_index_ready: + taken = {row[1] for row in indexes} + index_name, suffix = unique_index_name, 1 + while index_name in taken: + suffix += 1 + index_name = f'{unique_index_name}_{suffix}' + conn.execute(f""" + CREATE UNIQUE INDEX {index_name} + ON alert_records(dedup_key) + WHERE dedup_key IS NOT NULL AND dedup_key <> '' + """) + + conn.execute('CREATE INDEX IF NOT EXISTS idx_alert_records_asset_date ON alert_records(asset_date)') + conn.execute('CREATE INDEX IF NOT EXISTS idx_alert_records_event_time ON alert_records(event_time)') + conn.execute('CREATE INDEX IF NOT EXISTS idx_alert_records_source_type ON alert_records(source_type)') + conn.execute('CREATE INDEX IF NOT EXISTS idx_alert_records_threat_name ON alert_records(threat_name)') + + +def _event_time_value(alert): + for key in ('time', 'event_time', 'timestamp', 'timestamp_real', 'occur_time', 'created_at'): + value = alert.get(key) + if value in (None, ''): + continue + if isinstance(value, (int, float)): + ts = float(value) + if ts > 100000000000: + ts = ts / 1000.0 + return int(ts) + text = str(value).strip() + if not text: + continue + try: + ts = float(text) + if ts > 100000000000: + ts = ts / 1000.0 + return int(ts) + except Exception: + pass + normalized = text.replace('Z', '+00:00') + try: + return int(_datetime.datetime.fromisoformat(normalized).timestamp()) + except Exception: + pass + for fmt in ('%Y-%m-%d %H:%M:%S', '%Y/%m/%d %H:%M:%S', '%Y-%m-%d %H:%M', '%Y/%m/%d %H:%M'): + try: + return int(_datetime.datetime.strptime(text, fmt).timestamp()) + except Exception: + continue + return int(time.time()) + + +def _asset_date_value(alert, event_time): + value = alert.get('asset_date') or alert.get('_asset_date') or alert.get('date') + if value: + text = str(value).strip() + if re.match(r'^\d{4}-\d{2}-\d{2}$', text): + return text + try: + return _datetime.datetime.fromtimestamp(int(event_time)).strftime('%Y-%m-%d') + except Exception: + return _datetime.datetime.now().strftime('%Y-%m-%d') + + +def _source_type_value(alert): + for key in ('source_type', '_source_type', 'data_source', 'log_type', 'vendor', 'device_type'): + value = alert.get(key) + if value not in (None, ''): + return str(value) + return '' + + +def _record_id_value(alert): + for key in ('record_id', 'id', 'uuid', 'event_id', 'dedup_key'): + value = alert.get(key) + if value not in (None, ''): + return str(value) + return '' + + +def _stable_row_id(alert, source_file, line_number, event_time): + existing = alert.get('row_id') or alert.get('_row_id') + if existing: + return str(existing) + import hashlib as _hashlib + basis = { + 'record_id': _record_id_value(alert), + 'dedup_key': alert.get('dedup_key', ''), + 'time': event_time, + 'source_file': source_file, + 'line_number': line_number, + 'sip': alert.get('sip', ''), + 'sport': alert.get('sport', ''), + 'dip': alert.get('dip', ''), + 'dport': alert.get('dport', ''), + 'threat_rule_id': alert.get('threat_rule_id') or alert.get('rule_id') or '', + } + raw = json.dumps(basis, sort_keys=True, ensure_ascii=False) + return _hashlib.sha256(raw.encode('utf-8')).hexdigest() + + +def _load_existing_soc_rows(conn, dedup_keys): + existing = {} + unique_keys = list(dict.fromkeys(str(key).strip() for key in dedup_keys if str(key).strip())) + for start in range(0, len(unique_keys), 500): + chunk = unique_keys[start:start + 500] + placeholders = ','.join('?' for _ in chunk) + rows = conn.execute(f""" + SELECT row_id, record_id, asset_date, source_file, line_number, + event_time, source_type, threat_name, dedup_key, + is_duplicate, record_json + FROM alert_records + WHERE dedup_key IN ({placeholders}) + """, chunk) + for row in rows: + try: + record = json.loads(row[10]) + except Exception: + record = {} + if not isinstance(record, dict): + record = {} + existing[row[8]] = { + 'row_id': row[0], + 'record_id': row[1], + 'asset_date': row[2], + 'source_file': row[3], + 'line_number': row[4], + 'event_time': row[5], + 'source_type': row[6], + 'threat_name': row[7], + 'record': record, + } + return existing + + +def _merge_triage_record(existing_record, incoming_record): + merged = dict(existing_record) if isinstance(existing_record, dict) else {} + triage_fields = ( + 'has_dedup_key', + 'triage_source', + 'triage_status', + 'triage_attack_verdict', + 'risk_level', + 'report_title', + 'triage_report', + 'triage_attack_success', + 'triage_ms', + 'triage_error', + '_triage_run_id', + '_triage_persisted_at', + ) + for key in triage_fields: + if key in incoming_record: + merged[key] = incoming_record[key] + elif key in {'triage_ms', 'triage_error'}: + merged.pop(key, None) + return merged + + +def _triage_write_soc_db(db_path, alerts, run_id, default_source_file=''): + db_path = str(db_path) + db_dir = os.path.dirname(db_path) + if db_dir: + os.makedirs(db_dir, exist_ok=True) + default_source_file = str(default_source_file or '') + + persisted_at = _datetime.datetime.now().isoformat() + candidates = [] + seen_dedup_keys = set() + for idx, alert in enumerate(alerts, 1): + if not isinstance(alert, dict): + continue + dedup_key = str(alert.get('dedup_key') or '').strip() + if not dedup_key or dedup_key in seen_dedup_keys: + continue + seen_dedup_keys.add(dedup_key) + record = dict(alert) + record['dedup_key'] = dedup_key + record['is_duplicate'] = False + record['_triage_run_id'] = run_id + record['_triage_persisted_at'] = persisted_at + source_file = str( + record.get('source_file') + or record.get('_source_file') + or record.get('file_path') + or default_source_file + or 'stream_alert_triage' + ) + try: + line_number = int(record.get('line_number') or record.get('_line_number') or idx) + except Exception: + line_number = idx + event_time = _event_time_value(record) + candidates.append({ + 'row_id': _stable_row_id(record, source_file, line_number, event_time), + 'record_id': _record_id_value(record), + 'asset_date': _asset_date_value(record, event_time), + 'source_file': source_file, + 'line_number': line_number, + 'event_time': event_time, + 'source_type': _source_type_value(record), + 'threat_name': str(record.get('threat_name') or record.get('rule_name') or ''), + 'dedup_key': dedup_key, + 'record': record, + }) + + insert_rows = [] + update_rows = [] + with sqlite3.connect(db_path, timeout=30) as conn: + conn.execute('BEGIN IMMEDIATE') + _ensure_soc_db_schema(conn) + existing_by_key = _load_existing_soc_rows( + conn, [candidate['dedup_key'] for candidate in candidates], + ) + for candidate in candidates: + existing = existing_by_key.get(candidate['dedup_key']) + if existing: + merged_record = _merge_triage_record(existing['record'], candidate['record']) + merged_record['dedup_key'] = candidate['dedup_key'] + merged_record['is_duplicate'] = False + update_rows.append(( + candidate['dedup_key'], + json.dumps(merged_record, ensure_ascii=False), + existing['row_id'], + )) + continue + insert_rows.append(( + candidate['row_id'], + candidate['record_id'], + candidate['asset_date'], + candidate['source_file'], + candidate['line_number'], + candidate['event_time'], + candidate['source_type'], + candidate['threat_name'], + candidate['dedup_key'], + 0, + json.dumps(candidate['record'], ensure_ascii=False), + )) + + if insert_rows: + conn.executemany(""" + INSERT INTO alert_records ( + row_id, record_id, asset_date, source_file, line_number, + event_time, source_type, threat_name, dedup_key, + is_duplicate, record_json + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + """, insert_rows) + if update_rows: + conn.executemany(""" + UPDATE alert_records + SET dedup_key = ?, is_duplicate = 0, record_json = ? + WHERE row_id = ? + """, update_rows) + conn.commit() + + persisted_rows = len(insert_rows) + len(update_rows) + return { + 'path': db_path, + 'table': 'alert_records', + 'rows': persisted_rows, + 'inserted_rows': len(insert_rows), + 'updated_rows': len(update_rows), + } + + +# ── LLM provider warm-up (avoid cold-start race in _parallel_4_branches) ────── +# +# Background: when this node starts, the LLM provider (e.g. threatbook-cn-llm) +# is lazy-initialized on the first call. Inside `_parallel_4_branches` we +# submit 4 LLM calls to a ThreadPoolExecutor simultaneously; whichever one +# wins the race may race against provider registration and fail with +# "provider 'xxx' not exists" while subsequent calls succeed. A single +# synchronous warm-up call before any concurrent fan-out forces the provider +# to finish registering on the main thread, eliminating the race entirely. +# +# Failure of the warm-up is non-fatal — we just log and continue. The first +# real LLM call will still see the same error and surface it normally. + + +def ensure_schema() -> None: + """Create the alert store, or bring an older one up to date.""" + db_path = _paths.soc_db() + db_path.parent.mkdir(parents=True, exist_ok=True) + with sqlite3.connect(db_path, timeout=30) as conn: + conn.execute('BEGIN IMMEDIATE') + _ensure_soc_db_schema(conn) + conn.commit() + + +def persist_triage_alerts(alerts, run_id, source_file=''): + """Store triaged alerts, one row per dedup_key; says where and how many rows it wrote.""" + result = _triage_write_soc_db(_paths.soc_db(), alerts, run_id, source_file) + return {'backend': 'sqlite', 'unchanged_rows': 0, **result} diff --git a/packaging/linux/versions.manifest.json b/packaging/linux/versions.manifest.json index d386a6389..879cc1ae6 100644 --- a/packaging/linux/versions.manifest.json +++ b/packaging/linux/versions.manifest.json @@ -9,8 +9,8 @@ "CXXABI": "1.3.11" }, "python": { - "version": "3.12.12", - "python_build_standalone_release": "20251202", + "version": "3.12.16", + "python_build_standalone_release": "20261026", "archive_template": "cpython-{version}+{release}-{triple}-unknown-linux-gnu-install_only_stripped.tar.gz", "base_url": "https://github.com/astral-sh/python-build-standalone/releases/download" }, diff --git a/pyproject.toml b/pyproject.toml index 58710462a..82ccd4398 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "flocks" -version = "v2026.11.09" +version = "v2026.11.18" description = "AI-Native SecOps platform with multi-agent collaboration" authors = [ {name = "Flocks Team", email = "team@example.com"} @@ -77,6 +77,10 @@ dependencies = [ "slack-sdk>=3.38.0", "python-socks>=2.8.1", "pytz>=2026.1.post1", + # Windows has no IANA time zone database of its own: zoneinfo reads it from tzdata there. Without it + # ZoneInfo("Asia/Shanghai") raises, so the alert operations suite cannot be installed (its query tool sets + # its time zone on import) and a scheduled task's time zone is refused as invalid. + "tzdata>=2025.2; sys_platform == 'win32'", # docs parser "pypdf>=6.8.0", "markitdown>=0.1.5", diff --git a/tests/agent/test_agent_factory.py b/tests/agent/test_agent_factory.py index e32309137..7817d08c5 100644 --- a/tests/agent/test_agent_factory.py +++ b/tests/agent/test_agent_factory.py @@ -824,6 +824,64 @@ def test_default_metadata_generated_for_agent_without_prompt_metadata(self): assert available[0].metadata.cost == "medium" +# =========================================================================== +# Runtime-registered agents as delegation candidates +# =========================================================================== + +class TestRegisteredDelegationCandidates: + + def test_registered_agents_join_the_candidates_like_the_registry_merge(self): + from flocks.agent.registry import _build_available_agents, _delegation_candidates + + loaded = { + "rex": AgentInfo(name="rex", mode="primary", native=True), + "explore": AgentInfo(name="explore", mode="subagent", delegatable=True, native=True), + } + registered = { + "ext-auditor": AgentInfo(name="ext-auditor", mode="subagent", delegatable=True), + "ext-hidden": AgentInfo(name="ext-hidden", mode="subagent", delegatable=True, hidden=True), + "ext-primary": AgentInfo(name="ext-primary", mode="primary"), + "managed-one": AgentInfo(name="managed-one", mode="subagent", delegatable=True), + } + + candidates = _delegation_candidates(loaded, registered, {"managed-one"}, None) + assert [agent.name for agent in _build_available_agents(candidates)] == ["explore", "ext-auditor"] + # Like the merge itself: nothing is added to the loaded agents here. + assert set(loaded) == {"rex", "explore"} + + allowed = _delegation_candidates(loaded, registered, set(), ["rex", "explore"]) + assert [agent.name for agent in _build_available_agents(allowed)] == ["explore"] + + @pytest.mark.asyncio + async def test_rex_prompt_offers_a_registered_delegatable_subagent(self): + from flocks.agent.agent import AgentPromptMetadata, DelegationTrigger + from flocks.agent.registry import Agent + + name = "ext-code-auditor" + Agent.register(name, AgentInfo( + name=name, + description="Audits source code for vulnerabilities. Also reviews fixes.", + mode="subagent", + delegatable=True, + prompt_metadata=AgentPromptMetadata( + category="security", + cost="medium", + triggers=[DelegationTrigger(domain="源码安全审计", trigger='"代码审计", "code audit"')], + ), + )) + try: + await Agent.refresh() + rex = await Agent.get("rex") + assert rex is not None + # The agent table and the security routing both name it. + assert f"| `{name}` | medium | Audits source code for vulnerabilities |" in rex.prompt + assert f"| 源码安全审计 | `{name}` |" in rex.prompt + finally: + Agent.unregister(name) + await Agent.refresh() + assert name not in (await Agent.get("rex")).prompt + + # =========================================================================== # Project-level plugin agent scanning # =========================================================================== diff --git a/tests/channel/test_channel_routes_hardening.py b/tests/channel/test_channel_routes_hardening.py index 3f6d0de84..56de0743c 100644 --- a/tests/channel/test_channel_routes_hardening.py +++ b/tests/channel/test_channel_routes_hardening.py @@ -66,7 +66,13 @@ def test_record_inbound_and_bind_reject_unknown_channel(client): assert r.status_code == 404 -@pytest.mark.parametrize("base_url", ["http://127.0.0.1:5173", "https://localhost", "https://10.0.0.1", "ftp://x"]) +@pytest.mark.parametrize( + "base_url", + [ + "http://example.com", "https://10.0.0.1", "https://192.168.1.1", "https://[fd00::1]", "ftp://x", "ftp://127.0.0.1", + "http://127.0.0.1%25.attacker.example", + ], +) def test_weixin_qr_rejects_non_public_base_url(client, base_url): r = client.post("/api/channel/weixin/qr-login/start", json={"baseUrl": base_url}) assert r.status_code == 422, r.text @@ -74,6 +80,33 @@ def test_weixin_qr_rejects_non_public_base_url(client, base_url): assert r.status_code == 422, r.text +@pytest.mark.parametrize( + "base_url", + ["http://127.0.0.1:5173", "https://localhost", "http://localhost:8080/", "http://[::1]:9000"], +) +def test_weixin_qr_accepts_loopback_base_url(client, monkeypatch, base_url): + """本机回环上的 iLink 地址(本地中转、联调桩)放行,http 也可以。""" + from flocks.channel.builtin.weixin import qr_login + + seen: list[str] = [] + + async def _start(*, base_url): + seen.append(base_url) + return {"qrcode_value": "v", "qrcode_url": "u"} + + async def _poll(*, qrcode_value, base_url): + seen.append(base_url) + return {"status": "waiting"} + + monkeypatch.setattr(qr_login, "start_qr_login", _start) + monkeypatch.setattr(qr_login, "poll_qr_status", _poll) + r = client.post("/api/channel/weixin/qr-login/start", json={"baseUrl": base_url}) + assert r.status_code == 200, r.text + r = client.get("/api/channel/weixin/qr-login/status", params={"qrcode": "abc", "baseUrl": base_url}) + assert r.status_code == 200, r.text + assert seen == [base_url.rstrip("/")] * 2 + + def test_whatsapp_paths_must_stay_inside_flocks_root(client, tmp_path, monkeypatch): monkeypatch.setenv("FLOCKS_ROOT", str(tmp_path / "root")) r = client.get("/api/channel/whatsapp/session-status", params={"sessionPath": "/etc"}) @@ -138,3 +171,40 @@ async def dispatch(self, request, call_next): client = TestClient(app, raise_server_exceptions=False) r = client.post("/api/channel/session-send", json={"session_id": "ses_other", "text": "x"}) assert r.status_code == 403, r.text + + +@pytest.mark.asyncio +@pytest.mark.parametrize("proxy", [None, "http://proxy.invalid:3128"]) +async def test_weixin_qr_login_reaches_a_loopback_ilink_directly(monkeypatch, proxy): + """本机回环上的 iLink 中转直连,环境里配了代理也不经代理。""" + import http.server + import threading + + from flocks.channel.builtin.weixin import qr_login + + for name in ("HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "http_proxy", "https_proxy", "all_proxy", "NO_PROXY", "no_proxy"): + monkeypatch.delenv(name, raising=False) + if proxy: + for name in ("HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY"): + monkeypatch.setenv(name, proxy) + body = json.dumps({"qrcode": "abc123", "qrcode_img_content": "https://liteapp.weixin.qq.com/q/x"}).encode() + + class _Handler(http.server.BaseHTTPRequestHandler): + def do_GET(self): + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *args): + pass + + server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), _Handler) + threading.Thread(target=server.serve_forever, daemon=True).start() + try: + result = await qr_login.start_qr_login(base_url=f"http://127.0.0.1:{server.server_address[1]}") + finally: + server.shutdown() + server.server_close() + assert result == {"qrcode_value": "abc123", "qrcode_url": "https://liteapp.weixin.qq.com/q/x"} diff --git a/tests/channel/test_wecom.py b/tests/channel/test_wecom.py index 62a20059f..5a7eb4187 100644 --- a/tests/channel/test_wecom.py +++ b/tests/channel/test_wecom.py @@ -516,6 +516,372 @@ async def _disconnect(self): assert ch._ws_client is None +# ------------------------------------------------------------------ +# connection status: what the channel page shows when WeCom fails +# ------------------------------------------------------------------ + +def _scripted_ws_client(script): + """A WSClient stand-in whose connect() replays SDK events: [(event, *args), ...].""" + + class FakeWSClient: + last_instance = None + + def __init__(self, *args, **kwargs): + self.handlers = {} + self.disconnect = AsyncMock() + FakeWSClient.last_instance = self + + def on(self, event, handler): + self.handlers[event] = handler + + async def connect(self): + for event, *args in script: + self.handlers[event](*args) + + return FakeWSClient + + +class TestWeComConnectionStatus: + AUTH_REFUSED = Exception("Authentication failed: invalid secret (code: 40058)") + REPLACED = "New connection established, server disconnected this connection" + + def test_connection_is_self_managed(self): + # Connected only once WeCom accepts the credentials, not when start() runs. + assert WeComChannel().capabilities().self_managed_connection is True + + async def test_refused_credentials_end_start_with_the_reason(self): + FakeWSClient = _scripted_ws_client([("error", self.AUTH_REFUSED)]) + ch = WeComChannel() + config = {"botId": "bot-1", "secret": "wrong-secret"} + + with patch("wecom_aibot_sdk.WSClient", FakeWSClient): + with pytest.raises(RuntimeError, match="鉴权失败") as raised: + await asyncio.wait_for(ch.start(config, AsyncMock(), asyncio.Event()), timeout=5) + + assert "Bot ID 和 Secret" in str(raised.value) + assert "企业微信错误码 40058" in str(raised.value) + # What the server said stays in the server log, not in the status. + assert "invalid secret" not in str(raised.value) + assert ch.status.connected is False + assert ch.status.last_error == str(raised.value) + assert ch.status.error_count == 1 + FakeWSClient.last_instance.disconnect.assert_awaited_once() + + async def test_connection_replaced_elsewhere_ends_start_with_the_reason(self): + FakeWSClient = _scripted_ws_client([("authenticated",), ("disconnected", self.REPLACED)]) + ch = WeComChannel() + config = {"botId": "bot-1", "secret": "secret-1"} + + with patch("wecom_aibot_sdk.WSClient", FakeWSClient): + with pytest.raises(RuntimeError, match="别处建立了新的长连接") as raised: + await asyncio.wait_for(ch.start(config, AsyncMock(), asyncio.Event()), timeout=5) + + assert "停掉其他正在使用这个机器人的服务" in str(raised.value) + assert ch.status.connected is False + assert ch.status.last_error == str(raised.value) + + async def test_reconnect_timeout_names_the_last_error(self): + FakeWSClient = _scripted_ws_client([ + ("error", ConnectionRefusedError(61, "Connect call failed ('127.0.0.1', 9)")), + ("reconnecting", 1), + ]) + ch = WeComChannel() + config = { + "botId": "bot-1", + "secret": "secret-1", + "websocketUrl": "ws://127.0.0.1:9", + "reconnectTimeoutSeconds": 0.01, + } + + with patch("wecom_aibot_sdk.WSClient", FakeWSClient): + with pytest.raises(RuntimeError, match="reconnect timed out") as raised: + await asyncio.wait_for(ch.start(config, AsyncMock(), asyncio.Event()), timeout=5) + + message = str(raised.value) + assert "最近一次错误" in message + assert "ws://127.0.0.1:9" in message + assert "错误类型 ConnectionRefusedError,errno 61" in message + assert "Connect call failed" not in message + assert "ConnectionRefusedError" in (ch.status.last_error or "") + + TOKEN_URL = "wss://bot:pa55word@gw.example.com:8443/ws/path-token-abc?token=SECRET123#frag" # secret-guard: allow (synthetic test credential) + URL_SECRETS = ("SECRET123", "path-token-abc", "pa55word", "#frag") + + async def test_status_keeps_credentials_in_the_address_out(self): + # The channel status is readable by every signed-in user; a custom + # address may carry a token. Only scheme, host and port are shown. + FakeWSClient = _scripted_ws_client([ + ("error", ValueError(f"{self.TOKEN_URL} isn't a valid URI")), + ("error", OSError("connect to gw.example.com:8443/ws/path-token-abc?token=SECRET123 failed")), + ("reconnecting", 1), + ]) + ch = WeComChannel() + config = { + "botId": "bot-1", + "secret": "secret-1", + "websocketUrl": self.TOKEN_URL, + "reconnectTimeoutSeconds": 0.01, + } + + with patch("wecom_aibot_sdk.WSClient", FakeWSClient): + with pytest.raises(RuntimeError, match="reconnect timed out") as raised: + await asyncio.wait_for(ch.start(config, AsyncMock(), asyncio.Event()), timeout=5) + + for shown in (str(raised.value), ch.status.last_error or ""): + assert "wss://gw.example.com:8443" in shown + for secret in self.URL_SECRETS: + assert secret not in shown + + async def test_reconnect_timeout_without_error_shows_only_the_host(self): + FakeWSClient = _scripted_ws_client([("disconnected", "socket closed")]) + ch = WeComChannel() + config = { + "botId": "bot-1", + "secret": "secret-1", + "websocketUrl": self.TOKEN_URL, + "reconnectTimeoutSeconds": 0.01, + } + + with patch("wecom_aibot_sdk.WSClient", FakeWSClient): + with pytest.raises(RuntimeError, match="reconnect timed out") as raised: + await asyncio.wait_for(ch.start(config, AsyncMock(), asyncio.Event()), timeout=5) + + assert "wss://gw.example.com:8443" in str(raised.value) + for secret in self.URL_SECRETS: + assert secret not in str(raised.value) + + @pytest.mark.parametrize( + ("configured", "raw_error", "secrets"), + [ + # websockets' redirect check names the target, which keeps only some of the parameters. + ( + "wss://gw.example/ws/path-token?token=SECRET123®ion=cn", # secret-guard: allow (synthetic test credential) + "cannot follow redirect to ws://gw.example/ws/path-token?token=SECRET123", + ("SECRET123", "path-token"), + ), + # A parameter value on its own, outside any address. + ( + "wss://gw.example/ws?token=SECRET123®ion=cn", # secret-guard: allow (synthetic test credential) + "server refused credential SECRET123", + ("SECRET123",), + ), + # Percent-encoded in the configured address, decoded (or encoded) in the error. + ( + "wss://gw.example/ws?token=a%2Fb%2Bc12345", # secret-guard: allow (synthetic test credential) + "rejected a/b+c12345 (sent as a%2Fb%2Bc12345)", + ("a/b+c12345", "a%2Fb%2Bc12345"), + ), + # User info, in an address the error rewrote with an explicit port. + ( + "wss://bot:pa55word@gw.example/ws", # secret-guard: allow (synthetic test credential) + "InvalidURI: wss://bot:pa55word@gw.example:443/ws is not valid", # secret-guard: allow (synthetic) + ("pa55word", "bot:pa55word"), + ), + # A quote inside the credential: an address pattern would stop there and miss the rest. + ( + "wss://bot:ab'LONGSECRET123456@gw.example/ws", # secret-guard: allow (synthetic test credential) + "cannot follow redirect to ws://bot:ab'LONGSECRET123456@gw.example/ws", # secret-guard: allow (synthetic) + ("LONGSECRET123456",), + ), + ( + "wss://gw.example/ws?token=ab%27LONGSECRET123456", # secret-guard: allow (synthetic test credential) + "cannot follow redirect to ws://gw.example/ws?token=ab'LONGSECRET123456", # secret-guard: allow (synthetic) + ("LONGSECRET123456",), + ), + ], + ) + def test_error_text_loses_credentials_of_the_address(self, configured, raw_error, secrets): + from flocks.channel.builtin.wecom.channel import _describe_sdk_error + + shown = _describe_sdk_error(RuntimeError(raw_error), configured) + + assert "wss://gw.example" in shown + for secret in secrets: + assert secret not in shown + + def test_status_gives_type_and_codes_never_the_error_text(self): + from flocks.channel.builtin.wecom.channel import _describe_sdk_error + + class InvalidStatus(Exception): + # Shaped like websockets.exceptions.InvalidStatus: the code sits on the response. + def __init__(self): + super().__init__("server rejected WebSocket connection: HTTP 403 body=whatever-the-proxy-said") + self.response = types.SimpleNamespace(status_code=403) + + shown = _describe_sdk_error(InvalidStatus(), "wss://gw.example/ws") + assert "错误类型 InvalidStatus,HTTP 403" in shown + assert "whatever-the-proxy-said" not in shown + + refused = _describe_sdk_error( + Exception("Authentication failed: echoed wss://gw.example/ws?token=ECHOED (code: 40058)"), + "wss://gw.example/ws", + ) + assert "企业微信错误码 40058" in refused + assert "ECHOED" not in refused + assert "wecom.ws.error" in refused # where the full error is + + @staticmethod + def _cert_failure(): + import ssl + + # As the ssl module raises it when no root certificate vouches for the server's. + error = ssl.SSLCertVerificationError( + 1, + "[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: " + "unable to get local issuer certificate (_ssl.c:1010)", + ) + error.verify_code = 20 + error.verify_message = "unable to get local issuer certificate" + return error + + def test_certificate_failure_points_at_root_certificates_not_the_network(self): + from flocks.channel.builtin.wecom.channel import _describe_sdk_error + + shown = _describe_sdk_error(self._cert_failure(), "wss://openws.work.weixin.qq.com") + + assert "(wss://openws.work.weixin.qq.com)时证书校验没通过" in shown + assert "ca-certificates" in shown + assert "根证书加进系统信任" in shown + assert "错误类型 SSLCertVerificationError,errno 1,证书校验错误码 20" in shown + assert "wecom.ws.error" in shown + # Not the hint for an address the server cannot reach. + assert "请确认服务器能访问这个地址" not in shown + assert "检查代理设置" not in shown + assert "_ssl.c" not in shown + + def test_certificate_failure_is_found_behind_a_wrapping_error(self): + from flocks.channel.builtin.wecom.channel import _describe_sdk_error + + try: + try: + raise self._cert_failure() + except Exception as cause: + raise RuntimeError("websocket connect failed") from cause + except RuntimeError as wrapped: + shown = _describe_sdk_error(wrapped, "wss://gw.example/ws") + + assert "时证书校验没通过" in shown + assert "错误类型 SSLCertVerificationError" in shown + assert "websocket connect failed" not in shown + + def test_other_ssl_errors_keep_the_reachability_hint(self): + import ssl + + from flocks.channel.builtin.wecom.channel import _describe_sdk_error + + shown = _describe_sdk_error(ssl.SSLError(1, "[SSL: WRONG_VERSION_NUMBER] wrong version number"), "wss://gw.example/ws") + + assert "证书校验没通过" not in shown + assert "请确认服务器能访问这个地址" in shown + assert "错误类型 SSLError" in shown + + async def test_reconnect_timeout_names_the_certificate_failure(self): + ch = WeComChannel() + client = object() + ch._ws_client = client + + ch._handle_error(self._cert_failure(), client=client) + assert "证书校验没通过" in (ch.status.last_error or "") + assert not ch._failure_event.is_set() # the SDK keeps retrying; a fixed trust store recovers + + message = ch._reconnect_timeout_message() + assert message.startswith("WeCom reconnect timed out after") + assert "证书校验没通过" in message + assert "检查代理设置" not in message + + @pytest.mark.parametrize( + ("url", "shown"), + [ + ("wss://openws.work.weixin.qq.com", "wss://openws.work.weixin.qq.com"), + ("ws://[::1]:9/path?k=v", "ws://[::1]:9"), + ("wss://user:pw@host.example/x", "wss://host.example"), + ("wss://host.example:99999/x", "自定义地址"), + ("openws.work.weixin.qq.com/ws", "自定义地址"), + ], + ) + def test_shown_address_is_scheme_host_and_port(self, url, shown): + from flocks.channel.builtin.wecom.channel import _shown_ws_url + + assert _shown_ws_url(url) == shown + + async def test_transient_connection_error_shows_until_authenticated(self): + ch = WeComChannel() + client = object() + ch._ws_client = client + + ch._handle_error(OSError("network is unreachable"), client=client) + assert ch.status.connected is False + assert "错误类型 OSError" in (ch.status.last_error or "") + assert "network is unreachable" not in (ch.status.last_error or "") + assert not ch._failure_event.is_set() + + ch._handle_authenticated(client=client) + assert ch.status.connected is True + assert ch.status.last_error is None + + async def test_events_from_a_replaced_client_are_ignored(self): + ch = WeComChannel() + old_client, new_client = object(), object() + ch._ws_client = new_client + + ch._handle_error(self.AUTH_REFUSED, client=old_client) + ch._handle_disconnected(self.REPLACED, client=old_client) + ch._handle_authenticated(client=old_client) + + assert not ch._failure_event.is_set() + assert ch.status.connected is False + assert ch.status.last_error is None + + async def test_gateway_marks_connected_only_after_authentication(self): + from flocks.channel.gateway.manager import GatewayManager + + FakeWSClient = _scripted_ws_client([]) # connected socket, no answer to the subscribe yet + ch = WeComChannel() + abort_event = asyncio.Event() + + with patch("wecom_aibot_sdk.WSClient", FakeWSClient): + task = asyncio.create_task(GatewayManager()._run_with_reconnect( + channel_id="wecom", + plugin=ch, + config={"botId": "bot-1", "secret": "secret-1"}, + on_message=AsyncMock(), + abort_event=abort_event, + )) + # The gateway pre-marks channels that are not self-managed after 0.5 s. + await asyncio.sleep(0.7) + assert ch.status.connected is False + + FakeWSClient.last_instance.handlers["authenticated"]() + assert ch.status.connected is True + + abort_event.set() + await asyncio.wait_for(task, timeout=5) + + async def test_gateway_shows_refused_credentials_while_waiting_to_retry(self): + from flocks.channel.gateway.manager import GatewayManager + + FakeWSClient = _scripted_ws_client([("error", self.AUTH_REFUSED)]) + ch = WeComChannel() + abort_event = asyncio.Event() + + with patch("wecom_aibot_sdk.WSClient", FakeWSClient): + task = asyncio.create_task(GatewayManager()._run_with_reconnect( + channel_id="wecom", + plugin=ch, + config={"botId": "bot-1", "secret": "wrong-secret"}, + on_message=AsyncMock(), + abort_event=abort_event, + )) + await asyncio.sleep(0.2) # first attempt failed; the gateway waits before retrying + + assert ch.status.connected is False + assert "鉴权失败" in (ch.status.last_error or "") + assert ch.status.error_count == 1 + + abort_event.set() + await asyncio.wait_for(task, timeout=5) + + # ------------------------------------------------------------------ # normalize_target # ------------------------------------------------------------------ diff --git a/tests/cli/test_service_manager.py b/tests/cli/test_service_manager.py index 98c1b2b4f..54b9edd50 100644 --- a/tests/cli/test_service_manager.py +++ b/tests/cli/test_service_manager.py @@ -1523,7 +1523,8 @@ def test_start_backend_reports_started_after_probe_succeeds(monkeypatch, tmp_pat service_manager._start_backend_process(service_manager.ServiceConfig(), console) backend_env = spawn_calls[0]["kwargs"]["env"] - assert backend_env["_FLOCKS_WEBUI_HOST"] == "127.0.0.1" + # The default bind: every interface (service_config.DEFAULT_SERVICE_HOST). + assert backend_env["_FLOCKS_WEBUI_HOST"] == "0.0.0.0" assert backend_env["_FLOCKS_WEBUI_PORT"] == "5173" assert not paths.backend_pid.exists() assert backend_env["FLOCKS_CONSOLE_BASE_URL"] == service_manager.DEFAULT_FLOCKS_CONSOLE_BASE_URL diff --git a/tests/console/test_connectivity.py b/tests/console/test_connectivity.py new file mode 100644 index 000000000..ad34902ee --- /dev/null +++ b/tests/console/test_connectivity.py @@ -0,0 +1,85 @@ +"""flocks.console.connectivity: whether this install reaches Console now. + +Case list (编号 | 场景): + CN1 no Console address: not configured, not online, nothing asked + CN2 Console answering /health is online, an older one answering 404 too; a 5xx in its place, no + answer or a timeout is not + CN3 an answer is kept for CACHE_SECONDS; refresh asks again; another address asks again +""" + +from __future__ import annotations + +import httpx +import pytest +from flocks.console import connectivity + +pytestmark = pytest.mark.asyncio + +_REAL_CLIENT = httpx.AsyncClient + + +@pytest.fixture(autouse=True) +def _fresh(monkeypatch: pytest.MonkeyPatch): + connectivity.forget() + monkeypatch.setenv("FLOCKS_CONSOLE_BASE_URL", "https://console.example") + yield + connectivity.forget() + + +def console(monkeypatch: pytest.MonkeyPatch, handler) -> list[httpx.Request]: + """A Console answering through handler; the requests it got.""" + seen: list[httpx.Request] = [] + + def record(request: httpx.Request) -> httpx.Response: + seen.append(request) + return handler(request) + + class Client(_REAL_CLIENT): # type: ignore[misc,valid-type] + def __init__(self, *args, **kwargs): + kwargs["transport"] = httpx.MockTransport(record) + super().__init__(*args, **kwargs) + + monkeypatch.setattr(connectivity.httpx, "AsyncClient", Client) + return seen + + +async def test_cn1_no_console_address(monkeypatch: pytest.MonkeyPatch): + seen = console(monkeypatch, lambda r: httpx.Response(200)) + monkeypatch.setenv("FLOCKS_CONSOLE_BASE_URL", "") + answer = await connectivity.console_connectivity() + assert (answer["configured"], answer["online"], answer["console_host"]) == (False, False, "") + assert seen == [] + + +@pytest.mark.parametrize("respond, online", [ + (lambda r: httpx.Response(200, json={"status": "ok"}), True), + (lambda r: httpx.Response(404), True), + (lambda r: httpx.Response(502, text="Bad Gateway"), False), + (lambda r: (_ for _ in ()).throw(httpx.ConnectError("refused")), False), + (lambda r: (_ for _ in ()).throw(httpx.ReadTimeout("slow")), False), +]) +async def test_cn2_what_counts_as_online(monkeypatch: pytest.MonkeyPatch, respond, online: bool): + seen = console(monkeypatch, respond) + answer = await connectivity.console_connectivity() + assert answer["configured"] is True and answer["online"] is online + assert answer["console_host"] == "console.example" and answer["checked_at"] + assert [str(r.url) for r in seen] == ["https://console.example/health"] + + +async def test_cn3_an_answer_is_kept_for_a_while(monkeypatch: pytest.MonkeyPatch): + seen = console(monkeypatch, lambda r: httpx.Response(200)) + assert (await connectivity.console_connectivity())["online"] is True + assert (await connectivity.console_connectivity())["online"] is True + assert len(seen) == 1 + # Asked again on purpose, or for another address. + await connectivity.console_connectivity(refresh=True) + assert len(seen) == 2 + monkeypatch.setenv("FLOCKS_CONSOLE_BASE_URL", "console-b.example") + answer = await connectivity.console_connectivity() + assert len(seen) == 3 and answer["console_host"] == "console-b.example" + assert str(seen[-1].url) == "https://console-b.example/health" + # Kept no longer than CACHE_SECONDS. + base, asked_at, kept = connectivity._kept + connectivity._kept = (base, asked_at - connectivity.CACHE_SECONDS - 1, kept) + await connectivity.console_connectivity() + assert len(seen) == 4 diff --git a/tests/contracts/access/test_soc_alert_filters.py b/tests/contracts/access/test_soc_alert_filters.py index 08025871b..45ffaaa05 100644 --- a/tests/contracts/access/test_soc_alert_filters.py +++ b/tests/contracts/access/test_soc_alert_filters.py @@ -27,18 +27,13 @@ def soc_query(tmp_path, monkeypatch, request): spec = importlib.util.spec_from_file_location("soc_filter_test", path) ops = importlib.util.module_from_spec(spec) spec.loader.exec_module(ops) + # The contract names the platform's SOC alert store; here that is this SQLite file. + from flocks.workflow.soc_store import _paths + db = tmp_path / "soc.db" - monkeypatch.setattr( - ops, - "_sqlite_settings", - lambda: { - "db_path": db, - "table": "alert_records", - "record_column": "record_json", - "date_column": "asset_date", - "event_time_column": "event_time", - }, - ) + monkeypatch.setattr(_paths, "SOC_DB", db) + monkeypatch.delenv("FLOCKS_SOC_ALERTS_SQLITE_DB", raising=False) + monkeypatch.delenv("FLOCKS_SOC_ALERTS_CONFIG", raising=False) jsonl = tmp_path / "jsonl" if request.param == "jsonl": diff --git a/tests/hub/test_catalog_bad_local_plugins.py b/tests/hub/test_catalog_bad_local_plugins.py new file mode 100644 index 000000000..be987e720 --- /dev/null +++ b/tests/hub/test_catalog_bad_local_plugins.py @@ -0,0 +1,124 @@ +"""One broken plugin on disk must not take the hub catalog, and the pages built on it, down. + +Where a deployment runs the service from the account's home (the enterprise +core does), the project plugin root and the user plugin root are one directory: +every agent and workflow someone wrote there goes through the catalog's +manifest readers. The runtime's own loaders skip a bad one; so must the catalog. +""" + +import json +from pathlib import Path + +import pytest + +from flocks.hub import catalog, local +from flocks.server.routes.hub import _load_scene_suites + + +@pytest.fixture() +def home_as_project(isolated_hub_env, monkeypatch: pytest.MonkeyPatch): + home: Path = isolated_hub_env["home"] + monkeypatch.delenv("FLOCKS_ROOT", raising=False) + monkeypatch.chdir(home) + catalog.clear_catalog_caches() + assert local.install_root("agent", "project").resolve() == local.install_root("agent", "global").resolve() + yield {"plugins": local.install_root("agent", "project").parent, "data_dir": isolated_hub_env["data_dir"]} + catalog.clear_catalog_caches() + + +def _write(path: Path, content: bytes | str) -> Path: + path.parent.mkdir(parents=True, exist_ok=True) + if isinstance(content, str): + content = content.encode("utf-8") + path.write_bytes(content) + return path + + +def _healthy_neighbours(plugins: Path) -> None: + _write(plugins / "agents" / "healthy_agent" / "agent.yaml", "name: healthy_agent\ntools: [bash]\n") + _write(plugins / "workflows" / "healthy_flow" / "workflow.json", json.dumps({"name": "healthy_flow"})) + + +def _assert_catalog_works(*expected: tuple[str, str]) -> dict[tuple[str, str], object]: + catalog.clear_catalog_caches() + entries = {(entry.type, entry.id): entry for entry in catalog.list_catalog()} + assert ("component", "soc-workspace") in entries + for key in expected: + assert key in entries, key + # What the scene page reads. + assert "soc-workspace" in {suite.id for suite in _load_scene_suites()} + return entries + + +@pytest.mark.parametrize( + "content", + [ + pytest.param("name: bad_agent\ntools:\n", id="tools-empty-key"), + pytest.param("name: bad_agent\ntags:\n", id="tags-empty-key"), + pytest.param("name: bad_agent\ntools: 3\n", id="tools-a-number"), + pytest.param("name: bad_agent\ntags: true\n", id="tags-a-bool"), + pytest.param("name: [bad_agent\n", id="not-yaml"), + pytest.param("- just\n- a list\n", id="yaml-list"), + ], +) +def test_an_agent_with_odd_yaml_is_still_listed(home_as_project, content: str): + plugins = home_as_project["plugins"] + _healthy_neighbours(plugins) + _write(plugins / "agents" / "bad_agent" / "agent.yaml", content) + + entries = _assert_catalog_works(("agent", "bad_agent"), ("agent", "healthy_agent"), ("workflow", "healthy_flow")) + + assert entries[("agent", "bad_agent")].state == "installed" + + +@pytest.mark.parametrize( + "content", + [ + pytest.param(b"{broken", id="not-json"), + pytest.param(b"", id="empty-file"), + pytest.param(b"[1, 2]", id="json-list"), + pytest.param(b"\xef\xbb\xbf{\"name\": \"x\"}", id="utf8-bom"), + pytest.param(b"{\"name\": \"\xd6\xd0\"}", id="gbk"), + ], +) +def test_a_workflow_with_a_broken_file_is_still_listed(home_as_project, content: bytes): + plugins = home_as_project["plugins"] + _healthy_neighbours(plugins) + _write(plugins / "workflows" / "bad_flow" / "workflow.json", content) + + entries = _assert_catalog_works(("workflow", "bad_flow"), ("agent", "healthy_agent"), ("workflow", "healthy_flow")) + + assert entries[("workflow", "bad_flow")].name == "bad_flow" + + +def test_a_reader_that_fails_costs_only_that_plugin(home_as_project, monkeypatch: pytest.MonkeyPatch): + plugins = home_as_project["plugins"] + _healthy_neighbours(plugins) + _write(plugins / "agents" / "exploding" / "agent.yaml", "name: exploding\n") + real = catalog._agent_manifest + + def reader(plugin_id, root): + if plugin_id == "exploding": + raise RuntimeError("something nobody thought of") + return real(plugin_id, root) + + monkeypatch.setattr(catalog, "_agent_manifest", reader) + + entries = _assert_catalog_works(("agent", "healthy_agent"), ("workflow", "healthy_flow")) + + assert ("agent", "exploding") not in entries + + +def test_a_superseded_scan_is_not_mistaken_for_a_bad_plugin(home_as_project, monkeypatch: pytest.MonkeyPatch): + def reader(_plugin_id, _root): + raise catalog.tool_tree.Superseded() + + with pytest.raises(catalog.tool_tree.Superseded): + catalog._read_local_plugin(reader, "any", Path("any")) + + +def test_an_install_record_file_that_is_not_an_object_reads_as_no_records(home_as_project): + _write(home_as_project["data_dir"] / "hub" / "installed.json", "[1]") + + assert local.load_installed_records() == {} + _assert_catalog_works() diff --git a/tests/hub/test_soc_dashboard_schema.py b/tests/hub/test_soc_dashboard_schema.py index f9b86f46a..796d00202 100644 --- a/tests/hub/test_soc_dashboard_schema.py +++ b/tests/hub/test_soc_dashboard_schema.py @@ -1,5 +1,6 @@ import importlib.util import asyncio +import uuid import gc import json import sqlite3 @@ -49,7 +50,7 @@ def test_activity_preview_handles_bounded_execution_shapes(wrapper): inputs = {"syslog_message": {"message": "Sep 11 device vendor: " + json.dumps(record)}} else: inputs = {"syslog_message": {"message": json.dumps({"data": {"message": json.dumps(record)}})}} - alert, count = handlers._dashboard_execution_detail(json.dumps(output), json.dumps(inputs)) + alert, count = handlers._store._dashboard_execution_detail(json.dumps(output), json.dumps(inputs)) assert alert == {"id": "a", "threatName": "scan", "sourceType": "ndr", "srcIp": "192.0.2.1", "dstIp": "198.51.100.2"} assert count == (1 if wrapper == "direct" else None) @@ -61,85 +62,85 @@ def test_activity_does_not_combine_unrelated_alerts_or_guess_source(): {"id": "a", "threat_name": "first", "sip": "192.0.2.1"}, {"id": "b", "dip": "198.51.100.2", "_source_type": "ndr"}, ]} - alert, _ = handlers._dashboard_execution_detail(json.dumps(output), "{}") + alert, _ = handlers._store._dashboard_execution_detail(json.dumps(output), "{}") assert alert["id"] == "a" assert alert["dstIp"] == alert["sourceType"] == "" def test_activity_distinguishes_empty_unknown_and_real_batches(tmp_path): handlers = _load_dashboard_handlers() - handlers.WORKFLOW_DB = _activity_workflow_db(tmp_path) - _activity_execution(handlers.WORKFLOW_DB, "empty", output={"stats": {"raw_count": 0}}) - _activity_execution(handlers.WORKFLOW_DB, "unknown", inputs={"source_log_type": "ndr"}) - _activity_execution(handlers.WORKFLOW_DB, "nonempty", inputs={"_soc_alert_count": 5}) - _activity_execution(handlers.WORKFLOW_DB, "queued", status="queued", inputs={"_soc_alert_count": 2}) - events = {e["eventId"]: e for e in handlers._get_workflow_recent_events("stream_alert_denoise")} + handlers._store._paths.WORKFLOW_DB = _activity_workflow_db(tmp_path) + _activity_execution(handlers._store._paths.WORKFLOW_DB, "empty", output={"stats": {"raw_count": 0}}) + _activity_execution(handlers._store._paths.WORKFLOW_DB, "unknown", inputs={"source_log_type": "ndr"}) + _activity_execution(handlers._store._paths.WORKFLOW_DB, "nonempty", inputs={"_soc_alert_count": 5}) + _activity_execution(handlers._store._paths.WORKFLOW_DB, "queued", status="queued", inputs={"_soc_alert_count": 2}) + events = {e["eventId"]: e for e in handlers._store.workflow_recent_events("stream_alert_denoise")} assert "workflow-execution:empty" not in events assert events["workflow-execution:unknown"]["result"]["rawCount"] is None assert events["workflow-execution:unknown"]["alert"]["threatName"] == "降噪批次 · 数量未提供" assert events["workflow-execution:nonempty"]["result"]["rawCount"] == 5 assert events["workflow-execution:queued"]["status"] == "queued" - with sqlite3.connect(handlers.WORKFLOW_DB) as conn: + with sqlite3.connect(handlers._store._paths.WORKFLOW_DB) as conn: assert conn.execute("SELECT count(*) FROM workflow_executions").fetchone()[0] == 4 def test_activity_keeps_long_running_execution_and_bounds_history(tmp_path): handlers = _load_dashboard_handlers() - handlers.WORKFLOW_DB = _activity_workflow_db(tmp_path) - _activity_execution(handlers.WORKFLOW_DB, "long-running", started=1000) + handlers._store._paths.WORKFLOW_DB = _activity_workflow_db(tmp_path) + _activity_execution(handlers._store._paths.WORKFLOW_DB, "long-running", started=1000) for index in range(30): - _activity_execution(handlers.WORKFLOW_DB, f"done-{index}", status="success", started=2000 + index) + _activity_execution(handlers._store._paths.WORKFLOW_DB, f"done-{index}", status="success", started=2000 + index) snapshot = {"complete": True} - events = handlers._get_workflow_recent_events("stream_alert_denoise", snapshot=snapshot) + events = handlers._store.workflow_recent_events("stream_alert_denoise", snapshot=snapshot) assert len(events) == 11 assert events[0]["eventId"] == "workflow-execution:long-running" assert events[0]["updatedAt"] != events[0]["occurredAt"] assert snapshot["complete"] is True assert all(e["eventId"] != "workflow-execution:long-running" for e in - handlers._get_workflow_recent_events("stream_alert_denoise", 2, 3)) + handlers._store.workflow_recent_events("stream_alert_denoise", 2, 3)) def test_activity_large_payload_and_database_lock_degrade_without_writes(tmp_path): handlers = _load_dashboard_handlers() - handlers.WORKFLOW_DB = _activity_workflow_db(tmp_path) - _activity_execution(handlers.WORKFLOW_DB, "large", payload={"large": "x" * 1_000_000}, + handlers._store._paths.WORKFLOW_DB = _activity_workflow_db(tmp_path) + _activity_execution(handlers._store._paths.WORKFLOW_DB, "large", payload={"large": "x" * 1_000_000}, inputs={"large": "x" * 1_000_000}) - events = handlers._get_workflow_recent_events("stream_alert_denoise") + events = handlers._store.workflow_recent_events("stream_alert_denoise") assert len(json.dumps(events)) < 4096 - with sqlite3.connect(handlers.WORKFLOW_DB) as conn: + with sqlite3.connect(handlers._store._paths.WORKFLOW_DB) as conn: conn.execute("BEGIN EXCLUSIVE") snapshot = {"complete": True} started = time.monotonic() - assert handlers._get_workflow_recent_events("stream_alert_denoise", snapshot=snapshot) == [] + assert handlers._store.workflow_recent_events("stream_alert_denoise", snapshot=snapshot) == [] assert time.monotonic() - started < 1.0 assert snapshot["complete"] is False def test_activity_truncated_active_snapshot_is_not_authoritative(tmp_path): handlers = _load_dashboard_handlers() - handlers.WORKFLOW_DB = _activity_workflow_db(tmp_path) + handlers._store._paths.WORKFLOW_DB = _activity_workflow_db(tmp_path) for index in range(12): - _activity_execution(handlers.WORKFLOW_DB, str(index)) + _activity_execution(handlers._store._paths.WORKFLOW_DB, str(index)) snapshot = {"complete": True} - assert len(handlers._get_workflow_recent_events("stream_alert_denoise", snapshot=snapshot)) <= 20 + assert len(handlers._store.workflow_recent_events("stream_alert_denoise", snapshot=snapshot)) <= 20 assert snapshot["complete"] is False def test_activity_does_not_substitute_execution_id_for_missing_alert_id(tmp_path): handlers = _load_dashboard_handlers() - handlers.WORKFLOW_DB = _activity_workflow_db(tmp_path) - _activity_execution(handlers.WORKFLOW_DB, "batch", inputs={ + handlers._store._paths.WORKFLOW_DB = _activity_workflow_db(tmp_path) + _activity_execution(handlers._store._paths.WORKFLOW_DB, "batch", inputs={ "alerts": [{"threat_name": "scan", "sip": "192.0.2.1"}], }) - event = handlers._get_workflow_recent_events("stream_alert_denoise")[0] + event = handlers._store.workflow_recent_events("stream_alert_denoise")[0] assert event["eventId"] == "workflow-execution:batch" assert event["alert"]["id"] == "" def test_activity_old_sqlite_omits_payloads_instead_of_using_unsafe_length(tmp_path, monkeypatch): handlers = _load_dashboard_handlers() - handlers.WORKFLOW_DB = _activity_workflow_db(tmp_path) - _activity_execution(handlers.WORKFLOW_DB, "old-sqlite", inputs={ + handlers._store._paths.WORKFLOW_DB = _activity_workflow_db(tmp_path) + _activity_execution(handlers._store._paths.WORKFLOW_DB, "old-sqlite", inputs={ "alerts": [{"threat_name": "must not read this"}], }) original_connect = sqlite3.connect @@ -152,8 +153,8 @@ def execute(self, sql, *args): raise sqlite3.OperationalError("no such function: octet_length") return super().execute(sql, *args) - monkeypatch.setattr(handlers.sqlite3, "connect", lambda *a, **kw: original_connect(*a, **kw, factory=OldSQLiteConnection)) - events = handlers._get_workflow_recent_events("stream_alert_denoise") + monkeypatch.setattr(handlers._store.sqlite3, "connect", lambda *a, **kw: original_connect(*a, **kw, factory=OldSQLiteConnection)) + events = handlers._store.workflow_recent_events("stream_alert_denoise") assert events[0]["status"] == "running" assert "must not read this" not in json.dumps(events) assert not any("CASE WHEN" in query or "length(payload)" in query for query in queries) @@ -161,17 +162,17 @@ def execute(self, sql, *args): def test_activity_reader_does_not_wait_or_open_another_db_when_busy(tmp_path, monkeypatch): handlers = _load_dashboard_handlers() - handlers.WORKFLOW_DB = _activity_workflow_db(tmp_path) - _activity_execution(handlers.WORKFLOW_DB, "active") - with handlers._workflow_activity_read_lock: + handlers._store._paths.WORKFLOW_DB = _activity_workflow_db(tmp_path) + _activity_execution(handlers._store._paths.WORKFLOW_DB, "active") + with handlers._store._workflow_activity_read_lock: with monkeypatch.context() as patch: def unexpected_connect(*args, **kwargs): raise AssertionError("contending reader must not open SQLite") - patch.setattr(handlers.sqlite3, "connect", unexpected_connect) + patch.setattr(handlers._store.sqlite3, "connect", unexpected_connect) snapshot = {"complete": True, "available": True} - assert handlers._get_workflow_recent_events("stream_alert_denoise", snapshot=snapshot) == [] + assert handlers._store.workflow_recent_events("stream_alert_denoise", snapshot=snapshot) == [] assert snapshot == {"complete": False, "available": False} - assert handlers._get_workflow_recent_events("stream_alert_denoise") + assert handlers._store.workflow_recent_events("stream_alert_denoise") @pytest.mark.asyncio @@ -184,48 +185,48 @@ def blocked_read(*args): assert release.wait(3), "test must release its worker" return [] - monkeypatch.setattr(handlers, "_read_workflow_recent_events", blocked_read) - request = asyncio.create_task(asyncio.to_thread(handlers._get_workflow_recent_events, "stream_alert_denoise")) + monkeypatch.setattr(handlers._store, "_read_workflow_recent_events", blocked_read) + request = asyncio.create_task(asyncio.to_thread(handlers._store.workflow_recent_events, "stream_alert_denoise")) try: assert await asyncio.to_thread(entered.wait, 3) request.cancel() with pytest.raises(asyncio.CancelledError): await request - assert handlers._workflow_activity_read_lock.locked() + assert handlers._store._workflow_activity_read_lock.locked() snapshot = {"complete": True, "available": True} - assert handlers._get_workflow_recent_events("stream_alert_denoise", snapshot=snapshot) == [] + assert handlers._store.workflow_recent_events("stream_alert_denoise", snapshot=snapshot) == [] assert snapshot == {"complete": False, "available": False} finally: release.set() - assert await asyncio.to_thread(handlers._workflow_activity_read_lock.acquire, True, 3) - handlers._workflow_activity_read_lock.release() + assert await asyncio.to_thread(handlers._store._workflow_activity_read_lock.acquire, True, 3) + handlers._store._workflow_activity_read_lock.release() def test_activity_preview_limit_counts_utf8_bytes_not_characters(tmp_path): handlers = _load_dashboard_handlers() - handlers.WORKFLOW_DB = _activity_workflow_db(tmp_path) - _activity_execution(handlers.WORKFLOW_DB, "unicode") + handlers._store._paths.WORKFLOW_DB = _activity_workflow_db(tmp_path) + _activity_execution(handlers._store._paths.WORKFLOW_DB, "unicode") inputs = json.dumps({"padding": "中" * 100_000, "alerts": [{"threat_name": "oversized-preview"}]}, ensure_ascii=False) assert len(inputs) < 262144 < len(inputs.encode("utf-8")) - with sqlite3.connect(handlers.WORKFLOW_DB) as conn: + with sqlite3.connect(handlers._store._paths.WORKFLOW_DB) as conn: conn.execute("UPDATE workflow_executions SET input_params = ?", (inputs,)) - events = handlers._get_workflow_recent_events("stream_alert_denoise") + events = handlers._store.workflow_recent_events("stream_alert_denoise") assert events[0]["status"] == "running" assert "oversized-preview" not in json.dumps(events) def test_activity_deadline_is_checked_even_without_sqlite_progress_callback(tmp_path, monkeypatch): handlers = _load_dashboard_handlers() - handlers.WORKFLOW_DB = _activity_workflow_db(tmp_path) - _activity_execution(handlers.WORKFLOW_DB, "active") + handlers._store._paths.WORKFLOW_DB = _activity_workflow_db(tmp_path) + _activity_execution(handlers._store._paths.WORKFLOW_DB, "active") ticks = iter([100.0, 101.0]) - monkeypatch.setattr(handlers, "time", SimpleNamespace(monotonic=lambda: next(ticks, 101.0))) + monkeypatch.setattr(handlers._store, "time", SimpleNamespace(monotonic=lambda: next(ticks, 101.0))) snapshot = {"complete": True, "available": True} - assert handlers._get_workflow_recent_events("stream_alert_denoise", snapshot=snapshot) == [] + assert handlers._store.workflow_recent_events("stream_alert_denoise", snapshot=snapshot) == [] assert snapshot == {"complete": False, "available": False} # Errors must release the worker-owned lock as well. - assert handlers._workflow_activity_read_lock.acquire(blocking=False) - handlers._workflow_activity_read_lock.release() + assert handlers._store._workflow_activity_read_lock.acquire(blocking=False) + handlers._store._workflow_activity_read_lock.release() @pytest.mark.skipif(sys.platform not in {"darwin", "linux"}, reason="native RSS via resource is Unix-only") @@ -238,21 +239,19 @@ def test_activity_large_text_is_not_materialized_in_native_sqlite_memory(tmp_pat # A fresh process excludes fixture allocations; tracemalloc alone cannot # see SQLite's native buffers. Do not start the application or touch user DBs. script = ''' -import importlib.util, json, resource, sys +import json, resource, sys from pathlib import Path -spec = importlib.util.spec_from_file_location("soc_native_rss_test", sys.argv[1]) -module = importlib.util.module_from_spec(spec) -sys.modules[spec.name] = module -spec.loader.exec_module(module) -module.WORKFLOW_DB = Path(sys.argv[2]) +from flocks.workflow.soc_store import _paths, dashboard +_paths.WORKFLOW_DB = Path(sys.argv[1]) before = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss -events = module._get_workflow_recent_events("stream_alert_denoise") +events = dashboard.workflow_recent_events("stream_alert_denoise") after = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss scale = 1024**2 if sys.platform == "darwin" else 1024 print(json.dumps({"growth_mib": (after - before) / scale, "events": len(events)})) ''' - result = subprocess.run([sys.executable, "-B", "-c", script, handlers.__file__, str(db)], - check=True, text=True, capture_output=True, timeout=20) + result = subprocess.run([sys.executable, "-B", "-c", script, str(db)], + check=True, text=True, capture_output=True, timeout=60, + cwd=Path(__file__).resolve().parents[2]) measurement = json.loads(result.stdout) assert measurement["events"] == 11 assert measurement["growth_mib"] < 16, measurement @@ -260,20 +259,20 @@ def test_activity_large_text_is_not_materialized_in_native_sqlite_memory(tmp_pat def test_activity_repeated_projection_does_not_retain_payloads(tmp_path): handlers = _load_dashboard_handlers() - handlers.WORKFLOW_DB = _activity_workflow_db(tmp_path) + handlers._store._paths.WORKFLOW_DB = _activity_workflow_db(tmp_path) for index in range(12): - _activity_execution(handlers.WORKFLOW_DB, str(index), inputs={ + _activity_execution(handlers._store._paths.WORKFLOW_DB, str(index), inputs={ "_soc_alert_preview": {"threat_name": "scan", "sip": "192.0.2.1"}, "padding": "x" * 20000, }) tracemalloc.start(1) try: for _ in range(10): - handlers._get_workflow_recent_events("stream_alert_denoise") + handlers._store.workflow_recent_events("stream_alert_denoise") gc.collect() before, _ = tracemalloc.get_traced_memory() for _ in range(200): - events = handlers._get_workflow_recent_events("stream_alert_denoise") + events = handlers._store.workflow_recent_events("stream_alert_denoise") assert len(events) <= 20 assert len(json.dumps(events)) < 20000 gc.collect() @@ -284,6 +283,31 @@ def test_activity_repeated_projection_does_not_retain_payloads(tmp_path): tracemalloc.stop() +def _fresh_soc_store(): + """The platform's SOC data service (flocks.workflow.soc_store), as a copy of its own. + + The pages' handlers hold no database code; they read through this package. + Each test gets a fresh copy so that its caches, locks and file locations + start clean, as a newly loaded handlers module's did. + """ + package_dir = Path(__file__).resolve().parents[2] / "flocks" / "workflow" / "soc_store" + name = f"_soc_store_test_{uuid.uuid4().hex}" + spec = importlib.util.spec_from_file_location( + name, package_dir / "__init__.py", submodule_search_locations=[str(package_dir)], + ) + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + sys.modules[name] = module + spec.loader.exec_module(module) + return module + + +def _soc_context(store=None): + """What the page runtime hands a SOC page's handlers: the data service as ``ctx.services.soc``.""" + store = store or _fresh_soc_store() + return SimpleNamespace(services=SimpleNamespace(soc=store.page_service())) + + def _load_dashboard_handlers(): handler_path = ( Path(__file__).resolve().parents[2] @@ -305,6 +329,8 @@ def _load_dashboard_handlers(): spec.loader.exec_module(module) finally: sys.dont_write_bytecode = previous + module._soc_context = _soc_context() + module._bind(module._soc_context) return module @@ -329,6 +355,8 @@ def _load_overview_handlers(): spec.loader.exec_module(module) finally: sys.dont_write_bytecode = previous + module._soc_context = _soc_context() + module._bind(module._soc_context) return module @@ -395,10 +423,10 @@ def test_soc_dashboard_migrates_legacy_alert_records_schema(tmp_path: Path): conn.commit() handlers = _load_dashboard_handlers() - handlers.DEFAULT_SQLITE_DB = db_path - handlers._schema_ready.clear() + handlers._store._paths.SOC_DB = db_path + handlers._store._schema_ready.clear() - assert handlers._ensure_sqlite_schema() is True + assert handlers._store.ensure_schema() is True second_record = { "_source_type": "hids", @@ -414,8 +442,8 @@ def test_soc_dashboard_migrates_legacy_alert_records_schema(tmp_path: Path): ) conn.commit() - handlers._schema_ready.clear() - assert handlers._ensure_sqlite_schema() is True + handlers._store._schema_ready.clear() + assert handlers._store.ensure_schema() is True updated_first_record = { **first_record, @@ -582,11 +610,11 @@ def test_soc_dashboard_triage_outcomes_partition_records(tmp_path: Path): conn.commit() handlers = _load_dashboard_handlers() - handlers.DEFAULT_SQLITE_DB = db_path - handlers._schema_ready.clear() + handlers._store._paths.SOC_DB = db_path + handlers._store._schema_ready.clear() - assert handlers._ensure_sqlite_schema() is True - sources = handlers._find_sqlite_sources( + assert handlers._store.ensure_schema() is True + sources = handlers._store.find_sources( asset_date, asset_date, 1784014800, @@ -595,9 +623,9 @@ def test_soc_dashboard_triage_outcomes_partition_records(tmp_path: Path): triage = handlers._read_triage(sources) closed_loop = handlers._build_closed_loop(triage) with sqlite3.connect(db_path) as conn: - timeline = handlers._sqlite_timeline( + timeline = handlers._store._sqlite_timeline( conn, - handlers._sqlite_settings(), + handlers._store._settings(), "asset_date = ? AND event_time BETWEEN ? AND ?", [asset_date, 1784014800, 1784014800 + len(records)], [asset_date], @@ -640,10 +668,10 @@ def test_soc_dashboard_triage_outcomes_partition_records(tmp_path: Path): assert sum(timeline["attack"]) == triage["attackTotal"] overview_handlers = _load_overview_handlers() - overview_handlers.DEFAULT_SQLITE_DB = db_path + overview_handlers._store._paths.SOC_DB = db_path overview_triage = overview_handlers._read_triage( [ - overview_handlers._RecordSource( + overview_handlers._store.RecordSource( path=db_path, role="triage", date=asset_date, @@ -735,8 +763,8 @@ def test_soc_overview_keeps_threat_names_and_types_separate(tmp_path: Path): conn.commit() handlers = _load_overview_handlers() - handlers.DEFAULT_SQLITE_DB = db_path - source = handlers._RecordSource( + handlers._store._paths.SOC_DB = db_path + source = handlers._store.RecordSource( path=db_path, role="denoise", date=asset_date, @@ -770,8 +798,8 @@ def _overview_alert_store(db_path: Path, asset_date: str, records: list[dict], s def _overview_stats(db_path: Path, monkeypatch: pytest.MonkeyPatch, date: str) -> dict: handlers = _load_overview_handlers() monkeypatch.setenv("FLOCKS_SOC_ALERTS_SQLITE_DB", str(db_path)) - monkeypatch.setattr(handlers, "WORKFLOW_DB", db_path.parent / "no-workflow.db") - return handlers.get_stats(SimpleNamespace(), SimpleNamespace(query_params={"date": date})) + monkeypatch.setattr(handlers._store._paths, "WORKFLOW_DB", db_path.parent / "no-workflow.db") + return handlers.get_stats(handlers._soc_context, SimpleNamespace(query_params={"date": date})) def test_soc_overview_reports_the_model_verdicts_instead_of_estimating_them( @@ -855,13 +883,13 @@ def test_soc_dashboard_holds_the_write_lock_while_its_triggers_are_down(tmp_path ) conn.commit() handlers = _load_dashboard_handlers() - handlers.DEFAULT_SQLITE_DB = db_path - handlers._schema_ready.clear() - assert handlers._ensure_sqlite_schema() is True - handlers._schema_ready.clear() # a restart: same schema version, the triggers are replaced again + handlers._store._paths.SOC_DB = db_path + handlers._store._schema_ready.clear() + assert handlers._store.ensure_schema() is True + handlers._store._schema_ready.clear() # a restart: same schema version, the triggers are replaced again seen = {} - real_drop = handlers._drop_dashboard_triggers + real_drop = handlers._store._drop_dashboard_triggers def drop_then_another_writer(conn): real_drop(conn) @@ -878,8 +906,8 @@ def drop_then_another_writer(conn): finally: other.close() - monkeypatch.setattr(handlers, "_drop_dashboard_triggers", drop_then_another_writer) - assert handlers._ensure_sqlite_schema() is True + monkeypatch.setattr(handlers._store, "_drop_dashboard_triggers", drop_then_another_writer) + assert handlers._store.ensure_schema() is True with sqlite3.connect(db_path) as conn: alerts = conn.execute("SELECT COUNT(*) FROM alert_records").fetchone()[0] @@ -938,11 +966,11 @@ def authorizer(action, name, *_): return connection handlers = _load_dashboard_handlers() - handlers.DEFAULT_SQLITE_DB = db_path - handlers._schema_ready.clear() + handlers._store._paths.SOC_DB = db_path + handlers._store._schema_ready.clear() with monkeypatch.context() as patch: patch.setattr(sqlite3, "connect", connect) - assert handlers._ensure_sqlite_schema() is True + assert handlers._store.ensure_schema() is True with sqlite3.connect(db_path) as conn: facts = conn.execute( @@ -975,7 +1003,7 @@ def test_soc_dashboard_activity_does_not_mix_name_type_or_risk_fields(): ), } - event = handlers._activity_event(row) + event = handlers._store._activity_event(row) assert event["alert"]["threatName"] == "未知告警" assert event["alert"]["threatType"] == "web_attack" @@ -1077,13 +1105,16 @@ def test_every_soc_entry_reads_an_attack_outcome_the_same_way(record, expected): """Alerts page, posture dashboard (Python and SQL), overview and the query tool (Python and SQL).""" dashboard = _load_dashboard_handlers() query_tool = _load_workspace_query_tool() + # The SQL readings are the platform's now: the dashboard's facts and the query tool's search. + from flocks.workflow.soc_store import alerts as alert_store + with sqlite3.connect(":memory:") as conn: conn.execute("CREATE TABLE alert_records (record_json TEXT NOT NULL)") conn.execute("INSERT INTO alert_records VALUES (?)", (json.dumps(record),)) dashboard_sql = conn.execute( - f"SELECT {dashboard._fact_expressions('source')[-1]} FROM alert_records AS source" + f"SELECT {dashboard._store._fact_expressions('source')[-1]} FROM alert_records AS source" ).fetchone()[0] - query_sql = conn.execute(f"SELECT {query_tool.ATTACK_RESULT_SQL} FROM alert_records").fetchone()[0] + query_sql = conn.execute(f"SELECT {alert_store.ATTACK_RESULT_SQL} FROM alert_records").fetchone()[0] readings = { "alerts": _load_alert_operations()._triage_attack_success(record), @@ -1114,11 +1145,11 @@ def test_soc_dashboard_activity_exposes_live_denoise_workflow_progress(tmp_path: conn.commit() handlers = _load_dashboard_handlers() - handlers.WORKFLOW_DB = workflow_db - handlers.DEFAULT_SQLITE_DB = tmp_path / "missing-soc.db" - handlers._activity_pruned_at = float("inf") + handlers._store._paths.WORKFLOW_DB = workflow_db + handlers._store._paths.SOC_DB = tmp_path / "missing-soc.db" + handlers._store._activity_pruned_at = float("inf") - payload = handlers._get_activity({"bootstrap": "latest"}) + payload = handlers._store.activity({"bootstrap": "latest"}) assert payload["workflowStats"] == {"callCount": 42, "latestStartedAt": 0} assert payload["workflowEvents"] == [] @@ -1131,7 +1162,7 @@ def test_soc_dashboard_activity_exposes_live_denoise_workflow_progress(tmp_path: ) conn.commit() - assert handlers._get_activity({"bootstrap": "latest"})["workflowStats"] == { + assert handlers._store.activity({"bootstrap": "latest"})["workflowStats"] == { "callCount": 43, "latestStartedAt": 0, } @@ -1180,11 +1211,11 @@ def test_soc_dashboard_activity_exposes_triage_workflow_link_context(tmp_path: P conn.commit() handlers = _load_dashboard_handlers() - handlers.WORKFLOW_DB = workflow_db - handlers.DEFAULT_SQLITE_DB = tmp_path / "missing-soc.db" - handlers._activity_pruned_at = float("inf") + handlers._store._paths.WORKFLOW_DB = workflow_db + handlers._store._paths.SOC_DB = tmp_path / "missing-soc.db" + handlers._store._activity_pruned_at = float("inf") - payload = handlers._get_activity({"bootstrap": "latest"}) + payload = handlers._store.activity({"bootstrap": "latest"}) triage_events = [ event for event in payload["workflowEvents"] if event["workflowId"] == "stream_alert_triage" @@ -1233,11 +1264,11 @@ def test_soc_dashboard_activity_tolerates_empty_soc_db_with_workflow_events(tmp_ conn.commit() handlers = _load_dashboard_handlers() - handlers.DEFAULT_SQLITE_DB = soc_db - handlers.WORKFLOW_DB = workflow_db - handlers._activity_pruned_at = float("inf") + handlers._store._paths.SOC_DB = soc_db + handlers._store._paths.WORKFLOW_DB = workflow_db + handlers._store._activity_pruned_at = float("inf") - payload = handlers._get_activity({"bootstrap": "latest"}) + payload = handlers._store.activity({"bootstrap": "latest"}) assert "error" not in payload assert payload["workflowEvents"][0]["alert"]["threatName"] == "Mock 研判" @@ -1515,10 +1546,10 @@ def test_soc_dashboard_task_center_summarizes_tasks_and_workflows(tmp_path: Path conn.commit() handlers = _load_dashboard_handlers() - handlers.TASK_DB = tasks_db - handlers.WORKFLOW_DB = workflow_db + handlers._store._paths.TASK_DB = tasks_db + handlers._store._paths.WORKFLOW_DB = workflow_db monkeypatch.setattr( - handlers, + handlers._store, "_workflow_node_count", lambda workflow_id: 4 if workflow_id == "stream_alert_triage" else 1, ) @@ -1607,8 +1638,8 @@ def test_soc_dashboard_task_center_hides_mock_pinned_workflows_by_default(tmp_pa conn.commit() handlers = _load_dashboard_handlers() - handlers.TASK_DB = tmp_path / "missing-tasks.db" - handlers.WORKFLOW_DB = workflow_db + handlers._store._paths.TASK_DB = tmp_path / "missing-tasks.db" + handlers._store._paths.WORKFLOW_DB = workflow_db payload = handlers._get_task_center() assert payload["workflows"] == [] @@ -1623,8 +1654,8 @@ def test_soc_dashboard_task_center_hides_mock_pinned_workflows_by_default(tmp_pa def test_soc_dashboard_token_usage_uses_grouped_cached_reads(tmp_path: Path, monkeypatch): handlers = _load_dashboard_handlers() usage_db = tmp_path / "flocks.db" - handlers.USAGE_DB = usage_db - handlers._token_usage_cache.update({"updatedAt": 0.0, "mtimeNs": 0, "value": None}) + handlers._store._paths.USAGE_DB = usage_db + handlers._store._token_usage_cache.update({"updatedAt": 0.0, "mtimeNs": 0, "value": None}) now = datetime.now().astimezone().replace(hour=10, minute=0, second=0, microsecond=0) yesterday = now - timedelta(days=1) @@ -1633,14 +1664,14 @@ def test_soc_dashboard_token_usage_uses_grouped_cached_reads(tmp_path: Path, mon conn.executemany( "INSERT INTO usage_records VALUES (?, ?)", [ - (handlers._usage_iso(now), 10), - (handlers._usage_iso(now + timedelta(minutes=5)), 15), - (handlers._usage_iso(yesterday), 7), + (handlers._store._usage_iso(now), 10), + (handlers._store._usage_iso(now + timedelta(minutes=5)), 15), + (handlers._store._usage_iso(yesterday), 7), ], ) conn.commit() - first = handlers._read_token_usage() + first = handlers._store.token_usage() assert first["totalTokens"] == 32 assert first["todayTokens"] == 25 @@ -1651,8 +1682,8 @@ def test_soc_dashboard_token_usage_uses_grouped_cached_reads(tmp_path: Path, mon def fail_connect(*args, **kwargs): raise AssertionError("token usage should be served from cache") - monkeypatch.setattr(handlers.sqlite3, "connect", fail_connect) - assert handlers._read_token_usage() == first + monkeypatch.setattr(handlers._store.sqlite3, "connect", fail_connect) + assert handlers._store.token_usage() == first def test_soc_dashboard_task_center_supports_legacy_workflow_execution_schema(tmp_path: Path): @@ -1696,8 +1727,8 @@ def test_soc_dashboard_task_center_supports_legacy_workflow_execution_schema(tmp conn.commit() handlers = _load_dashboard_handlers() - handlers.TASK_DB = tmp_path / "missing-tasks.db" - handlers.WORKFLOW_DB = workflow_db + handlers._store._paths.TASK_DB = tmp_path / "missing-tasks.db" + handlers._store._paths.WORKFLOW_DB = workflow_db payload = handlers._get_task_center() @@ -1782,8 +1813,8 @@ def test_soc_dashboard_task_center_ignores_disabled_trigger_workflow_runs(tmp_pa conn.commit() handlers = _load_dashboard_handlers() - handlers.TASK_DB = tmp_path / "missing-tasks.db" - handlers.WORKFLOW_DB = workflow_db + handlers._store._paths.TASK_DB = tmp_path / "missing-tasks.db" + handlers._store._paths.WORKFLOW_DB = workflow_db payload = handlers._get_task_center() @@ -1890,8 +1921,8 @@ def test_soc_dashboard_task_center_uses_trigger_runtime_window_for_active_workfl conn.commit() handlers = _load_dashboard_handlers() - handlers.TASK_DB = tmp_path / "missing-tasks.db" - handlers.WORKFLOW_DB = workflow_db + handlers._store._paths.TASK_DB = tmp_path / "missing-tasks.db" + handlers._store._paths.WORKFLOW_DB = workflow_db payload = handlers._get_task_center() @@ -1949,8 +1980,8 @@ def test_soc_dashboard_task_center_marks_stale_running_without_trigger_config(tm conn.commit() handlers = _load_dashboard_handlers() - handlers.TASK_DB = tmp_path / "missing-tasks.db" - handlers.WORKFLOW_DB = workflow_db + handlers._store._paths.TASK_DB = tmp_path / "missing-tasks.db" + handlers._store._paths.WORKFLOW_DB = workflow_db payload = handlers._get_task_center() @@ -2124,8 +2155,8 @@ def test_soc_dashboard_task_center_orders_dynamic_rows(tmp_path: Path): conn.commit() handlers = _load_dashboard_handlers() - handlers.TASK_DB = tasks_db - handlers.WORKFLOW_DB = workflow_db + handlers._store._paths.TASK_DB = tasks_db + handlers._store._paths.WORKFLOW_DB = workflow_db payload = handlers._get_task_center() @@ -2144,9 +2175,9 @@ def test_soc_dashboard_task_center_orders_dynamic_rows(tmp_path: Path): def test_soc_dashboard_workflow_progress_marks_unavailable_database(tmp_path: Path): handlers = _load_dashboard_handlers() - handlers.WORKFLOW_DB = tmp_path / "missing-workflow.db" + handlers._store._paths.WORKFLOW_DB = tmp_path / "missing-workflow.db" - assert handlers._get_workflow_progress("stream_alert_denoise") == { + assert handlers._store.workflow_progress("stream_alert_denoise") == { "callCount": None, "latestStartedAt": None, } @@ -2165,7 +2196,7 @@ def test_soc_dashboard_corrects_legacy_single_alert_duplicate_metrics(): "is_duplicate": True, } - metrics = handlers._workflow_execution_metrics(json.dumps(output)) + metrics = handlers._store._workflow_execution_metrics(json.dumps(output)) assert metrics["uniqueCount"] == 0 assert metrics["duplicateCount"] == 1 @@ -2173,7 +2204,7 @@ def test_soc_dashboard_corrects_legacy_single_alert_duplicate_metrics(): assert metrics["reductionRate"] == 1 assert metrics["dedupRate"] == 1 - flag_only_metrics = handlers._workflow_execution_metrics( + flag_only_metrics = handlers._store._workflow_execution_metrics( json.dumps({"is_duplicate": True}) ) @@ -2184,7 +2215,7 @@ def test_soc_dashboard_corrects_legacy_single_alert_duplicate_metrics(): assert flag_only_metrics["reductionRate"] == 1 output["is_duplicate"] = False - first_seen_metrics = handlers._workflow_execution_metrics(json.dumps(output)) + first_seen_metrics = handlers._store._workflow_execution_metrics(json.dumps(output)) assert first_seen_metrics["uniqueCount"] == 1 assert first_seen_metrics["duplicateCount"] == 0 @@ -2197,7 +2228,7 @@ def test_soc_dashboard_corrects_legacy_single_alert_duplicate_metrics(): after_filter_count=2, after_dedup_count=2, ) - batch_metrics = handlers._workflow_execution_metrics(json.dumps(output)) + batch_metrics = handlers._store._workflow_execution_metrics(json.dumps(output)) assert batch_metrics["uniqueCount"] == 2 assert batch_metrics["duplicateCount"] == 0 @@ -2373,9 +2404,9 @@ def insert_execution( conn.commit() handlers = _load_dashboard_handlers() - handlers.DEFAULT_SQLITE_DB = soc_db - handlers.WORKFLOW_DB = workflow_db - handlers._schema_ready.clear() + handlers._store._paths.SOC_DB = soc_db + handlers._store._paths.WORKFLOW_DB = workflow_db + handlers._store._schema_ready.clear() stats = handlers._get_stats( {"startTime": str(start_time), "endTime": str(end_time), "force": "1"} @@ -2411,7 +2442,7 @@ def insert_execution( "other": 0, } - activity = handlers._get_activity( + activity = handlers._store.activity( { "bootstrap": "latest", "startTime": str(start_time), @@ -2427,7 +2458,7 @@ def insert_execution( "降噪批次 · 数量未提供", ] - events = handlers._get_workflow_recent_events( + events = handlers._store.workflow_recent_events( "stream_alert_denoise", start_time, end_time, diff --git a/tests/hub/test_soc_suite_store_clients.py b/tests/hub/test_soc_suite_store_clients.py new file mode 100644 index 000000000..9fd22699c --- /dev/null +++ b/tests/hub/test_soc_suite_store_clients.py @@ -0,0 +1,197 @@ +"""The alert operations suite's files hold no database code: they go through flocks.workflow.soc_store. + +One set of files serves every database backend. A backend replaces +``flocks.workflow.soc_store`` (flocks.db_backend.REPLACEABLE_MODULES); the +suite's five database clients must therefore reach their data only through +that package, and say so with the marker a deployment tool recognises them by. +""" + +from __future__ import annotations + +import ast +import json +from pathlib import Path +from types import SimpleNamespace + +import pytest + +PLUGINS = Path(__file__).resolve().parents[2] / ".flocks" / "flockshub" / "plugins" + +#: The suite's five database clients, by the kind a deployment tool knows them as. +CLIENTS = { + "workflow": PLUGINS / "workflows" / "stream_alert_triage" / "workflow.json", + "query": PLUGINS / "tools" / "python" / "soc_workspace_query" / "soc_workspace_query.py", + "dashboard": PLUGINS / "webuis" / "soc_ui" / "soc_dashboard" / "api" / "handlers.py", + "overview": PLUGINS / "webuis" / "soc_ui" / "soc_overview" / "api" / "handlers.py", + "contract": PLUGINS / "webuis" / "soc_ui" / "access" / "soc_alerts_operations.py", +} + +#: What marks a file as a client of the platform's SOC store, whatever its content otherwise is. +MARKER = "flocks-soc-store-client" + +#: What a file that reached a database itself would contain. +DATABASE_CODE = ( + "sqlite", "soc.db", "postgres", "psycopg", "asyncpg", "json_extract", "pragma ", + "alert_records", "insert into", "create table", "select count", " from workflow_", ".connect(", +) + + +@pytest.mark.parametrize("kind", sorted(CLIENTS)) +def test_client_is_marked_and_holds_no_database_code(kind: str) -> None: + text = CLIENTS[kind].read_text(encoding="utf-8") + + assert MARKER in text + lowered = text.lower() + assert [needle for needle in DATABASE_CODE if needle in lowered] == [] + + +@pytest.mark.parametrize("kind", ["query", "dashboard", "overview", "contract"]) +def test_python_client_imports_no_database_driver(kind: str) -> None: + tree = ast.parse(CLIENTS[kind].read_text(encoding="utf-8")) + imported = set() + for node in ast.walk(tree): + if isinstance(node, ast.Import): + imported.update(alias.name.split(".")[0] for alias in node.names) + elif isinstance(node, ast.ImportFrom) and node.module: + imported.add(node.module) + + assert not imported & {"sqlite3", "psycopg", "asyncpg", "flocks.db", "flocks.db.sync_query"} + + +def test_workflow_writes_only_through_the_soc_service() -> None: + workflow = json.loads(CLIENTS["workflow"].read_text(encoding="utf-8")) + code = next(node["code"] for node in workflow["nodes"] if node["id"] == "concurrent_triage") + tree = ast.parse(code) + writes = [ + node for node in ast.walk(tree) + if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) + and isinstance(node.func.value, ast.Name) and node.func.value.id == "soc" + ] + + assert [call.func.attr for call in writes] == ["write_alerts"] + assert "import sqlite3" not in code + + +def test_soc_store_is_a_module_a_database_backend_replaces() -> None: + from flocks import db_backend + from flocks.workflow import soc_store + + assert "flocks.workflow.soc_store" in db_backend.REPLACEABLE_MODULES + assert soc_store.BACKEND == "sqlite" + # What every implementation of the package answers to. + for name in ("ensure_schema", "persist_triage_alerts", "SOCWriteCapability", "page_service", + "MAX_ALERT_ROWS", "MAX_ALERT_BYTES"): + assert hasattr(soc_store, name), name + service = soc_store.page_service() + for name in ("ensure_schema", "find_sources", "available_dates", "read_denoise", "read_triage", "iter_records", + "workflow_denoise_stats", "workflow_progress", "workflow_recent_events", "token_usage", + "task_center_tasks", "task_center_workflows", "activity", "source_status"): + assert callable(getattr(service.dashboard, name)), name + for name in ("settings", "source_status", "find_sources", "available_dates", "iter_records", "workflow_call_count"): + assert callable(getattr(service.overview, name)), name + from flocks.workflow.soc_store import alerts + + for name in ("search", "record_fields", "latest_date", "source_info", "workflow_runs", "contract_source"): + assert callable(getattr(alerts, name)), name + assert alerts.FILTER_FIELDS + + +def test_page_runtime_hands_pages_the_soc_service() -> None: + from flocks.contracts.webui.api_runtime import WebUIPageApiRuntime + from flocks.workflow.soc_store import dashboard, overview + + ctx = WebUIPageApiRuntime()._create_context("soc-dashboard", None) + + assert ctx.services.soc.dashboard is dashboard + assert ctx.services.soc.overview is overview + assert ctx.database is None + + +def test_page_runtime_tolerates_a_backend_without_page_services(monkeypatch: pytest.MonkeyPatch) -> None: + """A backend's coordination module written before pages were handed services has no such function.""" + from flocks import coordination + from flocks.contracts.webui.api_runtime import WebUIPageApiRuntime + + monkeypatch.delattr(coordination, "page_api_services") + + ctx = WebUIPageApiRuntime()._create_context("soc-dashboard", None) + + assert vars(ctx.services) == {} + + +@pytest.mark.parametrize("page", ["soc_dashboard", "soc_overview"]) +def test_page_handlers_say_what_is_missing_on_a_platform_without_the_service( + page: str, monkeypatch: pytest.MonkeyPatch, +) -> None: + """Installed on an older Flocks, a page explains itself instead of failing on a missing attribute.""" + import builtins + import importlib.util + + path = PLUGINS / "webuis" / "soc_ui" / page / "api" / "handlers.py" + spec = importlib.util.spec_from_file_location(f"soc_missing_service_{page}", path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + real_import = builtins.__import__ + + def no_soc_store(name, globals=None, locals=None, fromlist=(), level=0): + if name == "flocks.workflow" and "soc_store" in (fromlist or ()): + raise ImportError("No module named 'flocks.workflow.soc_store'") + return real_import(name, globals, locals, fromlist, level) + + monkeypatch.setattr(builtins, "__import__", no_soc_store) + + with pytest.raises(RuntimeError, match="update Flocks"): + module.get_stats(SimpleNamespace(), SimpleNamespace(query_params={})) + + +def test_contract_names_the_platform_alert_store_and_no_file() -> None: + import importlib.util + + from flocks.contracts.access.driver import SOC_ALERTS_ADAPTER_KIND + + spec = importlib.util.spec_from_file_location("soc_contract_binding_test", CLIENTS["contract"]) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + + binding = module._BindingResolver().resolve( + page_id="soc-alerts", slot_id="main", contract_id=module.CONTRACT_ID, contract_version=module.CONTRACT_VERSION, + ) + + assert binding.adapter_kind == SOC_ALERTS_ADAPTER_KIND == "builtin-soc-alerts" + assert binding.driver_allowlist_roots == () + assert not binding.source_root.is_absolute() + assert set(binding.driver_options) == {"settings", "settingsDir", "facetFields"} + + +def test_dashboard_names_workflows_from_the_release_when_the_installation_has_none( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + """The dashboard's queries moved out of the page's directory: what they read beside it must not have moved with them. + + A workflow that ran here but is not installed (any more) is still named, + and its steps counted, from the manifest the release bundles. + """ + monkeypatch.setenv("HOME", str(tmp_path / "home")) + monkeypatch.setenv("FLOCKS_ROOT", str(tmp_path / "root")) + monkeypatch.setenv("FLOCKS_WORKSPACE_DIR", str(tmp_path / "workspace")) + monkeypatch.delenv("FLOCKS_HUB_ROOT", raising=False) + from flocks.workflow.soc_store import _paths, dashboard + + bundled = PLUGINS / "workflows" + roots = _paths.workflow_roots() + assert roots[-1].resolve() == bundled.resolve() + assert all(tmp_path in root.parents for root in roots[:-1]), roots + nodes = json.loads((bundled / "stream_alert_triage" / "workflow.json").read_text(encoding="utf-8"))["nodes"] + assert dashboard._workflow_node_count("stream_alert_triage") == len(nodes) > 0 + manifest = json.loads((bundled / "stream_alert_triage" / "manifest.json").read_text(encoding="utf-8")) + assert dashboard._workflow_manifest_name_map()["stream_alert_triage"] in { + manifest.get("nameCn"), manifest.get("name"), (manifest.get("nameI18n") or {}).get("zh-CN"), + } + + # The installation's own copy is the one that counts once it is there. + installed = roots[0] / "stream_alert_triage" + installed.mkdir(parents=True) + (installed / "manifest.json").write_text(json.dumps({"name": "本机改名的研判"}), encoding="utf-8") + (installed / "workflow.json").write_text(json.dumps({"nodes": [{"id": "only"}]}), encoding="utf-8") + assert dashboard._workflow_manifest_name_map()["stream_alert_triage"] == "本机改名的研判" + assert dashboard._workflow_node_count("stream_alert_triage") == 1 diff --git a/tests/hub/test_soc_workspace_query.py b/tests/hub/test_soc_workspace_query.py index 77e020871..f52c70d90 100644 --- a/tests/hub/test_soc_workspace_query.py +++ b/tests/hub/test_soc_workspace_query.py @@ -22,8 +22,13 @@ def workspace_tool(tmp_path, monkeypatch): module = importlib.util.module_from_spec(spec) monkeypatch.setitem(sys.modules, spec.name, module) spec.loader.exec_module(module) + # The tool holds no database code: it reads through the platform's SOC store. + from flocks.workflow.soc_store import _paths + module.SOC_DB = tmp_path / "soc.db" module.WORKFLOW_DB = tmp_path / "workflow.db" + monkeypatch.setattr(_paths, "SOC_DB", module.SOC_DB) + monkeypatch.setattr(_paths, "WORKFLOW_DB", module.WORKFLOW_DB) return module @@ -129,7 +134,7 @@ def test_unreadable_time_filters_are_rejected(workspace_tool, bad): with pytest.raises(ValueError, match="startTime"): workspace_tool._page_query_params({"startTime": bad}) with pytest.raises(ValueError, match="startTime"): - workspace_tool._alert_where({"startTime": bad}) + workspace_tool._alert_criteria({"startTime": bad}) def test_numeric_json_fields_filter_like_their_text(workspace_tool, soc_time_rows): @@ -147,7 +152,7 @@ def test_numeric_json_fields_filter_like_their_text(workspace_tool, soc_time_row async def test_the_dashboard_page_answers_through_the_tool(workspace_tool, monkeypatch): - """The dashboard's handler is a coroutine function: the tool must wait for it.""" + """The tool hands the page's handler the SOC data service the page runtime would.""" from flocks.tool.registry import ToolContext monkeypatch.setattr( @@ -157,3 +162,31 @@ async def test_the_dashboard_page_answers_through_the_tool(workspace_tool, monke assert result.success, result.error payload = json.loads(result.output) if isinstance(result.output, str) else result.output assert payload["page"] == "dashboard" and "error" not in payload + + +async def test_the_tool_asks_the_store_nothing_on_the_event_loop(workspace_tool, soc_time_rows, monkeypatch): + """A store may be a database whose synchronous queries refuse the event loop (PostgreSQL's do).""" + import asyncio + + from flocks.tool.registry import ToolContext + + store = workspace_tool._alert_store() + + def off_the_loop(function): + def call(*args, **kwargs): + try: + asyncio.get_running_loop() + except RuntimeError: + return function(*args, **kwargs) + raise AssertionError(f"{function.__name__} was called on the event loop") + + return call + + for name in ("search", "source_info", "record_fields", "latest_date", "workflow_runs"): + monkeypatch.setattr(store, name, off_the_loop(getattr(store, name))) + + result = await workspace_tool.soc_workspace_query(ToolContext(session_id="s", message_id="m"), page="alerts") + + assert result.success, result.error + assert result.metadata["soc_db"] == str(workspace_tool.SOC_DB) + assert result.metadata["workflow_db"] == str(workspace_tool.WORKFLOW_DB) diff --git a/tests/hub/test_uninstall_flocks_root_g3b.py b/tests/hub/test_uninstall_flocks_root_g3b.py index 1af7ec431..07eb02f3f 100644 --- a/tests/hub/test_uninstall_flocks_root_g3b.py +++ b/tests/hub/test_uninstall_flocks_root_g3b.py @@ -70,3 +70,106 @@ async def test_uninstall_still_refuses_paths_outside_user_root(isolated_root, tm with pytest.raises(ValueError, match="user-managed install location"): await installer.uninstall_plugin("skill", "foreign") assert elsewhere.exists() + + +@pytest.fixture +def home_project_root(tmp_path, monkeypatch): + """The default layout with the server started from the home directory. + + The instance directory is ``~`` and the flocks root ``~/.flocks``: the + project plugin root ``~/.flocks/plugins`` is the user plugin root itself. + """ + home = tmp_path / "home" + root = home / ".flocks" + (root / "config").mkdir(parents=True) + (root / "data").mkdir() + monkeypatch.setenv("FLOCKS_ROOT", str(root)) + monkeypatch.setenv("HOME", str(home)) + monkeypatch.setattr(local.Instance, "get_directory", staticmethod(lambda: str(home))) + monkeypatch.setattr(local.Config, "get_data_path", staticmethod(lambda: root / "data")) + assert local.install_root("component", "project").resolve() == local.install_root("component", "global").resolve() + return root + + +async def test_uninstall_from_home_directory_instance_is_not_a_project_builtin(home_project_root, monkeypatch): + """v0.21 #6: 场景管理卸载告警运营套件报 "Built-in project Hub plugins cannot be removed".""" + path = _install_skill_under(home_project_root, "home-skill") + + async def _no_refresh(*_a, **_k): + return None + + monkeypatch.setattr(installer, "_refresh_runtime", _no_refresh) + monkeypatch.setattr(installer, "_remove_attached_access_contracts", lambda *_a, **_k: None) + + assert installer._is_project_install_path("skill", path) is False + assert await installer.uninstall_plugin("skill", "home-skill") is True + assert not path.exists() + + +async def test_project_scope_record_in_shared_root_is_still_confined(home_project_root, tmp_path, monkeypatch): + elsewhere = tmp_path / "elsewhere" / "skills" / "foreign" + elsewhere.mkdir(parents=True) + (elsewhere / "SKILL.md").write_text("---\nname: foreign\ndescription: d\n---\n", encoding="utf-8") + local.save_installed_record(InstalledPluginRecord( + id="foreign", type="skill", version="1.0.0", source="x", installedAt=1, enabled=True, + scope="project", installPath=str(elsewhere), + )) + + with pytest.raises(ValueError, match="user-managed install location"): + await installer.uninstall_plugin("skill", "foreign") + assert elsewhere.exists() + + +def test_distinct_project_root_still_protects_shipped_plugins(isolated_root, tmp_path): + shipped = tmp_path / "proj" / ".flocks" / "plugins" / "skills" / "shipped" + shipped.mkdir(parents=True) + assert installer._is_project_install_path("skill", shipped) is True + with pytest.raises(ValueError, match="Built-in project Hub plugins cannot be removed"): + installer._validate_uninstall_target("skill", "shipped", shipped, "global") + + +def _install_webui_under_shared_root(plugin_id: str, *, scope: str) -> tuple[Path, Path]: + page = local.install_dir("webui", plugin_id, "global") + (page / "pages" / "home").mkdir(parents=True) + (page / "pages" / "home" / "page.json").write_text("{}", encoding="utf-8") + access = local.install_root("webui", "global").resolve().parent / "access" / plugin_id + access.mkdir(parents=True) + (access / "contract.py").write_text("# access contract\n", encoding="utf-8") + local.save_installed_record(InstalledPluginRecord( + id=plugin_id, type="webui", version="1.0.0", source="bundled:plugins/webuis/" + plugin_id, + installedAt=1, enabled=True, scope=scope, installPath=str(page), + )) + return page, access + + +@pytest.mark.parametrize("scope", ["project", "global"]) +async def test_shared_root_webui_record_is_removed_with_its_access_contracts(home_project_root, monkeypatch, scope): + # Codex review 20261112-212545-2f33: a "project" record in the shared root used to pass the + # path check, delete the pages and then be refused at the access contracts. + page, access = _install_webui_under_shared_root("shared_ui", scope=scope) + + async def _no_refresh(*_a, **_k): + return None + + monkeypatch.setattr(installer, "_refresh_runtime", _no_refresh) + assert await installer.uninstall_plugin("webui", "shared_ui") is True + assert not page.exists() and not access.exists() + assert local.get_record("webui", "shared_ui") is None + + +async def test_shared_root_webui_is_untouched_when_its_access_contracts_cannot_be_removed(home_project_root, tmp_path, monkeypatch): + page, access = _install_webui_under_shared_root("linked_ui", scope="project") + # A link where the access contracts should be: refused before anything is deleted. + elsewhere = tmp_path / "elsewhere-access" + access.rename(elsewhere) + access.symlink_to(elsewhere, target_is_directory=True) + + async def _no_refresh(*_a, **_k): + return None + + monkeypatch.setattr(installer, "_refresh_runtime", _no_refresh) + with pytest.raises(ValueError, match="escapes"): + await installer.uninstall_plugin("webui", "linked_ui") + assert (page / "pages" / "home" / "page.json").is_file() + assert (elsewhere / "contract.py").is_file() + assert local.get_record("webui", "linked_ui") is not None diff --git a/tests/ingest/test_kafka_delivery.py b/tests/ingest/test_kafka_delivery.py index d6767d9f2..426ca832c 100644 --- a/tests/ingest/test_kafka_delivery.py +++ b/tests/ingest/test_kafka_delivery.py @@ -135,7 +135,7 @@ async def pipeline(monkeypatch): # noqa: ANN001 monkeypatch.setattr(kafka_manager, "_REBALANCE_RECOVERY_DELAY_S", 0.01) async def start( # noqa: ANN202 - broker, *, workers=3, filter_spec=None, reset_policy="earliest", expected_state="running", + broker, *, workers=3, filter_spec=None, reset_policy="earliest", expected_state="running", batchsize=None, batch_timeout_ms=40, ): # noqa: ANN001 monkeypatch.setitem( sys.modules, @@ -167,7 +167,7 @@ async def get_config(*args, **kwargs): # noqa: ANN002, ANN003, ANN202 "type": "kafka", "enabled": True, "mapping": {"kafka_message": "$.body"}, - "inputs": {"tool_context_required": False}, + "inputs": {"tool_context_required": False, **({"_kafka_batching": True, "batchsize": batchsize, "batch_timeout_ms": batch_timeout_ms, "maxparallel": workers} if batchsize is not None else {})}, "concurrency": {"maxParallel": workers, "queueSize": 8}, **({"filter": filter_spec} if filter_spec else {}), }], @@ -423,7 +423,11 @@ async def persist(data): # noqa: ANN001, ANN202 release.set() await eventually(lambda: broker.committed.get(Partition("alerts", 0)) == 1) assert persisted[0]["status"] == "success" - assert executions[0]["inputs"]["_flocks"]["trigger"]["deliveryId"] == "kafka:alerts:0:0" + inputs = executions[0]["inputs"] + assert inputs["_flocks"]["trigger"]["deliveryId"] == "kafka:alerts:0:0" + assert inputs["kafka_message"] == {"partition": 0, "offset": 0} + assert "_kafka_delivery_ids" not in inputs + assert "_kafka_batch_seq" not in inputs @pytest.mark.asyncio @@ -1066,3 +1070,222 @@ async def getone(self): await eventually(lambda: manager.get_consumer_status("delivery-test")["state"] == "failed") assert manager.get_consumer_status("delivery-test")["error_code"] == "fetch_cancelled" assert not broker.commit_attempts + + +@pytest.mark.asyncio +async def test_batch_twenty_is_one_dispatch_and_one_durable_ack(pipeline, monkeypatch): + manager, start = pipeline + broker = Broker([record(0, offset) for offset in range(10000)]) + calls = [] + + async def dispatch(wid, plan, message, key, inputs, **kwargs): + calls.append((message, inputs, kwargs)) + return acknowledge() + + monkeypatch.setattr(manager, "_trigger_workflow", dispatch) + await start(broker, workers=2, batchsize=20, batch_timeout_ms=5000) + await eventually(lambda: broker.committed.get(Partition("alerts", 0)) == 10000, timeout=10) + assert [len(call[0]) for call in calls] == [20] * 500 + assert [call[1]["_kafka_batch_seq"] for call in calls] == list(range(500)) + assert [call[2]["trigger"].inputs["_kafka_batch_seq"] for call in calls] == list(range(500)) + assert len({call[2]["trigger"].inputs["_kafka_batch_generation"] for call in calls}) == 1 + assert len({call[2]["delivery_id"] for call in calls}) == 500 + assert all(call[2]["kafka_metadata"]["batchSize"] == 20 for call in calls) + assert len(broker.commit_attempts) <= 500 + + +@pytest.mark.asyncio +async def test_later_batch_cannot_commit_past_unfinished_first_batch(pipeline, monkeypatch): + manager, start = pipeline + broker = Broker([record(0, offset) for offset in range(40)]) + release = asyncio.Event() + later_done = asyncio.Event() + + async def dispatch(wid, plan, message, *args, **kwargs): + if message[0]["offset"] == 0: + await release.wait() + else: + later_done.set() + return acknowledge() + + monkeypatch.setattr(manager, "_trigger_workflow", dispatch) + await start(broker, workers=2, batchsize=20) + await eventually(later_done.is_set) + assert broker.commit_attempts == [] + release.set() + await eventually(lambda: broker.committed.get(Partition("alerts", 0)) == 40) + assert broker.commit_attempts == [{Partition("alerts", 0): 40}] + + +@pytest.mark.asyncio +async def test_partial_batch_flushes_on_timeout_without_losing_records(pipeline, monkeypatch): + manager, start = pipeline + broker = Broker([record(0, offset) for offset in range(25)]) + sizes = [] + + async def dispatch(wid, plan, message, *args, **kwargs): + sizes.append(len(message)) + return acknowledge() + + monkeypatch.setattr(manager, "_trigger_workflow", dispatch) + await start(broker, workers=2, batchsize=20) + await eventually(lambda: broker.committed.get(Partition("alerts", 0)) == 25) + assert sizes == [20, 5] + + +@pytest.mark.asyncio +async def test_failed_batch_never_commits_its_records(pipeline, monkeypatch): + manager, start = pipeline + broker = Broker([record(0, offset) for offset in range(20)]) + calls = [] + + async def dispatch(wid, plan, message, *args, **kwargs): + calls.append(kwargs["delivery_id"]) + raise RuntimeError("batch persistence failed") + + monkeypatch.setattr(manager, "_trigger_workflow", dispatch) + await start(broker, workers=2, batchsize=20) + await eventually(lambda: manager.get_consumer_status("delivery-test")["state"] == "failed") + assert len(calls) == kafka_manager._DELIVERY_MAX_ATTEMPTS + assert len(set(calls)) == 1 + assert broker.commit_attempts == [] + + +@pytest.mark.asyncio +async def test_backpressure_keeps_full_batches_while_the_broker_has_data(pipeline, monkeypatch): + manager, start = pipeline + broker = Broker([record(0, offset) for offset in range(260)]) + sizes = [] + + async def dispatch(wid, plan, message, *args, **kwargs): + sizes.append(len(message)) + await asyncio.sleep(.06) # Longer than the 40 ms idle-tail timeout. + return acknowledge() + + monkeypatch.setattr(manager, "_trigger_workflow", dispatch) + await start(broker, workers=2, batchsize=20) + await eventually(lambda: broker.committed.get(Partition("alerts", 0)) == 260) + assert sizes == [20] * 13 + + +@pytest.mark.asyncio +async def test_idle_flush_does_not_cancel_a_fetch_that_already_advanced_position(pipeline, monkeypatch): + manager, start = pipeline + broker = Broker([record(0, offset) for offset in range(20)]) + fetch = broker.Consumer.getone + observed = [] + + async def slow_fetch(consumer): + item = await fetch(consumer) + if item.offset == 1: + await asyncio.sleep(.08) # The first record's 40 ms flush expires here. + return item + + async def dispatch(wid, plan, message, *args, **kwargs): + observed.extend(item["offset"] for item in message) + return acknowledge() + + monkeypatch.setattr(broker.Consumer, "getone", slow_fetch) + monkeypatch.setattr(manager, "_trigger_workflow", dispatch) + await start(broker, workers=2, batchsize=20) + await eventually(lambda: broker.committed.get(Partition("alerts", 0)) == 20) + assert sorted(observed) == list(range(20)) + + +@pytest.mark.parametrize("batchsize", [1, 20]) +@pytest.mark.asyncio +async def test_batch_inputs_reach_workflow_and_wait_for_persistence(pipeline, monkeypatch, batchsize): + _, start = pipeline + records = [record(0, 0), record(1, 0), record(0, 1)] + broker = Broker(records) + saving = asyncio.Event() + release = asyncio.Event() + + async def persist(data): + saving.set() + await release.wait() + + executions, persisted = mock_execution(monkeypatch, persist=persist) + await start(broker, workers=1, batchsize=batchsize) + try: + await asyncio.wait_for(saving.wait(), 3) + assert broker.commit_attempts == [] + finally: + release.set() + await eventually(lambda: broker.committed == { + Partition("alerts", 0): 2, Partition("alerts", 1): 1, + }) + assert len(executions) == len(persisted) == (3 if batchsize == 1 else 1) + observed = [] + for sequence, execution in enumerate(executions): + inputs = execution["inputs"] + messages = inputs["kafka_message"] + assert isinstance(messages, list) + assert inputs["_kafka_batch_seq"] == sequence + assert inputs["_kafka_batch_generation"] + assert inputs["_kafka_delivery_ids"] == [ + f"kafka:alerts:{item['partition']}:{item['offset']}" for item in messages + ] + observed.extend(messages) + assert observed == [json.loads(item.value) for item in records] + + +@pytest.mark.asyncio +async def test_record_ids_allow_deduplication_when_replay_regroups_a_partial_batch(pipeline, monkeypatch): + manager, start = pipeline + broker = Broker([record(0, offset) for offset in range(20)]) + original_fetch = broker.Consumer.getone + first_generation = True + effects = [] + seen = set() + + async def fetch(consumer): + item = await original_fetch(consumer) + if first_generation and item.offset == 1: + # Force an idle flush of [0]; restart will fetch [0..19] together. + await asyncio.Event().wait() + return item + + async def persist(data): + if first_generation: + raise RuntimeError("business effects succeeded but persistence failed") + + executions, persisted = mock_execution(monkeypatch, persist=persist) + original_run = kafka_manager.run_workflow + + def run(**kwargs): + inputs = kwargs["inputs"] + messages = inputs["kafka_message"] + identities = inputs["_kafka_delivery_ids"] + assert len(messages) == len(identities) + for message, identity in zip(messages, identities): + if identity not in seen: + effects.append(message["offset"]) + seen.add(identity) + return original_run(**kwargs) + + monkeypatch.setattr(broker.Consumer, "getone", fetch) + monkeypatch.setattr(kafka_manager, "run_workflow", run) + await start(broker, workers=1, batchsize=20) + await eventually(lambda: manager.get_consumer_status("delivery-test")["state"] == "failed") + assert len(executions) == kafka_manager._DELIVERY_MAX_ATTEMPTS + assert all( + execution["inputs"]["kafka_message"] == [{"partition": 0, "offset": 0}] + for execution in executions + ) + first_inputs = executions[0]["inputs"] + assert first_inputs["_kafka_delivery_ids"] == ["kafka:alerts:0:0"] + assert effects == [0] + assert broker.commit_attempts == [] + assert persisted == [] + + first_generation = False + await start(broker, workers=1, batchsize=20) + await eventually(lambda: broker.committed.get(Partition("alerts", 0)) == 20) + replay_inputs = executions[-1]["inputs"] + assert len(replay_inputs["kafka_message"]) == 20 + assert replay_inputs["_kafka_delivery_ids"] == [f"kafka:alerts:0:{offset}" for offset in range(20)] + assert replay_inputs["_kafka_batch_generation"] != first_inputs["_kafka_batch_generation"] + assert replay_inputs["_flocks"]["trigger"]["deliveryId"] != first_inputs["_flocks"]["trigger"]["deliveryId"] + assert effects == list(range(20)) + assert len(persisted) == 1 diff --git a/tests/ingest/test_kafka_manager.py b/tests/ingest/test_kafka_manager.py index 0be7fa2ca..fd44ce752 100644 --- a/tests/ingest/test_kafka_manager.py +++ b/tests/ingest/test_kafka_manager.py @@ -223,6 +223,14 @@ async def _fake_trigger(workflow_id, workflow_json, msg, input_key, producer=Non def test_trigger_concurrency_config_is_honored_with_safety_caps() -> None: + default = TriggerDefinition(type="kafka") + assert kafka_manager._worker_count_for_trigger(default) == 1 + assert kafka_manager._queue_size_for_trigger(default) == 100 + + at_limit = TriggerDefinition(type="kafka", concurrency={"maxParallel": 20, "queueSize": 5000}) + assert kafka_manager._worker_count_for_trigger(at_limit) == 20 + assert kafka_manager._queue_size_for_trigger(at_limit) == 5000 + trigger = TriggerDefinition.model_validate( { "id": "kafka-limited", @@ -240,8 +248,8 @@ def test_trigger_concurrency_config_is_honored_with_safety_caps() -> None: "concurrency": {"maxParallel": 999, "queueSize": 999_999}, } ) - assert kafka_manager._worker_count_for_trigger(oversized) == kafka_manager._MAX_CONCURRENT_EXECUTIONS - assert kafka_manager._queue_size_for_trigger(oversized) == kafka_manager._MAX_QUEUE_SIZE + assert kafka_manager._worker_count_for_trigger(oversized) == 20 + assert kafka_manager._queue_size_for_trigger(oversized) == 5000 @pytest.mark.asyncio diff --git a/tests/ingest/test_syslog_manager_backpressure.py b/tests/ingest/test_syslog_manager_backpressure.py index 29750f055..3c31b5e4c 100644 --- a/tests/ingest/test_syslog_manager_backpressure.py +++ b/tests/ingest/test_syslog_manager_backpressure.py @@ -130,6 +130,14 @@ async def test_bounded_queue_drops_excess_on_full() -> None: def test_trigger_concurrency_config_is_honored_with_safety_caps() -> None: + default = TriggerDefinition(type="syslog") + assert syslog_manager._worker_count_for_trigger(default) == 1 + assert syslog_manager._queue_size_for_trigger(default) == 100 + + at_limit = TriggerDefinition(type="syslog", concurrency={"maxParallel": 20, "queueSize": 5000}) + assert syslog_manager._worker_count_for_trigger(at_limit) == 20 + assert syslog_manager._queue_size_for_trigger(at_limit) == 5000 + trigger = TriggerDefinition.model_validate( { "id": "syslog-limited", @@ -147,8 +155,8 @@ def test_trigger_concurrency_config_is_honored_with_safety_caps() -> None: "concurrency": {"maxParallel": 999, "queueSize": 999_999}, } ) - assert syslog_manager._worker_count_for_trigger(oversized) == syslog_manager._MAX_CONCURRENT_EXECUTIONS - assert syslog_manager._queue_size_for_trigger(oversized) == syslog_manager._MAX_QUEUE_SIZE + assert syslog_manager._worker_count_for_trigger(oversized) == 20 + assert syslog_manager._queue_size_for_trigger(oversized) == 5000 @pytest.mark.asyncio diff --git a/tests/project/test_project_directory_access.py b/tests/project/test_project_directory_access.py new file mode 100644 index 000000000..213802910 --- /dev/null +++ b/tests/project/test_project_directory_access.py @@ -0,0 +1,118 @@ +"""The allowed roots and the service account's access to a project directory. + +They are separate settings an administrator changes (FLOCKS_PROJECT_ROOTS; the +folder's permissions or ACL), so a directory the account running Flocks cannot +reach is reported as such, never as missing, and both are named when both are +missing (INC-61BE1F94). +""" + +import os +from contextlib import contextmanager +from pathlib import Path + +import pytest + +import flocks.project.project as project_module +from flocks.project.project import Project + +posix_permissions = pytest.mark.skipif( + os.name == "nt" or (hasattr(os, "geteuid") and os.geteuid() == 0), + reason="needs POSIX directory permissions enforced for this account", +) + + +@contextmanager +def _mode(path: Path, mode: int): + original = path.stat().st_mode & 0o777 + path.chmod(mode) + try: + yield + finally: + path.chmod(original) + + +@pytest.fixture +def allowed_root(tmp_path, monkeypatch): + root = tmp_path / "allowed" + root.mkdir() + monkeypatch.setenv("FLOCKS_PROJECT_ROOTS", str(root)) + return root + + +@posix_permissions +def test_unreachable_directory_is_not_reported_missing(allowed_root): + parent = allowed_root / "svc-denied" + worktree = parent / "repo" + worktree.mkdir(parents=True) + + with _mode(parent, 0o600): + with pytest.raises(ValueError, match=r"^Project directory is not readable$"): + Project.validate_worktree(str(worktree)) + assert Project._path_status(str(worktree)) == "unreadable" + + +@posix_permissions +def test_missing_root_and_missing_permission_are_both_named(allowed_root, tmp_path): + parent = tmp_path / "elsewhere" + worktree = parent / "repo" + worktree.mkdir(parents=True) + + with _mode(parent, 0o600): + with pytest.raises( + ValueError, + match=r"^Project directory is outside the allowed roots and is not readable$", + ): + Project.validate_worktree(str(worktree)) + with pytest.raises(ValueError, match=r"^Project directory is outside the allowed roots$"): + Project.validate_worktree(str(worktree)) + + +@posix_permissions +def test_creating_under_an_unreachable_parent_is_a_permission_error(allowed_root): + parent = allowed_root / "svc-denied" + parent.mkdir() + + with _mode(parent, 0o600): + with pytest.raises(ValueError, match=r"^Project directory is not readable$"): + Project.validate_worktree(str(parent / "repo"), create_if_missing=True) + assert not (parent / "repo").exists() + + +@posix_permissions +def test_listing_is_checked_where_permission_bits_allow_it(allowed_root, monkeypatch): + """Windows' os.access ignores the ACL that leaves the service account out.""" + + worktree = allowed_root / "acl-denied" + worktree.mkdir() + real_access = os.access + + def access_ignoring_acl(path, mode, *args, **kwargs): + if Path(path) == worktree: + return True + return real_access(path, mode, *args, **kwargs) + + monkeypatch.setattr(project_module.os, "access", access_ignoring_acl) + with _mode(worktree, 0o000): + assert Project._path_status(str(worktree)) == "unreadable" + with pytest.raises(ValueError, match=r"^Project directory is not readable$"): + Project.validate_worktree(str(worktree)) + assert Project._path_status(str(worktree)) == "available" + + +def test_what_did_not_change(allowed_root): + path = allowed_root / "file.txt" + path.write_text("x", encoding="utf-8") + readable = allowed_root / "repo" + readable.mkdir() + + with pytest.raises(ValueError, match=r"^Project path must be a directory$"): + Project.validate_worktree(str(path)) + with pytest.raises(ValueError, match=r"^Project directory does not exist$"): + Project.validate_worktree(str(allowed_root / "absent")) + assert Project.validate_worktree(str(readable)) == os.path.normcase(str(readable.resolve())) + created = allowed_root / "new" / "nested" + assert Project.validate_worktree(str(created), create_if_missing=True) == os.path.normcase( + str(created.resolve()) + ) + assert Project._path_status(str(readable)) == "available" + assert Project._path_status(str(allowed_root / "absent")) == "missing" diff --git a/tests/provider/test_empty_stream_tool_fallback.py b/tests/provider/test_empty_stream_tool_fallback.py new file mode 100644 index 000000000..51988faff --- /dev/null +++ b/tests/provider/test_empty_stream_tool_fallback.py @@ -0,0 +1,279 @@ +"""An empty streamed answer keeps its tools on the non-streaming fallback. + +The fallback used to keep only ``content``: an answer made of tool calls alone +(content null) counted as empty, and the request was then repeated without its +tools, so an agent such as the code audit's threat modeler was told it had none. +""" + +from types import SimpleNamespace +from unittest.mock import AsyncMock, MagicMock + +import pytest + +from flocks.provider.provider import ChatMessage, ChatResponse +from flocks.provider.sdk.openai_base import OpenAIBaseProvider, chat_fallback_tool_call_chunks +from flocks.provider.sdk.openai_compatible import OpenAICompatibleProvider +from flocks.session.lifecycle.retry import SessionRetry +from flocks.session.streaming.tool_accumulator import ( + StreamToolArgumentsTruncatedError, + ToolCallAccumulator, +) + + +TOOLS = [{"type": "function", "function": {"name": "audit_repository_summary", "parameters": {"type": "object"}}}] +TOOL_CALLS = [{ + "index": 0, + "id": "call_summary", + "type": "function", + "function": {"name": "audit_repository_summary", "arguments": "{}"}, +}] + + +class _BaseProvider(OpenAIBaseProvider): + DEFAULT_BASE_URL = "https://api.custom.com/v1" + ENV_API_KEY = ["CUSTOM_API_KEY"] + ENV_BASE_URL = "CUSTOM_BASE_URL" + CATALOG_ID = "" + + def __init__(self): + super().__init__(provider_id="custom-provider", name="Custom Provider") + + +def _with_client(provider): + create = AsyncMock() + provider._client = MagicMock() + provider._client.chat.completions.create = create + return provider, create + + +async def _empty_stream(): + if False: + yield None + + +def _fallback(*, content="", tool_calls=None, reasoning=None, finish_reason=None, **extra) -> ChatResponse: + return ChatResponse( + id="resp_fallback", + model="deepseek-v4-flash", + content=content, + finish_reason=finish_reason or ("tool_calls" if tool_calls else "stop"), + usage={"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2}, + tool_calls=tool_calls, + reasoning=reasoning, + **extra, + ) + + +PROVIDERS = [ + pytest.param(OpenAICompatibleProvider, id="openai_compatible"), + pytest.param(_BaseProvider, id="openai_base"), +] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("provider_class", PROVIDERS) +async def test_tool_calls_of_the_chat_fallback_reach_the_stream(provider_class): + provider, create = _with_client(provider_class()) + create.return_value = _empty_stream() + provider.chat = AsyncMock(return_value=_fallback(tool_calls=TOOL_CALLS, reasoning="先看仓库概况")) + + chunks = [ + chunk async for chunk in provider.chat_stream( + "deepseek-v4-flash", + [ChatMessage(role="user", content="build the threat model")], + tools=TOOLS, + ) + ] + + assert [chunk.reasoning for chunk in chunks if chunk.event_type == "reasoning"] == ["先看仓库概况"] + terminal = chunks[-1] + assert terminal.tool_calls == TOOL_CALLS + assert terminal.finish_reason == "tool_calls" + provider.chat.assert_awaited_once() + assert provider.chat.await_args.kwargs["tools"] == TOOLS + + +@pytest.mark.asyncio +@pytest.mark.parametrize("provider_class", PROVIDERS) +async def test_a_blank_answer_is_not_retried_without_the_tools(provider_class): + provider, create = _with_client(provider_class()) + create.return_value = _empty_stream() + provider.chat = AsyncMock(return_value=_fallback(content="")) + + # "empty streaming response" is what the session retry treats as transient. + with pytest.raises(ValueError, match="empty streaming response.*tools_declared=True"): + _ = [ + chunk async for chunk in provider.chat_stream( + "deepseek-v4-flash", + [ChatMessage(role="user", content="build the threat model")], + tools=TOOLS, + ) + ] + + provider.chat.assert_awaited_once() + assert provider.chat.await_args.kwargs["tools"] == TOOLS + + +@pytest.mark.asyncio +@pytest.mark.parametrize("provider_class", PROVIDERS) +async def test_chat_returns_the_tool_calls_and_reasoning_of_its_message(provider_class): + provider, create = _with_client(provider_class()) + message = SimpleNamespace( + content=None, + reasoning_content="先看仓库概况", + tool_calls=[SimpleNamespace( + id="call_summary", + function=SimpleNamespace(name="audit_repository_summary", arguments=""), + )], + ) + create.return_value = SimpleNamespace( + id="resp_1", + model="deepseek-v4-flash", + usage=SimpleNamespace(prompt_tokens=1, completion_tokens=1, total_tokens=2), + choices=[SimpleNamespace(finish_reason="tool_calls", message=message)], + ) + + response = await provider.chat( + "deepseek-v4-flash", + [ChatMessage(role="user", content="build the threat model")], + tools=TOOLS, + ) + + assert response.content == "" + assert response.reasoning == "先看仓库概况" + assert response.reasoning_source == "reasoning_content" + # Kept as sent: only the replay decides whether "" means "no parameters". + assert response.tool_calls == [{ + "index": 0, + "id": "call_summary", + "type": "function", + "function": {"name": "audit_repository_summary", "arguments": ""}, + }] + + +class _Events: + session_id = "ses_fallback" + + def __init__(self) -> None: + self.events = [] + + async def process_event(self, event) -> None: + self.events.append(event) + + +async def _accumulate(chunks): + """Feed replayed chunks to the real accumulator, as the runner does.""" + processor = _Events() + accumulator = ToolCallAccumulator(processor) + finish_reason = None + for chunk in chunks: + for call in chunk.tool_calls or []: + await accumulator.feed_chunk(call) + finish_reason = chunk.finish_reason or finish_reason + try: + await accumulator.flush_remaining(finish_reason, output_limit=100, raised_output_limit=200) + except StreamToolArgumentsTruncatedError: + # The runner turns this into a tool error the model can react to. + processor.events.append(SimpleNamespace(truncated=True)) + return [type(event).__name__ for event in processor.events], processor.events + + +@pytest.mark.asyncio +@pytest.mark.parametrize("finish_reason", ["length", "max_tokens"]) +async def test_a_cut_off_fallback_call_is_refused_not_run(finish_reason): + chunks = chat_fallback_tool_call_chunks( + _fallback(tool_calls=[{**TOOL_CALLS[0], "function": {"name": "audit_repository_summary", "arguments": ""}}], + finish_reason=finish_reason), + provider_id="custom-h20", + model_id="deepseek-v4-flash", + ) + + kinds, events = await _accumulate(chunks) + + assert "ToolCallEvent" not in kinds + assert "ToolInputErrorEvent" in kinds + assert getattr(events[-1], "truncated", False) + + +@pytest.mark.asyncio +async def test_a_finished_fallback_call_without_arguments_runs_with_none(): + chunks = chat_fallback_tool_call_chunks( + _fallback(tool_calls=[{**TOOL_CALLS[0], "function": {"name": "audit_repository_summary", "arguments": ""}}]), + provider_id="custom-h20", + model_id="deepseek-v4-flash", + ) + + kinds, events = await _accumulate(chunks) + + calls = [event for event in events if type(event).__name__ == "ToolCallEvent"] + assert [(call.tool_name, call.input) for call in calls] == [("audit_repository_summary", {})] + + +def test_reasoning_details_alone_still_make_a_reasoning_chunk(): + details = [{"type": "reasoning.encrypted", "data": "opaque"}] + + chunks = chat_fallback_tool_call_chunks( + _fallback(tool_calls=TOOL_CALLS, reasoning_details=details), + provider_id="openrouter", + model_id="some-model", + ) + + reasoning = [chunk for chunk in chunks if chunk.event_type == "reasoning"] + assert len(reasoning) == 1 + assert reasoning[0].metadata["reasoningDetails"] == details + + +@pytest.mark.asyncio +async def test_empty_choices_on_the_fallback_are_retried_with_the_tools(): + provider, create = _with_client(OpenAICompatibleProvider()) + create.side_effect = [ + _empty_stream(), + SimpleNamespace(id="resp_empty", model="deepseek-v4-flash", usage=None, choices=[]), + ] + + with pytest.raises(ValueError, match="empty choices") as raised: + _ = [ + chunk async for chunk in provider.chat_stream( + "deepseek-v4-flash", + [ChatMessage(role="user", content="build the threat model")], + tools=TOOLS, + ) + ] + + message = str(raised.value) + assert SessionRetry.retryable({"name": "UnknownError", "message": message, "data": {"message": message}}) + assert create.await_count == 2 + assert all(call.kwargs.get("tools") == TOOLS for call in create.await_args_list) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("provider_class", PROVIDERS) +async def test_a_cut_off_call_from_the_endpoint_is_not_run_through_the_fallback(provider_class): + provider, create = _with_client(provider_class()) + message = SimpleNamespace( + content=None, + tool_calls=[SimpleNamespace( + id="call_summary", + function=SimpleNamespace(name="audit_repository_summary", arguments=""), + )], + ) + create.side_effect = [ + _empty_stream(), + SimpleNamespace( + id="resp_cut", model="deepseek-v4-flash", + usage=SimpleNamespace(prompt_tokens=1, completion_tokens=1, total_tokens=2), + choices=[SimpleNamespace(finish_reason="length", message=message)], + ), + ] + + chunks = [ + chunk async for chunk in provider.chat_stream( + "deepseek-v4-flash", + [ChatMessage(role="user", content="build the threat model")], + tools=TOOLS, + ) + ] + kinds, _events = await _accumulate(chunks) + + assert "ToolCallEvent" not in kinds + assert "ToolInputErrorEvent" in kinds diff --git a/tests/provider/test_model_discovery.py b/tests/provider/test_model_discovery.py index 0df5842c1..5e9ac3677 100644 --- a/tests/provider/test_model_discovery.py +++ b/tests/provider/test_model_discovery.py @@ -14,6 +14,7 @@ from flocks.config.config import Config, ConfigInfo from flocks.config.config_writer import ConfigWriter from flocks.provider.provider import Provider +from tests.provider.tls_helpers import describe_verify, make_ca @pytest.fixture @@ -127,8 +128,8 @@ async def test_id_only_lists_block_known_non_chat_families_without_blocking_audi ("options", "trust_env_var", "expected"), [ ({}, None, {"verify": True, "trust_env": True}), - ({"verify_ssl": False}, None, {"verify": False, "trust_env": True}), - ({"ssl_verify": "false"}, None, {"verify": False, "trust_env": True}), + ({"verify_ssl": False}, None, {"verify": "no-verify", "trust_env": True}), + ({"ssl_verify": "false"}, None, {"verify": "no-verify", "trust_env": True}), ({"trust_env": False}, None, {"verify": True, "trust_env": False}), ({}, "0", {"verify": True, "trust_env": False}), ({"trust_env": True}, "0", {"verify": True, "trust_env": True}), @@ -149,7 +150,91 @@ async def test_discovery_connects_the_way_the_providers_own_client_does( result = await discovery_runtime.module.discover_models("openai-compatible", api_key="key") assert result["status"] == "success" - assert {name: upstream.options[0][name] for name in expected} == expected + assert {name: describe_verify(upstream.options[0][name]) if name == "verify" else upstream.options[0][name] for name in expected} == expected + + +@pytest.mark.asyncio +async def test_unsaved_tls_settings_replace_the_stored_ones(discovery_runtime, upstream): + """A form checks a gateway with SSL settings it has not saved yet.""" + save_provider( + discovery_runtime, "openai-compatible", options={"baseURL": "https://gateway.test/v1", "ssl_verify": False} + ) + + result = await discovery_runtime.module.discover_models("openai-compatible", api_key="key") + assert result["status"] == "success" + assert describe_verify(upstream.options[-1]["verify"]) == "no-verify" + + result = await discovery_runtime.module.discover_models( + "openai-compatible", api_key="key", tls_overrides={"verify_ssl": True} + ) + assert result["status"] == "success" + assert upstream.options[-1]["verify"] is True + + result = await discovery_runtime.module.discover_models( + "openai-compatible", api_key="key", base_url="https://other.test/v1", tls_overrides={"verify_ssl": False} + ) + assert result["status"] == "success" + assert describe_verify(upstream.options[-1]["verify"]) == "no-verify" + + +@pytest.mark.asyncio +@pytest.mark.parametrize("switch_key", ["verify_ssl", "ssl_verify"]) +async def test_sending_only_the_switch_keeps_the_stored_ca_cert(switch_key, discovery_runtime, upstream): + """The edit form sends only what changed: turning the checks back on must not drop the saved CA.""" + import ssl + + import certifi + + ca = make_ca() + save_provider( + discovery_runtime, + "openai-compatible", + options={"baseURL": "https://gateway.test/v1", switch_key: False, "ca_cert": ca.cert_pem}, + ) + + result = await discovery_runtime.module.discover_models( + "openai-compatible", api_key="key", tls_overrides={"verify_ssl": True} + ) + + assert result["status"] == "success" + verify = upstream.options[-1]["verify"] + assert isinstance(verify, ssl.SSLContext) and verify.verify_mode == ssl.CERT_REQUIRED + default_cas = ssl.create_default_context(cafile=certifi.where()).cert_store_stats()["x509_ca"] + assert verify.cert_store_stats()["x509_ca"] == default_cas + 1 + + +@pytest.mark.asyncio +async def test_a_ca_cert_that_does_not_load_is_reported_without_a_request(discovery_runtime, upstream): + save_provider(discovery_runtime, "openai-compatible", options={"baseURL": "https://gateway.test/v1"}) + + result = await discovery_runtime.module.discover_models( + "openai-compatible", api_key="key", tls_overrides={"ca_cert": "relative/ca.pem"} + ) + + assert (result["status"], result["code"]) == ("error", "invalid_ca_cert") + assert "绝对路径" in result["message"] + assert upstream.requests == [] + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("message", "code"), + [ + ("[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self-signed certificate", "tls_certificate_failed"), + ("[SSL: SSLV3_ALERT_HANDSHAKE_FAILURE] ssl/tls alert handshake failure", "tls_handshake_failed"), + ("[Errno 61] Connection refused", "connection_error"), + ], +) +async def test_tls_failures_are_told_apart_from_other_connection_errors(message, code, discovery_runtime, upstream): + save_provider(discovery_runtime, "openai-compatible", options={"baseURL": "https://gateway.test/v1"}) + + def fail(request): + raise httpx.ConnectError(message, request=request) + + upstream.handler = fail + result = await discovery_runtime.module.discover_models("openai-compatible", api_key="key") + + assert (result["status"], result["code"]) == ("error", code) @pytest.mark.asyncio @@ -604,6 +689,27 @@ async def test_non_http_url_is_rejected_without_network(discovery_runtime, upstr assert not upstream.requests +@pytest.mark.asyncio +@pytest.mark.parametrize("base_url", ["http://a..b/v1", "http://" + "x" * 64 + ".example.com/v1"]) +async def test_host_name_the_resolver_cannot_encode_is_an_invalid_url(base_url, discovery_runtime, monkeypatch): + # v0.21 #27: these used to escape the resolver check as UnicodeError and + # answer 500 "Internal server error". The real resolver check runs here + # (the upstream fixture stubs it); the transport only records requests. + requests = [] + real_client = httpx.AsyncClient + + def factory(*args, **kwargs): + kwargs["transport"] = httpx.MockTransport(lambda request: requests.append(request) or httpx.Response(200, json={"data": []})) + return real_client(*args, **kwargs) + + monkeypatch.setattr(discovery_runtime.module.httpx, "AsyncClient", factory) + result = await discovery_runtime.module.discover_models("openai-compatible", api_key="sk-test", base_url=base_url) # secret-guard: allow 误报:测试用假 key + + assert result["status"] == "error" + assert result["code"] == "invalid_base_url" + assert not requests + + @pytest.mark.asyncio async def test_missing_url_and_key_are_distinguished(discovery_runtime, upstream): missing_url = await discovery_runtime.module.discover_models("openai-compatible") diff --git a/tests/provider/test_openai_base_provider.py b/tests/provider/test_openai_base_provider.py index afda5c443..6d0cb2814 100644 --- a/tests/provider/test_openai_base_provider.py +++ b/tests/provider/test_openai_base_provider.py @@ -13,6 +13,8 @@ import httpx import pytest + +from tests.provider.tls_helpers import assert_no_verify_context from openai import AsyncOpenAI import flocks.provider.sdk.openai_base as openai_base_module @@ -501,7 +503,7 @@ def test_get_client_respects_verify_ssl_false(self, mock_async_openai, mock_http # See ``OpenAIBaseProvider._get_client``. assert mock_http_client.call_count == 1 kwargs = mock_http_client.call_args.kwargs - assert kwargs["verify"] is False + assert_no_verify_context(kwargs["verify"]) assert kwargs["trust_env"] is True timeout_arg = kwargs["timeout"] # Either an httpx.Timeout instance or compatible object: assert the diff --git a/tests/provider/test_openai_compatible_provider.py b/tests/provider/test_openai_compatible_provider.py index 1ef5b20cb..70ad6ab73 100644 --- a/tests/provider/test_openai_compatible_provider.py +++ b/tests/provider/test_openai_compatible_provider.py @@ -3,6 +3,8 @@ import pytest +from tests.provider.tls_helpers import assert_no_verify_context + from flocks.provider.provider import ChatMessage, ChatResponse from flocks.provider.provider import ProviderConfig from flocks.provider.sdk.openai_compatible import OpenAICompatibleProvider @@ -52,7 +54,7 @@ def test_get_client_respects_verify_ssl_false(self, mock_async_openai, mock_http # so minor adjustments to non-critical values don't break the test. assert mock_http_client.call_count == 1 kwargs = mock_http_client.call_args.kwargs - assert kwargs["verify"] is False + assert_no_verify_context(kwargs["verify"]) assert kwargs["trust_env"] is True timeout_arg = kwargs["timeout"] assert getattr(timeout_arg, "connect", None) == 30.0 diff --git a/tests/provider/test_openai_provider.py b/tests/provider/test_openai_provider.py index bc671640b..af32e5c9c 100644 --- a/tests/provider/test_openai_provider.py +++ b/tests/provider/test_openai_provider.py @@ -3,6 +3,8 @@ import pytest +from tests.provider.tls_helpers import assert_no_verify_context + from flocks.provider.provider import ChatMessage, ProviderConfig from flocks.provider.sdk.openai import OpenAIProvider @@ -37,7 +39,7 @@ def test_get_client_respects_verify_ssl_false(self, mock_async_openai, mock_http assert mock_http_client.call_count == 1 kwargs = mock_http_client.call_args.kwargs assert kwargs["trust_env"] is True - assert kwargs["verify"] is False + assert_no_verify_context(kwargs["verify"]) timeout_arg = kwargs["timeout"] assert getattr(timeout_arg, "connect", None) == 30.0 assert getattr(timeout_arg, "read", None) == 180.0 diff --git a/tests/provider/test_provider_tls.py b/tests/provider/test_provider_tls.py new file mode 100644 index 000000000..0d3f844f4 --- /dev/null +++ b/tests/provider/test_provider_tls.py @@ -0,0 +1,488 @@ +"""SSL settings of LLM provider clients: ``verify_ssl`` and ``ca_cert`` (flocks.provider.tls). + +The handshake tests run real TLS against a gateway on 127.0.0.1 whose +certificate is made for the test: self-signed, issued by an internal CA, or +offered over RSA key exchange only, as older appliances do. +""" + +from __future__ import annotations + +import json +import ssl +from unittest.mock import MagicMock + +import certifi +import httpx +import pytest + +from flocks.config.config_writer import ConfigWriter +from flocks.provider import tls +from flocks.provider.provider import ChatMessage, Provider, ProviderConfig +from flocks.provider.sdk.anthropic import AnthropicProvider +from flocks.provider.sdk.azure import AzureProvider +from flocks.provider.sdk.openai import OpenAIProvider +from flocks.provider.sdk.openai_compatible import OpenAICompatibleProvider +from tests.provider.tls_helpers import ( + RSA_KEY_EXCHANGE_ONLY, + assert_no_verify_context, + https_gateway, + make_ca, + make_server, +) + + +@pytest.fixture(scope="module") +def internal_ca(): + return make_ca() + + +# --------------------------------------------------------------------------- +# Settings -> httpx ``verify`` +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize("settings", [None, {}, {"verify_ssl": True}, {"verify_ssl": True, "ca_cert": " "}]) +def test_without_settings_httpx_keeps_its_own_checks(settings): + assert tls.httpx_verify(settings) is True + assert tls.has_custom_tls(settings) is False + + +@pytest.mark.parametrize( + "settings", + [ + {"verify_ssl": False}, + {"verify_ssl": "false"}, + {"ssl_verify": 0}, + # The certificate is not used while the checks are off. + {"verify_ssl": False, "ca_cert": "relative/path.pem"}, + ], +) +def test_checks_off_also_accepts_older_handshakes(settings): + context = tls.httpx_verify(settings) + + assert_no_verify_context(context) + assert context.minimum_version == ssl.TLSVersion.MINIMUM_SUPPORTED + assert context.options & ssl.OP_LEGACY_SERVER_CONNECT + cipher_names = {cipher["name"] for cipher in context.get_ciphers()} + assert "AES128-GCM-SHA256" in cipher_names # RSA key exchange, left out by CPython's default list + assert tls.has_custom_tls(settings) is True + + +def test_checks_off_builds_no_deprecated_protocol_setting(): + import warnings + + with warnings.catch_warnings(): + warnings.simplefilter("error", DeprecationWarning) + tls.compat_context() + + +def test_ca_cert_is_trusted_besides_the_default_bundle(internal_ca): + context = tls.httpx_verify({"ca_cert": internal_ca.cert_pem}) + + assert context.verify_mode == ssl.CERT_REQUIRED + assert context.check_hostname is True + default_cas = ssl.create_default_context(cafile=certifi.where()).cert_store_stats()["x509_ca"] + assert context.cert_store_stats()["x509_ca"] == default_cas + 1 + assert context.verify_flags & ssl.VERIFY_X509_PARTIAL_CHAIN + + +def test_ca_cert_path_and_ssl_cert_file_are_both_trusted(internal_ca, tmp_path, monkeypatch): + other_ca = make_ca() + bundle = tmp_path / "system-bundle.pem" + bundle.write_text(other_ca.cert_pem) + ca_file = tmp_path / "corp-ca.pem" + ca_file.write_text(internal_ca.cert_pem) + monkeypatch.setenv("SSL_CERT_FILE", str(bundle)) + monkeypatch.delenv("SSL_CERT_DIR", raising=False) + + context = tls.httpx_verify({"ca_cert": str(ca_file)}) + assert context.cert_store_stats()["x509_ca"] == 2 + + # trust_env off: certifi, as httpx itself does. + context = tls.httpx_verify({"ca_cert": str(ca_file)}, trust_env=False) + default_cas = ssl.create_default_context(cafile=certifi.where()).cert_store_stats()["x509_ca"] + assert context.cert_store_stats()["x509_ca"] == default_cas + 1 + + +@pytest.mark.parametrize( + ("value", "message"), + [ + ("certs/corp-ca.pem", "绝对路径"), + ("/nonexistent/flocks-test/corp-ca.pem", "找不到 CA 证书文件"), + ("-----BEGIN CERTIFICATE-----\nnot base64\n-----END CERTIFICATE-----\n", "无法解析"), + ("-----BEGIN PRIVATE KEY-----\nAAAA\n-----END PRIVATE KEY-----\n", "不要粘贴私钥"), # secret-guard: allow (test value) + ], +) +def test_a_ca_cert_that_does_not_load_is_refused(value, message): + with pytest.raises(tls.CACertError, match=message): + tls.validate_ca_cert(value) + with pytest.raises(tls.CACertError): + tls.httpx_verify({"ca_cert": value}) + + +def test_a_file_without_certificates_is_refused(tmp_path): + empty = tmp_path / "empty.pem" + empty.write_text("# nothing here\n") + with pytest.raises(tls.CACertError): + tls.validate_ca_cert(str(empty)) + + +def test_validate_ca_cert_keeps_good_values(internal_ca, tmp_path): + ca_file = tmp_path / "ca.pem" + ca_file.write_text(internal_ca.cert_pem) + assert tls.validate_ca_cert(None) is None + assert tls.validate_ca_cert(" \n") is None + assert tls.validate_ca_cert("\n" + internal_ca.cert_pem) == internal_ca.cert_pem.strip() + assert tls.validate_ca_cert(f" {ca_file} ") == str(ca_file) + assert tls.validate_ca_cert(str(tmp_path)) == str(tmp_path) # hashed directory, read lazily + + +def test_tls_errors_are_recognised_through_the_wrappers(): + cert_error = ssl.SSLCertVerificationError(1, "[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed") + wrapped = httpx.ConnectError("[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed") + wrapped.__cause__ = cert_error + outer = RuntimeError("Connection error.") + outer.__cause__ = wrapped + assert tls.classify_tls_error(outer) == tls.TLS_CERTIFICATE_FAILED + + handshake = httpx.ConnectError("[SSL: SSLV3_ALERT_HANDSHAKE_FAILURE] ssl/tls alert handshake failure") + assert tls.classify_tls_error(handshake) == tls.TLS_HANDSHAKE_FAILED + assert "TLS 握手失败" in tls.tls_error_hint(handshake) + + assert tls.classify_tls_error(httpx.ConnectError("[Errno 61] Connection refused")) is None + assert tls.tls_error_hint(ValueError("x")) is None + + +# --------------------------------------------------------------------------- +# Real handshakes through the provider clients +# --------------------------------------------------------------------------- + + +def _provider(cls, base_url: str, settings: dict): + provider = cls() + provider.configure( + ProviderConfig(provider_id=provider.id, api_key="sk-test", base_url=base_url, custom_settings=settings) # secret-guard: allow (test value) + ) + return provider + + +async def _ask(provider, *, stream: bool) -> str: + messages = [ChatMessage(role="user", content="capital of France?")] + if stream: + parts = [] + async for chunk in provider.chat_stream("gw-test-model", messages, max_tokens=10): + if getattr(chunk, "delta", None): + parts.append(chunk.delta) + return "".join(parts) + response = await provider.chat("gw-test-model", messages, max_tokens=10) + return response.content + + +PROVIDERS = [OpenAICompatibleProvider, OpenAIProvider] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("provider_cls", PROVIDERS) +@pytest.mark.parametrize("stream", [False, True]) +async def test_checks_off_reach_a_gateway_that_offers_rsa_key_exchange_only(provider_cls, stream, tmp_path): + with https_gateway( + make_server(), tmp_path, ciphers=RSA_KEY_EXCHANGE_ONLY, maximum_version=ssl.TLSVersion.TLSv1_2 + ) as base_url: + with pytest.raises(Exception) as caught: + await _ask(_provider(provider_cls, base_url, {}), stream=stream) + assert tls.classify_tls_error(caught.value) == tls.TLS_HANDSHAKE_FAILED + + assert await _ask(_provider(provider_cls, base_url, {"verify_ssl": False}), stream=stream) == "Paris" + + +@pytest.mark.asyncio +@pytest.mark.parametrize("provider_cls", PROVIDERS) +@pytest.mark.parametrize("stream", [False, True]) +async def test_internal_ca_gateway_needs_the_ca_or_checks_off(provider_cls, stream, internal_ca, tmp_path): + ca_file = tmp_path / "corp-ca.pem" + ca_file.write_text(internal_ca.cert_pem) + with https_gateway(make_server(internal_ca), tmp_path) as base_url: + with pytest.raises(Exception) as caught: + await _ask(_provider(provider_cls, base_url, {}), stream=stream) + assert tls.classify_tls_error(caught.value) == tls.TLS_CERTIFICATE_FAILED + + for settings in ({"ca_cert": internal_ca.cert_pem}, {"ca_cert": str(ca_file)}, {"verify_ssl": False}): + assert await _ask(_provider(provider_cls, base_url, settings), stream=stream) == "Paris" + + # Another CA does not make the gateway trusted. + with pytest.raises(Exception) as caught: + await _ask(_provider(provider_cls, base_url, {"ca_cert": make_ca().cert_pem}), stream=stream) + assert tls.classify_tls_error(caught.value) == tls.TLS_CERTIFICATE_FAILED + + +@pytest.mark.asyncio +async def test_a_self_signed_gateway_certificate_can_be_trusted_as_is(tmp_path): + gateway = make_server() + with https_gateway(gateway, tmp_path) as base_url: + provider = _provider(OpenAICompatibleProvider, base_url, {"ca_cert": gateway.cert_pem}) + assert await _ask(provider, stream=False) == "Paris" + + +# --------------------------------------------------------------------------- +# Clients built by the provider SDKs +# --------------------------------------------------------------------------- + + +def _ssl_context(httpx_client) -> ssl.SSLContext: + return httpx_client._transport._pool._ssl_context + + +@pytest.mark.parametrize( + ("factory", "settings_key"), + [ + (lambda settings: _provider(AnthropicProvider, "https://gateway.internal", settings), "anthropic"), + ( + lambda settings: _provider(AzureProvider, "https://gateway.internal/", {**settings, "api_version": "2025-04-01-preview"}), + "azure", + ), + ], +) +def test_anthropic_and_azure_clients_follow_the_settings(factory, settings_key, internal_ca): + relaxed = factory({"verify_ssl": False})._get_client() + assert_no_verify_context(_ssl_context(relaxed._client)) + + with_ca = factory({"ca_cert": internal_ca.cert_pem})._get_client() + context = _ssl_context(with_ca._client) + assert context.verify_mode == ssl.CERT_REQUIRED + default_cas = ssl.create_default_context(cafile=certifi.where()).cert_store_stats()["x509_ca"] + assert context.cert_store_stats()["x509_ca"] == default_cas + 1 + + default = factory({})._get_client() + assert _ssl_context(default._client).verify_mode == ssl.CERT_REQUIRED + + +def _tls_provider_classes(): + """Every SDK provider class that says its client follows the settings.""" + import importlib + import inspect + import pkgutil + + import flocks.provider.sdk as sdk + from flocks.provider.provider import BaseProvider + + found = {} + for info in pkgutil.iter_modules(sdk.__path__): + module = importlib.import_module(f"flocks.provider.sdk.{info.name}") + for _, cls in inspect.getmembers(module, inspect.isclass): + if issubclass(cls, BaseProvider) and cls.__module__ == module.__name__ and cls.SUPPORTS_TLS_SETTINGS: + found[cls.__qualname__] = cls + return sorted(found.items()) + + +TLS_PROVIDER_CLASSES = _tls_provider_classes() + + +@pytest.mark.parametrize(("name", "cls"), TLS_PROVIDER_CLASSES, ids=[name for name, _ in TLS_PROVIDER_CLASSES]) +def test_every_provider_offering_the_settings_applies_them(name, cls, internal_ca): + """A subclass that builds its own client must not drop the settings it claims to follow.""" + try: + cls() + except TypeError: + pytest.skip("base class: needs constructor arguments") + + def client_for(settings): + provider = cls() + provider.configure( + ProviderConfig( + provider_id=provider.id, + api_key="sk-test", # secret-guard: allow (test value) + base_url="https://gateway.internal/v1", + custom_settings={**settings, "api_version": "2025-04-01-preview"}, + ) + ) + return provider._get_client()._client + + assert_no_verify_context(_ssl_context(client_for({"verify_ssl": False}))) + with_ca = _ssl_context(client_for({"ca_cert": internal_ca.cert_pem})) + default_cas = ssl.create_default_context(cafile=certifi.where()).cert_store_stats()["x509_ca"] + assert with_ca.verify_mode == ssl.CERT_REQUIRED + assert with_ca.cert_store_stats()["x509_ca"] == default_cas + 1 + assert _ssl_context(client_for({})).verify_mode == ssl.CERT_REQUIRED + + +def test_providers_that_offer_the_settings(): + for cls in (OpenAICompatibleProvider, OpenAIProvider, AnthropicProvider, AzureProvider): + assert cls.SUPPORTS_TLS_SETTINGS is True + from flocks.provider.sdk.deepseek import DeepSeekProvider + from flocks.provider.sdk.google import GoogleProvider + from flocks.provider.sdk.xai import XAIProvider + + assert DeepSeekProvider.SUPPORTS_TLS_SETTINGS is True # OpenAIBaseProvider + assert GoogleProvider.SUPPORTS_TLS_SETTINGS is False + assert XAIProvider.SUPPORTS_TLS_SETTINGS is False + + +# --------------------------------------------------------------------------- +# Settings saved and read through the provider routes +# --------------------------------------------------------------------------- + + +@pytest.fixture +def saved_config(tmp_path, monkeypatch): + """A flocks.json in a temporary directory, an empty registry, in-memory secrets.""" + config_file = tmp_path / "flocks.json" + config_file.write_text("{}", encoding="utf-8") + monkeypatch.setattr(ConfigWriter, "_get_config_path", lambda: config_file) + monkeypatch.setattr(Provider, "_providers", {}) + monkeypatch.setattr(Provider, "_models", {}) + monkeypatch.setattr(Provider, "_initialized", True) + store: dict = {} + secrets = MagicMock() + secrets.get.side_effect = store.get + secrets.set.side_effect = store.__setitem__ + monkeypatch.setattr("flocks.security.get_secret_manager", lambda: secrets) + from flocks.server.routes import provider as provider_routes + + monkeypatch.setattr(provider_routes.Config, "clear_cache", MagicMock()) + + def write(providers: dict) -> None: + config_file.write_text(json.dumps({"provider": providers}), encoding="utf-8") + + def read(provider_id: str) -> dict: + return json.loads(config_file.read_text(encoding="utf-8"))["provider"][provider_id] + + return MagicMock(write=write, read=read, secrets=store) + + +@pytest.mark.asyncio +async def test_credentials_save_and_read_the_tls_settings(saved_config, internal_ca): + from flocks.server.routes import provider as provider_routes + + saved_config.write({ + "custom-gw": { + "npm": "@ai-sdk/openai-compatible", + "name": "Gateway", + "options": {"apiKey": "{secret:custom-gw_llm_key}", "baseURL": "https://gw.internal/v1", "ssl_verify": True}, + "models": {}, + } + }) + saved_config.secrets["custom-gw_llm_key"] = "sk-test" + + before = provider_routes._load_llm_provider_credentials("custom-gw") + assert (before.verify_ssl, before.ca_cert, before.tls_configurable) == (True, None, True) + + await provider_routes.set_provider_credentials( + "custom-gw", provider_routes.ProviderCredentialRequest(verify_ssl=False, ca_cert=internal_ca.cert_pem) + ) + options = saved_config.read("custom-gw")["options"] + assert options["verify_ssl"] is False + assert "ssl_verify" not in options # the older spelling would contradict the new value + assert options["ca_cert"] == internal_ca.cert_pem.strip() + assert options["baseURL"] == "https://gw.internal/v1" + after = provider_routes._load_llm_provider_credentials("custom-gw") + assert (after.verify_ssl, after.ca_cert) == (False, internal_ca.cert_pem.strip()) + + # Back to the defaults: no TLS keys are left behind. + await provider_routes.set_provider_credentials( + "custom-gw", provider_routes.ProviderCredentialRequest(verify_ssl=True, ca_cert="") + ) + options = saved_config.read("custom-gw")["options"] + assert not {"verify_ssl", "ssl_verify", "ca_cert"} & set(options) + + # Leaving the fields out changes nothing. + await provider_routes.set_provider_credentials( + "custom-gw", provider_routes.ProviderCredentialRequest(verify_ssl=False) + ) + await provider_routes.set_provider_credentials( + "custom-gw", provider_routes.ProviderCredentialRequest(base_url="https://gw2.internal/v1") + ) + assert saved_config.read("custom-gw")["options"]["verify_ssl"] is False + + +@pytest.mark.asyncio +async def test_a_bad_ca_cert_is_refused_before_anything_is_saved(saved_config): + from fastapi import HTTPException + + from flocks.server.routes import provider as provider_routes + + saved_config.write({ + "custom-gw": {"npm": "@ai-sdk/openai-compatible", "options": {"baseURL": "https://gw.internal/v1"}, "models": {}} + }) + with pytest.raises(HTTPException) as caught: + await provider_routes.set_provider_credentials( + "custom-gw", + provider_routes.ProviderCredentialRequest(api_key="sk-new", ca_cert="certs/ca.pem"), # secret-guard: allow (test value) + ) + assert caught.value.status_code == 400 + assert "绝对路径" in caught.value.detail + assert saved_config.read("custom-gw")["options"] == {"baseURL": "https://gw.internal/v1"} + assert "custom-gw_llm_key" not in saved_config.secrets + + +@pytest.mark.asyncio +async def test_providers_whose_client_ignores_the_settings_refuse_them(saved_config): + from fastapi import HTTPException + + from flocks.server.routes import provider as provider_routes + + saved_config.write({"google": {"npm": "@ai-sdk/google", "options": {}, "models": {}}}) + assert provider_routes._load_llm_provider_credentials("google").tls_configurable is False + with pytest.raises(HTTPException) as caught: + await provider_routes.set_provider_credentials( + "google", provider_routes.ProviderCredentialRequest(api_key="k", verify_ssl=False) + ) + assert caught.value.status_code == 400 + + +@pytest.mark.asyncio +async def test_a_new_provider_is_created_with_its_tls_settings(saved_config): + from flocks.server.routes import provider as provider_routes + + await provider_routes.set_provider_credentials( + "anthropic", + provider_routes.ProviderCredentialRequest( + api_key="sk-ant", base_url="https://claude-gw.internal", verify_ssl=False, skip_catalog_bootstrap=True # secret-guard: allow (test value) + ), + ) + assert saved_config.read("anthropic")["options"]["verify_ssl"] is False + + +@pytest.mark.asyncio +async def test_catalog_says_which_providers_offer_the_settings(saved_config): + from flocks.server.routes import provider as provider_routes + + catalog = {entry["id"]: entry for entry in (await provider_routes.get_provider_catalog())["providers"]} + assert catalog["openai-compatible"]["tls_configurable"] is True + assert catalog["anthropic"]["tls_configurable"] is True + assert catalog["azure-openai"]["tls_configurable"] is True + assert catalog["google"]["tls_configurable"] is False + + +@pytest.mark.asyncio +async def test_custom_provider_is_created_with_its_tls_settings(saved_config, internal_ca): + from fastapi import HTTPException + + from flocks.server.routes import custom_provider + + created = await custom_provider.create_provider( + custom_provider.CreateProviderReq( + name="corp gw", base_url="https://gw.internal/v1", api_key="sk-test", ca_cert=internal_ca.cert_pem # secret-guard: allow (test value) + ), + _admin=None, + ) + options = saved_config.read(created.id)["options"] + assert options["ca_cert"] == internal_ca.cert_pem.strip() + assert "verify_ssl" not in options + runtime = Provider._providers[created.id] + assert runtime._config.custom_settings == {"ca_cert": internal_ca.cert_pem.strip()} + + created = await custom_provider.create_provider( + custom_provider.CreateProviderReq(name="old gw", base_url="https://old.internal/v1", verify_ssl=False), + _admin=None, + ) + assert saved_config.read(created.id)["options"]["verify_ssl"] is False + + with pytest.raises(HTTPException) as caught: + await custom_provider.create_provider( + custom_provider.CreateProviderReq(name="bad gw", base_url="https://bad.internal/v1", ca_cert="ca.pem"), + _admin=None, + ) + assert caught.value.status_code == 422 + assert "provider" not in json.loads(ConfigWriter._get_config_path().read_text()) or "custom-bad-gw" not in json.loads( + ConfigWriter._get_config_path().read_text() + )["provider"] diff --git a/tests/provider/tls_helpers.py b/tests/provider/tls_helpers.py new file mode 100644 index 000000000..4817c2267 --- /dev/null +++ b/tests/provider/tls_helpers.py @@ -0,0 +1,186 @@ +"""Certificates and a local HTTPS gateway for the provider TLS tests. + +Keys and certificates are made while the tests run, so none is kept in the +repository. +""" + +from __future__ import annotations + +import contextlib +import datetime +import ipaddress +import json +import ssl +import threading +from dataclasses import dataclass +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from typing import Iterator, Optional + + +def assert_no_verify_context(verify) -> None: + """``verify_ssl: false`` gives an httpx ``verify`` context that checks nothing.""" + assert isinstance(verify, ssl.SSLContext), verify + assert verify.verify_mode == ssl.CERT_NONE + assert verify.check_hostname is False + + +def describe_verify(verify): + """``True`` for httpx's default checks, ``"no-verify"`` for the relaxed context.""" + if verify is True: + return True + if isinstance(verify, ssl.SSLContext) and verify.verify_mode == ssl.CERT_NONE: + return "no-verify" + return verify + + +@dataclass +class Credential: + cert_pem: str + key_pem: str + + +def _name(common_name: str): + from cryptography import x509 + from cryptography.x509.oid import NameOID + + return x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, common_name)]) + + +def _make(subject: str, *, issuer: Optional[Credential] = None, ca: bool = False, key_size: int = 2048) -> Credential: + from cryptography import x509 + from cryptography.hazmat.primitives import hashes, serialization + from cryptography.hazmat.primitives.asymmetric import rsa + + key = rsa.generate_private_key(public_exponent=65537, key_size=key_size) + now = datetime.datetime.now(datetime.timezone.utc) + if issuer is None: + issuer_name, signing_key = _name(subject), key + else: + issuer_cert = x509.load_pem_x509_certificate(issuer.cert_pem.encode()) + issuer_name = issuer_cert.subject + signing_key = serialization.load_pem_private_key(issuer.key_pem.encode(), password=None) + builder = ( + x509.CertificateBuilder() + .subject_name(_name(subject)) + .issuer_name(issuer_name) + .public_key(key.public_key()) + .serial_number(x509.random_serial_number()) + .not_valid_before(now - datetime.timedelta(minutes=5)) + .not_valid_after(now + datetime.timedelta(days=2)) + .add_extension(x509.BasicConstraints(ca=ca, path_length=None), critical=True) + ) + if ca: + builder = builder.add_extension( + x509.KeyUsage( + digital_signature=True, content_commitment=False, key_encipherment=False, + data_encipherment=False, key_agreement=False, key_cert_sign=True, crl_sign=True, + encipher_only=False, decipher_only=False, + ), + critical=True, + ) + else: + builder = builder.add_extension( + x509.SubjectAlternativeName([x509.DNSName("localhost"), x509.IPAddress(ipaddress.ip_address("127.0.0.1"))]), + critical=False, + ) + cert = builder.sign(signing_key, hashes.SHA256()) + return Credential( + cert_pem=cert.public_bytes(serialization.Encoding.PEM).decode(), + key_pem=key.private_bytes( + serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, serialization.NoEncryption() + ).decode(), + ) + + +def make_ca() -> Credential: + return _make("Flocks Test Internal CA", ca=True) + + +def make_server(issuer: Optional[Credential] = None) -> Credential: + """A gateway certificate for 127.0.0.1 / localhost: issued by *issuer*, or self-signed.""" + return _make("llm-gateway.test", issuer=issuer) + + +MODEL_ID = "gw-test-model" + + +class _Handler(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def log_message(self, *args) -> None: # keep test output quiet + pass + + def _json(self, payload) -> None: + body = json.dumps(payload).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def do_GET(self) -> None: + self._json({"object": "list", "data": [{"id": MODEL_ID, "object": "model"}]}) + + def do_POST(self) -> None: + length = int(self.headers.get("Content-Length") or 0) + request = json.loads(self.rfile.read(length) or b"{}") + if request.get("stream"): + self.send_response(200) + self.send_header("Content-Type", "text/event-stream") + self.send_header("Connection", "close") + self.end_headers() + for chunk in ( + {"id": "c1", "object": "chat.completion.chunk", "created": 0, "model": MODEL_ID, + "choices": [{"index": 0, "delta": {"role": "assistant", "content": "Paris"}, "finish_reason": None}]}, + {"id": "c1", "object": "chat.completion.chunk", "created": 0, "model": MODEL_ID, + "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}]}, + ): + self.wfile.write(b"data: " + json.dumps(chunk).encode() + b"\n\n") + self.wfile.write(b"data: [DONE]\n\n") + self.close_connection = True + return + self._json({ + "id": "c1", "object": "chat.completion", "created": 0, "model": MODEL_ID, + "choices": [{"index": 0, "message": {"role": "assistant", "content": "Paris"}, "finish_reason": "stop"}], + "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2}, + }) + + +@contextlib.contextmanager +def https_gateway( + credential: Credential, + tmp_path, + *, + ciphers: Optional[str] = None, + maximum_version: Optional[ssl.TLSVersion] = None, +) -> Iterator[str]: + """Serve an OpenAI-style API over HTTPS on 127.0.0.1; yields its ``/v1`` base URL. + + *ciphers* / *maximum_version* make it an older gateway: e.g. RSA key + exchange only, which CPython's default client settings refuse. + """ + cert_file = tmp_path / "gateway.crt" + key_file = tmp_path / "gateway.key" + cert_file.write_text(credential.cert_pem) + key_file.write_text(credential.key_pem) + context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + context.load_cert_chain(str(cert_file), str(key_file)) + if maximum_version is not None: + context.maximum_version = maximum_version + if ciphers: + context.set_ciphers(ciphers) + server = ThreadingHTTPServer(("127.0.0.1", 0), _Handler) + server.socket = context.wrap_socket(server.socket, server_side=True) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + yield f"https://127.0.0.1:{server.server_address[1]}/v1" + finally: + server.shutdown() + server.server_close() + thread.join(timeout=5) + + +# Only RSA key exchange (no ECDHE/DHE) in TLS 1.2: what older appliances often +# offer, and what CPython's default client cipher list leaves out. +RSA_KEY_EXCHANGE_ONLY = "AES128-GCM-SHA256:AES256-GCM-SHA384:@SECLEVEL=0" diff --git a/tests/server/routes/test_auth_console_login_routes.py b/tests/server/routes/test_auth_console_login_routes.py index 3884e8e21..69cf54d24 100644 --- a/tests/server/routes/test_auth_console_login_routes.py +++ b/tests/server/routes/test_auth_console_login_routes.py @@ -457,3 +457,41 @@ async def _finish(**kwargs): resp = await client.post("/api/auth/console-login/finish", json={"console_login_id": "x"}) assert resp.status_code == status.HTTP_502_BAD_GATEWAY assert resp.json()["message"] == "console 登录服务调用失败,请稍后重试" + + +async def test_console_connectivity_route(client: AsyncClient, monkeypatch: pytest.MonkeyPatch): + """Administrators only; whether Console answers from here, as flocks.console.connectivity says.""" + import httpx + from fastapi import HTTPException + + from flocks.console import connectivity + from flocks.server.routes import auth as auth_routes + + def member(_request): + raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="admin only") + + monkeypatch.setattr(auth_routes, "require_admin", member) + resp = await client.get("/api/auth/console-login/connectivity") + assert resp.status_code == status.HTTP_403_FORBIDDEN + + monkeypatch.setattr(auth_routes, "require_admin", lambda _req: _mock_admin()) + monkeypatch.setenv("FLOCKS_CONSOLE_BASE_URL", "https://console.example") + connectivity.forget() + seen: list[httpx.Request] = [] + real = httpx.AsyncClient + + class Client(real): # type: ignore[misc,valid-type] + def __init__(self, *args, **kwargs): + kwargs["transport"] = httpx.MockTransport(lambda request: seen.append(request) or httpx.Response(503)) + super().__init__(*args, **kwargs) + + monkeypatch.setattr(connectivity.httpx, "AsyncClient", Client) + try: + resp = await client.get("/api/auth/console-login/connectivity", params={"refresh": "true"}) + finally: + connectivity.forget() + assert resp.status_code == status.HTTP_200_OK + body = resp.json() + assert (body["configured"], body["online"], body["console_host"]) == (True, False, "console.example") + assert [str(request.url) for request in seen] == ["https://console.example/health"] + diff --git a/tests/server/routes/test_bootstrap_local_only.py b/tests/server/routes/test_bootstrap_local_only.py new file mode 100644 index 000000000..d2458ddc9 --- /dev/null +++ b/tests/server/routes/test_bootstrap_local_only.py @@ -0,0 +1,223 @@ +"""The first administrator is created only from the machine running Flocks. + +``flocks start`` listens on every interface by default (0.0.0.0): until an +administrator exists, whoever reached ``/api/auth/bootstrap-admin`` first +would become it. A browser elsewhere is refused and told to run +``flocks admin generate-one-time-password`` on the machine, which creates the +first administrator when there is no account yet. +""" + +from __future__ import annotations + +import asyncio +from types import SimpleNamespace + +import pytest +from httpx import ASGITransport, AsyncClient +from starlette.requests import Request + +from flocks.auth.service import AuthService +from flocks.server.auth import is_local_request +from flocks.server.routes import auth as auth_routes + +_BROWSER = {"sec-fetch-mode": "cors", "user-agent": "Mozilla/5.0", "Authorization": ""} +_ADMIN = {"username": "admin", "password": "Passw0rd!x"} + + +def _client(peer: str) -> AsyncClient: + from flocks.server.app import app + + return AsyncClient( + transport=ASGITransport(app=app, client=(peer, 51000)), + base_url="http://test", + headers=_BROWSER, + ) + + +@pytest.mark.parametrize( + ("host", "local"), + [ + ("127.0.0.1", True), + ("127.9.8.7", True), + ("::1", True), + ("::ffff:127.0.0.1", True), + ("10.0.0.5", False), + ("192.168.1.20", False), + ("172.17.0.1", False), + ("2001:db8::7", False), + ("::ffff:10.0.0.5", False), + ("0.0.0.0", False), + ("127.0.0.1%eth0", False), + ("testclient", False), + ("", False), + ], +) +def test_is_local_request_only_for_loopback_peers(host, local): + request = Request({"type": "http", "client": (host, 51000), "headers": []}) + assert is_local_request(request) is local + + +def test_is_local_request_without_peer(): + assert is_local_request(Request({"type": "http", "client": None, "headers": []})) is False + + +@pytest.mark.parametrize("peer", ["127.0.0.1", "::1", "::ffff:127.0.0.1"]) +@pytest.mark.parametrize( + "header", [(b"x-forwarded-for", b"10.1.2.3"), (b"forwarded", b"for=10.1.2.3"), (b"x-real-ip", b"10.1.2.3")] +) +def test_a_proxied_request_from_loopback_is_not_local(peer, header): + """A reverse proxy on this machine connects from loopback for a client elsewhere; + uvicorn resolves X-Forwarded-For only for 127.0.0.1 (not ::1 or mapped addresses).""" + request = Request({"type": "http", "client": (peer, 51000), "headers": [header]}) + assert is_local_request(request) is False + + +@pytest.mark.parametrize( + ("host", "port", "url"), + [ + ("0.0.0.0", "5173", "http://127.0.0.1:5173"), + ("127.0.0.1", "18573", "http://127.0.0.1:18573"), + ("127.0.0.2", "18573", "http://127.0.0.2:18573"), + ("localhost", "5173", "http://127.0.0.1:5173"), + ("::", "5173", "http://[::1]:5173"), + ("::1", "5173", "http://[::1]:5173"), + ("192.168.1.10", "5173", None), + ("", "5173", None), + ("0.0.0.0", "", None), + ], +) +def test_local_setup_url_follows_where_the_service_listens(monkeypatch, host, port, url): + monkeypatch.setenv("_FLOCKS_SERVER_HOST", host) + monkeypatch.setenv("_FLOCKS_SERVER_PORT", port) + assert auth_routes._local_setup_url() == url + + +@pytest.mark.asyncio +@pytest.mark.parametrize("peer", ["10.0.0.5", "172.17.0.1", "2001:db8::7"]) +async def test_remote_browser_cannot_create_first_admin(monkeypatch, peer): + monkeypatch.setenv("_FLOCKS_SERVER_HOST", "0.0.0.0") + monkeypatch.setenv("_FLOCKS_SERVER_PORT", "18573") + async with _client(peer) as client: + status = await client.get("/api/auth/bootstrap-status") + # A forwarded-for header the peer writes itself proves nothing. + response = await client.post( + "/api/auth/bootstrap-admin", json=_ADMIN, headers={"X-Forwarded-For": "127.0.0.1"} + ) + + assert status.status_code == 200 + assert status.json() == {"bootstrapped": False, "setup_allowed": False, "local_url": "http://127.0.0.1:18573"} + assert response.status_code == 403, response.text + assert "flocks admin generate-one-time-password" in response.text + assert "http://127.0.0.1:18573" in response.text + assert await AuthService.has_users() is False + assert "flocks_session" not in response.headers.get("set-cookie", "") + + +@pytest.mark.asyncio +@pytest.mark.parametrize("peer", ["127.0.0.1", "::1"]) +async def test_browser_on_this_machine_creates_first_admin(peer): + async with _client(peer) as client: + before = await client.get("/api/auth/bootstrap-status") + response = await client.post("/api/auth/bootstrap-admin", json=_ADMIN) + after = await client.get("/api/auth/bootstrap-status") + + assert before.json() == {"bootstrapped": False, "setup_allowed": True, "local_url": None} + assert response.status_code == 200, response.text + assert response.json()["role"] == "admin" + assert after.json() == {"bootstrapped": True, "setup_allowed": False, "local_url": None} + + +@pytest.mark.asyncio +async def test_a_proxy_on_this_machine_cannot_create_first_admin_for_a_client_elsewhere(monkeypatch): + """``--host ::`` behind a proxy on [::1]: uvicorn keeps ::1 as the peer, the header says who it is for.""" + monkeypatch.setenv("_FLOCKS_SERVER_HOST", "::") + monkeypatch.setenv("_FLOCKS_SERVER_PORT", "5173") + async with _client("::1") as client: + status = await client.get("/api/auth/bootstrap-status", headers={"X-Forwarded-For": "10.1.2.3"}) + response = await client.post( + "/api/auth/bootstrap-admin", json=_ADMIN, headers={"X-Forwarded-For": "10.1.2.3"} + ) + + assert status.json() == {"bootstrapped": False, "setup_allowed": False, "local_url": "http://[::1]:5173"} + assert response.status_code == 403, response.text + assert await AuthService.has_users() is False + + +@pytest.mark.asyncio +async def test_an_administrator_made_on_the_command_line_gets_the_old_sessions_at_first_sign_in(monkeypatch): + """As the core's ``issue-temporary-password`` makes it: no account at startup, so the server + left the sessions from before accounts without an owner.""" + from flocks.session import session as session_module + + orphans = [SimpleNamespace(id="ses_old", project_id="proj", owner_user_id=None, owner_username=None)] + updated: list[dict] = [] + + async def list_all(): + return orphans + + async def update(**kwargs): + updated.append(kwargs) + + monkeypatch.setattr(session_module.Session, "list_all", staticmethod(list_all)) + monkeypatch.setattr(session_module.Session, "update", staticmethod(update)) + admin = await AuthService._create_user_internal(username="admin", password=_ADMIN["password"], role="admin") + + async with _client("10.0.0.5") as client: + first = await client.post("/api/auth/login", json=_ADMIN) + second = await client.post("/api/auth/login", json=_ADMIN) + + assert first.status_code == 200 and second.status_code == 200, (first.text, second.text) + assert [(u["session_id"], u["owner_user_id"]) for u in updated] == [("ses_old", admin.id)] + + +@pytest.mark.asyncio +async def test_one_time_password_creates_first_admin_when_there_is_no_account(): + await AuthService.init() + assert await AuthService.has_users() is False + + temp = await AuthService.generate_admin_temp_password(username="admin") + + user, _, _ = await AuthService.get_user_by_username("admin") + assert user.role == "admin" + assert user.must_reset_password is True + logged_in, session_id = await AuthService.login("admin", temp) + assert logged_in.username == "admin" and session_id + # Once the account is there, the command resets its password as before. + again = await AuthService.generate_admin_temp_password(username="admin") + assert again != temp + assert [u.username for u in await AuthService.list_users()] == ["admin"] + + +@pytest.mark.asyncio +async def test_one_time_password_creates_nothing_once_accounts_exist(): + await AuthService.bootstrap_admin("root", "Passw0rd!x") + + with pytest.raises(ValueError, match="管理员账号不存在"): + await AuthService.generate_admin_temp_password(username="admin") + + assert [u.username for u in await AuthService.list_users()] == ["root"] + + +@pytest.mark.asyncio +async def test_first_administrator_from_both_entries_is_made_once(): + """The one-time password's first administrator and the setup page's race on the same guard.""" + await AuthService.init() + + async def cli(name): + try: + return ("made", name, await AuthService.generate_admin_temp_password(username=name)) + except ValueError as exc: + return ("refused", name, str(exc)) + + async def web(name): + try: + return ("made", (await AuthService.bootstrap_admin(name, _ADMIN["password"])).username, None) + except ValueError as exc: + return ("refused", name, str(exc)) + + results = await asyncio.gather(cli("cli-a"), web("web-a"), cli("cli-b"), web("web-b")) + + made = [r for r in results if r[0] == "made"] + assert len(made) == 1, results + assert [u.username for u in await AuthService.list_users()] == [made[0][1]] + assert {r[2] for r in results if r[0] == "refused"} <= {"账号体系已初始化", "管理员账号不存在"} diff --git a/tests/server/routes/test_enterprise_upgrade_routes.py b/tests/server/routes/test_enterprise_upgrade_routes.py index 87483b277..b3282a232 100644 --- a/tests/server/routes/test_enterprise_upgrade_routes.py +++ b/tests/server/routes/test_enterprise_upgrade_routes.py @@ -11,6 +11,9 @@ words, and taking a licence answers with the machine's new situation ER6 syncing the licence with Console: whether the terms changed; what stopped it as a 409 with its words + ER7 licensing offline: the application file from the form checked as above, the licence file's + import with the machine's new situation, refusals as a 409 with their words, a file far too big + refused before anything runs """ from __future__ import annotations @@ -45,7 +48,7 @@ async def test_er1_administrators_only(client: AsyncClient, monkeypatch: pytest. for method, path in (("get", ""), ("post", "/check"), ("post", "/start"), ("get", "/progress"), ("get", "/applications"), ("post", "/applications"), ("post", "/applications/req_1/withdraw"), ("post", "/applications/req_1/take"), - ("post", "/licence/sync")): + ("post", "/licence/sync"), ("post", "/applications/offline"), ("post", "/licence/import")): resp = await getattr(client, method)(f"/api/enterprise-upgrade{path}") assert resp.status_code == status.HTTP_403_FORBIDDEN, path @@ -179,3 +182,52 @@ async def stopped(): monkeypatch.setattr(enterprise_application, "sync_licence", stopped) resp = await client.post("/api/enterprise-upgrade/licence/sync") assert resp.status_code == status.HTTP_409_CONFLICT and "先登录云账号" in json.dumps(resp.json(), ensure_ascii=False) + + +async def test_er7_licensing_offline(client: AsyncClient, monkeypatch: pytest.MonkeyPatch): + monkeypatch.setattr(routes, "require_admin", _admin) + form = {"license_type": "poc", "company": "Acme", "applicant_name": "Li Lei", + "applicant_email": "li@acme.example", "applicant_phone": "+86 138 0000 0000"} + made: list[tuple[dict, str]] = [] + + async def offline_application(sent: dict, applied_by: str) -> dict: + made.append((sent, applied_by)) + return {"format": "flocks-licence-application/1", "company": sent["company"], "machine": "0" * 32} + + monkeypatch.setattr(enterprise_application, "offline_application", offline_application) + resp = await client.post("/api/enterprise-upgrade/applications/offline", json=form) + assert resp.status_code == 200 and resp.json()["application"]["machine"] == "0" * 32 + assert made[0][1] == "admin" and made[0][0]["company"] == "Acme" + resp = await client.post("/api/enterprise-upgrade/applications/offline", json={**form, "applicant_email": "nope"}) + assert resp.status_code == 422 and len(made) == 1 + + async def refused_application(sent: dict, applied_by: str) -> dict: + raise enterprise.EnterpriseUpgradeError("这台机器已经有企业版授权,直接升级即可") + + monkeypatch.setattr(enterprise_application, "offline_application", refused_application) + resp = await client.post("/api/enterprise-upgrade/applications/offline", json=form) + assert resp.status_code == status.HTTP_409_CONFLICT and "已经有企业版授权" in json.dumps(resp.json(), ensure_ascii=False) + + imported: list[str] = [] + + async def import_licence(content: str) -> dict: + imported.append(content) + return {"license_id": "lic_off_1", "license_status": "poc", "expires_at": 4102444800} + + monkeypatch.setattr(enterprise_application, "import_licence", import_licence) + monkeypatch.setattr(enterprise, "situation", lambda: {"available": True, "previous": {"license_id": "lic_off_1"}}) + resp = await client.post("/api/enterprise-upgrade/licence/import", json={"content": '{"key": "a.b.c"}'}) + assert resp.status_code == 200 + assert resp.json()["licence"]["license_id"] == "lic_off_1" and resp.json()["situation"]["previous"]["license_id"] == "lic_off_1" + assert imported == ['{"key": "a.b.c"}'] + # Far bigger than any licence: refused before it is read. + resp = await client.post("/api/enterprise-upgrade/licence/import", + json={"content": "x" * (enterprise_application.MAX_LICENCE_CHARS + 1)}) + assert resp.status_code == 422 and len(imported) == 1 + + async def refused_import(content: str) -> dict: + raise enterprise.EnterpriseUpgradeError("这份授权绑定的是另一台机器:请用这台机器的申请信息重新申请") + + monkeypatch.setattr(enterprise_application, "import_licence", refused_import) + resp = await client.post("/api/enterprise-upgrade/licence/import", json={"content": "a.b.c"}) + assert resp.status_code == status.HTTP_409_CONFLICT and "另一台机器" in json.dumps(resp.json(), ensure_ascii=False) diff --git a/tests/server/routes/test_model_discovery_routes.py b/tests/server/routes/test_model_discovery_routes.py index 6622fca49..38068d750 100644 --- a/tests/server/routes/test_model_discovery_routes.py +++ b/tests/server/routes/test_model_discovery_routes.py @@ -170,6 +170,7 @@ async def test_discovery_forwards_transient_credentials_and_returns_structured_e "custom-inventory", api_key="transient-secret", base_url="https://candidate.test/v1", + tls_overrides=None, ) assert saved(inventory) == inventory.initial inventory.write.assert_not_called() @@ -177,6 +178,32 @@ async def test_discovery_forwards_transient_credentials_and_returns_structured_e assert "transient-secret" not in response.text +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("body", "overrides"), + [ + ({"verify_ssl": False}, {"verify_ssl": False}), + ({"ca_cert": ""}, {"ca_cert": ""}), + ({"verify_ssl": True, "ca_cert": "/etc/pki/corp-ca.pem"}, {"verify_ssl": True, "ca_cert": "/etc/pki/corp-ca.pem"}), + ], +) +async def test_discovery_and_key_check_use_unsaved_tls_settings(body, overrides, inventory, inventory_client, monkeypatch): + """The settings form checks a gateway with the SSL settings it has not saved yet.""" + result = {"source": "api", "status": "success", "code": "models_discovered", "message": "", "truncated": False, "models": []} + discover = AsyncMock(return_value=result) + monkeypatch.setattr(inventory.routes, "discover_models", discover) + + response = await inventory_client.post("/api/provider/custom-inventory/discover-models", json=body) + assert response.status_code == 200 + assert discover.await_args.kwargs["tls_overrides"] == overrides + + discover.reset_mock() + response = await inventory_client.post("/api/provider/custom-inventory/check-key", json={"api_key": "k", **body}) + assert response.status_code == 200 + assert [call.kwargs["tls_overrides"] for call in discover.await_args_list] == [overrides, overrides] + assert saved(inventory) == inventory.initial + + @pytest.mark.asyncio @pytest.mark.parametrize( "operation,body", @@ -615,7 +642,9 @@ async def test_threatbook_key_check_uses_one_live_inventory_request_without_savi }) assert response.status_code == 200 assert response.json() == {'status': status, 'code': expected_code} - discover.assert_awaited_once_with(provider_id, api_key='candidate-key', base_url='https://configured.test/v1') + discover.assert_awaited_once_with( + provider_id, api_key='candidate-key', base_url='https://configured.test/v1', tls_overrides=None # secret-guard: allow (test value) + ) assert saved(inventory) == inventory.initial inventory.write.assert_not_called() inventory.apply_config.assert_not_awaited() diff --git a/tests/server/routes/test_private_file_entrypoints.py b/tests/server/routes/test_private_file_entrypoints.py index 5ddf901d6..93dc0ef64 100644 --- a/tests/server/routes/test_private_file_entrypoints.py +++ b/tests/server/routes/test_private_file_entrypoints.py @@ -237,3 +237,10 @@ def test_project_folder_browser_hides_and_refuses_private_directories(private_fi assert response.status_code == 200 assert 'private-directory' not in response.text assert client.get('/project/folders', params={'path': str(private_files.context / 'private-directory')}).status_code == 403 + # The nearest existing ancestor of a missing directory is refused the same way. + missing_below_private = str(private_files.context / 'private-directory' / 'not-created') + assert client.get('/project/folders', params={'path': missing_below_private, 'nearest': 'true'}).status_code == 403 + missing_below_public = client.get('/project/folders', params={'path': str(private_files.context / 'not-created'), 'nearest': 'true'}) + assert missing_below_public.status_code == 200 + assert missing_below_public.json()['missing'] is True + assert 'private-directory' not in missing_below_public.text diff --git a/tests/server/routes/test_project_routes.py b/tests/server/routes/test_project_routes.py index 9bfc3c2b5..8966c2f5d 100644 --- a/tests/server/routes/test_project_routes.py +++ b/tests/server/routes/test_project_routes.py @@ -539,6 +539,34 @@ async def test_project_list_reports_unreachable_worktree_as_unreadable( assert fetched.json()["pathStatus"] == "unreadable" +@pytest.mark.skipif( + os.name == "nt" or (hasattr(os, "geteuid") and os.geteuid() == 0), + reason="needs POSIX directory search permission enforced for this account", +) +@pytest.mark.asyncio +async def test_create_project_reports_unreachable_directory_as_not_readable( + client: AsyncClient, + tmp_path: Path, +): + """INC-61BE1F94: a folder the service account cannot reach is a permission to + grant, not a missing directory, and never a 500 carrying the server's path.""" + + parent = tmp_path / "svc-denied" + worktree = parent / "repo" + worktree.mkdir(parents=True) + parent.chmod(0o600) + try: + response = await client.post( + "/api/project", + json={"name": "Denied", "worktree": str(worktree)}, + ) + finally: + parent.chmod(0o700) + + assert response.status_code == status.HTTP_400_BAD_REQUEST, response.text + assert response.json()["message"] == "Project directory is not readable" + + @pytest.mark.asyncio async def test_folder_browser_starts_at_home_when_path_is_omitted( client: AsyncClient, @@ -581,6 +609,95 @@ async def test_folder_browser_lists_directories_and_blocks_outside_root( assert escaped_listing.status_code == status.HTTP_403_FORBIDDEN +@pytest.mark.asyncio +async def test_folder_browser_opens_on_nearest_existing_ancestor_of_a_directory_not_created_yet( + client: AsyncClient, + tmp_path: Path, +): + # INC-14B4A77C: the folder dialog fills in "/", which is only + # created on save, and its Browse button asks for that directory. + parent = tmp_path / "parent" + (parent / "child").mkdir(parents=True) + not_created = parent / "new-folder" / "src" + + strict = await client.get("/api/project/folders", params={"path": str(not_created)}) + assert strict.status_code == status.HTTP_400_BAD_REQUEST + + response = await client.get( + "/api/project/folders", + params={"path": str(not_created), "nearest": "true"}, + ) + + assert response.status_code == status.HTTP_200_OK, response.text + payload = response.json() + assert payload["missing"] is True + assert payload["path"] == str(parent.resolve()) + assert payload["parent"] == str(tmp_path.resolve()) + assert {entry["name"] for entry in payload["entries"]} == {"child"} + assert not not_created.exists() and not not_created.parent.exists() + + existing = await client.get( + "/api/project/folders", + params={"path": str(parent), "nearest": "true"}, + ) + assert existing.status_code == status.HTTP_200_OK, existing.text + assert existing.json()["missing"] is False + assert existing.json()["path"] == str(parent.resolve()) + + default = await client.get("/api/project/folders", params={"nearest": "true"}) + assert default.status_code == status.HTTP_200_OK, default.text + assert default.json()["missing"] is False + + +@pytest.mark.asyncio +async def test_folder_browser_nearest_ancestor_stays_inside_the_allowed_roots( + client: AsyncClient, + tmp_path: Path, +): + parent = tmp_path / "parent" + parent.mkdir() + (parent / "notes.txt").write_text("a file") + escape_link = parent / "escape" + escape_link.symlink_to(Path.home(), target_is_directory=True) + + async def browse(path: str): + return await client.get("/api/project/folders", params={"path": path, "nearest": "true"}) + + # Nothing outside the roots is listed, whether or not the directory exists. + outside = await browse(str(Path.home() / "inc-14b4a77c-not-created" / "src")) + assert outside.status_code == status.HTTP_403_FORBIDDEN + through_link = await browse(str(escape_link / "inc-14b4a77c-not-created")) + assert through_link.status_code == status.HTTP_403_FORBIDDEN + # A file cannot become a project directory, and neither can a path below one. + assert (await browse(str(parent / "notes.txt"))).status_code == status.HTTP_400_BAD_REQUEST + assert (await browse(str(parent / "notes.txt" / "below"))).status_code == status.HTTP_400_BAD_REQUEST + # Only an absolute path has ancestors worth offering. + assert (await browse("inc-14b4a77c-relative/new")).status_code == status.HTTP_400_BAD_REQUEST + # The climb is bounded: a directory far below anything that exists is not looked for. + from flocks.server.routes.project import _NEAREST_ANCESTOR_LEVELS + + within_reach = parent.joinpath(*["new"] * _NEAREST_ANCESTOR_LEVELS) + reached = await browse(str(within_reach)) + assert reached.status_code == status.HTTP_200_OK, reached.text + assert reached.json()["path"] == str(parent.resolve()) + assert (await browse(str(within_reach / "new"))).status_code == status.HTTP_400_BAD_REQUEST + + +@pytest.mark.asyncio +@pytest.mark.parametrize("nearest", ["false", "true"]) +async def test_folder_browser_rejects_a_path_with_a_nul_byte( + client: AsyncClient, + tmp_path: Path, + nearest: str, +): + response = await client.get( + "/api/project/folders", + params={"path": f"{tmp_path}/a\x00b", "nearest": nearest}, + ) + + assert response.status_code == status.HTTP_400_BAD_REQUEST + + @pytest.mark.asyncio async def test_project_local_sharing_includes_existing_and_future_sessions( client: AsyncClient, diff --git a/tests/server/routes/test_skill_hardening_g3b.py b/tests/server/routes/test_skill_hardening_g3b.py index cf87f8af1..1c3860c0c 100644 --- a/tests/server/routes/test_skill_hardening_g3b.py +++ b/tests/server/routes/test_skill_hardening_g3b.py @@ -167,6 +167,119 @@ async def test_url_install_rejects_plain_http_and_internal(monkeypatch: pytest.M assert r1.success is False and "must use https" in r1.error r2 = await SkillInstaller._install_from_url("https://169.254.169.254/latest/meta-data/", "global") assert r2.success is False and "Blocked request to internal" in r2.error + # plain http stays refused for anything but this machine's loopback + r3 = await SkillInstaller._install_from_url("http://10.0.0.5/SKILL.md", "global") + assert r3.success is False and "must use https" in r3.error + r4 = await SkillInstaller._install_from_url("ftp://127.0.0.1/SKILL.md", "global") + assert r4.success is False and "must use https" in r4.error + # a name that only starts like 127.0.0.1 is not this machine + r5 = await SkillInstaller._install_from_url("http://127.0.0.1%25.attacker.example/SKILL.md", "global") + assert r5.success is False and "must use https" in r5.error + + +@pytest.mark.asyncio +@pytest.mark.parametrize("proxy", [None, "http://proxy.invalid:3128"]) +async def test_url_install_from_loopback_over_plain_http( + client: AsyncClient, skills_root: Path, monkeypatch: pytest.MonkeyPatch, proxy +): + """本机回环上的 http 地址可以直接装技能(11-17 用户要求不拦 localhost / 127.0.0.1); + 环境里配了代理也直连本机,不经代理。""" + import http.server + import threading + + from flocks.skill import installer as installer_mod + + monkeypatch.setattr(installer_mod, "_resolve_install_root", lambda scope: skills_root) + monkeypatch.delenv("FLOCKS_WEBFETCH_ALLOW_INTERNAL", raising=False) + for name in ("HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "http_proxy", "https_proxy", "all_proxy", "NO_PROXY", "no_proxy"): + monkeypatch.delenv(name, raising=False) + if proxy: + for name in ("HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY"): + monkeypatch.setenv(name, proxy) + body = "---\nname: loopback-skill\ndescription: d\n---\n\nserved locally\n".encode() + + class _Handler(http.server.BaseHTTPRequestHandler): + def do_GET(self): + self.send_response(200) + self.send_header("Content-Type", "text/markdown; charset=utf-8") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *args): + pass + + server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), _Handler) + threading.Thread(target=server.serve_forever, daemon=True).start() + try: + port = server.server_address[1] + resp = await client.post( + "/api/skills/install", json={"source": f"http://127.0.0.1:{port}/SKILL.md"} + ) + assert resp.status_code == 200, resp.text + assert "served locally" in (skills_root / "loopback-skill" / "SKILL.md").read_text() + again = await client.post( + "/api/skills/install", + json={"source": f"http://localhost:{port}/SKILL.md", "overwrite": True}, + ) + assert again.status_code == 200, again.text + finally: + server.shutdown() + server.server_close() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("host", ["127.0.0.1", "localhost"]) +async def test_url_install_from_loopback_https_keeps_the_environment_ca( + client: AsyncClient, skills_root: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, host: str +): + """本机 https 服务用私有 CA 签的证书、CA 由 SSL_CERT_FILE 给出:直连本机时照样认这个 CA,环境代理照样不走。""" + import http.server + import ssl + import threading + + from flocks.skill import installer as installer_mod + from tests.provider.tls_helpers import make_ca, make_server + + monkeypatch.setattr(installer_mod, "_resolve_install_root", lambda scope: skills_root) + monkeypatch.delenv("FLOCKS_WEBFETCH_ALLOW_INTERNAL", raising=False) + monkeypatch.delenv("SSL_CERT_DIR", raising=False) + for name in ("NO_PROXY", "no_proxy", "http_proxy", "https_proxy", "all_proxy"): + monkeypatch.delenv(name, raising=False) + for name in ("HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY"): + monkeypatch.setenv(name, "http://proxy.invalid:3128") + ca = make_ca() + server_cred = make_server(issuer=ca) + (tmp_path / "ca.pem").write_text(ca.cert_pem) + (tmp_path / "server.crt").write_text(server_cred.cert_pem) + (tmp_path / "server.key").write_text(server_cred.key_pem) + monkeypatch.setenv("SSL_CERT_FILE", str(tmp_path / "ca.pem")) + body = "---\nname: tls-loopback-skill\ndescription: d\n---\n\nserved over https\n".encode() + + class _Handler(http.server.BaseHTTPRequestHandler): + def do_GET(self): + self.send_response(200) + self.send_header("Content-Type", "text/markdown; charset=utf-8") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *args): + pass + + context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + context.load_cert_chain(str(tmp_path / "server.crt"), str(tmp_path / "server.key")) + server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), _Handler) + server.socket = context.wrap_socket(server.socket, server_side=True) + threading.Thread(target=server.serve_forever, daemon=True).start() + try: + port = server.server_address[1] + resp = await client.post("/api/skills/install", json={"source": f"https://{host}:{port}/SKILL.md"}) + assert resp.status_code == 200, resp.text + assert "served over https" in (skills_root / "tls-loopback-skill" / "SKILL.md").read_text() + finally: + server.shutdown() + server.server_close() @pytest.mark.asyncio diff --git a/tests/server/routes/test_tool_reload_off_event_loop.py b/tests/server/routes/test_tool_reload_off_event_loop.py new file mode 100644 index 000000000..febcea331 --- /dev/null +++ b/tests/server/routes/test_tool_reload_off_event_loop.py @@ -0,0 +1,150 @@ +"""Routes that reload plugin tools keep the rest of the server answering. + +A reload re-reads every plugin source and takes seconds. Run on the event +loop, it held up every other request on the server until it ended. +""" + +from __future__ import annotations + +import asyncio +import threading + +import httpx +import pytest +from fastapi import FastAPI + +from flocks.auth.context import AuthUser +from flocks.server.auth import require_admin +from flocks.tool.registry import ToolRegistry + +_ADMIN = AuthUser( + id="admin-test", + username="admin-test", + role="admin", + status="active", + must_reset_password=False, +) + + +def _app() -> FastAPI: + from flocks.server.routes.device import router as device_router + from flocks.server.routes.tool import router as tool_router + + app = FastAPI() + app.include_router(tool_router, prefix="/api/tools") + app.include_router(device_router, prefix="/api/devices") + app.dependency_overrides[require_admin] = lambda: _ADMIN + + @app.get("/ping") + async def ping() -> dict: + return {"ok": True} + + return app + + +class _HeldReload: + """A stand-in reload that blocks its thread until released.""" + + def __init__(self) -> None: + self.entered = threading.Event() + self.release = threading.Event() + self.calls = 0 + + def __call__(self, *_args, **_kwargs): + self.calls += 1 + self.entered.set() + assert self.release.wait(timeout=5) + return [] + + +async def _ping_while_held( + app: FastAPI, + method: str, + url: str, + held: _HeldReload, + json: dict | None = None, +) -> httpx.Response: + transport = httpx.ASGITransport(app=app) + async with httpx.AsyncClient(transport=transport, base_url="http://test") as client: + slow = asyncio.create_task(client.request(method, url, json=json)) + try: + # The reload starts on a worker thread; the loop stays free meanwhile. + for _ in range(200): + if held.entered.is_set(): + break + await asyncio.sleep(0.01) + assert held.entered.is_set(), "the reload never started" + ping = await asyncio.wait_for(client.get("/ping"), timeout=1) + assert ping.status_code == 200 + assert not slow.done(), "the reload finished before the ping was answered" + finally: + held.release.set() + return await asyncio.wait_for(slow, timeout=5) + + +@pytest.mark.asyncio +async def test_tools_refresh_runs_reloads_off_the_event_loop(monkeypatch: pytest.MonkeyPatch): + held = _HeldReload() + monkeypatch.setattr(ToolRegistry, "init", classmethod(lambda cls: None)) + monkeypatch.setattr(ToolRegistry, "refresh_dynamic_tools", classmethod(lambda cls: held())) + monkeypatch.setattr(ToolRegistry, "refresh_plugin_tools", classmethod(lambda cls, changed_path=None: [])) + monkeypatch.setattr(ToolRegistry, "all_tool_ids", classmethod(lambda cls: [])) + + response = await _ping_while_held(_app(), "POST", "/api/tools/refresh", held) + + assert response.status_code == 200, response.text + assert response.json()["stages"] == {"dynamic": "success", "plugin": "success"} + + +@pytest.mark.asyncio +async def test_tool_delete_reloads_off_the_event_loop(monkeypatch: pytest.MonkeyPatch): + from flocks.hub import local as hub_local + from flocks.tool import tool_loader + + held = _HeldReload() + monkeypatch.setattr(ToolRegistry, "init", classmethod(lambda cls: None)) + monkeypatch.setattr(ToolRegistry, "refresh_plugin_tools", classmethod(lambda cls, changed_path=None: held())) + monkeypatch.setattr(tool_loader, "find_yaml_tool", lambda name: True) + monkeypatch.setattr(tool_loader, "delete_yaml_tool", lambda name: True) + monkeypatch.setattr(hub_local, "remove_installed_record", lambda *_args, **_kwargs: None) + + response = await _ping_while_held(_app(), "DELETE", "/api/tools/held_plugin_tool", held) + + assert response.status_code == 200, response.text + assert held.calls == 1 + + +@pytest.mark.asyncio +async def test_custom_device_template_is_created_off_the_event_loop(monkeypatch: pytest.MonkeyPatch): + from flocks.server.routes import device as device_routes + from flocks.tool.device.models import DeviceTemplate + + held = _HeldReload() + template = DeviceTemplate( + plugin_id="held_device", + storage_key="held_device", + service_id="held_device", + name="Held device", + installed=True, + state="installed", + source="global", + ) + monkeypatch.setattr(device_routes, "require_admin", lambda request: _ADMIN) + + def _create(body): + held() + return template + + monkeypatch.setattr(device_routes, "create_custom_device_template", _create) + + response = await _ping_while_held( + _app(), + "POST", + "/api/devices/templates/custom", + held, + json={"plugin_id": "held_device", "name": "Held device", "service_id": "held_device"}, + ) + + assert response.status_code == 201, response.text + assert response.json()["plugin_id"] == "held_device" + assert held.calls == 1 diff --git a/tests/server/routes/test_tool_routes.py b/tests/server/routes/test_tool_routes.py index 7c19f633d..eef2cfc00 100644 --- a/tests/server/routes/test_tool_routes.py +++ b/tests/server/routes/test_tool_routes.py @@ -775,10 +775,10 @@ async def handler(ctx) -> ToolResult: original_build_tool_index_item = tool_routes._build_tool_index_item index_builds = 0 - def counted_build_tool_index_item(tool_info): + def counted_build_tool_index_item(tool_info, **kwargs): nonlocal index_builds index_builds += 1 - return original_build_tool_index_item(tool_info) + return original_build_tool_index_item(tool_info, **kwargs) monkeypatch.setattr(tool_routes, "_build_tool_index_item", counted_build_tool_index_item) diff --git a/tests/server/routes/test_workflow_poller_routes.py b/tests/server/routes/test_workflow_poller_routes.py index 0b2c833a6..bdc82b497 100644 --- a/tests/server/routes/test_workflow_poller_routes.py +++ b/tests/server/routes/test_workflow_poller_routes.py @@ -257,3 +257,81 @@ async def _fake_restart(workflow_id: str) -> dict[str, Any]: assert response.status_code == 200, response.text same_type = [trigger for trigger in persisted[0] if trigger.type == trigger_type] assert [trigger.id for trigger in same_type] == [custom_id] + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("endpoint", "trigger_type", "manager_path", "settings"), + [ + ("kafka-config", "kafka", "flocks.ingest.kafka.manager.default_manager", {"inputTopic": "alerts"}), + ("poller-config", "schedule", "flocks.workflow.poller_manager.default_manager", {"intervalSeconds": 60}), + ("syslog-config", "syslog", "flocks.ingest.syslog.manager.default_manager", {"port": 5514}), + ], +) +@pytest.mark.parametrize( + "concurrency", + [ + None, + {"policy": "allow", "maxParallel": 6, "queueSize": 1000}, + {"policy": "queue", "maxParallel": 3, "queueSize": 250}, + ], +) +async def test_legacy_config_stop_start_preserves_concurrency( + client: AsyncClient, + monkeypatch: pytest.MonkeyPatch, + endpoint: str, + trigger_type: str, + manager_path: str, + settings: dict[str, Any], + concurrency: dict[str, Any] | None, +) -> None: + from flocks.workflow.triggers.models import TriggerDefinition + + expected = concurrency or {"policy": "allow", "maxParallel": 1, "queueSize": 100} + trigger_id = f"custom-{trigger_type}" + preserved_fields = { + "name": "Alert input", + "description": "Keep fields absent from the config form", + "filter": {"expr": "$.body.severity == 'high'"}, + "testSamples": [{"name": "sample", "payload": {"severity": "high"}, "headers": {}, "query": {}}], + } + triggers = [] if concurrency is None else [ + {"id": trigger_id, "type": trigger_type, "enabled": True, + "concurrency": concurrency, **preserved_fields} + ] + data = {"workflowJson": { + "start": "n1", + "nodes": [{"id": "n1", "type": "python", "code": "result = {'ok': True}"}], + "edges": [], + "triggers": triggers, + }} + restart_states: list[bool] = [] + + def _fake_write(workflow_id: str, workflow_json: dict[str, Any], *args: Any, **kwargs: Any) -> None: + # Exercise real trigger serialization/persistence, then reload it on restart. + data["workflowJson"] = workflow_json + + async def _fake_restart(workflow_id: str) -> dict[str, Any]: + saved = data["workflowJson"]["triggers"] + assert len(saved) == 1 + trigger = TriggerDefinition.model_validate(saved[0]) + assert trigger.concurrency.model_dump() == expected + if concurrency is not None: + assert trigger.id == trigger_id + for field, value in preserved_fields.items(): + assert saved[0][field] == value + restart_states.append(trigger.enabled) + return {"workflowId": workflow_id, "state": "running" if trigger.enabled else "stopped"} + + monkeypatch.setattr(workflow_routes, "_read_workflow_from_fs", lambda workflow_id: data) + monkeypatch.setattr(workflow_routes, "_write_workflow_to_fs", _fake_write) + monkeypatch.setattr(manager_path, SimpleNamespace(restart_workflow=_fake_restart)) + + for enabled in (False, True, False, True): + response = await client.post( + f"/api/workflow/wf-1/{endpoint}", json={**settings, "enabled": enabled}, + ) + assert response.status_code == 200, response.text + assert data["workflowJson"]["triggers"][0]["concurrency"] == expected + + assert restart_states == [False, True, False, True] diff --git a/tests/server/routes/test_workflow_routes_hardening_regressions.py b/tests/server/routes/test_workflow_routes_hardening_regressions.py index 6697cb743..fd3951bf7 100644 --- a/tests/server/routes/test_workflow_routes_hardening_regressions.py +++ b/tests/server/routes/test_workflow_routes_hardening_regressions.py @@ -467,3 +467,38 @@ def _request(role: str) -> Any: assert all("apiKey" not in item for item in listed) # In-process callers without a request keep the full record. assert (await workflow_module.get_workflow_service("w"))["apiKey"] == "secret-key" + + +@pytest.mark.asyncio +@pytest.mark.parametrize("method", ["post", "put"]) +async def test_trigger_save_preserves_omitted_fields_and_applies_explicit_resets( + client: AsyncClient, quiet_trigger_runtime: None, method: str, +) -> None: + trigger = { + "id": "alerts", "type": "kafka", "enabled": True, + "source": {"inputTopic": "alerts"}, + "concurrency": {"policy": "queue", "maxParallel": 6, "queueSize": 1000}, + "filter": {"expr": "$.body.severity == 'high'"}, + "inputs": {"region": "east"}, + } + path = _write_workflow("wf-save-fields", _wf_json(triggers=[trigger])) + endpoint = "/api/workflow/wf-save-fields/triggers" + ("/alerts" if method == "put" else "") + + # The unified API and old config forms share the same save semantics. + response = await client.request(method, endpoint, json={"id": "alerts", "type": "kafka", "enabled": False}) + assert response.status_code == 200, response.text + saved = json.loads((path / "workflow.json").read_text())["triggers"][0] + assert saved["enabled"] is False + for field in ("source", "concurrency", "filter", "inputs"): + assert saved[field] == trigger[field] + + # Explicit reset values must still take effect, rather than inheriting old values. + response = await client.request(method, endpoint, json={ + "id": "alerts", "type": "kafka", "concurrency": {}, "filter": None, "inputs": {}, + }) + assert response.status_code == 200, response.text + saved = json.loads((path / "workflow.json").read_text())["triggers"][0] + assert saved["concurrency"] == {"policy": "allow", "maxParallel": 1, "queueSize": 100} + assert saved.get("filter") is None + assert saved["inputs"] == {} + assert saved["enabled"] is False diff --git a/tests/server/test_app_cors.py b/tests/server/test_app_cors.py index 295a2266e..001ee4764 100644 --- a/tests/server/test_app_cors.py +++ b/tests/server/test_app_cors.py @@ -1,5 +1,7 @@ import json +import pytest + from flocks.server import app as app_module @@ -47,6 +49,24 @@ def test_read_cors_config_ignores_localhost_and_wildcard_runtime_hosts(monkeypat assert allow_origin_regex is None +@pytest.mark.parametrize("wildcard", ["0.0.0.0", "::"]) +def test_read_cors_config_wildcard_bind_allows_only_loopback_origins(monkeypatch, tmp_path, wildcard) -> None: + """``flocks start`` binds 0.0.0.0 by default: this machine's origins, not every host.""" + config_file = tmp_path / "missing.json" + monkeypatch.setattr(app_module.Config, "get_config_file", lambda: config_file) + monkeypatch.setenv("_FLOCKS_WEBUI_HOST", wildcard) + monkeypatch.setenv("_FLOCKS_WEBUI_PORT", "5173") + + allow_origins, allow_origin_regex = app_module._read_cors_config() + + assert allow_origins == [ + "http://127.0.0.1:5173", + "http://[::1]:5173", + "http://localhost:5173", + ] + assert allow_origin_regex is None + + def test_read_cors_config_brackets_ipv6_webui_origin(monkeypatch, tmp_path) -> None: config_file = tmp_path / "missing.json" monkeypatch.setattr(app_module.Config, "get_config_file", lambda: config_file) diff --git a/tests/server/test_server_port_config.py b/tests/server/test_server_port_config.py index ed973f541..b6290d5d1 100644 --- a/tests/server/test_server_port_config.py +++ b/tests/server/test_server_port_config.py @@ -14,6 +14,8 @@ from types import SimpleNamespace from unittest.mock import patch +import pytest + from typer.testing import CliRunner from flocks.config.config import Config @@ -380,11 +382,30 @@ def test_service_config_default_public_port_is_webui_port(self, monkeypatch): config = cli_main._service_config() - assert config.backend_host == "127.0.0.1" + # Every interface by default; the legacy backend it cleans up stays where it was. + assert config.backend_host == "0.0.0.0" assert config.backend_port == 5173 - assert config.frontend_host == "127.0.0.1" + assert config.frontend_host == "0.0.0.0" assert config.frontend_port == 5173 + assert config.legacy_backend_host == "127.0.0.1" assert config.legacy_backend_port == 8000 + assert config.backend_url == "http://127.0.0.1:5173" + + @pytest.mark.parametrize("via", ["cli", "env"]) + def test_service_config_loopback_host_keeps_it_on_this_machine(self, monkeypatch, via): + """``--host 127.0.0.1`` / ``FLOCKS_HOST=127.0.0.1`` still listen on loopback only.""" + for name in ("FLOCKS_HOST", "FLOCKS_PORT", "FLOCKS_PUBLIC_HOST", "FLOCKS_PUBLIC_PORT", + "FLOCKS_SERVER_HOST", "FLOCKS_SERVER_PORT", "FLOCKS_WEBUI_HOST", "FLOCKS_WEBUI_PORT"): + monkeypatch.delenv(name, raising=False) + Config._global_config = None + if via == "env": + monkeypatch.setenv("FLOCKS_HOST", "127.0.0.1") + config = cli_main._service_config() + else: + config = cli_main._service_config(host="127.0.0.1") + + assert config.backend_host == config.frontend_host == "127.0.0.1" + assert config.backend_port == 5173 def test_service_config_prefers_public_values(self, monkeypatch): """Test unified public values override legacy CLI and environment values.""" diff --git a/tests/server/test_tool_setting_routes.py b/tests/server/test_tool_setting_routes.py index 4f4d75dc7..de2c27390 100644 --- a/tests/server/test_tool_setting_routes.py +++ b/tests/server/test_tool_setting_routes.py @@ -403,6 +403,233 @@ def test_reload_path_refreshes_enabled_default(self, tool_client): ) +class TestServiceEnabledFlag: + """``service_enabled`` tells a client why a tool is off and cannot be opened. + + Regression for INC-F5C08C1C: the status switch of a tool whose API + service is disabled did nothing visible, because the refused PATCH + answers 200 with ``enabled=false`` and nothing said why. + """ + + def test_refused_enable_reports_the_disabled_service(self, tool_client): + client, enabled_tool, _ = tool_client + _set_service(enabled=False) + name = enabled_tool.info.name + + before = client.get(f"/api/tools/{name}").json() + assert (before["enabled"], before["service_enabled"]) == (False, False) + + res = client.patch(f"/api/tools/{name}", json={"enabled": True}) + assert res.status_code == 200, res.text + body = res.json() + # The gate itself is unchanged: the tool stays off ... + assert body["enabled"] is False + # ... and the answer now carries the reason. + assert body["service_enabled"] is False + + def test_follows_the_service_flag(self, tool_client): + client, enabled_tool, _ = tool_client + name = enabled_tool.info.name + + # No api_services entry at all counts as off, exactly like the gate. + body = client.get(f"/api/tools/{name}").json() + assert (body["enabled"], body["service_enabled"]) == (False, False) + + _set_service(enabled=True) + body = client.get(f"/api/tools/{name}").json() + assert (body["enabled"], body["service_enabled"]) == (True, True) + + _set_service(enabled=False) + body = client.get(f"/api/tools/{name}").json() + assert (body["enabled"], body["service_enabled"]) == (False, False) + + def test_list_rows_carry_the_flag(self, tool_client): + client, enabled_tool, disabled_tool = tool_client + _set_service(enabled=False) + + rows = {row["name"]: row for row in client.get("/api/tools/page").json()["items"]} + assert rows[enabled_tool.info.name]["service_enabled"] is False + assert rows[enabled_tool.info.name]["enabled"] is False + listed = {row["name"]: row for row in client.get("/api/tools").json()} + assert listed[disabled_tool.info.name]["service_enabled"] is False + + # The paged list is served from a snapshot: a service change must show. + _set_service(enabled=True) + rows = {row["name"]: row for row in client.get("/api/tools/page").json()["items"]} + assert rows[enabled_tool.info.name]["service_enabled"] is True + assert rows[enabled_tool.info.name]["enabled"] is True + assert rows[disabled_tool.info.name]["service_enabled"] is True + assert rows[disabled_tool.info.name]["enabled"] is False + + def test_null_without_an_owning_service(self, tool_client): + client, _, _ = tool_client + + async def handler(ctx: ToolContext) -> ToolResult: + return ToolResult(success=True, output="ok") + + ToolRegistry.register(Tool( + info=ToolInfo( + name="plain_tool_test", + description="a tool no service gates", + category=ToolCategory.CUSTOM, + enabled=True, + ), + handler=handler, + )) + + body = client.get("/api/tools/plain_tool_test").json() + assert (body["enabled"], body["service_enabled"]) == (True, None) + assert body["service_integration_type"] is None + body = client.patch("/api/tools/plain_tool_test", json={"enabled": False}).json() + assert (body["enabled"], body["service_enabled"]) == (False, None) + body = client.patch("/api/tools/plain_tool_test", json={"enabled": True}).json() + assert (body["enabled"], body["service_enabled"]) == (True, None) + rows = {row["name"]: row for row in client.get("/api/tools/page").json()["items"]} + assert rows["plain_tool_test"]["service_enabled"] is None + + def test_provider_gate_is_reported_for_other_sources(self, tool_client): + """The gate keys on ``provider`` whatever the source; report it there too. + + A YAML plugin tool with a provider is not an api/device tool, yet the + registry forces it off while the provider's service is off and PATCH + refuses to open it. Without the flag it would be the same dead switch. + """ + client, _, _ = tool_client + tool = _stub_api_tool("yaml_plugin_tool_test", enabled=True) + tool.info.source = "plugin_yaml" + ToolRegistry.register(tool) + _set_service(enabled=False) + name = tool.info.name + + body = client.get(f"/api/tools/{name}").json() + assert body["source"] == "plugin_yaml" + assert (body["enabled"], body["service_enabled"]) == (False, False) + body = client.patch(f"/api/tools/{name}", json={"enabled": True}).json() + assert (body["enabled"], body["service_enabled"]) == (False, False) + + _set_service(enabled=True) + body = client.get(f"/api/tools/{name}").json() + assert (body["enabled"], body["service_enabled"]) == (True, True) + + + def test_reports_where_the_owning_service_is_managed(self, tool_client, tmp_path, monkeypatch): + """A device plugin installed under ``tools/api`` loads as an ``api`` tool. + + Its service is still managed on the device page: the API service list + reports ``integration_type: device`` and the API tab leaves it out. + The tool response has to carry the same answer, or a client that goes + by ``source`` sends the user to a tab that cannot show the service. + """ + from types import SimpleNamespace + + from flocks.server.routes import provider as provider_routes + from flocks.server.routes.tool import _invalidate_tool_summary_cache + + client, enabled_tool, _ = tool_client + _set_service(enabled=False) + name = enabled_tool.info.name + provider_yaml = tmp_path / "plugins" / "tools" / "api" / "legacy_device" / "_provider.yaml" + provider_yaml.parent.mkdir(parents=True) + descriptor = SimpleNamespace( + service_id=_TEST_SERVICE_ID, + version=None, + storage_key=_TEST_SERVICE_ID, + provider_yaml=provider_yaml, + ) + monkeypatch.setattr( + provider_routes, + "_find_api_service_descriptor", + lambda provider_id: descriptor if provider_id == _TEST_SERVICE_ID else None, + ) + + def declared(integration_type): + lines = [f"name: {_TEST_SERVICE_ID}"] + if integration_type is not None: + lines.append(f"integration_type: {integration_type}") + provider_yaml.write_text("\n".join(lines) + "\n", encoding="utf-8") + provider_routes._clear_api_service_summary_metadata_cache() + _invalidate_tool_summary_cache() + detail = client.get(f"/api/tools/{name}").json() + rows = {row["name"]: row for row in client.get("/api/tools/page").json()["items"]} + listed = {row["name"]: row for row in client.get("/api/tools").json()} + assert detail["source"] == "api" + assert detail["service_enabled"] is False + return ( + detail["service_integration_type"], + rows[name]["service_integration_type"], + listed[name]["service_integration_type"], + ) + + try: + assert declared("device") == ("device", "device", "device") + # The refused enable carries it too: that answer is what the drawer renders. + body = client.patch(f"/api/tools/{name}", json={"enabled": True}).json() + assert (body["enabled"], body["service_integration_type"]) == (False, "device") + assert declared('" Device "') == ("device", "device", "device") + assert declared("api") == ("api", "api", "api") + assert declared(None) == (None, None, None) + finally: + provider_routes._clear_api_service_summary_metadata_cache() + + def test_unreadable_service_metadata_does_not_break_the_tool_list(self, tool_client, monkeypatch): + from flocks.server.routes import provider as provider_routes + from flocks.server.routes.tool import _invalidate_tool_summary_cache + + client, enabled_tool, _ = tool_client + _set_service(enabled=False) + + def broken(provider_id): + raise ValueError("corrupt metadata") + + monkeypatch.setattr(provider_routes, "_load_api_service_summary_metadata_data", broken) + _invalidate_tool_summary_cache() + + page = client.get("/api/tools/page") + assert page.status_code == 200, page.text + rows = {row["name"]: row for row in page.json()["items"]} + assert rows[enabled_tool.info.name]["service_enabled"] is False + assert rows[enabled_tool.info.name]["service_integration_type"] is None + detail = client.get(f"/api/tools/{enabled_tool.info.name}") + assert detail.status_code == 200, detail.text + + def test_list_reads_each_service_once_not_once_per_tool(self, tool_client, monkeypatch): + """``get_api_service_raw`` re-reads and parses flocks.json on every call. + + One list response builds a row per tool; the service facts for those + rows must cost one lookup per service, however many tools share it. + """ + from flocks.config.config_writer import ConfigWriter + from flocks.server.routes.tool import _invalidate_tool_summary_cache + + client, _, _ = tool_client + _set_service(enabled=True) + calls: list[str] = [] + original = ConfigWriter.get_api_service_raw.__func__ + + def counting(cls, service_id): + calls.append(service_id) + return original(cls, service_id) + + monkeypatch.setattr(ConfigWriter, "get_api_service_raw", classmethod(counting)) + + def reads(path: str) -> int: + _invalidate_tool_summary_cache() + calls.clear() + assert client.get(path).status_code == 200 + return len(calls) + + paths = ("/api/tools/page", "/api/tools") + for path in paths: + reads(path) # the first lookup also fills the service metadata cache + few = {path: reads(path) for path in paths} + for idx in range(10): + ToolRegistry.register(_stub_api_tool(f"bulk_tool_test_{idx}", enabled=True)) + many = {path: reads(path) for path in paths} + + assert all(count > 0 for count in few.values()), few + assert many == few, (few, many) + + class TestUpdateTool: def test_manual_reenable_clears_repeated_failure_count(self, tool_client): client, enabled_tool, _ = tool_client diff --git a/tests/session/test_agent_session_policy.py b/tests/session/test_agent_session_policy.py index f027a6bac..52862446a 100644 --- a/tests/session/test_agent_session_policy.py +++ b/tests/session/test_agent_session_policy.py @@ -325,6 +325,82 @@ async def test_session_create_applies_agent_directory_and_memory_policy( assert session.memory_enabled is False +@pytest.mark.asyncio +async def test_agent_policy_never_turns_memory_back_on_for_a_child( + policy_storage, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + # A delegatable dedicated agent whose own policy keeps Memory on. + delegate = AgentInfo( + name="dedicated-delegate", + mode="subagent", + tools=["bash"], + memory_enabled=True, + require_dedicated_session=True, + ) + agents = {"rex": _ordinary_agent(), delegate.name: delegate} + + async def get(name): + return agents.get(name) + + monkeypatch.setattr(Agent, "get", get) + parent = await Session.create( + project_id="policy-project", directory=str(tmp_path), agent="rex", memory_enabled=False, + ) + child = await Session.create( + project_id="policy-project", directory=str(tmp_path), agent=delegate.name, parent_id=parent.id, + ) + root = await Session.create(project_id="policy-project", directory=str(tmp_path), agent=delegate.name) + + prepared_child = await prepare_session_for_agent(child, delegate) + prepared_root = await prepare_session_for_agent(root, delegate) + + assert child.memory_enabled is False + assert prepared_child.memory_enabled is False + assert (await Session.get_by_id_unfiltered(child.id)).memory_enabled is False + # Without a parent that keeps no Memory, the agent's policy still applies. + assert prepared_root.memory_enabled is True + + +@pytest.mark.asyncio +async def test_agent_policy_keeps_memory_off_when_the_parent_cannot_be_read( + policy_storage, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + delegate = AgentInfo( + name="dedicated-delegate", + mode="subagent", + tools=["bash"], + memory_enabled=True, + require_dedicated_session=True, + ) + agents = {"rex": _ordinary_agent(), delegate.name: delegate} + + async def get(name): + return agents.get(name) + + monkeypatch.setattr(Agent, "get", get) + parent = await Session.create( + project_id="policy-project", directory=str(tmp_path), agent="rex", memory_enabled=False, + ) + child = await Session.create( + project_id="policy-project", directory=str(tmp_path), agent=delegate.name, parent_id=parent.id, + ) + read = Session.get_by_id_unfiltered.__func__ + + async def unreadable_parent(cls, session_id): + # A failed read comes back as no session (Session.get_by_id). + return None if session_id == parent.id else await read(cls, session_id) + + monkeypatch.setattr(Session, "get_by_id_unfiltered", classmethod(unreadable_parent)) + prepared = await prepare_session_for_agent(child, delegate) + + assert prepared.memory_enabled is False + assert (await Session.get_by_id_unfiltered(child.id)).memory_enabled is False + + @pytest.mark.asyncio async def test_isolated_agent_binding_cannot_be_switched_away( policy_storage, diff --git a/tests/session/test_session_activity_events.py b/tests/session/test_session_activity_events.py new file mode 100644 index 000000000..ecda2d6a7 --- /dev/null +++ b/tests/session/test_session_activity_events.py @@ -0,0 +1,209 @@ +"""A session continued from the history goes to the top of the session lists. + +INC-CB90DF32: lists sort by ``time.updated``, newest first, and the WebUI +history refreshes on ``session.*`` events. A turn only touched the session at +its end and said nothing, so a session continued from the history kept its +place in a list already on screen. The loop now touches the session as the +turn starts and as it ends, and announces ``session.updated`` each time. + +Case list (编号 | 场景): + SA1 a root session's turn: touched and announced as it starts (after busy, before + the turn runs) and as it ends (after idle), each announcement after its touch + SA2 a sub-agent session's turn: touched as well, never announced (not a row of + the lists; its turns would only make them refetch) + SA3 a touch that fails neither stops the turn nor is announced + SA4 real storage: two sessions, the older one continued -- the project's list + puts it first before the turn runs, and the events name it + SA5 a session the lists leave out (category test, hideFromSessionManager: an + agent's test run) is touched, never announced + SA6 a touch that writes nothing (the session archived meanwhile) is not + announced, and the turn still ends with its idle notice + SA7 a Session whose touch returns nothing (the Pro edition's, which takes the + open one's place): the loop goes by update, which says what it wrote +""" + +from __future__ import annotations + +import asyncio +from pathlib import Path +from unittest.mock import AsyncMock, patch + +import pytest + +import flocks.session.session_loop as loop_mod +from flocks.bus.events import SessionIdle +from flocks.session.session import Session, SessionInfo +from flocks.session.session_loop import LoopCallbacks, LoopResult, SessionLoop +from flocks.storage.storage import Storage + + +def _info(session_id: str, *, parent_id: str | None = None, category: str = "user", metadata: dict | None = None) -> SessionInfo: + return SessionInfo.model_construct( + id=session_id, slug="t", project_id="proj", directory="/tmp", title="t", parent_id=parent_id, + category=category, metadata=metadata or {}, + ) + + +def _recorder(written: SessionInfo | None): + """What happened, in order: touches -- Session.update with nothing to change, answering + *written* as it does -- and published events.""" + seen: list[tuple] = [] + + async def touch(project_id: str, session_id: str, **updates): + assert not updates, updates + seen.append(("touch", session_id)) + return written + + async def publish(event_type: str, properties: dict) -> None: + if event_type == "session.status": + seen.append((event_type, properties["status"]["type"])) + else: + seen.append((event_type, properties.get("id"))) + + return seen, touch, publish + + +async def _run(session_info: SessionInfo, *, touch, publish, get_by_id=None, run_loop=None, bus=None, session_touch=None) -> LoopResult: + async def stop(*_args, **_kwargs): + return LoopResult(action="stop") + + with patch.object(loop_mod.Session, "get_by_id", get_by_id or AsyncMock(return_value=session_info)), \ + patch.object(loop_mod.Message, "list", AsyncMock(return_value=[])), \ + patch("flocks.session.orphan_tools.abort_orphan_running_parts", AsyncMock(return_value=0)), \ + patch.object(SessionLoop, "_run_loop", AsyncMock(side_effect=run_loop or stop)), \ + patch.object(SessionLoop, "_settle_todos", AsyncMock()), \ + patch.object(loop_mod.Session, "update", touch), \ + patch.object(loop_mod.Session, "touch", session_touch or AsyncMock(return_value=None)), \ + patch("flocks.bus.bus.Bus.publish", bus or AsyncMock()): + return await SessionLoop.run( + session_id=session_info.id, provider_id="p", model_id="m", agent_name="rex", + callbacks=LoopCallbacks(event_publish_callback=publish), + ) + + +@pytest.mark.asyncio +async def test_sa1_a_root_session_is_touched_and_announced_as_its_turn_starts_and_ends(): + session = _info("ses_sa1") + seen, touch, publish = _recorder(session) + at_turn: list[tuple] = [] + + async def run_loop(*_args, **_kwargs): + # The list is told before the turn runs, not after it. + at_turn.extend(seen) + return LoopResult(action="stop") + + result = await _run(session, touch=touch, publish=publish, run_loop=run_loop) + + assert result.action == "stop" + assert at_turn == [("session.status", "busy"), ("touch", "ses_sa1"), ("session.updated", "ses_sa1")] + assert seen == [ + ("session.status", "busy"), + ("touch", "ses_sa1"), + ("session.updated", "ses_sa1"), + ("session.status", "idle"), + ("touch", "ses_sa1"), + ("session.updated", "ses_sa1"), + ] + + +@pytest.mark.asyncio +async def test_sa2_a_sub_agent_session_is_touched_but_not_announced(): + child = _info("ses_sa2_child", parent_id="ses_sa2_parent") + seen, touch, publish = _recorder(child) + + await _run(child, touch=touch, publish=publish) + + assert seen.count(("touch", "ses_sa2_child")) == 2 + assert not [entry for entry in seen if entry[0] == "session.updated"] + + +@pytest.mark.asyncio +async def test_sa3_a_touch_that_fails_neither_stops_the_turn_nor_is_announced(): + seen, _touch, publish = _recorder(None) + + async def failing_touch(project_id: str, session_id: str, **updates): + raise RuntimeError("storage is busy") + + result = await _run(_info("ses_sa3"), touch=failing_touch, publish=publish) + + assert result.action == "stop" + assert seen == [("session.status", "busy"), ("session.status", "idle")] + + +@pytest.mark.parametrize("hidden", [ + pytest.param({"category": "test"}, id="agent-test-category"), + pytest.param({"metadata": {"hideFromSessionManager": True}}, id="hidden-from-session-manager"), +]) +@pytest.mark.asyncio +async def test_sa5_a_session_the_lists_leave_out_is_touched_but_not_announced(hidden: dict): + session = _info("ses_sa5", **hidden) + seen, touch, publish = _recorder(session) + + await _run(session, touch=touch, publish=publish) + + assert seen.count(("touch", "ses_sa5")) == 2 + assert not [entry for entry in seen if entry[0] == "session.updated"] + + +@pytest.mark.asyncio +async def test_sa6_a_touch_that_writes_nothing_is_not_announced_and_the_turn_still_says_idle(): + seen, touch, publish = _recorder(None) # Session.update wrote nothing: archived meanwhile + bus = AsyncMock() + + result = await _run(_info("ses_sa6"), touch=touch, publish=publish, bus=bus) + + assert result.action == "stop" + assert seen == [("session.status", "busy"), ("touch", "ses_sa6"), ("session.status", "idle"), ("touch", "ses_sa6")] + assert any(call.args and call.args[0] is SessionIdle for call in bus.await_args_list) + + +@pytest.fixture +async def activity_storage(tmp_path: Path): + await Storage.init(tmp_path / "activity.db") + Session.invalidate_cache() + yield + for prefix in ("session:", "message:", "message_parts:"): + await Storage.clear(prefix) + Session.invalidate_cache() + + +@pytest.mark.asyncio +async def test_sa4_the_continued_session_goes_first_in_its_projects_list(activity_storage, tmp_path: Path): + older = await Session.create(project_id="proj-sa4", directory=str(tmp_path), title="older") + await asyncio.sleep(0.01) + newer = await Session.create(project_id="proj-sa4", directory=str(tmp_path), title="newer") + assert [s.id for s in await Session.list("proj-sa4")] == [newer.id, older.id] + + events: list[tuple[str, dict]] = [] + at_turn: dict = {} + + async def publish(event_type: str, properties: dict) -> None: + events.append((event_type, properties)) + + async def run_loop(*_args, **_kwargs): + at_turn["order"] = [s.id for s in await Session.list("proj-sa4")] + at_turn["updated"] = [props for kind, props in events if kind == "session.updated"] + return LoopResult(action="stop") + + await asyncio.sleep(0.01) + await _run(older, touch=Session.update, publish=publish, get_by_id=Session.get_by_id, run_loop=run_loop, + session_touch=Session.touch) + + # Already first, and said so, as the turn starts; still first after it. + assert at_turn == {"order": [older.id, newer.id], "updated": [{"id": older.id}]} + assert [s.id for s in await Session.list("proj-sa4")] == [older.id, newer.id] + assert [props for kind, props in events if kind == "session.updated"] == [{"id": older.id}, {"id": older.id}] + + +@pytest.mark.asyncio +async def test_sa7_the_loop_goes_by_update_not_by_touch_whose_return_says_nothing(): + """INC-CB90DF32 review: the Pro edition's Session takes this one's place, and its touch + returns nothing even when it wrote; the loop must not take that for "nothing written".""" + session = _info("ses_sa7") + seen, update, publish = _recorder(session) + pro_touch = AsyncMock(return_value=None) + + await _run(session, touch=update, publish=publish, session_touch=pro_touch) + + assert [entry for entry in seen if entry[0] == "session.updated"] == [("session.updated", "ses_sa7")] * 2 + pro_touch.assert_not_awaited() diff --git a/tests/session/test_session_child_memory.py b/tests/session/test_session_child_memory.py new file mode 100644 index 000000000..e80f2c54f --- /dev/null +++ b/tests/session/test_session_child_memory.py @@ -0,0 +1,37 @@ +"""A child session never keeps Memory its parent does not.""" + +import pytest + +from flocks.session.session import Session + + +@pytest.mark.asyncio +async def test_child_of_session_without_memory_has_none(tmp_path): + parent = await Session.create(project_id="p", directory=str(tmp_path), agent="rex", memory_enabled=False) + + delegate = await Session.create(project_id="p", directory=str(tmp_path), agent="explore", parent_id=parent.id) + # Asking for Memory does not override the parent's choice either. + asked = await Session.create( + project_id="p", directory=str(tmp_path), agent="explore", parent_id=parent.id, memory_enabled=True, + ) + grandchild = await Session.create(project_id="p", directory=str(tmp_path), agent="explore", parent_id=delegate.id) + + assert parent.memory_enabled is False + assert delegate.memory_enabled is False + assert asked.memory_enabled is False + assert grandchild.memory_enabled is False + stored = await Session.get_by_id(delegate.id) + assert stored is not None and stored.memory_enabled is False + + +@pytest.mark.asyncio +async def test_child_of_session_with_memory_keeps_its_own_default(tmp_path): + parent = await Session.create(project_id="p", directory=str(tmp_path), agent="rex") + child = await Session.create(project_id="p", directory=str(tmp_path), agent="explore", parent_id=parent.id) + opted_out = await Session.create( + project_id="p", directory=str(tmp_path), agent="explore", parent_id=parent.id, memory_enabled=False, + ) + + assert parent.memory_enabled is True + assert child.memory_enabled is True + assert opted_out.memory_enabled is False diff --git a/tests/test_ca_certs.py b/tests/test_ca_certs.py new file mode 100644 index 000000000..704700d04 --- /dev/null +++ b/tests/test_ca_certs.py @@ -0,0 +1,230 @@ +""" +Tests for flocks/ca_certs.py: root certificates where OpenSSL's defaults find none. + +The file system layouts are built under tmp_path and stand in for the real +ones; OpenSSL's default locations are what ``ssl.get_default_verify_paths`` +reports, patched to point there. +""" + +from __future__ import annotations + +import os +import ssl +import sys +import types +from pathlib import Path + +import pytest + +from flocks import ca_certs + +PEM = "-----BEGIN CERTIFICATE-----\nMIIB\n-----END CERTIFICATE-----\n" + + +def _clear_cert_env(monkeypatch) -> None: + """No SSL_CERT_* now, and none left behind by what the test sets (delenv alone records nothing to undo).""" + for name in ("SSL_CERT_FILE", "SSL_CERT_DIR"): + monkeypatch.setenv(name, "") + monkeypatch.delenv(name) + + +def _defaults(cafile: Path, capath: Path) -> ssl.DefaultVerifyPaths: + """What get_default_verify_paths returns when OpenSSL was built to look at *cafile* and *capath*.""" + return ssl.DefaultVerifyPaths( + str(cafile) if cafile.is_file() else None, + str(capath) if capath.is_dir() else None, + "SSL_CERT_FILE", + str(cafile), + "SSL_CERT_DIR", + str(capath), + ) + + +@pytest.fixture +def machine(tmp_path, monkeypatch): + """A Linux machine whose OpenSSL looks in /etc/ssl, and whose bundles are under .""" + root = tmp_path / "root" + (root / "etc/ssl").mkdir(parents=True) + monkeypatch.setattr(sys, "platform", "linux") + _clear_cert_env(monkeypatch) + monkeypatch.setattr( + ssl, + "get_default_verify_paths", + lambda: _defaults(root / "etc/ssl/cert.pem", root / "etc/ssl/certs"), + ) + monkeypatch.setattr( + ca_certs, + "SYSTEM_BUNDLES", + tuple(str(root / path.lstrip("/")) for path in ca_certs.SYSTEM_BUNDLES), + ) + # certifi's bundle, unless a test takes it away. + certifi_bundle = tmp_path / "certifi" / "cacert.pem" + certifi_bundle.parent.mkdir() + certifi_bundle.write_text(PEM) + import certifi + + monkeypatch.setattr(certifi, "where", lambda: str(certifi_bundle)) + return types.SimpleNamespace(root=root, certifi=certifi_bundle) + + +def _rhel8(root: Path) -> None: + """RHEL 8's layout: no /etc/ssl/cert.pem; /etc/ssl/certs links to a directory without hashed names.""" + extracted = root / "etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem" + extracted.parent.mkdir(parents=True) + extracted.write_text(PEM) + certs = root / "etc/pki/tls/certs" + certs.mkdir(parents=True) + (certs / "ca-bundle.crt").symlink_to(extracted) + (certs / "ca-bundle.trust.crt").write_text(PEM) + (root / "etc/pki/tls/cert.pem").symlink_to(extracted) + (root / "etc/ssl/certs").symlink_to(certs) + + +def test_rhel8_layout_gets_the_system_bundle(machine): + _rhel8(machine.root) + environ: dict[str, str] = {} + + chosen = ca_certs.ensure(environ) + + assert chosen == str(machine.root / "etc/pki/tls/cert.pem") + assert environ == {"SSL_CERT_FILE": chosen} + + +def test_sets_the_process_environment_by_default(machine): + _rhel8(machine.root) + + chosen = ca_certs.ensure() + + assert chosen is not None + assert os.environ["SSL_CERT_FILE"] == chosen + + +def test_default_cafile_present_changes_nothing(machine): + _rhel8(machine.root) + (machine.root / "etc/ssl/cert.pem").write_text(PEM) # RHEL 9, Alpine, macOS + environ: dict[str, str] = {} + + assert ca_certs.ensure(environ) is None + assert environ == {} + + +def test_hashed_default_directory_changes_nothing(machine): + certs = machine.root / "etc/ssl/certs" # Debian and Ubuntu: no cert.pem, a hashed directory + certs.mkdir() + (certs / "ca-certificates.crt").write_text(PEM) + (certs / "5ad8a5d6.0").symlink_to(certs / "ca-certificates.crt") + environ: dict[str, str] = {} + + assert ca_certs.ensure(environ) is None + assert environ == {} + + +def test_empty_default_cafile_holds_no_certificates(machine): + _rhel8(machine.root) + (machine.root / "etc/ssl/cert.pem").write_text("") # there, but OpenSSL loads nothing from it + environ: dict[str, str] = {} + + # The empty default is skipped as a candidate too. + assert ca_certs.ensure(environ) == str(machine.root / "etc/pki/tls/cert.pem") + + +def test_unreadable_default_cafile_holds_no_certificates(machine, monkeypatch): + _rhel8(machine.root) + default = machine.root / "etc/ssl/cert.pem" + default.write_text(PEM) + real_access = os.access + # As for a service account the file's mode leaves out (chmod does not stop root, who runs CI). + monkeypatch.setattr(ca_certs.os, "access", lambda path, mode: path != str(default) and real_access(path, mode)) + environ: dict[str, str] = {} + + assert ca_certs.ensure(environ) == str(machine.root / "etc/pki/tls/cert.pem") + + +@pytest.mark.parametrize("broken", ["dangling link", "empty file", "directory"]) +def test_hashed_names_that_hold_nothing_do_not_count(machine, broken): + _rhel8(machine.root) + certs = machine.root / "etc/pki/tls/certs" # what /etc/ssl/certs links to + hashed = certs / "5ad8a5d6.0" + if broken == "dangling link": + hashed.symlink_to(certs / "removed.pem") + elif broken == "empty file": + hashed.write_text("") + else: + hashed.mkdir() + environ: dict[str, str] = {} + + assert ca_certs.ensure(environ) == str(machine.root / "etc/pki/tls/cert.pem") + + +@pytest.mark.parametrize("name", ["SSL_CERT_FILE", "SSL_CERT_DIR"]) +def test_certificates_the_environment_names_win(machine, name): + _rhel8(machine.root) + # Even a path that is not there: the operator's choice, not ours to replace. + environ = {name: "/srv/missing-bundle.pem"} + + assert ca_certs.ensure(environ) is None + assert environ == {name: "/srv/missing-bundle.pem"} + + +def test_no_system_bundle_falls_back_to_certifi(machine): + environ: dict[str, str] = {} + + assert ca_certs.ensure(environ) == str(machine.certifi) + assert environ["SSL_CERT_FILE"] == str(machine.certifi) + + +def test_empty_bundles_are_passed_over(machine): + debian = machine.root / "etc/ssl/certs/ca-certificates.crt" + debian.parent.mkdir(parents=True) + debian.write_text("") # ca-certificates installed but never generated + suse = machine.root / "etc/ssl/ca-bundle.pem" + suse.write_text(PEM) + environ: dict[str, str] = {} + + assert ca_certs.ensure(environ) == str(suse) + + +def test_nothing_to_point_at_changes_nothing(machine, monkeypatch): + import certifi + + monkeypatch.setattr(certifi, "where", lambda: str(machine.root / "no-such-cacert.pem")) + environ: dict[str, str] = {} + + assert ca_certs.ensure(environ) is None + assert environ == {} + + +def test_without_certifi_installed_changes_nothing(machine, monkeypatch): + monkeypatch.setitem(sys.modules, "certifi", None) # import certifi raises ImportError + environ: dict[str, str] = {} + + assert ca_certs.ensure(environ) is None + assert environ == {} + + +@pytest.mark.parametrize("platform", ["darwin", "win32"]) +def test_other_platforms_are_left_alone(machine, monkeypatch, platform): + monkeypatch.setattr(sys, "platform", platform) + environ: dict[str, str] = {} + + assert ca_certs.ensure(environ) is None + assert environ == {} + + +def test_bundle_it_sets_is_what_a_default_context_loads(tmp_path, monkeypatch): + """End to end through OpenSSL: a default context created afterwards trusts the bundle.""" + import certifi + + real_bundle = certifi.where() + monkeypatch.setattr(sys, "platform", "linux") + _clear_cert_env(monkeypatch) + empty = tmp_path / "empty" + empty.mkdir() + monkeypatch.setattr(ssl, "get_default_verify_paths", lambda: _defaults(empty / "cert.pem", empty)) + monkeypatch.setattr(ca_certs, "SYSTEM_BUNDLES", ()) + + assert ca_certs.ensure() == real_bundle + + stats = ssl.create_default_context().cert_store_stats() + expected = ssl.create_default_context(cafile=real_bundle).cert_store_stats() + assert stats["x509_ca"] >= expected["x509_ca"] > 0 diff --git a/tests/test_db_backend.py b/tests/test_db_backend.py index 5c0a34948..e30d804d0 100644 --- a/tests/test_db_backend.py +++ b/tests/test_db_backend.py @@ -786,7 +786,9 @@ def test_coordination_answers_for_one_process(): assert asyncio.run(coordination.sessions_running_elsewhere()) == [] assert coordination.page_api_database() is None - assert coordination.workflow_services(lambda: False) == {} + # The SOC suite's data service: what its triage workflow writes and its pages read through. + assert set(coordination.workflow_services(lambda: False)) == {"soc"} + assert set(coordination.page_api_services()) == {"soc"} def test_coordination_recognises_a_duplicate_key_on_either_database(): diff --git a/tests/tool/test_device_plugin_index.py b/tests/tool/test_device_plugin_index.py index 2b2e2d203..b260b3614 100644 --- a/tests/tool/test_device_plugin_index.py +++ b/tests/tool/test_device_plugin_index.py @@ -2,6 +2,8 @@ import asyncio import json +import threading +import time from pathlib import Path from types import SimpleNamespace @@ -36,6 +38,15 @@ def _write_tool(root: Path, name: str = "device_ping") -> None: ) +@pytest.fixture(autouse=True) +def _no_recorded_clean_plugin_load(monkeypatch): + """A clean plugin load recorded by an earlier test would let forced + refreshes here skip the (stubbed) reload they are about.""" + from flocks.tool.registry import ToolRegistry + + monkeypatch.setattr(ToolRegistry, "_plugin_sources_stamp", None) + + def _reset_env(monkeypatch, tmp_path): from flocks.config.config import Config from flocks.config import api_versioning @@ -263,6 +274,39 @@ def test_device_template_refresh_reloads_plugin_tools(monkeypatch, tmp_path): assert calls == ["refresh"] +def test_forced_template_refresh_skips_the_reload_when_no_plugin_file_changed(monkeypatch, tmp_path): + """The page forces a refresh on every return to the window. With no plugin + file changed since the last clean load, the tool registry is not reloaded + (seconds of CPU each time), but the template index is still rebuilt.""" + from flocks.tool.device import plugin_index + + _reset_env(monkeypatch, tmp_path) + calls: list[str] = [] + fingerprint = ["same"] + + monkeypatch.setattr(plugin_index.hub_catalog, "list_catalog", lambda plugin_type=None: []) + monkeypatch.setattr( + plugin_index.ToolRegistry, + "refresh_plugin_tools", + classmethod(lambda cls: calls.append("refresh") or []), + ) + monkeypatch.setattr( + plugin_index.ToolRegistry, + "_plugin_sources_fingerprint", + classmethod(lambda cls: (fingerprint[0],)), + ) + monkeypatch.setattr(plugin_index.ToolRegistry, "_plugin_sources_stamp", ("same",)) + monkeypatch.setattr(plugin_index, "_template_cache", ["stale index"]) + + assert plugin_index.list_device_templates(refresh=True) == [] + assert calls == [] + assert plugin_index._template_cache == [] + + fingerprint[0] = "a plugin file changed" + assert plugin_index.list_device_templates(refresh=True) == [] + assert calls == ["refresh"] + + def test_create_custom_device_template_writes_user_plugin(monkeypatch, tmp_path): from flocks.tool.device import plugin_index @@ -307,6 +351,59 @@ def test_create_custom_device_template_writes_user_plugin(monkeypatch, tmp_path) assert records["plugins"]["device:custom_demo"]["type"] == "device" +def test_concurrent_custom_templates_with_one_id_are_created_once(monkeypatch, tmp_path): + """The route creates templates on worker threads: the existence check and + the writes are one step, or both requests pass the check and both 'win'.""" + from flocks.tool.device import plugin_index + + _reset_env(monkeypatch, tmp_path) + monkeypatch.setattr(plugin_index.hub_catalog, "list_catalog", lambda plugin_type=None: []) + monkeypatch.setattr(plugin_index.hub_catalog, "system_plugin_root", lambda plugin_type, plugin_id: None) + monkeypatch.setattr(plugin_index.ToolRegistry, "refresh_plugin_tools", classmethod(lambda cls: [])) + monkeypatch.setattr(plugin_index.ToolRegistry, "init", classmethod(lambda cls: None)) + monkeypatch.setattr(plugin_index.ToolRegistry, "list_tools", classmethod(lambda cls: [])) + + both_checked = threading.Barrier(2, timeout=5) + write_yaml = plugin_index._write_yaml + + def slow_first_write(path, data): + # Both requests reach the writes before either has written anything. + if path.name == "_provider.yaml": + try: + both_checked.wait() + except threading.BrokenBarrierError: + pass + write_yaml(path, data) + + monkeypatch.setattr(plugin_index, "_write_yaml", slow_first_write) + body = CustomDeviceTemplateCreate( + plugin_id="custom_race", + name="Custom Race", + service_id="custom_race_api", + tools=[{"name": "custom_race_ping", "description": "Ping", "handler": {"type": "http", "path": "/ping"}}], + ) + outcomes: list[str] = [] + outcomes_lock = threading.Lock() + + def create() -> None: + try: + plugin_index.create_custom_device_template(body) + outcome = "created" + except FileExistsError: + outcome = "exists" + with outcomes_lock: + outcomes.append(outcome) + + threads = [threading.Thread(target=create) for _ in range(2)] + for thread in threads: + thread.start() + for thread in threads: + thread.join(10) + assert not thread.is_alive() + + assert sorted(outcomes) == ["created", "exists"] + + def test_device_template_route_is_not_shadowed_by_device_id(monkeypatch): from flocks.server.routes import device as device_routes @@ -498,3 +595,357 @@ async def slow_insert_device(**kwargs): assert insert_attempts == 1 assert len(devices) == 1 assert devices[0].storage_key == "custom_demo_api_v0_1_0" + + +def _patch_empty_template_sources(monkeypatch, plugin_index) -> None: + monkeypatch.setattr(plugin_index.hub_catalog, "list_catalog", lambda **kw: []) + monkeypatch.setattr(plugin_index, "_device_tool_counts", lambda: {}) + + +class _CountingCondition(threading.Condition): + """Condition that counts its waiters, so a test can wait for them deterministically.""" + + waiting = 0 + + def wait(self, timeout=None): + self.waiting += 1 + try: + return super().wait(timeout) + finally: + self.waiting -= 1 + + +def _counting_refresh_cond(monkeypatch, plugin_index) -> _CountingCondition: + cond = _CountingCondition() + # raising=False keeps the test runnable (and red) against the pre-fix module. + monkeypatch.setattr(plugin_index, "_runtime_refresh_cond", cond, raising=False) + return cond + + +def _wait_until(predicate, timeout: float = 5.0) -> bool: + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + if predicate(): + return True + time.sleep(0.01) + return predicate() + + +def test_overlapping_forced_template_refreshes_share_reloads(monkeypatch): + """INC-5959A657: queued page syncs each reloaded every plugin tool.""" + from flocks.tool.device import plugin_index + + _patch_empty_template_sources(monkeypatch, plugin_index) + cond = _counting_refresh_cond(monkeypatch, plugin_index) + monkeypatch.setattr(plugin_index, "discover_api_service_descriptors", lambda **kw: []) + events: list[str] = [] + events_lock = threading.Lock() + first_started = threading.Event() + release_first = threading.Event() + + def slow_refresh_plugin_tools(cls): + with events_lock: + run = sum(event.startswith("start-") for event in events) + 1 + events.append(f"start-{run}") + if run == 1: + first_started.set() + assert release_first.wait(5) + with events_lock: + events.append(f"end-{run}") + return [] + + monkeypatch.setattr( + plugin_index.ToolRegistry, "refresh_plugin_tools", classmethod(slow_refresh_plugin_tools), + ) + + def call(name: str) -> None: + assert plugin_index.list_device_templates(refresh=True) == [] + with events_lock: + events.append(f"return-{name}") + + first = threading.Thread(target=call, args=("first",)) + first.start() + assert first_started.wait(5) + late = [threading.Thread(target=call, args=(f"late{index}",)) for index in range(5)] + for thread in late: + thread.start() + # Every late caller asks while the first reload still runs. + assert _wait_until(lambda: cond.waiting == 5), "late callers did not wait for the running reload" + release_first.set() + for thread in [first, *late]: + thread.join(5) + assert not thread.is_alive() + + assert [event for event in events if event.startswith("start-")] == ["start-1", "start-2"] + assert events.index("return-first") > events.index("end-1") + for index in range(5): + # A caller that asked during reload 1 must see a reload that began after it asked. + assert events.index(f"return-late{index}") > events.index("end-2") + + +def test_caller_of_a_finished_reload_does_not_wait_for_the_next_one(monkeypatch): + """The first of two overlapping forced refreshes returns after its own reload. + + Building the index reads the tool registry, whose lock a running reload + holds, so a caller that rebuilt only after giving up the reload would sit + through the reload queued behind it (17 s -> 34 s, past the WebUI timeout). + """ + from flocks.tool.device import plugin_index + + monkeypatch.setattr(plugin_index.hub_catalog, "list_catalog", lambda **kw: []) + monkeypatch.setattr(plugin_index, "discover_api_service_descriptors", lambda **kw: []) + cond = _counting_refresh_cond(monkeypatch, plugin_index) + registry_lock = threading.RLock() # stands in for ToolRegistry._refresh_lock + first_returned = threading.Event() + events: list[str] = [] + events_lock = threading.Lock() + + def device_tool_counts(): + with registry_lock: # ToolRegistry.list_tools() takes the refresh lock + return {} + + def refresh_plugin_tools(cls): + with registry_lock: + with events_lock: + run = sum(event.startswith("start-") for event in events) + 1 + events.append(f"start-{run}") + if run == 1: + assert _wait_until(lambda: cond.waiting == 1), "second caller never waited" + else: + first_returned.wait(5) + with events_lock: + events.append(f"end-{run}") + return [] + + monkeypatch.setattr(plugin_index, "_device_tool_counts", device_tool_counts) + monkeypatch.setattr(plugin_index.ToolRegistry, "refresh_plugin_tools", classmethod(refresh_plugin_tools)) + + def first_caller() -> None: + plugin_index.list_device_templates(refresh=True) + # Like a device sync reading the index again under its instance lock: + # by then the queued reload has started and holds the registry lock. + assert _wait_until(lambda: "start-2" in events), "second reload never started" + plugin_index.list_device_templates() + with events_lock: + events.append("return-first") + first_returned.set() + + def second_caller() -> None: + plugin_index.list_device_templates(refresh=True) + with events_lock: + events.append("return-second") + + first = threading.Thread(target=first_caller) + first.start() + assert _wait_until(lambda: "start-1" in events) + second = threading.Thread(target=second_caller) + second.start() + for thread in (first, second): + thread.join(15) + assert not thread.is_alive() + + assert events.index("return-first") < events.index("end-2") + assert events.index("return-second") > events.index("end-2") + + +def test_failed_forced_template_refresh_is_not_shared(monkeypatch): + from flocks.tool.device import plugin_index + + _patch_empty_template_sources(monkeypatch, plugin_index) + monkeypatch.setattr(plugin_index.ToolRegistry, "refresh_plugin_tools", classmethod(lambda cls: [])) + scans = 0 + + def flaky_discover(*, refresh: bool = False): + nonlocal scans + if refresh: + scans += 1 + if scans == 1: + raise RuntimeError("descriptor scan failed") + return [] + + monkeypatch.setattr(plugin_index, "discover_api_service_descriptors", flaky_discover) + + with pytest.raises(RuntimeError, match="descriptor scan failed"): + plugin_index.list_device_templates(refresh=True) + assert plugin_index.list_device_templates(refresh=True) == [] + assert scans == 2 + + +def test_failed_tool_reload_is_not_shared_with_waiters(monkeypatch): + """A tool reload that failed (logged, not raised) must not satisfy waiting callers.""" + from flocks.tool.device import plugin_index + + _patch_empty_template_sources(monkeypatch, plugin_index) + cond = _counting_refresh_cond(monkeypatch, plugin_index) + failed_runner: list[str] = [] + monkeypatch.setattr(plugin_index, "discover_api_service_descriptors", lambda **kw: []) + events: list[str] = [] + events_lock = threading.Lock() + first_started = threading.Event() + release_first = threading.Event() + + def flaky_refresh_plugin_tools(cls): + with events_lock: + run = sum(event.startswith("start-") for event in events) + 1 + events.append(f"start-{run}") + if run == 1: + first_started.set() + assert release_first.wait(5) + if run == 2: + with events_lock: + events.append("fail-2") + failed_runner.append(threading.current_thread().name) + raise RuntimeError("plugin load failed") + with events_lock: + events.append(f"end-{run}") + return [] + + monkeypatch.setattr( + plugin_index.ToolRegistry, "refresh_plugin_tools", classmethod(flaky_refresh_plugin_tools), + ) + + def call(name: str) -> None: + plugin_index.list_device_templates(refresh=True) + with events_lock: + events.append(f"return-{name}") + + first = threading.Thread(target=call, args=("first",), name="first") + first.start() + assert first_started.wait(5) + late_names = [f"late{index}" for index in range(3)] + late = [threading.Thread(target=call, args=(name,), name=name) for name in late_names] + for thread in late: + thread.start() + assert _wait_until(lambda: cond.waiting == 3), "late callers did not wait for the running reload" + release_first.set() + for thread in [first, *late]: + thread.join(5) + assert not thread.is_alive() + + assert [event for event in events if event.startswith("start-")] == ["start-1", "start-2", "start-3"] + # The caller that ran the failed reload 2 has its failure logged; the other + # two must not take that reload as theirs and only return after reload 3. + waiters = [name for name in late_names if name not in failed_runner] + assert len(waiters) == 2 + for name in waiters: + assert events.index(f"return-{name}") > events.index("end-3") + + +def test_index_build_failure_after_a_reload_drops_the_old_index(monkeypatch): + from flocks.tool.device import plugin_index + + monkeypatch.setattr(plugin_index, "_device_tool_counts", lambda: {}) + monkeypatch.setattr(plugin_index, "discover_api_service_descriptors", lambda **kw: []) + monkeypatch.setattr(plugin_index.ToolRegistry, "refresh_plugin_tools", classmethod(lambda cls: [])) + monkeypatch.setattr(plugin_index.hub_catalog, "list_catalog", lambda **kw: []) + plugin_index.clear_device_template_cache() + assert plugin_index.list_device_templates() == [] + assert plugin_index._template_cache == [] + + def broken_catalog(**kwargs): + raise RuntimeError("catalog unreadable") + + monkeypatch.setattr(plugin_index.hub_catalog, "list_catalog", broken_catalog) + with pytest.raises(RuntimeError, match="catalog unreadable"): + plugin_index.list_device_templates(refresh=True) + assert plugin_index._template_cache is None + + +def test_forced_template_refresh_from_inside_a_reload_does_not_deadlock(monkeypatch): + from flocks.tool.device import plugin_index + + _patch_empty_template_sources(monkeypatch, plugin_index) + monkeypatch.setattr(plugin_index, "discover_api_service_descriptors", lambda **kw: []) + reloads: list[bool] = [] + + def reentrant_refresh_plugin_tools(cls): + reloads.append(True) + if len(reloads) == 1: + plugin_index.list_device_templates(refresh=True) + return [] + + monkeypatch.setattr( + plugin_index.ToolRegistry, "refresh_plugin_tools", classmethod(reentrant_refresh_plugin_tools), + ) + + worker = threading.Thread(target=plugin_index.list_device_templates, kwargs={"refresh": True}) + worker.start() + worker.join(5) + + assert not worker.is_alive() + assert len(reloads) == 2 + + +def test_template_rebuild_overtaken_by_a_cache_clear_is_not_stored(monkeypatch): + from flocks.tool.device import plugin_index + + monkeypatch.setattr(plugin_index, "_device_tool_counts", lambda: {}) + monkeypatch.setattr(plugin_index, "discover_api_service_descriptors", lambda **kw: []) + + def list_catalog_racing_a_plugin_change(**kwargs): + plugin_index.clear_device_template_cache() # a Hub install lands mid-rebuild + return [] + + monkeypatch.setattr(plugin_index.hub_catalog, "list_catalog", list_catalog_racing_a_plugin_change) + plugin_index.clear_device_template_cache() + + assert plugin_index.list_device_templates() == [] + assert plugin_index._template_cache is None + + +@pytest.mark.asyncio +async def test_overlapping_forced_device_syncs_share_the_plugin_reload(monkeypatch, tmp_path): + """INC-5959A657: each queued /api/devices/sync?refresh=true reloaded all plugins.""" + from flocks.storage.storage import Storage + from flocks.tool.device import intake, plugin_index + from flocks.tool.device.store import list_devices + + home, _data, _project = _reset_env(monkeypatch, tmp_path) + await Storage.init() + root = home / ".flocks" / "plugins" / "tools" / "device" / "custom_demo" + _write_provider( + root, + { + "name": "Custom Demo", + "service_id": "custom_demo_api", + "version": "0.1.0", + "integration_type": "device", + "credential_fields": [], + }, + ) + _write_tool(root, "custom_demo_ping") + reloads = 0 + reloads_lock = threading.Lock() + cond = _counting_refresh_cond(monkeypatch, plugin_index) + + def slow_refresh_plugin_tools(cls): + nonlocal reloads + with reloads_lock: + reloads += 1 + run = reloads + if run == 1: + # Hold the first reload until the other four syncs are waiting on it. + _wait_until(lambda: cond.waiting >= 4) + return [] + + async def fake_sync_service_tool_state(service_id: str) -> None: + return None + + monkeypatch.setattr(plugin_index.hub_catalog, "list_catalog", lambda plugin_type=None: []) + monkeypatch.setattr(plugin_index.hub_catalog, "system_plugin_root", lambda plugin_type, plugin_id: None) + monkeypatch.setattr( + plugin_index.ToolRegistry, "refresh_plugin_tools", classmethod(slow_refresh_plugin_tools), + ) + monkeypatch.setattr(plugin_index.ToolRegistry, "init", classmethod(lambda cls: None)) + monkeypatch.setattr(plugin_index.ToolRegistry, "list_tools", classmethod(lambda cls: [])) + monkeypatch.setattr(intake, "sync_service_tool_state", fake_sync_service_tool_state) + + created_counts = await asyncio.gather( + *(intake.ensure_user_device_instances(refresh_templates=True) for _ in range(5)), + ) + devices = await list_devices() + + assert sorted(created_counts) == [0, 0, 0, 0, 1] + assert [device.storage_key for device in devices] == ["custom_demo_api_v0_1_0"] + assert reloads == 2 + plugin_index.clear_device_template_cache() diff --git a/tests/tool/test_tool_refresh_outcomes.py b/tests/tool/test_tool_refresh_outcomes.py index 4efd7544b..3dc6c0b33 100644 --- a/tests/tool/test_tool_refresh_outcomes.py +++ b/tests/tool/test_tool_refresh_outcomes.py @@ -1,18 +1,25 @@ from __future__ import annotations +import asyncio from collections.abc import Iterator from contextlib import contextmanager from pathlib import Path +import sys import threading +from types import SimpleNamespace import pytest +from flocks.config.config import Config, ConfigInfo +from flocks.config.config_writer import ConfigWriter from flocks.tool.registry import ( Tool, ToolCategory, + ToolFileWatcher, ToolInfo, ToolRefreshError, ToolRegistry, + ToolResult, ) @@ -430,54 +437,682 @@ def _refresh_dynamic(): assert set(ToolRegistry._tools) == {"base", "new_dynamic"} -def test_registry_readers_do_not_observe_an_in_progress_refresh( +@contextmanager +def _plugin_refresh_held_open( monkeypatch: pytest.MonkeyPatch, -): + *, + fail: bool = True, + on_load=None, +) -> Iterator[threading.Thread]: + """Run refresh_plugin_tools on a thread and keep it inside the plugin load. + + The registry has already unregistered every plugin tool at that point, as + a real reload does before it loads them again one by one. + """ load_entered = threading.Event() - allow_failure = threading.Event() - reader_finished = threading.Event() - reader_results: list[Tool | None] = [] + allow_finish = threading.Event() + outcome: list[BaseException | None] = [] + + def _held_plugin_load(cls, errors): + if on_load is not None: + on_load() + load_entered.set() + assert allow_finish.wait(timeout=5) + if fail: + errors.append("plugin loader: unavailable") + + monkeypatch.setattr( + ToolRegistry, + "_load_plugin_tools", + classmethod(_held_plugin_load), + ) + def _refresh() -> None: + try: + ToolRegistry.refresh_plugin_tools() + except BaseException as exc: # noqa: BLE001 - reported to the test + outcome.append(exc) + else: + outcome.append(None) + + refresh_thread = threading.Thread(target=_refresh, daemon=True) + refresh_thread.start() + try: + assert load_entered.wait(timeout=2) + yield SimpleNamespace(thread=refresh_thread, release=allow_finish.set) + finally: + allow_finish.set() + refresh_thread.join(timeout=5) + assert not refresh_thread.is_alive() + if fail: + assert len(outcome) == 1 and isinstance(outcome[0], ToolRefreshError) + else: + assert outcome == [None] + + +def _on_thread(fn, timeout: float = 1.0): + """Call *fn* on another thread; return (finished in time, its result).""" + results: list = [] + worker = threading.Thread(target=lambda: results.append(fn()), daemon=True) + worker.start() + worker.join(timeout=timeout) + return (not worker.is_alive(), results[0] if results else None) + + +def test_registry_readers_see_the_pre_refresh_state_without_waiting( + monkeypatch: pytest.MonkeyPatch, +): + """A read during a reload neither waits for it nor sees it half done. + + Reads run on the event loop (request handlers, tool calls): waiting out a + reload there stopped every request on the server until the reload ended. + """ with _isolated_registry(): + builtin = _tool("builtin_tool", "builtin") previous = _tool("previous_plugin", "plugin_py") + ToolRegistry._tools[builtin.info.name] = builtin ToolRegistry._tools[previous.info.name] = previous + ToolRegistry._enabled_defaults[previous.info.name] = True ToolRegistry._plugin_tool_names = [previous.info.name] + ToolRegistry._revision = 7 - def _failed_plugin_load(cls, errors): - load_entered.set() - assert allow_failure.wait(timeout=2) - errors.append("plugin loader: unavailable") + with _plugin_refresh_held_open(monkeypatch): + # The live registry is mid-reload: the plugin tool is unregistered. + assert previous.info.name not in ToolRegistry._tools - monkeypatch.setattr( - ToolRegistry, - "_load_plugin_tools", - classmethod(_failed_plugin_load), - ) + finished, got = _on_thread(lambda: ToolRegistry.get(previous.info.name)) + assert finished, "get() waited for the reload" + assert got is previous + + finished, infos = _on_thread(ToolRegistry.list_tools) + assert finished + assert {info.name for info in infos} == {builtin.info.name, previous.info.name} + + finished, ids = _on_thread(ToolRegistry.all_tool_ids) + assert finished + assert set(ids) == {builtin.info.name, previous.info.name} + + finished, identity = _on_thread(ToolRegistry.snapshot_identity) + assert finished + assert identity[0] == 7 + assert set(identity[1]) == {builtin.info.name, previous.info.name} + + finished, revision = _on_thread(ToolRegistry.revision) + assert finished and revision == 7 + + finished, default = _on_thread( + lambda: ToolRegistry.get_default_enabled(previous.info.name) + ) + assert finished and default is True + + # The failed reload restored the previous registry; reads use it again. + assert ToolRegistry.get(previous.info.name) is previous + assert ToolRegistry._reload_view is None + + +def test_registry_reads_after_a_reload_see_its_result( + monkeypatch: pytest.MonkeyPatch, +): + with _isolated_registry(): + previous = _tool("previous_plugin", "plugin_py") + replacement = _tool("previous_plugin", "plugin_py") + ToolRegistry._tools[previous.info.name] = previous + ToolRegistry._plugin_tool_names = [previous.info.name] + + def _register_replacement(): + ToolRegistry.register(replacement) + + with _plugin_refresh_held_open(monkeypatch, fail=False, on_load=_register_replacement): + finished, during = _on_thread(lambda: ToolRegistry.get(previous.info.name)) + assert finished and during is previous + + assert ToolRegistry.get(previous.info.name) is replacement + assert ToolRegistry._reload_view is None + + +def test_reloading_thread_reads_its_own_progress(monkeypatch: pytest.MonkeyPatch): + """Plugin code run by the reload (entry points) sees what it has loaded so far.""" + seen: dict[str, object] = {} + + with _isolated_registry(): + previous = _tool("previous_plugin", "plugin_py") + fresh = _tool("fresh_plugin", "plugin_py") + ToolRegistry._tools[previous.info.name] = previous + ToolRegistry._plugin_tool_names = [previous.info.name] + + def _load_and_look(): + ToolRegistry.register(fresh) + seen["fresh"] = ToolRegistry.get(fresh.info.name) + seen["previous"] = ToolRegistry.get(previous.info.name) + seen["ids"] = set(ToolRegistry.all_tool_ids()) + + with _plugin_refresh_held_open(monkeypatch, fail=False, on_load=_load_and_look): + pass + + assert seen["fresh"] is fresh + assert seen["previous"] is None + assert seen["ids"] == {fresh.info.name} + + +def test_registry_writers_still_wait_for_a_reload(monkeypatch: pytest.MonkeyPatch): + with _isolated_registry(): + previous = _tool("previous_plugin", "plugin_py") + late = _tool("late_tool", "builtin") + ToolRegistry._tools[previous.info.name] = previous + ToolRegistry._plugin_tool_names = [previous.info.name] + + with _plugin_refresh_held_open(monkeypatch): + writer = threading.Thread(target=lambda: ToolRegistry.register(late), daemon=True) + writer.start() + writer.join(timeout=0.2) + assert writer.is_alive(), "register() ran inside another thread's reload" + writer.join(timeout=2) + assert not writer.is_alive() + # Registered after the failed reload rolled back, so it survives it. + assert ToolRegistry.get(late.info.name) is late + + +def test_tool_failure_bookkeeping_does_not_wait_for_a_reload( + monkeypatch: pytest.MonkeyPatch, +): + """Every tool call resets or counts failures on the event loop afterwards.""" + with _isolated_registry(): + previous = _tool("previous_plugin", "plugin_py") + ToolRegistry._tools[previous.info.name] = previous + ToolRegistry._plugin_tool_names = [previous.info.name] + monkeypatch.setattr(ToolRegistry, "_failure_state", {"previous_plugin": {"key": "k", "count": 1}}) + + with _plugin_refresh_held_open(monkeypatch): + finished, _ = _on_thread(lambda: ToolRegistry._reset_failure_state("previous_plugin")) + assert finished, "_reset_failure_state waited for the reload" + assert "previous_plugin" not in ToolRegistry._failure_state + + finished, disabled = _on_thread( + lambda: ToolRegistry._record_failure(previous, {"q": 1}, "upstream exploded") + ) + assert finished, "_record_failure waited for the reload" + assert disabled is False + assert ToolRegistry._failure_state["previous_plugin"]["count"] == 1 + + +def test_config_sync_is_skipped_during_another_threads_reload( + monkeypatch: pytest.MonkeyPatch, +): + synced: list[str] = [] + monkeypatch.setattr(ToolRegistry, "_config_state_token", ("before",)) + monkeypatch.setattr( + ToolRegistry, + "_current_config_state_token", + classmethod(lambda cls: ("after",)), + ) + monkeypatch.setattr( + ToolRegistry, + "_apply_tool_settings", + classmethod(lambda cls: synced.append("settings")), + ) + monkeypatch.setattr(ToolRegistry, "_sync_api_service_states", classmethod(lambda cls: None)) + + with _isolated_registry(): + previous = _tool("previous_plugin", "plugin_py") + ToolRegistry._tools[previous.info.name] = previous + ToolRegistry._plugin_tool_names = [previous.info.name] + + with _plugin_refresh_held_open(monkeypatch): + finished, got = _on_thread(lambda: ToolRegistry.get(previous.info.name)) + assert finished and got is previous + assert synced == [] + assert ToolRegistry._config_state_token == ("before",) + + # The first read after the reload applies the changed config. + ToolRegistry.get(previous.info.name) + assert synced == ["settings"] + assert ToolRegistry._config_state_token == ("after",) + + +def _custom_tool(name: str, handler, provider: str | None = None) -> Tool: + return Tool( + info=ToolInfo( + name=name, + description=name, + category=ToolCategory.CUSTOM, + source="plugin_py", + provider=provider, + ), + handler=handler, + ) + + +def _execute_across_a_held_reload(held, tool_name: str, on_hold=None): + """Start executing *tool_name* while a reload is held, then let it finish. + + Returns (event-loop ticks while held, whether the call finished while held, result). + """ + async def scenario(): + ticks = 0 + stop = asyncio.Event() + + async def ticker(): + nonlocal ticks + while not stop.is_set(): + await asyncio.sleep(0.01) + ticks += 1 + + ticking = asyncio.create_task(ticker()) + call = asyncio.create_task(ToolRegistry.execute(tool_name)) + await asyncio.sleep(0.3) + observed = (ticks, call.done()) + if on_hold is not None: + on_hold() + held.release() + result = await asyncio.wait_for(call, timeout=5) + stop.set() + await ticking + return (*observed, result) + + return asyncio.run(scenario()) + + +def test_execute_waits_out_a_reload_and_obeys_config_written_meanwhile( + monkeypatch: pytest.MonkeyPatch, +): + """Reads skip the config sync during a reload; execution must not. + + A call made during a reload waits for it (the event loop keeps running), + then decides on the registry with the current config applied: a tool + switched off meanwhile by another worker does not run. That includes a + tool off by default whose "on" override was removed, and a tool whose + API service was switched off. + """ + runs: list[str] = [] + + async def handler(_ctx, **_kwargs) -> ToolResult: + runs.append("ran") + return ToolResult(success=True, output="ran") + + token = ["before"] + settings: dict = {"default_off_tool": {"enabled": True}} + services: dict = {"guarded_api": {"enabled": True}} + monkeypatch.setattr(ToolRegistry, "_current_config_state_token", classmethod(lambda cls: (token[0],))) + monkeypatch.setattr(ConfigWriter, "list_tool_settings", lambda: settings) + monkeypatch.setattr(ConfigWriter, "list_api_services_raw", lambda: services) + + with _isolated_registry(): + plain = _custom_tool("guarded_tool", handler) + api = _custom_tool("guarded_api_tool", handler, provider="guarded_api") + default_off = _custom_tool("default_off_tool", handler) + for tool in (plain, api, default_off): + ToolRegistry._tools[tool.info.name] = tool + ToolRegistry._enabled_defaults[tool.info.name] = True + ToolRegistry._enabled_defaults[default_off.info.name] = False + ToolRegistry._plugin_tool_names = [plain.info.name, api.info.name, default_off.info.name] + monkeypatch.setattr(ToolRegistry, "_config_state_token", ("before",)) + + cases = [ + (plain.info.name, None, True), + (plain.info.name, lambda: settings.__setitem__(plain.info.name, {"enabled": False}), False), + (api.info.name, lambda: services.__setitem__("guarded_api", {"enabled": False}), False), + (default_off.info.name, lambda: settings.pop(default_off.info.name), False), + ] + for name, change, should_run in cases: + with _plugin_refresh_held_open(monkeypatch) as held: + on_hold = None + if change is not None: + def on_hold(change=change, name=name): + token[0] = f"after: {name}" + change() + ticks, finished_during_reload, result = _execute_across_a_held_reload(held, name, on_hold) + assert ticks >= 10, f"{name}: the event loop stood still during the reload" + assert finished_during_reload is False, f"{name}: ran from the pre-reload copy" + assert result.success is should_run, (name, result.error) + if not should_run: + assert result.error == f"Tool is disabled: {name}" + + assert runs == ["ran"] + + +def test_auto_disable_after_repeated_failures_does_not_block_the_event_loop( + monkeypatch: pytest.MonkeyPatch, +): + """The third identical failure switches the tool off under the registry + lock; while a reload holds it, that wait must not stop the event loop, + and the reload's rollback must not switch the tool back on.""" + error = "synthetic repeated failure" + + async def handler(_ctx, **_kwargs) -> ToolResult: + return ToolResult(success=False, error=error) + + monkeypatch.setattr(Config, "_cached_config", ConfigInfo()) + persisted_on: list[threading.Thread] = [] + monkeypatch.setattr( + ConfigWriter, + "set_tool_setting", + lambda _name, _setting: persisted_on.append(threading.current_thread()), + ) + + with _isolated_registry(): + tool = _custom_tool("flaky_tool", handler) + ToolRegistry._tools[tool.info.name] = tool + ToolRegistry._plugin_tool_names = [tool.info.name] + monkeypatch.setattr(ToolRegistry, "_failure_state", { + tool.info.name: { + "key": ToolRegistry._failure_key(tool.info.name, {"query": "same"}, error), + "count": ToolRegistry._failure_disable_threshold - 1, + }, + }) + + with _plugin_refresh_held_open(monkeypatch) as held: + async def scenario(): + ticks = 0 + stop = asyncio.Event() + + async def ticker(): + nonlocal ticks + while not stop.is_set(): + await asyncio.sleep(0.01) + ticks += 1 + + ticking = asyncio.create_task(ticker()) + call = asyncio.create_task(ToolRegistry.execute(tool.info.name, query="same")) + await asyncio.sleep(0.3) + observed = (ticks, call.done()) + held.release() + result = await asyncio.wait_for(call, timeout=5) + stop.set() + await ticking + return observed, result + + (ticks, done_during_reload), result = asyncio.run(scenario()) + + assert ticks >= 10, "the event loop stood still while the disable waited for the reload" + assert done_during_reload is False + assert result.metadata == {"disabled": True, "disabled_reason": "repeated_error"} + assert tool.info.enabled is False + # Written on the event loop's thread, in line with the other config + # writers there; from a worker thread it could overwrite a config they + # saved in between (lost update). + assert persisted_on == [threading.current_thread()] + + +def test_failure_bookkeeping_waits_for_a_held_registry_lock_without_blocking_the_loop( + monkeypatch: pytest.MonkeyPatch, +): + """A reload that starts while a call runs: the failure bookkeeping after it + waits for the registry lock asynchronously, on the loop's own thread.""" + error = "synthetic repeated failure" + finish = asyncio.Event() + + async def handler(_ctx, **_kwargs) -> ToolResult: + await finish.wait() + return ToolResult(success=False, error=error) + + monkeypatch.setattr(Config, "_cached_config", ConfigInfo()) + persisted_on: list[threading.Thread] = [] + monkeypatch.setattr( + ConfigWriter, + "set_tool_setting", + lambda _name, _setting: persisted_on.append(threading.current_thread()), + ) + + with _isolated_registry(): + tool = _custom_tool("flaky_tool", handler) + ToolRegistry._tools[tool.info.name] = tool + monkeypatch.setattr(ToolRegistry, "_failure_state", { + tool.info.name: { + "key": ToolRegistry._failure_key(tool.info.name, {"query": "same"}, error), + "count": ToolRegistry._failure_disable_threshold - 1, + }, + }) + held = threading.Event() + release = threading.Event() + + def hold_registry_lock(): + with ToolRegistry._refresh_lock: + held.set() + release.wait(timeout=2) + + async def scenario(): + ticks = 0 + stop = asyncio.Event() + + async def ticker(): + nonlocal ticks + while not stop.is_set(): + await asyncio.sleep(0.01) + ticks += 1 + + call = asyncio.create_task(ToolRegistry.execute(tool.info.name, query="same")) + await asyncio.sleep(0.05) # the call is inside the tool now + holder = threading.Thread(target=hold_registry_lock, daemon=True) + holder.start() + while not held.is_set(): + await asyncio.sleep(0.01) + ticking = asyncio.create_task(ticker()) + finish.set() + await asyncio.sleep(0.3) + observed = (ticks, call.done()) + release.set() + result = await asyncio.wait_for(call, timeout=5) + stop.set() + await ticking + holder.join(timeout=2) + return observed, result + + (ticks, done_while_held), result = asyncio.run(scenario()) + + assert ticks >= 10, "the event loop stood still while the bookkeeping waited for the lock" + assert done_while_held is False + assert result.metadata == {"disabled": True, "disabled_reason": "repeated_error"} + assert persisted_on == [threading.current_thread()] + + +def test_first_execute_during_background_init_does_not_deadlock(monkeypatch: pytest.MonkeyPatch): + """init() holds _init_lock and takes _refresh_lock per tool; a call that + took _refresh_lock first and then initialized would wait the other way.""" + async def handler(_ctx, **_kwargs) -> ToolResult: + return ToolResult(success=True, output="ok") + + tool = _custom_tool("cold_tool", handler) + init_holding = threading.Event() + + def slow_builtins(cls) -> None: + init_holding.set() + threading.Event().wait(0.3) # the first call arrives meanwhile + cls.register(tool) + + monkeypatch.setattr(ToolRegistry, "_register_builtin_tools", classmethod(slow_builtins)) + monkeypatch.setattr(ToolRegistry, "_register_dynamic_tools", classmethod(lambda cls, errors=None: None)) + monkeypatch.setattr(ToolRegistry, "_register_plugin_extension_point", classmethod(lambda cls: None)) + monkeypatch.setattr(ToolRegistry, "_load_plugin_tools", classmethod(lambda cls, errors=None: [])) + monkeypatch.setattr(ToolRegistry, "_plugin_sources_fingerprint", classmethod(lambda cls: ())) - refresh_thread = threading.Thread( - target=lambda: pytest.raises( - ToolRefreshError, - ToolRegistry.refresh_plugin_tools, - ), + with _isolated_registry(): + ToolRegistry._initialized = False + init_thread = threading.Thread(target=ToolRegistry.init, daemon=True) + init_thread.start() + assert init_holding.wait(timeout=2) + results: list[ToolResult] = [] + caller = threading.Thread( + target=lambda: results.append(asyncio.run(ToolRegistry.execute(tool.info.name))), + daemon=True, + ) + caller.start() + caller.join(timeout=5) + init_thread.join(timeout=5) + assert not caller.is_alive() and not init_thread.is_alive(), ( + "the first call deadlocked with the background init" ) - def _read_plugin() -> None: - reader_results.append(ToolRegistry.get(previous.info.name)) - reader_finished.set() + assert [result.success for result in results] == [True] + + +def test_registry_write_lock_waits_for_a_reload_without_blocking_the_loop( + monkeypatch: pytest.MonkeyPatch, +): + with _isolated_registry(): + previous = _tool("previous_plugin", "plugin_py") + ToolRegistry._tools[previous.info.name] = previous + ToolRegistry._plugin_tool_names = [previous.info.name] + + with _plugin_refresh_held_open(monkeypatch) as held: + async def scenario(): + ticks = 0 + entered = asyncio.Event() + + async def writer(): + async with ToolRegistry.write_lock(): + entered.set() + assert ToolRegistry._reload_view is None # the reload is over + + async def ticker(): + nonlocal ticks + while not entered.is_set(): + await asyncio.sleep(0.01) + ticks += 1 + + write = asyncio.create_task(writer()) + ticking = asyncio.create_task(ticker()) + await asyncio.sleep(0.3) + observed = (ticks, entered.is_set()) + held.release() + await asyncio.wait_for(write, timeout=5) + await ticking + return observed + + ticks, entered_during_reload = asyncio.run(scenario()) + + assert ticks >= 10 + assert entered_during_reload is False + + +def test_file_watcher_reloads_off_the_event_loop(monkeypatch: pytest.MonkeyPatch): + """A plugin file change used to run the whole reload on the event loop.""" + loop = asyncio.new_event_loop() + loop_thread = threading.Thread(target=loop.run_forever, daemon=True) + loop_thread.start() + ran_on: list[threading.Thread] = [] + try: + watcher = ToolFileWatcher() + # How the watcher found the loop before (start() captured it). + watcher._loop = loop + monkeypatch.setattr(watcher, "_run_refresh", lambda: ran_on.append(threading.current_thread())) + timer_thread = threading.Thread(target=watcher._do_refresh) + timer_thread.start() + timer_thread.join(timeout=2) + for _ in range(100): + if ran_on: + break + threading.Event().wait(0.01) + finally: + loop.call_soon_threadsafe(loop.stop) + loop_thread.join(timeout=2) + loop.close() + + assert ran_on == [timer_thread] + + +def test_plugin_fingerprint_follows_installed_packages( + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, +): + """A newly installed package may bring a flocks.plugins entry point.""" + site_packages = tmp_path / "lib" / "site-packages" + site_packages.mkdir(parents=True) + plugins = tmp_path / "plugins" + plugins.mkdir() + monkeypatch.setattr(ToolRegistry, "_plugin_source_roots", classmethod(lambda cls: [str(plugins)])) + monkeypatch.setattr(sys, "path", [str(site_packages)]) + + before = ToolRegistry._plugin_sources_fingerprint() + assert ToolRegistry._plugin_sources_fingerprint() == before + (site_packages / "acme_flocks_plugin-1.0.dist-info").mkdir() + assert ToolRegistry._plugin_sources_fingerprint() != before - reader_thread = threading.Thread(target=_read_plugin) - refresh_thread.start() - assert load_entered.wait(timeout=1) - reader_thread.start() - assert not reader_finished.wait(timeout=0.1) - allow_failure.set() - refresh_thread.join(timeout=1) - reader_thread.join(timeout=1) +def _counting_plugin_load(monkeypatch: pytest.MonkeyPatch, errors_to_report: list[str]) -> list[int]: + loads: list[int] = [] - assert not refresh_thread.is_alive() - assert not reader_thread.is_alive() - assert reader_results == [previous] + def _load(cls, errors): + loads.append(1) + errors.extend(errors_to_report) + + monkeypatch.setattr(ToolRegistry, "_load_plugin_tools", classmethod(_load)) + return loads + + +def test_refresh_if_changed_reloads_only_when_a_plugin_file_changed( + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, +): + root = tmp_path / "plugins" + tool_dir = root / "tools" / "device" / "acme" + tool_dir.mkdir(parents=True) + (tool_dir / "acme_query.yaml").write_text("name: acme_query\n", encoding="utf-8") + (tool_dir / "_provider.yaml").write_text("name: acme\n", encoding="utf-8") + monkeypatch.setattr(ToolRegistry, "_plugin_source_roots", classmethod(lambda cls: [str(root)])) + monkeypatch.setattr(ToolRegistry, "_plugin_sources_stamp", None) + loads = _counting_plugin_load(monkeypatch, []) + + with _isolated_registry(): + assert ToolRegistry.refresh_plugin_tools_if_changed() is True # nothing on record yet + assert ToolRegistry.refresh_plugin_tools_if_changed() is False + assert len(loads) == 1 + + # Bytecode caches are not sources. + (tool_dir / "__pycache__").mkdir() + (tool_dir / "__pycache__" / "acme.cpython-312.pyc").write_bytes(b"cache") + assert ToolRegistry.refresh_plugin_tools_if_changed() is False + + (tool_dir / "acme_query.yaml").write_text("name: acme_query\ndescription: changed\n", encoding="utf-8") + assert ToolRegistry.refresh_plugin_tools_if_changed() is True + assert ToolRegistry.refresh_plugin_tools_if_changed() is False + + (tool_dir / "acme_ops.yaml").write_text("name: acme_ops\n", encoding="utf-8") + assert ToolRegistry.refresh_plugin_tools_if_changed() is True + + (tool_dir / "acme_ops.yaml").unlink() + assert ToolRegistry.refresh_plugin_tools_if_changed() is True + + # A forced reload records the files it read, too. + (tool_dir / "acme_query.yaml").write_text("name: acme_query\n", encoding="utf-8") + ToolRegistry.refresh_plugin_tools() + assert ToolRegistry.refresh_plugin_tools_if_changed() is False + + assert len(loads) == 5 + + +def test_refresh_if_changed_retries_a_load_that_reported_errors( + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, +): + root = tmp_path / "plugins" + (root / "tools").mkdir(parents=True) + (root / "tools" / "broken.yaml").write_text("name: [\n", encoding="utf-8") + monkeypatch.setattr(ToolRegistry, "_plugin_source_roots", classmethod(lambda cls: [str(root)])) + monkeypatch.setattr(ToolRegistry, "_plugin_sources_stamp", None) + + with _isolated_registry(): + # A failed reload: rolled back, never treated as current. + loads = _counting_plugin_load(monkeypatch, ["plugin loader: unavailable"]) + with pytest.raises(ToolRefreshError): + ToolRegistry.refresh_plugin_tools_if_changed() + with pytest.raises(ToolRefreshError): + ToolRegistry.refresh_plugin_tools_if_changed() + assert len(loads) == 2 + assert ToolRegistry._plugin_sources_stamp is None + + # A partial reload (errors outside the changed path) is kept, but not recorded as clean. + outside = str((root / "tools" / "broken.yaml").resolve()) + loads = _counting_plugin_load(monkeypatch, [f"{outside}: YAMLError: bad"]) + ToolRegistry.refresh_plugin_tools(changed_path=tmp_path / "elsewhere") + assert len(loads) == 1 + assert ToolRegistry._plugin_sources_stamp is None + + # Nothing changed on disk, yet the next ask reloads (whatever failed may be + # fixed now); once the same files load cleanly they are current. + loads = _counting_plugin_load(monkeypatch, []) + assert ToolRegistry.refresh_plugin_tools_if_changed() is True + assert ToolRegistry.refresh_plugin_tools_if_changed() is False + assert len(loads) == 1 def test_tool_extension_consumer_reports_invalid_specs(): diff --git a/tests/tool/test_web_tools_hardening_g3b.py b/tests/tool/test_web_tools_hardening_g3b.py index 3f1ff088b..48833ae4f 100644 --- a/tests/tool/test_web_tools_hardening_g3b.py +++ b/tests/tool/test_web_tools_hardening_g3b.py @@ -6,7 +6,7 @@ import pytest -from flocks.tool.web.webfetch import _ssrf_error, html_to_markdown +from flocks.tool.web.webfetch import _ssrf_error, html_to_markdown, is_loopback_host def test_html_to_markdown_tag_boundaries(): @@ -18,9 +18,9 @@ def test_html_to_markdown_tag_boundaries(): @pytest.mark.parametrize("url", [ - "http://127.0.0.1:8000/api/health", "http://169.254.169.254/latest/meta-data/", "http://10.0.0.1/", "http://192.168.1.1/", "http://172.16.0.1/", "http://0.0.0.0/", + "http://[fe80::1]/", "http://[fd00::1]/", "http://[::ffff:10.0.0.1]/", ]) def test_ssrf_guard_blocks_internal(monkeypatch, url): monkeypatch.delenv("FLOCKS_WEBFETCH_ALLOW_INTERNAL", raising=False) @@ -28,14 +28,79 @@ def test_ssrf_guard_blocks_internal(monkeypatch, url): assert err and "Blocked request to internal" in err +@pytest.mark.parametrize("url", [ + "http://127.0.0.1:8000/api/health", + "http://127.8.9.10/", + "http://localhost:8088/page.html", + "http://LOCALHOST./", + "http://[::1]:8080/", + "http://[::ffff:127.0.0.1]/", +]) +def test_ssrf_guard_allows_loopback(monkeypatch, url): + """本机回环(localhost、127.0.0.0/8、::1)不拦:本地服务和代理都在这上面。""" + monkeypatch.delenv("FLOCKS_WEBFETCH_ALLOW_INTERNAL", raising=False) + assert _ssrf_error(url) is None + + def test_ssrf_guard_allowlist_and_dns_failure(monkeypatch): - monkeypatch.setenv("FLOCKS_WEBFETCH_ALLOW_INTERNAL", "127.0.0.1") - assert _ssrf_error("http://127.0.0.1:8088/page.html") is None + monkeypatch.setenv("FLOCKS_WEBFETCH_ALLOW_INTERNAL", "10.0.0.5") + assert _ssrf_error("http://10.0.0.5:8088/page.html") is None monkeypatch.delenv("FLOCKS_WEBFETCH_ALLOW_INTERNAL", raising=False) + assert "Blocked request to internal" in (_ssrf_error("http://10.0.0.5:8088/page.html") or "") # 解析失败不当作 SSRF 拦截,交给请求本身报错 assert _ssrf_error("http://no.such.host.invalid/") is None +@pytest.mark.parametrize(("host", "expected"), [ + ("localhost", True), ("LOCALHOST.", True), ("api.localhost", True), + ("127.0.0.1", True), ("127.1.2.3", True), ("::1", True), ("[::1]", True), + ("::1%lo0", True), ("::1%25lo0", True), ("::ffff:127.0.0.1", True), + ("localhost.example.com", False), ("evil-localhost", False), ("10.0.0.1", False), + # a % after an IPv4 address makes a name, not an address + ("127.0.0.1%25.attacker.example", False), ("127.0.0.1%eth0", False), + ("0.0.0.0", False), ("::", False), ("example.com", False), ("", False), (None, False), +]) +def test_is_loopback_host(host, expected): + assert is_loopback_host(host) is expected + + +@pytest.mark.asyncio +async def test_webfetch_reads_a_page_served_on_loopback(monkeypatch): + """真起一个只听 127.0.0.1 的服务,webfetch 用 127.0.0.1 和 localhost 都能抓到。""" + import http.server + import threading + + from flocks.tool.registry import ToolContext + from flocks.tool.web.webfetch import webfetch_tool + + class _Handler(http.server.BaseHTTPRequestHandler): + def do_GET(self): + body = "

local ok

".encode() + self.send_response(200) + self.send_header("Content-Type", "text/html; charset=utf-8") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *args): + pass + + monkeypatch.delenv("FLOCKS_WEBFETCH_ALLOW_INTERNAL", raising=False) + server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), _Handler) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + port = server.server_address[1] + ctx = ToolContext(session_id="s", message_id="m") + for host in ("127.0.0.1", "localhost"): + result = await webfetch_tool(ctx, url=f"http://{host}:{port}/page.html") + assert result.success, result.error + assert "local ok" in result.output + finally: + server.shutdown() + server.server_close() + + @pytest.mark.asyncio async def test_websearch_timeout_message(monkeypatch): import aiohttp diff --git a/tests/updater/test_enterprise_application.py b/tests/updater/test_enterprise_application.py index 30c1fba01..b5779443a 100644 --- a/tests/updater/test_enterprise_application.py +++ b/tests/updater/test_enterprise_application.py @@ -48,6 +48,7 @@ from flocks.storage.storage import Storage from flocks.updater import enterprise, enterprise_application as application +from flocks.updater.machine_fingerprint import MachineNames _REMEMBER = application._remember @@ -134,7 +135,7 @@ def approved(request_id: str = "req_1", license_id: str = "lic_1") -> dict: async def test_ea1_an_application_goes_to_console_and_its_id_is_kept(machine: Path, monkeypatch: pytest.MonkeyPatch): seen = console(monkeypatch, lambda r: httpx.Response(200, json={"request_id": "req_1", "status": "pending"})) - monkeypatch.setattr(application, "machine_fingerprint", lambda: "0123456789abcdef0123456789abcdef") + monkeypatch.setattr(application, "machine_names", lambda: MachineNames("0123456789abcdef0123456789abcdef", "machine-id", "a6d4534ba1eb061f2eb21438bdaec761")) sent = await application.apply(dict(FORM), "admin") assert sent["request_id"] == "req_1" and sent["status"] == "pending" and sent["company"] == "Acme" body = json.loads(seen[0].content) @@ -143,8 +144,11 @@ async def test_ea1_an_application_goes_to_console_and_its_id_is_kept(machine: Pa # The machine is the node: Console holds one open application per node. assert (body["node_id"], body["fingerprint"], body["install_id"], body["passport_uid"]) == ("inst-1", "fp-1", "inst-1", "pp-1") assert body["form_data"]["applied_by"] == "admin" and body["idempotency_key"] == body["form_data"]["idempotency_key"] - # Console binds the licence it issues to the host the application came from. + # Console binds the licence it issues to the host the application came from, by the machine-id digest every + # enterprise core reads; the device id goes beside it for Console's records. assert body["form_data"]["machine"] == "0123456789abcdef0123456789abcdef" + assert body["form_data"]["machine_kind"] == "machine-id" + assert body["form_data"]["devid"] == "a6d4534ba1eb061f2eb21438bdaec761" assert await Storage.get("console:upgrade_request_pending") is None assert body["company_name"] == "Acme" and body["contact_email"] == "li@acme.example" assert body["form_data"]["license_type"] == "poc" and body["form_data"]["applicant_phone"] == "+86 138 0000 0000" @@ -185,18 +189,19 @@ async def test_ea1b_none_while_the_hosts_identifier_cannot_be_read(machine: Path seen = console(monkeypatch, lambda r: httpx.Response(200, json={"request_id": "req_1", "status": "pending"})) from flocks.updater.machine_fingerprint import MachineIdUnreadable - def unreadable() -> str: + def unreadable() -> MachineNames: raise MachineIdUnreadable("ioreg 没有给出 IOPlatformUUID(退出码 1)") - monkeypatch.setattr(application, "machine_fingerprint", unreadable) + monkeypatch.setattr(application, "machine_names", unreadable) with pytest.raises(enterprise.EnterpriseUpgradeError, match="读不到这台机器的标识"): await application.apply(dict(FORM), "admin") assert seen == [] and await Storage.get("console:upgrade_request_pending") is None # A host that keeps none (a container without /etc/machine-id) applies, and Console shows it. - monkeypatch.setattr(application, "machine_fingerprint", lambda: "") + monkeypatch.setattr(application, "machine_names", lambda: MachineNames("", "", "")) await application.apply(dict(FORM), "admin") - assert json.loads(seen[0].content)["form_data"]["machine"] is None + sent = json.loads(seen[0].content)["form_data"] + assert sent["machine"] is None and sent["machine_kind"] is None and sent["devid"] is None async def test_ea2_the_listing(machine: Path, monkeypatch: pytest.MonkeyPatch): @@ -454,7 +459,7 @@ def _lapsed_licence(root: Path) -> Path: async def test_ea7_a_machine_whose_licence_is_over_applies_again(machine: Path, monkeypatch: pytest.MonkeyPatch): licence = _lapsed_licence(machine) seen = console(monkeypatch, lambda r: httpx.Response(200, json={"request_id": "req_7", "status": "pending"})) - monkeypatch.setattr(application, "machine_fingerprint", lambda: "0123456789abcdef0123456789abcdef") + monkeypatch.setattr(application, "machine_names", lambda: MachineNames("0123456789abcdef0123456789abcdef", "machine-id", "a6d4534ba1eb061f2eb21438bdaec761")) sent = await application.apply(dict(FORM), "admin") @@ -521,7 +526,7 @@ def answer(request: httpx.Request) -> httpx.Response: assert (await application.applications())["items"][0]["can_take"] is False # It was never going to be taken: a new application goes through. - monkeypatch.setattr(application, "machine_fingerprint", lambda: "0123456789abcdef0123456789abcdef") + monkeypatch.setattr(application, "machine_names", lambda: MachineNames("0123456789abcdef0123456789abcdef", "machine-id", "a6d4534ba1eb061f2eb21438bdaec761")) assert (await application.apply(dict(FORM), "admin"))["request_id"] == "req_10" # Taking it all the same changes nothing on the machine, and Console hears of it if it had not. @@ -551,7 +556,7 @@ def answer(request: httpx.Request) -> httpx.Response: return httpx.Response(200, json=other) console(monkeypatch, answer) - monkeypatch.setattr(application, "machine_fingerprint", lambda: "0123456789abcdef0123456789abcdef") + monkeypatch.setattr(application, "machine_names", lambda: MachineNames("0123456789abcdef0123456789abcdef", "machine-id", "a6d4534ba1eb061f2eb21438bdaec761")) assert (await application.apply(dict(FORM), "admin"))["request_id"] == "req_10" await application.take("req_9") @@ -663,7 +668,7 @@ async def test_ea7h_a_token_a_patch_revoked_does_not_offer_itself_by_its_own_dat assert (await application.applications())["items"][0]["can_take"] is False console(monkeypatch, lambda r: httpx.Response(200, json={"request_id": "req_10", "status": "pending"})) - monkeypatch.setattr(application, "machine_fingerprint", lambda: "0123456789abcdef0123456789abcdef") + monkeypatch.setattr(application, "machine_names", lambda: MachineNames("0123456789abcdef0123456789abcdef", "machine-id", "a6d4534ba1eb061f2eb21438bdaec761")) assert (await application.apply(dict(FORM), "admin"))["request_id"] == "req_10" diff --git a/tests/updater/test_enterprise_licence_file.py b/tests/updater/test_enterprise_licence_file.py new file mode 100644 index 000000000..e6c44e6ad --- /dev/null +++ b/tests/updater/test_enterprise_licence_file.py @@ -0,0 +1,316 @@ +"""flocks.updater.enterprise_application: licensing offline from the Flocks Pro page. + +Case list (编号 | 场景): + LF1 a licence file in the shape Console's offline issue downloads is written where taking an approved + application writes it, readable by this account only, its patches with it; the machine then has it + LF2 the bare token, as an operator may copy it, is taken as the file's key + LF3 what is no licence file is refused, saying why: empty, not JSON nor a token, no token, a token + not Console's (not ES256), an id that is not the token's, a payload that is not the token's + LF4 a licence no longer valid is refused: revoked by its status, past its date, revoked by the + patch in force + LF5 a licence bound to another machine is refused; bound to this one (by either fingerprint) it is + taken; a host whose fingerprints cannot be read now takes it (the core judges the binding) + LF6 another licence still good is never replaced; one no longer valid is, and a copy of it kept + LF7 the same token again: the file stands, takes the patches it lacked, and no copy is made + LF8 an install the enterprise core runs imports nothing here + LF9 the same token again is judged with the patches the machine holds: a renewal it holds keeps an + expired token good (and the answer says so), a revocation it holds keeps it revoked + LF10 an import and a heartbeat at once: neither writes back a copy read before the other's write, so + no patch is lost + LF11 the same token again, bound to another machine (a data directory moved here): refused before + anything is written, the patches it brings too + OA1 the offline application carries the form and the machine a licence is to be bound to (the machine-id + digest), the device id beside it; nothing goes to Console and nothing is kept + OA2 no offline application while the machine has a licence, while the host's identifier cannot be + read, or on an install the enterprise core runs +""" + +from __future__ import annotations + +import asyncio +import base64 +import json +import stat +import threading +import time +from pathlib import Path + +import pytest + +from flocks.storage.storage import Storage +from flocks.updater import enterprise, enterprise_application as application +from flocks.updater.machine_fingerprint import MachineIdUnreadable, MachineNames + +pytestmark = pytest.mark.asyncio + +FORM = { + "license_type": "poc", + "company": "Acme", + "applicant_name": "Li Lei", + "applicant_email": "li@acme.example", + "applicant_phone": "+86 138 0000 0000", + "sales_rep_name": None, + "notes": "trial for SOC", +} +OURS = "0123456789abcdef0123456789abcdef" +LEGACY = "fedcba9876543210fedcba9876543210" + + +@pytest.fixture +def machine(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: + root = tmp_path / ".flocks" + root.mkdir() + monkeypatch.setenv("FLOCKS_ROOT", str(root)) + monkeypatch.setenv("HOME", str(tmp_path / "home")) + for key in ("FLOCKS_DEPLOY_MODE", "FLOCKS_OFFLINE_INSTALL", "INVOCATION_ID", "FLOCKSPRO_LICENSE_ID", + "FLOCKS_UPDATE_CHANNEL"): + monkeypatch.delenv(key, raising=False) + monkeypatch.setenv("FLOCKS_CONSOLE_BASE_URL", "https://console.example") + enterprise.detect_deploy_mode.cache_clear() + monkeypatch.setattr(application, "_lock", asyncio.Lock()) + monkeypatch.setattr(enterprise, "PREVIOUS_DISTRIBUTION", "flockspro-not-installed-here") + monkeypatch.setattr(enterprise, "_previous_status", lambda: {}) + # This host goes by two fingerprints: its device id and the digest of its identifier. + monkeypatch.setattr(application, "machine_fingerprints", lambda: {OURS, LEGACY}) + monkeypatch.setattr(application, "machine_names", lambda: MachineNames(LEGACY, "machine-id", OURS)) + yield root + enterprise.detect_deploy_mode.cache_clear() + + +def part(value: dict) -> str: + return base64.urlsafe_b64encode(json.dumps(value).encode()).rstrip(b"=").decode() + + +def token(claims: dict, alg: str = "ES256") -> str: + return f"{part({'alg': alg, 'kid': 'flocks-license-prod-2026', 'typ': 'JWT'})}.{part(claims)}.c2ln" + + +def claims(**over) -> dict: + now = int(time.time()) + return {"license_id": "lic_off_1", "status": "poc", "expires_at": now + 90 * 86400, "issued_at": now, + "max_admins": 3, "max_members": 20, **over} + + +def licence_file(**over) -> str: + """The license.json Console's offline issue downloads.""" + body = {"license_id": "lic_off_1", "key": token(claims()), "payload": {}, "patches": []} + body.update(over) + return json.dumps(body) + + +def kept(root: Path) -> Path: + return root / "flockspro" / "license.json" + + +async def test_lf1_a_licence_file_is_written_where_taking_one_writes_it(machine: Path): + patch = token({"license_id": "lic_off_1", "serial": 1, "issued_at": int(time.time()), "dynamic_status": "poc", + "dynamic_expires_at": int(time.time()) + 200 * 86400}) + sent = licence_file(patches=[patch], fingerprint="fp-9", install_id="inst-9") + answer = await application.import_licence(sent) + assert answer["license_id"] == "lic_off_1" and answer["license_status"] == "poc" + written = json.loads(kept(machine).read_text()) + # The Python package's shape, as go/internal/license/legacy.go and the installer read it. + assert written["license_id"] == "lic_off_1" and written["key"] == json.loads(sent)["key"] + assert written["payload"] == {} and written["patches"] == [patch] + assert written["fingerprint"] == "fp-9" and written["install_id"] == "inst-9" and written["imported_at"] + assert stat.S_IMODE(kept(machine).stat().st_mode) == 0o600 + assert stat.S_IMODE(kept(machine).parent.stat().st_mode) == 0o700 + # The page now moves this machine as one with a licence, with the terms of the patch in force. + previous = enterprise.situation()["previous"] + assert previous["license_id"] == "lic_off_1" and not previous["lapsed"] + assert previous["max_admins"] == 3 + + +async def test_lf2_the_bare_token_is_taken_as_the_files_key(machine: Path): + bare = token(claims(license_id="lic_tok_2")) + await application.import_licence(f" {bare}\n") + written = json.loads(kept(machine).read_text()) + assert written["license_id"] == "lic_tok_2" and written["key"] == bare and written["patches"] == [] + + +@pytest.mark.parametrize("content, said", [ + (" ", "空的"), + ("hello, this is no licence", "既不是 JSON"), + ("[1, 2]", "不是 JSON 对象"), + ('{"license_id": "lic_x"}', "没有授权令牌"), + (json.dumps({"key": token(claims(), alg="HS256")}), "不是 Console 签发的格式"), + (json.dumps({"key": token(claims(license_id=""))}), "没有授权编号"), + (json.dumps({"license_id": "lic_other", "key": token(claims())}), "对不上"), + (json.dumps({"key": token(claims()), "payload": {"license_id": "lic_off_1", "status": "commercial"}}), "payload"), +]) +async def test_lf3_what_is_no_licence_file_is_refused(machine: Path, content: str, said: str): + with pytest.raises(enterprise.EnterpriseUpgradeError, match=said): + await application.import_licence(content) + assert not kept(machine).exists() + + +async def test_lf4_a_licence_no_longer_valid_is_refused(machine: Path): + with pytest.raises(enterprise.EnterpriseUpgradeError, match="已吊销"): + await application.import_licence(licence_file(key=token(claims(status="revoked")))) + with pytest.raises(enterprise.EnterpriseUpgradeError, match="到期"): + await application.import_licence(licence_file(key=token(claims(expires_at=int(time.time()) - 86400)))) + # Revoked by Console after it was issued: the patch in force says so. + revoked = token({"license_id": "lic_off_1", "serial": 2, "issued_at": int(time.time()), "dynamic_status": "revoked", + "dynamic_expires_at": int(time.time()) + 86400}) + with pytest.raises(enterprise.EnterpriseUpgradeError, match="已吊销"): + await application.import_licence(licence_file(patches=[revoked])) + assert not kept(machine).exists() + + +async def test_lf5_a_licence_bound_to_another_machine_is_refused(machine: Path, monkeypatch: pytest.MonkeyPatch): + with pytest.raises(enterprise.EnterpriseUpgradeError, match="另一台机器"): + await application.import_licence(licence_file(key=token(claims(machine="aaaabbbbccccddddeeeeffff00001111")))) + assert not kept(machine).exists() + # Bound to this host by the digest of its identifier (a licence issued before the device id). + await application.import_licence(licence_file(key=token(claims(machine=LEGACY.upper())))) + assert json.loads(kept(machine).read_text())["license_id"] == "lic_off_1" + kept(machine).unlink() + # Nothing readable to hold it to: the core judges the binding when the machine moves. + monkeypatch.setattr(application, "machine_fingerprints", lambda: set()) + await application.import_licence(licence_file(key=token(claims(machine="aaaabbbbccccddddeeeeffff00001111")))) + assert kept(machine).exists() + + +async def test_lf6_a_good_licence_is_never_replaced_one_no_longer_valid_is(machine: Path): + kept(machine).parent.mkdir(parents=True) + kept(machine).write_text(json.dumps({"license_id": "lic-old-7", "key": token(claims(license_id="lic-old-7"))})) + with pytest.raises(enterprise.EnterpriseUpgradeError, match="lic-old-7"): + await application.import_licence(licence_file()) + assert json.loads(kept(machine).read_text())["license_id"] == "lic-old-7" + + lapsed = claims(license_id="lic-old-7", expires_at=int(time.time()) - 86400) + kept(machine).write_text(json.dumps({"license_id": "lic-old-7", "key": token(lapsed), "payload": lapsed})) + await application.import_licence(licence_file()) + assert json.loads(kept(machine).read_text())["license_id"] == "lic_off_1" + copies = list(kept(machine).parent.glob("license.replaced-*.json")) + assert len(copies) == 1 and json.loads(copies[0].read_text())["license_id"] == "lic-old-7" + + +async def test_lf7_the_same_token_again_keeps_the_file_and_takes_the_patches_it_lacked(machine: Path): + first = token({"license_id": "lic_off_1", "serial": 1, "issued_at": int(time.time()), "dynamic_status": "poc", + "dynamic_expires_at": int(time.time()) + 100 * 86400}) + second = token({"license_id": "lic_off_1", "serial": 2, "issued_at": int(time.time()), "dynamic_status": "poc", + "dynamic_expires_at": int(time.time()) + 300 * 86400}) + await application.import_licence(licence_file(patches=[first])) + before = json.loads(kept(machine).read_text()) + await application.import_licence(licence_file(patches=[first, second])) + after = json.loads(kept(machine).read_text()) + assert after["patches"] == [first, second] and after["imported_at"] == before["imported_at"] + assert list(kept(machine).parent.glob("license.replaced-*.json")) == [] + # Nothing new: nothing written. + stamp = kept(machine).stat().st_mtime_ns + await application.import_licence(licence_file(patches=[second])) + assert kept(machine).stat().st_mtime_ns == stamp + + +async def test_lf8_an_enterprise_install_imports_nothing_here(machine: Path, monkeypatch: pytest.MonkeyPatch): + monkeypatch.setattr(enterprise, "available", lambda: False) + with pytest.raises(enterprise.EnterpriseUpgradeError, match="已经是企业版"): + await application.import_licence(licence_file()) + assert not kept(machine).exists() + + +async def test_oa1_the_offline_application_carries_the_form_and_this_machine(machine: Path): + before = await Storage.list_keys(prefix="console:upgrade_request") + document = await application.offline_application(dict(FORM), "admin") + assert document["format"] == application.OFFLINE_APPLICATION_FORMAT and document["product"] == "Flocks Pro" + assert {key: document[key] for key in FORM} == FORM + # Console's offline issue binds the licence to the machine-id digest, which every enterprise core reads, and + # keeps the device id beside it. + assert (document["machine"], document["machine_kind"], document["devid"]) == (LEGACY, "machine-id", OURS) + assert document["install_id"] and document["platform"] == enterprise.platform_id() and document["flocks_version"] + assert document["applied_by"] == "admin" and document["replaces_license_id"] is None + # Nothing kept: there is nothing at Console to follow. + assert await Storage.list_keys(prefix="console:upgrade_request") == before + + +async def test_oa2_no_offline_application_where_there_should_be_none(machine: Path, monkeypatch: pytest.MonkeyPatch): + await application.import_licence(licence_file()) + with pytest.raises(enterprise.EnterpriseUpgradeError, match="已经有企业版授权"): + await application.offline_application(dict(FORM), "admin") + kept(machine).unlink() + + def unreadable() -> MachineNames: + raise MachineIdUnreadable("ioreg 没有给出 IOPlatformUUID(退出码 1)") + + monkeypatch.setattr(application, "machine_names", unreadable) + with pytest.raises(enterprise.EnterpriseUpgradeError, match="读不到这台机器的标识"): + await application.offline_application(dict(FORM), "admin") + + monkeypatch.setattr(enterprise, "available", lambda: False) + with pytest.raises(enterprise.EnterpriseUpgradeError, match="不能在这里申请"): + await application.offline_application(dict(FORM), "admin") + + +def patch_token(serial: int, status: str = "poc", days: int = 200) -> str: + now = int(time.time()) + return token({"license_id": "lic_off_1", "serial": serial, "issued_at": now, "dynamic_status": status, + "dynamic_expires_at": now + days * 86400}) + + +async def test_lf9_the_same_token_again_is_judged_with_what_the_machine_holds(machine: Path): + expired = token(claims(expires_at=int(time.time()) - 86400)) + renewal = patch_token(1, days=300) + kept(machine).parent.mkdir(parents=True) + kept(machine).write_text(json.dumps({"license_id": "lic_off_1", "key": expired, "payload": {}, "patches": [renewal]})) + # The token by itself is past its date; the machine holds its renewal. + answer = await application.import_licence(licence_file(key=expired)) + assert answer["license_status"] == "poc" and answer["expires_at"] > time.time() + 200 * 86400 + assert json.loads(kept(machine).read_text())["patches"] == [renewal] + + # A revocation the machine holds outranks an older good patch the file brings. + revoked = patch_token(5, status="revoked") + older = patch_token(2) + kept(machine).write_text(json.dumps({"license_id": "lic_off_1", "key": expired, "payload": {}, "patches": [renewal, revoked]})) + with pytest.raises(enterprise.EnterpriseUpgradeError, match="已吊销"): + await application.import_licence(licence_file(key=expired, patches=[older])) + held = json.loads(kept(machine).read_text()) + assert held["patches"] == [renewal, revoked, older] and held["key"] == expired + + +async def test_lf10_an_import_and_a_heartbeat_at_once_lose_no_patch(machine: Path, monkeypatch: pytest.MonkeyPatch): + from flocks.console.login import keep_previous_licence_current + + first, second, revoke = patch_token(1), patch_token(2), patch_token(3, status="revoked") + await application.import_licence(licence_file(patches=[first])) + entered, release = threading.Event(), threading.Event() + real_write = application._write_licence + + def slow_write(path: Path, content: dict) -> None: + entered.set() + release.wait(5) + real_write(path, content) + + monkeypatch.setattr(application, "_write_licence", slow_write) + failures: list[BaseException] = [] + + def run_import() -> None: + try: + asyncio.run(application._import_licence(licence_file(patches=[first, second]))) + except BaseException as exc: # reported below + failures.append(exc) + + importer = threading.Thread(target=run_import) + importer.start() + assert entered.wait(5) + # The heartbeat arrives while the import is between its read and its write. + heartbeat = threading.Thread(target=keep_previous_licence_current, args=({"license_patch": revoke},)) + heartbeat.start() + heartbeat.join(0.3) + assert heartbeat.is_alive(), "the heartbeat must wait for the import's write" + release.set() + importer.join(5) + heartbeat.join(5) + assert not failures + patches = json.loads(kept(machine).read_text())["patches"] + assert set(patches) == {first, second, revoke} + + +async def test_lf11_the_same_token_bound_elsewhere_is_refused_before_anything_is_written(machine: Path): + elsewhere = token(claims(machine="b" * 32, expires_at=int(time.time()) - 86400)) + kept(machine).parent.mkdir(parents=True) + held = {"license_id": "lic_off_1", "key": elsewhere, "payload": {}, "patches": []} + kept(machine).write_text(json.dumps(held)) + with pytest.raises(enterprise.EnterpriseUpgradeError, match="另一台机器"): + await application.import_licence(licence_file(key=elsewhere, patches=[patch_token(1, days=300)])) + assert json.loads(kept(machine).read_text()) == held diff --git a/tests/updater/test_enterprise_upgrade.py b/tests/updater/test_enterprise_upgrade.py index d0a0b210c..815c62a4e 100644 --- a/tests/updater/test_enterprise_upgrade.py +++ b/tests/updater/test_enterprise_upgrade.py @@ -20,6 +20,11 @@ ended (exit status, log), also after this server is gone EU5b a finished install the enterprise edition has since gone back from (its downgrade record is newer) is no upgrade any more: the page does not say it is installed + EU5i an install whose exit status never came back (the Windows installer writes it last, from a + console window that can hold it there or be closed on it) is finished once the installer's + own record of this run says done; an earlier run's record, one still switching the machine + over, one that does not read or a run that did not note what was there say nothing, and an + exit status that did come back keeps the last word EU6 the whole of it: a systemd machine ends with root's command for the downloaded file, an account's own install with the installer running; one at a time EU7 what the enterprise edition's downgrades kept aside is listed from its record (when, still @@ -775,6 +780,100 @@ def test_eu5f_a_process_gone_without_an_exit_code_is_not_given_its_last_line_for assert state["recovery"] == "unknown" +def _installers_record(machine: Path, record_id: str, phase: str, **fields) -> Path: + """The record install-managed leaves in the open edition's data (installation-result.json).""" + path = machine / "run" / "installation-result.json" + path.parent.mkdir(parents=True, exist_ok=True) + text = {"title": "企业版升级未完成", "message": "原 SQLite 数据和原安装已保留,可以继续使用。"} + path.write_text(json.dumps({ + "version": 1, "id": record_id, "phase": phase, "recovery": "unchanged", + "updated_at": "2026-11-12T02:25:33Z", "detail": "", + "messages": {"zh-CN": text, "en-US": text}, **fields, + }), encoding="utf-8") + return path + + +def test_eu5i_an_install_the_installer_recorded_done_is_finished_without_its_exit_status(machine: Path): + """INC-E6D264C2: the enterprise edition served, and the page went on saying installing: the + installer never got to write its exit status, and nothing else was asked.""" + # The installer is still there as far as anyone can tell, and has left no exit status. + running = {"phase": "installing", "pid": os.getpid(), "log": "", "version": "2026.11.9", "prior_result": "an-earlier-run"} + enterprise._write_state(running) + assert enterprise.read_state()["phase"] == "installing" + # The record that was there before this run, whatever it says: another run's. + _installers_record(machine, "an-earlier-run", "done") + assert enterprise.read_state()["phase"] == "installing" + # This run's, while it switches the machine over. + _installers_record(machine, "this-run-started", "running") + assert enterprise.read_state()["phase"] == "installing" + # And once the release it put in place serves. + _installers_record(machine, "this-run-ended", "done") + state = enterprise.read_state() + assert state["phase"] == "finished" and "exit_code" not in state and "reason" not in state + assert enterprise.situation()["upgrade"]["phase"] == "finished" + # Gone since or not (its window closed, the machine restarted): it finished. + enterprise._write_state({**running, "pid": 2**22 + 12345}) + assert enterprise.read_state()["phase"] == "finished" + # A machine with no record before the run. + enterprise._write_state({**running, "prior_result": None}) + assert enterprise.read_state()["phase"] == "finished" + + +def test_eu5i_a_record_that_says_nothing_of_this_run_ends_nothing(machine: Path): + running = {"phase": "installing", "pid": os.getpid(), "log": "", "prior_result": "an-earlier-run"} + gone = {**running, "pid": 2**22 + 12345} + result = _installers_record(machine, "this-run", "done") + # A run that did not note which record was there before it, or could not read it then: the + # record may be that one. + for noted in ({}, {"prior_result": "unreadable"}): + enterprise._write_state({key: value for key, value in running.items() if key != "prior_result"} | noted) + assert enterprise.read_state()["phase"] == "installing" + # A record that does not read. + result.write_text("not json", encoding="utf-8") + enterprise._write_state(running) + assert enterprise.read_state()["phase"] == "installing" + enterprise._write_state(gone) + state = enterprise.read_state() + assert state["phase"] == "failed" and state["recovery"] == "unknown" + # One that says it failed: the installer has yet to say how it ended; gone without, it failed + # as the record says. + _installers_record(machine, "this-run", "failed", recovery="restored", detail="the core did not come up") + enterprise._write_state(running) + assert enterprise.read_state()["phase"] == "installing" + enterprise._write_state(gone) + state = enterprise.read_state() + assert state["phase"] == "failed" and state["recovery"] == "restored" and state["reason"] == "the core did not come up" + + +def test_eu5i_an_exit_status_that_came_back_keeps_the_last_word(machine: Path): + enterprise._write_state({"phase": "installing", "pid": os.getpid(), "log": "", "prior_result": "an-earlier-run"}) + _installers_record(machine, "this-run", "done") + exit_file = enterprise.work_dir() / "exit-status" + exit_file.write_text("3\n", encoding="utf-8") + state = enterprise.read_state() + assert state["phase"] == "failed" and state["exit_code"] == 3 + exit_file.write_text("0\n", encoding="utf-8") + state = enterprise.read_state() + assert state["phase"] == "finished" and state["exit_code"] == 0 + # One being written this moment reads as none yet. + exit_file.write_text("", encoding="utf-8") + assert enterprise.read_state()["phase"] == "finished" + + +def test_eu5i_an_install_finished_by_its_record_that_went_back_is_no_upgrade_any_more(machine: Path): + enterprise._write_state({"phase": "installing", "pid": 2**22 + 12345, "version": "2026.11.9", "log": "", "prior_result": None}) + started = time.time() - 100 + os.utime(enterprise._state_file(), (started, started)) + _installers_record(machine, "this-run", "done") + assert enterprise.read_state()["phase"] == "finished" + record = machine / enterprise.DOWNGRADE_RECORD + record.write_text('{"version": 1, "kept": []}', encoding="utf-8") + os.utime(record, (started - 50, started - 50)) # a downgrade before this install + assert enterprise.read_state()["phase"] == "finished" + os.utime(record, (started + 50, started + 50)) # and one after it + assert enterprise.read_state() is None + + def test_eu5g_a_run_from_the_terminal_failed_at_the_install(machine: Path): enterprise.work_dir().mkdir(parents=True, exist_ok=True) (enterprise.work_dir() / "exit-status").write_text("1\n", encoding="utf-8") @@ -1072,6 +1171,27 @@ class Child: assert enterprise.read_state()["phase"] == "finished" +def test_eu8_the_windows_installer_held_in_its_window_is_finished_by_its_record(windows: Path, monkeypatch: pytest.MonkeyPatch): + """The page's run on Windows: the installer it started waits on the elevated one, whose window + holds it after the release serves. No exit status, and the process is there.""" + asked: list[int] = [] + monkeypatch.setattr(enterprise, "_windows_pid_alive", lambda pid: asked.append(pid) or True) + work = enterprise.work_dir() + work.mkdir(parents=True, exist_ok=True) + log_file = work / "install.log" + log_file.write_text("\n== 2026-11-12T10:21:07+0800 flockspro-2026.11.9-windows-amd64.exe\n安装要管理员权限,正在请求(请在弹出的确认框里点「是」)...\n", encoding="utf-8") + enterprise._write_state({"phase": "installing", "pid": 31337, "release_id": "2026.11.9-windows-amd64", "version": "2026.11.9", + "log": str(log_file), "prior_result": None}) + state = enterprise.read_state() + assert state["phase"] == "installing" and asked == [31337] + _installers_record(windows, "2026-11-12T02:25:33.5Z-1a2b3c4d", "done") + state = enterprise.read_state() + assert state["phase"] == "finished" and "exit_code" not in state + assert "安装要管理员权限,正在请求(请在弹出的确认框里点「是」)..." in state["log_tail"] + # Nobody asks after the process once the record says how the run ended. + assert asked == [31337] + + def test_eu8_a_run_is_looked_at_without_os_kill_on_windows(windows: Path, monkeypatch: pytest.MonkeyPatch): def kill(*_args): raise AssertionError("os.kill ends the process it names on Windows") diff --git a/tests/updater/test_machine_fingerprint.py b/tests/updater/test_machine_fingerprint.py index ceb5f3452..a6a24313d 100644 --- a/tests/updater/test_machine_fingerprint.py +++ b/tests/updater/test_machine_fingerprint.py @@ -1,12 +1,23 @@ """flocks.updater.machine_fingerprint: this machine as the enterprise core names it. Case list (编号 | 场景): - MF1 the digest is the core's (activation.MachineFingerprint): sha256 of the domain and the id, trimmed - and lower-cased, its first 16 bytes in hex; no id gives none - MF2 on Linux the machine id comes from /etc/machine-id, then the D-Bus copy; none when neither has one; - one that cannot be read is MachineIdUnreadable, not none - MF3 on macOS it comes from the platform UUID ioreg reports; ioreg not running, failing or naming none - is MachineIdUnreadable (every Mac has one) + MF1 the machine-id digest is the core's: sha256 of the domain and the id, trimmed and lower-cased, its first + 16 bytes in hex; no id gives none + MF2 the device id is the core's and the library's: MD5 of "flocks" and what it hashes, the digits libdevid + printed on a Linux VM (in lower case), real UUIDs put in its SMBIOS table among them; UUIDs format as + dmidecode prints them, in lower case; the SMBIOS table walk finds the type 1 UUID and stops at a table cut + short -- the same cases as flockspro go/internal/devid + MF3 on Linux the machine id gives the fingerprint a licence is bound to, the digest, from /etc/machine-id, + then the D-Bus copy, whether or not the SMBIOS table can be read; the device id from a readable table + (root) goes beside it, none without root or for a UUID the firmware leaves unset; a host without a + machine id is named by its device id, by nothing when it has neither; a machine id that cannot be read + (a file it may not read, one that is not text) is MachineIdUnreadable, not none, even with the device + id there, which still counts among the host's fingerprints + MF4 an AWS Xen host's device id hashes its board asset tag, else its hypervisor UUID, which any account may + read; it names the host only where there is no machine id + MF5 on macOS the platform UUID ioreg reports gives the digest, its device id beside it; ioreg not running, + failing or naming none is MachineIdUnreadable (every Mac has one) + MF6 elsewhere (Windows) the host is not named: applications go out unbound, as before """ from __future__ import annotations @@ -25,27 +36,132 @@ def test_mf1_the_digest_is_the_cores(): assert mf.fingerprint_of(" ") == "" -def test_mf2_linux_reads_the_machine_id_then_the_dbus_copy(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): - etc, dbus = tmp_path / "machine-id", tmp_path / "dbus-machine-id" +def test_mf2_the_device_id_is_the_librarys(): + # get_dev_id("flocks", "") of libdevid-1.2.6 on a QEMU VM whose firmware sets no UUID: none read without + # root, "Not Settable" with. + assert mf.device_id_of("") == "58ab768421a90d0fec6ecff8ea0b1bf5" + assert mf.device_id_of("Not Settable") == "a6d4534ba1eb061f2eb21438bdaec761" + # Real UUIDs as the table holds them (SMBIOS 2.8), and what libdevid printed for each once root bind-mounted + # that table over /sys/firmware/dmi/tables/DMI. Upper-case text hashes to other ids. + for raw, want in { + "44454c4c350010308030b4c04f4b4b32": "4118c84a2b529d4532ecef9d021c2ae3", + "0123456789abcdeffedcba9876543210": "c7093283e36914e17c95fb40281665fc", + "a1b2c3d4e5f60718293a4b5c6d7e8f90": "2d71ce041ce578e2da445b203efb372f", + }.items(): + assert mf.device_id_of(mf.format_smbios_uuid(bytes.fromhex(raw), 2, 8)) == want, raw + + uuid = bytes([0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE, 0xF0, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88]) + assert mf.format_smbios_uuid(bytes(16), 2, 8) == "Not Settable" + assert mf.format_smbios_uuid(b"\xff" * 16, 3, 0) == "Not Present" + assert mf.format_smbios_uuid(uuid, 2, 8) == "78563412-bc9a-f0de-1122-334455667788" + assert mf.format_smbios_uuid(uuid, 3, 2) == "78563412-bc9a-f0de-1122-334455667788" + assert mf.format_smbios_uuid(uuid, 2, 5) == "12345678-9abc-def0-1122-334455667788" + assert mf.format_smbios_uuid(uuid[:15], 2, 8) == "" + + bios = bytes([0, 0x12, 0, 0]) + bytes(0x0E) + b"v1\0\0" + system = bytes([1, 0x1B, 1, 0, 1, 2, 0, 0]) + uuid + bytes([6, 0, 0]) + b"QEMU\0pc\0\0" + end = bytes([127, 4, 2, 0, 0, 0]) + assert mf.smbios_system_uuid(bios + system + end, 2, 8) == "78563412-bc9a-f0de-1122-334455667788" + for name, cut in { + "no type 1": bios + end, + "type 1 before the UUID": bytes([1, 0x08, 1, 0, 1, 2, 0, 0, 0, 0]), + "length past the end": bytes([1, 0x40, 1, 0, 0, 0]), + "length under four": bytes([1, 2, 0, 0, 0, 0]), + "UUID cut short": system[:20], + "empty": b"", + }.items(): + assert mf.smbios_system_uuid(cut, 2, 8) == "", name + + +def _linux(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> dict[str, Path]: + paths = { + "etc": tmp_path / "machine-id", "dbus": tmp_path / "dbus-machine-id", "entry": tmp_path / "smbios_entry_point", + "table": tmp_path / "DMI", "hypervisor": tmp_path / "hypervisor-uuid", "tag": tmp_path / "board_asset_tag", + } monkeypatch.setattr(mf.sys, "platform", "linux") - monkeypatch.setattr(mf, "LINUX_MACHINE_ID_FILES", (etc, dbus)) - assert mf.machine_fingerprint() == "" - dbus.write_text("ABC\n") - assert mf.machine_fingerprint() == mf.fingerprint_of("abc") - etc.write_text("\n") + monkeypatch.setattr(mf, "LINUX_MACHINE_ID_FILES", (paths["etc"], paths["dbus"])) + monkeypatch.setattr(mf, "LINUX_SMBIOS_ENTRY_POINT", paths["entry"]) + monkeypatch.setattr(mf, "LINUX_SMBIOS_TABLE", paths["table"]) + monkeypatch.setattr(mf, "LINUX_HYPERVISOR_UUID", paths["hypervisor"]) + monkeypatch.setattr(mf, "LINUX_BOARD_ASSET_TAG", paths["tag"]) + return paths + + +def _table(uuid: bytes) -> bytes: + return bytes([1, 0x1B, 1, 0, 1, 2, 0, 0]) + uuid + bytes([6, 0, 0]) + b"QEMU\0pc\0\0" + bytes([127, 4, 2, 0, 0, 0]) + + +def test_mf3_linux(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): + paths = _linux(monkeypatch, tmp_path) + # No SMBIOS table to read (no root here) and no machine id: nothing names the host. + assert mf.machine_names() == ("", "", "") + assert mf.machine_identity() == ("", "") + paths["dbus"].write_text("ABC\n") + assert mf.machine_names() == (mf.fingerprint_of("abc"), mf.KIND_MACHINE_ID, "") + paths["etc"].write_text("\n") assert mf.machine_fingerprint() == mf.fingerprint_of("abc"), "an empty machine-id falls through to the D-Bus copy" - etc.write_text("def\n") - assert mf.machine_fingerprint() == mf.fingerprint_of("def") + paths["etc"].write_text("def\n") + assert mf.machine_identity() == (mf.fingerprint_of("def"), mf.KIND_MACHINE_ID) + + # SMBIOS 3.0 entry point (version at bytes 7 and 8), and the table root may read: the digest still names + # the host, the device id goes beside it. + uuid = bytes([0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE, 0xF0, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88]) + paths["entry"].write_bytes(b"_SM3_" + bytes([0x18, 0x18, 3, 2]) + bytes(15)) + paths["table"].write_bytes(_table(uuid)) + device = mf.device_id_of("78563412-bc9a-f0de-1122-334455667788") + assert mf.machine_names() == (mf.fingerprint_of("def"), mf.KIND_MACHINE_ID, device) + assert mf.machine_identity() == (mf.fingerprint_of("def"), mf.KIND_MACHINE_ID) + assert mf.machine_fingerprints() == {mf.fingerprint_of("def"), device} + # A 32-bit entry point of SMBIOS 2.4: the UUID as the firmware has it. + paths["entry"].write_bytes(b"_SM_" + bytes([0, 0x1F, 2, 4]) + bytes(23)) + assert mf.machine_names().devid == mf.device_id_of("12345678-9abc-def0-1122-334455667788") + # A UUID the firmware leaves unset is no device id. + paths["table"].write_bytes(_table(bytes(16))) + assert mf.machine_names() == (mf.fingerprint_of("def"), mf.KIND_MACHINE_ID, "") + paths["table"].write_bytes(_table(uuid)) + # A host without a machine id is named by its device id. + paths["etc"].unlink() + paths["dbus"].unlink() + device = mf.device_id_of("12345678-9abc-def0-1122-334455667788") + assert mf.machine_names() == (device, mf.KIND_DEVID, device) + paths["etc"].write_text("def\n") def unreadable(self, *args, **kwargs): raise PermissionError(13, "Permission denied") + # A machine id file that is not text cannot be read either: said as such, not as a crash, and the device id + # still counts among the host's fingerprints. + paths["etc"].write_bytes(b"\xff\xfe not utf-8\n") + with pytest.raises(mf.MachineIdUnreadable, match="不是文本"): + mf.machine_names() + assert mf.machine_fingerprints() == {device} + paths["etc"].write_text("def\n") + + # A machine id that cannot be read is no host without one: the device id does not stand in for it, a core + # that cannot read the device id would not know the host by it. monkeypatch.setattr(Path, "read_text", unreadable) + with pytest.raises(mf.MachineIdUnreadable, match="Permission denied"): + mf.machine_names() + assert mf.machine_fingerprints() == {device} + paths["table"].unlink() with pytest.raises(mf.MachineIdUnreadable, match="Permission denied"): mf.machine_fingerprint() -def test_mf3_macos_reads_the_platform_uuid(monkeypatch: pytest.MonkeyPatch): +def test_mf4_an_aws_host(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): + paths = _linux(monkeypatch, tmp_path) + paths["hypervisor"].write_text("ec2e1916-9099-7caf-fd21-012345abcdef\n") + assert mf.machine_identity() == (mf.device_id_of("ec2e1916-9099-7caf-fd21-012345abcdef"), mf.KIND_DEVID) + paths["tag"].write_text("i-0abc\n") + assert mf.machine_identity() == (mf.device_id_of("i-0abc"), mf.KIND_DEVID) + paths["etc"].write_text("abc\n") + assert mf.machine_names() == (mf.fingerprint_of("abc"), mf.KIND_MACHINE_ID, mf.device_id_of("i-0abc")) + paths["etc"].unlink() + paths["hypervisor"].write_text("4c4c4544-0035-3010-8030-b4c04f4b4b32\n") + assert mf.machine_identity() == ("", ""), "a hypervisor UUID that is no EC2 one is no AWS host" + + +def test_mf5_macos_reads_the_platform_uuid(monkeypatch: pytest.MonkeyPatch): monkeypatch.setattr(mf.sys, "platform", "darwin") calls: list[list[str]] = [] @@ -54,7 +170,8 @@ def run(args, **kwargs): return subprocess.CompletedProcess(args, 0, stdout=' "IOPlatformUUID" = "1A2B-3C4D"\n', stderr="") monkeypatch.setattr(mf.subprocess, "run", run) - assert mf.machine_fingerprint() == mf.fingerprint_of("1a2b-3c4d") + assert mf.machine_names() == (mf.fingerprint_of("1A2B-3C4D"), mf.KIND_MACHINE_ID, mf.device_id_of("1a2b-3c4d")) + assert mf.fingerprint_of("1A2B-3C4D") == mf.fingerprint_of("1a2b-3c4d"), "the core digests the id in lower case" assert calls == [["/usr/sbin/ioreg", "-rd1", "-c", "IOPlatformExpertDevice"]] monkeypatch.setattr(mf.subprocess, "run", lambda *a, **k: subprocess.CompletedProcess(a, 0, stdout="nothing", stderr="")) @@ -71,3 +188,9 @@ def timeout(*args, **kwargs): monkeypatch.setattr(mf.subprocess, "run", timeout) with pytest.raises(mf.MachineIdUnreadable): mf.machine_fingerprint() + + +def test_mf6_elsewhere_the_host_is_not_named(monkeypatch: pytest.MonkeyPatch): + monkeypatch.setattr(mf.sys, "platform", "win32") + assert mf.machine_identity() == ("", "") + assert mf.machine_names() == ("", "", "") diff --git a/tests/workflow/test_stream_alert_triage_persistence.py b/tests/workflow/test_stream_alert_triage_persistence.py index 5cd1f2a62..50d54b0b2 100644 --- a/tests/workflow/test_stream_alert_triage_persistence.py +++ b/tests/workflow/test_stream_alert_triage_persistence.py @@ -36,7 +36,33 @@ def _load_dedup_code() -> str: return next(node["code"] for node in workflow["nodes"] if node["id"] == "load_dedup_file") +# Writing the alert store is the platform's job now (flocks.workflow.soc_store); +# the workflow only hands its alerts to the ``soc`` service. These are the +# functions that moved there with the SQLite store. +_STORE_FUNCTIONS = frozenset({ + "_ensure_soc_db_schema", + "_event_time_value", + "_asset_date_value", + "_source_type_value", + "_record_id_value", + "_stable_row_id", + "_load_existing_soc_rows", + "_merge_triage_record", + "_triage_write_soc_db", +}) + + def _load_functions(*names: str) -> dict[str, object]: + namespace = _load_workflow_functions(*(name for name in names if name not in _STORE_FUNCTIONS)) + from flocks.workflow.soc_store import triage + + for name in names: + if name in _STORE_FUNCTIONS: + namespace[name] = getattr(triage, name) + return namespace + + +def _load_workflow_functions(*names: str) -> dict[str, object]: tree = ast.parse(_concurrent_triage_code()) body = [ node @@ -234,8 +260,97 @@ def test_soc_db_persistence_uses_filtered_first_seen_alerts() -> None: ] assert len(write_calls) == 1 - assert isinstance(write_calls[0].args[1], ast.Name) - assert write_calls[0].args[1].id == "first_seen_soc_alerts" + assert isinstance(write_calls[0].args[0], ast.Name) + assert write_calls[0].args[0].id == "first_seen_soc_alerts" + + +def test_workflow_hands_alerts_to_the_soc_service_in_bounded_batches() -> None: + """The node opens no database: it sends batches to ``soc.write_alerts`` and adds the answers up.""" + functions = _load_workflow_functions("_triage_write_soc_db") + calls: list[tuple[int, str, str]] = [] + + class FakeSoc: + def write_alerts(self, alerts, run_id, source_file=""): + calls.append((len(alerts), run_id, source_file)) + return {"backend": "anywhere", "path": "the/alert/store", "table": "alert_records", + "rows": len(alerts), "inserted_rows": len(alerts) - 1, "updated_rows": 1, "unchanged_rows": 0} + + functions["soc"] = FakeSoc() + functions["inputs"] = {"loaded_files": ["/source/batch.jsonl"]} + alerts = [{"dedup_key": f"key-{index}", "is_duplicate": False} for index in range(450)] + + result = functions["_triage_write_soc_db"](alerts, 42) + + assert calls == [(200, "42", "/source/batch.jsonl"), (200, "42", "/source/batch.jsonl"), (50, "42", "/source/batch.jsonl")] + assert result == {"backend": "anywhere", "path": "the/alert/store", "table": "alert_records", + "rows": 450, "inserted_rows": 447, "updated_rows": 3, "unchanged_rows": 0} + + +def test_workflow_batches_by_bytes_and_sends_an_oversized_alert_alone() -> None: + functions = _load_workflow_functions("_triage_write_soc_db") + sizes: list[int] = [] + + class FakeSoc: + def write_alerts(self, alerts, run_id, source_file=""): + sizes.append(len(alerts)) + return {"rows": len(alerts)} + + functions["soc"] = FakeSoc() + functions["inputs"] = {} + megabyte = "x" * (1024 * 1024) + alerts = [ + {"dedup_key": "a", "payload": megabyte}, + {"dedup_key": "b", "payload": megabyte}, # a + b would pass 2 MiB + {"dedup_key": "huge", "payload": megabyte * 3}, # larger than a batch on its own + {"dedup_key": "c"}, + ] + + result = functions["_triage_write_soc_db"](alerts, "run") + + assert sizes == [1, 1, 1, 1] + assert result["rows"] == 4 + + +def test_workflow_node_writes_the_sqlite_store_through_the_soc_service(tmp_path: Path, monkeypatch) -> None: + """End to end on this backend: the node's code, the service a node gets, the SQLite alert store.""" + from flocks.coordination import workflow_services + from flocks.workflow.soc_store import _paths + + db_path = tmp_path / "data" / "soc.db" + monkeypatch.setattr(_paths, "SOC_DB", db_path) + functions = _load_workflow_functions("_triage_write_soc_db") + functions["soc"] = workflow_services(lambda: False)["soc"] + functions["inputs"] = {"loaded_files": ["/source/batch.jsonl"]} + alerts = [ + {"dedup_key": "first", "is_duplicate": False, "id": "1", "time": 1784026800}, + {"dedup_key": "second", "is_duplicate": False, "id": "2", "time": 1784026801}, + ] + + first = functions["_triage_write_soc_db"](alerts, "run-1") + again = functions["_triage_write_soc_db"](alerts[:1], "run-2") + + assert (first["backend"], first["path"], first["table"]) == ("sqlite", str(db_path), "alert_records") + assert (first["rows"], first["inserted_rows"], first["updated_rows"]) == (2, 2, 0) + assert (again["rows"], again["inserted_rows"], again["updated_rows"]) == (1, 0, 1) + with sqlite3.connect(db_path) as connection: + rows = connection.execute( + "SELECT dedup_key, source_file, json_extract(record_json, '$._triage_run_id') " + "FROM alert_records ORDER BY event_time" + ).fetchall() + assert rows == [("first", "/source/batch.jsonl", "run-2"), ("second", "/source/batch.jsonl", "run-1")] + + +def test_soc_service_refuses_a_cancelled_workflow(tmp_path: Path, monkeypatch) -> None: + from flocks.coordination import workflow_services + from flocks.workflow.soc_store import _paths + + monkeypatch.setattr(_paths, "SOC_DB", tmp_path / "soc.db") + service = workflow_services(lambda: True)["soc"] + + assert service.exposed_methods == ("write_alerts",) + with pytest.raises(RuntimeError, match="cancelled"): + service.write_alerts([{"dedup_key": "first", "is_duplicate": False}], "run") + assert not (tmp_path / "soc.db").exists() def test_apply_triage_fields_preserves_original_alert_fields() -> None: diff --git a/uv.lock b/uv.lock index 46915e387..2c7d4b879 100644 --- a/uv.lock +++ b/uv.lock @@ -553,7 +553,7 @@ wheels = [ [[package]] name = "flocks" -version = "2026.11.9" +version = "2026.11.18" source = { editable = "." } dependencies = [ { name = "aiofiles" }, @@ -609,6 +609,7 @@ dependencies = [ { name = "toml" }, { name = "tree-sitter" }, { name = "typer" }, + { name = "tzdata", marker = "sys_platform == 'win32'" }, { name = "ulid-py" }, { name = "uvicorn", extra = ["standard"] }, { name = "watchdog" }, @@ -681,6 +682,7 @@ requires-dist = [ { name = "toml", specifier = ">=0.10.2" }, { name = "tree-sitter", specifier = ">=0.21.0" }, { name = "typer", specifier = ">=0.9.0,<0.24.0" }, + { name = "tzdata", marker = "sys_platform == 'win32'", specifier = ">=2025.2" }, { name = "ulid-py", specifier = ">=1.1.0" }, { name = "uvicorn", extras = ["standard"], specifier = ">=0.27.0" }, { name = "watchdog", specifier = ">=4.0.0" }, @@ -2415,6 +2417,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/dc/9b/47798a6c91d8bdb567fe2698fe81e0c6b7cb7ef4d13da4114b41d239f65d/typing_inspection-0.4.2-py3-none-any.whl", hash = "sha256:4ed1cacbdc298c220f1bd249ed5287caa16f34d44ef4e9c3d0cbad5b521545e7", size = 14611, upload-time = "2025-10-01T02:14:40.154Z" }, ] +[[package]] +name = "tzdata" +version = "2026.6" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/7a/29/6a1391d31cd00ff9e927215a224a880e1e84e826b64ba80a499e51c074d8/tzdata-2026.6.tar.gz", hash = "sha256:85d2cd9c09f81f0bb29db27759fc83af4f1e620efb814f8c5bf8b4cc4feece6d", size = 201017, upload-time = "2026-10-28T09:57:09.137Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0a/66/9a06c2227fedfd4919f0eaaa8b94377d9730882a7e4f95823c9a331ab5e1/tzdata-2026.6-py2.py3-none-any.whl", hash = "sha256:0a10eec6e13ef16b627fabed9a5f2ba61a62b1c67f327305f4e7e412a70b4aec", size = 348210, upload-time = "2026-10-28T09:57:07.276Z" }, +] + [[package]] name = "ulid-py" version = "1.1.0" diff --git a/webui/src/api/auth.ts b/webui/src/api/auth.ts index 936b3474f..ebc01bf57 100644 --- a/webui/src/api/auth.ts +++ b/webui/src/api/auth.ts @@ -2,6 +2,10 @@ import client from './client'; export interface BootstrapStatus { bootstrapped: boolean; + /** Whether this browser may create the first administrator (only one on the server's own machine). */ + setup_allowed?: boolean; + /** Where a browser on that machine reaches the service, when loopback reaches it. */ + local_url?: string | null; } export interface LocalUser { @@ -33,6 +37,16 @@ export interface ConsoleLoginFinishResult { updated_at?: string | null; } +/** Whether this install reaches Console now (flocks.console.connectivity): what the licence pages offer. */ +export interface ConsoleConnectivity { + /** A Console address is set at all. */ + configured: boolean; + /** Console answered just now (or within half a minute). */ + online: boolean; + console_host: string; + checked_at: string; +} + export interface ConsoleLoginSessionStatus { logged_in: boolean; console_login_id?: string | null; @@ -102,4 +116,12 @@ export const authApi = { logoutConsoleLogin: async (): Promise => { await client.post('/api/auth/console-login/logout'); }, + + /** Whether Console can be reached from here; `refresh` asks it now rather than from the last half minute. */ + consoleConnectivity: async (refresh = false): Promise => { + const response = await client.get('/api/auth/console-login/connectivity', { + params: refresh ? { refresh: true } : undefined, + }); + return response.data; + }, }; diff --git a/webui/src/api/enterpriseUpgrade.ts b/webui/src/api/enterpriseUpgrade.ts index fd213e764..cf33902a3 100644 --- a/webui/src/api/enterpriseUpgrade.ts +++ b/webui/src/api/enterpriseUpgrade.ts @@ -111,6 +111,46 @@ export interface LicenceApplicationForm { notes?: string | null; } +/** + * The application handed to whoever issues licences when Console cannot be reached from here + * (flocks.updater.enterprise_application.offline_application): the form, and the machine a licence + * issued for it is bound to. + */ +export interface OfflineApplication { + format: string; + product: string; + license_type: 'poc' | 'commercial'; + company: string; + applicant_name: string; + applicant_email: string; + applicant_phone: string; + sales_rep_name: string | null; + notes: string | null; + replaces_license_id: string | null; + /** + * 32 hex digits, what the licence is bound to: the machine-id digest, the device id of a host without a + * machine id; null on a host that keeps neither (the licence then cannot be bound). + */ + machine: string | null; + /** 'machine-id' or 'devid': which fingerprint machine is. */ + machine_kind: string | null; + /** The device id where it can be read, beside machine, for Console's records. */ + devid?: string | null; + install_id: string | null; + hostname: string | null; + platform: string; + flocks_version: string; + applied_by: string; + created_at: string; +} + +/** A licence file imported on this machine. */ +export interface ImportedLicence { + license_id: string; + license_status: string | null; + expires_at: string | number | null; +} + /** What a sync with Console came to (flocks.updater.enterprise_application.sync_licence). */ export interface LicenceSync { /** The licence's terms are not what they were before it. */ @@ -151,6 +191,14 @@ export const enterpriseUpgradeApi = { withdraw: async (requestId: string): Promise => (await client.post(`/api/enterprise-upgrade/applications/${encodeURIComponent(requestId)}/withdraw`)).data.application, + /** The application file for an offline application; nothing is sent to Console. */ + offlineApplication: async (form: LicenceApplicationForm): Promise => + (await client.post('/api/enterprise-upgrade/applications/offline', form)).data.application, + + /** Writes a licence file sent back for an offline application on this machine; its situation after it. */ + importLicence: async (content: string): Promise<{ licence: ImportedLicence; situation: EnterpriseSituation }> => + (await client.post('/api/enterprise-upgrade/licence/import', { content })).data, + /** Writes the approved licence on this machine; the machine's situation after it. */ take: async (requestId: string): Promise<{ application: LicenceApplication; situation: EnterpriseSituation }> => (await client.post(`/api/enterprise-upgrade/applications/${encodeURIComponent(requestId)}/take`)).data, diff --git a/webui/src/api/hub.test.ts b/webui/src/api/hub.test.ts index 57a1e5e11..67e9e39b1 100644 --- a/webui/src/api/hub.test.ts +++ b/webui/src/api/hub.test.ts @@ -54,6 +54,22 @@ describe('hubAPI.installStream', () => { .rejects.toThrow('该套件需要授权后才能安装'); }); + it.each([ + // The service's exception handler puts the route's `detail` under `message`; there is no `detail`. + ['a refusal', 403, '该套件需要授权后才能安装', '该套件需要授权后才能安装'], + ['a structured refusal', 409, { code: 'hub_guided_install', message: '该插件通过 Rex 会话安装' }, '该插件通过 Rex 会话安装'], + ])('says why the service rejected an install before streaming: %s', async (_name, status, message, expected) => { + vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ + ok: false, + status, + json: async () => ({ error: 'HTTPException', message }), + })); + + const { hubAPI } = await import('./hub'); + + await expect(hubAPI.installStream('component', 'pro-scene', vi.fn())).rejects.toThrow(expected); + }); + it('falls back to the HTTP status for a non-JSON error response', async () => { vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: false, diff --git a/webui/src/api/hub.ts b/webui/src/api/hub.ts index 43dacefaf..5db0b669e 100644 --- a/webui/src/api/hub.ts +++ b/webui/src/api/hub.ts @@ -1,4 +1,5 @@ import client, { getApiBase } from './client'; +import { extractServerMessage } from '@/utils/error'; export type HubPluginType = 'skill' | 'agent' | 'tool' | 'device' | 'workflow' | 'webui' | 'component'; export type HubPluginState = @@ -233,8 +234,8 @@ export const hubAPI = { }) .then(async (res) => { if (!res.ok || !res.body) { - const payload = await res.json().catch(() => null) as { detail?: unknown } | null; - reject(new Error(typeof payload?.detail === 'string' ? payload.detail : `HTTP ${res.status}`)); + const payload: unknown = await res.json().catch(() => null); + reject(new Error(extractServerMessage({ response: { data: payload } }) ?? `HTTP ${res.status}`)); return; } diff --git a/webui/src/api/provider.ts b/webui/src/api/provider.ts index 4dafe0c70..627d5499d 100644 --- a/webui/src/api/provider.ts +++ b/webui/src/api/provider.ts @@ -1,6 +1,7 @@ import client from './client'; import type { ProviderCredentials, + ProviderConnectionInput, ProviderCredentialInput, ProviderInfoV2, ModelDefinitionV2, @@ -90,7 +91,7 @@ function listApiServicesCached(options: { force?: boolean } = {}) { // ==================== Provider API (Legacy + Enhanced) ==================== export const providerAPI = { - discoverModels: (id: string, credentials: { api_key?: string; base_url?: string } = {}) => + discoverModels: (id: string, credentials: ProviderConnectionInput = {}) => client.post(`/api/provider/${encodeURIComponent(id)}/discover-models`, credentials), importModels: (id: string, models: ModelImportInput[]) => @@ -122,7 +123,7 @@ export const providerAPI = { getModelInventory: (id: string) => client.get<{ models: InventoryModelInput[] }>(`/api/provider/${encodeURIComponent(id)}/model-inventory`), saveModelInventory: (id: string, draft: ModelInventoryDraft) => client.post(`/api/provider/${encodeURIComponent(id)}/model-inventory`, draft), // Authentication checks can make two bounded upstream requests. - checkKey: (id: string, credentials?: { api_key?: string; base_url?: string }) => client.post<{ status: 'valid' | 'invalid' | 'unverified'; code: string }>(`/api/provider/${encodeURIComponent(id)}/check-key`, credentials ?? {}, { timeout: 60_000 }), + checkKey: (id: string, credentials?: ProviderConnectionInput) => client.post<{ status: 'valid' | 'invalid' | 'unverified'; code: string }>(`/api/provider/${encodeURIComponent(id)}/check-key`, credentials ?? {}, { timeout: 60_000 }), // Credentials management (LLM providers — uses _llm_key convention) getCredentials: (id: string) => diff --git a/webui/src/components/common/EntitySheet.test.tsx b/webui/src/components/common/EntitySheet.test.tsx index a8a85b394..421e95153 100644 --- a/webui/src/components/common/EntitySheet.test.tsx +++ b/webui/src/components/common/EntitySheet.test.tsx @@ -54,6 +54,7 @@ const entityTranslations: Record = { 'entity.createTitle': '创建 {{entityType}}', 'entity.editTitle': '编辑 {{entityType}}', 'entity.editTitleWithName': '编辑 {{entityType}}:{{entityName}}', + 'entity.viewTitleWithName': '{{entityType}}详情:{{entityName}}', 'entity.defaultCreate': '创建', 'entity.defaultSave': '保存', 'entity.tabDetails': '详情', @@ -448,6 +449,26 @@ describe('EntitySheet', () => { }); }); + describe('Read-only view', () => { + it('titles the sheet as details and offers no save or cancel, only the close button', async () => { + const user = userEvent.setup(); + const onClose = vi.fn(); + const onSubmit = vi.fn(); + render( + +
Form content
+
, + ); + + expect(screen.getByText('模型详情:DeepSeek-V4.1-Flash-1017')).toBeInTheDocument(); + expect(screen.queryByText('保存')).not.toBeInTheDocument(); + expect(screen.queryByText('取消')).not.toBeInTheDocument(); + await user.click(document.querySelectorAll('button')[0]); + expect(onClose).toHaveBeenCalled(); + expect(onSubmit).not.toHaveBeenCalled(); + }); + }); + describe('Footer actions', () => { it('should show "创建" button in create mode', () => { render( diff --git a/webui/src/components/common/EntitySheet.tsx b/webui/src/components/common/EntitySheet.tsx index ca541df12..3040a92f9 100644 --- a/webui/src/components/common/EntitySheet.tsx +++ b/webui/src/components/common/EntitySheet.tsx @@ -176,6 +176,8 @@ export interface EntitySheetProps { rexComposerTextareaMaxHeight?: number; /** Optional element rendered on the left side of the form-tab footer (e.g. delete button) */ footerLeft?: React.ReactNode; + /** Edit mode the viewer may only look at: "{{entityType}}详情" title, no save/cancel (the header still closes). */ + readOnly?: boolean; } // ─── Main Component ─────────────────────────────────────────────────────────── @@ -224,6 +226,7 @@ export default function EntitySheet({ rexComposerTextareaMinHeight, rexComposerTextareaMaxHeight, footerLeft, + readOnly = false, }: EntitySheetProps) { const { t } = useTranslation('common'); const supportsVision = useDefaultModelVision(); @@ -234,9 +237,13 @@ export default function EntitySheet({ const title = mode === 'create' ? t('entity.createTitle', { entityType }) - : entityName - ? t('entity.editTitleWithName', { entityType, entityName }) - : t('entity.editTitle', { entityType }); + : readOnly + ? entityName + ? t('entity.viewTitleWithName', { entityType, entityName }) + : t('entity.viewTitle', { entityType }) + : entityName + ? t('entity.editTitleWithName', { entityType, entityName }) + : t('entity.editTitle', { entityType }); const defaultSubmitLabel = mode === 'create' ? t('entity.defaultCreate') : t('entity.defaultSave'); const effectiveDefaultTestPrompt = defaultTestPrompt ?? t('entity.defaultTestPrompt', { defaultValue: 'Hello, please introduce yourself.' }); @@ -767,8 +774,8 @@ export default function EntitySheet({ )} - {/* ── Footer ── */} - {(!showTabs || activeTab === 'form') && ( + {/* ── Footer ── (a read-only sheet with nothing on the left has none) */} + {(!showTabs || activeTab === 'form') && !(readOnly && !footerLeft && !(onRunTest && !hideTest)) && (
{/* Left: custom footer element and/or test button */} @@ -785,14 +792,16 @@ export default function EntitySheet({ )}
- + {!readOnly && ( + + )}
)} diff --git a/webui/src/components/common/LogViewerModal.test.tsx b/webui/src/components/common/LogViewerModal.test.tsx index 0ec2347b0..89a5dc76a 100644 --- a/webui/src/components/common/LogViewerModal.test.tsx +++ b/webui/src/components/common/LogViewerModal.test.tsx @@ -1,6 +1,8 @@ import { fireEvent, render, screen } from '@testing-library/react'; import { expect, it, vi } from 'vitest'; import LogViewerModal from './LogViewerModal'; +import { logsAPI } from '@/api/logs'; +import { backendError } from '@/test/helpers'; vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) })); vi.mock('@/api/logs', () => ({ @@ -18,3 +20,10 @@ it('loads the latest log and closes from the backdrop', async () => { fireEvent.click(document.querySelector('div.fixed.inset-0.z-40')!); expect(onClose).toHaveBeenCalledTimes(1); }); + +it('says why the log could not be read instead of the bare status code', async () => { + vi.mocked(logsAPI.readLatest).mockRejectedValueOnce(backendError(403, '只有管理员可以查看系统日志')); + render(); + expect(await screen.findByText('只有管理员可以查看系统日志')).toBeInTheDocument(); + expect(screen.queryByText(/status code 403/)).not.toBeInTheDocument(); +}); diff --git a/webui/src/components/common/LogViewerModal.tsx b/webui/src/components/common/LogViewerModal.tsx index cb6f14ef1..26bcf29cd 100644 --- a/webui/src/components/common/LogViewerModal.tsx +++ b/webui/src/components/common/LogViewerModal.tsx @@ -2,6 +2,7 @@ import { useState, useEffect, useRef, useCallback } from 'react'; import { X, RefreshCw, ChevronDown, FileText } from 'lucide-react'; import { useTranslation } from 'react-i18next'; import { logsAPI, type LogFileInfo, type LogContentResponse } from '@/api/logs'; +import { extractErrorMessage } from '@/utils/error'; interface LogViewerModalProps { open: boolean; @@ -37,7 +38,7 @@ export default function LogViewerModal({ open, onClose }: LogViewerModalProps) { setLogContent(res.data); setSelectedFile(res.data?.filename || null); } catch (err: any) { - setError(err.response?.data?.detail || err.message || 'Failed to load logs'); + setError(extractErrorMessage(err, 'Failed to load logs')); setLogContent(null); } finally { setLoading(false); diff --git a/webui/src/components/common/OnboardingModal.test.tsx b/webui/src/components/common/OnboardingModal.test.tsx index 25d609544..2a480a075 100644 --- a/webui/src/components/common/OnboardingModal.test.tsx +++ b/webui/src/components/common/OnboardingModal.test.tsx @@ -5,6 +5,7 @@ import userEvent from '@testing-library/user-event'; import { MemoryRouter, useLocation } from 'react-router-dom'; import OnboardingModal from './OnboardingModal'; import zhCNCommon from '@/locales/zh-CN/common.json'; +import { backendError } from '@/test/helpers'; const { catalogAPI, @@ -330,6 +331,50 @@ describe('OnboardingModal', () => { })); }); + it('says why the draft could not be saved when the service gives a reason', async () => { + const user = userEvent.setup(); + const onClose = vi.fn(); + onboardingAPI.saveDraft.mockRejectedValueOnce(backendError(403, '只有管理员可以修改引导配置')); + renderOnboarding(onClose); + + await screen.findByRole('button', { name: 'onboarding.bootstrap.savePrimary' }); + await user.selectOptions(screen.getByRole('combobox'), 'openai-compatible'); + await user.type(screen.getByPlaceholderText('onboarding.bootstrap.thirdPartyKeyPlaceholder'), 'some-key'); + await user.click(screen.getByRole('button', { name: 'onboarding.bootstrap.dontShowAgain' })); + + expect(await screen.findByText('只有管理员可以修改引导配置')).toBeInTheDocument(); + expect(screen.queryByText('onboarding.bootstrap.saveError')).not.toBeInTheDocument(); + expect(onClose).not.toHaveBeenCalled(); + }); + + it('keeps its own wording when the service only says that saving the draft failed', async () => { + const user = userEvent.setup(); + onboardingAPI.saveDraft.mockRejectedValueOnce(Object.assign(new Error('Request failed with status code 500'), { + response: { status: 500, data: { error: 'InternalServerError', message: 'Internal server error' } }, + })); + renderOnboarding(); + + const key = await screen.findByPlaceholderText('onboarding.bootstrap.modelKeyPlaceholder'); + await user.type(key, 'pending-model-key'); + await user.click(screen.getByRole('button', { name: 'onboarding.bootstrap.nextStep' })); + + expect(await screen.findByText('onboarding.bootstrap.saveError')).toBeInTheDocument(); + expect(screen.queryByText('Internal server error')).not.toBeInTheDocument(); + }); + + it('says why advancing to the next step could not save the draft', async () => { + const user = userEvent.setup(); + onboardingAPI.saveDraft.mockRejectedValueOnce(backendError(503, '数据库当前只读,暂时不能保存')); + renderOnboarding(); + + const key = await screen.findByPlaceholderText('onboarding.bootstrap.modelKeyPlaceholder'); + await user.type(key, 'pending-model-key'); + await user.click(screen.getByRole('button', { name: 'onboarding.bootstrap.nextStep' })); + + expect(await screen.findByText('数据库当前只读,暂时不能保存')).toBeInTheDocument(); + expect(screen.queryByText('onboarding.bootstrap.intelPageTitle')).not.toBeInTheDocument(); + }); + it('prevents input changes and duplicate actions while the next-step draft save is pending', async () => { const user = userEvent.setup(); const save = deferred<{ data: ReturnType }>(); diff --git a/webui/src/components/common/OnboardingModal.tsx b/webui/src/components/common/OnboardingModal.tsx index f0e572f3f..62386800f 100644 --- a/webui/src/components/common/OnboardingModal.tsx +++ b/webui/src/components/common/OnboardingModal.tsx @@ -26,6 +26,7 @@ import { } from '@/api/onboarding'; import type { CatalogProvider } from '@/types'; import { getDefaultThreatBookRegion, THREATBOOK_REGION_CONFIG } from '@/constants/threatbook'; +import { extractErrorMessage, extractServerMessage } from '@/utils/error'; const MODEL_KEY_LINK = 'https://portal.agentflocks.com'; @@ -751,7 +752,7 @@ export default function OnboardingModal({ onClose }: OnboardingModalProps) { onClose(); if (destination) navigate(destination); } catch (err: any) { - setStartStatus({ tone: 'error', message: err?.response?.data?.detail || t('onboarding.bootstrap.saveError') }); + setStartStatus({ tone: 'error', message: extractServerMessage(err) || t('onboarding.bootstrap.saveError') }); } finally { setDraftSaving(false); } @@ -764,7 +765,7 @@ export default function OnboardingModal({ onClose }: OnboardingModalProps) { if (!showPrimaryConfiguredDetails) await onboardingAPI.saveDraft({ model: buildPrimaryPayload() }); setStep('intel'); } catch (err: any) { - setStartStatus({ tone: 'error', message: err?.response?.data?.detail || t('onboarding.bootstrap.saveError') }); + setStartStatus({ tone: 'error', message: extractServerMessage(err) || t('onboarding.bootstrap.saveError') }); } finally { setDraftSaving(false); } @@ -823,7 +824,7 @@ export default function OnboardingModal({ onClose }: OnboardingModalProps) { } catch (err: any) { setPrimaryStatus({ tone: 'error', - message: err?.response?.data?.detail || err?.message || t('onboarding.bootstrap.revealModelKeyError'), + message: extractErrorMessage(err, t('onboarding.bootstrap.revealModelKeyError')), }); return; } finally { @@ -851,7 +852,7 @@ export default function OnboardingModal({ onClose }: OnboardingModalProps) { } catch (err: any) { setIntelStatus({ tone: 'error', - message: err?.response?.data?.detail || err?.message || t('onboarding.bootstrap.revealIntelKeyError'), + message: extractErrorMessage(err, t('onboarding.bootstrap.revealIntelKeyError')), }); return; } finally { diff --git a/webui/src/components/common/ProBadge.tsx b/webui/src/components/common/ProBadge.tsx new file mode 100644 index 000000000..864ce0f3a --- /dev/null +++ b/webui/src/components/common/ProBadge.tsx @@ -0,0 +1,17 @@ +import { Gem } from 'lucide-react'; + +/** + * The enterprise edition's mark: PRO on gold with a gem, the same in both themes but for the shade of gold. + * The colours are the design's own (its account-pro-badge), not the palette's ambers. + */ +export const PRO_BADGE_CLASS = + 'inline-flex shrink-0 items-center gap-0.5 rounded-md border border-[#d59624] bg-gradient-to-br from-[#fff6d4] via-[#ffe69d] to-[#ffce65] px-1.5 text-[10px] font-bold leading-4 tracking-wide text-[#674000] dark:border-[#ffdb7c] dark:from-[#fff2c5] dark:via-[#ffdf8c] dark:to-[#ffc752] dark:text-[#593300]'; + +export default function ProBadge({ label = 'PRO', className = '' }: { label?: string; className?: string }) { + return ( + + + ); +} diff --git a/webui/src/components/common/SessionChat.tsx b/webui/src/components/common/SessionChat.tsx index 911581a46..ed9a8c7da 100644 --- a/webui/src/components/common/SessionChat.tsx +++ b/webui/src/components/common/SessionChat.tsx @@ -98,6 +98,7 @@ import { } from '@/utils/imageUpload'; import type { Message, MessagePart, SessionGoalState, ToolState } from '@/types'; import type { SessionExecutionMode } from '@/utils/sessionExecutionMode'; +import { extractErrorMessage } from '@/utils/error'; import { buildInstructionDisplayText, fetchSessionChatCommands, @@ -3627,7 +3628,7 @@ export default function SessionChat({ }); }); } catch (err: any) { - const detail = err?.response?.data?.detail ?? err?.message ?? t('chat.upload.errorGeneric'); + const detail = extractErrorMessage(err, t('chat.upload.errorGeneric')); setAttachments((prev) => prev.map((attachment) => ( entries.some((entry) => entry.id === attachment.id) ? { ...attachment, status: 'error', error: detail } @@ -3984,10 +3985,9 @@ export default function SessionChat({ onExecutionModeAccepted?.(promptExecutionMode); } catch (err: any) { const statusCode = err?.response?.status; - const detail = err?.response?.data?.detail; const message = statusCode === 409 ? t('chat.queue.full') - : detail || err?.message || t('chat.queue.enqueueFailed'); + : extractErrorMessage(err, t('chat.queue.enqueueFailed')); toast.error(message); throw err; } @@ -4401,7 +4401,7 @@ export default function SessionChat({ try { await saveQueuedEdit(item); } catch (err: any) { - toast.error(err?.response?.data?.detail || err?.message || t('chat.queue.updateFailed')); + toast.error(extractErrorMessage(err, t('chat.queue.updateFailed'))); } }, [saveQueuedEdit, t, toast]); @@ -4409,7 +4409,7 @@ export default function SessionChat({ try { await removeQueuedPrompt(item); } catch (err: any) { - toast.error(err?.response?.data?.detail || err?.message || t('chat.queue.removeFailed')); + toast.error(extractErrorMessage(err, t('chat.queue.removeFailed'))); } }, [removeQueuedPrompt, t, toast]); @@ -4423,7 +4423,7 @@ export default function SessionChat({ suppressStreamingUntilIdleRef.current = false; setIsStreaming(true); } catch (err: any) { - toast.error(err?.response?.data?.detail || err?.message || t('chat.queue.runNowFailed')); + toast.error(extractErrorMessage(err, t('chat.queue.runNowFailed'))); } }, [runQueuedPromptNow, t, toast]); diff --git a/webui/src/components/common/UpdateModal.test.tsx b/webui/src/components/common/UpdateModal.test.tsx index 9176b352f..9795cd4ae 100644 --- a/webui/src/components/common/UpdateModal.test.tsx +++ b/webui/src/components/common/UpdateModal.test.tsx @@ -1002,6 +1002,47 @@ describe('UpdateModal on a release its own core installs', () => { expect(screen.queryByText('stageLabels.error')).not.toBeInTheDocument(); }); + it('offers to retry a release that did not come up, and asks the source for it only once confirmed', async () => { + const start = vi.fn((onProgress: (progress: unknown) => void) => { + onProgress({ stage: 'restarting', message: '', success: null, progress_token: 'managed:abc' }); // secret-guard: allow (the test's own request id) + return Promise.resolve(); + }); + const outcome = vi.fn().mockResolvedValue({ + id: 'abc', state: 'failed', detail: 'release r2 was rolled back before (x); pass the retry option to try it again', + failed_step: 'start', recovery: 'unchanged', retryable: true, + }); + const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime }); + render(); + await user.click(screen.getByRole('button', { name: 'confirmAction' })); + await vi.advanceTimersByTimeAsync(1_500); + expect(await screen.findByTestId('retry-rolled-back-release')).toBeInTheDocument(); + expect(start).toHaveBeenCalledTimes(1); + expect(start.mock.calls[0][1]).toBeUndefined(); + // One click only asks for the confirmation; cancelling it starts nothing. + await user.click(screen.getByRole('button', { name: 'retryRelease' })); + await user.click(screen.getByRole('button', { name: 'retryReleaseCancel' })); + expect(start).toHaveBeenCalledTimes(1); + await user.click(screen.getByRole('button', { name: 'retryRelease' })); + await user.click(screen.getByRole('button', { name: 'retryReleaseConfirm' })); + expect(start).toHaveBeenCalledTimes(2); + // The retry names the update it was confirmed on, so the source can refuse it once another replaced it. + expect(start.mock.calls[1][1]).toEqual({ retryOf: 'abc' }); + }); + + it('offers no retry for a failure that was not the release coming up', async () => { + const start = vi.fn((onProgress: (progress: unknown) => void) => { + onProgress({ stage: 'restarting', message: '', success: null, progress_token: 'managed:abc' }); // secret-guard: allow (the test's own request id) + return Promise.resolve(); + }); + const outcome = vi.fn().mockResolvedValue({ state: 'failed', detail: 'does not verify', failed_step: 'bundle', recovery: 'unchanged' }); + const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime }); + render(); + await user.click(screen.getByRole('button', { name: 'confirmAction' })); + await vi.advanceTimersByTimeAsync(1_500); + expect(await screen.findByTestId('upgrade-failure')).toBeInTheDocument(); + expect(screen.queryByTestId('retry-rolled-back-release')).not.toBeInTheDocument(); + }); + it('stops at the service refusing the question, which will not change', async () => { const outcome = vi.fn().mockRejectedValue({ response: { status: 401, data: { detail: '请重新登录' } } }); await started(outcome); @@ -1011,6 +1052,27 @@ describe('UpdateModal on a release its own core installs', () => { expect(outcome).toHaveBeenCalledTimes(1); }); + it('keeps asking when a proxy answers 404 for the service while it restarts', async () => { + // nginx's own page, as a gateway set up that way sends it for a service it cannot reach: not this service's JSON. + const proxyPage = '\r\n404 Not Found\r\n\r\n

404 Not Found

\r\n
nginx
\r\n\r\n\r\n'; + const proxyAnswer = { response: { status: 404, data: proxyPage }, message: 'Request failed with status code 404' }; + const outcome = vi.fn() + .mockResolvedValueOnce({ state: 'running' }) + .mockRejectedValueOnce(proxyAnswer) + .mockRejectedValueOnce(proxyAnswer) + .mockResolvedValue({ state: 'done' }); + await started(outcome); + await vi.advanceTimersByTimeAsync(1_500); + for (let asked = 0; asked < 2; asked += 1) { + await vi.advanceTimersByTimeAsync(2_000); + expect(location.reload).not.toHaveBeenCalled(); + } + expect(screen.queryByText('Request failed with status code 404')).not.toBeInTheDocument(); + await vi.advanceTimersByTimeAsync(2_000); + expect(outcome).toHaveBeenCalledTimes(4); + expect(location.reload).toHaveBeenCalledTimes(1); + }); + it('says what stopped it before it was handed over', async () => { const start = vi.fn().mockRejectedValue(new Error('Console 没有这个平台的发布包')); const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime }); diff --git a/webui/src/components/common/UpdateModal.tsx b/webui/src/components/common/UpdateModal.tsx index 90ebde15f..f5a6e3ecc 100644 --- a/webui/src/components/common/UpdateModal.tsx +++ b/webui/src/components/common/UpdateModal.tsx @@ -26,11 +26,12 @@ import { type UpgradeHandoffProgress, } from '@/api/update'; import { checkRestartReadiness } from '@/utils/restartPolling'; +import { formatProductVersion } from '@/utils/productVersion'; import UpgradeHandoffSteps, { useHandoffFailureMessage } from './UpgradeHandoffSteps'; import UpgradeFailureDetails, { failureOfEnterpriseUpgrade, failureOfReleaseUpdate, type UpgradeFailure } from './UpgradeFailureDetails'; import { ENTERPRISE_UPDATE_CHANNEL, UPDATE_DISMISSED_KEY, buildUpdateDismissalKey } from '@/utils/updateDismissal'; import { withReleaseUpdate, type ReleaseUpdateSource } from '@/utils/releaseUpdate'; -import { extractErrorMessage } from '@/utils/error'; +import { extractErrorMessage, isServiceRefusal } from '@/utils/error'; import { ENTERPRISE_UPGRADE_PAGE, EnterpriseUpgradeRefused, enterpriseUpgradeApi, enterpriseVersionInfo, type EnterpriseUpgradeState } from '@/api/enterpriseUpgrade'; // ------------------------------------------------------------------ // @@ -44,10 +45,9 @@ const ENTERPRISE_FAILED_STAGE: Record = { downl export { UPDATE_DISMISSED_KEY }; +// Versions on screen are written one way: v... (utils/productVersion). function formatUpdateVersion(version?: string | null): string { - const raw = (version || '').trim(); - if (!raw) return '—'; - return /^\d/.test(raw) ? `v${raw}` : raw; + return formatProductVersion(version) ?? '—'; } function clampPercent(value?: number | null): number | null { @@ -118,6 +118,10 @@ export default function UpdateModal({ // Where a failed upgrade stopped, when what failed said; `error` is the plain text of the rest. const [failure, setFailure] = useState(null); const [failedStage, setFailedStage] = useState(null); + // A release update that ended with the release not coming up: asked for again as usual it is + // refused, so the administrator may confirm a retry of that update (its outcome id), and is confirming it. + const [retryRequestId, setRetryRequestId] = useState(null); + const [confirmingRetry, setConfirmingRetry] = useState(false); const [installLog, setInstallLog] = useState(null); const lastStageRef = useRef(null); const [restarting, setRestarting] = useState(false); @@ -253,14 +257,15 @@ export default function UpdateModal({ return; } if (outcome.state === 'failed' || outcome.state === 'stalled' || outcome.state === 'unknown') { + setRetryRequestId(outcome.state === 'failed' && outcome.retryable === true && outcome.id ? outcome.id : null); unlock(failureOfReleaseUpdate(outcome, t('upgradeFailed'))); return; } } catch (e: any) { - // Out of reach, or the proxy's answer while the service restarts: keep asking. - // The service's own refusal (signed out, say) will not change. - const code = e?.response?.status; - if (typeof code === 'number' && code >= 400 && code < 500) { + // Out of reach, or a proxy answering for the service while it restarts (a 502 or 503 page + // on most, a 404 on some): keep asking. The service's own refusal (signed out, say) + // comes in its own JSON and will not change. + if (isServiceRefusal(e)) { unlock({ reason: extractErrorMessage(e, t('upgradeFailed')) }); return; } @@ -359,7 +364,7 @@ export default function UpdateModal({ } }; - const handleUpgrade = useCallback(async () => { + const handleUpgrade = useCallback(async (retryOf?: string) => { if (!info?.has_update || !canUpgrade || info.update_allowed === false) return; // The way the shown version came: a background check must not change what this button does. if (info.channel === ENTERPRISE_UPDATE_CHANNEL) { @@ -372,6 +377,8 @@ export default function UpdateModal({ setError(null); setFailure(null); setFailedStage(null); + setRetryRequestId(null); + setConfirmingRetry(false); lastStageRef.current = null; const viaRelease = info.deploy_mode === 'managed' ? releaseUpdate : undefined; @@ -401,7 +408,7 @@ export default function UpdateModal({ } }; if (viaRelease) { - await viaRelease.start(onProgress); + await viaRelease.start(onProgress, retryOf ? { retryOf } : undefined); } else { await applyUpdate(info.latest_version!, onProgress, i18n.language, channel); } @@ -651,6 +658,40 @@ export default function UpdateModal({ )} + {!isBusy && retryRequestId && ( +
+

{t('retryReleaseHint')}

+
+ {confirmingRetry ? ( + <> + + + + ) : ( + + )} +
+
+ )} + {!isBusy && error && ( + + ), + }), + }; + const { container } = render( + + + } /> + , + ); + fireEvent.click(screen.getByRole('button', { name: 'accountAndGlobal' })); + const upgrade = within(screen.getByRole('menu')).getByRole('menuitem', { name: /Upgrade/ }); + expect(upgrade.tagName).toBe('BUTTON'); + expect(upgrade).toHaveAttribute('aria-haspopup', 'dialog'); + fireEvent.click(upgrade); + const opened = await screen.findByRole('dialog', { name: 'quick' }); + // Not inside the sidebar, whose transform would hold a fixed box in it. + expect(container.querySelector('aside')).not.toContainElement(opened); + expect(screen.getByTestId('path')).toHaveTextContent('/sessions'); + expect(screen.queryByRole('menu')).not.toBeInTheDocument(); + fireEvent.click(within(opened).getByRole('button', { name: 'close' })); + await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument()); + expect(onNavigate).toHaveBeenCalledOnce(); + }); + + it('marks the enterprise edition with the gold PRO mark on its Flocks Pro entry, and the open edition with none', () => { + const { unmount } = render( + + + , + ); + // Nothing on the avatar or beside the version: the mark is the entry's. + expect(screen.queryByTestId('pro-badge')).not.toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: 'accountAndGlobal' })); + const menu = screen.getByRole('menu'); + const marks = within(menu).getAllByTestId('pro-badge'); + expect(marks).toHaveLength(1); + expect(marks[0]).toHaveTextContent('PRO'); + expect(marks[0].className).toContain('from-[#fff6d4]'); + expect(marks[0]).not.toHaveClass('bg-red-600'); + expect(within(menu).getByRole('menuitem', { name: /Flocks Pro/ })).toContainElement(marks[0]); + unmount(); + + render( + + + , + ); + fireEvent.click(screen.getByRole('button', { name: 'accountAndGlobal' })); + const open = within(screen.getByRole('menu')); + expect(open.getByRole('menuitem', { name: 'Flocks Pro' })).toBeInTheDocument(); + expect(open.queryByTestId('pro-badge')).not.toBeInTheDocument(); + }); }); + diff --git a/webui/src/components/layout/AccountMenu.tsx b/webui/src/components/layout/AccountMenu.tsx index 803026cc9..19250835b 100644 --- a/webui/src/components/layout/AccountMenu.tsx +++ b/webui/src/components/layout/AccountMenu.tsx @@ -1,6 +1,12 @@ +import { Suspense, lazy, useState, type ComponentType, type LazyExoticComponent } from 'react'; +import { createPortal } from 'react-dom'; import { Link } from 'react-router-dom'; import { useTranslation } from 'react-i18next'; import { ChevronUp, Gauge, LogOut, RefreshCw, Settings, type LucideIcon } from 'lucide-react'; +import LazyLoadErrorBoundary from '@/components/common/LazyLoadErrorBoundary'; +import ProBadge from '@/components/common/ProBadge'; +import { preloadI18nNamespaces } from '@/i18nResources'; +import type { ExtensionDialog } from '@ext/registry'; import HeaderMenu, { MENU_ITEM_CLASS, MENU_SEPARATOR_CLASS } from './HeaderMenu'; export const FLOCKS_LLM_USAGE_URL = 'https://portal.agentflocks.com'; @@ -15,6 +21,24 @@ export interface AccountMenuExtraItem { highlight?: boolean; /** Short tag shown at the end of the row. */ badge?: string; + /** How the tag is drawn: the action colour (default), or the enterprise edition's gold PRO. */ + badgeTone?: 'action' | 'pro'; + /** Opened in a dialog over the page instead of following `href`. */ + dialog?: ExtensionDialog; +} + +const ACTION_BADGE_CLASS = 'shrink-0 rounded bg-ui-action px-1.5 text-[10px] font-semibold leading-4 text-ui-on-action'; + +type DialogComponent = LazyExoticComponent void }>>; +// One lazy component per dialog loader, so reopening a dialog does not load (or remount) it anew. +const dialogComponents = new WeakMap(); +function dialogComponent(dialog: ExtensionDialog): DialogComponent { + let component = dialogComponents.get(dialog); + if (!component) { + component = lazy(() => Promise.all([dialog.load(), preloadI18nNamespaces(dialog.i18nNamespaces ?? [])]).then(([module]) => module)); + dialogComponents.set(dialog, component); + } + return component; } interface AccountMenuProps { @@ -37,7 +61,11 @@ export default function AccountMenu({ version, update, extensionItems = [], onCheckUpdate, onLogout, }: AccountMenuProps) { const { t } = useTranslation('nav'); + // The entry whose dialog is open over the page, if any. + const [dialogItem, setDialogItem] = useState(null); + const Dialog = dialogItem?.dialog ? dialogComponent(dialogItem.dialog) : null; return ( + <> {t('modelUsageHint')} - {extensionItems.map((item) => ( - { close(); onNavigate?.(); }} - className={item.highlight ? `${MENU_ITEM_CLASS} mt-1 border border-ui-border bg-ui-subtle` : MENU_ITEM_CLASS} - > -