unis-oa/backend/app/engine/expressions.py

368 lines
11 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

"""Sandboxed expression / script evaluation used by the flow engine.
Route conditions and ``taskScript`` / ``script`` activities are authored by
process designers, so they run through an AST allow-list instead of a raw
``eval``: no imports, no attribute access to private members, no comprehensions
over arbitrary callables beyond the helper functions exposed below.
"""
from __future__ import annotations
import ast
import re
from datetime import date, datetime
_ALLOWED_NODES: tuple[type[ast.AST], ...] = (
ast.Match if hasattr(ast, "Match") else ast.AST,
ast.Expression,
ast.Module,
ast.Expr,
ast.Assign,
ast.AugAssign,
ast.AnnAssign,
ast.If,
ast.For,
ast.While,
ast.Break,
ast.Continue,
ast.Return,
ast.Pass,
ast.Name,
ast.Load,
ast.Store,
ast.Constant,
ast.Tuple,
ast.List,
ast.Dict,
ast.Set,
ast.Starred,
ast.BinOp,
ast.UnaryOp,
ast.BoolOp,
ast.Compare,
ast.IfExp,
ast.Call,
ast.keyword,
ast.Attribute,
ast.Subscript,
ast.Slice,
ast.comprehension,
ast.ListComp,
ast.SetComp,
ast.DictComp,
ast.GeneratorExp,
ast.JoinedStr,
ast.FormattedValue,
ast.Add,
ast.Sub,
ast.Mult,
ast.Div,
ast.FloorDiv,
ast.Mod,
ast.Pow,
ast.MatMult,
ast.USub,
ast.UAdd,
ast.Not,
ast.And,
ast.Or,
ast.In,
ast.NotIn,
ast.Is,
ast.IsNot,
ast.Eq,
ast.NotEq,
ast.Lt,
ast.LtE,
ast.Gt,
ast.GtE,
)
_BLOCKED_ATTRS = {
"__class__",
"__bases__",
"__subclasses__",
"__globals__",
"__code__",
"__closure__",
"__dict__",
"__mro__",
"__getattr__",
"__getattribute__",
"__reduce__",
"__reduce_ex__",
"__builtins__",
"__import__",
}
def _money_cn(value: object) -> str:
"""金额转中文大写;延迟导入避开 service 与 engine 之间的循环引用。"""
from ..service.formruntime import chinese_upper
return chinese_upper(value)
def _cell_texts(value: object) -> set[str]:
"""单元格翻成一组可比文本:多选列存的是数组,其余按一个标量算。"""
if value is None:
return set()
if isinstance(value, (list, tuple, set)):
return {str(item).strip() for item in value if str(item or "").strip() != ""}
text = str(value).strip()
return {text} if text else set()
def _total(value: object, key: object = "", where_key: object = None, where_value: object = None) -> float:
"""明细列求和;带上条件列就只算对得上的那些行。
``total(明细, 值列)`` 是整列求和,``total(明细, 值列, 条件列, 条件值)`` 只合计
条件成立的行,条件值写逗号串(``"travel,it"``)就是「属于这几个」。设计器按
这个口径拼公式,界面上填的明细也是同一份数据,两边算出来必须一样,所以非数字
的格子跟前端一样跳过,而不是让整条公式报错。
"""
column = str(key or "")
gate = str(where_key or "").strip()
wanted: set[str] | None = None
if gate:
wanted = None if where_value is None else {item for chunk in _cell_texts(where_value) for item in chunk.split(",")}
wanted = {item.strip() for item in wanted if item.strip() != ""}
amount = 0.0
for row in value or []:
if not isinstance(row, dict):
continue
if wanted and not (_cell_texts(row.get(gate)) & wanted):
continue
raw = str(row.get(column) or "").strip()
if raw == "":
continue
try:
amount += float(raw)
except ValueError:
continue
return round(amount, 2)
def _count(value: object, key: object = None, expected: object = None) -> int:
"""明细行数;带判断列就只数填了的行,再带取值就只数对得上的行。
取值的口径跟 ``total`` 的条件值一致:写逗号串(``"travel,it"``)就是「属于这几个」,
多选列的格子里只要有一个值对上就算。设计器里条件值可以挑好几个,拼出来的就是这种逗号串,
两边算不到一块去的话,界面挑完数就是错的。
"""
rows = [row for row in (value or []) if isinstance(row, dict)]
column = str(key or "").strip()
if not column:
return len(rows)
if expected is None:
return sum(1 for row in rows if _cell_texts(row.get(column)))
wanted = {item.strip() for chunk in _cell_texts(expected) for item in chunk.split(",") if item.strip()}
if not wanted:
return len(rows)
return sum(1 for row in rows if _cell_texts(row.get(column)) & wanted)
_SAFE_FUNCTIONS = {
"len": len,
"int": int,
"float": float,
"str": str,
"bool": bool,
"abs": abs,
"min": min,
"max": max,
"sum": sum,
"round": round,
"sorted": sorted,
"reversed": reversed,
"enumerate": enumerate,
"zip": zip,
"any": any,
"all": all,
"map": map,
"filter": filter,
"list": list,
"dict": dict,
"set": set,
"tuple": tuple,
"range": range,
"isinstance": isinstance,
"contains": lambda needle, haystack: any(n in haystack for n in ([needle] if not isinstance(needle, (list, tuple, set)) else needle)),
"startswith": lambda value, prefix: str(value).startswith(str(prefix)),
"endswith": lambda value, suffix: str(value).endswith(str(suffix)),
"upper": lambda value: str(value).upper(),
"lower": lambda value: str(value).lower(),
"today": date.today,
"now": datetime.now,
"days_between": lambda a, b: abs((datetime.fromisoformat(str(b)) - datetime.fromisoformat(str(a))).days)
if isinstance(a, str) and isinstance(b, str)
else abs((b - a).days),
"get": lambda obj, key, default=None: (obj or {}).get(key, default) if isinstance(obj, dict) else default,
# 明细表常用统计:total(明细字段, 列名) 求和、rows(明细字段) 拿行、
# count(明细字段, 列名, 值) 数行数;条件分支里不用手写生成器。
# 值写逗号串就是「属于这几个」,跟 total 的条件值同一个口径。
"rows": lambda value: [item for item in (value or []) if isinstance(item, dict)],
"total": _total,
"count": _count,
"money_cn": _money_cn,
}
class ExpressionError(ValueError):
"""Raised when a designer authored script is invalid or unsafe."""
def _validate(source: str) -> ast.AST:
try:
tree = ast.parse(source, mode="eval")
except SyntaxError:
try:
tree = ast.parse(source, mode="exec")
except SyntaxError as exc: # pragma: no cover - surfaced to designer
raise ExpressionError(f"脚本语法错误: {exc.msg}") from exc
for node in ast.walk(tree):
if not isinstance(node, _ALLOWED_NODES):
raise ExpressionError(f"脚本包含不允许的语法: {type(node).__name__}")
if isinstance(node, ast.Attribute) and node.attr in _BLOCKED_ATTRS:
raise ExpressionError(f"脚本禁止访问属性: {node.attr}")
if isinstance(node, ast.Global):
raise ExpressionError("脚本禁止使用 global")
_validate_names(tree)
return tree
def _namespace(context: dict) -> dict:
data = context.get("data") if isinstance(context.get("data"), dict) else {}
namespace = dict(_SAFE_FUNCTIONS)
namespace.update(
{
"data": data,
"form": data,
"work": context.get("work") or {},
"user": context.get("user") or {},
"context": context,
"true": True,
"false": False,
"null": None,
}
)
# Convenience: expose top level form fields as bare names (amount > 5000).
for key, value in data.items():
if isinstance(key, str) and key.isidentifier() and key not in namespace:
namespace[key] = value
return namespace
def evaluate(source: str, context: dict) -> object:
"""Evaluate an expression string, returning whatever it computes."""
source = (source or "").strip()
if not source:
return True
tree = _validate(source)
namespace = _namespace(context)
try:
if isinstance(tree, ast.Expression):
return eval(compile(tree, "<oa-expression>", "eval"), {"__builtins__": {}}, namespace) # noqa: S307
exec(compile(ast.Module(body=tree.body, type_ignores=[]), "<oa-script>", "exec"), {"__builtins__": {}}, namespace) # noqa: S102
return namespace.get("result", True)
except ExpressionError:
raise
except Exception as exc: # pragma: no cover - designer error surface
raise ExpressionError(f"脚本执行失败: {exc}") from exc
def evaluate_condition(source: str, context: dict) -> bool:
"""Route guard: empty condition always passes, everything else coerces."""
try:
return bool(evaluate(source, context))
except ExpressionError:
return False
_BLOCKED_NAMES = {
"__import__",
"eval",
"exec",
"compile",
"open",
"globals",
"locals",
"vars",
"dir",
"getattr",
"setattr",
"delattr",
"hasattr",
"input",
"print",
"breakpoint",
"exit",
"quit",
"help",
"memoryview",
"object",
"type",
"super",
"license",
"copyright",
}
def _validate_names(tree: ast.AST) -> None:
for node in ast.walk(tree):
if isinstance(node, ast.Name) and node.id in _BLOCKED_NAMES:
raise ExpressionError(f"脚本禁止使用: {node.id}")
if isinstance(node, ast.Attribute) and node.attr.startswith("__") and node.attr.endswith("__"):
raise ExpressionError(f"脚本禁止访问属性: {node.attr}")
_SCRIPT_ASSIGN_RE = re.compile(r"^\s*(?!\d)\w+\s*=", re.MULTILINE)
def run_identity_script(script: str, context: dict) -> list[str]:
"""Run a ``taskScript`` and normalise its output to a list of identities.
Designers write either real python (``result = [...]``) or a plain list of
distinguished names separated by newlines / commas, so evaluation failures
fall back to a literal split instead of silently dropping approvers.
"""
script = (script or "").strip()
if not script:
return []
raw: object
try:
if _SCRIPT_ASSIGN_RE.search(script) or "\n" in script:
raw = evaluate(script, context)
else:
raw = evaluate(script if script.startswith(("[", "{")) else f"[{script}]", context)
except ExpressionError:
raw = [token for token in re.split(r"[\n,;]+", script) if token.strip()]
if raw is None:
return []
if isinstance(raw, (list, tuple, set)):
return [str(item).strip() for item in raw if str(item).strip()]
if isinstance(raw, dict):
return [str(raw.get("identity") or raw.get("distinguishedName") or "").strip()]
return [str(raw).strip()]
def run_script(script: str, context: dict) -> dict:
"""Run an activity script, returning the (possibly updated) ``data`` dict."""
script = (script or "").strip()
if not script:
return context.get("data") or {}
evaluate(script, context)
data = context.get("data")
return data if isinstance(data, dict) else {}
def validate_script(script: str) -> str | None:
"""Return an error message when the script cannot be compiled."""
script = (script or "").strip()
if not script:
return None
try:
_validate(script)
except ExpressionError as exc:
return str(exc)
return None