rsnarsna
feat(alli-backend): Wave-1 standardization, standalone sys.env node & vault crypto, and DEC-014 security hardening
8628c98 Download lambdas/validate_handler.py from Rsnarsna/auto: direct link, hf CLI and curl.
- Browser
- Download file 10.8 kB
-
https://huggingface.co/spaces/Rsnarsna/auto/resolve/main/lambdas/validate_handler.py
- Command line
-
hf download hf://spaces/Rsnarsna/auto/lambdas/validate_handler.py
-
curl -L -o validate_handler.py https://huggingface.co/spaces/Rsnarsna/auto/resolve/main/lambdas/validate_handler.py
10.8 kB
| """ | |
| ALLI Lambda Function: Language Core Validator (alli-validate) | |
| Facade orchestrating type compatibility, connection checks, graph validation, and Lambda dispatch. | |
| """ | |
| import json | |
| from collections import defaultdict | |
| from typing import Any, Dict, List, Optional | |
| from language_core.node_schema import NodeDefinition, default_registry | |
| from lambdas.validation.connection_validator import validate_connection_logic | |
| from lambdas.validation.graph_checks import validate_graph_cycles, validate_graph_entrypoints | |
| from lambdas.validation.metadata_validator import validate_node_metadata_logic | |
| from lambdas.validation.node_checks import validate_all_nodes | |
| from lambdas.validation.types_and_expr import ( | |
| APPROVED_AGENT_TYPES, | |
| APPROVED_REASONER_TYPES, | |
| is_agent_reasoner_or_memory, | |
| is_approved_agent_node, | |
| is_configured_port_value, | |
| is_loop_header_node, | |
| is_valid_node_id, | |
| validate_expression_logic, | |
| validate_types_logic, | |
| ) | |
| STD_LIBS = { | |
| "math", "json", "sys", "os", "re", "time", "datetime", "random", | |
| "collections", "itertools", "functools", "urllib", "typing", "string", | |
| "copy", "hashlib", "base64", "io", "pathlib", "subprocess", "logging", | |
| "shutil", "csv", "tempfile", "traceback", "struct", "unicodedata", | |
| "core", "operator", | |
| } | |
| def validate_workflow_protocol_logic( | |
| graph: Dict[str, Any], | |
| execution_exit_code: Optional[int] = None, | |
| ) -> Dict[str, Any]: | |
| """Phase 3.9: Complete 10-Possibility Workflow Validation Engine.""" | |
| from language_core.workflow_migration import migrate_workflow | |
| if graph and isinstance(graph, dict): | |
| try: | |
| graph = migrate_workflow(graph) | |
| except Exception: | |
| pass | |
| raw_nodes = graph.get("nodes", []) | |
| raw_edges = graph.get("edges") if graph.get("edges") is not None else (graph.get("connections") or []) | |
| nodes = [ | |
| n for n in raw_nodes | |
| if str(n.get("node_type") or n.get("type") or n.get("data", {}).get("node_type") or "") | |
| not in ("system.workflow_group", "workflow_group", "workflowGroup") | |
| ] | |
| edges = [ | |
| e for e in raw_edges | |
| if not str(e.get("source", "")).startswith("group_") and not str(e.get("target", "")).startswith("group_") | |
| ] | |
| diagnostics: List[Dict[str, Any]] = [] | |
| possibility_map = { | |
| "Start Validation": {"errors": 0, "warnings": 0, "summary": "Valid starter trigger"}, | |
| "Node Validation": {"errors": 0, "warnings": 0, "summary": "Node parameters checked"}, | |
| "Connection Validation": {"errors": 0, "warnings": 0, "summary": "Ports & topology verified"}, | |
| "Control Flow": {"errors": 0, "warnings": 0, "summary": "Branch paths verified"}, | |
| "Loop Validation": {"errors": 0, "warnings": 0, "summary": "Iteration & exit behavior checked"}, | |
| "Data Validation": {"errors": 0, "warnings": 0, "summary": "Incoming data schema checked"}, | |
| "Expression Validation": {"errors": 0, "warnings": 0, "summary": "AST expressions validated"}, | |
| "Credential Validation": {"errors": 0, "warnings": 0, "summary": "Security and credentials verified"}, | |
| "Dependency Validation": {"errors": 0, "warnings": 0, "summary": "Libraries & imports checked"}, | |
| "Error Handling": {"errors": 0, "warnings": 0, "summary": "Failure handlers reviewed"}, | |
| "Execution Validation": {"errors": 0, "warnings": 0, "summary": "Execution readiness checked"}, | |
| } | |
| def add_diag( | |
| severity: str, | |
| category: str, | |
| code: str, | |
| msg: str, | |
| rule: int, | |
| node_id: Optional[str] = None, | |
| port_id: Optional[str] = None, | |
| edge_id: Optional[str] = None, | |
| fix: Optional[str] = None, | |
| ) -> None: | |
| diagnostics.append({ | |
| "code": code, | |
| "severity": severity, | |
| "category": category, | |
| "rule_number": rule, | |
| "message": msg, | |
| "node_id": node_id, | |
| "port_id": port_id, | |
| "edge_id": edge_id, | |
| "fix_suggestion": fix, | |
| }) | |
| if category in possibility_map: | |
| if severity == "error": | |
| possibility_map[category]["errors"] += 1 | |
| elif severity == "warning": | |
| possibility_map[category]["warnings"] += 1 | |
| if not nodes: | |
| add_diag("warning", "Start Validation", "VAL-001", "Canvas is empty. Add nodes to build a workflow.", 1, fix="Insert nodes via the library palette or context menu.") | |
| return {"valid": False, "status": "Warning", "can_execute": False, "error_count": 0, "warning_count": 1, "diagnostics": diagnostics, "possibilities": possibility_map} | |
| id_counts: Dict[str, int] = defaultdict(int) | |
| node_map: Dict[str, Dict[str, Any]] = {} | |
| for n in nodes: | |
| raw_id = n.get("id") | |
| lbl = str(n.get("data", {}).get("label") or n.get("node_type") or "Node") | |
| is_valid_id, err_code = is_valid_node_id(raw_id) | |
| if not is_valid_id: | |
| if err_code == "VAL-NODE-ID-EMPTY": | |
| add_diag("error", "Node Validation", "VAL-NODE-ID-EMPTY", f"Empty Node ID: Node '{lbl}' has a missing, null, or empty identifier. Every node must have a non-empty string ID.", 2, node_id="", fix="Assign a unique, non-empty identifier to each node in the workflow.") | |
| else: | |
| id_disp = str(raw_id) if raw_id is not None else "" | |
| add_diag("error", "Node Validation", "VAL-NODE-ID-MALFORMED", f"Malformed Node ID: Identifier '{id_disp}' on node '{lbl}' contains invalid characters, whitespace, or exceeds 128 characters. Allowed characters: alphanumeric, '_', '-', '.', ':', '#', '@', '/'.", 2, node_id=id_disp, fix="Use a valid alphanumeric identifier without whitespace, quotes, newlines, or illegal characters.") | |
| continue | |
| id_str = str(raw_id) | |
| id_counts[id_str] += 1 | |
| node_map.setdefault(id_str, n) | |
| for nid, count in id_counts.items(): | |
| if count > 1: | |
| add_diag("error", "Node Validation", "VAL-DUPLICATE-NODE-ID", f"Duplicate Node ID: Multiple nodes ({count}) share the identifier '{nid}'. Each node in the workflow must have a unique ID.", 2, node_id=nid, fix="Assign unique IDs to each node in the workflow.") | |
| incoming_map: Dict[str, List[Dict[str, Any]]] = {nid: [] for nid in node_map} | |
| outgoing_map: Dict[str, List[Dict[str, Any]]] = {nid: [] for nid in node_map} | |
| for edge in edges: | |
| src = edge.get("source") or edge.get("from_node") | |
| tgt = edge.get("target") or edge.get("to_node") | |
| src_port = edge.get("sourceHandle") or edge.get("from_port") or edge.get("source_handle") or "out" | |
| tgt_port = edge.get("targetHandle") or edge.get("to_port") or edge.get("target_handle") or "input" | |
| if src not in node_map: | |
| add_diag("error", "Connection Validation", "VAL-003", f"Broken Connection: Edge connects from nonexistent source node '{src}'.", 3, port_id=src_port, fix="Delete the broken connection wire.") | |
| continue | |
| if tgt not in node_map: | |
| add_diag("error", "Connection Validation", "VAL-004", f"Broken Connection: Edge connects to nonexistent target node '{tgt}'.", 3, port_id=tgt_port, fix="Delete the broken connection wire.") | |
| continue | |
| outgoing_map[src].append(edge) | |
| incoming_map[tgt].append(edge) | |
| conn_res = validate_connection_logic(edge, nodes_map=node_map, edges=edges, skip_cycle_check=True) | |
| edge_id = edge.get("id") | |
| if not conn_res.get("valid", True): | |
| add_diag("error", "Connection Validation", conn_res.get("code", "VAL-007"), conn_res.get("message", "Port connection validation failed."), 3, node_id=tgt, port_id=tgt_port, edge_id=edge_id, fix="Ensure compatible port types, avoid duplicate connections, and connect output to input.") | |
| elif conn_res.get("warning"): | |
| add_diag("warning", "Connection Typing", "WARN-CONV", conn_res["warning"], 1, node_id=tgt, port_id=tgt_port, edge_id=edge_id, fix="Verify runtime types match expected contract.") | |
| validate_graph_cycles(nodes, edges, node_map, add_diag) | |
| validate_graph_entrypoints(nodes, node_map, incoming_map, outgoing_map, add_diag) | |
| graph_deps = {str(d).lower() for d in (graph.get("dependencies") or [])} | |
| req_txt = graph.get("compiled_artifacts", {}).get("requirements_txt", "") | |
| for rline in req_txt.splitlines(): | |
| pkg_cleaned = rline.strip().split("==")[0].split(">=")[0].split("<=")[0].strip().lower() | |
| if pkg_cleaned: | |
| graph_deps.add(pkg_cleaned) | |
| validate_all_nodes(nodes, incoming_map, graph_deps, STD_LIBS, add_diag) | |
| if execution_exit_code is not None: | |
| if execution_exit_code == 0: | |
| possibility_map["Execution Validation"]["summary"] = "Sandbox execution passed (Exit 0)." | |
| else: | |
| add_diag("error", "Execution Validation", "EXEC-E001", f"Execution failed with Exit Code {execution_exit_code}.", 8) | |
| errors = sum(p["errors"] for p in possibility_map.values()) | |
| warnings = sum(p["warnings"] for p in possibility_map.values()) | |
| status = "Runtime Error" if (execution_exit_code is not None and execution_exit_code != 0) else ("Error" if errors > 0 else ("Warning" if warnings > 0 else "Valid")) | |
| return {"valid": errors == 0, "status": status, "can_execute": errors == 0, "error_count": errors, "warning_count": warnings, "diagnostics": diagnostics, "possibilities": possibility_map} | |
| def handler(event: Dict[str, Any], context: Any = None) -> Dict[str, Any]: | |
| """Standalone AWS Lambda handler entrypoint for alli-validate function.""" | |
| try: | |
| body_raw = event.get("body", "{}") | |
| body = json.loads(body_raw) if isinstance(body_raw, str) else body_raw | |
| if "graph" in body or "graph_spec" in body: | |
| res = validate_workflow_protocol_logic(body.get("graph") or body.get("graph_spec"), execution_exit_code=body.get("execution_exit_code")) | |
| elif "expression" in body: | |
| res = validate_expression_logic(body["expression"]) | |
| elif "node_metadata" in body or "node_definition" in body: | |
| res = validate_node_metadata_logic(body.get("node_metadata") or body.get("node_definition")) | |
| elif "connection" in body: | |
| res = validate_connection_logic(body["connection"], nodes_map=body.get("nodes_map")) | |
| else: | |
| res = validate_types_logic(body.get("source_type", "Any"), body.get("target_type", "Any")) | |
| return {"statusCode": 200, "headers": {"Content-Type": "application/json", "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "POST, OPTIONS"}, "body": json.dumps(res)} | |
| except Exception as err: | |
| return {"statusCode": 500, "headers": {"Content-Type": "application/json", "Access-Control-Allow-Origin": "*"}, "body": json.dumps({"error": str(err)})} | |