编辑代码
数据管理
字段字典
代码管理
服务发布
编辑:validators.py
/home/ubuntu/app/dashboard/validators.py
"""输入校验与 API 安全加固。 原实现把前端传来的字段直接落库/使用,缺三道校验: 1. alert_rules.operator 未校验 → 传"contains"之类非法值时预警规则静默失效, 用户以为配好了却永不触发(比报错更糟) 2. CORS(app) 全开放 → 任何网站都能跨域调你的 API并读到数据 3. SSE / 列表接口无数据量上限 → 大数据集会让内存爆掉 本模块提供集中校验,app.py 在入口处调用。 """ import re from typing import Any, Dict, List, Optional # ---------- 通用 ---------- # 数据集 / 门店等 ID:统一前缀 + 安全字符 ID_RE = re.compile(r"^[A-Za-z0-9_\-]{1,64}$") # 平台名白名单 PLATFORMS = {"wps", "kdocs", "dingtalk", "feishu"} # 聚合算子白名单(与 field_engine.aggregate 保持一致) AGG_OPS = {"none", "first", "sum", "avg", "count", "max", "min"} # 字段引用类型 REF_TYPES = {"cell", "row", "column", "range"} # 预警比较算子(与 evaluate_alerts 的实现分支严格对应) ALERT_OPS = {">", "<", "=", ">=", "<=", "!="} class ValidationError(ValueError): """校验失败,app.py 应转成 400 返回。""" def _fail(msg: str): raise ValidationError(msg) def check_id(value: Any, field: str) -> str: if not isinstance(value, str) or not ID_RE.match(value): _fail(f"{field} 非法:只允许字母数字下划线和短横线,长度 1-64") return value def check_platform(value: Any) -> str: v = str(value or "").lower() if v not in PLATFORMS: _fail(f"platform 仅支持 {'/'.join(sorted(PLATFORMS))}") return v def check_json_array(value: Any, field: str, max_len: int = 2000) -> List: """确保是可解析的 JSON 数组,并限制长度。""" if value is None: return [] if isinstance(value, str): import json try: value = json.loads(value) except Exception: _fail(f"{field} 不是合法 JSON") if not isinstance(value, list): _fail(f"{field} 必须是数组") if len(value) > max_len: _fail(f"{field} 过长({len(value)} > {max_len})") return value def check_agg(value: Any) -> str: v = str(value or "sum") if v not in AGG_OPS: _fail(f"聚合方式非法:{v},仅支持 {'/'.join(sorted(AGG_OPS))}") return v def check_field_ref(ref: Any) -> Dict: """校验卡片字段引用结构。""" if not isinstance(ref, dict): _fail("field_ref 必须是对象") t = ref.get("type") if t not in REF_TYPES: _fail(f"field_ref.type 仅支持 {'/'.join(sorted(REF_TYPES))}") if t == "cell": if not re.match(r"^[A-Za-z]+\d+$", str(ref.get("ref", ""))): _fail("cell 类型需提供 ref,如 B2") elif t == "range": if not re.match(r"^[A-Za-z]+\d+:[A-Za-z]+\d+$", str(ref.get("ref", ""))): _fail("range 类型需提供 ref,如 B2:D10") elif t == "row": if not isinstance(ref.get("row"), int) or ref["row"] < 1: _fail("row 类型需提供正整数 row(从 1 开始)") elif t == "column": if not re.match(r"^[A-Za-z]+$", str(ref.get("column", ""))): _fail("column 类型需提供列字母,如 C") flt = ref.get("filter") if flt is not None: if not isinstance(flt, dict): _fail("filter 必须是对象") if flt.get("op", "=") not in {"=", "!="}: _fail("filter.op 仅支持 = 或 !=") if not re.match(r"^[A-Za-z]+$", str(flt.get("column", ""))): _fail("filter.column 需为列字母") return ref def check_alert_rule(data: Dict) -> Dict: """校验预警规则。非法 operator 必须报错而不是静默失效。""" if not isinstance(data, dict): _fail("请求体必须是 JSON 对象") for f in ("type_id", "dataset_id", "column_name", "operator", "threshold"): if not data.get(f) and data.get(f) != 0: _fail(f"缺少必填字段:{f}") check_id(data["type_id"], "type_id") check_id(data["dataset_id"], "dataset_id") op = str(data["operator"]) if op not in ALERT_OPS: _fail(f"比较方式非法:{op},仅支持 {' '.join(sorted(ALERT_OPS))}") # threshold 必须能转成数字,否则预警永不触发 try: float(str(data["threshold"]).replace(",", "").replace("%", "")) except Exception: _fail("阈值必须是数字") return data def check_binding(binding: Any) -> Dict: """校验仪表盘卡片的字段绑定。""" if not isinstance(binding, dict): _fail("binding 必须是对象") check_field_ref(binding.get("field_ref")) check_agg(binding.get("aggregation", "sum")) cmp_ = binding.get("compare") if cmp_ is not None: if not isinstance(cmp_, dict): _fail("compare 必须是对象") if cmp_.get("type") not in (None, "period_over_period"): _fail("compare.type 目前仅支持 period_over_period") pr = cmp_.get("period_rows", 1) if not isinstance(pr, int) or pr < 1: _fail("compare.period_rows 需为正整数") return binding def check_columns(value: Any, max_cols: int = 200) -> List[str]: """校验表头:数量上限 + 全转字符串(避免 None/数字混排)。""" cols = check_json_array(value, "columns", max_cols) return ["" if c is None else str(c) for c in cols] def check_rows(value: Any, max_rows: int = 100000, ncols: int = 200) -> List[List]: """校验数据行:行数上限 + 列数对齐 + 补齐缺失列。""" rows = check_json_array(value, "rows", max_rows) out = [] for r in rows: if not isinstance(r, list): _fail("rows 每行必须是数组") if len(r) > ncols: _fail(f"单行列数超过 {ncols}") out.append(list(r)) return out # ---------- CORS 白名单 ---------- def make_cors(app, allowed_origins: Optional[List[str]] = None): """按环境变量生成 CORS 配置。 默认只允许同源(空列表 = 不跨域)。设置 DASHBOARD_ALLOWED_ORIGINS 为逗号分隔的白名单后才放开——而不是像 CORS(app) 那样全开。 """ import os from flask_cors import CORS env = os.environ.get("DASHBOARD_ALLOWED_ORIGINS", "").strip() if env: origins = [x.strip() for x in env.split(",") if x.strip()] CORS(app, resources={r"/api/*": {"origins": origins}}) print(f"[安全] CORS 白名单:{origins}") else: # 不启用跨域;同源访问不受CORS 限制 print("[安全] CORS 未配置白名单,默认禁止跨域(如需放开请设 DASHBOARD_ALLOWED_ORIGINS)") if __name__ == "__main__": # 用可变容器计数:模块级作用域不能用 nonlocal counters = {"ok": 0, "bad": 0} def t(name, fn, should_pass=True): try: fn() if should_pass: counters["ok"] += 1 print(f" ✓ {name}") else: counters["bad"] += 1 print(f" ✗ {name}(应被拒绝却通过了)") except ValidationError as e: if should_pass: counters["bad"] += 1 print(f" ✗ {name}(被误拒: {e})") else: counters["ok"] += 1 print(f" ✓ {name} → 已拒绝") print("[校验自测]") t("合法 id", lambda: check_id("ds_123", "id")) t("注入 id", lambda: check_id("ds'; DROP TABLE", "id"), False) t("空 id", lambda: check_id("", "id"), False) t("合法平台", lambda: check_platform("dingtalk")) t("非法平台", lambda: check_platform("mysql"), False) t("合法聚合", lambda: check_agg("sum")) t("非法聚合", lambda: check_agg("exec"), False) t("cell 引用", lambda: check_field_ref({"type": "cell", "ref": "B2"})) t("坏 cell 引用", lambda: check_field_ref({"type": "cell", "ref": "B"}), False) t("range 引用", lambda: check_field_ref({"type": "range", "ref": "B2:D10"})) t("未知 ref 类型", lambda: check_field_ref({"type": "hack"}), False) t("列过滤", lambda: check_field_ref( {"type": "column", "column": "C", "filter": {"column": "A", "op": "=", "value": "x"}})) t("非法 filter op", lambda: check_field_ref( {"type": "column", "column": "C", "filter": {"column": "A", "op": ">", "value": "1"}}), False) good_rule = {"type_id": "t1", "dataset_id": "d1", "column_name": "库存", "operator": ">", "threshold": "10"} t("合法预警规则", lambda: check_alert_rule(good_rule)) t("非法 operator", lambda: check_alert_rule({**good_rule, "operator": "contains"}), False) t("非数字阈值", lambda: check_alert_rule({**good_rule, "threshold": "abc"}), False) t("缺字段", lambda: check_alert_rule({**good_rule, "column_name": ""}), False) t("卡片绑定", lambda: check_binding({ "field_ref": {"type": "column", "column": "B"}, "aggregation": "avg"})) t("绑定缺 field_ref", lambda: check_binding({"aggregation": "sum"}), False) t("表头校验", lambda: check_columns(["a", None, 3])) t("行校验", lambda: check_rows([[1, 2], [3]])) t("行超上限", lambda: check_rows([[1]] * 100001, max_rows=1000), False) print(f"\n结果:{counters['ok']} 通过 / {counters['bad']} 失败") raise SystemExit(1 if counters["bad"] else 0)
保存到服务器
取消